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

ClaudeSkills.ts

148 lines5.5 KB

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