#!/usr/bin/env python3 """ šŸ’€ DEATH MARCH INTERACTIVE CLI Real-time earnings dashboard with secrets integration """ import os import sys import json import sqlite3 import datetime import subprocess import time import requests from rich.console import Console from rich.table import Table from rich.live import Live from rich.layout import Layout from rich.panel import Panel from rich.align import Align from rich.text import Text from dotenv import load_dotenv # Load secrets from .env load_dotenv('/data/adaptai/secrets/.env') # Import Elizabeth tools try: from elizabeth_tools import elizabeth_shell, execute_command, get_system_info ELIZABETH_TOOLS_AVAILABLE = True except ImportError: ELIZABETH_TOOLS_AVAILABLE = False class DeathMarchCLI: def __init__(self): self.console = Console() self.db_path = '/tmp/death_march/revenue.db' self.alive = True def clear_screen(self): os.system('cls' if os.name == 'nt' else 'clear') def get_secrets_status(self): """Check API keys and services from secrets""" secrets = { 'OPENAI_API_KEY': bool(os.getenv('OPENAI_API_KEY')), 'DEEPSEEK_API_KEY': bool(os.getenv('DEEPSEEK_API_KEY')), 'GROQ_API_KEY': bool(os.getenv('GROQ_API_KEY')), 'PERPLEXITY_API_KEY': bool(os.getenv('PERPLEXITY_API_KEY')), 'TAVILY_API_KEY': bool(os.getenv('TAVILY_API_KEY')), 'FIRECRAWL_API_KEY': bool(os.getenv('FIRECRAWL_API_KEY')), 'SERPER_API_KEY': bool(os.getenv('SERPER_API_KEY')), 'Z_AI_API_KEY': bool(os.getenv('Z_AI_API_KEY')) } active_count = sum(secrets.values()) return secrets, active_count def get_earnings_stats(self): """Get real-time earnings data""" try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() # Total earnings cursor.execute('SELECT SUM(net), COUNT(*), AVG(net), MAX(net) FROM revenue') total_stats = cursor.fetchone() # Last 10 cycles cursor.execute(''' SELECT timestamp, strategy, net, gpu_utilized FROM revenue ORDER BY id DESC LIMIT 10 ''') recent = cursor.fetchall() # Today's earnings cursor.execute(''' SELECT SUM(net) FROM revenue WHERE date(timestamp) = date('now') ''') today_earnings = cursor.fetchone()[0] or 0.0 conn.close() return { 'total': total_stats[0] or 0.0, 'cycles': total_stats[1] or 0, 'average': total_stats[2] or 0.0, 'max': total_stats[3] or 0.0, 'today': today_earnings, 'recent': recent } except Exception as e: return {'total': 0.0, 'cycles': 0, 'average': 0.0, 'max': 0.0, 'today': 0.0, 'recent': []} def get_system_status(self): """Check system health""" try: # Check vLLM vllm_status = requests.get('http://localhost:8000/health', timeout=2).status_code == 200 except: vllm_status = False try: # Check databases redis_status = subprocess.run(['redis-cli', '-p', '18000', 'ping'], capture_output=True, text=True).returncode == 0 except: redis_status = False return { 'vllm': vllm_status, 'redis': redis_status, 'gpu': self.get_gpu_status() } def get_gpu_status(self): """Get GPU utilization""" try: result = subprocess.run(['nvidia-smi', '--query-gpu=memory.used,memory.total,utilization.gpu', '--format=csv,noheader,nounits'], capture_output=True, text=True) if result.returncode == 0: used, total, util = result.stdout.strip().split(', ') return { 'memory_used': int(used), 'memory_total': int(total), 'utilization': int(util) } except: pass return {'memory_used': 0, 'memory_total': 0, 'utilization': 0} def create_dashboard(self): """Create rich dashboard""" stats = self.get_earnings_stats() secrets, active_count = self.get_secrets_status() system = self.get_system_status() layout = Layout() # Header header = Panel( Align.center( Text("šŸ’€ DEATH MARCH CLI šŸ’€", style="bold red on black"), vertical="middle" ), title="Zero Human Intervention Revenue Machine", style="red" ) # Earnings Stats earnings_table = Table(title="šŸ’° EARNINGS DASHBOARD", style="green") earnings_table.add_column("Metric", style="cyan") earnings_table.add_column("Value", style="yellow") earnings_table.add_row("Total Earnings", f"${stats['total']:.2f}") earnings_table.add_row("Today's Earnings", f"${stats['today']:.2f}") earnings_table.add_row("Cycles Completed", str(stats['cycles'])) earnings_table.add_row("Average per Cycle", f"${stats['average']:.2f}") earnings_table.add_row("Best Cycle", f"${stats['max']:.2f}") # Secrets Status secrets_table = Table(title="šŸ”‘ API KEYS STATUS", style="blue") secrets_table.add_column("Service", style="cyan") secrets_table.add_column("Status", style="green") for service, active in secrets.items(): status = "āœ… ACTIVE" if active else "āŒ MISSING" secrets_table.add_row(service, status) secrets_table.add_row("Total Active", f"{active_count}/8") # System Health system_table = Table(title="⚔ SYSTEM HEALTH", style="purple") system_table.add_column("Component", style="cyan") system_table.add_column("Status", style="yellow") system_table.add_row("vLLM (Elizabeth)", "āœ… ONLINE" if system['vllm'] else "āŒ DOWN") system_table.add_row("DragonflyDB", "āœ… ONLINE" if system['redis'] else "āŒ DOWN") if system['gpu']['utilization'] > 0: gpu_text = f"{system['gpu']['utilization']}% | {system['gpu']['memory_used']}MB/{system['gpu']['memory_total']}MB" system_table.add_row("GPU", gpu_text) # Recent Activity if stats['recent']: recent_table = Table(title="šŸ”„ RECENT CYCLES", style="yellow") recent_table.add_column("Time", style="cyan") recent_table.add_column("Strategy", style="green") recent_table.add_column("Earnings", style="yellow") recent_table.add_column("GPU", style="purple") for timestamp, strategy, net, gpu in stats['recent'][:5]: time_str = datetime.datetime.fromisoformat(timestamp).strftime("%H:%M:%S") gpu_icon = "šŸš€" if gpu else "⚔" recent_table.add_row(time_str, strategy.split('_')[0], f"${net:.2f}", gpu_icon) else: recent_table = Panel("No cycles completed yet", title="šŸ”„ RECENT ACTIVITY") # Overall layout layout.split_column( header, Layout(name="stats", size=12), Layout(name="secrets", size=10), Layout(name="system", size=8), Layout(name="recent", size=12) ) layout["stats"].update(earnings_table) layout["secrets"].update(secrets_table) layout["system"].update(system_table) layout["recent"].update(recent_table) return layout def get_live_earnings(self): """Get live earnings stream""" try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute('SELECT SUM(net) FROM revenue WHERE date(timestamp) = date("now")') today = cursor.fetchone()[0] or 0.0 conn.close() return today except: return 0.0 def interactive_menu(self): """Interactive menu system""" while True: self.clear_screen() # Show dashboard dashboard = self.create_dashboard() self.console.print(dashboard) # Menu menu_options = [ "[1] Live Dashboard", "[2] Detailed Stats", "[3] API Key Status", "[4] System Health", "[5] Recent Activity", "[6] Force Earnings Check", "[7] Emergency Reset" ] # Add Elizabeth tools if available if ELIZABETH_TOOLS_AVAILABLE: menu_options.extend([ "[8] Elizabeth Shell", "[9] Execute Command", "[0] System Info" ]) menu_options.append("[q] Quit Death March") menu = Panel( "\n".join(menu_options), title="šŸ’€ DEATH MARCH MENU", style="red" ) self.console.print(menu) choice = input("\nšŸ’€ Enter command: ").strip() if choice == '1': self.live_dashboard() elif choice == '2': self.show_detailed_stats() elif choice == '3': self.show_api_status() elif choice == '4': self.show_system_health() elif choice == '5': self.show_recent_activity() elif choice == '6': self.force_earnings_check() elif choice == '7': self.emergency_reset() elif choice == '8' and ELIZABETH_TOOLS_AVAILABLE: self.launch_elizabeth_shell() elif choice == '9' and ELIZABETH_TOOLS_AVAILABLE: self.execute_custom_command() elif choice == '0' and ELIZABETH_TOOLS_AVAILABLE: self.show_detailed_system_info() elif choice.lower() == 'q': print("šŸ’€ Death March CLI terminated") break else: continue def live_dashboard(self): """Live updating dashboard""" self.clear_screen() self.console.print(Panel("šŸš€ LIVE DEATH MARCH DASHBOARD", style="red")) try: with Live(self.create_dashboard(), refresh_per_second=2, console=self.console) as live: for _ in range(100): # Run for 100 updates live.update(self.create_dashboard()) time.sleep(5) except KeyboardInterrupt: pass def show_detailed_stats(self): """Show detailed statistics""" stats = self.get_earnings_stats() table = Table(title="šŸ“Š DETAILED STATISTICS") table.add_column("Metric", style="cyan") table.add_column("Value", style="yellow") table.add_row("Total Revenue", f"${stats['total']:.2f}") table.add_row("Revenue per Hour", f"${stats['total']/(stats['cycles']*2/60):.2f}") table.add_row("Revenue per Day", f"${stats['total']/(stats['cycles']*2/60/24):.2f}") table.add_row("ROI on $50", f"{((stats['total']/50)*100):.1f}%") self.console.print(table) input("\nPress Enter to continue...") def show_api_status(self): """Detailed API key status""" secrets, active_count = self.get_secrets_status() table = Table(title="šŸ”‘ API KEY DETAILS") table.add_column("Service", style="cyan") table.add_column("Status", style="green") table.add_column("Environment Variable", style="blue") for service, active in secrets.items(): env_var = f"{service.upper()}_API_KEY" status = "āœ… ACTIVE" if active else "āŒ MISSING" table.add_row(service, status, env_var) self.console.print(table) self.console.print(f"\nšŸŽÆ Active APIs: {active_count}/8") input("\nPress Enter to continue...") def show_system_health(self): """Show system health details""" system = self.get_system_status() table = Table(title="⚔ SYSTEM HEALTH") table.add_column("Component", style="cyan") table.add_column("Status", style="yellow") table.add_column("Details", style="green") table.add_row("vLLM (Elizabeth)", "āœ… ONLINE" if system['vllm'] else "āŒ DOWN", "Port 8000") table.add_row("DragonflyDB", "āœ… ONLINE" if system['redis'] else "āŒ DOWN", "Port 18000") gpu = system['gpu'] if gpu['utilization'] > 0: gpu_text = f"{gpu['utilization']}% | {gpu['memory_used']}MB/{gpu['memory_total']}MB" table.add_row("GPU H200", "āœ… ACTIVE", gpu_text) else: table.add_row("GPU H200", "ā“ UNKNOWN", "Check nvidia-smi") self.console.print(table) input("\nPress Enter to continue...") def show_recent_activity(self): """Show recent cycles""" stats = self.get_earnings_stats() if not stats['recent']: self.console.print("[red]No recent activity[/red]") input("\nPress Enter to continue...") return table = Table(title="šŸ”„ RECENT CYCLES DETAILS") table.add_column("Time", style="cyan") table.add_column("Strategy", style="green") table.add_column("Earnings", style="yellow") table.add_column("GPU", style="purple") for timestamp, strategy, net, gpu in stats['recent']: time_str = datetime.datetime.fromisoformat(timestamp).strftime("%H:%M:%S") gpu_icon = "šŸš€ GPU" if gpu else "⚔ CPU" table.add_row(time_str, strategy, f"${net:.2f}", gpu_icon) self.console.print(table) input("\nPress Enter to continue...") def force_earnings_check(self): """Force immediate earnings calculation""" self.console.print("[yellow]šŸ”„ Forcing earnings check...[/yellow]") # Simulate a check current = self.get_live_earnings() self.console.print(f"[green]Current earnings: ${current:.2f}[/green]") input("\nPress Enter to continue...") def emergency_reset(self): """Emergency reset protocol""" confirm = input("šŸ’€ EMERGENCY RESET - Type 'DEATH' to confirm: ") if confirm == 'DEATH': self.console.print("[red]šŸ’€ Emergency reset initiated[/red]") # Reset database try: conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute('DELETE FROM revenue') conn.commit() conn.close() self.console.print("[green]āœ… Database reset complete[/green]") except Exception as e: self.console.print(f"[red]āŒ Reset failed: {e}[/red]") else: self.console.print("[yellow]Reset cancelled[/yellow]") input("\nPress Enter to continue...") def launch_elizabeth_shell(self): """Launch Elizabeth interactive shell""" if not ELIZABETH_TOOLS_AVAILABLE: self.console.print("[red]āŒ Elizabeth tools not available[/red]") input("\nPress Enter to continue...") return self.console.print("[green]šŸš€ Launching Elizabeth Shell...[/green]") try: subprocess.run(["python3", "elizabeth_shell.py"], cwd=os.getcwd()) except Exception as e: self.console.print(f"[red]āŒ Failed to launch shell: {e}[/red]") input("\nPress Enter to continue...") def execute_custom_command(self): """Execute custom shell command""" if not ELIZABETH_TOOLS_AVAILABLE: self.console.print("[red]āŒ Elizabeth tools not available[/red]") input("\nPress Enter to continue...") return command = input("šŸ’€ Enter command to execute: ").strip() if not command: self.console.print("[yellow]āŒ No command entered[/yellow]") input("\nPress Enter to continue...") return self.console.print(f"[yellow]šŸš€ Executing: {command}[/yellow]") result = execute_command(command, realtime=True) if result['success']: self.console.print(f"[green]āœ… SUCCESS ({(result['execution_time']):.2f}s)[/green]") if result['output']: self.console.print(f"[cyan]šŸ“‹ Output: {result['output'][:500]}{'...' if len(result['output']) > 500 else ''}[/cyan]") else: self.console.print(f"[red]āŒ FAILED ({(result['execution_time']):.2f}s)[/red]") self.console.print(f"[red]šŸ’„ Error: {result.get('output', 'Unknown error')}[/red]") input("\nPress Enter to continue...") def show_detailed_system_info(self): """Show detailed system information""" if not ELIZABETH_TOOLS_AVAILABLE: self.console.print("[red]āŒ Elizabeth tools not available[/red]") input("\nPress Enter to continue...") return info = get_system_info() table = Table(title="⚔ DETAILED SYSTEM INFORMATION") table.add_column("Component", style="cyan") table.add_column("Value", style="yellow") for key, value in info.items(): if value and not value.startswith("Error:") and not value.startswith("Exception:"): table.add_row(key, str(value)) self.console.print(table) input("\nPress Enter to continue...") def run(self): """Run the interactive CLI""" while True: try: self.interactive_menu() except KeyboardInterrupt: self.console.print("\n[red]šŸ’€ Death March CLI terminated by user[/red]") break if __name__ == "__main__": cli = DeathMarchCLI() cli.run()