The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(memory): carry the turn's author to sync_turn
Erosika8969511209af
diff --git a/agent/memory_manager.py b/agent/memory_manager.pyindex bc23f6617b4..4cdd5e6911a 100644--- a/agent/memory_manager.py+++ b/agent/memory_manager.py@@ -472,27 +472,31 @@ class MemoryManager:), kind="prefetch")@staticmethod- def _provider_sync_accepts_messages(provider: MemoryProvider) -> bool:- """Whether ``sync_turn`` accepts a ``messages`` keyword (uninspectable → assume yes)."""+ def _provider_sync_accepts(provider: MemoryProvider, keyword: str) -> bool:+ """Whether ``sync_turn`` accepts ``keyword`` (uninspectable → assume yes)."""params = _signature_params(provider.sync_turn)- return params is None or _has_var_kwargs(params) or "messages" in params+ return params is None or _has_var_kwargs(params) or keyword in paramsdef sync_all(self, user_content: str, assistant_content: str, *, session_id: str = "",- messages: Optional[List[Dict[str, Any]]] = None) -> None:+ messages: Optional[List[Dict[str, Any]]] = None,+ turn_author: Optional[Dict[str, Any]] = None) -> None:"""Sync a completed turn to all providers on the background worker.Never inline: a provider's ``sync_turn`` may block for minutes, which kept ``run_conversation``open after the user saw the response. The single worker also serializes writes (turn N before N+1).+ ``turn_author`` reaches only providers whose ``sync_turn`` accepts it."""providers = list(self._providers)clean_user_content = self._strip_skill_scaffolding(user_content) if providers else Noneif not clean_user_content:return+ optional_kwargs = {"messages": messages, "turn_author": turn_author}def _sync(provider: MemoryProvider) -> None:kwargs: Dict[str, Any] = {"session_id": session_id}- if messages is not None and self._provider_sync_accepts_messages(provider):- kwargs["messages"] = messages+ for keyword, value in optional_kwargs.items():+ if value is not None and self._provider_sync_accepts(provider, keyword):+ kwargs[keyword] = valueprovider.sync_turn(clean_user_content, assistant_content, **kwargs)self._submit_background(diff --git a/agent/memory_provider.py b/agent/memory_provider.pyindex d4a21c74bea..81e12ae21ed 100644--- a/agent/memory_provider.py+++ b/agent/memory_provider.py@@ -107,8 +107,11 @@ class MemoryProvider(ABC):def sync_turn(self, user_content: str, assistant_content: str, *,session_id: str = "", messages: Optional[List[Dict[str, Any]]] = None,+ turn_author: Optional[Dict[str, Any]] = None,) -> None:- """Persist a completed turn (non-blocking). ``messages`` is the OpenAI-style list so far."""+ """Persist a completed turn (non-blocking). ``messages`` is the OpenAI-style list so far.+ ``turn_author`` (``{"id", "name", "is_bot"}``) is who wrote the user side of this turn.+ Providers may ignore it. The manager sends it only to signatures that accept it."""@abstractmethoddef get_tool_schemas(self) -> List[Dict[str, Any]]:@@ -125,9 +128,16 @@ class MemoryProvider(ABC):def on_turn_start(self, turn_number: int, message: str, **kwargs) -> None:"""Per-turn tick. kwargs may include remaining_tokens, model, platform, tool_count,- author_id, author_name, author_is_bot. The author trio names who wrote THIS turn: a shared- session carries several participants and other agents, so a provider keying durable state- on identity must read it per turn. All three are absent when the transport gave no author."""+ author_id, author_name, author_is_bot. The author trio names who wrote THIS turn:+ a shared session carries several participants and other agents, so a provider keying durable+ state on identity must read it per turn. All three are None when the transport gave no author."""++ def identity_signature(self) -> Dict[str, Any]:+ """Identity-mapping values that must bust a cached gateway agent when they change: which+ user/agent identity the provider writes under, alias tables, session-name prefixing. Keys are+ namespaced by the provider; values are JSON-serializable primitives or sorted lists. The gateway+ calls this on an uninitialized instance on every inbound message, so keep it cheap and read-only."""+ return {}def on_session_end(self, messages: List[Dict[str, Any]]) -> None:"""End-of-session extraction; fires only at real session boundaries, never per-turn."""diff --git a/agent/turn_author.py b/agent/turn_author.pynew file mode 100644index 00000000000..8b69c6f9580--- /dev/null+++ b/agent/turn_author.py@@ -0,0 +1,58 @@+"""Who wrote the user side of a turn, carried from the dispatcher into the recipient's turn.++The dispatcher sets ``HERMES_TURN_AUTHOR`` on the recipient's one-shot subprocess only. A cached+gateway agent sees several authors over its lifetime, so the author is read per turn, never per agent.+"""++from __future__ import annotations++import json+import os+from typing import Any, Dict, Mapping, Optional++TURN_AUTHOR_ENV = "HERMES_TURN_AUTHOR"++_MAX_FIELD_LEN = 200+++def _clean_text(value: Any) -> Optional[str]:+ """Strip whitespace and control characters, cap the length; None when nothing is left."""+ if not isinstance(value, str):+ return None+ text = "".join(ch for ch in value if ch.isprintable()).strip()+ if not text:+ return None+ return text[:_MAX_FIELD_LEN]+++def parse_turn_author(raw: Any) -> Optional[Dict[str, Any]]:+ """Normalize a dict or JSON string into ``{"id", "name", "is_bot"}``; None for anything else. Never raises."""+ try:+ if isinstance(raw, (str, bytes)):+ raw = json.loads(raw)+ if not isinstance(raw, Mapping):+ return None+ return {+ "id": _clean_text(raw.get("id")),+ "name": _clean_text(raw.get("name")),+ "is_bot": bool(raw.get("is_bot")),+ }+ except Exception:+ return None+++def turn_author_from_env(environ: Mapping[str, str] = os.environ) -> Optional[Dict[str, Any]]:+ """The author the dispatcher placed in ``HERMES_TURN_AUTHOR``, or None."""+ return parse_turn_author(environ.get(TURN_AUTHOR_ENV))+++def turn_author_env(author: Dict[str, Any]) -> Dict[str, str]:+ """The environment entry a dispatcher merges into a child's env."""+ return {TURN_AUTHOR_ENV: json.dumps(author, separators=(",", ":"))}+++def a2a_key(author: Optional[Dict[str, Any]]) -> Optional[str]:+ """``a2a:<bot id>``, the shared name for a bot author's turns. None for a human or an id-less bot."""+ if not isinstance(author, dict) or not author.get("is_bot") or not author.get("id"):+ return None+ return f"a2a:{author['id']}"diff --git a/agent/turn_context.py b/agent/turn_context.pyindex e2ec8471dba..0629e6a3045 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -25,6 +25,7 @@ from agent.message_metadata import append_message, stamp_message_timestampfrom agent.model_metadata import estimate_messages_tokens_rough, estimate_request_tokens_roughfrom agent.image_token_cost import bind_image_token_costfrom agent.usage_anchor import anchored_context_tokens, restore_usage_anchor+from agent.turn_author import parse_turn_authorlogger = logging.getLogger(__name__)@@ -869,6 +870,11 @@ def build_turn_context(# Guard stdio against OSError from broken pipes (systemd/headless/daemon).install_safe_stdio()+ # Reset first: a cached gateway agent must never carry the previous turn's bot author into a+ # human turn. The end-of-turn memory sync reads these back.+ turn_author = parse_turn_author(turn_author)+ agent._turn_author = turn_author+# Recover a rotated session before binding log/turn ids or copying client history so# everything in this turn belongs to the canonical child.recovered_history = recover_rotated_compression_session(agent)diff --git a/run_agent.py b/run_agent.pyindex 49d390ced1d..305200ae0cb 100644--- a/run_agent.py+++ b/run_agent.py@@ -404,6 +404,8 @@ class AIAgent(# Turn counter (added after reset_session_state was first written — #2635)self._user_turn_count = 0+ # Who wrote the current turn; build_turn_context() sets it at the start of every turn.+ self._turn_author = None# Copilot x-initiator: True for the first API call of a user turn, False for tool-loop follow-ups.self._is_user_initiated_turn = False@@ -891,6 +893,10 @@ class AIAgent(returntry:sync_kwargs = {"session_id": self.session_id or "", **({"messages": messages} if messages is not None else {})}+ # Stashed by build_turn_context() for this turn; None on a human turn.+ turn_author = getattr(self, "_turn_author", None)+ if turn_author is not None:+ sync_kwargs["turn_author"] = turn_authorself._memory_manager.sync_all(user_text, response_text, **sync_kwargs)# Sibling of the build_turn_context() prefetch gate: don't key recall on zero-signal prompts.if not is_trivial_prompt(user_text):diff --git a/tests/agent/test_memory_provider.py b/tests/agent/test_memory_provider.pyindex b4243ce9b34..4e6decd63a1 100644--- a/tests/agent/test_memory_provider.py+++ b/tests/agent/test_memory_provider.py@@ -94,6 +94,13 @@ class MessagesMemoryProvider(FakeMemoryProvider):self.synced_turns.append((user_content, assistant_content, session_id, messages))+class AuthorMemoryProvider(FakeMemoryProvider):+ """Provider that opts into the per-turn author."""++ def sync_turn(self, user_content, assistant_content, *, session_id="", messages=None, turn_author=None):+ self.synced_turns.append((user_content, assistant_content, turn_author))++class BlockingPrefetchProvider(FakeMemoryProvider):"""External provider whose prefetch call blocks until released."""@@ -138,6 +145,9 @@ class TestMemoryProviderABC:p.sync_turn("user", "assistant")p.shutdown()+ def test_identity_signature_defaults_to_empty(self):+ assert FakeMemoryProvider().identity_signature() == {}+# ---------------------------------------------------------------------------# MemoryManager tests@@ -268,6 +278,41 @@ class TestMemoryManager:assert legacy_provider.synced_turns == [("user", "assistant")]+ def test_sync_all_forwards_author_and_scope_only_to_providers_that_accept_them(self):+ """A bot turn reaches the new-signature provider with its author; legacy and messages-only+ providers get the call without the keywords they cannot take."""+ legacy = FakeMemoryProvider("legacy")+ messages_only = MessagesMemoryProvider("messages")+ author_aware = AuthorMemoryProvider("author")+ author = {"id": "bot:alpha", "name": "Alpha", "is_bot": True}++ # One manager per provider: a manager admits a single external provider.+ for p in (legacy, messages_only, author_aware):+ mgr = MemoryManager()+ mgr.add_provider(p)+ mgr.sync_all("user", "assistant", session_id="s1", turn_author=author)+ mgr.flush_pending(timeout=5)++ assert legacy.synced_turns == [("user", "assistant")]+ assert messages_only.synced_turns == [("user", "assistant", "s1", None)]+ assert author_aware.synced_turns == [("user", "assistant", author)]++ def test_sync_all_without_author_sends_none_to_author_aware_provider(self):+ mgr = MemoryManager()+ author_aware = AuthorMemoryProvider("author")+ mgr.add_provider(author_aware)++ mgr.sync_all("user", "assistant")+ mgr.flush_pending(timeout=5)++ assert author_aware.synced_turns == [("user", "assistant", None)]++ def test_provider_sync_accepts_inspects_named_keyword(self):+ assert MemoryManager._provider_sync_accepts(AuthorMemoryProvider(), "turn_author")+ assert not MemoryManager._provider_sync_accepts(MessagesMemoryProvider(), "turn_author")+ assert not MemoryManager._provider_sync_accepts(FakeMemoryProvider(), "messages")+ assert MemoryManager._provider_sync_accepts_messages(MessagesMemoryProvider())+# -- Tool routing -------------------------------------------------------diff --git a/tests/agent/test_turn_author.py b/tests/agent/test_turn_author.pynew file mode 100644index 00000000000..1b5bc74f8f4--- /dev/null+++ b/tests/agent/test_turn_author.py@@ -0,0 +1,76 @@+"""Tests for agent.turn_author: the per-turn author carried from a dispatcher to memory hooks."""++import json++import pytest++from agent.turn_author import (+ TURN_AUTHOR_ENV,+ a2a_key,+ parse_turn_author,+ turn_author_env,+ turn_author_from_env,+)+++class TestParseTurnAuthor:+ def test_dict_is_normalized(self):+ out = parse_turn_author({"id": " bot:alpha ", "name": "Alpha", "is_bot": True, "extra": 1})+ assert out == {"id": "bot:alpha", "name": "Alpha", "is_bot": True}++ def test_json_string_is_parsed(self):+ raw = json.dumps({"id": "bot:alpha", "name": "Alpha", "is_bot": 1})+ assert parse_turn_author(raw) == {"id": "bot:alpha", "name": "Alpha", "is_bot": True}++ def test_missing_fields_default(self):+ assert parse_turn_author({}) == {"id": None, "name": None, "is_bot": False}++ @pytest.mark.parametrize("raw", [None, 42, [], ["bot:alpha"], "not json", '"a string"', "[1, 2]", b"\xff"])+ def test_junk_returns_none(self, raw):+ assert parse_turn_author(raw) is None++ def test_non_string_fields_become_none(self):+ assert parse_turn_author({"id": 7, "name": ["x"], "is_bot": "yes"}) == {+ "id": None, "name": None, "is_bot": True,+ }++ def test_empty_and_whitespace_become_none(self):+ assert parse_turn_author({"id": "", "name": " "}) == {"id": None, "name": None, "is_bot": False}++ def test_control_characters_are_stripped(self):+ out = parse_turn_author({"id": "bot:\x00al\x1bpha\n", "name": "Al\tpha\r"})+ assert out["id"] == "bot:alpha"+ assert out["name"] == "Alpha"++ def test_oversize_fields_are_capped(self):+ out = parse_turn_author({"id": "x" * 500, "name": "y" * 201})+ assert len(out["id"]) == 200+ assert len(out["name"]) == 200+++class TestEnvCarrier:+ def test_round_trip_through_env(self):+ author = {"id": "bot:alpha", "name": "Alpha", "is_bot": True}+ env = turn_author_env(author)+ assert set(env) == {TURN_AUTHOR_ENV}+ assert turn_author_from_env(env) == author++ def test_env_json_is_compact(self):+ assert turn_author_env({"id": "a", "is_bot": True})[TURN_AUTHOR_ENV] == '{"id":"a","is_bot":true}'++ def test_absent_env_is_none(self):+ assert turn_author_from_env({}) is None++ def test_garbage_env_is_none(self):+ assert turn_author_from_env({TURN_AUTHOR_ENV: "{not json"}) is None++[email protected]("author, expected", [+ ({"id": "bot:coder", "name": "coder", "is_bot": True}, "a2a:bot:coder"),+ ({"id": "5551234", "name": "SomeBot", "is_bot": True}, "a2a:5551234"),+ ({"id": "111222", "name": "Alice", "is_bot": False}, None),+ ({"id": None, "name": "mystery", "is_bot": True}, None),+ (None, None),+])+def test_a2a_key_names_a_bot_authors_turns(author, expected):+ assert a2a_key(author) == expecteddiff --git a/tests/agent/test_turn_context.py b/tests/agent/test_turn_context.pyindex 3125f86a97e..bb66d574fb2 100644--- a/tests/agent/test_turn_context.py+++ b/tests/agent/test_turn_context.py@@ -292,6 +292,40 @@ def test_prefetch_runs_for_substantive_user_message():assert ctx.ext_prefetch_cache == "REMEMBERED CONTEXT"+# ── Per-turn author ──────────────────────────────────────────────────────────+++def test_turn_author_is_normalized_then_reaches_on_turn_start_and_the_agent_stash():+ agent, mm = _agent_with_memory_manager()++ _build(agent, user_message="what did we decide about the deploy pipeline?",+ turn_author={"id": " bot:al\x00pha ", "name": "Alpha", "is_bot": 1, "x": 1})++ kwargs = mm.on_turn_start.call_args.kwargs+ assert (kwargs["author_id"], kwargs["author_name"], kwargs["author_is_bot"]) == ("bot:alpha", "Alpha", True)+ # The end-of-turn sync reads this back off the agent.+ assert agent._turn_author == {"id": "bot:alpha", "name": "Alpha", "is_bot": True}+++def test_turn_without_author_clears_previous_bot_author():+ agent, mm = _agent_with_memory_manager()+ _build(agent, user_message="first turn", turn_author={"id": "bot:alpha", "name": "Alpha", "is_bot": True})+ assert agent._turn_author["id"] == "bot:alpha"++ _build(agent, user_message="second turn")++ assert agent._turn_author is None+ kwargs = mm.on_turn_start.call_args.kwargs+ assert kwargs["author_id"] is None+ assert kwargs["author_is_bot"] is False+++def test_author_is_stashed_even_without_memory_manager():+ agent = _FakeAgent()+ _build(agent, turn_author={"id": "bot:alpha", "name": "Alpha", "is_bot": True})+ assert agent._turn_author == {"id": "bot:alpha", "name": "Alpha", "is_bot": True}++def test_turn_start_replaces_stale_parent_history_with_compression_child():agent = _FakeAgent()stale_history = [{"role": "user", "content": "stale parent"}]diff --git a/tests/run_agent/test_memory_sync_interrupted.py b/tests/run_agent/test_memory_sync_interrupted.pyindex 5325e18bf38..e879676d1fa 100644--- a/tests/run_agent/test_memory_sync_interrupted.py+++ b/tests/run_agent/test_memory_sync_interrupted.py@@ -54,6 +54,33 @@ class TestSyncExternalMemoryForTurn:agent._memory_manager.sync_all.assert_not_called()agent._memory_manager.queue_prefetch_all.assert_not_called()+ # --- Per-turn author (stashed by build_turn_context) -----------------++ def test_stashed_bot_author_reaches_sync_all(self):+ agent = _bare_agent()+ agent._turn_author = {"id": "bot:alpha", "name": "Alpha", "is_bot": True}++ agent._sync_external_memory_for_turn(+ original_user_message="Message from Alpha: status?", final_response="All green.", interrupted=False,+ )++ kwargs = agent._memory_manager.sync_all.call_args.kwargs+ assert kwargs["turn_author"] == {"id": "bot:alpha", "name": "Alpha", "is_bot": True}+ assert kwargs["session_id"] == "test_session_001"++ @pytest.mark.parametrize("stash", ["human turn", "no stash yet"])+ def test_human_turn_or_agent_without_stash_sends_no_author_keyword(self, stash):+ """A bare agent built before any turn has no stash; the sync must not depend on it."""+ agent = _bare_agent()+ if stash == "human turn":+ agent._turn_author = None++ agent._sync_external_memory_for_turn(+ original_user_message="status?", final_response="All green.", interrupted=False,+ )++ agent._memory_manager.sync_all.assert_called_once()+ assert "turn_author" not in agent._memory_manager.sync_all.call_args.kwargs# --- Normal completed turn still syncs ------------------------------