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.
Files changed (49) hide show
  1. package/CHANGELOG.md +267 -0
  2. package/CONTRIBUTING.md +2 -2
  3. package/README.md +282 -94
  4. package/README.zh.md +236 -97
  5. package/client.js +3325 -295
  6. package/docs/ARCHITECTURE.md +111 -24
  7. package/docs/COMPATIBILITY.md +28 -7
  8. package/docs/DETAIL.md +148 -0
  9. package/docs/DETAIL.zh.md +105 -1
  10. package/docs/FAQ.md +49 -7
  11. package/docs/PERFORMANCE.md +60 -6
  12. package/docs/images/demo.gif +0 -0
  13. package/docs/images/dock.png +0 -0
  14. package/docs/images/panel-dark.png +0 -0
  15. package/docs/images/panel-drawer.png +0 -0
  16. package/docs/images/panel-insights.png +0 -0
  17. package/docs/images/panel-manage-expanded.png +0 -0
  18. package/docs/images/panel-manage.png +0 -0
  19. package/docs/images/panel-settings.png +0 -0
  20. package/docs/images/panel-sidebar.png +0 -0
  21. package/docs/preview.svg +177 -23
  22. package/icon.svg +19 -5
  23. package/index.js +100 -14
  24. package/lib/actions.js +12 -4
  25. package/lib/apply.js +14 -2
  26. package/lib/compaction.js +126 -0
  27. package/lib/content.js +360 -0
  28. package/lib/events.js +216 -0
  29. package/lib/health.js +210 -0
  30. package/lib/pressure.js +146 -0
  31. package/lib/routes.js +293 -9
  32. package/lib/snapshot.js +256 -29
  33. package/lib/stats.js +394 -0
  34. package/lib/text.js +160 -0
  35. package/lib/trend.js +168 -0
  36. package/locale/de.json +251 -6
  37. package/locale/en.json +251 -6
  38. package/locale/es.json +251 -6
  39. package/locale/fr.json +251 -6
  40. package/locale/ja.json +251 -6
  41. package/locale/pt.json +251 -6
  42. package/locale/ru.json +252 -7
  43. package/locale/zh.json +249 -4
  44. package/package.json +16 -3
  45. package/screenshots.json +7 -5
  46. package/docs/images/panel-about.png +0 -0
  47. package/docs/images/panel-budget.png +0 -0
  48. package/docs/images/panel-policy.png +0 -0
  49. package/docs/images/panel-suites.png +0 -0
package/lib/routes.js CHANGED
@@ -8,17 +8,31 @@ import { readFile } from 'node:fs/promises'
8
8
  import { dirname, join } from 'node:path'
9
9
  import { fileURLToPath } from 'node:url'
10
10
  import { applyPolicyForAgent, rewriteStats, savePolicy } from './apply.js'
11
+ import { collectContent } from './content.js'
12
+ import { buildHealth } from './health.js'
11
13
  import { pushUndo, undoState } from './history.js'
12
14
  import { restorePolicyAt, undoLastPolicy } from './actions.js'
13
15
  import { hostInfo } from './hostinfo.js'
14
16
  import { CHANNELS, defaultPolicy, isExcluded, normalizePolicy, policyFilePath, readPolicy } from './policy.js'
15
17
  import { PRESET_NAMES, presetPolicy } from './presets.js'
16
- import { buildSnapshot, planBudget, policyFromPlan, appliedAgents, lastApplicationState } from './snapshot.js'
18
+ import {
19
+ buildSnapshot,
20
+ estimateItemTokens,
21
+ appliedAgents,
22
+ lastApplicationState,
23
+ planBudget,
24
+ policyFromPlan,
25
+ } from './snapshot.js'
17
26
  import { getSettings } from './settings.js'
27
+ import { backfillState, readStats, requestBackfill } from './stats.js'
28
+ import { readEvents } from './events.js'
29
+ import { readTrend, TREND_RANGES, TREND_LIMIT } from './trend.js'
18
30
  import { renderCard, renderText } from './text.js'
19
31
 
20
32
  const PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)))
21
33
  export const ROUTE_PREFIX = '/plugins/dsh-injection-manager'
34
+ // Bumped when the HTTP contract gains fields the panel can feature-detect.
35
+ export const API_VERSION = 2
22
36
 
23
37
  export const ROUTES = {
24
38
  ping: `${ROUTE_PREFIX}/ping`,
@@ -31,6 +45,11 @@ export const ROUTES = {
31
45
  verify: `${ROUTE_PREFIX}/verify`,
32
46
  registrations: `${ROUTE_PREFIX}/registrations`,
33
47
  boot: `${ROUTE_PREFIX}/boot`,
48
+ stats: `${ROUTE_PREFIX}/stats`,
49
+ content: `${ROUTE_PREFIX}/content`,
50
+ trend: `${ROUTE_PREFIX}/trend`,
51
+ events: `${ROUTE_PREFIX}/events`,
52
+ health: `${ROUTE_PREFIX}/health`,
34
53
  }
35
54
 
36
55
  // In-memory diagnostics written by the browser half. Never persisted.
@@ -173,26 +192,51 @@ function toggleItem(policy, channel, name, enabled) {
173
192
  if (!current.names.includes(name)) current.names.push(name)
174
193
  }
175
194
 
195
+ function sessionIdOf(agent) {
196
+ return typeof agent?.id === 'string' && agent.id.length > 0 ? agent.id : undefined
197
+ }
198
+
199
+ /**
200
+ * Name count and token size for a set of switched items. Sizes come from the
201
+ * inventory cache a previous snapshot measured; a name this process never saw
202
+ * still counts but contributes 0 tokens instead of a guessed number.
203
+ */
204
+ function switchNumbers(channel, names) {
205
+ const estimate = estimateItemTokens(channel, names)
206
+ return { count: names.length, tokens: estimate.tokens, known: estimate.known }
207
+ }
208
+
176
209
  async function applyAction(ctx, agent, action) {
210
+ const sessionId = sessionIdOf(agent)
177
211
  const state = await readPolicy()
178
212
  const policy = normalizePolicy(state.policy)
179
213
 
180
214
  if (action?.kind === 'undo') {
181
- return undoLastPolicy()
215
+ return undoLastPolicy({ sessionId, params: { via: 'panel' } })
182
216
  }
183
217
 
184
218
  if (action?.kind === 'restore') {
185
- return restorePolicyAt(Number(action.index))
219
+ return restorePolicyAt(Number(action.index), { sessionId, params: { via: 'panel' } })
186
220
  }
187
221
 
188
222
  // Everything below is a mutation; remember the pre-write policy so the panel
189
223
  // can offer one-click undo for a whole-suite switch.
190
224
  const before = JSON.parse(JSON.stringify(policy))
191
225
  const undoLabel = typeof action.label === 'string' && action.label.trim().length > 0 ? action.label : describeAction(action)
226
+ // The event row for the insights feed. Every mutation below overwrites the
227
+ // kind/params it can describe; savePolicy records it in the same atomic step.
228
+ const event = { kind: 'policy-saved', params: {}, tokensDelta: 0 }
192
229
 
193
230
  switch (action?.kind) {
194
231
  case 'item': {
195
- toggleItem(policy, action.channel, String(action.name ?? ''), action.enabled === true)
232
+ const channel = String(action.channel ?? '')
233
+ const name = String(action.name ?? '')
234
+ const enabled = action.enabled === true
235
+ toggleItem(policy, channel, name, enabled)
236
+ const numbers = switchNumbers(channel, [name])
237
+ event.kind = 'switch'
238
+ event.params = { channel, name, op: enabled ? 'on' : 'off', count: 1, tokens: numbers.tokens }
239
+ event.tokensDelta = enabled ? numbers.tokens : -numbers.tokens
196
240
  policy.preset = 'custom'
197
241
  break
198
242
  }
@@ -212,12 +256,18 @@ async function applyAction(ctx, agent, action) {
212
256
  rule.names = rule.mode === 'except' ? rule.names.filter((name) => !wanted.has(name)) : [...new Set(rule.names.concat(names))]
213
257
  }
214
258
  if (rule.mode === 'except' && rule.names.length === 0) rule.mode = 'all'
259
+ const numbers = switchNumbers(channel, names)
260
+ event.kind = 'switch'
261
+ event.params = { channel, op: action.enabled === false ? 'off' : 'on', count: numbers.count, tokens: numbers.tokens, suite: true }
262
+ event.tokensDelta = action.enabled === false ? -numbers.tokens : numbers.tokens
215
263
  policy.preset = 'custom'
216
264
  break
217
265
  }
218
266
  case 'channel': {
219
267
  if (!CHANNELS.includes(action.channel)) throw new Error(`unknown channel: ${action.channel}`)
220
268
  policy[action.channel] = action.enabled === true ? { mode: 'all', names: [] } : { mode: 'only', names: [] }
269
+ event.kind = 'switch'
270
+ event.params = { channel: String(action.channel), op: action.enabled === true ? 'on' : 'off', scope: 'channel' }
221
271
  policy.preset = 'custom'
222
272
  break
223
273
  }
@@ -236,6 +286,8 @@ async function applyAction(ctx, agent, action) {
236
286
  next.prompt = policy.prompt
237
287
  next.budget = policy.budget
238
288
  Object.assign(policy, next)
289
+ event.kind = 'preset'
290
+ event.params = { name, via: 'panel' }
239
291
  break
240
292
  }
241
293
  case 'group': {
@@ -243,10 +295,50 @@ async function applyAction(ctx, agent, action) {
243
295
  const group = String(action.group ?? '')
244
296
  if (!CHANNELS.includes(channel)) throw new Error(`unknown channel: ${channel}`)
245
297
  const snapshot = await buildSnapshot(ctx, agent, 'action', undefined)
246
- const names = snapshot.items
247
- .filter((item) => item.channel === channel && item.group === group && !item.locked)
248
- .map((item) => item.name)
298
+ const rows = snapshot.items.filter((item) => item.channel === channel && item.group === group && !item.locked)
299
+ const names = rows.map((item) => item.name)
249
300
  for (const name of names) toggleItem(policy, channel, name, action.enabled === true)
301
+ const tokens = rows.reduce((sum, item) => sum + item.tokens, 0)
302
+ event.kind = 'switch'
303
+ event.params = {
304
+ channel,
305
+ group: rows[0]?.groupLabel ?? group,
306
+ groupId: group,
307
+ op: action.enabled === true ? 'on' : 'off',
308
+ count: names.length,
309
+ tokens,
310
+ }
311
+ event.tokensDelta = action.enabled === true ? tokens : -tokens
312
+ policy.preset = 'custom'
313
+ break
314
+ }
315
+ case 'groups': {
316
+ // A suite can span channels (REA's MCP tools plus its prompt section), so
317
+ // one switch has to address several group ids at once.
318
+ const list = Array.isArray(action.groups) ? action.groups : []
319
+ const snapshot = await buildSnapshot(ctx, agent, 'action', undefined)
320
+ const labels = []
321
+ let count = 0
322
+ let tokens = 0
323
+ for (const entry of list) {
324
+ const channel = String(entry.channel ?? '')
325
+ const group = String(entry.group ?? '')
326
+ if (!CHANNELS.includes(channel)) continue
327
+ const rows = snapshot.items.filter((item) => item.channel === channel && item.group === group && !item.locked)
328
+ const names = rows.map((item) => item.name)
329
+ for (const name of names) toggleItem(policy, channel, name, action.enabled === true)
330
+ count += names.length
331
+ tokens += rows.reduce((sum, item) => sum + item.tokens, 0)
332
+ if (rows[0]?.groupLabel !== undefined && !labels.includes(rows[0].groupLabel)) labels.push(rows[0].groupLabel)
333
+ }
334
+ event.kind = 'switch'
335
+ event.params = {
336
+ op: action.enabled === true ? 'on' : 'off',
337
+ count,
338
+ tokens,
339
+ groups: labels,
340
+ }
341
+ event.tokensDelta = action.enabled === true ? tokens : -tokens
250
342
  policy.preset = 'custom'
251
343
  break
252
344
  }
@@ -260,17 +352,28 @@ async function applyAction(ctx, agent, action) {
260
352
  throw new Error('invalid-policy: expected a policy object')
261
353
  }
262
354
  Object.assign(policy, normalizePolicy(candidate))
355
+ event.kind = 'import'
356
+ event.params = { via: 'panel', format: source !== candidate ? 'manifest' : 'policy' }
263
357
  break
264
358
  }
265
359
  case 'prompt': {
266
360
  if (typeof action.prefix === 'string') policy.prompt.prefix = action.prefix
267
361
  if (typeof action.suffix === 'string') policy.prompt.suffix = action.suffix
362
+ event.kind = 'policy-saved'
363
+ event.params = {
364
+ via: 'panel',
365
+ prompt: true,
366
+ prefixChars: policy.prompt.prefix.length,
367
+ suffixChars: policy.prompt.suffix.length,
368
+ }
268
369
  policy.preset = 'custom'
269
370
  break
270
371
  }
271
372
  case 'budget': {
272
373
  const tokens = Number(action.tokens)
273
374
  policy.budget.tokens = Number.isFinite(tokens) && tokens > 0 ? Math.round(tokens) : 0
375
+ event.kind = 'budget'
376
+ event.params = { tokens: policy.budget.tokens, via: 'panel' }
274
377
  break
275
378
  }
276
379
  case 'budget.apply': {
@@ -281,19 +384,24 @@ async function applyAction(ctx, agent, action) {
281
384
  next.prompt = policy.prompt
282
385
  next.budget = { tokens: Math.round(target) }
283
386
  Object.assign(policy, next)
387
+ event.kind = 'budget'
388
+ event.params = { tokens: Math.round(target), dropped: plan.drop.length, saved: plan.savedTokens, via: 'plan' }
389
+ event.tokensDelta = -plan.savedTokens
284
390
  break
285
391
  }
286
392
  case 'reset': {
287
393
  const fresh = defaultPolicy()
288
394
  fresh.prompt = policy.prompt
289
395
  Object.assign(policy, fresh)
396
+ event.kind = 'policy-saved'
397
+ event.params = { via: 'panel', reset: true, preset: 'all' }
290
398
  break
291
399
  }
292
400
  default:
293
401
  throw new Error(`unknown action kind: ${action?.kind}`)
294
402
  }
295
403
 
296
- await savePolicy(policy)
404
+ await savePolicy(policy, { sessionId, ...event })
297
405
  pushUndo(before, undoLabel)
298
406
  return policy
299
407
  }
@@ -303,6 +411,8 @@ function describeAction(action) {
303
411
  switch (kind) {
304
412
  case 'group':
305
413
  return `group ${action.group} ${action.enabled ? 'on' : 'off'}`
414
+ case 'groups':
415
+ return `groups ${(action.groups || []).length} ${action.enabled ? 'on' : 'off'}`
306
416
  case 'item':
307
417
  return `${action.enabled ? 'on' : 'off'} ${action.name}`
308
418
  case 'names':
@@ -341,8 +451,14 @@ export function createRoutes(ctx) {
341
451
  scopeSource = agent === undefined ? 'route.none' : 'route.last-live'
342
452
  }
343
453
  const snapshot = await buildSnapshot(ctx, agent, scopeSource, undefined)
454
+ const health = buildHealth(snapshot)
344
455
  const payload = {
345
456
  ...snapshot,
457
+ ok: true,
458
+ apiVersion: API_VERSION,
459
+ // Counts only: the full check list has its own route, and a summary
460
+ // refresh should stay small.
461
+ healthSummary: { high: health.summary.high, warn: health.summary.warn, info: health.summary.info },
346
462
  text: renderText(snapshot),
347
463
  card: renderCard(snapshot),
348
464
  presets: PRESET_NAMES,
@@ -581,7 +697,175 @@ export function createRoutes(ctx) {
581
697
  }
582
698
  }
583
699
 
584
- return { summary, policy, locale, action, ping, diag, verify, export: exportRoute, boot: report('boot'), registrations: report('registrations') }
700
+ /**
701
+ * History for the 统计 tab. Everything here is what this plugin measured —
702
+ * the file is written by `recordSnapshot()` — so the response states its own
703
+ * coverage rather than claiming to describe conversations it never saw.
704
+ *
705
+ * The read path never replays durable logs: it answers from stats.json (and
706
+ * the session index once a background pass listed it) and asks for one
707
+ * bounded fill in the background. `backfilling:true` tells the panel that the
708
+ * corpus is still being priced; the next poll sees the new rows.
709
+ */
710
+ const stats = async (req, res) => {
711
+ try {
712
+ if (req.method !== 'GET') {
713
+ respondJson(res, 405, { error: 'method-not-allowed' })
714
+ return
715
+ }
716
+ const url = new URL(req.url ?? ROUTES.stats, 'http://localhost')
717
+ const request = url.searchParams.get('backfill') === '0' ? { started: false, running: false } : requestBackfill(ctx)
718
+ const history = await readStats()
719
+ const fill = backfillState()
720
+ respondJson(res, 200, {
721
+ ...history,
722
+ sessions: fill.sessions.slice(0, 60),
723
+ backfill: fill.last,
724
+ backfilling: request.started || request.running || fill.running,
725
+ coverage: { ...history.coverage, known: fill.known },
726
+ generatedAt: Date.now(),
727
+ })
728
+ } catch (error) {
729
+ respondJson(res, 500, { error: 'stats-failed', message: String(error?.message ?? error) })
730
+ }
731
+ }
732
+
733
+ /**
734
+ * Original text behind one snapshot row. This is the only route that opens a
735
+ * file, and it only opens paths that the snapshot collection registered
736
+ * (skill files, instruction files): the request cannot name a path.
737
+ * A 2s abort keeps the panel responsive; the response says `timeout` rather
738
+ * than serving a half-collected item.
739
+ */
740
+ const content = async (req, res) => {
741
+ try {
742
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
743
+ respondJson(res, 405, { ok: false, error: 'method-not-allowed' })
744
+ return
745
+ }
746
+ const url = new URL(req.url ?? ROUTES.content, 'http://localhost')
747
+ const channel = url.searchParams.get('channel') ?? ''
748
+ const id = url.searchParams.get('id') ?? ''
749
+ const picked = pickAgent(ctx, url.searchParams.get('session') ?? undefined)
750
+ let agent = picked.agent
751
+ if (agent === undefined) agent = pickLastLive(ctx)
752
+ const controller = new AbortController()
753
+ // The contract budgets a read at 2s. Race the collection against that
754
+ // budget so a slow assemble can never hold the drawer open; the abort
755
+ // signal additionally stops providers that honour it.
756
+ let timer
757
+ const deadline = new Promise((resolve) => {
758
+ timer = setTimeout(() => {
759
+ controller.abort()
760
+ resolve({ ok: false, status: 504, error: 'timeout', message: 'content collection exceeded the 2s budget' })
761
+ }, 2000)
762
+ })
763
+ let result
764
+ try {
765
+ result = await Promise.race([collectContent(ctx, agent, channel, id, controller.signal), deadline])
766
+ } finally {
767
+ clearTimeout(timer)
768
+ }
769
+ if (result.ok !== true) {
770
+ respondJson(res, result.status ?? 500, {
771
+ ok: false,
772
+ error: result.error ?? 'content-failed',
773
+ ...(result.message === undefined ? {} : { message: result.message }),
774
+ })
775
+ return
776
+ }
777
+ respondJson(res, 200, result)
778
+ } catch (error) {
779
+ respondJson(res, 500, { ok: false, error: 'content-failed', message: String(error?.message ?? error) })
780
+ }
781
+ }
782
+
783
+ /**
784
+ * Cross-session first-turn trend. Same measured rows the stats route reports,
785
+ * plus the bounded durable-log backfill; unknown channel splits stay null.
786
+ */
787
+ const trend = async (req, res) => {
788
+ try {
789
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
790
+ respondJson(res, 405, { ok: false, error: 'method-not-allowed' })
791
+ return
792
+ }
793
+ const url = new URL(req.url ?? ROUTES.trend, 'http://localhost')
794
+ const range = url.searchParams.get('range') ?? 'all'
795
+ if (!TREND_RANGES.includes(range)) {
796
+ respondJson(res, 400, { ok: false, error: 'invalid-range', message: `range must be one of ${TREND_RANGES.join('|')}` })
797
+ return
798
+ }
799
+ const limit = url.searchParams.get('limit') ?? String(TREND_LIMIT)
800
+ const payload = await readTrend(range, limit, ctx)
801
+ respondJson(res, 200, { ok: true, ...payload })
802
+ } catch (error) {
803
+ respondJson(res, 500, { ok: false, error: 'trend-failed', message: String(error?.message ?? error) })
804
+ }
805
+ }
806
+
807
+ /** Injection event feed: what changed, for one session or the whole install. */
808
+ const events = async (req, res) => {
809
+ try {
810
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
811
+ respondJson(res, 405, { ok: false, error: 'method-not-allowed' })
812
+ return
813
+ }
814
+ const url = new URL(req.url ?? ROUTES.events, 'http://localhost')
815
+ let sessionId = url.searchParams.get('session') ?? ''
816
+ if (sessionId.length === 0) {
817
+ const picked = pickAgent(ctx, undefined)
818
+ const agent = picked.agent ?? pickLastLive(ctx)
819
+ sessionId = typeof agent?.id === 'string' ? agent.id : ''
820
+ }
821
+ const limit = url.searchParams.get('limit') ?? '60'
822
+ const payload = await readEvents(sessionId.length > 0 ? sessionId : undefined, limit)
823
+ respondJson(res, 200, { ok: true, ...payload })
824
+ } catch (error) {
825
+ respondJson(res, 500, { ok: false, error: 'events-failed', message: String(error?.message ?? error) })
826
+ }
827
+ }
828
+
829
+ /** Health checks for the current session (the /summary counts come from here). */
830
+ const health = async (req, res) => {
831
+ try {
832
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
833
+ respondJson(res, 405, { ok: false, error: 'method-not-allowed' })
834
+ return
835
+ }
836
+ const url = new URL(req.url ?? ROUTES.health, 'http://localhost')
837
+ const picked = pickAgent(ctx, url.searchParams.get('session') ?? undefined)
838
+ let agent = picked.agent
839
+ let scopeSource = `health.${picked.source}`
840
+ if (agent === undefined) {
841
+ agent = pickLastLive(ctx)
842
+ scopeSource = agent === undefined ? 'health.none' : 'health.last-live'
843
+ }
844
+ const snapshot = await buildSnapshot(ctx, agent, scopeSource, undefined)
845
+ const report = buildHealth(snapshot)
846
+ respondJson(res, 200, { ok: true, summary: report.summary, checks: report.checks })
847
+ } catch (error) {
848
+ respondJson(res, 500, { ok: false, error: 'health-failed', message: String(error?.message ?? error) })
849
+ }
850
+ }
851
+
852
+ return {
853
+ summary,
854
+ policy,
855
+ locale,
856
+ action,
857
+ ping,
858
+ diag,
859
+ verify,
860
+ export: exportRoute,
861
+ stats,
862
+ content,
863
+ trend,
864
+ events,
865
+ health,
866
+ boot: report('boot'),
867
+ registrations: report('registrations'),
868
+ }
585
869
  }
586
870
 
587
871
  const countApplied = () => {