The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-chat): deliver toolset changes to the canonical Bot Chat
finn763fcda937c5d6c
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 9028cb926a5..e4c5966eeed 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -718,6 +718,69 @@ def _restore_pinned_tools(agent, session_row) -> list:return built_for_this_surface+def _refresh_bot_chat_tool_snapshot(agent) -> None:+ """Adopt the current on-disk toolset selection and rebuild tools[] for a Bot Chat+ capability refresh (#124211).++ A canonical Bot Chat never forks, so without this its tools[] is a fossil of session+ creation: the epoch rebuilds the prompt while the tool schema stays frozen. The+ selection is re-resolved (it is what ``hermes tools enable/disable`` writes) and the+ snapshot rebuilt content-aware like the compaction boundary — no prefix preservation,+ so a disabled toolset actually drops (the prompt rebuild already breaks the cache).+ Only a session that already carries a selection adopts a new one: ``None`` means+ unrestricted and must stay that way. Fail-open: any failure keeps the previous+ tools[] and the prompt rebuild still lands.++ The selection is resolved the way the desktop/TUI BUILDER resolved it — the ``cli``+ slice plus ``with_session_toolsets`` — never ``platform_toolsets.<surface>``: the+ session's surface (``desktop``/``tui``) is not a platform-configuration key, so+ asking for it fell through to the ``hermes-<surface>`` default and collapsed a+ 28-toolset session to the MCP-only surface in one turn (#124211 review, §1)."""+ try:+ from agent.skill_utils import parse_config_string_list+ from agent.system_prompt import _agent_home+ from hermes_cli.config import load_config_readonly+ from hermes_cli.tools_config import _get_platform_tools+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override+ from toolsets import with_session_toolsets+ home = _agent_home(agent)+ token = set_hermes_home_override(str(home)) if home is not None else None+ try:+ cfg = load_config_readonly() or {}+ finally:+ if token is not None:+ reset_hermes_home_override(token)+ # Read BEFORE the resolve: the fold-in below has to respect the updated+ # suppression list, and a later read would arrive after the selection was built.+ try:+ agent.disabled_toolsets = (+ parse_config_string_list((cfg.get("agent") or {}).get("disabled_toolsets")) or None+ )+ except Exception:+ logger.debug("Bot Chat disabled-toolsets re-resolve skipped", exc_info=True)+ if getattr(agent, "enabled_toolsets", None) is not None:+ try:+ base = _get_platform_tools(cfg, "cli", include_default_mcp_servers=True)+ agent.enabled_toolsets = sorted(+ with_session_toolsets(+ base,+ getattr(agent, "platform", None),+ disabled=agent.disabled_toolsets,+ )+ )+ except Exception:+ logger.debug("Bot Chat toolset re-resolve skipped", exc_info=True)+ except Exception:+ logger.debug("Bot Chat toolset adoption skipped", exc_info=True)+ try:+ from tools.mcp_tool_agent import refresh_agent_mcp_tools+ added = refresh_agent_mcp_tools(agent, quiet_mode=True, content_aware=True)+ if added:+ logger.info("Bot Chat capability refresh added tools: %s", sorted(added))+ except Exception:+ logger.debug("Bot Chat tool refresh skipped", exc_info=True)++def _restore_or_build_system_prompt(agent, system_message, conversation_history):"""Restore the cached system prompt from the session DB or build it fresh.@@ -757,14 +820,18 @@ def _restore_or_build_system_prompt(agent, system_message, conversation_history)clear_skills_system_prompt_cache(clear_snapshot=True)except Exception:pass+ _refresh_bot_chat_tool_snapshot(agent)agent._cached_system_prompt = agent._build_system_prompt(system_message)stage_surface_switch_note(agent, agent._cached_system_prompt, conversation_history)# Persist so the NEXT turn restores the new bytes verbatim (cache break is- # once per capability change). on_session_start not re-fired: continuation.+ # once per capability change). Tools re-pin too: without it the next+ # turn's pin-restore would resurrect the pre-refresh toolset (#124211).+ # on_session_start not re-fired: continuation._persist_system_prompt(agent,"Session DB update_system_prompt failed after Bot Chat capability refresh ""(session=%s): %s. The refresh will re-fire next turn.",+ persist_tools=True,)return# Continuing session — reuse the exact system prompt from thediff --git a/tests/agent/test_bot_chat_toolset_refresh.py b/tests/agent/test_bot_chat_toolset_refresh.pynew file mode 100644index 00000000000..92c236140fc--- /dev/null+++ b/tests/agent/test_bot_chat_toolset_refresh.py@@ -0,0 +1,182 @@+"""RED tests for #124211: toolset changes must reach the canonical Bot Chat.++1. The capability epoch must flip when ``platform_toolsets`` (the key+ ``hermes tools enable/disable`` actually writes) changes. The epoch used to+ watch only ``tools.enabled_toolsets``, a key no surface writes, so the+ staleness detector was blind to real toolset edits.+2. The Bot Chat capability-refresh branch must rebuild ``agent.tools`` (and+ re-pin the session row), not just the system prompt. It used to return+ early after rebuilding the prompt, leaving tools[] a fossil of session+ creation forever.+"""++from __future__ import annotations++import textwrap+from unittest.mock import MagicMock, patch++from tools import bot_mode_probe+++def _make_bot_profile(root, name, *, managed=True):+ d = root / "profiles" / name+ d.mkdir(parents=True, exist_ok=True)+ if managed:+ (d / "profile.yaml").write_text(+ textwrap.dedent(+ """\+ ui_meta:+ hermes-bots:+ shape: cloud+ color: '#8b5cf6'+ """+ ),+ encoding="utf-8",+ )+ return d+++def test_capability_epoch_follows_platform_toolset_edits(tmp_path):+ """``hermes tools enable computer_use`` writes platform_toolsets.<platform>;+ the Bot Chat epoch must flip so the next turn rebuilds."""+ bot_mode_probe._reset_cache_for_tests()+ try:+ home = tmp_path / ".hermes"+ home.mkdir()+ _make_bot_profile(home, "researcher", managed=True)+ (home / "config.yaml").write_text(+ "platform_toolsets:\n desktop: [hermes-desktop]\n", encoding="utf-8"+ )+ base = bot_mode_probe.capability_fingerprint(home)+ (home / "config.yaml").write_text(+ "platform_toolsets:\n desktop: [hermes-desktop, computer_use]\n",+ encoding="utf-8",+ )+ assert bot_mode_probe.capability_fingerprint(home) != base+ finally:+ bot_mode_probe._reset_cache_for_tests()+++def test_capability_epoch_follows_global_toolset_suppression(tmp_path):+ """``agent.disabled_toolsets`` suppresses tools in every session; flipping it+ must flip the Bot Chat epoch too."""+ bot_mode_probe._reset_cache_for_tests()+ try:+ home = tmp_path / ".hermes"+ home.mkdir()+ _make_bot_profile(home, "researcher", managed=True)+ (home / "config.yaml").write_text("agent:\n disabled_toolsets: []\n", encoding="utf-8")+ base = bot_mode_probe.capability_fingerprint(home)+ (home / "config.yaml").write_text(+ "agent:\n disabled_toolsets: [computer_use]\n", encoding="utf-8"+ )+ assert bot_mode_probe.capability_fingerprint(home) != base+ finally:+ bot_mode_probe._reset_cache_for_tests()+++def _stored_prompt() -> str:+ return (+ "SYSTEM PROMPT BODY\n\nConversation started: Monday, January 05, 2026\n"+ "Model: test-model\nProvider: openrouter\nPlatform: desktop"+ )+++def _make_agent(db):+ from agent.conversation_loop import _restore_or_build_system_prompt # noqa: F401++ agent = MagicMock()+ agent._cached_system_prompt = None+ agent.session_id = "test-session-id"+ agent.model = "test-model"+ agent.provider = "openrouter"+ agent.platform = "desktop"+ agent._session_db = db+ agent._use_prompt_caching = False+ agent._build_system_prompt = MagicMock(return_value="NEW_PROMPT")+ agent.enabled_toolsets = ["web"]+ agent.disabled_toolsets = None+ agent.tools = [{"type": "function", "function": {"name": "web_search", "parameters": {}}}]+ agent.valid_tool_names = {"web_search"}+ agent._bot_mode_protocol = True+ agent._session_title_hint = "Bot Chat"+ agent._platform_hint_overrides = None+ agent._surface_switch_note = ""+ agent._gateway_turn_context_notes = ""+ return agent+++def test_bot_chat_capability_refresh_rebuilds_tools():+ """When the Bot Chat epoch is stale, the refresh must rebuild tools[] (not+ just the prompt) and re-pin the session row."""+ from agent.conversation_loop import _restore_or_build_system_prompt++ db = MagicMock()+ db.get_session.return_value = {"system_prompt": _stored_prompt(), "tool_names": None}+ agent = _make_agent(db)+ history = [{"role": "user", "content": "hi"}]+ with (+ patch("tools.bot_mode_probe.stored_prompt_capability_stale", return_value=True),+ patch("tools.mcp_tool_agent.refresh_agent_mcp_tools", return_value={"new_tool"}) as refresh,+ ):+ _restore_or_build_system_prompt(agent, None, history)+ assert agent._cached_system_prompt == "NEW_PROMPT"+ refresh.assert_called_once()+ # The rebuilt tool snapshot must be re-pinned so the next turn restores it.+ assert db.update_session_tool_names.called+++def _refreshable_agent(home, platform, *, enabled=("web",)):+ """An agent whose home resolves to *home*, so the refresh reads a real config file."""+ agent = MagicMock()+ agent.platform = platform+ agent.enabled_toolsets = list(enabled)+ agent.disabled_toolsets = None+ agent._session_db.db_path = str(home / "state.db")+ return agent+++def _refresh(agent):+ from agent.conversation_loop import _refresh_bot_chat_tool_snapshot++ with patch("tools.mcp_tool_agent.refresh_agent_mcp_tools", return_value=set()):+ _refresh_bot_chat_tool_snapshot(agent)+++def test_refresh_adopts_the_builders_selection_not_the_session_surface(tmp_path):+ """Assert WHAT was selected (review §1). The refresh used to ask+ ``platform_toolsets.<surface>`` — ``desktop``/``tui`` are not configuration keys, so+ ``_get_platform_tools`` fell through to the ``hermes-<surface>`` default and replaced+ a working 28-toolset selection with the MCP-only fallback in one turn."""+ home = tmp_path+ (home / "config.yaml").write_text(+ "platform_toolsets:\n cli: [terminal, file, web]\n", encoding="utf-8"+ )+ agent = _refreshable_agent(home, "desktop")++ _refresh(agent)++ selection = set(agent.enabled_toolsets)+ # The `cli` slice the desktop/TUI builder reads — not a synthesized fallback name.+ assert {"terminal", "file", "web"} <= selection+ # ...plus the client-surface fold-in, same as the build.+ assert {"desktop_ui", "project"} <= selection+ assert "hermes-desktop" not in selection+++def test_refresh_reads_disabled_toolsets_before_the_fold_in(tmp_path):+ """Review §4c: the re-read lands BEFORE the fold-in, so a suppressed client-surface+ toolset cannot ride back in on the refresh (``desktop_ui`` survives, #54433)."""+ home = tmp_path+ (home / "config.yaml").write_text(+ "agent:\n disabled_toolsets: [project]\nplatform_toolsets:\n cli: [terminal, web]\n",+ encoding="utf-8",+ )+ agent = _refreshable_agent(home, "desktop")++ _refresh(agent)++ assert agent.disabled_toolsets == ["project"]+ assert "project" not in agent.enabled_toolsets+ assert "desktop_ui" in agent.enabled_toolsets+ assert {"terminal", "web"} <= set(agent.enabled_toolsets)diff --git a/tests/tools/test_bot_mode_probe.py b/tests/tools/test_bot_mode_probe.pyindex 3f542520f07..b64dbfe9987 100644--- a/tests/tools/test_bot_mode_probe.py+++ b/tests/tools/test_bot_mode_probe.py@@ -186,18 +186,31 @@ def test_fingerprint_changes_on_each_capability_axis(tmp_path):after_skill = bot_mode_probe.capability_fingerprint(home)assert after_skill != base- # toolset pin changed- (home / "config.yaml").write_text("tools:\n enabled_toolsets: [web]\n", encoding="utf-8")+ # toolset pin changed (the key `hermes tools enable/disable` writes, #124211)+ (home / "config.yaml").write_text(+ "platform_toolsets:\n desktop: [hermes-desktop, computer_use]\n", encoding="utf-8"+ )after_tools = bot_mode_probe.capability_fingerprint(home)assert after_tools != after_skill+ # global suppression changed+ (home / "config.yaml").write_text(+ "platform_toolsets:\n desktop: [hermes-desktop, computer_use]\n"+ "agent:\n disabled_toolsets: [computer_use]\n",+ encoding="utf-8",+ )+ after_disabled = bot_mode_probe.capability_fingerprint(home)+ assert after_disabled != after_tools+# MCP server added(home / "config.yaml").write_text(- "tools:\n enabled_toolsets: [web]\nmcp_servers:\n github:\n preset: github\n",+ "platform_toolsets:\n desktop: [hermes-desktop, computer_use]\n"+ "agent:\n disabled_toolsets: [computer_use]\n"+ "mcp_servers:\n github:\n preset: github\n",encoding="utf-8",)after_mcp = bot_mode_probe.capability_fingerprint(home)- assert after_mcp != after_tools+ assert after_mcp != after_disabled# SOUL edited(home / "SOUL.md").write_text("# New identity\n", encoding="utf-8")diff --git a/tools/bot_mode_probe.py b/tools/bot_mode_probe.pyindex a964388c677..e62a091dcda 100644--- a/tools/bot_mode_probe.py+++ b/tools/bot_mode_probe.py@@ -355,6 +355,19 @@ def _model_prompt_capability_surface(model_cfg: object) -> dict:}+def _normalized_disabled_toolsets(cfg: dict) -> list:+ """Global toolset suppression as the runtime reads it (``hermes config set+ agent.disabled_toolsets`` may store a JSON-array string; see #97015). Falls back+ to the raw value so the epoch still flips when the parser is unavailable."""+ raw = (cfg.get("agent") or {}).get("disabled_toolsets") if isinstance(cfg.get("agent"), dict) else None+ try:+ from agent.skill_utils import parse_config_string_list++ return sorted(s for s in parse_config_string_list(raw) if str(s).strip())+ except Exception:+ return sorted(raw) if isinstance(raw, list) else ([str(raw)] if raw else [])++def capability_fingerprint(home: str | os.PathLike | None = None) -> str:"""12-hex digest of the capability surface for ``home``'s profile: disabled skills +enabled toolsets + MCP config, model capability overrides that change the prompt@@ -380,11 +393,18 @@ def capability_fingerprint(home: str | os.PathLike | None = None) -> str:finally:reset_hermes_home_override(token)skills_cfg = cfg.get("skills") if isinstance(cfg.get("skills"), dict) else {}- tools_cfg = cfg.get("tools") if isinstance(cfg.get("tools"), dict) else {}model_cfg = cfg.get("model") if isinstance(cfg.get("model"), dict) else {}surface["model_capabilities"] = _model_prompt_capability_surface(model_cfg)surface["disabled_skills"] = sorted(str(s).lower() for s in (skills_cfg.get("disabled") or []))- surface["enabled_toolsets"] = sorted(str(t) for t in (tools_cfg.get("enabled_toolsets") or []))+ # The live selection is platform_toolsets.<platform> (+ the global+ # agent.disabled_toolsets suppression); tools.enabled_toolsets is not+ # written by any surface, so watching it left Bot Chats blind to real+ # `hermes tools enable/disable` edits (#124211). Raw slices: any edit+ # flips the epoch even when the effective selection is unchanged (one+ # spurious rebuild at most).+ surface["platform_toolsets"] = json.dumps(+ cfg.get("platform_toolsets") or {}, sort_keys=True, default=str)+ surface["disabled_toolsets"] = _normalized_disabled_toolsets(cfg)mcp = cfg.get("mcp_servers")surface["mcp"] = json.dumps(mcp, sort_keys=True, default=str) if isinstance(mcp, dict) else ""except Exception:diff --git a/toolsets.py b/toolsets.pyindex 89386334b9c..d638a5fce21 100644--- a/toolsets.py+++ b/toolsets.py@@ -73,6 +73,40 @@ _CODING_TOOLS = _core_without("image_generate", "text_to_speech", "cronjob_manag# config: another surface lacking them made no configuration choice.CLIENT_SURFACE_TOOLSETS = frozenset({"project", "desktop_ui"})++def session_surface_toolsets(platform: Optional[str]) -> Set[str]:+ """Toolsets that exist because of the CLIENT (both off ``_HERMES_CORE_TOOLS``; this is the one gate).+ ``platform`` is the SESSION's source, never a process env var: the desktop may drive a URL/cloud+ backend where ``HERMES_DESKTOP`` is unset (AGENTS.md surface rule)."""+ return set(CLIENT_SURFACE_TOOLSETS) if platform == "desktop" else {"project"}+++def with_session_toolsets(+ selection, platform: Optional[str], *, disabled: Optional[List[str]] = None+) -> List[str]:+ """*selection* plus what the session carries whatever its config says (the client surface's+ toolsets when *platform* is given; the ones its PROFILE's role reserves, from the backend-written+ profile.yaml under the session's home override), minus toolsets reserved for another role.++ The fold-in happens after ``_get_platform_tools`` already subtracted ``agent.disabled_toolsets``,+ so the same subtraction is applied to the fold-in itself — otherwise ``disabled_toolsets:+ [project]`` is a no-op on desktop/TUI, the only surfaces where the client toolsets exist+ (#54433). ``desktop_ui`` is kept regardless: it is the client's own control surface, not a+ model toolset.++ THE selection policy for a session's surface. The desktop/TUI builder and the Bot Chat capability+ refresh both go through here so a refresh adopts the selection the session was BUILT with rather+ than re-deriving the policy from a different platform key (#124211).+ """+ granted, denied = profile_role_toolsets()+ surface = session_surface_toolsets(platform) if platform is not None else set()+ kept = [name for name in selection if name not in denied]+ fold_in = (surface | granted) - set(kept)+ blocked = set(disabled or [])+ if blocked:+ fold_in -= blocked - {"desktop_ui"}+ return [*kept, *sorted(fold_in)]+# Core toolset definitions: individual tools or references to other toolsets.TOOLSETS = {# Basic toolsets - individual tool categoriesdiff --git a/tui_gateway/server.py b/tui_gateway/server.pyindex 715fa025334..61d93813120 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1854,32 +1854,18 @@ def _load_tool_progress_mode() -> str:def _gui_surface_toolsets(platform: str) -> set[str]:- """Toolsets that exist because of the CLIENT (both off ``_HERMES_CORE_TOOLS``; this is the one gate).- ``platform`` is the SESSION's source, never a process env var: the desktop may drive a URL/cloud- backend where ``HERMES_DESKTOP`` is unset (AGENTS.md surface rule)."""- from toolsets import CLIENT_SURFACE_TOOLSETS- return set(CLIENT_SURFACE_TOOLSETS) if platform == "desktop" else {"project"}+ """Toolsets that exist because of the CLIENT. Thin binding of the shared policy+ (``toolsets.session_surface_toolsets``), which the Bot Chat refresh also reads (#124211)."""+ from toolsets import session_surface_toolsets+ return session_surface_toolsets(platform)def _with_session_toolsets(selection, platform: str | None) -> list[str]:- """*selection* plus what the session carries whatever its config says (the client surface's- toolsets when *platform* is given; the ones its PROFILE's role reserves, from the backend-written- profile.yaml under the session's home override), minus toolsets reserved for another role.-- The fold-in happens after ``_get_platform_tools`` already subtracted ``agent.disabled_toolsets``,- so the same subtraction is applied to the fold-in itself — otherwise ``disabled_toolsets:- [project]`` is a no-op on desktop/TUI, the only surfaces where the client toolsets exist- (#54433). ``desktop_ui`` is kept regardless: it is the client's own control surface, not a- model toolset."""- from toolsets import profile_role_toolsets- granted, denied = profile_role_toolsets()- surface = _gui_surface_toolsets(platform) if platform is not None else set()- kept = [name for name in selection if name not in denied]- fold_in = (surface | granted) - set(kept)- disabled = set(_load_disabled_toolsets() or [])- if disabled:- fold_in -= disabled - {"desktop_ui"}- return [*kept, *sorted(fold_in)]+ """The session's selection: *selection* plus its client-surface and profile-role toolsets, minus+ the ones ``agent.disabled_toolsets`` suppresses. Thin binding of ``toolsets.with_session_toolsets``+ (the shared policy, so the build and the Bot Chat refresh cannot drift apart — #124211)."""+ from toolsets import with_session_toolsets+ return with_session_toolsets(selection, platform, disabled=_load_disabled_toolsets())def _tui_notice(text: str) -> None: