dsh-skill-harbor 0.3.0 → 0.3.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.
@@ -0,0 +1,284 @@
1
+ /**
2
+ * 技能港湾面板(客户端半)。
3
+ *
4
+ * 无框架依赖:DSH 的 slots 只要求返回 DOM 节点。用原生 DOM 避免把 React
5
+ * 打进插件包,也避免跨 React 根复用组件的样式事故。
6
+ */
7
+ import { api, dict } from './api.js'
8
+ import { FILE_STATE_LABEL } from './labels.js'
9
+
10
+ const CSS_ID = 'dsh-skill-harbor-style'
11
+
12
+ function injectStyles() {
13
+ if (typeof document === 'undefined') return
14
+ if (document.getElementById(CSS_ID) !== null) return
15
+ const style = document.createElement('style')
16
+ style.id = CSS_ID
17
+ style.textContent = `
18
+ .dshh-root { display: flex; flex-direction: column; gap: 12px; padding: 12px; font-size: 13px; }
19
+ .dshh-tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--dsw-alias-border, #3334); }
20
+ .dshh-tab { padding: 6px 12px; cursor: pointer; border: none; background: transparent; color: inherit; border-radius: 4px 4px 0 0; }
21
+ .dshh-tab[data-active="true"] { background: var(--dsw-alias-surface, #ffffff10); font-weight: 600; }
22
+ .dshh-toolbar { display: flex; gap: 8px; align-items: center; flex-wrap: nowrap; }
23
+ .dshh-spacer { flex: 1; }
24
+ .dshh-table { width: 100%; border-collapse: collapse; }
25
+ .dshh-table th, .dshh-table td { text-align: left; padding: 6px 8px; border-bottom: 1px solid var(--dsw-alias-border, #3333); }
26
+ .dshh-state { padding: 1px 6px; border-radius: 3px; font-size: 11px; }
27
+ .dshh-state[data-state="editable"] { background: #2e7d3233; color: #4caf50; }
28
+ .dshh-state[data-state="provider-file"] { background: #ed6c0233; color: #ff9800; }
29
+ .dshh-state[data-state="virtual"] { background: #9e9e9e33; color: #9e9e9e; }
30
+ .dshh-shadowed { opacity: 0.55; }
31
+ .dshh-shadow-tag { font-size: 11px; color: #ff9800; }
32
+ .dshh-btn { padding: 3px 8px; border-radius: 3px; border: 1px solid var(--dsw-alias-border, #3336); background: transparent; color: inherit; cursor: pointer; }
33
+ .dshh-btn:disabled { opacity: 0.4; cursor: not-allowed; }
34
+ .dshh-empty { padding: 24px; text-align: center; opacity: 0.6; }
35
+ .dshh-verdict { padding: 1px 6px; border-radius: 3px; font-size: 11px; }
36
+ .dshh-verdict[data-v="ok"] { background: #2e7d3233; color: #4caf50; }
37
+ .dshh-verdict[data-v="warn"] { background: #ed6c0233; color: #ff9800; }
38
+ .dshh-verdict[data-v="fail"] { background: #c6282833; color: #f44336; }
39
+ .dshh-verdict[data-v="skipped"] { background: #9e9e9e33; color: #9e9e9e; }
40
+ `
41
+ document.head.appendChild(style)
42
+ }
43
+
44
+ function el(tag, props = {}, children = []) {
45
+ const node = document.createElement(tag)
46
+ for (const [key, value] of Object.entries(props)) {
47
+ if (key === 'className') node.className = value
48
+ else if (key.startsWith('data-')) node.setAttribute(key, value)
49
+ else if (key === 'text') node.textContent = value
50
+ else if (key === 'onClick') node.addEventListener('click', value)
51
+ else node.setAttribute(key, value)
52
+ }
53
+ for (const child of children) node.append(child)
54
+ return node
55
+ }
56
+
57
+ /**
58
+ * 创建面板。返回 { node, destroy }。
59
+ * @param {{ lang?: string }} options
60
+ */
61
+ export function createPanel(options = {}) {
62
+ const lang = options.lang ?? 'zh'
63
+ const t = dict(lang)
64
+
65
+ injectStyles()
66
+
67
+ let tab = 'overview'
68
+ let state = { skills: [], duplicates: [], totals: {}, audit: null, budget: null, error: null }
69
+ let destroyed = false
70
+
71
+ const root = el('div', { className: 'dshh-root' })
72
+ const tabsBar = el('div', { className: 'dshh-tabs' })
73
+ const body = el('div', {})
74
+
75
+ const tabs = [
76
+ ['overview', t.tabOverview],
77
+ ['audit', t.tabAudit],
78
+ ['budget', t.tabBudget],
79
+ ]
80
+
81
+ function renderTabs() {
82
+ tabsBar.replaceChildren(
83
+ ...tabs.map(([id, label]) =>
84
+ el('button', {
85
+ className: 'dshh-tab',
86
+ 'data-active': String(tab === id),
87
+ text: label,
88
+ onClick: () => {
89
+ tab = id
90
+ void refresh()
91
+ },
92
+ }),
93
+ ),
94
+ )
95
+ }
96
+
97
+ function renderOverview() {
98
+ if (state.skills.length === 0) {
99
+ return el('div', { className: 'dshh-empty', text: t.noSkills })
100
+ }
101
+
102
+ const rows = state.skills.map(skill => {
103
+ const shadowed = skill.shadowedBy !== null
104
+ const cells = [
105
+ el('td', { text: skill.name }),
106
+ el('td', { text: sourceLabel(t, skill.source) }),
107
+ el('td', { text: String(skill.rank) }),
108
+ el('td', {}, [
109
+ el('span', {
110
+ className: 'dshh-state',
111
+ 'data-state': skill.fileState,
112
+ text: FILE_STATE_LABEL[skill.fileState] ?? skill.fileState,
113
+ }),
114
+ ]),
115
+ el('td', { text: skill.modelInvocable ? '✓' : '—' }),
116
+ el('td', { text: String(skill.announcementChars) }),
117
+ el('td', {}, [
118
+ shadowed
119
+ ? el('span', { className: 'dshh-shadow-tag', text: `${t.shadowedBy}: ${skill.shadowedBy.source}` })
120
+ : buildActions(skill),
121
+ ]),
122
+ ]
123
+ return el('tr', { className: shadowed ? 'dshh-shadowed' : '' }, cells)
124
+ })
125
+
126
+ return el('div', {}, [
127
+ el('table', { className: 'dshh-table' }, [
128
+ el('thead', {}, [
129
+ el('tr', {}, [
130
+ el('th', { text: t.colName }),
131
+ el('th', { text: t.colSource }),
132
+ el('th', { text: t.colRank }),
133
+ el('th', { text: t.colState }),
134
+ el('th', { text: t.colModel }),
135
+ el('th', { text: t.colChars }),
136
+ el('th', { text: t.colActions }),
137
+ ]),
138
+ ]),
139
+ el('tbody', {}, rows),
140
+ ]),
141
+ ])
142
+ }
143
+
144
+ function buildActions(skill) {
145
+ // provider-file / virtual 一律不渲染写控件
146
+ if (!skill.writable) return el('span', {})
147
+
148
+ const toggle = el('button', {
149
+ className: 'dshh-btn',
150
+ text: skill.modelInvocable ? t.actionDisable : t.actionEnable,
151
+ onClick: async () => {
152
+ try {
153
+ await api.setEnabled(skill.path, !skill.modelInvocable)
154
+ await refresh()
155
+ } catch (error) {
156
+ state.error = error.message
157
+ render()
158
+ }
159
+ },
160
+ })
161
+
162
+ const remove = el('button', {
163
+ className: 'dshh-btn',
164
+ text: t.actionDelete,
165
+ onClick: async () => {
166
+ if (!window.confirm(t.deleteConfirm)) return
167
+ try {
168
+ await api.remove(skill.path)
169
+ await refresh()
170
+ } catch (error) {
171
+ state.error = error.message
172
+ render()
173
+ }
174
+ },
175
+ })
176
+
177
+ return el('span', {}, [toggle, document.createTextNode(' '), remove])
178
+ }
179
+
180
+ function renderAudit() {
181
+ if (state.audit === null) return el('div', { className: 'dshh-empty', text: t.loading })
182
+ const rows = state.audit.results.map(result =>
183
+ el('tr', {}, [
184
+ el('td', { text: result.name }),
185
+ el('td', {}, [el('span', { className: 'dshh-verdict', 'data-v': result.verdict, text: verdictLabel(t, result.verdict) })]),
186
+ el('td', {
187
+ text: result.findings.map(f => `${f.rule} ${f.message}`).join('; ') || result.reason || '',
188
+ }),
189
+ ]),
190
+ )
191
+ const totals = state.audit.totals
192
+ return el('div', {}, [
193
+ el('div', { className: 'dshh-toolbar' }, [
194
+ el('span', { text: `${t.auditOk}: ${totals.ok}` }),
195
+ el('span', { text: `${t.auditWarn}: ${totals.warn}` }),
196
+ el('span', { text: `${t.auditFail}: ${totals.fail}` }),
197
+ el('span', { text: `${t.auditSkipped}: ${totals.skipped}` }),
198
+ ]),
199
+ el('table', { className: 'dshh-table' }, [
200
+ el('thead', {}, [el('tr', {}, [
201
+ el('th', { text: t.colName }),
202
+ el('th', { text: t.tabAudit }),
203
+ el('th', { text: t.colActions }),
204
+ ])]),
205
+ el('tbody', {}, rows),
206
+ ]),
207
+ ])
208
+ }
209
+
210
+ function renderBudget() {
211
+ if (state.budget === null) return el('div', { className: 'dshh-empty', text: t.loading })
212
+ const budget = state.budget
213
+ return el('div', {}, [
214
+ el('div', { className: 'dshh-toolbar' }, [
215
+ el('span', { text: `${t.budgetTotal}: ${budget.total} chars` }),
216
+ el('span', { text: `${t.budgetAnnounced}: ${budget.announcedTotal} chars (${budget.announcedCount})` }),
217
+ el('span', { text: `${t.budgetSkipped}: ${budget.skippedTotal} chars (${budget.skippedCount})` }),
218
+ ]),
219
+ budget.overLimit.length > 0
220
+ ? el('ul', {}, budget.overLimit.map(row =>
221
+ el('li', { text: `${row.name}: ${row.chars} > ${budget.perSkillLimit} (${t.budgetOverLimit})` }),
222
+ ))
223
+ : el('span', {}),
224
+ ])
225
+ }
226
+
227
+ function render() {
228
+ if (destroyed) return
229
+ renderTabs()
230
+ body.replaceChildren(
231
+ state.error !== null ? el('div', { className: 'dshh-empty', text: state.error }) : el('span', {}),
232
+ tab === 'overview' ? renderOverview() : tab === 'audit' ? renderAudit() : renderBudget(),
233
+ )
234
+ }
235
+
236
+ async function refresh() {
237
+ state.error = null
238
+ render()
239
+ try {
240
+ if (tab === 'overview') {
241
+ const data = await api.list()
242
+ state.skills = data.skills
243
+ state.duplicates = data.duplicates
244
+ state.totals = data.totals
245
+ } else if (tab === 'audit') {
246
+ state.audit = await api.audit()
247
+ } else {
248
+ state.budget = await api.budget()
249
+ }
250
+ } catch (error) {
251
+ state.error = error.message
252
+ }
253
+ render()
254
+ }
255
+
256
+ root.append(tabsBar, body)
257
+ void refresh()
258
+
259
+ return {
260
+ node: root,
261
+ destroy() {
262
+ destroyed = true
263
+ root.remove()
264
+ },
265
+ }
266
+ }
267
+
268
+ function sourceLabel(t, source) {
269
+ const map = {
270
+ 'project-dsh': t.sourceProjectDsh,
271
+ 'project-agents': t.sourceProjectAgents,
272
+ runtime: t.sourceRuntime,
273
+ custom: t.sourceCustom,
274
+ 'user-dsh': t.sourceUserDsh,
275
+ 'user-agents': t.sourceUserAgents,
276
+ bundled: t.sourceBundled,
277
+ }
278
+ return map[source] ?? source
279
+ }
280
+
281
+ function verdictLabel(t, verdict) {
282
+ const map = { ok: t.auditOk, warn: t.auditWarn, fail: t.auditFail, skipped: t.auditSkipped }
283
+ return map[verdict] ?? verdict
284
+ }
package/src/client.js CHANGED
@@ -1,14 +1,23 @@
1
1
  /**
2
- * dsh-skill-harbor — client half(Phase 1 只占位,面板在 Phase 2 落地)。
2
+ * dsh-skill-harbor — client half.
3
3
  *
4
4
  * 注册 id **必须**等于 npm 包名,否则 DSH 静默忽略整个客户端半。
5
+ * 注册必须发生在 apply 期顶层,关在任何 inject 回调里 = 失活。
5
6
  */
7
+ import { createPanel } from './panel.js'
8
+ import { LOCALES, LOCALE_IDS } from './locales.js'
9
+
6
10
  const id = 'dsh-skill-harbor'
7
11
 
8
- function factory() {
12
+ function factory(_require) {
9
13
  return {
10
14
  id,
11
- // Phase 2 会在这里注册 slots / 面板 / 设置卡片
15
+ locales: LOCALES,
16
+ localeIds: LOCALE_IDS,
17
+ /** 宿主调用此方法把面板挂到槽位。 */
18
+ createPanel(options = {}) {
19
+ return createPanel(options)
20
+ },
12
21
  }
13
22
  }
14
23
 
@@ -16,4 +25,4 @@ if (typeof window !== 'undefined' && window.__ModuleLoader__?.load) {
16
25
  window.__ModuleLoader__.load({ id, factory })
17
26
  }
18
27
 
19
- export { id, factory }
28
+ export { id, factory, createPanel }
package/src/config.js ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * 插件配置 schema(0.1.7+ 形态)。
3
+ *
4
+ * 按 Phase 0 实测:`installSection` 在 0.1.7 已移除,设置卡由 Config 字段
5
+ * 标 `.volatile()` 自动生成。这里只声明字段语义;具体 schema 对象由宿主
6
+ * 的 config schema 机制消费。
7
+ */
8
+
9
+ /** 单技能公告字符上限的默认值。 */
10
+ export const DEFAULT_BUDGET_LIMIT = 4000
11
+
12
+ /** systemPrompt 公告的硬上限(checklist:开启时 ≤200 字)。 */
13
+ export const ANNOUNCEMENT_HARD_LIMIT = 200
14
+
15
+ /**
16
+ * 配置的默认值与归一化。
17
+ * `managementOnly` 为 true 时**不注册 provider、不注册工具、不碰技能目录**。
18
+ */
19
+ export function normalizeConfig(input = {}) {
20
+ return {
21
+ cwd: typeof input.cwd === 'string' ? input.cwd : process.cwd(),
22
+ dshHome: typeof input.dshHome === 'string' ? input.dshHome : undefined,
23
+ agentsHome: typeof input.agentsHome === 'string' ? input.agentsHome : undefined,
24
+ customSkillDirs: Array.isArray(input.customSkillDirs) ? input.customSkillDirs : [],
25
+ bundledSkillDir: typeof input.bundledSkillDir === 'string' ? input.bundledSkillDir : undefined,
26
+
27
+ budgetLimit: Number.isFinite(input.budgetLimit) && input.budgetLimit > 0
28
+ ? input.budgetLimit
29
+ : DEFAULT_BUDGET_LIMIT,
30
+
31
+ // 默认**不**往 systemPrompt 写公告
32
+ announceToSystemPrompt: input.announceToSystemPrompt === true,
33
+
34
+ managementOnly: input.managementOnly === true,
35
+ }
36
+ }
37
+
38
+ /** 公告文本裁剪到硬上限(按码点,不切坏 emoji)。 */
39
+ export function clampAnnouncement(text) {
40
+ const chars = [...String(text ?? '')]
41
+ return chars.length <= ANNOUNCEMENT_HARD_LIMIT ? chars.join('') : chars.slice(0, ANNOUNCEMENT_HARD_LIMIT).join('')
42
+ }
package/src/index.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * dsh-skill-harbor — host half.
3
3
  *
4
- * Phase 1(证据层):扫描 6 个约定根、解析 frontmatter、三态判定、遮蔽判定,
5
- * 通过 provider 把结果交给官方 skill registry。
6
- * Phase 2(本地管理):受闸保护的 HTTP 路由(列表/读/启停/更新/删除)。
4
+ * Phase 1:证据层(扫描 / 三态 / 遮蔽 / provider)
5
+ * Phase 2:本地管理(受闸 HTTP 路由 + 导入)
6
+ * Phase 3:审计与预算
7
7
  *
8
8
  * Phase 0 实测结论(findings.md):
9
9
  * - `ctx.skills.registerProvider` 全线返回 `() => void`,可直接当 disposer
@@ -12,15 +12,23 @@
12
12
  */
13
13
  import { installProvider } from './provider/lifecycle.js'
14
14
  import { registerRoutes } from './routes/index.js'
15
+ import { normalizeConfig } from './config.js'
15
16
 
16
17
  export const name = 'dsh-skill-harbor'
17
18
 
18
19
  export const inject = ['skills']
19
20
 
20
- export function apply(ctx, config = {}) {
21
- installProvider(ctx, config)
21
+ export function apply(ctx, rawConfig = {}) {
22
+ const config = normalizeConfig(rawConfig)
23
+
24
+ // managementOnly:不注册 provider、不注册工具、不碰 ctx.skills。
25
+ // 只保留只读路由(面板仍能列出它自己扫到的东西)。
26
+ if (!config.managementOnly) {
27
+ installProvider(ctx, config)
28
+ }
22
29
 
23
- // webServer 可能不存在(纯 CLI 场景)→ registerRoutes 内部自行降级
24
30
  const disposeRoutes = registerRoutes(ctx, config)
25
31
  ctx.effect(() => disposeRoutes, 'dsh-skill-harbor.routes')
32
+
33
+ return { name, managementOnly: config.managementOnly }
26
34
  }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * 导入安装器 —— 把归档里的技能落到正确的根,或在更弱的根上明确拒绝。
3
+ *
4
+ * 顺序(不可调换):
5
+ * 解包 → 审计四步 → 落点判定(rank 遮蔽) → 写
6
+ *
7
+ * 「审计先行」是关键:先落盘再审计等于把恶意文件写进用户磁盘,
8
+ * 哪怕随后删掉也留下过时间窗。
9
+ */
10
+ import { mkdirSync, writeFileSync, existsSync } from 'node:fs'
11
+ import { basename, dirname, join, posix } from 'node:path'
12
+
13
+ import { extractTextFiles, stripCommonPrefix, IMPORT_LIMITS, ZipError } from './zip.js'
14
+ import { auditSkillText } from '../audit/rules.js'
15
+ import { safePath, MAX_SEGMENTS } from '../routes/safe-path.js'
16
+ import { rankOf } from '../collect/ranks.js'
17
+
18
+ /** 从一个 zip 里抽出所有技能(每个含 SKILL.md 的目录是一个技能)。 */
19
+ export function parseSkillsFromArchive(buffer) {
20
+ const { files, skippedSymlinks, totalBytes } = extractTextFiles(buffer, IMPORT_LIMITS)
21
+
22
+ const stripped = stripCommonPrefix(files.map(f => f.name))
23
+ const byDir = new Map()
24
+
25
+ for (let i = 0; i < files.length; i += 1) {
26
+ const path = stripped[i]
27
+ const content = files[i].content
28
+ if (!path.toLowerCase().endsWith('skill.md')) continue
29
+
30
+ const dir = posix.dirname(path)
31
+ const name = dir === '.' ? basename(dirname(path)) : posix.basename(dir)
32
+ const siblings = files
33
+ .map((f, index) => ({ path: stripped[index], content: f.content }))
34
+ .filter(item => posix.dirname(item.path) === dir)
35
+
36
+ byDir.set(dir === '.' ? '' : dir, { name, dir, content, siblings })
37
+ }
38
+
39
+ if (byDir.size === 0) {
40
+ throw new ZipError('no-skills', '归档里没有找到含 SKILL.md 的技能')
41
+ }
42
+
43
+ return { skills: [...byDir.values()], skippedSymlinks, totalBytes }
44
+ }
45
+
46
+ /**
47
+ * 判定落点:目标根必须存在,且不能让新技能被更强的根遮蔽。
48
+ *
49
+ * @param {object} options
50
+ * @param {string} options.skillName
51
+ * @param {{path:string, source:string, rank:number}} options.targetRoot 想写入的根
52
+ * @param {Array<{path:string, source:string, rank:number}>} options.allRoots 全部根
53
+ * @param {Array<object>} options.observations 当前扫描结果
54
+ */
55
+ export function decidePlacement({ skillName, targetRoot, allRoots, observations }) {
56
+ const targetRank = rankOf(targetRoot.source)
57
+
58
+ // 已存在同名条目:只有 target 比所有现存的都**更强或相等**才允许覆盖,
59
+ // 否则写进去也是死的(会被遮蔽),报 shadowed 且不写。
60
+ const existing = observations.filter(
61
+ o => o.name.toLowerCase() === String(skillName).toLowerCase() && o.shadowedBy === undefined,
62
+ )
63
+
64
+ if (existing.length > 0) {
65
+ const winner = existing[0]
66
+ const winnerRank = rankOf(winner.source)
67
+ if (winnerRank < targetRank) {
68
+ return {
69
+ ok: false,
70
+ reason: 'shadowed',
71
+ message: `同名技能 "${winner.name}" 已存在于更强的根(${winner.source}, rank ${winnerRank}),写入 ${targetRoot.source}(rank ${targetRank})会被遮蔽,未写入`,
72
+ }
73
+ }
74
+ if (winnerRank === targetRank && winner.path !== undefined) {
75
+ return {
76
+ ok: false,
77
+ reason: 'already-exists',
78
+ message: `同名技能已存在于同一 rank 的根:${winner.path}`,
79
+ }
80
+ }
81
+ }
82
+
83
+ // 目标目录的每一段都要过 safePath
84
+ const probe = join(targetRoot.path, skillName, 'SKILL.md')
85
+ const safe = safePath(probe)
86
+ if (!safe.ok) {
87
+ return { ok: false, reason: safe.reason, message: `目标路径不安全:${safe.reason}` }
88
+ }
89
+
90
+ return { ok: true, targetDir: join(targetRoot.path, skillName) }
91
+ }
92
+
93
+ /**
94
+ * 安装一个技能到磁盘。审计未过则**不写任何文件**。
95
+ *
96
+ * @returns {{ installed: boolean, reason?: string, message?: string, files?: string[], verdict?: string }}
97
+ */
98
+ export function installSkill({ skill, targetDir, dependencies = true }) {
99
+ // 1) 审计主体
100
+ const audit = auditSkillText(skill.content, { name: skill.name })
101
+ if (audit.verdict === 'fail') {
102
+ return {
103
+ installed: false,
104
+ reason: 'audit-failed',
105
+ verdict: audit.verdict,
106
+ message: `审计阻断:${audit.findings.map(f => `${f.rule} ${f.message}`).join('; ')}`,
107
+ findings: audit.findings,
108
+ }
109
+ }
110
+
111
+ // 2) 目录安全
112
+ const dirSafe = safePath(targetDir)
113
+ if (!dirSafe.ok) {
114
+ return { installed: false, reason: dirSafe.reason, message: `目标目录不安全:${dirSafe.reason}` }
115
+ }
116
+
117
+ // 3) 同目录其它文件也过审计(技能可以带脚本)
118
+ const sidecars = (skill.siblings ?? []).filter(item => !item.path.toLowerCase().endsWith('skill.md'))
119
+ for (const file of sidecars) {
120
+ const fileAudit = auditSkillText(file.content, { name: file.path })
121
+ if (fileAudit.verdict === 'fail') {
122
+ return {
123
+ installed: false,
124
+ reason: 'audit-failed',
125
+ verdict: fileAudit.verdict,
126
+ message: `附属文件 ${file.path} 审计阻断:${fileAudit.findings.map(f => `${f.rule} ${f.message}`).join('; ')}`,
127
+ findings: fileAudit.findings,
128
+ }
129
+ }
130
+ const relSafe = safePath(posix.normalize(file.path))
131
+ if (!relSafe.ok || posix.normalize(file.path).split('/').length > MAX_SEGMENTS) {
132
+ return { installed: false, reason: 'unsafe-sidecar-path', message: `附属文件路径不安全:${file.path}` }
133
+ }
134
+ }
135
+
136
+ // 4) 落盘(只有到这里才开始写磁盘)
137
+ const written = []
138
+ try {
139
+ mkdirSync(targetDir, { recursive: true })
140
+ writeFileSync(join(targetDir, 'SKILL.md'), skill.content, 'utf8')
141
+ written.push(join(targetDir, 'SKILL.md'))
142
+
143
+ for (const file of sidecars) {
144
+ const relative = posix.normalize(file.path)
145
+ const dest = join(targetDir, relative)
146
+ // 再确认一次没跑出 targetDir(`..` 已被 safePath 挡,这是纵深防御)
147
+ if (!dest.startsWith(targetDir)) {
148
+ return { installed: false, reason: 'escaped-target', message: `附属文件越出目标目录:${file.path}` }
149
+ }
150
+ mkdirSync(dirname(dest), { recursive: true })
151
+ writeFileSync(dest, file.content, 'utf8')
152
+ written.push(dest)
153
+ }
154
+ } catch (error) {
155
+ return {
156
+ installed: false,
157
+ reason: 'write-failed',
158
+ message: `写入失败:${error?.message ?? error}`,
159
+ files: written,
160
+ }
161
+ }
162
+
163
+ return {
164
+ installed: true,
165
+ verdict: audit.verdict,
166
+ findings: audit.findings,
167
+ files: written,
168
+ }
169
+ }