Download app.py from Evidra/web-agent: direct link, hf CLI and curl.
- Browser
- Download file 12.6 kB
-
https://huggingface.co/spaces/Evidra/web-agent/resolve/main/app.py
- Command line
-
hf download hf://spaces/Evidra/web-agent/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Evidra/web-agent/resolve/main/app.py
12.6 kB
| #!/usr/bin/env python3 | |
| """web-agent — live application server. | |
| A working product surface for the web-agent system: pick a task and | |
| watch the agent actually run it in headless Chromium, streamed live — | |
| every observation, action outcome, failure, recovery and screenshot is | |
| a real event from a real execution of the system's own code | |
| (see runner.py). The Evaluation view reads the system's recorded | |
| full-suite run files (results/run_on.json / results/run_off.json in the | |
| system directory) at request time; nothing is hand-entered. | |
| Pure Python standard library HTTP server — the environment has no web | |
| framework, and none is needed. Two ways to run it: | |
| * Development (uses the web-agent system's own virtual environment, | |
| which provides Playwright): | |
| ~/workspace/browser-agent-lab/.venv/bin/python app.py | |
| * Deployment / any Python with Playwright installed (the agent code | |
| is vendored under system/ in this directory — see runner.py): | |
| python3 app.py | |
| Then open http://localhost:8000 (PORT env var overrides the port; | |
| Hugging Face Spaces sets PORT=7860 via the Dockerfile). | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import os | |
| import queue | |
| import threading | |
| from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer | |
| from pathlib import Path | |
| from urllib.parse import parse_qs, unquote, urlparse | |
| import runner | |
| APP_DIR = Path(__file__).resolve().parent | |
| STATIC_DIR = APP_DIR / "static" | |
| RESULTS_DIR = runner.LAB_DIR / "results" | |
| FIXTURES_DIR = runner.FIXTURES_DIR | |
| MAX_CONCURRENT_RUNS = 2 | |
| _run_slots = threading.Semaphore(MAX_CONCURRENT_RUNS) | |
| CONTENT_TYPES = {".html": "text/html; charset=utf-8", | |
| ".css": "text/css; charset=utf-8", | |
| ".js": "text/javascript; charset=utf-8", | |
| ".json": "application/json", | |
| ".png": "image/png", ".jpg": "image/jpeg", | |
| ".webp": "image/webp", | |
| ".svg": "image/svg+xml", ".ico": "image/x-icon"} | |
| def load_recorded() -> dict: | |
| """Parse the system's recorded full-suite results from its own | |
| run files. This is the single source for every number in the | |
| Evaluation view.""" | |
| data = {} | |
| for mode in ("on", "off"): | |
| path = RESULTS_DIR / f"run_{mode}.json" | |
| if path.exists(): | |
| payload = json.loads(path.read_text()) | |
| data[mode] = {"passed": payload["passed"], | |
| "total": payload["total"], | |
| "by_task": {r["task"]: r for r in payload["tasks"]}} | |
| return data | |
| def evaluation_payload() -> dict: | |
| rec = load_recorded() | |
| on, off = rec.get("on"), rec.get("off") | |
| out = {"source_files": ["results/run_on.json", "results/run_off.json"], | |
| "summary": {}, "categories": [], "tasks": []} | |
| if not (on and off): | |
| out["available"] = False | |
| return out | |
| out["available"] = True | |
| def split(rows_by_task, names): | |
| sel = [rows_by_task[n] for n in names if n in rows_by_task] | |
| return {"passed": sum(1 for r in sel if r["success"]), | |
| "total": len(sel)} | |
| all_names = [t["name"] for t in runner.task_catalogue({})] | |
| adv_names = [t.name for t in runner.TASKS if t.adversarial] | |
| ctl_names = [t.name for t in runner.TASKS if not t.adversarial] | |
| for mode, payload in (("on", on), ("off", off)): | |
| out["summary"][mode] = { | |
| "overall": {"passed": payload["passed"], | |
| "total": payload["total"]}, | |
| "adversarial": split(payload["by_task"], adv_names), | |
| "controls": split(payload["by_task"], ctl_names)} | |
| cats = [] | |
| for t in runner.TASKS: | |
| cat = runner.TASK_CATEGORIES.get(t.name, "Other") | |
| if cat not in cats: | |
| cats.append(cat) | |
| for cat in cats: | |
| names = [t.name for t in runner.TASKS | |
| if runner.TASK_CATEGORIES.get(t.name, "Other") == cat] | |
| out["categories"].append({ | |
| "category": cat, | |
| "on": split(on["by_task"], names), | |
| "off": split(off["by_task"], names)}) | |
| for t in runner.TASKS: | |
| row = {"task": t.name, "adversarial": t.adversarial, | |
| "category": runner.TASK_CATEGORIES.get(t.name, "Other")} | |
| for mode, payload in (("on", on), ("off", off)): | |
| r = payload["by_task"].get(t.name) | |
| row[mode] = ({"success": r["success"], "attempts": r["attempts"], | |
| "recoveries": r["recoveries"], | |
| "error": r["error"]} if r else None) | |
| out["tasks"].append(row) | |
| return out | |
| class Handler(BaseHTTPRequestHandler): | |
| server_version = "WebAgentApp/1.0" | |
| def log_message(self, fmt, *args): # keep the console readable | |
| pass | |
| # -- helpers ------------------------------------------------------ | |
| def _send(self, code, body: bytes, ctype: str) -> None: | |
| self.send_response(code) | |
| self.send_header("Content-Type", ctype) | |
| self.send_header("Content-Length", str(len(body))) | |
| self.end_headers() | |
| self.wfile.write(body) | |
| def _send_json(self, obj, code=200) -> None: | |
| self._send(code, json.dumps(obj).encode(), "application/json") | |
| def _send_file(self, path: Path) -> None: | |
| if not path.is_file(): | |
| self._send_json({"error": "not found"}, 404) | |
| return | |
| ctype = CONTENT_TYPES.get(path.suffix.lower(), | |
| "application/octet-stream") | |
| self._send(200, path.read_bytes(), ctype) | |
| # -- routes --------------------------------------------------------- | |
| def do_GET(self): | |
| parsed = urlparse(self.path) | |
| path = parsed.path | |
| if path in ("/", "/index.html"): | |
| self._send_file(STATIC_DIR / "index.html") | |
| elif path.startswith("/static/"): | |
| rel = unquote(path[len("/static/"):]) | |
| self._send_file((STATIC_DIR / rel).resolve() | |
| if (STATIC_DIR / rel).resolve().is_relative_to( | |
| STATIC_DIR.resolve()) | |
| else Path("/nonexistent")) | |
| elif path.startswith("/fixtures/"): | |
| name = unquote(path[len("/fixtures/"):]) | |
| target = (FIXTURES_DIR / name).resolve() | |
| if target.is_relative_to(FIXTURES_DIR.resolve()) \ | |
| and target.suffix == ".html": | |
| self._send_file(target) | |
| else: | |
| self._send_json({"error": "not found"}, 404) | |
| elif path == "/api/tasks": | |
| rec = load_recorded() | |
| flat = {mode: p["by_task"] for mode, p in rec.items()} | |
| self._send_json({"tasks": runner.task_catalogue(flat)}) | |
| elif path == "/api/evaluation": | |
| self._send_json(evaluation_payload()) | |
| elif path == "/api/traces": | |
| self._send_json({"traces": runner.trace_catalogue()}) | |
| elif path == "/api/trace": | |
| self._stream_trace(parsed) | |
| elif path == "/api/run-public-check": | |
| qs = parse_qs(parsed.query) | |
| url = (qs.get("url") or [""])[0] | |
| check = runner.validate_public_url(url) | |
| self._send_json({"ok": check["ok"], | |
| "error": check.get("error", ""), | |
| "domain": check.get("domain", "")}) | |
| elif path == "/api/run-public": | |
| self._stream_public_run(parsed) | |
| elif path == "/api/run": | |
| self._stream_run(parsed) | |
| else: | |
| self._send_json({"error": "not found"}, 404) | |
| def _stream_events(self, work) -> None: | |
| """Run `work(emit)` on a thread under the run-slot semaphore | |
| and stream its events as SSE until its terminal sentinel.""" | |
| if not _run_slots.acquire(blocking=False): | |
| self._send_json( | |
| {"error": "another run is in progress — try again shortly"}, | |
| 429) | |
| return | |
| events: queue.Queue = queue.Queue() | |
| def runner_thread(): | |
| try: | |
| work(events.put) | |
| finally: | |
| events.put(None) # terminal sentinel | |
| _run_slots.release() | |
| threading.Thread(target=runner_thread, daemon=True).start() | |
| try: | |
| self.send_response(200) | |
| self.send_header("Content-Type", "text/event-stream") | |
| self.send_header("Cache-Control", "no-cache") | |
| self.send_header("Connection", "close") | |
| self.end_headers() | |
| self.close_connection = True | |
| while True: | |
| try: | |
| ev = events.get(timeout=180) | |
| except queue.Empty: | |
| self.wfile.write(b": run timed out\n\n") | |
| break | |
| if ev is None: | |
| break | |
| self.wfile.write( | |
| f"data: {json.dumps(ev)}\n\n".encode()) | |
| self.wfile.flush() | |
| except (BrokenPipeError, ConnectionResetError): | |
| pass # visitor closed the stream; the run finishes on its own | |
| def _stream_trace(self, parsed) -> None: | |
| qs = parse_qs(parsed.query) | |
| name = (qs.get("name") or [""])[0] | |
| if name not in runner.trace_names(): | |
| self._send_json({"error": f"unknown trace: {name}"}, 400) | |
| return | |
| self._stream_events(lambda emit: runner.play_trace(name, emit)) | |
| def _stream_public_run(self, parsed) -> None: | |
| qs = parse_qs(parsed.query) | |
| url = (qs.get("url") or [""])[0] | |
| intent = (qs.get("intent") or [""])[0] | |
| label = (qs.get("label") or [""])[0] | |
| text = (qs.get("text") or [""])[0] | |
| recovery = (qs.get("recovery") or ["on"])[0].lower() != "off" | |
| if intent not in ("click", "type"): | |
| self._send_json({"error": "unknown intent"}, 400) | |
| return | |
| if not label.strip(): | |
| self._send_json({"error": "a label is required"}, 400) | |
| return | |
| # The rails are enforced before any browsing: a refused URL | |
| # never reaches the runner. | |
| check = runner.validate_public_url(url) | |
| if not check["ok"]: | |
| self._send_json({"error": check["error"]}, 400) | |
| return | |
| self._stream_events( | |
| lambda emit: runner.execute_public_run( | |
| url, intent, label, text, recovery, emit)) | |
| def _stream_run(self, parsed) -> None: | |
| qs = parse_qs(parsed.query) | |
| task_name = (qs.get("task") or [""])[0] | |
| recovery = (qs.get("recovery") or ["on"])[0].lower() != "off" | |
| if task_name not in runner.TASKS_BY_NAME: | |
| self._send_json({"error": f"unknown task: {task_name}"}, 400) | |
| return | |
| if not _run_slots.acquire(blocking=False): | |
| self._send_json( | |
| {"error": "another run is in progress — try again shortly"}, | |
| 429) | |
| return | |
| events: queue.Queue = queue.Queue() | |
| def work(): | |
| try: | |
| runner.execute_run(task_name, recovery, events.put) | |
| finally: | |
| events.put(None) # terminal sentinel | |
| _run_slots.release() | |
| threading.Thread(target=work, daemon=True).start() | |
| try: | |
| self.send_response(200) | |
| self.send_header("Content-Type", "text/event-stream") | |
| self.send_header("Cache-Control", "no-cache") | |
| self.send_header("Connection", "close") | |
| self.end_headers() | |
| # The stream has no Content-Length; closing the connection | |
| # when the run ends is what tells the client it is complete. | |
| self.close_connection = True | |
| while True: | |
| try: | |
| ev = events.get(timeout=180) | |
| except queue.Empty: | |
| self.wfile.write(b": run timed out\n\n") | |
| break | |
| if ev is None: | |
| break | |
| self.wfile.write( | |
| f"data: {json.dumps(ev)}\n\n".encode()) | |
| self.wfile.flush() | |
| except (BrokenPipeError, ConnectionResetError): | |
| pass # visitor closed the stream; the run finishes on its own | |
| def main() -> None: | |
| port = int(os.environ.get("PORT", "8000")) | |
| server = ThreadingHTTPServer(("0.0.0.0", port), Handler) | |
| server.daemon_threads = True | |
| print(f"web-agent app: http://localhost:{port} " | |
| f"(system: {runner.LAB_DIR})") | |
| try: | |
| server.serve_forever() | |
| except KeyboardInterrupt: | |
| pass | |
| if __name__ == "__main__": | |
| main() | |