"use strict";
// =============================================================================
// Pure Agent - Skills Tool
// Ported from Hermes tools/skills_tool.py
// =============================================================================
Object.defineProperty(exports, "__esModule", { value: true });
exports.registerSkillsTools = registerSkillsTools;
const tool_registry_1 = require("./tool-registry");
const result_types_1 = require("./result-types");
const skill_utils_1 = require("./skill-utils");
const logger_1 = require("./logger");
// ---------------------------------------------------------------------------
// skills_list handler
// ---------------------------------------------------------------------------
async function skillsListHandler(args, _context) {
    const { category } = args;
    try {
        let skills = (0, skill_utils_1.discoverAllSkills)();
        // Filter by category if specified
        if (category) {
            skills = skills.filter(s => s.category === category);
        }
        const categories = [...new Set(skills.map(s => s.category).filter(Boolean))];
        return (0, result_types_1.toolResult)({
            success: true,
            skills: skills.map(s => ({
                name: s.name,
                description: s.description,
                category: s.category,
            })),
            categories,
            count: skills.length,
            hint: 'Use skill_view with a skill name to see its full content and instructions.',
        });
    }
    catch (err) {
        return (0, result_types_1.toolError)(`Failed to list skills: ${err.message}`);
    }
}
// ---------------------------------------------------------------------------
// skill_view handler
// ---------------------------------------------------------------------------
async function skillViewHandler(args, _context) {
    const { name, file_path } = args;
    if (!name)
        return (0, result_types_1.toolError)('Missing required parameter: name');
    try {
        const result = (0, skill_utils_1.skillView)(name);
        if (!result.success) {
            return (0, result_types_1.toolError)(result.error || `Skill "${name}" not found`);
        }
        // If a specific linked file is requested
        if (file_path && result.skillDir) {
            const fullPath = require('path').join(result.skillDir, file_path);
            // Security: prevent path traversal
            if (!fullPath.startsWith(result.skillDir)) {
                return (0, result_types_1.toolError)('Path traversal detected');
            }
            try {
                const fileContent = require('fs').readFileSync(fullPath, 'utf-8');
                return (0, result_types_1.toolResult)({
                    success: true,
                    name: result.name,
                    file_path,
                    content: fileContent,
                });
            }
            catch (err) {
                return (0, result_types_1.toolError)(`Failed to read file: ${err.message}`);
            }
        }
        return (0, result_types_1.toolResult)({
            success: true,
            name: result.name,
            description: result.description,
            content: result.content,
            path: result.path,
            skill_dir: result.skillDir,
            linked_files: result.linkedFiles,
            tags: result.tags,
        });
    }
    catch (err) {
        return (0, result_types_1.toolError)(`Failed to view skill: ${err.message}`);
    }
}
// ---------------------------------------------------------------------------
// skill_manage handler (create/update/delete)
// ---------------------------------------------------------------------------
async function skillManageHandler(args, context) {
    const { action, name, content, description } = args;
    if (!action)
        return (0, result_types_1.toolError)('Missing required parameter: action');
    if (!name)
        return (0, result_types_1.toolError)('Missing required parameter: name');
    const fs = require('fs');
    const pathMod = require('path');
    const { getSkillsDir, normalizeSkillName } = require('./skill-utils');
    const skillsDir = getSkillsDir();
    const safeName = normalizeSkillName(name);
    const skillDir = pathMod.join(skillsDir, safeName);
    const skillPath = pathMod.join(skillDir, 'SKILL.md');
    switch (action) {
        case 'create': {
            if (!content)
                return (0, result_types_1.toolError)('Missing required parameter: content for create');
            if (fs.existsSync(skillPath)) {
                return (0, result_types_1.toolError)(`Skill "${name}" already exists at ${skillPath}`);
            }
            // Ensure skills directory exists
            if (!fs.existsSync(skillsDir)) {
                fs.mkdirSync(skillsDir, { recursive: true });
            }
            if (!fs.existsSync(skillDir)) {
                fs.mkdirSync(skillDir, { recursive: true });
            }
            // Build SKILL.md with frontmatter
            const fm = [
                '---',
                `name: ${safeName}`,
                `description: ${description || 'User-created skill'}`,
                '---',
                '',
            ].join('\n');
            fs.writeFileSync(skillPath, fm + content, 'utf-8');
            (0, logger_1.getLogger)().info(`Created skill: ${safeName} at ${skillPath}`);
            return (0, result_types_1.toolResult)({
                success: true,
                action: 'created',
                name: safeName,
                path: skillPath,
                message: `Skill "${safeName}" created successfully`,
            });
        }
        case 'update': {
            if (!content)
                return (0, result_types_1.toolError)('Missing required parameter: content for update');
            if (!fs.existsSync(skillPath)) {
                return (0, result_types_1.toolError)(`Skill "${name}" not found at ${skillPath}`);
            }
            const existing = fs.readFileSync(skillPath, 'utf-8');
            const [fm] = require('./skill-utils').parseFrontmatter(existing);
            const newContent = [
                '---',
                ...Object.entries(fm).map(([k, v]) => {
                    if (Array.isArray(v))
                        return `${k}: [${v.join(', ')}]`;
                    return `${k}: ${v}`;
                }),
                '---',
                '',
                content,
            ].join('\n');
            fs.writeFileSync(skillPath, newContent, 'utf-8');
            (0, logger_1.getLogger)().info(`Updated skill: ${safeName}`);
            return (0, result_types_1.toolResult)({
                success: true,
                action: 'updated',
                name: safeName,
                path: skillPath,
            });
        }
        case 'delete': {
            if (!fs.existsSync(skillPath)) {
                return (0, result_types_1.toolError)(`Skill "${name}" not found at ${skillPath}`);
            }
            // Safety: only delete from user skills dir, not bundled
            if (!skillDir.startsWith(skillsDir)) {
                return (0, result_types_1.toolError)('Cannot delete skills outside the user skills directory');
            }
            fs.rmSync(skillDir, { recursive: true, force: true });
            (0, logger_1.getLogger)().info(`Deleted skill: ${safeName}`);
            return (0, result_types_1.toolResult)({
                success: true,
                action: 'deleted',
                name: safeName,
            });
        }
        default:
            return (0, result_types_1.toolError)(`Unknown action: ${action}. Valid: create, update, delete`);
    }
}
// ---------------------------------------------------------------------------
// Registration
// ---------------------------------------------------------------------------
function registerSkillsTools() {
    tool_registry_1.registry.register({
        name: 'skills_list',
        toolset: 'skills',
        schema: {
            description: 'List all available skills. Returns skill names, descriptions, and categories. Use skill_view to see a specific skill\'s full content.',
            parameters: {
                type: 'object',
                properties: {
                    category: {
                        type: 'string',
                        description: 'Filter by category (optional)',
                    },
                },
                required: [],
            },
        },
        handler: skillsListHandler,
        isAsync: true,
        description: 'List available skills',
        emoji: '📋',
    });
    tool_registry_1.registry.register({
        name: 'skill_view',
        toolset: 'skills',
        schema: {
            description: 'View a skill\'s full content and instructions. Use skills_list first to see available skills. The skill content includes detailed instructions for the agent to follow.',
            parameters: {
                type: 'object',
                properties: {
                    name: {
                        type: 'string',
                        description: 'The skill name (from skills_list)',
                    },
                    file_path: {
                        type: 'string',
                        description: 'Optional: specific linked file to read (e.g., "references/api.md")',
                    },
                },
                required: ['name'],
            },
        },
        handler: skillViewHandler,
        isAsync: true,
        description: 'View skill content',
        emoji: '📖',
    });
    tool_registry_1.registry.register({
        name: 'skill_manage',
        toolset: 'skills',
        schema: {
            description: 'Create, update, or delete user skills. Skills are stored in ~/.pure-agent/skills/.',
            parameters: {
                type: 'object',
                properties: {
                    action: {
                        type: 'string',
                        enum: ['create', 'update', 'delete'],
                        description: 'Action to perform',
                    },
                    name: {
                        type: 'string',
                        description: 'Skill name',
                    },
                    content: {
                        type: 'string',
                        description: 'Skill content (for create/update)',
                    },
                    description: {
                        type: 'string',
                        description: 'Skill description (for create)',
                    },
                },
                required: ['action', 'name'],
            },
        },
        handler: skillManageHandler,
        isAsync: true,
        description: 'Manage user skills',
        emoji: '🔧',
    });
}
// Auto-register
registerSkillsTools();
//# sourceMappingURL=skills-tool.js.map