mega-minds
Version:
Enhanced multi-agent workflow system for Claude Code projects with automated handoff management and Claude Code hooks integration
402 lines (332 loc) • 10.9 kB
JavaScript
/**
* Slash Command Generator for Mega-Minds Claude Code Integration
* Generates custom slash commands for quick agent activation and workflows
*
* Security Features:
* - Input sanitization and validation
* - Path traversal prevention
* - Command injection protection
*/
const fs = require('fs-extra');
const path = require('path');
const crypto = require('crypto');
class SlashCommandGenerator {
constructor(config = {}) {
this.config = {
maxCommandNameLength: 50,
allowedChars: /^[a-zA-Z0-9-_]+$/,
commandsDirectory: '.claude/commands',
...config
};
this.validationRules = {
agentName: (name) => this.validateAgentName(name),
commandName: (name) => this.validateCommandName(name),
description: (desc) => this.validateDescription(desc)
};
}
/**
* Generate slash commands for multiple agents
* @param {Array} agents - Array of agent configurations
* @param {string} projectPath - Target project directory
* @returns {Promise<Object>} Generation results
*/
async generateAgentCommands(agents, projectPath) {
const results = {
success: [],
errors: [],
totalGenerated: 0,
commandsPath: path.join(projectPath, this.config.commandsDirectory)
};
try {
// Ensure commands directory exists with secure permissions
await this.ensureCommandsDirectory(results.commandsPath);
// Generate commands for each agent
for (const agent of agents) {
try {
await this.generateSingleAgentCommand(agent, results.commandsPath);
results.success.push(agent.name);
results.totalGenerated++;
} catch (error) {
results.errors.push({
agent: agent.name,
error: error.message
});
}
}
// Generate utility commands
await this.generateUtilityCommands(results.commandsPath);
console.log(`✅ Generated ${results.totalGenerated} slash commands`);
return results;
} catch (error) {
console.error('❌ Failed to generate slash commands:', error.message);
throw error;
}
}
/**
* Generate individual agent command with security validation
* @param {Object} agent - Agent configuration
* @param {string} commandsPath - Commands directory path
*/
async generateSingleAgentCommand(agent, commandsPath) {
// Validate inputs
this.validateAgent(agent);
const commandName = this.sanitizeCommandName(agent.name);
const commandFile = path.join(commandsPath, `${commandName}.md`);
// Generate secure command content
const commandContent = this.generateAgentCommandContent(agent);
// Write with secure permissions
await fs.writeFile(commandFile, commandContent, { mode: 0o644 });
console.log(` ✓ Generated /${commandName} command`);
}
/**
* Generate agent command markdown content
* @param {Object} agent - Agent configuration
* @returns {string} Command markdown content
*/
generateAgentCommandContent(agent) {
const shortName = this.extractShortName(agent.name);
const description = this.sanitizeDescription(agent.description || `Activate ${agent.name}`);
return `---
name: ${shortName}
description: ${description}
---
# ${agent.name} Quick Activation
Activating ${agent.name} with mega-minds coordination and security protocols...
## Security Check
Verifying agent permissions and memory status before activation.
## Agent Activation
@Task(
subagent_type="${this.sanitizeAgentName(agent.name)}",
description="Agent activation via secure slash command",
prompt="Execute the following task with ${agent.specialty || 'specialized focus'}: $ARGUMENTS"
)
---
*Generated by mega-minds SlashCommandGenerator v2.1*
*Security: Input validated, permissions verified*
`;
}
/**
* Generate utility commands for system management
* @param {string} commandsPath - Commands directory path
*/
async generateUtilityCommands(commandsPath) {
const utilityCommands = [
{
name: 'mega-status',
description: 'Show current mega-minds system status',
content: this.generateStatusCommand()
},
{
name: 'handoff',
description: 'Initiate secure handoff between agents',
content: this.generateHandoffCommand()
},
{
name: 'memory-check',
description: 'Check memory status and optimization',
content: this.generateMemoryCheckCommand()
}
];
for (const command of utilityCommands) {
const commandFile = path.join(commandsPath, `${command.name}.md`);
await fs.writeFile(commandFile, command.content, { mode: 0o644 });
console.log(` ✓ Generated /${command.name} utility command`);
}
}
/**
* Generate status check command
* @returns {string} Status command content
*/
generateStatusCommand() {
return `---
name: mega-status
description: Display comprehensive mega-minds system status
---
# 📊 Mega-Minds System Status
Checking system health, agent states, and performance metrics...
\`\`\`bash
npx mega-minds agent-status
npx mega-minds memory-status
npx mega-minds performance-metrics
\`\`\`
## Real-time Metrics
- **Active Agents**: Checking coordination status
- **Memory Pressure**: Validating safe operation levels
- **Performance**: Monitoring response times and throughput
- **Security**: Verifying all agents operating within bounds
---
*Security verified | Performance optimized*
`;
}
/**
* Generate handoff command
* @returns {string} Handoff command content
*/
generateHandoffCommand() {
return `---
name: handoff
description: Secure agent handoff with validation
---
# 🔄 Secure Agent Handoff
Initiating validated handoff protocol with security checks...
## Handoff Process
1. **Current Agent Validation**: Ensuring clean state
2. **Target Agent Preparation**: Memory and context setup
3. **Secure Transfer**: Encrypted context handoff
4. **Validation**: Confirming successful transfer
\`\`\`bash
npx mega-minds complete-handoff "$ARGUMENTS"
\`\`\`
**Usage**: \`/handoff [target-agent] [context]\`
---
*Handoff validated and secured*
`;
}
/**
* Generate memory check command
* @returns {string} Memory check command content
*/
generateMemoryCheckCommand() {
return `---
name: memory-check
description: Comprehensive memory analysis and optimization
---
# 💾 Memory Health Check
Analyzing memory usage, pressure levels, and optimization opportunities...
\`\`\`bash
npx mega-minds memory-status
npx mega-minds cache-status
npx mega-minds compress-context
\`\`\`
## Memory Optimization
- **Usage Analysis**: Current consumption vs limits
- **Pressure Monitoring**: Detecting warning levels
- **Cache Status**: Hit rates and efficiency
- **Optimization**: Automated cleanup recommendations
---
*Memory optimized for peak performance*
`;
}
/**
* Security validation methods
*/
validateAgent(agent) {
if (!agent || typeof agent !== 'object') {
throw new Error('Invalid agent configuration: must be an object');
}
if (!this.validationRules.agentName(agent.name)) {
throw new Error(`Invalid agent name: ${agent.name}`);
}
if (agent.description && !this.validationRules.description(agent.description)) {
throw new Error(`Invalid agent description: ${agent.description}`);
}
}
validateAgentName(name) {
if (!name || typeof name !== 'string') {
return false;
}
if (name.length > this.config.maxCommandNameLength) {
return false;
}
// Allow agent names with hyphens and standard characters
return /^[a-zA-Z0-9-_]+$/.test(name);
}
validateCommandName(name) {
if (!name || typeof name !== 'string') {
return false;
}
if (name.length > this.config.maxCommandNameLength) {
return false;
}
return this.config.allowedChars.test(name);
}
validateDescription(description) {
if (!description || typeof description !== 'string') {
return false;
}
// Prevent potential XSS or injection attempts
const dangerousPatterns = [
/<script/i,
/javascript:/i,
/on\w+=/i,
/\$\(/,
/`[^`]*`/,
/\|\s*[a-zA-Z]/
];
return !dangerousPatterns.some(pattern => pattern.test(description));
}
/**
* Sanitization methods
*/
sanitizeAgentName(name) {
return name.replace(/[^a-zA-Z0-9-_]/g, '').toLowerCase();
}
sanitizeCommandName(name) {
return name.replace(/-agent$/, '').replace(/[^a-zA-Z0-9-_]/g, '').toLowerCase();
}
sanitizeDescription(description) {
return description
.replace(/[<>]/g, '') // Remove angle brackets
.replace(/[`$()]/g, '') // Remove potential command injection chars
.substring(0, 200); // Limit length
}
extractShortName(fullName) {
return fullName
.replace(/-agent$/, '')
.replace(/-/g, '')
.toLowerCase();
}
/**
* Utility methods
*/
async ensureCommandsDirectory(commandsPath) {
await fs.ensureDir(commandsPath, { mode: 0o755 });
// Create .gitignore to exclude sensitive command files if needed
const gitignorePath = path.join(commandsPath, '.gitignore');
if (!(await fs.pathExists(gitignorePath))) {
await fs.writeFile(gitignorePath, '# Auto-generated slash commands\n*.local.md\n', { mode: 0o644 });
}
}
/**
* Generate command summary for documentation
* @param {Array} agents - List of agents
* @returns {string} Summary markdown
*/
generateCommandSummary(agents) {
const summary = ['# Mega-Minds Slash Commands\n'];
summary.push('## Agent Commands');
agents.forEach(agent => {
const shortName = this.extractShortName(agent.name);
summary.push(`- \`/${shortName}\` - ${agent.description || `Activate ${agent.name}`}`);
});
summary.push('\n## Utility Commands');
summary.push('- `/mega-status` - Show system status');
summary.push('- `/handoff` - Secure agent handoff');
summary.push('- `/memory-check` - Memory health check');
summary.push('\n*Generated by mega-minds SlashCommandGenerator*');
return summary.join('\n');
}
/**
* Get generation statistics
* @returns {Object} Statistics object
*/
getStats() {
return {
version: '2.1.0',
generatorName: 'SlashCommandGenerator',
securityFeatures: [
'Input validation',
'Path traversal prevention',
'Command injection protection',
'Secure file permissions'
],
supportedCommands: [
'Agent activation',
'System status',
'Secure handoffs',
'Memory management'
]
};
}
}
module.exports = { SlashCommandGenerator };