text
stringlengths
0
1.47k
else row.level = Number(tag[1]);
if (tag === 'a') row.href = (el.getAttribute('href') || '').slice(0, 120);
if (tag === 'input' || tag === 'textarea') { if (el.value && el.type !== 'password') row.value = String(el.value).slice(0, 60); if (el.disabled) row.disabled = true; }
if (el.type === 'checkbox' || el.type === 'radio') row.checked = !!el.checked;
out.push(row);
}
return out;
}
"""
def _fmt_snapshot(rows: list[dict]) -> str:
lines = []
for r in rows:
if r.get("truncated"):
lines.append("… more elements below; scroll or ask for a larger snapshot")
continue
if r.get("role") == "heading":
lines.append(f"h{r.get('level', 2)} \"{r.get('name', '')}\"")
continue
extra = ""
if r.get("href"):
extra += f" href={r['href']}"
if "value" in r:
extra += f" value=\"{r['value']}\""
if "checked" in r:
extra += " checked" if r["checked"] else " unchecked"
if r.get("disabled"):
extra += " disabled"
lines.append(f"{r.get('ref')} {r.get('role')} \"{r.get('name', '')}\"{extra}")
return "\n".join(lines) if lines else "(nothing interactive is visible on this page)"
async def _snapshot(s: Session, max_elements: int) -> str:
rows = await s.page.evaluate(_SNAPSHOT_JS, max(1, min(int(max_elements or SNAPSHOT_CAP), 500)))
return _fmt_snapshot(rows or [])
def _target(s: Session, args: dict):
ref, selector = str(args.get("ref") or "").strip(), str(args.get("selector") or "").strip()
if ref:
return s.page.locator(f'[data-hr-ref="{ref}"]').first
if selector:
return s.page.locator(selector).first
raise BrowserToolError("Say which element: a ref from the snapshot or a selector.")
async def _where(s: Session) -> str:
try:
title = await s.page.title()
except Exception: # noqa: BLE001
title = ""
return f"{s.page.url}" + (f" ({title})" if title else "")
async def _settled(s: Session) -> None:
with_timeout = getattr(s.page, "wait_for_load_state", None)
if with_timeout:
try:
await asyncio.wait_for(s.page.wait_for_load_state("domcontentloaded"), 8)
except Exception: # noqa: BLE001
pass
async def _mark(s: Session, loc) -> None:
"""Remember the centre of the element about to be acted on, in page coordinates, so the console
can show a ghost cursor going there. Best effort: a locator that cannot be measured leaves the
last point standing."""
try:
box = await loc.bounding_box()
except Exception: # noqa: BLE001
return
if isinstance(box, dict) and box.get("width") is not None:
s.pointer = {"x": round(float(box["x"]) + float(box["width"]) / 2, 1), "y": round(float(box["y"]) + float(box["height"]) / 2, 1)}
async def viewport_of(s: Session) -> dict:
"""The page's own layout viewport (window.innerWidth/innerHeight), the coordinate space of
`pointer`. Asked of the page, not of the context: the vendor's default context carries its
window's size, not the 1280 x 800 this plane asks for when it makes a context of its own, and
a cursor placed on the assumed size landed low and right of the element the agent clicked
(hr-test, 2026-09-27)."""
try:
v = await s.page.evaluate("() => [window.innerWidth, window.innerHeight]")
if isinstance(v, (list, tuple)) and len(v) == 2 and int(v[0]) > 0:
return {"w": int(v[0]), "h": int(v[1])}
except Exception: # noqa: BLE001
pass
try:
vs = s.page.viewport_size if s.page is not None else None
except Exception: # noqa: BLE001
vs = None
return {"w": int((vs or {}).get("width") or 1280), "h": int((vs or {}).get("height") or 800)}
async def call(s: Session, name: str, args: dict):
"""Run one tool on this session. Returns text, or ("image", png bytes, caption) for a
screenshot the caller stores. Raises BrowserToolError with a sentence the agent can act on."""
await registry.bump(s.sid, last_used=time.time(), calls=1)
page = s.page