universal-plugin-hub 0.0.0-stage → 1.0.5

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/parser.js ADDED
@@ -0,0 +1,1038 @@
1
+ /**
2
+ * Universal Agent Plugin Marketplace Parser.
3
+ *
4
+ * Supports multiple AI Agent ecosystem plugin & marketplace specifications:
5
+ * 1. Claude Code Marketplace (.claude-plugin/marketplace.json, marketplace.json, claude-plugins.json)
6
+ * 2. MCP Server Registries & Catalogs (mcp-servers.json, servers.json, server.json, mcp.json)
7
+ * 3. Agent Skills / Agent Card Specifications (.well-known/agent-card.json, registry.json, catalog.json, plugins.json)
8
+ * 4. Multi-plugin Monorepos (plugins/*, skills/*, packages/*, tools/*, extensions/*)
9
+ * 5. Single-plugin Standalone Repositories (root SKILL.md, plugin.json, skills/, commands/, agents/, .cursorrules)
10
+ */
11
+ import { existsSync, readFileSync, readdirSync, statSync, mkdirSync, copyFileSync } from 'node:fs'
12
+ import { join, basename, dirname, isAbsolute } from 'node:path'
13
+ import { load as parseYaml } from 'js-yaml'
14
+ import { sourceCacheDir, installedDir } from './store.js'
15
+ import { safeSegment, pluginPath, sourceRepositoryDir } from './market.js'
16
+ import { parseAgentDefinition } from './agents-map.js'
17
+ import { buildPluginIcons } from './icons.js'
18
+
19
+ const DIR_PARSER_CACHE = new Map()
20
+ const DIR_PARSER_CACHE_TTL = 20000 // 20s TTL for file scanning
21
+
22
+ export function invalidateParserCaches() {
23
+ DIR_PARSER_CACHE.clear()
24
+ }
25
+
26
+ export function formatDisplayName(name) {
27
+ if (!name) return ''
28
+ return name.replace(/[-_]+/g, ' ').replace(/^\w/, (c) => c.toUpperCase())
29
+ }
30
+
31
+ function extractMdDescription(text) {
32
+ if (!text) return ''
33
+ const fmMatch = text.match(/^---\r?\n([\s\S]*?)\r?\n---/)
34
+ if (fmMatch) {
35
+ try {
36
+ const parsed = parseYaml(fmMatch[1])
37
+ if (parsed && typeof parsed === 'object') {
38
+ const desc = parsed.description || parsed.desc || parsed.summary || parsed.about
39
+ if (typeof desc === 'string' && desc.trim()) {
40
+ return desc.trim().replace(/\r?\n+/g, ' ').slice(0, 300)
41
+ }
42
+ }
43
+ } catch {}
44
+ const descMatch = fmMatch[1].match(/^description:\s*(.+)$/m)
45
+ if (descMatch) {
46
+ const val = descMatch[1].trim().replace(/^["']|["']$/g, '')
47
+ if (val && val !== '>' && val !== '|' && val !== '>-' && val !== '|-') {
48
+ return val.slice(0, 300)
49
+ }
50
+ }
51
+ }
52
+ const lines = text.split(/\r?\n/)
53
+ for (const line of lines) {
54
+ const trimmed = line.trim()
55
+ if (
56
+ trimmed &&
57
+ !trimmed.startsWith('#') &&
58
+ !trimmed.startsWith('---') &&
59
+ !trimmed.startsWith('![') &&
60
+ !trimmed.startsWith('>') &&
61
+ !trimmed.startsWith('```')
62
+ ) {
63
+ return trimmed.slice(0, 300)
64
+ }
65
+ }
66
+ return ''
67
+ }
68
+
69
+ function normalizeRow(row, sourceId, dir) {
70
+ if (!row) return null
71
+ const name = typeof row.name === 'string' ? row.name : (typeof row.identifier === 'string' ? row.identifier : '')
72
+ if (!name || !/^[a-z0-9][a-z0-9._-]*$/i.test(name)) return null
73
+ const cleanName = name.toLowerCase()
74
+
75
+ const author = row.author && typeof row.author === 'object'
76
+ ? row.author.name
77
+ : (typeof row.author === 'string' ? row.author : undefined)
78
+
79
+ const meta = row.meta || {}
80
+ const displayName = row.displayName || row.interface?.displayName || meta.title || formatDisplayName(name)
81
+ const description = typeof row.description === 'string'
82
+ ? row.description
83
+ : (row.interface?.shortDescription || meta.description || '')
84
+
85
+ const source = row.source?.source === 'local' ? row.source.path : (row.source || './')
86
+ if (row.source?.source === 'local' && (typeof source !== 'string' || !source.startsWith('./'))) return null
87
+
88
+ return {
89
+ id: `${sourceId}/${cleanName}`,
90
+ sourceId,
91
+ name: cleanName,
92
+ displayName,
93
+ description,
94
+ author: typeof author === 'string' ? author : (meta.author || undefined),
95
+ version: typeof row.version === 'string' ? row.version : (meta.version || undefined),
96
+ category: typeof row.category === 'string' ? row.category : (meta.category || undefined),
97
+ homepage: typeof row.homepage === 'string' ? row.homepage : (meta.homepage || undefined),
98
+ source,
99
+ local: typeof source === 'string' && (source === './' || source.startsWith('./')),
100
+ lspServers: row.lspServers || undefined,
101
+ icons: buildPluginIcons(row, { sourceId, name: cleanName, dir, source }),
102
+ }
103
+ }
104
+
105
+ const MARKETPLACE_CACHE = new Map()
106
+ const MARKETPLACE_CACHE_TTL = 30000 // 30 seconds
107
+
108
+ export function invalidateMarketplaceCache(sourceId) {
109
+ if (sourceId) {
110
+ MARKETPLACE_CACHE.delete(sourceId)
111
+ } else {
112
+ MARKETPLACE_CACHE.clear()
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Universal Marketplace Reader.
118
+ * Inspects a source repository cache and extracts all discoverable plugins.
119
+ */
120
+ export function readMarketplace(sourceId) {
121
+ safeSegment(sourceId, 'source id')
122
+ const cache = sourceCacheDir(sourceId)
123
+ if (!existsSync(cache)) return []
124
+
125
+ const now = Date.now()
126
+ const cached = MARKETPLACE_CACHE.get(sourceId)
127
+ if (cached && (now - cached.time < MARKETPLACE_CACHE_TTL)) {
128
+ return cached.data
129
+ }
130
+
131
+ const rows = parseMarketplaceFromDisk(sourceId, cache)
132
+ MARKETPLACE_CACHE.set(sourceId, { time: now, data: rows })
133
+ return rows
134
+ }
135
+
136
+ export function parsePluginRowFromDir(entryDir, fallbackName, sourceId) {
137
+ const rootSkill = existsSync(join(entryDir, 'SKILL.md')) || existsSync(join(entryDir, 'skill.md'))
138
+ const hasSkill = rootSkill || existsSync(join(entryDir, 'skills')) || existsSync(join(entryDir, 'commands'))
139
+ const hasManifest = existsSync(join(entryDir, '.codex-plugin', 'plugin.json')) || existsSync(join(entryDir, '.claude-plugin', 'plugin.json')) || existsSync(join(entryDir, 'plugin.json')) || existsSync(join(entryDir, 'package.json'))
140
+ const hasMcp = existsSync(join(entryDir, 'mcp.json')) || existsSync(join(entryDir, '.mcp.json')) || existsSync(join(entryDir, 'server.json'))
141
+ const hasAgents = existsSync(join(entryDir, 'agents'))
142
+ if (!hasSkill && !hasManifest && !hasMcp && !hasAgents) return null
143
+
144
+ let displayName = formatDisplayName(fallbackName)
145
+ let description = ''
146
+ let version = '1.0.0'
147
+ let author = undefined
148
+ let name = fallbackName
149
+
150
+ const manifest = readPluginManifest(entryDir, false)
151
+ if (manifest) {
152
+ if (manifest.name) name = manifest.name
153
+ displayName = manifest.displayName || formatDisplayName(name)
154
+ if (manifest.description) description = manifest.description
155
+ if (manifest.version) version = manifest.version
156
+ if (manifest.author) author = typeof manifest.author === 'string' ? manifest.author : manifest.author?.name
157
+ } else if (rootSkill) {
158
+ try {
159
+ const raw = readFileSync(join(entryDir, existsSync(join(entryDir, 'SKILL.md')) ? 'SKILL.md' : 'skill.md'), 'utf8')
160
+ const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/)
161
+ const meta = match ? parseYaml(match[1]) : null
162
+ if (typeof meta?.name === 'string') name = meta.name
163
+ displayName = formatDisplayName(name)
164
+ description = extractMdDescription(raw)
165
+ } catch {}
166
+ } else if (existsSync(join(entryDir, 'README.md'))) {
167
+ try { description = extractMdDescription(readFileSync(join(entryDir, 'README.md'), 'utf8')) } catch {}
168
+ }
169
+
170
+ return normalizeRow({
171
+ ...manifest,
172
+ name,
173
+ displayName,
174
+ description,
175
+ version,
176
+ author,
177
+ source: `./${fallbackName}`,
178
+ }, sourceId, entryDir)
179
+ }
180
+
181
+ export function parseMarketplaceFromDisk(sourceId, cache) {
182
+ // 1. Check Multi-Plugin Manifest Candidates
183
+ const manifestCandidates = [
184
+ join(cache, '.agents', 'plugins', 'marketplace.json'),
185
+ join(cache, '.claude-plugin', 'marketplace.json'),
186
+ join(cache, 'marketplace.json'),
187
+ join(cache, 'claude-plugins.json'),
188
+ join(cache, 'registry.json'),
189
+ join(cache, 'plugins.json'),
190
+ join(cache, 'catalog.json'),
191
+ join(cache, 'market.json'),
192
+ join(cache, 'mcp-servers.json'),
193
+ join(cache, 'servers.json'),
194
+ join(cache, 'index.json'),
195
+ join(cache, '.well-known', 'agent-card.json'),
196
+ ]
197
+
198
+ for (const manifestPath of manifestCandidates) {
199
+ if (existsSync(manifestPath)) {
200
+ try {
201
+ const content = JSON.parse(readFileSync(manifestPath, 'utf8'))
202
+ // Case A: Claude / standard manifest with plugins array
203
+ if (Array.isArray(content.plugins)) {
204
+ const rows = content.plugins.map((r) => {
205
+ const source = r.source?.source === 'local' ? r.source.path : r.source
206
+ let manifest = null
207
+ let dir = null
208
+ if (typeof source === 'string' && source.startsWith('./')) {
209
+ dir = pluginPath(cache, source)
210
+ } else if (source && typeof source === 'object' && r.name) {
211
+ dir = sourceRepositoryDir(cache, source) || pluginContentDir(sourceId, r.name, source, false)
212
+ }
213
+ if (dir) manifest = readPluginManifest(dir, false)
214
+ return normalizeRow({ ...manifest, ...r,
215
+ displayName: r.displayName || r.interface?.displayName || manifest?.displayName,
216
+ description: r.description || r.interface?.shortDescription || manifest?.description,
217
+ }, sourceId, dir)
218
+ }).filter(Boolean)
219
+ if (rows.length > 0) return rows
220
+ }
221
+ // Case B: Direct array of plugin descriptors
222
+ if (Array.isArray(content)) {
223
+ const rows = content.map((r) => normalizeRow(r, sourceId)).filter(Boolean)
224
+ if (rows.length > 0) return rows
225
+ }
226
+ // Case C: MCP Servers dictionary (mcpServers or servers object)
227
+ const mcpDict = (content.mcpServers && typeof content.mcpServers === 'object')
228
+ ? content.mcpServers
229
+ : ((content.servers && typeof content.servers === 'object') ? content.servers : null)
230
+ if (mcpDict) {
231
+ const rows = []
232
+ for (const [srvName, srvCfg] of Object.entries(mcpDict)) {
233
+ rows.push(normalizeRow({
234
+ name: srvName,
235
+ displayName: srvCfg.title || formatDisplayName(srvName),
236
+ description: srvCfg.description || `MCP Server: ${srvName}`,
237
+ author: srvCfg.author || content.author || 'MCP',
238
+ category: 'mcp',
239
+ source: './',
240
+ }, sourceId))
241
+ }
242
+ if (rows.filter(Boolean).length > 0) return rows.filter(Boolean)
243
+ }
244
+ } catch {
245
+ // Continue fallback search on malformed JSON
246
+ }
247
+ }
248
+ }
249
+
250
+ // 2. Local source direct subdirectories discovery
251
+ if (sourceId === 'local') {
252
+ const localRows = []
253
+ if (existsSync(cache)) {
254
+ try {
255
+ for (const entry of readdirSync(cache, { withFileTypes: true })) {
256
+ if (entry.isDirectory() && !entry.name.startsWith('.')) {
257
+ const row = parsePluginRowFromDir(join(cache, entry.name), entry.name, 'local')
258
+ if (row) localRows.push(row)
259
+ }
260
+ }
261
+ } catch {}
262
+ }
263
+ return localRows
264
+ }
265
+
266
+ // Explicit plugin manifests describe the whole package, including its skills.
267
+ if (existsSync(join(cache, '.codex-plugin', 'plugin.json')) || existsSync(join(cache, '.claude-plugin', 'plugin.json'))) {
268
+ const row = parsePluginRowFromDir(cache, sourceId, sourceId)
269
+ if (row) return [{ ...row, source: './' }]
270
+ }
271
+ if (existsSync(join(cache, 'SKILL.md')) || existsSync(join(cache, 'skill.md'))) {
272
+ const row = parsePluginRowFromDir(cache, sourceId, sourceId)
273
+ if (row) return [{ ...row, source: './' }]
274
+ }
275
+
276
+ // 3. Monorepo subdirectories auto-discovery (plugins/*, skills/*, packages/*, tools/*, extensions/*)
277
+ const monoDirs = ['plugins', 'skills', 'packages', 'tools', 'extensions']
278
+ const monoRows = []
279
+ for (const sub of monoDirs) {
280
+ const subRoot = join(cache, sub)
281
+ if (existsSync(subRoot)) {
282
+ try {
283
+ for (const entry of readdirSync(subRoot, { withFileTypes: true })) {
284
+ if (entry.isDirectory()) {
285
+ const row = parsePluginRowFromDir(join(subRoot, entry.name), entry.name, sourceId)
286
+ if (row) {
287
+ row.source = `./${sub}/${entry.name}`
288
+ monoRows.push(row)
289
+ }
290
+ }
291
+ }
292
+ } catch {}
293
+ }
294
+ }
295
+ if (monoRows.filter(Boolean).length > 0) return monoRows.filter(Boolean)
296
+
297
+ // 3. Single Standalone Root Plugin Repository
298
+ const rootSkillMd = join(cache, 'SKILL.md')
299
+ const rootSkillsDir = join(cache, 'skills')
300
+ const rootCommandsDir = join(cache, 'commands')
301
+ const rootAgentsDir = join(cache, 'agents')
302
+ const rootHooksDir = join(cache, 'hooks')
303
+ const rootMcp = join(cache, 'mcp.json')
304
+ const rootDotMcp = join(cache, '.mcp.json')
305
+ const rootServerJson = join(cache, 'server.json')
306
+ const rootPluginJson = join(cache, '.claude-plugin', 'plugin.json')
307
+ const rootCodexPluginJson = join(cache, '.codex-plugin', 'plugin.json')
308
+ const rootDirectPluginJson = join(cache, 'plugin.json')
309
+ const rootCursorRules = join(cache, '.cursor', 'rules')
310
+ const rootCursorRulesFile = join(cache, '.cursorrules')
311
+ const rootPkgJson = join(cache, 'package.json')
312
+
313
+ const isRootPlugin = existsSync(rootSkillMd)
314
+ || existsSync(rootSkillsDir)
315
+ || existsSync(rootCommandsDir)
316
+ || existsSync(rootAgentsDir)
317
+ || existsSync(rootHooksDir)
318
+ || existsSync(rootMcp)
319
+ || existsSync(rootDotMcp)
320
+ || existsSync(rootServerJson)
321
+ || existsSync(rootPluginJson)
322
+ || existsSync(rootCodexPluginJson)
323
+ || existsSync(rootDirectPluginJson)
324
+ || existsSync(rootCursorRules)
325
+ || existsSync(rootCursorRulesFile)
326
+ || existsSync(rootPkgJson)
327
+
328
+ if (isRootPlugin) {
329
+ let name = sourceId
330
+ let displayName = formatDisplayName(sourceId)
331
+ let description = ''
332
+ let version = '1.0.0'
333
+ let author = undefined
334
+
335
+ const manifest = readPluginManifest(cache)
336
+ if (manifest) {
337
+ if (manifest.name) name = manifest.name
338
+ if (manifest.displayName) displayName = manifest.displayName
339
+ if (manifest.description) description = manifest.description
340
+ if (manifest.version) version = manifest.version
341
+ if (manifest.author) author = typeof manifest.author === 'string' ? manifest.author : manifest.author.name
342
+ } else if (existsSync(rootSkillMd)) {
343
+ try {
344
+ description = extractMdDescription(readFileSync(rootSkillMd, 'utf8'))
345
+ } catch {}
346
+ } else if (existsSync(join(cache, 'README.md'))) {
347
+ try {
348
+ description = extractMdDescription(readFileSync(join(cache, 'README.md'), 'utf8'))
349
+ } catch {}
350
+ }
351
+
352
+ return [normalizeRow({
353
+ ...manifest,
354
+ name,
355
+ displayName,
356
+ description,
357
+ version,
358
+ author,
359
+ source: './',
360
+ }, sourceId, cache)].filter(Boolean)
361
+ }
362
+
363
+ return []
364
+ }
365
+
366
+ /** Resolve the directory that holds a plugin's content (cache or remote checkout). */
367
+ export function pluginContentDir(sourceId, pluginName, source, preferInstalled = true) {
368
+ safeSegment(sourceId, 'source id')
369
+ safeSegment(pluginName, 'plugin name')
370
+
371
+ // Check if already installed (installed/ tree, not the market/ cache)
372
+ const installed = installedDir(pluginName)
373
+ if (preferInstalled && existsSync(installed)) return installed
374
+
375
+ // Check if in local source cache (root or subdir)
376
+ if (typeof source === 'string' && (source === './' || source === '.' || source === '')) {
377
+ const dir = sourceCacheDir(sourceId)
378
+ return existsSync(dir) ? dir : null
379
+ }
380
+ if (typeof source === 'string' && source.startsWith('./')) {
381
+ const rel = source.replace(/^\.\//, '')
382
+ const dir = pluginPath(sourceCacheDir(sourceId), `./${rel}`)
383
+ return existsSync(dir) ? dir : null
384
+ }
385
+
386
+ // Check if in remote git cache
387
+ if (source && typeof source === 'object' && (source.source === 'url' || source.source === 'git-subdir')) {
388
+ if (typeof source.url === 'string') {
389
+ const ownDir = sourceRepositoryDir(sourceCacheDir(sourceId), source)
390
+ if (ownDir) return ownDir
391
+ const clean = String(source.url).replace(/^https?:\/\//, '').replace(/\.git$/, '')
392
+ const remoteKey = clean.replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/g, '').toLowerCase() || 'repo'
393
+ const checkout = join(sourceCacheDir('remote'), remoteKey)
394
+ const dir = source.path ? pluginPath(checkout, source.path) : checkout
395
+ return existsSync(dir) ? dir : null
396
+ }
397
+ }
398
+
399
+ // Fallback check in source root
400
+ const fallback = sourceCacheDir(sourceId)
401
+ return existsSync(fallback) ? fallback : null
402
+ }
403
+
404
+ /** Read manifest descriptor from candidate paths in a plugin directory. */
405
+ export function readPluginManifest(dir, includeParent = true) {
406
+ const rootManifest = join(dir, 'plugin.json')
407
+ let portable = false
408
+ try {
409
+ const root = JSON.parse(readFileSync(rootManifest, 'utf8'))
410
+ portable = /^https:\/\/agent-plugins\.org\//.test(root.$schema || '') || Boolean(root.extensions?.['com.openai'])
411
+ } catch {}
412
+ const candidates = [
413
+ ...(portable ? [rootManifest] : []),
414
+ join(dir, '.codex-plugin', 'plugin.json'),
415
+ join(dir, '.claude-plugin', 'plugin.json'),
416
+ join(dir, '.claude-plugin', 'marketplace.json'),
417
+ rootManifest,
418
+ join(dir, 'manifest.json'),
419
+ join(dir, 'server.json'),
420
+ join(dir, 'package.json'),
421
+ ...(includeParent ? [join(dir, '..', '.claude-plugin', 'plugin.json'),
422
+ join(dir, '..', '.claude-plugin', 'marketplace.json'),
423
+ join(dir, '..', 'plugin.json'),
424
+ join(dir, '..', 'manifest.json')] : []),
425
+ ]
426
+
427
+ for (const p of candidates) {
428
+ if (existsSync(p)) {
429
+ try {
430
+ const raw = JSON.parse(readFileSync(p, 'utf8'))
431
+ if (p.endsWith('package.json')) {
432
+ if (raw['claude-plugin']) return raw['claude-plugin']
433
+ return {
434
+ name: raw.name,
435
+ displayName: raw.displayName || formatDisplayName(raw.name),
436
+ description: raw.description,
437
+ version: raw.version,
438
+ author: raw.author,
439
+ mcpServers: raw.mcpServers,
440
+ lspServers: raw.lspServers,
441
+ }
442
+ }
443
+ if (raw && Array.isArray(raw.plugins) && raw.plugins.length > 0) {
444
+ const matched = raw.plugins.find((x) => x.name === basename(dir) || x.name === basename(join(dir, '..'))) || raw.plugins[0]
445
+ return {
446
+ name: matched.name || raw.name,
447
+ displayName: matched.displayName || formatDisplayName(matched.name || raw.name),
448
+ description: matched.description || raw.metadata?.description || '',
449
+ version: matched.version || raw.metadata?.version || undefined,
450
+ author: matched.author || raw.owner?.name || undefined,
451
+ skills: matched.skills,
452
+ commands: matched.commands,
453
+ agents: matched.agents,
454
+ mcpServers: matched.mcpServers,
455
+ lspServers: matched.lspServers,
456
+ }
457
+ }
458
+ const openai = raw.extensions?.['com.openai']
459
+ const settings = openai && typeof openai === 'object' ? openai : raw
460
+ return {
461
+ ...raw,
462
+ ...settings,
463
+ name: raw.name,
464
+ version: raw.version,
465
+ displayName: raw.displayName || settings.interface?.displayName,
466
+ description: raw.description || settings.interface?.shortDescription || settings.interface?.longDescription || '',
467
+ author: raw.author || settings.interface?.developerName,
468
+ homepage: raw.homepage || settings.interface?.websiteURL,
469
+ }
470
+ } catch {}
471
+ }
472
+ }
473
+ return null
474
+ }
475
+
476
+ /** List skill & command directories/files (skills/*, commands/*, root SKILL.md, .cursor/rules). */
477
+ export function listSkills(dir) {
478
+ const out = []
479
+ const seen = new Set()
480
+
481
+ const addSkill = (name, skillMdPath) => {
482
+ if (!name || seen.has(name)) return
483
+ let description = ''
484
+ if (skillMdPath) {
485
+ try {
486
+ description = extractMdDescription(readFileSync(skillMdPath, 'utf8'))
487
+ } catch {}
488
+ }
489
+ out.push({ name, command: `/${name}`, description })
490
+ seen.add(name)
491
+ }
492
+
493
+ // 1. Check skills/ subdirectory
494
+ const manifest = readPluginManifest(dir)
495
+ const declaredSkills = typeof manifest?.skills === 'string' ? [manifest.skills] : (Array.isArray(manifest?.skills) ? manifest.skills.filter((s) => typeof s === 'string' && s.startsWith('./')) : [])
496
+ const candidateSkillRoots = [...declaredSkills.map((p) => pluginPath(dir, p)), join(dir, 'skills'), join(dir, '..', 'skills')]
497
+ for (const sRoot of candidateSkillRoots) {
498
+ if (existsSync(sRoot)) {
499
+ try {
500
+ if (statSync(sRoot).isFile()) {
501
+ if (/^skill\.md$/i.test(basename(sRoot))) addSkill(basename(dirname(sRoot)), sRoot)
502
+ continue
503
+ }
504
+ const rootMd = ['SKILL.md', 'skill.md'].map((f) => join(sRoot, f)).find(existsSync)
505
+ if (rootMd) addSkill(basename(sRoot), rootMd)
506
+ for (const entry of readdirSync(sRoot, { withFileTypes: true })) {
507
+ if (entry.isDirectory()) {
508
+ if (['node_modules', '.git', '.agents', 'agents', 'commands', 'prompts', 'hooks', '.cursor', 'docs', 'assets', 'eval', 'staging', 'walkthroughs'].includes(entry.name)) continue
509
+ const skillMd = join(sRoot, entry.name, 'SKILL.md')
510
+ const altMd = join(sRoot, entry.name, 'skill.md')
511
+ if (existsSync(skillMd)) {
512
+ addSkill(entry.name, skillMd)
513
+ } else if (existsSync(altMd)) {
514
+ addSkill(entry.name, altMd)
515
+ }
516
+ } else if (entry.isFile() && entry.name.endsWith('.md') && !['README.md', 'CONTRIBUTING.md', 'LICENSE.md', 'CHANGELOG.md'].includes(entry.name)) {
517
+ const name = entry.name.replace(/\.md$/, '')
518
+ addSkill(name, join(sRoot, entry.name))
519
+ }
520
+ }
521
+ } catch {}
522
+ }
523
+ }
524
+
525
+ // 2. Check commands/ and .claude/commands/ (Claude Code slash commands)
526
+ const candidateCmdRoots = [
527
+ join(dir, 'commands'),
528
+ join(dir, '..', 'commands'),
529
+ join(dir, '.claude', 'commands'),
530
+ join(dir, '..', '.claude', 'commands'),
531
+ ]
532
+ for (const cRoot of candidateCmdRoots) {
533
+ if (existsSync(cRoot)) {
534
+ try {
535
+ for (const entry of readdirSync(cRoot, { withFileTypes: true })) {
536
+ if (entry.isFile() && entry.name.endsWith('.md')) {
537
+ addSkill(entry.name.replace(/\.md$/, ''), join(cRoot, entry.name))
538
+ } else if (entry.isDirectory()) {
539
+ const skillMd = join(cRoot, entry.name, 'SKILL.md')
540
+ const directMd = join(cRoot, `${entry.name}.md`)
541
+ const targetMd = existsSync(skillMd) ? skillMd : (existsSync(directMd) ? directMd : null)
542
+ if (targetMd) {
543
+ addSkill(entry.name, targetMd)
544
+ }
545
+ }
546
+ }
547
+ } catch {}
548
+ }
549
+ }
550
+
551
+
552
+
553
+ // 4. Single-skill repository fallback: if no skills/ or commands/ exist, check root SKILL.md
554
+ if (out.length === 0) {
555
+ const rootSkillMd = ['SKILL.md', 'skill.md'].map((f) => join(dir, f)).find(existsSync)
556
+ if (rootSkillMd) {
557
+ let skillName = basename(dir)
558
+ try {
559
+ const raw = readFileSync(rootSkillMd, 'utf8')
560
+ const nameMatch = raw.match(/^name:\s*(.+)$/m)
561
+ if (nameMatch) skillName = nameMatch[1].trim().replace(/^["']|["']$/g, '')
562
+ } catch {}
563
+ addSkill(skillName, rootSkillMd)
564
+ }
565
+ }
566
+
567
+ // 5. Check manifest (plugin.json / package.json / marketplace.json "skills" / "commands")
568
+ if (manifest && out.length === 0) {
569
+ if (Array.isArray(manifest.skills)) {
570
+ for (const item of manifest.skills) {
571
+ const rawName = typeof item === 'string' ? item : item?.name
572
+ if (rawName) {
573
+ const name = basename(rawName).replace(/\.(md|mdc)$/i, '')
574
+ if (name && !['skills', 'commands'].includes(name.toLowerCase()) && !seen.has(name)) {
575
+ seen.add(name)
576
+ out.push({
577
+ name,
578
+ command: `/${name}`,
579
+ description: typeof item === 'object' ? item.description || '' : '',
580
+ })
581
+ }
582
+ }
583
+ }
584
+ }
585
+ if (Array.isArray(manifest.commands)) {
586
+ for (const item of manifest.commands) {
587
+ const rawName = typeof item === 'string' ? item : item?.name
588
+ if (rawName) {
589
+ const name = basename(rawName).replace(/\.md$/i, '')
590
+ if (name && !['skills', 'commands'].includes(name.toLowerCase()) && !seen.has(name)) {
591
+ seen.add(name)
592
+ out.push({
593
+ name,
594
+ command: `/${name}`,
595
+ description: typeof item === 'object' ? item.description || '' : '',
596
+ })
597
+ }
598
+ }
599
+ }
600
+ }
601
+ }
602
+
603
+ return out
604
+ }
605
+
606
+ /** List agent definition files (agents/*.yaml|yml|md|json, .well-known/agent-card.json, agent.json). */
607
+ export function listAgents(dir) {
608
+ const out = []
609
+ const seen = new Set()
610
+
611
+ const candidateAgentRoots = [
612
+ join(dir, 'agents'),
613
+ join(dir, '.agents'),
614
+ join(dir, '..', 'agents'),
615
+ join(dir, '..', '.agents'),
616
+ join(dir, '.claude-plugin', 'agents'),
617
+ join(dir, '..', '.claude-plugin', 'agents'),
618
+ ]
619
+
620
+ const pluginName = basename(dir)
621
+
622
+ for (const agentsRoot of candidateAgentRoots) {
623
+ if (existsSync(agentsRoot)) {
624
+ try {
625
+ for (const entry of readdirSync(agentsRoot, { withFileTypes: true })) {
626
+ if (!entry.isFile()) continue
627
+ if (!/\.(ya?ml|md|json)$/i.test(entry.name)) continue
628
+ if (seen.has(entry.name)) continue
629
+
630
+ try {
631
+ const raw = readFileSync(join(agentsRoot, entry.name), 'utf8')
632
+ if (raw) {
633
+ const parsed = parseAgentDefinition(pluginName, entry.name, raw)
634
+ if (parsed && !parsed.error) {
635
+ seen.add(entry.name)
636
+ out.push({
637
+ file: entry.name,
638
+ name: parsed.name,
639
+ displayName: parsed.displayName || parsed.name,
640
+ description: parsed.description,
641
+ tools: parsed.tools,
642
+ model: parsed.model,
643
+ instructions: parsed.instructions,
644
+ raw,
645
+ })
646
+ continue
647
+ }
648
+ }
649
+ } catch { /* skip */ }
650
+
651
+ // Fallback if parsing failed
652
+ seen.add(entry.name)
653
+ const fallbackName = entry.name.replace(/\.[^.]+$/, '')
654
+ out.push({
655
+ file: entry.name,
656
+ name: fallbackName,
657
+ displayName: formatDisplayName(fallbackName),
658
+ description: 'Autonomous sub-agent workflow',
659
+ tools: null,
660
+ model: null,
661
+ instructions: '',
662
+ raw: null,
663
+ })
664
+ }
665
+ } catch {}
666
+ }
667
+ }
668
+
669
+ // Check Agent Card format (.well-known/agent-card.json or agent.json)
670
+ for (const agentCardPath of [join(dir, '.well-known', 'agent-card.json'), join(dir, 'agent.json')]) {
671
+ if (existsSync(agentCardPath) && !seen.has(basename(agentCardPath))) {
672
+ try {
673
+ const raw = readFileSync(agentCardPath, 'utf8')
674
+ const parsed = parseAgentDefinition(pluginName, basename(agentCardPath), raw)
675
+ seen.add(basename(agentCardPath))
676
+ if (parsed && !parsed.error) {
677
+ out.push({
678
+ file: basename(agentCardPath),
679
+ name: parsed.name,
680
+ displayName: parsed.displayName || parsed.name,
681
+ description: parsed.description,
682
+ tools: parsed.tools,
683
+ model: parsed.model,
684
+ instructions: parsed.instructions,
685
+ raw,
686
+ })
687
+ } else {
688
+ const jsonDoc = JSON.parse(raw)
689
+ out.push({
690
+ file: basename(agentCardPath),
691
+ name: jsonDoc.name || basename(dir),
692
+ displayName: jsonDoc.displayName || formatDisplayName(jsonDoc.name || basename(dir)),
693
+ description: jsonDoc.description || '',
694
+ tools: jsonDoc.tools || null,
695
+ model: jsonDoc.model || null,
696
+ instructions: jsonDoc.instructions || '',
697
+ raw,
698
+ })
699
+ }
700
+ } catch {}
701
+ }
702
+ }
703
+
704
+ // Check manifest "agents" array
705
+ const manifest = readPluginManifest(dir)
706
+ if (manifest && Array.isArray(manifest.agents)) {
707
+ for (const item of manifest.agents) {
708
+ const rawName = typeof item === 'string' ? item : item?.name
709
+ if (rawName && !seen.has(rawName)) {
710
+ seen.add(rawName)
711
+ const name = typeof item === 'string' ? item : (item.name || rawName)
712
+ const displayName = typeof item === 'object' && item.displayName ? item.displayName : (typeof item === 'object' && item.name ? item.name : formatDisplayName(name))
713
+ out.push({
714
+ file: typeof item === 'object' && item.file ? item.file : `${name}.md`,
715
+ name,
716
+ displayName,
717
+ description: typeof item === 'object' ? item.description || '' : '',
718
+ tools: typeof item === 'object' ? item.tools || null : null,
719
+ model: typeof item === 'object' ? item.model || null : null,
720
+ instructions: '',
721
+ raw: null,
722
+ })
723
+ }
724
+ }
725
+ }
726
+
727
+ return out
728
+ }
729
+
730
+ /** Prompt-ish entries: prompts/*.md|txt|yaml or plugin.json "prompts". */
731
+ export function listPrompts(dir) {
732
+ const prompts = []
733
+ const pRoots = [join(dir, 'prompts'), join(dir, '..', 'prompts')]
734
+ for (const pRoot of pRoots) {
735
+ if (existsSync(pRoot)) {
736
+ try {
737
+ for (const entry of readdirSync(pRoot, { withFileTypes: true })) {
738
+ if (entry.isFile() && /\.(md|txt|ya?ml|json)$/i.test(entry.name) && !['README.md', 'CONTRIBUTING.md', 'LICENSE.md'].includes(entry.name)) {
739
+ prompts.push(entry.name.replace(/\.[^.]+$/, ''))
740
+ }
741
+ }
742
+ } catch {}
743
+ }
744
+ }
745
+ const manifest = readPluginManifest(dir)
746
+ if (manifest && Array.isArray(manifest.prompts)) {
747
+ prompts.push(...manifest.prompts.map((p) => (typeof p === 'string' ? p : p.name)).filter(Boolean))
748
+ }
749
+ return [...new Set(prompts)]
750
+ }
751
+
752
+ function formatHookEventName(evt) {
753
+ const map = {
754
+ 'PreToolUse': 'Pre-tool use',
755
+ 'PostToolUse': 'Post-tool use',
756
+ 'PreCompact': 'Pre-compact',
757
+ 'PostCompact': 'Post-compact',
758
+ 'SessionStart': 'SessionStart',
759
+ 'SessionEnd': 'SessionEnd',
760
+ 'Stop': 'Stop',
761
+ 'PostToolUseFailure': 'PostToolUseFailure',
762
+ 'Notification': 'Notification',
763
+ }
764
+ return map[evt] || evt
765
+ }
766
+
767
+ /**
768
+ * Parse hook event names from a Claude/Codex hook config file's content.
769
+ * Accepts `{ hooks: {...} }`, a doubly-nested `{ hooks: { hooks: {...} } }`,
770
+ * or a bare event map. Never treats implementation scripts as hooks.
771
+ */
772
+ export function parseHookConfig(raw, isJson) {
773
+ const out = []
774
+ let parsed
775
+ try {
776
+ parsed = isJson ? JSON.parse(raw) : parseYaml(raw)
777
+ } catch {
778
+ return out
779
+ }
780
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return out
781
+ let hookObj = (parsed.hooks && typeof parsed.hooks === 'object' && !Array.isArray(parsed.hooks)) ? parsed.hooks : parsed
782
+ if (hookObj && typeof hookObj === 'object' && !Array.isArray(hookObj) && typeof hookObj.hooks === 'object' && !Array.isArray(hookObj.hooks)) {
783
+ hookObj = hookObj.hooks
784
+ }
785
+ for (const [eventName, val] of Object.entries(hookObj)) {
786
+ const formattedEvent = formatHookEventName(eventName)
787
+ if (Array.isArray(val)) {
788
+ for (const item of val) {
789
+ const matcher = item && typeof item === 'object' && item.matcher ? `: ${item.matcher}` : ''
790
+ out.push(`${formattedEvent}${matcher}`)
791
+ }
792
+ } else if (val && typeof val === 'object') {
793
+ const matcher = val.matcher ? `: ${val.matcher}` : ''
794
+ out.push(`${formattedEvent}${matcher}`)
795
+ } else {
796
+ out.push(formattedEvent)
797
+ }
798
+ }
799
+ return out
800
+ }
801
+
802
+ /**
803
+ * Resolve the plugin's Claude/Codex hook config file path: the manifest `hooks`
804
+ * path first, then `hooks/hooks.json|yaml|yml`, then `*-hooks.{json,yaml}` files.
805
+ * Returns null when the plugin declares no hook config (e.g. only scripts).
806
+ */
807
+ export function resolveHookConfigPath(dir) {
808
+ const manifest = readPluginManifest(dir)
809
+ if (manifest && typeof manifest.hooks === 'string') {
810
+ const p = isAbsolute(manifest.hooks) ? manifest.hooks : join(dir, manifest.hooks)
811
+ if (existsSync(p) && statSync(p).isFile()) return p
812
+ }
813
+ const hooksRoot = join(dir, 'hooks')
814
+ if (existsSync(hooksRoot)) {
815
+ const fixed = ['hooks.json', 'hooks.yaml', 'hooks.yml'].map((n) => join(hooksRoot, n)).find((p) => existsSync(p) && statSync(p).isFile())
816
+ if (fixed) return fixed
817
+ try {
818
+ const dialect = readdirSync(hooksRoot)
819
+ .filter((n) => /-hooks\.(json|ya?ml)$/i.test(n) && statSync(join(hooksRoot, n)).isFile())
820
+ .sort((a, b) => {
821
+ const score = (n) => (/claude/i.test(n) ? 0 : (/codex/i.test(n) ? 1 : 2))
822
+ return score(a) - score(b)
823
+ })
824
+ if (dialect.length > 0) return join(hooksRoot, dialect[0])
825
+ } catch {}
826
+ }
827
+ return null
828
+ }
829
+
830
+ /** Hook entries: follow the plugin manifest's `hooks` config, then hooks/ config files. */
831
+ export function listHooks(dir) {
832
+ const hooks = []
833
+ const seen = new Set()
834
+ const add = (h) => { if (h && !seen.has(h)) { seen.add(h); hooks.push(h) } }
835
+
836
+ const cfg = resolveHookConfigPath(dir)
837
+ if (cfg) {
838
+ try {
839
+ const raw = readFileSync(cfg, 'utf8')
840
+ for (const h of parseHookConfig(raw, /\.json$/i.test(cfg))) add(h)
841
+ } catch {}
842
+ }
843
+
844
+ // Manifest `hooks` as inline object/array (no file path to follow).
845
+ if (hooks.length === 0) {
846
+ const manifest = readPluginManifest(dir)
847
+ if (manifest && manifest.hooks) {
848
+ if (Array.isArray(manifest.hooks)) {
849
+ for (const h of manifest.hooks) add(typeof h === 'string' ? h : (h && h.name))
850
+ } else if (typeof manifest.hooks === 'object') {
851
+ for (const h of parseHookConfig(JSON.stringify({ hooks: manifest.hooks }), true)) add(h)
852
+ }
853
+ }
854
+ }
855
+
856
+ return hooks
857
+ }
858
+
859
+ /** Connector-ish entries: .mcp.json, mcp.json, server.json, or plugin.json "mcp" / "connectors". */
860
+ export function listConnectors(dir) {
861
+ const connectors = []
862
+ const seen = new Set()
863
+
864
+ for (const mcpFile of ['.mcp.json', 'mcp.json', 'server.json', 'mcp-servers.json']) {
865
+ const mcpPath = join(dir, mcpFile)
866
+ if (existsSync(mcpPath)) {
867
+ try {
868
+ const mcp = JSON.parse(readFileSync(mcpPath, 'utf8'))
869
+ let dict = null
870
+ if (mcp && typeof mcp === 'object' && !Array.isArray(mcp)) {
871
+ if (mcp.mcpServers && typeof mcp.mcpServers === 'object') {
872
+ dict = mcp.mcpServers
873
+ } else if (mcp.servers && typeof mcp.servers === 'object') {
874
+ dict = mcp.servers
875
+ } else if (mcp.name && (mcp.url || mcp.command || mcp.type)) {
876
+ dict = { [mcp.name]: mcp }
877
+ } else {
878
+ const direct = {}
879
+ for (const [k, v] of Object.entries(mcp)) {
880
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
881
+ if (v.url || v.command || v.type || v.args || v.headers || v.env) {
882
+ direct[k] = v
883
+ }
884
+ }
885
+ }
886
+ if (Object.keys(direct).length > 0) dict = direct
887
+ }
888
+ }
889
+ if (dict && typeof dict === 'object') {
890
+ for (const [name, cfg] of Object.entries(dict)) {
891
+ if (!seen.has(name)) {
892
+ seen.add(name)
893
+ connectors.push({
894
+ name,
895
+ type: cfg.type || (cfg.url ? 'http' : 'stdio'),
896
+ url: cfg.url || null,
897
+ command: cfg.command || null,
898
+ args: cfg.args || [],
899
+ env: cfg.env || {},
900
+ headers: cfg.headers || {},
901
+ })
902
+ }
903
+ }
904
+ }
905
+ } catch { /* ignore malformed */ }
906
+ }
907
+ }
908
+
909
+ const manifest = readPluginManifest(dir)
910
+ if (manifest) {
911
+ let dict = null
912
+ if (manifest.mcpServers && typeof manifest.mcpServers === 'object') {
913
+ dict = manifest.mcpServers
914
+ } else if (manifest.servers && typeof manifest.servers === 'object') {
915
+ dict = manifest.servers
916
+ } else if (manifest.mcp && typeof manifest.mcp === 'object') {
917
+ dict = manifest.mcp.mcpServers || manifest.mcp
918
+ }
919
+ if (dict && typeof dict === 'object') {
920
+ for (const [name, cfg] of Object.entries(dict)) {
921
+ if (!seen.has(name)) {
922
+ seen.add(name)
923
+ connectors.push({
924
+ name,
925
+ type: cfg.type || (cfg.url ? 'http' : 'stdio'),
926
+ url: cfg.url || null,
927
+ command: cfg.command || null,
928
+ args: cfg.args || [],
929
+ env: cfg.env || {},
930
+ headers: cfg.headers || {},
931
+ })
932
+ }
933
+ }
934
+ }
935
+ if (Array.isArray(manifest.connectors)) {
936
+ for (const c of manifest.connectors) {
937
+ const name = typeof c === 'string' ? c : c.name
938
+ if (name && !seen.has(name)) {
939
+ seen.add(name)
940
+ connectors.push({
941
+ name,
942
+ type: c.type || (c.url ? 'http' : 'stdio'),
943
+ url: c.url || null,
944
+ command: c.command || null,
945
+ args: c.args || [],
946
+ env: c.env || {},
947
+ headers: c.headers || {},
948
+ })
949
+ }
950
+ }
951
+ }
952
+ }
953
+ return connectors
954
+ }
955
+
956
+ /**
957
+ * List LSP server definitions from a plugin's manifest (`lspServers` record).
958
+ *
959
+ * Accepts either a directory path (reads the on-disk manifest via
960
+ * `readPluginManifest`) or a pre-resolved marketplace row object (uses
961
+ * `row.lspServers` directly). The fallback path lets the plugin detail
962
+ * surface LSP servers in browse mode, where the plugin directory itself
963
+ * is only a README placeholder and the lspServers live in marketplace.json.
964
+ */
965
+ export function listLspServers(input) {
966
+ let raw
967
+ if (typeof input === 'string') {
968
+ raw = readPluginManifest(input)?.lspServers
969
+ } else if (input && typeof input === 'object' && !Array.isArray(input)) {
970
+ raw = input.lspServers
971
+ }
972
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return []
973
+ const out = []
974
+ for (const [name, cfg] of Object.entries(raw)) {
975
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue
976
+ out.push({
977
+ name,
978
+ command: cfg.command || null,
979
+ args: Array.isArray(cfg.args) ? cfg.args : [],
980
+ env: (cfg.env && typeof cfg.env === 'object') ? cfg.env : {},
981
+ extensionToLanguage: (cfg.extensionToLanguage && typeof cfg.extensionToLanguage === 'object') ? cfg.extensionToLanguage : {},
982
+ initializationOptions: cfg.initializationOptions ?? null,
983
+ configuration: cfg.configuration ?? null,
984
+ startupTimeout: cfg.startupTimeout ?? null,
985
+ })
986
+ }
987
+ return out
988
+ }
989
+
990
+ /** Full detail view for one plugin (installed copy or cache). */
991
+ export function pluginDetail(sourceId, pluginName, source, rowFallback) {
992
+ const dir = pluginContentDir(sourceId, pluginName, source)
993
+ if (!dir) return null
994
+ const manifest = readPluginManifest(dir)
995
+ // LSP servers: prefer the on-disk manifest (post-install writes `lspServers`
996
+ // into `installed/<name>/.claude-plugin/plugin.json`); if absent — e.g. when
997
+ // browsing an uninstalled plugin whose directory is only a README placeholder
998
+ // — fall back to the `lspServers` field carried by the marketplace row.
999
+ let lspServers = listLspServers(dir)
1000
+ if (lspServers.length === 0 && rowFallback) {
1001
+ lspServers = listLspServers(rowFallback)
1002
+ }
1003
+ return {
1004
+ name: pluginName,
1005
+ displayName: manifest?.displayName || rowFallback?.displayName || formatDisplayName(pluginName),
1006
+ description: manifest?.description || rowFallback?.description || '',
1007
+ author: manifest?.author?.name || (typeof manifest?.author === 'string' ? manifest.author : rowFallback?.author),
1008
+ version: manifest?.version || rowFallback?.version,
1009
+ icons: buildPluginIcons(manifest, { sourceId, name: pluginName, dir, source }),
1010
+ skills: listSkills(dir),
1011
+ agents: listAgents(dir).map((a) => ({
1012
+ file: a.file,
1013
+ name: a.name,
1014
+ displayName: a.displayName || a.name,
1015
+ description: a.description,
1016
+ tools: a.tools || null,
1017
+ model: a.model || null,
1018
+ })),
1019
+ prompts: listPrompts(dir),
1020
+ connectors: listConnectors(dir),
1021
+ hooks: listHooks(dir),
1022
+ lspServers,
1023
+ }
1024
+ }
1025
+
1026
+ /** Recursively copy a directory (plain JS; avoids shell dependency). */
1027
+ export function copyDir(from, to) {
1028
+ mkdirSync(to, { recursive: true })
1029
+ for (const entry of readdirSync(from)) {
1030
+ const src = join(from, entry)
1031
+ const dest = join(to, entry)
1032
+ if (statSync(src).isDirectory()) {
1033
+ copyDir(src, dest)
1034
+ } else {
1035
+ copyFileSync(src, dest)
1036
+ }
1037
+ }
1038
+ }