import { readdir, readFile, realpath, stat } from "node:fs/promises"; import { basename, isAbsolute, relative, resolve } from "node:path"; import { parseDocument } from "yaml"; import { fingerprintSuiteBytes, REQUIRED_SUITE_FILES, type RequiredSuiteFile, } from "./checker.ts"; const MAX_SOURCE_BYTES = 256 * 1024; const MAX_CHECKER_BYTES = 256 * 1024; const MAX_ITEMS_BYTES = 1024 * 1024; const MAX_PROMPT_BYTES = 16 * 1024; const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; type LoadedCommand = { name: string; source: string; sourceInfo?: { path?: string; scope?: string; source?: string; origin?: string; baseDir?: string; }; }; export type LoadedSkill = { name: string; path: string; scope: string; sourceInfo: { path: string; scope: string; source: string; origin: string; baseDir?: string; }; }; export type SourceSkill = { frontmatter: string; body: string; name: string; description: string; }; export type ValidatedSuite = { suitePath: string; checkerPath: string; fingerprint?: string; splitCounts: { test: number; train: number; val: number }; }; export type ValidatedItem = Record & { id: string; prompt: string; }; type SuiteSplit = "test" | "train" | "val"; const suiteItems = new WeakMap< ValidatedSuite, Record >(); function decodeUtf8(bytes: Buffer, label: string): string { try { return new TextDecoder("utf-8", { fatal: true }).decode(bytes); } catch { throw new Error(`${label} must be valid UTF-8`); } } function isContained(child: string, parent: string): boolean { const path = relative(parent, child); return path === "" || (!path.startsWith("..") && !isAbsolute(path)); } async function canonicalContained( path: string, parent: string, label: string, ): Promise { const canonical = await realpath(path); if (!isContained(canonical, parent)) throw new Error(`${label} must be contained by trusted project`); return canonical; } export async function resolveLoadedSkill( inputPath: string, commands: readonly LoadedCommand[], projectTrusted: boolean, cwd = process.cwd(), ): Promise { const path = await realpath(resolve(cwd, inputPath)); const matches: LoadedSkill[] = []; for (const command of commands) { if ( command.source !== "skill" || typeof command.sourceInfo?.path !== "string" ) continue; let commandPath: string; try { commandPath = await realpath(command.sourceInfo.path); } catch { continue; } if (commandPath === path) { matches.push({ name: command.name, path, scope: command.sourceInfo.scope ?? "temporary", sourceInfo: { path, scope: command.sourceInfo.scope ?? "temporary", source: command.sourceInfo.source ?? command.source, origin: command.sourceInfo.origin ?? "top-level", ...(command.sourceInfo.baseDir === undefined ? {} : { baseDir: command.sourceInfo.baseDir }), }, }); } } if (matches.length !== 1) throw new Error("source path must match exactly one loaded skill command"); const match = matches[0]; if (!match) throw new Error("source path must match exactly one loaded skill command"); if (match.scope === "project" && !projectTrusted) throw new Error("project skill requires a trusted project"); return match; } export function parseSourceSkill(bytes: Buffer): SourceSkill { if (bytes.byteLength > MAX_SOURCE_BYTES) throw new Error("source skill exceeds 256 KiB"); const text = decodeUtf8(bytes, "source skill"); const firstLineEnd = text.indexOf("\n"); if ( firstLineEnd < 0 || text.slice(0, firstLineEnd).replace(/\r$/, "") !== "---" ) { throw new Error("source skill requires YAML frontmatter"); } let cursor = firstLineEnd + 1; let closeEnd = -1; while (cursor <= text.length) { const next = text.indexOf("\n", cursor); const end = next < 0 ? text.length : next; const line = text.slice(cursor, end).replace(/\r$/, ""); if (line === "---" || line === "...") { closeEnd = next < 0 ? end : next + 1; break; } if (next < 0) break; cursor = next + 1; } if (closeEnd < 0) throw new Error("source skill requires closed YAML frontmatter"); const frontmatter = text.slice(0, closeEnd); const yaml = parseDocument(text.slice(firstLineEnd + 1, cursor)); if ( yaml.errors.length > 0 || !yaml.contents || typeof yaml.toJS() !== "object" ) { throw new Error("source skill frontmatter must be valid YAML"); } const data = yaml.toJS() as { name?: unknown; description?: unknown }; if (typeof data.name !== "string" || !SKILL_NAME.test(data.name)) throw new Error("source skill has invalid name"); if ( typeof data.description !== "string" || data.description.trim().length === 0 ) { throw new Error("source skill requires a nonempty description"); } const body = text.slice(closeEnd); if (body.trim().length === 0) throw new Error("source skill requires a nonempty Markdown body"); return { frontmatter, body, name: data.name, description: data.description }; } function validateItem( value: unknown, split: string, ids: Set, ): ValidatedItem { if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(`${split} item must be an object`); const item = value as ValidatedItem; if (typeof item.id !== "string" || item.id.trim().length === 0) throw new Error(`${split} item requires a nonempty id`); if (typeof item.prompt !== "string" || item.prompt.length === 0) throw new Error(`${split} item requires a nonempty prompt`); if (Buffer.byteLength(item.prompt, "utf8") > MAX_PROMPT_BYTES) throw new Error(`${split} item prompt exceeds 16 KiB`); if (ids.has(item.id)) throw new Error(`duplicate item id: ${item.id}`); ids.add(item.id); return item; } function compareCodePointIds(left: string, right: string): number { const leftPoints = Array.from(left); const rightPoints = Array.from(right); for ( let index = 0; index < Math.min(leftPoints.length, rightPoints.length); index += 1 ) { const difference = (leftPoints[index]?.codePointAt(0) ?? 0) - (rightPoints[index]?.codePointAt(0) ?? 0); if (difference !== 0) return difference; } return leftPoints.length - rightPoints.length; } function validateItems( bytes: Buffer, split: string, ids: Set, ): ValidatedItem[] { if (bytes.byteLength > MAX_ITEMS_BYTES) throw new Error(`${split}/items.json exceeds 1 MiB`); const text = decodeUtf8(bytes, `${split}/items.json`); let value: unknown; try { value = JSON.parse(text); } catch { throw new Error(`${split}/items.json must be JSON`); } if (!Array.isArray(value) || value.length < 1 || value.length > 64) throw new Error(`${split}/items.json must contain 1 to 64 items`); const items = value.map((item) => validateItem(item, split, ids)); return items.sort((left, right) => compareCodePointIds(left.id, right.id)); } async function assertExactSuiteLayout(suitePath: string): Promise { const expectedRoot = new Map([ ["check.mjs", "file"], ["test", "directory"], ["train", "directory"], ["val", "directory"], ]); const rootEntries = await readdir(suitePath, { withFileTypes: true }); if (rootEntries.length !== expectedRoot.size) throw new Error("suite must contain exactly the required four-file layout"); for (const entry of rootEntries) { const expected = expectedRoot.get(entry.name); if ( (expected === "file" && !entry.isFile()) || (expected === "directory" && !entry.isDirectory()) || expected === undefined ) { throw new Error( "suite must contain exactly the required four-file layout", ); } } for (const split of ["test", "train", "val"] as const) { const entries = await readdir(resolve(suitePath, split), { withFileTypes: true, }); if ( entries.length !== 1 || entries[0]?.name !== "items.json" || !entries[0].isFile() ) { throw new Error( "suite must contain exactly the required four-file layout", ); } } } export function getValidatedSuiteItems( suite: ValidatedSuite, split: SuiteSplit, ): readonly ValidatedItem[] { const items = suiteItems.get(suite)?.[split]; if (!items) throw new Error("validated suite items are unavailable"); return items; } export async function validateTrustedSuite( inputSuitePath: string, cwd: string, projectTrusted: boolean, ): Promise { if (!projectTrusted) throw new Error("suite requires a trusted project"); const canonicalCwd = await realpath(resolve(cwd)); const suitePath = await canonicalContained( resolve(canonicalCwd, inputSuitePath), canonicalCwd, "suite", ); const suiteStat = await stat(suitePath); if (!suiteStat.isDirectory()) throw new Error("suite must be a directory"); await assertExactSuiteLayout(suitePath); const files = new Map(); for (const filename of REQUIRED_SUITE_FILES) { const canonical = await canonicalContained( resolve(suitePath, filename), suitePath, basename(filename), ); const fileStat = await stat(canonical); if (!fileStat.isFile()) throw new Error(`${filename} must be a file`); if (filename === "check.mjs" && fileStat.size > MAX_CHECKER_BYTES) throw new Error("check.mjs exceeds 256 KiB"); files.set(filename, canonical); } const checkerPath = files.get("check.mjs"); const trainPath = files.get("train/items.json"); const valPath = files.get("val/items.json"); const testPath = files.get("test/items.json"); if (!checkerPath || !trainPath || !valPath || !testPath) throw new Error("suite is missing required files"); const snapshot = new Map(); for (const filename of REQUIRED_SUITE_FILES) { const path = files.get(filename); if (!path) throw new Error(`suite is missing ${filename}`); const bytes = await readFile(path); if (filename === "check.mjs" && bytes.byteLength > MAX_CHECKER_BYTES) throw new Error("check.mjs exceeds 256 KiB"); snapshot.set(filename, bytes); } const ids = new Set(); const train = validateItems( snapshot.get("train/items.json") as Buffer, "train", ids, ); const val = validateItems( snapshot.get("val/items.json") as Buffer, "val", ids, ); const test = validateItems( snapshot.get("test/items.json") as Buffer, "test", ids, ); const suite = { suitePath, checkerPath, fingerprint: fingerprintSuiteBytes(snapshot), splitCounts: { test: test.length, train: train.length, val: val.length }, }; suiteItems.set(suite, { test, train, val }); return suite; }