dsh-injection-manager 1.10.4 → 2.0.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/CHANGELOG.md +267 -0
- package/CONTRIBUTING.md +2 -2
- package/README.md +282 -94
- package/README.zh.md +236 -97
- package/client.js +3325 -295
- package/docs/ARCHITECTURE.md +111 -24
- package/docs/COMPATIBILITY.md +28 -7
- package/docs/DETAIL.md +148 -0
- package/docs/DETAIL.zh.md +105 -1
- package/docs/FAQ.md +49 -7
- package/docs/PERFORMANCE.md +60 -6
- package/docs/images/demo.gif +0 -0
- package/docs/images/dock.png +0 -0
- package/docs/images/panel-dark.png +0 -0
- package/docs/images/panel-drawer.png +0 -0
- package/docs/images/panel-insights.png +0 -0
- package/docs/images/panel-manage-expanded.png +0 -0
- package/docs/images/panel-manage.png +0 -0
- package/docs/images/panel-settings.png +0 -0
- package/docs/images/panel-sidebar.png +0 -0
- package/docs/preview.svg +177 -23
- package/icon.svg +19 -5
- package/index.js +100 -14
- package/lib/actions.js +12 -4
- package/lib/apply.js +14 -2
- package/lib/compaction.js +126 -0
- package/lib/content.js +360 -0
- package/lib/events.js +216 -0
- package/lib/health.js +210 -0
- package/lib/pressure.js +146 -0
- package/lib/routes.js +293 -9
- package/lib/snapshot.js +256 -29
- package/lib/stats.js +394 -0
- package/lib/text.js +160 -0
- package/lib/trend.js +168 -0
- package/locale/de.json +251 -6
- package/locale/en.json +251 -6
- package/locale/es.json +251 -6
- package/locale/fr.json +251 -6
- package/locale/ja.json +251 -6
- package/locale/pt.json +251 -6
- package/locale/ru.json +252 -7
- package/locale/zh.json +249 -4
- package/package.json +16 -3
- package/screenshots.json +7 -5
- package/docs/images/panel-about.png +0 -0
- package/docs/images/panel-budget.png +0 -0
- package/docs/images/panel-policy.png +0 -0
- package/docs/images/panel-suites.png +0 -0
package/lib/stats.js
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
// History: one row per conversation this plugin has measured.
|
|
2
|
+
//
|
|
3
|
+
// The question the 统计 tab answers is "how much have my conversations been
|
|
4
|
+
// carrying, over time, and where did it go" — and the only source that can
|
|
5
|
+
// answer it without replaying every durable log is what the plugin already
|
|
6
|
+
// measured. So every snapshot that reaches the panel, the tool or the command
|
|
7
|
+
// updates a small per-session record here; the file is capped and written
|
|
8
|
+
// atomically, and the tab states its own coverage instead of implying it saw
|
|
9
|
+
// every conversation.
|
|
10
|
+
//
|
|
11
|
+
// Deliberately not done: replaying `sessionQuery.readSession()` for every
|
|
12
|
+
// session. That loads and validates complete logs (megabytes each), which is
|
|
13
|
+
// too expensive to run on a panel refresh.
|
|
14
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
15
|
+
import { dirname, join } from 'node:path'
|
|
16
|
+
import { resolveDshHome } from './policy.js'
|
|
17
|
+
|
|
18
|
+
const FILE_NAME = 'stats.json'
|
|
19
|
+
const VERSION = 1
|
|
20
|
+
const LIMIT = 400
|
|
21
|
+
|
|
22
|
+
export const statsFilePath = () => join(resolveDshHome(), 'injection-manager', FILE_NAME)
|
|
23
|
+
|
|
24
|
+
let cache = null
|
|
25
|
+
let writing = null
|
|
26
|
+
let dirty = false
|
|
27
|
+
|
|
28
|
+
function blank() {
|
|
29
|
+
return { version: VERSION, sessions: {} }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function load() {
|
|
33
|
+
if (cache !== null) return cache
|
|
34
|
+
try {
|
|
35
|
+
const parsed = JSON.parse(await readFile(statsFilePath(), 'utf8'))
|
|
36
|
+
cache = parsed !== null && typeof parsed === 'object' && parsed.sessions !== null && typeof parsed.sessions === 'object' ? parsed : blank()
|
|
37
|
+
} catch {
|
|
38
|
+
cache = blank()
|
|
39
|
+
}
|
|
40
|
+
return cache
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Keep the newest LIMIT sessions, then write the file once per burst. */
|
|
44
|
+
async function flush() {
|
|
45
|
+
if (writing !== null) {
|
|
46
|
+
dirty = true
|
|
47
|
+
return writing
|
|
48
|
+
}
|
|
49
|
+
writing = (async () => {
|
|
50
|
+
try {
|
|
51
|
+
do {
|
|
52
|
+
dirty = false
|
|
53
|
+
const state = cache ?? blank()
|
|
54
|
+
const entries = Object.entries(state.sessions)
|
|
55
|
+
if (entries.length > LIMIT) {
|
|
56
|
+
entries.sort((left, right) => (right[1].at ?? 0) - (left[1].at ?? 0))
|
|
57
|
+
state.sessions = Object.fromEntries(entries.slice(0, LIMIT))
|
|
58
|
+
}
|
|
59
|
+
const body = JSON.stringify({ version: VERSION, sessions: state.sessions })
|
|
60
|
+
const target = statsFilePath()
|
|
61
|
+
await mkdir(dirname(target), { recursive: true })
|
|
62
|
+
const temp = `${target}.tmp-${process.pid}`
|
|
63
|
+
await writeFile(temp, body, 'utf8')
|
|
64
|
+
await rename(temp, target)
|
|
65
|
+
} while (dirty)
|
|
66
|
+
} catch {
|
|
67
|
+
/* history is a nicety; a failed write must never break a snapshot */
|
|
68
|
+
} finally {
|
|
69
|
+
writing = null
|
|
70
|
+
}
|
|
71
|
+
})()
|
|
72
|
+
return writing
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Fold one measured snapshot into the history. Called on every snapshot build,
|
|
77
|
+
* so it must stay allocation-light and never throw.
|
|
78
|
+
*/
|
|
79
|
+
export function recordSnapshot(snapshot) {
|
|
80
|
+
const id = snapshot?.agent?.id
|
|
81
|
+
if (typeof id !== 'string' || id.length === 0) return
|
|
82
|
+
const state = cache ?? (cache = blank())
|
|
83
|
+
const skills = snapshot.skillsState ?? {}
|
|
84
|
+
const tools = snapshot.toolsState ?? {}
|
|
85
|
+
const context = snapshot.context ?? {}
|
|
86
|
+
const previous = state.sessions[id]
|
|
87
|
+
const allOn = Number(snapshot.totals?.tokens) || 0
|
|
88
|
+
const effective = Number(snapshot.effective?.totals?.tokens) || 0
|
|
89
|
+
|
|
90
|
+
// Per-channel split: only snapshots built after v2.0 carry it. Old rows keep
|
|
91
|
+
// whatever they had (nothing) — the trend renders that as unknown, not zero.
|
|
92
|
+
const channelTokens = {}
|
|
93
|
+
let channelKnown = false
|
|
94
|
+
for (const channel of Array.isArray(snapshot.channels) ? snapshot.channels : []) {
|
|
95
|
+
if (channel === null || typeof channel !== 'object' || typeof channel.id !== 'string') continue
|
|
96
|
+
if (!Number.isFinite(Number(channel.tokens))) continue
|
|
97
|
+
channelTokens[channel.id] = Number(channel.tokens)
|
|
98
|
+
channelKnown = true
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const compaction = context.compaction ?? {}
|
|
102
|
+
state.sessions[id] = {
|
|
103
|
+
id,
|
|
104
|
+
at: Date.now(),
|
|
105
|
+
firstAt: previous?.firstAt ?? Date.now(),
|
|
106
|
+
cwd: typeof snapshot.cwd === 'string' ? snapshot.cwd : '',
|
|
107
|
+
scope: typeof snapshot.agent?.scopeSource === 'string' ? snapshot.agent.scopeSource : '',
|
|
108
|
+
allOn,
|
|
109
|
+
effective,
|
|
110
|
+
peak: Math.max(previous?.peak ?? 0, allOn),
|
|
111
|
+
samples: (previous?.samples ?? 0) + 1,
|
|
112
|
+
skills: Number(skills.catalogTokens) || 0,
|
|
113
|
+
skillCount: Number(skills.total) || 0,
|
|
114
|
+
tools: Number(tools.count) || 0,
|
|
115
|
+
toolsTokens: (snapshot.channels ?? []).find((channel) => channel.id === 'tools')?.tokens ?? 0,
|
|
116
|
+
window: Number(context.window) || null,
|
|
117
|
+
used: Number(context.used) || null,
|
|
118
|
+
occupancy: Number.isFinite(context.occupancy) ? context.occupancy : null,
|
|
119
|
+
saved: Math.max(0, allOn - effective),
|
|
120
|
+
policy: typeof snapshot.policy?.preset === 'string' ? snapshot.policy.preset : 'all',
|
|
121
|
+
...(channelKnown ? { channels: channelTokens } : {}),
|
|
122
|
+
compactions: {
|
|
123
|
+
count: Math.max(0, (Number(compaction.count) || 0) + (Number(compaction.prunes) || 0)),
|
|
124
|
+
freed: Math.max(0, Number(compaction.saved) || 0),
|
|
125
|
+
},
|
|
126
|
+
}
|
|
127
|
+
void flush()
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Every recorded session, newest first, plus the aggregates the tab prints. */
|
|
131
|
+
export async function readStats() {
|
|
132
|
+
const state = await load()
|
|
133
|
+
const rows = Object.values(state.sessions).sort((left, right) => (right.at ?? 0) - (left.at ?? 0))
|
|
134
|
+
const total = rows.length
|
|
135
|
+
const sum = (pick) => rows.reduce((acc, row) => acc + (pick(row) || 0), 0)
|
|
136
|
+
const average = (pick) => (total === 0 ? 0 : Math.round(sum(pick) / total))
|
|
137
|
+
|
|
138
|
+
// One bucket per local day, so "上周比这周贵" is answerable at a glance.
|
|
139
|
+
const days = new Map()
|
|
140
|
+
for (const row of rows) {
|
|
141
|
+
const day = new Date(row.at).toLocaleDateString('en-CA')
|
|
142
|
+
const bucket = days.get(day) ?? { day, sessions: 0, allOn: 0, skills: 0, peak: 0 }
|
|
143
|
+
bucket.sessions += 1
|
|
144
|
+
bucket.allOn += row.allOn || 0
|
|
145
|
+
bucket.skills += row.skills || 0
|
|
146
|
+
bucket.peak = Math.max(bucket.peak, row.peak || 0)
|
|
147
|
+
days.set(day, bucket)
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return {
|
|
151
|
+
rows,
|
|
152
|
+
coverage: { recorded: total },
|
|
153
|
+
aggregate: {
|
|
154
|
+
sessions: total,
|
|
155
|
+
avgAllOn: average((row) => row.allOn),
|
|
156
|
+
avgEffective: average((row) => row.effective),
|
|
157
|
+
avgSkills: average((row) => row.skills),
|
|
158
|
+
totalSaved: sum((row) => row.saved),
|
|
159
|
+
peakAllOn: rows.reduce((max, row) => Math.max(max, row.peak || 0), 0),
|
|
160
|
+
heaviest: rows.slice().sort((left, right) => (right.peak || 0) - (left.peak || 0))[0] ?? null,
|
|
161
|
+
maxSkill: rows.slice().sort((left, right) => (right.skills || 0) - (left.skills || 0))[0] ?? null,
|
|
162
|
+
},
|
|
163
|
+
days: [...days.values()].sort((left, right) => left.day.localeCompare(right.day)).slice(-30),
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Test hook: forget the in-memory cache (the file stays as written). */
|
|
168
|
+
export function resetStatsCache() {
|
|
169
|
+
cache = null
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Test/teardown hook: wait for a queued atomic write to land. */
|
|
173
|
+
export function flushStats() {
|
|
174
|
+
return flush()
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Read one durable log and price what it was carrying.
|
|
179
|
+
*
|
|
180
|
+
* The durable shapes (probed against a real 18 MB log):
|
|
181
|
+
* request/header → data.header = { config, adapterDefaults, tools }
|
|
182
|
+
* system/message → data.message = { role, content, source, id }
|
|
183
|
+
*
|
|
184
|
+
* `sessionQuery.readSession()` replays and validates the complete log, so this
|
|
185
|
+
* is the expensive path and it is never run on a plain `/stats` read: the route
|
|
186
|
+
* calls it for a few unmeasured sessions per request under a wall-clock budget,
|
|
187
|
+
* and the result is cached in stats.json under `from_log`.
|
|
188
|
+
*/
|
|
189
|
+
async function priceSession(sessionQuery, id) {
|
|
190
|
+
const loaded = await sessionQuery.readSession(id)
|
|
191
|
+
const events = Array.isArray(loaded?.events) ? loaded.events : Array.isArray(loaded) ? loaded : []
|
|
192
|
+
if (events.length === 0) return null
|
|
193
|
+
|
|
194
|
+
let tools = []
|
|
195
|
+
let system = ''
|
|
196
|
+
for (const event of events) {
|
|
197
|
+
if (event === null || typeof event !== 'object') continue
|
|
198
|
+
if (event.type === 'request/header') {
|
|
199
|
+
const header = event.data?.header ?? event.data ?? {}
|
|
200
|
+
if (Array.isArray(header.tools)) tools = header.tools
|
|
201
|
+
} else if (event.type === 'system/message') {
|
|
202
|
+
const content = event.data?.message?.content ?? event.data?.content
|
|
203
|
+
if (Array.isArray(content)) {
|
|
204
|
+
const text = content.map((block) => (typeof block?.text === 'string' ? block.text : '')).join('')
|
|
205
|
+
if (text.length > 0) system = text
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
let toolChars = 0
|
|
211
|
+
for (const tool of tools) {
|
|
212
|
+
try {
|
|
213
|
+
toolChars += JSON.stringify(tool ?? {}).length
|
|
214
|
+
} catch {
|
|
215
|
+
/* a schema that cannot be serialised simply contributes nothing */
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
const toolTokens = Math.round(toolChars / 4)
|
|
219
|
+
const systemTokens = Math.round(system.length / 4)
|
|
220
|
+
return {
|
|
221
|
+
tools: tools.length,
|
|
222
|
+
toolsTokens: toolTokens,
|
|
223
|
+
systemTokens,
|
|
224
|
+
peak: toolTokens + systemTokens,
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* Backfill a bounded number of unmeasured sessions from their durable logs.
|
|
230
|
+
* Ids arrive newest-first, so the most recent conversations fill in first.
|
|
231
|
+
* A row this plugin already has is never re-priced: measured rows carry the
|
|
232
|
+
* per-channel split a log replay cannot recover, and a log-priced row is final.
|
|
233
|
+
*/
|
|
234
|
+
export async function backfillStats(sessionQuery, ids, { limit = 3, budgetMs = 4000 } = {}) {
|
|
235
|
+
const state = await load()
|
|
236
|
+
const started = Date.now()
|
|
237
|
+
let added = 0
|
|
238
|
+
for (const id of ids) {
|
|
239
|
+
if (added >= limit || Date.now() - started > budgetMs) break
|
|
240
|
+
const existing = state.sessions[id]
|
|
241
|
+
if (existing !== undefined) continue
|
|
242
|
+
try {
|
|
243
|
+
const priced = await priceSession(sessionQuery, id)
|
|
244
|
+
if (priced === null) continue
|
|
245
|
+
state.sessions[id] = {
|
|
246
|
+
...(existing ?? {}),
|
|
247
|
+
id,
|
|
248
|
+
at: existing?.at ?? Date.now(),
|
|
249
|
+
firstAt: existing?.firstAt ?? Date.now(),
|
|
250
|
+
cwd: existing?.cwd ?? '',
|
|
251
|
+
scope: 'backfill',
|
|
252
|
+
allOn: priced.peak,
|
|
253
|
+
effective: priced.peak,
|
|
254
|
+
peak: priced.peak,
|
|
255
|
+
samples: existing?.samples ?? 0,
|
|
256
|
+
skills: 0,
|
|
257
|
+
skillCount: 0,
|
|
258
|
+
tools: priced.tools,
|
|
259
|
+
toolsTokens: priced.toolsTokens,
|
|
260
|
+
systemTokens: priced.systemTokens,
|
|
261
|
+
window: existing?.window ?? null,
|
|
262
|
+
used: existing?.used ?? null,
|
|
263
|
+
occupancy: existing?.occupancy ?? null,
|
|
264
|
+
saved: 0,
|
|
265
|
+
policy: existing?.policy ?? 'unknown',
|
|
266
|
+
fromLog: true,
|
|
267
|
+
}
|
|
268
|
+
added += 1
|
|
269
|
+
} catch {
|
|
270
|
+
/* one unreadable log must not stop the batch */
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
if (added > 0) await flush()
|
|
274
|
+
const remaining = Object.values(state.sessions).filter((row) => row.fromLog !== true).length
|
|
275
|
+
return { added, remaining }
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// ---------------------------------------------------------------- background backfill
|
|
279
|
+
//
|
|
280
|
+
// A read route must not wait for durable-log replay: at ~671 unmeasured
|
|
281
|
+
// sessions a single 6s backfill pass made /trend take 7s per poll. The read
|
|
282
|
+
// path therefore answers from stats.json immediately and asks for one bounded
|
|
283
|
+
// pass in the background. Single-flight (one pass per process), 60s cooldown,
|
|
284
|
+
// ≤8 logs / 6s per pass, failures silent — the next poll retries naturally.
|
|
285
|
+
const BACKFILL_COOLDOWN_MS = 60_000
|
|
286
|
+
const BACKFILL_BATCH = 8
|
|
287
|
+
const BACKFILL_BUDGET_MS = 6000
|
|
288
|
+
// The corpus index is only used to order the fill and to report `known`; a few
|
|
289
|
+
// thousand entries is cheap to keep in memory.
|
|
290
|
+
const SESSION_INDEX_LIMIT = 4000
|
|
291
|
+
const SESSION_INDEX_TTL_MS = 60_000
|
|
292
|
+
|
|
293
|
+
let sessionIndex = { at: 0, known: null, sessions: [] }
|
|
294
|
+
let backfillRun = null
|
|
295
|
+
let backfillLastAt = 0
|
|
296
|
+
let backfillLastResult = null
|
|
297
|
+
let backfillLastError = null
|
|
298
|
+
|
|
299
|
+
/** Test hook: forget the index, the cooldown and any completed pass. */
|
|
300
|
+
export function resetBackfillState() {
|
|
301
|
+
sessionIndex = { at: 0, known: null, sessions: [] }
|
|
302
|
+
backfillRun = null
|
|
303
|
+
backfillLastAt = 0
|
|
304
|
+
backfillLastResult = null
|
|
305
|
+
backfillLastError = null
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* What the route should report about the background fill:
|
|
310
|
+
* `running` is true while a pass is in flight, `last` is the latest completed
|
|
311
|
+
* pass, `known` is the corpus size (null until the index has been listed once).
|
|
312
|
+
*/
|
|
313
|
+
export function backfillState() {
|
|
314
|
+
return {
|
|
315
|
+
running: backfillRun !== null,
|
|
316
|
+
lastAt: backfillLastAt,
|
|
317
|
+
indexAt: sessionIndex.at,
|
|
318
|
+
known: sessionIndex.known,
|
|
319
|
+
sessions: sessionIndex.sessions,
|
|
320
|
+
last: backfillLastResult,
|
|
321
|
+
error: backfillLastError,
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function sessionQueryOf(ctx) {
|
|
326
|
+
try {
|
|
327
|
+
return typeof ctx?.get === 'function' ? ctx.get('sessionQuery') : undefined
|
|
328
|
+
} catch {
|
|
329
|
+
return undefined
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
async function refreshSessionIndex(sessionQuery) {
|
|
334
|
+
if (sessionQuery === undefined || sessionQuery === null || typeof sessionQuery.listSessions !== 'function') return sessionIndex
|
|
335
|
+
try {
|
|
336
|
+
const listed = await sessionQuery.listSessions()
|
|
337
|
+
if (!Array.isArray(listed)) return sessionIndex
|
|
338
|
+
const sessions = listed
|
|
339
|
+
.map((entry) => {
|
|
340
|
+
const header = entry?.header ?? entry ?? {}
|
|
341
|
+
return {
|
|
342
|
+
id: typeof header.id === 'string' ? header.id : '',
|
|
343
|
+
at: Number(header.createdAt) || 0,
|
|
344
|
+
cwd: typeof header.cwd === 'string' ? header.cwd : '',
|
|
345
|
+
live: entry?.live === true,
|
|
346
|
+
subagent: typeof header.parentSession === 'string' && header.parentSession.length > 0,
|
|
347
|
+
}
|
|
348
|
+
})
|
|
349
|
+
.filter((entry) => entry.id.length > 0)
|
|
350
|
+
.sort((left, right) => right.at - left.at)
|
|
351
|
+
sessionIndex = { at: Date.now(), known: listed.length, sessions: sessions.slice(0, SESSION_INDEX_LIMIT) }
|
|
352
|
+
} catch {
|
|
353
|
+
/* an unreadable session index leaves `known` unknown */
|
|
354
|
+
}
|
|
355
|
+
return sessionIndex
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Fire-and-forget: start one bounded backfill pass if allowed.
|
|
360
|
+
* Returns immediately; never throws and never awaits log replay. The internal
|
|
361
|
+
* promise is exposed only through `whenBackfillIdle()` for tests.
|
|
362
|
+
*/
|
|
363
|
+
export function requestBackfill(ctx) {
|
|
364
|
+
if (backfillRun !== null) return { started: false, running: true }
|
|
365
|
+
if (Date.now() - backfillLastAt < BACKFILL_COOLDOWN_MS) return { started: false, running: false }
|
|
366
|
+
const sessionQuery = sessionQueryOf(ctx)
|
|
367
|
+
if (sessionQuery === undefined || sessionQuery === null || typeof sessionQuery.readSession !== 'function') {
|
|
368
|
+
return { started: false, running: false }
|
|
369
|
+
}
|
|
370
|
+
backfillLastAt = Date.now()
|
|
371
|
+
backfillRun = (async () => {
|
|
372
|
+
try {
|
|
373
|
+
const fresh = sessionIndex.known !== null && Date.now() - sessionIndex.at < SESSION_INDEX_TTL_MS
|
|
374
|
+
const index = fresh ? sessionIndex : await refreshSessionIndex(sessionQuery)
|
|
375
|
+
const ids = index.sessions.map((entry) => entry.id)
|
|
376
|
+
const result =
|
|
377
|
+
ids.length === 0
|
|
378
|
+
? { added: 0, remaining: Object.values((await load()).sessions).filter((row) => row.fromLog !== true).length }
|
|
379
|
+
: await backfillStats(sessionQuery, ids, { limit: BACKFILL_BATCH, budgetMs: BACKFILL_BUDGET_MS })
|
|
380
|
+
backfillLastResult = { at: Date.now(), added: result.added, remaining: result.remaining, known: index.known }
|
|
381
|
+
backfillLastError = null
|
|
382
|
+
} catch (error) {
|
|
383
|
+
backfillLastError = String(error?.message ?? error)
|
|
384
|
+
} finally {
|
|
385
|
+
backfillRun = null
|
|
386
|
+
}
|
|
387
|
+
})()
|
|
388
|
+
return { started: true, running: true }
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** Test hook: await an in-flight pass (including its session-index refresh). */
|
|
392
|
+
export function whenBackfillIdle() {
|
|
393
|
+
return backfillRun ?? Promise.resolve()
|
|
394
|
+
}
|
package/lib/text.js
CHANGED
|
@@ -21,6 +21,55 @@ const statusText = (status) => {
|
|
|
21
21
|
return '加载'
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
/**
|
|
25
|
+
* What a model can DO with this snapshot.
|
|
26
|
+
*
|
|
27
|
+
* The tool is read-only by design, so the honest answer is "these switches exist,
|
|
28
|
+
* here is what they would save, and a human has to press one". A model that
|
|
29
|
+
* reads a table without this sentence can only describe it; a model that reads
|
|
30
|
+
* this sentence knows the next move is a sentence to its user, not a tool call.
|
|
31
|
+
*/
|
|
32
|
+
function advice(snapshot) {
|
|
33
|
+
const total = Math.max(1, snapshot.totals.tokens)
|
|
34
|
+
const context = snapshot.context
|
|
35
|
+
const skills = snapshot.skillsState ?? {}
|
|
36
|
+
const biggest = (snapshot.groups ?? []).filter((group) => group.savableTokens > 0)[0]
|
|
37
|
+
const lines = []
|
|
38
|
+
|
|
39
|
+
// Skills first: a user who collected hundreds of skills is the user this
|
|
40
|
+
// plugin is for, and their catalog is the line that actually answers "why is
|
|
41
|
+
// my prompt so big".
|
|
42
|
+
if (Number.isFinite(skills.catalogTokens) && skills.catalogTokens > 0) {
|
|
43
|
+
const heaviest = skills.heaviest ? `,最大的是 ${skills.heaviest.name}(${formatTokens(skills.heaviest.tokens)})` : ''
|
|
44
|
+
lines.push(
|
|
45
|
+
`- 技能目录:${skills.total ?? 0} 个技能共 ${formatTokens(skills.catalogTokens)} token,占首轮 ${skills.catalogShare}%,平均每个 ${formatTokens(skills.averageTokens ?? 0)}${heaviest}。收藏越多,这条越长——它对每个请求都生效。`,
|
|
46
|
+
)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const overBudget = snapshot.policy.budget.tokens > 0 && snapshot.policy.preview.after > snapshot.policy.budget.tokens
|
|
50
|
+
const nearWindow = context !== undefined && context !== null && Number.isFinite(context.occupancy) && context.occupancy >= 70
|
|
51
|
+
if (nearWindow || overBudget) {
|
|
52
|
+
const why = nearWindow ? `窗口已用 ${context.occupancy}%` : `策略后 ${formatTokens(snapshot.policy.preview.after)} 仍超预算 ${formatTokens(snapshot.policy.budget.tokens)}`
|
|
53
|
+
lines.push(`- **${why}**:先关最大的可关套件${biggest === undefined ? '' : `(${biggest.label},−${formatTokens(biggest.savableTokens)})`},而不是逐个条目挑。`)
|
|
54
|
+
} else if (biggest !== undefined && biggest.savableTokens / total >= 0.2) {
|
|
55
|
+
lines.push(
|
|
56
|
+
`- 最大的可关套件是 **${biggest.label}**:${biggest.count} 条、${formatTokens(biggest.savableTokens)} token(占首轮 ${percent(biggest.savableTokens, total)}%)。关掉整套比逐条关划算。`,
|
|
57
|
+
)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if (snapshot.policy.appliedToThisAgent !== true) {
|
|
61
|
+
lines.push('- 本会话**没有**受当前策略影响(策略只作用于之后新建的会话);改完策略要让用户开一个新会话才会看到效果。')
|
|
62
|
+
}
|
|
63
|
+
if (context !== undefined && context !== null && context.compaction !== undefined && context.compaction !== null && context.compaction.saved > 0) {
|
|
64
|
+
lines.push(`- 宿主已经压缩过 ${context.compaction.count + context.compaction.prunes} 次、释放 ${formatTokens(context.compaction.saved)} token;压缩不可逆,需要原文时让用户尽早看。`)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
lines.push(
|
|
68
|
+
'- 开关只能由用户在侧栏面板点:模型侧工具 `context_injection` 只读,没有写入口。要动手就对用户说清楚「关哪一套、省多少、什么时候生效」。',
|
|
69
|
+
)
|
|
70
|
+
return lines
|
|
71
|
+
}
|
|
72
|
+
|
|
24
73
|
/**
|
|
25
74
|
* Tool card: one table for the four manageable channels plus the read-only
|
|
26
75
|
* instruction chain, the current policy, and what it would save next session.
|
|
@@ -52,11 +101,22 @@ export function renderCard(snapshot) {
|
|
|
52
101
|
.slice(0, 5)
|
|
53
102
|
.map((group) => `- ${group.label} · ${group.count} 条 · ${formatTokens(group.tokens)} token(可关 ${formatTokens(group.savableTokens)})`)
|
|
54
103
|
|
|
104
|
+
const skills = snapshot.skillsState ?? {}
|
|
105
|
+
const skillLine =
|
|
106
|
+
Number.isFinite(skills.catalogTokens) && skills.catalogTokens > 0
|
|
107
|
+
? `**技能目录(收藏越多越长)** ${skills.total ?? 0} 个 · ${formatTokens(skills.catalogTokens)} token · 占首轮 ${skills.catalogShare}%`
|
|
108
|
+
: null
|
|
109
|
+
|
|
55
110
|
const lines = [
|
|
56
111
|
`### 上下文注入 · 首轮 ${formatTokens(totals.tokens)} token`,
|
|
57
112
|
'',
|
|
113
|
+
...(skillLine === null ? [] : [skillLine, '']),
|
|
58
114
|
...rows,
|
|
59
115
|
'',
|
|
116
|
+
...windowLines(snapshot, true),
|
|
117
|
+
'**能做什么**',
|
|
118
|
+
...advice(snapshot),
|
|
119
|
+
'',
|
|
60
120
|
'**最大的套件(可一键关整套)**',
|
|
61
121
|
...(suites.length > 0 ? suites : ['- 无']),
|
|
62
122
|
'',
|
|
@@ -79,6 +139,35 @@ const describe = (channel) => {
|
|
|
79
139
|
return `${channel.mode === 'only' ? '仅' : '排除'} ${names}`
|
|
80
140
|
}
|
|
81
141
|
|
|
142
|
+
/**
|
|
143
|
+
* The context-window block shared by the card and the text report. Absent when
|
|
144
|
+
* the host has not measured this session yet — a made-up denominator is worse
|
|
145
|
+
* than a missing one.
|
|
146
|
+
*/
|
|
147
|
+
function windowLines(snapshot, markdown) {
|
|
148
|
+
const context = snapshot.context
|
|
149
|
+
if (context === undefined || context === null || context.window === null || context.used === null) return []
|
|
150
|
+
const head = markdown === true ? '**上下文窗口** ' : '上下文窗口:'
|
|
151
|
+
const lines = [
|
|
152
|
+
`${head}${groupDigits(context.used)} / ${groupDigits(context.window)} token(已用 ${context.occupancy}%,剩余 ${groupDigits(context.remaining)})`,
|
|
153
|
+
]
|
|
154
|
+
if (context.breakdown !== null && context.breakdown !== undefined) {
|
|
155
|
+
const b = context.breakdown
|
|
156
|
+
lines.push(`本次请求构成(估算):系统 ${groupDigits(b.system)} · 工具 ${groupDigits(b.tools)} · 消息 ${groupDigits(b.messages)}`)
|
|
157
|
+
}
|
|
158
|
+
const compaction = context.compaction
|
|
159
|
+
if (compaction !== undefined && compaction !== null && (compaction.count > 0 || compaction.prunes > 0)) {
|
|
160
|
+
const parts = []
|
|
161
|
+
if (compaction.count > 0) parts.push(`摘要 ${compaction.count} 次`)
|
|
162
|
+
if (compaction.prunes > 0) parts.push(`剪枝 ${compaction.prunes} 次`)
|
|
163
|
+
parts.push(`省下 ${groupDigits(compaction.saved)} token`)
|
|
164
|
+
if (compaction.failures > 0) parts.push(`失败 ${compaction.failures} 次`)
|
|
165
|
+
lines.push(`已压缩:${parts.join(' · ')}(本插件装载后记录)`)
|
|
166
|
+
}
|
|
167
|
+
lines.push('')
|
|
168
|
+
return lines
|
|
169
|
+
}
|
|
170
|
+
|
|
82
171
|
/** Plain-text report used by `/inject` in a terminal and by the diag route. */
|
|
83
172
|
export function renderText(snapshot) {
|
|
84
173
|
const lines = []
|
|
@@ -92,6 +181,8 @@ export function renderText(snapshot) {
|
|
|
92
181
|
)
|
|
93
182
|
}
|
|
94
183
|
lines.push(`合计:${groupDigits(snapshot.totals.tokens)} token,其中可关 ${groupDigits(snapshot.totals.savableTokens)}(${snapshot.totals.savablePercent}%)`)
|
|
184
|
+
// `windowLines` ends with its own blank separator.
|
|
185
|
+
lines.push(...windowLines(snapshot, false).slice(0, -1))
|
|
95
186
|
lines.push('')
|
|
96
187
|
|
|
97
188
|
lines.push('工作区规则(DSH 直接注入,本插件只读)')
|
|
@@ -130,3 +221,72 @@ export function renderText(snapshot) {
|
|
|
130
221
|
lines.push(`宿主 DSH ${host} · 撤销栈 ${depth} 步 · 策略文件 ${policyFilePath()}`)
|
|
131
222
|
return lines.join('\n')
|
|
132
223
|
}
|
|
224
|
+
|
|
225
|
+
// ---------------------------------------------------------------- health
|
|
226
|
+
|
|
227
|
+
const SEVERITY_LABEL = { high: '高', warn: '注意', info: '信息' }
|
|
228
|
+
const TAB_LABEL = { manage: '管理', insights: '洞察', settings: '设置' }
|
|
229
|
+
|
|
230
|
+
/** One line of human text for a health check's params. */
|
|
231
|
+
export function healthCheckText(check) {
|
|
232
|
+
const params = check?.params ?? {}
|
|
233
|
+
switch (check?.code) {
|
|
234
|
+
case 'heavy-suite':
|
|
235
|
+
return `${params.label ?? '套件'} 占首轮 ${params.share ?? 0}%(${formatTokens(params.tokens ?? 0)} token · ${params.count ?? 0} 条)`
|
|
236
|
+
case 'budget-gap':
|
|
237
|
+
return `比预算多 ${formatTokens(params.gap ?? 0)} token(策略后 ${formatTokens(params.current ?? 0)} / 预算 ${formatTokens(params.target ?? 0)})`
|
|
238
|
+
case 'catalog-truncated':
|
|
239
|
+
return `${params.count ?? 0} 个技能描述被截断(>${params.limit ?? 500} 字)`
|
|
240
|
+
case 'locked-items':
|
|
241
|
+
return `${params.count ?? 0} 项不可关,${formatTokens(params.tokens ?? 0)} token(占 ${params.share ?? 0}%)`
|
|
242
|
+
case 'unknown-window':
|
|
243
|
+
return '宿主还没报告上下文窗口,占用比例未知'
|
|
244
|
+
case 'no-policy':
|
|
245
|
+
return `还没保存过策略(全开),可关 ${formatTokens(params.savableTokens ?? 0)} token`
|
|
246
|
+
case 'empty-catalog':
|
|
247
|
+
return '技能目录为空'
|
|
248
|
+
case 'duplicate-skill':
|
|
249
|
+
return `同名技能来自多个来源${params.name === undefined ? '' : `:${params.name}`}`
|
|
250
|
+
case 'tool-name-collision':
|
|
251
|
+
return `工具名冲突${params.name === undefined ? '' : `:${params.name}`}`
|
|
252
|
+
default:
|
|
253
|
+
return String(check?.code ?? 'unknown')
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** The one-line summary appended to `/inject` and shown in the dock tooltip. */
|
|
258
|
+
export function renderHealthLine(health) {
|
|
259
|
+
const summary = health?.summary ?? { high: 0, warn: 0, info: 0 }
|
|
260
|
+
const checks = Array.isArray(health?.checks) ? health.checks : []
|
|
261
|
+
if (checks.length === 0) return '健康检查:未发现问题。'
|
|
262
|
+
const head = `健康检查:${summary.high} 高 · ${summary.warn} 注意 · ${summary.info} 信息`
|
|
263
|
+
const first = checks[0]
|
|
264
|
+
const prefix = SEVERITY_LABEL[first.severity] ?? first.severity
|
|
265
|
+
return `${head};最需关注「${prefix}」${healthCheckText(first)}`
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Full report for `/inject health`. */
|
|
269
|
+
export function renderHealthText(health) {
|
|
270
|
+
const summary = health?.summary ?? { high: 0, warn: 0, info: 0 }
|
|
271
|
+
const checks = Array.isArray(health?.checks) ? health.checks : []
|
|
272
|
+
const lines = [`健康检查:${summary.high} 高 · ${summary.warn} 注意 · ${summary.info} 信息`]
|
|
273
|
+
if (checks.length === 0) {
|
|
274
|
+
lines.push('', '没有发现需要处理的项。')
|
|
275
|
+
return lines.join('\n')
|
|
276
|
+
}
|
|
277
|
+
lines.push('')
|
|
278
|
+
checks.forEach((check, index) => {
|
|
279
|
+
const severity = SEVERITY_LABEL[check.severity] ?? check.severity
|
|
280
|
+
lines.push(`${index + 1}. [${severity}] ${check.code} — ${healthCheckText(check)}`)
|
|
281
|
+
const action = check.action
|
|
282
|
+
if (action === undefined || action === null) return
|
|
283
|
+
const payload = action.payload ?? {}
|
|
284
|
+
if (action.kind === 'switch-group') lines.push(` → 建议关掉「${payload.group ?? payload.key ?? ''}」(POST /action {kind:"group", channel:"${payload.channel ?? ''}", group:"${payload.group ?? ''}", enabled:false})`)
|
|
285
|
+
else if (action.kind === 'set-budget') lines.push(` → 把预算调到 ${formatTokens(payload.tokens ?? 0)}(面板设置页)`)
|
|
286
|
+
else if (action.kind === 'open-content') lines.push(` → 在面板打开内容:${payload.id ?? ''}`)
|
|
287
|
+
else if (action.kind === 'open-tab') lines.push(` → 打开「${TAB_LABEL[payload.tab] ?? payload.tab ?? ''}」页`)
|
|
288
|
+
})
|
|
289
|
+
lines.push('')
|
|
290
|
+
lines.push('说明:本命令只读;开关在侧栏「上下文注入」面板点,改完策略对之后新建的会话生效。')
|
|
291
|
+
return lines.join('\n')
|
|
292
|
+
}
|