""" one.OS Backend — Tornado-based REST API Autonomous Cognitive Ecosystem Platform """ import tornado.ioloop import tornado.web import tornado.httpserver import json import uuid import random import time import datetime import os # ─── In-Memory State ─────────────────────────────────────────────────────────── STATE = { "workloads": [], "clean_rooms": [], "contracts": [], "agents": [ {"id": "a-001", "name": "WeMeet-Agent", "status": "active", "tasks": 3, "type": "collaboration"}, {"id": "a-002", "name": "Project-Agent", "status": "active", "tasks": 7, "type": "intelligence"}, {"id": "a-003", "name": "RiskAgent", "status": "standby", "tasks": 1, "type": "compliance"}, {"id": "a-004", "name": "Legal-Agent", "status": "active", "tasks": 5, "type": "legal"}, {"id": "a-005", "name": "IP-Guardian", "status": "active", "tasks": 2, "type": "ip"}, ], "users": [ {"id": "u-001", "name": "Prof. Dr. Schmidt", "org": "HHN", "role": "Researcher", "sphere": "academic"}, {"id": "u-002", "name": "Anna Weber", "org": "Porsche AG", "role": "Engineer", "sphere": "commercial"}, {"id": "u-003", "name": "Max Müller", "org": "TUM", "role": "Student", "sphere": "academic"}, {"id": "u-004", "name": "Dr. Fischer", "org": "Fraunhofer", "role": "Scientist", "sphere": "academic"}, {"id": "u-005", "name": "Laura Klein", "org": "ebmpapst", "role": "PM", "sphere": "commercial"}, ], "compliance_log": [], "orchestration_tasks": [], "projects": [], "ip_records": [], } METRICS = { "total_compute_tb": 42.8, "active_workloads": 12, "active_clean_rooms": 5, "compliance_score": 98.2, "active_agents": 4, "collaborations": 27, "legal_latency_ms": 380, "ip_protected": 134, "users_online": 89, "data_processed_gb": 1847, "innovation_index": 9.1, "uptime_percent": 99.97, } RESOURCE_POOL = { "cpu_cores_total": 1024, "cpu_cores_used": 387, "gpu_units_total": 256, "gpu_units_used": 112, "tpu_units_total": 64, "tpu_units_used": 18, "storage_tb_total": 500, "storage_tb_used": 187, "ram_tb_total": 128, "ram_tb_used": 54, "network_gbps": 400, } # ─── Base Handler ─────────────────────────────────────────────────────────────── class BaseHandler(tornado.web.RequestHandler): def set_default_headers(self): self.set_header("Content-Type", "application/json") self.set_header("Access-Control-Allow-Origin", "*") self.set_header("Access-Control-Allow-Headers", "Content-Type") self.set_header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS") def options(self, *args, **kwargs): self.set_status(204) self.finish() def json(self, data, status=200): self.set_status(status) self.write(json.dumps(data, default=str)) def body(self): try: return json.loads(self.request.body) except Exception: return {} def ts(): return datetime.datetime.now().isoformat() # ─── Dashboard ───────────────────────────────────────────────────────────────── class MetricsHandler(BaseHandler): def get(self): # Simulate live fluctuation m = dict(METRICS) m["users_online"] += random.randint(-3, 5) m["data_processed_gb"] += random.randint(0, 20) m["legal_latency_ms"] = max(200, m["legal_latency_ms"] + random.randint(-30, 30)) m["active_workloads"] = len(STATE["workloads"]) + 12 m["active_clean_rooms"] = len(STATE["clean_rooms"]) + 5 m["collaborations"] = len(STATE["users"]) * 3 + len(STATE["clean_rooms"]) m["ip_protected"] += len(STATE["ip_records"]) m["timestamp"] = ts() self.json(m) class StatusHandler(BaseHandler): def get(self): layers = { "liquid_ai": {"status": "operational", "health": 99.2, "version": "2.1.0"}, "legal_fabric":{"status": "operational", "health": 98.7, "version": "1.8.3"}, "ace": {"status": "operational", "health": 99.8, "version": "3.0.1"}, "ambient": {"status": "operational", "health": 97.4, "version": "1.5.2"}, "icp": {"status": "operational", "health": 99.1, "version": "2.0.0"}, } self.json({ "system": "one.OS", "version": "1.0.0-beta", "location":"Heilbronn Innovation Campus", "status": "operational", "layers": layers, "uptime": "99.97%", "timestamp": ts(), }) # ─── Liquid AI ───────────────────────────────────────────────────────────────── class LiquidResourcesHandler(BaseHandler): def get(self): r = dict(RESOURCE_POOL) r["cpu_cores_used"] += random.randint(-5, 5) r["gpu_units_used"] += random.randint(-2, 2) r["timestamp"] = ts() self.json(r) class LiquidAllocateHandler(BaseHandler): def post(self): body = self.body() name = body.get("name", f"Workload-{len(STATE['workloads'])+1}") cpu = body.get("cpu", random.randint(4, 32)) gpu = body.get("gpu", random.randint(1, 8)) storage = body.get("storage", random.randint(10, 200)) priority = body.get("priority", "normal") workload = { "id": str(uuid.uuid4())[:8], "name": name, "cpu_cores": cpu, "gpu_units": gpu, "storage_gb":storage, "priority": priority, "status": "running", "created_at":ts(), "owner": body.get("owner", "system"), } STATE["workloads"].append(workload) RESOURCE_POOL["cpu_cores_used"] += cpu RESOURCE_POOL["gpu_units_used"] += gpu self.json({"success": True, "workload": workload, "message": f"Workload '{name}' erfolgreich allokiert."}) class LiquidWorkloadsHandler(BaseHandler): def get(self): self.json({"workloads": STATE["workloads"], "count": len(STATE["workloads"])}) class LiquidTerminateHandler(BaseHandler): def delete(self, wid): before = len(STATE["workloads"]) w = next((x for x in STATE["workloads"] if x["id"] == wid), None) if w: STATE["workloads"] = [x for x in STATE["workloads"] if x["id"] != wid] RESOURCE_POOL["cpu_cores_used"] = max(0, RESOURCE_POOL["cpu_cores_used"] - w["cpu_cores"]) RESOURCE_POOL["gpu_units_used"] = max(0, RESOURCE_POOL["gpu_units_used"] - w["gpu_units"]) self.json({"success": True, "message": f"Workload {wid} beendet."}) else: self.json({"success": False, "message": "Workload nicht gefunden."}, 404) # ─── Sovereign Trust & Legal Fabric ──────────────────────────────────────────── class CleanRoomsHandler(BaseHandler): def get(self): self.json({"clean_rooms": STATE["clean_rooms"], "count": len(STATE["clean_rooms"])}) def post(self): body = self.body() room = { "id": str(uuid.uuid4())[:8], "name": body.get("name", f"DCR-{len(STATE['clean_rooms'])+1}"), "actors": body.get("actors", []), "purpose": body.get("purpose", "collaboration"), "sphere": body.get("sphere", "mixed"), "status": "active", "compliance": "verified", "ip_protected":True, "created_at": ts(), "blockchain_hash": "0x" + uuid.uuid4().hex[:40], } STATE["clean_rooms"].append(room) # Auto-trigger compliance check STATE["compliance_log"].append({ "id": str(uuid.uuid4())[:8], "room_id": room["id"], "result": "passed", "score": random.uniform(96, 100), "checked_at": ts(), }) self.json({"success": True, "clean_room": room, "message": f"Dynamic Clean Room '{room['name']}' erstellt."}) class ContractsHandler(BaseHandler): def get(self): self.json({"contracts": STATE["contracts"], "count": len(STATE["contracts"])}) def post(self): body = self.body() parties = body.get("parties", ["Actor A", "Actor B"]) ctype = body.get("type", "research_collaboration") contract = { "id": str(uuid.uuid4())[:8], "type": ctype, "parties": parties, "status": "generated", "latency_ms": random.randint(120, 600), "ip_clauses": body.get("ip_clauses", True), "tax_sphere": body.get("tax_sphere", "mixed"), "legal_hash": "0x" + uuid.uuid4().hex[:32], "created_at": ts(), "valid_until": (datetime.datetime.now() + datetime.timedelta(days=365)).isoformat(), } STATE["contracts"].append(contract) self.json({"success": True, "contract": contract, "message": f"Vertrag in {contract['latency_ms']}ms generiert — Latenz von Monaten auf Millisekunden."}) class ComplianceCheckHandler(BaseHandler): def post(self): body = self.body() target = body.get("target", "workspace") score = random.uniform(93, 100) issues = [] if score > 97 else [{"code": "GDPR-ART-5", "severity": "low", "desc": "Datenspeicher-Policy prüfen"}] result = { "id": str(uuid.uuid4())[:8], "target": target, "score": round(score, 2), "status": "passed" if score > 95 else "warning", "issues": issues, "regulations":["GDPR", "BDSG", "EU AI Act", "Abgabenordnung"], "checked_at": ts(), } STATE["compliance_log"].append(result) self.json({"success": True, "result": result}) class IPProtectHandler(BaseHandler): def post(self): body = self.body() record = { "id": str(uuid.uuid4())[:8], "asset": body.get("asset", "Unknown Asset"), "owner": body.get("owner", "system"), "fingerprint": "0x" + uuid.uuid4().hex, "contract_id": body.get("contract_id", None), "status": "protected", "protected_at":ts(), } STATE["ip_records"].append(record) self.json({"success": True, "record": record, "message": "Geistiges Eigentum erfolgreich registriert und geschützt."}) class TaxSphereHandler(BaseHandler): def post(self): body = self.body() sphere = body.get("sphere", "mixed") items = body.get("items", []) result = { "id": str(uuid.uuid4())[:8], "sphere": sphere, "allocation": {"academic": 60, "commercial": 40} if sphere == "mixed" else {"academic" if sphere=="academic" else "commercial": 100}, "tax_rate": 0 if sphere=="academic" else 19, "invoices": len(items), "total_eur": random.randint(1000, 50000), "status": "calculated", "calculated_at":ts(), } self.json({"success": True, "result": result, "message": "Steuer-Autopilot Berechnung abgeschlossen."}) # ─── ACE Intelligence Layer ──────────────────────────────────────────────────── class AgentsHandler(BaseHandler): def get(self): agents = STATE["agents"] for a in agents: a["last_ping"] = ts() a["health"] = random.uniform(96, 100) self.json({"agents": agents, "count": len(agents)}) class OrchestrateHandler(BaseHandler): def post(self): body = self.body() task_id = str(uuid.uuid4())[:8] goal = body.get("goal", "Automatisierungsaufgabe") agents = ["WeMeet-Agent", "Project-Agent", "RiskAgent"] task = { "id": task_id, "goal": goal, "agents": agents, "steps": [ {"step": 1, "agent": "Project-Agent", "action": "Ziel analysieren", "status": "done"}, {"step": 2, "agent": "WeMeet-Agent", "action": "Stakeholder identifizieren","status": "done"}, {"step": 3, "agent": "RiskAgent", "action": "Risiken bewerten", "status": "running"}, {"step": 4, "agent": "Legal-Agent", "action": "Compliance prüfen", "status": "pending"}, {"step": 5, "agent": "IP-Guardian", "action": "IP sichern", "status": "pending"}, ], "status": "running", "started_at": ts(), "estimated_completion": "~2 Minuten", } STATE["orchestration_tasks"].append(task) for a in STATE["agents"]: if a["name"] in agents: a["tasks"] += 1 self.json({"success": True, "task": task, "message": f"Multi-Agenten-Orchestrierung gestartet für: '{goal}'"}) class ACETasksHandler(BaseHandler): def get(self): self.json({"tasks": STATE["orchestration_tasks"], "count": len(STATE["orchestration_tasks"])}) # ─── Ambient Interface ───────────────────────────────────────────────────────── class ProjectsHandler(BaseHandler): def get(self): self.json({"projects": STATE["projects"], "count": len(STATE["projects"])}) def post(self): body = self.body() project = { "id": str(uuid.uuid4())[:8], "name": body.get("name", f"Projekt-{len(STATE['projects'])+1}"), "description": body.get("description", ""), "actors": body.get("actors", []), "method": body.get("method", "agile"), "milestones": [ {"phase": "Ideenscreening", "status": "done", "due": "2026-Q1"}, {"phase": "Konzeptentwicklung", "status": "active", "due": "2026-Q2"}, {"phase": "Prototyping & Testing", "status": "pending", "due": "2026-Q3"}, {"phase": "Markteinführung", "status": "pending", "due": "2027-Q1"}, ], "board": { "open": random.randint(3, 10), "in_progress":random.randint(2, 6), "done": random.randint(1, 8), "risks": random.randint(0, 3), }, "status": "active", "created_at": ts(), } STATE["projects"].append(project) self.json({"success": True, "project": project, "message": f"Projekt '{project['name']}' erstellt — Workspace automatisch konfiguriert."}) # ─── ICP — Intelligent Campus Platform ───────────────────────────────────────── class UsersHandler(BaseHandler): def get(self): self.json({"users": STATE["users"], "count": len(STATE["users"]), "online": random.randint(60, 120)}) class ConnectActorsHandler(BaseHandler): def post(self): body = self.body() actor_a = body.get("actor_a", "Unknown A") actor_b = body.get("actor_b", "Unknown B") goal = body.get("goal", "Zusammenarbeit") collab = { "id": str(uuid.uuid4())[:8], "actor_a": actor_a, "actor_b": actor_b, "goal": goal, "status": "connected", "next_step":"Dynamic Clean Room automatisch vorbereitet", "connected_at": ts(), } self.json({"success": True, "collaboration": collab, "message": f"'{actor_a}' und '{actor_b}' erfolgreich verbunden für: {goal}"}) class ComplianceLogHandler(BaseHandler): def get(self): self.json({"log": STATE["compliance_log"][-20:], "total": len(STATE["compliance_log"])}) # ─── Static Frontend ─────────────────────────────────────────────────────────── class MainHandler(tornado.web.RequestHandler): def get(self): self.redirect("/static/index.html") # ─── App Setup ───────────────────────────────────────────────────────────────── def make_app(): static_path = os.path.join(os.path.dirname(__file__), "static") return tornado.web.Application([ # Dashboard (r"/", MainHandler), (r"/api/metrics", MetricsHandler), (r"/api/status", StatusHandler), # Liquid AI (r"/api/liquid-ai/resources", LiquidResourcesHandler), (r"/api/liquid-ai/allocate", LiquidAllocateHandler), (r"/api/liquid-ai/workloads", LiquidWorkloadsHandler), (r"/api/liquid-ai/workloads/([^/]+)",LiquidTerminateHandler), # Legal Fabric (r"/api/legal/clean-rooms", CleanRoomsHandler), (r"/api/legal/contracts", ContractsHandler), (r"/api/legal/compliance/check", ComplianceCheckHandler), (r"/api/legal/ip/protect", IPProtectHandler), (r"/api/legal/tax/sphere", TaxSphereHandler), # ACE (r"/api/ace/agents", AgentsHandler), (r"/api/ace/orchestrate", OrchestrateHandler), (r"/api/ace/tasks", ACETasksHandler), # Ambient Interface (r"/api/ambient/projects", ProjectsHandler), # ICP (r"/api/icp/users", UsersHandler), (r"/api/icp/connect", ConnectActorsHandler), (r"/api/compliance/log", ComplianceLogHandler), # Static files (r"/static/(.*)", tornado.web.StaticFileHandler, {"path": static_path}), ], debug=False) if __name__ == "__main__": port = 8080 app = make_app() server = tornado.httpserver.HTTPServer(app) server.listen(port) print(f"✅ one.OS Backend läuft auf http://localhost:{port}") print(f"📡 API bereit — alle Routen registriert") tornado.ioloop.IOLoop.current().start()