Open History to see the last commit
1/**
2 * CursorSkills — workspace-aware discovery and native invocation for Cursor.
3 *
4 * Cursor discovers Agent Skills recursively from user and project roots but
5 * its ACP command catalog only appears after opening a real session. Scanning
6 * the same roots avoids starting an agent and its MCP servers just to populate
7 * a composer menu.
8 *
9 * @module provider/Drivers/CursorSkills
10 */
11import * as NodeOS from "node:os";
12
13import type { ServerProviderSkill } from "@t3tools/contracts";
14import * as Effect from "effect/Effect";
15import * as FileSystem from "effect/FileSystem";
16import * as Path from "effect/Path";
17import * as PlatformError from "effect/PlatformError";
18import * as Schema from "effect/Schema";
19import { parse as parseYamlDocument } from "yaml";
20
21const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
22const SKILL_MENTION_PATTERN = /(^|\s)\$([a-zA-Z][a-zA-Z0-9:_-]*)(?=\s|$)/g;
23const HAS_SKILL_MENTION_PATTERN = /(^|\s)\$[a-zA-Z][a-zA-Z0-9:_-]*(?=\s|$)/;
24const MAX_SKILL_DEPTH = 10;
25const MAX_SKILL_BYTES = FileSystem.Size(1_000_000);
26const MAX_SKILL_SCAN_ENTRIES = 10_000;
27const MAX_SKILL_SCAN_BYTES = FileSystem.Size(8_000_000);
28
29interface CursorSkillFrontmatter {
30 readonly description?: string;
31 readonly displayName?: string;
32 readonly userInvocationOnly?: boolean;
33 readonly userInvocable?: boolean;
34 readonly cliVisible: boolean;
35}
36
37interface CursorSkillScanBudget {
38 remainingEntries: number;
39 remainingBytes: bigint;
40 exhausted: boolean;
41 incomplete: boolean;
42}
43
44class CursorSkillsProbeError extends Schema.TaggedErrorClass<CursorSkillsProbeError>()(
45 "CursorSkillsProbeError",
46 {
47 reason: Schema.Literals(["scan-budget-exhausted", "filesystem-error"]),
48 cwd: Schema.optional(Schema.String),
49 },
50) {
51 override get message(): string {
52 const location = this.cwd === undefined ? "" : ` for '${this.cwd}'`;
53 return `Cursor skill discovery${location} was incomplete (${this.reason}).`;
54 }
55}
56
57const orUndefined = <A, R>(
58 effect: Effect.Effect<A, PlatformError.PlatformError, R>,
59 budget?: CursorSkillScanBudget,
60): Effect.Effect<A | undefined, never, R> =>
61 effect.pipe(
62 Effect.map((value): A | undefined => value),
63 Effect.catchTags({
64 PlatformError: (error) => {
65 if (error.reason._tag !== "NotFound" && budget) budget.incomplete = true;
66 return Effect.void.pipe(Effect.as(undefined));
67 },
68 }),
69 );
70
71function parseFrontmatterBoolean(value: unknown): boolean | undefined {
72 if (typeof value === "boolean") return value;
73 if (typeof value === "number") return value === 1 ? true : value === 0 ? false : undefined;
74 if (typeof value !== "string") return undefined;
75 switch (value.trim().toLowerCase()) {
76 case "true":
77 case "yes":
78 case "on":
79 return true;
80 case "false":
81 case "no":
82 case "off":
83 return false;
84 default:
85 return undefined;
86 }
87}
88
89function parseSkillFrontmatter(contents: string): CursorSkillFrontmatter | undefined {
90 const match = FRONTMATTER_PATTERN.exec(contents);
91 if (!match) return { cliVisible: true };
92
93 let parsed: unknown;
94 try {
95 parsed = parseYamlDocument(match[1] ?? "");
96 } catch {
97 return undefined;
98 }
99 if (typeof parsed !== "object" || parsed === null) return undefined;
100
101 const record = parsed as Record<string, unknown>;
102 const metadata =
103 typeof record.metadata === "object" && record.metadata !== null
104 ? (record.metadata as Record<string, unknown>)
105 : undefined;
106 const rawSurfaces = metadata?.surfaces;
107 const surfaces = Array.isArray(rawSurfaces)
108 ? rawSurfaces.filter((surface): surface is string => typeof surface === "string")
109 : typeof rawSurfaces === "string"
110 ? rawSurfaces.split(",")
111 : [];
112 const description = typeof record.description === "string" ? record.description.trim() : "";
113 const displayName = typeof record.name === "string" ? record.name.trim() : "";
114 return {
115 cliVisible:
116 surfaces.length === 0 || surfaces.some((surface) => surface.trim().toLowerCase() === "cli"),
117 ...(description ? { description } : {}),
118 ...(displayName ? { displayName } : {}),
119 ...(parseFrontmatterBoolean(record["disable-model-invocation"]) === true
120 ? { userInvocationOnly: true }
121 : {}),
122 ...(parseFrontmatterBoolean(record["user-invocable"]) === false
123 ? { userInvocable: false }
124 : {}),
125 };
126}
127
128const discoverSkillsInRoot = Effect.fn("discoverCursorSkillsInRoot")(function* (input: {
129 readonly directory: string;
130 readonly scope: "user" | "project";
131 readonly budget: CursorSkillScanBudget;
132}): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
133 const fileSystem = yield* FileSystem.FileSystem;
134 const path = yield* Path.Path;
135 const skills: ServerProviderSkill[] = [];
136 if (input.budget.exhausted) return skills;
137 const rootDirectory = yield* orUndefined(fileSystem.realPath(input.directory), input.budget);
138 if (!rootDirectory) return skills;
139 const visitedDirectories = new Set<string>();
140
141 const visit = Effect.fn("visitCursorSkillDirectory")(function* (
142 directory: string,
143 depth: number,
144 ): Effect.fn.Return<void, never> {
145 if (input.budget.exhausted) return;
146 const resolvedDirectory = yield* orUndefined(fileSystem.realPath(directory), input.budget);
147 if (!resolvedDirectory) {
148 return;
149 }
150 if (visitedDirectories.has(resolvedDirectory)) {
151 return;
152 }
153 visitedDirectories.add(resolvedDirectory);
154 // A symlink whose target lives outside the root is a skill package
155 // boundary: read its own SKILL.md so linked skill libraries show up, but
156 // never walk the target tree.
157 const insideRoot =
158 resolvedDirectory === rootDirectory ||
159 resolvedDirectory.startsWith(`${rootDirectory}${path.sep}`);
160
161 const skillPath = path.join(directory, "SKILL.md");
162 const skillInfo = yield* orUndefined(fileSystem.stat(skillPath), input.budget);
163 if (skillInfo?.type === "File") {
164 let frontmatter: CursorSkillFrontmatter | undefined = { cliVisible: true };
165 if (skillInfo.size <= MAX_SKILL_BYTES && skillInfo.size <= input.budget.remainingBytes) {
166 const contents = yield* orUndefined(fileSystem.readFileString(skillPath));
167 if (contents !== undefined) {
168 input.budget.remainingBytes -= skillInfo.size;
169 frontmatter = parseSkillFrontmatter(contents);
170 }
171 }
172 const name = path.basename(directory).trim();
173 if (frontmatter?.cliVisible && name) {
174 skills.push({
175 name,
176 path: skillPath,
177 scope: input.scope,
178 enabled: true,
179 ...(frontmatter.displayName && frontmatter.displayName !== name
180 ? { displayName: frontmatter.displayName }
181 : {}),
182 ...(frontmatter.description ? { description: frontmatter.description } : {}),
183 ...(frontmatter.userInvocationOnly ? { userInvocationOnly: true } : {}),
184 ...(frontmatter.userInvocable === false ? { userInvocable: false } : {}),
185 });
186 }
187 }
188
189 if (!insideRoot) {
190 return;
191 }
192 const entries = yield* orUndefined(fileSystem.readDirectory(directory), input.budget);
193 if (!entries) {
194 return;
195 }
196 for (const entry of [...entries].sort()) {
197 if (input.budget.remainingEntries === 0) {
198 input.budget.exhausted = true;
199 return;
200 }
201 input.budget.remainingEntries -= 1;
202 const child = path.join(directory, entry);
203 const info = yield* orUndefined(fileSystem.stat(child), input.budget);
204 if (info?.type !== "Directory") continue;
205 if (depth >= MAX_SKILL_DEPTH) {
206 input.budget.exhausted = true;
207 return;
208 }
209 yield* visit(child, depth + 1);
210 }
211 });
212
213 yield* visit(rootDirectory, 0);
214 return skills;
215});
216
217const inspectCursorSkills = Effect.fn("inspectCursorSkills")(function* (
218 cwd?: string,
219 environment: NodeJS.ProcessEnv = process.env,
220) {
221 const path = yield* Path.Path;
222 const userHome = environment.HOME?.trim() || environment.USERPROFILE?.trim() || NodeOS.homedir();
223 const rootsBelow = (base: string, scope: "user" | "project") => [
224 { directory: path.join(base, ".cursor", "skills"), scope },
225 { directory: path.join(base, ".agents", "skills"), scope },
226 { directory: path.join(base, ".codex", "skills"), scope },
227 { directory: path.join(base, ".claude", "skills"), scope },
228 ];
229 const roots = [...(cwd ? rootsBelow(cwd, "project") : []), ...rootsBelow(userHome, "user")];
230
231 const skillsByName = new Map<string, ServerProviderSkill>();
232 const budget: CursorSkillScanBudget = {
233 remainingEntries: MAX_SKILL_SCAN_ENTRIES,
234 remainingBytes: MAX_SKILL_SCAN_BYTES,
235 exhausted: false,
236 incomplete: false,
237 };
238 for (const root of roots) {
239 if (budget.exhausted) break;
240 const skills = yield* discoverSkillsInRoot({ ...root, budget });
241 for (const skill of skills) {
242 if (!skillsByName.has(skill.name)) skillsByName.set(skill.name, skill);
243 }
244 }
245 return {
246 skills: [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name)),
247 failureReason: budget.exhausted
248 ? ("scan-budget-exhausted" as const)
249 : budget.incomplete
250 ? ("filesystem-error" as const)
251 : undefined,
252 };
253});
254
255export const discoverCursorSkills = Effect.fn("discoverCursorSkills")(function* (
256 cwd?: string,
257 environment: NodeJS.ProcessEnv = process.env,
258) {
259 return (yield* inspectCursorSkills(cwd, environment)).skills;
260});
261
262export const probeCursorSkills = Effect.fn("probeCursorSkills")(function* (
263 cwd?: string,
264 environment: NodeJS.ProcessEnv = process.env,
265) {
266 const inspection = yield* inspectCursorSkills(cwd, environment);
267 if (inspection.failureReason) {
268 return yield* new CursorSkillsProbeError({
269 reason: inspection.failureReason,
270 ...(cwd ? { cwd } : {}),
271 });
272 }
273 return inspection.skills;
274});
275
276/** Cursor invokes Agent Skills with `/name`; T3 composers insert `$name`. */
277export function hasCursorSkillMention(prompt: string): boolean {
278 return HAS_SKILL_MENTION_PATTERN.test(prompt);
279}
280
281export function rewriteCursorSkillMentions(
282 prompt: string,
283 skillNames: ReadonlySet<string>,
284): string {
285 return prompt.replace(SKILL_MENTION_PATTERN, (match, prefix: string, name: string) =>
286 skillNames.has(name) ? `${prefix}/${name}` : match,
287 );
288}