Spaces:
Running
Running
Launch the alphaBell Flint Arcade gateway
Browse files- Dockerfile +9 -0
- README.md +32 -5
- proxy.py +229 -0
Dockerfile
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11.14-slim
|
| 2 |
+
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
|
| 3 |
+
RUN pip install --no-cache-dir fastapi==0.159.1 httpx==0.28.1 uvicorn==0.54.0 \
|
| 4 |
+
&& useradd --create-home --uid 1000 arcade
|
| 5 |
+
WORKDIR /app
|
| 6 |
+
COPY --chown=arcade:arcade proxy.py /app/proxy.py
|
| 7 |
+
USER 1000
|
| 8 |
+
EXPOSE 7860
|
| 9 |
+
CMD ["uvicorn", "proxy:create_app", "--factory", "--host", "0.0.0.0", "--port", "7860", "--workers", "1", "--no-access-log", "--no-proxy-headers"]
|
README.md
CHANGED
|
@@ -1,10 +1,37 @@
|
|
| 1 |
---
|
| 2 |
title: Flint Arcade
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: docker
|
| 7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
---
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
title: Flint Arcade
|
| 3 |
+
emoji: 🕹️
|
| 4 |
+
colorFrom: yellow
|
| 5 |
+
colorTo: red
|
| 6 |
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
license: apache-2.0
|
| 9 |
+
short_description: Describe a strange game. Play it. Make it stranger.
|
| 10 |
+
models:
|
| 11 |
+
- RecursiveSI/flint
|
| 12 |
+
datasets:
|
| 13 |
+
- alphabell/Flint-Arcade-Trajectories
|
| 14 |
+
tags:
|
| 15 |
+
- flint
|
| 16 |
+
- code-generation
|
| 17 |
+
- browser-games
|
| 18 |
+
- game-generation
|
| 19 |
+
- agents
|
| 20 |
+
- alphaBell
|
| 21 |
---
|
| 22 |
|
| 23 |
+
# Flint Arcade by alphaBell
|
| 24 |
+
|
| 25 |
+
Describe a tiny world. Flint writes the game. Play it, share the result and remix it with another sentence.
|
| 26 |
+
|
| 27 |
+
This Space presents the live [alphaBell Arcade](https://alphabell.com/arcade/) through a bounded server-side gateway. Model inference and durable game storage run on the alphaBell application backend. The initial release uses stock [Recursive Flint](https://huggingface.co/RecursiveSI/flint) Q8_0 with browser feedback and repair. Each build checks the selected inference model's metadata and requires 8-bit Q8_0.
|
| 28 |
+
|
| 29 |
+
New games adapt a small tested alphaBell foundation for input, rendering and game state. Flint returns a complete standalone HTML game, which the browser checker exercises before publication. Remixes use the actual parent game's code. There is no Arcade-trained adapter in this release.
|
| 30 |
+
|
| 31 |
+
Try [Moon Garden](https://alphabell.com/arcade/g/moon-garden), then give it one more twist. The [generation and repair dataset](https://huggingface.co/datasets/alphabell/Flint-Arcade-Trajectories) records alphaBell-authored briefs, actual candidate code, measured feedback and generation budgets, including failures. It excludes raw reasoning and infrastructure identifiers.
|
| 32 |
+
|
| 33 |
+
Published games are public. Keep private information out of your brief. Training-data contribution is optional and disabled by default. Browser smoke checks do not establish that every game is complete or winnable.
|
| 34 |
+
|
| 35 |
+
The gateway has no Hugging Face token. Its `ARCADE_EDGE_SECRET` Space secret signs a timestamp and a pseudonymous client identifier for backend quota enforcement. It never forwards raw IP addresses or exposes the signing secret to the browser. The primary backend enforces a durable global limit of 100 accepted builds per rolling 24 hours and a client limit of three per hour. The Space adds transient limits of three forwarded requests per client per hour and thirty total per rolling day; its counters reset on a Space restart.
|
| 36 |
+
|
| 37 |
+
[Source and evaluation method](https://github.com/alphabell-research/flint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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Small, bounded same-origin gateway for the alphaBell Arcade Space."""
|
| 2 |
+
import asyncio
|
| 3 |
+
from collections import defaultdict, deque
|
| 4 |
+
from contextlib import asynccontextmanager
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
import hashlib
|
| 7 |
+
import hmac
|
| 8 |
+
from http.cookies import SimpleCookie
|
| 9 |
+
import ipaddress
|
| 10 |
+
import os
|
| 11 |
+
import re
|
| 12 |
+
import secrets
|
| 13 |
+
import time
|
| 14 |
+
from urllib.parse import urlsplit
|
| 15 |
+
|
| 16 |
+
from fastapi import FastAPI, Request
|
| 17 |
+
from fastapi.responses import JSONResponse, Response
|
| 18 |
+
import httpx
|
| 19 |
+
|
| 20 |
+
MAX_DOCUMENT = 1_500_000
|
| 21 |
+
MAX_ASSET = 500_000
|
| 22 |
+
EDGE_COOKIE = "arcade_edge"
|
| 23 |
+
ASSETS = {"/app.js", "/styles.css", "/favicon.svg"}
|
| 24 |
+
ASSET_ROUTES = re.compile(r"^/(?:preview/[A-Za-z0-9_-]{1,80}\.png|fonts/[A-Za-z0-9][A-Za-z0-9_-]{0,100}\.(?:woff2|txt))$")
|
| 25 |
+
ROUTES = re.compile(r"^/(?:g/[A-Za-z0-9_-]{1,80}|play/[A-Za-z0-9_-]{1,80}|download/[A-Za-z0-9_-]{1,80}|api/(?:config|games(?:/[A-Za-z0-9_-]{1,80})?|jobs(?:/[A-Za-z0-9_-]{1,80})?)|health)?$")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass(frozen=True)
|
| 29 |
+
class Settings:
|
| 30 |
+
origin: str = "https://alphabell.com/arcade"
|
| 31 |
+
edge_secret: str = ""
|
| 32 |
+
space_host: str = ""
|
| 33 |
+
per_hour: int = 3
|
| 34 |
+
daily_cap: int = 30
|
| 35 |
+
|
| 36 |
+
def __post_init__(self):
|
| 37 |
+
parsed = urlsplit(self.origin)
|
| 38 |
+
if parsed.scheme != "https" or parsed.netloc != "alphabell.com" or parsed.path.rstrip("/") != "/arcade" or parsed.query or parsed.fragment:
|
| 39 |
+
raise ValueError("The gateway target must be the alphaBell Arcade application")
|
| 40 |
+
if self.space_host and not re.fullmatch(r"[a-z0-9-]+\.hf\.space", self.space_host):
|
| 41 |
+
raise ValueError("Invalid Space host")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class Limits:
|
| 45 |
+
"""A single-worker admission limit, in addition to durable backend quotas."""
|
| 46 |
+
def __init__(self):
|
| 47 |
+
self.hourly = defaultdict(deque)
|
| 48 |
+
self.daily = deque()
|
| 49 |
+
self.lock = asyncio.Lock()
|
| 50 |
+
|
| 51 |
+
async def admit(self, cookie, client):
|
| 52 |
+
now = time.time()
|
| 53 |
+
async with self.lock:
|
| 54 |
+
for key in list(self.hourly):
|
| 55 |
+
values = self.hourly[key]
|
| 56 |
+
while values and values[0] <= now - 3600:
|
| 57 |
+
values.popleft()
|
| 58 |
+
if not values:
|
| 59 |
+
del self.hourly[key]
|
| 60 |
+
while self.daily and self.daily[0] <= now - 86400:
|
| 61 |
+
self.daily.popleft()
|
| 62 |
+
if len(self.daily) >= self.daily_cap:
|
| 63 |
+
return False
|
| 64 |
+
keys = ("cookie:" + cookie, "client:" + client)
|
| 65 |
+
if any(len(self.hourly[key]) >= self.per_hour for key in keys):
|
| 66 |
+
return False
|
| 67 |
+
for key in keys:
|
| 68 |
+
self.hourly[key].append(now)
|
| 69 |
+
self.daily.append(now)
|
| 70 |
+
return True
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _signature(secret, value):
|
| 74 |
+
return hmac.new(secret.encode(), value.encode(), hashlib.sha256).hexdigest()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _edge_cookie(request, secret):
|
| 78 |
+
value = request.cookies.get(EDGE_COOKIE, "")
|
| 79 |
+
identity, _, signature = value.partition(".")
|
| 80 |
+
if not re.fullmatch(r"[A-Za-z0-9_-]{32}", identity) or not hmac.compare_digest(signature, _signature(secret, "cookie\n" + identity)):
|
| 81 |
+
identity = secrets.token_urlsafe(24)
|
| 82 |
+
return identity, identity + "." + _signature(secret, "cookie\n" + identity)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def _client(request, settings):
|
| 86 |
+
# HF's gateway appends the address it observes. Never trust the leftmost
|
| 87 |
+
# element, which a caller can supply. Outside Spaces use the direct peer.
|
| 88 |
+
address = request.client.host if request.client else "unknown"
|
| 89 |
+
forwarded = request.headers.get("x-forwarded-for", "")
|
| 90 |
+
if settings.space_host and forwarded:
|
| 91 |
+
address = forwarded.split(",")[-1].strip()
|
| 92 |
+
try:
|
| 93 |
+
address = str(ipaddress.ip_address(address))
|
| 94 |
+
except ValueError:
|
| 95 |
+
address = "unknown"
|
| 96 |
+
return _signature(settings.edge_secret, "client-ip\n" + address)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _upstream_cookie(raw):
|
| 100 |
+
cookies = SimpleCookie()
|
| 101 |
+
try:
|
| 102 |
+
cookies.load(raw)
|
| 103 |
+
except Exception:
|
| 104 |
+
return ""
|
| 105 |
+
item = cookies.get("arcade_owner")
|
| 106 |
+
if item and re.fullmatch(r"[A-Za-z0-9_-]{32}\.[0-9a-f]{64}", item.value):
|
| 107 |
+
return "arcade_owner=" + item.value
|
| 108 |
+
return ""
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _rewrite_cookie(raw):
|
| 112 |
+
if not raw.lower().startswith("arcade_owner="):
|
| 113 |
+
return None
|
| 114 |
+
# Drop Domain and origin-specific Path; keep only this gateway's cookie.
|
| 115 |
+
parts = [part.strip() for part in raw.split(";")]
|
| 116 |
+
kept = [parts[0]]
|
| 117 |
+
for part in parts[1:]:
|
| 118 |
+
name = part.split("=", 1)[0].lower()
|
| 119 |
+
if name in {"max-age", "expires"}:
|
| 120 |
+
kept.append(part)
|
| 121 |
+
return "; ".join(kept + ["Path=/", "HttpOnly", "Secure", "SameSite=None", "Partitioned"])
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _rewrite_location(location, origin):
|
| 125 |
+
parsed = urlsplit(location)
|
| 126 |
+
if parsed.scheme or parsed.netloc:
|
| 127 |
+
if parsed.scheme != "https" or parsed.netloc != "alphabell.com":
|
| 128 |
+
return None
|
| 129 |
+
path = parsed.path
|
| 130 |
+
else:
|
| 131 |
+
path = parsed.path
|
| 132 |
+
prefix = urlsplit(origin).path.rstrip("/")
|
| 133 |
+
if not (path == prefix or path.startswith(prefix + "/")):
|
| 134 |
+
return None
|
| 135 |
+
return (path[len(prefix):] or "/") + ("?" + parsed.query if parsed.query else "")
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def create_app(settings=None, transport=None):
|
| 139 |
+
settings = settings or Settings(origin=os.environ.get("ARCADE_ORIGIN", "https://alphabell.com/arcade").rstrip("/"), edge_secret=os.environ.get("ARCADE_EDGE_SECRET", ""), space_host=os.environ.get("SPACE_HOST", ""))
|
| 140 |
+
client = httpx.AsyncClient(transport=transport, trust_env=False, follow_redirects=False, verify=True, limits=httpx.Limits(max_connections=12, max_keepalive_connections=4))
|
| 141 |
+
limits = Limits()
|
| 142 |
+
limits.per_hour, limits.daily_cap = settings.per_hour, settings.daily_cap
|
| 143 |
+
|
| 144 |
+
@asynccontextmanager
|
| 145 |
+
async def lifespan(app):
|
| 146 |
+
yield
|
| 147 |
+
await client.aclose()
|
| 148 |
+
|
| 149 |
+
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
|
| 150 |
+
|
| 151 |
+
@app.api_route("/{path:path}", methods=["GET", "HEAD", "POST"])
|
| 152 |
+
async def proxy(path, request: Request):
|
| 153 |
+
public_path = "/" + path
|
| 154 |
+
if settings.space_host and request.url.hostname != settings.space_host:
|
| 155 |
+
return JSONResponse({"detail": "Not found."}, status_code=404)
|
| 156 |
+
is_asset = public_path in ASSETS or bool(ASSET_ROUTES.fullmatch(public_path))
|
| 157 |
+
if b"%" in request.scope.get("raw_path", b"") or request.url.query or (not is_asset and not ROUTES.fullmatch(public_path)):
|
| 158 |
+
return JSONResponse({"detail": "Not found."}, status_code=404)
|
| 159 |
+
is_post = request.method == "POST"
|
| 160 |
+
if is_post and public_path != "/api/jobs":
|
| 161 |
+
return JSONResponse({"detail": "Method not allowed."}, status_code=405)
|
| 162 |
+
if not is_post and public_path == "/api/jobs":
|
| 163 |
+
return JSONResponse({"detail": "Method not allowed."}, status_code=405)
|
| 164 |
+
cookie = _upstream_cookie(request.headers.get("cookie", ""))
|
| 165 |
+
# An explicit (possibly empty) Cookie header prevents the shared HTTP
|
| 166 |
+
# client's upstream cookie jar from crossing browser ownership boundaries.
|
| 167 |
+
outgoing = {"Accept": "*/*", "Accept-Encoding": "identity", "Cookie": cookie}
|
| 168 |
+
body = b""
|
| 169 |
+
edge_cookie = None
|
| 170 |
+
if is_post:
|
| 171 |
+
if not settings.edge_secret:
|
| 172 |
+
return JSONResponse({"detail": "Generation is temporarily unavailable."}, status_code=503)
|
| 173 |
+
incoming = request.headers.get("origin")
|
| 174 |
+
expected_host = settings.space_host or request.url.netloc
|
| 175 |
+
if incoming:
|
| 176 |
+
parsed = urlsplit(incoming)
|
| 177 |
+
if parsed.scheme not in {"https", "http"} or parsed.netloc != expected_host or parsed.path or parsed.query or parsed.fragment or (settings.space_host and parsed.scheme != "https"):
|
| 178 |
+
return JSONResponse({"detail": "Cross-origin requests are not allowed."}, status_code=403)
|
| 179 |
+
if request.headers.get("content-type", "").split(";", 1)[0].strip().lower() != "application/json":
|
| 180 |
+
return JSONResponse({"detail": "A JSON request is required."}, status_code=415)
|
| 181 |
+
chunks, size = [], 0
|
| 182 |
+
async for chunk in request.stream():
|
| 183 |
+
size += len(chunk)
|
| 184 |
+
if size > 16_384:
|
| 185 |
+
return JSONResponse({"detail": "Request is too large."}, status_code=413)
|
| 186 |
+
chunks.append(chunk)
|
| 187 |
+
body = b"".join(chunks)
|
| 188 |
+
identity, edge_cookie = _edge_cookie(request, settings.edge_secret)
|
| 189 |
+
pseudonym = _client(request, settings)
|
| 190 |
+
if not await limits.admit(identity, pseudonym):
|
| 191 |
+
return JSONResponse({"detail": "The arcade build limit has been reached. Please try again later."}, status_code=429)
|
| 192 |
+
timestamp = str(int(time.time()))
|
| 193 |
+
outgoing.update({"Content-Type": "application/json", "Origin": "https://alphabell.com", "X-Arcade-Edge-Client": pseudonym, "X-Arcade-Edge-Timestamp": timestamp, "X-Arcade-Edge-Signature": _signature(settings.edge_secret, timestamp + "\n" + pseudonym)})
|
| 194 |
+
target = settings.origin.rstrip("/") + public_path
|
| 195 |
+
timeout = httpx.Timeout(20 if is_post else 35, connect=10)
|
| 196 |
+
try:
|
| 197 |
+
async with asyncio.timeout(20 if is_post else 35), client.stream(request.method, target, headers=outgoing, content=body, timeout=timeout) as upstream:
|
| 198 |
+
if upstream.status_code >= 500:
|
| 199 |
+
return JSONResponse({"detail": "The arcade is temporarily unavailable. Please try again shortly."}, status_code=502)
|
| 200 |
+
cap = MAX_ASSET if is_asset else MAX_DOCUMENT
|
| 201 |
+
payload = bytearray()
|
| 202 |
+
async for chunk in upstream.aiter_bytes():
|
| 203 |
+
if len(payload) + len(chunk) > cap:
|
| 204 |
+
return JSONResponse({"detail": "The arcade response is unavailable."}, status_code=502)
|
| 205 |
+
payload.extend(chunk)
|
| 206 |
+
headers = {}
|
| 207 |
+
for name in ("content-type", "content-disposition", "content-security-policy", "permissions-policy", "referrer-policy", "x-content-type-options"):
|
| 208 |
+
if name in upstream.headers:
|
| 209 |
+
headers[name] = upstream.headers[name]
|
| 210 |
+
headers["Cache-Control"] = "no-store" if public_path.startswith("/api/jobs") or is_post else "public, max-age=60"
|
| 211 |
+
if "location" in upstream.headers:
|
| 212 |
+
location = _rewrite_location(upstream.headers["location"], settings.origin)
|
| 213 |
+
if location is None:
|
| 214 |
+
return JSONResponse({"detail": "The arcade response is unavailable."}, status_code=502)
|
| 215 |
+
headers["Location"] = location
|
| 216 |
+
if public_path == "/" or public_path.startswith("/g/"):
|
| 217 |
+
payload = bytes(payload).replace(b'<base href="/arcade/">', b'<base href="/">')
|
| 218 |
+
response = Response(bytes(payload), status_code=upstream.status_code, headers=headers)
|
| 219 |
+
for raw in upstream.headers.get_list("set-cookie"):
|
| 220 |
+
rewritten = _rewrite_cookie(raw)
|
| 221 |
+
if rewritten:
|
| 222 |
+
response.headers.append("set-cookie", rewritten)
|
| 223 |
+
if edge_cookie:
|
| 224 |
+
response.headers.append("set-cookie", f"{EDGE_COOKIE}={edge_cookie}; Path=/; Max-Age=86400; HttpOnly; Secure; SameSite=None; Partitioned")
|
| 225 |
+
return response
|
| 226 |
+
except (httpx.HTTPError, ValueError, TimeoutError):
|
| 227 |
+
return JSONResponse({"detail": "The arcade is temporarily unavailable. Please try again shortly."}, status_code=502)
|
| 228 |
+
|
| 229 |
+
return app
|