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 Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as HostProcess from "@t3tools/shared/HostProcess";
8import { parseCliArgs } from "@t3tools/shared/cliArgs";
9import { fromLenientJson } from "@t3tools/shared/schemaJson";
10import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens";
11import { parse as parseYamlDocument } from "yaml";
12
13import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
14
15type ClaudeSkillScope = "user" | "project";
16
17type ClaudeSkillRoot = {
18 readonly directory: string;
19 readonly scope: ClaudeSkillScope;
20 readonly prefix?: string;
21};
22
23const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
24
25type SkillFrontmatter =
26 | { readonly kind: "missing" }
27 | { readonly kind: "malformed" }
28 | {
29 readonly kind: "parsed";
30 readonly name?: string;
31 readonly description?: string;
32 readonly userInvocationOnly?: boolean;
33 readonly userInvocable?: boolean;
34 };
35
36/** Claude accepts YAML 1.1 booleans that this YAML 1.2 parser leaves as strings or numbers. */
37function parseFrontmatterBoolean(value: unknown): boolean | undefined {
38 if (typeof value === "boolean") return value;
39 if (typeof value === "number") {
40 return value === 1 ? true : value === 0 ? false : undefined;
41 }
42 if (typeof value !== "string") return undefined;
43 switch (value.trim().toLowerCase()) {
44 case "true":
45 case "yes":
46 case "on":
47 case "y":
48 return true;
49 case "false":
50 case "no":
51 case "off":
52 case "n":
53 return false;
54 default:
55 return undefined;
56 }
57}
58
59function parseSkillFrontmatter(contents: string): SkillFrontmatter {
60 const match = FRONTMATTER_PATTERN.exec(contents);
61 if (!match) {
62 return { kind: "missing" };
63 }
64
65 const frontmatter = match[1] ?? "";
66 let parsed: unknown;
67 try {
68 parsed = parseYamlDocument(frontmatter);
69 } catch {
70 // Repair Claude's accepted ': ' scalars without disturbing comments or YAML structure.
71 const repaired = frontmatter.replace(
72 /^([\w-]+:[ \t]*)([^\r\n]*)/gm,
73 (line, prefix: string, value: string) => {
74 const scalar = value.split(/[ \t]+#/)[0] ?? "";
75 if (!/:[ \t]/.test(scalar) || /^(?:["'[\]{}|>&*!#%@`]|[-?:](?:[ \t]|$))/.test(scalar)) {
76 return line;
77 }
78 return `${prefix}${JSON.stringify(scalar)}${value.slice(scalar.length)}`;
79 },
80 );
81 try {
82 parsed = parseYamlDocument(repaired);
83 } catch {
84 return { kind: "malformed" };
85 }
86 }
87 if (typeof parsed !== "object" || parsed === null) {
88 return { kind: "malformed" };
89 }
90
91 const record = parsed as Record<string, unknown>;
92 const name = typeof record.name === "string" ? record.name.trim() : "";
93 const description = typeof record.description === "string" ? record.description.trim() : "";
94 return {
95 kind: "parsed",
96 ...(name ? { name } : {}),
97 ...(description ? { description } : {}),
98 ...(parseFrontmatterBoolean(record["disable-model-invocation"]) === true
99 ? { userInvocationOnly: true }
100 : {}),
101 ...(parseFrontmatterBoolean(record["user-invocable"]) === false
102 ? { userInvocable: false }
103 : {}),
104 };
105}
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";
120}
121
122function skillOverrideSettingsPaths(
123 path: Path.Path,
124 configDirPath: string,
125 cwd: string | undefined,
126 platform: NodeJS.Platform,
127 environment: NodeJS.ProcessEnv,
128 repositoryRoot?: string,
129): ReadonlyArray<string> {
130 const managedPath = claudeManagedSettingsPath(path, platform, environment);
131 const root = repositoryRoot !== undefined && repositoryRoot !== cwd ? repositoryRoot : undefined;
132 return [
133 path.join(configDirPath, "settings.json"),
134 ...(cwd
135 ? [
136 path.join(cwd, ".claude", "settings.json"),
137 path.join(cwd, ".claude", "settings.local.json"),
138 ]
139 : []),
140 ...(root ? [path.join(root, ".claude", "settings.local.json")] : []),
141 ...(managedPath ? [managedPath] : []),
142 ];
143}
144
145const findRepositoryRoot = Effect.fn("findRepositoryRoot")(function* (
146 cwd: string,
147): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {
148 const fileSystem = yield* FileSystem.FileSystem;
149 const path = yield* Path.Path;
150 let current = path.resolve(cwd);
151 while (true) {
152 const isRoot = yield* fileSystem
153 .exists(path.join(current, ".git"))
154 .pipe(Effect.orElseSucceed(() => false));
155 if (isRoot) {
156 return current;
157 }
158 const parent = path.dirname(current);
159 if (parent === current) {
160 return undefined;
161 }
162 current = parent;
163 }
164});
165
166const findPluginRepositoryRoot = Effect.fn("findPluginRepositoryRoot")(function* (cwd: string) {
167 const fileSystem = yield* FileSystem.FileSystem;
168 const path = yield* Path.Path;
169 const root = yield* findRepositoryRoot(cwd);
170 if (root === undefined) return undefined;
171 const gitFile = yield* fileSystem
172 .readFileString(path.join(root, ".git"))
173 .pipe(Effect.orElseSucceed(() => ""));
174 if (!gitFile.trim().startsWith("gitdir:")) return root;
175 const gitDirectory = path.resolve(root, gitFile.trim().slice(7).trim());
176 const commonFile = yield* fileSystem
177 .readFileString(path.join(gitDirectory, "commondir"))
178 .pipe(Effect.orElseSucceed(() => ""));
179 const worktreeFile = yield* fileSystem
180 .readFileString(path.join(gitDirectory, "gitdir"))
181 .pipe(Effect.orElseSucceed(() => ""));
182 if (!commonFile.trim() || !worktreeFile.trim()) return root;
183 const commonDirectory = path.resolve(gitDirectory, commonFile.trim());
184 const backlinkPath = yield* fileSystem
185 .realPath(path.resolve(gitDirectory, worktreeFile.trim()))
186 .pipe(Effect.orElseSucceed(() => undefined));
187 const worktreeGitPath = yield* fileSystem
188 .realPath(path.join(root, ".git"))
189 .pipe(Effect.orElseSucceed(() => undefined));
190 if (
191 path.dirname(gitDirectory) !== path.join(commonDirectory, "worktrees") ||
192 backlinkPath === undefined ||
193 backlinkPath !== worktreeGitPath
194 ) {
195 return root;
196 }
197 // Claude shares plugin install records across linked worktrees, using their common repository.
198 return path.basename(commonDirectory) === ".git"
199 ? path.dirname(commonDirectory)
200 : commonDirectory;
201});
202
203/**
204 * The CLI validates the whole map, not each entry: verified against it, one
205 * entry with an unknown value (or a boolean) makes it drop every override in
206 * that file, so this schema does the same rather than applying the valid
207 * siblings the CLI ignores.
208 */
209const SkillOverrideValue = Schema.Literals(["on", "name-only", "user-invocable-only", "off"]);
210
211// Lenient because these settings files are hand-edited and Claude Code itself
212// tolerates comments and trailing commas in them.
213const SkillSettings = fromLenientJson(
214 Schema.Struct({
215 skillOverrides: Schema.optional(Schema.Record(Schema.String, SkillOverrideValue)),
216 enabledPlugins: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
217 }),
218);
219const decodeSkillSettings = Schema.decodeUnknownEffect(SkillSettings);
220
221type SkillOverride = {
222 readonly enabled: boolean;
223 readonly userInvocationOnly: boolean;
224};
225
226function parseSkillOverride(value: typeof SkillOverrideValue.Type): SkillOverride {
227 switch (value) {
228 case "off":
229 return { enabled: false, userInvocationOnly: false };
230 case "user-invocable-only":
231 return { enabled: true, userInvocationOnly: true };
232 case "on":
233 case "name-only":
234 return { enabled: true, userInvocationOnly: false };
235 }
236}
237
238const readSkillSettings = Effect.fn("readSkillSettings")(function* (
239 configDirPath: string,
240 cwd: string | undefined,
241 environment: NodeJS.ProcessEnv,
242) {
243 const fileSystem = yield* FileSystem.FileSystem;
244 const path = yield* Path.Path;
245 const platform = yield* HostProcess.Platform;
246 const overridesByName = new Map<string, SkillOverride>();
247 const enabledPlugins = new Map<string, boolean>();
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* decodeSkillSettings(contents).pipe(
266 Effect.tapError((cause) =>
267 Effect.logDebug("claude settings file is unreadable; ignoring skill settings", {
268 path: settingsPath,
269 cause,
270 }),
271 ),
272 Effect.orElseSucceed(() => undefined),
273 );
274 for (const [name, value] of Object.entries(parsed?.skillOverrides ?? {})) {
275 overridesByName.set(name, parseSkillOverride(value));
276 }
277 for (const [key, enabled] of Object.entries(parsed?.enabledPlugins ?? {})) {
278 if (typeof enabled === "boolean") {
279 enabledPlugins.set(key, enabled);
280 } else {
281 // Extended formats replace lower-precedence values without enabling the plugin here.
282 enabledPlugins.delete(key);
283 }
284 }
285 }
286
287 return { skillOverrides: overridesByName, enabledPlugins };
288});
289
290const InstalledPlugins = Schema.fromJsonString(
291 Schema.Struct({ plugins: Schema.Record(Schema.String, Schema.Array(Schema.Unknown)) }),
292);
293const decodeInstalledPlugin = Schema.decodeUnknownOption(
294 Schema.Struct({
295 scope: Schema.Literals(["user", "project", "local", "managed"]),
296 installPath: Schema.NonEmptyString,
297 projectPath: Schema.optional(Schema.NonEmptyString),
298 }),
299);
300const PluginManifest = Schema.fromJsonString(
301 Schema.Struct({
302 name: Schema.optional(Schema.NonEmptyString),
303 skills: Schema.optional(Schema.Union([Schema.String, Schema.Array(Schema.String)])),
304 }),
305);
306
307function isInsideDirectory(path: Path.Path, directory: string, candidate: string): boolean {
308 const relative = path.relative(directory, candidate);
309 return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
310}
311
312const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* (
313 configDirPath: string,
314 cwd: string | undefined,
315 enabledPlugins: ReadonlyMap<string, boolean>,
316 environment: NodeJS.ProcessEnv,
317) {
318 const fileSystem = yield* FileSystem.FileSystem;
319 const path = yield* Path.Path;
320 const home = yield* HostProcess.HomeDirectory;
321 const pluginDirectory = environment.CLAUDE_CODE_PLUGIN_CACHE_DIR;
322 const pluginsPath = pluginDirectory
323 ? path.resolve(cwd ?? ".", expandHomePath(pluginDirectory, home))
324 : path.join(configDirPath, "plugins");
325 const installed = yield* fileSystem
326 .readFileString(path.join(pluginsPath, "installed_plugins.json"))
327 .pipe(
328 Effect.flatMap(Schema.decodeUnknownEffect(InstalledPlugins)),
329 Effect.orElseSucceed(() => undefined),
330 );
331 if (installed === undefined) return [];
332 const roots: Array<ClaudeSkillRoot> = [];
333 // The CLI's process.cwd() resolves symlinks; registry projectPath values remain lexical.
334 const workspace =
335 cwd === undefined
336 ? undefined
337 : yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => path.resolve(cwd)));
338 const repositoryRoot =
339 workspace === undefined ? undefined : yield* findPluginRepositoryRoot(workspace);
340
341 for (const [key, entries] of Object.entries(installed.plugins).sort()) {
342 if (enabledPlugins.get(key) !== true) continue;
343 const applicable = yield* Effect.filter(
344 entries.flatMap((entry) => Option.toArray(decodeInstalledPlugin(entry))),
345 (record) =>
346 Effect.gen(function* () {
347 if (record.scope === "user" || record.scope === "managed") return true;
348 if (record.projectPath === undefined || workspace === undefined) return false;
349 if (path.resolve(record.projectPath) === workspace) return true;
350 return (
351 repositoryRoot !== undefined &&
352 (yield* findPluginRepositoryRoot(record.projectPath)) === repositoryRoot
353 );
354 }),
355 );
356 // The native loader keeps registry order, preferring the first install that exists.
357 const existing = yield* Effect.findFirst(applicable, (record) =>
358 fileSystem
359 .exists(path.resolve(cwd ?? ".", record.installPath))
360 .pipe(Effect.orElseSucceed(() => false)),
361 );
362 const install = Option.getOrElse(existing, () => applicable[0]);
363 if (!install) continue;
364 const scope = install.scope === "user" || install.scope === "managed" ? "user" : "project";
365 const installPath = path.resolve(cwd ?? ".", install.installPath);
366 const manifest = yield* fileSystem
367 .readFileString(path.join(installPath, ".claude-plugin", "plugin.json"))
368 .pipe(
369 Effect.flatMap(Schema.decodeUnknownEffect(PluginManifest)),
370 Effect.orElseSucceed(() => undefined),
371 );
372 const prefix = manifest?.name ?? key.split("@")[0];
373 if (!prefix) continue;
374
375 const defaultDirectory = path.join(installPath, "skills");
376 const hasDefaultDirectory = yield* fileSystem
377 .exists(defaultDirectory)
378 .pipe(Effect.orElseSucceed(() => false));
379 if (hasDefaultDirectory) roots.push({ directory: defaultDirectory, scope, prefix });
380 const declared = manifest?.skills;
381 if (declared === undefined && !hasDefaultDirectory) {
382 const hasRootSkill = yield* fileSystem
383 .exists(path.join(installPath, "SKILL.md"))
384 .pipe(Effect.orElseSucceed(() => false));
385 if (hasRootSkill) roots.push({ directory: installPath, scope, prefix });
386 }
387
388 const canonicalInstallPath = yield* fileSystem
389 .realPath(installPath)
390 .pipe(Effect.orElseSucceed(() => undefined));
391 for (const relative of typeof declared === "string" ? [declared] : (declared ?? [])) {
392 const directory = path.resolve(installPath, relative);
393 if (!isInsideDirectory(path, installPath, directory) || canonicalInstallPath === undefined) {
394 continue;
395 }
396 const canonicalDirectory = yield* fileSystem
397 .realPath(directory)
398 .pipe(Effect.orElseSucceed(() => undefined));
399 // The native loader rejects manifest roots that escape through a symlink, too.
400 if (
401 canonicalDirectory !== undefined &&
402 isInsideDirectory(path, canonicalInstallPath, canonicalDirectory)
403 ) {
404 roots.push({ directory, scope, prefix });
405 }
406 }
407 }
408 return roots;
409});
410
411const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
412 config: Pick<ClaudeSettings, "homePath">,
413 environment: NodeJS.ProcessEnv,
414 cwd?: string,
415): Effect.fn.Return<string, never, Path.Path> {
416 const path = yield* Path.Path;
417 const home = yield* HostProcess.HomeDirectory;
418 const homePath = config.homePath.trim();
419 if (homePath.length > 0) {
420 return path.resolve(expandHomePath(homePath, home));
421 }
422 // Match the spawned CLI: preserve a literal ~ and resolve relative config against workspace cwd.
423 const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
424 if (environmentConfigDir.length > 0) {
425 return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
426 }
427 return path.join(home, ".claude");
428});
429
430/** First name wins, matching Claude Code's precedence of user skills over project skills. */
431export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
432 config: Pick<ClaudeSettings, "homePath"> & Partial<Pick<ClaudeSettings, "launchArgs">>,
433 cwd?: string,
434 environment?: NodeJS.ProcessEnv,
435): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
436 const fileSystem = yield* FileSystem.FileSystem;
437 const path = yield* Path.Path;
438 const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);
439 const { skillOverrides, enabledPlugins } = yield* readSkillSettings(
440 configDirPath,
441 cwd,
442 environment ?? process.env,
443 );
444
445 const additionalDirectory = parseCliArgs(config.launchArgs ?? "").flags["add-dir"];
446 const roots: ReadonlyArray<ClaudeSkillRoot> = [
447 { directory: path.join(configDirPath, "skills"), scope: "user" },
448 ...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
449 ...(additionalDirectory && (cwd || path.isAbsolute(additionalDirectory))
450 ? [
451 {
452 directory: path.join(
453 path.resolve(cwd ?? ".", additionalDirectory),
454 ".claude",
455 "skills",
456 ),
457 scope: "project" as const,
458 },
459 ]
460 : []),
461 ...(yield* discoverPluginSkillRoots(
462 configDirPath,
463 cwd,
464 enabledPlugins,
465 environment ?? process.env,
466 )),
467 ];
468
469 const skillsByName = new Map<string, ServerProviderSkill>();
470 for (const root of roots) {
471 const singleSkill =
472 root.prefix !== undefined &&
473 (yield* fileSystem
474 .exists(path.join(root.directory, "SKILL.md"))
475 .pipe(Effect.orElseSucceed(() => false)));
476 const entries = singleSkill
477 ? [path.basename(root.directory)]
478 : yield* fileSystem
479 .readDirectory(root.directory)
480 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
481
482 for (const entry of [...entries].sort()) {
483 const skillPath = singleSkill
484 ? path.join(root.directory, "SKILL.md")
485 : path.join(root.directory, entry, "SKILL.md");
486 const contents = yield* fileSystem
487 .readFileString(skillPath)
488 .pipe(Effect.orElseSucceed(() => undefined));
489 if (contents === undefined) {
490 continue;
491 }
492
493 const frontmatter = parseSkillFrontmatter(contents);
494 if (frontmatter.kind === "malformed") {
495 continue;
496 }
497
498 const directoryName = entry.trim();
499 if (!directoryName) continue;
500 let name = directoryName;
501 if (root.prefix) {
502 // Native folder skills use their folder; only a single SKILL.md uses its name field.
503 const declaredName = singleSkill && frontmatter.kind === "parsed" ? frontmatter.name : "";
504 const unprefixedName = declaredName?.startsWith(`${root.prefix}:`)
505 ? declaredName.slice(root.prefix.length + 1)
506 : declaredName;
507 name = `${root.prefix}:${(unprefixedName || entry).replace(/[^a-zA-Z0-9_-]/g, "-")}`;
508 // Advertise only exact native names the shared composer grammar can invoke.
509 const [mention] = `$${name}`.matchAll(SKILL_MENTION_PATTERN);
510 if (mention?.[2] !== name) continue;
511 }
512
513 if (skillsByName.has(name)) {
514 continue;
515 }
516
517 const override = root.prefix ? undefined : skillOverrides.get(name);
518 const userInvocationOnly =
519 (frontmatter.kind === "parsed" && frontmatter.userInvocationOnly === true) ||
520 override?.userInvocationOnly === true;
521 skillsByName.set(name, {
522 name,
523 path: skillPath,
524 enabled: override?.enabled ?? true,
525 scope: root.scope,
526 ...(frontmatter.kind === "parsed" && frontmatter.description
527 ? { description: frontmatter.description }
528 : {}),
529 ...(userInvocationOnly ? { userInvocationOnly: true } : {}),
530 ...(frontmatter.kind === "parsed" && frontmatter.userInvocable === false
531 ? { userInvocable: false }
532 : {}),
533 });
534 }
535 }
536
537 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
538});