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

ClaudeSkills.ts

340 lines11.5 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 Schema from "effect/Schema";
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import { fromLenientJson } from "@t3tools/shared/schemaJson";
8import { parse as parseYamlDocument } from "yaml";
9​
10import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
11​
12type ClaudeSkillScope = "user" | "project";
13​
14const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
15​
16type SkillFrontmatter =
17 | { readonly kind: "missing" }
18 | { readonly kind: "malformed" }
19 | {
20 readonly kind: "parsed";
21 readonly description?: string;
22 readonly userInvocationOnly?: boolean;
23 readonly userInvocable?: boolean;
24 };
25​
26/**
27 * Claude Code accepts the YAML 1.1 boolean spellings (`yes`/`no`, `on`/`off`,
28 * `1`/`0`), which the 1.2 core schema this parser uses leaves as strings and
29 * numbers.
30 */
31function parseFrontmatterBoolean(value: unknown): boolean | undefined {
32 if (typeof value === "boolean") return value;
33 if (typeof value === "number") {
34 return value === 1 ? true : value === 0 ? false : undefined;
35 }
36 if (typeof value !== "string") return undefined;
37 switch (value.trim().toLowerCase()) {
38 case "true":
39 case "yes":
40 case "on":
41 case "y":
42 return true;
43 case "false":
44 case "no":
45 case "off":
46 case "n":
47 return false;
48 default:
49 return undefined;
50 }
52​
53function parseSkillFrontmatter(contents: string): SkillFrontmatter {
54 const match = FRONTMATTER_PATTERN.exec(contents);
55 if (!match) {
56 return { kind: "missing" };
57 }
58​
59 const frontmatter = match[1] ?? "";
60 let parsed: unknown;
61 try {
62 parsed = parseYamlDocument(frontmatter);
63 } catch {
64 // Claude Code accepts plain scalars containing `: `. Repair only those,
65 // leaving comments and YAML structure for the full-document parser.
66 const repaired = frontmatter.replace(
67 /^([\w-]+:[ \t]*)([^\r\n]*)/gm,
68 (line, prefix: string, value: string) => {
69 const scalar = value.split(/[ \t]+#/)[0] ?? "";
70 if (!/:[ \t]/.test(scalar) || /^(?:["'[\]{}|>&*!#%@`]|[-?:](?:[ \t]|$))/.test(scalar)) {
71 return line;
72 }
73 return `${prefix}${JSON.stringify(scalar)}${value.slice(scalar.length)}`;
74 },
75 );
76 try {
77 parsed = parseYamlDocument(repaired);
78 } catch {
79 return { kind: "malformed" };
80 }
81 }
82 if (typeof parsed !== "object" || parsed === null) {
83 return { kind: "malformed" };
84 }
85​
86 const record = parsed as Record<string, unknown>;
87 const description = typeof record.description === "string" ? record.description.trim() : "";
88 return {
89 kind: "parsed",
90 ...(description ? { description } : {}),
91 ...(parseFrontmatterBoolean(record["disable-model-invocation"]) === true
92 ? { userInvocationOnly: true }
93 : {}),
94 ...(parseFrontmatterBoolean(record["user-invocable"]) === false
95 ? { userInvocable: false }
96 : {}),
97 };
99​
100function claudeManagedSettingsPath(
101 path: Path.Path,
102 platform: NodeJS.Platform,
103 environment: NodeJS.ProcessEnv,
104): string | undefined {
105 if (platform === "darwin") {
106 return "/Library/Application Support/ClaudeCode/managed-settings.json";
107 }
108 if (platform === "win32") {
109 const programData = environment.PROGRAMDATA?.trim();
110 return programData ? path.join(programData, "ClaudeCode", "managed-settings.json") : undefined;
111 }
112 return "/etc/claude-code/managed-settings.json";
114​
115export function skillOverrideSettingsPaths(
116 path: Path.Path,
117 configDirPath: string,
118 cwd: string | undefined,
119 platform: NodeJS.Platform,
120 environment: NodeJS.ProcessEnv,
121 repositoryRoot?: string,
122): ReadonlyArray<string> {
123 const managedPath = claudeManagedSettingsPath(path, platform, environment);
124 const root = repositoryRoot !== undefined && repositoryRoot !== cwd ? repositoryRoot : undefined;
125 return [
126 path.join(configDirPath, "settings.json"),
127 ...(cwd
128 ? [
129 path.join(cwd, ".claude", "settings.json"),
130 path.join(cwd, ".claude", "settings.local.json"),
131 ]
132 : []),
133 ...(root ? [path.join(root, ".claude", "settings.local.json")] : []),
134 ...(managedPath ? [managedPath] : []),
135 ];
137​
138const findRepositoryRoot = Effect.fn("findRepositoryRoot")(function* (
139 cwd: string,
140): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {
141 const fileSystem = yield* FileSystem.FileSystem;
142 const path = yield* Path.Path;
143 let current = path.resolve(cwd);
144 while (true) {
145 const isRoot = yield* fileSystem
146 .exists(path.join(current, ".git"))
147 .pipe(Effect.orElseSucceed(() => false));
148 if (isRoot) {
149 return current;
150 }
151 const parent = path.dirname(current);
152 if (parent === current) {
153 return undefined;
154 }
155 current = parent;
156 }
157});
158​
159/**
160 * The CLI validates the whole map, not each entry: verified against it, one
161 * entry with an unknown value (or a boolean) makes it drop every override in
162 * that file, so this schema does the same rather than applying the valid
163 * siblings the CLI ignores.
164 */
165const SkillOverrideValue = Schema.Literals(["on", "name-only", "user-invocable-only", "off"]);
166​
167// Lenient because these settings files are hand-edited and Claude Code itself
168// tolerates comments and trailing commas in them.
169const SkillOverrideSettings = fromLenientJson(
170 Schema.Struct({
171 skillOverrides: Schema.optional(Schema.Record(Schema.String, SkillOverrideValue)),
172 }),
173);
174const decodeSkillOverrideSettings = Schema.decodeUnknownEffect(SkillOverrideSettings);
175​
176type SkillOverride = {
177 readonly enabled: boolean;
178 readonly userInvocationOnly: boolean;
179};
180​
181function parseSkillOverride(value: typeof SkillOverrideValue.Type): SkillOverride {
182 switch (value) {
183 case "off":
184 return { enabled: false, userInvocationOnly: false };
185 case "user-invocable-only":
186 return { enabled: true, userInvocationOnly: true };
187 case "on":
188 case "name-only":
189 return { enabled: true, userInvocationOnly: false };
190 }
192​
193const readSkillOverrides = Effect.fn("readSkillOverrides")(function* (
194 configDirPath: string,
195 cwd: string | undefined,
196 environment: NodeJS.ProcessEnv,
197): Effect.fn.Return<ReadonlyMap<string, SkillOverride>, never, FileSystem.FileSystem | Path.Path> {
198 const fileSystem = yield* FileSystem.FileSystem;
199 const path = yield* Path.Path;
200 const platform = yield* HostProcess.Platform;
201 const overridesByName = new Map<string, SkillOverride>();
202 const repositoryRoot = cwd === undefined ? undefined : yield* findRepositoryRoot(cwd);
203​
204 for (const settingsPath of skillOverrideSettingsPaths(
205 path,
206 configDirPath,
207 cwd,
208 platform,
209 environment,
210 repositoryRoot,
211 )) {
212 const contents = yield* fileSystem
213 .readFileString(settingsPath)
214 .pipe(Effect.orElseSucceed(() => undefined));
215 if (contents === undefined) {
216 continue;
217 }
218​
219 const parsed = yield* decodeSkillOverrideSettings(contents).pipe(
220 Effect.tapError((cause) =>
221 Effect.logDebug("claude settings file is unreadable; ignoring skillOverrides", {
222 path: settingsPath,
223 cause,
224 }),
225 ),
226 Effect.orElseSucceed(() => undefined),
227 );
228 const overrides = parsed?.skillOverrides;
229 if (!overrides) {
230 continue;
231 }
232​
233 for (const [name, value] of Object.entries(overrides)) {
234 overridesByName.set(name, parseSkillOverride(value));
235 }
236 }
237​
238 return overridesByName;
239});
240​
241const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
242 config: Pick<ClaudeSettings, "homePath">,
243 environment: NodeJS.ProcessEnv,
244 cwd?: string,
245): Effect.fn.Return<string, never, Path.Path> {
246 const path = yield* Path.Path;
247 const home = yield* HostProcess.HomeDirectory;
248 const homePath = config.homePath.trim();
249 if (homePath.length > 0) {
250 return path.resolve(expandHomePath(homePath, home));
251 }
252 // No tilde expansion here: the spawned CLI receives this env var verbatim
253 // (env vars are never shell-expanded), so a literal `~` must stay literal
254 // for discovery to scan the same directory the runtime would. A relative
255 // value is resolved against the workspace cwd — the subprocess's own cwd —
256 // for the same reason.
257 const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
258 if (environmentConfigDir.length > 0) {
259 return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
260 }
261 return path.join(home, ".claude");
262});
263​
264/**
265 * Roots are listed highest precedence first and the first hit for a name wins,
266 * matching Claude Code: verified against the CLI with the same skill name in
267 * both scopes, the user copy is the one that runs.
268 */
269export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
270 config: Pick<ClaudeSettings, "homePath">,
271 cwd?: string,
272 environment?: NodeJS.ProcessEnv,
273): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
274 const fileSystem = yield* FileSystem.FileSystem;
275 const path = yield* Path.Path;
276 const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);
277 const skillOverrides = yield* readSkillOverrides(configDirPath, cwd, environment ?? process.env);
278​
279 const roots: ReadonlyArray<{ directory: string; scope: ClaudeSkillScope }> = [
280 { directory: path.join(configDirPath, "skills"), scope: "user" },
281 ...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
282 ];
283​
284 const skillsByName = new Map<string, ServerProviderSkill>();
285 for (const root of roots) {
286 const entries = yield* fileSystem
287 .readDirectory(root.directory)
288 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
289​
290 for (const entry of [...entries].sort()) {
291 const skillPath = path.join(root.directory, entry, "SKILL.md");
292 const contents = yield* fileSystem
293 .readFileString(skillPath)
294 .pipe(Effect.orElseSucceed(() => undefined));
295 if (contents === undefined) {
296 continue;
297 }
298​
299 const frontmatter = parseSkillFrontmatter(contents);
300 if (frontmatter.kind === "malformed") {
301 continue;
302 }
303​
304 // Claude Code identifies a skill by its directory, not by the
305 // frontmatter `name`: verified against the CLI, a skill in `probe-alias/`
306 // declaring `name: probe-alias-frontmatter` is published as
307 // `probe-alias`, and only `skillOverrides["probe-alias"]` switches it
308 // off. Keying off the frontmatter name would report a command that does
309 // not exist and miss the override that disables it.
310 const name = entry.trim();
311 if (!name) {
312 continue;
313 }
314​
315 if (skillsByName.has(name)) {
316 continue;
317 }
318​
319 const override = skillOverrides.get(name);
320 const userInvocationOnly =
321 (frontmatter.kind === "parsed" && frontmatter.userInvocationOnly === true) ||
322 override?.userInvocationOnly === true;
323 skillsByName.set(name, {
324 name,
325 path: skillPath,
326 enabled: override?.enabled ?? true,
327 scope: root.scope,
328 ...(frontmatter.kind === "parsed" && frontmatter.description
329 ? { description: frontmatter.description }
330 : {}),
331 ...(userInvocationOnly ? { userInvocationOnly: true } : {}),
332 ...(frontmatter.kind === "parsed" && frontmatter.userInvocable === false
333 ? { userInvocable: false }
334 : {}),
335 });
336 }
337 }
338​
339 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
340});