This commit is contained in:
rUv committed 2025-07-17 04:11:59 +00:00
1 parent b74b2136f8
commit ca9d2995a0
63 files changed
+3601 -1148

No files matched your search

+1 -1
View File
@@ -72,7 +72,7 @@ class CLI {
command(cmd: Command): this {
// Handle both our Command interface and Commander.js Command objects
const cmdName = typeof cmd.name === 'function' ? cmd.name() : (cmd.name || 'unknown');
const cmdName = typeof (cmd as any).name === 'function' ? (cmd as any).name() : (cmd.name || 'unknown');
this.commands.set(cmdName, cmd);
if (cmd.aliases && typeof cmd.aliases[Symbol.iterator] === 'function') {
for (const alias of cmd.aliases) {
+272
View File
@@ -0,0 +1,272 @@
/**
* Claude API management commands
*/
import chalk from 'chalk';
import inquirer from 'inquirer';
import { Command } from 'commander';
import { ConfigManager } from '../../config/config-manager.js';
import { ClaudeAPIClient, ClaudeModel } from '../../api/claude-client.js';
import { Logger } from '../../core/logger.js';
import { getErrorMessage } from '../../utils/error-handler.js';
export const claudeApiCommand = new Command()
.name('claude-api')
.description('Manage Claude API configuration and test connectivity')
.action(() => {
claudeApiCommand.help();
});
// Configure command
claudeApiCommand
.command('configure')
.description('Configure Claude API settings')
.option('--api-key <key>', 'Claude API key')
.option('--model <model>', 'Claude model to use')
.option('--temperature <temp>', 'Temperature (0.0-1.0)', parseFloat)
.option('--max-tokens <tokens>', 'Maximum tokens', parseInt)
.option('--interactive', 'Interactive configuration')
.action(async (options: any) => {
try {
const configManager = ConfigManager.getInstance();
let config = configManager.getClaudeConfig();
if (options.interactive) {
console.log(chalk.blue('🤖 Claude API Configuration'));
console.log('Configure your Claude API settings.\n');
const answers = await inquirer.prompt([
{
type: 'input',
name: 'apiKey',
message: 'Enter your Claude API key:',
default: config.apiKey || process.env.ANTHROPIC_API_KEY,
validate: (input) => input ? true : 'API key is required',
},
{
type: 'list',
name: 'model',
message: 'Select Claude model:',
choices: [
{ name: 'Claude 3 Opus (Most capable)', value: 'claude-3-opus-20240229' },
{ name: 'Claude 3 Sonnet (Balanced)', value: 'claude-3-sonnet-20240229' },
{ name: 'Claude 3 Haiku (Fastest)', value: 'claude-3-haiku-20240307' },
{ name: 'Claude 2.1', value: 'claude-2.1' },
{ name: 'Claude 2.0', value: 'claude-2.0' },
{ name: 'Claude Instant 1.2', value: 'claude-instant-1.2' },
],
default: config.model || 'claude-3-sonnet-20240229',
},
{
type: 'input',
name: 'temperature',
message: 'Temperature (0.0-1.0):',
default: config.temperature?.toString() || '0.7',
validate: (input) => {
const num = parseFloat(input);
return (num >= 0 && num <= 1) ? true : 'Temperature must be between 0.0 and 1.0';
},
filter: (input) => parseFloat(input),
},
{
type: 'input',
name: 'maxTokens',
message: 'Maximum tokens:',
default: config.maxTokens?.toString() || '4096',
validate: (input) => {
const num = parseInt(input);
return (num > 0 && num <= 100000) ? true : 'Max tokens must be between 1 and 100000';
},
filter: (input) => parseInt(input),
},
]);
config = { ...config, ...answers };
} else {
// Non-interactive mode
if (options.apiKey) config.apiKey = options.apiKey;
if (options.model) config.model = options.model;
if (options.temperature !== undefined) config.temperature = options.temperature;
if (options.maxTokens !== undefined) config.maxTokens = options.maxTokens;
}
// Update configuration
configManager.setClaudeConfig(config);
await configManager.save();
console.log(chalk.green('✅ Claude API configuration saved'));
console.log(chalk.gray(`Model: ${config.model}`));
console.log(chalk.gray(`Temperature: ${config.temperature}`));
console.log(chalk.gray(`Max tokens: ${config.maxTokens}`));
} catch (error) {
console.error(chalk.red('❌ Failed to configure Claude API:'), getErrorMessage(error));
process.exit(1);
}
});
// Test command
claudeApiCommand
.command('test')
.description('Test Claude API connectivity')
.option('--model <model>', 'Model to test')
.option('--temperature <temp>', 'Temperature for test', parseFloat)
.option('--prompt <prompt>', 'Test prompt', 'Hello, Claude! Please respond with a brief greeting.')
.action(async (options: any) => {
try {
const configManager = ConfigManager.getInstance();
if (!configManager.isClaudeAPIConfigured()) {
console.error(chalk.red('❌ Claude API not configured. Run "claude-api configure" first.'));
process.exit(1);
}
console.log(chalk.blue('🧪 Testing Claude API connectivity...'));
const logger = new Logger({ level: 'info', format: 'text', destination: 'console' });
const client = new ClaudeAPIClient(logger, configManager);
const testOptions: any = {};
if (options.model) testOptions.model = options.model;
if (options.temperature !== undefined) testOptions.temperature = options.temperature;
const start = Date.now();
const response = await client.complete(options.prompt, testOptions);
const duration = Date.now() - start;
console.log(chalk.green('✅ Claude API test successful!'));
console.log(chalk.gray(`Duration: ${duration}ms`));
console.log(chalk.cyan('\nResponse:'));
console.log(response);
} catch (error) {
console.error(chalk.red('❌ Claude API test failed:'), getErrorMessage(error));
process.exit(1);
}
});
// Status command
claudeApiCommand
.command('status')
.description('Show Claude API configuration status')
.action(async () => {
try {
const configManager = ConfigManager.getInstance();
const config = configManager.getClaudeConfig();
const isConfigured = configManager.isClaudeAPIConfigured();
console.log(chalk.blue('🤖 Claude API Status\n'));
if (isConfigured) {
console.log(chalk.green('✅ Configured'));
console.log(chalk.gray(`Model: ${config.model || 'claude-3-sonnet-20240229'}`));
console.log(chalk.gray(`Temperature: ${config.temperature ?? 0.7}`));
console.log(chalk.gray(`Max tokens: ${config.maxTokens || 4096}`));
console.log(chalk.gray(`API key: ${config.apiKey ? '***masked***' : 'Not set'}`));
if (process.env.ANTHROPIC_API_KEY && !config.apiKey) {
console.log(chalk.yellow('⚠️ Using API key from ANTHROPIC_API_KEY environment variable'));
}
} else {
console.log(chalk.red('❌ Not configured'));
console.log(chalk.gray('Run "claude-api configure" to set up Claude API.'));
}
} catch (error) {
console.error(chalk.red('❌ Failed to get status:'), getErrorMessage(error));
process.exit(1);
}
});
// Models command
claudeApiCommand
.command('models')
.description('List available Claude models')
.action(() => {
console.log(chalk.blue('📋 Available Claude Models\n'));
const models = [
{
id: 'claude-3-opus-20240229',
name: 'Claude 3 Opus',
description: 'Most capable model, best for complex tasks',
contextWindow: '200K tokens',
},
{
id: 'claude-3-sonnet-20240229',
name: 'Claude 3 Sonnet',
description: 'Balanced performance and speed',
contextWindow: '200K tokens',
},
{
id: 'claude-3-haiku-20240307',
name: 'Claude 3 Haiku',
description: 'Fastest model, best for simple tasks',
contextWindow: '200K tokens',
},
{
id: 'claude-2.1',
name: 'Claude 2.1',
description: 'Previous generation, enhanced capabilities',
contextWindow: '200K tokens',
},
{
id: 'claude-2.0',
name: 'Claude 2.0',
description: 'Previous generation model',
contextWindow: '100K tokens',
},
{
id: 'claude-instant-1.2',
name: 'Claude Instant 1.2',
description: 'Fast, cost-effective model',
contextWindow: '100K tokens',
},
];
models.forEach((model) => {
console.log(chalk.cyan(`${model.name} (${model.id})`));
console.log(chalk.gray(` ${model.description}`));
console.log(chalk.gray(` Context: ${model.contextWindow}\n`));
});
});
// Update command
claudeApiCommand
.command('update')
.description('Update specific Claude API settings')
.option('--model <model>', 'Update model')
.option('--temperature <temp>', 'Update temperature', parseFloat)
.option('--max-tokens <tokens>', 'Update max tokens', parseInt)
.action(async (options: any) => {
try {
const configManager = ConfigManager.getInstance();
if (!configManager.isClaudeAPIConfigured()) {
console.error(chalk.red('❌ Claude API not configured. Run "claude-api configure" first.'));
process.exit(1);
}
const updates: any = {};
if (options.model) updates.model = options.model;
if (options.temperature !== undefined) updates.temperature = options.temperature;
if (options.maxTokens !== undefined) updates.maxTokens = options.maxTokens;
if (Object.keys(updates).length === 0) {
console.log(chalk.yellow('⚠️ No updates specified. Use --model, --temperature, or --max-tokens.'));
return;
}
configManager.setClaudeConfig(updates);
await configManager.save();
console.log(chalk.green('✅ Claude API configuration updated'));
Object.entries(updates).forEach(([key, value]) => {
console.log(chalk.gray(`${key}: ${value}`));
});
} catch (error) {
console.error(chalk.red('❌ Failed to update configuration:'), getErrorMessage(error));
process.exit(1);
}
});
+14 -2
View File
@@ -11,6 +11,10 @@ import { spawnCommand } from './spawn.js';
import { statusCommand } from './status.js';
import { taskCommand } from './task.js';
import { wizardCommand } from './wizard.js';
import { stopCommand } from './stop.js';
import { pauseCommand } from './pause.js';
import { resumeCommand } from './resume.js';
import { psCommand } from './ps.js';
export const hiveMindCommand = new Command('hive-mind')
.description('Hive Mind collective intelligence swarm management')
@@ -18,7 +22,11 @@ export const hiveMindCommand = new Command('hive-mind')
.addCommand(spawnCommand)
.addCommand(statusCommand)
.addCommand(taskCommand)
.addCommand(wizardCommand);
.addCommand(wizardCommand)
.addCommand(stopCommand)
.addCommand(pauseCommand)
.addCommand(resumeCommand)
.addCommand(psCommand);
// Export individual commands for testing
export {
@@ -26,5 +34,9 @@ export {
spawnCommand,
statusCommand,
taskCommand,
wizardCommand
wizardCommand,
stopCommand,
pauseCommand,
resumeCommand,
psCommand
};
+86
View File
@@ -0,0 +1,86 @@
#!/usr/bin/env node
/**
* Hive Mind Pause Command
*
* Pause active swarm sessions
*/
import { Command } from 'commander';
import chalk from 'chalk';
import { HiveMindSessionManager } from '../../simple-commands/hive-mind/session-manager.js';
import inquirer from 'inquirer';
export const pauseCommand = new Command('pause')
.description('Pause active hive mind sessions')
.option('-s, --session <id>', 'Pause specific session by ID')
.action(async (options) => {
const sessionManager = new HiveMindSessionManager();
try {
if (options.session) {
// Pause specific session
const sessionId = options.session;
const session = sessionManager.getSession(sessionId);
if (!session) {
console.log(chalk.red(`Session ${sessionId} not found`));
return;
}
if ((session as any).status === 'paused') {
console.log(chalk.yellow(`Session ${sessionId} is already paused`));
return;
}
if ((session as any).status !== 'active') {
console.log(chalk.yellow(`Session ${sessionId} is not active (status: ${(session as any).status})`));
return;
}
console.log(chalk.cyan(`Pausing session ${sessionId}...`));
const result = sessionManager.pauseSession(sessionId);
if (result) {
console.log(chalk.green(`✓ Session ${sessionId} paused successfully`));
console.log(chalk.gray(`Use 'claude-flow hive-mind resume -s ${sessionId}' to resume`));
} else {
console.log(chalk.red(`Failed to pause session ${sessionId}`));
}
} else {
// Interactive selection
const sessions = sessionManager.getActiveSessions().filter(s => s.status === 'active');
if (sessions.length === 0) {
console.log(chalk.yellow('No active sessions found to pause'));
return;
}
const { sessionId } = await inquirer.prompt([{
type: 'list',
name: 'sessionId',
message: 'Select session to pause:',
choices: sessions.map(s => ({
name: `${s.swarm_name} (${s.id}) - ${s.completion_percentage}% complete`,
value: s.id
}))
}]);
console.log(chalk.cyan(`Pausing session ${sessionId}...`));
const result = sessionManager.pauseSession(sessionId);
if (result) {
console.log(chalk.green(`✓ Session paused successfully`));
console.log(chalk.gray(`Use 'claude-flow hive-mind resume -s ${sessionId}' to resume`));
} else {
console.log(chalk.red(`Failed to pause session`));
}
}
} catch (error) {
console.error(chalk.red('Error pausing session:'), (error as Error).message);
process.exit(1);
} finally {
sessionManager.close();
}
});
+133
View File
@@ -0,0 +1,133 @@
#!/usr/bin/env node
/**
* Hive Mind PS (Process Status) Command
*
* Show active sessions and their processes
*/
import { Command } from 'commander';
import chalk from 'chalk';
import { HiveMindSessionManager } from '../../simple-commands/hive-mind/session-manager.js';
import Table from 'cli-table3';
export const psCommand = new Command('ps')
.description('Show active hive mind sessions and processes')
.option('-a, --all', 'Show all sessions including stopped ones')
.option('-v, --verbose', 'Show detailed process information')
.action(async (options) => {
const sessionManager = new HiveMindSessionManager();
try {
const sessions = options.all
? sessionManager.getActiveSessionsWithProcessInfo()
: sessionManager.getActiveSessionsWithProcessInfo().filter(s =>
s.status === 'active' || s.status === 'paused'
);
if (sessions.length === 0) {
console.log(chalk.yellow('No sessions found'));
return;
}
// Clean up orphaned processes first
const cleanedCount = sessionManager.cleanupOrphanedProcesses();
if (cleanedCount > 0) {
console.log(chalk.blue(`Cleaned up ${cleanedCount} orphaned session(s)\n`));
}
// Create table
const table = new Table({
head: [
chalk.cyan('Session ID'),
chalk.cyan('Swarm'),
chalk.cyan('Status'),
chalk.cyan('Parent PID'),
chalk.cyan('Child PIDs'),
chalk.cyan('Progress'),
chalk.cyan('Duration')
],
style: {
head: [],
border: ['gray']
}
});
for (const session of sessions) {
const duration = new Date() - new Date(session.created_at);
const durationStr = formatDuration(duration);
const statusColor =
session.status === 'active' ? chalk.green :
session.status === 'paused' ? chalk.yellow :
session.status === 'stopped' ? chalk.red :
chalk.gray;
table.push([
session.id.substring(0, 20) + '...',
session.swarm_name,
statusColor(session.status),
session.parent_pid || '-',
session.child_pids.length > 0 ? session.child_pids.join(', ') : '-',
`${session.completion_percentage}%`,
durationStr
]);
}
console.log(table.toString());
if (options.verbose) {
console.log('\n' + chalk.bold('Detailed Session Information:'));
for (const session of sessions) {
console.log('\n' + chalk.cyan(`Session: ${session.id}`));
console.log(chalk.gray(` Objective: ${session.objective || 'N/A'}`));
console.log(chalk.gray(` Created: ${new Date(session.created_at).toLocaleString()}`));
console.log(chalk.gray(` Updated: ${new Date(session.updated_at).toLocaleString()}`));
if (session.paused_at) {
console.log(chalk.gray(` Paused: ${new Date(session.paused_at).toLocaleString()}`));
}
console.log(chalk.gray(` Agents: ${session.agent_count || 0}`));
console.log(chalk.gray(` Tasks: ${session.task_count || 0} (${session.completed_tasks || 0} completed)`));
if (session.child_pids.length > 0) {
console.log(chalk.gray(` Active Processes:`));
for (const pid of session.child_pids) {
console.log(chalk.gray(` - PID ${pid}`));
}
}
}
}
// Summary
const activeSessions = sessions.filter(s => s.status === 'active').length;
const pausedSessions = sessions.filter(s => s.status === 'paused').length;
const totalProcesses = sessions.reduce((sum, s) => sum + s.total_processes, 0);
console.log('\n' + chalk.bold('Summary:'));
console.log(chalk.gray(` Active sessions: ${activeSessions}`));
console.log(chalk.gray(` Paused sessions: ${pausedSessions}`));
console.log(chalk.gray(` Total processes: ${totalProcesses}`));
} catch (error) {
console.error(chalk.red('Error listing sessions:'), error.message);
process.exit(1);
} finally {
sessionManager.close();
}
});
function formatDuration(ms: number) {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
if (hours > 0) {
return `${hours}h ${minutes % 60}m`;
} else if (minutes > 0) {
return `${minutes}m ${seconds % 60}s`;
} else {
return `${seconds}s`;
}
}
+66
View File
@@ -0,0 +1,66 @@
#!/usr/bin/env node
/**
* Hive Mind Resume Command
*
* Resume paused swarm sessions
*/
import { Command } from 'commander';
import chalk from 'chalk';
import { HiveMindSessionManager } from '../../simple-commands/hive-mind/session-manager.js';
import inquirer from 'inquirer';
export const resumeCommand = new Command('resume')
.description('Resume paused hive mind sessions')
.option('-s, --session <id>', 'Resume specific session by ID')
.action(async (options) => {
const sessionManager = new HiveMindSessionManager();
try {
if (options.session) {
// Resume specific session
const sessionId = options.session;
console.log(chalk.cyan(`Resuming session ${sessionId}...`));
const session = await sessionManager.resumeSession(sessionId);
console.log(chalk.green(`✓ Session ${sessionId} resumed successfully`));
console.log(chalk.gray(`Swarm: ${session.swarm_name}`));
console.log(chalk.gray(`Objective: ${session.objective}`));
console.log(chalk.gray(`Progress: ${session.statistics.completionPercentage}%`));
} else {
// Interactive selection
const sessions = sessionManager.getActiveSessions().filter(s => s.status === 'paused');
if (sessions.length === 0) {
console.log(chalk.yellow('No paused sessions found to resume'));
return;
}
const { sessionId } = await inquirer.prompt([{
type: 'list',
name: 'sessionId',
message: 'Select session to resume:',
choices: sessions.map(s => ({
name: `${s.swarm_name} (${s.id}) - ${s.completion_percentage}% complete`,
value: s.id
}))
}]);
console.log(chalk.cyan(`Resuming session ${sessionId}...`));
const session = await sessionManager.resumeSession(sessionId);
console.log(chalk.green(`✓ Session resumed successfully`));
console.log(chalk.gray(`Swarm: ${session.swarm_name}`));
console.log(chalk.gray(`Objective: ${session.objective}`));
console.log(chalk.gray(`Progress: ${session.statistics.completionPercentage}%`));
}
} catch (error) {
console.error(chalk.red('Error resuming session:'), error.message);
process.exit(1);
} finally {
sessionManager.close();
}
});
+134
View File
@@ -0,0 +1,134 @@
#!/usr/bin/env node
/**
* Hive Mind Stop Command
*
* Stop active swarm sessions and terminate child processes
*/
import { Command } from 'commander';
import chalk from 'chalk';
import { HiveMindSessionManager } from '../../simple-commands/hive-mind/session-manager.js';
import inquirer from 'inquirer';
export const stopCommand = new Command('stop')
.description('Stop active hive mind sessions')
.option('-s, --session <id>', 'Stop specific session by ID')
.option('-a, --all', 'Stop all active sessions')
.option('-f, --force', 'Force stop without confirmation')
.action(async (options) => {
const sessionManager = new HiveMindSessionManager();
try {
if (options.all) {
// Stop all active sessions
const sessions = sessionManager.getActiveSessionsWithProcessInfo();
if (sessions.length === 0) {
console.log(chalk.yellow('No active sessions found'));
return;
}
if (!options.force) {
const { confirm } = await inquirer.prompt([{
type: 'confirm',
name: 'confirm',
message: `Stop all ${sessions.length} active session(s)?`,
default: false
}]);
if (!confirm) {
console.log(chalk.gray('Operation cancelled'));
return;
}
}
for (const session of sessions) {
console.log(chalk.cyan(`Stopping session ${session.id}...`));
await sessionManager.stopSession(session.id);
console.log(chalk.green(`✓ Session ${session.id} stopped`));
}
console.log(chalk.green(`\n✅ All sessions stopped successfully`));
} else if (options.session) {
// Stop specific session
const sessionId = options.session;
const session = sessionManager.getSession(sessionId);
if (!session) {
console.log(chalk.red(`Session ${sessionId} not found`));
return;
}
if (session.status === 'stopped') {
console.log(chalk.yellow(`Session ${sessionId} is already stopped`));
return;
}
if (!options.force) {
const { confirm } = await inquirer.prompt([{
type: 'confirm',
name: 'confirm',
message: `Stop session ${sessionId} (${session.swarm_name})?`,
default: false
}]);
if (!confirm) {
console.log(chalk.gray('Operation cancelled'));
return;
}
}
console.log(chalk.cyan(`Stopping session ${sessionId}...`));
await sessionManager.stopSession(sessionId);
console.log(chalk.green(`✓ Session ${sessionId} stopped successfully`));
} else {
// Interactive selection
const sessions = sessionManager.getActiveSessionsWithProcessInfo();
if (sessions.length === 0) {
console.log(chalk.yellow('No active sessions found'));
return;
}
const { sessionId } = await inquirer.prompt([{
type: 'list',
name: 'sessionId',
message: 'Select session to stop:',
choices: sessions.map(s => ({
name: `${s.swarm_name} (${s.id}) - ${s.total_processes} process(es)`,
value: s.id
}))
}]);
const { confirm } = await inquirer.prompt([{
type: 'confirm',
name: 'confirm',
message: 'Stop this session?',
default: false
}]);
if (!confirm) {
console.log(chalk.gray('Operation cancelled'));
return;
}
console.log(chalk.cyan(`Stopping session ${sessionId}...`));
await sessionManager.stopSession(sessionId);
console.log(chalk.green(`✓ Session stopped successfully`));
}
// Clean up orphaned processes
const cleanedCount = sessionManager.cleanupOrphanedProcesses();
if (cleanedCount > 0) {
console.log(chalk.blue(`\nCleaned up ${cleanedCount} orphaned session(s)`));
}
} catch (error) {
console.error(chalk.red('Error stopping session:'), error.message);
process.exit(1);
} finally {
sessionManager.close();
}
});
+16
View File
@@ -2236,6 +2236,22 @@ Now, please proceed with the task: ${task}`;
const { taskCommand } = await import('./hive-mind/task.js');
await taskCommand.parseAsync(process.argv.slice(3));
break;
case "stop":
const { stopCommand } = await import('./hive-mind/stop.js');
await stopCommand.parseAsync(process.argv.slice(3));
break;
case "pause":
const { pauseCommand } = await import('./hive-mind/pause.js');
await pauseCommand.parseAsync(process.argv.slice(3));
break;
case "resume":
const { resumeCommand } = await import('./hive-mind/resume.js');
await resumeCommand.parseAsync(process.argv.slice(3));
break;
case "ps":
const { psCommand } = await import('./hive-mind/ps.js');
await psCommand.parseAsync(process.argv.slice(3));
break;
case "wizard":
default:
const { wizardCommand } = await import('./hive-mind/wizard.js');
+5 -1
View File
@@ -161,7 +161,11 @@ export async function swarmAction(ctx: CommandContext) {
await Deno.mkdir(swarmDir, { recursive: true });
// Create objective in coordinator
const objectiveId = await coordinator.createObjective(objective, options.strategy);
const objectiveId = await coordinator.createObjective(
`Swarm Task ${Date.now()}`,
objective,
options.strategy || 'auto'
);
console.log(`\n📝 Objective created with ID: ${objectiveId}`);
+2 -2
View File
@@ -3,14 +3,14 @@
* Provides clear, actionable command documentation
*/
export const VERSION = '2.0.0-alpha.57';
export const VERSION = '2.0.0-alpha.58';
export const MAIN_HELP = `
🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform
🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 87 MCP tools, neural networking, and production-ready infrastructure
🐝 NEW: Advanced Hive Mind System with Queen-led coordination, collective intelligence, and unlimited scaling
⚡ ALPHA 57: Complete Alpha 57 fixes - TypeScript refactoring, PR review system, and enhanced stability
⚡ ALPHA 58: Hive-mind wizard prompt generation, session cleanup, Claude API config, and TypeScript fixes
USAGE:
claude-flow <command> [options]
+1 -1
View File
@@ -130,7 +130,7 @@ async function main() {
}
}
if (import.meta.main) {
if (import.meta.url === `file://${Deno.execPath()}`) {
main().catch((error) => {
printError(`Error: ${(error instanceof Error ? error.message : String(error))}`);
process.exit(1);
+18 -22
View File
@@ -38,17 +38,13 @@ const cli = new Command()
.description('Claude-Flow: Advanced AI agent orchestration system for multi-agent coordination')
// .meta() commented out - not available
// .meta() commented out - not available
.globalOption('-c, --config <path:string>', 'Path to configuration file', {
default: './claude-flow.config.json',
})
.globalOption('-v, --verbose', 'Enable verbose logging')
.globalOption('-q, --quiet', 'Suppress non-essential output')
.globalOption('--log-level <level:string>', 'Set log level (debug, info, warn, error)', {
default: 'info',
})
.globalOption('--no-color', 'Disable colored output')
.globalOption('--json', 'Output in JSON format where applicable')
.globalOption('--profile <profile:string>', 'Use named configuration profile')
.option('-c, --config <path>', 'Path to configuration file', './claude-flow.config.json')
.option('-v, --verbose', 'Enable verbose logging')
.option('-q, --quiet', 'Suppress non-essential output')
.option('--log-level <level>', 'Set log level (debug, info, warn, error)', 'info')
.option('--no-color', 'Disable colored output')
.option('--json', 'Output in JSON format where applicable')
.option('--profile <profile>', 'Use named configuration profile')
.action(async (options: any) => {
// If no subcommand, show banner and start REPL
await setupLogging(options);
@@ -63,17 +59,17 @@ const cli = new Command()
// Add subcommands
cli
.command('start', startCommand)
.command('agent', agentCommand)
.command('task', taskCommand)
.command('memory', memoryCommand)
.command('config', configCommand)
.command('status', statusCommand)
.command('monitor', monitorCommand)
.command('session', sessionCommand)
.command('workflow', workflowCommand)
.command('mcp', mcpCommand)
.command('help', helpCommand)
.addCommand(startCommand)
.addCommand(agentCommand)
.addCommand(taskCommand)
.addCommand(memoryCommand)
.addCommand(configCommand)
.addCommand(statusCommand)
.addCommand(monitorCommand)
.addCommand(sessionCommand)
.addCommand(workflowCommand)
.addCommand(mcpCommand)
.addCommand(helpCommand)
.command('repl', new Command()
.description('Start interactive REPL mode with command completion')
.option('--no-banner', 'Skip welcome banner')
+18 -15
View File
@@ -59,7 +59,7 @@ class CommandHistory {
private async loadHistory(): Promise<void> {
try {
const content = await fs.readFile(this.historyFile);
const content = await fs.readFile(this.historyFile, 'utf-8');
this.history = content.split('\n').filter((line: string) => line.trim());
} catch {
// History file doesn't exist yet
@@ -495,9 +495,10 @@ function showHelp(commands: REPLCommand[]): void {
console.log(chalk.white.bold('Available Commands:'));
console.log();
const table = new Table()
.header(['Command', 'Aliases', 'Description'])
.border(false);
const table = new Table({
head: ['Command', 'Aliases', 'Description'],
style: { 'padding-left': 0, 'padding-right': 1, border: [] }
});
for (const cmd of commands) {
table.push([
@@ -643,9 +644,9 @@ async function showAgentList(): Promise<void> {
console.log(chalk.cyan.bold(`Active Agents (${agents.length})`));
console.log('─'.repeat(50));
const table = new Table()
.header(['ID', 'Name', 'Type', 'Status', 'Tasks'])
.border(true);
const table = new Table({
head: ['ID', 'Name', 'Type', 'Status', 'Tasks']
});
for (const agent of agents) {
const statusIcon = formatStatusIndicator(agent.status);
@@ -688,10 +689,12 @@ async function handleAgentSpawn(args: string[]): Promise<void> {
}
async function handleAgentTerminate(agentId: string): Promise<void> {
const confirmed = await confirm.prompt({
const { confirmed } = await inquirer.prompt([{
type: 'confirm',
name: 'confirmed',
message: `Terminate agent ${agentId}?`,
default: false,
});
}]);
if (!confirmed) {
console.log(chalk.gray('Termination cancelled'));
@@ -765,9 +768,9 @@ async function showTaskList(): Promise<void> {
console.log(chalk.cyan.bold(`Tasks (${tasks.length})`));
console.log('─'.repeat(60));
const table = new Table()
.header(['ID', 'Type', 'Description', 'Status', 'Agent'])
.border(true);
const table = new Table({
head: ['ID', 'Type', 'Description', 'Status', 'Agent']
});
for (const task of tasks) {
const statusIcon = formatStatusIndicator(task.status);
@@ -902,9 +905,9 @@ async function showSessionList(): Promise<void> {
console.log(chalk.cyan.bold(`Saved Sessions (${sessions.length})`));
console.log('─'.repeat(50));
const table = new Table()
.header(['ID', 'Name', 'Date', 'Agents', 'Tasks'])
.border(true);
const table = new Table({
head: ['ID', 'Name', 'Date', 'Agents', 'Tasks']
});
for (const session of sessions) {
table.push([
+1 -1
View File
@@ -1193,7 +1193,7 @@ async function main() {
}
// Parse flags
const flags = {};
const flags: Record<string, any> = {};
for (let i = taskEndIndex; i < subArgs.length; i++) {
const arg = subArgs[i];
if (arg === '--tools' || arg === '-t') {
+132 -22
View File
@@ -39,6 +39,7 @@ ${chalk.bold('SUBCOMMANDS:')}
${chalk.green('spawn')} Spawn hive mind swarm for a task
${chalk.green('status')} Show hive mind status
${chalk.green('resume')} Resume a paused hive mind session
${chalk.green('stop')} Stop a running hive mind session
${chalk.green('sessions')} List all hive mind sessions
${chalk.green('consensus')} View consensus decisions
${chalk.green('memory')} Manage collective memory
@@ -1290,6 +1291,10 @@ export async function hiveMindCommand(args, flags) {
await resumeSession(subArgs, flags);
break;
case 'stop':
await stopSession(subArgs, flags);
break;
case 'consensus':
await showConsensus(flags);
break;
@@ -1679,6 +1684,11 @@ async function spawnClaudeCodeInstances(swarmId, swarmName, objective, workers,
console.log(chalk.cyan('MCP Tools:'), 'Full Claude-Flow integration enabled');
try {
// ALWAYS save the prompt file first (fix for issue #330)
const promptFile = `hive-mind-prompt-${swarmId}.txt`;
await writeFile(promptFile, hiveMindPrompt, 'utf8');
console.log(chalk.green(`\n✓ Hive Mind prompt saved to: ${promptFile}`));
// Check if claude command exists
const { spawn: childSpawn, execSync } = await import('child_process');
let claudeAvailable = false;
@@ -1695,7 +1705,8 @@ async function spawnClaudeCodeInstances(swarmId, swarmName, objective, workers,
if (claudeAvailable && !flags.dryRun) {
// Pass the prompt directly as an argument to claude
const claudeArgs = [hiveMindPrompt];
// Using non-interactive mode to prevent hanging
const claudeArgs = [hiveMindPrompt, '--no-interactive'];
// Add auto-permission flag by default for hive-mind mode (unless explicitly disabled)
if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {
@@ -1704,31 +1715,49 @@ async function spawnClaudeCodeInstances(swarmId, swarmName, objective, workers,
}
// Spawn claude with the prompt as the first argument
// Use 'pipe' instead of 'inherit' to prevent terminal conflicts
const claudeProcess = childSpawn('claude', claudeArgs, {
stdio: 'inherit',
stdio: 'pipe',
shell: false
});
// Handle stdout
if (claudeProcess.stdout) {
claudeProcess.stdout.on('data', (data) => {
console.log(data.toString());
});
}
// Handle stderr
if (claudeProcess.stderr) {
claudeProcess.stderr.on('data', (data) => {
console.error(chalk.red(data.toString()));
});
}
// Handle process exit
claudeProcess.on('exit', (code) => {
if (code === 0) {
console.log(chalk.green('\n✓ Claude Code completed successfully'));
} else {
console.log(chalk.red(`\n✗ Claude Code exited with code ${code}`));
}
});
console.log(chalk.green('\n✓ Claude Code launched with Hive Mind coordination'));
console.log(chalk.blue(' The Queen coordinator will orchestrate all worker agents'));
console.log(chalk.blue(' Use MCP tools for collective intelligence and task distribution'));
console.log(chalk.gray(` Prompt file saved at: ${promptFile}`));
} else if (flags.dryRun) {
console.log(chalk.blue('\nDry run - would execute Claude Code with prompt:'));
console.log(chalk.gray('Prompt length:'), hiveMindPrompt.length, 'characters');
console.log(chalk.gray('\nFirst 500 characters of prompt:'));
console.log(chalk.yellow(hiveMindPrompt.substring(0, 500) + '...'));
// Save prompt to file for inspection
const promptFile = `hive-mind-prompt-${swarmId}.txt`;
await writeFile(promptFile, hiveMindPrompt, 'utf8');
console.log(chalk.green(`\n✓ Full prompt saved to: ${promptFile}`));
console.log(chalk.gray(`\nFull prompt saved to: ${promptFile}`));
} else {
// Claude not available - save prompt and show instructions
const promptFile = `hive-mind-prompt-${swarmId}.txt`;
await writeFile(promptFile, hiveMindPrompt, 'utf8');
// Claude not available - show instructions with already saved prompt
console.log(chalk.yellow('\n📋 Manual Execution Instructions:'));
console.log(chalk.gray('─'.repeat(50)));
console.log(chalk.gray('1. Install Claude Code:'));
@@ -2158,10 +2187,11 @@ async function resumeSession(args, flags) {
return;
}
if (session.status !== 'paused') {
spinner.fail(`Session is not paused (status: ${session.status})`);
sessionManager.close();
return;
// Allow resuming any session regardless of status
spinner.text = `Resuming session from status: ${session.status}...`;
if (session.status === 'stopped') {
spinner.text = 'Restarting stopped session with original configuration...';
}
// Resume the session
@@ -2224,6 +2254,60 @@ async function resumeSession(args, flags) {
}
}
/**
* Stop a hive mind session
*/
async function stopSession(args, flags) {
const sessionId = args[0];
if (!sessionId) {
console.error(chalk.red('Error: Please provide a session ID'));
console.log('Usage: claude-flow hive-mind stop <session-id>');
console.log('Run "claude-flow hive-mind sessions" to see available sessions');
return;
}
const spinner = ora('Stopping Hive Mind session...').start();
try {
const sessionManager = new HiveMindSessionManager();
// Get session details
const session = sessionManager.getSession(sessionId);
if (!session) {
spinner.fail(`Session ${sessionId} not found`);
console.log('\nRun "claude-flow hive-mind sessions" to see available sessions');
sessionManager.close();
return;
}
// Stop the session
await sessionManager.stopSession(sessionId);
spinner.succeed('Session stopped successfully!');
// Display session summary
console.log('\n' + chalk.bold('🛑 Stopped Session Summary:'));
console.log(chalk.gray('─'.repeat(50)));
console.log(chalk.cyan('Session ID:'), sessionId);
console.log(chalk.cyan('Swarm Name:'), session.swarm_name || 'Unknown');
console.log(chalk.cyan('Final Status:'), 'Stopped');
console.log(chalk.cyan('Active Agents:'), session.statistics ? session.statistics.activeAgents : 0);
console.log(chalk.gray('─'.repeat(50)));
console.log('\n' + chalk.yellow('💡 Session has been stopped and all processes cleaned up.'));
console.log(chalk.gray('To resume this session later, use: claude-flow hive-mind resume ' + sessionId));
sessionManager.close();
} catch (error) {
spinner.fail('Failed to stop session');
console.error(chalk.red('Error:'), error.message);
exit(1);
}
}
/**
* Generate prompt for restored session
*/
@@ -2288,6 +2372,11 @@ Resume the hive mind operation and continue working towards the objective.`;
*/
async function launchClaudeWithContext(prompt, flags) {
try {
// ALWAYS save the prompt file first (fix for issue #330)
const promptFile = `hive-mind-resume-${Date.now()}.txt`;
await writeFile(promptFile, prompt);
console.log(chalk.green(`\n✓ Session context saved to: ${promptFile}`));
const { spawn: childSpawn, execSync } = await import('child_process');
let claudeAvailable = false;
@@ -2296,28 +2385,49 @@ async function launchClaudeWithContext(prompt, flags) {
claudeAvailable = true;
} catch {
console.log(chalk.yellow('\n⚠️ Claude Code CLI not found'));
// Save prompt to file
const promptFile = `hive-mind-resume-${Date.now()}.txt`;
await writeFile(promptFile, prompt);
console.log(chalk.green(`\n✓ Session context saved to: ${promptFile}`));
console.log(chalk.gray('Install Claude Code: npm install -g @anthropic-ai/claude-code'));
console.log(chalk.gray(`Run with: claude < ${promptFile}`));
return;
}
if (claudeAvailable && !flags.dryRun) {
const claudeArgs = [prompt];
const claudeArgs = [prompt, '--no-interactive'];
if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {
claudeArgs.push('--dangerously-skip-permissions');
}
// Use 'pipe' instead of 'inherit' to prevent terminal conflicts
const claudeProcess = childSpawn('claude', claudeArgs, {
stdio: 'inherit',
stdio: 'pipe',
shell: false
});
// Handle stdout
if (claudeProcess.stdout) {
claudeProcess.stdout.on('data', (data) => {
console.log(data.toString());
});
}
// Handle stderr
if (claudeProcess.stderr) {
claudeProcess.stderr.on('data', (data) => {
console.error(chalk.red(data.toString()));
});
}
// Handle process exit
claudeProcess.on('exit', (code) => {
if (code === 0) {
console.log(chalk.green('\n✓ Claude Code completed successfully'));
} else {
console.log(chalk.red(`\n✗ Claude Code exited with code ${code}`));
}
});
console.log(chalk.green('\n✓ Claude Code launched with restored session context'));
console.log(chalk.gray(` Prompt file saved at: ${promptFile}`));
}
} catch (error) {
console.error(chalk.red('Failed to launch Claude Code:'), error.message);
@@ -13,6 +13,7 @@ export class AutoSaveMiddleware {
this.saveTimer = null;
this.pendingChanges = [];
this.isActive = false;
this.childProcesses = new Set();
}
/**
@@ -37,14 +38,16 @@ export class AutoSaveMiddleware {
this.performAutoSave();
});
process.on('SIGINT', () => {
this.performAutoSave();
process.exit();
process.on('SIGINT', async () => {
console.log('\n\nReceived SIGINT, cleaning up...');
await this.cleanup();
process.exit(0);
});
process.on('SIGTERM', () => {
this.performAutoSave();
process.exit();
process.on('SIGTERM', async () => {
console.log('\n\nReceived SIGTERM, cleaning up...');
await this.cleanup();
process.exit(0);
});
}
@@ -213,6 +216,77 @@ export class AutoSaveMiddleware {
isAutoSaveActive() {
return this.isActive;
}
/**
* Register a child process
*/
registerChildProcess(childProcess) {
if (childProcess && childProcess.pid) {
this.childProcesses.add(childProcess);
this.sessionManager.addChildPid(this.sessionId, childProcess.pid);
// Remove from tracking when process exits
childProcess.on('exit', () => {
this.childProcesses.delete(childProcess);
this.sessionManager.removeChildPid(this.sessionId, childProcess.pid);
});
}
}
/**
* Clean up all resources and child processes
*/
async cleanup() {
try {
// Stop the save timer
if (this.saveTimer) {
clearInterval(this.saveTimer);
this.saveTimer = null;
}
// Perform final save
await this.performAutoSave();
// Terminate all child processes
for (const childProcess of this.childProcesses) {
try {
if (childProcess.pid) {
console.log(`Terminating child process ${childProcess.pid}...`);
childProcess.kill('SIGTERM');
// Give it a moment to terminate gracefully
await new Promise(resolve => setTimeout(resolve, 100));
// Force kill if still alive
try {
process.kill(childProcess.pid, 0); // Check if still alive
childProcess.kill('SIGKILL');
} catch (e) {
// Process already dead, good
}
}
} catch (error) {
console.error(`Failed to terminate child process:`, error.message);
}
}
// Clear the set
this.childProcesses.clear();
// Stop the session if it's still active
const session = this.sessionManager.getSession(this.sessionId);
if (session && (session.status === 'active' || session.status === 'paused')) {
await this.sessionManager.stopSession(this.sessionId);
}
// Close database connection
this.sessionManager.close();
console.log('Cleanup completed successfully');
} catch (error) {
console.error('Error during cleanup:', error);
}
}
}
/**
@@ -40,6 +40,7 @@ export class HiveMindSessionManager {
* Initialize database schema for sessions
*/
initializeSchema() {
// Create the base schema
this.db.exec(`
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
@@ -77,6 +78,33 @@ export class HiveMindSessionManager {
FOREIGN KEY (session_id) REFERENCES sessions(id)
);
`);
// Run migrations to add new columns
this.runMigrations();
}
/**
* Run database migrations
*/
runMigrations() {
try {
// Check if parent_pid column exists
const columns = this.db.prepare("PRAGMA table_info(sessions)").all();
const hasParentPid = columns.some(col => col.name === 'parent_pid');
const hasChildPids = columns.some(col => col.name === 'child_pids');
if (!hasParentPid) {
this.db.exec('ALTER TABLE sessions ADD COLUMN parent_pid INTEGER');
console.log('Added parent_pid column to sessions table');
}
if (!hasChildPids) {
this.db.exec('ALTER TABLE sessions ADD COLUMN child_pids TEXT');
console.log('Added child_pids column to sessions table');
}
} catch (error) {
console.error('Migration error:', error);
}
}
/**
@@ -86,17 +114,18 @@ export class HiveMindSessionManager {
const sessionId = `session-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
const stmt = this.db.prepare(`
INSERT INTO sessions (id, swarm_id, swarm_name, objective, metadata)
VALUES (?, ?, ?, ?, ?)
INSERT INTO sessions (id, swarm_id, swarm_name, objective, metadata, parent_pid)
VALUES (?, ?, ?, ?, ?, ?)
`);
stmt.run(sessionId, swarmId, swarmName, objective, JSON.stringify(metadata));
stmt.run(sessionId, swarmId, swarmName, objective, JSON.stringify(metadata), process.pid);
// Log session creation
this.logSessionEvent(sessionId, 'info', 'Session created', null, {
swarmId,
swarmName,
objective
objective,
parentPid: process.pid
});
return sessionId;
@@ -266,7 +295,7 @@ export class HiveMindSessionManager {
}
/**
* Resume a paused session
* Resume any previous session (paused, stopped, or inactive)
*/
async resumeSession(sessionId) {
const session = this.getSession(sessionId);
@@ -275,8 +304,12 @@ export class HiveMindSessionManager {
throw new Error(`Session ${sessionId} not found`);
}
if (session.status !== 'paused') {
throw new Error(`Session ${sessionId} is not paused (status: ${session.status})`);
// Allow resuming any session regardless of status
console.log(`Resuming session ${sessionId} from status: ${session.status}`);
// If session was stopped, log that we're restarting it
if (session.status === 'stopped') {
this.logSessionEvent(sessionId, 'info', `Restarting stopped session with original configuration`);
}
// Update session status
@@ -511,6 +544,164 @@ export class HiveMindSessionManager {
return newSessionId;
}
/**
* Add a child process PID to session
*/
addChildPid(sessionId, pid) {
const session = this.db.prepare('SELECT child_pids FROM sessions WHERE id = ?').get(sessionId);
if (!session) return false;
const childPids = session.child_pids ? JSON.parse(session.child_pids) : [];
if (!childPids.includes(pid)) {
childPids.push(pid);
}
const stmt = this.db.prepare(`
UPDATE sessions
SET child_pids = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`);
stmt.run(JSON.stringify(childPids), sessionId);
this.logSessionEvent(sessionId, 'info', 'Child process added', null, { pid });
return true;
}
/**
* Remove a child process PID from session
*/
removeChildPid(sessionId, pid) {
const session = this.db.prepare('SELECT child_pids FROM sessions WHERE id = ?').get(sessionId);
if (!session) return false;
const childPids = session.child_pids ? JSON.parse(session.child_pids) : [];
const index = childPids.indexOf(pid);
if (index > -1) {
childPids.splice(index, 1);
}
const stmt = this.db.prepare(`
UPDATE sessions
SET child_pids = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`);
stmt.run(JSON.stringify(childPids), sessionId);
this.logSessionEvent(sessionId, 'info', 'Child process removed', null, { pid });
return true;
}
/**
* Get all child PIDs for a session
*/
getChildPids(sessionId) {
const session = this.db.prepare('SELECT child_pids FROM sessions WHERE id = ?').get(sessionId);
if (!session || !session.child_pids) return [];
return JSON.parse(session.child_pids);
}
/**
* Stop a session and terminate all child processes
*/
async stopSession(sessionId) {
const session = this.getSession(sessionId);
if (!session) {
throw new Error(`Session ${sessionId} not found`);
}
// Get child PIDs
const childPids = this.getChildPids(sessionId);
// Terminate child processes
for (const pid of childPids) {
try {
process.kill(pid, 'SIGTERM');
this.logSessionEvent(sessionId, 'info', 'Child process terminated', null, { pid });
} catch (err) {
// Process might already be dead
this.logSessionEvent(sessionId, 'warning', 'Failed to terminate child process', null, {
pid,
error: err.message
});
}
}
// Update session status
const stmt = this.db.prepare(`
UPDATE sessions
SET status = 'stopped', updated_at = CURRENT_TIMESTAMP
WHERE id = ?
`);
stmt.run(sessionId);
// Update swarm status
this.db.prepare('UPDATE swarms SET status = ? WHERE id = ?').run('stopped', session.swarm_id);
this.logSessionEvent(sessionId, 'info', 'Session stopped');
return true;
}
/**
* Get active sessions with process information
*/
getActiveSessionsWithProcessInfo() {
const sessions = this.getActiveSessions();
// Add process info to each session
return sessions.map(session => {
const childPids = session.child_pids ? JSON.parse(session.child_pids) : [];
const aliveChildPids = [];
// Check which child processes are still alive
for (const pid of childPids) {
try {
process.kill(pid, 0); // Signal 0 just checks if process exists
aliveChildPids.push(pid);
} catch (err) {
// Process is dead
}
}
return {
...session,
parent_pid: session.parent_pid,
child_pids: aliveChildPids,
total_processes: 1 + aliveChildPids.length
};
});
}
/**
* Clean up orphaned processes
*/
cleanupOrphanedProcesses() {
const sessions = this.db.prepare(`
SELECT * FROM sessions
WHERE status IN ('active', 'paused')
`).all();
let cleanedCount = 0;
for (const session of sessions) {
// Check if parent process is still alive
try {
process.kill(session.parent_pid, 0);
} catch (err) {
// Parent is dead, clean up session
this.stopSession(session.id);
cleanedCount++;
this.logSessionEvent(session.id, 'info', 'Orphaned session cleaned up');
}
}
return cleanedCount;
}
/**
* Clean up and close database connection
*/