dsh-plugin-balance-usage 0.0.0-stage → 1.0.0

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,3 @@
1
+ - insert:
2
+ - id: balance-usage
3
+ name: 'dsh-plugin-balance-usage'
package/docs/DETAIL.md ADDED
@@ -0,0 +1,75 @@
1
+ # 余额与用量 / Balance & usage
2
+
3
+ 在 DeepSeek Harness 左侧栏底部加一个入口:直接显示账户余额和今日 Token 用量,点开是一个面板,可以看累计用量、近 14 天走势、按运营商 / 模型分组(可折叠),并把任意模型设为「主线」。面板底部按钮打开官方 Token 用量详情页——桌面版在应用内直接打开,浏览器里退回新标签页。
4
+
5
+ ## 数据从哪里来
6
+
7
+ | 数据 | 来源 | 说明 |
8
+ | --- | --- | --- |
9
+ | 账户余额 / 赠送余额 | `ctx.remote.account.getState()` + `getBalance()` | 与「设置 → 账户」相同的平台接口;未登录时只显示提示 |
10
+ | 官方用量页地址 | `AccountView.links.usageUrl` | 默认 `https://platform.deepseek.com/usage`,账号换了 origin 也跟着换 |
11
+ | Token 用量 | 本插件 Host 半扫描 `$DSH_HOME/sessions/**/session.v4.jsonl.zstd` | 读取每条 `assistant/message` 的 `usage` 与 `message.source`(provider / model),按天、按模型汇总 |
12
+
13
+ 用量是本机日志的汇总:不会上传、也不需要额外 npm 依赖。日志是「多帧拼接的 zstd」,`zlib.zstdDecompress` 只会解第一帧,所以 Host 半自带一个帧表扫描器逐帧解码,末帧被截断时用 `ZSTD_e_flush` 抢救。
14
+
15
+ ## 两个半边
16
+
17
+ - **Host(`index.js`)**:注册只读路由 `GET /plugins/balance-usage/summary`(只接受同源请求),扫描并缓存会话日志,20 秒 TTL;启动 2 秒后预热一次缓存。
18
+ - bundle 插件无法给 Client 新增 Remote namespace,所以用 `webServer` 路由把汇总数据交给前端。
19
+ - **Client(`client.js`)**:
20
+ - `sidebar.footer.action`:侧栏底部的入口,展开/收起时自动切换紧凑图标形态(`ownerProps.wide`)。
21
+ - `shell.overlay`:浮层面板,挂在侧栏列右侧(窄轨时正好让开 56px 轨道),按 Esc 或点击空白处关闭。
22
+
23
+ ## 交互与可访问性
24
+
25
+ - 打开面板时焦点移入面板(`role="dialog"` + `aria-labelledby`),Tab 在面板内首尾循环,Esc 关闭后焦点回到入口按钮;入口带 `aria-haspopup="dialog"` / `aria-controls` / `aria-expanded`,星标是 `aria-pressed` 的切换按钮。
26
+ - 折叠行用 `aria-expanded` + `aria-controls` 关联模型列表;图表是 `role="img"`,用一句汇总文案代替逐柱朗读。
27
+ - Esc 监听挂在冒泡阶段且尊重 `defaultPrevented`,不抢占设置弹窗等更上层浮层的按键。
28
+ - 应用内用量页是主内容区里的一页:Esc 或标签栏的 × 关闭,打开时焦点落在关闭按钮上;侧栏保持可见可点,点侧栏任意位置就把页面交还。
29
+ - 首次加载显示骨架条而不是「没有记录」;请求 8 秒超时;失败时保留上一次的「更新于」并标注「(未更新)」,错误块内带「重试」。
30
+ - 侧栏入口的数字会自己走:面板关着时每 30 秒、开着时每 15 秒刷新一次,窗口重新获得焦点或标签页切回前台时还会立刻补一次,所以不用点开就能看到余额和今日用量在变。定时器每 5 秒醒一次,只在数据超过对应间隔时才真的发请求。
31
+ - 颜色只用主题 token:`--dsw-alias-bg-skeleton`(hover / 胶囊底)、`--dsw-alias-chart-messages`(柱状图与主线标记)、`--dsw-alias-state-warn-label`(星标激活)、`--dsw-alias-label-tertiary`(星标静止态);浅色、深色两套主题都实测过。
32
+
33
+ ## 在应用内打开官方用量页
34
+
35
+ - 桌面版渲染进程暴露了 `window.dshPlatform`(`open(page, bounds)` / `setBounds(bounds)` / `close()`),只在 `location.protocol === 'dsh-app:' && location.hostname === 'app'` 时注入。宿主会在页面之上用 `WebContentsView` 加载 `https://platform.deepseek.com/usage`,账号会话由主进程注入,所以不需要再开浏览器、也不会遇到登录态问题。
36
+ - 检测到桥时,底部 CTA 是 `<button>`:点击后关闭浮层,在主内容区(侧栏右侧、窗口顶到窗口底)显示一条 44px 的页面标签栏(`● Token 用量 ×`)加剩余矩形作为原生视图的位置,并调用 `bridge.open('usage', bounds)`;窗口尺寸或侧栏宽度变化时 `ResizeObserver` 调 `setBounds`;点 × / 按 Esc / 点侧栏任意位置都会调 `bridge.close()` 并回到面板、顺手刷新一次余额。
37
+ - 视口矩形由「侧栏列的右边缘」算出(从入口向上找宽度 ≤480 的祖先列),展开态约 `x=280`,窄轨态 `x=56`;因此原生页面不会盖住侧栏,也不会盖住页面标签栏。
38
+ - 没有桥(普通浏览器标签页、`dsh web`)时仍是 `<a target="_blank">` 外链,因此不会出现「点了没反应」。
39
+ - 平台页加载失败会显示错误文案 + 「重试」+ 「在浏览器打开」兜底;iframe 不可行(平台用 CSP / `X-Frame-Options` 拒绝被嵌入),所以只能走宿主的原生视图。
40
+
41
+ ## 设置
42
+
43
+ - **主线模型**:在面板中点击任意模型右侧的星标。若没设过主线,自动取累计用量最高的模型(列表里用 2px 蓝色左条标出);再点一次星标取消,回到自动。
44
+ - **折叠**:点击运营商一行折叠/展开它的模型列表。
45
+ - 两者都存在 `localStorage`:`dsh.balance-usage.primary`、`dsh.balance-usage.collapsed`。
46
+
47
+ ## 接入要点(踩过的坑)
48
+
49
+ - Client 半调用 `ctx.remote.account.*` 时,`inject` 必须同时声明 `'remote'` 和 `'remote.account'`,否则运行时报 `cannot get property "remote.account" without inject`。
50
+ - `ctx.locale.getLocale()` 返回的是 `{ active, locales, revision }` 快照,不是字符串;语言切换通过 `ctx.on('locale/change', …)` 订阅后重绘。
51
+ - `account.getBalance(meta)` 需要 `{ version, locale, timezoneOffsetSeconds }`,`version` 取 `process.env.DSH_CLIENT_VERSION`,缺省时退回 `'web'`。
52
+ - 底部链接必须是真 `<a target="_blank">`:`window.open(url, '_blank', 'noopener')` 会返回 `null`,任何「打不开就 `location.assign`」的兜底都会把整个 DSH 页面导航走。
53
+ - 入口按钮是内容宽度(约 100px),面板定位要向上找更宽的祖先列作为侧栏右边缘,否则面板会压住侧栏会话列表。
54
+
55
+ ## 已验证
56
+
57
+ 在 `http://127.0.0.1:54218` 的真实页面上逐项点过(2026-11-19,桌面版客户端):
58
+
59
+ - 侧栏展开态入口显示 `余额与用量 ¥8.48 今日 36.92M`;窄轨态退化为 32×32 钱包图标 + 右上角小圆点,位置在账号行上方。
60
+ - 面板中文 / 英文文案、余额(账户 / 赠送)、今日 / 累计 / 输入 / 输出 / 缓存读取(含命中率)、近 14 天柱状图、「近 14 天 · N 次请求」全部正确。
61
+ - 点星标写入 `dsh.balance-usage.primary` 并即时改入口数字;再点一次取消并回到自动主线(自动态星标为空心,`aria-pressed=false`)。
62
+ - 折叠运营商行写入 `dsh.balance-usage.collapsed`,刷新页面后仍保持折叠。
63
+ - 底部 CTA 在浏览器里是 `https://platform.deepseek.com/usage` 的外链(`target="_blank" rel="noopener noreferrer"`),点击不会把 DSH 页面导航走;桌面版是按钮,走 `window.dshPlatform`。
64
+ - 用注入的假桥验证过应用内页面:CTA 变 `<button>`,展开态 `open` 收到 `{ page: 'usage', bounds: { x: 280, y: 44, width: 888, height: 398 } }`、窄轨态 `x: 56`,标签栏 44px、视口紧贴其下,侧栏始终可见;窗口缩到 1184×571 后 `setBounds` 收到新的 `{ width: 896, height: 398 }`;点侧栏、点 ×、按 Esc 都会 `close()` 并回到面板;失败时显示「应用内页面打开失败」+ 重试 + 浏览器兜底。
65
+ - Escape 关闭面板且焦点回到入口;浅色与深色主题下都检查过对比度与图形可见性。
66
+ - `node --check` 通过 Host / Client 两个入口文件。
67
+
68
+ ## 已知限制
69
+
70
+ - 面板里的用量只统计会话日志里带 `usage` 的模型消息,工具调用等其它事件不计入 Token;因此本机数字会小于平台账单(平台把每次请求都算进去)。
71
+ - 缓存 TTL 20 秒:刚发完消息立刻看到面板,数字可能仍是上一轮扫描的结果(入口最长 30 秒内也会跟上);想立刻看最新就点面板右上角的刷新。
72
+ - 后台标签页会被浏览器节流,定时器可能拉长到 60 秒以上;切回前台时会立刻补一次刷新。
73
+ - 窄窗口(<760px)下面板改为贴左的宽浮层,会盖住部分内容。
74
+ - 应用内用量页只有桌面版有(依赖 `window.dshPlatform`);`dsh web` 或普通浏览器里仍是新标签页。
75
+ - Electron 桌面版的页面从 `file://` 加载、`fetch` 走 IPC bridge;该版本下自建路由可能不可达,此时面板只显示余额与官方链接,并提示「用量统计服务未就绪」。Web 版(`dsh web`)不受影响。
package/icon.svg ADDED
@@ -0,0 +1,9 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Balance &amp; usage">
2
+ <rect width="64" height="64" rx="15" fill="#2f6df6"/>
3
+ <g fill="none" stroke="#ffffff" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round">
4
+ <path d="M15 27.5A6.5 6.5 0 0 1 21.5 21H44"/>
5
+ <path d="M15 27.5h32.5A5.5 5.5 0 0 1 53 33v10.5A5.5 5.5 0 0 1 47.5 49h-27A5.5 5.5 0 0 1 15 43.5z"/>
6
+ <path d="M15 32.5h15"/>
7
+ </g>
8
+ <circle cx="44.5" cy="39.5" r="3" fill="#ffffff"/>
9
+ </svg>
package/index.js ADDED
@@ -0,0 +1,443 @@
1
+ /**
2
+ * Host half of the balance & usage bundle.
3
+ *
4
+ * The Client half renders a sidebar footer entry plus a floating panel. It needs
5
+ * two kinds of data that no existing Remote namespace offers:
6
+ *
7
+ * - account balance: available through `ctx.remote.account.getBalance()` from
8
+ * the Client, so it stays there;
9
+ * - whole-history token usage: only recoverable by reading the persisted
10
+ * session logs. This half scans `$DSH_HOME/sessions/**\/session.v4.jsonl.zstd`
11
+ * and serves the aggregate over one read-only HTTP route.
12
+ *
13
+ * A bundle may not extend the Client's Remote capability set, so a plain
14
+ * `webServer` route is the supported way to hand Host-side numbers to the
15
+ * Client too.
16
+ */
17
+ import { readdir, readFile, stat } from 'node:fs/promises'
18
+ import os from 'node:os'
19
+ import path from 'node:path'
20
+ import zlib from 'node:zlib'
21
+
22
+ const ROUTE = '/plugins/balance-usage/summary'
23
+ const LOG_FILE = 'session.v4.jsonl.zstd'
24
+ const SCAN_TTL_MS = 20_000
25
+ const MAX_FILE_BYTES = 64 * 1024 * 1024
26
+ const ZSTD_MAGIC = 0xfd2fb528
27
+ const DAYS_SHOWN = 14
28
+
29
+ /* ------------------------------------------------------------------ *
30
+ * zstd container: a session log is a concatenation of independent
31
+ * frames, and `zlib.zstdDecompress` stops after the first one, so the
32
+ * frame table has to be walked by hand before decoding.
33
+ * ------------------------------------------------------------------ */
34
+
35
+ function scanZstdFrames(buffer) {
36
+ const frames = []
37
+ let offset = 0
38
+ let tornStart
39
+
40
+ while (offset + 4 <= buffer.length) {
41
+ if (buffer.readUInt32LE(offset) !== ZSTD_MAGIC) break
42
+
43
+ const start = offset
44
+ offset += 4
45
+ const descriptor = buffer[offset++]
46
+ const contentSizeFlag = descriptor >>> 6
47
+ const singleSegment = (descriptor & 0x20) !== 0
48
+ const hasChecksum = (descriptor & 0x04) !== 0
49
+ const dictionaryFlag = descriptor & 0x03
50
+ const dictionaryBytes = dictionaryFlag === 3 ? 4 : dictionaryFlag
51
+ const contentSizeBytes = contentSizeFlag === 0 ? (singleSegment ? 1 : 0) : 1 << contentSizeFlag
52
+ offset += (singleSegment ? 0 : 1) + dictionaryBytes + contentSizeBytes
53
+
54
+ let complete = false
55
+ while (offset + 3 <= buffer.length) {
56
+ const header = buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16)
57
+ offset += 3
58
+ const lastBlock = (header & 1) !== 0
59
+ const blockType = (header >>> 1) & 0x03
60
+ const blockSize = header >>> 3
61
+ if (blockType === 0x03) break
62
+ offset += blockType === 0x01 ? 1 : blockSize
63
+ if (lastBlock) {
64
+ complete = true
65
+ break
66
+ }
67
+ }
68
+
69
+ if (!complete) {
70
+ tornStart = start
71
+ break
72
+ }
73
+ if (hasChecksum) offset += 4
74
+ if (offset > buffer.length) {
75
+ tornStart = start
76
+ break
77
+ }
78
+ frames.push({ start, end: offset })
79
+ }
80
+
81
+ return { frames, tornStart }
82
+ }
83
+
84
+ function decodeZstdLog(buffer) {
85
+ const { frames, tornStart } = scanZstdFrames(buffer)
86
+ const parts = []
87
+
88
+ for (const frame of frames) {
89
+ try {
90
+ parts.push(zlib.zstdDecompressSync(buffer.subarray(frame.start, frame.end)))
91
+ } catch {
92
+ /* skip an undecodable frame instead of losing the whole log */
93
+ }
94
+ }
95
+
96
+ if (tornStart !== undefined) {
97
+ /* A live session may end in a partially written frame: salvage what is
98
+ there rather than dropping the newest events. */
99
+ try {
100
+ parts.push(
101
+ zlib.zstdDecompressSync(buffer.subarray(tornStart), {
102
+ finishFlush: zlib.constants.ZSTD_e_flush,
103
+ }),
104
+ )
105
+ } catch {
106
+ /* nothing salvageable */
107
+ }
108
+ }
109
+
110
+ return Buffer.concat(parts).toString('utf8')
111
+ }
112
+
113
+ /* ------------------------------------------------------------------ *
114
+ * Aggregation
115
+ * ------------------------------------------------------------------ */
116
+
117
+ function emptyCounters() {
118
+ return { tokens: 0, requests: 0, inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0 }
119
+ }
120
+
121
+ function addCounters(target, source) {
122
+ target.tokens += source.tokens || 0
123
+ target.requests += source.requests || 0
124
+ target.inputTokens += source.inputTokens || 0
125
+ target.outputTokens += source.outputTokens || 0
126
+ target.cacheReadTokens += source.cacheReadTokens || 0
127
+ target.cacheWriteTokens += source.cacheWriteTokens || 0
128
+ return target
129
+ }
130
+
131
+ function counterFromUsage(usage) {
132
+ const inputTokens = numberOrZero(usage.inputTokens)
133
+ const outputTokens = numberOrZero(usage.outputTokens)
134
+ const cacheReadTokens = numberOrZero(usage.cacheReadTokens)
135
+ const cacheWriteTokens = numberOrZero(usage.cacheWriteTokens)
136
+ const total = numberOrZero(usage.totalTokens) || inputTokens + outputTokens
137
+ return { tokens: total, requests: 1, inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens }
138
+ }
139
+
140
+ function numberOrZero(value) {
141
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0
142
+ }
143
+
144
+ function dayKey(ms) {
145
+ const date = new Date(ms)
146
+ const month = String(date.getMonth() + 1).padStart(2, '0')
147
+ const day = String(date.getDate()).padStart(2, '0')
148
+ return `${date.getFullYear()}-${month}-${day}`
149
+ }
150
+
151
+ function aggregateLog(text) {
152
+ const models = new Map()
153
+ const days = new Map()
154
+ const totals = emptyCounters()
155
+
156
+ for (const line of text.split('\n')) {
157
+ if (line.length === 0) continue
158
+
159
+ let event
160
+ try {
161
+ event = JSON.parse(line)
162
+ } catch {
163
+ continue
164
+ }
165
+
166
+ if (event.type !== 'assistant/message') continue
167
+ const usage = event.data?.usage
168
+ if (!usage) continue
169
+
170
+ const source = event.data?.message?.source
171
+ if (source?.kind !== 'model') continue
172
+
173
+ const counters = counterFromUsage(usage)
174
+ const provider = typeof source.provider === 'string' ? source.provider : 'unknown'
175
+ const model = typeof source.model === 'string' ? source.model : 'unknown'
176
+ const key = `${provider}\u0000${model}`
177
+ const at = typeof event.time === 'number' ? event.time : Date.now()
178
+ const day = dayKey(at)
179
+
180
+ addCounters(totals, counters)
181
+
182
+ const entry = models.get(key) || {
183
+ provider,
184
+ model,
185
+ ...emptyCounters(),
186
+ lastUsed: 0,
187
+ firstUsed: at,
188
+ }
189
+ addCounters(entry, counters)
190
+ entry.lastUsed = Math.max(entry.lastUsed, at)
191
+ entry.firstUsed = Math.min(entry.firstUsed, at)
192
+ models.set(key, entry)
193
+
194
+ const bucket = days.get(day) || emptyCounters()
195
+ addCounters(bucket, counters)
196
+ days.set(day, bucket)
197
+ }
198
+
199
+ return { totals, models: [...models.values()], days: Object.fromEntries(days) }
200
+ }
201
+
202
+ /* ------------------------------------------------------------------ *
203
+ * Scanning
204
+ * ------------------------------------------------------------------ */
205
+
206
+ function sessionsRoot() {
207
+ const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
208
+ return path.join(home, 'sessions')
209
+ }
210
+
211
+ async function listLogFiles(root) {
212
+ const files = []
213
+ let workspaces
214
+ try {
215
+ workspaces = await readdir(root, { withFileTypes: true })
216
+ } catch {
217
+ return files
218
+ }
219
+
220
+ for (const workspace of workspaces) {
221
+ if (!workspace.isDirectory()) continue
222
+ const workspaceDir = path.join(root, workspace.name)
223
+ let sessions
224
+ try {
225
+ sessions = await readdir(workspaceDir, { withFileTypes: true })
226
+ } catch {
227
+ continue
228
+ }
229
+ for (const session of sessions) {
230
+ if (!session.isDirectory()) continue
231
+ const file = path.join(workspaceDir, session.name, LOG_FILE)
232
+ try {
233
+ const info = await stat(file)
234
+ if (info.isFile() && info.size <= MAX_FILE_BYTES) {
235
+ files.push({ file, mtimeMs: info.mtimeMs, size: info.size })
236
+ }
237
+ } catch {
238
+ continue
239
+ }
240
+ }
241
+ }
242
+
243
+ return files
244
+ }
245
+
246
+ async function aggregateFile(entry) {
247
+ const buffer = await readFile(entry.file)
248
+ const text = decodeZstdLog(buffer)
249
+ return { ...aggregateLog(text), size: buffer.length, mtimeMs: entry.mtimeMs }
250
+ }
251
+
252
+ function mergeAll(aggregates) {
253
+ const totals = emptyCounters()
254
+ const today = emptyCounters()
255
+ const models = new Map()
256
+ const days = new Map()
257
+ const todayLabel = dayKey(Date.now())
258
+
259
+ for (const aggregate of aggregates) {
260
+ addCounters(totals, aggregate.totals)
261
+
262
+ const bucket = aggregate.days[todayLabel]
263
+ if (bucket) addCounters(today, bucket)
264
+
265
+ for (const model of aggregate.models) {
266
+ const key = `${model.provider}\u0000${model.model}`
267
+ const entry = models.get(key) || {
268
+ provider: model.provider,
269
+ model: model.model,
270
+ ...emptyCounters(),
271
+ firstUsed: model.firstUsed,
272
+ lastUsed: model.lastUsed,
273
+ }
274
+ addCounters(entry, model)
275
+ entry.firstUsed = Math.min(entry.firstUsed, model.firstUsed)
276
+ entry.lastUsed = Math.max(entry.lastUsed, model.lastUsed)
277
+ models.set(key, entry)
278
+ }
279
+
280
+ for (const [day, counters] of Object.entries(aggregate.days)) {
281
+ const bucket = days.get(day) || emptyCounters()
282
+ addCounters(bucket, counters)
283
+ days.set(day, bucket)
284
+ }
285
+ }
286
+
287
+ const groups = new Map()
288
+ for (const model of models.values()) {
289
+ const group = groups.get(model.provider) || {
290
+ provider: model.provider,
291
+ ...emptyCounters(),
292
+ lastUsed: 0,
293
+ models: [],
294
+ }
295
+ addCounters(group, model)
296
+ group.lastUsed = Math.max(group.lastUsed, model.lastUsed)
297
+ group.models.push({
298
+ model: model.model,
299
+ ...emptyCounters(),
300
+ tokens: model.tokens,
301
+ requests: model.requests,
302
+ inputTokens: model.inputTokens,
303
+ outputTokens: model.outputTokens,
304
+ cacheReadTokens: model.cacheReadTokens,
305
+ cacheWriteTokens: model.cacheWriteTokens,
306
+ firstUsed: model.firstUsed,
307
+ lastUsed: model.lastUsed,
308
+ })
309
+ groups.set(model.provider, group)
310
+ }
311
+
312
+ const groupList = [...groups.values()]
313
+ .map((group) => ({
314
+ ...group,
315
+ models: group.models.sort((a, b) => b.tokens - a.tokens || b.lastUsed - a.lastUsed),
316
+ }))
317
+ .sort((a, b) => b.tokens - a.tokens || b.lastUsed - a.lastUsed)
318
+
319
+ const series = []
320
+ for (let index = DAYS_SHOWN - 1; index >= 0; index -= 1) {
321
+ const date = new Date()
322
+ date.setHours(0, 0, 0, 0)
323
+ date.setDate(date.getDate() - index)
324
+ const key = dayKey(date.getTime())
325
+ series.push({ date: key, tokens: days.get(key)?.tokens || 0 })
326
+ }
327
+
328
+ return { totals, today, groups: groupList, series }
329
+ }
330
+
331
+ /* ------------------------------------------------------------------ *
332
+ * Route
333
+ * ------------------------------------------------------------------ */
334
+
335
+ function sameOrigin(request) {
336
+ const site = request.headers.get('sec-fetch-site')
337
+ if (site && site !== 'same-origin' && site !== 'none') return false
338
+
339
+ const origin = request.headers.get('origin')
340
+ if (origin) {
341
+ try {
342
+ if (new URL(origin).host !== request.headers.get('host')) return false
343
+ } catch {
344
+ return false
345
+ }
346
+ }
347
+
348
+ return true
349
+ }
350
+
351
+ function json(body, status = 200) {
352
+ return new Response(JSON.stringify(body), {
353
+ status,
354
+ headers: {
355
+ 'content-type': 'application/json; charset=utf-8',
356
+ 'cache-control': 'no-store',
357
+ },
358
+ })
359
+ }
360
+
361
+ export const name = 'balance-usage'
362
+ export const inject = ['webServer']
363
+
364
+ export function apply(ctx) {
365
+ const files = new Map()
366
+ let scanning = null
367
+ let cached = null
368
+ let cachedAt = 0
369
+
370
+ async function scan() {
371
+ const listing = await listLogFiles(sessionsRoot())
372
+ const present = new Set(listing.map((entry) => entry.file))
373
+
374
+ for (const known of [...files.keys()]) {
375
+ if (!present.has(known)) files.delete(known)
376
+ }
377
+
378
+ const queue = listing.filter((entry) => {
379
+ const cachedEntry = files.get(entry.file)
380
+ return !cachedEntry || cachedEntry.mtimeMs !== entry.mtimeMs || cachedEntry.size !== entry.size
381
+ })
382
+
383
+ for (const entry of queue) {
384
+ try {
385
+ files.set(entry.file, await aggregateFile(entry))
386
+ } catch {
387
+ /* unreadable log: keep whatever the previous scan had, if anything */
388
+ }
389
+ }
390
+
391
+ const merged = mergeAll([...files.values()])
392
+ return {
393
+ ...merged,
394
+ sessions: listing.length,
395
+ generatedAt: new Date().toISOString(),
396
+ }
397
+ }
398
+
399
+ async function summary() {
400
+ if (cached && Date.now() - cachedAt < SCAN_TTL_MS) return cached
401
+ if (!scanning) {
402
+ scanning = scan()
403
+ .then((result) => {
404
+ cached = result
405
+ cachedAt = Date.now()
406
+ return result
407
+ })
408
+ .finally(() => {
409
+ scanning = null
410
+ })
411
+ }
412
+ return scanning
413
+ }
414
+
415
+ ctx.effect(
416
+ () =>
417
+ ctx.webServer.register({
418
+ kind: 'exact',
419
+ path: ROUTE,
420
+ resource: async (request) => {
421
+ if (!sameOrigin(request)) return json({ ok: false, error: 'forbidden' }, 403)
422
+ try {
423
+ const result = await summary()
424
+ return json({ ok: true, ...result })
425
+ } catch (error) {
426
+ ctx.logger?.warn?.(error)
427
+ return json({ ok: false, error: String(error?.message ?? error) }, 500)
428
+ }
429
+ },
430
+ }),
431
+ 'balance-usage: summary route',
432
+ )
433
+
434
+ /* Warm the cache once so the first open of the panel is instant. */
435
+ ctx.effect(() => {
436
+ const timer = setTimeout(() => {
437
+ summary().catch(() => {})
438
+ }, 2_000)
439
+ return () => clearTimeout(timer)
440
+ }, 'balance-usage: warm scan')
441
+
442
+ ctx.logger?.info?.(`[balance-usage] serving ${ROUTE}`)
443
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Balance & usage",
4
+ "description": "Shows the DeepSeek account balance and token usage at the sidebar foot, with a shortcut to the official usage page.",
5
+ "detail": "Adds an entry at the sidebar foot that shows the account balance and today's token usage. Clicking it opens a panel with lifetime usage, a 14-day trend, and collapsible groups per provider and model; any model can be promoted to \"main\" and drives the numbers shown in the sidebar. The button at the bottom of the panel opens the official token usage page. The balance comes from the DeepSeek platform account API; usage is aggregated from local session logs by this plugin and never leaves the machine."
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "余额与用量",
4
+ "description": "在左侧栏底部显示 DeepSeek 账户余额与 Token 用量,一键打开官方用量详情页。",
5
+ "detail": "在左侧栏底部新增一个入口:直接显示账户余额和今日 Token 用量,点击展开面板可查看累计用量、近 14 天走势,并按运营商 / 模型分组折叠;每个模型都能设为「主线」,主线决定侧栏上显示的数字。面板底部的按钮会打开官方 Token 用量详情页。余额来自 DeepSeek 平台账户接口,用量由本插件扫描本机会话日志汇总得出,数据不会离开这台机器。"
6
+ }
7
+ }
package/package.json CHANGED
@@ -1,6 +1,73 @@
1
1
  {
2
2
  "name": "dsh-plugin-balance-usage",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "DSH 侧栏余额与用量:在左侧栏底部显示 DeepSeek 账户余额与 Token 用量,面板内可查看近 14 天走势、按运营商/模型折叠、设置主线,并直接在应用内打开官方用量页。",
6
+ "keywords": [
7
+ "dsh-plugin",
8
+ "deepseek-harness",
9
+ "dsh",
10
+ "cordis",
11
+ "balance",
12
+ "usage",
13
+ "tokens",
14
+ "sidebar",
15
+ "余额",
16
+ "用量"
17
+ ],
18
+ "license": "MIT",
19
+ "author": {
20
+ "name": "kasshuang"
21
+ },
22
+ "homepage": "https://github.com/kasshuang/dsh-plugin-balance-usage#readme",
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "git+https://github.com/kasshuang/dsh-plugin-balance-usage.git"
26
+ },
27
+ "bugs": {
28
+ "url": "https://github.com/kasshuang/dsh-plugin-balance-usage/issues"
29
+ },
30
+ "icon": "icon.svg",
31
+ "main": "./index.js",
32
+ "exports": {
33
+ ".": "./index.js",
34
+ "./client": "./client.js",
35
+ "./locale/*.json": "./locale/*.json",
36
+ "./icon": "./icon.svg",
37
+ "./package.json": "./package.json"
38
+ },
39
+ "files": [
40
+ "index.js",
41
+ "client.js",
42
+ "cordis.patch.yml",
43
+ "locale/*.json",
44
+ "docs",
45
+ "icon.svg",
46
+ "README.md",
47
+ "LICENSE",
48
+ "CHANGELOG.md"
49
+ ],
50
+ "engines": {
51
+ "dsh": ">=0.2.2-rc.1 <0.3.0-0 || >=0.2.3-rc.1 <0.3.0-0 || >=0.2.4-rc.1 <0.3.0-0",
52
+ "node": ">=22"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public"
56
+ },
57
+ "dsh": {
58
+ "bundle": {
59
+ "patch": "./cordis.patch.yml"
60
+ },
61
+ "client": {
62
+ "platform": "web",
63
+ "immediately": true,
64
+ "inject": ["@deepseek-ai/dsh-api-remotes", "@deepseek-ai/dsh-client-locale"]
65
+ },
66
+ "compatibility": {
67
+ "dsh": ">=0.2.2-rc.1 <0.3.0-0 || >=0.2.3-rc.1 <0.3.0-0 || >=0.2.4-rc.1 <0.3.0-0",
68
+ "dshReleases": {
69
+ "0.2.2-rc.3": "compatible"
70
+ }
71
+ }
72
+ }
73
+ }