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/client.js ADDED
@@ -0,0 +1,1066 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-capability-trimmer',
3
+ factory(require) {
4
+ const React = require('react')
5
+ const h = React.createElement
6
+ const { useCallback, useEffect, useMemo, useState } = React
7
+
8
+ const API = '/capability-trimmer'
9
+
10
+ const STYLE = `
11
+ .cm{display:flex;flex-direction:column;gap:14px;padding:18px 22px 40px;overflow:auto;height:100%;color:var(--dsw-alias-label-primary);font-size:13px;box-sizing:border-box}
12
+ .cm-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;flex-wrap:wrap}
13
+ .cm-title{display:flex;align-items:center;gap:8px;font-size:15px;font-weight:600;letter-spacing:-.01em}
14
+ .cm-mode{font-size:12px;font-weight:500;padding:2px 9px;border-radius:999px;background:var(--dsw-alias-bg-layer-2);border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary)}
15
+ .cm-mode[data-state="off"]{border-color:var(--dsw-alias-state-warn-primary);color:var(--dsw-alias-state-warn-primary)}
16
+ .cm-sub{margin:5px 0 0;font-size:12px;line-height:1.55;color:var(--dsw-alias-label-secondary);max-width:70ch}
17
+ .cm-actions{display:flex;gap:8px;align-items:center}
18
+ .cm-btn{padding:6px 13px;border-radius:8px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);color:inherit;font:inherit;font-size:12px;cursor:pointer}
19
+ .cm-btn:hover{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary)}
20
+ .cm-btn:disabled{opacity:.55;cursor:progress}
21
+ .cm-banner{display:flex;gap:10px;align-items:flex-start;padding:11px 14px;border-radius:12px;border:1px solid var(--dsw-alias-state-warn-primary);background:var(--dsw-alias-bg-layer-2)}
22
+ .cm-banner b{color:var(--dsw-alias-state-warn-primary);font-weight:600}
23
+ .cm-banner p{margin:3px 0 0;font-size:11.5px;line-height:1.55;color:var(--dsw-alias-label-secondary)}
24
+ .cm-tabs{display:flex;gap:6px;flex-wrap:wrap}
25
+ .cm-tab{padding:5px 12px;border-radius:999px;border:1px solid var(--dsw-alias-border-l1);background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;cursor:pointer}
26
+ .cm-tab[aria-selected="true"]{background:var(--dsw-alias-brand-primary);border-color:var(--dsw-alias-brand-primary);color:#fff}
27
+ .cm-tab b{font-weight:600;font-variant-numeric:tabular-nums}
28
+ .cm-tab[data-hot="true"]:not([aria-selected="true"]){border-color:var(--dsw-alias-state-warn-primary);color:var(--dsw-alias-state-warn-primary)}
29
+ .cm-search{width:100%;box-sizing:border-box;padding:7px 11px;border-radius:9px;border:1px solid var(--dsw-alias-border-l1);background:var(--dsw-alias-bg-layer-1);color:inherit;font:inherit;font-size:12.5px;outline:none}
30
+ .cm-search:focus{border-color:var(--dsw-alias-brand-primary)}
31
+ .cm-group{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;overflow:hidden;background:var(--dsw-alias-bg-layer-1)}
32
+ .cm-grouphead{display:flex;justify-content:space-between;align-items:baseline;padding:9px 14px;background:var(--dsw-alias-bg-layer-2);border-bottom:1px solid var(--dsw-alias-border-l1)}
33
+ .cm-grouphead strong{font-size:12.5px;font-weight:600}
34
+ .cm-grouphead span{font-size:11px;color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
35
+ .cm-item{display:flex;gap:14px;align-items:flex-start;padding:10px 14px;border-bottom:1px solid var(--dsw-alias-border-l1)}
36
+ .cm-item:last-child{border-bottom:none}
37
+ .cm-item:hover{background:var(--dsw-alias-bg-layer-2)}
38
+ .cm-main{flex:1;min-width:0}
39
+ .cm-name{font-weight:600;font-size:12.5px;word-break:break-word}
40
+ .cm-name em{font-style:normal;font-weight:400;color:var(--dsw-alias-label-secondary);margin-left:6px;font-size:11px}
41
+ .cm-desc{margin-top:3px;font-size:11.5px;line-height:1.5;color:var(--dsw-alias-label-secondary);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
42
+ .cm-off .cm-name,.cm-off .cm-desc{opacity:.5}
43
+ .cm-dot{flex:0 0 auto;width:7px;height:7px;border-radius:50%;margin-top:7px;background:var(--dsw-alias-state-success-primary)}
44
+ .cm-dot[data-off="true"]{background:var(--dsw-alias-state-idle-primary)}
45
+ .cm-switch{flex:0 0 auto;position:relative;width:36px;height:20px;border-radius:999px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-2);cursor:pointer;transition:background .15s,border-color .15s;padding:0;margin-top:2px}
46
+ .cm-switch::after{content:"";position:absolute;top:2px;left:2px;width:14px;height:14px;border-radius:50%;background:var(--dsw-alias-label-secondary);transition:transform .15s,background .15s}
47
+ .cm-switch[aria-checked="true"]{background:var(--dsw-alias-brand-primary);border-color:var(--dsw-alias-brand-primary)}
48
+ .cm-switch[aria-checked="true"]::after{transform:translateX(16px);background:#fff}
49
+ .cm-switch:disabled{opacity:.5;cursor:progress}
50
+ .cm-pair{padding:12px 14px;border-bottom:1px solid var(--dsw-alias-border-l1)}
51
+ .cm-pair:last-child{border-bottom:none}
52
+ .cm-pairtop{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:12px}
53
+ .cm-descs{display:grid;grid-template-columns:1fr 1fr;gap:8px;margin:10px 0 2px}
54
+ .cm-desccard{padding:8px 10px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;font-size:11.5px;line-height:1.55}
55
+ .cm-desccard b{display:block;font-size:11px;margin-bottom:3px}
56
+ .cm-desccard--keep b{color:var(--dsw-alias-brand-primary)}
57
+ .cm-desccard--drop b{color:var(--dsw-alias-state-warn-primary)}
58
+ .cm-desccard p{margin:0;white-space:pre-wrap;word-break:break-word;color:var(--dsw-alias-label-secondary)}
59
+ @media (max-width:720px){.cm-descs{grid-template-columns:1fr}}
60
+ .cm-pairname{font-weight:600}
61
+ .cm-pairkind{font-size:10.5px;padding:1px 6px;border-radius:5px;border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary)}
62
+ .cm-score{margin-left:auto;font-variant-numeric:tabular-nums;font-size:11.5px;font-weight:600;color:var(--dsw-alias-state-warn-primary)}
63
+ .cm-why{margin:5px 0 0;font-size:11px;line-height:1.5;color:var(--dsw-alias-label-secondary)}
64
+ .cm-paira{display:flex;gap:7px;margin-top:9px;flex-wrap:wrap}
65
+ .cm-paira .cm-btn{font-size:11.5px;padding:5px 11px}
66
+ .cm-paira .cm-btn[data-primary="true"]{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary)}
67
+ .cm-mask{position:fixed;inset:0;background:rgba(0,0,0,.45);display:flex;overflow-y:auto;z-index:9999}
68
+ .cm-dialog{margin:auto;width:min(440px,88vw);max-height:88vh;overflow-y:auto;overscroll-behavior:contain;border-radius:14px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-overlay);padding:18px 20px;box-shadow:0 18px 48px rgba(0,0,0,.28)}
69
+ .cm-dialog h3{margin:0;font-size:14px;font-weight:600}
70
+ .cm-dialog p{margin:9px 0 0;font-size:12px;line-height:1.6;color:var(--dsw-alias-label-secondary)}
71
+ .cm-dialog code{font-size:11.5px;padding:1px 5px;border-radius:4px;background:var(--dsw-alias-bg-layer-2);color:var(--dsw-alias-label-primary)}
72
+ .cm-dialogfoot{display:flex;justify-content:flex-end;align-items:center;gap:8px;margin-top:16px;position:sticky;bottom:-18px;padding:10px 0 0;background:var(--dsw-alias-bg-overlay);border-top:1px solid var(--dsw-alias-border-l1)}
73
+ .cm-used{margin-top:3px;font-size:11px;line-height:1.5;color:var(--dsw-alias-state-warn-primary)}
74
+ .cm-dephead{margin:2px 0}
75
+ .cm-check{display:flex;align-items:center;gap:6px;font-size:11.5px;color:var(--dsw-alias-label-secondary);cursor:pointer;margin-right:auto}
76
+ .cm-graphwrap--dialog{max-height:32vh}
77
+ .cm-graphload{font-size:11.5px;color:var(--dsw-alias-label-tertiary)}
78
+ .cm-skiptag{font-size:11px;color:var(--dsw-alias-state-warn-primary)}
79
+ .cm-deplist{display:flex;flex-wrap:wrap;gap:6px;margin:7px 0 4px}
80
+ .cm-dep{font-size:11px;padding:2px 8px;border-radius:6px;border:1px solid var(--dsw-alias-border-l1);color:var(--dsw-alias-label-secondary);font-variant-numeric:tabular-nums}
81
+ .cm-dep[data-strength="must"]{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary);font-weight:600}
82
+ .cm-dep[data-strength="often"]{border-color:var(--dsw-alias-state-warn-primary);color:var(--dsw-alias-state-warn-primary)}
83
+ .cm-depwarn{color:var(--dsw-alias-state-error-primary)}
84
+ .cm-detaildesc{margin:4px 0 10px;padding:9px 12px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;font-size:12px;line-height:1.6}
85
+ .cm-descedit{width:100%;min-height:88px;box-sizing:border-box;margin-top:6px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;padding:8px 10px;font:inherit;font-size:12px;line-height:1.6;background:var(--dsw-alias-bg-overlay);color:inherit;resize:vertical}
86
+ .cm-desceditbar{display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:8px}
87
+ .cm-descmsg{font-size:12px;color:#2e9e63}
88
+ .cm-descmsg--err{color:#c0392b}
89
+ .cm-descnote{margin:8px 0 0;font-size:11px;line-height:1.6;color:var(--dsw-alias-label-secondary)}
90
+ .cm-detaildesc b{display:block;font-size:11px;color:var(--dsw-alias-label-secondary);margin-bottom:3px}
91
+ .cm-detaildesc p{margin:0;white-space:pre-wrap;word-break:break-word}
92
+ .cm-detailsub{font-size:11px;color:var(--dsw-alias-label-secondary);margin:0 0 4px}
93
+ .cm-graphbtn{flex:0 0 auto;padding:4px 10px;margin-top:2px;border-radius:7px;border:1px solid var(--dsw-alias-border-l1);background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:11px;cursor:pointer}
94
+ .cm-graphbtn:hover{border-color:var(--dsw-alias-brand-primary);color:var(--dsw-alias-brand-primary)}
95
+ .cm-graphdlg{width:min(940px,94vw)}
96
+ .cm-graphwrap{margin-top:12px;max-height:62vh;overflow:auto;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1)}
97
+ .cm-graphfoot{display:flex;justify-content:space-between;align-items:center;gap:14px;margin-top:12px;font-size:11px;line-height:1.5;color:var(--dsw-alias-label-secondary)}
98
+ .cm-note{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;padding:11px 14px;background:var(--dsw-alias-bg-layer-2);font-size:11.5px;line-height:1.6;color:var(--dsw-alias-label-secondary)}
99
+ .cm-note b{color:var(--dsw-alias-label-primary);font-weight:600}
100
+ .cm-error{color:var(--dsw-alias-state-error-primary);font-size:12px}
101
+ .cm-empty{padding:26px 14px;text-align:center;font-size:12px;color:var(--dsw-alias-label-secondary)}
102
+ `
103
+
104
+ /** 双语文案:zh 为完整基准(测试断言依赖),en 为英文版。键名即身份,不许改。 */
105
+ const LOCALE_NS = 'capability-trimmer'
106
+ const STRINGS = {
107
+ zh: {
108
+ tab: '能力',
109
+ title: '能力扫描',
110
+ sub: '当前模式下挂载的 MCP、技能与插件。开关即时生效;插件状态来自该模式的组合,只读。',
111
+ subProviderOff: '当前模式下技能提供者未启用,模型看不到任何技能。',
112
+ presetDefault: '默认模式',
113
+ recheck: '重新检查', checking: '检查中…',
114
+ skipTag: '已忽略关闭确认', skipTagTitle: '刷新页面后恢复',
115
+ readFail: '读取失败:',
116
+ firstOpen: '首次打开,正在扫描…',
117
+ tabOverlap: '重合', tabSkill: '技能', tabPlugin: '插件',
118
+ toolsUnit: ' 工具', enabledUnit: ' 启用',
119
+ searchMcp: '按服务器或工具名筛选…',
120
+ searchSkill: '按名称或描述筛选技能…',
121
+ searchPlugin: '按插件名筛选…',
122
+ bannerFound: '发现 ', bannerFoundSuffix: ' 组能力重合',
123
+ bannerHint: '每组里挑一个保留即可,另一个会被关掉;不是重合就点「不是重合 · 忽略」;描述不清可到技能页「详情」里改描述。',
124
+ overlapTitle: '重合的能力', overlapSummary: ' 组待决定',
125
+ overlapEmpty: '没有检测到重合,或已全部处理',
126
+ kindSkill: '技能', kindMcp: 'MCP',
127
+ leftUsedBy: '左项被 ', rightUsedBy: '右项被 ', usedByRef: ' 引用',
128
+ keep: '保留 ', notOverlap: '不是重合 · 忽略',
129
+ notOverlapTitle: '判定为非重合/误报:不再出现在重合列表,可随时在下方恢复',
130
+ ignoredTitle: '已忽略(判定非重合)', ignoredSummary: ' 组', restore: '恢复检查',
131
+ mcpNone: '未挂载', mcpEmpty: '当前模式下没有 MCP 工具',
132
+ blockedUse: '已拦 · 改用 ',
133
+ skillTitle: '技能', skillEmptyQ: '没有匹配的技能', skillEmpty: '没有技能',
134
+ copiesUnit: ' 份', copiesLink: ' · 含软链',
135
+ pluginTitle: '插件', pluginSummarySuffix: ' 启用 · 只读',
136
+ pluginEmptyQ: '没有匹配的插件', pluginEmpty: '没有插件行', pluginCond: '条件 ',
137
+ usedByLabel: '被引用:', usedByMore: ' 等 ', usedByCount: ' 个',
138
+ graphBtn: '详情', graphBtnTitle: '能力详情与上下游',
139
+ readonlyOn: '已启用', readonlyOff: '未启用', disable: '停用', enable: '启用',
140
+ detail: '详情:', desc: '描述', noDesc: '(无描述)',
141
+ editDesc: '编辑描述', save: '保存', saving: '保存中…', cancel: '取消',
142
+ savedMsg: '已写回 SKILL.md ✓ 重新检查后重合分重算',
143
+ editDescNote: '写回该技能 SKILL.md 的 frontmatter;同步目录可能被下次同步覆盖,模型读到新描述的时机由 DSH 决定。',
144
+ toolDescNote: 'MCP 工具描述由服务端下发,本地改不了:可在列表里禁用并登记「改用」,或把该对标记为非重合。',
145
+ upstreamTitle: '上下游', graphLoading: '关联数据加载中…',
146
+ emptyGraph1: '没有任何文本引用关系。上游为空:没有技能在正文里点名它;',
147
+ emptyGraph2: '工具没有正文,所以工具永远没有下游;技能的下游为空说明它的文档没有点名任何工具或技能。',
148
+ methodFoot: '口径:扫描已启用技能的正文(SKILL.md + references/),按点名次数分档;这是文本引用,不是运行时调用链。',
149
+ methodFootAt: ' 数据生成于 ', close: '关闭',
150
+ svgUp: '上游 · 谁引用它', svgCenter: '本能力', svgDown: '下游 · 它引用谁',
151
+ svgTool: 'MCP 工具', svgSkill: '技能', svgHits: ' · 点名 ', svgHitsSuffix: ' 次',
152
+ strengthMust: '必须', strengthOften: '常用', strengthOptional: '可有可无',
153
+ legendMust: '必须 · 点名 ≥3 次', legendOften: '常用 · 2 次', legendOptional: '可有可无 · 1 次',
154
+ svgHidden: '另有 ', svgHiddenSuffix: ' 个未展示(按点名次数截断)',
155
+ confirmTitle: '确认关闭这个能力?',
156
+ confirmKeep: '保留 ', confirmClosePrefix: '关闭 ', confirmComma: ',关闭 ', confirmEnd: '。',
157
+ keepCard: '保留 · ', dropCard: '关闭 · ',
158
+ affectHead: '关闭会影响这些关联技能的使用:',
159
+ depHits: '正文点名 ', depHitsSuffix: ' 次',
160
+ depMore: '等 ', depMoreSuffix: ' 个',
161
+ mustWarn: '存在必须级引用(点名 ≥3 次):这些技能的对应流程大概率直接跑不通,建议保留或先确认不用。',
162
+ degradeWarn: '禁用后它们的相应步骤会退化。',
163
+ noDep: '没有技能点名引用它,禁用影响面只有这一个能力。',
164
+ bothMention1: '其中 ', bothMention2: ' 同时提到了保留项,替代可行。',
165
+ noAlt: '注意:引用它的技能都没有提到保留项,没有现成替代。',
166
+ altReg1: '替代已自动登记:之后任何对 ', altReg2: ' 从模型视野移除,替代关系已登记:能力页记录改用 ', altReg3: '。',
167
+ keepSkill1: '保留项是技能:对 ', keepSkill2: ' 从模型视野移除;技能靠场景触发,无法硬性改道,保留项会在相同场景被选中。',
168
+ dropSkillShadow: '技能在注册表层被压制:模型目录和 skill 工具都不再加载它;保留项覆盖相同的触发场景,会被模型在相同上下文选中。',
169
+ graphLoadDialog: '上下游结构图加载中…',
170
+ skillHow: '技能会在注册表层被影子压制(目录原样保留,同步器恢复也无妨):模型目录和 skill 工具都不再加载它,随时可以在「技能」页打开恢复。',
171
+ toolHow: 'MCP 工具会从模型视野整体移除(restrict 生效后模型看不到它的定义,也不会尝试调用);随时可以在「MCP」页打开恢复。',
172
+ noConfirmAgain: '本次会话内不再确认', confirmCloseBtn: '确认关闭',
173
+ howTitle: '重合是怎么算的:',
174
+ howBody1: ' 复用 capability 审计的算法(描述 TF-IDF 余弦为主,叠加触发词、名称、共享术语),',
175
+ howBody2: ' 语料只取当前模式里**已启用**的能力,阈值 ',
176
+ howBody3: '。分数是这份语料内部的相对值,不同模式之间不可比。插件行不参与——它们没有描述。',
177
+ whyPluginTitle: '为什么插件行没有开关:',
178
+ whyPluginBody1: ' 预设的插件行在挂载时进入 agent 的隔离分组,agentPresets 只提供 list / read / select / recompose 这类读取与会话级接口,没有“改某一行”的运行时入口;',
179
+ whyPluginBody2: ' 本插件是 profile 级插件,拿不到某个会话的 agent 上下文。',
180
+ whyPluginBody3: ' 真要关掉某一行,等于改该模式的定义文件再重启——需要的话我可以生成那段 patch,但不会替你写进配置。',
181
+ errEmptyDesc: '描述不能为空', errNameReq: '缺少技能名',
182
+ errNotFound: '找不到该技能的本地目录:',
183
+ },
184
+ en: {
185
+ tab: 'Capabilities',
186
+ title: 'Capability Scan',
187
+ sub: 'MCP tools, skills, and plugins mounted in the current preset. Toggles take effect immediately; plugin rows are read-only composition facts.',
188
+ subProviderOff: 'The skill provider is off in this preset — the model sees no skills.',
189
+ presetDefault: 'Default preset',
190
+ recheck: 'Re-scan', checking: 'Scanning…',
191
+ skipTag: 'Confirmations skipped', skipTagTitle: 'Restored after page refresh',
192
+ readFail: 'Failed to load: ',
193
+ firstOpen: 'First open, scanning…',
194
+ tabOverlap: 'Overlaps', tabSkill: 'Skills', tabPlugin: 'Plugins',
195
+ toolsUnit: ' tools', enabledUnit: ' on',
196
+ searchMcp: 'Filter by server or tool name…',
197
+ searchSkill: 'Filter skills by name or description…',
198
+ searchPlugin: 'Filter plugins by name…',
199
+ bannerFound: 'Found ', bannerFoundSuffix: ' overlapping capability groups',
200
+ bannerHint: 'Keep one per group and the other gets disabled; if it is not a real overlap, click "Not overlapping · Ignore"; if a description is unclear, fix it via Details on the Skills tab.',
201
+ overlapTitle: 'Overlapping capabilities', overlapSummary: ' to decide',
202
+ overlapEmpty: 'No overlaps detected, or all handled',
203
+ kindSkill: 'skill', kindMcp: 'MCP',
204
+ leftUsedBy: 'Left is used by ', rightUsedBy: 'Right is used by ', usedByRef: '',
205
+ keep: 'Keep ', notOverlap: 'Not overlapping · Ignore',
206
+ notOverlapTitle: 'Mark as not-a-real-overlap / false positive: it leaves the list and can be restored below anytime',
207
+ ignoredTitle: 'Ignored (not overlapping)', ignoredSummary: ' groups', restore: 'Restore check',
208
+ mcpNone: 'none mounted', mcpEmpty: 'No MCP tools in the current preset',
209
+ blockedUse: 'gated · use ',
210
+ skillTitle: 'Skills', skillEmptyQ: 'No matching skills', skillEmpty: 'No skills',
211
+ copiesUnit: ' copies', copiesLink: ' · symlinked',
212
+ pluginTitle: 'Plugins', pluginSummarySuffix: ' on · read-only',
213
+ pluginEmptyQ: 'No matching plugins', pluginEmpty: 'No plugin rows', pluginCond: 'cond ',
214
+ usedByLabel: 'Used by: ', usedByMore: ' +', usedByCount: ' more',
215
+ graphBtn: 'Details', graphBtnTitle: 'Capability details and graph',
216
+ readonlyOn: 'enabled', readonlyOff: 'disabled', disable: 'disable', enable: 'enable',
217
+ detail: 'Details: ', desc: 'Description', noDesc: '(no description)',
218
+ editDesc: 'Edit description', save: 'Save', saving: 'Saving…', cancel: 'Cancel',
219
+ savedMsg: 'Written back to SKILL.md ✓ overlap scores recompute on next re-scan',
220
+ editDescNote: 'Writes back to the frontmatter of this skill\'s SKILL.md; sync-managed roots may be overwritten by the next sync, and when the model sees the new wording is up to DSH.',
221
+ toolDescNote: 'MCP tool descriptions are served by the MCP server and cannot be edited locally: disable it in the list with a "use instead" note, or mark the pair as not overlapping.',
222
+ upstreamTitle: 'Upstream / Downstream', graphLoading: 'Loading graph…',
223
+ emptyGraph1: 'No textual references at all. Empty upstream: no skill mentions it in its body; ',
224
+ emptyGraph2: 'tools have no body, so a tool never has downstream; an empty skill downstream means its docs name no tool or skill.',
225
+ methodFoot: 'Method: scans enabled skills\' bodies (SKILL.md + references/), graded by mention counts; this is textual reference, not a runtime call graph.',
226
+ methodFootAt: ' Generated at ', close: 'Close',
227
+ svgUp: 'Upstream · who references it', svgCenter: 'This capability', svgDown: 'Downstream · what it references',
228
+ svgTool: 'MCP tool', svgSkill: 'skill', svgHits: ' · mentioned ', svgHitsSuffix: '×',
229
+ strengthMust: 'must', strengthOften: 'often', strengthOptional: 'optional',
230
+ legendMust: 'must · ≥3 mentions', legendOften: 'often · 2', legendOptional: 'optional · 1',
231
+ svgHidden: '', svgHiddenSuffix: ' more hidden (truncated by mention count)',
232
+ confirmTitle: 'Disable this capability?',
233
+ confirmKeep: 'Keep ', confirmClosePrefix: 'Disable ', confirmComma: ', disable ', confirmEnd: '.',
234
+ keepCard: 'Keep · ', dropCard: 'Disable · ',
235
+ affectHead: 'Disabling affects these dependent skills:',
236
+ depHits: 'mentioned ', depHitsSuffix: '× in body',
237
+ depMore: 'plus ', depMoreSuffix: ' more',
238
+ mustWarn: 'Must-level references exist (≥3 mentions): their flows will most likely break outright. Prefer keeping it, or confirm it is unused first.',
239
+ degradeWarn: 'Their corresponding steps degrade after disabling.',
240
+ noDep: 'No skill references it; the impact is this capability alone.',
241
+ bothMention1: 'Some dependents (', bothMention2: ') also mention the kept one, so the replacement is viable.',
242
+ noAlt: 'Note: none of its dependents mention the kept one — no drop-in replacement.',
243
+ altReg1: 'Replacement registered: ', altReg2: ' is removed from the model\'s view and the redirect is recorded — the panel notes "use ', altReg3: '".',
244
+ keepSkill1: 'The kept one is a skill: ', keepSkill2: ' is removed from the model\'s view; skills trigger by scenario and cannot be hard-rerouted, the kept one gets picked in the same scenarios.',
245
+ dropSkillShadow: 'The disabled skill is shadowed at the registry layer: neither the catalog nor the skill tool loads it; the kept one covers the same trigger scenarios.',
246
+ graphLoadDialog: 'Loading graph…',
247
+ skillHow: 'Skills are shadowed at the registry layer (the directory stays, so the syncer restoring it is harmless): neither the catalog nor the skill tool loads it; re-enable anytime on the Skills tab.',
248
+ toolHow: 'MCP tools are removed from the model\'s view entirely (once the restriction applies, the model cannot see its definition or attempt it); re-enable anytime on the MCP tab.',
249
+ noConfirmAgain: 'Skip confirmations this session', confirmCloseBtn: 'Disable it',
250
+ howTitle: 'How overlaps are computed:',
251
+ howBody1: ' reuses the capability-audit algorithm (description TF-IDF cosine plus trigger-word, name, and shared-term signals),',
252
+ howBody2: ' over the corpus of **enabled** capabilities in this preset only, threshold ',
253
+ howBody3: '. Scores are relative within this corpus and not comparable across presets. Plugin rows are excluded — they have no description.',
254
+ whyPluginTitle: 'Why plugin rows have no toggle:',
255
+ whyPluginBody1: ' Preset plugin rows enter the agent\'s isolated group at mount time, and agentPresets only offers read and session-level APIs (list / read / select / recompose) — no per-row runtime entry;',
256
+ whyPluginBody2: ' this plugin is profile-level and cannot reach a session\'s agent context.',
257
+ whyPluginBody3: ' Turning a row off means editing that preset\'s definition and restarting — I can generate the patch on request, but will not write it into your config.',
258
+ errEmptyDesc: 'Description cannot be empty', errNameReq: 'Skill name is required',
259
+ errNotFound: 'Cannot find a local directory for this skill: ',
260
+ },
261
+ }
262
+
263
+ /**
264
+ * 翻译入口:优先用 DSH 官方 ctx.locale.bind(跟随「界面语言」设置),
265
+ * 没有时(测试沙箱 / 旧版宿主)回退 zh 词典;键缺失再回退键名,永不返回 undefined。
266
+ */
267
+ let activeT = null
268
+ const baseTr = (key) => {
269
+ const viaActive = activeT ? activeT(key) : undefined
270
+ return viaActive ?? STRINGS.zh[key] ?? key
271
+ }
272
+
273
+ function Switch({ checked, disabled, onToggle, label }) {
274
+ return h('button', {
275
+ className: 'cm-switch',
276
+ type: 'button',
277
+ role: 'switch',
278
+ 'aria-checked': checked ? 'true' : 'false',
279
+ 'aria-label': label,
280
+ disabled,
281
+ onClick: onToggle,
282
+ })
283
+ }
284
+
285
+ function Item({ name, suffix, description, enabled, onToggle, pending, readonly, usedBy, usedByDetail, onGraph }) {
286
+ return h('div', { className: `cm-item${enabled ? '' : ' cm-off'}` },
287
+ h('div', { className: 'cm-main' },
288
+ h('div', { className: 'cm-name' }, name, suffix ? h('em', null, suffix) : null),
289
+ description ? h('div', { className: 'cm-desc' }, description) : null,
290
+ usedBy?.length
291
+ ? h('div', { className: 'cm-used' },
292
+ baseTr('usedByLabel') + (usedByDetail ?? usedBy.map((name) => ({ name, strength: 'optional' }))).slice(0, 3)
293
+ .map((dep) => (dep.strength === 'must' ? '★' : '') + dep.name).join('、')
294
+ + (usedBy.length > 3 ? baseTr('usedByMore') + usedBy.length + baseTr('usedByCount') : ''))
295
+ : null,
296
+ ),
297
+ onGraph
298
+ ? h('button', { className: 'cm-graphbtn', type: 'button', title: baseTr('graphBtnTitle'), onClick: onGraph }, baseTr('graphBtn'))
299
+ : null,
300
+ readonly
301
+ ? h('span', { className: 'cm-dot', 'data-off': enabled ? 'false' : 'true', title: baseTr(enabled ? 'readonlyOn' : 'readonlyOff') })
302
+ : h(Switch, { checked: enabled, disabled: pending, label: `${name} ${baseTr(enabled ? 'disable' : 'enable')}`, onToggle }),
303
+ )
304
+ }
305
+
306
+ const STRENGTH = {
307
+ must: { color: 'var(--dsw-alias-brand-primary)', width: 2.4, tag: baseTr('strengthMust') },
308
+ often: { color: 'var(--dsw-alias-state-warn-primary)', width: 1.7, tag: baseTr('strengthOften') },
309
+ optional: { color: 'var(--dsw-alias-state-idle-primary)', width: 1.1, tag: baseTr('strengthOptional') },
310
+ }
311
+
312
+ const shortText = (value, max) => (value.length > max ? value.slice(0, max - 1) + '…' : value)
313
+
314
+ /** 共享的上下游 SVG 图:「关联」弹框和关闭确认框都用它。中心=本能力,左=上游,右=下游。 */
315
+ function GraphSvg({ data }) {
316
+ const cap = 12
317
+ const upstream = (data?.upstream ?? []).slice(0, cap)
318
+ const downstream = (data?.downstream ?? []).slice(0, cap)
319
+ const hidden = Math.max((data?.upstream?.length ?? 0) - upstream.length, (data?.downstream?.length ?? 0) - downstream.length, 0)
320
+ const rowH = 48
321
+ const top = 56
322
+ const rows = Math.max(upstream.length, downstream.length, 1)
323
+ const height = top + rows * rowH + 52
324
+ const width = 880
325
+ const centerY = top + (rows * rowH) / 2 - 17
326
+
327
+ const node = (item, x, y, w, center) => {
328
+ const style = STRENGTH[item.strength] ?? STRENGTH.optional
329
+ return h('g', { key: item.name },
330
+ center
331
+ ? null
332
+ : h('line', {
333
+ x1: x < 440 ? x + w : 320 + 240,
334
+ y1: x < 440 ? y + 17 : centerY + 17,
335
+ x2: x < 440 ? 320 : x,
336
+ y2: x < 440 ? centerY + 17 : y + 17,
337
+ stroke: style.color, strokeWidth: style.width,
338
+ }),
339
+ h('rect', {
340
+ x, y, width: w, height: 34, rx: 9,
341
+ fill: center ? 'var(--dsw-alias-brand-primary)' : 'var(--dsw-alias-bg-layer-1)',
342
+ stroke: center ? 'none' : style.color,
343
+ strokeWidth: center ? 0 : style.width,
344
+ }),
345
+ h('text', {
346
+ x: x + 12, y: y + 14, fontSize: center ? 13 : 11.5,
347
+ fill: center ? '#fff' : (item.strength === 'must' ? 'var(--dsw-alias-label-primary)' : 'var(--dsw-alias-label-secondary)'),
348
+ }, shortText(item.label, center ? 28 : 21)),
349
+ h('text', {
350
+ x: x + 12, y: y + 27, fontSize: 9.5,
351
+ fill: center ? 'rgba(255,255,255,.8)' : 'var(--dsw-alias-label-tertiary)',
352
+ }, (item.kind === 'tool' ? baseTr('svgTool') : baseTr('svgSkill')) + (item.hits > 0 ? baseTr('svgHits') + item.hits + baseTr('svgHitsSuffix') : '')),
353
+ )
354
+ }
355
+
356
+ const legend = [
357
+ ['must', baseTr('legendMust')],
358
+ ['often', baseTr('legendOften')],
359
+ ['optional', baseTr('legendOptional')],
360
+ ]
361
+
362
+ return h('svg', { viewBox: `0 0 ${width} ${height}`, width: '100%', role: 'img' },
363
+ h('text', { x: 20, y: 30, fontSize: 11, fill: 'var(--dsw-alias-label-secondary)' }, baseTr('svgUp')),
364
+ h('text', { x: 440, y: 30, fontSize: 11, textAnchor: 'middle', fill: 'var(--dsw-alias-label-secondary)' }, baseTr('svgCenter')),
365
+ h('text', { x: 860, y: 30, fontSize: 11, textAnchor: 'end', fill: 'var(--dsw-alias-label-secondary)' }, baseTr('svgDown')),
366
+ upstream.map((item, index) => node(item, 20, top + index * rowH, 230, false)),
367
+ downstream.map((item, index) => node(item, 630, top + index * rowH, 230, false)),
368
+ node({ name: data?.name, label: data?.label ?? '?', kind: data?.kind, hits: 0 }, 320, centerY, 240, true),
369
+ legend.map(([key, text], index) => h('g', { key },
370
+ h('rect', { x: 20 + index * 170, y: height - 34, width: 10, height: 10, rx: 3, fill: STRENGTH[key].color }),
371
+ h('text', { x: 36 + index * 170, y: height - 25, fontSize: 10, fill: 'var(--dsw-alias-label-secondary)' }, text),
372
+ )),
373
+ hidden > 0
374
+ ? h('text', { x: 860, y: height - 25, fontSize: 10, textAnchor: 'end', fill: 'var(--dsw-alias-label-tertiary)' }, baseTr('svgHidden') + hidden + baseTr('svgHiddenSuffix'))
375
+ : null,
376
+ )
377
+ }
378
+
379
+ /**
380
+ * 「详情」按钮的弹框:描述(技能可就地编辑)+ 图 + 加载/空态/口径。图本体在 GraphSvg。
381
+ */
382
+ function GraphModal({ target, data, error, onClose, onSaveDesc }) {
383
+ const [editing, setEditing] = useState(null)
384
+ const [saving, setSaving] = useState(false)
385
+ const [msg, setMsg] = useState(null)
386
+ const empty = data && (data.upstream?.length ?? 0) === 0 && (data.downstream?.length ?? 0) === 0
387
+ const editable = target.kind === 'skill' && typeof onSaveDesc === 'function'
388
+ return h('div', { className: 'cm-mask', role: 'dialog', 'aria-modal': 'true', onClick: (e) => { if (e.target === e.currentTarget) onClose() } },
389
+ h('div', { className: 'cm-dialog cm-graphdlg' },
390
+ h('h3', null, baseTr('detail') + target.label),
391
+ data
392
+ ? h('div', { className: 'cm-detaildesc' },
393
+ h('b', null, baseTr('desc')),
394
+ editing === null
395
+ ? h('p', null, data.description || baseTr('noDesc'))
396
+ : h('textarea', {
397
+ className: 'cm-descedit',
398
+ value: editing,
399
+ rows: 4,
400
+ onChange: (event) => setEditing(event.target.value),
401
+ }),
402
+ editable
403
+ ? h('div', { className: 'cm-desceditbar' },
404
+ editing === null
405
+ ? h('button', { className: 'cm-btn', type: 'button', onClick: () => { setEditing(data.description || ''); setMsg(null) } }, baseTr('editDesc'))
406
+ : h(React.Fragment, null,
407
+ h('button', {
408
+ className: 'cm-btn', type: 'button', 'data-primary': 'true', disabled: saving,
409
+ onClick: async () => {
410
+ setSaving(true)
411
+ setMsg(null)
412
+ try {
413
+ await onSaveDesc(editing)
414
+ setEditing(null)
415
+ setMsg({ text: baseTr('savedMsg'), err: false })
416
+ } catch (cause) {
417
+ setMsg({ text: cause instanceof Error ? cause.message : String(cause), err: true })
418
+ } finally {
419
+ setSaving(false)
420
+ }
421
+ },
422
+ }, saving ? baseTr('saving') : baseTr('save')),
423
+ h('button', { className: 'cm-btn', type: 'button', disabled: saving, onClick: () => { setEditing(null); setMsg(null) } }, baseTr('cancel'))),
424
+ msg ? h('span', { className: msg.err ? 'cm-descmsg cm-descmsg--err' : 'cm-descmsg' }, msg.text) : null,
425
+ h('p', { className: 'cm-descnote' }, baseTr('editDescNote')))
426
+ : (target.kind === 'tool'
427
+ ? h('p', { className: 'cm-descnote' }, baseTr('toolDescNote'))
428
+ : null),
429
+ )
430
+ : null,
431
+ h('p', { className: 'cm-detailsub' }, baseTr('upstreamTitle')),
432
+ error
433
+ ? h('p', { className: 'cm-error' }, baseTr('readFail') + error)
434
+ : !data
435
+ ? h('p', null, baseTr('graphLoading'))
436
+ : (empty
437
+ ? h('p', null,
438
+ baseTr('emptyGraph1'),
439
+ baseTr('emptyGraph2'))
440
+ : h('div', { className: 'cm-graphwrap' }, h(GraphSvg, { data }))),
441
+ h('div', { className: 'cm-graphfoot' },
442
+ h('span', null, baseTr('methodFoot'),
443
+ data?.at ? baseTr('methodFootAt') + new Date(data.at).toLocaleTimeString() : ''),
444
+ h('button', { className: 'cm-btn', type: 'button', onClick: onClose }, baseTr('close')),
445
+ ),
446
+ ))
447
+ }
448
+
449
+ function Group({ title, summary, children }) {
450
+ return h('div', { className: 'cm-group' },
451
+ h('div', { className: 'cm-grouphead' }, h('strong', null, title), h('span', null, summary)),
452
+ children,
453
+ )
454
+ }
455
+
456
+ /** Process-wide cache: leaving the view and coming back must not refetch. */
457
+ const cache = { preset: null, data: null }
458
+
459
+ function presetOf(snapshot) {
460
+ if (!snapshot) return null
461
+ const candidate = snapshot.agentPreset ?? snapshot.preset ?? snapshot.presetId
462
+ if (typeof candidate === 'string') return candidate
463
+ if (candidate && typeof candidate === 'object') return candidate.id ?? null
464
+ return null
465
+ }
466
+
467
+ function CapabilityManager(props) {
468
+ const useSession = props?.useSession
469
+ // i18n:prop 传入的 t(测试)或 apply() 里绑的 ctx.locale(跟随界面语言)。
470
+ const prevT = activeT
471
+ activeT = props?.t ?? activeT
472
+ try {
473
+ return renderCapabilityManager(useSession)
474
+ } finally {
475
+ activeT = prevT
476
+ }
477
+ }
478
+
479
+ function renderCapabilityManager(useSession) {
480
+ let presetId = null
481
+ try {
482
+ const snapshot = typeof useSession === 'function' ? useSession((value) => value) : null
483
+ presetId = presetOf(snapshot)
484
+ } catch {
485
+ presetId = null
486
+ }
487
+
488
+ const [state, setState] = useState(() => (cache.preset === presetId ? cache.data : null))
489
+ const [error, setError] = useState(null)
490
+ const [query, setQuery] = useState('')
491
+ const [tab, setTab] = useState(null)
492
+ const [resolved, setResolved] = useState(() => new Set())
493
+ const [confirming, setConfirming] = useState(null)
494
+ const [graph, setGraph] = useState(null)
495
+ const [graphData, setGraphData] = useState(null)
496
+ const [graphError, setGraphError] = useState(null)
497
+ const [skipConfirm, setSkipConfirm] = useState(false)
498
+ const [confirmGraph, setConfirmGraph] = useState(null)
499
+ const [busy, setBusy] = useState(false)
500
+ const [pending, setPending] = useState(() => new Set())
501
+
502
+ const load = useCallback(async (force) => {
503
+ if (!force && cache.data && cache.preset === presetId) {
504
+ setState(cache.data)
505
+ return
506
+ }
507
+ setBusy(true)
508
+ try {
509
+ const suffix = presetId ? `?preset=${encodeURIComponent(presetId)}` : ''
510
+ const response = await fetch(`${API}/mode${suffix}`, { credentials: 'same-origin' })
511
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
512
+ const payload = await response.json()
513
+ cache.preset = presetId
514
+ cache.data = payload
515
+ setState(payload)
516
+ setError(null)
517
+ } catch (cause) {
518
+ setError(cause instanceof Error ? cause.message : String(cause))
519
+ } finally {
520
+ setBusy(false)
521
+ }
522
+ }, [presetId])
523
+
524
+ // First mount only; every later visit reuses the cache.
525
+ useEffect(() => { load(false) }, [load])
526
+
527
+ const doToggle = useCallback(async (kind, name, enabled, use = '') => {
528
+ const key = `${kind}:${name}`
529
+ setPending((current) => new Set(current).add(key))
530
+ try {
531
+ const response = await fetch(`${API}/toggle`, {
532
+ method: 'POST',
533
+ headers: { 'content-type': 'application/json' },
534
+ credentials: 'same-origin',
535
+ body: JSON.stringify({ kind, name, enabled, use }),
536
+ })
537
+ const payload = await response.json()
538
+ if (!response.ok) throw new Error(payload?.error ?? `HTTP ${response.status}`)
539
+ // Patch locally instead of refetching the whole payload.
540
+ setState((current) => {
541
+ if (!current) return current
542
+ if (kind === 'skill') {
543
+ const skills = current.skills.map((row) => (row.name === name ? { ...row, enabled } : row))
544
+ return {
545
+ ...current,
546
+ skills,
547
+ counts: { ...current.counts, skillsOff: skills.filter((row) => !row.enabled).length },
548
+ }
549
+ }
550
+ const mcps = current.mcps.map((mcp) => {
551
+ const tools = mcp.tools.map((tool) => (tool.name === name ? { ...tool, enabled } : tool))
552
+ return { ...mcp, tools, on: tools.filter((tool) => tool.enabled).length }
553
+ })
554
+ return {
555
+ ...current,
556
+ mcps,
557
+ counts: { ...current.counts, mcpOff: mcps.reduce((total, mcp) => total + (mcp.tools.length - mcp.on), 0) },
558
+ }
559
+ })
560
+ setError(null)
561
+ } catch (cause) {
562
+ setError(cause instanceof Error ? cause.message : String(cause))
563
+ load(true)
564
+ } finally {
565
+ setPending((current) => {
566
+ const next = new Set(current)
567
+ next.delete(key)
568
+ return next
569
+ })
570
+ }
571
+ }, [load])
572
+
573
+ const metaBy = useMemo(() => {
574
+ const map = new Map()
575
+ for (const skill of state?.skills ?? []) map.set('skill:' + skill.name, skill)
576
+ for (const mcp of state?.mcps ?? []) for (const tool of mcp.tools) map.set('tool:' + tool.name, tool)
577
+ return map
578
+ }, [state])
579
+ const counts = state?.counts
580
+ const preset = state?.preset
581
+ const needle = query.trim().toLowerCase()
582
+ const match = (value) => !needle || (value ?? '').toLowerCase().includes(needle)
583
+
584
+ const overlaps = useMemo(
585
+ () => (state?.overlaps ?? []).filter((pair) => !resolved.has(pair.key)),
586
+ [state, resolved],
587
+ )
588
+ const ignoredOverlaps = state?.ignoredOverlaps ?? []
589
+ const skills = useMemo(
590
+ () => (state?.skills ?? []).filter((row) => match(row.name) || match(row.description)),
591
+ [state, needle],
592
+ )
593
+ const mcps = useMemo(() => (state?.mcps ?? [])
594
+ .map((mcp) => ({ ...mcp, tools: mcp.tools.filter((tool) => match(tool.tool) || match(tool.description)) }))
595
+ .filter((mcp) => mcp.tools.length > 0 || match(mcp.server)), [state, needle])
596
+ const plugins = useMemo(
597
+ () => (state?.plugins ?? []).filter((row) => match(row.module)),
598
+ [state, needle],
599
+ )
600
+
601
+ const fetchGraph = useCallback(async (kind, name) => {
602
+ try {
603
+ const response = await fetch(API + '/graph?kind=' + kind + '&name=' + encodeURIComponent(name), { credentials: 'same-origin' })
604
+ const payload = await response.json()
605
+ if (!response.ok) throw new Error(payload?.error ?? 'HTTP ' + response.status)
606
+ return payload
607
+ } catch (cause) {
608
+ return { error: cause instanceof Error ? cause.message : String(cause) }
609
+ }
610
+ }, [])
611
+
612
+ const openGraph = useCallback(async (kind, name, label) => {
613
+ setGraph({ kind, name, label })
614
+ setGraphData(null)
615
+ setGraphError(null)
616
+ const payload = await fetchGraph(kind, name)
617
+ if (payload?.error) setGraphError(payload.error)
618
+ else setGraphData(payload)
619
+ }, [fetchGraph])
620
+
621
+ const applyConfirm = useCallback(async (target) => {
622
+ setConfirming(null)
623
+ setConfirmGraph(null)
624
+ if (target.pair) {
625
+ setResolved((current) => new Set(current).add(target.pair.key))
626
+ const kept = target.which === 'left' ? target.pair.right : target.pair.left
627
+ const use = target.drop.kind === 'tool' && kept?.kind === 'tool' ? kept.name : ''
628
+ await doToggle(target.drop.kind, target.drop.name, false, use)
629
+ } else {
630
+ await doToggle(target.kind, target.name, false)
631
+ }
632
+ }, [doToggle])
633
+
634
+ /** 弹确认框,并顺带拉取关闭目标的上下游图。 */
635
+ const askConfirm = useCallback((target) => {
636
+ setConfirming(target)
637
+ setConfirmGraph(null)
638
+ fetchGraph(target.kind, target.name).then((payload) => {
639
+ if (payload?.error) return
640
+ setConfirmGraph({ for: target.kind + ':' + target.name, data: payload })
641
+ })
642
+ }, [fetchGraph])
643
+
644
+ /** 一次选择会真的关掉一个能力,所以先弹确认(含上下游图);勾选过忽略则直接执行。 */
645
+ const keep = useCallback((pair, which) => {
646
+ const drop = which === 'left' ? pair.right : pair.left
647
+ const target = {
648
+ pair,
649
+ which,
650
+ drop,
651
+ label: drop.label,
652
+ kind: drop.kind,
653
+ name: drop.name,
654
+ usedBy: drop.usedBy ?? [],
655
+ usedByDetail: drop.usedByDetail ?? [],
656
+ bothMention: pair.bothMention ?? [],
657
+ }
658
+ if (skipConfirm) {
659
+ applyConfirm(target)
660
+ return
661
+ }
662
+ askConfirm(target)
663
+ }, [skipConfirm, applyConfirm, askConfirm])
664
+
665
+ /** 关一个被引用的能力,先过确认框;没有引用的、或已忽略确认的,直接执行。 */
666
+ const onToggle = (kind, name, enabled) => {
667
+ if (!enabled && !skipConfirm) {
668
+ const item = metaBy.get(`${kind}:${name}`)
669
+ if (item?.usedBy?.length) {
670
+ askConfirm({ kind, name, label: item.tool ?? item.name, usedBy: item.usedBy, usedByDetail: item.usedByDetail, bothMention: [] })
671
+ return
672
+ }
673
+ }
674
+ doToggle(kind, name, enabled)
675
+ }
676
+
677
+ /** 忽略(判定非重合):写进 Host 状态文件;回包就是新的 mode 数据,顺带刷新本地缓存。 */
678
+ const dismiss = useCallback(async (pair) => {
679
+ setResolved((current) => new Set(current).add(pair.key))
680
+ try {
681
+ const response = await fetch(`${API}/ignore`, {
682
+ method: 'POST',
683
+ headers: { 'content-type': 'application/json' },
684
+ credentials: 'same-origin',
685
+ body: JSON.stringify({ key: pair.key, ignored: true }),
686
+ })
687
+ const payload = await response.json().catch(() => null)
688
+ if (payload && !payload.error) {
689
+ cache.preset = presetId
690
+ cache.data = payload
691
+ setState(payload)
692
+ }
693
+ } catch (cause) {
694
+ setError(cause instanceof Error ? cause.message : String(cause))
695
+ }
696
+ }, [presetId])
697
+
698
+ /** 恢复一组被忽略的重合检查。 */
699
+ const restorePair = useCallback(async (row) => {
700
+ try {
701
+ const response = await fetch(`${API}/ignore`, {
702
+ method: 'POST',
703
+ headers: { 'content-type': 'application/json' },
704
+ credentials: 'same-origin',
705
+ body: JSON.stringify({ key: row.key, ignored: false }),
706
+ })
707
+ const payload = await response.json().catch(() => null)
708
+ if (payload && !payload.error) {
709
+ cache.preset = presetId
710
+ cache.data = payload
711
+ setState(payload)
712
+ setResolved((current) => {
713
+ const next = new Set(current)
714
+ next.delete(row.key)
715
+ return next
716
+ })
717
+ }
718
+ } catch (cause) {
719
+ setError(cause instanceof Error ? cause.message : String(cause))
720
+ }
721
+ }, [presetId])
722
+
723
+ /** 技能描述就地编辑:写回 SKILL.md 后全量刷新(技能行、详情、重合语料都会重算)。 */
724
+ const saveSkillDesc = useCallback(async (name, description) => {
725
+ const response = await fetch(`${API}/skill-desc`, {
726
+ method: 'POST',
727
+ headers: { 'content-type': 'application/json' },
728
+ credentials: 'same-origin',
729
+ body: JSON.stringify({ name, description }),
730
+ })
731
+ const payload = await response.json().catch(() => ({}))
732
+ if (!response.ok) throw new Error(mapHostError(payload?.error, name) ?? `HTTP ${response.status}`)
733
+ if (cache.data) cache.data = null
734
+ await load(true)
735
+ setGraphData((current) => (current ? { ...current, description: payload.description } : current))
736
+ }, [load])
737
+
738
+ /** 宿主错误码 → 本地化消息;未知错误返回 null 由调用方兜底。 */
739
+ const mapHostError = (code, name) => {
740
+ if (code === 'empty-description') return baseTr('errEmptyDesc')
741
+ if (code === 'name-required') return baseTr('errNameReq')
742
+ if (typeof code === 'string' && code.startsWith('skill-not-found:')) return baseTr('errNotFound') + (code.slice('skill-not-found:'.length) || name)
743
+ return null
744
+ }
745
+
746
+ const providerOff = Boolean(state && state.skillProviderOn === false)
747
+ const active = tab ?? (overlaps.length > 0 ? 'overlap' : 'mcp')
748
+
749
+ const tabs = [
750
+ ['overlap', baseTr('tabOverlap'), overlaps.length ? String(overlaps.length) : '0'],
751
+ ['mcp', 'MCP', counts ? `${counts.mcpTools}` + baseTr('toolsUnit') : ''],
752
+ ['skill', baseTr('tabSkill'), counts ? `${counts.skills - counts.skillsOff}/${counts.skills}` + baseTr('enabledUnit') : ''],
753
+ ['plugin', baseTr('tabPlugin'), counts ? `${counts.pluginsOn}/${counts.plugins}` + baseTr('enabledUnit') : ''],
754
+ ]
755
+
756
+ return h('div', { className: 'cm' },
757
+ h('style', null, STYLE),
758
+ h('div', { className: 'cm-head' },
759
+ h('div', null,
760
+ h('div', { className: 'cm-title' },
761
+ baseTr('title'),
762
+ h('span', { className: 'cm-mode', 'data-state': providerOff ? 'off' : 'on' },
763
+ preset ? (preset.name ?? preset.id) : baseTr('presetDefault')),
764
+ ),
765
+ h('p', { className: 'cm-sub' },
766
+ providerOff ? baseTr('subProviderOff') : baseTr('sub')),
767
+ ),
768
+ h('div', { className: 'cm-actions' },
769
+ h('button', { className: 'cm-btn', type: 'button', disabled: busy, onClick: () => load(true) },
770
+ busy ? baseTr('checking') : baseTr('recheck')),
771
+ skipConfirm ? h('span', { className: 'cm-skiptag', title: baseTr('skipTagTitle') }, baseTr('skipTag')) : null,
772
+ ),
773
+ ),
774
+
775
+ error ? h('div', { className: 'cm-error' }, baseTr('readFail') + `${error}`) : null,
776
+ !state && !error ? h('div', { className: 'cm-empty' }, baseTr('firstOpen')) : null,
777
+
778
+ state && overlaps.length > 0
779
+ ? h('div', { className: 'cm-banner' },
780
+ h('div', null,
781
+ h('b', null, baseTr('bannerFound') + overlaps.length + baseTr('bannerFoundSuffix')),
782
+ h('p', null, baseTr('bannerHint')),
783
+ ),
784
+ )
785
+ : null,
786
+
787
+ state
788
+ ? h(React.Fragment, null,
789
+ h('div', { className: 'cm-tabs' },
790
+ tabs.map(([key, label, hint]) => h('button', {
791
+ key,
792
+ className: 'cm-tab',
793
+ type: 'button',
794
+ role: 'tab',
795
+ 'data-hot': key === 'overlap' && overlaps.length > 0 ? 'true' : 'false',
796
+ 'aria-selected': active === key ? 'true' : 'false',
797
+ onClick: () => setTab(key),
798
+ }, label, hint ? h('b', null, ` ${hint}`) : null)),
799
+ ),
800
+
801
+ active !== 'overlap'
802
+ ? h('input', {
803
+ className: 'cm-search',
804
+ type: 'search',
805
+ value: query,
806
+ placeholder: active === 'mcp'
807
+ ? baseTr('searchMcp')
808
+ : active === 'skill' ? baseTr('searchSkill') : baseTr('searchPlugin'),
809
+ onChange: (event) => setQuery(event.target.value),
810
+ })
811
+ : null,
812
+
813
+ active === 'overlap'
814
+ ? h(Group, { title: baseTr('overlapTitle'), summary: `${overlaps.length}` + baseTr('overlapSummary') },
815
+ overlaps.length === 0
816
+ ? h('div', { className: 'cm-empty' }, baseTr('overlapEmpty'))
817
+ : overlaps.map((pair) => h('div', { key: pair.key, className: 'cm-pair' },
818
+ h('div', { className: 'cm-pairtop' },
819
+ h('span', { className: 'cm-pairname' }, pair.left.label),
820
+ h('span', { className: 'cm-pairkind' }, pair.left.kind === 'skill' ? baseTr('kindSkill') : baseTr('kindMcp')),
821
+ h('span', { className: 'cm-pairkind' }, '×'),
822
+ h('span', { className: 'cm-pairname' }, pair.right.label),
823
+ h('span', { className: 'cm-pairkind' }, pair.right.kind === 'skill' ? baseTr('kindSkill') : baseTr('kindMcp')),
824
+ h('span', { className: 'cm-score' }, pair.score.toFixed(2)),
825
+ ),
826
+ pair.reasons?.length
827
+ ? h('p', { className: 'cm-why' }, pair.reasons.join(' · '))
828
+ : null,
829
+ pair.left?.usedBy?.length || pair.right?.usedBy?.length
830
+ ? h('p', { className: 'cm-why' },
831
+ pair.left?.usedBy?.length ? baseTr('leftUsedBy') + pair.left.usedBy.join('、') + baseTr('usedByRef') : '',
832
+ pair.left?.usedBy?.length && pair.right?.usedBy?.length ? ';' : '',
833
+ pair.right?.usedBy?.length ? baseTr('rightUsedBy') + pair.right.usedBy.join('、') + baseTr('usedByRef') : '')
834
+ : null,
835
+ h('div', { className: 'cm-paira' },
836
+ h('button', {
837
+ className: 'cm-btn',
838
+ type: 'button',
839
+ 'data-primary': 'true',
840
+ disabled: pending.has(`${pair.left.kind}:${pair.left.name}`) || pending.has(`${pair.right.kind}:${pair.right.name}`),
841
+ onClick: () => keep(pair, 'left'),
842
+ }, baseTr('keep') + pair.left.label),
843
+ h('button', {
844
+ className: 'cm-btn',
845
+ type: 'button',
846
+ 'data-primary': 'true',
847
+ disabled: pending.has(`${pair.left.kind}:${pair.left.name}`) || pending.has(`${pair.right.kind}:${pair.right.name}`),
848
+ onClick: () => keep(pair, 'right'),
849
+ }, baseTr('keep') + pair.right.label),
850
+ h('button', {
851
+ className: 'cm-btn',
852
+ type: 'button',
853
+ title: baseTr('notOverlapTitle'),
854
+ onClick: () => dismiss(pair),
855
+ }, baseTr('notOverlap')),
856
+ ),
857
+ )))
858
+ : null,
859
+
860
+ active === 'overlap' && ignoredOverlaps.length > 0
861
+ ? h(Group, { title: baseTr('ignoredTitle'), summary: `${ignoredOverlaps.length}` + baseTr('ignoredSummary') },
862
+ ignoredOverlaps.map((row) => h('div', { key: row.key, className: 'cm-pair' },
863
+ h('div', { className: 'cm-pairtop' },
864
+ h('span', { className: 'cm-pairname' }, row.left),
865
+ h('span', { className: 'cm-pairkind' }, '×'),
866
+ h('span', { className: 'cm-pairname' }, row.right)),
867
+ h('div', { className: 'cm-paira' },
868
+ h('button', { className: 'cm-btn', type: 'button', onClick: () => restorePair(row) }, baseTr('restore'))))))
869
+ : null,
870
+
871
+ active === 'mcp'
872
+ ? (mcps.length === 0
873
+ ? h(Group, { title: 'MCP', summary: baseTr('mcpNone') },
874
+ h('div', { className: 'cm-empty' }, baseTr('mcpEmpty')))
875
+ : mcps.map((mcp) => h(Group, {
876
+ key: mcp.server,
877
+ title: `MCP · ${mcp.server}`,
878
+ summary: `${mcp.on}/${mcp.tools.length}` + baseTr('toolsUnit'),
879
+ }, mcp.tools.map((tool) => h(Item, {
880
+ key: tool.name,
881
+ name: tool.tool,
882
+ suffix: !tool.enabled && tool.use ? baseTr('blockedUse') + tool.use.split('__').pop() : undefined,
883
+ usedBy: tool.usedBy,
884
+ usedByDetail: tool.usedByDetail,
885
+ onGraph: () => openGraph('tool', tool.name, tool.tool),
886
+ description: tool.description,
887
+ enabled: tool.enabled,
888
+ pending: pending.has(`tool:${tool.name}`),
889
+ onToggle: () => onToggle('tool', tool.name, !tool.enabled),
890
+ })))))
891
+ : null,
892
+
893
+ active === 'skill'
894
+ ? h(Group, { title: baseTr('skillTitle'), summary: `${counts.skills - counts.skillsOff}/${counts.skills}` + baseTr('enabledUnit') },
895
+ skills.length === 0
896
+ ? h('div', { className: 'cm-empty' }, query ? baseTr('skillEmptyQ') : baseTr('skillEmpty'))
897
+ : skills.map((skill) => h(Item, {
898
+ key: skill.name,
899
+ name: skill.name,
900
+ usedBy: skill.usedBy,
901
+ usedByDetail: skill.usedByDetail,
902
+ onGraph: () => openGraph('skill', skill.name, skill.name),
903
+ suffix: `${skill.copies.length}` + baseTr('copiesUnit') + (skill.copies.some((copy) => copy.link) ? baseTr('copiesLink') : ''),
904
+ description: skill.description,
905
+ enabled: skill.enabled,
906
+ pending: pending.has(`skill:${skill.name}`),
907
+ onToggle: () => onToggle('skill', skill.name, !skill.enabled),
908
+ })))
909
+ : null,
910
+
911
+ active === 'plugin'
912
+ ? h(Group, { title: baseTr('pluginTitle'), summary: `${counts.pluginsOn}/${counts.plugins}` + baseTr('pluginSummarySuffix') },
913
+ plugins.length === 0
914
+ ? h('div', { className: 'cm-empty' }, query ? baseTr('pluginEmptyQ') : baseTr('pluginEmpty'))
915
+ : plugins.map((plugin) => h(Item, {
916
+ key: plugin.module,
917
+ name: plugin.module.replace(/^@deepseek-ai\//, ''),
918
+ suffix: plugin.condition ? baseTr('pluginCond') + plugin.condition : undefined,
919
+ description: plugin.module,
920
+ enabled: plugin.enabled,
921
+ readonly: true,
922
+ })))
923
+ : null,
924
+
925
+
926
+ confirming
927
+ ? h('div', { className: 'cm-mask', role: 'dialog', 'aria-modal': 'true' },
928
+ h('div', { className: 'cm-dialog cm-graphdlg' },
929
+ h('h3', null, baseTr('confirmTitle')),
930
+ h('p', null,
931
+ confirming.pair ? baseTr('confirmKeep') : baseTr('confirmClosePrefix'),
932
+ confirming.pair
933
+ ? h('code', null, confirming.which === 'left' ? confirming.pair.left.label : confirming.pair.right.label)
934
+ : null,
935
+ confirming.pair ? baseTr('confirmComma') : null,
936
+ h('code', null, confirming.label),
937
+ baseTr('confirmEnd'),
938
+ ),
939
+ confirming.pair
940
+ ? h('div', { className: 'cm-descs' },
941
+ h('div', { className: 'cm-desccard cm-desccard--keep' },
942
+ h('b', null, baseTr('keepCard') + (confirming.which === 'left' ? confirming.pair.left.label : confirming.pair.right.label)),
943
+ h('p', null, (confirming.which === 'left' ? confirming.pair.left.description : confirming.pair.right.description) || baseTr('noDesc'))),
944
+ h('div', { className: 'cm-desccard cm-desccard--drop' },
945
+ h('b', null, baseTr('dropCard') + confirming.drop.label),
946
+ h('p', null, confirming.drop.description || baseTr('noDesc'))))
947
+ : null,
948
+ confirming.usedBy?.length
949
+ ? h('div', null,
950
+ h('p', { className: 'cm-dephead' },
951
+ baseTr('affectHead')),
952
+ h('div', { className: 'cm-deplist' },
953
+ (confirming.usedByDetail ?? confirming.usedBy.map((name) => ({ name, hits: 0, strength: 'optional' })))
954
+ .slice(0, 6)
955
+ .map((dep) => h('span', {
956
+ key: dep.name,
957
+ className: 'cm-dep',
958
+ 'data-strength': dep.strength,
959
+ title: baseTr('depHits') + dep.hits + baseTr('depHitsSuffix'),
960
+ }, dep.name + (dep.hits ? ' ×' + dep.hits : ''))),
961
+ confirming.usedBy.length > 6 ? h('span', { className: 'cm-dep' }, baseTr('depMore') + confirming.usedBy.length + baseTr('depMoreSuffix')) : null),
962
+ (confirming.usedByDetail ?? []).some((dep) => dep.strength === 'must')
963
+ ? h('p', { className: 'cm-depwarn' },
964
+ baseTr('mustWarn'))
965
+ : h('p', null, baseTr('degradeWarn')),
966
+ )
967
+ : h('p', null, baseTr('noDep')),
968
+ confirming.pair
969
+ ? (confirming.bothMention?.length
970
+ ? h('p', null, baseTr('bothMention1') + confirming.bothMention.join('、') + baseTr('bothMention2'))
971
+ : h('p', null, baseTr('noAlt')))
972
+ : null,
973
+ confirming.pair
974
+ ? (confirming.drop.kind === 'tool'
975
+ ? ((confirming.which === 'left' ? confirming.pair.right : confirming.pair.left).kind === 'tool'
976
+ ? h('p', null,
977
+ baseTr('altReg1'),
978
+ h('code', null, confirming.drop.label),
979
+ baseTr('altReg2'),
980
+ h('code', null, (confirming.which === 'left' ? confirming.pair.right : confirming.pair.left).label),
981
+ baseTr('altReg3'))
982
+ : h('p', null,
983
+ baseTr('keepSkill1'),
984
+ h('code', null, confirming.drop.label),
985
+ baseTr('keepSkill2')))
986
+ : h('p', null, baseTr('dropSkillShadow')))
987
+ : null,
988
+ confirmGraph && confirmGraph.for === confirming.kind + ':' + confirming.name && confirmGraph.data
989
+ ? h('div', { className: 'cm-graphwrap cm-graphwrap--dialog' }, h(GraphSvg, { data: confirmGraph.data }))
990
+ : h('p', { className: 'cm-graphload' }, baseTr('graphLoadDialog')),
991
+ h('p', null,
992
+ confirming.kind === 'skill' ? baseTr('skillHow') : baseTr('toolHow'),
993
+ ),
994
+ h('div', { className: 'cm-dialogfoot' },
995
+ h('label', { className: 'cm-check' },
996
+ h('input', {
997
+ type: 'checkbox',
998
+ checked: skipConfirm,
999
+ onChange: (event) => setSkipConfirm(event.target.checked),
1000
+ }),
1001
+ baseTr('noConfirmAgain')),
1002
+ h('button', { className: 'cm-btn', type: 'button', onClick: () => { setConfirming(null); setConfirmGraph(null) } }, baseTr('cancel')),
1003
+ h('button', { className: 'cm-btn', type: 'button', onClick: () => applyConfirm(confirming) }, baseTr('confirmCloseBtn')),
1004
+ ),
1005
+ ))
1006
+ : null,
1007
+
1008
+ graph
1009
+ ? h(GraphModal, {
1010
+ target: graph,
1011
+ data: graphData,
1012
+ error: graphError,
1013
+ onClose: () => { setGraph(null); setGraphData(null) },
1014
+ onSaveDesc: graph.kind === 'skill' ? (text) => saveSkillDesc(graph.name, text) : undefined,
1015
+ })
1016
+ : null,
1017
+
1018
+ h('div', { className: 'cm-note' },
1019
+ h('b', null, baseTr('howTitle')),
1020
+ baseTr('howBody1'),
1021
+ baseTr('howBody2'),
1022
+ String(state.overlapFloor ?? 0.25),
1023
+ baseTr('howBody3'),
1024
+ ),
1025
+
1026
+ h('div', { className: 'cm-note' },
1027
+ h('b', null, baseTr('whyPluginTitle')),
1028
+ baseTr('whyPluginBody1'),
1029
+ baseTr('whyPluginBody2'),
1030
+ baseTr('whyPluginBody3'),
1031
+ ),
1032
+ )
1033
+ : null,
1034
+ )
1035
+ }
1036
+
1037
+ return {
1038
+ inject: ['slots', 'locale'],
1039
+ apply(ctx) {
1040
+ // i18n:向 DSH 的「界面语言」注册双语词典,绑定后 tab 标签与面板文案跟随语言切换。
1041
+ try {
1042
+ if (ctx.locale?.bind) activeT = ctx.locale.bind(LOCALE_NS)
1043
+ if (ctx.locale?.register && ctx.effect) {
1044
+ ctx.effect(() => ctx.locale.register(LOCALE_NS, STRINGS), 'capability-trimmer: locale dictionaries')
1045
+ }
1046
+ } catch (cause) {
1047
+ console.error('[capability-trimmer] locale wiring failed', cause)
1048
+ }
1049
+ // conversation.view 是「对话」「轨迹」所在的那一排(chat=0 / trajectory=10)。
1050
+ const options = {
1051
+ name: 'conversation.view',
1052
+ id: 'capability',
1053
+ order: 20,
1054
+ label: () => baseTr('tab'),
1055
+ strings: STRINGS,
1056
+ }
1057
+ try {
1058
+ ctx.slots.inject('conversation.view', () => ctx.slots.register(options, CapabilityManager))
1059
+ } catch (cause) {
1060
+ console.error('[capability-trimmer] slot registration failed', cause)
1061
+ ctx.slots.register(options, CapabilityManager)
1062
+ }
1063
+ },
1064
+ }
1065
+ },
1066
+ })