Open History to see the last commit
1// Scan skills without opening an ACP session and starting its MCP servers.
2
3import type { ServerProviderSkill } from "@t3tools/contracts";
4import * as ByteSize from "effect/ByteSize";
5import * as Effect from "effect/Effect";
6import * as FileSystem from "effect/FileSystem";
7import * as Path from "effect/Path";
8import * as PlatformError from "effect/PlatformError";
9import * as Schema from "effect/Schema";
10import { parse as parseYamlDocument } from "yaml";
11import * as HostProcess from "@t3tools/shared/HostProcess";
12
13const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
14const SKILL_MENTION_PATTERN =
15 /(^|\s)\p{Sc}(?![0-9][0-9_]*(?:[kKmMbBtT]|[eE][0-9]+)?(?:\s|$))(?=[a-zA-Z0-9:_-]*[a-zA-Z])([a-zA-Z0-9][a-zA-Z0-9:_-]*)(?=\s|$)/gu;
16const HAS_SKILL_MENTION_PATTERN = new RegExp(SKILL_MENTION_PATTERN.source, "u");
17const SLASH_SKILL_PATTERN = /(?:^|\s)\/([a-zA-Z0-9][a-zA-Z0-9:_-]*)(?=\s|$)/gu;
18const MAX_SKILL_DEPTH = 10;
19const MAX_SKILL_BYTES = ByteSize.bytes(1_000_000);
20const MAX_SKILL_SCAN_ENTRIES = 10_000;
21const MAX_SKILL_SCAN_STATS = 100_000;
22const MAX_SKILL_SCAN_BYTES = ByteSize.bytes(8_000_000);
23
24interface CursorSkillFrontmatter {
25 readonly description?: string;
26 readonly displayName?: string;
27 readonly userInvocationOnly?: boolean;
28 readonly userInvocable?: boolean;
29 readonly cliVisible: boolean;
30}
31
32interface CursorSkillScanBudget {
33 remainingEntries: number;
34 remainingStats: number;
35 remainingBytes: bigint;
36 exhausted: boolean;
37 incomplete: boolean;
38}
39
40class CursorSkillsProbeError extends Schema.TaggedError<CursorSkillsProbeError>()(
41 "CursorSkillsProbeError",
42 {
43 reason: Schema.Literals(["scan-budget-exhausted", "filesystem-error"]),
44 cwd: Schema.optional(Schema.String),
45 },
46) {
47 override get message(): string {
48 const location = this.cwd === undefined ? "" : ` for '${this.cwd}'`;
49 return `Cursor skill discovery${location} was incomplete (${this.reason}).`;
50 }
51}
52
53const isSymlinkLoop = ({ reason }: PlatformError.PlatformError) =>
54 reason._tag === "BadResource" &&
55 typeof reason.cause === "object" &&
56 reason.cause !== null &&
57 "code" in reason.cause &&
58 reason.cause.code === "ELOOP";
59
60const orUndefined = <A, R>(
61 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
62 budget?: CursorSkillScanBudget,
63): Effect.Effect<A | undefined, never, R> =>
64 effect.pipe(
65 Effect.map((value): A | undefined => value),
66 Effect.catchTags({
67 PlatformError: (error) => {
68 // A symlink loop (ELOOP, mapped to BadResource) resolves nowhere, like a dangling link.
69 const unresolved = error.reason._tag === "NotFound" || isSymlinkLoop(error);
70 if (!unresolved && budget) budget.incomplete = true;
71 return Effect.void.pipe(Effect.as(undefined));
72 },
73 }),
74 );
75
76function parseFrontmatterBoolean(value: unknown): boolean | undefined {
77 if (typeof value === "boolean") return value;
78 if (typeof value === "number") return value === 1 ? true : value === 0 ? false : undefined;
79 if (typeof value !== "string") return undefined;
80 switch (value.trim().toLowerCase()) {
81 case "true":
82 case "yes":
83 case "on":
84 return true;
85 case "false":
86 case "no":
87 case "off":
88 return false;
89 default:
90 return undefined;
91 }
92}
93
94function parseSkillFrontmatter(contents: string): CursorSkillFrontmatter | undefined {
95 const match = FRONTMATTER_PATTERN.exec(contents);
96 if (!match) return { cliVisible: true };
97
98 let parsed: unknown;
99 try {
100 parsed = parseYamlDocument(match[1] ?? "");
101 } catch {
102 return undefined;
103 }
104 if (typeof parsed !== "object" || parsed === null) return undefined;
105
106 const record = parsed as Record<string, unknown>;
107 const metadata =
108 typeof record.metadata === "object" && record.metadata !== null
109 ? (record.metadata as Record<string, unknown>)
110 : undefined;
111 const rawSurfaces = metadata?.surfaces;
112 const surfaces = Array.isArray(rawSurfaces)
113 ? rawSurfaces.filter((surface): surface is string => typeof surface === "string")
114 : typeof rawSurfaces === "string"
115 ? rawSurfaces.split(",")
116 : [];
117 const description = typeof record.description === "string" ? record.description.trim() : "";
118 const displayName = typeof record.name === "string" ? record.name.trim() : "";
119 return {
120 cliVisible:
121 surfaces.length === 0 || surfaces.some((surface) => surface.trim().toLowerCase() === "cli"),
122 ...(description ? { description } : {}),
123 ...(displayName ? { displayName } : {}),
124 ...(parseFrontmatterBoolean(record["disable-model-invocation"]) === true
125 ? { userInvocationOnly: true }
126 : {}),
127 ...(parseFrontmatterBoolean(record["user-invocable"]) === false
128 ? { userInvocable: false }
129 : {}),
130 };
131}
132
133const discoverSkillsInRoot = Effect.fn("discoverCursorSkillsInRoot")(function* (input: {
134 readonly directory: string;
135 readonly scope: "user" | "project" | "system";
136 readonly budget: CursorSkillScanBudget;
137 readonly scannedRoots: Set<string>;
138}): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
139 const fileSystem = yield* FileSystem.FileSystem;
140 const path = yield* Path.Path;
141 const skills: ServerProviderSkill[] = [];
142 if (input.budget.exhausted) return skills;
143 const rootDirectory = yield* orUndefined(fileSystem.realPath(input.directory), input.budget);
144 if (!rootDirectory) return skills;
145 // Symlinked roots may share a tree; do not charge its scan budget twice.
146 if (input.scannedRoots.has(rootDirectory)) return skills;
147 input.scannedRoots.add(rootDirectory);
148 const visitedDirectories = new Set<string>();
149
150 const visit = Effect.fn("visitCursorSkillDirectory")(function* (
151 directory: string,
152 depth: number,
153 ): Effect.fn.Return<void, never> {
154 if (input.budget.exhausted) return;
155 const resolvedDirectory = yield* orUndefined(fileSystem.realPath(directory), input.budget);
156 if (!resolvedDirectory) {
157 return;
158 }
159 if (visitedDirectories.has(resolvedDirectory)) {
160 return;
161 }
162 visitedDirectories.add(resolvedDirectory);
163 // Outside-root symlinks expose only their own SKILL.md; never traverse the target tree.
164 const insideRoot =
165 resolvedDirectory === rootDirectory ||
166 resolvedDirectory.startsWith(`${rootDirectory}${path.sep}`);
167
168 if (input.budget.remainingStats === 0) {
169 input.budget.exhausted = true;
170 return;
171 }
172 input.budget.remainingStats -= 1;
173 const skillPath = path.join(directory, "SKILL.md");
174 const skillInfo = yield* orUndefined(fileSystem.stat(skillPath), input.budget);
175 if (skillInfo?.type === "File") {
176 let frontmatter: CursorSkillFrontmatter | undefined = { cliVisible: true };
177 if (skillInfo.size <= MAX_SKILL_BYTES && skillInfo.size <= input.budget.remainingBytes) {
178 const contents = yield* orUndefined(fileSystem.readFileString(skillPath));
179 if (contents !== undefined) {
180 input.budget.remainingBytes -= skillInfo.size;
181 frontmatter = parseSkillFrontmatter(contents);
182 }
183 }
184 const name = path.basename(directory).trim();
185 if (frontmatter?.cliVisible && name) {
186 skills.push({
187 name,
188 path: skillPath,
189 scope: input.scope,
190 enabled: true,
191 ...(frontmatter.displayName && frontmatter.displayName !== name
192 ? { displayName: frontmatter.displayName }
193 : {}),
194 ...(frontmatter.description ? { description: frontmatter.description } : {}),
195 ...(frontmatter.userInvocationOnly ? { userInvocationOnly: true } : {}),
196 ...(frontmatter.userInvocable === false ? { userInvocable: false } : {}),
197 });
198 }
199 }
200
201 if (!insideRoot) {
202 return;
203 }
204 const entries = yield* orUndefined(fileSystem.readDirectory(directory), input.budget);
205 if (!entries) {
206 return;
207 }
208 for (const entry of [...entries].sort()) {
209 // Installed dependencies can exhaust the shared budget and hide unrelated skills.
210 if (entry === "node_modules") continue;
211 // Files spend no directory budget, so a separate cap keeps a huge file tree bounded.
212 if (input.budget.remainingStats === 0) {
213 input.budget.exhausted = true;
214 return;
215 }
216 input.budget.remainingStats -= 1;
217 const child = path.join(directory, entry);
218 const info = yield* orUndefined(fileSystem.stat(child), input.budget);
219 // Only directories can hold skills, so only they spend the budget: a skill
220 // shipping many ordinary files must not hide its siblings.
221 if (info?.type !== "Directory") continue;
222 if (depth >= MAX_SKILL_DEPTH) continue;
223 if (input.budget.remainingEntries === 0) {
224 input.budget.exhausted = true;
225 return;
226 }
227 input.budget.remainingEntries -= 1;
228 yield* visit(child, depth + 1);
229 }
230 });
231
232 yield* visit(rootDirectory, 0);
233 return skills;
234});
235
236const inspectCursorSkills = Effect.fn("inspectCursorSkills")(function* (
237 cwd?: string,
238 environment: NodeJS.ProcessEnv = process.env,
239) {
240 const path = yield* Path.Path;
241 const userHome =
242 environment.HOME?.trim() ||
243 environment.USERPROFILE?.trim() ||
244 (yield* HostProcess.HomeDirectory);
245 const rootsBelow = (base: string, scope: "user" | "project") => [
246 { directory: path.join(base, ".cursor", "skills"), scope },
247 { directory: path.join(base, ".agents", "skills"), scope },
248 { directory: path.join(base, ".codex", "skills"), scope },
249 { directory: path.join(base, ".claude", "skills"), scope },
250 ];
251 const roots = [
252 ...(cwd ? rootsBelow(cwd, "project") : []),
253 ...rootsBelow(userHome, "user"),
254 // Cursor syncs its built-in skills here; same-named user and project skills win.
255 { directory: path.join(userHome, ".cursor", "skills-cursor"), scope: "system" as const },
256 ];
257
258 const skillsByName = new Map<string, ServerProviderSkill>();
259 const budget: CursorSkillScanBudget = {
260 remainingEntries: MAX_SKILL_SCAN_ENTRIES,
261 remainingStats: MAX_SKILL_SCAN_STATS,
262 remainingBytes: MAX_SKILL_SCAN_BYTES,
263 exhausted: false,
264 incomplete: false,
265 };
266 const scannedRoots = new Set<string>();
267 for (const root of roots) {
268 if (budget.exhausted) break;
269 const skills = yield* discoverSkillsInRoot({ ...root, budget, scannedRoots });
270 for (const skill of skills) {
271 if (!skillsByName.has(skill.name)) skillsByName.set(skill.name, skill);
272 }
273 }
274 return {
275 skills: [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name)),
276 failureReason: budget.exhausted
277 ? ("scan-budget-exhausted" as const)
278 : budget.incomplete
279 ? ("filesystem-error" as const)
280 : undefined,
281 };
282});
283
284export const discoverCursorSkills = Effect.fn("discoverCursorSkills")(function* (
285 cwd?: string,
286 environment: NodeJS.ProcessEnv = process.env,
287) {
288 return (yield* inspectCursorSkills(cwd, environment)).skills;
289});
290
291export const probeCursorSkills = Effect.fn("probeCursorSkills")(function* (
292 cwd?: string,
293 environment: NodeJS.ProcessEnv = process.env,
294) {
295 const inspection = yield* inspectCursorSkills(cwd, environment);
296 if (inspection.failureReason) {
297 return yield* new CursorSkillsProbeError({
298 reason: inspection.failureReason,
299 ...(cwd ? { cwd } : {}),
300 });
301 }
302 return inspection.skills;
303});
304
305/** Cursor invokes Agent Skills with `/name`; T3 composers insert `$name`. */
306export function hasCursorSkillMention(prompt: string): boolean {
307 return HAS_SKILL_MENTION_PATTERN.test(prompt);
308}
309
310export function rewriteCursorSkillMentions(
311 prompt: string,
312 skillNames: ReadonlySet<string>,
313): string {
314 return prompt.replace(SKILL_MENTION_PATTERN, (match, prefix: string, name: string) =>
315 skillNames.has(name) ? `${prefix}/${name}` : match,
316 );
317}
318
319/** Names invoked as `/name`, the form Cursor uses and `rewriteCursorSkillMentions` produces. */
320export function cursorSlashSkillNames(prompt: string): ReadonlySet<string> {
321 return new Set(Array.from(prompt.matchAll(SLASH_SKILL_PATTERN), (match) => match[1] ?? ""));
322}
323
324/** Cursor hides `disable-model-invocation` skills from the model, so the prompt carries them. */
325export function appendCursorInvokedSkills(
326 prompt: string,
327 skills: ReadonlyArray<{ readonly name: string; readonly contents: string }>,
328): string {
329 if (skills.length === 0) return prompt;
330 const blocks = skills.map(
331 (skill) =>
332 `<skill name="${skill.name}">\n${skill.contents.replace(FRONTMATTER_PATTERN, "").trim()}\n</skill>`,
333 );
334 return `${prompt}\n\nThe user invoked these skills. Follow their instructions:\n\n${blocks.join("\n\n")}`;
335}