summaryrefslogtreecommitdiffhomepage
path: root/packages/core/src/skills/loader.ts
blob: 5d043dda95f7458090945ca730a6c5f5e6277078 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import chokidar from "chokidar";
import type { AgentSkillMapping, SkillDefinition, SkillScope } from "../types/index.js";
import { parseSkillFile } from "./parser.js";

// ─── Internal Helpers ────────────────────────────────────────────

/**
 * Recursively scan a directory for .md skill files.
 * The `directory` field on each skill is the relative path from `baseDir` to the file's parent.
 * Skips the `agents/` subdirectory (handled separately).
 */
function scanSkillsRecursive(baseDir: string, scope: SkillScope): SkillDefinition[] {
	if (!fs.existsSync(baseDir)) return [];

	const results: SkillDefinition[] = [];

	function walk(dir: string) {
		let entries: fs.Dirent[];
		try {
			entries = fs.readdirSync(dir, { withFileTypes: true });
		} catch {
			return;
		}

		for (const entry of entries) {
			const fullPath = path.join(dir, entry.name);

			if (entry.isDirectory()) {
				// Skip agents/ at the top level (handled by loadAgentMappings)
				const relFromBase = path.relative(baseDir, fullPath);
				if (relFromBase === "agents") continue;
				walk(fullPath);
			} else if (entry.isFile() && entry.name.endsWith(".md")) {
				const relDir = path.relative(baseDir, dir);
				// relDir is "" for root, "general" for general/, "general/webapps" for nested
				const directory = relDir === "." ? "" : relDir;
				try {
					const content = fs.readFileSync(fullPath, "utf-8");
					const skill = parseSkillFile(fullPath, content, scope, directory);
					results.push(skill);
				} catch {
					// Skip unreadable files
				}
			}
		}
	}

	walk(baseDir);
	return results;
}

function loadAgentMappings(agentsDir: string, scope: SkillScope): AgentSkillMapping[] {
	if (!fs.existsSync(agentsDir)) {
		return [];
	}

	const results: AgentSkillMapping[] = [];
	let entries: fs.Dirent[];
	try {
		entries = fs.readdirSync(agentsDir, { withFileTypes: true });
	} catch {
		return [];
	}

	for (const entry of entries) {
		if (!entry.isFile() || !entry.name.endsWith(".txt")) {
			continue;
		}

		const fileName = entry.name;
		let isOrchestrator = false;
		let agentType: string;

		if (fileName.endsWith(".o.txt")) {
			isOrchestrator = true;
			agentType = fileName.slice(0, -6); // remove ".o.txt"
		} else {
			agentType = fileName.slice(0, -4); // remove ".txt"
		}

		const filePath = path.join(agentsDir, fileName);
		try {
			const content = fs.readFileSync(filePath, "utf-8");
			const skills = content
				.split("\n")
				.map((line) => line.trim())
				.filter((line) => line.length > 0 && !line.startsWith("#"));

			results.push({ agentType, isOrchestrator, skills, scope });
		} catch {
			// Skip unreadable mapping files
		}
	}

	return results;
}

// ─── Public API ──────────────────────────────────────────────────

export function loadSkills(projectDir: string): {
	skills: SkillDefinition[];
	mappings: AgentSkillMapping[];
} {
	const globalBase = path.join(os.homedir(), ".skills");
	const projectBase = path.join(projectDir, ".skills");

	const skills: SkillDefinition[] = [];
	const mappings: AgentSkillMapping[] = [];

	// 1. Scan all global skills recursively (skipping agents/)
	skills.push(...scanSkillsRecursive(globalBase, "global"));

	// 2. Scan all project skills recursively (skipping agents/)
	skills.push(...scanSkillsRecursive(projectBase, "project"));

	// 3. Agent mappings — global then project
	mappings.push(...loadAgentMappings(path.join(globalBase, "agents"), "global"));
	mappings.push(...loadAgentMappings(path.join(projectBase, "agents"), "project"));

	return { skills, mappings };
}

export function resolveSkillsForAgent(
	agentType: string,
	isOrchestrator: boolean,
	skills: SkillDefinition[],
	mappings: AgentSkillMapping[],
): SkillDefinition[] {
	// Helper: project overrides global for same-named skills
	const dedupeByName = (list: SkillDefinition[]): SkillDefinition[] => {
		const seen = new Map<string, SkillDefinition>();
		for (const skill of list) {
			const existing = seen.get(skill.name);
			if (!existing || skill.scope === "project") {
				seen.set(skill.name, skill);
			}
		}
		return Array.from(seen.values());
	};

	// All default-directory skills (global first, then project — dedupe preserves project)
	const defaultSkills = skills.filter((s) => s.directory === "default");

	// Skills mapped to this agent type
	const relevantMappings = mappings.filter(
		(m) => m.agentType === agentType && m.isOrchestrator === isOrchestrator,
	);

	// Gather agent-specific skills in order: global mappings first, then project
	const globalMappings = relevantMappings.filter((m) => m.scope === "global");
	const projectMappings = relevantMappings.filter((m) => m.scope === "project");

	const agentSkillNames: string[] = [];
	for (const mapping of [...globalMappings, ...projectMappings]) {
		for (const skillFile of mapping.skills) {
			const skillName = path.basename(skillFile, path.extname(skillFile));
			agentSkillNames.push(skillName);
		}
	}

	const agentSpecificSkills = agentSkillNames
		.map((name) => getSkillByName(name, skills, "project"))
		.filter((s): s is SkillDefinition => s !== undefined);

	const combined = [...defaultSkills, ...agentSpecificSkills];
	return dedupeByName(combined);
}

export function getSkillByName(
	name: string,
	skills: SkillDefinition[],
	preferScope?: SkillScope,
): SkillDefinition | undefined {
	const matches = skills.filter((s) => s.name === name);
	if (matches.length === 0) {
		return undefined;
	}

	if (preferScope) {
		const preferred = matches.find((s) => s.scope === preferScope);
		if (preferred) {
			return preferred;
		}
	}

	// Default: project takes precedence
	const projectMatch = matches.find((s) => s.scope === "project");
	return projectMatch ?? matches[0];
}

export function createSkillsWatcher(
	projectDir: string,
	onChange: (result: { skills: SkillDefinition[]; mappings: AgentSkillMapping[] }) => void,
): { close(): void } {
	const globalBase = path.join(os.homedir(), ".skills");
	const projectBase = path.join(projectDir, ".skills");

	let debounceTimer: ReturnType<typeof setTimeout> | null = null;

	const reload = () => {
		if (debounceTimer !== null) {
			clearTimeout(debounceTimer);
		}
		debounceTimer = setTimeout(() => {
			debounceTimer = null;
			const result = loadSkills(projectDir);
			onChange(result);
		}, 300);
	};

	const watchPaths = [globalBase, projectBase];

	const watcher = chokidar.watch(watchPaths, {
		ignoreInitial: true,
		persistent: true,
	});

	watcher.on("add", (filePath: string) => {
		if (filePath.endsWith(".md") || filePath.endsWith(".txt")) {
			reload();
		}
	});

	watcher.on("change", (filePath: string) => {
		if (filePath.endsWith(".md") || filePath.endsWith(".txt")) {
			reload();
		}
	});

	watcher.on("unlink", (filePath: string) => {
		if (filePath.endsWith(".md") || filePath.endsWith(".txt")) {
			reload();
		}
	});

	return {
		close() {
			if (debounceTimer !== null) {
				clearTimeout(debounceTimer);
				debounceTimer = null;
			}
			watcher.close();
		},
	};
}