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.
@@ -0,0 +1,5 @@
1
+ # dsh-token-dash bundle:底栏 Token 看板 + 设置页。
2
+ - insert:
3
+ - id: dsh-token-dash
4
+ name: 'dsh-token-dash'
5
+ config: {}
Binary file
Binary file
Binary file
Binary file
package/index.js ADDED
@@ -0,0 +1,342 @@
1
+ /**
2
+ * dsh-token-dash — host half: collect, aggregate, pricing, adapters and routes.
3
+ */
4
+ import { readFileSync } from 'node:fs'
5
+ import { existsSync } from 'node:fs'
6
+ import { spawn } from 'node:child_process'
7
+ import { dirname, join } from 'node:path'
8
+ import { buildSummary, emptyState, num } from './src/core.js'
9
+ import { ingest, backfill } from './src/collect.js'
10
+ import { createFlusher, dataDir, loadPrefs, loadState, logsDir, saveJson } from './src/store.js'
11
+ import { logAdapterEvents, readProviders, readSubscriptions } from './src/adapters.js'
12
+ import { catalogInfo, loadCommunityPricing, loadRouterPricing } from './src/pricing.js'
13
+ import { clearLog, createLogger, exportLog } from './src/diagnostics.js'
14
+
15
+ export const name = 'dsh-token-dash'
16
+
17
+ const ROUTE_PREFIX = '/token-dash/api'
18
+ const CURRENT_VERSION = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version
19
+ const PROVIDER_TTL = 30000
20
+ let updateCache = { at: 0, data: null }
21
+
22
+ function versionParts(value) {
23
+ return String(value).split('.').map((part) => Number.parseInt(part, 10) || 0)
24
+ }
25
+
26
+ function isNewer(latest, current) {
27
+ const left = versionParts(latest)
28
+ const right = versionParts(current)
29
+ for (let index = 0; index < Math.max(left.length, right.length); index += 1) {
30
+ const diff = (left[index] ?? 0) - (right[index] ?? 0)
31
+ if (diff !== 0) return diff > 0
32
+ }
33
+ return false
34
+ }
35
+
36
+ /** Locate the bundled dsh CLI (same layout scripts/e2e.mjs relies on). */
37
+ function findDshCli() {
38
+ const fromEnv = process.env.DSH_CLI
39
+ if (typeof fromEnv === 'string' && fromEnv !== '' && existsSync(fromEnv)) return fromEnv
40
+ try {
41
+ const bundled = join(dirname(process.execPath), 'resources', 'app.asar', 'dsh', 'node_modules', '@deepseek-ai', 'dsh-desktop-host', 'lib', 'cli.js')
42
+ if (existsSync(bundled)) return bundled
43
+ } catch {
44
+ // ignore
45
+ }
46
+ return null
47
+ }
48
+
49
+ /** Run `dsh plugin --profile <p> update dsh-token-dash`; resolves with { ok, reason?, command, output }. */
50
+ function runPluginUpdate(profile) {
51
+ return new Promise((resolve) => {
52
+ const command = `dsh plugin --profile ${profile} update dsh-token-dash`
53
+ const cli = findDshCli()
54
+ if (cli === null) {
55
+ resolve({ ok: false, reason: 'cli-not-found', command, output: '' })
56
+ return
57
+ }
58
+ const child = spawn(process.execPath, ['--expose-internals', cli, 'plugin', '--profile', profile, 'update', 'dsh-token-dash'], {
59
+ env: { ...process.env, ELECTRON_RUN_AS_NODE: '1' },
60
+ windowsHide: true,
61
+ })
62
+ let tail = ''
63
+ const collect = (chunk) => {
64
+ tail = `${tail}${String(chunk)}`.slice(-2000)
65
+ }
66
+ child.stdout?.on('data', collect)
67
+ child.stderr?.on('data', collect)
68
+ const timer = setTimeout(() => {
69
+ try { child.kill() } catch { /* ignore */ }
70
+ }, 120000)
71
+ child.on('error', (error) => {
72
+ clearTimeout(timer)
73
+ resolve({ ok: false, reason: String(error?.message ?? error), command, output: tail })
74
+ })
75
+ child.on('close', (code) => {
76
+ clearTimeout(timer)
77
+ if (code === 0) resolve({ ok: true, command, output: tail })
78
+ else resolve({ ok: false, reason: `exit-${code}`, command, output: tail })
79
+ })
80
+ })
81
+ }
82
+
83
+ function json(res, status, body) {
84
+ res.writeHead(status, {
85
+ 'content-type': 'application/json; charset=utf-8',
86
+ 'cache-control': 'no-store',
87
+ connection: 'close',
88
+ })
89
+ res.end(JSON.stringify(body))
90
+ }
91
+
92
+ function readBody(req) {
93
+ return new Promise((resolve, reject) => {
94
+ let text = ''
95
+ req.setEncoding('utf8')
96
+ req.on('data', (chunk) => {
97
+ text += chunk
98
+ if (text.length > 64 * 1024) reject(new Error('body-too-large'))
99
+ })
100
+ req.on('error', reject)
101
+ req.on('end', () => resolve(text))
102
+ })
103
+ }
104
+
105
+ function budgetPatch(raw, base) {
106
+ if (raw === null || typeof raw !== 'object') return base
107
+ const amount = Number(raw.amount)
108
+ if (!Number.isFinite(amount) || amount < 0 || amount > 9999999.99) throw new Error('invalid-budget')
109
+ return { amount: Math.round(amount * 100) / 100, currency: raw.currency === 'USD' ? 'USD' : 'CNY' }
110
+ }
111
+
112
+ function normalizePrefs(input, base) {
113
+ const prefs = {
114
+ version: 1,
115
+ budget: { ...base.budget },
116
+ budgets: { ...(base.budgets ?? {}) },
117
+ billingModes: { ...(base.billingModes ?? {}) },
118
+ refreshMs: base.refreshMs,
119
+ showBalance: base.showBalance,
120
+ showMonthTokens: base.showMonthTokens !== false,
121
+ logLevel: base.logLevel === 'debug' ? 'debug' : 'info',
122
+ }
123
+ if (input?.budget !== undefined) prefs.budget = budgetPatch(input.budget, prefs.budget)
124
+ if (input?.budgets !== undefined) {
125
+ if (input.budgets === null || typeof input.budgets !== 'object') throw new Error('invalid-budgets')
126
+ const next = {}
127
+ for (const [id, value] of Object.entries(input.budgets)) {
128
+ if (typeof id !== 'string' || id === '') continue
129
+ next[id] = budgetPatch(value, { amount: 0, currency: 'CNY' })
130
+ }
131
+ prefs.budgets = next
132
+ }
133
+ if (input?.billingModes !== undefined) {
134
+ if (input.billingModes === null || typeof input.billingModes !== 'object') throw new Error('invalid-modes')
135
+ const next = {}
136
+ for (const [id, value] of Object.entries(input.billingModes)) {
137
+ if (value === 'api' || value === 'subscription' || value === 'hide') next[id] = value
138
+ }
139
+ prefs.billingModes = next
140
+ }
141
+ if (input?.refreshMs !== undefined) {
142
+ const refresh = Number(input.refreshMs)
143
+ if (![30000, 60000, 300000].includes(refresh)) throw new Error('invalid-refresh')
144
+ prefs.refreshMs = refresh
145
+ }
146
+ if (input?.showBalance !== undefined) prefs.showBalance = input.showBalance === true
147
+ if (input?.showMonthTokens !== undefined) prefs.showMonthTokens = input.showMonthTokens === true
148
+ if (input?.logLevel !== undefined) prefs.logLevel = input.logLevel === 'debug' ? 'debug' : 'info'
149
+ return prefs
150
+ }
151
+
152
+ export function apply(ctx) {
153
+ const dir = dataDir(ctx)
154
+ const logDir = logsDir(ctx)
155
+ const logger = createLogger({ dir: logDir, version: CURRENT_VERSION, dshVersion: '0.2.1-rc.5' })
156
+ let prefs
157
+ let state
158
+ let providerCache = { at: 0, data: [] }
159
+ const ready = Promise.all([loadState(dir, logger), loadPrefs(dir, logger)]).then(([loadedState, loadedPrefs]) => {
160
+ state = loadedState ?? emptyState()
161
+ prefs = loadedPrefs
162
+ logger.info('boot', 'start', { version: CURRENT_VERSION })
163
+ return { state, prefs }
164
+ })
165
+ const flusher = { schedule() {}, flush: async () => {}, stop() {} }
166
+ let flushReady
167
+
168
+ ctx.effect(() => {
169
+ let disposed = false
170
+ ready
171
+ .then(() => {
172
+ if (disposed) return
173
+ const local = createFlusher(dir, state, 2000, logger)
174
+ flusher.schedule = local.schedule
175
+ flusher.flush = local.flush
176
+ flusher.stop = local.stop
177
+ flushReady = flusher
178
+ flusher.flush().catch(() => {})
179
+ })
180
+ .catch(() => {})
181
+ const tick = setInterval(() => {
182
+ if (flushReady !== undefined) flushReady.flush().catch(() => {})
183
+ }, 30000)
184
+ tick.unref?.()
185
+ return () => {
186
+ disposed = true
187
+ clearInterval(tick)
188
+ flushReady?.stop?.()
189
+ }
190
+ }, 'dsh-token-dash: store')
191
+
192
+ // Pricing refresh is best-effort and never blocks summary.
193
+ ready.then(() => {
194
+ // #47:加载失败不再静默——费用"未定价"报障的关键线索
195
+ void loadCommunityPricing()
196
+ .then((info) => logger.info('pricing', 'catalog.loaded', info))
197
+ .catch((error) => logger.warn('pricing', 'catalog.fail', { message: String(error?.message ?? error) }))
198
+ void loadRouterPricing()
199
+ .then((ok) => logger.info('pricing', 'router.loaded', { ok }))
200
+ .catch((error) => logger.warn('pricing', 'router.fail', { message: String(error?.message ?? error) }))
201
+ })
202
+
203
+ ctx.inject(['sessionPersistence'], (scoped) => {
204
+ ready
205
+ .then(async () => {
206
+ const result = await backfill(scoped, state)
207
+ await flushReady?.flush?.()
208
+ logger.info('collect', result.degraded === null ? 'backfill.done' : 'backfill.degraded', result)
209
+ })
210
+ .catch((error) => logger.warn('collect', 'backfill.failed', { message: String(error) }))
211
+ })
212
+
213
+ ctx.on(
214
+ 'session/event',
215
+ (session, event) => {
216
+ if (state === undefined) return
217
+ const sessionId = session?.id ?? session?.header?.id ?? 'live'
218
+ const record = ingest(state, sessionId, event, num(session?.header?.seedLength))
219
+ if (record !== undefined) flushReady?.schedule?.()
220
+ },
221
+ { global: true },
222
+ )
223
+
224
+ ctx.inject(['webServer'], (scoped) => {
225
+ const webServer = scoped.webServer
226
+ if (webServer === undefined) return
227
+ const off = webServer.register({
228
+ kind: 'prefix',
229
+ path: ROUTE_PREFIX,
230
+ handler: async (req, res) => {
231
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1')
232
+ try {
233
+ await ready
234
+ if (url.pathname === `${ROUTE_PREFIX}/summary` && req.method === 'GET') {
235
+ if (Date.now() - providerCache.at > PROVIDER_TTL) {
236
+ providerCache = { at: Date.now(), data: await readProviders(scoped, prefs) }
237
+ logAdapterEvents(logger, providerCache.data)
238
+ }
239
+ const summary = buildSummary(state, prefs, Date.now(), providerCache.data)
240
+ summary.version = CURRENT_VERSION
241
+ summary.refreshMs = prefs.refreshMs
242
+ logger.info('vm', 'build', { providers: summary.providers.length, api: summary.providers.filter((item) => item.kind === 'api').length, subscription: summary.providers.filter((item) => item.kind === 'subscription').length })
243
+ json(res, 200, { ok: true, data: summary })
244
+ return
245
+ }
246
+ if (url.pathname === `${ROUTE_PREFIX}/providers/refresh` && req.method === 'POST') {
247
+ // 仅重查订阅 provider 配额(GLM / Kimi Coding),绕过 TTL 缓存;无 Key 的订阅 provider 从缓存移除。
248
+ const subs = await readSubscriptions(scoped, prefs)
249
+ const map = new Map(providerCache.data.map((item) => [item.id, item]))
250
+ map.delete('zhipu')
251
+ map.delete('moonshot')
252
+ for (const item of subs) map.set(item.id, item)
253
+ providerCache = { at: Date.now(), data: [...map.values()] }
254
+ logAdapterEvents(logger, subs)
255
+ logger.info('provider', 'subscriptions.refreshed', { ids: subs.map((item) => item.id) })
256
+ json(res, 200, { ok: true, data: { refreshed: subs.map((item) => item.id) } })
257
+ return
258
+ }
259
+ if (url.pathname === `${ROUTE_PREFIX}/log` && req.method === 'POST') {
260
+ // #46:client 端 slot 挂载上报落盘——模块白名单仅 slot,防日志注入
261
+ const body = JSON.parse((await readBody(req)) || '{}')
262
+ if (body?.module !== 'slot' || typeof body?.event !== 'string') {
263
+ json(res, 400, { ok: false, reason: 'invalid-log' })
264
+ return
265
+ }
266
+ logger.info('slot', body.event, typeof body.meta === 'object' && body.meta !== null ? body.meta : {})
267
+ json(res, 200, { ok: true, data: { logged: true } })
268
+ return
269
+ }
270
+ if (url.pathname === `${ROUTE_PREFIX}/update/install` && req.method === 'POST') {
271
+ const profile = typeof process.env.DSH_PROFILE === 'string' && process.env.DSH_PROFILE !== '' ? process.env.DSH_PROFILE : 'desktop'
272
+ const result = await runPluginUpdate(profile)
273
+ logger.info('update', result.ok ? 'install.ok' : 'install.fail', {
274
+ profile,
275
+ reason: result.reason ?? null,
276
+ ...(result.ok ? {} : { output: String(result.output ?? '').slice(-500) }),
277
+ })
278
+ json(res, 200, { ok: result.ok, data: result, ...(result.ok ? {} : { reason: 'install-failed' }) })
279
+ return
280
+ }
281
+ if (url.pathname === `${ROUTE_PREFIX}/update` && req.method === 'GET') {
282
+ if (updateCache.data !== null && Date.now() - updateCache.at < 300000) {
283
+ json(res, 200, { ok: true, data: updateCache.data })
284
+ return
285
+ }
286
+ const response = await fetch('https://registry.npmjs.org/dsh-token-dash/latest', {
287
+ headers: { accept: 'application/json' },
288
+ signal: AbortSignal.timeout(5000),
289
+ })
290
+ if (response.status === 404) {
291
+ const data = { current: CURRENT_VERSION, latest: null, hasUpdate: false, published: false }
292
+ updateCache = { at: Date.now(), data }
293
+ json(res, 200, { ok: true, data })
294
+ return
295
+ }
296
+ if (!response.ok) throw new Error(`registry-${response.status}`)
297
+ const meta = await response.json()
298
+ if (typeof meta?.version !== 'string') throw new Error('invalid-registry-response')
299
+ const data = { current: CURRENT_VERSION, latest: meta.version, hasUpdate: isNewer(meta.version, CURRENT_VERSION), published: true }
300
+ updateCache = { at: Date.now(), data }
301
+ json(res, 200, { ok: true, data })
302
+ return
303
+ }
304
+ if (url.pathname === `${ROUTE_PREFIX}/prefs` && req.method === 'GET') {
305
+ json(res, 200, { ok: true, data: prefs })
306
+ return
307
+ }
308
+ if (url.pathname === `${ROUTE_PREFIX}/prefs` && req.method === 'PUT') {
309
+ const body = JSON.parse((await readBody(req)) || '{}')
310
+ prefs = normalizePrefs(body, prefs)
311
+ await saveJson(dir, 'prefs.json', prefs)
312
+ providerCache = { at: 0, data: [] }
313
+ logger.info('boot', 'prefs.saved', { budgets: Object.keys(prefs.budgets).length, modes: Object.keys(prefs.billingModes).length })
314
+ json(res, 200, { ok: true, data: prefs })
315
+ return
316
+ }
317
+ if (url.pathname === `${ROUTE_PREFIX}/logs/meta` && req.method === 'GET') {
318
+ json(res, 200, { ok: true, data: { dir: logDir, file: logger.file } })
319
+ return
320
+ }
321
+ if (url.pathname === `${ROUTE_PREFIX}/logs/export` && req.method === 'GET') {
322
+ const exported = exportLog(logDir, logger)
323
+ logger.info('diag', 'export', { bytes: exported.bytes, redacted: exported.redacted === true })
324
+ json(res, 200, { ok: true, data: { file: exported.file, content: exported.content } })
325
+ return
326
+ }
327
+ if (url.pathname === `${ROUTE_PREFIX}/logs` && req.method === 'DELETE') {
328
+ clearLog(logDir, logger)
329
+ logger.info('diag', 'clear', {})
330
+ json(res, 200, { ok: true, data: { cleared: true } })
331
+ return
332
+ }
333
+ json(res, 404, { ok: false, reason: 'not-found' })
334
+ } catch (error) {
335
+ logger.error('route', 'failed', { method: req.method, path: url.pathname, message: error instanceof Error ? error.message : String(error) })
336
+ json(res, 400, { ok: false, reason: error instanceof Error ? error.message : String(error) })
337
+ }
338
+ },
339
+ })
340
+ return off
341
+ })
342
+ }
package/locale/en.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "nav": "Token dash",
3
+ "title": "Monthly spend and quota",
4
+ "budget": "Monthly budget",
5
+ "refresh": "Refresh interval",
6
+ "balance": "Account balance",
7
+ "version": "Version"
8
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "nav": "Token 看板",
3
+ "title": "本月费用与额度",
4
+ "budget": "月度预算",
5
+ "refresh": "刷新间隔",
6
+ "balance": "账户余额",
7
+ "version": "版本"
8
+ }
package/package.json CHANGED
@@ -1,6 +1,66 @@
1
1
  {
2
2
  "name": "dsh-token-dash",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "DSH Token 看板:API/订阅动态 provider、预算、配额、模型费用/用量与诊断日志。",
5
+ "type": "module",
6
+ "main": "./index.js",
7
+ "exports": {
8
+ ".": "./index.js",
9
+ "./client": "./client.js",
10
+ "./package.json": "./package.json"
11
+ },
12
+ "files": [
13
+ "index.js",
14
+ "client.js",
15
+ "src",
16
+ "locale",
17
+ "doc/pic",
18
+ "cordis.patch.yml",
19
+ "README.md",
20
+ "LICENSE",
21
+ "AGENTS.md"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "keywords": [
27
+ "deepseek",
28
+ "deepseek-harness",
29
+ "dsh",
30
+ "token",
31
+ "usage",
32
+ "budget"
33
+ ],
34
+ "license": "MIT",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/spartawhy117/dsh-token-dash.git"
38
+ },
39
+ "homepage": "https://github.com/spartawhy117/dsh-token-dash#readme",
40
+ "bugs": {
41
+ "url": "https://github.com/spartawhy117/dsh-token-dash/issues"
42
+ },
43
+ "scripts": {
44
+ "test": "node --test test/unit/*.test.mjs",
45
+ "e2e": "node scripts/e2e.mjs",
46
+ "logs": "node tools/logs.mjs",
47
+ "pack": "node -e \"require('fs').mkdirSync('build',{recursive:true})\" && npm pack --pack-destination build",
48
+ "prepublishOnly": "npm test"
49
+ },
50
+ "dsh": {
51
+ "bundle": {
52
+ "patch": "./cordis.patch.yml"
53
+ },
54
+ "client": {
55
+ "platform": "web",
56
+ "immediately": true,
57
+ "inject": [
58
+ "@deepseek-ai/dsh-client-ui-conversation",
59
+ "@deepseek-ai/dsh-client-ui-settings"
60
+ ]
61
+ }
62
+ },
63
+ "devDependencies": {
64
+ "playwright": "1.64.1"
65
+ }
66
+ }