_common.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143
  1. """Shared base for the bundled cloud-browser plugins. Every vendor speaks the same REST shape
  2. (POST to create a session, one request to release it); :class:`CloudBrowserProvider` owns that
  3. lifecycle, subclasses supply attributes + hooks. Logs go to the subclass module's logger with the
  4. vendor label so emitted text matches the pre-refactor per-vendor modules."""
  5. from __future__ import annotations
  6. import logging
  7. import uuid
  8. from typing import Any, Dict, List, Optional
  9. import requests
  10. from agent.browser_provider import BrowserProvider
  11. from agent.ssl_verify import requests_verify
  12. _CLOSE_OK = {200, 201, 204}
  13. class CloudBrowserProvider(BrowserProvider):
  14. """Subclasses set ``provider_id``/``label``, ``release_method``/``release_path`` (``{session_id}``
  15. placeholder appended to ``config["base_url"]``), implement ``_get_config_or_none()`` and
  16. ``_headers(config)``, and build ``create_session`` on ``_post_create``/``_check_created``."""
  17. provider_id: str
  18. label: str
  19. release_method: str
  20. release_path: str
  21. missing_credentials_error: str = ""
  22. setup_tag: Optional[str] = None # ``None`` hides the provider from the setup picker
  23. setup_env_vars: list[dict[str, str]] = []
  24. create_label_suffix: str = "" # "Failed to create <label><suffix> session"; Firecrawl: " browser"
  25. close_fail_fmt: Optional[str] = None # Browserbase's close warning historically omits the vendor
  26. @property
  27. def name(self) -> str:
  28. return self.provider_id
  29. @property
  30. def display_name(self) -> str:
  31. return self.label
  32. @property
  33. def _log(self) -> logging.Logger:
  34. return logging.getLogger(type(self).__module__)
  35. def is_available(self) -> bool:
  36. return self._get_config_or_none() is not None
  37. def _get_config_or_none(self) -> Optional[dict[str, Any]]:
  38. raise NotImplementedError
  39. def _get_config(self) -> dict[str, Any]:
  40. config = self._get_config_or_none()
  41. if config is None:
  42. raise ValueError(self.missing_credentials_error)
  43. return config
  44. def _headers(self, config: dict[str, Any]) -> dict[str, str]:
  45. raise NotImplementedError
  46. def _release_headers(self, config: dict[str, Any]) -> dict[str, str]:
  47. return self._headers(config)
  48. def _release_body(self, config: dict[str, Any]) -> Optional[dict[str, object]]:
  49. return None
  50. def _release(self, config: dict[str, Any], session_id: str, timeout: int) -> requests.Response:
  51. # requests resolves verify=True through a bundle path frozen at its own import,
  52. # which a replaced install environment leaves dangling; hand it a live one.
  53. kwargs: dict[str, Any] = {
  54. "headers": self._release_headers(config),
  55. "timeout": timeout,
  56. "verify": requests_verify(),
  57. }
  58. body = self._release_body(config)
  59. if body is not None:
  60. kwargs["json"] = body
  61. url = f"{config['base_url']}{self.release_path.format(session_id=session_id)}"
  62. return getattr(requests, self.release_method)(url, **kwargs)
  63. @staticmethod
  64. def _session_name(task_id: str) -> str:
  65. return f"hermes_{task_id}_{uuid.uuid4().hex[:8]}"
  66. def _post_create(
  67. self, url: str, headers: dict[str, str], payload: dict[str, object], *, wrap_errors: bool = True
  68. ) -> requests.Response:
  69. """POST the create request; network failures → RuntimeError unless the managed gateway
  70. caller needs the raw exception to retry."""
  71. try:
  72. return requests.post(url, headers=headers, json=payload, timeout=30, verify=requests_verify())
  73. except requests.RequestException as exc:
  74. if not wrap_errors:
  75. raise
  76. raise RuntimeError(f"{self.label} API connection failed: {exc}") from exc
  77. def _check_created(self, response: requests.Response) -> None:
  78. if not response.ok:
  79. raise RuntimeError(
  80. f"Failed to create {self.label}{self.create_label_suffix} session: "
  81. f"{response.status_code} {response.text}")
  82. def close_session(self, session_id: str) -> bool:
  83. try:
  84. config = self._get_config()
  85. except ValueError:
  86. self._log.warning("Cannot close %s session %s — missing credentials", self.label, session_id)
  87. return False
  88. try:
  89. response = self._release(config, session_id, timeout=10)
  90. if response.status_code in _CLOSE_OK:
  91. self._log.debug("Successfully closed %s session %s", self.label, session_id)
  92. return True
  93. self._log.warning(
  94. self.close_fail_fmt or f"Failed to close {self.label} session %s: HTTP %s - %s",
  95. session_id, response.status_code, response.text[:200])
  96. return False
  97. except Exception as e:
  98. self._log.error("Exception closing %s session %s: %s", self.label, session_id, e)
  99. return False
  100. def emergency_cleanup(self, session_id: str) -> None:
  101. config = self._get_config_or_none()
  102. if config is None:
  103. self._log.warning(
  104. "Cannot emergency-cleanup %s session %s — missing credentials", self.label, session_id
  105. )
  106. return
  107. try:
  108. self._release(config, session_id, timeout=5)
  109. except Exception as e:
  110. self._log.debug("Emergency cleanup failed for %s session %s: %s", self.label, session_id, e)
  111. def get_setup_schema(self) -> Optional[dict[str, Any]]:
  112. if self.setup_tag is None:
  113. return None
  114. return {
  115. "name": self.label,
  116. "badge": "paid",
  117. "tag": self.setup_tag,
  118. "env_vars": [dict(v) for v in self.setup_env_vars],
  119. }