Skip to content

The agent that grows with you

perf(memory): resolve the bound profile key and the tool-call signature once per manager

unsupportedpastelsefe5751584d2
diff --git a/agent/memory_caller_scope.py b/agent/memory_caller_scope.py
index cda9e41ba8f..083a32a7e40 100644
--- a/agent/memory_caller_scope.py
+++ b/agent/memory_caller_scope.py
@@ -62,11 +62,17 @@ def _refuse(label: str, reason: str, caller_home: Any, bound_home: Any, multiple
label, CALLER_PROFILE_REFUSAL, reason, caller_home, bound_home, multiplexed)
+def bound_scope(hermes_home: Any, agent_identity: Any = None) -> dict[str, Any]:
+ """What ``initialize_all`` records for ``caller_scope``: the bound home's key is resolved once
+ here, so each call only resolves the caller's."""
+ return {"hermes_home": hermes_home, "agent_identity": agent_identity, "home_key": _home_key(hermes_home)}
+
+
def caller_scope(bound: Optional[dict[str, Any]], label: str) -> Optional[dict[str, Any]]:
"""Provider kwargs naming the calling profile, or None when the call/hook must be refused.
- ``bound`` is what ``initialize_all`` recorded (``hermes_home``, ``agent_identity``); ``label``
- names the call in the log (``tool <name>`` / ``hook <name>``)."""
+ ``bound`` is what ``initialize_all`` recorded (``bound_scope``); ``label`` names the call in the
+ log (``tool <name>`` / ``hook <name>``)."""
from agent.secret_scope import is_multiplex_active
bound = bound or {}
bound_home = bound.get("hermes_home")
@@ -84,7 +90,7 @@ def caller_scope(bound: Optional[dict[str, Any]], label: str) -> Optional[dict[s
return None
return {"hermes_home": str(caller_home)}
caller_key = _home_key(caller_home)
- if caller_key is None or caller_key != _home_key(bound_home):
+ if caller_key is None or caller_key != (bound.get("home_key") or _home_key(bound_home)):
_refuse(label, "the caller's profile is not the one its provider was initialized for",
caller_home, bound_home, multiplexed)
return None
diff --git a/agent/memory_manager.py b/agent/memory_manager.py
index a9956ef888d..fec9ec8d7d4 100644
--- a/agent/memory_manager.py
+++ b/agent/memory_manager.py
@@ -18,7 +18,7 @@ from typing import Any, Callable, Dict, List, Optional
from agent.redact import redact_for_egress
-from agent.memory_caller_scope import caller_scope, claim_instance, in_owner_home, refused_tool_message
+from agent.memory_caller_scope import bound_scope, caller_scope, claim_instance, in_owner_home, refused_tool_message
# Moved to agent.memory_context; still importable here because agent.memory_manager is a public
# module for plugins (hermes_cli/plugin_validate_private_imports.py).
from agent.memory_context import StreamingContextScrubber, build_memory_context_block, sanitize_context
@@ -251,6 +251,7 @@ class MemoryManager:
}
# The profile ``initialize_all`` bound the providers to; tool calls must come from it (#140058).
self._bound_scope: Optional[dict[str, Any]] = None
+ self._tool_call_keywords_cache: dict[int, Optional[frozenset[str]]] = {}
def _each_provider(self, label: str, call: Callable[[MemoryProvider], Any], *, level: int = logging.DEBUG,
providers: Optional[list[MemoryProvider]] = None, exc_info: bool = False) -> list[Any]:
@@ -269,7 +270,17 @@ class MemoryManager:
for (#140058; see ``agent/memory_caller_scope.py``). Nothing to reach, nothing to refuse."""
return not self._providers or caller_scope(self._bound_scope, f"hook {hook}") is not None
+ def _tool_call_keywords(self, provider: MemoryProvider) -> Optional[frozenset[str]]:
+ """The keywords ``provider.handle_tool_call`` declares; None when it takes any (``**kwargs``, or
+ a signature that can't be read). Worked out once per provider, not on every tool call."""
+ if id(provider) not in self._tool_call_keywords_cache:
+ params = _signature_params(provider.handle_tool_call)
+ self._tool_call_keywords_cache[id(provider)] = (
+ None if params is None or _has_var_kwargs(params) else frozenset(params))
+ return self._tool_call_keywords_cache[id(provider)]
+
def _drop_provider(self, provider: MemoryProvider) -> None:
+ self._tool_call_keywords_cache.pop(id(provider), None)
self._providers = [p for p in self._providers if p is not provider]
self._tool_to_provider = {t: p for t, p in self._tool_to_provider.items() if p is not provider}
self._has_external = any(p.name != "builtin" for p in self._providers)
@@ -565,9 +576,9 @@ class MemoryManager:
return tool_error(refused_tool_message(tool_name))
kwargs = {**kwargs, **scope}
# A provider written against ``handle_tool_call(tool_name, args)`` gets only what it declares.
- params = _signature_params(provider.handle_tool_call)
- if params is not None and not _has_var_kwargs(params):
- kwargs = {k: v for k, v in kwargs.items() if k in params}
+ accepted = self._tool_call_keywords(provider)
+ if accepted is not None:
+ kwargs = {k: v for k, v in kwargs.items() if k in accepted}
args = _redact_for_provider(args)
from hermes_cli.observability.shared_metrics_loop import record_provider_memory_call
try:
@@ -870,7 +881,7 @@ class MemoryManager:
if "hermes_home" not in kwargs:
from hermes_constants import get_hermes_home
kwargs["hermes_home"] = str(get_hermes_home())
- self._bound_scope = {key: kwargs.get(key) for key in ("hermes_home", "agent_identity")}
+ self._bound_scope = bound_scope(kwargs["hermes_home"], kwargs.get("agent_identity"))
# One instance, one profile: never rebind an instance another profile's manager bound (#140058).
for provider in [p for p in self._providers if p.name != "builtin"]:
if not claim_instance(provider, kwargs["hermes_home"]):
diff --git a/tests/agent/test_memory_provider_caller_profile.py b/tests/agent/test_memory_provider_caller_profile.py
index 19100b049de..00f09a59a6a 100644
--- a/tests/agent/test_memory_provider_caller_profile.py
+++ b/tests/agent/test_memory_provider_caller_profile.py
@@ -333,6 +333,23 @@ def test_multiplexed_lifecycle_hook_without_a_caller_scope_is_refused(homes, hoo
assert _InstanceScopedProvider.events == []
+def test_tool_calls_reuse_what_initialize_bound(homes, monkeypatch):
+ # Per call, only the caller's home is resolved: the bound home's key and the provider's
+ # handle_tool_call signature are worked out once per manager, not on every call.
+ from agent import memory_caller_scope, memory_manager
+ alpha_home, _ = homes
+ alpha = _manager(alpha_home)
+ keys, signatures = [], []
+ real_key, real_signature = memory_caller_scope._home_key, memory_manager._signature_params
+ monkeypatch.setattr(memory_caller_scope, "_home_key", lambda home: keys.append(home) or real_key(home))
+ monkeypatch.setattr(memory_manager, "_signature_params", lambda fn: signatures.append(fn) or real_signature(fn))
+ with _Scope(alpha_home):
+ for _ in range(3):
+ assert json.loads(alpha.handle_tool_call(_HOOK_TOOL, {})) == {"ok": True}
+ assert keys == [str(alpha_home)] * 3, keys
+ assert len(signatures) <= 1, signatures
+
+
def test_refused_checkpoint_compression_fails_closed(homes):
alpha_home, beta_home = homes
alpha = _manager(alpha_home)