browser_session_real_profile.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. """Real-profile local browsing: snapshot the user's default Chromium profile into a Hermes-owned copy and
  2. launch the user's REAL browser binary on it through the launcher.
  3. The real binary (not the packaged Chromium, and never ``--password-store=basic``/``--use-mock-keychain``)
  4. keeps the OS keychain path intact, so macOS cookies decrypt and the copy stays signed in. One shared
  5. browser per profile home serves every session of that profile (concurrent tasks must not launch rival
  6. Chromiums on one copy dir); it is terminated at exit or when THAT profile turns consent off.
  7. """
  8. from __future__ import annotations
  9. import logging
  10. import threading
  11. from typing import Optional
  12. logger = logging.getLogger(__name__)
  13. _RP = "browser.use_real_profile is on, but "
  14. # Keep lock contention well inside the agent's 420-second outer tool deadline (an abandoned holder
  15. # may be a daemon worker Python cannot terminate).
  16. _LOCK_TIMEOUT_S = 30.0
  17. # One launch lock per profile home (the real-profile browser and its copy dir are per home): a slow or
  18. # abandoned launch in one profile must never make another wait, then fall back to a signed-out browser.
  19. _locks: dict[str, threading.Lock] = {}
  20. _locks_guard = threading.Lock()
  21. # Extra flags on top of the launcher's base set: no hang monitor / popup blocking / repost prompts on an
  22. # unattended browser driving the user's own sessions.
  23. _REAL_PROFILE_EXTRA_FLAGS = ("--disable-hang-monitor", "--disable-popup-blocking", "--disable-prompt-on-repost")
  24. def real_profile_fallback_note(err: str) -> str:
  25. """Tool-result note when the real profile can't load and a fresh browser serves instead: the browser keeps
  26. working (a consented user is never left with no browser), and the model is told it is signed out."""
  27. return (f"{err} Using a fresh browser without the user's logins for this session instead; "
  28. "tell the user if the task needs their accounts.")
  29. def _unsupported_reason(browser) -> Optional[str]:
  30. """Why the default browser's profile can't be used, else None. A pre-release channel lives in a profile
  31. dir we don't resolve; normalizing it to the stable family would drive a DIFFERENT account."""
  32. from hermes_cli.browser_connect import UNSUPPORTED_CHANNEL
  33. if browser is None:
  34. return (_RP + "your default browser is not a supported Chromium browser (Chrome, Edge, Brave, "
  35. "Brave Origin, Chromium). Real-profile browsing requires a Chromium default; set one or turn the toggle off.")
  36. if browser == UNSUPPORTED_CHANNEL:
  37. return (_RP + "your default browser is a pre-release Chromium channel (Beta / Dev / Canary), which "
  38. "real-profile browsing does not support. Set your default to a "
  39. "stable Chrome / Edge / Brave / Brave Origin / Chromium, or turn the toggle off.")
  40. return None
  41. def _snapshot_error(err: str) -> str:
  42. """A locked profile adds the approved-close command, which the agent must ASK the user about first."""
  43. from hermes_cli.browser_connect import _PROFILE_LOCKED_PREFIX
  44. if err and err.startswith(_PROFILE_LOCKED_PREFIX):
  45. return (err[len(_PROFILE_LOCKED_PREFIX):] + " To close it (only after the user approves — it "
  46. "quits their browser and loses unsaved tabs), run: `hermes browser close-profile`; the next "
  47. "browser session then uses the profile.")
  48. return f"{_RP}{err}"
  49. def _home_lock() -> threading.Lock:
  50. from hermes_constants import hermes_home_key
  51. with _locks_guard:
  52. return _locks.setdefault(hermes_home_key(), threading.Lock())
  53. def real_profile_key() -> str:
  54. """Launcher key of the CURRENT profile's real-profile browser. Per home: one process serves many profiles,
  55. so a consent-off profile must never stop another's browser, nor a consenting one reuse its cookie jar."""
  56. from hermes_constants import hermes_home_key
  57. return f"hermes-real-profile@{hermes_home_key()}"
  58. def terminate_real_profile_browser() -> None:
  59. """Stop this profile's real-profile browser if this process launched it (idempotent)."""
  60. from tools.browser_launcher import stop_browser
  61. stop_browser(real_profile_key())
  62. def _consent_revoked() -> tuple[None, None]:
  63. """Consent off: stop the copy-browser and delete the snapshot store (copies of cookies/logins), so
  64. revoking consent actually removes the credential copies."""
  65. terminate_real_profile_browser()
  66. try:
  67. from hermes_cli.browser_connect import cleanup_real_profile_snapshots
  68. cleanup_real_profile_snapshots()
  69. except OSError as exc:
  70. logger.debug("real-profile cleanup-on-consent-off failed: %s", exc)
  71. return None, None
  72. def _launch(browser_name: str) -> tuple[Optional[str], Optional[str]]:
  73. from hermes_cli.browser_connect import chromium_executable, real_profile_copy_dir, snapshot_real_profile
  74. from tools.browser_launcher import launch_chromium
  75. from tools.browser_session import ensure_screen_for_headed_chromium
  76. real_binary = chromium_executable(browser_name)
  77. if real_binary is None:
  78. return None, f"{_RP}the real browser binary for '{browser_name}' could not be found. Reinstall it or turn the toggle off."
  79. snapshot_failure: list[str] = []
  80. def overlay() -> Optional[str]:
  81. # The snapshot overlay rewrites Cookies / Login Data, so it runs inside the launcher's cross-process
  82. # step on the copy dir: never beside another process's copy, never under a live copy-browser (maybe
  83. # from an earlier Hermes process; the launcher ATTACHES to that one instead).
  84. copied, err = snapshot_real_profile(browser_name)
  85. if err or not copied:
  86. snapshot_failure.append(_snapshot_error(err))
  87. return snapshot_failure[0]
  88. return None
  89. ensure_screen_for_headed_chromium()
  90. launched, err = launch_chromium(real_profile_key(), executable=real_binary,
  91. user_data_dir=real_profile_copy_dir(browser_name), ephemeral=False,
  92. extra_args=_REAL_PROFILE_EXTRA_FLAGS, timeout=30.0, sandbox_bypass=False,
  93. prepare=overlay)
  94. if launched is None:
  95. return None, snapshot_failure[0] if snapshot_failure else f"{_RP}the real-profile browser failed to start: {err}"
  96. logger.info("real-profile browser ready for %s at %s (%s)", browser_name, launched.http_url, launched.user_data_dir)
  97. return launched.cdp_url, None
  98. def real_profile_cdp() -> tuple[Optional[str], Optional[str]]:
  99. """``(cdp_url, error)`` for consented real-profile browsing.
  100. Snapshot → launch the real binary on the copy (or attach to the one already running) → its CDP URL.
  101. ``(None, message)`` when it can't (callers fall back to a fresh browser and report the message);
  102. ``(None, None)`` when consent is off."""
  103. from tools.browser_session_cloud import use_real_profile
  104. if not use_real_profile():
  105. return _consent_revoked()
  106. # Lightpanda cannot load a Chromium profile; checked before default-browser detection so a host with no
  107. # Chromium default still reports the actionable engine conflict.
  108. from tools.browser_lightpanda import using_lightpanda_engine
  109. if using_lightpanda_engine():
  110. return None, (_RP + "browser.engine is set to 'lightpanda', which cannot load a real Chromium profile. "
  111. "Set browser.engine to 'auto' to use real-profile browsing, or turn the toggle off.")
  112. lock = _home_lock()
  113. if not lock.acquire(timeout=_LOCK_TIMEOUT_S):
  114. return None, (_RP + "the real-profile browser is already being prepared by another call that has not "
  115. "finished. Retry after that call completes, or restart Hermes if it was abandoned.")
  116. try:
  117. from tools.browser_launcher import get_browser
  118. running = get_browser(real_profile_key())
  119. if running is not None:
  120. return running.cdp_url, None
  121. from hermes_cli.browser_connect import detect_default_chromium
  122. browser_name = detect_default_chromium()
  123. unsupported = _unsupported_reason(browser_name)
  124. if unsupported:
  125. return None, unsupported
  126. return _launch(browser_name)
  127. finally:
  128. lock.release()