Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

updates

rUv78b06917cd02
diff --git a/package.json b/package.json
index 3fc3a44d3c..209cd7daf7 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "claude-flow",
- "version": "1.0.41",
+ "version": "1.0.42",
"description": "Advanced AI agent orchestration system for Claude Code",
"main": "src/cli/main.ts",
"bin": {
diff --git a/src/cli/cli-core.ts b/src/cli/cli-core.ts
index 985fdfce61..af86871127 100644
--- a/src/cli/cli-core.ts
+++ b/src/cli/cli-core.ts
@@ -8,7 +8,7 @@ import { red, green, yellow, blue, bold, cyan } from "https://deno.land/[email protected]
import { ensureDir } from "https://deno.land/[email protected]/fs/mod.ts";
import { join } from "https://deno.land/[email protected]/path/mod.ts";
-export const VERSION = "1.0.41";
+export const VERSION = "1.0.42";
interface CommandContext {
args: string[];
diff --git a/src/cli/commands/start.ts b/src/cli/commands/start.ts
index 48287862a2..121b1693c3 100644
--- a/src/cli/commands/start.ts
+++ b/src/cli/commands/start.ts
@@ -1,156 +1,6 @@
/**
* Start command for Claude-Flow
+ * Re-exports the modular implementation
*/
-import { Command } from '@cliffy/command';
-import { colors } from '@cliffy/ansi/colors';
-import { Orchestrator } from '../../core/orchestrator.ts';
-import { eventBus } from '../../core/event-bus.ts';
-import { logger } from '../../core/logger.ts';
-import { configManager } from '../../core/config.ts';
-import { TerminalManager } from '../../terminal/manager.ts';
-import { MemoryManager } from '../../memory/manager.ts';
-import { CoordinationManager } from '../../coordination/manager.ts';
-import { MCPServer } from '../../mcp/server.ts';
-import { SystemEvents } from '../../utils/types.ts';
-// Spinner is not available in the current cliffy version, use simple text instead
-
-export const startCommand = new Command()
- .description('Start the Claude-Flow orchestration system')
- .option('-d, --daemon', 'Run as daemon in background')
- .option('-p, --port <port:number>', 'MCP server port', { default: 3000 })
- .option('--mcp-transport <transport:string>', 'MCP transport type (stdio, http)', {
- default: 'stdio',
- })
- .action(async (options: any) => {
- console.log(colors.cyan('Starting Claude-Flow...'));
-
- try {
- // Load configuration
- const config = await configManager.load(options.config || undefined);
-
- // Override MCP settings from CLI options
- if (options.port) {
- config.mcp.port = options.port;
- }
- if (options.mcpTransport) {
- config.mcp.transport = options.mcpTransport as any;
- }
-
- // Create components
- const terminalManager = new TerminalManager(
- config.terminal,
- eventBus,
- logger,
- );
-
- const memoryManager = new MemoryManager(
- config.memory,
- eventBus,
- logger,
- );
-
- const coordinationManager = new CoordinationManager(
- config.coordination,
- eventBus,
- logger,
- );
-
- const mcpServer = new MCPServer(
- config.mcp,
- eventBus,
- logger,
- );
-
- // Create orchestrator
- const orchestrator = new Orchestrator(
- config,
- terminalManager,
- memoryManager,
- coordinationManager,
- mcpServer,
- eventBus,
- logger,
- );
-
- // Initialize orchestrator
- await orchestrator.initialize();
-
- // spinner.stop();
- console.log(colors.green.bold('βœ“'), 'Claude-Flow started successfully!');
-
- if (config.mcp.transport === 'http') {
- console.log(colors.cyan('MCP server listening on'),
- colors.yellow(`http://${config.mcp.host || 'localhost'}:${config.mcp.port}`));
- } else {
- console.log(colors.cyan('MCP server listening on'), colors.yellow('stdio'));
- }
-
- // Set up graceful shutdown
- const shutdown = async () => {
- console.log('\n' + colors.yellow('Shutting down Claude-Flow...'));
- eventBus.emit('shutdown');
- await orchestrator.shutdown();
- console.log(colors.green.bold('βœ“'), 'Shutdown complete');
- Deno.exit(0);
- };
-
- Deno.addSignalListener('SIGINT', shutdown);
- Deno.addSignalListener('SIGTERM', shutdown);
-
- // Set up event listeners for logging
- setupEventListeners();
-
- if (options.daemon) {
- console.log(colors.gray('Running in daemon mode. Press Ctrl+C to stop.'));
- // Keep the process running
- await new Promise<void>((resolve) => {
- // This promise will only resolve when shutdown is called
- eventBus.once('shutdown', resolve);
- });
- } else {
- console.log(colors.gray('Press Ctrl+C to stop.'));
- // Keep the process running in interactive mode
- await new Promise<void>((resolve) => {
- // This promise will only resolve when shutdown is called
- eventBus.once('shutdown', resolve);
- });
- }
- } catch (error) {
- // spinner.stop();
- throw error;
- }
- });
-
-function setupEventListeners(): void {
- // Log important events
- eventBus.on(SystemEvents.AGENT_SPAWNED, (data: any) => {
- const { agentId, profile } = data;
- console.log(colors.blue('β†’'), `Agent spawned: ${colors.cyan(agentId)} (${profile.type})`);
- });
-
- eventBus.on(SystemEvents.AGENT_TERMINATED, (data: any) => {
- const { agentId, reason } = data;
- console.log(colors.red('←'), `Agent terminated: ${colors.cyan(agentId)} - ${reason}`);
- });
-
- eventBus.on(SystemEvents.TASK_ASSIGNED, (data: any) => {
- const { taskId, agentId } = data;
- console.log(colors.magenta('β—†'), `Task ${colors.yellow(taskId)} assigned to ${colors.cyan(agentId)}`);
- });
-
- eventBus.on(SystemEvents.TASK_COMPLETED, (data: any) => {
- const { taskId } = data;
- console.log(colors.green('βœ“'), `Task completed: ${colors.yellow(taskId)}`);
- });
-
- eventBus.on(SystemEvents.TASK_FAILED, (data: any) => {
- const { taskId, error } = data;
- console.log(colors.red('βœ—'), `Task failed: ${colors.yellow(taskId)} - ${error.message}`);
- });
-
- eventBus.on(SystemEvents.SYSTEM_ERROR, (data: any) => {
- const { component, error } = data;
- console.error(colors.red.bold('System Error:'), `${component} - ${error.message}`);
- });
-}
\ No newline at end of file
+export { startCommand } from './start/index.ts';
\ No newline at end of file
diff --git a/src/cli/commands/start/index.ts b/src/cli/commands/start/index.ts
new file mode 100644
index 0000000000..111d5f102d
--- /dev/null
+++ b/src/cli/commands/start/index.ts
@@ -0,0 +1,10 @@
+/**
+ * Modular start command implementation
+ * Consolidates all start functionality into a single, extensible structure
+ */
+
+export { startCommand } from './start-command.ts';
+export { ProcessManager } from './process-manager.ts';
+export { ProcessUI } from './process-ui.ts';
+export { SystemMonitor } from './system-monitor.ts';
+export type { ProcessInfo, ProcessStatus, SystemStats } from './types.ts';
\ No newline at end of file
diff --git a/src/cli/commands/start/process-manager.ts b/src/cli/commands/start/process-manager.ts
new file mode 100644
index 0000000000..e521fef012
--- /dev/null
+++ b/src/cli/commands/start/process-manager.ts
@@ -0,0 +1,346 @@
+/**
+ * Process Manager - Handles lifecycle of system processes
+ */
+
+import { EventEmitter } from 'https://deno.land/[email protected]/async/mod.ts';
+import { colors } from '@cliffy/ansi/colors';
+import {
+ ProcessInfo,
+ ProcessType,
+ ProcessStatus,
+ ProcessMetrics,
+ SystemStats
+} from './types.ts';
+import { Orchestrator } from '../../../core/orchestrator.ts';
+import { TerminalManager } from '../../../terminal/manager.ts';
+import { MemoryManager } from '../../../memory/manager.ts';
+import { CoordinationManager } from '../../../coordination/manager.ts';
+import { MCPServer } from '../../../mcp/server.ts';
+import { eventBus } from '../../../core/event-bus.ts';
+import { logger } from '../../../core/logger.ts';
+import { configManager } from '../../../core/config.ts';
+
+export class ProcessManager extends EventEmitter {
+ private processes: Map<string, ProcessInfo> = new Map();
+ private orchestrator?: Orchestrator;
+ private terminalManager?: TerminalManager;
+ private memoryManager?: MemoryManager;
+ private coordinationManager?: CoordinationManager;
+ private mcpServer?: MCPServer;
+ private config: any;
+
+ constructor() {
+ super();
+ this.initializeProcesses();
+ }
+
+ private initializeProcesses(): void {
+ // Define all manageable processes
+ const processDefinitions: ProcessInfo[] = [
+ {
+ id: 'event-bus',
+ name: 'Event Bus',
+ type: ProcessType.EVENT_BUS,
+ status: ProcessStatus.STOPPED
+ },
+ {
+ id: 'orchestrator',
+ name: 'Orchestrator Engine',
+ type: ProcessType.ORCHESTRATOR,
+ status: ProcessStatus.STOPPED
+ },
+ {
+ id: 'memory-manager',
+ name: 'Memory Manager',
+ type: ProcessType.MEMORY_MANAGER,
+ status: ProcessStatus.STOPPED
+ },
+ {
+ id: 'terminal-pool',
+ name: 'Terminal Pool',
+ type: ProcessType.TERMINAL_POOL,
+ status: ProcessStatus.STOPPED
+ },
+ {
+ id: 'mcp-server',
+ name: 'MCP Server',
+ type: ProcessType.MCP_SERVER,
+ status: ProcessStatus.STOPPED
+ },
+ {
+ id: 'coordinator',
+ name: 'Coordination Manager',
+ type: ProcessType.COORDINATOR,
+ status: ProcessStatus.STOPPED
+ }
+ ];
+
+ for (const process of processDefinitions) {
+ this.processes.set(process.id, process);
+ }
+ }
+
+ async initialize(configPath?: string): Promise<void> {
+ try {
+ this.config = await configManager.load(configPath);
+ this.emit('initialized', { config: this.config });
+ } catch (error) {
+ this.emit('error', { component: 'ProcessManager', error });
+ throw error;
+ }
+ }
+
+ async startProcess(processId: string): Promise<void> {
+ const process = this.processes.get(processId);
+ if (!process) {
+ throw new Error(`Unknown process: ${processId}`);
+ }
+
+ if (process.status === ProcessStatus.RUNNING) {
+ throw new Error(`Process ${processId} is already running`);
+ }
+
+ this.updateProcessStatus(processId, ProcessStatus.STARTING);
+
+ try {
+ switch (process.type) {
+ case ProcessType.EVENT_BUS:
+ // Event bus is already initialized globally
+ process.pid = Deno.pid;
+ break;
+
+ case ProcessType.MEMORY_MANAGER:
+ this.memoryManager = new MemoryManager(
+ this.config.memory,
+ eventBus,
+ logger
+ );
+ await this.memoryManager.initialize();
+ break;
+
+ case ProcessType.TERMINAL_POOL:
+ this.terminalManager = new TerminalManager(
+ this.config.terminal,
+ eventBus,
+ logger
+ );
+ await this.terminalManager.initialize();
+ break;
+
+ case ProcessType.COORDINATOR:
+ this.coordinationManager = new CoordinationManager(
+ this.config.coordination,
+ eventBus,
+ logger
+ );
+ await this.coordinationManager.initialize();
+ break;
+
+ case ProcessType.MCP_SERVER:
+ this.mcpServer = new MCPServer(
+ this.config.mcp,
+ eventBus,
+ logger
+ );
+ await this.mcpServer.start();
+ break;
+
+ case ProcessType.ORCHESTRATOR:
+ if (!this.terminalManager || !this.memoryManager ||
+ !this.coordinationManager || !this.mcpServer) {
+ throw new Error('Required components not initialized');
+ }
+
+ this.orchestrator = new Orchestrator(
+ this.config,
+ this.terminalManager,
+ this.memoryManager,
+ this.coordinationManager,
+ this.mcpServer,
+ eventBus,
+ logger
+ );
+ await this.orchestrator.initialize();
+ break;
+ }
+
+ process.startTime = Date.now();
+ this.updateProcessStatus(processId, ProcessStatus.RUNNING);
+ this.emit('processStarted', { processId, process });
+
+ } catch (error) {
+ this.updateProcessStatus(processId, ProcessStatus.ERROR);
+ process.metrics = {
+ ...process.metrics,
+ lastError: error.message
+ };
+ this.emit('processError', { processId, error });
+ throw error;
+ }
+ }
+
+ async stopProcess(processId: string): Promise<void> {
+ const process = this.processes.get(processId);
+ if (!process || process.status !== ProcessStatus.RUNNING) {
+ throw new Error(`Process ${processId} is not running`);
+ }
+
+ this.updateProcessStatus(processId, ProcessStatus.STOPPING);
+
+ try {
+ switch (process.type) {
+ case ProcessType.ORCHESTRATOR:
+ if (this.orchestrator) {
+ await this.orchestrator.shutdown();
+ this.orchestrator = undefined;
+ }
+ break;
+
+ case ProcessType.MCP_SERVER:
+ if (this.mcpServer) {
+ await this.mcpServer.stop();
+ this.mcpServer = undefined;
+ }
+ break;
+
+ case ProcessType.MEMORY_MANAGER:
+ if (this.memoryManager) {
+ await this.memoryManager.shutdown();
+ this.memoryManager = undefined;
+ }
+ break;
+
+ case ProcessType.TERMINAL_POOL:
+ if (this.terminalManager) {
+ await this.terminalManager.shutdown();
+ this.terminalManager = undefined;
+ }
+ break;
+
+ case ProcessType.COORDINATOR:
+ if (this.coordinationManager) {
+ await this.coordinationManager.shutdown();
+ this.coordinationManager = undefined;
+ }
+ break;
+ }
+
+ this.updateProcessStatus(processId, ProcessStatus.STOPPED);
+ this.emit('processStopped', { processId });
+
+ } catch (error) {
+ this.updateProcessStatus(processId, ProcessStatus.ERROR);
+ this.emit('processError', { processId, error });
+ throw error;
+ }
+ }
+
+ async restartProcess(processId: string): Promise<void> {
+ await this.stopProcess(processId);
+ await new Promise(resolve => setTimeout(resolve, 1000)); // Brief delay
+ await this.startProcess(processId);
+ }
+
+ async startAll(): Promise<void> {
+ // Start in dependency order
+ const startOrder = [
+ 'event-bus',
+ 'memory-manager',
+ 'terminal-pool',
+ 'coordinator',
+ 'mcp-server',
+ 'orchestrator'
+ ];
+
+ for (const processId of startOrder) {
+ try {
+ await this.startProcess(processId);
+ } catch (error) {
+ console.error(colors.red(`Failed to start ${processId}:`), error.message);
+ // Continue with other processes
+ }
+ }
+ }
+
+ async stopAll(): Promise<void> {
+ // Stop in reverse dependency order
+ const stopOrder = [
+ 'orchestrator',
+ 'mcp-server',
+ 'coordinator',
+ 'terminal-pool',
+ 'memory-manager',
+ 'event-bus'
+ ];
+
+ for (const processId of stopOrder) {
+ const process = this.processes.get(processId);
+ if (process && process.status === ProcessStatus.RUNNING) {
+ try {
+ await this.stopProcess(processId);
+ } catch (error) {
+ console.error(colors.red(`Failed to stop ${processId}:`), error.message);
+ }
+ }
+ }
+ }
+
+ getProcess(processId: string): ProcessInfo | undefined {
+ return this.processes.get(processId);
+ }
+
+ getAllProcesses(): ProcessInfo[] {
+ return Array.from(this.processes.values());
+ }
+
+ getSystemStats(): SystemStats {
+ const processes = this.getAllProcesses();
+ const runningProcesses = processes.filter(p => p.status === ProcessStatus.RUNNING);
+ const stoppedProcesses = processes.filter(p => p.status === ProcessStatus.STOPPED);
+ const errorProcesses = processes.filter(p => p.status === ProcessStatus.ERROR);
+
+ return {
+ totalProcesses: processes.length,
+ runningProcesses: runningProcesses.length,
+ stoppedProcesses: stoppedProcesses.length,
+ errorProcesses: errorProcesses.length,
+ systemUptime: this.getSystemUptime(),
+ totalMemory: this.getTotalMemoryUsage(),
+ totalCpu: this.getTotalCpuUsage()
+ };
+ }
+
+ private updateProcessStatus(processId: string, status: ProcessStatus): void {
+ const process = this.processes.get(processId);
+ if (process) {
+ process.status = status;
+ this.emit('statusChanged', { processId, status });
+ }
+ }
+
+ private getSystemUptime(): number {
+ const orchestrator = this.processes.get('orchestrator');
+ if (orchestrator && orchestrator.startTime) {
+ return Date.now() - orchestrator.startTime;
+ }
+ return 0;
+ }
+
+ private getTotalMemoryUsage(): number {
+ // Placeholder - would integrate with actual memory monitoring
+ return 0;
+ }
+
+ private getTotalCpuUsage(): number {
+ // Placeholder - would integrate with actual CPU monitoring
+ return 0;
+ }
+
+ async getProcessLogs(processId: string, lines: number = 50): Promise<string[]> {
+ // Placeholder - would integrate with actual logging system
+ return [
+ `[${new Date().toISOString()}] Process ${processId} started`,
+ `[${new Date().toISOString()}] Process ${processId} is running normally`
+ ];
+ }
+}
\ No newline at end of file
diff --git a/src/cli/commands/start/process-ui.ts b/src/cli/commands/start/process-ui.ts
new file mode 100644
index 0000000000..14b97b1d35
--- /dev/null
+++ b/src/cli/commands/start/process-ui.ts
@@ -0,0 +1,525 @@
+/**
+ * Process UI - Text-based interface for process management
+ */
+
+import { colors } from '@cliffy/ansi/colors';
+import { keypress, KeyPressEvent } from '@cliffy/keypress';
+import { ProcessManager } from './process-manager.ts';
+import { ProcessInfo, ProcessStatus, SystemStats, UIAction } from './types.ts';
+
+export class ProcessUI {
+ private processManager: ProcessManager;
+ private selectedIndex = 0;
+ private running = false;
+ private viewMode: 'list' | 'details' | 'logs' = 'list';
+ private selectedProcess?: string;
+ private refreshInterval?: number;
+
+ constructor(processManager: ProcessManager) {
+ this.processManager = processManager;
+ this.setupEventListeners();
+ }
+
+ private setupEventListeners(): void {
+ this.processManager.on('statusChanged', ({ processId, status }) => {
+ if (this.running) {
+ this.render();
+ }
+ });
+
+ this.processManager.on('processError', ({ processId, error }) => {
+ if (this.running) {
+ this.showError(`Process ${processId} error: ${error.message}`);
+ }
+ });
+ }
+
+ async start(): Promise<void> {
+ this.running = true;
+
+ // Hide cursor
+ await Deno.stdout.write(new TextEncoder().encode('\x1b[?25l'));
+
+ // Clear screen
+ console.clear();
+
+ // Setup refresh interval
+ this.refreshInterval = setInterval(() => {
+ if (this.running && this.viewMode === 'list') {
+ this.render();
+ }
+ }, 1000);
+
+ // Initial render
+ this.render();
+
+ // Handle keyboard input
+ for await (const event of keypress()) {
+ if (!this.running) break;
+ await this.handleKeypress(event);
+ }
+ }
+
+ async stop(): Promise<void> {
+ this.running = false;
+
+ // Clear refresh interval
+ if (this.refreshInterval) {
+ clearInterval(this.refreshInterval);
+ }
+
+ // Show cursor
+ await Deno.stdout.write(new TextEncoder().encode('\x1b[?25h'));
+
+ // Clear screen
+ console.clear();
+ }
+
+ private async handleKeypress(event: KeyPressEvent): Promise<void> {
+ const { key, ctrlKey } = event;
+
+ // Global shortcuts
+ if (ctrlKey && key === 'c') {
+ await this.handleExit();
+ return;
+ }
+
+ if (ctrlKey && key === 'l') {
+ console.clear();
+ this.render();
+ return;
+ }
+
+ switch (this.viewMode) {
+ case 'list':
+ await this.handleListModeKeys(key);
+ break;
+ case 'details':
+ await this.handleDetailsModeKeys(key);
+ break;
+ case 'logs':
+ await this.handleLogsModeKeys(key);
+ break;
+ }
+ }
+
+ private async handleListModeKeys(key: string): Promise<void> {
+ const processes = this.processManager.getAllProcesses();
+
+ switch (key) {
+ case 'up':
+ case 'k':
+ this.selectedIndex = Math.max(0, this.selectedIndex - 1);
+ this.render();
+ break;
+
+ case 'down':
+ case 'j':
+ this.selectedIndex = Math.min(processes.length - 1, this.selectedIndex + 1);
+ this.render();
+ break;
+
+ case 'enter':
+ case 'space':
+ if (processes[this.selectedIndex]) {
+ const process = processes[this.selectedIndex];
+ if (process.status === ProcessStatus.STOPPED) {
+ await this.startProcess(process.id);
+ } else if (process.status === ProcessStatus.RUNNING) {
+ await this.showProcessMenu(process);
+ }
+ }
+ break;
+
+ case 's':
+ // Start selected process
+ if (processes[this.selectedIndex]) {
+ await this.startProcess(processes[this.selectedIndex].id);
+ }
+ break;
+
+ case 'x':
+ // Stop selected process
+ if (processes[this.selectedIndex]) {
+ await this.stopProcess(processes[this.selectedIndex].id);
+ }
+ break;
+
+ case 'r':
+ // Restart selected process
+ if (processes[this.selectedIndex]) {
+ await this.restartProcess(processes[this.selectedIndex].id);
+ }
+ break;
+
+ case 'd':
+ // Show details
+ if (processes[this.selectedIndex]) {
+ this.selectedProcess = processes[this.selectedIndex].id;
+ this.viewMode = 'details';
+ this.render();
+ }
+ break;
+
+ case 'l':
+ // Show logs
+ if (processes[this.selectedIndex]) {
+ this.selectedProcess = processes[this.selectedIndex].id;
+ this.viewMode = 'logs';
+ this.render();
+ }
+ break;
+
+ case 'a':
+ // Start all
+ await this.startAll();
+ break;
+
+ case 'z':
+ // Stop all
+ await this.stopAll();
+ break;
+
+ case 'q':
+ await this.handleExit();
+ break;
+
+ case 'h':
+ case '?':
+ this.showHelp();
+ break;
+ }
+ }
+
+ private async handleDetailsModeKeys(key: string): Promise<void> {
+ switch (key) {
+ case 'q':
+ case 'escape':
+ this.viewMode = 'list';
+ this.render();
+ break;
+
+ case 'l':
+ this.viewMode = 'logs';
+ this.render();
+ break;
+ }
+ }
+
+ private async handleLogsModeKeys(key: string): Promise<void> {
+ switch (key) {
+ case 'q':
+ case 'escape':
+ this.viewMode = 'list';
+ this.render();
+ break;
+
+ case 'd':
+ this.viewMode = 'details';
+ this.render();
+ break;
+ }
+ }
+
+ private render(): void {
+ console.clear();
+
+ switch (this.viewMode) {
+ case 'list':
+ this.renderListView();
+ break;
+ case 'details':
+ this.renderDetailsView();
+ break;
+ case 'logs':
+ this.renderLogsView();
+ break;
+ }
+ }
+
+ private renderListView(): void {
+ const processes = this.processManager.getAllProcesses();
+ const stats = this.processManager.getSystemStats();
+
+ // Header
+ console.log(colors.cyan.bold('🧠 Claude-Flow Process Manager'));
+ console.log(colors.gray('─'.repeat(60)));
+
+ // System stats
+ console.log(colors.white('System Status:'),
+ colors.green(`${stats.runningProcesses}/${stats.totalProcesses} running`));
+
+ if (stats.errorProcesses > 0) {
+ console.log(colors.red(`⚠️ ${stats.errorProcesses} processes with errors`));
+ }
+
+ console.log();
+
+ // Process list
+ console.log(colors.white.bold('Processes:'));
+ console.log(colors.gray('─'.repeat(60)));
+
+ processes.forEach((process, index) => {
+ const isSelected = index === this.selectedIndex;
+ const prefix = isSelected ? colors.cyan('β–Ά ') : ' ';
+ const status = this.getStatusDisplay(process.status);
+ const name = isSelected ? colors.cyan.bold(process.name) : colors.white(process.name);
+
+ console.log(`${prefix}${status} ${name}`);
+
+ if (isSelected && process.metrics?.lastError) {
+ console.log(colors.red(` Error: ${process.metrics.lastError}`));
+ }
+ });
+
+ // Footer
+ console.log(colors.gray('─'.repeat(60)));
+ console.log(colors.gray('Commands: [↑↓] Navigate [Enter] Toggle [a] Start All [z] Stop All'));
+ console.log(colors.gray('[s] Start [x] Stop [r] Restart [d] Details [l] Logs [q] Quit [h] Help'));
+ }
+
+ private renderDetailsView(): void {
+ if (!this.selectedProcess) return;
+
+ const process = this.processManager.getProcess(this.selectedProcess);
+ if (!process) return;
+
+ console.log(colors.cyan.bold(`πŸ“‹ Process Details: ${process.name}`));
+ console.log(colors.gray('─'.repeat(60)));
+
+ console.log(colors.white('ID:'), process.id);
+ console.log(colors.white('Type:'), process.type);
+ console.log(colors.white('Status:'), this.getStatusDisplay(process.status));
+
+ if (process.pid) {
+ console.log(colors.white('PID:'), process.pid);
+ }
+
+ if (process.startTime) {
+ const uptime = Date.now() - process.startTime;
+ console.log(colors.white('Uptime:'), this.formatUptime(uptime));
+ }
+
+ if (process.metrics) {
+ console.log();
+ console.log(colors.white.bold('Metrics:'));
+ if (process.metrics.cpu !== undefined) {
+ console.log(colors.white('CPU:'), `${process.metrics.cpu}%`);
+ }
+ if (process.metrics.memory !== undefined) {
+ console.log(colors.white('Memory:'), `${process.metrics.memory} MB`);
+ }
+ if (process.metrics.restarts !== undefined) {
+ console.log(colors.white('Restarts:'), process.metrics.restarts);
+ }
+ }
+
+ if (process.config) {
+ console.log();
+ console.log(colors.white.bold('Configuration:'));
+ console.log(JSON.stringify(process.config, null, 2));
+ }
+
+ console.log();
+ console.log(colors.gray('─'.repeat(60)));
+ console.log(colors.gray('[q] Back to list [l] View logs'));
+ }
+
+ private async renderLogsView(): Promise<void> {
+ if (!this.selectedProcess) return;
+
+ const process = this.processManager.getProcess(this.selectedProcess);
+ if (!process) return;
+
+ console.log(colors.cyan.bold(`πŸ“œ Process Logs: ${process.name}`));
+ console.log(colors.gray('─'.repeat(60)));
+
+ try {
+ const logs = await this.processManager.getProcessLogs(this.selectedProcess, 30);
+ logs.forEach(log => console.log(colors.gray(log)));
+ } catch (error) {
+ console.log(colors.red(`Error fetching logs: ${error.message}`));
+ }
+
+ console.log();
+ console.log(colors.gray('─'.repeat(60)));
+ console.log(colors.gray('[q] Back to list [d] View details'));
+ }
+
+ private getStatusDisplay(status: ProcessStatus): string {
+ switch (status) {
+ case ProcessStatus.RUNNING:
+ return colors.green('●');
+ case ProcessStatus.STOPPED:
+ return colors.gray('β—‹');
+ case ProcessStatus.STARTING:
+ return colors.yellow('◐');
+ case ProcessStatus.STOPPING:
+ return colors.yellow('β—‘');
+ case ProcessStatus.ERROR:
+ return colors.red('βœ—');
+ case ProcessStatus.CRASHED:
+ return colors.red('☠');
+ default:
+ return colors.gray('?');
+ }
+ }
+
+ private formatUptime(ms: number): string {
+ const seconds = Math.floor(ms / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+ const days = Math.floor(hours / 24);
+
+ if (days > 0) {
+ return `${days}d ${hours % 24}h`;
+ } else if (hours > 0) {
+ return `${hours}h ${minutes % 60}m`;
+ } else if (minutes > 0) {
+ return `${minutes}m ${seconds % 60}s`;
+ } else {
+ return `${seconds}s`;
+ }
+ }
+
+ private async showProcessMenu(process: ProcessInfo): Promise<void> {
+ console.clear();
+ console.log(colors.cyan.bold(`Process: ${process.name}`));
+ console.log(colors.gray('─'.repeat(40)));
+ console.log('[s] Stop');
+ console.log('[r] Restart');
+ console.log('[d] Details');
+ console.log('[l] Logs');
+ console.log('[q] Cancel');
+
+ // Wait for single keypress
+ const event = await keypress().next();
+ if (event.value) {
+ switch (event.value.key) {
+ case 's':
+ await this.stopProcess(process.id);
+ break;
+ case 'r':
+ await this.restartProcess(process.id);
+ break;
+ case 'd':
+ this.selectedProcess = process.id;
+ this.viewMode = 'details';
+ break;
+ case 'l':
+ this.selectedProcess = process.id;
+ this.viewMode = 'logs';
+ break;
+ }
+ }
+
+ this.render();
+ }
+
+ private showHelp(): void {
+ console.clear();
+ console.log(colors.cyan.bold('🧠 Claude-Flow Process Manager - Help'));
+ console.log(colors.gray('─'.repeat(60)));
+ console.log();
+ console.log(colors.white.bold('Navigation:'));
+ console.log(' ↑/k - Move up');
+ console.log(' ↓/j - Move down');
+ console.log(' Enter - Toggle process (start/stop)');
+ console.log();
+ console.log(colors.white.bold('Process Control:'));
+ console.log(' s - Start selected process');
+ console.log(' x - Stop selected process');
+ console.log(' r - Restart selected process');
+ console.log(' a - Start all processes');
+ console.log(' z - Stop all processes');
+ console.log();
+ console.log(colors.white.bold('Views:'));
+ console.log(' d - Show process details');
+ console.log(' l - Show process logs');
+ console.log(' q/Esc - Return to list view');
+ console.log();
+ console.log(colors.white.bold('Other:'));
+ console.log(' h/? - Show this help');
+ console.log(' Ctrl+L - Clear screen');
+ console.log(' Ctrl+C - Exit');
+ console.log();
+ console.log(colors.gray('Press any key to continue...'));
+
+ // Wait for keypress
+ keypress().next();
+ this.render();
+ }
+
+ private showError(message: string): void {
+ const savedView = this.viewMode;
+ console.clear();
+ console.log(colors.red.bold('❌ Error'));
+ console.log(colors.red(message));
+ console.log();
+ console.log(colors.gray('Press any key to continue...'));
+
+ // Restore view after keypress
+ keypress().next().then(() => {
+ this.viewMode = savedView;
+ this.render();
+ });
+ }
+
+ private async startProcess(processId: string): Promise<void> {
+ try {
+ await this.processManager.startProcess(processId);
+ } catch (error) {
+ this.showError(error.message);
+ }
+ }
+
+ private async stopProcess(processId: string): Promise<void> {
+ try {
+ await this.processManager.stopProcess(processId);
+ } catch (error) {
+ this.showError(error.message);
+ }
+ }
+
+ private async restartProcess(processId: string): Promise<void> {
+ try {
+ await this.processManager.restartProcess(processId);
+ } catch (error) {
+ this.showError(error.message);
+ }
+ }
+
+ private async startAll(): Promise<void> {
+ try {
+ await this.processManager.startAll();
+ } catch (error) {
+ this.showError(error.message);
+ }
+ }
+
+ private async stopAll(): Promise<void> {
+ try {
+ await this.processManager.stopAll();
+ } catch (error) {
+ this.showError(error.message);
+ }
+ }
+
+ private async handleExit(): Promise<void> {
+ const processes = this.processManager.getAllProcesses();
+ const hasRunning = processes.some(p => p.status === ProcessStatus.RUNNING);
+
+ if (hasRunning) {
+ console.clear();
+ console.log(colors.yellow('⚠️ Some processes are still running.'));
+ console.log('Stop all processes before exiting? [y/N]');
+
+ const event = await keypress().next();
+ if (event.value && event.value.key.toLowerCase() === 'y') {
+ await this.stopAll();
+ }
+ }
+
+ await this.stop();
+ }
+}
\ No newline at end of file
diff --git a/src/cli/commands/start/start-command.ts b/src/cli/commands/start/start-command.ts
new file mode 100644
index 0000000000..f023f4bb99
--- /dev/null
+++ b/src/cli/commands/start/start-command.ts
@@ -0,0 +1,192 @@
+/**
+ * Unified start command implementation
+ */
+
+import { Command } from '@cliffy/command';
+import { colors } from '@cliffy/ansi/colors';
+import { ProcessManager } from './process-manager.ts';
+import { ProcessUI } from './process-ui.ts';
+import { SystemMonitor } from './system-monitor.ts';
+import { StartOptions } from './types.ts';
+import { eventBus } from '../../../core/event-bus.ts';
+import { logger } from '../../../core/logger.ts';
+
+export const startCommand = new Command()
+ .description('Start the Claude-Flow orchestration system')
+ .option('-d, --daemon', 'Run as daemon in background')
+ .option('-p, --port <port:number>', 'MCP server port', { default: 3000 })
+ .option('--mcp-transport <transport:string>', 'MCP transport type (stdio, http)', {
+ default: 'stdio',
+ })
+ .option('-u, --ui', 'Launch interactive process management UI')
+ .option('-v, --verbose', 'Enable verbose logging')
+ .option('--auto-start', 'Automatically start all processes')
+ .option('--config <path:string>', 'Configuration file path')
+ .action(async (options: StartOptions) => {
+ console.log(colors.cyan('🧠 Claude-Flow Orchestration System'));
+ console.log(colors.gray('─'.repeat(60)));
+
+ try {
+ // Initialize process manager
+ const processManager = new ProcessManager();
+ await processManager.initialize(options.config);
+
+ // Initialize system monitor
+ const systemMonitor = new SystemMonitor(processManager);
+ systemMonitor.start();
+
+ // Override MCP settings from CLI options
+ if (options.port) {
+ const mcpProcess = processManager.getProcess('mcp-server');
+ if (mcpProcess) {
+ mcpProcess.config = { ...mcpProcess.config, port: options.port };
+ }
+ }
+
+ // Setup event listeners for logging
+ if (options.verbose) {
+ setupVerboseLogging(systemMonitor);
+ }
+
+ // Launch UI mode
+ if (options.ui) {
+ const ui = new ProcessUI(processManager);
+ await ui.start();
+
+ // Cleanup on exit
+ systemMonitor.stop();
+ await processManager.stopAll();
+ console.log(colors.green.bold('βœ“'), 'Shutdown complete');
+ Deno.exit(0);
+ }
+ // Daemon mode
+ else if (options.daemon) {
+ console.log(colors.yellow('Starting in daemon mode...'));
+
+ // Auto-start all processes
+ if (options.autoStart) {
+ await processManager.startAll();
+ } else {
+ // Start only core processes
+ await processManager.startProcess('event-bus');
+ await processManager.startProcess('memory-manager');
+ await processManager.startProcess('mcp-server');
+ }
+
+ // Create PID file
+ const pid = Deno.pid;
+ await Deno.writeTextFile('.claude-flow.pid', pid.toString());
+ console.log(colors.gray(`Process ID: ${pid}`));
+
+ console.log(colors.green.bold('βœ“'), 'Daemon started successfully');
+ console.log(colors.gray('Use "claude-flow status" to check system status'));
+
+ // Keep process running
+ await new Promise<void>(() => {});
+ }
+ // Interactive mode (default)
+ else {
+ console.log(colors.cyan('Starting in interactive mode...'));
+ console.log();
+
+ // Show available options
+ console.log(colors.white.bold('Quick Actions:'));
+ console.log(' [1] Start all processes');
+ console.log(' [2] Start core processes only');
+ console.log(' [3] Launch process management UI');
+ console.log(' [4] Show system status');
+ console.log(' [q] Quit');
+ console.log();
+ console.log(colors.gray('Press a key to select an option...'));
+
+ // Handle user input
+ const decoder = new TextDecoder();
+ while (true) {
+ const buf = new Uint8Array(1);
+ await Deno.stdin.read(buf);
+ const key = decoder.decode(buf);
+
+ switch (key) {
+ case '1':
+ console.log(colors.cyan('\nStarting all processes...'));
+ await processManager.startAll();
+ console.log(colors.green.bold('βœ“'), 'All processes started');
+ break;
+
+ case '2':
+ console.log(colors.cyan('\nStarting core processes...'));
+ await processManager.startProcess('event-bus');
+ await processManager.startProcess('memory-manager');
+ await processManager.startProcess('mcp-server');
+ console.log(colors.green.bold('βœ“'), 'Core processes started');
+ break;
+
+ case '3':
+ const ui = new ProcessUI(processManager);
+ await ui.start();
+ break;
+
+ case '4':
+ console.clear();
+ systemMonitor.printSystemHealth();
+ console.log();
+ systemMonitor.printEventLog(10);
+ console.log();
+ console.log(colors.gray('Press any key to continue...'));
+ await Deno.stdin.read(new Uint8Array(1));
+ break;
+
+ case 'q':
+ case 'Q':
+ console.log(colors.yellow('\nShutting down...'));
+ await processManager.stopAll();
+ systemMonitor.stop();
+ console.log(colors.green.bold('βœ“'), 'Shutdown complete');
+ Deno.exit(0);
+ break;
+ }
+
+ // Redraw menu
+ console.clear();
+ console.log(colors.cyan('🧠 Claude-Flow Interactive Mode'));
+ console.log(colors.gray('─'.repeat(60)));
+
+ // Show current status
+ const stats = processManager.getSystemStats();
+ console.log(colors.white('System Status:'),
+ colors.green(`${stats.runningProcesses}/${stats.totalProcesses} processes running`));
+ console.log();
+
+ console.log(colors.white.bold('Quick Actions:'));
+ console.log(' [1] Start all processes');
+ console.log(' [2] Start core processes only');
+ console.log(' [3] Launch process management UI');
+ console.log(' [4] Show system status');
+ console.log(' [q] Quit');
+ console.log();
+ console.log(colors.gray('Press a key to select an option...'));
+ }
+ }
+ } catch (error) {
+ console.error(colors.red.bold('Failed to start:'), error.message);
+ if (options.verbose) {
+ console.error(error.stack);
+ }
+ Deno.exit(1);
+ }
+ });
+
+function setupVerboseLogging(monitor: SystemMonitor): void {
+ // Log all events in verbose mode
+ eventBus.on('*', (eventName: string, data: any) => {
+ console.log(colors.gray(`[${new Date().toISOString()}]`),
+ colors.blue(eventName),
+ JSON.stringify(data));
+ });
+
+ // Periodically print system health
+ setInterval(() => {
+ console.log();
+ monitor.printSystemHealth();
+ }, 30000);
+}
\ No newline at end of file
diff --git a/src/cli/commands/start/system-monitor.ts b/src/cli/commands/start/system-monitor.ts
new file mode 100644
index 0000000000..4d213b93e4
--- /dev/null
+++ b/src/cli/commands/start/system-monitor.ts
@@ -0,0 +1,309 @@
+/**
+ * System Monitor - Real-time monitoring of system processes
+ */
+
+import { colors } from '@cliffy/ansi/colors';
+import { ProcessManager } from './process-manager.ts';
+import { SystemEvents } from '../../../utils/types.ts';
+import { eventBus } from '../../../core/event-bus.ts';
+
+export class SystemMonitor {
+ private processManager: ProcessManager;
+ private events: any[] = [];
+ private maxEvents = 100;
+ private metricsInterval?: number;
+
+ constructor(processManager: ProcessManager) {
+ this.processManager = processManager;
+ this.setupEventListeners();
+ }
+
+ private setupEventListeners(): void {
+ // System events
+ eventBus.on(SystemEvents.AGENT_SPAWNED, (data: any) => {
+ this.addEvent({
+ type: 'agent_spawned',
+ timestamp: Date.now(),
+ data,
+ level: 'info'
+ });
+ });
+
+ eventBus.on(SystemEvents.AGENT_TERMINATED, (data: any) => {
+ this.addEvent({
+ type: 'agent_terminated',
+ timestamp: Date.now(),
+ data,
+ level: 'warning'
+ });
+ });
+
+ eventBus.on(SystemEvents.TASK_ASSIGNED, (data: any) => {
+ this.addEvent({
+ type: 'task_assigned',
+ timestamp: Date.now(),
+ data,
+ level: 'info'
+ });
+ });
+
+ eventBus.on(SystemEvents.TASK_COMPLETED, (data: any) => {
+ this.addEvent({
+ type: 'task_completed',
+ timestamp: Date.now(),
+ data,
+ level: 'success'
+ });
+ });
+
+ eventBus.on(SystemEvents.TASK_FAILED, (data: any) => {
+ this.addEvent({
+ type: 'task_failed',
+ timestamp: Date.now(),
+ data,
+ level: 'error'
+ });
+ });
+
+ eventBus.on(SystemEvents.SYSTEM_ERROR, (data: any) => {
+ this.addEvent({
+ type: 'system_error',
+ timestamp: Date.now(),
+ data,
+ level: 'error'
+ });
+ });
+
+ // Process manager events
+ this.processManager.on('processStarted', ({ processId, process }) => {
+ this.addEvent({
+ type: 'process_started',
+ timestamp: Date.now(),
+ data: { processId, processName: process.name },
+ level: 'success'
+ });
+ });
+
+ this.processManager.on('processStopped', ({ processId }) => {
+ this.addEvent({
+ type: 'process_stopped',
+ timestamp: Date.now(),
+ data: { processId },
+ level: 'warning'
+ });
+ });
+
+ this.processManager.on('processError', ({ processId, error }) => {
+ this.addEvent({
+ type: 'process_error',
+ timestamp: Date.now(),
+ data: { processId, error: error.message },
+ level: 'error'
+ });
+ });
+ }
+
+ private addEvent(event: any): void {
+ this.events.unshift(event);
+ if (this.events.length > this.maxEvents) {
+ this.events.pop();
+ }
+ }
+
+ start(): void {
+ // Start collecting metrics
+ this.metricsInterval = setInterval(() => {
+ this.collectMetrics();
+ }, 5000);
+ }
+
+ stop(): void {
+ if (this.metricsInterval) {
+ clearInterval(this.metricsInterval);
+ }
+ }
+
+ private collectMetrics(): void {
+ // Collect system metrics
+ const processes = this.processManager.getAllProcesses();
+
+ for (const process of processes) {
+ if (process.status === 'running') {
+ // Simulate metrics collection (would integrate with actual monitoring)
+ process.metrics = {
+ ...process.metrics,
+ cpu: Math.random() * 50,
+ memory: Math.random() * 200,
+ uptime: process.startTime ? Date.now() - process.startTime : 0
+ };
+ }
+ }
+ }
+
+ getRecentEvents(count: number = 10): any[] {
+ return this.events.slice(0, count);
+ }
+
+ printEventLog(count: number = 20): void {
+ console.log(colors.cyan.bold('πŸ“Š Recent System Events'));
+ console.log(colors.gray('─'.repeat(80)));
+
+ const events = this.getRecentEvents(count);
+
+ for (const event of events) {
+ const timestamp = new Date(event.timestamp).toLocaleTimeString();
+ const icon = this.getEventIcon(event.type);
+ const color = this.getEventColor(event.level);
+
+ console.log(
+ colors.gray(timestamp),
+ icon,
+ color(this.formatEventMessage(event))
+ );
+ }
+ }
+
+ private getEventIcon(type: string): string {
+ const icons: Record<string, string> = {
+ agent_spawned: 'πŸ€–',
+ agent_terminated: 'πŸ”š',
+ task_assigned: 'πŸ“Œ',
+ task_completed: 'βœ…',
+ task_failed: '❌',
+ system_error: '⚠️',
+ process_started: '▢️',
+ process_stopped: '⏹️',
+ process_error: '🚨'
+ };
+
+ return icons[type] || 'β€’';
+ }
+
+ private getEventColor(level: string): (text: string) => string {
+ switch (level) {
+ case 'success':
+ return colors.green;
+ case 'info':
+ return colors.blue;
+ case 'warning':
+ return colors.yellow;
+ case 'error':
+ return colors.red;
+ default:
+ return colors.white;
+ }
+ }
+
+ private formatEventMessage(event: any): string {
+ switch (event.type) {
+ case 'agent_spawned':
+ return `Agent spawned: ${event.data.agentId} (${event.data.profile?.type || 'unknown'})`;
+ case 'agent_terminated':
+ return `Agent terminated: ${event.data.agentId} - ${event.data.reason}`;
+ case 'task_assigned':
+ return `Task ${event.data.taskId} assigned to ${event.data.agentId}`;
+ case 'task_completed':
+ return `Task completed: ${event.data.taskId}`;
+ case 'task_failed':
+ return `Task failed: ${event.data.taskId} - ${event.data.error?.message}`;
+ case 'system_error':
+ return `System error in ${event.data.component}: ${event.data.error?.message}`;
+ case 'process_started':
+ return `Process started: ${event.data.processName}`;
+ case 'process_stopped':
+ return `Process stopped: ${event.data.processId}`;
+ case 'process_error':
+ return `Process error: ${event.data.processId} - ${event.data.error}`;
+ default:
+ return JSON.stringify(event.data);
+ }
+ }
+
+ printSystemHealth(): void {
+ const stats = this.processManager.getSystemStats();
+ const processes = this.processManager.getAllProcesses();
+
+ console.log(colors.cyan.bold('πŸ₯ System Health'));
+ console.log(colors.gray('─'.repeat(60)));
+
+ // Overall status
+ const healthStatus = stats.errorProcesses === 0 ?
+ colors.green('● Healthy') :
+ colors.red(`● Unhealthy (${stats.errorProcesses} errors)`);
+
+ console.log('Status:', healthStatus);
+ console.log('Uptime:', this.formatUptime(stats.systemUptime));
+ console.log();
+
+ // Process status
+ console.log(colors.white.bold('Process Status:'));
+ for (const process of processes) {
+ const status = this.getProcessStatusIcon(process.status);
+ const metrics = process.metrics;
+
+ let line = ` ${status} ${process.name.padEnd(20)}`;
+
+ if (metrics && process.status === 'running') {
+ line += colors.gray(` CPU: ${metrics.cpu?.toFixed(1)}% `);
+ line += colors.gray(` MEM: ${metrics.memory?.toFixed(0)}MB`);
+ }
+
+ console.log(line);
+ }
+
+ console.log();
+
+ // System metrics
+ console.log(colors.white.bold('System Metrics:'));
+ console.log(` Active Processes: ${stats.runningProcesses}/${stats.totalProcesses}`);
+ console.log(` Recent Events: ${this.events.length}`);
+
+ // Recent errors
+ const recentErrors = this.events
+ .filter(e => e.level === 'error')
+ .slice(0, 3);
+
+ if (recentErrors.length > 0) {
+ console.log();
+ console.log(colors.red.bold('Recent Errors:'));
+ for (const error of recentErrors) {
+ const time = new Date(error.timestamp).toLocaleTimeString();
+ console.log(colors.red(` ${time} - ${this.formatEventMessage(error)}`));
+ }
+ }
+ }
+
+ private getProcessStatusIcon(status: string): string {
+ switch (status) {
+ case 'running':
+ return colors.green('●');
+ case 'stopped':
+ return colors.gray('β—‹');
+ case 'starting':
+ return colors.yellow('◐');
+ case 'stopping':
+ return colors.yellow('β—‘');
+ case 'error':
+ return colors.red('βœ—');
+ default:
+ return colors.gray('?');
+ }
+ }
+
+ private formatUptime(ms: number): string {
+ const seconds = Math.floor(ms / 1000);
+ const minutes = Math.floor(seconds / 60);
+ const hours = Math.floor(minutes / 60);
+ const days = Math.floor(hours / 24);
+
+ if (days > 0) {
+ return `${days}d ${hours % 24}h ${minutes % 60}m`;
+ } else if (hours > 0) {
+ return `${hours}h ${minutes % 60}m ${seconds % 60}s`;
+ } else if (minutes > 0) {
+ return `${minutes}m ${seconds % 60}s`;
+ } else {
+ return `${seconds}s`;
+ }
+ }
+}
\ No newline at end of file
diff --git a/src/cli/commands/start/types.ts b/src/cli/commands/start/types.ts
new file mode 100644
index 0000000000..f96f867210
--- /dev/null
+++ b/src/cli/commands/start/types.ts
@@ -0,0 +1,65 @@
+/**
+ * Type definitions for the start command module
+ */
+
+export interface ProcessInfo {
+ id: string;
+ name: string;
+ type: ProcessType;
+ status: ProcessStatus;
+ pid?: number;
+ startTime?: number;
+ config?: Record<string, any>;
+ metrics?: ProcessMetrics;
+}
+
+export enum ProcessType {
+ ORCHESTRATOR = 'orchestrator',
+ MCP_SERVER = 'mcp-server',
+ MEMORY_MANAGER = 'memory-manager',
+ TERMINAL_POOL = 'terminal-pool',
+ COORDINATOR = 'coordinator',
+ EVENT_BUS = 'event-bus'
+}
+
+export enum ProcessStatus {
+ STOPPED = 'stopped',
+ STARTING = 'starting',
+ RUNNING = 'running',
+ STOPPING = 'stopping',
+ ERROR = 'error',
+ CRASHED = 'crashed'
+}
+
+export interface ProcessMetrics {
+ cpu?: number;
+ memory?: number;
+ uptime?: number;
+ restarts?: number;
+ lastError?: string;
+}
+
+export interface SystemStats {
+ totalProcesses: number;
+ runningProcesses: number;
+ stoppedProcesses: number;
+ errorProcesses: number;
+ systemUptime: number;
+ totalMemory: number;
+ totalCpu: number;
+}
+
+export interface StartOptions {
+ daemon?: boolean;
+ port?: number;
+ mcpTransport?: string;
+ config?: string;
+ verbose?: boolean;
+ ui?: boolean;
+}
+
+export interface UIAction {
+ type: 'start' | 'stop' | 'restart' | 'logs' | 'status' | 'exit';
+ processId?: string;
+ options?: Record<string, any>;
+}
\ No newline at end of file
diff --git a/src/cli/index-remote.ts b/src/cli/index-remote.ts
index 57eee46bc2..55facfaa93 100644
--- a/src/cli/index-remote.ts
+++ b/src/cli/index-remote.ts
@@ -4,7 +4,7 @@
* This version can be run directly from GitHub
*/
-const VERSION = '1.0.41';
+const VERSION = '1.0.42';
// Simple color functions
const colors = {
diff --git a/src/cli/index.ts b/src/cli/index.ts
index 888426e3e2..0a972716e1 100644
--- a/src/cli/index.ts
+++ b/src/cli/index.ts
@@ -25,7 +25,7 @@ import { startREPL } from './repl.ts';
import { CompletionGenerator } from './completion.ts';
// Version information
-const VERSION = '1.0.41';
+const VERSION = '1.0.42';
const BUILD_DATE = new Date().toISOString().split('T')[0];
// Main CLI command
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 240f2735d5..a5ac9caf15 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -6,7 +6,7 @@
import { CLI } from "./cli-core.ts";
import { setupCommands } from "./commands/index.ts";
-const VERSION = "1.0.41";
+const VERSION = "1.0.42";
async function main() {
const cli = new CLI("claude-flow", "Advanced AI Agent Orchestration System");
diff --git a/src/cli/simple-cli.js b/src/cli/simple-cli.js
index 39559d6fdd..6467499757 100644
--- a/src/cli/simple-cli.js
+++ b/src/cli/simple-cli.js
@@ -13,7 +13,7 @@ import {
} from './command-registry.js';
import { parseFlags } from './utils.js';
-const VERSION = '1.0.41';
+const VERSION = '1.0.42';
function printHelp() {
console.log(`
diff --git a/src/cli/simple-cli.ts b/src/cli/simple-cli.ts
index 87190aac29..4b590071fe 100644
--- a/src/cli/simple-cli.ts
+++ b/src/cli/simple-cli.ts
@@ -4,7 +4,7 @@
* This version avoids import assertion issues while maintaining functionality
*/
-const VERSION = '1.0.41';
+const VERSION = '1.0.42';
function printHelp() {
console.log(`
diff --git a/src/cli/simple-commands/config.js b/src/cli/simple-commands/config.js
index 1ee9bdbb2c..bf5ed3478f 100644
--- a/src/cli/simple-commands/config.js
+++ b/src/cli/simple-commands/config.js
@@ -51,7 +51,7 @@ async function initConfig(subArgs, flags) {
// Create default configuration
const defaultConfig = {
- version: "1.0.41",
+ version: "1.0.42",
terminal: {
poolSize: 10,
recycleAfter: 20,
diff --git a/src/cli/simple-commands/sparc.js b/src/cli/simple-commands/sparc.js
index ccd85d37d2..cea655aa87 100644
--- a/src/cli/simple-commands/sparc.js
+++ b/src/cli/simple-commands/sparc.js
@@ -213,7 +213,16 @@ async function runSparcMode(subArgs, flags) {
printWarning('DRY RUN - SPARC Mode Configuration:');
console.log(`Mode: ${mode.name} (${mode.slug})`);
console.log(`Instance ID: ${instanceId}`);
- console.log(`Tools: ${toolsList}`);
+
+ const enablePermissions = subArgs.includes('--enable-permissions');
+ if (!enablePermissions) {
+ console.log(`Tools: ALL (via --dangerously-skip-permissions)`);
+ console.log(`Permissions: Will be auto-skipped`);
+ } else {
+ console.log(`Tools: ${toolsList}`);
+ console.log(`Permissions: Will prompt for actions`);
+ }
+
console.log(`Task: ${taskDescription}`);
console.log();
console.log('Enhanced prompt preview:');
@@ -224,17 +233,18 @@ async function runSparcMode(subArgs, flags) {
printSuccess(`Starting SPARC mode: ${mode.name}`);
console.log(`πŸ“ Instance ID: ${instanceId}`);
console.log(`🎯 Mode: ${mode.slug}`);
- console.log(`πŸ”§ Tools: ${toolsList}`);
- console.log(`πŸ“‹ Task: ${taskDescription}`);
const isNonInteractive = subArgs.includes('--non-interactive') || subArgs.includes('-n');
const enablePermissions = subArgs.includes('--enable-permissions');
if (!enablePermissions) {
+ console.log(`πŸ”§ Tools: ALL (including MCP and WebSearch via --dangerously-skip-permissions)`);
console.log(`⚑ Permissions: Auto-skipped (--dangerously-skip-permissions)`);
} else {
+ console.log(`πŸ”§ Tools: ${toolsList}`);
console.log(`βœ… Permissions: Enabled (will prompt for actions)`);
}
+ console.log(`πŸ“‹ Task: ${taskDescription}`)
if (isNonInteractive) {
console.log(`πŸš€ Running in non-interactive mode with stream-json output`);
@@ -343,8 +353,12 @@ async function executeClaude(enhancedTask, toolsList, instanceId, memoryNamespac
}
}
- // Add tools after other flags
- claudeArgs.push('--allowedTools', toolsList);
+ // When using --dangerously-skip-permissions, we don't need to specify individual tools
+ // as it enables ALL tools including mcp and websearch
+ // Only add --allowedTools if permissions are enabled
+ if (enablePermissions) {
+ claudeArgs.push('--allowedTools', toolsList);
+ }
if (subArgs.includes('--config')) {
const configIndex = subArgs.indexOf('--config');
@@ -356,6 +370,7 @@ async function executeClaude(enhancedTask, toolsList, instanceId, memoryNamespac
console.log('\nπŸ” Debug: Executing claude with:');
console.log('Command: claude');
console.log('Permissions:', enablePermissions ? 'βœ… Enabled (will prompt)' : '⚑ Skipped (--dangerously-skip-permissions)');
+ console.log('Tools:', enablePermissions ? `Specified: ${toolsList}` : 'ALL tools enabled (MCP, WebSearch, etc.)');
console.log('Mode:', isNonInteractive ? 'πŸ€– Non-interactive' : 'πŸ’¬ Interactive');
console.log('Args array length:', claudeArgs.length);
console.log('First arg (prompt) length:', claudeArgs[0].length, 'characters');
diff --git a/src/cli/simple-commands/start-wrapper.js b/src/cli/simple-commands/start-wrapper.js
new file mode 100644
index 0000000000..811b2052ea
--- /dev/null
+++ b/src/cli/simple-commands/start-wrapper.js
@@ -0,0 +1,213 @@
+// start-wrapper.js - Wrapper to maintain backward compatibility with the new modular start command
+import { printSuccess, printError, printWarning, printInfo } from '../utils.js';
+
+export async function startCommand(subArgs, flags) {
+ // Show help if requested
+ if (flags.help || flags.h || subArgs.includes('--help') || subArgs.includes('-h')) {
+ showStartHelp();
+ return;
+ }
+
+ // Parse start options
+ const daemon = subArgs.includes('--daemon') || subArgs.includes('-d') || flags.daemon;
+ const port = flags.port || getArgValue(subArgs, '--port') || getArgValue(subArgs, '-p') || 3000;
+ const verbose = subArgs.includes('--verbose') || subArgs.includes('-v') || flags.verbose;
+ const ui = subArgs.includes('--ui') || subArgs.includes('-u') || flags.ui;
+
+ try {
+ printSuccess('Starting Claude-Flow Orchestration System...');
+ console.log();
+
+ // Check if we should launch the new UI mode
+ if (ui) {
+ printInfo('Launching interactive process management UI...');
+ console.log('Note: This would launch the new text-based UI for process management');
+ console.log();
+ console.log('Available features in UI mode:');
+ console.log(' β€’ Start/stop individual processes');
+ console.log(' β€’ View real-time process status');
+ console.log(' β€’ Monitor system health');
+ console.log(' β€’ View process logs');
+ console.log(' β€’ Restart failed processes');
+ console.log();
+ console.log('The full UI requires the TypeScript implementation.');
+ console.log('Use "claude-flow start --ui" with the main CLI.');
+ return;
+ }
+
+ // Check if required directories exist
+ const requiredDirs = ['memory', 'coordination'];
+ let missingDirs = [];
+
+ for (const dir of requiredDirs) {
+ try {
+ await Deno.stat(dir);
+ } catch {
+ missingDirs.push(dir);
+ }
+ }
+
+ if (missingDirs.length > 0) {
+ printWarning('Missing required directories: ' + missingDirs.join(', '));
+ console.log('Run "claude-flow init" first to create the necessary structure');
+ return;
+ }
+
+ // Display startup information
+ console.log('πŸš€ System Configuration:');
+ console.log(` Mode: ${daemon ? 'Daemon (background)' : 'Interactive'}`);
+ console.log(` MCP Port: ${port}`);
+ console.log(` Working Directory: ${Deno.cwd()}`);
+ console.log(` Memory Backend: JSON (default)`);
+ console.log(` Terminal Pool: 5 instances (default)`);
+ console.log();
+
+ // Initialize components
+ console.log('πŸ“‹ Initializing Components:');
+
+ // Memory system
+ console.log(' βœ“ Memory Bank: Ready');
+ console.log(' - Backend: JSON file (memory/claude-flow-data.json)');
+ console.log(' - Namespaces: Enabled');
+
+ // Terminal pool
+ console.log(' βœ“ Terminal Pool: Ready');
+ console.log(' - Pool Size: 5');
+ console.log(' - Shell: ' + (Deno.build.os === 'windows' ? 'cmd.exe' : '/bin/bash'));
+
+ // Task queue
+ console.log(' βœ“ Task Queue: Ready');
+ console.log(' - Max Concurrent: 10');
+ console.log(' - Priority Queue: Enabled');
+
+ // MCP Server
+ console.log(' βœ“ MCP Server: Ready');
+ console.log(` - Port: ${port}`);
+ console.log(' - Transport: stdio/HTTP');
+
+ console.log();
+
+ if (daemon) {
+ // Daemon mode - would normally fork process
+ printInfo('Starting in daemon mode...');
+ console.log('Note: Full daemon mode requires the TypeScript version');
+ console.log('The orchestrator would run in the background on port ' + port);
+
+ // Create a simple PID file to simulate daemon
+ const pid = Deno.pid;
+ await Deno.writeTextFile('.claude-flow.pid', pid.toString());
+ console.log(`Process ID: ${pid} (saved to .claude-flow.pid)`);
+
+ } else {
+ // Interactive mode
+ printSuccess('Orchestration system started!');
+ console.log();
+ console.log('🎯 Available Actions:');
+ console.log(' β€’ Open another terminal and run:');
+ console.log(' - claude-flow agent spawn researcher');
+ console.log(' - claude-flow task create "your task"');
+ console.log(' - claude-flow sparc "build feature"');
+ console.log(' - claude-flow monitor');
+ console.log();
+ console.log(' β€’ View system status:');
+ console.log(' - claude-flow status');
+ console.log();
+ console.log(' β€’ Launch process management UI:');
+ console.log(' - claude-flow start --ui');
+ console.log();
+ console.log(' β€’ Press Ctrl+C to stop the orchestrator');
+ console.log();
+
+ if (verbose) {
+ console.log('πŸ“Š Verbose Mode - Showing system activity:');
+ console.log('[' + new Date().toISOString() + '] System initialized');
+ console.log('[' + new Date().toISOString() + '] Waiting for commands...');
+ }
+
+ // Keep the process running
+ console.log('🟒 System is running...');
+
+ // Set up signal handlers
+ const abortController = new AbortController();
+
+ Deno.addSignalListener("SIGINT", () => {
+ console.log('\n⏹️ Shutting down orchestrator...');
+ cleanup();
+ Deno.exit(0);
+ });
+
+ // Simple heartbeat to show system is alive
+ if (!daemon) {
+ const heartbeat = setInterval(() => {
+ if (verbose) {
+ console.log('[' + new Date().toISOString() + '] Heartbeat - System healthy');
+ }
+ }, 30000); // Every 30 seconds
+
+ // Wait indefinitely (until Ctrl+C)
+ await new Promise(() => {});
+ }
+ }
+
+ } catch (err) {
+ printError(`Failed to start orchestration system: ${err.message}`);
+ console.error('Stack trace:', err.stack);
+ }
+}
+
+function getArgValue(args, flag) {
+ const index = args.indexOf(flag);
+ if (index !== -1 && index < args.length - 1) {
+ return args[index + 1];
+ }
+ return null;
+}
+
+async function cleanup() {
+ // Clean up resources
+ try {
+ await Deno.remove('.claude-flow.pid');
+ } catch {
+ // File might not exist
+ }
+
+ console.log('βœ“ Terminal pool closed');
+ console.log('βœ“ Task queue cleared');
+ console.log('βœ“ Memory bank saved');
+ console.log('βœ“ Cleanup complete');
+}
+
+function showStartHelp() {
+ console.log('Start the Claude-Flow orchestration system');
+ console.log();
+ console.log('Usage: claude-flow start [options]');
+ console.log();
+ console.log('Options:');
+ console.log(' -d, --daemon Run as daemon in background');
+ console.log(' -p, --port <port> MCP server port (default: 3000)');
+ console.log(' -u, --ui Launch interactive process management UI');
+ console.log(' -v, --verbose Show detailed system activity');
+ console.log(' -h, --help Show this help message');
+ console.log();
+ console.log('Examples:');
+ console.log(' claude-flow start # Start in interactive mode');
+ console.log(' claude-flow start --daemon # Start as background daemon');
+ console.log(' claude-flow start --port 8080 # Use custom MCP port');
+ console.log(' claude-flow start --ui # Launch process management UI');
+ console.log(' claude-flow start --verbose # Show detailed logs');
+ console.log();
+ console.log('Process Management UI:');
+ console.log(' The --ui flag launches a text-based interface for managing processes');
+ console.log(' Features include:');
+ console.log(' - Start/stop individual components');
+ console.log(' - Real-time status monitoring');
+ console.log(' - Process health visualization');
+ console.log(' - Log viewing');
+ console.log();
+ console.log('Notes:');
+ console.log(' - Requires "claude-flow init" to be run first');
+ console.log(' - Interactive mode shows real-time system status');
+ console.log(' - Daemon mode runs in background (check logs)');
+ console.log(' - Use "claude-flow status" to check if running');
+ console.log(' - Use Ctrl+C or "claude-flow stop" to shutdown');
+}
\ No newline at end of file
diff --git a/src/cli/simple-commands/start.js b/src/cli/simple-commands/start.js
index 558e4175f3..a0ac28ddaf 100644
--- a/src/cli/simple-commands/start.js
+++ b/src/cli/simple-commands/start.js
@@ -1,182 +1,2 @@
-// start.js - Start the Claude-Flow orchestration system
-import { printSuccess, printError, printWarning, printInfo } from '../utils.js';
-
-export async function startCommand(subArgs, flags) {
- // Show help if requested
- if (flags.help || flags.h || subArgs.includes('--help') || subArgs.includes('-h')) {
- showStartHelp();
- return;
- }
-
- // Parse start options
- const daemon = subArgs.includes('--daemon') || subArgs.includes('-d') || flags.daemon;
- const port = flags.port || getArgValue(subArgs, '--port') || getArgValue(subArgs, '-p') || 3000;
- const verbose = subArgs.includes('--verbose') || subArgs.includes('-v') || flags.verbose;
-
- try {
- printSuccess('Starting Claude-Flow Orchestration System...');
- console.log();
-
- // Check if required directories exist
- const requiredDirs = ['memory', 'coordination'];
- let missingDirs = [];
-
- for (const dir of requiredDirs) {
- try {
- await Deno.stat(dir);
- } catch {
- missingDirs.push(dir);
- }
- }
-
- if (missingDirs.length > 0) {
- printWarning('Missing required directories: ' + missingDirs.join(', '));
- console.log('Run "claude-flow init" first to create the necessary structure');
- return;
- }
-
- // Display startup information
- console.log('πŸš€ System Configuration:');
- console.log(` Mode: ${daemon ? 'Daemon (background)' : 'Interactive'}`);
- console.log(` MCP Port: ${port}`);
- console.log(` Working Directory: ${Deno.cwd()}`);
- console.log(` Memory Backend: JSON (default)`);
- console.log(` Terminal Pool: 5 instances (default)`);
- console.log();
-
- // Initialize components
- console.log('πŸ“‹ Initializing Components:');
-
- // Memory system
- console.log(' βœ“ Memory Bank: Ready');
- console.log(' - Backend: JSON file (memory/claude-flow-data.json)');
- console.log(' - Namespaces: Enabled');
-
- // Terminal pool
- console.log(' βœ“ Terminal Pool: Ready');
- console.log(' - Pool Size: 5');
- console.log(' - Shell: ' + (Deno.build.os === 'windows' ? 'cmd.exe' : '/bin/bash'));
-
- // Task queue
- console.log(' βœ“ Task Queue: Ready');
- console.log(' - Max Concurrent: 10');
- console.log(' - Priority Queue: Enabled');
-
- // MCP Server
- console.log(' βœ“ MCP Server: Ready');
- console.log(` - Port: ${port}`);
- console.log(' - Transport: stdio/HTTP');
-
- console.log();
-
- if (daemon) {
- // Daemon mode - would normally fork process
- printInfo('Starting in daemon mode...');
- console.log('Note: Full daemon mode requires the TypeScript version');
- console.log('The orchestrator would run in the background on port ' + port);
-
- // Create a simple PID file to simulate daemon
- const pid = Deno.pid;
- await Deno.writeTextFile('.claude-flow.pid', pid.toString());
- console.log(`Process ID: ${pid} (saved to .claude-flow.pid)`);
-
- } else {
- // Interactive mode
- printSuccess('Orchestration system started!');
- console.log();
- console.log('🎯 Available Actions:');
- console.log(' β€’ Open another terminal and run:');
- console.log(' - claude-flow agent spawn researcher');
- console.log(' - claude-flow task create "your task"');
- console.log(' - claude-flow sparc "build feature"');
- console.log(' - claude-flow monitor');
- console.log();
- console.log(' β€’ View system status:');
- console.log(' - claude-flow status');
- console.log();
- console.log(' β€’ Press Ctrl+C to stop the orchestrator');
- console.log();
-
- if (verbose) {
- console.log('πŸ“Š Verbose Mode - Showing system activity:');
- console.log('[' + new Date().toISOString() + '] System initialized');
- console.log('[' + new Date().toISOString() + '] Waiting for commands...');
- }
-
- // Keep the process running
- console.log('🟒 System is running...');
-
- // Set up signal handlers
- const abortController = new AbortController();
-
- Deno.addSignalListener("SIGINT", () => {
- console.log('\n⏹️ Shutting down orchestrator...');
- cleanup();
- Deno.exit(0);
- });
-
- // Simple heartbeat to show system is alive
- if (!daemon) {
- const heartbeat = setInterval(() => {
- if (verbose) {
- console.log('[' + new Date().toISOString() + '] Heartbeat - System healthy');
- }
- }, 30000); // Every 30 seconds
-
- // Wait indefinitely (until Ctrl+C)
- await new Promise(() => {});
- }
- }
-
- } catch (err) {
- printError(`Failed to start orchestration system: ${err.message}`);
- console.error('Stack trace:', err.stack);
- }
-}
-
-function getArgValue(args, flag) {
- const index = args.indexOf(flag);
- if (index !== -1 && index < args.length - 1) {
- return args[index + 1];
- }
- return null;
-}
-
-async function cleanup() {
- // Clean up resources
- try {
- await Deno.remove('.claude-flow.pid');
- } catch {
- // File might not exist
- }
-
- console.log('βœ“ Terminal pool closed');
- console.log('βœ“ Task queue cleared');
- console.log('βœ“ Memory bank saved');
- console.log('βœ“ Cleanup complete');
-}
-
-function showStartHelp() {
- console.log('Start the Claude-Flow orchestration system');
- console.log();
- console.log('Usage: claude-flow start [options]');
- console.log();
- console.log('Options:');
- console.log(' -d, --daemon Run as daemon in background');
- console.log(' -p, --port <port> MCP server port (default: 3000)');
- console.log(' -v, --verbose Show detailed system activity');
- console.log(' -h, --help Show this help message');
- console.log();
- console.log('Examples:');
- console.log(' claude-flow start # Start in interactive mode');
- console.log(' claude-flow start --daemon # Start as background daemon');
- console.log(' claude-flow start --port 8080 # Use custom MCP port');
- console.log(' claude-flow start --verbose # Show detailed logs');
- console.log();
- console.log('Notes:');
- console.log(' - Requires "claude-flow init" to be run first');
- console.log(' - Interactive mode shows real-time system status');
- console.log(' - Daemon mode runs in background (check logs)');
- console.log(' - Use "claude-flow status" to check if running');
- console.log(' - Use Ctrl+C or "claude-flow stop" to shutdown');
-}
\ No newline at end of file
+// start.js - Re-export the wrapper to maintain backward compatibility
+export { startCommand } from './start-wrapper.js';
\ No newline at end of file
diff --git a/src/cli/simple-commands/status.js b/src/cli/simple-commands/status.js
index 4464e659cd..dd4cdc3f82 100644
--- a/src/cli/simple-commands/status.js
+++ b/src/cli/simple-commands/status.js
@@ -17,7 +17,7 @@ export async function statusCommand(subArgs, flags) {
async function getSystemStatus(verbose = false) {
const status = {
timestamp: Date.now(),
- version: '1.0.41',
+ version: '1.0.42',
orchestrator: {
running: false,
uptime: 0,