Files
hermes-agent/plugins/browser/_common.py
Pedro Relvas 6bd9c10e32 fix(ssl): re-resolve certifi's CA bundle after an install-environment rotation
A process that imported certifi before the package manager replaced its install
environment keeps the deleted directory in `certifi.where()` for the rest of its
life: the path is derived from the imported module's `__file__` and nothing
re-derives it. httpx builds every SSL context through that path, so
`httpx.Client(verify=True)` raises FileNotFoundError at construction — the
OpenAI-compatible client factory turns that into `RuntimeError: Failed to
initialize OpenAI client: [Errno 2] No such file or directory`, and every TLS
tool that process owns fails until it restarts. `requests` fails one step
further out: its DEFAULT_CA_BUNDLE_PATH is a string frozen when requests is
imported, so a rotated environment leaves every call raising `OSError: Could not
find a suitable TLS CA certificate bundle`.

- agent/ssl_verify.py: certifi_bundle_path() re-executes the imported certifi
  module against the live sys.path when its bundle is gone, logs one WARNING
  naming the dead path and the recovered one, and reports None when there is
  nothing to re-resolve. resolve_httpx_verify() hands the platform context over
  in that case instead of the bare `True` httpx would resolve through the dead
  path; requests_verify() gives requests call sites a bundle that exists now.
- plugins/browser/_common.py, plugins/web/keenable/provider.py: pass that bundle
  to the two requests call sites that inherit requests' frozen default.
- tests/agent/test_ssl_verify.py: the rotation is simulated by importing certifi
  from a stand-in environment, deleting its directory and then building a client
  (no package manager involved).
2026-10-18 06:04:35 +05:30

146 lines
5.8 KiB
Python

"""Shared base for the bundled cloud-browser plugins. Every vendor speaks the same REST shape
(POST to create a session, one request to release it); :class:`CloudBrowserProvider` owns that
lifecycle, subclasses supply attributes + hooks. Logs go to the subclass module's logger with the
vendor label so emitted text matches the pre-refactor per-vendor modules."""
from __future__ import annotations
import logging
import uuid
from typing import Any, Dict, List, Optional
import requests
from agent.browser_provider import BrowserProvider
from agent.ssl_verify import requests_verify
_CLOSE_OK = {200, 201, 204}
class CloudBrowserProvider(BrowserProvider):
"""Subclasses set ``provider_id``/``label``, ``release_method``/``release_path`` (``{session_id}``
placeholder appended to ``config["base_url"]``), implement ``_get_config_or_none()`` and
``_headers(config)``, and build ``create_session`` on ``_post_create``/``_check_created``."""
provider_id: str
label: str
release_method: str
release_path: str
missing_credentials_error: str = ""
setup_tag: Optional[str] = None # ``None`` hides the provider from the setup picker
setup_env_vars: list[dict[str, str]] = []
create_label_suffix: str = "" # "Failed to create <label><suffix> session"; Firecrawl: " browser"
close_fail_fmt: Optional[str] = None # Browserbase's close warning historically omits the vendor
@property
def name(self) -> str:
return self.provider_id
@property
def display_name(self) -> str:
return self.label
@property
def _log(self) -> logging.Logger:
return logging.getLogger(type(self).__module__)
def is_available(self) -> bool:
return self._get_config_or_none() is not None
def _get_config_or_none(self) -> Optional[dict[str, Any]]:
raise NotImplementedError
def _get_config(self) -> dict[str, Any]:
config = self._get_config_or_none()
if config is None:
raise ValueError(self.missing_credentials_error)
return config
def _headers(self, config: dict[str, Any]) -> dict[str, str]:
raise NotImplementedError
def _release_headers(self, config: dict[str, Any]) -> dict[str, str]:
return self._headers(config)
def _release_body(self, config: dict[str, Any]) -> Optional[dict[str, object]]:
return None
def _release(self, config: dict[str, Any], session_id: str, timeout: int) -> requests.Response:
# requests resolves verify=True through a bundle path frozen at its own import,
# which a replaced install environment leaves dangling; hand it a live one.
kwargs: dict[str, Any] = {
"headers": self._release_headers(config),
"timeout": timeout,
"verify": requests_verify(),
}
body = self._release_body(config)
if body is not None:
kwargs["json"] = body
url = f"{config['base_url']}{self.release_path.format(session_id=session_id)}"
return getattr(requests, self.release_method)(url, **kwargs)
@staticmethod
def _session_name(task_id: str) -> str:
return f"hermes_{task_id}_{uuid.uuid4().hex[:8]}"
def _post_create(
self, url: str, headers: dict[str, str], payload: dict[str, object], *, wrap_errors: bool = True
) -> requests.Response:
"""POST the create request; network failures → RuntimeError unless the managed gateway
caller needs the raw exception to retry."""
try:
return requests.post(url, headers=headers, json=payload, timeout=30, verify=requests_verify())
except requests.RequestException as exc:
if not wrap_errors:
raise
raise RuntimeError(f"{self.label} API connection failed: {exc}") from exc
def _check_created(self, response: requests.Response) -> None:
if not response.ok:
raise RuntimeError(
f"Failed to create {self.label}{self.create_label_suffix} session: "
f"{response.status_code} {response.text}")
def close_session(self, session_id: str) -> bool:
try:
config = self._get_config()
except ValueError:
self._log.warning("Cannot close %s session %s — missing credentials", self.label, session_id)
return False
try:
response = self._release(config, session_id, timeout=10)
if response.status_code in _CLOSE_OK:
self._log.debug("Successfully closed %s session %s", self.label, session_id)
return True
self._log.warning(
self.close_fail_fmt or f"Failed to close {self.label} session %s: HTTP %s - %s",
session_id, response.status_code, response.text[:200])
return False
except Exception as e:
self._log.error("Exception closing %s session %s: %s", self.label, session_id, e)
return False
def emergency_cleanup(self, session_id: str) -> None:
config = self._get_config_or_none()
if config is None:
self._log.warning(
"Cannot emergency-cleanup %s session %s — missing credentials", self.label, session_id
)
return
try:
self._release(config, session_id, timeout=5)
except Exception as e:
self._log.debug("Emergency cleanup failed for %s session %s: %s", self.label, session_id, e)
def get_setup_schema(self) -> Optional[dict[str, Any]]:
if self.setup_tag is None:
return None
return {
"name": self.label,
"badge": "paid",
"tag": self.setup_tag,
"env_vars": [dict(v) for v in self.setup_env_vars],
# Cloud-scoped hook: installs the agent-browser CLI only (the vendor hosts Chromium).
"post_setup": "browserbase",
}