All files / src/skills loader.ts

90.83% Statements 109/120
78.12% Branches 50/64
100% Functions 17/17
90.75% Lines 108/119

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537                    48x 48x                           13x                               13x                       13x                           13x             13x           16x             21x 21x             15x       15x 15x 15x   15x       2x       13x             71x                               86x 86x                               90x 90x   4x 4x             86x 86x   86x                         8x   8x 5x     3x                                                       14x 14x     14x 14x 1x     13x     13x 13x                 13x 24x     24x 24x 19x 19x 19x         19x       5x 4x 4x 2x             2x 2x 1x           13x 13x                                               2x   2x 4x 4x   2x 2x 3x 3x                 2x       1x       2x                             1x       1x 1x 2x 2x       1x                                                                       22x     22x               22x 11x   11x 11x 6x     5x 3x     2x       11x 5x 10x   10x 10x 4x     6x 6x           7x 5x 5x 5x   5x 5x 3x     2x 2x           4x     13x               13x                                                     18x                                                     2x 1x   1x                                               4x    
import { readFile, readdir } from 'node:fs/promises';
import { dirname, extname, join } from 'node:path';
import { existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { loadSkillMd, SkillLoadError } from '@sentry/dotagents-lib';
import type { SkillDefinition } from '../config/schema.js';
import { isPathLike, resolvePathTarget } from '../utils/path.js';
 
export class SkillLoaderError extends Error {
  constructor(message: string, options?: { cause?: unknown }) {
    super(message, options);
    this.name = 'SkillLoaderError';
  }
}
 
/**
 * A loaded skill with its source entry path.
 */
export interface LoadedSkill {
  skill: SkillDefinition;
  /** The entry name (file or directory) where the skill was found */
  entry: string;
}
 
/** Cache for loaded skills directories to avoid repeated disk reads */
const skillsCache = new Map<string, Map<string, LoadedSkill>>();
 
/**
 * Conventional skill directories, checked in priority order.
 *
 * Skills are discovered from these directories in order:
 * 1. .warden/skills - Repo-local generated skills
 * 2. .agents/skills - Primary authored skills
 * 3. .claude/skills - Backup (matches Claude Code convention)
 *
 * Skills follow the agentskills.io specification:
 * - skill-name/SKILL.md (directory with SKILL.md inside - preferred)
 * - skill-name.md (flat markdown with SKILL.md frontmatter format)
 *
 * When a skill name exists in multiple directories, the first one found wins.
 */
export const SKILL_DIRECTORIES = [
  '.warden/skills',
  '.agents/skills',
  '.claude/skills',
] as const;
 
/**
 * Package-native Warden skills, resolved by name without installation.
 *
 * Repo-local conventional skills take precedence over these defaults so teams
 * can override built-ins with their own policy.
 */
export const BUILTIN_SKILL_DIRECTORIES = [
  'src/builtin-skills',
] as const;
 
/**
 * Conventional agent directories, checked in priority order.
 *
 * Agents are discovered from these directories in order:
 * 1. .agents/agents - Primary (recommended)
 * 2. .claude/agents - Backup (matches Claude Code convention)
 * 3. .warden/agents - Legacy
 *
 * Agents use the same format as skills but with AGENT.md marker files.
 */
export const AGENT_DIRECTORIES = [
  '.agents/agents',
  '.claude/agents',
  '.warden/agents',
] as const;
 
/** Marker filename for agent definitions */
export const AGENT_MARKER_FILE = 'AGENT.md';
 
/**
 * Resolve a skill path, handling absolute paths, tilde expansion, and relative paths.
 */
export function resolveSkillPath(nameOrPath: string, repoRoot?: string): string {
  return resolvePathTarget(nameOrPath, repoRoot);
}
 
/**
 * Resolve the package root from source or compiled dist locations.
 */
function resolvePackageRoot(): string {
  const __filename = fileURLToPath(import.meta.url);
  return join(dirname(__filename), '..', '..');
}
 
/**
 * Return true when a skill name resolves to a package-native built-in skill.
 */
export function isBuiltinSkillName(name: string): boolean {
  Iif (isPathLike(name)) {
    return false;
  }
 
  const packageRoot = resolvePackageRoot();
  for (const dir of BUILTIN_SKILL_DIRECTORIES) {
    const dirPath = join(packageRoot, dir);
 
    if (
      existsSync(join(dirPath, name, 'SKILL.md')) ||
      existsSync(join(dirPath, `${name}.md`))
    ) {
      return true;
    }
  }
 
  return false;
}
 
/**
 * Clear the skills cache. Useful for testing or when skills may have changed.
 */
export function clearSkillsCache(): void {
  skillsCache.clear();
}
 
/**
 * Options for loading a skill from markdown.
 */
export interface LoadSkillFromMarkdownOptions {
  /** Callback for reporting warnings (e.g., invalid tool names) */
  onWarning?: (message: string) => void;
}
 
/**
 * Extract the markdown body that follows the SKILL.md YAML frontmatter.
 * Returns the empty string if the file lacks a frontmatter block.
 */
function extractBody(content: string): string {
  const match = content.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?([\s\S]*)$/);
  return match?.[1] ?? '';
}
 
/**
 * Load a skill from a SKILL.md file (agentskills.io format).
 *
 * Frontmatter parsing and `allowed-tools` interpretation are delegated to
 * `@sentry/dotagents-lib`; this wrapper attaches warden-specific fields
 * (`prompt` body, `rootDir`, `tools.allowed`) and translates lib errors to
 * `SkillLoaderError` for callers that catch on warden's error type.
 */
export async function loadSkillFromMarkdown(
  filePath: string,
  options?: LoadSkillFromMarkdownOptions
): Promise<SkillDefinition> {
  let meta;
  try {
    meta = await loadSkillMd(filePath, { onWarning: options?.onWarning });
  } catch (err) {
    Eif (err instanceof SkillLoadError) {
      throw new SkillLoaderError(err.message, { cause: err });
    }
    throw err;
  }
 
  // Lib doesn't return the body; re-read for the markdown content. Cheap —
  // the OS file cache catches the second read.
  const content = await readFile(filePath, 'utf-8');
  const body = extractBody(content);
 
  return {
    name: meta.name,
    description: meta.description,
    prompt: body.trim(),
    tools: meta.allowedTools !== undefined ? { allowed: meta.allowedTools } : undefined,
    rootDir: dirname(filePath),
  };
}
 
/**
 * Load a skill from a file (agentskills.io format .md files).
 */
export async function loadSkillFromFile(filePath: string): Promise<SkillDefinition> {
  const ext = extname(filePath).toLowerCase();
 
  if (ext === '.md') {
    return loadSkillFromMarkdown(filePath);
  }
 
  throw new SkillLoaderError(`Unsupported skill file: ${filePath}. Skills must be .md files following the agentskills.io format.`);
}
 
/**
 * Options for loading skills from a directory.
 */
export interface LoadSkillsOptions {
  /** Callback for reporting warnings (e.g., failed skill loading) */
  onWarning?: (message: string) => void;
  /** Marker filename for directory-format entries. Default: 'SKILL.md' */
  markerFile?: string;
}
 
/**
 * Load all skills from a directory.
 *
 * Supports the agentskills.io specification:
 * - skill-name/SKILL.md (directory with SKILL.md inside - preferred)
 * - skill-name.md (flat markdown with SKILL.md frontmatter format)
 *
 * Results are cached to avoid repeated disk reads.
 *
 * @returns Map of skill name to LoadedSkill (includes entry path for tracking)
 */
export async function loadSkillsFromDirectory(
  dirPath: string,
  options?: LoadSkillsOptions
): Promise<Map<string, LoadedSkill>> {
  const markerFile = options?.markerFile ?? 'SKILL.md';
  const cacheKey = `${dirPath}:${markerFile}`;
 
  // Check cache first
  const cached = skillsCache.get(cacheKey);
  if (cached) {
    return cached;
  }
 
  const skills = new Map<string, LoadedSkill>();
 
  let entries: string[];
  try {
    entries = await readdir(dirPath);
  } catch {
    skillsCache.set(cacheKey, skills);
    return skills;
  }
 
  // Process entries following agentskills.io format priority:
  // 1. Directories with marker file (preferred)
  // 2. Flat .md files with valid frontmatter
  for (const entry of entries) {
    const entryPath = join(dirPath, entry);
 
    // Check for agentskills.io format: entry-name/{markerFile} (preferred)
    const markerPath = join(entryPath, markerFile);
    if (existsSync(markerPath)) {
      try {
        const skill = await loadSkillFromMarkdown(markerPath, { onWarning: options?.onWarning });
        skills.set(skill.name, { skill, entry });
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        options?.onWarning?.(`Failed to load skill from ${markerPath}: ${message}`);
      }
      continue;
    }
 
    // Check for flat .md files (with frontmatter format)
    if (entry.endsWith('.md')) {
      try {
        const skill = await loadSkillFromMarkdown(entryPath, { onWarning: options?.onWarning });
        skills.set(skill.name, { skill, entry });
      } catch (error) {
        // Skip files without YAML frontmatter (e.g., README.md, documentation)
        // but warn about files that have frontmatter but are malformed.
        // Lib's loadSkillMd throws "No YAML frontmatter in <path>" for the
        // no-frontmatter case; everything else (missing required field,
        // unparseable YAML) is a real malformation worth reporting.
        const message = error instanceof Error ? error.message : String(error);
        if (!message.includes('No YAML frontmatter')) {
          options?.onWarning?.(`Failed to load skill from ${entry}: ${message}`);
        }
      }
    }
  }
 
  skillsCache.set(cacheKey, skills);
  return skills;
}
 
/**
 * A discovered skill with source metadata.
 */
export interface DiscoveredSkill {
  skill: SkillDefinition;
  /** Source label where the skill was found (e.g., "./.agents/skills" or "built-in") */
  directory: string;
  /** Full path to the skill */
  path: string;
}
 
/**
 * Discover all entries (skills or agents) from conventional directories.
 * Scans directories in order; first occurrence of a name wins.
 */
async function discoverFromDirectories(
  rootDir: string,
  directories: readonly string[],
  options?: LoadSkillsOptions,
  sourceLabel?: (dir: string) => string,
): Promise<Map<string, DiscoveredSkill>> {
  const result = new Map<string, DiscoveredSkill>();
 
  for (const dir of directories) {
    const dirPath = join(rootDir, dir);
    if (!existsSync(dirPath)) continue;
 
    const loaded = await loadSkillsFromDirectory(dirPath, options);
    for (const [name, entry] of loaded) {
      Eif (!result.has(name)) {
        result.set(name, {
          skill: entry.skill,
          directory: sourceLabel ? sourceLabel(dir) : `./${dir}`,
          path: join(dirPath, entry.entry),
        });
      }
    }
  }
 
  return result;
}
 
async function discoverBuiltinSkills(options?: LoadSkillsOptions): Promise<Map<string, DiscoveredSkill>> {
  return discoverFromDirectories(
    resolvePackageRoot(),
    BUILTIN_SKILL_DIRECTORIES,
    options,
    () => 'built-in',
  );
}
 
/**
 * Discover all available skills from conventional directories.
 *
 * @param repoRoot - Repository root path for finding skills
 * @param options - Options for skill loading (e.g., warning callback)
 * @returns Map of skill name to discovered skill info
 */
export async function discoverAllSkills(
  repoRoot?: string,
  options?: LoadSkillsOptions
): Promise<Map<string, DiscoveredSkill>> {
  const discovered = repoRoot
    ? await discoverFromDirectories(repoRoot, SKILL_DIRECTORIES, options)
    : new Map<string, DiscoveredSkill>();
 
  const builtin = await discoverBuiltinSkills(options);
  for (const [name, entry] of builtin) {
    Eif (!discovered.has(name)) {
      discovered.set(name, entry);
    }
  }
 
  return discovered;
}
 
export interface ResolveSkillOptions {
  /** Remote repository reference (e.g., "owner/repo" or "owner/repo@sha") */
  remote?: string;
  /** Skip network operations - only use cache for remote skills */
  offline?: boolean;
}
 
/** Configuration for the shared resolve logic */
interface ResolveConfig {
  markerFile: string;
  directories: readonly string[];
  builtinDirectories?: readonly string[];
  label: string;
  kind: 'skill' | 'agent';
}
 
/**
 * Resolve a skill or agent by name or path.
 *
 * Resolution order:
 * 1. Remote repository (if remote option is set)
 * 2. Direct path (if nameOrPath contains / or \ or starts with .)
 *    - Directory: load marker file from it
 *    - File: load the .md file directly
 * 3. Conventional directories (if repoRoot provided)
 * 4. Package-native built-in directories (skills only)
 */
async function resolveEntry(
  nameOrPath: string,
  repoRoot: string | undefined,
  options: ResolveSkillOptions | undefined,
  config: ResolveConfig,
): Promise<SkillDefinition> {
  const { remote, offline } = options ?? {};
 
  // 1. Remote repository resolution takes priority when specified
  Iif (remote) {
    // Dynamic import to avoid circular dependencies
    const { resolveRemoteSkill, resolveRemoteAgent } = await import('./remote.js');
    const resolver = config.kind === 'skill' ? resolveRemoteSkill : resolveRemoteAgent;
    return resolver(remote, nameOrPath, { offline });
  }
 
  // 2. Direct path resolution
  if (isPathLike(nameOrPath)) {
    const resolvedPath = resolveSkillPath(nameOrPath, repoRoot);
 
    const markerPath = join(resolvedPath, config.markerFile);
    if (existsSync(markerPath)) {
      return loadSkillFromMarkdown(markerPath);
    }
 
    if (existsSync(resolvedPath)) {
      return loadSkillFromFile(resolvedPath);
    }
 
    throw new SkillLoaderError(`${config.label} not found at path: ${nameOrPath}`);
  }
 
  // 3. Check conventional directories
  if (repoRoot) {
    for (const dir of config.directories) {
      const dirPath = join(repoRoot, dir);
 
      const markerPath = join(dirPath, nameOrPath, config.markerFile);
      if (existsSync(markerPath)) {
        return loadSkillFromMarkdown(markerPath);
      }
 
      const mdPath = join(dirPath, `${nameOrPath}.md`);
      Iif (existsSync(mdPath)) {
        return loadSkillFromMarkdown(mdPath);
      }
    }
  }
 
  if (config.builtinDirectories) {
    const packageRoot = resolvePackageRoot();
    for (const dir of config.builtinDirectories) {
      const dirPath = join(packageRoot, dir);
 
      const markerPath = join(dirPath, nameOrPath, config.markerFile);
      if (existsSync(markerPath)) {
        return loadSkillFromMarkdown(markerPath);
      }
 
      const mdPath = join(dirPath, `${nameOrPath}.md`);
      Iif (existsSync(mdPath)) {
        return loadSkillFromMarkdown(mdPath);
      }
    }
  }
 
  throw new SkillLoaderError(`${config.label} not found: ${nameOrPath}`);
}
 
const SKILL_RESOLVE_CONFIG: ResolveConfig = {
  markerFile: 'SKILL.md',
  directories: SKILL_DIRECTORIES,
  builtinDirectories: BUILTIN_SKILL_DIRECTORIES,
  label: 'Skill',
  kind: 'skill',
};
 
const AGENT_RESOLVE_CONFIG: ResolveConfig = {
  markerFile: AGENT_MARKER_FILE,
  directories: AGENT_DIRECTORIES,
  label: 'Agent',
  kind: 'agent',
};
 
/**
 * Resolve a skill by name or path.
 *
 * Resolution order:
 * 1. Remote repository (if remote option is set)
 * 2. Direct path (if nameOrPath contains / or \ or starts with .)
 *    - Directory: load SKILL.md from it
 *    - File: load the .md file directly
 * 3. Conventional directories (if repoRoot provided)
 *    - .warden/skills/{name}/SKILL.md or .warden/skills/{name}.md
 *    - .agents/skills/{name}/SKILL.md or .agents/skills/{name}.md
 *    - .claude/skills/{name}/SKILL.md or .claude/skills/{name}.md
 * 4. Package-native built-in skills
 *    - src/builtin-skills/{name}/SKILL.md or src/builtin-skills/{name}.md
 */
export async function resolveSkillAsync(
  nameOrPath: string,
  repoRoot?: string,
  options?: ResolveSkillOptions
): Promise<SkillDefinition> {
  return resolveEntry(nameOrPath, repoRoot, options, SKILL_RESOLVE_CONFIG);
}
 
// =============================================================================
// Agent Discovery (parallel to skills, using AGENT.md marker files)
// =============================================================================
 
/** An agent definition uses the same shape as a skill definition */
export type AgentDefinition = SkillDefinition;
 
/** A loaded agent with its source entry path */
export type LoadedAgent = LoadedSkill;
 
/** A discovered agent with source metadata */
export type DiscoveredAgent = DiscoveredSkill;
 
/**
 * Discover all available agents from conventional directories.
 *
 * @param repoRoot - Repository root path for finding agents
 * @param options - Options for loading (e.g., warning callback)
 * @returns Map of agent name to discovered agent info
 */
export async function discoverAllAgents(
  repoRoot?: string,
  options?: LoadSkillsOptions
): Promise<Map<string, DiscoveredAgent>> {
  if (!repoRoot) {
    return new Map();
  }
  return discoverFromDirectories(repoRoot, AGENT_DIRECTORIES, {
    ...options,
    markerFile: AGENT_MARKER_FILE,
  });
}
 
/**
 * Resolve an agent by name or path.
 *
 * Resolution order:
 * 1. Remote repository (if remote option is set)
 * 2. Direct path (if nameOrPath contains / or \ or starts with .)
 *    - Directory: load AGENT.md from it
 *    - File: load the .md file directly
 * 3. Conventional directories (if repoRoot provided)
 *    - .agents/agents/{name}/AGENT.md or .agents/agents/{name}.md
 *    - .claude/agents/{name}/AGENT.md or .claude/agents/{name}.md
 *    - .warden/agents/{name}/AGENT.md or .warden/agents/{name}.md
 */
export async function resolveAgentAsync(
  nameOrPath: string,
  repoRoot?: string,
  options?: ResolveSkillOptions
): Promise<AgentDefinition> {
  return resolveEntry(nameOrPath, repoRoot, options, AGENT_RESOLVE_CONFIG);
}