"use strict";
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.SkillsPlugin = void 0;
const fs_1 = require("fs");
const path = __importStar(require("path"));
const PluginBase_1 = require("./PluginBase");
const config_1 = require("../config");
function parseFrontmatter(content) {
    const match = content.match(/^---\n([\s\S]*?)\n---/);
    if (!match)
        return {};
    const result = {};
    for (const line of match[1].split("\n")) {
        const [key, ...rest] = line.split(":");
        if (key && rest.length)
            result[key.trim()] = rest.join(":").trim();
    }
    return result;
}
class SkillsPlugin extends PluginBase_1.PluginBase {
    static meta = {
        key: "skills",
        name: "Skills Plugin",
        description: "Scans configured skills directories for SKILL.md files and provides skill content to agents",
        requires: [],
    };
    meta = SkillsPlugin.meta;
    constructor(context) {
        super(context);
    }
    async call(input) {
        const result = await this.embed(input || "");
        return result.map((e) => e.text).join("\n\n");
    }
    async embed(userPrompt) {
        const config = await (0, config_1.getConfig)();
        const skillDirs = config.skills || [];
        if (skillDirs.length === 0) {
            return [];
        }
        const skills = await this.scanSkills(skillDirs);
        if (skills.length === 0) {
            return [];
        }
        const matchedSkills = skills.filter((skill) => userPrompt.toLowerCase().includes(skill.name.toLowerCase()));
        if (matchedSkills.length > 0) {
            const results = [];
            for (const skill of matchedSkills) {
                try {
                    const content = await fs_1.promises.readFile(skill.filePath, "utf-8");
                    results.push({
                        id: skill.filePath,
                        text: `## Skill: ${skill.name}\nFile: ${skill.filePath}\n\n${content}`,
                        metadata: { filePath: skill.filePath },
                    });
                }
                catch {
                }
            }
            return results;
        }
        const summary = this.buildSkillSummary(skills);
        return [
            {
                id: "skills:summary",
                text: summary,
                metadata: {},
            },
        ];
    }
    async scanSkills(dirs) {
        const skills = [];
        for (const dir of dirs) {
            const resolvedDir = dir.replace(/^~/, process.env.HOME || "");
            try {
                const found = await this.findSkillFiles(resolvedDir);
                skills.push(...found);
            }
            catch {
            }
        }
        return skills;
    }
    async findSkillFiles(dir) {
        const skills = [];
        let entries;
        try {
            entries = await fs_1.promises.readdir(dir, { withFileTypes: true });
        }
        catch {
            return skills;
        }
        for (const entry of entries) {
            const fullPath = path.join(dir, entry.name);
            if (entry.isDirectory()) {
                const nested = await this.findSkillFiles(fullPath);
                skills.push(...nested);
            }
            else if (entry.isFile() && entry.name === "SKILL.md") {
                try {
                    const content = await fs_1.promises.readFile(fullPath, "utf-8");
                    const frontmatter = parseFrontmatter(content);
                    const name = frontmatter.name;
                    const description = frontmatter.description || "";
                    if (name) {
                        skills.push({ name, description, filePath: fullPath });
                    }
                }
                catch {
                }
            }
        }
        return skills;
    }
    buildSkillSummary(skills) {
        const lines = ["Available skills:"];
        for (const skill of skills) {
            lines.push(`- ${skill.name} (${skill.filePath}): ${skill.description}`);
        }
        lines.push("");
        lines.push("To use a skill, reference its name in your request and I will load the full instructions.");
        return lines.join("\n");
    }
}
exports.SkillsPlugin = SkillsPlugin;
//# sourceMappingURL=SkillsPlugin.js.map