Skip to content

The agent that grows with you

feat(plugins): run third-party plugins in a per-profile plugin host (plugins.isolation: host)

teknium15fa55d167859
diff --git a/evals/plugin_isolation/audit_catalog.py b/evals/plugin_isolation/audit_catalog.py
new file mode 100644
index 00000000000..2ae66678922
--- /dev/null
+++ b/evals/plugin_isolation/audit_catalog.py
@@ -0,0 +1,116 @@
+"""Run the plugin-host readiness audit over every plugin-catalog entry at its pinned commit.
+
+ python evals/plugin_isolation/audit_catalog.py --out <dir> [--jobs 12] [--limit N]
+
+Fetches each entry's repo at its pinned sha (shallow, blob-filtered) into ``<dir>/src/``, runs
+:func:`hermes_cli.plugin_isolation_audit.audit_plugin_dir` on the entry's subdir, and writes
+``<dir>/results.json`` plus a markdown summary on stdout: how many catalog plugins run in the
+plugin host unchanged, and the reasons the rest need in-process loading.
+"""
+
+from __future__ import annotations
+
+import argparse
+import collections
+import json
+import re
+import subprocess
+import sys
+from concurrent.futures import ThreadPoolExecutor
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(REPO_ROOT))
+
+from hermes_cli.plugin_catalog import load_catalog # noqa: E402
+from hermes_cli.plugin_isolation_audit import audit_plugin_dir # noqa: E402
+
+
+def _git(args, cwd: Path) -> None:
+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True, timeout=180,
+ stdin=subprocess.DEVNULL)
+
+
+def _fetch(entry, src_root: Path) -> Path:
+ dest = src_root / re.sub(r"[^A-Za-z0-9_.-]", "_", entry.name)
+ marker = dest / ".audited_sha"
+ if marker.is_file() and marker.read_text(encoding="utf-8-sig").strip() == entry.sha:
+ return dest
+ dest.mkdir(parents=True, exist_ok=True)
+ if not (dest / ".git").is_dir():
+ _git(["init", "-q"], dest)
+ _git(["remote", "add", "origin", entry.repo if "://" in entry.repo else f"https://github.com/{entry.repo}"], dest)
+ _git(["fetch", "-q", "--depth", "1", "--filter=blob:none", "origin", entry.sha], dest)
+ _git(["checkout", "-q", "--force", "FETCH_HEAD"], dest)
+ marker.write_text(entry.sha, encoding="utf-8")
+ return dest
+
+
+def _audit(entry, src_root: Path) -> dict:
+ row = {"name": entry.name, "repo": entry.repo, "sha": entry.sha, "tier": entry.tier, "category": entry.category}
+ try:
+ checkout = _fetch(entry, src_root)
+ except Exception as exc:
+ return {**row, "verdict": "fetch_failed", "reasons": [str(exc)[:300]], "notes": []}
+ plugin_dir = checkout / entry.subdir if entry.subdir else checkout
+ if not plugin_dir.is_dir():
+ return {**row, "verdict": "fetch_failed", "reasons": [f"subdir {entry.subdir!r} missing"], "notes": []}
+ return {**row, **audit_plugin_dir(plugin_dir).to_dict()}
+
+
+def _reason_class(reason: str) -> str:
+ if "patches" in reason or "setattr()" in reason:
+ return "patches a Hermes module attribute"
+ if "directly instead of through ctx" in reason:
+ return "mutates a Hermes registry directly (not through ctx)"
+ match = re.search(r"ctx\.(\w+)\(\)", reason)
+ if match:
+ return f"ctx.{match.group(1)}()"
+ if reason.startswith("kind "):
+ return reason.split(":")[0]
+ if "create_client()" in reason:
+ return "model-provider builds its own SDK client (create_client)"
+ if reason.startswith("dashboard backend"):
+ return "dashboard backend API streams (SSE/websocket)"
+ return reason[:80]
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Plugin-host readiness audit over the plugin catalog")
+ parser.add_argument("--out", required=True, type=Path)
+ parser.add_argument("--jobs", type=int, default=12)
+ parser.add_argument("--limit", type=int, default=0)
+ args = parser.parse_args()
+ entries = load_catalog()
+ if args.limit:
+ entries = entries[: args.limit]
+ src_root = args.out / "src"
+ src_root.mkdir(parents=True, exist_ok=True)
+ with ThreadPoolExecutor(max_workers=args.jobs) as pool:
+ rows = list(pool.map(lambda e: _audit(e, src_root), entries))
+ (args.out / "results.json").write_text(json.dumps(rows, indent=2), encoding="utf-8")
+
+ verdicts = collections.Counter(r["verdict"] for r in rows)
+ audited = len(rows) - verdicts.get("fetch_failed", 0)
+ ready = verdicts.get("host", 0) + verdicts.get("portable", 0)
+ blockers = collections.Counter()
+ for r in rows:
+ if r["verdict"] == "in_process":
+ for cls in {_reason_class(x) for x in r["reasons"]}:
+ blockers[cls] += 1
+ print(f"**{ready}/{audited} catalog plugins run in the plugin host unchanged** "
+ f"({100 * ready / max(audited, 1):.1f}%; {len(rows)} entries, {verdicts.get('fetch_failed', 0)} unfetchable)\n")
+ print("| verdict | count |\n|---|---|")
+ for verdict, count in verdicts.most_common():
+ print(f"| {verdict} | {count} |")
+ print("\n| needs in-process because | plugins |\n|---|---|")
+ for cls, count in blockers.most_common():
+ print(f"| {cls} | {count} |")
+ print("\nin-process entries:")
+ for r in sorted((r for r in rows if r["verdict"] == "in_process"), key=lambda r: r["name"]):
+ print(f"- {r['name']}: " + "; ".join(sorted({_reason_class(x) for x in r['reasons']})))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index dca80464281..7f4db9e3b9d 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -1731,6 +1731,16 @@ DEFAULT_CONFIG = {
# Opt-in unattended apply for the cadence check. Git-row plugins ONLY; every apply runs the
# same security scan / consent pipeline as the manual update command.
"auto_apply": False,
+ # Where third-party Python plugins run. in_process: imported into Hermes (default).
+ # host: one plugin-host process per profile runs them and they reach Hermes only through
+ # ctx (a crashing or hanging plugin takes down its host, which restarts; Hermes keeps
+ # running). Bundled plugins stay in-process; `hermes plugins validate` says whether a
+ # plugin can run in the host.
+ "isolation": "in_process",
+ "host": {
+ # argv prefix the plugin host runs under, e.g. a sandbox runner. [] = plain subprocess.
+ "launcher": [],
+ },
},
# Shell-script hooks: event name (pre_tool_call, post_tool_call, pre_llm_call, subagent_stop,
# ...) -> list of {matcher, command, timeout}. First run of a new command prompts for consent;
diff --git a/hermes_cli/plugin_host.py b/hermes_cli/plugin_host.py
new file mode 100644
index 00000000000..1570cfe30e5
--- /dev/null
+++ b/hermes_cli/plugin_host.py
@@ -0,0 +1,445 @@
+"""Parent side of the plugin host: one process per profile that runs its third-party plugins.
+
+With ``plugins.isolation: host`` the loader hands a general Python plugin to :class:`PluginHost`
+instead of importing it. The host process imports it and runs ``register(ctx)``; every ``ctx`` call
+arrives here and is replayed on the plugin's real :class:`~hermes_cli.plugins.PluginContext`, with
+the plugin's callables and provider objects swapped for proxies that call back into the host. From
+then on the rest of Hermes sees ordinary registrations — the registry, hook dispatch, the ledger,
+unload and ``hermes plugins list`` do not know the plugin lives elsewhere, and neither does the
+plugin: its code is unchanged and never learns which process or tenant it serves.
+
+Requests the host makes while Hermes is waiting on it (a tool handler calling ``ctx.dispatch_tool``)
+run in the caller's context — same profile home, secret scope and session — via the wire's
+``origin`` field; spontaneous ones (a ``spawn_task`` loop) run bound to this profile's home.
+
+When the host dies every proxy raises :class:`PluginHostUnavailable`: tool calls return an error,
+hooks fail like any raising callback, and Hermes itself keeps running. A fresh host is then started
+and its plugins reloaded (bounded restarts; a plugin that killed the host while loading stays out).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import contextvars
+import inspect
+import functools
+import importlib
+import itertools
+import logging
+import os
+import subprocess
+import sys
+import threading
+import time
+from pathlib import Path
+from typing import Any, Callable, Dict, Optional
+
+from hermes_cli.plugin_host_wire import (
+ Channel, PluginHostUnavailable, PluginHostUnsupported, decode, encode, signature_from,
+)
+
+logger = logging.getLogger("hermes_cli.plugins")
+
+_HOST_MODULE = "hermes_cli.plugin_host_child"
+_START_TIMEOUT_SECS = 30.0
+_SHUTDOWN_GRACE_SECS = 3.0
+# A host that dies is restarted (its plugins reloaded) at most this many times per window; a plugin
+# that kills the host while loading is not reloaded, so one bad plugin cannot crash-loop the rest.
+_RESTART_BUDGET = 3
+_RESTART_WINDOW_SECS = 600.0
+
+
+class PluginHost:
+ """One host process for one :class:`~hermes_cli.plugins.PluginManager` (one profile home)."""
+
+ def __init__(self, manager: Any):
+ self._manager = manager
+ self._home = Path(manager.home_path)
+ self._lock = threading.Lock()
+ self._proc: Optional[subprocess.Popen] = None
+ self._channel: Optional[Channel] = None
+ self._contexts: Dict[str, Any] = {}
+ self._handles: Dict[int, Any] = {}
+ self._handle_ids = itertools.count(1)
+ self._base_context = self._build_base_context()
+ self._loading: Optional[str] = None
+ self._stopping = False
+ self._restarts: list = []
+ self.info: Dict[str, Any] = {}
+
+ # -- lifecycle ----------------------------------------------------------------------------------
+ @property
+ def pid(self) -> Optional[int]:
+ return self._proc.pid if self._proc is not None else None
+
+ @property
+ def alive(self) -> bool:
+ return (self._channel is not None and self._channel.closed_reason is None
+ and self._proc is not None and self._proc.poll() is None)
+
+ def _build_base_context(self) -> contextvars.Context:
+ context = contextvars.copy_context()
+
+ def bind() -> None:
+ from hermes_constants import set_hermes_home_override
+ set_hermes_home_override(self._home)
+ from agent.secret_scope import build_profile_secret_scope, is_multiplex_active, set_secret_scope
+ if is_multiplex_active():
+ set_secret_scope(build_profile_secret_scope(self._home), profile_home=str(self._home))
+
+ context.run(bind)
+ return context
+
+ def _argv(self) -> list:
+ from hermes_cli.plugin_isolation import host_launcher
+ return [*host_launcher(), sys.executable, "-m", _HOST_MODULE]
+
+ def _env(self) -> Dict[str, str]:
+ from tools.environments.local import served_profile_child_env
+ env = self._base_context.run(served_profile_child_env, target_home=self._home, inherit_credentials=True)
+ repo_root = str(Path(__file__).resolve().parents[1])
+ env["PYTHONPATH"] = os.pathsep.join(p for p in (repo_root, env.get("PYTHONPATH", "")) if p)
+ env.setdefault("HERMES_PLUGIN_HOST_LOG_LEVEL", "WARNING")
+ from hermes_cli.plugin_isolation import HOST_PROCESS_ENV
+ env[HOST_PROCESS_ENV] = "1"
+ return env
+
+ def ensure_started(self) -> Channel:
+ with self._lock:
+ if self.alive:
+ return self._channel # type: ignore[return-value]
+ self._stopping = False
+ argv = self._argv()
+ proc = subprocess.Popen(argv, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
+ stderr=subprocess.PIPE, env=self._env(), cwd=str(self._home),
+ bufsize=0)
+ threading.Thread(target=_pump_stderr, args=(proc, self._home.name), daemon=True,
+ name=f"plugin-host-{proc.pid}-stderr").start()
+ channel = Channel(proc.stdout, proc.stdin, self._handle, # type: ignore[arg-type]
+ name=f"plugin-host[{proc.pid}]",
+ on_close=self._on_channel_close,
+ context_for_origin=self._context_for_origin).start()
+ self._proc, self._channel = proc, channel
+ try:
+ self.info = channel.call("hello", {}, timeout=_START_TIMEOUT_SECS)
+ except Exception as exc:
+ self.shutdown()
+ raise PluginHostUnavailable(f"plugin host failed to start ({' '.join(argv)}): {exc}") from exc
+ logger.info("Plugin host started for %s (pid %s)", self._home, proc.pid)
+ return channel
+
+ def _exit_reason(self) -> str:
+ proc = self._proc
+ code = proc.poll() if proc is not None else None
+ if proc is not None and code is None:
+ try:
+ code = proc.wait(timeout=0.5) # the pipe closes a moment before the exit status lands
+ except subprocess.TimeoutExpired:
+ pass
+ 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
+ logger.warning("Plugin host for %s exited (%s)%s", self._home, self._exit_reason(),
+ f" while loading plugin '{culprit}'" if culprit else "")
+ if keys:
+ threading.Thread(target=self._restart, args=(keys,), daemon=True,
+ name="plugin-host-restart").start()
+
+ 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))
+ return
+ self._restarts.append(now)
+ time.sleep(0.5 * len(self._restarts))
+ manager = self._manager
+ for key in keys:
+ loaded = manager._plugins.get(key)
+ if loaded is None or not loaded.enabled:
+ continue
+ manager.unload(key)
+ manager._load_plugin(loaded.manifest)
+
+ def shutdown(self) -> None:
+ self._stopping = True
+ with self._lock:
+ proc, channel = self._proc, self._channel
+ self._proc = self._channel = None
+ if channel is not None and channel.closed_reason is None:
+ try:
+ channel.call("shutdown", {}, timeout=_SHUTDOWN_GRACE_SECS)
+ except Exception:
+ pass
+ channel.close("shutdown")
+ if proc is not None:
+ try:
+ proc.wait(timeout=_SHUTDOWN_GRACE_SECS)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait(timeout=_SHUTDOWN_GRACE_SECS)
+
+ # -- loading ------------------------------------------------------------------------------------
+ def load(self, manifest: Any, ctx: Any, *, module_name: Optional[str], entrypoint: bool) -> str:
+ """Import ``manifest``'s plugin in the host and replay its registrations onto ``ctx``."""
+ from hermes_cli.plugins import PluginContext, manifest_key
+ channel = self.ensure_started()
+ plugin_key = manifest_key(manifest)
+ self._contexts[plugin_key] = ctx
+ params = {
+ "plugin_key": plugin_key, "plugin_id": ctx.plugin_id, "name": manifest.name,
+ "path": manifest.path, "module_name": module_name, "entrypoint": entrypoint,
+ "profile_name": self._base_context.copy().run(lambda: ctx.profile_name),
+ "manifest": {k: getattr(manifest, k, None) for k in (
+ "name", "version", "description", "author", "source", "path", "key", "kind",
+ "skill_namespace")},
+ "ctx_methods": sorted(n for n in dir(PluginContext) if not n.startswith("_")),
+ }
+ self._loading = plugin_key
+ try:
+ result = channel.call("load", params)
+ except BaseException:
+ self._contexts.pop(plugin_key, None)
+ raise
+ finally:
+ self._loading = None
+ ctx.on_unload(functools.partial(self._unload, plugin_key))
+ 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:
+ """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."""
+ channel = self.ensure_started()
+ plugin_key = f"{capture}:{Path(plugin_dir).name}"
+ if ctx is not None:
+ self._contexts[plugin_key] = ctx
+ from hermes_cli.plugins import PluginContext
+ params = {
+ "plugin_key": plugin_key, "plugin_id": getattr(ctx, "plugin_id", Path(plugin_dir).name),
+ "name": Path(plugin_dir).name, "path": str(plugin_dir), "module_name": module_name,
+ "base": base_ref, "capture": capture, "forward": ctx is not None,
+ "manifest": {"name": Path(plugin_dir).name, "path": str(plugin_dir), "source": "user"},
+ "ctx_methods": sorted(n for n in dir(PluginContext) if not n.startswith("_")),
+ }
+ self._loading = plugin_key
+ try:
+ 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))
+
+ def profile_call(self, plugin_dir: str, module_name: str, profile: str, attr: str,
+ args: tuple, kwargs: dict) -> Any:
+ """Run a model-provider profile's overridden method / callable field in the host."""
+ self.ensure_started()
+ return self._call("profile_call", {"path": plugin_dir, "module_name": module_name, "profile": profile,
+ "attr": attr, "args": encode(list(args)), "kwargs": encode(kwargs)})
+
+ def asgi_request(self, plugin_name: str, dashboard_dir: str, api_file: str, method: str, path: str,
+ query: str, headers: list, body: bytes) -> Dict[str, Any]:
+ """One dashboard ``/api/plugins/<name>/`` request, served by the plugin's router in the host."""
+ self.ensure_started()
+ return self._call("asgi", {"plugin": plugin_name, "dashboard_dir": dashboard_dir, "api_file": api_file,
+ "method": method, "path": path, "query": query,
+ "headers": [list(h) for h in headers], "body": encode(body)})
+
+ def _unload(self, plugin_key: str) -> None:
+ self._contexts.pop(plugin_key, None)
+ channel = self._channel
+ if channel is None or channel.closed_reason is not None:
+ return
+ errors = (channel.call("unload", {"plugin_key": plugin_key}) or {}).get("errors") or []
+ for error in errors:
+ 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:
+ channel = self._channel
+ try:
+ if channel is None:
+ raise PluginHostUnavailable("not started")
+ 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 obj_invoke(self, ref: int, method: str, args: tuple, kwargs: dict) -> Any:
+ return self._call("obj_invoke", {"ref": ref, "method": method, "args": encode(list(args)),
+ "kwargs": encode(kwargs)})
+
+ def obj_getattr(self, ref: int, name: str) -> Any:
+ return self._call("obj_getattr", {"ref": ref, "name": name})
+
+ def obj_setattr(self, ref: int, name: str, value: Any) -> None:
+ self._call("obj_setattr", {"ref": ref, "name": name, "value": encode(value)})
+
+ # -- host -> parent -----------------------------------------------------------------------------
+ def _context_for_origin(self, origin: Optional[int]) -> contextvars.Context:
+ channel = self._channel
+ caller = channel.context_of(origin) if channel is not None else None
+ return (caller or self._base_context).copy()
+
+ def _handle(self, method: str, params: Dict[str, Any], _origin: Optional[int]) -> Any:
+ if method == "ctx":
+ return self._serve_ctx(params)
+ if method == "facade":
+ return self._serve_facade(params)
+ if method == "dispose":
+ handle = self._handles.pop(int(params["handle"]), None)
+ if handle is not None:
+ handle.dispose()
+ return None
+ raise ValueError(f"unknown plugin host request {method!r}")
+
+ def _plugin_ctx(self, params: Dict[str, Any]) -> Any:
+ ctx = self._contexts.get(str(params.get("plugin")))
+ if ctx is None:
+ raise LookupError(f"plugin {params.get('plugin')!r} is not loaded in this host")
+ return ctx
+
+ def _serve_ctx(self, params: Dict[str, Any]) -> Any:
+ from hermes_cli.plugin_isolation import (
+ HOST_OBJECT_BASES, HOST_SKIPPED_CTX_METHODS, HOST_UNSUPPORTED_CTX_METHODS,
+ )
+ ctx = self._plugin_ctx(params)
+ method = str(params.get("method") or "")
+ if (method.startswith("_") or method in HOST_UNSUPPORTED_CTX_METHODS
+ or method in HOST_SKIPPED_CTX_METHODS or method in {"on_unload", "spawn_task"}):
+ raise PluginHostUnsupported(f"ctx.{method}() cannot be called across the plugin host")
+ base = _import_ref(HOST_OBJECT_BASES[method]) if method in HOST_OBJECT_BASES else None
+ resolve = functools.partial(self._resolve_ref, base=base)
+ args = decode(params.get("args") or [], resolve)
+ kwargs = decode(params.get("kwargs") or {}, resolve)
+ result = getattr(ctx, method)(*args, **kwargs)
+ return self._encode_for_host(result)
+
+ def _serve_facade(self, params: Dict[str, Any]) -> Any:
+ from hermes_cli.plugin_isolation import HOST_REMOTE_FACADES
+ ctx = self._plugin_ctx(params)
+ facade, method = str(params.get("facade") or ""), str(params.get("method") or "")
+ if facade not in HOST_REMOTE_FACADES or method.startswith("_"):
+ raise PluginHostUnsupported(f"ctx.{facade}.{method} is not available in the plugin host")
+ target = getattr(getattr(ctx, facade), method)
+ if not callable(target):
+ return self._encode_for_host(target)
+ if params.get("probe"):
+ return {"__method__": True}
+ 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)
+ return self._encode_for_host(result)
+
+ def _encode_for_host(self, value: Any) -> Any:
+ from hermes_cli.plugins_ledger import PluginRegistration
+
+ def refs(obj: Any) -> Optional[dict]:
+ if isinstance(obj, PluginRegistration):
+ handle_id = next(self._handle_ids)
+ self._handles[handle_id] = obj
+ return {"__handle__": handle_id, "kind": obj.kind, "key": obj.key}
+ return None
+
+ return encode(value, refs)
+
+ # -- proxies ------------------------------------------------------------------------------------
+ def _resolve_ref(self, ref: Dict[str, Any], base: Optional[type] = None) -> Any:
+ if "__callable__" in ref:
+ return self._callable_proxy(ref)
+ if "__object__" in ref:
+ if base is None:
+ raise PluginHostUnsupported(f"a {ref.get('type', 'plugin')} object cannot be passed here "
+ "across the plugin host")
+ return self._object_proxy(ref, base)
+ 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__"])
+ async def async_proxy(*args: Any, **kwargs: Any) -> Any:
+ return await asyncio.to_thread(self.invoke, ref_id, args, kwargs)
+
+ def sync_proxy(*args: Any, **kwargs: Any) -> Any:
+ return self.invoke(ref_id, args, kwargs)
+
+ proxy: Any = async_proxy if ref.get("async") else sync_proxy
+ signature = signature_from(ref.get("sig"))
+ if signature is not None:
+ proxy.__signature__ = signature # type: ignore[attr-defined]
+ proxy.__name__ = str(ref.get("name") or "callback")
+ proxy.__qualname__ = str(ref.get("qualname") or proxy.__name__)
+ # Tool override policy and hook attribution key on the defining module.
+ proxy.__module__ = str(ref.get("module") or __name__)
+ 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__"])
+ host = self
+ live = frozenset(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
+
+ def __getattribute__(self_: Any, name: str) -> Any: # noqa: N807
+ if name in live:
+ return host.obj_getattr(ref_id, 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)
+
+ 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}>")
+ cls = type(f"Hosted{ref.get('type') or base.__name__}", (base,), namespace)
+ cls.__abstractmethods__ = frozenset()
+ return object.__new__(cls)
+
+
+def _method_proxy(host: PluginHost, ref_id: int, 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)
+
+ def sync_method(self_: Any, *args: Any, **kwargs: Any) -> Any:
+ return host.obj_invoke(ref_id, name, args, kwargs)
+
+ method: Any = async_method if meta.get("async") else sync_method
+ method.__name__ = method.__qualname__ = name
+ signature = signature_from(meta.get("sig"))
+ if signature is not None: # callers introspect accepted kwargs; bound access drops ``self`` again
+ self_param = inspect.Parameter("self", inspect.Parameter.POSITIONAL_OR_KEYWORD)
+ method.__signature__ = signature.replace(parameters=[self_param, *signature.parameters.values()])
+ return method
+
+
+def _import_ref(ref: str) -> type:
+ module, attr = ref.split(":")
+ return getattr(importlib.import_module(module), attr)
+
+
+def _pump_stderr(proc: subprocess.Popen, label: str) -> None:
+ """Plugin output and host logs go to the Hermes log, tagged with the host's profile."""
+ stream = proc.stderr
+ if stream is None:
+ return
+ for raw in iter(stream.readline, b""):
+ line = raw.decode("utf-8", "replace").rstrip()
+ if line:
+ logger.info("plugin host [%s]: %s", label, line)
diff --git a/hermes_cli/plugin_host_child.py b/hermes_cli/plugin_host_child.py
new file mode 100644
index 00000000000..4a5a4a9d072
--- /dev/null
+++ b/hermes_cli/plugin_host_child.py
@@ -0,0 +1,551 @@
+"""The plugin host process: imports third-party plugins and serves their callbacks to Hermes.
+
+Started by :class:`hermes_cli.plugin_host.PluginHost` as ``python -m hermes_cli.plugin_host_child``
+(optionally under ``plugins.host.launcher``, e.g. a sandbox runner) with the profile's environment.
+Plugins get a :class:`RemotePluginContext` that looks like ``PluginContext``: registrations and
+queries are forwarded to Hermes, callables and provider objects stay here and are invoked by
+reference. Nothing in this module is imported by the Hermes process itself.
+
+stdin/stdout carry the protocol, so the real file descriptors are duplicated for the channel and
+fd 0/1 are pointed at /dev/null and stderr before any plugin code runs: a stray ``print()`` in a
+plugin lands in the host log instead of corrupting the wire.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import functools
+import importlib
+import importlib.metadata
+import importlib.util
+import inspect
+import itertools
+import logging
+import os
+import sys
+import threading
+import types
+from pathlib import Path
+from typing import Any, Callable, Dict, List, Optional
+
+from hermes_cli.plugin_host_wire import (
+ Channel, Opaque, PROTOCOL_VERSION, PluginHostUnsupported, decode, describe_signature, encode, is_async_callable,
+)
+
+logger = logging.getLogger("hermes_cli.plugin_host_child")
+
+_ENTRY_POINTS_GROUP = "hermes_agent.plugins"
+
+
+class RemoteRegistration:
+ """Child-side twin of ``PluginRegistration``: ``dispose()`` releases the Hermes-side entry."""
+
+ def __init__(self, runtime: "HostRuntime", handle_id: int, kind: str, key: str):
+ self._runtime, self._id, self.kind, self.key = runtime, handle_id, kind, key
+ self._disposed = False
+
+ @property
+ def active(self) -> bool:
+ return not self._disposed
+
+ def dispose(self) -> None:
+ if self._disposed:
+ return
+ self._disposed = True
+ self._runtime.channel.call("dispose", {"handle": self._id})
+
+
+class RemoteFacade:
+ """``ctx.state`` / ``ctx.llm`` / ...: every method call runs on the Hermes-side facade."""
+
+ 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()
+
+ def __getattr__(self, attr: str) -> Any:
+ if attr.startswith("_"):
+ raise AttributeError(attr)
+ if attr not in self._methods:
+ 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)
+
+
+class RemotePluginContext:
+ """What ``register(ctx)`` receives inside the host. Mirrors ``PluginContext``'s public surface as
+ announced by Hermes at load, so ``hasattr(ctx, "register_x")`` answers the same as in-process."""
+
+ def __init__(self, runtime: "HostRuntime", plugin_key: str, info: Dict[str, Any]):
+ self._runtime, self._plugin_key = runtime, plugin_key
+ self._methods = set(info.get("ctx_methods") or ())
+ self._facades: Dict[str, RemoteFacade] = {}
+ self.manifest = types.SimpleNamespace(**(info.get("manifest") or {}))
+ self.plugin_id = info.get("plugin_id") or plugin_key
+ self.profile_name = info.get("profile_name")
+
+ def __getattr__(self, name: str) -> Any:
+ if name.startswith("_"):
+ raise AttributeError(name)
+ from hermes_cli.plugin_isolation import (
+ HOST_REMOTE_FACADES, HOST_SKIPPED_CTX_METHODS, HOST_UNSUPPORTED_CTX_METHODS,
+ )
+ if name in HOST_UNSUPPORTED_CTX_METHODS:
+ def unsupported(*_args: Any, **_kwargs: Any) -> Any:
+ raise PluginHostUnsupported(
+ f"ctx.{name}() cannot run in the plugin host: {HOST_UNSUPPORTED_CTX_METHODS[name]}")
+ return unsupported
+ if name in HOST_SKIPPED_CTX_METHODS:
+ def skipped(*_args: Any, **_kwargs: Any) -> None:
+ logger.warning("Plugin '%s': ctx.%s() is skipped in the plugin host (%s)",
+ self.manifest.name, name, HOST_SKIPPED_CTX_METHODS[name])
+ return None
+ return skipped
+ if name in HOST_REMOTE_FACADES:
+ return self._facades.setdefault(name, RemoteFacade(self._runtime, self._plugin_key, name))
+ if name not in self._methods:
+ raise AttributeError(f"'PluginContext' object has no attribute {name!r}")
+ return functools.partial(self._runtime.ctx_call, self._plugin_key, name)
+
+ def on_unload(self, callback: Callable[[], Any]) -> None:
+ if not callable(callback):
+ raise TypeError("on_unload() callback must be callable")
+ self._runtime.unload_callbacks.setdefault(self._plugin_key, []).append(callback)
+
+ def spawn_task(self, coro: Any, *, name: Optional[str] = None) -> Any:
+ return self._runtime.spawn(coro, name=name)
+
+
+class HostRuntime:
+ """Reference tables, the asyncio loop for async plugin code, and the request handler."""
+
+ def __init__(self, reader, writer):
+ self.refs: Dict[int, Any] = {}
+ self.owners: Dict[int, str] = {}
+ self._ids = itertools.count(1)
+ self._lock = threading.Lock()
+ self.unload_callbacks: Dict[str, List[Callable[[], Any]]] = {}
+ self.modules: Dict[str, str] = {}
+ self.asgi_apps: Dict[str, Any] = {}
+ self.profiles: Dict[str, 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()
+ self.channel = Channel(reader, writer, self.handle, name="plugin-host",
+ on_close=lambda _reason: self.stopped.set())
+
+ # -- references -----------------------------------------------------------------------------
+ def _remember(self, plugin_key: str, value: Any) -> int:
+ with self._lock:
+ ref = next(self._ids)
+ self.refs[ref] = value
+ self.owners[ref] = plugin_key
+ return ref
+
+ def ref_for(self, plugin_key: str, value: Any, *, allow_objects: bool) -> Optional[dict]:
+ if isinstance(value, type):
+ return None
+ if callable(value) and not (allow_objects and _is_provider_object(value)):
+ return {"__callable__": self._remember(plugin_key, value), "async": is_async_callable(value),
+ "sig": describe_signature(value), "name": getattr(value, "__name__", "callback"),
+ "qualname": getattr(value, "__qualname__", None),
+ "module": getattr(value, "__module__", None)}
+ if allow_objects and _is_provider_object(value):
+ return self._describe_object(plugin_key, value)
+ return None
+
+ def _describe_object(self, plugin_key: str, obj: Any) -> dict:
+ """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:
+ continue
+ raw = inspect.getattr_static(obj, name, None)
+ if isinstance(raw, property) or type(raw).__name__ == "cached_property":
+ live.append(name)
+ continue
+ value = getattr(obj, name, None)
+ if callable(value):
+ methods[name] = {"async": is_async_callable(value), "sig": describe_signature(value)}
+ else:
+ static[name] = encode(value)
+ return {"__object__": self._remember(plugin_key, obj), "methods": methods, "live": live,
+ "static": static, "type": type(obj).__name__}
+
+ def resolve_from_parent(self, ref: dict) -> Any:
+ if "__handle__" in ref:
+ return RemoteRegistration(self, int(ref["__handle__"]), str(ref.get("kind") or ""),
+ str(ref.get("key") or ""))
+ return Opaque("callable" if "__callable__" in ref else "object")
+
+ # -- outgoing ---------------------------------------------------------------------------------
+ def _send_call(self, method: str, plugin_key: str, payload: Dict[str, Any], *, allow_objects: bool) -> Any:
+ refs = functools.partial(self.ref_for, plugin_key, allow_objects=allow_objects)
+ payload = {**payload, "plugin": plugin_key,
+ "args": encode(list(payload.pop("args", ())), refs),
+ "kwargs": encode(dict(payload.pop("kwargs", {})), refs)}
+ return decode(self.channel.call(method, payload), self.resolve_from_parent)
+
+ def ctx_call(self, plugin_key: str, method: str, *args: Any, **kwargs: Any) -> Any:
+ from hermes_cli.plugin_isolation import HOST_OBJECT_BASES
+ return self._send_call("ctx", plugin_key, {"method": method, "args": args, "kwargs": kwargs},
+ allow_objects=method in HOST_OBJECT_BASES)
+
+ def facade_call(self, plugin_key: str, facade: str, method: str, *args: Any, _probe: bool = False,
+ **kwargs: Any) -> Any:
+ return self._send_call("facade", plugin_key, {"facade": facade, "method": method, "probe": _probe,
+ "args": args, "kwargs": kwargs}, allow_objects=False)
+
+ 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)
+
+ # -- incoming ---------------------------------------------------------------------------------
+ def handle(self, method: str, params: Dict[str, Any], _origin: Optional[int]) -> Any:
+ handler = _HANDLERS.get(method)
+ if handler is None:
+ raise ValueError(f"unknown plugin host request {method!r}")
+ return handler(self, params)
+
+ def _run(self, result: Any) -> Any:
+ if inspect.isawaitable(result):
+ return asyncio.run_coroutine_threadsafe(_await(result), self.loop).result()
+ return result
+
+ def _encode_result(self, plugin_key: str, value: Any) -> Any:
+ return encode(value, functools.partial(self.ref_for, plugin_key, allow_objects=False))
+
+ def _decode_args(self, params: Dict[str, Any]):
+ return decode(params.get("args") or [], None), decode(params.get("kwargs") or {}, None)
+
+ def op_hello(self, _params: Dict[str, Any]) -> Dict[str, Any]:
+ return {"protocol": PROTOCOL_VERSION, "pid": os.getpid(), "python": sys.version.split()[0]}
+
+ def op_load(self, params: Dict[str, Any]) -> Dict[str, Any]:
+ plugin_key = str(params["plugin_key"])
+ target = _import_plugin(params)
+ register = target if callable(target) and not isinstance(target, types.ModuleType) \
+ else getattr(target, "register", None)
+ if not callable(register):
+ raise AttributeError(f"Plugin '{params.get('name')}' has no register() function")
+ module_name = getattr(target, "__name__", None) or getattr(register, "__module__", None)
+ self.modules[plugin_key] = str(module_name or "")
+ self._run(register(RemotePluginContext(self, plugin_key, params)))
+ return {"module": module_name}
+
+ def op_load_instance(self, params: Dict[str, Any]) -> Any:
+ """Category plugins (memory provider, context engine, cron scheduler): import the directory,
+ run ``register(ctx)`` capturing the one ``capture`` registration, else instantiate the first
+ subclass of ``base``. Other registrations reach Hermes only when it bound a ctx for them."""
+ plugin_key = str(params["plugin_key"])
+ module = _import_plugin(params)
+ self.modules[plugin_key] = module.__name__
+ base = _import_base(str(params["base"]))
+ capture = str(params["capture"])
+ captured: List[Any] = []
+ register = getattr(module, "register", None)
+ if callable(register):
+ ctx = _CapturingContext(self, plugin_key, params, capture, base, captured,
+ forward=bool(params.get("forward")))
+ try:
+ self._run(register(ctx))
+ except Exception as exc:
+ if not captured:
+ logger.debug("register() failed for %s: %s", params.get("name"), exc)
+ if not captured:
+ for attr in dir(module):
+ value = getattr(module, attr, None)
+ if isinstance(value, type) and issubclass(value, base) and value is not base:
+ try:
+ captured.append(value())
+ break
+ except Exception:
+ continue
+ if not captured:
+ return None
+ return self._describe_object(plugin_key, captured[0])
+
+ def op_profile_call(self, params: Dict[str, Any]) -> Any:
+ """Run one overridden method (or callable field) of a model-provider profile, loading the
+ plugin on first use in this host process. Addressed by name, so it survives host restarts."""
+ profiles = self.profiles.get(str(params["path"]))
+ if profiles is None:
+ profiles = self.profiles[str(params["path"])] = {
+ p.name: p for p in capture_profiles(str(params["path"]), str(params["module_name"]))}
+ target = getattr(profiles[str(params["profile"])], str(params["attr"]))
+ args, kwargs = self._decode_args(params)
+ return encode(self._run(target(*args, **kwargs)))
+
+ def op_asgi(self, params: Dict[str, Any]) -> Any:
+ """Serve one dashboard API request with the plugin's FastAPI ``router`` (loaded once)."""
+ api_path = Path(str(params["dashboard_dir"])) / str(params["api_file"])
+ app = self.asgi_apps.get(str(api_path))
+ if app is None:
+ from fastapi import FastAPI
+ module_name = f"hermes_dashboard_plugin_{params['plugin']}"
+ spec = importlib.util.spec_from_file_location(module_name, api_path)
+ if spec is None or spec.loader is None:
+ raise ImportError(f"cannot load dashboard api {api_path}")
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[module_name] = module
+ spec.loader.exec_module(module)
+ router = getattr(module, "router", None)
+ if router is None:
+ raise AttributeError(f"dashboard api {api_path.name} has no 'router'")
+ app = FastAPI()
+ app.include_router(router)
+ self.asgi_apps[str(api_path)] = app
+
+ async def request() -> Dict[str, Any]:
+ import httpx
+ transport = httpx.ASGITransport(app=app)
+ async with httpx.AsyncClient(transport=transport, base_url="http://plugin-host") as client:
+ response = await client.request(
+ str(params["method"]), str(params["path"]), params=str(params.get("query") or ""),
+ headers=[tuple(h) for h in params.get("headers") or []],
+ content=decode(params.get("body")) or b"")
+ return {"status": response.status_code, "headers": list(response.headers.multi_items()),
+ "body": response.content}
+
+ return encode(self._run(request()))
+
+ def op_invoke(self, params: Dict[str, Any]) -> Any:
+ ref = int(params["ref"])
+ fn = self.refs.get(ref)
+ if fn is None:
+ raise LookupError(f"plugin host callable {ref} was released")
+ args, kwargs = self._decode_args(params)
+ return self._encode_result(self.owners.get(ref, ""), self._run(fn(*args, **kwargs)))
+
+ def op_obj_invoke(self, params: Dict[str, Any]) -> Any:
+ ref = int(params["ref"])
+ obj = self.refs.get(ref)
+ if obj is None:
+ raise LookupError(f"plugin host object {ref} was released")
+ method = str(params["method"])
+ if method.startswith("_"):
+ raise AttributeError(method)
+ args, kwargs = self._decode_args(params)
+ 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:
+ obj = self.refs.get(int(params["ref"]))
+ name = str(params["name"])
+ if obj is None or name.startswith("_"):
+ raise AttributeError(name)
+ return self._encode_result(self.owners.get(int(params["ref"]), ""), getattr(obj, name))
+
+ def op_obj_setattr(self, params: Dict[str, Any]) -> None:
+ obj = self.refs.get(int(params["ref"]))
+ name = str(params["name"])
+ if obj is None or name.startswith("_"):
+ raise AttributeError(name)
+ setattr(obj, name, decode(params.get("value"), None))
+
+ def op_unload(self, params: Dict[str, Any]) -> Dict[str, Any]:
+ plugin_key = str(params["plugin_key"])
+ errors = []
+ for callback in reversed(self.unload_callbacks.pop(plugin_key, [])):
+ try:
+ self._run(callback())
+ except Exception as exc:
+ errors.append(f"{type(exc).__name__}: {exc}")
+ with self._lock:
+ for ref in [r for r, owner in self.owners.items() if owner == plugin_key]:
+ self.refs.pop(ref, None)
+ self.owners.pop(ref, None)
+ module_name = self.modules.pop(plugin_key, "")
+ if module_name:
+ for name in [m for m in sys.modules if m == module_name or m.startswith(module_name + ".")]:
+ sys.modules.pop(name, None)
+ return {"errors": errors}
+
+ def op_shutdown(self, _params: Dict[str, Any]) -> None:
+ for plugin_key in list(self.unload_callbacks):
+ self.op_unload({"plugin_key": plugin_key})
+ self.stopped.set()
+
+
+_HANDLERS: Dict[str, Callable[[HostRuntime, Dict[str, Any]], Any]] = {
+ "hello": HostRuntime.op_hello, "load": HostRuntime.op_load, "load_instance": HostRuntime.op_load_instance,
+ "asgi": HostRuntime.op_asgi, "profile_call": HostRuntime.op_profile_call,
+ "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,
+ "shutdown": HostRuntime.op_shutdown,
+}
+
+
+class _CapturingContext(RemotePluginContext):
+ """``register(ctx)`` for a category plugin: the category's own registration is kept here; the rest
+ forward to Hermes when it bound a context (memory providers), else are no-ops."""
+
+ def __init__(self, runtime: HostRuntime, plugin_key: str, info: Dict[str, Any], capture: str,
+ base: type, captured: List[Any], *, forward: bool):
+ super().__init__(runtime, plugin_key, info)
+ self._capture, self._base, self._captured, self._forward = capture, base, captured, forward
+
+ def __getattr__(self, name: str) -> Any:
+ if name == self._capture:
+ def capture(obj: Any, *_args: Any, **_kwargs: Any) -> None:
+ if isinstance(obj, self._base) and not self._captured:
+ self._captured.append(obj)
+ return capture
+ if not self._forward and (name.startswith("register_") or name in {"subscribe"}):
+ return lambda *_args, **_kwargs: None
+ return super().__getattr__(name)
+
+
+def _import_base(ref: str) -> type:
+ module, attr = ref.split(":")
+ return getattr(importlib.import_module(module), attr)
+
+
+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,
+ functools.partial, type)) and type(value).__module__ != "builtins"
+
+
+async def _await(awaitable: Any) -> Any:
+ return 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"):
+ for ep in importlib.metadata.entry_points().select(group=_ENTRY_POINTS_GROUP):
+ if ep.name == params.get("name"):
+ return ep.load()
+ raise ImportError(f"Entry point '{params.get('name')}' not found in group '{_ENTRY_POINTS_GROUP}'")
+ plugin_dir = Path(str(params["path"]))
+ init_file = plugin_dir / "__init__.py"
+ if not init_file.exists():
+ raise FileNotFoundError(f"No __init__.py in {plugin_dir}")
+ module_name = str(params["module_name"])
+ parts = module_name.split(".")[:-1]
+ for i in range(1, len(parts) + 1): # synthetic parent packages (hermes_plugins, _hermes_user_memory)
+ parent = ".".join(parts[:i])
+ if parent not in sys.modules:
+ ns_pkg = types.ModuleType(parent)
+ ns_pkg.__path__ = [] # type: ignore[attr-defined]
+ ns_pkg.__package__ = parent
+ sys.modules[parent] = ns_pkg
+ spec = importlib.util.spec_from_file_location(module_name, init_file,
+ submodule_search_locations=[str(plugin_dir)])
+ if spec is None or spec.loader is None:
+ raise ImportError(f"Cannot create module spec for {init_file}")
+ module = importlib.util.module_from_spec(spec)
+ module.__package__ = module_name
+ module.__path__ = [str(plugin_dir)] # type: ignore[attr-defined]
+ sys.modules[module_name] = module
+ try:
+ spec.loader.exec_module(module)
+ except BaseException:
+ for name in [m for m in sys.modules if m == module_name or m.startswith(module_name + ".")]:
+ sys.modules.pop(name, None)
+ raise
+ return module
+
+
+def _take_protocol_streams():
+ """Duplicate stdin/stdout for the channel, then point fd 0 at /dev/null and fd 1 at stderr."""
+ reader = os.fdopen(os.dup(0), "rb") # windows-footgun: ok — binary protocol stream
+ writer = os.fdopen(os.dup(1), "wb") # windows-footgun: ok — binary protocol stream
+ devnull = os.open(os.devnull, os.O_RDONLY)
+ os.dup2(devnull, 0)
+ os.close(devnull)
+ os.dup2(2, 1)
+ sys.stdin = open(os.devnull, encoding="utf-8-sig") # noqa: SIM115 — lives for the process
+ sys.stdout = sys.stderr
+ return reader, writer
+
+
+def capture_profiles(path: str, module_name: str) -> List[Any]:
+ """Import a model-provider plugin and return the profiles it passes to ``register_provider``."""
+ import providers
+ from providers.base import ProviderProfile
+ providers.list_providers() # bundled + known profiles register before the capture window
+ captured: List[Any] = []
+ original = providers.register_provider
+ providers.register_provider = captured.append # type: ignore[assignment]
+ try:
+ _import_plugin({"path": path, "module_name": module_name, "name": Path(path).name})
+ finally:
+ providers.register_provider = original # type: ignore[assignment]
+ for profile in captured:
+ if type(profile).create_client is not ProviderProfile.create_client:
+ raise PluginHostUnsupported(
+ f"provider profile {getattr(profile, 'name', '?')!r} overrides create_client(), which returns "
+ "a live SDK client; it runs only in-process")
+ return captured
+
+
+def describe_profile(profile: Any) -> Dict[str, Any]:
+ """Profile data (instance fields) plus the methods and callable fields that must run here."""
+ from providers.base import ProviderProfile
+ fields: Dict[str, Any] = {}
+ calls: Dict[str, Any] = {}
+ for name, value in vars(profile).items():
+ if name.startswith("_"):
+ continue
+ if callable(value):
+ calls[name] = {"async": is_async_callable(value), "sig": describe_signature(value), "field": True}
+ else:
+ fields[name] = encode(value)
+ for name in dir(type(profile)):
+ if name.startswith("_") or name in fields or name in calls:
+ continue
+ attr = getattr(type(profile), name)
+ if attr is getattr(ProviderProfile, name, object()):
+ continue
+ if isinstance(inspect.getattr_static(profile, name), property) or not callable(attr):
+ fields[name] = encode(getattr(profile, name))
+ continue
+ calls[name] = {"async": is_async_callable(attr), "sig": describe_signature(getattr(profile, name)),
+ "field": False}
+ return {"name": profile.name, "type": type(profile).__name__, "fields": fields, "calls": calls}
+
+
+def extract_profiles_main(path: str, module_name: str) -> int:
+ """``--extract-profiles``: one-shot, credential-free; prints the profiles as JSON on stdout."""
+ import json
+ reader, writer = _take_protocol_streams()
+ del reader
+ import hermes_bootstrap # noqa: F401
+ try:
+ payload = {"profiles": [describe_profile(p) for p in capture_profiles(path, module_name)]}
+ except Exception as exc:
+ payload = {"error": f"{type(exc).__name__}: {exc}"}
+ writer.write(json.dumps(payload).encode("utf-8"))
+ writer.flush()
+ return 0
+
+
+def main() -> int:
+ reader, writer = _take_protocol_streams()
+ import hermes_bootstrap # noqa: F401 — PM dependency environments, like every Hermes entry point
+ logging.basicConfig(stream=sys.stderr, level=os.environ.get("HERMES_PLUGIN_HOST_LOG_LEVEL", "WARNING"),
+ format="%(levelname)s %(name)s: %(message)s")
+ runtime = HostRuntime(reader, writer)
+ runtime.channel.start()
+ runtime.stopped.wait()
+ runtime.channel.close("host shutdown")
+ return 0
+
+
+if __name__ == "__main__":
+ code = (extract_profiles_main(sys.argv[2], sys.argv[3]) if sys.argv[1:2] == ["--extract-profiles"]
+ else main())
+ sys.stderr.flush()
+ # A plugin thread stuck in a handler must not keep the host alive once Hermes has gone.
+ os._exit(code)
diff --git a/hermes_cli/plugin_host_profiles.py b/hermes_cli/plugin_host_profiles.py
new file mode 100644
index 00000000000..07fe08d794a
--- /dev/null
+++ b/hermes_cli/plugin_host_profiles.py
@@ -0,0 +1,149 @@
+"""Model-provider plugins under ``plugins.isolation: host``.
+
+Model-provider discovery runs while ``hermes_cli.config`` / ``hermes_cli.auth`` are still importing,
+so it must not start the plugin host (building the host's environment imports those same modules).
+Profile DATA therefore comes from a one-shot, credential-free extraction
+(``plugin_host_child --extract-profiles``), cached under the profile home by the plugin's file
+fingerprint. Overridden methods and callable fields run later in the profile's plugin host, addressed
+by (plugin dir, profile name, attribute) so they survive host restarts.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import inspect
+import json
+import logging
+import os
+import subprocess
+import sys
+from pathlib import Path
+from typing import Any, Callable, Dict, List
+
+from hermes_cli.plugin_host_wire import PluginHostUnavailable, decode, signature_from
+
+logger = logging.getLogger(__name__)
+
+_EXTRACT_TIMEOUT_SECS = 60.0
+_CACHE_VERSION = 1
+
+
+def load_hosted_profiles(plugin_dir: Path, module_name: str) -> List[Any]:
+ """ProviderProfile proxies for a model-provider plugin whose code runs in the plugin host."""
+ from providers.base import ProviderProfile
+ payload = _cached_extraction(Path(plugin_dir), module_name)
+ if payload.get("error"):
+ raise PluginHostUnavailable(str(payload["error"]))
+ return [_profile_proxy(ProviderProfile, str(plugin_dir), module_name, entry)
+ for entry in payload.get("profiles") or []]
+
+
+def _fingerprint(plugin_dir: Path) -> str:
+ digest = hashlib.sha256(f"{_CACHE_VERSION}|{sys.executable}".encode())
+ try:
+ from hermes_cli import __version__
+ digest.update(str(__version__).encode())
+ except Exception:
+ pass
+ for path in sorted(plugin_dir.rglob("*")):
+ if not path.is_file() or "__pycache__" in path.parts or ".git" in path.parts:
+ continue
+ stat = path.stat()
+ digest.update(f"{path.relative_to(plugin_dir)}|{stat.st_size}|{stat.st_mtime_ns}".encode())
+ return digest.hexdigest()
+
+
+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"
+ fingerprint = _fingerprint(plugin_dir)
+ try:
+ cached = json.loads(cache.read_text(encoding="utf-8-sig"))
+ if cached.get("fingerprint") == fingerprint and cached.get("module_name") == module_name:
+ return cached["payload"]
+ except (OSError, ValueError, KeyError):
+ pass
+ payload = _extract(plugin_dir, module_name)
+ if not payload.get("error"):
+ cache.parent.mkdir(parents=True, exist_ok=True)
+ tmp = cache.with_suffix(f".{os.getpid()}.tmp")
+ tmp.write_text(json.dumps({"fingerprint": fingerprint, "module_name": module_name,
+ "payload": payload}), encoding="utf-8")
+ os.replace(tmp, cache)
+ return payload
+
+
+def _extract(plugin_dir: Path, module_name: str) -> Dict[str, Any]:
+ """Import the plugin in a throwaway host process with no credentials and read its profiles."""
+ from hermes_cli.plugin_isolation import HOST_PROCESS_ENV, host_launcher
+ from hermes_constants import get_hermes_home
+ repo_root = str(Path(__file__).resolve().parents[1])
+ env = {key: os.environ[key] for key in ("PATH", "LANG", "LC_ALL", "TZ", "SYSTEMROOT") if key in os.environ}
+ env.update(HOME=str(Path.home()), HERMES_HOME=str(get_hermes_home()), PYTHONPATH=repo_root,
+ **{HOST_PROCESS_ENV: "1"})
+ argv = [*host_launcher(), sys.executable, "-m", "hermes_cli.plugin_host_child", "--extract-profiles",
+ str(plugin_dir), module_name]
+ try:
+ done = subprocess.run(argv, stdin=subprocess.DEVNULL, capture_output=True, env=env,
+ timeout=_EXTRACT_TIMEOUT_SECS, check=False)
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ return {"error": f"profile extraction failed: {exc}"}
+ try:
+ return json.loads(done.stdout.decode("utf-8"))
+ except ValueError:
+ tail = done.stderr.decode("utf-8", "replace").strip().splitlines()[-3:]
+ return {"error": f"profile extraction exited {done.returncode}: {' | '.join(tail)}"}
+
+
+def _host_call(plugin_dir: str, module_name: str, profile: str, attr: str) -> Callable[..., Any]:
+ def call(*args: Any, **kwargs: Any) -> Any:
+ from hermes_cli.plugin_isolation import user_plugin_host
+ host = user_plugin_host()
+ if host is None:
+ raise PluginHostUnavailable("plugins.isolation is no longer 'host'; restart Hermes")
+ return host.profile_call(plugin_dir, module_name, profile, attr, args, kwargs)
+ return call
+
+
+def _profile_proxy(base: type, plugin_dir: str, module_name: str, entry: Dict[str, Any]) -> Any:
+ name = str(entry["name"])
+ namespace: Dict[str, Any] = {"__module__": __name__,
+ "__repr__": lambda self_: f"<plugin-host profile {name!r}>"}
+ fields = {key: decode(value) for key, value in (entry.get("fields") or {}).items()}
+ for attr, meta in (entry.get("calls") or {}).items():
+ call = _host_call(plugin_dir, module_name, name, attr)
+ if meta.get("async"):
+ sync_call = call
+
+ async def call(*args: Any, _sync: Callable[..., Any] = sync_call, **kwargs: Any) -> Any:
+ return await asyncio.to_thread(_sync, *args, **kwargs)
+ signature = signature_from(meta.get("sig"))
+ if signature is not None:
+ call.__signature__ = signature # type: ignore[attr-defined]
+ call.__name__ = call.__qualname__ = attr
+ if meta.get("field"):
+ fields[attr] = call
+ else:
+ namespace[attr] = _as_method(call)
+ cls = type(f"Hosted{entry.get('type') or base.__name__}", (base,), namespace)
+ profile = object.__new__(cls)
+ for key, value in fields.items():
+ object.__setattr__(profile, key, value)
+ return profile
+
+
+def _as_method(call: Callable[..., Any]) -> Callable[..., Any]:
+ if asyncio.iscoroutinefunction(call):
+ async def method(self_: Any, *args: Any, **kwargs: Any) -> Any:
+ return await call(*args, **kwargs)
+ else:
+ def method(self_: Any, *args: Any, **kwargs: Any) -> Any:
+ return call(*args, **kwargs)
+ method.__name__ = method.__qualname__ = call.__name__
+ signature = getattr(call, "__signature__", None)
+ if signature is not None: # callers introspect accepted kwargs; bound access drops ``self`` again
+ self_param = inspect.Parameter("self", inspect.Parameter.POSITIONAL_OR_KEYWORD)
+ method.__signature__ = signature.replace( # type: ignore[attr-defined]
+ parameters=[self_param, *signature.parameters.values()])
+ return method
diff --git a/hermes_cli/plugin_host_wire.py b/hermes_cli/plugin_host_wire.py
new file mode 100644
index 00000000000..732bae7269b
--- /dev/null
+++ b/hermes_cli/plugin_host_wire.py
@@ -0,0 +1,325 @@
+"""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
+nested request in the caller's contextvars (profile home, secret scope, session) instead of the
+reader thread's bare context.
+
+Values cross as JSON. Callables and provider objects travel as references the other side turns
+back into proxies; dataclasses become :class:`Record` (dict + attribute access); anything else
+becomes 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.
+"""
+
+from __future__ import annotations
+
+import base64
+import contextvars
+import dataclasses
+import enum
+import itertools
+import json
+import logging
+import threading
+from concurrent.futures import Future, ThreadPoolExecutor
+from pathlib import PurePath
+from typing import Any, BinaryIO, Callable, Dict, Optional
+
+logger = logging.getLogger("hermes_cli.plugins")
+
+PROTOCOL_VERSION = 1
+
+
+class PluginHostError(RuntimeError):
+ """The host (or the parent) raised while serving a request; ``type_name`` is the remote class."""
+
+ def __init__(self, type_name: str, message: str):
+ super().__init__(f"{type_name}: {message}" if type_name else message)
+ self.type_name = type_name
+ self.remote_message = message
+
+
+class PluginHostUnavailable(RuntimeError):
+ """The channel is closed: the host process exited or was never started."""
+
+
+class PluginHostUnsupported(RuntimeError):
+ """A ctx method that cannot cross the plugin-host boundary."""
+
+
+_REMOTE_EXCEPTIONS = {
+ cls.__name__: cls for cls in (ValueError, TypeError, KeyError, FileNotFoundError, PermissionError,
+ NotImplementedError, TimeoutError, LookupError, RuntimeError)
+}
+_REMOTE_EXCEPTIONS["PluginHostUnsupported"] = PluginHostUnsupported
+
+
+def raise_remote(error: Dict[str, Any]) -> None:
+ """Re-raise a remote error, as the builtin type when it is one plugins commonly catch."""
+ type_name = str(error.get("type") or "")
+ message = str(error.get("message") or "")
+ cls = _REMOTE_EXCEPTIONS.get(type_name)
+ if cls is not None:
+ raise cls(message)
+ raise PluginHostError(type_name, message)
+
+
+class Record(dict):
+ """A dataclass that crossed the boundary: item AND attribute access, like the original fields."""
+
+ def __getattr__(self, name: str) -> Any:
+ try:
+ return self[name]
+ except KeyError:
+ raise AttributeError(name) from None
+
+
+class Opaque:
+ """Placeholder for a live object the other process owns (a gateway runner, an SDK client)."""
+
+ def __init__(self, type_name: str, text: str = ""):
+ self.type_name, self.text = type_name, text
+
+ def __getattr__(self, name: str) -> Any:
+ raise AttributeError(f"{self.type_name!r} is a live object in the Hermes process and is not "
+ f"available inside the plugin host (attribute {name!r})")
+
+ def __bool__(self) -> bool:
+ return True
+
+ def __repr__(self) -> str:
+ return f"<opaque {self.type_name}>"
+
+
+def encode(value: Any, refs: Optional[Callable[[Any], Optional[dict]]] = None, _depth: int = 0) -> Any:
+ """JSON-safe form of ``value``; ``refs`` may turn callables/objects into reference dicts."""
+ if value is None or isinstance(value, (bool, int, float, str)):
+ return value
+ if _depth > 64:
+ return {"__opaque__": type(value).__name__, "repr": "<too deep>"}
+ if isinstance(value, enum.Enum):
+ return encode(value.value, refs, _depth + 1)
+ if isinstance(value, PurePath):
+ return str(value)
+ if isinstance(value, (bytes, bytearray)):
+ return {"__bytes__": base64.b64encode(bytes(value)).decode("ascii")}
+ if isinstance(value, dict):
+ return {str(k): encode(v, refs, _depth + 1) for k, v in value.items()}
+ if isinstance(value, (list, tuple, set, frozenset)):
+ return [encode(v, refs, _depth + 1) for v in value]
+ if isinstance(value, Opaque):
+ return {"__opaque__": value.type_name, "repr": value.text}
+ if refs is not None:
+ ref = refs(value)
+ if ref is not None:
+ return ref
+ if dataclasses.is_dataclass(value) and not isinstance(value, type):
+ fields = {f.name: getattr(value, f.name, None) for f in dataclasses.fields(value)}
+ return {"__record__": type(value).__name__, "fields": encode(fields, refs, _depth + 1)}
+ dump = getattr(value, "model_dump", None) # pydantic models
+ if callable(dump) and not isinstance(value, type):
+ try:
+ return {"__record__": type(value).__name__, "fields": encode(dump(), refs, _depth + 1)}
+ except Exception:
+ pass
+ try:
+ text = repr(value)[:200]
+ except Exception:
+ text = ""
+ return {"__opaque__": type(value).__name__, "repr": text}
+
+
+def decode(value: Any, resolve: Optional[Callable[[dict], Any]] = None) -> Any:
+ """Inverse of :func:`encode`; ``resolve`` turns ``__callable__``/``__object__`` refs into proxies."""
+ if isinstance(value, list):
+ return [decode(v, resolve) for v in value]
+ if not isinstance(value, dict):
+ return value
+ if "__record__" in value:
+ return Record(decode(value.get("fields") or {}, resolve))
+ if "__bytes__" in value:
+ return base64.b64decode(value["__bytes__"])
+ if "__opaque__" in value:
+ return Opaque(str(value["__opaque__"]), str(value.get("repr") or ""))
+ if ("__callable__" in value or "__object__" in value or "__handle__" in value) and resolve is not None:
+ return resolve(value)
+ return {k: decode(v, resolve) for k, v in value.items()}
+
+
+def is_async_callable(fn: Any) -> bool:
+ import inspect
+ target = getattr(fn, "__func__", fn)
+ return inspect.iscoroutinefunction(target) or inspect.iscoroutinefunction(getattr(fn, "__call__", None))
+
+
+def describe_signature(fn: Any) -> Optional[list]:
+ """``[[name, kind, has_default], ...]`` so the peer's proxy presents the same parameters (hook
+ dispatch passes only the kwargs a callback declares)."""
+ import inspect
+ try:
+ sig = inspect.signature(fn)
+ except (TypeError, ValueError):
+ return None
+ return [[p.name, int(p.kind), p.default is not inspect.Parameter.empty] for p in sig.parameters.values()]
+
+
+def signature_from(spec: Optional[list]):
+ import inspect
+ if not spec:
+ return None
+ try:
+ return inspect.Signature([
+ inspect.Parameter(name, inspect._ParameterKind(kind),
+ default=None if has_default else inspect.Parameter.empty)
+ for name, kind, has_default in spec
+ ])
+ except (TypeError, ValueError):
+ return None
+
+
+_serving = threading.local()
+
+
+class Channel:
+ """Bidirectional request/response over a pair of byte streams (one JSON document per line)."""
+
+ 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,
+ context_for_origin: Optional[Callable[[Optional[int]], contextvars.Context]] = None):
+ self._reader, self._writer = reader, writer
+ self._handler, self._name, self._on_close = handler, name, on_close
+ self._context_for_origin = context_for_origin
+ self._write_lock = threading.Lock()
+ self._ids = itertools.count(1)
+ 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] = None
+ self._thread = threading.Thread(target=self._read_loop, name=f"{name}-reader", daemon=True)
+
+ def start(self) -> "Channel":
+ self._thread.start()
+ return self
+
+ @property
+ def closed_reason(self) -> Optional[str]:
+ return self._closed_reason
+
+ def context_of(self, request_id: Optional[int]) -> Optional[contextvars.Context]:
+ """Caller context recorded when THIS side sent ``request_id`` (still in flight)."""
+ return self._contexts.get(request_id) if request_id is not None else None
+
+ def request(self, method: str, params: Dict[str, Any], *, timeout: Optional[float] = None) -> Any:
+ if self._closed_reason is not None:
+ raise PluginHostUnavailable(self._closed_reason)
+ request_id = next(self._ids)
+ future: Future = Future()
+ with self._pending_lock:
+ self._pending[request_id] = future
+ self._contexts[request_id] = contextvars.copy_context()
+ message = {"id": request_id, "method": method, "params": params,
+ "origin": getattr(_serving, "request_id", None)}
+ try:
+ self._send(message)
+ return future.result(timeout=timeout)
+ finally:
+ with self._pending_lock:
+ self._pending.pop(request_id, None)
+ self._contexts.pop(request_id, None)
+
+ def _send(self, message: Dict[str, Any]) -> None:
+ data = (json.dumps(message, separators=(",", ":"), allow_nan=True) + "\n").encode("utf-8")
+ with self._write_lock:
+ if self._closed_reason is not None:
+ raise PluginHostUnavailable(self._closed_reason)
+ try:
+ self._writer.write(data)
+ self._writer.flush()
+ except (BrokenPipeError, OSError, ValueError) as exc:
+ self._close(f"{self._name} channel write failed: {exc}")
+ raise PluginHostUnavailable(self._closed_reason or str(exc)) from exc
+
+ def _read_loop(self) -> None:
+ reason = f"{self._name} channel closed"
+ try:
+ for line in iter(self._reader.readline, b""):
+ if not line.strip():
+ continue
+ try:
+ message = json.loads(line)
+ except ValueError:
+ logger.warning("%s: dropped a malformed frame: %.200r", self._name, line)
+ continue
+ if "method" in message:
+ self._pool.submit(self._serve, message)
+ continue
+ with self._pending_lock:
+ future = self._pending.get(message.get("id"))
+ if future is not None and not future.done():
+ future.set_result(message)
+ except (OSError, ValueError) as exc:
+ reason = f"{self._name} channel read failed: {exc}"
+ self._close(reason)
+
+ def _serve(self, message: Dict[str, Any]) -> None:
+ request_id = message.get("id")
+ origin = message.get("origin")
+ context = self._context_for_origin(origin) if self._context_for_origin else None
+
+ def run() -> Dict[str, Any]:
+ _serving.request_id = request_id
+ try:
+ result = self._handler(str(message.get("method")), message.get("params") or {}, origin)
+ return {"id": request_id, "result": result}
+ except BaseException as exc: # a plugin may raise anything, SystemExit included
+ if not isinstance(exc, Exception):
+ logger.warning("%s: request %s raised %s", self._name, message.get("method"),
+ type(exc).__name__)
+ return {"id": request_id, "error": {"type": type(exc).__name__, "message": str(exc)}}
+ finally:
+ _serving.request_id = None
+
+ reply = context.run(run) if context is not None else run()
+ if request_id is None:
+ return
+ try:
+ self._send(reply)
+ except PluginHostUnavailable:
+ pass
+ except (TypeError, ValueError) as exc: # unserializable result slipped past encode()
+ self._send({"id": request_id, "error": {"type": "TypeError", "message": str(exc)}})
+
+ def result_of(self, reply: Dict[str, Any]) -> Any:
+ if "error" in reply:
+ raise_remote(reply["error"])
+ return reply.get("result")
+
+ def call(self, method: str, params: Dict[str, Any], *, timeout: Optional[float] = None) -> Any:
+ return self.result_of(self.request(method, params, timeout=timeout))
+
+ def _close(self, reason: str) -> None:
+ with self._pending_lock:
+ if self._closed_reason is not None:
+ return
+ self._closed_reason = reason
+ pending = list(self._pending.values())
+ 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)
+ except Exception:
+ logger.debug("%s: on_close raised", self._name, exc_info=True)
+
+ def close(self, reason: str = "closed") -> None:
+ self._close(reason)
+ for stream in (self._writer, self._reader):
+ try:
+ stream.close()
+ except OSError:
+ pass
diff --git a/hermes_cli/plugin_isolation.py b/hermes_cli/plugin_isolation.py
new file mode 100644
index 00000000000..1f9d3e1034d
--- /dev/null
+++ b/hermes_cli/plugin_isolation.py
@@ -0,0 +1,136 @@
+"""Where third-party Python plugin code is allowed to run (``plugins.isolation``).
+
+``in_process`` (default) imports every plugin into the Hermes process, as always. ``host`` keeps
+third-party plugin code OUT of it: general plugins load in one plugin-host process per profile
+(:mod:`hermes_cli.plugin_host`) and talk to Hermes only through ``ctx``; every other path that would
+import a user-supplied module in-process (category providers, model-provider profiles, dashboard
+plugin APIs) refuses with a stated reason. Bundled plugins ship with Hermes and stay in-process.
+
+That second half is the property a pooled deployment needs: one Hermes process serving many
+profiles must never share an interpreter with a profile's plugin code. The same boundary gives a
+single-user install crash isolation (a plugin that segfaults or hangs takes down its host, not the
+gateway), which is why it is a plain config value and not a cloud-only switch.
+
+The ctx surface tables below are the single source of truth for both the runtime boundary
+(:mod:`hermes_cli.plugin_host_child` refuses these methods) and the static audit
+(:mod:`hermes_cli.plugin_isolation_audit`), so "the audit says pool-safe" and "it loads in the host"
+cannot drift apart.
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+from typing import Any, Dict, FrozenSet, List, Mapping, Optional
+
+logger = logging.getLogger("hermes_cli.plugins")
+
+ISOLATION_IN_PROCESS = "in_process"
+ISOLATION_HOST = "host"
+_ISOLATION_MODES = frozenset({ISOLATION_IN_PROCESS, ISOLATION_HOST})
+
+# ctx methods that hand a plugin (or receive from it) live objects no process boundary can carry:
+# 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_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",
+ "register_slack_action_handler": "the callback receives native slack_bolt ack/body objects",
+ "register_dashboard_auth_provider": "dashboard auth is owned by the launch process, not a profile",
+ "register_approval_transport": "approval transports hold the live approval request/response channel",
+}
+
+# Registered in-process only; skipped (with a warning, the plugin still loads) inside the host
+# because the surface they extend does not exist in a server process.
+HOST_SKIPPED_CTX_METHODS: Dict[str, str] = {
+ "register_cli_command": "`hermes <command>` subcommands are wired into the local CLI parser",
+}
+
+# Live ctx facades the host reaches by method call; each call returns plain data.
+HOST_REMOTE_FACADES: FrozenSet[str] = frozenset({"state", "llm", "platform_actions", "subagent_lifecycle"})
+
+# Object-taking ctx methods and the ABC the parent checks. The host sends the object's method table
+# and the parent builds a subclass of that ABC whose methods run in the host.
+HOST_OBJECT_BASES: Dict[str, str] = {
+ "register_image_gen_provider": "agent.image_gen_provider:ImageGenProvider",
+ "register_video_gen_provider": "agent.video_gen_provider:VideoGenProvider",
+ "register_web_search_provider": "agent.web_search_provider:WebSearchProvider",
+ "register_browser_provider": "agent.browser_provider:BrowserProvider",
+ "register_terminal_environment_provider": "agent.terminal_env_provider:TerminalEnvironmentProvider",
+ "register_secret_source": "agent.secret_sources.base:SecretSource",
+ "register_tts_provider": "agent.tts_provider:TTSProvider",
+ "register_transcription_provider": "agent.transcription_provider:TranscriptionProvider",
+ "register_context_engine": "agent.context_engine:ContextEngine",
+ "register_context_reference": "agent.context_references:ContextReferenceProvider",
+ "register_memory_provider": "agent.memory_provider:MemoryProvider",
+}
+
+# Hooks whose payload carries live handles (the gateway runner, the session store). In the host the
+# callback receives placeholders for those fields, so a plugin that uses them needs in-process.
+HOST_DEGRADED_HOOKS: Dict[str, str] = {
+ "pre_gateway_dispatch": "receives the live gateway runner and session store",
+}
+
+
+def _plugins_config(config: Optional[Mapping[str, Any]] = None) -> Mapping[str, Any]:
+ if config is None:
+ from hermes_cli.config import load_config_readonly
+ config = load_config_readonly() or {}
+ section = config.get("plugins") if isinstance(config, Mapping) else None
+ return section if isinstance(section, Mapping) else {}
+
+
+# Set in the plugin host's environment: inside the host, plugin code is already out of Hermes, so
+# every loader there imports directly (a host must never spawn a host of its own).
+HOST_PROCESS_ENV = "HERMES_PLUGIN_HOST_PROCESS"
+
+
+def isolation_mode(config: Optional[Mapping[str, Any]] = None) -> str:
+ """``plugins.isolation`` for the active profile; an unknown value warns and means in-process."""
+ if os.environ.get(HOST_PROCESS_ENV) == "1":
+ return ISOLATION_IN_PROCESS
+ raw = _plugins_config(config).get("isolation", ISOLATION_IN_PROCESS)
+ mode = str(raw or ISOLATION_IN_PROCESS).strip().lower().replace("-", "_")
+ if mode not in _ISOLATION_MODES:
+ logger.warning("plugins.isolation=%r is not one of %s; loading plugins in-process",
+ raw, ", ".join(sorted(_ISOLATION_MODES)))
+ return ISOLATION_IN_PROCESS
+ return mode
+
+
+def host_launcher(config: Optional[Mapping[str, Any]] = None) -> List[str]:
+ """``plugins.host.launcher``: argv prefix the host process runs under (a sandbox runner)."""
+ host = _plugins_config(config).get("host")
+ launcher = host.get("launcher") if isinstance(host, Mapping) else None
+ if not launcher:
+ return []
+ if isinstance(launcher, str):
+ import shlex
+ return shlex.split(launcher)
+ return [str(part) for part in launcher]
+
+
+def in_process_import_refusal(what: str, *, source: str = "user",
+ config: Optional[Mapping[str, Any]] = None) -> Optional[str]:
+ """Reason an in-process import of third-party code must not happen, or ``None`` when allowed.
+
+ Every loader that imports a user-supplied module into the Hermes process asks this first;
+ bundled code always passes.
+ """
+ if source == "bundled" or isolation_mode(config) != ISOLATION_HOST:
+ return None
+ return (f"{what} runs only in-process, and plugins.isolation is 'host' (third-party plugin code "
+ f"never runs inside the Hermes process); set plugins.isolation: in_process to load it")
+
+
+def user_plugin_host() -> Any:
+ """The active profile's plugin host when ``plugins.isolation`` is ``host``, else ``None``.
+
+ Category loaders (memory providers, context engines, cron schedulers) ask this before importing
+ a user plugin directory, so the same plugins keep working with their code in the host.
+ """
+ if isolation_mode() != ISOLATION_HOST:
+ return None
+ from hermes_cli.plugins import get_plugin_manager
+ return get_plugin_manager()._plugin_host()
diff --git a/hermes_cli/plugin_isolation_audit.py b/hermes_cli/plugin_isolation_audit.py
new file mode 100644
index 00000000000..2d27dd545ed
--- /dev/null
+++ b/hermes_cli/plugin_isolation_audit.py
@@ -0,0 +1,233 @@
+"""Static answer to "will this plugin run in the plugin host?" (``plugins.isolation: host``).
+
+Reads a plugin directory's manifest and Python source (never imports it) and reports whether the
+plugin reaches Hermes only through ``ctx`` surfaces that cross the host boundary. The rules come
+from :mod:`hermes_cli.plugin_isolation`, the same tables the host enforces at runtime, so a plugin
+the audit calls host-ready loads in the host, and one it flags fails there with the same reason.
+
+What it cannot see in a process boundary it flags:
+
+* ctx methods that hand over live objects (platform adapters, SDK clients, argparse);
+* writing attributes of Hermes modules (monkeypatching): the patch lands in the host's copy;
+* mutating a global registry directly instead of through ``ctx``: the registration lands in the
+ host's registry, which Hermes never reads;
+* gateway platform adapters (``kind: platform``), model-provider profiles that build their own SDK
+ client (``create_client``), and dashboard APIs that stream (the host bridge buffers responses).
+
+``hermes plugins validate`` prints the verdict; ``evals/plugin_isolation/audit_catalog.py`` runs it
+over every catalog entry.
+"""
+
+from __future__ import annotations
+
+import ast
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Any, Dict, List, Mapping, Optional, Set
+
+VERDICT_HOST = "host"
+VERDICT_IN_PROCESS = "in_process"
+VERDICT_PORTABLE = "portable"
+
+# Top-level packages that are Hermes's own process state when imported by a plugin.
+HERMES_PACKAGES: frozenset = frozenset({
+ "agent", "tools", "hermes_cli", "gateway", "cron", "providers", "plugins", "tui_gateway",
+ "acp_adapter", "run_agent", "cli", "model_tools", "toolsets", "hermes_state", "hermes_constants",
+ "hermes_logging", "hermes_time", "utils", "registration_lifecycle", "hermes_platform",
+})
+# ``<module>.<callable>`` that mutate a Hermes-process registry when called from plugin code.
+_DIRECT_REGISTRY_CALLS: frozenset = frozenset({
+ ("tools.registry", "register"), ("tools.registry", "deregister"),
+ ("gateway.platform_registry", "register"), ("providers", "register_provider"),
+})
+_MANIFEST_KIND_REASONS: Dict[str, str] = {
+ "platform": "kind 'platform': gateway platform adapters run in the Hermes process",
+}
+_STREAMING_MARKERS = ("StreamingResponse", "EventSourceResponse", ".websocket(", "WebSocket")
+_SKIP_DIRS = frozenset({"tests", "test", ".git", "__pycache__", "node_modules", ".venv", "venv", "docs"})
+
+
+@dataclass
+class IsolationReport:
+ verdict: str
+ reasons: List[str] = field(default_factory=list)
+ notes: List[str] = field(default_factory=list)
+ ctx_methods: Set[str] = field(default_factory=set)
+
+ @property
+ def host_ready(self) -> bool:
+ return self.verdict in {VERDICT_HOST, VERDICT_PORTABLE}
+
+ def summary(self) -> str:
+ if self.verdict == VERDICT_PORTABLE:
+ return "portable plugin (no Python): runs anywhere"
+ if self.verdict == VERDICT_HOST:
+ return "runs in the plugin host (plugins.isolation: host)"
+ return "in-process only: " + "; ".join(self.reasons)
+
+ def to_dict(self) -> Dict[str, Any]:
+ return {"verdict": self.verdict, "host_ready": self.host_ready, "reasons": list(self.reasons),
+ "notes": list(self.notes), "ctx_methods": sorted(self.ctx_methods)}
+
+
+def _python_files(plugin_dir: Path) -> List[Path]:
+ files = []
+ for path in sorted(plugin_dir.rglob("*.py")):
+ rel = path.relative_to(plugin_dir).parts
+ if any(part in _SKIP_DIRS or part.startswith(".") for part in rel[:-1]):
+ continue
+ if rel[-1].startswith("test_") or rel[-1] == "conftest.py":
+ continue
+ files.append(path)
+ return files
+
+
+class _SourceVisitor(ast.NodeVisitor):
+ """Collects ctx method calls, Hermes-module aliases, and writes through those aliases."""
+
+ def __init__(self, rel: str, *, model_provider: bool = False):
+ from hermes_cli.plugin_isolation import (
+ HOST_DEGRADED_HOOKS, HOST_OBJECT_BASES, HOST_SKIPPED_CTX_METHODS, HOST_UNSUPPORTED_CTX_METHODS,
+ )
+ self._unsupported, self._skipped = HOST_UNSUPPORTED_CTX_METHODS, HOST_SKIPPED_CTX_METHODS
+ self._degraded, self._object_methods = HOST_DEGRADED_HOOKS, HOST_OBJECT_BASES
+ self.rel = rel
+ # A model-provider plugin's register_provider() call is its contract; the host captures it.
+ self.model_provider = model_provider
+ self.aliases: Dict[str, str] = {} # local name -> hermes module path (or module.attr)
+ self.reasons: List[str] = []
+ self.notes: List[str] = []
+ self.ctx_methods: Set[str] = set()
+
+ def _hermes(self, module: str) -> bool:
+ return module.split(".")[0] in HERMES_PACKAGES
+
+ def visit_Import(self, node: ast.Import) -> None:
+ for alias in node.names:
+ if self._hermes(alias.name):
+ self.aliases[alias.asname or alias.name.split(".")[0]] = (
+ alias.name if alias.asname else alias.name.split(".")[0])
+
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
+ if node.level == 0 and node.module and self._hermes(node.module):
+ for alias in node.names:
+ self.aliases[alias.asname or alias.name] = f"{node.module}.{alias.name}"
+
+ def _resolve(self, node: ast.AST) -> Optional[str]:
+ if isinstance(node, ast.Name):
+ return self.aliases.get(node.id)
+ if isinstance(node, ast.Attribute):
+ base = self._resolve(node.value)
+ return f"{base}.{node.attr}" if base else None
+ return None
+
+ def _flag_write(self, target: ast.AST, line: int) -> None:
+ if isinstance(target, ast.Attribute):
+ owner = self._resolve(target.value)
+ if owner:
+ self.reasons.append(f"{self.rel}:{line} patches {owner}.{target.attr} (a Hermes module "
+ f"attribute; the host's copy is not the one Hermes runs)")
+
+ def visit_Assign(self, node: ast.Assign) -> None:
+ for target in node.targets:
+ self._flag_write(target, node.lineno)
+ self.generic_visit(node)
+
+ def visit_AugAssign(self, node: ast.AugAssign) -> None:
+ self._flag_write(node.target, node.lineno)
+ self.generic_visit(node)
+
+ def visit_Call(self, node: ast.Call) -> None:
+ func = node.func
+ if isinstance(func, ast.Name) and func.id == "setattr" and node.args:
+ owner = self._resolve(node.args[0])
+ if owner:
+ self.reasons.append(f"{self.rel}:{node.lineno} setattr() on {owner} (patches a Hermes module)")
+ if isinstance(func, ast.Attribute):
+ name = func.attr
+ if name in self._unsupported:
+ self.reasons.append(f"{self.rel}:{node.lineno} ctx.{name}(): {self._unsupported[name]}")
+ elif name in self._skipped:
+ self.notes.append(f"ctx.{name}() is skipped in the host ({self._skipped[name]})")
+ if name.startswith("register_") or name in {"subscribe", "dispatch_tool", "inject_message", "emit"}:
+ self.ctx_methods.add(name)
+ if name == "register_hook" and node.args and isinstance(node.args[0], ast.Constant) \
+ and node.args[0].value in self._degraded:
+ hook = node.args[0].value
+ self.notes.append(f"hook {hook} {self._degraded[hook]}; those fields are placeholders in the host")
+ self._flag_registry_call(self._resolve(func), node.lineno)
+ elif isinstance(func, ast.Name):
+ self._flag_registry_call(self.aliases.get(func.id), node.lineno)
+ self.generic_visit(node)
+
+ def _flag_registry_call(self, target: Optional[str], line: int) -> None:
+ if not target:
+ return
+ module, _, attr = target.rpartition(".")
+ if self.model_provider and (module, attr) == ("providers", "register_provider"):
+ return
+ if (module, attr) in _DIRECT_REGISTRY_CALLS or (
+ module.endswith("_registry") and attr in {"register", "register_provider"}):
+ self.reasons.append(f"{self.rel}:{line} calls {target}() directly instead of "
+ f"through ctx (registers in the host, not in Hermes)")
+
+ def visit_ClassDef(self, node: ast.ClassDef) -> None:
+ if self.model_provider and any(isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef))
+ and item.name == "create_client" for item in node.body):
+ self.reasons.append(f"{self.rel}:{node.lineno} {node.name}.create_client() returns a live SDK "
+ f"client (model-provider profiles cross the host as data + methods)")
+ self.generic_visit(node)
+
+
+def audit_plugin_dir(plugin_dir: Path, manifest: Optional[Mapping[str, Any]] = None) -> IsolationReport:
+ """Classify one plugin directory without importing it."""
+ plugin_dir = Path(plugin_dir)
+ if manifest is None:
+ manifest = _read_manifest(plugin_dir)
+ if not (plugin_dir / "__init__.py").is_file():
+ return IsolationReport(VERDICT_PORTABLE)
+ reasons: List[str] = []
+ notes: List[str] = []
+ ctx_methods: Set[str] = set()
+ kind = str((manifest or {}).get("kind") or "").strip().lower()
+ if kind in _MANIFEST_KIND_REASONS:
+ reasons.append(_MANIFEST_KIND_REASONS[kind])
+ dashboard = plugin_dir / "dashboard"
+ if (dashboard / "manifest.json").is_file() and '"api"' in (dashboard / "manifest.json").read_text(
+ encoding="utf-8", errors="replace"):
+ api_source = "".join(p.read_text(encoding="utf-8-sig", errors="replace") for p in dashboard.rglob("*.py"))
+ if any(marker in api_source for marker in _STREAMING_MARKERS):
+ reasons.append("dashboard backend API streams (SSE/websocket); the host bridge buffers responses")
+ else:
+ notes.append("dashboard backend API is served through the plugin host (buffered responses)")
+ for path in _python_files(plugin_dir):
+ rel = str(path.relative_to(plugin_dir))
+ try:
+ tree = ast.parse(path.read_text(encoding="utf-8-sig", errors="replace"), filename=rel)
+ except SyntaxError as exc:
+ notes.append(f"{rel}: not parseable ({exc.msg}); not audited")
+ continue
+ visitor = _SourceVisitor(rel, model_provider=kind == "model-provider")
+ visitor.visit(tree)
+ reasons.extend(visitor.reasons)
+ notes.extend(visitor.notes)
+ ctx_methods |= visitor.ctx_methods
+ verdict = VERDICT_IN_PROCESS if reasons else VERDICT_HOST
+ return IsolationReport(verdict, _dedupe(reasons), _dedupe(notes), ctx_methods)
+
+
+def _dedupe(items: List[str]) -> List[str]:
+ return list(dict.fromkeys(items))
+
+
+def _read_manifest(plugin_dir: Path) -> Dict[str, Any]:
+ for name in ("plugin.yaml", "plugin.yml"):
+ path = plugin_dir / name
+ if path.is_file():
+ try:
+ import hermes_yaml as yaml
+ data = yaml.safe_load(path.read_text(encoding="utf-8-sig"))
+ return data if isinstance(data, dict) else {}
+ except Exception:
+ return {}
+ return {}
diff --git a/hermes_cli/plugin_validate.py b/hermes_cli/plugin_validate.py
index e0a96d1a28e..b31f97d6fe2 100644
--- a/hermes_cli/plugin_validate.py
+++ b/hermes_cli/plugin_validate.py
@@ -42,6 +42,7 @@ class ValidationReport:
checks: List[Tuple[str, bool, str]] = field(default_factory=list)
warnings: List[str] = field(default_factory=list)
+ isolation: Optional[Dict[str, Any]] = None # plugin-host readiness; informational, never fails
@property
def failures(self) -> List[str]:
@@ -69,6 +70,7 @@ class ValidationReport:
for name, ok, detail in self.checks
],
"warnings": list(self.warnings),
+ "isolation": self.isolation,
}
@@ -520,6 +522,8 @@ def validate_plugin_dir(plugin_dir: Path) -> ValidationReport:
check_core_override(report, plugin_dir)
check_desktop_surface(report, plugin_dir)
check_language_packs(report, manifest, plugin_dir)
+ from hermes_cli.plugin_isolation_audit import audit_plugin_dir
+ report.isolation = audit_plugin_dir(plugin_dir, manifest).to_dict()
return report
@@ -624,4 +628,6 @@ def _validate_portable_plugin(report: ValidationReport, plugin_dir: Path) -> Val
report.add(f"server availability: {server_name}", True, detail)
_check_security_scan(report, plugin_dir)
check_desktop_surface(report, plugin_dir)
+ from hermes_cli.plugin_isolation_audit import audit_plugin_dir
+ report.isolation = audit_plugin_dir(plugin_dir, manifest).to_dict()
return report
diff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.py
index 29b6ec0b5ef..eb222694148 100644
--- a/hermes_cli/plugins_cmd_catalog.py
+++ b/hermes_cli/plugins_cmd_catalog.py
@@ -788,6 +788,12 @@ def cmd_validate(path: str, as_json: bool = False, install_deps: bool = False) -
+ (f" [dim]— {detail}[/dim]" if detail else ""))
for warning in report.warnings:
console.print(f"[yellow]⚠ {warning}[/yellow]")
+ if report.isolation:
+ from hermes_cli.plugin_isolation_audit import IsolationReport
+ iso = IsolationReport(report.isolation["verdict"], report.isolation["reasons"], report.isolation["notes"])
+ console.print(f"{'[green]◆[/green]' if iso.host_ready else '[dim]◇[/dim]'} Isolation [dim]— {iso.summary()}[/dim]")
+ for note in iso.notes:
+ console.print(f" [dim]· {note}[/dim]")
console.print()
console.print("[green bold]Validation passed.[/green bold]" if report.ok else "[red bold]Validation failed.[/red bold]")
sys.exit(report.exit_code)
diff --git a/hermes_cli/plugins_cmd_listing.py b/hermes_cli/plugins_cmd_listing.py
index fb73023b606..c7dad8ec9d5 100644
--- a/hermes_cli/plugins_cmd_listing.py
+++ b/hermes_cli/plugins_cmd_listing.py
@@ -134,6 +134,14 @@ def cmd_show(name: str) -> None:
console.print(f"[dim]Status:[/dim] {status}")
console.print(f"[dim]Source:[/dim] {source}")
console.print(f"[dim]Key:[/dim] {key}")
+ if dir_path and source != "bundled":
+ from hermes_cli.plugin_isolation import ISOLATION_HOST, isolation_mode
+ from hermes_cli.plugin_isolation_audit import audit_plugin_dir
+ audit = audit_plugin_dir(Path(dir_path), manifest)
+ runs_in = ("plugin host" if isolation_mode() == ISOLATION_HOST and audit.host_ready
+ else "refused (plugins.isolation: host)" if isolation_mode() == ISOLATION_HOST
+ else "Hermes process")
+ console.print(f"[dim]Runs in:[/dim] {runs_in} [dim]— {audit.summary()}[/dim]")
console.print("[dim]Emits:[/dim] " + (", ".join(emits) if emits else "[dim](none)[/dim]"))
console.print("[dim]Listens:[/dim] " + (", ".join(listens) if listens else "[dim](none)[/dim]"))
console.print()
diff --git a/hermes_cli/plugins_loader.py b/hermes_cli/plugins_loader.py
index 5290606f963..a0d4422f4b5 100644
--- a/hermes_cli/plugins_loader.py
+++ b/hermes_cli/plugins_loader.py
@@ -455,12 +455,17 @@ class PluginLoaderMixin:
module_name = self._policy_module_name(manifest)
self._track_tool_override_policy(manifest, module_name)
ctx = PluginContext(manifest, self)
+ in_host = self._runs_in_plugin_host(manifest)
def _import_and_register() -> bool:
"""Import + register() — the part a plugin controls, so the part the deadline covers."""
# Declared language packs register before any plugin code runs, inside the same ledger slice
# so a failing register() unwinds them too.
self._register_declared_locales(manifest, ctx)
+ if in_host and not self._is_manifest_only_language_pack(manifest):
+ self._plugin_host().load(manifest, ctx, module_name=module_name,
+ entrypoint=manifest.source not in {"user", "project"})
+ return True
# Reuse a deferred platform's already-imported package so its body doesn't run twice.
# See #78050.
module = self._predeclared_modules.pop(plugin_key, None)
@@ -535,6 +540,19 @@ class PluginLoaderMixin:
logger.warning("Plugin '%s' declares provides_locales %r but %s has no %s.yaml",
manifest.name, lang_id, locales_dir, lang_id)
+ def _runs_in_plugin_host(self, manifest: PluginManifest) -> bool:
+ """``plugins.isolation: host`` sends every non-bundled Python plugin to the profile's host."""
+ from hermes_cli.plugin_isolation import ISOLATION_HOST, isolation_mode
+ return manifest.source != "bundled" and isolation_mode() == ISOLATION_HOST
+
+ def _plugin_host(self) -> Any:
+ """This manager's plugin host (one process per profile home), created on first use."""
+ host = getattr(self, "_plugin_host_instance", None)
+ if host is None:
+ from hermes_cli.plugin_host import PluginHost
+ host = self._plugin_host_instance = PluginHost(self)
+ return host
+
def _track_tool_override_policy(self, manifest: PluginManifest, module_name: str) -> None:
"""Install the plugin's tool-override policy in tools.registry as a ledger-owned lease."""
from hermes_cli.plugins import PluginContext
diff --git a/hermes_cli/web_server_dashboard.py b/hermes_cli/web_server_dashboard.py
index ae014fc5383..a3ac854f8a6 100644
--- a/hermes_cli/web_server_dashboard.py
+++ b/hermes_cli/web_server_dashboard.py
@@ -1,6 +1,7 @@
"""Dashboard UI assets: SPA mount, theme normalisation/bootstrap CSS, dashboard-plugin discovery and the plugins-hub merge.
"""
+import asyncio
import logging
import importlib.util
import json
@@ -802,6 +803,29 @@ async def _plugin_route_secret_scope(profile: Optional[str] = None):
yield
+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 profile
+ scope still apply here first). Responses are buffered: streaming and websockets need in-process."""
+ name, dashboard_dir = plugin["name"], str(plugin["_dir"])
+
+ async def forward(request: Request, path: str = "") -> Response:
+ from hermes_cli.plugins import get_plugin_manager
+ host = get_plugin_manager()._plugin_host()
+ result = await asyncio.to_thread(
+ host.asgi_request, name, dashboard_dir, api_file_name, 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)
+
+ app.add_api_route(f"/api/plugins/{name}/{{path:path}}", forward, include_in_schema=False,
+ methods=["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"],
+ dependencies=[Depends(_plugin_route_secret_scope)])
+ _log.info("Mounted plugin API routes via the plugin host: /api/plugins/%s/", name)
+
+
def _mount_plugin_api_routes():
"""Import and mount backend API routes from plugins that declare them.
@@ -834,6 +858,11 @@ def _mount_plugin_api_routes():
if skip:
_log.debug("Plugin %s: skipping API mount (%s)", plugin.get("name", ""), skip)
continue
+ if plugin.get("source") not in ("bundled", "project"):
+ from hermes_cli.plugin_isolation import ISOLATION_HOST, isolation_mode
+ if isolation_mode() == ISOLATION_HOST:
+ _mount_hosted_plugin_api(app, plugin, api_file_name)
+ continue
if plugin.get("source") == "project":
_log.warning(
"Plugin %s: ignoring backend api=%s (project plugins may "
diff --git a/plugins/context_engine/__init__.py b/plugins/context_engine/__init__.py
index c54a69ad588..b4a20f0bb2f 100644
--- a/plugins/context_engine/__init__.py
+++ b/plugins/context_engine/__init__.py
@@ -74,6 +74,11 @@ def _load_engine_from_dir(engine_dir: Path) -> Optional["ContextEngine"]: # noq
name = engine_dir.name
is_bundled = engine_dir.parent == _CONTEXT_ENGINE_PLUGINS_DIR
module_name = f"plugins.context_engine.{name}" if is_bundled else f"{_USER_NAMESPACE}.{name}"
+ from hermes_cli.plugin_isolation import user_plugin_host
+ host = None if is_bundled else user_plugin_host()
+ if host is not None:
+ return host.load_instance(engine_dir, module_name=module_name, capture="register_context_engine",
+ base_ref="agent.context_engine:ContextEngine")
mod = _loader.load_plugin_module(
module_name, engine_dir, parents=("plugins", "plugins.context_engine"), logger=logger,
synthetic_namespace=None if is_bundled else _USER_NAMESPACE)
diff --git a/plugins/cron_providers/__init__.py b/plugins/cron_providers/__init__.py
index a22d04acc8f..a4485e7e576 100644
--- a/plugins/cron_providers/__init__.py
+++ b/plugins/cron_providers/__init__.py
@@ -78,6 +78,11 @@ def _load_provider_from_dir(provider_dir: Path) -> Optional["CronScheduler"]: #
name = provider_dir.name
is_bundled = _CRON_PLUGINS_DIR in provider_dir.parents or provider_dir.parent == _CRON_PLUGINS_DIR
module_name = f"plugins.cron_providers.{name}" if is_bundled else f"{_USER_NAMESPACE}.{name}"
+ from hermes_cli.plugin_isolation import user_plugin_host
+ host = None if is_bundled else user_plugin_host()
+ if host is not None:
+ return host.load_instance(provider_dir, module_name=module_name, capture="register_cron_scheduler",
+ base_ref="cron.scheduler_provider:CronScheduler")
mod = _loader.load_plugin_module(
module_name, provider_dir, parents=("plugins", "plugins.cron_providers"), logger=logger,
synthetic_namespace=None if is_bundled else _USER_NAMESPACE)
diff --git a/plugins/memory/__init__.py b/plugins/memory/__init__.py
index 2506f737965..16a81cd2b20 100644
--- a/plugins/memory/__init__.py
+++ b/plugins/memory/__init__.py
@@ -212,6 +212,11 @@ def load_memory_provider(name: str, *, register_skills: Optional[bool] = None) -
def _load(_dir):
if provider_dir:
return _load_provider_from_dir(provider_dir, register_skills=register_skills)
+ from hermes_cli.plugin_isolation import in_process_import_refusal
+ refusal = in_process_import_refusal(f"pip-installed memory provider {name!r}")
+ if refusal:
+ logger.warning("%s", refusal)
+ return None
return _load_provider_from_entry_point(entry_point, register_skills=register_skills)
return _loader.load_named(name, provider_dir, _load, kind="Memory provider", noun="provider", logger=logger)
@@ -228,6 +233,9 @@ def import_memory_provider_module(name: Optional[str] = None) -> bool:
name = name or _get_active_memory_provider()
if not name:
return False
+ from hermes_cli.plugin_isolation import ISOLATION_HOST, isolation_mode
+ if isolation_mode() == ISOLATION_HOST and not _is_bundled(find_provider_dir(name) or Path("/")):
+ return False # third-party code runs in the plugin host; nothing to warm in this process
imported = False
try:
if provider_dir := find_provider_dir(name):
@@ -332,6 +340,11 @@ def _load_provider_from_entry_point(entry_point, *, register_skills: bool = True
def _load_provider_from_dir(provider_dir: Path, *, register_skills: bool = True) -> Optional["MemoryProvider"]:
"""Import a provider module; ``register(ctx)`` first, else a top-level subclass."""
name = provider_dir.name
+ 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:
+ return _ProviderCollector(name, register_skills=register_skills).collect_in_host(
+ host, provider_dir, _module_name(provider_dir, name))
mod = _load_package(provider_dir, name)
if mod is None:
return None
@@ -382,6 +395,21 @@ class _ProviderCollector:
manager._drop_fallback_hooks(self._hook_source)
register(self)
+ def collect_in_host(self, host, provider_dir: Path, module_name: str):
+ """``collect`` for a provider whose code runs in the plugin host: the host captures the
+ provider and forwards every other registration here. The discovery lock is NOT held across
+ the host call — its registrations arrive on another thread and take the lock themselves."""
+ from hermes_cli.plugins_ledger import _hook_source_of
+
+ 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)
+ self.provider = host.load_instance(
+ provider_dir, module_name=module_name, capture="register_memory_provider",
+ base_ref="agent.memory_provider:MemoryProvider", ctx=self)
+ return self.provider
+
def register_hook(self, hook_name, callback):
context = self._plugin_context()
with context._manager._discovery_lock:
@@ -498,6 +526,10 @@ def discover_plugin_cli_commands() -> List[dict]:
return []
module_name = _module_name(plugin_dir, active_provider) + ".cli"
+ if not _is_bundled(plugin_dir):
+ from hermes_cli.plugin_isolation import in_process_import_refusal
+ if in_process_import_refusal(f"memory provider {active_provider!r} CLI commands"):
+ return []
try:
cli_mod = sys.modules.get(module_name)
if cli_mod is None:
diff --git a/plugins/plugin_loader.py b/plugins/plugin_loader.py
index f21c1a5effc..53911ce8200 100644
--- a/plugins/plugin_loader.py
+++ b/plugins/plugin_loader.py
@@ -99,6 +99,12 @@ def load_plugin_module(module_name: str, plugin_dir: Path, *, parents: Tuple[str
init_file = plugin_dir / "__init__.py"
if not init_file.exists():
return None
+ if synthetic_namespace: # user code: never imported in-process under plugins.isolation: host
+ from hermes_cli.plugin_isolation import in_process_import_refusal
+ refusal = in_process_import_refusal(f"plugin {plugin_dir.name!r} (loaded as {module_name})")
+ if refusal:
+ logger.warning("%s", refusal)
+ return None
# A synthetic package shell has no __file__; only reuse modules loaded from disk.
cached = sys.modules.get(module_name)
if cached is not None and getattr(cached, "__file__", None):
diff --git a/providers/__init__.py b/providers/__init__.py
index 9787b61a55b..4d253aacfb0 100644
--- a/providers/__init__.py
+++ b/providers/__init__.py
@@ -399,6 +399,20 @@ def _import_plugin_dir(plugin_dir: Path, source: str, *, home_key: str = "") ->
init_file = plugin_dir / "__init__.py"
if not init_file.exists():
return
+ if source != "bundled":
+ from hermes_cli.plugin_isolation import ISOLATION_HOST, isolation_mode
+ if isolation_mode() == ISOLATION_HOST: # the plugin's code runs in the plugin host
+ from hermes_cli.plugin_host_profiles import load_hosted_profiles
+ _current_source = source
+ try:
+ for profile in load_hosted_profiles(plugin_dir, _user_module_name(plugin_dir, home_key)):
+ register_provider(profile)
+ except Exception as exc:
+ logger.warning("Failed to load user provider plugin %s in the plugin host: %s",
+ plugin_dir.name, exc)
+ finally:
+ _current_source = None
+ return
# Give bundled plugins a stable import path (``plugins.model_providers.<name>``)
# so relative imports within the plugin work. User plugins load via
@@ -499,6 +513,11 @@ def _discover_entry_point_providers() -> None:
"entry-point provider %r skipped: not enabled in config", ep.name
)
continue
+ from hermes_cli.plugin_isolation import in_process_import_refusal
+ refusal = in_process_import_refusal(f"pip-installed model-provider plugin {ep.name!r}")
+ if refusal:
+ logger.warning("%s", refusal)
+ continue
try:
loaded = ep.load()
except Exception as exc:
diff --git a/tests/hermes_cli/test_plugin_host.py b/tests/hermes_cli/test_plugin_host.py
new file mode 100644
index 00000000000..ffd5e5b29c9
--- /dev/null
+++ b/tests/hermes_cli/test_plugin_host.py
@@ -0,0 +1,159 @@
+"""plugins.isolation: host — third-party plugins run in a per-profile host process, reached only via ctx."""
+
+import json
+import os
+import sys
+import time
+
+import hermes_yaml as yaml
+import pytest
+
+from hermes_cli import plugins as plugins_mod
+from hermes_cli.plugins import PluginManager
+
+PROBE_PLUGIN = '''
+import json, os
+from agent.image_gen_provider import ImageGenProvider
+
+class Painter(ImageGenProvider):
+ @property
+ def name(self):
+ return "hostpainter"
+ def generate(self, prompt, aspect_ratio="landscape", **kw):
+ return {"success": True, "image": f"{prompt}@{os.getpid()}"}
+
+SEEN = []
+
+def register(ctx):
+ ctx.register_tool(name="hostprobe_pid", toolset="hostprobe", schema={"name": "hostprobe_pid",
+ "description": "d", "parameters": {"type": "object", "properties": {}}},
+ handler=lambda args, **kw: json.dumps({"pid": os.getpid(), "seen": SEEN, "x": args.get("x")}))
+ ctx.register_tool(name="hostprobe_nested", toolset="hostprobe", schema={"name": "hostprobe_nested",
+ "description": "d", "parameters": {"type": "object", "properties": {}}},
+ handler=lambda args, **kw: ctx.dispatch_tool("hostprobe_pid", {"x": "nested"}))
+ ctx.register_tool(name="hostprobe_crash", toolset="hostprobe", schema={"name": "hostprobe_crash",
+ "description": "d", "parameters": {"type": "object", "properties": {}}},
+ handler=lambda args, **kw: os._exit(3))
+ ctx.register_hook("post_tool_call", lambda tool_name=None, **kw: SEEN.append(tool_name))
+ ctx.register_image_gen_provider(Painter())
+'''
+
+PLATFORM_PLUGIN = '''
+def register(ctx):
+ ctx.register_platform("x", "X", adapter_factory=lambda cfg: None, check_fn=lambda: True)
+'''
+
+
+def _home_with_plugins(tmp_path, monkeypatch, plugins: dict, isolation="host"):
+ home = tmp_path / ".hermes"
+ home.mkdir(parents=True, exist_ok=True)
+ for name, body in plugins.items():
+ 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": list(plugins), "isolation": isolation}}), 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
+
+
[email protected](sys.platform == "win32", reason="POSIX process semantics (os._exit child)")
+def test_plugin_runs_out_of_process_with_ctx_round_trips_and_survives_host_crash(tmp_path, monkeypatch):
+ from agent import image_gen_registry
+ from agent.image_gen_provider import ImageGenProvider
+ from tools.registry import registry
+
+ _home_with_plugins(tmp_path, monkeypatch, {"hostprobe": PROBE_PLUGIN, "platformprobe": PLATFORM_PLUGIN})
+ manager = PluginManager()
+ manager.discover_and_load()
+ try:
+ # The plugin's code never entered this interpreter, yet its registrations are ordinary.
+ assert not any("hostprobe" in name for name in sys.modules)
+ assert manager._plugins["hostprobe"].error is None
+ first = json.loads(registry.dispatch("hostprobe_pid", {"x": 1}, scope=manager.scope_key))
+ host_pid = first["pid"]
+ assert host_pid != os.getpid()
+ # A handler calling back into Hermes while Hermes waits on it (nested ctx.dispatch_tool).
+ nested = json.loads(registry.dispatch("hostprobe_nested", {}, scope=manager.scope_key))
+ assert nested["pid"] == host_pid and nested["x"] == "nested"
+ # Hooks fire in the host; provider objects arrive as instances of the ABC Hermes checks.
+ manager.invoke_hook("post_tool_call", tool_name="read_file", args={}, result="ok")
+ assert "read_file" in json.loads(registry.dispatch("hostprobe_pid", {}, scope=manager.scope_key))["seen"]
+ painter = image_gen_registry.get_provider("hostpainter")
+ assert isinstance(painter, ImageGenProvider)
+ assert painter.generate("cat") == {"success": True, "image": f"cat@{host_pid}"}
+ # Live-object ctx surfaces fail the plugin with the boundary's reason, not a crash.
+ assert "register_platform" in str(manager._plugins["platformprobe"].error)
+
+ # A plugin killing its host costs one tool error; Hermes keeps running and the host restarts.
+ crashed = registry.dispatch("hostprobe_crash", {}, scope=manager.scope_key)
+ assert "plugin host" in crashed
+ deadline, result = time.monotonic() + 15, ""
+ while time.monotonic() < deadline:
+ result = registry.dispatch("hostprobe_pid", {}, scope=manager.scope_key)
+ if '"pid"' in result:
+ break
+ time.sleep(0.2)
+ assert json.loads(result)["pid"] not in {host_pid, os.getpid()}
+ finally:
+ manager.unload()
+ manager._plugin_host().shutdown()
+
+
+def test_isolation_host_keeps_every_user_import_path_out_of_process(tmp_path, monkeypatch):
+ from hermes_cli.plugin_isolation_audit import audit_plugin_dir
+ from plugins import plugin_loader
+
+ home = _home_with_plugins(tmp_path, monkeypatch, {"platformprobe": PLATFORM_PLUGIN, "fine": PROBE_PLUGIN})
+ # Category loaders' in-process import refuses user code under host isolation (the backstop
+ # behind the memory / context-engine / cron host routes).
+ import logging
+ assert plugin_loader.load_plugin_module(
+ "_hermes_user_x.fine", home / "plugins" / "fine", parents=("_hermes_user_x",),
+ logger=logging.getLogger("t"), synthetic_namespace="_hermes_user_x") is None
+ assert "_hermes_user_x.fine" not in sys.modules
+ # The static audit reads the same boundary table the host enforces.
+ assert audit_plugin_dir(home / "plugins" / "fine").verdict == "host"
+ blocked = audit_plugin_dir(home / "plugins" / "platformprobe")
+ assert blocked.verdict == "in_process" and "register_platform" in blocked.reasons[0]
+
+
+MODEL_PROVIDER_PLUGIN = '''
+import os
+from providers import register_provider
+from providers.base import ProviderProfile
+
+class HostModel(ProviderProfile):
+ def build_extra_body(self, *, session_id=None, **context):
+ return {"pid": os.getpid(), "session_id": session_id}
+
+register_provider(HostModel(name="hostmodel", base_url="https://hostmodel.example/v1", env_vars=("HOSTMODEL_KEY",)))
+'''
+
+
+def test_model_provider_profile_data_is_local_and_overrides_run_in_the_host(tmp_path, monkeypatch):
+ import providers
+
+ home = _home_with_plugins(tmp_path, monkeypatch, {})
+ plugin_dir = home / "plugins" / "model-providers" / "hostmodel"
+ plugin_dir.mkdir(parents=True)
+ (plugin_dir / "plugin.yaml").write_text("name: hostmodel\nkind: model-provider\n", encoding="utf-8")
+ (plugin_dir / "__init__.py").write_text(MODEL_PROVIDER_PLUGIN, encoding="utf-8")
+ profile = providers.get_provider_profile("hostmodel")
+ try:
+ 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 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
+ if host is not None:
+ host.shutdown()