The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(plugins): hosted providers keep their declared types across the plugin-host wire
Teknium808eaf32f91a
diff --git a/agent/context_references.py b/agent/context_references.pyindex 825f9fb712a..0d38a7a62b9 100644--- a/agent/context_references.py+++ b/agent/context_references.py@@ -30,15 +30,17 @@ BUILTIN_PREFIXES = frozenset({"diff", "staged", "file", "folder", "git", "url"})_context_reference_providers: dict[str, ContextReferenceProvider] = {}+@dataclass(slots=True)class ContextCompletionItem:- """A single autocomplete result from a context reference provider."""+ """A single autocomplete result from a context reference provider (a dataclass, so it crosses+ the plugin-host wire as data)."""- __slots__ = ("display", "meta", "text")+ text: str+ display: str = ""+ meta: str = ""- def __init__(self, text: str, display: str = "", meta: str = "") -> None:- self.text = text- self.display = display or text- self.meta = meta+ def __post_init__(self) -> None:+ self.display = self.display or self.textclass ContextReferenceProvider(ABC):diff --git a/hermes_cli/plugin_host.py b/hermes_cli/plugin_host.pyindex 0c0123914b0..5ba92a76541 100644--- a/hermes_cli/plugin_host.py+++ b/hermes_cli/plugin_host.py@@ -37,7 +37,8 @@ from pathlib import Pathfrom typing import Any, Callable, Dict, Optionalfrom hermes_cli.plugin_host_wire import (- Channel, PluginHostUnavailable, PluginHostUnsupported, decode, encode, signature_from,+ Channel, Opaque, PluginHostUnavailable, PluginHostUnsupported, declared_return, decode, encode, restore,+ signature_from,)logger = logging.getLogger("hermes_cli.plugins")@@ -313,7 +314,8 @@ class PluginHost:# -- parent -> host -----------------------------------------------------------------------------def _call(self, method: str, params: dict[str, Any], *, generation: Optional[int] = None,- timeout: Optional[float] = None) -> Any:+ timeout: Optional[float] = None, returns: Any = None) -> Any:+ """``returns`` is the type a core ABC declares for the result; the reply is rebuilt as it."""channel = self._channeltry:if channel is None:@@ -323,7 +325,8 @@ class PluginHost:if self._releases:released, self._releases = self._releases, []channel.call("release", {"refs": released})- return decode(channel.call(method, params, timeout=timeout), self._resolve_ref)+ resolve = functools.partial(self._resolve_result_ref, base=_host_object_base(returns))+ return restore(decode(channel.call(method, params, timeout=timeout), resolve), returns)except PluginHostUnavailable as exc:raise PluginHostUnavailable(self._exit_reason()) from exc@@ -336,14 +339,14 @@ class PluginHost:return self._call("invoke", {"ref": ref, "args": encode(list(args)), "kwargs": encode(kwargs)},generation=generation)- def obj_invoke(self, slot: _ObjectSlot, method: str, args: tuple, kwargs: dict) -> Any:+ def obj_invoke(self, slot: _ObjectSlot, method: str, args: tuple, kwargs: dict, returns: Any = None) -> Any:ref, generation = slot.live()return self._call("obj_invoke", {"ref": ref, "method": method, "args": encode(list(args)),- "kwargs": encode(kwargs)}, generation=generation)+ "kwargs": encode(kwargs)}, generation=generation, returns=returns)- def obj_getattr(self, slot: _ObjectSlot, name: str) -> Any:+ def obj_getattr(self, slot: _ObjectSlot, name: str, returns: Any = None) -> Any:ref, generation = slot.live()- value = self._call("obj_getattr", {"ref": ref, "name": name}, generation=generation)+ value = self._call("obj_getattr", {"ref": ref, "name": name}, generation=generation, returns=returns)if isinstance(value, dict) and set(value) == {"__missing__"}:raise AttributeError(name)return value@@ -433,6 +436,14 @@ class PluginHost:return self._object_proxy(ref, base)raise PluginHostUnsupported("registration handles are owned by the plugin host")+ def _resolve_result_ref(self, ref: dict[str, Any], base: Optional[type] = None) -> Any:+ """A provider object a hosted method returned (``ContextEngine.clone_for_agent``): a proxy when+ the contract declares that provider type, otherwise a placeholder (and the host drops it)."""+ if "__object__" in ref and base is None:+ self._release(self._generation, int(ref["__object__"]))+ return Opaque(str(ref.get("type") or "object"))+ return self._resolve_ref(ref, base)+def _callable_proxy(self, ref: dict[str, Any]) -> Callable[..., Any]:ref_id, generation = int(ref["__callable__"]), self._generation@@ -462,11 +473,11 @@ class PluginHost:live = set(ref.get("live") or ())namespace: dict[str, Any] = {}for name, meta in (ref.get("methods") or {}).items():- namespace[name] = _method_proxy(host, slot, name, meta)+ namespace[name] = _method_proxy(host, slot, name, meta, declared_return(base, name))def __getattribute__(self_: Any, name: str) -> Any:if name in live:- return host.obj_getattr(slot, name)+ return host.obj_getattr(slot, name, declared_return(base, name))return object.__getattribute__(self_, name)def __getattr__(self_: Any, name: str) -> Any:@@ -557,12 +568,13 @@ def _run_on_gateway_loop(coro: Any) -> Any:return asyncio.run(coro)-def _method_proxy(host: PluginHost, slot: _ObjectSlot, name: str, meta: dict[str, Any]) -> Callable[..., Any]:+def _method_proxy(host: PluginHost, slot: _ObjectSlot, name: str, meta: dict[str, Any],+ returns: Any) -> Callable[..., Any]:async def async_method(self_: Any, *args: Any, **kwargs: Any) -> Any:- return await asyncio.to_thread(host.obj_invoke, slot, name, args, kwargs)+ return await asyncio.to_thread(host.obj_invoke, slot, name, args, kwargs, returns)def sync_method(self_: Any, *args: Any, **kwargs: Any) -> Any:- return host.obj_invoke(slot, name, args, kwargs)+ return host.obj_invoke(slot, name, args, kwargs, returns)method: Any = async_method if meta.get("async") else sync_methodmethod.__name__ = method.__qualname__ = name@@ -573,6 +585,14 @@ def _method_proxy(host: PluginHost, slot: _ObjectSlot, name: str, meta: dict[strreturn method+def _host_object_base(hint: Any) -> Optional[type]:+ """``hint`` when it is a provider ABC a hosted object may stand in for (``HOST_OBJECT_BASES``)."""+ from hermes_cli.plugin_isolation import HOST_OBJECT_BASES+ if isinstance(hint, type) and f"{hint.__module__}:{hint.__qualname__}" in HOST_OBJECT_BASES.values():+ return hint+ return None++def _import_ref(ref: str) -> type:module, attr = ref.split(":")return getattr(importlib.import_module(module), attr)diff --git a/hermes_cli/plugin_host_child.py b/hermes_cli/plugin_host_child.pyindex 6426fdbcc07..f17e153c17d 100644--- a/hermes_cli/plugin_host_child.py+++ b/hermes_cli/plugin_host_child.py@@ -29,8 +29,8 @@ from pathlib import Pathfrom typing import Any, Callable, Dict, List, Optionalfrom hermes_cli.plugin_host_wire import (- Channel, Opaque, PROTOCOL_VERSION, PluginHostUnsupported, bind_serving_request, decode, describe_signature,- encode, is_async_callable, serving_request,+ Channel, Opaque, PROTOCOL_VERSION, PluginHostUnsupported, bind_serving_request, declared_member, decode,+ describe_signature, encode, is_async_callable, restore_arguments, serving_request,)logger = logging.getLogger("hermes_cli.plugin_host_child")@@ -230,7 +230,12 @@ class HostRuntime:return resultdef _encode_result(self, plugin_key: str, value: Any) -> Any:- return encode(value, functools.partial(self.ref_for, plugin_key, allow_objects=False))+ def refs(obj: Any) -> Optional[dict]:+ if _provider_base(obj) is not None: # e.g. the engine ``clone_for_agent`` returns+ return self._describe_object(plugin_key, obj)+ return self.ref_for(plugin_key, obj, allow_objects=False)++ return encode(value, refs)def _decode_args(self, params: dict[str, Any]):return decode(params.get("args") or [], None), decode(params.get("kwargs") or {}, None)@@ -348,6 +353,9 @@ class HostRuntime:if method.startswith("_"):raise AttributeError(method)args, kwargs = self._decode_args(params)+ base = _provider_base(obj)+ if base is not None: # the ABC's annotations say what Hermes passed (``home_path: Path``)+ args, kwargs = restore_arguments(declared_member(base, method), args, kwargs)return self._encode_result(self.owners.get(ref, ""), self._run(getattr(obj, method)(*args, **kwargs)))def op_obj_getattr(self, params: dict[str, Any]) -> Any:@@ -443,6 +451,18 @@ def _import_base(ref: str) -> type:return getattr(importlib.import_module(module), attr)+def _provider_base(value: Any) -> Optional[type]:+ """The provider ABC (``HOST_OBJECT_BASES``) ``value`` implements. Only an already-imported base+ can match: a plugin object subclassing it imported it."""+ from hermes_cli.plugin_isolation import HOST_OBJECT_BASES+ for ref in HOST_OBJECT_BASES.values():+ module, attr = ref.split(":")+ base = getattr(sys.modules.get(module), attr, None)+ if isinstance(base, type) and isinstance(value, base):+ return base+ return None++def _is_provider_object(value: Any) -> bool:"""A plugin-defined instance (provider/engine), as opposed to a function or bound method."""return not isinstance(value, (types.FunctionType, types.MethodType, types.BuiltinFunctionType,diff --git a/hermes_cli/plugin_host_wire.py b/hermes_cli/plugin_host_wire.pyindex ff336a76e9c..dd1125dcbb1 100644--- a/hermes_cli/plugin_host_wire.py+++ b/hermes_cli/plugin_host_wire.py@@ -11,7 +11,8 @@ reader thread's bare context.Values cross as JSON. Callables and provider objects travel as references the other side turnsback into proxies; dataclasses become :class:`Record` (dict + attribute access); anything elsebecomes an :class:`Opaque` placeholder naming its type, so a plugin that touches a live handle it-cannot have fails with a readable error rather than a pickle surprise.+cannot have fails with a readable error rather than a pickle surprise. Where a core ABC declares+the type (``SecretSource.fetch -> FetchResult``, ``home_path: Path``), :func:`restore` rebuilds it."""from __future__ import annotations@@ -20,10 +21,15 @@ import base64import contextvarsimport dataclassesimport enum+import functools+import inspectimport itertoolsimport jsonimport loggingimport threading+import types+import typing+from collections import abcfrom concurrent.futures import Futurefrom pathlib import PurePathfrom typing import Any, BinaryIO, Callable, Dict, Optional@@ -149,8 +155,86 @@ def decode(value: Any, resolve: Optional[Callable[[dict], Any]] = None) -> Any:return {k: decode(v, resolve) for k, v in value.items()}+def restore(value: Any, hint: Any) -> Any:+ """``value`` as decoded, rebuilt as the type ``hint`` declares: JSON carries dicts, lists and+ scalars, so a ``FetchResult`` arrives as a :class:`Record`, a ``Path`` as ``str``, an enum as its+ value, a ``frozenset`` as a list. A value that does not fit stays as decoded, so the consumer's+ own type check still names it."""+ if value is None or hint is None or hint is Any:+ return value+ origin = typing.get_origin(hint)+ if origin in (typing.Union, types.UnionType):+ arms = [arm for arm in typing.get_args(hint) if arm is not type(None)]+ return restore(value, arms[0]) if len(arms) == 1 else value+ if origin is not None:+ return _restore_container(value, origin, typing.get_args(hint))+ if not isinstance(hint, type) or isinstance(value, hint):+ return value+ try:+ if dataclasses.is_dataclass(hint) and isinstance(value, Record):+ hints = typing.get_type_hints(hint)+ return hint(**{f.name: restore(value[f.name], hints.get(f.name))+ for f in dataclasses.fields(hint) if f.init and f.name in value})+ if issubclass(hint, (enum.Enum, PurePath)):+ return hint(value)+ except (TypeError, ValueError, NameError):+ pass+ return value+++_SEQUENCES: dict[Any, type] = {list: list, tuple: tuple, set: set, frozenset: frozenset,+ abc.Sequence: list, abc.Set: frozenset, abc.Iterable: list}+++def _restore_container(value: Any, origin: Any, args: tuple) -> Any:+ if origin in (dict, abc.Mapping) and isinstance(value, dict):+ key_hint, item_hint = args if len(args) == 2 else (None, None)+ return {restore(k, key_hint): restore(v, item_hint) for k, v in value.items()}+ kind = _SEQUENCES.get(origin)+ if kind is None or not isinstance(value, list):+ return value+ if kind is tuple and args and args[-1] is not Ellipsis: # tuple[str, str]: one hint per slot+ return tuple(restore(v, a) for v, a in zip(value, args)) if len(args) == len(value) else tuple(value)+ return kind(restore(v, args[0] if args else None) for v in value)+++def declared_member(cls: type, name: str) -> Optional[Callable[..., Any]]:+ """The function ``cls`` declares for method or property ``name`` (its annotations are the contract)."""+ raw = inspect.getattr_static(cls, name, None)+ if isinstance(raw, property):+ raw = raw.fget+ return raw if inspect.isfunction(raw) else None++[email protected]_cache(maxsize=512)+def declared_return(cls: type, name: str) -> Any:+ """Return type ``cls`` declares for method/property ``name``; None when undeclared or unresolvable."""+ fn = declared_member(cls, name)+ try:+ return typing.get_type_hints(fn).get("return") if fn is not None else None+ except (NameError, TypeError, AttributeError):+ return None+++def restore_arguments(fn: Optional[Callable[..., Any]], args: list, kwargs: dict) -> tuple[list, dict]:+ """``args``/``kwargs`` for a call to the unbound method ``fn``, each rebuilt as its declared+ parameter type; unchanged when the call does not bind to ``fn``'s signature."""+ if fn is None:+ return args, kwargs+ try:+ hints = typing.get_type_hints(fn)+ signature = inspect.signature(fn)+ bound = signature.bind(None, *args, **kwargs) # None stands in for ``self``+ except (NameError, TypeError, ValueError, AttributeError):+ return args, kwargs+ variadic = (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)+ for name, value in bound.arguments.items():+ if signature.parameters[name].kind not in variadic:+ bound.arguments[name] = restore(value, hints.get(name))+ return list(bound.args[1:]), dict(bound.kwargs)++def is_async_callable(fn: Any) -> bool:- import inspecttarget = getattr(fn, "__func__", fn)return inspect.iscoroutinefunction(target) or inspect.iscoroutinefunction(getattr(fn, "__call__", None)) # noqa: B004 -- __call__ feeds iscoroutinefunction (async instances), not a callability test@@ -158,7 +242,6 @@ def is_async_callable(fn: Any) -> bool:def describe_signature(fn: Any) -> Optional[list]:"""``[[name, kind, has_default], ...]`` so the peer's proxy presents the same parameters (hookdispatch passes only the kwargs a callback declares)."""- import inspecttry:sig = inspect.signature(fn)except (TypeError, ValueError):@@ -167,7 +250,6 @@ def describe_signature(fn: Any) -> Optional[list]:def signature_from(spec: Optional[list]):- import inspectif not spec:return Nonetry:diff --git a/plugins/AGENTS.md b/plugins/AGENTS.mdindex c346225656b..34bfd928e72 100644--- a/plugins/AGENTS.md+++ b/plugins/AGENTS.md@@ -125,6 +125,10 @@ Invariants:adapter objects). The runtime refusal and the static audit (`plugin_isolation_audit.py`, shown by`hermes plugins validate/show`) both read it; `evals/plugin_isolation/audit_catalog.py` re-measuresthe catalog.+- **Values keep the provider ABC's declared types across the wire:** JSON carries dicts, lists and+ scalars, so `plugin_host_wire.restore` rebuilds arguments (child) and results (parent) from the ABC's+ annotations (`FetchResult`, `Path`, enums, a returned engine as a proxy). A value a core consumer+ type-checks must be a dataclass annotated on the ABC method, or it arrives as `Record`/`Opaque`.- **A host never spawns a host** (`HERMES_PLUGIN_HOST_PROCESS=1` makes `isolation_mode()` in-processthere) and must not start while a module import holds its lock (model-provider discovery is theknown case).diff --git a/tests/hermes_cli/test_plugin_host_return_types.py b/tests/hermes_cli/test_plugin_host_return_types.pynew file mode 100644index 00000000000..2c2a8813884--- /dev/null+++ b/tests/hermes_cli/test_plugin_host_return_types.py@@ -0,0 +1,160 @@+"""plugins.isolation: host — values a hosted provider returns reach core as the types its ABC promises.++Each test loads a real plugin into a real host subprocess and drives the core consumer, so a+return value that crosses the wire as a generic placeholder fails here the way it fails users.+"""++import os+import sys++import hermes_yaml as yaml+import pytest++from hermes_cli import plugins as plugins_mod+from hermes_cli.plugins import PluginManager+++def _home_with_plugin(tmp_path, monkeypatch, name: str, body: str):+ home = tmp_path / ".hermes"+ plugin_dir = home / "plugins" / name+ plugin_dir.mkdir(parents=True)+ (plugin_dir / "plugin.yaml").write_text(yaml.safe_dump({"name": name, "version": "1.0"}), encoding="utf-8")+ (plugin_dir / "__init__.py").write_text(body, encoding="utf-8")+ (home / "config.yaml").write_text(yaml.safe_dump(+ {"plugins": {"enabled": [name], "isolation": "host"}}), encoding="utf-8")+ empty_bundled = tmp_path / "bundled"+ empty_bundled.mkdir()+ monkeypatch.setenv("HOME", str(tmp_path / "os-home"))+ monkeypatch.setenv("HERMES_HOME", str(home))+ monkeypatch.setattr(plugins_mod, "get_bundled_plugins_dir", lambda: empty_bundled)+ return home+++def _load(name: str) -> PluginManager:+ manager = PluginManager()+ manager.discover_and_load()+ assert manager._plugins[name].error is None+ assert not any(name in module for module in sys.modules) # the plugin ran only in the host+ return manager+++def _shutdown(manager: PluginManager) -> None:+ manager.unload()+ manager._plugin_host().shutdown()+++SECRET_SOURCE_PLUGIN = '''+import os+from agent.secret_sources.base import ErrorKind, FetchResult, SecretSource++class DummyVault(SecretSource):+ name = "hostvault"+ label = "Host vault"++ def fetch(self, cfg, home_path):+ if cfg.get("mode") == "locked":+ return FetchResult().fail("vault is locked", ErrorKind.AUTH_FAILED)+ return FetchResult(secrets={"HOSTED_DUMMY_TOKEN": f"dummy-from-{os.getpid()}"},+ warnings=["dummy warning"], binary_path=home_path / "bin" / "vault")++def register(ctx):+ ctx.register_secret_source(DummyVault())+'''++[email protected]("any") # the host is a child process: its env/home resolution is per-OS+def test_hosted_secret_source_secrets_are_applied(tmp_path, monkeypatch):+ from agent.secret_sources.base import ErrorKind+ from agent.secret_sources.registry import apply_all++ home = _home_with_plugin(tmp_path, monkeypatch, "hostvault", SECRET_SOURCE_PLUGIN)+ manager = _load("hostvault")+ try:+ target: dict[str, str] = {}+ report = apply_all({"hostvault": {"enabled": True}}, home, environ=target)+ (source_report,) = report.sources+ assert source_report.result.ok, source_report.result.error+ assert source_report.applied == ["HOSTED_DUMMY_TOKEN"]+ value = target["HOSTED_DUMMY_TOKEN"]+ assert value.startswith("dummy-from-") and value != f"dummy-from-{os.getpid()}"+ assert source_report.result.warnings == ["dummy warning"]+ assert source_report.result.binary_path == home / "bin" / "vault"++ # A failure keeps its kind, which drives stale-cache fallback and remediation text.+ locked: dict[str, str] = {}+ report = apply_all({"hostvault": {"enabled": True, "mode": "locked"}}, home, environ=locked)+ (source_report,) = report.sources+ assert source_report.result.error == "vault is locked"+ assert source_report.result.error_kind is ErrorKind.AUTH_FAILED+ assert locked == {}+ finally:+ _shutdown(manager)+++CONTEXT_REFERENCE_PLUGIN = '''+from agent.context_references import ContextCompletionItem, ContextReferenceProvider++class Tickets(ContextReferenceProvider):+ prefix = "hostticket"+ description = "tickets"++ async def autocomplete(self, query, *, limit=10):+ return [ContextCompletionItem(text=f"{query}-1", meta="open"), ContextCompletionItem(text=f"{query}-2")]++ async def expand(self, target):+ return f"ticket {target}"++def register(ctx):+ ctx.register_context_reference(Tickets())+'''++[email protected]("any")+def test_hosted_context_reference_autocomplete_returns_items(tmp_path, monkeypatch):+ from tui_gateway.methods_complete import _plugin_reference_items++ _home_with_plugin(tmp_path, monkeypatch, "hostticket", CONTEXT_REFERENCE_PLUGIN)+ manager = _load("hostticket")+ try:+ assert _plugin_reference_items("hostticket", "bug") == [+ {"text": "@hostticket:bug-1", "display": "bug-1", "meta": "open"},+ {"text": "@hostticket:bug-2", "display": "bug-2", "meta": ""},+ ]+ finally:+ _shutdown(manager)+++CONTEXT_ENGINE_PLUGIN = '''+from agent.context_engine import ContextEngine++class Ledger(ContextEngine):+ @property+ def name(self):+ return "hostledger"+ def update_from_response(self, usage):+ self.last_prompt_tokens = usage["prompt_tokens"]+ def should_compress(self, prompt_tokens=None):+ return False+ def compress(self, messages, current_tokens=None, **kw):+ return messages++def register(ctx):+ ctx.register_context_engine(Ledger())+'''++[email protected]("any")+def test_hosted_context_engine_clone_is_an_independent_engine(tmp_path, monkeypatch):+ from agent.context_engine import ContextEngine++ _home_with_plugin(tmp_path, monkeypatch, "hostledger", CONTEXT_ENGINE_PLUGIN)+ manager = _load("hostledger")+ try:+ shared = manager._context_engine+ clone = shared.clone_for_agent() # what every AIAgent does with a plugin engine+ assert isinstance(clone, ContextEngine) and clone.name == "hostledger"+ clone.update_from_response({"prompt_tokens": 1234})+ assert clone.last_prompt_tokens == 1234+ assert shared.last_prompt_tokens == 0 # the agent's budget state is its own+ finally:+ _shutdown(manager)diff --git a/website/docs/user-guide/features/plugins.md b/website/docs/user-guide/features/plugins.mdindex 759e8687d52..880521209b0 100644--- a/website/docs/user-guide/features/plugins.md+++ b/website/docs/user-guide/features/plugins.md@@ -868,8 +868,9 @@ plugins:Plugins do not change. They receive the same `ctx` and register tools, hooks, slash commands, skills andprovider objects (image/video generation, web search, browser, TTS/STT, memory, context engines,-model-provider profiles) exactly as before; Hermes registers matching entries on its side that call into-the host. Dashboard plugin APIs are served by the host too. Bundled plugins keep running in-process.+secret sources, `@` context references, model-provider profiles) exactly as before; Hermes registers+matching entries on its side that call into the host, and values cross as the types the provider base+class declares (a secret source's `fetch()` gets a `Path` and returns a `FetchResult`). Dashboard plugin APIs are served by the host too. Bundled plugins keep running in-process.In-process dashboard API handlers share the gateway's event loop, so they must not block it (see[Don't block the event loop](extending-the-dashboard.md#dont-block-the-event-loop)).