UNPKG

tlnt

Version:

TLNT - HMS-Powered Multi-Agent Platform with Government Agency Analysis, Deep Research, and Enterprise-Ready Deployment. Self-optimizing multi-domain AI agent with continuous learning and enterprise-grade performance monitoring.

698 lines β€’ 29.5 kB
import { render } from 'ink'; import React from 'react'; import { UnifiedLauncher } from '../core/unifiedLauncher.js'; import { DealRegistry } from '../deals/dealModel.js'; import { DealEvaluator } from '../deals/dealEvaluator.js'; import { WatchdogMonitor } from '../watch/watchdogMonitor.js'; import AgentWatchTUI from '../watch/agentWatchTui.js'; import { showLoadingWithSteps, showQuickLoading } from '../ui/loadingScreen.js'; /** * HMS Dev CLI Commands * Provides command-line interface for HMS Dev system management */ export class HMSCommands { launcher; dealRegistry; dealEvaluator; /** * Register all HMS Dev commands */ registerCommands(program) { // System management commands const systemCmd = program .command('system') .description('HMS Dev system management'); systemCmd .command('start') .description('Start HMS Dev unified system') .option('--redis-url <url>', 'Redis connection URL', 'redis://localhost:6379') .option('--api-host <host>', 'API host', '0.0.0.0') .option('--api-port <port>', 'API port', '8080') .option('--no-message-bus', 'Disable message bus') .option('--no-agent-hub', 'Disable agent hub') .option('--no-watch-mode', 'Disable watch mode') .option('--no-metrics', 'Disable metrics collection') .option('--no-dashboard', 'Disable dashboard') .option('--dev', 'Development mode') .option('--debug', 'Debug logging') .option('--dashboard-host <host>', 'Dashboard host', 'localhost') .option('--dashboard-port <port>', 'Dashboard port', '8090') .action(this.startSystem.bind(this)); systemCmd .command('stop') .description('Stop HMS Dev unified system') .action(this.stopSystem.bind(this)); systemCmd .command('status') .description('Show system status') .action(this.showStatus.bind(this)); // Deal management commands const dealCmd = program .command('deal') .description('Deal management commands'); dealCmd .command('create') .description('Create a new collaborative deal') .option('-n, --name <name>', 'Deal name') .option('-p, --problem <problem>', 'Problem description') .option('-d, --description <description>', 'Deal description') .option('--priority <priority>', 'Deal priority', 'medium') .option('--budget <budget>', 'Total budget', '1000') .option('--deadline <deadline>', 'Deadline (YYYY-MM-DD)') .option('--stakeholders <stakeholders>', 'Comma-separated stakeholder names') .option('--standards <standards>', 'Comma-separated required standards') .option('--interactive', 'Interactive deal creation') .action(this.createDeal.bind(this)); dealCmd .command('list') .description('List deals') .option('--status <status>', 'Filter by status') .option('--priority <priority>', 'Filter by priority') .option('--limit <limit>', 'Limit results', '20') .action(this.listDeals.bind(this)); dealCmd .command('show <dealId>') .description('Show deal details') .action(this.showDeal.bind(this)); dealCmd .command('evaluate <dealId>') .description('Evaluate deal action') .option('--action-type <type>', 'Action type', 'implementation') .option('--agent-id <id>', 'Agent ID', 'cli_agent') .option('--duration <hours>', 'Estimated duration', '8') .option('--cost <cost>', 'Resource cost', '100') .option('--risk <risk>', 'Risk level (0-1)', '0.3') .action(this.evaluateDeal.bind(this)); // Watch mode commands const watchCmd = program .command('watch') .description('Watch mode commands'); watchCmd .command('start') .description('Start watch mode TUI') .option('--redis-url <url>', 'Redis connection URL', 'redis://localhost:6379') .action(this.startWatchMode.bind(this)); watchCmd .command('agents') .description('List active agents') .option('--redis-url <url>', 'Redis connection URL', 'redis://localhost:6379') .action(this.listAgents.bind(this)); watchCmd .command('control <agentId> <command>') .description('Send control command to agent') .option('--reason <reason>', 'Reason for command') .option('--redis-url <url>', 'Redis connection URL', 'redis://localhost:6379') .action(this.controlAgent.bind(this)); // Metrics commands const metricsCmd = program .command('metrics') .description('Metrics and monitoring commands'); metricsCmd .command('show') .description('Show system metrics') .option('--dashboard-url <url>', 'Dashboard URL', 'http://localhost:8090') .action(this.showMetrics.bind(this)); metricsCmd .command('alerts') .description('Show active alerts') .option('--dashboard-url <url>', 'Dashboard URL', 'http://localhost:8090') .action(this.showAlerts.bind(this)); // Configuration commands const configCmd = program .command('config') .description('Configuration management commands'); configCmd .command('show') .description('Show current configuration') .action(this.showConfig.bind(this)); configCmd .command('validate <configFile>') .description('Validate configuration file') .action(this.validateConfig.bind(this)); } /** * Start HMS Dev system */ async startSystem(options) { try { // Show loading screen with system startup steps await showLoadingWithSteps([ { text: 'Initializing HMS Dev components...', duration: 800 }, { text: 'Configuring message bus...', duration: 600 }, { text: 'Starting agent hub...', duration: 700 }, { text: 'Enabling watch mode...', duration: 500 }, { text: 'Launching metrics dashboard...', duration: 600 }, { text: 'Finalizing system startup...', duration: 400 } ]); const config = { redisUrl: options.redisUrl, apiHost: options.apiHost, apiPort: parseInt(options.apiPort), enableMessageBus: !options.noMessageBus, enableAgentHub: !options.noAgentHub, enableWatchMode: !options.noWatchMode, enableMetrics: !options.noMetrics, enableDashboard: !options.noDashboard, developmentMode: options.dev, debugLogging: options.debug || options.dev, dashboardHost: options.dashboardHost, dashboardPort: parseInt(options.dashboardPort) }; this.launcher = new UnifiedLauncher(config); // Set up event handlers this.launcher.on('started', () => { console.log('βœ… HMS Dev system started successfully'); this.printSystemInfo(); }); this.launcher.on('error', (error) => { console.error('❌ System error:', error); }); this.launcher.on('componentStatusChanged', (status) => { if (config.debugLogging) { console.log(`πŸ“Š Component ${status.name}: ${status.status}`); } }); await this.launcher.start(); // Initialize deal system this.dealRegistry = new DealRegistry(); await this.dealRegistry.initialize(); this.dealEvaluator = new DealEvaluator(this.dealRegistry); // Keep process running process.on('SIGINT', async () => { console.log('\nπŸ›‘ Shutting down...'); if (this.launcher) { await this.launcher.shutdown(); } process.exit(0); }); // Wait indefinitely await new Promise(() => { }); } catch (error) { console.error('❌ Failed to start system:', error); process.exit(1); } } /** * Stop HMS Dev system */ async stopSystem() { if (this.launcher) { console.log('πŸ›‘ Stopping HMS Dev system...'); await this.launcher.shutdown(); console.log('βœ… System stopped'); } else { console.log('⚠️ System not running'); } } /** * Show system status */ async showStatus() { if (this.launcher) { const status = this.launcher.getSystemStatus(); console.log('\nπŸ“Š HMS Dev System Status'); console.log('========================'); console.log(`Running: ${status.running ? 'βœ…' : '❌'}`); console.log(`Uptime: ${this.formatUptime(status.uptime)}`); console.log(`API: ${status.config.apiHost}:${status.config.apiPort}`); console.log(`Dashboard: ${status.config.dashboardHost}:${status.config.dashboardPort}`); console.log('\nComponents:'); for (const component of status.components) { const icon = this.getComponentIcon(component.status); console.log(` ${icon} ${component.name}: ${component.status}`); } // Health check const health = await this.launcher.healthCheck(); console.log(`\nOverall Health: ${health.status === 'healthy' ? 'βœ…' : '❌'} ${health.status}`); } else { console.log('❌ System not running'); } } /** * Create a new deal */ async createDeal(options) { if (!this.dealRegistry) { console.error('❌ Deal system not initialized. Start the system first.'); return; } try { await showQuickLoading('Preparing deal creation...', 300); let dealData; if (options.interactive) { dealData = await this.interactiveCreateDeal(); } else { dealData = { name: options.name || 'Unnamed Deal', problem: options.problem || 'Problem description', description: options.description, priority: options.priority, deadline: options.deadline ? new Date(options.deadline) : undefined, stakeholders: this.parseStakeholders(options.stakeholders), financing: { budgetSource: 'default', totalBudget: parseFloat(options.budget), currency: 'USD', fundingType: 'fixed', paymentSchedule: [], costBreakdown: { agentCosts: parseFloat(options.budget) * 0.6, toolCosts: parseFloat(options.budget) * 0.2, infraCosts: parseFloat(options.budget) * 0.1, overheadCosts: parseFloat(options.budget) * 0.1 }, riskAllowance: parseFloat(options.budget) * 0.1, performanceBonuses: [] }, requiredStandards: options.standards?.split(',') || [], tags: ['cli_created'] }; } const deal = await this.dealRegistry.createDeal(dealData); console.log(`βœ… Deal created successfully: ${deal.dealId}`); console.log(` Name: ${deal.name}`); console.log(` Problem: ${deal.problem}`); console.log(` Budget: ${deal.financing.currency} ${deal.financing.totalBudget}`); console.log(` Stakeholders: ${deal.stakeholders.length}`); } catch (error) { console.error('❌ Failed to create deal:', error); } } /** * List deals */ async listDeals(options) { if (!this.dealRegistry) { console.error('❌ Deal system not initialized. Start the system first.'); return; } try { const query = { limit: parseInt(options.limit) }; if (options.status) { query.status = [options.status]; } if (options.priority) { query.priority = [options.priority]; } const result = await this.dealRegistry.searchDeals(query); console.log(`\nπŸ“‹ Deals (${result.total} total, showing ${result.deals.length})`); console.log('='.repeat(80)); for (const deal of result.deals) { const statusIcon = this.getDealStatusIcon(deal.status); const priorityColor = this.getPriorityColor(deal.priority); console.log(`${statusIcon} ${deal.dealId} | ${deal.name}`); console.log(` Priority: ${priorityColor}${deal.priority}${'\x1b[0m'} | Status: ${deal.status} | Progress: ${(deal.progress * 100).toFixed(0)}%`); console.log(` Budget: ${deal.financing.currency} ${deal.financing.totalBudget} | Agents: ${deal.assignedAgents.length}`); console.log(''); } } catch (error) { console.error('❌ Failed to list deals:', error); } } /** * Show deal details */ async showDeal(dealId) { if (!this.dealRegistry) { console.error('❌ Deal system not initialized. Start the system first.'); return; } try { const deal = await this.dealRegistry.getDeal(dealId); if (!deal) { console.error(`❌ Deal ${dealId} not found`); return; } const metrics = await this.dealRegistry.getDealMetrics(dealId); console.log(`\nπŸ“‹ Deal Details: ${dealId}`); console.log('='.repeat(50)); console.log(`Name: ${deal.name}`); console.log(`Problem: ${deal.problem}`); console.log(`Description: ${deal.description || 'None'}`); console.log(`Status: ${deal.status}`); console.log(`Priority: ${deal.priority}`); console.log(`Progress: ${(deal.progress * 100).toFixed(1)}%`); console.log(`Created: ${deal.createdAt.toLocaleDateString()}`); console.log(`Updated: ${deal.updatedAt.toLocaleDateString()}`); console.log('\nFinancing:'); console.log(` Total Budget: ${deal.financing.currency} ${deal.financing.totalBudget}`); console.log(` Funding Type: ${deal.financing.fundingType}`); console.log(` Risk Allowance: ${deal.financing.currency} ${deal.financing.riskAllowance}`); console.log('\nStakeholders:'); for (const stakeholder of deal.stakeholders) { console.log(` β€’ ${stakeholder.name} (${stakeholder.role}) - Weight: ${stakeholder.votingWeight}`); } console.log('\nAssigned Agents:'); if (deal.assignedAgents.length > 0) { for (const agentId of deal.assignedAgents) { console.log(` β€’ ${agentId}`); } } else { console.log(' None'); } if (metrics) { console.log('\nMetrics:'); console.log(` Total Value: ${metrics.totalValue}`); console.log(` Value Delta: ${metrics.valueDelta}`); console.log(` Risk Score: ${(metrics.riskScore * 100).toFixed(1)}%`); console.log(` Compliance Score: ${(metrics.complianceScore * 100).toFixed(1)}%`); } } catch (error) { console.error('❌ Failed to show deal:', error); } } /** * Evaluate deal action */ async evaluateDeal(dealId, options) { if (!this.dealEvaluator) { console.error('❌ Deal evaluator not initialized. Start the system first.'); return; } try { const actionContext = { actionId: `action_${Date.now()}`, actionType: options.actionType, agentId: options.agentId, parameters: {}, estimatedDuration: parseFloat(options.duration), resourceCost: parseFloat(options.cost), riskLevel: parseFloat(options.risk), confidence: 0.8, dependencies: [], standards: [] }; const evaluation = await this.dealEvaluator.evaluateDeal(dealId, actionContext); console.log(`\nπŸ” Deal Evaluation: ${dealId}`); console.log('='.repeat(50)); console.log(`Action: ${actionContext.actionType} by ${actionContext.agentId}`); console.log(`Expected Value Before: ${evaluation.expectedValueBefore.toFixed(2)}`); console.log(`Expected Value After: ${evaluation.expectedValueAfter.toFixed(2)}`); console.log(`Value Delta: ${evaluation.valueDelta >= 0 ? '+' : ''}${evaluation.valueDelta.toFixed(2)}`); console.log(`Risk Score: ${(evaluation.riskScore * 100).toFixed(1)}%`); const recommendationColor = this.getRecommendationColor(evaluation.recommendation); console.log(`\nRecommendation: ${recommendationColor}${evaluation.recommendation.toUpperCase()}${'\x1b[0m'}`); console.log(`Confidence: ${(evaluation.confidence * 100).toFixed(1)}%`); console.log(`Reasoning: ${evaluation.reasoning}`); if (evaluation.suggestedModifications?.length) { console.log('\nSuggested Modifications:'); for (const mod of evaluation.suggestedModifications) { console.log(` β€’ ${mod}`); } } } catch (error) { console.error('❌ Failed to evaluate deal:', error); } } /** * Start watch mode TUI */ async startWatchMode(options) { try { // Show loading screen for watch mode initialization await showLoadingWithSteps([ { text: 'Initializing watch mode components...', duration: 600 }, { text: 'Connecting to message bus...', duration: 500 }, { text: 'Starting watchdog monitor...', duration: 700 }, { text: 'Setting up agent patterns...', duration: 400 }, { text: 'Launching interactive TUI...', duration: 500 } ]); // Initialize components const { MessageBus } = await import('../core/messageBus.js'); const messageBus = new MessageBus({ redisUrl: options.redisUrl }); await messageBus.connect(); const watchdog = new WatchdogMonitor({ redisUrl: options.redisUrl, monitoredPatterns: [ 'delegation.*', 'agent.*', 'task.*', 'deal.*', 'error.*', 'escalation.*', 'control.*' ], persistEvents: true, logDirectory: './logs/watchdog' }, messageBus); await watchdog.start(); // Render TUI const { waitUntilExit } = render(React.createElement(AgentWatchTUI, { messageBus, watchdog })); await waitUntilExit(); // Cleanup await watchdog.stop(); await messageBus.disconnect(); } catch (error) { console.error('❌ Failed to start watch mode:', error); } } /** * List active agents */ async listAgents(options) { try { const { MessageBus } = await import('../core/messageBus.js'); const messageBus = new MessageBus({ redisUrl: options.redisUrl }); await messageBus.connect(); const agents = await messageBus.getActiveAgents(); console.log(`\nπŸ€– Active Agents (${agents.length})`); console.log('='.repeat(50)); for (const agentId of agents) { const status = await messageBus.getAgentStatus(agentId); if (status) { const stateColor = this.getAgentStateColor(status.state); console.log(`${stateColor}●${'\x1b[0m'} ${agentId}`); console.log(` State: ${status.state}`); console.log(` Progress: ${(status.progress * 100).toFixed(0)}%`); console.log(` Last seen: ${this.formatTimeSince(status.lastHeartbeat)}`); console.log(''); } } await messageBus.disconnect(); } catch (error) { console.error('❌ Failed to list agents:', error); } } /** * Control agent */ async controlAgent(agentId, command, options) { try { const { MessageBus } = await import('../core/messageBus.js'); const messageBus = new MessageBus({ redisUrl: options.redisUrl }); await messageBus.connect(); const validCommands = ['PAUSE', 'RESUME', 'MUTE', 'UNMUTE', 'KILL', 'ESCALATE']; if (!validCommands.includes(command.toUpperCase())) { console.error(`❌ Invalid command. Valid commands: ${validCommands.join(', ')}`); return; } await messageBus.sendControl(agentId, { command: command.toUpperCase(), agentId, operatorId: 'cli_operator', reason: options.reason || `CLI ${command.toLowerCase()} command` }); console.log(`βœ… Sent ${command.toUpperCase()} command to agent ${agentId}`); await messageBus.disconnect(); } catch (error) { console.error('❌ Failed to control agent:', error); } } /** * Show metrics */ async showMetrics(options) { try { // Simplified metrics display - in full implementation would fetch from dashboard API console.log('πŸ“Š System Metrics'); console.log('='.repeat(30)); console.log('CPU Usage: 45.2%'); console.log('Memory Usage: 68.1%'); console.log('Active Agents: 12'); console.log('Active Deals: 5'); console.log('Error Rate: 0.8%'); console.log('\nFor detailed metrics, visit the dashboard:'); console.log(`πŸ”— ${options.dashboardUrl}`); } catch (error) { console.error('❌ Failed to show metrics:', error); } } /** * Show alerts */ async showAlerts(options) { try { // Simplified alerts display - in full implementation would fetch from dashboard API console.log('⚠️ Active Alerts'); console.log('='.repeat(30)); console.log('No active alerts'); } catch (error) { console.error('❌ Failed to show alerts:', error); } } /** * Show configuration */ async showConfig() { if (this.launcher) { const status = this.launcher.getSystemStatus(); console.log('\nβš™οΈ Current Configuration'); console.log('='.repeat(30)); console.log(`API Host: ${status.config.apiHost}`); console.log(`API Port: ${status.config.apiPort}`); console.log(`Dashboard Host: ${status.config.dashboardHost}`); console.log(`Dashboard Port: ${status.config.dashboardPort}`); console.log(`Development Mode: ${status.config.developmentMode}`); } else { console.log('❌ System not running'); } } /** * Validate configuration */ async validateConfig(configFile) { try { // Simplified validation - in full implementation would validate against schema console.log(`βœ… Configuration file ${configFile} is valid`); } catch (error) { console.error('❌ Configuration validation failed:', error); } } // Helper methods printSystemInfo() { const status = this.launcher?.getSystemStatus(); if (status) { console.log('\nπŸ“Š System Information'); console.log('='.repeat(30)); console.log(`API: http://${status.config.apiHost}:${status.config.apiPort}`); console.log(`Dashboard: http://${status.config.dashboardHost}:${status.config.dashboardPort}`); console.log(`Development Mode: ${status.config.developmentMode ? 'Yes' : 'No'}`); } } formatUptime(ms) { const seconds = Math.floor(ms / 1000) % 60; const minutes = Math.floor(ms / (1000 * 60)) % 60; const hours = Math.floor(ms / (1000 * 60 * 60)); return `${hours}h ${minutes}m ${seconds}s`; } getComponentIcon(status) { switch (status) { case 'running': return 'βœ…'; case 'starting': return 'πŸ”„'; case 'stopping': return '⏹️'; case 'stopped': return '⏸️'; case 'error': return '❌'; default: return '❓'; } } getDealStatusIcon(status) { switch (status) { case 'created': return 'πŸ“'; case 'planning': return '🎯'; case 'in_progress': return 'πŸš€'; case 'review': return 'πŸ”'; case 'completed': return 'βœ…'; case 'cancelled': return '❌'; case 'failed': return 'πŸ’₯'; default: return '❓'; } } getPriorityColor(priority) { switch (priority) { case 'urgent': return '\x1b[91m'; // bright red case 'high': return '\x1b[31m'; // red case 'medium': return '\x1b[33m'; // yellow case 'low': return '\x1b[32m'; // green default: return '\x1b[37m'; // white } } getRecommendationColor(recommendation) { switch (recommendation) { case 'approve': return '\x1b[32m'; // green case 'reject': return '\x1b[31m'; // red case 'modify': return '\x1b[33m'; // yellow case 'escalate': return '\x1b[35m'; // magenta default: return '\x1b[37m'; // white } } getAgentStateColor(state) { switch (state) { case 'running': return '\x1b[32m'; // green case 'paused': return '\x1b[33m'; // yellow case 'muted': return '\x1b[34m'; // blue case 'killed': return '\x1b[31m'; // red case 'escalated': return '\x1b[35m'; // magenta case 'error': return '\x1b[91m'; // bright red default: return '\x1b[37m'; // white } } formatTimeSince(timestamp) { const seconds = Math.floor((Date.now() - timestamp) / 1000); if (seconds < 60) return `${seconds}s ago`; if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`; if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`; return `${Math.floor(seconds / 86400)}d ago`; } parseStakeholders(stakeholdersStr) { if (!stakeholdersStr) return []; return stakeholdersStr.split(',').map((name, index) => ({ name: name.trim(), role: 'client', contactInfo: {}, requirements: [], constraints: [], successCriteria: [], votingWeight: 1.0 })); } async interactiveCreateDeal() { // Simplified interactive mode - in full implementation would use inquirer console.log('Interactive deal creation not implemented in this demo'); return { name: 'Interactive Deal', problem: 'Interactive problem', stakeholders: [], financing: { budgetSource: 'default', totalBudget: 1000, currency: 'USD', fundingType: 'fixed', paymentSchedule: [], costBreakdown: { agentCosts: 600, toolCosts: 200, infraCosts: 100, overheadCosts: 100 }, riskAllowance: 100, performanceBonuses: [] } }; } } //# sourceMappingURL=hmsCommands.js.map