dsh-usage-bar 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +150 -2
- package/Versions/Alpha Release/A-v0.1.0.md +45 -0
- package/Versions/Alpha Release/A-v0.1.1.md +45 -0
- package/Versions/Alpha Release/A-v0.1.3.md +51 -0
- package/Versions/Alpha Release/A-v0.1.4.md +35 -0
- package/Versions/Alpha Release/A-v0.1.5.md +42 -0
- package/Versions/Alpha Release/A-v0.1.6.md +46 -0
- package/Versions/Alpha Release/A-v0.1.7.md +39 -0
- package/Versions/Alpha Release/A-v0.1.8.md +37 -0
- package/Versions/Beta Release/B-v0.2.0.md +50 -0
- package/Versions/Official Release/R-v0.1.0.md +38 -0
- package/Versions/README.md +49 -0
- package/Versions/_template.md +40 -0
- package/cordis.patch.yml +4 -0
- package/docs/DETAIL.md +250 -0
- package/docs/Development.md +98 -0
- package/docs/assets/backfill.png +0 -0
- package/docs/assets/handoff.png +0 -0
- package/docs/assets/hero.png +0 -0
- package/docs/assets/logo.svg +4 -0
- package/docs/assets/sidebar.png +0 -0
- package/docs/readme/README_zh.md +229 -0
- package/docs/releases/B-v0.2.0.md +86 -0
- package/docs/releases/_template.md +51 -0
- package/icon.svg +4 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +60 -4
- package/src/client.js +1529 -0
- package/src/index.js +663 -0
- package/src/lib/bili-stats.js +69 -0
- package/src/lib/ledger-stats.js +162 -0
- package/src/lib/session-context.js +185 -0
- package/src/lib/usage-backfill.js +81 -0
- package/src/lib/usage-migration.js +19 -0
- package/src/lib/usage-store.js +232 -0
- package/tint.example.json +7 -0
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
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
|
+
/**
|
|
87
|
+
* 逐个 magic 位置解压,返回每帧的压缩字节范围与文本行。
|
|
88
|
+
* 容忍被尾部边界截断的帧;坏帧跳过,不影响其他帧。
|
|
89
|
+
*/
|
|
90
|
+
export function decodeFrames(buffer) {
|
|
91
|
+
const frames = []
|
|
92
|
+
let at = buffer.indexOf(MAGIC)
|
|
93
|
+
while (at >= 0) {
|
|
94
|
+
const next = buffer.indexOf(MAGIC, at + 4)
|
|
95
|
+
const end = next >= 0 ? next : buffer.length
|
|
96
|
+
try {
|
|
97
|
+
const text = zstdDecompressSync(buffer.subarray(at, end)).toString('utf8')
|
|
98
|
+
const lines = text.split('\n').filter((line) => line.trim())
|
|
99
|
+
frames.push({ at, bytes: end - at, lines })
|
|
100
|
+
} catch {
|
|
101
|
+
// 帧不完整,跳过
|
|
102
|
+
}
|
|
103
|
+
at = next
|
|
104
|
+
}
|
|
105
|
+
return frames
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function decodeLines(buffer) {
|
|
109
|
+
const lines = []
|
|
110
|
+
for (const frame of decodeFrames(buffer)) lines.push(...frame.lines)
|
|
111
|
+
return lines
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function readUsage(file) {
|
|
115
|
+
let usage = null
|
|
116
|
+
for (const line of decodeLines(readTail(file))) {
|
|
117
|
+
let event
|
|
118
|
+
try {
|
|
119
|
+
event = JSON.parse(line)
|
|
120
|
+
} catch {
|
|
121
|
+
continue
|
|
122
|
+
}
|
|
123
|
+
if (event.type === 'assistant/message' && event.data && event.data.usage) usage = event.data.usage
|
|
124
|
+
}
|
|
125
|
+
if (!usage) return null
|
|
126
|
+
const used =
|
|
127
|
+
(Number(usage.inputTokens) || 0) +
|
|
128
|
+
(Number(usage.cacheReadTokens) || 0) +
|
|
129
|
+
(Number(usage.cacheWriteTokens) || 0)
|
|
130
|
+
if (used <= 0) return null
|
|
131
|
+
return {
|
|
132
|
+
used,
|
|
133
|
+
window: DEFAULT_WINDOW,
|
|
134
|
+
pct: (used / DEFAULT_WINDOW) * 100,
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** 按会话 id 找会话日志文件;找不到返回 null。 */
|
|
139
|
+
export function findSessionFile(sessionId) {
|
|
140
|
+
const key = normalizeId(sessionId)
|
|
141
|
+
if (!key) return null
|
|
142
|
+
return sessionIndex().get(key) || null
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 单个会话的上下文占用。
|
|
147
|
+
* @returns {{used:number, window:number, pct:number}|null}
|
|
148
|
+
*/
|
|
149
|
+
export function fetchSessionContext(sessionId) {
|
|
150
|
+
const key = normalizeId(sessionId)
|
|
151
|
+
if (!key) return null
|
|
152
|
+
const cached = resultCache.get(key)
|
|
153
|
+
if (cached && Date.now() - cached.at < RESULT_TTL_MS) return cached.value
|
|
154
|
+
const file = sessionIndex().get(key)
|
|
155
|
+
if (!file) return null
|
|
156
|
+
let value = null
|
|
157
|
+
try {
|
|
158
|
+
value = readUsage(file)
|
|
159
|
+
} catch {
|
|
160
|
+
value = null
|
|
161
|
+
}
|
|
162
|
+
resultCache.set(key, { at: Date.now(), value })
|
|
163
|
+
return value
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* 批量取多个会话的上下文占用,只返回能算出来的项。
|
|
168
|
+
* @returns {Record<string, {used:number, window:number, pct:number}>}
|
|
169
|
+
*/
|
|
170
|
+
export function fetchSessionContexts(sessionIds) {
|
|
171
|
+
const out = {}
|
|
172
|
+
const seen = new Set()
|
|
173
|
+
for (const raw of sessionIds || []) {
|
|
174
|
+
const key = normalizeId(raw)
|
|
175
|
+
if (!key || seen.has(key)) continue
|
|
176
|
+
seen.add(key)
|
|
177
|
+
const value = fetchSessionContext(key)
|
|
178
|
+
if (value) out[key] = value
|
|
179
|
+
}
|
|
180
|
+
return out
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function sessionContextIndexSize() {
|
|
184
|
+
return sessionIndex().size
|
|
185
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 按需回填:扫描整个会话日志,累加所有 assistant/message 的 usage。
|
|
3
|
+
*
|
|
4
|
+
* 会话文件是 zstd 帧拼接的 JSONL;这里整份读入后复用 session-context 的
|
|
5
|
+
* decodeFrames 逐帧解压。文件一般几 MB,超过 200MB 直接拒绝,避免把
|
|
6
|
+
* host 线程和内存拖垮。
|
|
7
|
+
*/
|
|
8
|
+
import { readFile, stat } from 'node:fs/promises'
|
|
9
|
+
import { decodeFrames } from './session-context.js'
|
|
10
|
+
|
|
11
|
+
const MAX_BYTES = 200 * 1024 * 1024
|
|
12
|
+
|
|
13
|
+
function fail(code) {
|
|
14
|
+
const error = new Error(code)
|
|
15
|
+
error.code = code
|
|
16
|
+
return error
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function finite(value) {
|
|
20
|
+
const num = Number(value)
|
|
21
|
+
return Number.isFinite(num) && num > 0 ? num : 0
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* @param {string} file 会话日志绝对路径
|
|
26
|
+
* @param {{onProgress?: (ratio:number)=>void}} [options]
|
|
27
|
+
* @returns {Promise<{input:number, cacheRead:number, cacheWrite:number, output:number,
|
|
28
|
+
* requests:number, bytes:number, frames:number}>}
|
|
29
|
+
*/
|
|
30
|
+
export async function scanSessionUsage(file, options = {}) {
|
|
31
|
+
if (!file) throw fail('NO_SESSION_LOG')
|
|
32
|
+
let info
|
|
33
|
+
try {
|
|
34
|
+
info = await stat(file)
|
|
35
|
+
} catch {
|
|
36
|
+
throw fail('NO_SESSION_LOG')
|
|
37
|
+
}
|
|
38
|
+
if (!info.isFile()) throw fail('NO_SESSION_LOG')
|
|
39
|
+
if (info.size > MAX_BYTES) throw fail('TOO_LARGE')
|
|
40
|
+
|
|
41
|
+
let buffer
|
|
42
|
+
try {
|
|
43
|
+
buffer = await readFile(file)
|
|
44
|
+
} catch {
|
|
45
|
+
throw fail('READ_FAILED')
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const totals = { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, requests: 0 }
|
|
49
|
+
const frames = decodeFrames(buffer)
|
|
50
|
+
const totalBytes = buffer.length || 1
|
|
51
|
+
let doneBytes = 0
|
|
52
|
+
|
|
53
|
+
for (const frame of frames) {
|
|
54
|
+
doneBytes += frame.bytes
|
|
55
|
+
for (const line of frame.lines) {
|
|
56
|
+
let event
|
|
57
|
+
try {
|
|
58
|
+
event = JSON.parse(line)
|
|
59
|
+
} catch {
|
|
60
|
+
continue
|
|
61
|
+
}
|
|
62
|
+
if (!event || event.type !== 'assistant/message') continue
|
|
63
|
+
const usage = event.data && event.data.usage
|
|
64
|
+
if (!usage) continue
|
|
65
|
+
totals.input += finite(usage.inputTokens)
|
|
66
|
+
totals.cacheRead += finite(usage.cacheReadTokens)
|
|
67
|
+
totals.cacheWrite += finite(usage.cacheWriteTokens)
|
|
68
|
+
totals.output += finite(usage.outputTokens)
|
|
69
|
+
totals.requests += 1
|
|
70
|
+
}
|
|
71
|
+
if (typeof options.onProgress === 'function') {
|
|
72
|
+
options.onProgress(Math.min(doneBytes / totalBytes, 1))
|
|
73
|
+
}
|
|
74
|
+
await new Promise((resolve) => setImmediate(resolve))
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
if (typeof options.onProgress === 'function') options.onProgress(1)
|
|
78
|
+
return { ...totals, bytes: buffer.length, frames: frames.length }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export { MAX_BYTES }
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 旧对话回填判定。
|
|
3
|
+
*
|
|
4
|
+
* 自采只从插件首次运行后开始累加;插件安装前就存在的对话,自采里没有历史。
|
|
5
|
+
* 只有在「自采是唯一来源、且该对话创建时间早于插件首次运行」时才提示回填,
|
|
6
|
+
* 避免把 cost-meter 账本或 billion-context 已经提供的准确数字误标成「仅新增」。
|
|
7
|
+
*/
|
|
8
|
+
export function needsBackfill({ self, ledger, bili, sessionCreatedAt, startedAt }) {
|
|
9
|
+
if (!self || self.historyApplied) return { needed: false }
|
|
10
|
+
if (ledger || bili) return { needed: false }
|
|
11
|
+
|
|
12
|
+
const created = Number(sessionCreatedAt)
|
|
13
|
+
const started = Number(startedAt)
|
|
14
|
+
if (!Number.isFinite(created) || created <= 0) return { needed: false }
|
|
15
|
+
if (!Number.isFinite(started) || started <= 0) return { needed: false }
|
|
16
|
+
if (created >= started) return { needed: false }
|
|
17
|
+
|
|
18
|
+
return { needed: true, reason: 'legacy-session', startedAt: started, sessionCreatedAt: created }
|
|
19
|
+
}
|