"""Live run execution for the web-agent app. This module is the thinnest possible wrapper around the web-agent system's own code: * The agent that runs is the system's own `src.agent.Agent`, imported unchanged from the system directory — the byte-identical vendored copy under `system/` next to this file (deployment layout), or the system checkout at ~/workspace/browser-agent-lab (development layout); see LAB_DIR resolution below. Task definitions come from the system's own `src.tasks.TASKS`, and the browser is driven exactly the way the system's evaluation runner drives it: headless Chromium, one fresh context per task, the fixture page loaded from its real location on disk. * The only additions here are presentation hooks: - `StreamLog` is a drop-in replacement for the system's file-based `RunLog` (the Agent only ever calls `log.write(...)`), which forwards each observe / failure / recovery event to the caller as it happens. - `StreamingAgent` subclasses `Agent` and overrides two methods solely to capture a screenshot after each step and after an overlay dismissal. No grounding, action, verification or recovery logic is altered. * Every run is a real execution. Nothing is replayed or simulated. """ from __future__ import annotations import base64 import json import os import sys import time from pathlib import Path from urllib.parse import urlparse _APP_DIR = Path(__file__).resolve().parent if os.environ.get("WEB_AGENT_LAB_DIR"): LAB_DIR = Path(os.environ["WEB_AGENT_LAB_DIR"]) elif (_APP_DIR / "system").is_dir(): # Deployment layout: the system's code is vendored byte-identical # under system/ inside this app (the HF Spaces container cannot # reach the checkout outside its own directory). LAB_DIR = _APP_DIR / "system" else: # Development layout: the system checkout beside this app. LAB_DIR = _APP_DIR.parent / "browser-agent-lab" LAB_DIR = LAB_DIR.resolve() if str(LAB_DIR) not in sys.path: sys.path.insert(0, str(LAB_DIR)) from playwright.sync_api import sync_playwright # noqa: E402 from src.agent import ACTION_TIMEOUT_MS, Agent, Step, Target, Task # noqa: E402 from src.public_mode import (MAX_PUBLIC_STEPS, field_block_reason, # noqa: E402 registrable_domain, resolve_host, validate_public_url) from src.snapshot import Snapshot # noqa: E402 from src.tasks import TASK_CATEGORIES, TASKS, field_value_is # noqa: E402 FIXTURES_DIR = LAB_DIR / "fixtures" TASKS_BY_NAME = {t.name: t for t in TASKS} TRACES_DIR = _APP_DIR / "traces" VIEWPORT = {"width": 1100, "height": 750} class StreamLog: """Duck-typed stand-in for the system's RunLog: same write() interface, but each record is normalised into a stream event.""" def __init__(self, emit): self._emit = emit def write(self, task: str, event: str, **kw) -> None: if event == "observe": self._emit({"type": "observe", "step": kw.get("step"), "elements": kw.get("elements")}) elif event == "step_ok": self._emit({"type": "step_ok", "step": kw.get("step"), "ref": kw.get("ref")}) elif event == "failure": self._emit({"type": "failure", "step": kw.get("step"), "reason": kw.get("reason", "")}) elif event == "recovery": if kw.get("kind") == "dismiss_overlay": self._emit({"type": "dismiss_overlay", "control": kw.get("control", "")}) else: self._emit({"type": "recovery", "step": kw.get("step"), "kind": kw.get("kind", "reground_retry")}) elif event == "task_success": self._emit({"type": "task_success", "attempts": kw.get("attempts"), "recoveries": kw.get("recoveries")}) def close(self) -> None: pass class StreamingAgent(Agent): """The system's Agent, plus screenshot hooks. Behaviour identical.""" def __init__(self, page, recovery: bool, log, emit): super().__init__(page, recovery=recovery, log=log) self._emit = emit def _shot(self, note: str, step=None) -> None: try: # Viewport capture only (full_page=False): the streamed # frame shows what the agent itself sees — its 1100x750 # viewport — not the fixture's full page height. png = self.page.screenshot(type="jpeg", quality=68, full_page=False) self._emit({"type": "screenshot", "step": step, "note": note, "data": base64.b64encode(png).decode("ascii")}) except Exception: pass # a failed capture never fails the run def _run_step(self, task, idx, step, res) -> bool: ok = super()._run_step(task, idx, step, res) self._shot(f"after step {idx}", step=idx) return ok def _dismiss_overlay(self, task_name: str) -> bool: dismissed = super()._dismiss_overlay(task_name) if dismissed: self._shot("overlay dismissed") return dismissed def execute_run(task_name: str, recovery: bool, emit) -> None: """Run one task for real and stream events through `emit`. Runs on its own thread (Playwright's sync API is thread-bound) and always finishes by emitting exactly one terminal event: `verdict` or `error`. """ task = TASKS_BY_NAME.get(task_name) if task is None: emit({"type": "error", "message": f"unknown task: {task_name}"}) return try: with sync_playwright() as pw: browser = pw.chromium.launch(headless=True) try: context = browser.new_context(viewport=VIEWPORT) page = context.new_page() page.goto((FIXTURES_DIR / task.fixture).as_uri()) agent = StreamingAgent(page, recovery=recovery, log=StreamLog(emit), emit=emit) agent._shot("task page loaded", step=0) emit({"type": "started", "task": task.name, "fixture": task.fixture, "description": task.description, "adversarial": task.adversarial, "recovery": recovery, "steps_total": len(task.steps)}) res = agent.run_task(task) emit({"type": "verdict", "task": task.name, "success": res.success, "steps_completed": res.steps_completed, "steps_total": len(task.steps), "attempts": res.attempts, "recoveries": res.recoveries, "error": res.error}) context.close() finally: browser.close() except Exception as exc: # harness-level failure: report, never fake emit({"type": "error", "message": f"run failed: {exc}"}) # --------------------------------------------------------------------------- # Public-page mode (bounded generic mode) # # A visitor supplies one public http(s) URL and one fixed intent — # click the element with a given label, or type text into the field # with a given label and submit. The run reuses the StreamingAgent # loop unchanged; everything specific to this mode is a rail around # it, implemented in src/public_mode.py (validation) and in # PublicStreamingAgent / execute_public_run below: # * the URL is validated before any browsing (scheme, localhost, # every resolved address public); # * the target field is checked before the run and before every # fill step (password / payment fields are refused); # * navigation requests to a different registrable domain are # aborted at the network layer, and the page's domain is checked # before and after every step — leaving the entered domain is a # hard stop, reported as such; # * downloads are disabled; # * an intent is at most MAX_PUBLIC_STEPS steps, inside the fixture # suite's own step/attempt budgets. # --------------------------------------------------------------------------- SUBMIT_TEXTS = {"submit", "search", "send", "save", "go", "apply", "continue", "sign in", "log in", "subscribe", "ok"} class PublicBlocked(Exception): """A public-page run hit a safety rail; the message says which.""" class PublicStreamingAgent(StreamingAgent): """StreamingAgent plus two per-step rails: the page must still be on the entered registrable domain, and a fill step's field must not be a password or payment field.""" def __init__(self, page, recovery: bool, log, emit, allowed_domain: str, blocked_nav=None): super().__init__(page, recovery=recovery, log=log, emit=emit) self._allowed_domain = allowed_domain # callable -> host the network guard stopped a navigation to, # or None; a blocked navigation must be reported, not hidden self._blocked_nav = blocked_nav def _domain_now(self) -> str: host = urlparse(self.page.url).hostname or "" return registrable_domain(host) def _nav_block(self, res) -> bool: """True (with res.error set) when the run must hard-stop for leaving, or trying to leave, the entered domain.""" if self._blocked_nav is not None: host = self._blocked_nav() if host: res.error = ("blocked: the run tried to navigate to a " f"different domain ({host}) than the one " "entered — run stopped") return True if self._domain_now() != self._allowed_domain: res.error = ("blocked: the page navigated to a different " f"domain ({self._domain_now()}) than the one " "entered — run stopped") return True return False def _run_step(self, task, idx, step, res) -> bool: if self._nav_block(res): return False if step.action == "fill": snap = Snapshot.take(self.page) rec = self._find_exact(snap, step.target) if rec is not None: reason = field_block_reason(rec) if reason is not None: res.error = (f"refused: the field labelled " f"“{step.target.label or step.target.name}” " f"was not typed into — {reason}") return False ok = super()._run_step(task, idx, step, res) if self._nav_block(res): return False return ok # Field-matching tiers for public-mode grounding, in order: the # visitor's label is matched against a field's own