The best way to control Claude Code, Codex and more from any computer or phone

main
ts 884 lines 34.4 KB
Raw
1 import type { ClaudeSettings, ServerProviderSkill } from "@t3tools/contracts";
2 import * as Effect from "effect/Effect";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Path from "effect/Path";
5 import * as Option from "effect/Option";
6 import * as Schema from "effect/Schema";
7 import * as HostProcess from "@t3tools/shared/HostProcess";
8 import { tokenizeCliArgs } from "@t3tools/shared/cliArgs";
9 import { fromLenientJson } from "@t3tools/shared/schemaJson";
10 import { SKILL_MENTION_PATTERN } from "@t3tools/shared/composerInlineTokens";
11 import { parse as parseYamlDocument } from "yaml";
12
13 import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
14
15 import { claudeAccountConfigPath, readClaudeOauthAccount } from "../claudeResetCredits.ts";
16
17 type ClaudeSkillScope = "user" | "project";
18
19 type ClaudeSkillRoot = {
20 readonly directory: string;
21 readonly scope: ClaudeSkillScope;
22 readonly prefix?: string;
23 };
24
25 const FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/;
26
27 type 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. */
39 function 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
61 function 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.
110 function 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
117 function 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
132 function 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. */
147 function 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.
170 const 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
191 const 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 */
234 const 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.
238 const 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 );
245 const decodeSkillSettings = Schema.decodeUnknownEffect(SkillSettings);
246
247 type SkillOverride = {
248 readonly enabled: boolean;
249 readonly userInvocationOnly: boolean;
250 };
251
252 function 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
264 const 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
333 const InstalledPlugins = Schema.fromJsonString(
334 Schema.Struct({ plugins: Schema.Record(Schema.String, Schema.Array(Schema.Unknown)) }),
335 );
336 const 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 );
343 const 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 );
350
351 const SyncedPlugins = Schema.fromJsonString(
352 Schema.Struct({ plugins: Schema.Array(Schema.Unknown) }),
353 );
354 const decodeSyncedPlugin = Schema.decodeUnknownOption(
355 Schema.Struct({
356 pluginId: Schema.String,
357 name: Schema.String,
358 generation: Schema.optional(Schema.Number),
359 }),
360 );
361 const ACCOUNT_UUID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
362
363 /** Claude compares plugin names case-insensitively. */
364 function pluginNameKey(name: string): string {
365 return name.normalize("NFC").toLowerCase();
366 }
367
368 /** Claude's folder for a synced row: reserved characters become `_`, trailing dots and spaces go. */
369 function syncedPluginDirectoryName(name: string): string {
370 const replaced = name.replace(/[<>:"|?*\\/]/g, "_");
371 let end = replaced.length;
372 while (end > 0 && (replaced[end - 1] === "." || replaced[end - 1] === " ")) end--;
373 return replaced.slice(0, end);
374 }
375
376 function isInsideDirectory(path: Path.Path, directory: string, candidate: string): boolean {
377 const relative = path.relative(directory, candidate);
378 return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
379 }
380
381 const readPluginManifest = Effect.fn("readPluginManifest")(function* (pluginPath: string) {
382 const fileSystem = yield* FileSystem.FileSystem;
383 const path = yield* Path.Path;
384 return yield* fileSystem
385 .readFileString(path.join(pluginPath, ".claude-plugin", "plugin.json"))
386 .pipe(
387 Effect.flatMap(Schema.decodeUnknownEffect(PluginManifest)),
388 Effect.orElseSucceed(() => undefined),
389 );
390 });
391
392 const pluginSkillRoots = Effect.fn("pluginSkillRoots")(function* (
393 installPath: string,
394 scope: ClaudeSkillScope,
395 prefix: string,
396 manifest: typeof PluginManifest.Type | undefined,
397 ) {
398 const fileSystem = yield* FileSystem.FileSystem;
399 const path = yield* Path.Path;
400 const roots: Array<ClaudeSkillRoot> = [];
401 const defaultDirectory = path.join(installPath, "skills");
402 const hasDefaultDirectory = yield* fileSystem
403 .exists(defaultDirectory)
404 .pipe(Effect.orElseSucceed(() => false));
405 if (hasDefaultDirectory) roots.push({ directory: defaultDirectory, scope, prefix });
406 const declared = manifest?.skills;
407 if (declared === undefined && !hasDefaultDirectory) {
408 const hasRootSkill = yield* fileSystem
409 .exists(path.join(installPath, "SKILL.md"))
410 .pipe(Effect.orElseSucceed(() => false));
411 if (hasRootSkill) roots.push({ directory: installPath, scope, prefix });
412 }
413
414 const canonicalInstallPath = yield* fileSystem
415 .realPath(installPath)
416 .pipe(Effect.orElseSucceed(() => undefined));
417 for (const relative of typeof declared === "string" ? [declared] : (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 // The native loader rejects manifest roots that escape through a symlink, too.
426 if (
427 canonicalDirectory !== undefined &&
428 isInsideDirectory(path, canonicalInstallPath, canonicalDirectory)
429 ) {
430 roots.push({ directory, scope, prefix });
431 }
432 }
433 return roots;
434 });
435
436 /** The `<org>_<account>` folder Claude syncs the signed-in account's claude.ai plugins into. */
437 const resolveSyncedPluginBucket = Effect.fn("resolveSyncedPluginBucket")(function* (
438 config: Pick<ClaudeSettings, "homePath">,
439 configDirPath: string,
440 environment: NodeJS.ProcessEnv,
441 ) {
442 const accountConfigPath = yield* claudeAccountConfigPath(
443 config.homePath.trim() || environment.CLAUDE_CONFIG_DIR?.trim() ? configDirPath : undefined,
444 );
445 const account = yield* readClaudeOauthAccount(accountConfigPath);
446 const organizationId = environment.CLAUDE_CODE_ORGANIZATION_UUID ?? account?.organizationUuid;
447 // A stored claude.ai login names its own account; an injected token uses the env account.
448 const environmentAccountId = environment.CLAUDE_CODE_ACCOUNT_UUID;
449 const accountId =
450 account !== undefined && !environment.CLAUDE_CODE_OAUTH_TOKEN
451 ? typeof account.accountUuid === "string"
452 ? account.accountUuid
453 : undefined
454 : environmentAccountId && ACCOUNT_UUID_PATTERN.test(environmentAccountId)
455 ? environmentAccountId
456 : "unbound";
457 if (
458 !organizationId ||
459 !accountId ||
460 !ACCOUNT_UUID_PATTERN.test(organizationId) ||
461 (accountId !== "unbound" && !ACCOUNT_UUID_PATTERN.test(accountId))
462 ) {
463 return undefined;
464 }
465 return `${organizationId.toLowerCase()}_${accountId.toLowerCase()}`;
466 });
467
468 /** A plugin folder itself, or else the manifest-bearing plugins directly inside it. */
469 const expandInlinePluginDirectory = Effect.fn("expandInlinePluginDirectory")(function* (
470 directory: string,
471 ) {
472 const fileSystem = yield* FileSystem.FileSystem;
473 const path = yield* Path.Path;
474 const exists = (candidate: string) =>
475 fileSystem.exists(candidate).pipe(Effect.orElseSucceed(() => false));
476 for (const component of [path.join(".claude-plugin", "plugin.json"), "skills", "SKILL.md"]) {
477 if (yield* exists(path.join(directory, component))) return [directory];
478 }
479 const children = yield* fileSystem
480 .readDirectory(directory)
481 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
482 return yield* Effect.filter(
483 [...children].sort().map((child) => path.join(directory, child)),
484 (child) => exists(path.join(child, ".claude-plugin", "plugin.json")),
485 );
486 });
487
488 /**
489 * Plugin folders Claude Code loads inline, from --plugin-dir launch arguments and then
490 * CLAUDE_CODE_PLUGIN_DIRS, and their plugin names.
491 */
492 const discoverInlinePluginSkillRoots = Effect.fn("discoverInlinePluginSkillRoots")(function* (
493 launchArgPluginDirectories: ReadonlyArray<string>,
494 environmentPluginDirectories: string | undefined,
495 cwd: string | undefined,
496 enabledPlugins: ReadonlyMap<string, boolean>,
497 managedPluginNames: ReadonlySet<string>,
498 ) {
499 const path = yield* Path.Path;
500 const home = yield* HostProcess.HomeDirectory;
501 const platform = yield* HostProcess.Platform;
502 const roots: Array<ClaudeSkillRoot> = [];
503 const names = new Set<string>();
504 const seen = new Set<string>();
505 const directories = [
506 // Claude resolves a relative --plugin-dir against its cwd and expands no `~` in it.
507 ...launchArgPluginDirectories
508 .filter((directory) => directory && (cwd || path.isAbsolute(directory)))
509 .map((directory) => path.resolve(cwd ?? ".", directory)),
510 // Claude skips relative CLAUDE_CODE_PLUGIN_DIRS entries rather than resolving them.
511 ...(environmentPluginDirectories ?? "")
512 .split(platform === "win32" ? ";" : ":")
513 .map((entry) => expandHomePath(entry.trim(), home))
514 .filter((directory) => directory && path.isAbsolute(directory))
515 .map((directory) => path.resolve(directory)),
516 ];
517 for (const directory of directories) {
518 for (const installPath of yield* expandInlinePluginDirectory(directory)) {
519 if (seen.has(installPath)) continue;
520 seen.add(installPath);
521 const manifest = yield* readPluginManifest(installPath);
522 const prefix = manifest?.name ?? path.basename(installPath);
523 // A `<name>@inline` setting wins; otherwise the manifest's `defaultEnabled` decides.
524 const setting = enabledPlugins.get(`${prefix}@inline`);
525 if (setting === false || (setting === undefined && manifest?.defaultEnabled === false)) {
526 continue;
527 }
528 // Managed enabledPlugins entries, true or false, lock the name against inline copies.
529 if (managedPluginNames.has(pluginNameKey(prefix))) continue;
530 names.add(pluginNameKey(prefix));
531 roots.push(...(yield* pluginSkillRoots(installPath, "user", prefix, manifest)));
532 }
533 }
534 return { roots, names };
535 });
536
537 const discoverPluginSkillRoots = Effect.fn("discoverPluginSkillRoots")(function* (
538 configDirPath: string,
539 cwd: string | undefined,
540 enabledPlugins: ReadonlyMap<string, boolean>,
541 inlinePluginNames: ReadonlySet<string>,
542 syncedBucket: string | undefined,
543 environment: NodeJS.ProcessEnv,
544 ) {
545 const fileSystem = yield* FileSystem.FileSystem;
546 const path = yield* Path.Path;
547 const home = yield* HostProcess.HomeDirectory;
548 const pluginDirectory = environment.CLAUDE_CODE_PLUGIN_CACHE_DIR;
549 const pluginsPath = pluginDirectory
550 ? path.resolve(cwd ?? ".", expandHomePath(pluginDirectory, home))
551 : path.join(configDirPath, "plugins");
552 const installed = yield* fileSystem
553 .readFileString(path.join(pluginsPath, "installed_plugins.json"))
554 .pipe(
555 Effect.flatMap(Schema.decodeUnknownEffect(InstalledPlugins)),
556 Effect.orElseSucceed(() => undefined),
557 );
558 const roots: Array<ClaudeSkillRoot> = [];
559 // An enabled inline plugin replaces installed and synced plugins of the same name.
560 const claimedPluginNames = new Set(inlinePluginNames);
561 // The CLI's process.cwd() resolves symlinks; registry projectPath values remain lexical.
562 const workspace =
563 cwd === undefined
564 ? undefined
565 : yield* fileSystem.realPath(cwd).pipe(Effect.orElseSucceed(() => path.resolve(cwd)));
566 // Install records repeat project paths, often hundreds of times per discovery.
567 const projectRepositoryRoots = new Map<string, string | undefined>();
568 const repositoryRoot =
569 workspace === undefined ? undefined : yield* findPluginRepositoryRoot(workspace);
570
571 for (const [key, entries] of Object.entries(installed?.plugins ?? {}).sort()) {
572 if (enabledPlugins.get(key) !== true) continue;
573 const applicable = yield* Effect.filter(
574 entries.flatMap((entry) => Option.toArray(decodeInstalledPlugin(entry))),
575 (record) =>
576 Effect.gen(function* () {
577 if (record.scope === "user" || record.scope === "managed") return true;
578 if (record.projectPath === undefined || workspace === undefined) return false;
579 const projectPath = path.resolve(record.projectPath);
580 if (projectPath === workspace) return true;
581 if (repositoryRoot === undefined) return false;
582 if (!projectRepositoryRoots.has(projectPath)) {
583 projectRepositoryRoots.set(projectPath, yield* findPluginRepositoryRoot(projectPath));
584 }
585 return projectRepositoryRoots.get(projectPath) === repositoryRoot;
586 }),
587 );
588 // The native loader keeps registry order, preferring the first install that exists.
589 const existing = yield* Effect.findFirst(applicable, (record) =>
590 fileSystem
591 .exists(path.resolve(cwd ?? ".", record.installPath))
592 .pipe(Effect.orElseSucceed(() => false)),
593 );
594 const install = Option.getOrElse(existing, () => applicable[0]);
595 if (!install) continue;
596 const scope = install.scope === "user" || install.scope === "managed" ? "user" : "project";
597 const installPath = path.resolve(cwd ?? ".", install.installPath);
598 const manifest = yield* readPluginManifest(installPath);
599 const prefix = manifest?.name ?? key.split("@")[0];
600 if (!prefix || inlinePluginNames.has(pluginNameKey(prefix))) continue;
601 // A registry record whose install is gone loads nothing and claims no namespace.
602 if (Option.isSome(existing)) claimedPluginNames.add(pluginNameKey(prefix));
603 roots.push(...(yield* pluginSkillRoots(installPath, scope, prefix, manifest)));
604 }
605 if (syncedBucket === undefined) return roots;
606
607 const syncedPath = path.join(configDirPath, "plugins", "synced");
608 const bucketPath = path.join(syncedPath, syncedBucket);
609 const disabledSyncedPlugins = new Set(
610 [...enabledPlugins].flatMap(([pluginKey, enabled]) =>
611 !enabled && pluginKey.endsWith("@synced") ? [pluginNameKey(pluginKey.slice(0, -7))] : [],
612 ),
613 );
614 const hasBucketMarker = yield* fileSystem
615 .exists(path.join(syncedPath, `.bucket-${syncedBucket}`))
616 .pipe(Effect.orElseSucceed(() => false));
617 if (!hasBucketMarker) return roots;
618 const synced = yield* fileSystem.readFileString(path.join(bucketPath, "manifest.json")).pipe(
619 Effect.flatMap(Schema.decodeUnknownEffect(SyncedPlugins)),
620 Effect.orElseSucceed(() => undefined),
621 );
622 for (const row of synced?.plugins ?? []) {
623 const plugin = Option.getOrUndefined(decodeSyncedPlugin(row));
624 const directoryName = plugin === undefined ? "" : syncedPluginDirectoryName(plugin.name);
625 if (!plugin || !directoryName || directoryName.startsWith(".")) continue;
626 const generation = plugin.generation;
627 const pluginPath = path.join(
628 bucketPath,
629 generation !== undefined && Number.isInteger(generation) && generation >= 2
630 ? `${directoryName}~g${generation}`
631 : directoryName,
632 );
633 const manifest = yield* readPluginManifest(pluginPath);
634 const prefix = manifest?.name ?? directoryName;
635 // An installed plugin of the same name, then the first synced row, holds the namespace.
636 const key = pluginNameKey(prefix);
637 if (claimedPluginNames.has(key) || disabledSyncedPlugins.has(key)) continue;
638 claimedPluginNames.add(key);
639 roots.push(...(yield* pluginSkillRoots(pluginPath, "user", prefix, manifest)));
640 }
641 return roots;
642 });
643
644 const resolveClaudeConfigDirPath = Effect.fn("resolveClaudeConfigDirPath")(function* (
645 config: Pick<ClaudeSettings, "homePath">,
646 environment: NodeJS.ProcessEnv,
647 cwd?: string,
648 ): Effect.fn.Return<string, never, Path.Path> {
649 const path = yield* Path.Path;
650 const home = yield* HostProcess.HomeDirectory;
651 const homePath = config.homePath.trim();
652 if (homePath.length > 0) {
653 return path.resolve(expandHomePath(homePath, home));
654 }
655 // Match the spawned CLI: preserve a literal ~ and resolve relative config against workspace cwd.
656 const environmentConfigDir = environment.CLAUDE_CONFIG_DIR?.trim() ?? "";
657 if (environmentConfigDir.length > 0) {
658 return cwd ? path.resolve(cwd, environmentConfigDir) : path.resolve(environmentConfigDir);
659 }
660 return path.join(home, ".claude");
661 });
662
663 const SettingsEnv = Schema.Struct({
664 ANTHROPIC_BASE_URL: Schema.optional(Schema.String),
665 CLAUDE_CODE_ENTRYPOINT: Schema.optional(Schema.String),
666 CLAUDE_CODE_PLUGIN_DIRS: Schema.optional(Schema.String),
667 // Unquoted JSON values must not fail the decode and drop ANTHROPIC_BASE_URL with them.
668 CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY: Schema.optional(Schema.Unknown),
669 CLAUDE_CODE_GATEWAY_MODEL_DISCOVERY_TIMEOUT_MS: Schema.optional(Schema.Unknown),
670 });
671 const decodeSettingsEnv = Schema.decodeUnknownEffect(
672 fromLenientJson(Schema.Struct({ env: Schema.optional(SettingsEnv) })),
673 );
674
675 /** The `env` values T3 Code reads from Claude's user and managed settings; later files win. */
676 export const readClaudeSettingsEnv = Effect.fn("readClaudeSettingsEnv")(function* (
677 config: Pick<ClaudeSettings, "homePath">,
678 cwd: string | undefined,
679 environment: NodeJS.ProcessEnv,
680 ): Effect.fn.Return<typeof SettingsEnv.Type, never, FileSystem.FileSystem | Path.Path> {
681 const fileSystem = yield* FileSystem.FileSystem;
682 const path = yield* Path.Path;
683 const platform = yield* HostProcess.Platform;
684 const configDirPath = yield* resolveClaudeConfigDirPath(config, environment, cwd);
685 const settingsEnv: typeof SettingsEnv.Type = {};
686 for (const settingsPath of claudeSettingsPaths(
687 path,
688 configDirPath,
689 undefined,
690 platform,
691 environment,
692 )) {
693 const contents = yield* fileSystem
694 .readFileString(settingsPath)
695 .pipe(Effect.orElseSucceed(() => undefined));
696 if (contents === undefined) continue;
697 const parsed = yield* decodeSettingsEnv(contents).pipe(Effect.orElseSucceed(() => undefined));
698 Object.assign(settingsEnv, parsed?.env);
699 }
700 return settingsEnv;
701 });
702
703 /** The host of an `ANTHROPIC_BASE_URL` that is not Anthropic's own API. */
704 export function customClaudeApiEndpointHost(baseUrl: string | undefined): string | undefined {
705 const endpoint = URL.parse(baseUrl?.trim() ?? "");
706 return endpoint !== null &&
707 (endpoint.protocol === "http:" || endpoint.protocol === "https:") &&
708 endpoint.hostname !== "" &&
709 endpoint.hostname !== "api.anthropic.com"
710 ? endpoint.hostname
711 : undefined;
712 }
713
714 // Claude's --add-dir is repeatable and variadic; parseCliArgs keeps only one value.
715 export function claudeLaunchArgDirectories(launchArgs?: string): ReadonlyArray<string> {
716 const directories: string[] = [];
717 let collecting = false;
718 for (const token of tokenizeCliArgs(launchArgs)) {
719 if (token === "--") break;
720 if (token === "--add-dir") {
721 collecting = true;
722 } else if (token.startsWith("--add-dir=")) {
723 directories.push(token.slice("--add-dir=".length));
724 collecting = false;
725 } else if (token.startsWith("-")) {
726 collecting = false;
727 } else if (collecting) {
728 directories.push(token);
729 }
730 }
731 return directories;
732 }
733
734 // The Claude CLI takes the next token as this flag's value even when it starts with `--`.
735 export const claudeLaunchArgParseOptions = { valueFlags: ["append-system-prompt"] };
736
737 // Claude's --plugin-dir is repeatable; parseCliArgs keeps only the last one.
738 export function claudeLaunchArgPluginDirectories(launchArgs?: string): ReadonlyArray<string> {
739 const tokens = tokenizeCliArgs(launchArgs);
740 const directories: string[] = [];
741 for (let index = 0; index < tokens.length && tokens[index] !== "--"; index++) {
742 const token = tokens[index]!;
743 if (!token.startsWith("--") || token.includes("=")) {
744 if (token.startsWith("--plugin-dir=")) directories.push(token.slice("--plugin-dir=".length));
745 continue;
746 }
747 const next = tokens[index + 1];
748 const takesNext =
749 next !== undefined &&
750 (!next.startsWith("--") || claudeLaunchArgParseOptions.valueFlags.includes(token.slice(2)));
751 if (!takesNext) continue;
752 if (token === "--plugin-dir") directories.push(next);
753 index++;
754 }
755 return directories;
756 }
757
758 /** First name wins: managed skills, then user skills, then project skills. */
759 export const discoverClaudeSkills = Effect.fn("discoverClaudeSkills")(function* (
760 config: Pick<ClaudeSettings, "homePath"> & Partial<Pick<ClaudeSettings, "launchArgs">>,
761 cwd?: string,
762 environment?: NodeJS.ProcessEnv,
763 ): Effect.fn.Return<ReadonlyArray<ServerProviderSkill>, never, FileSystem.FileSystem | Path.Path> {
764 const fileSystem = yield* FileSystem.FileSystem;
765 const path = yield* Path.Path;
766 const env = environment ?? process.env;
767 const configDirPath = yield* resolveClaudeConfigDirPath(config, env, cwd);
768 const { skillOverrides, enabledPlugins, managedPluginNames, syncedPluginsHidden } =
769 yield* readSkillSettings(configDirPath, cwd, env);
770 const managedDirectory = claudeManagedDirectory(path, yield* HostProcess.Platform, env);
771 // Most installs have no synced folder; skip reading `.claude.json` for them.
772 const hasSyncedPlugins =
773 !syncedPluginsHidden &&
774 (yield* fileSystem
775 .exists(path.join(configDirPath, "plugins", "synced"))
776 .pipe(Effect.orElseSucceed(() => false)));
777 const syncedBucket = hasSyncedPlugins
778 ? yield* resolveSyncedPluginBucket(config, configDirPath, env)
779 : undefined;
780 // Claude applies its settings `env` over the inherited environment.
781 const inlinePluginDirectories =
782 (yield* readClaudeSettingsEnv(config, cwd, env)).CLAUDE_CODE_PLUGIN_DIRS ??
783 env.CLAUDE_CODE_PLUGIN_DIRS;
784 const inlinePlugins = yield* discoverInlinePluginSkillRoots(
785 claudeLaunchArgPluginDirectories(config.launchArgs),
786 inlinePluginDirectories,
787 cwd,
788 enabledPlugins,
789 managedPluginNames,
790 );
791
792 const roots: ReadonlyArray<ClaudeSkillRoot> = [
793 ...(managedDirectory
794 ? [{ directory: path.join(managedDirectory, ".claude", "skills"), scope: "user" as const }]
795 : []),
796 { directory: path.join(configDirPath, "skills"), scope: "user" },
797 ...(cwd ? [{ directory: path.join(cwd, ".claude", "skills"), scope: "project" as const }] : []),
798 ...claudeLaunchArgDirectories(config.launchArgs)
799 .filter((directory) => directory && (cwd || path.isAbsolute(directory)))
800 .map((directory) => ({
801 directory: path.join(path.resolve(cwd ?? ".", directory), ".claude", "skills"),
802 scope: "project" as const,
803 })),
804 ...inlinePlugins.roots,
805 ...(yield* discoverPluginSkillRoots(
806 configDirPath,
807 cwd,
808 enabledPlugins,
809 inlinePlugins.names,
810 syncedBucket,
811 env,
812 )),
813 ];
814
815 const skillsByName = new Map<string, ServerProviderSkill>();
816 for (const root of roots) {
817 const singleSkill =
818 root.prefix !== undefined &&
819 (yield* fileSystem
820 .exists(path.join(root.directory, "SKILL.md"))
821 .pipe(Effect.orElseSucceed(() => false)));
822 const entries = singleSkill
823 ? [path.basename(root.directory)]
824 : yield* fileSystem
825 .readDirectory(root.directory)
826 .pipe(Effect.orElseSucceed((): ReadonlyArray<string> => []));
827
828 for (const entry of [...entries].sort()) {
829 const skillPath = singleSkill
830 ? path.join(root.directory, "SKILL.md")
831 : path.join(root.directory, entry, "SKILL.md");
832 const contents = yield* fileSystem
833 .readFileString(skillPath)
834 .pipe(Effect.orElseSucceed(() => undefined));
835 if (contents === undefined) {
836 continue;
837 }
838
839 const frontmatter = parseSkillFrontmatter(contents);
840 if (frontmatter.kind === "malformed") {
841 continue;
842 }
843
844 const directoryName = entry.trim();
845 if (!directoryName) continue;
846 let name = directoryName;
847 if (root.prefix) {
848 // Native folder skills use their folder; only a single SKILL.md uses its name field.
849 const declaredName = singleSkill && frontmatter.kind === "parsed" ? frontmatter.name : "";
850 const unprefixedName = declaredName?.startsWith(`${root.prefix}:`)
851 ? declaredName.slice(root.prefix.length + 1)
852 : declaredName;
853 name = `${root.prefix}:${(unprefixedName || entry).replace(/[^a-zA-Z0-9_-]/g, "-")}`;
854 // Advertise only exact native names the shared composer grammar can invoke.
855 const [mention] = `$${name}`.matchAll(SKILL_MENTION_PATTERN);
856 if (mention?.[2] !== name) continue;
857 }
858
859 if (skillsByName.has(name)) {
860 continue;
861 }
862
863 const override = root.prefix ? undefined : skillOverrides.get(name);
864 const userInvocationOnly =
865 (frontmatter.kind === "parsed" && frontmatter.userInvocationOnly === true) ||
866 override?.userInvocationOnly === true;
867 skillsByName.set(name, {
868 name,
869 path: skillPath,
870 enabled: override?.enabled ?? true,
871 scope: root.scope,
872 ...(frontmatter.kind === "parsed" && frontmatter.description
873 ? { description: frontmatter.description }
874 : {}),
875 ...(userInvocationOnly ? { userInvocationOnly: true } : {}),
876 ...(frontmatter.kind === "parsed" && frontmatter.userInvocable === false
877 ? { userInvocable: false }
878 : {}),
879 });
880 }
881 }
882
883 return [...skillsByName.values()].sort((left, right) => left.name.localeCompare(right.name));
884 });