universal-plugin-hub 1.0.6 → 1.0.25
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/README.md +41 -5
- package/README.zh.md +41 -5
- package/assets/Add-plugin-source.png +0 -0
- package/assets/MCP.png +0 -0
- package/assets/Plugin-management.png +0 -0
- package/assets/Plugins-official.png +0 -0
- package/assets/Skills.png +0 -0
- package/assets/fluent-3d/balance_scale_3d.png +0 -0
- package/assets/fluent-3d/bar_chart_3d.png +0 -0
- package/assets/fluent-3d/books_3d.png +0 -0
- package/assets/fluent-3d/brain_3d.png +0 -0
- package/assets/fluent-3d/briefcase_3d.png +0 -0
- package/assets/fluent-3d/card_file_box_3d.png +0 -0
- package/assets/fluent-3d/chart_increasing_3d.png +0 -0
- package/assets/fluent-3d/clapper_board_3d.png +0 -0
- package/assets/fluent-3d/clipboard_3d.png +0 -0
- package/assets/fluent-3d/cloud_3d.png +0 -0
- package/assets/fluent-3d/compass_3d.png +0 -0
- package/assets/fluent-3d/control_knobs_3d.png +0 -0
- package/assets/fluent-3d/desktop_computer_3d.png +0 -0
- package/assets/fluent-3d/framed_picture_3d.png +0 -0
- package/assets/fluent-3d/gear_3d.png +0 -0
- package/assets/fluent-3d/globe_with_meridians_3d.png +0 -0
- package/assets/fluent-3d/graduation_cap_3d.png +0 -0
- package/assets/fluent-3d/handshake_3d.png +0 -0
- package/assets/fluent-3d/identification_card_3d.png +0 -0
- package/assets/fluent-3d/input_latin_letters_3d.png +0 -0
- package/assets/fluent-3d/lady_beetle_3d.png +0 -0
- package/assets/fluent-3d/laptop_3d.png +0 -0
- package/assets/fluent-3d/link_3d.png +0 -0
- package/assets/fluent-3d/locked_3d.png +0 -0
- package/assets/fluent-3d/magnifying_glass_tilted_left_3d.png +0 -0
- package/assets/fluent-3d/manifest.json +221 -0
- package/assets/fluent-3d/memo_3d.png +0 -0
- package/assets/fluent-3d/microscope_3d.png +0 -0
- package/assets/fluent-3d/money_bag_3d.png +0 -0
- package/assets/fluent-3d/musical_notes_3d.png +0 -0
- package/assets/fluent-3d/notebook_3d.png +0 -0
- package/assets/fluent-3d/open_book_3d.png +0 -0
- package/assets/fluent-3d/puzzle_piece_3d.png +0 -0
- package/assets/fluent-3d/red_question_mark_3d.png +0 -0
- package/assets/fluent-3d/robot_3d.png +0 -0
- package/assets/fluent-3d/shield_3d.png +0 -0
- package/assets/fluent-3d/shopping_bags_3d.png +0 -0
- package/assets/fluent-3d/sparkles_3d.png +0 -0
- package/assets/fluent-3d/speech_balloon_3d.png +0 -0
- package/assets/fluent-3d/spiral_calendar_3d.png +0 -0
- package/assets/fluent-3d/ticket_3d.png +0 -0
- package/assets/fluent-3d/triangular_ruler_3d.png +0 -0
- package/assets/fluent-3d/world_map_3d.png +0 -0
- package/assets/licenses/fluent-emoji.txt +21 -0
- package/client/client.js +910 -1240
- package/package.json +20 -4
- package/screenshots.json +7 -0
- package/src/icons.js +5 -1
- package/src/index.js +30 -2
- package/src/install.js +191 -37
- package/src/oauth-bridge.js +270 -0
- package/src/oauth-config.js +48 -0
- package/src/oauth-store.js +86 -0
- package/src/oauth.js +165 -0
- package/src/parser.js +25 -3
- package/src/routes.js +112 -10
- package/src/skills.js +365 -0
- package/assets/hero.png +0 -0
package/src/routes.js
CHANGED
|
@@ -15,17 +15,19 @@ import { getOrFetchIcon, readLocalIcon } from './icons.js'
|
|
|
15
15
|
import {
|
|
16
16
|
installPlugin, uninstallPlugin, togglePlugin, updatePlugin, installedDetails, isScanDirRegistered,
|
|
17
17
|
toggleConnector, isConnectorActive, verifyConnectorAuth, saveConnectorAuth,
|
|
18
|
-
fetchConnectorTools, setToolDisabled, isLspActive, readCordisPatch, unregisterConnector, getConnectorEntry,
|
|
18
|
+
fetchConnectorTools, setToolDisabled, isLspActive, readCordisPatch, unregisterConnector, getConnectorEntry, readMcpToolsState,
|
|
19
19
|
} from './install.js'
|
|
20
20
|
import { inspectLocalPlugin, importLocalPlugin, saveUploadedZip } from './local.js'
|
|
21
|
+
import { getOAuthVerification, cancelOAuthVerification, readSavedOAuthClient } from './oauth.js'
|
|
22
|
+
import { remoteConfigFromEntry } from './oauth-config.js'
|
|
21
23
|
|
|
22
24
|
const API_PREFIX = '/universal-plugin-hub/api'
|
|
23
25
|
|
|
24
|
-
export function mountRoutes(webServer) {
|
|
26
|
+
export function mountRoutes(webServer, skills = null) {
|
|
25
27
|
const r = webServer.register({
|
|
26
28
|
kind: 'prefix',
|
|
27
29
|
path: API_PREFIX,
|
|
28
|
-
handler: (req, res) => handle(req, res, API_PREFIX),
|
|
30
|
+
handler: (req, res) => handle(req, res, API_PREFIX, skills),
|
|
29
31
|
})
|
|
30
32
|
return () => {
|
|
31
33
|
try { if (typeof r === 'function') r() } catch {}
|
|
@@ -46,10 +48,13 @@ function userMcpConfig(name, body) {
|
|
|
46
48
|
env: body.env && typeof body.env === 'object' ? body.env : {},
|
|
47
49
|
headers: body.headers && typeof body.headers === 'object' ? body.headers : {},
|
|
48
50
|
oauth: body.oauth || 'none',
|
|
51
|
+
oauthClientId: body.oauthClientId || '',
|
|
52
|
+
oauthCallbackPort: body.oauthCallbackPort || null,
|
|
53
|
+
oauthScope: body.oauthScope || '',
|
|
49
54
|
}
|
|
50
55
|
}
|
|
51
56
|
|
|
52
|
-
async function handle(req, res, prefix = API_PREFIX) {
|
|
57
|
+
async function handle(req, res, prefix = API_PREFIX, skills = null) {
|
|
53
58
|
const url = new URL(req.url, 'http://localhost')
|
|
54
59
|
const path = url.pathname.slice(prefix.length).replace(/\/+$/, '') || '/'
|
|
55
60
|
const method = req.method ?? 'GET'
|
|
@@ -93,8 +98,20 @@ async function handle(req, res, prefix = API_PREFIX) {
|
|
|
93
98
|
if (method === 'GET' && path === '/state') {
|
|
94
99
|
const state = readState()
|
|
95
100
|
const details = installedDetails()
|
|
101
|
+
let sources = state.sources.map((source) => source.id === 'local' ? { ...source, pluginCount: new Set([...readMarketplace('local').map(p => p.name), ...details.filter(p => p.sourceId === 'local' && existsSync(installedDir(p.name))).map(p => p.name)]).size } : source)
|
|
102
|
+
if (skills && skills.entries().length) {
|
|
103
|
+
const skillSource = { id: 'skills-local', name: 'Skills', virtual: true }
|
|
104
|
+
const ordered = Array.isArray(state.tabOrder) ? state.tabOrder : []
|
|
105
|
+
if (ordered.includes(skillSource.id)) {
|
|
106
|
+
const order = new Map(ordered.map((id, index) => [id, index]))
|
|
107
|
+
sources = [...sources, skillSource].sort((a, b) => (order.get(a.id) ?? 1e9) - (order.get(b.id) ?? 1e9))
|
|
108
|
+
} else {
|
|
109
|
+
const anthropic = sources.findIndex(s => s.id === 'anthropic')
|
|
110
|
+
sources.splice(anthropic < 0 ? 0 : anthropic + 1, 0, skillSource)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
96
113
|
return sendJson(res, 200, {
|
|
97
|
-
sources
|
|
114
|
+
sources,
|
|
98
115
|
plugins: details.map((p) => ({
|
|
99
116
|
...p,
|
|
100
117
|
skillsEnabled: isScanDirRegistered(join(installedDir(p.name), 'skills')),
|
|
@@ -102,12 +119,38 @@ async function handle(req, res, prefix = API_PREFIX) {
|
|
|
102
119
|
})
|
|
103
120
|
}
|
|
104
121
|
|
|
122
|
+
if (path === '/skills' && method === 'GET' && skills) return sendJson(res, 200, { skills: await skills.list() })
|
|
123
|
+
if (path === '/skills/refresh' && method === 'POST' && skills) {
|
|
124
|
+
requireSameOrigin(req); skills.refresh()
|
|
125
|
+
return sendJson(res, 200, { skills: await skills.list() })
|
|
126
|
+
}
|
|
127
|
+
if (path === '/skills/toggle' && method === 'POST' && skills) {
|
|
128
|
+
requireSameOrigin(req)
|
|
129
|
+
const body = await readJsonBody(req)
|
|
130
|
+
if (typeof body.enabled !== 'boolean') throw new Error('无效的开关状态')
|
|
131
|
+
return sendJson(res, 200, await skills.toggle(body.id, body.enabled))
|
|
132
|
+
}
|
|
133
|
+
if (path === '/skills/detail' && method === 'GET' && skills) return sendJson(res, 200, { skill: skills.detail(url.searchParams.get('id'), false) })
|
|
134
|
+
if (path === '/skills/resource' && method === 'GET' && skills) return sendJson(res, 200, { content: skills.resource(url.searchParams.get('id'), url.searchParams.get('path')) })
|
|
135
|
+
if (path === '/skills/icon' && method === 'GET' && skills) {
|
|
136
|
+
try {
|
|
137
|
+
const item = skills.detail(url.searchParams.get('id'), false)
|
|
138
|
+
const { buffer, contentType } = readLocalIcon(item.directory, item.iconPath)
|
|
139
|
+
res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': 'public, max-age=3600', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox" })
|
|
140
|
+
return res.end(buffer)
|
|
141
|
+
} catch { return sendJson(res, 404, { error: 'Icon not found' }) }
|
|
142
|
+
}
|
|
143
|
+
|
|
105
144
|
// ── market listing / refresh ─────────────────────────────────────────
|
|
106
145
|
if (method === 'GET' && path === '/market') {
|
|
107
146
|
const rawSource = url.searchParams.get('sourceId') || url.searchParams.get('source') || 'anthropic'
|
|
108
147
|
const sourceId = safeSegment(rawSource, 'source id')
|
|
109
148
|
await ensureSourceCloned(sourceId, sourceUrlOf(sourceId))
|
|
110
|
-
|
|
149
|
+
let rows = readMarketplace(sourceId)
|
|
150
|
+
if (sourceId === 'local') {
|
|
151
|
+
const names = new Set(rows.map(r => r.name))
|
|
152
|
+
rows = [...rows, ...installedDetails().filter(p => p.sourceId === 'local' && existsSync(installedDir(p.name)) && !names.has(p.name)).map(p => ({ ...p, sourceMissing: true }))]
|
|
153
|
+
}
|
|
111
154
|
return sendJson(res, 200, { plugins: rows })
|
|
112
155
|
}
|
|
113
156
|
|
|
@@ -120,7 +163,12 @@ async function handle(req, res, prefix = API_PREFIX) {
|
|
|
120
163
|
await ensureSourceCloned(sourceId, sourceUrlOf(sourceId))
|
|
121
164
|
await pullSource(sourceId)
|
|
122
165
|
invalidateMarketplaceCache(sourceId)
|
|
123
|
-
|
|
166
|
+
let plugins = readMarketplace(sourceId)
|
|
167
|
+
if (sourceId === 'local') {
|
|
168
|
+
const names = new Set(plugins.map(p => p.name))
|
|
169
|
+
plugins = [...plugins, ...installedDetails().filter(p => p.sourceId === 'local' && existsSync(installedDir(p.name)) && !names.has(p.name)).map(p => ({ ...p, sourceMissing: true }))]
|
|
170
|
+
}
|
|
171
|
+
return sendJson(res, 200, { ok: true, plugins })
|
|
124
172
|
}
|
|
125
173
|
|
|
126
174
|
// ── sources ──────────────────────────────────────────────────────────
|
|
@@ -221,6 +269,11 @@ async function handle(req, res, prefix = API_PREFIX) {
|
|
|
221
269
|
const sourceIds = Array.isArray(body.sourceIds) ? body.sourceIds : []
|
|
222
270
|
if (sourceIds.length === 0) throw new Error('无效的插件源列表')
|
|
223
271
|
const state = readState()
|
|
272
|
+
const order = sourceIds.filter((id, index) => typeof id === 'string' && sourceIds.indexOf(id) === index)
|
|
273
|
+
if (!order.includes('skills-local') && state.tabOrder?.includes('skills-local')) {
|
|
274
|
+
order.splice(Math.min(state.tabOrder.indexOf('skills-local'), order.length), 0, 'skills-local')
|
|
275
|
+
}
|
|
276
|
+
state.tabOrder = order
|
|
224
277
|
const sourceMap = new Map(state.sources.map((s) => [s.id, s]))
|
|
225
278
|
const reordered = []
|
|
226
279
|
for (const id of sourceIds) {
|
|
@@ -285,9 +338,31 @@ async function handle(req, res, prefix = API_PREFIX) {
|
|
|
285
338
|
if (changed) writeState(state)
|
|
286
339
|
const mcps = state.userMcps
|
|
287
340
|
.filter((x) => x && x.name)
|
|
288
|
-
.map((x) =>
|
|
341
|
+
.map((x) => {
|
|
342
|
+
const entry = getConnectorEntry('user-mcp', x.name)
|
|
343
|
+
const remote = remoteConfigFromEntry(entry?.config) || readMcpToolsState()[`user-mcp::${x.name}`]?.savedOAuthRemoteConfig
|
|
344
|
+
const client = remote?.oauth === 'custom' ? readSavedOAuthClient('user-mcp', x.name, remote.url, remote.oauth) : null
|
|
345
|
+
return {
|
|
346
|
+
...x,
|
|
347
|
+
...(remote ? {
|
|
348
|
+
transport: 'http', url: remote.url, headers: remote.headers,
|
|
349
|
+
oauth: remote.oauth, oauthClientId: client?.clientId || remote.oauthClientId,
|
|
350
|
+
oauthHasClientSecret: client?.hasClientSecret || false,
|
|
351
|
+
oauthCallbackPort: remote.oauthCallbackPort || null, oauthScope: remote.oauthScope || '',
|
|
352
|
+
} : {}),
|
|
353
|
+
enabled: enabledIds.has('mcp-user-mcp-' + x.name),
|
|
354
|
+
}
|
|
355
|
+
})
|
|
289
356
|
return sendJson(res, 200, { ok: true, mcps })
|
|
290
357
|
}
|
|
358
|
+
if (path === '/mcps/oauth-status') {
|
|
359
|
+
requireSameOrigin(req)
|
|
360
|
+
if (method !== 'GET' && method !== 'POST') return sendJson(res, 405, { error: 'method not allowed' })
|
|
361
|
+
const sessionId = String(method === 'GET' ? url.searchParams.get('sessionId') : (await readJsonBody(req)).sessionId || '')
|
|
362
|
+
const result = getOAuthVerification(sessionId, { pluginName: 'user-mcp' })
|
|
363
|
+
if (method === 'POST') return sendJson(res, 200, { ok: true, cancelled: result.found ? cancelOAuthVerification(sessionId, '已取消授权', { pluginName: 'user-mcp' }) : false })
|
|
364
|
+
return sendJson(res, 200, result)
|
|
365
|
+
}
|
|
291
366
|
if (method === 'POST' && path === '/mcps/verify') {
|
|
292
367
|
requireSameOrigin(req)
|
|
293
368
|
const body = await readJsonBody(req)
|
|
@@ -363,11 +438,22 @@ async function handle(req, res, prefix = API_PREFIX) {
|
|
|
363
438
|
}
|
|
364
439
|
|
|
365
440
|
// ── connector routes (must precede catch-all /plugins/ routes) ────────
|
|
441
|
+
if ((method === 'GET' || method === 'POST') && path.startsWith('/plugins/') && path.includes('/connectors/') && path.endsWith('/oauth-status')) {
|
|
442
|
+
requireSameOrigin(req)
|
|
443
|
+
const parts = path.slice('/plugins/'.length).split('/')
|
|
444
|
+
const pluginName = safeSegment(parts[0], 'plugin name')
|
|
445
|
+
const connectorName = safeSegment(parts[2], 'connector name')
|
|
446
|
+
const sessionId = String(method === 'GET' ? url.searchParams.get('sessionId') : (await readJsonBody(req)).sessionId || '')
|
|
447
|
+
const result = getOAuthVerification(sessionId, { pluginName, connectorName })
|
|
448
|
+
if (method === 'POST') return sendJson(res, 200, { ok: true, cancelled: result.found ? cancelOAuthVerification(sessionId, '已取消授权', { pluginName, connectorName }) : false })
|
|
449
|
+
return sendJson(res, 200, result)
|
|
450
|
+
}
|
|
451
|
+
|
|
366
452
|
if (method === 'GET' && path.startsWith('/plugins/') && path.includes('/connectors/') && path.endsWith('/tools')) {
|
|
367
453
|
const parts = path.slice('/plugins/'.length).split('/')
|
|
368
454
|
const pluginName = safeSegment(parts[0], 'plugin name')
|
|
369
455
|
const connectorName = safeSegment(parts[2], 'connector name')
|
|
370
|
-
const result = await fetchConnectorTools(pluginName, connectorName)
|
|
456
|
+
const result = await fetchConnectorTools(pluginName, connectorName, url.searchParams.get('fresh') === '1')
|
|
371
457
|
return sendJson(res, 200, result)
|
|
372
458
|
}
|
|
373
459
|
|
|
@@ -432,16 +518,32 @@ async function handle(req, res, prefix = API_PREFIX) {
|
|
|
432
518
|
row = readMarketplace(sourceId).find((r) => r.name === pluginName) || row
|
|
433
519
|
detail = pluginDetail(sourceId, pluginName, row.source, row)
|
|
434
520
|
}
|
|
521
|
+
// One pass over the installed tree per request: `installedDetails()` re-reads
|
|
522
|
+
// every connector, skill and LSP entry for every plugin, so it must not run
|
|
523
|
+
// twice in the same handler.
|
|
524
|
+
let installed = null
|
|
525
|
+
const findInstalled = () => {
|
|
526
|
+
if (!installed) installed = installedDetails().find((p) => p.name === pluginName)
|
|
527
|
+
return installed
|
|
528
|
+
}
|
|
435
529
|
if (!detail) {
|
|
436
|
-
const inst =
|
|
530
|
+
const inst = findInstalled()
|
|
437
531
|
if (inst) {
|
|
438
532
|
detail = inst
|
|
439
533
|
if (!row) row = inst
|
|
440
534
|
}
|
|
441
535
|
}
|
|
442
536
|
if (detail && Array.isArray(detail.connectors)) {
|
|
537
|
+
// `pluginDetail` reads the marketplace copy, which knows nothing about
|
|
538
|
+
// what the user saved here (OAuth mode, client id, callback port, the
|
|
539
|
+
// URL they edited). Take the installed row's entry whenever one exists,
|
|
540
|
+
// so opening a connector's settings reflects the saved configuration
|
|
541
|
+
// instead of silently reverting it to `None` and the manifest URL.
|
|
542
|
+
const installedConnectors = new Map(((findInstalled()?.connectors) || []).map((c) => [c.name, c]))
|
|
443
543
|
detail.connectors = detail.connectors.map((c) => ({
|
|
444
544
|
...c,
|
|
545
|
+
...(installedConnectors.get(c.name) || {}),
|
|
546
|
+
name: c.name,
|
|
445
547
|
connected: isConnectorActive(pluginName, c.name),
|
|
446
548
|
}))
|
|
447
549
|
}
|
package/src/skills.js
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto'
|
|
2
|
+
import { existsSync, readdirSync, readFileSync, realpathSync, statSync, watch } from 'node:fs'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
5
|
+
import { load as parseYaml } from 'js-yaml'
|
|
6
|
+
import { readState, writeState } from './store.js'
|
|
7
|
+
import { formatDisplayName } from './parser.js'
|
|
8
|
+
|
|
9
|
+
const PROVIDER = 'universal-plugin-hub-skills'
|
|
10
|
+
const EXCLUDED = new Set(['.git', 'node_modules', '__pycache__'])
|
|
11
|
+
const MAX_FILE = 2 * 1024 * 1024
|
|
12
|
+
const NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
13
|
+
|
|
14
|
+
function canonical(path) {
|
|
15
|
+
try { return realpathSync.native(path) } catch { return resolve(path) }
|
|
16
|
+
}
|
|
17
|
+
function samePath(a, b) {
|
|
18
|
+
if (!a || !b) return false
|
|
19
|
+
const left = canonical(a), right = canonical(b)
|
|
20
|
+
return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right
|
|
21
|
+
}
|
|
22
|
+
function skillId(file) {
|
|
23
|
+
const path = canonical(file)
|
|
24
|
+
return createHash('sha256').update(process.platform === 'win32' ? path.toLowerCase() : path).digest('hex')
|
|
25
|
+
}
|
|
26
|
+
function policyValue(value, fallback) {
|
|
27
|
+
if (value === undefined) return fallback
|
|
28
|
+
if (typeof value === 'boolean') return value
|
|
29
|
+
const normalized = String(value).toLowerCase()
|
|
30
|
+
if (['true', 'yes', 'on', '1'].includes(normalized)) return true
|
|
31
|
+
if (['false', 'no', 'off', '0'].includes(normalized)) return false
|
|
32
|
+
throw new Error('调用策略必须是布尔值')
|
|
33
|
+
}
|
|
34
|
+
function readSkill(file, root, isNested) {
|
|
35
|
+
let raw = '', meta = {}, content = '', error = ''
|
|
36
|
+
let invocation = { modelInvocable: true, userInvocable: true }
|
|
37
|
+
try {
|
|
38
|
+
if (statSync(file).size > MAX_FILE) throw new Error('SKILL.md 文件过大')
|
|
39
|
+
raw = readFileSync(file, 'utf8').replace(/^\uFEFF/, '')
|
|
40
|
+
const match = raw.match(/^---\s*\r?\n([\s\S]*?)\r?\n---\s*(?:\r?\n|$)/)
|
|
41
|
+
if (!match) throw new Error('缺少完整的 YAML 元数据')
|
|
42
|
+
meta = parseYaml(match[1]) || {}
|
|
43
|
+
if (typeof meta !== 'object' || Array.isArray(meta)) throw new Error('YAML 元数据必须是对象')
|
|
44
|
+
content = raw.slice(match[0].length)
|
|
45
|
+
if (typeof meta.name !== 'string' || !NAME.test(meta.name)) throw new Error('名称不符合 DSH 的小写连字符格式')
|
|
46
|
+
if (typeof meta.description !== 'string' || !meta.description.trim()) throw new Error('缺少 description')
|
|
47
|
+
invocation = { modelInvocable: !policyValue(meta['disable-model-invocation'], false), userInvocable: policyValue(meta['user-invocable'], true) }
|
|
48
|
+
} catch (e) {
|
|
49
|
+
error = String(e.message).split('\n')[0]
|
|
50
|
+
if (!meta || typeof meta !== 'object' || Array.isArray(meta)) meta = {}
|
|
51
|
+
if (!meta.name) meta.name = raw.match(/^name:\s*([^\r\n]+)/m)?.[1]?.trim().replace(/^['"]|['"]$/g, '')
|
|
52
|
+
if (!meta.description) meta.description = raw.match(/^description:\s*([^\r\n]+)/m)?.[1]?.trim().replace(/^['"]|['"]$/g, '') || raw.match(/^#\s+(.+)/m)?.[1] || ''
|
|
53
|
+
}
|
|
54
|
+
const name = typeof meta.name === 'string' && meta.name.trim() ? meta.name : /^skill\.md$/i.test(basename(file)) ? basename(dirname(file)) : basename(file).replace(/\.md$/i, '')
|
|
55
|
+
const icons = [meta.icon, meta.logo, 'assets/icon.svg', 'assets/logo.svg', 'assets/icon.png', 'assets/logo.png', 'icon.svg', 'icon.png', 'logo.png']
|
|
56
|
+
const iconPath = icons.find(path => typeof path === 'string' && !path.includes('..') && existsSync(join(dirname(file), path)))
|
|
57
|
+
return {
|
|
58
|
+
id: skillId(file), name, displayName: typeof meta.displayName === 'string' ? meta.displayName : formatDisplayName(name), description: typeof meta.description === 'string' ? meta.description : '',
|
|
59
|
+
path: file, directory: dirname(file), relativePath: relative(root, file), nested: isNested,
|
|
60
|
+
error, content: content || raw, metadata: meta, iconPath,
|
|
61
|
+
invocation,
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function discoverSkills(root = join(process.env.DSH_AGENTS_HOME || join(homedir(), '.agents'), 'skills')) {
|
|
66
|
+
const entries = [], seen = new Set()
|
|
67
|
+
let children
|
|
68
|
+
try { children = readdirSync(root, { withFileTypes: true }) } catch { return entries }
|
|
69
|
+
// Match DSH's native boundary: <root>/<name>/SKILL.md or <root>/<name>.md.
|
|
70
|
+
for (const entry of children) {
|
|
71
|
+
if (EXCLUDED.has(entry.name)) continue
|
|
72
|
+
const path = join(root, entry.name)
|
|
73
|
+
try {
|
|
74
|
+
const stat = entry.isSymbolicLink() ? statSync(path) : entry
|
|
75
|
+
let file
|
|
76
|
+
if (stat.isDirectory()) {
|
|
77
|
+
const manifest = readdirSync(path).find(name => /^skill\.md$/i.test(name) && statSync(join(path, name)).isFile())
|
|
78
|
+
if (manifest) file = join(path, manifest)
|
|
79
|
+
} else if (stat.isFile() && /\.md$/i.test(entry.name)) file = path
|
|
80
|
+
if (!file) continue
|
|
81
|
+
const id = skillId(file)
|
|
82
|
+
if (!seen.has(id)) { seen.add(id); entries.push(readSkill(file, root, false)) }
|
|
83
|
+
} catch {}
|
|
84
|
+
}
|
|
85
|
+
// Identical direct entries share one card and one provider candidate.
|
|
86
|
+
entries.sort((a, b) => a.path.localeCompare(b.path))
|
|
87
|
+
const identical = new Map(), merged = []
|
|
88
|
+
for (const item of entries) {
|
|
89
|
+
const key = JSON.stringify([item.name, item.metadata, item.content.replace(/\r\n/g, '\n')])
|
|
90
|
+
const existing = !item.error && identical.get(key)
|
|
91
|
+
const location = { id: item.id, path: item.path, relativePath: item.relativePath }
|
|
92
|
+
if (existing) existing.locations.push(location)
|
|
93
|
+
else { item.locations = [location]; merged.push(item); if (!item.error) identical.set(key, item) }
|
|
94
|
+
}
|
|
95
|
+
const counts = new Map()
|
|
96
|
+
for (const item of merged) counts.set(item.name, (counts.get(item.name) || 0) + 1)
|
|
97
|
+
for (const item of merged) item.duplicate = counts.get(item.name) > 1
|
|
98
|
+
return merged.sort((a, b) => a.name.localeCompare(b.name))
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function createSkillsManager(root) {
|
|
102
|
+
root ||= join(process.env.DSH_AGENTS_HOME || join(homedir(), '.agents'), 'skills')
|
|
103
|
+
let cache = null, registry = null, invalidate = null, catalogChanged = null, watcher = null, watchTimer = null, toggling = false
|
|
104
|
+
const agentViews = new Map()
|
|
105
|
+
const scopePolicies = new Map(), presetProviders = new Map()
|
|
106
|
+
let createPolicyScope = null
|
|
107
|
+
function invalidateAll() {
|
|
108
|
+
invalidate?.()
|
|
109
|
+
for (const preset of presetProviders.values()) preset.invalidate?.()
|
|
110
|
+
}
|
|
111
|
+
function ensureScope(scope, service = registry) {
|
|
112
|
+
if (!scope || !createPolicyScope) return
|
|
113
|
+
const existing = scopePolicies.get(scope)
|
|
114
|
+
if (existing?.service === service) return existing.ready
|
|
115
|
+
if (!existing) {
|
|
116
|
+
const off = disabled()
|
|
117
|
+
if (!scan().some(item => !item.error && isDisabled(item, off))) return
|
|
118
|
+
}
|
|
119
|
+
existing?.dispose()
|
|
120
|
+
scopePolicies.delete(scope)
|
|
121
|
+
let owner
|
|
122
|
+
try { owner = createPolicyScope(service.ctx, scope) }
|
|
123
|
+
catch { return }
|
|
124
|
+
let settle
|
|
125
|
+
const pending = new Promise(resolve => { settle = resolve })
|
|
126
|
+
scopePolicies.set(scope, { service, ready: pending, dispose: () => { settle(); return owner.dispose() } })
|
|
127
|
+
// Never reject: failing to register only means this one scope gets no
|
|
128
|
+
// disabled-skill overlay. A rejected promise would be cached here and
|
|
129
|
+
// re-thrown on every later read of this scope, and because catalogs()
|
|
130
|
+
// reads through Promise.all it would blank the entire skills list rather
|
|
131
|
+
// than just this scope.
|
|
132
|
+
owner.ctx.inject(['skills'], target => {
|
|
133
|
+
try { target.skills.registerProvider(() => disabledProvider()) }
|
|
134
|
+
catch { scopePolicies.delete(scope); try { owner.dispose() } catch {} }
|
|
135
|
+
finally { settle() }
|
|
136
|
+
})
|
|
137
|
+
// Cold catalog leases can mint scopes without live agents. Bound their
|
|
138
|
+
// policy lifetimes — but only those: evicting a live agent's policy would
|
|
139
|
+
// quietly report its switched-off skills as enabled again.
|
|
140
|
+
if (scopePolicies.size > 128) {
|
|
141
|
+
for (const key of scopePolicies.keys()) {
|
|
142
|
+
if (agentViews.has(key)) continue
|
|
143
|
+
scopePolicies.get(key).dispose(); scopePolicies.delete(key); break
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
return pending
|
|
147
|
+
}
|
|
148
|
+
const scan = (force = false) => {
|
|
149
|
+
if (force || !cache) cache = discoverSkills(root)
|
|
150
|
+
return cache
|
|
151
|
+
}
|
|
152
|
+
const disabled = () => readState().disabledLocalSkills || {}
|
|
153
|
+
const isDisabled = (item, off = disabled()) => item.locations.some(location => off[location.id])
|
|
154
|
+
const matches = (item, current) => current && item.locations.some(location => samePath(current.path, location.path))
|
|
155
|
+
const entries = () => {
|
|
156
|
+
const off = disabled()
|
|
157
|
+
return scan().map(item => {
|
|
158
|
+
const { content, metadata, ...summary } = item
|
|
159
|
+
const icon = item.iconPath ? `/universal-plugin-hub/api/skills/icon?id=${encodeURIComponent(item.id)}` : null
|
|
160
|
+
return { ...summary, sourceId: 'skills-local', enabled: !isDisabled(item, off), available: !!registry, icons: { light: icon ? [icon] : [], dark: icon ? [icon] : [] } }
|
|
161
|
+
})
|
|
162
|
+
}
|
|
163
|
+
function candidate(item, isDisabled) {
|
|
164
|
+
return {
|
|
165
|
+
name: item.name, description: item.description, invocation: isDisabled ? { modelInvocable: false, userInvocable: false } : item.invocation,
|
|
166
|
+
// The same ~/.agents file can be discovered as a project root (rank 200).
|
|
167
|
+
// An explicit off choice must precede every native filesystem rank.
|
|
168
|
+
provider: PROVIDER, source: 'user-agents', rank: isDisabled ? 99 : 501,
|
|
169
|
+
path: item.path, resourceBase: { kind: 'directory', path: item.directory }, locator: item.id,
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const provider = {
|
|
173
|
+
name: PROVIDER,
|
|
174
|
+
async list(options = {}) {
|
|
175
|
+
await ensureScope(options.scope)
|
|
176
|
+
const off = disabled()
|
|
177
|
+
// The native filesystem provider (rank 500) wins whenever it discovers
|
|
178
|
+
// the skill. Profiles that omit that user root still get a fallback.
|
|
179
|
+
return scan().filter(item => !item.error).map(item => candidate(item, isDisabled(item, off)))
|
|
180
|
+
},
|
|
181
|
+
async get(entry) {
|
|
182
|
+
const item = scan().find(s => s.id === entry.locator)
|
|
183
|
+
if (!item || item.error) return undefined
|
|
184
|
+
const fresh = readSkill(item.path, root, item.nested)
|
|
185
|
+
if (fresh.error || fresh.name !== item.name) return undefined
|
|
186
|
+
const { rank, locator, ...summary } = candidate(fresh, isDisabled(item))
|
|
187
|
+
return { ...summary, content: fresh.content, metadata: fresh.metadata.metadata }
|
|
188
|
+
},
|
|
189
|
+
}
|
|
190
|
+
function disabledProvider() {
|
|
191
|
+
return { ...provider, async list() {
|
|
192
|
+
const off = disabled()
|
|
193
|
+
return scan().filter(item => !item.error && isDisabled(item, off)).map(item => candidate(item, true))
|
|
194
|
+
} }
|
|
195
|
+
}
|
|
196
|
+
function refresh() { cache = null; invalidateAll(); catalogChanged?.(); return entries() }
|
|
197
|
+
async function catalogs() {
|
|
198
|
+
return Promise.all([registry.list(), ...[...agentViews.values()].map(view => view.registry().list(view.lookup()))])
|
|
199
|
+
}
|
|
200
|
+
async function status(item) {
|
|
201
|
+
if (!registry) return { available: false, message: 'DSH Skills 服务不可用' }
|
|
202
|
+
try {
|
|
203
|
+
// A session that never surfaced this skill has nothing to enforce, and
|
|
204
|
+
// must not veto the switch: requiring every agent catalogue to list it
|
|
205
|
+
// would revert every toggle as soon as one preset scopes it away.
|
|
206
|
+
const present = (await catalogs()).map(list => list.find(s => s.name === item.name)).filter(Boolean)
|
|
207
|
+
if (!present.length) return { available: false, message: '当前管理视图未查到此 Skill,无法确认调用状态' }
|
|
208
|
+
const foreign = present.find(s => !matches(item, s))
|
|
209
|
+
if (foreign) return { available: false, message: `/${item.name} 当前使用另一份 Skill:${foreign.path || foreign.provider}` }
|
|
210
|
+
return { available: true, invocations: present.map(s => s.invocation) }
|
|
211
|
+
} catch (e) { return { available: false, message: e.message } }
|
|
212
|
+
}
|
|
213
|
+
async function list() {
|
|
214
|
+
const list = entries()
|
|
215
|
+
if (!registry) return list.map(x => ({ ...x, enabled: null, statusMessage: x.error || 'DSH Skills 服务不可用' }))
|
|
216
|
+
let current
|
|
217
|
+
try { current = await catalogs() } catch { return list.map(x => ({ ...x, enabled: null, available: false, statusMessage: x.error || '无法读取 DSH Skills 状态' })) }
|
|
218
|
+
const catalogsByName = current.map(rows => new Map(rows.map(s => [s.name, s])))
|
|
219
|
+
return list.map(item => {
|
|
220
|
+
// Only the catalogues that actually surface this skill have a say, the
|
|
221
|
+
// same rule status() uses, so a preset that scopes a skill away does not
|
|
222
|
+
// show it as unavailable or reverted.
|
|
223
|
+
const found = catalogsByName.map(rows => rows.get(item.name)).filter(Boolean)
|
|
224
|
+
const foreign = found.find(s => !matches(item, s))
|
|
225
|
+
const matching = found.length > 0 && !foreign
|
|
226
|
+
const desired = item.enabled ? item.invocation : { modelInvocable: false, userInvocable: false }
|
|
227
|
+
const applied = matching && found.every(s => s.invocation.modelInvocable === desired.modelInvocable && s.invocation.userInvocable === desired.userInvocable)
|
|
228
|
+
const actualInvocation = matching ? { modelInvocable: found.some(s => s.invocation.modelInvocable), userInvocable: found.some(s => s.invocation.userInvocable) } : null
|
|
229
|
+
return { ...item, enabled: matching ? applied ? item.enabled : actualInvocation.modelInvocable || actualInvocation.userInvocable : null,
|
|
230
|
+
available: matching && !item.error, actualInvocation, verifiedViews: matching ? found.length : 0, activePath: matching ? found[0].path : null,
|
|
231
|
+
statusMessage: item.error || (!matching && !foreign ? '当前管理视图未查到此 Skill,无法确认调用状态' : foreign ? `/${item.name} 当前使用另一份 Skill:${foreign.path || foreign.provider}` : !applied ? '开关状态尚未在所有会话中生效,请重新切换' : '') }
|
|
232
|
+
})
|
|
233
|
+
}
|
|
234
|
+
async function toggle(id, enabled) {
|
|
235
|
+
if (toggling) throw new Error('正在更新另一个 Skill,请稍后重试')
|
|
236
|
+
toggling = true
|
|
237
|
+
try {
|
|
238
|
+
const item = scan().find(s => s.id === id)
|
|
239
|
+
if (!item) throw new Error('Skill 不存在,请刷新列表')
|
|
240
|
+
if (item.error) throw new Error(item.error)
|
|
241
|
+
const before = await status(item)
|
|
242
|
+
if (!before.available) throw new Error(before.message)
|
|
243
|
+
const state = readState(), previous = { ...(state.disabledLocalSkills || {}) }
|
|
244
|
+
state.disabledLocalSkills = { ...previous }
|
|
245
|
+
for (const location of item.locations) {
|
|
246
|
+
if (enabled) delete state.disabledLocalSkills[location.id]
|
|
247
|
+
else state.disabledLocalSkills[location.id] = true
|
|
248
|
+
}
|
|
249
|
+
writeState(state); invalidateAll()
|
|
250
|
+
const after = await status(item)
|
|
251
|
+
const desired = enabled ? item.invocation : { modelInvocable: false, userInvocable: false }
|
|
252
|
+
if (!after.available || !after.invocations.every(policy => policy.modelInvocable === desired.modelInvocable && policy.userInvocable === desired.userInvocable)) {
|
|
253
|
+
state.disabledLocalSkills = previous; writeState(state); invalidateAll()
|
|
254
|
+
catalogChanged?.()
|
|
255
|
+
throw new Error(after.message || 'DSH 未确认开关状态,已恢复原状态')
|
|
256
|
+
}
|
|
257
|
+
catalogChanged?.()
|
|
258
|
+
return { ok: true, skills: await list() }
|
|
259
|
+
} finally { toggling = false }
|
|
260
|
+
}
|
|
261
|
+
function detail(id, includeFiles = true) {
|
|
262
|
+
const item = scan().find(s => s.id === id)
|
|
263
|
+
if (!item) throw new Error('Skill 不存在,请刷新列表')
|
|
264
|
+
const files = []
|
|
265
|
+
function walk(dir, depth) {
|
|
266
|
+
if (depth > 8 || files.length >= 500) return
|
|
267
|
+
let children; try { children = readdirSync(dir, { withFileTypes: true }) } catch { return }
|
|
268
|
+
for (const entry of children) {
|
|
269
|
+
if (entry.name === '.git' || entry.name === 'node_modules' || entry.isSymbolicLink()) continue
|
|
270
|
+
const path = join(dir, entry.name)
|
|
271
|
+
if (entry.isDirectory()) walk(path, depth + 1)
|
|
272
|
+
else if (entry.isFile() && path !== item.path) files.push({ path: relative(item.directory, path).split(sep).join('/'), category: relative(item.directory, path).split(sep)[0] })
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
if (includeFiles) walk(item.directory, 0)
|
|
276
|
+
return { ...item, enabled: !isDisabled(item), files }
|
|
277
|
+
}
|
|
278
|
+
function resource(id, name) {
|
|
279
|
+
const item = scan().find(s => s.id === id)
|
|
280
|
+
if (!item) throw new Error('Skill 不存在')
|
|
281
|
+
const file = resolve(item.directory, String(name || ''))
|
|
282
|
+
const base = canonical(item.directory), real = canonical(file), rel = relative(base, real)
|
|
283
|
+
if (!rel || isAbsolute(rel) || rel === '..' || rel.startsWith(`..${sep}`) || resolve(base, rel) !== real) throw new Error('无效的资源路径')
|
|
284
|
+
if (!existsSync(file) || !statSync(file).isFile() || statSync(file).size > MAX_FILE) throw new Error('资源不存在或文件过大')
|
|
285
|
+
const data = readFileSync(file)
|
|
286
|
+
if (data.includes(0)) throw new Error('该资源不是文本文件')
|
|
287
|
+
return data.toString('utf8')
|
|
288
|
+
}
|
|
289
|
+
function attach(service, onCatalogChanged = null) {
|
|
290
|
+
registry = service
|
|
291
|
+
catalogChanged = onCatalogChanged
|
|
292
|
+
const dispose = service.registerProvider(control => { invalidate = control.invalidate; return provider })
|
|
293
|
+
try {
|
|
294
|
+
watcher = watch(root, { recursive: true }, (event, filename) => {
|
|
295
|
+
if (filename) {
|
|
296
|
+
const parts = String(filename).split(/[\\/]/)
|
|
297
|
+
if (parts.length > 2 || (parts.length === 2 && !/^skill\.md$/i.test(parts[1]))) return
|
|
298
|
+
if (event === 'change' && parts.length === 1 && !/\.md$/i.test(parts[0])) return
|
|
299
|
+
}
|
|
300
|
+
clearTimeout(watchTimer)
|
|
301
|
+
watchTimer = setTimeout(() => { cache = null; invalidateAll(); catalogChanged?.() }, 150)
|
|
302
|
+
watchTimer.unref?.()
|
|
303
|
+
})
|
|
304
|
+
watcher.on('error', () => {})
|
|
305
|
+
} catch {}
|
|
306
|
+
return () => { clearTimeout(watchTimer); watcher?.close(); watcher = null; registry = null; invalidate = null; catalogChanged = null; dispose() }
|
|
307
|
+
}
|
|
308
|
+
function attachAgents(ctx, createScope = null) {
|
|
309
|
+
createPolicyScope = createScope
|
|
310
|
+
// Every per-agent registration is best effort: one agent whose context
|
|
311
|
+
// lacks a skills service (or already holds this provider name) must not
|
|
312
|
+
// abort the loop and leave the remaining agents unbound.
|
|
313
|
+
function guard(what, run) {
|
|
314
|
+
try { return run() } catch (error) { ctx.logger?.warn?.(`[universal-plugin-hub] ${what} skipped: ${error.message}`); return null }
|
|
315
|
+
}
|
|
316
|
+
const bind = (agent) => {
|
|
317
|
+
if (agentViews.has(agent)) return
|
|
318
|
+
// A preset's filesystem provider shadows the global layer regardless of
|
|
319
|
+
// rank. Explicit off choices must also live in the exact agent scope.
|
|
320
|
+
// Enabled skills continue to resolve through their native providers.
|
|
321
|
+
const serviceFor = () => ctx.get?.('agentPresets')?.serviceFor(agent, 'skills') ?? registry
|
|
322
|
+
const service = serviceFor()
|
|
323
|
+
if (service !== registry && !presetProviders.has(service)) {
|
|
324
|
+
let invalidatePreset
|
|
325
|
+
const dispose = guard('preset provider', () => service.registerProvider(control => { invalidatePreset = control.invalidate; return { ...disabledProvider(), async list(options = {}) {
|
|
326
|
+
await ensureScope(options.scope, service)
|
|
327
|
+
return disabledProvider().list(options)
|
|
328
|
+
} } }))
|
|
329
|
+
// A provider that failed to register has no invalidation hook, so it
|
|
330
|
+
// must not be tracked: doing so would hand out a users count for a
|
|
331
|
+
// registration that does not exist.
|
|
332
|
+
if (dispose) presetProviders.set(service, { dispose, invalidate: invalidatePreset, users: 0 })
|
|
333
|
+
}
|
|
334
|
+
if (service !== registry && presetProviders.has(service)) presetProviders.get(service).users++
|
|
335
|
+
const dispose = (createScope ? (() => { const policy = scopePolicies.get(agent); scopePolicies.delete(agent); return policy?.dispose() })
|
|
336
|
+
: guard('agent provider', () => agent.ctx.skills.registerProvider(() => disabledProvider()))) || (() => {})
|
|
337
|
+
agentViews.set(agent, { dispose: () => {
|
|
338
|
+
const pending = dispose()
|
|
339
|
+
const preset = presetProviders.get(service)
|
|
340
|
+
if (preset && --preset.users === 0) { preset.dispose(); presetProviders.delete(service) }
|
|
341
|
+
return pending
|
|
342
|
+
}, registry: serviceFor, lookup: () => ({ scope: agent, cwd: ctx.get?.('workingDirectory')?.get(agent.session) ?? agent.session?.header?.cwd }) })
|
|
343
|
+
}
|
|
344
|
+
const unbind = (agent) => { const view = agentViews.get(agent); agentViews.delete(agent); return view?.dispose() }
|
|
345
|
+
const offCreated = ctx.on('agent/created', ({ agent }) => bind(agent))
|
|
346
|
+
const offDisposed = ctx.on('agent/disposed', ({ agent }) => unbind(agent))
|
|
347
|
+
const offPreset = ctx.on('agent-preset/selected', async id => {
|
|
348
|
+
const agent = ctx.agents.get(id)
|
|
349
|
+
if (agent) { await unbind(agent); bind(agent) }
|
|
350
|
+
})
|
|
351
|
+
for (const agent of ctx.agents.list()) bind(agent)
|
|
352
|
+
invalidateAll()
|
|
353
|
+
catalogChanged?.()
|
|
354
|
+
return () => {
|
|
355
|
+
offCreated(); offDisposed(); offPreset()
|
|
356
|
+
const pending = [...agentViews.keys()].map(unbind)
|
|
357
|
+
for (const policy of scopePolicies.values()) pending.push(policy.dispose())
|
|
358
|
+
scopePolicies.clear(); createPolicyScope = null
|
|
359
|
+
for (const { dispose } of presetProviders.values()) dispose()
|
|
360
|
+
presetProviders.clear()
|
|
361
|
+
return Promise.all(pending)
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return { attach, attachAgents, entries, list, toggle, detail, resource, refresh }
|
|
365
|
+
}
|
package/assets/hero.png
DELETED
|
Binary file
|