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

319 lines 15.9 kB
/** * Unified Hive AI Tool * * Provides natural language interface to all Hive AI CLI capabilities * Examples: "hive update models", "hive run consensus on X", "hive check template health" */ import { z } from "zod"; export const UnifiedHiveToolSchema = z.object({ command: z.string().describe('Natural language command for Hive AI (e.g., "update models", "run consensus on my question", "check templates", "setup profiles")') }); export async function runUnifiedHiveTool(args) { const { command } = args; try { // Parse natural language command into structured action const parsedCommand = parseHiveCommand(command); if (!parsedCommand) { // Check if user might need help const { getContextualHelp } = await import('./help-system.js'); const contextualHelp = getContextualHelp(command); if (contextualHelp) { return { result: contextualHelp }; } return { result: `❌ Could not understand command: "${command}"\n\n` + `Try these:\n` + `• \`hive help\` - Quick start guide\n` + `• \`hive help consensus\` - Learn about consensus\n` + `• \`hive help commands\` - See all commands\n\n` + `**Popular commands:**\n` + `• "hive update models"\n` + `• "hive run consensus on 'your question'"\n` + `• "hive setup"\n` + `• "hive status"` }; } // Execute the parsed command return await executeHiveCommand(parsedCommand); } catch (error) { return { result: `❌ Error executing command: ${error instanceof Error ? error.message : 'Unknown error'}` }; } } function parseHiveCommand(command) { const cmd = command.toLowerCase().trim(); // Remove common prefixes const cleanCmd = cmd .replace(/^(hive|hive-ai|hiveai)\s+/i, '') .replace(/^(please\s+|can\s+you\s+|could\s+you\s+)/i, '') .trim(); // Model management commands if (cleanCmd.match(/^(update|sync|refresh)\s+(models?|model\s+data)/)) { return { action: 'update_models', originalCommand: command }; } if (cleanCmd.match(/^(list|show)\s+(models?|available\s+models?)/)) { const providerMatch = cleanCmd.match(/for\s+(\w+)|from\s+(\w+)|(\w+)\s+models?$/); const provider = providerMatch ? (providerMatch[1] || providerMatch[2] || providerMatch[3]) : undefined; return { action: 'list_models', params: provider ? { provider_name: provider } : {}, originalCommand: command }; } // Consensus commands if (cleanCmd.match(/^(run\s+consensus|consensus)\s+on\s+/)) { const questionMatch = command.match(/(?:run\s+consensus|consensus)\s+on\s+['"]?([^'"]+)['"]?/i); const question = questionMatch ? questionMatch[1].trim() : ''; return { action: 'consensus', params: { question }, originalCommand: command }; } // Setup commands if (cleanCmd.match(/^(setup|guided\s+setup|configure|initial\s+setup)/)) { return { action: 'setup', originalCommand: command }; } // Intelligent setup commands if (cleanCmd.match(/^(intelligent\s+setup|smart\s+setup|analyze\s+my\s+needs)/)) { return { action: 'intelligent_setup', originalCommand: command }; } // Profile management commands if (cleanCmd.match(/^(list|show)\s+(profiles?|pipeline\s+profiles?)/)) { return { action: 'list_profiles', originalCommand: command }; } if (cleanCmd.match(/^(set|use)\s+(default\s+)?profile/)) { const profileMatch = cleanCmd.match(/profile\s+(\w+)/); const profileName = profileMatch ? profileMatch[1] : ''; return { action: 'set_default_profile', params: { profile_name: profileName }, originalCommand: command }; } if (cleanCmd.match(/^(configure|create|setup)\s+(profile|new\s+profile)/)) { const nameMatch = cleanCmd.match(/(?:profile|new\s+profile)\s+(?:called\s+|named\s+)?(\w+)/); const profileName = nameMatch ? nameMatch[1] : ''; return { action: 'configure_profile', params: { command: profileName }, originalCommand: command }; } // Provider commands if (cleanCmd.match(/^(check|test|validate)\s+(providers?|api\s+keys?)/)) { return { action: 'test_providers', originalCommand: command }; } if (cleanCmd.match(/^(list|show)\s+providers?/)) { return { action: 'list_providers', originalCommand: command }; } // Template maintenance commands if (cleanCmd.match(/^(check|validate)\s+(templates?|template\s+health)/)) { return { action: 'check_templates', originalCommand: command }; } if (cleanCmd.match(/^(fix|repair|update)\s+templates?/)) { return { action: 'fix_templates', originalCommand: command }; } if (cleanCmd.match(/^(template\s+status|maintenance\s+status)/)) { return { action: 'template_status', originalCommand: command }; } // Status commands if (cleanCmd.match(/^(status|health|check\s+everything|system\s+status)/)) { return { action: 'system_status', originalCommand: command }; } // Help commands with topic support if (cleanCmd.match(/^(help|commands|what\s+can\s+you\s+do)/)) { const topicMatch = cleanCmd.match(/help\s+(?:with\s+)?(\w+)/); const topic = topicMatch ? topicMatch[1] : undefined; return { action: 'help', params: topic ? { topic } : {}, originalCommand: command }; } return null; } async function executeHiveCommand(parsed) { const { action, params = {}, originalCommand } = parsed; try { switch (action) { case 'update_models': const { runUpdateModelsTool } = await import('./model-selection.js'); return await runUpdateModelsTool(); case 'list_models': const { runListModelsTool } = await import('./model-selection.js'); return await runListModelsTool(params); case 'consensus': if (!params.question) { return { result: `❌ No question provided for consensus.\n\nExample: "hive run consensus on 'What is the best approach for microservices architecture?'"` }; } const { runConsensusPipeline, validateConsensusPrerequisites } = await import('../enhanced-consensus-engine.js'); // Validate prerequisites const validation = await validateConsensusPrerequisites(); if (!validation.valid) { return { result: `❌ Consensus prerequisites not met:\n${validation.errors.join('\n')}\n\nPlease run: "hive setup"` }; } // Generate conversation ID const { v4: uuidv4 } = await import('uuid'); const conversationId = uuidv4(); const result = await runConsensusPipeline(params.question, conversationId); return { result: `✅ **Consensus Result for:** "${params.question}"\n\n${result}` }; case 'setup': return { result: `🚀 **Guided Setup**\n\n` + `To run the interactive setup wizard, use the CLI directly:\n\n` + `\`\`\`bash\nnpx hive-ai setup\n\`\`\`\n\n` + `For intelligent recommendations based on your needs:\n` + `• "hive intelligent setup" - Smart setup with question analysis\n\n` + `Or configure individual components:\n` + `• "hive configure provider openrouter <api-key>"\n` + `• "hive list models" to see available models\n` + `• "hive configure profile <name>" to create profiles` }; case 'intelligent_setup': const { runIntelligentSetup } = await import('./intelligent-setup-wizard.js'); return await runIntelligentSetup({}); case 'list_profiles': const { runListPipelineProfilesTool } = await import('./pipeline-config.js'); return await runListPipelineProfilesTool(); case 'set_default_profile': if (!params.profile_name) { return { result: `❌ No profile name provided.\n\nExample: "hive set default profile Expert-Coding"` }; } const { runSetDefaultProfileTool } = await import('./pipeline-config.js'); return await runSetDefaultProfileTool({ profile_name: params.profile_name }); case 'configure_profile': const { runConfigurePipelineTool } = await import('./pipeline-config.js'); return await runConfigurePipelineTool({ command: params.command || '' }); case 'test_providers': const { runTestProvidersTool } = await import('./provider-config.js'); return await runTestProvidersTool(); case 'list_providers': const { runListProvidersTool } = await import('./provider-config.js'); return await runListProvidersTool(); case 'check_templates': const { runTemplateMaintenanceTool: checkTool } = await import('./template-maintenance-tool.js'); return await checkTool({ action: 'check', dry_run: false }); case 'fix_templates': const { runTemplateMaintenanceTool: fixTool } = await import('./template-maintenance-tool.js'); return await fixTool({ action: 'fix', dry_run: false }); case 'template_status': const { runTemplateMaintenanceTool: statusTool } = await import('./template-maintenance-tool.js'); return await statusTool({ action: 'status', dry_run: false }); case 'system_status': return await generateSystemStatus(); case 'help': const { runHelpTool } = await import('./help-system.js'); return await runHelpTool({ topic: params.topic, format: params.format || 'quick' }); default: return { result: `❌ Unknown action: ${action}\n\nOriginal command: "${originalCommand}"\n\nTry: "hive help" for available commands` }; } } catch (error) { return { result: `❌ Error executing "${action}": ${error instanceof Error ? error.message : 'Unknown error'}` }; } } export async function generateSystemStatus() { let result = `🔍 **Hive AI System Status**\n\n`; try { // Check provider configuration const { providerUtils } = await import('./provider-config.js'); const isConfigured = await providerUtils.isConfigured(); result += `**OpenRouter Configuration:** ${isConfigured ? '✅ Configured' : '❌ Not configured'}\n`; // Check model data const { getDatabase } = await import('../../storage/unified-database.js'); const database = await getDatabase(); const modelCount = await database.get('SELECT COUNT(*) as count FROM openrouter_models WHERE is_active = 1'); result += `**Model Database:** ${modelCount?.count || 0} active models\n`; // Check profiles const { getAllPipelineProfiles } = await import('../../storage/unified-database.js'); const profiles = await getAllPipelineProfiles(); result += `**Pipeline Profiles:** ${profiles.length} configured\n`; // Check template health const { TemplateMaintenanceManager } = await import('./template-maintenance.js'); const manager = new TemplateMaintenanceManager(); const reports = await manager.validateAllTemplates(); const healthyTemplates = reports.filter(r => r.isHealthy).length; result += `**Expert Templates:** ${healthyTemplates}/${reports.length} healthy\n\n`; // Check maintenance status const { getConfig } = await import('../../storage/unified-database.js'); const lastMaintenanceStr = await getConfig('last_template_maintenance'); if (lastMaintenanceStr) { const maintenanceData = JSON.parse(lastMaintenanceStr); const lastRun = new Date(maintenanceData.timestamp); result += `**Last Maintenance:** ${lastRun.toLocaleDateString()}\n`; } else { result += `**Last Maintenance:** Never run\n`; } // Provide next steps result += `\n**Quick Actions:**\n`; if (!isConfigured) { result += `• Configure OpenRouter: "hive configure provider"\n`; } if (!modelCount?.count || modelCount.count < 100) { result += `• Update models: "hive update models"\n`; } if (profiles.length === 0) { result += `• Setup profiles: "hive setup"\n`; } if (healthyTemplates < reports.length) { result += `• Fix templates: "hive fix templates"\n`; } return { result }; } catch (error) { return { result: `❌ Error checking system status: ${error instanceof Error ? error.message : 'Unknown error'}` }; } } async function generateHelpMessage() { return { result: `🤖 **Hive AI - Natural Language Commands**\n\n` + `**Model Management:**\n` + `• "hive update models" - Sync latest OpenRouter models\n` + `• "hive list models" - Show all available models\n` + `• "hive list openai models" - Show models from specific provider\n\n` + `**Consensus Pipeline:**\n` + `• "hive run consensus on 'your question'" - Execute 4-stage consensus\n` + `• "hive consensus on 'best practices for X'" - Alternative syntax\n\n` + `**Profile Management:**\n` + `• "hive list profiles" - Show configured pipeline profiles\n` + `• "hive set default profile Expert-Coding" - Set default profile\n` + `• "hive configure profile MyProfile" - Create/edit profile\n\n` + `**System Management:**\n` + `• "hive setup" - Launch guided setup wizard\n` + `• "hive status" - Check system health\n` + `• "hive test providers" - Validate API keys\n` + `• "hive check templates" - Validate template health\n` + `• "hive fix templates" - Apply template fixes\n\n` + `**Examples:**\n` + `• "hive update our models please"\n` + `• "hive run consensus on 'What are the pros and cons of microservices?'"\n` + `• "hive check if everything is working"\n` + `• "hive show me the available anthropic models"\n\n` + `**Pro Tip:** Use natural language! The system understands variations and conversational phrases.` }; } // Tool exports export const unifiedHiveToolName = 'hive'; export const unifiedHiveToolDescription = 'Natural language interface to all Hive AI capabilities - use conversational commands like "update models", "run consensus on X", "check system status"'; //# sourceMappingURL=unified-hive-tool.js.map