// engine/plugins/extensions/tool-extension.ts — Tool registration (SPEC-085 AC-04)
import { withPluginTimeout } from '../sandbox.js';
/** Registry of plugin tools keyed by prefixed name */
const pluginToolRegistry = new Map();
/**
 * Builds the prefixed tool name for a plugin tool.
 */
export function buildPluginToolName(pluginId, toolName) {
    return `plugin:${pluginId}:${toolName}`;
}
/**
 * Registers tools from a plugin. Each tool is prefixed with `plugin:{pluginId}:`.
 * Returns the list of registered prefixed names.
 */
export function registerPluginTools(pluginId, tools, builtInTools) {
    const registered = [];
    for (const tool of tools) {
        const prefixedName = buildPluginToolName(pluginId, tool.name);
        if (builtInTools.has(tool.name)) {
            throw new Error(`Plugin "${pluginId}" tool "${tool.name}" conflicts with built-in tool`);
        }
        if (pluginToolRegistry.has(prefixedName)) {
            const existing = pluginToolRegistry.get(prefixedName);
            /* v8 ignore next -- existing is always truthy after .has() check */
            if (existing && existing.pluginId !== pluginId) {
                throw new Error(`Plugin "${pluginId}" tool "${tool.name}" conflicts with plugin "${existing.pluginId}"`);
            }
        }
        pluginToolRegistry.set(prefixedName, { pluginId, definition: tool });
        registered.push(prefixedName);
    }
    return registered;
}
/**
 * Unregisters all tools belonging to a plugin.
 */
export function unregisterPluginTools(pluginId) {
    const removed = [];
    for (const [name, entry] of pluginToolRegistry) {
        if (entry.pluginId === pluginId) {
            pluginToolRegistry.delete(name);
            removed.push(name);
        }
    }
    return removed;
}
/**
 * Invokes a plugin tool by its prefixed name, with timeout wrapping.
 */
export async function invokePluginTool(prefixedName, input, timeoutMs) {
    const entry = pluginToolRegistry.get(prefixedName);
    if (!entry) {
        throw new Error(`Plugin tool "${prefixedName}" not found`);
    }
    return withPluginTimeout(entry.pluginId, `tool:${entry.definition.name}`, () => entry.definition.handler(input), timeoutMs);
}
/**
 * Returns all registered plugin tools.
 */
export function getRegisteredPluginTools() {
    return new Map(pluginToolRegistry);
}
/**
 * Returns the count of tools registered for a specific plugin.
 */
export function getPluginToolCount(pluginId) {
    let count = 0;
    for (const entry of pluginToolRegistry.values()) {
        if (entry.pluginId === pluginId) {
            count++;
        }
    }
    return count;
}
/**
 * Clears all plugin tools (for testing).
 */
export function clearPluginToolRegistry() {
    pluginToolRegistry.clear();
}
//# sourceMappingURL=tool-extension.js.map