"use strict";
/**
 * OpenCode Plugin Entry Point
 * Exports 5 tools for CLI Brain integration
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = plugin;
const plugin_1 = require("@opencode-ai/plugin");
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const os = __importStar(require("os"));
const adapter_js_1 = require("../nvidia/adapter.js");
const agent_loader_js_1 = require("../executor/agent-loader.js");
const agent_executor_js_1 = require("../executor/agent-executor.js");
const background_executor_js_1 = require("../executor/background-executor.js");
const intent_router_js_1 = require("../../router/intent-router.js");
// Global instances
let nvidia = null;
let loader = null;
let executor = null;
let router = null;
/**
 * Initialize the plugin
 */
async function initializePlugin() {
    try {
        // Load config
        const config = await loadConfig();
        // Initialize NVIDIA
        nvidia = new adapter_js_1.NVIDIAAdapter(config.nvidia);
        // Initialize loader
        const agentsPath = (0, agent_loader_js_1.getGlobalAgentsPath)();
        if (!fs.existsSync(agentsPath)) {
            throw new Error('Agents not installed. Run: npx cli-brain-opencode init');
        }
        loader = new agent_loader_js_1.AgentLoader(agentsPath);
        // Build registry
        const registry = await loader.buildRegistry();
        // Initialize executor
        executor = new agent_executor_js_1.AgentExecutor(nvidia, loader);
        // Initialize router
        router = new intent_router_js_1.IntentRouter();
        return true;
    }
    catch (error) {
        console.error('Failed to initialize CLI Brain plugin:', error);
        return false;
    }
}
/**
 * Load configuration
 */
async function loadConfig() {
    const configPath = path.join(os.homedir(), '.cli-brain', 'config.json');
    // Default config
    const defaultConfig = {
        nvidia: {
            apiKey: process.env.NVIDIA_API_KEY || '',
            baseUrl: 'https://integrate.api.nvidia.com/v1',
            defaultModel: 'nvidia/moonshotai/kimi-k2.5',
            availableModels: [
                'nvidia/moonshotai/kimi-k2.5',
                'nvidia/google/gemma-4-31b-it',
                'nvidia/deepseek-ai/deepseek-r1',
                'nvidia/mistralai/mixtral-8x22b-instruct-v0.1'
            ]
        }
    };
    if (fs.existsSync(configPath)) {
        try {
            const saved = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
            return {
                nvidia: { ...defaultConfig.nvidia, ...saved.nvidia }
            };
        }
        catch {
            // Use defaults
        }
    }
    return defaultConfig;
}
/**
 * Main plugin export
 */
async function plugin(ctx) {
    // Initialize on first load
    const initialized = await initializePlugin();
    if (!initialized) {
        return {
            tool: {
                cli_brain_status: (0, plugin_1.tool)({
                    description: "CLI Brain status - shows initialization error",
                    args: {},
                    async execute() {
                        return "❌ CLI Brain not initialized. Run: npx cli-brain-opencode init";
                    }
                })
            }
        };
    }
    // Load available agents for schema
    const registry = await loader.buildRegistry();
    const agentIds = Object.keys(registry.agents);
    const workflowNames = Object.keys(registry.workflows || {});
    return {
        tool: {
            /**
             * Tool 1: Orchestrate - Auto-route to best agent
             */
            orchestrate: (0, plugin_1.tool)({
                description: "Route task to best agent automatically. 181 agents available for code, design, marketing, etc.",
                args: {
                    prompt: plugin_1.tool.schema.string().describe("Task description"),
                    model: plugin_1.tool.schema.string().optional().describe("NVIDIA model to use (kimi-k2.5, gemma-4-31b, deepseek-r1, mixtral-8x22b)"),
                    async: plugin_1.tool.schema.boolean().default(true).describe("Run in background (true) or wait for result (false)"),
                    temperature: plugin_1.tool.schema.number().min(0).max(2).default(0.7).optional().describe("Temperature for generation")
                },
                async execute({ prompt, model, async, temperature }, context) {
                    // Route to best agent
                    const result = router.route(prompt);
                    if (!async) {
                        // Synchronous execution
                        const execResult = await executor.execute({
                            agent: result.primaryAgent,
                            task: prompt,
                            model,
                            temperature
                        });
                        if (!execResult.success) {
                            return { output: `❌ Error: ${execResult.error}`, metadata: { success: false } };
                        }
                        return {
                            output: execResult.content,
                            metadata: {
                                agent: result.primaryAgent,
                                model: execResult.model,
                                confidence: result.confidence,
                                success: true
                            }
                        };
                    }
                    // Async execution
                    const background = new background_executor_js_1.BackgroundExecutor(context.worktree, executor);
                    const workflowId = await background.start({
                        agent: result.primaryAgent,
                        task: prompt,
                        model
                    });
                    return {
                        output: `🚀 Started ${result.primaryAgent}. Workflow ID: ${workflowId}\nUse "check status ${workflowId}" to monitor progress.`,
                        metadata: {
                            workflowId,
                            agent: result.primaryAgent,
                            confidence: result.confidence,
                            async: true
                        }
                    };
                }
            }),
            /**
             * Tool 2: Use Agent - Explicit agent selection
             */
            use_agent: (0, plugin_1.tool)({
                description: "Execute specific agent directly. 181 agents available.",
                args: {
                    agent: plugin_1.tool.schema.string().describe(`Agent ID (e.g., @frontend-developer, @api-architect)`),
                    task: plugin_1.tool.schema.string().describe("Task to execute"),
                    model: plugin_1.tool.schema.string().optional().describe("NVIDIA model to use"),
                    async: plugin_1.tool.schema.boolean().default(false).describe("Run in background"),
                    temperature: plugin_1.tool.schema.number().min(0).max(2).default(0.7).optional().describe("Temperature")
                },
                async execute({ agent, task, model, async, temperature }, context) {
                    // Clean agent ID
                    const agentId = agent.startsWith('@') ? agent : `@${agent}`;
                    if (!async) {
                        const result = await executor.execute({
                            agent: agentId,
                            task,
                            model,
                            temperature
                        });
                        if (!result.success) {
                            return { output: `❌ Error: ${result.error}`, metadata: { success: false } };
                        }
                        return {
                            output: result.content,
                            metadata: {
                                agent: agentId,
                                model: result.model,
                                tokens: result.usage,
                                success: true
                            }
                        };
                    }
                    // Async
                    const background = new background_executor_js_1.BackgroundExecutor(context.worktree, executor);
                    const workflowId = await background.start({
                        agent: agentId,
                        task,
                        model
                    });
                    return {
                        output: `🚀 Started ${agentId}. Workflow ID: ${workflowId}`,
                        metadata: { workflowId, async: true }
                    };
                }
            }),
            /**
             * Tool 3: Run Workflow - Multi-agent chains
             */
            run_workflow: (0, plugin_1.tool)({
                description: "Run predefined multi-agent workflows",
                args: {
                    workflow: plugin_1.tool.schema.string().describe("Workflow name (landing-page, saas-mvp, api-service, auth-system)"),
                    context: plugin_1.tool.schema.object({}).optional().describe("Additional context (project name, style, etc)"),
                    async: plugin_1.tool.schema.boolean().default(true).describe("Run in background")
                },
                async execute({ workflow, context: workflowContext, async }, context) {
                    // Get workflow definition
                    const engine = executor;
                    const workflows = executor.getPredefinedWorkflows?.() || {
                        'landing-page': {
                            steps: [
                                { agent: '@design-system-consultant', task: 'Design color palette, typography, and component specs' },
                                { agent: '@frontend-developer', task: 'Build landing page with design specs' }
                            ]
                        },
                        'saas-mvp': {
                            steps: [
                                { agent: '@product-manager', task: 'Define MVP scope' },
                                { agent: '@api-architect', task: 'Design API' },
                                { agent: '@backend-architect', task: 'Build backend' },
                                { agent: '@frontend-developer', task: 'Build frontend' },
                                { agent: '@testing-reality-checker', task: 'Test MVP' }
                            ]
                        }
                    };
                    const def = workflows[workflow];
                    if (!def) {
                        return { output: `❌ Workflow "${workflow}" not found`, metadata: { success: false } };
                    }
                    // Apply context to tasks
                    const steps = def.steps.map((s) => ({
                        agent: s.agent,
                        task: s.task,
                        model: workflowContext?.model
                    }));
                    if (!async) {
                        // Run synchronously
                        const results = [];
                        for (const step of steps) {
                            const result = await executor.execute(step);
                            results.push(result);
                            if (!result.success)
                                break;
                        }
                        return {
                            output: `✅ Workflow completed\n\n${results.map((r, i) => `Step ${i + 1} (${r.agent}): ${r.success ? '✅' : '❌'} ${r.error || 'Complete'}`).join('\n')}`,
                            metadata: { results, success: true }
                        };
                    }
                    // Async
                    const background = new background_executor_js_1.BackgroundExecutor(context.worktree, executor);
                    const workflowId = await background.startWorkflow(workflow, steps, workflowContext || {});
                    return {
                        output: `🚀 Workflow "${workflow}" started. ID: ${workflowId}\nSteps: ${steps.length} agents`,
                        metadata: { workflowId, steps: steps.length, async: true }
                    };
                }
            }),
            /**
             * Tool 4: Workflow Status - Check background execution
             */
            workflow_status: (0, plugin_1.tool)({
                description: "Check workflow execution status",
                args: {
                    workflow_id: plugin_1.tool.schema.string().describe("Workflow ID from orchestrate, use_agent, or run_workflow")
                },
                async execute({ workflow_id }, context) {
                    const background = new background_executor_js_1.BackgroundExecutor(context.worktree, executor);
                    const status = background.getStatus(workflow_id);
                    if (!status) {
                        return { output: `❌ Workflow ${workflow_id} not found`, metadata: { found: false } };
                    }
                    const elapsedSec = status.elapsed ? Math.round(status.elapsed / 1000) : 0;
                    const lines = [
                        `📊 Workflow: ${status.name}`,
                        `Status: ${status.status}`,
                        `Progress: ${status.progress.current}/${status.progress.total} (${status.progress.percent}%)`,
                        `Started: ${new Date(status.startedAt).toLocaleString()}`,
                        `Elapsed: ${elapsedSec}s`,
                        '',
                        'Steps:'
                    ];
                    status.steps.forEach((s, i) => {
                        const icon = s.status === 'completed' ? '✅' : s.status === 'running' ? '⏳' : s.status === 'failed' ? '❌' : '⏸️';
                        const duration = s.duration ? ` (${Math.round(s.duration / 1000)}s)` : '';
                        lines.push(`  ${i + 1}. ${icon} ${s.agent}${duration}`);
                    });
                    // If complete, show output
                    if (status.status === 'completed') {
                        const output = background.getOutput(workflow_id);
                        if (output?.success && output.output) {
                            lines.push('', '📝 Output:', output.output.substring(0, 500) + (output.output.length > 500 ? '...' : ''));
                        }
                    }
                    return {
                        output: lines.join('\n'),
                        metadata: status
                    };
                }
            }),
            /**
             * Tool 5: List Models - Show available NVIDIA models
             */
            list_models: (0, plugin_1.tool)({
                description: "List available NVIDIA models and their best use cases",
                args: {},
                async execute() {
                    const models = executor.getAvailableModels();
                    const modelInfo = {
                        'nvidia/moonshotai/kimi-k2.5': { name: 'Kimi K2.5', bestFor: ['Code generation', 'Long context'] },
                        'nvidia/google/gemma-4-31b-it': { name: 'Gemma 4 31B', bestFor: ['Balanced performance', 'General tasks'] },
                        'nvidia/deepseek-ai/deepseek-r1': { name: 'DeepSeek R1', bestFor: ['Complex reasoning', 'Architecture'] },
                        'nvidia/mistralai/mixtral-8x22b-instruct-v0.1': { name: 'Mixtral 8x22B', bestFor: ['MoE efficiency', 'Parallel tasks'] }
                    };
                    const lines = ['🤖 Available NVIDIA Models\n'];
                    models.forEach((model, i) => {
                        const info = modelInfo[model];
                        lines.push(`${i + 1}. ${info?.name || model}`);
                        lines.push(`   ID: ${model}`);
                        lines.push(`   Best for: ${info?.bestFor.join(', ') || 'General tasks'}`);
                        lines.push('');
                    });
                    lines.push(`Current default: ${executor.getDefaultModel()}`);
                    return { output: lines.join('\n') };
                }
            }),
            /**
             * Tool 6: List Agents - Show available agents
             */
            list_agents: (0, plugin_1.tool)({
                description: "List available agents by category",
                args: {
                    category: plugin_1.tool.schema.string().optional().describe("Filter by category (engineering, design, marketing, etc)")
                },
                async execute({ category }) {
                    const registry = await loader.buildRegistry();
                    const lines = ['🤖 CLI Brain Agents\n'];
                    const departments = category
                        ? { [category]: registry.departments[category] }
                        : registry.departments;
                    for (const [dept, agents] of Object.entries(departments)) {
                        if (dept === 'root')
                            continue;
                        lines.push(`📁 ${dept.toUpperCase()} (${agents.length})`);
                        agents.slice(0, 5).forEach(agent => {
                            lines.push(`  ${agent.emoji || '🤖'} ${agent.id} - ${agent.description.substring(0, 50)}${agent.description.length > 50 ? '...' : ''}`);
                        });
                        if (agents.length > 5) {
                            lines.push(`  ... and ${agents.length - 5} more`);
                        }
                        lines.push('');
                    }
                    lines.push(`Total: ${registry.totalAgents} agents`);
                    return { output: lines.join('\n') };
                }
            })
        }
    };
}
//# sourceMappingURL=plugin.js.map