File size: 30,541 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 | import memoize from 'lodash-es/memoize.js'
import { basename, dirname, join } from 'path'
import { getInlinePlugins, getSessionId } from '../../bootstrap/state.js'
import type { Command } from '../../types/command.js'
import { getPluginErrorMessage } from '../../types/plugin.js'
import {
parseArgumentNames,
substituteArguments,
} from '../argumentSubstitution.js'
import { logForDebugging } from '../debug.js'
import { EFFORT_LEVELS, parseEffortValue } from '../effort.js'
import { isBareMode } from '../envUtils.js'
import { isENOENT } from '../errors.js'
import {
coerceDescriptionToString,
type FrontmatterData,
parseBooleanFrontmatter,
parseFrontmatter,
parseShellFrontmatter,
} from '../frontmatterParser.js'
import { getFsImplementation, isDuplicatePath } from '../fsOperations.js'
import {
extractDescriptionFromMarkdown,
parseSlashCommandToolsFromFrontmatter,
} from '../markdownConfigLoader.js'
import { parseUserSpecifiedModel } from '../model/model.js'
import { executeShellCommandsInPrompt } from '../promptShellExecution.js'
import { loadAllPluginsCacheOnly } from './pluginLoader.js'
import {
loadPluginOptions,
substitutePluginVariables,
substituteUserConfigInContent,
} from './pluginOptionsStorage.js'
import type { CommandMetadata, PluginManifest } from './schemas.js'
import { walkPluginMarkdown } from './walkPluginMarkdown.js'
// Similar to MarkdownFile but for plugin sources
type PluginMarkdownFile = {
filePath: string
baseDir: string
frontmatter: FrontmatterData
content: string
}
// Configuration for loading commands or skills
type LoadConfig = {
isSkillMode: boolean // true when loading from skills/ directory
}
/**
* Check if a file path is a skill file (SKILL.md)
*/
function isSkillFile(filePath: string): boolean {
return /^skill\.md$/i.test(basename(filePath))
}
/**
* Get command name from file path, handling both regular files and skills
*/
function getCommandNameFromFile(
filePath: string,
baseDir: string,
pluginName: string,
): string {
const isSkill = isSkillFile(filePath)
if (isSkill) {
// For skills, use the parent directory name
const skillDirectory = dirname(filePath)
const parentOfSkillDir = dirname(skillDirectory)
const commandBaseName = basename(skillDirectory)
// Build namespace from parent of skill directory
const relativePath = parentOfSkillDir.startsWith(baseDir)
? parentOfSkillDir.slice(baseDir.length).replace(/^\//, '')
: ''
const namespace = relativePath ? relativePath.split('/').join(':') : ''
return namespace
? `${pluginName}:${namespace}:${commandBaseName}`
: `${pluginName}:${commandBaseName}`
} else {
// For regular files, use filename without .md
const fileDirectory = dirname(filePath)
const commandBaseName = basename(filePath).replace(/\.md$/, '')
// Build namespace from file directory
const relativePath = fileDirectory.startsWith(baseDir)
? fileDirectory.slice(baseDir.length).replace(/^\//, '')
: ''
const namespace = relativePath ? relativePath.split('/').join(':') : ''
return namespace
? `${pluginName}:${namespace}:${commandBaseName}`
: `${pluginName}:${commandBaseName}`
}
}
/**
* Recursively collects all markdown files from a directory
*/
async function collectMarkdownFiles(
dirPath: string,
baseDir: string,
loadedPaths: Set<string>,
): Promise<PluginMarkdownFile[]> {
const files: PluginMarkdownFile[] = []
const fs = getFsImplementation()
await walkPluginMarkdown(
dirPath,
async fullPath => {
if (isDuplicatePath(fs, fullPath, loadedPaths)) return
const content = await fs.readFile(fullPath, { encoding: 'utf-8' })
const { frontmatter, content: markdownContent } = parseFrontmatter(
content,
fullPath,
)
files.push({
filePath: fullPath,
baseDir,
frontmatter,
content: markdownContent,
})
},
{ stopAtSkillDir: true, logLabel: 'commands' },
)
return files
}
/**
* Transforms plugin markdown files to handle skill directories
*/
function transformPluginSkillFiles(
files: PluginMarkdownFile[],
): PluginMarkdownFile[] {
const filesByDir = new Map<string, PluginMarkdownFile[]>()
for (const file of files) {
const dir = dirname(file.filePath)
const dirFiles = filesByDir.get(dir) ?? []
dirFiles.push(file)
filesByDir.set(dir, dirFiles)
}
const result: PluginMarkdownFile[] = []
for (const [dir, dirFiles] of filesByDir) {
const skillFiles = dirFiles.filter(f => isSkillFile(f.filePath))
if (skillFiles.length > 0) {
// Use the first skill file if multiple exist
const skillFile = skillFiles[0]!
if (skillFiles.length > 1) {
logForDebugging(
`Multiple skill files found in ${dir}, using ${basename(skillFile.filePath)}`,
)
}
// Directory has a skill - only include the skill file
result.push(skillFile)
} else {
result.push(...dirFiles)
}
}
return result
}
async function loadCommandsFromDirectory(
commandsPath: string,
pluginName: string,
sourceName: string,
pluginManifest: PluginManifest,
pluginPath: string,
config: LoadConfig = { isSkillMode: false },
loadedPaths: Set<string> = new Set(),
): Promise<Command[]> {
// Collect all markdown files
const markdownFiles = await collectMarkdownFiles(
commandsPath,
commandsPath,
loadedPaths,
)
// Apply skill transformation
const processedFiles = transformPluginSkillFiles(markdownFiles)
// Convert to commands
const commands: Command[] = []
for (const file of processedFiles) {
const commandName = getCommandNameFromFile(
file.filePath,
file.baseDir,
pluginName,
)
const command = createPluginCommand(
commandName,
file,
sourceName,
pluginManifest,
pluginPath,
isSkillFile(file.filePath),
config,
)
if (command) {
commands.push(command)
}
}
return commands
}
/**
* Create a Command from a plugin markdown file
*/
function createPluginCommand(
commandName: string,
file: PluginMarkdownFile,
sourceName: string,
pluginManifest: PluginManifest,
pluginPath: string,
isSkill: boolean,
config: LoadConfig = { isSkillMode: false },
): Command | null {
try {
const { frontmatter, content } = file
const validatedDescription = coerceDescriptionToString(
frontmatter.description,
commandName,
)
const description =
validatedDescription ??
extractDescriptionFromMarkdown(
content,
isSkill ? 'Plugin skill' : 'Plugin command',
)
// Substitute ${CLAUDE_PLUGIN_ROOT} in allowed-tools before parsing
const rawAllowedTools = frontmatter['allowed-tools']
const substitutedAllowedTools =
typeof rawAllowedTools === 'string'
? substitutePluginVariables(rawAllowedTools, {
path: pluginPath,
source: sourceName,
})
: Array.isArray(rawAllowedTools)
? rawAllowedTools.map(tool =>
typeof tool === 'string'
? substitutePluginVariables(tool, {
path: pluginPath,
source: sourceName,
})
: tool,
)
: rawAllowedTools
const allowedTools = parseSlashCommandToolsFromFrontmatter(
substitutedAllowedTools,
)
const argumentHint = frontmatter['argument-hint'] as string | undefined
const argumentNames = parseArgumentNames(
frontmatter.arguments as string | string[] | undefined,
)
const whenToUse = frontmatter.when_to_use as string | undefined
const version = frontmatter.version as string | undefined
const displayName = frontmatter.name as string | undefined
// Handle model configuration, resolving aliases like 'haiku', 'sonnet', 'opus'
const model =
frontmatter.model === 'inherit'
? undefined
: frontmatter.model
? parseUserSpecifiedModel(frontmatter.model as string)
: undefined
const effortRaw = frontmatter['effort']
const effort =
effortRaw !== undefined ? parseEffortValue(effortRaw) : undefined
if (effortRaw !== undefined && effort === undefined) {
logForDebugging(
`Plugin command ${commandName} has invalid effort '${effortRaw}'. Valid options: ${EFFORT_LEVELS.join(', ')} or an integer`,
)
}
const disableModelInvocation = parseBooleanFrontmatter(
frontmatter['disable-model-invocation'],
)
const userInvocableValue = frontmatter['user-invocable']
const userInvocable =
userInvocableValue === undefined
? true
: parseBooleanFrontmatter(userInvocableValue)
const shell = parseShellFrontmatter(frontmatter.shell, commandName)
return {
type: 'prompt',
name: commandName,
description,
hasUserSpecifiedDescription: validatedDescription !== null,
allowedTools,
argumentHint,
argNames: argumentNames.length > 0 ? argumentNames : undefined,
whenToUse,
version,
model,
effort,
disableModelInvocation,
userInvocable,
contentLength: content.length,
source: 'plugin' as const,
loadedFrom: isSkill || config.isSkillMode ? 'plugin' : undefined,
pluginInfo: {
pluginManifest,
repository: sourceName,
},
isHidden: !userInvocable,
progressMessage: isSkill || config.isSkillMode ? 'loading' : 'running',
userFacingName(): string {
return displayName || commandName
},
async getPromptForCommand(args, context) {
// For skills from skills/ directory, include base directory
let finalContent = config.isSkillMode
? `Base directory for this skill: ${dirname(file.filePath)}\n\n${content}`
: content
finalContent = substituteArguments(
finalContent,
args,
true,
argumentNames,
)
// Replace ${CLAUDE_PLUGIN_ROOT} and ${CLAUDE_PLUGIN_DATA} with their paths
finalContent = substitutePluginVariables(finalContent, {
path: pluginPath,
source: sourceName,
})
// Replace ${user_config.X} with saved option values. Sensitive keys
// resolve to a descriptive placeholder instead — skill content goes to
// the model prompt and we don't put secrets there.
if (pluginManifest.userConfig) {
finalContent = substituteUserConfigInContent(
finalContent,
loadPluginOptions(sourceName),
pluginManifest.userConfig,
)
}
// Replace ${CLAUDE_SKILL_DIR} with this specific skill's directory.
// Distinct from ${CLAUDE_PLUGIN_ROOT}: a plugin can contain multiple
// skills, so CLAUDE_PLUGIN_ROOT points to the plugin root while
// CLAUDE_SKILL_DIR points to the individual skill's subdirectory.
if (config.isSkillMode) {
const rawSkillDir = dirname(file.filePath)
const skillDir =
process.platform === 'win32'
? rawSkillDir.replace(/\\/g, '/')
: rawSkillDir
finalContent = finalContent.replace(
/\$\{CLAUDE_SKILL_DIR\}/g,
skillDir,
)
}
// Replace ${CLAUDE_SESSION_ID} with the current session ID
finalContent = finalContent.replace(
/\$\{CLAUDE_SESSION_ID\}/g,
getSessionId(),
)
finalContent = await executeShellCommandsInPrompt(
finalContent,
{
...context,
getAppState() {
const appState = context.getAppState()
return {
...appState,
toolPermissionContext: {
...appState.toolPermissionContext,
alwaysAllowRules: {
...appState.toolPermissionContext.alwaysAllowRules,
command: allowedTools,
},
},
}
},
},
`/${commandName}`,
shell,
)
return [{ type: 'text', text: finalContent }]
},
} satisfies Command
} catch (error) {
logForDebugging(
`Failed to create command from ${file.filePath}: ${error}`,
{
level: 'error',
},
)
return null
}
}
export const getPluginCommands = memoize(async (): Promise<Command[]> => {
// --bare: skip marketplace plugin auto-load. Explicit --plugin-dir still
// works — getInlinePlugins() is set by main.tsx from --plugin-dir.
// loadAllPluginsCacheOnly already short-circuits to inline-only when
// inlinePlugins.length > 0.
if (isBareMode() && getInlinePlugins().length === 0) {
return []
}
// Only load commands from enabled plugins
const { enabled, errors } = await loadAllPluginsCacheOnly()
if (errors.length > 0) {
logForDebugging(
`Plugin loading errors: ${errors.map(e => getPluginErrorMessage(e)).join(', ')}`,
)
}
// Process plugins in parallel; each plugin has its own loadedPaths scope
const perPluginCommands = await Promise.all(
enabled.map(async (plugin): Promise<Command[]> => {
// Track loaded file paths to prevent duplicates within this plugin
const loadedPaths = new Set<string>()
const pluginCommands: Command[] = []
// Load commands from default commands directory
if (plugin.commandsPath) {
try {
const commands = await loadCommandsFromDirectory(
plugin.commandsPath,
plugin.name,
plugin.source,
plugin.manifest,
plugin.path,
{ isSkillMode: false },
loadedPaths,
)
pluginCommands.push(...commands)
if (commands.length > 0) {
logForDebugging(
`Loaded ${commands.length} commands from plugin ${plugin.name} default directory`,
)
}
} catch (error) {
logForDebugging(
`Failed to load commands from plugin ${plugin.name} default directory: ${error}`,
{ level: 'error' },
)
}
}
// Load commands from additional paths specified in manifest
if (plugin.commandsPaths) {
logForDebugging(
`Plugin ${plugin.name} has commandsPaths: ${plugin.commandsPaths.join(', ')}`,
)
// Process all commandsPaths in parallel. isDuplicatePath is synchronous
// (check-and-add), so concurrent access to loadedPaths is safe.
const pathResults = await Promise.all(
plugin.commandsPaths.map(async (commandPath): Promise<Command[]> => {
try {
const fs = getFsImplementation()
const stats = await fs.stat(commandPath)
logForDebugging(
`Checking commandPath ${commandPath} - isDirectory: ${stats.isDirectory()}, isFile: ${stats.isFile()}`,
)
if (stats.isDirectory()) {
// Load all .md files and skill directories from directory
const commands = await loadCommandsFromDirectory(
commandPath,
plugin.name,
plugin.source,
plugin.manifest,
plugin.path,
{ isSkillMode: false },
loadedPaths,
)
if (commands.length > 0) {
logForDebugging(
`Loaded ${commands.length} commands from plugin ${plugin.name} custom path: ${commandPath}`,
)
} else {
logForDebugging(
`Warning: No commands found in plugin ${plugin.name} custom directory: ${commandPath}. Expected .md files or SKILL.md in subdirectories.`,
{ level: 'warn' },
)
}
return commands
} else if (stats.isFile() && commandPath.endsWith('.md')) {
if (isDuplicatePath(fs, commandPath, loadedPaths)) {
return []
}
// Load single command file
const content = await fs.readFile(commandPath, {
encoding: 'utf-8',
})
const { frontmatter, content: markdownContent } =
parseFrontmatter(content, commandPath)
// Check if there's metadata for this command (object-mapping format)
let commandName: string | undefined
let metadataOverride: CommandMetadata | undefined
if (plugin.commandsMetadata) {
// Find metadata by matching the command's absolute path to the metadata source
// Convert metadata.source (relative to plugin root) to absolute path for comparison
for (const [name, metadata] of Object.entries(
plugin.commandsMetadata,
)) {
if (metadata.source) {
const fullMetadataPath = join(
plugin.path,
metadata.source,
)
if (commandPath === fullMetadataPath) {
commandName = `${plugin.name}:${name}`
metadataOverride = metadata
break
}
}
}
}
// Fall back to filename-based naming if no metadata
if (!commandName) {
commandName = `${plugin.name}:${basename(commandPath).replace(/\.md$/, '')}`
}
// Apply metadata overrides to frontmatter
const finalFrontmatter = metadataOverride
? {
...frontmatter,
...(metadataOverride.description && {
description: metadataOverride.description,
}),
...(metadataOverride.argumentHint && {
'argument-hint': metadataOverride.argumentHint,
}),
...(metadataOverride.model && {
model: metadataOverride.model,
}),
...(metadataOverride.allowedTools && {
'allowed-tools':
metadataOverride.allowedTools.join(','),
}),
}
: frontmatter
const file: PluginMarkdownFile = {
filePath: commandPath,
baseDir: dirname(commandPath),
frontmatter: finalFrontmatter,
content: markdownContent,
}
const command = createPluginCommand(
commandName,
file,
plugin.source,
plugin.manifest,
plugin.path,
false,
)
if (command) {
logForDebugging(
`Loaded command from plugin ${plugin.name} custom file: ${commandPath}${metadataOverride ? ' (with metadata override)' : ''}`,
)
return [command]
}
}
return []
} catch (error) {
logForDebugging(
`Failed to load commands from plugin ${plugin.name} custom path ${commandPath}: ${error}`,
{ level: 'error' },
)
return []
}
}),
)
for (const commands of pathResults) {
pluginCommands.push(...commands)
}
}
// Load commands with inline content (no source file)
// Note: Commands with source files were already loaded in the previous loop
// when iterating through commandsPaths. This loop handles metadata entries
// that specify inline content instead of file references.
if (plugin.commandsMetadata) {
for (const [name, metadata] of Object.entries(
plugin.commandsMetadata,
)) {
// Only process entries with inline content (no source)
if (metadata.content && !metadata.source) {
try {
// Parse inline content for frontmatter
const { frontmatter, content: markdownContent } =
parseFrontmatter(
metadata.content,
`<inline:${plugin.name}:${name}>`,
)
// Apply metadata overrides to frontmatter
const finalFrontmatter: FrontmatterData = {
...frontmatter,
...(metadata.description && {
description: metadata.description,
}),
...(metadata.argumentHint && {
'argument-hint': metadata.argumentHint,
}),
...(metadata.model && {
model: metadata.model,
}),
...(metadata.allowedTools && {
'allowed-tools': metadata.allowedTools.join(','),
}),
}
const commandName = `${plugin.name}:${name}`
const file: PluginMarkdownFile = {
filePath: `<inline:${commandName}>`, // Virtual path for inline content
baseDir: plugin.path, // Use plugin root as base directory
frontmatter: finalFrontmatter,
content: markdownContent,
}
const command = createPluginCommand(
commandName,
file,
plugin.source,
plugin.manifest,
plugin.path,
false,
)
if (command) {
pluginCommands.push(command)
logForDebugging(
`Loaded inline content command from plugin ${plugin.name}: ${commandName}`,
)
}
} catch (error) {
logForDebugging(
`Failed to load inline content command ${name} from plugin ${plugin.name}: ${error}`,
{ level: 'error' },
)
}
}
}
}
return pluginCommands
}),
)
const allCommands = perPluginCommands.flat()
logForDebugging(`Total plugin commands loaded: ${allCommands.length}`)
return allCommands
})
export function clearPluginCommandCache(): void {
getPluginCommands.cache?.clear?.()
}
/**
* Loads skills from plugin skills directories
* Skills are directories containing SKILL.md files
*/
async function loadSkillsFromDirectory(
skillsPath: string,
pluginName: string,
sourceName: string,
pluginManifest: PluginManifest,
pluginPath: string,
loadedPaths: Set<string>,
): Promise<Command[]> {
const fs = getFsImplementation()
const skills: Command[] = []
// First, check if skillsPath itself contains SKILL.md (direct skill directory)
const directSkillPath = join(skillsPath, 'SKILL.md')
let directSkillContent: string | null = null
try {
directSkillContent = await fs.readFile(directSkillPath, {
encoding: 'utf-8',
})
} catch (e: unknown) {
if (!isENOENT(e)) {
logForDebugging(`Failed to load skill from ${directSkillPath}: ${e}`, {
level: 'error',
})
return skills
}
// ENOENT: no direct SKILL.md, fall through to scan subdirectories
}
if (directSkillContent !== null) {
// This is a direct skill directory, load the skill from here
if (isDuplicatePath(fs, directSkillPath, loadedPaths)) {
return skills
}
try {
const { frontmatter, content: markdownContent } = parseFrontmatter(
directSkillContent,
directSkillPath,
)
const skillName = `${pluginName}:${basename(skillsPath)}`
const file: PluginMarkdownFile = {
filePath: directSkillPath,
baseDir: dirname(directSkillPath),
frontmatter,
content: markdownContent,
}
const skill = createPluginCommand(
skillName,
file,
sourceName,
pluginManifest,
pluginPath,
true, // isSkill
{ isSkillMode: true }, // config
)
if (skill) {
skills.push(skill)
}
} catch (error) {
logForDebugging(
`Failed to load skill from ${directSkillPath}: ${error}`,
{
level: 'error',
},
)
}
return skills
}
// Otherwise, scan for subdirectories containing SKILL.md files
let entries
try {
entries = await fs.readdir(skillsPath)
} catch (e: unknown) {
if (!isENOENT(e)) {
logForDebugging(
`Failed to load skills from directory ${skillsPath}: ${e}`,
{ level: 'error' },
)
}
return skills
}
await Promise.all(
entries.map(async entry => {
// Accept both directories and symlinks (symlinks may point to skill directories)
if (!entry.isDirectory() && !entry.isSymbolicLink()) {
return
}
const skillDirPath = join(skillsPath, entry.name)
const skillFilePath = join(skillDirPath, 'SKILL.md')
// Try to read SKILL.md directly; skip if it doesn't exist
let content: string
try {
content = await fs.readFile(skillFilePath, { encoding: 'utf-8' })
} catch (e: unknown) {
if (!isENOENT(e)) {
logForDebugging(`Failed to load skill from ${skillFilePath}: ${e}`, {
level: 'error',
})
}
return
}
if (isDuplicatePath(fs, skillFilePath, loadedPaths)) {
return
}
try {
const { frontmatter, content: markdownContent } = parseFrontmatter(
content,
skillFilePath,
)
const skillName = `${pluginName}:${entry.name}`
const file: PluginMarkdownFile = {
filePath: skillFilePath,
baseDir: dirname(skillFilePath),
frontmatter,
content: markdownContent,
}
const skill = createPluginCommand(
skillName,
file,
sourceName,
pluginManifest,
pluginPath,
true, // isSkill
{ isSkillMode: true }, // config
)
if (skill) {
skills.push(skill)
}
} catch (error) {
logForDebugging(
`Failed to load skill from ${skillFilePath}: ${error}`,
{ level: 'error' },
)
}
}),
)
return skills
}
export const getPluginSkills = memoize(async (): Promise<Command[]> => {
// --bare: same gate as getPluginCommands above — honor explicit
// --plugin-dir, skip marketplace auto-load.
if (isBareMode() && getInlinePlugins().length === 0) {
return []
}
// Only load skills from enabled plugins
const { enabled, errors } = await loadAllPluginsCacheOnly()
if (errors.length > 0) {
logForDebugging(
`Plugin loading errors: ${errors.map(e => getPluginErrorMessage(e)).join(', ')}`,
)
}
logForDebugging(
`getPluginSkills: Processing ${enabled.length} enabled plugins`,
)
// Process plugins in parallel; each plugin has its own loadedPaths scope
const perPluginSkills = await Promise.all(
enabled.map(async (plugin): Promise<Command[]> => {
// Track loaded file paths to prevent duplicates within this plugin
const loadedPaths = new Set<string>()
const pluginSkills: Command[] = []
logForDebugging(
`Checking plugin ${plugin.name}: skillsPath=${plugin.skillsPath ? 'exists' : 'none'}, skillsPaths=${plugin.skillsPaths ? plugin.skillsPaths.length : 0} paths`,
)
// Load skills from default skills directory
if (plugin.skillsPath) {
logForDebugging(
`Attempting to load skills from plugin ${plugin.name} default skillsPath: ${plugin.skillsPath}`,
)
try {
const skills = await loadSkillsFromDirectory(
plugin.skillsPath,
plugin.name,
plugin.source,
plugin.manifest,
plugin.path,
loadedPaths,
)
pluginSkills.push(...skills)
logForDebugging(
`Loaded ${skills.length} skills from plugin ${plugin.name} default directory`,
)
} catch (error) {
logForDebugging(
`Failed to load skills from plugin ${plugin.name} default directory: ${error}`,
{ level: 'error' },
)
}
}
// Load skills from additional paths specified in manifest
if (plugin.skillsPaths) {
logForDebugging(
`Attempting to load skills from plugin ${plugin.name} skillsPaths: ${plugin.skillsPaths.join(', ')}`,
)
// Process all skillsPaths in parallel. isDuplicatePath is synchronous
// (check-and-add), so concurrent access to loadedPaths is safe.
const pathResults = await Promise.all(
plugin.skillsPaths.map(async (skillPath): Promise<Command[]> => {
try {
logForDebugging(
`Loading from skillPath: ${skillPath} for plugin ${plugin.name}`,
)
const skills = await loadSkillsFromDirectory(
skillPath,
plugin.name,
plugin.source,
plugin.manifest,
plugin.path,
loadedPaths,
)
logForDebugging(
`Loaded ${skills.length} skills from plugin ${plugin.name} custom path: ${skillPath}`,
)
return skills
} catch (error) {
logForDebugging(
`Failed to load skills from plugin ${plugin.name} custom path ${skillPath}: ${error}`,
{ level: 'error' },
)
return []
}
}),
)
for (const skills of pathResults) {
pluginSkills.push(...skills)
}
}
return pluginSkills
}),
)
const allSkills = perPluginSkills.flat()
logForDebugging(`Total plugin skills loaded: ${allSkills.length}`)
return allSkills
})
export function clearPluginSkillsCache(): void {
getPluginSkills.cache?.clear?.()
}
|