File size: 6,241 Bytes
409ebb3 | 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 | import json
import uuid
import asyncio
import zipfile
from pathlib import Path
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request, HTTPException
from fastapi.responses import (
HTMLResponse, JSONResponse, FileResponse, StreamingResponse,
)
from fastapi.middleware.cors import CORSMiddleware
from sse_starlette.sse import EventSourceResponse
from config import settings
from schemas import GenerateRequest, FixRequest, ProjectState
from pipeline import PipelineEngine
# βββ state ββββββββββββββββββββββββββββββββββββββββββββββββ
sessions: dict[str, ProjectState] = {}
engine = PipelineEngine()
@asynccontextmanager
async def lifespan(app: FastAPI):
Path("/tmp/nexus_projects").mkdir(parents=True, exist_ok=True)
yield
app = FastAPI(title="Nexus Builder", version="1.0.0", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
DEFAULT_SYSTEMS = [
"client_portal",
"public_landing",
"marketing_cms",
"analytics_dashboard",
"admin_panel",
]
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# API ROUTES
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.post("/api/generate")
async def generate(req: GenerateRequest):
sid = str(uuid.uuid4())[:12]
state = ProjectState(
session_id=sid,
user_prompt=req.prompt,
app_type=req.app_type or "saas",
status="queued",
systems=req.systems or DEFAULT_SYSTEMS,
)
sessions[sid] = state
asyncio.create_task(engine.run(state))
return {"session_id": sid, "status": "started"}
@app.get("/api/stream/{sid}")
async def stream(request: Request, sid: str):
if sid not in sessions:
raise HTTPException(404, "Session not found")
async def gen():
state = sessions[sid]
cursor = 0
while True:
if await request.is_disconnected():
break
msgs = state.messages[cursor:]
for m in msgs:
yield {
"event": m.event_type,
"data": json.dumps(m.model_dump(), default=str),
}
cursor = len(state.messages)
if state.status in ("completed", "error"):
yield {
"event": "done",
"data": json.dumps(
{"status": state.status, "session_id": sid}
),
}
break
await asyncio.sleep(0.25)
return EventSourceResponse(gen())
@app.get("/api/status/{sid}")
async def status(sid: str):
if sid not in sessions:
raise HTTPException(404)
s = sessions[sid]
return {
"session_id": sid,
"status": s.status,
"current_agent": s.current_agent,
"file_tree": s.file_tree,
"errors": s.errors,
}
@app.get("/api/files/{sid}")
async def files(sid: str):
if sid not in sessions:
raise HTTPException(404)
return {"files": sessions[sid].generated_files}
@app.get("/api/file/{sid}/{path:path}")
async def file_content(sid: str, path: str):
if sid not in sessions:
raise HTTPException(404)
c = sessions[sid].generated_files.get(path)
if c is None:
raise HTTPException(404, "File not found")
return {"path": path, "content": c}
@app.post("/api/fix/{sid}")
async def fix(sid: str, req: FixRequest):
if sid not in sessions:
raise HTTPException(404)
state = sessions[sid]
state.status = "fixing"
asyncio.create_task(engine.fix(state, req.error_message, req.file_path))
return {"status": "fix_started"}
@app.get("/api/export/{sid}")
async def export(sid: str):
if sid not in sessions:
raise HTTPException(404)
zp = Path(f"/tmp/nexus_projects/{sid}.zip")
with zipfile.ZipFile(zp, "w", zipfile.ZIP_DEFLATED) as zf:
for fp, content in sessions[sid].generated_files.items():
zf.writestr(fp, content)
return FileResponse(zp, filename=f"nexus-{sid}.zip", media_type="application/zip")
@app.get("/api/preview/{sid}")
async def preview(sid: str):
if sid not in sessions:
raise HTTPException(404)
s = sessions[sid]
for k in ("preview/index.html", "frontend/index.html", "index.html"):
if k in s.generated_files:
return HTMLResponse(s.generated_files[k])
return HTMLResponse(
"<html><body style='background:#0A0A0F;color:#F0F0FF;font-family:sans-serif;"
"display:flex;align-items:center;justify-content:center;height:100vh'>"
"<h2>β³ Preview buildingβ¦</h2></body></html>"
)
@app.get("/api/preview/{sid}/{system}")
async def preview_system(sid: str, system: str):
if sid not in sessions:
raise HTTPException(404)
s = sessions[sid]
key = f"{system}/index.html"
if key in s.generated_files:
return HTMLResponse(s.generated_files[key])
return HTMLResponse(
f"<html><body style='background:#0A0A0F;color:#F0F0FF;font-family:sans-serif;padding:40px'>"
f"<h2>{system.replace('_',' ').title()}</h2><p>No preview yet.</p></body></html>"
)
@app.get("/api/health")
async def health():
return {
"status": "ok",
"key_set": bool(settings.OPENROUTER_API_KEY),
"models": settings.MODEL_IDS,
}
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# SERVE FRONTEND (index.html at root)
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
@app.get("/")
async def root():
return FileResponse("index.html", media_type="text/html") |