universal-plugin-hub 0.0.0-stage → 1.0.6

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 ADDED
@@ -0,0 +1,559 @@
1
+ /**
2
+ * webServer REST routes bridging the browser UI to the host.
3
+ * This layer only parses requests, calls service modules, and serializes.
4
+ * Mutations are same-origin only.
5
+ */
6
+ import { existsSync } from 'node:fs'
7
+ import { join } from 'node:path'
8
+ import { sendJson, readJsonBody, sameOrigin } from './http.js'
9
+ import {
10
+ readState, writeState, slugify, suggestSourceName, parseGitUrl, normalizeGitRepoUrl, findDuplicateSource, installedDir,
11
+ } from './store.js'
12
+ import { ensureSourceCloned, pullSource, safeSegment, materializePlugin } from './market.js'
13
+ import { readMarketplace, pluginDetail, pluginContentDir, invalidateMarketplaceCache } from './parser.js'
14
+ import { getOrFetchIcon, readLocalIcon } from './icons.js'
15
+ import {
16
+ installPlugin, uninstallPlugin, togglePlugin, updatePlugin, installedDetails, isScanDirRegistered,
17
+ toggleConnector, isConnectorActive, verifyConnectorAuth, saveConnectorAuth,
18
+ fetchConnectorTools, setToolDisabled, isLspActive, readCordisPatch, unregisterConnector, getConnectorEntry,
19
+ } from './install.js'
20
+ import { inspectLocalPlugin, importLocalPlugin, saveUploadedZip } from './local.js'
21
+
22
+ const API_PREFIX = '/universal-plugin-hub/api'
23
+
24
+ export function mountRoutes(webServer) {
25
+ const r = webServer.register({
26
+ kind: 'prefix',
27
+ path: API_PREFIX,
28
+ handler: (req, res) => handle(req, res, API_PREFIX),
29
+ })
30
+ return () => {
31
+ try { if (typeof r === 'function') r() } catch {}
32
+ }
33
+ }
34
+
35
+ function normalizeMcpName(value) {
36
+ return String(value || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[.-]+|-+$/g, '') || 'mcp'
37
+ }
38
+
39
+ function userMcpConfig(name, body) {
40
+ return {
41
+ name,
42
+ transport: body.transport === 'http' ? 'http' : 'stdio',
43
+ url: body.url || null,
44
+ command: body.command || null,
45
+ args: Array.isArray(body.args) ? body.args : [],
46
+ env: body.env && typeof body.env === 'object' ? body.env : {},
47
+ headers: body.headers && typeof body.headers === 'object' ? body.headers : {},
48
+ oauth: body.oauth || 'none',
49
+ }
50
+ }
51
+
52
+ async function handle(req, res, prefix = API_PREFIX) {
53
+ const url = new URL(req.url, 'http://localhost')
54
+ const path = url.pathname.slice(prefix.length).replace(/\/+$/, '') || '/'
55
+ const method = req.method ?? 'GET'
56
+
57
+ try {
58
+ // ── icon local cache & proxy ─────────────────────────────────────────
59
+ if (method === 'GET' && path === '/icon') {
60
+ const targetUrl = url.searchParams.get('u')
61
+ if (!targetUrl) return sendJson(res, 400, { error: 'missing u parameter' })
62
+ try {
63
+ const { buffer, contentType } = await getOrFetchIcon(targetUrl)
64
+ res.writeHead(200, {
65
+ 'Content-Type': contentType || 'image/png',
66
+ 'Cache-Control': 'public, max-age=604800',
67
+ 'X-Content-Type-Options': 'nosniff',
68
+ 'Content-Security-Policy': "default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox",
69
+ })
70
+ return res.end(buffer)
71
+ } catch (err) {
72
+ return sendJson(res, 502, { error: err.message })
73
+ }
74
+ }
75
+
76
+ if (method === 'GET' && path === '/plugin-icon') {
77
+ try {
78
+ const sourceId = safeSegment(url.searchParams.get('sourceId'), 'source id')
79
+ const name = safeSegment(url.searchParams.get('name'), 'plugin name')
80
+ const record = readState().plugins.find((p) => p.name === name && p.sourceId === sourceId)
81
+ const row = readMarketplace(sourceId).find((p) => p.name === name)
82
+ const dir = record && existsSync(installedDir(name)) ? installedDir(name) : (row ? pluginContentDir(sourceId, name, row.source, false) : null)
83
+ if (!dir) return sendJson(res, 404, { error: 'Plugin icon not found' })
84
+ const { buffer, contentType } = readLocalIcon(dir, url.searchParams.get('path'))
85
+ res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': 'public, max-age=604800', 'X-Content-Type-Options': 'nosniff', 'Content-Security-Policy': "default-src 'none'; img-src data:; style-src 'unsafe-inline'; sandbox" })
86
+ return res.end(buffer)
87
+ } catch {
88
+ return sendJson(res, 404, { error: 'Plugin icon not found' })
89
+ }
90
+ }
91
+
92
+ // ── state ────────────────────────────────────────────────────────────
93
+ if (method === 'GET' && path === '/state') {
94
+ const state = readState()
95
+ const details = installedDetails()
96
+ return sendJson(res, 200, {
97
+ sources: state.sources.map((source) => source.id === 'local' ? { ...source, pluginCount: readMarketplace('local').length } : source),
98
+ plugins: details.map((p) => ({
99
+ ...p,
100
+ skillsEnabled: isScanDirRegistered(join(installedDir(p.name), 'skills')),
101
+ })),
102
+ })
103
+ }
104
+
105
+ // ── market listing / refresh ─────────────────────────────────────────
106
+ if (method === 'GET' && path === '/market') {
107
+ const rawSource = url.searchParams.get('sourceId') || url.searchParams.get('source') || 'anthropic'
108
+ const sourceId = safeSegment(rawSource, 'source id')
109
+ await ensureSourceCloned(sourceId, sourceUrlOf(sourceId))
110
+ const rows = readMarketplace(sourceId)
111
+ return sendJson(res, 200, { plugins: rows })
112
+ }
113
+
114
+ if (method === 'POST' && path === '/market/refresh') {
115
+ requireSameOrigin(req)
116
+ const body = await readJsonBody(req)
117
+ const sourceId = safeSegment(body.sourceId || 'anthropic', 'source id')
118
+ // Clone first if the source has never been fetched (fresh install), so a
119
+ // first-launch refresh does not fail with "尚未克隆".
120
+ await ensureSourceCloned(sourceId, sourceUrlOf(sourceId))
121
+ await pullSource(sourceId)
122
+ invalidateMarketplaceCache(sourceId)
123
+ return sendJson(res, 200, { ok: true, plugins: readMarketplace(sourceId) })
124
+ }
125
+
126
+ // ── sources ──────────────────────────────────────────────────────────
127
+ if (method === 'POST' && path === '/sources/ensure') {
128
+ requireSameOrigin(req)
129
+ const body = await readJsonBody(req)
130
+ const rawInput = String(body.url || '').trim()
131
+ const url = normalizeGitRepoUrl(rawInput)
132
+ if (!url || !/^https?:\/\//i.test(url)) {
133
+ throw new Error('请输入有效的 Git 仓库地址或 owner/repo(例如 anthropics/claude-plugins-community)')
134
+ }
135
+ const parsed = parseGitUrl(url)
136
+ const id = slugify(parsed ? `${parsed.owner}-${parsed.repo}` : url)
137
+ if (!id) throw new Error('无法从该地址识别仓库')
138
+
139
+ // Check duplicates BEFORE cloning
140
+ const state = readState()
141
+ const duplicate = findDuplicateSource(state, id, url)
142
+ if (duplicate) {
143
+ throw new Error(`该插件源已存在(${duplicate.name})`)
144
+ }
145
+
146
+ // Validate by cloning into the cache
147
+ await ensureSourceCloned(id, url)
148
+ const rows = readMarketplace(id)
149
+ const count = Array.isArray(rows) ? rows.length : 0
150
+
151
+ const repoLabel = parsed ? `${parsed.owner}/${parsed.repo}` : (url.replace(/^https?:\/\//i, '').replace(/\.git$/i, ''))
152
+
153
+ return sendJson(res, 200, {
154
+ ok: true,
155
+ sourceId: id,
156
+ repoLabel,
157
+ normalizedUrl: url,
158
+ pluginCount: count,
159
+ suggestedName: suggestSourceName(url),
160
+ })
161
+ }
162
+
163
+ // ── local plugin inspection & import ──────────────────────────────────
164
+ if (method === 'POST' && path === '/plugins/local/inspect') {
165
+ requireSameOrigin(req)
166
+ const body = await readJsonBody(req, 30_000_000)
167
+ const target = body.data ? await saveUploadedZip(body.data, body.filename) : body.path
168
+ const result = await inspectLocalPlugin(target)
169
+ return sendJson(res, 200, result)
170
+ }
171
+
172
+ if (method === 'POST' && path === '/plugins/local/import') {
173
+ requireSameOrigin(req)
174
+ const body = await readJsonBody(req, 30_000_000)
175
+ const target = body.data ? await saveUploadedZip(body.data, body.filename) : body.path
176
+ const result = await importLocalPlugin({ path: target, overwrite: body.overwrite, sourceName: body.sourceName })
177
+ return sendJson(res, 200, result)
178
+ }
179
+
180
+ if (method === 'POST' && path === '/sources') {
181
+ requireSameOrigin(req)
182
+ const body = await readJsonBody(req)
183
+ const rawInput = String(body.url || '').trim()
184
+ const url = normalizeGitRepoUrl(rawInput)
185
+ const name = String(body.name || '').trim()
186
+ if (!name) throw new Error('请输入源名称')
187
+ if (!url || !/^https?:\/\//i.test(url)) {
188
+ throw new Error('请输入有效的 Git 仓库地址或 owner/repo')
189
+ }
190
+ const parsed = parseGitUrl(url)
191
+ const id = slugify(parsed ? `${parsed.owner}-${parsed.repo}` : url)
192
+ if (!id) throw new Error('无法从该地址识别仓库')
193
+
194
+ const state = readState()
195
+ const duplicate = findDuplicateSource(state, id, url)
196
+ if (duplicate) {
197
+ throw new Error(`该插件源已存在(${duplicate.name})`)
198
+ }
199
+
200
+ // Check name duplication (e.g. user naming two sources with the same label)
201
+ if (state.sources.some((s) => s.name.trim().toLowerCase() === name.toLowerCase())) {
202
+ throw new Error(`已存在同名的插件源「${name}」,请换一个名称`)
203
+ }
204
+
205
+ await ensureSourceCloned(id, url)
206
+ const rows = readMarketplace(id)
207
+ const count = Array.isArray(rows) ? rows.length : 0
208
+
209
+ state.sources.push({ id, name, url, addedAt: Date.now() })
210
+ writeState(state)
211
+ return sendJson(res, 200, {
212
+ ok: true,
213
+ source: state.sources[state.sources.length - 1],
214
+ pluginCount: count,
215
+ })
216
+ }
217
+
218
+ if (method === 'POST' && path === '/sources/reorder') {
219
+ requireSameOrigin(req)
220
+ const body = await readJsonBody(req)
221
+ const sourceIds = Array.isArray(body.sourceIds) ? body.sourceIds : []
222
+ if (sourceIds.length === 0) throw new Error('无效的插件源列表')
223
+ const state = readState()
224
+ const sourceMap = new Map(state.sources.map((s) => [s.id, s]))
225
+ const reordered = []
226
+ for (const id of sourceIds) {
227
+ if (sourceMap.has(id)) {
228
+ reordered.push(sourceMap.get(id))
229
+ sourceMap.delete(id)
230
+ }
231
+ }
232
+ // append any remaining sources not in the list
233
+ for (const s of sourceMap.values()) {
234
+ reordered.push(s)
235
+ }
236
+ state.sources = reordered
237
+ writeState(state)
238
+ return sendJson(res, 200, { ok: true, sources: state.sources })
239
+ }
240
+
241
+ if (method === 'DELETE' && path.startsWith('/sources/')) {
242
+ requireSameOrigin(req)
243
+ const sourceId = safeSegment(path.slice('/sources/'.length), 'source id')
244
+ const state = readState()
245
+ const source = state.sources.find((s) => s.id === sourceId)
246
+ if (!source) throw new Error('插件源不存在')
247
+ if (source.builtin) throw new Error('内置源不可删除')
248
+ const used = state.plugins.some((p) => p.sourceId === sourceId)
249
+ if (used) throw new Error('该源下仍有已安装插件,请先卸载')
250
+ state.sources = state.sources.filter((s) => s.id !== sourceId)
251
+ writeState(state)
252
+ invalidateMarketplaceCache(sourceId)
253
+ return sendJson(res, 200, { ok: true })
254
+ }
255
+
256
+ // ── user-added MCP servers (standalone, not tied to an installed plugin) ──
257
+ if (method === 'GET' && path === '/mcps') {
258
+ const state = readState()
259
+ if (!Array.isArray(state.userMcps)) state.userMcps = []
260
+ const patch = readCordisPatch()
261
+ const enabledIds = new Set()
262
+ for (const block of patch) {
263
+ if (!block || !Array.isArray(block.insert)) continue
264
+ for (const item of block.insert) {
265
+ if (item && typeof item.id === 'string') enabledIds.add(item.id)
266
+ }
267
+ }
268
+ // Migrate legacy patch-only entries (saved before userMcps state existed)
269
+ let changed = false
270
+ for (const block of patch) {
271
+ if (!block || !Array.isArray(block.insert)) continue
272
+ for (const item of block.insert) {
273
+ if (!item || typeof item.id !== 'string' || !item.id.startsWith('mcp-user-mcp-')) continue
274
+ const cfg = item.config || {}
275
+ if (cfg.serverName && !state.userMcps.some((x) => x && x.name === cfg.serverName)) {
276
+ state.userMcps.push(userMcpConfig(cfg.serverName, {
277
+ transport: cfg.transport, url: cfg.url, command: cfg.command,
278
+ args: Array.isArray(cfg.args) ? cfg.args : [], env: cfg.env || {},
279
+ headers: cfg.headers || {}, oauth: cfg.oauth || 'none',
280
+ }))
281
+ changed = true
282
+ }
283
+ }
284
+ }
285
+ if (changed) writeState(state)
286
+ const mcps = state.userMcps
287
+ .filter((x) => x && x.name)
288
+ .map((x) => ({ ...x, enabled: enabledIds.has('mcp-user-mcp-' + x.name) }))
289
+ return sendJson(res, 200, { ok: true, mcps })
290
+ }
291
+ if (method === 'POST' && path === '/mcps/verify') {
292
+ requireSameOrigin(req)
293
+ const body = await readJsonBody(req)
294
+ const name = String(body.name || '').trim().toLowerCase().replace(/[^a-z0-9._-]+/g, '-').replace(/^[.-]+|-+$/g, '') || 'mcp'
295
+ const result = await verifyConnectorAuth('user-mcp', name, body)
296
+ return sendJson(res, 200, result)
297
+ }
298
+
299
+ if (method === 'POST' && path === '/mcps') {
300
+ requireSameOrigin(req)
301
+ const body = await readJsonBody(req)
302
+ const name = safeSegment(normalizeMcpName(body.name), 'MCP 名称')
303
+ const result = saveConnectorAuth('user-mcp', name, body)
304
+ if (result && result.ok) {
305
+ const state = readState()
306
+ if (!Array.isArray(state.userMcps)) state.userMcps = []
307
+ state.userMcps = state.userMcps.filter((x) => x && x.name !== name)
308
+ state.userMcps.push(userMcpConfig(name, body))
309
+ writeState(state)
310
+ }
311
+ return sendJson(res, 200, result)
312
+ }
313
+
314
+ if (method === 'POST' && path === '/mcps/update') {
315
+ requireSameOrigin(req)
316
+ const body = await readJsonBody(req)
317
+ const name = safeSegment(normalizeMcpName(body.name), 'MCP 名称')
318
+ const state = readState()
319
+ if (!Array.isArray(state.userMcps)) state.userMcps = []
320
+ const idx = state.userMcps.findIndex((x) => x && x.name === name)
321
+ if (idx < 0) throw new Error(`MCP 不存在:${name}`)
322
+ const wasEnabled = !!getConnectorEntry('user-mcp', name)
323
+ let result = { ok: true }
324
+ if (wasEnabled) {
325
+ result = saveConnectorAuth('user-mcp', name, body)
326
+ if (!result || !result.ok) return sendJson(res, 200, result)
327
+ }
328
+ state.userMcps[idx] = userMcpConfig(name, body)
329
+ writeState(state)
330
+ return sendJson(res, 200, result)
331
+ }
332
+
333
+ if (method === 'POST' && path === '/mcps/toggle') {
334
+ requireSameOrigin(req)
335
+ const body = await readJsonBody(req)
336
+ const name = safeSegment(normalizeMcpName(body.name), 'MCP 名称')
337
+ const state = readState()
338
+ const cfg = (state.userMcps || []).find((x) => x && x.name === name)
339
+ if (!cfg) throw new Error(`MCP 不存在:${name}`)
340
+ if (body.enabled !== false) {
341
+ const result = saveConnectorAuth('user-mcp', name, cfg)
342
+ return sendJson(res, 200, result)
343
+ }
344
+ unregisterConnector('user-mcp', name)
345
+ return sendJson(res, 200, { ok: true })
346
+ }
347
+
348
+ // ── user MCP tool list / per-tool toggle (same shape as plugin connectors) ──
349
+ if (method === 'GET' && path.startsWith('/mcps/') && path.endsWith('/tools')) {
350
+ const name = safeSegment(normalizeMcpName(path.slice('/mcps/'.length, -'/tools'.length)), 'MCP 名称')
351
+ const result = await fetchConnectorTools('user-mcp', name)
352
+ return sendJson(res, 200, result)
353
+ }
354
+
355
+ if (method === 'POST' && path.startsWith('/mcps/') && path.endsWith('/tools/toggle')) {
356
+ requireSameOrigin(req)
357
+ const name = safeSegment(normalizeMcpName(path.slice('/mcps/'.length, -'/tools/toggle'.length)), 'MCP 名称')
358
+ const body = await readJsonBody(req)
359
+ const toolName = String(body.toolName || body.tool || '')
360
+ const enabled = body.enabled !== false
361
+ const disabledTools = setToolDisabled('user-mcp', name, toolName, !enabled)
362
+ return sendJson(res, 200, { ok: true, disabledTools })
363
+ }
364
+
365
+ // ── connector routes (must precede catch-all /plugins/ routes) ────────
366
+ if (method === 'GET' && path.startsWith('/plugins/') && path.includes('/connectors/') && path.endsWith('/tools')) {
367
+ const parts = path.slice('/plugins/'.length).split('/')
368
+ const pluginName = safeSegment(parts[0], 'plugin name')
369
+ const connectorName = safeSegment(parts[2], 'connector name')
370
+ const result = await fetchConnectorTools(pluginName, connectorName)
371
+ return sendJson(res, 200, result)
372
+ }
373
+
374
+ if (method === 'POST' && path.startsWith('/plugins/') && path.includes('/connectors/') && path.endsWith('/tools/toggle')) {
375
+ requireSameOrigin(req)
376
+ const parts = path.slice('/plugins/'.length).split('/')
377
+ const pluginName = safeSegment(parts[0], 'plugin name')
378
+ const connectorName = safeSegment(parts[2], 'connector name')
379
+ const body = await readJsonBody(req)
380
+ const toolName = String(body.toolName || body.tool || '')
381
+ const enabled = body.enabled !== false
382
+ const disabledTools = setToolDisabled(pluginName, connectorName, toolName, !enabled)
383
+ return sendJson(res, 200, { ok: true, disabledTools })
384
+ }
385
+
386
+ if (method === 'POST' && path.startsWith('/plugins/') && path.includes('/connectors/') && path.endsWith('/toggle')) {
387
+ requireSameOrigin(req)
388
+ const parts = path.slice('/plugins/'.length).split('/')
389
+ const pluginName = safeSegment(parts[0], 'plugin name')
390
+ const connectorName = safeSegment(parts[2], 'connector name')
391
+ const body = await readJsonBody(req)
392
+ const result = toggleConnector(pluginName, connectorName, body.enabled !== false)
393
+ return sendJson(res, 200, result)
394
+ }
395
+
396
+ if (method === 'POST' && path.startsWith('/plugins/') && path.includes('/connectors/') && path.endsWith('/verify')) {
397
+ requireSameOrigin(req)
398
+ const parts = path.slice('/plugins/'.length).split('/')
399
+ const pluginName = safeSegment(parts[0], 'plugin name')
400
+ const connectorName = safeSegment(parts[2], 'connector name')
401
+ const body = await readJsonBody(req)
402
+ const result = await verifyConnectorAuth(pluginName, connectorName, body)
403
+ return sendJson(res, 200, result)
404
+ }
405
+
406
+ if (method === 'POST' && path.startsWith('/plugins/') && path.includes('/connectors/') && path.endsWith('/auth')) {
407
+ requireSameOrigin(req)
408
+ const parts = path.slice('/plugins/'.length).split('/')
409
+ const pluginName = safeSegment(parts[0], 'plugin name')
410
+ const connectorName = safeSegment(parts[2], 'connector name')
411
+ const body = await readJsonBody(req)
412
+ const result = saveConnectorAuth(pluginName, connectorName, body)
413
+ return sendJson(res, 200, result)
414
+ }
415
+
416
+ // ── plugin detail ────────────────────────────────────────────────────
417
+ if (method === 'GET' && path.startsWith('/plugins/') && !path.includes('/connectors/')) {
418
+ const rest = path.slice('/plugins/'.length)
419
+ const slash = rest.indexOf('/')
420
+ const rawSource = slash < 0 ? 'anthropic' : rest.slice(0, slash) || 'anthropic'
421
+ const rawPlugin = slash < 0 ? rest : rest.slice(slash + 1)
422
+ const sourceId = safeSegment(rawSource, 'source id')
423
+ const pluginName = safeSegment(rawPlugin, 'plugin name')
424
+ const rows = readMarketplace(sourceId)
425
+ let row = rows.find((r) => r.name === pluginName)
426
+ let detail = pluginDetail(sourceId, pluginName, row ? row.source : undefined, row)
427
+ // An external plugin may not have been installed or previewed before.
428
+ // Fetch its content for the preview, then enrich the sparse marketplace row.
429
+ if (!detail && row?.source && typeof row.source === 'object') {
430
+ await materializePlugin(sourceId, pluginName, row.source)
431
+ invalidateMarketplaceCache(sourceId)
432
+ row = readMarketplace(sourceId).find((r) => r.name === pluginName) || row
433
+ detail = pluginDetail(sourceId, pluginName, row.source, row)
434
+ }
435
+ if (!detail) {
436
+ const inst = installedDetails().find((p) => p.name === pluginName)
437
+ if (inst) {
438
+ detail = inst
439
+ if (!row) row = inst
440
+ }
441
+ }
442
+ if (detail && Array.isArray(detail.connectors)) {
443
+ detail.connectors = detail.connectors.map((c) => ({
444
+ ...c,
445
+ connected: isConnectorActive(pluginName, c.name),
446
+ }))
447
+ }
448
+ if (detail && Array.isArray(detail.lspServers)) {
449
+ detail.lspServers = detail.lspServers.map((s) => ({
450
+ ...s,
451
+ active: isLspActive(pluginName, s.name),
452
+ }))
453
+ }
454
+ return sendJson(res, 200, {
455
+ plugin: {
456
+ ...(row || { name: pluginName, displayName: pluginName, sourceId }),
457
+ detail,
458
+ },
459
+ })
460
+ }
461
+
462
+ // ── install / toggle / update / uninstall ────────────────────────────
463
+ if (method === 'POST' && path === '/plugins/install') {
464
+ requireSameOrigin(req)
465
+ const body = await readJsonBody(req)
466
+ const sourceId = safeSegment(body.sourceId || '', 'source id')
467
+ const pluginName = safeSegment(body.pluginName || '', 'plugin name')
468
+ const result = await installPlugin({
469
+ sourceId,
470
+ pluginName,
471
+ })
472
+ invalidateMarketplaceCache(sourceId)
473
+ return sendJson(res, 200, result)
474
+ }
475
+
476
+ if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/toggle')) {
477
+ requireSameOrigin(req)
478
+ const pluginName = safeSegment(path.slice('/plugins/'.length, -'/toggle'.length), 'plugin name')
479
+ const body = await readJsonBody(req)
480
+ return sendJson(res, 200, await togglePlugin(pluginName, body.enabled === true))
481
+ }
482
+
483
+ if (method === 'POST' && path.startsWith('/plugins/') && path.endsWith('/update')) {
484
+ requireSameOrigin(req)
485
+ const pluginName = safeSegment(path.slice('/plugins/'.length, -'/update'.length), 'plugin name')
486
+ const result = await updatePlugin(pluginName)
487
+ invalidateMarketplaceCache()
488
+ return sendJson(res, 200, result)
489
+ }
490
+
491
+ if (method === 'POST' && path === '/restart') {
492
+ requireSameOrigin(req)
493
+ try {
494
+ let restartFn = null
495
+ try {
496
+ const dshSkillsRestart = await import('dsh-agent-skills/lib/restart.js')
497
+ if (dshSkillsRestart && typeof dshSkillsRestart.scheduleDshRestart === 'function') {
498
+ restartFn = dshSkillsRestart.scheduleDshRestart
499
+ }
500
+ } catch {}
501
+
502
+ if (restartFn) {
503
+ const result = restartFn()
504
+ return sendJson(res, 202, { ok: true, ...(result || {}) })
505
+ }
506
+
507
+ // Direct spawn fallback
508
+ const { spawn } = await import('node:child_process')
509
+ const nodeExe = process.argv0 || process.execPath
510
+ const entry = process.argv[1]
511
+ const args = process.argv.slice(2)
512
+ const helper = spawn(nodeExe, [entry, ...args], {
513
+ detached: true,
514
+ stdio: 'ignore',
515
+ env: process.env,
516
+ cwd: process.cwd(),
517
+ })
518
+ helper.unref()
519
+ setTimeout(() => process.exit(0), 500)
520
+ return sendJson(res, 202, { ok: true })
521
+ } catch (e) {
522
+ return sendJson(res, 500, { error: e.message })
523
+ }
524
+ }
525
+
526
+ if (method === 'DELETE' && path.startsWith('/plugins/')) {
527
+ requireSameOrigin(req)
528
+ const pluginName = safeSegment(path.slice('/plugins/'.length), 'plugin name')
529
+ const result = uninstallPlugin(pluginName)
530
+ invalidateMarketplaceCache()
531
+ return sendJson(res, 200, result)
532
+ }
533
+
534
+ return sendJson(res, 404, { error: 'not found' })
535
+ } catch (error) {
536
+ const status = (error && typeof error === 'object' && error.status) ? error.status : 500
537
+ sendJson(res, status, { error: error instanceof Error ? error.message : String(error) })
538
+ }
539
+ }
540
+
541
+ function requireSameOrigin(req) {
542
+ if (!sameOrigin(req)) {
543
+ const error = new Error('cross-origin request rejected')
544
+ error.status = 403
545
+ throw error
546
+ }
547
+ }
548
+
549
+ function sourceUrlOf(sourceId) {
550
+ const state = readState()
551
+ const source = state.sources.find((s) => s.id === sourceId)
552
+ if (!source) throw new Error(`unknown source: ${sourceId}`)
553
+ return source.url
554
+ }
555
+
556
+ /** True when a plugin's skills dir is currently registered (used by UI). */
557
+ export function pluginScanState(pluginName) {
558
+ return isScanDirRegistered(join(installedDir(pluginName), 'skills'))
559
+ }