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 SettingsEnv = Schema.Struct({
432 ANTHROPIC_BASE_URL: Schema.optional(Schema.String),
433 CLAUDE_CODE_ENTRYPOINT: Schema.optional(Schema.String),
434});
435const decodeSettingsEnv = Schema.decodeUnknownEffect(
436 fromLenientJson(Schema.Struct({ env: Schema.optional(SettingsEnv) })),
437);
438
439/** The `env` values T3 Code reads from Claude's user and managed settings; later files win. */
440export const readClaudeSettingsEnv = Effect.fn("readClaudeSettingsEnv")(function* (
441 config: Pick<ClaudeSettings, "homePath">,
442 cwd: string | undefined,
443 environment: NodeJS.ProcessEnv,
444): Effect.fn.Return<typeof SettingsEnv.Type, never, FileSystem.FileSystem | Path.Path> {
445 const fileSystem = yield* FileSystem.FileSystem;
446 const path = yield* Path.Path;
447 const platform = yield* HostProcess.Platform;
448 const configDirPath = yield* resolveClaudeConfigDirPath(config, environment, cwd);
449 const settingsEnv: typeof SettingsEnv.Type = {};
450 for (const settingsPath of claudeSettingsPaths(
451 path,
452 configDirPath,
453 undefined,
454 platform,
455 environment,
456 )) {
457 const contents = yield* fileSystem
458 .readFileString(settingsPath)
459 .pipe(Effect.orElseSucceed(() => undefined));
460 if (contents === undefined) continue;
461 const parsed = yield* decodeSettingsEnv(contents).pipe(Effect.orElseSucceed(() => undefined));
462 Object.assign(settingsEnv, parsed?.env);
463 }
464 return settingsEnv;
465});
466
467// Claude's --add-dir is repeatable and variadic; parseCliArgs keeps only one value.
468export function claudeLaunchArgDirectories(launchArgs?: string): ReadonlyArray<string> {
469 const directories: string[] = [];
470 let collecting = false;
471 for (const token of tokenizeCliArgs(launchArgs)) {
472 if (token === "--") break;
473 if (token === "--add-dir") {
474 collecting = true;
475 } else if (token.startsWith("--add-dir=")) {
476 directories.push(token.slice("--add-dir=".length));
477 collecting = false;
478 } else if (token.startsWith("-")) {
479 collecting = false;
480 } else if (collecting) {
481 directories.push(token);
482 }
483 }
484 return directories;
485}
486
487/** First name wins, matching Claude Code's precedence of user skills over project skills. */
488export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
489 config: Pick<ClaudeSettings, "homePath"> & Partial<Pick<ClaudeSettings, "launchArgs">>,
490 cwd?: string,
491 environment?: NodeJS.ProcessEnv,
492): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
493 const fileSystem = yield* FileSystem.FileSystem;
494 const path = yield* Path.Path;
495 const configDirPath = yield* resolveClaudeConfigDirPath(config, environment ?? process.env, cwd);
496 const { skillOverrides, enabledPlugins } = yield* readSkillSettings(
497 configDirPath,
498 cwd,
499 environment ?? process.env,
500 );
501
502 const roots: ReadonlyArray<ClaudeSkillRoot> = [
503 { directory: path.join(configDirPath, "skills"), scope: "user" },
504 ...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
505 ...claudeLaunchArgDirectories(config.launchArgs)
506 .filter((directory) => directory && (cwd || path.isAbsolute(directory)))
507 .map((directory) => ({
508 directory: path.join(path.resolve(cwd ?? ".", directory), ".claude", "skills"),
509 scope: "project" as const,
510 })),
511 ...(yield* discoverPluginSkillRoots(
512 configDirPath,
513 cwd,
514 enabledPlugins,
515 environment ?? process.env,
516 )),
517 ];
518
519 const skillsByName = new Map<string, ServerProviderSkill>();
520 for (const root of roots) {
521 const singleSkill =
522 root.prefix !== undefined &&
523 (yield* fileSystem
524 .exists(path.join(root.directory, "SKILL.md"))
525 .pipe(Effect.orElseSucceed(() => false)));
526 const entries = singleSkill
527 ? [path.basename(root.directory)]
528 : yield* fileSystem
529 .readDirectory(root.directory)
530 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
531
532 for (const entry of [...entries].sort()) {
533 const skillPath = singleSkill
534 ? path.join(root.directory, "SKILL.md")
535 : path.join(root.directory, entry, "SKILL.md");
536 const contents = yield* fileSystem
537 .readFileString(skillPath)
538 .pipe(Effect.orElseSucceed(() => undefined));
539 if (contents === undefined) {
540 continue;
541 }
542
543 const frontmatter = parseSkillFrontmatter(contents);
544 if (frontmatter.kind === "malformed") {
545 continue;
546 }
547
548 const directoryName = entry.trim();
549 if (!directoryName) continue;
550 let name = directoryName;
551 if (root.prefix) {
552 // Native folder skills use their folder; only a single SKILL.md uses its name field.
553 const declaredName = singleSkill && frontmatter.kind === "parsed" ? frontmatter.name : "";
554 const unprefixedName = declaredName?.startsWith(`${root.prefix}:`)
555 ? declaredName.slice(root.prefix.length + 1)
556 : declaredName;
557 name = `${root.prefix}:${(unprefixedName || entry).replace(/[^a-zA-Z0-9_-]/g, "-")}`;
558 // Advertise only exact native names the shared composer grammar can invoke.
559 const [mention] = `$${name}`.matchAll(SKILL_MENTION_PATTERN);
560 if (mention?.[2] !== name) continue;
561 }
562
563 if (skillsByName.has(name)) {
564 continue;
565 }
566
567 const override = root.prefix ? undefined : skillOverrides.get(name);
568 const userInvocationOnly =
569 (frontmatter.kind === "parsed" && frontmatter.userInvocationOnly === true) ||
570 override?.userInvocationOnly === true;
571 skillsByName.set(name, {
572 name,
573 path: skillPath,
574 enabled: override?.enabled ?? true,
575 scope: root.scope,
576 ...(frontmatter.kind === "parsed" && frontmatter.description
577 ? { description: frontmatter.description }
578 : {}),
579 ...(userInvocationOnly ? { userInvocationOnly: true } : {}),
580 ...(frontmatter.kind === "parsed" && frontmatter.userInvocable === false
581 ? { userInvocable: false }
582 : {}),
583 });
584 }
585 }
586
587 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
588});