Skip to content

The agent that grows with you

fix(api-server): anchor the Responses current turn on this turn's user row, not a history prefix match

teknium1d19963782b74
diff --git a/gateway/platforms/api_server_openai_routes.py b/gateway/platforms/api_server_openai_routes.py
index 33dbeea597f..186010e8f2d 100644
--- a/gateway/platforms/api_server_openai_routes.py
+++ b/gateway/platforms/api_server_openai_routes.py
@@ -88,28 +88,6 @@ def _message_item(text: Any) -> Dict[str, Any]:
"content": [{"type": "output_text", "text": text}]}
-_TRANSCRIPT_IDENTITY_KEYS = ("role", "content", "tool_calls", "tool_call_id")
-
-
-def _same_transcript_prefix(agent_messages: List[Any], prefix: List[Any]) -> bool:
- """True when ``agent_messages`` starts with ``prefix`` by what each message *says*.
-
- The API layer builds bare ``{"role", "content"}`` dicts while the agent stamps its copies
- with ``timestamp`` / ``_db_persisted`` / ``reasoning`` / ``finish_reason``; whole-dict
- equality therefore never matched and every chained turn re-appended the full prior
- transcript (#95137, #101644, #82513)."""
- if len(agent_messages) < len(prefix):
- return False
- for got, want in zip(agent_messages, prefix):
- if not isinstance(got, dict) or not isinstance(want, dict):
- if got != want:
- return False
- continue
- if any(got.get(k) != want.get(k) for k in _TRANSCRIPT_IDENTITY_KEYS):
- return False
- return True
-
-
def _cap_text(text: str, keep: int) -> str:
"""Head of ``text`` plus a marker saying how much was cut (the Responses truncation rule)."""
return text[:keep] + "...[" + str(len(text) - keep) + " more chars]"
@@ -1182,17 +1160,9 @@ class OpenAICompatRoutesMixin:
def _response_messages_turn_start_index(
conversation_history: List[Dict[str, Any]], user_message: Any, result: Dict[str, Any],
) -> int:
- """Detect transcript-shaped result["messages"] and return turn start."""
- agent_messages = result.get("messages") if isinstance(result, dict) else None
- if not isinstance(agent_messages, list) or not agent_messages:
- return 0
- prior = list(conversation_history)
- expected_prefix = prior + [{"role": "user", "content": user_message}]
- if _same_transcript_prefix(agent_messages, expected_prefix):
- return len(expected_prefix)
- if prior and _same_transcript_prefix(agent_messages, prior):
- return len(prior)
- return 0
+ """Index where this turn starts in a transcript-shaped result["messages"] (0 = all)."""
+ from gateway.platforms.api_server_turn_boundary import response_turn_start_index
+ return response_turn_start_index(conversation_history, user_message, result)
@classmethod
def _turn_transcript_messages(
diff --git a/gateway/platforms/api_server_turn_boundary.py b/gateway/platforms/api_server_turn_boundary.py
new file mode 100644
index 00000000000..0731abb52f9
--- /dev/null
+++ b/gateway/platforms/api_server_turn_boundary.py
@@ -0,0 +1,61 @@
+"""Current-turn boundary inside an agent transcript returned to the OpenAI-compat routes.
+
+``AIAgent.run_conversation`` hands back the FULL transcript (client history + this turn),
+and the routes need the index where this turn starts to build Responses ``output`` items,
+``run.completed`` turn transcripts and the stored ``previous_response_id`` history.
+"""
+from typing import Any, Dict, List
+
+_TRANSCRIPT_IDENTITY_KEYS = ("role", "content", "tool_calls", "tool_call_id")
+
+
+def _same_transcript_prefix(agent_messages: List[Any], prefix: List[Any]) -> bool:
+ """True when ``agent_messages`` starts with ``prefix`` by what each message *says*.
+
+ The API layer builds bare ``{"role", "content"}`` dicts while the agent stamps its copies
+ with ``timestamp`` / ``_db_persisted`` / ``reasoning`` / ``finish_reason``; whole-dict
+ equality therefore never matched and every chained turn re-appended the full prior
+ transcript (#95137, #101644, #82513)."""
+ if len(agent_messages) < len(prefix):
+ return False
+ for got, want in zip(agent_messages, prefix):
+ if not isinstance(got, dict) or not isinstance(want, dict):
+ if got != want:
+ return False
+ continue
+ if any(got.get(k) != want.get(k) for k in _TRANSCRIPT_IDENTITY_KEYS):
+ return False
+ return True
+
+
+def response_turn_start_index(
+ conversation_history: List[Dict[str, Any]], user_message: Any, result: Dict[str, Any],
+) -> int:
+ """Index in ``result["messages"]`` where this turn's assistant/tool rows begin (0 = all).
+
+ Anchored on this turn's user row (the loop's canonical ``reanchor_current_turn_user_idx``),
+ not on prefix equality with the client history: the loop repairs host-fed history before
+ the first call (merging consecutive assistant/user rows, dropping stray tool results) and
+ compaction rewrites it, so the returned transcript legitimately stops sharing a prefix with
+ ``conversation_history`` and a prefix match then returned 0 — the whole transcript was
+ treated as the current turn, replaying earlier ``function_call`` items and doubling the
+ stored history on every chained turn (#89891).
+
+ Mocked/legacy paths return only this turn's suffix (no user row): the prefix match stays as
+ the fallback for them.
+ """
+ from agent.turn_context import reanchor_current_turn_user_idx
+
+ agent_messages = result.get("messages") if isinstance(result, dict) else None
+ if not isinstance(agent_messages, list) or not agent_messages:
+ return 0
+ user_idx = reanchor_current_turn_user_idx(agent_messages, user_message)
+ if user_idx >= 0:
+ return user_idx + 1
+ prior = list(conversation_history)
+ expected_prefix = prior + [{"role": "user", "content": user_message}]
+ if _same_transcript_prefix(agent_messages, expected_prefix):
+ return len(expected_prefix)
+ if prior and _same_transcript_prefix(agent_messages, prior):
+ return len(prior)
+ return 0
diff --git a/tests/gateway/test_api_server_responses_history_dedupe.py b/tests/gateway/test_api_server_responses_history_dedupe.py
index a7ca3910c1f..2d59557850f 100644
--- a/tests/gateway/test_api_server_responses_history_dedupe.py
+++ b/tests/gateway/test_api_server_responses_history_dedupe.py
@@ -36,11 +36,10 @@ def test_chained_responses_turns_store_each_message_once():
assert [m["role"] for m in history] == ["user", "assistant"] * 3
-def test_divergent_transcript_still_falls_back_to_appending():
+def test_suffix_only_result_still_appends_to_history():
build = APIServerAdapter._build_response_conversation_history
prior = [{"role": "user", "content": "a"}, {"role": "assistant", "content": "b"}]
- # A transcript whose first row differs in what it says is not a prefix match.
- result = {"messages": [{"role": "user", "content": "DIFFERENT", "timestamp": 1.0},
- {"role": "assistant", "content": "d"}]}
+ # Mocked/legacy paths return only this turn's rows (no user row): appended after the input.
+ result = {"messages": [{"role": "assistant", "content": "d"}]}
stored = build(prior, "c", result, "d")
- assert [m["content"] for m in stored] == ["a", "b", "c", "DIFFERENT", "d"]
+ assert [m["content"] for m in stored] == ["a", "b", "c", "d"]
diff --git a/tests/gateway/test_api_server_turn_boundary.py b/tests/gateway/test_api_server_turn_boundary.py
new file mode 100644
index 00000000000..2ea4bc43fea
--- /dev/null
+++ b/tests/gateway/test_api_server_turn_boundary.py
@@ -0,0 +1,66 @@
+"""The Responses current-turn boundary is anchored on this turn's user row, not on prefix
+equality with the client history (#89891).
+
+The loop repairs host-fed history before its first call (consecutive assistant rows merge,
+stray tool results drop) and compaction rewrites it, so ``result["messages"]`` legitimately
+stops sharing a prefix with ``conversation_history``. A prefix match then reported 0 and the
+whole transcript became "the current turn": earlier ``function_call`` items were replayed as
+this turn's output and the stored history doubled on every chained turn.
+"""
+
+from agent.agent_runtime_helpers import repair_message_sequence
+from agent.message_metadata import append_message
+from gateway.platforms.api_server import APIServerAdapter
+
+
+class _Agent:
+ api_mode = "chat_completions"
+ session_id = "s"
+
+
+def _tool_turn(messages, call_id, answer):
+ append_message(messages, {"role": "assistant", "content": "", "tool_calls": [
+ {"id": call_id, "type": "function", "function": {"name": "terminal", "arguments": "{}"}}]})
+ append_message(messages, {"role": "tool", "tool_call_id": call_id, "content": "ok"})
+ append_message(messages, {"role": "assistant", "content": answer, "finish_reason": "stop"})
+
+
+def test_repaired_earlier_rows_keep_only_this_turn_as_output():
+ # A stateless client replays two consecutive assistant items; the loop merges them, so the
+ # transcript is one row shorter than the client history from index 1 on.
+ history = [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello"},
+ {"role": "assistant", "content": "again"}]
+ prompt = "Q1: run the tool"
+ messages = list(history)
+ append_message(messages, {"role": "user", "content": prompt})
+ repair_message_sequence(_Agent(), messages)
+ _tool_turn(messages, "call-current", "done")
+ result = {"messages": messages}
+
+ start = APIServerAdapter._response_messages_turn_start_index(history, prompt, result)
+ items = APIServerAdapter._extract_output_items(result, start_index=start)
+ assert messages[start - 1]["content"] == prompt
+ assert [i["type"] for i in items] == ["function_call", "function_call_output", "message"]
+ # Stored as the agent's transcript, not client history + transcript again.
+ stored = APIServerAdapter._build_response_conversation_history(history, prompt, result, "done")
+ assert [m["role"] for m in stored] == ["user", "assistant", "user", "assistant", "tool", "assistant"]
+
+
+def test_compacted_transcript_keeps_only_this_turn_as_output():
+ # Compaction replaced the oldest rows with a summary carrier and kept the recent
+ # tool-bearing turn verbatim: nothing before the current user row is this turn's output.
+ history = [{"role": "user", "content": "old ask"}, {"role": "assistant", "content": "old answer"},
+ {"role": "user", "content": "recent ask"}]
+ messages = [{"role": "user", "content": "[Compressed summary of earlier turns]"},
+ {"role": "assistant", "content": "Understood."},
+ {"role": "user", "content": "recent ask"}]
+ _tool_turn(messages, "call-old", "recent answer")
+ history = history + [dict(m) for m in messages[3:]]
+ append_message(messages, {"role": "user", "content": "Q2"})
+ _tool_turn(messages, "call-current", "answer 2")
+ result = {"messages": messages, "_compressed": True}
+
+ start = APIServerAdapter._response_messages_turn_start_index(history, "Q2", result)
+ items = APIServerAdapter._extract_output_items(result, start_index=start)
+ assert [i["type"] for i in items] == ["function_call", "function_call_output", "message"]
+ assert items[0]["call_id"] == "call-current"
diff --git a/website/docs/user-guide/features/api-server.md b/website/docs/user-guide/features/api-server.md
index 4c469d6a7fc..94d9c9daa3d 100644
--- a/website/docs/user-guide/features/api-server.md
+++ b/website/docs/user-guide/features/api-server.md
@@ -187,6 +187,8 @@ Chain responses to maintain full context (including tool calls) across turns:
The server reconstructs the full conversation from the stored response chain — all previous tool calls and results are preserved. Chained requests also share the same session, so multi-turn conversations appear as a single entry in the dashboard and session history.
+Each response's `output` lists only that turn's items (its `function_call` / `function_call_output` entries and final `message`), never earlier turns' tool calls — including when Hermes repaired the supplied history before the call (merged consecutive `assistant` or `user` items, dropped orphan tool results) or compacted it mid-chain. The stored chain is that repaired transcript, so the history does not grow by a second copy on every turn.
+
#### Named conversations
Use the `conversation` parameter instead of tracking response IDs: