@crocketc/dsh-capability-manager 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.js CHANGED
@@ -1,358 +1,585 @@
1
- window.__ModuleLoader__.load({ id: '@crocketc/dsh-capability-manager', factory(require) {
2
- const React = require('react')
3
-
4
- /** Browser entry for the Agent Capability Manager panel. */
5
- const inject = ['slots']
6
-
7
- const ID = 'dsh-capability-manager'
8
- const ENDPOINT = '/api/dsh-capability-manager'
9
- const categories = [
10
- ['skill-catalog', '全局技能', '#7843d6'],
11
- ['workspace-skill-catalog', '工作区技能', '#c23080'],
12
- ['builtin-tools', '内置工具', '#2761c5'],
13
- ['plugin-tools', '插件工具', '#ad6c0b'],
14
- ['mcp-tools', 'MCP 工具', '#008577'],
15
- ['unknown-tools', '未归因工具', '#767e91'],
16
- ['tool-prompt', '工具提示', '#755a35'],
17
- ['ptc-shared', 'PTC 共享声明', '#467da2'],
18
- ['run-code', 'PTC 固定入口', '#9663a0'],
19
- ['base-system', '基础系统提示词', '#62738c'],
20
- ['automatic', '其他自动注入', '#c76334'],
21
- ]
22
-
23
- function budgetRows(budget) {
24
- const counts = new Map()
25
- for (const { key, tokens } of budget?.breakdown ?? []) {
26
- const category = /^ptc-.*-tools$/.test(key) ? key.slice(4) : key
27
- counts.set(category, (counts.get(category) ?? 0) + tokens)
28
- }
29
- return categories.map(([key, label, color], index) => ({
30
- key, label, color, tokens: counts.get(key) ?? 0, show: index < 5 || index >= 9 || counts.has(key),
31
- })).filter(row => row.show)
32
- }
33
-
34
- function apply(ctx) {
35
- const h = React.createElement
36
- const { useCallback, useEffect, useRef, useState } = React
37
-
38
- function request(action, payload = {}, signal) {
39
- return fetch(ENDPOINT, {
40
- method: 'POST',
41
- headers: { 'content-type': 'application/json', 'x-dsh-capability-manager': '1' },
42
- body: JSON.stringify({ action, ...payload }),
43
- signal,
44
- }).then(async response => {
45
- const value = await response.json().catch(() => ({}))
46
- if (!response.ok || value?.error) throw new Error(value?.error || `请求失败 (${response.status})`)
47
- return value
48
- })
49
- }
50
-
51
- function Panel({ useSessions }) {
52
- const [data, setData] = useState(null)
53
- const [draft, setDraft] = useState(null)
54
- const [savedPolicy, setSavedPolicy] = useState(null)
55
- const [busy, setBusy] = useState(false)
56
- const [error, setError] = useState('')
57
- const [notice, setNotice] = useState('')
58
- const [toolQuery, setToolQuery] = useState('')
59
- const [skillQuery, setSkillQuery] = useState('')
60
- const [toolGroup, setToolGroup] = useState('builtin')
61
- const [toolStatus, setToolStatus] = useState('all')
62
- const [skillStatus, setSkillStatus] = useState('all')
63
- const [skillGroup, setSkillGroup] = useState('global')
64
- const [skillSource, setSkillSource] = useState('skills.sh')
65
- const [discoverQuery, setDiscoverQuery] = useState('')
66
- const [results, setResults] = useState([])
67
- const [target, setTarget] = useState('global')
68
- const [searching, setSearching] = useState(false)
69
- const seq = useRef(0)
70
- const debounce = useRef(null)
71
- const refreshTimer = useRef(null)
72
- const searchSeq = useRef(0)
73
- const sessions = useSessions(state => state)
74
- const activeSession = Object.values(sessions.byId).find(session => (session.retainedBy?.mainView ?? 0) > 0)?.id
75
- const [recordSession, setRecordSession] = useState(undefined)
76
- const [showActual, setShowActual] = useState(false)
77
- const sessionId = recordSession ?? activeSession
78
-
79
- const load = useCallback(async (selection = {}, quiet = false) => {
80
- const current = ++seq.current
81
- if (!quiet) { clearTimeout(refreshTimer.current); setBusy(true); setError('') }
82
- try {
83
- const next = await request('state', { sessionId, ...selection })
84
- if (current !== seq.current) return
85
- setData(next)
86
- if (!selection.draft) {
87
- setSavedPolicy(next.policy || { disabledTools: [], enabledTools: [], disabledSkills: [], enabledSkills: [], importedSkills: [] })
88
- setDraft(next.policy || { disabledTools: [], enabledTools: [], disabledSkills: [], enabledSkills: [], importedSkills: [] })
89
- }
90
- } catch (err) {
91
- if (current === seq.current) setError(err.message || String(err))
92
- } finally { if (current === seq.current && !quiet) setBusy(false) }
93
- }, [sessionId])
94
-
95
- useEffect(() => { load() }, [load])
96
- useEffect(() => () => { seq.current++; searchSeq.current++; clearTimeout(debounce.current); clearTimeout(refreshTimer.current) }, [])
97
-
98
- const refresh = useCallback((selection = {}, value = draft) => {
99
- clearTimeout(refreshTimer.current)
100
- refreshTimer.current = setTimeout(() => load({ ...selection, ...(value ? { draft: value } : {}) }, true), 180)
101
- }, [draft, load])
102
-
103
- const changed = JSON.stringify(draft) !== JSON.stringify(savedPolicy || {})
104
- const toggle = (kind, item) => {
105
- if (!item.available || item.fixed) return
106
- const isTool = kind === 'tool'
107
- const enabledKey = isTool ? 'enabledTools' : 'enabledSkills'
108
- const disabledKey = isTool ? 'disabledTools' : 'disabledSkills'
109
- const enabledNow = !!item.enabled
110
- const id = item.name
111
- const nextDraft = { ...(draft || {}), [enabledKey]: [...(draft?.[enabledKey] || [])], [disabledKey]: [...(draft?.[disabledKey] || [])] }
112
- nextDraft[enabledKey] = nextDraft[enabledKey].filter(value => value !== id)
113
- nextDraft[disabledKey] = nextDraft[disabledKey].filter(value => value !== id)
114
- if (enabledNow) nextDraft[disabledKey].push(id)
115
- else nextDraft[enabledKey].push(id)
116
- setDraft(() => {
117
- return nextDraft
118
- })
119
- const list = isTool ? 'tools' : 'skills'
120
- setData(previous => previous && ({ ...previous, [list]: previous[list].map(row => row.name === id ? { ...row, enabled: !enabledNow } : row) }))
121
- refresh({ presetId: data?.presetId, workspaceId: data?.workspaceId }, nextDraft)
122
- }
123
-
124
- async function save() {
125
- if (!draft || !data) return
126
- setBusy(true); setError(''); setNotice('')
127
- try {
128
- clearTimeout(refreshTimer.current)
129
- await request('save', { presetId: data.presetId, workspaceId: data.workspaceId, draft, sessionId })
130
- setNotice('配置已保存')
131
- await load({ presetId: data.presetId, workspaceId: data.workspaceId })
132
- } catch (err) { setError(err.message || String(err)) }
133
- finally { setBusy(false) }
134
- }
135
-
136
- const search = useCallback((query, source = skillSource) => {
137
- clearTimeout(debounce.current)
138
- if (!query.trim()) { setResults([]); setSearching(false); return }
139
- const requestId = ++searchSeq.current
140
- setSearching(true)
141
- debounce.current = setTimeout(async () => {
142
- try {
143
- const result = await request('search', { source, query: query.trim() })
144
- if (requestId === searchSeq.current) setResults(result.results || [])
145
- } catch (err) { if (requestId === searchSeq.current) setError(err.message || String(err)) }
146
- finally { if (requestId === searchSeq.current) setSearching(false) }
147
- }, 320)
148
- }, [skillSource])
149
-
150
- async function importSkill(selection) {
151
- setBusy(true); setError(''); setNotice('')
152
- try {
153
- const result = await request('import', { selection, workspaceId: data?.workspaceId, target })
154
- setNotice(`已导入 ${result.name || selection.name || selection.id || '技能'}`)
155
- await load({ presetId: data?.presetId, workspaceId: data?.workspaceId, ...(changed ? { draft } : {}) })
156
- } catch (err) { setError(err.message || String(err)) }
157
- finally { setBusy(false) }
158
- }
159
-
160
- if (!data) return h('div', { className: 'dcm' }, h(Style), h('header', { className: 'dcm-head' }, h('h1', null, 'Agent 能力管理')), error ? h('div', { className: 'dcm-error', role: 'alert' }, error) : h('p', { className: 'dcm-muted' }, '正在读取 DSH 能力目录…'))
161
-
162
- const matches = (row, query, state) => (state === 'all' || row.enabled === (state === 'enabled')) &&
163
- `${row.name} ${row.description || ''} ${row.source || ''}`.toLowerCase().includes(query.toLowerCase())
164
- const toolTab = (data.tools || []).filter(row => row.group === toolGroup)
165
- const skillTab = (data.skills || []).filter(row => row.group === skillGroup)
166
- const tools = toolTab.filter(row => matches(row, toolQuery, toolStatus))
167
- const skills = skillTab.filter(row => matches(row, skillQuery, skillStatus))
168
- const visibleBudget = showActual && data.actual ? data.actual.budget : data.budget
169
- const breakdown = budgetRows(visibleBudget)
170
- const n = value => Number(value || 0).toLocaleString('zh-CN')
171
- const labelGroup = value => ({ builtin: '内置工具', plugin: '插件工具', mcp: 'MCP 工具', unknown: '未归因', global: '全局技能', workspace: '工作区技能' })[value] || value || '其他'
172
- const delta = value => `${value > 0 ? '+' : ''}${n(value)}`
173
- const fee = value => new Intl.NumberFormat('zh-CN', { style: 'currency', currency: data.pricing.currency, maximumFractionDigits: 4, signDisplay: 'exceptZero' }).format(value)
174
- const fees = data.pricing?.minimum == null ? data.pricing?.status || '暂无适用费率'
175
- : data.pricing.minimum === data.pricing.maximum ? fee(data.pricing.minimum) : `${fee(data.pricing.minimum)} ~ ${fee(data.pricing.maximum)}`
176
- const heading = h('header', { className: 'dcm-head' }, h('h1', null, 'Agent 能力管理'),
177
- h('div', { className: 'dcm-controls' },
178
- h('label', null, 'Agent 预设', h('select', { value: data.presetId || '', onChange: e => load({ presetId: e.target.value, workspaceId: data.workspaceId }) }, ...(data.presets || []).map(p => h('option', { key: p.id, value: p.id, disabled: p.available === false }, `${p.name}${p.available === false ? `(不可用:${p.reason || '无法加载'})` : ''}`)))),
179
- h('label', null, '预算工作区', h('select', { value: data.workspaceId || '', onChange: e => load({
180
- presetId: data.presetId, workspaceId: e.target.value, ...(changed ? { draft } : {}),
181
- }) }, h('option', { value: '' }, '无工作区'), ...(data.workspaces || []).map(w => h('option', { key: w.id, value: w.id }, w.name)))),
182
- h('button', { className: 'dcm-primary', disabled: !changed || busy, onClick: save }, busy ? '处理中…' : '保存预设')))
183
-
184
- const displayedActual = showActual && data.actual
185
- const sessionOptions = sessions.ids.map(id => sessions.byId[id]).filter(row => row && !row.parentId)
186
- const summary = h('section', { className: 'dcm-summary' },
187
- h('article', { className: 'dcm-card' },
188
- h('div', { className: 'dcm-card-title' },
189
- title('整体统计', '月度费用按每月 1,500 次模型请求、未命中缓存的输入费率估算。'),
190
- h('span', null, `计价模型 ${data.pricing?.model || '—'} · DSH 默认`)),
191
- h('div', { className: 'dcm-metrics' },
192
- metric('已启用能力', `${n(data.budget?.count)} 项`, `${delta(data.budget.count - data.savedBudget.count)} 项较已保存`),
193
- metric('能力注入 · 单次', `${n(data.budget?.capability)} tok`, `${delta(data.budget.capability - data.savedBudget.capability)} tok 较已保存`),
194
- metric('初始注入 · 单次', `${n(data.budget?.total)} tok`, '含系统与其他自动注入'),
195
- metric('月度输入费用变化', fees, '每月 1,500 次模型请求'))),
196
- h('article', { className: 'dcm-card' },
197
- h('div', { className: 'dcm-card-title' },
198
- title(displayedActual ? '首请求注入明细 · 实际' : '首请求注入明细 · 估算', '按注入内容估算 token。技能按目录条目计量。预算排除用户消息、会话历史和工作区指令。'),
199
- sessionOptions.length > 0 && h('select', {
200
- 'aria-label': '核对首请求的会话', value: sessionId || '',
201
- onChange: event => { setRecordSession(event.target.value); setShowActual(!!event.target.value) },
202
- }, h('option', { value: '' }, '选择会话核对'), ...sessionOptions.map(row => h('option', { key: row.id, value: row.id }, row.displayTitle))),
203
- data.actual && h('button', { className: 'dcm-button', onClick: () => setShowActual(!showActual) }, displayedActual ? '查看预算' : '查看实际')),
204
- h('div', { className: 'dcm-bar', 'aria-hidden': true }, ...breakdown.filter(row => row.tokens).map(row => h('i', {
205
- key: row.key, title: `${row.label} ${n(row.tokens)} tok`, style: { background: row.color, flexGrow: row.tokens },
206
- }))),
207
- h('div', { className: 'dcm-breakdown' },
208
- h('div', { className: 'dcm-breakcolumn' }, ...breakdown.filter(row => !['base-system', 'automatic'].includes(row.key)).map(budgetRow)),
209
- h('div', { className: 'dcm-breakcolumn' },
210
- budgetRow({ key: 'capability', label: 'Agent 能力小计', tokens: visibleBudget.capability }),
211
- ...breakdown.filter(row => ['base-system', 'automatic'].includes(row.key)).map(budgetRow),
212
- h('div', { className: 'dcm-breakrow dcm-total' }, h('strong', null, '初始注入总量'), h('strong', null, `${n(visibleBudget.total)} tok`)))),
213
- displayedActual && h('small', { className: 'dcm-caption' }, [
214
- data.actual.presetId && (data.presets.find(row => row.id === data.actual.presetId)?.name ?? data.actual.presetId),
215
- data.workspaces.find(row => row.id === data.actual.workspaceId)?.name,
216
- [data.actual.provider, data.actual.model].filter(Boolean).join(' / '),
217
- data.actual.inputTokens == null ? '' : `服务商报告输入 ${n(data.actual.inputTokens)} tok`,
218
- ].filter(Boolean).join(' · '))))
219
-
220
- const toolGroups = ['builtin', 'plugin', 'mcp', ...(data.tools.some(row => row.group === 'unknown') ? ['unknown'] : [])]
221
- const toolPanel = h('section', { className: 'dcm-card dcm-list' }, h('div', { className: 'dcm-listhead' }, h('h2', null, '工具'),
222
- tabs(toolGroups.map(group => [group, labelGroup(group)]), toolGroup, setToolGroup),
223
- h('span', null, `${toolTab.filter(x => x.enabled).length} / ${toolTab.length} 已启用`)),
224
- h('div', { className: 'dcm-filter' }, h('input', { type: 'search', value: toolQuery, placeholder: '搜索名称、说明或来源', onChange: e => setToolQuery(e.target.value), 'aria-label': '搜索工具' }), statusFilter(toolStatus, setToolStatus)),
225
- h('div', { className: 'dcm-scroll', role: 'region', 'aria-label': '工具列表' }, tools.length ? tools.map(row => itemRow(row, 'tool')) : empty('没有符合条件的工具')))
226
-
227
- const skillPanel = h('section', { className: 'dcm-card dcm-list' }, h('div', { className: 'dcm-listhead' }, h('h2', null, '技能'),
228
- tabs([['global', '全局技能'], ['workspace', '工作区技能'], ['discover', '发现技能']], skillGroup, setSkillGroup),
229
- skillGroup !== 'discover' && h('span', null, `${skillTab.filter(x => x.enabled).length} / ${skillTab.length} 已启用`)),
230
- skillGroup === 'discover' ? h('div', { className: 'dcm-discover' }, h('div', { className: 'dcm-filter' }, h('select', { value: skillSource, onChange: e => { setSkillSource(e.target.value); search(discoverQuery, e.target.value) } }, h('option', { value: 'skills.sh' }, 'skills.sh'), h('option', { value: 'github' }, 'GitHub 仓库')), h('input', { type: 'search', value: discoverQuery, placeholder: '搜索技能或公开仓库', onChange: e => { setDiscoverQuery(e.target.value); search(e.target.value) }, 'aria-label': '搜索发现技能' })), h('div', { className: 'dcm-target' }, h('span', null, '导入到'), h('select', { value: target, onChange: e => setTarget(e.target.value) }, h('option', { value: 'global' }, 'DSH 全局技能'), h('option', { value: 'workspace', disabled: !data.workspaceId }, '当前工作区技能'))), h('div', { className: 'dcm-scroll' }, searching ? empty('正在搜索…') : results.length ? results.map(row => h('div', { className: 'dcm-row', key: row.id }, h('div', { className: 'dcm-row-info' }, h('strong', null, row.name), h('small', null, row.description || ''), h('small', null, `${row.source || skillSource} · ${row.repository || ''}${row.path ? `/${row.path}` : ''}`)), h('button', { className: 'dcm-button', disabled: busy, onClick: () => importSkill(row) }, '导入'))) : empty('输入关键词搜索技能目录')))
231
- : h(React.Fragment, null, h('div', { className: 'dcm-filter' }, h('input', { type: 'search', value: skillQuery, placeholder: '搜索名称、说明或来源', onChange: e => setSkillQuery(e.target.value), 'aria-label': '搜索技能' }), statusFilter(skillStatus, setSkillStatus)), h('div', { className: 'dcm-scroll', role: 'region', 'aria-label': '技能列表' }, skills.length ? skills.map(row => itemRow(row, 'skill')) : empty('没有符合条件的技能'))))
232
-
233
- return h('main', { className: 'dcm' }, h(Style), heading, error ? h('div', { className: 'dcm-error', role: 'alert' }, error) : null, notice ? h('div', { className: 'dcm-notice', role: 'status' }, notice) : null,
234
- h('div', { className: 'dcm-dashboard' }, summary, toolPanel, skillPanel))
235
-
236
- function metric(label, value, detail) {
237
- return h('div', { className: 'dcm-metric', key: label }, h('small', null, label), h('strong', null, value), h('small', null, detail))
238
- }
239
- function title(label, help) {
240
- return h('h2', null, label, h('button', { type: 'button', className: 'dcm-help', title: help, 'aria-label': help }, '!'))
241
- }
242
- function budgetRow(row) {
243
- return h('div', { className: 'dcm-breakrow', key: row.key },
244
- h('span', null, row.color && h('i', { style: { background: row.color } }), row.label),
245
- h('strong', null, `${n(row.tokens)} tok`))
246
- }
247
- function tabs(options, selected, setSelected) {
248
- return h('div', { className: 'dcm-tabs' }, ...options.map(([key, label]) => h('button', {
249
- key, className: selected === key ? 'active' : '', 'aria-pressed': selected === key, onClick: () => setSelected(key),
250
- }, label)))
251
- }
252
- function statusFilter(selected, setSelected) {
253
- return h('select', { value: selected, onChange: event => setSelected(event.target.value), 'aria-label': '按状态筛选' },
254
- ...[['all', '全部状态'], ['enabled', '已启用'], ['disabled', '已关闭']].map(([key, label]) => h('option', { key, value: key }, label)))
255
- }
256
- function empty(text) { return h('p', { className: 'dcm-empty', role: 'status' }, text) }
257
- function itemRow(row, kind) {
258
- return h('div', { className: 'dcm-row', key: `${kind}:${row.name}` }, h('div', { className: 'dcm-row-info' }, h('strong', { title: row.name }, row.name), h('small', { title: row.description || '' }, row.description || '无说明'), h('small', null, `${labelGroup(row.group)} · ${row.source || '来源未说明'}`)), h('span', { className: 'dcm-tokens' }, `≈${n(row.tokens)} tok`), row.fixed ? h('span', { className: 'dcm-fixed' }, '始终启用') : h('button', { type: 'button', role: 'switch', className: `dcm-switch ${row.enabled ? 'on' : ''}`, 'aria-checked': !!row.enabled, 'aria-label': `${row.enabled ? '关闭' : '启用'} ${row.name}`, disabled: row.available === false || busy, title: row.reason, onClick: () => toggle(kind, row) }, h('span')))
259
- }
260
- }
261
-
262
- function Style() {
263
- return h('style', null, `.dcm{--ink:#17243a;--muted:#68768a;--line:#dce3ed;--accent:#2867c8;color:var(--ink);font:14px/1.45 Inter,"Segoe UI",sans-serif;padding:22px 26px 32px;min-height:100%;box-sizing:border-box;background:#f3f6fa}
264
- .dcm *{box-sizing:border-box}
265
- .dcm-head{display:flex;align-items:flex-end;justify-content:space-between;gap:18px;margin-bottom:14px}
266
- .dcm h1{font-size:26px;margin:0 0 3px}
267
- .dcm h2{font-size:16px;margin:0}
268
- .dcm-muted,.dcm-caption{color:var(--muted);font-size:12px;margin:3px 0 0}
269
- .dcm-controls{display:flex;align-items:flex-end;gap:10px;flex-wrap:wrap}
270
- .dcm-controls label{display:grid;gap:4px;font-size:11px;color:var(--muted)}
271
- .dcm select,.dcm input{min-width:140px;border:1px solid #bbc9da;border-radius:7px;padding:7px 9px;background:white;color:var(--ink);font:inherit}
272
- .dcm button{font:inherit;cursor:pointer}
273
- .dcm-primary,.dcm-button{border:1px solid #c7d2e1;border-radius:7px;padding:7px 12px;background:#fff;color:#24344b}
274
- .dcm-primary{background:#2867c8;border-color:#2867c8;color:white;font-weight:600}
275
- .dcm button:disabled{opacity:.48;cursor:not-allowed}
276
- .dcm-dashboard{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));grid-template-rows:minmax(245px,34vh) minmax(330px,1fr);gap:12px;min-height:620px}
277
- .dcm-summary{grid-column:1/-1;display:grid;grid-template-columns:1fr 1fr;grid-template-rows:minmax(0,1fr) auto;gap:10px;min-height:0}
278
- .dcm-card{background:#fff;border:1px solid var(--line);border-radius:11px;box-shadow:0 2px 8px #24395408;min-width:0}
279
- .dcm-summary>.dcm-card{padding:12px 15px;overflow:auto}
280
- .dcm-card-title,.dcm-listhead{display:flex;align-items:center;justify-content:space-between;gap:10px}
281
- .dcm-card-title>span,.dcm-listhead>span{font-size:11px;color:var(--muted)}
282
- .dcm-metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px;margin:12px 0 7px}
283
- .dcm-metric{padding:10px 8px;border:1px solid var(--line);border-radius:8px;background:#f8fafc;min-width:0}
284
- .dcm-metric small{display:block;color:var(--muted);font-size:11px}
285
- .dcm-metric strong{display:block;font-size:clamp(15px,1.7vw,22px);margin-top:3px;overflow-wrap:anywhere}
286
- .dcm-breakdown{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:5px 14px;margin:10px 0}
287
- .dcm-breakrow{display:flex;justify-content:space-between;gap:8px;border-bottom:1px solid #edf0f5;padding:3px 0;font-size:12px}
288
- .dcm-breakrow strong{white-space:nowrap}
289
- .dcm-actual{grid-column:1/-1;display:flex;gap:15px;flex-wrap:wrap;padding:7px 12px;border:1px solid #cddbeb;border-radius:8px;background:#f8fbff;font-size:12px}
290
- .dcm-list{display:flex;flex-direction:column;min-height:0;overflow:hidden}
291
- .dcm-listhead{padding:10px 13px;border-bottom:1px solid var(--line)}
292
- .dcm-filter{display:flex;gap:7px;padding:8px 12px;border-bottom:1px solid var(--line)}
293
- .dcm-filter input{flex:1;min-width:0;padding:6px 8px;font-size:12px}
294
- .dcm-filter select{min-width:95px;padding:6px;font-size:12px}
295
- .dcm-scroll{flex:1;min-height:0;overflow:auto;padding:4px 12px 10px;overscroll-behavior:contain}
296
- .dcm-row{display:grid;grid-template-columns:minmax(0,1fr) auto auto;align-items:center;gap:10px;padding:8px 2px;border-bottom:1px solid #edf0f5}
297
- .dcm-row-info{min-width:0;display:flex;flex-direction:column}
298
- .dcm-row-info strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px}
299
- .dcm-row-info small{color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:11px}
300
- .dcm-tokens,.dcm-fixed{font-size:11px;color:var(--muted);white-space:nowrap}
301
- .dcm-switch{width:38px;height:22px;border:0;border-radius:12px;padding:2px;background:#cbd3df;transition:background .15s}
302
- .dcm-switch span{display:block;width:18px;height:18px;border-radius:50%;background:white;box-shadow:0 1px 3px #0003;transition:transform .15s}
303
- .dcm-switch.on{background:#2867c8}
304
- .dcm-switch.on span{transform:translateX(16px)}
305
- .dcm-tabs{display:flex;gap:14px;padding:5px 12px;border-bottom:1px solid var(--line);overflow:auto;flex:none}
306
- .dcm-tabs button{border:0;border-bottom:2px solid transparent;background:none;color:var(--muted);padding:5px 1px;white-space:nowrap;font-size:12px}
307
- .dcm-tabs button.active{color:var(--accent);border-color:var(--accent);font-weight:600}
308
- .dcm-discover{display:flex;flex:1;min-height:0;flex-direction:column}
309
- .dcm-target{display:flex;align-items:center;gap:8px;padding:5px 12px;color:var(--muted);font-size:12px}
310
- .dcm-target select{padding:4px;min-width:0}
311
- .dcm-empty{padding:16px 4px;color:var(--muted);font-size:12px}
312
- .dcm-error,.dcm-notice{padding:8px 11px;margin:0 0 10px;border-radius:7px;font-size:12px}
313
- .dcm-error{color:#9c2f26;background:#fff0ee;border:1px solid #f0c4bf}
314
- .dcm-notice{color:#24623c;background:#effaf2;border:1px solid #c7e7ce}
315
- @media(max-width:850px){.dcm{padding:16px}
316
- .dcm-head{align-items:flex-start;flex-direction:column}
317
- .dcm-dashboard{display:flex;flex-direction:column;min-height:0}
318
- .dcm-summary{grid-template-columns:1fr;grid-template-rows:auto}
319
- .dcm-summary>.dcm-card{min-height:190px}
320
- .dcm-list{min-height:270px}
321
- .dcm-metrics{grid-template-columns:repeat(2,minmax(0,1fr))}}
322
- .dcm{height:100%;min-height:0;padding:14px 16px;display:flex;flex-direction:column;overflow:auto;container-type:inline-size}
323
- .dcm-head{align-items:center;margin-bottom:9px;gap:8px}
324
- .dcm h1{font-size:20px;margin:0;white-space:nowrap}
325
- .dcm-dashboard{flex:1;min-height:0;grid-template-rows:auto minmax(170px,1fr);gap:8px}
326
- .dcm-summary{grid-template-rows:auto;gap:8px}
327
- .dcm-summary>.dcm-card{padding:9px 11px;overflow:visible;min-height:0}
328
- .dcm-card-title{min-height:24px;justify-content:flex-start;flex-wrap:wrap;gap:5px}
329
- .dcm-card-title h2{margin-right:auto}
330
- .dcm-card-title select,.dcm-card-title .dcm-button{font-size:11px;padding:2px 5px;min-width:0;max-width:110px}
331
- .dcm-help{margin-left:5px;border:0;border-radius:50%;height:15px;width:15px;padding:0;background:#e7edf4;color:#58697e;font-size:10px!important}
332
- .dcm-metrics{grid-template-columns:repeat(2,minmax(0,1fr));margin:5px 0 0;gap:5px}
333
- .dcm-metric{min-width:0;padding:4px 7px;background:#fcfdff}
334
- .dcm-metric strong{font-size:17px;line-height:1.16;margin:1px 0}
335
- .dcm-bar{display:flex;height:7px;border-radius:7px;overflow:hidden;background:#e9eef5;margin:5px 0}
336
- .dcm-bar i{flex-basis:0}
337
- .dcm-breakdown{margin:0;gap:9px}
338
- .dcm-breakcolumn{display:grid;grid-auto-rows:minmax(18px,auto);align-content:start}
339
- .dcm-breakrow{border:0;align-items:center;padding:0;gap:4px}
340
- .dcm-breakrow span{display:flex;gap:4px;align-items:center}
341
- .dcm-breakrow i{display:block;flex:none;width:7px;height:7px;border-radius:2px}
342
- .dcm-total{grid-row:span 2;border-top:1px solid var(--line);margin-top:2px}
343
- .dcm-listhead{padding:0 8px;justify-content:flex-start;gap:7px;flex-wrap:wrap}
344
- .dcm-listhead>span{margin-left:auto;white-space:nowrap}
345
- .dcm-listhead .dcm-tabs{padding:0;gap:8px;border:0}
346
- .dcm-filter{padding:4px 8px}
347
- .dcm-row{padding:5px 2px}
348
- @media(max-height:580px){.dcm-dashboard{flex:none;min-height:470px}}
349
- @container (max-width:640px){.dcm-dashboard{display:flex;flex-direction:column}.dcm-summary{grid-template-columns:1fr}.dcm-list{height:45vh;min-height:270px;flex:none}}
350
- `)
351
- }
352
-
353
- ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: ID }, Panel))
354
- ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({ name: 'sidebar.panellist', id: ID, label: 'Agent能力管理' }, function Icon() { return h('span', { 'aria-hidden': true, className: 'dcm-sidebar-icon' }, '◈') }))
355
- }
356
-
357
- return { inject, apply }
358
- } })
1
+ window.__ModuleLoader__.load({ id: '@crocketc/dsh-capability-manager', factory(require) {
2
+ const React = require('react')
3
+
4
+ /** Browser entry for the Agent Capability Manager panel. */
5
+ const inject = ['slots', 'pluginNavigation']
6
+
7
+ const ID = 'dsh-capability-manager'
8
+ const PACKAGE_NAME = '@crocketc/dsh-capability-manager'
9
+ const ENDPOINT = '/api/dsh-capability-manager'
10
+ const MARKET_CAPABILITIES_PATH = '/dsh-market/api/v1/capabilities'
11
+ const MARKET_UPDATES_PATH = '/dsh-market/api/v1/updates'
12
+ const MARKET_OPERATIONS_PATH = '/dsh-market/api/v1/operations'
13
+ const PLUGIN_VERSION = '0.3.0'
14
+ const categories = [
15
+ ['skill-catalog', '全局技能', '#7843d6'],
16
+ ['workspace-skill-catalog', '工作区技能', '#c23080'],
17
+ ['builtin-tools', '内置工具', '#2761c5'],
18
+ ['plugin-tools', '插件工具', '#ad6c0b'],
19
+ ['mcp-tools', 'MCP 工具', '#008577'],
20
+ ['unknown-tools', '其他来源工具', '#767e91'],
21
+ ['tool-prompt', '工具提示', '#755a35'],
22
+ ['ptc-shared', 'PTC 共享声明', '#467da2'],
23
+ ['run-code', 'PTC 固定入口', '#9663a0'],
24
+ ['base-system', '基础系统提示词', '#62738c'],
25
+ ['automatic', '其他自动注入', '#c76334'],
26
+ ]
27
+
28
+ function budgetRows(budget) {
29
+ const counts = new Map()
30
+ for (const { key, tokens } of budget?.breakdown ?? []) {
31
+ const category = /^ptc-.*-tools$/.test(key) ? key.slice(4) : key
32
+ counts.set(category, (counts.get(category) ?? 0) + tokens)
33
+ }
34
+ return categories.map(([key, label, color], index) => ({
35
+ key, label, color, tokens: counts.get(key) ?? 0, show: index < 5 || index >= 9 || counts.has(key),
36
+ })).filter(row => row.show)
37
+ }
38
+
39
+ function apply(ctx) {
40
+ const h = React.createElement
41
+ const { useCallback, useEffect, useRef, useState } = React
42
+
43
+ function request(action, payload = {}, signal) {
44
+ return fetch(ENDPOINT, {
45
+ method: 'POST',
46
+ headers: { 'content-type': 'application/json', 'x-dsh-capability-manager': '1' },
47
+ body: JSON.stringify({ action, ...payload }),
48
+ signal,
49
+ }).then(async response => {
50
+ const value = await response.json().catch(() => ({}))
51
+ if (!response.ok || value?.error) throw new Error(value?.error || `请求失败 (${response.status})`)
52
+ return value
53
+ })
54
+ }
55
+
56
+ async function marketApi(signal) {
57
+ try {
58
+ const capabilityResponse = await fetch(MARKET_CAPABILITIES_PATH, { credentials: 'same-origin', signal })
59
+ if (!capabilityResponse.ok) return undefined
60
+ const capability = await capabilityResponse.json()
61
+ if (capability.schema !== 'dsh-market/update-api/v1' || capability.apiVersion !== 1 ||
62
+ capability.stability === undefined || !capability.features?.check || !capability.features?.update || !capability.features?.progress ||
63
+ capability.endpoints?.updates !== MARKET_UPDATES_PATH || capability.endpoints?.operations !== MARKET_OPERATIONS_PATH) return undefined
64
+ return true
65
+ } catch {
66
+ return undefined
67
+ }
68
+ }
69
+
70
+ async function checkMarketUpdate(installedSource, installedVersion, signal) {
71
+ try {
72
+ if (!['npm', 'git'].includes(installedSource)) return undefined
73
+ if (!await marketApi(signal)) return undefined
74
+ const response = await fetch(`${MARKET_UPDATES_PATH}?name=${encodeURIComponent(PACKAGE_NAME)}&force=1`, { credentials: 'same-origin', signal })
75
+ if (!response.ok) return undefined
76
+ const result = await response.json()
77
+ if (result.schema !== 'dsh-market/update-api/v1' || result.package?.name !== PACKAGE_NAME) return undefined
78
+ const item = result.package
79
+ const reportedSource = typeof item.source === 'string' ? item.source : item.source?.kind
80
+ const marketSource = ({ github: 'git', git: 'git', npm: 'npm', registry: 'npm' })[String(reportedSource || '').toLowerCase()]
81
+ if (!marketSource || marketSource !== installedSource || item.installedVersion !== installedVersion ||
82
+ (item.updateAvailable && typeof item.latestVersion !== 'string')) return undefined
83
+ return { version: item.installedVersion, ...(item.updateAvailable ? { update: item.latestVersion } : {}),
84
+ status: 'checked', source: marketSource, market: true }
85
+ } catch {
86
+ return undefined
87
+ }
88
+ }
89
+
90
+ function Panel({ useSessions }) {
91
+ const [data, setData] = useState(null)
92
+ const [pluginVersion, setPluginVersion] = useState({ version: PLUGIN_VERSION })
93
+ const [draft, setDraft] = useState(null)
94
+ const [savedPolicy, setSavedPolicy] = useState(null)
95
+ const [busy, setBusy] = useState(false)
96
+ const [refreshing, setRefreshing] = useState(false)
97
+ const [refreshStatus, setRefreshStatus] = useState('')
98
+ const [updateProgress, setUpdateProgress] = useState('')
99
+ const [updateFallback, setUpdateFallback] = useState(false)
100
+ const [updatingPlugin, setUpdatingPlugin] = useState(false)
101
+ const [error, setError] = useState('')
102
+ const [notice, setNotice] = useState('')
103
+ const [toolQuery, setToolQuery] = useState('')
104
+ const [skillQuery, setSkillQuery] = useState('')
105
+ const [toolGroup, setToolGroup] = useState('builtin')
106
+ const [toolStatus, setToolStatus] = useState('all')
107
+ const [skillStatus, setSkillStatus] = useState('all')
108
+ const [skillGroup, setSkillGroup] = useState('global')
109
+ const [skillSource, setSkillSource] = useState('skills.sh')
110
+ const [discoverQuery, setDiscoverQuery] = useState('')
111
+ const [discoveryError, setDiscoveryError] = useState('')
112
+ const [results, setResults] = useState([])
113
+ const [target, setTarget] = useState('global')
114
+ const [searching, setSearching] = useState(false)
115
+ const seq = useRef(0)
116
+ const debounce = useRef(null)
117
+ const refreshTimer = useRef(null)
118
+ const feedbackTimer = useRef(null)
119
+ const refreshGeneration = useRef(0)
120
+ const searchSeq = useRef(0)
121
+ const updateInFlight = useRef(false)
122
+ const updateController = useRef(null)
123
+ const sessions = useSessions(state => state)
124
+ const activeSession = Object.values(sessions.byId).find(session => (session.retainedBy?.mainView ?? 0) > 0)?.id
125
+ const [recordSession, setRecordSession] = useState(undefined)
126
+ const [showActual, setShowActual] = useState(false)
127
+ const sessionId = recordSession ?? activeSession
128
+
129
+ const load = useCallback(async (selection = {}, quiet = false) => {
130
+ const current = ++seq.current
131
+ if (!quiet) { clearTimeout(refreshTimer.current); setBusy(true); setError('') }
132
+ try {
133
+ const next = await request('state', { sessionId, ...selection })
134
+ if (current !== seq.current) return undefined
135
+ setData(next)
136
+ if (!selection.draft) {
137
+ setSavedPolicy(next.policy || { disabledTools: [], enabledTools: [], disabledSkills: [], enabledSkills: [], importedSkills: [] })
138
+ setDraft(next.policy || { disabledTools: [], enabledTools: [], disabledSkills: [], enabledSkills: [], importedSkills: [] })
139
+ }
140
+ return true
141
+ } catch (err) {
142
+ if (current === seq.current) setError(err.message || String(err))
143
+ return current === seq.current ? false : undefined
144
+ } finally { if (current === seq.current && !quiet) setBusy(false) }
145
+ }, [sessionId])
146
+
147
+ useEffect(() => { load() }, [load])
148
+ useEffect(() => {
149
+ let active = true
150
+ request('plugin-version').then(local => checkMarketUpdate(local.source, local.version).then(result => result || local))
151
+ .then(result => { if (active && result.status !== 'unavailable') setPluginVersion(result) }).catch(() => {})
152
+ return () => { active = false }
153
+ }, [])
154
+ useEffect(() => () => {
155
+ seq.current++; searchSeq.current++; refreshGeneration.current++
156
+ updateController.current?.abort()
157
+ clearTimeout(debounce.current); clearTimeout(refreshTimer.current); clearTimeout(feedbackTimer.current)
158
+ }, [])
159
+
160
+ const refresh = useCallback((selection = {}, value = draft) => {
161
+ clearTimeout(refreshTimer.current)
162
+ refreshTimer.current = setTimeout(() => load({ ...selection, ...(value ? { draft: value } : {}) }, true), 180)
163
+ }, [draft, load])
164
+
165
+ async function refreshInventory() {
166
+ if (!data || refreshing || busy) return
167
+ clearTimeout(refreshTimer.current)
168
+ clearTimeout(feedbackTimer.current)
169
+ const generation = ++refreshGeneration.current
170
+ setRefreshing(true)
171
+ setRefreshStatus('正在刷新能力清单…')
172
+ setError('')
173
+ const succeeded = await load({ presetId: data.presetId, workspaceId: data.workspaceId, ...(draft ? { draft } : {}) }, true)
174
+ let versionCheck = '插件版本检查暂不可用'
175
+ try {
176
+ const localVersion = await request('plugin-version')
177
+ const nextVersion = await checkMarketUpdate(localVersion.source, localVersion.version) || localVersion
178
+ if (generation === refreshGeneration.current && nextVersion.status !== 'unavailable') setPluginVersion(nextVersion)
179
+ versionCheck = nextVersion.status === 'checked'
180
+ ? '插件版本检查完成'
181
+ : nextVersion.status === 'unsupported'
182
+ ? '插件来源暂不支持版本检查'
183
+ : nextVersion.status === 'unavailable'
184
+ ? '插件版本检查暂不可用'
185
+ : '插件版本状态已刷新'
186
+ } catch {
187
+ // Keep the last successful version result if local source checking also fails.
188
+ }
189
+ if (generation !== refreshGeneration.current) return
190
+ setRefreshing(false)
191
+ const inventoryCheck = succeeded === true ? '能力清单已刷新' : succeeded === false ? '能力清单刷新失败' : '能力清单刷新状态已变化'
192
+ setRefreshStatus(`${inventoryCheck};${versionCheck}`)
193
+ feedbackTimer.current = setTimeout(() => setRefreshStatus(''), 1800)
194
+ }
195
+
196
+ async function updatePlugin() {
197
+ if (!pluginVersion.market) { ctx.pluginNavigation.openBundle(PACKAGE_NAME); return }
198
+ if (updateInFlight.current) return
199
+ updateInFlight.current = true
200
+ const controller = new AbortController()
201
+ updateController.current = controller
202
+ setUpdatingPlugin(true)
203
+ setUpdateFallback(false)
204
+ setUpdateProgress('正在通过插件市场更新…')
205
+ try {
206
+ const localVersion = await request('plugin-version', {}, controller.signal)
207
+ const verifiedMarketVersion = await checkMarketUpdate(localVersion.source, localVersion.version, controller.signal)
208
+ if (controller.signal.aborted) return
209
+ if (!verifiedMarketVersion?.market || verifiedMarketVersion.source !== localVersion.source) {
210
+ ctx.pluginNavigation.openBundle(PACKAGE_NAME); setUpdateProgress('插件市场来源校验未通过,已打开 DSH 插件管理器'); return
211
+ }
212
+ if (!verifiedMarketVersion.update) {
213
+ setPluginVersion(verifiedMarketVersion)
214
+ setUpdateProgress('插件已是最新版本')
215
+ return
216
+ }
217
+ const response = await fetch(MARKET_UPDATES_PATH, { method: 'POST', credentials: 'same-origin',
218
+ headers: { 'content-type': 'application/json' }, body: JSON.stringify({ packageName: PACKAGE_NAME }), signal: controller.signal })
219
+ if (!response.ok) throw new Error(`更新请求失败 (${response.status})`)
220
+ const { operationId } = await response.json()
221
+ if (!operationId) throw new Error('更新接口未返回操作编号')
222
+ for (let attempt = 0; attempt < 300; attempt++) {
223
+ const progress = await fetch(`${MARKET_OPERATIONS_PATH}?operationId=${encodeURIComponent(operationId)}`, { credentials: 'same-origin', signal: controller.signal })
224
+ if (!progress.ok) throw new Error(`读取更新进度失败 (${progress.status})`)
225
+ const operation = await progress.json()
226
+ const state = operation.operation || operation
227
+ setUpdateProgress(state.message || state.step || state.status || '正在更新…')
228
+ if (['succeeded', 'failed', 'cancelled', 'rolled-back'].includes(state.status)) {
229
+ if (state.status === 'rolled-back') {
230
+ setUpdateProgress(state.message || '更新失败,已回滚到更新前版本')
231
+ setUpdateFallback(true)
232
+ return
233
+ }
234
+ if (state.status === 'failed' || state.status === 'cancelled') throw new Error(state.message || '更新未完成')
235
+ if (state.installedVersion) setPluginVersion({ version: state.installedVersion, status: 'checked', source: pluginVersion.source })
236
+ setUpdateProgress(state.restartRequired ? '更新完成,请重启 DSH' : '更新完成')
237
+ return
238
+ }
239
+ await new Promise(resolve => setTimeout(resolve, 1000))
240
+ }
241
+ throw new Error('等待更新结果超时,请在插件市场已安装页面查看状态')
242
+ } catch (error) {
243
+ if (controller.signal.aborted) return
244
+ setUpdateProgress(error.message || '市场更新不可用,请在 DSH 插件管理器中更新')
245
+ setUpdateFallback(true)
246
+ } finally {
247
+ updateInFlight.current = false
248
+ if (updateController.current === controller) updateController.current = null
249
+ if (!controller.signal.aborted) setUpdatingPlugin(false)
250
+ }
251
+ }
252
+
253
+ const changed = JSON.stringify(draft) !== JSON.stringify(savedPolicy || {})
254
+ const toggle = (kind, item) => {
255
+ if (!item.available || item.fixed) return
256
+ const isTool = kind === 'tool'
257
+ const enabledKey = isTool ? 'enabledTools' : 'enabledSkills'
258
+ const disabledKey = isTool ? 'disabledTools' : 'disabledSkills'
259
+ const enabledNow = !!item.enabled
260
+ const id = item.name
261
+ const nextDraft = { ...(draft || {}), [enabledKey]: [...(draft?.[enabledKey] || [])], [disabledKey]: [...(draft?.[disabledKey] || [])] }
262
+ nextDraft[enabledKey] = nextDraft[enabledKey].filter(value => value !== id)
263
+ nextDraft[disabledKey] = nextDraft[disabledKey].filter(value => value !== id)
264
+ if (enabledNow) nextDraft[disabledKey].push(id)
265
+ else nextDraft[enabledKey].push(id)
266
+ setDraft(() => {
267
+ return nextDraft
268
+ })
269
+ const list = isTool ? 'tools' : 'skills'
270
+ setData(previous => previous && ({ ...previous, [list]: previous[list].map(row => row.name === id ? { ...row, enabled: !enabledNow } : row) }))
271
+ refresh({ presetId: data?.presetId, workspaceId: data?.workspaceId }, nextDraft)
272
+ }
273
+
274
+ async function save() {
275
+ if (!draft || !data) return
276
+ setBusy(true); setError(''); setNotice('')
277
+ try {
278
+ clearTimeout(refreshTimer.current)
279
+ await request('save', { presetId: data.presetId, workspaceId: data.workspaceId, draft, sessionId })
280
+ setNotice('配置已保存')
281
+ await load({ presetId: data.presetId, workspaceId: data.workspaceId })
282
+ } catch (err) { setError(err.message || String(err)) }
283
+ finally { setBusy(false) }
284
+ }
285
+
286
+ const search = useCallback((query, source = skillSource) => {
287
+ clearTimeout(debounce.current)
288
+ setDiscoveryError('')
289
+ const requestId = ++searchSeq.current
290
+ if (!query.trim()) { setResults([]); setSearching(false); return }
291
+ setSearching(true)
292
+ debounce.current = setTimeout(async () => {
293
+ try {
294
+ const result = await request('search', { source, query: query.trim() })
295
+ if (requestId === searchSeq.current) setResults(result.results || [])
296
+ } catch (err) { if (requestId === searchSeq.current) setDiscoveryError(err.message || String(err)) }
297
+ finally { if (requestId === searchSeq.current) setSearching(false) }
298
+ }, 320)
299
+ }, [skillSource])
300
+
301
+ async function importSkill(selection) {
302
+ setBusy(true); setError(''); setDiscoveryError(''); setNotice('')
303
+ try {
304
+ const result = await request('import', { selection, workspaceId: data?.workspaceId, target })
305
+ setNotice(`已导入 ${result.name || selection.name || selection.id || '技能'}`)
306
+ await load({ presetId: data?.presetId, workspaceId: data?.workspaceId, ...(changed ? { draft } : {}) })
307
+ } catch (err) { setDiscoveryError(err.message || String(err)) }
308
+ finally { setBusy(false) }
309
+ }
310
+
311
+ if (!data) return h('div', { className: 'dcm' }, h(Style), h('header', { className: 'dcm-head' }, h('h1', null, 'Agent 能力管理')), error ? h('div', { className: 'dcm-error', role: 'alert' }, error) : h('p', { className: 'dcm-muted' }, '正在读取 DSH 能力目录…'))
312
+
313
+ const matches = (row, query, state) => (state === 'all' || row.enabled === (state === 'enabled')) &&
314
+ `${row.name} ${row.description || ''} ${row.source || ''}`.toLowerCase().includes(query.toLowerCase())
315
+ const toolTab = (data.tools || []).filter(row => row.group === toolGroup)
316
+ const skillTab = (data.skills || []).filter(row => row.group === skillGroup)
317
+ const tools = toolTab.filter(row => matches(row, toolQuery, toolStatus))
318
+ const skills = skillTab.filter(row => matches(row, skillQuery, skillStatus))
319
+ const visibleBudget = showActual && data.actual ? data.actual.budget : data.budget
320
+ const breakdown = budgetRows(visibleBudget)
321
+ const n = value => Number(value || 0).toLocaleString('zh-CN')
322
+ const labelGroup = value => ({ builtin: '内置工具', plugin: '插件工具', mcp: 'MCP 工具', unknown: '其他来源', global: '全局技能', workspace: '工作区技能' })[value] || value || '其他'
323
+ const delta = value => `${value > 0 ? '+' : ''}${n(value)}`
324
+ const tokenSum = keys => (visibleBudget?.breakdown || []).reduce((total, row) => total + (keys.includes(row.key) ? row.tokens : 0), 0)
325
+ const actualCounts = visibleBudget?.categoryCounts
326
+ const categoryCounts = actualCounts || data.budget?.categoryCounts || { tool: 0, mcp: 0, skill: 0 }
327
+ const actualCategoryCountsMissing = showActual && data.actual && (!actualCounts ||
328
+ Number(actualCounts.tool || 0) + Number(actualCounts.mcp || 0) + Number(actualCounts.skill || 0) === 0) && (visibleBudget?.count > 0)
329
+ const countLabel = key => actualCategoryCountsMissing ? '—' : n(categoryCounts[key])
330
+ const fee = value => new Intl.NumberFormat('zh-CN', { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 4, signDisplay: 'exceptZero' }).format(value)
331
+ const fees = data.pricing?.minimum == null ? data.pricing?.status || '暂无适用费率'
332
+ : h('span', { className: 'dcm-fees' },
333
+ data.pricing.minimum === data.pricing.maximum ? fee(data.pricing.minimum) : `${fee(data.pricing.minimum)} ~ ${fee(data.pricing.maximum)}`,
334
+ h('small', { className: 'dcm-currency-code' }, data.pricing.currency))
335
+ const validGitHubRepository = value => /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})\/[A-Za-z0-9._-]{1,100}$/.test(value)
336
+ || /^https:\/\/github\.com\/[A-Za-z0-9-]+\/[A-Za-z0-9._-]+(?:\/tree\/.+)?\/?$/.test(value)
337
+ const discoveryFeedback = discoveryError && h('div', { className: 'dcm-discovery-error', role: 'alert' },
338
+ h('span', null, discoveryError),
339
+ h('button', { type: 'button', onClick: () => setDiscoveryError(''), 'aria-label': '关闭错误提示', title: '关闭错误提示' }, '×'))
340
+ function searchDiscovery(value, source = skillSource) {
341
+ if (source === 'github' && value.trim() && !validGitHubRepository(value.trim())) {
342
+ clearTimeout(debounce.current)
343
+ searchSeq.current++
344
+ setResults([])
345
+ setSearching(false)
346
+ setDiscoveryError('请输入精确的 GitHub owner/repo 或公开仓库 URL')
347
+ return
348
+ }
349
+ search(value, source)
350
+ }
351
+ const heading = h('header', { className: 'dcm-head' },
352
+ h('div', { className: 'dcm-heading-main' },
353
+ h('h1', null, 'Agent 能力管理'),
354
+ h('div', { className: 'dcm-controls' },
355
+ h('label', null, 'Agent 预设',
356
+ h('select', {
357
+ value: data.presetId || '',
358
+ onChange: e => load({ presetId: e.target.value, workspaceId: data.workspaceId }),
359
+ }, ...(data.presets || []).map(p => h('option', {
360
+ key: p.id, value: p.id, disabled: p.available === false,
361
+ }, `${p.name}${p.available === false ? `(不可用:${p.reason || '无法加载'})` : ''}`)))),
362
+ h('label', null, '预算工作区',
363
+ h('select', {
364
+ value: data.workspaceId || '',
365
+ onChange: e => load({ presetId: data.presetId, workspaceId: e.target.value, ...(changed ? { draft } : {}) }),
366
+ }, h('option', { value: '' }, '无工作区'), ...(data.workspaces || []).map(w => h('option', { key: w.id, value: w.id }, w.name)))))),
367
+ h('div', { className: 'dcm-heading-tools' },
368
+ h('a', { className: 'dcm-repository', href: 'https://github.com/crocketc/dsh-capability-manager', target: '_blank', rel: 'noreferrer', title: '打开 Agent 能力管理 GitHub 仓库', 'aria-label': '打开 Agent 能力管理 GitHub 仓库' },
369
+ h('svg', { viewBox: '0 0 24 24', 'aria-hidden': true }, h('path', { fill: 'currentColor', d: 'M12 .5C5.65.5.5 5.75.5 12.23c0 5.18 3.3 9.57 7.88 11.12.58.11.79-.26.79-.57v-2.17c-3.2.71-3.87-1.39-3.87-1.39-.53-1.36-1.28-1.72-1.28-1.72-1.05-.74.08-.73.08-.73 1.16.08 1.77 1.22 1.77 1.22 1.03 1.8 2.7 1.28 3.36.98.1-.76.4-1.28.73-1.57-2.55-.3-5.23-1.3-5.23-5.8 0-1.28.45-2.32 1.2-3.14-.12-.3-.52-1.49.11-3.1 0 0 .98-.32 3.2 1.2a10.85 10.85 0 0 1 5.82 0c2.22-1.52 3.2-1.2 3.2-1.2.63 1.61.23 2.8.12 3.1.75.82 1.2 1.86 1.2 3.14 0 4.51-2.69 5.5-5.26 5.79.41.36.78 1.06.78 2.14v3.18c0 .31.21.69.8.57A11.74 11.74 0 0 0 23.5 12.23C23.5 5.75 18.35.5 12 .5z' }))),
370
+ pluginVersion.update
371
+ ? h('button', { type: 'button', className: 'dcm-plugin-update', onClick: updatePlugin, disabled: updatingPlugin, title: `更新来源:${pluginVersion.source || 'npm'}` }, updatingPlugin ? '正在更新…' : `新版本 ↑ ${pluginVersion.update}`)
372
+ : h('span', { className: 'dcm-plugin-version', title: pluginVersion.detail || (pluginVersion.status === 'unsupported'
373
+ ? 'Git 来源暂时无法精确检查更新'
374
+ : `当前安装版本${pluginVersion.status === 'unavailable' ? ';暂时无法检查更新' : ''}`) },
375
+ `v${pluginVersion.version || PLUGIN_VERSION}${pluginVersion.status === 'unsupported' ? ' · 无法精确检查' : ''}`),
376
+ h('div', { className: 'dcm-actions' },
377
+ (refreshStatus || updateProgress) && h('small', { className: 'dcm-action-status', 'aria-live': 'polite' }, updateProgress || refreshStatus),
378
+ updateFallback && h('button', { type: 'button', className: 'dcm-button', onClick: () => ctx.pluginNavigation.openBundle(PACKAGE_NAME) }, '打开 DSH 插件管理器'),
379
+ h('button', {
380
+ type: 'button', className: `dcm-refresh ${refreshing ? 'is-refreshing' : ''}`,
381
+ disabled: refreshing || busy, onClick: refreshInventory,
382
+ title: '刷新能力清单', 'aria-label': '刷新能力清单',
383
+ }, h('span', { 'aria-hidden': true }, '↻')),
384
+ h('button', { className: 'dcm-primary', disabled: !changed || busy || refreshing, onClick: save }, busy ? '处理中…' : '保存预设'))))
385
+
386
+ const displayedActual = showActual && data.actual
387
+ const sessionOptions = sessions.ids.map(id => sessions.byId[id]).filter(row => row && !row.parentId)
388
+ const detailRows = [
389
+ ...breakdown.filter(row => !['base-system', 'automatic'].includes(row.key)),
390
+ { key: 'capability', label: 'Agent 能力小计', tokens: visibleBudget.capability, emphasis: true },
391
+ ...breakdown.filter(row => ['base-system', 'automatic'].includes(row.key)),
392
+ { key: 'total', label: '初始注入总量', tokens: visibleBudget.total, emphasis: true, total: true },
393
+ ]
394
+ const splitAt = Math.ceil(detailRows.length / 2)
395
+ const detailFont = `${Math.max(9, 12 - Math.max(0, detailRows.length - 8) * 0.35)}px`
396
+ const summary = h('section', { className: 'dcm-summary' },
397
+ h('article', { className: 'dcm-card' },
398
+ h('div', { className: 'dcm-card-title' },
399
+ title('整体统计', '月度费用按每月 1,500 次模型请求、未命中缓存的输入费率估算。'),
400
+ h('span', null, `计价模型 ${data.pricing?.model || '—'} · DSH 默认`)),
401
+ h('div', { className: 'dcm-metrics' },
402
+ metric('工具', `${countLabel('tool')} 项`, `≈ ${n(tokenSum(['builtin-tools', 'plugin-tools', 'unknown-tools', 'ptc-builtin-tools', 'ptc-plugin-tools', 'ptc-unknown-tools', 'run-code']))} tok`),
403
+ metric('MCP 工具', `${countLabel('mcp')} 项`, `≈ ${n(tokenSum(['mcp-tools', 'ptc-mcp-tools']))} tok`),
404
+ metric('技能', `${countLabel('skill')} 项`, `≈ ${n(tokenSum(['skill-catalog', 'workspace-skill-catalog']))} tok`),
405
+ h('div', { className: 'dcm-metric dcm-agent-summary' },
406
+ h('small', null, 'Agent 能力小计'),
407
+ h('strong', null, `${n(visibleBudget?.capability)} tok`),
408
+ h('small', null, `${delta(data.budget.capability - data.savedBudget.capability)} tok 较已保存`),
409
+ h('strong', { className: 'dcm-summary-total' }, `初始注入总量 ${n(visibleBudget?.total)} tok`)),
410
+ metric('月度输入费用变化', fees, '较已保存 · 每月 1,500 次请求'))),
411
+ h('article', { className: 'dcm-card dcm-injection' },
412
+ h('div', { className: 'dcm-card-title' },
413
+ title(displayedActual ? '首请求注入明细 · 实际' : '首请求注入明细 · 估算', '按注入内容估算 token。技能按目录条目计量。预算排除用户消息、会话历史和工作区指令。'),
414
+ sessionOptions.length > 0 && h('select', {
415
+ 'aria-label': '核对首请求的会话', value: sessionId || '',
416
+ onChange: event => { setRecordSession(event.target.value); setShowActual(!!event.target.value) },
417
+ }, h('option', { value: '' }, '选择会话核对'), ...sessionOptions.map(row => h('option', { key: row.id, value: row.id }, row.displayTitle))),
418
+ data.actual && h('button', { className: 'dcm-button', onClick: () => setShowActual(!showActual) }, displayedActual ? '查看预算' : '查看实际')),
419
+ h('div', { className: 'dcm-bar', 'aria-hidden': true }, ...breakdown.filter(row => row.tokens).map(row => h('i', {
420
+ key: row.key, title: `${row.label} ${n(row.tokens)} tok`, style: { background: row.color, flexGrow: row.tokens },
421
+ }))),
422
+ h('div', { className: 'dcm-breakdown' },
423
+ detailColumn(detailRows.slice(0, splitAt)),
424
+ detailColumn(detailRows.slice(splitAt))),
425
+ displayedActual && h('small', { className: 'dcm-caption' }, [
426
+ data.actual.presetId && (data.presets.find(row => row.id === data.actual.presetId)?.name ?? data.actual.presetId),
427
+ data.workspaces.find(row => row.id === data.actual.workspaceId)?.name,
428
+ [data.actual.provider, data.actual.model].filter(Boolean).join(' / '),
429
+ data.actual.inputTokens == null ? '' : `服务商报告输入 ${n(data.actual.inputTokens)} tok`,
430
+ ].filter(Boolean).join(' · '))))
431
+
432
+ const toolGroups = ['builtin', 'plugin', 'mcp', ...(data.tools.some(row => row.group === 'unknown') ? ['unknown'] : [])]
433
+ const toolPanel = h('section', { className: 'dcm-card dcm-list' }, h('div', { className: 'dcm-listhead' }, h('h2', null, '工具'),
434
+ tabs(toolGroups.map(group => [group, labelGroup(group)]), toolGroup, setToolGroup),
435
+ h('span', null, `${toolTab.filter(x => x.enabled).length} / ${toolTab.length} 已启用`)),
436
+ h('div', { className: 'dcm-filter' }, h('input', { type: 'search', value: toolQuery, placeholder: '搜索名称、说明或来源', onChange: e => setToolQuery(e.target.value), 'aria-label': '搜索工具' }), statusFilter(toolStatus, setToolStatus)),
437
+ h('div', { className: 'dcm-scroll', role: 'region', 'aria-label': '工具列表' }, tools.length ? tools.map(row => itemRow(row, 'tool')) : empty('没有符合条件的工具')))
438
+
439
+ const skillPanel = h('section', { className: 'dcm-card dcm-list' }, h('div', { className: 'dcm-listhead' }, h('h2', null, '技能'),
440
+ tabs([['global', '全局技能'], ['workspace', '工作区技能'], ['discover', '发现技能']], skillGroup, setSkillGroup),
441
+ skillGroup !== 'discover' && h('span', null, `${skillTab.filter(x => x.enabled).length} / ${skillTab.length} 已启用`)),
442
+ skillGroup === 'discover' ? h('div', { className: 'dcm-discover' }, h('div', { className: 'dcm-filter' }, h('select', { value: skillSource, onChange: e => { setSkillSource(e.target.value); setDiscoveryError(''); searchDiscovery(discoverQuery, e.target.value) }, 'aria-label': '发现技能来源' }, h('option', { value: 'skills.sh' }, 'skills.sh'), h('option', { value: 'github' }, 'GitHub 仓库')), h('input', { type: 'search', value: discoverQuery, placeholder: skillSource === 'github' ? 'owner/repo 或公开 GitHub 仓库 URL' : '搜索技能关键词', onChange: e => { setDiscoverQuery(e.target.value); searchDiscovery(e.target.value) }, 'aria-label': skillSource === 'github' ? '输入 GitHub 仓库' : '搜索技能关键词' })), discoveryFeedback, h('div', { className: 'dcm-target' }, h('span', null, '导入到'), h('select', { value: target, onChange: e => setTarget(e.target.value) }, h('option', { value: 'global' }, 'DSH 全局技能'), h('option', { value: 'workspace', disabled: !data.workspaceId }, '当前工作区技能'))), h('div', { className: 'dcm-scroll' }, searching ? empty('正在搜索…') : results.length ? results.map(row => h('div', { className: 'dcm-row', key: row.id }, h('div', { className: 'dcm-row-info' }, h('strong', null, row.name), h('small', null, row.description || ''), h('small', null, `${row.source || skillSource} · ${row.repository || ''}${row.path ? `/${row.path}` : ''}`)), h('button', { className: 'dcm-button', disabled: busy, onClick: () => importSkill(row) }, '导入'))) : empty(skillSource === 'github' ? '输入公开 GitHub 仓库查看可导入技能' : '输入关键词搜索技能目录')))
443
+ : h(React.Fragment, null, h('div', { className: 'dcm-filter' }, h('input', { type: 'search', value: skillQuery, placeholder: '搜索名称、说明或来源', onChange: e => setSkillQuery(e.target.value), 'aria-label': '搜索技能' }), statusFilter(skillStatus, setSkillStatus)), h('div', { className: 'dcm-scroll', role: 'region', 'aria-label': '技能列表' }, skills.length ? skills.map(row => itemRow(row, 'skill')) : empty('没有符合条件的技能'))))
444
+
445
+ return h('main', { className: 'dcm' }, h(Style), heading, error ? h('div', { className: 'dcm-error', role: 'alert' }, error) : null, notice ? h('div', { className: 'dcm-notice', role: 'status' }, notice) : null,
446
+ h('div', { className: 'dcm-dashboard' }, summary, toolPanel, skillPanel))
447
+
448
+ function metric(label, value, detail) {
449
+ return h('div', { className: 'dcm-metric', key: label }, h('small', null, label), h('strong', null, value), h('small', null, detail))
450
+ }
451
+ function title(label, help) {
452
+ return h('h2', null, label, h('button', { type: 'button', className: 'dcm-help', title: help, 'aria-label': help }, '!'))
453
+ }
454
+ function budgetRow(row) {
455
+ return h('div', { className: `dcm-breakrow ${row.emphasis ? 'dcm-emphasis' : ''} ${row.total ? 'dcm-total' : ''}`, key: row.key },
456
+ h('span', null, row.color && h('i', { style: { background: row.color } }), row.label),
457
+ h('strong', null, `${n(row.tokens)} tok`))
458
+ }
459
+ function detailColumn(rows) {
460
+ return h('div', { className: 'dcm-breakcolumn', style: { '--row-count': rows.length, '--detail-font': detailFont } },
461
+ ...rows.map(budgetRow))
462
+ }
463
+ function tabs(options, selected, setSelected) {
464
+ return h('div', { className: 'dcm-tabs' }, ...options.map(([key, label]) => h('button', {
465
+ key, className: selected === key ? 'active' : '', 'aria-pressed': selected === key, onClick: () => setSelected(key),
466
+ }, label)))
467
+ }
468
+ function statusFilter(selected, setSelected) {
469
+ return h('select', { value: selected, onChange: event => setSelected(event.target.value), 'aria-label': '按状态筛选' },
470
+ ...[['all', '全部状态'], ['enabled', '已启用'], ['disabled', '已关闭']].map(([key, label]) => h('option', { key, value: key }, label)))
471
+ }
472
+ function empty(text) { return h('p', { className: 'dcm-empty', role: 'status' }, text) }
473
+ function itemRow(row, kind) {
474
+ return h('div', { className: 'dcm-row', key: `${kind}:${row.name}` },
475
+ h('div', { className: 'dcm-row-info' },
476
+ h('div', { className: 'dcm-row-title' }, h('strong', { title: row.name }, row.name), row.source ? h('small', { className: 'dcm-source', title: row.source }, row.source) : null),
477
+ h('small', { title: row.description || '' }, row.description || '无说明')),
478
+ h('span', { className: 'dcm-tokens' }, `≈${n(row.tokens)} tok`),
479
+ row.fixed ? h('span', { className: 'dcm-fixed' }, '始终启用') : h('button', { type: 'button', role: 'switch', className: `dcm-switch ${row.enabled ? 'on' : ''}`, 'aria-checked': !!row.enabled, 'aria-label': `${row.enabled ? '关闭' : '启用'} ${row.name}`, disabled: row.available === false || busy, title: row.reason, onClick: () => toggle(kind, row) }, h('span')))
480
+ }
481
+ }
482
+
483
+ function Style() {
484
+ return h('style', null, `.dcm{--ink:#17243a;--muted:#68768a;--line:#dce3ed;--accent:#2867c8;color:var(--ink);font:14px/1.4 Inter,"Segoe UI",sans-serif;height:100%;min-height:0;padding:14px 16px;display:flex;flex-direction:column;overflow:auto;container-type:inline-size;background:#f3f6fa}
485
+ .dcm *{box-sizing:border-box}
486
+ .dcm-head{display:flex;align-items:center;justify-content:space-between;gap:30px;margin-bottom:8px;min-width:0}
487
+ .dcm-heading-main{display:flex;align-items:center;gap:30px;min-width:0;flex:1}
488
+ .dcm-heading-tools{display:flex;align-items:center;justify-content:flex-end;gap:8px;flex:none;min-width:0}
489
+ .dcm h1{font-size:20px;margin:0;white-space:nowrap}
490
+ .dcm h2{font-size:15px;margin:0}
491
+ .dcm-muted{color:var(--muted);font-size:11px;margin:4px 0 0}
492
+ .dcm-controls{display:flex;align-items:flex-end;justify-content:flex-end;gap:10px;flex-wrap:wrap}
493
+ .dcm-controls label{display:grid;gap:3px;font-size:10px;color:var(--muted)}
494
+ .dcm select,.dcm input{min-width:125px;border:1px solid #bbc9da;border-radius:7px;padding:6px 8px;background:white;color:var(--ink);font:inherit}
495
+ .dcm button{font:inherit;cursor:pointer}
496
+ .dcm-actions{display:flex;align-items:center;justify-content:flex-end;gap:7px;min-height:34px}
497
+ .dcm-action-status{margin-right:auto;color:var(--muted);font-size:11px}
498
+ .dcm-repository{display:grid;place-items:center;width:27px;height:27px;border-radius:50%;background:#eef2f7;color:#536276}
499
+ .dcm-repository:hover,.dcm-repository:focus-visible{background:#e3ecfa;color:#225fbd}
500
+ .dcm-repository svg{width:16px;height:16px;display:block}
501
+ .dcm-plugin-version{font-size:11px;color:#626d7c;white-space:nowrap}
502
+ .dcm-plugin-update{border:1px solid #d5d8de;border-radius:999px;background:#fff;color:#6e747e;padding:5px 10px;font-size:11px;white-space:nowrap}
503
+ .dcm-plugin-update:hover,.dcm-plugin-update:focus-visible{background:#f4f7fb;color:#245bb1}
504
+ .dcm-primary,.dcm-button{border:1px solid #c7d2e1;border-radius:7px;padding:6px 11px;background:#fff;color:#24344b}
505
+ .dcm-primary{background:#2867c8;border-color:#2867c8;color:white;font-weight:600}
506
+ .dcm button:disabled{opacity:.48;cursor:not-allowed}
507
+ .dcm-refresh{width:30px;height:30px;display:grid;place-items:center;border:1px solid #c7d2e1;border-radius:7px;background:white;color:#24344b;font-size:19px;line-height:1}
508
+ .dcm-refresh.is-refreshing span{animation:dcm-spin .8s linear infinite}
509
+ @keyframes dcm-spin{to{transform:rotate(360deg)}}
510
+ .dcm-dashboard{flex:1;min-height:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));grid-template-rows:minmax(0,1fr) minmax(0,2fr);gap:8px}
511
+ .dcm-summary{grid-column:1/-1;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;min-height:0;align-items:stretch}
512
+ .dcm-card{background:#fff;border:1px solid var(--line);border-radius:11px;box-shadow:0 2px 8px #24395408;min-width:0}
513
+ .dcm-summary>.dcm-card{padding:9px 11px;min-height:0;overflow:hidden}
514
+ .dcm-summary>.dcm-card:first-child{display:flex;flex-direction:column}
515
+ .dcm-card-title,.dcm-listhead{display:flex;align-items:center;justify-content:space-between;gap:7px;min-width:0}
516
+ .dcm-card-title h2{margin-right:auto;white-space:nowrap}
517
+ .dcm-card-title>span,.dcm-listhead>span{font-size:10px;color:var(--muted)}
518
+ .dcm-card-title select,.dcm-card-title .dcm-button{font-size:10px;padding:3px 5px;min-width:0;max-width:110px}
519
+ .dcm-help{margin-left:4px;border:0;border-radius:50%;height:15px;width:15px;padding:0;background:#e7edf4;color:#58697e;font-size:10px!important}
520
+ .dcm-metrics{display:grid;flex:1;min-height:0;grid-template-columns:repeat(6,minmax(0,1fr));grid-template-rows:repeat(2,minmax(0,1fr));gap:6px;margin:7px 0 0}
521
+ .dcm-metric{grid-column:span 2;padding:6px 7px;border:1px solid var(--line);border-radius:8px;background:#f8fafc;min-width:0;overflow:hidden}
522
+ .dcm-metric:nth-child(n+4){grid-column:span 3}
523
+ .dcm-metric small{display:block;color:var(--muted);font-size:clamp(9px,1.1vh,13px);line-height:1.2;overflow-wrap:anywhere}
524
+ .dcm-metric strong{display:block;font-size:clamp(14px,2.4vh,24px);line-height:1.1;margin:3px 0;overflow-wrap:anywhere}
525
+ .dcm-agent-summary{display:flex;flex-direction:column;justify-content:center;gap:clamp(0px,.35vh,3px)}
526
+ .dcm-agent-summary strong{font-weight:700}
527
+ .dcm-agent-summary .dcm-summary-total{padding-top:2px;border-top:1px solid var(--line);color:var(--ink);font-size:clamp(14px,2.4vh,24px);font-weight:700}
528
+ .dcm-fees{white-space:nowrap;font-size:.9em}
529
+ .dcm-currency-code{font-size:.68em;color:var(--muted);font-weight:500;margin-left:4px}
530
+ .dcm-injection{display:flex;flex-direction:column;min-height:0;contain:size}
531
+ .dcm-injection .dcm-bar{flex:none}
532
+ .dcm-injection .dcm-breakdown{flex:1;min-height:0}
533
+ .dcm-bar{display:flex;height:6px;flex:none;border-radius:7px;overflow:hidden;background:#e9eef5;margin:6px 0}
534
+ .dcm-bar i{flex-basis:0}
535
+ .dcm-breakdown{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 12px;margin:0}
536
+ .dcm-breakcolumn{display:grid;grid-template-rows:repeat(var(--row-count),minmax(0,1fr));min-width:0;min-height:0;overflow:hidden}
537
+ .dcm-breakrow{display:flex;align-items:center;justify-content:space-between;gap:4px;min-width:0;overflow:hidden;border-bottom:1px solid #edf0f5;padding:0;font-size:var(--detail-font,11px);line-height:1.2}
538
+ .dcm-breakrow>span{display:flex;align-items:center;gap:4px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
539
+ .dcm-breakrow i{display:block;flex:none;width:7px;height:7px;border-radius:2px}
540
+ .dcm-breakrow strong{flex:none;white-space:nowrap;font-size:inherit}
541
+ .dcm-emphasis{font-weight:700;border-top:1px solid var(--line)}
542
+ .dcm-total{border-top:1px solid var(--line);border-bottom:0}
543
+ .dcm-caption{display:block;flex:none;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--muted);font-size:9px;margin-top:3px}
544
+ .dcm-list{display:flex;flex-direction:column;min-height:0;overflow:hidden}
545
+ .dcm-listhead{padding:7px 9px 0;justify-content:flex-start;flex-wrap:wrap}
546
+ .dcm-listhead>span{margin-left:auto;white-space:nowrap}
547
+ .dcm-listhead .dcm-tabs{padding:0;gap:8px;border:0}
548
+ .dcm-filter{display:flex;gap:7px;padding:5px 8px;border-bottom:1px solid var(--line)}
549
+ .dcm-filter input{flex:1;min-width:0;padding:5px 7px;font-size:11px}
550
+ .dcm-filter select{min-width:90px;padding:5px;font-size:11px}
551
+ .dcm-scroll{flex:1;min-height:0;overflow:auto;padding:3px 9px 8px;overscroll-behavior:contain}
552
+ .dcm-row{display:grid;grid-template-columns:minmax(0,1fr) auto auto;align-items:center;gap:9px;padding:6px 2px;border-bottom:1px solid #edf0f5}
553
+ .dcm-row-info{min-width:0;display:flex;flex-direction:column}
554
+ .dcm-row-title{display:flex;align-items:baseline;gap:6px;min-width:0}
555
+ .dcm-row-info strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px}
556
+ .dcm-row-title strong{flex:0 1 auto}
557
+ .dcm-row-info small{color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10px}
558
+ .dcm-row-info .dcm-source{flex:none;max-width:38%;font-size:9px;color:#718096}
559
+ .dcm-tokens,.dcm-fixed{font-size:10px;color:var(--muted);white-space:nowrap}
560
+ .dcm-switch{width:36px;height:21px;border:0;border-radius:12px;padding:2px;background:#cbd3df;transition:background .15s}
561
+ .dcm-switch span{display:block;width:17px;height:17px;border-radius:50%;background:white;box-shadow:0 1px 3px #0003;transition:transform .15s}
562
+ .dcm-switch.on{background:#2867c8}
563
+ .dcm-switch.on span{transform:translateX(15px)}
564
+ .dcm-tabs{display:flex;gap:12px;padding:4px 9px;border-bottom:1px solid var(--line);overflow:auto;flex:none}
565
+ .dcm-tabs button{border:0;border-bottom:2px solid transparent;background:none;color:var(--muted);padding:4px 1px;white-space:nowrap;font-size:11px}
566
+ .dcm-tabs button.active{color:var(--accent);border-color:var(--accent);font-weight:600}
567
+ .dcm-discover{display:flex;flex:1;min-height:0;flex-direction:column}
568
+ .dcm-discovery-error{display:flex;align-items:flex-start;justify-content:space-between;gap:8px;padding:7px 9px;border:1px solid #f0c4bf;border-radius:7px;background:#fff0ee;color:#9c2f26;font-size:11px;line-height:1.35}
569
+ .dcm-discovery-error button{flex:none;border:0;background:transparent;color:inherit;font-size:16px;line-height:1;cursor:pointer}
570
+ .dcm-target{display:flex;align-items:center;gap:8px;padding:5px 9px;color:var(--muted);font-size:11px}
571
+ .dcm-target select{padding:4px;min-width:0}
572
+ .dcm-empty{padding:16px 4px;color:var(--muted);font-size:11px}
573
+ .dcm-error,.dcm-notice{padding:7px 10px;margin:0 0 8px;border-radius:7px;font-size:11px}
574
+ .dcm-error{color:#9c2f26;background:#fff0ee;border:1px solid #f0c4bf}
575
+ .dcm-notice{color:#24623c;background:#effaf2;border:1px solid #c7e7ce}
576
+ @media(max-width:850px){.dcm{padding:12px}.dcm-head{align-items:stretch;flex-direction:column;gap:7px}.dcm-heading-main{justify-content:space-between;gap:14px;flex-wrap:wrap}.dcm-heading-tools{justify-content:flex-end;flex-wrap:wrap}.dcm-controls{justify-content:flex-start}.dcm-dashboard{display:flex;flex-direction:column;min-height:0}.dcm-summary{grid-template-columns:1fr}.dcm-summary>.dcm-card{min-height:140px}.dcm-injection{min-height:175px;contain:none}.dcm-metrics{grid-template-columns:repeat(6,minmax(0,1fr));grid-template-rows:repeat(2,minmax(64px,auto))}.dcm-metric{grid-column:span 2}.dcm-metric:nth-child(n+4){grid-column:span 3}.dcm-list{height:42vh;min-height:240px;flex:none}}
577
+ @container (max-width:640px){.dcm-dashboard{display:flex;flex-direction:column}.dcm-summary{grid-template-columns:1fr}.dcm-list{min-height:230px;flex:none}.dcm-breakdown{gap:0 8px}}
578
+ `)
579
+ }
580
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: ID }, Panel))
581
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({ name: 'sidebar.panellist', id: ID, label: 'Agent能力管理' }, function Icon() { return h('span', { 'aria-hidden': true, className: 'dcm-sidebar-icon' }, '◈') }))
582
+ }
583
+
584
+ return { inject, apply }
585
+ } })