browser.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. """The bot's browser on its Bot Desktop: one executable, one persistent user-data-dir per profile.
  2. The agent's Chromium (``tools.browser_session`` → ``tools.browser_launcher``) and the dock's Browser icon a
  3. human clicks must be THE SAME browser — same binary, same ``--user-data-dir`` — or the human logs in to a
  4. jar the bot never sees. Chromium's singleton makes a second launch on the same user-data-dir open a window
  5. in the running instance, which is the hand-over we want in ONE direction. When the human's dock instance is
  6. already up, a launch would be forwarded to it and exit without a DevTools endpoint, so the dock exposes a
  7. debugging port and the launcher ATTACHES to it instead of launching.
  8. """
  9. from __future__ import annotations
  10. import os
  11. import shutil
  12. from pathlib import Path
  13. from typing import Optional
  14. from tools.bot_desktop import runtime
  15. DISK_CACHE_BYTES = 256 * 1024 * 1024
  16. _SYSTEM_BROWSERS = ("google-chrome", "google-chrome-stable", "chromium", "chromium-browser")
  17. def profile_dir() -> Path:
  18. """User-data-dir the bot's browser uses on this profile's screen. ``browser.user_data_dir`` pins your own:
  19. ``~`` expands, and a relative path is anchored at this profile's HERMES_HOME (where the rest of the screen's
  20. state lives), so ``pin`` means ``<HERMES_HOME>/pin`` and two profiles never share one jar by accident."""
  21. from tools.browser_session_cloud import user_data_dir
  22. override = user_data_dir()
  23. return Path(override) if override else runtime.state_dir() / "browser-profile"
  24. def executable() -> Optional[str]:
  25. """The Chromium the bot runs: an explicit ``browser.executable_path``, else the packaged Chromium, else a
  26. system Chrome/Chromium. ``None`` when there is none.
  27. Non-root under ``kernel.apparmor_restrict_unprivileged_userns=1`` (Ubuntu 23.10+) flips the order:
  28. Playwright's bundle has no setuid ``chrome_sandbox`` and dies 'FATAL: No usable sandbox!' there, while
  29. a distro chromium ships the helper. The bundle stays the answer when it is the only browser — a dock
  30. icon that fails loudly beats a non-root ``--no-sandbox``.
  31. """
  32. from tools.browser_session_cloud import executable_path
  33. explicit = executable_path()
  34. if explicit and os.access(explicit, os.X_OK) and not _is_headless_shell(explicit):
  35. return explicit
  36. finders = [_managed_executable, _system_executable]
  37. if not _is_root() and _userns_restricted():
  38. finders.reverse()
  39. return next((exe for find in finders if (exe := find())), None)
  40. def _managed_executable() -> Optional[str]:
  41. from hermes_cli.browser_runtime import chromium_executable
  42. exe = chromium_executable(allow_override=False)
  43. return exe if exe and os.access(exe, os.X_OK) and not _is_headless_shell(exe) else None
  44. def _is_headless_shell(exe: str) -> bool:
  45. """Playwright's ``chrome-headless-shell`` can drive pages but cannot open a window; trusting such an
  46. override blindly would pin a windowless binary to the dock's Browser icon."""
  47. return "headless" in os.path.basename(exe).lower() or "headless_shell" in exe
  48. def _system_executable() -> Optional[str]:
  49. return next((shutil.which(name) for name in _SYSTEM_BROWSERS if shutil.which(name)), None)
  50. def _is_root() -> bool:
  51. return hasattr(os, "geteuid") and os.geteuid() == 0
  52. def _userns_restricted() -> bool:
  53. from tools.browser_launcher import apparmor_restricts_unprivileged_userns
  54. return apparmor_restricts_unprivileged_userns()
  55. def dock_launch() -> Optional[tuple[str, str]]:
  56. """``(executable, user_data_dir)`` for the dock's Browser icon, or ``None`` when no Chromium exists."""
  57. exe = executable()
  58. return (exe, str(profile_dir())) if exe else None
  59. # Flags the agent's launch and the dock's icon share on the persistent profile. --test-type hides the
  60. # "Chrome for Testing is only for automated testing" and unsupported-flag (--no-sandbox as root) infobars
  61. # that would sit over the human's takeover view; the persistent profile's HTTP cache is capped (uncapped it
  62. # grows for months toward a hosted instance's 6 GB).
  63. SHARED_PROFILE_ARGS = ("--test-type", f"--disk-cache-size={DISK_CACHE_BYTES}")
  64. def dock_argv(exe: str, user_data_dir: str, *, sandbox_bypass: Optional[bool] = None) -> list[str]:
  65. """Command the dock's Browser icon runs. ``--remote-debugging-port=0`` makes a human-started
  66. instance attachable (Chromium writes the chosen port to ``<user-data-dir>/DevToolsActivePort``);
  67. first-run / default-browser dialogs would sit between the human and the bot's tabs. The sandbox policy
  68. is the launcher's (root, Docker, AppArmor userns): the human's Browser is the bot's browser."""
  69. from tools.browser_launcher import CHROMIUM_SANDBOX_BYPASS_ARGS, needs_chromium_sandbox_bypass
  70. return [exe, f"--user-data-dir={user_data_dir}", "--remote-debugging-port=0", "--no-first-run",
  71. "--no-default-browser-check", *SHARED_PROFILE_ARGS,
  72. *(CHROMIUM_SANDBOX_BYPASS_ARGS if (needs_chromium_sandbox_bypass() if sandbox_bypass is None
  73. else sandbox_bypass) else ())]
  74. def dock_exec_line(exe: str, user_data_dir: str, *, sandbox_bypass: Optional[bool] = None) -> str:
  75. """The ``Exec=`` line of the dock's ``.desktop`` entry. Every argument is double-quoted per the
  76. Desktop Entry spec (a browser under ``/opt/Google Chrome/`` or a profile under a spaced HERMES_HOME
  77. otherwise splits into garbage): inside the quotes ``" ` $ \\`` are backslash-escaped, and because the
  78. value is itself a string field, each of those backslashes is escaped once more."""
  79. def quote(arg: str) -> str:
  80. quoted = "".join("\\" + ch if ch in '"`$\\' else ch for ch in arg)
  81. return '"' + quoted.replace("\\", "\\\\") + '"'
  82. return "Exec=" + " ".join(quote(arg) for arg in dock_argv(exe, user_data_dir, sandbox_bypass=sandbox_bypass))