@mcviseron/dsh-qq-bridge 0.2.0 → 0.3.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/bot/usage.mjs ADDED
@@ -0,0 +1,175 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Token accounting for DSH Sessions.
4
+ *
5
+ * node usage.mjs <sessionId> one Session
6
+ * node usage.mjs --all the most recent Sessions (newest 20)
7
+ *
8
+ * DSH stores each Session as multi-frame zstd (one frame per appended batch);
9
+ * Node's zstdDecompressSync stops after the first frame, so the buffer is split
10
+ * on the frame magic and decompressed batch by batch. Usage numbers live on
11
+ * every assistant/message event, the title on session/title.
12
+ */
13
+ import { readFileSync, readdirSync, statSync } from 'node:fs'
14
+ import { homedir } from 'node:os'
15
+ import { join } from 'node:path'
16
+ import { zstdDecompressSync } from 'node:zlib'
17
+
18
+ const MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
19
+ const FILE = 'session.v4.jsonl.zstd'
20
+
21
+ /** Every zstd frame in one buffer, decoded in order. */
22
+ function decodeFrames(buffer) {
23
+ const offsets = []
24
+ let cursor = 0
25
+ while (cursor < buffer.length - 4) {
26
+ const at = buffer.indexOf(MAGIC, cursor)
27
+ if (at < 0) break
28
+ offsets.push(at)
29
+ cursor = at + 4
30
+ }
31
+ const parts = []
32
+ for (let index = 0; index < offsets.length; index += 1) {
33
+ const start = offsets[index]
34
+ for (let next = index + 1; next <= offsets.length; next += 1) {
35
+ const end = next < offsets.length ? offsets[next] : buffer.length
36
+ try {
37
+ parts.push(zstdDecompressSync(buffer.subarray(start, end)))
38
+ index = next - 1
39
+ break
40
+ } catch {
41
+ // Frame boundary sat inside the payload; extend to the next magic.
42
+ }
43
+ }
44
+ }
45
+ return Buffer.concat(parts).toString('utf8')
46
+ }
47
+
48
+ /** DSH home: DSH_HOME, else ~/.dsh. */
49
+ function dshHome() {
50
+ return process.env.DSH_HOME && process.env.DSH_HOME !== '' ? process.env.DSH_HOME : join(homedir(), '.dsh')
51
+ }
52
+
53
+ /** Aggregate usage fields over every assistant message of one Session log. */
54
+ function sumUsage(text) {
55
+ const totals = {
56
+ messages: 0,
57
+ inputTokens: 0,
58
+ outputTokens: 0,
59
+ cacheReadTokens: 0,
60
+ cacheWriteTokens: 0,
61
+ totalTokens: 0,
62
+ firstAt: null,
63
+ lastAt: null,
64
+ }
65
+ const models = new Set()
66
+ let title = ''
67
+ for (const line of text.split('\n')) {
68
+ if (line.trim() === '') continue
69
+ let event
70
+ try {
71
+ event = JSON.parse(line)
72
+ } catch {
73
+ continue
74
+ }
75
+ if (event.type === 'session/title' && typeof event.data?.title === 'string') title = event.data.title
76
+ if (event.type !== 'assistant/message' || event.data === null || typeof event.data !== 'object') continue
77
+ const usage = event.data.usage
78
+ if (usage === null || typeof usage !== 'object') continue
79
+ totals.messages += 1
80
+ totals.inputTokens += Number(usage.inputTokens) || 0
81
+ totals.outputTokens += Number(usage.outputTokens) || 0
82
+ totals.cacheReadTokens += Number(usage.cacheReadTokens) || 0
83
+ totals.cacheWriteTokens += Number(usage.cacheWriteTokens) || 0
84
+ totals.totalTokens += Number(usage.totalTokens) || 0
85
+ if (totals.firstAt === null) totals.firstAt = event.time
86
+ totals.lastAt = event.time
87
+ const model = event.data.message?.source?.model
88
+ if (typeof model === 'string' && model !== '') models.add(model)
89
+ }
90
+ return { ...totals, title, models: [...models] }
91
+ }
92
+
93
+ /** Absolute path of one Session's event log, or undefined. */
94
+ function findSessionFile(sessionId) {
95
+ const root = join(dshHome(), 'sessions')
96
+ let groups = []
97
+ try {
98
+ groups = readdirSync(root)
99
+ } catch {
100
+ return undefined
101
+ }
102
+ for (const group of groups) {
103
+ const candidate = join(root, group, sessionId, FILE)
104
+ try {
105
+ statSync(candidate)
106
+ return candidate
107
+ } catch {
108
+ // Next workspace group.
109
+ }
110
+ }
111
+ return undefined
112
+ }
113
+
114
+ /** The most recently written Session logs, newest first. */
115
+ function recentSessionFiles(limit) {
116
+ const root = join(dshHome(), 'sessions')
117
+ const found = []
118
+ let groups = []
119
+ try {
120
+ groups = readdirSync(root)
121
+ } catch {
122
+ return found
123
+ }
124
+ for (const group of groups) {
125
+ let ids = []
126
+ try {
127
+ ids = readdirSync(join(root, group))
128
+ } catch {
129
+ continue
130
+ }
131
+ for (const id of ids) {
132
+ const path = join(root, group, id, FILE)
133
+ try {
134
+ found.push({ sessionId: id, path, mtimeMs: statSync(path).mtimeMs })
135
+ } catch {
136
+ // Not a Session directory.
137
+ }
138
+ }
139
+ }
140
+ found.sort((left, right) => right.mtimeMs - left.mtimeMs)
141
+ return found.slice(0, limit)
142
+ }
143
+
144
+ function emit(value) {
145
+ console.log(JSON.stringify(value))
146
+ }
147
+
148
+ const argument = process.argv[2] ?? ''
149
+
150
+ if (argument === '--all') {
151
+ const sessions = []
152
+ for (const entry of recentSessionFiles(20)) {
153
+ try {
154
+ const totals = sumUsage(decodeFrames(readFileSync(entry.path)))
155
+ if (totals.messages === 0) continue
156
+ sessions.push({ sessionId: entry.sessionId, ...totals })
157
+ } catch {
158
+ // A corrupt log must not hide the other Sessions.
159
+ }
160
+ }
161
+ emit({ ok: true, sessions })
162
+ } else if (argument === '') {
163
+ emit({ ok: false, error: 'session id required' })
164
+ } else {
165
+ const file = findSessionFile(argument)
166
+ if (file === undefined) {
167
+ emit({ ok: false, error: 'session log not found' })
168
+ } else {
169
+ try {
170
+ emit({ ok: true, sessionId: argument, file, ...sumUsage(decodeFrames(readFileSync(file))) })
171
+ } catch (error) {
172
+ emit({ ok: false, error: error instanceof Error ? error.message : String(error) })
173
+ }
174
+ }
175
+ }