""" Illustrative example of integrating agent-permissions with BrowserUse. Prerequisites: pip install browseruse agent-permissions """ from __future__ import annotations import asyncio from typing import Optional from lxml import html from agent_permissions import build_prompt_instructions, validate_interaction from agent_permissions import async_api def translate_action(action) -> Optional[tuple[str, str]]: """ Translate a BrowserUse action into a (verb, css_selector) tuple. Adjust the mapping to the actual action structure you receive from BrowserUse. """ action_type = getattr(action, "type", None) selector = getattr(action, "selector", None) or getattr(action, "css_selector", None) if action_type == "click" and selector: return ("click_element", selector) if action_type == "follow_link" and selector: return ("follow_link", selector) if action_type == "fill" and selector: return ("set_input_value", selector) return None async def main() -> None: try: from browseruse import BrowserAgent # type: ignore except ImportError: # pragma: no cover - sample only raise SystemExit("Install browseruse to run this example: pip install browseruse") start_url = "https://example.com/products" manifest_wrapper = await async_api.discover_manifest(start_url) if manifest_wrapper and manifest_wrapper.manifest: prompt_prefix = build_prompt_instructions(manifest_wrapper.manifest) else: prompt_prefix = "No manifest found; behave conservatively." class PermissionAwareAgent(BrowserAgent): # type: ignore async def before_action(self, action, page): interaction = translate_action(action) if not interaction or not manifest_wrapper or not manifest_wrapper.manifest: return True verb, selector = interaction dom = html.fromstring(await page.content()) matches = dom.cssselect(selector) if not matches: self.logger.warning("Selector %s matched no elements; skipping", selector) return False result = validate_interaction( manifest_wrapper.manifest, verb=verb, element=matches[0], ) if not result.allowed: self.logger.warning("Denied action %s: %s", action, result.reasons) return False return True agent = PermissionAwareAgent( goal="Survey the product catalog responsibly.", start_url=start_url, system_prompt_prefix=prompt_prefix, ) await agent.run() # type: ignore[attr-defined] if __name__ == "__main__": asyncio.run(main())