Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ClaudeSkills.ts

751 lines28.9 KB

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 }
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 };
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();
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";
131​
132/** Claude Code settings files, lowest precedence first. */
133function claudeSettingsPaths(
134 path: Path.Path,
135 configDirPath: string,
136 cwd: string | undefined,
137 platform: NodeJS.Platform,
138 environment: NodeJS.ProcessEnv,
139 repositoryRoot?: string,
140): ReadonlyArray<string> {
141 const managedDirectory = claudeManagedDirectory(path, platform, environment);
142 const programData =
143 platform === "win32" ? windowsEnvironmentValue(environment, "ProgramData") : undefined;
144 const root = repositoryRoot !== undefined && repositoryRoot !== cwd ? repositoryRoot : undefined;
145 return [
146 path.join(configDirPath, "settings.json"),
147 ...(cwd
148 ? [
149 path.join(cwd, ".claude", "settings.json"),
150 path.join(cwd, ".claude", "settings.local.json"),
151 ]
152 : []),
153 ...(root ? [path.join(root, ".claude", "settings.local.json")] : []),
154 ...(programData ? [path.join(programData, "ClaudeCode", "managed-settings.json")] : []),
155 ...(managedDirectory ? [path.join(managedDirectory, "managed-settings.json")] : []),
156 ];
158​
159// Untraced: skill discovery resolves every distinct plugin project path, too often for spans.
160const findRepositoryRoot = Effect.fnUntraced(function* (
161 cwd: string,
162): Effect.fn.Return<string | undefined, never, FileSystem.FileSystem | Path.Path> {
163 const fileSystem = yield* FileSystem.FileSystem;
164 const path = yield* Path.Path;
165 let current = path.resolve(cwd);
166 while (true) {
167 const isRoot = yield* fileSystem
168 .exists(path.join(current, ".git"))
169 .pipe(Effect.orElseSucceed(() => false));
170 if (isRoot) {
171 return current;
172 }
173 const parent = path.dirname(current);
174 if (parent === current) {
175 return undefined;
176 }
177 current = parent;
178 }
179});
180​
181const findPluginRepositoryRoot = Effect.fnUntraced(function* (cwd: string) {
182 const fileSystem = yield* FileSystem.FileSystem;
183 const path = yield* Path.Path;
184 const root = yield* findRepositoryRoot(cwd);
185 if (root === undefined) return undefined;
186 const gitFile = yield* fileSystem
187 .readFileString(path.join(root, ".git"))
188 .pipe(Effect.orElseSucceed(() => ""));
189 if (!gitFile.trim().startsWith("gitdir:")) return root;
190 const gitDirectory = path.resolve(root, gitFile.trim().slice(7).trim());
191 const commonFile = yield* fileSystem
192 .readFileString(path.join(gitDirectory, "commondir"))
193 .pipe(Effect.orElseSucceed(() => ""));
194 const worktreeFile = yield* fileSystem
195 .readFileString(path.join(gitDirectory, "gitdir"))
196 .pipe(Effect.orElseSucceed(() => ""));
197 if (!commonFile.trim() || !worktreeFile.trim()) return root;
198 const commonDirectory = path.resolve(gitDirectory, commonFile.trim());
199 const backlinkPath = yield* fileSystem
200 .realPath(path.resolve(gitDirectory, worktreeFile.trim()))
201 .pipe(Effect.orElseSucceed(() => undefined));
202 const worktreeGitPath = yield* fileSystem
203 .realPath(path.join(root, ".git"))
204 .pipe(Effect.orElseSucceed(() => undefined));
205 if (
206 path.dirname(gitDirectory) !== path.join(commonDirectory, "worktrees") ||
207 backlinkPath === undefined ||
208 backlinkPath !== worktreeGitPath
209 ) {
210 return root;
211 }
212 // Claude shares plugin install records across linked worktrees, using their common repository.
213 return path.basename(commonDirectory) === ".git"
214 ? path.dirname(commonDirectory)
215 : commonDirectory;
216});
217​
218/**
219 * The CLI validates the whole map, not each entry: verified against it, one
220 * entry with an unknown value (or a boolean) makes it drop every override in
221 * that file, so this schema does the same rather than applying the valid
222 * siblings the CLI ignores.
223 */
224const SkillOverrideValue = Schema.Literals(["on", "name-only", "user-invocable-only", "off"]);
225​
226// Lenient because these settings files are hand-edited and Claude Code itself
227// tolerates comments and trailing commas in them.
228const SkillSettings = fromLenientJson(
229 Schema.Struct({
230 skillOverrides: Schema.optional(Schema.Record(Schema.String, SkillOverrideValue)),
231 enabledPlugins: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
232 syncClaudeAiPlugins: Schema.optional(Schema.Unknown),
233 }),
234);
235const decodeSkillSettings = Schema.decodeUnknownEffect(SkillSettings);
236​
237type SkillOverride = {
238 readonly enabled: boolean;
239 readonly userInvocationOnly: boolean;
240};
241​
242function parseSkillOverride(value: typeof SkillOverrideValue.Type): SkillOverride {
243 switch (value) {
244 case "off":
245 return { enabled: false, userInvocationOnly: false };
246 case "user-invocable-only":
247 return { enabled: true, userInvocationOnly: true };
248 case "on":
249 case "name-only":
250 return { enabled: true, userInvocationOnly: false };
251 }
253​
254const readSkillSettings = Effect.fn("readSkillSettings")(function* (
255 configDirPath: string,
256 cwd: string | undefined,
257 environment: NodeJS.ProcessEnv,
258) {
259 const fileSystem = yield* FileSystem.FileSystem;
260 const path = yield* Path.Path;
261 const platform = yield* HostProcess.Platform;
262 const overridesByName = new Map<string, SkillOverride>();
263 const enabledPlugins = new Map<string, boolean>();
264 let syncedPluginsHidden = false;
265 const repositoryRoot = cwd === undefined ? undefined : yield* findRepositoryRoot(cwd);
266 const projectSettingsPath =
267 cwd === undefined ? undefined : path.join(cwd, ".claude", "settings.json");
268​
269 for (const settingsPath of claudeSettingsPaths(
270 path,
271 configDirPath,
272 cwd,
273 platform,
274 environment,
275 repositoryRoot,
276 )) {
277 const contents = yield* fileSystem
278 .readFileString(settingsPath)
279 .pipe(Effect.orElseSucceed(() => undefined));
280 if (contents === undefined) {
281 continue;
282 }
283​
284 const parsed = yield* decodeSkillSettings(contents).pipe(
285 Effect.tapError((cause) =>
286 Effect.logDebug("claude settings file is unreadable; ignoring skill settings", {
287 path: settingsPath,
288 cause,
289 }),
290 ),
291 Effect.orElseSucceed(() => undefined),
292 );
293 for (const [name, value] of Object.entries(parsed?.skillOverrides ?? {})) {
294 overridesByName.set(name, parseSkillOverride(value));
295 }
296 for (const [key, enabled] of Object.entries(parsed?.enabledPlugins ?? {})) {
297 if (typeof enabled === "boolean") {
298 enabledPlugins.set(key, enabled);
299 } else {
300 // Extended formats replace lower-precedence values without enabling the plugin here.
301 enabledPlugins.delete(key);
302 }
303 }
304 // Claude ignores this switch in shared project settings, and honors only false.
305 if (parsed?.syncClaudeAiPlugins === false && settingsPath !== projectSettingsPath) {
306 syncedPluginsHidden = true;
307 }
308 }
309​
310 return { skillOverrides: overridesByName, enabledPlugins, syncedPluginsHidden };
311});
312​
313const InstalledPlugins = Schema.fromJsonString(
314 Schema.Struct({ plugins: Schema.Record(Schema.String, Schema.Array(Schema.Unknown)) }),
315);
316const decodeInstalledPlugin = Schema.decodeUnknownOption(
317 Schema.Struct({
318 scope: Schema.Literals(["user", "project", "local", "managed"]),
319 installPath: Schema.NonEmptyString,
320 projectPath: Schema.optional(Schema.NonEmptyString),
321 }),
322);
323const PluginManifest = Schema.fromJsonString(
324 Schema.Struct({
325 name: Schema.optional(Schema.NonEmptyString),
326 skills: Schema.optional(Schema.Union([Schema.String, Schema.Array(Schema.String)])),
327 }),
328);
329​
330const SyncedPlugins = Schema.fromJsonString(
331 Schema.Struct({ plugins: Schema.Array(Schema.Unknown) }),
332);
333const decodeSyncedPlugin = Schema.decodeUnknownOption(
334 Schema.Struct({
335 pluginId: Schema.String,
336 name: Schema.String,
337 generation: Schema.optional(Schema.Number),
338 }),
339);
340const ACCOUNT_UUID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
341​
342/** Claude compares plugin names case-insensitively. */
343function pluginNameKey(name: string): string {
344 return name.normalize("NFC").toLowerCase();
346​
347/** Claude's folder for a synced row: reserved characters become `_`, trailing dots and spaces go. */
348function syncedPluginDirectoryName(name: string): string {
349 const replaced = name.replace(/[<>:"|?*\\/]/g, "_");
350 let end = replaced.length;
351 while (end > 0 && (replaced[end - 1] === "." || replaced[end - 1] === " ")) end--;
352 return replaced.slice(0, end);
354​
355function isInsideDirectory(path: Path.Path, directory: string, candidate: string): boolean {
356 const relative = path.relative(directory, candidate);
357 return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
359​
360const readPluginManifest = Effect.fn("readPluginManifest")(function* (pluginPath: string) {
361 const fileSystem = yield* FileSystem.FileSystem;
362 const path = yield* Path.Path;
363 return yield* fileSystem
364 .readFileString(path.join(pluginPath, ".claude-plugin", "plugin.json"))
365 .pipe(
366 Effect.flatMap(Schema.decodeUnknownEffect(PluginManifest)),
367 Effect.orElseSucceed(() => undefined),
368 );
369});
370​
371const pluginSkillRoots = Effect.fn("pluginSkillRoots")(function* (
372 installPath: string,
373 scope: ClaudeSkillScope,
374 prefix: string,
375 manifest: typeof PluginManifest.Type | undefined,
376) {
377 const fileSystem = yield* FileSystem.FileSystem;
378 const path = yield* Path.Path;
379 const roots: Array<ClaudeSkillRoot> = [];
380 const defaultDirectory = path.join(installPath, "skills");
381 const hasDefaultDirectory = yield* fileSystem
382 .exists(defaultDirectory)
383 .pipe(Effect.orElseSucceed(() => false));
384 if (hasDefaultDirectory) roots.push({ directory: defaultDirectory, scope, prefix });
385 const declared = manifest?.skills;
386 if (declared === undefined && !hasDefaultDirectory) {
387 const hasRootSkill = yield* fileSystem
388 .exists(path.join(installPath, "SKILL.md"))
389 .pipe(Effect.orElseSucceed(() => false));
390 if (hasRootSkill) roots.push({ directory: installPath, scope, prefix });
391 }
392​
393 const canonicalInstallPath = yield* fileSystem
394 .realPath(installPath)
395 .pipe(Effect.orElseSucceed(() => undefined));
396 for (const relative of typeof declared === "string" ? [declared] : (declared ?? [])) {
397 const directory = path.resolve(installPath, relative);
398 if (!isInsideDirectory(path, installPath, directory) || canonicalInstallPath === undefined) {
399 continue;
400 }
401 const canonicalDirectory = yield* fileSystem
402 .realPath(directory)
403 .pipe(Effect.orElseSucceed(() => undefined));
404 // The native loader rejects manifest roots that escape through a symlink, too.
405 if (
406 canonicalDirectory !== undefined &&
407 isInsideDirectory(path, canonicalInstallPath, canonicalDirectory)
408 ) {
409 roots.push({ directory, scope, prefix });
410 }
411 }
412 return roots;
413});
414​
415/** The `<org>_<account>` folder Claude syncs the signed-in account's claude.ai plugins into. */
416const resolveSyncedPluginBucket = Effect.fn("resolveSyncedPluginBucket")(function* (
417 config: Pick<ClaudeSettings, "homePath">,
418 configDirPath: string,
419 environment: NodeJS.ProcessEnv,
420) {
421 const accountConfigPath = yield* claudeAccountConfigPath(
422 config.homePath.trim() || environment.CLAUDE_CONFIG_DIR?.trim() ? configDirPath : undefined,
423 );
424 const account = yield* readClaudeOauthAccount(accountConfigPath);
425 const organizationId = environment.CLAUDE_CODE_ORGANIZATION_UUID ?? account?.organizationUuid;
426 // A stored claude.ai login names its own account; an injected token uses the env account.
427 const environmentAccountId = environment.CLAUDE_CODE_ACCOUNT_UUID;
428 const accountId =
429 account !== undefined && !environment.CLAUDE_CODE_OAUTH_TOKEN
430 ? typeof account.accountUuid === "string"
431 ? account.accountUuid
432 : undefined
433 : environmentAccountId && ACCOUNT_UUID_PATTERN.test(environmentAccountId)
434 ? environmentAccountId
435 : "unbound";
436 if (
437 !organizationId ||
438 !accountId ||
439 !ACCOUNT_UUID_PATTERN.test(organizationId) ||
440 (accountId !== "unbound" && !ACCOUNT_UUID_PATTERN.test(accountId))
441 ) {
442 return undefined;
443 }
444 return `${organizationId.toLowerCase()}_${accountId.toLowerCase()}`;
445});
446​
447const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* (
448 configDirPath: string,
449 cwd: string | undefined,
450 enabledPlugins: ReadonlyMap<string, boolean>,
451 syncedBucket: string | undefined,
452 environment: NodeJS.ProcessEnv,
453) {
454 const fileSystem = yield* FileSystem.FileSystem;
455 const path = yield* Path.Path;
456 const home = yield* HostProcess.HomeDirectory;
457 const pluginDirectory = environment.CLAUDE_CODE_PLUGIN_CACHE_DIR;
458 const pluginsPath = pluginDirectory
459 ? path.resolve(cwd ?? ".", expandHomePath(pluginDirectory, home))
460 : path.join(configDirPath, "plugins");
461 const installed = yield* fileSystem
462 .readFileString(path.join(pluginsPath, "installed_plugins.json"))
463 .pipe(
464 Effect.flatMap(Schema.decodeUnknownEffect(InstalledPlugins)),
465 Effect.orElseSucceed(() => undefined),
466 );
467 const roots: Array<ClaudeSkillRoot> = [];
468 const claimedPluginNames = new Set<string>();
469 // The CLI's process.cwd() resolves symlinks; registry projectPath values remain lexical.
470 const workspace =
471 cwd === undefined
472 ? undefined
473 : yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => path.resolve(cwd)));
474 // Install records repeat project paths, often hundreds of times per discovery.
475 const projectRepositoryRoots = new Map<string, string | undefined>();
476 const repositoryRoot =
477 workspace === undefined ? undefined : yield* findPluginRepositoryRoot(workspace);
478​
479 for (const [key, entries] of Object.entries(installed?.plugins ?? {}).sort()) {
480 if (enabledPlugins.get(key) !== true) continue;
481 const applicable = yield* Effect.filter(
482 entries.flatMap((entry) => Option.toArray(decodeInstalledPlugin(entry))),
483 (record) =>
484 Effect.gen(function* () {
485 if (record.scope === "user" || record.scope === "managed") return true;
486 if (record.projectPath === undefined || workspace === undefined) return false;
487 const projectPath = path.resolve(record.projectPath);
488 if (projectPath === workspace) return true;
489 if (repositoryRoot === undefined) return false;
490 if (!projectRepositoryRoots.has(projectPath)) {
491 projectRepositoryRoots.set(projectPath, yield* findPluginRepositoryRoot(projectPath));
492 }
493 return projectRepositoryRoots.get(projectPath) === repositoryRoot;
494 }),
495 );
496 // The native loader keeps registry order, preferring the first install that exists.
497 const existing = yield* Effect.findFirst(applicable, (record) =>
498 fileSystem
499 .exists(path.resolve(cwd ?? ".", record.installPath))
500 .pipe(Effect.orElseSucceed(() => false)),
501 );
502 const install = Option.getOrElse(existing, () => applicable[0]);
503 if (!install) continue;
504 const scope = install.scope === "user" || install.scope === "managed" ? "user" : "project";
505 const installPath = path.resolve(cwd ?? ".", install.installPath);
506 const manifest = yield* readPluginManifest(installPath);
507 const prefix = manifest?.name ?? key.split("@")[0];
508 if (!prefix) continue;
509 // A registry record whose install is gone loads nothing and claims no namespace.
510 if (Option.isSome(existing)) claimedPluginNames.add(pluginNameKey(prefix));
511 roots.push(...(yield* pluginSkillRoots(installPath, scope, prefix, manifest)));
512 }
513 if (syncedBucket === undefined) return roots;
514​
515 const syncedPath = path.join(configDirPath, "plugins", "synced");
516 const bucketPath = path.join(syncedPath, syncedBucket);
517 const disabledSyncedPlugins = new Set(
518 [...enabledPlugins].flatMap(([pluginKey, enabled]) =>
519 !enabled && pluginKey.endsWith("@synced") ? [pluginNameKey(pluginKey.slice(0, -7))] : [],
520 ),
521 );
522 const hasBucketMarker = yield* fileSystem
523 .exists(path.join(syncedPath, `.bucket-${syncedBucket}`))
524 .pipe(Effect.orElseSucceed(() => false));
525 if (!hasBucketMarker) return roots;
526 const synced = yield* fileSystem.readFileString(path.join(bucketPath, "manifest.json")).pipe(
527 Effect.flatMap(Schema.decodeUnknownEffect(SyncedPlugins)),
528 Effect.orElseSucceed(() => undefined),
529 );
530 for (const row of synced?.plugins ?? []) {
531 const plugin = Option.getOrUndefined(decodeSyncedPlugin(row));
532 const directoryName = plugin === undefined ? "" : syncedPluginDirectoryName(plugin.name);
533 if (!plugin || !directoryName || directoryName.startsWith(".")) continue;
534 const generation = plugin.generation;
535 const pluginPath = path.join(
536 bucketPath,
537 generation !== undefined && Number.isInteger(generation) && generation >= 2
538 ? `${directoryName}~g${generation}`
539 : directoryName,
540 );
541 const manifest = yield* readPluginManifest(pluginPath);
542 const prefix = manifest?.name ?? directoryName;
543 // An installed plugin of the same name, then the first synced row, holds the namespace.
544 const key = pluginNameKey(prefix);
545 if (claimedPluginNames.has(key) || disabledSyncedPlugins.has(key)) continue;
546 claimedPluginNames.add(key);
547 roots.push(...(yield* pluginSkillRoots(pluginPath, "user", prefix, manifest)));
548 }
549 return roots;
550});
551​
552const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
553 config: Pick<ClaudeSettings, "homePath">,
554 environment: NodeJS.ProcessEnv,
555 cwd?: string,
556): Effect.fn.Return<string, never, Path.Path> {
557 const path = yield* Path.Path;
558 const home = yield* HostProcess.HomeDirectory;
559 const homePath = config.homePath.trim();
560 if (homePath.length > 0) {
561 return path.resolve(expandHomePath(homePath, home));
562 }
563 // Match the spawned CLI: preserve a literal ~ and resolve relative config against workspace cwd.
564 const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
565 if (environmentConfigDir.length > 0) {
566 return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
567 }
568 return path.join(home, ".claude");
569});
570​
571const SettingsEnv = Schema.Struct({
572 ANTHROPIC_BASE_URL: Schema.optional(Schema.String),
573 CLAUDE_CODE_ENTRYPOINT: Schema.optional(Schema.String),
574 // Unquoted JSON values must not fail the decode and drop ANTHROPIC_BASE_URL with them.
575 CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: Schema.optional(Schema.Unknown),
576 CLAUDE_CODE_GATEWAY_MODEL_DISCOVERY_TIMEOUT_MS: Schema.optional(Schema.Unknown),
577});
578const decodeSettingsEnv = Schema.decodeUnknownEffect(
579 fromLenientJson(Schema.Struct({ env: Schema.optional(SettingsEnv) })),
580);
581​
582/** The `env` values T3 Code reads from Claude's user and managed settings; later files win. */
583export const readClaudeSettingsEnv = Effect.fn("readClaudeSettingsEnv")(function* (
584 config: Pick<ClaudeSettings, "homePath">,
585 cwd: string | undefined,
586 environment: NodeJS.ProcessEnv,
587): Effect.fn.Return<typeof SettingsEnv.Type, never, FileSystem.FileSystem | Path.Path> {
588 const fileSystem = yield* FileSystem.FileSystem;
589 const path = yield* Path.Path;
590 const platform = yield* HostProcess.Platform;
591 const configDirPath = yield* resolveClaudeConfigDirPath(config, environment, cwd);
592 const settingsEnv: typeof SettingsEnv.Type = {};
593 for (const settingsPath of claudeSettingsPaths(
594 path,
595 configDirPath,
596 undefined,
597 platform,
598 environment,
599 )) {
600 const contents = yield* fileSystem
601 .readFileString(settingsPath)
602 .pipe(Effect.orElseSucceed(() => undefined));
603 if (contents === undefined) continue;
604 const parsed = yield* decodeSettingsEnv(contents).pipe(Effect.orElseSucceed(() => undefined));
605 Object.assign(settingsEnv, parsed?.env);
606 }
607 return settingsEnv;
608});
609​
610/** The host of an `ANTHROPIC_BASE_URL` that is not Anthropic's own API. */
611export function customClaudeApiEndpointHost(baseUrl: string | undefined): string | undefined {
612 const endpoint = URL.parse(baseUrl?.trim() ?? "");
613 return endpoint !== null &&
614 (endpoint.protocol === "http:" || endpoint.protocol === "https:") &&
615 endpoint.hostname !== "" &&
616 endpoint.hostname !== "api.anthropic.com"
617 ? endpoint.hostname
618 : undefined;
620​
621// Claude's --add-dir is repeatable and variadic; parseCliArgs keeps only one value.
622export function claudeLaunchArgDirectories(launchArgs?: string): ReadonlyArray<string> {
623 const directories: string[] = [];
624 let collecting = false;
625 for (const token of tokenizeCliArgs(launchArgs)) {
626 if (token === "--") break;
627 if (token === "--add-dir") {
628 collecting = true;
629 } else if (token.startsWith("--add-dir=")) {
630 directories.push(token.slice("--add-dir=".length));
631 collecting = false;
632 } else if (token.startsWith("-")) {
633 collecting = false;
634 } else if (collecting) {
635 directories.push(token);
636 }
637 }
638 return directories;
640​
641/** First name wins: managed skills, then user skills, then project skills. */
642export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
643 config: Pick<ClaudeSettings, "homePath"> & Partial<Pick<ClaudeSettings, "launchArgs">>,
644 cwd?: string,
645 environment?: NodeJS.ProcessEnv,
646): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
647 const fileSystem = yield* FileSystem.FileSystem;
648 const path = yield* Path.Path;
649 const env = environment ?? process.env;
650 const configDirPath = yield* resolveClaudeConfigDirPath(config, env, cwd);
651 const { skillOverrides, enabledPlugins, syncedPluginsHidden } = yield* readSkillSettings(
652 configDirPath,
653 cwd,
654 env,
655 );
656 const managedDirectory = claudeManagedDirectory(path, yield* HostProcess.Platform, env);
657 // Most installs have no synced folder; skip reading `.claude.json` for them.
658 const hasSyncedPlugins =
659 !syncedPluginsHidden &&
660 (yield* fileSystem
661 .exists(path.join(configDirPath, "plugins", "synced"))
662 .pipe(Effect.orElseSucceed(() => false)));
663 const syncedBucket = hasSyncedPlugins
664 ? yield* resolveSyncedPluginBucket(config, configDirPath, env)
665 : undefined;
666​
667 const roots: ReadonlyArray<ClaudeSkillRoot> = [
668 ...(managedDirectory
669 ? [{ directory: path.join(managedDirectory, ".claude", "skills"), scope: "user" as const }]
670 : []),
671 { directory: path.join(configDirPath, "skills"), scope: "user" },
672 ...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
673 ...claudeLaunchArgDirectories(config.launchArgs)
674 .filter((directory) => directory && (cwd || path.isAbsolute(directory)))
675 .map((directory) => ({
676 directory: path.join(path.resolve(cwd ?? ".", directory), ".claude", "skills"),
677 scope: "project" as const,
678 })),
679 ...(yield* discoverPluginSkillRoots(configDirPath, cwd, enabledPlugins, syncedBucket, env)),
680 ];
681​
682 const skillsByName = new Map<string, ServerProviderSkill>();
683 for (const root of roots) {
684 const singleSkill =
685 root.prefix !== undefined &&
686 (yield* fileSystem
687 .exists(path.join(root.directory, "SKILL.md"))
688 .pipe(Effect.orElseSucceed(() => false)));
689 const entries = singleSkill
690 ? [path.basename(root.directory)]
691 : yield* fileSystem
692 .readDirectory(root.directory)
693 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
694​
695 for (const entry of [...entries].sort()) {
696 const skillPath = singleSkill
697 ? path.join(root.directory, "SKILL.md")
698 : path.join(root.directory, entry, "SKILL.md");
699 const contents = yield* fileSystem
700 .readFileString(skillPath)
701 .pipe(Effect.orElseSucceed(() => undefined));
702 if (contents === undefined) {
703 continue;
704 }
705​
706 const frontmatter = parseSkillFrontmatter(contents);
707 if (frontmatter.kind === "malformed") {
708 continue;
709 }
710​
711 const directoryName = entry.trim();
712 if (!directoryName) continue;
713 let name = directoryName;
714 if (root.prefix) {
715 // Native folder skills use their folder; only a single SKILL.md uses its name field.
716 const declaredName = singleSkill && frontmatter.kind === "parsed" ? frontmatter.name : "";
717 const unprefixedName = declaredName?.startsWith(`${root.prefix}:`)
718 ? declaredName.slice(root.prefix.length + 1)
719 : declaredName;
720 name = `${root.prefix}:${(unprefixedName || entry).replace(/[^a-zA-Z0-9_-]/g, "-")}`;
721 // Advertise only exact native names the shared composer grammar can invoke.
722 const [mention] = `$${name}`.matchAll(SKILL_MENTION_PATTERN);
723 if (mention?.[2] !== name) continue;
724 }
725​
726 if (skillsByName.has(name)) {
727 continue;
728 }
729​
730 const override = root.prefix ? undefined : skillOverrides.get(name);
731 const userInvocationOnly =
732 (frontmatter.kind === "parsed" && frontmatter.userInvocationOnly === true) ||
733 override?.userInvocationOnly === true;
734 skillsByName.set(name, {
735 name,
736 path: skillPath,
737 enabled: override?.enabled ?? true,
738 scope: root.scope,
739 ...(frontmatter.kind === "parsed" && frontmatter.description
740 ? { description: frontmatter.description }
741 : {}),
742 ...(userInvocationOnly ? { userInvocationOnly: true } : {}),
743 ...(frontmatter.kind === "parsed" && frontmatter.userInvocable === false
744 ? { userInvocable: false }
745 : {}),
746 });
747 }
748 }
749​
750 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
751});