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) and
5 * `<cwd>/.claude/skills` (project scope), one directory per skill with a
6 * `SKILL.md` carrying YAML frontmatter. The user root wins on name collisions,
7 * matching the CLI. `.agents/skills` is a Codex location: verified against the
8 * CLI, a skill that lives only there is answered with `Unknown command`, so it
9 * is not scanned here.
10 * The Agent SDK init handshake surfaces skills only as slash commands without
11 * their filesystem paths, so the provider snapshot scans the same locations
12 * directly, mirroring how the Codex app-server reports its skills.
13 *
14 * @module provider/Drivers/ClaudeSkills
15 */
16import * as NodeOS from "node:os";
17
18import type { ClaudeSettings, ServerProviderSkill } from "@t3tools/contracts";
19import * as Effect from "effect/Effect";
20import * as FileSystem from "effect/FileSystem";
21import * as Path from "effect/Path";
22import * as Schema from "effect/Schema";
23import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
24import { fromLenientJson } from "@t3tools/shared/schemaJson";
25import { parse as parseYamlDocument } from "yaml";
26
27import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
28
29type ClaudeSkillScope = "user" | "project";
30
31const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
32
33type SkillFrontmatter =
34 | { readonly kind: "missing" }
35 | { readonly kind: "malformed" }
36 | {
37 readonly kind: "parsed";
38 readonly description?: string;
39 readonly userInvocationOnly?: boolean;
40 readonly userInvocable?: boolean;
41 };
42
43/**
44 * Claude Code accepts the YAML 1.1 boolean spellings (`yes`/`no`, `on`/`off`,
45 * `1`/`0`), which the 1.2 core schema this parser uses leaves as strings and
46 * numbers. Verified against the CLI: a skill carrying `user-invocable: no` is
47 * absent from its published slash commands, so a strict `=== false` here would
48 * offer a command the CLI rejects.
49 */
50function parseFrontmatterBoolean(value: unknown): boolean | undefined {
51 if (typeof value === "boolean") return value;
52 if (typeof value === "number") {
53 return value === 1 ? true : value === 0 ? false : undefined;
54 }
55 if (typeof value !== "string") return undefined;
56 switch (value.trim().toLowerCase()) {
57 case "true":
58 case "yes":
59 case "on":
60 case "y":
61 return true;
62 case "false":
63 case "no":
64 case "off":
65 case "n":
66 return false;
67 default:
68 return undefined;
69 }
70}
71
72function parseSkillFrontmatter(contents: string): SkillFrontmatter {
73 const match = FRONTMATTER_PATTERN.exec(contents);
74 if (!match) {
75 return { kind: "missing" };
76 }
77
78 const frontmatter = match[1] ?? "";
79 let parsed: unknown;
80 try {
81 parsed = parseYamlDocument(frontmatter);
82 } catch {
83 // Claude Code accepts plain scalars containing `: `. Repair only those,
84 // leaving comments and YAML structure for the full-document parser.
85 const repaired = frontmatter.replace(
86 /^([\w-]+:[ \t]*)([^\r\n]*)/gm,
87 (line, prefix: string, value: string) => {
88 const scalar = value.split(/[ \t]+#/)[0] ?? "";
89 if (!/:[ \t]/.test(scalar) || /^(?:["'[\]{}|>&*!#%@`]|[-?:](?:[ \t]|$))/.test(scalar)) {
90 return line;
91 }
92 return `${prefix}${JSON.stringify(scalar)}${value.slice(scalar.length)}`;
93 },
94 );
95 try {
96 parsed = parseYamlDocument(repaired);
97 } catch {
98 return { kind: "malformed" };
99 }
100 }
101 if (typeof parsed !== "object" || parsed === null) {
102 return { kind: "malformed" };
103 }
104
105 const record = parsed as Record<string, unknown>;
106 const description = typeof record.description === "string" ? record.description.trim() : "";
107 return {
108 kind: "parsed",
109 ...(description ? { description } : {}),
110 ...(parseFrontmatterBoolean(record["disable-model-invocation"]) === true
111 ? { userInvocationOnly: true }
112 : {}),
113 ...(parseFrontmatterBoolean(record["user-invocable"]) === false
114 ? { userInvocable: false }
115 : {}),
116 };
117}
118
119/**
120 * Where an administrator installs the policy file whose settings outrank every
121 * user and project one. Absent on almost every machine, which is why a missing
122 * file is the normal case rather than an error.
123 */
124function claudeManagedSettingsPath(
125 path: Path.Path,
126 platform: NodeJS.Platform,
127 environment: NodeJS.ProcessEnv,
128): string | undefined {
129 if (platform === "darwin") {
130 return "/Library/Application Support/ClaudeCode/managed-settings.json";
131 }
132 if (platform === "win32") {
133 const programData = environment.PROGRAMDATA?.trim();
134 return programData ? path.join(programData, "ClaudeCode", "managed-settings.json") : undefined;
135 }
136 return "/etc/claude-code/managed-settings.json";
137}
138
139/**
140 * Settings files Claude Code merges for `skillOverrides`, in increasing
141 * precedence: user, project, project-local, then the administrator's managed
142 * policy, which wins outright. When the workspace sits inside a git
143 * repository, the repository root's `settings.local.json` is read too and
144 * outranks the workspace's own local file. Verified against the CLI from a
145 * nested cwd: a root local file switching a skill off wins over a cwd one
146 * switching it on, the root's plain `settings.json` is not consulted, and
147 * without a `.git` above the cwd no root file is read. A skill the user
148 * switched off is reported disabled rather than dropped, so the picker can
149 * grey it out instead of silently losing it.
150 */
151export function skillOverrideSettingsPaths(
152 path: Path.Path,
153 configDirPath: string,
154 cwd: string | undefined,
155 platform: NodeJS.Platform,
156 environment: NodeJS.ProcessEnv,
157 repositoryRoot?: string,
158): ReadonlyArray<string> {
159 const managedPath = claudeManagedSettingsPath(path, platform, environment);
160 const root = repositoryRoot !== undefined && repositoryRoot !== cwd ? repositoryRoot : undefined;
161 return [
162 path.join(configDirPath, "settings.json"),
163 ...(cwd
164 ? [
165 path.join(cwd, ".claude", "settings.json"),
166 path.join(cwd, ".claude", "settings.local.json"),
167 ]
168 : []),
169 ...(root ? [path.join(root, ".claude", "settings.local.json")] : []),
170 ...(managedPath ? [managedPath] : []),
171 ];
172}
173
174/**
175 * Nearest ancestor of `cwd` (inclusive) holding a `.git` entry, which is the
176 * boundary Claude Code walks up to for project settings. `undefined` outside
177 * a repository.
178 */
179const findRepositoryRoot = Effect.fn("findRepositoryRoot")(function* (
180 cwd: string,
181): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {
182 const fileSystem = yield* FileSystem.FileSystem;
183 const path = yield* Path.Path;
184 let current = path.resolve(cwd);
185 while (true) {
186 const isRoot = yield* fileSystem
187 .exists(path.join(current, ".git"))
188 .pipe(Effect.orElseSucceed(() => false));
189 if (isRoot) {
190 return current;
191 }
192 const parent = path.dirname(current);
193 if (parent === current) {
194 return undefined;
195 }
196 current = parent;
197 }
198});
199
200/**
201 * The four states Claude Code accepts. The CLI validates the whole map, not
202 * each entry: verified against it, one entry with an unknown value (or a
203 * boolean) makes it drop every override in that file, so this schema does the
204 * same rather than applying the valid siblings the CLI ignores.
205 */
206const SkillOverrideValue = Schema.Literals(["on", "name-only", "user-invocable-only", "off"]);
207
208// Lenient because these settings files are hand-edited and Claude Code itself
209// tolerates comments and trailing commas in them.
210const SkillOverrideSettings = fromLenientJson(
211 Schema.Struct({
212 skillOverrides: Schema.optional(Schema.Record(Schema.String, SkillOverrideValue)),
213 }),
214);
215const decodeSkillOverrideSettings = Schema.decodeUnknownEffect(SkillOverrideSettings);
216
217/**
218 * What a `skillOverrides` entry says about one skill. `"user-invocable-only"`
219 * hides it from the agent exactly as `disable-model-invocation` does, so it is
220 * kept apart from a plain on/off decision rather than collapsed into one.
221 */
222type SkillOverride = {
223 readonly enabled: boolean;
224 readonly userInvocationOnly: boolean;
225};
226
227function parseSkillOverride(value: typeof SkillOverrideValue.Type): SkillOverride {
228 switch (value) {
229 case "off":
230 return { enabled: false, userInvocationOnly: false };
231 case "user-invocable-only":
232 return { enabled: true, userInvocationOnly: true };
233 case "on":
234 case "name-only":
235 return { enabled: true, userInvocationOnly: false };
236 }
237}
238
239const readSkillOverrides = Effect.fn("readSkillOverrides")(function* (
240 configDirPath: string,
241 cwd: string | undefined,
242 environment: NodeJS.ProcessEnv,
243): Effect.fn.Return<ReadonlyMap<string, SkillOverride>, never, FileSystem.FileSystem | Path.Path> {
244 const fileSystem = yield* FileSystem.FileSystem;
245 const path = yield* Path.Path;
246 const platform = yield* HostProcessPlatform;
247 const overridesByName = new Map<string, SkillOverride>();
248 const repositoryRoot = cwd === undefined ? undefined : yield* findRepositoryRoot(cwd);
249
250 for (const settingsPath of skillOverrideSettingsPaths(
251 path,
252 configDirPath,
253 cwd,
254 platform,
255 environment,
256 repositoryRoot,
257 )) {
258 const contents = yield* fileSystem
259 .readFileString(settingsPath)
260 .pipe(Effect.orElseSucceed(() => undefined));
261 if (contents === undefined) {
262 continue;
263 }
264
265 const parsed = yield* decodeSkillOverrideSettings(contents).pipe(
266 Effect.tapError((cause) =>
267 Effect.logDebug("claude settings file is unreadable; ignoring skillOverrides", {
268 path: settingsPath,
269 cause,
270 }),
271 ),
272 Effect.orElseSucceed(() => undefined),
273 );
274 const overrides = parsed?.skillOverrides;
275 if (!overrides) {
276 continue;
277 }
278
279 for (const [name, value] of Object.entries(overrides)) {
280 overridesByName.set(name, parseSkillOverride(value));
281 }
282 }
283
284 return overridesByName;
285});
286
287/**
288 * Resolve the Claude config directory the CLI would use, matching the
289 * precedence the spawned CLI sees: the instance's `homePath` (exported as
290 * `CLAUDE_CONFIG_DIR` by `makeClaudeEnvironment`), then a `CLAUDE_CONFIG_DIR`
291 * already present in the process environment, then `~/.claude`.
292 */
293const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
294 config: Pick<ClaudeSettings, "homePath">,
295 environment: NodeJS.ProcessEnv,
296 cwd?: string,
297): Effect.fn.Return<string, never, Path.Path> {
298 const path = yield* Path.Path;
299 const homePath = config.homePath.trim();
300 if (homePath.length > 0) {
301 return path.resolve(expandHomePath(homePath));
302 }
303 // No tilde expansion here: the spawned CLI receives this env var verbatim
304 // (env vars are never shell-expanded), so a literal `~` must stay literal
305 // for discovery to scan the same directory the runtime would. A relative
306 // value is resolved against the workspace cwd — the subprocess's own cwd —
307 // for the same reason.
308 const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
309 if (environmentConfigDir.length > 0) {
310 return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
311 }
312 return path.join(NodeOS.homedir(), ".claude");
313});
314
315/**
316 * Enumerate Claude Code skills from the user config dir and the workspace
317 * `.claude/skills`. Discovery is best-effort: unreadable roots and malformed
318 * skill entries are skipped so a broken skill never degrades the provider
319 * snapshot. Roots are listed highest precedence first and the first hit for a
320 * name wins, matching Claude Code: verified against the CLI with the same
321 * skill name in both scopes, the user copy is the one that runs. Reporting the
322 * project copy instead would attach its invocation metadata to a command
323 * Claude Code resolves elsewhere.
324 */
325export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
326 config: Pick<ClaudeSettings, "homePath">,
327 cwd?: string,
328 environment?: NodeJS.ProcessEnv,
329): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
330 const fileSystem = yield* FileSystem.FileSystem;
331 const path = yield* Path.Path;
332 const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);
333 const skillOverrides = yield* readSkillOverrides(configDirPath, cwd, environment ?? process.env);
334
335 const roots: ReadonlyArray<{ directory: string; scope: ClaudeSkillScope }> = [
336 { directory: path.join(configDirPath, "skills"), scope: "user" },
337 ...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
338 ];
339
340 const skillsByName = new Map<string, ServerProviderSkill>();
341 for (const root of roots) {
342 const entries = yield* fileSystem
343 .readDirectory(root.directory)
344 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
345
346 for (const entry of [...entries].sort()) {
347 const skillPath = path.join(root.directory, entry, "SKILL.md");
348 const contents = yield* fileSystem
349 .readFileString(skillPath)
350 .pipe(Effect.orElseSucceed(() => undefined));
351 if (contents === undefined) {
352 continue;
353 }
354
355 const frontmatter = parseSkillFrontmatter(contents);
356 // Malformed frontmatter means the skill won't load in Claude Code
357 // either — skip it rather than surfacing a broken entry under its
358 // directory name.
359 if (frontmatter.kind === "malformed") {
360 continue;
361 }
362
363 // Claude Code identifies a skill by its directory, not by the
364 // frontmatter `name`: verified against the CLI, a skill in `probe-alias/`
365 // declaring `name: probe-alias-frontmatter` is published as
366 // `probe-alias`, and only `skillOverrides["probe-alias"]` switches it
367 // off. Keying off the frontmatter name would report a command that does
368 // not exist and miss the override that disables it.
369 const name = entry.trim();
370 if (!name) {
371 continue;
372 }
373
374 // First root wins, so a later root never displaces a higher-precedence
375 // skill of the same name.
376 if (skillsByName.has(name)) {
377 continue;
378 }
379
380 const override = skillOverrides.get(name);
381 const userInvocationOnly =
382 (frontmatter.kind === "parsed" && frontmatter.userInvocationOnly === true) ||
383 override?.userInvocationOnly === true;
384 skillsByName.set(name, {
385 name,
386 path: skillPath,
387 enabled: override?.enabled ?? true,
388 scope: root.scope,
389 ...(frontmatter.kind === "parsed" && frontmatter.description
390 ? { description: frontmatter.description }
391 : {}),
392 ...(userInvocationOnly ? { userInvocationOnly: true } : {}),
393 ...(frontmatter.kind === "parsed" && frontmatter.userInvocable === false
394 ? { userInvocable: false }
395 : {}),
396 });
397 }
398 }
399
400 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
401});