config_migrations_browser.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. """Config step 51 -> 52 (registered in ``hermes_cli.config_migrations.MIGRATIONS``): agent-browser and the
  2. built-in browser_* tools left Hermes, so ``browser.backend`` / ``browser.extension_control`` go and the
  3. AGENT_BROWSER_* settings a home's .env gave agent-browser move to the ``browser.*`` keys the launcher reads."""
  4. from __future__ import annotations
  5. import os
  6. import re
  7. from typing import Any
  8. # AGENT_BROWSER_* (read by agent-browser, which left Hermes) -> the browser.* key Hermes reads now.
  9. _AGENT_BROWSER_ENV_KEYS = (
  10. ("AGENT_BROWSER_EXECUTABLE_PATH", "executable_path"),
  11. ("AGENT_BROWSER_PROFILE", "user_data_dir"),
  12. ("AGENT_BROWSER_ARGS", "chromium_args"),
  13. ("AGENT_BROWSER_HEADED", "headed"),
  14. ("AGENT_BROWSER_ENGINE", "engine"),
  15. )
  16. def _agent_browser_env(home) -> dict[str, str]:
  17. """AGENT_BROWSER_* as *home* set them: its dotenv layers, then the process env for the launch home
  18. only (a served profile's env is the launch profile's, not its own)."""
  19. from hermes_cli.env_loader import resolve_home_dotenv
  20. from hermes_constants import get_routing_process_hermes_home, hermes_home_key
  21. dotenv = resolve_home_dotenv(home)
  22. launch = hermes_home_key(home) == hermes_home_key(get_routing_process_hermes_home())
  23. found = {}
  24. for name, _key in _AGENT_BROWSER_ENV_KEYS:
  25. value = (dotenv.get(name) or (os.environ.get(name) if launch else None) or "").strip()
  26. if value:
  27. found[name] = value
  28. return found
  29. def _inside_pm_store(value: str) -> bool:
  30. """pm (and the Docker image, from pm) exported its own Chromium as AGENT_BROWSER_EXECUTABLE_PATH:
  31. that is the default now, and a copied versioned store path would break at the next Chromium bump."""
  32. from pathlib import Path
  33. from pm import paths
  34. try:
  35. resolved = Path(value).expanduser().resolve()
  36. roots = {paths.store_root().resolve(), paths.writable_store_root().resolve()}
  37. except (OSError, RuntimeError):
  38. return False
  39. return any(resolved.is_relative_to(root) for root in roots)
  40. def _browser_value_from_env(key: str, value: str) -> Any:
  41. """The ``browser.<key>`` value an AGENT_BROWSER_* value meant, or None when it carries nothing."""
  42. if key == "chromium_args":
  43. return [arg.strip() for arg in re.split(r"[,\n]", value) if arg.strip()] or None
  44. if key == "headed":
  45. return True if value.lower() in ("1", "true", "yes", "on") else None
  46. if key == "engine":
  47. return value.lower() if value.lower() in ("auto", "lightpanda", "chrome") else None
  48. if key == "executable_path" and _inside_pm_store(value):
  49. return None
  50. if key == "user_data_dir" and not os.path.isabs(os.path.expanduser(value)):
  51. # agent-browser inherited Hermes's cwd and resolved a relative profile there; browser.user_data_dir
  52. # anchors relative paths at HERMES_HOME, so pin the directory the logins are in now.
  53. return os.path.abspath(os.path.expanduser(value))
  54. return value
  55. def _config_decided(key: str, current: Any) -> bool:
  56. """``browser.<key>`` already won over its AGENT_BROWSER_* var, as core resolved them: ``engine: auto``
  57. deferred to AGENT_BROWSER_ENGINE and ``headed`` was config OR env, so those defaults (core's `hermes
  58. tools` Local Browser row wrote ``engine: auto``; old saves materialised both) do not block the move."""
  59. if key == "engine":
  60. return str(current or "").strip().lower() not in ("", "auto")
  61. if key == "headed":
  62. return current is not None and str(current).strip().lower() in ("true", "1", "yes")
  63. return current not in (None, "", [])
  64. # browser.backend chose Browser Use mode (browser_exec) or the built-in browser_* tools; any value but
  65. # ``browser-use`` meant the built-in tools, on whatever browser the value named.
  66. _BACKEND_REASONS = {
  67. "browser-use": "browser_exec (Browser Use mode) is the only browser now",
  68. "agent-browser": "agent-browser left Hermes; browser_exec is the browser now",
  69. "camofox": "Camofox is now the camofox plugin (`hermes plugins install camofox`)",
  70. "local": "browser_exec launches Hermes's packaged Chromium itself (browser.cloud_provider: local)",
  71. **dict.fromkeys(("browserbase", "firecrawl", "nous"),
  72. "a cloud browser is chosen with browser.cloud_provider (`hermes tools` → Browser Automation)"),
  73. }
  74. def _backend_removed_note(backend: Any) -> str:
  75. value = "" if backend is None or isinstance(backend, bool) else str(backend).strip()
  76. if not value:
  77. return "removed browser.backend (unset)"
  78. reason = _BACKEND_REASONS.get(value.lower(), "browser_exec is the only browser now")
  79. return f"removed browser.backend: {value} — {reason}"
  80. def move_agent_browser_env(home, browser: dict) -> tuple[list[str], list[str]]:
  81. """Move *home*'s AGENT_BROWSER_* settings into *browser* (its raw ``browser:`` section), never over a
  82. value that already won over them (:func:`_config_decided`). Returns the ``NAME → browser.key`` moves and
  83. the notes for a relative profile pinned to an absolute directory, which the user must read."""
  84. moved, pinned = [], []
  85. for name, value in _agent_browser_env(home).items():
  86. key = dict(_AGENT_BROWSER_ENV_KEYS)[name]
  87. if _config_decided(key, browser.get(key)):
  88. continue
  89. new = _browser_value_from_env(key, value)
  90. if new is None:
  91. continue
  92. browser[key] = new
  93. moved.append(f"{name} → browser.{key}")
  94. if key == "user_data_dir" and new != value:
  95. # Resolved against this process's cwd, which need not be where Hermes ran before.
  96. pinned.append(f"pinned browser.user_data_dir to {new}: {name}={value} was relative to the directory "
  97. f"Hermes ran in; check that the browser logins are there")
  98. return moved, pinned
  99. def agent_browser_env_pending() -> bool:
  100. """The active home's config.yaml would still take AGENT_BROWSER_* settings from its .env (the v52 move)."""
  101. from pathlib import Path
  102. from hermes_cli.config import read_raw_config
  103. from hermes_constants import get_hermes_home
  104. config = read_raw_config()
  105. browser = config.get("browser") if isinstance(config.get("browser"), dict) else {}
  106. return bool(move_agent_browser_env(Path(get_hermes_home()), dict(browser))[0])
  107. def adopt_agent_browser_env(home, config: dict) -> list[str]:
  108. """*config* is about to give *home* its first ``_config_version`` outside a config step, so the v52 step
  109. will never move this home's AGENT_BROWSER_* settings: move them into *config* now. Once only, because
  110. every later write carries the stamp. Returns the moves; a pinned profile becomes a startup notice."""
  111. browser = config.get("browser") if isinstance(config.get("browser"), dict) else {}
  112. moved, pinned = move_agent_browser_env(home, browser)
  113. if moved:
  114. config["browser"] = browser
  115. if pinned:
  116. from hermes_cli.left_core_migration import defer_startup_notice
  117. for note in pinned:
  118. defer_startup_notice(f"{note[0].upper()}{note[1:]}.")
  119. return moved
  120. def migrate_to_52(results: dict[str, Any], quiet: bool) -> None:
  121. # 51 -> 52: agent-browser and the built-in browser_* tools left Hermes; browser_exec is the only
  122. # browser. `browser.backend` chose between the two, so it is dropped (an `off`, the opt-out of
  123. # browser_exec, gets a notice saying how to turn browsing off now). The AGENT_BROWSER_* settings
  124. # this home's .env gave agent-browser move to the browser.* keys the launcher reads, never over
  125. # a value that already won over them (:func:`_config_decided`). .env itself is left alone. Camofox left core in the same release: a home
  126. # running it is recorded now, from its pre-v52 files, so its left-core row converts it later
  127. # while a newer home that installs the camofox plugin itself keeps browser_exec. The
  128. # browser-extension control lane dispatched to the removed tools, so its key goes too.
  129. from pathlib import Path
  130. from hermes_cli.config_migrations import _persist_migration, read_raw_config
  131. from hermes_cli.left_core_migration import record_core_use
  132. from hermes_constants import get_hermes_home
  133. config = read_raw_config()
  134. browser = config.get("browser") if isinstance(config.get("browser"), dict) else {}
  135. # notices: what the user must read even when nothing prints this migration (boot runs it quietly).
  136. added, messages, notices = [], [], []
  137. if "backend" in browser:
  138. backend = browser.pop("backend")
  139. # YAML 1.1 reads an unquoted `off` as False; core treated that as off too.
  140. if backend is False or (isinstance(backend, str) and backend.strip().lower() == "off"):
  141. # config_added is what `hermes update` re-surfaces on its quiet path, so the notice rides in it.
  142. note = ("removed browser.backend: off — the built-in browser tools are gone and browser_exec is the "
  143. "browser now; to turn browsing off, disable the `browser` toolset in `hermes tools`")
  144. added.append(note)
  145. messages.append(f" ✓ {note[0].upper()}{note[1:]}.")
  146. notices.append(f"{note[0].upper()}{note[1:]}.")
  147. else:
  148. added.append(_backend_removed_note(backend))
  149. if "extension_control" in browser:
  150. browser.pop("extension_control")
  151. added.append("removed browser.extension_control")
  152. moved, pinned = move_agent_browser_env(Path(get_hermes_home()), browser)
  153. for note in pinned:
  154. added.append(note)
  155. messages.append(f" ✓ {note[0].upper()}{note[1:]}.")
  156. notices.append(f"{note[0].upper()}{note[1:]}.")
  157. if moved:
  158. added.append(f"browser: {', '.join(moved)}")
  159. messages.append(f" ✓ Moved agent-browser settings from .env to config.yaml: {', '.join(moved)}")
  160. used = record_core_use(Path(get_hermes_home()), config, 52)
  161. if not added and not used:
  162. return
  163. if added:
  164. config["browser"] = browser
  165. _persist_migration(config)
  166. results["config_added"].extend(added)
  167. results.setdefault("notices", []).extend(notices)
  168. if not quiet:
  169. for message in messages:
  170. print(message)