Skip to content

The agent that grows with you

feat(computer-use): pluggable single-select computer-use providers

Teknium63f5e0ea4572
diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.py
index f9f9bd02fda..38e552b5177 100644
--- a/hermes_cli/plugins_cmd.py
+++ b/hermes_cli/plugins_cmd.py
@@ -804,11 +804,11 @@ def _discover_all_plugins() -> list:
in ``PluginManager.discover_and_load`` order: bundled, user, then entry points — which never
displace a directory plugin of the same key (see ``PluginManager._discover_and_load_inner``)."""
seen: dict = {}
- # memory/, context_engine/ and model-providers/ load through dedicated registries, not the
+ # memory/, context_engine/, computer_use/ and model-providers/ load through dedicated registries, not the
# PluginManager opt-in surface, so listing them as toggleable plugins would mislead.
from hermes_cli.plugins import discover_entrypoint_manifests, get_bundled_plugins_dir
for base, source, skip in (
- (get_bundled_plugins_dir(), "bundled", {"memory", "context_engine", "model-providers"}),
+ (get_bundled_plugins_dir(), "bundled", {"memory", "context_engine", "computer_use", "model-providers"}),
(_plugins_dir(), "user", set()),
):
_scan_level(base, source, skip, "", 0, seen)
diff --git a/hermes_cli/plugins_discovery.py b/hermes_cli/plugins_discovery.py
index edd684af8d2..2cd1cf2bcf1 100644
--- a/hermes_cli/plugins_discovery.py
+++ b/hermes_cli/plugins_discovery.py
@@ -205,7 +205,7 @@ def collect_directory_manifests() -> List[PluginManifest]:
repo_plugins = _origin.get_bundled_plugins_dir()
logger.debug("Scanning bundled plugins: %s", repo_plugins)
_scan("bundled (top-level)", repo_plugins, "bundled",
- {"memory", "context_engine", "model-providers", "cron_providers"})
+ {"memory", "context_engine", "model-providers", "cron_providers", "computer_use"})
user_dir = get_hermes_home() / "plugins"
logger.debug("Scanning user plugins: %s", user_dir)
_scan("user", user_dir, "user")
diff --git a/hermes_cli/plugins_manifest.py b/hermes_cli/plugins_manifest.py
index 409b309361d..19d791f5aab 100644
--- a/hermes_cli/plugins_manifest.py
+++ b/hermes_cli/plugins_manifest.py
@@ -267,11 +267,12 @@ def resolve_plugin_load_order(manifests: Mapping[str, "PluginManifest"]) -> List
def _detect_kind_from_source(source_text: str) -> Optional[str]:
"""Kind implied by source markers (mirrors plugins/memory ``_is_memory_provider_dir`` and
- plugins/cron_providers ``_is_cron_provider_dir``): memory- or cron-provider markers -> ``exclusive``;
+ plugins/cron_providers ``_is_cron_provider_dir``): memory-, cron- or computer-use-provider markers -> ``exclusive``;
``register_provider`` + ``ProviderProfile`` -> ``model-provider``; else ``None``. Keeps these kinds out
of the general manager's eager import (its PluginContext has no ``register_cron_scheduler``, #62951)."""
if any(marker in source_text for marker in (
- "register_memory_provider", "MemoryProvider", "register_cron_scheduler", "CronScheduler")):
+ "register_memory_provider", "MemoryProvider", "register_cron_scheduler", "CronScheduler",
+ "register_computer_use_provider", "ComputerUseProvider")):
return "exclusive"
if "register_provider" in source_text and "ProviderProfile" in source_text:
return "model-provider"
diff --git a/hermes_cli/subcommands/computer_use.py b/hermes_cli/subcommands/computer_use.py
index e88509f9fd2..cc46c1b8244 100644
--- a/hermes_cli/subcommands/computer_use.py
+++ b/hermes_cli/subcommands/computer_use.py
@@ -7,12 +7,32 @@ import sys
from hermes_cli.subcommands._shared import add_json_flag
+def _exit_if_plugin_backend(*, doctor: bool = False) -> None:
+ """cua-driver checks do not apply when ``computer_use.backend`` selects another backend: report it
+ (running its own ``doctor()`` when asked and it ships one) and exit; return for the built-in."""
+ from plugins.computer_use import DEFAULT_BACKEND, configured_backend_name, get_active_provider
+ if configured_backend_name() == DEFAULT_BACKEND:
+ return
+ try:
+ provider = get_active_provider()
+ except LookupError as e:
+ print(f"Computer Use: {e}")
+ sys.exit(2)
+ if doctor and (rc := provider.doctor()) is not None:
+ sys.exit(rc)
+ ok = provider.is_available()
+ print(f"Computer Use backend: {provider.name} ({provider.display_name}) — "
+ f"{'available' if ok else 'not available'}. cua-driver checks do not apply to this backend.")
+ sys.exit(0 if ok else 1)
+
+
def _cu_install(args) -> int:
from hermes_cli.tools_config_cua import install_cua_driver
return 0 if install_cua_driver(upgrade=bool(getattr(args, "upgrade", False))) else 1
def _cu_status(args) -> int:
+ _exit_if_plugin_backend()
import os as _os
from hermes_cli.tools_config_cua import _cua_driver_contract_status, _cua_version_summary
from tools.computer_use.cua_backend_driver import resolve_cua_driver_cmd
@@ -54,6 +74,7 @@ def _cu_status(args) -> int:
def _cu_doctor(args) -> None:
+ _exit_if_plugin_backend(doctor=True)
from tools.computer_use.doctor import run_doctor
sys.exit(run_doctor(
include=list(getattr(args, "include", []) or []),
@@ -62,6 +83,8 @@ def _cu_doctor(args) -> None:
def _cu_perms_status(args) -> None:
+ if not getattr(args, "json", False): # --json: computer_use_status() reports the selected backend itself
+ _exit_if_plugin_backend()
import json as _json
from tools.computer_use.permissions import TCC_FIELDS, computer_use_status, stale_tcc_grant_hint
st = computer_use_status()
@@ -94,6 +117,7 @@ def _cu_perms_status(args) -> None:
def _cu_perms_grant(args) -> None:
+ _exit_if_plugin_backend()
from tools.computer_use.permissions import request_permissions_grant
sys.exit(request_permissions_grant())
diff --git a/hermes_cli/tools_config_providers.py b/hermes_cli/tools_config_providers.py
index d710dce9c5f..bb9aa772cdd 100644
--- a/hermes_cli/tools_config_providers.py
+++ b/hermes_cli/tools_config_providers.py
@@ -125,7 +125,17 @@ _PLUGIN_ROW_BUILDERS = {
"Video Generation": _plugin_video_gen_providers,
"Web Search & Extract": _plugin_web_search_providers,
"Browser Automation": _plugin_browser_providers,
- "Text-to-Speech": _plugin_tts_providers}
+ "Text-to-Speech": _plugin_tts_providers,
+ "Computer Use (macOS/Windows/Linux)": lambda: _computer_use_provider_rows()}
+
+
+def _computer_use_provider_rows() -> list[dict]:
+ """Rows for installed computer-use providers other than the built-in ``cua`` (hand-written row with its
+ install post-setup). Read from plugin.yaml without importing: an unselected provider stays dormant."""
+ from plugins.computer_use import DEFAULT_BACKEND, discover_computer_use_providers
+
+ return [{"name": name, "badge": "", "tag": desc, "env_vars": [], "computer_use_backend": name}
+ for name, desc in discover_computer_use_providers() if name != DEFAULT_BACKEND]
def _visible_providers(
diff --git a/plugins/computer_use/__init__.py b/plugins/computer_use/__init__.py
new file mode 100644
index 00000000000..cf7ee7152bd
--- /dev/null
+++ b/plugins/computer_use/__init__.py
@@ -0,0 +1,108 @@
+"""Computer-use provider discovery: bundled ``plugins/computer_use/<name>/`` (the built-in ``cua`` driver lives
+here too) then user ``$HERMES_HOME/plugins/<name>/`` (bundled wins on collision). Exactly one provider is active:
+``computer_use.backend`` in the active profile's config.yaml names its directory (default ``cua``), read per call.
+Only that provider is imported; the others stay on disk, so a plugin that is installed but not selected is just an
+option in ``hermes tools``. A configured name that resolves to nothing fails; there is no fallback driver."""
+
+from __future__ import annotations
+
+import logging
+from pathlib import Path
+from typing import TYPE_CHECKING, List, Optional, Tuple
+
+from plugins import plugin_loader as _loader
+
+if TYPE_CHECKING:
+ from tools.computer_use.backend import ComputerUseProvider
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_BACKEND = "cua"
+_CU_PLUGINS_DIR = Path(__file__).parent
+# Synthetic parent package for user-installed providers (keeps them out of the bundled namespace).
+_USER_NAMESPACE = "_hermes_user_computer_use"
+
+
+def _is_computer_use_dir(path: Path) -> bool:
+ """Cheap text heuristic: ``__init__.py`` mentions the computer-use provider contract."""
+ try:
+ source = (path / "__init__.py").read_text(errors="replace", encoding="utf-8-sig")[:8192]
+ except OSError:
+ return False
+ return "register_computer_use_provider" in source or "ComputerUseProvider" in source
+
+
+def _iter_provider_dirs() -> List[Tuple[str, Path]]:
+ """``(name, path)`` for bundled then user providers; bundled wins on collisions."""
+ dirs = [(child.name, child) for child in _loader.iter_plugin_dirs(_CU_PLUGINS_DIR)]
+ seen = {name for name, _ in dirs}
+ user_dir = _loader.user_plugins_dir()
+ if user_dir:
+ dirs.extend((child.name, child) for child in _loader.iter_plugin_dirs(user_dir)
+ if child.name not in seen and _is_computer_use_dir(child))
+ return dirs
+
+
+def discover_computer_use_providers() -> List[Tuple[str, str]]:
+ """``[(name, description), ...]`` from plugin.yaml only: listing never imports a provider."""
+ return [(name, _loader.read_plugin_description(child)) for name, child in _iter_provider_dirs()]
+
+
+def find_provider_dir(name: str) -> Optional[Path]:
+ """Resolve a provider name to its directory (bundled first, then user-installed)."""
+ return next((path for found, path in _iter_provider_dirs() if found == name), None)
+
+
+def load_computer_use_provider(name: str) -> Optional["ComputerUseProvider"]:
+ """Import the named provider and return its ComputerUseProvider; None if not found or it fails to load."""
+ provider_dir = find_provider_dir(name)
+ if provider_dir is None:
+ return None
+ return _loader.load_named(name, provider_dir, _load_provider_from_dir, kind="Computer-use provider",
+ noun="provider", logger=logger)
+
+
+def _load_provider_from_dir(provider_dir: Path) -> Optional["ComputerUseProvider"]:
+ # Providers hand back live driver sessions, so they load in-process only: load_plugin_module refuses user
+ # code under ``plugins.isolation: host`` (warning + None), which surfaces as "could not be loaded".
+ from tools.computer_use.backend import ComputerUseProvider
+ name = provider_dir.name
+ is_bundled = provider_dir.parent == _CU_PLUGINS_DIR
+ mod = _loader.load_plugin_module(
+ f"plugins.computer_use.{name}" if is_bundled else f"{_USER_NAMESPACE}.{name}", provider_dir,
+ parents=("plugins", "plugins.computer_use"), logger=logger,
+ synthetic_namespace=None if is_bundled else _USER_NAMESPACE)
+ return mod and _loader.instance_from_module(
+ mod, collector=_ProviderCollector(), collected_attr="provider", base_cls=ComputerUseProvider,
+ name=name, logger=logger)
+
+
+class _ProviderCollector(_loader.NoopPluginContext):
+ """Fake plugin context that captures ``register_computer_use_provider``."""
+
+ def __init__(self):
+ self.provider = None
+
+ def register_computer_use_provider(self, provider):
+ self.provider = provider
+
+
+def configured_backend_name() -> str:
+ """``computer_use.backend`` from the active profile's config.yaml (``cua`` when unset)."""
+ from hermes_cli.config import load_config_readonly
+
+ raw = ((load_config_readonly() or {}).get("computer_use") or {}).get("backend")
+ return raw.strip() if isinstance(raw, str) and raw.strip() else DEFAULT_BACKEND
+
+
+def get_active_provider() -> "ComputerUseProvider":
+ """The one provider ``computer_use.backend`` selects; ``LookupError`` naming the available ones otherwise."""
+ name = configured_backend_name()
+ provider = load_computer_use_provider(name)
+ if provider is None:
+ available = ", ".join(found for found, _ in discover_computer_use_providers())
+ state = "could not be loaded (see the log)" if find_provider_dir(name) else "is not installed"
+ raise LookupError(
+ f"computer_use.backend is {name!r}, but that computer-use provider {state} (available: {available}). "
+ "Install it under ~/.hermes/plugins/<name>/ or pick a backend with `hermes tools`.")
+ return provider
diff --git a/plugins/computer_use/cua/__init__.py b/plugins/computer_use/cua/__init__.py
new file mode 100644
index 00000000000..230fc073d4c
--- /dev/null
+++ b/plugins/computer_use/cua/__init__.py
@@ -0,0 +1,33 @@
+"""Built-in ``cua`` computer-use provider: cua-driver over MCP (:mod:`tools.computer_use.cua_backend`)."""
+
+from __future__ import annotations
+
+import sys
+
+from tools.computer_use.backend import ComputerUseBackend, ComputerUseProvider
+
+
+class CuaDriverProvider(ComputerUseProvider):
+ name = "cua"
+ display_name = "cua-driver (background)"
+
+ def create_backend(self, *, permission_mode: str) -> ComputerUseBackend:
+ from tools.computer_use.cua_backend import CuaDriverBackend
+ return CuaDriverBackend(permission_mode=permission_mode)
+
+ def is_available(self) -> bool:
+ """macOS/Windows/Linux + cua-driver binary (or env override). `hermes computer-use doctor` names blocked checks."""
+ if sys.platform not in ("darwin", "win32", "linux"):
+ return False
+ from tools.computer_use.cua_backend_driver import cua_driver_binary_available
+ if cua_driver_binary_available():
+ return True
+ # No host driver: the tool is still real when the desktop is placed inside a terminal backend whose image
+ # carries cua-driver (nousresearch/hermes-sandbox:desktop). Placement is config; the binary is probed lazily
+ # at first use, so this stays a cheap check_fn.
+ from tools.bot_desktop import placement
+ return placement.resolve().where == placement.TERMINAL
+
+
+def register(ctx):
+ ctx.register_computer_use_provider(CuaDriverProvider())
diff --git a/plugins/computer_use/cua/plugin.yaml b/plugins/computer_use/cua/plugin.yaml
new file mode 100644
index 00000000000..abf0826ff5d
--- /dev/null
+++ b/plugins/computer_use/cua/plugin.yaml
@@ -0,0 +1,6 @@
+name: cua
+description: >-
+ cua-driver (built-in) — background computer use on macOS, Windows and Linux; does not steal the cursor
+ or focus. Default when computer_use.backend is unset.
+version: 1.0.0
+author: Nous Research
diff --git a/tests/tools/test_computer_use.py b/tests/tools/test_computer_use.py
index 452b0ad0b53..1fac4ec7188 100644
--- a/tests/tools/test_computer_use.py
+++ b/tests/tools/test_computer_use.py
@@ -20,12 +20,12 @@ import pytest
def _reset_backend(grant_computer_use_approvals):
"""Tear down the cached backend between tests; destructive actions get an interactive "once"
through the shared approval gate (the tool fails closed with nobody to ask)."""
- from tools.computer_use.tool import reset_backend_for_tests
- reset_backend_for_tests()
+ from tools.computer_use import tool as cu_tool
+ cu_tool.reset_backend_for_tests()
# Force the noop backend.
- with patch.dict(os.environ, {"HERMES_COMPUTER_USE_BACKEND": "noop"}, clear=False):
+ with patch.object(cu_tool, "_new_backend", lambda mode: cu_tool._NoopBackend()):
yield
- reset_backend_for_tests()
+ cu_tool.reset_backend_for_tests()
@pytest.fixture
diff --git a/tests/tools/test_computer_use_backend_plugins.py b/tests/tools/test_computer_use_backend_plugins.py
new file mode 100644
index 00000000000..1ff85375216
--- /dev/null
+++ b/tests/tools/test_computer_use_backend_plugins.py
@@ -0,0 +1,130 @@
+"""Computer-use provider plugins: ``computer_use.backend`` selects exactly one provider per profile, only that one
+is imported, the built-in ``cua`` stays the default, and an unknown name fails loudly instead of falling back."""
+
+from __future__ import annotations
+
+import json
+import sys
+from pathlib import Path
+
+import pytest
+
+import hermes_yaml as yaml
+from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+_PLUGIN = '''
+from pathlib import Path
+from tools.computer_use.backend import ActionResult, ComputerUseBackend, ComputerUseProvider
+
+TAG = Path(__file__).parent.name
+CALLS = []
+
+class FakeBackend(ComputerUseBackend):
+ def __init__(self, mode): self.mode = mode
+ def start(self): CALLS.append(("start", self.mode))
+ def stop(self): CALLS.append(("stop", None))
+ def is_available(self): return True
+ def capture(self, mode="som", app=None, pid=None, window_id=None): raise NotImplementedError
+ def click(self, **kw):
+ CALLS.append(("click", kw.get("element")))
+ return ActionResult(ok=True, action="click")
+ def drag(self, **kw): return ActionResult(ok=True, action="drag")
+ def scroll(self, **kw): return ActionResult(ok=True, action="scroll")
+ def type_text(self, text, **kw): return ActionResult(ok=True, action="type")
+ def key(self, keys, **kw): return ActionResult(ok=True, action="key")
+ def list_apps(self): return [{"backend": TAG, "file": __file__}]
+ def focus_app(self, app, raise_window=False): return ActionResult(ok=True, action="focus_app")
+ def set_value(self, value, element=None): return ActionResult(ok=True, action="set_value")
+
+class FakeProvider(ComputerUseProvider):
+ name = TAG
+ def create_backend(self, *, permission_mode): return FakeBackend(permission_mode)
+
+def register(ctx):
+ ctx.register_computer_use_provider(FakeProvider())
+'''
+
+
+def _home(home: Path, plugins: tuple, backend: str | None) -> Path:
+ for plugin in plugins:
+ (plugin_dir := home / "plugins" / plugin).mkdir(parents=True, exist_ok=True)
+ (plugin_dir / "plugin.yaml").write_text(yaml.safe_dump({"name": plugin, "description": f"{plugin} driver"}))
+ (plugin_dir / "__init__.py").write_text(_PLUGIN)
+ home.mkdir(parents=True, exist_ok=True)
+ (home / "config.yaml").write_text(yaml.safe_dump({"computer_use": {"backend": backend}} if backend else {}))
+ return home
+
+
+def _list_apps(session_id: str = "s1") -> list:
+ from tools.computer_use.tool import handle_computer_use
+ out = json.loads(handle_computer_use({"action": "list_apps"}, session_id=session_id))
+ assert "apps" in out, out
+ return out["apps"]
+
+
[email protected](autouse=True)
+def _clean():
+ from tools.computer_use.tool import reset_backend_for_tests
+ reset_backend_for_tests()
+ yield
+ reset_backend_for_tests()
+ for name in [m for m in sys.modules if m.startswith("_hermes_user_computer_use.")]:
+ del sys.modules[name]
+
+
+def test_selected_plugin_receives_tool_calls_and_unselected_stays_dormant(tmp_path, grant_computer_use_approvals):
+ home = _home(tmp_path / "home", ("cu-alpha", "cu-beta"), "cu-beta")
+ tok = set_hermes_home_override(str(home))
+ try:
+ from tools.computer_use.tool import check_computer_use_requirements, handle_computer_use
+ assert check_computer_use_requirements() is True
+ assert _list_apps()[0]["backend"] == "cu-beta"
+ assert json.loads(handle_computer_use({"action": "click", "element": 3}, session_id="s1"))["ok"] is True
+ calls = sys.modules["_hermes_user_computer_use.cu-beta"].CALLS
+ assert ("start", "standard") in calls and ("click", 3) in calls
+ assert "_hermes_user_computer_use.cu-alpha" not in sys.modules # installed, not selected: never imported
+ from hermes_cli.tools_config_providers import _computer_use_provider_rows # `hermes tools` / Desktop rows
+ assert [r["computer_use_backend"] for r in _computer_use_provider_rows()] == ["cu-alpha", "cu-beta"]
+ assert "_hermes_user_computer_use.cu-alpha" not in sys.modules # listing does not import either
+ finally:
+ reset_hermes_home_override(tok)
+
+
+def test_unknown_backend_errors_naming_configured_and_available(tmp_path):
+ home = _home(tmp_path / "home", (), "nope")
+ tok = set_hermes_home_override(str(home))
+ try:
+ from tools.computer_use.tool import check_computer_use_requirements, handle_computer_use
+ out = json.loads(handle_computer_use({"action": "list_apps"}, session_id="s1"))
+ assert "'nope'" in out["error"] and "available: cua" in out["error"]
+ assert "hint" not in out # the cua-driver install hint would mislead here
+ assert check_computer_use_requirements() is True # the tool stays visible so the call can say why
+ finally:
+ reset_hermes_home_override(tok)
+
+
[email protected]("backend", [None, "cua"])
+def test_builtin_cua_is_default_and_plugin_never_self_activates(tmp_path, backend):
+ home = _home(tmp_path / "home", ("cu-alpha",), backend) # installed but not selected
+ tok = set_hermes_home_override(str(home))
+ try:
+ from plugins.computer_use import get_active_provider
+ from tools.computer_use.cua_backend import CuaDriverBackend
+ from tools.computer_use.tool import _new_backend
+ assert get_active_provider().name == "cua"
+ assert isinstance(_new_backend("standard"), CuaDriverBackend)
+ assert "_hermes_user_computer_use.cu-alpha" not in sys.modules
+ finally:
+ reset_hermes_home_override(tok)
+
+
+def test_each_profile_gets_its_own_configured_backend(tmp_path):
+ home_a = _home(tmp_path / "profiles" / "a", ("cu-alpha",), "cu-alpha")
+ home_b = _home(tmp_path / "profiles" / "b", ("cu-beta",), "cu-beta")
+ for home, expected in ((home_a, "cu-alpha"), (home_b, "cu-beta"), (home_a, "cu-alpha")):
+ tok = set_hermes_home_override(str(home))
+ try:
+ app = _list_apps(session_id="shared")[0]
+ assert app["backend"] == expected and str(home) in app["file"]
+ finally:
+ reset_hermes_home_override(tok)
diff --git a/tests/tools/test_computer_use_delivery_ladder.py b/tests/tools/test_computer_use_delivery_ladder.py
index 19afe03d937..e85a826e5b8 100644
--- a/tests/tools/test_computer_use_delivery_ladder.py
+++ b/tests/tools/test_computer_use_delivery_ladder.py
@@ -17,7 +17,6 @@ Stdlib + pytest + unittest.mock only. No live cua-driver, no network.
from __future__ import annotations
import json
-import os
from typing import Any, Dict, Optional
from unittest.mock import patch
@@ -214,7 +213,7 @@ def test_foreground_refused_on_old_driver():
def test_dispatcher_threads_delivery_mode_to_backend(grant_computer_use_approvals):
"""End-to-end through the tool dispatcher with the noop backend."""
from tools.computer_use import tool as cu
- with patch.dict(os.environ, {"HERMES_COMPUTER_USE_BACKEND": "noop"}, clear=False):
+ with patch.object(cu, "_new_backend", lambda mode: cu._NoopBackend()):
cu.reset_backend_for_tests()
be = cu._get_backend()
cu.handle_computer_use({"action": "click", "element": 5,
diff --git a/tests/tools/test_computer_use_native_platform.py b/tests/tools/test_computer_use_native_platform.py
index 37a6fcd6805..7c6442b5418 100644
--- a/tests/tools/test_computer_use_native_platform.py
+++ b/tests/tools/test_computer_use_native_platform.py
@@ -11,7 +11,7 @@ from tools.computer_use import tool
@pytest.fixture
def backend(monkeypatch):
tool.reset_backend_for_tests()
- monkeypatch.setenv("HERMES_COMPUTER_USE_BACKEND", "noop")
+ monkeypatch.setattr(tool, "_new_backend", lambda mode: tool._NoopBackend())
# Input actions are approval-gated; a CI runner has no approver, so the gate would block
# before the dispatch this test is about. Same seam the capture-fence tests use.
monkeypatch.setattr(tool, "_request_approval", lambda *a, **k: None)
diff --git a/tools/computer_use/backend.py b/tools/computer_use/backend.py
index 77666ce0e38..4956d2af490 100644
--- a/tools/computer_use/backend.py
+++ b/tools/computer_use/backend.py
@@ -1,6 +1,7 @@
-"""Abstract backend interface for computer use. Any implementation (cua-driver over MCP,
-pyautogui, noop, future Linux/Windows) returns the shapes below. All methods are synchronous;
-async is handled inside the backend implementation if needed."""
+"""Abstract backend interface for computer use. Any implementation (cua-driver over MCP, a plugin
+driver, the test noop) returns the shapes below. All methods are synchronous; async is handled inside
+the backend implementation if needed. :class:`ComputerUseProvider` is the factory a provider plugin
+registers (see :mod:`plugins.computer_use`); ``computer_use.backend`` selects exactly one."""
from __future__ import annotations
@@ -10,6 +11,8 @@ from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Tuple
+from agent.provider_base import ProviderBase
+
_JPEG_SOF_MARKERS = frozenset({0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF})
def image_dimensions_from_bytes(raw: bytes) -> Optional[Tuple[int, int]]:
@@ -172,3 +175,25 @@ class ComputerUseBackend(ABC):
def wait(self, seconds: float) -> ActionResult: # default implementation
time.sleep(max(0.0, min(seconds, 30.0)))
return ActionResult(ok=True, action="wait", message=f"waited {seconds:.2f}s")
+
+
+class ComputerUseProvider(ProviderBase):
+ """Factory for one computer_use driver, registered via ``ctx.register_computer_use_provider`` from a provider
+ plugin whose directory name is the ``computer_use.backend`` value (built-in: ``plugins/computer_use/cua``). Only
+ the selected provider is imported and instantiated. The model-facing tool schema is identical for every backend:
+ an action the driver cannot perform returns ``ActionResult(ok=False, code="unsupported_action", message=...)``
+ rather than changing the schema."""
+
+ @abstractmethod
+ def create_backend(self, *, permission_mode: str) -> ComputerUseBackend:
+ """A fresh, unstarted backend for one Hermes session (the tool calls ``start()``/``stop()``).
+ ``permission_mode`` is ``standard`` | ``bounded`` | ``unrestricted`` (approval bypass active)."""
+
+ def is_available(self) -> bool:
+ """Usable on this host right now (the tool's ``check_fn``). Cheap: no network, no spawning."""
+ return True
+
+ def doctor(self) -> Optional[int]:
+ """``hermes computer-use doctor`` for this backend: print findings, return the exit code.
+ ``None`` (default) means the backend ships no doctor."""
+ return None
diff --git a/tools/computer_use/permissions.py b/tools/computer_use/permissions.py
index 9df1af20798..ed4450f835a 100644
--- a/tools/computer_use/permissions.py
+++ b/tools/computer_use/permissions.py
@@ -86,11 +86,23 @@ def computer_use_status(driver_cmd: Optional[str] = None) -> Dict[str, Any]:
"""OS-aware readiness for the desktop card; key order is an API payload contract. ``ready`` is the single signal the
UI keys off: macOS = both TCC grants, elsewhere = driver health (no TCC model); ``None`` = unknown (binary missing /
probe failed). ``can_grant`` is macOS-only."""
+ from plugins.computer_use import DEFAULT_BACKEND, configured_backend_name, get_active_provider
from tools.computer_use.cua_backend_driver import resolve_cua_driver_cmd # same resolver as the tool itself
- plat, binary = sys.platform, resolve_cua_driver_cmd(driver_cmd)
+ plat, name = sys.platform, configured_backend_name()
+ binary = resolve_cua_driver_cmd(driver_cmd) if name == DEFAULT_BACKEND else None
out: Dict[str, Any] = {"platform": plat, "platform_supported": plat in _RUNTIME_PLATFORMS,
"installed": bool(binary), "version": None, "ready": None, "can_grant": plat == "darwin",
"checks": [], "source": None, "error": None, **{k: None for k in _BOOLS}}
+ if name != DEFAULT_BACKEND: # another driver is selected: cua-driver probes and TCC grants do not apply
+ out.update(platform_supported=True, can_grant=False)
+ try:
+ provider = get_active_provider()
+ except LookupError as e:
+ out["error"] = str(e)
+ return out
+ out.update(installed=True, version=f"{provider.display_name} (computer_use.backend: {provider.name})",
+ ready=provider.is_available())
+ return out
if not binary:
return out
with suppress(Exception):
diff --git a/tools/computer_use/tool.py b/tools/computer_use/tool.py
index e3c9d92fce1..25ccf175ca7 100644
--- a/tools/computer_use/tool.py
+++ b/tools/computer_use/tool.py
@@ -158,13 +158,8 @@ def _cua_permission_mode(session_id: str) -> str:
return configured
def _new_backend(permission_mode: str) -> ComputerUseBackend:
- backend_name = os.environ.get("HERMES_COMPUTER_USE_BACKEND", "cua").lower()
- if backend_name in {"cua", "cua-driver", ""}:
- from tools.computer_use.cua_backend import CuaDriverBackend
- return CuaDriverBackend(permission_mode=permission_mode)
- if backend_name != "noop":
- raise RuntimeError(f"Unknown HERMES_COMPUTER_USE_BACKEND={backend_name!r}")
- return _NoopBackend() # pragma: no cover
+ from plugins.computer_use import get_active_provider
+ return get_active_provider().create_backend(permission_mode=permission_mode)
def _install_backend(sid: str, backend: ComputerUseBackend, permission_mode: str) -> ComputerUseBackend:
"""Record a backend in the session caches (the empty session also mirrors it onto the ``_backend`` hook).
@@ -308,7 +303,7 @@ def _noop_stub(name: str, *params: str, result: Any = None):
return method
class _NoopBackend(ComputerUseBackend): # pragma: no cover
- """Test/CI stub (HERMES_COMPUTER_USE_BACKEND=noop). Records ``(name, kwargs)`` calls; returns trivial results."""
+ """Test stub (tests patch ``_new_backend`` to return it). Records ``(name, kwargs)`` calls; returns trivial results."""
def __init__(self) -> None: self.calls: List[Tuple[str, Dict[str, Any]]] = []
start = stop = lambda self: None
@@ -353,9 +348,11 @@ def handle_computer_use(args: Dict[str, Any], **kwargs) -> Any:
try:
backend = call.enter_context(_backend_for_call(session_id))
except Exception as e:
- return json.dumps({"error": f"computer_use backend unavailable: {e}",
- "hint": "If the cua-driver binary is missing, run `hermes computer-use install`. "
- "If a Python dependency is missing, the error above shows the exact install command."})
+ from plugins.computer_use import DEFAULT_BACKEND, configured_backend_name
+ hint = ({"hint": "If the cua-driver binary is missing, run `hermes computer-use install`. If a Python "
+ "dependency is missing, the error above shows the exact install command."}
+ if configured_backend_name() == DEFAULT_BACKEND else {})
+ return json.dumps({"error": f"computer_use backend unavailable: {e}", **hint})
try:
with call:
# Re-check under the dispatch lock: approval, backend start-up and lock waits above can take
@@ -947,17 +944,13 @@ def _route_capture_through_aux_vision(cap: CaptureResult, summary: str, *, visib
# ── Availability check (used by the tool registry check_fn) ─────────────────
def check_computer_use_requirements() -> bool:
- """macOS/Windows/Linux + cua-driver binary (or env override). `hermes computer-use doctor` names blocked checks."""
- if sys.platform not in ("darwin", "win32", "linux"):
- return False
- from tools.computer_use.cua_backend_driver import cua_driver_binary_available
- if cua_driver_binary_available():
+ """The selected ``computer_use.backend``'s ``is_available()``. An unregistered name stays True so the call
+ surfaces the "not registered (available: ...)" error instead of the tool silently vanishing."""
+ from plugins.computer_use import get_active_provider
+ try:
+ return get_active_provider().is_available()
+ except LookupError:
return True
- # No host driver: the tool is still real when the desktop is placed inside a terminal backend whose image
- # carries cua-driver (nousresearch/hermes-sandbox:desktop). Placement is config; the binary is probed lazily
- # at first use, so this stays a cheap check_fn.
- from tools.bot_desktop import placement
- return placement.resolve().where == placement.TERMINAL
def get_computer_use_schema() -> Dict[str, Any]:
from tools.computer_use.schema import COMPUTER_USE_SCHEMA
diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.md
index c3c168735e7..57794fd5e9d 100644
--- a/website/docs/developer-guide/plugins/index.md
+++ b/website/docs/developer-guide/plugins/index.md
@@ -25,6 +25,7 @@ Hermes has several distinct pluggable interfaces — some use Python `register_*
| A **video-generation backend** | [Video Generation Provider Plugins](../video-gen-provider-plugin.md) |
| A **web-search / extract backend** | [Web Search Provider Plugins](../web-search-provider-plugin.md) |
| A **cloud browser backend** (Browserbase-style CDP session provider) | [Browser Provider Plugins](../browser-provider-plugin.md) |
+| A **computer-use driver** (desktop control behind the `computer_use` tool) | [Computer-use backend plugins](#computer-use-backend-plugins) — `ctx.register_computer_use_provider()` |
| A **secret-manager backend** (vault / password manager / OS keystore) | [Secret Source Plugins](../secret-source-plugin.md) |
| A **dashboard OIDC/auth provider** | [Web Dashboard — custom providers](../../user-guide/features/web-dashboard.md#custom-providers) — `ctx.register_dashboard_auth_provider()` |
| A **TTS backend** (any CLI — Piper, VoxCPM, Kokoro, voice cloning, …) | [TTS custom command providers](../../user-guide/features/tts.md#custom-command-providers) — config-driven, no Python needed |
@@ -1841,6 +1842,90 @@ description: Custom image generation backend
**Reference examples:** `plugins/image_gen/openai/` (DALL-E / GPT-Image via OpenAI SDK), `plugins/image_gen/openai-codex/`, `plugins/image_gen/xai/` (Grok image gen).
+### Computer-use backend plugins
+
+The `computer_use` tool talks to exactly one **driver** through the `ComputerUseBackend` ABC
+(`tools/computer_use/backend.py`). `computer_use.backend` in `config.yaml` picks it; the default is the
+built-in cua-driver, which ships as an ordinary provider at `plugins/computer_use/cua/`. Another driver
+is a provider plugin in `~/.hermes/plugins/<name>/` whose `register(ctx)` calls
+`ctx.register_computer_use_provider()`. The directory name is the value you put in `computer_use.backend`.
+Computer-use providers are single-select, like memory providers and context engines:
+
+```python
+# ~/.hermes/plugins/my-driver/__init__.py
+from tools.computer_use.backend import (
+ ActionResult, CaptureResult, ComputerUseBackend, ComputerUseProvider,
+)
+
+class MyBackend(ComputerUseBackend):
+ def start(self): ... # open the driver session
+ def stop(self): ... # tear it down (also called at exit)
+ def is_available(self): return True
+ def capture(self, mode="som", app=None, pid=None, window_id=None):
+ return CaptureResult(mode=mode, width=1920, height=1080, png_b64=...)
+ def click(self, **kw): return ActionResult(ok=True, action="click")
+ def drag(self, **kw): return ActionResult(ok=True, action="drag")
+ def scroll(self, **kw): return ActionResult(ok=True, action="scroll")
+ def type_text(self, text, **kw): return ActionResult(ok=True, action="type")
+ def key(self, keys, **kw): return ActionResult(ok=True, action="key")
+ def list_apps(self): return []
+ def focus_app(self, app, raise_window=False): return ActionResult(ok=True, action="focus_app")
+ def set_value(self, value, element=None):
+ # A driver that can't do an action says so per call; the tool schema never changes.
+ return ActionResult(ok=False, action="set_value", code="unsupported_action",
+ message="my-driver has no accessibility value setter")
+
+class MyDriverProvider(ComputerUseProvider):
+ name = "my-driver"
+ display_name = "My driver"
+
+ def create_backend(self, *, permission_mode):
+ return MyBackend() # permission_mode: standard | bounded | unrestricted
+
+ def is_available(self): # gates the tool; cheap, no network
+ return True
+
+ def doctor(self): # optional: `hermes computer-use doctor`
+ print("my-driver: ok")
+ return 0
+
+def register(ctx):
+ ctx.register_computer_use_provider(MyDriverProvider())
+```
+
+```yaml
+# ~/.hermes/plugins/my-driver/plugin.yaml
+name: my-driver
+version: 1.0.0
+description: Alternative computer-use driver # shown in the picker
+```
+
+Select it in `hermes tools` → Computer Use (installed providers are listed under cua-driver, in the
+CLI and in the Desktop toolset panel), or set it directly. No `plugins.enabled` entry is needed:
+
+```yaml
+# config.yaml
+computer_use:
+ backend: my-driver # default: cua
+```
+
+Rules:
+
+- **One provider is active at a time.** Only the selected one is imported and instantiated. Installed
+ providers that aren't selected stay on disk and are only listed (from `plugin.yaml`) as options. A
+ provider never activates itself.
+- **Selection is per profile and read when a session starts its driver.** If the configured name
+ doesn't resolve, the call fails with an error naming it and the installed providers. Hermes never
+ falls back to another driver.
+- **The model-facing schema is the same for every provider**, so the prompt cache survives a driver
+ swap. Report gaps per action with `ActionResult(ok=False, code="unsupported_action", ...)`.
+- Approval gating, the Bot Desktop lease, screenshot dedup, element caps and vision routing all run
+ in the tool, above the backend. The backend only drives the screen.
+- `hermes computer-use status`/`doctor`/`permissions` run cua-driver checks only when `cua` is
+ selected. For any other provider they report its `is_available()` and run its `doctor()` if it has one.
+- Providers return live driver sessions, so they load in-process only. Under
+ `plugins.isolation: host`, a user provider is refused and the call reports that it could not be loaded.
+
## Non-Python extension surfaces
Hermes also accepts extensions that aren't Python plugins at all. These are shown in the [Pluggable interfaces table](../../user-guide/features/plugins.md#pluggable-interfaces--where-to-go-for-each); the sections below sketch each authoring style briefly.
diff --git a/website/docs/user-guide/features/computer-use.md b/website/docs/user-guide/features/computer-use.md
index d8649e42a43..c1a2955e9c3 100644
--- a/website/docs/user-guide/features/computer-use.md
+++ b/website/docs/user-guide/features/computer-use.md
@@ -524,11 +524,10 @@ recipe). If the task exists but you want it gone, remove it with
from an elevated shell — Hermes does not re-register it once
`computer_use.autostart` is false.
-Swap the backend entirely (for testing):
-
-```
-HERMES_COMPUTER_USE_BACKEND=noop # records calls, no side effects
-```
+Swap the driver entirely: `computer_use.backend` in `config.yaml` names the one
+active provider (`cua`, the default, or an installed provider plugin; see
+[computer-use backend plugins](../../developer-guide/plugins/index.md#computer-use-backend-plugins)).
+`hermes tools` → Computer Use lists every installed provider.
### Telemetry
diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.md
index 1e37f545107..b413655aa76 100644
--- a/website/docs/user-guide/features/plugins.md
+++ b/website/docs/user-guide/features/plugins.md
@@ -113,6 +113,7 @@ Every `ctx.*` API below is available inside a plugin's `register(ctx)` function.
| Register a video-generation backend | `ctx.register_video_gen_provider(provider)` — see [Video Generation Provider Plugins](../../developer-guide/video-gen-provider-plugin.md) |
| Register a context-compression engine | `ctx.register_context_engine(engine)` — see [Context Engine Plugins](../../developer-guide/context-engine-plugin.md) |
| Register a terminal execution backend (cloud sandbox) | `ctx.register_terminal_environment_provider(provider)` — see [Terminal Environment Plugins](../../developer-guide/terminal-environment-plugin.md) |
+| Register a computer-use driver | `ctx.register_computer_use_provider(provider)` — selected by `computer_use.backend`; see [Computer-use backend plugins](../../developer-guide/plugins/index.md#computer-use-backend-plugins) |
| Route human approval prompts | `ctx.register_approval_transport(name, present_fn)` — see [Approval transports](#approval-transports) |
| Register a memory backend | Subclass `MemoryProvider` in `plugins/memory/<name>/__init__.py` — see [Memory Provider Plugins](../../developer-guide/memory-provider-plugin.md) (uses a separate discovery system) |
| Run a host-owned LLM call | `ctx.llm.complete(...)` / `ctx.llm.complete_structured(...)` — borrow the user's active model + auth for a one-shot completion with optional JSON schema validation. See [Plugin LLM Access](../../developer-guide/plugin-llm-access.md) |
@@ -360,6 +361,7 @@ The table above shows the four plugin categories, but within "General plugins" t
| A **context-compression strategy** | Context-engine plugin — `ctx.register_context_engine()` | [Context Engine Plugins](../../developer-guide/context-engine-plugin.md) |
| An **image-generation backend** (DALL·E, SDXL, …) | Backend plugin — `ctx.register_image_gen_provider()` | [Image Generation Provider Plugins](../../developer-guide/image-gen-provider-plugin.md) |
| A **video-generation backend** (Veo, Kling, Pixverse, Grok-Imagine, Runway, …) | Backend plugin — `ctx.register_video_gen_provider()` | [Video Generation Provider Plugins](../../developer-guide/video-gen-provider-plugin.md) |
+| A **computer-use driver** (desktop control behind the `computer_use` tool) | Single-select provider plugin — `ctx.register_computer_use_provider()`, selected by `computer_use.backend` | [Computer-use backend plugins](../../developer-guide/plugins/index.md#computer-use-backend-plugins) |
| A **TTS backend** (any CLI — Piper, VoxCPM, Kokoro, xtts, voice-cloning scripts, …) | Config-driven (recommended) — declare under `tts.providers.<name>` with `type: command` in `config.yaml`. OR Python backend plugin — `ctx.register_tts_provider()` for Python-SDK / streaming engines that need more than a shell template. | [TTS Setup](./tts.md#custom-command-providers) · [Python plugin guide](./tts.md#python-plugin-providers) |
| An **STT backend** (any CLI — whisper.cpp, custom whisper binary, local ASR CLI) | Config-driven (recommended) — declare under `stt.providers.<name>` with `type: command` in `config.yaml`, or set `HERMES_LOCAL_STT_COMMAND` for the legacy single-command escape hatch. OR Python backend plugin — `ctx.register_transcription_provider()` for Python-SDK engines (OpenRouter, SenseAudio, Gemini-STT, etc.). | [STT Setup](./tts.md#stt-custom-command-providers) · [Python plugin guide](./tts.md#python-plugin-providers-stt) |
| **External tools via MCP** (filesystem, GitHub, Linear, Notion, any MCP server) | Config-driven — declare `mcp_servers.<name>` with `command:` / `url:` in `config.yaml`. Hermes auto-discovers the server's tools and registers them alongside built-ins. | [MCP](./mcp.md) |
diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/computer-use.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/computer-use.md
index ac979fb145d..accbeee0033 100644
--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/computer-use.md
+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/computer-use.md
@@ -121,11 +121,8 @@ Hermes 应用多层防护机制:
HERMES_CUA_DRIVER_CMD=/opt/homebrew/bin/cua-driver
```
-完全替换后端(用于测试):
-
-```
-HERMES_COMPUTER_USE_BACKEND=noop # records calls, no side effects
-```
+完全替换驱动:在 `config.yaml` 中用 `computer_use.backend` 指定后端(默认 `cua`,或已安装的 provider 插件目录名)。
+`hermes tools` → Computer Use 会列出所有已安装的后端。
### Windows 自动启动(可选)