The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(loop): export {turn_id, current_turn_user_idx} on every result envelope
Felipe Portavales37f42713ef73
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex bb1afe163ad..6f9eff403c2 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -1407,7 +1407,7 @@ def _run_api_retry_loop(agent, s: _LoopState) -> Optional[Dict[str, Any]]:return None-def run_conversation(+def _run_conversation_turn(agent,user_message: Any,system_message: str = None,@@ -1555,6 +1555,46 @@ def run_conversation(return result+def run_conversation(+ agent,+ user_message: Any,+ system_message: str = None,+ conversation_history: List[Dict[str, Any]] = None,+ task_id: str = None,+ stream_callback: Optional[callable] = None,+ persist_user_message: Optional[Any] = None,+ persist_user_timestamp: Optional[float] = None,+ persist_user_display_kind: Optional[str] = None,+ persist_user_display_metadata: Optional[Dict[str, Any]] = None,+ persist_user_platform_id: Optional[str] = None,+ moa_config: Optional[dict[str, Any]] = None,+) -> Dict[str, Any]:+ """Run one turn (see ``_run_conversation_turn``) and export the current-turn boundary.++ Every envelope that leaves the loop — success, partial/error, interrupt, retry-exhausted,+ tool-limit, preflight timeout, codex runtime — passes through here, so the+ ``{turn_id, current_turn_user_idx}`` pair is stamped beside the exact ``messages`` it+ addresses, after every history rewrite including post-turn micro-compaction.+ """+ from agent.turn_context import export_current_turn_boundary++ result = _run_conversation_turn(+ agent,+ user_message,+ system_message=system_message,+ conversation_history=conversation_history,+ task_id=task_id,+ stream_callback=stream_callback,+ persist_user_message=persist_user_message,+ persist_user_timestamp=persist_user_timestamp,+ persist_user_display_kind=persist_user_display_kind,+ persist_user_display_metadata=persist_user_display_metadata,+ persist_user_platform_id=persist_user_platform_id,+ moa_config=moa_config,+ )+ return export_current_turn_boundary(agent, result, user_message)++__all__ = ["run_conversation"]diff --git a/agent/turn_context.py b/agent/turn_context.pyindex 3fa0c304168..eb071645438 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -244,6 +244,44 @@ def reanchor_current_turn_user_idx(messages: List[Any], user_message: Any) -> inreturn fallback+def export_current_turn_boundary(agent: Any, result: Any, user_message: Any) -> Any:+ """Stamp ``{turn_id, current_turn_user_idx}`` on a result envelope, proven against the+ exact ``result["messages"]`` projection it travels with.++ Hosts that settle their own transcript by index (hermes-webui) must never guess which+ row is the current user turn after this loop rewrote history (alternation repair,+ compaction, post-turn micro-compaction): a guessed index or a text match can relabel an+ identical historical prompt and claim its old answer as this turn's. So the producer+ exports the coordinate, computed on the final list, only when the addressed row is this+ turn's user message verbatim. Otherwise the keys are omitted and hosts fail closed.+ Also mirrors the final index into ``_persist_user_message_idx`` so the persist override+ targets the surviving row after post-turn micro-compaction.+ """+ if not isinstance(result, dict):+ return result+ messages = result.get("messages")+ turn_id = str(getattr(agent, "_current_turn_id", "") or "")+ if not isinstance(messages, list) or not turn_id or user_message is None:+ return result+ idx = reanchor_current_turn_user_idx(messages, user_message)+ if idx < 0 or idx >= len(messages):+ return result+ row = messages[idx]+ if not (isinstance(row, dict) and row.get("role") == "user"):+ return result+ from agent.context_compressor import user_originated_turn_view++ live_view = user_originated_turn_view(row)+ if row.get("content") != user_message and not (+ isinstance(live_view, dict) and live_view.get("content") == user_message+ ):+ return result # rewritten (merge-into-tail) row: not a proven boundary+ result["turn_id"] = turn_id+ result["current_turn_user_idx"] = idx+ agent._persist_user_message_idx = idx+ return result++def compression_made_progress(orig_len: int, new_len: int, orig_tokens: int, new_tokens: int) -> bool:diff --git a/agent/turn_iteration_prep.py b/agent/turn_iteration_prep.pyindex fe7e56c74aa..70c126512fe 100644--- a/agent/turn_iteration_prep.py+++ b/agent/turn_iteration_prep.py@@ -193,6 +193,11 @@ def prepare_iteration(# a stale anchor injects prefetch into a historical row and makes hosts that settle# their transcript by this index (hermes-webui) write the current turn to the FRONT# of the context, rewriting the prompt's leading messages every turn.+ # reanchor_current_turn_user_idx scans from the tail: with two identical user+ # rows it resolves to the LAST one, i.e. this turn, never the historical copy.+ # Without the message text the index cannot be re-derived; leave it (an+ # out-of-range index is detectably stale, a clamped one would silently target+ # a wrong row)._reanchored_idx = (reanchor_current_turn_user_idx(messages, user_message) if user_message is not Noneelse current_turn_user_idxdiff --git a/tests/run_agent/test_export_current_turn_boundary.py b/tests/run_agent/test_export_current_turn_boundary.pynew file mode 100644index 00000000000..65f07accd2f--- /dev/null+++ b/tests/run_agent/test_export_current_turn_boundary.py@@ -0,0 +1,131 @@+"""The loop exports ``{turn_id, current_turn_user_idx}`` beside the exact ``messages`` it+addresses, and only when that row is this turn's user message verbatim.++Hosts that settle a transcript by index (hermes-webui) must not guess the current-turn+row after the loop rewrote history (alternation repair, compaction, post-turn+micro-compaction): with a repeated prompt a guessed index or a text match relabels the+historical copy and claims its old answer. The producer therefore proves the coordinate on+the final list; when it cannot, the keys are omitted and hosts fail closed.+"""++from __future__ import annotations++from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++from agent.turn_context import export_current_turn_boundary+++class _Agent:+ def __init__(self, turn_id="session:task:abcd1234"):+ self._current_turn_id = turn_id+ self._persist_user_message_idx = None+++def test_repeated_prompt_resolves_to_the_last_verbatim_row():+ messages = [+ {"role": "user", "content": "same question"},+ {"role": "assistant", "content": "old answer"},+ {"role": "user", "content": "same question"},+ {"role": "assistant", "content": "new answer"},+ ]+ agent = _Agent()+ result = export_current_turn_boundary(agent, {"messages": messages}, "same question")+ assert result["current_turn_user_idx"] == 2+ assert result["turn_id"] == agent._current_turn_id+ assert agent._persist_user_message_idx == 2+++def test_missing_current_row_exports_nothing():+ messages = [+ {"role": "user", "content": "same question"},+ {"role": "assistant", "content": "old answer"},+ ]+ agent = _Agent()+ result = export_current_turn_boundary(agent, {"messages": messages}, "another question")+ assert "current_turn_user_idx" not in result and "turn_id" not in result+ assert agent._persist_user_message_idx is None+++def test_rewritten_row_is_not_a_proven_boundary():+ # merge-into-tail rewrote the surviving row's content: reanchor would fall back to it,+ # but the export refuses to claim a row that is not the verbatim message.+ messages = [+ {"role": "user", "content": "summary\n\nsame question"},+ {"role": "assistant", "content": "answer"},+ ]+ result = export_current_turn_boundary(_Agent(), {"messages": messages}, "same question")+ assert "current_turn_user_idx" not in result+++def test_multimodal_content_is_matched_verbatim():+ content = [{"type": "text", "text": "look"}, {"type": "image_url", "image_url": {"url": "data:x"}}]+ messages = [{"role": "user", "content": content}, {"role": "assistant", "content": "ok"}]+ result = export_current_turn_boundary(_Agent(), {"messages": messages}, content)+ assert result["current_turn_user_idx"] == 0+++def test_no_turn_id_or_non_dict_result_is_left_alone():+ assert export_current_turn_boundary(_Agent(turn_id=""), {"messages": [{"role": "user", "content": "q"}]}, "q") == {+ "messages": [{"role": "user", "content": "q"}]+ }+ assert export_current_turn_boundary(_Agent(), None, "q") is None+++def loop_agent():+ from run_agent import AIAgent++ with (+ patch("model_tools.get_tool_definitions", return_value=[]),+ patch("model_tools.check_toolset_requirements", return_value={}),+ patch("agent.process_bootstrap.OpenAI"),+ ):+ a = AIAgent(+ api_key="test-key-1234567890",+ base_url="https://openrouter.ai/api/v1",+ quiet_mode=True,+ skip_context_files=True,+ skip_memory=True,+ )+ a.client = MagicMock()+ a._cached_system_prompt = "You are helpful."+ a._use_prompt_caching = False+ a.compression_enabled = False+ a.save_trajectories = False+ return a+++def _stub(content, finish_reason="stop"):+ from tests.run_agent.test_run_agent import _mock_assistant_msg++ return SimpleNamespace(+ id="chatcmpl-test",+ model="test/model",+ choices=[SimpleNamespace(index=0, message=_mock_assistant_msg(content=content), finish_reason=finish_reason)],+ usage=None,+ )+++def test_run_conversation_exports_the_pair_on_a_success_envelope(loop_agent):+ loop_agent.client.chat.completions.create.side_effect = [_stub("new answer")]+ history = [+ {"role": "user", "content": "same question"},+ {"role": "assistant", "content": "old answer"},+ ]+ with (+ patch.object(loop_agent, "_persist_session"),+ patch.object(loop_agent, "_save_trajectory"),+ patch.object(loop_agent, "_cleanup_task_resources"),+ ):+ result = loop_agent.run_conversation("same question", conversation_history=history)++ assert result["completed"] is True+ idx = result["current_turn_user_idx"]+ assert result["messages"][idx]["role"] == "user"+ assert result["messages"][idx]["content"] == "same question"+ assert idx > 0 # the historical identical prompt at index 0 is never the export+ assert result["turn_id"] == loop_agent._current_turn_id+ assert result["messages"][-1]["content"] == "new answer"