Upload server.py
Browse files17 unmodified lines181920212223242526273 unmodified lines313233343536373839404142434445464748498 unmodified lines585960616263641 unmodified line6667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529610 unmodified lines3073083093103113123133143153163173183193203213223233243253263273283293303313323333343 unmodified lines3383393403413423433443453463474 unmodified lines35235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940017 unmodified lines)from ghost_deploy import ghost, CANONICAL_REPO, PinggyTunnel# βββ STABLE VIBE: Port 8765 for HF Spaces Docker routing βββ# The Dockerfile exposes 8765; HF reverse proxy routes to it.# Override via WIZARD_PORT only in dev sandboxes.PORT = int(os.environ.get("WIZARD_PORT", 8765))STATIC = Path(__file__).parent / "static"WIZARD_HAT_COLOR = "steady-gold" # The Athanor is active3 unmodified linesasync def stream_gen(sid, prompt):"""Omni-Vibe streaming pipeline:1. POSE β all three agents analyze in parallel2. GENERATE β Pose Architect + Pose Painter produce code3. AUDIT β Pose Auditor verifies step-by-step4. HEAL β Reflect-Select loop until perfection5. DEPLOY β Ghost Deploy to HF Spaces + Pinggy tunnel"""session = st.sessions[sid]session["status"] = "streaming"st.sandbox[sid] = "building"# Phase 1: Poseyield _sse("phase", {"phase": "pose", "hat": WIZARD_HAT_COLOR})await asyncio.sleep(0.05)8 unmodified lines"auditor": pose_plan["auditor"],})# Phase 2: Generateyield _sse("phase", {"phase": "generate"})await asyncio.sleep(0.05)1 unmodified linecode, schema = st.engine.generate(prompt)elapsed = (time.time() - t0) * 1000# Stream in chunks for live UIchunk_size = max(1, len(code) // 30)for i in range(0, len(code), chunk_size):chunk = code[i:i + chunk_size]yield _sse("code", {"chunk": chunk,"partial": code[:i + chunk_size],"progress": min(100, int((i + chunk_size) / len(code) * 100)),})await asyncio.sleep(0.015)st.codes[sid] = codest.sessions[sid]["schema"] = schemayield _sse("generated", {"chars": len(code),"elapsed_ms": round(elapsed, 1),"schema": {k: v for k, v in schema.items() if k != "files_needed"},})# Phase 3: Audityield _sse("phase", {"phase": "audit"})await asyncio.sleep(0.05)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"),"details": [{"line": f.line, "severity": f.severity, "message": f.message}for f in findings[:5]],})# Phase 4: Heal (Reflect-Select)yield _sse("phase", {"phase": "heal"})code, auto_fixes = st.engine.auditor.heal_findings(code, findings)st.codes[sid] = codehealed, found, fixed = st.reflect.heal(code)total_heals = fixed + auto_fixesfor i in range(15):result = sandbox_validate(healed)if result["success"]:breakhealed, _, extra = st.reflect.heal(healed, result["errors"])total_heals += extrast.codes[sid] = healedawait asyncio.sleep(0.01)yield _sse("heal", {"auto_fixes": auto_fixes,"reflect_fixes": fixed,"total_heals": total_heals,"loop_iterations": i + 1,})# Phase 5: Sandbox Validationyield _sse("phase", {"phase": "sandbox"})result = sandbox_validate(healed)if result["success"]:st.sandbox[sid] = "stable"st.publish_ready[sid] = Trueyield _sse("sandbox", {"status": "stable", "errors": 0, "hat": "steady-gold"})else:st.sandbox[sid] = "error"yield _sse("sandbox", {"status": "error", "errors": result["errors"]})session["status"] = "complete"yield _sse("done", {"status": st.sandbox[sid],"hat": "steady-gold" if st.sandbox[sid] == "stable" else "red-glow",})async def handle_stream(req):sid = str(uuid.uuid4())[:8]d = await req.json()prompt = d.get("prompt", "")st.sessions[sid] = {"id": sid, "prompt": prompt, "status": "init"}st.sandbox[sid] = "building"st.publish_ready[sid] = Falseresp = 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 respasync def handle_publish(req):d = await req.json()sid = d.get("session_id")vibe_name = d.get("vibe_name", f"omni-vibe-{sid}")if not st.publish_ready.get(sid):return web.json_response({"success": False, "error": "Sandbox not stable β Pose Auditor requires perfection."},status=400,)code = st.codes.get(sid, "")if not code:return web.json_response({"success": False, "error": "No code generated"}, status=400)description = d.get("description", st.sessions.get(sid, {}).get("prompt", ""))result = await ghost.publish(code, vibe_name, description[:200] if description else "", port=PORT)if result.get("success"):st.sessions[sid]["published"] = Truest.sessions[sid]["deploy_url"] = result.get("space_url")st.sessions[sid]["tunnel_url"] = result.get("tunnel_url")return web.json_response(result)async def handle_health(req):return web.json_response({"status": "alive","engine": "Omni-Vibe Studio β Specialized Swarm","protocol": "omni-vibe / tokenless / shadow-hosting","registry": CANONICAL_REPO,"lifert": True,"poses": {"architect": "full-stack + zero-DB + Google OAuth","painter": "Liquid Glass design system","auditor": "step-by-step verification",},"hat": WIZARD_HAT_COLOR,"hf_token": bool(os.environ.get("HF_TOKEN")),})async def handle_agent(req):return web.json_response(ghost.generate_agent_card("omni-vibe-studio","Omni-Vibe Studio β Specialized AI Swarm. Pose Architect designs full-stack schemas with zero-config DB and Google OAuth. Pose Painter enforces Liquid Glass design. Pose Auditor verifies step-by-step. LiteRT engine for sub-second latency.","https://dryymatt-wizard-vibe-studio-v2.hf.space",))async def handle_preview(req):sid = req.query.get("session_id", "")return web.Response(text=st.codes.get(sid, "<!-- Omni-Vibe β no code -->"),content_type="text/html",)async def handle_status(req):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"),"tunnel_url": s.get("tunnel_url"),"hat": "steady-gold" if st.publish_ready.get(sid) else "cyan-blink",})return web.json_response({"sessions": len(st.sessions),"engine": "omni-vibe","hat": WIZARD_HAT_COLOR,})async def handle_vibes(req):vibes = await ghost.list_vibes()return web.json_response({"vibes": vibes,"count": len(vibes),"registry": CANONICAL_REPO,})async def handle_tunnel(req):"""Bring up an ephemeral Pinggy/Cloudflare tunnel for instant preview."""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):"""Get the full-stack schema for the current session."""sid = req.query.get("session_id", "")s = st.sessions.get(sid, {})schema = s.get("schema", {})return web.json_response(schema)# βββββββββββββββββββββββββββββββββββββββββββββββββββββββ# ROOT HANDLER β HF Platform Health-Check Protocol# βββββββββββββββββββββββββββββββββββββββββββββββββββββββ# HF Spaces sends periodic HEAD/GET probes to /.# aiohttp auto-registers HEAD for every GET route.# A 404 or timeout triggers "Starting" loops.# This handler returns 200 OK in <1ms.async def handle_root_get(req):"""GET / β Liquid Glass landing page with 200 OK."""fp = STATIC / "index.html"if fp.exists():return web.Response(text=fp.read_text(), content_type="text/html")return web.Response(text=INDEX_FALLBACK, content_type="text/html")# Static fallback for when static/index.html is missingINDEX_FALLBACK = """<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">10 unmodified lines<body><div class="glass"><h1 class="gradient-text">Omni-Vibe Studio</h1><p>Specialized Swarm β Steady Gold</p><p style="font-size:.85rem;color:#606080;margin-top:2rem">Pose Architect Β· Pose Painter Β· Pose Auditor</p></div></body></html>"""# βββ Static file handler (for all non-root paths) βββasync def handle_static(req):path = req.match_info.get("path", "index.html")fp = STATIC / pathif 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 create_app():app = web.Application()# βββ Root: GET returns Liquid Glass; aiohttp auto-adds HEAD β 200 βββapp.router.add_get("/", handle_root_get)# βββ API routes βββapp.router.add_post("/api/stream", handle_stream)app.router.add_post("/api/publish", handle_publish)app.router.add_get("/api/status", handle_status)3 unmodified linesapp.router.add_get("/api/tunnel", handle_tunnel)app.router.add_get("/api/schema", handle_schema)app.router.add_get("/.well-known/agent.json", handle_agent)# βββ Catch-all static (after explicit root) βββapp.router.add_get("/{path:.*}", handle_static)return app4 unmodified linesprint(f" Pose Auditor : step-by-step verification")print(f" Athanor : LiteRT engine, sub-second latency")print(f" Registry : {CANONICAL_REPO}")print(f" Port : {PORT} (hardcoded 7860)")print(f" Hat : {WIZARD_HAT_COLOR}")# βββ Ghost-Link Persistence: start tunnel watchdog βββtunnel = ghost.tunnelloop = asyncio.new_event_loop()asyncio.set_event_loop(loop)async def tunnel_watchdog(interval: float = 30.0):"""Keep the Pinggy/Cloudflare tunnel alive. Restart on drop."""await asyncio.sleep(3) # let the server bind firstretries = 0while True:try:if tunnel.url is None:print(f"π Tunnel: attempting connect (retry #{retries})β¦")url = await tunnel.up(PORT, timeout=10.0)if url:print(f"π Tunnel: LIVE β {url}")retries = 0else:retries += 1else:# Health check: curl the tunnel URLalive = await _ping_url(tunnel.url)if not alive:print(f"π Tunnel: DEAD ({tunnel.url}) β restartingβ¦")tunnel.down()retries += 1except Exception as e:print(f"π Tunnel: error β {e}")retries += 1await asyncio.sleep(interval * (1 + min(retries, 5) * 0.5))async def _ping_url(url: str) -> bool:try:import aiohttpasync with aiohttp.ClientSession() as s:async with s.get(url, timeout=aiohttp.ClientTimeout(total=5)) as r:return r.status < 500except Exception:return Falseloop.create_task(tunnel_watchdog())web.run_app(create_app(), host="0.0.0.0", port=PORT, handle_signals=True)17 unmodified lines1819202122232425263 unmodified lines30313233343536373839408 unmodified lines4950515253541 unmodified line565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720810 unmodified lines2192202212222232242252262272282292302312322332342352362372382392403 unmodified lines2442452462472482492504 unmodified lines25525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929017 unmodified lines)from ghost_deploy import ghost, CANONICAL_REPO, PinggyTunnel# βββ VISIBILITY OVERRIDE: Port 7860 hardcoded, 0.0.0.0 binding βββ# Binds strictly to 0.0.0.0:7860. Override via WIZARD_PORT only in dev.PORT = int(os.environ.get("WIZARD_PORT", 7860))STATIC = Path(__file__).parent / "static"WIZARD_HAT_COLOR = "steady-gold" # The Athanor is active3 unmodified linesasync def stream_gen(sid, prompt):"""Omni-Vibe streaming pipeline: Pose β Generate β Audit β Heal β Sandbox"""session = st.sessions[sid]session["status"] = "streaming"st.sandbox[sid] = "building"yield _sse("phase", {"phase": "pose", "hat": WIZARD_HAT_COLOR})await asyncio.sleep(0.05)8 unmodified lines"auditor": pose_plan["auditor"],})yield _sse("phase", {"phase": "generate"})await asyncio.sleep(0.05)1 unmodified linecode, schema = st.engine.generate(prompt)elapsed = (time.time() - t0) * 1000chunk_size = max(1, len(code) // 30)for i in range(0, len(code), chunk_size):chunk = code[i:i + chunk_size]yield _sse("code", {"chunk": chunk, "partial": code[:i + chunk_size],"progress": min(100, int((i + chunk_size) / len(code) * 100)),})await asyncio.sleep(0.015)st.codes[sid] = codest.sessions[sid]["schema"] = schemayield _sse("generated", {"chars": len(code), "elapsed_ms": round(elapsed, 1),"schema": {k: v for k, v in schema.items() if k != "files_needed"}})yield _sse("phase", {"phase": "audit"})await asyncio.sleep(0.05)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"),"details": [{"line": f.line, "severity": f.severity, "message": f.message}for f in findings[:5]]})yield _sse("phase", {"phase": "heal"})code, auto_fixes = st.engine.auditor.heal_findings(code, findings)st.codes[sid] = codehealed, found, fixed = st.reflect.heal(code)total_heals = fixed + auto_fixesfor i in range(15):result = sandbox_validate(healed)if result["success"]: breakhealed, _, extra = st.reflect.heal(healed, result["errors"])total_heals += extrast.codes[sid] = healedawait asyncio.sleep(0.01)yield _sse("heal", {"auto_fixes": auto_fixes, "reflect_fixes": fixed,"total_heals": total_heals, "loop_iterations": i + 1})yield _sse("phase", {"phase": "sandbox"})result = sandbox_validate(healed)if result["success"]:st.sandbox[sid] = "stable"; st.publish_ready[sid] = Trueyield _sse("sandbox", {"status": "stable", "errors": 0, "hat": "steady-gold"})else:st.sandbox[sid] = "error"yield _sse("sandbox", {"status": "error", "errors": result["errors"]})session["status"] = "complete"yield _sse("done", {"status": st.sandbox[sid],"hat": "steady-gold" if st.sandbox[sid] == "stable" else "red-glow"})async def handle_stream(req):sid = str(uuid.uuid4())[:8]d = await req.json(); prompt = d.get("prompt", "")st.sessions[sid] = {"id": sid, "prompt": prompt, "status": "init"}st.sandbox[sid] = "building"; st.publish_ready[sid] = Falseresp = 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 respasync def handle_publish(req):d = await req.json(); sid = d.get("session_id")vibe_name = d.get("vibe_name", f"omni-vibe-{sid}")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, vibe_name, description[:200] if description else "", port=PORT)if result.get("success"):st.sessions[sid]["published"] = Truest.sessions[sid]["deploy_url"] = result.get("space_url")return web.json_response(result)async def handle_health(req):return web.json_response({"status": "alive", "engine": "Omni-Vibe Studio β Specialized Swarm","protocol": "omni-vibe / tokenless / shadow-hosting","registry": CANONICAL_REPO, "lifert": True,"poses": {"architect": "full-stack + zero-DB + Google OAuth","painter": "Liquid Glass design system","auditor": "step-by-step verification"},"hat": WIZARD_HAT_COLOR, "hf_token": bool(os.environ.get("HF_TOKEN")),"binding": "0.0.0.0:7860",})async def handle_agent(req):return web.json_response(ghost.generate_agent_card("omni-vibe-studio","Omni-Vibe Studio β Specialized AI Swarm. 0.0.0.0:7860. Zero-config DB, Google OAuth, Liquid Glass.","https://dryymatt-wizard-vibe-studio-v2.hf.space"))async def handle_preview(req):sid = req.query.get("session_id", "")return web.Response(text=st.codes.get(sid, "<!-- Omni-Vibe -->"), content_type="text/html")async def handle_status(req):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"),"hat":"steady-gold" if st.publish_ready.get(sid) else "cyan-blink"})return web.json_response({"sessions":len(st.sessions),"engine":"omni-vibe","hat":WIZARD_HAT_COLOR})async def handle_vibes(req):vibes = await ghost.list_vibes()return web.json_response({"vibes":vibes,"count":len(vibes),"registry":CANONICAL_REPO})async def handle_tunnel(req):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):sid = req.query.get("session_id", "")return web.json_response(st.sessions.get(sid,{}).get("schema",{}))# βββββββββββββββββ ROOT HANDLER βββββββββββββββββ# Returns valid HTML at / β no redirects, no auth.# aiohttp auto-registers HEAD β 200 OK for health probes.async def handle_root_get(req):fp = STATIC / "index.html"if fp.exists():return web.Response(text=fp.read_text(), content_type="text/html")return web.Response(text=INDEX_FALLBACK, content_type="text/html")INDEX_FALLBACK = """<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">10 unmodified lines<body><div class="glass"><h1 class="gradient-text">Omni-Vibe Studio</h1><p>Specialized Swarm β Steady Gold</p><p style="font-size:.85rem;color:#606080;margin-top:2rem">0.0.0.0:7860 Β· Pose Architect Β· Pose Painter Β· Pose Auditor</p></div></body></html>"""async def handle_static(req):path = req.match_info.get("path", "index.html")fp = STATIC / pathif 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 create_app():app = web.Application()app.router.add_get("/", handle_root_get)app.router.add_post("/api/stream", handle_stream)app.router.add_post("/api/publish", handle_publish)app.router.add_get("/api/status", handle_status)3 unmodified linesapp.router.add_get("/api/tunnel", handle_tunnel)app.router.add_get("/api/schema", handle_schema)app.router.add_get("/.well-known/agent.json", handle_agent)app.router.add_get("/{path:.*}", handle_static)return app4 unmodified linesprint(f" Pose Auditor : step-by-step verification")print(f" Athanor : LiteRT engine, sub-second latency")print(f" Registry : {CANONICAL_REPO}")print(f" Binding : 0.0.0.0:{PORT}")print(f" Hat : {WIZARD_HAT_COLOR}")tunnel = ghost.tunnelloop = asyncio.new_event_loop()asyncio.set_event_loop(loop)async def tunnel_watchdog(interval: float = 30.0):await asyncio.sleep(3)retries = 0while True:try:if tunnel.url is None:print(f"π Tunnel: connecting (retry #{retries})β¦")url = await tunnel.up(PORT, timeout=10.0)if url:print(f"π Tunnel: LIVE β {url}")retries = 0else: retries += 1else:import aiohttpasync with aiohttp.ClientSession() as s:async with s.get(tunnel.url, timeout=aiohttp.ClientTimeout(total=5)) as r:if r.status >= 500:print(f"π Tunnel: DEAD β restartingβ¦")tunnel.down(); retries += 1except Exception as e:print(f"π Tunnel: error β {e}"); retries += 1await asyncio.sleep(interval * (1 + min(retries, 5) * 0.5))loop.create_task(tunnel_watchdog())web.run_app(create_app(), host="0.0.0.0", port=PORT, handle_signals=True)
server.py+62-172