Spaces:
Running
Running
Download src/browser_automation_agent/tools/executor.py from sitcod3/dracull-agent: direct link, hf CLI and curl.
- Browser
- Download file 21.4 kB
-
https://huggingface.co/spaces/sitcod3/dracull-agent/resolve/main/src/browser_automation_agent/tools/executor.py
- Command line
-
hf download hf://spaces/sitcod3/dracull-agent/src/browser_automation_agent/tools/executor.py
-
curl -L -o executor.py https://huggingface.co/spaces/sitcod3/dracull-agent/resolve/main/src/browser_automation_agent/tools/executor.py
21.4 kB
| """The deterministic tool executor β plan Chapter 7, steps 1-7. | |
| One pipeline per tool call, always in this order: | |
| 1. validate the tool name against the registry -> structured error | |
| 2. parse the arguments JSON (string or dict) -> structured error | |
| 3. validate arguments against the registry model -> structured error | |
| 4. apply the permission/risk gate -> APPROVAL_REQUIRED, no run | |
| 5. enforce the URL policy -> POLICY_BLOCKED | |
| 6. check the browser is connected -> BROWSER_DISCONNECTED | |
| (a session with a rebuild path recovers in step 7 instead) | |
| 7. run under a timeout (asyncio.wait_for) -> structured error on timeout | |
| Every outcome returns the result envelope: ``{"ok": bool, "tool": name, | |
| "data": ...}`` plus, on failure, ``{"error": {code, message, retryable, | |
| diagnostic_id}}``; optional ``tab_id`` and ``verification`` are lifted to | |
| envelope level when the handler reports them. ``execute_tool_calls`` turns a | |
| multi-call provider response into exactly one ordered result per | |
| ``tool_call_id``. | |
| """ | |
| from __future__ import annotations | |
| import asyncio | |
| import contextlib | |
| import inspect | |
| import json | |
| from collections.abc import Awaitable, Callable | |
| from dataclasses import dataclass | |
| from typing import Any, Protocol | |
| from pydantic import ValidationError | |
| from ..browser.errors import ( | |
| APPROVAL_REQUIRED, | |
| BROWSER_DISCONNECTED, | |
| INVALID_ARGUMENTS, | |
| POLICY_BLOCKED, | |
| UNKNOWN, | |
| ClassifiedError, | |
| classify_exception, | |
| write_diagnostic_log, | |
| ) | |
| from ..config import settings | |
| from ..protocol import HITLActionType | |
| from .constants import RESULT_TEXT_CAP | |
| from .registry import REGISTRY, ToolSpec | |
| from .url_policy import PolicyViolation, enforce_url_policy | |
| class GateDecision: | |
| allowed: bool | |
| risk: str | |
| reason: str | None = None | |
| class ApprovalResult(Protocol): | |
| """The minimal response shape needed from the live HITL broker.""" | |
| request_id: str | |
| approved: bool | |
| data: dict[str, Any] | None | |
| class ApprovalRequest: | |
| """Secret-free description of the consequential action awaiting approval.""" | |
| tool: str | |
| message: str | |
| details: dict[str, Any] | |
| ApprovalRequester = Callable[[ApprovalRequest], Awaitable[ApprovalResult]] | |
| async def _request_approval( | |
| tool: str, | |
| args: Any, | |
| requester: ApprovalRequester, | |
| ) -> ApprovalResult: | |
| """Ask a human to approve one consequential action. | |
| The request deliberately contains no argument values. A ``type`` request | |
| names only the target element index and that submission will happen; it | |
| never includes the text to type, and no other argument values are copied. | |
| """ | |
| details: dict[str, Any] = {"tool": tool, "risk": "consequential"} | |
| if tool == "type": | |
| details["target_index"] = getattr(args, "index", None) | |
| details["will_submit"] = True | |
| message = ( | |
| "Type into the element at index " | |
| f"{getattr(args, 'index', 'unknown')} and submit it" | |
| ) | |
| else: | |
| message = f"Run the consequential action '{tool}'" | |
| outcome = requester(ApprovalRequest(tool=tool, message=message, details=details)) | |
| # The protocol says the requester is async, but a SYNCHRONOUS approver is | |
| # a reasonable thing for an embedder to provide (a policy lookup that | |
| # answers immediately). Awaiting a plain value would raise TypeError and | |
| # turn a decision into an UNKNOWN error, so accept both shapes. | |
| if inspect.isawaitable(outcome): | |
| return await outcome | |
| return outcome # type: ignore[return-value] | |
| # Live diagnostic logs show the model calling Playwright-MCP-style tool names | |
| # (browser_snapshot, browser_tabs, browser_new_tab) that this registry has | |
| # never exposed β each became an UNKNOWN error and a wasted turn. These | |
| # aliases resolve the familiar names onto the registry's canonical tools so | |
| # orchestration survives the naming mismatch instead of failing it. The | |
| # canonical name always wins in the envelope (plus an alias_for note), so the | |
| # model can self-correct to the real schema. | |
| TOOL_ALIASES: dict[str, str] = { | |
| "browser_navigate": "navigate", | |
| "browser_snapshot": "observe", | |
| "browser_click": "click", | |
| "browser_type": "type", | |
| "browser_press_key": "press_key", | |
| "browser_take_screenshot": "screenshot", | |
| "browser_tabs": "tab_list", | |
| "browser_tab_list": "tab_list", | |
| "browser_new_tab": "tab_open", | |
| "browser_tab_open": "tab_open", | |
| "browser_tab_select": "tab_select", | |
| "browser_close_tab": "tab_close", | |
| "browser_tab_close": "tab_close", | |
| "browser_select_option": "select_option", | |
| "browser_wait_for": "wait_for", | |
| "browser_extract_text": "extract_text", | |
| "browser_scroll": "scroll", | |
| } | |
| # Names that LOOK familiar but have no faithful registry equivalent: they stay | |
| # unknown, and the unknown-tool error lists the real tools instead. | |
| UNMAPPED_HINTS: tuple[str, ...] = ( | |
| "browser_hover", | |
| "browser_console_messages", | |
| "browser_network_requests", | |
| "browser_evaluate", | |
| "browser_file_upload", | |
| "browser_handle_dialog", | |
| ) | |
| async def _live_approval_request(request: ApprovalRequest) -> ApprovalResult: | |
| """Bridge the executor's secret-free request to the shared HITL broker.""" | |
| from ..hitl.handler import hitl_handler | |
| response = await hitl_handler.request_confirmation( | |
| session_id="executor", | |
| action_type=HITLActionType.FORM_SUBMIT, | |
| title=f"Confirm consequential action: {request.tool}", | |
| message=request.message, | |
| details=request.details, | |
| ) | |
| return response | |
| # The production host installs the live broker explicitly. Keeping the module | |
| # default empty makes direct executor use fail closed and keeps unit tests | |
| # hermetic instead of accidentally waiting for a human. | |
| approval_request: ApprovalRequester | None = None | |
| def configure_approval_request(requester: ApprovalRequester | None) -> None: | |
| """Install (or clear) the process-wide live approval requester.""" | |
| global approval_request | |
| approval_request = requester | |
| def gate(spec: ToolSpec, args: Any, browser: Any = None) -> GateDecision: | |
| """Permission/risk hook (plan Chapter 7, step 4) β the single choke point. | |
| Phase 2 default policy: every non-consequential tool runs without approval; | |
| a ``consequential`` risk level is refused with APPROVAL_REQUIRED and never | |
| executed (the interactive approval UI wiring is Phase 3). ``type`` becomes | |
| consequential when it would submit (Table 5: submit counts as a | |
| consequential action), which only the user can approve. | |
| The session adds what only it can know: a click on a submit/pay control and | |
| an Enter keypress on a credential/payment page also SEND data. Those are | |
| resolved from the snapshot the session recorded, so the gate asks the | |
| human instead of silently sending. | |
| """ | |
| risk = spec.risk | |
| if spec.name == "type" and bool(getattr(args, "submit", False)): | |
| risk = "consequential" | |
| elif spec.name == "click" and browser is not None: | |
| # An unreadable snapshot never blocks the action: if the approval | |
| # check itself cannot run, the action keeps its declared risk. | |
| with contextlib.suppress(Exception): | |
| if browser.element_requires_approval(args.index, args.snapshot_id): | |
| risk = "consequential" | |
| elif spec.name == "press_key" and browser is not None: | |
| with contextlib.suppress(Exception): | |
| if browser.key_requires_approval(args.key): | |
| risk = "consequential" | |
| if risk == "consequential": | |
| return GateDecision( | |
| False, risk, "this action sends or submits data and needs user approval" | |
| ) | |
| return GateDecision(True, risk, None) | |
| def _error_envelope( | |
| name: str, | |
| err: ClassifiedError, | |
| *, | |
| needs_consent: bool = False, | |
| data: dict[str, Any] | None = None, | |
| alias: dict[str, Any] | None = None, | |
| ) -> dict[str, Any]: | |
| envelope: dict[str, Any] = {"ok": False, "tool": name, "error": err.to_payload()} | |
| if data is not None: | |
| envelope["data"] = data | |
| if needs_consent: | |
| envelope["needs_consent"] = True | |
| if alias: | |
| envelope.update(alias) | |
| return envelope | |
| def _success_envelope( | |
| name: str, | |
| data: dict[str, Any], | |
| alias: dict[str, Any] | None = None, | |
| ) -> dict[str, Any]: | |
| envelope: dict[str, Any] = {"ok": True, "tool": name, "data": data} | |
| tab_id = data.pop("tab_id", None) | |
| verification = data.pop("verification", None) | |
| if tab_id is not None: | |
| envelope["tab_id"] = tab_id | |
| if verification is not None: | |
| envelope["verification"] = verification | |
| if alias: | |
| envelope.update(alias) | |
| return envelope | |
| def _invalid_arguments( | |
| name: str, | |
| message: str, | |
| operation: str, | |
| alias: dict[str, Any] | None = None, | |
| ) -> dict[str, Any]: | |
| err = ClassifiedError(INVALID_ARGUMENTS, message=message, operation=operation) | |
| write_diagnostic_log(err) | |
| return _error_envelope(name, err, alias=alias) | |
| async def execute_tool( | |
| browser: Any, | |
| name: str, | |
| arguments: str | dict | None, | |
| *, | |
| approval_request: ApprovalRequester | None = None, | |
| ) -> dict[str, Any]: | |
| """Run one tool call and ALWAYS return an envelope β never raise. | |
| This wrapper is the structural guarantee of the tool contract: the chat | |
| loop puts the returned envelope straight into the model context, so an | |
| exception escaping here would abort the whole chat request. The pipeline | |
| below handles each failure class explicitly; this outer catch-all is the | |
| backstop for anything unforeseen (a malformed URL the policy module does | |
| not recognise, an exotic validation error, a third-party parser blowing | |
| up). Cancellation is the one exception: it is a control-flow signal, not a | |
| failure, and it propagates untouched. | |
| """ | |
| canonical = TOOL_ALIASES.get(name, name) | |
| try: | |
| return await _execute_tool_pipeline( | |
| browser, name, arguments, approval_request=approval_request, | |
| ) | |
| except asyncio.CancelledError: | |
| raise | |
| except Exception as exc: # noqa: BLE001 β the contract is one envelope, always | |
| err = classify_exception(exc, operation=f"tool:{canonical}") | |
| write_diagnostic_log(err, exc) | |
| return _error_envelope(canonical, err) | |
| async def _execute_tool_pipeline( | |
| browser: Any, | |
| canonical: str, | |
| arguments: str | dict | None, | |
| *, | |
| approval_request: ApprovalRequester | None = None, | |
| ) -> dict[str, Any]: | |
| """The tool pipeline itself; ``execute_tool`` wraps it with the backstop.""" | |
| # ββ 1. resolve the name against the registry (aliases included) βββββββββ | |
| requested = canonical | |
| canonical = TOOL_ALIASES.get(canonical, canonical) | |
| spec = REGISTRY.get(canonical) | |
| if spec is None: | |
| hint = "" | |
| if requested.lower() in UNMAPPED_HINTS: | |
| hint = ( | |
| " β this agent has no such tool; use the registry tools listed " | |
| "here instead" | |
| ) | |
| available = ", ".join(sorted(REGISTRY)) | |
| err = ClassifiedError( | |
| UNKNOWN, | |
| message=f"unknown tool '{requested}'{hint}. Available tools: {available}", | |
| operation=f"tool:{requested}", | |
| ) | |
| write_diagnostic_log(err) | |
| return _error_envelope(requested, err) | |
| operation = f"tool:{canonical}" | |
| alias_note: dict[str, Any] | None = ( | |
| {"requested_alias": requested, "alias_for": canonical} | |
| if canonical != requested else None | |
| ) | |
| # ββ 2. parse the arguments (they may arrive as a JSON string) βββββββββββ | |
| if isinstance(arguments, str): | |
| try: | |
| parsed = json.loads(arguments) if arguments.strip() else {} | |
| except json.JSONDecodeError as exc: | |
| return _invalid_arguments( | |
| canonical, | |
| f"arguments are not valid JSON ({exc.msg} at character {exc.pos})", | |
| operation, | |
| alias=alias_note, | |
| ) | |
| except (RecursionError, ValueError) as exc: | |
| # A pathologically nested payload blows the JSON decoder's stack and | |
| # a bare number can decode to a non-object. Neither may escape as an | |
| # exception: the model only ever sees an envelope. | |
| return _invalid_arguments( | |
| canonical, | |
| f"arguments could not be decoded ({type(exc).__name__})", | |
| operation, | |
| alias=alias_note, | |
| ) | |
| elif arguments is None: | |
| parsed = {} | |
| elif isinstance(arguments, dict): | |
| parsed = arguments | |
| else: | |
| parsed = None # fall through to the object check below | |
| if not isinstance(parsed, dict): | |
| return _invalid_arguments( | |
| canonical, "arguments must be a JSON object", operation, alias=alias_note | |
| ) | |
| # ββ 3. validate against the registry model (extra keys rejected) βββββββ | |
| try: | |
| args = spec.model(**parsed) | |
| except ValidationError as exc: | |
| first = exc.errors()[0] | |
| loc = ".".join(str(part) for part in first.get("loc") or ()) | |
| return _invalid_arguments( | |
| canonical, f"invalid arguments: {loc}: {first.get('msg')}", operation, | |
| alias=alias_note, | |
| ) | |
| except TypeError as exc: | |
| # Non-string keys in a directly supplied dict make **kwargs explode. | |
| return _invalid_arguments( | |
| canonical, f"invalid arguments: {exc}", operation, alias=alias_note, | |
| ) | |
| # ββ 4. permission/risk gate βββββββββββββββββββββββββββββββββββββββββββββ | |
| decision = gate(spec, args, browser) | |
| approval_envelope: dict[str, Any] | None = None | |
| if not decision.allowed: | |
| requester = approval_request if approval_request is not None else globals().get( | |
| "approval_request" | |
| ) | |
| if requester is None: | |
| err = ClassifiedError( | |
| APPROVAL_REQUIRED, | |
| message=( | |
| f"tool '{canonical}' requires approval, but no approval manager is " | |
| "available. The action was not executed." | |
| ), | |
| operation=operation, | |
| ) | |
| write_diagnostic_log(err) | |
| return _error_envelope(canonical, err, alias=alias_note) | |
| response = await _request_approval(canonical, args, requester) | |
| request_id = response.request_id | |
| if not response.approved: | |
| reason = (response.data or {}).get("reason", "denied") | |
| if str(reason).lower() == "timeout": | |
| message = ( | |
| f"approval request {request_id} timed out. The action was not executed." | |
| ) | |
| else: | |
| message = ( | |
| f"approval request {request_id} was denied ({reason}). " | |
| "The action was not executed." | |
| ) | |
| err = ClassifiedError( | |
| APPROVAL_REQUIRED, | |
| message=message, | |
| operation=operation, | |
| ) | |
| write_diagnostic_log(err) | |
| envelope = _error_envelope(canonical, err, alias=alias_note) | |
| envelope["approval"] = { | |
| "request_id": request_id, | |
| "approved": False, | |
| "reason": reason, | |
| } | |
| return envelope | |
| approval_envelope = {"request_id": request_id, "approved": True} | |
| # ββ 5. URL policy, enforced in the executor (plan 7.1) βββββββββββββββββ | |
| if spec.url_field: | |
| url_value = getattr(args, spec.url_field, None) | |
| if url_value: | |
| try: | |
| await enforce_url_policy( | |
| url_value, | |
| allow_private=bool(settings.allow_private_networks), | |
| context=spec.name, | |
| ) | |
| except PolicyViolation as exc: | |
| err = ClassifiedError( | |
| POLICY_BLOCKED, message=f"blocked by the URL policy: {exc}", | |
| operation=operation, | |
| ) | |
| write_diagnostic_log(err) | |
| return _error_envelope(canonical, err, alias=alias_note) | |
| # ββ 6. browser-connected check ββββββββββββββββββββββββββββββββββββββββββ | |
| # A disconnected probe is a refusal only for a browser that cannot rebuild. | |
| # A session carrying the documented recovery path (_ensure: close the | |
| # orphaned context, relaunch β chat_tools.py:660) heals AT the failing | |
| # step, which is exactly what the BROWSER_DISCONNECTED contract promises | |
| # (errors.py _RETRYABLE). Refusing here blocked that recovery forever: the | |
| # dead context stays registered in manager._contexts, so the probe kept | |
| # reporting disconnected and every retry re-entered this refusal instead | |
| # of ever reaching the handler that would clean it up. | |
| if spec.requires_browser: | |
| connected = getattr(browser, "browser_connected", None) | |
| if ( | |
| callable(connected) | |
| and not connected() | |
| and not callable(getattr(browser, "_ensure", None)) | |
| ): | |
| err = ClassifiedError(BROWSER_DISCONNECTED, operation=operation) | |
| write_diagnostic_log(err) | |
| return _error_envelope(canonical, err, alias=alias_note) | |
| # ββ 7. run under a timeout; cancellation propagates untouched ββββββββββ | |
| # Per-tool timeout comes from settings.browser_timeout (ms); the 1 ms | |
| # floor only guards against a zero/negative setting. | |
| timeout_s = max(int(settings.browser_timeout), 1) / 1000.0 | |
| try: | |
| data = await asyncio.wait_for(spec.handler(browser, args), timeout=timeout_s) | |
| except TimeoutError: | |
| err = ClassifiedError( | |
| UNKNOWN, | |
| message=f"tool '{canonical}' timed out after {timeout_s:.2f}s", | |
| operation=operation, | |
| ) | |
| write_diagnostic_log(err) | |
| return _error_envelope(canonical, err, alias=alias_note) | |
| except ClassifiedError as exc: | |
| if exc.operation is None: | |
| exc.operation = operation | |
| write_diagnostic_log(exc) | |
| if getattr(exc, "needs_consent", False): | |
| return _error_envelope( | |
| canonical, exc, needs_consent=True, | |
| data={"actual": getattr(exc, "actual", None)}, alias=alias_note, | |
| ) | |
| return _error_envelope(canonical, exc, alias=alias_note) | |
| except PolicyViolation as exc: | |
| # A refusal raised INSIDE the handler (a redirect to a blocked host, a | |
| # domain the operator has blocked) is a policy decision, not an | |
| # unknown failure. | |
| err = ClassifiedError( | |
| POLICY_BLOCKED, | |
| message=str(exc), | |
| operation=operation, | |
| ) | |
| write_diagnostic_log(err, exc) | |
| return _error_envelope(canonical, err, alias=alias_note) | |
| except Exception as exc: # noqa: BLE001 β every failure becomes one envelope | |
| err = classify_exception(exc, operation=operation) | |
| write_diagnostic_log(err, exc) | |
| return _error_envelope(canonical, err, alias=alias_note) | |
| if not isinstance(data, dict): | |
| data = {"result": data} | |
| envelope = _success_envelope(canonical, data, alias=alias_note) | |
| if approval_envelope is not None: | |
| envelope["approval"] = approval_envelope | |
| return envelope | |
| async def execute_tool_calls( | |
| browser: Any, | |
| tool_calls: Any, | |
| *, | |
| approval_request: ApprovalRequester | None = None, | |
| ) -> list[dict[str, Any]]: | |
| """One ``role:"tool"`` result per tool call, IN ORDER, keyed by tool_call_id. | |
| Handles a multi-call provider response: a failing call yields its own | |
| structured error and never stops the remaining calls from running. | |
| """ | |
| results: list[dict[str, Any]] = [] | |
| for call in tool_calls: | |
| function = getattr(call, "function", None) | |
| name = getattr(function, "name", None) or "" | |
| raw_arguments = getattr(function, "arguments", None) | |
| envelope = await execute_tool( | |
| browser, name, raw_arguments, approval_request=approval_request | |
| ) | |
| results.append({ | |
| "role": "tool", | |
| "tool_call_id": getattr(call, "id", None), | |
| "content": json.dumps(envelope, default=str)[:RESULT_TEXT_CAP], | |
| # The full envelope travels with the message so the chat loop can | |
| # build its tool trace without re-parsing the (possibly truncated) | |
| # content string. | |
| "envelope": envelope, | |
| }) | |
| return results | |