@mastra/core
Version:
3,170 lines • 109 kB
JavaScript
const require_rolldown_runtime = require("./rolldown-runtime-BrhgMLW6.cjs");
const require_errors = require("./errors-D5kMB1FQ.cjs");
let os = require("os");
os = require_rolldown_runtime.__toESM(os, 1);
let path = require("path");
path = require_rolldown_runtime.__toESM(path, 1);
let fs_promises = require("fs/promises");
fs_promises = require_rolldown_runtime.__toESM(fs_promises, 1);
let picomatch = require("picomatch");
picomatch = require_rolldown_runtime.__toESM(picomatch, 1);
let yaml = require("yaml");
// src/workspace/filesystem/fs-utils.ts
/**
* Shared filesystem utilities for LocalFilesystem and LocalSkillSource.
*
* These utilities provide consistent implementations for common fs operations.
*/
/**
* Expand a leading `~` or `~/` to the user's home directory.
* Shell commands handle this automatically, but Node.js path APIs do not.
*/
function expandTilde(p) {
if (p === "~") return os.homedir();
if (p.startsWith("~/") || p.startsWith("~\\")) return path.join(os.homedir(), p.slice(2));
return p;
}
/**
* Check if an error is an ENOENT (file not found) error.
*/
function isEnoentError(error) {
return error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT";
}
/**
* Check if an error is an ENOTDIR error (a path component is not a directory,
* e.g. treating a file as a directory). Like ENOENT, this means the requested
* target cannot be resolved.
*/
function isEnotdirError(error) {
return error !== null && typeof error === "object" && "code" in error && error.code === "ENOTDIR";
}
/**
* Check if an error is an EEXIST (file exists) error.
*/
function isEexistError(error) {
return error !== null && typeof error === "object" && "code" in error && error.code === "EEXIST";
}
const MIME_TYPES = {
txt: "text/plain",
html: "text/html",
htm: "text/html",
css: "text/css",
csv: "text/csv",
md: "text/markdown",
js: "application/javascript",
mjs: "application/javascript",
ts: "application/typescript",
tsx: "application/typescript",
jsx: "application/javascript",
json: "application/json",
xml: "application/xml",
yaml: "text/yaml",
yml: "text/yaml",
py: "text/x-python",
rb: "text/x-ruby",
go: "text/x-go",
rs: "text/x-rust",
java: "text/x-java",
c: "text/x-c",
cpp: "text/x-c++",
h: "text/x-c",
hpp: "text/x-c++",
sh: "text/x-sh",
bash: "text/x-sh",
zsh: "text/x-sh",
toml: "text/toml",
ini: "text/plain",
env: "text/plain",
sql: "text/x-sql",
graphql: "application/graphql",
gql: "application/graphql",
vue: "text/x-vue",
svelte: "text/x-svelte",
scss: "text/x-scss",
sass: "text/x-sass",
less: "text/x-less",
php: "application/x-php",
swift: "text/x-swift",
kt: "text/x-kotlin",
kts: "text/x-kotlin",
dart: "application/dart",
lua: "text/x-lua",
r: "text/x-r",
tf: "text/x-terraform",
tfvars: "text/x-terraform",
mdx: "text/markdown",
sas: "text/plain",
log: "text/plain",
jsonl: "application/jsonl",
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
gif: "image/gif",
svg: "image/svg+xml",
webp: "image/webp",
ico: "image/x-icon",
bmp: "image/bmp",
tiff: "image/tiff",
tif: "image/tiff",
heic: "image/heic",
heif: "image/heif",
avif: "image/avif",
pdf: "application/pdf",
mp3: "audio/mpeg",
wav: "audio/wav",
ogg: "audio/ogg",
flac: "audio/flac",
m4a: "audio/mp4",
aac: "audio/aac",
mp4: "video/mp4",
webm: "video/webm",
mov: "video/quicktime",
avi: "video/x-msvideo",
mkv: "video/x-matroska",
zip: "application/zip",
tar: "application/x-tar",
gz: "application/gzip",
tgz: "application/gzip",
bz2: "application/x-bzip2",
"7z": "application/x-7z-compressed",
rar: "application/vnd.rar",
exe: "application/vnd.microsoft.portable-executable",
dll: "application/vnd.microsoft.portable-executable",
so: "application/x-sharedlib",
dylib: "application/x-sharedlib",
bin: "application/x-binary",
dat: "application/x-binary",
dmg: "application/x-apple-diskimage",
iso: "application/x-iso9660-image",
deb: "application/vnd.debian.binary-package",
rpm: "application/x-rpm",
doc: "application/msword",
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
xls: "application/vnd.ms-excel",
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
ppt: "application/vnd.ms-powerpoint",
pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
ttf: "font/ttf",
otf: "font/otf",
woff: "font/woff",
woff2: "font/woff2",
wasm: "application/wasm",
class: "application/java-vm",
pyc: "application/x-python-code"
};
/**
* Get MIME type for a filename based on extension.
*/
function getMimeType(filename) {
const ext = path.extname(filename).slice(1).toLowerCase();
const mimeType = Object.hasOwn(MIME_TYPES, ext) ? MIME_TYPES[ext] : void 0;
return typeof mimeType === "string" ? mimeType : "application/octet-stream";
}
/**
* Extensions that should be treated as text files.
*/
const TEXT_EXTENSIONS = /* @__PURE__ */ new Set([
".md",
".txt",
".json",
".yaml",
".yml",
".js",
".mjs",
".ts",
".tsx",
".jsx",
".py",
".rb",
".go",
".rs",
".java",
".c",
".cpp",
".h",
".hpp",
".sh",
".bash",
".zsh",
".html",
".htm",
".css",
".xml",
".toml",
".ini",
".env",
".csv",
".sql",
".graphql",
".gql",
".vue",
".svg",
".mdx",
".scss",
".sass",
".less",
".svelte",
".php",
".swift",
".kt",
".kts",
".dart",
".lua",
".r",
".tf",
".tfvars",
".sas",
".log",
".jsonl",
".erb",
".hbs",
".handlebars",
".haml",
".slim",
".ejs",
".mustache",
".jinja",
".j2",
".twig",
".cshtml",
".gemspec",
".lock",
".proto",
".gradle",
".properties"
]);
/**
* Normalize a text extension to the internal form: lowercased and dot-prefixed.
* e.g. `SAS` -> `.sas`, `.LOG` -> `.log`.
*/
function normalizeTextExtension(ext) {
const lower = ext.trim().toLowerCase();
return lower.startsWith(".") ? lower : `.${lower}`;
}
/**
* Check if a file should be treated as text based on extension.
*
* @param filename - The filename (or path) to check.
* @param extraExtensions - Optional set of additional normalized extensions
* (lowercased, dot-prefixed) to treat as text, in addition to the built-in set.
*/
function isTextFile(filename, extraExtensions) {
const ext = path.extname(filename).toLowerCase();
return TEXT_EXTENSIONS.has(ext) || (extraExtensions?.has(ext) ?? false);
}
/**
* Resolve a path against a base directory.
*
* - Tilde (`~`) is expanded to the user's home directory.
* - Absolute paths are normalized and returned as-is.
* - Relative paths (including `../`) are resolved against `basePath`.
*
* @param basePath - The absolute base path to resolve against
* @param filePath - The path to resolve
* @returns The absolute resolved path
*/
function resolveToBasePath(basePath, filePath) {
const expanded = expandTilde(filePath);
if (path.isAbsolute(expanded)) return path.normalize(expanded);
return path.resolve(basePath, expanded);
}
/**
* Check if a path exists.
* Never throws - returns false on any error.
*
* @param absolutePath - The absolute path to check
* @returns true if path exists and is accessible
*/
async function fsExists(absolutePath) {
try {
await fs_promises.access(absolutePath);
return true;
} catch {
return false;
}
}
/**
* Get file/directory stats.
* Throws FileNotFoundError if path doesn't exist.
*
* @param absolutePath - The absolute path to stat
* @param userPath - The user-facing path for error messages
* @returns File stat information
* @throws {FileNotFoundError} if path doesn't exist
*/
async function fsStat(absolutePath, userPath) {
try {
const stats = await fs_promises.stat(absolutePath);
return {
name: path.basename(absolutePath),
type: stats.isDirectory() ? "directory" : "file",
size: stats.size,
createdAt: stats.birthtime,
modifiedAt: stats.mtime,
mimeType: stats.isFile() ? getMimeType(absolutePath) : void 0
};
} catch (error) {
if (isEnoentError(error)) throw new require_errors.FileNotFoundError(userPath);
throw error;
}
}
// src/workspace/glob.ts
/**
* Glob Pattern Utilities
*
* Shared glob pattern matching for workspace operations.
* Uses picomatch for battle-tested glob support including
* brace expansion, character classes, negation, and `**`.
*/
/** Characters that indicate a glob pattern (not a plain path) */
const GLOB_CHARS = /[*?{}[\]]/;
/**
* Check if a string contains glob metacharacters.
*
* @example
* isGlobPattern('/docs') // false
* isGlobPattern('/docs/**\/*.md') // true
* isGlobPattern('*.ts') // true
* isGlobPattern('/src/{a,b}') // true
*/
function isGlobPattern(input) {
return GLOB_CHARS.test(input);
}
/**
* Extract the static directory prefix before the first glob metacharacter.
* Returns the deepest non-glob ancestor directory.
*
* @example
* extractGlobBase('docs/**\/*.md') // 'docs'
* extractGlobBase('**\/*.md') // '.'
* extractGlobBase('src/*.ts') // 'src'
* extractGlobBase('exact/path') // 'exact/path'
*/
function extractGlobBase(pattern) {
const firstMeta = pattern.search(GLOB_CHARS);
if (firstMeta === -1) return pattern;
const prefix = pattern.slice(0, firstMeta);
const lastSlash = prefix.lastIndexOf("/");
if (lastSlash <= 0) return ".";
return prefix.slice(0, lastSlash);
}
/**
* Strip leading './' or '/' from a path for picomatch matching.
* picomatch does not match paths with these prefixes, so both
* patterns and test paths must be normalized before matching.
*
* This only affects matching — filesystem paths should keep their
* original form for correct resolution with contained/uncontained modes.
*/
function normalizeForMatch(input) {
if (input.startsWith("./")) return input.slice(2);
if (input.startsWith("/")) return input.slice(1);
return input;
}
/**
* Compile glob pattern(s) into a reusable matcher function.
* The matcher tests paths using workspace-style forward slashes.
*
* Automatically normalizes leading './' and '/' from both patterns
* and test paths, since picomatch does not match these prefixes.
*
* @example
* const match = createGlobMatcher('**\/*.ts');
* match('src/index.ts') // true
* match('src/style.css') // false
*
* const multi = createGlobMatcher(['**\/*.ts', '**\/*.tsx']);
* multi('App.tsx') // true
*/
function createGlobMatcher(patterns, options) {
const patternArray = (Array.isArray(patterns) ? patterns : [patterns]).map(normalizeForMatch);
const matcher = (0, picomatch.default)(patternArray, {
posix: true,
dot: options?.dot ?? false
});
return (path) => matcher(normalizeForMatch(path));
}
/**
* One-off convenience: test if a path matches a glob pattern.
*
* For repeated matching against the same pattern, prefer createGlobMatcher()
* to compile once and reuse.
*
* @example
* matchGlob('src/index.ts', '**\/*.ts') // true
*/
function matchGlob(path, pattern, options) {
return createGlobMatcher(pattern, options)(path);
}
/**
* Walk a directory tree recursively, returning all entries (files and directories).
* Skips symlinked directories to prevent infinite loops.
*/
async function walkAll(readdir, dir, depth, maxDepth) {
if (depth >= maxDepth) return [];
try {
const entries = await readdir(dir);
const results = [];
for (const entry of entries) {
if (entry.type === "directory" && entry.isSymlink) continue;
const fullPath = dir === "." || dir === "" ? entry.name : `${dir}/${entry.name}`;
results.push({
path: fullPath,
type: entry.type
});
if (entry.type === "directory") results.push(...await walkAll(readdir, fullPath, depth + 1, maxDepth));
}
return results;
} catch {
return [];
}
}
/**
* Resolve a path pattern to matching filesystem entries.
*
* Handles both plain paths and glob patterns consistently:
* - Plain paths: determines file vs directory via readdir probe, returns single entry
* - Glob patterns: walks from the glob base, matches both files and directories
*
* @example
* // Plain paths
* resolvePathPattern('/docs', readdir) // [{ path: '/docs', type: 'directory' }]
* resolvePathPattern('/docs/readme.md', readdir) // [{ path: '/docs/readme.md', type: 'file' }]
*
* // Glob patterns — matches files and directories
* resolvePathPattern('/docs/**\/*.md', readdir) // all .md files under /docs
* resolvePathPattern('**\/skills', readdir) // all directories (and files) named 'skills'
* resolvePathPattern('/skills/**', readdir) // everything under /skills
*/
async function resolvePathPattern(pattern, readdir, options) {
const maxDepth = options?.maxDepth ?? 10;
const normalized = pattern.length > 1 && pattern.endsWith("/") ? pattern.slice(0, -1) : pattern;
if (!isGlobPattern(normalized)) try {
await readdir(normalized);
return [{
path: normalized,
type: "directory"
}];
} catch {
return [{
path: normalized,
type: "file"
}];
}
const walkRoot = extractGlobBase(normalized);
const matcher = createGlobMatcher(normalized, { dot: options?.dot ?? false });
return (await walkAll(readdir, walkRoot, 0, maxDepth)).filter((entry) => matcher(entry.path));
}
/**
* Default tokenization options
*/
const DEFAULT_TOKENIZE_OPTIONS = {
lowercase: true,
removePunctuation: true,
minLength: 2,
stopwords: /* @__PURE__ */ new Set([
"a",
"an",
"and",
"are",
"as",
"at",
"be",
"by",
"for",
"from",
"has",
"he",
"in",
"is",
"it",
"its",
"of",
"on",
"or",
"that",
"the",
"to",
"was",
"were",
"will",
"with"
]),
splitPattern: /\s+/
};
/**
* Tokenize text into an array of terms
*/
function tokenize(text, options = {}) {
if (options.tokenizer) return options.tokenizer(text);
const opts = {
...DEFAULT_TOKENIZE_OPTIONS,
...options
};
let processed = text;
if (opts.lowercase) processed = processed.toLowerCase();
if (opts.removePunctuation) processed = processed.replace(/[^\p{L}\p{N}_\s]/gu, " ");
return processed.split(opts.splitPattern).filter((token) => {
if (token.length < opts.minLength) return false;
if (opts.stopwords?.has(token)) return false;
return true;
});
}
/**
* Find the line range where query terms appear in content.
* Returns the range spanning from the first to the last line containing any query term.
*
* @param content - The document content
* @param queryTerms - Tokenized query terms to find
* @param options - Tokenization options (should match indexing options)
* @returns LineRange if terms found, undefined otherwise
*/
function findLineRange(content, queryTerms, options = {}) {
if (queryTerms.length === 0) return void 0;
const lines = content.split("\n");
const opts = {
lowercase: true,
removePunctuation: true,
minLength: 2,
...options
};
const lowercase = !opts.tokenizer && opts.lowercase;
const normalizedTerms = new Set(queryTerms.map((t) => lowercase ? t.toLowerCase() : t));
let firstMatchLine;
let lastMatchLine;
for (let i = 0; i < lines.length; i++) {
const lineTokens = tokenize(lines[i], options);
for (const token of lineTokens) if (normalizedTerms.has(token)) {
const lineNum = i + 1;
if (firstMatchLine === void 0) firstMatchLine = lineNum;
lastMatchLine = lineNum;
break;
}
}
if (firstMatchLine !== void 0 && lastMatchLine !== void 0) return {
start: firstMatchLine,
end: lastMatchLine
};
}
/**
* Compute term frequencies for a list of tokens
*/
function computeTermFrequencies(tokens) {
const frequencies = /* @__PURE__ */ new Map();
for (const token of tokens) frequencies.set(token, (frequencies.get(token) || 0) + 1);
return frequencies;
}
/**
* BM25 Index for keyword-based document retrieval
*/
var BM25Index = class BM25Index {
/** BM25 k1 parameter */
k1;
/** BM25 b parameter */
b;
/** Documents in the index */
#documents = /* @__PURE__ */ new Map();
/** Inverted index: term -> document IDs containing the term */
#invertedIndex = /* @__PURE__ */ new Map();
/** Document frequency: term -> number of documents containing the term */
#documentFrequency = /* @__PURE__ */ new Map();
/** Average document length */
#avgDocLength = 0;
/** Total number of documents */
#docCount = 0;
/** Tokenization options */
#tokenizeOptions;
constructor(config = {}, tokenizeOptions = {}) {
this.k1 = config.k1 ?? 1.5;
this.b = config.b ?? .75;
this.#tokenizeOptions = tokenizeOptions;
}
/**
* Add a document to the index
*/
add(id, content, metadata) {
if (this.#documents.has(id)) this.remove(id);
const tokens = tokenize(content, this.#tokenizeOptions);
const termFrequencies = computeTermFrequencies(tokens);
const doc = {
id,
content,
tokens,
termFrequencies,
length: tokens.length,
metadata
};
this.#documents.set(id, doc);
this.#docCount++;
for (const term of termFrequencies.keys()) {
if (!this.#invertedIndex.has(term)) this.#invertedIndex.set(term, /* @__PURE__ */ new Set());
this.#invertedIndex.get(term).add(id);
this.#documentFrequency.set(term, (this.#documentFrequency.get(term) || 0) + 1);
}
this.#updateAvgDocLength();
}
/**
* Remove a document from the index
*/
remove(id) {
const doc = this.#documents.get(id);
if (!doc) return false;
for (const term of doc.termFrequencies.keys()) {
const docIds = this.#invertedIndex.get(term);
if (docIds) {
docIds.delete(id);
if (docIds.size === 0) {
this.#invertedIndex.delete(term);
this.#documentFrequency.delete(term);
} else this.#documentFrequency.set(term, (this.#documentFrequency.get(term) || 1) - 1);
}
}
this.#documents.delete(id);
this.#docCount--;
this.#updateAvgDocLength();
return true;
}
/**
* Clear all documents from the index
*/
clear() {
this.#documents.clear();
this.#invertedIndex.clear();
this.#documentFrequency.clear();
this.#docCount = 0;
this.#avgDocLength = 0;
}
/**
* Search for documents matching the query
*/
search(query, topK = 10, minScore = 0) {
const queryTokens = tokenize(query, this.#tokenizeOptions);
if (queryTokens.length === 0 || this.#docCount === 0) return [];
const scores = /* @__PURE__ */ new Map();
for (const queryTerm of queryTokens) {
const docIds = this.#invertedIndex.get(queryTerm);
if (!docIds) continue;
const df = this.#documentFrequency.get(queryTerm) || 0;
const idf = this.#computeIDF(df);
for (const docId of docIds) {
const doc = this.#documents.get(docId);
const tf = doc.termFrequencies.get(queryTerm) || 0;
const termScore = this.#computeTermScore(tf, doc.length, idf);
scores.set(docId, (scores.get(docId) || 0) + termScore);
}
}
const results = [];
for (const [docId, score] of scores.entries()) if (score >= minScore) {
const doc = this.#documents.get(docId);
results.push({
id: docId,
content: doc.content,
score,
metadata: doc.metadata
});
}
results.sort((a, b) => b.score - a.score);
return results.slice(0, topK);
}
/**
* Get a document by ID
*/
get(id) {
return this.#documents.get(id);
}
/**
* Check if a document exists in the index
*/
has(id) {
return this.#documents.has(id);
}
/**
* Get the number of documents in the index
*/
get size() {
return this.#docCount;
}
/**
* Get all document IDs
*/
get documentIds() {
return Array.from(this.#documents.keys());
}
/**
* Serialize the index to a JSON-compatible object
*/
serialize() {
const documents = [];
for (const [id, doc] of this.#documents.entries()) documents.push({
id,
content: doc.content,
tokens: doc.tokens,
termFrequencies: Object.fromEntries(doc.termFrequencies),
length: doc.length,
metadata: doc.metadata
});
return {
k1: this.k1,
b: this.b,
documents,
avgDocLength: this.#avgDocLength
};
}
/**
* Deserialize an index from a JSON object
*/
static deserialize(data, tokenizeOptions = {}) {
const index = new BM25Index({
k1: data.k1,
b: data.b
}, tokenizeOptions);
for (const doc of data.documents) {
const termFrequencies = new Map(Object.entries(doc.termFrequencies));
const document = {
id: doc.id,
content: doc.content,
tokens: doc.tokens,
termFrequencies,
length: doc.length,
metadata: doc.metadata
};
index.#documents.set(doc.id, document);
index.#docCount++;
for (const term of termFrequencies.keys()) {
if (!index.#invertedIndex.has(term)) index.#invertedIndex.set(term, /* @__PURE__ */ new Set());
index.#invertedIndex.get(term).add(doc.id);
index.#documentFrequency.set(term, (index.#documentFrequency.get(term) || 0) + 1);
}
}
index.#avgDocLength = data.avgDocLength;
return index;
}
/**
* Update average document length after add/remove operations
*/
#updateAvgDocLength() {
if (this.#docCount === 0) {
this.#avgDocLength = 0;
return;
}
let totalLength = 0;
for (const doc of this.#documents.values()) totalLength += doc.length;
this.#avgDocLength = totalLength / this.#docCount;
}
/**
* Compute IDF (Inverse Document Frequency) for a term
*/
#computeIDF(df) {
return Math.log((this.#docCount - df + .5) / (df + .5) + 1);
}
/**
* Compute the BM25 score component for a single term
*/
#computeTermScore(tf, docLength, idf) {
return idf * (tf * (this.k1 + 1) / (tf + this.k1 * (1 - this.b + this.b * (docLength / this.#avgDocLength))));
}
};
// src/workspace/search/search-engine.ts
/**
* Type guard: returns true when the embedder is the batch-capable variant.
*/
function isBatchEmbedder(embedder) {
return typeof embedder === "function" && embedder.batch === true;
}
/** Default `indexMany` / lazy-vector flush concurrency (embedder + upsert). */
const DEFAULT_INDEX_MANY_CONCURRENCY = 8;
/** Documents per embedder call when the embedder does not declare its own `maxBatchSize`. */
const DEFAULT_EMBED_GROUP_SIZE = 256;
/**
* Upper bound on vectors handed to a single `upsert`.
*
* Vector stores cap how much one write request may carry — `PineconeVector` already slices at
* this exact size — and each document's metadata carries its full text, so an unbounded batch
* turns into an unbounded request. Kept separate from the embedder's `maxBatchSize`, which
* limits the embedding API rather than the store.
*/
const MAX_VECTORS_PER_UPSERT = 100;
/**
* Documents to group per embedder call, honouring the embedder's own limit.
*
* A `maxBatchSize` of `0`, a negative number or `NaN` (easy to produce with
* `Number(process.env.EMBED_BATCH_SIZE)`) would otherwise mean "never make progress", so those
* fall back to the default rather than stalling or silently indexing nothing.
*/
function resolveEmbedGroupSize(embedder) {
const declared = embedder.maxBatchSize;
if (declared === void 0 || !Number.isFinite(declared) || declared < 1) return DEFAULT_EMBED_GROUP_SIZE;
return Math.floor(declared);
}
function chunkItems(items, size) {
const groups = [];
for (let i = 0; i < items.length; i += size) groups.push(items.slice(i, i + size));
return groups;
}
const DEFAULT_MAX_CHUNK_CHARS = 4e3;
const DEFAULT_OVERLAP_LINES = 3;
/**
* Split text into line-based chunks that stay within a character budget.
*
* Each chunk is formed by accumulating whole lines until adding the next line
* would exceed `maxChunkChars`. Adjacent chunks share `overlapLines` lines so
* that context around chunk boundaries is preserved for embedding quality.
*
* Returns the original text as a single chunk when it already fits.
*/
function splitIntoChunks(text, options = {}) {
const maxChars = Math.max(1, Math.floor(options.maxChunkChars ?? DEFAULT_MAX_CHUNK_CHARS));
const overlapLines = Math.max(0, Math.floor(options.overlapLines ?? DEFAULT_OVERLAP_LINES));
if (text.length <= maxChars) return [{
content: text,
startLine: 1
}];
const lines = text.split("\n");
const chunks = [];
let start = 0;
while (start < lines.length) {
let end = start;
let charCount = 0;
while (end < lines.length) {
const lineLen = lines[end].length + (end > start ? 1 : 0);
if (charCount + lineLen > maxChars && end > start) break;
charCount += lineLen;
end++;
}
const chunkContent = lines.slice(start, end).join("\n");
if (chunkContent.length <= maxChars) chunks.push({
content: chunkContent,
startLine: start + 1
});
else for (let offset = 0; offset < chunkContent.length; offset += maxChars) chunks.push({
content: chunkContent.slice(offset, offset + maxChars),
startLine: start + 1
});
if (end >= lines.length) break;
const nextStart = end - overlapLines;
start = nextStart <= start ? end : nextStart;
}
return chunks;
}
/**
* Unified search engine supporting BM25, vector, and hybrid search.
*
* Used internally by Workspace to provide consistent search functionality.
*
* @example
* ```typescript
* const engine = new SearchEngine({
* bm25: { tokenize: { lowercase: true } },
* vector: { vectorStore, embedder, indexName: 'my-index' },
* });
*
* // Index documents
* await engine.index({ id: 'doc1', content: 'Hello world' });
*
* // Search
* const results = await engine.search('hello', { mode: 'hybrid', topK: 5 });
* ```
*/
var SearchEngine = class {
/** BM25 index for keyword search */
#bm25Index;
/** Tokenization options (stored for lineRange computation) */
#tokenizeOptions;
/** Vector configuration */
#vectorConfig;
/** Whether to use lazy vector indexing */
#lazyVectorIndex;
/** All indexed document IDs (used for prefix-based removal across backends) */
#indexedIds = /* @__PURE__ */ new Set();
/** Documents pending vector indexing (for lazy mode) */
#pendingVectorDocs = [];
/** Whether vector index has been built (for lazy mode) */
#vectorIndexBuilt = false;
/** Whether createIndex has been attempted on the vector store */
#vectorIndexReady = false;
constructor(config = {}) {
if (config.bm25 !== void 0) {
this.#tokenizeOptions = config.bm25.tokenize;
this.#bm25Index = new BM25Index(config.bm25.bm25, this.#tokenizeOptions);
}
if (config.vector) {
if (!config.vector.embedder && !config.vector.vectorStore.isSelfEmbedding) throw new Error("Vector search requires an embedder, or a vector store that generates embeddings itself.");
this.#vectorConfig = config.vector;
}
this.#lazyVectorIndex = config.lazyVectorIndex ?? false;
}
/**
* Index a document for search
*/
async index(doc) {
const docWithMergedMetadata = this.#indexNonVectorParts(doc);
if (this.#vectorConfig) {
if (this.#lazyVectorIndex) {
this.#pendingVectorDocs.push(docWithMergedMetadata);
this.#vectorIndexBuilt = false;
} else await this.#indexVector(docWithMergedMetadata);
}
}
/**
* Run the synchronous, per-document half of indexing: metadata merge, id tracking and BM25.
*
* Returns the document with merged metadata so the caller can hand it to the vector path.
* Split out of {@link SearchEngine.index} so `indexMany` can keep BM25 per-document while
* batching the vector work.
*/
#indexNonVectorParts(doc) {
const metadata = { ...doc.metadata };
if (doc.startLineOffset !== void 0) metadata._startLineOffset = doc.startLineOffset;
this.#indexedIds.add(doc.id);
if (this.#bm25Index) this.#bm25Index.add(doc.id, doc.content, metadata);
return {
...doc,
metadata
};
}
/**
* Index multiple documents (up to `concurrency` at a time when async vector work runs).
*
* @param docs - Documents to index
* @param options - `p-map` options; `concurrency` defaults to 8
*/
async indexMany(docs, options) {
const stopOnError = options?.stopOnError;
const concurrency = options?.concurrency ?? DEFAULT_INDEX_MANY_CONCURRENCY;
if (this.#lazyVectorIndex || !this.#groupsWrites()) {
const pMap = (await import("p-map")).default;
await pMap(docs, (doc) => this.index(doc), {
stopOnError,
concurrency
});
return;
}
const groups = chunkItems(this.#dedupeDocsLastWins(docs), this.#writeGroupSize());
if (groups.length === 0) return;
const failures = [];
const runGroup = async (group) => {
const merged = this.#indexNonVectorPartsOf(group);
if (stopOnError !== false) {
await this.#embedAndUpsertGroup(merged);
return;
}
try {
await this.#embedAndUpsertGroup(merged);
} catch {
for (const doc of merged) try {
await this.#indexVector(doc);
} catch (error) {
failures.push(error);
}
}
};
await runGroup(groups[0]);
if (groups.length > 1) {
const pMap = (await import("p-map")).default;
await pMap(groups.slice(1), runGroup, {
stopOnError,
concurrency
});
}
if (failures.length > 0) throw new AggregateError(failures);
}
/**
* BM25-index a group of documents as it is attempted.
*
* Keeping this inside the group task means a rejected `indexMany` leaves the keyword index in
* the same shape the per-document path would have: populated only for documents that indexing
* actually reached, rather than for every document handed in.
*/
#indexNonVectorPartsOf(group) {
return group.map((doc) => this.#indexNonVectorParts(doc));
}
/**
* Collapse duplicate document ids so a single upsert runs per id (last entry wins).
*/
#dedupeDocsLastWins(docs) {
const byId = /* @__PURE__ */ new Map();
for (const doc of docs) byId.set(doc.id, doc);
return [...byId.values()];
}
/**
* Remove a document from the index
*/
async remove(id) {
this.#indexedIds.delete(id);
if (this.#bm25Index) this.#bm25Index.remove(id);
if (this.#vectorConfig) {
try {
await this.#vectorConfig.vectorStore.deleteVector({
indexName: this.#vectorConfig.indexName,
id
});
} catch {}
if (this.#lazyVectorIndex) this.#pendingVectorDocs = this.#pendingVectorDocs.filter((d) => d.id !== id);
}
}
/**
* Number of indexed documents whose ID starts with the given prefix.
*/
countByPrefix(prefix) {
let count = 0;
for (const id of this.#indexedIds) if (id.startsWith(prefix)) count++;
return count;
}
/**
* Remove all documents whose ID starts with the given prefix.
* Used to remove all chunks belonging to a single source document.
*/
async removeByPrefix(prefix) {
const matchedIds = [...this.#indexedIds].filter((id) => id.startsWith(prefix));
for (const id of matchedIds) this.#indexedIds.delete(id);
if (this.#bm25Index) for (const id of matchedIds) this.#bm25Index.remove(id);
if (this.#vectorConfig) {
if (this.#lazyVectorIndex) this.#pendingVectorDocs = this.#pendingVectorDocs.filter((d) => !d.id.startsWith(prefix));
for (const id of matchedIds) try {
await this.#vectorConfig.vectorStore.deleteVector({
indexName: this.#vectorConfig.indexName,
id
});
} catch {}
}
}
/**
* Remove a source document and all of its chunked variants.
*
* This also attempts a metadata-based bulk delete for chunk vectors so stale
* chunk IDs from previous process runs are cleaned up in persistent stores.
*/
async removeSource(sourceId) {
await this.remove(sourceId);
await this.removeByPrefix(`${sourceId}#chunk-`);
if (this.#vectorConfig) try {
await this.#vectorConfig.vectorStore.deleteVectors({
indexName: this.#vectorConfig.indexName,
filter: { sourceFile: sourceId }
});
} catch {}
}
/**
* Clear all indexed documents
*/
clear() {
this.#indexedIds.clear();
if (this.#bm25Index) this.#bm25Index.clear();
this.#pendingVectorDocs = [];
this.#vectorIndexBuilt = false;
}
/**
* Search for documents
*/
async search(query, options = {}) {
const { topK = 10, minScore, mode, vectorWeight = .5, filter } = options;
const effectiveMode = this.#determineSearchMode(mode);
if (effectiveMode === "bm25") return this.#searchBM25(query, topK, minScore);
if (effectiveMode === "vector") return this.#searchVector(query, topK, minScore, filter);
return this.#searchHybrid(query, topK, minScore, vectorWeight, filter);
}
/**
* Check if BM25 search is available
*/
get canBM25() {
return !!this.#bm25Index;
}
/**
* Check if vector search is available
*/
get canVector() {
return !!this.#vectorConfig;
}
/**
* Check if hybrid search is available
*/
get canHybrid() {
return this.canBM25 && this.canVector;
}
/**
* Get the BM25 index (for serialization/debugging)
*/
get bm25Index() {
return this.#bm25Index;
}
/**
* Determine the effective search mode
*/
#determineSearchMode(requestedMode) {
if (requestedMode) {
if (requestedMode === "vector" && !this.canVector) throw new Error("Vector search requires vector configuration.");
if (requestedMode === "bm25" && !this.canBM25) throw new Error("BM25 search requires BM25 configuration.");
if (requestedMode === "hybrid" && !this.canHybrid) throw new Error("Hybrid search requires both vector and BM25 configuration.");
return requestedMode;
}
if (this.canHybrid) return "hybrid";
if (this.canVector) return "vector";
if (this.canBM25) return "bm25";
throw new Error("No search configuration available. Provide bm25 or vector config.");
}
/**
* True when the vector store generates the embeddings, so this engine sends it text.
* False whenever an embedder is configured, which keeps the client-side path intact.
*/
#embedsServerSide() {
return !this.#vectorConfig?.embedder && this.#vectorConfig?.vectorStore.isSelfEmbedding === true;
}
/** True when documents are written in groups rather than one at a time. */
#groupsWrites() {
const embedder = this.#vectorConfig?.embedder;
return this.#embedsServerSide() || !!embedder && isBatchEmbedder(embedder);
}
/** Documents per group: the embedder's own limit, or the upsert bound when the store embeds. */
#writeGroupSize() {
const embedder = this.#vectorConfig?.embedder;
return embedder && isBatchEmbedder(embedder) ? resolveEmbedGroupSize(embedder) : MAX_VECTORS_PER_UPSERT;
}
/**
* Embed a single text, dispatching to the batch path with a one-element array
* when the configured embedder is batch-capable.
*/
async #embedOne(text) {
if (!this.#vectorConfig) throw new Error("Vector configuration is required to embed text.");
const { embedder } = this.#vectorConfig;
if (!embedder) throw new Error("This vector store generates embeddings itself, so there is no embedder to call.");
if (isBatchEmbedder(embedder)) {
const [embedding] = await embedder([text]);
if (!embedding) throw new Error("Batch embedder returned no embedding for input text.");
return embedding;
}
return embedder(text);
}
/**
* Embed many texts. Uses a single batched call (chunked by `maxBatchSize`)
* when the embedder is batch-capable; otherwise falls back to parallel
* single-text calls.
*/
async #embedAll(texts) {
if (!this.#vectorConfig) throw new Error("Vector configuration is required to embed texts.");
if (texts.length === 0) return [];
const pMap = (await import("p-map")).default;
const { embedder } = this.#vectorConfig;
if (!embedder) throw new Error("This vector store generates embeddings itself, so there is no embedder to call.");
if (isBatchEmbedder(embedder)) {
const max = resolveEmbedGroupSize(embedder);
if (texts.length <= max) return embedder(texts);
return (await pMap(chunkItems(texts, max), (chunk) => embedder(chunk), { concurrency: DEFAULT_INDEX_MANY_CONCURRENCY })).flat();
}
return pMap(texts, (text) => embedder(text), { concurrency: DEFAULT_INDEX_MANY_CONCURRENCY });
}
/**
* Index a single document in the vector store.
*
* Used by the eager (non-lazy) write path. The lazy flush path embeds all
* pending docs together via {@link SearchEngine.#flushVectorBatch} for true
* batch embedding when supported.
*/
async #indexVector(doc) {
if (!this.#vectorConfig) return;
if (this.#embedsServerSide()) {
await this.#embedAndUpsertGroup([doc]);
return;
}
const { vectorStore, indexName } = this.#vectorConfig;
const embedding = await this.#embedOne(doc.content);
if (!this.#vectorIndexReady) try {
await vectorStore.createIndex({
indexName,
dimension: embedding.length
});
} catch {}
await vectorStore.upsert({
indexName,
vectors: [embedding],
metadata: [{
id: doc.id,
text: doc.content,
...doc.metadata
}],
ids: [doc.id]
});
this.#vectorIndexReady = true;
}
/**
* Embed and upsert a batch of documents in as few provider calls as possible.
*
* - If the embedder is batch-capable, texts are grouped into `maxBatchSize` embedder calls
* and written with upserts bounded by {@link MAX_VECTORS_PER_UPSERT}.
* - If the store embeds server-side, the texts are written as they are, in the same bounded
* upserts.
* - Otherwise falls back to per-doc embedding via {@link SearchEngine.#indexVector}.
*/
async #flushVectorBatch(docs) {
if (!this.#vectorConfig || docs.length === 0) return;
const pMap = (await import("p-map")).default;
if (!this.#groupsWrites()) {
await pMap(docs, (doc) => this.#indexVector(doc), { concurrency: DEFAULT_INDEX_MANY_CONCURRENCY });
return;
}
const groups = chunkItems(docs, this.#writeGroupSize());
await this.#embedAndUpsertGroup(groups[0]);
if (groups.length > 1) await pMap(groups.slice(1), (group) => this.#embedAndUpsertGroup(group), { concurrency: DEFAULT_INDEX_MANY_CONCURRENCY });
}
/**
* Embed one group of documents with a single embedder call, then write the vectors using
* upserts no larger than {@link MAX_VECTORS_PER_UPSERT}.
*
* Vectors are paired with their documents positionally, so the embedder must return exactly
* one embedding per input in input order.
*/
async #embedAndUpsertGroup(docs) {
if (!this.#vectorConfig || docs.length === 0) return;
const { vectorStore, indexName } = this.#vectorConfig;
const embedsServerSide = this.#embedsServerSide();
const embeddings = embedsServerSide ? [] : await this.#embedAll(docs.map((d) => d.content));
if (!embedsServerSide && embeddings.length !== docs.length) throw new Error(`Batch embedder returned ${embeddings.length} embeddings for ${docs.length} inputs.`);
if (!this.#vectorIndexReady) try {
await vectorStore.createIndex(embedsServerSide ? { indexName } : {
indexName,
dimension: embeddings[0].length
});
} catch {}
for (let start = 0; start < docs.length; start += MAX_VECTORS_PER_UPSERT) {
const slice = docs.slice(start, start + MAX_VECTORS_PER_UPSERT);
const rows = {
indexName,
metadata: slice.map((doc) => ({
id: doc.id,
text: doc.content,
...doc.metadata
})),
ids: slice.map((d) => d.id)
};
if (embedsServerSide) await vectorStore.upsert({
...rows,
documents: slice.map((d) => d.content)
});
else await vectorStore.upsert({
...rows,
vectors: embeddings.slice(start, start + MAX_VECTORS_PER_UPSERT)
});
this.#vectorIndexReady = true;
}
}
/**
* Ensure vector index is built (for lazy mode).
*
* Drains the pending queue into a local batch before awaiting upserts so concurrent `index()` calls
* append to a fresh queue and are not wiped by a blanket clear. Loops until the queue is empty so
* documents added mid-flush are indexed before search runs. Re-queues the batch on flush failure.
*/
async #ensureVectorIndex() {
if (!this.#lazyVectorIndex) return;
if (this.#pendingVectorDocs.length === 0) {
this.#vectorIndexBuilt = true;
return;
}
while (this.#pendingVectorDocs.length > 0) {
const batch = this.#pendingVectorDocs;
this.#pendingVectorDocs = [];
const uniqueDocs = this.#dedupeDocsLastWins(batch);
try {
await this.#flushVectorBatch(uniqueDocs);
} catch (error) {
this.#pendingVectorDocs = [...uniqueDocs, ...this.#pendingVectorDocs];
throw error;
}
}
this.#vectorIndexBuilt = true;
}
/**
* BM25 keyword search
*/
#searchBM25(query, topK, minScore) {
if (!this.#bm25Index) throw new Error("BM25 search requires BM25 configuration.");
const results = this.#bm25Index.search(query, topK, minScore);
const queryTokens = tokenize(query, this.#tokenizeOptions);
return results.map((result) => {
const rawLineRange = findLineRange(result.content, queryTokens, this.#tokenizeOptions);
const lineRange = this.#adjustLineRange(rawLineRange, result.metadata);
const { _startLineOffset, ...cleanMetadata } = result.metadata ?? {};
return {
id: result.id,
content: result.content,
score: result.score,
lineRange,
metadata: Object.keys(cleanMetadata).length > 0 ? cleanMetadata : void 0,
scoreDetails: { bm25: result.score }
};
});
}
/**
* Vector semantic search
*/
async #searchVector(query, topK, minScore, filter) {
if (!this.#vectorConfig) throw new Error("Vector search requires vector configuration.");
await this.#ensureVectorIndex();
const { vectorStore, indexName } = this.#vectorConfig;
const vectorResults = this.#embedsServerSide() ? await vectorStore.query({
indexName,
queryText: query,
topK,
filter
}) : await vectorStore.query({
indexName,
queryVector: await this.#embedOne(query),
topK,
filter
});
const queryTokens = tokenize(query, this.#tokenizeOptions);
const results = [];
for (const result of vectorResults) {
if (minScore !== void 0 && result.score < minScore) continue;
const id = result.metadata?.id ?? result.id;
const content = result.metadata?.text ?? "";
const { id: _id, text: _text, _startLineOffset, ...restMetadata } = result.metadata ?? {};
const rawLineRange = findLineRange(content, queryTokens, this.#tokenizeOptions);
const lineRange = this.#adjustLineRange(rawLineRange, result.metadata);
results.push({
id,
content,
score: result.score,
lineRange,
metadata: Object.keys(restMetadata).length > 0 ? restMetadata : void 0,
scoreDetails: { vector: result.score }
});
}
return results;
}
/**
* Hybrid search combining vector and BM25 scores
*/
async #searchHybrid(query, topK, minScore, vectorWeight = .5, filter) {
const expandedTopK = Math.min(topK * 2, 50);
const [vectorResults, bm25Results] = await Promise.all([this.#searchVector(query, expandedTopK, void 0, filter), Promise.resolve(this.#searchBM25(query, expandedTopK, void 0))]);
const normalizedBM25 = this.#normalizeBM25Scores(bm25Results);
const bm25Map = /* @__PURE__ */ new Map();
for (const result of normalizedBM25) bm25Map.set(result.id, result);
const vectorMap = /* @__PURE__ */ new Map();
for (const result of vectorResults) vectorMap.set(result.id, result);
const combinedResults = /* @__PURE__ */ new Map();
const allIds = /* @__PURE__ */ new Set([...vectorMap.keys(), ...bm25Map.keys()]);
const bm25Weight = 1 - vectorWeight;
for (const id of allIds) {
const vectorResult = vectorMap.get(id);
const bm25Result = bm25Map.get(id);
const vectorScore = vectorResult?.scoreDetails?.vector ?? 0;
const bm25Score = bm25Result?.score ?? 0;
const combinedScore = vectorWeight * vectorScore + bm25Weight * bm25Score;
const baseResult = vectorResult ?? bm25Result;
combinedResults.set(id, {
id,
content: baseResult.content,
score: combinedScore,
lineRange: bm25Result?.lineRange ?? vectorResult?.lineRange,
metadata: baseResult.metadata,
scoreDetails: {
vector: vectorResult?.scoreDetails?.vector,
bm25: bm25Result?.scoreDetails?.bm25
}
});
}
let results = Array.from(combinedResults.values());
results.sort((a, b) => b.score - a.score);
if (minScore !== void 0) results = results.filter((r) => r.score >= minScore);
return results.slice(0, topK);
}
/**
* Normalize BM25 scores to 0-1 range using min-max normalization
*/
#normalizeBM25Scores(results) {
if (results.length === 0) return results;
const scores = results.map((r) => r.scoreDetails?.bm25 ?? r.score);
const maxScore = Math.max(...scores);
const minScore = Math.min(...scores);
const range = maxScore - minScore;
if (range === 0) return results.map((r) => ({
...r,
score: 1
}));
return results.map((r) => ({
...r,
score: ((r.scoreDetails?.bm25 ?? r.score) - minScore) / range
}));
}
/**
* Adjust line range for chunked documents.
* If the document has a _startLineOffset in metadata, adjust the line range
* to reflect the original document's line numbers.
*/
#adjustLineRange(lineRange, metadata) {
if (!lineRange) return void 0;
const startLineOffset = metadata?._startLineOffset;
if (typeof startLineOffset !== "number") return lineRange;
return {
start: lineRange.start + startLineOffset - 1,
end: lineRange.end + startLineOffset - 1
};
}
};
// src/workspace/skills/local-skill-source.ts
/**
* LocalSkillSource - Read-only skill source backed by local filesystem.
*
* Uses Node.js fs/promises to read skills directly from disk.
* This allows skills to be loaded without requiring a full WorkspaceFilesystem.
*
* @example
* ```typescript
* const source = new LocalSkillSource({
* basePath: process.cwd(),
* });
*
* // skills paths are relative to basePath
* const skillsImpl = new WorkspaceSkillsImpl({
* source,
* skills: ['./skills', './node_modules/@company/skills'],
* });
* ```
*/
/**
* Read-only skill source that loads skills from the local filesystem.
*
* Unlike WorkspaceFilesystem, this doesn't provide write operations.
* Skills loaded from this source are read-only.
*/
var LocalSkillSource = class {
#basePath;
constructor(options = {}) {
this.#basePath = options.basePath ?? process.cwd();
}
/**
* Resolve a path relative to the base path.
* Handles both absolute and relative paths.
*/
#resolvePath(skillPath) {
if (path.isAbsolute(skillPath)) return skillPath;
return path.resolve(this.#basePath, skillPath);
}
async exists(skillPath) {
return fsExists(this.#resolvePath(skillPath));
}
async stat(skillPath) {
return fsStat(this.#resolvePath(skillPath), skillPath);
}
async readFile(skillPath) {
const resolved = this.#resolvePath(skillPath);
const content = await fs_promises.readFile(resolved);
if (isTextFile(skillPath)) return content.toString("utf-8");
return content;
}
async readdir(skillPath) {
const resolved = this.#resolvePath(skillPath);
const entries = await fs_promises.readdir(resolved, { withFileTypes: true });
return Promise.all(entries.map(async (entry) => {
const entryPath = path.join(resolved, entry.name);
const isSymlink = entry.isSymbolicLink();
let type = entry.isDirectory() ? "directory" : "file";
if (isSymlink) try {
type = (await fs_promises.stat(entryPath)).isDirectory() ? "directory" : "file";
} catch {
type = "file";
}
return {
name: entry.name,
type,
isSymlink: isSymlink || void 0
};
}));
}
async realpath(skillPath) {
return fs_promises.realpath(this.#resolvePath(skillPath));
}
};
// ../_internal-core/dist/frontmatter/index.js
const OPEN = "---";
const CLOSE = "\n---";
/**
* Split a markdown document into YAML frontmatter and body.
*
* A frontmatter block starts with `---` on the first line and ends at the next
* line that is exactly `---` (a longer dash run or `--- !tag` is not a delimiter). An optional language tag may follow the opening
* delimiter (`---yaml`); only YAML and JSON are accepted, and a `js`/`javascript`
* tag throws instead of being evaluated. Documents that do not start with `---`
* are returned unchanged with empty data.
*
* Throws when the frontmatter is not valid YAML or is not a mapping.
*/
function parseFrontmatter(input) {
const str = input.charCodeAt(0) === 65279 ? input.slice(1) : input;
if (!str.startsWith(OPEN) || str.charAt(3) === "-") return {
data: {},
content: str
};
let rest = str.slice(3);
const firstLineEnd = rest.indexOf("\n");
const language = (firstLineEnd === -1 ? rest : rest.slice(0, firstLineEnd)).trim().toLowerCase();
if (language) rest = firstLineEnd === -1 ? "" : rest.slice(firstLineEnd);
let closeIndex = rest.indexOf(CLOSE);
let closeEnd = -1;
while (closeIndex !== -1) {
closeEnd = closeIndex + 4;
while (rest[closeEnd] === " " || rest[closeEnd] === " ") closeEnd++;
const after = rest.charAt(closeEnd);
if (after === "" || after === "\n" || after === "\r") break;
closeIndex = rest.indexOf(CLOSE, closeIndex + 1);
}
const block = (closeIndex === -1 ? rest : rest.slice(0, closeIndex)).replace(/\r(?=\n|$)/g, "");
let content = closeIndex === -1 ? "" : rest.slice(closeEnd);
if (content.startsWith("\r")) content = content.slice(1);
if (content.startsWith("\n")) content = content.slice(1);
return {
data: parseBlock(block, language),
content
};
}
function parseBlock(block, language) {
if (block.replace(/^\s*#[^\n]*/gm, "").trim() === "") return {};
let data;
switch (language) {
case "":
case "yaml":
case "yml":
data = (0, yaml.parse)(block);
break;
case "json":
data = JSON.parse(block);
break;
case "js":
case "javascript": throw new Error("JavaScript frontmatter is not supported");
default: throw new Error(`Frontmatter language "${language}" is not supported`);
}
if (data === null || data === void 0) return {};
if (typeof data !== "object" || Array.isArray(data)) throw new Error("Frontmatter must be a mapping of fields");
return data;
}
/**
* Serialize `data` as a YAML frontmatter block followed by `content`.
* The block is omitted when `data` has no fields. The result always ends with a newline.
*/
function stringifyFrontmatter(content, data) {
const body = content.endsWith("\n") ? content : `${content}\n`;
if (Object.keys(data).length === 0) return body;
const block = (0, yaml.stringify)(data, { lineWidth: 0 }).trimEnd();
return `${OPEN}\n${block}\n${OPEN}\n${body}`;
}
// src/workspace/skills/schemas.ts
/**
* Validation for Skills following the Agent Skills specification.
* @see https://agentskills.io/specification
*
* This module uses plain validation functions instead of Zod to avoid
* version compatibility issues between Zod 3 and Zod 4.
*/
/**
* Recommended limits from the Agent Skills spec
*/
const SKILL_LIMITS = {
/** Recommended max tokens for instructions */
MAX_INSTRUCTION_TOKENS: 5e3,
/** Recommended max lines for SKILL.md */
MAX_INSTRUCTION_LINES: 500,
/** Max characters for name field */
MAX_NAME_LENGTH: 64,
/** Max characters for description field */
MAX_DESCRIPTION_LENGTH: 1024,
/** Max characters for compatibility field */
MAX_COMPATIBILITY_LENGTH: 500
};
/**
* Validate skill name according to spec:
* - 1-64 characters
* - Lowercase letters, numbers, hyphens only
* - Must not start or end with hyphen
* - Must not contain consecutive hyphens
*
* @param name - The name to validate
* @returns Array of error messages (empty if valid)
*/
function validateSkillName(name) {
const errors = [];
const fieldPath = "name";
if (typeof name !== "string") {
errors.push(`${fieldPath}: Expected string, received ${typeof name}`);
return errors;
}
if (name.length === 0) {
errors.push(`${fieldPath}: Skill name cannot be empty`);
return errors;
}
if (name.length > SKILL_LIMITS.MAX_NAME_LENGTH) errors.push(`${fieldPath}: Skill name must be ${SKILL_LIMITS.MAX_NAME_LENGTH} characters or less`);
if (!/^[a-z0-9-]+$/.test(name)) errors.push(`${fieldPath}: Skill name must contain only lowercase letters, numbers, and hyphens`);
if (name.startsWith("-") || name.endsWith("-")) errors.push(`${fieldPath}: Skill name must not start or end with a hyphen`);
if (name.includes("--")) errors.push(`${fieldPath}: Skill name must not contain consecutive hyphens`);
return errors;
}
/**
* Validate skill description according to spec:
* - 1-1024 characters
* - Cannot be empty or only whitespace
*
* @param description - The description to validate
* @returns Array of error messages (empty if valid)
*/
function validateSkillDescription(description) {
const errors = [];
const fieldPath = "description";
if (typeof description !== "string") {
errors.push(`${fieldPath}: Expected string, received ${typeof description}`);
return errors;
}
if (description.length === 0) {
errors.push(`${fieldPath}: Skill description cannot be empty`);
return errors;
}
if (description.length > SKILL_LIMITS.MAX_DESCRIPTION_LENGTH) errors.push(`${fieldPath}: Skill description must be ${SKILL_LIMITS.MAX_DESCRIPTION_LENGTH} characters or less`);
if (description.trim().length === 0) errors.push(`${fieldPath}: Skill description cannot be only whitespace`);
return errors;
}
/**
* Validate skill license (optional string).
*
* @param license - The license to validate
* @returns Array of error messages (empty if valid)
*/
function validateSkillLicense(license) {
const errors = [];
const fieldPath = "license";
if (license === void 0 || license === null) return errors;
if (typeof license !== "string") errors.push(`${fieldPath}: Expected string, received ${typeof license}`);
return errors;
}
/**
* Validate skill compatibility notes (optional).
* Accepts string or any JSON-serializable value for flexibility with external skills.
*
* @param compatibility - The compatibility value to validate
* @returns Array of error messages (empty if valid)
*/
function validateSkillCompatibility(_compatibility) {
return [];
}
/**
* Validate skill metadata field (optional Record<string, unknown>).
* Accepts any values (not just strings) for flexibility with external skills.
*
* @param metadata - The metadata object to validate
* @returns Array of error messages (empty if valid)
*/
function validateSkillMetadataField(metadata) {
const errors = [];
const fieldPath = "metadata";
if (metadata === void 0 || metadata === null) return errors;
if (typeof metadata !== "object" || Array.isArray(metadata)) {
errors.push(`${fieldPath}: Expected object, received ${Array.isArray(metadata) ? "array" : typeof metadata}`);
return errors;
}
return errors;
}
function validateUserInvocable(userInvocable) {
if (userInvocable === void 0 || typeof userInvocable === "boolean") return [];
return [`user-invocable: Expected boolean, received ${typeof userInvocable}`];
}
/**
* Rough token estimate (words * 1.3)
* This is a simple heuristic; actual token counts vary by model
*/
function estimateTokens(text) {
const words = text.split(/\s+/).filter(Boolean).length;
return Math.ceil(words * 1.3);
}
/**
* Count lines in text
*/
function countLines(text) {
return text.split("\n").length;
}
/**
* Validate skill metadata with optional content warnings.
*
* @param options.metadata - The skill metadata to validate
* @param options.directoryName - The directory name (must match skill name)
* @param options.instructions - Optional instructions content for token/line warnings
* @returns Validation result with errors and warnings
*
* @example
* ```typescript
* const result = validateSkillMetadata({
* metadata: { name: 'my-skill', description: 'A helpful skill' },
* directoryName: 'my-skill',
* instructions: '# Instructions\n...',
* });
*
* if (!result.valid) {
* console.error('Validation errors:', result.errors);
* }
* if (result.warnings.length > 0) {
* console.warn('Warnings:', result.warnings);
* }
* ```
*/
function validateSkillMetadata({ metadata, directoryName, instructions }) {
const errors = [];
const warnings = [];
if (typeof metadata !== "object" || metadata === null || Array.isArray(metadata)) {
errors.push(`Expected object, received ${metadata === null ? "null" : Array.isArray(metadata) ? "array" : typeof metadata}`);
return {
valid: false,
errors,
warnings
};
}
const data = metadata;
errors.push(...validateSkillName(data.name));
errors.push(...validateSkillDescription(data.description));
errors.push(...validateSkillLicense(data.license));
errors.push(...validateSkillCompatibility(data.compatibility));
errors.push(...validateUserInvocable(data["user-invocable"]));
errors.push(...validateSkillMetadataField(data.metadata));
if (directoryName && typeof data.name === "string" && data.name !== directoryName) errors.push(`Skill name "${data.name}" must match directory name "${directoryName}"`);
if (instructions) {
const lineCount = countLines(instructions);
const tokenEstimate = estimateTokens(instructions);
if (lineCount > SKILL_LIMITS.MAX_INSTRUCTION_LINES) warnings.push(`Instructions have ${lineCount} lines (recommended: <${SKILL_LIMITS.MAX_INSTRUCTION_LINES}). Consider moving content to references/.`);
if (tokenEstimate > SKILL_LIMITS.MAX_INSTRUCTION_TOKENS) warnings.push(`Instructions have ~${tokenEstimate} estimated tokens (recommended: <${SKILL_LIMITS.MAX_INSTRUCTION_TOKENS}). Consider moving content to references/.`);
}
return {
valid: errors.length === 0,
errors,
warnings
};
}
/**
* Parse SKILL.md content into frontmatter fields and body.
* Throws if the frontmatter is not valid YAML.
* @internal
*/
function extractSkillFrontmatter(content) {
const parsed = parseFrontmatter(content);
const data = parsed.data;
return {
metadata: {
name: data.name,
description: data.description,
license: data.license,
compatibility: data.compatibility,
"user-invocable": data["user-invocable"],
metadata: data.metadata
},
instructions: parsed.content.trim()
};
}
/**
* Validate raw SKILL.md content (frontmatter + body) using the same rules
* applied when skills are loaded. Pure: no filesystem access or logging.
*
* @param options.content - Full SKILL.md file content
* @param options.directoryName - Name of the directory the skill will live in (name must match)
*
* @example
* ```typescript
* const result = validateSkillContent({ content: skillMd, directoryName: 'my-skill' });
* if (!result.valid) throw new Error(result.errors.join('\n'));
* ```
*/
function validateSkillContent({ content, directoryName }) {
let extracted;
try {
extracted = extractSkillFrontmatter(content);
} catch (error) {
return {
valid: false,
errors: [`Invalid frontmatter: ${error instanceof Error ? error.message : String(error)}`],
warnings: []
};
}
return {
...validateSkillMetadata({
metadata: extracted.metadata,
directoryName,
instructions: extracted.instructions
}),
metadata: { ...extracted.metadata },
instructions: extracted.instructions
};
}
// src/workspace/skills/workspace-skills.ts
/**
* WorkspaceSkills - Skills implementation.
*
* Provides discovery and search operations for skills stored
* in skills paths. All operations are async.
*/
/** @internal Prefix of every search document ID owned by a request-scoped skills view. */
const SKILL_SCOPE_DOCUMENT_PREFIX = "skill-scope:";
/** Search document ID suffix for a skill's name + description document. */
const SKILL_METADATA_SOURCE = "SKILL.md#metadata";
/**
* Implementation of WorkspaceSkills interface.
*/
var WorkspaceSkillsImpl = class WorkspaceSkillsImpl {
#source;
#skillsResolver;
#searchEngine;
#validateOnLoad;
#assertAvailable;
#checkSkillFileMtime;
#searchNamespace;
#sharedSearchState;
#onIndexReadmit;
#onIndexIdle;
/** Search documents were released by the owner; re-index on next search use. */
#indexReleased = false;
#readmitPromise = null;
/** Index-dependent operations currently in flight on this view. */
#inFlight = 0;
#resolvedChildren = /* @__PURE__ */ new Set();
/** Request-scoped views for dynamic resolvers, cached by request and canonical path set. */
#scopedByRequest = /* @__PURE__ */ new WeakMap();
#scopedByPaths = /* @__PURE__ */ new Map();
/** Map of skill name -> array of candidates (supports same-named skills from different sources) */
#skills = /* @__PURE__ */ new Map();
/** Map of remapped location -> skill path, registered by SkillsProcessor formatLocation overrides */
#locationAliases = /* @__PURE__ */ new Map();
/** Whether skills have been discovered */
#initialized = false;
/** Promise for ongoing initialization (prevents concurrent discovery) */
#initPromise = null;
/** Timestamp of last skills discovery (for staleness check) */
#lastDiscoveryTime = 0;
/** Currently resolved skills paths (used to detect changes) */
#resolvedPaths = [];
/** Cached glob-resolved directories and per-pattern resolve timestamps */
#globDirCache = /* @__PURE__ */ new Map();
#globResolveTimes = /* @__PURE__ */ new Map();
static GLOB_RESOLVE_INTERVAL = 5e3;
static STALENESS_CHECK_COOLDOWN = 3e4;
/** In-flight refresh, shared by concurrent refresh() callers */
#refreshPromise = null;
/** In-flight maybeRefresh, shared so overlapping callers run one staleness walk */
#maybeRefreshPromise = null;
constructor(config) {
this.#source = config.source;
this.#skillsResolver = config.skills;
this.#searchEngine = config.searchEngine;
this.#validateOnLoad = config.validateOnLoad ?? true;
this.#assertAvailable = config.assertAvailable;
this.#checkSkillFileMtime = config.checkSkillFileMtime ?? false;
this.#searchNamespace = config.searchNamespace;
this.#sharedSearchState = config.sharedSearchState ?? { documentIds: /* @__PURE__ */ new Set() };
this.#onIndexReadmit = config.onIndexReadmit;
this.#onIndexIdle = config.onIndexIdle;
}
/**
* @internal True while this view (or a path-scoped child) is inside an
* index-dependent operation. Owners must not release a busy view's index.
*/
get isIndexBusy() {
if (this.#inFlight > 0) return true;
for (const child of this.#resolvedChildren) if (child.isIndexBusy) return true;
return false;
}
async #withIndexPinned(fn) {
this.#inFlight++;
try {
return await fn();
} finally {
this.#inFlight--;
if (this.#inFlight === 0) await this.#onIndexIdle?.();
}
}
/**
* @internal Drop every search document this view (and its path-scoped
* children) indexed. The catalog stays intact; the next search-dependent
* operation re-admits the view via `onIndexReadmit` and re-indexes.
*/
async releaseSearchIndex() {
if (!this.#searchEngine) return;
this.#indexReleased = true;
for (const candidates of this.#skills.values()) for (const skill of candidates) await this.#removeSkillFromIndex(skill);
for (const child of this.#resolvedChildren) await child.releaseSearchIndex();
}
/**
* Re-index the current catalog if the search documents were released.
* Returns true when a re-index happened (the index is then fully current).
*/
async #readmitIndexIfReleased() {
if (!this.#indexReleased || !this.#searchEngine) return false;
this.#readmitPromise ??= (async () => {
this.#indexReleased = false;
await this.#onIndexReadmit?.();
for (const candidates of this.#skills.values()) for (const skill of candidates) {
if (this.#indexReleased) break;
await this.#indexSkill(skill);
}
if (this.#indexReleased) for (const candidates of this.#skills.values()) for (const skill of candidates) await this.#removeSkillFromIndex(skill);
})().finally(() => {
this.#readmitPromise = null;
});
await this.#readmitPromise;
return true;
}
async getScoped(context) {
if (Array.isArray(this.#skillsResolver)) return this;
const requestContext = context?.requestContext;
if (requestContext && typeof requestContext === "object") {
const cached = this.#scopedByRequest.get(requestContext);
if (cached) return cached;
const scoped = this.#createScoped(context).catch((error) => {
this.#scopedByRequest.delete(requestContext);
throw error;
});
this.#scopedByRequest.set(requestContext, scoped);
return scoped;
}
return this.#createScoped(context);
}
async #createScoped(context) {
const paths = await this.#resolvePaths(context);
const key = [...paths].sort().join("\n");
const cached = this.#scopedByPaths.get(key);
if (cached) return cached;
const child = new WorkspaceSkillsImpl({
source: this.#source,
skills: paths,
searchEngine: this.#searchEngine,
validateOnLoad: this.#validateOnLoad,
assertAvailable: this.#assertAvailable,
checkSkillFileMtime: this.#checkSkillFileMtime,
searchNamespace: this.#searchNamespace ? `${this.#searchNamespace}/${encodeURIComponent(key)}` : encodeURIComponent(key),
sharedSearchState: this.#sharedSearchState,
onIndexReadmit: this.#onIndexReadmit,
onIndexIdle: this.#onIndexIdle
});
this.#resolvedChildren.add(child);
const scoped = Promise.resolve(child);
this.#scopedByPaths.set(key, scoped);
return scoped;
}
async list() {
await this.#ensureInitialized();
const results = [];
for (const candidates of this.#skills.values()) {
const canonicalCandidates = await this.#dedupeCanonicalCandidates(candidates);
for (const skill of canonicalCandidates) results.push({
name: skill.name,
path: skill.path,
description: skill.description,
license: skill.license,
compatibility: skill.compatibility,
"user-invocable": skill["user-invocable"],
metadata: skill.metadata
});
}
return results;
}
async get(name) {
await this.#ensureInitialized();
const skill = await this.#resolveByName(name) ?? this.#resolveByPath(name) ?? this.#resolveByAlias(name);
if (!skill) return null;
const { indexableContent: _, ...skillData } = skill;
return skillData;
}
async has(name) {
await this.#ensureInitialized();
return (await this.#resolveByName(name) ?? this.#resolveByPath(name) ?? this.#resolveByAlias(name)) !== null;
}
/**
* Register an alternate location string that resolves to the skill at `skillPath`.
* Called by SkillsProcessor when a `formatLocation` override remaps the advertised
* location, so the `skill` and `skill_read` tools can resolve the remapped
* location back to the underlying skill.
*
* Both the exact location and its `/SKILL.md`-stripped form are registered so
* lookups succeed whether or not the model preserves the suffix.
*/
registerLocationAlias(location, skillPath) {
this.#locationAliases.set(location, skillPath);
const normalized = location.replace(/\/SKILL\.md$/, "");
if (normalized !== location) this.#locationAliases.set(normalized, skillPath);
}
/**
* Resolve a skill by name with tie-breaking when multiple candidates exist.
* Priority: local > managed > external, then alphabetical path.
*/
async #resolveByName(name) {
const candidates = this.#skills.get(name);
if (!candidates || candidates.length === 0) return null;
return this.#tieBreak(candidates);
}
/**
* Resolve a skill by exact path (escape hatch for disambiguation).
* Searches across all candidate arrays.
* Accepts paths with or without a trailing `/SKILL.md` suffix, since
* SkillsProcessor.formatLocation() exposes `${path}/SKILL.md` to the LLM.
*/
#resolveByPath(skillPath) {
const normalized = skillPath.replace(/\/SKILL\.md$/, "");
for (const candidates of this.#skills.values()) {
const match = candidates.find((s) => s.path === normalized);
if (match) return match;
}
return null;
}
/**
* Resolve a skill via a registered location alias (formatLocation override).
* Tried last so canonical names and paths always win over aliases.
*/
#resolveByAlias(location) {
const target = this.#locationAliases.get(location) ?? this.#locationAliases.get(location.replace(/\/SKILL\.md$/, ""));
if (!target) return null;
return this.#resolveByPath(target);
}
async #getCanonicalSkillPath(skillPath) {
if (!this.#source.realpath) return skillPath;
try {
return await this.#source.realpath(skillPath);
} catch {
return skillPath;
}
}
async #dedupeCanonicalCandidates(candidates) {
const canonicalGroups = /* @__PURE__ */ new Map();
for (const candidate of candidates) {
const canonicalPath = await this.#getCanonicalSkillPath(candidate.path);
const group = canonicalGroups.get(canonicalPath) ?? [];
group.push(candidate);
canonicalGroups.set(canonicalPath, group);
}
const SOURCE_PRIORITY = {
local: 0,
managed: 1,
external: 2
};
return [...canonicalGroups.values()].map((group) => [...group].sort((a, b) => {
const aPri = SOURCE_PRIORITY[a.source.type] ?? 99;
const bPri = SOURCE_PRIORITY[b.source.type] ?? 99;
if (aPri !== bPri) return aPri - bPri;
return a.path.localeCompare(b.path);
})[0]);
}
/**
* Pick the winning skill from an array of same-named candidates.
* When there's only one candidate, returns it directly (no warning).
* When there are multiple, de-duplicates alias paths that point to the same
* canonical skill, then applies source-type priority and warns.
*
* Priority: local (0) > managed (1) > external (2).
* Throws if source-type priority can't resolve the tie (e.g., two distinct local skills with same name).
*/
async #tieBreak(candidates) {
if (candidates.length === 0) return null;
if (candidates.length === 1) return candidates[0];
const deduped = await this.#dedupeCanonicalCandidates(candidates);
if (deduped.length === 1) return deduped[0];
const SOURCE_PRIORITY = {
local: 0,
managed: 1,
external: 2
};
const sorted = [...deduped].sort((a, b) => {
const aPri = SOURCE_PRIORITY[a.source.type] ?? 99;
const bPri = SOURCE_PRIORITY[b.source.type] ?? 99;
if (aPri !== bPri) return aPri - bPri;
return a.path.localeCompare(b.path);
});
const winner = sorted[0];
const runnerUp = sorted[1];
if (winner.source.type === runnerUp.source.type) {
const paths = sorted.filter((s) => s.source.type === winner.source.type).map((s) => `"${s.path}"`).join(", ");
throw new Error(`[WorkspaceSkills] Cannot resolve skill "${winner.name}": multiple ${winner.source.type} skills found at ${paths}. Rename one or move it to a different source type.`);
}
console.warn(`[WorkspaceSkills] Multiple skills named "${winner.name}" found. Using "${winner.path}" (source: ${winner.source.type}). Other candidates: ${sorted.slice(1).map((s) => `"${s.path}" (${s.source.type})`).join(", ")}`);
return winner;
}
async refresh() {
this.#assertAvailable?.();
if (this.#refreshPromise) return this.#refreshPromise;
const inFlight = this.#withIndexPinned(() => this.#doRefresh()).finally(() => {
if (this.#refreshPromise === inFlight) this.#refreshPromise = null;
});
this.#refreshPromise = inFlight;
return inFlight;
}
/**
* Rebuild the catalog into fresh state and swap it in atomically.
*
* The current #skills map keeps serving list()/get() for the whole
* re-discovery; only when the new catalog is complete is #skills swapped,
* so readers always see a complete catalog (old or new, never partial).
* The shared search engine is then reconciled entry-by-entry (it also
* holds workspace content and cannot be rebuilt wholesale).
*/
async #doRefresh() {
for (;;) {
const pathsAtStart = this.#resolvedPaths;
const newSkills = /* @__PURE__ */ new Map();
await this.#discoverSkills(newSkills);
const oldSkills = this.#skills;
this.#skills = newSkills;
this.#initialized = true;
await this.#reconcileIndex(oldSkills, newSkills);
if (this.#resolvedPaths === pathsAtStart) {
this.#refreshPromise = null;
return;
}
}
}
/**
* Reconcile the shared search index after a catalog swap:
* remove entries for skills that disappeared, re-index skills whose
* content changed, index new skills. Unchanged skills are left alone.
* Transient index states during reconcile are acceptable; catalog
* consistency is guaranteed by the map swap, not by the index.
*/
async #reconcileIndex(oldSkills, newSkills) {
if (await this.#readmitIndexIfReleased()) return;
const flatten = (map) => {
const byPath = /* @__PURE__ */ new Map();
for (const candidates of map.values()) for (const skill of candidates) byPath.set(skill.path, skill);
return byPath;
};
const oldByPath = flatten(oldSkills);
const newByPath = flatten(newSkills);
for (const [path, oldSkill] of oldByPath) if (!newByPath.has(path)) await this.#removeSkillFromIndex(oldSkill);
for (const [path, newSkill] of newByPath) {
const oldSkill = oldByPath.get(path);
if (oldSkill && oldSkill.instructions === newSkill.instructions && oldSkill.name === newSkill.name && oldSkill.description === newSkill.description && oldSkill.references.length === newSkill.references.length && oldSkill.references.every((r, i) => r === newSkill.references[i])) continue;
if (oldSkill) await this.#removeSkillFromIndex(oldSkill);
await this.#indexSkill(newSkill);
}
}
async maybeRefresh(context) {
await this.#ensureInitialized();
if (this.#maybeRefreshPromise) return this.#maybeRefreshPromise;
this.#maybeRefreshPromise = this.#doMaybeRefresh(context).finally(() => {
this.#maybeRefreshPromise = null;
});
return this.#maybeRefreshPromise;
}
async #doMaybeRefresh(context) {
const currentPaths = await this.#resolvePaths(context);
if (!this.#arePathsEqual(this.#resolvedPaths, currentPaths)) {
this.#resolvedPaths = currentPaths;
await this.refresh();
return;
}
if (await this.#isSkillsPathStale()) await this.refresh();
}
async addSkill(skillPath) {
await this.#ensureInitialized();
return this.#withIndexPinned(() => this.#doAddSkill(skillPath));
}
async #doAddSkill(skillPath) {
await this.#readmitIndexIfReleased();
let skillFilePath;
let dirName;
if (isSkillFilePath(skillPath)) {
skillFilePath = skillPath;
dirName = splitPathSegments(this.#getParentPath(skillPath)).pop() || "unknown";
} else {
skillFilePath = this.#joinPath(skillPath, "SKILL.md");
dirName = splitPathSegments(skillPath).pop() || "unknown";
}
const source = this.#inferSource(skillPath);
const skill = await this.#parseSkillFile(skillFilePath, dirName, source);
const candidates = this.#skills.get(skill.name) ?? [];
const existingIdx = candidates.findIndex((s) => s.path === skill.path);
if (existingIdx >= 0) {
await this.#removeSkillFromIndex(candidates[existingIdx]);
candidates[existingIdx] = skill;
} else candidates.push(skill);
this.#skills.set(skill.name, candidates);
await this.#indexSkill(skill);
this.#lastDiscoveryTime = Date.now();
}
async removeSkill(skillName) {
await this.#ensureInitialized();
const skill = await this.#resolveByName(skillName) ?? this.#resolveByPath(skillName);
if (!skill) return;
await this.#removeSkillFromIndex(skill);
const candidates = this.#skills.get(skill.name);
if (candidates) {
const idx = candidates.findIndex((s) => s.path === skill.path);
if (idx >= 0) candidates.splice(idx, 1);
if (candidates.length === 0) this.#skills.delete(skill.name);
}
this.#lastDiscoveryTime = Date.now();
}
/**
* Resolve skills paths from the resolver (static array or function).
*/
async #resolvePaths(context) {
if (Array.isArray(this.#skillsResolver)) return this.#skillsResolver;
return this.#skillsResolver(context ?? {});
}
/**
* Compare two path arrays for equality (order-independent).
*/
#arePathsEqual(a, b) {
if (a.length !== b.length) return false;
const sortedA = [...a].sort();
const sortedB = [...b].sort();
return sortedA.every((path, i) => path === sortedB[i]);
}
async search(query, options = {}) {
await this.#ensureInitialized();
if (!this.#searchEngine) return this.#simpleSearch(query, options);
return this.#withIndexPinned(() => this.#indexedSearch(query, options));
}
async #indexedSearch(query, options) {
await this.#readmitIndexIfReleased();
const { topK = 5, minScore, skillNames, includeReferences = true, mode } = options;
const totalIndexedDocuments = this.#searchNamespace ? this.#sharedSearchState.documentIds.size : [...this.#skills.values()].reduce((count, candidates) => count + candidates.reduce((skillCount, skill) => skillCount + 2 + skill.references.length, 0), 0);
const expandedTopK = Math.max(skillNames ? topK * 3 : topK, totalIndexedDocuments);
const searchResults = await this.#searchEngine.search(query, {
topK: expandedTopK,
minScore,
mode
});
const results = [];
const seenCanonicalSources = /* @__PURE__ */ new Set();
for (const result of searchResults) {
const skillPath = result.metadata?.skillPath;
const source = result.metadata?.source;
if (!skillPath || !source) continue;
if (this.#searchNamespace && result.metadata?.skillScope !== this.#searchNamespace) continue;
const matchedSkill = this.#resolveByPath(skillPath);
if (!matchedSkill) continue;
const skill = await this.#resolveByName(matchedSkill.name) ?? matchedSkill;
if (skillNames && !skillNames.includes(skill.name)) continue;
if (!includeReferences && source !== "SKILL.md") continue;
const canonicalSourceKey = `${skill.path}:${source}`;
if (seenCanonicalSources.has(canonicalSourceKey)) continue;
seenCanonicalSources.add(canonicalSourceKey);
const isMetadataHit = result.id === this.#searchDocumentId(skillPath, SKILL_METADATA_SOURCE);
results.push({
skillName: skill.name,
skillPath: skill.path,
source,
content: isMetadataHit ? skill.description : result.content,
score: result.score,
lineRange: isMetadataHit ? void 0 : result.lineRange,
scoreDetails: result.scoreDetails
});
if (results.length >= topK) break;
}
return results;
}
async getReference(skillName, referencePath) {
await this.#ensureInitialized();
const skill = await this.#resolveByName(skillName) ?? this.#resolveByPath(skillName);
if (!skill) return null;
const safeRefPath = this.#assertRelativePath(referencePath, "reference");
const refFilePath = this.#joinPath(skill.path, safeRefPath);
if (!await this.#source.exists(refFilePath)) return null;
try {
const content = await this.#source.readFile(refFilePath);
return typeof content === "string" ? content : content.toString("utf-8");
} catch {
return null;
}
}
async getScript(skillName, scriptPath) {
await this.#ensureInitialized();
const skill = await this.#resolveByName(skillName) ?? this.#resolveByPath(skillName);
if (!skill) return null;
const safeScriptPath = this.#assertRelativePath(scriptPath, "script");
const scriptFilePath = this.#joinPath(skill.path, safeScriptPath);
if (!await this.#source.exists(scriptFilePath)) return null;
try {
const content = await this.#source.readFile(scriptFilePath);
return typeof content === "string" ? content : content.toString("utf-8");
} catch {
return null;
}
}
async getAsset(skillName, assetPath) {
await this.#ensureInitialized();
const skill = await this.#resolveByName(skillName) ?? this.#resolveByPath(skillName);
if (!skill) return null;
const safeAssetPath = this.#assertRelativePath(assetPath, "asset");
const assetFilePath = this.#joinPath(skill.path, safeAssetPath);
if (!await this.#source.exists(assetFilePath)) return null;
try {
const content = await this.#source.readFile(assetFilePath);
return typeof content === "string" ? Buffer.from(content, "utf-8") : content;
} catch {
return null;
}
}
async listReferences(skillName) {
await this.#ensureInitialized();
return (await this.#resolveByName(skillName) ?? this.#resolveByPath(skillName))?.references ?? [];
}
async listScripts(skillName) {
await this.#ensureInitialized();
return (await this.#resolveByName(skillName) ?? this.#resolveByPath(skillName))?.scripts ?? [];
}
async listAssets(skillName) {
await this.#ensureInitialized();
return (await this.#resolveByName(skillName) ?? this.#resolveByPath(skillName))?.assets ?? [];
}
/**
* Ensure skills have been discovered.
* Uses a promise to prevent concurrent discovery.
*/
async #ensureInitialized() {
this.#assertAvailable?.();
if (this.#initialized) return;
if (this.#initPromise) {
await this.#initPromise;
return;
}
this.#initPromise = (async () => {
try {
if (this.#resolvedPaths.length === 0) this.#resolvedPaths = await this.#resolvePaths();
const newSkills = /* @__PURE__ */ new Map();
await this.#discoverSkills(newSkills);
const oldSkills = this.#skills;
this.#skills = newSkills;
this.#initialized = true;
await this.#reconcileIndex(oldSkills, newSkills);
} finally {
this.#initPromise = null;
}
})();
await this.#initPromise;
}
/**
* Add a skill to a candidates map, keyed by name.
* Replaces an existing entry at the same path (update case), otherwise appends.
*/
#addToSkillsMap(skill, target) {
const candidates = target.get(skill.name) ?? [];
const idx = candidates.findIndex((s) => s.path === skill.path);
if (idx >= 0) candidates[idx] = skill;
else candidates.push(skill);
target.set(skill.name, candidates);
}
/**
* Discover skills from all skills paths.
* Uses currently resolved paths (must be set before calling).
*
* Paths can be plain directories, glob patterns, or direct
* skill references (e.g., '/skills/my-skill/SKILL.md').
*
* Uses resolvePathPattern for unified glob resolution. File matches
* pointing to SKILL.md are loaded directly; directory matches are
* tried as direct skills first, then scanned for subdirectories.
*/
async #discoverSkills(target) {
this.#globDirCache.clear();
this.#globResolveTimes.clear();
const readdir = async (dir) => {
return (await this.#source.readdir(dir)).map((e) => ({
name: e.name,
type: e.type,
isSymlink: e.isSymlink
}));
};
for (const rawSkillsPath of this.#resolvedPaths) {
const skillsPath = rawSkillsPath.length > 1 && rawSkillsPath.endsWith("/") ? rawSkillsPath.slice(0, -1) : rawSkillsPath;
const source = this.#determineSource(skillsPath);
if (isGlobPattern(skillsPath)) {
const resolved = await resolvePathPattern(skillsPath, readdir, {
dot: true,
maxDepth: 4
});
const dirs = /* @__PURE__ */ new Set();
for (const entry of resolved) if (entry.type === "directory") dirs.add(entry.path);
else dirs.add(this.#getParentPath(entry.path));
this.#globDirCache.set(skillsPath, [...dirs]);
this.#globResolveTimes.set(skillsPath, Date.now());
const results = await Promise.allSettled(resolved.map(async (entry) => {
if (entry.type === "file") await this.#discoverDirectSkill(entry.path, source, target);
else if (!await this.#discoverDirectSkill(entry.path, source, target)) await this.#discoverSkillsInPath(entry.path, source, target);
}));
for (const [index, result] of results.entries()) {
const entry = resolved[index];
if (entry && result.status === "rejected") {
const error = result.reason;
if (isProgrammingError(error)) throw error;
if (error instanceof Error) console.error(`[WorkspaceSkills] Failed to load skill from ${entry.path}:`, error.message);
}
}
} else if (!await this.#discoverDirectSkill(skillsPath, source, target)) await this.#discoverSkillsInPath(skillsPath, source, target);
}
this.#lastDiscoveryTime = Date.now();
}
/**
* Discover skills in a single path
*/
async #discoverSkillsInPath(skillsPath, source, target) {
try {
if (!await this.#source.exists(skillsPath)) return;
} catch (error) {
if (isProgrammingError(error)) throw error;
const msg = error instanceof Error ? error.message : String(error);
let hint = "";
if (skillsPath.startsWith("/") && msg.includes("Permission denied")) {
const relativePath = skillsPath.slice(1);
try {
if (await this.#source.exists(relativePath)) hint = ` (did you mean to use the relative path "${relativePath}"?)`;
} catch {}
}
console.warn(`[WorkspaceSkills] Cannot access skills path "${skillsPath}": ${msg}${hint}`);
return;
}
try {
const entries = await this.#source.readdir(skillsPath);
const results = await Promise.allSettled(entries.filter((entry) => entry.type === "directory").map(async (entry) => {
const entryPath = this.#joinPath(skillsPath, entry.name);
const skillFilePath = this.#joinPath(entryPath, "SKILL.md");
if (await this.#source.exists(skillFilePath)) return await this.#parseSkillFile(skillFilePath, entry.name, source);
return null;
}));
for (const result of results) if (result.status === "fulfilled" && result.value) this.#addToSkillsMap(result.value, target);
else if (result.status === "rejected") {
const error = result.reason;
if (isProgrammingError(error)) throw error;
if (error instanceof Error) console.error(`[WorkspaceSkills] Failed to load skill from ${skillsPath}:`, error.message);
}
} catch (error) {
if (isProgrammingError(error)) throw error;
if (error instanceof Error) console.error(`[WorkspaceSkills] Failed to scan skills directory ${skillsPath}:`, error.message);
}
}
/**
* Attempt to discover a skill from a direct path reference.
*
* Handles two cases:
* - Path ends with `/SKILL.md` → parse directly, extract dirName from parent
* - Path is a directory containing `SKILL.md` → parse it as a single skill
*
* Returns `true` if the path was a direct skill reference (skip subdirectory scan),
* `false` to fall through to the normal subdirectory scan.
*/
async #discoverDirectSkill(skillsPath, source, target) {
try {
if (isSkillFilePath(skillsPath)) {
if (!await this.#source.exists(skillsPath)) return true;
const skillDir = this.#getParentPath(skillsPath);
const dirName = splitPathSegments(skillDir).pop() || skillDir;
try {
const skill = await this.#parseSkillFile(skillsPath, dirName, source);
this.#addToSkillsMap(skill, target);
} catch (error) {
if (error instanceof Error) console.error(`[WorkspaceSkills] Failed to load skill from ${skillsPath}:`, error.message);
}
return true;
}
if (await this.#source.exists(skillsPath)) {
const skillFilePath = this.#joinPath(skillsPath, "SKILL.md");
if (await this.#source.exists(skillFilePath)) {
const dirName = splitPathSegments(skillsPath).pop() || skillsPath;
try {
const skill = await this.#parseSkillFile(skillFilePath, dirName, source);
this.#addToSkillsMap(skill, target);
} catch (error) {
if (error instanceof Error) console.error(`[WorkspaceSkills] Failed to load skill from ${skillFilePath}:`, error.message);
}
return true;
}
}
return false;
} catch (error) {
if (isProgrammingError(error)) throw error;
return false;
}
}
/**
* Check if any skills path directory has been modified since last discovery.
* Compares directory mtime to lastDiscoveryTime.
* For glob patterns, checks the walk root and expanded directories.
*/
async #isSkillsPathStale() {
if (this.#lastDiscoveryTime === 0) return true;
if (Date.now() - this.#lastDiscoveryTime < WorkspaceSkillsImpl.STALENESS_CHECK_COOLDOWN) return false;
for (const skillsPath of this.#resolvedPaths) {
let pathsToCheck;
if (isGlobPattern(skillsPath)) {
const now = Date.now();
if (now - (this.#globResolveTimes.get(skillsPath) ?? 0) > WorkspaceSkillsImpl.GLOB_RESOLVE_INTERVAL || !this.#globDirCache.has(skillsPath)) {
const readdir = async (dir) => {
return (await this.#source.readdir(dir)).map((e) => ({
name: e.name,
type: e.type,
isSymlink: e.isSymlink
}));
};
const resolved = await resolvePathPattern(skillsPath, readdir, {
dot: true,
maxDepth: 4
});
const dirs = /* @__PURE__ */ new Set();
for (const entry of resolved) if (entry.type === "directory") dirs.add(entry.path);
else dirs.add(this.#getParentPath(entry.path));
const dirList = [...dirs];
this.#globDirCache.set(skillsPath, dirList);
this.#globResolveTimes.set(skillsPath, now);
}
pathsToCheck = this.#globDirCache.get(skillsPath) ?? [];
} else pathsToCheck = [skillsPath];
for (const pathToCheck of pathsToCheck) try {
const stat = await this.#source.stat(pathToCheck);
if (stat.modifiedAt.getTime() > this.#lastDiscoveryTime) return true;
if (stat.type !== "directory") continue;
if (this.#checkSkillFileMtime) {
const directSkillFilePath = this.#joinPath(pathToCheck, "SKILL.md");
try {
const directSkillFileStat = await this.#source.stat(directSkillFilePath);
if (directSkillFileStat.type === "file" && directSkillFileStat.modifiedAt.getTime() > this.#lastDiscoveryTime) return true;
} catch {}
}
const dirEntries = (await this.#source.readdir(pathToCheck)).filter((entry) => entry.type === "directory");
if (dirEntries.length > 0) {
if ((await Promise.all(dirEntries.map(async (entry) => {
const entryPath = this.#joinPath(pathToCheck, entry.name);
try {
if ((await this.#source.stat(entryPath)).modifiedAt.getTime() > this.#lastDiscoveryTime) return true;
if (this.#checkSkillFileMtime) {
const skillFilePath = this.#joinPath(entryPath, "SKILL.md");
try {
const skillFileStat = await this.#source.stat(skillFilePath);
return skillFileStat.type === "file" && skillFileStat.modifiedAt.getTime() > this.#lastDiscoveryTime;
} catch {}
}
} catch {}
return false;
}))).some((stale) => stale)) return true;
}
} catch {
continue;
}
}
return false;
}
/**
* Parse a SKILL.md file
*/
async #parseSkillFile(filePath, dirName, source) {
const rawContent = await this.#source.readFile(filePath);
const { metadata: frontmatter, instructions: body } = extractSkillFrontmatter(typeof rawContent === "string" ? rawContent : rawContent.toString("utf-8"));
const skillPath = this.#getParentPath(filePath);
const metadata = {
...frontmatter,
path: skillPath
};
if (this.#validateOnLoad) {
const validation = this.#validateSkillMetadata(metadata, dirName, body);
if (!validation.valid) throw new Error(`Invalid skill metadata in ${filePath}:\n${validation.errors.join("\n")}`);
}
const [references, scripts, assets] = await Promise.all([
this.#discoverFilesInSubdir(skillPath, "references"),
this.#discoverFilesInSubdir(skillPath, "scripts"),
this.#discoverFilesInSubdir(skillPath, "assets")
]);
const indexableContent = await this.#buildIndexableContent(body, skillPath, references);
return {
...metadata,
instructions: body,
source,
references,
scripts,
assets,
indexableContent
};
}
/**
* Validate skill metadata (delegates to shared validation function)
*/
#validateSkillMetadata(metadata, dirName, instructions) {
const result = validateSkillMetadata({
metadata,
directoryName: dirName,
instructions
});
if (result.warnings.length > 0) for (const warning of result.warnings) console.warn(`[WorkspaceSkills] ${metadata.name}: ${warning}`);
return result;
}
/**
* Discover files in a subdirectory of a skill (references/, scripts/, assets/)
*/
async #discoverFilesInSubdir(skillPath, subdir) {
const subdirPath = this.#joinPath(skillPath, subdir);
const files = [];
if (!await this.#source.exists(subdirPath)) return files;
try {
await this.#walkDirectory(subdirPath, subdirPath, (relativePath) => {
files.push(relativePath);
});
} catch {}
return files;
}
/**
* Walk a directory recursively and call callback for each file.
* Limited to maxDepth (default 20) to prevent stack overflow on deep hierarchies.
*/
async #walkDirectory(basePath, dirPath, callback, depth = 0, maxDepth = 20) {
if (depth >= maxDepth) return;
const entries = await this.#source.readdir(dirPath);
for (const entry of entries) {
const entryPath = this.#joinPath(dirPath, entry.name);
if (entry.type === "directory" && !entry.isSymlink) await this.#walkDirectory(basePath, entryPath, callback, depth + 1, maxDepth);
else callback(entryPath.substring(basePath.length + 1));
}
}
/**
* Build indexable content from instructions and references
*/
async #buildIndexableContent(instructions, skillPath, references) {
const parts = [instructions];
const refContents = await Promise.all(references.map(async (refPath) => {
const fullPath = this.#joinPath(skillPath, "references", refPath);
try {
const rawContent = await this.#source.readFile(fullPath);
return typeof rawContent === "string" ? rawContent : rawContent.toString("utf-8");
} catch {
return null;
}
}));
for (const content of refContents) if (content !== null) parts.push(content);
return parts.join("\n\n");
}
#searchDocumentId(skillPath, source) {
const id = `skill:${skillPath}:${source}`;
return this.#searchNamespace ? `${SKILL_SCOPE_DOCUMENT_PREFIX}${this.#searchNamespace}:${id}` : id;
}
/**
* Remove a skill's entries from the search index.
*/
async #removeSkillFromIndex(skill) {
if (!this.#searchEngine?.remove) return;
const ids = [
this.#searchDocumentId(skill.path, "SKILL.md"),
this.#searchDocumentId(skill.path, SKILL_METADATA_SOURCE),
...skill.references.map((r) => this.#searchDocumentId(skill.path, r))
];
for (const id of ids) try {
await this.#searchEngine.remove(id);
this.#sharedSearchState.documentIds.delete(id);
} catch {}
}
/**
* Infer the ContentSource for a skill path by matching against resolved paths.
*/
#inferSource(skillPath) {
for (const rp of this.#resolvedPaths) if (skillPath === rp || skillPath.startsWith(rp + "/")) return this.#determineSource(rp);
return this.#determineSource(skillPath);
}
/**
* Index a skill for search
*/
async #indexSkill(skill) {
if (!this.#searchEngine || this.#indexReleased) return;
const skillDocumentId = this.#searchDocumentId(skill.path, "SKILL.md");
await this.#searchEngine.index({
id: skillDocumentId,
content: skill.instructions,
metadata: {
skillPath: skill.path,
source: "SKILL.md",
...this.#searchNamespace ? { skillScope: this.#searchNamespace } : {}
}
});
this.#sharedSearchState.documentIds.add(skillDocumentId);
const metadataDocumentId = this.#searchDocumentId(skill.path, SKILL_METADATA_SOURCE);
await this.#searchEngine.index({
id: metadataDocumentId,
content: `${skill.name}\n${skill.description}`,
metadata: {
skillPath: skill.path,
source: "SKILL.md",
...this.#searchNamespace ? { skillScope: this.#searchNamespace } : {}
}
});
this.#sharedSearchState.documentIds.add(metadataDocumentId);
await Promise.all(skill.references.map(async (refPath) => {
const fullPath = this.#joinPath(skill.path, "references", refPath);
try {
const rawContent = await this.#source.readFile(fullPath);
const content = typeof rawContent === "string" ? rawContent : rawContent.toString("utf-8");
const referenceDocumentId = this.#searchDocumentId(skill.path, refPath);
await this.#searchEngine.index({
id: referenceDocumentId,
content,
metadata: {
skillPath: skill.path,
source: `references/${refPath}`,
...this.#searchNamespace ? { skillScope: this.#searchNamespace } : {}
}
});
this.#sharedSearchState.documentIds.add(referenceDocumentId);
} catch {}
}));
if (this.#indexReleased) await this.#removeSkillFromIndex(skill);
}
/**
* Simple text search fallback when no search engine is configured
*/
async #simpleSearch(query, options) {
const { topK = 5, skillNames, includeReferences = true } = options;
const skills = [];
for (const candidates of this.#skills.values()) {
const skill = await this.#tieBreak(candidates);
if (skill && (!skillNames || skillNames.includes(skill.name))) skills.push(skill);
}
const nameWords = new Set(skills.flatMap((skill) => skill.name.toLowerCase().split(/[-_\s]+/)));
const allTerms = [...new Set(query.toLowerCase().split(/\s+/).map((word) => word.replace(/^[^\p{L}\p{N}]+|[^\p{L}\p{N}]+$/gu, "")).filter(Boolean))];
const longTerms = allTerms.filter((term) => term.length > 2 || nameWords.has(term));
const terms = longTerms.length > 0 ? longTerms : allTerms;
if (terms.length === 0) return this.#listSkillDocuments(skills, topK, includeReferences);
const skillHits = [];
for (const skill of skills) {
const lowerAbout = `${skill.name}\n${skill.description}`.toLowerCase();
const lowerBody = skill.instructions.toLowerCase();
let aboutMatches = 0;
let weighted = 0;
for (const term of terms) if (lowerAbout.includes(term)) {
aboutMatches++;
weighted += 1;
} else if (lowerBody.includes(term)) weighted += .5;
if (weighted > 0) skillHits.push({
skillName: skill.name,
skillPath: skill.path,
source: "SKILL.md",
content: aboutMatches > 0 ? skill.description : skill.instructions.substring(0, 200),
score: weighted / terms.length
});
}
skillHits.sort((a, b) => b.score - a.score);
const referenceHits = [];
if (includeReferences && skillHits.filter((hit) => hit.score > .5).length < topK) {
const skillsByPath = new Map(skills.map((skill) => [skill.path, skill]));
const byRank = skillHits.map((hit) => skillsByPath.get(hit.skillPath));
for (const hit of skillHits) skillsByPath.delete(hit.skillPath);
byRank.push(...skillsByPath.values());
search: for (const skill of byRank) for (const refPath of skill.references) {
const content = await this.getReference(skill.name, `references/${refPath}`);
if (!content) continue;
const lower = content.toLowerCase();
const matched = terms.filter((term) => lower.includes(term)).length;
if (matched === 0) continue;
referenceHits.push({
skillName: skill.name,
skillPath: skill.path,
source: `references/${refPath}`,
content: content.substring(0, 200),
score: .5 * matched / terms.length
});
if (referenceHits.length >= topK) break search;
}
}
return [...skillHits, ...referenceHits].sort((a, b) => b.score - a.score).slice(0, topK);
}
/** Empty-query search: every skill and reference file, in discovery order. */
async #listSkillDocuments(skills, topK, includeReferences) {
const results = [];
for (const skill of skills) {
if (results.length >= topK) break;
results.push({
skillName: skill.name,
skillPath: skill.path,
source: "SKILL.md",
content: skill.instructions.substring(0, 200),
score: 1
});
if (!includeReferences) continue;
for (const refPath of skill.references) {
if (results.length >= topK) break;
const content = await this.getReference(skill.name, `references/${refPath}`);
if (content) results.push({
skillName: skill.name,
skillPath: skill.path,
source: `references/${refPath}`,
content: content.substring(0, 200),
score: .8
});
}
}
return results;
}
/**
* Determine the source type based on the path
*/
#determineSource(skillsPath) {
if (splitPathSegments(skillsPath).includes("node_modules")) return {
type: "external",
packagePath: skillsPath
};
const normalized = skillsPath.replace(/\\/g, "/");
if (normalized.includes("/.mastra/skills") || normalized.startsWith(".mastra/skills")) return {
type: "managed",
mastraPath: skillsPath
};
return {
type: "local",
projectPath: skillsPath
};
}
/**
* Join path segments (workspace paths use forward slashes)
*/
#joinPath(...segments) {
return segments.map((seg, i) => i === 0 ? stripTrailingSlashes(seg) : stripLeadingAndTrailingSlashes(seg)).filter(Boolean).join("/");
}
/**
* Validate and normalize a relative path to prevent directory traversal.
* Throws if the path contains traversal segments (..) or is absolute.
*/
#assertRelativePath(input, label) {
const normalized = input.replace(/\\/g, "/");
const segments = normalized.split("/").filter((seg) => Boolean(seg) && seg !== ".");
if (normalized.startsWith("/") || segments.some((seg) => seg === "..")) throw new Error(`Invalid ${label} path: ${input}`);
return segments.join("/");
}
/**
* Get parent path
*/
#getParentPath(path) {
const lastSlash = Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\"));
return lastSlash > 0 ? path.substring(0, lastSlash) : "/";
}
};
const DEFAULT_MAX_CACHED_SOURCES = 16;
let nextResolvedSkillsOwnerId = 0;
/**
* WorkspaceSkills backed by a per-request skill source.
*
* `getScoped()` resolves the source for the request and returns a
* `WorkspaceSkillsImpl` bound to it. Views are cached per resolved source
* instance and per request context. Sources are keyed by object identity only
* (never by a user-supplied `id`) so two tenants can never share a view by
* accident. Each source gets its own search namespace so same-named skills
* from different sources never bleed into each other's search results.
*
* The per-source cache is a bounded LRU: when a source is evicted, every
* document it indexed into the shared search engine is removed, so a resolver
* that returns a new filesystem on every request cannot grow the index
* without bound. An evicted view that is still in use re-admits itself (and
* re-indexes) on its next search, so callers never observe missing results.
* Resolvers that return a stable instance per tenant keep that tenant's
* discovery cache warm across requests.
*
* Calls made directly on this instance (without `getScoped`) resolve the
* source with an empty context, mirroring how workspace tools resolve the
* filesystem when no request context is available.
*/
var ResolvedSourceWorkspaceSkills = class {
#resolver;
#config;
#maxCachedSources;
#ownerId = nextResolvedSkillsOwnerId++;
#sharedSearchState = { documentIds: /* @__PURE__ */ new Set() };
#scopedByRequest = /* @__PURE__ */ new WeakMap();
/** Map insertion order doubles as LRU order; hits re-insert. */
#bySource = /* @__PURE__ */ new Map();
#nextSourceId = 0;
constructor(config) {
const { source, maxCachedSources, ...rest } = config;
this.#resolver = source;
this.#config = rest;
if (rest.searchEngine && typeof rest.searchEngine.remove !== "function") throw new TypeError("ResolvedSourceWorkspaceSkills searchEngine must implement remove()");
if (maxCachedSources !== void 0 && (!Number.isSafeInteger(maxCachedSources) || maxCachedSources < 1)) throw new RangeError(`maxCachedSources must be a positive integer, received ${String(maxCachedSources)}`);
this.#maxCachedSources = maxCachedSources ?? DEFAULT_MAX_CACHED_SOURCES;
}
async getScoped(context) {
const requestContext = context?.requestContext;
if (requestContext && typeof requestContext === "object") {
const cached = this.#scopedByRequest.get(requestContext);
if (cached) return cached;
const scoped = this.#createScoped(context).catch((error) => {
this.#scopedByRequest.delete(requestContext);
throw error;
});
this.#scopedByRequest.set(requestContext, scoped);
return scoped;
}
return this.#createScoped(context ?? {});
}
async #createScoped(context) {
const source = await this.#resolver(context);
let impl = this.#bySource.get(source);
if (impl) await this.#admit(source, impl);
else {
impl = new WorkspaceSkillsImpl({
...this.#config,
source,
searchNamespace: `owner-${this.#ownerId}/source-${this.#nextSourceId++}`,
sharedSearchState: this.#sharedSearchState,
onIndexReadmit: () => this.#admit(source, impl),
onIndexIdle: () => this.#trimOverflow()
});
await this.#admit(source, impl);
}
return impl.getScoped(context);
}
/**
* Insert or bump a source to most-recently-used, evicting overflow.
*
* Only idle views are evicted: a view inside an in-flight search/refresh
* keeps its documents until it finishes, so concurrent live views beyond the
* bound still return results. The cache may therefore briefly exceed
* `maxCachedSources` under concurrency; it settles back on the next admit.
*/
async #admit(source, impl) {
this.#bySource.delete(source);
this.#bySource.set(source, impl);
await this.#trimOverflow(impl);
}
/** Release least-recently-used idle views until the cache is within bound. */
async #trimOverflow(keep) {
let overflow = this.#bySource.size - this.#maxCachedSources;
for (const [candidateSource, candidate] of [...this.#bySource]) {
if (overflow <= 0) break;
if (candidate === keep || candidate.isIndexBusy) continue;
this.#bySource.delete(candidateSource);
overflow--;
await candidate.releaseSearchIndex();
}
}
async list() {
return (await this.getScoped()).list();
}
async get(name) {
return (await this.getScoped()).get(name);
}
async has(name) {
return (await this.getScoped()).has(name);
}
async refresh() {
return (await this.getScoped()).refresh();
}
async maybeRefresh(context) {
return (await this.getScoped(context)).maybeRefresh(context);
}
async search(query, options) {
return (await this.getScoped()).search(query, options);
}
async getReference(skillName, referencePath) {
return (await this.getScoped()).getReference(skillName, referencePath);
}
async getScript(skillName, scriptPath) {
return (await this.getScoped()).getScript(skillName, scriptPath);
}
async getAsset(skillName, assetPath) {
return (await this.getScoped()).getAsset(skillName, assetPath);
}
async listReferences(skillName) {
return (await this.getScoped()).listReferences(skillName);
}
async listScripts(skillName) {
return (await this.getScoped()).listScripts(skillName);
}
async listAssets(skillName) {
return (await this.getScoped()).listAssets(skillName);
}
};
/**
* Whether an error is a Node `ERR_INVALID_ARG*` error (e.g. a non-string path
* handed to `fs`/`path`). Only coded errors qualify: a bare `TypeError` can also
* come from `fetch` network failures in fetch-backed content sources, which must
* keep the warn-and-continue path.
*/
function isProgrammingError(error) {
const code = error?.code;
return typeof code === "string" && code.startsWith("ERR_INVALID_ARG");
}
/**
* Split a path into segments, tolerating both POSIX (`/`) and Windows (`\`)
* separators. Workspace-internal paths use forward slashes, but consumer-supplied
* absolute paths (e.g. via `new Workspace({ skills: [...] })`) may use backslashes
* on Windows.
*/
function splitPathSegments(path) {
return path.split(/[\\/]+/);
}
/**
* Whether a path points directly at a `SKILL.md` file, tolerating both separators.
*/
function isSkillFilePath(path) {
return path === "SKILL.md" || /[\\/]SKILL\.md$/.test(path);
}
function stripTrailingSlashes(s) {
let end = s.length;
while (end > 0 && s.charCodeAt(end - 1) === 47) end--;
return end === s.length ? s : s.slice(0, end);
}
function stripLeadingAndTrailingSlashes(s) {
let start = 0;
while (start < s.length && s.charCodeAt(start) === 47) start++;
let end = s.length;
while (end > start && s.charCodeAt(end - 1) === 47) end--;
return start === 0 && end === s.length ? s : s.slice(start, end);
}
Object.defineProperty(exports, "BM25Index", {
enumerable: true,
get: function() {
return BM25Index;
}
});
Object.defineProperty(exports, "LocalSkillSource", {
enumerable: true,
get: function() {
return LocalSkillSource;
}
});
Object.defineProperty(exports, "ResolvedSourceWorkspaceSkills", {
enumerable: true,
get: function() {
return ResolvedSourceWorkspaceSkills;
}
});
Object.defineProperty(exports, "SKILL_LIMITS", {
enumerable: true,
get: function() {
return SKILL_LIMITS;
}
});
Object.defineProperty(exports, "SKILL_SCOPE_DOCUMENT_PREFIX", {
enumerable: true,
get: function() {
return SKILL_SCOPE_DOCUMENT_PREFIX;
}
});
Object.defineProperty(exports, "SearchEngine", {
enumerable: true,
get: function() {
return SearchEngine;
}
});
Object.defineProperty(exports, "WorkspaceSkillsImpl", {
enumerable: true,
get: function() {
return WorkspaceSkillsImpl;
}
});
Object.defineProperty(exports, "createGlobMatcher", {
enumerable: true,
get: function() {
return createGlobMatcher;
}
});
Object.defineProperty(exports, "expandTilde", {
enumerable: true,
get: function() {
return expandTilde;
}
});
Object.defineProperty(exports, "extractGlobBase", {
enumerable: true,
get: function() {
return extractGlobBase;
}
});
Object.defineProperty(exports, "extractSkillFrontmatter", {
enumerable: true,
get: function() {
return extractSkillFrontmatter;
}
});
Object.defineProperty(exports, "fsExists", {
enumerable: true,
get: function() {
return fsExists;
}
});
Object.defineProperty(exports, "fsStat", {
enumerable: true,
get: function() {
return fsStat;
}
});
Object.defineProperty(exports, "getMimeType", {
enumerable: true,
get: function() {
return getMimeType;
}
});
Object.defineProperty(exports, "isEexistError", {
enumerable: true,
get: function() {
return isEexistError;
}
});
Object.defineProperty(exports, "isEnoentError", {
enumerable: true,
get: function() {
return isEnoentError;
}
});
Object.defineProperty(exports, "isEnotdirError", {
enumerable: true,
get: function() {
return isEnotdirError;
}
});
Object.defineProperty(exports, "isGlobPattern", {
enumerable: true,
get: function() {
return isGlobPattern;
}
});
Object.defineProperty(exports, "isTextFile", {
enumerable: true,
get: function() {
return isTextFile;
}
});
Object.defineProperty(exports, "matchGlob", {
enumerable: true,
get: function() {
return matchGlob;
}
});
Object.defineProperty(exports, "normalizeTextExtension", {
enumerable: true,
get: function() {
return normalizeTextExtension;
}
});
Object.defineProperty(exports, "resolvePathPattern", {
enumerable: true,
get: function() {
return resolvePathPattern;
}
});
Object.defineProperty(exports, "resolveToBasePath", {
enumerable: true,
get: function() {
return resolveToBasePath;
}
});
Object.defineProperty(exports, "splitIntoChunks", {
enumerable: true,
get: function() {
return splitIntoChunks;
}
});
Object.defineProperty(exports, "stringifyFrontmatter", {
enumerable: true,
get: function() {
return stringifyFrontmatter;
}
});
Object.defineProperty(exports, "tokenize", {
enumerable: true,
get: function() {
return tokenize;
}
});
Object.defineProperty(exports, "validateSkillContent", {
enumerable: true,
get: function() {
return validateSkillContent;
}
});
Object.defineProperty(exports, "validateSkillMetadata", {
enumerable: true,
get: function() {
return validateSkillMetadata;
}
});
//# sourceMappingURL=workspace-skills-CKBkzxPb.cjs.map