The best way to control Claude Code, Codex and more from any computer or phone

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