"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }// ../packages/skills/dist/index.js
var _graymatter = require('gray-matter'); var _graymatter2 = _interopRequireDefault(_graymatter);








var _fs = require('fs');
var _os = require('os');
var _path = require('path');


function validateSkillDefinitionContent(content, file = "SKILL.md") {
  const errors = [];
  const warnings = [];
  let parsed;
  try {
    parsed = _graymatter2.default.call(void 0, content);
  } catch (error) {
    errors.push(issue(
      file,
      "frontmatter",
      `Invalid skill frontmatter: ${error instanceof Error ? error.message : "Unknown error"}`,
      "error"
    ));
    return result(errors, warnings);
  }
  const data = parsed.data && typeof parsed.data === "object" ? parsed.data : {};
  if (!isNonEmptyString(data.name)) {
    errors.push(issue(file, "frontmatter.name", "Skill metadata requires name", "error"));
  }
  if (!isNonEmptyString(data.description)) {
    errors.push(issue(file, "frontmatter.description", "Skill metadata requires description", "error"));
  }
  validateStringArray(data.globs, "frontmatter.globs", file, errors);
  validateStringArray(data.alwaysAllow, "frontmatter.alwaysAllow", file, errors);
  validateRequiredSources(data.requiredSources, file, errors);
  if (!data.globs && !data.requiredSources) {
    warnings.push(issue(
      file,
      "frontmatter",
      "Skill has no activation metadata",
      "warning",
      "Add globs, requiredSources, or select the skill explicitly from the host UI."
    ));
  }
  if (!parsed.content.trim()) {
    warnings.push(issue(
      file,
      "content",
      "Skill body is empty",
      "warning",
      "Add provider instructions to make the skill useful when activated."
    ));
  }
  return result(errors, warnings);
}
function validateRequiredSources(value, file, errors) {
  if (value === void 0) return;
  if (typeof value === "string") return;
  validateStringArray(value, "frontmatter.requiredSources", file, errors);
}
function validateStringArray(value, path, file, errors) {
  if (value === void 0) return;
  if (!Array.isArray(value)) {
    errors.push(issue(file, path, `${leafName(path)} must be an array of strings`, "error"));
    return;
  }
  value.forEach((entry, index) => {
    if (typeof entry !== "string") {
      errors.push(issue(file, `${path}[${index}]`, `${leafName(path)} entries must be strings`, "error"));
    }
  });
}
function issue(file, path, message, severity, suggestion) {
  return {
    file,
    path,
    message,
    severity,
    ...suggestion ? { suggestion } : {}
  };
}
function result(errors, warnings) {
  return {
    valid: errors.length === 0,
    errors,
    warnings
  };
}
function isNonEmptyString(value) {
  return typeof value === "string" && value.trim().length > 0;
}
function leafName(path) {
  return _nullishCoalesce(path.split(".").at(-1), () => ( path));
}
function getWorkspaceSkillsPath(workspaceRoot) {
  return _path.join.call(void 0, workspaceRoot, "skills");
}
function validateIconValue(value, context) {
  if (value === void 0 || value === null) return void 0;
  if (typeof value !== "string") return void 0;
  if (/^[\p{Emoji}\u200d\ufe0f]+$/u.test(value)) return value;
  if (value.startsWith("http://") || value.startsWith("https://")) return value;
  console.warn(`[${context}] Invalid icon value: "${value}". Only emoji and URLs are supported.`);
  return void 0;
}
function findIconFile(dirPath) {
  return void 0;
}
async function downloadIcon(dirPath, iconUrl, context) {
  console.warn(`[${context}] Icon download stub: would download ${iconUrl}`);
  return null;
}
function needsIconDownload(icon, iconPath) {
  if (!icon) return false;
  if (icon.startsWith("http://") || icon.startsWith("https://")) {
    return !iconPath;
  }
  return false;
}
var GLOBAL_AGENT_SKILLS_DIR = _path.join.call(void 0, _os.homedir.call(void 0, ), ".agents", "skills");
var PROJECT_AGENT_SKILLS_DIR = ".agents/skills";
function normalizeRequiredSources(value) {
  const asArray = typeof value === "string" ? [value] : Array.isArray(value) ? value : void 0;
  if (!asArray) return void 0;
  const normalized = Array.from(new Set(
    asArray.filter((entry) => typeof entry === "string").map((entry) => entry.trim()).filter(Boolean)
  ));
  return normalized.length > 0 ? normalized : void 0;
}
function parseSkillFile(content) {
  try {
    const parsed = _graymatter2.default.call(void 0, content);
    if (!parsed.data.name || !parsed.data.description) {
      return null;
    }
    const icon = validateIconValue(parsed.data.icon, "Skills");
    return {
      metadata: {
        name: parsed.data.name,
        description: parsed.data.description,
        globs: parsed.data.globs,
        alwaysAllow: parsed.data.alwaysAllow,
        icon,
        requiredSources: normalizeRequiredSources(parsed.data.requiredSources)
      },
      body: parsed.content
    };
  } catch (e) {
    return null;
  }
}
function loadSkillFromDir(skillsDir, slug, source) {
  const skillDir = _path.join.call(void 0, skillsDir, slug);
  const skillFile = _path.join.call(void 0, skillDir, "SKILL.md");
  if (!_fs.existsSync.call(void 0, skillDir) || !_fs.statSync.call(void 0, skillDir).isDirectory()) {
    return null;
  }
  if (!_fs.existsSync.call(void 0, skillFile)) {
    return null;
  }
  let content;
  try {
    content = _fs.readFileSync.call(void 0, skillFile, "utf-8");
  } catch (e2) {
    return null;
  }
  const parsed = parseSkillFile(content);
  if (!parsed) {
    return null;
  }
  return {
    slug,
    metadata: parsed.metadata,
    content: parsed.body,
    iconPath: findIconFile(skillDir),
    path: skillDir,
    source
  };
}
function loadSkillsFromDir(skillsDir, source) {
  if (!_fs.existsSync.call(void 0, skillsDir)) {
    return [];
  }
  const skills = [];
  try {
    const entries = _fs.readdirSync.call(void 0, skillsDir, { withFileTypes: true });
    for (const entry of entries) {
      if (!entry.isDirectory()) continue;
      const skill = loadSkillFromDir(skillsDir, entry.name, source);
      if (skill) {
        skills.push(skill);
      }
    }
  } catch (e3) {
  }
  return skills;
}
function loadSkill(workspaceRoot, slug) {
  const skillsDir = getWorkspaceSkillsPath(workspaceRoot);
  return loadSkillFromDir(skillsDir, slug, "workspace");
}
function loadWorkspaceSkills(workspaceRoot) {
  const skillsDir = getWorkspaceSkillsPath(workspaceRoot);
  return loadSkillsFromDir(skillsDir, "workspace");
}
var skillsCache = /* @__PURE__ */ new Map();
var SKILLS_CACHE_TTL = 5 * 6e4;
function invalidateSkillsCache() {
  skillsCache.clear();
}
function loadAllSkills(workspaceRoot, projectRoot) {
  const cacheKey = `${workspaceRoot}::${_nullishCoalesce(projectRoot, () => ( ""))}`;
  const now = Date.now();
  const cached = skillsCache.get(cacheKey);
  if (cached && now - cached.ts < SKILLS_CACHE_TTL) {
    return cached.skills;
  }
  const skillsBySlug = /* @__PURE__ */ new Map();
  for (const skill of loadSkillsFromDir(GLOBAL_AGENT_SKILLS_DIR, "global")) {
    skillsBySlug.set(skill.slug, skill);
  }
  for (const skill of loadWorkspaceSkills(workspaceRoot)) {
    skillsBySlug.set(skill.slug, skill);
  }
  if (projectRoot) {
    const projectSkillsDir = _path.join.call(void 0, projectRoot, PROJECT_AGENT_SKILLS_DIR);
    for (const skill of loadSkillsFromDir(projectSkillsDir, "project")) {
      skillsBySlug.set(skill.slug, skill);
    }
  }
  const result2 = Array.from(skillsBySlug.values());
  skillsCache.set(cacheKey, { skills: result2, ts: now });
  return result2;
}
function loadSkillBySlug(workspaceRoot, slug, projectRoot) {
  if (projectRoot) {
    const projectSkillsDir = _path.join.call(void 0, projectRoot, PROJECT_AGENT_SKILLS_DIR);
    const skill = loadSkillFromDir(projectSkillsDir, slug, "project");
    if (skill) return skill;
  }
  const workspaceSkill = loadSkillFromDir(getWorkspaceSkillsPath(workspaceRoot), slug, "workspace");
  if (workspaceSkill) return workspaceSkill;
  return loadSkillFromDir(GLOBAL_AGENT_SKILLS_DIR, slug, "global");
}
function getSkillIconPath(workspaceRoot, slug) {
  const skillsDir = getWorkspaceSkillsPath(workspaceRoot);
  const skillDir = _path.join.call(void 0, skillsDir, slug);
  if (!_fs.existsSync.call(void 0, skillDir)) {
    return null;
  }
  return findIconFile(skillDir) || null;
}
function deleteSkill(workspaceRoot, slug) {
  const skillsDir = getWorkspaceSkillsPath(workspaceRoot);
  const skillDir = _path.join.call(void 0, skillsDir, slug);
  if (!_fs.existsSync.call(void 0, skillDir)) {
    return false;
  }
  try {
    _fs.rmSync.call(void 0, skillDir, { recursive: true });
    return true;
  } catch (e4) {
    return false;
  }
}
function createSkill(workspaceRoot, input) {
  const skillsDir = getWorkspaceSkillsPath(workspaceRoot);
  const skillDir = _path.join.call(void 0, skillsDir, input.slug);
  const skillFile = _path.join.call(void 0, skillDir, "SKILL.md");
  const frontmatter = {
    name: input.name,
    description: input.description
  };
  if (input.globs) frontmatter.globs = input.globs;
  if (input.alwaysAllow) frontmatter.alwaysAllow = input.alwaysAllow;
  if (input.icon) {
    const validated = validateIconValue(input.icon, "Skills");
    if (validated) frontmatter.icon = validated;
  }
  if (input.requiredSources) frontmatter.requiredSources = input.requiredSources;
  const fileContent = _graymatter2.default.stringify(input.content, frontmatter);
  _fs.mkdirSync.call(void 0, skillDir, { recursive: true });
  _fs.writeFileSync.call(void 0, skillFile, fileContent, "utf-8");
  invalidateSkillsCache();
  const loaded = loadSkillFromDir(skillsDir, input.slug, "workspace");
  if (!loaded) {
    throw new Error(`Failed to load newly created skill: ${input.slug}`);
  }
  return loaded;
}
function updateSkill(workspaceRoot, slug, patch) {
  const skillsDir = getWorkspaceSkillsPath(workspaceRoot);
  const existing = loadSkillFromDir(skillsDir, slug, "workspace");
  if (!existing) {
    throw new Error(`Skill not found: ${slug}`);
  }
  const frontmatter = {
    name: _nullishCoalesce(patch.name, () => ( existing.metadata.name)),
    description: _nullishCoalesce(patch.description, () => ( existing.metadata.description))
  };
  const globs = _nullishCoalesce(patch.globs, () => ( existing.metadata.globs));
  if (globs) frontmatter.globs = globs;
  const alwaysAllow = _nullishCoalesce(patch.alwaysAllow, () => ( existing.metadata.alwaysAllow));
  if (alwaysAllow) frontmatter.alwaysAllow = alwaysAllow;
  const icon = _nullishCoalesce(patch.icon, () => ( existing.metadata.icon));
  if (icon) {
    const validated = validateIconValue(icon, "Skills");
    if (validated) frontmatter.icon = validated;
  }
  const requiredSources = _nullishCoalesce(patch.requiredSources, () => ( existing.metadata.requiredSources));
  if (requiredSources) frontmatter.requiredSources = requiredSources;
  const content = _nullishCoalesce(patch.content, () => ( existing.content));
  const fileContent = _graymatter2.default.stringify(content, frontmatter);
  const skillFile = _path.join.call(void 0, skillsDir, slug, "SKILL.md");
  _fs.writeFileSync.call(void 0, skillFile, fileContent, "utf-8");
  invalidateSkillsCache();
  const loaded = loadSkillFromDir(skillsDir, slug, "workspace");
  if (!loaded) {
    throw new Error(`Failed to load updated skill: ${slug}`);
  }
  return loaded;
}
function skillExists(workspaceRoot, slug) {
  const skillsDir = getWorkspaceSkillsPath(workspaceRoot);
  const skillDir = _path.join.call(void 0, skillsDir, slug);
  const skillFile = _path.join.call(void 0, skillDir, "SKILL.md");
  return _fs.existsSync.call(void 0, skillDir) && _fs.existsSync.call(void 0, skillFile);
}
function listSkillSlugs(workspaceRoot) {
  const skillsDir = getWorkspaceSkillsPath(workspaceRoot);
  if (!_fs.existsSync.call(void 0, skillsDir)) {
    return [];
  }
  try {
    return _fs.readdirSync.call(void 0, skillsDir, { withFileTypes: true }).filter((entry) => {
      if (!entry.isDirectory()) return false;
      const skillFile = _path.join.call(void 0, skillsDir, entry.name, "SKILL.md");
      return _fs.existsSync.call(void 0, skillFile);
    }).map((entry) => entry.name);
  } catch (e5) {
    return [];
  }
}
async function downloadSkillIcon(skillDir, iconUrl) {
  return downloadIcon(skillDir, iconUrl, "Skills");
}
function skillNeedsIconDownload(skill) {
  return needsIconDownload(skill.metadata.icon, skill.iconPath);
}

















exports.validateSkillDefinitionContent = validateSkillDefinitionContent; exports.GLOBAL_AGENT_SKILLS_DIR = GLOBAL_AGENT_SKILLS_DIR; exports.PROJECT_AGENT_SKILLS_DIR = PROJECT_AGENT_SKILLS_DIR; exports.loadSkill = loadSkill; exports.invalidateSkillsCache = invalidateSkillsCache; exports.loadAllSkills = loadAllSkills; exports.loadSkillBySlug = loadSkillBySlug; exports.getSkillIconPath = getSkillIconPath; exports.deleteSkill = deleteSkill; exports.createSkill = createSkill; exports.updateSkill = updateSkill; exports.skillExists = skillExists; exports.listSkillSlugs = listSkillSlugs; exports.downloadSkillIcon = downloadSkillIcon; exports.skillNeedsIconDownload = skillNeedsIconDownload;
