Skip to content

The agent that grows with you

fix(plugins): chain request middleware so each callback sees the previous rewrite

nekwoecf6114229f7
diff --git a/hermes_cli/middleware.py b/hermes_cli/middleware.py
index c0940d26bbd..8d8112b5c28 100644
--- a/hermes_cli/middleware.py
+++ b/hermes_cli/middleware.py
@@ -64,10 +64,10 @@ def _apply_request_chain(
kind: str, payload_key: str, trace: List[Dict[str, Any]], original: Any, **kwargs: Any
) -> RequestMiddlewareResult:
"""Feed ``kwargs[payload_key]`` through every ``kind`` middleware; each may return ``{payload_key: {...}}``."""
- from hermes_cli.plugins import invoke_middleware
+ from hermes_cli.plugins import invoke_middleware_chain
current = kwargs[payload_key]
- for result in invoke_middleware(kind, **middleware_payload(**kwargs)):
+ for result in invoke_middleware_chain(kind, payload_key, **middleware_payload(**kwargs)):
if not isinstance(result, dict):
continue
next_payload = result.get(payload_key)
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index 4fbf7394c85..068614a0c91 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -1964,6 +1964,17 @@ def invoke_middleware(kind: str, **kwargs: Any) -> List[Any]:
return _delivery_manager().invoke_middleware(kind, **kwargs)
+def invoke_middleware_chain(kind: str, payload_key: str, **kwargs: Any) -> List[Any]:
+ """Invoke request middleware in registration order, each seeing the previous rewrite.
+
+ A manager without the chained entry point (a test double) gets the flat fan-out.
+ """
+ chain = getattr(_delivery_manager(), "invoke_middleware_chain", None)
+ if not callable(chain):
+ return invoke_middleware(kind, **kwargs)
+ return chain(kind, payload_key, **kwargs)
+
+
def has_middleware(kind: str) -> bool:
"""True when middleware is registered for ``kind``; lazy-discovers first since callers gate
:func:`invoke_middleware` on it.
diff --git a/hermes_cli/plugins_dispatch.py b/hermes_cli/plugins_dispatch.py
index 78c3927fc4f..e65386108b7 100644
--- a/hermes_cli/plugins_dispatch.py
+++ b/hermes_cli/plugins_dispatch.py
@@ -600,3 +600,23 @@ class PluginDispatchMixin:
# Runs once per tool call like a hook, so a mis-declared callback floods identically.
self._report_hook_failure(kind, cb, kwargs, exc, surface="Middleware")
return results
+
+ def invoke_middleware_chain(self, kind: str, payload_key: str, **kwargs: Any) -> List[Any]:
+ """Like :meth:`invoke_middleware`, but each callback sees the previous one's rewrite.
+
+ A result carrying a dict under ``payload_key`` replaces ``kwargs[payload_key]`` for the
+ callbacks after it, so two request rewrites compose instead of the last one winning.
+ """
+ results: List[Any] = []
+ for cb in self._middleware.get(kind, []):
+ try:
+ ret = cb(**kwargs)
+ except (Exception, SystemExit) as exc:
+ self._report_hook_failure(kind, cb, kwargs, exc, surface="Middleware")
+ continue
+ if ret is None:
+ continue
+ results.append(ret)
+ if isinstance(ret, dict) and isinstance(ret.get(payload_key), dict):
+ kwargs[payload_key] = ret[payload_key]
+ return results
diff --git a/tests/hermes_cli/test_plugins.py b/tests/hermes_cli/test_plugins.py
index 3fe75a3b2af..2c945730830 100644
--- a/tests/hermes_cli/test_plugins.py
+++ b/tests/hermes_cli/test_plugins.py
@@ -2718,3 +2718,20 @@ class TestAsyncHookOnCallerLoop:
results = asyncio.run(mgr.ainvoke_hook("pre_gateway_dispatch", event="e", gateway="g"))
assert results == [{"seen": "e"}, {"seen_async": "e"}]
assert "async plugin blew up" in caplog.text
+
+
+def test_request_middleware_chains_each_callback_onto_the_previous_result(monkeypatch):
+ """Two llm_request callbacks: the second must see (and keep) the first's rewrite."""
+ mgr = PluginManager()
+ mgr._discovered = True
+ mgr._middleware["llm_request"] = [
+ lambda **kw: {"request": {**kw["request"], "a": True}, "source": "first"},
+ lambda **kw: {"request": {**kw["request"], "b": True}, "source": "second"},
+ ]
+ monkeypatch.setattr("hermes_cli.plugins.get_plugin_manager", lambda: mgr)
+
+ result = apply_llm_request_middleware({"messages": []})
+
+ assert result.payload == {"messages": [], "a": True, "b": True}
+ assert result.original_payload == {"messages": []}
+ assert [entry["source"] for entry in result.trace] == ["first", "second"]