Spaces:
Sleeping
Sleeping
Adarsh Kumar commited on
Update cloudflare_provider.py
Browse files2 unmodified lines34567891067891011121312131415161415161728 unmodified lines4647485149505155525354555657585960596162636465666768691 unmodified line717273747576687778798081828373848586878889908081919293941 unmodified line969798899091929394959910010110210310410510610798108109100101102110111112113106114115116117167 unmodified lines2852862872802812822882892902912922932862872942952962972982922932942993003013023036 unmodified lines3103113123133143153163093103173183193203153163173213223233243253269 unmodified lines33633733833933334034133534234334434534634734811 unmodified lines3603613623533543553563573583593603633643653663673623683693703713663723733743759 unmodified lines3853863873883893903833843913923933946 unmodified lines4014024033973984044054064 unmodified lines41141241340941441541641741841941541641742042142242342442551 unmodified lines47747847947548048148248326 unmodified lines5105115125085135145105115125135155165175185195155205215225231 unmodified line52552652752352452552652752852953053153253353453553652953053753853953253353453553654054154254354454554654754854955053855155255354054154254355455555655755855956056156256356456555256656756856957057155557257357457557657757857958055758158258358458558656458758858959059159259359457159559657359759859960060157857958060260360460538 unmodified lines64464564662562662762862963063163263363463563663763863964764864965065165265322 unmodified lines6766776786686696706716726796806816826836846856866876776786796886896906916846856866926936948 unmodified lines7037047057017067077087097107117127087137147157167177187197207147217227237187247257267217277287297307317257327277337347357367377387397407417337347357367377427437447457467477487497507407417427437517527537547557567577587597607507617627637641 unmodified line76676776875876977077177277377476577577677777820 unmodified lines79980080179280280380436 unmodified lines84184284383583683784484584684784284384484584684784884884985085185285385485585685732 unmodified lines89089189288788888989389489521 unmodified lines91791891991792092192292341 unmodified lines9659669679659689699702 unmodified lines9739749759749769779769789789799809819826 unmodified lines98999099199199299299399499553 unmodified lines10491050105110521053105410521053105410581059106010551056105710 unmodified lines106810691070107710781079107110721073107410759 unmodified lines1085108610871095109610971088108910901091110010921093109410952 unmodified lines1098109911001109111011011102110311041105111411062 unmodified lines║ cloudflare_provider.py ║║ Cloudflare AI Playground — Reverse Engineered Provider ║║ ║║ Connection Strategy: ║║ 1. Try DIRECT Python WebSocket (no browser needed) ║║ 2. If blocked → launch browser with Xvfb virtual display ║║ extract cookies → reconnect with cookies via Python WS ║║ 3. If still blocked → keep browser as WS relay ║║ Display modes (auto-detected, no config needed): ║║ XVFB_EXTERNAL=1 + DISPLAY=:99 ║║ → entrypoint.sh already started Xvfb; just use DISPLAY ║║ VR_DISPLAY=1 ║║ → pyvirtualdisplay starts its own Xvfb (dev/local use) ║║ Neither ║║ → direct Python WS only; browser fallback disabled ║║ ║║ Virtual Display: ║║ Set env var VR_DISPLAY=1 to auto-start Xvfb via ║║ pyvirtualdisplay (required on headless Linux / HF Spaces). ║║ ║║ NOTE: Headless Chrome is intentionally disabled — ║║ NOTE: Chrome --headless is intentionally NEVER used. ║║ Cloudflare blocks headless user agents. ║╚═══════════════════════════════════════════════════════════════╝"""28 unmodified lines
_HAS_BROWSER = Falsetry: _install("DrissionPage") from DrissionPage import ChromiumPage, ChromiumOptions _HAS_BROWSER = Trueexcept Exception: pass try: _install("DrissionPage") from DrissionPage import ChromiumPage, ChromiumOptions _HAS_BROWSER = True except Exception as _br_err: print(f"[cloudflare] ⚠ DrissionPage unavailable: {_br_err}", file=sys.stderr)
# ═══════════════════════════════════════════════════════════# §1b — VIRTUAL DISPLAY (from OS env)# §1b — DISPLAY DETECTION## Three modes, detected in priority order:# 1. XVFB_EXTERNAL=1 → entrypoint.sh manages Xvfb, DISPLAY is set# 2. VR_DISPLAY=1 → we spawn pyvirtualdisplay ourselves# 3. DISPLAY is set → assume a real display exists (local dev)# ═══════════════════════════════════════════════════════════def _parse_bool_env(key: str, default: bool = False) -> bool: val = os.environ.get(key, "").strip().lower()1 unmodified line return default return val in ("1", "true", "yes", "on", "enable", "enabled")
XVFB_EXTERNAL = _parse_bool_env("XVFB_EXTERNAL", default=False)VR_DISPLAY = _parse_bool_env("VR_DISPLAY", default=False)
VR_DISPLAY = _parse_bool_env("VR_DISPLAY", default=False)# Is any display available?_DISPLAY_ENV = os.environ.get("DISPLAY", "").strip()HAS_DISPLAY = bool(_DISPLAY_ENV) or XVFB_EXTERNAL
_HAS_VIRTUAL_DISPLAY = False_Display = None
if VR_DISPLAY:if VR_DISPLAY and not XVFB_EXTERNAL: try: _install("pyvirtualdisplay", "PyVirtualDisplay") from pyvirtualdisplay import Display as _Display _HAS_VIRTUAL_DISPLAY = True except Exception as _vd_err: print( f"[cloudflare] ⚠ VR_DISPLAY=1 but pyvirtualdisplay failed: {_vd_err}\n" f"[cloudflare] Make sure Xvfb is installed: sudo apt install xvfb", f"[cloudflare] ⚠ pyvirtualdisplay failed: {_vd_err}", file=sys.stderr, flush=True, )
1 unmodified line# ═══════════════════════════════════════════════════════════# §2 — CONSTANTS# ═══════════════════════════════════════════════════════════_SITE = "https://playground.ai.cloudflare.com"_WS_BASE = "wss://playground.ai.cloudflare.com/agents/playground"_CACHE = Path(__file__).resolve().parent / "cache"_MFILE = _CACHE / "cloudflare_models.json"_CHARS = string.ascii_letters + string.digits_LOWER = string.ascii_lowercase + string.digits_UA = (_SITE = "https://playground.ai.cloudflare.com"_WS_BASE = "wss://playground.ai.cloudflare.com/agents/playground"_CACHE = Path(__file__).resolve().parent / "cache"_MFILE = _CACHE / "cloudflare_models.json"_CHARS = string.ascii_letters + string.digits_LOWER = string.ascii_lowercase + string.digits_UA = ( "Mozilla/5.0 (Windows NT 10.0; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/146.0.0.0 Safari/537.36" "Chrome/136.0.0.0 Safari/537.36")
# Model cache TTL — 6 hours_CACHE_TTL_SECONDS = 6 * 3600_CACHE_TTL = 6 * 3600 # 6 hours
# ═══════════════════════════════════════════════════════════# §3 — MODEL TABLE (short alias → full @cf/@hf ID)# §3 — MODEL TABLE# ═══════════════════════════════════════════════════════════_SHORT_TO_FULL: dict[str, str] = { "gpt-oss-120b": "@cf/openai/gpt-oss-120b",167 unmodified lines def save(models): _CACHE.mkdir(parents=True, exist_ok=True) _MFILE.write_text(json.dumps({ "ts": time.time(), # epoch for TTL checks "ts_human": time.strftime("%Y-%m-%d %H:%M:%S"), "models": models, "ts": time.time(), "ts_human": time.strftime("%Y-%m-%d %H:%M:%S"), "models": models, }, indent=2, ensure_ascii=False))
@staticmethod def load(ttl: int = _CACHE_TTL_SECONDS): """Load cache only if it exists and is within TTL.""" def load(ttl: int = _CACHE_TTL): if not _MFILE.exists(): return None try: data = json.loads(_MFILE.read_text()) age = time.time() - data.get("ts", 0) if age > ttl: return None # stale — force refresh if time.time() - data.get("ts", 0) > ttl: return None # stale return data.get("models") except Exception: return None6 unmodified lines
# ═══════════════════════════════════════════════════════════# §6b — VIRTUAL DISPLAY MANAGER# Only used when VR_DISPLAY=1 AND XVFB_EXTERNAL=0.# When XVFB_EXTERNAL=1, the entrypoint.sh manages Xvfb.# ═══════════════════════════════════════════════════════════class _VirtualDisplayManager: """Thread-safe singleton that manages a single Xvfb display."""
_instance = None _lock = threading.Lock()
def __init__(self): self._display = None self._running = False self._enabled = VR_DISPLAY and _HAS_VIRTUAL_DISPLAY self._display = None self._running = False self._enabled = VR_DISPLAY and _HAS_VIRTUAL_DISPLAY and not XVFB_EXTERNAL
@classmethod def instance(cls) -> "_VirtualDisplayManager":9 unmodified lines
@property def running(self) -> bool: # If external Xvfb is managing the display, report as "running" return self._running return self._running or XVFB_EXTERNAL
def start(self, width: int = 1920, height: int = 1080, depth: int = 24): def start(self, width=1920, height=1080, depth=24): if XVFB_EXTERNAL: _log_vd("External Xvfb detected (XVFB_EXTERNAL=1) — skipping pyvirtualdisplay") return if not self._enabled: return if self._running:11 unmodified lines ) self._display.start() self._running = True _log_vd(f"✓ Virtual display started " f"({width}x{height}x{depth}) " f"on :{self._display.display}") except FileNotFoundError: _log_vd( "✗ Xvfb binary not found! Install: sudo apt install xvfb" ) self._enabled = False # Make sure DISPLAY env is set for child processes if not os.environ.get("DISPLAY"): os.environ["DISPLAY"] = f":{self._display.display}" _log_vd(f"✓ Started pyvirtualdisplay on DISPLAY={os.environ.get('DISPLAY')}") except Exception as exc: _log_vd(f"✗ Failed to start virtual display: {exc}") _log_vd(f"✗ pyvirtualdisplay failed: {exc}") self._enabled = False
def stop(self): if not self._running: if XVFB_EXTERNAL or not self._running: return with self._lock: if not self._running:9 unmodified lines self._running = False
def __repr__(self): if XVFB_EXTERNAL: return f"VirtualDisplay(external DISPLAY={_DISPLAY_ENV})" state = "running" if self._running else ("idle" if self._enabled else "disabled") disp = f" :{self._display.display}" if self._running and self._display else "" return f"VirtualDisplay({state}{disp})" return f"VirtualDisplay({state})"
def _log_vd(msg: str):6 unmodified lines
# ── 7a: Direct Python WebSocket ──────────────────────────class _DirectTransport: """Pure Python WS via websocket-client with background recv thread."""
def __init__(self, debug=False): self._ws = None self._inbox = []4 unmodified lines
def connect(self, url: str, cookies: str = "") -> bool: self._ws = _ws_mod.WebSocket() headers = [f"User-Agent: {_UA}"] headers = [f"User-Agent: {_UA}"] if cookies: headers.append(f"Cookie: {cookies}")
self._ws.connect( url, origin=_SITE, header=headers, timeout=15, origin = _SITE, header = headers, timeout = 15, )
self._running = True51 unmodified lines self._thread = None
# ── 7b: Browser-based WebSocket (fallback) ───────────────# ── 7b: Browser WebSocket (Xvfb display required) ────────_BROWSER_JS = """(function(){ if(window.__cfws) return 'exists';26 unmodified lines
class _BrowserTransport: """ Headless-FREE Chrome WebSocket relay via Xvfb virtual display. Chrome WebSocket relay.
NOTE: We intentionally do NOT use Chrome's --headless flag because Cloudflare Playground detects and blocks headless user agents. Instead we rely on pyvirtualdisplay / Xvfb to provide a real (but invisible) X11 display on servers that have no physical monitor. Display requirements (in priority order): 1. XVFB_EXTERNAL=1 — entrypoint.sh started Xvfb, DISPLAY=:99 is set 2. VR_DISPLAY=1 — pyvirtualdisplay spawns its own Xvfb 3. DISPLAY env var — any real display (local dev)
Set VR_DISPLAY=1 before importing to enable this behaviour. Chrome --headless is NEVER used. Cloudflare blocks headless agents. """
def __init__(self, debug=False):1 unmodified line self._debug = debug self._vd_mgr = _VirtualDisplayManager.instance()
def connect(self, url: str, **_) -> bool: if not _HAS_BROWSER: raise RuntimeError( "DrissionPage not available — cannot use browser fallback" ) def _ensure_display(self): """Make sure a display is available before launching Chrome.""" display = os.environ.get("DISPLAY", "")
if display: # Display already set (external Xvfb or local X11) _log_vd(f"Using existing display DISPLAY={display}") return
# ── Start virtual display (Xvfb) if enabled ────── if self._vd_mgr.enabled and not self._vd_mgr.running: # Try to start pyvirtualdisplay if self._vd_mgr.enabled: self._vd_mgr.start() if not self._vd_mgr.running: raise RuntimeError( "Virtual display (Xvfb) failed to start. " "Install xvfb: apt-get install -y xvfb" ) display = os.environ.get("DISPLAY", "") if display: return
raise RuntimeError( "No X display available for Chrome.\n" " On servers: set XVFB_EXTERNAL=1 and start Xvfb before this process,\n" " or set VR_DISPLAY=1 to let pyvirtualdisplay manage Xvfb.\n" " Headless Chrome is intentionally disabled (Cloudflare blocks it)." )
if not self._vd_mgr.running: def connect(self, url: str, **_) -> bool: if not _HAS_BROWSER: raise RuntimeError( "No display available and VR_DISPLAY is not set. " "Set VR_DISPLAY=1 to use Xvfb virtual display, " "or run on a machine with a real display. " "Headless Chrome is intentionally disabled." "DrissionPage not installed — cannot use browser fallback.\n" "Install: pip install DrissionPage" )
self._ensure_display()
opts = ChromiumOptions() opts.set_argument("--disable-blink-features=AutomationControlled") opts.set_argument("--no-sandbox") opts.set_argument("--disable-dev-shm-usage") opts.set_argument("--disable-gpu") opts.set_argument("--disable-extensions") opts.set_argument("--disable-plugins") opts.set_argument("--disable-infobars") opts.set_argument("--window-size=1280,720") opts.set_argument("--disable-background-networking") opts.set_argument("--disable-sync") opts.set_argument("--metrics-recording-only") opts.set_argument("--mute-audio") # ── NO headless flag — Cloudflare blocks headless ── # ── NO --headless flag — Cloudflare blocks headless ──
_log_vd(f"Launching Chrome on DISPLAY={os.environ.get('DISPLAY', 'unset')}")
try: self._page = ChromiumPage(addr_or_opts=opts) except Exception as e: raise RuntimeError(f"Chrome failed to launch: {e}") from e
self._page = ChromiumPage(addr_or_opts=opts) self._page.get(_SITE) time.sleep(4)
self._page.run_js(_BROWSER_JS) self._page.run_js(f"window.__cfws.connect('{url}');")
deadline = time.time() + 15 deadline = time.time() + 20 while time.time() < deadline: if self._page.run_js("return window.__cfws.alive;"): _log_vd("✓ Browser WebSocket connected") return True err = self._page.run_js("return window.__cfws.error;") if err: raise ConnectionError(f"Browser WS failed: {err}") time.sleep(0.1) time.sleep(0.15)
raise ConnectionError("Browser WS timed out waiting for connection") raise ConnectionError("Browser WS timed out waiting for open state")
def send(self, data: str) -> bool: try: return bool( self._page.run_js( f"return window.__cfws.send({json.dumps(data)});" ) self._page.run_js(f"return window.__cfws.send({json.dumps(data)});") ) except Exception: return False38 unmodified lines """ ☁️ Cloudflare AI Playground — fully modular provider.
Virtual Display (required on headless servers): Set VR_DISPLAY=1 before importing this module. This starts Xvfb so Chrome has a real (invisible) display. Headless Chrome is intentionally NOT used — Cloudflare blocks it.
$ export VR_DISPLAY=1 $ python server.py
Usage: provider = CloudflareProvider() for chunk in provider.chat(data="Hello!"): print(chunk, end="")
# non-streaming: response = provider.ask("What is 2+2?") Display modes (auto-detected): • XVFB_EXTERNAL=1 — entrypoint.sh manages Xvfb on DISPLAY=:99 • VR_DISPLAY=1 — pyvirtualdisplay spawns Xvfb internally • DISPLAY set — use existing display (local dev) """
def __init__(22 unmodified lines self.last_response: str = "" self.last_reasoning: str = ""
self._sid: str = "" self._pk: str = "" self._transport = None self._mode: str = "" self._on: bool = False self._sid: str = "" self._pk: str = "" self._transport = None self._mode: str = "" self._on: bool = False
self._boot() atexit.register(self.close)
# ───────────────────────────────────────────────── # Logging # ───────────────────────────────────────────────── def _d(self, *a): if self.debug: print("[cloudflare]", *a, file=sys.stderr, flush=True)
# ───────────────────────────────────────────────── # Low-level WS # ───────────────────────────────────────────────── def _pull(self) -> list[str]: msgs = self._transport.recv() if self.debug:8 unmodified lines raise RuntimeError("WebSocket send failed")
# ───────────────────────────────────────────────── # Boot — tries direct WS first, then Xvfb browser # Boot # ───────────────────────────────────────────────── def _boot(self): self._sid = _make_sid() self._pk = _make_pk() url = _make_ws_url(self._sid, self._pk)
# ── Attempt 1: direct Python WebSocket ────── # ── Attempt 1: direct Python WS ───────────── direct_err = None try: self._d("Trying direct Python WebSocket...") t = _DirectTransport(debug=self.debug) t.connect(url) time.sleep(0.4)
time.sleep(0.3) if t.alive: self._transport = t self._mode = "direct" self._d("✓ Direct connection — no browser needed!") self._d("✓ Direct WebSocket connected") else: t.close() raise ConnectionError("Direct WS not alive after connect") raise ConnectionError("WS not alive after connect")
except Exception as e: direct_err = e self._d(f"Direct failed: {e}") self._d("Falling back to browser transport (Xvfb)...")
# ── Attempt 2: Xvfb + Chrome relay ────── # ── Attempt 2: Browser relay via Xvfb ─────── if self._transport is None: browser_err = None try: self._d("Trying browser transport (Xvfb Chrome)...") t = _BrowserTransport(debug=self.debug) t.connect(url) self._transport = t self._mode = "browser" self._d("✓ Browser transport connected") vd = _VirtualDisplayManager.instance() if vd.running: self._d(f" └─ {vd}") except Exception as e2: self._d(f"✓ Browser transport connected (DISPLAY={os.environ.get('DISPLAY', '?')})")
except Exception as e: browser_err = e self._d(f"Browser failed: {e}")
if self._transport is None: raise ConnectionError( f"All connection methods failed.\n" f" Direct: {e}\n" f" Browser: {e2}\n" f" Tip: ensure VR_DISPLAY=1 and xvfb is installed." ) from e2 f" Direct: {direct_err}\n" f" Browser: {browser_err}\n" f" → Check network connectivity and DISPLAY / XVFB_EXTERNAL env vars." )
self._on = True
# ── Handshake ────────────────────────────── want = {"cf_agent_identity", "cf_agent_state", "cf_agent_mcp_servers"} seen = set() deadline = time.time() + 10 deadline = time.time() + 12 while time.time() < deadline and seen < want: for raw in self._pull(): try:1 unmodified line except Exception: pass time.sleep(0.05)
self._d(f"Handshake received: {seen}")
self._push({"type": "cf_agent_stream_resume_request"}) time.sleep(0.3) self._pull()
# ── Models + state ───────────────────────── # ── Models ───────────────────────────────── self._load_models() if self.max_tokens is None: self.max_tokens = self._ctx_window(self.model)20 unmodified lines def _fetch_models(self): rid = str(uuid.uuid4()) self._push({"args": [], "id": rid, "method": "getModels", "type": "rpc"})
deadline = time.time() + 15 while time.time() < deadline: for raw in self._pull():36 unmodified lines return full return _SHORT_TO_FULL.get(name, name)
# ───────────────────────────────────────────────── # State Sync # ───────────────────────────────────────────────── def _sync(self): self._push({ "type": "cf_agent_state", "state": { "model": self.model, "temperature": self.temperature, "stream": True, "system": self.system, "useExternalProvider": False, "externalProvider": "openai", "authMethod": "provider-key", "model": self.model, "temperature": self.temperature, "stream": True, "system": self.system, "useExternalProvider": False, "externalProvider": "openai", "authMethod": "provider-key", }, }) time.sleep(0.15)32 unmodified lines def get_history(self) -> list[dict]: return _Conv.to_openai(self.history, self.system)
# ───────────────────────────────────────────────── # Model listing # ───────────────────────────────────────────────── def list_models(self) -> list[dict]: return [{ "name": m.get("name", ""),21 unmodified lines max_tokens: int = None, ) -> Generator[str, None, None]: if not self._on: raise RuntimeError("Not connected — call new_session()") raise RuntimeError("Not connected") if not messages and not data: raise ValueError("Provide 'messages' or 'data'")
41 unmodified lines
while not done: if not self._transport.alive: self._d("Transport died mid-stream") if not full_text: yield "[Connection lost]\n" break2 unmodified lines
if not msgs: elapsed = time.time() - last_data limit = self.timeout_idle if got_first else self.timeout_init limit = self.timeout_idle if got_first else self.timeout_init if elapsed > limit: self._d(f"Timeout after {elapsed:.1f}s") if not full_text: yield "[Timeout — no response received]\n" yield "[Timeout — no response]\n" break time.sleep(0.015 if got_first else 0.04) continue6 unmodified lines except Exception: continue
ftype = f.get("type", "") if ftype != "cf_agent_use_chat_response": if f.get("type") != "cf_agent_use_chat_response": continue
body_str = f.get("body", "")53 unmodified lines self.last_response = full_text self.last_reasoning = reasoning
# ───────────────────────────────────────────────── # ask() — non-streaming convenience # ───────────────────────────────────────────────── def ask(self, prompt: str, **kwargs) -> str: return "".join(self.chat(data=prompt, **kwargs))
# ───────────────────────────────────────────────── # Session management # ───────────────────────────────────────────────── def new_session(self): self._close_transport() self.history.clear()10 unmodified lines
def close(self): self._close_transport() if self._mode == "browser": vd = _VirtualDisplayManager.instance() vd.stop() if self._mode == "browser" and not XVFB_EXTERNAL: _VirtualDisplayManager.instance().stop() self._d("Closed.")
def __enter__(self):9 unmodified lines pass
def __repr__(self): s = "✅" if self._on else "❌" vd = _VirtualDisplayManager.instance() vd_info = f" vdisplay={vd}" if vd.enabled else "" s = "✅" if self._on else "❌" vd = _VirtualDisplayManager.instance() return ( f"CloudflareProvider({s} mode={self._mode!r} " f"model={self.model!r} max_tokens={self.max_tokens}{vd_info})" f"model={self.model!r} {vd})" )
2 unmodified lines# ═══════════════════════════════════════════════════════════def _cleanup_virtual_display(): try: vd = _VirtualDisplayManager.instance() vd.stop() if not XVFB_EXTERNAL: _VirtualDisplayManager.instance().stop() except Exception: pass
atexit.register(_cleanup_virtual_display)atexit.register(_cleanup_virtual_display)cloudflare_provider.py+169-177