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

skills.ts

286 lines10.1 KB

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;
34​
35interface CursorSkillScanBudget {
36 remainingEntries: number;
37 remainingBytes: bigint;
38 exhausted: boolean;
39 incomplete: boolean;
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 }
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 }
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 };
125​
126const discoverSkillsInRoot = Effect.fn("discoverCursorSkillsInRoot")(function* (input: {
127 readonly directory: string;
128 readonly scope: "user" | "project";
129 readonly budget: CursorSkillScanBudget;
130}): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
131 const fileSystem = yield* FileSystem.FileSystem;
132 const path = yield* Path.Path;
133 const skills: ServerProviderSkill[] = [];
134 if (input.budget.exhausted) return skills;
135 const rootDirectory = yield* orUndefined(fileSystem.realPath(input.directory), input.budget);
136 if (!rootDirectory) return skills;
137 const visitedDirectories = new Set<string>();
138​
139 const visit = Effect.fn("visitCursorSkillDirectory")(function* (
140 directory: string,
141 depth: number,
142 ): Effect.fn.Return<void, never> {
143 if (input.budget.exhausted) return;
144 const resolvedDirectory = yield* orUndefined(fileSystem.realPath(directory), input.budget);
145 if (!resolvedDirectory) {
146 return;
147 }
148 if (visitedDirectories.has(resolvedDirectory)) {
149 return;
150 }
151 visitedDirectories.add(resolvedDirectory);
152 // A symlink whose target lives outside the root is a skill package
153 // boundary: read its own SKILL.md so linked skill libraries show up, but
154 // never walk the target tree.
155 const insideRoot =
156 resolvedDirectory === rootDirectory ||
157 resolvedDirectory.startsWith(`${rootDirectory}${path.sep}`);
158​
159 const skillPath = path.join(directory, "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(directory).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 if (!insideRoot) {
188 return;
189 }
190 const entries = yield* orUndefined(fileSystem.readDirectory(directory), input.budget);
191 if (!entries) {
192 return;
193 }
194 for (const entry of [...entries].sort()) {
195 if (input.budget.remainingEntries === 0) {
196 input.budget.exhausted = true;
197 return;
198 }
199 input.budget.remainingEntries -= 1;
200 const child = path.join(directory, entry);
201 const info = yield* orUndefined(fileSystem.stat(child), input.budget);
202 if (info?.type !== "Directory") continue;
203 if (depth >= MAX_SKILL_DEPTH) continue;
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 =
218 environment.HOME?.trim() ||
219 environment.USERPROFILE?.trim() ||
220 (yield* HostProcess.HomeDirectory);
221 const rootsBelow = (base: string, scope: "user" | "project") => [
222 { directory: path.join(base, ".cursor", "skills"), scope },
223 { directory: path.join(base, ".agents", "skills"), scope },
224 { directory: path.join(base, ".codex", "skills"), scope },
225 { directory: path.join(base, ".claude", "skills"), scope },
226 ];
227 const roots = [...(cwd ? rootsBelow(cwd, "project") : []), ...rootsBelow(userHome, "user")];
228​
229 const skillsByName = new Map<string, ServerProviderSkill>();
230 const budget: CursorSkillScanBudget = {
231 remainingEntries: MAX_SKILL_SCAN_ENTRIES,
232 remainingBytes: MAX_SKILL_SCAN_BYTES,
233 exhausted: false,
234 incomplete: false,
235 };
236 for (const root of roots) {
237 if (budget.exhausted) break;
238 const skills = yield* discoverSkillsInRoot({ ...root, budget });
239 for (const skill of skills) {
240 if (!skillsByName.has(skill.name)) skillsByName.set(skill.name, skill);
241 }
242 }
243 return {
244 skills: [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name)),
245 failureReason: budget.exhausted
246 ? ("scan-budget-exhausted" as const)
247 : budget.incomplete
248 ? ("filesystem-error" as const)
249 : undefined,
250 };
251});
252​
253export const discoverCursorSkills = Effect.fn("discoverCursorSkills")(function* (
254 cwd?: string,
255 environment: NodeJS.ProcessEnv = process.env,
256) {
257 return (yield* inspectCursorSkills(cwd, environment)).skills;
258});
259​
260export const probeCursorSkills = Effect.fn("probeCursorSkills")(function* (
261 cwd?: string,
262 environment: NodeJS.ProcessEnv = process.env,
263) {
264 const inspection = yield* inspectCursorSkills(cwd, environment);
265 if (inspection.failureReason) {
266 return yield* new CursorSkillsProbeError({
267 reason: inspection.failureReason,
268 ...(cwd ? { cwd } : {}),
269 });
270 }
271 return inspection.skills;
272});
273​
274/** Cursor invokes Agent Skills with `/name`; T3 composers insert `$name`. */
275export function hasCursorSkillMention(prompt: string): boolean {
276 return HAS_SKILL_MENTION_PATTERN.test(prompt);
278​
279export function rewriteCursorSkillMentions(
280 prompt: string,
281 skillNames: ReadonlySet<string>,
282): string {
283 return prompt.replace(SKILL_MENTION_PATTERN, (match, prefix: string, name: string) =>
284 skillNames.has(name) ? `${prefix}/${name}` : match,
285 );