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

ClaudeSkills.ts

552 lines20.2 KB

1import type { ClaudeSettings, ServerProviderSkill } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Path from "effect/Path";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import { parseCliArgs } from "@t3tools/shared/cliArgs";
9import { fromLenientJson } from "@t3tools/shared/schemaJson";
10import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens";
11import { parse as parseYamlDocument } from "yaml";
12​
13import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
14​
15type ClaudeSkillScope = "user" | "project";
16​
17type ClaudeSkillRoot = {
18 readonly directory: string;
19 readonly scope: ClaudeSkillScope;
20 readonly prefix?: string;
21};
22​
23const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
24​
25type SkillFrontmatter =
26 | { readonly kind: "missing" }
27 | { readonly kind: "malformed" }
28 | {
29 readonly kind: "parsed";
30 readonly name?: string;
31 readonly description?: string;
32 readonly userInvocationOnly?: boolean;
33 readonly userInvocable?: boolean;
34 };
35​
36/**
37 * Claude Code accepts the YAML 1.1 boolean spellings (`yes`/`no`, `on`/`off`,
38 * `1`/`0`), which the 1.2 core schema this parser uses leaves as strings and
39 * numbers.
40 */
41function parseFrontmatterBoolean(value: unknown): boolean | undefined {
42 if (typeof value === "boolean") return value;
43 if (typeof value === "number") {
44 return value === 1 ? true : value === 0 ? false : undefined;
45 }
46 if (typeof value !== "string") return undefined;
47 switch (value.trim().toLowerCase()) {
48 case "true":
49 case "yes":
50 case "on":
51 case "y":
52 return true;
53 case "false":
54 case "no":
55 case "off":
56 case "n":
57 return false;
58 default:
59 return undefined;
60 }
62​
63function parseSkillFrontmatter(contents: string): SkillFrontmatter {
64 const match = FRONTMATTER_PATTERN.exec(contents);
65 if (!match) {
66 return { kind: "missing" };
67 }
68​
69 const frontmatter = match[1] ?? "";
70 let parsed: unknown;
71 try {
72 parsed = parseYamlDocument(frontmatter);
73 } catch {
74 // Claude Code accepts plain scalars containing `: `. Repair only those,
75 // leaving comments and YAML structure for the full-document parser.
76 const repaired = frontmatter.replace(
77 /^([\w-]+:[ \t]*)([^\r\n]*)/gm,
78 (line, prefix: string, value: string) => {
79 const scalar = value.split(/[ \t]+#/)[0] ?? "";
80 if (!/:[ \t]/.test(scalar) || /^(?:["'[\]{}|>&*!#%@`]|[-?:](?:[ \t]|$))/.test(scalar)) {
81 return line;
82 }
83 return `${prefix}${JSON.stringify(scalar)}${value.slice(scalar.length)}`;
84 },
85 );
86 try {
87 parsed = parseYamlDocument(repaired);
88 } catch {
89 return { kind: "malformed" };
90 }
91 }
92 if (typeof parsed !== "object" || parsed === null) {
93 return { kind: "malformed" };
94 }
95​
96 const record = parsed as Record<string, unknown>;
97 const name = typeof record.name === "string" ? record.name.trim() : "";
98 const description = typeof record.description === "string" ? record.description.trim() : "";
99 return {
100 kind: "parsed",
101 ...(name ? { name } : {}),
102 ...(description ? { description } : {}),
103 ...(parseFrontmatterBoolean(record["disable-model-invocation"]) === true
104 ? { userInvocationOnly: true }
105 : {}),
106 ...(parseFrontmatterBoolean(record["user-invocable"]) === false
107 ? { userInvocable: false }
108 : {}),
109 };
111​
112function claudeManagedSettingsPath(
113 path: Path.Path,
114 platform: NodeJS.Platform,
115 environment: NodeJS.ProcessEnv,
116): string | undefined {
117 if (platform === "darwin") {
118 return "/Library/Application Support/ClaudeCode/managed-settings.json";
119 }
120 if (platform === "win32") {
121 const programData = environment.PROGRAMDATA?.trim();
122 return programData ? path.join(programData, "ClaudeCode", "managed-settings.json") : undefined;
123 }
124 return "/etc/claude-code/managed-settings.json";
126​
127function skillOverrideSettingsPaths(
128 path: Path.Path,
129 configDirPath: string,
130 cwd: string | undefined,
131 platform: NodeJS.Platform,
132 environment: NodeJS.ProcessEnv,
133 repositoryRoot?: string,
134): ReadonlyArray<string> {
135 const managedPath = claudeManagedSettingsPath(path, platform, environment);
136 const root = repositoryRoot !== undefined && repositoryRoot !== cwd ? repositoryRoot : undefined;
137 return [
138 path.join(configDirPath, "settings.json"),
139 ...(cwd
140 ? [
141 path.join(cwd, ".claude", "settings.json"),
142 path.join(cwd, ".claude", "settings.local.json"),
143 ]
144 : []),
145 ...(root ? [path.join(root, ".claude", "settings.local.json")] : []),
146 ...(managedPath ? [managedPath] : []),
147 ];
149​
150const findRepositoryRoot = Effect.fn("findRepositoryRoot")(function* (
151 cwd: string,
152): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {
153 const fileSystem = yield* FileSystem.FileSystem;
154 const path = yield* Path.Path;
155 let current = path.resolve(cwd);
156 while (true) {
157 const isRoot = yield* fileSystem
158 .exists(path.join(current, ".git"))
159 .pipe(Effect.orElseSucceed(() => false));
160 if (isRoot) {
161 return current;
162 }
163 const parent = path.dirname(current);
164 if (parent === current) {
165 return undefined;
166 }
167 current = parent;
168 }
169});
170​
171const findPluginRepositoryRoot = Effect.fn("findPluginRepositoryRoot")(function* (cwd: string) {
172 const fileSystem = yield* FileSystem.FileSystem;
173 const path = yield* Path.Path;
174 const root = yield* findRepositoryRoot(cwd);
175 if (root === undefined) return undefined;
176 const gitFile = yield* fileSystem
177 .readFileString(path.join(root, ".git"))
178 .pipe(Effect.orElseSucceed(() => ""));
179 if (!gitFile.trim().startsWith("gitdir:")) return root;
180 const gitDirectory = path.resolve(root, gitFile.trim().slice(7).trim());
181 const commonFile = yield* fileSystem
182 .readFileString(path.join(gitDirectory, "commondir"))
183 .pipe(Effect.orElseSucceed(() => ""));
184 const worktreeFile = yield* fileSystem
185 .readFileString(path.join(gitDirectory, "gitdir"))
186 .pipe(Effect.orElseSucceed(() => ""));
187 if (!commonFile.trim() || !worktreeFile.trim()) return root;
188 const commonDirectory = path.resolve(gitDirectory, commonFile.trim());
189 const backlinkPath = yield* fileSystem
190 .realPath(path.resolve(gitDirectory, worktreeFile.trim()))
191 .pipe(Effect.orElseSucceed(() => undefined));
192 const worktreeGitPath = yield* fileSystem
193 .realPath(path.join(root, ".git"))
194 .pipe(Effect.orElseSucceed(() => undefined));
195 if (
196 path.dirname(gitDirectory) !== path.join(commonDirectory, "worktrees") ||
197 backlinkPath === undefined ||
198 backlinkPath !== worktreeGitPath
199 ) {
200 return root;
201 }
202 // Claude shares plugin install records across linked worktrees, using their common repository.
203 return path.basename(commonDirectory) === ".git"
204 ? path.dirname(commonDirectory)
205 : commonDirectory;
206});
207​
208/**
209 * The CLI validates the whole map, not each entry: verified against it, one
210 * entry with an unknown value (or a boolean) makes it drop every override in
211 * that file, so this schema does the same rather than applying the valid
212 * siblings the CLI ignores.
213 */
214const SkillOverrideValue = Schema.Literals(["on", "name-only", "user-invocable-only", "off"]);
215​
216// Lenient because these settings files are hand-edited and Claude Code itself
217// tolerates comments and trailing commas in them.
218const SkillSettings = fromLenientJson(
219 Schema.Struct({
220 skillOverrides: Schema.optional(Schema.Record(Schema.String, SkillOverrideValue)),
221 enabledPlugins: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
222 }),
223);
224const decodeSkillSettings = Schema.decodeUnknownEffect(SkillSettings);
225​
226type SkillOverride = {
227 readonly enabled: boolean;
228 readonly userInvocationOnly: boolean;
229};
230​
231function parseSkillOverride(value: typeof SkillOverrideValue.Type): SkillOverride {
232 switch (value) {
233 case "off":
234 return { enabled: false, userInvocationOnly: false };
235 case "user-invocable-only":
236 return { enabled: true, userInvocationOnly: true };
237 case "on":
238 case "name-only":
239 return { enabled: true, userInvocationOnly: false };
240 }
242​
243const readSkillSettings = Effect.fn("readSkillSettings")(function* (
244 configDirPath: string,
245 cwd: string | undefined,
246 environment: NodeJS.ProcessEnv,
247) {
248 const fileSystem = yield* FileSystem.FileSystem;
249 const path = yield* Path.Path;
250 const platform = yield* HostProcess.Platform;
251 const overridesByName = new Map<string, SkillOverride>();
252 const enabledPlugins = new Map<string, boolean>();
253 const repositoryRoot = cwd === undefined ? undefined : yield* findRepositoryRoot(cwd);
254​
255 for (const settingsPath of skillOverrideSettingsPaths(
256 path,
257 configDirPath,
258 cwd,
259 platform,
260 environment,
261 repositoryRoot,
262 )) {
263 const contents = yield* fileSystem
264 .readFileString(settingsPath)
265 .pipe(Effect.orElseSucceed(() => undefined));
266 if (contents === undefined) {
267 continue;
268 }
269​
270 const parsed = yield* decodeSkillSettings(contents).pipe(
271 Effect.tapError((cause) =>
272 Effect.logDebug("claude settings file is unreadable; ignoring skill settings", {
273 path: settingsPath,
274 cause,
275 }),
276 ),
277 Effect.orElseSucceed(() => undefined),
278 );
279 for (const [name, value] of Object.entries(parsed?.skillOverrides ?? {})) {
280 overridesByName.set(name, parseSkillOverride(value));
281 }
282 for (const [key, enabled] of Object.entries(parsed?.enabledPlugins ?? {})) {
283 if (typeof enabled === "boolean") {
284 enabledPlugins.set(key, enabled);
285 } else {
286 // Extended formats replace lower-precedence values without enabling the plugin here.
287 enabledPlugins.delete(key);
288 }
289 }
290 }
291​
292 return { skillOverrides: overridesByName, enabledPlugins };
293});
294​
295const InstalledPlugins = Schema.fromJsonString(
296 Schema.Struct({ plugins: Schema.Record(Schema.String, Schema.Array(Schema.Unknown)) }),
297);
298const decodeInstalledPlugin = Schema.decodeUnknownOption(
299 Schema.Struct({
300 scope: Schema.Literals(["user", "project", "local", "managed"]),
301 installPath: Schema.NonEmptyString,
302 projectPath: Schema.optional(Schema.NonEmptyString),
303 }),
304);
305const PluginManifest = Schema.fromJsonString(
306 Schema.Struct({
307 name: Schema.optional(Schema.NonEmptyString),
308 skills: Schema.optional(Schema.Union([Schema.String, Schema.Array(Schema.String)])),
309 }),
310);
311​
312function isInsideDirectory(path: Path.Path, directory: string, candidate: string): boolean {
313 const relative = path.relative(directory, candidate);
314 return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
316​
317const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* (
318 configDirPath: string,
319 cwd: string | undefined,
320 enabledPlugins: ReadonlyMap<string, boolean>,
321 environment: NodeJS.ProcessEnv,
322) {
323 const fileSystem = yield* FileSystem.FileSystem;
324 const path = yield* Path.Path;
325 const home = yield* HostProcess.HomeDirectory;
326 const pluginDirectory = environment.CLAUDE_CODE_PLUGIN_CACHE_DIR;
327 const pluginsPath = pluginDirectory
328 ? path.resolve(cwd ?? ".", expandHomePath(pluginDirectory, home))
329 : path.join(configDirPath, "plugins");
330 const installed = yield* fileSystem
331 .readFileString(path.join(pluginsPath, "installed_plugins.json"))
332 .pipe(
333 Effect.flatMap(Schema.decodeUnknownEffect(InstalledPlugins)),
334 Effect.orElseSucceed(() => undefined),
335 );
336 if (installed === undefined) return [];
337 const roots: Array<ClaudeSkillRoot> = [];
338 // The CLI's process.cwd() resolves symlinks; registry projectPath values remain lexical.
339 const workspace =
340 cwd === undefined
341 ? undefined
342 : yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => path.resolve(cwd)));
343 const repositoryRoot =
344 workspace === undefined ? undefined : yield* findPluginRepositoryRoot(workspace);
345​
346 for (const [key, entries] of Object.entries(installed.plugins).sort()) {
347 if (enabledPlugins.get(key) !== true) continue;
348 const applicable = yield* Effect.filter(
349 entries.flatMap((entry) => Option.toArray(decodeInstalledPlugin(entry))),
350 (record) =>
351 Effect.gen(function* () {
352 if (record.scope === "user" || record.scope === "managed") return true;
353 if (record.projectPath === undefined || workspace === undefined) return false;
354 if (path.resolve(record.projectPath) === workspace) return true;
355 return (
356 repositoryRoot !== undefined &&
357 (yield* findPluginRepositoryRoot(record.projectPath)) === repositoryRoot
358 );
359 }),
360 );
361 // The native loader keeps registry order, preferring the first install that exists.
362 const existing = yield* Effect.findFirst(applicable, (record) =>
363 fileSystem
364 .exists(path.resolve(cwd ?? ".", record.installPath))
365 .pipe(Effect.orElseSucceed(() => false)),
366 );
367 const install = Option.getOrElse(existing, () => applicable[0]);
368 if (!install) continue;
369 const scope = install.scope === "user" || install.scope === "managed" ? "user" : "project";
370 const installPath = path.resolve(cwd ?? ".", install.installPath);
371 const manifest = yield* fileSystem
372 .readFileString(path.join(installPath, ".claude-plugin", "plugin.json"))
373 .pipe(
374 Effect.flatMap(Schema.decodeUnknownEffect(PluginManifest)),
375 Effect.orElseSucceed(() => undefined),
376 );
377 const prefix = manifest?.name ?? key.split("@")[0];
378 if (!prefix) continue;
379​
380 const defaultDirectory = path.join(installPath, "skills");
381 const hasDefaultDirectory = yield* fileSystem
382 .exists(defaultDirectory)
383 .pipe(Effect.orElseSucceed(() => false));
384 if (hasDefaultDirectory) roots.push({ directory: defaultDirectory, scope, prefix });
385 const declared = manifest?.skills;
386 if (declared === undefined && !hasDefaultDirectory) {
387 const hasRootSkill = yield* fileSystem
388 .exists(path.join(installPath, "SKILL.md"))
389 .pipe(Effect.orElseSucceed(() => false));
390 if (hasRootSkill) roots.push({ directory: installPath, scope, prefix });
391 }
392​
393 const canonicalInstallPath = yield* fileSystem
394 .realPath(installPath)
395 .pipe(Effect.orElseSucceed(() => undefined));
396 for (const relative of typeof declared === "string" ? [declared] : (declared ?? [])) {
397 const directory = path.resolve(installPath, relative);
398 if (!isInsideDirectory(path, installPath, directory) || canonicalInstallPath === undefined) {
399 continue;
400 }
401 const canonicalDirectory = yield* fileSystem
402 .realPath(directory)
403 .pipe(Effect.orElseSucceed(() => undefined));
404 // The native loader rejects manifest roots that escape through a symlink, too.
405 if (
406 canonicalDirectory !== undefined &&
407 isInsideDirectory(path, canonicalInstallPath, canonicalDirectory)
408 ) {
409 roots.push({ directory, scope, prefix });
410 }
411 }
412 }
413 return roots;
414});
415​
416const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
417 config: Pick<ClaudeSettings, "homePath">,
418 environment: NodeJS.ProcessEnv,
419 cwd?: string,
420): Effect.fn.Return<string, never, Path.Path> {
421 const path = yield* Path.Path;
422 const home = yield* HostProcess.HomeDirectory;
423 const homePath = config.homePath.trim();
424 if (homePath.length > 0) {
425 return path.resolve(expandHomePath(homePath, home));
426 }
427 // No tilde expansion here: the spawned CLI receives this env var verbatim
428 // (env vars are never shell-expanded), so a literal `~` must stay literal
429 // for discovery to scan the same directory the runtime would. A relative
430 // value is resolved against the workspace cwd — the subprocess's own cwd —
431 // for the same reason.
432 const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
433 if (environmentConfigDir.length > 0) {
434 return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
435 }
436 return path.join(home, ".claude");
437});
438​
439/**
440 * Roots are listed highest precedence first and the first hit for a name wins,
441 * matching Claude Code: verified against the CLI with the same skill name in
442 * both scopes, the user copy is the one that runs.
443 */
444export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
445 config: Pick<ClaudeSettings, "homePath"> & Partial<Pick<ClaudeSettings, "launchArgs">>,
446 cwd?: string,
447 environment?: NodeJS.ProcessEnv,
448): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
449 const fileSystem = yield* FileSystem.FileSystem;
450 const path = yield* Path.Path;
451 const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);
452 const { skillOverrides, enabledPlugins } = yield* readSkillSettings(
453 configDirPath,
454 cwd,
455 environment ?? process.env,
456 );
457​
458 // Use the session's argument parser so discovery sees the same --add-dir value.
459 const additionalDirectory = parseCliArgs(config.launchArgs ?? "").flags["add-dir"];
460 const roots: ReadonlyArray<ClaudeSkillRoot> = [
461 { directory: path.join(configDirPath, "skills"), scope: "user" },
462 ...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
463 ...(additionalDirectory && (cwd || path.isAbsolute(additionalDirectory))
464 ? [
465 {
466 directory: path.join(
467 path.resolve(cwd ?? ".", additionalDirectory),
468 ".claude",
469 "skills",
470 ),
471 scope: "project" as const,
472 },
473 ]
474 : []),
475 ...(yield* discoverPluginSkillRoots(
476 configDirPath,
477 cwd,
478 enabledPlugins,
479 environment ?? process.env,
480 )),
481 ];
482​
483 const skillsByName = new Map<string, ServerProviderSkill>();
484 for (const root of roots) {
485 const singleSkill =
486 root.prefix !== undefined &&
487 (yield* fileSystem
488 .exists(path.join(root.directory, "SKILL.md"))
489 .pipe(Effect.orElseSucceed(() => false)));
490 const entries = singleSkill
491 ? [path.basename(root.directory)]
492 : yield* fileSystem
493 .readDirectory(root.directory)
494 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
495​
496 for (const entry of [...entries].sort()) {
497 const skillPath = singleSkill
498 ? path.join(root.directory, "SKILL.md")
499 : path.join(root.directory, entry, "SKILL.md");
500 const contents = yield* fileSystem
501 .readFileString(skillPath)
502 .pipe(Effect.orElseSucceed(() => undefined));
503 if (contents === undefined) {
504 continue;
505 }
506​
507 const frontmatter = parseSkillFrontmatter(contents);
508 if (frontmatter.kind === "malformed") {
509 continue;
510 }
511​
512 const directoryName = entry.trim();
513 if (!directoryName) continue;
514 let name = directoryName;
515 if (root.prefix) {
516 // Native folder skills use their folder; only a single SKILL.md uses its name field.
517 const declaredName = singleSkill && frontmatter.kind === "parsed" ? frontmatter.name : "";
518 const unprefixedName = declaredName?.startsWith(`${root.prefix}:`)
519 ? declaredName.slice(root.prefix.length + 1)
520 : declaredName;
521 name = `${root.prefix}:${(unprefixedName || entry).replace(/[^a-zA-Z0-9_-]/g, "-")}`;
522 // Advertise only exact native names the shared composer grammar can invoke.
523 const [mention] = `$${name}`.matchAll(SKILL_MENTION_PATTERN);
524 if (mention?.[2] !== name) continue;
525 }
526​
527 if (skillsByName.has(name)) {
528 continue;
529 }
530​
531 const override = root.prefix ? undefined : skillOverrides.get(name);
532 const userInvocationOnly =
533 (frontmatter.kind === "parsed" && frontmatter.userInvocationOnly === true) ||
534 override?.userInvocationOnly === true;
535 skillsByName.set(name, {
536 name,
537 path: skillPath,
538 enabled: override?.enabled ?? true,
539 scope: root.scope,
540 ...(frontmatter.kind === "parsed" && frontmatter.description
541 ? { description: frontmatter.description }
542 : {}),
543 ...(userInvocationOnly ? { userInvocationOnly: true } : {}),
544 ...(frontmatter.kind === "parsed" && frontmatter.userInvocable === false
545 ? { userInvocable: false }
546 : {}),
547 });
548 }
549 }
550​
551 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
552});