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