Skip to content

The agent that grows with you

fix(anthropic): make preserved-thinking replay coherent

joaomarcos582750e3f998
diff --git a/agent/anthropic_message_convert.py b/agent/anthropic_message_convert.py
index 60e400b1b52..b54c41a6a41 100644
--- a/agent/anthropic_message_convert.py
+++ b/agent/anthropic_message_convert.py
@@ -11,6 +11,7 @@ import re
from typing import Any, Dict, List, Optional, Tuple
from agent.image_eviction_policy import outbound_image_retire_count
+from agent.anthropic_thinking_policy import model_preserves_prior_thinking
from agent.anthropic_endpoints import (
_is_deepseek_anthropic_endpoint, _is_kimi_family_endpoint, _is_nous_portal_endpoint,
_is_third_party_anthropic_endpoint, _model_name_is_deepseek_thinking,
@@ -546,10 +547,10 @@ def _merge_consecutive_roles(result: List[Dict[str, Any]]) -> List[Dict[str, Any
return fixed
-def _keep_valid_latest_thinking(content: List[Any], signature_dead: bool) -> List[Any]:
- """Latest assistant turn on direct Anthropic: keep signed thinking, demote unsigned to text so
- the reasoning isn't lost. If orphan-stripping mutated THIS turn every signature is dead (and a
- bare signed block with no tool_use is also invalid), so demote ALL of them."""
+def _keep_valid_thinking(content: List[Any], signature_dead: bool) -> List[Any]:
+ """Keep valid signed Anthropic thinking, demoting readable unsigned/invalidated thinking.
+ Preserved-thinking models apply this to historical turns too; older models apply it only
+ to the latest assistant turn."""
new_content = []
for b in content:
if _block_type(b) not in _THINKING_TYPES:
@@ -568,11 +569,12 @@ def _manage_thinking_signatures(result: List[Dict[str, Any]], base_url: str | No
"""Strip or preserve thinking blocks per endpoint. Mutates ``result`` in place.
Anthropic signs thinking blocks against the full turn; any upstream mutation invalidates them
- (400 "Invalid signature in thinking block"), so on direct Anthropic only the LATEST assistant
- turn keeps signed blocks. Signatures are proprietary: third-party endpoints strip all thinking.
- Kimi replays as-is; DeepSeek needs unsigned blocks round-tripped but rejects signed ones. Nous
- Portal proxies Claude with sticky sessions and validates the same signatures, so it takes the
- native path despite not being anthropic.com.
+ (400 "Invalid signature in thinking block"). Native preserved-thinking models keep valid signed
+ blocks on every assistant turn; older Claude models retain the established latest-turn-only
+ policy. Signatures are proprietary: third-party endpoints strip all thinking. Kimi replays as-is;
+ DeepSeek needs unsigned blocks round-tripped but rejects signed ones. Nous Portal proxies Claude
+ with sticky sessions and validates the same signatures, so it takes the native path despite not
+ being anthropic.com.
"""
is_third_party = _is_third_party_anthropic_endpoint(base_url) and not _is_nous_portal_endpoint(base_url)
is_kimi = _is_kimi_family_endpoint(base_url, model)
@@ -580,6 +582,7 @@ def _manage_thinking_signatures(result: List[Dict[str, Any]], base_url: str | No
is_third_party and _model_name_is_deepseek_thinking(model)
)
last_assistant_idx = next((i for i in range(len(result) - 1, -1, -1) if result[i].get("role") == "assistant"), None)
+ preserve_prior = model_preserves_prior_thinking(model)
for idx, m in _assistant_block_lists(result):
if is_kimi:
pass # shared cleanup below still strips cache markers + the flag
@@ -590,10 +593,10 @@ def _manage_thinking_signatures(result: List[Dict[str, Any]], base_url: str | No
if _block_type(b) not in _THINKING_TYPES or not (b.get("signature") or b.get("data"))
]
m["content"] = new_content or [_text_block("(empty)")]
- elif is_third_party or idx != last_assistant_idx:
+ elif is_third_party or (idx != last_assistant_idx and not preserve_prior):
m["content"] = _strip_thinking(m["content"]) or [_text_block("(thinking elided)")]
else:
- new_content = _keep_valid_latest_thinking(m["content"], bool(m.get("_thinking_signature_invalidated")))
+ new_content = _keep_valid_thinking(m["content"], bool(m.get("_thinking_signature_invalidated")))
m["content"] = new_content or [_text_block("(empty)")]
# cache_control on thinking blocks interferes with signature validation.
for b in m["content"]:
diff --git a/agent/anthropic_thinking_policy.py b/agent/anthropic_thinking_policy.py
new file mode 100644
index 00000000000..1e2333998e1
--- /dev/null
+++ b/agent/anthropic_thinking_policy.py
@@ -0,0 +1,63 @@
+"""Shared Anthropic prior-turn thinking retention policy.
+
+Anthropic preserves and bills prior assistant thinking on Opus 4.5+ and
+Sonnet 4.6+ (plus the newer Fable/Mythos families). Older models accept
+replayed blocks but strip them server-side. Keep the model capability in
+one place so message conversion and context accounting cannot diverge.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import Any
+
+from agent.anthropic_endpoints import (
+ _is_nous_portal_endpoint,
+ _is_third_party_anthropic_endpoint,
+)
+
+
+_CLAUDE_VERSION_RE = re.compile(
+ r"claude[-_.](opus|sonnet|fable|mythos)[-_.](\d+)(?:[-_.](\d+))?",
+ re.IGNORECASE,
+)
+
+
+def _claude_family_version(model: Any) -> tuple[str, tuple[int, int]] | None:
+ if not isinstance(model, str):
+ return None
+ match = _CLAUDE_VERSION_RE.search(model.strip())
+ if not match:
+ return None
+ family = match.group(1).lower()
+ major = int(match.group(2))
+ minor = int(match.group(3) or 0)
+ return family, (major, minor)
+
+
+def model_preserves_prior_thinking(model: Any) -> bool:
+ """Whether Anthropic keeps prior assistant thinking in model-visible context."""
+ if isinstance(model, str) and re.search(
+ r"claude[-_.]mythos[-_.]preview", model.strip(), re.IGNORECASE
+ ):
+ return True
+ parsed = _claude_family_version(model)
+ if parsed is None:
+ return False
+ family, version = parsed
+ if family == "opus":
+ return version >= (4, 5)
+ if family == "sonnet":
+ return version >= (4, 6)
+ if family in {"fable", "mythos"}:
+ return version in {(5, 0), (5, 1)}
+ return False
+
+
+def native_anthropic_preserves_prior_thinking(base_url: Any, model: Any) -> bool:
+ """True for direct Anthropic/Nous Portal routes whose model retains old thinking."""
+ native_route = (
+ not _is_third_party_anthropic_endpoint(base_url)
+ or _is_nous_portal_endpoint(base_url)
+ )
+ return native_route and model_preserves_prior_thinking(model)
diff --git a/agent/anthropic_thinking_replay.py b/agent/anthropic_thinking_replay.py
new file mode 100644
index 00000000000..aff8c0ddda3
--- /dev/null
+++ b/agent/anthropic_thinking_replay.py
@@ -0,0 +1,182 @@
+"""Durable suppression of Anthropic thinking blocks rejected by signature validation.
+
+A signature failure is request-specific evidence about opaque replay blocks, not a reason
+to erase canonical reasoning history. Store only hashes of rejected signatures in the
+session model config, filter every replay carrier on retry, and reapply the suppression
+when a later request (or resumed process) rebuilds the wire copy.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import logging
+from typing import Any, Iterable
+
+
+logger = logging.getLogger(__name__)
+
+_MODEL_CONFIG_KEY = "_anthropic_rejected_thinking"
+_THINKING_TYPES = frozenset({"thinking", "redacted_thinking"})
+
+
+def _opaque_value(block: Any) -> Any:
+ if not isinstance(block, dict):
+ return None
+ if block.get("type") == "thinking":
+ return block.get("signature")
+ if block.get("type") == "redacted_thinking":
+ return block.get("data")
+ return None
+
+
+def _fingerprint(block: Any) -> str | None:
+ value = _opaque_value(block)
+ if value in (None, "", b""):
+ return None
+ try:
+ payload = json.dumps(value, sort_keys=True, ensure_ascii=True, default=str)
+ except (TypeError, ValueError):
+ payload = repr(value)
+ kind = str(block.get("type") if isinstance(block, dict) else "")
+ return hashlib.sha256(f"{kind}\0{payload}".encode("utf-8", "replace")).hexdigest()
+
+
+def _carrier_lists(message: Any) -> Iterable[list]:
+ if not isinstance(message, dict):
+ return
+ for key in ("reasoning_details", "anthropic_content_blocks", "_anthropic_content_blocks"):
+ value = message.get(key)
+ if isinstance(value, list):
+ yield value
+
+
+def _collect_fingerprints(messages: Any) -> set[str]:
+ found: set[str] = set()
+ if not isinstance(messages, list):
+ return found
+ for message in messages:
+ for blocks in _carrier_lists(message):
+ for block in blocks:
+ if isinstance(block, dict) and block.get("type") in _THINKING_TYPES:
+ if fp := _fingerprint(block):
+ found.add(fp)
+ return found
+
+
+def _decode_state(raw: Any) -> tuple[set[str], bool]:
+ if isinstance(raw, list):
+ return ({v for v in raw if isinstance(v, str) and v}, False)
+ if not isinstance(raw, dict):
+ return set(), False
+ values = raw.get("fingerprints")
+ fingerprints = {
+ value for value in (values if isinstance(values, list) else [])
+ if isinstance(value, str) and value
+ }
+ return fingerprints, bool(raw.get("strip_all"))
+
+
+def _load_state(agent: Any) -> tuple[set[str], bool]:
+ if getattr(agent, "_anthropic_rejected_thinking_loaded", False):
+ return (
+ set(getattr(agent, "_anthropic_rejected_thinking_fingerprints", set()) or set()),
+ bool(getattr(agent, "_anthropic_rejected_thinking_strip_all", False)),
+ )
+
+ fingerprints: set[str] = set()
+ strip_all = False
+ getter = getattr(getattr(agent, "_session_db", None), "get_session_model_config_value", None)
+ session_id = getattr(agent, "session_id", None)
+ if session_id and callable(getter):
+ try:
+ fingerprints, strip_all = _decode_state(getter(session_id, _MODEL_CONFIG_KEY, None))
+ except Exception:
+ logger.debug("Anthropic thinking suppression restore failed", exc_info=True)
+
+ agent._anthropic_rejected_thinking_fingerprints = fingerprints
+ agent._anthropic_rejected_thinking_strip_all = strip_all
+ agent._anthropic_rejected_thinking_loaded = True
+ return fingerprints, strip_all
+def _persist_state(agent: Any, fingerprints: set[str], strip_all: bool) -> None:
+ if getattr(agent, "_persist_disabled", False):
+ return
+ patcher = getattr(getattr(agent, "_session_db", None), "patch_session_model_config", None)
+ session_id = getattr(agent, "session_id", None)
+ if not session_id or not callable(patcher):
+ return
+ value = {
+ "fingerprints": sorted(fingerprints),
+ "strip_all": bool(strip_all),
+ }
+ try:
+ patcher(session_id, {_MODEL_CONFIG_KEY: value})
+ except Exception:
+ logger.debug("Anthropic thinking suppression persist failed", exc_info=True)
+
+
+def _should_remove(block: Any, fingerprints: set[str], strip_all: bool) -> bool:
+ if not isinstance(block, dict) or block.get("type") not in _THINKING_TYPES:
+ return False
+ if strip_all:
+ return True
+ fp = _fingerprint(block)
+ return fp is not None and fp in fingerprints
+
+
+def _filter_message(message: Any, fingerprints: set[str], strip_all: bool) -> int:
+ if not isinstance(message, dict):
+ return 0
+ removed = 0
+ for key in ("reasoning_details", "anthropic_content_blocks", "_anthropic_content_blocks"):
+ blocks = message.get(key)
+ if not isinstance(blocks, list):
+ continue
+ kept = []
+ for block in blocks:
+ if _should_remove(block, fingerprints, strip_all):
+ removed += 1
+ else:
+ kept.append(block)
+ if kept:
+ message[key] = kept
+ else:
+ message.pop(key, None)
+ return removed
+
+
+def apply_rejected_thinking_suppression(agent: Any, messages: Any) -> int:
+ """Filter previously rejected thinking from a freshly built request copy."""
+ if getattr(agent, "api_mode", None) != "anthropic_messages" or not isinstance(messages, list):
+ return 0
+ fingerprints, strip_all = _load_state(agent)
+ if not fingerprints and not strip_all:
+ return 0
+ return sum(_filter_message(message, fingerprints, strip_all) for message in messages)
+
+
+def remember_rejected_thinking(agent: Any, api_messages: Any) -> int:
+ """Remember signed blocks from a rejected request and remove them from every carrier.
+
+ The provider error generally does not identify which signed block failed, so all signed
+ thinking blocks in that rejected request become suppressed suspects. New blocks produced
+ later have different signatures and continue to replay normally.
+ """
+ if not isinstance(api_messages, list):
+ return 0
+
+ current = _collect_fingerprints(api_messages)
+ fingerprints, strip_all = _load_state(agent)
+ if current:
+ fingerprints.update(current)
+ else:
+ # Defensive fallback: a signature-classified error without an inspectable signature
+ # must still change the retry request instead of burning the one-shot on identical bytes.
+ strip_all = True
+
+ agent._anthropic_rejected_thinking_fingerprints = fingerprints
+ agent._anthropic_rejected_thinking_strip_all = strip_all
+ agent._anthropic_rejected_thinking_loaded = True
+ _persist_state(agent, fingerprints, strip_all)
+
+ return sum(_filter_message(message, fingerprints, strip_all) for message in api_messages)
diff --git a/agent/message_sanitization.py b/agent/message_sanitization.py
index 1377f5de8b5..a6d7aaa2751 100644
--- a/agent/message_sanitization.py
+++ b/agent/message_sanitization.py
@@ -631,6 +631,10 @@ def stale_thinking_reaches_wire(api_mode: Any, provider: Any, model: Any, base_u
to preflight yet fully tail-protected to the walk — an infinite compaction loop.
``codex_responses`` never reads the text keys (continuity rides the encrypted sidecar).
"""
+ if (api_mode or "") == "anthropic_messages":
+ from agent.anthropic_thinking_policy import native_anthropic_preserves_prior_thinking
+ if native_anthropic_preserves_prior_thinking(base_url, model):
+ return True
return (api_mode or "") != "codex_responses" and needs_reasoning_echo(provider, model, base_url)
diff --git a/agent/turn_context.py b/agent/turn_context.py
index ac00c87229b..53db4271e9a 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -1286,6 +1286,11 @@ def build_api_messages(
# wire for every route that does not replay it (OpenRouter/Nous do).
api_messages.append(api_msg)
+ # A provider-rejected Anthropic signature is suppressed outside canonical history and
+ # survives fresh request construction / process resume via session model_config.
+ from agent.anthropic_thinking_replay import apply_rejected_thinking_suppression
+ apply_rejected_thinking_suppression(agent, api_messages)
+
# Final system message = cached prompt + ephemeral additions (API-time only).
# Plugin/recall context goes into the user message, never the system prompt: the
# prompt is built ONCE per session and replayed verbatim (stable cache prefix).
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index 5fdb1627853..ad599bbc364 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -490,21 +490,28 @@ def _recover_format_errors(
"""One-shot format-recovery strips: thinking-signature → invalid-encrypted-content
replay disable → native-compaction reject → llama.cpp grammar strip. Returns True when
the request was repaired and should be retried."""
- # Upstream mutation invalidates Anthropic's thinking-block signature (400). Strip
- # ``reasoning_details`` from ``api_messages`` only, never ``messages`` (state.db).
+ # Upstream mutation can invalidate a thinking signature. Native Anthropic has multiple replay
+ # carriers and preserved historical blocks, so suppress the rejected opaque blocks across all
+ # carriers and persist that suppression. Other transports keep their established one-request
+ # repair: drop reasoning_details only.
if classified.reason == FailoverReason.thinking_signature and not _retry.thinking_sig_retry_attempted:
_retry.thinking_sig_retry_attempted = True
- _api_stripped = 0
- for _m in api_messages:
- if isinstance(_m, dict) and "reasoning_details" in _m:
- _m.pop("reasoning_details", None)
- _api_stripped += 1
- _vlines(agent, "⚠️ Thinking block signature invalid, stripped reasoning_details from api_messages for retry...")
+ if getattr(agent, "api_mode", None) == "anthropic_messages":
+ from agent.anthropic_thinking_replay import remember_rejected_thinking
+ removed = remember_rejected_thinking(agent, api_messages)
+ detail = "suppressed rejected Anthropic replay blocks"
+ else:
+ removed = 0
+ for message in api_messages:
+ if isinstance(message, dict) and "reasoning_details" in message:
+ message.pop("reasoning_details", None)
+ removed += 1
+ detail = "stripped reasoning_details"
+ _vlines(agent, f"⚠️ Thinking block signature invalid, {detail} and retrying...")
logger.warning(
- "%sThinking block signature recovery: stripped "
- "reasoning_details from %d api_messages "
+ "%sThinking block signature recovery: %s from %d carrier/message(s) "
"(canonical messages unchanged)",
- agent.log_prefix, _api_stripped,
+ agent.log_prefix, detail, removed,
)
return True
diff --git a/tests/agent/test_anthropic_preserved_thinking_replay.py b/tests/agent/test_anthropic_preserved_thinking_replay.py
new file mode 100644
index 00000000000..ace26db4083
--- /dev/null
+++ b/tests/agent/test_anthropic_preserved_thinking_replay.py
@@ -0,0 +1,239 @@
+from __future__ import annotations
+
+import copy
+from types import SimpleNamespace
+
+import pytest
+
+from agent.anthropic_message_convert import convert_messages_to_anthropic
+from agent.message_sanitization import stale_thinking_reaches_wire
+from agent.model_metadata import estimate_messages_tokens_rough
+
+
+def _signed_turn(question: str, answer: str, sig: str, *, thinking: str | None = None):
+ return [
+ {"role": "user", "content": question},
+ {
+ "role": "assistant",
+ "content": answer,
+ "reasoning": thinking or f"thought-{sig}",
+ "reasoning_details": [
+ {"type": "thinking", "thinking": thinking or f"thought-{sig}", "signature": sig}
+ ],
+ },
+ ]
+
+
+def _assistant(messages, index: int):
+ return [m for m in messages if m["role"] == "assistant"][index]
+ ("model", "expected"),
+ [
+ ("claude-opus-4-4", False),
+ ("claude-opus-4-5", True),
+ ("claude-opus-4-6", True),
+ ("claude-sonnet-4-5", False),
+ ("claude-sonnet-4-6", True),
+ ("claude-opus-5", True),
+ ("claude-sonnet-5-5", True),
+ ("claude-fable-5-1", True),
+ ("claude-mythos-5", True),
+ ("claude-mythos-preview", True),
+ ("claude-haiku-4-5", False),
+ ],
+)
+def test_native_anthropic_wire_truth_tracks_preserved_thinking_models(model, expected):
+ assert stale_thinking_reaches_wire(
+ "anthropic_messages", "anthropic", model, "https://api.anthropic.com"
+ ) is expected
+
+
+def test_formerly_latest_turn_stays_byte_stable_on_preserved_thinking_model():
+ prefix = _signed_turn("Q1", "A1", "sig_1") + _signed_turn("Q2", "A2", "sig_2")
+ _, short = convert_messages_to_anthropic(prefix, model="claude-opus-4-6")
+ _, long = convert_messages_to_anthropic(
+ prefix + _signed_turn("Q3", "A3", "sig_3"), model="claude-opus-4-6"
+ )
+
+ assert _assistant(short, 1) == _assistant(long, 1)
+ assert _assistant(long, 1)["content"][0]["signature"] == "sig_2"
+def test_older_claude_keeps_latest_only_policy():
+ messages = _signed_turn("Q1", "A1", "sig_1") + _signed_turn("Q2", "A2", "sig_2")
+ _, converted = convert_messages_to_anthropic(messages, model="claude-sonnet-4-5")
+
+ first, second = (_assistant(converted, 0), _assistant(converted, 1))
+ assert not any(
+ isinstance(block, dict) and block.get("type") in {"thinking", "redacted_thinking"}
+ for block in first["content"]
+ )
+ assert any(
+ isinstance(block, dict) and block.get("type") == "thinking"
+ for block in second["content"]
+ )
+
+
+def test_preserved_thinking_accounting_charges_historical_turns():
+ thinking = "x" * 8000
+ messages = (
+ _signed_turn("Q1", "A1", "sig_1", thinking=thinking)
+ + _signed_turn("Q2", "A2", "sig_2", thinking=thinking)
+ + _signed_turn("Q3", "A3", "sig_3", thinking=thinking)
+ )
+ keep_all = estimate_messages_tokens_rough(messages, charge_stale_thinking=True)
+ latest_only = estimate_messages_tokens_rough(messages, charge_stale_thinking=False)
+
+ assert keep_all - latest_only >= 3500
+
+
+class _ConfigDB:
+ def __init__(self):
+ self.config = {}
+
+ def patch_session_model_config(self, session_id, patch):
+ self.config.update(patch)
+
+ def get_session_model_config_value(self, session_id, key, default=None):
+ return self.config.get(key, default)
+
+
+def _agent(db):
+ return SimpleNamespace(
+ api_mode="anthropic_messages",
+ provider="anthropic",
+ model="claude-opus-4-6",
+ base_url="https://api.anthropic.com",
+ session_id="session-1",
+ _session_db=db,
+ _persist_disabled=False,
+ )
+def _carrier_message():
+ return {
+ "role": "assistant",
+ "content": "answer",
+ "reasoning_details": [
+ {"type": "thinking", "thinking": "secret chain", "signature": "sig_bad"},
+ {"type": "redacted_thinking", "data": "red_bad"},
+ ],
+ "anthropic_content_blocks": [
+ {"type": "thinking", "thinking": "secret chain", "signature": "sig_bad"},
+ {"type": "text", "text": "answer"},
+ {"type": "tool_use", "id": "tool_1", "name": "search", "input": {"q": "x"}},
+ {"type": "redacted_thinking", "data": "red_bad"},
+ ],
+ }
+
+
+def test_rejected_signature_is_removed_from_every_carrier_and_persists_across_resume():
+ from agent.anthropic_thinking_replay import (
+ apply_rejected_thinking_suppression,
+ remember_rejected_thinking,
+ )
+
+ db = _ConfigDB()
+ first_agent = _agent(db)
+ request = [_carrier_message()]
+
+ removed = remember_rejected_thinking(first_agent, request)
+ assert removed >= 4
+ assert "reasoning_details" not in request[0]
+ assert [b["type"] for b in request[0]["anthropic_content_blocks"]] == ["text", "tool_use"]
+
+ resumed_agent = _agent(db)
+ rebuilt = [_carrier_message()]
+ apply_rejected_thinking_suppression(resumed_agent, rebuilt)
+ assert "reasoning_details" not in rebuilt[0]
+ assert [b["type"] for b in rebuilt[0]["anthropic_content_blocks"]] == ["text", "tool_use"]
+
+
+def test_build_api_messages_applies_persisted_rejection_suppression():
+ from agent.anthropic_thinking_replay import remember_rejected_thinking
+ from agent.turn_context import build_api_messages
+
+ db = _ConfigDB()
+ first_agent = _agent(db)
+ rejected = [_carrier_message()]
+ remember_rejected_thinking(first_agent, rejected)
+
+ resumed = _agent(db)
+ resumed._current_turn_timestamp = 1.0
+ resumed.ephemeral_system_prompt = ""
+ resumed._copy_reasoning_content_for_api = lambda source, target: None
+ resumed._should_sanitize_tool_calls = lambda: False
+
+ history = [
+ {"role": "user", "content": "Q"},
+ _carrier_message(),
+ {"role": "user", "content": "continue"},
+ ]
+ api_messages, _ = build_api_messages(
+ resumed,
+ copy.deepcopy(history),
+ current_turn_user_idx=2,
+ ext_prefetch_cache="",
+ plugin_user_context="",
+ moa_config=None,
+ active_system_prompt="",
+ )
+
+ assistant = next(m for m in api_messages if m.get("role") == "assistant")
+ assert "reasoning_details" not in assistant
+ assert [b["type"] for b in assistant["anthropic_content_blocks"]] == ["text", "tool_use"]
+
+
+def test_nous_portal_uses_same_preserved_thinking_capability_boundary():
+ assert stale_thinking_reaches_wire(
+ "anthropic_messages",
+ "nous",
+ "claude-opus-4-6",
+ "https://inference-api.nousresearch.com/v1/messages",
+ )
+ assert not stale_thinking_reaches_wire(
+ "anthropic_messages",
+ "openrouter",
+ "claude-opus-4-6",
+ "https://openrouter.ai/api/v1",
+ )
+
+
+
+
+def test_turn_recovery_repairs_recognized_anthropic_signature_rejection():
+ from agent.error_classifier import FailoverReason
+ from agent.turn_recovery import _recover_format_errors
+ from agent.turn_retry_state import TurnRetryState
+
+ db = _ConfigDB()
+ agent = _agent(db)
+ agent.log_prefix = ""
+ agent._vprint = lambda *args, **kwargs: None
+
+ canonical = [_carrier_message()]
+ canonical_before = copy.deepcopy(canonical)
+ request = copy.deepcopy(canonical)
+ retry = TurnRetryState()
+ classified = SimpleNamespace(reason=FailoverReason.thinking_signature)
+
+ assert _recover_format_errors(
+ agent,
+ RuntimeError("Invalid signature in thinking block"),
+ classified,
+ retry,
+ canonical,
+ request,
+ )
+ assert retry.thinking_sig_retry_attempted
+ assert canonical == canonical_before
+ assert "reasoning_details" not in request[0]
+ assert [block["type"] for block in request[0]["anthropic_content_blocks"]] == [
+ "text",
+ "tool_use",
+ ]
+
+ rebuilt = copy.deepcopy(canonical)
+ from agent.anthropic_thinking_replay import apply_rejected_thinking_suppression
+ apply_rejected_thinking_suppression(_agent(db), rebuilt)
+ assert "reasoning_details" not in rebuilt[0]
+ assert [block["type"] for block in rebuilt[0]["anthropic_content_blocks"]] == [
+ "text",
+ "tool_use",
+ ]