@mastra/core
Version:
1 lines • 222 kB
Source Map (JSON)
{"version":3,"file":"workspace-skills-CKBkzxPb.cjs","names":["fs","FileNotFoundError","fs","parse","stringify"],"sources":["../src/workspace/filesystem/fs-utils.ts","../src/workspace/glob.ts","../src/workspace/search/bm25.ts","../src/workspace/search/search-engine.ts","../src/workspace/skills/local-skill-source.ts","../../_internal-core/dist/frontmatter/index.js","../src/workspace/skills/schemas.ts","../src/workspace/skills/workspace-skills.ts"],"sourcesContent":["/**\n * Shared filesystem utilities for LocalFilesystem and LocalSkillSource.\n *\n * These utilities provide consistent implementations for common fs operations.\n */\n\nimport * as fs from 'node:fs/promises';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\n\nimport { FileNotFoundError } from '../errors';\n\n// =============================================================================\n// Tilde Expansion\n// =============================================================================\n\n/**\n * Expand a leading `~` or `~/` to the user's home directory.\n * Shell commands handle this automatically, but Node.js path APIs do not.\n */\nexport function expandTilde(p: string): string {\n if (p === '~') return os.homedir();\n if (p.startsWith('~/') || p.startsWith('~\\\\')) {\n return path.join(os.homedir(), p.slice(2));\n }\n return p;\n}\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Full file stat information.\n * Used by both WorkspaceFilesystem and SkillSource.\n */\nexport interface FsStatResult {\n /** File or directory name */\n name: string;\n /** 'file' or 'directory' */\n type: 'file' | 'directory';\n /** Size in bytes (0 for directories) */\n size: number;\n /** Creation time */\n createdAt: Date;\n /** Last modification time */\n modifiedAt: Date;\n /** MIME type (for files) */\n mimeType?: string;\n}\n\n// =============================================================================\n// Error Utilities\n// =============================================================================\n\n/**\n * Check if an error is an ENOENT (file not found) error.\n */\nexport function isEnoentError(error: unknown): error is NodeJS.ErrnoException & { code: 'ENOENT' } {\n return (\n error !== null && typeof error === 'object' && 'code' in error && (error as NodeJS.ErrnoException).code === 'ENOENT'\n );\n}\n\n/**\n * Check if an error is an ENOTDIR error (a path component is not a directory,\n * e.g. treating a file as a directory). Like ENOENT, this means the requested\n * target cannot be resolved.\n */\nexport function isEnotdirError(error: unknown): error is NodeJS.ErrnoException & { code: 'ENOTDIR' } {\n return (\n error !== null &&\n typeof error === 'object' &&\n 'code' in error &&\n (error as NodeJS.ErrnoException).code === 'ENOTDIR'\n );\n}\n\n/**\n * Check if an error is an EEXIST (file exists) error.\n */\nexport function isEexistError(error: unknown): error is NodeJS.ErrnoException & { code: 'EEXIST' } {\n return (\n error !== null && typeof error === 'object' && 'code' in error && (error as NodeJS.ErrnoException).code === 'EEXIST'\n );\n}\n\n// =============================================================================\n// MIME Type Detection\n// =============================================================================\n\nconst MIME_TYPES: Record<string, string> = {\n // Text\n txt: 'text/plain',\n html: 'text/html',\n htm: 'text/html',\n css: 'text/css',\n csv: 'text/csv',\n md: 'text/markdown',\n // Code\n js: 'application/javascript',\n mjs: 'application/javascript',\n ts: 'application/typescript',\n tsx: 'application/typescript',\n jsx: 'application/javascript',\n json: 'application/json',\n xml: 'application/xml',\n yaml: 'text/yaml',\n yml: 'text/yaml',\n // Programming languages\n py: 'text/x-python',\n rb: 'text/x-ruby',\n go: 'text/x-go',\n rs: 'text/x-rust',\n java: 'text/x-java',\n c: 'text/x-c',\n cpp: 'text/x-c++',\n h: 'text/x-c',\n hpp: 'text/x-c++',\n sh: 'text/x-sh',\n bash: 'text/x-sh',\n zsh: 'text/x-sh',\n // Config\n toml: 'text/toml',\n ini: 'text/plain',\n env: 'text/plain',\n // Database/Query\n sql: 'text/x-sql',\n graphql: 'application/graphql',\n gql: 'application/graphql',\n // Frameworks\n vue: 'text/x-vue',\n svelte: 'text/x-svelte',\n // Web styles\n scss: 'text/x-scss',\n sass: 'text/x-sass',\n less: 'text/x-less',\n // Additional languages\n php: 'application/x-php',\n swift: 'text/x-swift',\n kt: 'text/x-kotlin',\n kts: 'text/x-kotlin',\n dart: 'application/dart',\n lua: 'text/x-lua',\n r: 'text/x-r',\n tf: 'text/x-terraform',\n tfvars: 'text/x-terraform',\n mdx: 'text/markdown',\n sas: 'text/plain',\n log: 'text/plain',\n jsonl: 'application/jsonl',\n // Images\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n svg: 'image/svg+xml',\n webp: 'image/webp',\n ico: 'image/x-icon',\n bmp: 'image/bmp',\n tiff: 'image/tiff',\n tif: 'image/tiff',\n heic: 'image/heic',\n heif: 'image/heif',\n avif: 'image/avif',\n // Documents\n pdf: 'application/pdf',\n // Audio\n mp3: 'audio/mpeg',\n wav: 'audio/wav',\n ogg: 'audio/ogg',\n flac: 'audio/flac',\n m4a: 'audio/mp4',\n aac: 'audio/aac',\n // Video\n mp4: 'video/mp4',\n webm: 'video/webm',\n mov: 'video/quicktime',\n avi: 'video/x-msvideo',\n mkv: 'video/x-matroska',\n // Archives\n zip: 'application/zip',\n tar: 'application/x-tar',\n gz: 'application/gzip',\n tgz: 'application/gzip',\n bz2: 'application/x-bzip2',\n '7z': 'application/x-7z-compressed',\n rar: 'application/vnd.rar',\n // Executables / binaries\n exe: 'application/vnd.microsoft.portable-executable',\n dll: 'application/vnd.microsoft.portable-executable',\n so: 'application/x-sharedlib',\n dylib: 'application/x-sharedlib',\n bin: 'application/x-binary',\n dat: 'application/x-binary',\n // Disk images / packages\n dmg: 'application/x-apple-diskimage',\n iso: 'application/x-iso9660-image',\n deb: 'application/vnd.debian.binary-package',\n rpm: 'application/x-rpm',\n // Office documents\n doc: 'application/msword',\n docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n xls: 'application/vnd.ms-excel',\n xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n ppt: 'application/vnd.ms-powerpoint',\n pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n // Fonts\n ttf: 'font/ttf',\n otf: 'font/otf',\n woff: 'font/woff',\n woff2: 'font/woff2',\n // Compiled code\n wasm: 'application/wasm',\n class: 'application/java-vm',\n pyc: 'application/x-python-code',\n};\n\n/**\n * Get MIME type for a filename based on extension.\n */\nexport function getMimeType(filename: string): string {\n const ext = path.extname(filename).slice(1).toLowerCase();\n // Read via a local so inherited Object.prototype members (e.g. an extension of\n // `constructor` or `__proto__`) never leak a non-string; only own string values map.\n const mimeType = Object.hasOwn(MIME_TYPES, ext) ? MIME_TYPES[ext] : undefined;\n return typeof mimeType === 'string' ? mimeType : 'application/octet-stream';\n}\n\n/**\n * Extensions that should be treated as text files.\n */\nconst TEXT_EXTENSIONS = new Set([\n '.md',\n '.txt',\n '.json',\n '.yaml',\n '.yml',\n '.js',\n '.mjs',\n '.ts',\n '.tsx',\n '.jsx',\n '.py',\n '.rb',\n '.go',\n '.rs',\n '.java',\n '.c',\n '.cpp',\n '.h',\n '.hpp',\n '.sh',\n '.bash',\n '.zsh',\n '.html',\n '.htm',\n '.css',\n '.xml',\n '.toml',\n '.ini',\n '.env',\n '.csv',\n '.sql',\n '.graphql',\n '.gql',\n '.vue',\n '.svg',\n '.mdx',\n '.scss',\n '.sass',\n '.less',\n '.svelte',\n '.php',\n '.swift',\n '.kt',\n '.kts',\n '.dart',\n '.lua',\n '.r',\n '.tf',\n '.tfvars',\n '.sas',\n '.log',\n '.jsonl',\n // Templates\n '.erb',\n '.hbs',\n '.handlebars',\n '.haml',\n '.slim',\n '.ejs',\n '.mustache',\n '.jinja',\n '.j2',\n '.twig',\n '.cshtml',\n // Build, package and lock files\n '.gemspec',\n '.lock',\n '.proto',\n '.gradle',\n '.properties',\n]);\n\n/**\n * Normalize a text extension to the internal form: lowercased and dot-prefixed.\n * e.g. `SAS` -> `.sas`, `.LOG` -> `.log`.\n */\nexport function normalizeTextExtension(ext: string): string {\n const lower = ext.trim().toLowerCase();\n return lower.startsWith('.') ? lower : `.${lower}`;\n}\n\n/**\n * Check if a file should be treated as text based on extension.\n *\n * @param filename - The filename (or path) to check.\n * @param extraExtensions - Optional set of additional normalized extensions\n * (lowercased, dot-prefixed) to treat as text, in addition to the built-in set.\n */\nexport function isTextFile(filename: string, extraExtensions?: ReadonlySet<string>): boolean {\n const ext = path.extname(filename).toLowerCase();\n return TEXT_EXTENSIONS.has(ext) || (extraExtensions?.has(ext) ?? false);\n}\n\n// =============================================================================\n// Path Resolution\n// =============================================================================\n\n/**\n * Resolve a path against a base directory.\n *\n * - Tilde (`~`) is expanded to the user's home directory.\n * - Absolute paths are normalized and returned as-is.\n * - Relative paths (including `../`) are resolved against `basePath`.\n *\n * @param basePath - The absolute base path to resolve against\n * @param filePath - The path to resolve\n * @returns The absolute resolved path\n */\nexport function resolveToBasePath(basePath: string, filePath: string): string {\n const expanded = expandTilde(filePath);\n if (path.isAbsolute(expanded)) {\n return path.normalize(expanded);\n }\n return path.resolve(basePath, expanded);\n}\n\n// =============================================================================\n// Filesystem Operations\n// =============================================================================\n\n/**\n * Check if a path exists.\n * Never throws - returns false on any error.\n *\n * @param absolutePath - The absolute path to check\n * @returns true if path exists and is accessible\n */\nexport async function fsExists(absolutePath: string): Promise<boolean> {\n try {\n await fs.access(absolutePath);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Get file/directory stats.\n * Throws FileNotFoundError if path doesn't exist.\n *\n * @param absolutePath - The absolute path to stat\n * @param userPath - The user-facing path for error messages\n * @returns File stat information\n * @throws {FileNotFoundError} if path doesn't exist\n */\nexport async function fsStat(absolutePath: string, userPath: string): Promise<FsStatResult> {\n try {\n const stats = await fs.stat(absolutePath);\n return {\n name: path.basename(absolutePath),\n type: stats.isDirectory() ? 'directory' : 'file',\n size: stats.size,\n createdAt: stats.birthtime,\n modifiedAt: stats.mtime,\n mimeType: stats.isFile() ? getMimeType(absolutePath) : undefined,\n };\n } catch (error: unknown) {\n if (isEnoentError(error)) {\n throw new FileNotFoundError(userPath);\n }\n throw error;\n }\n}\n","/**\n * Glob Pattern Utilities\n *\n * Shared glob pattern matching for workspace operations.\n * Uses picomatch for battle-tested glob support including\n * brace expansion, character classes, negation, and `**`.\n */\n\nimport picomatch from 'picomatch';\n\n// =============================================================================\n// Glob Metacharacter Detection\n// =============================================================================\n\n/** Characters that indicate a glob pattern (not a plain path) */\nconst GLOB_CHARS = /[*?{}[\\]]/;\n\n/**\n * Check if a string contains glob metacharacters.\n *\n * @example\n * isGlobPattern('/docs') // false\n * isGlobPattern('/docs/**\\/*.md') // true\n * isGlobPattern('*.ts') // true\n * isGlobPattern('/src/{a,b}') // true\n */\nexport function isGlobPattern(input: string): boolean {\n return GLOB_CHARS.test(input);\n}\n\n// =============================================================================\n// Glob Base Extraction\n// =============================================================================\n\n/**\n * Extract the static directory prefix before the first glob metacharacter.\n * Returns the deepest non-glob ancestor directory.\n *\n * @example\n * extractGlobBase('docs/**\\/*.md') // 'docs'\n * extractGlobBase('**\\/*.md') // '.'\n * extractGlobBase('src/*.ts') // 'src'\n * extractGlobBase('exact/path') // 'exact/path'\n */\nexport function extractGlobBase(pattern: string): string {\n // Find position of first glob metacharacter\n const firstMeta = pattern.search(GLOB_CHARS);\n\n if (firstMeta === -1) {\n // No glob chars — return the pattern as-is (it's a plain path)\n return pattern;\n }\n\n // Get the portion before the first metacharacter\n const prefix = pattern.slice(0, firstMeta);\n\n // Walk back to the last directory separator\n const lastSlash = prefix.lastIndexOf('/');\n\n if (lastSlash <= 0) {\n // No slash or only root slash — base is workspace root\n return '.';\n }\n\n return prefix.slice(0, lastSlash);\n}\n\n// =============================================================================\n// Glob Matcher\n// =============================================================================\n\n/** A compiled matcher function: returns true if a path matches */\nexport type GlobMatcher = (path: string) => boolean;\n\nexport interface GlobMatcherOptions {\n /** Match dotfiles (default: false) */\n dot?: boolean;\n}\n\n/**\n * Strip leading './' or '/' from a path for picomatch matching.\n * picomatch does not match paths with these prefixes, so both\n * patterns and test paths must be normalized before matching.\n *\n * This only affects matching — filesystem paths should keep their\n * original form for correct resolution with contained/uncontained modes.\n */\nfunction normalizeForMatch(input: string): string {\n if (input.startsWith('./')) return input.slice(2);\n if (input.startsWith('/')) return input.slice(1);\n return input;\n}\n\n/**\n * Compile glob pattern(s) into a reusable matcher function.\n * The matcher tests paths using workspace-style forward slashes.\n *\n * Automatically normalizes leading './' and '/' from both patterns\n * and test paths, since picomatch does not match these prefixes.\n *\n * @example\n * const match = createGlobMatcher('**\\/*.ts');\n * match('src/index.ts') // true\n * match('src/style.css') // false\n *\n * const multi = createGlobMatcher(['**\\/*.ts', '**\\/*.tsx']);\n * multi('App.tsx') // true\n */\nexport function createGlobMatcher(patterns: string | string[], options?: GlobMatcherOptions): GlobMatcher {\n const patternArray = (Array.isArray(patterns) ? patterns : [patterns]).map(normalizeForMatch);\n const matcher = picomatch(patternArray, {\n posix: true,\n dot: options?.dot ?? false,\n });\n return (path: string) => matcher(normalizeForMatch(path));\n}\n\n/**\n * One-off convenience: test if a path matches a glob pattern.\n *\n * For repeated matching against the same pattern, prefer createGlobMatcher()\n * to compile once and reuse.\n *\n * @example\n * matchGlob('src/index.ts', '**\\/*.ts') // true\n */\nexport function matchGlob(path: string, pattern: string | string[], options?: GlobMatcherOptions): boolean {\n return createGlobMatcher(pattern, options)(path);\n}\n\n// =============================================================================\n// Path Pattern Resolution\n// =============================================================================\n\n/** A filesystem entry returned by resolvePathPattern */\nexport interface PathEntry {\n path: string;\n type: 'file' | 'directory';\n}\n\n/** Minimal readdir entry — compatible with both FileEntry and SkillSourceEntry */\nexport interface ReaddirEntry {\n name: string;\n type: 'file' | 'directory';\n isSymlink?: boolean;\n}\n\nexport interface ResolvePathOptions {\n /** Match dotfiles (default: false) */\n dot?: boolean;\n /** Maximum directory depth to walk (default: 10) */\n maxDepth?: number;\n}\n\n/**\n * Walk a directory tree recursively, returning all entries (files and directories).\n * Skips symlinked directories to prevent infinite loops.\n */\nasync function walkAll(\n readdir: (dir: string) => Promise<ReaddirEntry[]>,\n dir: string,\n depth: number,\n maxDepth: number,\n): Promise<PathEntry[]> {\n if (depth >= maxDepth) return [];\n try {\n const entries = await readdir(dir);\n const results: PathEntry[] = [];\n for (const entry of entries) {\n if (entry.type === 'directory' && entry.isSymlink) continue;\n const fullPath = dir === '.' || dir === '' ? entry.name : `${dir}/${entry.name}`;\n results.push({ path: fullPath, type: entry.type });\n if (entry.type === 'directory') {\n results.push(...(await walkAll(readdir, fullPath, depth + 1, maxDepth)));\n }\n }\n return results;\n } catch {\n return [];\n }\n}\n\n/**\n * Resolve a path pattern to matching filesystem entries.\n *\n * Handles both plain paths and glob patterns consistently:\n * - Plain paths: determines file vs directory via readdir probe, returns single entry\n * - Glob patterns: walks from the glob base, matches both files and directories\n *\n * @example\n * // Plain paths\n * resolvePathPattern('/docs', readdir) // [{ path: '/docs', type: 'directory' }]\n * resolvePathPattern('/docs/readme.md', readdir) // [{ path: '/docs/readme.md', type: 'file' }]\n *\n * // Glob patterns — matches files and directories\n * resolvePathPattern('/docs/**\\/*.md', readdir) // all .md files under /docs\n * resolvePathPattern('**\\/skills', readdir) // all directories (and files) named 'skills'\n * resolvePathPattern('/skills/**', readdir) // everything under /skills\n */\nexport async function resolvePathPattern(\n pattern: string,\n readdir: (dir: string) => Promise<ReaddirEntry[]>,\n options?: ResolvePathOptions,\n): Promise<PathEntry[]> {\n const maxDepth = options?.maxDepth ?? 10;\n\n // Strip trailing slash for consistent path handling (e.g. '/skills/' → '/skills')\n const normalized = pattern.length > 1 && pattern.endsWith('/') ? pattern.slice(0, -1) : pattern;\n\n if (!isGlobPattern(normalized)) {\n // Plain path — probe with readdir to determine if it's a directory or file\n try {\n await readdir(normalized);\n return [{ path: normalized, type: 'directory' }];\n } catch {\n // readdir failed — treat as a file path (consumer handles non-existence)\n return [{ path: normalized, type: 'file' }];\n }\n }\n\n // Glob pattern — walk from base, match all entries (files and directories)\n const walkRoot = extractGlobBase(normalized);\n const matcher = createGlobMatcher(normalized, { dot: options?.dot ?? false });\n const allEntries = await walkAll(readdir, walkRoot, 0, maxDepth);\n return allEntries.filter(entry => matcher(entry.path));\n}\n","/**\n * BM25 (Best Matching 25) implementation for keyword-based search.\n *\n * BM25 is a probabilistic ranking function used for information retrieval.\n * It ranks documents based on the query terms appearing in each document,\n * taking into account term frequency and document length normalization.\n */\n\nimport type { LineRange } from '../line-utils';\n\n/**\n * BM25 configuration parameters\n */\nexport interface BM25Config {\n /**\n * Controls term frequency saturation.\n * Higher values give more weight to term frequency.\n * Typical range: 1.2 - 2.0\n * @default 1.5\n */\n k1?: number;\n\n /**\n * Controls document length normalization.\n * 0 = no length normalization, 1 = full normalization\n * @default 0.75\n */\n b?: number;\n}\n\n/**\n * Represents a document in the BM25 index\n */\nexport interface BM25Document {\n /** Document identifier */\n id: string;\n /** Document content */\n content: string;\n /** Pre-computed tokens for the document */\n tokens: string[];\n /** Token frequency map */\n termFrequencies: Map<string, number>;\n /** Total number of tokens */\n length: number;\n /** Optional metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Result from a BM25 search\n */\nexport interface BM25SearchResult {\n /** Document identifier */\n id: string;\n /** Document content */\n content: string;\n /** BM25 score (higher is more relevant) */\n score: number;\n /** Optional metadata */\n metadata?: Record<string, unknown>;\n /** Line range where query terms were found (if computed) */\n lineRange?: LineRange;\n}\n\n/**\n * Tokenization options\n */\nexport interface TokenizeOptions {\n /** Convert to lowercase */\n lowercase?: boolean;\n /** Remove punctuation */\n removePunctuation?: boolean;\n /** Minimum token length */\n minLength?: number;\n /** Custom stopwords to remove */\n stopwords?: Set<string>;\n /** Custom split pattern (default: /\\s+/) */\n splitPattern?: RegExp;\n /**\n * Custom tokenizer function that bypasses the built-in pipeline entirely.\n * When provided, all other options (lowercase, removePunctuation, etc.) are ignored.\n * Useful for CJK languages that need morphological analysis or n-gram tokenization.\n *\n * @example\n * ```ts\n * // Character bigram tokenizer for CJK\n * tokenizer: (text) => {\n * const tokens: string[] = [];\n * const normalized = text.toLowerCase();\n * for (let i = 0; i < normalized.length - 1; i++) {\n * const bigram = normalized.slice(i, i + 2).trim();\n * if (bigram.length === 2) tokens.push(bigram);\n * }\n * return tokens;\n * }\n * ```\n */\n tokenizer?: (text: string) => string[];\n}\n\n/**\n * Default English stopwords\n */\nexport const DEFAULT_STOPWORDS = new Set([\n 'a',\n 'an',\n 'and',\n 'are',\n 'as',\n 'at',\n 'be',\n 'by',\n 'for',\n 'from',\n 'has',\n 'he',\n 'in',\n 'is',\n 'it',\n 'its',\n 'of',\n 'on',\n 'or',\n 'that',\n 'the',\n 'to',\n 'was',\n 'were',\n 'will',\n 'with',\n]);\n\n/**\n * Default tokenization options\n */\nconst DEFAULT_TOKENIZE_OPTIONS: Omit<Required<TokenizeOptions>, 'tokenizer'> = {\n lowercase: true,\n removePunctuation: true,\n minLength: 2,\n stopwords: DEFAULT_STOPWORDS,\n splitPattern: /\\s+/,\n};\n\n/**\n * Tokenize text into an array of terms\n */\nexport function tokenize(text: string, options: TokenizeOptions = {}): string[] {\n // If a custom tokenizer is provided, bypass the built-in pipeline entirely\n if (options.tokenizer) {\n return options.tokenizer(text);\n }\n\n const opts = { ...DEFAULT_TOKENIZE_OPTIONS, ...options };\n\n let processed = text;\n\n // Convert to lowercase if enabled\n if (opts.lowercase) {\n processed = processed.toLowerCase();\n }\n\n // Remove punctuation if enabled — use Unicode-aware pattern to preserve\n // non-Latin characters (CJK, Arabic, Thai, etc.). \\p{L} matches any\n // Unicode letter, \\p{N} any Unicode digit, so the negated class strips\n // only characters that are neither letters, digits, underscores, nor\n // whitespace.\n if (opts.removePunctuation) {\n processed = processed.replace(/[^\\p{L}\\p{N}_\\s]/gu, ' ');\n }\n\n // Split into tokens\n const tokens = processed.split(opts.splitPattern).filter(token => {\n // Filter by minimum length\n if (token.length < opts.minLength) {\n return false;\n }\n // Filter stopwords\n if (opts.stopwords?.has(token)) {\n return false;\n }\n return true;\n });\n\n return tokens;\n}\n\n// Re-export line utilities from line-utils.ts (except findLineRange which is defined here)\nexport {\n extractLines,\n extractLinesWithLimit,\n formatWithLineNumbers,\n replaceString,\n StringNotFoundError,\n StringNotUniqueError,\n} from '../line-utils';\n\n/**\n * Find the line range where query terms appear in content.\n * Returns the range spanning from the first to the last line containing any query term.\n *\n * @param content - The document content\n * @param queryTerms - Tokenized query terms to find\n * @param options - Tokenization options (should match indexing options)\n * @returns LineRange if terms found, undefined otherwise\n */\nexport function findLineRange(\n content: string,\n queryTerms: string[],\n options: TokenizeOptions = {},\n): LineRange | undefined {\n if (queryTerms.length === 0) return undefined;\n\n const lines = content.split('\\n');\n\n // Default tokenize options for matching\n const defaultOpts = { lowercase: true, removePunctuation: true, minLength: 2 };\n const opts = { ...defaultOpts, ...options };\n\n // Normalize query terms the same way line tokens are normalized; a custom tokenizer owns normalization\n const lowercase = !opts.tokenizer && opts.lowercase;\n const normalizedTerms = new Set(queryTerms.map(t => (lowercase ? t.toLowerCase() : t)));\n\n let firstMatchLine: number | undefined;\n let lastMatchLine: number | undefined;\n\n for (let i = 0; i < lines.length; i++) {\n const lineTokens = tokenize(lines[i]!, options);\n\n // Check if any query term appears in this line\n for (const token of lineTokens) {\n if (normalizedTerms.has(token)) {\n const lineNum = i + 1; // 1-indexed\n if (firstMatchLine === undefined) {\n firstMatchLine = lineNum;\n }\n lastMatchLine = lineNum;\n break; // Found a match on this line, move to next line\n }\n }\n }\n\n if (firstMatchLine !== undefined && lastMatchLine !== undefined) {\n return { start: firstMatchLine, end: lastMatchLine };\n }\n\n return undefined;\n}\n\n/**\n * Compute term frequencies for a list of tokens\n */\nfunction computeTermFrequencies(tokens: string[]): Map<string, number> {\n const frequencies = new Map<string, number>();\n for (const token of tokens) {\n frequencies.set(token, (frequencies.get(token) || 0) + 1);\n }\n return frequencies;\n}\n\n/**\n * BM25 Index for keyword-based document retrieval\n */\nexport class BM25Index {\n /** BM25 k1 parameter */\n readonly k1: number;\n /** BM25 b parameter */\n readonly b: number;\n\n /** Documents in the index */\n #documents: Map<string, BM25Document> = new Map();\n /** Inverted index: term -> document IDs containing the term */\n #invertedIndex: Map<string, Set<string>> = new Map();\n /** Document frequency: term -> number of documents containing the term */\n #documentFrequency: Map<string, number> = new Map();\n /** Average document length */\n #avgDocLength: number = 0;\n /** Total number of documents */\n #docCount: number = 0;\n /** Tokenization options */\n #tokenizeOptions: TokenizeOptions;\n\n constructor(config: BM25Config = {}, tokenizeOptions: TokenizeOptions = {}) {\n this.k1 = config.k1 ?? 1.5;\n this.b = config.b ?? 0.75;\n this.#tokenizeOptions = tokenizeOptions;\n }\n\n /**\n * Add a document to the index\n */\n add(id: string, content: string, metadata?: Record<string, unknown>): void {\n // Remove existing document if it exists\n if (this.#documents.has(id)) {\n this.remove(id);\n }\n\n const tokens = tokenize(content, this.#tokenizeOptions);\n const termFrequencies = computeTermFrequencies(tokens);\n\n const doc: BM25Document = {\n id,\n content,\n tokens,\n termFrequencies,\n length: tokens.length,\n metadata,\n };\n\n this.#documents.set(id, doc);\n this.#docCount++;\n\n // Update inverted index and document frequency\n for (const term of termFrequencies.keys()) {\n if (!this.#invertedIndex.has(term)) {\n this.#invertedIndex.set(term, new Set());\n }\n this.#invertedIndex.get(term)!.add(id);\n this.#documentFrequency.set(term, (this.#documentFrequency.get(term) || 0) + 1);\n }\n\n // Update average document length\n this.#updateAvgDocLength();\n }\n\n /**\n * Remove a document from the index\n */\n remove(id: string): boolean {\n const doc = this.#documents.get(id);\n if (!doc) {\n return false;\n }\n\n // Update inverted index and document frequency\n for (const term of doc.termFrequencies.keys()) {\n const docIds = this.#invertedIndex.get(term);\n if (docIds) {\n docIds.delete(id);\n if (docIds.size === 0) {\n this.#invertedIndex.delete(term);\n this.#documentFrequency.delete(term);\n } else {\n this.#documentFrequency.set(term, (this.#documentFrequency.get(term) || 1) - 1);\n }\n }\n }\n\n this.#documents.delete(id);\n this.#docCount--;\n\n // Update average document length\n this.#updateAvgDocLength();\n\n return true;\n }\n\n /**\n * Clear all documents from the index\n */\n clear(): void {\n this.#documents.clear();\n this.#invertedIndex.clear();\n this.#documentFrequency.clear();\n this.#docCount = 0;\n this.#avgDocLength = 0;\n }\n\n /**\n * Search for documents matching the query\n */\n search(query: string, topK: number = 10, minScore: number = 0): BM25SearchResult[] {\n const queryTokens = tokenize(query, this.#tokenizeOptions);\n\n if (queryTokens.length === 0 || this.#docCount === 0) {\n return [];\n }\n\n const scores = new Map<string, number>();\n\n // Calculate BM25 scores for each document\n for (const queryTerm of queryTokens) {\n const docIds = this.#invertedIndex.get(queryTerm);\n if (!docIds) {\n continue;\n }\n\n const df = this.#documentFrequency.get(queryTerm) || 0;\n const idf = this.#computeIDF(df);\n\n for (const docId of docIds) {\n const doc = this.#documents.get(docId)!;\n const tf = doc.termFrequencies.get(queryTerm) || 0;\n const termScore = this.#computeTermScore(tf, doc.length, idf);\n\n scores.set(docId, (scores.get(docId) || 0) + termScore);\n }\n }\n\n // Sort by score and return top K results\n const results: BM25SearchResult[] = [];\n\n for (const [docId, score] of scores.entries()) {\n if (score >= minScore) {\n const doc = this.#documents.get(docId)!;\n results.push({\n id: docId,\n content: doc.content,\n score,\n metadata: doc.metadata,\n });\n }\n }\n\n // Sort by score descending\n results.sort((a, b) => b.score - a.score);\n\n return results.slice(0, topK);\n }\n\n /**\n * Get a document by ID\n */\n get(id: string): BM25Document | undefined {\n return this.#documents.get(id);\n }\n\n /**\n * Check if a document exists in the index\n */\n has(id: string): boolean {\n return this.#documents.has(id);\n }\n\n /**\n * Get the number of documents in the index\n */\n get size(): number {\n return this.#docCount;\n }\n\n /**\n * Get all document IDs\n */\n get documentIds(): string[] {\n return Array.from(this.#documents.keys());\n }\n\n /**\n * Serialize the index to a JSON-compatible object\n */\n serialize(): BM25IndexData {\n const documents: SerializedBM25Document[] = [];\n for (const [id, doc] of this.#documents.entries()) {\n documents.push({\n id,\n content: doc.content,\n tokens: doc.tokens,\n termFrequencies: Object.fromEntries(doc.termFrequencies),\n length: doc.length,\n metadata: doc.metadata,\n });\n }\n\n return {\n k1: this.k1,\n b: this.b,\n documents,\n avgDocLength: this.#avgDocLength,\n };\n }\n\n /**\n * Deserialize an index from a JSON object\n */\n static deserialize(data: BM25IndexData, tokenizeOptions: TokenizeOptions = {}): BM25Index {\n const index = new BM25Index({ k1: data.k1, b: data.b }, tokenizeOptions);\n\n for (const doc of data.documents) {\n const termFrequencies = new Map(Object.entries(doc.termFrequencies));\n\n const document: BM25Document = {\n id: doc.id,\n content: doc.content,\n tokens: doc.tokens,\n termFrequencies,\n length: doc.length,\n metadata: doc.metadata,\n };\n\n index.#documents.set(doc.id, document);\n index.#docCount++;\n\n // Rebuild inverted index and document frequency\n for (const term of termFrequencies.keys()) {\n if (!index.#invertedIndex.has(term)) {\n index.#invertedIndex.set(term, new Set());\n }\n index.#invertedIndex.get(term)!.add(doc.id);\n index.#documentFrequency.set(term, (index.#documentFrequency.get(term) || 0) + 1);\n }\n }\n\n index.#avgDocLength = data.avgDocLength;\n\n return index;\n }\n\n /**\n * Update average document length after add/remove operations\n */\n #updateAvgDocLength(): void {\n if (this.#docCount === 0) {\n this.#avgDocLength = 0;\n return;\n }\n\n let totalLength = 0;\n for (const doc of this.#documents.values()) {\n totalLength += doc.length;\n }\n this.#avgDocLength = totalLength / this.#docCount;\n }\n\n /**\n * Compute IDF (Inverse Document Frequency) for a term\n */\n #computeIDF(df: number): number {\n // Using Robertson-Spärck Jones IDF formula\n return Math.log((this.#docCount - df + 0.5) / (df + 0.5) + 1);\n }\n\n /**\n * Compute the BM25 score component for a single term\n */\n #computeTermScore(tf: number, docLength: number, idf: number): number {\n const numerator = tf * (this.k1 + 1);\n const denominator = tf + this.k1 * (1 - this.b + this.b * (docLength / this.#avgDocLength));\n return idf * (numerator / denominator);\n }\n}\n\n/**\n * Serialized document format for persistence\n */\ninterface SerializedBM25Document {\n id: string;\n content: string;\n tokens: string[];\n termFrequencies: Record<string, number>;\n length: number;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Serialized index data for persistence\n */\nexport interface BM25IndexData {\n k1: number;\n b: number;\n documents: SerializedBM25Document[];\n avgDocLength: number;\n}\n","/**\n * SearchEngine - Unified search engine supporting BM25, vector, and hybrid search.\n *\n * Provides search capabilities for Workspace, enabling keyword-based (BM25),\n * semantic (vector), and combined hybrid search across indexed content.\n */\n\nimport type { MastraVector, VectorFilter } from '../../vector';\nimport type { LineRange } from '../line-utils';\n\nimport { BM25Index, tokenize, findLineRange } from './bm25';\nimport type { BM25Config, TokenizeOptions } from './bm25';\n\n/**\n * Search mode options\n */\nexport type SearchMode = 'vector' | 'bm25' | 'hybrid';\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Single-text embedder - takes one text and returns its embedding.\n *\n * This is the legacy embedder shape and remains the default. Each document is\n * embedded with a separate call.\n */\nexport interface SingleEmbedder {\n (text: string): Promise<number[]>;\n}\n\n/**\n * Batch-capable embedder - takes an array of texts and returns their embeddings\n * in the same order.\n *\n * Branded with `batch: true` so {@link SearchEngine} can detect batch support at\n * runtime and dispatch to a single batched embedder call instead of one call\n * per document. This dramatically speeds up large index rebuilds against\n * providers that support batch embedding (e.g. OpenAI's `embedMany`).\n *\n * @example\n * ```ts\n * import { embedMany } from 'ai';\n * import { openai } from '@ai-sdk/openai';\n *\n * const model = openai.embedding('text-embedding-3-small');\n * const embedder: BatchEmbedder = Object.assign(\n * async (texts: string[]) => {\n * const { embeddings } = await embedMany({ model, values: texts });\n * return embeddings;\n * },\n * { batch: true as const, maxBatchSize: 2048 },\n * );\n * ```\n */\nexport interface BatchEmbedder {\n (texts: string[]): Promise<number[][]>;\n /** Brand that marks this embedder as batch-capable. */\n readonly batch: true;\n /**\n * Maximum number of texts the underlying provider accepts per call. When\n * unset, all pending texts are sent in a single request.\n */\n readonly maxBatchSize?: number;\n}\n\n/**\n * Embedder interface - either a legacy single-text embedder or a batch-capable\n * embedder branded with `batch: true`.\n */\nexport type Embedder = SingleEmbedder | BatchEmbedder;\n\n/**\n * Type guard: returns true when the embedder is the batch-capable variant.\n */\nexport function isBatchEmbedder(embedder: Embedder): embedder is BatchEmbedder {\n return typeof embedder === 'function' && (embedder as Partial<BatchEmbedder>).batch === true;\n}\n\n/**\n * Configuration for vector search\n */\nexport interface VectorConfig {\n /** Vector store for semantic search */\n vectorStore: MastraVector;\n /**\n * Embedder function for generating vectors. Omit it when the vector store generates\n * embeddings itself, in which case the store receives the text.\n */\n embedder?: Embedder;\n /** Index name for the vector store */\n indexName: string;\n}\n\n/**\n * Configuration for BM25 search\n */\nexport interface BM25SearchConfig {\n /** BM25 algorithm parameters */\n bm25?: BM25Config;\n /** Tokenization options */\n tokenize?: TokenizeOptions;\n}\n\n/**\n * A document to be indexed\n */\nexport interface IndexDocument {\n /** Unique identifier for this document */\n id: string;\n /** Text content to index */\n content: string;\n /** Optional metadata to store with the document */\n metadata?: Record<string, unknown>;\n /**\n * For chunked documents: the starting line number of this chunk in the original document.\n * When provided, lineRange in search results will be adjusted to reflect original document lines.\n * (1-indexed)\n */\n startLineOffset?: number;\n}\n\n/**\n * Base search result with common fields\n */\nexport interface SearchResult {\n /** Document identifier */\n id: string;\n /** Document content */\n content: string;\n /** Search score (0-1 for normalized results) */\n score: number;\n /** Line range where query terms appear */\n lineRange?: LineRange;\n /** Optional metadata */\n metadata?: Record<string, unknown>;\n /** Score breakdown by search type */\n scoreDetails?: {\n vector?: number;\n bm25?: number;\n };\n}\n\n/**\n * Options for searching\n */\nexport interface SearchOptions {\n /** Maximum number of results to return */\n topK?: number;\n /** Minimum score threshold */\n minScore?: number;\n /** Search mode: 'bm25', 'vector', or 'hybrid' */\n mode?: SearchMode;\n /** Weight for vector scores in hybrid search (0-1, default 0.5) */\n vectorWeight?: number;\n /** Filter for vector search */\n filter?: Record<string, unknown>;\n}\n\n/** Options for batch indexing */\nexport interface IndexManyOptions {\n /**\n * Maximum number of indexing units to run concurrently (embedder + vector upsert).\n * Must be a safe integer ≥ 1 (same rule as `p-map`).\n *\n * A unit is one document, or — when the embedder is batch-capable — one group of up to\n * `maxBatchSize` documents sharing a single embedder call.\n * @default 8\n */\n concurrency?: number;\n /**\n * When `true` (default), the first rejected `index` rejects the whole `indexMany` call.\n * When `false`, all documents are processed; if any failed, the promise rejects with an `AggregateError`.\n */\n stopOnError?: boolean;\n}\n\n/** Default `indexMany` / lazy-vector flush concurrency (embedder + upsert). */\nconst DEFAULT_INDEX_MANY_CONCURRENCY = 8;\n\n/** Documents per embedder call when the embedder does not declare its own `maxBatchSize`. */\nconst DEFAULT_EMBED_GROUP_SIZE = 256;\n\n/**\n * Upper bound on vectors handed to a single `upsert`.\n *\n * Vector stores cap how much one write request may carry — `PineconeVector` already slices at\n * this exact size — and each document's metadata carries its full text, so an unbounded batch\n * turns into an unbounded request. Kept separate from the embedder's `maxBatchSize`, which\n * limits the embedding API rather than the store.\n */\nconst MAX_VECTORS_PER_UPSERT = 100;\n\n/**\n * Documents to group per embedder call, honouring the embedder's own limit.\n *\n * A `maxBatchSize` of `0`, a negative number or `NaN` (easy to produce with\n * `Number(process.env.EMBED_BATCH_SIZE)`) would otherwise mean \"never make progress\", so those\n * fall back to the default rather than stalling or silently indexing nothing.\n */\nfunction resolveEmbedGroupSize(embedder: BatchEmbedder): number {\n const declared = embedder.maxBatchSize;\n if (declared === undefined || !Number.isFinite(declared) || declared < 1) {\n return DEFAULT_EMBED_GROUP_SIZE;\n }\n return Math.floor(declared);\n}\n\nfunction chunkItems<T>(items: readonly T[], size: number): T[][] {\n const groups: T[][] = [];\n for (let i = 0; i < items.length; i += size) {\n groups.push(items.slice(i, i + size));\n }\n return groups;\n}\n\n/**\n * Configuration for SearchEngine\n */\nexport interface SearchEngineConfig {\n /** BM25 configuration (enables BM25 search) */\n bm25?: BM25SearchConfig;\n /** Vector configuration (enables vector search) */\n vector?: VectorConfig;\n /** Whether to use lazy vector indexing (default: false = eager) */\n lazyVectorIndex?: boolean;\n}\n\n// =============================================================================\n// Chunking\n// =============================================================================\n\nconst DEFAULT_MAX_CHUNK_CHARS = 4000;\nconst DEFAULT_OVERLAP_LINES = 3;\n\nexport interface ChunkOptions {\n maxChunkChars?: number;\n overlapLines?: number;\n}\n\nexport interface TextChunk {\n content: string;\n startLine: number;\n}\n\n/**\n * Split text into line-based chunks that stay within a character budget.\n *\n * Each chunk is formed by accumulating whole lines until adding the next line\n * would exceed `maxChunkChars`. Adjacent chunks share `overlapLines` lines so\n * that context around chunk boundaries is preserved for embedding quality.\n *\n * Returns the original text as a single chunk when it already fits.\n */\nexport function splitIntoChunks(text: string, options: ChunkOptions = {}): TextChunk[] {\n const maxChars = Math.max(1, Math.floor(options.maxChunkChars ?? DEFAULT_MAX_CHUNK_CHARS));\n const overlapLines = Math.max(0, Math.floor(options.overlapLines ?? DEFAULT_OVERLAP_LINES));\n\n if (text.length <= maxChars) {\n return [{ content: text, startLine: 1 }];\n }\n\n const lines = text.split('\\n');\n const chunks: TextChunk[] = [];\n let start = 0;\n\n while (start < lines.length) {\n let end = start;\n let charCount = 0;\n\n while (end < lines.length) {\n const lineLen = lines[end]!.length + (end > start ? 1 : 0);\n if (charCount + lineLen > maxChars && end > start) break;\n charCount += lineLen;\n end++;\n }\n\n const chunkContent = lines.slice(start, end).join('\\n');\n\n if (chunkContent.length <= maxChars) {\n chunks.push({ content: chunkContent, startLine: start + 1 });\n } else {\n // Single line exceeds maxChars — split by character boundaries.\n for (let offset = 0; offset < chunkContent.length; offset += maxChars) {\n chunks.push({\n content: chunkContent.slice(offset, offset + maxChars),\n startLine: start + 1,\n });\n }\n }\n\n if (end >= lines.length) break;\n\n const nextStart = end - overlapLines;\n start = nextStart <= start ? end : nextStart;\n }\n\n return chunks;\n}\n\n// =============================================================================\n// SearchEngine\n// =============================================================================\n\n/**\n * Unified search engine supporting BM25, vector, and hybrid search.\n *\n * Used internally by Workspace to provide consistent search functionality.\n *\n * @example\n * ```typescript\n * const engine = new SearchEngine({\n * bm25: { tokenize: { lowercase: true } },\n * vector: { vectorStore, embedder, indexName: 'my-index' },\n * });\n *\n * // Index documents\n * await engine.index({ id: 'doc1', content: 'Hello world' });\n *\n * // Search\n * const results = await engine.search('hello', { mode: 'hybrid', topK: 5 });\n * ```\n */\nexport class SearchEngine {\n /** BM25 index for keyword search */\n #bm25Index?: BM25Index;\n\n /** Tokenization options (stored for lineRange computation) */\n #tokenizeOptions?: TokenizeOptions;\n\n /** Vector configuration */\n #vectorConfig?: VectorConfig;\n\n /** Whether to use lazy vector indexing */\n #lazyVectorIndex: boolean;\n\n /** All indexed document IDs (used for prefix-based removal across backends) */\n #indexedIds: Set<string> = new Set();\n\n /** Documents pending vector indexing (for lazy mode) */\n #pendingVectorDocs: IndexDocument[] = [];\n\n /** Whether vector index has been built (for lazy mode) */\n #vectorIndexBuilt: boolean = false;\n\n /** Whether createIndex has been attempted on the vector store */\n #vectorIndexReady: boolean = false;\n\n constructor(config: SearchEngineConfig = {}) {\n // Initialize BM25 if configured\n if (config.bm25 !== undefined) {\n this.#tokenizeOptions = config.bm25.tokenize;\n this.#bm25Index = new BM25Index(config.bm25.bm25, this.#tokenizeOptions);\n }\n\n // Store vector config if provided\n if (config.vector) {\n if (!config.vector.embedder && !config.vector.vectorStore.isSelfEmbedding) {\n throw new Error('Vector search requires an embedder, or a vector store that generates embeddings itself.');\n }\n this.#vectorConfig = config.vector;\n }\n\n this.#lazyVectorIndex = config.lazyVectorIndex ?? false;\n }\n\n // ===========================================================================\n // Public API\n // ===========================================================================\n\n /**\n * Index a document for search\n */\n async index(doc: IndexDocument): Promise<void> {\n const docWithMergedMetadata = this.#indexNonVectorParts(doc);\n\n // Vector indexing\n if (this.#vectorConfig) {\n if (this.#lazyVectorIndex) {\n // Store for later indexing\n this.#pendingVectorDocs.push(docWithMergedMetadata);\n this.#vectorIndexBuilt = false;\n } else {\n // Index immediately\n await this.#indexVector(docWithMergedMetadata);\n }\n }\n }\n\n /**\n * Run the synchronous, per-document half of indexing: metadata merge, id tracking and BM25.\n *\n * Returns the document with merged metadata so the caller can hand it to the vector path.\n * Split out of {@link SearchEngine.index} so `indexMany` can keep BM25 per-document while\n * batching the vector work.\n */\n #indexNonVectorParts(doc: IndexDocument): IndexDocument {\n // Merge startLineOffset into metadata for retrieval at search time\n const metadata: Record<string, unknown> = {\n ...doc.metadata,\n };\n if (doc.startLineOffset !== undefined) {\n metadata._startLineOffset = doc.startLineOffset;\n }\n\n this.#indexedIds.add(doc.id);\n\n // BM25 indexing (always synchronous and immediate)\n if (this.#bm25Index) {\n this.#bm25Index.add(doc.id, doc.content, metadata);\n }\n\n return { ...doc, metadata };\n }\n\n /**\n * Index multiple documents (up to `concurrency` at a time when async vector work runs).\n *\n * @param docs - Documents to index\n * @param options - `p-map` options; `concurrency` defaults to 8\n */\n async indexMany(docs: IndexDocument[], options?: IndexManyOptions): Promise<void> {\n const stopOnError = options?.stopOnError;\n const concurrency = options?.concurrency ?? DEFAULT_INDEX_MANY_CONCURRENCY;\n\n // Grouping only pays off on the eager vector path for a batch-capable embedder or a store\n // that embeds server-side. Lazy mode already batches at flush time, and a single-text\n // embedder gains nothing from grouping.\n if (this.#lazyVectorIndex || !this.#groupsWrites()) {\n const pMap = (await import('p-map')).default;\n await pMap(docs, doc => this.index(doc), { stopOnError, concurrency });\n return;\n }\n\n // Match the lazy path: a repeated id must not appear twice in one upsert payload.\n const unique = this.#dedupeDocsLastWins(docs);\n\n const groups = chunkItems(unique, this.#writeGroupSize());\n if (groups.length === 0) return;\n\n // Contract for `stopOnError: false`: every document is processed and the call rejects with a\n // flat `AggregateError` of the individual failures. Collect them here rather than letting a\n // failed group reject, so the caller never sees an `AggregateError` nested inside another one.\n const failures: unknown[] = [];\n const runGroup = async (group: IndexDocument[]) => {\n const merged = this.#indexNonVectorPartsOf(group);\n if (stopOnError !== false) {\n await this.#embedAndUpsertGroup(merged);\n return;\n }\n try {\n await this.#embedAndUpsertGroup(merged);\n } catch {\n // One unusable document must not drop the rest of its group.\n for (const doc of merged) {\n try {\n await this.#indexVector(doc);\n } catch (error) {\n failures.push(error);\n }\n }\n }\n };\n\n // The first group runs alone so `createIndex` completes before any parallel writes, matching\n // what the lazy flush does. Otherwise every concurrent group sees `#vectorIndexReady === false`\n // and upserts against an index that may still be under construction.\n await runGroup(groups[0]!);\n if (groups.length > 1) {\n const pMap = (await import('p-map')).default;\n await pMap(groups.slice(1), runGroup, { stopOnError, concurrency });\n }\n\n if (failures.length > 0) {\n throw new AggregateError(failures);\n }\n }\n\n /**\n * BM25-index a group of documents as it is attempted.\n *\n * Keeping this inside the group task means a rejected `indexMany` leaves the keyword index in\n * the same shape the per-document path would have: populated only for documents that indexing\n * actually reached, rather than for every document handed in.\n */\n #indexNonVectorPartsOf(group: IndexDocument[]): IndexDocument[] {\n return group.map(doc => this.#indexNonVectorParts(doc));\n }\n\n /**\n * Collapse duplicate document ids so a single upsert runs per id (last entry wins).\n */\n #dedupeDocsLastWins(docs: readonly IndexDocument[]): IndexDocument[] {\n const byId = new Map<string, IndexDocument>();\n for (const doc of docs) {\n byId.set(doc.id, doc);\n }\n return [...byId.values()];\n }\n\n /**\n * Remove a document from the index\n */\n async remove(id: string): Promise<void> {\n this.#indexedIds.delete(id);\n\n // Remove from BM25\n if (this.#bm25Index) {\n this.#bm25Index.remove(id);\n }\n\n // Remove from vector store\n if (this.#vectorConfig) {\n try {\n await this.#vectorConfig.vectorStore.deleteVector({\n indexName: this.#vectorConfig.indexName,\n id,\n });\n } catch {\n // Vector may not exist, ignore\n }\n\n // Also remove from pending docs if in lazy mode\n if (this.#lazyVectorIndex) {\n this.#pendingVectorDocs = this.#pendingVectorDocs.filter(d => d.id !== id);\n }\n }\n }\n\n /**\n * Number of indexed documents whose ID starts with the given prefix.\n */\n countByPrefix(prefix: string): number {\n let count = 0;\n for (const id of this.#indexedIds) {\n if (id.startsWith(prefix)) count++;\n }\n return count;\n }\n\n /**\n * Remove all documents whose ID starts with the given prefix.\n * Used to remove all chunks belonging to a single source document.\n */\n async removeByPrefix(prefix: string): Promise<void> {\n const matchedIds = [...this.#indexedIds].filter(id => id.startsWith(prefix));\n\n for (const id of matchedIds) {\n this.#indexedIds.delete(id);\n }\n\n if (this.#bm25Index) {\n for (const id of matchedIds) {\n this.#bm25Index.remove(id);\n }\n }\n\n if (this.#vectorConfig) {\n if (this.#lazyVectorIndex) {\n this.#pendingVectorDocs = this.#pendingVectorDocs.filter(d => !d.id.startsWith(prefix));\n }\n\n for (const id of matchedIds) {\n try {\n await this.#vectorConfig.vectorStore.deleteVector({\n indexName: this.#vectorConfig.indexName,\n id,\n });\n } catch {\n // Vector may not exist, ignore\n }\n }\n }\n }\n\n /**\n * Remove a source document and all of its chunked variants.\n *\n * This also attempts a metadata-based bulk delete for chunk vectors so stale\n * chunk IDs from previous process runs are cleaned up in persistent stores.\n */\n async removeSource(sourceId: string): Promise<void> {\n await this.remove(sourceId);\n await this.removeByPrefix(`${sourceId}#chunk-`);\n\n if (this.#vectorConfig) {\n try {\n await this.#vectorConfig.vectorStore.deleteVectors({\n indexName: this.#vectorConfig.indexName,\n filter: { sourceFile: sourceId } as VectorFilter,\n });\n } catch {\n // Bulk delete/filter may not be supported by all vector backends.\n }\n }\n }\n\n /**\n * Clear all indexed documents\n */\n clear(): void {\n this.#indexedIds.clear();\n if (this.#bm25Index) {\n this.#bm25Index.clear();\n }\n this.#pendingVectorDocs = [];\n this.#vectorIndexBuilt = false;\n // Note: We don't clear the vector store here as it may be shared\n }\n\n /**\n * Search for documents\n */\n async search(query: string, options: SearchOptions = {}): Promise<SearchResult[]> {\n const { topK = 10, minScore, mode, vectorWeight = 0.5, filter } = options;\n\n const effectiveMode = this.#determineSearchMode(mode);\n\n if (effectiveMode === 'bm25') {\n return this.#searchBM25(query, topK, minScore);\n }\n\n if (effectiveMode === 'vector') {\n return this.#searchVector(query, topK, minScore, filter);\n }\n\n // Hybrid search\n return this.#searchHybrid(query, topK, minScore, vectorWeight, filter);\n }\n\n /**\n * Check if BM25 search is available\n */\n get canBM25(): boolean {\n return !!this.#bm25Index;\n }\n\n /**\n * Check if vector search is available\n */\n get canVector(): boolean {\n return !!this.#vectorConfig;\n }\n\n /**\n * Check if hybrid search is available\n */\n get canHybrid(): boolean {\n return this.canBM25 && this.canVector;\n }\n\n /**\n * Get the BM25 index (for serialization/debugging)\n */\n get bm25Index(): BM25Index | undefined {\n return this.#bm25Index;\n }\n\n // ===========================================================================\n // Private Methods\n // ===========================================================================\n\n /**\n * Determine the effective search mode\n */\n #determineSearchMode(requestedMode?: SearchMode): SearchMode {\n if (requestedMode) {\n if (requestedMode === 'vector' && !this.canVector) {\n throw new Error('Vector search requires vector configuration.');\n }\n if (requestedMode === 'bm25' && !this.canBM25) {\n throw new Error('BM25 search requires BM25 configuration.');\n }\n if (requestedMode === 'hybrid' && !this.canHybrid) {\n throw new Error('Hybrid search requires both vector and BM25 configuration.');\n }\n return requestedMode;\n }\n\n // Auto-determine based on available configuration\n if (this.canHybrid) {\n return 'hybrid';\n }\n if (this.canVector) {\n return 'vector';\n }\n if (this.canBM25) {\n return 'bm25';\n }\n\n throw new Error('No search configuration available. Provide bm25 or vector config.');\n }\n\n /**\n * True when the vector store generates the embeddings, so this engine sends it text.\n * False whenever an embedder is configured, which keeps the client-side path intact.\n */\n #embedsServerSide(): boolean {\n return !this.#vectorConfig?.embedder && this.#vectorConfig?.vectorStore.isSelfEmbedding === true;\n }\n\n /** True when documents are written in groups rather than one at a time. */\n #groupsWrites(): boolean {\n const embedder = this.#vectorConfig?.embedder;\n return this.#embedsServerSide() || (!!embedder && isBatchEmbedder(embedder));\n }\n\n /** Documents per group: the embedder's own limit, or the upsert bound when the store embeds. */\n #writeGroupSize(): number {\n const embedder = this.#vectorConfig?.embedder;\n return embedder && isBatchEmbedder(embedder) ? resolveEmbedGroupSize(embedder) : MAX_VECTORS_PER_UPSERT;\n }\n\n /**\n * Embed a single text, dispatching to the batch path with a one-element array\n * when the configured embedder is batch-capable.\n */\n async #embedOne(text: string): Promise<number[]> {\n if (!this.#vectorConfig) {\n throw new Error('Vector configuration is required to embed text.');\n }\n const { embedder } = this.#vectorConfig;\n if (!embedder) {\n throw new Error('This vector store generates embeddings itself, so there is no embedder to call.');\n }\n if (isBatchEmbedder(embedder)) {\n const [embedding] = await embedder([text]);\n if (!embedding) {\n throw new Error('Batch embedder returned no embedding for input text.');\n }\n return embedding;\n }\n return embedder(text);\n }\n\n /**\n * Embed many texts. Uses a single batched call (chunked by `maxBatchSize`)\n * when the embedder is batch-capable; otherwise falls back to parallel\n * single-text calls.\n */\n async #embedAll(texts: string[]): Promise<number[][]> {\n if (!this.#vectorConfig) {\n throw new Error('Vector configuration is required to embed texts.');\n }\n if (texts.length === 0) return [];\n\n const pMap = (await import('p-map')).default;\n const { embedder } = this.#vectorConfig;\n if (!embedder) {\n throw new Error('This vector store generates embeddings itself, so there is no embedder to call.');\n }\n\n if (isBatchEmbedder(embedder)) {\n // Same sanitized size the callers group by, so an unusable `maxBatchSize` can never turn\n // this loop into a non-advancing one.\n const max = resolveEmbedGroupSize(embedder);\n if (texts.length <= max) {\n return embedder(texts);\n }\n\n // Chunk by maxBatchSize and run chunks in parallel up to DEFAULT_INDEX_MANY_CONCURRENCY.\n const results = await pMap(chunkItems(texts, max), chunk => embedder(chunk), {\n concurrency: DEFAULT_INDEX_MANY_CONCURRENCY,\n });\n return results.flat();\n }\n\n return pMap(texts, text => embedder(text), {\n concurrency: DEFAULT_INDEX_MANY_CONCURRENCY,\n });\n }\n\n /**\n * Index a single document in the vector store.\n *\n * Used by the eager (non-lazy) write path. The lazy flush path embeds all\n * pending docs together via {@link SearchEngine.#flushVectorBatch} for true\n * batch embedding when supported.\n */\n async #indexVector(doc: IndexDocument): Promise<void> {\n if (!this.#vectorConfig) return;\n\n if (this.#embedsServerSide()) {\n await this.#embedAndUpsertGroup([doc]);\n return;\n }\n\n const { vectorStore, indexName } = this.#vectorConfig;\n\n const embedding = await this.#embedOne(doc.content);\n\n if (!this.#vectorIndexReady) {\n // Some backends (e.g. LibSQLVector) require createIndex before upsert.\n // createIndex is expected to be idempotent; we ignore errors here and let\n // upsert determine whether the index is actually usable.\n try {\n await vectorStore.createIndex({ indexName, dimension: embedding.length });\n } catch {\n // Already exists, temporarily unavailable, or not required by backend.\n }\n }\n\n await vectorStore.upsert({\n indexName,\n vectors: [embedding],\n metadata: [\n {\n id: doc.id,\n text: doc.content,\n ...doc.metadata,\n },\n ],\n ids: [doc.id],\n });\n\n // Mark index as ready only after a successful upsert so createIndex is retried\n // on subsequent writes if the previous attempt did not produce a usable index.\n this.#vectorIndexReady = true;\n }\n\n /**\n * Embed and upsert a batch of documents in as few provider calls as possible.\n *\n * - If the embedder is batch-capable, texts are grouped into `maxBatchSize` embedder calls\n * and written with upserts bounded by {@link MAX_VECTORS_PER_UPSERT}.\n * - If the store embeds server-side, the texts are written as they are, in the same bounded\n * upserts.\n * - Otherwise falls back to per-doc embedding via {@link SearchEngine.#indexVector}.\n */\n async #flushVectorBatch(docs: IndexDocument[]): Promise<void> {\n if (!this.#vectorConfig || docs.length === 0) return;\n\n const pMap = (await import('p-map')).default;\n\n if (!this.#groupsWrites()) {\n // Single-text embedder: parallelize per-doc work, preserving prior semantics.\n await pMap(docs, doc => this.#indexVector(doc), {\n concurrency: DEFAULT_INDEX_MANY_CONCURRENCY,\n });\n return;\n }\n\n const groups = chunkItems(docs, this.#writeGroupSize());\n\n // The first group runs alone so `createIndex` happens once, before any parallel writes.\n await this.#embedAndUpsertGroup(groups[0]!);\n if (groups.length > 1) {\n await pMap(groups.slice(1), group => this.#embedAndUpsertGroup(group), {\n concurrency: DEFAULT_INDEX_MANY_CONCURRENCY,\n });\n }\n }\n\n /**\n * Embed one group of documents with a single embedder call, then write the vectors using\n * upserts no larger than {@link MAX_VECTORS_PER_UPSERT}.\n *\n * Vectors are paired with their documents positionally, so the embedder must return exactly\n * one embedding per input in input order.\n */\n async #embedAndUpsertGroup(docs: IndexDocument[]): Promise<void> {\n if (!this.#vectorConfig || docs.length === 0) return;\n\n const { vectorStore, indexName } = this.#vectorConfig;\n\n const embedsServerSide = this.#embedsServerSide();\n const embeddings = embedsServerSide ? [] : await this.#embedAll(docs.map(d => d.content));\n if (!embedsServerSide && embeddings.length !== docs.length) {\n throw new Error(`Batch embedder returned ${embeddings.length} embeddings for ${docs.length} inputs.`);\n }\n\n if (!this.#vectorIndexReady) {\n try {\n // A store that embeds server-side derives the dimension from its own model, so\n // CreateIndexParams.dimension has nothing to carry.\n await vectorStore.createIndex(\n embedsServerSide ? ({ indexName } as never) : { indexName, dimension: embeddings[0]!.length },\n );\n } catch {\n // Already exists, temporarily unavailable, or not required by backend.\n }\n }\n\n for (let start = 0; start < docs.length; start += MAX_VECTORS_PER_UPSERT) {\n const slice = docs.slice(start, start + MAX_VECTORS_PER_UPSERT);\n const rows = {\n indexName,\n metadata: slice.map(doc => ({\n id: doc.id,\n text: doc.content,\n ...doc.metadata,\n })),\n ids: slice.map(d => d.id),\n };\n if (embedsServerSide) {\n // `documents` is accepted only by stores that embed server-side, so it is not on the\n // shared UpsertVectorParams.\n await vectorStore.upsert({ ...rows, documents: slice.map(d => d.content) } as never);\n } else {\n await vectorStore.upsert({ ...rows, vectors: embeddings.slice(start, start + MAX_VECTORS_PER_UPSERT) });\n }\n\n // Mark index as ready only after a successful upsert so createIndex is retried\n // on subsequent writes if the previous attempt did not produce a usable index.\n this.#vectorIndexReady = true;\n }\n }\n\n /**\n * Ensure vector index is built (for lazy mode).\n *\n * Drains the pending queue into a local batch before awaiting upserts so concurrent `index()` calls\n * append to a fresh queue and are not wiped by a blanket clear. Loops until the queue is empty so\n * documents added mid-flush are indexed before search runs. Re-queues the batch on flush failure.\n */\n async #ensureVectorIndex(): Promise<void> {\n if (!this.#lazyVectorIndex) {\n return;\n }\n\n if (this.#pendingVectorDocs.length === 0) {\n this.#vectorIndexBuilt = true;\n return;\n }\n\n while (this.#pendingVectorDocs.length > 0) {\n const batch = this.#pendingVectorDocs;\n this.#pendingVectorDocs = [];\n\n const uniqueDocs = this.#dedupeDocsLastWins(batch);\n\n try {\n await this.#flushVectorBatch(uniqueDocs);\n } catch (error) {\n this.#pendingVectorDocs = [...uniqueDocs, ...this.#pendingVectorDocs];\n throw error;\n }\n }\n\n this.#vectorIndexBuilt = true;\n }\n\n /**\n * BM25 keyword search\n */\n #searchBM25(query: string, topK: number, minScore?: number): SearchResult[] {\n if (!this.#bm25Index) {\n throw new Error('BM25 search requires BM25 configuration.');\n }\n\n const results = this.#bm25Index.search(query, topK, minScore);\n const queryTokens = tokenize(query, this.#tokenizeOptions);\n\n return results.map(result => {\n const rawLineRange = findLineRange(result.content, queryTokens, this.#tokenizeOptions);\n const lineRange = this.#adjustLineRange(rawLineRange, result.metadata);\n const { _startLineOffset, ...cleanMetadata } = result.metadata ?? {};\n\n return {\n id: result.id,\n content: result.content,\n score: result.score,\n lineRange,\n metadata: Object.keys(cleanMetadata).length > 0 ? cleanMetadata : undefined,\n scoreDetails: { bm25: result.score },\n };\n });\n }\n\n /**\n * Vector semantic search\n */\n async #searchVector(\n query: string,\n topK: number,\n minScore?: number,\n filter?: Record<string, unknown>,\n ): Promise<SearchResult[]> {\n if (!this.#vectorConfig) {\n throw new Error('Vector search requires vector configuration.');\n }\n\n // Ensure lazy index is built\n await this.#ensureVectorIndex();\n\n const { vectorStore, indexName } = this.#vectorConfig;\n\n // A store that embeds server-side takes the search string itself. `queryText` is accepted\n // only by those stores, so it is not on the shared QueryVectorParams.\n const vectorResults = this.#embedsServerSide()\n ? await vectorStore.query({ indexName, queryText: query, topK, filter: filter as VectorFilter } as never)\n : await vectorStore.query({\n indexName,\n queryVector: await this.#embedOne(query),\n topK,\n filter: filter as VectorFilter,\n });\n\n const queryTokens = tokenize(query, this.#tokenizeOptions);\n const results: SearchResult[] = [];\n\n for (const result of vectorResults) {\n if (minScore !== undefined && result.score < minScore) {\n continue;\n }\n\n const id = (result.metadata?.id as string) ?? result.id;\n const content = (result.metadata?.text as string) ?? '';\n\n // Extract metadata, excluding internal fields\n const { id: _id, text: _text, _startLineOffset, ...restMetadata } = result.metadata ?? {};\n\n const rawLineRange = findLineRange(content, queryTokens, this.#tokenizeOptions);\n const lineRange = this.#adjustLineRange(rawLineRange, result.metadata);\n\n results.push({\n id,\n content,\n score: result.score,\n lineRange,\n metadata: Object.keys(restMetadata).length > 0 ? restMetadata : undefined,\n scoreDetails: { vector: result.score },\n });\n }\n\n return results;\n }\n\n /**\n * Hybrid search combining vector and BM25 scores\n */\n async #searchHybrid(\n query: string,\n topK: number,\n minScore?: number,\n vectorWeight: number = 0.5,\n filter?: Record<string, unknown>,\n ): Promise<SearchResult[]> {\n // Get more results than requested to account for merging\n const expandedTopK = Math.min(topK * 2, 50);\n\n // Perform both searches in parallel\n const [vectorResults, bm25Results] = await Promise.all([\n this.#searchVector(query, expandedTopK, undefined, filter),\n Promise.resolve(this.#searchBM25(query, expandedTopK, undefined)),\n ]);\n\n // Normalize BM25 scores to 0-1 range\n const normalizedBM25 = this.#normalizeBM25Scores(bm25Results);\n\n // Create score maps by document id\n const bm25Map = new Map<string, SearchResult>();\n for (const result of normalizedBM25) {\n bm25Map.set(result.id, result);\n }\n\n const vectorMap = new Map<string, SearchResult>();\n for (const result of vectorResults) {\n vectorMap.set(result.id, result);\n }\n\n // Combine scores\n const combinedResults = new Map<string, SearchResult>();\n const allIds = new Set([...vectorMap.keys(), ...bm25Map.keys()]);\n const bm25Weight = 1 - vectorWeight;\n\n for (const id of allIds) {\n const vectorResult = vectorMap.get(id);\n const bm25Result = bm25Map.get(id);\n\n const vectorScore = vectorResult?.scoreDetails?.vector ?? 0;\n const bm25Score = bm25Result?.score ?? 0; // Already normalized\n\n const combinedScore = vectorWeight * vectorScore + bm25Weight * bm25Score;\n\n // Use data from whichever source has it\n const baseResult = vectorResult ?? bm25Result!;\n\n combinedResults.set(id, {\n id,\n content: baseResult.content,\n score: combinedScore,\n lineRange: bm25Result?.lineRange ?? vectorResult?.lineRange,\n metadata: baseResult.metadata,\n scoreDetails: {\n vector: vectorResult?.scoreDetails?.vector,\n bm25: bm25Result?.scoreDetails?.bm25,\n },\n });\n }\n\n // Sort by combined score and apply filters\n let results = Array.from(combinedResults.values());\n results.sort((a, b) => b.score - a.score);\n\n if (minScore !== undefined) {\n results = results.filter(r => r.score >= minScore);\n }\n\n return results.slice(0, topK);\n }\n\n /**\n * Normalize BM25 scores to 0-1 range using min-max normalization\n */\n #normalizeBM25Scores(results: SearchResult[]): SearchResult[] {\n if (results.length === 0) return results;\n\n const scores = results.map(r => r.scoreDetails?.bm25 ?? r.score);\n const maxScore = Math.max(...scores);\n const minScore = Math.min(...scores);\n const range = maxScore - minScore;\n\n if (range === 0) {\n return results.map(r => ({ ...r, score: 1 }));\n }\n\n return results.map(r => ({\n ...r,\n score: ((r.scoreDetails?.bm25 ?? r.score) - minScore) / range,\n }));\n }\n\n /**\n * Adjust line range for chunked documents.\n * If the document has a _startLineOffset in metadata, adjust the line range\n * to reflect the original document's line numbers.\n */\n #adjustLineRange(lineRange: LineRange | undefined, metadata?: Record<string, unknown>): LineRange | undefined {\n if (!lineRange) return undefined;\n\n const startLineOffset = metadata?._startLineOffset;\n if (typeof startLineOffset !== 'number') {\n return lineRange;\n }\n\n // Adjust line numbers: chunk lines are 1-indexed relative to chunk,\n // offset is 1-indexed relative to original document\n // So line 1 in chunk with offset 10 becomes line 10 in original\n return {\n start: lineRange.start + startLineOffset - 1,\n end: lineRange.end + startLineOffset - 1,\n };\n }\n}\n","/**\n * LocalSkillSource - Read-only skill source backed by local filesystem.\n *\n * Uses Node.js fs/promises to read skills directly from disk.\n * This allows skills to be loaded without requiring a full WorkspaceFilesystem.\n *\n * @example\n * ```typescript\n * const source = new LocalSkillSource({\n * basePath: process.cwd(),\n * });\n *\n * // skills paths are relative to basePath\n * const skillsImpl = new WorkspaceSkillsImpl({\n * source,\n * skills: ['./skills', './node_modules/@company/skills'],\n * });\n * ```\n */\n\nimport * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\n\nimport { fsExists, fsStat, isTextFile } from '../filesystem';\nimport type { SkillSource, SkillSourceEntry, SkillSourceStat } from './skill-source';\n\n/**\n * Configuration for LocalSkillSource.\n */\nexport interface LocalSkillSourceOptions {\n /**\n * Base path for resolving relative skill paths.\n * Defaults to process.cwd().\n */\n basePath?: string;\n}\n\n/**\n * Read-only skill source that loads skills from the local filesystem.\n *\n * Unlike WorkspaceFilesystem, this doesn't provide write operations.\n * Skills loaded from this source are read-only.\n */\nexport class LocalSkillSource implements SkillSource {\n readonly #basePath: string;\n\n constructor(options: LocalSkillSourceOptions = {}) {\n this.#basePath = options.basePath ?? process.cwd();\n }\n\n /**\n * Resolve a path relative to the base path.\n * Handles both absolute and relative paths.\n */\n #resolvePath(skillPath: string): string {\n if (path.isAbsolute(skillPath)) {\n return skillPath;\n }\n return path.resolve(this.#basePath, skillPath);\n }\n\n async exists(skillPath: string): Promise<boolean> {\n return fsExists(this.#resolvePath(skillPath));\n }\n\n async stat(skillPath: string): Promise<SkillSourceStat> {\n return fsStat(this.#resolvePath(skillPath), skillPath);\n }\n\n async readFile(skillPath: string): Promise<string | Buffer> {\n const resolved = this.#resolvePath(skillPath);\n const content = await fs.readFile(resolved);\n // Convert to string for text files\n if (isTextFile(skillPath)) {\n return content.toString('utf-8');\n }\n return content;\n }\n\n async readdir(skillPath: string): Promise<SkillSourceEntry[]> {\n const resolved = this.#resolvePath(skillPath);\n const entries = await fs.readdir(resolved, { withFileTypes: true });\n // Dirent.isDirectory() returns false for symlinks, even when they point to\n // directories. Detect the target type so skill discovery can load symlinked\n // skills while still letting higher layers decide whether to recurse.\n return Promise.all(\n entries.map(async entry => {\n const entryPath = path.join(resolved, entry.name);\n const isSymlink = entry.isSymbolicLink();\n let type: SkillSourceEntry['type'] = entry.isDirectory() ? 'directory' : 'file';\n\n if (isSymlink) {\n try {\n const targetStat = await fs.stat(entryPath);\n type = targetStat.isDirectory() ? 'directory' : 'file';\n } catch {\n type = 'file';\n }\n }\n\n return {\n name: entry.name,\n type,\n isSymlink: isSymlink || undefined,\n };\n }),\n );\n }\n\n async realpath(skillPath: string): Promise<string> {\n return fs.realpath(this.#resolvePath(skillPath));\n }\n}\n","import { parse, stringify } from \"yaml\";\n// src/frontmatter/index.ts\nconst OPEN = \"---\";\nconst CLOSE = \"\\n---\";\n/**\n* Split a markdown document into YAML frontmatter and body.\n*\n* A frontmatter block starts with `---` on the first line and ends at the next\n* line that is exactly `---` (a longer dash run or `--- !tag` is not a delimiter). An optional language tag may follow the opening\n* delimiter (`---yaml`); only YAML and JSON are accepted, and a `js`/`javascript`\n* tag throws instead of being evaluated. Documents that do not start with `---`\n* are returned unchanged with empty data.\n*\n* Throws when the frontmatter is not valid YAML or is not a mapping.\n*/\nfunction parseFrontmatter(input) {\n\tconst str = input.charCodeAt(0) === 65279 ? input.slice(1) : input;\n\tif (!str.startsWith(OPEN) || str.charAt(3) === \"-\") return {\n\t\tdata: {},\n\t\tcontent: str\n\t};\n\tlet rest = str.slice(3);\n\tconst firstLineEnd = rest.indexOf(\"\\n\");\n\tconst language = (firstLineEnd === -1 ? rest : rest.slice(0, firstLineEnd)).trim().toLowerCase();\n\tif (language) rest = firstLineEnd === -1 ? \"\" : rest.slice(firstLineEnd);\n\tlet closeIndex = rest.indexOf(CLOSE);\n\tlet closeEnd = -1;\n\twhile (closeIndex !== -1) {\n\t\tcloseEnd = closeIndex + 4;\n\t\twhile (rest[closeEnd] === \" \" || rest[closeEnd] === \"\t\") closeEnd++;\n\t\tconst after = rest.charAt(closeEnd);\n\t\tif (after === \"\" || after === \"\\n\" || after === \"\\r\") break;\n\t\tcloseIndex = rest.indexOf(CLOSE, closeIndex + 1);\n\t}\n\tconst block = (closeIndex === -1 ? rest : rest.slice(0, closeIndex)).replace(/\\r(?=\\n|$)/g, \"\");\n\tlet content = closeIndex === -1 ? \"\" : rest.slice(closeEnd);\n\tif (content.startsWith(\"\\r\")) content = content.slice(1);\n\tif (content.startsWith(\"\\n\")) content = content.slice(1);\n\treturn {\n\t\tdata: parseBlock(block, language),\n\t\tcontent\n\t};\n}\nfunction parseBlock(block, language) {\n\tif (block.replace(/^\\s*#[^\\n]*/gm, \"\").trim() === \"\") return {};\n\tlet data;\n\tswitch (language) {\n\t\tcase \"\":\n\t\tcase \"yaml\":\n\t\tcase \"yml\":\n\t\t\tdata = parse(block);\n\t\t\tbreak;\n\t\tcase \"json\":\n\t\t\tdata = JSON.parse(block);\n\t\t\tbreak;\n\t\tcase \"js\":\n\t\tcase \"javascript\": throw new Error(\"JavaScript frontmatter is not supported\");\n\t\tdefault: throw new Error(`Frontmatter language \"${language}\" is not supported`);\n\t}\n\tif (data === null || data === void 0) return {};\n\tif (typeof data !== \"object\" || Array.isArray(data)) throw new Error(\"Frontmatter must be a mapping of fields\");\n\treturn data;\n}\n/**\n* Serialize `data` as a YAML frontmatter block followed by `content`.\n* The block is omitted when `data` has no fields. The result always ends with a newline.\n*/\nfunction stringifyFrontmatter(content, data) {\n\tconst body = content.endsWith(\"\\n\") ? content : `${content}\\n`;\n\tif (Object.keys(data).length === 0) return body;\n\tconst block = stringify(data, { lineWidth: 0 }).trimEnd();\n\treturn `${OPEN}\\n${block}\\n${OPEN}\\n${body}`;\n}\nexport { parseFrontmatter, stringifyFrontmatter };\n\n//# sourceMappingURL=index.js.map","/**\n * Validation for Skills following the Agent Skills specification.\n * @see https://agentskills.io/specification\n *\n * This module uses plain validation functions instead of Zod to avoid\n * version compatibility issues between Zod 3 and Zod 4.\n */\n\nimport { parseFrontmatter } from '@internal/core/frontmatter';\n\n// =============================================================================\n// Constants\n// =============================================================================\n\n/**\n * Recommended limits from the Agent Skills spec\n */\nexport const SKILL_LIMITS = {\n /** Recommended max tokens for instructions */\n MAX_INSTRUCTION_TOKENS: 5000,\n /** Recommended max lines for SKILL.md */\n MAX_INSTRUCTION_LINES: 500,\n /** Max characters for name field */\n MAX_NAME_LENGTH: 64,\n /** Max characters for description field */\n MAX_DESCRIPTION_LENGTH: 1024,\n /** Max characters for compatibility field */\n MAX_COMPATIBILITY_LENGTH: 500,\n} as const;\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * Skill metadata input type (what users provide)\n */\nexport interface SkillMetadataInput {\n /** Skill name (1-64 chars, lowercase letters/numbers/hyphens only, must match directory name) */\n name: string;\n /** Description of what the skill does and when to use it (1-1024 characters) */\n description: string;\n /** License for the skill (e.g., \"Apache-2.0\", \"MIT\") */\n license?: string;\n /** Environment requirements or compatibility notes (string or object for flexibility) */\n compatibility?: unknown;\n /** Whether this skill should be directly invokable by users. Defaults to true. */\n 'user-invocable'?: boolean;\n /** Arbitrary key-value metadata - values can be strings, arrays, objects, etc. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Skill metadata output type (after validation)\n */\nexport type SkillMetadataOutput = SkillMetadataInput;\n\n/**\n * Validation result with warnings\n */\nexport interface SkillValidationResult {\n valid: boolean;\n errors: string[];\n warnings: string[];\n}\n\n// =============================================================================\n// Field Validators\n// =============================================================================\n\n/**\n * Validate skill name according to spec:\n * - 1-64 characters\n * - Lowercase letters, numbers, hyphens only\n * - Must not start or end with hyphen\n * - Must not contain consecutive hyphens\n *\n * @param name - The name to validate\n * @returns Array of error messages (empty if valid)\n */\nfunction validateSkillName(name: unknown): string[] {\n const errors: string[] = [];\n const fieldPath = 'name';\n\n // Check type\n if (typeof name !== 'string') {\n errors.push(`${fieldPath}: Expected string, received ${typeof name}`);\n return errors;\n }\n\n // Check not empty\n if (name.length === 0) {\n errors.push(`${fieldPath}: Skill name cannot be empty`);\n return errors;\n }\n\n // Check max length\n if (name.length > SKILL_LIMITS.MAX_NAME_LENGTH) {\n errors.push(`${fieldPath}: Skill name must be ${SKILL_LIMITS.MAX_NAME_LENGTH} characters or less`);\n }\n\n // Check allowed characters (lowercase letters, numbers, hyphens only)\n if (!/^[a-z0-9-]+$/.test(name)) {\n errors.push(`${fieldPath}: Skill name must contain only lowercase letters, numbers, and hyphens`);\n }\n\n // Check not starting or ending with hyphen\n if (name.startsWith('-') || name.endsWith('-')) {\n errors.push(`${fieldPath}: Skill name must not start or end with a hyphen`);\n }\n\n // Check no consecutive hyphens\n if (name.includes('--')) {\n errors.push(`${fieldPath}: Skill name must not contain consecutive hyphens`);\n }\n\n return errors;\n}\n\n/**\n * Validate skill description according to spec:\n * - 1-1024 characters\n * - Cannot be empty or only whitespace\n *\n * @param description - The description to validate\n * @returns Array of error messages (empty if valid)\n */\nfunction validateSkillDescription(description: unknown): string[] {\n const errors: string[] = [];\n const fieldPath = 'description';\n\n // Check type\n if (typeof description !== 'string') {\n errors.push(`${fieldPath}: Expected string, received ${typeof description}`);\n return errors;\n }\n\n // Check not empty\n if (description.length === 0) {\n errors.push(`${fieldPath}: Skill description cannot be empty`);\n return errors;\n }\n\n // Check max length\n if (description.length > SKILL_LIMITS.MAX_DESCRIPTION_LENGTH) {\n errors.push(`${fieldPath}: Skill description must be ${SKILL_LIMITS.MAX_DESCRIPTION_LENGTH} characters or less`);\n }\n\n // Check not only whitespace\n if (description.trim().length === 0) {\n errors.push(`${fieldPath}: Skill description cannot be only whitespace`);\n }\n\n return errors;\n}\n\n/**\n * Validate skill license (optional string).\n *\n * @param license - The license to validate\n * @returns Array of error messages (empty if valid)\n */\nfunction validateSkillLicense(license: unknown): string[] {\n const errors: string[] = [];\n const fieldPath = 'license';\n\n // Optional field - undefined/null is valid\n if (license === undefined || license === null) {\n return errors;\n }\n\n // If provided, must be string\n if (typeof license !== 'string') {\n errors.push(`${fieldPath}: Expected string, received ${typeof license}`);\n }\n\n return errors;\n}\n\n/**\n * Validate skill compatibility notes (optional).\n * Accepts string or any JSON-serializable value for flexibility with external skills.\n *\n * @param compatibility - The compatibility value to validate\n * @returns Array of error messages (empty if valid)\n */\nfunction validateSkillCompatibility(_compatibility: unknown): string[] {\n // Optional field - any value is allowed (string, object, array, etc.)\n // External skills don't always follow the spec strictly\n return [];\n}\n\n/**\n * Validate skill metadata field (optional Record<string, unknown>).\n * Accepts any values (not just strings) for flexibility with external skills.\n *\n * @param metadata - The metadata object to validate\n * @returns Array of error messages (empty if valid)\n */\nfunction validateSkillMetadataField(metadata: unknown): string[] {\n const errors: string[] = [];\n const fieldPath = 'metadata';\n\n // Optional field - undefined/null is valid\n if (metadata === undefined || metadata === null) {\n return errors;\n }\n\n // If provided, must be object (but values can be anything)\n if (typeof metadata !== 'object' || Array.isArray(metadata)) {\n errors.push(`${fieldPath}: Expected object, received ${Array.isArray(metadata) ? 'array' : typeof metadata}`);\n return errors;\n }\n\n // Allow any values - external skills use arrays, objects, etc.\n return errors;\n}\n\nfunction validateUserInvocable(userInvocable: unknown): string[] {\n if (userInvocable === undefined || typeof userInvocable === 'boolean') return [];\n return [`user-invocable: Expected boolean, received ${typeof userInvocable}`];\n}\n\n// =============================================================================\n// Validation Helpers\n// =============================================================================\n\n/**\n * Rough token estimate (words * 1.3)\n * This is a simple heuristic; actual token counts vary by model\n */\nfunction estimateTokens(text: string): number {\n const words = text.split(/\\s+/).filter(Boolean).length;\n return Math.ceil(words * 1.3);\n}\n\n/**\n * Count lines in text\n */\nfunction countLines(text: string): number {\n return text.split('\\n').length;\n}\n\n// =============================================================================\n// Main Validation Function\n// =============================================================================\n\n/**\n * Validate skill metadata with optional content warnings.\n *\n * @param options.metadata - The skill metadata to validate\n * @param options.directoryName - The directory name (must match skill name)\n * @param options.instructions - Optional instructions content for token/line warnings\n * @returns Validation result with errors and warnings\n *\n * @example\n * ```typescript\n * const result = validateSkillMetadata({\n * metadata: { name: 'my-skill', description: 'A helpful skill' },\n * directoryName: 'my-skill',\n * instructions: '# Instructions\\n...',\n * });\n *\n * if (!result.valid) {\n * console.error('Validation errors:', result.errors);\n * }\n * if (result.warnings.length > 0) {\n * console.warn('Warnings:', result.warnings);\n * }\n * ```\n */\nexport function validateSkillMetadata({\n metadata,\n directoryName,\n instructions,\n}: {\n metadata: unknown;\n directoryName?: string;\n instructions?: string;\n}): SkillValidationResult {\n const errors: string[] = [];\n const warnings: string[] = [];\n\n // Check that metadata is an object\n if (typeof metadata !== 'object' || metadata === null || Array.isArray(metadata)) {\n errors.push(\n `Expected object, received ${metadata === null ? 'null' : Array.isArray(metadata) ? 'array' : typeof metadata}`,\n );\n return { valid: false, errors, warnings };\n }\n\n const data = metadata as Record<string, unknown>;\n\n // Validate each field\n errors.push(...validateSkillName(data.name));\n errors.push(...validateSkillDescription(data.description));\n errors.push(...validateSkillLicense(data.license));\n errors.push(...validateSkillCompatibility(data.compatibility));\n errors.push(...validateUserInvocable(data['user-invocable']));\n errors.push(...validateSkillMetadataField(data.metadata));\n\n // Check directory name match (only if no name errors and name is valid)\n if (directoryName && typeof data.name === 'string' && data.name !== directoryName) {\n errors.push(`Skill name \"${data.name}\" must match directory name \"${directoryName}\"`);\n }\n\n // Check instruction limits (warnings only)\n if (instructions) {\n const lineCount = countLines(instructions);\n const tokenEstimate = estimateTokens(instructions);\n\n if (lineCount > SKILL_LIMITS.MAX_INSTRUCTION_LINES) {\n warnings.push(\n `Instructions have ${lineCount} lines (recommended: <${SKILL_LIMITS.MAX_INSTRUCTION_LINES}). Consider moving content to references/.`,\n );\n }\n\n if (tokenEstimate > SKILL_LIMITS.MAX_INSTRUCTION_TOKENS) {\n warnings.push(\n `Instructions have ~${tokenEstimate} estimated tokens (recommended: <${SKILL_LIMITS.MAX_INSTRUCTION_TOKENS}). Consider moving content to references/.`,\n );\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n}\n\n/**\n * Result of validating raw SKILL.md content\n */\nexport interface SkillContentValidationResult extends SkillValidationResult {\n /** Raw parsed frontmatter fields (present when frontmatter could be parsed; may be invalid) */\n metadata?: Record<string, unknown>;\n /** Markdown body after the frontmatter, trimmed */\n instructions?: string;\n}\n\n/**\n * Parse SKILL.md content into frontmatter fields and body.\n * Throws if the frontmatter is not valid YAML.\n * @internal\n */\nexport function extractSkillFrontmatter(content: string): { metadata: SkillMetadataInput; instructions: string } {\n const parsed = parseFrontmatter(content);\n // Raw fields are validated by validateSkillMetadata; keep them loosely typed here.\n const data: Record<string, any> = parsed.data;\n return {\n metadata: {\n name: data.name,\n description: data.description,\n license: data.license,\n compatibility: data.compatibility,\n 'user-invocable': data['user-invocable'],\n metadata: data.metadata,\n },\n instructions: parsed.content.trim(),\n };\n}\n\n/**\n * Validate raw SKILL.md content (frontmatter + body) using the same rules\n * applied when skills are loaded. Pure: no filesystem access or logging.\n *\n * @param options.content - Full SKILL.md file content\n * @param options.directoryName - Name of the directory the skill will live in (name must match)\n *\n * @example\n * ```typescript\n * const result = validateSkillContent({ content: skillMd, directoryName: 'my-skill' });\n * if (!result.valid) throw new Error(result.errors.join('\\n'));\n * ```\n */\nexport function validateSkillContent({\n content,\n directoryName,\n}: {\n content: string;\n directoryName?: string;\n}): SkillContentValidationResult {\n let extracted: ReturnType<typeof extractSkillFrontmatter>;\n try {\n extracted = extractSkillFrontmatter(content);\n } catch (error) {\n return {\n valid: false,\n errors: [`Invalid frontmatter: ${error instanceof Error ? error.message : String(error)}`],\n warnings: [],\n };\n }\n return {\n ...validateSkillMetadata({\n metadata: extracted.metadata,\n directoryName,\n instructions: extracted.instructions,\n }),\n metadata: { ...extracted.metadata },\n instructions: extracted.instructions,\n };\n}\n","/**\n * WorkspaceSkills - Skills implementation.\n *\n * Provides discovery and search operations for skills stored\n * in skills paths. All operations are async.\n */\n\nimport { isGlobPattern, resolvePathPattern } from '../glob';\nimport type { ReaddirEntry } from '../glob';\nimport type { IndexDocument, SearchResult } from '../search';\nimport { extractSkillFrontmatter, validateSkillMetadata } from './schemas';\nimport type { SkillSource as SkillSourceInterface } from './skill-source';\nimport type {\n ContentSource,\n Skill,\n SkillMetadata,\n SkillSearchResult,\n SkillSearchOptions,\n WorkspaceSkills,\n SkillsResolver,\n SkillsContext,\n} from './types';\n\n// =============================================================================\n// Internal Types\n// =============================================================================\n\n/**\n * Minimal search engine interface - only the methods we actually use.\n * This allows both the real SearchEngine and test mocks to be used.\n */\ninterface SkillSearchEngine {\n index(doc: IndexDocument): Promise<void>;\n remove?(id: string): Promise<void>;\n search(\n query: string,\n options?: { topK?: number; minScore?: number; mode?: 'bm25' | 'vector' | 'hybrid' },\n ): Promise<SearchResult[]>;\n clear(): void;\n}\n\ninterface RemovableSkillSearchEngine extends SkillSearchEngine {\n remove(id: string): Promise<void>;\n}\n\ninterface InternalSkill extends Skill {\n /** Content for BM25 indexing (instructions + all references) */\n indexableContent: string;\n}\n\ninterface SharedSearchState {\n documentIds: Set<string>;\n}\n\n/** @internal Prefix of every search document ID owned by a request-scoped skills view. */\nexport const SKILL_SCOPE_DOCUMENT_PREFIX = 'skill-scope:';\n\n/** Search document ID suffix for a skill's name + description document. */\nconst SKILL_METADATA_SOURCE = 'SKILL.md#metadata';\n\n// =============================================================================\n// WorkspaceSkillsImpl\n// =============================================================================\n\n/**\n * Configuration for WorkspaceSkillsImpl\n */\nexport interface WorkspaceSkillsImplConfig {\n /**\n * Source for loading skills.\n */\n source: SkillSourceInterface;\n /**\n * Paths to scan for skills.\n * Can be a static array or a function that returns paths based on context.\n */\n skills: SkillsResolver;\n /** Search engine for skill search (optional) */\n searchEngine?: SkillSearchEngine;\n /** Validate skills on load (default: true) */\n validateOnLoad?: boolean;\n /** Assert that the owning workspace can still serve skill operations. */\n assertAvailable?: () => void;\n /**\n * Check SKILL.md file mtime in addition to directory mtime for staleness detection.\n * Enables detection of in-place file edits (e.g., fixing validation errors).\n * Increases stat calls - recommended for local development only.\n * Default: false\n */\n checkSkillFileMtime?: boolean;\n /** @internal Namespace used to isolate a dynamic resolver's search documents. */\n searchNamespace?: string;\n /** @internal Search document registry shared by request-scoped views. */\n sharedSearchState?: SharedSearchState;\n /**\n * @internal Called before this view re-indexes after `releaseSearchIndex()`,\n * so the owner can re-admit it into its bounded cache first.\n */\n onIndexReadmit?: () => Promise<void>;\n /**\n * @internal Called when this view's last in-flight index-dependent operation\n * finishes, so the owner can evict it if the cache is over its bound.\n */\n onIndexIdle?: () => Promise<void>;\n}\n\n/**\n * Implementation of WorkspaceSkills interface.\n */\nexport class WorkspaceSkillsImpl implements WorkspaceSkills {\n readonly #source: SkillSourceInterface;\n readonly #skillsResolver: SkillsResolver;\n readonly #searchEngine?: SkillSearchEngine;\n readonly #validateOnLoad: boolean;\n readonly #assertAvailable?: () => void;\n readonly #checkSkillFileMtime: boolean;\n readonly #searchNamespace?: string;\n readonly #sharedSearchState: SharedSearchState;\n readonly #onIndexReadmit?: () => Promise<void>;\n readonly #onIndexIdle?: () => Promise<void>;\n\n /** Search documents were released by the owner; re-index on next search use. */\n #indexReleased = false;\n #readmitPromise: Promise<void> | null = null;\n /** Index-dependent operations currently in flight on this view. */\n #inFlight = 0;\n readonly #resolvedChildren = new Set<WorkspaceSkillsImpl>();\n\n /** Request-scoped views for dynamic resolvers, cached by request and canonical path set. */\n readonly #scopedByRequest = new WeakMap<object, Promise<WorkspaceSkills>>();\n readonly #scopedByPaths = new Map<string, Promise<WorkspaceSkills>>();\n\n /** Map of skill name -> array of candidates (supports same-named skills from different sources) */\n #skills: Map<string, InternalSkill[]> = new Map();\n\n /** Map of remapped location -> skill path, registered by SkillsProcessor formatLocation overrides */\n #locationAliases: Map<string, string> = new Map();\n\n /** Whether skills have been discovered */\n #initialized = false;\n\n /** Promise for ongoing initialization (prevents concurrent discovery) */\n #initPromise: Promise<void> | null = null;\n\n /** Timestamp of last skills discovery (for staleness check) */\n #lastDiscoveryTime = 0;\n\n /** Currently resolved skills paths (used to detect changes) */\n #resolvedPaths: string[] = [];\n\n /** Cached glob-resolved directories and per-pattern resolve timestamps */\n #globDirCache: Map<string, string[]> = new Map();\n #globResolveTimes: Map<string, number> = new Map();\n static readonly GLOB_RESOLVE_INTERVAL = 5_000; // Re-walk glob dirs every 5s\n // Staleness walks issue a stat/readdir per skill root and a stat per skill\n // directory; over remote sandbox filesystems each of those is a network\n // round-trip costing hundreds of milliseconds. 30s bounds how often any\n // caller (turn-boundary processors and skill tools alike) pays that walk,\n // so skill edits are picked up within at most 30s of the last check.\n static readonly STALENESS_CHECK_COOLDOWN = 30_000;\n\n /** In-flight refresh, shared by concurrent refresh() callers */\n #refreshPromise: Promise<void> | null = null;\n\n /** In-flight maybeRefresh, shared so overlapping callers run one staleness walk */\n #maybeRefreshPromise: Promise<void> | null = null;\n\n constructor(config: WorkspaceSkillsImplConfig) {\n this.#source = config.source;\n this.#skillsResolver = config.skills;\n this.#searchEngine = config.searchEngine;\n this.#validateOnLoad = config.validateOnLoad ?? true;\n this.#assertAvailable = config.assertAvailable;\n this.#checkSkillFileMtime = config.checkSkillFileMtime ?? false;\n this.#searchNamespace = config.searchNamespace;\n this.#sharedSearchState = config.sharedSearchState ?? { documentIds: new Set() };\n this.#onIndexReadmit = config.onIndexReadmit;\n this.#onIndexIdle = config.onIndexIdle;\n }\n\n /**\n * @internal True while this view (or a path-scoped child) is inside an\n * index-dependent operation. Owners must not release a busy view's index.\n */\n get isIndexBusy(): boolean {\n if (this.#inFlight > 0) return true;\n for (const child of this.#resolvedChildren) {\n if (child.isIndexBusy) return true;\n }\n return false;\n }\n\n async #withIndexPinned<T>(fn: () => Promise<T>): Promise<T> {\n this.#inFlight++;\n try {\n return await fn();\n } finally {\n this.#inFlight--;\n if (this.#inFlight === 0) {\n await this.#onIndexIdle?.();\n }\n }\n }\n\n /**\n * @internal Drop every search document this view (and its path-scoped\n * children) indexed. The catalog stays intact; the next search-dependent\n * operation re-admits the view via `onIndexReadmit` and re-indexes.\n */\n async releaseSearchIndex(): Promise<void> {\n if (!this.#searchEngine) return;\n this.#indexReleased = true;\n for (const candidates of this.#skills.values()) {\n for (const skill of candidates) {\n await this.#removeSkillFromIndex(skill);\n }\n }\n for (const child of this.#resolvedChildren) {\n await child.releaseSearchIndex();\n }\n }\n\n /**\n * Re-index the current catalog if the search documents were released.\n * Returns true when a re-index happened (the index is then fully current).\n */\n async #readmitIndexIfReleased(): Promise<boolean> {\n if (!this.#indexReleased || !this.#searchEngine) return false;\n this.#readmitPromise ??= (async () => {\n // Clear before admitting so an eviction that lands while admission is in\n // flight is not overwritten and short-circuits the loop below.\n this.#indexReleased = false;\n await this.#onIndexReadmit?.();\n for (const candidates of this.#skills.values()) {\n for (const skill of candidates) {\n if (this.#indexReleased) break;\n await this.#indexSkill(skill);\n }\n }\n // Evicted again while re-indexing: a skill that was mid-index when\n // release ran may have landed after release removed it. Sweep so the\n // evicted namespace holds no documents.\n if (this.#indexReleased) {\n for (const candidates of this.#skills.values()) {\n for (const skill of candidates) {\n await this.#removeSkillFromIndex(skill);\n }\n }\n }\n })().finally(() => {\n this.#readmitPromise = null;\n });\n await this.#readmitPromise;\n return true;\n }\n\n async getScoped(context?: SkillsContext): Promise<WorkspaceSkills> {\n if (Array.isArray(this.#skillsResolver)) {\n return this;\n }\n\n const requestContext = context?.requestContext;\n if (requestContext && typeof requestContext === 'object') {\n const cached = this.#scopedByRequest.get(requestContext);\n if (cached) return cached;\n\n const scoped = this.#createScoped(context).catch(error => {\n this.#scopedByRequest.delete(requestContext);\n throw error;\n });\n this.#scopedByRequest.set(requestContext, scoped);\n return scoped;\n }\n\n return this.#createScoped(context);\n }\n\n async #createScoped(context?: SkillsContext): Promise<WorkspaceSkills> {\n const paths = await this.#resolvePaths(context);\n const key = [...paths].sort().join('\\n');\n const cached = this.#scopedByPaths.get(key);\n if (cached) return cached;\n\n const child = new WorkspaceSkillsImpl({\n source: this.#source,\n skills: paths,\n searchEngine: this.#searchEngine,\n validateOnLoad: this.#validateOnLoad,\n assertAvailable: this.#assertAvailable,\n checkSkillFileMtime: this.#checkSkillFileMtime,\n // Nest under this instance's namespace so views built for different\n // resolved sources never share search documents for the same path set.\n searchNamespace: this.#searchNamespace\n ? `${this.#searchNamespace}/${encodeURIComponent(key)}`\n : encodeURIComponent(key),\n sharedSearchState: this.#sharedSearchState,\n onIndexReadmit: this.#onIndexReadmit,\n onIndexIdle: this.#onIndexIdle,\n });\n this.#resolvedChildren.add(child);\n const scoped = Promise.resolve<WorkspaceSkills>(child);\n this.#scopedByPaths.set(key, scoped);\n return scoped;\n }\n\n // ===========================================================================\n // Discovery\n // ===========================================================================\n\n async list(): Promise<SkillMetadata[]> {\n await this.#ensureInitialized();\n\n const results: SkillMetadata[] = [];\n for (const candidates of this.#skills.values()) {\n const canonicalCandidates = await this.#dedupeCanonicalCandidates(candidates);\n for (const skill of canonicalCandidates) {\n results.push({\n name: skill.name,\n path: skill.path,\n description: skill.description,\n license: skill.license,\n compatibility: skill.compatibility,\n 'user-invocable': skill['user-invocable'],\n metadata: skill.metadata,\n });\n }\n }\n return results;\n }\n\n async get(name: string): Promise<Skill | null> {\n await this.#ensureInitialized();\n // Try name-based lookup first, then fall back to path-based (escape hatch),\n // then to registered location aliases (formatLocation overrides)\n const skill = (await this.#resolveByName(name)) ?? this.#resolveByPath(name) ?? this.#resolveByAlias(name);\n if (!skill) return null;\n\n // Return without internal indexableContent field\n const { indexableContent: _, ...skillData } = skill;\n return skillData;\n }\n\n async has(name: string): Promise<boolean> {\n await this.#ensureInitialized();\n return ((await this.#resolveByName(name)) ?? this.#resolveByPath(name) ?? this.#resolveByAlias(name)) !== null;\n }\n\n /**\n * Register an alternate location string that resolves to the skill at `skillPath`.\n * Called by SkillsProcessor when a `formatLocation` override remaps the advertised\n * location, so the `skill` and `skill_read` tools can resolve the remapped\n * location back to the underlying skill.\n *\n * Both the exact location and its `/SKILL.md`-stripped form are registered so\n * lookups succeed whether or not the model preserves the suffix.\n */\n registerLocationAlias(location: string, skillPath: string): void {\n this.#locationAliases.set(location, skillPath);\n const normalized = location.replace(/\\/SKILL\\.md$/, '');\n if (normalized !== location) {\n this.#locationAliases.set(normalized, skillPath);\n }\n }\n\n // ===========================================================================\n // Skill Resolution (Private)\n // ===========================================================================\n\n /**\n * Resolve a skill by name with tie-breaking when multiple candidates exist.\n * Priority: local > managed > external, then alphabetical path.\n */\n async #resolveByName(name: string): Promise<InternalSkill | null> {\n const candidates = this.#skills.get(name);\n if (!candidates || candidates.length === 0) return null;\n return this.#tieBreak(candidates);\n }\n\n /**\n * Resolve a skill by exact path (escape hatch for disambiguation).\n * Searches across all candidate arrays.\n * Accepts paths with or without a trailing `/SKILL.md` suffix, since\n * SkillsProcessor.formatLocation() exposes `${path}/SKILL.md` to the LLM.\n */\n #resolveByPath(skillPath: string): InternalSkill | null {\n const normalized = skillPath.replace(/\\/SKILL\\.md$/, '');\n for (const candidates of this.#skills.values()) {\n const match = candidates.find(s => s.path === normalized);\n if (match) return match;\n }\n return null;\n }\n\n /**\n * Resolve a skill via a registered location alias (formatLocation override).\n * Tried last so canonical names and paths always win over aliases.\n */\n #resolveByAlias(location: string): InternalSkill | null {\n const target =\n this.#locationAliases.get(location) ?? this.#locationAliases.get(location.replace(/\\/SKILL\\.md$/, ''));\n if (!target) return null;\n return this.#resolveByPath(target);\n }\n\n async #getCanonicalSkillPath(skillPath: string): Promise<string> {\n if (!this.#source.realpath) return skillPath;\n\n try {\n return await this.#source.realpath(skillPath);\n } catch {\n return skillPath;\n }\n }\n\n async #dedupeCanonicalCandidates(candidates: InternalSkill[]): Promise<InternalSkill[]> {\n const canonicalGroups = new Map<string, InternalSkill[]>();\n for (const candidate of candidates) {\n const canonicalPath = await this.#getCanonicalSkillPath(candidate.path);\n const group = canonicalGroups.get(canonicalPath) ?? [];\n group.push(candidate);\n canonicalGroups.set(canonicalPath, group);\n }\n\n const SOURCE_PRIORITY: Record<string, number> = { local: 0, managed: 1, external: 2 };\n return [...canonicalGroups.values()].map(\n group =>\n [...group].sort((a, b) => {\n const aPri = SOURCE_PRIORITY[a.source.type] ?? 99;\n const bPri = SOURCE_PRIORITY[b.source.type] ?? 99;\n if (aPri !== bPri) return aPri - bPri;\n return a.path.localeCompare(b.path);\n })[0]!,\n );\n }\n\n /**\n * Pick the winning skill from an array of same-named candidates.\n * When there's only one candidate, returns it directly (no warning).\n * When there are multiple, de-duplicates alias paths that point to the same\n * canonical skill, then applies source-type priority and warns.\n *\n * Priority: local (0) > managed (1) > external (2).\n * Throws if source-type priority can't resolve the tie (e.g., two distinct local skills with same name).\n */\n async #tieBreak(candidates: InternalSkill[]): Promise<InternalSkill | null> {\n if (candidates.length === 0) return null;\n if (candidates.length === 1) return candidates[0]!;\n\n const deduped = await this.#dedupeCanonicalCandidates(candidates);\n\n if (deduped.length === 1) return deduped[0]!;\n\n const SOURCE_PRIORITY: Record<string, number> = { local: 0, managed: 1, external: 2 };\n const sorted = [...deduped].sort((a, b) => {\n const aPri = SOURCE_PRIORITY[a.source.type] ?? 99;\n const bPri = SOURCE_PRIORITY[b.source.type] ?? 99;\n if (aPri !== bPri) return aPri - bPri;\n return a.path.localeCompare(b.path);\n });\n\n const winner = sorted[0]!;\n const runnerUp = sorted[1]!;\n\n // Error if source-type priority can't break the tie\n if (winner.source.type === runnerUp.source.type) {\n const paths = sorted\n .filter(s => s.source.type === winner.source.type)\n .map(s => `\"${s.path}\"`)\n .join(', ');\n throw new Error(\n `[WorkspaceSkills] Cannot resolve skill \"${winner.name}\": multiple ${winner.source.type} skills found at ${paths}. ` +\n `Rename one or move it to a different source type.`,\n );\n }\n\n console.warn(\n `[WorkspaceSkills] Multiple skills named \"${winner.name}\" found. ` +\n `Using \"${winner.path}\" (source: ${winner.source.type}). ` +\n `Other candidates: ${sorted\n .slice(1)\n .map(s => `\"${s.path}\" (${s.source.type})`)\n .join(', ')}`,\n );\n\n return winner;\n }\n\n async refresh(): Promise<void> {\n this.#assertAvailable?.();\n\n // Coalesce concurrent refresh() calls onto one in-flight rebuild.\n // Invariant: #refreshPromise is never non-null-and-satisfied - the\n // success path clears it synchronously inside #doRefresh, so a caller\n // arriving in the settle microtask gap starts a fresh rebuild instead of\n // coalescing onto one that may have used stale paths.\n if (this.#refreshPromise) {\n return this.#refreshPromise;\n }\n const inFlight = this.#withIndexPinned(() => this.#doRefresh()).finally(() => {\n // Rejection path only; the success path already cleared it.\n if (this.#refreshPromise === inFlight) {\n this.#refreshPromise = null;\n }\n });\n this.#refreshPromise = inFlight;\n return inFlight;\n }\n\n /**\n * Rebuild the catalog into fresh state and swap it in atomically.\n *\n * The current #skills map keeps serving list()/get() for the whole\n * re-discovery; only when the new catalog is complete is #skills swapped,\n * so readers always see a complete catalog (old or new, never partial).\n * The shared search engine is then reconciled entry-by-entry (it also\n * holds workspace content and cannot be rebuilt wholesale).\n */\n async #doRefresh(): Promise<void> {\n // Loop: a coalesced maybeRefresh may swap #resolvedPaths while a rebuild\n // is in flight (the in-flight walk captured the old paths). Re-run the\n // rebuild until the paths it used are still current at completion, so a\n // paths-changed caller is never satisfied by a stale-path rebuild.\n for (;;) {\n const pathsAtStart = this.#resolvedPaths;\n const newSkills = new Map<string, InternalSkill[]>();\n await this.#discoverSkills(newSkills);\n\n // Snapshot the currently indexed skills just before the swap\n const oldSkills = this.#skills;\n this.#skills = newSkills;\n this.#initialized = true;\n\n await this.#reconcileIndex(oldSkills, newSkills);\n\n if (this.#resolvedPaths === pathsAtStart) {\n // Clear the coalescing handle in the same synchronous step as the\n // success decision. If this waited for the wrapper's .finally (one\n // microtask after settle), a paths-changed refresh() landing in that\n // gap would coalesce onto this already-finished rebuild and its new\n // paths would never be discovered.\n this.#refreshPromise = null;\n return;\n }\n }\n }\n\n /**\n * Reconcile the shared search index after a catalog swap:\n * remove entries for skills that disappeared, re-index skills whose\n * content changed, index new skills. Unchanged skills are left alone.\n * Transient index states during reconcile are acceptable; catalog\n * consistency is guaranteed by the map swap, not by the index.\n */\n async #reconcileIndex(\n oldSkills: Map<string, InternalSkill[]>,\n newSkills: Map<string, InternalSkill[]>,\n ): Promise<void> {\n // A released view re-indexes the whole (already swapped) catalog instead.\n if (await this.#readmitIndexIfReleased()) return;\n\n const flatten = (map: Map<string, InternalSkill[]>): Map<string, InternalSkill> => {\n const byPath = new Map<string, InternalSkill>();\n for (const candidates of map.values()) {\n for (const skill of candidates) {\n byPath.set(skill.path, skill);\n }\n }\n return byPath;\n };\n\n const oldByPath = flatten(oldSkills);\n const newByPath = flatten(newSkills);\n\n for (const [path, oldSkill] of oldByPath) {\n if (!newByPath.has(path)) {\n await this.#removeSkillFromIndex(oldSkill);\n }\n }\n\n for (const [path, newSkill] of newByPath) {\n const oldSkill = oldByPath.get(path);\n const unchanged =\n oldSkill &&\n oldSkill.instructions === newSkill.instructions &&\n oldSkill.name === newSkill.name &&\n oldSkill.description === newSkill.description &&\n oldSkill.references.length === newSkill.references.length &&\n oldSkill.references.every((r, i) => r === newSkill.references[i]);\n if (unchanged) continue;\n\n if (oldSkill) {\n // Remove first so reference docs dropped by the new version don't linger\n await this.#removeSkillFromIndex(oldSkill);\n }\n await this.#indexSkill(newSkill);\n }\n }\n\n async maybeRefresh(context?: SkillsContext): Promise<void> {\n // Ensure initial discovery is complete\n await this.#ensureInitialized();\n\n // Coalesce overlapping revalidations (e.g. skills processor and\n // skill-search in the same turn) onto one staleness walk\n if (this.#maybeRefreshPromise) {\n return this.#maybeRefreshPromise;\n }\n this.#maybeRefreshPromise = this.#doMaybeRefresh(context).finally(() => {\n this.#maybeRefreshPromise = null;\n });\n return this.#maybeRefreshPromise;\n }\n\n async #doMaybeRefresh(context?: SkillsContext): Promise<void> {\n // Resolve current paths (may be dynamic based on context)\n const currentPaths = await this.#resolvePaths(context);\n\n // Check if paths have changed (for dynamic resolvers)\n const pathsChanged = !this.#arePathsEqual(this.#resolvedPaths, currentPaths);\n if (pathsChanged) {\n // Paths changed - need full refresh with new paths\n this.#resolvedPaths = currentPaths;\n await this.refresh();\n return;\n }\n\n // Check if any skills path has been modified since last discovery\n const isStale = await this.#isSkillsPathStale();\n if (isStale) {\n await this.refresh();\n }\n }\n\n async addSkill(skillPath: string): Promise<void> {\n await this.#ensureInitialized();\n return this.#withIndexPinned(() => this.#doAddSkill(skillPath));\n }\n\n async #doAddSkill(skillPath: string): Promise<void> {\n await this.#readmitIndexIfReleased();\n\n // Determine SKILL.md path and dirName\n let skillFilePath: string;\n let dirName: string;\n if (isSkillFilePath(skillPath)) {\n skillFilePath = skillPath;\n dirName = splitPathSegments(this.#getParentPath(skillPath)).pop() || 'unknown';\n } else {\n skillFilePath = this.#joinPath(skillPath, 'SKILL.md');\n dirName = splitPathSegments(skillPath).pop() || 'unknown';\n }\n\n // Determine source from existing resolved paths\n const source = this.#inferSource(skillPath);\n\n // Parse and add to cache\n const skill = await this.#parseSkillFile(skillFilePath, dirName, source);\n\n // Remove old index entries if skill already exists at same path (for update case)\n const candidates = this.#skills.get(skill.name) ?? [];\n const existingIdx = candidates.findIndex(s => s.path === skill.path);\n if (existingIdx >= 0) {\n await this.#removeSkillFromIndex(candidates[existingIdx]!);\n candidates[existingIdx] = skill;\n } else {\n candidates.push(skill);\n }\n this.#skills.set(skill.name, candidates);\n await this.#indexSkill(skill);\n\n // Update discovery time so maybeRefresh() doesn't trigger full scan\n this.#lastDiscoveryTime = Date.now();\n }\n\n async removeSkill(skillName: string): Promise<void> {\n await this.#ensureInitialized();\n\n // Resolve by name (tie-break winner), then fall back to path-based lookup\n const skill = (await this.#resolveByName(skillName)) ?? this.#resolveByPath(skillName);\n if (!skill) return;\n\n // Remove from search index\n await this.#removeSkillFromIndex(skill);\n\n // Remove from candidates array\n const candidates = this.#skills.get(skill.name);\n if (candidates) {\n const idx = candidates.findIndex(s => s.path === skill.path);\n if (idx >= 0) candidates.splice(idx, 1);\n if (candidates.length === 0) {\n this.#skills.delete(skill.name);\n }\n }\n\n // Update discovery time so maybeRefresh() doesn't trigger full scan\n this.#lastDiscoveryTime = Date.now();\n }\n\n /**\n * Resolve skills paths from the resolver (static array or function).\n */\n async #resolvePaths(context?: SkillsContext): Promise<string[]> {\n if (Array.isArray(this.#skillsResolver)) {\n return this.#skillsResolver;\n }\n return this.#skillsResolver(context ?? {});\n }\n\n /**\n * Compare two path arrays for equality (order-independent).\n */\n #arePathsEqual(a: string[], b: string[]): boolean {\n if (a.length !== b.length) return false;\n const sortedA = [...a].sort();\n const sortedB = [...b].sort();\n return sortedA.every((path, i) => path === sortedB[i]);\n }\n\n // ===========================================================================\n // Search\n // ===========================================================================\n\n async search(query: string, options: SkillSearchOptions = {}): Promise<SkillSearchResult[]> {\n await this.#ensureInitialized();\n\n if (!this.#searchEngine) {\n // Fall back to simple text matching if no search engine\n return this.#simpleSearch(query, options);\n }\n return this.#withIndexPinned(() => this.#indexedSearch(query, options));\n }\n\n async #indexedSearch(query: string, options: SkillSearchOptions): Promise<SkillSearchResult[]> {\n await this.#readmitIndexIfReleased();\n\n const { topK = 5, minScore, skillNames, includeReferences = true, mode } = options;\n\n // Ask the search engine for enough rows to survive post-search filtering and\n // canonical alias de-duplication before applying the final topK.\n const totalIndexedDocuments = this.#searchNamespace\n ? this.#sharedSearchState.documentIds.size\n : [...this.#skills.values()].reduce(\n (count, candidates) =>\n count + candidates.reduce((skillCount, skill) => skillCount + 2 + skill.references.length, 0),\n 0,\n );\n const expandedTopK = Math.max(skillNames ? topK * 3 : topK, totalIndexedDocuments);\n\n // Delegate to SearchEngine\n const searchResults = await this.#searchEngine!.search(query, {\n topK: expandedTopK,\n minScore,\n mode,\n });\n\n const results: SkillSearchResult[] = [];\n const seenCanonicalSources = new Set<string>();\n\n for (const result of searchResults) {\n const skillPath = result.metadata?.skillPath as string;\n const source = result.metadata?.source as string;\n\n if (!skillPath || !source) continue;\n if (this.#searchNamespace && result.metadata?.skillScope !== this.#searchNamespace) continue;\n\n // Map path back to the canonical skill winner for filtering and results.\n const matchedSkill = this.#resolveByPath(skillPath);\n if (!matchedSkill) continue;\n\n const skill = (await this.#resolveByName(matchedSkill.name)) ?? matchedSkill;\n\n // Filter by skill names if specified\n if (skillNames && !skillNames.includes(skill.name)) {\n continue;\n }\n\n // Filter out references if not included\n if (!includeReferences && source !== 'SKILL.md') {\n continue;\n }\n\n const canonicalSourceKey = `${skill.path}:${source}`;\n if (seenCanonicalSources.has(canonicalSourceKey)) {\n continue;\n }\n seenCanonicalSources.add(canonicalSourceKey);\n\n // The name + description document isn't part of SKILL.md, so its line\n // numbers would point at the wrong lines of the file.\n const isMetadataHit = result.id === this.#searchDocumentId(skillPath, SKILL_METADATA_SOURCE);\n\n results.push({\n skillName: skill.name,\n skillPath: skill.path,\n source,\n // The metadata document starts with the name, which the result already carries\n content: isMetadataHit ? skill.description : result.content,\n score: result.score,\n lineRange: isMetadataHit ? undefined : result.lineRange,\n scoreDetails: result.scoreDetails,\n });\n\n if (results.length >= topK) break;\n }\n\n return results;\n }\n\n // ===========================================================================\n // Single-item Accessors\n // ===========================================================================\n\n async getReference(skillName: string, referencePath: string): Promise<string | null> {\n await this.#ensureInitialized();\n\n const skill = (await this.#resolveByName(skillName)) ?? this.#resolveByPath(skillName);\n if (!skill) return null;\n\n const safeRefPath = this.#assertRelativePath(referencePath, 'reference');\n const refFilePath = this.#joinPath(skill.path, safeRefPath);\n\n if (!(await this.#source.exists(refFilePath))) {\n return null;\n }\n\n try {\n const content = await this.#source.readFile(refFilePath);\n return typeof content === 'string' ? content : content.toString('utf-8');\n } catch {\n return null;\n }\n }\n\n async getScript(skillName: string, scriptPath: string): Promise<string | null> {\n await this.#ensureInitialized();\n\n const skill = (await this.#resolveByName(skillName)) ?? this.#resolveByPath(skillName);\n if (!skill) return null;\n\n const safeScriptPath = this.#assertRelativePath(scriptPath, 'script');\n const scriptFilePath = this.#joinPath(skill.path, safeScriptPath);\n\n if (!(await this.#source.exists(scriptFilePath))) {\n return null;\n }\n\n try {\n const content = await this.#source.readFile(scriptFilePath);\n return typeof content === 'string' ? content : content.toString('utf-8');\n } catch {\n return null;\n }\n }\n\n async getAsset(skillName: string, assetPath: string): Promise<Buffer | null> {\n await this.#ensureInitialized();\n\n const skill = (await this.#resolveByName(skillName)) ?? this.#resolveByPath(skillName);\n if (!skill) return null;\n\n const safeAssetPath = this.#assertRelativePath(assetPath, 'asset');\n const assetFilePath = this.#joinPath(skill.path, safeAssetPath);\n\n if (!(await this.#source.exists(assetFilePath))) {\n return null;\n }\n\n try {\n const content = await this.#source.readFile(assetFilePath);\n return typeof content === 'string' ? Buffer.from(content, 'utf-8') : content;\n } catch {\n return null;\n }\n }\n\n // ===========================================================================\n // Listing Accessors\n // ===========================================================================\n\n async listReferences(skillName: string): Promise<string[]> {\n await this.#ensureInitialized();\n const skill = (await this.#resolveByName(skillName)) ?? this.#resolveByPath(skillName);\n return skill?.references ?? [];\n }\n\n async listScripts(skillName: string): Promise<string[]> {\n await this.#ensureInitialized();\n const skill = (await this.#resolveByName(skillName)) ?? this.#resolveByPath(skillName);\n return skill?.scripts ?? [];\n }\n\n async listAssets(skillName: string): Promise<string[]> {\n await this.#ensureInitialized();\n const skill = (await this.#resolveByName(skillName)) ?? this.#resolveByPath(skillName);\n return skill?.assets ?? [];\n }\n\n // ===========================================================================\n // Private Methods\n // ===========================================================================\n\n /**\n * Ensure skills have been discovered.\n * Uses a promise to prevent concurrent discovery.\n */\n async #ensureInitialized(): Promise<void> {\n this.#assertAvailable?.();\n\n if (this.#initialized) {\n return;\n }\n\n // If initialization is already in progress, wait for it\n if (this.#initPromise) {\n await this.#initPromise;\n return;\n }\n\n // Start initialization and store the promise\n this.#initPromise = (async () => {\n try {\n // Resolve paths on first initialization (uses empty context)\n if (this.#resolvedPaths.length === 0) {\n this.#resolvedPaths = await this.#resolvePaths();\n }\n const newSkills = new Map<string, InternalSkill[]>();\n await this.#discoverSkills(newSkills);\n const oldSkills = this.#skills;\n this.#skills = newSkills;\n this.#initialized = true;\n await this.#reconcileIndex(oldSkills, newSkills);\n } finally {\n this.#initPromise = null;\n }\n })();\n\n await this.#initPromise;\n }\n\n /**\n * Add a skill to a candidates map, keyed by name.\n * Replaces an existing entry at the same path (update case), otherwise appends.\n */\n #addToSkillsMap(skill: InternalSkill, target: Map<string, InternalSkill[]>): void {\n const candidates = target.get(skill.name) ?? [];\n const idx = candidates.findIndex(s => s.path === skill.path);\n if (idx >= 0) {\n candidates[idx] = skill;\n } else {\n candidates.push(skill);\n }\n target.set(skill.name, candidates);\n }\n\n /**\n * Discover skills from all skills paths.\n * Uses currently resolved paths (must be set before calling).\n *\n * Paths can be plain directories, glob patterns, or direct\n * skill references (e.g., '/skills/my-skill/SKILL.md').\n *\n * Uses resolvePathPattern for unified glob resolution. File matches\n * pointing to SKILL.md are loaded directly; directory matches are\n * tried as direct skills first, then scanned for subdirectories.\n */\n async #discoverSkills(target: Map<string, InternalSkill[]>): Promise<void> {\n // Clear glob cache so discovery gets fresh results\n this.#globDirCache.clear();\n this.#globResolveTimes.clear();\n\n // Adapt SkillSource.readdir to the ReaddirEntry interface used by resolvePathPattern\n const readdir = async (dir: string): Promise<ReaddirEntry[]> => {\n const entries = await this.#source.readdir(dir);\n return entries.map(e => ({ name: e.name, type: e.type, isSymlink: e.isSymlink }));\n };\n\n for (const rawSkillsPath of this.#resolvedPaths) {\n // Strip trailing slash for consistent path handling (e.g. '/skills/' → '/skills')\n const skillsPath =\n rawSkillsPath.length > 1 && rawSkillsPath.endsWith('/') ? rawSkillsPath.slice(0, -1) : rawSkillsPath;\n const source = this.#determineSource(skillsPath);\n\n if (isGlobPattern(skillsPath)) {\n // Glob pattern: resolve to matching entries, then discover skills from each\n const resolved = await resolvePathPattern(skillsPath, readdir, { dot: true, maxDepth: 4 });\n\n // Cache directories for staleness checks: matched dirs directly,\n // and parent dirs for matched files (e.g. **/SKILL.md → parent skill dir)\n const dirs = new Set<string>();\n for (const entry of resolved) {\n if (entry.type === 'directory') {\n dirs.add(entry.path);\n } else {\n dirs.add(this.#getParentPath(entry.path));\n }\n }\n this.#globDirCache.set(skillsPath, [...dirs]);\n this.#globResolveTimes.set(skillsPath, Date.now());\n\n // Process glob-resolved entries in parallel (independent discoveries)\n const results = await Promise.allSettled(\n resolved.map(async entry => {\n if (entry.type === 'file') {\n // File match (e.g., **/SKILL.md) — load as direct skill\n await this.#discoverDirectSkill(entry.path, source, target);\n } else {\n // Directory match — try as direct skill first, then scan subdirectories\n const isDirect = await this.#discoverDirectSkill(entry.path, source, target);\n if (!isDirect) {\n await this.#discoverSkillsInPath(entry.path, source, target);\n }\n }\n }),\n );\n\n for (const [index, result] of results.entries()) {\n const entry = resolved[index];\n if (entry && result.status === 'rejected') {\n const error = result.reason;\n if (isProgrammingError(error)) throw error;\n if (error instanceof Error) {\n console.error(`[WorkspaceSkills] Failed to load skill from ${entry.path}:`, error.message);\n }\n }\n }\n } else {\n // Check if the path is a direct skill reference (directory with SKILL.md or SKILL.md file)\n const isDirect = await this.#discoverDirectSkill(skillsPath, source, target);\n if (!isDirect) {\n // Plain path: scan subdirectories for skills\n await this.#discoverSkillsInPath(skillsPath, source, target);\n }\n }\n }\n // Track when discovery completed for staleness check\n this.#lastDiscoveryTime = Date.now();\n }\n\n /**\n * Discover skills in a single path\n */\n async #discoverSkillsInPath(\n skillsPath: string,\n source: ContentSource,\n target: Map<string, InternalSkill[]>,\n ): Promise<void> {\n try {\n if (!(await this.#source.exists(skillsPath))) {\n return;\n }\n } catch (error) {\n // Programming errors (bad argument types, mis-wired content sources) must\n // surface rather than be mistaken for an inaccessible path.\n if (isProgrammingError(error)) throw error;\n\n const msg = error instanceof Error ? error.message : String(error);\n let hint = '';\n\n // If an absolute path like \"/skills\" fails, check if the relative equivalent exists\n if (skillsPath.startsWith('/') && msg.includes('Permission denied')) {\n const relativePath = skillsPath.slice(1);\n try {\n if (await this.#source.exists(relativePath)) {\n hint = ` (did you mean to use the relative path \"${relativePath}\"?)`;\n }\n } catch {\n // ignore — just skip the hint\n }\n }\n\n console.warn(`[WorkspaceSkills] Cannot access skills path \"${skillsPath}\": ${msg}${hint}`);\n return;\n }\n\n try {\n const entries = await this.#source.readdir(skillsPath);\n\n // Process all skill directories in parallel (each is independent)\n const results = await Promise.allSettled(\n entries\n .filter(entry => entry.type === 'directory')\n .map(async entry => {\n const entryPath = this.#joinPath(skillsPath, entry.name);\n const skillFilePath = this.#joinPath(entryPath, 'SKILL.md');\n\n if (await this.#source.exists(skillFilePath)) {\n const skill = await this.#parseSkillFile(skillFilePath, entry.name, source);\n return skill;\n }\n return null;\n }),\n );\n\n // Apply results sequentially to preserve overwrite semantics.\n // Discovery only collects into the target map; the live search index\n // is reconciled after the catalog swap (see #reconcileIndex).\n for (const result of results) {\n if (result.status === 'fulfilled' && result.value) {\n this.#addToSkillsMap(result.value, target);\n } else if (result.status === 'rejected') {\n const error = result.reason;\n if (isProgrammingError(error)) throw error;\n if (error instanceof Error) {\n console.error(`[WorkspaceSkills] Failed to load skill from ${skillsPath}:`, error.message);\n }\n }\n }\n } catch (error) {\n if (isProgrammingError(error)) throw error;\n if (error instanceof Error) {\n console.error(`[WorkspaceSkills] Failed to scan skills directory ${skillsPath}:`, error.message);\n }\n }\n }\n\n /**\n * Attempt to discover a skill from a direct path reference.\n *\n * Handles two cases:\n * - Path ends with `/SKILL.md` → parse directly, extract dirName from parent\n * - Path is a directory containing `SKILL.md` → parse it as a single skill\n *\n * Returns `true` if the path was a direct skill reference (skip subdirectory scan),\n * `false` to fall through to the normal subdirectory scan.\n */\n async #discoverDirectSkill(\n skillsPath: string,\n source: ContentSource,\n target: Map<string, InternalSkill[]>,\n ): Promise<boolean> {\n try {\n // Case 1: Path points directly to a SKILL.md file\n if (isSkillFilePath(skillsPath)) {\n if (!(await this.#source.exists(skillsPath))) {\n return true; // It was a direct reference, just doesn't exist — skip subdirectory scan\n }\n\n const skillDir = this.#getParentPath(skillsPath);\n const dirName = splitPathSegments(skillDir).pop() || skillDir;\n\n try {\n const skill = await this.#parseSkillFile(skillsPath, dirName, source);\n this.#addToSkillsMap(skill, target);\n } catch (error) {\n if (error instanceof Error) {\n console.error(`[WorkspaceSkills] Failed to load skill from ${skillsPath}:`, error.message);\n }\n }\n return true;\n }\n\n // Case 2: Path is a directory that directly contains SKILL.md\n if (await this.#source.exists(skillsPath)) {\n const skillFilePath = this.#joinPath(skillsPath, 'SKILL.md');\n if (await this.#source.exists(skillFilePath)) {\n const dirName = splitPathSegments(skillsPath).pop() || skillsPath;\n\n try {\n const skill = await this.#parseSkillFile(skillFilePath, dirName, source);\n this.#addToSkillsMap(skill, target);\n } catch (error) {\n if (error instanceof Error) {\n console.error(`[WorkspaceSkills] Failed to load skill from ${skillFilePath}:`, error.message);\n }\n }\n return true;\n }\n }\n\n return false;\n } catch (error) {\n if (isProgrammingError(error)) throw error;\n return false;\n }\n }\n\n /**\n * Check if any skills path directory has been modified since last discovery.\n * Compares directory mtime to lastDiscoveryTime.\n * For glob patterns, checks the walk root and expanded directories.\n */\n async #isSkillsPathStale(): Promise<boolean> {\n if (this.#lastDiscoveryTime === 0) {\n // Never discovered, consider stale\n return true;\n }\n\n // Skip the expensive stat calls if discovery happened very recently\n // (e.g., right after a surgical addSkill/removeSkill). This avoids\n // a timing race where the filesystem write updates directory mtime\n // to the same second as #lastDiscoveryTime, and also avoids slow\n // stat calls to external mounts immediately after a known-good update.\n if (Date.now() - this.#lastDiscoveryTime < WorkspaceSkillsImpl.STALENESS_CHECK_COOLDOWN) {\n return false;\n }\n\n for (const skillsPath of this.#resolvedPaths) {\n let pathsToCheck: string[];\n\n if (isGlobPattern(skillsPath)) {\n // Use cached glob dirs, re-resolve periodically to discover new entries\n const now = Date.now();\n const lastResolved = this.#globResolveTimes.get(skillsPath) ?? 0;\n if (now - lastResolved > WorkspaceSkillsImpl.GLOB_RESOLVE_INTERVAL || !this.#globDirCache.has(skillsPath)) {\n const readdir = async (dir: string): Promise<ReaddirEntry[]> => {\n const entries = await this.#source.readdir(dir);\n return entries.map(e => ({ name: e.name, type: e.type, isSymlink: e.isSymlink }));\n };\n const resolved = await resolvePathPattern(skillsPath, readdir, { dot: true, maxDepth: 4 });\n // For staleness checks we need directories: matched dirs directly,\n // and parent dirs for matched files (e.g. **/SKILL.md → parent skill dir)\n const dirs = new Set<string>();\n for (const entry of resolved) {\n if (entry.type === 'directory') {\n dirs.add(entry.path);\n } else {\n dirs.add(this.#getParentPath(entry.path));\n }\n }\n const dirList = [...dirs];\n this.#globDirCache.set(skillsPath, dirList);\n this.#globResolveTimes.set(skillsPath, now);\n }\n pathsToCheck = this.#globDirCache.get(skillsPath) ?? [];\n } else {\n pathsToCheck = [skillsPath];\n }\n\n for (const pathToCheck of pathsToCheck) {\n try {\n const stat = await this.#source.stat(pathToCheck);\n const mtime = stat.modifiedAt.getTime();\n\n if (mtime > this.#lastDiscoveryTime) {\n return true;\n }\n\n // Skip subdirectory scan for non-directory paths (direct skill references)\n if (stat.type !== 'directory') {\n continue;\n }\n\n // If this directory is itself a skill root, check its SKILL.md mtime.\n // This covers direct skill paths and file-level glob expansions (e.g., **/SKILL.md).\n if (this.#checkSkillFileMtime) {\n const directSkillFilePath = this.#joinPath(pathToCheck, 'SKILL.md');\n try {\n const directSkillFileStat = await this.#source.stat(directSkillFilePath);\n if (\n directSkillFileStat.type === 'file' &&\n directSkillFileStat.modifiedAt.getTime() > this.#lastDiscoveryTime\n ) {\n return true;\n }\n } catch {\n // Not a direct skill dir (or SKILL.md unavailable), continue to subdirectory scan.\n }\n }\n\n // Also check subdirectories (skill directories) for changes — in parallel\n const entries = await this.#source.readdir(pathToCheck);\n const dirEntries = entries.filter(entry => entry.type === 'directory');\n\n if (dirEntries.length > 0) {\n const statResults = await Promise.all(\n dirEntries.map(async entry => {\n const entryPath = this.#joinPath(pathToCheck, entry.name);\n try {\n const entryStat = await this.#source.stat(entryPath);\n if (entryStat.modifiedAt.getTime() > this.#lastDiscoveryTime) {\n return true;\n }\n\n // Optionally check SKILL.md file mtime - editing file content may not update directory mtime.\n // This doubles stat calls per skill, so it's opt-in for local development scenarios.\n if (this.#checkSkillFileMtime) {\n const skillFilePath = this.#joinPath(entryPath, 'SKILL.md');\n try {\n const skillFileStat = await this.#source.stat(skillFilePath);\n return (\n skillFileStat.type === 'file' && skillFileStat.modifiedAt.getTime() > this.#lastDiscoveryTime\n );\n } catch {\n // SKILL.md doesn't exist or can't be stat'd, skip\n }\n }\n } catch {\n // Couldn't stat entry, skip it\n }\n return false;\n }),\n );\n if (statResults.some(stale => stale)) {\n return true;\n }\n }\n } catch {\n // Couldn't stat path (doesn't exist or error), skip to next\n continue;\n }\n }\n }\n\n return false;\n }\n\n /**\n * Parse a SKILL.md file\n */\n async #parseSkillFile(filePath: string, dirName: string, source: ContentSource): Promise<InternalSkill> {\n const rawContent = await this.#source.readFile(filePath);\n const content = typeof rawContent === 'string' ? rawContent : rawContent.toString('utf-8');\n\n const { metadata: frontmatter, instructions: body } = extractSkillFrontmatter(content);\n\n // Extract required fields\n // Get skill directory path (parent of SKILL.md) - needed for SkillMetadata\n const skillPath = this.#getParentPath(filePath);\n\n const metadata: SkillMetadata = {\n ...frontmatter,\n path: skillPath,\n };\n\n // Validate if enabled (includes token/line count warnings)\n if (this.#validateOnLoad) {\n const validation = this.#validateSkillMetadata(metadata, dirName, body);\n if (!validation.valid) {\n throw new Error(`Invalid skill metadata in ${filePath}:\\n${validation.errors.join('\\n')}`);\n }\n }\n\n // Discover reference, script, and asset files (parallel — independent subdirs)\n const [references, scripts, assets] = await Promise.all([\n this.#discoverFilesInSubdir(skillPath, 'references'),\n this.#discoverFilesInSubdir(skillPath, 'scripts'),\n this.#discoverFilesInSubdir(skillPath, 'assets'),\n ]);\n\n // Build indexable content (instructions + references)\n const indexableContent = await this.#buildIndexableContent(body, skillPath, references);\n\n return {\n ...metadata,\n instructions: body,\n source,\n references,\n scripts,\n assets,\n indexableContent,\n };\n }\n\n /**\n * Validate skill metadata (delegates to shared validation function)\n */\n #validateSkillMetadata(\n metadata: SkillMetadata,\n dirName: string,\n instructions?: string,\n ): { valid: boolean; errors: string[]; warnings: string[] } {\n const result = validateSkillMetadata({ metadata, directoryName: dirName, instructions });\n\n // Log warnings if any\n if (result.warnings.length > 0) {\n for (const warning of result.warnings) {\n console.warn(`[WorkspaceSkills] ${metadata.name}: ${warning}`);\n }\n }\n\n return result;\n }\n\n /**\n * Discover files in a subdirectory of a skill (references/, scripts/, assets/)\n */\n async #discoverFilesInSubdir(skillPath: string, subdir: 'references' | 'scripts' | 'assets'): Promise<string[]> {\n const subdirPath = this.#joinPath(skillPath, subdir);\n const files: string[] = [];\n\n if (!(await this.#source.exists(subdirPath))) {\n return files;\n }\n\n try {\n await this.#walkDirectory(subdirPath, subdirPath, (relativePath: string) => {\n files.push(relativePath);\n });\n } catch {\n // Failed to read subdirectory\n }\n\n return files;\n }\n\n /**\n * Walk a directory recursively and call callback for each file.\n * Limited to maxDepth (default 20) to prevent stack overflow on deep hierarchies.\n */\n async #walkDirectory(\n basePath: string,\n dirPath: string,\n callback: (relativePath: string) => void,\n depth: number = 0,\n maxDepth: number = 20,\n ): Promise<void> {\n if (depth >= maxDepth) {\n return;\n }\n\n const entries = await this.#source.readdir(dirPath);\n\n for (const entry of entries) {\n const entryPath = this.#joinPath(dirPath, entry.name);\n\n if (entry.type === 'directory' && !entry.isSymlink) {\n await this.#walkDirectory(basePath, entryPath, callback, depth + 1, maxDepth);\n } else {\n // Get relative path from base\n const relativePath = entryPath.substring(basePath.length + 1);\n callback(relativePath);\n }\n }\n }\n\n /**\n * Build indexable content from instructions and references\n */\n async #buildIndexableContent(instructions: string, skillPath: string, references: string[]): Promise<string> {\n const parts = [instructions];\n\n // Read all reference files in parallel (independent reads, order preserved by map)\n const refContents = await Promise.all(\n references.map(async refPath => {\n const fullPath = this.#joinPath(skillPath, 'references', refPath);\n try {\n const rawContent = await this.#source.readFile(fullPath);\n return typeof rawContent === 'string' ? rawContent : rawContent.toString('utf-8');\n } catch {\n return null; // Skip files that can't be read\n }\n }),\n );\n\n for (const content of refContents) {\n if (content !== null) parts.push(content);\n }\n\n return parts.join('\\n\\n');\n }\n\n #searchDocumentId(skillPath: string, source: string): string {\n const id = `skill:${skillPath}:${source}`;\n return this.#searchNamespace ? `${SKILL_SCOPE_DOCUMENT_PREFIX}${this.#searchNamespace}:${id}` : id;\n }\n\n /**\n * Remove a skill's entries from the search index.\n */\n async #removeSkillFromIndex(skill: InternalSkill): Promise<void> {\n if (!this.#searchEngine?.remove) return;\n\n const ids = [\n this.#searchDocumentId(skill.path, 'SKILL.md'),\n this.#searchDocumentId(skill.path, SKILL_METADATA_SOURCE),\n ...skill.references.map(r => this.#searchDocumentId(skill.path, r)),\n ];\n for (const id of ids) {\n try {\n await this.#searchEngine.remove(id);\n this.#sharedSearchState.documentIds.delete(id);\n } catch {\n // Best-effort removal; entry may already be gone\n }\n }\n }\n\n /**\n * Infer the ContentSource for a skill path by matching against resolved paths.\n */\n #inferSource(skillPath: string): ContentSource {\n for (const rp of this.#resolvedPaths) {\n if (skillPath === rp || skillPath.startsWith(rp + '/')) {\n return this.#determineSource(rp);\n }\n }\n return this.#determineSource(skillPath);\n }\n\n /**\n * Index a skill for search\n */\n async #indexSkill(skill: InternalSkill): Promise<void> {\n // A released view must not write under its namespace until re-admitted;\n // an in-flight reconcile racing an eviction would otherwise leak documents.\n if (!this.#searchEngine || this.#indexReleased) return;\n\n // Index the main skill instructions\n const skillDocumentId = this.#searchDocumentId(skill.path, 'SKILL.md');\n await this.#searchEngine.index({\n id: skillDocumentId,\n content: skill.instructions,\n metadata: {\n skillPath: skill.path,\n source: 'SKILL.md',\n ...(this.#searchNamespace ? { skillScope: this.#searchNamespace } : {}),\n },\n });\n this.#sharedSearchState.documentIds.add(skillDocumentId);\n\n // Index name + description as their own document so searches can find a\n // skill by what it is for. Kept separate from the body so body line ranges\n // stay accurate; shares source 'SKILL.md' so results de-dup per skill.\n const metadataDocumentId = this.#searchDocumentId(skill.path, SKILL_METADATA_SOURCE);\n await this.#searchEngine.index({\n id: metadataDocumentId,\n content: `${skill.name}\\n${skill.description}`,\n metadata: {\n skillPath: skill.path,\n source: 'SKILL.md',\n ...(this.#searchNamespace ? { skillScope: this.#searchNamespace } : {}),\n },\n });\n this.#sharedSearchState.documentIds.add(metadataDocumentId);\n\n // Index each reference file in parallel (independent reads + index calls)\n await Promise.all(\n skill.references.map(async refPath => {\n const fullPath = this.#joinPath(skill.path, 'references', refPath);\n try {\n const rawContent = await this.#source.readFile(fullPath);\n const content = typeof rawContent === 'string' ? rawContent : rawContent.toString('utf-8');\n const referenceDocumentId = this.#searchDocumentId(skill.path, refPath);\n await this.#searchEngine!.index({\n id: referenceDocumentId,\n content,\n metadata: {\n skillPath: skill.path,\n source: `references/${refPath}`,\n ...(this.#searchNamespace ? { skillScope: this.#searchNamespace } : {}),\n },\n });\n this.#sharedSearchState.documentIds.add(referenceDocumentId);\n } catch {\n // Skip files that can't be read\n }\n }),\n );\n\n // Released while the writes above were in flight: take them back out so\n // the evicted namespace holds nothing.\n if (this.#indexReleased) {\n await this.#removeSkillFromIndex(skill);\n }\n }\n\n /**\n * Simple text search fallback when no search engine is configured\n */\n async #simpleSearch(query: string, options: SkillSearchOptions): Promise<SkillSearchResult[]> {\n const { topK = 5, skillNames, includeReferences = true } = options;\n\n const skills: Skill[] = [];\n for (const candidates of this.#skills.values()) {\n // Use tie-break winner for each name\n const skill = await this.#tieBreak(candidates);\n if (skill && (!skillNames || skillNames.includes(skill.name))) skills.push(skill);\n }\n\n // Score by the share of query words found (case-insensitive), so keyword\n // queries rank skills instead of needing every word or the exact phrase.\n // Words found in the name or description count double: they say what the\n // skill is for. Words of one or two letters (\"a\", \"do\") appear in almost\n // every skill, so they're ignored unless the query has nothing longer, or\n // the word is part of a skill's name (\"ci\", \"pr\", \"db\").\n const nameWords = new Set(skills.flatMap(skill => skill.name.toLowerCase().split(/[-_\\s]+/)));\n const allTerms = [\n ...new Set(\n query\n .toLowerCase()\n .split(/\\s+/)\n // \"review,\" or \"(test)\" should match \"review\" and \"test\"\n .map(word => word.replace(/^[^\\p{L}\\p{N}]+|[^\\p{L}\\p{N}]+$/gu, ''))\n .filter(Boolean),\n ),\n ];\n const longTerms = allTerms.filter(term => term.length > 2 || nameWords.has(term));\n const terms = longTerms.length > 0 ? longTerms : allTerms;\n\n if (terms.length === 0) {\n return this.#listSkillDocuments(skills, topK, includeReferences);\n }\n\n const skillHits: SkillSearchResult[] = [];\n for (const skill of skills) {\n const lowerAbout = `${skill.name}\\n${skill.description}`.toLowerCase();\n const lowerBody = skill.instructions.toLowerCase();\n let aboutMatches = 0;\n let weighted = 0;\n for (const term of terms) {\n if (lowerAbout.includes(term)) {\n aboutMatches++;\n weighted += 1;\n } else if (lowerBody.includes(term)) {\n weighted += 0.5;\n }\n }\n if (weighted > 0) {\n skillHits.push({\n skillName: skill.name,\n skillPath: skill.path,\n source: 'SKILL.md',\n // Preview the description when it matched: it says what the skill is for\n content: aboutMatches > 0 ? skill.description : skill.instructions.substring(0, 200),\n score: weighted / terms.length,\n });\n }\n }\n // Stable sort keeps discovery order for equal scores\n skillHits.sort((a, b) => b.score - a.score);\n\n // Reference files are read from the filesystem, which may be remote, so read\n // as few as possible. A reference scores at most 0.5, so skip them when topK\n // skills already score higher. Otherwise read the best-matching skills'\n // references first and stop after topK reference hits.\n const referenceHits: SkillSearchResult[] = [];\n if (includeReferences && skillHits.filter(hit => hit.score > 0.5).length < topK) {\n const skillsByPath = new Map(skills.map(skill => [skill.path, skill]));\n const byRank = skillHits.map(hit => skillsByPath.get(hit.skillPath)!);\n for (const hit of skillHits) skillsByPath.delete(hit.skillPath);\n byRank.push(...skillsByPath.values());\n search: for (const skill of byRank) {\n for (const refPath of skill.references) {\n const content = await this.getReference(skill.name, `references/${refPath}`);\n if (!content) continue;\n const lower = content.toLowerCase();\n const matched = terms.filter(term => lower.includes(term)).length;\n if (matched === 0) continue;\n referenceHits.push({\n skillName: skill.name,\n skillPath: skill.path,\n source: `references/${refPath}`,\n content: content.substring(0, 200),\n score: (0.5 * matched) / terms.length,\n });\n if (referenceHits.length >= topK) break search;\n }\n }\n }\n\n return [...skillHits, ...referenceHits].sort((a, b) => b.score - a.score).slice(0, topK);\n }\n\n /** Empty-query search: every skill and reference file, in discovery order. */\n async #listSkillDocuments(skills: Skill[], topK: number, includeReferences: boolean): Promise<SkillSearchResult[]> {\n const results: SkillSearchResult[] = [];\n for (const skill of skills) {\n if (results.length >= topK) break;\n results.push({\n skillName: skill.name,\n skillPath: skill.path,\n source: 'SKILL.md',\n content: skill.instructions.substring(0, 200),\n score: 1,\n });\n if (!includeReferences) continue;\n for (const refPath of skill.references) {\n if (results.length >= topK) break;\n const content = await this.getReference(skill.name, `references/${refPath}`);\n if (content) {\n results.push({\n skillName: skill.name,\n skillPath: skill.path,\n source: `references/${refPath}`,\n content: content.substring(0, 200),\n score: 0.8,\n });\n }\n }\n }\n return results;\n }\n\n /**\n * Determine the source type based on the path\n */\n #determineSource(skillsPath: string): ContentSource {\n // Use path segment matching to avoid false positives (e.g., my-node_modules).\n // Consumer-supplied absolute paths may use either separator ('\\' on Windows).\n const segments = splitPathSegments(skillsPath);\n if (segments.includes('node_modules')) {\n return { type: 'external', packagePath: skillsPath };\n }\n const normalized = skillsPath.replace(/\\\\/g, '/');\n if (normalized.includes('/.mastra/skills') || normalized.startsWith('.mastra/skills')) {\n return { type: 'managed', mastraPath: skillsPath };\n }\n return { type: 'local', projectPath: skillsPath };\n }\n\n /**\n * Join path segments (workspace paths use forward slashes)\n */\n #joinPath(...segments: string[]): string {\n return segments\n .map((seg, i) => (i === 0 ? stripTrailingSlashes(seg) : stripLeadingAndTrailingSlashes(seg)))\n .filter(Boolean)\n .join('/');\n }\n\n /**\n * Validate and normalize a relative path to prevent directory traversal.\n * Throws if the path contains traversal segments (..) or is absolute.\n */\n #assertRelativePath(input: string, label: string): string {\n const normalized = input.replace(/\\\\/g, '/');\n const segments = normalized.split('/').filter(seg => Boolean(seg) && seg !== '.');\n if (normalized.startsWith('/') || segments.some(seg => seg === '..')) {\n throw new Error(`Invalid ${label} path: ${input}`);\n }\n return segments.join('/');\n }\n\n /**\n * Get parent path\n */\n #getParentPath(path: string): string {\n const lastSlash = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\\\'));\n return lastSlash > 0 ? path.substring(0, lastSlash) : '/';\n }\n}\n\n// =============================================================================\n// ResolvedSourceWorkspaceSkills\n// =============================================================================\n\n/**\n * Resolves the skill source per request (e.g. from a dynamic workspace\n * filesystem resolver).\n */\nexport type SkillSourceResolver = (context: SkillsContext) => Promise<SkillSourceInterface> | SkillSourceInterface;\n\nexport interface ResolvedSourceWorkspaceSkillsConfig extends Omit<\n WorkspaceSkillsImplConfig,\n 'source' | 'searchEngine' | 'searchNamespace' | 'sharedSearchState'\n> {\n /** Resolves the skill source for a request. */\n source: SkillSourceResolver;\n /** Search engine whose documents can be removed when a resolved source is evicted. */\n searchEngine?: RemovableSkillSearchEngine;\n /**\n * Maximum number of resolved sources to keep discovery caches and search\n * documents for. Least-recently-used sources beyond this are evicted and\n * their search documents removed. Defaults to 16.\n */\n maxCachedSources?: number;\n}\n\nconst DEFAULT_MAX_CACHED_SOURCES = 16;\nlet nextResolvedSkillsOwnerId = 0;\n\n/**\n * WorkspaceSkills backed by a per-request skill source.\n *\n * `getScoped()` resolves the source for the request and returns a\n * `WorkspaceSkillsImpl` bound to it. Views are cached per resolved source\n * instance and per request context. Sources are keyed by object identity only\n * (never by a user-supplied `id`) so two tenants can never share a view by\n * accident. Each source gets its own search namespace so same-named skills\n * from different sources never bleed into each other's search results.\n *\n * The per-source cache is a bounded LRU: when a source is evicted, every\n * document it indexed into the shared search engine is removed, so a resolver\n * that returns a new filesystem on every request cannot grow the index\n * without bound. An evicted view that is still in use re-admits itself (and\n * re-indexes) on its next search, so callers never observe missing results.\n * Resolvers that return a stable instance per tenant keep that tenant's\n * discovery cache warm across requests.\n *\n * Calls made directly on this instance (without `getScoped`) resolve the\n * source with an empty context, mirroring how workspace tools resolve the\n * filesystem when no request context is available.\n */\nexport class ResolvedSourceWorkspaceSkills implements WorkspaceSkills {\n readonly #resolver: SkillSourceResolver;\n readonly #config: Omit<ResolvedSourceWorkspaceSkillsConfig, 'source' | 'maxCachedSources'>;\n readonly #maxCachedSources: number;\n readonly #ownerId = nextResolvedSkillsOwnerId++;\n readonly #sharedSearchState: SharedSearchState = { documentIds: new Set() };\n\n readonly #scopedByRequest = new WeakMap<object, Promise<WorkspaceSkills>>();\n /** Map insertion order doubles as LRU order; hits re-insert. */\n readonly #bySource = new Map<SkillSourceInterface, WorkspaceSkillsImpl>();\n #nextSourceId = 0;\n\n constructor(config: ResolvedSourceWorkspaceSkillsConfig) {\n const { source, maxCachedSources, ...rest } = config;\n this.#resolver = source;\n this.#config = rest;\n if (rest.searchEngine && typeof rest.searchEngine.remove !== 'function') {\n throw new TypeError('ResolvedSourceWorkspaceSkills searchEngine must implement remove()');\n }\n if (maxCachedSources !== undefined && (!Number.isSafeInteger(maxCachedSources) || maxCachedSources < 1)) {\n throw new RangeError(`maxCachedSources must be a positive integer, received ${String(maxCachedSources)}`);\n }\n this.#maxCachedSources = maxCachedSources ?? DEFAULT_MAX_CACHED_SOURCES;\n }\n\n async getScoped(context?: SkillsContext): Promise<WorkspaceSkills> {\n const requestContext = context?.requestContext;\n if (requestContext && typeof requestContext === 'object') {\n const cached = this.#scopedByRequest.get(requestContext);\n if (cached) return cached;\n\n const scoped = this.#createScoped(context).catch(error => {\n this.#scopedByRequest.delete(requestContext);\n throw error;\n });\n this.#scopedByRequest.set(requestContext, scoped);\n return scoped;\n }\n\n return this.#createScoped(context ?? {});\n }\n\n async #createScoped(context: SkillsContext): Promise<WorkspaceSkills> {\n const source = await this.#resolver(context);\n\n let impl = this.#bySource.get(source);\n if (impl) {\n await this.#admit(source, impl);\n } else {\n impl = new WorkspaceSkillsImpl({\n ...this.#config,\n source,\n searchNamespace: `owner-${this.#ownerId}/source-${this.#nextSourceId++}`,\n sharedSearchState: this.#sharedSearchState,\n // A view evicted from the LRU may still be held by a caller (or by a\n // request-context cache). When it next needs its search documents it\n // re-admits itself here before re-indexing, so the bound still holds\n // and live views never silently lose search.\n onIndexReadmit: () => this.#admit(source, impl!),\n onIndexIdle: () => this.#trimOverflow(),\n });\n await this.#admit(source, impl);\n }\n\n return impl.getScoped(context);\n }\n\n /**\n * Insert or bump a source to most-recently-used, evicting overflow.\n *\n * Only idle views are evicted: a view inside an in-flight search/refresh\n * keeps its documents until it finishes, so concurrent live views beyond the\n * bound still return results. The cache may therefore briefly exceed\n * `maxCachedSources` under concurrency; it settles back on the next admit.\n */\n async #admit(source: SkillSourceInterface, impl: WorkspaceSkillsImpl): Promise<void> {\n this.#bySource.delete(source);\n this.#bySource.set(source, impl);\n await this.#trimOverflow(impl);\n }\n\n /** Release least-recently-used idle views until the cache is within bound. */\n async #trimOverflow(keep?: WorkspaceSkillsImpl): Promise<void> {\n let overflow = this.#bySource.size - this.#maxCachedSources;\n for (const [candidateSource, candidate] of [...this.#bySource]) {\n if (overflow <= 0) break;\n if (candidate === keep || candidate.isIndexBusy) continue;\n this.#bySource.delete(candidateSource);\n overflow--;\n await candidate.releaseSearchIndex();\n }\n }\n\n async list(): Promise<SkillMetadata[]> {\n return (await this.getScoped()).list();\n }\n\n async get(name: string): Promise<Skill | null> {\n return (await this.getScoped()).get(name);\n }\n\n async has(name: string): Promise<boolean> {\n return (await this.getScoped()).has(name);\n }\n\n async refresh(): Promise<void> {\n return (await this.getScoped()).refresh();\n }\n\n async maybeRefresh(context?: SkillsContext): Promise<void> {\n return (await this.getScoped(context)).maybeRefresh(context);\n }\n\n async search(query: string, options?: SkillSearchOptions): Promise<SkillSearchResult[]> {\n return (await this.getScoped()).search(query, options);\n }\n\n async getReference(skillName: string, referencePath: string): Promise<string | null> {\n return (await this.getScoped()).getReference(skillName, referencePath);\n }\n\n async getScript(skillName: string, scriptPath: string): Promise<string | null> {\n return (await this.getScoped()).getScript(skillName, scriptPath);\n }\n\n async getAsset(skillName: string, assetPath: string): Promise<Buffer | null> {\n return (await this.getScoped()).getAsset(skillName, assetPath);\n }\n\n async listReferences(skillName: string): Promise<string[]> {\n return (await this.getScoped()).listReferences(skillName);\n }\n\n async listScripts(skillName: string): Promise<string[]> {\n return (await this.getScoped()).listScripts(skillName);\n }\n\n async listAssets(skillName: string): Promise<string[]> {\n return (await this.getScoped()).listAssets(skillName);\n }\n}\n\n/**\n * Whether an error is a Node `ERR_INVALID_ARG*` error (e.g. a non-string path\n * handed to `fs`/`path`). Only coded errors qualify: a bare `TypeError` can also\n * come from `fetch` network failures in fetch-backed content sources, which must\n * keep the warn-and-continue path.\n */\nfunction isProgrammingError(error: unknown): boolean {\n const code = (error as { code?: unknown } | null)?.code;\n return typeof code === 'string' && code.startsWith('ERR_INVALID_ARG');\n}\n\n/**\n * Split a path into segments, tolerating both POSIX (`/`) and Windows (`\\`)\n * separators. Workspace-internal paths use forward slashes, but consumer-supplied\n * absolute paths (e.g. via `new Workspace({ skills: [...] })`) may use backslashes\n * on Windows.\n */\nfunction splitPathSegments(path: string): string[] {\n return path.split(/[\\\\/]+/);\n}\n\n/**\n * Whether a path points directly at a `SKILL.md` file, tolerating both separators.\n */\nfunction isSkillFilePath(path: string): boolean {\n return path === 'SKILL.md' || /[\\\\/]SKILL\\.md$/.test(path);\n}\n\nfunction stripTrailingSlashes(s: string): string {\n let end = s.length;\n while (end > 0 && s.charCodeAt(end - 1) === 47 /* \"/\" */) {\n end--;\n }\n return end === s.length ? s : s.slice(0, end);\n}\n\nfunction stripLeadingAndTrailingSlashes(s: string): string {\n let start = 0;\n while (start < s.length && s.charCodeAt(start) === 47 /* \"/\" */) {\n start++;\n }\n let end = s.length;\n while (end > start && s.charCodeAt(end - 1) === 47 /* \"/\" */) {\n end--;\n }\n return start === 0 && end === s.length ? s : s.slice(start, end);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,YAAY,GAAmB;CAC7C,IAAI,MAAM,KAAK,OAAO,GAAG,QAAQ;CACjC,IAAI,EAAE,WAAW,IAAI,KAAK,EAAE,WAAW,KAAK,GAC1C,OAAO,KAAK,KAAK,GAAG,QAAQ,GAAG,EAAE,MAAM,CAAC,CAAC;CAE3C,OAAO;AACT;;;;AAgCA,SAAgB,cAAc,OAAqE;CACjG,OACE,UAAU,QAAQ,OAAO,UAAU,YAAY,UAAU,SAAU,MAAgC,SAAS;AAEhH;;;;;;AAOA,SAAgB,eAAe,OAAsE;CACnG,OACE,UAAU,QACV,OAAO,UAAU,YACjB,UAAU,SACT,MAAgC,SAAS;AAE9C;;;;AAKA,SAAgB,cAAc,OAAqE;CACjG,OACE,UAAU,QAAQ,OAAO,UAAU,YAAY,UAAU,SAAU,MAAgC,SAAS;AAEhH;AAMA,MAAM,aAAqC;CAEzC,KAAK;CACL,MAAM;CACN,KAAK;CACL,KAAK;CACL,KAAK;CACL,IAAI;CAEJ,IAAI;CACJ,KAAK;CACL,IAAI;CACJ,KAAK;CACL,KAAK;CACL,MAAM;CACN,KAAK;CACL,MAAM;CACN,KAAK;CAEL,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,GAAG;CACH,KAAK;CACL,GAAG;CACH,KAAK;CACL,IAAI;CACJ,MAAM;CACN,KAAK;CAEL,MAAM;CACN,KAAK;CACL,KAAK;CA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