__init__.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. """Computer-use provider discovery: bundled ``plugins/computer_use/<name>/`` (the built-in ``cua`` driver lives
  2. here too) then user ``$HERMES_HOME/plugins/<name>/`` (bundled wins on collision). Exactly one provider is active:
  3. ``computer_use.backend`` in the active profile's config.yaml names its directory (default ``cua``), read per call.
  4. Only that provider is imported; the others stay on disk, so a plugin that is installed but not selected is just an
  5. option in ``hermes tools``. A configured name that resolves to nothing fails; there is no fallback driver."""
  6. from __future__ import annotations
  7. import logging
  8. from pathlib import Path
  9. from typing import TYPE_CHECKING, List, Optional, Tuple
  10. from plugins import plugin_loader as _loader
  11. if TYPE_CHECKING:
  12. from tools.computer_use.backend import ComputerUseProvider
  13. logger = logging.getLogger(__name__)
  14. DEFAULT_BACKEND = "cua"
  15. _CU_PLUGINS_DIR = Path(__file__).parent
  16. # Synthetic parent package for user-installed providers (keeps them out of the bundled namespace).
  17. _USER_NAMESPACE = "_hermes_user_computer_use"
  18. def _is_computer_use_dir(path: Path) -> bool:
  19. """Cheap text heuristic: ``__init__.py`` mentions the computer-use provider contract."""
  20. try:
  21. source = (path / "__init__.py").read_text(errors="replace", encoding="utf-8-sig")[:8192]
  22. except OSError:
  23. return False
  24. return "register_computer_use_provider" in source or "ComputerUseProvider" in source
  25. def _iter_provider_dirs() -> list[tuple[str, Path]]:
  26. """``(name, path)`` for bundled then user providers; bundled wins on collisions."""
  27. dirs = [(child.name, child) for child in _loader.iter_plugin_dirs(_CU_PLUGINS_DIR)]
  28. seen = {name for name, _ in dirs}
  29. user_dir = _loader.user_plugins_dir()
  30. if user_dir:
  31. dirs.extend((child.name, child) for child in _loader.iter_plugin_dirs(user_dir)
  32. if child.name not in seen and _is_computer_use_dir(child))
  33. return dirs
  34. def discover_computer_use_providers() -> list[tuple[str, str]]:
  35. """``[(name, description), ...]`` from plugin.yaml only: listing never imports a provider."""
  36. return [(name, _loader.read_plugin_description(child)) for name, child in _iter_provider_dirs()]
  37. def find_provider_dir(name: str) -> Optional[Path]:
  38. """Resolve a provider name to its directory (bundled first, then user-installed)."""
  39. return next((path for found, path in _iter_provider_dirs() if found == name), None)
  40. def load_computer_use_provider(name: str) -> Optional[ComputerUseProvider]:
  41. """Import the named provider and return its ComputerUseProvider; None if not found or it fails to load."""
  42. provider_dir = find_provider_dir(name)
  43. if provider_dir is None:
  44. return None
  45. return _loader.load_named(name, provider_dir, _load_provider_from_dir, kind="Computer-use provider",
  46. noun="provider", logger=logger)
  47. def _load_provider_from_dir(provider_dir: Path) -> Optional[ComputerUseProvider]:
  48. # Providers hand back live driver sessions, so they load in-process only: load_plugin_module refuses user
  49. # code under ``plugins.isolation: host`` (warning + None), which surfaces as "could not be loaded".
  50. from tools.computer_use.backend import ComputerUseProvider
  51. name = provider_dir.name
  52. is_bundled = provider_dir.parent == _CU_PLUGINS_DIR
  53. mod = _loader.load_plugin_module(
  54. f"plugins.computer_use.{name}" if is_bundled else f"{_USER_NAMESPACE}.{name}", provider_dir,
  55. parents=("plugins", "plugins.computer_use"), logger=logger,
  56. synthetic_namespace=None if is_bundled else _USER_NAMESPACE)
  57. return mod and _loader.instance_from_module(
  58. mod, collector=_ProviderCollector(), collected_attr="provider", base_cls=ComputerUseProvider,
  59. name=name, logger=logger)
  60. class _ProviderCollector(_loader.NoopPluginContext):
  61. """Fake plugin context that captures ``register_computer_use_provider``."""
  62. def __init__(self):
  63. self.provider = None
  64. def register_computer_use_provider(self, provider):
  65. self.provider = provider
  66. def configured_backend_name() -> str:
  67. """``computer_use.backend`` from the active profile's config.yaml (``cua`` when unset)."""
  68. from hermes_cli.config import load_config_readonly
  69. raw = ((load_config_readonly() or {}).get("computer_use") or {}).get("backend")
  70. return raw.strip() if isinstance(raw, str) and raw.strip() else DEFAULT_BACKEND
  71. def get_active_provider() -> ComputerUseProvider:
  72. """The one provider ``computer_use.backend`` selects; ``LookupError`` naming the available ones otherwise."""
  73. name = configured_backend_name()
  74. provider = load_computer_use_provider(name)
  75. if provider is None:
  76. available = ", ".join(found for found, _ in discover_computer_use_providers())
  77. state = "could not be loaded (see the log)" if find_provider_dir(name) else "is not installed"
  78. raise LookupError(
  79. f"computer_use.backend is {name!r}, but that computer-use provider {state} (available: {available}). "
  80. "Install it under ~/.hermes/plugins/<name>/ or pick a backend with `hermes tools`.")
  81. return provider