@crocketc/dsh-capability-manager 0.0.0-stage → 0.1.1

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 ADDED
@@ -0,0 +1,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 [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
+ } })
@@ -0,0 +1,214 @@
1
+ import { execFile as execFileCallback } from 'node:child_process';
2
+ import { promisify } from 'node:util';
3
+ import { mkdtemp, mkdir, rename, rm, writeFile } from 'node:fs/promises';
4
+ import { isAbsolute, join, resolve, sep } from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+
7
+ const execFile = promisify(execFileCallback);
8
+ const SKILLS_SEARCH = 'https://skills.sh/api/search';
9
+ const SKILLS_DOWNLOAD = 'https://skills.sh/api/download';
10
+ const MAX_QUERY = 100;
11
+ const MAX_FILES = 1000;
12
+ const MAX_FILE_BYTES = 4 * 1024 * 1024;
13
+ const MAX_SKILL_BYTES = 16 * 1024 * 1024;
14
+ const SAFE_SEGMENT = /^(?!\.\.?$)(?!.*[. ]$)(?!^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$))[A-Za-z0-9._-]{1,128}$/i;
15
+
16
+ function fail(message) { throw new Error(message); }
17
+
18
+ function safeRelativePath(value) {
19
+ if (typeof value !== 'string' || !value || value.length > 512 || value.includes('\\') || value.startsWith('/') || value.includes('\0')) return false;
20
+ const parts = value.split('/');
21
+ return parts.length <= 32 && parts.every(part => SAFE_SEGMENT.test(part));
22
+ }
23
+
24
+ function parseRepository(input) {
25
+ if (typeof input !== 'string') fail('GitHub 来源必须是 owner/repo 或公开 GitHub URL');
26
+ const raw = input.trim();
27
+ let match = /^([A-Za-z0-9](?:[A-Za-z0-9-]{0,38}))\/([A-Za-z0-9._-]{1,100})$/.exec(raw);
28
+ if (!match) {
29
+ try {
30
+ const url = new URL(raw);
31
+ if (url.protocol !== 'https:' || url.hostname.toLowerCase() !== 'github.com' || url.username || url.password || url.search || url.hash) fail('仅支持公开 GitHub 仓库 URL');
32
+ const parts = url.pathname.split('/').filter(Boolean);
33
+ if (parts.length === 2) match = [raw, parts[0], parts[1]];
34
+ else if (parts.length >= 4 && parts[2] === 'tree') match = [raw, parts[0], parts[1]];
35
+ } catch (error) { if (error.message.startsWith('仅支持')) throw error; }
36
+ }
37
+ if (!match || match[2] === '.' || match[2] === '..') fail('请输入精确的 GitHub owner/repo 或仓库 URL');
38
+ return { owner: match[1], repo: match[2].replace(/\.git$/i, ''), url: `https://github.com/${match[1]}/${match[2].replace(/\.git$/i, '')}.git` };
39
+ }
40
+
41
+ function frontmatter(markdown) {
42
+ const block = /^---\s*\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(markdown)?.[1];
43
+ if (!block) return null;
44
+ const scalar = key => {
45
+ const line = block.split(/\r?\n/).find(row => new RegExp(`^${key}:\\s*`).test(row));
46
+ if (!line) return '';
47
+ let value = line.slice(line.indexOf(':') + 1).trim();
48
+ if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) value = value.slice(1, -1);
49
+ return value.trim();
50
+ };
51
+ const name = scalar('name');
52
+ const description = scalar('description');
53
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) || !description || description.length > 1000) return null;
54
+ return { name, description };
55
+ }
56
+
57
+ function searchUrl(query) {
58
+ const url = new URL(SKILLS_SEARCH);
59
+ url.searchParams.set('q', query);
60
+ return url;
61
+ }
62
+
63
+ async function fetchJson(url, limit = 1024 * 1024) {
64
+ const response = await fetch(url, { headers: { accept: 'application/json' }, redirect: 'error', signal: AbortSignal.timeout(15000) });
65
+ if (!response.ok) fail(`技能目录请求失败 (${response.status})`);
66
+ const data = await response.arrayBuffer();
67
+ if (data.byteLength > limit) fail('技能目录响应过大');
68
+ return JSON.parse(Buffer.from(data).toString('utf8'));
69
+ }
70
+
71
+ async function git(args, cwd) {
72
+ const { stdout } = await execFile('git', args, { cwd, encoding: 'buffer', maxBuffer: 8 * 1024 * 1024, timeout: 120000, windowsHide: true });
73
+ return Buffer.isBuffer(stdout) ? stdout : Buffer.from(stdout);
74
+ }
75
+
76
+ function parseTree(buffer) {
77
+ const records = [];
78
+ for (const item of buffer.toString('utf8').split('\0')) {
79
+ if (!item) continue;
80
+ const tab = item.indexOf('\t');
81
+ const header = item.slice(0, tab).split(' ');
82
+ const path = item.slice(tab + 1);
83
+ if (header.length !== 3 || !safeRelativePath(path)) continue;
84
+ const [mode, type, oid] = header;
85
+ records.push({ mode, type, oid, path });
86
+ }
87
+ return records;
88
+ }
89
+
90
+ async function inspectGitHub(repository) {
91
+ const scratch = await mkdtemp(join(tmpdir(), 'dsh-skill-discovery-'));
92
+ try {
93
+ await git(['clone', '--no-checkout', '--depth', '1', '--filter=blob:none', '--', repository.url, scratch]);
94
+ const tree = parseTree(await git(['ls-tree', '-r', '-z', 'HEAD'], scratch));
95
+ const docs = tree.filter(file => file.type === 'blob' && (file.mode === '100644' || file.mode === '100755') && (file.path === 'SKILL.md' || file.path.endsWith('/SKILL.md'))).slice(0, MAX_FILES);
96
+ const results = [];
97
+ for (const doc of docs) {
98
+ const metadata = frontmatter((await git(['show', `HEAD:${doc.path}`], scratch)).toString('utf8'));
99
+ if (!metadata) continue;
100
+ results.push({ id: `github:${repository.owner}/${repository.repo}:${doc.path}`, name: metadata.name, description: metadata.description, repository: `${repository.owner}/${repository.repo}`, path: doc.path.slice(0, -'SKILL.md'.length).replace(/\/$/, ''), source: 'github' });
101
+ }
102
+ return results;
103
+ } finally { await rm(scratch, { recursive: true, force: true }); }
104
+ }
105
+
106
+ async function searchSkillsSh(query) {
107
+ if (typeof query !== 'string' || !query.trim() || query.trim().length > MAX_QUERY) fail('搜索词不能为空且不能超过 100 个字符');
108
+ const payload = await fetchJson(searchUrl(query.trim()));
109
+ if (!Array.isArray(payload?.skills)) fail('skills.sh 返回了无效搜索结果');
110
+ return payload.skills.slice(0, 100).flatMap(item => {
111
+ if (!item || typeof item !== 'object' || typeof item.source !== 'string' || typeof item.skillId !== 'string' || typeof item.name !== 'string') return [];
112
+ const parts = item.source.split('/');
113
+ if (parts.length !== 2 || !parts.every(part => SAFE_SEGMENT.test(part)) || !safeRelativePath(item.skillId)) return [];
114
+ const id = typeof item.id === 'string' ? item.id : `${item.source}/${item.skillId}`;
115
+ return [{ id: `skillsh:${id}`, name: item.name, description: '', repository: item.source, path: item.skillId, source: 'skills.sh' }];
116
+ });
117
+ }
118
+
119
+ /** 搜索 skills.sh,或扫描一个公开 GitHub 仓库中的 SKILL.md。 */
120
+ export async function searchSkills(source, query) {
121
+ if (typeof source !== 'string') fail('技能来源无效');
122
+ const kind = source.trim().toLowerCase();
123
+ if (kind === 'skills.sh' || kind === 'skillsh') return searchSkillsSh(query);
124
+ const repository = parseRepository(kind === 'github' ? query : source);
125
+ const results = await inspectGitHub(repository);
126
+ const needle = typeof query === 'string' && kind !== 'github' ? query.trim().toLowerCase() : '';
127
+ return needle ? results.filter(item => `${item.name} ${item.description} ${item.path}`.toLowerCase().includes(needle)) : results;
128
+ }
129
+
130
+ function resolveSelection(selection) {
131
+ if (!selection || typeof selection !== 'object' || typeof selection.source !== 'string' || typeof selection.repository !== 'string' || typeof selection.path !== 'string' || (selection.path !== '' && !safeRelativePath(selection.path))) fail('技能选择无效');
132
+ if (selection.source === 'github') {
133
+ const repo = parseRepository(selection.repository);
134
+ return { kind: 'github', repo, skillPath: selection.path };
135
+ }
136
+ if (selection.source === 'skills.sh') {
137
+ if (!selection.path) fail('skills.sh 来源路径无效');
138
+ const parts = selection.repository.split('/');
139
+ if (parts.length !== 2 || !parts.every(part => SAFE_SEGMENT.test(part))) fail('skills.sh 来源无效');
140
+ return { kind: 'skills.sh', owner: parts[0], repo: parts[1], skillPath: selection.path };
141
+ }
142
+ fail('不支持的技能来源');
143
+ }
144
+
145
+ async function downloadSkillsSh(source) {
146
+ const url = new URL(`${SKILLS_DOWNLOAD}/${encodeURIComponent(source.owner)}/${encodeURIComponent(source.repo)}/${encodeURIComponent(source.skillPath)}`);
147
+ const payload = await fetchJson(url, MAX_SKILL_BYTES);
148
+ if (!Array.isArray(payload?.files) || !payload.files.length || payload.files.length > MAX_FILES) fail('skills.sh 下载结果无效');
149
+ return payload.files.map(file => {
150
+ if (!file || typeof file.path !== 'string' || !safeRelativePath(file.path) || typeof file.contents !== 'string') fail('skills.sh 包含不安全文件路径');
151
+ return { path: file.path, data: Buffer.from(file.contents, 'utf8') };
152
+ });
153
+ }
154
+
155
+ async function readGitSkill(source) {
156
+ const scratch = await mkdtemp(join(tmpdir(), 'dsh-skill-import-'));
157
+ try {
158
+ await git(['clone', '--no-checkout', '--depth', '1', '--filter=blob:none', '--', source.repo.url, scratch]);
159
+ const root = source.skillPath ? `${source.skillPath}/` : '';
160
+ const tree = parseTree(await git(['ls-tree', '-r', '-z', 'HEAD'], scratch));
161
+ const selected = tree.filter(file => file.path.startsWith(root));
162
+ if (!selected.some(file => file.path === `${root}SKILL.md`)) fail('所选目录没有 SKILL.md');
163
+ if (selected.length > MAX_FILES) fail('技能文件数量过多');
164
+ const entries = [];
165
+ let total = 0;
166
+ for (const file of selected) {
167
+ const relative = file.path.slice(root.length);
168
+ if (file.type !== 'blob' || (file.mode !== '100644' && file.mode !== '100755')) fail('技能目录包含符号链接或特殊文件');
169
+ if (!safeRelativePath(relative)) fail('技能文件路径不安全');
170
+ const data = await git(['show', `HEAD:${file.path}`], scratch);
171
+ if (data.length > MAX_FILE_BYTES || (total += data.length) > MAX_SKILL_BYTES) fail('技能文件体积过大');
172
+ entries.push({ path: relative, data });
173
+ }
174
+ return entries;
175
+ } finally { await rm(scratch, { recursive: true, force: true }); }
176
+ }
177
+
178
+ /** 安全导入一个已发现的技能。发布仅通过同目录 rename 原子完成。 */
179
+ export async function importSkill(selection, destination, beforePublish = async () => {},
180
+ commit = async (_name, publish) => publish()) {
181
+ const source = resolveSelection(selection);
182
+ if (typeof destination !== 'string' || !isAbsolute(destination)) fail('目标必须是绝对技能目录');
183
+ if (typeof beforePublish !== 'function') fail('beforePublish 必须是函数');
184
+ const entries = source.kind === 'github' ? await readGitSkill(source) : await downloadSkillsSh(source);
185
+ const doc = entries.find(entry => entry.path === 'SKILL.md');
186
+ if (!doc) fail('所选技能缺少 SKILL.md');
187
+ const metadata = frontmatter(doc.data.toString('utf8'));
188
+ if (!metadata) fail('SKILL.md 必须包含有效的 name 和 description');
189
+ const parent = resolve(destination);
190
+ await mkdir(parent, { recursive: true });
191
+ const staging = await mkdtemp(join(parent, '.dsh-skill-staging-'));
192
+ const target = join(parent, metadata.name);
193
+ try {
194
+ for (const entry of entries) {
195
+ if (!safeRelativePath(entry.path)) fail('技能文件路径不安全');
196
+ const output = resolve(staging, ...entry.path.split('/'));
197
+ if (!output.startsWith(`${staging}${sep}`)) fail('技能文件越过暂存目录');
198
+ await mkdir(resolve(output, '..'), { recursive: true });
199
+ await writeFile(output, entry.data, { flag: 'wx' });
200
+ }
201
+ await beforePublish(metadata.name);
202
+ let published = false;
203
+ try {
204
+ await commit(metadata.name, async () => {
205
+ await rename(staging, target);
206
+ published = true;
207
+ });
208
+ } catch (error) {
209
+ if (published) await rename(target, staging);
210
+ throw error;
211
+ }
212
+ return { name: metadata.name };
213
+ } finally { await rm(staging, { recursive: true, force: true }).catch(() => {}); }
214
+ }