"use strict";
// =============================================================================
// Pure Agent - Plugin System
// Ported from Hermes plugins/__init__.py
// Full plugin loading, execution, hooks, and lifecycle management
// =============================================================================
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.PluginSystem = void 0;
exports.getPluginSystem = getPluginSystem;
exports.discoverPlugins = discoverPlugins;
exports.loadPlugins = loadPlugins;
exports.getPluginContext = getPluginContext;
exports.invokeHook = invokeHook;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
const events_1 = require("events");
const constants_1 = require("./constants");
const tool_registry_1 = require("./tool-registry");
const logger_1 = require("./logger");
const result_types_1 = require("./tools/../result-types");
const ALL_HOOKS = [
    'on_session_start', 'on_session_end',
    'on_turn_start', 'on_turn_end',
    'on_response', 'on_tool_call',
    'on_error', 'on_message_received', 'on_message_sent',
];
// ---------------------------------------------------------------------------
// PluginSystem
// ---------------------------------------------------------------------------
class PluginSystem extends events_1.EventEmitter {
    _plugins = new Map();
    _hooks = new Map();
    _pluginsDir;
    constructor() {
        super();
        this._pluginsDir = path.join((0, constants_1.getPureAgentHome)(), 'plugins');
    }
    // -------------------------------------------------------------------------
    // Discovery
    // -------------------------------------------------------------------------
    discover() {
        if (!fs.existsSync(this._pluginsDir)) {
            fs.mkdirSync(this._pluginsDir, { recursive: true });
            return [];
        }
        const discovered = [];
        const entries = fs.readdirSync(this._pluginsDir, { withFileTypes: true });
        for (const entry of entries) {
            if (!entry.isDirectory())
                continue;
            const pluginDir = path.join(this._pluginsDir, entry.name);
            const manifestPath = path.join(pluginDir, 'plugin.json');
            if (!fs.existsSync(manifestPath))
                continue;
            try {
                const raw = fs.readFileSync(manifestPath, 'utf-8');
                const manifest = JSON.parse(raw);
                if (!manifest.name) {
                    (0, logger_1.getLogger)().warn(`Plugin ${entry.name}: missing name in manifest`);
                    continue;
                }
                // Check if already registered
                if (this._plugins.has(manifest.name)) {
                    (0, logger_1.getLogger)().debug(`Plugin ${manifest.name}: already discovered`);
                    continue;
                }
                const instance = {
                    manifest,
                    dir: pluginDir,
                    module: null,
                    enabled: true,
                    loadedAt: null,
                    error: null,
                    registeredTools: [],
                };
                this._plugins.set(manifest.name, instance);
                discovered.push(manifest.name);
                (0, logger_1.getLogger)().info(`Discovered plugin: ${manifest.name} v${manifest.version}`);
            }
            catch (err) {
                (0, logger_1.getLogger)().warn(`Plugin ${entry.name}: failed to parse manifest: ${err.message}`);
            }
        }
        return discovered;
    }
    // -------------------------------------------------------------------------
    // Loading
    // -------------------------------------------------------------------------
    async loadPlugin(name) {
        const instance = this._plugins.get(name);
        if (!instance) {
            (0, logger_1.getLogger)().error(`Plugin ${name}: not discovered`);
            return false;
        }
        if (instance.module) {
            (0, logger_1.getLogger)().debug(`Plugin ${name}: already loaded`);
            return true;
        }
        // Check dependencies
        if (instance.manifest.dependencies) {
            for (const dep of instance.manifest.dependencies) {
                const depInstance = this._plugins.get(dep);
                if (!depInstance || !depInstance.module) {
                    (0, logger_1.getLogger)().error(`Plugin ${name}: missing dependency ${dep}`);
                    instance.error = `Missing dependency: ${dep}`;
                    return false;
                }
            }
        }
        try {
            // Load entry module
            const entryFile = instance.manifest.entry || 'index.js';
            const entryPath = path.join(instance.dir, entryFile);
            if (!fs.existsSync(entryPath)) {
                // Try index.ts compiled to dist
                const distPath = path.join(instance.dir, 'dist', 'index.js');
                if (fs.existsSync(distPath)) {
                    instance.module = require(distPath);
                }
                else {
                    throw new Error(`Entry file not found: ${entryFile}`);
                }
            }
            else {
                instance.module = require(entryPath);
            }
            instance.loadedAt = new Date().toISOString();
            instance.error = null;
            // Register tools
            this._registerPluginTools(instance);
            // Register hooks
            this._registerPluginHooks(instance);
            // Call plugin init if exported
            if (typeof instance.module.onLoad === 'function') {
                await instance.module.onLoad();
            }
            (0, logger_1.getLogger)().info(`Loaded plugin: ${name} v${instance.manifest.version}`);
            return true;
        }
        catch (err) {
            instance.error = err.message;
            (0, logger_1.getLogger)().error(`Plugin ${name}: load failed: ${err.message}`);
            return false;
        }
    }
    async loadAll() {
        const loaded = [];
        // Topological sort by dependencies
        const sorted = this._topologicalSort();
        for (const name of sorted) {
            const success = await this.loadPlugin(name);
            if (success)
                loaded.push(name);
        }
        (0, logger_1.getLogger)().info(`Loaded ${loaded.length}/${this._plugins.size} plugins`);
        return loaded;
    }
    // -------------------------------------------------------------------------
    // Tool registration
    // -------------------------------------------------------------------------
    _registerPluginTools(instance) {
        const tools = instance.manifest.tools;
        if (!tools || !instance.module)
            return;
        for (const toolDef of tools) {
            const handler = instance.module[toolDef.handler];
            if (typeof handler !== 'function') {
                (0, logger_1.getLogger)().warn(`Plugin ${instance.manifest.name}: handler '${toolDef.handler}' not found for tool '${toolDef.name}'`);
                continue;
            }
            // Wrap handler to pass through plugin context
            const wrappedHandler = async (args, context) => {
                try {
                    return await handler(args, context);
                }
                catch (err) {
                    return (0, result_types_1.toolError)(`Plugin tool error: ${err.message}`);
                }
            };
            tool_registry_1.registry.register({
                name: toolDef.name,
                toolset: toolDef.toolset || `plugin-${instance.manifest.name}`,
                schema: {
                    description: toolDef.description,
                    parameters: toolDef.parameters,
                },
                handler: wrappedHandler,
                isAsync: toolDef.is_async !== false,
                description: toolDef.description,
                emoji: toolDef.emoji || '🔌',
            });
            instance.registeredTools.push(toolDef.name);
            (0, logger_1.getLogger)().info(`Plugin ${instance.manifest.name}: registered tool '${toolDef.name}'`);
        }
    }
    // -------------------------------------------------------------------------
    // Hook registration
    // -------------------------------------------------------------------------
    _registerPluginHooks(instance) {
        const hooks = instance.manifest.hooks;
        if (!hooks || !instance.module)
            return;
        for (const [hookName, fnName] of Object.entries(hooks)) {
            if (!ALL_HOOKS.includes(hookName)) {
                (0, logger_1.getLogger)().warn(`Plugin ${instance.manifest.name}: unknown hook '${hookName}'`);
                continue;
            }
            const fn = instance.module[fnName];
            if (typeof fn !== 'function') {
                (0, logger_1.getLogger)().warn(`Plugin ${instance.manifest.name}: hook function '${fnName}' not found`);
                continue;
            }
            if (!this._hooks.has(hookName)) {
                this._hooks.set(hookName, []);
            }
            this._hooks.get(hookName).push({
                plugin: instance.manifest.name,
                fn,
            });
            (0, logger_1.getLogger)().debug(`Plugin ${instance.manifest.name}: registered hook '${hookName}' -> '${fnName}'`);
        }
    }
    // -------------------------------------------------------------------------
    // Hook execution
    // -------------------------------------------------------------------------
    async invokeHook(hookName, data) {
        const handlers = this._hooks.get(hookName);
        if (!handlers || handlers.length === 0)
            return [];
        const results = [];
        for (const { plugin, fn } of handlers) {
            try {
                const result = await fn(data);
                results.push({ plugin, result });
            }
            catch (err) {
                (0, logger_1.getLogger)().warn(`Plugin ${plugin}: hook '${hookName}' error: ${err.message}`);
                results.push({ plugin, error: err.message });
            }
        }
        return results;
    }
    // -------------------------------------------------------------------------
    // Plugin management
    // -------------------------------------------------------------------------
    getPlugin(name) {
        return this._plugins.get(name);
    }
    getAllPlugins() {
        return Array.from(this._plugins.values());
    }
    getEnabledPlugins() {
        return Array.from(this._plugins.values()).filter(p => p.enabled);
    }
    async enablePlugin(name) {
        const instance = this._plugins.get(name);
        if (!instance)
            return false;
        if (!instance.module) {
            const loaded = await this.loadPlugin(name);
            if (!loaded)
                return false;
        }
        instance.enabled = true;
        (0, logger_1.getLogger)().info(`Plugin ${name}: enabled`);
        return true;
    }
    disablePlugin(name) {
        const instance = this._plugins.get(name);
        if (!instance)
            return false;
        instance.enabled = false;
        // Deregister tools
        for (const toolName of instance.registeredTools) {
            tool_registry_1.registry.deregister(toolName);
        }
        instance.registeredTools = [];
        // Remove hooks
        for (const [, handlers] of this._hooks) {
            const idx = handlers.findIndex(h => h.plugin === name);
            if (idx >= 0)
                handlers.splice(idx, 1);
        }
        (0, logger_1.getLogger)().info(`Plugin ${name}: disabled`);
        return true;
    }
    async unloadPlugin(name) {
        const instance = this._plugins.get(name);
        if (!instance)
            return false;
        // Disable first
        this.disablePlugin(name);
        // Call cleanup
        if (instance.module?.onUnload) {
            try {
                await instance.module.onUnload();
            }
            catch { /* ignore */ }
        }
        // Clear module cache
        if (instance.module) {
            const entryPath = path.join(instance.dir, instance.manifest.entry || 'index.js');
            delete require.cache[require.resolve(entryPath)];
        }
        instance.module = null;
        instance.loadedAt = null;
        this._plugins.delete(name);
        (0, logger_1.getLogger)().info(`Plugin ${name}: unloaded`);
        return true;
    }
    // -------------------------------------------------------------------------
    // Topological sort
    // -------------------------------------------------------------------------
    _topologicalSort() {
        const visited = new Set();
        const result = [];
        const visit = (name) => {
            if (visited.has(name))
                return;
            visited.add(name);
            const instance = this._plugins.get(name);
            if (instance?.manifest.dependencies) {
                for (const dep of instance.manifest.dependencies) {
                    if (this._plugins.has(dep))
                        visit(dep);
                }
            }
            result.push(name);
        };
        for (const name of this._plugins.keys()) {
            visit(name);
        }
        return result;
    }
    // -------------------------------------------------------------------------
    // Shutdown
    // -------------------------------------------------------------------------
    async shutdown() {
        for (const name of this._plugins.keys()) {
            await this.unloadPlugin(name);
        }
        this._hooks.clear();
        (0, logger_1.getLogger)().info('Plugin system shut down');
    }
}
exports.PluginSystem = PluginSystem;
// ---------------------------------------------------------------------------
// Singleton
// ---------------------------------------------------------------------------
let _instance = null;
function getPluginSystem() {
    if (!_instance) {
        _instance = new PluginSystem();
    }
    return _instance;
}
// ---------------------------------------------------------------------------
// Convenience functions
// ---------------------------------------------------------------------------
function discoverPlugins() {
    return getPluginSystem().discover();
}
async function loadPlugins() {
    return getPluginSystem().loadAll();
}
function getPluginContext() {
    return getPluginSystem();
}
async function invokeHook(hookName, data) {
    return getPluginSystem().invokeHook(hookName, data);
}
//# sourceMappingURL=plugin-system.js.map