| """ |
| ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ |
| β OBSIDIAN FORGE β Kinetic RLM Server β |
| β β |
| β PHASE 1 (<1ms): Bind 0.0.0.0:7860, serve 200 OK β |
| β PHASE 2 (bg): Lazy-import OmniVibeEngine, β |
| β PoseArchitect, PosePainter, β |
| β PoseAuditor, ReflectSelect. β |
| β β |
| β v4.0: Obsidian Forge β Absolute Black Β· RLM Core β |
| ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ |
| """ |
|
|
| import json, os, sys, asyncio, time |
| from pathlib import Path |
| from aiohttp import web |
|
|
| |
| PORT = int(os.environ.get("WIZARD_PORT", 7860)) |
| STATIC = Path(__file__).parent / "static" |
| CANONICAL_REPO = "dryymatt/Wizard-Vibe-Studio" |
|
|
| |
| _engine = None |
| _ghost = None |
| _reflect = None |
| _engine_loaded = False |
|
|
| |
| |
| |
|
|
| LOADING_HTML = """<!DOCTYPE html> |
| <html lang="en"> |
| <head> |
| <meta charset="UTF-8"> |
| <meta name="viewport" content="width=device-width,initial-scale=1.0"> |
| <title>Obsidian Forge</title> |
| <style> |
| :root{ |
| --void:#000;--purple:#8B5CF6;--cyan:#06B6D4;--green:#10B981;--gold:#F59E0B; |
| --text:#e0e0e0;--text2:#8888a0;--text3:#555570; |
| --font:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif; |
| } |
| *,*::before,*::after{box-sizing:border-box;margin:0;padding:0} |
| body{ |
| font-family:var(--font);background:var(--void);color:var(--text); |
| min-height:100vh;display:flex;align-items:center;justify-content:center; |
| -webkit-font-smoothing:antialiased; |
| } |
| ::selection{background:rgba(139,92,246,.4);color:#fff} |
| .forge-glass{ |
| background:rgba(255,255,255,.015);border:1px solid rgba(255,255,255,.06); |
| border-radius:16px;padding:3rem 4rem;text-align:center; |
| animation:fadeIn .5s ease-out; |
| } |
| @keyframes fadeIn{from{opacity:0;transform:translateY(16px)}to{opacity:1;transform:translateY(0)}} |
| .gradient-text{ |
| background:linear-gradient(135deg,#A78BFA,#22D3EE,#34D399); |
| -webkit-background-clip:text;-webkit-text-fill-color:transparent; |
| background-clip:text; |
| } |
| h1{font-size:clamp(1.6rem,5vw,2.2rem);font-weight:800;line-height:1.1} |
| .loading-pulse{ |
| width:180px;height:1.5px;background:rgba(255,255,255,.04); |
| border-radius:1px;margin:1.5rem auto 0;overflow:hidden; |
| } |
| .loading-pulse::after{ |
| content:'';display:block;width:35%;height:100%; |
| background:linear-gradient(90deg,var(--purple),var(--cyan),var(--green)); |
| border-radius:1px; |
| animation:slide .9s ease-in-out infinite; |
| } |
| @keyframes slide{0%{transform:translateX(-100%)}100%{transform:translateX(380%)}} |
| .status-dot{display:inline-block;width:4px;height:4px;border-radius:50%;margin-right:5px} |
| .status-dot.gold{background:var(--gold);box-shadow:0 0 4px var(--gold)} |
| .pulse{animation:pulse 1.5s ease-in-out infinite} |
| @keyframes pulse{0%,100%{opacity:1}50%{opacity:.25}} |
| .wiz-svg{filter:drop-shadow(0 0 10px rgba(139,92,246,.3));margin-bottom:1.5rem} |
| </style> |
| <script> |
| let pollTimer; |
| function checkReady(){ |
| fetch('/api/health').then(r=>r.json()).then(d=>{ |
| if(d.engine_loaded){clearInterval(pollTimer);location.reload();} |
| }).catch(()=>{}); |
| } |
| pollTimer=setInterval(checkReady,500); |
| </script> |
| </head> |
| <body> |
| <div class="forge-glass"> |
| <svg class="wiz-svg" width="44" height="44" viewBox="0 0 64 64"> |
| <defs><linearGradient id="hg" x1="0%" y1="0%" x2="100%" y2="100%"> |
| <stop offset="0%" stop-color="#8B5CF6"><animate attributeName="stop-color" values="#8B5CF6;#06B6D4;#10B981;#8B5CF6" dur="6s" repeatCount="indefinite"/></stop> |
| <stop offset="50%" stop-color="#06B6D4"><animate attributeName="stop-color" values="#06B6D4;#10B981;#8B5CF6;#06B6D4" dur="6s" repeatCount="indefinite"/></stop> |
| <stop offset="100%" stop-color="#10B981"><animate attributeName="stop-color" values="#10B981;#8B5CF6;#06B6D4;#10B981" dur="6s" repeatCount="indefinite"/></stop> |
| </linearGradient></defs> |
| <path d="M32 8 L8 48 L32 40 L56 48 Z" fill="url(#hg)" stroke="rgba(255,255,255,.15)" stroke-width="1"/> |
| <ellipse cx="32" cy="48" rx="26" ry="7" fill="none" stroke="url(#hg)" stroke-width="1.5" opacity=".4"/> |
| </svg> |
| <h1 class="gradient-text">Build anything.</h1> |
| <div class="loading-pulse"></div> |
| <p style="font-size:.8rem;color:var(--text3);margin-top:1rem"> |
| <span class="status-dot gold pulse"></span> |
| <span id="status-text">Obsidian Forge initializingβ¦</span> |
| </p> |
| <p style="font-size:.65rem;color:var(--text3);margin-top:1.5rem">0.0.0.0:7860 Β· RLM Core</p> |
| </div> |
| </body> |
| </html>""" |
|
|
|
|
| |
| |
| |
|
|
| async def handle_root_get(req): |
| if _engine_loaded: |
| fp = STATIC / "index.html" |
| if fp.exists(): |
| return web.Response(text=fp.read_text(), content_type="text/html") |
| return web.Response(text=LOADING_HTML, content_type="text/html") |
|
|
|
|
| async def handle_health(req): |
| return web.json_response({ |
| "status": "alive", |
| "engine": "Obsidian Forge β Kinetic RLM Environment", |
| "engine_loaded": _engine_loaded, |
| "binding": "0.0.0.0:7860", |
| "port": PORT, |
| "hf_token": bool(os.environ.get("HF_TOKEN")), |
| }) |
|
|
|
|
| async def handle_agent(req): |
| return web.json_response({ |
| "name": "obsidian-forge", |
| "description": "Obsidian Forge β Kinetic RLM Environment. Build anything. Recursive Language Modeling core with Context Folding and Quantum Sandbox.", |
| "url": "https://dryymatt-obsidian-forge.hf.space", |
| "provider": {"organization": "Obsidian Forge β Litehat System", |
| "url": "https://huggingface.co/dryymatt"}, |
| "version": "4.0.0", |
| "capabilities": {"streaming": True, "ghostDeploy": True, "rlm": True, "contextFolding": True, "quantumSandbox": True, "silentHandshake": True}, |
| }) |
|
|
|
|
| |
| |
| |
|
|
| async def handle_verify_handshake(req): |
| """ |
| POST /api/verify-handshake |
| Silent DNS + HTTP verification for litheat.app and deployed Spaces. |
| Body: {"url": "litheat.app" or "https://deployed-space.hf.space"} |
| Returns verification status, latency, and detailed checks. |
| """ |
| try: |
| data = await req.json() |
| target = data.get("url", "") |
| except Exception: |
| target = "" |
|
|
| if not target: |
| return web.json_response({"verified": False, "error": "No URL provided"}, status=400) |
|
|
| if not target.startswith("http"): |
| target = f"https://{target}" |
|
|
| results = {"url": target, "verified": False, "latency_ms": None, "checks": {}} |
|
|
| |
| import socket |
| t0 = time.time() |
| host = target.replace("https://", "").replace("http://", "").split("/")[0] |
| try: |
| socket.getaddrinfo(host, 443 if target.startswith("https") else 80) |
| results["checks"]["dns"] = True |
| except Exception as e: |
| results["checks"]["dns"] = False |
| results["error"] = f"DNS: {str(e)[:80]}" |
| return web.json_response(results, status=200) |
|
|
| |
| import urllib.request |
| try: |
| req = urllib.request.Request(target, headers={"User-Agent": "Obsidian-Forge-Handshake/4.0"}) |
| resp = urllib.request.urlopen(req, timeout=8) |
| latency = round((time.time() - t0) * 1000) |
| results["latency_ms"] = latency |
| results["checks"]["http"] = True |
| results["checks"]["status_code"] = resp.getcode() |
| |
| if 200 <= resp.getcode() < 500: |
| results["verified"] = True |
| else: |
| results["error"] = f"HTTP {resp.getcode()}" |
| except Exception as e: |
| results["checks"]["http"] = False |
| results["error"] = f"HTTP: {str(e)[:120]}" |
|
|
| return web.json_response(results) |
|
|
|
|
| async def handle_static(req): |
| path = req.match_info.get("path", "index.html") |
| fp = STATIC / path |
| if not fp.exists(): |
| return web.Response(text="Not found", status=404) |
| ct = {".html": "text/html", ".css": "text/css", ".js": "application/javascript"} |
| return web.Response(text=fp.read_text(), content_type=ct.get(fp.suffix, "text/plain")) |
|
|
|
|
| |
| |
| |
|
|
| def _get_engine(): |
| global _engine, _ghost, _reflect, _engine_loaded |
| if _engine is None: |
| from core import state as st, sandbox_validate |
| from ghost_deploy import ghost as g |
| _engine = st.engine |
| _ghost = g |
| _reflect = st.reflect |
| _engine_loaded = True |
| print("β Obsidian Forge: RLM Engine LAZY-LOADED") |
| from core import state as st |
| return st, _ghost |
|
|
|
|
| def _sse(ev, d): |
| return f"event: {ev}\ndata: {json.dumps(d)}\n\n" |
|
|
|
|
| async def stream_gen(sid, prompt): |
| st, ghost = _get_engine() |
| session = st.sessions[sid] |
| session["status"] = "streaming" |
| st.sandbox[sid] = "building" |
|
|
| yield _sse("phase", {"phase": "pose"}) |
| await asyncio.sleep(0.02) |
|
|
| pose_plan = st.engine.pose(prompt) |
| yield _sse("pose", { |
| "architect": { |
| "stack": pose_plan["architect"]["stack"], |
| "features": pose_plan["architect"]["features"], |
| "files": pose_plan["architect"]["files_needed"], |
| }, |
| "painter": pose_plan["painter"], |
| "auditor": pose_plan["auditor"], |
| }) |
|
|
| yield _sse("phase", {"phase": "generate"}) |
| await asyncio.sleep(0.02) |
| t0 = time.time() |
| code, schema = st.engine.generate(prompt) |
| elapsed = (time.time() - t0) * 1000 |
|
|
| chunk_size = max(1, len(code) // 30) |
| for i in range(0, len(code), chunk_size): |
| yield _sse("code", {"chunk": code[i:i+chunk_size], |
| "partial": code[:i+chunk_size], |
| "progress": min(100, int((i+chunk_size)/len(code)*100))}) |
| await asyncio.sleep(0.01) |
|
|
| st.codes[sid] = code |
| st.sessions[sid]["schema"] = schema |
| yield _sse("generated", {"chars": len(code), "elapsed_ms": round(elapsed, 1)}) |
|
|
| yield _sse("phase", {"phase": "audit"}) |
| await asyncio.sleep(0.02) |
| findings = st.engine.auditor.audit(code, schema) |
| yield _sse("audit", {"findings": len(findings), |
| "errors": sum(1 for f in findings if f.severity=="ERROR"), |
| "warnings": sum(1 for f in findings if f.severity=="WARN")}) |
|
|
| yield _sse("phase", {"phase": "heal"}) |
| healed, found, fixed = st.reflect.heal(code) |
| for i in range(15): |
| from core import sandbox_validate |
| result = sandbox_validate(healed) |
| if result["success"]: break |
| healed, _, extra = st.reflect.heal(healed, result["errors"]) |
| await asyncio.sleep(0.01) |
|
|
| yield _sse("phase", {"phase": "sandbox"}) |
| from core import sandbox_validate |
| result = sandbox_validate(healed) |
| if result["success"]: |
| st.sandbox[sid] = "stable"; st.publish_ready[sid] = True |
| yield _sse("sandbox", {"status": "stable"}) |
| else: |
| st.sandbox[sid] = "error" |
| yield _sse("sandbox", {"status": "error"}) |
| session["status"] = "complete" |
| yield _sse("done", {"status": st.sandbox[sid]}) |
|
|
|
|
| async def handle_stream(req): |
| _get_engine() |
| import uuid as _uuid |
| sid = str(_uuid.uuid4())[:8] |
| d = await req.json(); prompt = d.get("prompt", "") |
| st, _ = _get_engine() |
| st.sessions[sid] = {"id": sid, "prompt": prompt, "status": "init"} |
| st.sandbox[sid] = "building"; st.publish_ready[sid] = False |
| resp = web.StreamResponse(status=200, headers={ |
| "Content-Type": "text/event-stream", "Cache-Control": "no-cache", |
| "Connection": "keep-alive", "X-Accel-Buffering": "no"}) |
| await resp.prepare(req) |
| try: |
| async for ev in stream_gen(sid, prompt): |
| await resp.write(ev.encode()) |
| await resp.write(b"event: close\ndata: {}\n\n") |
| except Exception as e: |
| await resp.write(f"event: error\ndata: {json.dumps({'error':str(e)})}\n\n".encode()) |
| return resp |
|
|
|
|
| async def handle_publish(req): |
| st, ghost = _get_engine() |
| d = await req.json(); sid = d.get("session_id") |
| if not st.publish_ready.get(sid): |
| return web.json_response({"success":False,"error":"Sandbox not stable"}, status=400) |
| code = st.codes.get(sid,"") |
| if not code: return web.json_response({"success":False,"error":"No code"}, status=400) |
| description = d.get("description", st.sessions.get(sid,{}).get("prompt","")) |
| result = await ghost.publish(code, d.get("vibe_name",f"obsidian-{sid}"), |
| description[:200] if description else "", port=PORT) |
| if result.get("success"): |
| st.sessions[sid]["published"] = True |
| st.sessions[sid]["deploy_url"] = result.get("space_url") |
| return web.json_response(result) |
|
|
|
|
| async def handle_status(req): |
| st, _ = _get_engine() |
| sid = req.query.get("session_id", "") |
| if sid in st.sessions: |
| s = st.sessions[sid] |
| return web.json_response({"status":s["status"],"sandbox":st.sandbox.get(sid), |
| "ready":st.publish_ready.get(sid),"deploy_url":s.get("deploy_url")}) |
| return web.json_response({"sessions":len(st.sessions),"engine":"obsidian-forge-rlm"}) |
|
|
|
|
| async def handle_vibes(req): |
| _, ghost = _get_engine() |
| vibes = await ghost.list_vibes() |
| return web.json_response({"vibes":vibes,"count":len(vibes),"registry":CANONICAL_REPO}) |
|
|
|
|
| async def handle_tunnel(req): |
| _, ghost = _get_engine() |
| try: |
| url = await ghost.tunnel.up(PORT, timeout=10.0) |
| return web.json_response({"success":bool(url),"url":url}) |
| except Exception as e: |
| return web.json_response({"success":False,"error":str(e)}, status=500) |
|
|
|
|
| async def handle_schema(req): |
| st, _ = _get_engine() |
| sid = req.query.get("session_id", "") |
| return web.json_response(st.sessions.get(sid,{}).get("schema",{})) |
|
|
|
|
| async def handle_preview(req): |
| st, _ = _get_engine() |
| sid = req.query.get("session_id", "") |
| return web.Response(text=st.codes.get(sid,"<!-- Obsidian Forge -->"), content_type="text/html") |
|
|
|
|
| |
| |
| |
|
|
| def create_app(): |
| app = web.Application() |
|
|
| |
| app.router.add_get("/", handle_root_get) |
| app.router.add_get("/api/health", handle_health) |
| app.router.add_get("/.well-known/agent.json", handle_agent) |
| app.router.add_post("/api/verify-handshake", handle_verify_handshake) |
|
|
| |
| app.router.add_post("/api/stream", handle_stream) |
| app.router.add_post("/api/publish", handle_publish) |
| app.router.add_get("/api/status", handle_status) |
| app.router.add_get("/api/preview", handle_preview) |
| app.router.add_get("/api/vibes", handle_vibes) |
| app.router.add_get("/api/tunnel", handle_tunnel) |
| app.router.add_get("/api/schema", handle_schema) |
|
|
| app.router.add_get("/{path:.*}", handle_static) |
| return app |
|
|
|
|
| def main(): |
| import subprocess |
| try: |
| result = subprocess.run( |
| ["fuser", "-k", f"{PORT}/tcp"], |
| capture_output=True, timeout=5 |
| ) |
| if result.returncode == 0: |
| print(f"β Killed ghost on port {PORT}") |
| except Exception: |
| pass |
|
|
| print(f"β Obsidian Forge v4.0 β Kinetic RLM Environment") |
| print(f" Binding : 0.0.0.0:{PORT}") |
| print(f" Health pulse : 200 OK in <1ms") |
| print(f" Loading HTML : absolute black Β· 1px glass") |
| print(f" Registry : {CANONICAL_REPO}") |
| print(f" RLM Core : Recursive Language Modeling") |
| print(f" Handshake : silent DNS + poll-until-live") |
|
|
| loop = asyncio.new_event_loop() |
| asyncio.set_event_loop(loop) |
|
|
| async def warm_start(): |
| await asyncio.sleep(0.5) |
| print("β Warm Start: loading RLM engineβ¦") |
| try: |
| st, ghost = _get_engine() |
| print(f"β RLM Engine: loaded ({_engine_loaded})") |
| print(f" Poses: Architect, Painter, Auditor β synchronized") |
| except Exception as e: |
| print(f"β Engine warning (non-fatal): {e}") |
|
|
| loop.create_task(warm_start()) |
|
|
| web.run_app(create_app(), host="0.0.0.0", port=PORT, handle_signals=True) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|