The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(plugins): register_hook(..., hold_stream=True) for transform_llm_output
Teknium2eec2a7d2401
diff --git a/hermes_cli/plugin_validate.py b/hermes_cli/plugin_validate.pyindex ea88f7ce2a7..c6e609e9fb2 100644--- a/hermes_cli/plugin_validate.py+++ b/hermes_cli/plugin_validate.py@@ -232,7 +232,7 @@ class RecordingContext:def register_tool(self, name, *args, **kwargs):recorded["tools"].append(str(name))- def register_hook(self, hook_name, callback):+ def register_hook(self, hook_name, callback, *, hold_stream=False):recorded["hooks"].append(str(hook_name))def register_middleware(self, kind, callback):diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 4c9232552f7..eda71a0ee43 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -932,9 +932,9 @@ class PluginContext(PluginCapabilityCtxMixin):logger.warning("Plugin '%s' locale file %s skipped: %s", self.manifest.name, file, exc)return handles- def register_hook(self, hook_name: str, callback: Callable) -> PluginRegistration:- """Register a lifecycle hook callback (unknown names warn but are still stored)."""- return self._track_callback("hook", hook_name, callback, self._manager._hooks, VALID_HOOKS)+ def register_hook(self, hook_name: str, callback: Callable, *, hold_stream: bool = False) -> PluginRegistration:+ """Register a lifecycle hook callback (``PluginDispatchMixin.track_hook``)."""+ return self._manager.track_hook(self, hook_name, callback, hold_stream=hold_stream)def register_middleware(self, kind: str, callback: Callable) -> PluginRegistration:"""Register behavior-changing middleware (request kinds rewrite the payload, execution kindsdiff --git a/hermes_cli/plugins_dispatch.py b/hermes_cli/plugins_dispatch.pyindex accb9c5ddc1..eb35086e609 100644--- a/hermes_cli/plugins_dispatch.py+++ b/hermes_cli/plugins_dispatch.py@@ -66,6 +66,18 @@ _HOOK_TIMEOUT_SUPPRESSION_SECONDS = 60.0_HOOK_MAX_ABANDONED_WORKERS = 3_PRE_TOOL_CALL_TIMEOUT_BLOCK_MESSAGE = "pre_tool_call plugin callback timed out or is still running"+# The one hook whose callback rewrites the reply the user would otherwise see streaming.+STREAM_HOLDING_HOOK = "transform_llm_output"+++def stream_held() -> bool:+ """True when a plugin loaded in the active profile registered ``transform_llm_output`` with+ ``hold_stream=True``: that profile's replies reach the user only as the rewritten final.+ Lazy-discovers first, like ``has_hook``."""+ from hermes_cli.plugins import _delivery_manager++ return _delivery_manager().holds_stream()+def _policy_error_block_directive(hook_name: str, cb: Callable, exc: BaseException) -> dict[str, str]:"""Block directive for a fail-closed hook whose callback raised: names the callback and the@@ -534,6 +546,24 @@ class PluginDispatchMixin:return Falsereturn bool(self._hooks.get(hook_name))+ def track_hook(self, context: Any, hook_name: str, callback: Callable, *, hold_stream: bool = False):+ """Register ``callback`` for ``hook_name`` on behalf of ``context`` (unknown names warn but are+ still stored). ``hold_stream=True`` on ``transform_llm_output`` declares the rewrite must reach+ the user first, so this profile's replies are not streamed (:meth:`holds_stream`)."""+ from hermes_cli.plugins import VALID_HOOKS++ handle = context._track_callback("hook", hook_name, callback, self._hooks, VALID_HOOKS)+ if hold_stream and hook_name != STREAM_HOLDING_HOOK:+ logger.warning("Plugin '%s' set hold_stream on '%s'; only %s rewrites the reply, ignored",+ context.manifest.name, hook_name, STREAM_HOLDING_HOOK)+ else:+ handle.hold_stream = hold_stream+ return handle++ def holds_stream(self) -> bool:+ """True while a loaded plugin's ``transform_llm_output`` registration declared ``hold_stream``."""+ return any(r.hold_stream for owned in self._ownership_ledger.values() for r in owned)+async def ainvoke_hook(self, hook_name: str, **kwargs: Any) -> list[Any]:""":meth:`invoke_hook` for callers that are already on an event loop.diff --git a/hermes_cli/plugins_ledger.py b/hermes_cli/plugins_ledger.pyindex 5df35196b72..4f35251fa3e 100644--- a/hermes_cli/plugins_ledger.py+++ b/hermes_cli/plugins_ledger.py@@ -39,6 +39,9 @@ class PluginRegistration:# re-discovery when the plugin no longer re-registers it.# See #91701.persistent: bool = False+ # A ``transform_llm_output`` registration that must see the reply before the user does+ # (``register_hook(..., hold_stream=True)``; read by ``PluginDispatchMixin.holds_stream``).+ hold_stream: bool = False_disposed: bool = field(default=False, init=False, repr=False)_on_dispose: Optional[Callable[[PluginRegistration], None]] = field(default=None, init=False, repr=False)@@ -189,14 +192,15 @@ class PluginLedgerMixin:handle.dispose()def _register_fallback_hook(self, context: Any, hook_source: Optional[tuple], hook_name: str,- callback: Callable) -> PluginRegistration:+ callback: Callable, *, hold_stream: bool = False) -> PluginRegistration:"""Register ``callback`` unless the same source is already live through general discovery, inwhich case return an inert handle so the provider keeps its disposable-handle contract."""if hook_source is None:- return context.register_hook(hook_name, callback)+ return context.register_hook(hook_name, callback, hold_stream=hold_stream)owned = any(loaded.enabled and _hook_source_of(loaded.manifest.name, loaded.module) == hook_sourcefor loaded in self._plugins.values())- handle = context._track("hook", hook_name, lambda: None) if owned else context.register_hook(hook_name, callback)+ handle = (context._track("hook", hook_name, lambda: None) if owned+ else context.register_hook(hook_name, callback, hold_stream=hold_stream))self._memory_hook_registrations.setdefault(hook_source, []).append(handle)return handlediff --git a/plugins/memory/__init__.py b/plugins/memory/__init__.pyindex 5df42ac9c93..e2c8177fdc1 100644--- a/plugins/memory/__init__.py+++ b/plugins/memory/__init__.py@@ -436,10 +436,11 @@ class _ProviderCollector:base_ref="agent.memory_provider:MemoryProvider", ctx=self, before_reload=drop_hooks)return self.provider- def register_hook(self, hook_name, callback):+ def register_hook(self, hook_name, callback, *, hold_stream=False):context = self._plugin_context()with context._manager._discovery_lock:- return context._manager._register_fallback_hook(context, self._hook_source, hook_name, callback)+ return context._manager._register_fallback_hook(+ context, self._hook_source, hook_name, callback, hold_stream=hold_stream)def register_memory_provider(self, provider):self.provider = providerdiff --git a/tests/hermes_cli/test_plugin_hold_stream.py b/tests/hermes_cli/test_plugin_hold_stream.pynew file mode 100644index 00000000000..d8b050e91c3--- /dev/null+++ b/tests/hermes_cli/test_plugin_hold_stream.py@@ -0,0 +1,65 @@+"""``register_hook("transform_llm_output", fn, hold_stream=True)``: the declaration and its scope.++A plugin that rewrites the reply (redaction) must see it before the user does. Declaring+``hold_stream=True`` holds the streamed reply of every session in that plugin's profile; a plain+registration keeps streaming. The hold lives as long as the registration and never crosses into+another profile's plugin manager.+"""++import hermes_yaml as yaml+import pytest++from hermes_cli.plugins import PluginContext, PluginManager, PluginManifest++REDACTOR = (+ "def register(ctx):\n"+ " ctx.register_hook('transform_llm_output', lambda response_text, **_: response_text, hold_stream=True)\n"+)+++def test_the_hold_lasts_as_long_as_the_registration_that_declared_it():+ manager = PluginManager()+ ctx = PluginContext(PluginManifest(name="redactor", source="user"), manager)+ ctx.register_hook("transform_llm_output", lambda **_: None)+ assert manager.holds_stream() is False # a rewrite that did not ask keeps streaming++ held = ctx.register_hook("transform_llm_output", lambda **_: None, hold_stream=True)+ assert manager.holds_stream() is True++ held.dispose()+ assert manager.holds_stream() is False+ assert manager.has_hook("transform_llm_output") # the undeclared registration is still live+++def test_only_the_declaring_profile_holds(tmp_path, monkeypatch):+ from hermes_cli import plugins+ from hermes_cli.plugins_dispatch import stream_held++ monkeypatch.setenv("HERMES_ENABLE_PROJECT_PLUGINS", "0")+ monkeypatch.setenv("HERMES_BUNDLED_PLUGINS", str(tmp_path / "no-bundled"))+ homes = {name: tmp_path / name for name in ("alpha", "beta")}+ for name, home in homes.items():+ plugin = home / "plugins" / "redactor"+ plugin.mkdir(parents=True)+ (plugin / "plugin.yaml").write_text(yaml.safe_dump({"name": "redactor", "version": "0.1.0"}))+ (plugin / "__init__.py").write_text(REDACTOR if name == "alpha" else REDACTOR.replace(", hold_stream=True", ""))+ (home / "config.yaml").write_text(yaml.safe_dump({"plugins": {"enabled": ["redactor"]}}))++ plugins._reset_plugin_managers_for_tests()+ try:+ seen = []+ for name in ("alpha", "beta", "alpha"):+ monkeypatch.setenv("HERMES_HOME", str(homes[name]))+ seen.append(stream_held())+ assert seen == [True, False, True]+ finally:+ plugins._reset_plugin_managers_for_tests()++[email protected]("hook", ["post_llm_call", "transform_tool_result"])+def test_a_hold_on_a_hook_that_does_not_rewrite_the_reply_holds_nothing(hook, caplog):+ manager = PluginManager()+ ctx = PluginContext(PluginManifest(name="observer", source="user"), manager)+ ctx.register_hook(hook, lambda **_: None, hold_stream=True)+ assert manager.holds_stream() is False+ assert "hold_stream" in caplog.text