diff --git a/.hive-mind/hive.db-shm b/.hive-mind/hive.db-shm index e1d99a08e6..462d7091e3 100644 Binary files a/.hive-mind/hive.db-shm and b/.hive-mind/hive.db-shm differ diff --git a/.hive-mind/hive.db-wal b/.hive-mind/hive.db-wal index fac4ae9b8f..a19265862c 100644 Binary files a/.hive-mind/hive.db-wal and b/.hive-mind/hive.db-wal differ diff --git a/src/cli/simple-commands/hive-mind-wizard.js b/src/cli/simple-commands/hive-mind-wizard.js index d02dd9919a..de01720f29 100644 --- a/src/cli/simple-commands/hive-mind-wizard.js +++ b/src/cli/simple-commands/hive-mind-wizard.js @@ -1,7 +1,7 @@ const chalk = require('chalk'); const path = require('path'); const fs = require('fs'); -const sqlite3 = require('sqlite3').verbose(); +const Database = require('better-sqlite3'); // Interactive Wizard Implementation async function runInteractiveWizard() { diff --git a/src/cli/simple-commands/hive-mind.js b/src/cli/simple-commands/hive-mind.js index 1a9536bf21..1229f0292f 100644 --- a/src/cli/simple-commands/hive-mind.js +++ b/src/cli/simple-commands/hive-mind.js @@ -13,6 +13,7 @@ import chalk from 'chalk'; import ora from 'ora'; import { args, cwd, exit, writeTextFile, readTextFile, mkdirAsync } from '../node-compat.js'; import { isInteractive, isRawModeSupported, warnNonInteractive, checkNonInteractiveAuth } from '../utils/interactive-detector.js'; +import { safeInteractive, nonInteractiveProgress, nonInteractiveSelect } from '../utils/safe-interactive.js'; // Import SQLite for persistence import Database from 'better-sqlite3'; @@ -222,50 +223,87 @@ async function initHiveMind(flags) { /** * Interactive wizard for hive mind operations */ -async function hiveMindWizard() { - console.log(chalk.yellow('\nšŸ§™ Hive Mind Interactive Wizard\n')); - - const { action } = await inquirer.prompt([ - { - type: 'list', - name: 'action', - message: 'What would you like to do?', - choices: [ - { name: 'šŸ Create new swarm', value: 'spawn' }, - { name: 'šŸ“Š View swarm status', value: 'status' }, - { name: '🧠 Manage collective memory', value: 'memory' }, - { name: 'šŸ¤ View consensus decisions', value: 'consensus' }, - { name: 'šŸ“ˆ Performance metrics', value: 'metrics' }, - { name: 'šŸ”§ Configure hive mind', value: 'config' }, - { name: 'āŒ Exit', value: 'exit' } - ] +// Wrapped wizard function that handles non-interactive environments +const hiveMindWizard = safeInteractive( + // Interactive version + async function(flags = {}) { + console.log(chalk.yellow('\nšŸ§™ Hive Mind Interactive Wizard\n')); + + const { action } = await inquirer.prompt([ + { + type: 'list', + name: 'action', + message: 'What would you like to do?', + choices: [ + { name: 'šŸ Create new swarm', value: 'spawn' }, + { name: 'šŸ“Š View swarm status', value: 'status' }, + { name: '🧠 Manage collective memory', value: 'memory' }, + { name: 'šŸ¤ View consensus decisions', value: 'consensus' }, + { name: 'šŸ“ˆ Performance metrics', value: 'metrics' }, + { name: 'šŸ”§ Configure hive mind', value: 'config' }, + { name: 'āŒ Exit', value: 'exit' } + ] + } + ]); + + switch (action) { + case 'spawn': + await spawnSwarmWizard(); + break; + case 'status': + await showStatus({}); + break; + case 'memory': + await manageMemoryWizard(); + break; + case 'consensus': + await showConsensus({}); + break; + case 'metrics': + await showMetrics({}); + break; + case 'config': + await configureWizard(); + break; + case 'exit': + console.log(chalk.gray('Exiting wizard...')); + break; } - ]); - - switch (action) { - case 'spawn': - await spawnSwarmWizard(); - break; - case 'status': - await showStatus({}); - break; - case 'memory': - await manageMemoryWizard(); - break; - case 'consensus': - await showConsensus({}); - break; - case 'metrics': - await showMetrics({}); - break; - case 'config': - await configureWizard(); - break; - case 'exit': - console.log(chalk.gray('Exiting wizard...')); - break; + }, + // Non-interactive fallback + async function(flags = {}) { + console.log(chalk.yellow('\nšŸ§™ Hive Mind - Non-Interactive Mode\n')); + + // Default to creating a swarm with sensible defaults + console.log(chalk.cyan('Creating new swarm with default settings...')); + console.log(chalk.gray('Use command-line flags to customize:')); + console.log(chalk.gray(' --objective "Your task" Set swarm objective')); + console.log(chalk.gray(' --queen-type strategic Set queen type')); + console.log(chalk.gray(' --max-workers 8 Set worker count')); + console.log(); + + const objective = flags.objective || 'General task coordination'; + const config = { + name: flags.name || `swarm-${Date.now()}`, + queenType: flags.queenType || flags['queen-type'] || 'strategic', + maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'), + consensusAlgorithm: flags.consensus || 'majority', + autoScale: flags.autoScale || flags['auto-scale'] || false, + encryption: flags.encryption || false + }; + + await spawnSwarm([objective], { + ...flags, + name: config.name, + queenType: config.queenType, + maxWorkers: config.maxWorkers, + consensusAlgorithm: config.consensusAlgorithm, + autoScale: config.autoScale, + encryption: config.encryption, + nonInteractive: true + }); } -} +); /** * Spawn swarm wizard @@ -1179,7 +1217,7 @@ export async function hiveMindCommand(args, flags) { break; case 'wizard': - await hiveMindWizard(); + await hiveMindWizard(flags); break; case 'help': diff --git a/src/cli/ui/fallback-handler.ts b/src/cli/ui/fallback-handler.ts index a82eba6270..318d734507 100644 --- a/src/cli/ui/fallback-handler.ts +++ b/src/cli/ui/fallback-handler.ts @@ -36,6 +36,8 @@ export async function handleRawModeError( console.log(); console.log(chalk.cyan('Common causes:')); console.log(chalk.gray('• VS Code integrated terminal')); + console.log(chalk.gray('• WSL (Windows Subsystem for Linux)')); + console.log(chalk.gray('• Native Windows terminals')); console.log(chalk.gray('• CI/CD environments')); console.log(chalk.gray('• Docker containers')); console.log(chalk.gray('• SSH sessions without TTY')); diff --git a/src/cli/utils/environment-detector.ts b/src/cli/utils/environment-detector.ts index 7f1e271f74..087f252f22 100644 --- a/src/cli/utils/environment-detector.ts +++ b/src/cli/utils/environment-detector.ts @@ -14,6 +14,8 @@ export interface ExecutionEnvironment { isSSH: boolean; isGitBash: boolean; isWindowsTerminal: boolean; + isWSL: boolean; + isWindows: boolean; supportsRawMode: boolean; supportsColor: boolean; terminalType: string; @@ -40,6 +42,8 @@ export function detectExecutionEnvironment(options: EnvironmentOptions = {}): Ex isSSH: false, isGitBash: false, isWindowsTerminal: false, + isWSL: false, + isWindows: false, supportsRawMode: false, supportsColor: true, terminalType: 'unknown', @@ -85,6 +89,16 @@ export function detectExecutionEnvironment(options: EnvironmentOptions = {}): Ex // Windows Terminal detection env.isWindowsTerminal = Boolean(process.env.WT_SESSION); + // Windows detection + env.isWindows = process.platform === 'win32'; + + // WSL detection + env.isWSL = Boolean( + process.env.WSL_DISTRO_NAME || + process.env.WSL_INTEROP || + (existsSync('/proc/version') && readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft')) + ); + // Raw mode support check env.supportsRawMode = checkRawModeSupport(); @@ -160,6 +174,21 @@ function generateRecommendations(env: ExecutionEnvironment): void { env.warnings.push('Git Bash detected - some interactive features may not work correctly'); } + // WSL specific recommendations + if (env.isWSL) { + env.recommendedFlags.push('--no-interactive'); + env.warnings.push('WSL detected - raw mode may cause hangs, using non-interactive mode'); + if (!env.supportsRawMode) { + env.warnings.push('WSL subprocess context detected - interactive features disabled'); + } + } + + // Windows specific recommendations + if (env.isWindows && !env.isWSL) { + env.recommendedFlags.push('--compatible-ui'); + env.warnings.push('Native Windows detected - using compatible UI mode'); + } + // Raw mode not supported if (!env.supportsRawMode && env.isInteractive) { env.recommendedFlags.push('--compatible-ui'); @@ -242,6 +271,8 @@ export function getEnvironmentDescription(env?: ExecutionEnvironment): string { if (environment.isSSH) parts.push('SSH'); if (environment.isGitBash) parts.push('Git Bash'); if (environment.isWindowsTerminal) parts.push('Windows Terminal'); + if (environment.isWSL) parts.push('WSL'); + if (environment.isWindows && !environment.isWSL) parts.push('Windows'); if (parts.length === 0) { parts.push(environment.terminalType); @@ -265,6 +296,8 @@ export function shouldUseNonInteractiveMode(options?: { force?: boolean }): bool return !env.isInteractive || env.isCI || env.isVSCode || + env.isWSL || + env.isWindows || !env.supportsRawMode; } diff --git a/src/cli/utils/safe-interactive.js b/src/cli/utils/safe-interactive.js new file mode 100644 index 0000000000..b3cd36867a --- /dev/null +++ b/src/cli/utils/safe-interactive.js @@ -0,0 +1,141 @@ +/** + * Safe Interactive Wrapper - Handles interactive commands in non-interactive environments + */ + +import chalk from 'chalk'; +import { shouldUseNonInteractiveMode, detectExecutionEnvironment } from './environment-detector.js'; + +/** + * Wraps an interactive function with safety checks + * @param {Function} interactiveFn - The interactive function to wrap + * @param {Function} fallbackFn - The non-interactive fallback function + * @param {Object} options - Options for the wrapper + * @returns {Function} The wrapped function + */ +export function safeInteractive(interactiveFn, fallbackFn, options = {}) { + return async function(...args) { + const flags = args[args.length - 1] || {}; + + // Check if user explicitly requested non-interactive mode + if (flags.nonInteractive || flags['no-interactive']) { + if (fallbackFn) { + return fallbackFn(...args); + } else { + console.log(chalk.yellow('āš ļø Non-interactive mode requested but no fallback available')); + console.log(chalk.gray('This command requires interactive mode to function properly')); + process.exit(1); + } + } + + // Auto-detect if we should use non-interactive mode + if (shouldUseNonInteractiveMode()) { + const env = detectExecutionEnvironment({ skipWarnings: true }); + + if (!options.silent) { + console.log(chalk.yellow('\nāš ļø Interactive mode not available')); + + // Provide specific message based on environment + if (env.isWSL) { + console.log(chalk.gray('WSL detected - raw mode may cause process hangs')); + console.log(chalk.cyan('šŸ’” Tip: Use --no-interactive flag or run in native Linux')); + } else if (env.isWindows) { + console.log(chalk.gray('Windows detected - terminal compatibility issues')); + console.log(chalk.cyan('šŸ’” Tip: Use Windows Terminal or WSL2 for better experience')); + } else if (env.isVSCode) { + console.log(chalk.gray('VS Code terminal detected - limited interactive support')); + console.log(chalk.cyan('šŸ’” Tip: Use external terminal for full functionality')); + } else if (!env.supportsRawMode) { + console.log(chalk.gray('Terminal does not support raw mode')); + } + + console.log(); + } + + if (fallbackFn) { + return fallbackFn(...args); + } else { + console.log(chalk.red('āŒ This command requires interactive mode')); + console.log(chalk.gray('Please run in a compatible terminal environment')); + process.exit(1); + } + } + + // Try to run the interactive function + try { + return await interactiveFn(...args); + } catch (error) { + // Check if it's a raw mode error + if (error.message && ( + error.message.includes('setRawMode') || + error.message.includes('raw mode') || + error.message.includes('stdin') || + error.message.includes('TTY') + )) { + console.log(chalk.yellow('\nāš ļø Interactive mode failed')); + console.log(chalk.gray(error.message)); + + if (fallbackFn) { + console.log(chalk.cyan('Falling back to non-interactive mode...')); + return fallbackFn(...args); + } else { + console.log(chalk.red('āŒ No non-interactive fallback available')); + process.exit(1); + } + } + + // Re-throw other errors + throw error; + } + }; +} + +/** + * Create a non-interactive version of a prompt + * @param {string} message - The prompt message + * @param {*} defaultValue - The default value to use + * @returns {*} The default value + */ +export function nonInteractivePrompt(message, defaultValue) { + console.log(chalk.gray(`šŸ“ ${message}`)); + console.log(chalk.cyan(` Using default: ${defaultValue}`)); + return defaultValue; +} + +/** + * Create a non-interactive version of a selection + * @param {string} message - The selection message + * @param {Array} choices - The available choices + * @param {*} defaultChoice - The default choice + * @returns {*} The default choice + */ +export function nonInteractiveSelect(message, choices, defaultChoice) { + console.log(chalk.gray(`šŸ“‹ ${message}`)); + console.log(chalk.gray(' Available choices:')); + choices.forEach(choice => { + const isDefault = choice === defaultChoice || choice.value === defaultChoice; + console.log(chalk.gray(` ${isDefault ? 'ā–¶' : ' '} ${choice.name || choice}`)); + }); + console.log(chalk.cyan(` Using default: ${defaultChoice}`)); + return defaultChoice; +} + +/** + * Show a non-interactive progress indicator + * @param {string} message - The progress message + * @returns {Object} Progress control object + */ +export function nonInteractiveProgress(message) { + console.log(chalk.gray(`ā³ ${message}...`)); + + return { + update: (newMessage) => { + console.log(chalk.gray(` ${newMessage}`)); + }, + succeed: (finalMessage) => { + console.log(chalk.green(`āœ… ${finalMessage || message}`)); + }, + fail: (errorMessage) => { + console.log(chalk.red(`āŒ ${errorMessage || 'Failed'}`)); + } + }; +} \ No newline at end of file