web-agent / runner.py
Evidra's picture
Public mode: reveal toggle-hidden fields; grounding order label > aria-label > placeholder > name
a5fc6c1 verified
Raw History Blame Contribute Delete
26.5 kB
"""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 <label> text
# first, then its aria-label, then its placeholder, then its name.
_FIELD_TIERS = ("label", "aria", "placeholder", "name")
_FIELD_TYPES = ("", "text", "email", "search", "password",
"number", "tel", "url")
def _is_field(rec: dict) -> bool:
return rec["tag"] == "textarea" or \
(rec["tag"] == "input" and rec["type"] in _FIELD_TYPES)
def _match_field(records, label: str):
"""First field record matching `label`, tier by tier
(label -> aria-label -> placeholder -> name). Returns
(record, tier) or (None, "")."""
for tier in _FIELD_TIERS:
for rec in records:
if _is_field(rec) and rec[tier] == label:
return rec, tier
return None, ""
def _find_toggle(snap: Snapshot, hidden_rec: dict, label: str):
"""The visible control that reveals a hidden field: a clickable
in the same widget (sharing an ancestor id with the field) whose
text or aria-label names the same purpose β€” the whole label, or
its first word (e.g. "Search" for "Search Wikipedia"). Falls back
to a purpose-named clickable anywhere on the page, then to the
widget's only clickable."""
clickables = [r for r in snap.elements
if r["visible"] and not r["disabled"] and r["recipe"]
and (r["tag"] in ("button", "a")
or r["role"] in ("button", "link"))]
purpose = label.strip().lower()
first_word = purpose.split()[0] if purpose.split() else ""
field_anc = set(hidden_rec.get("ancestors") or [])
same_widget = [r for r in clickables
if field_anc & set(r.get("ancestors") or [])]
def names(rec):
return {(rec["text"] or "").strip().lower(),
(rec["aria"] or "").strip().lower()}
for pool in (same_widget, clickables):
for rec in pool:
n = names(rec)
if purpose in n or (first_word and first_word in n):
return rec
if len(same_widget) == 1:
return same_widget[0]
return None
def _reveal_field(page, snap: Snapshot, hidden_rec: dict,
label: str) -> None:
"""Activate the toggle that hides the matched field, then wait
until re-observation shows the field. The toggle may expand the
field in place or navigate (same domain β€” the run's domain guard
still applies) to a page carrying it. Raises PublicBlocked when
there is no toggle or the field stays hidden."""
toggle = _find_toggle(snap, hidden_rec, label)
if toggle is None:
raise PublicBlocked(
f"the field labelled β€œ{label}” is hidden on the page and "
"no toggle control for it was found β€” the run was not "
"started")
try:
page.locator(toggle["recipe"]).first.click(
timeout=ACTION_TIMEOUT_MS)
except Exception:
raise PublicBlocked(
f"the field labelled β€œ{label}” is hidden on the page and "
"its toggle control could not be activated β€” the run was "
"not started")
deadline = time.time() + 3.0
while time.time() < deadline:
try:
snap_now = Snapshot.take(page)
except Exception:
snap_now = None # page mid-navigation; keep waiting
if snap_now is not None:
visible = [r for r in snap_now.elements
if r["visible"] and not r["disabled"]]
if _match_field(visible, label)[0] is not None:
return
time.sleep(0.25)
raise PublicBlocked(
f"the field labelled β€œ{label}” stayed hidden after its "
"toggle was used β€” the run was not started")
def _public_steps(page, intent: str, label: str, text: str) -> list:
"""Build the intent's steps from a fresh snapshot of the loaded
page. Raises PublicBlocked when the intent cannot be carried out
inside the rails (target missing, field refused, no submit
control)."""
snap = Snapshot.take(page)
visible = [r for r in snap.elements if r["visible"] and not r["disabled"]]
if intent == "click":
cands = [r for r in visible
if (r["tag"] == "button" or r["tag"] == "a"
or r["role"] in ("button", "link")
or (r["tag"] == "input"
and r["type"] in ("submit", "button")))
and (r["text"] == label or r["aria"] == label)]
if not cands:
raise PublicBlocked(
f"no clickable element labelled β€œ{label}” was found "
"on the page")
rec = cands[0]
role = "link" if rec["tag"] == "a" else "button"
return [Step("click", Target(role, text=label))]
# intent == "type": fill the labelled field, then submit.
# Grounding order: exact label -> aria-label -> placeholder ->
# name, visible fields first. A field that exists but is not
# visible is looked for with the same order among all records:
# real pages hide fields behind toggle controls (Wikipedia's
# header search collapses behind its search toggle below a
# 1120px viewport; this app runs at 1100px). A refused field is
# refused before anything is clicked; otherwise the toggle is
# activated and the page re-observed, and every step is then
# built from the fresh snapshot.
rec, _tier = _match_field(visible, label)
if rec is None:
hidden, _tier = _match_field(list(snap.elements), label)
if hidden is None:
raise PublicBlocked(
f"no field labelled β€œ{label}” was found on the page")
reason = field_block_reason(hidden)
if reason is not None:
raise PublicBlocked(
f"refused: the field labelled β€œ{label}” was not typed "
f"into β€” {reason}")
_reveal_field(page, snap, hidden, label)
snap = Snapshot.take(page)
visible = [r for r in snap.elements
if r["visible"] and not r["disabled"]]
rec, _tier = _match_field(visible, label)
if rec is None:
raise PublicBlocked(
f"the field labelled β€œ{label}” stayed hidden after "
"its toggle was used β€” the run was not started")
reason = field_block_reason(rec)
if reason is not None:
raise PublicBlocked(
f"refused: the field labelled β€œ{label}” was not typed "
f"into β€” {reason}")
if rec["label"] == label:
target = Target("textbox", label=label)
elif rec["name"]:
target = Target("textbox", name=rec["name"])
elif rec["label"]:
target = Target("textbox", label=rec["label"])
else:
target = Target("textbox", label=label)
steps = [Step("fill", target, text,
verify=field_value_is(rec["recipe"], text)
if rec["recipe"] else None)]
form = rec["form"]
submits = [r for r in visible
if (r["type"] == "submit"
or (r["tag"] == "button"
and r["text"].strip().lower() in SUBMIT_TEXTS))
and (not form or r["form"] == form)]
if not submits and form:
submits = [r for r in visible if r["type"] == "submit"]
if not submits:
raise PublicBlocked(
"no submit control was found for the field β€” the intent "
"needs one, so the run was not started")
sub = submits[0]
steps.append(Step("click",
Target("button", text=sub["text"], form=form,
kind="submit")))
if len(steps) > MAX_PUBLIC_STEPS:
raise PublicBlocked("refused: the intent exceeds the step budget")
return steps
def execute_public_run(url: str, intent: str, label: str, text: str,
recovery: bool, emit, resolver=None) -> None:
"""Run one bounded public-page intent and stream events through
`emit`, exactly like a fixture run. `resolver` exists only so
tests can stub the DNS-resolution layer; the app always uses the
default system resolver."""
check = validate_public_url(
url, resolver=resolver if resolver is not None else resolve_host)
if not check["ok"]:
emit({"type": "error", "message": check["error"]})
return
allowed_domain = check["domain"]
steps_total = 1 if intent == "click" else MAX_PUBLIC_STEPS
description = (f"Public page β€” click β€œ{label}”" if intent == "click"
else f"Public page β€” type into β€œ{label}” and submit")
try:
with sync_playwright() as pw:
browser = pw.chromium.launch(headless=True)
try:
context = browser.new_context(viewport=VIEWPORT,
accept_downloads=False)
page = context.new_page()
page.on("download", lambda d: d.cancel())
nav_state = {"blocked_host": ""}
def _route_guard(route, request):
host = urlparse(request.url).hostname or ""
if request.is_navigation_request() and host and \
registrable_domain(host) != allowed_domain:
nav_state["blocked_host"] = host
route.abort()
else:
route.continue_()
context.route("**/*", _route_guard)
try:
page.goto(url)
except Exception as exc:
if nav_state["blocked_host"]:
emit({"type": "error",
"message": "blocked: the page tried to "
"navigate to a different domain "
f"({nav_state['blocked_host']}) "
"than the one entered β€” run stopped"})
else:
emit({"type": "error",
"message": f"run failed: could not load the "
f"page: {exc}"})
return
agent = PublicStreamingAgent(
page, recovery=recovery, log=StreamLog(emit),
emit=emit, allowed_domain=allowed_domain,
blocked_nav=lambda: nav_state["blocked_host"] or None)
agent._shot("page loaded", step=0)
emit({"type": "started", "task": "public_page",
"fixture": check["host"], "description": description,
"adversarial": False, "recovery": recovery,
"steps_total": steps_total})
if registrable_domain(urlparse(page.url).hostname or "") \
!= allowed_domain:
emit({"type": "verdict", "task": "public_page",
"success": False, "steps_completed": 0,
"steps_total": steps_total, "attempts": 0,
"recoveries": 0,
"error": "blocked: the page redirected to a "
"different domain than the one "
"entered β€” run stopped"})
context.close()
return
try:
steps = _public_steps(page, intent, label, text)
except PublicBlocked as blocked:
emit({"type": "verdict", "task": "public_page",
"success": False, "steps_completed": 0,
"steps_total": steps_total, "attempts": 0,
"recoveries": 0, "error": str(blocked)})
context.close()
return
task = Task(name="public_page", fixture="", steps=steps,
description=description)
res = agent.run_task(task)
emit({"type": "verdict", "task": "public_page",
"success": res.success,
"steps_completed": res.steps_completed,
"steps_total": len(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}"})
# ---------------------------------------------------------------------------
# Stored traces: complete recorded runs (events + frames), played back
# through the same event stream a live run produces β€” no agent runs.
# ---------------------------------------------------------------------------
def load_trace(name: str) -> dict | None:
path = (TRACES_DIR / f"{name}.json")
if name not in trace_names() or not path.is_file():
return None
return json.loads(path.read_text())
def trace_names() -> list[str]:
if not TRACES_DIR.is_dir():
return []
return sorted(p.stem for p in TRACES_DIR.glob("*.json"))
def trace_catalogue() -> list:
out = []
for name in trace_names():
try:
data = load_trace(name)
except Exception:
continue
if not data:
continue
s = data.get("summary", {})
out.append({"name": name, "task": data.get("task", name),
"description": data.get("description", ""),
"adversarial": data.get("adversarial", False),
"success": s.get("success"),
"steps_completed": s.get("steps_completed"),
"steps_total": s.get("steps_total"),
"attempts": s.get("attempts"),
"recoveries": s.get("recoveries")})
return out
def play_trace(name: str, emit) -> None:
"""Stream a stored trace's events, in order, with short pauses so
the results panel, step tracker, screenshot stage and trace strip
build up the way they do for a live run."""
data = load_trace(name)
if data is None:
emit({"type": "error", "message": f"unknown trace: {name}"})
return
for ev in data.get("events", []):
emit(ev)
time.sleep(0.05 if ev.get("type") == "screenshot" else 0.025)
def task_catalogue(recorded: dict) -> list:
"""Task picker data: the system's tasks + their recorded results.
`recorded` maps mode -> task name -> result row, parsed from the
system's own results files by app.py.
"""
out = []
for t in TASKS:
row = {"name": t.name, "fixture": t.fixture,
"adversarial": t.adversarial,
"category": TASK_CATEGORIES.get(t.name, "Other"),
"description": t.description, "steps": len(t.steps),
"recorded": {}}
for mode in ("on", "off"):
r = recorded.get(mode, {}).get(t.name)
if r:
row["recorded"][mode] = {
"success": r["success"], "attempts": r["attempts"],
"recoveries": r["recoveries"],
"steps_completed": r["steps_completed"],
"steps_total": r["steps_total"], "error": r["error"]}
out.append(row)
return out