dsh-capability-trimmer 0.0.0-stage → 1.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.en.md +37 -0
- package/README.md +36 -2
- package/client.js +1066 -0
- package/cordis.patch.yml +3 -0
- package/core.mjs +284 -0
- package/icon.svg +8 -0
- package/index.js +1071 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +56 -4
package/index.js
ADDED
|
@@ -0,0 +1,1071 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* capability-trimmer, Host half.
|
|
3
|
+
*
|
|
4
|
+
* Serves one JSON endpoint under the local web origin. The Client half is the
|
|
5
|
+
* settings page; it only renders and calls this endpoint.
|
|
6
|
+
*
|
|
7
|
+
* Two levers, both at the registry layer (v2 — the model never sees a
|
|
8
|
+
* disabled capability, and no filesystem move can be undone by sync):
|
|
9
|
+
*
|
|
10
|
+
* - Tools: this plugin's own state file is the persisted truth for disables,
|
|
11
|
+
* and enforcement is `agent.ctx.tools.restrict({deny})` per agent scope. A
|
|
12
|
+
* restricted-away global reads as absent — no schema in the model view, no
|
|
13
|
+
* call to deny in the first place. agent/created mounts it for every new
|
|
14
|
+
* agent, agents.list() is swept for live ones, and tools/change retries
|
|
15
|
+
* names whose MCP server registered late. A sibling `~/.dsh/tool-gate.json`
|
|
16
|
+
* (written by the separate tool-gate plugin, if installed) is merged
|
|
17
|
+
* read-only so its denies still show up — read, never written.
|
|
18
|
+
*
|
|
19
|
+
* - Skills: `ctx.skills.register()` plants a runtime shadow (rank 250,
|
|
20
|
+
* above the disk user layers 400/500) with invocation
|
|
21
|
+
* {modelInvocable:false, userInvocable:false}. The catalog filter and the
|
|
22
|
+
* skill loader both refuse it, so neither the model nor the user sees the
|
|
23
|
+
* skill, while the directory can be re-synced back freely — the shadow
|
|
24
|
+
* outranks it in the registry, not on disk.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, readlinkSync, renameSync, symlinkSync, unlinkSync, writeFileSync, readdirSync } from 'node:fs'
|
|
28
|
+
import { homedir } from 'node:os'
|
|
29
|
+
import { dirname, join } from 'node:path'
|
|
30
|
+
|
|
31
|
+
export const name = 'capability-trimmer'
|
|
32
|
+
export const inject = ['webServer', 'tools', 'skills', 'agents', 'workingDirectory']
|
|
33
|
+
|
|
34
|
+
/** The browser module id: DSH requires it to equal the package name. */
|
|
35
|
+
const PACKAGE_NAME = 'dsh-capability-trimmer'
|
|
36
|
+
|
|
37
|
+
const GATE_FILE = join(homedir(), '.dsh', 'tool-gate.json')
|
|
38
|
+
const STATE_FILE = join(homedir(), '.dsh', 'capability-trimmer.json')
|
|
39
|
+
const DISABLED_SKILLS = join(homedir(), '.dsh', 'skills-disabled')
|
|
40
|
+
const DIAG_FILE = join(homedir(), '.dsh', 'capability-trimmer.diag.json')
|
|
41
|
+
|
|
42
|
+
/** Same user-level roots DSH's filesystem skill provider reads: ~/.agents/skills
|
|
43
|
+
* and ~/.dsh/skills. Project-level, custom, and bundled roots depend on the
|
|
44
|
+
* session cwd and stay out of this global view; other harnesses' directories
|
|
45
|
+
* (~/.claude, ~/.cursor, …) are not part of the model's view at all. */
|
|
46
|
+
const SKILL_ROOTS = [
|
|
47
|
+
join(homedir(), '.agents', 'skills'),
|
|
48
|
+
join(homedir(), '.dsh', 'skills'),
|
|
49
|
+
]
|
|
50
|
+
|
|
51
|
+
const MAX_BODY = 64 * 1024
|
|
52
|
+
|
|
53
|
+
function readJSON(file, fallback) {
|
|
54
|
+
try {
|
|
55
|
+
return JSON.parse(readFileSync(file, 'utf8'))
|
|
56
|
+
} catch {
|
|
57
|
+
return fallback
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function writeJSON(file, value) {
|
|
62
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
63
|
+
writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`)
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** One-line description from SKILL.md frontmatter, or its first prose line. */
|
|
67
|
+
function describeSkill(dir) {
|
|
68
|
+
try {
|
|
69
|
+
const text = readFileSync(join(dir, 'SKILL.md'), 'utf8')
|
|
70
|
+
const front = text.match(/^---\n([\s\S]*?)\n---/)
|
|
71
|
+
if (front) {
|
|
72
|
+
const line = front[1].match(/^description:\s*(.+)$/m)
|
|
73
|
+
if (line) return line[1].replace(/^["']|["']$/g, '').slice(0, 240)
|
|
74
|
+
}
|
|
75
|
+
const prose = text.split('\n').find((row) => row.trim() && !row.startsWith('#') && !row.startsWith('---'))
|
|
76
|
+
return (prose ?? '').trim().slice(0, 240)
|
|
77
|
+
} catch {
|
|
78
|
+
return ''
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** 把新描述写回 SKILL.md frontmatter 的 description(单行双引号),返回写入的文件路径。 */
|
|
83
|
+
export function setSkillDescription(name, description) {
|
|
84
|
+
const record = skillInventory().find((row) => row.name === name)
|
|
85
|
+
if (!record || !record.dir) throw new Error(`找不到技能 ${name} 的本地目录`)
|
|
86
|
+
const safe = String(description).replace(/\s+/g, ' ').trim().slice(0, 240)
|
|
87
|
+
if (!safe) throw new Error('描述不能为空')
|
|
88
|
+
const file = join(record.dir, 'SKILL.md')
|
|
89
|
+
const text = readFileSync(file, 'utf8')
|
|
90
|
+
const line = `description: ${JSON.stringify(safe)}`
|
|
91
|
+
let out
|
|
92
|
+
const front = text.match(/^---\n([\s\S]*?)\n---/)
|
|
93
|
+
if (front) {
|
|
94
|
+
const lines = front[1].split('\n')
|
|
95
|
+
const at = lines.findIndex((row) => /^description:/.test(row))
|
|
96
|
+
if (at === -1) {
|
|
97
|
+
lines.unshift(line)
|
|
98
|
+
} else {
|
|
99
|
+
let end = at + 1
|
|
100
|
+
// 块标量(description: | / >):连同后续缩进行一起替换
|
|
101
|
+
if (/^description:\s*[|>]/.test(lines[at])) {
|
|
102
|
+
while (end < lines.length) {
|
|
103
|
+
if (lines[end].trim() === '' || /^\s/.test(lines[end])) { end += 1; continue }
|
|
104
|
+
break
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
lines.splice(at, end - at, line)
|
|
108
|
+
}
|
|
109
|
+
out = `---\n${lines.join('\n')}\n---` + text.slice(front[0].length)
|
|
110
|
+
} else {
|
|
111
|
+
out = `---\n${line}\n---\n\n${text}`
|
|
112
|
+
}
|
|
113
|
+
writeFileSync(file, out)
|
|
114
|
+
return file
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
export function skillInventory() {
|
|
119
|
+
const byName = new Map()
|
|
120
|
+
for (const root of SKILL_ROOTS) {
|
|
121
|
+
let entries
|
|
122
|
+
try {
|
|
123
|
+
entries = readdirSync(root, { withFileTypes: true })
|
|
124
|
+
} catch {
|
|
125
|
+
continue
|
|
126
|
+
}
|
|
127
|
+
for (const entry of entries) {
|
|
128
|
+
const dir = join(root, entry.name)
|
|
129
|
+
if (!existsSync(join(dir, 'SKILL.md'))) continue
|
|
130
|
+
if (!byName.has(entry.name)) byName.set(entry.name, { name: entry.name, copies: [], description: '', dir: '' })
|
|
131
|
+
const record = byName.get(entry.name)
|
|
132
|
+
if (!record.dir) record.dir = dir
|
|
133
|
+
const link = lstatSync(dir).isSymbolicLink()
|
|
134
|
+
record.copies.push({ root: root.replace(homedir(), '~'), link })
|
|
135
|
+
if (!record.description) record.description = describeSkill(dir)
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name))
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const escapeRe = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
142
|
+
|
|
143
|
+
/** 一个技能的全部说明文本:SKILL.md 正文 + references/ 下的 markdown。 */
|
|
144
|
+
function readCorpus(dir) {
|
|
145
|
+
const parts = []
|
|
146
|
+
try {
|
|
147
|
+
parts.push(readFileSync(join(dir, 'SKILL.md'), 'utf8'))
|
|
148
|
+
} catch {}
|
|
149
|
+
try {
|
|
150
|
+
for (const file of readdirSync(join(dir, 'references'))) {
|
|
151
|
+
if (!file.endsWith('.md')) continue
|
|
152
|
+
try {
|
|
153
|
+
parts.push(readFileSync(join(dir, 'references', file), 'utf8'))
|
|
154
|
+
} catch {}
|
|
155
|
+
}
|
|
156
|
+
} catch {}
|
|
157
|
+
return parts.join('\n')
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* 上下游关系是文本层面的:扫描每个已启用技能的正文,统计它点名了哪些工具与技能。
|
|
162
|
+
* 这只能证明“文档里写了”,不能证明运行时一定调用;但对“禁用后哪个技能会退化”,
|
|
163
|
+
* 这是唯一可靠的信号。全名总是算数;短名至少 6 字符,避免 read/edit 之类的误报。
|
|
164
|
+
*
|
|
165
|
+
* 三张表:
|
|
166
|
+
* toolUse / skillUse —— 谁引用了它(上游),Map<目标, Map<引用者, 命中次数>>
|
|
167
|
+
* refsBy —— 它引用了谁(下游),Map<技能, Map<目标, 命中次数>>
|
|
168
|
+
*/
|
|
169
|
+
export function crossReference(skills, mcps) {
|
|
170
|
+
const corpora = []
|
|
171
|
+
for (const skill of skills) {
|
|
172
|
+
if (!skill.enabled || !skill.dir) continue
|
|
173
|
+
const text = readCorpus(skill.dir)
|
|
174
|
+
if (text) corpora.push({ name: skill.name, text })
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const toolKeys = new Map()
|
|
178
|
+
const kindOf = new Map()
|
|
179
|
+
for (const mcp of mcps) {
|
|
180
|
+
for (const tool of mcp.tools) {
|
|
181
|
+
toolKeys.set(tool.name, [...(toolKeys.get(tool.name) ?? []), tool.name])
|
|
182
|
+
kindOf.set(tool.name, 'tool')
|
|
183
|
+
if (tool.tool.length >= 6) toolKeys.set(tool.tool, [...(toolKeys.get(tool.tool) ?? []), tool.name])
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
for (const skill of skills) kindOf.set(skill.name, 'skill')
|
|
187
|
+
const skillNames = skills.filter((skill) => skill.enabled).map((skill) => skill.name)
|
|
188
|
+
|
|
189
|
+
// 长名在前:否则 db_get 会吃掉 db_get_enum 的匹配
|
|
190
|
+
const byLength = (a, b) => b.length - a.length
|
|
191
|
+
const toolRe = toolKeys.size
|
|
192
|
+
? new RegExp(`\\b(${[...toolKeys.keys()].sort(byLength).map(escapeRe).join('|')})\\b`, 'g')
|
|
193
|
+
: null
|
|
194
|
+
const skillRe = skillNames.length
|
|
195
|
+
? new RegExp(`\\b(${skillNames.slice().sort(byLength).map(escapeRe).join('|')})\\b`, 'g')
|
|
196
|
+
: null
|
|
197
|
+
|
|
198
|
+
const bump = (map, outer, inner) => {
|
|
199
|
+
if (!map.has(outer)) map.set(outer, new Map())
|
|
200
|
+
const row = map.get(outer)
|
|
201
|
+
row.set(inner, (row.get(inner) ?? 0) + 1)
|
|
202
|
+
}
|
|
203
|
+
const toolUse = new Map()
|
|
204
|
+
const skillUse = new Map()
|
|
205
|
+
const refsBy = new Map()
|
|
206
|
+
for (const { name, text } of corpora) {
|
|
207
|
+
if (toolRe) {
|
|
208
|
+
for (const match of text.matchAll(toolRe)) {
|
|
209
|
+
for (const full of toolKeys.get(match[1]) ?? []) {
|
|
210
|
+
bump(toolUse, full, name)
|
|
211
|
+
bump(refsBy, name, full)
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (skillRe) {
|
|
216
|
+
for (const match of text.matchAll(skillRe)) {
|
|
217
|
+
if (match[1] === name) continue
|
|
218
|
+
bump(skillUse, match[1], name)
|
|
219
|
+
bump(refsBy, name, match[1])
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
return { toolUse, skillUse, refsBy, kindOf }
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** 命中次数 → 强度档。阈值是经验值,页面上要明示口径。 */
|
|
227
|
+
export const strengthOf = (hits) => (hits >= 3 ? 'must' : hits >= 2 ? 'often' : 'optional')
|
|
228
|
+
|
|
229
|
+
/** 引用明细:名字 + 命中次数 + 强度档,按次数降序。确认框用它分档警示。 */
|
|
230
|
+
const detailOf = (map) => [...(map ?? new Map()).entries()]
|
|
231
|
+
.map(([name, hits]) => ({ name, hits, strength: strengthOf(hits) }))
|
|
232
|
+
.sort((a, b) => b.hits - a.hits || a.name.localeCompare(b.name))
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* v2: 禁用不再动文件系统。持久层只记名字,运行时由注册表影子压制;
|
|
237
|
+
* 旧的 move/unlink undo log 保留,enable 时仍可重放(目录可能真被移走过)。
|
|
238
|
+
*/
|
|
239
|
+
function disableSkill(name, state) {
|
|
240
|
+
state.disabledSkills[name] = state.disabledSkills[name] ?? []
|
|
241
|
+
return 0
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function disableSkillLegacy(name, state) {
|
|
245
|
+
const actions = []
|
|
246
|
+
for (const root of SKILL_ROOTS) {
|
|
247
|
+
const dir = join(root, name)
|
|
248
|
+
let stat
|
|
249
|
+
try {
|
|
250
|
+
stat = lstatSync(dir)
|
|
251
|
+
} catch {
|
|
252
|
+
continue
|
|
253
|
+
}
|
|
254
|
+
if (stat.isSymbolicLink()) {
|
|
255
|
+
const target = readlinkSync(dir)
|
|
256
|
+
unlinkSync(dir)
|
|
257
|
+
actions.push({ type: 'unlink', path: dir, target })
|
|
258
|
+
continue
|
|
259
|
+
}
|
|
260
|
+
mkdirSync(DISABLED_SKILLS, { recursive: true })
|
|
261
|
+
let target = join(DISABLED_SKILLS, name)
|
|
262
|
+
for (let i = 2; existsSync(target); i += 1) target = join(DISABLED_SKILLS, `${name}__${i}`)
|
|
263
|
+
renameSync(dir, target)
|
|
264
|
+
actions.push({ type: 'move', from: dir, to: target })
|
|
265
|
+
}
|
|
266
|
+
state.disabledSkills[name] = actions
|
|
267
|
+
return actions.length
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Replay a disable's actions backwards. A root that already came back is skipped. */
|
|
271
|
+
function enableSkill(name, state) {
|
|
272
|
+
const actions = state.disabledSkills[name] ?? []
|
|
273
|
+
for (const action of [...actions].reverse()) {
|
|
274
|
+
try {
|
|
275
|
+
if (action.type === 'unlink') {
|
|
276
|
+
if (!existsSync(action.path)) symlinkSync(action.target, action.path, 'dir')
|
|
277
|
+
} else if (existsSync(action.to)) {
|
|
278
|
+
mkdirSync(dirname(action.from), { recursive: true })
|
|
279
|
+
renameSync(action.to, action.from)
|
|
280
|
+
}
|
|
281
|
+
} catch {
|
|
282
|
+
// Left in place; the inventory read reports the true state next time.
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
delete state.disabledSkills[name]
|
|
286
|
+
return actions.length
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
let runtimeState
|
|
290
|
+
|
|
291
|
+
/**
|
|
292
|
+
* ── 注册表层禁用(root fix)───────────────────────────────────────────
|
|
293
|
+
* 旧机制:移技能目录 + 执行时 guard 拦截。两个缺陷:同步器会把目录铺回来;
|
|
294
|
+
* 被拦工具对模型仍可见(白白占上下文,模型还会尝试调用)。
|
|
295
|
+
* 新机制:技能在 skills 注册表挂 runtime 影子(rank 250 压过磁盘 user 层
|
|
296
|
+
* 400/500,invocation 双 false → 目录与 skill 工具双双拒绝);工具在每个
|
|
297
|
+
* agent 的 scope 上 restrict(reads as absent,模型视野直接没有)。
|
|
298
|
+
* 目录爱被谁同步回来都无所谓——影子在注册表层压着。
|
|
299
|
+
*/
|
|
300
|
+
|
|
301
|
+
const RESTRICT_LOG = new Set()
|
|
302
|
+
|
|
303
|
+
/** 对一个 agent scope 挂工具 restriction。未知名(如 MCP 尚未连上)跳过并留待 tools/change 重试。 */
|
|
304
|
+
function restrictAgentTools(ctx, agent, disposers) {
|
|
305
|
+
const deny = deniedTools()
|
|
306
|
+
if (deny.length === 0 || !agent?.ctx?.tools) return
|
|
307
|
+
const known = new Set(ctx.tools.schemas().map((schema) => schema.name))
|
|
308
|
+
const applicable = deny.filter((name) => known.has(name))
|
|
309
|
+
const pending = deny.filter((name) => !known.has(name))
|
|
310
|
+
for (const name of pending) {
|
|
311
|
+
if (!RESTRICT_LOG.has(name)) {
|
|
312
|
+
RESTRICT_LOG.add(name)
|
|
313
|
+
ctx.logger?.warn?.(`capability-trimmer: tool "${name}" not yet in global registry; will retry on tools/change`)
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
if (applicable.length === 0) return
|
|
317
|
+
try {
|
|
318
|
+
const dispose = agent.ctx.tools.restrict({ deny: applicable })
|
|
319
|
+
disposers.set(agent.id, dispose)
|
|
320
|
+
} catch (error) {
|
|
321
|
+
ctx.logger?.warn?.(`capability-trimmer: restrict failed for agent ${agent.id}: ${error instanceof Error ? error.message : String(error)}`)
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** 重建所有存活 agent 的 restriction。restrictions 只会相交,所以整组 dispose 再重挂。 */
|
|
326
|
+
function rebuildToolRestrictions(ctx) {
|
|
327
|
+
const deny = deniedTools()
|
|
328
|
+
for (const [id, dispose] of runtimeState.toolDisposers) {
|
|
329
|
+
try {
|
|
330
|
+
dispose()
|
|
331
|
+
} catch {
|
|
332
|
+
// Agent may already be gone; the next agent/disposed sweep clears it.
|
|
333
|
+
}
|
|
334
|
+
runtimeState.toolDisposers.delete(id)
|
|
335
|
+
}
|
|
336
|
+
if (deny.length === 0) return
|
|
337
|
+
for (const agent of ctx.agents.list()) {
|
|
338
|
+
restrictAgentTools(ctx, agent, runtimeState.toolDisposers)
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* 给一个被禁技能挂 runtime 影子,注册进 agent 自己的 scope 层。
|
|
344
|
+
* 注册表是"nearest layer wins outright":agent 层比全局层/用户层/任何外层都近,
|
|
345
|
+
* 所以这里的同名影子无条件压过磁盘条目和其他运行时注册,修复了全局层影子
|
|
346
|
+
* 被更近 scope 层(或更晚注册的同名条目)穿透的泄漏。
|
|
347
|
+
* agent.ctx 拿不到 skills 时回退注册到全局层(旧行为,聊胜于无)。
|
|
348
|
+
*/
|
|
349
|
+
function registerSkillShadowForAgent(ctx, agent, name, disposers) {
|
|
350
|
+
const key = agent ? agent.id + ':g:' + name : 'global:g:' + name
|
|
351
|
+
if (disposers.has(key)) return
|
|
352
|
+
const register = (target) => target.skills.register({
|
|
353
|
+
name,
|
|
354
|
+
description: SHADOW_DESC,
|
|
355
|
+
whenToUse: '此技能已被禁用:影子条目占住名字,模型目录与 skill 工具都不会加载它。',
|
|
356
|
+
invocation: { modelInvocable: false, userInvocable: false },
|
|
357
|
+
})
|
|
358
|
+
try {
|
|
359
|
+
if (agent?.ctx?.skills) {
|
|
360
|
+
runtimeState.shadowPaths.set(key, 'agent-layer')
|
|
361
|
+
disposers.set(key, register(agent.ctx))
|
|
362
|
+
} else {
|
|
363
|
+
runtimeState.shadowPaths.set(key, 'global-fallback')
|
|
364
|
+
disposers.set(key, register(ctx))
|
|
365
|
+
if (!RESTRICT_LOG.has('shadow-global:' + name)) {
|
|
366
|
+
RESTRICT_LOG.add('shadow-global:' + name)
|
|
367
|
+
ctx.logger?.warn?.(`capability-trimmer: agent ctx lacks skills; shadow "${name}" fell back to global layer`)
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
} catch (error) {
|
|
371
|
+
runtimeState.shadowPaths.set(key, 'register-failed')
|
|
372
|
+
ctx.logger?.warn?.(`capability-trimmer: skill shadow "${name}" failed: ${error instanceof Error ? error.message : String(error)}`)
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** 按持久层事实源重建:全卸再重挂,每个存活 agent 一份 agent 层影子。 */
|
|
377
|
+
function rebuildSkillShadows(ctx) {
|
|
378
|
+
const disabled = Object.keys(readJSON(STATE_FILE, { disabledSkills: {} }).disabledSkills ?? {})
|
|
379
|
+
const disposers = runtimeState.skillShadowDisposers
|
|
380
|
+
for (const [key, dispose] of [...disposers.entries()]) {
|
|
381
|
+
try {
|
|
382
|
+
dispose()
|
|
383
|
+
} catch {
|
|
384
|
+
// Fiber teardown may already have disposed it.
|
|
385
|
+
}
|
|
386
|
+
disposers.delete(key)
|
|
387
|
+
}
|
|
388
|
+
if (disabled.length === 0) return
|
|
389
|
+
for (const agent of ctx.agents.list()) {
|
|
390
|
+
for (const name of disabled) registerSkillShadowForAgent(ctx, agent, name, disposers)
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/** 一次性把运行时态(影子 + restriction)对齐到持久层,并触发影子压制审计。 */
|
|
395
|
+
function applyRuntime(ctx) {
|
|
396
|
+
rebuildSkillShadows(ctx)
|
|
397
|
+
rebuildToolRestrictions(ctx)
|
|
398
|
+
void auditSkillShadows(ctx)
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/**
|
|
402
|
+
* 影子压制审计:按每个存活 agent 的视角查一遍禁用技能是否真的被压住
|
|
403
|
+
* (skills.list({scope: agent}) 与 skill 工具/目录快照同口径),
|
|
404
|
+
* 结果落盘到 shadow-audit 文件,供诊断“禁了还能加载”的泄漏到底漏在哪一层。
|
|
405
|
+
*/
|
|
406
|
+
const SHADOW_AUDIT_FILE = join(homedir(), '.dsh', 'capability-trimmer.shadow-audit.json')
|
|
407
|
+
const SHADOW_DESC = '已由能力裁剪禁用(注册表层影子覆盖)'
|
|
408
|
+
let shadowAuditSeq = 0
|
|
409
|
+
async function auditSkillShadows(ctx) {
|
|
410
|
+
const seq = ++shadowAuditSeq
|
|
411
|
+
const disabled = Object.keys(readJSON(STATE_FILE, { disabledSkills: {} }).disabledSkills ?? {})
|
|
412
|
+
if (disabled.length === 0) return
|
|
413
|
+
const agents = ctx.agents.list()
|
|
414
|
+
const cwdOf = async (agent) => {
|
|
415
|
+
try {
|
|
416
|
+
return await ctx.workingDirectory?.ensure?.(agent)
|
|
417
|
+
} catch {
|
|
418
|
+
return undefined
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
// 与 skill 工具同口径:scope=agent + cwd。缺 cwd 会让 fs provider 被跳过,视图不可信。
|
|
422
|
+
const checkView = async (agent, cwd) => {
|
|
423
|
+
const lookup = agent === undefined ? (cwd === undefined ? {} : { cwd }) : { scope: agent, ...(cwd === undefined ? {} : { cwd }) }
|
|
424
|
+
const view = await ctx.skills.list(lookup)
|
|
425
|
+
const result = {}
|
|
426
|
+
for (const name of disabled) {
|
|
427
|
+
const row = view.find((row) => row.name === name)
|
|
428
|
+
result[name] = !row || row.invocation?.modelInvocable === false || row.description === SHADOW_DESC
|
|
429
|
+
}
|
|
430
|
+
return result
|
|
431
|
+
}
|
|
432
|
+
const perAgent = []
|
|
433
|
+
for (const agent of agents) {
|
|
434
|
+
const entry = { id: agent?.id ?? 'unknown' }
|
|
435
|
+
try {
|
|
436
|
+
entry.suppressed = await checkView(agent, await cwdOf(agent))
|
|
437
|
+
} catch (cause) {
|
|
438
|
+
entry.error = cause instanceof Error ? cause.message : String(cause)
|
|
439
|
+
}
|
|
440
|
+
perAgent.push(entry)
|
|
441
|
+
}
|
|
442
|
+
let globalView = null
|
|
443
|
+
if (agents.length > 0) {
|
|
444
|
+
try {
|
|
445
|
+
globalView = await checkView(undefined, await cwdOf(agents[0]))
|
|
446
|
+
} catch {
|
|
447
|
+
globalView = null
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
if (seq !== shadowAuditSeq) return
|
|
451
|
+
const shadowPaths = {}
|
|
452
|
+
for (const [key, path] of runtimeState.shadowPaths.entries()) shadowPaths[key] = path
|
|
453
|
+
try {
|
|
454
|
+
writeFileSync(SHADOW_AUDIT_FILE, JSON.stringify({ at: new Date().toISOString(), agentCount: agents.length, shadowPaths, globalView, agents: perAgent }, null, 2))
|
|
455
|
+
} catch {
|
|
456
|
+
// 审计写盘失败不影响主流程。
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* Deny entries as a Map(tool → use). Own state file is the source of truth;
|
|
461
|
+
* the sibling tool-gate plugin's file is merged read-only for interop.
|
|
462
|
+
* Accepts both the string and object entry forms in either file.
|
|
463
|
+
*/
|
|
464
|
+
function denyEntries() {
|
|
465
|
+
const out = new Map()
|
|
466
|
+
const collect = (entries) => {
|
|
467
|
+
for (const entry of entries ?? []) {
|
|
468
|
+
const tool = typeof entry === 'string' ? entry : entry?.tool
|
|
469
|
+
if (typeof tool !== 'string' || !tool || out.has(tool)) continue
|
|
470
|
+
out.set(tool, typeof entry === 'object' && entry?.use ? String(entry.use) : '')
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
collect(readJSON(STATE_FILE, {}).deniedTools)
|
|
474
|
+
collect(readJSON(GATE_FILE, { deny: [] }).deny)
|
|
475
|
+
return out
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function deniedTools() {
|
|
479
|
+
return [...denyEntries().keys()]
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
export function setToolEnabled(tool, enabled, use = '') {
|
|
483
|
+
const state = readJSON(STATE_FILE, {})
|
|
484
|
+
const deny = (state.deniedTools ?? []).filter((entry) => entry?.tool !== tool)
|
|
485
|
+
if (!enabled) {
|
|
486
|
+
deny.push({
|
|
487
|
+
tool,
|
|
488
|
+
reason: use ? `与 ${use} 职责重合,保留后者` : '在能力裁剪页关闭',
|
|
489
|
+
use,
|
|
490
|
+
})
|
|
491
|
+
}
|
|
492
|
+
state.deniedTools = deny
|
|
493
|
+
writeJSON(STATE_FILE, state)
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* One mode's skill view.
|
|
498
|
+
*
|
|
499
|
+
* The mode is a preset composition, and compositionInventory() is the only
|
|
500
|
+
* honest source for it: it lists that preset's plugin rows with each row's
|
|
501
|
+
* enablement. The skill list itself comes from the skill roots on disk, because
|
|
502
|
+
* no registry exposes a per-mode skill set without an Agent context.
|
|
503
|
+
*/
|
|
504
|
+
/** /mode 时算好的交叉引用缓存在这里;/graph 只读,不重扫语料。 */
|
|
505
|
+
export const xrefCache = { at: 0, toolUse: null, skillUse: null, refsBy: null, kindOf: null, labels: null }
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* 一个能力的上下游图。上游=谁在正文里点名它,下游=它的正文点名了谁。
|
|
509
|
+
* 强度按命中次数分档:≥3 必须 / 2 常用 / 1 可有可无——阈值是经验值,
|
|
510
|
+
* 页面上明示口径,不冒充客观真理。
|
|
511
|
+
*/
|
|
512
|
+
export function buildGraph(kind, name) {
|
|
513
|
+
const { toolUse, skillUse, refsBy, kindOf, labels } = xrefCache
|
|
514
|
+
const meta = (target) => ({
|
|
515
|
+
name: target,
|
|
516
|
+
kind: kindOf?.get(target) ?? 'skill',
|
|
517
|
+
label: labels?.get(target)?.label ?? target,
|
|
518
|
+
server: labels?.get(target)?.server ?? null,
|
|
519
|
+
hits: 0,
|
|
520
|
+
strength: 'optional',
|
|
521
|
+
})
|
|
522
|
+
const upstreamMap = kind === 'skill' ? skillUse?.get(name) : toolUse?.get(name)
|
|
523
|
+
const upstream = [...(upstreamMap ?? new Map()).entries()]
|
|
524
|
+
.map(([who, hits]) => ({ ...meta(who), hits, strength: strengthOf(hits) }))
|
|
525
|
+
.sort((a, b) => b.hits - a.hits || a.label.localeCompare(b.label))
|
|
526
|
+
const downstream = kind === 'skill'
|
|
527
|
+
? [...(refsBy?.get(name) ?? new Map()).entries()]
|
|
528
|
+
.map(([target, hits]) => ({ ...meta(target), hits, strength: strengthOf(hits) }))
|
|
529
|
+
.sort((a, b) => b.hits - a.hits || a.label.localeCompare(b.label))
|
|
530
|
+
: []
|
|
531
|
+
return {
|
|
532
|
+
kind,
|
|
533
|
+
name,
|
|
534
|
+
label: labels?.get(name)?.label ?? name,
|
|
535
|
+
description: xrefCache.descOf?.get(name) ?? '',
|
|
536
|
+
upstream,
|
|
537
|
+
downstream,
|
|
538
|
+
at: xrefCache.at || null,
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
async function buildMode(ctx, presetId) {
|
|
543
|
+
const state = readJSON(STATE_FILE, { disabledSkills: {} })
|
|
544
|
+
state.disabledSkills ??= {}
|
|
545
|
+
const skills = skillInventory().map((skill) => ({
|
|
546
|
+
...skill,
|
|
547
|
+
enabled: !(skill.name in state.disabledSkills),
|
|
548
|
+
}))
|
|
549
|
+
|
|
550
|
+
let preset = null
|
|
551
|
+
let skillRows = []
|
|
552
|
+
let plugins = []
|
|
553
|
+
let error = null
|
|
554
|
+
try {
|
|
555
|
+
const service = ctx.get?.('agentPresets')
|
|
556
|
+
const inventory = (await service?.compositionInventory?.()) ?? []
|
|
557
|
+
const roster = (await service?.list?.()) ?? []
|
|
558
|
+
const picked = inventory.find((row) => row.id === presetId)
|
|
559
|
+
?? inventory.find((row) => row.isDefault)
|
|
560
|
+
?? inventory[0]
|
|
561
|
+
?? null
|
|
562
|
+
if (picked) {
|
|
563
|
+
const meta = roster.find((row) => row.id === picked.id)
|
|
564
|
+
preset = { id: picked.id, name: meta?.name ?? picked.name ?? picked.id, isDefault: Boolean(picked.isDefault) }
|
|
565
|
+
plugins = (picked.rows ?? []).map((row) => ({
|
|
566
|
+
module: row.moduleName,
|
|
567
|
+
enabled: row.enabled === true,
|
|
568
|
+
condition: row.condition ?? null,
|
|
569
|
+
}))
|
|
570
|
+
skillRows = plugins.filter((row) => /skill/i.test(row.module))
|
|
571
|
+
}
|
|
572
|
+
} catch (cause) {
|
|
573
|
+
error = cause instanceof Error ? cause.message : String(cause)
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
const skillProviderOn = skillRows.length === 0 ? true : skillRows.some((row) => row.enabled)
|
|
577
|
+
|
|
578
|
+
// MCP tools live in the tool registry under mcp__<server>__<tool>; the registry
|
|
579
|
+
// has no per-server object, so the name is the only grouping key there is.
|
|
580
|
+
const useOf = denyEntries()
|
|
581
|
+
const denied = new Set(useOf.keys())
|
|
582
|
+
const byServer = new Map()
|
|
583
|
+
try {
|
|
584
|
+
for (const schema of ctx.tools.schemas()) {
|
|
585
|
+
if (!schema.name.startsWith('mcp__')) continue
|
|
586
|
+
const rest = schema.name.slice('mcp__'.length)
|
|
587
|
+
const cut = rest.indexOf('__')
|
|
588
|
+
const server = cut < 0 ? rest : rest.slice(0, cut)
|
|
589
|
+
if (!byServer.has(server)) byServer.set(server, [])
|
|
590
|
+
byServer.get(server).push({
|
|
591
|
+
name: schema.name,
|
|
592
|
+
tool: cut < 0 ? rest : rest.slice(cut + 2),
|
|
593
|
+
description: (schema.description ?? '').slice(0, 200),
|
|
594
|
+
enabled: !denied.has(schema.name),
|
|
595
|
+
use: useOf.get(schema.name) ?? '',
|
|
596
|
+
})
|
|
597
|
+
}
|
|
598
|
+
} catch (cause) {
|
|
599
|
+
error ??= cause instanceof Error ? cause.message : String(cause)
|
|
600
|
+
}
|
|
601
|
+
const mcps = [...byServer.entries()]
|
|
602
|
+
.map(([server, tools]) => ({
|
|
603
|
+
server,
|
|
604
|
+
tools: tools.sort((a, b) => a.tool.localeCompare(b.tool)),
|
|
605
|
+
on: tools.filter((tool) => tool.enabled).length,
|
|
606
|
+
}))
|
|
607
|
+
.sort((a, b) => b.tools.length - a.tools.length)
|
|
608
|
+
|
|
609
|
+
const { toolUse, skillUse, refsBy, kindOf } = crossReference(skills, mcps)
|
|
610
|
+
const labels = new Map()
|
|
611
|
+
const descOf = new Map()
|
|
612
|
+
for (const skill of skills) {
|
|
613
|
+
labels.set(skill.name, { label: skill.name, kind: 'skill' })
|
|
614
|
+
descOf.set(skill.name, skill.description ?? '')
|
|
615
|
+
}
|
|
616
|
+
for (const mcp of mcps) {
|
|
617
|
+
for (const tool of mcp.tools) {
|
|
618
|
+
labels.set(tool.name, { label: tool.tool, kind: 'tool', server: mcp.server })
|
|
619
|
+
descOf.set(tool.name, tool.description ?? '')
|
|
620
|
+
tool.usedBy = [...(toolUse.get(tool.name) ?? new Map()).keys()]
|
|
621
|
+
tool.usedByDetail = detailOf(toolUse.get(tool.name))
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
for (const skill of skills) {
|
|
625
|
+
skill.usedBy = [...(skillUse.get(skill.name) ?? new Map()).keys()]
|
|
626
|
+
skill.usedByDetail = detailOf(skillUse.get(skill.name))
|
|
627
|
+
}
|
|
628
|
+
Object.assign(xrefCache, { at: Date.now(), toolUse, skillUse, refsBy, kindOf, labels, descOf })
|
|
629
|
+
|
|
630
|
+
// 重合检测复用 capability-audit 的算法,只把语料换成当前模式里启用的能力。
|
|
631
|
+
// 插件行不参与:它们的模块名没有描述,算出来的相似度只是噪音。
|
|
632
|
+
state.ignoredPairs ??= []
|
|
633
|
+
const ignored = new Set(state.ignoredPairs)
|
|
634
|
+
let overlaps = []
|
|
635
|
+
try {
|
|
636
|
+
const module = await import(new URL('./core.mjs', import.meta.url).href)
|
|
637
|
+
const lookup = new Map()
|
|
638
|
+
const records = []
|
|
639
|
+
for (const skill of skills) {
|
|
640
|
+
if (!skill.enabled) continue
|
|
641
|
+
lookup.set(skill.name, { kind: 'skill', name: skill.name, description: skill.description ?? '' })
|
|
642
|
+
records.push({ kind: 'skill', label: skill.name, description: skill.description ?? '', source: 'skills' })
|
|
643
|
+
}
|
|
644
|
+
for (const mcp of mcps) {
|
|
645
|
+
for (const tool of mcp.tools) {
|
|
646
|
+
if (!tool.enabled) continue
|
|
647
|
+
lookup.set(tool.tool, { kind: 'tool', name: tool.name, description: tool.description ?? '' })
|
|
648
|
+
records.push({ kind: 'tool', label: tool.tool, description: tool.description ?? '', source: mcp.server })
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
const result = module.audit(records, { minScore: 0.25, top: 20 })
|
|
652
|
+
const dependentsMapOf = (side) => (side.kind === 'skill'
|
|
653
|
+
? skillUse.get(side.name)
|
|
654
|
+
: toolUse.get(side.name))
|
|
655
|
+
overlaps = result.pairs.filter((pair) => !ignored.has(`${pair.left}\u0000${pair.right}`)).map((pair) => {
|
|
656
|
+
const left = { label: pair.left, ...(lookup.get(pair.left) ?? { kind: pair.leftKind, name: pair.left }) }
|
|
657
|
+
const right = { label: pair.right, ...(lookup.get(pair.right) ?? { kind: pair.rightKind, name: pair.right }) }
|
|
658
|
+
const leftMap = dependentsMapOf(left)
|
|
659
|
+
const rightMap = dependentsMapOf(right)
|
|
660
|
+
const leftDeps = [...(leftMap ?? new Map()).keys()]
|
|
661
|
+
const rightDeps = [...(rightMap ?? new Map()).keys()]
|
|
662
|
+
return {
|
|
663
|
+
key: `${pair.left}\u0000${pair.right}`,
|
|
664
|
+
left: { ...left, usedBy: leftDeps, usedByDetail: detailOf(leftMap) },
|
|
665
|
+
right: { ...right, usedBy: rightDeps, usedByDetail: detailOf(rightMap) },
|
|
666
|
+
bothMention: leftDeps.filter((name) => rightDeps.includes(name)),
|
|
667
|
+
score: pair.score,
|
|
668
|
+
reasons: pair.reasons,
|
|
669
|
+
}
|
|
670
|
+
})
|
|
671
|
+
} catch (cause) {
|
|
672
|
+
// 缺少旁路的 core.mjs 时降级为“没有重合”,不影响其余功能
|
|
673
|
+
overlaps = []
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
return {
|
|
677
|
+
preset,
|
|
678
|
+
plugins,
|
|
679
|
+
mcps,
|
|
680
|
+
overlaps,
|
|
681
|
+
ignoredOverlaps: (state.ignoredPairs ?? []).map((key) => {
|
|
682
|
+
const [left, right] = key.split('\u0000')
|
|
683
|
+
return { key, left, right }
|
|
684
|
+
}),
|
|
685
|
+
overlapFloor: 0.25,
|
|
686
|
+
skillProviderOn,
|
|
687
|
+
error,
|
|
688
|
+
skills: skills.map(({ dir, ...rest }) => rest),
|
|
689
|
+
counts: {
|
|
690
|
+
plugins: plugins.length,
|
|
691
|
+
pluginsOn: plugins.filter((row) => row.enabled).length,
|
|
692
|
+
skills: skills.length,
|
|
693
|
+
skillsOff: skills.filter((skill) => !skill.enabled).length,
|
|
694
|
+
mcpServers: mcps.length,
|
|
695
|
+
mcpTools: byServer.size ? mcps.reduce((total, mcp) => total + mcp.tools.length, 0) : 0,
|
|
696
|
+
mcpOff: mcps.reduce((total, mcp) => total + (mcp.tools.length - mcp.on), 0),
|
|
697
|
+
},
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
async function buildState(ctx) {
|
|
702
|
+
const denied = new Set(deniedTools())
|
|
703
|
+
const state = readJSON(STATE_FILE, { disabledSkills: {} })
|
|
704
|
+
state.disabledSkills ??= {}
|
|
705
|
+
|
|
706
|
+
let tools = []
|
|
707
|
+
try {
|
|
708
|
+
tools = ctx.tools.schemas().map((schema) => ({
|
|
709
|
+
name: schema.name,
|
|
710
|
+
description: (schema.description ?? '').slice(0, 240),
|
|
711
|
+
group: schema.name.startsWith('mcp__') ? (schema.name.split('__')[1] ?? 'mcp') : '内置',
|
|
712
|
+
enabled: !denied.has(schema.name),
|
|
713
|
+
}))
|
|
714
|
+
} catch {
|
|
715
|
+
tools = []
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
const skills = skillInventory().map((skill) => ({
|
|
719
|
+
...skill,
|
|
720
|
+
enabled: !(skill.name in state.disabledSkills),
|
|
721
|
+
}))
|
|
722
|
+
|
|
723
|
+
let presets = []
|
|
724
|
+
try {
|
|
725
|
+
const service = ctx.get?.('agentPresets')
|
|
726
|
+
const list = (await service?.list?.()) ?? []
|
|
727
|
+
presets = list.map((preset) => ({ id: preset.id, title: preset.title ?? preset.id }))
|
|
728
|
+
} catch {
|
|
729
|
+
presets = []
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
return {
|
|
733
|
+
tools,
|
|
734
|
+
skills,
|
|
735
|
+
presets,
|
|
736
|
+
counts: {
|
|
737
|
+
tools: tools.length,
|
|
738
|
+
disabledTools: tools.filter((tool) => !tool.enabled).length,
|
|
739
|
+
skills: skills.length,
|
|
740
|
+
disabledSkills: skills.filter((skill) => !skill.enabled).length,
|
|
741
|
+
},
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
function send(res, status, payload) {
|
|
746
|
+
const body = JSON.stringify(payload)
|
|
747
|
+
res.writeHead(status, {
|
|
748
|
+
'content-type': 'application/json; charset=utf-8',
|
|
749
|
+
'cache-control': 'no-store',
|
|
750
|
+
'content-length': Buffer.byteLength(body),
|
|
751
|
+
})
|
|
752
|
+
res.end(body)
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
async function readBody(req) {
|
|
756
|
+
const chunks = []
|
|
757
|
+
let size = 0
|
|
758
|
+
for await (const chunk of req) {
|
|
759
|
+
size += chunk.length
|
|
760
|
+
if (size > MAX_BODY) throw new Error('request body too large')
|
|
761
|
+
chunks.push(chunk)
|
|
762
|
+
}
|
|
763
|
+
if (chunks.length === 0) return {}
|
|
764
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/**
|
|
768
|
+
* Browser-request trust for the panel routes.
|
|
769
|
+
*
|
|
770
|
+
* A `webServer` prefix route is matched before DSH's own `/api` fence, so this
|
|
771
|
+
* plugin has to run the same checks the fence runs: the Host must be loopback
|
|
772
|
+
* (or the listener's own bind address), an `Origin` must name the same
|
|
773
|
+
* authority, and `sec-fetch-site: cross-site` is refused. On top of that the
|
|
774
|
+
* host's `connection.admit()` adds the browser login, which is what keeps a
|
|
775
|
+
* script on another site from driving this panel through the user's browser.
|
|
776
|
+
* Without those checks any page the user had open could call these routes,
|
|
777
|
+
* which is what the market listing warned about.
|
|
778
|
+
*/
|
|
779
|
+
|
|
780
|
+
const LOOPBACK_HOSTNAME = /^(?:127(?:\.\d{1,3}){3}|::1|\[::1\]|localhost)$/i
|
|
781
|
+
|
|
782
|
+
function bareHostname(value) {
|
|
783
|
+
if (typeof value !== 'string' || !value) return ''
|
|
784
|
+
try {
|
|
785
|
+
return new URL('http://' + value).hostname.toLowerCase()
|
|
786
|
+
} catch {
|
|
787
|
+
return ''
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
function requestFacts(req) {
|
|
792
|
+
const host = req.headers.host ?? 'localhost'
|
|
793
|
+
const scheme = req.socket?.encrypted === true ? 'https' : 'http'
|
|
794
|
+
let url
|
|
795
|
+
try {
|
|
796
|
+
url = new URL(req.url ?? '/', `${scheme}://${host}`).href
|
|
797
|
+
} catch {
|
|
798
|
+
url = `${scheme}://localhost/`
|
|
799
|
+
}
|
|
800
|
+
return { method: req.method ?? 'GET', headers: req.headers, socket: req.socket, url }
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
/** 0 when the request passes the Host/Origin rules, otherwise the status to answer. */
|
|
804
|
+
function trustRejection(ctx, req) {
|
|
805
|
+
const host = req.headers.host
|
|
806
|
+
const hostname = bareHostname(host)
|
|
807
|
+
if (!hostname) return 403
|
|
808
|
+
const bind = bareHostname(ctx.webServer?.host)
|
|
809
|
+
if (!LOOPBACK_HOSTNAME.test(hostname) && !(bind && hostname === bind)) return 403
|
|
810
|
+
|
|
811
|
+
const site = req.headers['sec-fetch-site']
|
|
812
|
+
if (typeof site === 'string' && site.toLowerCase() === 'cross-site') return 403
|
|
813
|
+
|
|
814
|
+
const origin = req.headers.origin
|
|
815
|
+
if (typeof origin === 'string' && origin) {
|
|
816
|
+
if (origin === 'null') return 403
|
|
817
|
+
try {
|
|
818
|
+
if (new URL(origin).host.toLowerCase() !== String(host).toLowerCase()) return 403
|
|
819
|
+
} catch {
|
|
820
|
+
return 403
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
return 0
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
/** The host's own admission check (browser login), when the composition provides it. */
|
|
827
|
+
async function admissionRejection(connectionOf, req) {
|
|
828
|
+
const connection = connectionOf()
|
|
829
|
+
if (!connection) return 0
|
|
830
|
+
const facts = requestFacts(req)
|
|
831
|
+
try {
|
|
832
|
+
if (typeof connection.admit === 'function') {
|
|
833
|
+
const answer = await connection.admit(facts)
|
|
834
|
+
if (answer && typeof answer.rejection === 'number') return answer.rejection
|
|
835
|
+
if (answer && answer.peer) return 0
|
|
836
|
+
return 403
|
|
837
|
+
}
|
|
838
|
+
if (typeof connection.requestRejection === 'function') {
|
|
839
|
+
const status = connection.requestRejection(facts)
|
|
840
|
+
return typeof status === 'number' ? status : 0
|
|
841
|
+
}
|
|
842
|
+
} catch {
|
|
843
|
+
return 403
|
|
844
|
+
}
|
|
845
|
+
return 0
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
/** Answer an untrusted request here. Returns true when it was refused. */
|
|
849
|
+
async function refuse(ctx, req, res, connectionOf) {
|
|
850
|
+
let status = trustRejection(ctx, req)
|
|
851
|
+
if (!status) status = await admissionRejection(connectionOf, req)
|
|
852
|
+
if (!status) return false
|
|
853
|
+
send(res, status, {
|
|
854
|
+
error: status === 401
|
|
855
|
+
? '需要先登录 DSH:请重新打开启动时打印的那个网址。/ DSH login required: reopen the URL printed at startup.'
|
|
856
|
+
: '请求来自不受信任的地址,已拒绝。/ Refused: untrusted request origin.',
|
|
857
|
+
})
|
|
858
|
+
return true
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
async function handle(ctx, req, res, connectionOf) {
|
|
862
|
+
if (await refuse(ctx, req, res, connectionOf)) return
|
|
863
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
864
|
+
const route = url.pathname.replace(/^\/capability-trimmer/, '')
|
|
865
|
+
|
|
866
|
+
try {
|
|
867
|
+
if (req.method === 'GET' && (route === '' || route === '/state')) {
|
|
868
|
+
applyRuntime(ctx)
|
|
869
|
+
send(res, 200, await buildState(ctx))
|
|
870
|
+
return
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
if (req.method === 'POST' && route === '/ignore') {
|
|
874
|
+
const { key, ignored: ignore } = await readBody(req)
|
|
875
|
+
if (typeof key !== 'string' || !key) {
|
|
876
|
+
send(res, 400, { error: 'key is required' })
|
|
877
|
+
return
|
|
878
|
+
}
|
|
879
|
+
const state = readJSON(STATE_FILE, { disabledSkills: {}, ignoredPairs: [] })
|
|
880
|
+
const set = new Set(state.ignoredPairs ?? [])
|
|
881
|
+
if (ignore === false) set.delete(key)
|
|
882
|
+
else set.add(key)
|
|
883
|
+
state.ignoredPairs = [...set]
|
|
884
|
+
writeJSON(STATE_FILE, state)
|
|
885
|
+
send(res, 200, await buildMode(ctx, url.searchParams.get('preset') ?? undefined))
|
|
886
|
+
return
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
if (req.method === 'POST' && route === '/toggle') {
|
|
890
|
+
const body = await readBody(req)
|
|
891
|
+
const { kind, name: target, enabled, use } = body
|
|
892
|
+
if (typeof target !== 'string' || !target) {
|
|
893
|
+
send(res, 400, { error: 'name is required' })
|
|
894
|
+
return
|
|
895
|
+
}
|
|
896
|
+
if (kind === 'tool') {
|
|
897
|
+
setToolEnabled(target, Boolean(enabled), typeof use === 'string' && use && !enabled ? use : '')
|
|
898
|
+
} else if (kind === 'skill') {
|
|
899
|
+
const state = readJSON(STATE_FILE, { disabledSkills: {} })
|
|
900
|
+
state.disabledSkills ??= {}
|
|
901
|
+
if (enabled) enableSkill(target, state)
|
|
902
|
+
else disableSkill(target, state)
|
|
903
|
+
writeJSON(STATE_FILE, state)
|
|
904
|
+
} else {
|
|
905
|
+
send(res, 400, { error: `unknown kind: ${String(kind)}` })
|
|
906
|
+
return
|
|
907
|
+
}
|
|
908
|
+
send(res, 200, await buildState(ctx))
|
|
909
|
+
return
|
|
910
|
+
}
|
|
911
|
+
|
|
912
|
+
if (req.method === 'POST' && route === '/skill-desc') {
|
|
913
|
+
const { name, description } = await readBody(req)
|
|
914
|
+
if (typeof name !== 'string' || !name) {
|
|
915
|
+
send(res, 400, { error: 'name-required' })
|
|
916
|
+
return
|
|
917
|
+
}
|
|
918
|
+
if (typeof description !== 'string' || !description.trim()) {
|
|
919
|
+
send(res, 400, { error: 'empty-description' })
|
|
920
|
+
return
|
|
921
|
+
}
|
|
922
|
+
try {
|
|
923
|
+
const file = setSkillDescription(name, description)
|
|
924
|
+
send(res, 200, { ok: true, file: file.replace(homedir(), '~'), description: String(description).replace(/\s+/g, ' ').trim().slice(0, 240) })
|
|
925
|
+
} catch (cause) {
|
|
926
|
+
const message = cause instanceof Error ? cause.message : String(cause)
|
|
927
|
+
send(res, 400, { error: message.startsWith('找不到技能') ? `skill-not-found:${name}` : message })
|
|
928
|
+
}
|
|
929
|
+
return
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
if (req.method === 'GET' && route === '/graph') {
|
|
933
|
+
const kind = url.searchParams.get('kind')
|
|
934
|
+
const name = url.searchParams.get('name')
|
|
935
|
+
if (kind !== 'skill' && kind !== 'tool') {
|
|
936
|
+
send(res, 400, { error: 'kind 必须是 skill 或 tool' })
|
|
937
|
+
return
|
|
938
|
+
}
|
|
939
|
+
if (!name) {
|
|
940
|
+
send(res, 400, { error: 'name is required' })
|
|
941
|
+
return
|
|
942
|
+
}
|
|
943
|
+
if (!xrefCache.skillUse) {
|
|
944
|
+
send(res, 409, { error: '关联数据尚未生成:先打开能力页做一次扫描' })
|
|
945
|
+
return
|
|
946
|
+
}
|
|
947
|
+
send(res, 200, buildGraph(kind, name))
|
|
948
|
+
return
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
if (req.method === 'GET' && route === '/mode') {
|
|
952
|
+
send(res, 200, await buildMode(ctx, url.searchParams.get('preset') ?? undefined))
|
|
953
|
+
return
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
send(res, 404, { error: 'not found' })
|
|
957
|
+
} catch (error) {
|
|
958
|
+
send(res, 500, { error: error instanceof Error ? error.message : String(error) })
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
|
|
962
|
+
/**
|
|
963
|
+
* Write one startup record next to the plugin's own state.
|
|
964
|
+
*
|
|
965
|
+
* The web listener answers 403 to anything without the browser's session
|
|
966
|
+
* cookie, so neither curl nor a log line can tell whether the Client half
|
|
967
|
+
* reached the browser. This record answers that from the Host side: whether the
|
|
968
|
+
* row is advertised in the boot graph, and where its bundle file resolved.
|
|
969
|
+
*/
|
|
970
|
+
function writeDiagnostics(ctx, extra) {
|
|
971
|
+
const record = { at: new Date().toISOString(), ...extra }
|
|
972
|
+
try {
|
|
973
|
+
const clientModules = ctx.get?.('clientModules')
|
|
974
|
+
record.clientModules = Boolean(clientModules)
|
|
975
|
+
const graph = clientModules?.graph?.()
|
|
976
|
+
record.entries = graph?.entries?.map((entry) => entry.id) ?? null
|
|
977
|
+
record.advertised = graph?.entries?.some((entry) => entry.id === PACKAGE_NAME) ?? null
|
|
978
|
+
record.clientPath = clientModules?.clientPath?.(PACKAGE_NAME) ?? null
|
|
979
|
+
} catch (error) {
|
|
980
|
+
record.graphError = error instanceof Error ? error.message : String(error)
|
|
981
|
+
}
|
|
982
|
+
try {
|
|
983
|
+
writeJSON(DIAG_FILE, record)
|
|
984
|
+
} catch {
|
|
985
|
+
// Diagnostics must never stop the plugin from activating.
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
/**
|
|
990
|
+
* Snapshot after the boot flush, not during activation: read synchronously in
|
|
991
|
+
* apply(), the graph may not yet contain this very row, which reads as a false
|
|
992
|
+
* negative. Re-snapshot whenever the graph recomposes.
|
|
993
|
+
*/
|
|
994
|
+
function watchDiagnostics(ctx, route) {
|
|
995
|
+
const snapshot = () => writeDiagnostics(ctx, { route, phase: 'settled', v: 2 })
|
|
996
|
+
try {
|
|
997
|
+
ctx.get?.('clientModules')?.onGraphChanged?.(snapshot)
|
|
998
|
+
} catch {
|
|
999
|
+
// Optional hook; the timers below still capture a settled graph.
|
|
1000
|
+
}
|
|
1001
|
+
for (const delay of [1000, 4000]) setTimeout(snapshot, delay).unref?.()
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
export function apply(ctx) {
|
|
1005
|
+
let route = 'registered'
|
|
1006
|
+
// `connection.admit` is the host's own browser-login fence. Reading that
|
|
1007
|
+
// service needs a context that declares it, so resolve one lazily; a
|
|
1008
|
+
// composition without `connection` keeps the Host/Origin checks only.
|
|
1009
|
+
let connectionCtx
|
|
1010
|
+
let connectionScope
|
|
1011
|
+
try {
|
|
1012
|
+
connectionScope = ctx.inject?.(['connection'], (scoped) => {
|
|
1013
|
+
connectionCtx = scoped
|
|
1014
|
+
return () => {
|
|
1015
|
+
if (connectionCtx === scoped) connectionCtx = undefined
|
|
1016
|
+
}
|
|
1017
|
+
})
|
|
1018
|
+
} catch {
|
|
1019
|
+
// Host without ctx.inject: the direct read below still finds the service.
|
|
1020
|
+
}
|
|
1021
|
+
const connectionOf = () => (connectionCtx ?? ctx).get?.('connection')
|
|
1022
|
+
|
|
1023
|
+
try {
|
|
1024
|
+
// The route is a resource like any other: without this effect a reload or a
|
|
1025
|
+
// bundle removal leaves the old handler answering on the live server, which
|
|
1026
|
+
// is exactly how the pre-1.0.1 path kept serving unauthenticated after the
|
|
1027
|
+
// rename.
|
|
1028
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1029
|
+
kind: 'prefix',
|
|
1030
|
+
path: '/capability-trimmer',
|
|
1031
|
+
handler: (req, res) => handle(ctx, req, res, connectionOf),
|
|
1032
|
+
}))
|
|
1033
|
+
ctx.effect(() => () => {
|
|
1034
|
+
void connectionScope?.dispose?.()
|
|
1035
|
+
})
|
|
1036
|
+
} catch (error) {
|
|
1037
|
+
route = error instanceof Error ? error.message : String(error)
|
|
1038
|
+
}
|
|
1039
|
+
runtimeState ??= { toolDisposers: new Map(), skillShadowDisposers: new Map(), shadowPaths: new Map() }
|
|
1040
|
+
runtimeState.shadowPaths ??= new Map()
|
|
1041
|
+
|
|
1042
|
+
// 注册表层禁用:新 agent 挂 restriction,已存活的立即对齐;agent 到齐后再审计一轮。
|
|
1043
|
+
ctx.on('agent/created', ({ agent }) => {
|
|
1044
|
+
restrictAgentTools(ctx, agent, runtimeState.toolDisposers)
|
|
1045
|
+
const disabled = Object.keys(readJSON(STATE_FILE, { disabledSkills: {} }).disabledSkills ?? {})
|
|
1046
|
+
for (const name of disabled) registerSkillShadowForAgent(ctx, agent, name, runtimeState.skillShadowDisposers)
|
|
1047
|
+
setTimeout(() => { void auditSkillShadows(ctx) }, 2000)
|
|
1048
|
+
})
|
|
1049
|
+
ctx.on('agent/disposed', ({ agent }) => {
|
|
1050
|
+
runtimeState.toolDisposers.delete(agent.id)
|
|
1051
|
+
for (const key of [...runtimeState.skillShadowDisposers.keys()]) {
|
|
1052
|
+
if (key.startsWith(agent.id + ':')) runtimeState.skillShadowDisposers.delete(key)
|
|
1053
|
+
}
|
|
1054
|
+
})
|
|
1055
|
+
ctx.on('tools/change', () => {
|
|
1056
|
+
// MCP server 后到注册的工具有了名字,补挂一次。
|
|
1057
|
+
for (const agent of ctx.agents.list()) {
|
|
1058
|
+
if (!runtimeState.toolDisposers.has(agent.id)) {
|
|
1059
|
+
restrictAgentTools(ctx, agent, runtimeState.toolDisposers)
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
})
|
|
1063
|
+
try {
|
|
1064
|
+
applyRuntime(ctx)
|
|
1065
|
+
} catch (error) {
|
|
1066
|
+
ctx.logger?.warn?.('capability-trimmer: initial applyRuntime failed: ' + (error instanceof Error ? error.message : String(error)))
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
writeDiagnostics(ctx, { route, phase: 'activation', v: 2 })
|
|
1070
|
+
watchDiagnostics(ctx, route)
|
|
1071
|
+
}
|