import { readFile, readdir, stat } from 'node:fs/promises'; import { join, resolve } from 'node:path'; import { getWorkingDir } from '../bootstrap/workingDir.js'; import { getResourceSearchPaths } from '../utils/resourcePaths.js'; import { readPluginManifest } from './pluginManifest.js'; export interface PluginCommand { name: string; description: string; argumentHint?: string; pluginName: string; pluginRoot: string; promptBody: string; } export interface PluginManifest { name: string; version?: string; description?: string; root: string; commands: PluginCommand[]; hasStopHook: boolean; /** manifest 里 `appManuals` 声明的应用说明书目录(绝对路径,已安全收敛)。 */ appManualDirs: string[]; } const pluginCaches = new Map>(); function cacheFor(workingDir = getWorkingDir()): Map { return pluginCaches.get(resolve(workingDir)) ?? new Map(); } function stripQuotes(s: string): string { const trimmed = s.trim(); if ( (trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'")) ) { return trimmed.slice(1, -1); } return trimmed; } /** * 跨平台取路径最后一段。Windows 上 join() 产出反斜杠路径,单纯 split('/') * 不切分会让整条绝对路径变成"目录名"。同时吃 \\ 与 /,与 * hookEngine.pluginNameFromRoot 的归一逻辑保持一致。 */ export function baseName(p: string): string { const parts = p.replace(/[\\/]+$/, '').split(/[\\/]/); return parts[parts.length - 1] || p; } function parseCommandMarkdown(raw: string): { fields: Record; body: string } { const content = raw.replace(/^\uFEFF/, '').replace(/\r\n/g, '\n'); const match = /^---\n([\s\S]*?)^---[ \t]*(?:\n|$)/m.exec(content); if (!match || match.index !== 0) return { fields: {}, body: content.trim() }; const frontmatter: Record = {}; for (const line of match[1].split('\n')) { const colon = line.indexOf(':'); if (colon < 0) continue; const key = line.slice(0, colon).trim(); const value = line.slice(colon + 1).trim(); if (key) frontmatter[key] = stripQuotes(value); } return { fields: frontmatter, body: content.slice(match[0].length).trim() }; } async function loadPlugin(pluginDirPath: string): Promise { const dirName = baseName(pluginDirPath); // manifest 只在 `pluginManifest.ts` 解析一处:字段一旦有两份读法就会漂移, // 而说明书发现(vision/appGuide.ts)读的正是同一个文件。 const manifest = readPluginManifest(pluginDirPath); const manifestName = manifest?.name ?? dirName; const manifestVersion = manifest?.version; const manifestDesc = manifest?.description; for (const issue of manifest?.issues ?? []) { console.warn(`[minimal-agent] 插件 "${manifestName}" 的 plugin.json:${issue}`); } const commandsDir = join(pluginDirPath, 'commands'); const commands: PluginCommand[] = []; try { const entries = await readdir(commandsDir, { withFileTypes: true }); // 排序理由同 skillList.ts:命令顺序会进系统提示词(formatPluginHint), // readdir 的 fs 顺序不稳定会让提示词前缀漂移、打散 provider 的自动前缀缓存。 entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); for (const entry of entries) { if (!entry.name.endsWith('.md')) continue; const cmdPath = join(commandsDir, entry.name); try { const content = await readFile(cmdPath, 'utf8'); const { fields: fm, body } = parseCommandMarkdown(content); commands.push({ name: entry.name.replace(/\.md$/, ''), description: fm.description ?? '(no description)', argumentHint: fm['argument-hint'], pluginName: manifestName, pluginRoot: pluginDirPath, promptBody: body, }); } catch { } } } catch { } const hooksJsonPath = join(pluginDirPath, 'hooks', 'hooks.json'); let hasStopHook = false; try { const hooksRaw = await readFile(hooksJsonPath, 'utf8'); const hooksParsed = JSON.parse(hooksRaw); const stopHooks = hooksParsed?.hooks?.Stop; if (Array.isArray(stopHooks) && stopHooks.length > 0) { hasStopHook = true; } } catch { } // 「只提供应用说明书、没有命令也没有 hook」也是合法插件 —— 知识本身就是 // 一种贡献。此前这里会把它判成「不是插件」直接丢掉。 const appManualDirs = manifest?.appManualDirs ?? []; if (commands.length === 0 && !hasStopHook && appManualDirs.length === 0) { // A deliberately declared rich plugin may contribute just a lifecycle // hook. Discovery checks metadata only; it must not import code for prompts. if (!manifest || manifest.issues.length) return null; const entries = await Promise.all(['plugin.js', 'plugin.ts'].map(file => stat(join(pluginDirPath, file)).then(info => info.isFile(), () => false), )); if (!entries.some(Boolean)) return null; } return { name: manifestName, version: manifestVersion, description: manifestDesc, root: pluginDirPath, commands, hasStopHook, appManualDirs, }; } export async function discoverPlugins(workingDir = getWorkingDir()): Promise { const cacheKey = resolve(workingDir); const cached = pluginCaches.get(cacheKey); if (cached) { return Array.from(cached.values()); } const pluginCache = new Map(); // 双源扫描:cwd 优先 + packageRoot fallback;按数组顺序处理,已有 manifestName 跳过 const searchPaths = getResourceSearchPaths('plugins', import.meta.url, cacheKey); // 命令名 → 首个声明它的插件名。resolveCommand 按插入顺序返回第一个命中, // 所以两个不同插件声明同名命令时,先注册者生效、后者被影 —— 不再静默,warn 一次。 const commandOwners = new Map(); for (const root of searchPaths) { try { const entries = await readdir(root, { withFileTypes: true }); // 排序有两个作用: // 1. 提示词缓存:插件清单进系统提示词,顺序必须逐字节可复现(同 skillList.ts)。 // 2. 顺带修掉一个既有的不确定性 —— 下面「先注册者赢」的命令名冲突裁决此前 // 取决于 readdir 的 fs 返回顺序,同一份插件目录在不同机器/不同增删历史下 // 可能裁出不同赢家。排序后裁决稳定为字典序,行为可预测、可写进测试。 entries.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)); for (const entry of entries) { if (!entry.isDirectory()) continue; if (entry.name.startsWith('.')) continue; const plugin = await loadPlugin(join(root, entry.name)); if (!plugin) continue; if (pluginCache.has(plugin.name)) continue; // cwd 已注册的 manifestName,packageRoot 同名跳过 pluginCache.set(plugin.name, plugin); for (const cmd of plugin.commands) { const owner = commandOwners.get(cmd.name); if (owner && owner !== plugin.name) { console.warn( `[minimal-agent] 命令名冲突:/${cmd.name} 同时由插件 "${owner}" 与 "${plugin.name}" 声明;` + `先注册的 "${owner}" 生效,"${plugin.name}" 的同名命令被忽略。`, ); } else if (!owner) { commandOwners.set(cmd.name, plugin.name); } } } } catch { } } pluginCaches.set(cacheKey, pluginCache); return Array.from(pluginCache.values()); } /** 仅供测试:重置 discovery cache。 */ export function _resetPluginCache(): void { pluginCaches.clear(); } export function parseSlashCommand(input: string): { name: string; args: string } | null { const match = /^\/([^\s]+)(?:\s([\s\S]*))?$/.exec(input.trimStart()); return match ? { name: match[1]!, args: match[2] ?? '' } : null; } export function resolveCommand(input: string, workingDir?: string): { cmd: PluginCommand; arguments: string } | null { const parsed = parseSlashCommand(input); if (!parsed) return null; for (const plugin of cacheFor(workingDir).values()) { for (const cmd of plugin.commands) { if (cmd.name === parsed.name) { return { cmd, arguments: parsed.args }; } } } return null; } export function buildCommandInput( resolved: { cmd: PluginCommand; arguments: string }, ): string { const { cmd, arguments: args } = resolved; // Substitute template tokens exactly once; replacement values are literal text. let hadArgsPlaceholder = false; let input = cmd.promptBody.replace(/\$\{CLAUDE_PLUGIN_ROOT\}|\$\{ARGUMENTS\}|\$ARGUMENTS/g, (token) => { if (token === '${CLAUDE_PLUGIN_ROOT}') return cmd.pluginRoot; hadArgsPlaceholder = true; return args; }); if (!hadArgsPlaceholder && args.trim()) { input += `\n\n用户参数: ${args.trim()}`; } return input; } // 消费方是测试与宿主侧枚举(V1 红线守护测试 pluginRunner.isolation.test.ts 用它 // 断言「非 / 输入零 discovery 副作用」;commandRouter.test.ts 断言命令清单)—— // src 内无调用不代表死代码,勿删。 export function listAvailableCommands(workingDir?: string): { command: string; plugin: string; description: string }[] { const result: { command: string; plugin: string; description: string }[] = []; for (const plugin of cacheFor(workingDir).values()) { for (const cmd of plugin.commands) { result.push({ command: `/${cmd.name}`, plugin: plugin.name, description: cmd.description, }); } } return result; }