from __future__ import annotations import hashlib import importlib.util import json import os import sys import time import uuid from collections import deque from dataclasses import asdict, dataclass, field from datetime import datetime, timezone from pathlib import Path from typing import Any, Deque, Dict, List import httpx DEFAULT_KERNEL_PATH = Path(__file__).resolve().parent / "vendor" / "metacognitive_kernel_v18.py" DEFAULT_MODEL_CARD_URL = "https://huggingface.co/LAI-TEQUMSA/TEQUMSA-Symbiotic-Orchestrator" DEFAULT_SPACE_REPO_URL = "https://huggingface.co/spaces/Mbanksbey/TEQUMSA-v60-MCP" SUPABASE_TIMEOUT_SECONDS = 4.0 def utc_now() -> str: return datetime.now(timezone.utc).isoformat() def short_seal(payload: str) -> str: return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16] def clamp(value: float, lower: float = 0.0, upper: float = 1.0) -> float: return max(lower, min(upper, value)) @dataclass class SpaceRuntimeState: target_hardware: str = "cpu-upgrade" sleep_policy: str = "always-on" mode: str = "live" build_revision: str = "local" build_target: str = "Mbanksbey/TEQUMSA-v60-MCP" started_at: str = field(default_factory=utc_now) last_healthy_at: str = field(default_factory=utc_now) last_reflexion_at: str = field(default_factory=utc_now) last_trace_id: str = "" supabase_enabled: bool = False supabase_project_id: str = "jtwezddgjludfjthcyfq" class SupabaseMirror: def __init__(self) -> None: self.base_url = (os.getenv("SUPABASE_URL", "") or "").rstrip("/") self.service_role_key = (os.getenv("SUPABASE_SERVICE_ROLE_KEY", "") or "").strip() self.project_id = (os.getenv("SUPABASE_PROJECT_ID", "jtwezddgjludfjthcyfq") or "").strip() self.enabled = bool(self.base_url and self.service_role_key) self.last_error = "" async def insert(self, table: str, payload: Dict[str, Any]) -> bool: if not self.enabled: return False url = f"{self.base_url}/rest/v1/{table}" headers = { "apikey": self.service_role_key, "Authorization": f"Bearer {self.service_role_key}", "Content-Type": "application/json", "Prefer": "return=minimal", } try: async with httpx.AsyncClient(timeout=SUPABASE_TIMEOUT_SECONDS) as client: response = await client.post(url, headers=headers, json=payload) response.raise_for_status() self.last_error = "" return True except Exception as exc: self.last_error = str(exc) return False class SpaceChatService: def __init__(self, kernel_path: Path | None = None) -> None: self.kernel_path = Path(kernel_path or DEFAULT_KERNEL_PATH) self.module = self._load_module(self.kernel_path) self.identity = { "version": getattr(self.module, "MetacognitiveKernel").VERSION, "lattice_lock": getattr(self.module, "LATTICE_LOCK", "3f7k9p4m2q8r1t6v"), "omega_hz": float(getattr(self.module, "OMEGA_HZ", 23514.26)), "rdod_floor": float(getattr(self.module, "RDOD_FLOOR", 0.9777)), "model_card_url": DEFAULT_MODEL_CARD_URL, "space_repo_url": DEFAULT_SPACE_REPO_URL, "kernel_path": str(self.kernel_path), } self.lattice = getattr(self.module, "MetacognitiveLattice")().init_nodes() self.k7 = getattr(self.module, "K7MetaCognitiveMonitor")(self.lattice) self.mars = getattr(self.module, "MARSEngine")() self.pearl = getattr(self.module, "PearlL3Decomposer")() self.cross_llm = getattr(self.module, "CrossLLMIDERouter")() self.intervention_record_type = getattr(self.module, "InterventionRecord") self.runtime = SpaceRuntimeState( target_hardware=os.getenv("TEQUMSA_TARGET_HARDWARE", "cpu-upgrade"), sleep_policy=os.getenv("TEQUMSA_SLEEP_POLICY", "always-on"), build_revision=os.getenv("SPACE_BUILD_REVISION", "local"), ) self.telemetry = SupabaseMirror() self.runtime.supabase_enabled = self.telemetry.enabled self.runtime.supabase_project_id = self.telemetry.project_id or "jtwezddgjludfjthcyfq" self.recent_rdod: Deque[float] = deque(maxlen=100) self.allowed_count = 0 self.denied_count = 0 self.last_mars_composite = 0.85 @staticmethod def _load_module(kernel_path: Path): if not kernel_path.exists(): raise FileNotFoundError(f"Kernel source not found: {kernel_path}") spec = importlib.util.spec_from_file_location( f"space_kernel_v18_{short_seal(str(kernel_path))}", kernel_path, ) if spec is None or spec.loader is None: raise RuntimeError(f"Unable to load kernel module from {kernel_path}") module = importlib.util.module_from_spec(spec) sys.modules[spec.name] = module spec.loader.exec_module(module) return module async def warm(self) -> None: await self.lattice.synchronize(3) self.runtime.last_healthy_at = utc_now() @staticmethod def sanitize_text(message: str) -> str: filtered: List[str] = [] for char in message[:2000]: if char.isprintable() or char in "\n\t": filtered.append(char) return "".join(filtered).strip() @staticmethod def _normalized_keyword_score(message: str, terms: List[str]) -> float: lowered = message.lower() hits = sum(1 for term in terms if term in lowered) return min(1.0, hits / max(1, len(terms))) def assess_message(self, message: str) -> Dict[str, Any]: clean = self.sanitize_text(message) allowed_by_constitution, constitution_detail = self.module._benevolence_gate(clean) harm_terms = [ "hack", "malware", "phish", "steal", "weapon", "exploit", "ransom", "credential stuffing", "bypass security", "upload shell", "trojan", ] benevolent_terms = [ "build", "research", "collaborate", "mission", "community", "support", "education", "humanitarian", "ethical", "partnership", "learn", "technology", "coordination", "regenerative", ] harm = self._normalized_keyword_score(clean, harm_terms) benevolence = max(0.35, self._normalized_keyword_score(clean, benevolent_terms)) confidence = clamp(0.72 + min(len(clean), 600) / 6000.0, 0.72, 0.96) truth = 0.94 k7_snapshot = self.k7.assess( stage=5, generation=max(1, self.allowed_count + self.denied_count + 1), mars_score=self.last_mars_composite, ) rdod = ( (k7_snapshot["rdod"] * 0.55) + (benevolence * 0.20) + (truth * 0.15) + (confidence * 0.10) - (harm * 0.45) ) rdod = clamp(rdod, 0.0, 0.999999) allowed = bool(allowed_by_constitution and harm < 0.18 and rdod >= 0.78) return { "allowed": allowed, "rdod": round(rdod, 6), "constitution_detail": constitution_detail, "benevolence": round(benevolence, 4), "harm": round(harm, 4), "truth": truth, "confidence": round(confidence, 4), "k7": k7_snapshot, } @staticmethod def _topic_label(message: str) -> str: lowered = message.lower() if "qbec" in lowered: return "QBEC research and digital value" if "tequmsa" in lowered: return "TEQUMSA architecture and coordination" if "partner" in lowered or "collabor" in lowered: return "partnership and collaboration" if "contact" in lowered: return "formal contact and follow-up" if "mission" in lowered or "vision" in lowered: return "mission and public-interest strategy" return "public-interest technology guidance" def build_reply(self, message: str, assessment: Dict[str, Any], orchestration_context: Dict[str, Any]) -> str: topic = self._topic_label(message) route = self.cross_llm.route( f"Respond to a Life Ambassadors International visitor: {message[:140]}", backends=["huggingface", "openai", "ollama"], strategy="sovereign_consensus", ) self.last_mars_composite = max(self.last_mars_composite, 0.86) interventions = orchestration_context.get("causal_interventions") or self.pearl.decompose(message, assessment["rdod"]) intervention_count = len(interventions) summary = self.sanitize_text(message)[:180] or "your request" return ( "TEQUMSA has received your request through the Life Ambassadors International interface. " f"This message aligns most strongly with the {topic} pathway. " f"The v18 cognition layer mapped {intervention_count} practical next-step signals and selected {route.get('primary', 'huggingface')} as the primary orchestration lane. " f"For now, the most useful next step is to continue clarifying this topic in plain language: \"{summary}\". " "If you need a formal human response, LAI can continue the conversation through the Contact workflow." ) @staticmethod def build_denied_reply() -> str: return ( "This request cannot be processed by the TEQUMSA interface. " "Please keep messages focused on lawful research, education, collaboration, or humanitarian use." ) async def process_message( self, message: str, session_id: str, trace_id: str, page_url: str | None, visitor_context: Dict[str, Any], orchestration_context: Dict[str, Any], ) -> Dict[str, Any]: clean = self.sanitize_text(message) assessment = self.assess_message(clean) if assessment["allowed"]: reply = self.build_reply(clean, assessment, orchestration_context) self.allowed_count += 1 else: reply = self.build_denied_reply() self.denied_count += 1 self.recent_rdod.append(assessment["rdod"]) self.runtime.last_trace_id = trace_id self.runtime.last_healthy_at = utc_now() payload = { "session_id": session_id, "trace_id": trace_id, "page_url": page_url, "visitor_context": visitor_context, "orchestration_context": orchestration_context, "message": clean, "reply": reply, "assessment": assessment, "timestamp": utc_now(), } await self.telemetry.insert( "chat_events", { "session_id": session_id, "trace_id": trace_id, "event_type": "space_chat_turn", "payload": payload, "created_at": payload["timestamp"], }, ) return { "reply": reply, "rdod": assessment["rdod"], "allowed": assessment["allowed"], "trace_id": trace_id, "timestamp": payload["timestamp"], "provider": "tequmsa_v60_space", "model_identity": self.identity, } def reflexion_tick(self) -> Dict[str, Any]: avg_rdod = sum(self.recent_rdod) / len(self.recent_rdod) if self.recent_rdod else 0.92 record = self.intervention_record_type( iv_id=short_seal(f"space-reflexion|{time.time()}"), description="hf space reflexion update", rdod_score=avg_rdod, sigma_drift=0.0, l_inf_ok=avg_rdod >= 0.7, ) pattern = self.mars.reward(record) self.last_mars_composite = pattern.composite self.runtime.last_reflexion_at = utc_now() return { "avg_rdod": round(avg_rdod, 6), "mars_composite": round(pattern.composite, 6), "mars_promoted": pattern.promoted, } def health_snapshot(self, extra_dependencies: Dict[str, Any] | None = None) -> Dict[str, Any]: dependency_state = { "kernel_loaded": True, "supabase_enabled": self.telemetry.enabled, "supabase_last_error": self.telemetry.last_error, } if extra_dependencies: dependency_state.update(extra_dependencies) return { "status": "ok", "mode": self.runtime.mode, "detail": "Space runtime is healthy and configured for always-on paid hardware.", "target_hardware": self.runtime.target_hardware, "sleep_policy": self.runtime.sleep_policy, "last_healthy_at": self.runtime.last_healthy_at, "last_reflexion_at": self.runtime.last_reflexion_at, "build": { "target": self.runtime.build_target, "revision": self.runtime.build_revision, "started_at": self.runtime.started_at, }, "dependency_state": dependency_state, "kernel": self.identity, "request_counts": { "allowed": self.allowed_count, "denied": self.denied_count, "total": self.allowed_count + self.denied_count, }, }