Spaces:
Sleeping
Sleeping
Adarsh Kumar commited on
Update cloudflare_provider.py
Browse files2 unmodified lines34567891011121314151617181928 unmodified lines4849505152535455565758596061621 unmodified line6465666768697071727374757677787980818283841 unmodified line8687888990919293949596979899100101102103104105106107108109167 unmodified lines2772782792802812822832842852862872882892902912922932942952962976 unmodified lines3043053063073083093103113123133143153163173183193209 unmodified lines33033133233333433533633733811 unmodified lines3503513523533543553563573583593603613623633643653663673683699 unmodified lines3793803813823833843853863876 unmodified lines3943953963973983994004014 unmodified lines40640740840941041141241341441541641741841942051 unmodified lines47247347447547647747826 unmodified lines5055065075085095105115125135145155165175181 unmodified line52052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258338 unmodified lines62262362462562662762862963063163263363463563663763863964064164222 unmodified lines6656666676686696706716726736746756766776786796806816826836846856866876886898 unmodified lines6986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527531 unmodified line75575675775875976076176276376476576676776820 unmodified lines78979079179279379479536 unmodified lines83283383483583683783883984084184284384484584684784884985085132 unmodified lines88488588688788888989089189221 unmodified lines91491591691791891992041 unmodified lines9629639649659669679682 unmodified lines9719729739749759769779789799809816 unmodified lines98898999099199299399499553 unmodified lines10491050105110521053105410551056105710581059106010611062106310 unmodified lines1074107510761077107810791080108110829 unmodified lines1092109310941095109610971098109911001101110211032 unmodified lines1106110711081109111011111112111311142 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 ║║ ║║ 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 — ║║ Cloudflare blocks headless user agents. ║╚═══════════════════════════════════════════════════════════════╝"""28 unmodified lines_HAS_BROWSER = Falsetry:_install("DrissionPage")from DrissionPage import ChromiumPage, ChromiumOptions_HAS_BROWSER = Trueexcept Exception:pass# ═══════════════════════════════════════════════════════════# §1b — VIRTUAL DISPLAY (from OS env)# ═══════════════════════════════════════════════════════════def _parse_bool_env(key: str, default: bool = False) -> bool:val = os.environ.get(key, "").strip().lower()1 unmodified linereturn defaultreturn val in ("1", "true", "yes", "on", "enable", "enabled")VR_DISPLAY = _parse_bool_env("VR_DISPLAY", default=False)_HAS_VIRTUAL_DISPLAY = False_Display = Noneif VR_DISPLAY:try:_install("pyvirtualdisplay", "PyVirtualDisplay")from pyvirtualdisplay import Display as _Display_HAS_VIRTUAL_DISPLAY = Trueexcept 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",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 = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 (KHTML, like Gecko) ""Chrome/146.0.0.0 Safari/537.36")# Model cache TTL — 6 hours_CACHE_TTL_SECONDS = 6 * 3600# ═══════════════════════════════════════════════════════════# §3 — MODEL TABLE (short alias → full @cf/@hf ID)# ═══════════════════════════════════════════════════════════_SHORT_TO_FULL: dict[str, str] = {"gpt-oss-120b": "@cf/openai/gpt-oss-120b",167 unmodified linesdef 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,}, indent=2, ensure_ascii=False))@staticmethoddef load(ttl: int = _CACHE_TTL_SECONDS):"""Load cache only if it exists and is within TTL."""if not _MFILE.exists():return Nonetry:data = json.loads(_MFILE.read_text())age = time.time() - data.get("ts", 0)if age > ttl:return None # stale — force refreshreturn data.get("models")except Exception:return None6 unmodified lines# ═══════════════════════════════════════════════════════════# §6b — VIRTUAL DISPLAY MANAGER# ═══════════════════════════════════════════════════════════class _VirtualDisplayManager:"""Thread-safe singleton that manages a single Xvfb display."""_instance = None_lock = threading.Lock()def __init__(self):self._display = Noneself._running = Falseself._enabled = VR_DISPLAY and _HAS_VIRTUAL_DISPLAY@classmethoddef instance(cls) -> "_VirtualDisplayManager":9 unmodified lines@propertydef running(self) -> bool:return self._runningdef start(self, width: int = 1920, height: int = 1080, depth: int = 24):if not self._enabled:returnif 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 = Falseexcept Exception as exc:_log_vd(f"✗ Failed to start virtual display: {exc}")self._enabled = Falsedef stop(self):if not self._running:returnwith self._lock:if not self._running:9 unmodified linesself._running = Falsedef __repr__(self):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})"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 = Noneself._inbox = []4 unmodified linesdef connect(self, url: str, cookies: str = "") -> bool:self._ws = _ws_mod.WebSocket()headers = [f"User-Agent: {_UA}"]if cookies:headers.append(f"Cookie: {cookies}")self._ws.connect(url,origin=_SITE,header=headers,timeout=15,)self._running = True51 unmodified linesself._thread = None# ── 7b: Browser-based WebSocket (fallback) ───────────────_BROWSER_JS = """(function(){if(window.__cfws) return 'exists';26 unmodified linesclass _BrowserTransport:"""Headless-FREE Chrome WebSocket relay via Xvfb virtual display.NOTE: We intentionally do NOT use Chrome's --headless flag becauseCloudflare Playground detects and blocks headless user agents.Instead we rely on pyvirtualdisplay / Xvfb to provide a real (butinvisible) X11 display on servers that have no physical monitor.Set VR_DISPLAY=1 before importing to enable this behaviour."""def __init__(self, debug=False):1 unmodified lineself._debug = debugself._vd_mgr = _VirtualDisplayManager.instance()def connect(self, url: str, **_) -> bool:if not _HAS_BROWSER:raise RuntimeError("DrissionPage not available — cannot use browser fallback")# ── Start virtual display (Xvfb) if enabled ──────if self._vd_mgr.enabled and not self._vd_mgr.running: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")if not self._vd_mgr.running: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.")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")# ── NO headless flag — Cloudflare blocks headless ──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() + 15while time.time() < deadline:if self._page.run_js("return window.__cfws.alive;"):return Trueerr = self._page.run_js("return window.__cfws.error;")if err:raise ConnectionError(f"Browser WS failed: {err}")time.sleep(0.1)raise ConnectionError("Browser WS timed out waiting for connection")def send(self, data: str) -> bool:try:return bool(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.pyUsage:provider = CloudflareProvider()for chunk in provider.chat(data="Hello!"):print(chunk, end="")# non-streaming:response = provider.ask("What is 2+2?")"""def __init__(22 unmodified linesself.last_response: str = ""self.last_reasoning: str = ""self._sid: str = ""self._pk: str = ""self._transport = Noneself._mode: str = ""self._on: bool = Falseself._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 linesraise RuntimeError("WebSocket send failed")# ─────────────────────────────────────────────────# Boot — tries direct WS first, then Xvfb browser# ─────────────────────────────────────────────────def _boot(self):self._sid = _make_sid()self._pk = _make_pk()url = _make_ws_url(self._sid, self._pk)# ── Attempt 1: direct Python WebSocket ──────try:self._d("Trying direct Python WebSocket...")t = _DirectTransport(debug=self.debug)t.connect(url)time.sleep(0.3)if t.alive:self._transport = tself._mode = "direct"self._d("✓ Direct connection — no browser needed!")else:t.close()raise ConnectionError("Direct WS not alive after connect")except Exception as e:self._d(f"Direct failed: {e}")self._d("Falling back to browser transport (Xvfb)...")# ── Attempt 2: Xvfb + Chrome relay ──────try:t = _BrowserTransport(debug=self.debug)t.connect(url)self._transport = tself._mode = "browser"self._d("✓ Browser transport connected")vd = _VirtualDisplayManager.instance()if vd.running:self._d(f" └─ {vd}")except Exception as e2: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 e2self._on = True# ── Handshake ──────────────────────────────want = {"cf_agent_identity", "cf_agent_state", "cf_agent_mcp_servers"}seen = set()deadline = time.time() + 10while time.time() < deadline and seen < want:for raw in self._pull():try:1 unmodified lineexcept Exception:passtime.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 ─────────────────────────self._load_models()if self.max_tokens is None:self.max_tokens = self._ctx_window(self.model)20 unmodified linesdef _fetch_models(self):rid = str(uuid.uuid4())self._push({"args": [], "id": rid, "method": "getModels", "type": "rpc"})deadline = time.time() + 15while time.time() < deadline:for raw in self._pull():36 unmodified linesreturn fullreturn _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",},})time.sleep(0.15)32 unmodified linesdef 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 linesmax_tokens: int = None,) -> Generator[str, None, None]:if not self._on:raise RuntimeError("Not connected — call new_session()")if not messages and not data:raise ValueError("Provide 'messages' or 'data'")41 unmodified lineswhile not done:if not self._transport.alive:self._d("Transport died mid-stream")if not full_text:yield "[Connection lost]\n"break2 unmodified linesif not msgs:elapsed = time.time() - last_datalimit = self.timeout_idle if got_first else self.timeout_initif elapsed > limit:self._d(f"Timeout after {elapsed:.1f}s")if not full_text:yield "[Timeout — no response received]\n"breaktime.sleep(0.015 if got_first else 0.04)continue6 unmodified linesexcept Exception:continueftype = f.get("type", "")if ftype != "cf_agent_use_chat_response":continuebody_str = f.get("body", "")53 unmodified linesself.last_response = full_textself.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 linesdef close(self):self._close_transport()if self._mode == "browser":vd = _VirtualDisplayManager.instance()vd.stop()self._d("Closed.")def __enter__(self):9 unmodified linespassdef __repr__(self):s = "✅" if self._on else "❌"vd = _VirtualDisplayManager.instance()vd_info = f" vdisplay={vd}" if vd.enabled else ""return (f"CloudflareProvider({s} mode={self._mode!r} "f"model={self.model!r} max_tokens={self.max_tokens}{vd_info})")2 unmodified lines# ═══════════════════════════════════════════════════════════def _cleanup_virtual_display():try:vd = _VirtualDisplayManager.instance()vd.stop()except Exception:passatexit.register(_cleanup_virtual_display)2 unmodified lines3456789101112131415161728 unmodified lines4647484950515253545556575859606162636465666768691 unmodified line7172737475767778798081828384858687888990919293941 unmodified line96979899100101102103104105106107108109110111112113114115116117167 unmodified lines2852862872882892902912922932942952962972982993003013023036 unmodified lines3103113123133143153163173183193203213223233243253269 unmodified lines33633733833934034134234334434534634734811 unmodified lines3603613623633643653663673683693703713723733743759 unmodified lines3853863873883893903913923933946 unmodified lines4014024034044054064 unmodified lines41141241341441541641741841942042142242342442551 unmodified lines47747847948048148248326 unmodified lines5105115125135145155165175185195205215225231 unmodified line52552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460538 unmodified lines64464564664764864965065165265322 unmodified lines6766776786796806816826836846856866876886896906916926936948 unmodified lines7037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637641 unmodified line76676776876977077177277377477577677777820 unmodified lines79980080180280380436 unmodified lines84184284384484584684784884985085185285385485585685732 unmodified lines89089189289389489521 unmodified lines91791891992092192292341 unmodified lines9659669679689699702 unmodified lines9739749759769779789799809819826 unmodified lines98999099199299399499553 unmodified lines10491050105110521053105410551056105710 unmodified lines106810691070107110721073107410759 unmodified lines108510861087108810891090109110921093109410952 unmodified lines1098109911001101110211031104110511062 unmodified lines║ cloudflare_provider.py ║║ Cloudflare AI Playground — Reverse Engineered Provider ║║ ║║ 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 ║║ ║║ NOTE: Chrome --headless is intentionally NEVER used. ║║ Cloudflare blocks headless user agents. ║╚═══════════════════════════════════════════════════════════════╝"""28 unmodified lines_HAS_BROWSER = Falsetry:from DrissionPage import ChromiumPage, ChromiumOptions_HAS_BROWSER = Trueexcept Exception:try:_install("DrissionPage")from DrissionPage import ChromiumPage, ChromiumOptions_HAS_BROWSER = Trueexcept Exception as _br_err:print(f"[cloudflare] ⚠ DrissionPage unavailable: {_br_err}", file=sys.stderr)# ═══════════════════════════════════════════════════════════# §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 linereturn defaultreturn 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)# Is any display available?_DISPLAY_ENV = os.environ.get("DISPLAY", "").strip()HAS_DISPLAY = bool(_DISPLAY_ENV) or XVFB_EXTERNAL_HAS_VIRTUAL_DISPLAY = False_Display = Noneif VR_DISPLAY and not XVFB_EXTERNAL:try:_install("pyvirtualdisplay", "PyVirtualDisplay")from pyvirtualdisplay import Display as _Display_HAS_VIRTUAL_DISPLAY = Trueexcept Exception as _vd_err:print(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 = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) ""AppleWebKit/537.36 (KHTML, like Gecko) ""Chrome/136.0.0.0 Safari/537.36")_CACHE_TTL = 6 * 3600 # 6 hours# ═══════════════════════════════════════════════════════════# §3 — MODEL TABLE# ═══════════════════════════════════════════════════════════_SHORT_TO_FULL: dict[str, str] = {"gpt-oss-120b": "@cf/openai/gpt-oss-120b",167 unmodified linesdef save(models):_CACHE.mkdir(parents=True, exist_ok=True)_MFILE.write_text(json.dumps({"ts": time.time(),"ts_human": time.strftime("%Y-%m-%d %H:%M:%S"),"models": models,}, indent=2, ensure_ascii=False))@staticmethoddef load(ttl: int = _CACHE_TTL):if not _MFILE.exists():return Nonetry:data = json.loads(_MFILE.read_text())if time.time() - data.get("ts", 0) > ttl:return None # stalereturn 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:_instance = None_lock = threading.Lock()def __init__(self):self._display = Noneself._running = Falseself._enabled = VR_DISPLAY and _HAS_VIRTUAL_DISPLAY and not XVFB_EXTERNAL@classmethoddef instance(cls) -> "_VirtualDisplayManager":9 unmodified lines@propertydef running(self) -> bool:# If external Xvfb is managing the display, report as "running"return self._running or XVFB_EXTERNALdef start(self, width=1920, height=1080, depth=24):if XVFB_EXTERNAL:_log_vd("External Xvfb detected (XVFB_EXTERNAL=1) — skipping pyvirtualdisplay")returnif not self._enabled:returnif self._running:11 unmodified lines)self._display.start()self._running = True# Make sure DISPLAY env is set for child processesif 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"✗ pyvirtualdisplay failed: {exc}")self._enabled = Falsedef stop(self):if XVFB_EXTERNAL or not self._running:returnwith self._lock:if not self._running:9 unmodified linesself._running = Falsedef __repr__(self):if XVFB_EXTERNAL:return f"VirtualDisplay(external DISPLAY={_DISPLAY_ENV})"state = "running" if self._running else ("idle" if self._enabled else "disabled")return f"VirtualDisplay({state})"def _log_vd(msg: str):6 unmodified lines# ── 7a: Direct Python WebSocket ──────────────────────────class _DirectTransport:def __init__(self, debug=False):self._ws = Noneself._inbox = []4 unmodified linesdef connect(self, url: str, cookies: str = "") -> bool:self._ws = _ws_mod.WebSocket()headers = [f"User-Agent: {_UA}"]if cookies:headers.append(f"Cookie: {cookies}")self._ws.connect(url,origin = _SITE,header = headers,timeout = 15,)self._running = True51 unmodified linesself._thread = None# ── 7b: Browser WebSocket (Xvfb display required) ────────_BROWSER_JS = """(function(){if(window.__cfws) return 'exists';26 unmodified linesclass _BrowserTransport:"""Chrome WebSocket relay.Display requirements (in priority order):1. XVFB_EXTERNAL=1 — entrypoint.sh started Xvfb, DISPLAY=:99 is set2. VR_DISPLAY=1 — pyvirtualdisplay spawns its own Xvfb3. DISPLAY env var — any real display (local dev)Chrome --headless is NEVER used. Cloudflare blocks headless agents."""def __init__(self, debug=False):1 unmodified lineself._debug = debugself._vd_mgr = _VirtualDisplayManager.instance()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# Try to start pyvirtualdisplayif self._vd_mgr.enabled:self._vd_mgr.start()display = os.environ.get("DISPLAY", "")if display:returnraise 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).")def connect(self, url: str, **_) -> bool:if not _HAS_BROWSER:raise RuntimeError("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-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 ──_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 eself._page.get(_SITE)time.sleep(4)self._page.run_js(_BROWSER_JS)self._page.run_js(f"window.__cfws.connect('{url}');")deadline = time.time() + 20while time.time() < deadline:if self._page.run_js("return window.__cfws.alive;"):_log_vd("✓ Browser WebSocket connected")return Trueerr = self._page.run_js("return window.__cfws.error;")if err:raise ConnectionError(f"Browser WS failed: {err}")time.sleep(0.15)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)});"))except Exception:return False38 unmodified lines"""☁️ Cloudflare AI Playground — fully modular provider.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 linesself.last_response: str = ""self.last_reasoning: str = ""self._sid: str = ""self._pk: str = ""self._transport = Noneself._mode: str = ""self._on: bool = Falseself._boot()atexit.register(self.close)def _d(self, *a):if self.debug:print("[cloudflare]", *a, file=sys.stderr, flush=True)def _pull(self) -> list[str]:msgs = self._transport.recv()if self.debug:8 unmodified linesraise RuntimeError("WebSocket send failed")# ─────────────────────────────────────────────────# Boot# ─────────────────────────────────────────────────def _boot(self):self._sid = _make_sid()self._pk = _make_pk()url = _make_ws_url(self._sid, self._pk)# ── Attempt 1: direct Python WS ─────────────direct_err = Nonetry:self._d("Trying direct Python WebSocket...")t = _DirectTransport(debug=self.debug)t.connect(url)time.sleep(0.4)if t.alive:self._transport = tself._mode = "direct"self._d("✓ Direct WebSocket connected")else:t.close()raise ConnectionError("WS not alive after connect")except Exception as e:direct_err = eself._d(f"Direct failed: {e}")# ── Attempt 2: Browser relay via Xvfb ───────if self._transport is None:browser_err = Nonetry:self._d("Trying browser transport (Xvfb Chrome)...")t = _BrowserTransport(debug=self.debug)t.connect(url)self._transport = tself._mode = "browser"self._d(f"✓ Browser transport connected (DISPLAY={os.environ.get('DISPLAY', '?')})")except Exception as e:browser_err = eself._d(f"Browser failed: {e}")if self._transport is None:raise ConnectionError(f"All connection methods failed.\n"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() + 12while time.time() < deadline and seen < want:for raw in self._pull():try:1 unmodified lineexcept Exception:passtime.sleep(0.05)self._d(f"Handshake received: {seen}")self._push({"type": "cf_agent_stream_resume_request"})time.sleep(0.3)self._pull()# ── Models ─────────────────────────────────self._load_models()if self.max_tokens is None:self.max_tokens = self._ctx_window(self.model)20 unmodified linesdef _fetch_models(self):rid = str(uuid.uuid4())self._push({"args": [], "id": rid, "method": "getModels", "type": "rpc"})deadline = time.time() + 15while time.time() < deadline:for raw in self._pull():36 unmodified linesreturn fullreturn _SHORT_TO_FULL.get(name, name)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",},})time.sleep(0.15)32 unmodified linesdef get_history(self) -> list[dict]:return _Conv.to_openai(self.history, self.system)def list_models(self) -> list[dict]:return [{"name": m.get("name", ""),21 unmodified linesmax_tokens: int = None,) -> Generator[str, None, None]:if not self._on:raise RuntimeError("Not connected")if not messages and not data:raise ValueError("Provide 'messages' or 'data'")41 unmodified lineswhile not done:if not self._transport.alive:if not full_text:yield "[Connection lost]\n"break2 unmodified linesif not msgs:elapsed = time.time() - last_datalimit = self.timeout_idle if got_first else self.timeout_initif elapsed > limit:if not full_text:yield "[Timeout — no response]\n"breaktime.sleep(0.015 if got_first else 0.04)continue6 unmodified linesexcept Exception:continueif f.get("type") != "cf_agent_use_chat_response":continuebody_str = f.get("body", "")53 unmodified linesself.last_response = full_textself.last_reasoning = reasoningdef ask(self, prompt: str, **kwargs) -> str:return "".join(self.chat(data=prompt, **kwargs))def new_session(self):self._close_transport()self.history.clear()10 unmodified linesdef close(self):self._close_transport()if self._mode == "browser" and not XVFB_EXTERNAL:_VirtualDisplayManager.instance().stop()self._d("Closed.")def __enter__(self):9 unmodified linespassdef __repr__(self):s = "✅" if self._on else "❌"vd = _VirtualDisplayManager.instance()return (f"CloudflareProvider({s} mode={self._mode!r} "f"model={self.model!r} {vd})")2 unmodified lines# ═══════════════════════════════════════════════════════════def _cleanup_virtual_display():try:if not XVFB_EXTERNAL:_VirtualDisplayManager.instance().stop()except Exception:passatexit.register(_cleanup_virtual_display)
cloudflare_provider.py+169-177