dsh-usage-bar 0.0.0-stage → 0.1.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.
package/src/index.js ADDED
@@ -0,0 +1,434 @@
1
+ /**
2
+ * ContextMeter — host 半边。
3
+ *
4
+ * 职责:
5
+ * 1. 在 DSH Web 服务上注册同源只读路由 `/context-meter/stats`,
6
+ * 汇总「本会话累计计费输入 token」返回给浏览器端;
7
+ * 2. 注册 `/handoff` 与 `/handoff-file` 两个命令,把交接请求放进内存队列,
8
+ * 由浏览器端的进度条组件取走后执行(新建会话、改名只能由客户端做)。
9
+ *
10
+ * 两个数据源:
11
+ * 1. dsh-cost-meter 的账本(~/.dsh/storages/cost-meter/ledger.json)
12
+ * —— 持久化、覆盖历史会话,是主力来源;
13
+ * 2. billion-context 的 18787 端口 /__bili/stats
14
+ * —— 只有它本次进程见过的会话,但带窗口占用/折叠块等实时信息,做补充。
15
+ *
16
+ * 浏览器端直连 18787 会被 CORS 拦住,所以必须由 host 中转。
17
+ */
18
+
19
+ import { appendFileSync, readFileSync, writeFileSync } from 'node:fs'
20
+ import { homedir } from 'node:os'
21
+ import { join } from 'node:path'
22
+ import { fileURLToPath } from 'node:url'
23
+
24
+ import { fetchBiliStats } from './lib/bili-stats.js'
25
+ import { fetchAllLedgerSessions, fetchLedgerSession, ledgerLastError } from './lib/ledger-stats.js'
26
+ import { fetchSessionContexts } from './lib/session-context.js'
27
+
28
+ export const name = 'context-meter'
29
+
30
+ const ROUTE_PATH = '/context-meter/stats'
31
+ /** 全局 AGENTS 的真实路径,交给浏览器端拼交接引导词,避免在 client 里写死用户名。 */
32
+ const GLOBAL_AGENTS_FILE = join(homedir(), '.dsh', 'AGENTS.md')
33
+ const HANDOFF_PATH = '/context-meter/handoff'
34
+ /** 左侧栏着色用:批量返回多个会话的上下文占用率。 */
35
+ const CONTEXTS_PATH = '/context-meter/contexts'
36
+ /** 浏览器端把 DOM 探测结果写到这里,方便在没有 devtools 时排查渲染问题。 */
37
+ const DEBUG_PATH = '/context-meter/debug'
38
+ const DEBUG_FILE = fileURLToPath(new URL('../debug.log', import.meta.url))
39
+
40
+ /**
41
+ * 左侧栏着色的阈值配置。
42
+ * 放在项目目录的 tint.json 里,改文件后 5 秒内浏览器端就会重新拉到,不需要重启 DSH。
43
+ * 默认值就是需求里的 60% / 80%。
44
+ */
45
+ const TINT_PATH = '/context-meter/tint'
46
+ const TINT_FILE = fileURLToPath(new URL('../tint.json', import.meta.url))
47
+ const TINT_DEFAULT = { warn: 60, danger: 80, window: 500000000 }
48
+
49
+ // 「标记停用」状态:只是给人看的标记,不碰会话内容。
50
+ // 存成项目目录下的 disabled.json,重启 DSH 也不丢;
51
+ // 放在 host 端是为了让 /handoff 命令也能顺手把原对话标记为停用。
52
+ const DISABLED_PATH = '/context-meter/disabled'
53
+ const DISABLED_FILE = fileURLToPath(new URL('../disabled.json', import.meta.url))
54
+
55
+ function readDisabledIds() {
56
+ try {
57
+ const raw = readFileSync(DISABLED_FILE, 'utf8')
58
+ const data = JSON.parse(raw)
59
+ if (!data || typeof data.ids !== 'object' || !data.ids) return {}
60
+ return data.ids
61
+ } catch {
62
+ return {}
63
+ }
64
+ }
65
+
66
+ function writeDisabledIds(ids) {
67
+ try {
68
+ writeFileSync(DISABLED_FILE, JSON.stringify({ ids }, null, 2) + '\n', 'utf8')
69
+ } catch {
70
+ // 写盘失败不影响内存里的路由结果
71
+ }
72
+ }
73
+
74
+ function readTintConfig() {
75
+ try {
76
+ const raw = readFileSync(TINT_FILE, 'utf8')
77
+ const parsed = JSON.parse(raw)
78
+ const num = (value, fallback) => (Number.isFinite(Number(value)) ? Number(value) : fallback)
79
+ return {
80
+ warn: num(parsed.warn, TINT_DEFAULT.warn),
81
+ danger: num(parsed.danger, TINT_DEFAULT.danger),
82
+ window: num(parsed.window, TINT_DEFAULT.window),
83
+ source: 'tint.json',
84
+ }
85
+ } catch {
86
+ return { ...TINT_DEFAULT, source: 'default' }
87
+ }
88
+ }
89
+
90
+ /** 待浏览器端执行的交接请求:sessionId -> 请求数组(先进先出)。 */
91
+ const pendingHandoffs = new Map()
92
+
93
+ /** 统一会话 id:去掉 billion-context 的 session- 前缀并小写。 */
94
+ const normId = (id) => String(id || '').trim().toLowerCase().replace(/^session-/, '')
95
+
96
+ /** 只保留客户端需要的字段,避免把整个 stats 表传给页面。 */
97
+ function pickSession(entry) {
98
+ return {
99
+ id: entry.id,
100
+ title: entry.title || entry.label || '',
101
+ requests: entry.requests ?? 0,
102
+ inputTokens: entry.inputTokens ?? 0,
103
+ cachedTokens: entry.cachedTokens ?? 0,
104
+ outputTokens: entry.outputTokens ?? 0,
105
+ contextTokens: entry.contextTokens ?? 0,
106
+ contextWindow: entry.contextWindow ?? 0,
107
+ blocks: entry.blocks ?? 0,
108
+ cacheHitPct: entry.cacheHitPct ?? null,
109
+ lastModel: entry.lastModel || '',
110
+ lastSeen: entry.lastSeen ?? null,
111
+ source: entry.source || 'billion-context',
112
+ }
113
+ }
114
+
115
+ /**
116
+ * 合并两个来源:累计值取较大者(两个来源都只是下界),
117
+ * 实时信息优先用 billion-context。
118
+ */
119
+ function mergeSession(ledger, bili) {
120
+ const base = bili || ledger
121
+ if (!base) return null
122
+ const sources = []
123
+ if (ledger) sources.push('cost-meter-ledger')
124
+ if (bili) sources.push('billion-context')
125
+ return {
126
+ ...base,
127
+ title: base.title || (ledger && ledger.title) || '',
128
+ requests: Math.max(Number(ledger?.requests) || 0, Number(bili?.requests) || 0),
129
+ inputTokens: Math.max(Number(ledger?.inputTokens) || 0, Number(bili?.inputTokens) || 0),
130
+ cachedTokens: Math.max(Number(ledger?.cachedTokens) || 0, Number(bili?.cachedTokens) || 0),
131
+ outputTokens: Math.max(Number(ledger?.outputTokens) || 0, Number(bili?.outputTokens) || 0),
132
+ source: sources.join('+'),
133
+ }
134
+ }
135
+
136
+ function json(res, status, body) {
137
+ const payload = JSON.stringify(body)
138
+ res.writeHead(status, {
139
+ 'content-type': 'application/json; charset=utf-8',
140
+ 'cache-control': 'no-store',
141
+ 'content-length': Buffer.byteLength(payload),
142
+ })
143
+ res.end(payload)
144
+ }
145
+
146
+ /**
147
+ * 命令 handler:只登记请求并立刻返回。
148
+ * 真正的「让模型写文件 / 新建对话 / 改名」由浏览器端完成,
149
+ * 因为新建会话与改标题只有客户端服务能调。
150
+ */
151
+ function enqueueHandoff(invocation, kind) {
152
+ const sessionId = String(invocation?.agent?.id || '')
153
+ if (!sessionId) {
154
+ return { kind: 'error', text: '拿不到当前会话 id,无法登记交接请求。' }
155
+ }
156
+ const queue = pendingHandoffs.get(sessionId) || []
157
+ queue.push({ kind, at: Date.now() })
158
+ pendingHandoffs.set(sessionId, queue)
159
+
160
+ // 交接之后原对话就「交出去了」,顺手标记为停用,方便在侧栏一眼认出来。
161
+ try {
162
+ const ids = readDisabledIds()
163
+ ids[normId(sessionId)] = { at: Date.now(), by: 'handoff' }
164
+ writeDisabledIds(ids)
165
+ } catch {
166
+ // 标记失败不影响交接本身
167
+ }
168
+
169
+ return {
170
+ kind: 'success',
171
+ text:
172
+ kind === 'full'
173
+ ? '已登记:生成交接文件 → 新建「原名 #N」对话 → 在新对话里读取 AGENTS 与交接文件。交接文件的完整路径会在写完后给出。'
174
+ : '已登记:生成本次对话的工作交接文件。写完后会给出完整路径。',
175
+ }
176
+ }
177
+
178
+ export function apply(ctx) {
179
+ ctx.inject(['commands'], (cmdCtx) => {
180
+ cmdCtx.effect(
181
+ () =>
182
+ cmdCtx.commands.register({
183
+ name: 'handoff',
184
+ description: '交接并新开对话:生成交接文件,新建「原名 #N」对话并在其中读取交接文件',
185
+ handler: (invocation) => enqueueHandoff(invocation, 'full'),
186
+ }),
187
+ 'context-meter: handoff command',
188
+ )
189
+ cmdCtx.effect(
190
+ () =>
191
+ cmdCtx.commands.register({
192
+ name: 'handoff-file',
193
+ description: '只生成交接文件(不改动对话)',
194
+ handler: (invocation) => enqueueHandoff(invocation, 'file'),
195
+ }),
196
+ 'context-meter: handoff-file command',
197
+ )
198
+ })
199
+
200
+ ctx.inject(['webServer'], (webCtx) => {
201
+ webCtx.effect(
202
+ () =>
203
+ webCtx.webServer.register({
204
+ kind: 'exact',
205
+ path: ROUTE_PATH,
206
+ handler: async (req, res) => {
207
+ if (req.method !== 'GET') {
208
+ res.writeHead(405, { allow: 'GET' })
209
+ res.end()
210
+ return
211
+ }
212
+
213
+ let wantId = ''
214
+ try {
215
+ const url = new URL(req.url || ROUTE_PATH, 'http://localhost')
216
+ wantId = url.searchParams.get('sessionId') || ''
217
+ } catch {
218
+ // 查询串异常时按「返回全部摘要」处理
219
+ }
220
+
221
+ const [ledger, stats] = await Promise.all([
222
+ wantId ? fetchLedgerSession(wantId).catch(() => null) : Promise.resolve(null),
223
+ fetchBiliStats().catch(() => null),
224
+ ])
225
+
226
+ const all =
227
+ stats && Array.isArray(stats.sessions) ? stats.sessions.map(pickSession) : []
228
+ // billion-context 的会话 id 形如 session-<uuid>,两端都接受
229
+ const biliMatch = wantId
230
+ ? all.find((s) => s.id === wantId || s.id === 'session-' + wantId) || null
231
+ : null
232
+
233
+ // 不带 sessionId(左侧栏要全量)时,把账本里所有会话也并进来,
234
+ // 否则老对话在 billion-context 里查不到,侧栏永远是 0%。
235
+ let visible = all
236
+ if (!wantId) {
237
+ const ledgerAll = await fetchAllLedgerSessions().catch(() => new Map())
238
+ if (ledgerAll && ledgerAll.size > 0) {
239
+ const merged = new Map()
240
+ for (const item of all) merged.set(normId(item.id), item)
241
+ for (const [id, entry] of ledgerAll) {
242
+ merged.set(id, mergeSession(entry, merged.get(id) || null))
243
+ }
244
+ visible = [...merged.values()]
245
+ }
246
+ }
247
+
248
+ const session = mergeSession(ledger, biliMatch)
249
+ const biliUp = Boolean(stats && Array.isArray(stats.sessions))
250
+ const ledgerReadable = !ledgerLastError()
251
+ const available = biliUp || ledgerReadable
252
+
253
+ if (!session) {
254
+ json(res, 200, {
255
+ ok: available,
256
+ error: available ? null : '统计来源不可用(billion-context 未运行,cost-meter 账本不可读)',
257
+ sessions: visible,
258
+ session: null,
259
+ paths: { globalAgents: GLOBAL_AGENTS_FILE },
260
+ sources: biliUp ? ['billion-context'] : [],
261
+ ledgerError: ledgerLastError() || null,
262
+ fetchedAt: Date.now(),
263
+ })
264
+ return
265
+ }
266
+
267
+ json(res, 200, {
268
+ ok: true,
269
+ sessions: visible,
270
+ session,
271
+ paths: { globalAgents: GLOBAL_AGENTS_FILE },
272
+ sources: session.source ? session.source.split('+') : [],
273
+ ledgerError: ledgerLastError() || null,
274
+ fetchedAt: Date.now(),
275
+ })
276
+ },
277
+ }),
278
+ 'context-meter: stats route',
279
+ )
280
+
281
+ webCtx.effect(
282
+ () =>
283
+ webCtx.webServer.register({
284
+ kind: 'exact',
285
+ path: HANDOFF_PATH,
286
+ handler: (req, res) => {
287
+ if (req.method !== 'GET') {
288
+ res.writeHead(405, { allow: 'GET' })
289
+ res.end()
290
+ return
291
+ }
292
+ let sessionId = ''
293
+ try {
294
+ const url = new URL(req.url || HANDOFF_PATH, 'http://localhost')
295
+ sessionId = url.searchParams.get('sessionId') || ''
296
+ } catch {
297
+ // 查询串异常时按空会话处理
298
+ }
299
+ const queue = sessionId ? pendingHandoffs.get(sessionId) || [] : []
300
+ if (sessionId && queue.length > 0) pendingHandoffs.delete(sessionId)
301
+ json(res, 200, { ok: true, sessionId, requests: queue })
302
+ },
303
+ }),
304
+ 'context-meter: handoff route',
305
+ )
306
+
307
+ webCtx.effect(
308
+ () =>
309
+ webCtx.webServer.register({
310
+ kind: 'exact',
311
+ path: CONTEXTS_PATH,
312
+ handler: (req, res) => {
313
+ if (req.method !== 'GET') {
314
+ res.writeHead(405, { allow: 'GET' })
315
+ res.end()
316
+ return
317
+ }
318
+ let ids = []
319
+ try {
320
+ const url = new URL(req.url || CONTEXTS_PATH, 'http://localhost')
321
+ ids = (url.searchParams.get('ids') || '')
322
+ .split(',')
323
+ .map((s) => s.trim())
324
+ .filter(Boolean)
325
+ .slice(0, 60)
326
+ } catch {
327
+ // 查询串异常时按空列表处理
328
+ }
329
+ json(res, 200, { ok: true, items: fetchSessionContexts(ids) })
330
+ },
331
+ }),
332
+ 'context-meter: contexts route',
333
+ )
334
+
335
+ webCtx.effect(
336
+ () =>
337
+ webCtx.webServer.register({
338
+ kind: 'exact',
339
+ path: DEBUG_PATH,
340
+ handler: async (req, res) => {
341
+ if (req.method !== 'POST') {
342
+ res.writeHead(405, { allow: 'POST' })
343
+ res.end()
344
+ return
345
+ }
346
+ let raw = ''
347
+ try {
348
+ const chunks = []
349
+ let size = 0
350
+ for await (const chunk of req) {
351
+ size += chunk.length
352
+ if (size > 128 * 1024) break
353
+ chunks.push(chunk)
354
+ }
355
+ raw = Buffer.concat(chunks).toString('utf8')
356
+ } catch {
357
+ raw = ''
358
+ }
359
+ try {
360
+ appendFileSync(DEBUG_FILE, '[' + new Date().toISOString() + '] ' + raw + '\n')
361
+ } catch {
362
+ // 写日志失败不影响主流程
363
+ }
364
+ json(res, 200, { ok: true })
365
+ },
366
+ }),
367
+ 'context-meter: debug route',
368
+ )
369
+
370
+ webCtx.effect(
371
+ () =>
372
+ webCtx.webServer.register({
373
+ kind: 'exact',
374
+ path: TINT_PATH,
375
+ handler: (req, res) => {
376
+ if (req.method !== 'GET') {
377
+ res.writeHead(405, { allow: 'GET' })
378
+ res.end()
379
+ return
380
+ }
381
+ json(res, 200, { ok: true, ...readTintConfig() })
382
+ },
383
+ }),
384
+ 'context-meter: tint route',
385
+ )
386
+
387
+ // 「标记停用」的读写口。GET 拿全量标记,POST 切换单个会话。
388
+ webCtx.effect(
389
+ () =>
390
+ webCtx.webServer.register({
391
+ kind: 'exact',
392
+ path: DISABLED_PATH,
393
+ handler: async (req, res) => {
394
+ if (req.method === 'GET') {
395
+ json(res, 200, { ok: true, ids: Object.keys(readDisabledIds()) })
396
+ return
397
+ }
398
+ if (req.method !== 'POST') {
399
+ res.writeHead(405, { allow: 'GET, POST' })
400
+ res.end()
401
+ return
402
+ }
403
+
404
+ let body = null
405
+ try {
406
+ const chunks = []
407
+ let size = 0
408
+ for await (const chunk of req) {
409
+ size += chunk.length
410
+ if (size > 16 * 1024) break
411
+ chunks.push(chunk)
412
+ }
413
+ body = JSON.parse(Buffer.concat(chunks).toString('utf8'))
414
+ } catch {
415
+ body = null
416
+ }
417
+
418
+ const id = body && normId(body.id)
419
+ if (!id) {
420
+ json(res, 400, { ok: false, error: '缺少有效的会话 id' })
421
+ return
422
+ }
423
+
424
+ const ids = readDisabledIds()
425
+ if (body.disabled) ids[id] = { at: Date.now(), by: 'user' }
426
+ else delete ids[id]
427
+ writeDisabledIds(ids)
428
+ json(res, 200, { ok: true, ids: Object.keys(ids) })
429
+ },
430
+ }),
431
+ 'context-meter: disabled route',
432
+ )
433
+ })
434
+ }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * 从 billion-context 的本地 HTTP 服务取会话统计。
3
+ *
4
+ * 端口:billion-context 默认从 18787 起绑定(ZONE_PORT_BASE),
5
+ * 若被占用会顺延,所以这里做一次小范围探测并缓存命中的端口。
6
+ */
7
+
8
+ const PORT_START = 18787
9
+ const PORT_COUNT = 10
10
+ const PROBE_TIMEOUT_MS = 1200
11
+ const PORT_CACHE_MS = 30_000
12
+ const DATA_CACHE_MS = 2_500
13
+
14
+ let cachedPort = 0
15
+ let portCheckedAt = 0
16
+ let dataCache = null
17
+ let dataAt = 0
18
+
19
+ async function probe(port) {
20
+ const controller = new AbortController()
21
+ const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS)
22
+ try {
23
+ const res = await fetch(`http://127.0.0.1:${port}/__bili/stats`, {
24
+ signal: controller.signal,
25
+ headers: { accept: 'application/json' },
26
+ })
27
+ if (!res.ok) return null
28
+ const body = await res.json()
29
+ if (!body || !Array.isArray(body.sessions)) return null
30
+ return body
31
+ } catch {
32
+ return null
33
+ } finally {
34
+ clearTimeout(timer)
35
+ }
36
+ }
37
+
38
+ /**
39
+ * @returns {Promise<{sessions: Array<Record<string, unknown>>} | null>}
40
+ */
41
+ export async function fetchBiliStats() {
42
+ const now = Date.now()
43
+ if (dataCache && now - dataAt < DATA_CACHE_MS) return dataCache
44
+
45
+ // 先试上次命中的端口
46
+ if (cachedPort && now - portCheckedAt < PORT_CACHE_MS) {
47
+ const hit = await probe(cachedPort)
48
+ if (hit) {
49
+ dataCache = hit
50
+ dataAt = now
51
+ return hit
52
+ }
53
+ }
54
+
55
+ for (let i = 0; i < PORT_COUNT; i += 1) {
56
+ const port = PORT_START + i
57
+ if (port === cachedPort && now - portCheckedAt < PORT_CACHE_MS) continue
58
+ const hit = await probe(port)
59
+ if (hit) {
60
+ cachedPort = port
61
+ portCheckedAt = now
62
+ dataCache = hit
63
+ dataAt = now
64
+ return hit
65
+ }
66
+ }
67
+
68
+ return null
69
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * 从 dsh-cost-meter 的本地账本取「按会话累计输入 token」。
3
+ *
4
+ * 为什么需要它:billion-context 的 /__bili/stats 只保留它见过的会话,
5
+ * 老对话(或本次进程没触发过请求的对话)查不到 → 进度条只能显示 --。
6
+ * cost-meter 的账本按天持久化,覆盖了历史会话,正好补这个缺口。
7
+ *
8
+ * 账本结构(实测):
9
+ * { days: { '2026-11-27': { input, cacheRead, calls, sessions: [
10
+ * { id, at, input, output, cacheRead, cacheWrite, calls, cost, title }
11
+ * ] } } }
12
+ *
13
+ * 口径:input 是未命中缓存的输入,cacheRead 是命中缓存的输入,
14
+ * 两者之和 ≈ 每轮 prompt_tokens 累加,即「累计计费输入 token」。
15
+ */
16
+
17
+ import { readFile, stat } from 'node:fs/promises'
18
+ import { homedir } from 'node:os'
19
+ import { join } from 'node:path'
20
+
21
+ const LEDGER_PATH = join(homedir(), '.dsh', 'storages', 'cost-meter', 'ledger.json')
22
+
23
+ /** 账本变更不频繁,缓存几秒即可,避免每次轮询都读 1MB JSON。 */
24
+ const CACHE_MS = 5_000
25
+
26
+ let cache = null
27
+ let cacheAt = 0
28
+ let cacheMtime = 0
29
+ let lastError = ''
30
+
31
+ /** 会话 id 归一化:去掉 session- 前缀,统一小写。 */
32
+ function normalizeId(id) {
33
+ if (typeof id !== 'string') return ''
34
+ const trimmed = id.trim().toLowerCase()
35
+ return trimmed.startsWith('session-') ? trimmed.slice('session-'.length) : trimmed
36
+ }
37
+
38
+ async function readLedger() {
39
+ const now = Date.now()
40
+ if (cache && now - cacheAt < CACHE_MS) return cache
41
+
42
+ try {
43
+ const info = await stat(LEDGER_PATH)
44
+ if (cache && info.mtimeMs === cacheMtime) {
45
+ cacheAt = now
46
+ return cache
47
+ }
48
+
49
+ const raw = await readFile(LEDGER_PATH, 'utf8')
50
+ const parsed = JSON.parse(raw)
51
+ const days = parsed && typeof parsed.days === 'object' ? parsed.days : null
52
+ if (!days) throw new Error('ledger 缺少 days 字段')
53
+
54
+ const byId = new Map()
55
+ for (const day of Object.values(days)) {
56
+ const rows = day && Array.isArray(day.sessions) ? day.sessions : []
57
+ for (const row of rows) {
58
+ const id = normalizeId(row && row.id)
59
+ if (!id) continue
60
+ const prev = byId.get(id) || {
61
+ id: row.id,
62
+ title: '',
63
+ input: 0,
64
+ cached: 0,
65
+ output: 0,
66
+ calls: 0,
67
+ lastSeen: 0,
68
+ }
69
+ prev.input += Number(row.input) || 0
70
+ prev.cached += Number(row.cacheRead) || 0
71
+ prev.output += Number(row.output) || 0
72
+ prev.calls += Number(row.calls) || 0
73
+ if (Number(row.at) > prev.lastSeen) prev.lastSeen = Number(row.at)
74
+ if (row.title) prev.title = String(row.title)
75
+ byId.set(id, prev)
76
+ }
77
+ }
78
+
79
+ cache = byId
80
+ cacheAt = now
81
+ cacheMtime = info.mtimeMs
82
+ lastError = ''
83
+ return cache
84
+ } catch (err) {
85
+ lastError = err && err.message ? String(err.message) : String(err)
86
+ return null
87
+ }
88
+ }
89
+
90
+ /**
91
+ * 查一个会话的累计用量。
92
+ * @param {string} sessionId 裸 uuid 或 session-<uuid>
93
+ * @returns {Promise<null | {id: string, title: string, requests: number, inputTokens: number,
94
+ * cachedTokens: number, outputTokens: number, contextTokens: number, contextWindow: number,
95
+ * blocks: number, cacheHitPct: number|null, lastModel: string, lastSeen: number|null,
96
+ * source: string}>}
97
+ */
98
+ export async function fetchLedgerSession(sessionId) {
99
+ const want = normalizeId(sessionId)
100
+ if (!want) return null
101
+ const byId = await readLedger()
102
+ if (!byId) return null
103
+ const row = byId.get(want)
104
+ if (!row) return null
105
+
106
+ const inputTokens = row.input + row.cached
107
+ return {
108
+ id: row.id,
109
+ title: row.title,
110
+ requests: row.calls,
111
+ inputTokens,
112
+ cachedTokens: row.cached,
113
+ outputTokens: row.output,
114
+ contextTokens: 0,
115
+ contextWindow: 0,
116
+ blocks: 0,
117
+ cacheHitPct: inputTokens > 0 ? (row.cached / inputTokens) * 100 : null,
118
+ lastModel: '',
119
+ lastSeen: row.lastSeen || null,
120
+ source: 'cost-meter-ledger',
121
+ }
122
+ }
123
+
124
+ /**
125
+ * 全量导出账本里的会话摘要(左侧栏着色要用所有会话,不只是当前一个)。
126
+ * @returns {Promise<Map<string, object>>} normalize 后的 id -> 摘要
127
+ */
128
+ export async function fetchAllLedgerSessions() {
129
+ const byId = await readLedger()
130
+ const out = new Map()
131
+ if (!byId) return out
132
+ for (const [id, row] of byId) {
133
+ const inputTokens = (Number(row.input) || 0) + (Number(row.cached) || 0)
134
+ out.set(id, {
135
+ id: row.id,
136
+ title: row.title || '',
137
+ requests: row.calls || 0,
138
+ inputTokens,
139
+ cachedTokens: row.cached || 0,
140
+ outputTokens: row.output || 0,
141
+ contextTokens: 0,
142
+ contextWindow: 0,
143
+ blocks: 0,
144
+ cacheHitPct: inputTokens > 0 ? ((row.cached || 0) / inputTokens) * 100 : null,
145
+ lastModel: '',
146
+ lastSeen: row.lastSeen || null,
147
+ source: 'cost-meter-ledger',
148
+ })
149
+ }
150
+ return out
151
+ }
152
+
153
+ /** 账本里一共有多少个会话(诊断用)。 */
154
+ export async function ledgerSessionCount() {
155
+ const byId = await readLedger()
156
+ return byId ? byId.size : 0
157
+ }
158
+
159
+ /** 最近一次读取失败的原因,便于在错误信息里带上。 */
160
+ export function ledgerLastError() {
161
+ return lastError
162
+ }