Skip to content
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 21 additions & 11 deletions agent/memory_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,21 @@
_SYNC_DRAIN_TIMEOUT_S = 5.0


def memory_provider_tools_enabled(enabled_toolsets: Optional[List[str]], disabled_toolsets: Optional[List[str]] = None) -> bool:
"""Return whether external memory-provider tools should be exposed.

Gate logic (Issue #45422):
enabled_toolsets is None → no filter, inject (backward compat)
enabled_toolsets is non-empty → inject (platform has tools; external
memory provider works regardless of
whether the built-in memory toolset
is explicitly named)
enabled_toolsets is empty ([]) → skip (constrained platform, no tools)
"memory" in disabled_toolsets → skip (global nuclear option — user
explicitly opted out of ALL memory)
"""
if disabled_toolsets and "memory" in disabled_toolsets:
return False
def normalize_tool_schema(schema: Any) -> Optional[Dict[str, Any]]:
"""Return a function-tool dict with a resolvable top-level ``name``.

Expand Down Expand Up @@ -85,16 +100,8 @@ def memory_provider_tools_enabled(enabled_toolsets: Optional[List[str]]) -> bool
return True
if not enabled_toolsets:
return False
if "memory" in enabled_toolsets:
return True

try:
from toolsets import resolve_toolset

return any("memory" in resolve_toolset(name) for name in enabled_toolsets)
except Exception:
logger.debug("Failed to resolve enabled toolsets for memory-provider tools", exc_info=True)
return False
# Any non-empty toolset list allows external memory providers (#45422)
return True


def inject_memory_provider_tools(agent: Any) -> int:
Expand All @@ -111,7 +118,10 @@ def inject_memory_provider_tools(agent: Any) -> int:
}
if (
"memory" not in existing_tool_names
and not memory_provider_tools_enabled(getattr(agent, "enabled_toolsets", None))
and not memory_provider_tools_enabled(
getattr(agent, "enabled_toolsets", None),
getattr(agent, "disabled_toolsets", None),
)
):
return 0

Expand Down
2 changes: 1 addition & 1 deletion agent/system_prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ def build_system_prompt_parts(agent: Any, system_message: Optional[str] = None)

# Tool-aware behavioral guidance: only inject when the tools are loaded
tool_guidance = []
if "memory" in agent.valid_tool_names:
if "memory" in agent.valid_tool_names and agent._memory_enabled:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_memory_enabled alone is too narrow: when memory_enabled: false but user_profile_enabled: true, agent initialization still creates the built-in store and the memory tool still supports target: user, but this removes its guidance. Preserve guidance for the user-profile-only case and add a regression test.

tool_guidance.append(MEMORY_GUIDANCE)
if "session_search" in agent.valid_tool_names:
tool_guidance.append(SESSION_SEARCH_GUIDANCE)
Expand Down
64 changes: 45 additions & 19 deletions tests/agent/test_memory_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -1308,29 +1308,28 @@ def test_injection_frequency_first_turn_with_1indexed(self):


class TestMemoryToolToolsetGate:
"""Issue #5544: memory provider tools must respect platform_toolsets.

Before the fix, MemoryManager.get_all_tool_schemas() output was appended
to AIAgent.tools unconditionally in agent_init.py — bypassing the
enabled_toolsets filter. Result: `platform_toolsets: telegram: []`
still leaked fact_store and other memory tools into the tool surface,
causing 10x latency on local models (Qwen3-30B: 1.7s → 42s) and
tool-call loops on small models.
"""Issue #5544: memory provider tools must respect platform_toolsets,
and Issue #45422: external memory providers work regardless of whether
the built-in memory toolset is explicitly enabled.

These tests exercise the shared gate used by agent init and ACP refreshes.
The gate condition is:

enabled_toolsets is None → no filter, inject (backward compat)
selected toolsets include memory → user opted in, inject
otherwise (incl. []) → skip injection
The gate condition is (#45422):

enabled_toolsets is None → no filter, inject (backward compat)
enabled_toolsets is non-empty → inject (external provider works
regardless of whether the built-in
memory toolset is enabled)
enabled_toolsets is empty ([]) → skip (constrained platform, no tools)
"memory" in disabled_toolsets → skip (global nuclear option)
"""

@staticmethod
def _run_memory_injection(enabled_toolsets, memory_manager):
def _run_memory_injection(enabled_toolsets, memory_manager, disabled_toolsets=None):
"""Run the shared memory-tool injection helper against a fake agent."""
fake_agent = SimpleNamespace(
_memory_manager=memory_manager,
enabled_toolsets=enabled_toolsets,
disabled_toolsets=disabled_toolsets,
tools=[],
valid_tool_names=set(),
)
Expand Down Expand Up @@ -1374,25 +1373,52 @@ def test_empty_toolsets_blocks_injection(self):
assert tools == []
assert names == set()

def test_toolsets_without_memory_blocks_injection(self):
"""Toolsets that don't include memory must suppress injection."""
def test_toolsets_without_memory_still_injects(self):
"""Toolset list that doesn't name 'memory' still injects external providers (#45422).

Disabling the built-in memory toolset should not suppress external memory
providers configured via memory.provider in config.yaml.
"""
mgr = self._mgr_with_tools("fact_store")
tools, names = self._run_memory_injection(["terminal", "web"], mgr)
assert tools == []
assert names == set()
assert "fact_store" in names
assert any(t["function"]["name"] == "fact_store" for t in tools)

def test_no_memory_manager_no_injection(self):
"""Gate is moot without a memory manager."""
tools, names = self._run_memory_injection(None, None)
assert tools == []

def test_multiple_schemas_all_blocked_together(self):
"""When the gate is closed, no memory tools leak — not even partially."""
"""When the gate is closed (empty toolsets), no memory tools leak — not even partially."""
mgr = self._mgr_with_tools("fact_store", "memory_search", "memory_add")
tools, names = self._run_memory_injection([], mgr)
assert tools == []
assert names == set()

def test_multiple_schemas_all_injected_with_nonempty_toolsets(self):
"""Non-empty toolsets (without 'memory') still injects external provider tools (#45422)."""
mgr = self._mgr_with_tools("fact_store", "memory_search", "memory_add")
tools, names = self._run_memory_injection(["terminal"], mgr)
assert names == {"fact_store", "memory_search", "memory_add"}

def test_disabled_toolsets_blocks_injection(self):
"""agent.disabled_toolsets containing 'memory' suppresses all external provider tools."""
mgr = self._mgr_with_tools("fact_store")
tools, names = self._run_memory_injection(
["terminal", "web"], mgr, disabled_toolsets=["memory"]
)
assert tools == []
assert names == set()

def test_disabled_toolsets_none_does_not_block(self):
"""agent.disabled_toolsets without 'memory' does not suppress external providers."""
mgr = self._mgr_with_tools("fact_store")
tools, names = self._run_memory_injection(
["terminal", "web"], mgr, disabled_toolsets=["browser"]
)
assert "fact_store" in names

def test_multiple_schemas_all_injected_when_enabled(self):
"""When the gate is open, every memory tool schema is injected."""
mgr = self._mgr_with_tools("fact_store", "memory_search", "memory_add")
Expand Down
1 change: 1 addition & 0 deletions tests/run_agent/test_run_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ def agent_with_memory_tool():
skip_memory=True,
)
a.client = MagicMock()
a._memory_enabled = True # required for MEMORY_GUIDANCE injection (#45422)
return a


Expand Down