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/snapshot.js CHANGED
@@ -8,6 +8,9 @@ import { collectInstructions } from './instructions.js'
8
8
  import { assignGroups, summarizeGroups } from './group.js'
9
9
  import { undoState } from './history.js'
10
10
  import { hostInfo } from './hostinfo.js'
11
+ import { compactionOf } from './compaction.js'
12
+ import { occupancyTone, readContext } from './pressure.js'
13
+ import { recordSnapshot } from './stats.js'
11
14
  import {
12
15
  CHANNELS,
13
16
  describeChannel,
@@ -19,6 +22,27 @@ import {
19
22
  // How much of one skill's catalog line a description may occupy before the
20
23
  // harness truncates it (dsh-tool-skill default).
21
24
  const SKILL_DESCRIPTION_LIMIT = 500
25
+ // Preview ceil: the panel renders this inline, so a row stays one line-ish and
26
+ // the /summary payload stays bounded even with hundreds of items.
27
+ const PREVIEW_LIMIT = 180
28
+
29
+ /**
30
+ * First paragraph of arbitrary text, flattened and cut to PREVIEW_LIMIT code
31
+ * units without splitting a surrogate pair. Used only for presentation; the
32
+ * measured numbers stay on the item itself.
33
+ */
34
+ export function previewText(text, limit = PREVIEW_LIMIT) {
35
+ const source = typeof text === 'string' ? text : ''
36
+ if (source.trim().length === 0) return undefined
37
+ const paragraph = source.split(/\n\s*\n/).find((part) => part.trim().length > 0) ?? source
38
+ const flat = paragraph.replace(/\s+/g, ' ').trim()
39
+ if (flat.length === 0) return undefined
40
+ if (flat.length <= limit) return flat
41
+ let cut = limit - 1
42
+ const code = flat.charCodeAt(cut - 1)
43
+ if (code >= 0xd800 && code <= 0xdbff) cut -= 1
44
+ return `${flat.slice(0, cut)}…`
45
+ }
22
46
 
23
47
  export async function resolveCwd(ctx, agent, signal) {
24
48
  if (agent !== undefined && agent !== null) {
@@ -36,7 +60,9 @@ export async function resolveCwd(ctx, agent, signal) {
36
60
 
37
61
  function sectionItems(sections) {
38
62
  return sections.map((section, index) => {
39
- const measure = countText(typeof section?.text === 'string' ? section.text : '')
63
+ const text = typeof section?.text === 'string' ? section.text : ''
64
+ const measure = countText(text)
65
+ const preview = previewText(text)
40
66
  return {
41
67
  id: `section:${section?.name ?? index}`,
42
68
  channel: 'sections',
@@ -45,6 +71,7 @@ function sectionItems(sections) {
45
71
  chars: measure.chars,
46
72
  tokens: measure.tokens,
47
73
  locked: false,
74
+ ...(preview === undefined ? {} : { preview }),
48
75
  }
49
76
  })
50
77
  }
@@ -54,10 +81,17 @@ function sectionItems(sections) {
54
81
  // that must never be dropped are also pinned by name here.
55
82
  const REQUIRED_CONTEXTS = new Set(['working-directory:current', 'subagent:identity'])
56
83
 
84
+ /** Contexts that no policy can switch off; /content reports the same lock. */
85
+ export function isLockedContext(name) {
86
+ return REQUIRED_CONTEXTS.has(String(name ?? ''))
87
+ }
88
+
57
89
  function contextItems(contexts) {
58
90
  return contexts.map((context, index) => {
59
- const measure = countText(typeof context?.text === 'string' ? context.text : '')
60
- const locked = context?.required === true || REQUIRED_CONTEXTS.has(String(context?.name ?? ''))
91
+ const text = typeof context?.text === 'string' ? context.text : ''
92
+ const measure = countText(text)
93
+ const locked = context?.required === true || isLockedContext(context?.name)
94
+ const preview = previewText(text)
61
95
  return {
62
96
  id: `context:${context?.name ?? index}`,
63
97
  channel: 'contexts',
@@ -67,6 +101,7 @@ function contextItems(contexts) {
67
101
  tokens: measure.tokens,
68
102
  locked,
69
103
  lockReason: locked ? 'required-context' : undefined,
104
+ ...(preview === undefined ? {} : { preview }),
70
105
  }
71
106
  })
72
107
  }
@@ -75,6 +110,7 @@ function skillItems(skills) {
75
110
  return skills.map((skill) => {
76
111
  const description = typeof skill.description === 'string' ? skill.description : ''
77
112
  const measure = countText(`${skill.name}\n${description}`)
113
+ const preview = previewText(description)
78
114
  return {
79
115
  id: `skill:${skill.name}`,
80
116
  channel: 'skills',
@@ -87,6 +123,7 @@ function skillItems(skills) {
87
123
  provider: typeof skill.provider === 'string' ? skill.provider : undefined,
88
124
  source: typeof skill.source === 'string' ? skill.source : undefined,
89
125
  locked: false,
126
+ ...(preview === undefined ? {} : { preview }),
90
127
  }
91
128
  })
92
129
  }
@@ -101,6 +138,7 @@ function toolItems(schemas) {
101
138
  parameters = ''
102
139
  }
103
140
  const measure = countText(`${schema.name}\n${description}\n${parameters}`)
141
+ const preview = previewText(description)
104
142
  return {
105
143
  id: `tool:${schema.name ?? index}`,
106
144
  channel: 'tools',
@@ -110,6 +148,7 @@ function toolItems(schemas) {
110
148
  tokens: measure.tokens,
111
149
  deferred: schema.deferLoading === true,
112
150
  locked: false,
151
+ ...(preview === undefined ? {} : { preview }),
113
152
  }
114
153
  })
115
154
  }
@@ -131,6 +170,63 @@ function instructionItems(instructions) {
131
170
  }))
132
171
  }
133
172
 
173
+ // Why this plugin exists: people collect skills. Every skill's name and
174
+ // description sits in the catalog of every request, so a few dozen collected
175
+ // skills quietly costs money and dilutes the model's attention. The counts below
176
+ // are what the panel leads with — not a generic "how much is injected" figure.
177
+ //
178
+ // Skills are also not the only thing that grows: tool schemas (MCP servers) are
179
+ // a different kind of line item, and on most machines the bigger one. Kinds are
180
+ // reported side by side so "my skills are 3k, then why is the prompt 84k" is
181
+ // answered on the same card instead of left to the reader.
182
+ function kindOf(item) {
183
+ if (item.channel === 'skills') return 'skills'
184
+ if (item.channel === 'tools') return 'tools'
185
+ if (item.channel === 'sections') return 'prompts'
186
+ if (item.channel === 'contexts') return 'prompts'
187
+ return 'rules'
188
+ }
189
+
190
+ function skillFocus(skills, items, totals) {
191
+ const rows = items.filter((item) => item.channel === 'skills')
192
+ const catalogTokens = rows.reduce((sum, item) => sum + item.tokens, 0)
193
+ const total = Math.max(1, totals.tokens)
194
+ const byProvider = new Map()
195
+ for (const row of rows) {
196
+ const key = String(row.provider || row.source || 'skills')
197
+ const entry = byProvider.get(key) ?? { provider: key, count: 0, tokens: 0, unlocked: 0 }
198
+ entry.count += 1
199
+ entry.tokens += row.tokens
200
+ if (!row.locked) entry.unlocked += 1
201
+ byProvider.set(key, entry)
202
+ }
203
+ const providers = [...byProvider.values()].sort((left, right) => right.tokens - left.tokens)
204
+ const heaviest = rows.slice().sort((left, right) => right.tokens - left.tokens)[0] ?? null
205
+
206
+ // Same three kinds everywhere: what the reader compares, not a raw dump.
207
+ const kinds = { skills: { count: 0, tokens: 0 }, tools: { count: 0, tokens: 0 }, prompts: { count: 0, tokens: 0 }, rules: { count: 0, tokens: 0 } }
208
+ for (const item of items) {
209
+ const kind = kinds[kindOf(item)]
210
+ kind.count += 1
211
+ kind.tokens += item.tokens
212
+ }
213
+ const kindsOut = Object.entries(kinds).map(([id, entry]) => ({ id, count: entry.count, tokens: entry.tokens, share: percent(entry.tokens, total) }))
214
+
215
+ return {
216
+ total: rows.length,
217
+ modelVisible: skills.modelVisible?.length ?? 0,
218
+ userOnly: skills.userOnly ?? 0,
219
+ truncated: rows.filter((row) => row.truncated).length,
220
+ catalogTokens,
221
+ catalogShare: percent(catalogTokens, total),
222
+ averageTokens: rows.length === 0 ? 0 : Math.round(catalogTokens / rows.length),
223
+ providers: providers.length,
224
+ heaviest: heaviest === null ? null : { name: heaviest.name, tokens: heaviest.tokens, provider: heaviest.provider ?? null },
225
+ topProviders: providers.slice(0, 5),
226
+ kinds: kindsOut,
227
+ }
228
+ }
229
+
134
230
  async function collectSkills(ctx, agent, cwd, signal) {
135
231
  const options = { cwd }
136
232
  if (agent !== undefined) options.scope = agent
@@ -141,6 +237,9 @@ async function collectSkills(ctx, agent, cwd, signal) {
141
237
  return {
142
238
  complete: snapshot?.complete === true,
143
239
  total: all.length,
240
+ // Kept whole for /content: a skill row can be hidden by policy and still
241
+ // be worth reading, and its registered path lives on the same object.
242
+ all,
144
243
  modelVisible: all.filter((skill) => skill.invocation?.modelInvocable === true),
145
244
  userOnly: all.filter((skill) => skill.invocation?.modelInvocable !== true && skill.invocation?.userInvocable === true).length,
146
245
  }
@@ -149,7 +248,78 @@ async function collectSkills(ctx, agent, cwd, signal) {
149
248
  }
150
249
  }
151
250
 
152
- function collectAnchor(ctx, agent) {
251
+ // Raw collection shared by the snapshot pipeline and the content route.
252
+ //
253
+ // Both consumers need the same four sources (assembled prompt, skill catalogs,
254
+ // tool schemas, instruction files), and assembling the prompt is the expensive
255
+ // part. A snapshot stores its raw sources here for a short window, and
256
+ // `/content` reuses them when the drawer is opened right after a panel read.
257
+ // `buildSnapshot` itself always collects fresh data: registries and files can
258
+ // change between two builds, and a stale snapshot would be worse than a second
259
+ // read.
260
+ const SOURCE_TTL_MS = 2000
261
+ const SOURCE_CACHE_LIMIT = 8
262
+ const SOURCE_CACHE = new Map()
263
+
264
+ export function resetSourceCache() {
265
+ SOURCE_CACHE.clear()
266
+ }
267
+
268
+ /** Last collected raw sources for an agent, if they are still within the TTL. */
269
+ export function cachedSources(agent) {
270
+ const entry = SOURCE_CACHE.get(cacheKey(agent))
271
+ if (entry === undefined) return undefined
272
+ if (Date.now() - entry.at > SOURCE_TTL_MS) {
273
+ SOURCE_CACHE.delete(cacheKey(agent))
274
+ return undefined
275
+ }
276
+ return entry.sources
277
+ }
278
+
279
+ export async function collectSources(ctx, agent, cwd, signal) {
280
+ let assembly = { sections: [], contexts: [] }
281
+ let assemblyError = null
282
+ try {
283
+ const options = {}
284
+ if (agent !== undefined) options.scope = agent
285
+ if (signal !== undefined) options.signal = signal
286
+ assembly = await ctx.systemPrompt.assemble(options)
287
+ } catch (error) {
288
+ assemblyError = String(error?.message ?? error)
289
+ }
290
+
291
+ const skillState = await collectSkills(ctx, agent, cwd, signal)
292
+ let schemas = []
293
+ let toolsError = null
294
+ try {
295
+ schemas = ctx.tools.schemas(agent)
296
+ } catch (error) {
297
+ toolsError = String(error?.message ?? error)
298
+ }
299
+ const instructions = await collectInstructions(cwd)
300
+ const sources = {
301
+ at: Date.now(),
302
+ assembly,
303
+ assemblyError,
304
+ skillState,
305
+ schemas: Array.isArray(schemas) ? schemas : [],
306
+ toolsError,
307
+ instructions,
308
+ }
309
+ const key = cacheKey(agent)
310
+ SOURCE_CACHE.delete(key)
311
+ SOURCE_CACHE.set(key, { at: sources.at, sources })
312
+ if (SOURCE_CACHE.size > SOURCE_CACHE_LIMIT) {
313
+ const oldest = SOURCE_CACHE.keys().next()
314
+ if (!oldest.done) SOURCE_CACHE.delete(oldest.value)
315
+ }
316
+ return sources
317
+ }
318
+
319
+ function collectAnchor(ctx, agent, context) {
320
+ if (context !== undefined && context !== null && Number.isFinite(context.pressure) && context.pressure > 0) {
321
+ return { tokens: context.pressure, source: 'contextPressure' }
322
+ }
153
323
  const meter = ctx.get('tokenMeter')
154
324
  const session = agent?.session
155
325
  if (meter === undefined || meter === null || session === undefined || session === null) return null
@@ -357,6 +527,24 @@ function rememberInventory(agent, items) {
357
527
  }
358
528
  }
359
529
 
530
+ /**
531
+ * Size of items an earlier snapshot already measured. Policy actions use this
532
+ * so a switch event can carry a token delta without re-assembling the prompt
533
+ * just to answer "how much did I just turn off". A name this process never saw
534
+ * contributes 0; the event then says fewer tokens, not a guessed number.
535
+ */
536
+ export function estimateItemTokens(channel, names) {
537
+ let tokens = 0
538
+ let known = 0
539
+ for (const name of Array.isArray(names) ? names : []) {
540
+ const entry = nameCache.get(`${channel}:${name}`)
541
+ if (entry === undefined) continue
542
+ tokens += Number(entry.tokens) || 0
543
+ known += 1
544
+ }
545
+ return { tokens, known }
546
+ }
547
+
360
548
  function labelFromName(name) {
361
549
  const server = /^mcp__([^_]+(?:_[^_]+)*?)__/.exec(name)
362
550
  if (server !== null) return server[1].toUpperCase()
@@ -427,34 +615,29 @@ function collectClosed(agent, policy, items) {
427
615
  export async function buildSnapshot(ctx, agent, scopeSource, signal) {
428
616
  const cwd = await resolveCwd(ctx, agent, signal)
429
617
  const policyState = await readPolicy()
430
-
431
- let assembly = { sections: [], contexts: [] }
432
- let assemblyError = null
433
- try {
434
- const options = {}
435
- if (agent !== undefined) options.scope = agent
436
- if (signal !== undefined) options.signal = signal
437
- assembly = await ctx.systemPrompt.assemble(options)
438
- } catch (error) {
439
- assemblyError = String(error?.message ?? error)
440
- }
618
+ const sources = await collectSources(ctx, agent, cwd, signal)
619
+ const assembly = sources.assembly
620
+ const assemblyError = sources.assemblyError
441
621
 
442
622
  const sections = sectionItems(Array.isArray(assembly?.sections) ? assembly.sections : [])
443
623
  const contexts = contextItems(Array.isArray(assembly?.contexts) ? assembly.contexts : [])
444
- const skillState = await collectSkills(ctx, agent, cwd, signal)
624
+ const skillState = sources.skillState
445
625
  const skills = skillState.error === undefined ? skillItems(skillState.modelVisible) : []
446
- let schemas = []
447
- let toolsError = null
448
- try {
449
- schemas = ctx.tools.schemas(agent)
450
- } catch (error) {
451
- toolsError = String(error?.message ?? error)
452
- }
453
- const tools = toolItems(Array.isArray(schemas) ? schemas : [])
454
- const instructions = await collectInstructions(cwd)
626
+ const schemas = sources.schemas
627
+ const toolsError = sources.toolsError
628
+ const tools = toolItems(schemas)
629
+ const instructions = sources.instructions
455
630
  const instructionRows = instructionItems(instructions)
456
631
 
457
- const items = assignGroups([...sections, ...contexts, ...skills, ...tools, ...instructionRows])
632
+ // `on` is the single source of truth the panel renders: does the saved policy
633
+ // include this item in the next session? The panel used to recompute it (and
634
+ // the "heaviest suite" ranking read a field the host never sent, so every
635
+ // suite looked closed on real data). Locked items are always on: no policy can
636
+ // switch them off, so reporting false would contradict the lock explanation.
637
+ const items = assignGroups([...sections, ...contexts, ...skills, ...tools, ...instructionRows]).map((item) => ({
638
+ ...item,
639
+ on: item.locked === true ? true : !isExcluded(policyState.policy[item.channel], item.name),
640
+ }))
458
641
  rememberInventory(agent, items)
459
642
  const closedState = collectClosed(agent, policyState.policy, items)
460
643
  const groups = summarizeGroups(items)
@@ -490,15 +673,48 @@ export async function buildSnapshot(ctx, agent, scopeSource, signal) {
490
673
  (sum, channel) => ({
491
674
  chars: sum.chars + channel.chars,
492
675
  tokens: sum.tokens + channel.tokens,
676
+ count: sum.count + channel.count,
493
677
  savableTokens: sum.savableTokens + (channel.manageable ? channel.savableTokens : 0),
494
678
  }),
495
- { chars: 0, tokens: 0, savableTokens: 0 },
679
+ { chars: 0, tokens: 0, count: 0, savableTokens: 0 },
496
680
  )
497
681
 
682
+ // What the next session actually gets under the current policy, per channel.
683
+ const effectiveChannels = CHANNELS.map((channel) => {
684
+ // `on` already encodes the locked-items rule (a policy that names a locked
685
+ // item still cannot switch it off), so the effective projection and the
686
+ // per-item flag stay one answer instead of two.
687
+ const rows = items.filter((item) => item.channel === channel && item.on !== false)
688
+ return {
689
+ id: channel,
690
+ count: rows.length,
691
+ chars: rows.reduce((sum, item) => sum + item.chars, 0),
692
+ tokens: rows.reduce((sum, item) => sum + item.tokens, 0),
693
+ savableTokens: rows.filter((item) => !item.locked).reduce((sum, item) => sum + item.tokens, 0),
694
+ manageable: true,
695
+ }
696
+ })
697
+ effectiveChannels.push({ ...channels[channels.length - 1], manageable: false })
698
+ const effectiveTotals = effectiveChannels.reduce(
699
+ (sum, channel) => ({
700
+ chars: sum.chars + channel.chars,
701
+ tokens: sum.tokens + channel.tokens,
702
+ count: sum.count + channel.count,
703
+ savableTokens: sum.savableTokens + (channel.manageable ? channel.savableTokens : 0),
704
+ }),
705
+ { chars: 0, tokens: 0, count: 0, savableTokens: 0 },
706
+ )
707
+ effectiveTotals.savablePercent = percent(effectiveTotals.savableTokens, effectiveTotals.tokens)
708
+
498
709
  const preview = previewPolicy(policyState.policy, items, channelNames)
499
710
  const plan = planBudget(policyState.policy, items, policyState.policy.budget.tokens)
500
- const anchor = collectAnchor(ctx, agent)
711
+ const context = await readContext(ctx, agent, signal)
712
+ const anchor = collectAnchor(ctx, agent, context)
501
713
  const applied = agent !== undefined && agent !== null && appliedAgents.has(agent)
714
+ // Skills are the reason most people need this plugin at all, so the snapshot
715
+ // carries a dedicated view of the catalog rather than leaving the panel to
716
+ // count rows in a 300-item list.
717
+ const skillView = skillFocus(skillState, items, totals)
502
718
 
503
719
  const policy = {
504
720
  ...policyState.policy,
@@ -514,11 +730,13 @@ export async function buildSnapshot(ctx, agent, scopeSource, signal) {
514
730
  manageableShare: percent(totals.savableTokens, totals.tokens),
515
731
  }
516
732
 
517
- return {
733
+ const result = {
518
734
  generatedAt: Date.now(),
519
735
  cwd,
520
736
  agent: { id: typeof agent?.id === 'string' ? agent.id : undefined, scopeSource },
521
737
  channels,
738
+ context: { ...context, compaction: compactionOf(agent), tone: occupancyTone(context) },
739
+ effective: { channels: effectiveChannels, totals: effectiveTotals },
522
740
  items,
523
741
  groups,
524
742
  closed: closedState.closed,
@@ -534,6 +752,7 @@ export async function buildSnapshot(ctx, agent, scopeSource, signal) {
534
752
  complete: skillState.complete === true,
535
753
  error: skillState.error ?? null,
536
754
  truncated: skills.filter((item) => item.truncated).length,
755
+ ...skillView,
537
756
  },
538
757
  toolsState: { count: tools.length, deferred: tools.filter((item) => item.deferred).length, error: toolsError },
539
758
  promptsState: { sections: sections.length, contexts: contexts.length, error: assemblyError },
@@ -547,6 +766,14 @@ export async function buildSnapshot(ctx, agent, scopeSource, signal) {
547
766
  undo: undoState(),
548
767
  host: hostInfo(),
549
768
  }
769
+ // History for the 统计 tab: every measured conversation contributes one row.
770
+ // Wrapped because a statistics side effect must never fail a read.
771
+ try {
772
+ recordSnapshot(result)
773
+ } catch {
774
+ /* history is optional */
775
+ }
776
+ return result
550
777
  }
551
778
 
552
779
  // Filled in by index.js so the snapshot can report application state without