/**
 * ============================================================
 *  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) 未命中 → 当普通问句喂给 runQuery（让 LLM 自己解释 / 未知命令）
 * ============================================================
 */
import { discoverPlugins, resolveCommand, buildCommandInput, } from './commandRouter.js';
import { loadPluginApi } from './pluginLoader.js';
import { runQuery } from '../loop.js';
export async function* runWithPlugins(userInput, options) {
    const { provider, history, signal } = options;
    const isSlashCommand = userInput.trimStart().startsWith('/');
    if (!isSlashCommand) {
        yield* runQuery(userInput, {
            provider,
            history,
            signal,
            maxTurns: options.maxTurns,
            sessionState: options.sessionState,
        });
        return;
    }
    await discoverPlugins();
    const matched = resolveCommand(userInput);
    if (!matched) {
        // 未知 / 命令直接喂 LLM,让模型自然回复(等同于普通文本)
        yield* runQuery(userInput, {
            provider,
            history,
            signal,
            maxTurns: options.maxTurns,
            sessionState: options.sessionState,
        });
        return;
    }
    // 优先 plugin.ts.runCommand（富插件接管）
    const api = await loadPluginApi(matched.cmd.pluginRoot);
    if (api?.runCommand) {
        yield* api.runCommand(matched.cmd.name, matched.arguments, {
            provider,
            history,
            signal,
            sessionState: options.sessionState,
            maxTurns: options.maxTurns,
        });
        return;
    }
    // 声明式 fallback：把 markdown 命令体拼成 prompt 喂 LLM
    const promptInput = buildCommandInput(matched);
    yield* runQuery(promptInput, {
        provider,
        history,
        signal,
        maxTurns: options.maxTurns,
        sessionState: options.sessionState,
    });
}
