@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
698 lines (644 loc) • 29.8 kB
JavaScript
/**
* Knowledge Base Help System
*
* Intelligent help system that reads from installed documentation and provides
* AI-powered guidance on using Hive AI features optimally.
*/
import { z } from "zod";
import * as fs from 'fs';
import * as path from 'path';
export const KnowledgeBaseHelpSchema = z.object({
query: z.string().describe('User question about Hive AI features, usage, or optimization'),
context: z.enum(['cli', 'mcp', 'setup', 'advanced']).optional().describe('Context of the query'),
user_level: z.enum(['beginner', 'intermediate', 'expert']).optional().describe('User experience level')
});
export class KnowledgeBaseHelper {
documentation = [];
initialized = false;
constructor() {
this.initializeKnowledgeBase();
}
/**
* Initialize knowledge base from installed documentation
*/
async initializeKnowledgeBase() {
if (this.initialized)
return;
try {
// Find the npm package installation directory
const packagePaths = [
// Global npm installation
'/usr/local/lib/node_modules/@hivetechs/hive-ai',
'/opt/homebrew/lib/node_modules/@hivetechs/hive-ai',
// Local npm installation
'./node_modules/@hivetechs/hive-ai',
'../node_modules/@hivetechs/hive-ai',
// Current directory (for development)
'.'
];
let packageDir = '';
for (const testPath of packagePaths) {
if (fs.existsSync(testPath) && fs.existsSync(path.join(testPath, 'package.json'))) {
packageDir = testPath;
break;
}
}
if (!packageDir) {
console.warn('[KnowledgeBase] Could not find Hive AI package directory');
this.loadFallbackKnowledge();
return;
}
// Load documentation files
await this.loadDocumentationFiles(packageDir);
console.debug(`[KnowledgeBase] Loaded ${this.documentation.length} documentation sources`);
this.initialized = true;
}
catch (error) {
console.warn('[KnowledgeBase] Failed to initialize, using fallback knowledge:', error);
this.loadFallbackKnowledge();
}
}
/**
* Load documentation files from package directory
*/
async loadDocumentationFiles(packageDir) {
const docFiles = [
{ file: 'README.md', type: 'readme', priority: 10 },
{ file: 'SIMPLE_SETUP.md', type: 'guide', priority: 9 },
{ file: 'CLAUDE_CODE_INTEGRATION.md', type: 'integration', priority: 8 },
{ file: 'MCP_INTEGRATION_SUCCESS.md', type: 'integration', priority: 7 },
{ file: 'docs/MCP_IMPLEMENTATION_GUIDE.md', type: 'reference', priority: 6 }
];
for (const doc of docFiles) {
const filePath = path.join(packageDir, doc.file);
try {
if (fs.existsSync(filePath)) {
const content = fs.readFileSync(filePath, 'utf8');
this.documentation.push({
title: doc.file.replace('.md', '').replace('_', ' '),
content: content,
type: doc.type,
priority: doc.priority
});
}
}
catch (error) {
console.debug(`[KnowledgeBase] Could not load ${doc.file}:`, error);
}
}
}
/**
* Load fallback knowledge when documentation files aren't available
*/
loadFallbackKnowledge() {
this.documentation = [
{
title: 'Hive AI Core Features',
content: `
# Hive AI - Intelligent Consensus Platform
## Core Features:
- **4-Stage Consensus Pipeline**: Generator → Refiner → Validator → Curator
- **320+ AI Models**: Access to OpenRouter's complete model catalog
- **Intelligent Model Selection**: AUTO mode with question complexity analysis
- **Expert Profile Templates**: Pre-configured setups for different use cases
- **Cost Intelligence**: Budget optimization and cost prediction
- **Real-time Streaming**: Live output during consensus processing
## Key Intelligent Features:
- **Question Analysis**: Automatic complexity detection and categorization
- **Profile Matching**: Smart template selection based on question type
- **Budget Optimization**: Cost-aware model selection and routing
- **Template Maintenance**: Automatic model updates and health monitoring
`,
type: 'readme',
priority: 10
},
{
title: 'Expert Profile Templates',
content: `
# Expert Profile Templates
## Available Templates:
- **Expert-Coding**: Optimized for programming and development tasks
- **Complex-Coding**: Advanced algorithms and system architecture
- **Coding-Architecture**: System design and architectural decisions
- **Expert-Research**: Analysis, research, and fact-checking
- **Expert-Creative**: Creative writing and content generation
- **Expert-Fast**: Quick responses with speed optimization
- **Expert-Cheap**: Cost-effective analysis with budget constraints
## Intelligent Selection:
- AUTO mode automatically selects optimal templates based on question analysis
- Manual mode allows full control over profile selection
- Budget constraints influence template recommendations
`,
type: 'guide',
priority: 9
},
{
title: 'Infrastructure as Code (IAC)',
content: `
# Infrastructure as Code for Hive AI
## Overview:
Hive AI provides comprehensive Infrastructure-as-Code capabilities designed specifically for terminal developers who prefer scriptable, version-controlled configuration management.
## Key Features:
- **Script Templates**: Production-ready PowerShell and Bash scripts for automation
- **YAML Configuration**: Structured configuration files with environment variable substitution
- **Multi-Environment Support**: Separate configurations for dev/staging/production
- **CI/CD Integration**: Automation-friendly with validation, dry-run, and force modes
- **Version Control**: Store configurations in git for audit trails and collaboration
## Configuration Management:
- **Apply**: Deploy configuration files to the system
- **Validate**: Check configuration syntax and requirements before deployment
- **Diff**: Compare configuration files with current system settings
- **Export**: Create backups of current configurations
- **Template**: Generate example configurations for different use cases
## Environment Management:
- **Development**: Fast consensus, minimal requirements, debug features
- **Staging**: Production-like testing environment with monitoring
- **Production**: Elite models, full backup, comprehensive monitoring
## Automation Scripts:
**PowerShell (Windows/Cross-platform):**
- deploy-hive-config.ps1: Single environment deployment with logging and validation
- manage-hive-environments.ps1: Multi-environment management and health checks
**Bash (Linux/macOS):**
- deploy-hive-config.sh: Linux/macOS deployment with parallel execution
- manage-hive-environments.sh: Multi-environment automation for CI/CD pipelines
## Best Practices:
- Store configuration files in version control systems
- Use environment variables for sensitive information like API keys
- Validate configurations before applying to production environments
- Create backups before major configuration changes
- Implement proper CI/CD pipelines for automated deployments
`,
type: 'guide',
priority: 8
},
{
title: 'Configuration File Format',
content: `
# Hive AI Configuration File Format
## YAML Structure:
The configuration file uses YAML format with the following sections:
### Metadata:
- name: Human-readable configuration name
- description: Configuration description
- version: Configuration version for tracking changes
- environment: Target environment (development/staging/production)
### License:
- key: Hive AI license key (use environment variables for security)
### Providers:
- openrouter: OpenRouter API configuration with API key
### Consensus:
- profile: Consensus profile name (Consensus_Elite, Consensus_Balanced, etc.)
- max_agents: Maximum number of agents in consensus pipeline
### Backup (Optional):
- enabled: Enable/disable backup functionality
- locations: List of backup storage locations with priorities
## Environment Variable Substitution:
Use \${VARIABLE_NAME} syntax to substitute environment variables:
- license.key: "\${HIVE_LICENSE_KEY}"
- providers.openrouter.api_key: "\${OPENROUTER_API_KEY}"
## Example Configuration:
\`\`\`yaml
metadata:
name: "hive-ai-production"
environment: "production"
version: "1.0.0"
license:
key: "\${HIVE_LICENSE_KEY}"
providers:
openrouter:
api_key: "\${OPENROUTER_API_KEY}"
consensus:
profile: "Consensus_Elite"
max_agents: 8
backup:
enabled: true
locations:
- path: "/data/backups/hive"
priority: 1
free_space_gb: 100
\`\`\`
## Commands:
- hive config apply config.yaml: Apply configuration
- hive config validate config.yaml: Validate configuration
- hive config diff config.yaml: Show differences
- hive config export backup.yaml: Export current config
`,
type: 'reference',
priority: 7
},
{
title: 'MCP Tools Integration - Claude Code',
content: `
# MCP (Model Context Protocol) Tools - Claude Code Integration
## Overview:
Hive AI provides 18 comprehensive MCP tools for Claude Code users, enabling direct AI-powered operations without leaving your IDE.
## Available MCP Tools:
### Core System Tools (5):
- **hive_test**: Test MCP connectivity and verify Hive AI is working properly
- Usage: Test the connection with a simple echo message
- Example: "Use hive_test tool with message 'hello'"
- **hive_setup**: Quick setup for Hive AI (configure license and API key)
- Usage: Configure your Hive AI credentials
- Parameters: license_key, openrouter_api_key
- **hive_status**: Check Hive AI configuration status and system health
- Usage: View current configuration and health status
- No parameters required
- **hive_consensus**: Run 4-stage AI consensus on a question
- Usage: Get multi-model consensus on complex questions
- Parameters: question (required), profile (optional: Elite/Balanced/Speed/Cost)
- Example: "Use hive_consensus to analyze the best React patterns"
- **hive**: Ask Hive AI anything - natural language interface
- Usage: Direct questions to Hive AI
- Claude auto-uses this when you say "hive [question]"
- Example: "hive how do I optimize React performance?"
### Infrastructure as Code Tools (4):
- **hive_config_apply**: Apply a YAML or JSON configuration file
- Usage: Deploy configuration files to Hive AI
- Parameters: file_path (required), environment (optional)
- Perfect for GitOps and CI/CD workflows
- **hive_config_export**: Export current configuration as YAML/JSON
- Usage: Export configs for version control
- Parameters: format (yaml/json), include_credentials (boolean)
- **hive_config_validate**: Validate configuration files before applying
- Usage: Pre-deployment validation
- Parameters: file_path (required)
- **hive_config_template**: Generate configuration templates
- Usage: Create starter configs for different scenarios
- Parameters: type (basic/enterprise/development/ci-cd)
### Environment & Resource Management (3):
- **hive_environments**: Manage multiple environments (dev/staging/prod)
- Usage: Switch between different configurations
- Parameters: action (list/create/switch/delete/clone), environment_name
- Example: "Use hive_environments to switch to production"
- **hive_models**: Explore 320+ AI models from 55+ providers
- Usage: Search, compare, and benchmark models
- Parameters: action (list/search/info/benchmark/compare), query, provider
- Example: "Use hive_models to search for GPT-4 alternatives"
- **hive_templates**: Access expert templates for specialized tasks
- Usage: Use pre-configured templates for common scenarios
- Parameters: action (list/use/create/edit/delete), category, template_name
- Categories: coding, research, creative, business, analysis
### Analytics & Monitoring Tools (6):
- **hive_cost**: Monitor and optimize AI usage costs
- Usage: Track spending and set budget alerts
- Parameters: action (summary/breakdown/budget/optimize/forecast), timeframe
- Example: "Use hive_cost to show this month's spending"
- **hive_backup**: Create and manage configuration backups
- Usage: Protect your configurations and data
- Parameters: action (create/restore/list/delete/schedule), backup_name
- Example: "Use hive_backup to create a backup before deployment"
- **hive_health**: Monitor system health and API connectivity
- Usage: Check system status and diagnostics
- Parameters: action (check/detailed/history/alerts), component
- Components: api, database, models, all
- **hive_performance**: Analyze performance metrics
- Usage: Identify bottlenecks and optimize workflows
- Parameters: action (analyze/benchmark/compare/optimize/report), metric
- Metrics: speed, accuracy, cost, reliability
- **hive_reports**: Generate business intelligence reports
- Usage: Create executive dashboards and analytics
- Parameters: action (generate/schedule/export/dashboard), report_type, format
- Report types: usage, cost, performance, roi, executive
- **hive_intelligence**: Advanced AI capabilities
- Usage: Pattern recognition and predictive analytics
- Parameters: action (analyze/predict/optimize/insights/patterns), data_source, analysis_type
- Analysis types: trends, patterns, anomalies, predictions
## Using MCP Tools in Claude Code:
1. **Direct Tool Usage**: Type "/" in Claude Code to see all available tools
2. **Natural Language**: Just describe what you want, Claude will use the right tool
3. **Prefix Format**: Tools appear as "mcp__hive-ai__[tool_name]" in Claude Code
## Common Use Cases:
### DevOps & Infrastructure:
- "Apply my production config file using hive_config_apply"
- "Export current config for version control"
- "Switch to staging environment"
### Cost Optimization:
- "Show me this month's AI spending breakdown"
- "Set a budget alert for $100/month"
- "Analyze which models are most cost-effective"
### Performance Tuning:
- "Benchmark GPT-4 vs Claude for my use case"
- "Analyze performance bottlenecks in my workflow"
- "Generate a performance report for the team"
### Daily Operations:
- "Create a backup before making changes"
- "Check system health status"
- "Use the code review template for this PR"
## Tips for MCP Users:
1. **Auto-Updates**: MCP tools update automatically when you update the npm package
2. **Context Aware**: Claude understands your project context when using MCP tools
3. **Batch Operations**: Combine multiple tools for complex workflows
4. **Error Handling**: All tools provide clear error messages and suggestions
## Integration Benefits:
- No context switching - stay in Claude Code
- Direct access to all Hive AI features
- Automatic parameter validation
- Intelligent error handling and recovery
- Real-time results in your IDE
`,
type: 'integration',
priority: 10
}
];
this.initialized = true;
}
/**
* Generate intelligent help response
*/
async generateHelpResponse(query, context, userLevel) {
await this.initializeKnowledgeBase();
const relevantDocs = this.findRelevantDocumentation(query);
const intelligentFeatures = this.analyzeQueryForIntelligentFeatures(query);
let response = `🤖 **AI-Powered Help Response**\n\n`;
// Add query analysis
response += `**Query Analysis:**\n`;
response += `• Topic: ${this.categorizeQuery(query)}\n`;
response += `• Context: ${context || 'general'}\n`;
response += `• User Level: ${userLevel || 'intermediate'}\n\n`;
// Add intelligent feature recommendations
if (intelligentFeatures.length > 0) {
response += `**🧠 Intelligent Features for Your Query:**\n`;
intelligentFeatures.forEach(feature => {
response += `• **${feature.name}**: ${feature.description}\n`;
response += ` Command: \`${feature.command}\`\n\n`;
});
}
// Add relevant documentation excerpts
if (relevantDocs.length > 0) {
response += `**📚 Relevant Documentation:**\n\n`;
relevantDocs.slice(0, 2).forEach(doc => {
const excerpt = this.extractRelevantExcerpt(doc.content, query);
if (excerpt) {
response += `**From ${doc.title}:**\n`;
response += `${excerpt}\n\n`;
}
});
}
// Add smart recommendations based on query type
const recommendations = this.generateSmartRecommendations(query, userLevel);
if (recommendations.length > 0) {
response += `**💡 Smart Recommendations:**\n`;
recommendations.forEach(rec => {
response += `• ${rec}\n`;
});
response += '\n';
}
// Add learning path suggestions
const learningPath = this.generateLearningPath(query, userLevel);
if (learningPath.length > 0) {
response += `**📈 Suggested Learning Path:**\n`;
learningPath.forEach((step, index) => {
response += `${index + 1}. ${step}\n`;
});
response += '\n';
}
response += `**🔗 Related Commands:**\n`;
response += `• \`hive help [topic]\` - Get detailed help on specific topics\n`;
response += `• \`hive intelligent setup\` - Smart setup with personalized recommendations\n`;
response += `• \`hive status\` - Check system health and configuration\n`;
return response;
}
/**
* Find documentation relevant to the query
*/
findRelevantDocumentation(query) {
const queryLower = query.toLowerCase();
const keywords = queryLower.split(/\s+/);
return this.documentation
.map(doc => ({
...doc,
relevance: this.calculateRelevance(doc.content.toLowerCase(), keywords)
}))
.filter(doc => doc.relevance > 0)
.sort((a, b) => (b.relevance * b.priority) - (a.relevance * a.priority));
}
/**
* Calculate relevance score for documentation
*/
calculateRelevance(content, keywords) {
let score = 0;
keywords.forEach(keyword => {
if (keyword.length < 3)
return; // Skip short words
const matches = (content.match(new RegExp(keyword, 'g')) || []).length;
score += matches;
// Boost for header matches
if (content.includes(`# ${keyword}`) || content.includes(`## ${keyword}`)) {
score += 5;
}
});
return score;
}
/**
* Extract relevant excerpt from documentation
*/
extractRelevantExcerpt(content, query, maxLength = 300) {
const queryLower = query.toLowerCase();
const lines = content.split('\n');
// Find most relevant section
let bestScore = 0;
let bestSection = '';
let currentSection = '';
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.startsWith('#')) {
// Process previous section
if (currentSection) {
const score = this.calculateRelevance(currentSection.toLowerCase(), queryLower.split(/\s+/));
if (score > bestScore) {
bestScore = score;
bestSection = currentSection;
}
}
currentSection = line + '\n';
}
else {
currentSection += line + '\n';
}
}
// Process last section
if (currentSection) {
const score = this.calculateRelevance(currentSection.toLowerCase(), queryLower.split(/\s+/));
if (score > bestScore) {
bestSection = currentSection;
}
}
// Truncate if too long
if (bestSection.length > maxLength) {
bestSection = bestSection.substring(0, maxLength) + '...';
}
return bestSection.trim();
}
/**
* Analyze query for intelligent features
*/
analyzeQueryForIntelligentFeatures(query) {
const queryLower = query.toLowerCase();
const features = [];
if (queryLower.includes('setup') || queryLower.includes('getting started') || queryLower.includes('configure')) {
features.push({
name: 'Intelligent Setup',
description: 'Personalized setup with question analysis and template recommendations',
command: 'hive intelligent setup'
});
}
if (queryLower.includes('cost') || queryLower.includes('budget') || queryLower.includes('price')) {
features.push({
name: 'Cost Intelligence',
description: 'Estimate costs and set budget limits for optimal spending',
command: 'hive cost estimate "your question"'
});
}
if (queryLower.includes('auto') || queryLower.includes('automatic') || queryLower.includes('smart')) {
features.push({
name: 'AUTO Mode',
description: 'Intelligent model selection based on question complexity',
command: 'hive mode auto'
});
}
if (queryLower.includes('template') || queryLower.includes('profile') || queryLower.includes('preset')) {
features.push({
name: 'Expert Templates',
description: 'Pre-configured profiles optimized for specific use cases',
command: 'hive templates list'
});
}
if (queryLower.includes('config') || queryLower.includes('iac') || queryLower.includes('infrastructure') || queryLower.includes('automation')) {
features.push({
name: 'Infrastructure as Code',
description: 'Scriptable configuration management with YAML files and automation scripts',
command: 'hive config apply config.yaml'
});
}
if (queryLower.includes('environment') || queryLower.includes('deploy') || queryLower.includes('devops')) {
features.push({
name: 'Environment Management',
description: 'Multi-environment support with dev/staging/production configurations',
command: 'hive config environments list'
});
}
if (queryLower.includes('script') || queryLower.includes('powershell') || queryLower.includes('bash')) {
features.push({
name: 'Automation Scripts',
description: 'PowerShell and Bash script templates for deployment automation',
command: 'hive config environments templates'
});
}
return features;
}
/**
* Categorize the user query
*/
categorizeQuery(query) {
const queryLower = query.toLowerCase();
if (queryLower.includes('setup') || queryLower.includes('install') || queryLower.includes('configure')) {
return 'Setup & Configuration';
}
else if (queryLower.includes('consensus') || queryLower.includes('question') || queryLower.includes('ask')) {
return 'Consensus Pipeline';
}
else if (queryLower.includes('cost') || queryLower.includes('budget') || queryLower.includes('price')) {
return 'Cost Management';
}
else if (queryLower.includes('template') || queryLower.includes('profile')) {
return 'Profile Management';
}
else if (queryLower.includes('model') || queryLower.includes('ai') || queryLower.includes('openrouter')) {
return 'Model Management';
}
else if (queryLower.includes('claude') || queryLower.includes('mcp')) {
return 'Claude Code Integration';
}
else if (queryLower.includes('config') || queryLower.includes('iac') || queryLower.includes('infrastructure') || queryLower.includes('yaml')) {
return 'Infrastructure as Code';
}
else if (queryLower.includes('environment') || queryLower.includes('deploy') || queryLower.includes('devops') || queryLower.includes('automation')) {
return 'Environment Management';
}
else if (queryLower.includes('script') || queryLower.includes('powershell') || queryLower.includes('bash')) {
return 'Automation Scripts';
}
else {
return 'General Usage';
}
}
/**
* Generate smart recommendations based on query
*/
generateSmartRecommendations(query, userLevel) {
const recommendations = [];
const queryLower = query.toLowerCase();
if (userLevel === 'beginner') {
recommendations.push('Start with `hive setup` for guided configuration');
recommendations.push('Use AUTO mode for intelligent model selection');
}
if (queryLower.includes('cost') || queryLower.includes('budget')) {
recommendations.push('Set a budget limit with `hive cost settings [amount]`');
recommendations.push('Use Expert-Fast or Expert-Cheap templates for cost optimization');
}
if (queryLower.includes('coding') || queryLower.includes('programming')) {
recommendations.push('Try Expert-Coding or Complex-Coding templates');
recommendations.push('Use AUTO mode to automatically detect code complexity');
}
if (queryLower.includes('template') || queryLower.includes('profile')) {
recommendations.push('Let AUTO mode select profiles automatically based on your questions');
recommendations.push('Use `hive intelligent setup` for personalized recommendations');
}
if (queryLower.includes('config') || queryLower.includes('iac') || queryLower.includes('infrastructure')) {
recommendations.push('Start with configuration templates: `hive config template`');
recommendations.push('Use environment variables for secrets in YAML files');
recommendations.push('Store configurations in version control for team collaboration');
}
if (queryLower.includes('environment') || queryLower.includes('deploy') || queryLower.includes('devops')) {
recommendations.push('Use the provided PowerShell/Bash script templates for automation');
recommendations.push('Set up separate configurations for dev/staging/production');
recommendations.push('Validate configurations before deploying: `hive config validate`');
}
if (queryLower.includes('script') || queryLower.includes('automation')) {
recommendations.push('Check templates/README.md for complete automation guide');
recommendations.push('Use dry-run mode to test deployments safely');
recommendations.push('Implement CI/CD pipelines with the provided script examples');
}
return recommendations;
}
/**
* Generate learning path based on query and user level
*/
generateLearningPath(query, userLevel) {
const path = [];
const queryLower = query.toLowerCase();
if (userLevel === 'beginner') {
path.push('Complete initial setup with `hive setup`');
path.push('Try a simple consensus question');
path.push('Explore Expert Profile Templates');
path.push('Learn about AUTO vs MANUAL modes');
}
else if (userLevel === 'expert') {
path.push('Explore advanced profile customization');
path.push('Set up budget optimization strategies');
path.push('Use template maintenance for long-term reliability');
}
if (queryLower.includes('cost')) {
path.push('Understand cost estimation with `hive cost estimate`');
path.push('Configure budget limits for automatic optimization');
}
return path;
}
}
export async function runKnowledgeBaseHelp(args) {
const { query, context, user_level } = args;
try {
const helper = new KnowledgeBaseHelper();
const response = await helper.generateHelpResponse(query, context, user_level);
return { result: response };
}
catch (error) {
return {
result: `❌ Error generating AI help response: ${error instanceof Error ? error.message : 'Unknown error'}`
};
}
}
// Tool exports
export const knowledgeBaseHelpToolName = 'hive_knowledge_help';
export const knowledgeBaseHelpToolDescription = 'AI-powered help system that reads installed documentation and provides intelligent guidance on Hive AI features and optimization';
//# sourceMappingURL=knowledge-base-help.js.map