The Loadbalancer

Nov 23, 2026

Here the two files of the latest working loadbalancer. This script is supposed to be base for custom builds and
tailored versions of the Cyberdeck. They are a pattern.

Please customize to your needs under the Apache 2.0 Licence



#!/usr/bin/env python3
"""
UNIVERSAL Nexus Load Balancer v4
- Reads nodes from /etc/hosts (filter by IPv4 and optional network prefix)
- Uses specified SSH user for remote commands (e.g., mpiuser)
- Gathers RAM (SSH) and Ollama models (HTTP)
- Logs performance data for later analysis
- Dispatcher selects best node based on load + performance
- AI‑tunable parameters via JSON config
"""

import asyncio
import json
import uuid
import socket
import statistics
import os
import re
import time
import subprocess
import argparse
import logging
from enum import Enum
from datetime import datetime
from dataclasses import dataclass, field
from typing import Dict, List, Set, Optional, Any, Tuple
from collections import defaultdict
from pathlib import Path

# Attempt to import aiohttp for monitoring (optional)
try:
    import aiohttp
    from aiohttp import web
    HAS_AIOHTTP = True
except ImportError:
    HAS_AIOHTTP = False
    print("Warning: aiohttp not installed. Monitoring server disabled.")

# Setup logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger("NexusLBv4")

# ============================
# Protocol Constants
# ============================

class ProtocolState(Enum):
    LISTEN = "LISTEN"
    SYN_RECEIVED = "SYN_RECEIVED"
    ESTABLISHED = "ESTABLISHED"
    CLOSED = "CLOSED"

class MessageType(Enum):
    HELLO = "HELLO"
    SYN = "SYN"
    SYN_ACK = "SYN_ACK"
    ACK = "ACK"
    DATA = "DATA"
    FIN = "FIN"
    SCAN = "SCAN"
    SCAN_RESULT = "SCAN_RESULT"

@dataclass
class ClientIdentity:
    client_id: str
    script_name: str
    script_version: str
    capabilities: Dict[str, Any]
    required_features: List[str]   # generic hardware features

@dataclass
class Node:
    """Represents a node in the cluster."""
    node_id: str
    hostname: str
    ip: str
    ollama_port: int = 11434
    available_models: List[str] = field(default_factory=list)
    ram_total_mb: int = 0
    ram_free_mb: int = 0
    cpu_cores: int = 0
    load_avg: float = 0.0          # recent load (could be 1-min load)
    features: List[str] = field(default_factory=list)
    performance_score: float = 1.0  # derived from history
    last_seen: datetime = field(default_factory=datetime.now)
    is_online: bool = True
    current_sessions: int = 0      # active sessions on this node
    avg_response_time: float = 0.0 # rolling average in seconds

    def can_handle(self, required_models: List[str], min_ram_mb: int) -> bool:
        if not self.is_online:
            return False
        if self.ram_free_mb < min_ram_mb:
            return False
        if required_models:
            if not any(m in self.available_models for m in required_models):
                return False
        return True

    def calculate_fitness(self, required_models: List[str], min_ram_mb: int) -> float:
        """Score 0..1 – higher is better."""
        if not self.can_handle(required_models, min_ram_mb):
            return 0.0
        score = 0.0

        # RAM ratio (more free = better)
        if self.ram_total_mb > 0:
            ram_ratio = self.ram_free_mb / self.ram_total_mb
            score += ram_ratio * 0.25

        # Model match quality
        if required_models:
            best_match = 0.0
            for req in required_models:
                if req in self.available_models:
                    best_match = 1.0
                    break
                # family match
                req_family = req.split(':')[0].split('.')[0]
                for av in self.available_models:
                    av_family = av.split(':')[0].split('.')[0]
                    if req_family == av_family:
                        best_match = 0.8
            score += best_match * 0.25

        # Load factor (lower load = better)
        load_factor = max(0.0, 1.0 - (self.load_avg / 4.0))  # assume 4 is high
        score += load_factor * 0.2

        # Session count factor (fewer sessions = better)
        session_factor = max(0.0, 1.0 - (self.current_sessions / 10.0))
        score += session_factor * 0.15

        # Performance history
        score += self.performance_score * 0.15

        return min(1.0, score)

@dataclass
class Session:
    session_id: str
    client_id: str
    node_id: str
    assigned_model: str
    protocol_state: ProtocolState = ProtocolState.LISTEN
    start_time: datetime = field(default_factory=datetime.now)
    last_activity: datetime = field(default_factory=datetime.now)
    timeout_seconds: int = 600
    task_data: Optional[Dict] = None
    result_data: Optional[Dict] = None

    def is_expired(self) -> bool:
        return (datetime.now() - self.last_activity).total_seconds() > self.timeout_seconds

    def update_activity(self):
        self.last_activity = datetime.now()

# ============================
# Node Discovery & Capability Gathering
# ============================

def discover_nodes_from_hosts(network_prefix: Optional[str] = None) -> List[Dict[str, str]]:
    """
    Parse /etc/hosts and return list of {hostname, ip} for non-localhost IPv4 entries.
    If network_prefix is given, only include IPs that start with that prefix.
    """
    nodes = []
    try:
        with open('/etc/hosts', 'r') as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith('#'):
                    continue
                parts = line.split()
                if len(parts) < 2:
                    continue
                ip = parts[0]
                # Skip IPv6 addresses
                if ':' in ip:
                    continue
                # Skip localhost/loopback
                if ip.startswith('127.') or ip == '0.0.0.0':
                    continue
                # If a network prefix is given, only include IPs that start with it
                if network_prefix and not ip.startswith(network_prefix):
                    continue
                hostname = parts[1]
                if not any(n['ip'] == ip for n in nodes):
                    nodes.append({'hostname': hostname, 'ip': ip})
    except Exception as e:
        logger.error(f"Error reading /etc/hosts: {e}")
    # Always include localhost as a fallback (but treat it specially)
    if not any(n['ip'] == '127.0.0.1' for n in nodes):
        nodes.append({'hostname': 'localhost', 'ip': '127.0.0.1'})
    return nodes

async def get_ollama_models(ip: str, port: int = 11434) -> List[str]:
    """Fetch models from node's Ollama API."""
    try:
        reader, writer = await asyncio.wait_for(
            asyncio.open_connection(ip, port),
            timeout=3.0
        )
        writer.write(b'GET /api/tags HTTP/1.1\r\nHost: localhost\r\n\r\n')
        await writer.drain()
        response = await asyncio.wait_for(reader.read(8192), timeout=5.0)
        writer.close()
        await writer.wait_closed()
        response_str = response.decode('utf-8', errors='ignore')
        json_start = response_str.find('{')
        json_end = response_str.rfind('}') + 1
        if json_start != -1 and json_end > json_start:
            data = json.loads(response_str[json_start:json_end])
            return [m['name'] for m in data.get('models', [])]
    except Exception as e:
        logger.debug(f"Could not get models from {ip}: {e}")
    return []

async def get_ram_via_ssh(hostname: str, ssh_user: str) -> Tuple[int, int]:
    """Get total and free RAM in MB via SSH (assumes passwordless key for ssh_user)."""
    total = 0
    free = 0
    try:
        proc = await asyncio.create_subprocess_exec(
            'ssh', '-o', 'ConnectTimeout=5', '-o', 'BatchMode=yes',
            f'{ssh_user}@{hostname}', 'free -m',
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE
        )
        stdout, stderr = await proc.communicate()
        if proc.returncode == 0:
            for line in stdout.decode().split('\n'):
                if line.startswith('Mem:'):
                    parts = line.split()
                    if len(parts) >= 4:
                        total = int(parts[1])
                        free = int(parts[3])
                        break
    except Exception as e:
        logger.debug(f"SSH RAM query failed for {hostname}: {e}")
    return total, free

async def get_load_via_ssh(hostname: str, ssh_user: str) -> float:
    """Get 1‑minute load average via SSH."""
    try:
        proc = await asyncio.create_subprocess_exec(
            'ssh', '-o', 'ConnectTimeout=5', '-o', 'BatchMode=yes',
            f'{ssh_user}@{hostname}', 'uptime',
            stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE
        )
        stdout, stderr = await proc.communicate()
        if proc.returncode == 0:
            output = stdout.decode()
            match = re.search(r'load average: ([\d.]+),', output)
            if match:
                return float(match.group(1))
    except Exception as e:
        logger.debug(f"SSH load query failed for {hostname}: {e}")
    return 0.0

async def get_ram_local() -> Tuple[int, int]:
    """Get RAM info for localhost from /proc/meminfo."""
    total = 0
    free = 0
    try:
        with open('/proc/meminfo', 'r') as f:
            for line in f:
                if line.startswith('MemTotal:'):
                    total = int(line.split()[1]) // 1024   # kB to MB
                elif line.startswith('MemAvailable:'):
                    free = int(line.split()[1]) // 1024
    except Exception as e:
        logger.debug(f"Local RAM query failed: {e}")
    return total, free

async def get_load_local() -> float:
    """Get 1‑minute load average from /proc/loadavg."""
    try:
        with open('/proc/loadavg', 'r') as f:
            parts = f.read().split()
            if parts:
                return float(parts[0])
    except Exception:
        pass
    return 0.0

# ============================
# Performance Logger
# ============================

class PerformanceLogger:
    """Logs performance data and manages tunable parameters."""
    def __init__(self, log_dir: str = "performance_logs"):
        self.log_dir = Path(log_dir)
        self.log_dir.mkdir(exist_ok=True)
        self.session_log = self.log_dir / "sessions.jsonl"
        self.node_log = self.log_dir / "nodes.jsonl"
        self.config_file = self.log_dir / "config.json"
        self._init_logs()
        self._load_config()

    def _init_logs(self):
        for f in [self.session_log, self.node_log]:
            if not f.exists():
                f.touch()

    def _load_config(self):
        """Load tunable parameters from config file; create defaults if missing."""
        default_config = {
            "weights": {
                "ram_ratio": 0.25,
                "model_match": 0.25,
                "load_factor": 0.20,
                "session_factor": 0.15,
                "performance_score": 0.15
            },
            "selection": {
                "min_ram_mb": 1024,
                "default_timeout_seconds": 600,
                "max_concurrent_per_node": 5
            },
            "optimizer_enabled": True,
            "optimizer_interval_seconds": 600
        }
        try:
            with open(self.config_file, 'r') as f:
                self.config = json.load(f)
        except FileNotFoundError:
            self.config = default_config
            self.save_config()
        except json.JSONDecodeError:
            self.config = default_config
            self.save_config()

    def save_config(self):
        with open(self.config_file, 'w') as f:
            json.dump(self.config, f, indent=2)

    def log_session_start(self, session: Session):
        entry = {
            "event": "session_start",
            "timestamp": datetime.now().isoformat(),
            "session_id": session.session_id,
            "client_id": session.client_id,
            "node_id": session.node_id,
            "assigned_model": session.assigned_model
        }
        with open(self.session_log, 'a') as f:
            f.write(json.dumps(entry) + '\n')

    def log_session_result(self, session: Session, result: Dict):
        processing_time = (datetime.now() - session.start_time).total_seconds()
        entry = {
            "event": "session_result",
            "timestamp": datetime.now().isoformat(),
            "session_id": session.session_id,
            "client_id": session.client_id,
            "node_id": session.node_id,
            "assigned_model": session.assigned_model,
            "processing_time_seconds": processing_time,
            "success": result.get("success", False),
            "error": result.get("error"),
            "result_size": len(str(result.get("result", "")))
        }
        with open(self.session_log, 'a') as f:
            f.write(json.dumps(entry) + '\n')

    def log_node_metrics(self, node_id: str, metrics: Dict):
        entry = {
            "timestamp": datetime.now().isoformat(),
            "node_id": node_id,
            **metrics
        }
        with open(self.node_log, 'a') as f:
            f.write(json.dumps(entry) + '\n')

    def get_node_performance_scores(self) -> Dict[str, float]:
        """Calculate performance scores for nodes based on recent session results."""
        # This would parse the session log and compute success rate and avg time per node
        # For simplicity, we'll return a dummy score for now.
        # In a real implementation, you'd compute from the logs.
        return {}

# ============================
# Dispatcher
# ============================

class Dispatcher:
    """Selects the best node for a given request."""
    def __init__(self, logger: PerformanceLogger):
        self.logger = logger
        self.nodes: Dict[str, Node] = {}  # will be set by load balancer

    def set_nodes(self, nodes: Dict[str, Node]):
        self.nodes = nodes

    def select_best_node(self, required_models: List[str], min_ram_mb: int,
                         task_type: str = "general") -> Optional[str]:
        """Return node_id of best candidate, or None."""
        candidates = []
        for node_id, node in self.nodes.items():
            if not node.is_online:
                continue
            if not node.can_handle(required_models, min_ram_mb):
                continue
            fitness = node.calculate_fitness(required_models, min_ram_mb)
            candidates.append((fitness, node_id))
        if not candidates:
            return None
        candidates.sort(reverse=True)
        return candidates[0][1]

    def assign_model_for_node(self, node_id: str, required_models: List[str]) -> str:
        """Pick the best model on the node."""
        node = self.nodes[node_id]
        if not node.available_models:
            return "unknown"
        for req in required_models:
            if req in node.available_models:
                return req
        return node.available_models[0]

# ============================
# Load Balancer Core
# ============================

class NexusLoadBalancer:
    def __init__(self, host="0.0.0.0", port=8888, scan_interval=180,
                 network_prefix=None, ssh_user="mpiuser"):
        self.host = host
        self.port = port
        self.scan_interval = scan_interval
        self.network_prefix = network_prefix
        self.ssh_user = ssh_user

        # Core components
        self.logger = PerformanceLogger()
        self.dispatcher = Dispatcher(self.logger)

        # State
        self.nodes: Dict[str, Node] = {}
        self.sessions: Dict[str, Session] = {}
        self.clients: Dict[str, ClientIdentity] = {}

        # Statistics
        self.stats = {
            "total_sessions": 0,
            "active_sessions": 0,
            "completed_sessions": 0,
            "failed_sessions": 0,
            "nodes_discovered": 0,
            "clients_registered": 0,
            "start_time": datetime.now().isoformat()
        }

        # Background tasks
        self.running = False
        self.background_tasks = []

    # ========== Background Tasks ==========

    async def refresh_nodes(self):
        """Discover nodes from /etc/hosts and update capabilities."""
        raw = discover_nodes_from_hosts(self.network_prefix)
        logger.info(f"Discovered {len(raw)} nodes from /etc/hosts")

        # Update or add nodes
        for entry in raw:
            hostname = entry['hostname']
            ip = entry['ip']
            node_id = hostname.replace('.', '_')

            # Get models via HTTP
            models = await get_ollama_models(ip)

            # Get RAM and load (special case for localhost)
            if hostname == 'localhost' or ip == '127.0.0.1':
                total_ram, free_ram = await get_ram_local()
                load_avg = await get_load_local()
            else:
                total_ram, free_ram = await get_ram_via_ssh(hostname, self.ssh_user)
                load_avg = await get_load_via_ssh(hostname, self.ssh_user)

            is_online = (len(models) > 0) or (total_ram > 0)
            if node_id in self.nodes:
                node = self.nodes[node_id]
                node.available_models = models
                node.ram_total_mb = total_ram
                node.ram_free_mb = free_ram
                node.load_avg = load_avg
                node.is_online = is_online
                node.last_seen = datetime.now()
            else:
                node = Node(
                    node_id=node_id,
                    hostname=hostname,
                    ip=ip,
                    available_models=models,
                    ram_total_mb=total_ram,
                    ram_free_mb=free_ram,
                    load_avg=load_avg,
                    is_online=is_online
                )
                self.nodes[node_id] = node
                logger.info(f"Added new node: {node_id} ({ip})")

            # Log node metrics
            self.logger.log_node_metrics(node_id, {
                "models": models,
                "ram_total_mb": total_ram,
                "ram_free_mb": free_ram,
                "load_avg": load_avg,
                "is_online": is_online
            })

        # Mark missing nodes as offline
        current_ids = {n['hostname'].replace('.', '_') for n in raw}
        for nid, node in self.nodes.items():
            if nid not in current_ids and node.is_online:
                node.is_online = False
                logger.info(f"Node {nid} not in /etc/hosts, marked offline")

        self.stats["nodes_discovered"] = len([n for n in self.nodes.values() if n.is_online])
        self.dispatcher.set_nodes(self.nodes)

    async def node_refresh_loop(self):
        while self.running:
            await asyncio.sleep(self.scan_interval)
            await self.refresh_nodes()

    async def session_cleanup_loop(self):
        while self.running:
            await asyncio.sleep(60)
            expired = []
            for sid, sess in self.sessions.items():
                if sess.is_expired():
                    expired.append(sid)
                    self.stats["failed_sessions"] += 1
            for sid in expired:
                del self.sessions[sid]
                self.stats["active_sessions"] -= 1
                logger.debug(f"Cleaned expired session {sid}")

    async def performance_monitoring_loop(self):
        """Periodically update node performance scores from logs."""
        while self.running:
            await asyncio.sleep(30)
            # Compute performance scores (simplified for now)
            # In a real implementation, parse session logs
            for node_id, node in self.nodes.items():
                # Dummy: performance_score based on avg response time
                # We'll just set a default for now.
                node.performance_score = 0.5
            # Update config if needed (reload from file)
            self.logger._load_config()

    async def optimizer_loop(self):
        """Periodically run the AI optimizer (simulated)."""
        while self.running:
            await asyncio.sleep(self.logger.config.get("optimizer_interval_seconds", 600))
            # Here you would read the performance logs, analyze, and update config.
            # For demonstration, we just log that optimization ran.
            logger.info("AI optimizer run (placeholder)")

    async def monitoring_server(self):
        """HTTP server for health checks."""
        if not HAS_AIOHTTP:
            logger.warning("aiohttp not installed, monitoring server disabled")
            return
        app = web.Application()

        async def health(request):
            return web.json_response({
                "status": "running",
                "uptime_seconds": (datetime.now() - datetime.fromisoformat(self.stats["start_time"])).total_seconds(),
                "active_sessions": len(self.sessions),
                "total_sessions": self.stats["total_sessions"],
                "clients": len(self.clients),
                "online_nodes": len([n for n in self.nodes.values() if n.is_online])
            })

        async def nodes(request):
            data = {}
            for nid, node in self.nodes.items():
                data[nid] = {
                    "hostname": node.hostname,
                    "ip": node.ip,
                    "online": node.is_online,
                    "models": node.available_models,
                    "ram_free_mb": node.ram_free_mb,
                    "load_avg": node.load_avg,
                    "current_sessions": node.current_sessions,
                    "performance_score": node.performance_score
                }
            return web.json_response(data)

        app.router.add_get('/health', health)
        app.router.add_get('/nodes', nodes)

        runner = web.AppRunner(app)
        await runner.setup()
        site = web.TCPSite(runner, '0.0.0.0', 8889)
        await site.start()
        logger.info("Monitoring server started on port 8889")
        while self.running:
            await asyncio.sleep(1)

    # ========== Protocol Handlers ==========

    async def handle_connection(self, reader, writer):
        client_addr = writer.get_extra_info('peername')
        try:
            data = await reader.read(8192)
            if not data:
                return
            msg = json.loads(data.decode())
            msg_type = msg.get("type")

            if msg_type == MessageType.HELLO.value:
                resp = await self.handle_hello(msg, writer)
            elif msg_type == MessageType.SYN.value:
                resp = await self.handle_syn(msg, writer)
            elif msg_type == MessageType.ACK.value:
                resp = await self.handle_ack(msg, writer)
            elif msg_type == MessageType.DATA.value:
                resp = await self.handle_data(msg, writer)
            elif msg_type == MessageType.FIN.value:
                resp = await self.handle_fin(msg, writer)
            elif msg_type == MessageType.SCAN.value:
                resp = await self.handle_scan(msg, writer)
            else:
                resp = self.create_error(f"Unknown message type: {msg_type}")

            if resp:
                writer.write(json.dumps(resp).encode())
                await writer.drain()
        except json.JSONDecodeError:
            await self.send_error(writer, "Invalid JSON")
        except Exception as e:
            logger.error(f"Connection error from {client_addr}: {e}")
            await self.send_error(writer, str(e))
        finally:
            writer.close()

    async def handle_hello(self, msg: Dict, writer) -> Dict:
        data = msg.get("data", {})
        entity = data.get("entity_type")
        if entity == "client":
            client_id = data.get("client_id") or f"client_{int(time.time())}"
            client = ClientIdentity(
                client_id=client_id,
                script_name=data.get("script_name", "unknown"),
                script_version=data.get("script_version", "1.0"),
                capabilities=data.get("capabilities", {}),
                required_features=data.get("required_features", [])
            )
            self.clients[client_id] = client
            self.stats["clients_registered"] += 1
            logger.info(f"Client registered: {client.script_name} ({client_id})")
            return {
                "type": MessageType.HELLO.value,
                "data": {
                    "status": "registered",
                    "client_id": client_id,
                    "message": "OK"
                }
            }
        else:
            return self.create_error("Only client registration supported")

    async def handle_syn(self, msg: Dict, writer) -> Dict:
        data = msg.get("data", {})
        client_id = data.get("client_id")
        if client_id not in self.clients:
            return self.create_error("Client not registered. Send HELLO first.")

        required_models = data.get("required_models", [])
        min_ram = data.get("min_ram", 1024)
        task_type = data.get("task_type", "general")

        # Select best node
        best_node_id = self.dispatcher.select_best_node(required_models, min_ram, task_type)
        if not best_node_id:
            return {
                "type": MessageType.SYN_ACK.value,
                "data": {
                    "status": "wait",
                    "client_id": client_id,
                    "message": "No suitable node available",
                    "suggested_retry_seconds": 30
                }
            }

        node = self.nodes[best_node_id]
        assigned_model = self.dispatcher.assign_model_for_node(best_node_id, required_models)

        session_id = str(uuid.uuid4())
        session = Session(
            session_id=session_id,
            client_id=client_id,
            node_id=best_node_id,
            assigned_model=assigned_model,
            protocol_state=ProtocolState.SYN_RECEIVED,
            timeout_seconds=data.get("timeout_seconds", self.logger.config["selection"]["default_timeout_seconds"])
        )
        self.sessions[session_id] = session
        self.stats["active_sessions"] += 1
        self.stats["total_sessions"] += 1
        node.current_sessions += 1

        self.logger.log_session_start(session)
        logger.info(f"SYN: assigned session {session_id} to {best_node_id} with model {assigned_model}")

        return {
            "type": MessageType.SYN_ACK.value,
            "data": {
                "status": "ready",
                "session_id": session_id,
                "node_id": best_node_id,
                "node_ip": node.ip,
                "node_port": node.ollama_port,
                "assigned_model": assigned_model,
                "message": "Send ACK with task data"
            }
        }

    async def handle_ack(self, msg: Dict, writer) -> Dict:
        data = msg.get("data", {})
        session_id = data.get("session_id")
        if session_id not in self.sessions:
            return self.create_error("Invalid session")
        session = self.sessions[session_id]
        if session.protocol_state != ProtocolState.SYN_RECEIVED:
            return self.create_error(f"Invalid state: {session.protocol_state}")

        session.task_data = data.get("task_data", {})
        session.protocol_state = ProtocolState.ESTABLISHED
        session.update_activity()

        # Forward to node in background
        asyncio.create_task(self.forward_to_node(session))

        return {
            "type": MessageType.ACK.value,
            "data": {
                "status": "established",
                "session_id": session_id,
                "message": "Task queued"
            }
        }

    async def forward_to_node(self, session: Session):
        node = self.nodes.get(session.node_id)
        if not node or not node.is_online:
            session.result_data = {"error": "Node offline", "success": False}
            return

        prompt = session.task_data.get("prompt", "")
        parameters = session.task_data.get("parameters", {})

        ollama_payload = {
            "model": session.assigned_model,
            "prompt": prompt,
            "stream": False,
            "options": {
                "temperature": parameters.get("temperature", 0.7),
                "num_predict": parameters.get("num_predict", 512)
            }
        }

        start_time = time.time()
        try:
            reader, writer = await asyncio.wait_for(
                asyncio.open_connection(node.ip, node.ollama_port),
                timeout=10.0
            )
            request_data = json.dumps(ollama_payload)
            request = (
                f"POST /api/generate HTTP/1.1\r\n"
                f"Host: localhost\r\n"
                f"Content-Type: application/json\r\n"
                f"Content-Length: {len(request_data)}\r\n"
                f"\r\n"
                f"{request_data}"
            )
            writer.write(request.encode())
            await writer.drain()
            response_data = await asyncio.wait_for(reader.read(65536), timeout=session.timeout_seconds)
            writer.close()
            await writer.wait_closed()

            # Parse response
            response_str = response_data.decode('utf-8', errors='ignore')
            json_start = response_str.find('{')
            if json_start != -1:
                json_str = response_str[json_start:]
                result = json.loads(json_str)
                session.result_data = {
                    "success": True,
                    "result": result.get("response", ""),
                    "model": session.assigned_model
                }
                logger.info(f"Session {session.session_id} result ready")
            else:
                session.result_data = {"error": "Invalid response", "success": False}
        except asyncio.TimeoutError:
            session.result_data = {"error": "Node timeout", "success": False}
        except Exception as e:
            session.result_data = {"error": str(e), "success": False}
            logger.error(f"Forward error for {session.session_id}: {e}")

        # Update node stats
        node.avg_response_time = (node.avg_response_time * 0.9 + (time.time() - start_time) * 0.1)
        node.current_sessions -= 1
        # Log result
        self.logger.log_session_result(session, session.result_data)

    async def handle_data(self, msg: Dict, writer) -> Dict:
        data = msg.get("data", {})
        session_id = data.get("session_id")
        if session_id not in self.sessions:
            return self.create_error("Invalid session")
        session = self.sessions[session_id]
        session.update_activity()

        data_type = data.get("data_type", "unknown")
        if data_type == "result_request":
            if session.result_data is not None:
                return {
                    "type": MessageType.DATA.value,
                    "data": {
                        "session_id": session_id,
                        "data_type": "result",
                        "result": session.result_data
                    }
                }
            else:
                return {
                    "type": MessageType.DATA.value,
                    "data": {
                        "session_id": session_id,
                        "data_type": "no_result",
                        "message": "Processing..."
                    }
                }
        elif data_type == "status_request":
            return {
                "type": MessageType.DATA.value,
                "data": {
                    "session_id": session_id,
                    "protocol_state": session.protocol_state.value,
                    "age_seconds": (datetime.now() - session.start_time).total_seconds(),
                    "has_result": session.result_data is not None
                }
            }
        else:
            return self.create_error("Unknown data type")

    async def handle_fin(self, msg: Dict, writer) -> Dict:
        data = msg.get("data", {})
        session_id = data.get("session_id")
        if session_id in self.sessions:
            session = self.sessions.pop(session_id)
            self.stats["active_sessions"] -= 1
            if session.result_data and session.result_data.get("success"):
                self.stats["completed_sessions"] += 1
            else:
                self.stats["failed_sessions"] += 1
            logger.info(f"Session {session_id} closed")
        return {
            "type": MessageType.FIN.value,
            "data": {"status": "closed", "session_id": session_id}
        }

    async def handle_scan(self, msg: Dict, writer) -> Dict:
        # Return current node list
        nodes_list = []
        for nid, node in self.nodes.items():
            nodes_list.append({
                "node_id": nid,
                "ip": node.ip,
                "models": node.available_models,
                "is_online": node.is_online,
                "ram_free_mb": node.ram_free_mb,
                "load_avg": node.load_avg
            })
        return {
            "type": MessageType.SCAN_RESULT.value,
            "data": {"nodes": nodes_list}
        }

    def create_error(self, msg: str) -> Dict:
        return {"type": "ERROR", "data": {"error": msg}}

    async def send_error(self, writer, msg: str):
        resp = self.create_error(msg)
        writer.write(json.dumps(resp).encode())
        await writer.drain()

    # ========== Main Start ==========

    async def start(self):
        self.running = True
        server = await asyncio.start_server(self.handle_connection, self.host, self.port)

        # Initial node refresh
        await self.refresh_nodes()

        # Background tasks
        self.background_tasks.extend([
            asyncio.create_task(self.node_refresh_loop()),
            asyncio.create_task(self.session_cleanup_loop()),
            asyncio.create_task(self.performance_monitoring_loop()),
            asyncio.create_task(self.optimizer_loop())
        ])
        if HAS_AIOHTTP:
            self.background_tasks.append(asyncio.create_task(self.monitoring_server()))

        logger.info(f"Nexus Load Balancer v4 listening on {self.host}:{self.port}")
        async with server:
            await server.serve_forever()

# ============================
# Main Entry
# ============================

async def main():
    parser = argparse.ArgumentParser(description="Nexus Load Balancer v4")
    parser.add_argument("--host", default="0.0.0.0", help="Host to bind to")
    parser.add_argument("--port", type=int, default=8888, help="Port to listen on")
    parser.add_argument("--scan-interval", type=int, default=180,
                        help="Seconds between node scans")
    parser.add_argument("--network", default=None,
                        help="Network prefix to filter nodes (e.g., 192.168.178)")
    parser.add_argument("--ssh-user", default="mpiuser",
                        help="SSH user for remote commands (default: mpiuser)")
    args = parser.parse_args()

    lb = NexusLoadBalancer(
        host=args.host,
        port=args.port,
        scan_interval=args.scan_interval,
        network_prefix=args.network,
        ssh_user=args.ssh_user
    )
    await lb.start()

if __name__ == "__main__":
    asyncio.run(main())

And the connected monitor


#!/usr/bin/env python3
"""
Cyberdeck Nexus Monitor – Noir Terminal + Web Dashboard
Now focused on Nexus Load Balancer, RAG processor, and system health.
"""

import time
import json
import threading
import subprocess
import os
import re
import socket
from datetime import datetime
from pathlib import Path
from http.server import HTTPServer, BaseHTTPRequestHandler
import urllib.request

# ------------------------------------------------------------
# Configuration
# ------------------------------------------------------------
MONITOR_PORT = 8880
LB_HEALTH_URL = "http://localhost:8889/health"
LB_NODES_URL = "http://localhost:8889/nodes"
RAG_PROCESS_NAME = "7_Wikidump_RAGing"
POOLED_STORAGE = "/home/ibo/Pooled-Storage"
CHECKPOINT_FILE = Path("/home/ibo/Pooled-Storage/CyberdeckDB/checkpoint.json")
FILE_CHECKPOINT_FILE = Path("/home/ibo/Pooled-Storage/CyberdeckDB/file_checkpoint.json")
TEXT_RAG_DIR = Path("/home/ibo/Pooled-Storage/Wiki/text_rag")
HTML_RAG_DIR = Path("/home/ibo/Pooled-Storage/Wiki/html_rag")

# Global status cache
status_cache = {
    "timestamp": None,
    "nexus": {},
    "rag": {},
    "system": {},
    "recommendations": []
}

# ------------------------------------------------------------
# Data collection functions
# ------------------------------------------------------------
def fetch_json(url, timeout=5):
    try:
        with urllib.request.urlopen(url, timeout=timeout) as resp:
            return json.loads(resp.read().decode())
    except:
        return None

def check_nexus():
    """Fetch Nexus load balancer status."""
    health = fetch_json(LB_HEALTH_URL)
    nodes = fetch_json(LB_NODES_URL)
    if health is None or nodes is None:
        return {"status": "❌", "message": "Unreachable", "details": {}}
    online_nodes = [n for n, v in nodes.items() if v.get("online", False)]
    return {
        "status": "✅" if health.get("status") == "running" else "⚠️",
        "message": f"{len(online_nodes)}/{len(nodes)} nodes online",
        "details": {
            "health": health,
            "nodes": nodes,
            "online_count": len(online_nodes),
            "total_count": len(nodes)
        }
    }

def check_rag():
    """Check RAG processor process and checkpoints."""
    results = {}
    # Process
    try:
        proc = subprocess.run(["pgrep", "-f", RAG_PROCESS_NAME], capture_output=True, text=True)
        if proc.returncode == 0:
            pids = proc.stdout.strip().split()
            results["process"] = {"status": "✅", "message": f"Running (PIDs: {', '.join(pids)})"}
            if pids:
                pid = pids[0]
                cpu = subprocess.run(["ps", "-p", pid, "-o", "%cpu", "--no-headers"], capture_output=True, text=True).stdout.strip()
                mem = subprocess.run(["ps", "-p", pid, "-o", "%mem", "--no-headers"], capture_output=True, text=True).stdout.strip()
                results["process"]["cpu"] = cpu
                results["process"]["mem"] = mem
        else:
            results["process"] = {"status": "❌", "message": "Not running"}
    except:
        results["process"] = {"status": "⚠️", "message": "Check failed"}
    # Checkpoint
    if CHECKPOINT_FILE.exists():
        try:
            with open(CHECKPOINT_FILE) as f:
                cp = json.load(f)
            last_page = cp.get("last_page", 0)
            pages = cp.get("stats", {}).get("pages_processed", 0)
            timestamp = cp.get("timestamp", "")
            age_min = 0
            if timestamp:
                try:
                    dt = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
                    age_min = int((datetime.now() - dt).total_seconds() / 60)
                except:
                    pass
            results["checkpoint"] = {
                "status": "📄",
                "message": f"Page {last_page}: {pages} pages processed",
                "details": {"pages": pages, "age_minutes": age_min}
            }
        except:
            results["checkpoint"] = {"status": "⚠️", "message": "Corrupted"}
    else:
        results["checkpoint"] = {"status": "⚠️", "message": "No checkpoint"}
    # Files
    if FILE_CHECKPOINT_FILE.exists():
        try:
            with open(FILE_CHECKPOINT_FILE) as f:
                file_list = json.load(f)
            tracked = len(file_list)
            text_files = len(list(TEXT_RAG_DIR.glob("*.txt"))) if TEXT_RAG_DIR.exists() else 0
            html_files = len(list(HTML_RAG_DIR.glob("*.html"))) if HTML_RAG_DIR.exists() else 0
            results["files"] = {
                "status": "📁",
                "message": f"Tracked: {tracked}, Actual: {text_files}",
                "details": {"tracked": tracked, "text": text_files, "html": html_files}
            }
        except:
            results["files"] = {"status": "⚠️", "message": "File check failed"}
    else:
        results["files"] = {"status": "⚠️", "message": "No file checkpoint"}
    return results

def system_health():
    """Collect local system stats."""
    health = {}
    try:
        with open("/proc/loadavg", "r") as f:
            load = f.read().split()[0:3]
            health["load"] = [float(x) for x in load]
    except:
        health["load"] = [0,0,0]
    try:
        with open("/proc/meminfo", "r") as f:
            lines = f.readlines()
        total = int(lines[0].split()[1]) // 1024   # MB
        free = int(lines[1].split()[1]) // 1024
        used = total - free
        percent = (used / total) * 100
        health["memory"] = {"total_mb": total, "used_mb": used, "free_mb": free, "percent": percent}
    except:
        health["memory"] = {"total_mb": 0, "used_mb": 0, "free_mb": 0, "percent": 0}
    try:
        import shutil
        usage = shutil.disk_usage(POOLED_STORAGE)
        health["disk"] = {
            "total_gb": usage.total / (1024**3),
            "used_gb": usage.used / (1024**3),
            "free_gb": usage.free / (1024**3),
            "percent": (usage.used / usage.total) * 100
        }
    except:
        health["disk"] = {"total_gb": 0, "used_gb": 0, "free_gb": 0, "percent": 0}
    return health

def generate_recommendations(nexus, rag):
    rec = []
    if nexus.get("status") == "❌":
        rec.append("🚨 Nexus Load Balancer unreachable – check if nexus_lb_V*.py is running")
    elif nexus.get("details", {}).get("online_count", 0) == 0:
        rec.append("⚠️ No nodes online in Nexus – ensure nodes are reachable and Ollama is running")
    # Check for nodes with zero free RAM (likely SSH failure)
    nodes = nexus.get("details", {}).get("nodes", {})
    nodes_without_ram = [n for n, info in nodes.items() if info.get("online") and info.get("ram_free_mb", 0) == 0]
    if nodes_without_ram:
        rec.append(f"⚠️ {len(nodes_without_ram)} nodes have unknown RAM (SSH may need keys): {', '.join(nodes_without_ram[:3])}")
    if rag.get("process", {}).get("status") == "❌":
        rec.append("⚠️ RAG processor not running – start with python3 7_Wikidump_RAGing_POC_v9.py")
    elif rag.get("checkpoint", {}).get("details", {}).get("age_minutes", 0) > 10:
        rec.append("⚠️ Checkpoint is stale (>10 min) – processor may be stuck")
    files = rag.get("files", {}).get("details", {})
    if files.get("tracked", 0) != files.get("text", 0):
        rec.append("⚠️ File count mismatch – run diagnostic to fix file checkpoint")
    return rec

def update_status():
    """Refresh all status data."""
    nexus = check_nexus()
    rag = check_rag()
    sys_health = system_health()
    recs = generate_recommendations(nexus, rag)
    status_cache.update({
        "timestamp": datetime.now().isoformat(),
        "nexus": nexus,
        "rag": rag,
        "system": sys_health,
        "recommendations": recs
    })

# ------------------------------------------------------------
# Terminal output
# ------------------------------------------------------------
def print_terminal():
    """Print a beautiful noir‑style terminal display."""
    data = status_cache
    ts = data["timestamp"] or "?"
    print("\n" + "="*70)
    print(f"🕶️  CYBERDECK NEXUS MONITOR – {ts}")
    print("="*70)

    # Nexus
    nx = data["nexus"]
    print(f"\n🔌 NEXUS LOAD BALANCER  [{nx.get('status', '?')}]")
    print(f"   {nx.get('message', 'No data')}")
    if "details" in nx and nx["details"]:
        d = nx["details"]
        if "health" in d and d["health"]:
            h = d["health"]
            print(f"   Sessions: {h.get('active_sessions',0)} active / {h.get('total_sessions',0)} total")
            print(f"   Clients: {h.get('clients',0)} registered")
        if "nodes" in d:
            on = d.get("online_count", 0)
            tot = d.get("total_count", 0)
            print(f"   Nodes: {on}/{tot} online")
            for nid, info in d["nodes"].items():
                if info.get("online"):
                    mod_str = ", ".join(info.get("models", [])[:3])
                    if len(info.get("models", [])) > 3:
                        mod_str += "..."
                    print(f"     ✅ {nid}: {info['ip']} – {len(info.get('models',[]))} models, "
                          f"RAM free {info.get('ram_free_mb',0)} MB, load {info.get('load_avg',0)}")
                else:
                    print(f"     ❌ {nid}: {info['ip']} offline")

    # RAG
    rg = data["rag"]
    print(f"\n🔧 RAG PROCESSOR")
    proc = rg.get("process", {})
    print(f"   {proc.get('status','?')} Process: {proc.get('message','')}")
    if "cpu" in proc:
        print(f"     CPU: {proc['cpu']}% | MEM: {proc['mem']}%")
    cp = rg.get("checkpoint", {})
    if cp:
        print(f"   {cp.get('status','?')} Checkpoint: {cp.get('message','')}")
        if "details" in cp:
            d = cp["details"]
            print(f"     Pages: {d.get('pages',0)} | Age: {d.get('age_minutes',0)} min")
    fl = rg.get("files", {})
    if fl:
        print(f"   {fl.get('status','?')} Files: {fl.get('message','')}")
        if "details" in fl:
            d = fl["details"]
            if d.get("tracked",0) != d.get("text",0):
                print(f"     ⚠️ MISMATCH: tracked {d['tracked']} vs actual {d['text']}")

    # System
    sys = data["system"]
    print(f"\n💻 SYSTEM HEALTH")
    load = sys.get("load", [0,0,0])
    print(f"   📈 Load: {load[0]:.2f}, {load[1]:.2f}, {load[2]:.2f}")
    mem = sys.get("memory", {})
    if mem.get("total_mb",0):
        print(f"   🧠 Memory: {mem['percent']:.1f}% used ({mem['used_mb']/1024:.1f}G/{mem['total_mb']/1024:.1f}G)")
    disk = sys.get("disk", {})
    if disk.get("total_gb",0):
        print(f"   💾 Disk: {disk['percent']:.1f}% used ({disk['used_gb']:.1f}G/{disk['total_gb']:.1f}G)")

    # Recommendations
    recs = data["recommendations"]
    if recs:
        print("\n💡 RECOMMENDATIONS")
        for r in recs:
            print(f"   {r}")

    print("\n" + "="*70)
    print("⏳ Next update in 60 seconds (Ctrl+C to exit terminal, web UI keeps running)")
    print("🌐 Web dashboard: http://localhost:8880")
    print("="*70)

# ------------------------------------------------------------
# Web server
# ------------------------------------------------------------
class NoirHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/':
            self.send_response(200)
            self.send_header('Content-type', 'text/html; charset=utf-8')
            self.end_headers()
            self.wfile.write(HTML_PAGE.encode('utf-8'))
        elif self.path == '/api/status':
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(status_cache, indent=2, default=str).encode('utf-8'))
        elif self.path == '/api/nodes':
            nodes = status_cache.get("nexus", {}).get("details", {}).get("nodes", {})
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            self.wfile.write(json.dumps(nodes, indent=2, default=str).encode('utf-8'))
        else:
            self.send_response(404)
            self.end_headers()
            self.wfile.write(b'404 - Not Found')

    def log_message(self, format, *args):
        # Suppress default logging
        pass

def start_web_server():
    server = HTTPServer(('0.0.0.0', MONITOR_PORT), NoirHandler)
    print(f"🌐 Web dashboard available at http://localhost:{MONITOR_PORT}")
    server.serve_forever()

# HTML with noir style and auto-refresh via JavaScript
HTML_PAGE = """<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Cyberdeck Nexus Monitor</title>
    <style>
        body {
            background: #0a0f0f;
            color: #0f0;
            font-family: 'Courier New', monospace;
            margin: 0;
            padding: 20px;
        }
        .container {
            max-width: 1200px;
            margin: auto;
            background: rgba(0,0,0,0.8);
            border: 1px solid #0f0;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 20px rgba(0,255,0,0.2);
        }
        h1 {
            text-align: center;
            border-bottom: 1px solid #0f0;
            padding-bottom: 10px;
            text-shadow: 0 0 5px #0f0;
        }
        .status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        .card {
            background: #111;
            border: 1px solid #0f0;
            border-radius: 5px;
            padding: 15px;
            box-shadow: 0 0 5px rgba(0,255,0,0.3);
        }
        .card h2 {
            margin-top: 0;
            border-bottom: 1px dashed #0f0;
            display: inline-block;
        }
        .status-badge {
            float: right;
            font-weight: bold;
        }
        .ok { color: #0f0; }
        .warn { color: #ff0; }
        .crit { color: #f00; }
        .node-list {
            list-style: none;
            padding-left: 0;
        }
        .node-list li {
            margin: 5px 0;
            padding: 5px;
            background: #1a1a1a;
            border-left: 3px solid #0f0;
        }
        .node-offline {
            border-left-color: #f00;
            color: #aaa;
        }
        .timestamp {
            text-align: right;
            font-size: 0.8em;
            margin-top: 20px;
            color: #0f0;
        }
        .loading {
            text-align: center;
            animation: pulse 1s infinite;
        }
        @keyframes pulse {
            0% { opacity: 0.3; }
            100% { opacity: 1; }
        }
        a {
            color: #0f0;
            text-decoration: none;
        }
        a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>🕶️ CYBERDECK NEXUS MONITOR</h1>
    <div id="content">
        <div class="loading">Loading data...</div>
    </div>
    <div class="timestamp" id="timestamp"></div>
</div>

<script>
    async function fetchData() {
        try {
            const resp = await fetch('/api/status');
            const data = await resp.json();
            render(data);
        } catch(e) {
            document.getElementById('content').innerHTML = '<div class="crit">⚠️ Failed to fetch data. Is monitor running?</div>';
        }
    }

    function render(data) {
        const nx = data.nexus || {};
        const rag = data.rag || {};
        const sys = data.system || {};
        const recs = data.recommendations || [];
        const ts = data.timestamp || '?';

        let html = `<div class="status-grid">`;

        // Nexus card
        html += `<div class="card">
            <h2>🔌 NEXUS</h2>
            <span class="status-badge ${nx.status === '✅' ? 'ok' : (nx.status === '❌' ? 'crit' : 'warn')}">${nx.status || '?'}</span>
            <p>${nx.message || 'No data'}</p>`;
        if (nx.details && nx.details.health) {
            const h = nx.details.health;
            html += `<p>Sessions: ${h.active_sessions || 0} active / ${h.total_sessions || 0} total<br>Clients: ${h.clients || 0}</p>`;
        }
        if (nx.details && nx.details.nodes) {
            const nodes = nx.details.nodes;
            const online = Object.values(nodes).filter(n => n.online).length;
            html += `<p>Nodes: ${online}/${Object.keys(nodes).length} online</p><ul class="node-list">`;
            for (const [id, node] of Object.entries(nodes)) {
                const statusClass = node.online ? '' : 'node-offline';
                html += `<li class="${statusClass}">
                    <strong>${id}</strong> (${node.ip})<br>
                    ${node.online ? `✅ Models: ${node.models ? node.models.slice(0,3).join(', ') : 'none'}${node.models && node.models.length>3 ? '…' : ''}<br>
                    RAM free: ${node.ram_free_mb || 0} MB, Load: ${node.load_avg || 0}` : '❌ offline'}
                </li>`;
            }
            html += `</ul>`;
        }
        html += `</div>`;

        // RAG card
        html += `<div class="card">
            <h2>🔧 RAG</h2>`;
        const proc = rag.process || {};
        const procClass = proc.status === '✅' ? 'ok' : (proc.status === '❌' ? 'crit' : 'warn');
        html += `<p><span class="status-badge ${procClass}">${proc.status}</span> Process: ${proc.message || '?'}`;
        if (proc.cpu) html += `<br>CPU: ${proc.cpu}% | MEM: ${proc.mem}%`;
        html += `</p>`;
        const cp = rag.checkpoint || {};
        if (cp.status) {
            html += `<p><span class="status-badge">${cp.status}</span> Checkpoint: ${cp.message}`;
            if (cp.details) html += `<br>Pages: ${cp.details.pages} | Age: ${cp.details.age_minutes} min`;
            html += `</p>`;
        }
        const fl = rag.files || {};
        if (fl.status) {
            html += `<p><span class="status-badge">${fl.status}</span> Files: ${fl.message}`;
            if (fl.details && fl.details.tracked !== fl.details.text) {
                html += `<br><span class="warn">⚠️ Mismatch: tracked ${fl.details.tracked} vs actual ${fl.details.text}</span>`;
            }
            html += `</p>`;
        }
        html += `</div>`;

        // System card
        html += `<div class="card">
            <h2>💻 SYSTEM</h2>
            <p>📈 Load: ${sys.load ? sys.load.map(x => x.toFixed(2)).join(', ') : '?'}</p>
            <p>🧠 Memory: ${sys.memory ? `${sys.memory.percent.toFixed(1)}% used (${(sys.memory.used_mb/1024).toFixed(1)}G/${(sys.memory.total_mb/1024).toFixed(1)}G)` : '?'}</p>
            <p>💾 Disk: ${sys.disk ? `${sys.disk.percent.toFixed(1)}% used (${sys.disk.used_gb.toFixed(1)}G/${sys.disk.total_gb.toFixed(1)}G)` : '?'}</p>
        </div>`;

        html += `</div>`;

        // Recommendations
        if (recs.length) {
            html += `<div class="card"><h2>💡 RECOMMENDATIONS</h2><ul>`;
            recs.forEach(r => html += `<li>${r}</li>`);
            html += `</ul></div>`;
        }

        document.getElementById('content').innerHTML = html;
        document.getElementById('timestamp').innerHTML = `Last updated: ${ts}`;
    }

    // Refresh every 10 seconds
    fetchData();
    setInterval(fetchData, 10000);
</script>
</body>
</html>
"""

# ------------------------------------------------------------
# Main
# ------------------------------------------------------------
def monitor_loop():
    """Periodically update status and print to terminal."""
    while True:
        try:
            update_status()
            print_terminal()
        except Exception as e:
            print(f"Error in monitor loop: {e}")
        time.sleep(60)

if __name__ == "__main__":
    print("🕶️ Cyberdeck Nexus Monitor – starting...")
    # Start web server in a daemon thread
    web_thread = threading.Thread(target=start_web_server, daemon=True)
    web_thread.start()
    # Run terminal loop
    try:
        monitor_loop()
    except KeyboardInterrupt:
        print("\n🛑 Monitor stopped.")

I have the Class is not integrated yet into the pipline, the loadbalancer has. Since I know which way my Deck
will head I soon will start coding again. - let the DeepSeek Harness code.

Part of the Cyberdeck AI Knowledge System.

#_