universal-plugin-hub 1.1.0 → 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,27 +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()
126
325
  const MARKETPLACE_SELECTION_CACHE = new Map()
326
+ const PLUGIN_DIR_INDEX_CACHE = new Map()
327
+ const PLUGIN_DIR_INDEX_LIMIT = 64
127
328
  const MARKETPLACE_CACHE_TTL = 30000 // 30 seconds
128
329
 
129
330
  export function invalidateMarketplaceCache(sourceId) {
130
331
  if (sourceId) {
131
332
  MARKETPLACE_CACHE.delete(sourceId)
132
333
  MARKETPLACE_SELECTION_CACHE.delete(sourceId)
334
+ PLUGIN_DIR_INDEX_CACHE.delete(sourceId)
133
335
  } else {
134
336
  MARKETPLACE_CACHE.clear()
135
337
  MARKETPLACE_SELECTION_CACHE.clear()
338
+ PLUGIN_DIR_INDEX_CACHE.clear()
136
339
  }
137
340
  }
138
341
 
@@ -164,15 +367,52 @@ export function readMarketplace(sourceId, names) {
164
367
  return rows
165
368
  }
166
369
 
167
- 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 } = {}) {
168
407
  const rootSkill = existsSync(join(entryDir, 'SKILL.md')) || existsSync(join(entryDir, 'skill.md'))
169
408
  const hasSkill = rootSkill || existsSync(join(entryDir, 'skills')) || existsSync(join(entryDir, 'commands'))
170
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'))
171
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'))
172
412
  const hasAgents = existsSync(join(entryDir, 'agents'))
173
- if (!hasSkill && !hasManifest && !hasMcp && !hasAgents) return null
413
+ if (!hasSkill && !hasManifest && !hasMcp && !hasLsp && !hasAgents) return null
174
414
 
175
- let displayName = formatDisplayName(fallbackName)
415
+ let displayName = includeMetadata ? formatDisplayName(fallbackName) : ''
176
416
  let description = ''
177
417
  let version = '1.0.0'
178
418
  let author = undefined
@@ -181,87 +421,308 @@ export function parsePluginRowFromDir(entryDir, fallbackName, sourceId) {
181
421
  const manifest = readPluginManifest(entryDir, false)
182
422
  if (manifest) {
183
423
  if (manifest.name) name = manifest.name
184
- displayName = manifest.displayName || formatDisplayName(name)
185
- if (manifest.description) description = manifest.description
186
- if (manifest.version) version = manifest.version
187
- 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
+ }
188
430
  } else if (rootSkill) {
189
431
  try {
190
432
  const raw = readFileSync(join(entryDir, existsSync(join(entryDir, 'SKILL.md')) ? 'SKILL.md' : 'skill.md'), 'utf8')
191
433
  const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/)
192
434
  const meta = match ? parseYaml(match[1]) : null
193
435
  if (typeof meta?.name === 'string') name = meta.name
194
- displayName = formatDisplayName(name)
195
- description = extractMdDescription(raw)
436
+ if (includeMetadata) {
437
+ displayName = formatDisplayName(name)
438
+ description = extractMdDescription(raw)
439
+ }
196
440
  } catch {}
197
- } else if (existsSync(join(entryDir, 'README.md'))) {
441
+ } else if (includeMetadata && existsSync(join(entryDir, 'README.md'))) {
198
442
  try { description = extractMdDescription(readFileSync(join(entryDir, 'README.md'), 'utf8')) } catch {}
199
443
  }
200
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
+
201
481
  return normalizeRow({
202
- ...manifest,
203
- name,
204
- displayName,
205
- description,
206
- version,
207
- author,
482
+ ...info.manifest,
483
+ name: info.name,
484
+ displayName: info.displayName,
485
+ description: info.description,
486
+ version: info.version,
487
+ author: info.author,
208
488
  source: `./${fallbackName}`,
209
- }, sourceId, entryDir)
489
+ }, sourceId, entryDir, options)
490
+ }
491
+
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
210
539
  }
211
540
 
212
- export function parseMarketplaceFromDisk(sourceId, cache, names) {
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
+
213
604
  // 1. Check Multi-Plugin Manifest Candidates
214
- const manifestCandidates = [
215
- join(cache, '.claude-plugin', 'marketplace.json'),
216
- join(cache, '.agents', 'plugins', 'marketplace.json'),
217
- join(cache, 'marketplace.json'),
218
- join(cache, 'claude-plugins.json'),
219
- join(cache, 'registry.json'),
220
- join(cache, 'plugins.json'),
221
- join(cache, 'catalog.json'),
222
- join(cache, 'market.json'),
223
- join(cache, 'mcp-servers.json'),
224
- join(cache, 'servers.json'),
225
- join(cache, 'index.json'),
226
- join(cache, '.well-known', 'agent-card.json'),
227
- ]
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
+ }
228
640
 
229
- for (const manifestPath of manifestCandidates) {
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
+ }
672
+
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)
230
677
  if (existsSync(manifestPath)) {
231
678
  try {
232
679
  const content = JSON.parse(readFileSync(manifestPath, 'utf8'))
233
680
  // Case A: Claude / standard manifest with plugins array
234
681
  if (Array.isArray(content.plugins)) {
235
682
  let skipped = false
683
+ const pluginRootMeta = content.metadata?.pluginRoot
684
+ const marketVersion = normalizeVersion(content.metadata?.version) || normalizeVersion(content.version)
236
685
  const rows = content.plugins.map((r) => {
237
- const source = r.source?.source === 'local' ? r.source.path : r.source
238
- let dir = typeof source === 'string' && source.startsWith('./') ? pluginPath(cache, source) : null
239
- if (source && typeof source === 'object' && r.name) {
240
- dir = sourceRepositoryDir(cache, source) || pluginContentDir(sourceId, r.name, source, false)
241
- }
686
+ const { source, dir } = resolveCaseAEntryDir(sourceId, cache, r, pluginRootMeta)
687
+ if (source === null) return null
242
688
  if (names && typeof r.name === 'string' && !names.has(r.name.toLowerCase())) {
243
689
  skipped = true
244
690
  return null
245
691
  }
246
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
247
699
  return normalizeRow({ ...manifest, ...r,
700
+ version: resolvedVersion,
248
701
  displayName: r.displayName || r.interface?.displayName || manifest?.displayName,
249
702
  description: r.description || r.interface?.shortDescription || manifest?.description,
250
- }, sourceId, dir)
703
+ }, sourceId, dir, { ...options, pluginRootMeta })
251
704
  }).filter(Boolean)
252
705
  if (rows.length > 0) return rows
253
706
  // Preserve manifest precedence and discovery fallbacks on a miss.
254
- if (skipped) return parseMarketplaceFromDisk(sourceId, cache)
707
+ if (skipped) return parseMarketplaceFromDisk(sourceId, cache, undefined, options)
255
708
  }
256
709
  // Case B: Direct array of plugin descriptors
257
710
  if (Array.isArray(content)) {
258
- 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)
259
722
  if (rows.length > 0) return rows
260
723
  }
261
724
  // Case C: MCP Servers dictionary (mcpServers or servers object)
262
- const mcpDict = (content.mcpServers && typeof content.mcpServers === 'object')
263
- ? content.mcpServers
264
- : ((content.servers && typeof content.servers === 'object') ? content.servers : null)
725
+ const mcpDict = resolveMcpDict(content)
265
726
  if (mcpDict) {
266
727
  const rows = []
267
728
  for (const [srvName, srvCfg] of Object.entries(mcpDict)) {
@@ -272,7 +733,7 @@ export function parseMarketplaceFromDisk(sourceId, cache, names) {
272
733
  author: srvCfg.author || content.author || 'MCP',
273
734
  category: 'mcp',
274
735
  source: './',
275
- }, sourceId))
736
+ }, sourceId, undefined, options))
276
737
  }
277
738
  if (rows.filter(Boolean).length > 0) return rows.filter(Boolean)
278
739
  }
@@ -289,7 +750,7 @@ export function parseMarketplaceFromDisk(sourceId, cache, names) {
289
750
  try {
290
751
  for (const entry of readdirSync(cache, { withFileTypes: true })) {
291
752
  if (entry.isDirectory() && !entry.name.startsWith('.')) {
292
- const row = parsePluginRowFromDir(join(cache, entry.name), entry.name, 'local')
753
+ const row = parsePluginRowFromDir(join(cache, entry.name), entry.name, 'local', options)
293
754
  if (row) localRows.push(row)
294
755
  }
295
756
  }
@@ -299,25 +760,20 @@ export function parseMarketplaceFromDisk(sourceId, cache, names) {
299
760
  }
300
761
 
301
762
  // Explicit plugin manifests describe the whole package, including its skills.
302
- if (existsSync(join(cache, '.codex-plugin', 'plugin.json')) || existsSync(join(cache, '.claude-plugin', 'plugin.json'))) {
303
- const row = parsePluginRowFromDir(cache, sourceId, sourceId)
304
- if (row) return [{ ...row, source: './' }]
305
- }
306
- if (existsSync(join(cache, 'SKILL.md')) || existsSync(join(cache, 'skill.md'))) {
307
- const row = parsePluginRowFromDir(cache, sourceId, sourceId)
763
+ if (hasExplicitRootPlugin(cache)) {
764
+ const row = parsePluginRowFromDir(cache, sourceId, sourceId, options)
308
765
  if (row) return [{ ...row, source: './' }]
309
766
  }
310
767
 
311
768
  // 3. Monorepo subdirectories auto-discovery (plugins/*, skills/*, packages/*, tools/*, extensions/*)
312
- const monoDirs = ['plugins', 'skills', 'packages', 'tools', 'extensions']
313
769
  const monoRows = []
314
- for (const sub of monoDirs) {
770
+ for (const sub of MONO_DIRS) {
315
771
  const subRoot = join(cache, sub)
316
772
  if (existsSync(subRoot)) {
317
773
  try {
318
774
  for (const entry of readdirSync(subRoot, { withFileTypes: true })) {
319
775
  if (entry.isDirectory()) {
320
- const row = parsePluginRowFromDir(join(subRoot, entry.name), entry.name, sourceId)
776
+ const row = parsePluginRowFromDir(join(subRoot, entry.name), entry.name, sourceId, options)
321
777
  if (row) {
322
778
  row.source = `./${sub}/${entry.name}`
323
779
  monoRows.push(row)
@@ -330,69 +786,17 @@ export function parseMarketplaceFromDisk(sourceId, cache, names) {
330
786
  if (monoRows.filter(Boolean).length > 0) return monoRows.filter(Boolean)
331
787
 
332
788
  // 3. Single Standalone Root Plugin Repository
333
- const rootSkillMd = join(cache, 'SKILL.md')
334
- const rootSkillsDir = join(cache, 'skills')
335
- const rootCommandsDir = join(cache, 'commands')
336
- const rootAgentsDir = join(cache, 'agents')
337
- const rootHooksDir = join(cache, 'hooks')
338
- const rootMcp = join(cache, 'mcp.json')
339
- const rootDotMcp = join(cache, '.mcp.json')
340
- const rootServerJson = join(cache, 'server.json')
341
- const rootPluginJson = join(cache, '.claude-plugin', 'plugin.json')
342
- const rootCodexPluginJson = join(cache, '.codex-plugin', 'plugin.json')
343
- const rootDirectPluginJson = join(cache, 'plugin.json')
344
- const rootCursorRules = join(cache, '.cursor', 'rules')
345
- const rootCursorRulesFile = join(cache, '.cursorrules')
346
- const rootPkgJson = join(cache, 'package.json')
347
-
348
- const isRootPlugin = existsSync(rootSkillMd)
349
- || existsSync(rootSkillsDir)
350
- || existsSync(rootCommandsDir)
351
- || existsSync(rootAgentsDir)
352
- || existsSync(rootHooksDir)
353
- || existsSync(rootMcp)
354
- || existsSync(rootDotMcp)
355
- || existsSync(rootServerJson)
356
- || existsSync(rootPluginJson)
357
- || existsSync(rootCodexPluginJson)
358
- || existsSync(rootDirectPluginJson)
359
- || existsSync(rootCursorRules)
360
- || existsSync(rootCursorRulesFile)
361
- || existsSync(rootPkgJson)
362
-
363
- if (isRootPlugin) {
364
- let name = sourceId
365
- let displayName = formatDisplayName(sourceId)
366
- let description = ''
367
- let version = '1.0.0'
368
- let author = undefined
369
-
370
- const manifest = readPluginManifest(cache)
371
- if (manifest) {
372
- if (manifest.name) name = manifest.name
373
- if (manifest.displayName) displayName = manifest.displayName
374
- if (manifest.description) description = manifest.description
375
- if (manifest.version) version = manifest.version
376
- if (manifest.author) author = typeof manifest.author === 'string' ? manifest.author : manifest.author.name
377
- } else if (existsSync(rootSkillMd)) {
378
- try {
379
- description = extractMdDescription(readFileSync(rootSkillMd, 'utf8'))
380
- } catch {}
381
- } else if (existsSync(join(cache, 'README.md'))) {
382
- try {
383
- description = extractMdDescription(readFileSync(join(cache, 'README.md'), 'utf8'))
384
- } catch {}
385
- }
386
-
789
+ const rootInfo = resolveStandaloneRootInfo(cache, sourceId, { includeMetadata: true })
790
+ if (rootInfo) {
387
791
  return [normalizeRow({
388
- ...manifest,
389
- name,
390
- displayName,
391
- description,
392
- version,
393
- author,
792
+ ...rootInfo.manifest,
793
+ name: rootInfo.name,
794
+ displayName: rootInfo.displayName,
795
+ description: rootInfo.description,
796
+ version: rootInfo.version,
797
+ author: rootInfo.author,
394
798
  source: './',
395
- }, sourceId, cache)].filter(Boolean)
799
+ }, sourceId, cache, options)].filter(Boolean)
396
800
  }
397
801
 
398
802
  return []
@@ -419,14 +823,15 @@ export function pluginContentDir(sourceId, pluginName, source, preferInstalled =
419
823
  }
420
824
 
421
825
  // Check if in remote git cache
422
- if (source && typeof source === 'object' && (source.source === 'url' || source.source === 'git-subdir')) {
423
- if (typeof source.url === 'string') {
424
- 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)
425
830
  if (ownDir) return ownDir
426
- const clean = String(source.url).replace(/^https?:\/\//, '').replace(/\.git$/, '')
831
+ const clean = String(remoteSrc.url).replace(/^https?:\/\//, '').replace(/\.git$/, '')
427
832
  const remoteKey = clean.replace(/[^a-z0-9]+/gi, '-').replace(/^-+|-+$/g, '').toLowerCase() || 'repo'
428
833
  const checkout = join(sourceCacheDir('remote'), remoteKey)
429
- const dir = source.path ? pluginPath(checkout, source.path) : checkout
834
+ const dir = remoteSrc.path ? pluginPath(checkout, remoteSrc.path) : checkout
430
835
  return existsSync(dir) ? dir : null
431
836
  }
432
837
  }
@@ -436,7 +841,7 @@ export function pluginContentDir(sourceId, pluginName, source, preferInstalled =
436
841
  return existsSync(fallback) ? fallback : null
437
842
  }
438
843
 
439
- /** Read plugin metadata with Claude precedence when multiple formats coexist. */
844
+ /** Read plugin metadata with Claude/portable precedence and Codex overlay merge. */
440
845
  export function readPluginManifest(dir, includeParent = true) {
441
846
  const rootManifest = join(dir, 'plugin.json')
442
847
  let portable = false
@@ -451,12 +856,14 @@ export function readPluginManifest(dir, includeParent = true) {
451
856
  ...(portable ? [rootManifest] : []),
452
857
  join(dir, '.codex-plugin', 'plugin.json'),
453
858
  join(dir, '.claude-plugin', 'marketplace.json'),
859
+ join(dir, '.agents', 'plugins', 'marketplace.json'),
454
860
  rootManifest,
455
861
  join(dir, 'manifest.json'),
456
862
  join(dir, 'server.json'),
457
863
  join(dir, 'package.json'),
458
864
  ...(includeParent ? [join(dir, '..', '.claude-plugin', 'plugin.json'),
459
865
  join(dir, '..', '.claude-plugin', 'marketplace.json'),
866
+ join(dir, '..', '.agents', 'plugins', 'marketplace.json'),
460
867
  join(dir, '..', 'plugin.json'),
461
868
  join(dir, '..', 'manifest.json')] : []),
462
869
  ]
@@ -466,12 +873,17 @@ export function readPluginManifest(dir, includeParent = true) {
466
873
  try {
467
874
  const raw = JSON.parse(readFileSync(p, 'utf8'))
468
875
  if (p.endsWith('package.json')) {
469
- 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
+ }
470
882
  return {
471
883
  name: raw.name,
472
884
  displayName: raw.displayName || formatDisplayName(raw.name),
473
885
  description: raw.description,
474
- version: raw.version,
886
+ version: normalizeVersion(raw.version),
475
887
  author: raw.author,
476
888
  mcpServers: raw.mcpServers,
477
889
  lspServers: raw.lspServers,
@@ -483,26 +895,48 @@ export function readPluginManifest(dir, includeParent = true) {
483
895
  name: matched.name || raw.name,
484
896
  displayName: matched.displayName || formatDisplayName(matched.name || raw.name),
485
897
  description: matched.description || raw.metadata?.description || '',
486
- 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),
487
903
  author: matched.author || raw.owner?.name || undefined,
904
+ strict: matched.strict,
905
+ prompts: matched.prompts,
488
906
  skills: matched.skills,
489
907
  commands: matched.commands,
490
908
  agents: matched.agents,
909
+ hooks: matched.hooks,
491
910
  mcpServers: matched.mcpServers,
492
911
  lspServers: matched.lspServers,
493
912
  }
494
913
  }
495
914
  const openai = raw.extensions?.['com.openai']
496
- 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))
497
932
  return {
498
- ...raw,
499
- ...settings,
500
- name: raw.name,
501
- version: raw.version,
502
- displayName: raw.displayName || settings.interface?.displayName,
503
- description: raw.description || settings.interface?.shortDescription || settings.interface?.longDescription || '',
504
- author: raw.author || settings.interface?.developerName,
505
- 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,
506
940
  }
507
941
  } catch {}
508
942
  }
@@ -510,81 +944,221 @@ export function readPluginManifest(dir, includeParent = true) {
510
944
  return null
511
945
  }
512
946
 
513
- /** List skill & command directories/files (skills/*, commands/*, root SKILL.md, .cursor/rules). */
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: '' })
959
+ }
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: '' })
982
+ }
983
+ }
984
+ scanCommandDirectory(fullPath, seenFiles, addCommandEntry, nextPrefix)
985
+ }
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)
999
+ }
1000
+
1001
+ const candidateCmdRoots = [
1002
+ join(dir, 'commands'),
1003
+ join(dir, '..', 'commands'),
1004
+ join(dir, '.claude', 'commands'),
1005
+ join(dir, '..', '.claude', 'commands'),
1006
+ ]
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)
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 })
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). */
514
1088
  export function listSkills(dir, manifest = readPluginManifest(dir)) {
515
1089
  const out = []
516
1090
  const seen = new Set()
517
1091
 
518
- const addSkill = (name, skillMdPath) => {
1092
+ const addSkill = (name, skillMdPath, inlineContent = null, fallbackDesc = '') => {
519
1093
  if (!name || seen.has(name)) return
520
1094
  let description = ''
521
1095
  if (skillMdPath) {
522
1096
  try {
523
1097
  description = extractMdDescription(readFileSync(skillMdPath, 'utf8'))
524
1098
  } catch {}
1099
+ } else if (typeof inlineContent === 'string') {
1100
+ description = extractMdDescription(inlineContent)
525
1101
  }
526
- out.push({ name, command: `/${name}`, description })
1102
+ out.push({ name, command: `/${name}`, description: description || fallbackDesc || '' })
527
1103
  seen.add(name)
528
1104
  }
529
1105
 
530
- // 1. Check skills/ subdirectory
531
- const declaredSkills = typeof manifest?.skills === 'string' ? [manifest.skills] : (Array.isArray(manifest?.skills) ? manifest.skills.filter((s) => typeof s === 'string' && s.startsWith('./')) : [])
532
- const candidateSkillRoots = [...declaredSkills.map((p) => pluginPath(dir, p)), join(dir, 'skills'), join(dir, '..', 'skills')]
533
- for (const sRoot of candidateSkillRoots) {
534
- if (existsSync(sRoot)) {
535
- try {
536
- if (statSync(sRoot).isFile()) {
537
- if (/^skill\.md$/i.test(basename(sRoot))) addSkill(basename(dirname(sRoot)), sRoot)
538
- continue
539
- }
540
- const rootMd = ['SKILL.md', 'skill.md'].map((f) => join(sRoot, f)).find(existsSync)
541
- if (rootMd) addSkill(basename(sRoot), rootMd)
542
- for (const entry of readdirSync(sRoot, { withFileTypes: true })) {
543
- if (entry.isDirectory()) {
544
- if (['node_modules', '.git', '.agents', 'agents', 'commands', 'prompts', 'hooks', '.cursor', 'docs', 'assets', 'eval', 'staging', 'walkthroughs'].includes(entry.name)) continue
545
- const skillMd = join(sRoot, entry.name, 'SKILL.md')
546
- const altMd = join(sRoot, entry.name, 'skill.md')
547
- if (existsSync(skillMd)) {
548
- addSkill(entry.name, skillMd)
549
- } else if (existsSync(altMd)) {
550
- addSkill(entry.name, altMd)
551
- }
552
- } else if (entry.isFile() && entry.name.endsWith('.md') && !['README.md', 'CONTRIBUTING.md', 'LICENSE.md', 'CHANGELOG.md'].includes(entry.name)) {
553
- const name = entry.name.replace(/\.md$/, '')
554
- addSkill(name, join(sRoot, entry.name))
555
- }
556
- }
557
- } catch {}
558
- }
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)
559
1125
  }
560
1126
 
561
- // 2. Check commands/ and .claude/commands/ (Claude Code slash commands)
562
- const candidateCmdRoots = [
563
- join(dir, 'commands'),
564
- join(dir, '..', 'commands'),
565
- join(dir, '.claude', 'commands'),
566
- join(dir, '..', '.claude', 'commands'),
567
- ]
568
- for (const cRoot of candidateCmdRoots) {
569
- if (existsSync(cRoot)) {
570
- try {
571
- for (const entry of readdirSync(cRoot, { withFileTypes: true })) {
572
- if (entry.isFile() && entry.name.endsWith('.md')) {
573
- addSkill(entry.name.replace(/\.md$/, ''), join(cRoot, entry.name))
574
- } else if (entry.isDirectory()) {
575
- const skillMd = join(cRoot, entry.name, 'SKILL.md')
576
- const directMd = join(cRoot, `${entry.name}.md`)
577
- const targetMd = existsSync(skillMd) ? skillMd : (existsSync(directMd) ? directMd : null)
578
- if (targetMd) {
579
- addSkill(entry.name, targetMd)
580
- }
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)
581
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))
582
1152
  }
583
- } catch {}
584
- }
1153
+ }
1154
+ } catch {}
585
1155
  }
586
1156
 
587
-
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
+ }
588
1162
 
589
1163
  // 4. Single-skill repository fallback: if no skills/ or commands/ exist, check root SKILL.md
590
1164
  if (out.length === 0) {
@@ -600,14 +1174,14 @@ export function listSkills(dir, manifest = readPluginManifest(dir)) {
600
1174
  }
601
1175
  }
602
1176
 
603
- // 5. Check manifest (plugin.json / package.json / marketplace.json "skills" / "commands")
1177
+ // 5. Fallback for non-path entries declared in manifest.skills / manifest.commands
604
1178
  if (manifest && out.length === 0) {
605
1179
  if (Array.isArray(manifest.skills)) {
606
1180
  for (const item of manifest.skills) {
607
1181
  const rawName = typeof item === 'string' ? item : item?.name
608
1182
  if (rawName) {
609
1183
  const name = basename(rawName).replace(/\.(md|mdc)$/i, '')
610
- if (name && !['skills', 'commands'].includes(name.toLowerCase()) && !seen.has(name)) {
1184
+ if (name && !['.', 'skills', 'commands'].includes(name.toLowerCase()) && !seen.has(name)) {
611
1185
  seen.add(name)
612
1186
  out.push({
613
1187
  name,
@@ -618,20 +1192,12 @@ export function listSkills(dir, manifest = readPluginManifest(dir)) {
618
1192
  }
619
1193
  }
620
1194
  }
621
- if (Array.isArray(manifest.commands)) {
622
- for (const item of manifest.commands) {
623
- const rawName = typeof item === 'string' ? item : item?.name
624
- if (rawName) {
625
- const name = basename(rawName).replace(/\.md$/i, '')
626
- if (name && !['skills', 'commands'].includes(name.toLowerCase()) && !seen.has(name)) {
627
- seen.add(name)
628
- out.push({
629
- name,
630
- command: `/${name}`,
631
- description: typeof item === 'object' ? item.description || '' : '',
632
- })
633
- }
634
- }
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 || '') : '' })
635
1201
  }
636
1202
  }
637
1203
  }
@@ -639,123 +1205,167 @@ export function listSkills(dir, manifest = readPluginManifest(dir)) {
639
1205
  return out
640
1206
  }
641
1207
 
642
- /** List agent definition files (agents/*.yaml|yml|md|json, .well-known/agent-card.json, agent.json). */
1208
+ /** List agent definition files (agents/<subpath>/*.yaml|yml|md|json, .well-known/agent-card.json, agent.json, manifest.agents). */
643
1209
  export function listAgents(dir, manifest = readPluginManifest(dir)) {
644
1210
  const out = []
645
- const seen = new Set()
646
-
647
- const candidateAgentRoots = [
648
- join(dir, 'agents'),
649
- join(dir, '.agents'),
650
- join(dir, '..', 'agents'),
651
- join(dir, '..', '.agents'),
652
- join(dir, '.claude-plugin', 'agents'),
653
- join(dir, '..', '.claude-plugin', 'agents'),
654
- ]
655
-
1211
+ const seenFiles = new Set()
1212
+ const seenNames = new Set()
656
1213
  const pluginName = basename(dir)
657
1214
 
658
- for (const agentsRoot of candidateAgentRoots) {
659
- if (existsSync(agentsRoot)) {
660
- try {
661
- for (const entry of readdirSync(agentsRoot, { withFileTypes: true })) {
662
- if (!entry.isFile()) continue
663
- if (!/\.(ya?ml|md|json)$/i.test(entry.name)) continue
664
- if (seen.has(entry.name)) continue
665
-
666
- try {
667
- const raw = readFileSync(join(agentsRoot, entry.name), 'utf8')
668
- if (raw) {
669
- const parsed = parseAgentDefinition(pluginName, entry.name, raw)
670
- if (parsed && !parsed.error) {
671
- seen.add(entry.name)
672
- out.push({
673
- file: entry.name,
674
- name: parsed.name,
675
- displayName: parsed.displayName || parsed.name,
676
- description: parsed.description,
677
- tools: parsed.tools,
678
- model: parsed.model,
679
- instructions: parsed.instructions,
680
- raw,
681
- })
682
- continue
683
- }
684
- }
685
- } catch { /* skip */ }
686
-
687
- // Fallback if parsing failed
688
- seen.add(entry.name)
689
- 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)
690
1228
  out.push({
691
- file: entry.name,
692
- name: fallbackName,
693
- displayName: formatDisplayName(fallbackName),
694
- description: 'Autonomous sub-agent workflow',
695
- tools: null,
696
- model: null,
697
- instructions: '',
698
- 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,
699
1237
  })
1238
+ return
700
1239
  }
701
- } 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
+ }
702
1299
  }
1300
+ fallbackAgentItems.push(item)
703
1301
  }
704
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
+
705
1310
  // Check Agent Card format (.well-known/agent-card.json or agent.json)
706
1311
  for (const agentCardPath of [join(dir, '.well-known', 'agent-card.json'), join(dir, 'agent.json')]) {
707
- if (existsSync(agentCardPath) && !seen.has(basename(agentCardPath))) {
1312
+ if (existsSync(agentCardPath) && !seenFiles.has(resolve(agentCardPath))) {
1313
+ seenFiles.add(resolve(agentCardPath))
708
1314
  try {
709
1315
  const raw = readFileSync(agentCardPath, 'utf8')
710
1316
  const parsed = parseAgentDefinition(pluginName, basename(agentCardPath), raw)
711
- seen.add(basename(agentCardPath))
712
1317
  if (parsed && !parsed.error) {
713
- out.push({
714
- file: basename(agentCardPath),
715
- name: parsed.name,
716
- displayName: parsed.displayName || parsed.name,
717
- description: parsed.description,
718
- tools: parsed.tools,
719
- model: parsed.model,
720
- instructions: parsed.instructions,
721
- raw,
722
- })
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
+ }
723
1331
  } else {
724
1332
  const jsonDoc = JSON.parse(raw)
725
- out.push({
726
- file: basename(agentCardPath),
727
- name: jsonDoc.name || basename(dir),
728
- displayName: jsonDoc.displayName || formatDisplayName(jsonDoc.name || basename(dir)),
729
- description: jsonDoc.description || '',
730
- tools: jsonDoc.tools || null,
731
- model: jsonDoc.model || null,
732
- instructions: jsonDoc.instructions || '',
733
- raw,
734
- })
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
+ }
735
1347
  }
736
1348
  } catch {}
737
1349
  }
738
1350
  }
739
1351
 
740
- // Check manifest "agents" array
741
- if (manifest && Array.isArray(manifest.agents)) {
742
- for (const item of manifest.agents) {
743
- const rawName = typeof item === 'string' ? item : item?.name
744
- if (rawName && !seen.has(rawName)) {
745
- seen.add(rawName)
746
- const name = typeof item === 'string' ? item : (item.name || rawName)
747
- const displayName = typeof item === 'object' && item.displayName ? item.displayName : (typeof item === 'object' && item.name ? item.name : formatDisplayName(name))
748
- out.push({
749
- file: typeof item === 'object' && item.file ? item.file : `${name}.md`,
750
- name,
751
- displayName,
752
- description: typeof item === 'object' ? item.description || '' : '',
753
- tools: typeof item === 'object' ? item.tools || null : null,
754
- model: typeof item === 'object' ? item.model || null : null,
755
- instructions: '',
756
- raw: null,
757
- })
758
- }
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
+ })
759
1369
  }
760
1370
  }
761
1371
 
@@ -798,24 +1408,34 @@ function formatHookEventName(evt) {
798
1408
  return map[evt] || evt
799
1409
  }
800
1410
 
801
- /**
802
- * Parse hook event names from a Claude/Codex hook config file's content.
803
- * Accepts `{ hooks: {...} }`, a doubly-nested `{ hooks: { hooks: {...} } }`,
804
- * or a bare event map. Never treats implementation scripts as hooks.
805
- */
806
- export function parseHookConfig(raw, isJson) {
807
- const out = []
1411
+ function extractHookEventMap(raw, isJson) {
808
1412
  let parsed
809
1413
  try {
810
1414
  parsed = isJson ? JSON.parse(raw) : parseYaml(raw)
811
1415
  } catch {
812
- return out
1416
+ return null
813
1417
  }
814
- 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
815
1423
  let hookObj = (parsed.hooks && typeof parsed.hooks === 'object' && !Array.isArray(parsed.hooks)) ? parsed.hooks : parsed
816
1424
  if (hookObj && typeof hookObj === 'object' && !Array.isArray(hookObj) && typeof hookObj.hooks === 'object' && !Array.isArray(hookObj.hooks)) {
817
1425
  hookObj = hookObj.hooks
818
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
819
1439
  for (const [eventName, val] of Object.entries(hookObj)) {
820
1440
  const formattedEvent = formatHookEventName(eventName)
821
1441
  if (Array.isArray(val)) {
@@ -833,31 +1453,82 @@ export function parseHookConfig(raw, isJson) {
833
1453
  return out
834
1454
  }
835
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
+
836
1524
  /**
837
1525
  * Resolve the plugin's Claude/Codex hook config file path: the manifest `hooks`
838
1526
  * path first, then `hooks/hooks.json|yaml|yml`, then `*-hooks.{json,yaml}` files.
839
1527
  * Returns null when the plugin declares no hook config (e.g. only scripts).
840
1528
  */
841
1529
  export function resolveHookConfigPath(dir, manifest = readPluginManifest(dir)) {
842
- if (manifest && typeof manifest.hooks === 'string') {
843
- const p = isAbsolute(manifest.hooks) ? manifest.hooks : join(dir, manifest.hooks)
844
- if (existsSync(p) && statSync(p).isFile()) return p
845
- }
846
- const hooksRoot = join(dir, 'hooks')
847
- if (existsSync(hooksRoot)) {
848
- const fixed = ['hooks.json', 'hooks.yaml', 'hooks.yml'].map((n) => join(hooksRoot, n)).find((p) => existsSync(p) && statSync(p).isFile())
849
- if (fixed) return fixed
850
- try {
851
- const dialect = readdirSync(hooksRoot)
852
- .filter((n) => /-hooks\.(json|ya?ml)$/i.test(n) && statSync(join(hooksRoot, n)).isFile())
853
- .sort((a, b) => {
854
- const score = (n) => (/claude/i.test(n) ? 0 : (/codex/i.test(n) ? 1 : 2))
855
- return score(a) - score(b)
856
- })
857
- if (dialect.length > 0) return join(hooksRoot, dialect[0])
858
- } catch {}
859
- }
860
- return null
1530
+ const firstFile = collectHookSources(dir, manifest).find((s) => s.type === 'file')
1531
+ return firstFile ? firstFile.path : null
861
1532
  }
862
1533
 
863
1534
  /** Hook entries: follow the plugin manifest's `hooks` config, then hooks/ config files. */
@@ -866,26 +1537,90 @@ export function listHooks(dir, manifest = readPluginManifest(dir)) {
866
1537
  const seen = new Set()
867
1538
  const add = (h) => { if (h && !seen.has(h)) { seen.add(h); hooks.push(h) } }
868
1539
 
869
- const cfg = resolveHookConfigPath(dir, manifest)
870
- if (cfg) {
871
- try {
872
- const raw = readFileSync(cfg, 'utf8')
873
- for (const h of parseHookConfig(raw, /\.json$/i.test(cfg))) add(h)
874
- } 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
+ }
875
1551
  }
876
1552
 
877
- // Manifest `hooks` as inline object/array (no file path to follow).
878
- if (hooks.length === 0) {
879
- if (manifest && manifest.hooks) {
880
- if (Array.isArray(manifest.hooks)) {
881
- for (const h of manifest.hooks) add(typeof h === 'string' ? h : (h && h.name))
882
- } else if (typeof manifest.hooks === 'object') {
883
- for (const h of parseHookConfig(JSON.stringify({ hooks: manifest.hooks }), true)) add(h)
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
+ }
1578
+ }
1579
+
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
+ }
884
1619
  }
885
1620
  }
886
1621
  }
887
1622
 
888
- return hooks
1623
+ return Object.keys(compiled).length > 0 ? { hooks: compiled } : null
889
1624
  }
890
1625
 
891
1626
  /**
@@ -910,158 +1645,207 @@ export function isRemoteTransportName(type) {
910
1645
  return type === 'http' || type === 'sse' || type === 'streamable-http' || type === 'streamableHttp'
911
1646
  }
912
1647
 
913
- /** Connector-ish entries: .mcp.json, mcp.json, server.json, or plugin.json "mcp" / "connectors". */
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". */
914
1708
  export function listConnectors(dir, manifest = readPluginManifest(dir)) {
915
1709
  const connectors = []
916
1710
  const seen = new Set()
1711
+ const seenFiles = new Set()
917
1712
 
918
1713
  for (const mcpFile of ['.mcp.json', 'mcp.json', 'server.json', 'mcp-servers.json']) {
919
1714
  const mcpPath = join(dir, mcpFile)
920
1715
  if (existsSync(mcpPath)) {
921
- try {
922
- const mcp = JSON.parse(readFileSync(mcpPath, 'utf8'))
923
- let dict = null
924
- if (mcp && typeof mcp === 'object' && !Array.isArray(mcp)) {
925
- if (mcp.mcpServers && typeof mcp.mcpServers === 'object') {
926
- dict = mcp.mcpServers
927
- } else if (mcp.servers && typeof mcp.servers === 'object') {
928
- dict = mcp.servers
929
- } else if (mcp.name && (mcp.url || mcp.command || mcp.type)) {
930
- dict = { [mcp.name]: mcp }
931
- } else {
932
- const direct = {}
933
- for (const [k, v] of Object.entries(mcp)) {
934
- if (v && typeof v === 'object' && !Array.isArray(v)) {
935
- if (v.url || v.command || v.type || v.args || v.headers || v.env) {
936
- direct[k] = v
937
- }
938
- }
939
- }
940
- if (Object.keys(direct).length > 0) dict = direct
941
- }
942
- }
943
- if (dict && typeof dict === 'object') {
944
- for (const [name, cfg] of Object.entries(dict)) {
945
- if (!seen.has(name)) {
946
- seen.add(name)
947
- connectors.push({
948
- name,
949
- type: connectorTransport(cfg.type, cfg.url, cfg.command),
950
- url: cfg.url || null,
951
- command: cfg.command || null,
952
- args: cfg.args || [],
953
- env: cfg.env || {},
954
- headers: cfg.headers || {},
955
- })
956
- }
957
- }
958
- }
959
- } catch { /* ignore malformed */ }
1716
+ loadMcpEntry(`./${mcpFile}`, dir, seen, connectors, seenFiles)
960
1717
  }
961
1718
  }
962
1719
 
963
1720
  if (manifest) {
964
- let dict = null
965
- if (manifest.mcpServers && typeof manifest.mcpServers === 'object') {
966
- dict = manifest.mcpServers
967
- } else if (manifest.servers && typeof manifest.servers === 'object') {
968
- dict = manifest.servers
969
- } else if (manifest.mcp && typeof manifest.mcp === 'object') {
970
- 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)
971
1725
  }
972
- if (dict && typeof dict === 'object') {
973
- for (const [name, cfg] of Object.entries(dict)) {
974
- 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)) {
975
1730
  seen.add(name)
1731
+ const cfg = typeof c === 'object' ? c : {}
976
1732
  connectors.push({
977
1733
  name,
978
1734
  type: connectorTransport(cfg.type, cfg.url, cfg.command),
979
1735
  url: cfg.url || null,
980
1736
  command: cfg.command || null,
981
- args: cfg.args || [],
1737
+ args: Array.isArray(cfg.args) ? cfg.args : [],
1738
+ ...(cfg.cwd !== undefined ? { cwd: cfg.cwd } : {}),
982
1739
  env: cfg.env || {},
983
1740
  headers: cfg.headers || {},
984
1741
  })
985
1742
  }
986
1743
  }
987
1744
  }
988
- if (Array.isArray(manifest.connectors)) {
989
- for (const c of manifest.connectors) {
990
- const name = typeof c === 'string' ? c : c.name
991
- if (name && !seen.has(name)) {
992
- seen.add(name)
993
- connectors.push({
994
- name,
995
- type: connectorTransport(c.type, c.url, c.command),
996
- url: c.url || null,
997
- command: c.command || null,
998
- args: c.args || [],
999
- env: c.env || {},
1000
- headers: c.headers || {},
1001
- })
1002
- }
1003
- }
1004
- }
1005
1745
  }
1006
1746
  return connectors
1007
1747
  }
1008
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
+
1009
1775
  /**
1010
- * List LSP server definitions from a plugin's manifest (`lspServers` record).
1011
- *
1012
- * Accepts either a directory path (reads the on-disk manifest via
1013
- * `readPluginManifest`) or a pre-resolved marketplace row object (uses
1014
- * `row.lspServers` directly). The fallback path lets the plugin detail
1015
- * surface LSP servers in browse mode, where the plugin directory itself
1016
- * 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.
1017
1779
  */
1018
- export function listLspServers(input) {
1019
- let raw
1780
+ export function listLspServers(input, manifestOverride) {
1781
+ const dicts = []
1782
+ const seenFiles = new Set()
1783
+
1020
1784
  if (typeof input === 'string') {
1021
- 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)
1022
1791
  } else if (input && typeof input === 'object' && !Array.isArray(input)) {
1023
- raw = input.lspServers
1792
+ collectLspDicts(input.lspServers, null, seenFiles, dicts)
1024
1793
  }
1025
- if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return []
1794
+
1026
1795
  const out = []
1027
- for (const [name, cfg] of Object.entries(raw)) {
1028
- if (!cfg || typeof cfg !== 'object' || Array.isArray(cfg)) continue
1029
- out.push({
1030
- name,
1031
- command: cfg.command || null,
1032
- args: Array.isArray(cfg.args) ? cfg.args : [],
1033
- env: (cfg.env && typeof cfg.env === 'object') ? cfg.env : {},
1034
- extensionToLanguage: (cfg.extensionToLanguage && typeof cfg.extensionToLanguage === 'object') ? cfg.extensionToLanguage : {},
1035
- initializationOptions: cfg.initializationOptions ?? null,
1036
- configuration: cfg.configuration ?? null,
1037
- startupTimeout: cfg.startupTimeout ?? null,
1038
- })
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
+ }
1039
1814
  }
1040
1815
  return out
1041
1816
  }
1042
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
+
1043
1830
  /** Full detail view for one plugin (installed copy or cache). */
1044
1831
  export function pluginDetail(sourceId, pluginName, source, rowFallback) {
1045
1832
  const dir = pluginContentDir(sourceId, pluginName, source)
1046
1833
  if (!dir) return null
1047
1834
  const manifest = readPluginManifest(dir)
1048
- // LSP servers: prefer the on-disk manifest (post-install writes `lspServers`
1049
- // into `installed/<name>/.claude-plugin/plugin.json`); if absent — e.g. when
1050
- // browsing an uninstalled plugin whose directory is only a README placeholder
1051
- // — fall back to the `lspServers` field carried by the marketplace row.
1052
- let lspServers = listLspServers(dir)
1835
+ const effectiveManifest = mergeManifestWithRow(manifest, rowFallback)
1836
+ let lspServers = listLspServers(dir, effectiveManifest)
1053
1837
  if (lspServers.length === 0 && rowFallback) {
1054
1838
  lspServers = listLspServers(rowFallback)
1055
1839
  }
1056
1840
  return {
1057
1841
  name: pluginName,
1058
- displayName: manifest?.displayName || rowFallback?.displayName || formatDisplayName(pluginName),
1059
- description: manifest?.description || rowFallback?.description || '',
1060
- author: manifest?.author?.name || (typeof manifest?.author === 'string' ? manifest.author : rowFallback?.author),
1061
- version: manifest?.version || rowFallback?.version,
1062
- icons: buildPluginIcons(manifest, { sourceId, name: pluginName, dir, source }),
1063
- skills: listSkills(dir),
1064
- 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) => ({
1065
1849
  file: a.file,
1066
1850
  name: a.name,
1067
1851
  displayName: a.displayName || a.name,
@@ -1069,9 +1853,12 @@ export function pluginDetail(sourceId, pluginName, source, rowFallback) {
1069
1853
  tools: a.tools || null,
1070
1854
  model: a.model || null,
1071
1855
  })),
1072
- prompts: listPrompts(dir),
1073
- connectors: listConnectors(dir),
1074
- 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),
1075
1862
  lspServers,
1076
1863
  }
1077
1864
  }