The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(tools): support scoped browser vault backend plugins
Jess Sullivand4e19b983913
diff --git a/agent/vault_backend_registry.py b/agent/vault_backend_registry.pynew file mode 100644index 00000000000..5f993518d31--- /dev/null+++ b/agent/vault_backend_registry.py@@ -0,0 +1,27 @@+"""Profile-scoped, leased browser-vault backends for trusted in-process plugins."""+import logging+import re+from agent.provider_registry import ProviderRegistry+from agent.vault_backends.base import LoginBackend++_registry = ProviderRegistry(label="Login backend", provider_cls=LoginBackend,+ logger=logging.getLogger(__name__))+_registry.export(globals())+++def register_provider(provider, *, scope=None):+ if not isinstance(provider, LoginBackend):+ raise ValueError("login backend must subclass LoginBackend")+ name, prefix = getattr(provider, "name", ""), getattr(provider, "prefix", "")+ if not isinstance(name, str) or not re.fullmatch(r"[a-z][a-z0-9_]*", name):+ raise ValueError("invalid login backend name")+ if not isinstance(prefix, str) or not re.fullmatch(r"[a-z][a-z0-9_]*:", prefix):+ raise ValueError("invalid login backend prefix")+ if name in {"local", "onepassword", "bitwarden"} or prefix in {"op:", "bw:"}:+ raise ValueError("builtin login backend namespace is reserved")+ for existing in _registry.list_providers(scope=scope):+ if existing.name == name and existing.prefix != prefix:+ raise ValueError("login backend prefix cannot change during replacement")+ if existing.name != name and existing.prefix == prefix:+ raise ValueError("login backend prefix is already registered")+ _registry.register(provider, scope=scope)diff --git a/agent/vault_backends/base.py b/agent/vault_backends/base.pyindex 6e7c1f5bab1..2e13412ee03 100644--- a/agent/vault_backends/base.py+++ b/agent/vault_backends/base.py@@ -10,6 +10,7 @@ namespaced by ``prefix`` so ``backend_for_handle`` needs no lookup table.from __future__ import annotationsimport subprocess+from contextlib import nullcontextfrom abc import ABC, abstractmethodfrom pathlib import Pathfrom typing import Dict, List, Optional, Sequence@@ -37,6 +38,10 @@ class LoginBackend(ABC):def is_unlocked(self) -> bool:return True+ def fill_context(self):+ """Optional profile-exclusive context covering origin check through CDP fill."""+ return nullcontext()+@abstractmethoddef list_items(self) -> list[VaultItemMeta]:"""Metadata only. Locked external backends return [] (the agent sees a lock hint instead)."""@@ -132,6 +137,11 @@ def enabled_backends() -> list[LoginBackend]:if is_enabled(cls.name):section = cfg.get(cls.name) or {}out.append(cls(section if isinstance(section, dict) else {}))+ from agent.vault_backend_registry import list_providers+ for backend in list_providers():+ section = cfg.get(backend.name)+ if isinstance(section, dict) and section.get("enabled") is True:+ out.append(backend)return outdiff --git a/hermes_cli/plugin_isolation.py b/hermes_cli/plugin_isolation.pyindex 1aa406e9972..2582bee07c1 100644--- a/hermes_cli/plugin_isolation.py+++ b/hermes_cli/plugin_isolation.py@@ -33,6 +33,7 @@ _ISOLATION_MODES = frozenset({ISOLATION_IN_PROCESS, ISOLATION_HOST})# raw platform SDK clients, argparse parsers, adapter classes bound to the gateway's event loop, the# launch-scope dashboard auth registry. A plugin calling one of these runs only in-process.HOST_UNSUPPORTED_CTX_METHODS: dict[str, str] = {+ "register_login_backend": "browser-vault fills hold a server-local context manager","register_platform": "platform adapters run on the gateway's event loop with native SDK clients","register_platform_handler": "the handler factory receives the platform's native SDK client","register_telegram_handler": "the handler factory receives the native Telegram Application",diff --git a/hermes_cli/plugins_registrars.py b/hermes_cli/plugins_registrars.pyindex 3ee9099f672..bb30a0b6871 100644--- a/hermes_cli/plugins_registrars.py+++ b/hermes_cli/plugins_registrars.py@@ -13,6 +13,12 @@ from __future__ import annotationsfrom typing import Any, Callable, Optional_SCOPED_PROVIDER_REGISTRARS: tuple[tuple[str, str, str, str, str, str, dict[str, Any]], ...] = (+ ("register_login_backend", "login_backend", "agent.vault_backend_registry",+ "agent.vault_backends.base:LoginBackend", "login backend",+ "Register a trusted in-process browser-vault LoginBackend; explicit vault.<name>.enabled "+ "is required. Registration is profile-scoped and removed on plugin unload. "+ "Backend instances must read active-profile configuration lazily.",+ {"normalize": None, "reject_message": "Plugin '%s' login backend rejected: %s"}),("register_image_gen_provider", "image_gen_provider", "agent.image_gen_registry","agent.image_gen_provider:ImageGenProvider", "image_gen provider","Register an :class:`agent.image_gen_provider.ImageGenProvider`; "diff --git a/tests/agent/test_vault_backend_registry.py b/tests/agent/test_vault_backend_registry.pynew file mode 100644index 00000000000..86a9bdbb99a--- /dev/null+++ b/tests/agent/test_vault_backend_registry.py@@ -0,0 +1,123 @@+"""Plugin vault registration uses existing scoped leases; no browser/secrets."""+from unittest.mock import patch+from textwrap import dedent+import pytest+from agent.vault_backends.base import LoginBackend, backend_for_handle+from agent import vault_backend_registry as registry+++class Example(LoginBackend):+ name, prefix, display_name = "example", "example:", "Example"+ def list_items(self):+ return []+ def get_meta(self, handle):+ return None+ def resolve_password(self, handle):+ raise AssertionError("registry tests must never resolve passwords")+++def test_registration_requires_explicit_profile_enablement():+ with patch.dict(registry._providers, clear=True), \+ patch("agent.vault_backends.base.is_enabled", return_value=False), \+ patch("agent.vault_backends.base._cfg", return_value={}) as cfg:+ registry.register_provider(Example())+ assert backend_for_handle("example:one") is None+ cfg.return_value = {"example": {"enabled": True}}+ assert backend_for_handle("example:one").name == "example"+++def test_builtin_names_and_handle_prefixes_are_reserved():+ class Reserved(Example):+ name = "local"+ with pytest.raises(ValueError):+ registry.register_provider(Reserved())+ class ReservedPrefix(Example):+ prefix = "op:"+ with pytest.raises(ValueError):+ registry.register_provider(ReservedPrefix())+++def test_reload_cannot_change_prefix_and_leave_ambiguous_restore(tmp_path):+ from hermes_cli.plugins import PluginContext, PluginManager+ from hermes_cli.plugins_manifest import PluginManifest+ scope = str(tmp_path / "home")+ context = PluginContext(PluginManifest(name="login-example"), PluginManager(scope_key=scope))+ original = Example()+ first = context.register_login_backend(original)+ class ChangedPrefix(Example):+ prefix = "changed:"+ assert context.register_login_backend(ChangedPrefix()) is None+ class Other(Example):+ name = "other"+ assert context.register_login_backend(Other()) is None+ assert registry.get_provider("example", scope=scope) is original+ first.dispose()+ assert registry.get_provider("example", scope=scope) is None+++def test_lease_reload_and_unload_do_not_cross_profiles(tmp_path):+ from hermes_cli.plugins import PluginContext, PluginManager+ from hermes_cli.plugins_manifest import PluginManifest+ first, second = str(tmp_path / "first"), str(tmp_path / "second")+ manifest = PluginManifest(name="test-vault")+ first_ctx = PluginContext(manifest, PluginManager(scope_key=first))+ second_ctx = PluginContext(manifest, PluginManager(scope_key=second))+ original, replacement, sibling = Example(), Example(), Example()+ a = first_ctx.register_login_backend(original)+ b = first_ctx.register_login_backend(replacement)+ c = second_ctx.register_login_backend(sibling)+ assert registry.get_provider("example", scope=first) is replacement+ assert registry.get_provider("example", scope=second) is sibling+ b.dispose()+ assert registry.get_provider("example", scope=first) is original+ a.dispose()+ assert registry.get_provider("example", scope=first) is None+ assert registry.get_provider("example", scope=second) is sibling+ c.dispose()+++def test_real_plugin_discovery_reload_and_disable(tmp_path, monkeypatch):+ from hermes_cli.plugins import PluginManager+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override+ home = tmp_path / "home"+ plugin = home / "plugins" / "login_example"+ plugin.mkdir(parents=True)+ (plugin / "plugin.yaml").write_text("name: login_example\n", encoding="utf-8")+ (plugin / "__init__.py").write_text(dedent('''+ from agent.vault_backends.base import LoginBackend+ class Backend(LoginBackend):+ name, prefix, display_name = "example", "example:", "Example"+ def list_items(self):+ return []+ def get_meta(self, handle):+ return None+ def resolve_password(self, handle):+ raise AssertionError("no secret reads in discovery")+ def register(ctx):+ ctx.register_login_backend(Backend())+ '''), encoding="utf-8")+ config = home / "config.yaml"+ config.write_text("plugins:\n enabled: [login_example]\nvault:\n example:\n enabled: true\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(home))+ token = set_hermes_home_override(home)+ manager = PluginManager(scope_key=str(home))+ try:+ manager.discover_and_load()+ first = backend_for_handle("example:one")+ assert first is not None+ manager.discover_and_load(force=True)+ assert backend_for_handle("example:one") is not first+ config.write_text("plugins:\n enabled: []\nvault:\n example:\n enabled: true\n", encoding="utf-8")+ manager.discover_and_load(force=True)+ assert backend_for_handle("example:one") is None+ finally:+ manager.unload()+ reset_hermes_home_override(token)+++def test_host_plugin_refuses_server_local_fill_context():+ from hermes_cli.plugin_host_child import RemotePluginContext+ from hermes_cli.plugin_host_wire import PluginHostUnsupported+ remote = RemotePluginContext(None, "example", {"ctx_methods": ["register_login_backend"]})+ with pytest.raises(PluginHostUnsupported, match="server-local"):+ remote.register_login_backend(Example())diff --git a/tools/browser_vault_context.py b/tools/browser_vault_context.pynew file mode 100644index 00000000000..da7aa4d323f--- /dev/null+++ b/tools/browser_vault_context.py@@ -0,0 +1,19 @@+"""Backend-specific trusted fill lifetime; credential exceptions never leave it."""+import json+from contextlib import nullcontext+from functools import wraps+++def with_backend_fill_context(fill):+ @wraps(fill)+ def wrapped(handle, task_id=None):+ from agent.vault_backends import backend_for_handle+ try:+ backend = backend_for_handle(handle)+ context = backend.fill_context() if backend is not None and hasattr(backend, "fill_context") else nullcontext()+ with context:+ return fill(handle, task_id, _backend=backend)+ except Exception: # health: allow BLE001 -- backend failures may contain credentials; never log exception text+ return json.dumps({"success": False, "error_type": "backend_unavailable",+ "error": "Credential backend unavailable or browser profile busy."})+ return wrappeddiff --git a/tools/browser_vault_tool.py b/tools/browser_vault_tool.pyindex 53403c0524a..3e7ba6e48a8 100644--- a/tools/browser_vault_tool.py+++ b/tools/browser_vault_tool.py@@ -415,7 +415,11 @@ def browser_vault_enter_code(handle: str = "", task_id: Optional[str] = None) ->"next": "Submit the form (many sites auto-submit when the last digit lands)."})-def browser_vault_fill(handle: str, task_id: Optional[str] = None) -> str:+from tools.browser_vault_context import with_backend_fill_context+++@with_backend_fill_context+def browser_vault_fill(handle: str, task_id: Optional[str] = None, *, _backend=None) -> str:"""Fill the current page's password field from a vault handle.Password-only: the identifier is agent-visible metadata (see@@ -438,7 +442,7 @@ def browser_vault_fill(handle: str, task_id: Optional[str] = None) -> str:from agent.vault_store import ADDRESS_FIELDS, PAYMENT_FIELDS, scrub_secret_from_texteffective_task_id = task_id or "default"- backend = backend_for_handle(handle)+ backend = _backendif backend is not None and backend.needs_unlock and not backend.is_unlocked():unlocked = json.loads(browser_vault_unlock(backend.name))if not unlocked.get("success"):diff --git a/website/docs/developer-guide/browser-vault-plugin.md b/website/docs/developer-guide/browser-vault-plugin.mdnew file mode 100644index 00000000000..66457c974c7--- /dev/null+++ b/website/docs/developer-guide/browser-vault-plugin.md@@ -0,0 +1,37 @@+---+title: Browser Vault Plugins+description: Explicit, profile-scoped login backends for trusted in-process plugins+---++Browser login backends are separate from startup provider secret sources. A+`SecretSource` registration does not make a password manager available to+`browser_vault`.++An **in-process** plugin may implement `agent.vault_backends.base.LoginBackend`+and call `ctx.register_login_backend(instance)` in `register(ctx)`. The existing+plugin registration ledger scopes it to the current home and disposes/restores+registrations on unload/reload. Host-isolated plugin RPC is not supported by+this extension because `fill_context()` is a server-local context manager.++Every custom backend requires `vault.<name>.enabled: true`; installed code is+never automatically enabled. Names must be lowercase identifiers; custom+handle prefixes use `name:` syntax. Builtin names/prefixes and another backend's+prefix cannot be claimed.++Construct the backend without fetching credentials or reading profile state.+Read the active profile's config lazily. `list_items()` and `get_meta()` return+only `VaultItemMeta` with exact HTTPS origins and opaque IDs. Passwords are+resolved only through `resolve_password()` after the existing browser origin+precheck. Exceptions must contain fixed diagnostics, never credential values or+secret-manager response bodies.++`fill_context()` defaults to a no-op. A backend may override it to lock fills+and freeze credential-reference/origin configuration for the entire operation.+This prevents reload from pairing old metadata with a newly configured secret.+The context must reset/release on failure. A fill lock does not serialize+unrelated browser navigation; applications must separately establish ownership+of their persistent browser profile.++The existing browser tool keeps its atomic in-page origin assertion, secret CDP+evaluation with no argv fallback, and egress redaction registration. A plugin+must not bypass those through a model-facing password-returning tool.