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