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 (
151 visitedDirectories.has(resolvedDirectory) ||
152 (resolvedDirectory !== rootDirectory &&
153 !resolvedDirectory.startsWith(`${rootDirectory}${path.sep}`))
154 ) {
155 return;
156 }
157 visitedDirectories.add(resolvedDirectory);
158
159 const skillPath = path.join(resolvedDirectory, "SKILL.md");
160 const skillInfo = yield* orUndefined(fileSystem.stat(skillPath), input.budget);
161 if (skillInfo?.type === "File") {
162 let frontmatter: CursorSkillFrontmatter | undefined = { cliVisible: true };
163 if (skillInfo.size <= MAX_SKILL_BYTES && skillInfo.size <= input.budget.remainingBytes) {
164 const contents = yield* orUndefined(fileSystem.readFileString(skillPath));
165 if (contents !== undefined) {
166 input.budget.remainingBytes -= skillInfo.size;
167 frontmatter = parseSkillFrontmatter(contents);
168 }
169 }
170 const name = path.basename(resolvedDirectory).trim();
171 if (frontmatter?.cliVisible && name) {
172 skills.push({
173 name,
174 path: skillPath,
175 scope: input.scope,
176 enabled: true,
177 ...(frontmatter.displayName && frontmatter.displayName !== name
178 ? { displayName: frontmatter.displayName }
179 : {}),
180 ...(frontmatter.description ? { description: frontmatter.description } : {}),
181 ...(frontmatter.userInvocationOnly ? { userInvocationOnly: true } : {}),
182 ...(frontmatter.userInvocable === false ? { userInvocable: false } : {}),
183 });
184 }
185 }
186
187 const entries = yield* orUndefined(fileSystem.readDirectory(resolvedDirectory), input.budget);
188 if (!entries) {
189 return;
190 }
191 for (const entry of [...entries].sort()) {
192 if (input.budget.remainingEntries === 0) {
193 input.budget.exhausted = true;
194 return;
195 }
196 input.budget.remainingEntries -= 1;
197 const child = path.join(resolvedDirectory, entry);
198 const info = yield* orUndefined(fileSystem.stat(child), input.budget);
199 if (info?.type !== "Directory") continue;
200 if (depth >= MAX_SKILL_DEPTH) {
201 input.budget.exhausted = true;
202 return;
203 }
204 yield* visit(child, depth + 1);
205 }
206 });
207
208 yield* visit(rootDirectory, 0);
209 return skills;
210});
211
212const inspectCursorSkills = Effect.fn("inspectCursorSkills")(function* (
213 cwd?: string,
214 environment: NodeJS.ProcessEnv = process.env,
215) {
216 const path = yield* Path.Path;
217 const userHome = environment.HOME?.trim() || environment.USERPROFILE?.trim() || NodeOS.homedir();
218 const rootsBelow = (base: string, scope: "user" | "project") => [
219 { directory: path.join(base, ".cursor", "skills"), scope },
220 { directory: path.join(base, ".agents", "skills"), scope },
221 { directory: path.join(base, ".codex", "skills"), scope },
222 { directory: path.join(base, ".claude", "skills"), scope },
223 ];
224 const roots = [...(cwd ? rootsBelow(cwd, "project") : []), ...rootsBelow(userHome, "user")];
225
226 const skillsByName = new Map<string, ServerProviderSkill>();
227 const budget: CursorSkillScanBudget = {
228 remainingEntries: MAX_SKILL_SCAN_ENTRIES,
229 remainingBytes: MAX_SKILL_SCAN_BYTES,
230 exhausted: false,
231 incomplete: false,
232 };
233 for (const root of roots) {
234 if (budget.exhausted) break;
235 const skills = yield* discoverSkillsInRoot({ ...root, budget });
236 for (const skill of skills) {
237 if (!skillsByName.has(skill.name)) skillsByName.set(skill.name, skill);
238 }
239 }
240 return {
241 skills: [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name)),
242 failureReason: budget.exhausted
243 ? ("scan-budget-exhausted" as const)
244 : budget.incomplete
245 ? ("filesystem-error" as const)
246 : undefined,
247 };
248});
249
250export const discoverCursorSkills = Effect.fn("discoverCursorSkills")(function* (
251 cwd?: string,
252 environment: NodeJS.ProcessEnv = process.env,
253) {
254 return (yield* inspectCursorSkills(cwd, environment)).skills;
255});
256
257export const probeCursorSkills = Effect.fn("probeCursorSkills")(function* (
258 cwd?: string,
259 environment: NodeJS.ProcessEnv = process.env,
260) {
261 const inspection = yield* inspectCursorSkills(cwd, environment);
262 if (inspection.failureReason) {
263 return yield* new CursorSkillsProbeError({
264 reason: inspection.failureReason,
265 ...(cwd ? { cwd } : {}),
266 });
267 }
268 return inspection.skills;
269});
270
271/** Cursor invokes Agent Skills with `/name`; T3 composers insert `$name`. */
272export function hasCursorSkillMention(prompt: string): boolean {
273 return HAS_SKILL_MENTION_PATTERN.test(prompt);
274}
275
276export function rewriteCursorSkillMentions(
277 prompt: string,
278 skillNames: ReadonlySet<string>,
279): string {
280 return prompt.replace(SKILL_MENTION_PATTERN, (match, prefix: string, name: string) =>
281 skillNames.has(name) ? `${prefix}/${name}` : match,
282 );
283}