Open History to see the last commit
1/**
2 * ClaudeSkills — filesystem discovery of Claude Code skills for the `$` picker.
3 *
4 * Claude Code loads skills from `<config dir>/skills` (user scope), then
5 * `<cwd>/.agents/skills` and `<cwd>/.claude/skills` (project scope), one
6 * directory per skill with a `SKILL.md` carrying YAML frontmatter. Later roots
7 * win on name collisions, so precedence is user, `.agents`, then `.claude`.
8 * The Agent SDK init handshake surfaces skills only as slash commands without
9 * their filesystem paths, so the provider snapshot scans the same locations
10 * directly, mirroring how the Codex app-server reports its skills.
11 *
12 * @module provider/Drivers/ClaudeSkills
13 */
14import * as NodeOS from "node:os";
15
16import type { ClaudeSettings, ServerProviderSkill } from "@t3tools/contracts";
17import * as Effect from "effect/Effect";
18import * as FileSystem from "effect/FileSystem";
19import * as Path from "effect/Path";
20import { parse as parseYamlDocument } from "yaml";
21
22import { expandHomePath } from "../../pathExpansion.ts";
23
24type ClaudeSkillScope = "user" | "project";
25
26const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
27
28type SkillFrontmatter =
29 | { readonly kind: "missing" }
30 | { readonly kind: "malformed" }
31 | { readonly kind: "parsed"; readonly name?: string; readonly description?: string };
32
33function parseSkillFrontmatter(contents: string): SkillFrontmatter {
34 const match = FRONTMATTER_PATTERN.exec(contents);
35 if (!match) {
36 return { kind: "missing" };
37 }
38
39 let parsed: unknown;
40 try {
41 parsed = parseYamlDocument(match[1] ?? "");
42 } catch {
43 return { kind: "malformed" };
44 }
45 if (typeof parsed !== "object" || parsed === null) {
46 return { kind: "malformed" };
47 }
48
49 const record = parsed as Record<string, unknown>;
50 const name = typeof record.name === "string" ? record.name.trim() : "";
51 const description = typeof record.description === "string" ? record.description.trim() : "";
52 return {
53 kind: "parsed",
54 ...(name ? { name } : {}),
55 ...(description ? { description } : {}),
56 };
57}
58
59/**
60 * Resolve the Claude config directory the CLI would use, matching the
61 * precedence the spawned CLI sees: the instance's `homePath` (exported as
62 * `CLAUDE_CONFIG_DIR` by `makeClaudeEnvironment`), then a `CLAUDE_CONFIG_DIR`
63 * already present in the process environment, then `~/.claude`.
64 */
65const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
66 config: Pick<ClaudeSettings, "homePath">,
67 environment: NodeJS.ProcessEnv,
68 cwd?: string,
69): Effect.fn.Return<string, never, Path.Path> {
70 const path = yield* Path.Path;
71 const homePath = config.homePath.trim();
72 if (homePath.length > 0) {
73 return path.resolve(expandHomePath(homePath));
74 }
75 // No tilde expansion here: the spawned CLI receives this env var verbatim
76 // (env vars are never shell-expanded), so a literal `~` must stay literal
77 // for discovery to scan the same directory the runtime would. A relative
78 // value is resolved against the workspace cwd — the subprocess's own cwd —
79 // for the same reason.
80 const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
81 if (environmentConfigDir.length > 0) {
82 return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
83 }
84 return path.join(NodeOS.homedir(), ".claude");
85});
86
87/**
88 * Enumerate Claude Code skills from the user config dir, workspace
89 * `.agents/skills`, and workspace `.claude/skills`, in that order. Discovery
90 * is best-effort: unreadable roots and malformed skill entries are skipped so
91 * a broken skill never degrades the provider snapshot. On name collisions,
92 * later roots win: `.agents` beats user and `.claude` beats `.agents`, matching
93 * Claude Code's resolution.
94 */
95export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
96 config: Pick<ClaudeSettings, "homePath">,
97 cwd?: string,
98 environment?: NodeJS.ProcessEnv,
99): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
100 const fileSystem = yield* FileSystem.FileSystem;
101 const path = yield* Path.Path;
102 const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);
103
104 const roots: ReadonlyArray<{ directory: string; scope: ClaudeSkillScope }> = [
105 { directory: path.join(configDirPath, "skills"), scope: "user" },
106 ...(cwd
107 ? [
108 { directory: path.join(cwd, ".agents", "skills"), scope: "project" as const },
109 { directory: path.join(cwd, ".claude", "skills"), scope: "project" as const },
110 ]
111 : []),
112 ];
113
114 const skillsByName = new Map<string, ServerProviderSkill>();
115 for (const root of roots) {
116 const entries = yield* fileSystem
117 .readDirectory(root.directory)
118 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
119
120 for (const entry of [...entries].sort()) {
121 const skillPath = path.join(root.directory, entry, "SKILL.md");
122 const contents = yield* fileSystem
123 .readFileString(skillPath)
124 .pipe(Effect.orElseSucceed(() => undefined));
125 if (contents === undefined) {
126 continue;
127 }
128
129 const frontmatter = parseSkillFrontmatter(contents);
130 // Malformed frontmatter means the skill won't load in Claude Code
131 // either — skip it rather than surfacing a broken entry under its
132 // directory name.
133 if (frontmatter.kind === "malformed") {
134 continue;
135 }
136
137 const name = (frontmatter.kind === "parsed" ? frontmatter.name : undefined) ?? entry.trim();
138 if (!name) {
139 continue;
140 }
141
142 skillsByName.set(name, {
143 name,
144 path: skillPath,
145 enabled: true,
146 scope: root.scope,
147 ...(frontmatter.kind === "parsed" && frontmatter.description
148 ? { description: frontmatter.description }
149 : {}),
150 });
151 }
152 }
153
154 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
155});