Skip to content

The agent that grows with you

fix(agent): a plugin that goes live mid-turn is told in the next tool result, once

alt-glitch57fa33675f6d
diff --git a/agent/plugin_live_notes.py b/agent/plugin_live_notes.py
new file mode 100644
index 00000000000..e9a340d5c4e
--- /dev/null
+++ b/agent/plugin_live_notes.py
@@ -0,0 +1,77 @@
+"""Tell an open chat about a plugin that went live while it runs, once, without breaking its cache.
+
+An install from any surface (the onboarding plugins card, Settings, ``hermes plugins install`` with a
+serve backend) makes the plugin's MCP tools and skills usable in this profile's open chats at once
+(``hermes_cli.plugins_activation.load_and_go_live``) and queues the notice here, one per plugin key: a
+second install or update of the same plugin replaces its notice. The notice rides the next tool result
+of the running turn (``agent/tool_executor.py``), after its content: a new row not yet flushed, so no
+cached byte moves. When no tool runs again this turn, the next user message carries it instead
+(``agent/turn_context.py::_merge_gateway_notes``). Either way it is popped, so it is delivered once.
+"""
+
+from __future__ import annotations
+
+import threading
+from typing import Any
+
+from agent.message_content import flatten_message_text
+
+_QUEUED = "_plugin_live_notes"
+_IN_BATCH = "_plugin_notes_in_tool_batch"
+# The install RPC thread queues while the agent thread delivers.
+_LOCK = threading.Lock()
+
+
+def _queued(agent: Any) -> dict[str, str]:
+ notes = getattr(agent, _QUEUED, None)
+ return notes if isinstance(notes, dict) else {}
+
+
+def queue_plugin_notice(agent: Any, plugin_key: str, note: str) -> None:
+ """Queue ``note`` for ``agent``'s next tool result or user turn; it replaces this plugin's older one."""
+ with _LOCK:
+ notes = {key: text for key, text in _queued(agent).items() if key != plugin_key}
+ notes[plugin_key] = note
+ setattr(agent, _QUEUED, notes)
+
+
+def pop_plugin_notices(agent: Any) -> str:
+ """Every queued notice, oldest plugin first, and clear the queue."""
+ with _LOCK:
+ notes = _queued(agent)
+ if notes:
+ setattr(agent, _QUEUED, {})
+ return "\n\n".join(notes.values())
+
+
+def attach_to_tool_message(agent: Any, message: dict) -> None:
+ """Append every queued notice to ``message``, the tool result about to be appended and flushed. It
+ goes after the content, so a result wrapped as untrusted data keeps the notice outside the wrapper."""
+ notes = pop_plugin_notices(agent)
+ if not notes:
+ return
+ _append(message, notes)
+ in_batch = getattr(agent, _IN_BATCH, None)
+ in_batch = in_batch if isinstance(in_batch, dict) else {}
+ setattr(agent, _IN_BATCH, {**in_batch, message.get("tool_call_id"): notes})
+
+
+def keep_after_turn_budget(agent: Any, batch: list[dict]) -> None:
+ """Put a notice back on a batch row whose content the turn budget spilled to a file: the inline
+ preview keeps only the head, and the notice sits at the tail. The flushed row already holds it."""
+ in_batch = getattr(agent, _IN_BATCH, None)
+ if not isinstance(in_batch, dict) or not in_batch:
+ return
+ setattr(agent, _IN_BATCH, {})
+ for message in batch:
+ notes = in_batch.get(message.get("tool_call_id"))
+ if notes and notes not in flatten_message_text(message.get("content")):
+ _append(message, notes)
+
+
+def _append(message: dict, notes: str) -> None:
+ content = message.get("content")
+ if isinstance(content, list):
+ message["content"] = [*content, {"type": "text", "text": notes}]
+ else:
+ message["content"] = f"{content or ''}\n\n{notes}"
diff --git a/agent/tool_executor.py b/agent/tool_executor.py
index 69f9c962cc3..79d22e2b812 100644
--- a/agent/tool_executor.py
+++ b/agent/tool_executor.py
@@ -34,6 +34,7 @@ from agent.compression_marker import _COMPRESSION_MARKER_PREFIX
from agent.interrupt_control import _REASON_USER_INTERRUPT, interrupt_skip_wording
from agent.message_sanitization import coalesce_tool_call_id
from agent.onboarding import observe_tool_result as observe_onboarding_result
+from agent import plugin_live_notes
from agent.inline_tool_executors import (
INLINE_TOOL_EXECUTORS,
InlineToolContext,
@@ -1142,6 +1143,8 @@ def _commit_tool_result(
# string-safe fallback so a rejected image result never poisons history.
_tool_content = agent._tool_result_content_for_active_model(function_name, persisted_result)
tool_message = make_tool_result_message(function_name, _tool_content, tool_call_id, effect_disposition=effect_disposition)
+ # A plugin that went live during this turn is told on this new row (outside any untrusted-data wrapper).
+ plugin_live_notes.attach_to_tool_message(agent, tool_message)
# Prepare presentation data before the append. The emitting completion callback
# stays below the durability fence; raw tool/model content remains unchanged.
prepare_metadata = getattr(agent, "tool_result_metadata_callback", None)
@@ -1208,6 +1211,7 @@ def _finalize_tool_batch(agent, messages: list, effective_task_id: str, num_tool
batch = messages[-num_tools:]
contents_before = [message.get("content") for message in batch]
enforce_turn_budget(batch, env=get_active_env(effective_task_id), config=budget)
+ plugin_live_notes.keep_after_turn_budget(agent, batch)
record_tool_batch(agent, batch, contents_before)
agent._apply_pending_steer_to_tool_results(messages, num_tools)
diff --git a/agent/turn_context.py b/agent/turn_context.py
index 70d47a6c2ec..ffad01705c6 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -22,6 +22,7 @@ from agent.iteration_budget import IterationBudget
from agent.memory_manager import build_memory_context_block
from agent.memory_provider import is_trivial_prompt
from agent.message_content import flatten_message_text
+from agent.plugin_live_notes import pop_plugin_notices
from agent.skills_index_delta import stage_skills_index_note
from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS, append_message, stamp_message_timestamp
from agent.model_metadata import (
@@ -851,11 +852,11 @@ def _merge_gateway_notes(
agent: Any, messages: list[Any], current_turn_user_idx: int, plugin_user_context: str
) -> str:
"""Must-deliver per-turn notes ride the user-message injection channel (one-shot) so the
- ephemeral system prompt stays byte-stable: the gateway's staged notes, then the
- surface-switch correction. Multimodal (list) content can't take the string sidecar —
- append a durable text part instead."""
+ ephemeral system prompt stays byte-stable: the gateway's staged notes, plugin go-live notices no
+ tool result carried, then the surface-switch correction. Multimodal (list) content can't take the
+ string sidecar — append a durable text part instead."""
_turn_notes = "\n\n".join(
- part for part in (consume_gateway_turn_context_notes(agent),
+ part for part in (consume_gateway_turn_context_notes(agent), pop_plugin_notices(agent),
consume_surface_switch_note(agent),
consume_skills_index_note(agent)) if part
)
diff --git a/hermes_cli/plugins_activation.py b/hermes_cli/plugins_activation.py
index 99ef38be015..24076d0d928 100644
--- a/hermes_cli/plugins_activation.py
+++ b/hermes_cli/plugins_activation.py
@@ -167,7 +167,7 @@ def _go_live(name: str) -> Optional[dict[str, Any]]:
if server is not None and (servers or note):
from hermes_constants import get_hermes_home
try:
- server.refresh_plugin_sessions(Path(get_hermes_home()), note)
+ server.refresh_plugin_sessions(Path(get_hermes_home()), activation["key"], note)
except Exception:
logger.warning("open chats were not refreshed after activating %r", name, exc_info=True)
return activation
diff --git a/tests/agent/test_plugin_live_notes_delivery.py b/tests/agent/test_plugin_live_notes_delivery.py
new file mode 100644
index 00000000000..1ec45d88102
--- /dev/null
+++ b/tests/agent/test_plugin_live_notes_delivery.py
@@ -0,0 +1,141 @@
+"""A plugin that goes live while a turn runs is told to the model in that turn, once.
+
+Onboarding is one long turn: the plugins card blocks inside ``setup_beat`` while the user installs. In
+a live run the go-live notice waited for the next user message and arrived six minutes after the
+install, after the model had already failed to use the plugin. The notice now rides the next tool
+result (a new row, so the cached prefix is untouched); the next user message carries only what no
+tool result did, and nothing is told twice.
+"""
+
+from __future__ import annotations
+
+import copy
+import json
+from pathlib import Path
+import tempfile
+from types import SimpleNamespace
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from agent.plugin_live_notes import queue_plugin_notice
+from run_agent import AIAgent
+from tools.budget_config import BudgetConfig
+
+NOTE = "[System note: plugin blender was installed and is live in this chat now.]"
+OLD_NOTE = "[System note: plugin blender (an older install) is live.]"
+TOOL_OUTPUT = json.dumps({"results": ["a web page about Blender scripting"]})
+
+
[email protected](autouse=True)
+def _no_background_titles(monkeypatch):
+ monkeypatch.setattr("agent.title_generator.maybe_auto_title", lambda *args, **kwargs: None)
+
+
+def _agent():
+ home = Path(tempfile.mkdtemp(prefix="hermes-test-home-"))
+ (home / "logs").mkdir(parents=True, exist_ok=True)
+ tool = {"type": "function", "function": {"name": "web_search", "description": "search",
+ "parameters": {"type": "object", "properties": {}}}}
+ with (
+ patch("model_tools.get_tool_definitions", return_value=[tool]),
+ patch("model_tools.check_toolset_requirements", return_value={}),
+ patch("agent.process_bootstrap.OpenAI"),
+ patch("run_agent._hermes_home", home),
+ patch("agent.model_metadata.fetch_model_metadata", return_value={}),
+ ):
+ agent = AIAgent(api_key="test-key", base_url="https://openrouter.ai/api/v1", quiet_mode=True,
+ skip_context_files=True, skip_memory=True)
+ agent._cached_system_prompt = "You are helpful."
+ agent._use_prompt_caching = False
+ agent.compression_enabled = False
+ agent.save_trajectories = False
+ return agent
+
+
+def _response(content="", tool_call_id=None):
+ calls = [SimpleNamespace(id=tool_call_id, type="function",
+ function=SimpleNamespace(name="web_search", arguments="{}"))] if tool_call_id else None
+ message = SimpleNamespace(content=content, tool_calls=calls)
+ choice = SimpleNamespace(message=message, finish_reason="tool_calls" if calls else "stop")
+ return SimpleNamespace(choices=[choice], model="test/model", usage=None)
+
+
+def _script(agent, *responses):
+ """Answer the model calls in order; return the request each call was sent."""
+ requests, pending = [], list(responses)
+
+ def create(**kwargs):
+ requests.append(copy.deepcopy(kwargs["messages"]))
+ return pending.pop(0)
+
+ agent.client = MagicMock()
+ agent.client.chat.completions.create.side_effect = create
+ return requests
+
+
+def _run(agent, text, history=None, tool_result=lambda: TOOL_OUTPUT):
+ with (
+ patch.object(agent, "_persist_session"),
+ patch.object(agent, "_save_trajectory"),
+ patch.object(agent, "_cleanup_task_resources"),
+ patch("model_tools.handle_function_call", side_effect=lambda *a, **k: tool_result()),
+ ):
+ return agent.run_conversation(text, conversation_history=history)
+
+
+def _sent_text(message) -> str:
+ content = message.get("content")
+ return content if isinstance(content, str) else json.dumps(content)
+
+
+def _install_during_tool():
+ """The plugins card: the user installs (twice: an update) while the tool blocks."""
+ return lambda agent: (queue_plugin_notice(agent, "blender", OLD_NOTE),
+ queue_plugin_notice(agent, "blender", NOTE), TOOL_OUTPUT)[-1]
+
+
+def test_a_plugin_installed_during_a_tool_is_told_in_its_result_and_not_again_next_turn():
+ agent = _agent()
+ requests = _script(agent, _response(tool_call_id="c1"), _response("done"), _response("gg back"))
+ install = _install_during_tool()
+
+ first = _run(agent, "set me up", tool_result=lambda: install(agent))
+ _run(agent, "gg", history=first["messages"])
+
+ in_turn = requests[1] # the model call right after the tool result
+ tool_row = next(m for m in in_turn if m.get("role") == "tool")
+ # After the tool's output and outside the untrusted-data wrapper a web result gets: Hermes' own note.
+ assert TOOL_OUTPUT in tool_row["content"]
+ assert tool_row["content"].endswith(f"</untrusted_tool_result>\n\n{NOTE}")
+ assert OLD_NOTE not in json.dumps(in_turn) # a reinstall replaces the plugin's older notice
+
+ next_turn = requests[2]
+ assert next_turn[-1]["role"] == "user" and NOTE not in _sent_text(next_turn[-1])
+ assert json.dumps(next_turn).count(NOTE.replace('"', '\\"')) == 1
+
+
+def test_a_notice_no_tool_result_carried_rides_the_next_user_message_once():
+ agent = _agent()
+ requests = _script(agent, _response("hi"), _response("still here"))
+
+ queue_plugin_notice(agent, "blender", NOTE)
+ first = _run(agent, "hello")
+ _run(agent, "and now?", history=first["messages"])
+
+ assert NOTE in _sent_text(requests[0][-1])
+ assert NOTE not in _sent_text(requests[1][-1])
+
+
+def test_the_notice_survives_the_turn_budget_spilling_its_tool_result():
+ agent = _agent()
+ requests = _script(agent, _response(tool_call_id="c1"), _response("done"))
+ big = "x" * 20_000
+ install = _install_during_tool()
+
+ with patch("agent.tool_executor._budget_for_agent", return_value=BudgetConfig(turn_budget=16_000)):
+ _run(agent, "set me up", tool_result=lambda: (install(agent), big)[-1])
+
+ tool_row = next(m for m in requests[1] if m.get("role") == "tool")
+ assert big not in tool_row["content"] # spilled to a file, a preview stays inline
+ assert tool_row["content"].endswith(NOTE)
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index 3127960e962..2c5835da80b 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -305,7 +305,8 @@ def _mcp_reload_confirm_required() -> bool:
return True
-def _refresh_live_sessions(home=None, *, preserve_prefix: bool = False, note: str = "") -> None:
+def _refresh_live_sessions(home=None, *, preserve_prefix: bool = False,
+ plugin_note: tuple[str, str] | None = None) -> None:
"""Rebuild live sessions' cached tool snapshots from the registry and push session.info (agents
never re-read the registry). The MCP pool is process-global, so refreshing only the requester
would leave sibling sessions on stale tools until /new — and a request without a resolvable
@@ -314,8 +315,9 @@ def _refresh_live_sessions(home=None, *, preserve_prefix: bool = False, note: st
(config or a just-installed plugin) is in the session's ``tool_call`` scope.
``home``: only sessions of that profile home (a session with no ``profile_home`` belongs to the
- launch home). ``preserve_prefix``: append-only rebuild inside a live conversation. ``note``: queued
- for each session's next turn on the one-shot turn-note channel (``agent/turn_context.py``)."""
+ launch home). ``preserve_prefix``: append-only rebuild inside a live conversation. ``plugin_note``:
+ ``(plugin_key, text)`` queued once per session for its next tool result or turn
+ (``agent/plugin_live_notes.py``)."""
from hermes_constants import hermes_home_key
want = hermes_home_key(home) if home is not None else None
with _sessions_lock:
@@ -332,17 +334,17 @@ def _refresh_live_sessions(home=None, *, preserve_prefix: bool = False, note: st
quiet_mode=True, preserve_prefix=preserve_prefix)
except Exception as _exc:
logger.warning("Failed to refresh cached agent tools (session %s): %s", sid, _exc)
- if note:
- prior = getattr(agent, "_gateway_turn_context_notes", "") or ""
- agent._gateway_turn_context_notes = f"{prior}\n\n{note}" if prior else note
+ if plugin_note:
+ _tools_mod("agent.plugin_live_notes").queue_plugin_notice(agent, *plugin_note)
_emit("session.info", sid, _session_info(agent, sess))
-def refresh_plugin_sessions(home, note: str) -> None:
+def refresh_plugin_sessions(home, plugin_key: str, note: str) -> None:
"""A plugin just went live in ``home``: append its MCP tools to that profile's open chats (deferred
- behind tool_search, so the model-facing tool array is unchanged) and queue ``note`` for their next
- turn. Called by ``hermes_cli.plugins_activation_live``."""
- _refresh_live_sessions(home, preserve_prefix=True, note=note)
+ behind tool_search, so the model-facing tool array is unchanged) and queue ``note``, replacing an
+ older one for ``plugin_key``, for their next tool result or turn. Called by
+ ``hermes_cli.plugins_activation.load_and_go_live``."""
+ _refresh_live_sessions(home, preserve_prefix=True, plugin_note=(plugin_key, note) if note else None)
@_rpc("reload.mcp", 5015)