@crocketc/dsh-capability-manager 0.1.1 → 0.2.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,407 @@
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']
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 [refreshing, setRefreshing] = useState(false)
57
+ const [refreshStatus, setRefreshStatus] = useState('')
58
+ const [error, setError] = useState('')
59
+ const [notice, setNotice] = useState('')
60
+ const [toolQuery, setToolQuery] = useState('')
61
+ const [skillQuery, setSkillQuery] = useState('')
62
+ const [toolGroup, setToolGroup] = useState('builtin')
63
+ const [toolStatus, setToolStatus] = useState('all')
64
+ const [skillStatus, setSkillStatus] = useState('all')
65
+ const [skillGroup, setSkillGroup] = useState('global')
66
+ const [skillSource, setSkillSource] = useState('skills.sh')
67
+ const [discoverQuery, setDiscoverQuery] = useState('')
68
+ const [results, setResults] = useState([])
69
+ const [target, setTarget] = useState('global')
70
+ const [searching, setSearching] = useState(false)
71
+ const seq = useRef(0)
72
+ const debounce = useRef(null)
73
+ const refreshTimer = useRef(null)
74
+ const feedbackTimer = useRef(null)
75
+ const refreshGeneration = useRef(0)
76
+ const searchSeq = useRef(0)
77
+ const sessions = useSessions(state => state)
78
+ const activeSession = Object.values(sessions.byId).find(session => (session.retainedBy?.mainView ?? 0) > 0)?.id
79
+ const [recordSession, setRecordSession] = useState(undefined)
80
+ const [showActual, setShowActual] = useState(false)
81
+ const sessionId = recordSession ?? activeSession
82
+
83
+ const load = useCallback(async (selection = {}, quiet = false) => {
84
+ const current = ++seq.current
85
+ if (!quiet) { clearTimeout(refreshTimer.current); setBusy(true); setError('') }
86
+ try {
87
+ const next = await request('state', { sessionId, ...selection })
88
+ if (current !== seq.current) return undefined
89
+ setData(next)
90
+ if (!selection.draft) {
91
+ setSavedPolicy(next.policy || { disabledTools: [], enabledTools: [], disabledSkills: [], enabledSkills: [], importedSkills: [] })
92
+ setDraft(next.policy || { disabledTools: [], enabledTools: [], disabledSkills: [], enabledSkills: [], importedSkills: [] })
93
+ }
94
+ return true
95
+ } catch (err) {
96
+ if (current === seq.current) setError(err.message || String(err))
97
+ return current === seq.current ? false : undefined
98
+ } finally { if (current === seq.current && !quiet) setBusy(false) }
99
+ }, [sessionId])
100
+
101
+ useEffect(() => { load() }, [load])
102
+ useEffect(() => () => { seq.current++; searchSeq.current++; refreshGeneration.current++; clearTimeout(debounce.current); clearTimeout(refreshTimer.current); clearTimeout(feedbackTimer.current) }, [])
103
+
104
+ const refresh = useCallback((selection = {}, value = draft) => {
105
+ clearTimeout(refreshTimer.current)
106
+ refreshTimer.current = setTimeout(() => load({ ...selection, ...(value ? { draft: value } : {}) }, true), 180)
107
+ }, [draft, load])
108
+
109
+ async function refreshInventory() {
110
+ if (!data || refreshing || busy) return
111
+ clearTimeout(refreshTimer.current)
112
+ clearTimeout(feedbackTimer.current)
113
+ const generation = ++refreshGeneration.current
114
+ setRefreshing(true)
115
+ setRefreshStatus('正在刷新能力清单…')
116
+ setError('')
117
+ const succeeded = await load({ presetId: data.presetId, workspaceId: data.workspaceId, ...(draft ? { draft } : {}) }, true)
118
+ if (generation !== refreshGeneration.current) return
119
+ setRefreshing(false)
120
+ if (succeeded === undefined) {
121
+ setRefreshStatus('')
122
+ return
123
+ }
124
+ setRefreshStatus(succeeded ? '能力清单已刷新' : '刷新失败')
125
+ feedbackTimer.current = setTimeout(() => setRefreshStatus(''), 1800)
126
+ }
127
+
128
+ const changed = JSON.stringify(draft) !== JSON.stringify(savedPolicy || {})
129
+ const toggle = (kind, item) => {
130
+ if (!item.available || item.fixed) return
131
+ const isTool = kind === 'tool'
132
+ const enabledKey = isTool ? 'enabledTools' : 'enabledSkills'
133
+ const disabledKey = isTool ? 'disabledTools' : 'disabledSkills'
134
+ const enabledNow = !!item.enabled
135
+ const id = item.name
136
+ const nextDraft = { ...(draft || {}), [enabledKey]: [...(draft?.[enabledKey] || [])], [disabledKey]: [...(draft?.[disabledKey] || [])] }
137
+ nextDraft[enabledKey] = nextDraft[enabledKey].filter(value => value !== id)
138
+ nextDraft[disabledKey] = nextDraft[disabledKey].filter(value => value !== id)
139
+ if (enabledNow) nextDraft[disabledKey].push(id)
140
+ else nextDraft[enabledKey].push(id)
141
+ setDraft(() => {
142
+ return nextDraft
143
+ })
144
+ const list = isTool ? 'tools' : 'skills'
145
+ setData(previous => previous && ({ ...previous, [list]: previous[list].map(row => row.name === id ? { ...row, enabled: !enabledNow } : row) }))
146
+ refresh({ presetId: data?.presetId, workspaceId: data?.workspaceId }, nextDraft)
147
+ }
148
+
149
+ async function save() {
150
+ if (!draft || !data) return
151
+ setBusy(true); setError(''); setNotice('')
152
+ try {
153
+ clearTimeout(refreshTimer.current)
154
+ await request('save', { presetId: data.presetId, workspaceId: data.workspaceId, draft, sessionId })
155
+ setNotice('配置已保存')
156
+ await load({ presetId: data.presetId, workspaceId: data.workspaceId })
157
+ } catch (err) { setError(err.message || String(err)) }
158
+ finally { setBusy(false) }
159
+ }
160
+
161
+ const search = useCallback((query, source = skillSource) => {
162
+ clearTimeout(debounce.current)
163
+ if (!query.trim()) { setResults([]); setSearching(false); return }
164
+ const requestId = ++searchSeq.current
165
+ setSearching(true)
166
+ debounce.current = setTimeout(async () => {
167
+ try {
168
+ const result = await request('search', { source, query: query.trim() })
169
+ if (requestId === searchSeq.current) setResults(result.results || [])
170
+ } catch (err) { if (requestId === searchSeq.current) setError(err.message || String(err)) }
171
+ finally { if (requestId === searchSeq.current) setSearching(false) }
172
+ }, 320)
173
+ }, [skillSource])
174
+
175
+ async function importSkill(selection) {
176
+ setBusy(true); setError(''); setNotice('')
177
+ try {
178
+ const result = await request('import', { selection, workspaceId: data?.workspaceId, target })
179
+ setNotice(`已导入 ${result.name || selection.name || selection.id || '技能'}`)
180
+ await load({ presetId: data?.presetId, workspaceId: data?.workspaceId, ...(changed ? { draft } : {}) })
181
+ } catch (err) { setError(err.message || String(err)) }
182
+ finally { setBusy(false) }
183
+ }
184
+
185
+ 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 能力目录…'))
186
+
187
+ const matches = (row, query, state) => (state === 'all' || row.enabled === (state === 'enabled')) &&
188
+ `${row.name} ${row.description || ''} ${row.source || ''}`.toLowerCase().includes(query.toLowerCase())
189
+ const toolTab = (data.tools || []).filter(row => row.group === toolGroup)
190
+ const skillTab = (data.skills || []).filter(row => row.group === skillGroup)
191
+ const tools = toolTab.filter(row => matches(row, toolQuery, toolStatus))
192
+ const skills = skillTab.filter(row => matches(row, skillQuery, skillStatus))
193
+ const visibleBudget = showActual && data.actual ? data.actual.budget : data.budget
194
+ const breakdown = budgetRows(visibleBudget)
195
+ const n = value => Number(value || 0).toLocaleString('zh-CN')
196
+ const labelGroup = value => ({ builtin: '内置工具', plugin: '插件工具', mcp: 'MCP 工具', unknown: '其他来源', global: '全局技能', workspace: '工作区技能' })[value] || value || '其他'
197
+ const delta = value => `${value > 0 ? '+' : ''}${n(value)}`
198
+ const fee = value => new Intl.NumberFormat('zh-CN', { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 4, signDisplay: 'exceptZero' }).format(value)
199
+ const fees = data.pricing?.minimum == null ? data.pricing?.status || '暂无适用费率'
200
+ : h('span', { className: 'dcm-fees' },
201
+ data.pricing.minimum === data.pricing.maximum ? fee(data.pricing.minimum) : `${fee(data.pricing.minimum)} ~ ${fee(data.pricing.maximum)}`,
202
+ h('small', { className: 'dcm-currency-code' }, data.pricing.currency))
203
+ const heading = h(React.Fragment, null,
204
+ h('header', { className: 'dcm-head' },
205
+ h('h1', null, 'Agent 能力管理'),
206
+ h('div', { className: 'dcm-controls' },
207
+ h('label', null, 'Agent 预设',
208
+ h('select', {
209
+ value: data.presetId || '',
210
+ onChange: e => load({ presetId: e.target.value, workspaceId: data.workspaceId }),
211
+ }, ...(data.presets || []).map(p => h('option', {
212
+ key: p.id, value: p.id, disabled: p.available === false,
213
+ }, `${p.name}${p.available === false ? `(不可用:${p.reason || '无法加载'})` : ''}`)))),
214
+ h('label', null, '预算工作区',
215
+ h('select', {
216
+ value: data.workspaceId || '',
217
+ onChange: e => load({ presetId: data.presetId, workspaceId: e.target.value, ...(changed ? { draft } : {}) }),
218
+ }, h('option', { value: '' }, '无工作区'), ...(data.workspaces || []).map(w => h('option', { key: w.id, value: w.id }, w.name)))))),
219
+ h('div', { className: 'dcm-actions' },
220
+ refreshStatus && h('small', { className: 'dcm-action-status', 'aria-live': 'polite' }, refreshStatus),
221
+ h('button', {
222
+ type: 'button', className: `dcm-refresh ${refreshing ? 'is-refreshing' : ''}`,
223
+ disabled: refreshing || busy, onClick: refreshInventory,
224
+ title: '刷新能力清单', 'aria-label': '刷新能力清单',
225
+ }, h('span', { 'aria-hidden': true }, '↻')),
226
+ h('button', { className: 'dcm-primary', disabled: !changed || busy || refreshing, onClick: save }, busy ? '处理中…' : '保存预设')))
227
+
228
+ const displayedActual = showActual && data.actual
229
+ const sessionOptions = sessions.ids.map(id => sessions.byId[id]).filter(row => row && !row.parentId)
230
+ const detailRows = [
231
+ ...breakdown.filter(row => !['base-system', 'automatic'].includes(row.key)),
232
+ { key: 'capability', label: 'Agent 能力小计', tokens: visibleBudget.capability, emphasis: true },
233
+ ...breakdown.filter(row => ['base-system', 'automatic'].includes(row.key)),
234
+ { key: 'total', label: '初始注入总量', tokens: visibleBudget.total, emphasis: true, total: true },
235
+ ]
236
+ const splitAt = Math.ceil(detailRows.length / 2)
237
+ const detailFont = `${Math.max(9, 12 - Math.max(0, detailRows.length - 8) * 0.35)}px`
238
+ const summary = h('section', { className: 'dcm-summary' },
239
+ h('article', { className: 'dcm-card' },
240
+ h('div', { className: 'dcm-card-title' },
241
+ title('整体统计', '月度费用按每月 1,500 次模型请求、未命中缓存的输入费率估算。'),
242
+ h('span', null, `计价模型 ${data.pricing?.model || '—'} · DSH 默认`)),
243
+ h('div', { className: 'dcm-metrics' },
244
+ metric('已启用能力', `${n(data.budget?.count)} 项`, `${delta(data.budget.count - data.savedBudget.count)} 项较已保存`),
245
+ metric('能力注入 · 单次', `${n(data.budget?.capability)} tok`, `${delta(data.budget.capability - data.savedBudget.capability)} tok 较已保存`),
246
+ metric('初始注入 · 单次', `${n(data.budget?.total)} tok`, '含系统与其他自动注入'),
247
+ metric('月度输入费用变化', fees, '每月 1,500 次模型请求'))),
248
+ h('article', { className: 'dcm-card dcm-injection' },
249
+ h('div', { className: 'dcm-card-title' },
250
+ title(displayedActual ? '首请求注入明细 · 实际' : '首请求注入明细 · 估算', '按注入内容估算 token。技能按目录条目计量。预算排除用户消息、会话历史和工作区指令。'),
251
+ sessionOptions.length > 0 && h('select', {
252
+ 'aria-label': '核对首请求的会话', value: sessionId || '',
253
+ onChange: event => { setRecordSession(event.target.value); setShowActual(!!event.target.value) },
254
+ }, h('option', { value: '' }, '选择会话核对'), ...sessionOptions.map(row => h('option', { key: row.id, value: row.id }, row.displayTitle))),
255
+ data.actual && h('button', { className: 'dcm-button', onClick: () => setShowActual(!showActual) }, displayedActual ? '查看预算' : '查看实际')),
256
+ h('div', { className: 'dcm-bar', 'aria-hidden': true }, ...breakdown.filter(row => row.tokens).map(row => h('i', {
257
+ key: row.key, title: `${row.label} ${n(row.tokens)} tok`, style: { background: row.color, flexGrow: row.tokens },
258
+ }))),
259
+ h('div', { className: 'dcm-breakdown' },
260
+ detailColumn(detailRows.slice(0, splitAt)),
261
+ detailColumn(detailRows.slice(splitAt))),
262
+ displayedActual && h('small', { className: 'dcm-caption' }, [
263
+ data.actual.presetId && (data.presets.find(row => row.id === data.actual.presetId)?.name ?? data.actual.presetId),
264
+ data.workspaces.find(row => row.id === data.actual.workspaceId)?.name,
265
+ [data.actual.provider, data.actual.model].filter(Boolean).join(' / '),
266
+ data.actual.inputTokens == null ? '' : `服务商报告输入 ${n(data.actual.inputTokens)} tok`,
267
+ ].filter(Boolean).join(' · '))))
268
+
269
+ const toolGroups = ['builtin', 'plugin', 'mcp', ...(data.tools.some(row => row.group === 'unknown') ? ['unknown'] : [])]
270
+ const toolPanel = h('section', { className: 'dcm-card dcm-list' }, h('div', { className: 'dcm-listhead' }, h('h2', null, '工具'),
271
+ tabs(toolGroups.map(group => [group, labelGroup(group)]), toolGroup, setToolGroup),
272
+ h('span', null, `${toolTab.filter(x => x.enabled).length} / ${toolTab.length} 已启用`)),
273
+ h('div', { className: 'dcm-filter' }, h('input', { type: 'search', value: toolQuery, placeholder: '搜索名称、说明或来源', onChange: e => setToolQuery(e.target.value), 'aria-label': '搜索工具' }), statusFilter(toolStatus, setToolStatus)),
274
+ h('div', { className: 'dcm-scroll', role: 'region', 'aria-label': '工具列表' }, tools.length ? tools.map(row => itemRow(row, 'tool')) : empty('没有符合条件的工具')))
275
+
276
+ const skillPanel = h('section', { className: 'dcm-card dcm-list' }, h('div', { className: 'dcm-listhead' }, h('h2', null, '技能'),
277
+ tabs([['global', '全局技能'], ['workspace', '工作区技能'], ['discover', '发现技能']], skillGroup, setSkillGroup),
278
+ skillGroup !== 'discover' && h('span', null, `${skillTab.filter(x => x.enabled).length} / ${skillTab.length} 已启用`)),
279
+ 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('输入关键词搜索技能目录')))
280
+ : 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('没有符合条件的技能'))))
281
+
282
+ 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,
283
+ h('div', { className: 'dcm-dashboard' }, summary, toolPanel, skillPanel))
284
+
285
+ function metric(label, value, detail) {
286
+ return h('div', { className: 'dcm-metric', key: label }, h('small', null, label), h('strong', null, value), h('small', null, detail))
287
+ }
288
+ function title(label, help) {
289
+ return h('h2', null, label, h('button', { type: 'button', className: 'dcm-help', title: help, 'aria-label': help }, '!'))
290
+ }
291
+ function budgetRow(row) {
292
+ return h('div', { className: `dcm-breakrow ${row.emphasis ? 'dcm-emphasis' : ''} ${row.total ? 'dcm-total' : ''}`, key: row.key },
293
+ h('span', null, row.color && h('i', { style: { background: row.color } }), row.label),
294
+ h('strong', null, `${n(row.tokens)} tok`))
295
+ }
296
+ function detailColumn(rows) {
297
+ return h('div', { className: 'dcm-breakcolumn', style: { '--row-count': rows.length, '--detail-font': detailFont } },
298
+ ...rows.map(budgetRow))
299
+ }
300
+ function tabs(options, selected, setSelected) {
301
+ return h('div', { className: 'dcm-tabs' }, ...options.map(([key, label]) => h('button', {
302
+ key, className: selected === key ? 'active' : '', 'aria-pressed': selected === key, onClick: () => setSelected(key),
303
+ }, label)))
304
+ }
305
+ function statusFilter(selected, setSelected) {
306
+ return h('select', { value: selected, onChange: event => setSelected(event.target.value), 'aria-label': '按状态筛选' },
307
+ ...[['all', '全部状态'], ['enabled', '已启用'], ['disabled', '已关闭']].map(([key, label]) => h('option', { key, value: key }, label)))
308
+ }
309
+ function empty(text) { return h('p', { className: 'dcm-empty', role: 'status' }, text) }
310
+ function itemRow(row, kind) {
311
+ return h('div', { className: 'dcm-row', key: `${kind}:${row.name}` },
312
+ h('div', { className: 'dcm-row-info' },
313
+ 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),
314
+ h('small', { title: row.description || '' }, row.description || '无说明')),
315
+ h('span', { className: 'dcm-tokens' }, `≈${n(row.tokens)} tok`),
316
+ 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')))
317
+ }
318
+ }
319
+
320
+ function Style() {
321
+ 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}
322
+ .dcm *{box-sizing:border-box}
323
+ .dcm-head{display:flex;align-items:center;justify-content:space-between;gap:30px;margin-bottom:3px}
324
+ .dcm h1{font-size:20px;margin:0;white-space:nowrap}
325
+ .dcm h2{font-size:15px;margin:0}
326
+ .dcm-muted{color:var(--muted);font-size:11px;margin:4px 0 0}
327
+ .dcm-controls{display:flex;align-items:flex-end;justify-content:flex-end;gap:10px;flex-wrap:wrap}
328
+ .dcm-controls label{display:grid;gap:3px;font-size:10px;color:var(--muted)}
329
+ .dcm select,.dcm input{min-width:125px;border:1px solid #bbc9da;border-radius:7px;padding:6px 8px;background:white;color:var(--ink);font:inherit}
330
+ .dcm button{font:inherit;cursor:pointer}
331
+ .dcm-actions{display:flex;align-items:center;justify-content:flex-end;gap:8px;min-height:34px;margin-bottom:9px}
332
+ .dcm-action-status{margin-right:auto;color:var(--muted);font-size:11px}
333
+ .dcm-primary,.dcm-button{border:1px solid #c7d2e1;border-radius:7px;padding:6px 11px;background:#fff;color:#24344b}
334
+ .dcm-primary{background:#2867c8;border-color:#2867c8;color:white;font-weight:600}
335
+ .dcm button:disabled{opacity:.48;cursor:not-allowed}
336
+ .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}
337
+ .dcm-refresh.is-refreshing span{animation:dcm-spin .8s linear infinite}
338
+ @keyframes dcm-spin{to{transform:rotate(360deg)}}
339
+ .dcm-dashboard{flex:1;min-height:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));grid-template-rows:auto minmax(170px,1fr);gap:8px}
340
+ .dcm-summary{grid-column:1/-1;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px;min-height:0;align-items:stretch}
341
+ .dcm-card{background:#fff;border:1px solid var(--line);border-radius:11px;box-shadow:0 2px 8px #24395408;min-width:0}
342
+ .dcm-summary>.dcm-card{padding:9px 11px;min-height:0;overflow:hidden}
343
+ .dcm-card-title,.dcm-listhead{display:flex;align-items:center;justify-content:space-between;gap:7px;min-width:0}
344
+ .dcm-card-title h2{margin-right:auto;white-space:nowrap}
345
+ .dcm-card-title>span,.dcm-listhead>span{font-size:10px;color:var(--muted)}
346
+ .dcm-card-title select,.dcm-card-title .dcm-button{font-size:10px;padding:3px 5px;min-width:0;max-width:110px}
347
+ .dcm-help{margin-left:4px;border:0;border-radius:50%;height:15px;width:15px;padding:0;background:#e7edf4;color:#58697e;font-size:10px!important}
348
+ .dcm-metrics{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:6px;margin:7px 0 0}
349
+ .dcm-metric{padding:6px 7px;border:1px solid var(--line);border-radius:8px;background:#f8fafc;min-width:0}
350
+ .dcm-metric small{display:block;color:var(--muted);font-size:10px;line-height:1.3}
351
+ .dcm-metric strong{display:block;font-size:clamp(14px,1.35vw,19px);line-height:1.2;margin:3px 0;overflow-wrap:anywhere}
352
+ .dcm-fees{white-space:nowrap;font-size:.9em}
353
+ .dcm-currency-code{font-size:.68em;color:var(--muted);font-weight:500;margin-left:4px}
354
+ .dcm-injection{display:flex;flex-direction:column;min-height:0;contain:size}
355
+ .dcm-injection .dcm-bar{flex:none}
356
+ .dcm-injection .dcm-breakdown{flex:1;min-height:0}
357
+ .dcm-bar{display:flex;height:6px;flex:none;border-radius:7px;overflow:hidden;background:#e9eef5;margin:6px 0}
358
+ .dcm-bar i{flex-basis:0}
359
+ .dcm-breakdown{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:0 12px;margin:0}
360
+ .dcm-breakcolumn{display:grid;grid-template-rows:repeat(var(--row-count),minmax(0,1fr));min-width:0;min-height:0;overflow:hidden}
361
+ .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}
362
+ .dcm-breakrow>span{display:flex;align-items:center;gap:4px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
363
+ .dcm-breakrow i{display:block;flex:none;width:7px;height:7px;border-radius:2px}
364
+ .dcm-breakrow strong{flex:none;white-space:nowrap;font-size:inherit}
365
+ .dcm-emphasis{font-weight:700;border-top:1px solid var(--line)}
366
+ .dcm-total{border-top:1px solid var(--line);border-bottom:0}
367
+ .dcm-caption{display:block;flex:none;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--muted);font-size:9px;margin-top:3px}
368
+ .dcm-list{display:flex;flex-direction:column;min-height:0;overflow:hidden}
369
+ .dcm-listhead{padding:7px 9px 0;justify-content:flex-start;flex-wrap:wrap}
370
+ .dcm-listhead>span{margin-left:auto;white-space:nowrap}
371
+ .dcm-listhead .dcm-tabs{padding:0;gap:8px;border:0}
372
+ .dcm-filter{display:flex;gap:7px;padding:5px 8px;border-bottom:1px solid var(--line)}
373
+ .dcm-filter input{flex:1;min-width:0;padding:5px 7px;font-size:11px}
374
+ .dcm-filter select{min-width:90px;padding:5px;font-size:11px}
375
+ .dcm-scroll{flex:1;min-height:0;overflow:auto;padding:3px 9px 8px;overscroll-behavior:contain}
376
+ .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}
377
+ .dcm-row-info{min-width:0;display:flex;flex-direction:column}
378
+ .dcm-row-title{display:flex;align-items:baseline;gap:6px;min-width:0}
379
+ .dcm-row-info strong{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:12px}
380
+ .dcm-row-title strong{flex:0 1 auto}
381
+ .dcm-row-info small{color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:10px}
382
+ .dcm-row-info .dcm-source{flex:none;max-width:38%;font-size:9px;color:#718096}
383
+ .dcm-tokens,.dcm-fixed{font-size:10px;color:var(--muted);white-space:nowrap}
384
+ .dcm-switch{width:36px;height:21px;border:0;border-radius:12px;padding:2px;background:#cbd3df;transition:background .15s}
385
+ .dcm-switch span{display:block;width:17px;height:17px;border-radius:50%;background:white;box-shadow:0 1px 3px #0003;transition:transform .15s}
386
+ .dcm-switch.on{background:#2867c8}
387
+ .dcm-switch.on span{transform:translateX(15px)}
388
+ .dcm-tabs{display:flex;gap:12px;padding:4px 9px;border-bottom:1px solid var(--line);overflow:auto;flex:none}
389
+ .dcm-tabs button{border:0;border-bottom:2px solid transparent;background:none;color:var(--muted);padding:4px 1px;white-space:nowrap;font-size:11px}
390
+ .dcm-tabs button.active{color:var(--accent);border-color:var(--accent);font-weight:600}
391
+ .dcm-discover{display:flex;flex:1;min-height:0;flex-direction:column}
392
+ .dcm-target{display:flex;align-items:center;gap:8px;padding:5px 9px;color:var(--muted);font-size:11px}
393
+ .dcm-target select{padding:4px;min-width:0}
394
+ .dcm-empty{padding:16px 4px;color:var(--muted);font-size:11px}
395
+ .dcm-error,.dcm-notice{padding:7px 10px;margin:0 0 8px;border-radius:7px;font-size:11px}
396
+ .dcm-error{color:#9c2f26;background:#fff0ee;border:1px solid #f0c4bf}
397
+ .dcm-notice{color:#24623c;background:#effaf2;border:1px solid #c7e7ce}
398
+ @media(max-width:850px){.dcm{padding:12px}.dcm-head{align-items:flex-start;flex-direction:column;gap:7px}.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:120px}.dcm-injection{min-height:175px;contain:none}.dcm-metrics{grid-template-columns:repeat(2,minmax(0,1fr))}.dcm-list{height:42vh;min-height:240px;flex:none}}
399
+ @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}}
400
+ `)
401
+ }
402
+ ctx.slots.inject('main', () => ctx.slots.register({ name: 'main', key: ID }, Panel))
403
+ 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' }, '◈') }))
404
+ }
405
+
406
+ return { inject, apply }
407
+ } })