dsh-injection-manager 0.0.0-stage → 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 (62) hide show
  1. package/CHANGELOG.md +642 -0
  2. package/CONTRIBUTING.md +49 -0
  3. package/LICENSE +21 -0
  4. package/README.md +371 -2
  5. package/README.zh.md +330 -0
  6. package/SECURITY.md +35 -0
  7. package/client.js +4928 -0
  8. package/cordis.patch.yml +4 -0
  9. package/docs/ARCHITECTURE.md +195 -0
  10. package/docs/COMPATIBILITY.md +60 -0
  11. package/docs/DETAIL.de.md +1 -0
  12. package/docs/DETAIL.es.md +1 -0
  13. package/docs/DETAIL.fr.md +1 -0
  14. package/docs/DETAIL.ja.md +1 -0
  15. package/docs/DETAIL.md +149 -0
  16. package/docs/DETAIL.pt.md +1 -0
  17. package/docs/DETAIL.ru.md +1 -0
  18. package/docs/DETAIL.zh.md +105 -0
  19. package/docs/FAQ.md +96 -0
  20. package/docs/PERFORMANCE.md +73 -0
  21. package/docs/images/demo.gif +0 -0
  22. package/docs/images/dock.png +0 -0
  23. package/docs/images/panel-dark.png +0 -0
  24. package/docs/images/panel-drawer.png +0 -0
  25. package/docs/images/panel-insights.png +0 -0
  26. package/docs/images/panel-manage-expanded.png +0 -0
  27. package/docs/images/panel-manage.png +0 -0
  28. package/docs/images/panel-settings.png +0 -0
  29. package/docs/images/panel-sidebar.png +0 -0
  30. package/docs/preview.svg +178 -0
  31. package/icon.svg +20 -0
  32. package/index.js +304 -0
  33. package/lib/actions.js +33 -0
  34. package/lib/apply.js +230 -0
  35. package/lib/compaction.js +126 -0
  36. package/lib/content.js +360 -0
  37. package/lib/events.js +216 -0
  38. package/lib/group.js +141 -0
  39. package/lib/health.js +210 -0
  40. package/lib/history.js +47 -0
  41. package/lib/hostinfo.js +83 -0
  42. package/lib/instructions.js +142 -0
  43. package/lib/measure.js +51 -0
  44. package/lib/policy.js +189 -0
  45. package/lib/presets.js +45 -0
  46. package/lib/pressure.js +146 -0
  47. package/lib/routes.js +877 -0
  48. package/lib/settings.js +32 -0
  49. package/lib/snapshot.js +785 -0
  50. package/lib/stats.js +394 -0
  51. package/lib/text.js +292 -0
  52. package/lib/trend.js +168 -0
  53. package/locale/de.json +413 -0
  54. package/locale/en.json +413 -0
  55. package/locale/es.json +413 -0
  56. package/locale/fr.json +413 -0
  57. package/locale/ja.json +413 -0
  58. package/locale/pt.json +413 -0
  59. package/locale/ru.json +413 -0
  60. package/locale/zh.json +413 -0
  61. package/package.json +85 -4
  62. package/screenshots.json +11 -0
@@ -0,0 +1,4 @@
1
+ - insert:
2
+ - id: injection-manager
3
+ name: dsh-injection-manager
4
+ config: {}
@@ -0,0 +1,195 @@
1
+ # 架构
2
+
3
+ 这份文档只讲一件事:一次新会话的首轮上下文,从策略文件到模型请求,中间经过哪些环节、每一环用什么接口、失败时会怎样;v2 新增的只读表面(内容透视、趋势、事件、健康检查)分别从哪来、写到哪去。
4
+
5
+ ## 四条注入通道
6
+
7
+ 首轮上下文不是一整块,而是四条互不相同的通道。插件对它们的控制能力也不同,这是整个设计的前提。
8
+
9
+ | 通道 | 载体 | 产生者 | 本插件的控制方式 |
10
+ | --- | --- | --- | --- |
11
+ | A. 系统提示词段落 | `system` 角色文本 | `ctx.systemPrompt.section()` | 会话作用域的 `system-prompt/assemble` 过滤器按名字移除/替换 |
12
+ | B. 运行时上下文 | 独立 `user` 快照 | `ctx.systemPrompt.context()` | 同一个过滤器;`required: true` 的不动 |
13
+ | C. pre-step 用户消息 | 插在 claimed 批次后的 `user` 消息 | 各插件(`dsh-agent-instructions`、`dsh-tool-skill`、`dsh-time-context`) | 只能间接:技能逐条 shadow;工作区规则只读展示 |
14
+ | D. 工具 schema | 请求的 `tools` 字段 | `ctx.tools.register()` | `ctx.tools.restrict({ deny })`,只影响该会话 |
15
+
16
+ 没有任何一条通道通过「改文件」实现。旧版曾重命名 `AGENTS.md`、改 `SKILL.md` frontmatter,那会在多会话、多工作目录下改错对象,已废弃。
17
+
18
+ ## 快照流水线
19
+
20
+ 面板、模型工具、导出文件、应用策略、健康检查、内容抽屉,全部来自同一次 `buildSnapshot()`:
21
+
22
+ ```
23
+ policy.json ──┐
24
+ Config ───────┤
25
+ ├─▶ collectSections/Contexts (assemble)
26
+ 工作目录 ─────┤ collectSkills (snapshot)
27
+ │ collectTools (schemas)
28
+ │ collectInstructions (固定路径探测)
29
+ │ readContext (tokenMeter + contextBreakdown + llm)
30
+ ▼
31
+ assignGroups() → 按套件聚类
32
+ ▼
33
+ previewPolicy() → 关掉后剩多少 / 省多少
34
+ planBudget() → 目标预算下的关闭建议
35
+ ▼
36
+ { items(+preview), groups, channels, totals, context, policy, undo }
37
+ ├─▶ 面板 / context_injection / /export / applyPolicyForAgent
38
+ └─▶ buildHealth(snapshot) → 健康检查(纯函数,见下)
39
+ ```
40
+
41
+ `context` 那一路是唯一不由本插件估算的部分:`window` / `pressure` / `projected` 来自宿主的 `contextPressure` 投影,`breakdown` 来自 `contextBreakdown`,(缺分母时才)用 `ctx.llm.resolveModelInfo()` 的 `contextWindow` 兜底;压缩回执由 `session/event` 监听器从 `compaction/*` 累积。因此面板里的占用百分比与宿主自己的「上下文已用 x%」是同一个数,不会各说各话。
42
+
43
+ 关键不变量:**只有一份实现**。浏览器不重算 token、不重算预览;它拿到什么就画什么。这也让「预览数字」和「实际生效」不会打架。v2 只加了两个派生:每个条目的 `preview`(快照阶段切好的前 180 字符纯文本)和 `buildHealth()` 的检查结果——两者都从同一份快照算,不额外读盘。
44
+
45
+ ## 生效时序
46
+
47
+ ```
48
+ agent/created (source=startup|clear)
49
+ └─ buildSnapshot() ← 读策略、量一遍当前会话
50
+ └─ applySnapshotPolicy()
51
+ ├─ agent.ctx.on('system-prompt/assemble', rewrite) ← A/B 通道
52
+ └─ agent.ctx.inject(['tools','skills'], scoped => {
53
+ scoped.skills.register(shadow) ← C 通道(技能)
54
+ scoped.tools.restrict({ deny }) ← D 通道
55
+ })
56
+ ```
57
+
58
+ 三个时序事实决定了实现方式:
59
+
60
+ 1. `assemble()` 在 `agent/pre-step` **之前**执行,所以 per-session 注册必须发生在 `agent/created`,不能等 pre-step。
61
+ 2. 段落与上下文不能用「同名空文本再注册一次」的办法关掉:agent preset 已经在**同一作用域**注册了这些名字,再注册会抛 `already registered in this scope`。公开的改写点是 scoped `system-prompt/assemble` 瀑布。
62
+ 3. `tools.restrict()` 只能在作用域上下文里调用;名单必须来自该会话真实的 `schemas(agent)`,否则未知名字会抛错。
63
+
64
+ `resume` / `compact` 不处理:它们带着已有历史,中途改写不是「默认策略」该做的事。
65
+
66
+ ## HTTP 面
67
+
68
+ 全部挂在 `/plugins/dsh-injection-manager` 下,共 15 条路由:**12 条只读 GET + 3 条 POST-only**(`/action` 改策略;`/boot`、`/registrations` 是客户端自报诊断,二者收到 GET 会返回 405):
69
+
70
+ | 路由 | 方法 | 作用 | 响应要点 |
71
+ | --- | --- | --- | --- |
72
+ | `/ping` | GET | 注册自检 | 路由清单、策略文件路径 |
73
+ | `/summary` | GET | 面板快照 | `apiVersion: 2`、`healthSummary {high,warn,info}`、`items[].preview`、`settings`、`locale` |
74
+ | `/content` | GET | 单条原文 | `?channel=&id=[&session=]`;`contentType`、`content`、`bytes`、`truncated`、`sourcePath`、`note`;256KB 上限、2 秒预算、404/400 分支 |
75
+ | `/trend` | GET | 跨会话趋势 | `?range=all|30d|7d&limit=120`(上限 500);`points[]`、`aggregate`、`coverage {recorded, known}`、`backfilling` |
76
+ | `/events` | GET | 事件流 | `?session=&limit=60`(上限 300);`events[]`、`coverage {from, count, limit}` |
77
+ | `/health` | GET | 健康检查 | `?session=`;`summary {high,warn,info,checkedAt}`、`checks[]`(`code`、`severity`、`params`、可选 `action`) |
78
+ | `/stats` | GET | 历史与覆盖 | `stats.json` 内容 + `sessions` 头信息(≤60)+ 最近一轮 `backfill` + `backfilling` + `coverage` |
79
+ | `/policy` | GET | 策略文件状态 | 策略、路径、是否迁移、最近一次应用 |
80
+ | `/verify` | GET | 生效核对 | `?session=`;重新装配后的段落/上下文/工具名 |
81
+ | `/diag` | GET | 诊断 | 客户端 boot、最近应用、过滤器调用计数、宿主版本 |
82
+ | `/export` | GET | 导出 | Markdown / JSON |
83
+ | `/locale` | GET | 八语言字典 | 客户端词条 |
84
+ | `/registrations`、`/boot` | **POST** | 客户端自报诊断(仅内存) | 启动表与注册诊断,不落盘;GET 返回 405 |
85
+ | `/action` | **POST** | 改策略入口 | 同源 JSON;开关/预设/预算/导入/撤销 |
86
+
87
+ 约定的响应边界:JSON 单次响应有上限,`/summary` 的条目文本靠 `preview` 控制体积;`/content` 的 256KB 上限和 UTF-8 安全截断在 `lib/content.js` 里实现;`/trend` 的 `limit` 与被回填的会话数都封顶;`/events` 读的是已经封顶 300 条的 `events.json`。
88
+
89
+ ## 数据文件
90
+
91
+ | 位置 | 内容 | 谁写 | 生命周期 |
92
+ | --- | --- | --- | --- |
93
+ | `$DSH_HOME/injection-manager/policy.json` | 通道模式、名单、前言后记、预算 | 面板动作(原子写) | 持久,卸载后保留 |
94
+ | `$DSH_HOME/injection-manager/stats.json` | 每个会话一行测量:`allOn` / `effective` / `saved` / `peak` / `samples` / `firstAt` / `scope` / `policy` / `compactions` / 新快照才有的 `channels` | 每次取快照(面板/工具/命令) | 上限 400 行,原子写,可被日志回填补齐 |
95
+ | `$DSH_HOME/injection-manager/events.json` | `{version:1, events:[…]}`,最多 300 条;每条 `id` / `at` / `kind` / `params`(拍平的原始值,字符串 ≤200 字符,≤24 项)/ `tokensDelta` / 可选 `sessionId` / `dedupeKey` | 策略保存、预设、预算、导入、撤销、压缩 | 追加式;tmp+rename;去重键防重放 |
96
+ | `$DSH_HOME/injection-manager/` 的旧目录 | `context-injection/`、`context-preflight/` | 只在首次读取时迁移 | 只读兼容 |
97
+ | 插件行 `config` | dock / refreshOnFocus / showRawNames / budgetTokens | Plugins → Configuration | 持久 |
98
+ | 浏览器 localStorage | 抽屉行号、洞察范围、被关掉的 gate 卡 | 面板 | 只在这个浏览器 |
99
+ | 内存 | 撤销栈(20 步)、最近一次应用结果、客户端 boot 报告、压缩回执(按会话)、路由窗口容量缓存 | 进程内 | 重启清空 |
100
+
101
+ 不上传、不联网、不写 workspace 文件。
102
+
103
+ ## 事件埋点
104
+
105
+ `lib/events.js` 是唯一的写入口,`appendEvent()` 永不抛错(事件流是锦上添花,写失败不能把一次策略保存变成错误)。当前会产生事件的来源:
106
+
107
+ | 位置 | kind | 说明 |
108
+ | --- | --- | --- |
109
+ | `index.js` 的 `agent/created` | `session-created` | 新会话建立(`source: startup|clear`),fire-and-forget,不进首轮关键路径 |
110
+ | `lib/apply.js` 的 `savePolicy()` | `policy-saved` / `preset` / `budget` / `switch` / `import` / `undo` | 由调用方通过 `meta` 指定,缺省 `policy-saved` |
111
+ | `lib/compaction.js` 的摘要/剪枝回执 | `compaction` / `prune` | 宿主的 `compaction/summary`、`compaction/prune` 事件 |
112
+ | `lib/compaction.js` 的失败回执 | `diagnostic` | 宿主报告 `compaction/*` 带 `error` 时写一条:`params {phase:'compaction', error, compactionId}`,用于解释"这次压缩失败了" |
113
+
114
+ `model-switch` / `mode-toggle` 目前在枚举里预留、本版本不会主动产生(还没有对应的宿主事件入口);`/inject health` 这类只读命令也不写事件。也就是说:**写策略、压缩/剪枝、压缩失败、新会话**会留下事件,其余读取不会。
115
+
116
+ 去重键 = `时间戳|kind|params 的稳定哈希`(压缩事件可由调用方给显式 `dedupeKey`,如 `seq/compactionId`),因此同一条宿主事件被观察两次不会变成两行。`params` 只收原始值:嵌套对象直接丢弃,数组最多 20 项,字符串截到 200 字符——会话正文没有路径能进这个文件。
117
+
118
+ ## 健康检查
119
+
120
+ `lib/health.js` 的 `buildHealth(snapshot)` 是纯函数:输入一份快照,输出 `{summary, checks}`;唯一的时钟值是 `snapshot.generatedAt`,所以同一份快照两次调用逐字节一致。面板、`/health` 路由、`/inject health` 都调它。
121
+
122
+ - 固定 9 个 code 的枚举,当前实现实际会产生 7 个:`heavy-suite`(单套 ≥25% 或 ≥30k)、`budget-gap`(预测值超预算)、`catalog-truncated`(描述被目录行截断)、`locked-items`(不可关项 ≥10%)、`unknown-window`(无测量)、`no-policy`(从没保存过策略且全开)、`empty-catalog`(目录为空且完整)。
123
+ - `duplicate-skill` 与 `tool-name-collision` **刻意不产生**:这版宿主的技能注册表与工具注册表在插件可见之前就解析掉了重名,报出来就是编造。枚举保留完整,未来宿主能观察到时再加,UI 契约不变。
124
+ - `action.kind` 只有四种:`switch-group` / `set-budget` / `open-content` / `open-tab`;`payload` 直接是 `POST /action` 能吃下的形状(`{channel, group, enabled, op}` 等),面板不再做二次映射。
125
+ - 排序:严重度 → 涉及 token 数 → code;`summary` 按严重度计数,`checkedAt` 来自快照。
126
+
127
+ ## 内容透视
128
+
129
+ `lib/content.js` 回答「这一行到底是什么」。两条硬规则:
130
+
131
+ 1. **路径白名单**:只打开快照自己收集时登记过的路径(技能的注册路径、工作区规则探测到的文件)。接口不接受调用方给的路径,因此不可能变成任意文件读取。
132
+ 2. **截断安全**:上限按字节卡(HTTP 256KB、模型工具 32KB),在码点边界切,绝不切坏多字节字符;响应里的 `bytes` 描述的是实际返回的前缀。
133
+
134
+ `sourcePath` 只有在真的来自磁盘时才有;`note` 说明来源:`catalog`(技能没有定位到 SKILL.md,给的是目录行)、`file`(磁盘文件)、`assemble`(系统提示词装配结果,无单文件)、`snapshot`(会话快照)。工具内容做 JSON 格式化后返回(`contentType: json`),面板在抽屉里拆成「描述 / 参数表 / 原始 JSON」三视图。路由层给这次收集套 2 秒预算,超时返回 `timeout` 而不是半个结果。
135
+
136
+ ## 洞察数据
137
+
138
+ `lib/trend.js` 只合并两种诚实来源:本插件写下的 `stats.json` 行(`measured`)和有界的 durable-log 回填(`log`)。回填在**后台**跑,读取从不 await 它:一个进程内单飞的任务,冷却 60 秒、每轮最多 8 个会话、单轮预算 6 秒;`/trend` 立即返回已有行并带 `backfilling: true`,后续轮询会看到后台补进来的行。这样 671 个会话的语料不会让每次打开洞察页都等 7 秒。
139
+
140
+ - 老行与日志行没有通道分解:`channels` 报 `null`,不补 0;UI 画斜纹。
141
+ - 排序按 `firstAt`(时间轴左→右),`limit` 取最近的 N 个点;`aggregate` 在切 `limit` **之前**算,所以汇总代表整个范围而不是「最近 120 个」。
142
+ - 契约修订(2026-11-16):`scope` 是自由字符串(常见 `startup|clear|route.session|backfill`,未知值原样透传、截到 64 字符),`policy` 允许 `all|minimal|custom|unknown`——不为迎合枚举而改写历史数据。
143
+ - `coverage {recorded, known}`:`known` 来自 `sessionQuery.listSessions()` 的头信息数量(可失败为 `null`),`recorded` 是范围内的行数。UI 的覆盖率脚注就是这两个数。
144
+
145
+ ## 包结构
146
+
147
+ ```
148
+ index.js 插件入口:Config、工具(含单条内容模式)、/inject、路由、agent/created
149
+ lib/snapshot.js 快照、套件聚类、行内预览、策略预览/预算
150
+ lib/apply.js 四通道生效 + 策略保存(含事件埋点)
151
+ lib/group.js 套件聚类
152
+ lib/policy.js 策略 schema、原子读写、旧目录迁移
153
+ lib/routes.js HTTP 面(15 条路由、同源写校验、安全头)
154
+ lib/content.js 内容透视:白名单读取、UTF-8 安全截断
155
+ lib/events.js 事件流:校验、去重、封顶、原子写
156
+ lib/trend.js 跨会话趋势:stats + 有界日志回填合并
157
+ lib/health.js 健康检查:纯函数、固定 code 集
158
+ lib/stats.js 历史记录、通道分解、日志定价回填
159
+ lib/history.js 撤销栈
160
+ lib/settings.js Config 归一化
161
+ lib/text.js 模型卡片、文本报告、健康摘要
162
+ lib/instructions.js 工作区规则只读探测
163
+ lib/pressure.js 窗口占用(tokenMeter / contextBreakdown / llm 容量)
164
+ lib/compaction.js 压缩回执(session/event 上的 compaction/*)
165
+ client.js 浏览器半包:面板三页、侧栏、输入框徽标、内容抽屉
166
+ locale/*.json 八语言字典(宿主展示用 meta + 客户端词条)
167
+ ```
168
+
169
+ ## 安全边界
170
+
171
+ - 写操作(`POST /action`)要求 `content-type: application/json`,且 `sec-fetch-site` 不是跨站;带 `Origin` 时还要求 host 与页面一致。
172
+ - 所有 JSON 响应带 `x-content-type-options: nosniff`、`x-frame-options: DENY`、`cache-control: no-store`。
173
+ - 没有任何 GET 路由会写文件:`/summary`、`/content`、`/trend`、`/events`、`/health`、`/stats`、`/verify`、`/export` 都只读策略、快照、统计与事件文件。
174
+ - `/content` 是唯一读磁盘内容的接口,但路径来自快照登记,不接受外部路径;有 2 秒预算与 256KB 上限。
175
+ - 策略与统计、事件写入都是同目录临时文件 + rename,崩溃时保留旧文件。
176
+ - 插件不发起网络请求,不上传策略或会话内容;`events.json` 只收策略与被截断的原始值。
177
+
178
+ ## 测试
179
+
180
+ | 文件 | 覆盖 |
181
+ | --- | --- |
182
+ | `test/policy.test.mjs` | 模式语义、必填锁定、预算贪心、计划回写 |
183
+ | `test/group.test.mjs` | MCP/前缀/provider 聚类、汇总 |
184
+ | `test/settings.test.mjs` | 配置归一化与默认值 |
185
+ | `test/text.test.mjs` | 工具卡片、文本报告与健康摘要的数字/告警 |
186
+ | `test/apply.test.mjs` | 假 ctx 下四条通道端到端、幂等、resume 跳过 |
187
+ | `test/routes.test.mjs` | 动作/撤销/导出/同源校验、新路由的分支 |
188
+ | `test/pressure.test.mjs` | 占用分子/分母、容量兜底与缓存、缺数据不瞎猜、阈值档位 |
189
+ | `test/compaction.test.mjs` | 摘要/剪枝/失败回执、未知会话、事件转发 |
190
+ | `test/content.test.mjs` | 白名单、UTF-8 截断、四种 `note`、404/400、超时 |
191
+ | `test/events.test.mjs` | 去重、封顶、参数拍平、原子写、读窗 |
192
+ | `test/trend.test.mjs` | 范围切分、`channels: null`、聚合先于 limit、覆盖率 |
193
+ | `test/health.test.mjs` | 每个 code 的触发条件、排序、summary、不产生的 code |
194
+ | `test/tool-content.test.mjs` | 模型工具单条模式:参数校验、32KB 上限、错误 JSON |
195
+ | `test/command.test.mjs` | `/inject` 子命令(含 health)与错误分支 |
@@ -0,0 +1,60 @@
1
+ # 兼容性
2
+
3
+ 本插件只依赖 DeepSeek Harness 的公开服务与事件,不读内部状态、不写用户文件。
4
+
5
+ ## 已验证
6
+
7
+ | dsh 版本 | 环境 | 结果 | 验证方式 |
8
+ | --- | --- | --- | --- |
9
+ | `0.2.2-rc.1` | **CLI**:临时 profile `v2qa` 起的独立 `dsh web` 实例(49801),不碰 Desktop 实例 | 通过 | Playwright 全流程(管理/洞察/设置三 tab、内容抽屉、趋势、设置页)+ 四条新路由探针(135 项断言 PASS);宿主版本由 `hostinfo` 在真实宿主里读出 |
10
+ | `0.2.2-rc.3` | **Desktop**:用户真实 profile(49711) | 通过 | 真实会话:`/verify` 重新装配、`/diag` 过滤器计数、子智能体实测工具集 |
11
+ | `0.2.2-rc.2` | — | 未验证 | — |
12
+ | `0.2.1` / `0.2.0` | — | 未验证 | 旧版 `dsh-context-preflight` 曾在早期版本上运行,但注入过滤改用 `system-prompt/assemble` 后未复测 |
13
+
14
+ 运行时自检:插件会读宿主版本(`DSH_INSTALL_DIR` 的 `package.json`,或 profile 里的 `@deepseek-ai/dsh`),低于 `0.2.2` 时面板顶部提示「部分开关可能不生效」;版本读不到时按未知处理,不猜。版本读取在桌面 rc.3 与 CLI rc.1 两个真实宿主里都验证过(`hostinfo`),`/diag` 的 `host` 字段给出实际读到的版本与来源。
15
+
16
+ ## 依赖的接口(缺一个会降级或失效)
17
+
18
+ | 接口 | 用途 | 缺失时 |
19
+ | --- | --- | --- |
20
+ | `ctx.systemPrompt.assemble({ scope })` | 取本轮实际装配的段落与上下文并计数 | 清单为空,面板显示错误 |
21
+ | `system-prompt/assemble`(scoped waterfall) | 按策略移除段落 / 替换 persona 前缀后记 | 开关无法生效,仅剩展示 |
22
+ | `ctx.skills.snapshot({ cwd, scope })` | 技能目录清单与体积 | 技能通道标为读取失败 |
23
+ | `ctx.skills.register({ invocation })` | 用同名不可调用技能遮住目录条目 | 技能无法逐个关闭 |
24
+ | `ctx.tools.schemas(agent)` / `restrict({ deny })` | 工具 schema 清单与裁剪 | 工具无法关闭 |
25
+ | `ctx.agents.get(id)` / `currentInitiator()` | 面板对会话取数 | 退回到最近活跃会话 |
26
+ | `ctx.webServer.register({ kind: 'exact' })` | 面板路由 | 面板无数据(工具与命令仍可用) |
27
+ | `agent/created` 事件的 `source` | 区分新会话与恢复/压缩 | 只按 `startup` / `clear` 兜底 |
28
+ | `ctx.get('tokenMeter').contextPressure(session)` | 窗口占用:分子(provider 报的 prompt)与分母(`contextWindow`) | 窗口卡片显示「窗口未知」,其余功能不受影响 |
29
+ | `ctx.get('sessionProjections').snapshot(session)` 的 `contextBreakdown` | 系统 / 工具 / 消息构成 | 只显示占用条,不显示构成 |
30
+ | `ctx.llm.resolveModelInfo(provider, model)` | 首次请求前拿窗口容量(按路由缓存) | 首个请求之后才有分母 |
31
+ | `session/event` 上的 `compaction/summary` / `compaction/prune` / `compaction/end` | 压缩回执与释放的 token | 不显示压缩行;数值来自宿主 `shadowedTokenCount`,缺失时不猜 |
32
+
33
+ ## v2 HTTP 契约(2.0.0 起)
34
+
35
+ 面板与宿主之间多了一层版本协商:`GET /summary` 返回 `apiVersion: 2`。新版面板读到 v1 时显示可关掉的 gate 卡(新版洞察/内容透视/健康检查需要 v2 宿主),管理、设置与开关不受影响;v1 面板连 v2 宿主则照常工作(新增字段都是追加的)。
36
+
37
+ v2 新增的四条只读路由与它们的宿主侧依赖:
38
+
39
+ | 路由 | 依赖 | 缺失时 |
40
+ | --- | --- | --- |
41
+ | `/content?channel=&id=[&session=]` | 快照登记的技能路径、规则文件路径;`node:fs` 读取 | 抽屉显示读取失败,列表与开关不受影响 |
42
+ | `/trend?range=&limit=` | `stats.json` + `sessionQuery.listSessions()`(可选) | 无 `sessionQuery` 时只读历史文件,覆盖率 `known: null` |
43
+ | `/events?session=&limit=` | `$DSH_HOME/injection-manager/events.json` | 文件不存在时返回空窗口,不报错 |
44
+ | `/health?session=` | 与面板同一份 `buildSnapshot()` | 快照失败时返回错误,面板显示「健康检查读取失败」 |
45
+
46
+ 宿主版本无关:这些路由全部由插件自己实现,只用到 `0.2.2` 已有的公开服务(`agents`、`webServer`、`sessionQuery`)。
47
+
48
+ ## 明确不可管(不是兼容性问题)
49
+
50
+ - 工作区规则(`AGENTS.md` / `CLAUDE.md`):`dsh-agent-instructions` 在 `agent/pre-step` 直接注入 user 消息,0.2.2 没有公开抑制入口;本插件只读展示。
51
+ - 时间上下文、技能目录消息本身:同属 pre-step user 消息通道,只能通过逐条遮技能或关掉 `skill` 工具间接影响。
52
+ - 必填上下文(当前目录、子智能体身份):即使策略要求也会保留。
53
+
54
+ ## 升级排查顺序
55
+
56
+ 1. `GET /plugins/<id>/ping` 是否 200(路由注册)。
57
+ 2. `GET /plugins/<id>/diag` 的 `clientModule` 是否有值(客户端进了 boot 表)、`rewrite.count` 是否随新会话增长(过滤器被调用)。
58
+ 3. `GET /plugins/<id>/verify?session=<id>` 对比 `sections` 数量与面板预期。
59
+ 4. 新版表面单独排查:`/health` 是否 200(健康条)、`/trend` 是否返回点(洞察)、`/content?channel=tools&id=tool:<name>` 是否 200(抽屉);`/summary` 的 `apiVersion` 不是 2 时面板会显示 gate 卡,说明宿主加载的是旧版服务端半包。
60
+ 5. 仍不对时,先确认该版本是否仍导出上表中的方法(版本 release notes 与包内 README)。
@@ -0,0 +1 @@
1
+ ![Kontext-Injektion: viele Quellen, gebündelt in einer ersten Anfrage](preview.svg)
@@ -0,0 +1 @@
1
+ ![Inyección de contexto: muchas fuentes reducidas a una sola petición](preview.svg)
@@ -0,0 +1 @@
1
+ ![Injection de contexte : de nombreuses sources ramenées à une seule requête](preview.svg)
@@ -0,0 +1 @@
1
+ ![コンテキスト注入:多くの来源が 1 回のリクエストに収束する](preview.svg)
package/docs/DETAIL.md ADDED
@@ -0,0 +1,149 @@
1
+ ![Context injection: many sources narrowed into one first request](preview.svg)
2
+
3
+ # What this plugin actually changes
4
+
5
+ A new DSH session receives a lot before its first request reaches a model: the system prompt
6
+ sections, runtime contexts, the skill catalog as text, one JSON schema per tool, and the
7
+ `AGENTS.md` chain. None of it is visible in the conversation, and there is no single place to
8
+ turn any of it off.
9
+
10
+ This page is the five-minute version of what the plugin measures, what it can and cannot switch,
11
+ and what the new surfaces show. The [README](../README.md) is the overview; the
12
+ [architecture](ARCHITECTURE.md) is the implementation.
13
+
14
+ ## 1. Three numbers, three questions
15
+
16
+ | Number | Question | Where it comes from |
17
+ | --- | --- | --- |
18
+ | First-turn injection (e.g. 83.8k) | What will the *next new session* be given? | Assembled here: prompt sections and contexts from `systemPrompt.assemble()`, skills from `skills.snapshot()`, tool schemas from `tools.schemas()`, `AGENTS.md` read from the default chain |
19
+ | Window occupancy (e.g. 36%) | How full is *this* conversation? | The host's own `contextPressure` projection, divided by the model's window |
20
+ | Content (the drawer) | What does one line *actually say*? | The snapshot's own registered sources: assembled text, tool declarations, skill files or catalog lines, instruction files |
21
+
22
+ They are not comparable, and the panel never subtracts one from the other. The first number is
23
+ what the plugin controls; the second decides when the host compacts; the third is the raw text
24
+ behind a row, read only when you open it.
25
+
26
+ Token counts from this plugin are estimates (ASCII ÷ 4, other characters ÷ 1.6). The occupancy
27
+ figure is not: `pressureTokens` is provider-reported, and the window comes from the same request
28
+ record the model adapter used.
29
+
30
+ ## 2. Three tabs, two ambient entries
31
+
32
+ | Surface | What it is for |
33
+ | --- | --- |
34
+ | Manage (管理) | Health strip, KPI row, request strip, then the suite-clustered list with switches; every row can expand a preview or open its content. |
35
+ | Insights (洞察) | Cross-session first-turn trend, aggregate band, session cards, cross-session composition, heaviest suites, this session's event timeline, coverage footnote. |
36
+ | Settings (设置) | Presets, four channel masters, custom prefix/suffix, budget, export/import, undo history, verification, plugin preferences, versions and language. |
37
+ | Composer chip | First-turn total and window occupancy, one line, deliberately muted; × hides it. |
38
+ | `/inject` + `context_injection` | The same numbers as text, plus a read-only model tool (optionally one item's content). |
39
+
40
+ ## 3. What the manage page shows
41
+
42
+ - **Health** — deterministic findings over the current snapshot (section 5), each with an action.
43
+ - **KPI** — first-turn injection, window occupancy with its denominator, the switchable share and the
44
+ current budget; the composer chip mirrors the same numbers.
45
+ - **Request strip** — system / tools / messages split of the *current* request and compaction
46
+ receipts, from the host's own projections.
47
+ - **The list** — five channels, clustered into suites (one MCP server = one switch), with a
48
+ description column for every item. A suite row carries item count, tokens, share and a tri-state
49
+ switch; a closed suite stays visible with its remembered size so it can be reopened. Items expand
50
+ an inline preview; the content button opens the drawer.
51
+
52
+ ## 4. What the content drawer reads
53
+
54
+ Only sources the snapshot itself registered — a request cannot name a path:
55
+
56
+ | Row | Content | Note shown |
57
+ | --- | --- | --- |
58
+ | Prompt section / runtime context | The assembled text (no single file) | "from the system prompt assembly" |
59
+ | Tool schema | The JSON declaration, split into description / parameter table / raw JSON | "from the session snapshot" |
60
+ | Skill | `SKILL.md` body when resolvable, otherwise the exact catalog line that is injected | "file" or "skill catalog entry" |
61
+ | Workspace rule | The real `AGENTS.md` / `CLAUDE.md` content and path | "from a file on disk" |
62
+
63
+ The drawer shows line numbers (toggleable), in-content search with match highlighting and a
64
+ per-line match summary, copy full text / copy path, a truncation notice at the 256 KB cap (32 KB
65
+ for the model tool), and closes on Esc with focus restored. It renders plain text; nothing is
66
+ re-interpreted as HTML. A slow read returns `timeout` after 2 seconds instead of a half result.
67
+
68
+ ## 5. Health checks
69
+
70
+ | Code | Fires when | Action |
71
+ | --- | --- | --- |
72
+ | `heavy-suite` | one suite is ≥25% of the first turn or ≥30k tokens | turn that suite off |
73
+ | `budget-gap` | the projection is above the saved budget | open the budget / drop the suggested suite |
74
+ | `catalog-truncated` | skill descriptions are cut at the catalog line length | read the affected skill |
75
+ | `locked-items` | items that cannot be switched off are ≥10% | jump to the manage list |
76
+ | `unknown-window` | no measurement yet, so occupancy is unknowable | — |
77
+ | `no-policy` | nothing has been switched off in this workspace | open settings |
78
+ | `empty-catalog` | the skill catalog is complete and empty | open settings |
79
+
80
+ Checks are a pure function of one snapshot (two refreshes cannot disagree). Up to six findings are
81
+ shown with a "more" line. Two contract codes, `duplicate-skill` and `tool-name-collision`, are
82
+ never emitted: this host build resolves duplicate names before the plugin can observe them, and
83
+ inventing a finding would be a lie.
84
+
85
+ ## 6. The insights tab
86
+
87
+ - **Trend** — one stacked bar per session, split by the five channels; 7 days / 30 days / all;
88
+ hover for values, click to pin, Esc to unpin, ←/→ by keyboard. Above 40 points the bars merge
89
+ into overview buckets so a long history does not become hairlines. Rows without a channel split
90
+ are striped, not zeroed. The durable-log backfill runs in the background (one pass per minute,
91
+ ≤8 sessions) so opening the tab never waits on it; a response may carry `backfilling: true` while
92
+ a pass is running, and the panel notes that older sessions are still being filled in.
93
+ - **Aggregate band** — sessions measured (shown as measured / known), average, peak, cumulative
94
+ saved.
95
+ - **Session cards** — search by id/title/directory; sort by recent / heaviest / most saved; the
96
+ current session is marked; a card opens that session in the manage list or its content.
97
+ - **Cross-session composition** — the five-channel ring averaged over sessions that have a split.
98
+ - **Heaviest suites** — the current session's suites by size, with the policy-removed part drawn
99
+ lighter.
100
+ - **Event timeline** — policy saves, presets, budget edits, imports, undos, compactions and prunes
101
+ for this session (`events.json`, capped at 300, up to 60 shown).
102
+ - **Coverage footnote** — recorded N of M sessions; the trend only contains what this plugin
103
+ measured plus a bounded log backfill.
104
+
105
+ ## 7. What a policy does, and when
106
+
107
+ A policy is one JSON file: per channel, `all`, `only [names]` or `except [names]`, plus an optional
108
+ persona prefix/suffix and a token budget.
109
+
110
+ It is applied exactly once, at `agent/created` with `source: startup|clear`. A session that already
111
+ exists is never rewritten mid-flight, so:
112
+
113
+ - the panel says whether *this* session was affected;
114
+ - "after policy" numbers are a projection for the next new session;
115
+ - undo restores the previous policy file, but still cannot retroactively change a live session.
116
+
117
+ ## 8. Suites
118
+
119
+ Items cluster by name: `mcp__<server>__<tool>` is one suite per MCP server; non-MCP tools cluster by
120
+ shared prefix; skills by provider; prompt sections and contexts by namespace, so an MCP server's
121
+ prompt section joins the same suite as its tools. One switch then means "the whole server", which is
122
+ the reason this plugin exists.
123
+
124
+ ## 9. Data and privacy
125
+
126
+ `policy.json` (switches and budget), `stats.json` (one measured row per session, with a channel
127
+ split from 2.0.0 on), `events.json` (append-only, 300 rows, policy metadata only — strings are
128
+ flattened and truncated to 200 characters, prompt text has no path in), and browser-local UI
129
+ preferences. No network requests, no telemetry, no uploads. Details: [FAQ](FAQ.md).
130
+
131
+ ## 10. What the model sees
132
+
133
+ The model-facing tool `context_injection` returns the same snapshot the panel renders, plus a short
134
+ "What you can do" block: which suite is the biggest win, whether this session predates the policy,
135
+ what compaction already removed, and the fact that the tool cannot flip switches. With
136
+ `{channel, name}` it returns one item's content instead (≤32 KB). It is read-only by design; every
137
+ write comes from a human click in the panel.
138
+
139
+ ## 11. Failure behaviour
140
+
141
+ - Host older than 0.2.2: banner, switches may not take effect, the numbers still render.
142
+ - Host HTTP contract older than v2: the new surfaces show a dismissible gate card (current /
143
+ minimum / dismiss) instead of silently disappearing; manage, settings and switches keep working.
144
+ - No measurement yet in this session: the window card says "window unknown" rather than guessing.
145
+ - A `compaction/*` event this build does not know: ignored (the receipt simply does not count it).
146
+ - `events.json` unreadable or absent: the timeline shows an empty state; policy saves still work.
147
+ - A content read that exceeds 2 seconds: the drawer shows the timeout and can retry.
148
+ - Policy file unreadable: the panel shows the error and keeps running with the all-on defaults;
149
+ `/inject` still prints the snapshot.
@@ -0,0 +1 @@
1
+ ![Injeção de contexto: muitas fontes reduzidas a uma única requisição](preview.svg)
@@ -0,0 +1 @@
1
+ ![Инъекция контекста: множество источников сходится в один запрос](preview.svg)
@@ -0,0 +1,105 @@
1
+ ![上下文注入:多条来源收束成一次首轮请求](preview.svg)
2
+
3
+ # 这个插件到底改了什么
4
+
5
+ 一个新会话在第一次请求到达模型之前,已经收到了一大堆东西:系统提示词段落、运行时上下文、以文本形式列出的技能目录、每个工具一个 JSON schema,还有 `AGENTS.md` 链。这些内容在对话里完全看不见,也没有一个统一的地方可以关掉。
6
+
7
+ 这页是五分钟版:插件量了什么、能关什么、关不掉什么,以及 2.0.0 新增的几块界面各显示什么。总览看 [README](../README.zh.md),实现细节看 [架构](ARCHITECTURE.md)。
8
+
9
+ ## 1. 三个数字,三个问题
10
+
11
+ | 数字 | 回答的问题 | 来源 |
12
+ | --- | --- | --- |
13
+ | 首轮注入(如 83.8k) | **下一个新会话**会被塞进多少东西 | 本插件自己装配:段落与上下文来自 `systemPrompt.assemble()`,技能来自 `skills.snapshot()`,工具 schema 来自 `tools.schemas()`,`AGENTS.md` 按默认链读取 |
14
+ | 上下文窗口占用(如 36%) | **当前这段对话**有多满 | 宿主自己的 `contextPressure` 投影 ÷ 模型窗口 |
15
+ | 内容原文(抽屉) | 某一行**到底写了什么** | 快照自己登记过的来源:装配文本、工具声明、技能文件/目录行、规则文件 |
16
+
17
+ 三者不可比,面板也从不拿一个去减另一个。第一个是插件能控制的部分,第二个决定宿主什么时候压缩,第三个只在你打开时才读。
18
+
19
+ 本插件的 token 是估算(ASCII ÷ 4,其他字符 ÷ 1.6)。占用率不是:`pressureTokens` 是 provider 上报的真实请求大小,窗口来自同一条请求记录。
20
+
21
+ ## 2. 三个页面,两个常驻入口
22
+
23
+ | 表面 | 用来干什么 |
24
+ | --- | --- |
25
+ | 管理 | 健康检查条、KPI、请求构成条,然后是套件清单与开关;每行可展开行内预览或打开原文 |
26
+ | 洞察 | 跨会话首轮趋势、聚合带、会话卡、跨会话构成、最重套件排行、本会话事件时间线、覆盖率脚注 |
27
+ | 设置 | 预设、四条通道总开关、自定义前言/后记、预算、导出导入、撤销历史、生效核对、插件偏好、版本与语言 |
28
+ | 输入框徽标 | 一行「首轮注入 + 窗口占用」,刻意低存在感;点 × 隐藏 |
29
+ | `/inject` 与 `context_injection` | 同样的数字的文本版,外加只读模型工具(可读单条原文) |
30
+
31
+ ## 3. 管理页显示什么
32
+
33
+ - **健康检查**:当前快照上的确定性检查(见第 5 节),每条都能点动作。
34
+ - **KPI**:首轮注入、带分母的上下文窗口占用、可关闭占比、当前预算;输入框徽标与它们是同一份数字。
35
+ - **请求构成条**:当前这次请求的系统/工具/消息构成,以及压缩回执,全部来自宿主投影。
36
+ - **管理清单**:五条通道,按套件聚类(一个 MCP server 一套),每条带「说明」列。组头有项目数、token、占比与三态开关;整组关掉后仍留在清单里(带「已关闭」标记与记住的体积),随时能开回来。条目可展开行内预览,「内容」按钮打开抽屉。
37
+
38
+ ## 4. 内容抽屉读什么
39
+
40
+ 只读快照自己登记过的来源——请求里不能指定任意路径:
41
+
42
+ | 行 | 内容 | 来源标注 |
43
+ | --- | --- | --- |
44
+ | 提示词段落 / 运行时上下文 | 装配出来的文本(没有单一文件) | 「来自系统提示词装配」 |
45
+ | 工具 schema | JSON 声明,拆成描述 / 参数表 / 原始 JSON 三视图 | 「来自会话快照」 |
46
+ | 技能 | 能定位就读 `SKILL.md` 正文,否则给目录里真正注入的那一行 | 「来自磁盘文件」或「技能目录条目」 |
47
+ | 工作区规则 | 真实的 `AGENTS.md` / `CLAUDE.md` 内容与路径 | 「来自磁盘文件」 |
48
+
49
+ 抽屉里有行号开关、内容内搜索(高亮 + 命中行摘要)、复制全文 / 复制路径、超过 256KB(模型工具 32KB)的截断提示、Esc 关闭、焦点回到打开它的那一行;全部按纯文本渲染,不会把内容当 HTML 解释。读取超过 2 秒就返回 `timeout`,不给半个结果。
50
+
51
+ ## 5. 健康检查
52
+
53
+ | code | 什么时候报 | 动作 |
54
+ | --- | --- | --- |
55
+ | `heavy-suite` | 某一套占首轮 ≥25% 或 ≥30k token | 关掉这一套 |
56
+ | `budget-gap` | 预测值超出已设预算 | 去设预算 / 关掉建议的那一套 |
57
+ | `catalog-truncated` | 技能描述被目录行长度截断 | 看那条技能的内容 |
58
+ | `locked-items` | 不可关条目占首轮 ≥10% | 去管理列表 |
59
+ | `unknown-window` | 还没有测量数据,占用率无从判断 | — |
60
+ | `no-policy` | 这个工作区从没动过策略 | 去设置 |
61
+ | `empty-catalog` | 技能目录是完整的空 | 去设置 |
62
+
63
+ 检查项是同一份快照的纯函数(两次刷新不会互相打架)。契约里另有两个 code(`duplicate-skill`、`tool-name-collision`)永远不会出现:这版宿主在插件能看到之前就把重名解析掉了,凭空报一条就是撒谎。
64
+
65
+ ## 6. 洞察页
66
+
67
+ - **趋势**:每个会话一根按五通道堆叠的柱子;近 7 天 / 近 30 天 / 全部;悬停看数值、点击钉住、Esc 取消、←/→ 切换。超过 40 个点合并成总览分组,避免柱宽被压成线;没有通道分解的行画斜纹,不补 0。历史日志回填在后台跑(每分钟一轮、每轮 ≤8 个会话),打开页面不等它;响应可能带 `backfilling: true`,面板会提示历史仍在补齐。
68
+ - **聚合带**:已测量会话(按「实测 / 全部」显示)、均值、峰值、累计可省。
69
+ - **会话卡**:按 id/标题/目录搜索;按最新 / 最重 / 可省最多排序;本会话有标记;点卡片跳到管理列表或直接看内容。
70
+ - **跨会话平均构成**:只统计有通道分解的会话,五通道构成环。
71
+ - **最重套件排行**:当前会话的套件体积,被策略关掉的部分画浅色。
72
+ - **事件时间线**:本会话的策略保存、预设、预算、导入、撤销、压缩、剪枝(`events.json`,上限 300 条,最多显示 60 条)。
73
+ - **覆盖率脚注**:已记录 N 个 / 本机共 M 个;趋势只包含本插件测过的与有限日志回填的。
74
+
75
+ ## 7. 策略什么时候生效
76
+
77
+ 策略就是一个 JSON:每个通道 `all`、`only [名单]` 或 `except [名单]`,外加可选的人设前言/后记与 token 预算。
78
+
79
+ 它只在 `agent/created` 且 `source` 为 `startup` / `clear` 时应用一次。已经在跑的会话永远不会被中途改写,所以:
80
+
81
+ - 面板会标明「本会话是否按策略处理」;
82
+ - 「策略后」的数字是**下一个新会话**的预估;
83
+ - 撤销恢复的是策略文件,同样不会追溯改掉活着的会话。
84
+
85
+ ## 8. 套件
86
+
87
+ 条目按名字聚类:`mcp__<server>__<tool>` 一个 MCP server 一套;非 MCP 工具按共同前缀;技能按 provider;段落与上下文按命名空间——所以某个 MCP server 的说明段落会和它的工具并进同一套。于是一个开关就是「整个 server」,这正是这插件存在的理由。
88
+
89
+ ## 9. 数据与隐私
90
+
91
+ `policy.json`(开关与预算)、`stats.json`(每会话一行测量,2.0.0 起含通道分解)、`events.json`(追加式事件流,300 条上限,只存策略元数据——字符串被拍平并截到 200 字符,会话正文没有入口能进来)、以及浏览器本地的界面偏好。不联网、不遥测、不上传。细节见[常见问题](FAQ.md)。
92
+
93
+ ## 10. 模型看到什么
94
+
95
+ 模型侧工具 `context_injection` 返回和面板完全相同的快照,外加一段「能做什么」:哪一套最划算、本会话是否在策略之前创建、宿主已经压缩掉多少、以及这个工具**不能**自己拨开关。带 `{channel, name}` 时改为返回单条原文(≤32KB)。按设计只读,所有写操作都来自人在面板里点。
96
+
97
+ ## 11. 出问题时会怎样
98
+
99
+ - 宿主低于 0.2.2:顶部提示,开关可能不生效,数字照常显示。
100
+ - 宿主 HTTP 契约低于 v2:新表面显示可关掉的 gate 卡(当前版本 / 最低要求 / 知道了),而不是静默消失;管理、设置和开关照常工作。
101
+ - 本会话还没有测量数据:窗口显示「未知」,不猜一个数。
102
+ - 收到本版本还不认识的 `compaction/*` 事件:忽略(回执只是不统计它)。
103
+ - `events.json` 读不到或不存在:时间线显示空态,策略保存不受影响。
104
+ - 内容读取超过 2 秒:抽屉显示超时并可重试。
105
+ - 策略文件读不了:面板显示错误,按全开继续跑;`/inject` 仍能打印快照。