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/README.md +2 -1
- package/README.zh.md +2 -1
- package/client/client.js +10771 -10335
- package/package.json +1 -1
- package/src/icons.js +233 -24
- package/src/index.js +37 -15
- package/src/install.js +208 -11
- package/src/local.js +185 -7
- package/src/market.js +3 -3
- package/src/oauth-store.js +12 -1
- package/src/routes.js +118 -38
- package/src/runtime.js +134 -0
- package/src/skill-uploads.js +218 -0
- package/src/skills.js +214 -31
- package/src/store.js +5 -0
package/src/install.js
CHANGED
|
@@ -19,10 +19,11 @@ import { installedDir, readState, writeState, slugify, dshHome, dshSkillsDir, sa
|
|
|
19
19
|
import { materializePlugin, pullSource, pluginPath } from './market.js'
|
|
20
20
|
import { copyDir, listSkills, listAgents, listPrompts, listConnectors, listHooks, listLspServers, readPluginManifest, resolveHookConfigPath, invalidateParserCaches, invalidateMarketplaceCache, readMarketplace, connectorTransport, isRemoteTransportName } from './parser.js'
|
|
21
21
|
import { parseAgentDefinition, compileSubagentsHubSkill, cleanupLegacyPresets } from './agents-map.js'
|
|
22
|
+
import { isUploadedSkillTarget } from './skill-uploads.js'
|
|
22
23
|
import { buildPluginIcons } from './icons.js'
|
|
23
24
|
import { beginOAuthVerification, completeOAuthVerification, saveCustomOAuthClient, readSavedOAuthClient } from './oauth.js'
|
|
24
25
|
import { encodeOAuthConfig, isOAuthMode, oauthCredentialKey, oauthRuntimeConfig, remoteConfigFromEntry } from './oauth-config.js'
|
|
25
|
-
import { oauthStoreDir } from './oauth-store.js'
|
|
26
|
+
import { oauthStoreDir, readOAuthRecord, writeOAuthRecord, deleteOAuthRecord } from './oauth-store.js'
|
|
26
27
|
|
|
27
28
|
const OAUTH_BRIDGE_PATH = fileURLToPath(new URL('./oauth-bridge.js', import.meta.url))
|
|
28
29
|
|
|
@@ -310,6 +311,183 @@ export function unregisterConnector(pluginName, connectorName) {
|
|
|
310
311
|
return { ok: true, connected: false }
|
|
311
312
|
}
|
|
312
313
|
|
|
314
|
+
/**
|
|
315
|
+
* Delete a user-added MCP server completely: registration, saved definition,
|
|
316
|
+
* per-tool state and any OAuth credentials. `unregisterConnector` alone is the
|
|
317
|
+
* "turn it off" path and deliberately keeps the saved remote config so the
|
|
318
|
+
* server can be switched back on; a delete must leave nothing behind, or
|
|
319
|
+
* re-adding the same name would silently inherit the old sign-in.
|
|
320
|
+
*/
|
|
321
|
+
export function removeUserMcp(connectorName) {
|
|
322
|
+
const state = readState()
|
|
323
|
+
const saved = (Array.isArray(state.userMcps) ? state.userMcps : []).find((x) => x && x.name === connectorName)
|
|
324
|
+
if (!saved) throw new Error(`MCP 不存在:${connectorName}`)
|
|
325
|
+
|
|
326
|
+
// Credential keys cover both OAuth modes; the mode the server was saved with
|
|
327
|
+
// decides which file exists, and deleting a missing one is a no-op.
|
|
328
|
+
const remote = remoteConfigFromEntry(getConnectorEntry('user-mcp', connectorName)?.config) || saved
|
|
329
|
+
// A server can have been edited to a new URL since it signed in, so clear the
|
|
330
|
+
// record for every URL it is known to have used — the live one and the stored
|
|
331
|
+
// one — or the old sign-in survives the delete and is inherited on re-add.
|
|
332
|
+
const urls = new Set([remote?.url, saved.url, ...(Array.isArray(saved.usedUrls) ? saved.usedUrls : [])]
|
|
333
|
+
.filter((u) => typeof u === 'string' && u.trim()))
|
|
334
|
+
const credentialKeys = [...urls].flatMap((u) =>
|
|
335
|
+
['auto_register', 'custom'].map((mode) => oauthCredentialKey('user-mcp', connectorName, u, mode)))
|
|
336
|
+
const url = remote?.url || saved.url || null
|
|
337
|
+
|
|
338
|
+
unregisterConnector('user-mcp', connectorName)
|
|
339
|
+
|
|
340
|
+
const toolsKey = `user-mcp::${connectorName}`
|
|
341
|
+
const toolsState = readMcpToolsState()
|
|
342
|
+
if (Object.prototype.hasOwnProperty.call(toolsState, toolsKey)) {
|
|
343
|
+
delete toolsState[toolsKey]
|
|
344
|
+
writeMcpToolsState(toolsState)
|
|
345
|
+
}
|
|
346
|
+
MEMORY_TOOLS_CACHE.delete(toolsKey)
|
|
347
|
+
for (const key of credentialKeys) {
|
|
348
|
+
try { deleteOAuthRecord(key) } catch {}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
state.userMcps = (Array.isArray(state.userMcps) ? state.userMcps : []).filter((x) => x && x.name !== connectorName)
|
|
352
|
+
writeState(state)
|
|
353
|
+
return { ok: true, name: connectorName }
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Normalize one saved user MCP definition. `fallback` supplies the previous
|
|
358
|
+
* record, so a body that omits a field inherits the stored value instead of
|
|
359
|
+
* resetting it.
|
|
360
|
+
*/
|
|
361
|
+
export function userMcpConfig(name, body = {}, fallback = {}) {
|
|
362
|
+
// Only a *missing* field inherits the stored value. An explicit empty string
|
|
363
|
+
// is the user clearing the field; treating it as "keep previous" would make
|
|
364
|
+
// the editor unable to remove a callback port, scope or client id.
|
|
365
|
+
const pick = (value, previous) => (value === undefined ? previous : value)
|
|
366
|
+
// Remember every URL this server has used. A credential file is named by a
|
|
367
|
+
// hash of its URL, so once a server is edited to a new URL the old sign-in is
|
|
368
|
+
// unreachable unless its URL was recorded here.
|
|
369
|
+
const usedUrls = new Set(Array.isArray(fallback.usedUrls) ? fallback.usedUrls : [])
|
|
370
|
+
for (const candidate of [fallback.url, body.url]) {
|
|
371
|
+
if (typeof candidate === 'string' && candidate.trim()) usedUrls.add(candidate)
|
|
372
|
+
}
|
|
373
|
+
return {
|
|
374
|
+
name,
|
|
375
|
+
usedUrls: [...usedUrls],
|
|
376
|
+
transport: (body.transport || fallback.transport) === 'http' ? 'http' : 'stdio',
|
|
377
|
+
url: pick(body.url, fallback.url ?? null),
|
|
378
|
+
command: pick(body.command, fallback.command ?? null),
|
|
379
|
+
args: Array.isArray(body.args) ? body.args : (fallback.args || []),
|
|
380
|
+
env: body.env && typeof body.env === 'object' ? body.env : (fallback.env || {}),
|
|
381
|
+
headers: body.headers && typeof body.headers === 'object' ? body.headers : (fallback.headers || {}),
|
|
382
|
+
oauth: body.oauth || fallback.oauth || 'none',
|
|
383
|
+
oauthClientId: pick(body.oauthClientId, fallback.oauthClientId || ''),
|
|
384
|
+
oauthCallbackPort: pick(body.oauthCallbackPort, fallback.oauthCallbackPort ?? null),
|
|
385
|
+
oauthScope: pick(body.oauthScope, fallback.oauthScope || ''),
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Rename a user-added MCP. Everything that is keyed by the server name has to
|
|
391
|
+
* move with it: the cordis registration id, the saved OAuth record (its file
|
|
392
|
+
* name is a hash of the name, so a rename without this copy would look like a
|
|
393
|
+
* fresh, unauthenticated server), and per-tool state. OAuth records are copied
|
|
394
|
+
* before the re-registration so the new registration reuses the existing
|
|
395
|
+
* sign-in instead of starting a new browser handshake.
|
|
396
|
+
*/
|
|
397
|
+
export function renameUserMcp(oldName, newName, payload) {
|
|
398
|
+
if (oldName === newName) {
|
|
399
|
+
return saveConnectorAuth('user-mcp', newName, payload)
|
|
400
|
+
}
|
|
401
|
+
const state = readState()
|
|
402
|
+
if (!Array.isArray(state.userMcps)) state.userMcps = []
|
|
403
|
+
const idx = state.userMcps.findIndex((x) => x && x.name === oldName)
|
|
404
|
+
if (idx < 0) throw new Error(`MCP 不存在:${oldName}`)
|
|
405
|
+
if (state.userMcps.some((x) => x && x.name === newName)) throw new Error(`已存在同名 MCP:${newName}`)
|
|
406
|
+
|
|
407
|
+
const saved = state.userMcps[idx]
|
|
408
|
+
// One lookup for both facts: `readCordisPatch` re-reads and re-parses the
|
|
409
|
+
// patch file on every call, and this runs inside a user-visible action.
|
|
410
|
+
const entry = getConnectorEntry('user-mcp', oldName)
|
|
411
|
+
const wasEnabled = !!entry
|
|
412
|
+
const remote = remoteConfigFromEntry(entry?.config)
|
|
413
|
+
const url = remote?.url || saved.url || payload?.url || null
|
|
414
|
+
const modes = ['auto_register', 'custom']
|
|
415
|
+
// Carry every URL this server has used, exactly as `removeUserMcp` clears
|
|
416
|
+
// them: the sign-in may belong to a URL the server has since been edited
|
|
417
|
+
// away from, and copying only the current one would strand it.
|
|
418
|
+
const urls = [...new Set([url, saved.url, ...(Array.isArray(saved.usedUrls) ? saved.usedUrls : [])]
|
|
419
|
+
.filter((u) => typeof u === 'string' && u.trim()))]
|
|
420
|
+
|
|
421
|
+
for (const source of urls) {
|
|
422
|
+
for (const mode of modes) {
|
|
423
|
+
const from = oauthCredentialKey('user-mcp', oldName, source, mode)
|
|
424
|
+
const to = oauthCredentialKey('user-mcp', newName, source, mode)
|
|
425
|
+
const record = readOAuthRecord(from)
|
|
426
|
+
if (record && Object.keys(record).length > 0) writeOAuthRecord(to, record)
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
if (wasEnabled) {
|
|
431
|
+
const clientId = url ? readSavedOAuthClient('user-mcp', newName, url, 'custom').clientId : ''
|
|
432
|
+
// `saveConnectorAuth` reports failure both by returning `{ok:false}` and by
|
|
433
|
+
// throwing (e.g. a missing OAuth client id), so the rollback lives in one
|
|
434
|
+
// place that both paths reach.
|
|
435
|
+
const rollback = () => {
|
|
436
|
+
for (const source of urls) for (const mode of modes) deleteOAuthRecord(oauthCredentialKey('user-mcp', newName, source, mode))
|
|
437
|
+
}
|
|
438
|
+
let result
|
|
439
|
+
try {
|
|
440
|
+
result = saveConnectorAuth('user-mcp', newName, {
|
|
441
|
+
...payload,
|
|
442
|
+
// A cleared field stays cleared: falling back to the stored id would put
|
|
443
|
+
// the old client back into the live registration while the definition
|
|
444
|
+
// says empty, and the next toggle would fail on the mismatch.
|
|
445
|
+
oauthClientId: payload?.oauthClientId !== undefined ? payload.oauthClientId : (clientId || ''),
|
|
446
|
+
})
|
|
447
|
+
} catch (error) {
|
|
448
|
+
// Leave the old server untouched: a failed rename must not strand the
|
|
449
|
+
// user with neither name registered.
|
|
450
|
+
rollback()
|
|
451
|
+
throw error
|
|
452
|
+
}
|
|
453
|
+
if (!result || !result.ok) {
|
|
454
|
+
rollback()
|
|
455
|
+
return result
|
|
456
|
+
}
|
|
457
|
+
// Only drop the old registration when it is a different entry. Names are
|
|
458
|
+
// normalized but ids are slugified, so `a.dot` and `a-dot` share one id —
|
|
459
|
+
// unregistering by the old name would delete the entry just written and
|
|
460
|
+
// leave the server silently disabled.
|
|
461
|
+
if (getConnectorId('user-mcp', oldName) !== getConnectorId('user-mcp', newName)) {
|
|
462
|
+
unregisterConnector('user-mcp', oldName)
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
const toolsState = readMcpToolsState()
|
|
467
|
+
const oldKey = `user-mcp::${oldName}`
|
|
468
|
+
const newKey = `user-mcp::${newName}`
|
|
469
|
+
if (toolsState[oldKey] || toolsState[newKey]) {
|
|
470
|
+
const merged = { ...(toolsState[oldKey] || {}), ...(toolsState[newKey] || {}) }
|
|
471
|
+
if (Array.isArray(toolsState[oldKey]?.disabledTools)) merged.disabledTools = toolsState[oldKey].disabledTools
|
|
472
|
+
delete merged.cachedTools
|
|
473
|
+
toolsState[newKey] = merged
|
|
474
|
+
delete toolsState[oldKey]
|
|
475
|
+
writeMcpToolsState(toolsState)
|
|
476
|
+
}
|
|
477
|
+
MEMORY_TOOLS_CACHE.delete(oldKey)
|
|
478
|
+
MEMORY_TOOLS_CACHE.delete(newKey)
|
|
479
|
+
for (const source of urls) for (const mode of modes) deleteOAuthRecord(oauthCredentialKey('user-mcp', oldName, source, mode))
|
|
480
|
+
|
|
481
|
+
// Keep the whole edited form, not just the name: `/mcps/update` routes a
|
|
482
|
+
// rename here with the same body a plain save sends, so a rename that also
|
|
483
|
+
// edits command/url/args/env/headers must persist those edits — and on an
|
|
484
|
+
// enabled server the patch was already written from them, so storing the old
|
|
485
|
+
// record would silently revert the edit on the next toggle.
|
|
486
|
+
state.userMcps[idx] = userMcpConfig(newName, payload, saved)
|
|
487
|
+
writeState(state)
|
|
488
|
+
return { ok: true, name: newName, previousName: oldName }
|
|
489
|
+
}
|
|
490
|
+
|
|
313
491
|
// ── LSP server registration (cordis.patch.yml → @deepseek-ai/dsh-lsp-stdio) ──
|
|
314
492
|
//
|
|
315
493
|
// DSH exposes LSP as a capability seam with three packages:
|
|
@@ -1562,6 +1740,9 @@ export function syncPluginSkillsToDsh(pluginName) {
|
|
|
1562
1740
|
const srcSkillFile = join(srcSkillDir, 'SKILL.md')
|
|
1563
1741
|
if (existsSync(srcSkillFile)) {
|
|
1564
1742
|
const destSkillDir = join(dshSkills, entry.name)
|
|
1743
|
+
// A direct upload owns its junction/copy. A later plugin installation
|
|
1744
|
+
// must not replace it or delete the user's original through the link.
|
|
1745
|
+
if (isUploadedSkillTarget(destSkillDir)) continue
|
|
1565
1746
|
safeRmDir(destSkillDir)
|
|
1566
1747
|
copyDir(srcSkillDir, destSkillDir)
|
|
1567
1748
|
synced.push(entry.name)
|
|
@@ -1585,6 +1766,7 @@ export function removePluginSkillsFromDsh(pluginName) {
|
|
|
1585
1766
|
for (const entry of readdirSync(pluginSkillsDir, { withFileTypes: true })) {
|
|
1586
1767
|
if (entry.isDirectory()) {
|
|
1587
1768
|
const destSkillDir = join(dshSkills, entry.name)
|
|
1769
|
+
if (isUploadedSkillTarget(destSkillDir)) continue
|
|
1588
1770
|
safeRmDir(destSkillDir)
|
|
1589
1771
|
}
|
|
1590
1772
|
}
|
|
@@ -1592,7 +1774,7 @@ export function removePluginSkillsFromDsh(pluginName) {
|
|
|
1592
1774
|
|
|
1593
1775
|
// 2. Also remove any skills prefixed with plugin name or compiled subagent hub
|
|
1594
1776
|
const subagentHubName = `${pluginName}-agents`
|
|
1595
|
-
safeRmDir(join(dshSkills, subagentHubName))
|
|
1777
|
+
if (!isUploadedSkillTarget(join(dshSkills, subagentHubName))) safeRmDir(join(dshSkills, subagentHubName))
|
|
1596
1778
|
}
|
|
1597
1779
|
|
|
1598
1780
|
/**
|
|
@@ -1712,9 +1894,10 @@ export async function installPlugin({ sourceId, pluginName, refresh = false }) {
|
|
|
1712
1894
|
}
|
|
1713
1895
|
}
|
|
1714
1896
|
|
|
1715
|
-
// 2.5.
|
|
1897
|
+
// 2.5. Skill directories beside a root SKILL.md belong to that one skill.
|
|
1898
|
+
// Only expand them when the package has no root skill of its own.
|
|
1716
1899
|
try {
|
|
1717
|
-
for (const entry of readdirSync(target, { withFileTypes: true })) {
|
|
1900
|
+
if (!rootSkillMd) for (const entry of readdirSync(target, { withFileTypes: true })) {
|
|
1718
1901
|
if (
|
|
1719
1902
|
entry.isDirectory() &&
|
|
1720
1903
|
entry.name !== 'skills' &&
|
|
@@ -2019,13 +2202,14 @@ export async function findMarketRow(sourceId, pluginName) {
|
|
|
2019
2202
|
}
|
|
2020
2203
|
|
|
2021
2204
|
/**
|
|
2022
|
-
*
|
|
2023
|
-
* installed records written before the reader merged each
|
|
2024
|
-
*
|
|
2205
|
+
* The source's live marketplace row, read synchronously. Used as the last
|
|
2206
|
+
* fallback for installed records written before the reader merged each
|
|
2207
|
+
* plugin's own manifest, and as the identity source (`homepage`, `source`,
|
|
2208
|
+
* `icons`) the browse grid and connector rows render from. Null when absent.
|
|
2025
2209
|
*/
|
|
2026
|
-
function
|
|
2210
|
+
function findMarketRowSync(sourceId, pluginName) {
|
|
2027
2211
|
try {
|
|
2028
|
-
return readMarketplace(sourceId).find((r) => r.name === pluginName)
|
|
2212
|
+
return readMarketplace(sourceId).find((r) => r.name === pluginName) ?? null
|
|
2029
2213
|
} catch {
|
|
2030
2214
|
return null
|
|
2031
2215
|
}
|
|
@@ -2144,9 +2328,17 @@ export function installedDetails() {
|
|
|
2144
2328
|
const manifestAuthor = targetManifest?.author
|
|
2145
2329
|
? (typeof targetManifest.author === 'string' ? targetManifest.author : targetManifest.author.name)
|
|
2146
2330
|
: null
|
|
2147
|
-
const
|
|
2331
|
+
const marketRow = findMarketRowSync(rec.sourceId, rec.name)
|
|
2332
|
+
const author = rec.author || manifestAuthor || marketRow?.author
|
|
2333
|
+
// The browse list and the connector rows render the same plugin through the
|
|
2334
|
+
// same icon component, so they must be handed the same identity fields the
|
|
2335
|
+
// detail page merges in. Without these a plugin whose manifest declares no
|
|
2336
|
+
// icon falls back to "author name as a GitHub handle" and shows a stranger's
|
|
2337
|
+
// avatar while its own page shows the real logo.
|
|
2338
|
+
const declaredIcons = buildPluginIcons(targetManifest, { sourceId: rec.sourceId, name: rec.name, dir: existsSync(target) ? target : undefined, source: marketRow?.source })
|
|
2339
|
+
const hasDeclaredIcon = !!((declaredIcons.light.length) || (declaredIcons.dark.length))
|
|
2148
2340
|
const detail = existsSync(target) ? {
|
|
2149
|
-
icons:
|
|
2341
|
+
icons: hasDeclaredIcon ? declaredIcons : (marketRow?.icons || declaredIcons),
|
|
2150
2342
|
skills: listSkills(target),
|
|
2151
2343
|
agents: listAgents(target),
|
|
2152
2344
|
prompts: listPrompts(target),
|
|
@@ -2159,6 +2351,11 @@ export function installedDetails() {
|
|
|
2159
2351
|
...rec,
|
|
2160
2352
|
...detail,
|
|
2161
2353
|
author: author || rec.author,
|
|
2354
|
+
// Identity fields the icon chain reads. The detail page already merges
|
|
2355
|
+
// these from the marketplace row before rendering, which is why the same
|
|
2356
|
+
// plugin showed one icon inline and another on its own page.
|
|
2357
|
+
homepage: rec.homepage || marketRow?.homepage,
|
|
2358
|
+
source: rec.source || marketRow?.source,
|
|
2162
2359
|
skillCount: detail.skills.length,
|
|
2163
2360
|
agentCount: detail.agents.length,
|
|
2164
2361
|
promptCount: detail.prompts.length,
|
package/src/local.js
CHANGED
|
@@ -1,16 +1,34 @@
|
|
|
1
|
-
import { existsSync, readdirSync, statSync, cpSync, mkdirSync, writeFileSync, mkdtempSync } from 'node:fs'
|
|
1
|
+
import { existsSync, readdirSync, statSync, cpSync, copyFileSync, mkdirSync, writeFileSync, mkdtempSync, readFileSync } from 'node:fs'
|
|
2
2
|
import { join, basename, resolve, dirname, relative, isAbsolute } from 'node:path'
|
|
3
3
|
import { fileURLToPath } from 'node:url'
|
|
4
4
|
import { execFile } from 'node:child_process'
|
|
5
5
|
import { promisify } from 'node:util'
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
6
|
+
import { load as parseYaml } from 'js-yaml'
|
|
7
|
+
import { sourceCacheDir, readState, writeState, safeRmDir, slugify } from './store.js'
|
|
8
|
+
import { safeSegment, pluginPath } from './market.js'
|
|
9
|
+
import { parsePluginRowFromDir, parseMarketplaceFromDisk, listSkills, listAgents, readPluginManifest, invalidateMarketplaceCache, formatDisplayName } from './parser.js'
|
|
10
|
+
import { installUploadedSkills } from './skill-uploads.js'
|
|
9
11
|
|
|
10
12
|
const execFileAsync = promisify(execFile)
|
|
11
13
|
|
|
12
14
|
const TEMP_ROOT = () => join(sourceCacheDir('local'), '.temp')
|
|
13
15
|
|
|
16
|
+
/** True when `child` is `root` itself or sits inside it. */
|
|
17
|
+
function containsPath(root, child) {
|
|
18
|
+
const rel = relative(resolve(root), resolve(child))
|
|
19
|
+
return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith('..\\') && !rel.startsWith('../'))
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Copy a directory's entries into an existing directory, not into a subdir of it. */
|
|
23
|
+
function copyTreeContents(from, to) {
|
|
24
|
+
for (const entry of readdirSync(from, { withFileTypes: true })) {
|
|
25
|
+
const source = join(from, entry.name)
|
|
26
|
+
const target = join(to, entry.name)
|
|
27
|
+
if (entry.isDirectory()) cpSync(source, target, { recursive: true, force: true })
|
|
28
|
+
else if (entry.isFile()) copyFileSync(source, target)
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
14
32
|
/** Delete stale .temp artifacts (uploaded zips, inspect extraction dirs) older than 1h. */
|
|
15
33
|
function sweepTemp() {
|
|
16
34
|
const root = TEMP_ROOT()
|
|
@@ -73,6 +91,79 @@ export function resolvePluginDir(rootDir) {
|
|
|
73
91
|
return null
|
|
74
92
|
}
|
|
75
93
|
|
|
94
|
+
function skillFileMetadata(file) {
|
|
95
|
+
try {
|
|
96
|
+
const raw = readFileSync(file, 'utf8').replace(/^/, '')
|
|
97
|
+
const match = raw.match(/^---[ \t]*\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/)
|
|
98
|
+
const meta = match ? parseYaml(match[1]) : null
|
|
99
|
+
if (!meta || typeof meta !== 'object' || Array.isArray(meta)) return null
|
|
100
|
+
if (typeof meta.name !== 'string' || typeof meta.description !== 'string' || !meta.description.trim()) return null
|
|
101
|
+
return meta
|
|
102
|
+
} catch { return null }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function directSkillEntry(dir, fallbackName, file = null) {
|
|
106
|
+
const manifest = file ? skillFileMetadata(file) : skillFileMetadata(['SKILL.md', 'skill.md'].map(name => join(dir, name)).find(existsSync))
|
|
107
|
+
if (!manifest) return null
|
|
108
|
+
const name = manifest.name.trim()
|
|
109
|
+
if (!name) return null
|
|
110
|
+
return {
|
|
111
|
+
dir,
|
|
112
|
+
file: file || undefined,
|
|
113
|
+
singleFile: !!file,
|
|
114
|
+
row: {
|
|
115
|
+
id: `skills/${name}`, sourceId: 'skills-local', name,
|
|
116
|
+
displayName: typeof manifest.displayName === 'string' ? manifest.displayName : formatDisplayName(name),
|
|
117
|
+
description: manifest.description.trim(), version: '1.0.0', source: './',
|
|
118
|
+
},
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** A pure skill package is a root skill or one level of direct skill entries. */
|
|
123
|
+
function collectDirectSkills(dir, fallbackName) {
|
|
124
|
+
const rootFile = ['SKILL.md', 'skill.md'].map(name => join(dir, name)).find(existsSync)
|
|
125
|
+
if (rootFile) {
|
|
126
|
+
const entry = directSkillEntry(dir, fallbackName)
|
|
127
|
+
return entry ? [entry] : []
|
|
128
|
+
}
|
|
129
|
+
const root = existsSync(join(dir, 'skills')) ? join(dir, 'skills') : dir
|
|
130
|
+
const entries = []
|
|
131
|
+
try {
|
|
132
|
+
for (const child of readdirSync(root, { withFileTypes: true })) {
|
|
133
|
+
if (EXCLUDED_UPLOAD_DIRS.has(child.name) || child.name.startsWith('.')) continue
|
|
134
|
+
const path = join(root, child.name)
|
|
135
|
+
if (child.isDirectory()) {
|
|
136
|
+
const entry = directSkillEntry(path, child.name)
|
|
137
|
+
if (entry) entries.push(entry)
|
|
138
|
+
} else if (child.isFile() && /\.md$/i.test(child.name)) {
|
|
139
|
+
const entry = directSkillEntry(root, child.name.replace(/\.md$/i, ''), path)
|
|
140
|
+
if (entry) entries.push(entry)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
} catch {}
|
|
144
|
+
return entries
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const EXCLUDED_UPLOAD_DIRS = new Set(['node_modules', '__pycache__', 'agents', 'commands', 'hooks', 'docs', 'assets'])
|
|
148
|
+
|
|
149
|
+
function isPureSkillPackage(dir) {
|
|
150
|
+
return ![
|
|
151
|
+
'.claude-plugin/plugin.json', '.codex-plugin/plugin.json', 'plugin.json', 'package.json',
|
|
152
|
+
'mcp.json', '.mcp.json', 'server.json', 'agents', 'commands',
|
|
153
|
+
].some(path => existsSync(join(dir, path)))
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function marketSourceName(dir, fallbackName) {
|
|
157
|
+
for (const path of ['.claude-plugin/marketplace.json', '.agents/plugins/marketplace.json', 'marketplace.json']) {
|
|
158
|
+
try {
|
|
159
|
+
const raw = JSON.parse(readFileSync(join(dir, path), 'utf8'))
|
|
160
|
+
if (typeof raw.name === 'string' && raw.name.trim()) return raw.name.trim()
|
|
161
|
+
if (typeof raw.title === 'string' && raw.title.trim()) return raw.title.trim()
|
|
162
|
+
} catch {}
|
|
163
|
+
}
|
|
164
|
+
return formatDisplayName(fallbackName) || '本地市场'
|
|
165
|
+
}
|
|
166
|
+
|
|
76
167
|
export async function inspectLocalPlugin(rawPath) {
|
|
77
168
|
let targetPath = String(rawPath || '').trim().replace(/^["']|["']$/g, '')
|
|
78
169
|
if (/^file:/i.test(targetPath)) targetPath = fileURLToPath(targetPath)
|
|
@@ -109,9 +200,16 @@ export async function inspectLocalPlugin(rawPath) {
|
|
|
109
200
|
|
|
110
201
|
const rawFallbackName = (isZip && effectiveDir === tempExtractDir ? basename(targetPath).replace(/\.(zip|tgz|tar\.gz)$/i, '') : basename(effectiveDir)).toLowerCase().replace(/[^a-z0-9_-]/g, '') || 'local-plugin'
|
|
111
202
|
const fallbackName = safeSegment(rawFallbackName, 'plugin name')
|
|
112
|
-
|
|
113
|
-
|
|
203
|
+
// Recognition follows the package formats, not the upload transport:
|
|
204
|
+
// marketplace -> Claude -> Codex -> pure skills. Claude/Codex precedence in
|
|
205
|
+
// readPluginManifest is shared with the existing source installation path.
|
|
206
|
+
const isMarket = ['.claude-plugin/marketplace.json', '.agents/plugins/marketplace.json', 'marketplace.json'].some((p) => existsSync(join(effectiveDir, p)))
|
|
207
|
+
const pureSkills = !isMarket && isPureSkillPackage(effectiveDir)
|
|
208
|
+
const directSkills = pureSkills ? collectDirectSkills(effectiveDir, fallbackName) : []
|
|
209
|
+
const singleFile = !isZip && statSync(targetPath).isFile()
|
|
210
|
+
const kind = isMarket ? 'marketplace' : pureSkills ? 'skills' : existsSync(join(effectiveDir, '.claude-plugin', 'plugin.json')) ? 'claude' : existsSync(join(effectiveDir, '.codex-plugin', 'plugin.json')) ? 'codex' : 'plugin'
|
|
114
211
|
let entries
|
|
212
|
+
if (kind === 'skills') entries = directSkills
|
|
115
213
|
try {
|
|
116
214
|
if (isMarket) {
|
|
117
215
|
entries = parseMarketplaceFromDisk('local-upload', effectiveDir).map((row) => {
|
|
@@ -121,7 +219,7 @@ export async function inspectLocalPlugin(rawPath) {
|
|
|
121
219
|
if (rel.startsWith('..') || isAbsolute(rel) || !isPluginDir(dir)) throw new Error(`市场条目「${row.name}」缺少有效的本地插件目录`)
|
|
122
220
|
return { row, dir }
|
|
123
221
|
})
|
|
124
|
-
} else {
|
|
222
|
+
} else if (kind !== 'skills') {
|
|
125
223
|
const row = parsePluginRowFromDir(effectiveDir, fallbackName, 'local')
|
|
126
224
|
entries = row ? [{ row, dir: effectiveDir }] : []
|
|
127
225
|
if (!row) {
|
|
@@ -149,6 +247,7 @@ export async function inspectLocalPlugin(rawPath) {
|
|
|
149
247
|
const agents = entries.flatMap((e) => listAgents(e.dir))
|
|
150
248
|
|
|
151
249
|
const duplicate = entries.find((e) => existsSync(join(sourceCacheDir('local'), safeSegment(e.row.name, 'plugin name'))))
|
|
250
|
+
|| (kind === 'skills' ? entries.find((e) => (readState().uploadedSkills || []).some(record => record.name === e.row.name)) : undefined)
|
|
152
251
|
const localDest = duplicate ? join(sourceCacheDir('local'), duplicate.row.name) : join(sourceCacheDir('local'), cleanPluginName)
|
|
153
252
|
let exists = false
|
|
154
253
|
let existingVersion = undefined
|
|
@@ -165,6 +264,7 @@ export async function inspectLocalPlugin(rawPath) {
|
|
|
165
264
|
|
|
166
265
|
return {
|
|
167
266
|
ok: true,
|
|
267
|
+
kind,
|
|
168
268
|
effectiveDir,
|
|
169
269
|
tempExtractDir,
|
|
170
270
|
entries,
|
|
@@ -180,6 +280,84 @@ export async function inspectLocalPlugin(rawPath) {
|
|
|
180
280
|
}
|
|
181
281
|
}
|
|
182
282
|
|
|
283
|
+
/**
|
|
284
|
+
* Pure skill packages go straight into the Skills tab instead of the plugin
|
|
285
|
+
* install pipeline: no mirrored copy, no agents/commands conversion.
|
|
286
|
+
*/
|
|
287
|
+
export async function importLocalSkills(rawPath, { overwrite = false } = {}) {
|
|
288
|
+
const inspectRes = await inspectLocalPlugin(rawPath)
|
|
289
|
+
if (!inspectRes.ok) throw new Error(inspectRes.error)
|
|
290
|
+
if (inspectRes.kind !== 'skills') throw new Error('该内容不是纯 Skills 包')
|
|
291
|
+
const { tempExtractDir, entries, singleFile } = inspectRes
|
|
292
|
+
try {
|
|
293
|
+
// A bare SKILL.md upload is one flat skill. When the folder it came from is
|
|
294
|
+
// a collection, the walk up yields several entries, and flattening those
|
|
295
|
+
// would drop each skill's assets along with its directory.
|
|
296
|
+
const installed = installUploadedSkills(entries, { overwrite, singleFile: singleFile && entries.length === 1 })
|
|
297
|
+
return { ok: true, sourceId: 'skills-local', skills: installed, kind: 'skills' }
|
|
298
|
+
} finally {
|
|
299
|
+
if (tempExtractDir) safeRmDir(tempExtractDir)
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* An uploaded marketplace becomes its own plugin source tab: its declared
|
|
305
|
+
* plugins are copied under the source cache and listed by the normal market
|
|
306
|
+
* reader, so install/update/uninstall behave exactly like a Git source.
|
|
307
|
+
*/
|
|
308
|
+
export async function importLocalMarketplace(rawPath, { sourceName = '', overwrite = false } = {}) {
|
|
309
|
+
const inspectRes = await inspectLocalPlugin(rawPath)
|
|
310
|
+
if (!inspectRes.ok) throw new Error(inspectRes.error)
|
|
311
|
+
if (inspectRes.kind !== 'marketplace') throw new Error('该内容不是插件市场')
|
|
312
|
+
const { effectiveDir, tempExtractDir, entries } = inspectRes
|
|
313
|
+
const label = marketSourceName(effectiveDir, basename(effectiveDir))
|
|
314
|
+
const name = String(sourceName || '').trim().slice(0, 30) || label
|
|
315
|
+
const sourceId = `local-${slugify(label) || 'market'}`
|
|
316
|
+
const dest = sourceCacheDir(sourceId)
|
|
317
|
+
const state = readState()
|
|
318
|
+
if (existsSync(dest) && !overwrite && state.sources.some(source => source.id === sourceId)) {
|
|
319
|
+
if (tempExtractDir) safeRmDir(tempExtractDir)
|
|
320
|
+
throw new Error(`已存在同名插件市场「${label}」`)
|
|
321
|
+
}
|
|
322
|
+
// The destination is wiped below, so a source that is or contains it would be
|
|
323
|
+
// destroyed along with the copy that is still being read from.
|
|
324
|
+
if (containsPath(dest, effectiveDir) || containsPath(effectiveDir, dest)) {
|
|
325
|
+
if (tempExtractDir) safeRmDir(tempExtractDir)
|
|
326
|
+
throw new Error('导入源与插件市场存储目录重叠,请从独立文件夹导入')
|
|
327
|
+
}
|
|
328
|
+
try {
|
|
329
|
+
safeRmDir(dest)
|
|
330
|
+
mkdirSync(dest, { recursive: true })
|
|
331
|
+
for (const { row, dir } of entries) {
|
|
332
|
+
// Keep each plugin on the path its manifest declares: a rewritten layout
|
|
333
|
+
// (`plugins/<name>`) would break `./external_plugins/x` and `./`, and the
|
|
334
|
+
// reader resolves sources against the copied manifest after a restart.
|
|
335
|
+
const target = pluginPath(dest, `./${row.source.replace(/^\.\//, '')}`)
|
|
336
|
+
mkdirSync(dirname(target), { recursive: true })
|
|
337
|
+
if (resolve(target) !== resolve(dest)) cpSync(dir, target, { recursive: true, force: true })
|
|
338
|
+
else copyTreeContents(dir, target)
|
|
339
|
+
}
|
|
340
|
+
// Carry the marketplace manifest itself so the standard reader finds the
|
|
341
|
+
// same rows on the next start, not only during this upload.
|
|
342
|
+
for (const relativePath of ['.claude-plugin/marketplace.json', '.agents/plugins/marketplace.json', 'marketplace.json']) {
|
|
343
|
+
const file = join(effectiveDir, relativePath)
|
|
344
|
+
if (!existsSync(file)) continue
|
|
345
|
+
const out = join(dest, relativePath)
|
|
346
|
+
mkdirSync(dirname(out), { recursive: true })
|
|
347
|
+
copyFileSync(file, out)
|
|
348
|
+
}
|
|
349
|
+
} finally {
|
|
350
|
+
if (tempExtractDir) safeRmDir(tempExtractDir)
|
|
351
|
+
}
|
|
352
|
+
if (!state.sources.some(source => source.id === sourceId)) {
|
|
353
|
+
state.sources.push({ id: sourceId, name, url: `local-market://${sourceId}`, addedAt: Date.now() })
|
|
354
|
+
writeState(state)
|
|
355
|
+
}
|
|
356
|
+
invalidateMarketplaceCache(sourceId)
|
|
357
|
+
return { ok: true, kind: 'marketplace', sourceId, source: state.sources.find(source => source.id === sourceId), plugins: entries.map(entry => entry.row) }
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Legacy plugin-pipeline import; the UI routes pure skill packages elsewhere. */
|
|
183
361
|
export async function importLocalPlugin({ path: rawPath, overwrite = false, sourceName = '' }) {
|
|
184
362
|
const inspectRes = await inspectLocalPlugin(rawPath)
|
|
185
363
|
if (!inspectRes.ok) {
|
package/src/market.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
import { execFile } from 'node:child_process'
|
|
9
9
|
import { existsSync, mkdirSync, readFileSync } from 'node:fs'
|
|
10
10
|
import { join, resolve, relative, isAbsolute } from 'node:path'
|
|
11
|
-
import { sourceCacheDir, safeRmDir } from './store.js'
|
|
11
|
+
import { sourceCacheDir, safeRmDir, readState } from './store.js'
|
|
12
12
|
|
|
13
13
|
const SEGMENT_RE = /^[a-z0-9][a-z0-9._-]*$/i
|
|
14
14
|
|
|
@@ -100,7 +100,7 @@ function runGit(args, cwd) {
|
|
|
100
100
|
export async function ensureSourceCloned(sourceId, url) {
|
|
101
101
|
safeSegment(sourceId, 'source id')
|
|
102
102
|
const dir = sourceCacheDir(sourceId)
|
|
103
|
-
if (sourceId === 'local') {
|
|
103
|
+
if (sourceId === 'local' || /^local-(?:upload|market):\/\//i.test(String(url || ''))) {
|
|
104
104
|
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
|
|
105
105
|
return dir
|
|
106
106
|
}
|
|
@@ -138,7 +138,7 @@ export async function ensureSourceCloned(sourceId, url) {
|
|
|
138
138
|
/** git pull in a source cache dir (waits for any in-flight clone of the same source). */
|
|
139
139
|
export async function pullSource(sourceId) {
|
|
140
140
|
safeSegment(sourceId, 'source id')
|
|
141
|
-
if (sourceId === 'local') return
|
|
141
|
+
if (sourceId === 'local' || /^local-(?:upload|market):\/\//i.test(String(readState().sources.find(source => source.id === sourceId)?.url || ''))) return
|
|
142
142
|
const dir = sourceCacheDir(sourceId)
|
|
143
143
|
const inFlight = GIT_LOCKS.get(`src:${sourceId}`)
|
|
144
144
|
if (inFlight) {
|
package/src/oauth-store.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
2
2
|
import { dirname, join } from 'node:path'
|
|
3
3
|
import { execFileSync } from 'node:child_process'
|
|
4
4
|
import { randomBytes } from 'node:crypto'
|
|
@@ -84,3 +84,14 @@ export function saveOAuthClientCredentials(key, client) {
|
|
|
84
84
|
}
|
|
85
85
|
writeOAuthRecord(key, record)
|
|
86
86
|
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Delete a credential record outright. Used when the connector it belongs to is
|
|
90
|
+
* removed: leaving the file behind would resurrect a stale sign-in if a server
|
|
91
|
+
* of the same name were added again with the same URL and OAuth mode.
|
|
92
|
+
*/
|
|
93
|
+
export function deleteOAuthRecord(key) {
|
|
94
|
+
const file = oauthCredentialPath(key)
|
|
95
|
+
RECORD_CACHE.delete(file)
|
|
96
|
+
try { rmSync(file, { force: true }) } catch {}
|
|
97
|
+
}
|