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 { tokenizeCliArgs } 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
122/** Claude Code settings files, lowest precedence first. */
123function claudeSettingsPaths(
124 path: Path.Path,
125 configDirPath: string,
126 cwd: string | undefined,
127 platform: NodeJS.Platform,
128 environment: NodeJS.ProcessEnv,
129 repositoryRoot?: string,
130): ReadonlyArray<string> {
131 const managedPath = claudeManagedSettingsPath(path, platform, environment);
132 const root = repositoryRoot !== undefined && repositoryRoot !== cwd ? repositoryRoot : undefined;
133 return [
134 path.join(configDirPath, "settings.json"),
135 ...(cwd
136 ? [
137 path.join(cwd, ".claude", "settings.json"),
138 path.join(cwd, ".claude", "settings.local.json"),
139 ]
140 : []),
141 ...(root ? [path.join(root, ".claude", "settings.local.json")] : []),
142 ...(managedPath ? [managedPath] : []),
143 ];
144}
145
146const findRepositoryRoot = Effect.fn("findRepositoryRoot")(function* (
147 cwd: string,
148): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {
149 const fileSystem = yield* FileSystem.FileSystem;
150 const path = yield* Path.Path;
151 let current = path.resolve(cwd);
152 while (true) {
153 const isRoot = yield* fileSystem
154 .exists(path.join(current, ".git"))
155 .pipe(Effect.orElseSucceed(() => false));
156 if (isRoot) {
157 return current;
158 }
159 const parent = path.dirname(current);
160 if (parent === current) {
161 return undefined;
162 }
163 current = parent;
164 }
165});
166
167const findPluginRepositoryRoot = Effect.fn("findPluginRepositoryRoot")(function* (cwd: string) {
168 const fileSystem = yield* FileSystem.FileSystem;
169 const path = yield* Path.Path;
170 const root = yield* findRepositoryRoot(cwd);
171 if (root === undefined) return undefined;
172 const gitFile = yield* fileSystem
173 .readFileString(path.join(root, ".git"))
174 .pipe(Effect.orElseSucceed(() => ""));
175 if (!gitFile.trim().startsWith("gitdir:")) return root;
176 const gitDirectory = path.resolve(root, gitFile.trim().slice(7).trim());
177 const commonFile = yield* fileSystem
178 .readFileString(path.join(gitDirectory, "commondir"))
179 .pipe(Effect.orElseSucceed(() => ""));
180 const worktreeFile = yield* fileSystem
181 .readFileString(path.join(gitDirectory, "gitdir"))
182 .pipe(Effect.orElseSucceed(() => ""));
183 if (!commonFile.trim() || !worktreeFile.trim()) return root;
184 const commonDirectory = path.resolve(gitDirectory, commonFile.trim());
185 const backlinkPath = yield* fileSystem
186 .realPath(path.resolve(gitDirectory, worktreeFile.trim()))
187 .pipe(Effect.orElseSucceed(() => undefined));
188 const worktreeGitPath = yield* fileSystem
189 .realPath(path.join(root, ".git"))
190 .pipe(Effect.orElseSucceed(() => undefined));
191 if (
192 path.dirname(gitDirectory) !== path.join(commonDirectory, "worktrees") ||
193 backlinkPath === undefined ||
194 backlinkPath !== worktreeGitPath
195 ) {
196 return root;
197 }
198 // Claude shares plugin install records across linked worktrees, using their common repository.
199 return path.basename(commonDirectory) === ".git"
200 ? path.dirname(commonDirectory)
201 : commonDirectory;
202});
203
204/**
205 * The CLI validates the whole map, not each entry: verified against it, one
206 * entry with an unknown value (or a boolean) makes it drop every override in
207 * that file, so this schema does the same rather than applying the valid
208 * siblings the CLI ignores.
209 */
210const SkillOverrideValue = Schema.Literals(["on", "name-only", "user-invocable-only", "off"]);
211
212// Lenient because these settings files are hand-edited and Claude Code itself
213// tolerates comments and trailing commas in them.
214const SkillSettings = fromLenientJson(
215 Schema.Struct({
216 skillOverrides: Schema.optional(Schema.Record(Schema.String, SkillOverrideValue)),
217 enabledPlugins: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
218 }),
219);
220const decodeSkillSettings = Schema.decodeUnknownEffect(SkillSettings);
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 readSkillSettings = Effect.fn("readSkillSettings")(function* (
240 configDirPath: string,
241 cwd: string | undefined,
242 environment: NodeJS.ProcessEnv,
243) {
244 const fileSystem = yield* FileSystem.FileSystem;
245 const path = yield* Path.Path;
246 const platform = yield* HostProcess.Platform;
247 const overridesByName = new Map<string, SkillOverride>();
248 const enabledPlugins = new Map<string, boolean>();
249 const repositoryRoot = cwd === undefined ? undefined : yield* findRepositoryRoot(cwd);
250
251 for (const settingsPath of claudeSettingsPaths(
252 path,
253 configDirPath,
254 cwd,
255 platform,
256 environment,
257 repositoryRoot,
258 )) {
259 const contents = yield* fileSystem
260 .readFileString(settingsPath)
261 .pipe(Effect.orElseSucceed(() => undefined));
262 if (contents === undefined) {
263 continue;
264 }
265
266 const parsed = yield* decodeSkillSettings(contents).pipe(
267 Effect.tapError((cause) =>
268 Effect.logDebug("claude settings file is unreadable; ignoring skill settings", {
269 path: settingsPath,
270 cause,
271 }),
272 ),
273 Effect.orElseSucceed(() => undefined),
274 );
275 for (const [name, value] of Object.entries(parsed?.skillOverrides ?? {})) {
276 overridesByName.set(name, parseSkillOverride(value));
277 }
278 for (const [key, enabled] of Object.entries(parsed?.enabledPlugins ?? {})) {
279 if (typeof enabled === "boolean") {
280 enabledPlugins.set(key, enabled);
281 } else {
282 // Extended formats replace lower-precedence values without enabling the plugin here.
283 enabledPlugins.delete(key);
284 }
285 }
286 }
287
288 return { skillOverrides: overridesByName, enabledPlugins };
289});
290
291const InstalledPlugins = Schema.fromJsonString(
292 Schema.Struct({ plugins: Schema.Record(Schema.String, Schema.Array(Schema.Unknown)) }),
293);
294const decodeInstalledPlugin = Schema.decodeUnknownOption(
295 Schema.Struct({
296 scope: Schema.Literals(["user", "project", "local", "managed"]),
297 installPath: Schema.NonEmptyString,
298 projectPath: Schema.optional(Schema.NonEmptyString),
299 }),
300);
301const PluginManifest = Schema.fromJsonString(
302 Schema.Struct({
303 name: Schema.optional(Schema.NonEmptyString),
304 skills: Schema.optional(Schema.Union([Schema.String, Schema.Array(Schema.String)])),
305 }),
306);
307
308function isInsideDirectory(path: Path.Path, directory: string, candidate: string): boolean {
309 const relative = path.relative(directory, candidate);
310 return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
311}
312
313const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* (
314 configDirPath: string,
315 cwd: string | undefined,
316 enabledPlugins: ReadonlyMap<string, boolean>,
317 environment: NodeJS.ProcessEnv,
318) {
319 const fileSystem = yield* FileSystem.FileSystem;
320 const path = yield* Path.Path;
321 const home = yield* HostProcess.HomeDirectory;
322 const pluginDirectory = environment.CLAUDE_CODE_PLUGIN_CACHE_DIR;
323 const pluginsPath = pluginDirectory
324 ? path.resolve(cwd ?? ".", expandHomePath(pluginDirectory, home))
325 : path.join(configDirPath, "plugins");
326 const installed = yield* fileSystem
327 .readFileString(path.join(pluginsPath, "installed_plugins.json"))
328 .pipe(
329 Effect.flatMap(Schema.decodeUnknownEffect(InstalledPlugins)),
330 Effect.orElseSucceed(() => undefined),
331 );
332 if (installed === undefined) return [];
333 const roots: Array<ClaudeSkillRoot> = [];
334 // The CLI's process.cwd() resolves symlinks; registry projectPath values remain lexical.
335 const workspace =
336 cwd === undefined
337 ? undefined
338 : yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => path.resolve(cwd)));
339 const repositoryRoot =
340 workspace === undefined ? undefined : yield* findPluginRepositoryRoot(workspace);
341
342 for (const [key, entries] of Object.entries(installed.plugins).sort()) {
343 if (enabledPlugins.get(key) !== true) continue;
344 const applicable = yield* Effect.filter(
345 entries.flatMap((entry) => Option.toArray(decodeInstalledPlugin(entry))),
346 (record) =>
347 Effect.gen(function* () {
348 if (record.scope === "user" || record.scope === "managed") return true;
349 if (record.projectPath === undefined || workspace === undefined) return false;
350 if (path.resolve(record.projectPath) === workspace) return true;
351 return (
352 repositoryRoot !== undefined &&
353 (yield* findPluginRepositoryRoot(record.projectPath)) === repositoryRoot
354 );
355 }),
356 );
357 // The native loader keeps registry order, preferring the first install that exists.
358 const existing = yield* Effect.findFirst(applicable, (record) =>
359 fileSystem
360 .exists(path.resolve(cwd ?? ".", record.installPath))
361 .pipe(Effect.orElseSucceed(() => false)),
362 );
363 const install = Option.getOrElse(existing, () => applicable[0]);
364 if (!install) continue;
365 const scope = install.scope === "user" || install.scope === "managed" ? "user" : "project";
366 const installPath = path.resolve(cwd ?? ".", install.installPath);
367 const manifest = yield* fileSystem
368 .readFileString(path.join(installPath, ".claude-plugin", "plugin.json"))
369 .pipe(
370 Effect.flatMap(Schema.decodeUnknownEffect(PluginManifest)),
371 Effect.orElseSucceed(() => undefined),
372 );
373 const prefix = manifest?.name ?? key.split("@")[0];
374 if (!prefix) continue;
375
376 const defaultDirectory = path.join(installPath, "skills");
377 const hasDefaultDirectory = yield* fileSystem
378 .exists(defaultDirectory)
379 .pipe(Effect.orElseSucceed(() => false));
380 if (hasDefaultDirectory) roots.push({ directory: defaultDirectory, scope, prefix });
381 const declared = manifest?.skills;
382 if (declared === undefined && !hasDefaultDirectory) {
383 const hasRootSkill = yield* fileSystem
384 .exists(path.join(installPath, "SKILL.md"))
385 .pipe(Effect.orElseSucceed(() => false));
386 if (hasRootSkill) roots.push({ directory: installPath, scope, prefix });
387 }
388
389 const canonicalInstallPath = yield* fileSystem
390 .realPath(installPath)
391 .pipe(Effect.orElseSucceed(() => undefined));
392 for (const relative of typeof declared === "string" ? [declared] : (declared ?? [])) {
393 const directory = path.resolve(installPath, relative);
394 if (!isInsideDirectory(path, installPath, directory) || canonicalInstallPath === undefined) {
395 continue;
396 }
397 const canonicalDirectory = yield* fileSystem
398 .realPath(directory)
399 .pipe(Effect.orElseSucceed(() => undefined));
400 // The native loader rejects manifest roots that escape through a symlink, too.
401 if (
402 canonicalDirectory !== undefined &&
403 isInsideDirectory(path, canonicalInstallPath, canonicalDirectory)
404 ) {
405 roots.push({ directory, scope, prefix });
406 }
407 }
408 }
409 return roots;
410});
411
412const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
413 config: Pick<ClaudeSettings, "homePath">,
414 environment: NodeJS.ProcessEnv,
415 cwd?: string,
416): Effect.fn.Return<string, never, Path.Path> {
417 const path = yield* Path.Path;
418 const home = yield* HostProcess.HomeDirectory;
419 const homePath = config.homePath.trim();
420 if (homePath.length > 0) {
421 return path.resolve(expandHomePath(homePath, home));
422 }
423 // Match the spawned CLI: preserve a literal ~ and resolve relative config against workspace cwd.
424 const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
425 if (environmentConfigDir.length > 0) {
426 return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
427 }
428 return path.join(home, ".claude");
429});
430
431const SettingsBaseUrl = fromLenientJson(
432 Schema.Struct({
433 env: Schema.optional(Schema.Struct({ ANTHROPIC_BASE_URL: Schema.optional(Schema.String) })),
434 }),
435);
436const decodeSettingsBaseUrl = Schema.decodeUnknownEffect(SettingsBaseUrl);
437
438/** ANTHROPIC_BASE_URL from Claude's settings `env`, which Claude Code applies over the process env. */
439export const readClaudeSettingsBaseUrl = Effect.fn("readClaudeSettingsBaseUrl")(function* (
440 config: Pick<ClaudeSettings, "homePath">,
441 cwd: string | undefined,
442 environment: NodeJS.ProcessEnv,
443): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {
444 const fileSystem = yield* FileSystem.FileSystem;
445 const path = yield* Path.Path;
446 const platform = yield* HostProcess.Platform;
447 const configDirPath = yield* resolveClaudeConfigDirPath(config, environment, cwd);
448 let baseUrl: string | undefined;
449 for (const settingsPath of claudeSettingsPaths(
450 path,
451 configDirPath,
452 undefined,
453 platform,
454 environment,
455 )) {
456 const contents = yield* fileSystem
457 .readFileString(settingsPath)
458 .pipe(Effect.orElseSucceed(() => undefined));
459 if (contents === undefined) continue;
460 const parsed = yield* decodeSettingsBaseUrl(contents).pipe(
461 Effect.orElseSucceed(() => undefined),
462 );
463 baseUrl = parsed?.env?.ANTHROPIC_BASE_URL ?? baseUrl;
464 }
465 return baseUrl;
466});
467
468// Claude's --add-dir is repeatable and variadic; parseCliArgs keeps only one value.
469export function claudeLaunchArgDirectories(launchArgs?: string): ReadonlyArray<string> {
470 const directories: string[] = [];
471 let collecting = false;
472 for (const token of tokenizeCliArgs(launchArgs)) {
473 if (token === "--") break;
474 if (token === "--add-dir") {
475 collecting = true;
476 } else if (token.startsWith("--add-dir=")) {
477 directories.push(token.slice("--add-dir=".length));
478 collecting = false;
479 } else if (token.startsWith("-")) {
480 collecting = false;
481 } else if (collecting) {
482 directories.push(token);
483 }
484 }
485 return directories;
486}
487
488/** First name wins, matching Claude Code's precedence of user skills over project skills. */
489export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
490 config: Pick<ClaudeSettings, "homePath"> & Partial<Pick<ClaudeSettings, "launchArgs">>,
491 cwd?: string,
492 environment?: NodeJS.ProcessEnv,
493): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
494 const fileSystem = yield* FileSystem.FileSystem;
495 const path = yield* Path.Path;
496 const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);
497 const { skillOverrides, enabledPlugins } = yield* readSkillSettings(
498 configDirPath,
499 cwd,
500 environment ?? process.env,
501 );
502
503 const roots: ReadonlyArray<ClaudeSkillRoot> = [
504 { directory: path.join(configDirPath, "skills"), scope: "user" },
505 ...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
506 ...claudeLaunchArgDirectories(config.launchArgs)
507 .filter((directory) => directory && (cwd || path.isAbsolute(directory)))
508 .map((directory) => ({
509 directory: path.join(path.resolve(cwd ?? ".", directory), ".claude", "skills"),
510 scope: "project" as const,
511 })),
512 ...(yield* discoverPluginSkillRoots(
513 configDirPath,
514 cwd,
515 enabledPlugins,
516 environment ?? process.env,
517 )),
518 ];
519
520 const skillsByName = new Map<string, ServerProviderSkill>();
521 for (const root of roots) {
522 const singleSkill =
523 root.prefix !== undefined &&
524 (yield* fileSystem
525 .exists(path.join(root.directory, "SKILL.md"))
526 .pipe(Effect.orElseSucceed(() => false)));
527 const entries = singleSkill
528 ? [path.basename(root.directory)]
529 : yield* fileSystem
530 .readDirectory(root.directory)
531 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
532
533 for (const entry of [...entries].sort()) {
534 const skillPath = singleSkill
535 ? path.join(root.directory, "SKILL.md")
536 : path.join(root.directory, entry, "SKILL.md");
537 const contents = yield* fileSystem
538 .readFileString(skillPath)
539 .pipe(Effect.orElseSucceed(() => undefined));
540 if (contents === undefined) {
541 continue;
542 }
543
544 const frontmatter = parseSkillFrontmatter(contents);
545 if (frontmatter.kind === "malformed") {
546 continue;
547 }
548
549 const directoryName = entry.trim();
550 if (!directoryName) continue;
551 let name = directoryName;
552 if (root.prefix) {
553 // Native folder skills use their folder; only a single SKILL.md uses its name field.
554 const declaredName = singleSkill && frontmatter.kind === "parsed" ? frontmatter.name : "";
555 const unprefixedName = declaredName?.startsWith(`${root.prefix}:`)
556 ? declaredName.slice(root.prefix.length + 1)
557 : declaredName;
558 name = `${root.prefix}:${(unprefixedName || entry).replace(/[^a-zA-Z0-9_-]/g, "-")}`;
559 // Advertise only exact native names the shared composer grammar can invoke.
560 const [mention] = `$${name}`.matchAll(SKILL_MENTION_PATTERN);
561 if (mention?.[2] !== name) continue;
562 }
563
564 if (skillsByName.has(name)) {
565 continue;
566 }
567
568 const override = root.prefix ? undefined : skillOverrides.get(name);
569 const userInvocationOnly =
570 (frontmatter.kind === "parsed" && frontmatter.userInvocationOnly === true) ||
571 override?.userInvocationOnly === true;
572 skillsByName.set(name, {
573 name,
574 path: skillPath,
575 enabled: override?.enabled ?? true,
576 scope: root.scope,
577 ...(frontmatter.kind === "parsed" && frontmatter.description
578 ? { description: frontmatter.description }
579 : {}),
580 ...(userInvocationOnly ? { userInvocationOnly: true } : {}),
581 ...(frontmatter.kind === "parsed" && frontmatter.userInvocable === false
582 ? { userInvocable: false }
583 : {}),
584 });
585 }
586 }
587
588 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
589});