Skip to content

The agent that grows with you

fix(agent): count native Responses preflight against pruned wire

686f6c61e6b4f3750b45
diff --git a/agent/codex_responses_adapter.py b/agent/codex_responses_adapter.py
index 6541001e58b..42c4b693879 100644
--- a/agent/codex_responses_adapter.py
+++ b/agent/codex_responses_adapter.py
@@ -823,6 +823,105 @@ def _chat_messages_to_responses_input(
return prune_pre_checkpoint_items(items, item_sources=item_sources)
+def _agent_is_codex_backend(agent: Any) -> bool:
+ if getattr(agent, "provider", None) == "openai-codex":
+ return True
+ hostname = str(getattr(agent, "_base_url_hostname", "") or "").lower()
+ lower = str(getattr(agent, "_base_url_lower", "") or "")
+ if not lower:
+ lower = str(getattr(agent, "base_url", "") or "").lower()
+ if hostname == "chatgpt.com" and "/backend-api/codex" in lower:
+ return True
+ return "chatgpt.com" in lower and "/backend-api/codex" in lower
+
+
+def _agent_is_github_responses(agent: Any) -> bool:
+ hostname = str(getattr(agent, "_base_url_hostname", "") or "").lower()
+ lower = str(getattr(agent, "_base_url_lower", "") or getattr(agent, "base_url", "") or "").lower()
+ return hostname in {"models.github.ai", "githubcopilot.com"} or (
+ "models.github.ai" in lower or "githubcopilot.com" in lower
+ )
+
+
+def _agent_is_xai_responses(agent: Any) -> bool:
+ provider = getattr(agent, "provider", None)
+ hostname = str(getattr(agent, "_base_url_hostname", "") or "").lower()
+ return provider in {"xai", "xai-oauth"} or hostname == "api.x.ai"
+
+
+def estimate_native_responses_preflight_tokens(
+ agent: Any,
+ messages: List[Dict[str, Any]],
+ *,
+ system_prompt: str = "",
+ tools: Optional[List[Dict[str, Any]]] = None,
+) -> Optional[int]:
+ """Estimate tokens for the checkpoint-pruned Responses payload.
+
+ Automatic preflight previously counted the full durable transcript.
+ On a natively compacted Codex session that overstates the wire by
+ several times and fires local compression against history the main
+ request will never send (#96155).
+
+ Returns None when native compaction is not proven eligible for this
+ request, or when conversion fails — the caller must then use the
+ generic durable-transcript estimate (conservative).
+ """
+ if getattr(agent, "api_mode", None) != "codex_responses":
+ return None
+ if not isinstance(messages, list):
+ return None
+
+ is_codex_backend = _agent_is_codex_backend(agent)
+ is_xai_responses = _agent_is_xai_responses(agent)
+ is_github_responses = _agent_is_github_responses(agent)
+
+ from agent.native_compaction import native_compaction_context_management
+
+ context_management = native_compaction_context_management(
+ agent,
+ is_codex_backend=is_codex_backend,
+ is_xai_responses=is_xai_responses,
+ is_github_responses=is_github_responses,
+ )
+ if not context_management:
+ return None
+
+ try:
+ items = _chat_messages_to_responses_input(
+ messages,
+ is_xai_responses=is_xai_responses,
+ is_github_responses=is_github_responses,
+ replay_encrypted_reasoning=bool(
+ getattr(agent, "_codex_reasoning_replay_enabled", True)
+ ),
+ current_issuer_kind=_classify_responses_issuer(
+ is_xai_responses=is_xai_responses,
+ is_github_responses=is_github_responses,
+ is_codex_backend=is_codex_backend,
+ base_url=getattr(agent, "base_url", None),
+ ),
+ native_compaction_eligible=True,
+ )
+ except Exception:
+ logger.debug(
+ "native Responses preflight conversion failed; falling back to generic estimate",
+ exc_info=True,
+ )
+ return None
+
+ if not isinstance(items, list):
+ return None
+
+ from agent.model_metadata import estimate_request_tokens_rough
+
+ return estimate_request_tokens_rough(
+ items,
+ system_prompt=system_prompt or "",
+ tools=tools,
+ )
+
+
# ---------------------------------------------------------------------------
# Input preflight / validation
# ---------------------------------------------------------------------------
diff --git a/agent/turn_context.py b/agent/turn_context.py
index 5982e3846fd..1a7a72c0f0b 100644
--- a/agent/turn_context.py
+++ b/agent/turn_context.py
@@ -51,6 +51,45 @@ from agent.model_metadata import (
logger = logging.getLogger(__name__)
+def _preflight_request_tokens(
+ agent: Any,
+ messages: List[Dict[str, Any]],
+ system_prompt: str,
+) -> int:
+ """Token estimate for automatic preflight compression.
+
+ When the upcoming request is eligible for native Responses compaction,
+ count the checkpoint-pruned wire payload rather than the full durable
+ transcript. Auxiliary compression still uses the generic estimator
+ (``native_compaction_eligible=False``).
+ """
+ tools = getattr(agent, "tools", None) or None
+ try:
+ from agent.codex_responses_adapter import (
+ estimate_native_responses_preflight_tokens,
+ )
+
+ native = estimate_native_responses_preflight_tokens(
+ agent,
+ messages,
+ system_prompt=system_prompt or "",
+ tools=tools,
+ )
+ if isinstance(native, int) and not isinstance(native, bool) and native >= 0:
+ return native
+ except Exception:
+ logger.debug(
+ "native Responses preflight estimate unavailable; "
+ "using generic transcript estimate",
+ exc_info=True,
+ )
+ return estimate_request_tokens_rough(
+ messages,
+ system_prompt=system_prompt or "",
+ tools=tools,
+ )
+
+
def compose_user_api_content(
content: Any,
ext_prefetch_cache: str,
@@ -915,10 +954,10 @@ def build_turn_context(
agent.context_compressor.threshold_tokens,
)
):
- _preflight_tokens = estimate_request_tokens_rough(
+ _preflight_tokens = _preflight_request_tokens(
+ agent,
messages,
- system_prompt=active_system_prompt or "",
- tools=agent.tools or None,
+ active_system_prompt or "",
)
_compressor = agent.context_compressor
# getattr guard: minimal compressor doubles (SimpleNamespace in the
@@ -1079,10 +1118,10 @@ def build_turn_context(
# lower token count — e.g. summarising tool outputs) is
# recognised as progress instead of being misread as
# "Cannot compress further". Fixes #39548.
- _preflight_tokens = estimate_request_tokens_rough(
+ _preflight_tokens = _preflight_request_tokens(
+ agent,
messages,
- system_prompt=active_system_prompt or "",
- tools=agent.tools or None,
+ active_system_prompt or "",
)
if not _compression_made_progress(
_orig_len, len(messages), _orig_tokens, _preflight_tokens
diff --git a/tests/agent/test_native_preflight_estimate.py b/tests/agent/test_native_preflight_estimate.py
new file mode 100644
index 00000000000..b26b8ec94b7
--- /dev/null
+++ b/tests/agent/test_native_preflight_estimate.py
@@ -0,0 +1,100 @@
+"""Native Responses preflight must count the checkpoint-pruned wire (#96155)."""
+
+from types import SimpleNamespace
+
+from agent.codex_responses_adapter import estimate_native_responses_preflight_tokens
+from agent.model_metadata import estimate_request_tokens_rough
+from agent.turn_context import _preflight_request_tokens
+
+
+def _codex_agent(**over):
+ agent = SimpleNamespace(
+ api_mode="codex_responses",
+ provider="openai-codex",
+ model="gpt-5.6",
+ base_url="https://chatgpt.com/backend-api/codex",
+ _base_url_hostname="chatgpt.com",
+ _base_url_lower="https://chatgpt.com/backend-api/codex",
+ codex_responses_native_compaction=True,
+ compression_enabled=True,
+ _codex_reasoning_replay_enabled=True,
+ context_compressor=SimpleNamespace(threshold_tokens=765_000),
+ tools=None,
+ )
+ for key, value in over.items():
+ setattr(agent, key, value)
+ return agent
+
+
+def _history_with_checkpoint():
+ # Pre-checkpoint assistant/tool rows are dropped from the wire; user
+ # asks are retained. A durable estimate that counts those dropped rows
+ # is what falsely tripped local compression in #96155.
+ pre = []
+ for i in range(30):
+ pre.append({"role": "user", "content": f"ask {i}"})
+ pre.append({"role": "assistant", "content": "working " + ("tool output " * 400)})
+ pre.append(
+ {
+ "role": "tool",
+ "content": "result " + ("payload " * 400),
+ "tool_call_id": f"call-{i}",
+ }
+ )
+ checkpoint_turn = {
+ "role": "assistant",
+ "content": "checkpointed turn",
+ "codex_reasoning_items": [
+ {
+ "type": "compaction",
+ "encrypted_content": "blob",
+ "_issuer_kind": "codex_backend",
+ }
+ ],
+ }
+ tail = [{"role": "user", "content": "follow-up after checkpoint"}]
+ return pre + [checkpoint_turn] + tail
+
+
+def test_returns_none_when_api_mode_is_not_codex_responses():
+ agent = _codex_agent(api_mode="chat_completions")
+ assert estimate_native_responses_preflight_tokens(agent, _history_with_checkpoint()) is None
+
+
+def test_returns_none_when_native_compaction_is_disabled():
+ agent = _codex_agent(codex_responses_native_compaction=False)
+ assert estimate_native_responses_preflight_tokens(agent, _history_with_checkpoint()) is None
+
+
+def test_returns_none_when_model_is_outside_gpt56_family():
+ agent = _codex_agent(model="gpt-5.2")
+ assert estimate_native_responses_preflight_tokens(agent, _history_with_checkpoint()) is None
+
+
+def test_pruned_estimate_is_far_below_durable_transcript():
+ agent = _codex_agent()
+ messages = _history_with_checkpoint()
+ generic = estimate_request_tokens_rough(messages)
+ native = estimate_native_responses_preflight_tokens(agent, messages)
+
+ assert native is not None
+ assert generic > native * 2
+ assert native < 8_000
+
+
+def test_preflight_wrapper_uses_pruned_estimate_when_eligible():
+ agent = _codex_agent()
+ messages = _history_with_checkpoint()
+ native = estimate_native_responses_preflight_tokens(agent, messages)
+ wrapped = _preflight_request_tokens(agent, messages, "")
+
+ assert native is not None
+ assert wrapped == native
+
+
+def test_preflight_wrapper_falls_back_to_generic_when_ineligible():
+ agent = _codex_agent(api_mode="chat_completions")
+ messages = _history_with_checkpoint()
+ generic = estimate_request_tokens_rough(messages)
+
+ assert _preflight_request_tokens(agent, messages, "") == generic