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