dsh-usage-prism 0.0.0-stage → 0.1.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
+ # 组合包补丁:插入一条全局插件行。Host 半边自己 inject webServer 与
2
+ # sessionQuery,缺任何一个服务时整条安静地不激活——面板不出现,dsh 照常跑。
3
+ - insert:
4
+ - id: usage-prism
5
+ name: 'dsh-usage-prism'
package/docs/DETAIL.md ADDED
@@ -0,0 +1 @@
1
+ ![用量面板的本周视图:七个热力格子、token 用量与时间去向两张卡、逐模型明细表](preview.png)
Binary file
package/icon.svg ADDED
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 48 48" width="48" height="48" role="img" aria-label="usage panel">
2
+ <rect x="3" y="3" width="42" height="42" rx="13" fill="#fbe3de"/>
3
+ <rect x="11" y="24" width="6" height="13" rx="2" fill="#e2a9a2"/>
4
+ <rect x="21" y="15" width="6" height="22" rx="2" fill="#d08d85"/>
5
+ <rect x="31" y="20" width="6" height="17" rx="2" fill="#93bfb1"/>
6
+ </svg>
package/index.js ADDED
@@ -0,0 +1,271 @@
1
+ /**
2
+ * Host 半边:把本机的会话日志折成一份用量快照,只回答一个只读 GET。
3
+ *
4
+ * 数据只从 `ctx.sessionQuery` 来(live 优先的会话视图,底子是本机的会话日志),
5
+ * 不联网、不写回任何会话。折叠口径在 `lib/fold.js`,与 dsh 自带的 `sessionStats` /
6
+ * `tokenUsage` 投影逐项一致(`test/conformance.mjs` 拿真实日志核对)。
7
+ *
8
+ * 每次请求都重新问一遍 `listSessions()`:变了的会话重折,其余直接用上一次的结果,
9
+ * 所以反复打开面板是便宜的。
10
+ */
11
+
12
+ import fs from 'node:fs'
13
+ import os from 'node:os'
14
+ import path from 'node:path'
15
+ import { FOLD_VERSION, aggregate, dayKey, decodeSummary, encodeSummary, foldSession } from './lib/fold.js'
16
+
17
+ const ROUTE = '/api/usage-prism'
18
+ const DAY_MS = 86400000
19
+ const STORE_VERSION = 1
20
+
21
+ /**
22
+ * 摘要缓存的落盘位置:macOS 用 `~/Library/Caches`,其余平台遵守 `XDG_CACHE_HOME`
23
+ * (没设就退回 `~/.cache`)。缓存只用来省掉重启后的重折,删掉会自动重建。
24
+ */
25
+ function cacheDir() {
26
+ const home = os.homedir()
27
+ if (process.platform === 'darwin') return path.join(home, 'Library', 'Caches')
28
+ const xdg = process.env.XDG_CACHE_HOME
29
+ return xdg !== undefined && xdg !== '' ? xdg : path.join(home, '.cache')
30
+ }
31
+
32
+ const STORE_FILE = path.join(cacheDir(), 'dsh-usage-prism', 'summaries.json')
33
+
34
+ /**
35
+ * 一行诊断。固定为 `<标签>: <来源>: <详情>` 的单行文本,写 stderr 而不是日志服务:
36
+ * 面板是不是活着,看一眼终端最直接。`来源` 里不放冒号,`详情` 压成一行并截断,
37
+ * 免得一条异常把整行撑开。
38
+ */
39
+ function log(source, detail) {
40
+ const text = String(detail).replace(/\s+/g, ' ').trim().slice(0, 300)
41
+ process.stderr.write(`usage-prism: ${source}: ${text}\n`)
42
+ }
43
+
44
+ function localMidnight(ms) {
45
+ const d = new Date(ms)
46
+ d.setHours(0, 0, 0, 0)
47
+ return d.getTime()
48
+ }
49
+
50
+ /** 四种时间尺度的起止日(本地日历,含今天)。 */
51
+ export function scopeRange(scope, now = Date.now()) {
52
+ const today = localMidnight(now)
53
+ const day = new Date(today)
54
+ if (scope === 'week') {
55
+ // 周一算一周的头:JS 的 getDay() 里周日是 0,先挪成「离周一差几天」。
56
+ const offset = (day.getDay() + 6) % 7
57
+ return { from: new Date(today - offset * DAY_MS), to: day }
58
+ }
59
+ if (scope === 'month') return { from: new Date(day.getFullYear(), day.getMonth(), 1), to: day }
60
+ if (scope === 'year') return { from: new Date(day.getFullYear(), 0, 1), to: day }
61
+ return { from: day, to: day }
62
+ }
63
+
64
+ export function apply(ctx, config = {}) {
65
+ const cache = new Map()
66
+ let inflight = null
67
+ let lastLine = ''
68
+ let store = null
69
+ let writing = null
70
+ let storePending = false
71
+
72
+ const sessionQuery = () => ctx.get('sessionQuery')
73
+
74
+ /** 读一次磁盘摘要;坏了就当没有(缓存永远可以重建)。 */
75
+ async function loadStore() {
76
+ if (store !== null) return store
77
+ store = new Map()
78
+ try {
79
+ const payload = JSON.parse(await fs.promises.readFile(STORE_FILE, 'utf8'))
80
+ if (payload?.version !== STORE_VERSION) return store
81
+ for (const [id, entry] of Object.entries(payload.entries ?? {})) {
82
+ if (typeof entry?.key !== 'string' || entry.summary === undefined) continue
83
+ store.set(id, { key: entry.key, summary: decodeSummary(entry.summary) })
84
+ }
85
+ } catch {
86
+ /* 没有缓存或读不动:当空的,下面会重折 */
87
+ }
88
+ return store
89
+ }
90
+
91
+ /** 摘要变了就写回去;异步、原子替换,写失败只丢下一次的加速。 */
92
+ function saveStore() {
93
+ // 上一笔还在写:记一笔待办,写完再补一次,别把这一轮算出来的摘要丢掉。
94
+ if (writing !== null) {
95
+ storePending = true
96
+ return
97
+ }
98
+ const entries = {}
99
+ for (const [id, entry] of cache) {
100
+ // 正在写的会话(`live:`)下次启动必然重折,不占磁盘位置。
101
+ if (typeof entry.key !== 'string' || entry.key.startsWith('live:')) continue
102
+ entries[id] = { key: entry.key, summary: encodeSummary(entry.summary) }
103
+ }
104
+ // 一条都存不下来(比如这一轮根本没拿到会话索引):别拿空表把好缓存冲掉。
105
+ if (Object.keys(entries).length === 0) return
106
+ const body = JSON.stringify({ version: STORE_VERSION, entries })
107
+ writing = (async () => {
108
+ try {
109
+ await fs.promises.mkdir(path.dirname(STORE_FILE), { recursive: true })
110
+ // 临时名带上随机后缀:两个实例同时写也不会撞同一个文件名。
111
+ const temp = `${STORE_FILE}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`
112
+ await fs.promises.writeFile(temp, body)
113
+ await fs.promises.rename(temp, STORE_FILE)
114
+ // 本进程眼里磁盘就是这一份了,后面命中直接查它,不必等下次重启。
115
+ store = new Map(cache)
116
+ } catch (error) {
117
+ log('摘要缓存', `没写成:${error instanceof Error ? error.message : String(error)}`)
118
+ } finally {
119
+ writing = null
120
+ if (storePending) {
121
+ storePending = false
122
+ saveStore()
123
+ }
124
+ }
125
+ })()
126
+ }
127
+
128
+ async function foldAll() {
129
+ const query = sessionQuery()
130
+ if (query === undefined) throw new Error('sessionQuery 不可用')
131
+ const persistence = ctx.get('sessionPersistence')
132
+ const sessions = ctx.get('sessions')
133
+ const records = await query.listSessions()
134
+ const saved = await loadStore()
135
+ // 一次列全的变化令牌,省掉逐个会话去 stat
136
+ const keys = new Map()
137
+ if (persistence !== undefined) {
138
+ try {
139
+ for (const item of await persistence.list()) {
140
+ if (typeof item?.header?.id !== 'string') continue
141
+ // `revision` 是权威的变化令牌(含字节数与 mtime,跨重启可比),拿不到才退到字节数。
142
+ const token =
143
+ typeof item.revision === 'string' && item.revision !== ''
144
+ ? item.revision
145
+ : typeof item.sizeBytes === 'number'
146
+ ? `${item.sizeBytes}:${item.eventCount ?? ''}`
147
+ : null
148
+ if (token !== null) keys.set(item.header.id, `v${FOLD_VERSION}:${token}`)
149
+ }
150
+ } catch (error) {
151
+ // 列不出来就都当没命中:宁愿这一轮重折,也别拿不准的令牌去命中旧摘要。
152
+ log('索引缺失', `本轮全部重折:${error instanceof Error ? error.message : String(error)}`)
153
+ }
154
+ }
155
+ const next = new Map()
156
+ let skipped = 0
157
+ let refolded = 0
158
+ const started = Date.now()
159
+
160
+ /** 折一个会话:命中内存 / 磁盘就不读日志,否则读一遍再折。 */
161
+ const foldOne = async (record) => {
162
+ const id = record.header?.id
163
+ if (typeof id !== 'string') return
164
+ const live = record.live === true
165
+ // 稳定的变化令牌:写完的会话用 `revision`(跨重启也成立);
166
+ // 正在写的会话用内存日志的 seq(磁盘上的那份可能还没落全)。
167
+ let key = keys.get(id) ?? null
168
+ if (live && sessions !== undefined) {
169
+ try {
170
+ const seq = sessions.get(id)?.seq
171
+ if (typeof seq === 'number') key = `live:${seq}`
172
+ } catch {
173
+ /* 读不到就用磁盘那把钥匙 */
174
+ }
175
+ }
176
+ const memo = cache.get(id)
177
+ const disk = saved.get(id)
178
+ // 正在写的会话每次重折(内存里的才最新);其余只认 key 相同的
179
+ if (!live && key !== null && memo !== undefined && memo.key === key) {
180
+ next.set(id, memo)
181
+ return
182
+ }
183
+ if (!live && key !== null && disk !== undefined && disk.key === key) {
184
+ next.set(id, disk)
185
+ return
186
+ }
187
+ try {
188
+ const snapshot = await query.readSession(id)
189
+ next.set(id, { key, summary: foldSession(id, snapshot.events) })
190
+ refolded += 1
191
+ } catch (error) {
192
+ skipped += 1
193
+ log('跳过', `${id}:${error instanceof Error ? error.message : String(error)}`)
194
+ }
195
+ }
196
+
197
+ // 冷启动的时间几乎全花在读日志(解压 + 解析 + 克隆),这几步都是同步的 CPU 活:
198
+ // 同一个线程里并发读没有收益,所以一个个来,省内存。
199
+ for (const record of records) await foldOne(record)
200
+
201
+ cache.clear()
202
+ for (const [id, entry] of next) cache.set(id, entry)
203
+ if (refolded > 0) saveStore()
204
+ return {
205
+ summaries: [...next.values()].map((entry) => entry.summary),
206
+ skipped,
207
+ refolded,
208
+ ms: Date.now() - started,
209
+ total: records.length,
210
+ }
211
+ }
212
+
213
+ async function snapshot(scope) {
214
+ // 同一时间的多个请求共用一次折叠。
215
+ if (inflight === null) {
216
+ inflight = foldAll().finally(() => {
217
+ inflight = null
218
+ })
219
+ }
220
+ const folded = await inflight
221
+ const now = Date.now()
222
+ const range = scopeRange(scope, now)
223
+ const from = dayKey(range.from.getTime())
224
+ const to = dayKey(range.to.getTime())
225
+ const aggregated = aggregate(folded.summaries, { from, to })
226
+ const snapshot = {
227
+ scope,
228
+ from,
229
+ to,
230
+ today: dayKey(now),
231
+ generatedAt: now,
232
+ corpus: { sessions: folded.total, skipped: folded.skipped, refolded: folded.refolded, buildMs: folded.ms },
233
+ totals: aggregated.totals,
234
+ days: aggregated.days,
235
+ hours: scope === 'day' ? aggregated.hours : [],
236
+ models: aggregated.models,
237
+ }
238
+ const detail = `${scope} ${from}..${to} · ${snapshot.totals.tokens} tokens · ${folded.refolded}/${folded.total} 重折 · ${folded.ms}ms`
239
+ if (detail !== lastLine) {
240
+ log('就绪', detail)
241
+ lastLine = detail
242
+ }
243
+ return snapshot
244
+ }
245
+
246
+ ctx.inject(['webServer'], (web) => {
247
+ web.effect(() =>
248
+ web.webServer.register({
249
+ kind: 'exact',
250
+ path: ROUTE,
251
+ // 会话日志是本机隐私:这个端点走 dsh 自己的鉴权。
252
+ auth: 'required',
253
+ resource: async (request) => {
254
+ const url = new URL(request.url)
255
+ const scope = url.searchParams.get('scope') ?? 'week'
256
+ if (!['day', 'week', 'month', 'year'].includes(scope)) {
257
+ return Response.json({ error: 'scope 只能是 day/week/month/year' }, { status: 400 })
258
+ }
259
+ try {
260
+ const body = await snapshot(scope)
261
+ return Response.json(body, { headers: { 'cache-control': 'no-store' } })
262
+ } catch (error) {
263
+ const message = error instanceof Error ? error.message : String(error)
264
+ log('快照失败', message)
265
+ return Response.json({ error: message }, { status: 500, headers: { 'cache-control': 'no-store' } })
266
+ }
267
+ },
268
+ }),
269
+ )
270
+ })
271
+ }