319 lines
8.3 KiB
TypeScript
319 lines
8.3 KiB
TypeScript
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
import { dirname, resolve } from "node:path";
|
|
import { getLogger } from "@obs/logger";
|
|
|
|
export type TrustTier = "T1" | "T2" | "T3" | "T4";
|
|
export type SkillRiskTier = "low" | "medium" | "high";
|
|
|
|
export interface SkillOutputContract {
|
|
format?: string | undefined;
|
|
maxChars?: string | undefined;
|
|
requiredFields?: string | undefined;
|
|
}
|
|
|
|
export interface SkillCapabilityCard {
|
|
canHandle: string[];
|
|
cannotHandle: string[];
|
|
domain: string;
|
|
handoffTargets: string[];
|
|
outputContract: SkillOutputContract;
|
|
riskTier: SkillRiskTier;
|
|
}
|
|
|
|
export interface SkillManifest {
|
|
bodyPath: string;
|
|
canHandle: string[];
|
|
cannotHandle: string[];
|
|
description: string;
|
|
domain: string;
|
|
handoffTargets: string[];
|
|
intents: string[];
|
|
name: string;
|
|
outputContract: SkillOutputContract;
|
|
priority: number;
|
|
resources: Record<string, string>;
|
|
riskTier: SkillRiskTier;
|
|
tools: string[];
|
|
triggers: string[];
|
|
trustTier: TrustTier;
|
|
version: number;
|
|
}
|
|
|
|
interface ParsedSkillFile {
|
|
body: string;
|
|
manifest: SkillManifest;
|
|
}
|
|
|
|
const registryCache = new Map<string, SkillRegistry>();
|
|
|
|
function parseScalar(value: string): string | number {
|
|
const trimmed = value.trim();
|
|
const unquoted = trimmed.replace(/^["']|["']$/gu, "");
|
|
const numeric = Number(unquoted);
|
|
return Number.isFinite(numeric) && /^\d+$/u.test(unquoted) ? numeric : unquoted;
|
|
}
|
|
|
|
function parseInlineArray(value: string): string[] {
|
|
const trimmed = value.trim();
|
|
if (!trimmed.startsWith("[") || !trimmed.endsWith("]")) {
|
|
return [];
|
|
}
|
|
|
|
return trimmed
|
|
.slice(1, -1)
|
|
.split(",")
|
|
.map((item) => item.trim().replace(/^["']|["']$/gu, ""))
|
|
.filter(Boolean);
|
|
}
|
|
|
|
function parseFrontmatter(raw: string): {
|
|
body: string;
|
|
fields: Record<string, unknown>;
|
|
} | null {
|
|
if (!raw.startsWith("---\n")) {
|
|
return null;
|
|
}
|
|
|
|
const end = raw.indexOf("\n---", 4);
|
|
if (end === -1) {
|
|
return null;
|
|
}
|
|
|
|
const frontmatter = raw.slice(4, end).trimEnd();
|
|
const body = raw.slice(end + 4).trim();
|
|
const fields: Record<string, unknown> = {};
|
|
let currentMapKey: string | null = null;
|
|
|
|
for (const line of frontmatter.split(/\r?\n/u)) {
|
|
if (!line.trim()) {
|
|
continue;
|
|
}
|
|
|
|
if (/^\s{2,}[A-Za-z0-9_-]+:/u.test(line) && currentMapKey) {
|
|
const [key, ...rest] = line.trim().split(":");
|
|
if (key) {
|
|
const map = fields[currentMapKey] as Record<string, string>;
|
|
map[key] = rest.join(":").trim();
|
|
}
|
|
continue;
|
|
}
|
|
|
|
currentMapKey = null;
|
|
const [key, ...rest] = line.split(":");
|
|
if (!key) {
|
|
continue;
|
|
}
|
|
|
|
const value = rest.join(":").trim();
|
|
if (!value) {
|
|
fields[key] = {};
|
|
currentMapKey = key;
|
|
} else if (value.startsWith("[")) {
|
|
fields[key] = parseInlineArray(value);
|
|
} else {
|
|
fields[key] = parseScalar(value);
|
|
}
|
|
}
|
|
|
|
return { body, fields };
|
|
}
|
|
|
|
function readStringArray(fields: Record<string, unknown>, key: string): string[] {
|
|
const value = fields[key];
|
|
return Array.isArray(value)
|
|
? value.flatMap((item) => (typeof item === "string" ? [item] : []))
|
|
: [];
|
|
}
|
|
|
|
function readResources(
|
|
fields: Record<string, unknown>,
|
|
skillDir: string,
|
|
): Record<string, string> {
|
|
const raw = fields["resources"];
|
|
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
return {};
|
|
}
|
|
|
|
return Object.fromEntries(
|
|
Object.entries(raw as Record<string, unknown>).flatMap(([key, value]) =>
|
|
typeof value === "string" && value.trim()
|
|
? [[key, resolve(skillDir, value.trim())]]
|
|
: [],
|
|
),
|
|
);
|
|
}
|
|
|
|
function readStringMap(
|
|
fields: Record<string, unknown>,
|
|
key: string,
|
|
): Record<string, string> {
|
|
const raw = fields[key];
|
|
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
|
|
return {};
|
|
}
|
|
|
|
return Object.fromEntries(
|
|
Object.entries(raw as Record<string, unknown>).flatMap(([mapKey, value]) =>
|
|
typeof value === "string" && value.trim()
|
|
? [[mapKey, value.trim().replace(/^["']|["']$/gu, "")]]
|
|
: [],
|
|
),
|
|
);
|
|
}
|
|
|
|
function isTrustTier(value: unknown): value is TrustTier {
|
|
return value === "T1" || value === "T2" || value === "T3" || value === "T4";
|
|
}
|
|
|
|
function isRiskTier(value: unknown): value is SkillRiskTier {
|
|
return value === "low" || value === "medium" || value === "high";
|
|
}
|
|
|
|
function isPriority(value: unknown): value is number {
|
|
return (
|
|
typeof value === "number" &&
|
|
Number.isInteger(value) &&
|
|
value >= 0 &&
|
|
value <= 100
|
|
);
|
|
}
|
|
|
|
function parseSkillFile(path: string): ParsedSkillFile | null {
|
|
const raw = readFileSync(path, "utf8");
|
|
const parsed = parseFrontmatter(raw);
|
|
if (!parsed) {
|
|
return null;
|
|
}
|
|
|
|
const skillDir = dirname(path);
|
|
const name = parsed.fields["name"];
|
|
const description = parsed.fields["description"];
|
|
const priority = parsed.fields["priority"] ?? 50;
|
|
const version = parsed.fields["version"];
|
|
const trustTier = parsed.fields["trustTier"];
|
|
const domain = parsed.fields["domain"];
|
|
const riskTier = parsed.fields["riskTier"] ?? "low";
|
|
|
|
if (
|
|
typeof name !== "string" ||
|
|
!name.trim() ||
|
|
typeof description !== "string" ||
|
|
!description.trim() ||
|
|
!isPriority(priority) ||
|
|
typeof version !== "number" ||
|
|
!isTrustTier(trustTier) ||
|
|
!isRiskTier(riskTier)
|
|
) {
|
|
return null;
|
|
}
|
|
const outputContract = readStringMap(parsed.fields, "outputContract");
|
|
|
|
return {
|
|
body: parsed.body,
|
|
manifest: {
|
|
bodyPath: path,
|
|
canHandle: readStringArray(parsed.fields, "canHandle"),
|
|
cannotHandle: readStringArray(parsed.fields, "cannotHandle"),
|
|
description,
|
|
domain: typeof domain === "string" && domain.trim() ? domain : "general",
|
|
handoffTargets: readStringArray(parsed.fields, "handoffTargets"),
|
|
intents: readStringArray(parsed.fields, "intents"),
|
|
name,
|
|
outputContract,
|
|
priority,
|
|
resources: readResources(parsed.fields, skillDir),
|
|
riskTier,
|
|
tools: readStringArray(parsed.fields, "tools"),
|
|
triggers: readStringArray(parsed.fields, "triggers"),
|
|
trustTier,
|
|
version,
|
|
},
|
|
};
|
|
}
|
|
|
|
function findSkillFiles(rootDir: string): string[] {
|
|
if (!existsSync(rootDir)) {
|
|
return [];
|
|
}
|
|
|
|
return readdirSync(rootDir, { withFileTypes: true }).flatMap((entry) => {
|
|
const path = resolve(rootDir, entry.name);
|
|
if (entry.isDirectory()) {
|
|
return findSkillFiles(path);
|
|
}
|
|
return entry.isFile() && entry.name === "SKILL.md" ? [path] : [];
|
|
});
|
|
}
|
|
|
|
export class SkillRegistry {
|
|
private constructor(
|
|
private readonly manifests: SkillManifest[],
|
|
private readonly bodies: Map<string, string>,
|
|
) {}
|
|
|
|
static load(rootDir: string): SkillRegistry {
|
|
const normalizedRoot = resolve(rootDir);
|
|
const cached = registryCache.get(normalizedRoot);
|
|
if (cached) {
|
|
return cached;
|
|
}
|
|
|
|
const parsed = findSkillFiles(normalizedRoot).flatMap((path) => {
|
|
const skillFile = parseSkillFile(path);
|
|
return skillFile ? [skillFile] : [];
|
|
});
|
|
const seen = new Set<string>();
|
|
const manifests: SkillManifest[] = [];
|
|
const bodies = new Map<string, string>();
|
|
|
|
for (const item of parsed) {
|
|
if (seen.has(item.manifest.name)) {
|
|
getLogger().warn(
|
|
{
|
|
path: item.manifest.bodyPath,
|
|
skill: item.manifest.name,
|
|
},
|
|
"[SkillRegistry] Duplicate skill manifest ignored",
|
|
);
|
|
continue;
|
|
}
|
|
seen.add(item.manifest.name);
|
|
manifests.push(item.manifest);
|
|
bodies.set(item.manifest.name, item.body);
|
|
}
|
|
|
|
const registry = new SkillRegistry(manifests, bodies);
|
|
registryCache.set(normalizedRoot, registry);
|
|
return registry;
|
|
}
|
|
|
|
list(): SkillManifest[] {
|
|
return [...this.manifests];
|
|
}
|
|
|
|
get(name: string): SkillManifest | null {
|
|
return this.manifests.find((manifest) => manifest.name === name) ?? null;
|
|
}
|
|
|
|
loadBodySync(name: string): string {
|
|
return this.bodies.get(name) ?? "";
|
|
}
|
|
|
|
loadResourceSync(name: string, key: string): string {
|
|
const manifest = this.get(name);
|
|
const path = manifest?.resources[key];
|
|
if (!path || !existsSync(path)) {
|
|
return "";
|
|
}
|
|
return readFileSync(path, "utf8").trim();
|
|
}
|
|
|
|
async loadBody(name: string): Promise<string> {
|
|
return await Promise.resolve(this.loadBodySync(name));
|
|
}
|
|
|
|
async loadResource(name: string, key: string): Promise<string> {
|
|
return await Promise.resolve(this.loadResourceSync(name, key));
|
|
}
|
|
}
|