sitcod3's picture
sync: backend/src -> Space (browser settings autosave + writable settings file)
6eb6c4e verified
Raw History Blame Contribute Delete
6.43 kB
"""Agent web-navigation service: guarded navigation + per-session URL map.
The nanobrowser-style control surface (navigate anywhere / back / forward /
extract / search-then-visit) sits on top of the existing BrowserManager's
step executor, with two additions:
* every target URL goes through net_guard first (Mimosa: http(s) only, no
loopback/private/reserved β€” validated *after* DNS resolution);
* every verdict (allow and block) is audit-logged and counted, and the
visited URLs form the session's URL map the UI renders as history.
"""
from __future__ import annotations
import time
from collections import deque
from typing import Any
from rich.console import Console
from .browser.manager import BrowserManager, browser_manager
from .config import settings
from .exa_search import ExaClient, exa_client
from .net_guard import BlockedUrlError, policy_from_settings, validate_public_http_url
from .protocol import ActionType, TaskStep
console = Console()
class SessionNotFoundError(KeyError):
"""No live page for the requested session."""
class WebNavService:
"""Navigation facade used by the /api/browse and /api/search routes."""
def __init__(self, manager: BrowserManager = browser_manager, exa: ExaClient = exa_client) -> None:
self._manager = manager
self._exa = exa
# session_id -> deque[{url, title, at}] (bounded, audit-friendly)
self._url_maps: dict[str, deque] = {}
# enterprise-agent-ops metrics baseline
self.counters = {
"navigations_total": 0,
"navigations_blocked": 0,
"searches_total": 0,
"search_failures_total": 0,
}
# ── audit ────────────────────────────────────────────────────────────
def _audit(self, session_id: str, url: str, allowed: bool, reason: str = "") -> None:
if allowed:
self.counters["navigations_total"] += 1
else:
self.counters["navigations_blocked"] += 1
if settings.navigation_audit_log:
tail = f" β€” {reason}" if reason else ""
console.print(
f"[webnav audit] session={session_id} url={url} "
f"verdict={'allow' if allowed else 'BLOCK'}{tail}"
)
# ── URL map ──────────────────────────────────────────────────────────
def _record(self, session_id: str, url: str, title: str) -> None:
history = self._url_maps.setdefault(
session_id, deque(maxlen=max(10, int(settings.webnav_history_max)))
)
# Dedup consecutive repeats (reload/redirects), keep most recent last.
if history and history[-1]["url"] == url:
history[-1]["at"] = time.time()
history[-1]["title"] = title or history[-1]["title"]
else:
history.append({"url": url, "title": title, "at": time.time()})
def url_map(self, session_id: str) -> dict[str, Any]:
history = self._url_maps.get(session_id, ())
entries = list(history)
return {
"session_id": session_id,
"current": entries[-1] if entries else None,
"entries": entries,
"count": len(entries),
}
# ── navigation ───────────────────────────────────────────────────────
async def navigate(
self,
session_id: str,
url: str,
timeout: int | None = None,
) -> dict[str, Any]:
"""Validate β†’ goto β†’ record. Raises BlockedUrlError / SessionNotFoundError."""
policy = policy_from_settings()
try:
safe_url = validate_public_http_url(url, policy=policy)
except BlockedUrlError as exc:
self._audit(session_id, url, allowed=False, reason=str(exc))
raise
self._audit(session_id, safe_url, allowed=True)
page = await self._manager.get_page(session_id)
if page is None:
raise SessionNotFoundError(f"No live page for session {session_id}")
step = TaskStep(
action=ActionType.NAVIGATE,
url=safe_url,
timeout=timeout or settings.browser_timeout,
)
result = await self._manager.execute_step(session_id, step)
self._record(session_id, result.get("url", safe_url), result.get("title", ""))
return {**result, "recorded": True}
async def step(self, session_id: str, step: TaskStep) -> dict[str, Any]:
"""Run any non-navigate browser action (click/type/extract/...)."""
if step.action == ActionType.NAVIGATE:
# Keep a single guarded path for navigation, whatever calls it.
return await self.navigate(session_id, step.url or "", step.timeout)
page = await self._manager.get_page(session_id)
if page is None:
raise SessionNotFoundError(f"No live page for session {session_id}")
return await self._manager.execute_step(session_id, step)
# ── search ───────────────────────────────────────────────────────────
async def search(self, query: str, num_results: int = 8, category: str | None = None) -> dict[str, Any]:
self.counters["searches_total"] += 1
try:
results = await self._exa.search(query, num_results=num_results, category=category)
except Exception:
self.counters["search_failures_total"] += 1
raise
return {"query": query, "results": results, "count": len(results)}
async def visit_result(
self,
session_id: str,
url: str,
timeout: int | None = None,
) -> dict[str, Any]:
"""Navigate to a search result β€” same guard, same URL map."""
return await self.navigate(session_id, url, timeout=timeout)
# Module-level singleton (same DI style as browser_manager).
webnav = WebNavService()