text
stringlengths
0
1.47k
figures = await vendor_stop(str(rec["vendor_id"]))
except Exception: # noqa: BLE001
figures = {}
usd = vendor_cost(figures)
source = "vendor"
if not rec.get("vendor_id"):
usd, source = 0.0, "own" # the operator's own browser: nothing to meter
elif usd is None:
usd, source = round(minutes(rec) * PRICES["browser.minute"], 6), "table"
return {"minutes": minutes(rec), "usd": usd, "usd_source": source, "calls": int(rec.get("calls") or 0),
"screenshots": int(rec.get("screenshots") or 0), "blocked": list(rec.get("blocked") or [])[:20],
"proxy_mb": figures.get("proxyUsedMb") or 0}
async def expired_sessions(now: float | None = None) -> list[tuple[dict, str]]:
"""Every recorded browser past its cap or idle, from any process."""
now = now or time.time()
return [(rec, why) for rec in await registry.all() if (why := expired(rec, now))]
async def sweep_attachments() -> None:
"""Drop the attachments whose browser was stopped from another process."""
for s in list(_SESSIONS.values()):
if await registry.get(s.sid) is None:
await detach(s)
# ── the tools ────────────────────────────────────────────────────────────────────────────────
_TOOLS: list[dict] = []
def _tool(name: str, risk: str, description: str, schema: dict):
_TOOLS.append({"name": name, "risk": risk, "description": description,
"inputSchema": {"type": "object", "properties": schema.get("properties", {}),
"required": schema.get("required", []), "additionalProperties": False}})
_REF = {"ref": {"type": "string", "description": "An element ref from the last snapshot, like e12."},
"selector": {"type": "string", "description": "A CSS selector, when there is no ref for the element."}}
_tool("navigate", "act", "Open a web address in the current tab and read what is on the page.",
{"properties": {"url": {"type": "string", "description": "An http or https address."}}, "required": ["url"]})
_tool("get_url", "read", "The current tab's address and title.", {})
_tool("snapshot", "read", "What is on the page: headings, links, buttons and fields, each with a ref to act on.",
{"properties": {"max_elements": {"type": "integer", "description": f"At most this many elements (default {SNAPSHOT_CAP})."}}})
_tool("extract_text", "read", "The readable text of the page, or of one element.",
{"properties": {"selector": {"type": "string", "description": "A CSS selector; the whole page when absent."},
"max_chars": {"type": "integer", "description": f"At most this many characters (default {TEXT_CAP})."}}})
_tool("click", "act", "Click an element, by ref or selector.", {"properties": dict(_REF)})
_tool("type", "act", "Type text into a field, by ref or selector, replacing what is there.",
{"properties": {**_REF, "text": {"type": "string"}, "submit": {"type": "boolean", "description": "Press Enter afterwards."}},
"required": ["text"]})
_tool("press_key", "act", "Press a key, like Enter, Tab, Escape or ArrowDown.",
{"properties": {"key": {"type": "string"}}, "required": ["key"]})
_tool("scroll", "act", "Scroll the page.",
{"properties": {"direction": {"type": "string", "enum": ["down", "up"]},
"pixels": {"type": "integer", "description": "How far (default 600)."}}})
_tool("wait_for", "read", "Wait until text or an element appears, or for a number of milliseconds.",
{"properties": {"text": {"type": "string"}, "selector": {"type": "string"},
"ms": {"type": "integer", "description": f"Milliseconds, at most {int(CALL_CAP_S * 1000)}."}}})
_tool("screenshot", "read", "A picture of the current tab, kept with the task's files and shown to you.",
{"properties": {"full_page": {"type": "boolean", "description": "The whole page, not only the visible part."}}})
_tool("back", "act", "Go back one page in the current tab.", {})
_tool("list_tabs", "read", "The open tabs, with their index, address and title.", {})
_tool("switch_tab", "act", "Make one of the open tabs the current tab.",
{"properties": {"index": {"type": "integer"}}, "required": ["index"]})
def tool_list() -> list[dict]:
return [{"name": f"browser_{t['name']}", "description": f"[browser, {t['risk']}] {t['description']}",
"inputSchema": t["inputSchema"],
"annotations": {"readOnlyHint": t["risk"] == "read", "destructiveHint": False}} for t in _TOOLS]
def find(name: str) -> dict | None:
return next((t for t in _TOOLS if t["name"] == name), None)
_SNAPSHOT_JS = """
(max) => {
const out = []; let n = 0;
const seen = new Set();
// Visible to a person: laid out, not hidden, and at least 8 px each way. Sites keep tiny proxy
// controls (DuckDuckGo's 4 x 4 search input beside the field people see); an agent that types
// into one of those types into nothing anyone can see (hr-test, 2026-09-28).
const vis = (el) => { const r = el.getBoundingClientRect(); const cs = getComputedStyle(el);
return r.width >= 8 && r.height >= 8 && cs.visibility !== 'hidden' && cs.display !== 'none'; };
const nameOf = (el) => (el.getAttribute('aria-label') || el.getAttribute('title') || el.getAttribute('placeholder')
|| (el.labels && el.labels[0] && el.labels[0].innerText) || el.getAttribute('alt') || el.innerText || el.value || '').trim().replace(/\\s+/g, ' ').slice(0, 80);
const sel = 'h1,h2,h3,a[href],button,input,select,textarea,[role=button],[role=link],[role=tab],[role=menuitem],[role=checkbox],[role=radio],[role=textbox],[contenteditable=true],summary';
for (const el of document.querySelectorAll(sel)) {
if (n >= max) { out.push({truncated: true}); break; }
if (!vis(el) || seen.has(el)) continue;
seen.add(el);
const tag = el.tagName.toLowerCase();
const role = el.getAttribute('role') || (tag === 'a' ? 'link' : tag === 'button' || tag === 'summary' ? 'button'
: tag === 'select' ? 'combobox' : tag === 'textarea' ? 'textbox' : tag === 'input' ? ((el.type === 'checkbox' || el.type === 'radio' || el.type === 'submit' || el.type === 'button') ? el.type : 'textbox')
: /^h[1-3]$/.test(tag) ? 'heading' : tag);
const row = {role, name: nameOf(el)};
if (role !== 'heading') { const ref = 'e' + (++n); el.setAttribute('data-hr-ref', ref); row.ref = ref; }