universal-plugin-hub 1.0.30 → 1.0.45

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/routes.js CHANGED
@@ -15,19 +15,21 @@ 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, readMcpToolsState,
18
+ fetchConnectorTools, setToolDisabled, isLspActive, readCordisPatch, unregisterConnector, removeUserMcp, renameUserMcp, getConnectorEntry, getConnectorId, readMcpToolsState, userMcpConfig,
19
19
  } from './install.js'
20
- import { inspectLocalPlugin, importLocalPlugin, saveUploadedZip } from './local.js'
20
+ import { inspectLocalPlugin, importLocalPlugin, importLocalSkills, importLocalMarketplace, saveUploadedZip } from './local.js'
21
+ import { uninstallUploadedSkill, uploadedSkillRecord } from './skill-uploads.js'
21
22
  import { getOAuthVerification, cancelOAuthVerification, readSavedOAuthClient } from './oauth.js'
22
23
  import { remoteConfigFromEntry } from './oauth-config.js'
24
+ import { scheduledResult } from './runtime.js'
23
25
 
24
26
  const API_PREFIX = '/universal-plugin-hub/api'
25
27
 
26
- export function mountRoutes(webServer, skills = null) {
28
+ export function mountRoutes(webServer, skills = null, applyProfile = null) {
27
29
  const r = webServer.register({
28
30
  kind: 'prefix',
29
31
  path: API_PREFIX,
30
- handler: (req, res) => handle(req, res, API_PREFIX, skills),
32
+ handler: (req, res) => handle(req, res, API_PREFIX, skills, applyProfile),
31
33
  })
32
34
  return () => {
33
35
  try { if (typeof r === 'function') r() } catch {}
@@ -38,23 +40,8 @@ function normalizeMcpName(value) {
38
40
  return String(value || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[.-]+|-+$/g, '') || 'mcp'
39
41
  }
40
42
 
41
- function userMcpConfig(name, body) {
42
- return {
43
- name,
44
- transport: body.transport === 'http' ? 'http' : 'stdio',
45
- url: body.url || null,
46
- command: body.command || null,
47
- args: Array.isArray(body.args) ? body.args : [],
48
- env: body.env && typeof body.env === 'object' ? body.env : {},
49
- headers: body.headers && typeof body.headers === 'object' ? body.headers : {},
50
- oauth: body.oauth || 'none',
51
- oauthClientId: body.oauthClientId || '',
52
- oauthCallbackPort: body.oauthCallbackPort || null,
53
- oauthScope: body.oauthScope || '',
54
- }
55
- }
56
43
 
57
- async function handle(req, res, prefix = API_PREFIX, skills = null) {
44
+ async function handle(req, res, prefix = API_PREFIX, skills = null, applyProfile = null) {
58
45
  const url = new URL(req.url, 'http://localhost')
59
46
  const path = url.pathname.slice(prefix.length).replace(/\/+$/, '') || '/'
60
47
  const method = req.method ?? 'GET'
@@ -119,6 +106,19 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
119
106
  })
120
107
  }
121
108
 
109
+ // The runtime outcome of the last saved change. It is intentionally a
110
+ // separate read: applying a change can restart this plugin, so the write
111
+ // answers immediately and the result arrives here.
112
+ if (method === 'GET' && path === '/apply-status') {
113
+ const token = Number(url.searchParams.get('token'))
114
+ return sendJson(res, 200, {
115
+ ok: true,
116
+ ...(typeof applyProfile?.status === 'function'
117
+ ? applyProfile.status(Number.isFinite(token) ? token : undefined)
118
+ : { application: 'unknown' }),
119
+ })
120
+ }
121
+
122
122
  if (path === '/skills' && method === 'GET' && skills) return sendJson(res, 200, { skills: await skills.list() })
123
123
  if (path === '/skills/refresh' && method === 'POST' && skills) {
124
124
  requireSameOrigin(req); skills.refresh()
@@ -130,7 +130,19 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
130
130
  if (typeof body.enabled !== 'boolean') throw new Error('无效的开关状态')
131
131
  return sendJson(res, 200, await skills.toggle(body.id, body.enabled))
132
132
  }
133
- if (path === '/skills/detail' && method === 'GET' && skills) return sendJson(res, 200, { skill: skills.detail(url.searchParams.get('id'), false) })
133
+ if (path === '/skills/detail' && method === 'GET' && skills) {
134
+ const skill = skills.detail(url.searchParams.get('id'), false)
135
+ return sendJson(res, 200, { skill: { ...skill, uploaded: !!uploadedSkillRecord(skill.name) } })
136
+ }
137
+ if (path === '/skills/uninstall' && method === 'POST' && skills) {
138
+ requireSameOrigin(req)
139
+ const body = await readJsonBody(req)
140
+ const name = String(body.name || '')
141
+ if (!uploadedSkillRecord(name)) throw new Error('只能卸载通过本插件上传的 Skill')
142
+ uninstallUploadedSkill(name)
143
+ skills.refresh()
144
+ return sendJson(res, 200, { ok: true, skills: await skills.list() })
145
+ }
134
146
  if (path === '/skills/resource' && method === 'GET' && skills) return sendJson(res, 200, { content: skills.resource(url.searchParams.get('id'), url.searchParams.get('path')) })
135
147
  if (path === '/skills/icon' && method === 'GET' && skills) {
136
148
  try {
@@ -225,6 +237,26 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
225
237
  return sendJson(res, 200, result)
226
238
  }
227
239
 
240
+ // Pure skill packages bypass the plugin pipeline: upload, private copy,
241
+ // junction into $DSH_HOME/skills, then a hot refresh of the Skills tab.
242
+ if (method === 'POST' && path === '/skills/import') {
243
+ requireSameOrigin(req)
244
+ const body = await readJsonBody(req, 30_000_000)
245
+ const target = body.data ? await saveUploadedZip(body.data, body.filename) : body.path
246
+ const result = await importLocalSkills(target, { overwrite: body.overwrite === true })
247
+ skills?.refresh()
248
+ return sendJson(res, 200, result)
249
+ }
250
+
251
+ // An uploaded marketplace becomes its own plugin source tab.
252
+ if (method === 'POST' && path === '/marketplaces/import') {
253
+ requireSameOrigin(req)
254
+ const body = await readJsonBody(req, 30_000_000)
255
+ const target = body.data ? await saveUploadedZip(body.data, body.filename) : body.path
256
+ const result = await importLocalMarketplace(target, { sourceName: body.sourceName, overwrite: body.overwrite === true })
257
+ return sendJson(res, 200, result)
258
+ }
259
+
228
260
  if (method === 'POST' && path === '/sources') {
229
261
  requireSameOrigin(req)
230
262
  const body = await readJsonBody(req)
@@ -323,7 +355,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
323
355
  for (const block of patch) {
324
356
  if (!block || !Array.isArray(block.insert)) continue
325
357
  for (const item of block.insert) {
326
- if (!item || typeof item.id !== 'string' || !item.id.startsWith('mcp-user-mcp-')) continue
358
+ if (!item || typeof item.id !== 'string' || !item.id.startsWith(getConnectorId('user-mcp', ''))) continue
327
359
  const cfg = item.config || {}
328
360
  if (cfg.serverName && !state.userMcps.some((x) => x && x.name === cfg.serverName)) {
329
361
  state.userMcps.push(userMcpConfig(cfg.serverName, {
@@ -342,15 +374,22 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
342
374
  const entry = getConnectorEntry('user-mcp', x.name)
343
375
  const remote = remoteConfigFromEntry(entry?.config) || readMcpToolsState()[`user-mcp::${x.name}`]?.savedOAuthRemoteConfig
344
376
  const client = remote?.oauth === 'custom' ? readSavedOAuthClient('user-mcp', x.name, remote.url, remote.oauth) : null
377
+ // The live registration says what is *running*; the saved definition
378
+ // says what the editor should show. The client id comes from the
379
+ // credential record, since the definition never stores the secret.
345
380
  return {
346
381
  ...x,
347
382
  ...(remote ? {
348
383
  transport: 'http', url: remote.url, headers: remote.headers,
349
- oauth: remote.oauth, oauthClientId: client?.clientId || remote.oauthClientId,
384
+ oauth: remote.oauth,
385
+ oauthClientId: client?.clientId || x.oauthClientId || remote.oauthClientId,
350
386
  oauthHasClientSecret: client?.hasClientSecret || false,
351
- oauthCallbackPort: remote.oauthCallbackPort || null, oauthScope: remote.oauthScope || '',
387
+ // Fall back to the live config only when the definition has no
388
+ // opinion, so a cleared field stays cleared.
389
+ oauthCallbackPort: x.oauthCallbackPort ?? remote.oauthCallbackPort ?? null,
390
+ oauthScope: x.oauthScope ?? remote.oauthScope ?? '',
352
391
  } : {}),
353
- enabled: enabledIds.has('mcp-user-mcp-' + x.name),
392
+ enabled: enabledIds.has(getConnectorId('user-mcp', x.name)),
354
393
  }
355
394
  })
356
395
  return sendJson(res, 200, { ok: true, mcps })
@@ -383,26 +422,63 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
383
422
  state.userMcps.push(userMcpConfig(name, body))
384
423
  writeState(state)
385
424
  }
386
- return sendJson(res, 200, result)
425
+ // A rejected create registered nothing, so there is nothing to apply.
426
+ if (!result || !result.ok) return sendJson(res, 200, result)
427
+ return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId('user-mcp', name)]))
387
428
  }
388
429
 
389
430
  if (method === 'POST' && path === '/mcps/update') {
390
431
  requireSameOrigin(req)
391
432
  const body = await readJsonBody(req)
433
+ // `previousName` is only sent when the user renamed the server in the
434
+ // editor; without it the name in the body is also the stored one.
435
+ const previousName = body.previousName
436
+ ? safeSegment(normalizeMcpName(body.previousName), 'MCP 名称')
437
+ : null
392
438
  const name = safeSegment(normalizeMcpName(body.name), 'MCP 名称')
393
439
  const state = readState()
394
440
  if (!Array.isArray(state.userMcps)) state.userMcps = []
395
- const idx = state.userMcps.findIndex((x) => x && x.name === name)
396
- if (idx < 0) throw new Error(`MCP 不存在:${name}`)
441
+ const idx = state.userMcps.findIndex((x) => x && x.name === (previousName || name))
442
+ if (idx < 0) throw new Error(`MCP 不存在:${previousName || name}`)
443
+ if (previousName && previousName !== name) {
444
+ // Capture enablement before the rename: a disabled server registers
445
+ // nothing, so asking HMR to start its id would target an entry that
446
+ // does not exist.
447
+ const renamingEnabled = !!getConnectorEntry('user-mcp', previousName)
448
+ const renamed = renameUserMcp(previousName, name, body)
449
+ // A rename that failed registered nothing, so there is nothing to apply.
450
+ if (!renamed || !renamed.ok) return sendJson(res, 200, renamed)
451
+ return sendJson(res, 200, scheduledResult(
452
+ renamed, applyProfile, renamingEnabled ? [getConnectorId('user-mcp', name)] : []))
453
+ }
397
454
  const wasEnabled = !!getConnectorEntry('user-mcp', name)
398
455
  let result = { ok: true }
399
456
  if (wasEnabled) {
400
457
  result = saveConnectorAuth('user-mcp', name, body)
401
458
  if (!result || !result.ok) return sendJson(res, 200, result)
402
459
  }
403
- state.userMcps[idx] = userMcpConfig(name, body)
460
+ // Pass the stored record so an edit keeps the URL history a later delete
461
+ // needs to find every credential this server ever issued.
462
+ state.userMcps[idx] = userMcpConfig(name, body, state.userMcps[idx])
404
463
  writeState(state)
405
- return sendJson(res, 200, result)
464
+ return sendJson(res, 200, scheduledResult(result, applyProfile, wasEnabled ? [getConnectorId('user-mcp', name)] : []))
465
+ }
466
+
467
+ // One segment only: `/mcps/<name>/tools` belongs to the tool routes below.
468
+ // Decode and validate before the single-segment test, or an encoded slash
469
+ // slips past it; and reject a name that normalizes to nothing rather than
470
+ // falling back to the literal "mcp", which could match a real server.
471
+ if (method === 'DELETE' && path.startsWith('/mcps/')) {
472
+ // Check segments *after* decoding: `prod%2Fdb` decodes to a two-segment
473
+ // path and must not fall through to the server named `prod-db`.
474
+ const decoded = decodeURIComponent(path.slice('/mcps/'.length))
475
+ if (decoded.includes('/')) return sendJson(res, 404, { error: 'not found' })
476
+ requireSameOrigin(req)
477
+ const normalized = String(decoded || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[.-]+|-+$/g, '')
478
+ if (!normalized) throw new Error('无效的 MCP 名称')
479
+ const name = safeSegment(normalized, 'MCP 名称')
480
+ const result = removeUserMcp(name)
481
+ return sendJson(res, 200, scheduledResult(result, applyProfile))
406
482
  }
407
483
 
408
484
  if (method === 'POST' && path === '/mcps/toggle') {
@@ -414,10 +490,12 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
414
490
  if (!cfg) throw new Error(`MCP 不存在:${name}`)
415
491
  if (body.enabled !== false) {
416
492
  const result = saveConnectorAuth('user-mcp', name, cfg)
417
- return sendJson(res, 200, result)
493
+ // A rejected enable registered nothing: do not schedule a reconcile.
494
+ if (!result || !result.ok) return sendJson(res, 200, result)
495
+ return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId('user-mcp', name)]))
418
496
  }
419
497
  unregisterConnector('user-mcp', name)
420
- return sendJson(res, 200, { ok: true })
498
+ return sendJson(res, 200, scheduledResult({ ok: true }, applyProfile))
421
499
  }
422
500
 
423
501
  // ── user MCP tool list / per-tool toggle (same shape as plugin connectors) ──
@@ -476,7 +554,9 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
476
554
  const connectorName = safeSegment(parts[2], 'connector name')
477
555
  const body = await readJsonBody(req)
478
556
  const result = toggleConnector(pluginName, connectorName, body.enabled !== false)
479
- return sendJson(res, 200, result)
557
+ // A rejected toggle registered nothing: do not schedule a reconcile.
558
+ if (!result || !result.ok) return sendJson(res, 200, result)
559
+ return sendJson(res, 200, scheduledResult(result, applyProfile, body.enabled !== false ? [getConnectorId(pluginName, connectorName)] : []))
480
560
  }
481
561
 
482
562
  if (method === 'POST' && path.startsWith('/plugins/') && path.includes('/connectors/') && path.endsWith('/verify')) {
@@ -496,7 +576,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
496
576
  const connectorName = safeSegment(parts[2], 'connector name')
497
577
  const body = await readJsonBody(req)
498
578
  const result = saveConnectorAuth(pluginName, connectorName, body)
499
- return sendJson(res, 200, result)
579
+ return sendJson(res, 200, scheduledResult(result, applyProfile, [getConnectorId(pluginName, connectorName)]))
500
580
  }
501
581
 
502
582
  // ── plugin detail ────────────────────────────────────────────────────
@@ -572,14 +652,14 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
572
652
  pluginName,
573
653
  })
574
654
  invalidateMarketplaceCache(sourceId)
575
- return sendJson(res, 200, result)
655
+ return sendJson(res, 200, scheduledResult(result, applyProfile))
576
656
  }
577
657
 
578
658
  if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/toggle')) {
579
659
  requireSameOrigin(req)
580
660
  const pluginName = safeSegment(path.slice('/plugins/'.length, -'/toggle'.length), 'plugin name')
581
661
  const body = await readJsonBody(req)
582
- return sendJson(res, 200, await togglePlugin(pluginName, body.enabled === true))
662
+ return sendJson(res, 200, scheduledResult(await togglePlugin(pluginName, body.enabled === true), applyProfile))
583
663
  }
584
664
 
585
665
  if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/update')) {
@@ -587,7 +667,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
587
667
  const pluginName = safeSegment(path.slice('/plugins/'.length, -'/update'.length), 'plugin name')
588
668
  const result = await updatePlugin(pluginName)
589
669
  invalidateMarketplaceCache()
590
- return sendJson(res, 200, result)
670
+ return sendJson(res, 200, scheduledResult(result, applyProfile))
591
671
  }
592
672
 
593
673
  if (method === 'POST' && path === '/restart') {
@@ -630,7 +710,7 @@ async function handle(req, res, prefix = API_PREFIX, skills = null) {
630
710
  const pluginName = safeSegment(path.slice('/plugins/'.length), 'plugin name')
631
711
  const result = uninstallPlugin(pluginName)
632
712
  invalidateMarketplaceCache()
633
- return sendJson(res, 200, result)
713
+ return sendJson(res, 200, scheduledResult(result, applyProfile))
634
714
  }
635
715
 
636
716
  return sendJson(res, 404, { error: 'not found' })
package/src/runtime.js ADDED
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Apply saved hub changes to the running DSH profile.
3
+ *
4
+ * Writing cordis.patch.yml is persistence, not activation. The host owns the
5
+ * loader lifecycle, so new plugin/MCP entries go through its HMR service rather
6
+ * than a second connection layer or a process restart.
7
+ *
8
+ * Two constraints shape this module:
9
+ *
10
+ * 1. The application runs *after* the HTTP response. The hub loads from a
11
+ * linked directory, so a reconciliation may stop and restart the hub fiber;
12
+ * awaiting that inside a request the hub is serving would leave the response
13
+ * waiting on its own plugin being torn down.
14
+ * 2. A restart rebuilds the applicator, and with it the status. So the status
15
+ * is seeded from a token the client was already given: after a restart the
16
+ * new instance answers `applied` for that token instead of `idle`, and the
17
+ * poll converges instead of spinning out its window.
18
+ *
19
+ * Every outcome carries the token it belongs to, so a poll for change A can
20
+ * never read the result of change B.
21
+ */
22
+ export function createProfileApplicator(ctx) {
23
+ let queue = Promise.resolve()
24
+ let seq = 0
25
+ // Tokens that survived this process. A restarted fiber starts empty, so the
26
+ // first token it mints continues from the highest one the host handed out.
27
+ let last = Object.freeze({ application: 'idle', token: 0 })
28
+ let queued = null
29
+
30
+ // A reconciliation the host never settles would pin the status at `pending`
31
+ // and retain every closure queued behind it. Bound it: a timeout is reported
32
+ // as a failure the client can act on, and the queue moves on.
33
+ const RECONCILE_TIMEOUT_MS = 60_000
34
+
35
+ function applyProfile(requiredIds = []) {
36
+ const token = ++seq
37
+ last = Object.freeze({ application: 'pending', token })
38
+ // A change arriving while the queued reconciliation has not started yet is
39
+ // folded into it: one reconcile covers both, instead of restarting the hub
40
+ // once per rapid save. Its required ids join the same set.
41
+ if (queued && !queued.started) {
42
+ queued.token = token
43
+ queued.ids.push(...requiredIds)
44
+ // `done` must resolve with *this* change's token, not the token the run
45
+ // started with: report the caller's own identity.
46
+ const done = queued.run.then((outcome) => ({ ...outcome, token }))
47
+ done.then((outcome) => {
48
+ if (token === seq) last = Object.freeze({ ...outcome, at: Date.now() })
49
+ }, () => {})
50
+ return { token, done }
51
+ }
52
+ const pending = { started: false, token, ids: [...requiredIds], run: null }
53
+ queued = pending
54
+ const run = pending.run = queue.then(async () => {
55
+ pending.started = true
56
+ const ids = [...new Set(pending.ids)]
57
+ try {
58
+ // Resolve inside the try: a throwing service lookup must become a
59
+ // reported failure, not a rejection that strands the status.
60
+ const hmr = ctx?.root?.get?.('hmr') || ctx?.get?.('hmr')
61
+ if (!hmr || typeof hmr.reconcileProfile !== 'function') {
62
+ return { application: 'restart-required', restartReason: 'no-hmr', token: pending.token }
63
+ }
64
+ const reconcile = () => hmr.reconcileProfile(ids)
65
+ let timer
66
+ const timeout = new Promise((_, reject) => {
67
+ timer = setTimeout(() => reject(new Error(`reconcileProfile did not settle within ${RECONCILE_TIMEOUT_MS}ms`)), RECONCILE_TIMEOUT_MS)
68
+ timer.unref?.()
69
+ })
70
+ const result = await Promise.race([
71
+ typeof hmr.runExclusive === 'function' ? hmr.runExclusive(reconcile) : reconcile(),
72
+ timeout,
73
+ ]).finally(() => clearTimeout(timer))
74
+ // `reconcileProfile` reports a restart need either profile-wide or per
75
+ // pending module; either one means the change is not live yet.
76
+ const restartReason = result?.restartReason
77
+ || (Array.isArray(result?.pending) && result.pending.length ? result.pending[0]?.reason : undefined)
78
+ return {
79
+ application: restartReason ? 'restart-required' : 'applied',
80
+ token: pending.token,
81
+ ...(restartReason ? { restartReason } : {}),
82
+ }
83
+ } catch (error) {
84
+ // The saved change is still valid. Report that it is not live instead
85
+ // of turning a successful install into a misleading "install failed".
86
+ return {
87
+ application: 'failed',
88
+ token: pending.token,
89
+ applicationError: error instanceof Error ? error.message : String(error),
90
+ }
91
+ }
92
+ })
93
+ // One failed application must not poison later, independent changes.
94
+ queue = run.then(() => {}, () => {})
95
+ run.then((outcome) => {
96
+ // Only the newest change owns the status; an older, slower one must not
97
+ // overwrite a newer result a poll is already waiting on.
98
+ if (token === seq) last = Object.freeze({ ...outcome, at: Date.now() })
99
+ }, () => {})
100
+ return { token, done: run }
101
+ }
102
+
103
+ // A poll for a token this instance has not issued means the change was
104
+ // applied by a previous fiber that the reconciliation restarted — which is
105
+ // the success path for a linked plugin, not a superseded change.
106
+ applyProfile.status = (token) => {
107
+ if (typeof token === 'number' && token > seq) {
108
+ return Object.freeze({ application: 'applied', token: APPLIED_TOKEN })
109
+ }
110
+ return last
111
+ }
112
+ return applyProfile
113
+ }
114
+
115
+ /** Status served to a poll whose token predates this (restarted) instance. */
116
+ export const APPLIED_TOKEN = -1
117
+
118
+ /**
119
+ * Persist first, apply in the background. The response reports `scheduled`
120
+ * plus the token the client polls with; the outcome arrives through
121
+ * `status()`.
122
+ */
123
+ export function scheduledResult(result, applyProfile, requiredIds = []) {
124
+ if (typeof applyProfile !== 'function') return result
125
+ // Never await: a reconciliation can stop this very plugin. A fault while
126
+ // enqueueing must not turn a persisted change into an error response.
127
+ let token
128
+ try {
129
+ token = applyProfile(requiredIds).token
130
+ } catch (error) {
131
+ return { ...result, application: 'failed', applicationError: error instanceof Error ? error.message : String(error) }
132
+ }
133
+ return { ...result, application: 'scheduled', applicationToken: token }
134
+ }
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Direct skill imports live in the hub's private tree and are exposed through
3
+ * DSH's native user-dsh root. Directory bundles use junctions on Windows (and
4
+ * directory symlinks elsewhere); a bare SKILL.md is copied as <name>.md.
5
+ */
6
+ import { cpSync, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, symlinkSync } from 'node:fs'
7
+ import { createHash } from 'node:crypto'
8
+ import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
9
+ import { dshSkillsDir, readState, safeRmDir, uploadedSkillsDir, writeState } from './store.js'
10
+
11
+ const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
12
+
13
+ function samePath(a, b) {
14
+ if (!a || !b) return false
15
+ const left = resolve(a), right = resolve(b)
16
+ return process.platform === 'win32' ? left.toLowerCase() === right.toLowerCase() : left === right
17
+ }
18
+
19
+ /**
20
+ * The switch state is keyed by this hash (see skillId in skills.js), and the
21
+ * junction means the discovered path resolves to the private original, so both
22
+ * ends of the link have to be cleared.
23
+ */
24
+ function skillLocationId(path) {
25
+ let value
26
+ try { value = realpathSync.native(path) } catch { value = resolve(path) }
27
+ if (process.platform === 'win32') value = value.toLowerCase()
28
+ return createHash('sha256').update(value).digest('hex')
29
+ }
30
+
31
+ function contains(root, child) {
32
+ const rel = relative(resolve(root), resolve(child))
33
+ return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`))
34
+ }
35
+
36
+ function recordPaths(name, kind) {
37
+ if (!SKILL_NAME.test(name)) throw new Error('Skill 名称必须符合小写连字符格式')
38
+ return {
39
+ sourceDir: join(uploadedSkillsDir(), name),
40
+ target: join(dshSkillsDir(), kind === 'file' ? `${name}.md` : name),
41
+ }
42
+ }
43
+
44
+ export function isUploadedSkillTarget(path) {
45
+ return (readState().uploadedSkills || []).some(record => samePath(record?.target, path))
46
+ }
47
+
48
+ export function uploadedSkillRecord(name) {
49
+ return (readState().uploadedSkills || []).find(record => record?.name === name) || null
50
+ }
51
+
52
+ function pathExists(path) {
53
+ try { lstatSync(path); return true } catch { return false }
54
+ }
55
+
56
+ function removeTarget(record) {
57
+ const { target } = recordPaths(record.name, record.kind)
58
+ if (!pathExists(target)) return
59
+ const stat = lstatSync(target)
60
+ if (stat.isSymbolicLink()) {
61
+ // Remove the link itself. Never use safeRmDir's attrib fallback here:
62
+ // its recursive wildcard could modify the private original's files.
63
+ rmSync(target, { recursive: true, force: true })
64
+ } else if (stat.isDirectory()) safeRmDir(target)
65
+ else rmSync(target, { force: true })
66
+ }
67
+
68
+ function expose(record) {
69
+ const { sourceDir, target } = recordPaths(record.name, record.kind)
70
+ mkdirSync(dirname(target), { recursive: true })
71
+ if (record.kind === 'file') copyFileSync(join(sourceDir, 'SKILL.md'), target)
72
+ else symlinkSync(sourceDir, target, process.platform === 'win32' ? 'junction' : 'dir')
73
+ }
74
+
75
+ function rootSkillFile(dir) {
76
+ return ['SKILL.md', 'skill.md'].map(file => join(dir, file)).find(existsSync)
77
+ }
78
+
79
+ function validateEntry(entry) {
80
+ const name = String(entry?.row?.name || '')
81
+ if (!SKILL_NAME.test(name)) throw new Error(`Skill「${name || basename(entry?.dir || '')}」的 name 必须是小写连字符格式`)
82
+ // A flat `<name>.md` skill keeps its manifest in entry.file beside the other
83
+ // skills of the same folder, so the shared folder has no SKILL.md of its own.
84
+ const file = entry.file || rootSkillFile(entry.dir)
85
+ if (!file) throw new Error(`Skill「${name}」缺少 SKILL.md`)
86
+ const raw = readFileSyncSafe(file)
87
+ if (!/^description\s*:/m.test(raw)) throw new Error(`Skill「${name}」缺少 description`)
88
+ return { name, file }
89
+ }
90
+
91
+ function readFileSyncSafe(file) {
92
+ try { return readFileSync(file, 'utf8') } catch { return '' }
93
+ }
94
+
95
+ /** Every rejection this import can raise, so a batch can be checked up front. */
96
+ function preflight(entry, { overwrite, singleFile, fileDir = null }) {
97
+ const { name, file } = validateEntry(entry)
98
+ const kind = singleFile ? 'file' : 'directory'
99
+ const paths = recordPaths(name, kind)
100
+ const previous = uploadedSkillRecord(name)
101
+ if (previous && !overwrite) throw new Error(`已存在同名 Skill「${name}」`)
102
+ if (!previous && pathExists(paths.target)) {
103
+ throw new Error(`DSH Skills 目录已存在「${name}」,为避免覆盖你的文件,本次未导入`)
104
+ }
105
+ const source = resolve(entry.dir)
106
+ if (contains(uploadedSkillsDir(), source) || contains(source, uploadedSkillsDir())) {
107
+ throw new Error('导入源与技能存储目录重叠,请从独立文件夹导入')
108
+ }
109
+ return { name, file, kind, paths, previous, source }
110
+ }
111
+
112
+ function installOne(entry, options) {
113
+ const { name, file, kind, paths, previous, source } = preflight(entry, options)
114
+ // A bare SKILL.md file, or a flat `<name>.md` sitting beside other skills in
115
+ // one folder, has no assets to carry: only the manifest is copied.
116
+ const manifestOnly = options.singleFile || options.fileDir
117
+ mkdirSync(uploadedSkillsDir(), { recursive: true })
118
+ const staging = join(uploadedSkillsDir(), `.${name}-${process.pid}-${Date.now()}.tmp`)
119
+ let staged = false, installed = false, exposed = false
120
+ try {
121
+ if (manifestOnly) {
122
+ mkdirSync(staging, { recursive: true })
123
+ copyFileSync(file, join(staging, 'SKILL.md'))
124
+ } else {
125
+ cpSync(source, staging, { recursive: true, force: true })
126
+ const stagedRoot = join(staging, 'SKILL.md')
127
+ if (!existsSync(stagedRoot)) copyFileSync(join(staging, basename(file)), stagedRoot)
128
+ }
129
+ staged = true
130
+
131
+ if (previous) {
132
+ removeTarget(previous)
133
+ safeRmDir(recordPaths(previous.name, previous.kind).sourceDir)
134
+ }
135
+ renameSync(staging, paths.sourceDir)
136
+ staged = false
137
+ installed = true
138
+ expose({ name, kind })
139
+ exposed = true
140
+
141
+ const state = readState()
142
+ state.uploadedSkills = [...(state.uploadedSkills || []).filter(item => item.name !== name),
143
+ { name, kind, ...paths, uploadedAt: previous?.uploadedAt || Date.now(), updatedAt: Date.now() }]
144
+ writeState(state)
145
+ return { name, kind }
146
+ } catch (error) {
147
+ // Roll back only what this attempt created; never delete an old original
148
+ // that was already removed before the failure (its target is gone too, so
149
+ // the previous entry stays recorded and can be restored from the source).
150
+ if (exposed) { try { removeTarget({ name, kind }) } catch {} }
151
+ if (installed) { try { safeRmDir(paths.sourceDir) } catch {} }
152
+ throw error
153
+ } finally {
154
+ if (staged) { try { safeRmDir(staging) } catch {} }
155
+ }
156
+ }
157
+
158
+ export function installUploadedSkills(entries, { overwrite = false, singleFile = false } = {}) {
159
+ if (!Array.isArray(entries) || entries.length === 0) throw new Error('未检测到可上传的 Skill')
160
+ // A batch must not half-install: every rejection this import can predict is
161
+ // raised before the first file moves, so a duplicate name in the middle of
162
+ // the package cannot leave the earlier skills live while the UI reports a
163
+ // failure.
164
+ for (const entry of entries) preflight(entry, { overwrite, singleFile, fileDir: entry.singleFile })
165
+ const installed = []
166
+ try {
167
+ for (const entry of entries) {
168
+ const replaced = !!uploadedSkillRecord(String(entry?.row?.name || ''))
169
+ installed.push({ ...installOne(entry, { overwrite, singleFile, fileDir: entry.singleFile }), replaced })
170
+ }
171
+ return installed.map(({ replaced, ...skill }) => skill)
172
+ } catch (error) {
173
+ // Only a failure preflight cannot see (disk, permissions) gets here. Undo
174
+ // the entries this batch created; an overwrite has already replaced its
175
+ // original, so deleting it would be worse than leaving the new copy.
176
+ for (const skill of installed) {
177
+ if (skill.replaced) continue
178
+ try { uninstallUploadedSkill(skill.name) } catch {}
179
+ }
180
+ throw error
181
+ }
182
+ }
183
+
184
+ export function uninstallUploadedSkill(name) {
185
+ const record = uploadedSkillRecord(name)
186
+ if (!record) throw new Error('只能卸载通过本插件上传的 Skill')
187
+ const { sourceDir, target } = recordPaths(record.name, record.kind)
188
+ // The switch key hashes the manifest file, not the folder.
189
+ const removal = (record.kind === 'file' ? [target, join(sourceDir, 'SKILL.md')] : [join(target, 'SKILL.md'), join(sourceDir, 'SKILL.md')])
190
+ .map(file => skillLocationId(file))
191
+ removeTarget(record)
192
+ safeRmDir(recordPaths(record.name, record.kind).sourceDir)
193
+ const state = readState()
194
+ state.uploadedSkills = (state.uploadedSkills || []).filter(item => item.name !== name)
195
+ // The id hashes the canonical path, and a re-upload recreates that same path,
196
+ // so a stale "off" left here would switch the fresh copy off on arrival.
197
+ if (state.disabledLocalSkills) {
198
+ for (const id of removal) delete state.disabledLocalSkills[id]
199
+ }
200
+ writeState(state)
201
+ return { ok: true, name }
202
+ }
203
+
204
+ /** Repair links/copies after a restart without rewriting the originals. */
205
+ export function restoreUploadedSkills() {
206
+ const restored = []
207
+ for (const record of readState().uploadedSkills || []) {
208
+ try {
209
+ const paths = recordPaths(record.name, record.kind)
210
+ if (!existsSync(join(paths.sourceDir, 'SKILL.md'))) continue
211
+ if (!pathExists(paths.target)) {
212
+ expose(record)
213
+ restored.push(record.name)
214
+ }
215
+ } catch {}
216
+ }
217
+ return restored
218
+ }