The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(bot-chat): rebuild a stale Bot Chat's tools through the surface builder (#124211, salvage #124307)
teknium110708bc117e2
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex e4c5966eeed..7387d52ba59 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -718,67 +718,27 @@ 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)+def _refresh_bot_chat_tools(agent) -> None:+ """Rebuild ``agent.tools`` for a Bot Chat capability refresh through the builder that+ created the session, so the refreshed set is what a fresh desktop/TUI session gets+ (#124211). A canonical Bot Chat never forks, so its tools[] is otherwise a fossil of+ session creation: ``hermes tools enable/disable`` writes ``platform_toolsets`` and the+ automatic between-turns refresh reuses the build-time selection. Only the desktop/TUI+ gateway keeps agents alive across turns; every other surface builds a fresh agent whose+ tools[] already reflects config. No prefix preservation: a disabled toolset must drop,+ and the prompt rebuild this rides on already breaks the cache."""+ platform = getattr(agent, "platform", None)+ if platform not in ("desktop", "tui"):+ returntry: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)+ from tui_gateway.server import _load_disabled_toolsets, _load_enabled_toolsets+ refresh_agent_mcp_tools(+ agent, enabled_override=_load_enabled_toolsets(platform),+ disabled_override=_load_disabled_toolsets(), quiet_mode=True, content_aware=True)+ except Exception as exc:+ logger.warning("Bot Chat capability refresh kept the previous tools for session %s: %s",+ agent.session_id, exc)def _restore_or_build_system_prompt(agent, system_message, conversation_history):@@ -820,7 +780,7 @@ 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)+ _refresh_bot_chat_tools(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 isdiff --git a/tests/agent/test_bot_chat_toolset_refresh.py b/tests/agent/test_bot_chat_toolset_refresh.pyindex 92c236140fc..e899386f45b 100644--- a/tests/agent/test_bot_chat_toolset_refresh.py+++ b/tests/agent/test_bot_chat_toolset_refresh.py@@ -1,96 +1,27 @@-"""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.-"""+"""#124211: a Bot Chat capability refresh must rebuild tools[] through the surface's own+builder (what a fresh desktop/TUI session gets), not just the system prompt."""from __future__ import annotations-import textwrapfrom 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+from agent.conversation_loop import _restore_or_build_system_prompt+STORED_PROMPT = (+ "SYSTEM PROMPT BODY\n\nConversation started: Monday, January 05, 2026\n"+ "Model: test-model\nProvider: openrouter\nPlatform: desktop"+)+++def _stale_bot_chat_agent(platform: str):+ db = MagicMock()+ db.get_session.return_value = {"system_prompt": STORED_PROMPT, "tool_names": None}agent = MagicMock()agent._cached_system_prompt = Noneagent.session_id = "test-session-id"agent.model = "test-model"agent.provider = "openrouter"- agent.platform = "desktop"+ agent.platform = platformagent._session_db = dbagent._use_prompt_caching = Falseagent._build_system_prompt = MagicMock(return_value="NEW_PROMPT")@@ -100,83 +31,46 @@ def _make_agent(db):agent.valid_tool_names = {"web_search"}agent._bot_mode_protocol = Trueagent._session_title_hint = "Bot Chat"- agent._platform_hint_overrides = Noneagent._surface_switch_note = ""agent._gateway_turn_context_notes = ""- return agent+ return agent, db-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"}]+def _run_stale_refresh(agent):+ builder = MagicMock(return_value=["terminal", "file", "desktop_ui"])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,+ patch("tui_gateway.server._load_enabled_toolsets", builder),+ patch("tui_gateway.server._load_disabled_toolsets", return_value=["computer_use"]),+ patch("tools.mcp_tool_agent.refresh_agent_mcp_tools", return_value=set()) as refresh,):- _restore_or_build_system_prompt(agent, None, history)+ _restore_or_build_system_prompt(agent, None, [{"role": "user", "content": "hi"}])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.+ return builder, refresh+++def test_stale_epoch_rebuilds_tools_through_the_surface_builder():+ """The selection handed to the rebuild is the desktop builder's answer for THIS surface+ (never a `platform_toolsets.<surface>` lookup, which resolves to no tools), a disabled+ toolset is not carried forward, and the result is re-pinned for the next turn."""+ agent, db = _stale_bot_chat_agent("desktop")++ builder, refresh = _run_stale_refresh(agent)++ builder.assert_called_once_with("desktop")+ kwargs = refresh.call_args.kwargs+ assert kwargs["enabled_override"] == ["terminal", "file", "desktop_ui"]+ assert kwargs["disabled_override"] == ["computer_use"]+ assert not kwargs.get("preserve_prefix")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)+def test_stale_epoch_leaves_a_per_process_surface_alone():+ """A CLI resume builds a fresh agent from config every process; the desktop builder's+ fold-in (client-surface toolsets) must not be applied to it."""+ agent, _db = _stale_bot_chat_agent("cli")++ builder, refresh = _run_stale_refresh(agent)++ builder.assert_not_called()+ refresh.assert_not_called()diff --git a/tools/bot_mode_probe.py b/tools/bot_mode_probe.pyindex e62a091dcda..f4212f90dad 100644--- a/tools/bot_mode_probe.py+++ b/tools/bot_mode_probe.py@@ -355,19 +355,6 @@ 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@@ -384,6 +371,7 @@ def capability_fingerprint(home: str | os.PathLike | None = None) -> str:try:# Canonical loader (managed overlay + env expansion + normalization),# scoped to the bot's home via the override the loaders already honor.+ from agent.skill_utils import parse_config_string_listfrom hermes_cli.config import load_config_readonlyfrom hermes_constants import reset_hermes_home_override, set_hermes_home_override@@ -396,15 +384,13 @@ def capability_fingerprint(home: str | os.PathLike | None = None) -> str: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 []))- # 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)+ # The live selection is platform_toolsets.<platform> minus agent.disabled_toolsets;+ # tools.enabled_toolsets is written by no surface, so watching it left Bot Chats+ # blind to `hermes tools enable/disable` (#124211). Raw slices: an edit that leaves+ # the effective selection unchanged costs one spurious rebuild at most.+ agent_cfg = cfg.get("agent") if isinstance(cfg.get("agent"), dict) else {}+ surface["platform_toolsets"] = json.dumps(cfg.get("platform_toolsets") or {}, sort_keys=True, default=str)+ surface["disabled_toolsets"] = sorted(parse_config_string_list(agent_cfg.get("disabled_toolsets")))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 d638a5fce21..89386334b9c 100644--- a/toolsets.py+++ b/toolsets.py@@ -73,40 +73,6 @@ _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 61d93813120..715fa025334 100644--- a/tui_gateway/server.py+++ b/tui_gateway/server.py@@ -1854,18 +1854,32 @@ def _load_tool_progress_mode() -> str:def _gui_surface_toolsets(platform: str) -> set[str]:- """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)+ """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"}def _with_session_toolsets(selection, platform: str | None) -> list[str]:- """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())+ """*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)]def _tui_notice(text: str) -> None: