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

skills.ts

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