Spaces:
Running on Zero
Running on Zero
Download app.py from EXELYN404/exelyn-space: direct link, hf CLI and curl.
- Browser
- Download file 38.7 kB
-
https://huggingface.co/spaces/EXELYN404/exelyn-space/resolve/main/app.py
- Command line
-
hf download hf://spaces/EXELYN404/exelyn-space/app.py
-
curl -L -o app.py https://huggingface.co/spaces/EXELYN404/exelyn-space/resolve/main/app.py
38.7 kB
| """ | |
| EXELYN Sandbox Engine — server-side execution backend for EXELYN AI. | |
| Runs on a Hugging Face Space (16 GB RAM, free CPU tier) and exposes: | |
| * a small Gradio status page on "/" | |
| * a Bearer-protected JSON API under "/api/*" | |
| * a reverse proxy for every project dev server on "/preview/{project_id}/" | |
| Each project gets an isolated workspace at /tmp/workspaces/{project_id}; every | |
| requested path is resolved and checked against that root, so a call can never | |
| escape its own workspace. | |
| """ | |
| from __future__ import annotations | |
| import os as _os | |
| # ZeroGPU only proxies the port Gradio picks, and GRADIO_NUM_PORTS defaults to 1 | |
| # on Spaces; widen the scan before gradio reads it. | |
| _os.environ["GRADIO_NUM_PORTS"] = "20" | |
| try: # ZeroGPU runtime helper; absent on plain hosts | |
| import spaces # noqa: F401 | |
| except Exception: # noqa: BLE001 | |
| spaces = None # type: ignore[assignment] | |
| import asyncio | |
| import hmac | |
| import json | |
| import os | |
| import re | |
| import shutil | |
| import signal | |
| import socket | |
| import subprocess | |
| import tempfile | |
| import time | |
| from pathlib import Path | |
| from typing import Any, AsyncIterator | |
| import gradio as gr | |
| import httpx | |
| from fastapi import Depends, FastAPI, Header, HTTPException, Request | |
| from fastapi.responses import Response, StreamingResponse | |
| from starlette.concurrency import run_in_threadpool | |
| SECRET = os.environ.get("SANDBOX_SECRET_KEY", "").strip() | |
| WORKSPACE_ROOT = Path(os.environ.get("SANDBOX_WORKSPACE_ROOT", "/tmp/workspaces")).resolve() | |
| MAX_FILE_BYTES = 5 * 1024 * 1024 | |
| DEFAULT_EXEC_TIMEOUT = 120 | |
| MAX_EXEC_TIMEOUT = 600 | |
| PREVIEW_BOOT_TIMEOUT = float(os.environ.get("SANDBOX_PREVIEW_TIMEOUT", "240")) | |
| # Idle dev servers are the main RAM cost here; 10 minutes matches the client's | |
| # own idle teardown so a backgrounded tab does not keep node alive forever. | |
| PREVIEW_IDLE_TIMEOUT_S = float(os.environ.get("SANDBOX_PREVIEW_IDLE_S", "600")) | |
| PREVIEW_SWEEP_INTERVAL_S = float(os.environ.get("SANDBOX_PREVIEW_SWEEP_S", "60")) | |
| PREVIEW_STOP_GRACE_S = float(os.environ.get("SANDBOX_PREVIEW_STOP_GRACE_S", "3")) | |
| PROJECT_ID_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$") | |
| # ZeroGPU hardware refuses to start unless at least one GPU-decorated function | |
| # exists; the sandbox itself is CPU-only, so this marker is never invoked. | |
| try: # pragma: no cover - only available on ZeroGPU Spaces | |
| import spaces | |
| except ImportError: # plain CPU images do not ship the helper | |
| import types | |
| spaces = types.SimpleNamespace(GPU=lambda **_kwargs: (lambda fn: fn)) | |
| def gpu_marker() -> str: | |
| return "ok" | |
| app = FastAPI(title="EXELYN Sandbox Engine", docs_url=None, redoc_url=None) | |
| STARTED_AT = time.time() | |
| # --------------------------------------------------------------------------- # | |
| # Auth + workspace helpers | |
| # --------------------------------------------------------------------------- # | |
| def require_secret(authorization: str | None = Header(default=None)) -> None: | |
| """Rejects any request that does not carry the shared bearer token.""" | |
| if not SECRET: | |
| raise HTTPException(status_code=500, detail="SANDBOX_SECRET_KEY is not configured") | |
| if not authorization: | |
| raise HTTPException(status_code=401, detail="Missing Authorization header") | |
| scheme, _, token = authorization.partition(" ") | |
| if scheme.lower() != "bearer" or not token.strip(): | |
| raise HTTPException(status_code=401, detail="Expected 'Authorization: Bearer <token>'") | |
| if not hmac.compare_digest(token.strip(), SECRET): | |
| raise HTTPException(status_code=403, detail="Invalid sandbox token") | |
| def workspace(project_id: str, create: bool = True) -> Path: | |
| if not PROJECT_ID_RE.match(project_id or ""): | |
| raise HTTPException(status_code=400, detail="Invalid project_id") | |
| base = (WORKSPACE_ROOT / project_id).resolve() | |
| if base.parent != WORKSPACE_ROOT: | |
| raise HTTPException(status_code=400, detail="Invalid project_id") | |
| if create: | |
| base.mkdir(parents=True, exist_ok=True) | |
| return base | |
| def safe_path(project_id: str, relative: str | None) -> Path: | |
| base = workspace(project_id) | |
| cleaned = str(relative or "").replace("\\", "/").strip() | |
| target = (base / cleaned.lstrip("/")).resolve() | |
| if target != base and base not in target.parents: | |
| raise HTTPException(status_code=400, detail="Path escapes the project workspace") | |
| return target | |
| def relative_to_workspace(project_id: str, path: Path) -> str: | |
| return path.relative_to(workspace(project_id, create=False)).as_posix() | |
| def require_field(payload: dict[str, Any], key: str) -> Any: | |
| value = payload.get(key) | |
| if value is None or value == "": | |
| raise HTTPException(status_code=400, detail=f"'{key}' is required") | |
| return value | |
| # --------------------------------------------------------------------------- # | |
| # Preview process manager (non-blocking: boot runs in the background) | |
| # --------------------------------------------------------------------------- # | |
| class PreviewState: | |
| """Tracks one project dev server across boot, ready and failure.""" | |
| def __init__(self, project_id: str): | |
| self.project_id = project_id | |
| self.state = "starting" # starting | installing | ready | error | stopped | |
| self.port: int | None = None | |
| self.error: str | None = None | |
| self.process: subprocess.Popen[str] | None = None | |
| self.task: asyncio.Task[None] | None = None | |
| self.started_at = time.time() | |
| self.last_seen = time.time() | |
| def touch(self) -> None: | |
| self.last_seen = time.time() | |
| def idle_seconds(self) -> float: | |
| return round(time.time() - self.last_seen, 1) | |
| def running(self) -> bool: | |
| return self.state == "ready" and self.process is not None and self.process.poll() is None | |
| def url(self) -> str | None: | |
| return f"/preview/{self.project_id}/" if self.running() else None | |
| def as_dict(self) -> dict[str, Any]: | |
| return { | |
| "state": self.state, | |
| "port": self.port, | |
| "url": self.url(), | |
| "error": self.error, | |
| "uptime_s": round(time.time() - self.started_at, 1), | |
| "idle_s": self.idle_seconds(), | |
| } | |
| PREVIEWS: dict[str, PreviewState] = {} | |
| def port_is_free(port: int) -> bool: | |
| with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as probe: | |
| probe.settimeout(0.4) | |
| return probe.connect_ex(("127.0.0.1", port)) != 0 | |
| def pick_port(project_id: str) -> int: | |
| """Deterministic base port per project, nudged forward if something already listens.""" | |
| base = 3100 + (int.from_bytes(project_id.encode(), "little") % 500) | |
| for offset in range(50): | |
| candidate = base + offset | |
| if port_is_free(candidate): | |
| return candidate | |
| return base | |
| def tail_log(path: Path, limit: int = 1200) -> str: | |
| try: | |
| return path.read_text(errors="replace")[-limit:] | |
| except OSError: | |
| return "" | |
| async def wait_for_port(port: int, timeout: float) -> bool: | |
| deadline = time.time() + timeout | |
| async with httpx.AsyncClient(timeout=2.0) as client: | |
| while time.time() < deadline: | |
| try: | |
| await client.get(f"http://127.0.0.1:{port}/") | |
| return True | |
| except Exception: # noqa: BLE001 - any transport error means "not ready yet" | |
| await asyncio.sleep(1.0) | |
| return False | |
| def dev_command(project_id: str, port: int) -> list[str]: | |
| script = "dev" | |
| try: | |
| manifest = json.loads((workspace(project_id) / "package.json").read_text()) | |
| scripts = manifest.get("scripts") or {} | |
| if "dev" not in scripts and "start" in scripts: | |
| script = "start" | |
| except (OSError, ValueError): | |
| pass | |
| return ["npm", "run", script, "--", "--port", str(port), "--hostname", "127.0.0.1"] | |
| def spawn_dev_server(project_id: str, port: int) -> subprocess.Popen[str]: | |
| log_path = workspace(project_id) / ".exelyn-preview.log" | |
| log_file = log_path.open("a", encoding="utf-8") | |
| env = { | |
| **os.environ, | |
| "PORT": str(port), | |
| "HOSTNAME": "127.0.0.1", | |
| "NEXT_TELEMETRY_DISABLED": "1", | |
| "BROWSER": "none", | |
| "CI": "1", | |
| # Without a cap a single dev server can grow the heap past 1 GB. | |
| "NODE_OPTIONS": os.environ.get("NODE_OPTIONS", "--max-old-space-size=512"), | |
| } | |
| return subprocess.Popen( # noqa: S603 - fixed argv, never a shell string | |
| dev_command(project_id, port), | |
| cwd=str(workspace(project_id)), | |
| stdout=log_file, | |
| stderr=subprocess.STDOUT, | |
| env=env, | |
| start_new_session=True, | |
| text=True, | |
| ) | |
| def _signal_group(process: subprocess.Popen[str], sig: int) -> None: | |
| try: | |
| os.killpg(os.getpgid(process.pid), sig) | |
| except (ProcessLookupError, PermissionError): | |
| try: | |
| process.send_signal(sig) | |
| except (ProcessLookupError, OSError): | |
| pass | |
| def kill_preview(project_id: str) -> bool: | |
| """Stops the whole process group: `npm run dev` spawns node, and leaving it | |
| behind kept 150-250 MB alive for every project the user ever opened.""" | |
| preview = PREVIEWS.pop(project_id, None) | |
| if not preview: | |
| return False | |
| if preview.task and not preview.task.done(): | |
| preview.task.cancel() | |
| process = preview.process | |
| if process and process.poll() is None: | |
| _signal_group(process, signal.SIGTERM) | |
| try: | |
| process.wait(timeout=PREVIEW_STOP_GRACE_S) | |
| except subprocess.TimeoutExpired: | |
| _signal_group(process, signal.SIGKILL) | |
| try: | |
| process.wait(timeout=5) | |
| except subprocess.TimeoutExpired: | |
| pass | |
| except Exception: # noqa: BLE001 - best effort teardown | |
| pass | |
| preview.state = "stopped" | |
| return True | |
| async def preview_janitor() -> None: | |
| """Reaps dev servers nobody is watching. Idle previews are the single | |
| biggest RAM consumer in this Space, and nothing else ever stops them.""" | |
| while True: | |
| await asyncio.sleep(PREVIEW_SWEEP_INTERVAL_S) | |
| try: | |
| for project_id, preview in list(PREVIEWS.items()): | |
| if preview.state not in {"ready", "starting", "installing"}: | |
| continue | |
| if preview.idle_seconds() < PREVIEW_IDLE_TIMEOUT_S: | |
| continue | |
| kill_preview(project_id) | |
| except Exception as error: # noqa: BLE001 - the janitor must never die | |
| print(f"[preview-janitor] {error}", flush=True) | |
| async def boot_preview(project_id: str, preview: PreviewState) -> None: | |
| """Installs dependencies (once) and starts the dev server without blocking a request.""" | |
| root = workspace(project_id) | |
| try: | |
| if not (root / "package.json").exists(): | |
| preview.state = "error" | |
| preview.error = "Workspace has no package.json yet" | |
| return | |
| if shutil.which("npm") is None: | |
| preview.state = "error" | |
| preview.error = "npm is not available in the sandbox image" | |
| return | |
| if not (root / "node_modules").exists(): | |
| preview.state = "installing" | |
| install = await run_in_threadpool( | |
| subprocess.run, # noqa: S603 | |
| ["npm", "install", "--no-audit", "--no-fund", "--prefer-offline", "--loglevel=error"], | |
| cwd=str(root), | |
| capture_output=True, | |
| text=True, | |
| timeout=1200, | |
| check=False, | |
| ) | |
| if install.returncode != 0: | |
| preview.state = "error" | |
| preview.error = f"npm install failed: {(install.stderr or install.stdout or '')[-1200:]}" | |
| return | |
| preview.state = "starting" | |
| preview.port = pick_port(project_id) | |
| preview.process = spawn_dev_server(project_id, preview.port) | |
| ready = await wait_for_port(preview.port, PREVIEW_BOOT_TIMEOUT) | |
| if ready and preview.process.poll() is None: | |
| preview.state = "ready" | |
| elif ready: | |
| preview.state = "error" | |
| preview.error = f"Dev server exited right after start: {tail_log(root / '.exelyn-preview.log')}" | |
| else: | |
| preview.state = "error" | |
| preview.error = f"Dev server not ready after {int(PREVIEW_BOOT_TIMEOUT)}s: {tail_log(root / '.exelyn-preview.log')}" | |
| if preview.process.poll() is None: | |
| preview.process.terminate() | |
| except asyncio.CancelledError: | |
| preview.state = "stopped" | |
| raise | |
| except Exception as error: # noqa: BLE001 - surfaced to the client as a state | |
| preview.state = "error" | |
| preview.error = str(error)[:800] | |
| def start_preview(project_id: str, force: bool = False) -> PreviewState: | |
| current = PREVIEWS.get(project_id) | |
| if current and not force: | |
| if current.running() or current.state in {"starting", "installing"}: | |
| return current | |
| if current: | |
| kill_preview(project_id) | |
| preview = PreviewState(project_id) | |
| PREVIEWS[project_id] = preview | |
| preview.task = asyncio.create_task(boot_preview(project_id, preview)) | |
| return preview | |
| # --------------------------------------------------------------------------- # | |
| # Snippet matching, syntax checks and repo map | |
| # --------------------------------------------------------------------------- # | |
| def _normalize_line(line: str) -> str: | |
| return re.sub(r"\s+", " ", line).strip() | |
| def _line_spans(content: str) -> list[tuple[int, int, str]]: | |
| spans: list[tuple[int, int, str]] = [] | |
| cursor = 0 | |
| for text in content.split("\n"): | |
| spans.append((cursor, cursor + len(text), text)) | |
| cursor += len(text) + 1 | |
| return spans | |
| def find_edit_match(content: str, old_text: str) -> tuple[int, int, str, str] | None: | |
| """Exact match first, then whitespace/indentation-insensitive line matching.""" | |
| if not old_text: | |
| return None | |
| index = content.find(old_text) | |
| if index != -1 and content.find(old_text, index + 1) == -1: | |
| return index, index + len(old_text), old_text, "exact" | |
| target = [line for line in (_normalize_line(item) for item in old_text.split("\n")) if line] | |
| if not target: | |
| return None | |
| spans = _line_spans(content) | |
| normalized = [_normalize_line(text) for _, _, text in spans] | |
| match: tuple[int, int, str, str] | None = None | |
| for start, line in enumerate(normalized): | |
| if line != target[0]: | |
| continue | |
| wanted = 0 | |
| cursor = start | |
| last_end = spans[start][1] | |
| while wanted < len(target) and cursor < len(normalized): | |
| current = normalized[cursor] | |
| if not current: | |
| cursor += 1 | |
| continue | |
| if current != target[wanted]: | |
| break | |
| last_end = spans[cursor][1] | |
| wanted += 1 | |
| cursor += 1 | |
| if wanted != len(target): | |
| continue | |
| if match is not None: | |
| return None | |
| start_offset = spans[start][0] | |
| match = (start_offset, last_end, content[start_offset:last_end], "fuzzy") | |
| return match | |
| def reindent(matched: str, replacement: str) -> str: | |
| anchor = re.match(r"[ \t]*", matched).group(0) | |
| if not anchor or re.match(r"[ \t]", replacement): | |
| return replacement | |
| return "\n".join( | |
| line if not line.strip() else f"{anchor}{line}" for line in replacement.split("\n") | |
| ) | |
| def closest_snippet(content: str, old_text: str, context: int = 3) -> str | None: | |
| wanted = next((line for line in (_normalize_line(item) for item in old_text.split("\n")) if len(line) > 3), None) | |
| if not wanted: | |
| return None | |
| wanted_tokens = {token for token in re.split(r"[^A-Za-z0-9_$]+", wanted) if len(token) > 2} | |
| spans = _line_spans(content) | |
| best_index = -1 | |
| best_score = 0 | |
| for index, (_, _, text) in enumerate(spans): | |
| tokens = [token for token in re.split(r"[^A-Za-z0-9_$]+", _normalize_line(text)) if token] | |
| if not tokens: | |
| continue | |
| score = sum(1 for token in tokens if token in wanted_tokens) | |
| if score > best_score: | |
| best_score = score | |
| best_index = index | |
| if best_index == -1 or best_score == 0: | |
| return None | |
| start = max(0, best_index - context) | |
| end = min(len(spans), best_index + context + 1) | |
| return "\n".join(f"{start + offset + 1}: {spans[start + offset][2]}" for offset in range(end - start)) | |
| CHECKABLE_SUFFIXES = (".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs") | |
| def syntax_check(path: Path, workspace_root: Path) -> str: | |
| """Fast post-write guardrail: never blocks for more than a few seconds.""" | |
| if path.suffix.lower() not in CHECKABLE_SUFFIXES: | |
| return "" | |
| suffix = path.suffix.lower() | |
| esbuild = workspace_root / "node_modules" / ".bin" / "esbuild" | |
| commands: list[list[str]] = [] | |
| if esbuild.exists(): | |
| loader = "tsx" if suffix in {".ts", ".tsx"} else "jsx" if suffix == ".jsx" else "js" | |
| commands.append([str(esbuild), str(path), f"--loader={loader}", "--log-level=error", "--outfile=/dev/null"]) | |
| if suffix == ".cjs": | |
| commands.append(["node", "--check", str(path)]) | |
| elif suffix in {".js", ".mjs"}: | |
| # Node 20 exits 0 on ESM syntax inside a .js file, so check a .mjs copy. | |
| try: | |
| scratch = Path(tempfile.mkdtemp(prefix="exelyn-check-")) / "check.mjs" | |
| scratch.write_text(path.read_text("utf-8", "replace"), "utf-8") | |
| commands.append(["node", "--check", str(scratch)]) | |
| except OSError: | |
| pass | |
| tsc = workspace_root / "node_modules" / ".bin" / "tsc" | |
| if tsc.exists() and (workspace_root / "tsconfig.json").exists(): | |
| commands.append([str(tsc), "--noEmit", "--pretty", "false", "--skipLibCheck"]) | |
| for command in commands: | |
| try: | |
| completed = subprocess.run( | |
| command, | |
| cwd=str(workspace_root), | |
| capture_output=True, | |
| text=True, | |
| timeout=5, | |
| check=False, | |
| ) | |
| except (subprocess.TimeoutExpired, OSError): | |
| continue | |
| output = (completed.stdout or "") + (completed.stderr or "") | |
| if completed.returncode == 0: | |
| return "Syntax/Type Check: OK" | |
| lines = [line for line in output.splitlines() if line.strip()][:8] | |
| if lines: | |
| return "Syntax/Type Check: FAILED\n" + "\n".join(lines) | |
| return "" | |
| REPO_MAP_EXTENSIONS = {".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".vue", ".svelte", ".css", ".json"} | |
| REPO_MAP_IGNORED = {"node_modules", ".next", ".git", "dist", "build", "coverage"} | |
| REPO_MAP_MAX_FILES = 120 | |
| REPO_MAP_MAX_CHARS = 2000 | |
| SYMBOL_PATTERNS = [ | |
| re.compile(r"^\s*export\s+(?:default\s+)?(?:async\s+)?function\s+([A-Za-z0-9_$]+)", re.M), | |
| re.compile(r"^\s*export\s+(?:default\s+)?(?:abstract\s+)?class\s+([A-Za-z0-9_$]+)", re.M), | |
| re.compile(r"^\s*export\s+(?:const|let|var)\s+([A-Za-z0-9_$]+)", re.M), | |
| re.compile(r"^\s*export\s+(?:interface|type|enum)\s+([A-Za-z0-9_$]+)", re.M), | |
| re.compile(r"^\s*(?:async\s+)?function\s+([A-Za-z0-9_$]+)\s*\(", re.M), | |
| re.compile(r"^\s*(?:interface|type|enum)\s+([A-Za-z0-9_$]+)", re.M), | |
| re.compile(r"^\s*class\s+([A-Za-z0-9_$]+)", re.M), | |
| ] | |
| def collect_symbols(content: str, limit: int = 12) -> list[str]: | |
| found: list[str] = [] | |
| for pattern in SYMBOL_PATTERNS: | |
| for name in pattern.findall(content): | |
| if name and name not in found: | |
| found.append(name) | |
| if len(found) >= limit: | |
| return found | |
| return found | |
| def build_repo_map(root: Path) -> str: | |
| files: list[Path] = [] | |
| for path in sorted(root.rglob("*")): | |
| if len(files) >= REPO_MAP_MAX_FILES: | |
| break | |
| if not path.is_file(): | |
| continue | |
| if any(part in REPO_MAP_IGNORED for part in path.relative_to(root).parts): | |
| continue | |
| if path.suffix.lower() in REPO_MAP_EXTENSIONS: | |
| files.append(path) | |
| lines: list[str] = [] | |
| used = 0 | |
| for path in files: | |
| try: | |
| content = path.read_text("utf-8", "replace")[:60_000] | |
| except OSError: | |
| continue | |
| symbols = collect_symbols(content) | |
| relative = path.relative_to(root).as_posix() | |
| line = f"{relative}: {', '.join(symbols)}" if symbols else relative | |
| if used + len(line) + 1 > REPO_MAP_MAX_CHARS: | |
| lines.append(f"…[{len(files) - len(lines)} file lain tidak ditampilkan]") | |
| break | |
| lines.append(line) | |
| used += len(line) + 1 | |
| return "\n".join(lines) | |
| # --------------------------------------------------------------------------- # | |
| # API: health + filesystem | |
| # --------------------------------------------------------------------------- # | |
| def read_rss_mb() -> float | None: | |
| """Process RSS from /proc, so the Space metrics can be reproduced locally.""" | |
| try: | |
| with open("/proc/self/status", encoding="utf-8") as handle: | |
| for line in handle: | |
| if line.startswith("VmRSS:"): | |
| return round(int(line.split()[1]) / 1024, 1) | |
| except OSError: | |
| return None | |
| return None | |
| def child_process_count() -> int: | |
| """Surviving node/npm processes: the leak this service must not have.""" | |
| try: | |
| output = subprocess.run( | |
| ["ps", "-eo", "ppid=,comm="], capture_output=True, text=True, check=False | |
| ).stdout | |
| except OSError: | |
| return 0 | |
| me = os.getpid() | |
| return sum(1 for line in output.splitlines() if line.split()[:1] == [str(me)]) | |
| async def start_background_tasks() -> None: | |
| asyncio.create_task(preview_janitor()) | |
| async def health(_: None = Depends(require_secret)) -> dict[str, Any]: | |
| node = subprocess.run(["node", "--version"], capture_output=True, text=True, check=False) | |
| return { | |
| "status": "ok", | |
| "service": "exelyn-sandbox", | |
| "node": (node.stdout or "").strip() or None, | |
| "workspaces": len([p for p in WORKSPACE_ROOT.glob("*") if p.is_dir()]), | |
| "previews": { | |
| pid: {"port": item.port, "state": item.state, "idle_s": item.idle_seconds()} | |
| for pid, item in PREVIEWS.items() | |
| }, | |
| "rss_mb": read_rss_mb(), | |
| "child_processes": child_process_count(), | |
| "uptime_s": round(time.time() - STARTED_AT, 1), | |
| } | |
| async def files_list(payload: dict[str, Any], _: None = Depends(require_secret)) -> dict[str, Any]: | |
| project_id = str(require_field(payload, "project_id")) | |
| directory = safe_path(project_id, payload.get("path") or "") | |
| if not directory.exists(): | |
| return {"success": True, "files": []} | |
| if not directory.is_dir(): | |
| raise HTTPException(status_code=400, detail="Path is not a directory") | |
| entries = [] | |
| for entry in sorted(directory.iterdir(), key=lambda item: (item.is_file(), item.name)): | |
| if entry.name in {"node_modules", ".git", ".next"}: | |
| continue | |
| stat = entry.stat() | |
| entries.append( | |
| { | |
| "name": entry.name, | |
| "path": relative_to_workspace(project_id, entry), | |
| "type": "directory" if entry.is_dir() else "file", | |
| "size": stat.st_size, | |
| "modified": int(stat.st_mtime), | |
| } | |
| ) | |
| return {"success": True, "files": entries} | |
| async def files_read(payload: dict[str, Any], _: None = Depends(require_secret)) -> dict[str, Any]: | |
| project_id = str(require_field(payload, "project_id")) | |
| path = safe_path(project_id, require_field(payload, "path")) | |
| if not path.is_file(): | |
| raise HTTPException(status_code=404, detail="File not found") | |
| if path.stat().st_size > MAX_FILE_BYTES: | |
| raise HTTPException(status_code=413, detail="File is too large to read") | |
| content = await run_in_threadpool(path.read_text, "utf-8", "replace") | |
| return {"success": True, "path": relative_to_workspace(project_id, path), "content": content} | |
| async def files_write(payload: dict[str, Any], _: None = Depends(require_secret)) -> dict[str, Any]: | |
| project_id = str(require_field(payload, "project_id")) | |
| path = safe_path(project_id, require_field(payload, "path")) | |
| content = payload.get("content") | |
| if not isinstance(content, str): | |
| raise HTTPException(status_code=400, detail="'content' must be a string") | |
| if len(content.encode()) > MAX_FILE_BYTES: | |
| raise HTTPException(status_code=413, detail="Content is too large") | |
| await run_in_threadpool(path.parent.mkdir, parents=True, exist_ok=True) | |
| await run_in_threadpool(path.write_text, content, "utf-8") | |
| check = await run_in_threadpool(syntax_check, path, workspace(project_id)) | |
| return { | |
| "success": True, | |
| "path": relative_to_workspace(project_id, path), | |
| "bytes": len(content.encode()), | |
| **({"check": check} if check else {}), | |
| } | |
| async def files_edit(payload: dict[str, Any], _: None = Depends(require_secret)) -> dict[str, Any]: | |
| project_id = str(require_field(payload, "project_id")) | |
| path = safe_path(project_id, require_field(payload, "path")) | |
| old_text = require_field(payload, "old_text") | |
| new_text = payload.get("new_text") or "" | |
| replace_all = bool(payload.get("replace_all", False)) | |
| if not path.is_file(): | |
| raise HTTPException(status_code=404, detail="File not found") | |
| content = await run_in_threadpool(path.read_text, "utf-8", "replace") | |
| match = find_edit_match(content, old_text) | |
| if match is None: | |
| snippet = closest_snippet(content, old_text) | |
| detail = "old_text was not found in the file" | |
| if snippet: | |
| detail = f"old_text was not found. Closest region:\n{snippet}" | |
| raise HTTPException(status_code=409, detail=detail) | |
| start, end, matched, kind = match | |
| replacement = new_text if kind == "exact" else reindent(matched, new_text) | |
| if replace_all: | |
| updated = content.replace(matched, replacement) | |
| replacements = content.count(matched) | |
| else: | |
| updated = f"{content[:start]}{replacement}{content[end:]}" | |
| replacements = 1 | |
| await run_in_threadpool(path.write_text, updated, "utf-8") | |
| check = await run_in_threadpool(syntax_check, path, workspace(project_id)) | |
| return { | |
| "success": True, | |
| "path": relative_to_workspace(project_id, path), | |
| "replacements": replacements, | |
| "match": kind, | |
| **({"check": check} if check else {}), | |
| } | |
| async def files_delete(payload: dict[str, Any], _: None = Depends(require_secret)) -> dict[str, Any]: | |
| project_id = str(require_field(payload, "project_id")) | |
| path = safe_path(project_id, require_field(payload, "path")) | |
| if path == workspace(project_id): | |
| raise HTTPException(status_code=400, detail="Refusing to delete the workspace root") | |
| if not path.exists(): | |
| return {"success": True, "deleted": False} | |
| relative = relative_to_workspace(project_id, path) | |
| if path.is_dir(): | |
| await run_in_threadpool(shutil.rmtree, path) | |
| else: | |
| await run_in_threadpool(path.unlink) | |
| return {"success": True, "deleted": True, "path": relative} | |
| async def repo_map(payload: dict[str, Any], _: None = Depends(require_secret)) -> dict[str, Any]: | |
| """Compact project structure: paths plus the symbols each file declares.""" | |
| project_id = str(require_field(payload, "project_id")) | |
| root = workspace(project_id) | |
| if not root.exists(): | |
| return {"success": True, "project_id": project_id, "map": "", "files": 0} | |
| text = await run_in_threadpool(build_repo_map, root) | |
| return { | |
| "success": True, | |
| "project_id": project_id, | |
| "map": text, | |
| "files": len([line for line in text.splitlines() if line and not line.startswith("…")]), | |
| } | |
| # --------------------------------------------------------------------------- # | |
| # API: terminal + preview lifecycle | |
| # --------------------------------------------------------------------------- # | |
| async def terminal_exec(payload: dict[str, Any], _: None = Depends(require_secret)) -> dict[str, Any]: | |
| project_id = str(require_field(payload, "project_id")) | |
| command = str(require_field(payload, "command")).strip() | |
| if len(command) > 4000: | |
| raise HTTPException(status_code=413, detail="command is too long") | |
| timeout = min(int(payload.get("timeout") or DEFAULT_EXEC_TIMEOUT), MAX_EXEC_TIMEOUT) | |
| cwd = safe_path(project_id, payload.get("cwd") or "") | |
| if not cwd.is_dir(): | |
| cwd = workspace(project_id) | |
| def run() -> dict[str, Any]: | |
| try: | |
| completed = subprocess.run( # noqa: S602 - running shell commands is the point of a sandbox | |
| command, | |
| shell=True, | |
| cwd=str(cwd), | |
| capture_output=True, | |
| text=True, | |
| timeout=timeout, | |
| env={**os.environ, "CI": "1", "NEXT_TELEMETRY_DISABLED": "1"}, | |
| ) | |
| output = f"{completed.stdout or ''}{completed.stderr or ''}" | |
| return {"success": True, "exit_code": completed.returncode, "output": output[-40_000:]} | |
| except subprocess.TimeoutExpired as expired: | |
| stdout = expired.stdout or "" | |
| stderr = expired.stderr or "" | |
| if isinstance(stdout, bytes): | |
| stdout = stdout.decode("utf-8", "replace") | |
| if isinstance(stderr, bytes): | |
| stderr = stderr.decode("utf-8", "replace") | |
| return { | |
| "success": False, | |
| "exit_code": 124, | |
| "output": f"{stdout}{stderr}"[-40_000:] + f"\n[timed out after {timeout}s]", | |
| } | |
| return await run_in_threadpool(run) | |
| async def preview_start(payload: dict[str, Any], _: None = Depends(require_secret)) -> dict[str, Any]: | |
| """Kicks off the boot in the background and returns immediately (no long request).""" | |
| project_id = str(require_field(payload, "project_id")) | |
| preview = start_preview(project_id, force=bool(payload.get("force"))) | |
| preview.touch() | |
| return {"success": True, "project_id": project_id, **preview.as_dict()} | |
| async def preview_stop(payload: dict[str, Any], _: None = Depends(require_secret)) -> dict[str, Any]: | |
| project_id = str(require_field(payload, "project_id")) | |
| return {"success": True, "stopped": kill_preview(project_id), "state": "stopped"} | |
| async def preview_status(payload: dict[str, Any], _: None = Depends(require_secret)) -> dict[str, Any]: | |
| project_id = str(require_field(payload, "project_id")) | |
| preview = PREVIEWS.get(project_id) | |
| if not preview: | |
| return {"success": True, "project_id": project_id, "state": "idle", "url": None, "port": None, "error": None} | |
| preview.touch() | |
| return {"success": True, "project_id": project_id, **preview.as_dict()} | |
| # --------------------------------------------------------------------------- # | |
| # Preview reverse proxy | |
| # --------------------------------------------------------------------------- # | |
| HOP_BY_HOP = { | |
| "connection", | |
| "keep-alive", | |
| "proxy-authenticate", | |
| "proxy-authorization", | |
| "te", | |
| "trailers", | |
| "transfer-encoding", | |
| "upgrade", | |
| "content-encoding", | |
| "content-length", | |
| } | |
| REWRITABLE = ("text/html", "text/css", "javascript", "application/json") | |
| ROOT_URL_RE = re.compile(r'(?P<lead>href="|src="|action="|url\(|"|\'|\()(?P<path>/(?!/)[^"\'\s()\\]*)') | |
| def rewrite_assets(text: str, prefix: str) -> str: | |
| """Root-absolute URLs of the dev server must resolve under the proxy prefix.""" | |
| if not prefix: | |
| return text | |
| def replace(match: re.Match[str]) -> str: | |
| path = match.group("path") | |
| if path == prefix or path.startswith(f"{prefix}/"): | |
| return match.group(0) | |
| return f"{match.group('lead')}{prefix}{path}" | |
| return ROOT_URL_RE.sub(replace, text) | |
| async def preview_proxy(project_id: str, path: str, request: Request) -> Response: | |
| preview = PREVIEWS.get(project_id) | |
| if not preview or not preview.running() or preview.port is None: | |
| raise HTTPException(status_code=404, detail="Preview is not running for this project") | |
| preview.touch() | |
| prefix = request.headers.get("x-forwarded-prefix", "").rstrip("/") | |
| if not prefix: | |
| # Reached directly: derive the mount point from the request path. | |
| tail = f"/{path}" if path else "/" | |
| if request.url.path.endswith(tail): | |
| prefix = request.url.path[: len(request.url.path) - len(tail)].rstrip("/") | |
| target = f"http://127.0.0.1:{preview.port}/{path}" | |
| if request.url.query: | |
| target = f"{target}?{request.url.query}" | |
| forwarded_headers = { | |
| key: value | |
| for key, value in request.headers.items() | |
| if key.lower() not in HOP_BY_HOP and key.lower() not in {"host", "authorization"} | |
| } | |
| client = httpx.AsyncClient(timeout=60.0, follow_redirects=False) | |
| try: | |
| upstream = client.build_request( | |
| request.method, | |
| target, | |
| headers=forwarded_headers, | |
| content=await request.body() if request.method in {"POST", "PUT", "PATCH"} else None, | |
| ) | |
| response = await client.send(upstream, stream=True) | |
| except httpx.HTTPError as error: | |
| await client.aclose() | |
| raise HTTPException(status_code=502, detail=f"Dev server unreachable: {error}") from error | |
| headers = { | |
| key: value | |
| for key, value in response.headers.items() | |
| if key.lower() not in HOP_BY_HOP and key.lower() != "location" | |
| } | |
| location = response.headers.get("location") | |
| if location and prefix and location.startswith("/") and not location.startswith("//"): | |
| headers["location"] = f"{prefix}{location}" | |
| content_type = response.headers.get("content-type", "") | |
| if request.method != "HEAD" and any(kind in content_type for kind in REWRITABLE): | |
| raw = await response.aread() | |
| await response.aclose() | |
| await client.aclose() | |
| text = rewrite_assets(raw.decode("utf-8", "replace"), prefix) | |
| return Response( | |
| content=text, | |
| status_code=response.status_code, | |
| headers=headers, | |
| media_type=content_type or None, | |
| ) | |
| async def stream() -> AsyncIterator[bytes]: | |
| try: | |
| async for chunk in response.aiter_raw(): | |
| yield chunk | |
| finally: | |
| await response.aclose() | |
| await client.aclose() | |
| return StreamingResponse( | |
| stream(), | |
| status_code=response.status_code, | |
| headers=headers, | |
| media_type=content_type or None, | |
| ) | |
| # --------------------------------------------------------------------------- # | |
| # Gradio status page (mounted at "/") | |
| # --------------------------------------------------------------------------- # | |
| def build_ui() -> gr.Blocks: | |
| with gr.Blocks(title="EXELYN Sandbox Engine", theme=gr.themes.Base()) as blocks: | |
| gr.Markdown( | |
| """ | |
| # EXELYN Sandbox Engine Active | |
| 16 GB RAM server-side execution backend for **EXELYN AI**. | |
| | | | | |
| |---|---| | |
| | Workspaces | `/tmp/workspaces/{project_id}` | | |
| | Files API | `POST /api/files/list · read · write · edit · delete` | | |
| | Commands | `POST /api/terminal/exec` | | |
| | Preview | `POST /api/preview/start` + `GET /preview/{project_id}/` | | |
| Every `/api/*` call must send `Authorization: Bearer <SANDBOX_SECRET_KEY>`. | |
| """ | |
| ) | |
| with gr.Row(): | |
| project_box = gr.Textbox(label="Project ID", placeholder="exelyn-landing") | |
| check_button = gr.Button("Check workspace", variant="primary") | |
| output = gr.JSON(label="Result") | |
| def check(project_id: str) -> dict[str, Any]: | |
| candidate = (project_id or "").strip() | |
| if not PROJECT_ID_RE.match(candidate): | |
| return {"error": "invalid project id"} | |
| root = workspace(candidate, create=False) | |
| if not root.exists(): | |
| return {"project_id": candidate, "exists": False} | |
| files = [item.relative_to(root).as_posix() for item in root.rglob("*") if item.is_file()][:200] | |
| preview = PREVIEWS.get(candidate) | |
| return { | |
| "project_id": candidate, | |
| "exists": True, | |
| "files": len(files), | |
| "sample": files[:20], | |
| "preview_running": bool(preview and preview.running()), | |
| } | |
| check_button.click(check, inputs=project_box, outputs=output) | |
| if gpu_marker is not None: | |
| # Never clicked: ZeroGPU only needs one registered @spaces.GPU fn. | |
| gr.Button(visible=False).click(fn=gpu_marker, inputs=None, outputs=None) | |
| return blocks | |
| from exelyn_1p import exelyn_api as _exelyn_api | |
| app.mount("/v1", _exelyn_api) | |
| demo = build_ui() | |
| app = gr.mount_gradio_app(app, demo, path="/") | |
| # The Gradio frontend only proxies /gradio_api/* to Python, so the same routes | |
| # are also mounted under that prefix when running behind the Gradio app. | |
| sandbox_api = FastAPI(title="EXELYN Sandbox API", docs_url=None, redoc_url=None) | |
| sandbox_api.router.routes = list(app.router.routes) | |
| sandbox_api.mount("/v1", _exelyn_api) | |
| SANDBOX_MOUNT = "/gradio_api/sandbox" | |
| def _attach_sandbox_routes(target: FastAPI) -> None: | |
| target.mount(SANDBOX_MOUNT, sandbox_api) | |
| from exelyn_1p import exelyn_api | |
| target.mount("/v1", exelyn_api) | |
| def _patch_gradio_app() -> None: | |
| from gradio.routes import App as GradioApp | |
| original = GradioApp.create_app | |
| def create_app(blocks, *args, **kwargs): # type: ignore[no-untyped-def] | |
| gradio_app = original(blocks, *args, **kwargs) | |
| _attach_sandbox_routes(gradio_app) | |
| return gradio_app | |
| GradioApp.create_app = create_app # type: ignore[method-assign] | |
| if __name__ == "__main__": | |
| _patch_gradio_app() | |
| # demo.launch() runs the ZeroGPU handshake, lets Gradio pick the first free | |
| # port behind the Space supervisor, and serves the patched app. | |
| demo.launch(server_name="0.0.0.0", quiet=False, ssr_mode=False) | |