dsh-skillmart 0.0.0-stage → 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.
- package/LICENSE +21 -0
- package/README.md +45 -2
- package/client.js +978 -0
- package/cordis.patch.yml +3 -0
- package/icon.svg +5 -0
- package/index.js +685 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +48 -4
package/cordis.patch.yml
ADDED
package/icon.svg
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
|
2
|
+
<path d="M4.2 9.4h15.6l-.9 9.2a2 2 0 0 1-2 1.8H7.1a2 2 0 0 1-2-1.8z" />
|
|
3
|
+
<path d="M8.6 9.4V7.6a3.4 3.4 0 0 1 6.8 0v1.8" />
|
|
4
|
+
<path d="M9.4 13.4h5.2" />
|
|
5
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,685 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 技能市场 —— Host 半边。
|
|
3
|
+
*
|
|
4
|
+
* 三条只读路由把 SkillHub 的公开接口转给本机界面(浏览器直连上游会被跨域挡住),
|
|
5
|
+
* 一条写入路由负责把技能包落到本机技能目录。写入只发生在 <agentsHome>/skills/<slug>,
|
|
6
|
+
* 以及 DSH home 下的一本已装台账;不改动任何已有技能目录,也不碰 profile 配置。
|
|
7
|
+
*/
|
|
8
|
+
import { inflateRawSync } from 'node:zlib'
|
|
9
|
+
import { homedir } from 'node:os'
|
|
10
|
+
import { join } from 'node:path'
|
|
11
|
+
import { mkdir, readFile, readdir, rm, stat, writeFile } from 'node:fs/promises'
|
|
12
|
+
|
|
13
|
+
/** Cordis 函数插件名。 */
|
|
14
|
+
export const name = 'skill-market'
|
|
15
|
+
|
|
16
|
+
/** 只用宿主的两项服务:路由注册与来源校验。 */
|
|
17
|
+
export const inject = ['webServer', 'connection']
|
|
18
|
+
|
|
19
|
+
const UPSTREAM = 'https://api.skillhub.cn'
|
|
20
|
+
const ROUTE_PREFIX = '/local-view-25e475c1/skillhub'
|
|
21
|
+
const SKILLS_ROUTE = `${ROUTE_PREFIX}/skills`
|
|
22
|
+
const CATEGORIES_ROUTE = `${ROUTE_PREFIX}/categories`
|
|
23
|
+
const INSTALLED_ROUTE = `${ROUTE_PREFIX}/installed`
|
|
24
|
+
const INSTALL_ROUTE = `${ROUTE_PREFIX}/install`
|
|
25
|
+
const UNINSTALL_ROUTE = `${ROUTE_PREFIX}/uninstall`
|
|
26
|
+
const CONTENT_ROUTE = `${ROUTE_PREFIX}/content`
|
|
27
|
+
const CONTENT_LIMIT = 200 * 1024
|
|
28
|
+
const BODY_LIMIT = 64 * 1024
|
|
29
|
+
const UPSTREAM_TIMEOUT_MS = 20000
|
|
30
|
+
const DOWNLOAD_TIMEOUT_MS = 60000
|
|
31
|
+
|
|
32
|
+
/** 共享 agent 配置根(与 DSH 的 dsh-home-paths 同一取值规则)。 */
|
|
33
|
+
function agentsHome() {
|
|
34
|
+
const override = process.env.DSH_AGENTS_HOME
|
|
35
|
+
if (typeof override === 'string' && override.trim() !== '') return override.trim()
|
|
36
|
+
return join(homedir(), '.agents')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 用户级技能目录。 */
|
|
40
|
+
function skillsRoot() {
|
|
41
|
+
return join(agentsHome(), 'skills')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 已装台账所在目录。 */
|
|
45
|
+
function ledgerDir() {
|
|
46
|
+
const override = process.env.DSH_HOME
|
|
47
|
+
const home = typeof override === 'string' && override.trim() !== '' ? override.trim() : join(homedir(), '.dsh')
|
|
48
|
+
return join(home, 'skill-market')
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function ledgerFile() {
|
|
52
|
+
return join(ledgerDir(), 'installed.json')
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function sendJson(res, status, payload) {
|
|
56
|
+
res.statusCode = status
|
|
57
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
58
|
+
res.setHeader('cache-control', 'no-store')
|
|
59
|
+
res.end(JSON.stringify(payload))
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function methodNotAllowed(res, allow) {
|
|
63
|
+
res.statusCode = 405
|
|
64
|
+
res.setHeader('allow', allow)
|
|
65
|
+
res.end()
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 连接服务的同源/登录栅栏;没有该服务时按本机直连处理。 */
|
|
69
|
+
function rejected(ctx, req, res) {
|
|
70
|
+
let connection
|
|
71
|
+
try {
|
|
72
|
+
connection = Reflect.get(ctx, 'connection')
|
|
73
|
+
} catch {
|
|
74
|
+
return false
|
|
75
|
+
}
|
|
76
|
+
if (connection === undefined || connection === null) return false
|
|
77
|
+
if (typeof connection.requestRejection !== 'function') return false
|
|
78
|
+
let rejection
|
|
79
|
+
try {
|
|
80
|
+
rejection = connection.requestRejection(req)
|
|
81
|
+
} catch {
|
|
82
|
+
return false
|
|
83
|
+
}
|
|
84
|
+
if (rejection === undefined || rejection === null || rejection === false || rejection === 0) return false
|
|
85
|
+
res.statusCode = typeof rejection === 'number' ? rejection : 403
|
|
86
|
+
res.end()
|
|
87
|
+
return true
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function readJsonBody(req) {
|
|
91
|
+
return new Promise((resolve) => {
|
|
92
|
+
const chunks = []
|
|
93
|
+
let bytes = 0
|
|
94
|
+
let settled = false
|
|
95
|
+
const finish = (value) => {
|
|
96
|
+
if (settled) return
|
|
97
|
+
settled = true
|
|
98
|
+
resolve(value)
|
|
99
|
+
}
|
|
100
|
+
req.on('data', (chunk) => {
|
|
101
|
+
if (settled) return
|
|
102
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
|
|
103
|
+
bytes += buffer.length
|
|
104
|
+
if (bytes > BODY_LIMIT) {
|
|
105
|
+
finish(undefined)
|
|
106
|
+
return
|
|
107
|
+
}
|
|
108
|
+
chunks.push(buffer)
|
|
109
|
+
})
|
|
110
|
+
req.on('end', () => {
|
|
111
|
+
try {
|
|
112
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
113
|
+
finish(parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : undefined)
|
|
114
|
+
} catch {
|
|
115
|
+
finish(undefined)
|
|
116
|
+
}
|
|
117
|
+
})
|
|
118
|
+
req.on('error', () => finish(undefined))
|
|
119
|
+
})
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
async function upstreamJson(path) {
|
|
123
|
+
const response = await fetch(`${UPSTREAM}${path}`, {
|
|
124
|
+
headers: { accept: 'application/json' },
|
|
125
|
+
signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
|
|
126
|
+
})
|
|
127
|
+
if (!response.ok) throw new Error(`上游返回 ${response.status}`)
|
|
128
|
+
return response.json()
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function clampInt(value, fallback, min, max) {
|
|
132
|
+
const parsed = Number.parseInt(String(value ?? ''), 10)
|
|
133
|
+
if (!Number.isFinite(parsed)) return fallback
|
|
134
|
+
return Math.min(max, Math.max(min, parsed))
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function textOf(value) {
|
|
138
|
+
return typeof value === 'string' ? value : ''
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** 把上游技能条目压成本界面吃的形状。 */
|
|
142
|
+
function normalizeSkill(raw) {
|
|
143
|
+
const namespace = raw?.namespace ?? {}
|
|
144
|
+
const author =
|
|
145
|
+
textOf(namespace.displayName) || textOf(raw?.ownerName) || textOf(namespace.handle) || '未知作者'
|
|
146
|
+
return {
|
|
147
|
+
slug: textOf(raw?.slug),
|
|
148
|
+
name: textOf(raw?.name) || textOf(raw?.slug),
|
|
149
|
+
description: textOf(raw?.description_zh) || textOf(raw?.description) || '',
|
|
150
|
+
author,
|
|
151
|
+
downloads: Number.isFinite(raw?.downloads) ? raw.downloads : 0,
|
|
152
|
+
iconUrl: textOf(raw?.iconUrl),
|
|
153
|
+
category: textOf(raw?.category),
|
|
154
|
+
version: textOf(raw?.version),
|
|
155
|
+
verified: raw?.verified === true,
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function handleSkills(req, res) {
|
|
160
|
+
const url = new URL(String(req.url ?? '/'), 'http://localhost')
|
|
161
|
+
const page = clampInt(url.searchParams.get('page'), 1, 1, 5000)
|
|
162
|
+
const pageSize = clampInt(url.searchParams.get('pageSize'), 24, 1, 60)
|
|
163
|
+
const keyword = textOf(url.searchParams.get('keyword')).trim().slice(0, 80)
|
|
164
|
+
const category = textOf(url.searchParams.get('category')).trim().slice(0, 80)
|
|
165
|
+
const query = new URLSearchParams({ page: String(page), pageSize: String(pageSize) })
|
|
166
|
+
if (keyword !== '') query.set('keyword', keyword)
|
|
167
|
+
if (category !== '') query.set('category', category)
|
|
168
|
+
try {
|
|
169
|
+
const payload = await upstreamJson(`/api/skills?${query.toString()}`)
|
|
170
|
+
const body = payload?.data ?? payload ?? {}
|
|
171
|
+
const items = Array.isArray(body.skills) ? body.skills : Array.isArray(body.items) ? body.items : []
|
|
172
|
+
sendJson(res, 200, {
|
|
173
|
+
ok: true,
|
|
174
|
+
page,
|
|
175
|
+
pageSize,
|
|
176
|
+
total: Number.isFinite(body.total) ? body.total : items.length,
|
|
177
|
+
skills: items.map(normalizeSkill).filter((item) => item.slug !== ''),
|
|
178
|
+
})
|
|
179
|
+
} catch (error) {
|
|
180
|
+
sendJson(res, 502, { ok: false, error: `取技能列表失败:${describe(error)}` })
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function handleCategories(req, res) {
|
|
185
|
+
try {
|
|
186
|
+
const payload = await upstreamJson('/api/v1/categories')
|
|
187
|
+
const items = Array.isArray(payload?.items) ? payload.items : []
|
|
188
|
+
const categories = items
|
|
189
|
+
.filter((item) => item?.active !== false && textOf(item?.key) !== '')
|
|
190
|
+
.filter((item) => (Number.isFinite(item?.level) ? item.level : 1) === 1)
|
|
191
|
+
.sort((left, right) => (left?.sortOrder ?? 0) - (right?.sortOrder ?? 0))
|
|
192
|
+
.map((item) => ({ key: textOf(item.key), name: textOf(item.name) || textOf(item.nameEn) || textOf(item.key) }))
|
|
193
|
+
sendJson(res, 200, { ok: true, categories })
|
|
194
|
+
} catch (error) {
|
|
195
|
+
sendJson(res, 502, { ok: false, error: `取分类失败:${describe(error)}` })
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function readLedger() {
|
|
200
|
+
try {
|
|
201
|
+
const parsed = JSON.parse(await readFile(ledgerFile(), 'utf8'))
|
|
202
|
+
return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {}
|
|
203
|
+
} catch {
|
|
204
|
+
return {}
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function writeLedger(ledger) {
|
|
209
|
+
await mkdir(ledgerDir(), { recursive: true })
|
|
210
|
+
await writeFile(ledgerFile(), `${JSON.stringify(ledger, null, 2)}\n`, 'utf8')
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** 目录里真实存在 SKILL.md 才算已装;台账只补版本与时间。 */
|
|
214
|
+
async function listInstalled() {
|
|
215
|
+
const root = skillsRoot()
|
|
216
|
+
const ledger = await readLedger()
|
|
217
|
+
let dirents = []
|
|
218
|
+
try {
|
|
219
|
+
dirents = await readdir(root, { withFileTypes: true })
|
|
220
|
+
} catch {
|
|
221
|
+
return { root, skills: [] }
|
|
222
|
+
}
|
|
223
|
+
const skills = []
|
|
224
|
+
for (const dirent of dirents) {
|
|
225
|
+
if (!dirent.isDirectory()) continue
|
|
226
|
+
if (dirent.name.startsWith('.')) continue
|
|
227
|
+
const skillFile = join(root, dirent.name, 'SKILL.md')
|
|
228
|
+
try {
|
|
229
|
+
const info = await stat(skillFile)
|
|
230
|
+
if (!info.isFile()) continue
|
|
231
|
+
} catch {
|
|
232
|
+
continue
|
|
233
|
+
}
|
|
234
|
+
const record = ledger[dirent.name] ?? {}
|
|
235
|
+
skills.push({
|
|
236
|
+
slug: dirent.name,
|
|
237
|
+
name: textOf(record.name) || dirent.name,
|
|
238
|
+
version: textOf(record.version),
|
|
239
|
+
installedAt: textOf(record.installedAt),
|
|
240
|
+
iconUrl: textOf(record.iconUrl),
|
|
241
|
+
description: textOf(record.description),
|
|
242
|
+
author: textOf(record.author),
|
|
243
|
+
downloads: Number.isFinite(record.downloads) ? record.downloads : null,
|
|
244
|
+
category: textOf(record.category),
|
|
245
|
+
})
|
|
246
|
+
}
|
|
247
|
+
skills.sort((left, right) => left.slug.localeCompare(right.slug))
|
|
248
|
+
return { root, skills }
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** 上游批量取元数据:返回 slug → { iconUrl, name, description, author, category }。失败时安静返回空表。 */
|
|
252
|
+
async function fetchMeta(slugs) {
|
|
253
|
+
const map = new Map()
|
|
254
|
+
if (slugs.length === 0) return map
|
|
255
|
+
try {
|
|
256
|
+
const response = await fetch(`${UPSTREAM}/api/v1/skills/batch`, {
|
|
257
|
+
method: 'POST',
|
|
258
|
+
headers: { 'content-type': 'application/json', accept: 'application/json' },
|
|
259
|
+
body: JSON.stringify({ slugs: slugs.slice(0, 40) }),
|
|
260
|
+
signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
|
|
261
|
+
})
|
|
262
|
+
if (!response.ok) return map
|
|
263
|
+
const payload = await response.json()
|
|
264
|
+
const items = Array.isArray(payload?.items) ? payload.items : []
|
|
265
|
+
for (const item of items) {
|
|
266
|
+
const skill = item?.skill ?? item ?? {}
|
|
267
|
+
const slug = textOf(skill.slug)
|
|
268
|
+
if (slug === '') continue
|
|
269
|
+
const stats = skill.stats ?? {}
|
|
270
|
+
map.set(slug, {
|
|
271
|
+
iconUrl: textOf(skill.iconUrl),
|
|
272
|
+
name: textOf(skill.displayName) || textOf(skill.name),
|
|
273
|
+
description: textOf(skill.summary_zh) || textOf(skill.summary),
|
|
274
|
+
author: textOf(skill.githubAuthorLogin) || textOf(skill.upstream_owner_login),
|
|
275
|
+
category: textOf(skill.category),
|
|
276
|
+
downloads: Number.isFinite(stats.downloads) ? stats.downloads : null,
|
|
277
|
+
})
|
|
278
|
+
}
|
|
279
|
+
} catch {
|
|
280
|
+
// 上游取不到就退回台账与本地 SKILL.md。
|
|
281
|
+
}
|
|
282
|
+
return map
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** 读本地 SKILL.md 的 frontmatter,补 name 与 description。 */
|
|
286
|
+
async function readSkillFrontmatter(slug) {
|
|
287
|
+
try {
|
|
288
|
+
const raw = await readFile(join(skillsRoot(), slug, 'SKILL.md'), 'utf8')
|
|
289
|
+
const text = raw.replace(/^\uFEFF/u, '')
|
|
290
|
+
if (!text.startsWith('---')) return {}
|
|
291
|
+
const end = text.indexOf('\n---', 3)
|
|
292
|
+
if (end < 0) return {}
|
|
293
|
+
const result = {}
|
|
294
|
+
for (const line of text.slice(3, end).split(/\r?\n/u)) {
|
|
295
|
+
const matched = /^(name|description|version)\s*:\s*(.+)$/iu.exec(line.trim())
|
|
296
|
+
if (matched === null) continue
|
|
297
|
+
let value = matched[2].trim()
|
|
298
|
+
if (value.length > 1) {
|
|
299
|
+
const first = value.slice(0, 1)
|
|
300
|
+
if ((first === '"' || first === "'") && value.endsWith(first)) value = value.slice(1, -1)
|
|
301
|
+
}
|
|
302
|
+
result[matched[1].toLowerCase()] = value
|
|
303
|
+
}
|
|
304
|
+
return result
|
|
305
|
+
} catch {
|
|
306
|
+
return {}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function handleInstalled(req, res) {
|
|
311
|
+
try {
|
|
312
|
+
const { root, skills } = await listInstalled()
|
|
313
|
+
const needsRemote = skills.filter((item) => item.iconUrl === '' || item.description === '').map((item) => item.slug)
|
|
314
|
+
const remote = await fetchMeta(needsRemote)
|
|
315
|
+
const ledger = await readLedger()
|
|
316
|
+
let dirty = false
|
|
317
|
+
for (const item of skills) {
|
|
318
|
+
const record = ledger[item.slug] ?? {}
|
|
319
|
+
const upstream = remote.get(item.slug)
|
|
320
|
+
if (upstream !== undefined) {
|
|
321
|
+
if (item.iconUrl === '' && upstream.iconUrl !== '') item.iconUrl = upstream.iconUrl
|
|
322
|
+
if (item.description === '' && upstream.description !== '') item.description = upstream.description
|
|
323
|
+
if (item.name === item.slug && upstream.name !== '') item.name = upstream.name
|
|
324
|
+
if (upstream.author !== '') item.author = upstream.author
|
|
325
|
+
if (item.category === '' && upstream.category !== '') item.category = upstream.category
|
|
326
|
+
if (item.downloads === null && upstream.downloads !== null) item.downloads = upstream.downloads
|
|
327
|
+
}
|
|
328
|
+
if (item.description === '' || item.name === item.slug || item.version === '') {
|
|
329
|
+
const local = await readSkillFrontmatter(item.slug)
|
|
330
|
+
if (item.description === '' && textOf(local.description) !== '') item.description = local.description
|
|
331
|
+
if (item.name === item.slug && textOf(local.name) !== '') item.name = local.name
|
|
332
|
+
if (item.version === '' && textOf(local.version) !== '') item.version = local.version
|
|
333
|
+
}
|
|
334
|
+
if (item.description.length > 160) item.description = `${item.description.slice(0, 157)}…`
|
|
335
|
+
const next = {
|
|
336
|
+
...record,
|
|
337
|
+
name: item.name,
|
|
338
|
+
version: item.version || textOf(record.version),
|
|
339
|
+
installedAt: item.installedAt || new Date().toISOString(),
|
|
340
|
+
iconUrl: item.iconUrl,
|
|
341
|
+
description: item.description,
|
|
342
|
+
author: item.author,
|
|
343
|
+
category: item.category,
|
|
344
|
+
}
|
|
345
|
+
if (item.downloads !== null) next.downloads = item.downloads
|
|
346
|
+
if (JSON.stringify(next) !== JSON.stringify(record)) {
|
|
347
|
+
ledger[item.slug] = next
|
|
348
|
+
dirty = true
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
if (dirty) {
|
|
352
|
+
try {
|
|
353
|
+
await writeLedger(ledger)
|
|
354
|
+
} catch {
|
|
355
|
+
// 台账写不进去只影响下次是否重算。
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
sendJson(res, 200, { ok: true, root, skills })
|
|
359
|
+
} catch (error) {
|
|
360
|
+
sendJson(res, 500, { ok: false, error: `读取已装技能失败:${describe(error)}` })
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** 卸载:只删 skillsRoot/<slug> 这一层目录,并清掉台账里对应的一条。 */
|
|
365
|
+
async function handleContent(req, res) {
|
|
366
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1')
|
|
367
|
+
const slug = textOf(url.searchParams.get('slug'))
|
|
368
|
+
if (!SLUG_PATTERN.test(slug)) {
|
|
369
|
+
sendJson(res, 400, { ok: false, message: '技能名不合法' })
|
|
370
|
+
return
|
|
371
|
+
}
|
|
372
|
+
const file = join(skillsRoot(), slug, 'SKILL.md')
|
|
373
|
+
let content = ''
|
|
374
|
+
try {
|
|
375
|
+
const info = await stat(file)
|
|
376
|
+
if (!info.isFile()) throw new Error('not-file')
|
|
377
|
+
if (info.size > CONTENT_LIMIT) throw new Error('too-large')
|
|
378
|
+
content = await readFile(file, 'utf8')
|
|
379
|
+
} catch {
|
|
380
|
+
sendJson(res, 404, { ok: false, message: '本机没有这个技能的说明文件' })
|
|
381
|
+
return
|
|
382
|
+
}
|
|
383
|
+
sendJson(res, 200, { ok: true, slug, content })
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
async function handleUninstall(req, res) {
|
|
387
|
+
const body = await readJsonBody(req)
|
|
388
|
+
if (body === undefined) {
|
|
389
|
+
sendJson(res, 400, { ok: false, error: '请求体不是合法 JSON' })
|
|
390
|
+
return
|
|
391
|
+
}
|
|
392
|
+
const slug = textOf(body.slug).trim()
|
|
393
|
+
if (!SLUG_PATTERN.test(slug)) {
|
|
394
|
+
sendJson(res, 400, { ok: false, error: '技能标识不合法' })
|
|
395
|
+
return
|
|
396
|
+
}
|
|
397
|
+
const root = skillsRoot()
|
|
398
|
+
const target = join(root, slug)
|
|
399
|
+
if (target !== join(root, slug) || !target.startsWith(root)) {
|
|
400
|
+
sendJson(res, 400, { ok: false, error: '技能目录超出技能根目录' })
|
|
401
|
+
return
|
|
402
|
+
}
|
|
403
|
+
try {
|
|
404
|
+
const info = await stat(join(target, 'SKILL.md'))
|
|
405
|
+
if (!info.isFile()) {
|
|
406
|
+
sendJson(res, 404, { ok: false, error: '这个技能目录里没有 SKILL.md' })
|
|
407
|
+
return
|
|
408
|
+
}
|
|
409
|
+
} catch {
|
|
410
|
+
sendJson(res, 404, { ok: false, error: '这个技能没有装在本机' })
|
|
411
|
+
return
|
|
412
|
+
}
|
|
413
|
+
try {
|
|
414
|
+
await rm(target, { recursive: true, force: true })
|
|
415
|
+
} catch (error) {
|
|
416
|
+
sendJson(res, 500, { ok: false, error: `删除技能目录失败:${describe(error)}` })
|
|
417
|
+
return
|
|
418
|
+
}
|
|
419
|
+
try {
|
|
420
|
+
const ledger = await readLedger()
|
|
421
|
+
if (Object.prototype.hasOwnProperty.call(ledger, slug)) {
|
|
422
|
+
delete ledger[slug]
|
|
423
|
+
await writeLedger(ledger)
|
|
424
|
+
}
|
|
425
|
+
} catch {
|
|
426
|
+
// 目录已经删掉,台账残留只会让下次多查一次图标。
|
|
427
|
+
}
|
|
428
|
+
sendJson(res, 200, { ok: true, slug })
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function describe(error) {
|
|
432
|
+
if (error instanceof Error) return error.message
|
|
433
|
+
return String(error)
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
const SLUG_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$/
|
|
437
|
+
|
|
438
|
+
/** 只接受普通文件条目,拒绝绝对路径与 .. 跳出。 */
|
|
439
|
+
function safeEntryName(entryName) {
|
|
440
|
+
const normalized = entryName.replace(/\\/gu, '/')
|
|
441
|
+
if (normalized.startsWith('/')) return undefined
|
|
442
|
+
if (/^[A-Za-z]:/u.test(normalized)) return undefined
|
|
443
|
+
const parts = normalized.split('/').filter((part) => part !== '' && part !== '.')
|
|
444
|
+
if (parts.length === 0) return undefined
|
|
445
|
+
if (parts.some((part) => part === '..')) return undefined
|
|
446
|
+
return parts.join('/')
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** 最小 zip 读取器:只认 stored 与 deflate,够技能包用。 */
|
|
450
|
+
function readZipEntries(buffer) {
|
|
451
|
+
let eocd = -1
|
|
452
|
+
const lowest = Math.max(0, buffer.length - 66000)
|
|
453
|
+
for (let offset = buffer.length - 22; offset >= lowest; offset -= 1) {
|
|
454
|
+
if (buffer.readUInt32LE(offset) === 0x06054b50) {
|
|
455
|
+
eocd = offset
|
|
456
|
+
break
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
if (eocd < 0) throw new Error('技能包不是有效的 zip')
|
|
460
|
+
const count = buffer.readUInt16LE(eocd + 10)
|
|
461
|
+
let cursor = buffer.readUInt32LE(eocd + 16)
|
|
462
|
+
const entries = []
|
|
463
|
+
for (let index = 0; index < count; index += 1) {
|
|
464
|
+
if (cursor + 46 > buffer.length) throw new Error('技能包目录损坏')
|
|
465
|
+
if (buffer.readUInt32LE(cursor) !== 0x02014b50) throw new Error('技能包目录损坏')
|
|
466
|
+
const method = buffer.readUInt16LE(cursor + 10)
|
|
467
|
+
const compressedSize = buffer.readUInt32LE(cursor + 20)
|
|
468
|
+
const nameLength = buffer.readUInt16LE(cursor + 28)
|
|
469
|
+
const extraLength = buffer.readUInt16LE(cursor + 30)
|
|
470
|
+
const commentLength = buffer.readUInt16LE(cursor + 32)
|
|
471
|
+
const localOffset = buffer.readUInt32LE(cursor + 42)
|
|
472
|
+
const rawName = buffer.toString('utf8', cursor + 46, cursor + 46 + nameLength)
|
|
473
|
+
cursor += 46 + nameLength + extraLength + commentLength
|
|
474
|
+
if (rawName.endsWith('/')) continue
|
|
475
|
+
if (localOffset + 30 > buffer.length) continue
|
|
476
|
+
const dataStart = localOffset + 30 + buffer.readUInt16LE(localOffset + 26) + buffer.readUInt16LE(localOffset + 28)
|
|
477
|
+
const raw = buffer.subarray(dataStart, dataStart + compressedSize)
|
|
478
|
+
const safeName = safeEntryName(rawName)
|
|
479
|
+
if (safeName === undefined) continue
|
|
480
|
+
if (method === 0) {
|
|
481
|
+
entries.push({ name: safeName, data: Buffer.from(raw) })
|
|
482
|
+
} else if (method === 8) {
|
|
483
|
+
entries.push({ name: safeName, data: inflateRawSync(raw) })
|
|
484
|
+
} else {
|
|
485
|
+
throw new Error(`技能包用了不支持的压缩方式 ${method}`)
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return entries
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
async function handleInstall(ctx, req, res) {
|
|
492
|
+
const body = await readJsonBody(req)
|
|
493
|
+
if (body === undefined) {
|
|
494
|
+
sendJson(res, 400, { ok: false, error: '请求体不是合法 JSON' })
|
|
495
|
+
return
|
|
496
|
+
}
|
|
497
|
+
const slug = textOf(body.slug).trim()
|
|
498
|
+
if (!SLUG_PATTERN.test(slug)) {
|
|
499
|
+
sendJson(res, 400, { ok: false, error: '技能标识不合法' })
|
|
500
|
+
return
|
|
501
|
+
}
|
|
502
|
+
const query = new URLSearchParams({ slug })
|
|
503
|
+
const namespace = textOf(body.namespace).trim()
|
|
504
|
+
if (namespace !== '') query.set('namespace', namespace)
|
|
505
|
+
const version = textOf(body.version).trim()
|
|
506
|
+
if (version !== '') query.set('version', version)
|
|
507
|
+
|
|
508
|
+
let archive
|
|
509
|
+
try {
|
|
510
|
+
const response = await fetch(`${UPSTREAM}/api/v1/download?${query.toString()}`, {
|
|
511
|
+
signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),
|
|
512
|
+
})
|
|
513
|
+
if (!response.ok) {
|
|
514
|
+
sendJson(res, 502, { ok: false, error: `下载技能包失败:上游返回 ${response.status}` })
|
|
515
|
+
return
|
|
516
|
+
}
|
|
517
|
+
archive = Buffer.from(await response.arrayBuffer())
|
|
518
|
+
} catch (error) {
|
|
519
|
+
sendJson(res, 502, { ok: false, error: `下载技能包失败:${describe(error)}` })
|
|
520
|
+
return
|
|
521
|
+
}
|
|
522
|
+
if (archive.length < 4 || archive.readUInt32LE(0) !== 0x04034b50) {
|
|
523
|
+
sendJson(res, 502, { ok: false, error: '下载回来的不是 zip 技能包' })
|
|
524
|
+
return
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
let entries
|
|
528
|
+
try {
|
|
529
|
+
entries = readZipEntries(archive)
|
|
530
|
+
} catch (error) {
|
|
531
|
+
sendJson(res, 502, { ok: false, error: `解包失败:${describe(error)}` })
|
|
532
|
+
return
|
|
533
|
+
}
|
|
534
|
+
const skillEntry = entries.find((entry) => entry.name === 'SKILL.md' || entry.name.endsWith('/SKILL.md'))
|
|
535
|
+
if (skillEntry === undefined) {
|
|
536
|
+
sendJson(res, 502, { ok: false, error: '技能包里没有 SKILL.md' })
|
|
537
|
+
return
|
|
538
|
+
}
|
|
539
|
+
const stripPrefix = skillEntry.name === 'SKILL.md' ? '' : skillEntry.name.slice(0, skillEntry.name.length - 'SKILL.md'.length)
|
|
540
|
+
|
|
541
|
+
const target = join(skillsRoot(), slug)
|
|
542
|
+
try {
|
|
543
|
+
const existing = await stat(join(target, 'SKILL.md'))
|
|
544
|
+
if (existing.isFile()) {
|
|
545
|
+
sendJson(res, 409, { ok: false, error: '同名技能目录已存在,未覆盖' })
|
|
546
|
+
return
|
|
547
|
+
}
|
|
548
|
+
} catch {
|
|
549
|
+
// 目录还不存在,继续。
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
try {
|
|
553
|
+
for (const entry of entries) {
|
|
554
|
+
if (stripPrefix !== '' && !entry.name.startsWith(stripPrefix)) continue
|
|
555
|
+
const relative = stripPrefix === '' ? entry.name : entry.name.slice(stripPrefix.length)
|
|
556
|
+
const safeRelative = safeEntryName(relative)
|
|
557
|
+
if (safeRelative === undefined) continue
|
|
558
|
+
const destination = join(target, ...safeRelative.split('/'))
|
|
559
|
+
await mkdir(join(destination, '..'), { recursive: true })
|
|
560
|
+
await writeFile(destination, entry.data)
|
|
561
|
+
}
|
|
562
|
+
} catch (error) {
|
|
563
|
+
sendJson(res, 500, { ok: false, error: `写入技能目录失败:${describe(error)}` })
|
|
564
|
+
return
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
const ledger = await readLedger()
|
|
568
|
+
ledger[slug] = {
|
|
569
|
+
name: textOf(body.name) || slug,
|
|
570
|
+
version,
|
|
571
|
+
namespace,
|
|
572
|
+
installedAt: new Date().toISOString(),
|
|
573
|
+
iconUrl: textOf(body.iconUrl),
|
|
574
|
+
}
|
|
575
|
+
try {
|
|
576
|
+
await writeLedger(ledger)
|
|
577
|
+
} catch {
|
|
578
|
+
// 台账写不进去不影响技能本体。
|
|
579
|
+
}
|
|
580
|
+
sendJson(res, 200, { ok: true, slug, path: target })
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* 注册四条本机路由。
|
|
585
|
+
* @param ctx - Cordis 上下文。
|
|
586
|
+
*/
|
|
587
|
+
export function apply(ctx) {
|
|
588
|
+
ctx.effect(
|
|
589
|
+
() =>
|
|
590
|
+
ctx.webServer.register({
|
|
591
|
+
kind: 'exact',
|
|
592
|
+
path: CONTENT_ROUTE,
|
|
593
|
+
handler: async (req, res) => {
|
|
594
|
+
if (rejected(ctx, req, res)) return
|
|
595
|
+
if (req.method !== 'GET') {
|
|
596
|
+
methodNotAllowed(res, 'GET')
|
|
597
|
+
return
|
|
598
|
+
}
|
|
599
|
+
await handleContent(req, res)
|
|
600
|
+
},
|
|
601
|
+
}),
|
|
602
|
+
`skill-market: GET ${CONTENT_ROUTE}`,
|
|
603
|
+
)
|
|
604
|
+
|
|
605
|
+
ctx.effect(
|
|
606
|
+
() =>
|
|
607
|
+
ctx.webServer.register({
|
|
608
|
+
kind: 'exact',
|
|
609
|
+
path: SKILLS_ROUTE,
|
|
610
|
+
handler: async (req, res) => {
|
|
611
|
+
if (rejected(ctx, req, res)) return
|
|
612
|
+
if (req.method !== 'GET') {
|
|
613
|
+
methodNotAllowed(res, 'GET')
|
|
614
|
+
return
|
|
615
|
+
}
|
|
616
|
+
await handleSkills(req, res)
|
|
617
|
+
},
|
|
618
|
+
}),
|
|
619
|
+
`skill-market: GET ${SKILLS_ROUTE}`,
|
|
620
|
+
)
|
|
621
|
+
ctx.effect(
|
|
622
|
+
() =>
|
|
623
|
+
ctx.webServer.register({
|
|
624
|
+
kind: 'exact',
|
|
625
|
+
path: CATEGORIES_ROUTE,
|
|
626
|
+
handler: async (req, res) => {
|
|
627
|
+
if (rejected(ctx, req, res)) return
|
|
628
|
+
if (req.method !== 'GET') {
|
|
629
|
+
methodNotAllowed(res, 'GET')
|
|
630
|
+
return
|
|
631
|
+
}
|
|
632
|
+
await handleCategories(req, res)
|
|
633
|
+
},
|
|
634
|
+
}),
|
|
635
|
+
`skill-market: GET ${CATEGORIES_ROUTE}`,
|
|
636
|
+
)
|
|
637
|
+
ctx.effect(
|
|
638
|
+
() =>
|
|
639
|
+
ctx.webServer.register({
|
|
640
|
+
kind: 'exact',
|
|
641
|
+
path: INSTALLED_ROUTE,
|
|
642
|
+
handler: async (req, res) => {
|
|
643
|
+
if (rejected(ctx, req, res)) return
|
|
644
|
+
if (req.method !== 'GET') {
|
|
645
|
+
methodNotAllowed(res, 'GET')
|
|
646
|
+
return
|
|
647
|
+
}
|
|
648
|
+
await handleInstalled(req, res)
|
|
649
|
+
},
|
|
650
|
+
}),
|
|
651
|
+
`skill-market: GET ${INSTALLED_ROUTE}`,
|
|
652
|
+
)
|
|
653
|
+
ctx.effect(
|
|
654
|
+
() =>
|
|
655
|
+
ctx.webServer.register({
|
|
656
|
+
kind: 'exact',
|
|
657
|
+
path: INSTALL_ROUTE,
|
|
658
|
+
handler: async (req, res) => {
|
|
659
|
+
if (rejected(ctx, req, res)) return
|
|
660
|
+
if (req.method !== 'POST') {
|
|
661
|
+
methodNotAllowed(res, 'POST')
|
|
662
|
+
return
|
|
663
|
+
}
|
|
664
|
+
await handleInstall(ctx, req, res)
|
|
665
|
+
},
|
|
666
|
+
}),
|
|
667
|
+
`skill-market: POST ${INSTALL_ROUTE}`,
|
|
668
|
+
)
|
|
669
|
+
ctx.effect(
|
|
670
|
+
() =>
|
|
671
|
+
ctx.webServer.register({
|
|
672
|
+
kind: 'exact',
|
|
673
|
+
path: UNINSTALL_ROUTE,
|
|
674
|
+
handler: async (req, res) => {
|
|
675
|
+
if (rejected(ctx, req, res)) return
|
|
676
|
+
if (req.method !== 'POST') {
|
|
677
|
+
methodNotAllowed(res, 'POST')
|
|
678
|
+
return
|
|
679
|
+
}
|
|
680
|
+
await handleUninstall(req, res)
|
|
681
|
+
},
|
|
682
|
+
}),
|
|
683
|
+
`skill-market: POST ${UNINSTALL_ROUTE}`,
|
|
684
|
+
)
|
|
685
|
+
}
|