The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: plugin host review findings (async ctx, caller session, restarts, per-profile dashboard)
teknium1ad5c8e336ee8
diff --git a/hermes_cli/plugin_host.py b/hermes_cli/plugin_host.pyindex 1570cfe30e5..ed0a6adb330 100644--- a/hermes_cli/plugin_host.py+++ b/hermes_cli/plugin_host.py@@ -21,6 +21,7 @@ from __future__ import annotationsimport asyncioimport contextvars+import dataclassesimport inspectimport functoolsimport importlib@@ -31,6 +32,7 @@ import subprocessimport sysimport threadingimport time+import weakreffrom pathlib import Pathfrom typing import Any, Callable, Dict, Optional@@ -64,7 +66,11 @@ class PluginHost:self._base_context = self._build_base_context()self._loading: Optional[str] = Noneself._stopping = False- self._restarts: list = []+ self._deaths: list = []+ # Bumped per host process: a proxy made for an earlier process must not address this one+ # (object ids restart at 1, so a stale id would silently land on a different object).+ self._generation = 0+ self._releases: list = []self.info: Dict[str, Any] = {}# -- lifecycle ----------------------------------------------------------------------------------@@ -78,7 +84,9 @@ class PluginHost:and self._proc is not None and self._proc.poll() is None)def _build_base_context(self) -> contextvars.Context:- context = contextvars.copy_context()+ # A fresh context, not a copy of whichever caller created the host: requests with no+ # caller (a ``spawn_task`` loop) must not inherit that caller's session or approvals.+ context = contextvars.Context()def bind() -> None:from hermes_constants import set_hermes_home_override@@ -115,11 +123,13 @@ class PluginHost:bufsize=0)threading.Thread(target=_pump_stderr, args=(proc, self._home.name), daemon=True,name=f"plugin-host-{proc.pid}-stderr").start()+ self._generation += 1channel = Channel(proc.stdout, proc.stdin, self._handle, # type: ignore[arg-type]name=f"plugin-host[{proc.pid}]",- on_close=self._on_channel_close,+ on_close=functools.partial(self._on_channel_close, self._generation),context_for_origin=self._context_for_origin).start()self._proc, self._channel = proc, channel+ self._releases = []try:self.info = channel.call("hello", {}, timeout=_START_TIMEOUT_SECS)except Exception as exc:@@ -139,25 +149,30 @@ class PluginHost:return (f"the plugin host for this profile exited (code {code}); Hermes restarts it and reloads "f"its plugins automatically" if code is not None else "the plugin host is not running")- def _on_channel_close(self, reason: str) -> None:- if self._stopping:- return- keys, culprit = [k for k in self._contexts if k != self._loading], self._loading+ def _on_channel_close(self, generation: int, reason: str) -> None:+ if self._stopping or generation != self._generation:+ return # a deliberate shutdown, or a late close from a host already replaced+ culprit = self._loading+ keys = [k for k in self._contexts.copy() if k != culprit and k in self._manager._plugins]logger.warning("Plugin host for %s exited (%s)%s", self._home, self._exit_reason(),f" while loading plugin '{culprit}'" if culprit else "")+ now = time.monotonic()+ self._deaths = [t for t in self._deaths if now - t < _RESTART_WINDOW_SECS] + [now]if keys:threading.Thread(target=self._restart, args=(keys,), daemon=True,name="plugin-host-restart").start()+ def _restart_refused(self, what: str) -> bool:+ if len(self._deaths) <= _RESTART_BUDGET:+ return False+ logger.error("Plugin host for %s died %d times in %.0fs; not restarting it again (%s)",+ self._home, len(self._deaths), _RESTART_WINDOW_SECS, what)+ return True+def _restart(self, keys: list) -> None:- now = time.monotonic()- self._restarts = [t for t in self._restarts if now - t < _RESTART_WINDOW_SECS]- if len(self._restarts) >= _RESTART_BUDGET:- logger.error("Plugin host for %s died %d times in %.0fs; not restarting it again (plugins: %s)",- self._home, len(self._restarts), _RESTART_WINDOW_SECS, ", ".join(keys))+ if self._restart_refused("plugins: " + ", ".join(keys)):return- self._restarts.append(now)- time.sleep(0.5 * len(self._restarts))+ time.sleep(0.5 * len(self._deaths))manager = self._managerfor key in keys:loaded = manager._plugins.get(key)@@ -212,9 +227,32 @@ class PluginHost:return str((result or {}).get("module") or module_name or "")def load_instance(self, plugin_dir: Path, *, module_name: str, base_ref: str, capture: str,- ctx: Any = None) -> Any:+ ctx: Any = None, before_reload: Optional[Callable[[], None]] = None) -> Any:"""Load a category plugin (memory provider, context engine, cron scheduler) in the host and- return a proxy that is an instance of ``base_ref``. ``ctx`` receives its other registrations."""+ return a proxy that is an instance of ``base_ref``. ``ctx`` receives its other registrations.++ The proxy outlives a host crash: its next use loads the plugin into the new host (after+ ``before_reload``, which drops the registrations the old load forwarded) and carries on."""+ load = functools.partial(self._load_instance_ref, Path(plugin_dir), module_name=module_name,+ base_ref=base_ref, capture=capture, ctx=ctx)+ ref = load()+ if ref is None:+ return None++ def reload() -> Dict[str, Any]:+ if self._restart_refused(f"{capture} plugin {Path(plugin_dir).name}"):+ raise PluginHostUnavailable(self._exit_reason())+ if before_reload is not None:+ before_reload()+ fresh = load()+ if fresh is None:+ raise PluginHostUnavailable(f"plugin {Path(plugin_dir).name!r} no longer loads in the plugin host")+ return fresh++ return self._object_proxy(ref, _import_ref(base_ref), reload=reload)++ def _load_instance_ref(self, plugin_dir: Path, *, module_name: str, base_ref: str, capture: str,+ ctx: Any) -> Optional[Dict[str, Any]]:channel = self.ensure_started()plugin_key = f"{capture}:{Path(plugin_dir).name}"if ctx is not None:@@ -232,9 +270,14 @@ class PluginHost:ref = channel.call("load_instance", params)finally:self._loading = None- if ref is None:- return None- return self._object_proxy(ref, _import_ref(base_ref))+ if ref is not None:+ ref["generation"] = self._generation+ return ref++ def config_schema(self, path: Path) -> Any:+ """Run a user memory provider's ``config_schema.py`` here and return its ``CONFIG_SCHEMA``."""+ self.ensure_started()+ return self._call("config_schema", {"path": str(path)})def profile_call(self, plugin_dir: str, module_name: str, profile: str, attr: str,args: tuple, kwargs: dict) -> Any:@@ -261,27 +304,44 @@ class PluginHost:logger.warning("Plugin '%s' on_unload callback failed in the plugin host: %s", plugin_key, error)# -- parent -> host ------------------------------------------------------------------------------ def _call(self, method: str, params: Dict[str, Any]) -> Any:+ def _call(self, method: str, params: Dict[str, Any], *, generation: Optional[int] = None) -> Any:channel = self._channeltry:if channel is None:raise PluginHostUnavailable("not started")+ if generation is not None and generation != self._generation:+ raise PluginHostUnavailable("this object belonged to a plugin host process that has exited")+ if self._releases:+ released, self._releases = self._releases, []+ channel.call("release", {"refs": released})return decode(channel.call(method, params), self._resolve_ref)except PluginHostUnavailable as exc:raise PluginHostUnavailable(self._exit_reason()) from exc- def invoke(self, ref: int, args: tuple, kwargs: dict) -> Any:- return self._call("invoke", {"ref": ref, "args": encode(list(args)), "kwargs": encode(kwargs)})+ def _release(self, generation: int, ref: int) -> None:+ """Finalizer of an object proxy (any thread, GC time): queue only; sent with the next call."""+ if generation == self._generation:+ self._releases.append(ref)- def obj_invoke(self, ref: int, method: str, args: tuple, kwargs: dict) -> Any:+ def invoke(self, ref: int, args: tuple, kwargs: dict, *, generation: Optional[int] = None) -> Any:+ 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:+ ref, generation = slot.live()return self._call("obj_invoke", {"ref": ref, "method": method, "args": encode(list(args)),- "kwargs": encode(kwargs)})+ "kwargs": encode(kwargs)}, generation=generation)- def obj_getattr(self, ref: int, name: str) -> Any:- return self._call("obj_getattr", {"ref": ref, "name": name})+ def obj_getattr(self, slot: "_ObjectSlot", name: str) -> Any:+ ref, generation = slot.live()+ value = self._call("obj_getattr", {"ref": ref, "name": name}, generation=generation)+ if isinstance(value, dict) and set(value) == {"__missing__"}:+ raise AttributeError(name)+ return value- def obj_setattr(self, ref: int, name: str, value: Any) -> None:- self._call("obj_setattr", {"ref": ref, "name": name, "value": encode(value)})+ def obj_setattr(self, slot: "_ObjectSlot", name: str, value: Any) -> None:+ ref, generation = slot.live()+ self._call("obj_setattr", {"ref": ref, "name": name, "value": encode(value)}, generation=generation)# -- host -> parent -----------------------------------------------------------------------------def _context_for_origin(self, origin: Optional[int]) -> contextvars.Context:@@ -333,12 +393,12 @@ class PluginHost:if not callable(target):return self._encode_for_host(target)if params.get("probe"):- return {"__method__": True}+ return {"__method__": True, "async": inspect.iscoroutinefunction(target)}args = decode(params.get("args") or [], self._resolve_ref)kwargs = decode(params.get("kwargs") or {}, self._resolve_ref)result = target(*args, **kwargs)if asyncio.iscoroutine(result):- result = asyncio.run(result)+ result = _run_on_gateway_loop(result)return self._encode_for_host(result)def _encode_for_host(self, value: Any) -> Any:@@ -365,12 +425,13 @@ class PluginHost:raise PluginHostUnsupported("registration handles are owned by the plugin host")def _callable_proxy(self, ref: Dict[str, Any]) -> Callable[..., Any]:- ref_id = int(ref["__callable__"])+ ref_id, generation = int(ref["__callable__"]), self._generation+async def async_proxy(*args: Any, **kwargs: Any) -> Any:- return await asyncio.to_thread(self.invoke, ref_id, args, kwargs)+ return await asyncio.to_thread(self.invoke, ref_id, args, kwargs, generation=generation)def sync_proxy(*args: Any, **kwargs: Any) -> Any:- return self.invoke(ref_id, args, kwargs)+ return self.invoke(ref_id, args, kwargs, generation=generation)proxy: Any = async_proxy if ref.get("async") else sync_proxysignature = signature_from(ref.get("sig"))@@ -383,42 +444,109 @@ class PluginHost:proxy.__hermes_plugin_host_ref__ = ref_id # type: ignore[attr-defined]return proxy- def _object_proxy(self, ref: Dict[str, Any], base: type) -> Any:- ref_id = int(ref["__object__"])+ def _object_proxy(self, ref: Dict[str, Any], base: type,+ reload: Optional[Callable[[], Dict[str, Any]]] = None) -> Any:+ """An instance of ``base`` whose methods and public attributes live in the host. Attributes+ Hermes assigns go to the plugin's object when they can cross; live handles stay local."""host = self- live = frozenset(ref.get("live") or ())+ slot = _ObjectSlot(self, ref, reload)+ live = set(ref.get("live") or ())namespace: Dict[str, Any] = {}for name, meta in (ref.get("methods") or {}).items():- namespace[name] = _method_proxy(host, ref_id, name, meta)- for name, value in (ref.get("static") or {}).items():- decoded = decode(value, self._resolve_ref)- namespace[name] = staticmethod(decoded) if callable(decoded) else decoded+ namespace[name] = _method_proxy(host, slot, name, meta)def __getattribute__(self_: Any, name: str) -> Any: # noqa: N807if name in live:- return host.obj_getattr(ref_id, name)+ return host.obj_getattr(slot, name)return object.__getattribute__(self_, name)- def __setattr__(self_: Any, name: str, value: Any) -> None: # noqa: N807- if name in live:- host.obj_setattr(ref_id, name, value)- else:- object.__setattr__(self_, name, value)+ def __getattr__(self_: Any, name: str) -> Any: # noqa: N807 — set later inside the plugin+ if name.startswith("_"):+ raise AttributeError(name)+ try:+ return host.obj_getattr(slot, name)+ except PluginHostUnavailable as exc: # ``hasattr``/``getattr(x, n, None)`` probes stay probes+ raise AttributeError(name) from exc- namespace.update(__getattribute__=__getattribute__, __setattr__=__setattr__,- __module__=__name__, __hermes_plugin_host_ref__=ref_id,- __repr__=lambda self_: f"<plugin-host {ref.get('type')} #{ref_id}>")+ def __setattr__(self_: Any, name: str, value: Any) -> None: # noqa: N807+ if not name.startswith("_") and not _holds_live_handle(value):+ host.obj_setattr(slot, name, value)+ live.add(name)+ return+ live.discard(name)+ object.__setattr__(self_, name, value)++ namespace.update(__getattribute__=__getattribute__, __getattr__=__getattr__, __setattr__=__setattr__,+ __module__=__name__, __hermes_plugin_host_ref__=slot,+ __repr__=lambda self_: f"<plugin-host {ref.get('type')} #{slot.ref}>")cls = type(f"Hosted{ref.get('type') or base.__name__}", (base,), namespace)cls.__abstractmethods__ = frozenset()- return object.__new__(cls)+ proxy = object.__new__(cls)+ slot.track(proxy)+ return proxy-def _method_proxy(host: PluginHost, ref_id: int, name: str, meta: Dict[str, Any]) -> Callable[..., Any]:+class _ObjectSlot:+ """Which host object (id + host generation) a proxy addresses; re-resolved after a host restart+ when the proxy knows how to load its plugin again."""++ def __init__(self, host: PluginHost, ref: Dict[str, Any], reload: Optional[Callable[[], Dict[str, Any]]]):+ self._host, self._reload = host, reload+ self.ref, self.generation = int(ref["__object__"]), int(ref.get("generation") or host._generation)+ self._finalizer: Optional[weakref.finalize] = None+ self._proxy: Optional[weakref.ref] = None++ def track(self, proxy: Any) -> None:+ self._proxy = weakref.ref(proxy)+ self._finalizer = weakref.finalize(proxy, self._host._release, self.generation, self.ref)++ def live(self) -> tuple:+ if (self.generation != self._host._generation or not self._host.alive) and self._reload is not None:+ fresh = self._reload()+ if self._finalizer is not None:+ self._finalizer.detach()+ self.ref, self.generation = int(fresh["__object__"]), int(fresh["generation"])+ proxy = self._proxy() if self._proxy is not None else None+ if proxy is not None:+ self.track(proxy)+ return self.ref, self.generation+++def _holds_live_handle(value: Any) -> bool:+ """True when ``value`` would reach the host only as an opaque placeholder (an agent, a client)."""+ found = False++ def refs(obj: Any) -> Optional[dict]:+ nonlocal found+ if callable(obj) or not (dataclasses.is_dataclass(obj) or hasattr(obj, "model_dump")):+ found = True+ return None++ encoded = encode(value, refs)+ return found or (isinstance(encoded, dict) and "__opaque__" in encoded)+++def _run_on_gateway_loop(coro: Any) -> Any:+ """A facade coroutine (``platform_actions``) uses adapters bound to the gateway's event loop, so+ it runs there when a gateway is up; otherwise on a private loop. Always called off-loop (a+ channel thread), never from the loop itself."""+ try:+ from gateway.run import _gateway_runner_ref+ runner = _gateway_runner_ref()+ except Exception:+ runner = None+ loop = getattr(runner, "_gateway_loop", None)+ if loop is not None and loop.is_running() and not loop.is_closed():+ return asyncio.run_coroutine_threadsafe(coro, loop).result()+ return asyncio.run(coro)+++def _method_proxy(host: PluginHost, slot: _ObjectSlot, name: str, meta: Dict[str, Any]) -> Callable[..., Any]:async def async_method(self_: Any, *args: Any, **kwargs: Any) -> Any:- return await asyncio.to_thread(host.obj_invoke, ref_id, name, args, kwargs)+ return await asyncio.to_thread(host.obj_invoke, slot, name, args, kwargs)def sync_method(self_: Any, *args: Any, **kwargs: Any) -> Any:- return host.obj_invoke(ref_id, name, args, kwargs)+ return host.obj_invoke(slot, name, args, kwargs)method: Any = async_method if meta.get("async") else sync_methodmethod.__name__ = method.__qualname__ = namediff --git a/hermes_cli/plugin_host_child.py b/hermes_cli/plugin_host_child.pyindex 4a5a4a9d072..f6f5918d1a2 100644--- a/hermes_cli/plugin_host_child.py+++ b/hermes_cli/plugin_host_child.py@@ -29,7 +29,8 @@ from pathlib import Pathfrom typing import Any, Callable, Dict, List, Optionalfrom hermes_cli.plugin_host_wire import (- Channel, Opaque, PROTOCOL_VERSION, PluginHostUnsupported, decode, describe_signature, encode, is_async_callable,+ Channel, Opaque, PROTOCOL_VERSION, PluginHostUnsupported, bind_serving_request, decode, describe_signature,+ encode, is_async_callable, serving_request,)logger = logging.getLogger("hermes_cli.plugin_host_child")@@ -60,7 +61,7 @@ class RemoteFacade:def __init__(self, runtime: "HostRuntime", plugin_key: str, name: str):self._runtime, self._plugin_key, self._name = runtime, plugin_key, name- self._methods: set = set()+ self._methods: Dict[str, bool] = {} # method name -> is a coroutine function in Hermesdef __getattr__(self, attr: str) -> Any:if attr.startswith("_"):@@ -69,8 +70,16 @@ class RemoteFacade:value = self._runtime.facade_call(self._plugin_key, self._name, attr, _probe=True)if not (isinstance(value, dict) and value.get("__method__")):return value # a plain attribute (``ctx.state.data_dir``): read fresh every time- self._methods.add(attr)- return functools.partial(self._runtime.facade_call, self._plugin_key, self._name, attr)+ self._methods[attr] = bool(value.get("async"))+ call = functools.partial(self._runtime.facade_call, self._plugin_key, self._name, attr)+ if not self._methods[attr]:+ return call++ async def remote(*args: Any, **kwargs: Any) -> Any: # ``await ctx.llm.acomplete(...)``+ return await asyncio.to_thread(call, *args, **kwargs)++ remote.__name__ = attr+ return remoteclass RemotePluginContext:@@ -129,6 +138,7 @@ class HostRuntime:self.modules: Dict[str, str] = {}self.asgi_apps: Dict[str, Any] = {}self.profiles: Dict[str, Dict[str, Any]] = {}+ self.instance_modules: Dict[str, Any] = {}self.stopped = threading.Event()self.loop = asyncio.new_event_loop()threading.Thread(target=self.loop.run_forever, name="plugin-host-loop", daemon=True).start()@@ -159,7 +169,6 @@ class HostRuntime:"""Method table + attribute plan for a provider object; every method runs here, in the host."""methods: Dict[str, Any] = {}instance = sorted(k for k in vars(obj) if not k.startswith("_")) if hasattr(obj, "__dict__") else []- static: Dict[str, Any] = {}live: List[str] = list(instance)for name in dir(obj):if name.startswith("_") or name in instance:@@ -172,9 +181,11 @@ class HostRuntime:if callable(value):methods[name] = {"async": is_async_callable(value), "sig": describe_signature(value)}else:- static[name] = encode(value)+ # Class-level defaults too: an engine that sets ``context_length`` only later in+ # ``update_model()`` must not read as the base-class default forever in Hermes.+ live.append(name)return {"__object__": self._remember(plugin_key, obj), "methods": methods, "live": live,- "static": static, "type": type(obj).__name__}+ "type": type(obj).__name__}def resolve_from_parent(self, ref: dict) -> Any:if "__handle__" in ref:@@ -203,7 +214,7 @@ class HostRuntime:def spawn(self, coro: Any, *, name: Optional[str] = None) -> Any:if not inspect.iscoroutine(coro):raise TypeError("spawn_task() requires a coroutine object")- return asyncio.run_coroutine_threadsafe(_named(coro), self.loop)+ return asyncio.run_coroutine_threadsafe(_on_behalf_of(coro, serving_request()), self.loop)# -- incoming ---------------------------------------------------------------------------------def handle(self, method: str, params: Dict[str, Any], _origin: Optional[int]) -> Any:@@ -213,8 +224,10 @@ class HostRuntime:return handler(self, params)def _run(self, result: Any) -> Any:+ """Await plugin coroutines on the host loop, still attributed to the request being served+ (their ``ctx`` calls then run in that caller's session, not a bare context)."""if inspect.isawaitable(result):- return asyncio.run_coroutine_threadsafe(_await(result), self.loop).result()+ return asyncio.run_coroutine_threadsafe(_on_behalf_of(result, serving_request()), self.loop).result()return resultdef _encode_result(self, plugin_key: str, value: Any) -> Any:@@ -243,7 +256,11 @@ class HostRuntime:run ``register(ctx)`` capturing the one ``capture`` registration, else instantiate the firstsubclass of ``base``. Other registrations reach Hermes only when it bound a ctx for them."""plugin_key = str(params["plugin_key"])- module = _import_plugin(params)+ # Hermes asks for a fresh instance many times (agent cache, doctor, dashboard); like the+ # in-process loader, the module body runs once per host and only the instance is new.+ module = self.instance_modules.get(str(params["path"]))+ if module is None:+ module = self.instance_modules[str(params["path"])] = _import_plugin(params)self.modules[plugin_key] = module.__name__base = _import_base(str(params["base"]))capture = str(params["capture"])@@ -336,10 +353,29 @@ class HostRuntime:def op_obj_getattr(self, params: Dict[str, Any]) -> Any:obj = self.refs.get(int(params["ref"]))name = str(params["name"])- if obj is None or name.startswith("_"):- raise AttributeError(name)+ if obj is None:+ raise LookupError(f"plugin host object {params['ref']} was released")+ if name.startswith("_") or not hasattr(obj, name):+ return {"__missing__": name}return self._encode_result(self.owners.get(int(params["ref"]), ""), getattr(obj, name))+ def op_release(self, params: Dict[str, Any]) -> None:+ """Drop objects whose Hermes-side proxies were garbage-collected."""+ with self._lock:+ for ref in params.get("refs") or ():+ self.refs.pop(int(ref), None)+ self.owners.pop(int(ref), None)++ def op_config_schema(self, params: Dict[str, Any]) -> Any:+ """A memory provider's ``config_schema.py`` ``CONFIG_SCHEMA`` (user code: it runs here)."""+ path = Path(str(params["path"]))+ spec = importlib.util.spec_from_file_location(f"_hermes_memory_config_schema.{path.parent.name}", path)+ if spec is None or spec.loader is None:+ raise ImportError(f"cannot load {path}")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return encode(getattr(module, "CONFIG_SCHEMA", None))+def op_obj_setattr(self, params: Dict[str, Any]) -> None:obj = self.refs.get(int(params["ref"]))name = str(params["name"])@@ -377,6 +413,7 @@ _HANDLERS: Dict[str, Callable[[HostRuntime, Dict[str, Any]], Any]] = {"invoke": HostRuntime.op_invoke,"obj_invoke": HostRuntime.op_obj_invoke, "obj_getattr": HostRuntime.op_obj_getattr,"obj_setattr": HostRuntime.op_obj_setattr, "unload": HostRuntime.op_unload,+ "release": HostRuntime.op_release, "config_schema": HostRuntime.op_config_schema,"shutdown": HostRuntime.op_shutdown,}@@ -412,14 +449,11 @@ def _is_provider_object(value: Any) -> bool:functools.partial, type)) and type(value).__module__ != "builtins"-async def _await(awaitable: Any) -> Any:+async def _on_behalf_of(awaitable: Any, origin: Optional[int]) -> Any:+ bind_serving_request(origin) # this task's context only; tasks it spawns inherit itreturn await awaitable-async def _named(coro: Any) -> Any:- return await coro--def _import_plugin(params: Dict[str, Any]) -> Any:"""Import a directory plugin under the module name Hermes assigned, or resolve an entry point."""if params.get("entrypoint"):diff --git a/hermes_cli/plugin_host_profiles.py b/hermes_cli/plugin_host_profiles.pyindex 07fe08d794a..9ea3bf94022 100644--- a/hermes_cli/plugin_host_profiles.py+++ b/hermes_cli/plugin_host_profiles.py@@ -56,7 +56,9 @@ def _fingerprint(plugin_dir: Path) -> str:def _cached_extraction(plugin_dir: Path, module_name: str) -> Dict[str, Any]:from hermes_constants import get_hermes_home- cache = get_hermes_home() / "cache" / "plugin_host" / "model-providers" / f"{plugin_dir.name}.json"+ # Keyed by the full path too: a user and a project plugin may share a directory name.+ path_key = hashlib.sha256(str(plugin_dir.resolve()).encode("utf-8")).hexdigest()[:12]+ cache = get_hermes_home() / "cache" / "plugin_host" / "model-providers" / f"{plugin_dir.name}-{path_key}.json"fingerprint = _fingerprint(plugin_dir)try:cached = json.loads(cache.read_text(encoding="utf-8-sig"))diff --git a/hermes_cli/plugin_host_wire.py b/hermes_cli/plugin_host_wire.pyindex 732bae7269b..0a9be094dae 100644--- a/hermes_cli/plugin_host_wire.py+++ b/hermes_cli/plugin_host_wire.py@@ -1,8 +1,10 @@"""Wire format for the plugin host: framed JSON-RPC in both directions plus a value codec.Either side can call the other while a call is in flight (a host tool handler calling-``ctx.dispatch_tool`` re-enters the parent), so requests are served on a worker pool and every-outgoing request made while serving one names it as ``origin``. The parent uses that to run a+``ctx.dispatch_tool`` re-enters the parent), so every request is served on its own thread (nested+re-entry can go arbitrarily deep; a bounded pool would deadlock) and every outgoing request made+while serving one names it as ``origin``. The origin is a ContextVar, so it follows the work onto+event-loop tasks and ``to_thread`` hops. The parent uses that to run anested request in the caller's contextvars (profile home, secret scope, session) instead of thereader thread's bare context.@@ -22,7 +24,7 @@ import itertoolsimport jsonimport loggingimport threading-from concurrent.futures import Future, ThreadPoolExecutor+from concurrent.futures import Futurefrom pathlib import PurePathfrom typing import Any, BinaryIO, Callable, Dict, Optional@@ -178,7 +180,17 @@ def signature_from(spec: Optional[list]):return None-_serving = threading.local()+_SERVING: contextvars.ContextVar[Optional[int]] = contextvars.ContextVar("plugin_host_serving", default=None)+++def serving_request() -> Optional[int]:+ """The peer request this code is running for (the ``origin`` of any call it makes), if any."""+ return _SERVING.get()+++def bind_serving_request(request_id: Optional[int]) -> None:+ """Mark the current context (an event-loop task) as working for peer request ``request_id``."""+ _SERVING.set(request_id)class Channel:@@ -186,7 +198,7 @@ class Channel:def __init__(self, reader: BinaryIO, writer: BinaryIO,handler: Callable[[str, Dict[str, Any], Optional[int]], Any], *, name: str,- max_workers: int = 32, on_close: Optional[Callable[[str], None]] = None,+ on_close: Optional[Callable[[str], None]] = None,context_for_origin: Optional[Callable[[Optional[int]], contextvars.Context]] = None):self._reader, self._writer = reader, writerself._handler, self._name, self._on_close = handler, name, on_close@@ -196,7 +208,6 @@ class Channel:self._pending: Dict[int, Future] = {}self._pending_lock = threading.Lock()self._contexts: Dict[int, contextvars.Context] = {}- self._pool = ThreadPoolExecutor(max_workers=max_workers, thread_name_prefix=f"{name}-rpc")self._closed_reason: Optional[str] = Noneself._thread = threading.Thread(target=self._read_loop, name=f"{name}-reader", daemon=True)@@ -221,7 +232,7 @@ class Channel:self._pending[request_id] = futureself._contexts[request_id] = contextvars.copy_context()message = {"id": request_id, "method": method, "params": params,- "origin": getattr(_serving, "request_id", None)}+ "origin": _SERVING.get()}try:self._send(message)return future.result(timeout=timeout)@@ -254,7 +265,8 @@ class Channel:logger.warning("%s: dropped a malformed frame: %.200r", self._name, line)continueif "method" in message:- self._pool.submit(self._serve, message)+ threading.Thread(target=self._serve, args=(message,), daemon=True,+ name=f"{self._name}-rpc").start()continuewith self._pending_lock:future = self._pending.get(message.get("id"))@@ -270,7 +282,7 @@ class Channel:context = self._context_for_origin(origin) if self._context_for_origin else Nonedef run() -> Dict[str, Any]:- _serving.request_id = request_id+ token = _SERVING.set(request_id)try:result = self._handler(str(message.get("method")), message.get("params") or {}, origin)return {"id": request_id, "result": result}@@ -280,9 +292,9 @@ class Channel:type(exc).__name__)return {"id": request_id, "error": {"type": type(exc).__name__, "message": str(exc)}}finally:- _serving.request_id = None+ _SERVING.reset(token)- reply = context.run(run) if context is not None else run()+ reply = (context or contextvars.copy_context()).run(run)if request_id is None:returntry:@@ -309,7 +321,6 @@ class Channel:for future in pending:if not future.done():future.set_exception(PluginHostUnavailable(reason))- self._pool.shutdown(wait=False, cancel_futures=True)if self._on_close is not None:try:self._on_close(reason)diff --git a/hermes_cli/web_server_dashboard.py b/hermes_cli/web_server_dashboard.pyindex a3ac854f8a6..762ced4d868 100644--- a/hermes_cli/web_server_dashboard.py+++ b/hermes_cli/web_server_dashboard.py@@ -807,18 +807,24 @@ def _mount_hosted_plugin_api(app, plugin: dict, api_file_name: str) -> None:"""``plugins.isolation: host``: the plugin's router runs in the requesting profile's plugin host;this process only forwards each ``/api/plugins/<name>/`` request to it (auth and the profilescope still apply here first). Responses are buffered: streaming and websockets need in-process."""- name, dashboard_dir = plugin["name"], str(plugin["_dir"])+ name = plugin["name"]async def forward(request: Request, path: str = "") -> Response:- from hermes_cli.plugins import get_plugin_manager- host = get_plugin_manager()._plugin_host()+ # Resolve the plugin again in the REQUESTING profile (the route is mounted once, from the+ # launch profile): its own copy, gated by its own plugins.enabled, served by its own host.+ target = await asyncio.to_thread(_hosted_plugin_for_request, name)+ if target is None:+ return JSONResponse({"detail": f"plugin {name!r} is not enabled in this profile"}, status_code=404)+ host, dashboard_dir, api_file = targetresult = await asyncio.to_thread(- host.asgi_request, name, dashboard_dir, api_file_name, request.method, "/" + path,+ host.asgi_request, name, dashboard_dir, api_file, request.method, "/" + path,request.url.query, [(k, v) for k, v in request.headers.items() if k.lower() != "host"],await request.body())- headers = {k: v for k, v in result["headers"]- if k.lower() not in {"content-length", "transfer-encoding", "connection"}}- return Response(content=result["body"], status_code=int(result["status"]), headers=headers)+ response = Response(content=result["body"], status_code=int(result["status"]))+ for key, value in result["headers"]: # a list, so repeated headers (Set-Cookie) all survive+ if key.lower() not in {"content-length", "transfer-encoding", "connection"}:+ response.headers.append(key, value)+ return responseapp.add_api_route(f"/api/plugins/{name}/{{path:path}}", forward, include_in_schema=False,methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"],@@ -826,6 +832,20 @@ def _mount_hosted_plugin_api(app, plugin: dict, api_file_name: str) -> None:_log.info("Mounted plugin API routes via the plugin host: /api/plugins/%s/", name)+def _hosted_plugin_for_request(name: str) -> Optional[tuple]:+ """``(plugin host, dashboard dir, api file)`` for plugin ``name`` in the active profile, or None+ when that profile has no enabled user copy of it."""+ from hermes_cli.plugins import get_plugin_manager+ from hermes_cli.plugins_cmd import _get_disabled_set, _get_enabled_set+ for plugin in _discover_dashboard_plugins():+ if plugin.get("name") != name or not plugin.get("_api_file") or plugin.get("source") != "user":+ continue+ if _plugin_api_mount_skip_reason(plugin, _get_enabled_set(), _get_disabled_set()):+ return None+ return get_plugin_manager()._plugin_host(), str(plugin["_dir"]), str(plugin["_api_file"])+ return None++def _mount_plugin_api_routes():"""Import and mount backend API routes from plugins that declare them.diff --git a/plugins/memory/__init__.py b/plugins/memory/__init__.pyindex 16a81cd2b20..815c82ed6b8 100644--- a/plugins/memory/__init__.py+++ b/plugins/memory/__init__.py@@ -403,11 +403,15 @@ class _ProviderCollector:self._hook_source = _hook_source_of(self.name, SimpleNamespace(__file__=str(provider_dir / "__init__.py")))manager = self._plugin_context()._manager- with manager._discovery_lock:- manager._drop_fallback_hooks(self._hook_source)++ def drop_hooks() -> None: # also before a reload into a restarted host: no stale hook proxies+ with manager._discovery_lock:+ manager._drop_fallback_hooks(self._hook_source)++ drop_hooks()self.provider = host.load_instance(provider_dir, module_name=module_name, capture="register_memory_provider",- base_ref="agent.memory_provider:MemoryProvider", ctx=self)+ base_ref="agent.memory_provider:MemoryProvider", ctx=self, before_reload=drop_hooks)return self.providerdef register_hook(self, hook_name, callback):diff --git a/plugins/memory/config_schema.py b/plugins/memory/config_schema.pyindex d558ab7630c..5c5a8fa1ce5 100644--- a/plugins/memory/config_schema.py+++ b/plugins/memory/config_schema.py@@ -101,10 +101,16 @@ def get_provider_config_schema(name: str) -> ProviderConfigSchema | None:return _SCHEMA_CACHE[key]try:- spec = importlib.util.spec_from_file_location(f"_hermes_memory_config_schema.{name}", path)- module = importlib.util.module_from_spec(spec)- spec.loader.exec_module(module)- schema = getattr(module, "CONFIG_SCHEMA", None)+ from plugins.memory import _is_bundled+ from hermes_cli.plugin_isolation import user_plugin_host+ host = None if _is_bundled(provider_dir) else user_plugin_host()+ if host is not None: # plugins.isolation: host — a user schema file is user code too+ schema = _schema_from_record(host.config_schema(path))+ else:+ spec = importlib.util.spec_from_file_location(f"_hermes_memory_config_schema.{name}", path)+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ schema = getattr(module, "CONFIG_SCHEMA", None)except Exception:# Never cache a failed load: it would pin an empty panel until restart._log.exception("failed to load config schema for memory provider %r", name)@@ -113,3 +119,15 @@ def get_provider_config_schema(name: str) -> ProviderConfigSchema | None:if schema is not None:_SCHEMA_CACHE[key] = schemareturn schema+++def _schema_from_record(record) -> ProviderConfigSchema | None:+ """Rebuild a schema that crossed the plugin-host boundary as plain data."""+ if not record:+ return None+ fields = tuple(+ ProviderField(**{**f, "options": tuple(ProviderFieldOption(**o) for o in f.get("options") or ()),+ "aliases": tuple(f.get("aliases") or ()),+ "env_fallbacks": tuple(f.get("env_fallbacks") or ())})+ for f in record.get("fields") or ())+ return ProviderConfigSchema(**{**record, "fields": fields})diff --git a/tests/hermes_cli/test_plugin_host.py b/tests/hermes_cli/test_plugin_host.pyindex ffd5e5b29c9..e04ff528087 100644--- a/tests/hermes_cli/test_plugin_host.py+++ b/tests/hermes_cli/test_plugin_host.py@@ -62,7 +62,7 @@ def _home_with_plugins(tmp_path, monkeypatch, plugins: dict, isolation="host"):return home[email protected](sys.platform == "win32", reason="POSIX process semantics (os._exit child)")[email protected]("posix") # os._exit / SIGKILL process semanticsdef test_plugin_runs_out_of_process_with_ctx_round_trips_and_survives_host_crash(tmp_path, monkeypatch):from agent import image_gen_registryfrom agent.image_gen_provider import ImageGenProvider@@ -149,11 +149,105 @@ def test_model_provider_profile_data_is_local_and_overrides_run_in_the_host(tmp_assert isinstance(profile, providers.ProviderProfile)# Discovery never started a host: data came from the cached, credential-free extraction.assert profile.base_url == "https://hostmodel.example/v1" and tuple(profile.env_vars) == ("HOSTMODEL_KEY",)- assert list((home / "cache" / "plugin_host" / "model-providers").glob("hostmodel.json"))+ assert list((home / "cache" / "plugin_host" / "model-providers").glob("hostmodel-*.json"))assert not any("hostmodel" in name for name in sys.modules)body = profile.build_extra_body(session_id="s1")assert body["session_id"] == "s1" and body["pid"] != os.getpid()finally:- host = plugins_mod.get_plugin_manager()._plugin_host_instance+ host = getattr(plugins_mod.get_plugin_manager(), "_plugin_host_instance", None)if host is not None:host.shutdown()+++ASYNC_PLUGIN = '''+import asyncio, json+S = {"type": "object", "properties": {}}++def register(ctx):+ async def whoami(args, **kw): # async plugin code calling back into Hermes+ return json.dumps({"inner": json.loads(ctx.dispatch_tool("session_probe", {})),+ "acomplete_awaitable": asyncio.iscoroutinefunction(ctx.llm.acomplete)})+ ctx.register_tool(name="async_whoami", toolset="asyncprobe", schema={"name": "async_whoami",+ "description": "d", "parameters": S}, handler=whoami, is_async=True)+'''+++def test_async_plugin_code_calls_back_in_the_callers_session(tmp_path, monkeypatch):+ import contextvars+ from tools.registry import registry++ session = contextvars.ContextVar("session", default="<unset>")+ session.set("host-creator") # whoever first touches the host must not leak into later calls+ registry.register(name="session_probe", toolset="asyncprobe", schema={"name": "session_probe",+ "description": "d", "parameters": {"type": "object", "properties": {}}},+ handler=lambda args, **kw: json.dumps({"session": session.get()}))+ _home_with_plugins(tmp_path, monkeypatch, {"asyncprobe": ASYNC_PLUGIN})+ manager = PluginManager()+ manager.discover_and_load()+ try:+ def call_as(name):+ def run():+ session.set(name)+ return json.loads(registry.dispatch("async_whoami", {}, scope=manager.scope_key))+ return contextvars.copy_context().run(run)++ assert call_as("session-B") == {"inner": {"session": "session-B"}, "acomplete_awaitable": True}+ assert call_as("session-C")["inner"] == {"session": "session-C"}+ finally:+ registry.deregister("session_probe")+ manager.unload()+ manager._plugin_host().shutdown()+++MEMORY_PLUGIN = '''+import os+from agent.memory_provider import MemoryProvider++class Probe(MemoryProvider):+ level = 0 # a class-level default the provider changes later+ @property+ def name(self): return "memprobe"+ def is_available(self): return True+ def initialize(self, session_id, **kw): pass+ def get_tool_schemas(self): return []+ def whoami(self):+ self.level += 1+ return os.getpid()++def register(ctx):+ ctx.register_memory_provider(Probe())+'''++[email protected]("posix") # SIGKILL+def test_hosted_memory_provider_stays_live_across_a_host_crash(tmp_path, monkeypatch):+ import signal+ from plugins.memory import load_memory_provider+ from plugins.memory.config_schema import get_provider_config_schema++ home = _home_with_plugins(tmp_path, monkeypatch, {})+ provider_dir = home / "plugins" / "memprobe"+ provider_dir.mkdir(parents=True)+ (provider_dir / "__init__.py").write_text(MEMORY_PLUGIN, encoding="utf-8")+ marker = tmp_path / "schema_pid"+ (provider_dir / "config_schema.py").write_text(+ f"import os, pathlib\npathlib.Path({str(marker)!r}).write_text(str(os.getpid()))\nCONFIG_SCHEMA = None\n",+ encoding="utf-8")+ host = plugins_mod.get_plugin_manager()._plugin_host()+ try:+ provider = load_memory_provider("memprobe")+ first_pid = provider.whoami()+ assert first_pid == host.pid != os.getpid()+ assert provider.level == 1 # read live from the plugin's object, not the class default+ # The provider's schema file is user code too: it runs in the host, never here.+ get_provider_config_schema("memprobe")+ assert int(marker.read_text(encoding="utf-8-sig")) == host.pid++ os.kill(first_pid, signal.SIGKILL) # windows-footgun: ok — posix-only test (platforms marker)+ deadline = time.monotonic() + 10+ while host.alive and time.monotonic() < deadline:+ time.sleep(0.1)+ # The proxy Hermes already holds reloads the provider into the new host on next use.+ assert provider.whoami() not in {first_pid, os.getpid()}+ finally:+ host.shutdown()