The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: OpenAI and xAI models keep reasoning across turns and through compaction
Teknium3a53716ce417
diff --git a/agent/codex_responses_adapter.py b/agent/codex_responses_adapter.pyindex 4063e61780c..43f67df3b89 100644--- a/agent/codex_responses_adapter.py+++ b/agent/codex_responses_adapter.py@@ -55,6 +55,80 @@ def _wire_model_identity(model: Any) -> Optional[str]:return str(strip_codex_context_variant_suffix(model or "")).strip() or None++# api.openai.com model families that accept ``reasoning.context: "all_turns"`` and honour a reasoning blob+# minted by a sibling variant of the same family (LIVE: gpt-5.4<->5.4-mini, 5.5->5.5-pro, 5.6-luna<->terra,+# 6-astra<->6.1-sol all rendered the blob). o-series, base gpt-5-mini/nano and gpt-5.1/5.2/5.3-codex 400 on+# all_turns, so they are deliberately absent; a blob from another family is silently left out (200), so those+# keep exact-model matching.+_OPENAI_ALL_TURNS_FAMILIES = ("gpt-5.4", "gpt-5.5", "gpt-5.6", "gpt-6")+++def openai_reasoning_family(model: Any) -> Optional[str]:+ """``_OPENAI_ALL_TURNS_FAMILIES`` entry ``model`` belongs to (``gpt-6.1-sol`` -> ``gpt-6``), else None."""+ name = str(model or "").strip().lower()+ return next((f for f in _OPENAI_ALL_TURNS_FAMILIES if name == f or name.startswith((f + "-", f + "."))), None)+++def _is_openai_api_issuer(issuer_kind: Any) -> bool:+ from utils import base_url_hostname++ return isinstance(issuer_kind, str) and issuer_kind.startswith("other:") and (+ base_url_hostname(issuer_kind[len("other:"):]).lower() == "api.openai.com"+ )+++def _model_can_read_blob(issuer_kind: Optional[str], item_model: Any, current_model: Optional[str]) -> bool:+ """Exact model everywhere; same all_turns family on api.openai.com, which accepts sibling-variant blobs."""+ if current_model is None or item_model is None or item_model == current_model:+ return True+ family = openai_reasoning_family(current_model)+ return family is not None and family == openai_reasoning_family(item_model) and _is_openai_api_issuer(issuer_kind)+++# Responses hosts whose models render replayed reasoning from EARLIER user turns by default: xAI (LIVE: input+# grows by the turn-1 reasoning-token count; behavioural recall) and Meta ("Both modes preserve chain of thought+# across turns", dev.meta.ai/docs/protocols/responses). api.openai.com qualifies per model family (all_turns).+_PRIOR_TURN_REASONING_HOSTS = frozenset({"api.x.ai", "api.meta.ai"})+++def route_reads_prior_turn_reasoning(route: Any) -> bool:+ """True when earlier-turn ``codex_reasoning_items`` are continuity the model on ``route`` (agent or compressor:+ ``api_mode``/``provider``/``model``/``base_url``) actually reads, so compaction must keep them. The ChatGPT+ Codex backend stays False until its ``reasoning.context`` is probed."""+ from utils import base_url_hostname++ if getattr(route, "api_mode", None) != "codex_responses":+ return False+ host = base_url_hostname(str(getattr(route, "base_url", "") or "")).lower()+ if host == "api.openai.com":+ return openai_reasoning_family(_wire_model_identity(getattr(route, "model", None))) is not None+ return host in _PRIOR_TURN_REASONING_HOSTS or getattr(route, "provider", None) in {"xai", "xai-oauth"}+++def strip_unverified_reasoning_items(+ messages: Any, *, issuer_kind: Optional[str], issuer_model: Optional[str],+) -> int:+ """First ``invalid_encrypted_content`` rung: drop only reasoning items NOT stamped by exactly this issuer AND+ model (unstamped legacy blobs, sibling-variant blobs) from assistant rows, keeping the session's own+ continuity. Consumes its own precondition (a second call removes nothing), so recovery cannot loop.+ Rebinds the filtered list, never mutates a shared one; returns the number of items removed."""+ removed = 0+ for msg in messages if isinstance(messages, list) else []:+ items = msg.get("codex_reasoning_items") if isinstance(msg, dict) and msg.get("role") == "assistant" else None+ if not isinstance(items, list) or not items:+ continue+ kept = [+ i for i in items if isinstance(i, dict)+ and _canonical_issuer_kind(i.get("_issuer_kind")) == issuer_kind and i.get("_issuer_model") == issuer_model+ ]+ removed += len(items) - len(kept)+ if kept:+ msg["codex_reasoning_items"] = kept+ else:+ msg.pop("codex_reasoning_items")+ return removed+# Codex/Harmony tool-call serialization leaked into assistant text (no structured function_call)._TOOL_CALL_LEAK_PATTERN = re.compile(r"(?:^|[\s>|])to=functions\.[A-Za-z_][\w.]*", re.IGNORECASE)@@ -426,10 +500,9 @@ def _replay_reasoning_items(foreign_issuer = current_issuer_kind is not None and item_issuer is not None and item_issuer != current_issuer_kind# No model stamp → trust the endpoint stamp. Native compaction checkpoints and reasoning persisted# before model stamping carry none; dropping them would erase every existing session's context- # once. A wrong guess is caught by the invalid_encrypted_content 400 classifier.- foreign_model = (- current_issuer_model is not None and item_model is not None and item_model != current_issuer_model- )+ # once. A wrong guess is caught by the invalid_encrypted_content 400 classifier, whose first rung+ # strips exactly these unverified (unstamped / sibling-family) items.+ foreign_model = not _model_can_read_blob(current_issuer_kind, item_model, current_issuer_model)if foreign_issuer or foreign_model:if not _CROSS_ISSUER_WARN_EMITTED:logger.warning(diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 6e829eaf82d..4d6d349c114 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -479,12 +479,13 @@ def drop_shadowed_checkpoints(return rewritten-def _prune_stale_reasoning_replay(messages: list[dict[str, Any]]) -> int:+def _prune_stale_reasoning_replay(messages: list[dict[str, Any]], *, keep_prior_turns: bool = False) -> int:"""Strip stale ``codex_reasoning_items`` from assistant turns older than the active one.Boundary is the last USER message (a turn spans several assistant rows): the Responses API replays aturn's bridging reasoning items together, so cutting at the last ASSISTANT would strip mid-chain.Only the NEWEST ``type: "compaction"`` checkpoint survives (``drop_shadowed_checkpoints``): a shadowedone was still copied into the compacted transcript and every child session built from it (#102374).+ ``keep_prior_turns`` (``route_reads_prior_turn_reasoning``) applies only that checkpoint rule.Filter items, never pop the key on the carrier. In place; returns pruned message count."""# Active turn = everything after the last real user message; synthetic# continuation rows and tool results never mark a turn boundary.@@ -496,7 +497,7 @@ def _prune_stale_reasoning_replay(messages: list[dict[str, Any]]) -> int:pruned = set()for key in _STALE_REPLAY_PRUNE_KEYS:pruned.update(drop_shadowed_checkpoints(messages, key, before=last_user_idx))- for i in range(last_user_idx):+ for i in range(0 if keep_prior_turns else last_user_idx):msg = messages[i]if not isinstance(msg, dict) or msg.get("role") != "assistant":continue@@ -1291,8 +1292,7 @@ _REPLAY_BUDGET_KEYS = "reasoning", "reasoning_content", "codex_reasoning_items",_ALWAYS_REPLAYED_BUDGET_KEYS = "codex_reasoning_items", "codex_message_items"_NEWEST_TURN_ONLY_BUDGET_KEYS = "reasoning", "reasoning_content"-# Safe to strip from stale assistant turns: only the current turn's replay needs-# them, and the compaction boundary already invalidated the prompt-cache prefix.+# Stripped from stale turns only on routes that ignore earlier-turn reasoning; cache prefix already broken._STALE_REPLAY_PRUNE_KEYS = "codex_reasoning_items",@@ -5527,9 +5527,9 @@ Write only the summary body. Do not include any preamble or prefix."""# Invariant (#57491): no compacted message leaves compress() with a persistence marker._strip_persistence_markers(compressed)- # Prior-turn codex_reasoning_items are re-billed dead weight (#71058); the cache prefix is- # already broken here.- _pruned_replay = _prune_stale_reasoning_replay(compressed)+ # Prior-turn codex_reasoning_items: dead weight on current_turn routes (#71058), continuity elsewhere.+ from agent.codex_responses_adapter import route_reads_prior_turn_reasoning as _reads_prior+ _pruned_replay = _prune_stale_reasoning_replay(compressed, keep_prior_turns=_reads_prior(self))if _pruned_replay and not self.quiet_mode:logger.info("Pruned stale replay items from %d assistant message(s) during compaction", _pruned_replay)self._record_compression_effect(n_messages, compressed, pre_estimate, pruned_count, _pruned_replay)diff --git a/agent/transports/codex.py b/agent/transports/codex.pyindex 660e059887d..1d86a875770 100644--- a/agent/transports/codex.py+++ b/agent/transports/codex.py@@ -569,16 +569,29 @@ def _coerce_timeout(timeout: Any) -> Optional[float]:return None+def _sends_all_turns(model: Any, params: dict[str, Any]) -> bool:+ """``reasoning.context: "all_turns"`` goes only to api.openai.com models in the live-verified family+ table (gpt-5.4/5.5 default to ``current_turn`` and discard replayed earlier-turn blobs without it;+ o-series and gpt-5.1-5.3 400 on it). Never the ChatGPT Codex backend: acceptance there is unverified."""+ from agent.codex_responses_adapter import openai_reasoning_family++ return (+ params.get("is_codex_backend") is not True and _is_openai_api_origin(params.get("base_url"))+ and openai_reasoning_family(model) is not None+ )++def _reasoning_fields(model: str, params: dict[str, Any], *, effort: Any, enabled: bool, replay_encrypted_reasoning: bool,- is_xai_responses: bool, is_github_responses: bool,+ is_xai_responses: bool, is_github_responses: bool, all_turns: bool = False,) -> dict[str, Any]:"""``reasoning`` / ``include`` request fields for the endpoint family.xAI 400s on ``reasoning.effort`` outside its allowlist; GitHub Models takes averbatim ``github_reasoning_extra`` and never ``include``. A disabled ask resolved to``effort="none"`` is sent as ``{"effort": "none"}`` — the wire has no other way to switch- a reasoning model's default effort off (#75227).+ a reasoning model's default effort off (#75227). ``all_turns`` adds ``context: "all_turns"``+ so the model renders replayed reasoning from earlier user turns (``_sends_all_turns``)."""include = ["reasoning.encrypted_content"] if replay_encrypted_reasoning else []fields: dict[str, Any] = {}@@ -601,7 +614,7 @@ def _reasoning_fields(# See #46527.fields["reasoning"] = {**params["github_reasoning_extra"], "summary": "auto"}else:- fields["reasoning"] = {"effort": effort, "summary": "auto"}+ fields["reasoning"] = {"effort": effort, "summary": "auto", **({"context": "all_turns"} if all_turns else {})}fields["include"] = includeelif not is_github_responses and not is_xai_responses:fields["include"] = []@@ -621,6 +634,36 @@ class ResponsesApiTransport(ProviderTransport):_last_issuer_model: Optional[str] = None# ``{wire_alias: original}`` of the most recent build_kwargs. None = no request built (legacy map)._last_wire_aliases: Optional[dict[str, str]] = None+ # Wire models that 400'd on ``reasoning.context`` this session (the transport is cached per agent).+ _all_turns_rejected: frozenset = frozenset()+ _last_sent_all_turns: bool = False++ def reject_all_turns(self, error: Any) -> bool:+ """400 naming ``reasoning.context``/``all_turns`` on a request that carried the opt-in: omit it for that+ model for the rest of the session. False otherwise, so it buys at most one retry per model."""+ text = str(error).lower()+ if not self._last_sent_all_turns or getattr(error, "status_code", None) not in (400, None) or not (+ "reasoning.context" in text or "all_turns" in text+ ):+ return False+ self._all_turns_rejected = self._all_turns_rejected | {self._last_issuer_model}+ self._last_sent_all_turns = False+ logger.warning("reasoning.context rejected by %s; omitting it for this session", self._last_issuer_model)+ return True++ def drop_unverified_replay(self, *message_lists: Any) -> int:+ """First ``invalid_encrypted_content`` rung: drop the replayed blobs the failing request could not vouch+ for (not stamped by exactly its endpoint + model), keeping the session's own continuity. Returns the+ count removed from the first list; 0 means only the route's own blobs were sent."""+ from agent.codex_responses_adapter import strip_unverified_reasoning_items++ if self._last_issuer_kind is None or self._last_issuer_model is None:+ return 0+ removed = [+ strip_unverified_reasoning_items(msgs, issuer_kind=self._last_issuer_kind, issuer_model=self._last_issuer_model)+ for msgs in message_lists+ ]+ return removed[0] if removed else 0@propertydef api_mode(self) -> str:@@ -749,10 +792,14 @@ class ResponsesApiTransport(ProviderTransport):if cache_retention:kwargs.setdefault("prompt_cache_retention", cache_retention)+ self._last_sent_all_turns = (+ reasoning_enabled and _sends_all_turns(wire_model, params) and wire_model not in self._all_turns_rejected+ )kwargs.update(_reasoning_fields(model, params, effort=reasoning_effort, enabled=reasoning_enabled,replay_encrypted_reasoning=replay_encrypted_reasoning,is_xai_responses=is_xai_responses, is_github_responses=is_github_responses,+ all_turns=self._last_sent_all_turns,))# agent.text_verbosity -> top-level ``text.verbosity`` (#20203). Unset sends nothing;# xAI's /responses rejects unknown top-level fields, same as service_tier below.diff --git a/agent/turn_recovery.py b/agent/turn_recovery.pyindex a6470996920..2eb52f1069b 100644--- a/agent/turn_recovery.py+++ b/agent/turn_recovery.py@@ -472,7 +472,9 @@ def _recover_stale_codex_reasoning(agent: Any, _retry: TurnRetryState, messages: list[dict[str, Any]], api_messages: Any,) -> bool:"""Stale ``codex_reasoning_items`` blob rejected by the provider: strip cached items (mutates- persisted ``messages``) and retry once. The first rejection keeps replay on, since blobs the+ persisted ``messages``) and retry once. The first rung drops only the replayed blobs not stamped by+ exactly this endpoint+model (it consumes its own precondition, so it cannot loop); a repeat goes on+ to strip every item. The first full strip keeps replay on, since blobs theroute mints from now on are sealed with its current key; a repeat rejection means the routecannot round-trip its own blobs, so replay is disabled for the session."""if (@@ -488,6 +490,10 @@ def _recover_stale_codex_reasoning()):return False+ transport = agent._get_transport()+ if transport is not None and (removed := transport.drop_unverified_replay(messages, api_messages)):+ _vlines(agent, f"⚠️ Encrypted reasoning replay was rejected — dropped {removed} item(s) minted elsewhere, retrying...")+ return True_retry.invalid_encrypted_content_retry_attempted = Truekeep_replay = not getattr(agent, "_codex_reasoning_replay_rejected", False)agent._codex_reasoning_replay_rejected = True@@ -670,6 +676,11 @@ def _clamp_to_affordable_budget(agent: Any, api_error: Exception, classified: Anreturn True+def _reject_all_turns(agent: Any, api_error: Exception) -> bool:+ reject = getattr(agent._get_transport(), "reject_all_turns", None)+ return bool(reject(api_error)) if callable(reject) else False++def recover_after_classification(agent: Any, api_error: Exception, classified: Any, _retry: TurnRetryState, *,status_code: Optional[int], error_context: Any, messages: list[dict[str, Any]],@@ -677,7 +688,7 @@ def recover_after_classification() -> tuple[bool, bool]:"""One-shot recovery chain that runs AFTER ``classify_api_error`` and before thegeneric retry path. Order is load-bearing (each branch may ``return`` early):- welcome-tier repair → credit-limited 402 output-cap clamp → Nous paid-entitlement refresh →+ welcome-tier repair → credit-limited 402 output-cap clamp → ``reasoning.context`` opt-out → Nous paid-entitlement refresh →Codex stale-reasoning strip on 401 ``token_expired`` → credential-pool rotation → image shrink → multimodal-tool-content strip → corrupt-imagestrip → Anthropic OAuth 1M-beta disable → per-provider 401 credential refresh →format-recovery strips.@@ -685,10 +696,11 @@ def recover_after_classification(from agent.conversation_loop import _is_nous_inference_route# The credit-limited 402 clamp runs before pool rotation, which would bench a credential- # that still has credit.+ # that still has credit. A ``reasoning.context`` 400 is classified reasoning_mandatory, whose rung+ # would drop the whole reasoning config; omit only the all_turns opt-in, ahead of it.if _recover_welcome_tier(agent, classified, _retry) or _clamp_to_affordable_budget(agent, api_error, classified, _retry- ):+ ) or (agent.api_mode == "codex_responses" and _reject_all_turns(agent, api_error)):return True, False# 401 ``token_expired`` while the transcript still carries ``codex_reasoning_items`` is adiff --git a/tests/agent/test_cross_turn_reasoning_continuity.py b/tests/agent/test_cross_turn_reasoning_continuity.pynew file mode 100644index 00000000000..c3f469c5597--- /dev/null+++ b/tests/agent/test_cross_turn_reasoning_continuity.py@@ -0,0 +1,88 @@+"""Responses routes whose model renders earlier-turn reasoning keep it on the wire and through compaction.++Live basis (api.openai.com / api.x.ai, PR body): gpt-5.4/5.5 render replayed earlier-turn blobs only with+``reasoning.context: "all_turns"``; o-series / gpt-5-mini 400 on it; xAI renders them by default; sibling+variants of one OpenAI family read each other's blobs.+"""+import pytest++from agent.context_compressor import _prune_stale_reasoning_replay+from agent.transports.codex import ResponsesApiTransport++_OPENAI = "https://api.openai.com/v1"+++def _history(model, issuer=f"other:{_OPENAI}"):+ item = {"type": "reasoning", "encrypted_content": "BLOB-1", "id": "rs_1", "_issuer_kind": issuer, "_issuer_model": model}+ return [+ {"role": "user", "content": "turn 1"},+ {"role": "assistant", "content": "a1", "codex_reasoning_items": [item]},+ {"role": "user", "content": "turn 2"},+ ]+++def _build(model, base_url=_OPENAI, history_model=None, **params):+ transport = ResponsesApiTransport()+ kwargs = transport.build_kwargs(+ model=model, messages=_history(history_model or model), base_url=base_url,+ reasoning_config={"enabled": True, "effort": "low"}, **params,+ )+ return transport, kwargs++[email protected]("model, base_url, codex, expected", [+ ("gpt-5.5", _OPENAI, False, "all_turns"),+ ("gpt-6.1-sol", _OPENAI, False, "all_turns"),+ ("o4-mini", _OPENAI, False, None),+ ("gpt-5-mini", _OPENAI, False, None),+ ("gpt-5-nano", _OPENAI, False, None),+ ("o3", _OPENAI, False, None),+ ("gpt-5.5", "https://chatgpt.com/backend-api/codex", True, None),+ ("gpt-5.5", "https://relay.example.com/v1", False, None),+])+def test_reasoning_context_only_on_verified_openai_models(model, base_url, codex, expected):+ _, kwargs = _build(model, base_url, is_codex_backend=codex)+ assert kwargs["reasoning"].get("context") == expected+++def test_context_rejection_omits_it_once_and_keeps_effort():+ transport, _ = _build("gpt-5.5")+ err = type("E", (Exception,), {"status_code": 400})("param 'reasoning.context': 'all_turns' is not supported")+ assert transport.reject_all_turns(err) is True+ retry = transport.build_kwargs(model="gpt-5.5", messages=_history("gpt-5.5"), base_url=_OPENAI,+ reasoning_config={"enabled": True, "effort": "low"})+ assert "context" not in retry["reasoning"] and retry["reasoning"]["effort"] == "low"+ assert transport.reject_all_turns(err) is False # never loops+++def test_sibling_variant_blob_replays_on_openai_only():+ _, same_family = _build("gpt-5.6-terra", history_model="gpt-5.6-luna")+ _, cross_family = _build("gpt-5.6-terra", history_model="gpt-5.5")+ assert any(i.get("type") == "reasoning" for i in same_family["input"])+ assert not any(i.get("type") == "reasoning" for i in cross_family["input"])+++def test_compaction_keeps_prior_turn_reasoning_only_when_the_route_reads_it():+ from types import SimpleNamespace as Route+ from agent.codex_responses_adapter import route_reads_prior_turn_reasoning as reads++ def route(provider, model, base_url):+ return Route(api_mode="codex_responses", provider=provider, model=model, base_url=base_url)+ assert reads(route("xai", "grok-4.3", "https://api.x.ai/v1"))+ assert reads(route("openai-api", "gpt-5.5", _OPENAI))+ assert not reads(route("openai-api", "o4-mini", _OPENAI))+ assert not reads(route("openai-codex", "gpt-5.5", "https://chatgpt.com/backend-api/codex"))+ kept, pruned = _history("grok-4.3"), _history("o4-mini")+ assert _prune_stale_reasoning_replay(kept, keep_prior_turns=True) == 0+ assert kept[1]["codex_reasoning_items"][0]["encrypted_content"] == "BLOB-1"+ assert _prune_stale_reasoning_replay(pruned) == 1 and "codex_reasoning_items" not in pruned[1]+++def test_first_invalid_encrypted_rejection_drops_only_unverified_items():+ transport, _ = _build("gpt-5.5")+ own = {"type": "reasoning", "encrypted_content": "OWN", "_issuer_kind": f"other:{_OPENAI}", "_issuer_model": "gpt-5.5"}+ legacy = {"type": "reasoning", "encrypted_content": "LEGACY"}+ messages = [{"role": "assistant", "content": "x", "codex_reasoning_items": [own, legacy]}]+ assert transport.drop_unverified_replay(messages) == 1+ assert messages[0]["codex_reasoning_items"] == [own]+ assert transport.drop_unverified_replay(messages) == 0 # escalation path takes over next timediff --git a/tests/agent/transports/test_codex_transport.py b/tests/agent/transports/test_codex_transport.pyindex 98be7f15113..95fc50046db 100644--- a/tests/agent/transports/test_codex_transport.py+++ b/tests/agent/transports/test_codex_transport.py@@ -1990,7 +1990,7 @@ class TestOpenAIReasoningWireProjection:def test_explicit_none_is_sent_and_unset_keeps_the_default(self, transport):assert self._reasoning(transport, "gpt-5.6-sol", {"enabled": False}) == {"effort": "none"}- assert self._reasoning(transport, "gpt-5.6-sol", None) == {"effort": "medium", "summary": "auto"}+ assert self._reasoning(transport, "gpt-5.6-sol", None) == {"effort": "medium", "summary": "auto", "context": "all_turns"}# Astra's vocabulary has no ``none``: nothing to send, never an escalated level.assert self._reasoning(transport, "gpt-6-astra", {"enabled": False}) is Nonediff --git a/tests/fixtures/provider_wire_snapshot.json b/tests/fixtures/provider_wire_snapshot.jsonindex aefb6b00734..a5262861dfd 100644--- a/tests/fixtures/provider_wire_snapshot.json+++ b/tests/fixtures/provider_wire_snapshot.json@@ -9086,6 +9086,7 @@"parallel_tool_calls": true,"prompt_cache_key": "pck_f6d11aab44ec88459ba6fe2e","reasoning": {+ "context": "all_turns","effort": "high","summary": "auto"},@@ -9200,6 +9201,7 @@"parallel_tool_calls": true,"prompt_cache_key": "pck_f6d11aab44ec88459ba6fe2e","reasoning": {+ "context": "all_turns","effort": "medium","summary": "auto"},