/** * ============================================================ * src/plugins/pluginRunner.ts —— 框架级 slash-激活分发器 * ------------------------------------------------------------ * 通用分发器,**不含任何插件特定逻辑**。 * * 执行路径: * 1) 非 / 输入 → 直接透传 runQuery(T-A-O-R 红线,零插件副作用) * 2) / 输入 → discoverPlugins → resolveCommand * a) 命中插件且其 plugin.ts 暴露 runCommand → 让 plugin.ts 接管 * b) 命中插件但只有声明式 commands/*.md → 把 prompt 拼好喂给 runQuery * c) 未命中 -> warning 提示未知命令后透传 runQuery(/ 只是激活前缀, * 不是严格命令系统;未知的 /xxx 当普通用户输入处理,不报错) * ============================================================ */ import { getWorkingDir } from '../bootstrap/workingDir.js'; import { type RunQueryOptions, runQuery } from '../loop.js'; import type { LoopEvent, Message, Provider } from '../types.js'; import { buildCommandInput, discoverPlugins, listAvailableCommands, parseSlashCommand, resolveCommand, } from './commandRouter.js'; import type { PluginEvent } from './pluginApi.js'; import { presentPluginArtifacts } from './artifactDelivery.js'; import { loadPluginApi, loadPluginEntry } from './pluginLoader.js'; import { type SlashTarget, buildFallbackInput, parseExplicitPrefix, resolveSlashFallback, } from './slashFallback.js'; export interface PluginRunnerOptions { provider: Provider; history: Message[]; runtimeContext?: RunQueryOptions['runtimeContext']; allowedTools?: RunQueryOptions['allowedTools']; /** * 本回合实际可调用的工具对象池(不只是名字)。缺省时 `loop.ts` 退回 `ALL_TOOLS`—— * 那是静态全局注册表,装不下按回合动态构造的工具(比如群协作工具,每次都要闭包捕获 * 当次投递的 owner/群 id/回复回调)。此前这里只转发 `allowedTools`(纯名字数组), * 于是系统提示词会写"你有 GetGroupContext 工具"、允许名单里也有这个名字,但 API * 实际下发给模型的 tools schema 里从来没有它——模型如实报告"没有这个能力", * 比静默瞎猜更诚实,但这条工具从一开始就没进模型能调用的范围(2026-08-21 真实 * LLM 群回合 E2E 首次跑通时抓到的问题,此前所有测试都 stub 掉了 runAgentTurn, * 没有一条测试真的走到过这一层)。 */ availableTools?: RunQueryOptions['availableTools']; signal?: AbortSignal; maxTurns?: number; sessionState?: import('../session/sessionState.js').SessionState; /** * DI:把 chat / executeTool 透传给底层 runQuery(仅测试用,生产不传走默认实现)。 * 让测试用显式注入替代 mock.module(loop.js)——后者会全局泄漏污染其它测试文件。 */ chat?: RunQueryOptions['chat']; executeTool?: RunQueryOptions['executeTool']; commitFormalDelivery?: RunQueryOptions['commitFormalDelivery']; /** 工具执行闸门(生产用):透传给 runQuery。见 src/toolGate.ts。 */ toolGate?: RunQueryOptions['toolGate']; transientContext?: RunQueryOptions['transientContext']; transientBundle?: RunQueryOptions['transientBundle']; promptCache?: RunQueryOptions['promptCache']; userAttachments?: RunQueryOptions['userAttachments']; inputResources?: RunQueryOptions['inputResources']; executionId?: string; userMessageId?: RunQueryOptions['userMessageId']; /** Explicit delivery target chosen by the host; see RunQueryOptions.deliveryId. */ deliveryId?: RunQueryOptions['deliveryId']; backgroundContinuation?: RunQueryOptions['backgroundContinuation']; agentNoticeDelivery?: RunQueryOptions['agentNoticeDelivery']; deferBackgroundNotifications?: RunQueryOptions['deferBackgroundNotifications']; messageProvenance?: RunQueryOptions['messageProvenance']; userBrowserReferences?: RunQueryOptions['userBrowserReferences']; imageInputs?: RunQueryOptions['imageInputs']; parseInlineImages?: RunQueryOptions['parseInlineImages']; imageDetail?: RunQueryOptions['imageDetail']; imageMaxLongSidePixel?: RunQueryOptions['imageMaxLongSidePixel']; hasQueuedInput?: RunQueryOptions['hasQueuedInput']; takePendingMessages?: RunQueryOptions['takePendingMessages']; canConsumePendingMessages?: RunQueryOptions['canConsumePendingMessages']; steering?: RunQueryOptions['steering']; onToolStart?: RunQueryOptions['onToolStart']; onToolEnd?: RunQueryOptions['onToolEnd']; browserRun?: RunQueryOptions['browserRun']; computerRun?: RunQueryOptions['computerRun']; computerIntervention?: RunQueryOptions['computerIntervention']; memoryContext?: RunQueryOptions['memoryContext']; } export async function* runWithPlugins( userInput: string, options: PluginRunnerOptions, ): AsyncGenerator { const { provider, history, signal } = options; // All model-backed routes retain exactly the host's turn options. const query = (input: string, allowedTools = options.allowedTools) => runQuery(input, { ...options, allowedTools }); const isSlashCommand = userInput.trimStart().startsWith('/'); if (!isSlashCommand) { yield* query(userInput); return; } // 确保插件已发现(resolveCommand 依赖 pluginCache) const cwd = getWorkingDir(); const discoveredPlugins = await discoverPlugins(cwd); let matched = resolveCommand(userInput, cwd); const parsed = parseSlashCommand(userInput); const unknownCmd = parsed?.name ?? ''; const unknownArgs = parsed?.args.trim() ?? ''; // ── `/` 的解析规则(见 slashFallback.ts)──────────────────────────── // 显式前缀 → **只**在那一类里找,找不到就明确报错: // /tool <名字> … 只查工具 // /skill <名字> … 只查 skill // /workflow <名字> … 只查工作流(它是插件命令,走下面的 resolveCommand) // 省略前缀 → 工具 → skill → 插件 fallback;插件冲突必须报错。 // // 为什么要有链式:用户心里的 `/` 是「唤起一个能力」,而能力有三种载体、 // 名字对用户是平级的。只认插件命令的话,`/pptx`、`/research` 这些**明明存在** // 的能力全都会掉进「未知命令,按普通对话处理」—— 用户以为在跑工作流, // 实际只烧了一轮 LLM。 let fallback: SlashTarget | null = null; const explicit = matched ? null : parseExplicitPrefix(unknownCmd, unknownArgs); if (explicit) { if (!explicit.name) { yield { type: 'error', error: `/${unknownCmd} 用法:/${unknownCmd} <名字> [参数]。省略前缀直接写 /<名字> 也可以(会按 工具 → skill → 工作流 的顺序找)。`, }; return; } fallback = await resolveSlashFallback( explicit.name, explicit.args, cwd, explicit.kind, options, ); if (!fallback) { // ⚠️ 显式前缀找不到就**明确报错**,不回落成普通对话 —— // 用户点名要一个工具/skill,静默当聊天处理只会让他以为跑了但没效果。 const label = explicit.kind === 'tool' ? '工具' : 'skill'; yield { type: 'error', error: `当前回合没有可用的${label}「${explicit.name}」。`, }; return; } } else if (!matched && unknownCmd) { fallback = await resolveSlashFallback(unknownCmd, unknownArgs, cwd, undefined, options); if (!fallback) { const claims = []; for (const plugin of discoveredPlugins) { const api = await loadPluginApi(plugin.root); try { const claim = await api?.resolveSlashFallback?.(unknownCmd, unknownArgs, { cwd }); if (!claim) continue; if (typeof claim.commandName !== 'string' || !/^[^/\s]+$/.test(claim.commandName) || typeof claim.args !== 'string' || (claim.message !== undefined && typeof claim.message !== 'string')) throw new Error('简写解析器没有返回有效的命令和参数'); claims.push({ plugin, claim }); } catch (error) { yield { type: 'error', error: `插件「${plugin.name}」解析 /${unknownCmd} 失败:${error instanceof Error ? error.message : String(error)}。请使用显式命令。` }; return; } } if (claims.length > 1) { yield { type: 'error', error: `/${unknownCmd} 被多个插件同时认领:${claims.map((v) => v.plugin.name).join('、')}。请使用显式插件命令。`, }; return; } if (claims.length === 1) { const [{ claim, plugin }] = claims; matched = resolveCommand(`/${claim.commandName}`, cwd); if (!matched || matched.cmd.pluginRoot !== plugin.root || matched.cmd.name !== claim.commandName) { yield { type: 'error', error: `插件「${plugin.name}」认领了 /${unknownCmd},但改写目标 /${claim.commandName} 不是该插件的有效命令。`, }; return; } matched.arguments = claim.args; if (claim.message) { yield { type: 'plugin_progress', pluginId: plugin.name, message: claim.message, }; } } } } if (!matched && fallback) { // 工具 / skill 层:拼一段明确的指令交给模型(工具入参是结构化 schema, // 而命令行只有自由文本 —— 让模型做这层映射正是它擅长的)。 const label = fallback.kind === 'tool' ? '工具' : 'skill'; yield { type: 'plugin_progress', pluginId: 'slash-router', message: `▸ /${unknownCmd} → ${label}「${fallback.name}」`, }; yield* query(buildFallbackInput(fallback), fallback.kind === 'tool' ? [fallback.name] : options.allowedTools); return; } if (!matched) { // 四层都没命中 -> 提示后透传 runQuery。 // / 只是激活前缀(类似 Claude Code 的 / 模式),不是严格命令系统: // 不匹配仍当普通对话处理,让 LLM 自行理解意图。但 -p 等无人值守场景里 // 拼错的 /reseach 会被静默当文本烧一轮 LLM(实战:用户以为在跑工作流, // 实际什么都没发生)--先 warning 列出已注册命令,零成本纠正拼写。 if (unknownCmd) { const available = listAvailableCommands(cwd).map((c) => c.command); yield { type: 'warning', message: `未知命令 /${unknownCmd}(找遍了插件命令、工具、skill、工作流都没有;已注册插件命令:${available.length ? available.join('、') : '无'}),已按普通对话处理。`, }; } yield* query(userInput); return; } // 优先 plugin.ts.runCommand(富插件接管) const entry = await loadPluginEntry(matched.cmd.pluginRoot); if (entry.kind === 'broken') { yield { type: 'error', error: `插件「${matched.cmd.pluginName}」加载失败:${entry.error}。没有执行命令或转交给模型。` }; return; } const api = entry.kind === 'ready' ? entry.api : null; if (api?.runCommand) { yield* api.runCommand(matched.cmd.name, matched.arguments, { presentArtifacts: paths => presentPluginArtifacts(paths, options), executionId: options.executionId, provider, history, signal, sessionState: options.sessionState, maxTurns: options.maxTurns, transientContext: options.transientContext, transientBundle: options.transientBundle, promptCache: options.promptCache, runtimeContext: options.runtimeContext, allowedTools: options.allowedTools, executeTool: options.executeTool, availableTools: options.availableTools, messageProvenance: options.messageProvenance, // ⚠️ 宿主授权上下文**必须**跟着走。这一处曾经漏掉,而下面两条 runQuery 路径 // 都带着它 —— 于是富插件成了三条路里唯一拿不到 browserRun/computerRun 的那条。 // 后果不是"少个字段":workflow 里调 ComputerUse 恒返回「当前宿主未启用 // Computer Use」,同一个工具在主循环里却好好的,症状完全指不向这里。 host: { browserRun: options.browserRun, computerRun: options.computerRun, computerIntervention: options.computerIntervention, toolGate: options.toolGate, }, inputResources: options.inputResources, }); return; } // 声明式 fallback:把 markdown 命令体拼成 prompt 喂 LLM const promptInput = buildCommandInput(matched); yield* query(promptInput); }