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.
@@ -0,0 +1,168 @@
1
+ /**
2
+ * 从 DSH 的会话文件里读「当前上下文长度」。
3
+ *
4
+ * 每个会话落盘为 <home>/.dsh/sessions/<workspace>/<id>/session.v4.jsonl.zstd,
5
+ * 内容是 zstd 帧拼接的 JSONL 事件流。其中:
6
+ * - assistant/message 事件带 data.usage = {inputTokens, cacheReadTokens, cacheWriteTokens, ...}
7
+ * → 三项之和就是该轮请求的 prompt token 数,也就是当时的上下文长度;
8
+ * - request/context 事件带 contextWindow(只在会话开头写一次,尾部通常读不到)。
9
+ *
10
+ * 所以取「最后一个 usage」当上下文长度,窗口大小用默认 1048576
11
+ * (DSH 对 deepseek-flash 写死的值,与 billion-context 报的一致)。
12
+ *
13
+ * 只读文件尾部 64KB 并逐个 zstd 帧解压,避免整份文件(最大十几 MB)解压。
14
+ */
15
+ import { closeSync, openSync, readSync, readdirSync, statSync } from 'node:fs'
16
+ import { homedir } from 'node:os'
17
+ import { join } from 'node:path'
18
+ import { zstdDecompressSync } from 'node:zlib'
19
+
20
+ const SESSIONS_ROOT = join(homedir(), '.dsh', 'sessions')
21
+ const TAIL_BYTES = 64 * 1024
22
+ const DEFAULT_WINDOW = 1048576
23
+ const INDEX_TTL_MS = 60_000
24
+ const RESULT_TTL_MS = 30_000
25
+ const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
26
+
27
+ /** normalize 后的会话 id -> 会话文件绝对路径。 */
28
+ let indexCache = { at: 0, map: new Map() }
29
+ /** normalize 后的会话 id -> {at, value}。 */
30
+ const resultCache = new Map()
31
+
32
+ function normalizeId(id) {
33
+ return String(id || '')
34
+ .trim()
35
+ .toLowerCase()
36
+ .replace(/^session-/, '')
37
+ }
38
+
39
+ function buildIndex() {
40
+ const map = new Map()
41
+ let workspaces = []
42
+ try {
43
+ workspaces = readdirSync(SESSIONS_ROOT, { withFileTypes: true })
44
+ .filter((entry) => entry.isDirectory())
45
+ .map((entry) => entry.name)
46
+ } catch {
47
+ return map
48
+ }
49
+ for (const workspace of workspaces) {
50
+ const workspacePath = join(SESSIONS_ROOT, workspace)
51
+ let sessions = []
52
+ try {
53
+ sessions = readdirSync(workspacePath, { withFileTypes: true }).filter((entry) => entry.isDirectory())
54
+ } catch {
55
+ continue
56
+ }
57
+ for (const session of sessions) {
58
+ const key = normalizeId(session.name)
59
+ if (!key) continue
60
+ map.set(key, join(workspacePath, session.name, 'session.v4.jsonl.zstd'))
61
+ }
62
+ }
63
+ return map
64
+ }
65
+
66
+ function sessionIndex() {
67
+ if (Date.now() - indexCache.at < INDEX_TTL_MS) return indexCache.map
68
+ indexCache = { at: Date.now(), map: buildIndex() }
69
+ return indexCache.map
70
+ }
71
+
72
+ function readTail(file) {
73
+ const size = statSync(file).size
74
+ const start = Math.max(0, size - TAIL_BYTES)
75
+ const length = size - start
76
+ const buffer = Buffer.alloc(length)
77
+ const fd = openSync(file, 'r')
78
+ try {
79
+ readSync(fd, buffer, 0, length, start)
80
+ } finally {
81
+ closeSync(fd)
82
+ }
83
+ return buffer
84
+ }
85
+
86
+ /** 逐个 magic 位置解压,容忍被尾部边界截断的帧。 */
87
+ function decodeLines(buffer) {
88
+ const lines = []
89
+ let at = buffer.indexOf(MAGIC)
90
+ while (at >= 0) {
91
+ try {
92
+ const text = zstdDecompressSync(buffer.subarray(at)).toString('utf8')
93
+ for (const line of text.split('\n')) {
94
+ if (line.trim()) lines.push(line)
95
+ }
96
+ } catch {
97
+ // 帧不完整,跳过
98
+ }
99
+ at = buffer.indexOf(MAGIC, at + 4)
100
+ }
101
+ return lines
102
+ }
103
+
104
+ function readUsage(file) {
105
+ let usage = null
106
+ for (const line of decodeLines(readTail(file))) {
107
+ let event
108
+ try {
109
+ event = JSON.parse(line)
110
+ } catch {
111
+ continue
112
+ }
113
+ if (event.type === 'assistant/message' && event.data && event.data.usage) usage = event.data.usage
114
+ }
115
+ if (!usage) return null
116
+ const used =
117
+ (Number(usage.inputTokens) || 0) +
118
+ (Number(usage.cacheReadTokens) || 0) +
119
+ (Number(usage.cacheWriteTokens) || 0)
120
+ if (used <= 0) return null
121
+ return {
122
+ used,
123
+ window: DEFAULT_WINDOW,
124
+ pct: (used / DEFAULT_WINDOW) * 100,
125
+ }
126
+ }
127
+
128
+ /**
129
+ * 单个会话的上下文占用。
130
+ * @returns {{used:number, window:number, pct:number}|null}
131
+ */
132
+ export function fetchSessionContext(sessionId) {
133
+ const key = normalizeId(sessionId)
134
+ if (!key) return null
135
+ const cached = resultCache.get(key)
136
+ if (cached && Date.now() - cached.at < RESULT_TTL_MS) return cached.value
137
+ const file = sessionIndex().get(key)
138
+ if (!file) return null
139
+ let value = null
140
+ try {
141
+ value = readUsage(file)
142
+ } catch {
143
+ value = null
144
+ }
145
+ resultCache.set(key, { at: Date.now(), value })
146
+ return value
147
+ }
148
+
149
+ /**
150
+ * 批量取多个会话的上下文占用,只返回能算出来的项。
151
+ * @returns {Record<string, {used:number, window:number, pct:number}>}
152
+ */
153
+ export function fetchSessionContexts(sessionIds) {
154
+ const out = {}
155
+ const seen = new Set()
156
+ for (const raw of sessionIds || []) {
157
+ const key = normalizeId(raw)
158
+ if (!key || seen.has(key)) continue
159
+ seen.add(key)
160
+ const value = fetchSessionContext(key)
161
+ if (value) out[key] = value
162
+ }
163
+ return out
164
+ }
165
+
166
+ export function sessionContextIndexSize() {
167
+ return sessionIndex().size
168
+ }
@@ -0,0 +1,5 @@
1
+ {
2
+ "warn": 60,
3
+ "danger": 80,
4
+ "window": 500000000
5
+ }