Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CursorSkills.ts

289 lines10.2 KB

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