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

skills.ts

291 lines10.5 KB

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