The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(anthropic): keep rejected-thinking state scoped to its session and route
kshitijk4poorc29704d1a6cd
diff --git a/agent/anthropic_thinking_replay.py b/agent/anthropic_thinking_replay.pyindex 0a0dccc13bc..da925699de3 100644--- a/agent/anthropic_thinking_replay.py+++ b/agent/anthropic_thinking_replay.py@@ -3,7 +3,8 @@Canonical history stays untouched. We persist only fingerprints of rejected opaquesignature/data values, then filter those blocks from each rebuilt request copy. This isneeded beyond the immediate retry because context selection and process resume can rebuild-from canonical history later.+from canonical history later. The state belongs to one session (and is carried onto its+compression continuation); it applies only where Anthropic signs the blocks."""from __future__ import annotations@@ -18,7 +19,6 @@ logger = logging.getLogger(__name__)_MODEL_CONFIG_KEY = "_anthropic_rejected_thinking"_THINKING_TYPES = frozenset({"thinking", "redacted_thinking"})_CARRIERS = ("reasoning_details", "anthropic_content_blocks", "_anthropic_content_blocks")-_STRIP_ALL = "*"def _fingerprint(block: Any) -> str | None:@@ -32,29 +32,37 @@ def _fingerprint(block: Any) -> str | None:return hashlib.sha256(f"{kind}\0{payload}".encode("utf-8", "replace")).hexdigest()-def _rejected(agent: Any) -> set[str]:- if hasattr(agent, "_anthropic_rejected_thinking"):- return set(getattr(agent, "_anthropic_rejected_thinking") or set())+def tracks_rejected_thinking(agent: Any) -> bool:+ """Native Anthropic signatures only: Kimi, DeepSeek and third-party routes keep their own replay+ contract and the one-request ``reasoning_details`` repair."""+ from agent.anthropic_thinking_policy import anthropic_thinking_route++ return getattr(agent, "api_mode", None) == "anthropic_messages" and anthropic_thinking_route(+ getattr(agent, "base_url", None), getattr(agent, "model", None)+ ) == "native"+++def rejected_thinking_fingerprints(session_db: Any, session_id: Any) -> set[str]:+ """The persisted rejection fingerprints of ``session_id``."""+ getter = getattr(session_db, "get_session_model_config_value", None)+ if not session_id or not callable(getter):+ return set()+ try:+ raw = getter(session_id, _MODEL_CONFIG_KEY, [])+ except Exception:+ logger.debug("Anthropic thinking suppression restore failed", exc_info=True)+ return set()+ return {value for value in raw if isinstance(value, str) and value} if isinstance(raw, list) else set()+- rejected: set[str] = set()- getter = getattr(getattr(agent, "_session_db", None), "get_session_model_config_value", None)+def _rejected(agent: Any) -> set[str]:+ # Keyed by session: /new, /resume, /branch and compression rotate ``session_id`` on a live agent.session_id = getattr(agent, "session_id", None)- if session_id and callable(getter):- try:- raw = getter(session_id, _MODEL_CONFIG_KEY, [])- if isinstance(raw, list):- rejected.update(value for value in raw if isinstance(value, str) and value)- elif isinstance(raw, dict):- # Compatibility with the earlier review-fix head.- values = raw.get("fingerprints")- if isinstance(values, list):- rejected.update(value for value in values if isinstance(value, str) and value)- if raw.get("strip_all"):- rejected.add(_STRIP_ALL)- except Exception:- logger.debug("Anthropic thinking suppression restore failed", exc_info=True)-- agent._anthropic_rejected_thinking = rejected+ cached = getattr(agent, "_anthropic_rejected_thinking", None)+ if isinstance(cached, tuple) and cached[0] == session_id:+ return cached[1]+ rejected = rejected_thinking_fingerprints(getattr(agent, "_session_db", None), session_id)+ agent._anthropic_rejected_thinking = (session_id, rejected)return rejected@@ -71,33 +79,25 @@ def _persist(agent: Any, rejected: set[str]) -> None:logger.debug("Anthropic thinking suppression persist failed", exc_info=True)-def _mirrored_readable_thinking(message: Any) -> str | None:- if not isinstance(message, dict):- return None- for key in ("reasoning_details", "anthropic_content_blocks"):- blocks = message.get(key)- if not isinstance(blocks, list):- continue- readable = [- block.get("thinking")- for block in blocks- if (- isinstance(block, dict)- and block.get("type") == "thinking"- and isinstance(block.get("thinking"), str)- and block.get("thinking")- )- ]- if readable:- return "\n\n".join(readable)- return None+def _mirrored_readable_thinking(message: dict) -> str | None:+ from agent.anthropic_message_convert import assistant_replay_carrier+ _, carrier = assistant_replay_carrier(message)+ readable = [+ block["thinking"]+ for block in carrier+ if block.get("type") == "thinking" and isinstance(block.get("thinking"), str) and block["thinking"]+ ]+ return "\n\n".join(readable) if readable else None-def _strip_message(message: Any, rejected: set[str]) -> int:++def strip_rejected_thinking(message: Any, rejected: set[str] | None) -> int:+ """Drop rejected thinking blocks (every thinking block when ``rejected`` is None) from one request+ copy. Rebinds carrier keys on ``message`` only; the nested canonical lists are never mutated."""if not isinstance(message, dict):return 0- mirror = _mirrored_readable_thinking(message)+ mirror = _mirrored_readable_thinking(message) if message.get("role") == "assistant" else Noneremoved = 0for key in _CARRIERS:blocks = message.get(key)@@ -109,7 +109,7 @@ def _strip_message(message: Any, rejected: set[str]) -> int:if (isinstance(block, dict)and block.get("type") in _THINKING_TYPES- and (_STRIP_ALL in rejected or (fingerprint is not None and fingerprint in rejected))+ and (rejected is None or (fingerprint is not None and fingerprint in rejected))):removed += 1else:@@ -130,12 +130,12 @@ def _strip_message(message: Any, rejected: set[str]) -> int:def apply_rejected_thinking_suppression(agent: Any, messages: Any) -> int:"""Filter rejected thinking from a request copy rebuilt from canonical history."""- if getattr(agent, "api_mode", None) != "anthropic_messages" or not isinstance(messages, list):+ if not isinstance(messages, list) or not tracks_rejected_thinking(agent):return 0rejected = _rejected(agent)if not rejected:return 0- return sum(_strip_message(message, rejected) for message in messages)+ return sum(strip_rejected_thinking(message, rejected) for message in messages)def remember_rejected_thinking(agent: Any, api_messages: Any) -> int:@@ -151,14 +151,31 @@ def remember_rejected_thinking(agent: Any, api_messages: Any) -> int:for block in (message.get(key) if isinstance(message.get(key), list) else ())if (fingerprint := _fingerprint(block)) is not None}- rejected = _rejected(agent)- rejected.update(current or {_STRIP_ALL})- agent._anthropic_rejected_thinking = rejected- _persist(agent, rejected)-# The provider-visible history changed while the canonical content fingerprint did# not, so a previous prompt-token anchor is no longer valid for this request shape.from agent.usage_anchor import set_usage_anchorset_usage_anchor(agent, None)- return sum(_strip_message(message, rejected) for message in api_messages)+ if not current:+ # Nothing to fingerprint: repair this retry copy only. A persisted strip-all would also+ # drop every valid signature the session produces later.+ return sum(strip_rejected_thinking(message, None) for message in api_messages)+ rejected = _rejected(agent)+ rejected.update(current)+ _persist(agent, rejected)+ return sum(strip_rejected_thinking(message, rejected) for message in api_messages)+++def carry_rejected_thinking_to_session(agent: Any, old_session_id: str) -> None:+ """Compression publishes the child with the session's initial model_config while its retained+ tail still holds the rejected canonical rows; carry the fingerprints onto ``agent.session_id``."""+ cached = getattr(agent, "_anthropic_rejected_thinking", None)+ if isinstance(cached, tuple) and cached[0] == old_session_id:+ rejected = set(cached[1])+ else:+ rejected = rejected_thinking_fingerprints(getattr(agent, "_session_db", None), old_session_id)+ if not rejected:+ return+ rejected |= _rejected(agent)+ agent._anthropic_rejected_thinking = (getattr(agent, "session_id", None), rejected)+ _persist(agent, rejected)diff --git a/agent/conversation_compression.py b/agent/conversation_compression.pyindex f832e65dd75..9398e3b5e42 100644--- a/agent/conversation_compression.py+++ b/agent/conversation_compression.py@@ -3292,7 +3292,7 @@ def _parent_deliberately_ended(session_db: Any, session_id: str) -> bool:def _carry_session_state_to_child(agent: Any, old_session_id: str, old_title: Any) -> None:- """Migrate /goal, /heartbeat, /loop state and the title from the parent to the child.+ """Migrate /goal, /heartbeat, /loop state, rejected-thinking fingerprints and the title from the parent to the child.Each lookup is a flat per-session read with no parent walk, so state would silently die at the boundary. The titleis carried unchanged (renumbering per rotation made one session look like many); its provenance is read BEFORE thetransfer clears the ancestor's row, then restored so an inherited auto-title stays upgradeable.@@ -3309,6 +3309,9 @@ def _carry_session_state_to_child(agent: Any, old_session_id: str, old_title: Anwith _swallow('Could not migrate loop on compression: %s'):from hermes_cli.loops import migrate_loop_to_sessionmigrate_loop_to_session(old_session_id, agent.session_id, reason="compression")+ with _swallow('Could not carry rejected thinking on compression: %s'):+ from agent.anthropic_thinking_replay import carry_rejected_thinking_to_session+ carry_rejected_thinking_to_session(agent, old_session_id)if not old_title:return_src = Nonediff --git a/agent/turn_recovery.py b/agent/turn_recovery.pyindex ad599bbc364..994d6607edc 100644--- a/agent/turn_recovery.py+++ b/agent/turn_recovery.py@@ -496,8 +496,9 @@ def _recover_format_errors(# repair: drop reasoning_details only.if classified.reason == FailoverReason.thinking_signature and not _retry.thinking_sig_retry_attempted:_retry.thinking_sig_retry_attempted = True- if getattr(agent, "api_mode", None) == "anthropic_messages":- from agent.anthropic_thinking_replay import remember_rejected_thinking+ from agent.anthropic_thinking_replay import remember_rejected_thinking, tracks_rejected_thinking++ if tracks_rejected_thinking(agent):removed = remember_rejected_thinking(agent, api_messages)detail = "suppressed rejected Anthropic replay blocks"else: