/** * ============================================================ * src/plugins/pluginLoader.ts —— plugin entry dynamic import 缓存层 * ------------------------------------------------------------ * 按 pluginRoot 路径 lazy import 插件目录下的 plugin.js(优先) * 或 plugin.ts(回退)。 * * 双候选探测的原因: * - install 模式(npm 包内):tsc 编译后只剩 plugin.js,Node + Bun * 都能加载 * - dev 模式(仓库源码):物理只有 plugin.ts,Bun 直接吃 * - 用户 cwd 自带插件:可能写 .ts(须 Bun 跑)或 .js(Node + Bun 都行) * * 契约: * - 两个文件都不存在 → 使用已注册绿色版执行器,否则是纯声明式插件 * - 两个文件都存在 + plugin.ts mtime > plugin.js mtime → console.warn * 提示 stale(dev 模式跑过 build 后又改 .ts 源码的常见坑),加载行为 * 不变仍优先 plugin.js * - 富入口加载失败与纯声明式区分;已匹配命令不会悄悄改走模型 * - 缓存 key = pluginRoot 绝对路径 * * 框架 hot-reload 由测试调用 _resetPluginLoader() 实现。 * ============================================================ */ import { existsSync, statSync } from 'node:fs'; import { basename, join, relative, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import { compiledResourceRoots } from '../utils/resourcePaths.js'; import type { PluginApi } from './pluginApi.js'; type PluginEntry = | { kind: 'ready'; api: PluginApi } | { kind: 'declarative' } | { kind: 'broken'; error: string }; const loaderCache = new Map>(); /** * 内置插件静态注册表(仅绿色版 compile 入口 entry.compiled.tsx 会填充)。 * * 背景:`bun --compile` 后,rich 插件的 plugin.ts 顺链 import 的框架 SDK * (`../../../src/plugin-sdk.js`)已被焊进 exe、磁盘上不存在 → 动态 import * 外部 plugin.ts 必抛错。绿色版改为在 compile 入口**静态 import** 内置插件 * (`src/plugins/builtinRegistry.ts`),让 bun 把执行器整树打进 exe,再经 * setBuiltinPluginApi 注册到这里;仅没有磁盘入口的声明式布局从此表取内置执行器。 * * dev / npm 模式:entry.compiled 永不被 import → 此表恒为空 → 回退分支不触发 * → loadPluginApi 行为与改动前逐字节一致。 * * key = 插件目录名(`plugins//` 的 ``,等于 `basename(pluginRoot)`)。 */ const builtinApis = new Map(); /** 由绿色版 compile 入口调用,注册内置插件执行器。dev/npm 不会调用。 */ export function setBuiltinPluginApi(key: string, api: PluginApi): void { builtinApis.set(key, api); } function isPluginApi(value: unknown): value is PluginApi { if (!value || typeof value !== 'object' || Array.isArray(value)) return false; const api = value as Record; return ['runCommand', 'activate', 'resolveSlashFallback'].every( key => api[key] === undefined || typeof api[key] === 'function', ); } /** * 区分纯声明、执行器就绪、执行器损坏。相同绝对路径并发调用共用一次加载。 */ export function loadPluginEntry(pluginRoot: string): Promise { const root = resolve(pluginRoot); const cached = loaderCache.get(root); if (cached) return cached; const loading = readPluginEntry(root); loaderCache.set(root, loading); return loading; } /** Optional probes (activation, alias discovery) tolerate unrelated broken entries. */ export async function loadPluginApi(pluginRoot: string): Promise { const entry = await loadPluginEntry(pluginRoot); return entry.kind === 'ready' ? entry.api : null; } async function readPluginEntry(pluginRoot: string): Promise { // prefer plugin.js(install / Node 兼容),fallback plugin.ts(dev / 用户 Bun 插件) const jsPath = join(pluginRoot, 'plugin.js'); const tsPath = join(pluginRoot, 'plugin.ts'); const jsExists = existsSync(jsPath); const tsExists = existsSync(tsPath); // dev 模式 stale 检测:两文件都存在 + .ts 比 .js 新 → 用户改了源码但没清编译产物 if (jsExists && tsExists && !pluginRoot.split(/[\\/]/).includes('node_modules')) { try { const jsMtime = statSync(jsPath).mtimeMs; const tsMtime = statSync(tsPath).mtimeMs; if (tsMtime > jsMtime) { console.warn( `[minimal-agent] 检测到 stale plugin.js(${pluginRoot}):plugin.ts 比 plugin.js 新,` + `加载器仍优先吃 plugin.js。如果你刚改过源码却没生效,请跑 \`bun run clean\` 删掉原地编译产物。`, ); } } catch { // stat 失败静默,不影响加载 } } // Current green/desktop packages ship metadata on disk, executors in the binary. const id = basename(pluginRoot); const builtin = builtinApis.has(id) && compiledResourceRoots().some(root => relative(join(root, 'plugins', id), pluginRoot) === '', ) ? builtinApis.get(id) : undefined; const pluginEntry = jsExists ? jsPath : tsExists ? tsPath : undefined; if (!pluginEntry) { // 磁盘无 plugin.js/.ts:绿色目录只铺声明式部分(plugin.json + commands/), // 执行器在 exe 内注册表 → 这里命中。dev/npm 注册表空 → 维持原 null。 return builtin ? { kind: 'ready', api: builtin } : { kind: 'declarative' }; } try { const mod = await import(pathToFileURL(pluginEntry).href); const candidate = (mod as { default?: unknown }).default; if (!isPluginApi(candidate)) { throw new Error('default export is not a valid PluginApi'); } return { kind: 'ready', api: candidate }; } catch (err) { // An explicitly supplied executor failed. Do not switch implementations // just because a packaged plugin happens to have the same directory name. const error = `failed to load plugin entry at ${pluginEntry}: ${err instanceof Error ? err.message : String(err)}`; console.warn(`[minimal-agent] ${error}`); return { kind: 'broken', error }; } } /** 测试用:重置加载器缓存 + 绿色版内置注册表。 */ export function _resetPluginLoader(): void { loaderCache.clear(); builtinApis.clear(); }