universal-plugin-hub 1.0.50 → 1.3.1

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 CHANGED
@@ -9,15 +9,178 @@
9
9
  * 5. Single-plugin Standalone Repositories (root SKILL.md, plugin.json, skills/, commands/, agents/, .cursorrules)
10
10
  */
11
11
  import { existsSync, readFileSync, readdirSync, statSync, mkdirSync, copyFileSync } from 'node:fs'
12
- import { join, basename, dirname, isAbsolute } from 'node:path'
12
+ import { join, basename, dirname, isAbsolute, relative, resolve } from 'node:path'
13
13
  import { load as parseYaml } from 'js-yaml'
14
- import { sourceCacheDir, installedDir } from './store.js'
15
- import { safeSegment, pluginPath, sourceRepositoryDir } from './market.js'
14
+ import { sourceCacheDir, installedDir, pluginDataDir } from './store.js'
15
+ import { safeSegment, pluginPath, sourceRepositoryDir, normalizeRemotePluginSource } from './market.js'
16
16
  import { parseAgentDefinition } from './agents-map.js'
17
- import { buildPluginIcons } from './icons.js'
17
+ import { buildPluginIcons, touchLru, setLru } from './icons.js'
18
18
 
19
19
  const DIR_PARSER_CACHE = new Map()
20
20
  const DIR_PARSER_CACHE_TTL = 20000 // 20s TTL for file scanning
21
+ const VALID_PLUGIN_NAME = /^[a-z0-9][a-z0-9._-]*$/i
22
+ const MANIFEST_CANDIDATE_PARTS = [
23
+ ['.claude-plugin', 'marketplace.json'],
24
+ ['.agents', 'plugins', 'marketplace.json'],
25
+ ['marketplace.json'],
26
+ ['claude-plugins.json'],
27
+ ['registry.json'],
28
+ ['plugins.json'],
29
+ ['catalog.json'],
30
+ ['market.json'],
31
+ ['mcp-servers.json'],
32
+ ['servers.json'],
33
+ ['index.json'],
34
+ ['.well-known', 'agent-card.json'],
35
+ ]
36
+ const MONO_DIRS = ['plugins', 'skills', 'packages', 'tools', 'extensions']
37
+ const ROOT_PLUGIN_MARKER_PARTS = [
38
+ ['SKILL.md'],
39
+ ['skills'],
40
+ ['commands'],
41
+ ['agents'],
42
+ ['hooks'],
43
+ ['mcp.json'],
44
+ ['.mcp.json'],
45
+ ['server.json'],
46
+ ['.lsp.json'],
47
+ ['lsp.json'],
48
+ ['.claude-plugin', 'plugin.json'],
49
+ ['.codex-plugin', 'plugin.json'],
50
+ ['plugin.json'],
51
+ ['.cursor', 'rules'],
52
+ ['.cursorrules'],
53
+ ['package.json'],
54
+ ]
55
+
56
+ export const PLUGIN_RUNTIME_ENV_KEYS = ['PLUGIN_ROOT', 'PLUGIN_DATA', 'CLAUDE_PLUGIN_ROOT', 'CLAUDE_PLUGIN_DATA']
57
+ const BUILTIN_PLUGIN_ROOT_RE = /\$\{(?:CLAUDE_PLUGIN_ROOT|PLUGIN_ROOT)\}|\$(?:CLAUDE_PLUGIN_ROOT|PLUGIN_ROOT)\b/g
58
+ const BUILTIN_PLUGIN_DATA_RE = /\$\{(?:CLAUDE_PLUGIN_DATA|PLUGIN_DATA)\}|\$(?:CLAUDE_PLUGIN_DATA|PLUGIN_DATA)\b/g
59
+
60
+ export function hasUnresolvedVarPlaceholder(value) {
61
+ if (typeof value !== 'string') return false
62
+ const stripped = value.replace(BUILTIN_PLUGIN_ROOT_RE, '').replace(BUILTIN_PLUGIN_DATA_RE, '')
63
+ return /\$\{[^}]+\}/.test(stripped)
64
+ }
65
+
66
+ export function isDotRelativePath(value) {
67
+ return typeof value === 'string' && /^\.\.?(?:[\\/]|$)/.test(value.trim())
68
+ }
69
+
70
+ export function pluginDataDirForRoot(pluginRoot, explicitDataDir) {
71
+ if (typeof explicitDataDir === 'string' && explicitDataDir) return explicitDataDir
72
+ if (typeof pluginRoot === 'string' && pluginRoot) {
73
+ if (basename(dirname(pluginRoot)) === 'installed') return pluginDataDir(basename(pluginRoot))
74
+ return join(pluginRoot, '.plugin-data')
75
+ }
76
+ return ''
77
+ }
78
+
79
+ export function expandPluginVars(val, pluginRoot, explicitDataDir) {
80
+ if (typeof val === 'string') {
81
+ const normalizedRoot = String(pluginRoot || '').replace(/\\/g, '/')
82
+ const resolvedData = pluginDataDirForRoot(pluginRoot, explicitDataDir)
83
+ const normalizedData = String(resolvedData || '').replace(/\\/g, '/')
84
+ let out = val.replace(BUILTIN_PLUGIN_ROOT_RE, () => normalizedRoot)
85
+ if (normalizedData) out = out.replace(BUILTIN_PLUGIN_DATA_RE, () => normalizedData)
86
+ return out
87
+ }
88
+ if (Array.isArray(val)) return val.map((item) => expandPluginVars(item, pluginRoot, explicitDataDir))
89
+ if (val && typeof val === 'object') {
90
+ const res = {}
91
+ for (const [k, v] of Object.entries(val)) res[k] = expandPluginVars(v, pluginRoot, explicitDataDir)
92
+ return res
93
+ }
94
+ return val
95
+ }
96
+
97
+ function resolvePluginScopedPath(rawVal, pluginRoot, explicitDataDir) {
98
+ const rawTrimmed = String(rawVal).trim()
99
+ const expanded = expandPluginVars(rawVal, pluginRoot, explicitDataDir).trim()
100
+ if (!expanded) return null
101
+ if (pluginRoot && isDotRelativePath(expanded)) {
102
+ try { return pluginPath(pluginRoot, expanded).replace(/\\/g, '/') } catch { return null }
103
+ }
104
+ if (pluginRoot && /^\$(?:\{(?:CLAUDE_)?PLUGIN_ROOT\}|(?:CLAUDE_)?PLUGIN_ROOT\b)/.test(rawTrimmed)) {
105
+ const rel = relative(resolve(pluginRoot), resolve(expanded))
106
+ if (rel === '..' || rel.startsWith('..') || isAbsolute(rel)) return null
107
+ try { return pluginPath(pluginRoot, rel || '.').replace(/\\/g, '/') } catch { return null }
108
+ }
109
+ return expanded
110
+ }
111
+
112
+ export function resolvePluginCommand(command, pluginRoot, explicitDataDir) {
113
+ if (typeof command !== 'string') return command ?? null
114
+ return resolvePluginScopedPath(command, pluginRoot, explicitDataDir)
115
+ }
116
+
117
+ export function resolvePluginCwd(rawCwd, pluginRoot, explicitDataDir, { command, args } = {}) {
118
+ if (rawCwd === '') return ''
119
+ if (typeof rawCwd === 'string' && rawCwd.trim()) {
120
+ const scoped = resolvePluginScopedPath(rawCwd, pluginRoot, explicitDataDir)
121
+ return scoped ? scoped.replace(/\\/g, '/') : null
122
+ }
123
+ if (pluginRoot && (isDotRelativePath(command) || (Array.isArray(args) && args.some(isDotRelativePath)))) {
124
+ return pluginRoot.replace(/\\/g, '/')
125
+ }
126
+ return ''
127
+ }
128
+
129
+ export function resolveConnectorDisplay(cfg, pluginRoot, explicitDataDir) {
130
+ if (!cfg || typeof cfg !== 'object') {
131
+ return { displayUrl: null, displayCommand: null, displayArgs: [], displayCwd: null }
132
+ }
133
+ const expanded = expandPluginVars({
134
+ url: cfg.url || null,
135
+ args: Array.isArray(cfg.args) ? cfg.args : [],
136
+ }, pluginRoot, explicitDataDir)
137
+ const displayCommand = cfg.command ? resolvePluginCommand(cfg.command, pluginRoot, explicitDataDir) : null
138
+ const cwdVal = resolvePluginCwd(cfg.cwd ?? null, pluginRoot, explicitDataDir, {
139
+ command: cfg.command,
140
+ args: Array.isArray(cfg.args) ? cfg.args : [],
141
+ })
142
+ return {
143
+ displayUrl: expanded.url,
144
+ displayCommand,
145
+ displayArgs: expanded.args,
146
+ displayCwd: cwdVal || null,
147
+ }
148
+ }
149
+
150
+ export function resolvePluginSpecPath(dir, specPath) {
151
+ if (typeof specPath !== 'string') return null
152
+ const trimmed = specPath.trim()
153
+ if (!trimmed) return null
154
+ try {
155
+ return pluginPath(dir, trimmed)
156
+ } catch {
157
+ return null
158
+ }
159
+ }
160
+
161
+ function resolveMarketplacePluginSource(rawSource, pluginRootMeta) {
162
+ if (rawSource?.source === 'local') {
163
+ const localPath = typeof rawSource.path === 'string' ? rawSource.path.trim() : ''
164
+ if (!localPath.startsWith('./')) return null
165
+ return localPath
166
+ }
167
+ if (rawSource && typeof rawSource === 'object') {
168
+ return normalizeRemotePluginSource(rawSource)
169
+ }
170
+ if (typeof rawSource === 'string') {
171
+ const trimmed = rawSource.trim()
172
+ if (!trimmed || trimmed === '.' || trimmed === './') return './'
173
+ if (trimmed.startsWith('./')) return trimmed
174
+ if (/^https?:\/\//i.test(trimmed) || /^git@/i.test(trimmed)) return trimmed
175
+ if (trimmed.startsWith('/') || trimmed.includes('..') || /^[a-z]:/i.test(trimmed)) return null
176
+ const rawBase = typeof pluginRootMeta === 'string' ? pluginRootMeta.trim() : ''
177
+ if (rawBase && (rawBase.includes('..') || rawBase.startsWith('/') || /^[a-z]:/i.test(rawBase))) return null
178
+ const baseRoot = rawBase.replace(/^\.\//, '').replace(/^\/+|\/+$/g, '')
179
+ const combined = baseRoot ? `${baseRoot}/${trimmed.replace(/^\/+/, '')}` : trimmed
180
+ return `./${combined}`
181
+ }
182
+ return './'
183
+ }
21
184
 
22
185
  export function invalidateParserCaches() {
23
186
  DIR_PARSER_CACHE.clear()
@@ -83,10 +246,42 @@ function readPluginShortDescription(dir) {
83
246
  } catch { return '' }
84
247
  }
85
248
 
86
- function normalizeRow(row, sourceId, dir) {
249
+ /**
250
+ * Normalizes a semantic/free-form version string: trims whitespace, drops a
251
+ * redundant leading `v` before digits so UI badges render `vX.Y.Z` consistently,
252
+ * and maps empty values to `undefined`.
253
+ */
254
+ export function normalizeVersion(value) {
255
+ if (typeof value !== 'string') return undefined
256
+ const trimmed = value.trim()
257
+ if (!trimmed) return undefined
258
+ return trimmed.replace(/^v(?=\d)/i, '')
259
+ }
260
+
261
+ function manifestRootDir(manifestPath) {
262
+ const parent = dirname(manifestPath)
263
+ const folder = basename(parent)
264
+ if (folder === '.claude-plugin' || folder === '.codex-plugin' || folder === '.well-known') return dirname(parent)
265
+ if (folder === 'plugins' && basename(dirname(parent)) === '.agents') return dirname(dirname(parent))
266
+ return parent
267
+ }
268
+
269
+ function readPackageVersion(dir) {
270
+ if (!dir) return undefined
271
+ try {
272
+ const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8'))
273
+ return normalizeVersion(pkg?.['claude-plugin']?.version) || normalizeVersion(pkg?.version)
274
+ } catch {
275
+ return undefined
276
+ }
277
+ }
278
+
279
+ export const MARKETPLACE_COMPONENT_KEYS = ['mcpServers', 'lspServers', 'hooks', 'skills', 'commands', 'agents', 'prompts']
280
+
281
+ function normalizeRow(row, sourceId, dir, { skipIcons = false, pluginRootMeta = undefined } = {}) {
87
282
  if (!row) return null
88
283
  const name = typeof row.name === 'string' ? row.name : (typeof row.identifier === 'string' ? row.identifier : '')
89
- if (!name || !/^[a-z0-9][a-z0-9._-]*$/i.test(name)) return null
284
+ if (!name || !VALID_PLUGIN_NAME.test(name)) return null
90
285
  const cleanName = name.toLowerCase()
91
286
 
92
287
  const author = row.author && typeof row.author === 'object'
@@ -101,8 +296,8 @@ function normalizeRow(row, sourceId, dir) {
101
296
  const shortDescription = readPluginShortDescription(dir)
102
297
  || (typeof row.interface?.shortDescription === 'string' ? row.interface.shortDescription.trim() : '')
103
298
 
104
- const source = row.source?.source === 'local' ? row.source.path : (row.source || './')
105
- if (row.source?.source === 'local' && (typeof source !== 'string' || !source.startsWith('./'))) return null
299
+ const source = resolveMarketplacePluginSource(row.source, pluginRootMeta)
300
+ if (source === null) return null
106
301
 
107
302
  return {
108
303
  id: `${sourceId}/${cleanName}`,
@@ -112,24 +307,35 @@ function normalizeRow(row, sourceId, dir) {
112
307
  description,
113
308
  ...(shortDescription ? { shortDescription } : {}),
114
309
  author: typeof author === 'string' ? author : (meta.author || undefined),
115
- version: typeof row.version === 'string' ? row.version : (meta.version || undefined),
310
+ version: normalizeVersion(row.version)
311
+ || normalizeVersion(row.interface?.version)
312
+ || normalizeVersion(row.extensions?.['com.openai']?.version)
313
+ || normalizeVersion(meta.version),
116
314
  category: typeof row.category === 'string' ? row.category : (meta.category || undefined),
117
315
  homepage: typeof row.homepage === 'string' ? row.homepage : (meta.homepage || undefined),
118
316
  source,
119
317
  local: typeof source === 'string' && (source === './' || source.startsWith('./')),
120
- lspServers: row.lspServers || undefined,
121
- icons: buildPluginIcons(row, { sourceId, name: cleanName, dir, source }),
318
+ ...(row.strict !== undefined ? { strict: row.strict } : {}),
319
+ ...Object.fromEntries(MARKETPLACE_COMPONENT_KEYS.filter((k) => row[k] !== undefined).map((k) => [k, row[k]])),
320
+ ...(skipIcons ? {} : { icons: buildPluginIcons(row, { sourceId, name: cleanName, dir, source }) }),
122
321
  }
123
322
  }
124
323
 
125
324
  const MARKETPLACE_CACHE = new Map()
325
+ const MARKETPLACE_SELECTION_CACHE = new Map()
326
+ const PLUGIN_DIR_INDEX_CACHE = new Map()
327
+ const PLUGIN_DIR_INDEX_LIMIT = 64
126
328
  const MARKETPLACE_CACHE_TTL = 30000 // 30 seconds
127
329
 
128
330
  export function invalidateMarketplaceCache(sourceId) {
129
331
  if (sourceId) {
130
332
  MARKETPLACE_CACHE.delete(sourceId)
333
+ MARKETPLACE_SELECTION_CACHE.delete(sourceId)
334
+ PLUGIN_DIR_INDEX_CACHE.delete(sourceId)
131
335
  } else {
132
336
  MARKETPLACE_CACHE.clear()
337
+ MARKETPLACE_SELECTION_CACHE.clear()
338
+ PLUGIN_DIR_INDEX_CACHE.clear()
133
339
  }
134
340
  }
135
341
 
@@ -137,7 +343,7 @@ export function invalidateMarketplaceCache(sourceId) {
137
343
  * Universal Marketplace Reader.
138
344
  * Inspects a source repository cache and extracts all discoverable plugins.
139
345
  */
140
- export function readMarketplace(sourceId) {
346
+ export function readMarketplace(sourceId, names) {
141
347
  safeSegment(sourceId, 'source id')
142
348
  const cache = sourceCacheDir(sourceId)
143
349
  if (!existsSync(cache)) return []
@@ -145,23 +351,68 @@ export function readMarketplace(sourceId) {
145
351
  const now = Date.now()
146
352
  const cached = MARKETPLACE_CACHE.get(sourceId)
147
353
  if (cached && (now - cached.time < MARKETPLACE_CACHE_TTL)) {
148
- return cached.data
354
+ return names ? cached.data.filter(row => names.has(row.name)) : cached.data
149
355
  }
150
356
 
357
+ if (names) {
358
+ const key = JSON.stringify([...names].sort())
359
+ const selection = MARKETPLACE_SELECTION_CACHE.get(sourceId)
360
+ if (selection?.key === key && now - selection.time < MARKETPLACE_CACHE_TTL) return selection.data
361
+ const data = parseMarketplaceFromDisk(sourceId, cache, names).filter(row => names.has(row.name))
362
+ MARKETPLACE_SELECTION_CACHE.set(sourceId, { key, time: now, data })
363
+ return data
364
+ }
151
365
  const rows = parseMarketplaceFromDisk(sourceId, cache)
152
366
  MARKETPLACE_CACHE.set(sourceId, { time: now, data: rows })
153
367
  return rows
154
368
  }
155
369
 
156
- export function parsePluginRowFromDir(entryDir, fallbackName, sourceId) {
370
+ function resolveMcpDict(content) {
371
+ if (!content || typeof content !== 'object') return null
372
+ if (content.mcpServers && typeof content.mcpServers === 'object') return content.mcpServers
373
+ if (content.servers && typeof content.servers === 'object') return content.servers
374
+ return null
375
+ }
376
+
377
+ function resolveCaseAEntryDir(sourceId, cache, r, pluginRootMeta) {
378
+ const source = resolveMarketplacePluginSource(r.source, pluginRootMeta)
379
+ let dir = null
380
+ if (typeof source === 'string' && source.startsWith('./')) {
381
+ try { dir = pluginPath(cache, source) } catch { return { source: null, dir: null } }
382
+ }
383
+ if (source && typeof source === 'object' && r.name) {
384
+ dir = sourceRepositoryDir(cache, source) || pluginContentDir(sourceId, r.name, source, false)
385
+ }
386
+ return { source, dir }
387
+ }
388
+
389
+ function isPortableRootManifest(dir) {
390
+ const rootPath = join(dir, 'plugin.json')
391
+ if (!existsSync(rootPath)) return false
392
+ try {
393
+ const raw = JSON.parse(readFileSync(rootPath, 'utf8'))
394
+ return /^https:\/\/agent-plugins\.org\//.test(raw?.$schema || '') || Boolean(raw?.extensions?.['com.openai'])
395
+ } catch { return false }
396
+ }
397
+
398
+ function hasExplicitRootPlugin(cache) {
399
+ return existsSync(join(cache, '.codex-plugin', 'plugin.json'))
400
+ || existsSync(join(cache, '.claude-plugin', 'plugin.json'))
401
+ || isPortableRootManifest(cache)
402
+ || existsSync(join(cache, 'SKILL.md'))
403
+ || existsSync(join(cache, 'skill.md'))
404
+ }
405
+
406
+ function resolveDirPluginInfo(entryDir, fallbackName, { includeMetadata = true } = {}) {
157
407
  const rootSkill = existsSync(join(entryDir, 'SKILL.md')) || existsSync(join(entryDir, 'skill.md'))
158
408
  const hasSkill = rootSkill || existsSync(join(entryDir, 'skills')) || existsSync(join(entryDir, 'commands'))
159
409
  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'))
160
410
  const hasMcp = existsSync(join(entryDir, 'mcp.json')) || existsSync(join(entryDir, '.mcp.json')) || existsSync(join(entryDir, 'server.json'))
411
+ const hasLsp = existsSync(join(entryDir, '.lsp.json')) || existsSync(join(entryDir, 'lsp.json'))
161
412
  const hasAgents = existsSync(join(entryDir, 'agents'))
162
- if (!hasSkill && !hasManifest && !hasMcp && !hasAgents) return null
413
+ if (!hasSkill && !hasManifest && !hasMcp && !hasLsp && !hasAgents) return null
163
414
 
164
- let displayName = formatDisplayName(fallbackName)
415
+ let displayName = includeMetadata ? formatDisplayName(fallbackName) : ''
165
416
  let description = ''
166
417
  let version = '1.0.0'
167
418
  let author = undefined
@@ -170,83 +421,308 @@ export function parsePluginRowFromDir(entryDir, fallbackName, sourceId) {
170
421
  const manifest = readPluginManifest(entryDir, false)
171
422
  if (manifest) {
172
423
  if (manifest.name) name = manifest.name
173
- displayName = manifest.displayName || formatDisplayName(name)
174
- if (manifest.description) description = manifest.description
175
- if (manifest.version) version = manifest.version
176
- if (manifest.author) author = typeof manifest.author === 'string' ? manifest.author : manifest.author?.name
424
+ if (includeMetadata) {
425
+ displayName = manifest.displayName || formatDisplayName(name)
426
+ if (manifest.description) description = manifest.description
427
+ if (manifest.version) version = manifest.version
428
+ if (manifest.author) author = typeof manifest.author === 'string' ? manifest.author : manifest.author?.name
429
+ }
177
430
  } else if (rootSkill) {
178
431
  try {
179
432
  const raw = readFileSync(join(entryDir, existsSync(join(entryDir, 'SKILL.md')) ? 'SKILL.md' : 'skill.md'), 'utf8')
180
433
  const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/)
181
434
  const meta = match ? parseYaml(match[1]) : null
182
435
  if (typeof meta?.name === 'string') name = meta.name
183
- displayName = formatDisplayName(name)
184
- description = extractMdDescription(raw)
436
+ if (includeMetadata) {
437
+ displayName = formatDisplayName(name)
438
+ description = extractMdDescription(raw)
439
+ }
185
440
  } catch {}
186
- } else if (existsSync(join(entryDir, 'README.md'))) {
441
+ } else if (includeMetadata && existsSync(join(entryDir, 'README.md'))) {
187
442
  try { description = extractMdDescription(readFileSync(join(entryDir, 'README.md'), 'utf8')) } catch {}
188
443
  }
189
444
 
445
+ return { name, displayName, description, version, author, manifest }
446
+ }
447
+
448
+ function resolveStandaloneRootInfo(cache, sourceId, { includeMetadata = true } = {}) {
449
+ if (!ROOT_PLUGIN_MARKER_PARTS.some((parts) => existsSync(join(cache, ...parts)))) return null
450
+ let name = sourceId
451
+ let displayName = includeMetadata ? formatDisplayName(sourceId) : ''
452
+ let description = ''
453
+ let version = '1.0.0'
454
+ let author = undefined
455
+
456
+ const manifest = readPluginManifest(cache)
457
+ if (manifest) {
458
+ if (manifest.name) name = manifest.name
459
+ if (includeMetadata) {
460
+ if (manifest.displayName) displayName = manifest.displayName
461
+ if (manifest.description) description = manifest.description
462
+ if (manifest.version) version = manifest.version
463
+ if (manifest.author) author = typeof manifest.author === 'string' ? manifest.author : manifest.author.name
464
+ }
465
+ } else if (includeMetadata && existsSync(join(cache, 'SKILL.md'))) {
466
+ try {
467
+ description = extractMdDescription(readFileSync(join(cache, 'SKILL.md'), 'utf8'))
468
+ } catch {}
469
+ } else if (includeMetadata && existsSync(join(cache, 'README.md'))) {
470
+ try {
471
+ description = extractMdDescription(readFileSync(join(cache, 'README.md'), 'utf8'))
472
+ } catch {}
473
+ }
474
+ return { name, displayName, description, version, author, manifest }
475
+ }
476
+
477
+ export function parsePluginRowFromDir(entryDir, fallbackName, sourceId, options = {}) {
478
+ const info = resolveDirPluginInfo(entryDir, fallbackName, { includeMetadata: true })
479
+ if (!info) return null
480
+
190
481
  return normalizeRow({
191
- ...manifest,
192
- name,
193
- displayName,
194
- description,
195
- version,
196
- author,
482
+ ...info.manifest,
483
+ name: info.name,
484
+ displayName: info.displayName,
485
+ description: info.description,
486
+ version: info.version,
487
+ author: info.author,
197
488
  source: `./${fallbackName}`,
198
- }, sourceId, entryDir)
489
+ }, sourceId, entryDir, options)
199
490
  }
200
491
 
201
- export function parseMarketplaceFromDisk(sourceId, cache) {
492
+ function indexManifestPluginDirs(sourceId, cache, content) {
493
+ if (!content || typeof content !== 'object') return null
494
+ if (Array.isArray(content.plugins)) {
495
+ const entries = new Map()
496
+ const pluginRootMeta = content.metadata?.pluginRoot
497
+ for (const r of content.plugins) {
498
+ if (!r || typeof r !== 'object') continue
499
+ const { source, dir } = resolveCaseAEntryDir(sourceId, cache, r, pluginRootMeta)
500
+ if (source === null) continue
501
+ let rawName = ''
502
+ if (typeof r.name === 'string') {
503
+ rawName = r.name
504
+ } else {
505
+ const manifest = r.name === undefined && dir ? readPluginManifest(dir, false) : null
506
+ if (r.name === undefined && typeof manifest?.name === 'string') rawName = manifest.name
507
+ else rawName = typeof r.identifier === 'string' ? r.identifier : ''
508
+ }
509
+ if (!rawName || !VALID_PLUGIN_NAME.test(rawName)) continue
510
+ const cleanName = rawName.toLowerCase()
511
+ if (!entries.has(cleanName)) entries.set(cleanName, dir)
512
+ }
513
+ if (entries.size > 0) return entries
514
+ }
515
+ if (Array.isArray(content)) {
516
+ const entries = new Map()
517
+ for (const r of content) {
518
+ if (!r || typeof r !== 'object') continue
519
+ const rawName = typeof r.name === 'string' ? r.name : (typeof r.identifier === 'string' ? r.identifier : '')
520
+ if (!rawName || !VALID_PLUGIN_NAME.test(rawName)) continue
521
+ const source = r.source?.source === 'local' ? r.source.path : (r.source || './')
522
+ if (r.source?.source === 'local' && (typeof source !== 'string' || !source.startsWith('./'))) continue
523
+ const cleanName = rawName.toLowerCase()
524
+ if (!entries.has(cleanName)) entries.set(cleanName, pluginContentDir(sourceId, cleanName, source, false))
525
+ }
526
+ if (entries.size > 0) return entries
527
+ }
528
+ const mcpDict = resolveMcpDict(content)
529
+ if (mcpDict) {
530
+ const entries = new Map()
531
+ for (const srvName of Object.keys(mcpDict)) {
532
+ if (!VALID_PLUGIN_NAME.test(srvName)) continue
533
+ const cleanName = srvName.toLowerCase()
534
+ if (!entries.has(cleanName)) entries.set(cleanName, cache)
535
+ }
536
+ if (entries.size > 0) return entries
537
+ }
538
+ return null
539
+ }
540
+
541
+ function monoSubRootStamp(cache) {
542
+ return MONO_DIRS.map((sub) => {
543
+ try {
544
+ const info = statSync(join(cache, sub))
545
+ return info.isDirectory() ? String(info.mtimeMs) : ''
546
+ } catch { return '' }
547
+ }).join('|')
548
+ }
549
+
550
+ function indexMonoPluginDirs(cache) {
551
+ const entries = new Map()
552
+ for (const sub of MONO_DIRS) {
553
+ const subRoot = join(cache, sub)
554
+ if (!existsSync(subRoot)) continue
555
+ try {
556
+ for (const entry of readdirSync(subRoot, { withFileTypes: true })) {
557
+ if (!entry.isDirectory()) continue
558
+ const dir = join(subRoot, entry.name)
559
+ const info = resolveDirPluginInfo(dir, entry.name, { includeMetadata: false })
560
+ if (info && typeof info.name === 'string' && VALID_PLUGIN_NAME.test(info.name)) {
561
+ const cleanName = info.name.toLowerCase()
562
+ if (!entries.has(cleanName)) entries.set(cleanName, dir)
563
+ }
564
+ }
565
+ } catch {}
566
+ }
567
+ return entries
568
+ }
569
+
570
+ /**
571
+ * Resolve one plugin's directory in O(1) sharing the exact manifest/directory
572
+ * discovery precedence of `parseMarketplaceFromDisk` without scanning sibling
573
+ * artwork (`buildPluginIcons`) or unrelated plugins.
574
+ */
575
+ export function resolveMarketplacePluginDir(sourceId, pluginName) {
576
+ safeSegment(sourceId, 'source id')
577
+ const targetName = safeSegment(pluginName, 'plugin name').toLowerCase()
578
+ const cache = sourceCacheDir(sourceId)
579
+ if (!existsSync(cache)) {
580
+ PLUGIN_DIR_INDEX_CACHE.delete(sourceId)
581
+ return null
582
+ }
583
+
584
+ const cached = PLUGIN_DIR_INDEX_CACHE.get(sourceId)
585
+ if (cached) {
586
+ if (cached.manifestPath) {
587
+ try {
588
+ const info = statSync(cached.manifestPath)
589
+ if (info.isFile() && info.mtimeMs === cached.mtimeMs && info.size === cached.size) {
590
+ touchLru(PLUGIN_DIR_INDEX_CACHE, sourceId, cached)
591
+ return cached.entries.get(targetName) || null
592
+ }
593
+ } catch {}
594
+ PLUGIN_DIR_INDEX_CACHE.delete(sourceId)
595
+ } else if (cached.monoStamp !== undefined) {
596
+ if (monoSubRootStamp(cache) === cached.monoStamp) {
597
+ touchLru(PLUGIN_DIR_INDEX_CACHE, sourceId, cached)
598
+ return cached.entries.get(targetName) || null
599
+ }
600
+ PLUGIN_DIR_INDEX_CACHE.delete(sourceId)
601
+ }
602
+ }
603
+
202
604
  // 1. Check Multi-Plugin Manifest Candidates
203
- const manifestCandidates = [
204
- join(cache, '.claude-plugin', 'marketplace.json'),
205
- join(cache, '.agents', 'plugins', 'marketplace.json'),
206
- join(cache, 'marketplace.json'),
207
- join(cache, 'claude-plugins.json'),
208
- join(cache, 'registry.json'),
209
- join(cache, 'plugins.json'),
210
- join(cache, 'catalog.json'),
211
- join(cache, 'market.json'),
212
- join(cache, 'mcp-servers.json'),
213
- join(cache, 'servers.json'),
214
- join(cache, 'index.json'),
215
- join(cache, '.well-known', 'agent-card.json'),
216
- ]
605
+ for (const parts of MANIFEST_CANDIDATE_PARTS) {
606
+ const manifestPath = join(cache, ...parts)
607
+ let info
608
+ try { info = statSync(manifestPath) } catch { continue }
609
+ if (!info.isFile()) continue
610
+ try {
611
+ const content = JSON.parse(readFileSync(manifestPath, 'utf8'))
612
+ const entries = indexManifestPluginDirs(sourceId, cache, content)
613
+ if (entries) {
614
+ setLru(PLUGIN_DIR_INDEX_CACHE, PLUGIN_DIR_INDEX_LIMIT, sourceId, {
615
+ manifestPath, mtimeMs: info.mtimeMs, size: info.size, entries,
616
+ })
617
+ return entries.get(targetName) || null
618
+ }
619
+ } catch {}
620
+ }
621
+
622
+ // 2. Local source direct subdirectories discovery
623
+ if (sourceId === 'local') {
624
+ const direct = join(cache, targetName)
625
+ if (existsSync(direct)) {
626
+ const info = resolveDirPluginInfo(direct, targetName, { includeMetadata: false })
627
+ if (info && typeof info.name === 'string' && VALID_PLUGIN_NAME.test(info.name) && info.name.toLowerCase() === targetName) return direct
628
+ }
629
+ try {
630
+ for (const entry of readdirSync(cache, { withFileTypes: true })) {
631
+ if (entry.isDirectory() && !entry.name.startsWith('.')) {
632
+ const dir = join(cache, entry.name)
633
+ const info = resolveDirPluginInfo(dir, entry.name, { includeMetadata: false })
634
+ if (info && typeof info.name === 'string' && VALID_PLUGIN_NAME.test(info.name) && info.name.toLowerCase() === targetName) return dir
635
+ }
636
+ }
637
+ } catch {}
638
+ return null
639
+ }
640
+
641
+ // 3. Explicit root plugin manifests / SKILL.md
642
+ if (hasExplicitRootPlugin(cache)) {
643
+ const info = resolveDirPluginInfo(cache, sourceId, { includeMetadata: false })
644
+ if (info && typeof info.name === 'string' && VALID_PLUGIN_NAME.test(info.name)) {
645
+ return info.name.toLowerCase() === targetName ? cache : null
646
+ }
647
+ }
648
+
649
+ // 4. Monorepo subdirectories (direct path check first, then indexed scan)
650
+ for (const sub of MONO_DIRS) {
651
+ const direct = join(cache, sub, targetName)
652
+ if (existsSync(direct)) {
653
+ const info = resolveDirPluginInfo(direct, targetName, { includeMetadata: false })
654
+ if (info && typeof info.name === 'string' && VALID_PLUGIN_NAME.test(info.name) && info.name.toLowerCase() === targetName) return direct
655
+ }
656
+ }
657
+ const monoEntries = indexMonoPluginDirs(cache)
658
+ if (monoEntries.size > 0) {
659
+ setLru(PLUGIN_DIR_INDEX_CACHE, PLUGIN_DIR_INDEX_LIMIT, sourceId, {
660
+ monoStamp: monoSubRootStamp(cache), entries: monoEntries,
661
+ })
662
+ return monoEntries.get(targetName) || null
663
+ }
664
+
665
+ // 5. Single Standalone Root Plugin Repository
666
+ const rootInfo = resolveStandaloneRootInfo(cache, sourceId, { includeMetadata: false })
667
+ if (rootInfo && typeof rootInfo.name === 'string' && VALID_PLUGIN_NAME.test(rootInfo.name)) {
668
+ return rootInfo.name.toLowerCase() === targetName ? cache : null
669
+ }
670
+ return null
671
+ }
217
672
 
218
- for (const manifestPath of manifestCandidates) {
673
+ export function parseMarketplaceFromDisk(sourceId, cache, names, options = {}) {
674
+ // 1. Check Multi-Plugin Manifest Candidates
675
+ for (const parts of MANIFEST_CANDIDATE_PARTS) {
676
+ const manifestPath = join(cache, ...parts)
219
677
  if (existsSync(manifestPath)) {
220
678
  try {
221
679
  const content = JSON.parse(readFileSync(manifestPath, 'utf8'))
222
680
  // Case A: Claude / standard manifest with plugins array
223
681
  if (Array.isArray(content.plugins)) {
682
+ let skipped = false
683
+ const pluginRootMeta = content.metadata?.pluginRoot
684
+ const marketVersion = normalizeVersion(content.metadata?.version) || normalizeVersion(content.version)
224
685
  const rows = content.plugins.map((r) => {
225
- const source = r.source?.source === 'local' ? r.source.path : r.source
226
- let manifest = null
227
- let dir = null
228
- if (typeof source === 'string' && source.startsWith('./')) {
229
- dir = pluginPath(cache, source)
230
- } else if (source && typeof source === 'object' && r.name) {
231
- dir = sourceRepositoryDir(cache, source) || pluginContentDir(sourceId, r.name, source, false)
686
+ const { source, dir } = resolveCaseAEntryDir(sourceId, cache, r, pluginRootMeta)
687
+ if (source === null) return null
688
+ if (names && typeof r.name === 'string' && !names.has(r.name.toLowerCase())) {
689
+ skipped = true
690
+ return null
232
691
  }
233
- if (dir) manifest = readPluginManifest(dir, false)
692
+ const manifest = dir ? readPluginManifest(dir, false) : null
693
+ const resolvedVersion =
694
+ normalizeVersion(r.version)
695
+ || normalizeVersion(r.interface?.version)
696
+ || normalizeVersion(r.extensions?.['com.openai']?.version)
697
+ || normalizeVersion(manifest?.version)
698
+ || marketVersion
234
699
  return normalizeRow({ ...manifest, ...r,
700
+ version: resolvedVersion,
235
701
  displayName: r.displayName || r.interface?.displayName || manifest?.displayName,
236
702
  description: r.description || r.interface?.shortDescription || manifest?.description,
237
- }, sourceId, dir)
703
+ }, sourceId, dir, { ...options, pluginRootMeta })
238
704
  }).filter(Boolean)
239
705
  if (rows.length > 0) return rows
706
+ // Preserve manifest precedence and discovery fallbacks on a miss.
707
+ if (skipped) return parseMarketplaceFromDisk(sourceId, cache, undefined, options)
240
708
  }
241
709
  // Case B: Direct array of plugin descriptors
242
710
  if (Array.isArray(content)) {
243
- const rows = content.map((r) => normalizeRow(r, sourceId)).filter(Boolean)
711
+ const rows = content.map((r) => {
712
+ const { source, dir } = resolveCaseAEntryDir(sourceId, cache, r)
713
+ if (source === null) return null
714
+ const manifest = dir ? readPluginManifest(dir, false) : null
715
+ const resolvedVersion =
716
+ normalizeVersion(r?.version)
717
+ || normalizeVersion(r?.interface?.version)
718
+ || normalizeVersion(r?.extensions?.['com.openai']?.version)
719
+ || normalizeVersion(manifest?.version)
720
+ return normalizeRow({ ...manifest, ...r, version: resolvedVersion }, sourceId, dir, options)
721
+ }).filter(Boolean)
244
722
  if (rows.length > 0) return rows
245
723
  }
246
724
  // Case C: MCP Servers dictionary (mcpServers or servers object)
247
- const mcpDict = (content.mcpServers && typeof content.mcpServers === 'object')
248
- ? content.mcpServers
249
- : ((content.servers && typeof content.servers === 'object') ? content.servers : null)
725
+ const mcpDict = resolveMcpDict(content)
250
726
  if (mcpDict) {
251
727
  const rows = []
252
728
  for (const [srvName, srvCfg] of Object.entries(mcpDict)) {
@@ -257,7 +733,7 @@ export function parseMarketplaceFromDisk(sourceId, cache) {
257
733
  author: srvCfg.author || content.author || 'MCP',
258
734
  category: 'mcp',
259
735
  source: './',
260
- }, sourceId))
736
+ }, sourceId, undefined, options))
261
737
  }
262
738
  if (rows.filter(Boolean).length > 0) return rows.filter(Boolean)
263
739
  }
@@ -274,7 +750,7 @@ export function parseMarketplaceFromDisk(sourceId, cache) {
274
750
  try {
275
751
  for (const entry of readdirSync(cache, { withFileTypes: true })) {
276
752
  if (entry.isDirectory() && !entry.name.startsWith('.')) {
277
- const row = parsePluginRowFromDir(join(cache, entry.name), entry.name, 'local')
753
+ const row = parsePluginRowFromDir(join(cache, entry.name), entry.name, 'local', options)
278
754
  if (row) localRows.push(row)
279
755
  }
280
756
  }
@@ -284,25 +760,20 @@ export function parseMarketplaceFromDisk(sourceId, cache) {
284
760
  }
285
761
 
286
762
  // Explicit plugin manifests describe the whole package, including its skills.
287
- if (existsSync(join(cache, '.codex-plugin', 'plugin.json')) || existsSync(join(cache, '.claude-plugin', 'plugin.json'))) {
288
- const row = parsePluginRowFromDir(cache, sourceId, sourceId)
289
- if (row) return [{ ...row, source: './' }]
290
- }
291
- if (existsSync(join(cache, 'SKILL.md')) || existsSync(join(cache, 'skill.md'))) {
292
- const row = parsePluginRowFromDir(cache, sourceId, sourceId)
763
+ if (hasExplicitRootPlugin(cache)) {
764
+ const row = parsePluginRowFromDir(cache, sourceId, sourceId, options)
293
765
  if (row) return [{ ...row, source: './' }]
294
766
  }
295
767
 
296
768
  // 3. Monorepo subdirectories auto-discovery (plugins/*, skills/*, packages/*, tools/*, extensions/*)
297
- const monoDirs = ['plugins', 'skills', 'packages', 'tools', 'extensions']
298
769
  const monoRows = []
299
- for (const sub of monoDirs) {
770
+ for (const sub of MONO_DIRS) {
300
771
  const subRoot = join(cache, sub)
301
772
  if (existsSync(subRoot)) {
302
773
  try {
303
774
  for (const entry of readdirSync(subRoot, { withFileTypes: true })) {
304
775
  if (entry.isDirectory()) {
305
- const row = parsePluginRowFromDir(join(subRoot, entry.name), entry.name, sourceId)
776
+ const row = parsePluginRowFromDir(join(subRoot, entry.name), entry.name, sourceId, options)
306
777
  if (row) {
307
778
  row.source = `./${sub}/${entry.name}`
308
779
  monoRows.push(row)
@@ -315,69 +786,17 @@ export function parseMarketplaceFromDisk(sourceId, cache) {
315
786
  if (monoRows.filter(Boolean).length > 0) return monoRows.filter(Boolean)
316
787
 
317
788
  // 3. Single Standalone Root Plugin Repository
318
- const rootSkillMd = join(cache, 'SKILL.md')
319
- const rootSkillsDir = join(cache, 'skills')
320
- const rootCommandsDir = join(cache, 'commands')
321
- const rootAgentsDir = join(cache, 'agents')
322
- const rootHooksDir = join(cache, 'hooks')
323
- const rootMcp = join(cache, 'mcp.json')
324
- const rootDotMcp = join(cache, '.mcp.json')
325
- const rootServerJson = join(cache, 'server.json')
326
- const rootPluginJson = join(cache, '.claude-plugin', 'plugin.json')
327
- const rootCodexPluginJson = join(cache, '.codex-plugin', 'plugin.json')
328
- const rootDirectPluginJson = join(cache, 'plugin.json')
329
- const rootCursorRules = join(cache, '.cursor', 'rules')
330
- const rootCursorRulesFile = join(cache, '.cursorrules')
331
- const rootPkgJson = join(cache, 'package.json')
332
-
333
- const isRootPlugin = existsSync(rootSkillMd)
334
- || existsSync(rootSkillsDir)
335
- || existsSync(rootCommandsDir)
336
- || existsSync(rootAgentsDir)
337
- || existsSync(rootHooksDir)
338
- || existsSync(rootMcp)
339
- || existsSync(rootDotMcp)
340
- || existsSync(rootServerJson)
341
- || existsSync(rootPluginJson)
342
- || existsSync(rootCodexPluginJson)
343
- || existsSync(rootDirectPluginJson)
344
- || existsSync(rootCursorRules)
345
- || existsSync(rootCursorRulesFile)
346
- || existsSync(rootPkgJson)
347
-
348
- if (isRootPlugin) {
349
- let name = sourceId
350
- let displayName = formatDisplayName(sourceId)
351
- let description = ''
352
- let version = '1.0.0'
353
- let author = undefined
354
-
355
- const manifest = readPluginManifest(cache)
356
- if (manifest) {
357
- if (manifest.name) name = manifest.name
358
- if (manifest.displayName) displayName = manifest.displayName
359
- if (manifest.description) description = manifest.description
360
- if (manifest.version) version = manifest.version
361
- if (manifest.author) author = typeof manifest.author === 'string' ? manifest.author : manifest.author.name
362
- } else if (existsSync(rootSkillMd)) {
363
- try {
364
- description = extractMdDescription(readFileSync(rootSkillMd, 'utf8'))
365
- } catch {}
366
- } else if (existsSync(join(cache, 'README.md'))) {
367
- try {
368
- description = extractMdDescription(readFileSync(join(cache, 'README.md'), 'utf8'))
369
- } catch {}
370
- }
371
-
789
+ const rootInfo = resolveStandaloneRootInfo(cache, sourceId, { includeMetadata: true })
790
+ if (rootInfo) {
372
791
  return [normalizeRow({
373
- ...manifest,
374
- name,
375
- displayName,
376
- description,
377
- version,
378
- author,
792
+ ...rootInfo.manifest,
793
+ name: rootInfo.name,
794
+ displayName: rootInfo.displayName,
795
+ description: rootInfo.description,
796
+ version: rootInfo.version,
797
+ author: rootInfo.author,
379
798
  source: './',
380
- }, sourceId, cache)].filter(Boolean)
799
+ }, sourceId, cache, options)].filter(Boolean)
381
800
  }
382
801
 
383
802
  return []
@@ -404,14 +823,15 @@ export function pluginContentDir(sourceId, pluginName, source, preferInstalled =
404
823
  }
405
824
 
406
825
  // Check if in remote git cache
407
- if (source && typeof source === 'object' && (source.source === 'url' || source.source === 'git-subdir')) {
408
- if (typeof source.url === 'string') {
409
- const ownDir = sourceRepositoryDir(sourceCacheDir(sourceId), source)
826
+ const remoteSrc = normalizeRemotePluginSource(source)
827
+ if (remoteSrc && typeof remoteSrc === 'object' && (remoteSrc.source === 'url' || remoteSrc.source === 'git-subdir' || remoteSrc.source === 'github')) {
828
+ if (typeof remoteSrc.url === 'string' && remoteSrc.url) {
829
+ const ownDir = sourceRepositoryDir(sourceCacheDir(sourceId), remoteSrc)
410
830
  if (ownDir) return ownDir
411
- const clean = String(source.url).replace(/^https?:\/\//, '').replace(/\.git$/, '')
831
+ const clean = String(remoteSrc.url).replace(/^https?:\/\//, '').replace(/\.git$/, '')
412
832
  const remoteKey = clean.replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/g, '').toLowerCase() || 'repo'
413
833
  const checkout = join(sourceCacheDir('remote'), remoteKey)
414
- const dir = source.path ? pluginPath(checkout, source.path) : checkout
834
+ const dir = remoteSrc.path ? pluginPath(checkout, remoteSrc.path) : checkout
415
835
  return existsSync(dir) ? dir : null
416
836
  }
417
837
  }
@@ -421,25 +841,29 @@ export function pluginContentDir(sourceId, pluginName, source, preferInstalled =
421
841
  return existsSync(fallback) ? fallback : null
422
842
  }
423
843
 
424
- /** Read plugin metadata with Claude precedence when multiple formats coexist. */
844
+ /** Read plugin metadata with Claude/portable precedence and Codex overlay merge. */
425
845
  export function readPluginManifest(dir, includeParent = true) {
426
846
  const rootManifest = join(dir, 'plugin.json')
427
847
  let portable = false
428
- try {
429
- const root = JSON.parse(readFileSync(rootManifest, 'utf8'))
430
- portable = /^https:\/\/agent-plugins\.org\//.test(root.$schema || '') || Boolean(root.extensions?.['com.openai'])
431
- } catch {}
848
+ if (existsSync(rootManifest)) {
849
+ try {
850
+ const root = JSON.parse(readFileSync(rootManifest, 'utf8'))
851
+ portable = /^https:\/\/agent-plugins\.org\//.test(root.$schema || '') || Boolean(root.extensions?.['com.openai'])
852
+ } catch {}
853
+ }
432
854
  const candidates = [
433
855
  join(dir, '.claude-plugin', 'plugin.json'),
434
856
  ...(portable ? [rootManifest] : []),
435
857
  join(dir, '.codex-plugin', 'plugin.json'),
436
858
  join(dir, '.claude-plugin', 'marketplace.json'),
859
+ join(dir, '.agents', 'plugins', 'marketplace.json'),
437
860
  rootManifest,
438
861
  join(dir, 'manifest.json'),
439
862
  join(dir, 'server.json'),
440
863
  join(dir, 'package.json'),
441
864
  ...(includeParent ? [join(dir, '..', '.claude-plugin', 'plugin.json'),
442
865
  join(dir, '..', '.claude-plugin', 'marketplace.json'),
866
+ join(dir, '..', '.agents', 'plugins', 'marketplace.json'),
443
867
  join(dir, '..', 'plugin.json'),
444
868
  join(dir, '..', 'manifest.json')] : []),
445
869
  ]
@@ -449,12 +873,17 @@ export function readPluginManifest(dir, includeParent = true) {
449
873
  try {
450
874
  const raw = JSON.parse(readFileSync(p, 'utf8'))
451
875
  if (p.endsWith('package.json')) {
452
- if (raw['claude-plugin']) return raw['claude-plugin']
876
+ if (raw['claude-plugin']) {
877
+ return {
878
+ ...raw['claude-plugin'],
879
+ version: normalizeVersion(raw['claude-plugin']?.version) || normalizeVersion(raw.version),
880
+ }
881
+ }
453
882
  return {
454
883
  name: raw.name,
455
884
  displayName: raw.displayName || formatDisplayName(raw.name),
456
885
  description: raw.description,
457
- version: raw.version,
886
+ version: normalizeVersion(raw.version),
458
887
  author: raw.author,
459
888
  mcpServers: raw.mcpServers,
460
889
  lspServers: raw.lspServers,
@@ -466,26 +895,48 @@ export function readPluginManifest(dir, includeParent = true) {
466
895
  name: matched.name || raw.name,
467
896
  displayName: matched.displayName || formatDisplayName(matched.name || raw.name),
468
897
  description: matched.description || raw.metadata?.description || '',
469
- version: matched.version || raw.metadata?.version || undefined,
898
+ version: normalizeVersion(matched.version)
899
+ || normalizeVersion(matched.interface?.version)
900
+ || normalizeVersion(matched.extensions?.['com.openai']?.version)
901
+ || normalizeVersion(raw.metadata?.version)
902
+ || normalizeVersion(raw.version),
470
903
  author: matched.author || raw.owner?.name || undefined,
904
+ strict: matched.strict,
905
+ prompts: matched.prompts,
471
906
  skills: matched.skills,
472
907
  commands: matched.commands,
473
908
  agents: matched.agents,
909
+ hooks: matched.hooks,
474
910
  mcpServers: matched.mcpServers,
475
911
  lspServers: matched.lspServers,
476
912
  }
477
913
  }
478
914
  const openai = raw.extensions?.['com.openai']
479
- const settings = openai && typeof openai === 'object' ? openai : raw
915
+ let overlay = openai && typeof openai === 'object' && !Array.isArray(openai) ? openai : null
916
+ if (!overlay && (p === join(dir, '.claude-plugin', 'plugin.json') || p === rootManifest)) {
917
+ const codexPath = join(manifestRootDir(p), '.codex-plugin', 'plugin.json')
918
+ if (existsSync(codexPath)) {
919
+ try {
920
+ const codexRaw = JSON.parse(readFileSync(codexPath, 'utf8'))
921
+ if (codexRaw && typeof codexRaw === 'object') overlay = codexRaw
922
+ } catch {}
923
+ }
924
+ }
925
+ const merged = overlay ? { ...overlay, ...raw } : raw
926
+ const iface = overlay?.interface || raw.interface || {}
927
+ const version =
928
+ normalizeVersion(raw.version)
929
+ || normalizeVersion(overlay?.version)
930
+ || normalizeVersion(iface.version)
931
+ || readPackageVersion(manifestRootDir(p))
480
932
  return {
481
- ...raw,
482
- ...settings,
483
- name: raw.name,
484
- version: raw.version,
485
- displayName: raw.displayName || settings.interface?.displayName,
486
- description: raw.description || settings.interface?.shortDescription || settings.interface?.longDescription || '',
487
- author: raw.author || settings.interface?.developerName,
488
- homepage: raw.homepage || settings.interface?.websiteURL,
933
+ ...merged,
934
+ name: raw.name || overlay?.name,
935
+ version,
936
+ displayName: raw.displayName || iface.displayName,
937
+ description: raw.description || iface.shortDescription || iface.longDescription || '',
938
+ author: raw.author || iface.developerName,
939
+ homepage: raw.homepage || iface.websiteURL,
489
940
  }
490
941
  } catch {}
491
942
  }
@@ -493,82 +944,221 @@ export function readPluginManifest(dir, includeParent = true) {
493
944
  return null
494
945
  }
495
946
 
496
- /** List skill & command directories/files (skills/*, commands/*, root SKILL.md, .cursor/rules). */
497
- export function listSkills(dir) {
498
- const out = []
499
- const seen = new Set()
500
-
501
- const addSkill = (name, skillMdPath) => {
502
- if (!name || seen.has(name)) return
503
- let description = ''
504
- if (skillMdPath) {
505
- try {
506
- description = extractMdDescription(readFileSync(skillMdPath, 'utf8'))
507
- } catch {}
508
- }
509
- out.push({ name, command: `/${name}`, description })
510
- seen.add(name)
511
- }
512
-
513
- // 1. Check skills/ subdirectory
514
- const manifest = readPluginManifest(dir)
515
- const declaredSkills = typeof manifest?.skills === 'string' ? [manifest.skills] : (Array.isArray(manifest?.skills) ? manifest.skills.filter((s) => typeof s === 'string' && s.startsWith('./')) : [])
516
- const candidateSkillRoots = [...declaredSkills.map((p) => pluginPath(dir, p)), join(dir, 'skills'), join(dir, '..', 'skills')]
517
- for (const sRoot of candidateSkillRoots) {
518
- if (existsSync(sRoot)) {
519
- try {
520
- if (statSync(sRoot).isFile()) {
521
- if (/^skill\.md$/i.test(basename(sRoot))) addSkill(basename(dirname(sRoot)), sRoot)
522
- continue
947
+ function scanCommandDirectory(cmdRoot, seenFiles, addCommandEntry, prefix = '') {
948
+ if (!cmdRoot || !existsSync(cmdRoot)) return
949
+ try {
950
+ const st = statSync(cmdRoot)
951
+ if (st.isFile()) {
952
+ if (/\.(md)$/i.test(cmdRoot)) {
953
+ const key = resolve(cmdRoot)
954
+ if (!seenFiles.has(key)) {
955
+ seenFiles.add(key)
956
+ const stem = basename(cmdRoot).replace(/\.md$/i, '')
957
+ const name = prefix || stem
958
+ addCommandEntry({ name, filePath: cmdRoot, content: null, description: '' })
523
959
  }
524
- const rootMd = ['SKILL.md', 'skill.md'].map((f) => join(sRoot, f)).find(existsSync)
525
- if (rootMd) addSkill(basename(sRoot), rootMd)
526
- for (const entry of readdirSync(sRoot, { withFileTypes: true })) {
527
- if (entry.isDirectory()) {
528
- if (['node_modules', '.git', '.agents', 'agents', 'commands', 'prompts', 'hooks', '.cursor', 'docs', 'assets', 'eval', 'staging', 'walkthroughs'].includes(entry.name)) continue
529
- const skillMd = join(sRoot, entry.name, 'SKILL.md')
530
- const altMd = join(sRoot, entry.name, 'skill.md')
531
- if (existsSync(skillMd)) {
532
- addSkill(entry.name, skillMd)
533
- } else if (existsSync(altMd)) {
534
- addSkill(entry.name, altMd)
535
- }
536
- } else if (entry.isFile() && entry.name.endsWith('.md') && !['README.md', 'CONTRIBUTING.md', 'LICENSE.md', 'CHANGELOG.md'].includes(entry.name)) {
537
- const name = entry.name.replace(/\.md$/, '')
538
- addSkill(name, join(sRoot, entry.name))
960
+ }
961
+ return
962
+ }
963
+ for (const entry of readdirSync(cmdRoot, { withFileTypes: true })) {
964
+ const fullPath = join(cmdRoot, entry.name)
965
+ if (entry.isFile() && entry.name.endsWith('.md') && !/^readme\.md$/i.test(entry.name)) {
966
+ const key = resolve(fullPath)
967
+ if (seenFiles.has(key)) continue
968
+ seenFiles.add(key)
969
+ const stem = entry.name.replace(/\.md$/i, '')
970
+ const name = prefix ? `${prefix}-${stem}` : stem
971
+ addCommandEntry({ name, filePath: fullPath, content: null, description: '' })
972
+ } else if (entry.isDirectory()) {
973
+ const nextPrefix = prefix ? `${prefix}-${entry.name}` : entry.name
974
+ const skillMd = join(fullPath, 'SKILL.md')
975
+ const altMd = join(fullPath, 'skill.md')
976
+ const directMd = existsSync(skillMd) ? skillMd : (existsSync(altMd) ? altMd : null)
977
+ if (directMd) {
978
+ const key = resolve(directMd)
979
+ if (!seenFiles.has(key)) {
980
+ seenFiles.add(key)
981
+ addCommandEntry({ name: nextPrefix, filePath: directMd, content: null, description: '' })
539
982
  }
540
983
  }
541
- } catch {}
984
+ scanCommandDirectory(fullPath, seenFiles, addCommandEntry, nextPrefix)
985
+ }
542
986
  }
987
+ } catch {}
988
+ }
989
+
990
+ /** Resolve disk/inline slash command entries from commands/ dirs and manifest.commands. */
991
+ export function resolvePluginCommandEntries(dir, manifest = readPluginManifest(dir)) {
992
+ const entries = []
993
+ const seenNames = new Set()
994
+ const seenFiles = new Set()
995
+ const pushEntry = (item) => {
996
+ if (!item?.name || seenNames.has(item.name)) return
997
+ seenNames.add(item.name)
998
+ entries.push(item)
543
999
  }
544
1000
 
545
- // 2. Check commands/ and .claude/commands/ (Claude Code slash commands)
546
1001
  const candidateCmdRoots = [
547
1002
  join(dir, 'commands'),
548
1003
  join(dir, '..', 'commands'),
549
1004
  join(dir, '.claude', 'commands'),
550
1005
  join(dir, '..', '.claude', 'commands'),
551
1006
  ]
552
- for (const cRoot of candidateCmdRoots) {
553
- if (existsSync(cRoot)) {
554
- try {
555
- for (const entry of readdirSync(cRoot, { withFileTypes: true })) {
556
- if (entry.isFile() && entry.name.endsWith('.md')) {
557
- addSkill(entry.name.replace(/\.md$/, ''), join(cRoot, entry.name))
558
- } else if (entry.isDirectory()) {
559
- const skillMd = join(cRoot, entry.name, 'SKILL.md')
560
- const directMd = join(cRoot, `${entry.name}.md`)
561
- const targetMd = existsSync(skillMd) ? skillMd : (existsSync(directMd) ? directMd : null)
562
- if (targetMd) {
563
- addSkill(entry.name, targetMd)
564
- }
1007
+ const inlineFallbacks = []
1008
+ const declared = manifest?.commands
1009
+ if (typeof declared === 'string') {
1010
+ const resolved = resolvePluginSpecPath(dir, declared)
1011
+ if (resolved) candidateCmdRoots.push(resolved)
1012
+ } else if (Array.isArray(declared)) {
1013
+ for (const item of declared) {
1014
+ if (typeof item === 'string') {
1015
+ const resolved = resolvePluginSpecPath(dir, item)
1016
+ if (resolved && existsSync(resolved)) {
1017
+ candidateCmdRoots.push(resolved)
1018
+ } else {
1019
+ inlineFallbacks.push(item)
1020
+ }
1021
+ } else if (item && typeof item === 'object') {
1022
+ const rel = item.source || item.path || item.file
1023
+ const resolved = typeof rel === 'string' ? resolvePluginSpecPath(dir, rel) : null
1024
+ if (resolved && existsSync(resolved)) {
1025
+ if (statSync(resolved).isFile()) {
1026
+ const name = item.name || basename(resolved).replace(/\.md$/i, '')
1027
+ seenFiles.add(resolve(resolved))
1028
+ pushEntry({ name, filePath: resolved, content: null, description: item.description || '' })
1029
+ } else {
1030
+ candidateCmdRoots.push(resolved)
565
1031
  }
1032
+ } else if (item.name) {
1033
+ if (typeof item.content === 'string') {
1034
+ pushEntry({
1035
+ name: item.name,
1036
+ filePath: null,
1037
+ content: item.content,
1038
+ description: item.description || '',
1039
+ })
1040
+ } else {
1041
+ inlineFallbacks.push({ name: item.name, description: item.description || '' })
1042
+ }
1043
+ }
1044
+ }
1045
+ }
1046
+ } else if (declared && typeof declared === 'object') {
1047
+ for (const [cmdName, cfg] of Object.entries(declared)) {
1048
+ if (typeof cfg === 'string') {
1049
+ const resolved = resolvePluginSpecPath(dir, cfg)
1050
+ if (resolved && existsSync(resolved)) {
1051
+ if (statSync(resolved).isFile()) {
1052
+ seenFiles.add(resolve(resolved))
1053
+ pushEntry({ name: cmdName, filePath: resolved, content: null, description: '' })
1054
+ } else {
1055
+ scanCommandDirectory(resolved, seenFiles, pushEntry, cmdName)
1056
+ }
1057
+ } else {
1058
+ inlineFallbacks.push({ name: cmdName, description: cfg })
566
1059
  }
1060
+ } else if (cfg && typeof cfg === 'object') {
1061
+ const rel = cfg.source || cfg.path || cfg.file
1062
+ const resolved = typeof rel === 'string' ? resolvePluginSpecPath(dir, rel) : null
1063
+ if (resolved && existsSync(resolved) && statSync(resolved).isFile()) {
1064
+ seenFiles.add(resolve(resolved))
1065
+ pushEntry({ name: cmdName, filePath: resolved, content: null, description: cfg.description || '' })
1066
+ } else if (typeof cfg.content === 'string') {
1067
+ pushEntry({
1068
+ name: cmdName,
1069
+ filePath: null,
1070
+ content: cfg.content,
1071
+ description: cfg.description || '',
1072
+ })
1073
+ } else {
1074
+ inlineFallbacks.push({ name: cmdName, description: cfg.description || '' })
1075
+ }
1076
+ }
1077
+ }
1078
+ }
1079
+
1080
+ for (const cRoot of candidateCmdRoots) {
1081
+ scanCommandDirectory(cRoot, seenFiles, pushEntry)
1082
+ }
1083
+
1084
+ return { entries, inlineFallbacks }
1085
+ }
1086
+
1087
+ /** List skill & command directories/files (skills/*, commands/*, root SKILL.md, manifest declarations). */
1088
+ export function listSkills(dir, manifest = readPluginManifest(dir)) {
1089
+ const out = []
1090
+ const seen = new Set()
1091
+
1092
+ const addSkill = (name, skillMdPath, inlineContent = null, fallbackDesc = '') => {
1093
+ if (!name || seen.has(name)) return
1094
+ let description = ''
1095
+ if (skillMdPath) {
1096
+ try {
1097
+ description = extractMdDescription(readFileSync(skillMdPath, 'utf8'))
567
1098
  } catch {}
1099
+ } else if (typeof inlineContent === 'string') {
1100
+ description = extractMdDescription(inlineContent)
568
1101
  }
1102
+ out.push({ name, command: `/${name}`, description: description || fallbackDesc || '' })
1103
+ seen.add(name)
569
1104
  }
570
1105
 
1106
+ const NON_SKILL_DIRS = new Set([
1107
+ 'node_modules', '.git', '.agents', '.claude-plugin', '.codex-plugin', '.well-known',
1108
+ 'agents', 'commands', 'prompts', 'hooks', '.cursor', 'docs', 'assets', 'eval',
1109
+ 'staging', 'walkthroughs', 'mcp', 'lsp', 'scripts', 'server', 'dist', 'build', '__pycache__',
1110
+ ])
1111
+
1112
+ // 1. Check skills/ and manifest.skills paths (including '.' and './...')
1113
+ const rawSkills = typeof manifest?.skills === 'string' ? [manifest.skills] : (Array.isArray(manifest?.skills) ? manifest.skills : [])
1114
+ const declaredSkillPaths = rawSkills
1115
+ .filter((s) => typeof s === 'string' && isDotRelativePath(s))
1116
+ .map((p) => resolvePluginSpecPath(dir, p))
1117
+ .filter(Boolean)
1118
+ const candidateSkillRoots = []
1119
+ const seenSkillRoots = new Set()
1120
+ for (const rootCandidate of [...declaredSkillPaths, join(dir, 'skills'), join(dir, '..', 'skills')]) {
1121
+ const resolvedRoot = resolve(rootCandidate)
1122
+ if (seenSkillRoots.has(resolvedRoot)) continue
1123
+ seenSkillRoots.add(resolvedRoot)
1124
+ candidateSkillRoots.push(rootCandidate)
1125
+ }
571
1126
 
1127
+ for (const sRoot of candidateSkillRoots) {
1128
+ if (!existsSync(sRoot)) continue
1129
+ try {
1130
+ if (statSync(sRoot).isFile()) {
1131
+ if (/^skill\.md$/i.test(basename(sRoot))) addSkill(basename(dirname(sRoot)), sRoot)
1132
+ else if (/\.md$/i.test(sRoot)) addSkill(basename(sRoot).replace(/\.md$/i, ''), sRoot)
1133
+ continue
1134
+ }
1135
+ const rootMd = ['SKILL.md', 'skill.md'].map((f) => join(sRoot, f)).find(existsSync)
1136
+ if (rootMd && resolve(sRoot) !== resolve(dir)) {
1137
+ addSkill(basename(sRoot), rootMd)
1138
+ }
1139
+ for (const entry of readdirSync(sRoot, { withFileTypes: true })) {
1140
+ if (entry.isDirectory()) {
1141
+ if (NON_SKILL_DIRS.has(entry.name) || entry.name.startsWith('.')) continue
1142
+ const skillMd = join(sRoot, entry.name, 'SKILL.md')
1143
+ const altMd = join(sRoot, entry.name, 'skill.md')
1144
+ if (existsSync(skillMd)) {
1145
+ addSkill(entry.name, skillMd)
1146
+ } else if (existsSync(altMd)) {
1147
+ addSkill(entry.name, altMd)
1148
+ }
1149
+ } else if (entry.isFile() && entry.name.endsWith('.md') && !['README.md', 'CONTRIBUTING.md', 'LICENSE.md', 'CHANGELOG.md', 'SKILL.md', 'skill.md'].includes(entry.name)) {
1150
+ const name = entry.name.replace(/\.md$/, '')
1151
+ addSkill(name, join(sRoot, entry.name))
1152
+ }
1153
+ }
1154
+ } catch {}
1155
+ }
1156
+
1157
+ // 2. Check commands/ and .claude/commands/ and manifest.commands
1158
+ const { entries: cmdEntries, inlineFallbacks: cmdFallbacks } = resolvePluginCommandEntries(dir, manifest)
1159
+ for (const cmd of cmdEntries) {
1160
+ addSkill(cmd.name, cmd.filePath, cmd.content, cmd.description)
1161
+ }
572
1162
 
573
1163
  // 4. Single-skill repository fallback: if no skills/ or commands/ exist, check root SKILL.md
574
1164
  if (out.length === 0) {
@@ -584,14 +1174,14 @@ export function listSkills(dir) {
584
1174
  }
585
1175
  }
586
1176
 
587
- // 5. Check manifest (plugin.json / package.json / marketplace.json "skills" / "commands")
1177
+ // 5. Fallback for non-path entries declared in manifest.skills / manifest.commands
588
1178
  if (manifest && out.length === 0) {
589
1179
  if (Array.isArray(manifest.skills)) {
590
1180
  for (const item of manifest.skills) {
591
1181
  const rawName = typeof item === 'string' ? item : item?.name
592
1182
  if (rawName) {
593
1183
  const name = basename(rawName).replace(/\.(md|mdc)$/i, '')
594
- if (name && !['skills', 'commands'].includes(name.toLowerCase()) && !seen.has(name)) {
1184
+ if (name && !['.', 'skills', 'commands'].includes(name.toLowerCase()) && !seen.has(name)) {
595
1185
  seen.add(name)
596
1186
  out.push({
597
1187
  name,
@@ -602,20 +1192,12 @@ export function listSkills(dir) {
602
1192
  }
603
1193
  }
604
1194
  }
605
- if (Array.isArray(manifest.commands)) {
606
- for (const item of manifest.commands) {
607
- const rawName = typeof item === 'string' ? item : item?.name
608
- if (rawName) {
609
- const name = basename(rawName).replace(/\.md$/i, '')
610
- if (name && !['skills', 'commands'].includes(name.toLowerCase()) && !seen.has(name)) {
611
- seen.add(name)
612
- out.push({
613
- name,
614
- command: `/${name}`,
615
- description: typeof item === 'object' ? item.description || '' : '',
616
- })
617
- }
618
- }
1195
+ for (const item of cmdFallbacks) {
1196
+ const rawName = typeof item === 'string' ? item : item?.name
1197
+ const name = rawName ? basename(rawName).replace(/\.md$/i, '') : ''
1198
+ if (name && !['.', 'skills', 'commands'].includes(name.toLowerCase()) && !seen.has(name)) {
1199
+ seen.add(name)
1200
+ out.push({ name, command: `/${name}`, description: typeof item === 'object' ? (item.description || '') : '' })
619
1201
  }
620
1202
  }
621
1203
  }
@@ -623,124 +1205,167 @@ export function listSkills(dir) {
623
1205
  return out
624
1206
  }
625
1207
 
626
- /** List agent definition files (agents/*.yaml|yml|md|json, .well-known/agent-card.json, agent.json). */
627
- export function listAgents(dir) {
1208
+ /** List agent definition files (agents/<subpath>/*.yaml|yml|md|json, .well-known/agent-card.json, agent.json, manifest.agents). */
1209
+ export function listAgents(dir, manifest = readPluginManifest(dir)) {
628
1210
  const out = []
629
- const seen = new Set()
630
-
631
- const candidateAgentRoots = [
632
- join(dir, 'agents'),
633
- join(dir, '.agents'),
634
- join(dir, '..', 'agents'),
635
- join(dir, '..', '.agents'),
636
- join(dir, '.claude-plugin', 'agents'),
637
- join(dir, '..', '.claude-plugin', 'agents'),
638
- ]
639
-
1211
+ const seenFiles = new Set()
1212
+ const seenNames = new Set()
640
1213
  const pluginName = basename(dir)
641
1214
 
642
- for (const agentsRoot of candidateAgentRoots) {
643
- if (existsSync(agentsRoot)) {
644
- try {
645
- for (const entry of readdirSync(agentsRoot, { withFileTypes: true })) {
646
- if (!entry.isFile()) continue
647
- if (!/\.(ya?ml|md|json)$/i.test(entry.name)) continue
648
- if (seen.has(entry.name)) continue
649
-
650
- try {
651
- const raw = readFileSync(join(agentsRoot, entry.name), 'utf8')
652
- if (raw) {
653
- const parsed = parseAgentDefinition(pluginName, entry.name, raw)
654
- if (parsed && !parsed.error) {
655
- seen.add(entry.name)
656
- out.push({
657
- file: entry.name,
658
- name: parsed.name,
659
- displayName: parsed.displayName || parsed.name,
660
- description: parsed.description,
661
- tools: parsed.tools,
662
- model: parsed.model,
663
- instructions: parsed.instructions,
664
- raw,
665
- })
666
- continue
667
- }
668
- }
669
- } catch { /* skip */ }
670
-
671
- // Fallback if parsing failed
672
- seen.add(entry.name)
673
- const fallbackName = entry.name.replace(/\.[^.]+$/, '')
1215
+ const addAgentFile = (filePath, labelName) => {
1216
+ const absPath = resolve(filePath)
1217
+ if (seenFiles.has(absPath)) return
1218
+ seenFiles.add(absPath)
1219
+ const fileLabel = labelName.replace(/\\/g, '/')
1220
+ try {
1221
+ const raw = readFileSync(filePath, 'utf8')
1222
+ if (raw) {
1223
+ const parsed = parseAgentDefinition(pluginName, fileLabel, raw)
1224
+ if (parsed && !parsed.error) {
1225
+ const dedupeKey = parsed.name || fileLabel
1226
+ if (seenNames.has(dedupeKey)) return
1227
+ seenNames.add(dedupeKey)
674
1228
  out.push({
675
- file: entry.name,
676
- name: fallbackName,
677
- displayName: formatDisplayName(fallbackName),
678
- description: 'Autonomous sub-agent workflow',
679
- tools: null,
680
- model: null,
681
- instructions: '',
682
- raw: null,
1229
+ file: fileLabel,
1230
+ name: parsed.name,
1231
+ displayName: parsed.displayName || parsed.name,
1232
+ description: parsed.description,
1233
+ tools: parsed.tools,
1234
+ model: parsed.model,
1235
+ instructions: parsed.instructions,
1236
+ raw,
683
1237
  })
1238
+ return
684
1239
  }
685
- } catch {}
1240
+ }
1241
+ } catch { /* skip */ }
1242
+
1243
+ const fallbackName = basename(fileLabel).replace(/\.[^.]+$/, '')
1244
+ if (seenNames.has(fallbackName)) return
1245
+ seenNames.add(fallbackName)
1246
+ out.push({
1247
+ file: fileLabel,
1248
+ name: fallbackName,
1249
+ displayName: formatDisplayName(fallbackName),
1250
+ description: 'Autonomous sub-agent workflow',
1251
+ tools: null,
1252
+ model: null,
1253
+ instructions: '',
1254
+ raw: null,
1255
+ })
1256
+ }
1257
+
1258
+ const walkAgentDir = (rootDir, prefix = '', allowRecurse = true) => {
1259
+ if (!existsSync(rootDir)) return
1260
+ try {
1261
+ const st = statSync(rootDir)
1262
+ if (st.isFile()) {
1263
+ if (/\.(ya?ml|md|json)$/i.test(rootDir)) {
1264
+ addAgentFile(rootDir, (relative(dir, rootDir) || basename(rootDir)).replace(/\\/g, '/'))
1265
+ }
1266
+ return
1267
+ }
1268
+ for (const entry of readdirSync(rootDir, { withFileTypes: true })) {
1269
+ if (entry.name === 'node_modules' || entry.name === '.git') continue
1270
+ const full = join(rootDir, entry.name)
1271
+ const relLabel = prefix ? `${prefix}/${entry.name}` : entry.name
1272
+ if (entry.isFile() && /\.(ya?ml|md|json)$/i.test(entry.name)) {
1273
+ addAgentFile(full, relLabel)
1274
+ } else if (entry.isDirectory() && allowRecurse && entry.name !== 'plugins' && entry.name !== 'skills') {
1275
+ walkAgentDir(full, relLabel, true)
1276
+ }
1277
+ }
1278
+ } catch {}
1279
+ }
1280
+
1281
+ const declaredAgents = typeof manifest?.agents === 'string'
1282
+ ? [manifest.agents]
1283
+ : (Array.isArray(manifest?.agents) ? manifest.agents : [])
1284
+ const fallbackAgentItems = []
1285
+
1286
+ // Explicit manifest paths resolved first (supports nested files and custom subdirs like './custom-agents')
1287
+ for (const item of declaredAgents) {
1288
+ const spec = typeof item === 'string' ? item : (item?.source || item?.path || item?.file)
1289
+ if (typeof spec === 'string') {
1290
+ const resolved = resolvePluginSpecPath(dir, spec)
1291
+ if (resolved && existsSync(resolved)) {
1292
+ const relPrefix = relative(dir, resolved).replace(/\\/g, '/')
1293
+ const initPrefix = (!relPrefix || relPrefix === '.' || relPrefix === 'agents' || relPrefix === '.agents' || relPrefix === '.claude-plugin/agents')
1294
+ ? ''
1295
+ : relPrefix
1296
+ walkAgentDir(resolved, initPrefix, true)
1297
+ continue
1298
+ }
686
1299
  }
1300
+ fallbackAgentItems.push(item)
687
1301
  }
688
1302
 
1303
+ walkAgentDir(join(dir, 'agents'), '', true)
1304
+ walkAgentDir(join(dir, '.agents'), '', false)
1305
+ walkAgentDir(join(dir, '..', 'agents'), '', true)
1306
+ walkAgentDir(join(dir, '..', '.agents'), '', false)
1307
+ walkAgentDir(join(dir, '.claude-plugin', 'agents'), '', true)
1308
+ walkAgentDir(join(dir, '..', '.claude-plugin', 'agents'), '', true)
1309
+
689
1310
  // Check Agent Card format (.well-known/agent-card.json or agent.json)
690
1311
  for (const agentCardPath of [join(dir, '.well-known', 'agent-card.json'), join(dir, 'agent.json')]) {
691
- if (existsSync(agentCardPath) && !seen.has(basename(agentCardPath))) {
1312
+ if (existsSync(agentCardPath) && !seenFiles.has(resolve(agentCardPath))) {
1313
+ seenFiles.add(resolve(agentCardPath))
692
1314
  try {
693
1315
  const raw = readFileSync(agentCardPath, 'utf8')
694
1316
  const parsed = parseAgentDefinition(pluginName, basename(agentCardPath), raw)
695
- seen.add(basename(agentCardPath))
696
1317
  if (parsed && !parsed.error) {
697
- out.push({
698
- file: basename(agentCardPath),
699
- name: parsed.name,
700
- displayName: parsed.displayName || parsed.name,
701
- description: parsed.description,
702
- tools: parsed.tools,
703
- model: parsed.model,
704
- instructions: parsed.instructions,
705
- raw,
706
- })
1318
+ if (!seenNames.has(parsed.name)) {
1319
+ seenNames.add(parsed.name)
1320
+ out.push({
1321
+ file: basename(agentCardPath),
1322
+ name: parsed.name,
1323
+ displayName: parsed.displayName || parsed.name,
1324
+ description: parsed.description,
1325
+ tools: parsed.tools,
1326
+ model: parsed.model,
1327
+ instructions: parsed.instructions,
1328
+ raw,
1329
+ })
1330
+ }
707
1331
  } else {
708
1332
  const jsonDoc = JSON.parse(raw)
709
- out.push({
710
- file: basename(agentCardPath),
711
- name: jsonDoc.name || basename(dir),
712
- displayName: jsonDoc.displayName || formatDisplayName(jsonDoc.name || basename(dir)),
713
- description: jsonDoc.description || '',
714
- tools: jsonDoc.tools || null,
715
- model: jsonDoc.model || null,
716
- instructions: jsonDoc.instructions || '',
717
- raw,
718
- })
1333
+ const agentName = jsonDoc.name || basename(dir)
1334
+ if (!seenNames.has(agentName)) {
1335
+ seenNames.add(agentName)
1336
+ out.push({
1337
+ file: basename(agentCardPath),
1338
+ name: agentName,
1339
+ displayName: jsonDoc.displayName || formatDisplayName(agentName),
1340
+ description: jsonDoc.description || '',
1341
+ tools: jsonDoc.tools || null,
1342
+ model: jsonDoc.model || null,
1343
+ instructions: jsonDoc.instructions || '',
1344
+ raw,
1345
+ })
1346
+ }
719
1347
  }
720
1348
  } catch {}
721
1349
  }
722
1350
  }
723
1351
 
724
- // Check manifest "agents" array
725
- const manifest = readPluginManifest(dir)
726
- if (manifest && Array.isArray(manifest.agents)) {
727
- for (const item of manifest.agents) {
728
- const rawName = typeof item === 'string' ? item : item?.name
729
- if (rawName && !seen.has(rawName)) {
730
- seen.add(rawName)
731
- const name = typeof item === 'string' ? item : (item.name || rawName)
732
- const displayName = typeof item === 'object' && item.displayName ? item.displayName : (typeof item === 'object' && item.name ? item.name : formatDisplayName(name))
733
- out.push({
734
- file: typeof item === 'object' && item.file ? item.file : `${name}.md`,
735
- name,
736
- displayName,
737
- description: typeof item === 'object' ? item.description || '' : '',
738
- tools: typeof item === 'object' ? item.tools || null : null,
739
- model: typeof item === 'object' ? item.model || null : null,
740
- instructions: '',
741
- raw: null,
742
- })
743
- }
1352
+ // Fallback for non-path items declared in manifest.agents
1353
+ for (const item of fallbackAgentItems) {
1354
+ const rawName = typeof item === 'string' ? item : item?.name
1355
+ if (rawName && !seenNames.has(rawName)) {
1356
+ seenNames.add(rawName)
1357
+ const name = typeof item === 'string' ? item : (item.name || rawName)
1358
+ const displayName = typeof item === 'object' && item.displayName ? item.displayName : (typeof item === 'object' && item.name ? item.name : formatDisplayName(name))
1359
+ out.push({
1360
+ file: typeof item === 'object' && item.file ? item.file : `${name}.md`,
1361
+ name,
1362
+ displayName,
1363
+ description: typeof item === 'object' ? item.description || '' : '',
1364
+ tools: typeof item === 'object' ? item.tools || null : null,
1365
+ model: typeof item === 'object' ? item.model || null : null,
1366
+ instructions: '',
1367
+ raw: null,
1368
+ })
744
1369
  }
745
1370
  }
746
1371
 
@@ -748,7 +1373,7 @@ export function listAgents(dir) {
748
1373
  }
749
1374
 
750
1375
  /** Prompt-ish entries: prompts/*.md|txt|yaml or plugin.json "prompts". */
751
- export function listPrompts(dir) {
1376
+ export function listPrompts(dir, manifest = readPluginManifest(dir)) {
752
1377
  const prompts = []
753
1378
  const pRoots = [join(dir, 'prompts'), join(dir, '..', 'prompts')]
754
1379
  for (const pRoot of pRoots) {
@@ -762,7 +1387,6 @@ export function listPrompts(dir) {
762
1387
  } catch {}
763
1388
  }
764
1389
  }
765
- const manifest = readPluginManifest(dir)
766
1390
  if (manifest && Array.isArray(manifest.prompts)) {
767
1391
  prompts.push(...manifest.prompts.map((p) => (typeof p === 'string' ? p : p.name)).filter(Boolean))
768
1392
  }
@@ -784,24 +1408,34 @@ function formatHookEventName(evt) {
784
1408
  return map[evt] || evt
785
1409
  }
786
1410
 
787
- /**
788
- * Parse hook event names from a Claude/Codex hook config file's content.
789
- * Accepts `{ hooks: {...} }`, a doubly-nested `{ hooks: { hooks: {...} } }`,
790
- * or a bare event map. Never treats implementation scripts as hooks.
791
- */
792
- export function parseHookConfig(raw, isJson) {
793
- const out = []
1411
+ function extractHookEventMap(raw, isJson) {
794
1412
  let parsed
795
1413
  try {
796
1414
  parsed = isJson ? JSON.parse(raw) : parseYaml(raw)
797
1415
  } catch {
798
- return out
1416
+ return null
799
1417
  }
800
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return out
1418
+ return unwrapHookObject(parsed)
1419
+ }
1420
+
1421
+ function unwrapHookObject(parsed) {
1422
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null
801
1423
  let hookObj = (parsed.hooks && typeof parsed.hooks === 'object' && !Array.isArray(parsed.hooks)) ? parsed.hooks : parsed
802
1424
  if (hookObj && typeof hookObj === 'object' && !Array.isArray(hookObj) && typeof hookObj.hooks === 'object' && !Array.isArray(hookObj.hooks)) {
803
1425
  hookObj = hookObj.hooks
804
1426
  }
1427
+ return hookObj
1428
+ }
1429
+
1430
+ /**
1431
+ * Parse hook event names from a Claude/Codex hook config file's content.
1432
+ * Accepts `{ hooks: {...} }`, a doubly-nested `{ hooks: { hooks: {...} } }`,
1433
+ * or a bare event map. Never treats implementation scripts as hooks.
1434
+ */
1435
+ export function parseHookConfig(raw, isJson) {
1436
+ const out = []
1437
+ const hookObj = extractHookEventMap(raw, isJson)
1438
+ if (!hookObj) return out
805
1439
  for (const [eventName, val] of Object.entries(hookObj)) {
806
1440
  const formattedEvent = formatHookEventName(eventName)
807
1441
  if (Array.isArray(val)) {
@@ -819,61 +1453,174 @@ export function parseHookConfig(raw, isJson) {
819
1453
  return out
820
1454
  }
821
1455
 
1456
+ function collectHookSources(dir, manifest = readPluginManifest(dir)) {
1457
+ const sources = []
1458
+ const seenFiles = new Set()
1459
+
1460
+ const addFile = (filePath) => {
1461
+ if (!filePath || !existsSync(filePath)) return false
1462
+ try {
1463
+ if (!statSync(filePath).isFile()) return false
1464
+ const key = resolve(filePath)
1465
+ if (seenFiles.has(key)) return true
1466
+ seenFiles.add(key)
1467
+ sources.push({ type: 'file', path: filePath, isJson: /\.json$/i.test(filePath) })
1468
+ return true
1469
+ } catch {
1470
+ return false
1471
+ }
1472
+ }
1473
+
1474
+ const addInlineItem = (item) => {
1475
+ if (typeof item === 'string') {
1476
+ const resolved = resolvePluginSpecPath(dir, item)
1477
+ if (resolved && addFile(resolved)) return
1478
+ if (!/\.(json|ya?ml)$/i.test(item) && !isDotRelativePath(item)) {
1479
+ sources.push({ type: 'label', label: item })
1480
+ }
1481
+ return
1482
+ }
1483
+ if (item && typeof item === 'object' && !Array.isArray(item)) {
1484
+ if (typeof item.name === 'string' && !item.hooks && Object.keys(item).length <= 2) {
1485
+ sources.push({ type: 'label', label: item.name })
1486
+ return
1487
+ }
1488
+ const eventMap = unwrapHookObject(item)
1489
+ if (eventMap && Object.keys(eventMap).length > 0) {
1490
+ sources.push({ type: 'inline', eventMap })
1491
+ }
1492
+ }
1493
+ }
1494
+
1495
+ if (manifest?.hooks !== undefined) {
1496
+ if (Array.isArray(manifest.hooks)) {
1497
+ for (const item of manifest.hooks) addInlineItem(item)
1498
+ } else {
1499
+ addInlineItem(manifest.hooks)
1500
+ }
1501
+ }
1502
+
1503
+ const hooksRoot = join(dir, 'hooks')
1504
+ if (existsSync(hooksRoot)) {
1505
+ for (const fixedName of ['hooks.json', 'hooks.yaml', 'hooks.yml']) {
1506
+ if (addFile(join(hooksRoot, fixedName))) break
1507
+ }
1508
+ if (seenFiles.size === 0) {
1509
+ try {
1510
+ const dialect = readdirSync(hooksRoot)
1511
+ .filter((n) => /-hooks\.(json|ya?ml)$/i.test(n) && statSync(join(hooksRoot, n)).isFile())
1512
+ .sort((a, b) => {
1513
+ const score = (n) => (/claude/i.test(n) ? 0 : (/codex/i.test(n) ? 1 : 2))
1514
+ return score(a) - score(b)
1515
+ })
1516
+ if (dialect.length > 0) addFile(join(hooksRoot, dialect[0]))
1517
+ } catch {}
1518
+ }
1519
+ }
1520
+
1521
+ return sources
1522
+ }
1523
+
822
1524
  /**
823
1525
  * Resolve the plugin's Claude/Codex hook config file path: the manifest `hooks`
824
1526
  * path first, then `hooks/hooks.json|yaml|yml`, then `*-hooks.{json,yaml}` files.
825
1527
  * Returns null when the plugin declares no hook config (e.g. only scripts).
826
1528
  */
827
- export function resolveHookConfigPath(dir) {
828
- const manifest = readPluginManifest(dir)
829
- if (manifest && typeof manifest.hooks === 'string') {
830
- const p = isAbsolute(manifest.hooks) ? manifest.hooks : join(dir, manifest.hooks)
831
- if (existsSync(p) && statSync(p).isFile()) return p
832
- }
833
- const hooksRoot = join(dir, 'hooks')
834
- if (existsSync(hooksRoot)) {
835
- const fixed = ['hooks.json', 'hooks.yaml', 'hooks.yml'].map((n) => join(hooksRoot, n)).find((p) => existsSync(p) && statSync(p).isFile())
836
- if (fixed) return fixed
837
- try {
838
- const dialect = readdirSync(hooksRoot)
839
- .filter((n) => /-hooks\.(json|ya?ml)$/i.test(n) && statSync(join(hooksRoot, n)).isFile())
840
- .sort((a, b) => {
841
- const score = (n) => (/claude/i.test(n) ? 0 : (/codex/i.test(n) ? 1 : 2))
842
- return score(a) - score(b)
843
- })
844
- if (dialect.length > 0) return join(hooksRoot, dialect[0])
845
- } catch {}
846
- }
847
- return null
1529
+ export function resolveHookConfigPath(dir, manifest = readPluginManifest(dir)) {
1530
+ const firstFile = collectHookSources(dir, manifest).find((s) => s.type === 'file')
1531
+ return firstFile ? firstFile.path : null
848
1532
  }
849
1533
 
850
1534
  /** Hook entries: follow the plugin manifest's `hooks` config, then hooks/ config files. */
851
- export function listHooks(dir) {
1535
+ export function listHooks(dir, manifest = readPluginManifest(dir)) {
852
1536
  const hooks = []
853
1537
  const seen = new Set()
854
1538
  const add = (h) => { if (h && !seen.has(h)) { seen.add(h); hooks.push(h) } }
855
1539
 
856
- const cfg = resolveHookConfigPath(dir)
857
- if (cfg) {
858
- try {
859
- const raw = readFileSync(cfg, 'utf8')
860
- for (const h of parseHookConfig(raw, /\.json$/i.test(cfg))) add(h)
861
- } catch {}
1540
+ for (const src of collectHookSources(dir, manifest)) {
1541
+ if (src.type === 'file') {
1542
+ try {
1543
+ const raw = readFileSync(src.path, 'utf8')
1544
+ for (const h of parseHookConfig(raw, src.isJson)) add(h)
1545
+ } catch {}
1546
+ } else if (src.type === 'inline') {
1547
+ for (const h of parseHookConfig(JSON.stringify({ hooks: src.eventMap }), true)) add(h)
1548
+ } else if (src.type === 'label') {
1549
+ add(src.label)
1550
+ }
1551
+ }
1552
+
1553
+ return hooks
1554
+ }
1555
+
1556
+ function formatHookCmdArg(arg) {
1557
+ return /[\s"'\\$`]/.test(arg) ? JSON.stringify(arg) : arg
1558
+ }
1559
+
1560
+ /**
1561
+ * Compile all Claude/Codex hook sources (JSON, YAML, inline objects, mixed arrays,
1562
+ * `args` arrays, and builtin variables) into a single JSON structure compatible
1563
+ * with `@deepseek-ai/dsh-hooks-claude-code`. Returns null if no hook rules exist.
1564
+ */
1565
+ export function compileResolvedHooks(pluginRoot, manifest = readPluginManifest(pluginRoot), explicitDataDir) {
1566
+ const compiled = {}
1567
+ const eventMaps = []
1568
+
1569
+ for (const src of collectHookSources(pluginRoot, manifest)) {
1570
+ if (src.type === 'file') {
1571
+ try {
1572
+ const map = extractHookEventMap(readFileSync(src.path, 'utf8'), src.isJson)
1573
+ if (map) eventMaps.push(map)
1574
+ } catch {}
1575
+ } else if (src.type === 'inline') {
1576
+ eventMaps.push(src.eventMap)
1577
+ }
862
1578
  }
863
1579
 
864
- // Manifest `hooks` as inline object/array (no file path to follow).
865
- if (hooks.length === 0) {
866
- const manifest = readPluginManifest(dir)
867
- if (manifest && manifest.hooks) {
868
- if (Array.isArray(manifest.hooks)) {
869
- for (const h of manifest.hooks) add(typeof h === 'string' ? h : (h && h.name))
870
- } else if (typeof manifest.hooks === 'object') {
871
- for (const h of parseHookConfig(JSON.stringify({ hooks: manifest.hooks }), true)) add(h)
1580
+ for (const eventMap of eventMaps) {
1581
+ for (const [eventName, val] of Object.entries(eventMap)) {
1582
+ const rules = Array.isArray(val) ? val : (val && typeof val === 'object' ? [val] : [])
1583
+ for (const rule of rules) {
1584
+ if (!rule || typeof rule !== 'object') continue
1585
+ const rawInner = Array.isArray(rule.hooks) ? rule.hooks : (rule.command || rule.type ? [rule] : [])
1586
+ const compiledInner = []
1587
+ for (const h of rawInner) {
1588
+ if (!h || typeof h !== 'object') continue
1589
+ if (h.type === undefined || h.type === 'command') {
1590
+ let cmd = typeof h.command === 'string' ? expandPluginVars(h.command, pluginRoot, explicitDataDir).trim() : ''
1591
+ if (pluginRoot && /^\.\.?[\\/]/.test(cmd)) {
1592
+ const m = cmd.match(/^(\S+)([\s\S]*)$/)
1593
+ if (m) {
1594
+ const resolvedBin = resolvePluginCommand(m[1], pluginRoot, explicitDataDir)
1595
+ cmd = resolvedBin ? `${resolvedBin}${m[2]}` : ''
1596
+ }
1597
+ }
1598
+ if (Array.isArray(h.args) && h.args.length > 0) {
1599
+ const extraArgs = h.args.map((a) => {
1600
+ const expanded = expandPluginVars(String(a), pluginRoot, explicitDataDir)
1601
+ return formatHookCmdArg(expanded)
1602
+ })
1603
+ cmd = [cmd, ...extraArgs].filter(Boolean).join(' ')
1604
+ }
1605
+ if (!cmd) continue
1606
+ const { args: _droppedArgs, ...rest } = h
1607
+ compiledInner.push({ ...rest, type: 'command', command: cmd })
1608
+ } else {
1609
+ compiledInner.push(expandPluginVars(h, pluginRoot, explicitDataDir))
1610
+ }
1611
+ }
1612
+ if (compiledInner.length > 0) {
1613
+ if (!compiled[eventName]) compiled[eventName] = []
1614
+ compiled[eventName].push({
1615
+ ...(rule.matcher !== undefined ? { matcher: rule.matcher } : {}),
1616
+ hooks: compiledInner,
1617
+ })
1618
+ }
872
1619
  }
873
1620
  }
874
1621
  }
875
1622
 
876
- return hooks
1623
+ return Object.keys(compiled).length > 0 ? { hooks: compiled } : null
877
1624
  }
878
1625
 
879
1626
  /**
@@ -898,159 +1645,207 @@ export function isRemoteTransportName(type) {
898
1645
  return type === 'http' || type === 'sse' || type === 'streamable-http' || type === 'streamableHttp'
899
1646
  }
900
1647
 
901
- /** Connector-ish entries: .mcp.json, mcp.json, server.json, or plugin.json "mcp" / "connectors". */
902
- export function listConnectors(dir) {
1648
+ function extractConnectorDict(mcp) {
1649
+ if (!mcp || typeof mcp !== 'object' || Array.isArray(mcp)) return null
1650
+ if (mcp.mcpServers && typeof mcp.mcpServers === 'object') return mcp.mcpServers
1651
+ if (mcp.servers && typeof mcp.servers === 'object') return mcp.servers
1652
+ if (mcp.name && (mcp.url || mcp.command || mcp.type)) return { [mcp.name]: mcp }
1653
+ const direct = {}
1654
+ for (const [k, v] of Object.entries(mcp)) {
1655
+ if (v && typeof v === 'object' && !Array.isArray(v)) {
1656
+ if (v.url || v.command || v.type || v.args || v.headers || v.env || v.cwd !== undefined) {
1657
+ direct[k] = v
1658
+ }
1659
+ }
1660
+ }
1661
+ return Object.keys(direct).length > 0 ? direct : null
1662
+ }
1663
+
1664
+ function pushConnectorDict(dict, seen, connectors) {
1665
+ if (!dict || typeof dict !== 'object') return
1666
+ for (const [name, cfg] of Object.entries(dict)) {
1667
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue
1668
+ if (!seen.has(name)) {
1669
+ seen.add(name)
1670
+ connectors.push({
1671
+ name,
1672
+ type: connectorTransport(cfg.type, cfg.url, cfg.command),
1673
+ url: cfg.url || null,
1674
+ command: cfg.command || null,
1675
+ args: Array.isArray(cfg.args) ? cfg.args : [],
1676
+ ...(cfg.cwd !== undefined ? { cwd: cfg.cwd } : {}),
1677
+ env: cfg.env || {},
1678
+ headers: cfg.headers || {},
1679
+ })
1680
+ }
1681
+ }
1682
+ }
1683
+
1684
+ function loadMcpEntry(entry, dir, seen, connectors, seenFiles) {
1685
+ if (!entry) return
1686
+ if (typeof entry === 'string') {
1687
+ const resolved = resolvePluginSpecPath(dir, entry)
1688
+ if (!resolved || !existsSync(resolved)) return
1689
+ const key = resolve(resolved)
1690
+ if (seenFiles.has(key)) return
1691
+ seenFiles.add(key)
1692
+ try {
1693
+ const mcp = JSON.parse(readFileSync(resolved, 'utf8'))
1694
+ pushConnectorDict(extractConnectorDict(mcp), seen, connectors)
1695
+ } catch { /* ignore malformed */ }
1696
+ return
1697
+ }
1698
+ if (Array.isArray(entry)) {
1699
+ for (const item of entry) loadMcpEntry(item, dir, seen, connectors, seenFiles)
1700
+ return
1701
+ }
1702
+ if (typeof entry === 'object') {
1703
+ pushConnectorDict(extractConnectorDict(entry), seen, connectors)
1704
+ }
1705
+ }
1706
+
1707
+ /** Connector-ish entries: .mcp.json, mcp.json, server.json, or plugin.json "mcpServers" / "connectors". */
1708
+ export function listConnectors(dir, manifest = readPluginManifest(dir)) {
903
1709
  const connectors = []
904
1710
  const seen = new Set()
1711
+ const seenFiles = new Set()
905
1712
 
906
1713
  for (const mcpFile of ['.mcp.json', 'mcp.json', 'server.json', 'mcp-servers.json']) {
907
1714
  const mcpPath = join(dir, mcpFile)
908
1715
  if (existsSync(mcpPath)) {
909
- try {
910
- const mcp = JSON.parse(readFileSync(mcpPath, 'utf8'))
911
- let dict = null
912
- if (mcp && typeof mcp === 'object' && !Array.isArray(mcp)) {
913
- if (mcp.mcpServers && typeof mcp.mcpServers === 'object') {
914
- dict = mcp.mcpServers
915
- } else if (mcp.servers && typeof mcp.servers === 'object') {
916
- dict = mcp.servers
917
- } else if (mcp.name && (mcp.url || mcp.command || mcp.type)) {
918
- dict = { [mcp.name]: mcp }
919
- } else {
920
- const direct = {}
921
- for (const [k, v] of Object.entries(mcp)) {
922
- if (v && typeof v === 'object' && !Array.isArray(v)) {
923
- if (v.url || v.command || v.type || v.args || v.headers || v.env) {
924
- direct[k] = v
925
- }
926
- }
927
- }
928
- if (Object.keys(direct).length > 0) dict = direct
929
- }
930
- }
931
- if (dict && typeof dict === 'object') {
932
- for (const [name, cfg] of Object.entries(dict)) {
933
- if (!seen.has(name)) {
934
- seen.add(name)
935
- connectors.push({
936
- name,
937
- type: connectorTransport(cfg.type, cfg.url, cfg.command),
938
- url: cfg.url || null,
939
- command: cfg.command || null,
940
- args: cfg.args || [],
941
- env: cfg.env || {},
942
- headers: cfg.headers || {},
943
- })
944
- }
945
- }
946
- }
947
- } catch { /* ignore malformed */ }
1716
+ loadMcpEntry(`./${mcpFile}`, dir, seen, connectors, seenFiles)
948
1717
  }
949
1718
  }
950
1719
 
951
- const manifest = readPluginManifest(dir)
952
1720
  if (manifest) {
953
- let dict = null
954
- if (manifest.mcpServers && typeof manifest.mcpServers === 'object') {
955
- dict = manifest.mcpServers
956
- } else if (manifest.servers && typeof manifest.servers === 'object') {
957
- dict = manifest.servers
958
- } else if (manifest.mcp && typeof manifest.mcp === 'object') {
959
- dict = manifest.mcp.mcpServers || manifest.mcp
1721
+ loadMcpEntry(manifest.mcpServers, dir, seen, connectors, seenFiles)
1722
+ loadMcpEntry(manifest.servers, dir, seen, connectors, seenFiles)
1723
+ if (manifest.mcp && typeof manifest.mcp === 'object') {
1724
+ loadMcpEntry(manifest.mcp.mcpServers || manifest.mcp, dir, seen, connectors, seenFiles)
960
1725
  }
961
- if (dict && typeof dict === 'object') {
962
- for (const [name, cfg] of Object.entries(dict)) {
963
- if (!seen.has(name)) {
1726
+ if (Array.isArray(manifest.connectors)) {
1727
+ for (const c of manifest.connectors) {
1728
+ const name = typeof c === 'string' ? c : c?.name
1729
+ if (name && !seen.has(name)) {
964
1730
  seen.add(name)
1731
+ const cfg = typeof c === 'object' ? c : {}
965
1732
  connectors.push({
966
1733
  name,
967
1734
  type: connectorTransport(cfg.type, cfg.url, cfg.command),
968
1735
  url: cfg.url || null,
969
1736
  command: cfg.command || null,
970
- args: cfg.args || [],
1737
+ args: Array.isArray(cfg.args) ? cfg.args : [],
1738
+ ...(cfg.cwd !== undefined ? { cwd: cfg.cwd } : {}),
971
1739
  env: cfg.env || {},
972
1740
  headers: cfg.headers || {},
973
1741
  })
974
1742
  }
975
1743
  }
976
1744
  }
977
- if (Array.isArray(manifest.connectors)) {
978
- for (const c of manifest.connectors) {
979
- const name = typeof c === 'string' ? c : c.name
980
- if (name && !seen.has(name)) {
981
- seen.add(name)
982
- connectors.push({
983
- name,
984
- type: connectorTransport(c.type, c.url, c.command),
985
- url: c.url || null,
986
- command: c.command || null,
987
- args: c.args || [],
988
- env: c.env || {},
989
- headers: c.headers || {},
990
- })
991
- }
992
- }
993
- }
994
1745
  }
995
1746
  return connectors
996
1747
  }
997
1748
 
1749
+ function collectLspDicts(spec, dir, seenFiles, outDicts) {
1750
+ if (!spec) return
1751
+ if (typeof spec === 'string') {
1752
+ if (!dir) return
1753
+ const resolved = resolvePluginSpecPath(dir, spec)
1754
+ if (!resolved || !existsSync(resolved)) return
1755
+ const key = resolve(resolved)
1756
+ if (seenFiles.has(key)) return
1757
+ seenFiles.add(key)
1758
+ try {
1759
+ const parsed = JSON.parse(readFileSync(resolved, 'utf8'))
1760
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
1761
+ outDicts.push(parsed.lspServers && typeof parsed.lspServers === 'object' ? parsed.lspServers : parsed)
1762
+ }
1763
+ } catch {}
1764
+ return
1765
+ }
1766
+ if (Array.isArray(spec)) {
1767
+ for (const item of spec) collectLspDicts(item, dir, seenFiles, outDicts)
1768
+ return
1769
+ }
1770
+ if (typeof spec === 'object') {
1771
+ outDicts.push(spec.lspServers && typeof spec.lspServers === 'object' ? spec.lspServers : spec)
1772
+ }
1773
+ }
1774
+
998
1775
  /**
999
- * List LSP server definitions from a plugin's manifest (`lspServers` record).
1000
- *
1001
- * Accepts either a directory path (reads the on-disk manifest via
1002
- * `readPluginManifest`) or a pre-resolved marketplace row object (uses
1003
- * `row.lspServers` directly). The fallback path lets the plugin detail
1004
- * surface LSP servers in browse mode, where the plugin directory itself
1005
- * is only a README placeholder and the lspServers live in marketplace.json.
1776
+ * List LSP server definitions from `.lsp.json` / `lsp.json` and manifest
1777
+ * `lspServers` (object, file path, or array of paths/objects). Maps Claude's
1778
+ * `settings` field to `configuration` for DSH compatibility.
1006
1779
  */
1007
- export function listLspServers(input) {
1008
- let raw
1780
+ export function listLspServers(input, manifestOverride) {
1781
+ const dicts = []
1782
+ const seenFiles = new Set()
1783
+
1009
1784
  if (typeof input === 'string') {
1010
- raw = readPluginManifest(input)?.lspServers
1785
+ for (const fname of ['.lsp.json', 'lsp.json']) {
1786
+ const p = join(input, fname)
1787
+ if (existsSync(p)) collectLspDicts(`./${fname}`, input, seenFiles, dicts)
1788
+ }
1789
+ const manifest = manifestOverride ?? readPluginManifest(input)
1790
+ collectLspDicts(manifest?.lspServers, input, seenFiles, dicts)
1011
1791
  } else if (input && typeof input === 'object' && !Array.isArray(input)) {
1012
- raw = input.lspServers
1792
+ collectLspDicts(input.lspServers, null, seenFiles, dicts)
1013
1793
  }
1014
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return []
1794
+
1015
1795
  const out = []
1016
- for (const [name, cfg] of Object.entries(raw)) {
1017
- if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue
1018
- out.push({
1019
- name,
1020
- command: cfg.command || null,
1021
- args: Array.isArray(cfg.args) ? cfg.args : [],
1022
- env: (cfg.env && typeof cfg.env === 'object') ? cfg.env : {},
1023
- extensionToLanguage: (cfg.extensionToLanguage && typeof cfg.extensionToLanguage === 'object') ? cfg.extensionToLanguage : {},
1024
- initializationOptions: cfg.initializationOptions ?? null,
1025
- configuration: cfg.configuration ?? null,
1026
- startupTimeout: cfg.startupTimeout ?? null,
1027
- })
1796
+ const seen = new Set()
1797
+ for (const raw of dicts) {
1798
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) continue
1799
+ for (const [name, cfg] of Object.entries(raw)) {
1800
+ if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue
1801
+ if (seen.has(name)) continue
1802
+ seen.add(name)
1803
+ out.push({
1804
+ name,
1805
+ command: cfg.command || null,
1806
+ args: Array.isArray(cfg.args) ? cfg.args : [],
1807
+ env: (cfg.env && typeof cfg.env === 'object') ? cfg.env : {},
1808
+ extensionToLanguage: (cfg.extensionToLanguage && typeof cfg.extensionToLanguage === 'object') ? cfg.extensionToLanguage : {},
1809
+ initializationOptions: cfg.initializationOptions ?? null,
1810
+ configuration: cfg.configuration ?? cfg.settings ?? null,
1811
+ startupTimeout: cfg.startupTimeout ?? null,
1812
+ })
1813
+ }
1028
1814
  }
1029
1815
  return out
1030
1816
  }
1031
1817
 
1818
+ /** Merge manifest metadata with marketplace row overrides (especially `strict: false`). */
1819
+ export function mergeManifestWithRow(manifest, rowFallback) {
1820
+ if (!rowFallback || typeof rowFallback !== 'object') return manifest
1821
+ const base = manifest && typeof manifest === 'object' ? { ...manifest } : {}
1822
+ for (const key of MARKETPLACE_COMPONENT_KEYS) {
1823
+ if (rowFallback[key] !== undefined && (rowFallback.strict === false || !manifest || manifest[key] === undefined)) {
1824
+ base[key] = rowFallback[key]
1825
+ }
1826
+ }
1827
+ return Object.keys(base).length > 0 ? base : null
1828
+ }
1829
+
1032
1830
  /** Full detail view for one plugin (installed copy or cache). */
1033
1831
  export function pluginDetail(sourceId, pluginName, source, rowFallback) {
1034
1832
  const dir = pluginContentDir(sourceId, pluginName, source)
1035
1833
  if (!dir) return null
1036
1834
  const manifest = readPluginManifest(dir)
1037
- // LSP servers: prefer the on-disk manifest (post-install writes `lspServers`
1038
- // into `installed/<name>/.claude-plugin/plugin.json`); if absent — e.g. when
1039
- // browsing an uninstalled plugin whose directory is only a README placeholder
1040
- // — fall back to the `lspServers` field carried by the marketplace row.
1041
- let lspServers = listLspServers(dir)
1835
+ const effectiveManifest = mergeManifestWithRow(manifest, rowFallback)
1836
+ let lspServers = listLspServers(dir, effectiveManifest)
1042
1837
  if (lspServers.length === 0 && rowFallback) {
1043
1838
  lspServers = listLspServers(rowFallback)
1044
1839
  }
1045
1840
  return {
1046
1841
  name: pluginName,
1047
- displayName: manifest?.displayName || rowFallback?.displayName || formatDisplayName(pluginName),
1048
- description: manifest?.description || rowFallback?.description || '',
1049
- author: manifest?.author?.name || (typeof manifest?.author === 'string' ? manifest.author : rowFallback?.author),
1050
- version: manifest?.version || rowFallback?.version,
1051
- icons: buildPluginIcons(manifest, { sourceId, name: pluginName, dir, source }),
1052
- skills: listSkills(dir),
1053
- agents: listAgents(dir).map((a) => ({
1842
+ displayName: effectiveManifest?.displayName || rowFallback?.displayName || formatDisplayName(pluginName),
1843
+ description: effectiveManifest?.description || rowFallback?.description || '',
1844
+ author: effectiveManifest?.author?.name || (typeof effectiveManifest?.author === 'string' ? effectiveManifest.author : rowFallback?.author),
1845
+ version: effectiveManifest?.version || rowFallback?.version,
1846
+ icons: buildPluginIcons(effectiveManifest, { sourceId, name: pluginName, dir, source }),
1847
+ skills: listSkills(dir, effectiveManifest),
1848
+ agents: listAgents(dir, effectiveManifest).map((a) => ({
1054
1849
  file: a.file,
1055
1850
  name: a.name,
1056
1851
  displayName: a.displayName || a.name,
@@ -1058,9 +1853,12 @@ export function pluginDetail(sourceId, pluginName, source, rowFallback) {
1058
1853
  tools: a.tools || null,
1059
1854
  model: a.model || null,
1060
1855
  })),
1061
- prompts: listPrompts(dir),
1062
- connectors: listConnectors(dir),
1063
- hooks: listHooks(dir),
1856
+ prompts: listPrompts(dir, effectiveManifest),
1857
+ connectors: listConnectors(dir, effectiveManifest).map((c) => ({
1858
+ ...c,
1859
+ ...resolveConnectorDisplay(c, dir),
1860
+ })),
1861
+ hooks: listHooks(dir, effectiveManifest),
1064
1862
  lspServers,
1065
1863
  }
1066
1864
  }