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
15import { claudeAccountConfigPath, readClaudeOauthAccount } from "../claudeResetCredits.ts";
16
17type ClaudeSkillScope = "user" | "project";
18
19type ClaudeSkillRoot = {
20 readonly directory: string;
21 readonly scope: ClaudeSkillScope;
22 readonly prefix?: string;
23};
24
25const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
26
27type SkillFrontmatter =
28 | { readonly kind: "missing" }
29 | { readonly kind: "malformed" }
30 | {
31 readonly kind: "parsed";
32 readonly name?: string;
33 readonly description?: string;
34 readonly userInvocationOnly?: boolean;
35 readonly userInvocable?: boolean;
36 };
37
38/** Claude accepts YAML 1.1 booleans that this YAML 1.2 parser leaves as strings or numbers. */
39function parseFrontmatterBoolean(value: unknown): boolean | undefined {
40 if (typeof value === "boolean") return value;
41 if (typeof value === "number") {
42 return value === 1 ? true : value === 0 ? false : undefined;
43 }
44 if (typeof value !== "string") return undefined;
45 switch (value.trim().toLowerCase()) {
46 case "true":
47 case "yes":
48 case "on":
49 case "y":
50 return true;
51 case "false":
52 case "no":
53 case "off":
54 case "n":
55 return false;
56 default:
57 return undefined;
58 }
59}
60
61function parseSkillFrontmatter(contents: string): SkillFrontmatter {
62 const match = FRONTMATTER_PATTERN.exec(contents);
63 if (!match) {
64 return { kind: "missing" };
65 }
66
67 const frontmatter = match[1] ?? "";
68 let parsed: unknown;
69 try {
70 parsed = parseYamlDocument(frontmatter);
71 } catch {
72 // Repair Claude's accepted ': ' scalars without disturbing comments or YAML structure.
73 const repaired = frontmatter.replace(
74 /^([\w-]+:[ \t]*)([^\r\n]*)/gm,
75 (line, prefix: string, value: string) => {
76 const scalar = value.split(/[ \t]+#/)[0] ?? "";
77 if (!/:[ \t]/.test(scalar) || /^(?:["'[\]{}|>&*!#%@`]|[-?:](?:[ \t]|$))/.test(scalar)) {
78 return line;
79 }
80 return `${prefix}${JSON.stringify(scalar)}${value.slice(scalar.length)}`;
81 },
82 );
83 try {
84 parsed = parseYamlDocument(repaired);
85 } catch {
86 return { kind: "malformed" };
87 }
88 }
89 if (typeof parsed !== "object" || parsed === null) {
90 return { kind: "malformed" };
91 }
92
93 const record = parsed as Record<string, unknown>;
94 const name = typeof record.name === "string" ? record.name.trim() : "";
95 const description = typeof record.description === "string" ? record.description.trim() : "";
96 return {
97 kind: "parsed",
98 ...(name ? { name } : {}),
99 ...(description ? { description } : {}),
100 ...(parseFrontmatterBoolean(record["disable-model-invocation"]) === true
101 ? { userInvocationOnly: true }
102 : {}),
103 ...(parseFrontmatterBoolean(record["user-invocable"]) === false
104 ? { userInvocable: false }
105 : {}),
106 };
107}
108
109// A caller-supplied environment is a plain object, without Windows' case-insensitive keys.
110function windowsEnvironmentValue(environment: NodeJS.ProcessEnv, name: string) {
111 const key = name.toLowerCase();
112 return Object.entries(environment)
113 .find(([candidate]) => candidate.toLowerCase() === key)?.[1]
114 ?.trim();
115}
116
117function claudeManagedDirectory(
118 path: Path.Path,
119 platform: NodeJS.Platform,
120 environment: NodeJS.ProcessEnv,
121): string | undefined {
122 if (platform === "darwin") {
123 return "/Library/Application Support/ClaudeCode";
124 }
125 if (platform === "win32") {
126 const programFiles = windowsEnvironmentValue(environment, "ProgramFiles");
127 return programFiles ? path.join(programFiles, "ClaudeCode") : undefined;
128 }
129 return "/etc/claude-code";
130}
131
132function claudeManagedSettingsPaths(
133 path: Path.Path,
134 platform: NodeJS.Platform,
135 environment: NodeJS.ProcessEnv,
136): ReadonlyArray<string> {
137 const managedDirectory = claudeManagedDirectory(path, platform, environment);
138 const programData =
139 platform === "win32" ? windowsEnvironmentValue(environment, "ProgramData") : undefined;
140 return [
141 ...(programData ? [path.join(programData, "ClaudeCode", "managed-settings.json")] : []),
142 ...(managedDirectory ? [path.join(managedDirectory, "managed-settings.json")] : []),
143 ];
144}
145
146/** Claude Code settings files, lowest precedence first. */
147function claudeSettingsPaths(
148 path: Path.Path,
149 configDirPath: string,
150 cwd: string | undefined,
151 platform: NodeJS.Platform,
152 environment: NodeJS.ProcessEnv,
153 repositoryRoot?: string,
154): ReadonlyArray<string> {
155 const root = repositoryRoot !== undefined && repositoryRoot !== cwd ? repositoryRoot : undefined;
156 return [
157 path.join(configDirPath, "settings.json"),
158 ...(cwd
159 ? [
160 path.join(cwd, ".claude", "settings.json"),
161 path.join(cwd, ".claude", "settings.local.json"),
162 ]
163 : []),
164 ...(root ? [path.join(root, ".claude", "settings.local.json")] : []),
165 ...claudeManagedSettingsPaths(path, platform, environment),
166 ];
167}
168
169// Untraced: skill discovery resolves every distinct plugin project path, too often for spans.
170const findRepositoryRoot = Effect.fnUntraced(function* (
171 cwd: string,
172): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {
173 const fileSystem = yield* FileSystem.FileSystem;
174 const path = yield* Path.Path;
175 let current = path.resolve(cwd);
176 while (true) {
177 const isRoot = yield* fileSystem
178 .exists(path.join(current, ".git"))
179 .pipe(Effect.orElseSucceed(() => false));
180 if (isRoot) {
181 return current;
182 }
183 const parent = path.dirname(current);
184 if (parent === current) {
185 return undefined;
186 }
187 current = parent;
188 }
189});
190
191const findPluginRepositoryRoot = Effect.fnUntraced(function* (cwd: string) {
192 const fileSystem = yield* FileSystem.FileSystem;
193 const path = yield* Path.Path;
194 const root = yield* findRepositoryRoot(cwd);
195 if (root === undefined) return undefined;
196 const gitFile = yield* fileSystem
197 .readFileString(path.join(root, ".git"))
198 .pipe(Effect.orElseSucceed(() => ""));
199 if (!gitFile.trim().startsWith("gitdir:")) return root;
200 const gitDirectory = path.resolve(root, gitFile.trim().slice(7).trim());
201 const commonFile = yield* fileSystem
202 .readFileString(path.join(gitDirectory, "commondir"))
203 .pipe(Effect.orElseSucceed(() => ""));
204 const worktreeFile = yield* fileSystem
205 .readFileString(path.join(gitDirectory, "gitdir"))
206 .pipe(Effect.orElseSucceed(() => ""));
207 if (!commonFile.trim() || !worktreeFile.trim()) return root;
208 const commonDirectory = path.resolve(gitDirectory, commonFile.trim());
209 const backlinkPath = yield* fileSystem
210 .realPath(path.resolve(gitDirectory, worktreeFile.trim()))
211 .pipe(Effect.orElseSucceed(() => undefined));
212 const worktreeGitPath = yield* fileSystem
213 .realPath(path.join(root, ".git"))
214 .pipe(Effect.orElseSucceed(() => undefined));
215 if (
216 path.dirname(gitDirectory) !== path.join(commonDirectory, "worktrees") ||
217 backlinkPath === undefined ||
218 backlinkPath !== worktreeGitPath
219 ) {
220 return root;
221 }
222 // Claude shares plugin install records across linked worktrees, using their common repository.
223 return path.basename(commonDirectory) === ".git"
224 ? path.dirname(commonDirectory)
225 : commonDirectory;
226});
227
228/**
229 * The CLI validates the whole map, not each entry: verified against it, one
230 * entry with an unknown value (or a boolean) makes it drop every override in
231 * that file, so this schema does the same rather than applying the valid
232 * siblings the CLI ignores.
233 */
234const SkillOverrideValue = Schema.Literals(["on", "name-only", "user-invocable-only", "off"]);
235
236// Lenient because these settings files are hand-edited and Claude Code itself
237// tolerates comments and trailing commas in them.
238const SkillSettings = fromLenientJson(
239 Schema.Struct({
240 skillOverrides: Schema.optional(Schema.Record(Schema.String, SkillOverrideValue)),
241 enabledPlugins: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
242 syncClaudeAiPlugins: Schema.optional(Schema.Unknown),
243 }),
244);
245const decodeSkillSettings = Schema.decodeUnknownEffect(SkillSettings);
246
247type SkillOverride = {
248 readonly enabled: boolean;
249 readonly userInvocationOnly: boolean;
250};
251
252function parseSkillOverride(value: typeof SkillOverrideValue.Type): SkillOverride {
253 switch (value) {
254 case "off":
255 return { enabled: false, userInvocationOnly: false };
256 case "user-invocable-only":
257 return { enabled: true, userInvocationOnly: true };
258 case "on":
259 case "name-only":
260 return { enabled: true, userInvocationOnly: false };
261 }
262}
263
264const readSkillSettings = Effect.fn("readSkillSettings")(function* (
265 configDirPath: string,
266 cwd: string | undefined,
267 environment: NodeJS.ProcessEnv,
268) {
269 const fileSystem = yield* FileSystem.FileSystem;
270 const path = yield* Path.Path;
271 const platform = yield* HostProcess.Platform;
272 const overridesByName = new Map<string, SkillOverride>();
273 const enabledPlugins = new Map<string, boolean>();
274 const managedPluginNames = new Set<string>();
275 const managedPaths = new Set(claudeManagedSettingsPaths(path, platform, environment));
276 let syncedPluginsHidden = false;
277 const repositoryRoot = cwd === undefined ? undefined : yield* findRepositoryRoot(cwd);
278 const projectSettingsPath =
279 cwd === undefined ? undefined : path.join(cwd, ".claude", "settings.json");
280
281 for (const settingsPath of claudeSettingsPaths(
282 path,
283 configDirPath,
284 cwd,
285 platform,
286 environment,
287 repositoryRoot,
288 )) {
289 const contents = yield* fileSystem
290 .readFileString(settingsPath)
291 .pipe(Effect.orElseSucceed(() => undefined));
292 if (contents === undefined) {
293 continue;
294 }
295
296 const parsed = yield* decodeSkillSettings(contents).pipe(
297 Effect.tapError((cause) =>
298 Effect.logDebug("claude settings file is unreadable; ignoring skill settings", {
299 path: settingsPath,
300 cause,
301 }),
302 ),
303 Effect.orElseSucceed(() => undefined),
304 );
305 for (const [name, value] of Object.entries(parsed?.skillOverrides ?? {})) {
306 overridesByName.set(name, parseSkillOverride(value));
307 }
308 for (const [key, enabled] of Object.entries(parsed?.enabledPlugins ?? {})) {
309 if (typeof enabled === "boolean") {
310 enabledPlugins.set(key, enabled);
311 if (managedPaths.has(settingsPath) && key.includes("@")) {
312 managedPluginNames.add(pluginNameKey(key.slice(0, key.indexOf("@"))));
313 }
314 } else {
315 // Extended formats replace lower-precedence values without enabling the plugin here.
316 enabledPlugins.delete(key);
317 }
318 }
319 // Claude ignores this switch in shared project settings, and honors only false.
320 if (parsed?.syncClaudeAiPlugins === false && settingsPath !== projectSettingsPath) {
321 syncedPluginsHidden = true;
322 }
323 }
324
325 return {
326 skillOverrides: overridesByName,
327 enabledPlugins,
328 managedPluginNames,
329 syncedPluginsHidden,
330 };
331});
332
333const InstalledPlugins = Schema.fromJsonString(
334 Schema.Struct({ plugins: Schema.Record(Schema.String, Schema.Array(Schema.Unknown)) }),
335);
336const decodeInstalledPlugin = Schema.decodeUnknownOption(
337 Schema.Struct({
338 scope: Schema.Literals(["user", "project", "local", "managed"]),
339 installPath: Schema.NonEmptyString,
340 projectPath: Schema.optional(Schema.NonEmptyString),
341 }),
342);
343const PluginManifest = Schema.fromJsonString(
344 Schema.Struct({
345 name: Schema.optional(Schema.NonEmptyString),
346 skills: Schema.optional(Schema.Union([Schema.String, Schema.Array(Schema.String)])),
347 defaultEnabled: Schema.optional(Schema.Unknown),
348 }),
349);
350const KnownMarketplaces = Schema.fromJsonString(Schema.Record(Schema.String, Schema.Unknown));
351const decodeKnownMarketplace = Schema.decodeUnknownOption(
352 Schema.Struct({ installLocation: Schema.NonEmptyString }),
353);
354const MarketplaceManifest = Schema.fromJsonString(
355 Schema.Struct({ plugins: Schema.Array(Schema.Unknown) }),
356);
357const decodeMarketplaceEntry = Schema.decodeUnknownOption(
358 Schema.Struct({
359 name: Schema.String,
360 source: Schema.Unknown,
361 skills: Schema.optional(Schema.Union([Schema.String, Schema.Array(Schema.String)])),
362 }),
363);
364
365const SyncedPlugins = Schema.fromJsonString(
366 Schema.Struct({ plugins: Schema.Array(Schema.Unknown) }),
367);
368const decodeSyncedPlugin = Schema.decodeUnknownOption(
369 Schema.Struct({
370 pluginId: Schema.String,
371 name: Schema.String,
372 generation: Schema.optional(Schema.Number),
373 }),
374);
375const ACCOUNT_UUID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
376
377/** Claude compares plugin names case-insensitively. */
378function pluginNameKey(name: string): string {
379 return name.normalize("NFC").toLowerCase();
380}
381
382/** Claude's folder for a synced row: reserved characters become `_`, trailing dots and spaces go. */
383function syncedPluginDirectoryName(name: string): string {
384 const replaced = name.replace(/[<>:"|?*\\/]/g, "_");
385 let end = replaced.length;
386 while (end > 0 && (replaced[end - 1] === "." || replaced[end - 1] === " ")) end--;
387 return replaced.slice(0, end);
388}
389
390function isInsideDirectory(path: Path.Path, directory: string, candidate: string): boolean {
391 const relative = path.relative(directory, candidate);
392 return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
393}
394
395const readPluginManifest = Effect.fn("readPluginManifest")(function* (pluginPath: string) {
396 const fileSystem = yield* FileSystem.FileSystem;
397 const path = yield* Path.Path;
398 return yield* fileSystem
399 .readFileString(path.join(pluginPath, ".claude-plugin", "plugin.json"))
400 .pipe(
401 Effect.flatMap(Schema.decodeUnknownEffect(PluginManifest)),
402 Effect.orElseSucceed(() => undefined),
403 );
404});
405
406/** Declared skill folders that exist inside the install, through symlinks too, as the native loader requires. */
407const containedSkillDirectories = Effect.fn("containedSkillDirectories")(function* (
408 installPath: string,
409 declared: ReadonlyArray<string>,
410) {
411 const fileSystem = yield* FileSystem.FileSystem;
412 const path = yield* Path.Path;
413 const canonicalInstallPath = yield* fileSystem
414 .realPath(installPath)
415 .pipe(Effect.orElseSucceed(() => undefined));
416 const directories: Array<string> = [];
417 for (const relative of declared) {
418 const directory = path.resolve(installPath, relative);
419 if (!isInsideDirectory(path, installPath, directory) || canonicalInstallPath === undefined) {
420 continue;
421 }
422 const canonicalDirectory = yield* fileSystem
423 .realPath(directory)
424 .pipe(Effect.orElseSucceed(() => undefined));
425 if (
426 canonicalDirectory !== undefined &&
427 isInsideDirectory(path, canonicalInstallPath, canonicalDirectory)
428 ) {
429 directories.push(directory);
430 }
431 }
432 return directories;
433});
434
435const pluginSkillRoots = Effect.fn("pluginSkillRoots")(function* (
436 installPath: string,
437 scope: ClaudeSkillScope,
438 prefix: string,
439 manifest: typeof PluginManifest.Type | undefined,
440 entrySkills?: ReadonlyArray<string>,
441) {
442 const fileSystem = yield* FileSystem.FileSystem;
443 const path = yield* Path.Path;
444 const defaultDirectory = path.join(installPath, "skills");
445 // A root-sourced marketplace entry's skills list replaces the plugin's skills; `./` means skills/.
446 const entryDirectories =
447 entrySkills === undefined ? [] : yield* containedSkillDirectories(installPath, entrySkills);
448 if (entryDirectories.length > 0) {
449 return entryDirectories.map((directory) => ({
450 directory: directory === installPath ? defaultDirectory : directory,
451 scope,
452 prefix,
453 }));
454 }
455 const roots: Array<ClaudeSkillRoot> = [];
456 const hasDefaultDirectory = yield* fileSystem
457 .exists(defaultDirectory)
458 .pipe(Effect.orElseSucceed(() => false));
459 if (hasDefaultDirectory) roots.push({ directory: defaultDirectory, scope, prefix });
460 const declared = manifest?.skills;
461 if (declared === undefined && !hasDefaultDirectory) {
462 const hasRootSkill = yield* fileSystem
463 .exists(path.join(installPath, "SKILL.md"))
464 .pipe(Effect.orElseSucceed(() => false));
465 if (hasRootSkill) roots.push({ directory: installPath, scope, prefix });
466 }
467 const declaredDirectories = yield* containedSkillDirectories(
468 installPath,
469 typeof declared === "string" ? [declared] : (declared ?? []),
470 );
471 for (const directory of declaredDirectories) roots.push({ directory, scope, prefix });
472 return roots;
473});
474
475/** The `<org>_<account>` folder Claude syncs the signed-in account's claude.ai plugins into. */
476const resolveSyncedPluginBucket = Effect.fn("resolveSyncedPluginBucket")(function* (
477 config: Pick<ClaudeSettings, "homePath">,
478 configDirPath: string,
479 environment: NodeJS.ProcessEnv,
480) {
481 const accountConfigPath = yield* claudeAccountConfigPath(
482 config.homePath.trim() || environment.CLAUDE_CONFIG_DIR?.trim() ? configDirPath : undefined,
483 );
484 const account = yield* readClaudeOauthAccount(accountConfigPath);
485 const organizationId = environment.CLAUDE_CODE_ORGANIZATION_UUID ?? account?.organizationUuid;
486 // A stored claude.ai login names its own account; an injected token uses the env account.
487 const environmentAccountId = environment.CLAUDE_CODE_ACCOUNT_UUID;
488 const accountId =
489 account !== undefined && !environment.CLAUDE_CODE_OAUTH_TOKEN
490 ? typeof account.accountUuid === "string"
491 ? account.accountUuid
492 : undefined
493 : environmentAccountId && ACCOUNT_UUID_PATTERN.test(environmentAccountId)
494 ? environmentAccountId
495 : "unbound";
496 if (
497 !organizationId ||
498 !accountId ||
499 !ACCOUNT_UUID_PATTERN.test(organizationId) ||
500 (accountId !== "unbound" && !ACCOUNT_UUID_PATTERN.test(accountId))
501 ) {
502 return undefined;
503 }
504 return `${organizationId.toLowerCase()}_${accountId.toLowerCase()}`;
505});
506
507/** A plugin folder itself, or else the manifest-bearing plugins directly inside it. */
508const expandInlinePluginDirectory = Effect.fn("expandInlinePluginDirectory")(function* (
509 directory: string,
510) {
511 const fileSystem = yield* FileSystem.FileSystem;
512 const path = yield* Path.Path;
513 const exists = (candidate: string) =>
514 fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
515 for (const component of [path.join(".claude-plugin", "plugin.json"), "skills", "SKILL.md"]) {
516 if (yield* exists(path.join(directory, component))) return [directory];
517 }
518 const children = yield* fileSystem
519 .readDirectory(directory)
520 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
521 return yield* Effect.filter(
522 [...children].sort().map((child) => path.join(directory, child)),
523 (child) => exists(path.join(child, ".claude-plugin", "plugin.json")),
524 );
525});
526
527/**
528 * Plugin folders Claude Code loads inline, from --plugin-dir launch arguments and then
529 * CLAUDE_CODE_PLUGIN_DIRS, and their plugin names.
530 */
531const discoverInlinePluginSkillRoots = Effect.fn("discoverInlinePluginSkillRoots")(function* (
532 launchArgPluginDirectories: ReadonlyArray<string>,
533 environmentPluginDirectories: string | undefined,
534 cwd: string | undefined,
535 enabledPlugins: ReadonlyMap<string, boolean>,
536 managedPluginNames: ReadonlySet<string>,
537) {
538 const path = yield* Path.Path;
539 const home = yield* HostProcess.HomeDirectory;
540 const platform = yield* HostProcess.Platform;
541 const roots: Array<ClaudeSkillRoot> = [];
542 const names = new Set<string>();
543 const seen = new Set<string>();
544 const directories = [
545 // Claude resolves a relative --plugin-dir against its cwd and expands no `~` in it.
546 ...launchArgPluginDirectories
547 .filter((directory) => directory && (cwd || path.isAbsolute(directory)))
548 .map((directory) => path.resolve(cwd ?? ".", directory)),
549 // Claude skips relative CLAUDE_CODE_PLUGIN_DIRS entries rather than resolving them.
550 ...(environmentPluginDirectories ?? "")
551 .split(platform === "win32" ? ";" : ":")
552 .map((entry) => expandHomePath(entry.trim(), home))
553 .filter((directory) => directory && path.isAbsolute(directory))
554 .map((directory) => path.resolve(directory)),
555 ];
556 for (const directory of directories) {
557 for (const installPath of yield* expandInlinePluginDirectory(directory)) {
558 if (seen.has(installPath)) continue;
559 seen.add(installPath);
560 const manifest = yield* readPluginManifest(installPath);
561 const prefix = manifest?.name ?? path.basename(installPath);
562 // A `<name>@inline` setting wins; otherwise the manifest's `defaultEnabled` decides.
563 const setting = enabledPlugins.get(`${prefix}@inline`);
564 if (setting === false || (setting === undefined && manifest?.defaultEnabled === false)) {
565 continue;
566 }
567 // Managed enabledPlugins entries, true or false, lock the name against inline copies.
568 if (managedPluginNames.has(pluginNameKey(prefix))) continue;
569 names.add(pluginNameKey(prefix));
570 roots.push(...(yield* pluginSkillRoots(installPath, "user", prefix, manifest)));
571 }
572 }
573 return { roots, names };
574});
575
576const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* (
577 configDirPath: string,
578 cwd: string | undefined,
579 enabledPlugins: ReadonlyMap<string, boolean>,
580 inlinePluginNames: ReadonlySet<string>,
581 syncedBucket: string | undefined,
582 environment: NodeJS.ProcessEnv,
583) {
584 const fileSystem = yield* FileSystem.FileSystem;
585 const path = yield* Path.Path;
586 const home = yield* HostProcess.HomeDirectory;
587 const pluginDirectory = environment.CLAUDE_CODE_PLUGIN_CACHE_DIR;
588 const pluginsPath = pluginDirectory
589 ? path.resolve(cwd ?? ".", expandHomePath(pluginDirectory, home))
590 : path.join(configDirPath, "plugins");
591 const installed = yield* fileSystem
592 .readFileString(path.join(pluginsPath, "installed_plugins.json"))
593 .pipe(
594 Effect.flatMap(Schema.decodeUnknownEffect(InstalledPlugins)),
595 Effect.orElseSucceed(() => undefined),
596 );
597 const roots: Array<ClaudeSkillRoot> = [];
598 // An enabled inline plugin replaces installed and synced plugins of the same name.
599 const claimedPluginNames = new Set(inlinePluginNames);
600 // The CLI's process.cwd() resolves symlinks; registry projectPath values remain lexical.
601 const workspace =
602 cwd === undefined
603 ? undefined
604 : yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => path.resolve(cwd)));
605 // Install records repeat project paths, often hundreds of times per discovery.
606 const projectRepositoryRoots = new Map<string, string | undefined>();
607 const repositoryRoot =
608 workspace === undefined ? undefined : yield* findPluginRepositoryRoot(workspace);
609 const knownMarketplaces = yield* fileSystem
610 .readFileString(path.join(pluginsPath, "known_marketplaces.json"))
611 .pipe(
612 Effect.flatMap(Schema.decodeUnknownEffect(KnownMarketplaces)),
613 Effect.orElseSucceed((): Record<string, unknown> => ({})),
614 );
615 const marketplaceEntries = new Map<string, ReadonlyArray<unknown>>();
616 // Claude applies an entry's skills list only when the entry's source is the marketplace root.
617 const readRootEntrySkills = Effect.fnUntraced(function* (marketplace: string, plugin: string) {
618 if (!marketplaceEntries.has(marketplace)) {
619 const location = Option.getOrUndefined(
620 decodeKnownMarketplace(knownMarketplaces[marketplace]),
621 )?.installLocation;
622 const manifest =
623 location === undefined
624 ? undefined
625 : yield* fileSystem
626 .readFileString(path.join(location, ".claude-plugin", "marketplace.json"))
627 .pipe(
628 Effect.flatMap(Schema.decodeUnknownEffect(MarketplaceManifest)),
629 Effect.orElseSucceed(() => undefined),
630 );
631 marketplaceEntries.set(marketplace, manifest?.plugins ?? []);
632 }
633 const entry = (marketplaceEntries.get(marketplace) ?? [])
634 .flatMap((candidate) => Option.toArray(decodeMarketplaceEntry(candidate)))
635 .find((candidate) => candidate.name === plugin);
636 if (
637 entry?.skills === undefined ||
638 typeof entry.source !== "string" ||
639 !entry.source.split(/[\\/]/).every((segment) => segment === "" || segment === ".")
640 ) {
641 return undefined;
642 }
643 return typeof entry.skills === "string" ? [entry.skills] : entry.skills;
644 });
645
646 for (const [key, entries] of Object.entries(installed?.plugins ?? {}).sort()) {
647 if (enabledPlugins.get(key) !== true) continue;
648 const applicable = yield* Effect.filter(
649 entries.flatMap((entry) => Option.toArray(decodeInstalledPlugin(entry))),
650 (record) =>
651 Effect.gen(function* () {
652 if (record.scope === "user" || record.scope === "managed") return true;
653 if (record.projectPath === undefined || workspace === undefined) return false;
654 const projectPath = path.resolve(record.projectPath);
655 if (projectPath === workspace) return true;
656 if (repositoryRoot === undefined) return false;
657 if (!projectRepositoryRoots.has(projectPath)) {
658 projectRepositoryRoots.set(projectPath, yield* findPluginRepositoryRoot(projectPath));
659 }
660 return projectRepositoryRoots.get(projectPath) === repositoryRoot;
661 }),
662 );
663 // The native loader keeps registry order, preferring the first install that exists.
664 const existing = yield* Effect.findFirst(applicable, (record) =>
665 fileSystem
666 .exists(path.resolve(cwd ?? ".", record.installPath))
667 .pipe(Effect.orElseSucceed(() => false)),
668 );
669 const install = Option.getOrElse(existing, () => applicable[0]);
670 if (!install) continue;
671 const scope = install.scope === "user" || install.scope === "managed" ? "user" : "project";
672 const installPath = path.resolve(cwd ?? ".", install.installPath);
673 const manifest = yield* readPluginManifest(installPath);
674 const prefix = manifest?.name ?? key.split("@")[0];
675 if (!prefix || inlinePluginNames.has(pluginNameKey(prefix))) continue;
676 // A registry record whose install is gone loads nothing and claims no namespace.
677 if (Option.isSome(existing)) claimedPluginNames.add(pluginNameKey(prefix));
678 const separator = key.lastIndexOf("@");
679 const entrySkills =
680 separator > 0
681 ? yield* readRootEntrySkills(key.slice(separator + 1), key.slice(0, separator))
682 : undefined;
683 roots.push(...(yield* pluginSkillRoots(installPath, scope, prefix, manifest, entrySkills)));
684 }
685 if (syncedBucket === undefined) return roots;
686
687 const syncedPath = path.join(configDirPath, "plugins", "synced");
688 const bucketPath = path.join(syncedPath, syncedBucket);
689 const disabledSyncedPlugins = new Set(
690 [...enabledPlugins].flatMap(([pluginKey, enabled]) =>
691 !enabled && pluginKey.endsWith("@synced") ? [pluginNameKey(pluginKey.slice(0, -7))] : [],
692 ),
693 );
694 const hasBucketMarker = yield* fileSystem
695 .exists(path.join(syncedPath, `.bucket-${syncedBucket}`))
696 .pipe(Effect.orElseSucceed(() => false));
697 if (!hasBucketMarker) return roots;
698 const synced = yield* fileSystem.readFileString(path.join(bucketPath, "manifest.json")).pipe(
699 Effect.flatMap(Schema.decodeUnknownEffect(SyncedPlugins)),
700 Effect.orElseSucceed(() => undefined),
701 );
702 for (const row of synced?.plugins ?? []) {
703 const plugin = Option.getOrUndefined(decodeSyncedPlugin(row));
704 const directoryName = plugin === undefined ? "" : syncedPluginDirectoryName(plugin.name);
705 if (!plugin || !directoryName || directoryName.startsWith(".")) continue;
706 const generation = plugin.generation;
707 const pluginPath = path.join(
708 bucketPath,
709 generation !== undefined && Number.isInteger(generation) && generation >= 2
710 ? `${directoryName}~g${generation}`
711 : directoryName,
712 );
713 const manifest = yield* readPluginManifest(pluginPath);
714 const prefix = manifest?.name ?? directoryName;
715 // An installed plugin of the same name, then the first synced row, holds the namespace.
716 const key = pluginNameKey(prefix);
717 if (claimedPluginNames.has(key) || disabledSyncedPlugins.has(key)) continue;
718 claimedPluginNames.add(key);
719 roots.push(...(yield* pluginSkillRoots(pluginPath, "user", prefix, manifest)));
720 }
721 return roots;
722});
723
724const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
725 config: Pick<ClaudeSettings, "homePath">,
726 environment: NodeJS.ProcessEnv,
727 cwd?: string,
728): Effect.fn.Return<string, never, Path.Path> {
729 const path = yield* Path.Path;
730 const home = yield* HostProcess.HomeDirectory;
731 const homePath = config.homePath.trim();
732 if (homePath.length > 0) {
733 return path.resolve(expandHomePath(homePath, home));
734 }
735 // Match the spawned CLI: preserve a literal ~ and resolve relative config against workspace cwd.
736 const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
737 if (environmentConfigDir.length > 0) {
738 return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
739 }
740 return path.join(home, ".claude");
741});
742
743const SettingsEnv = Schema.Struct({
744 ANTHROPIC_BASE_URL: Schema.optional(Schema.String),
745 CLAUDE_CODE_ENTRYPOINT: Schema.optional(Schema.String),
746 CLAUDE_CODE_PLUGIN_DIRS: Schema.optional(Schema.String),
747 // Unquoted JSON values must not fail the decode and drop ANTHROPIC_BASE_URL with them.
748 CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: Schema.optional(Schema.Unknown),
749 CLAUDE_CODE_GATEWAY_MODEL_DISCOVERY_TIMEOUT_MS: Schema.optional(Schema.Unknown),
750});
751const decodeSettingsEnv = Schema.decodeUnknownEffect(
752 fromLenientJson(Schema.Struct({ env: Schema.optional(SettingsEnv) })),
753);
754
755/** The `env` values T3 Code reads from Claude's user and managed settings; later files win. */
756export const readClaudeSettingsEnv = Effect.fn("readClaudeSettingsEnv")(function* (
757 config: Pick<ClaudeSettings, "homePath">,
758 cwd: string | undefined,
759 environment: NodeJS.ProcessEnv,
760): Effect.fn.Return<typeof SettingsEnv.Type, never, FileSystem.FileSystem | Path.Path> {
761 const fileSystem = yield* FileSystem.FileSystem;
762 const path = yield* Path.Path;
763 const platform = yield* HostProcess.Platform;
764 const configDirPath = yield* resolveClaudeConfigDirPath(config, environment, cwd);
765 const settingsEnv: typeof SettingsEnv.Type = {};
766 for (const settingsPath of claudeSettingsPaths(
767 path,
768 configDirPath,
769 undefined,
770 platform,
771 environment,
772 )) {
773 const contents = yield* fileSystem
774 .readFileString(settingsPath)
775 .pipe(Effect.orElseSucceed(() => undefined));
776 if (contents === undefined) continue;
777 const parsed = yield* decodeSettingsEnv(contents).pipe(Effect.orElseSucceed(() => undefined));
778 Object.assign(settingsEnv, parsed?.env);
779 }
780 return settingsEnv;
781});
782
783const decodeSettingsRecord = Schema.decodeUnknownEffect(
784 fromLenientJson(Schema.Record(Schema.String, Schema.Unknown)),
785);
786
787/** Claude's user settings file as written; undefined when it is missing or not a JSON object. */
788export const readClaudeUserSettings = Effect.fn("readClaudeUserSettings")(function* (
789 config: Pick<ClaudeSettings, "homePath">,
790 cwd: string | undefined,
791 environment: NodeJS.ProcessEnv,
792): Effect.fn.Return<Record<string, unknown> | undefined, never, FileSystem.FileSystem | Path.Path> {
793 const fileSystem = yield* FileSystem.FileSystem;
794 const path = yield* Path.Path;
795 const configDirPath = yield* resolveClaudeConfigDirPath(config, environment, cwd);
796 return yield* fileSystem.readFileString(path.join(configDirPath, "settings.json")).pipe(
797 Effect.flatMap(decodeSettingsRecord),
798 Effect.orElseSucceed(() => undefined),
799 );
800});
801
802/** The host of an `ANTHROPIC_BASE_URL` that is not Anthropic's own API. */
803export function customClaudeApiEndpointHost(baseUrl: string | undefined): string | undefined {
804 const endpoint = URL.parse(baseUrl?.trim() ?? "");
805 return endpoint !== null &&
806 (endpoint.protocol === "http:" || endpoint.protocol === "https:") &&
807 endpoint.hostname !== "" &&
808 endpoint.hostname !== "api.anthropic.com"
809 ? endpoint.hostname
810 : undefined;
811}
812
813// Claude's --add-dir is repeatable and variadic; parseCliArgs keeps only one value.
814export function claudeLaunchArgDirectories(launchArgs?: string): ReadonlyArray<string> {
815 const directories: string[] = [];
816 let collecting = false;
817 for (const token of tokenizeCliArgs(launchArgs)) {
818 if (token === "--") break;
819 if (token === "--add-dir") {
820 collecting = true;
821 } else if (token.startsWith("--add-dir=")) {
822 directories.push(token.slice("--add-dir=".length));
823 collecting = false;
824 } else if (token.startsWith("-")) {
825 collecting = false;
826 } else if (collecting) {
827 directories.push(token);
828 }
829 }
830 return directories;
831}
832
833// The Claude CLI takes the next token as this flag's value even when it starts with `--`.
834export const claudeLaunchArgParseOptions = { valueFlags: ["append-system-prompt"] };
835
836// Claude's --plugin-dir is repeatable; parseCliArgs keeps only the last one.
837export function claudeLaunchArgPluginDirectories(launchArgs?: string): ReadonlyArray<string> {
838 const tokens = tokenizeCliArgs(launchArgs);
839 const directories: string[] = [];
840 for (let index = 0; index < tokens.length && tokens[index] !== "--"; index++) {
841 const token = tokens[index]!;
842 if (!token.startsWith("--") || token.includes("=")) {
843 if (token.startsWith("--plugin-dir=")) directories.push(token.slice("--plugin-dir=".length));
844 continue;
845 }
846 const next = tokens[index + 1];
847 const takesNext =
848 next !== undefined &&
849 (!next.startsWith("--") || claudeLaunchArgParseOptions.valueFlags.includes(token.slice(2)));
850 if (!takesNext) continue;
851 if (token === "--plugin-dir") directories.push(next);
852 index++;
853 }
854 return directories;
855}
856
857/** First name wins: managed skills, then user skills, then project skills. */
858export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
859 config: Pick<ClaudeSettings, "homePath"> & Partial<Pick<ClaudeSettings, "launchArgs">>,
860 cwd?: string,
861 environment?: NodeJS.ProcessEnv,
862): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
863 const fileSystem = yield* FileSystem.FileSystem;
864 const path = yield* Path.Path;
865 const env = environment ?? process.env;
866 const configDirPath = yield* resolveClaudeConfigDirPath(config, env, cwd);
867 const { skillOverrides, enabledPlugins, managedPluginNames, syncedPluginsHidden } =
868 yield* readSkillSettings(configDirPath, cwd, env);
869 const managedDirectory = claudeManagedDirectory(path, yield* HostProcess.Platform, env);
870 // Most installs have no synced folder; skip reading `.claude.json` for them.
871 const hasSyncedPlugins =
872 !syncedPluginsHidden &&
873 (yield* fileSystem
874 .exists(path.join(configDirPath, "plugins", "synced"))
875 .pipe(Effect.orElseSucceed(() => false)));
876 const syncedBucket = hasSyncedPlugins
877 ? yield* resolveSyncedPluginBucket(config, configDirPath, env)
878 : undefined;
879 // Claude applies its settings `env` over the inherited environment.
880 const inlinePluginDirectories =
881 (yield* readClaudeSettingsEnv(config, cwd, env)).CLAUDE_CODE_PLUGIN_DIRS ??
882 env.CLAUDE_CODE_PLUGIN_DIRS;
883 const inlinePlugins = yield* discoverInlinePluginSkillRoots(
884 claudeLaunchArgPluginDirectories(config.launchArgs),
885 inlinePluginDirectories,
886 cwd,
887 enabledPlugins,
888 managedPluginNames,
889 );
890
891 const roots: ReadonlyArray<ClaudeSkillRoot> = [
892 ...(managedDirectory
893 ? [{ directory: path.join(managedDirectory, ".claude", "skills"), scope: "user" as const }]
894 : []),
895 { directory: path.join(configDirPath, "skills"), scope: "user" },
896 ...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
897 ...claudeLaunchArgDirectories(config.launchArgs)
898 .filter((directory) => directory && (cwd || path.isAbsolute(directory)))
899 .map((directory) => ({
900 directory: path.join(path.resolve(cwd ?? ".", directory), ".claude", "skills"),
901 scope: "project" as const,
902 })),
903 ...inlinePlugins.roots,
904 ...(yield* discoverPluginSkillRoots(
905 configDirPath,
906 cwd,
907 enabledPlugins,
908 inlinePlugins.names,
909 syncedBucket,
910 env,
911 )),
912 ];
913
914 const skillsByName = new Map<string, ServerProviderSkill>();
915 for (const root of roots) {
916 const singleSkill =
917 root.prefix !== undefined &&
918 (yield* fileSystem
919 .exists(path.join(root.directory, "SKILL.md"))
920 .pipe(Effect.orElseSucceed(() => false)));
921 const entries = singleSkill
922 ? [path.basename(root.directory)]
923 : yield* fileSystem
924 .readDirectory(root.directory)
925 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
926
927 for (const entry of [...entries].sort()) {
928 const skillPath = singleSkill
929 ? path.join(root.directory, "SKILL.md")
930 : path.join(root.directory, entry, "SKILL.md");
931 const contents = yield* fileSystem
932 .readFileString(skillPath)
933 .pipe(Effect.orElseSucceed(() => undefined));
934 if (contents === undefined) {
935 continue;
936 }
937
938 const frontmatter = parseSkillFrontmatter(contents);
939 if (frontmatter.kind === "malformed") {
940 continue;
941 }
942
943 const directoryName = entry.trim();
944 if (!directoryName) continue;
945 let name = directoryName;
946 if (root.prefix) {
947 // Native folder skills use their folder; only a single SKILL.md uses its name field.
948 const declaredName = singleSkill && frontmatter.kind === "parsed" ? frontmatter.name : "";
949 const unprefixedName = declaredName?.startsWith(`${root.prefix}:`)
950 ? declaredName.slice(root.prefix.length + 1)
951 : declaredName;
952 name = `${root.prefix}:${(unprefixedName || entry).replace(/[^a-zA-Z0-9_-]/g, "-")}`;
953 // Advertise only exact native names the shared composer grammar can invoke.
954 const [mention] = `$${name}`.matchAll(SKILL_MENTION_PATTERN);
955 if (mention?.[2] !== name) continue;
956 }
957
958 if (skillsByName.has(name)) {
959 continue;
960 }
961
962 const override = root.prefix ? undefined : skillOverrides.get(name);
963 const userInvocationOnly =
964 (frontmatter.kind === "parsed" && frontmatter.userInvocationOnly === true) ||
965 override?.userInvocationOnly === true;
966 skillsByName.set(name, {
967 name,
968 path: skillPath,
969 enabled: override?.enabled ?? true,
970 scope: root.scope,
971 ...(frontmatter.kind === "parsed" && frontmatter.description
972 ? { description: frontmatter.description }
973 : {}),
974 ...(userInvocationOnly ? { userInvocationOnly: true } : {}),
975 ...(frontmatter.kind === "parsed" && frontmatter.userInvocable === false
976 ? { userInvocable: false }
977 : {}),
978 });
979 }
980 }
981
982 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
983});