File size: 17,987 Bytes
e256389
7e7eddc
cb8e44d
0e1554a
 
 
 
 
 
cb8e44d
7e7eddc
e256389
7e7eddc
0e1554a
e256389
 
7e7eddc
0e1554a
74a78ff
e256389
0e1554a
 
 
 
 
 
 
 
 
cb8e44d
0e1554a
 
 
 
 
 
 
cb8e44d
0e1554a
 
cb8e44d
 
0e1554a
 
 
 
cb8e44d
 
0e1554a
 
cb8e44d
 
 
 
 
0e1554a
cb8e44d
0e1554a
cb8e44d
0e1554a
 
 
cb8e44d
 
 
 
0e1554a
cb8e44d
 
0e1554a
cb8e44d
 
0e1554a
cb8e44d
 
 
 
 
 
0e1554a
 
 
 
 
cb8e44d
0e1554a
 
 
 
 
 
cb8e44d
 
0e1554a
cb8e44d
 
 
0e1554a
cb8e44d
 
0e1554a
2bbfae6
cb8e44d
 
0e1554a
cb8e44d
0e1554a
cb8e44d
0e1554a
 
 
 
 
 
cb8e44d
0e1554a
 
 
 
 
 
 
 
 
 
 
 
 
cb8e44d
0e1554a
 
 
 
 
 
 
 
 
cb8e44d
 
 
 
0e1554a
cb8e44d
 
0e1554a
 
 
b688c18
cb8e44d
b688c18
 
 
 
 
cb8e44d
b688c18
cb8e44d
b688c18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb8e44d
b688c18
 
 
 
 
cb8e44d
b688c18
 
 
cb8e44d
b688c18
cb8e44d
 
b688c18
 
 
 
cb8e44d
b688c18
 
 
 
 
 
cb8e44d
b688c18
 
 
 
0e1554a
 
 
 
 
 
 
 
 
 
b688c18
0e1554a
 
 
 
 
 
 
 
 
 
 
cb8e44d
0e1554a
 
7e7eddc
 
 
 
e256389
 
 
0e1554a
7e7eddc
 
e256389
7e7eddc
b688c18
0e1554a
7e7eddc
 
 
 
 
 
 
 
 
 
 
 
e256389
0e1554a
7e7eddc
 
 
 
 
 
0e1554a
 
 
 
7e7eddc
 
 
0e1554a
7e7eddc
 
0e1554a
7e7eddc
74a78ff
0e1554a
 
7e7eddc
e256389
 
5fdaf66
0e1554a
5fdaf66
74a78ff
7e7eddc
 
 
e256389
0e1554a
e256389
 
74a78ff
b688c18
e256389
 
0e1554a
7e7eddc
0e1554a
7e7eddc
e256389
 
0e1554a
b688c18
 
74a78ff
0e1554a
7e7eddc
74a78ff
 
 
 
e256389
 
b688c18
 
e256389
 
74a78ff
e256389
 
7e7eddc
e256389
0e1554a
74a78ff
5fdaf66
74a78ff
0e1554a
74a78ff
 
cb8e44d
0e1554a
5fdaf66
 
7e7eddc
5fdaf66
e256389
7e7eddc
e256389
0e1554a
7e7eddc
5fdaf66
 
74a78ff
b688c18
cb8e44d
7e7eddc
e256389
5fdaf66
0e1554a
5fdaf66
74a78ff
7e7eddc
 
 
0e1554a
7e7eddc
 
74a78ff
7e7eddc
74a78ff
7e7eddc
 
 
0e1554a
7e7eddc
74a78ff
7e7eddc
5fdaf66
0e1554a
 
 
cb8e44d
3cb0ad1
7e7eddc
0e1554a
b688c18
0e1554a
e256389
 
 
0e1554a
cb8e44d
3cb0ad1
0e1554a
 
b688c18
0e1554a
cb8e44d
e256389
 
 
 
5fdaf66
7e7eddc
 
0e1554a
e256389
 
 
7e7eddc
e256389
0e1554a
 
 
 
 
 
 
cb8e44d
0e1554a
 
 
cb8e44d
74a78ff
0e1554a
cb8e44d
0e1554a
cb8e44d
 
3cb0ad1
 
 
 
0e1554a
b688c18
cb8e44d
0e1554a
 
cb8e44d
 
0e1554a
cb8e44d
0e1554a
 
 
3cb0ad1
e256389
7e7eddc
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
"""
╔══════════════════════════════════════════════════════╗
β•‘  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

# ─── CONSTANTS (no heavy imports) ───
PORT = int(os.environ.get("WIZARD_PORT", 7860))
STATIC = Path(__file__).parent / "static"
CANONICAL_REPO = "dryymatt/Wizard-Vibe-Studio"

# ─── Engine refs β€” lazy-loaded in Phase 2 ───
_engine = None
_ghost = None
_reflect = None
_engine_loaded = False

# ──────────────────────────────────────────────────────
#  PHASE 1: Instant HTML β€” absolute black loading page
# ──────────────────────────────────────────────────────

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>"""


# ──────────────────────────────────────────────────────
#  PHASE 1 HANDLERS
# ──────────────────────────────────────────────────────

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},
    })


# ──────────────────────────────────────────────────────
#  E2E HANDSHAKE β€” enhanced for Obsidian Forge
# ──────────────────────────────────────────────────────

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": {}}

    # Check 1: DNS resolution
    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)

    # Check 2: HTTP reachability
    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()
        # Accept 200-499 (some sites return 301/302/401 β€” still reachable)
        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"))


# ──────────────────────────────────────────────────────
#  PHASE 2: Heavy imports, lazy-loaded
# ──────────────────────────────────────────────────────

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")


# ──────────────────────────────────────────────────────
#  APP BUILD
# ──────────────────────────────────────────────────────

def create_app():
    app = web.Application()

    # Phase 1 routes
    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)

    # Phase 2 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)
    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()