UNPKG

@hivetechs/hive-ai

Version:

Real-time streaming AI consensus platform with HTTP+SSE MCP integration for Claude Code, VS Code, Cursor, and Windsurf - powered by OpenRouter's unified API

1,014 lines (988 loc) โ€ข 359 kB
#!/usr/bin/env node /** * Hive.AI CLI - OpenRouter-Exclusive Architecture * * Simplified CLI for OpenRouter-powered AI consensus platform. * Access 400+ models from 60+ providers through unified API. */ import { fileURLToPath } from 'url'; import { dirname, join } from 'path'; import readline from 'readline'; import fs from 'fs'; import path from 'path'; import os from 'os'; import { getHelpForCommand } from './tools/hiveai/help-system.js'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); // Define path constants const DB_DIR = path.join(os.homedir(), '.hive'); // Global session conversation ID for interactive mode let sessionConversationId = null; let quietMode = true; // Start in quiet mode by default // Import the logger when available let logger; try { const loggerModule = await import('./utils/logging.js'); logger = loggerModule.logger; logger.setQuietMode(true); } catch (error) { // Fallback logger if import fails logger = { log: console.log, error: console.error, info: console.log, debug: console.log, warn: console.log, setQuietMode: (quiet) => { quietMode = quiet; }, setDebugMode: () => { } }; } // Simple edit distance calculation for typo detection function getEditDistance(str1, str2) { const matrix = Array(str2.length + 1).fill(null).map(() => Array(str1.length + 1).fill(null)); for (let i = 0; i <= str1.length; i++) matrix[0][i] = i; for (let j = 0; j <= str2.length; j++) matrix[j][0] = j; for (let j = 1; j <= str2.length; j++) { for (let i = 1; i <= str1.length; i++) { const indicator = str1[i - 1] === str2[j - 1] ? 0 : 1; matrix[j][i] = Math.min(matrix[j][i - 1] + 1, // deletion matrix[j - 1][i] + 1, // insertion matrix[j - 1][i - 1] + indicator // substitution ); } } return matrix[str2.length][str1.length]; } // Load session ID from unified database async function loadSessionId() { try { const { getConfig } = await import('./storage/unified-database.js'); const sessionId = await getConfig('cli_session_id'); if (sessionId) { sessionConversationId = sessionId; if (!quietMode) { console.log(`Loaded session conversation ID from database: ${sessionConversationId}`); } } } catch (error) { console.error(`Error loading session ID: ${error.message}`); } } // Save session ID to unified database async function saveSessionId(id) { try { const { setConfig } = await import('./storage/unified-database.js'); await setConfig('cli_session_id', id); if (!quietMode) { console.log(`Saved session conversation ID to database: ${id}`); } } catch (error) { console.error('Warning: Could not save session ID to database:', error.message); throw error; } } // Initialize database function async function initializeDatabase() { try { if (!fs.existsSync(DB_DIR)) { fs.mkdirSync(DB_DIR, { recursive: true }); } // Initialize the actual SQLite database with all tables const { initializeDatabase: initDB } = await import('./storage/database.js'); const dbInitialized = await initDB(); if (!dbInitialized) { logger.error('Failed to initialize SQLite database'); return false; } await loadSessionId(); return true; } catch (error) { logger.error(`Database initialization error: ${error.message}`); return false; } } /** * Show comprehensive help information */ function showHelp(topic) { // If a specific topic is requested, use the help system if (topic) { const helpContent = getHelpForCommand(topic); console.log(helpContent); return; } // Otherwise show the main help screen console.log(` ๐Ÿ hive CLI - OpenRouter-Powered AI Consensus Platform ๐Ÿš€ GETTING STARTED: hive quickstart - Complete setup: license + IDEs + MCP server hive help [topic] - Get detailed help on any topic ๐Ÿ‘ค ACCOUNT MANAGEMENT: hive login - Login or switch to different account hive logout - Logout current user and clear local data hive configure refresh - Refresh license after plan upgrades ๐Ÿค– CORE AI FEATURES: hive consensus "your prompt" [--auto|-a] - 4-stage AI consensus pipeline [--manual|-m] Use --auto/--manual to override mode hive "your prompt here" - Direct consensus (real-time streaming) hive concurrent "your prompt" - Experimental parallel stage execution ๐Ÿง  INTELLIGENT FEATURES: hive mode [auto|manual] - Toggle between intelligent and manual selection hive cost estimate "question" - Predict consensus cost with intelligent analysis hive templates check - Validate Expert Template health automatically ๐Ÿ”ง PROVIDERS & CONFIGURATION: hive provider configure openrouter <key> - Configure OpenRouter API key hive test-providers - Test OpenRouter connectivity hive list-providers - Show OpenRouter configuration status ๐Ÿ—‚๏ธ PIPELINE PROFILES: hive pipeline list - List configured pipeline profiles hive pipeline configure - Set up 4-stage consensus models hive pipeline clean - Remove outdated profile names hive mode [auto|manual] - Toggle profile selection mode hive toggle - Quick toggle between auto/manual ๐ŸŽฏ EXPERT TEMPLATES: templates list - List available expert profile templates templates apply <id> [name] - Create profile from expert template templates recommend [level] - Get template recommendations templates search <keyword> - Search templates by use case ๐Ÿง  DYNAMIC INTELLIGENCE: intelligence update - Update OpenRouter model rankings intelligence status - Show current intelligence data models ranking [limit] - Show top-ranked programming models models discover [filters] - Discover models with criteria models search <query> - Search models by description or capability models compare <model1> <model2> - Compare two models side-by-side cost estimate your question - Estimate consensus cost for question cost settings [budget] - Configure budget limits ๐Ÿ” MODELS & DATA: models list [provider] - List available models from OpenRouter models update - Update model data from OpenRouter cleanup-models [--dry-run] [--force] - Remove invalid model entries from database test-cleanup - Test database cleanup system functionality ๐Ÿงช A/B TESTING & EFFECTIVENESS: ab-test your question [--baseline] - A/B test: single model vs 4-stage consensus effectiveness report - Generate consensus effectiveness analytics [--from] [--to] [--category] [--complexity] ๐Ÿงช LEGACY EVALUATION & TESTING: create-test-profiles - Create test profiles for consensus evaluation test-consensus-models - Run comprehensive consensus model tests test-developer-consensus - Test consensus on complex coding challenges test-streaming - Test streaming consensus functionality consensus-report - Generate consensus analysis report analyze-latest - Analyze latest consensus runs ๐Ÿ”ฌ EXPERT ANALYTICS & BI: analytics collect [timeframe] - Collect comprehensive analytics metrics analytics trends [period] - Generate analytics trend analysis report generate [type] [period] - Generate professional analytics reports report export <id> [format] - Export reports (JSON, CSV, Excel, HTML, PDF) dashboard executive - Executive-level business intelligence dashboard dashboard operational - Operational performance dashboard kpi list [category] - List business KPIs by category kpi update - Force refresh of all KPIs insights strategic - Generate strategic business insights insights generate [focus] - AI-powered insights (cost/performance/quality) ๐ŸŽฏ EXPERT MONITORING: perf profile [name] [duration] - Profile pipeline performance with analysis perf compare <baseline> <current> - Compare performance across time periods perf bottlenecks [timeframe] - Identify and analyze performance bottlenecks alerts list - List active monitoring alerts alerts configure <action> - Configure advanced alert rules trace conversation <id> - Deep trace analysis of conversation pipeline optimize recommendations [focus] - Get AI-powered optimization recommendations export metrics [format] - Export performance metrics for external tools ๐Ÿฅ HEALTH & MONITORING: health [--detailed] - Check system health and error statistics reset-circuit <provider>/<model> - Reset circuit breaker for a model ๐Ÿ› ๏ธ DATABASE DIAGNOSTICS: diagnose - Check database health and profile saving issues repair [--yes] - Automatically fix common database problems reset-database --confirm - Nuclear option: completely reset database ๐Ÿ’พ BACKUP & RECOVERY: backup create [type] [label] - Create database backup (full/incremental/emergency) backup restore <path> - Restore database from backup file backup list [type] - List available backups by type backup health - Check backup system health and recommendations backup locations - Configure backup storage locations (local/cloud folders) backup emergency-restore - Emergency disaster recovery from latest valid backup ๐Ÿงน CACHE MANAGEMENT: cache clear - Clear all system caches (model data, API responses) โš™๏ธ CONFIGURATION AS CODE (IAC): hive config apply <file> - Apply configuration from YAML/JSON file hive config export [file] - Export current configuration to file hive config validate <file> - Validate configuration file syntax and requirements hive config diff <file> - Show differences between file and current configuration hive config template [type] - Generate configuration template (basic/enterprise) hive config validate - Validate current configuration hive config test-auth - Test OpenRouter API key authentication ๐Ÿ”Œ AI AGENT INTEGRATION: mcp-daemon start - Start persistent MCP daemon (2025 architecture) mcp-daemon status - Check daemon health and auto-recovery status mcp-daemon stop - Stop persistent daemon mcp-server start - Start Model Context Protocol server (legacy) mcp-server config - Show Claude Desktop integration config mcp-server status - Check MCP server status mcp-server help - Show MCP server help ๐ŸŒŠ REAL-TIME STREAMING: โ€ข All consensus questions use real-time streaming โ€ข See live progress through each stage โ€ข Watch token rates and completion times โ€ข Examples: hive design a React app hive explain machine learning concepts ๐Ÿ“š HELP TOPICS: help getting-started - New user guide with intelligent features help intelligent-features - Learn about AI optimization and smart features help consensus - Learn about 4-stage analysis with AUTO mode help models - AI model management (400+ models) help profiles - Pipeline configuration and Expert Templates help expert-templates - Pre-built configurations for different use cases help infrastructure-as-code - Script-based configuration management for DevOps help configuration - YAML/JSON configuration file management help streaming - Real-time streaming setup for IDEs help automation - PowerShell/Bash scripts and CI/CD integration help backup - Database backup, restore, and cloud storage integration help troubleshooting - Fix common issues and maintenance help commands - Complete command reference ๐ŸŽฏ QUICK START GUIDE: 1. hive quickstart # Complete setup 2. hive consensus "how do I optimize my code" # Ask your first question ๐Ÿ’ก FEATURES: โ€ข Access 400+ models from 60+ providers with one OpenRouter API key โ€ข 4-stage consensus pipeline (Generator โ†’ Refiner โ†’ Validator โ†’ Curator) โ€ข Daily conversation limits based on your license tier โ€ข Secure local SQLite storage for all configurations โš ๏ธ SPECIAL CHARACTERS: โ€ข Most queries work without quotes: hive how do I optimize React โ€ข Use quotes for special characters: hive "what about arrays?" โ€ข Required for: ? * [ ] { } ! and other shell special characters ๐Ÿ’ก COMMAND FORMAT: โ€ข ALL commands must start with "hive" โ€ข Examples: hive quickstart, hive config apply file.yaml, hive help topics Get OpenRouter API key: https://openrouter.ai/keys Get hive license: https://hivetechs.io/pricing Support: https://github.com/hivetechs-collective/hive.ai/issues `); } async function showVersion() { try { const packagePath = join(__dirname, '../package.json'); if (fs.existsSync(packagePath)) { const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8')); console.log(`๐Ÿ hive v${pkg.version}`); // Check for updates occasionally (non-blocking) checkForUpdatesQuietly(); } else { console.log('๐Ÿ hive v1.0.0-beta.55'); } } catch (error) { console.log('๐Ÿ hive v1.0.0-beta.55'); } } // Non-blocking update check for existing users async function checkForUpdatesQuietly() { try { const { PackageUpdateChecker } = await import('./tools/hiveai/package-update-checker.js'); const checker = new PackageUpdateChecker(); // Only check if it's time (respects frequency settings) const result = await checker.performUpdateCheckIfNeeded(); if (result && result.updateAvailable) { console.log(''); console.log('๐Ÿ†• Update available! Run: npm update -g @hivetechs/hive-ai'); console.log(` Current: v${result.currentVersion} โ†’ Latest: v${result.latestVersion}`); if (result.updateType === 'major' || result.updateType === 'minor') { console.log('โšก This update includes important streaming output fixes for Claude Code!'); } console.log(''); } } catch (error) { // Silently fail - don't interrupt user workflow } } // Non-blocking model discovery update check async function checkForModelUpdatesQuietly() { try { const { OpenRouterRankings } = await import('./tools/openrouter-rankings.js'); const intelligence = new OpenRouterRankings(); // Only check if rankings need refresh (older than 24 hours) const needsRefresh = await intelligence.needsRankingRefresh(); if (needsRefresh) { // Run the update silently in background await intelligence.collectRankingIntelligence(); await intelligence.discoverModelsViaAPI(); } // ๐Ÿ”ง ALWAYS check template maintenance during daily usage const { runTemplateMaintenanceIfDue } = await import('./tools/hiveai/template-maintenance.js'); await runTemplateMaintenanceIfDue(); } catch (error) { // Silently fail - don't interrupt user workflow // Model discovery updates are non-critical for immediate CLI operation } } /** * Execute a command with raw args array for better multi-word handling */ async function executeCommandWithArgs(rawArgs) { // Handle empty args if (rawArgs.length === 0) { return; } const cmd = rawArgs[0].toLowerCase(); const args = rawArgs; // Keep original args array try { if (cmd === 'consensus') { // Check for profile subcommands first const subCmd = args[1]?.toLowerCase(); if (subCmd === 'profile') { const profileAction = args[2]?.toLowerCase(); if (profileAction === 'set') { // Handle profile set command (interactive menu) await handleConsensusProfileSet(); } else { // Handle profile view command (show current profile) await handleConsensusProfileView(); } return; } // Check license before allowing consensus try { const { checkLicenseStatus } = await import('./tools/hiveai/license-configuration.js'); const licenseStatus = await checkLicenseStatus(); if (!licenseStatus.hasLicense || !licenseStatus.isValid) { console.log('\n๐Ÿ”‘ License Required\n'); console.log('hive consensus features require a valid license.\n'); console.log('๐Ÿ“‹ Quick setup:'); console.log(' 1. hive configure license # Get your license'); console.log(' 2. hive quickstart # Complete setup'); console.log(' 3. hive consensus your question here # Try again'); console.log(''); console.log('๐Ÿ†“ Get a free license at: https://hivetechs.io/pricing'); return; } const emailDisplay = licenseStatus.email ? ` - ${licenseStatus.email}` : ''; const versionDisplay = licenseStatus.version ? ` - v${licenseStatus.version}` : ''; console.log(`โœ… License verified - ${licenseStatus.tier} tier${emailDisplay}${versionDisplay}`); } catch (error) { console.log('\nโš ๏ธ License validation failed. Please configure your license:\n'); console.log(' hive configure license'); return; } // Parse flags and question const allArgs = args.slice(1); // Remove 'consensus' const flags = allArgs.filter(arg => arg.startsWith('--') || arg.startsWith('-')); const questionWords = allArgs.filter(arg => !arg.startsWith('--') && !arg.startsWith('-')); const question = questionWords.join(' '); if (!question || question.trim() === '') { console.log('โŒ Please provide a question'); console.log('Usage: hive consensus your question here [--auto|--manual|-a|-m]'); console.log(''); console.log('๐ŸŒŠ Real-time streaming output during consensus processing'); console.log(''); console.log('Examples:'); console.log(' hive consensus how do I optimize React performance'); console.log(' hive consensus explain machine learning concepts'); console.log(' hive consensus design a REST API --manual'); return; } // Check for mode override flags let modeOverride = null; if (flags.includes('--auto') || flags.includes('-a')) { modeOverride = 'auto'; console.log('๐Ÿค– Using AUTO mode for this question (override)'); } else if (flags.includes('--manual') || flags.includes('-m')) { modeOverride = 'manual'; console.log('๐ŸŽฏ Using MANUAL mode for this question (override)'); } // STREAMING IS ALWAYS ENABLED - provides superior user experience process.env.HIVE_STREAMING = 'true'; console.log('๐ŸŒŠ STREAMING CONSENSUS - Real-time 4-stage pipeline output'); // Run consensus per SOURCE_OF_TRUTH design await handleConsensusQuestion(question, modeOverride); } else if (cmd === 'interactive') { // Interactive chat mode console.log('๐Ÿ’ฌ Starting interactive mode...'); console.log('Type your questions and get real-time consensus responses.'); console.log('Commands: "exit" to quit, "stream" to toggle streaming mode'); console.log(''); // License check try { const { checkLicenseStatus } = await import('./tools/hiveai/license-configuration.js'); const licenseStatus = await checkLicenseStatus(); if (!licenseStatus.hasLicense || !licenseStatus.isValid) { console.log('\n๐Ÿ”‘ License Required\n'); console.log('Interactive mode requires a valid license.\n'); console.log('๐Ÿ“‹ Quick setup:'); console.log(' 1. hive configure license # Get your license'); console.log(' 2. hive quickstart # Complete setup'); console.log(' 3. hive interactive # Try again'); console.log(''); console.log('๐Ÿ†“ Get a free license at: https://hivetechs.io/pricing'); return; } const emailDisplay = licenseStatus.email ? ` - ${licenseStatus.email}` : ''; const versionDisplay = licenseStatus.version ? ` - v${licenseStatus.version}` : ''; console.log(`โœ… License verified - ${licenseStatus.tier} tier${emailDisplay}${versionDisplay}`); } catch (error) { console.log('\nโš ๏ธ License validation failed. Please configure your license:\n'); console.log(' hive configure license'); return; } // Start interactive session const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); let streamingEnabled = false; const askQuestion = () => { rl.question('๐Ÿ Your question: ', async (input) => { const trimmed = input.trim(); if (trimmed === 'exit' || trimmed === 'quit') { console.log('๐Ÿ‘‹ Goodbye!'); rl.close(); return; } if (trimmed === 'stream') { streamingEnabled = !streamingEnabled; console.log(`๐ŸŒŠ Streaming mode: ${streamingEnabled ? 'ON' : 'OFF'}`); askQuestion(); return; } if (trimmed === 'help') { console.log('๐Ÿ’ก Interactive mode commands:'); console.log(' exit/quit - Exit interactive mode'); console.log(' stream - Toggle streaming mode'); console.log(' help - Show this help'); console.log(''); askQuestion(); return; } if (!trimmed) { askQuestion(); return; } try { if (streamingEnabled) { process.env.HIVE_STREAMING = 'true'; } else { delete process.env.HIVE_STREAMING; } await handleConsensusQuestion(trimmed, null); console.log(''); } catch (error) { console.log(`โŒ Error: ${error.message}`); } askQuestion(); }); }; askQuestion(); } else if (cmd === 'stream') { // Dedicated streaming consensus command const questionWords = args.slice(1); const question = questionWords.join(' '); if (!question || question.trim() === '') { console.log('โŒ Please provide a question'); console.log('Usage: hive stream your question here'); console.log('Example: hive stream explain quantum computing concepts'); return; } // License check const { checkLicenseStatus } = await import('./tools/hiveai/license-configuration.js'); const licenseStatus = await checkLicenseStatus(); if (!licenseStatus.hasLicense || !licenseStatus.isValid) { console.log('\n๐Ÿ”‘ License Required\n'); console.log('hive streaming requires a valid license.\n'); console.log('๐Ÿ“‹ Quick setup:'); console.log(' 1. hive configure license # Get your license'); console.log(' 2. hive quickstart # Complete setup'); console.log(' 3. hive stream "question" # Try streaming'); console.log(''); console.log('๐Ÿ†“ Get a free license at: https://hivetechs.io/pricing'); return; } // Enable streaming and run process.env.HIVE_STREAMING = 'true'; console.log('๐ŸŒŠ STREAMING CONSENSUS - Real-time 4-stage pipeline'); await handleConsensusQuestion(question, null); } else if (cmd === 'concurrent') { // Experimental concurrent consensus command const questionWords = args.slice(1); const question = questionWords.join(' '); if (!question || question.trim() === '') { console.log('โŒ Please provide a question'); console.log('Usage: hive concurrent "your question here"'); return; } // License check const { checkLicenseStatus } = await import('./tools/hiveai/license-configuration.js'); const licenseStatus = await checkLicenseStatus(); if (!licenseStatus.hasLicense || !licenseStatus.isValid) { console.log('\n๐Ÿ”‘ License Required\n'); console.log('hive concurrent requires a valid license.\n'); console.log('๐Ÿ“‹ Quick setup:'); console.log(' 1. hive configure license # Get your license'); console.log(' 2. hive quickstart # Complete setup'); console.log(' 3. hive concurrent "question" # Try concurrent'); return; } // Enable streaming with concurrent execution process.env.HIVE_STREAMING = 'true'; process.env.HIVE_CONCURRENT = 'true'; console.log('โšก CONCURRENT STREAMING CONSENSUS - Parallel stage execution'); await handleConsensusQuestion(question, null); } else if (cmd === 'mode') { // Handle mode toggle for consensus profile selection const mode = args[1]; const { getConfig, setConfig } = await import('./storage/unified-database.js'); const currentMode = await getConfig('consensus_mode') || 'auto'; if (!mode) { // Show current mode console.log(`\n๐ŸŽฏ Current consensus mode: ${currentMode.toUpperCase()}`); console.log(currentMode === 'auto' ? ' Profile selection: AUTOMATIC (based on question complexity)' : ' Profile selection: MANUAL (always uses your default profile)'); console.log('\nTo change: hive mode [auto|manual]'); } else if (mode === 'auto' || mode === 'manual') { // Set new mode await setConfig('consensus_mode', mode); console.log(`\nโœ… Consensus mode set to: ${mode.toUpperCase()}`); console.log(mode === 'auto' ? ' ๐Ÿค– Smart profile selection enabled - profiles chosen based on question complexity' : ' ๐ŸŽฏ Manual mode enabled - will always use your default profile'); } else { console.log('โŒ Invalid mode. Use: hive mode [auto|manual]'); } } else if (cmd === 'toggle') { // Quick toggle between modes const { getConfig, setConfig } = await import('./storage/unified-database.js'); const currentMode = await getConfig('consensus_mode') || 'auto'; const newMode = currentMode === 'auto' ? 'manual' : 'auto'; await setConfig('consensus_mode', newMode); console.log(`\n๐Ÿ”„ Toggled consensus mode: ${currentMode.toUpperCase()} โ†’ ${newMode.toUpperCase()}`); console.log(newMode === 'auto' ? ' ๐Ÿค– Smart profile selection enabled' : ' ๐ŸŽฏ Manual mode enabled - using default profile'); } else if (cmd === 'quickstart') { // Complete unified setup: license + IDEs + MCP server await handleQuickstart(args); } else if (cmd === 'diagnose') { // Run database diagnostics for troubleshooting await handleDiagnostics(args); } else if (cmd === 'repair') { // Repair database issues automatically await handleDatabaseRepair(args); } else if (cmd === 'reset-database') { // Nuclear option: reset database completely await handleDatabaseReset(args); } else if (cmd === 'cache' && args[0] === 'clear') { // Clear all system caches await handleCacheClear(args.slice(1)); } else if (cmd === 'provider' || cmd === 'configure-provider') { const { runConfigureProviderTool } = await import('./tools/hiveai/provider-config.js'); const providerName = args[1]; const apiKey = args[2]; if (!providerName || !apiKey) { console.log('Usage: hive provider configure openrouter <your-api-key>'); console.log('Get your key at: https://openrouter.ai/keys'); return; } const result = await runConfigureProviderTool({ command: `${providerName} ${apiKey}` }); if (result && result.result) { console.log(result.result); } } else if (cmd === 'test-providers') { const { runTestProvidersTool } = await import('./tools/hiveai/provider-config.js'); const result = await runTestProvidersTool(); if (result && result.result) { console.log(result.result); } } else if (cmd === 'list-providers') { const { runListProvidersTool } = await import('./tools/hiveai/provider-config.js'); const result = await runListProvidersTool(); if (result && result.result) { console.log(result.result); } } else if (cmd === 'pipeline') { const subCmd = args[1]?.toLowerCase(); if (subCmd === 'configure') { const { runConfigurePipelineTool } = await import('./tools/hiveai/pipeline-config.js'); const profileName = args[2] || 'default'; try { const result = await runConfigurePipelineTool({ command: `${profileName} openai/gpt-4 anthropic/claude-3-sonnet google/gemini-pro meta-llama/llama-2-70b-chat` }); if (result && result.result) { console.log(result.result); } } catch (error) { console.log(`โŒ Error configuring pipeline: ${error.message}`); } } else if (subCmd === 'list') { const { runListPipelineProfilesTool } = await import('./tools/hiveai/pipeline-config.js'); try { const result = await runListPipelineProfilesTool(); if (result && result.result) { console.log(result.result); } } catch (error) { console.log(`โŒ Error listing profiles: ${error.message}`); } } else if (subCmd === 'clean') { // Clean up old/outdated profiles try { console.log('๐Ÿงน Cleaning up outdated profiles...\n'); const { getAllPipelineProfiles, deletePipelineProfile } = await import('./storage/unified-database.js'); const profiles = await getAllPipelineProfiles(); // Find outdated profiles to remove const outdatedPatterns = [ 'WOW_Flagship_2025', 'Developer_Elite_2025', 'Balanced_Excellence_2025', 'Speed_Champion_2025', 'Research_Master_2025' ]; const outdatedProfiles = profiles.filter(p => outdatedPatterns.some(pattern => p.name.includes(pattern))); if (outdatedProfiles.length === 0) { console.log('โœ… No outdated profiles found. Your profiles are current!'); return; } console.log(`๐Ÿ” Found ${outdatedProfiles.length} outdated profiles:`); outdatedProfiles.forEach(p => console.log(` โ€ข ${p.name}`)); console.log(''); const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); const confirmCleanup = await new Promise((resolve) => { rl.question('Remove these outdated profiles? (Y/n): ', resolve); }); rl.close(); if (confirmCleanup.toLowerCase() === 'n' || confirmCleanup.toLowerCase() === 'no') { console.log('๐Ÿšซ Cleanup cancelled.'); return; } let removed = 0; for (const profile of outdatedProfiles) { const success = await deletePipelineProfile(profile.id); if (success) { console.log(`โœ… Removed: ${profile.name}`); removed++; } else { console.log(`โš ๏ธ Could not remove: ${profile.name}`); } } console.log(`\n๐ŸŽ‰ Cleanup complete! Removed ${removed} outdated profiles.`); console.log('\n๐Ÿš€ Your current profiles use professional, timeless names:'); console.log(' โ€ข Consensus_Elite (Premium dynamic profile)'); console.log(' โ€ข Code_Architect (Complex code generation)'); console.log(' โ€ข Smart_Balance (Cost-effective with premium polish)'); console.log(' โ€ข Lightning_Fast (Speed optimized)'); console.log(' โ€ข Research_Pro (Deep research and analysis)'); } catch (error) { console.log(`โŒ Error cleaning profiles: ${error.message}`); } } else { console.log('๐Ÿ”ง Available pipeline commands:'); console.log(' configure [name] - Interactive pipeline setup'); console.log(' list - List configured pipeline profiles'); console.log(' clean - Remove outdated profile names'); console.log(''); console.log('๐Ÿ’ก All models accessed through OpenRouter with your single API key'); } } else if (cmd === 'profiles') { const subCmd = args[1]?.toLowerCase(); if (subCmd === 'help') { console.log('๐Ÿ‘ฅ Profile Management Commands:'); console.log(''); console.log(' hive profiles list - List configured consensus profiles'); console.log(' hive profiles set - Set active profile (interactive)'); console.log(' hive profiles show [name] - Show profile details'); console.log(' hive profiles create - Create custom profile'); console.log(' hive profiles templates - Browse expert templates'); console.log(''); console.log('Examples:'); console.log(' hive profiles'); console.log(' hive profiles show Consensus_Elite'); return; } // Default to list if no subcommand provided if (!subCmd || subCmd === 'list') { const { runListPipelineProfilesTool } = await import('./tools/hiveai/pipeline-config.js'); try { const result = await runListPipelineProfilesTool(); if (result && result.result) { console.log(result.result); } console.log(''); console.log('๐Ÿ’ก Run "hive profiles help" for more options'); } catch (error) { console.log(`โŒ Error listing profiles: ${error.message}`); } return; } if (subCmd === 'set') { await handleConsensusProfileSet(); } else if (subCmd === 'show') { const profileName = args[2]; if (!profileName) { await handleConsensusProfileView(); } else { console.log(`๐Ÿ“‹ Profile details for: ${profileName}`); console.log('Details functionality coming soon...'); } } else if (subCmd === 'create') { console.log('๐Ÿ”ง Interactive profile creation'); console.log('Profile creation wizard coming soon...'); } else if (subCmd === 'templates') { await handleTemplatesList(); } else { console.log(`Unknown profiles command: ${subCmd}`); console.log('Run "hive profiles help" for available options'); } } else if (cmd === 'templates') { const subCmd = args[1]?.toLowerCase(); if (subCmd === 'list') { await handleTemplatesList(); } else if (subCmd === 'apply') { const templateId = args[2]; const profileName = args[3]; await handleTemplatesApply(templateId, profileName); } else if (subCmd === 'recommend') { const userLevel = args[2]; await handleTemplatesRecommend(userLevel); } else if (subCmd === 'search') { const keyword = args.slice(2).join(' '); await handleTemplatesSearch(keyword); } else { console.log('๐ŸŽฏ Available templates commands:'); console.log(' list - List available expert profile templates'); console.log(' apply <id> [name] - Create profile from expert template'); console.log(' recommend [level] - Get template recommendations by skill level'); console.log(' search <keyword> - Search templates by use case'); console.log(''); console.log('๐Ÿ’ก Expert templates provide pre-configured consensus profiles for specific use cases'); console.log('๐Ÿ’ก Examples:'); console.log(' hive templates list'); console.log(' hive templates apply lightning-fast "Quick Dev"'); console.log(' hive templates recommend beginner'); console.log(' hive templates search security'); } } else if (cmd === 'intelligence') { const subCmd = args[1]?.toLowerCase(); if (subCmd === 'update') { await handleIntelligenceUpdate(); } else if (subCmd === 'status') { await handleIntelligenceStatus(); } else { console.log('๐Ÿง  Available intelligence commands:'); console.log(' update - Update OpenRouter model rankings'); console.log(' status - Show current intelligence data'); console.log(''); console.log('๐Ÿ’ก Intelligence system keeps model selection current with OpenRouter rankings'); } } else if (cmd === 'cost') { const subCmd = args[1]?.toLowerCase(); if (subCmd === 'estimate') { const question = args.slice(2).join(' '); if (!question) { console.log('Usage: hive cost estimate "your question here"'); return; } await handleCostEstimate(question); } else if (subCmd === 'settings') { const budget = args[2]; await handleCostSettings(budget); } else if (subCmd === 'breakdown') { await handleCostBreakdown(); } else { console.log('๐Ÿ’ฐ Available cost commands:'); console.log(' breakdown - Show cost breakdown and analysis'); console.log(' estimate "question" - Estimate consensus cost for question'); console.log(' settings [budget] - Configure budget limits'); console.log(''); console.log('๐Ÿ’ก Cost intelligence helps optimize spending while maintaining quality'); } } else if (cmd === 'ab-test') { const question = args.slice(1).join(' '); if (!question) { console.log('Usage: hive ab-test "your question" [--baseline model]'); console.log('Example: hive ab-test "write a React component" --baseline openai/gpt-4o'); return; } await handleABTest(question, args); } else if (cmd === 'effectiveness') { const subCmd = args[1]?.toLowerCase(); if (subCmd === 'report') { const filters = { dateFrom: args.find((_, i) => args[i - 1] === '--from'), dateTo: args.find((_, i) => args[i - 1] === '--to'), category: args.find((_, i) => args[i - 1] === '--category'), complexity: args.find((_, i) => args[i - 1] === '--complexity') }; await handleEffectivenessReport(filters); } else { console.log('๐Ÿ“Š Available effectiveness commands:'); console.log(' report - Generate consensus effectiveness report'); console.log(''); console.log('๐Ÿ’ก Options:'); console.log(' --from YYYY-MM-DD - Filter from date'); console.log(' --to YYYY-MM-DD - Filter to date'); console.log(' --category <type> - Filter by question category'); console.log(' --complexity <level> - Filter by complexity level'); console.log(''); console.log('๐Ÿ’ก Examples:'); console.log(' hive effectiveness report'); console.log(' hive effectiveness report --from 2024-01-01 --category programming'); } } else if (cmd === 'models') { const subCmd = args[1]?.toLowerCase(); if (subCmd === 'list') { const { runListModelsTool } = await import('./tools/hiveai/model-selection.js'); const providerName = args[2] || undefined; const result = await runListModelsTool({ provider_name: providerName }); if (result && result.result) { console.log(result.result); } } else if (subCmd === 'update') { const { runUpdateModelsTool } = await import('./tools/hiveai/model-selection.js'); const result = await runUpdateModelsTool(); if (result && result.result) { console.log(result.result); } } else if (subCmd === 'ranking') { const limit = parseInt(args[2]) || 10; await handleModelRanking(limit); } else if (subCmd === 'leaderboard') { await handleModelLeaderboard(); } else if (subCmd === 'discover') { const filters = args.slice(2).join(' '); await handleModelDiscover(filters); } else if (subCmd === 'search') { const query = args.slice(2).join(' '); await handleModelSearch(query); } else if (subCmd === 'compare') { const model1 = args[2]; const model2 = args[3]; await handleModelCompare(model1, model2); } else { console.log('๐Ÿ” Available models commands:'); console.log(' list [provider] - List available models from OpenRouter'); console.log(' update - Update model data from OpenRouter'); console.log(' ranking [limit] - Show top-ranked programming models'); console.log(' leaderboard - Show model performance leaderboard'); console.log(' discover [filters] - Discover models with criteria'); console.log(' search <query> - Search models by description or capability'); console.log(' compare <model1> <model2> - Compare two models side-by-side'); console.log(''); console.log('๐Ÿ’ก Examples:'); console.log(' hive models list # List all providers and models'); console.log(' hive models ranking 15 # Show top 15 programming models'); console.log(' hive models leaderboard # Show performance metrics'); console.log(' hive models discover # Discover models by criteria'); console.log(' hive models search "coding" # Find models good at coding'); console.log(' hive models compare gpt-4 claude-3-opus # Compare two models'); } } else if (cmd === 'config' || cmd === 'configure') { const subCmd = args[1]?.toLowerCase(); if (subCmd === 'license') { // Interactive license configuration try { const { configureLicenseFromCLI } = await import('./tools/hiveai/license-configuration.js'); await configureLicenseFromCLI(); } catch (error) { console.log(`โŒ Error configuring license: ${error.message}`); } } else if (subCmd === 'refresh' || subCmd === 'refresh-license') { // Refresh license information (useful after plan upgrades) try { console.log('๐Ÿ”„ Refreshing license information from server...\n'); const { ModernLicenseGate } = await import('./core/modern-license-gate.js'); const licenseGate = ModernLicenseGate.getInstance(); const refreshedLicense = await licenseGate.refreshLicense(); console.log('๐Ÿ“Š Updated License Information:'); const tierDisplay = refreshedLicense.tier === 'free' ? 'FREE' : (refreshedLicense.dailyLimit || 0) >= 999999 ? 'UNLIMITED' : 'PREMIUM'; console.log(` ๐ŸŽฏ Plan: ${tierDisplay}`); console.log(` ๐Ÿ’ฌ Daily Limit: ${(refreshedLicense.dailyLimit || 0) >= 999999 ? 'unlimited' : refreshedLicense.dailyLimit || 0} conversations`); console.log(` โœ… Status: ${refreshedLicense.valid ? 'Active' : 'Invalid'}`); if (refreshedLicense.features && refreshedLicense.features.length > 0) { console.log(` ๐Ÿ”“ Features: ${refreshedLicense.features.join(', ')}`); } console.log('\n๐Ÿ’ก Your license information has been updated successfully!'); console.log(' You can now use features from your current plan.\n'); } catch (error) { console.log(`โŒ Error refreshing license: ${error.message}`); console.log('๐Ÿ’ก Make sure you have a valid license con