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

ClaudeSkills.ts

384 lines14.0 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 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 "../../pathExpansion.ts";
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 }
71​
72function parseSkillFrontmatter(contents: string): SkillFrontmatter {
73 const match = FRONTMATTER_PATTERN.exec(contents);
74 if (!match) {
75 return { kind: "missing" };
76 }
77​
78 let parsed: unknown;
79 try {
80 parsed = parseYamlDocument(match[1] ?? "");
81 } catch {
82 return { kind: "malformed" };
83 }
84 if (typeof parsed !== "object" || parsed === null) {
85 return { kind: "malformed" };
86 }
87​
88 const record = parsed as Record<string, unknown>;
89 const description = typeof record.description === "string" ? record.description.trim() : "";
90 return {
91 kind: "parsed",
92 ...(description ? { description } : {}),
93 ...(parseFrontmatterBoolean(record["disable-model-invocation"]) === true
94 ? { userInvocationOnly: true }
95 : {}),
96 ...(parseFrontmatterBoolean(record["user-invocable"]) === false
97 ? { userInvocable: false }
98 : {}),
99 };
101​
102/**
103 * Where an administrator installs the policy file whose settings outrank every
104 * user and project one. Absent on almost every machine, which is why a missing
105 * file is the normal case rather than an error.
106 */
107function claudeManagedSettingsPath(
108 path: Path.Path,
109 platform: NodeJS.Platform,
110 environment: NodeJS.ProcessEnv,
111): string | undefined {
112 if (platform === "darwin") {
113 return "/Library/Application Support/ClaudeCode/managed-settings.json";
114 }
115 if (platform === "win32") {
116 const programData = environment.PROGRAMDATA?.trim();
117 return programData ? path.join(programData, "ClaudeCode", "managed-settings.json") : undefined;
118 }
119 return "/etc/claude-code/managed-settings.json";
121​
122/**
123 * Settings files Claude Code merges for `skillOverrides`, in increasing
124 * precedence: user, project, project-local, then the administrator's managed
125 * policy, which wins outright. When the workspace sits inside a git
126 * repository, the repository root's `settings.local.json` is read too and
127 * outranks the workspace's own local file. Verified against the CLI from a
128 * nested cwd: a root local file switching a skill off wins over a cwd one
129 * switching it on, the root's plain `settings.json` is not consulted, and
130 * without a `.git` above the cwd no root file is read. A skill the user
131 * switched off is reported disabled rather than dropped, so the picker can
132 * grey it out instead of silently losing it.
133 */
134export function skillOverrideSettingsPaths(
135 path: Path.Path,
136 configDirPath: string,
137 cwd: string | undefined,
138 platform: NodeJS.Platform,
139 environment: NodeJS.ProcessEnv,
140 repositoryRoot?: string,
141): ReadonlyArray<string> {
142 const managedPath = claudeManagedSettingsPath(path, platform, environment);
143 const root = repositoryRoot !== undefined && repositoryRoot !== cwd ? repositoryRoot : undefined;
144 return [
145 path.join(configDirPath, "settings.json"),
146 ...(cwd
147 ? [
148 path.join(cwd, ".claude", "settings.json"),
149 path.join(cwd, ".claude", "settings.local.json"),
150 ]
151 : []),
152 ...(root ? [path.join(root, ".claude", "settings.local.json")] : []),
153 ...(managedPath ? [managedPath] : []),
154 ];
156​
157/**
158 * Nearest ancestor of `cwd` (inclusive) holding a `.git` entry, which is the
159 * boundary Claude Code walks up to for project settings. `undefined` outside
160 * a repository.
161 */
162const findRepositoryRoot = Effect.fn("findRepositoryRoot")(function* (
163 cwd: string,
164): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {
165 const fileSystem = yield* FileSystem.FileSystem;
166 const path = yield* Path.Path;
167 let current = path.resolve(cwd);
168 while (true) {
169 const isRoot = yield* fileSystem
170 .exists(path.join(current, ".git"))
171 .pipe(Effect.orElseSucceed(() => false));
172 if (isRoot) {
173 return current;
174 }
175 const parent = path.dirname(current);
176 if (parent === current) {
177 return undefined;
178 }
179 current = parent;
180 }
181});
182​
183/**
184 * The four states Claude Code accepts. The CLI validates the whole map, not
185 * each entry: verified against it, one entry with an unknown value (or a
186 * boolean) makes it drop every override in that file, so this schema does the
187 * same rather than applying the valid siblings the CLI ignores.
188 */
189const SkillOverrideValue = Schema.Literals(["on", "name-only", "user-invocable-only", "off"]);
190​
191// Lenient because these settings files are hand-edited and Claude Code itself
192// tolerates comments and trailing commas in them.
193const SkillOverrideSettings = fromLenientJson(
194 Schema.Struct({
195 skillOverrides: Schema.optional(Schema.Record(Schema.String, SkillOverrideValue)),
196 }),
197);
198const decodeSkillOverrideSettings = Schema.decodeUnknownEffect(SkillOverrideSettings);
199​
200/**
201 * What a `skillOverrides` entry says about one skill. `"user-invocable-only"`
202 * hides it from the agent exactly as `disable-model-invocation` does, so it is
203 * kept apart from a plain on/off decision rather than collapsed into one.
204 */
205type SkillOverride = {
206 readonly enabled: boolean;
207 readonly userInvocationOnly: boolean;
208};
209​
210function parseSkillOverride(value: typeof SkillOverrideValue.Type): SkillOverride {
211 switch (value) {
212 case "off":
213 return { enabled: false, userInvocationOnly: false };
214 case "user-invocable-only":
215 return { enabled: true, userInvocationOnly: true };
216 case "on":
217 case "name-only":
218 return { enabled: true, userInvocationOnly: false };
219 }
221​
222const readSkillOverrides = Effect.fn("readSkillOverrides")(function* (
223 configDirPath: string,
224 cwd: string | undefined,
225 environment: NodeJS.ProcessEnv,
226): Effect.fn.Return<ReadonlyMap<string, SkillOverride>, never, FileSystem.FileSystem | Path.Path> {
227 const fileSystem = yield* FileSystem.FileSystem;
228 const path = yield* Path.Path;
229 const platform = yield* HostProcessPlatform;
230 const overridesByName = new Map<string, SkillOverride>();
231 const repositoryRoot = cwd === undefined ? undefined : yield* findRepositoryRoot(cwd);
232​
233 for (const settingsPath of skillOverrideSettingsPaths(
234 path,
235 configDirPath,
236 cwd,
237 platform,
238 environment,
239 repositoryRoot,
240 )) {
241 const contents = yield* fileSystem
242 .readFileString(settingsPath)
243 .pipe(Effect.orElseSucceed(() => undefined));
244 if (contents === undefined) {
245 continue;
246 }
247​
248 const parsed = yield* decodeSkillOverrideSettings(contents).pipe(
249 Effect.tapError((cause) =>
250 Effect.logDebug("claude settings file is unreadable; ignoring skillOverrides", {
251 path: settingsPath,
252 cause,
253 }),
254 ),
255 Effect.orElseSucceed(() => undefined),
256 );
257 const overrides = parsed?.skillOverrides;
258 if (!overrides) {
259 continue;
260 }
261​
262 for (const [name, value] of Object.entries(overrides)) {
263 overridesByName.set(name, parseSkillOverride(value));
264 }
265 }
266​
267 return overridesByName;
268});
269​
270/**
271 * Resolve the Claude config directory the CLI would use, matching the
272 * precedence the spawned CLI sees: the instance's `homePath` (exported as
273 * `CLAUDE_CONFIG_DIR` by `makeClaudeEnvironment`), then a `CLAUDE_CONFIG_DIR`
274 * already present in the process environment, then `~/.claude`.
275 */
276const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
277 config: Pick<ClaudeSettings, "homePath">,
278 environment: NodeJS.ProcessEnv,
279 cwd?: string,
280): Effect.fn.Return<string, never, Path.Path> {
281 const path = yield* Path.Path;
282 const homePath = config.homePath.trim();
283 if (homePath.length > 0) {
284 return path.resolve(expandHomePath(homePath));
285 }
286 // No tilde expansion here: the spawned CLI receives this env var verbatim
287 // (env vars are never shell-expanded), so a literal `~` must stay literal
288 // for discovery to scan the same directory the runtime would. A relative
289 // value is resolved against the workspace cwd — the subprocess's own cwd —
290 // for the same reason.
291 const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
292 if (environmentConfigDir.length > 0) {
293 return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
294 }
295 return path.join(NodeOS.homedir(), ".claude");
296});
297​
298/**
299 * Enumerate Claude Code skills from the user config dir and the workspace
300 * `.claude/skills`. Discovery is best-effort: unreadable roots and malformed
301 * skill entries are skipped so a broken skill never degrades the provider
302 * snapshot. Roots are listed highest precedence first and the first hit for a
303 * name wins, matching Claude Code: verified against the CLI with the same
304 * skill name in both scopes, the user copy is the one that runs. Reporting the
305 * project copy instead would attach its invocation metadata to a command
306 * Claude Code resolves elsewhere.
307 */
308export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
309 config: Pick<ClaudeSettings, "homePath">,
310 cwd?: string,
311 environment?: NodeJS.ProcessEnv,
312): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
313 const fileSystem = yield* FileSystem.FileSystem;
314 const path = yield* Path.Path;
315 const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);
316 const skillOverrides = yield* readSkillOverrides(configDirPath, cwd, environment ?? process.env);
317​
318 const roots: ReadonlyArray<{ directory: string; scope: ClaudeSkillScope }> = [
319 { directory: path.join(configDirPath, "skills"), scope: "user" },
320 ...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
321 ];
322​
323 const skillsByName = new Map<string, ServerProviderSkill>();
324 for (const root of roots) {
325 const entries = yield* fileSystem
326 .readDirectory(root.directory)
327 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
328​
329 for (const entry of [...entries].sort()) {
330 const skillPath = path.join(root.directory, entry, "SKILL.md");
331 const contents = yield* fileSystem
332 .readFileString(skillPath)
333 .pipe(Effect.orElseSucceed(() => undefined));
334 if (contents === undefined) {
335 continue;
336 }
337​
338 const frontmatter = parseSkillFrontmatter(contents);
339 // Malformed frontmatter means the skill won't load in Claude Code
340 // either — skip it rather than surfacing a broken entry under its
341 // directory name.
342 if (frontmatter.kind === "malformed") {
343 continue;
344 }
345​
346 // Claude Code identifies a skill by its directory, not by the
347 // frontmatter `name`: verified against the CLI, a skill in `probe-alias/`
348 // declaring `name: probe-alias-frontmatter` is published as
349 // `probe-alias`, and only `skillOverrides["probe-alias"]` switches it
350 // off. Keying off the frontmatter name would report a command that does
351 // not exist and miss the override that disables it.
352 const name = entry.trim();
353 if (!name) {
354 continue;
355 }
356​
357 // First root wins, so a later root never displaces a higher-precedence
358 // skill of the same name.
359 if (skillsByName.has(name)) {
360 continue;
361 }
362​
363 const override = skillOverrides.get(name);
364 const userInvocationOnly =
365 (frontmatter.kind === "parsed" && frontmatter.userInvocationOnly === true) ||
366 override?.userInvocationOnly === true;
367 skillsByName.set(name, {
368 name,
369 path: skillPath,
370 enabled: override?.enabled ?? true,
371 scope: root.scope,
372 ...(frontmatter.kind === "parsed" && frontmatter.description
373 ? { description: frontmatter.description }
374 : {}),
375 ...(userInvocationOnly ? { userInvocationOnly: true } : {}),
376 ...(frontmatter.kind === "parsed" && frontmatter.userInvocable === false
377 ? { userInvocable: false }
378 : {}),
379 });
380 }
381 }
382​
383 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
384});