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
package/src/index.js
ADDED
|
@@ -0,0 +1,663 @@
|
|
|
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, findSessionFile } from './lib/session-context.js'
|
|
27
|
+
import { scanSessionUsage } from './lib/usage-backfill.js'
|
|
28
|
+
import { needsBackfill } from './lib/usage-migration.js'
|
|
29
|
+
import { createUsageStore, toInputTokens } from './lib/usage-store.js'
|
|
30
|
+
|
|
31
|
+
export const name = 'context-meter'
|
|
32
|
+
|
|
33
|
+
const ROUTE_PATH = '/context-meter/stats'
|
|
34
|
+
/** 全局 AGENTS 的真实路径,交给浏览器端拼交接引导词,避免在 client 里写死用户名。 */
|
|
35
|
+
const GLOBAL_AGENTS_FILE = join(homedir(), '.dsh', 'AGENTS.md')
|
|
36
|
+
const HANDOFF_PATH = '/context-meter/handoff'
|
|
37
|
+
/** 左侧栏着色用:批量返回多个会话的上下文占用率。 */
|
|
38
|
+
const CONTEXTS_PATH = '/context-meter/contexts'
|
|
39
|
+
/** 旧对话历史回填:POST 建任务,GET 查进度。 */
|
|
40
|
+
const BACKFILL_PATH = '/context-meter/backfill'
|
|
41
|
+
/** 浏览器端把 DOM 探测结果写到这里,方便在没有 devtools 时排查渲染问题。 */
|
|
42
|
+
const DEBUG_PATH = '/context-meter/debug'
|
|
43
|
+
const DEBUG_FILE = fileURLToPath(new URL('../debug.log', import.meta.url))
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 顶栏进度条与左侧栏着色共用的配置。
|
|
47
|
+
* 放在项目目录的 tint.json 里,改文件后 5 秒内浏览器端就会重新拉到,不需要重启 DSH。
|
|
48
|
+
* warn / danger 是百分比阈值,window 是累计计费输入的上限(token)。
|
|
49
|
+
* 默认值对应需求里的 60% / 80% 与 500M。
|
|
50
|
+
*/
|
|
51
|
+
const TINT_PATH = '/context-meter/tint'
|
|
52
|
+
const TINT_FILE = fileURLToPath(new URL('../tint.json', import.meta.url))
|
|
53
|
+
const TINT_DEFAULT = {
|
|
54
|
+
warn: 60,
|
|
55
|
+
danger: 80,
|
|
56
|
+
window: 500000000,
|
|
57
|
+
warnColor: '#e6a700',
|
|
58
|
+
dangerColor: '#e5534b',
|
|
59
|
+
}
|
|
60
|
+
const COLOR_RE = /^#[0-9a-f]{6}$/i
|
|
61
|
+
|
|
62
|
+
// 「标记停用」状态:只是给人看的标记,不碰会话内容。
|
|
63
|
+
// 存成项目目录下的 disabled.json,重启 DSH 也不丢;
|
|
64
|
+
// 放在 host 端是为了让 /handoff 命令也能顺手把原对话标记为停用。
|
|
65
|
+
const DISABLED_PATH = '/context-meter/disabled'
|
|
66
|
+
const DISABLED_FILE = fileURLToPath(new URL('../disabled.json', import.meta.url))
|
|
67
|
+
|
|
68
|
+
function readDisabledIds() {
|
|
69
|
+
try {
|
|
70
|
+
const raw = readFileSync(DISABLED_FILE, 'utf8')
|
|
71
|
+
const data = JSON.parse(raw)
|
|
72
|
+
if (!data || typeof data.ids !== 'object' || !data.ids) return {}
|
|
73
|
+
return data.ids
|
|
74
|
+
} catch {
|
|
75
|
+
return {}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function writeDisabledIds(ids) {
|
|
80
|
+
try {
|
|
81
|
+
writeFileSync(DISABLED_FILE, JSON.stringify({ ids }, null, 2) + '\n', 'utf8')
|
|
82
|
+
} catch {
|
|
83
|
+
// 写盘失败不影响内存里的路由结果
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function readTintConfig() {
|
|
88
|
+
try {
|
|
89
|
+
const raw = readFileSync(TINT_FILE, 'utf8')
|
|
90
|
+
const parsed = JSON.parse(raw)
|
|
91
|
+
const num = (value, fallback) => (Number.isFinite(Number(value)) ? Number(value) : fallback)
|
|
92
|
+
const pct = (value, fallback) => Math.min(100, Math.max(0, num(value, fallback)))
|
|
93
|
+
const color = (value, fallback) =>
|
|
94
|
+
typeof value === 'string' && COLOR_RE.test(value.trim()) ? value.trim().toLowerCase() : fallback
|
|
95
|
+
const warn = pct(parsed.warn, TINT_DEFAULT.warn)
|
|
96
|
+
const danger = pct(parsed.danger, TINT_DEFAULT.danger)
|
|
97
|
+
const validPct = warn < danger
|
|
98
|
+
const limit = num(parsed.window, TINT_DEFAULT.window)
|
|
99
|
+
return {
|
|
100
|
+
warn: validPct ? warn : TINT_DEFAULT.warn,
|
|
101
|
+
danger: validPct ? danger : TINT_DEFAULT.danger,
|
|
102
|
+
window: limit > 0 ? limit : TINT_DEFAULT.window,
|
|
103
|
+
warnColor: color(parsed.warnColor, TINT_DEFAULT.warnColor),
|
|
104
|
+
dangerColor: color(parsed.dangerColor, TINT_DEFAULT.dangerColor),
|
|
105
|
+
source: 'tint.json',
|
|
106
|
+
}
|
|
107
|
+
} catch {
|
|
108
|
+
return { ...TINT_DEFAULT, source: 'default' }
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 待浏览器端执行的交接请求:sessionId -> 请求数组(先进先出)。 */
|
|
113
|
+
const pendingHandoffs = new Map()
|
|
114
|
+
|
|
115
|
+
/** 统一会话 id:去掉 billion-context 的 session- 前缀并小写。 */
|
|
116
|
+
const normId = (id) => String(id || '').trim().toLowerCase().replace(/^session-/, '')
|
|
117
|
+
|
|
118
|
+
/** 只保留客户端需要的字段,避免把整个 stats 表传给页面。 */
|
|
119
|
+
function pickSession(entry) {
|
|
120
|
+
return {
|
|
121
|
+
id: entry.id,
|
|
122
|
+
title: entry.title || entry.label || '',
|
|
123
|
+
requests: entry.requests ?? 0,
|
|
124
|
+
inputTokens: entry.inputTokens ?? 0,
|
|
125
|
+
cachedTokens: entry.cachedTokens ?? 0,
|
|
126
|
+
outputTokens: entry.outputTokens ?? 0,
|
|
127
|
+
contextTokens: entry.contextTokens ?? 0,
|
|
128
|
+
contextWindow: entry.contextWindow ?? 0,
|
|
129
|
+
blocks: entry.blocks ?? 0,
|
|
130
|
+
cacheHitPct: entry.cacheHitPct ?? null,
|
|
131
|
+
lastModel: entry.lastModel || '',
|
|
132
|
+
lastSeen: entry.lastSeen ?? null,
|
|
133
|
+
source: entry.source || 'billion-context',
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* 合并三个来源:累计值取较大者(三者都只是下界),
|
|
139
|
+
* 实时信息优先用 billion-context;自采数据在两者都缺失时兜底。
|
|
140
|
+
*/
|
|
141
|
+
function mergeSession(ledger, bili, self, selfId) {
|
|
142
|
+
const base = bili || ledger
|
|
143
|
+
if (!base && !self) return null
|
|
144
|
+
const sources = []
|
|
145
|
+
if (self) sources.push('self')
|
|
146
|
+
if (ledger) sources.push('cost-meter-ledger')
|
|
147
|
+
if (bili) sources.push('billion-context')
|
|
148
|
+
const selfInput = self ? toInputTokens(self) : 0
|
|
149
|
+
const fallback = self
|
|
150
|
+
? {
|
|
151
|
+
id: selfId || '',
|
|
152
|
+
inputTokens: selfInput,
|
|
153
|
+
cachedTokens: Number(self.cacheRead) || 0,
|
|
154
|
+
outputTokens: Number(self.output) || 0,
|
|
155
|
+
requests: Number(self.requests) || 0,
|
|
156
|
+
}
|
|
157
|
+
: null
|
|
158
|
+
return {
|
|
159
|
+
...(base || fallback),
|
|
160
|
+
title: (base && base.title) || '',
|
|
161
|
+
requests: Math.max(
|
|
162
|
+
Number(ledger && ledger.requests) || 0,
|
|
163
|
+
Number(bili && bili.requests) || 0,
|
|
164
|
+
Number(self && self.requests) || 0,
|
|
165
|
+
),
|
|
166
|
+
inputTokens: Math.max(
|
|
167
|
+
Number(ledger && ledger.inputTokens) || 0,
|
|
168
|
+
Number(bili && bili.inputTokens) || 0,
|
|
169
|
+
selfInput,
|
|
170
|
+
),
|
|
171
|
+
cachedTokens: Math.max(
|
|
172
|
+
Number(ledger && ledger.cachedTokens) || 0,
|
|
173
|
+
Number(bili && bili.cachedTokens) || 0,
|
|
174
|
+
Number(self && self.cacheRead) || 0,
|
|
175
|
+
),
|
|
176
|
+
outputTokens: Math.max(
|
|
177
|
+
Number(ledger && ledger.outputTokens) || 0,
|
|
178
|
+
Number(bili && bili.outputTokens) || 0,
|
|
179
|
+
Number(self && self.output) || 0,
|
|
180
|
+
),
|
|
181
|
+
source: sources.join('+'),
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function json(res, status, body) {
|
|
186
|
+
const payload = JSON.stringify(body)
|
|
187
|
+
res.writeHead(status, {
|
|
188
|
+
'content-type': 'application/json; charset=utf-8',
|
|
189
|
+
'cache-control': 'no-store',
|
|
190
|
+
'content-length': Buffer.byteLength(payload),
|
|
191
|
+
})
|
|
192
|
+
res.end(payload)
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/** 读 JSON 请求体,上限 16KB;只给回填路由用。 */
|
|
196
|
+
function readJsonBody(req, limit = 16 * 1024) {
|
|
197
|
+
return new Promise((resolve, reject) => {
|
|
198
|
+
const chunks = []
|
|
199
|
+
let size = 0
|
|
200
|
+
req.on('data', (chunk) => {
|
|
201
|
+
size += chunk.length
|
|
202
|
+
if (size > limit) {
|
|
203
|
+
reject(new Error('BODY_TOO_LARGE'))
|
|
204
|
+
req.destroy()
|
|
205
|
+
return
|
|
206
|
+
}
|
|
207
|
+
chunks.push(chunk)
|
|
208
|
+
})
|
|
209
|
+
req.on('end', () => {
|
|
210
|
+
try {
|
|
211
|
+
const text = Buffer.concat(chunks).toString('utf8')
|
|
212
|
+
resolve(text ? JSON.parse(text) : {})
|
|
213
|
+
} catch {
|
|
214
|
+
reject(new Error('BAD_JSON'))
|
|
215
|
+
}
|
|
216
|
+
})
|
|
217
|
+
req.on('error', reject)
|
|
218
|
+
})
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function backfillErrorText(code) {
|
|
222
|
+
if (code === 'NO_SESSION_LOG') return '找不到该会话的日志文件'
|
|
223
|
+
if (code === 'TOO_LARGE') return '会话日志超过 200MB,暂不支持回填'
|
|
224
|
+
if (code === 'READ_FAILED') return '读取会话日志失败'
|
|
225
|
+
return '回填失败:' + (code || '未知错误')
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* 命令 handler:只登记请求并立刻返回。
|
|
230
|
+
* 真正的「让模型写文件 / 新建对话 / 改名」由浏览器端完成,
|
|
231
|
+
* 因为新建会话与改标题只有客户端服务能调。
|
|
232
|
+
*/
|
|
233
|
+
function enqueueHandoff(invocation, kind) {
|
|
234
|
+
const sessionId = String(invocation?.agent?.id || '')
|
|
235
|
+
if (!sessionId) {
|
|
236
|
+
return { kind: 'error', text: '拿不到当前会话 id,无法登记交接请求。' }
|
|
237
|
+
}
|
|
238
|
+
const queue = pendingHandoffs.get(sessionId) || []
|
|
239
|
+
queue.push({ kind, at: Date.now() })
|
|
240
|
+
pendingHandoffs.set(sessionId, queue)
|
|
241
|
+
|
|
242
|
+
// 交接之后原对话就「交出去了」,顺手标记为停用,方便在侧栏一眼认出来。
|
|
243
|
+
try {
|
|
244
|
+
const ids = readDisabledIds()
|
|
245
|
+
ids[normId(sessionId)] = { at: Date.now(), by: 'handoff' }
|
|
246
|
+
writeDisabledIds(ids)
|
|
247
|
+
} catch {
|
|
248
|
+
// 标记失败不影响交接本身
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return {
|
|
252
|
+
kind: 'success',
|
|
253
|
+
text:
|
|
254
|
+
kind === 'full'
|
|
255
|
+
? '已登记:生成交接文件 → 新建「原名 #N」对话 → 在新对话里读取 AGENTS 与交接文件。交接文件的完整路径会在写完后给出。'
|
|
256
|
+
: '已登记:生成本次对话的工作交接文件。写完后会给出完整路径。',
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function apply(ctx) {
|
|
261
|
+
// 自采用量:DSH 的 assistant/message 事件自带 usage,和 cost-meter 记账同源。
|
|
262
|
+
// 先 load 历史,再监听新事件;插件卸载时 flush 一次。
|
|
263
|
+
const usageStore = createUsageStore()
|
|
264
|
+
usageStore.load()
|
|
265
|
+
// 旧会话的 createdAt 用它判断;sessions 是可选的,拿不到就不提示回填。
|
|
266
|
+
const sessions = ctx.get('sessions')
|
|
267
|
+
const backfillJobs = new Map()
|
|
268
|
+
const BACKFILL_MAX_AGE_MS = 10 * 60 * 1000
|
|
269
|
+
|
|
270
|
+
function pruneBackfillJobs() {
|
|
271
|
+
const now = Date.now()
|
|
272
|
+
for (const [id, job] of backfillJobs) {
|
|
273
|
+
if (now - job.createdAt > BACKFILL_MAX_AGE_MS) backfillJobs.delete(id)
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function publicJob(job) {
|
|
278
|
+
return {
|
|
279
|
+
jobId: job.id,
|
|
280
|
+
sessionId: job.sessionId,
|
|
281
|
+
status: job.status,
|
|
282
|
+
progress: job.progress,
|
|
283
|
+
result: job.result,
|
|
284
|
+
error: job.error,
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
async function runBackfill(job) {
|
|
289
|
+
try {
|
|
290
|
+
const file = findSessionFile(job.sessionId)
|
|
291
|
+
if (!file) {
|
|
292
|
+
const error = new Error('NO_SESSION_LOG')
|
|
293
|
+
error.code = 'NO_SESSION_LOG'
|
|
294
|
+
throw error
|
|
295
|
+
}
|
|
296
|
+
const totals = await scanSessionUsage(file, {
|
|
297
|
+
onProgress: (ratio) => {
|
|
298
|
+
job.progress = Math.max(0, Math.min(1, ratio))
|
|
299
|
+
},
|
|
300
|
+
})
|
|
301
|
+
usageStore.setBaseline(job.sessionId, totals)
|
|
302
|
+
usageStore.flush()
|
|
303
|
+
job.status = 'done'
|
|
304
|
+
job.progress = 1
|
|
305
|
+
job.result = {
|
|
306
|
+
inputTokens: toInputTokens(totals),
|
|
307
|
+
totalTokens: totals.input + totals.cacheRead + totals.cacheWrite + totals.output,
|
|
308
|
+
requests: totals.requests,
|
|
309
|
+
}
|
|
310
|
+
} catch (error) {
|
|
311
|
+
job.status = 'error'
|
|
312
|
+
job.error = backfillErrorText(error && error.code)
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
ctx.effect(() => () => usageStore.dispose(), 'context-meter: usage store')
|
|
317
|
+
ctx.on('session/event', (session, event) => {
|
|
318
|
+
if (!event || event.type !== 'assistant/message') return
|
|
319
|
+
const usage = event.data && event.data.usage
|
|
320
|
+
if (!usage) return
|
|
321
|
+
usageStore.fold(session && session.id, usage)
|
|
322
|
+
})
|
|
323
|
+
|
|
324
|
+
ctx.inject(['commands'], (cmdCtx) => {
|
|
325
|
+
cmdCtx.effect(
|
|
326
|
+
() =>
|
|
327
|
+
cmdCtx.commands.register({
|
|
328
|
+
name: 'handoff',
|
|
329
|
+
description: '交接并新开对话:生成交接文件,新建「原名 #N」对话并在其中读取交接文件',
|
|
330
|
+
handler: (invocation) => enqueueHandoff(invocation, 'full'),
|
|
331
|
+
}),
|
|
332
|
+
'context-meter: handoff command',
|
|
333
|
+
)
|
|
334
|
+
cmdCtx.effect(
|
|
335
|
+
() =>
|
|
336
|
+
cmdCtx.commands.register({
|
|
337
|
+
name: 'handoff-file',
|
|
338
|
+
description: '只生成交接文件(不改动对话)',
|
|
339
|
+
handler: (invocation) => enqueueHandoff(invocation, 'file'),
|
|
340
|
+
}),
|
|
341
|
+
'context-meter: handoff-file command',
|
|
342
|
+
)
|
|
343
|
+
})
|
|
344
|
+
|
|
345
|
+
ctx.inject(['webServer'], (webCtx) => {
|
|
346
|
+
webCtx.effect(
|
|
347
|
+
() =>
|
|
348
|
+
webCtx.webServer.register({
|
|
349
|
+
kind: 'exact',
|
|
350
|
+
path: ROUTE_PATH,
|
|
351
|
+
handler: async (req, res) => {
|
|
352
|
+
if (req.method !== 'GET') {
|
|
353
|
+
res.writeHead(405, { allow: 'GET' })
|
|
354
|
+
res.end()
|
|
355
|
+
return
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
let wantId = ''
|
|
359
|
+
try {
|
|
360
|
+
const url = new URL(req.url || ROUTE_PATH, 'http://localhost')
|
|
361
|
+
wantId = url.searchParams.get('sessionId') || ''
|
|
362
|
+
} catch {
|
|
363
|
+
// 查询串异常时按「返回全部摘要」处理
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
const [ledger, stats] = await Promise.all([
|
|
367
|
+
wantId ? fetchLedgerSession(wantId).catch(() => null) : Promise.resolve(null),
|
|
368
|
+
fetchBiliStats().catch(() => null),
|
|
369
|
+
])
|
|
370
|
+
|
|
371
|
+
const all =
|
|
372
|
+
stats && Array.isArray(stats.sessions) ? stats.sessions.map(pickSession) : []
|
|
373
|
+
// billion-context 的会话 id 形如 session-<uuid>,两端都接受
|
|
374
|
+
const biliMatch = wantId
|
|
375
|
+
? all.find((s) => s.id === wantId || s.id === 'session-' + wantId) || null
|
|
376
|
+
: null
|
|
377
|
+
const self = wantId
|
|
378
|
+
? usageStore.getByAny([wantId, ledger && ledger.id, biliMatch && biliMatch.id])
|
|
379
|
+
: null
|
|
380
|
+
|
|
381
|
+
// 不带 sessionId(左侧栏要全量)时,把账本与自采里所有会话也并进来,
|
|
382
|
+
// 否则老对话/新对话在 billion-context 里查不到,侧栏永远是 0%。
|
|
383
|
+
let visible = all
|
|
384
|
+
if (!wantId) {
|
|
385
|
+
const ledgerAll = await fetchAllLedgerSessions().catch(() => new Map())
|
|
386
|
+
const merged = new Map()
|
|
387
|
+
for (const item of all) merged.set(normId(item.id), item)
|
|
388
|
+
for (const [id, entry] of ledgerAll) {
|
|
389
|
+
merged.set(id, mergeSession(entry, merged.get(id) || null, usageStore.getByAny([id])))
|
|
390
|
+
}
|
|
391
|
+
// 只在自采里出现、billion-context 与账本都没有的会话(例如没装 cost-meter)
|
|
392
|
+
for (const [id, entry] of Object.entries(usageStore.snapshot().sessions)) {
|
|
393
|
+
const key = normId(id)
|
|
394
|
+
if (merged.has(key)) continue
|
|
395
|
+
merged.set(key, mergeSession(null, null, entry, id))
|
|
396
|
+
}
|
|
397
|
+
visible = [...merged.values()]
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const session = mergeSession(ledger, biliMatch, self, wantId)
|
|
401
|
+
const bareId = String(wantId).replace(/^session-/, '')
|
|
402
|
+
const live =
|
|
403
|
+
sessions && typeof sessions.get === 'function'
|
|
404
|
+
? sessions.get(wantId) || sessions.get(bareId) || sessions.get('session-' + bareId)
|
|
405
|
+
: null
|
|
406
|
+
const sessionCreatedAt =
|
|
407
|
+
live && live.header ? Number(live.header.createdAt) || 0 : 0
|
|
408
|
+
const migration = wantId
|
|
409
|
+
? needsBackfill({
|
|
410
|
+
self,
|
|
411
|
+
ledger,
|
|
412
|
+
bili: biliMatch,
|
|
413
|
+
sessionCreatedAt,
|
|
414
|
+
startedAt: usageStore.startedAt(),
|
|
415
|
+
})
|
|
416
|
+
: { needed: false }
|
|
417
|
+
const biliUp = Boolean(stats && Array.isArray(stats.sessions))
|
|
418
|
+
const ledgerReadable = !ledgerLastError()
|
|
419
|
+
const selfReadable = usageStore.size() > 0
|
|
420
|
+
const available = biliUp || ledgerReadable || selfReadable
|
|
421
|
+
|
|
422
|
+
if (!session) {
|
|
423
|
+
json(res, 200, {
|
|
424
|
+
ok: available,
|
|
425
|
+
error: available ? null : '统计来源不可用(billion-context 未运行,cost-meter 账本不可读,自采无数据)',
|
|
426
|
+
sessions: visible,
|
|
427
|
+
session: null,
|
|
428
|
+
migration,
|
|
429
|
+
paths: { globalAgents: GLOBAL_AGENTS_FILE },
|
|
430
|
+
sources: biliUp ? ['billion-context'] : [],
|
|
431
|
+
ledgerError: ledgerLastError() || null,
|
|
432
|
+
fetchedAt: Date.now(),
|
|
433
|
+
})
|
|
434
|
+
return
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
json(res, 200, {
|
|
438
|
+
ok: true,
|
|
439
|
+
sessions: visible,
|
|
440
|
+
session,
|
|
441
|
+
migration,
|
|
442
|
+
paths: { globalAgents: GLOBAL_AGENTS_FILE },
|
|
443
|
+
sources: session.source ? session.source.split('+') : [],
|
|
444
|
+
ledgerError: ledgerLastError() || null,
|
|
445
|
+
fetchedAt: Date.now(),
|
|
446
|
+
})
|
|
447
|
+
},
|
|
448
|
+
}),
|
|
449
|
+
'context-meter: stats route',
|
|
450
|
+
)
|
|
451
|
+
|
|
452
|
+
webCtx.effect(
|
|
453
|
+
() =>
|
|
454
|
+
webCtx.webServer.register({
|
|
455
|
+
kind: 'exact',
|
|
456
|
+
path: BACKFILL_PATH,
|
|
457
|
+
handler: async (req, res) => {
|
|
458
|
+
pruneBackfillJobs()
|
|
459
|
+
if (req.method === 'POST') {
|
|
460
|
+
let body
|
|
461
|
+
try {
|
|
462
|
+
body = await readJsonBody(req)
|
|
463
|
+
} catch (error) {
|
|
464
|
+
json(res, 400, { ok: false, error: error.message })
|
|
465
|
+
return
|
|
466
|
+
}
|
|
467
|
+
const sessionId = String((body && body.sessionId) || '').trim()
|
|
468
|
+
if (!sessionId) {
|
|
469
|
+
json(res, 400, { ok: false, error: '缺少 sessionId' })
|
|
470
|
+
return
|
|
471
|
+
}
|
|
472
|
+
for (const job of backfillJobs.values()) {
|
|
473
|
+
if (job.sessionId === sessionId && job.status === 'running') {
|
|
474
|
+
json(res, 200, { ok: true, ...publicJob(job) })
|
|
475
|
+
return
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
const job = {
|
|
479
|
+
id: 'bf_' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8),
|
|
480
|
+
sessionId,
|
|
481
|
+
status: 'running',
|
|
482
|
+
progress: 0,
|
|
483
|
+
createdAt: Date.now(),
|
|
484
|
+
result: null,
|
|
485
|
+
error: null,
|
|
486
|
+
}
|
|
487
|
+
backfillJobs.set(job.id, job)
|
|
488
|
+
runBackfill(job)
|
|
489
|
+
json(res, 200, { ok: true, ...publicJob(job) })
|
|
490
|
+
return
|
|
491
|
+
}
|
|
492
|
+
if (req.method !== 'GET') {
|
|
493
|
+
res.writeHead(405, { allow: 'GET, POST' })
|
|
494
|
+
res.end()
|
|
495
|
+
return
|
|
496
|
+
}
|
|
497
|
+
const url = new URL(req.url || BACKFILL_PATH, 'http://localhost')
|
|
498
|
+
const jobId = url.searchParams.get('jobId') || ''
|
|
499
|
+
const job = backfillJobs.get(jobId)
|
|
500
|
+
if (!job) {
|
|
501
|
+
json(res, 404, { ok: false, error: 'job 不存在或已过期' })
|
|
502
|
+
return
|
|
503
|
+
}
|
|
504
|
+
json(res, 200, { ok: true, ...publicJob(job) })
|
|
505
|
+
},
|
|
506
|
+
}),
|
|
507
|
+
'context-meter: backfill route',
|
|
508
|
+
)
|
|
509
|
+
|
|
510
|
+
webCtx.effect(
|
|
511
|
+
() =>
|
|
512
|
+
webCtx.webServer.register({
|
|
513
|
+
kind: 'exact',
|
|
514
|
+
path: HANDOFF_PATH,
|
|
515
|
+
handler: (req, res) => {
|
|
516
|
+
if (req.method !== 'GET') {
|
|
517
|
+
res.writeHead(405, { allow: 'GET' })
|
|
518
|
+
res.end()
|
|
519
|
+
return
|
|
520
|
+
}
|
|
521
|
+
let sessionId = ''
|
|
522
|
+
try {
|
|
523
|
+
const url = new URL(req.url || HANDOFF_PATH, 'http://localhost')
|
|
524
|
+
sessionId = url.searchParams.get('sessionId') || ''
|
|
525
|
+
} catch {
|
|
526
|
+
// 查询串异常时按空会话处理
|
|
527
|
+
}
|
|
528
|
+
const queue = sessionId ? pendingHandoffs.get(sessionId) || [] : []
|
|
529
|
+
if (sessionId && queue.length > 0) pendingHandoffs.delete(sessionId)
|
|
530
|
+
json(res, 200, { ok: true, sessionId, requests: queue })
|
|
531
|
+
},
|
|
532
|
+
}),
|
|
533
|
+
'context-meter: handoff route',
|
|
534
|
+
)
|
|
535
|
+
|
|
536
|
+
webCtx.effect(
|
|
537
|
+
() =>
|
|
538
|
+
webCtx.webServer.register({
|
|
539
|
+
kind: 'exact',
|
|
540
|
+
path: CONTEXTS_PATH,
|
|
541
|
+
handler: (req, res) => {
|
|
542
|
+
if (req.method !== 'GET') {
|
|
543
|
+
res.writeHead(405, { allow: 'GET' })
|
|
544
|
+
res.end()
|
|
545
|
+
return
|
|
546
|
+
}
|
|
547
|
+
let ids = []
|
|
548
|
+
try {
|
|
549
|
+
const url = new URL(req.url || CONTEXTS_PATH, 'http://localhost')
|
|
550
|
+
ids = (url.searchParams.get('ids') || '')
|
|
551
|
+
.split(',')
|
|
552
|
+
.map((s) => s.trim())
|
|
553
|
+
.filter(Boolean)
|
|
554
|
+
.slice(0, 60)
|
|
555
|
+
} catch {
|
|
556
|
+
// 查询串异常时按空列表处理
|
|
557
|
+
}
|
|
558
|
+
json(res, 200, { ok: true, items: fetchSessionContexts(ids) })
|
|
559
|
+
},
|
|
560
|
+
}),
|
|
561
|
+
'context-meter: contexts route',
|
|
562
|
+
)
|
|
563
|
+
|
|
564
|
+
webCtx.effect(
|
|
565
|
+
() =>
|
|
566
|
+
webCtx.webServer.register({
|
|
567
|
+
kind: 'exact',
|
|
568
|
+
path: DEBUG_PATH,
|
|
569
|
+
handler: async (req, res) => {
|
|
570
|
+
if (req.method !== 'POST') {
|
|
571
|
+
res.writeHead(405, { allow: 'POST' })
|
|
572
|
+
res.end()
|
|
573
|
+
return
|
|
574
|
+
}
|
|
575
|
+
let raw = ''
|
|
576
|
+
try {
|
|
577
|
+
const chunks = []
|
|
578
|
+
let size = 0
|
|
579
|
+
for await (const chunk of req) {
|
|
580
|
+
size += chunk.length
|
|
581
|
+
if (size > 128 * 1024) break
|
|
582
|
+
chunks.push(chunk)
|
|
583
|
+
}
|
|
584
|
+
raw = Buffer.concat(chunks).toString('utf8')
|
|
585
|
+
} catch {
|
|
586
|
+
raw = ''
|
|
587
|
+
}
|
|
588
|
+
try {
|
|
589
|
+
appendFileSync(DEBUG_FILE, '[' + new Date().toISOString() + '] ' + raw + '\n')
|
|
590
|
+
} catch {
|
|
591
|
+
// 写日志失败不影响主流程
|
|
592
|
+
}
|
|
593
|
+
json(res, 200, { ok: true })
|
|
594
|
+
},
|
|
595
|
+
}),
|
|
596
|
+
'context-meter: debug route',
|
|
597
|
+
)
|
|
598
|
+
|
|
599
|
+
webCtx.effect(
|
|
600
|
+
() =>
|
|
601
|
+
webCtx.webServer.register({
|
|
602
|
+
kind: 'exact',
|
|
603
|
+
path: TINT_PATH,
|
|
604
|
+
handler: (req, res) => {
|
|
605
|
+
if (req.method !== 'GET') {
|
|
606
|
+
res.writeHead(405, { allow: 'GET' })
|
|
607
|
+
res.end()
|
|
608
|
+
return
|
|
609
|
+
}
|
|
610
|
+
json(res, 200, { ok: true, ...readTintConfig() })
|
|
611
|
+
},
|
|
612
|
+
}),
|
|
613
|
+
'context-meter: tint route',
|
|
614
|
+
)
|
|
615
|
+
|
|
616
|
+
// 「标记停用」的读写口。GET 拿全量标记,POST 切换单个会话。
|
|
617
|
+
webCtx.effect(
|
|
618
|
+
() =>
|
|
619
|
+
webCtx.webServer.register({
|
|
620
|
+
kind: 'exact',
|
|
621
|
+
path: DISABLED_PATH,
|
|
622
|
+
handler: async (req, res) => {
|
|
623
|
+
if (req.method === 'GET') {
|
|
624
|
+
json(res, 200, { ok: true, ids: Object.keys(readDisabledIds()) })
|
|
625
|
+
return
|
|
626
|
+
}
|
|
627
|
+
if (req.method !== 'POST') {
|
|
628
|
+
res.writeHead(405, { allow: 'GET, POST' })
|
|
629
|
+
res.end()
|
|
630
|
+
return
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
let body = null
|
|
634
|
+
try {
|
|
635
|
+
const chunks = []
|
|
636
|
+
let size = 0
|
|
637
|
+
for await (const chunk of req) {
|
|
638
|
+
size += chunk.length
|
|
639
|
+
if (size > 16 * 1024) break
|
|
640
|
+
chunks.push(chunk)
|
|
641
|
+
}
|
|
642
|
+
body = JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
643
|
+
} catch {
|
|
644
|
+
body = null
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
const id = body && normId(body.id)
|
|
648
|
+
if (!id) {
|
|
649
|
+
json(res, 400, { ok: false, error: '缺少有效的会话 id' })
|
|
650
|
+
return
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
const ids = readDisabledIds()
|
|
654
|
+
if (body.disabled) ids[id] = { at: Date.now(), by: 'user' }
|
|
655
|
+
else delete ids[id]
|
|
656
|
+
writeDisabledIds(ids)
|
|
657
|
+
json(res, 200, { ok: true, ids: Object.keys(ids) })
|
|
658
|
+
},
|
|
659
|
+
}),
|
|
660
|
+
'context-meter: disabled route',
|
|
661
|
+
)
|
|
662
|
+
})
|
|
663
|
+
}
|