Skip to content

The agent that grows with you

refactor(agent/codex_responses_adapter): comprehension-ize _responses_tools, fold salvage/synth guards, compact docstrings

Tekniumfbe69d610b66
diff --git a/agent/codex_responses_adapter.py b/agent/codex_responses_adapter.py
index 7559841d3a1..004345cc4c6 100644
--- a/agent/codex_responses_adapter.py
+++ b/agent/codex_responses_adapter.py
@@ -22,9 +22,8 @@ def _classify_responses_issuer(
*, is_xai_responses: bool = False, is_github_responses: bool = False, is_codex_backend: bool = False,
base_url: Optional[str] = None,
) -> str:
- """Stable identifier for the endpoint that mints ``reasoning.encrypted_content``. Blobs
- are sealed to their issuer (HTTP 400 ``invalid_encrypted_content`` across endpoints), so
- stamping lets replay drop foreign blobs after a mid-conversation model switch."""
+ """Stable identifier for the endpoint that mints ``reasoning.encrypted_content``. Blobs are sealed to their
+ issuer (HTTP 400 ``invalid_encrypted_content``), so stamping lets replay drop foreign blobs after a model switch."""
for flag, kind in ((is_xai_responses, "xai_responses"), (is_github_responses, "github_responses"), (is_codex_backend, "codex_backend")):
if flag:
return kind
@@ -122,14 +121,12 @@ def _neutralize_harmony_tokens(text: str) -> str:
# check, so match on the visible text and rewrite the original spans.
original_positions = [i for i, char in enumerate(text) if unicodedata.category(char) != "Cf"]
visible_text = "".join(text[i] for i in original_positions)
- result: List[str] = []
- cursor = 0
+ result, cursor = [], 0
for match in _HARMONY_CONTROL_TOKEN_RE.finditer(visible_text):
start, end = original_positions[match.start()], original_positions[match.end() - 1] + 1
result += [text[cursor:start], f"<{_FULLWIDTH_PIPE}{match.group(1)}{_FULLWIDTH_PIPE}>"]
cursor = end
- result.append(text[cursor:])
- return "".join(result)
+ return "".join(result) + text[cursor:]
def _neutralize_harmony_structure(value: Any) -> Any:
@@ -196,9 +193,8 @@ def _chat_content_to_responses_parts(content: Any, *, role: str = "user") -> Lis
def _summarize_user_message_for_log(content: Any, *, sep: str = " ") -> str:
- """Flatten message content to plain text: text parts joined with ``sep`` (``" "`` for
- logs; ``"\\n"`` for memory providers feeding regexes), images → ``[N image(s)]``
- marker, ``""`` for None/empty, ``str(content)`` for other scalars."""
+ """Flatten message content to plain text: text parts joined with ``sep`` (``" "`` for logs; ``"\\n"`` for memory
+ providers feeding regexes), images → ``[N image(s)]`` marker, ``""`` for None, ``str(content)`` for other scalars."""
if not isinstance(content, list):
try:
return _str_or_empty(content)
@@ -218,9 +214,8 @@ _deterministic_call_id = deterministic_call_id
def _clamp_responses_call_id(call_id: str) -> str:
- """Keep ``call_id`` within the API's 64-char cap (the codex app-server namespaces MCP
- call ids past it). The surrogate is a pure function of the original so a
- ``function_call`` and its ``function_call_output`` map to the same value."""
+ """Keep ``call_id`` within the API's 64-char cap (the codex app-server namespaces MCP call ids past it). The
+ surrogate is a pure function of the original so a ``function_call`` and its ``function_call_output`` agree."""
if len(call_id) <= _MAX_RESPONSES_ITEM_ID_LENGTH:
return call_id
return f"call_{hashlib.sha256(call_id.encode('utf-8', errors='replace')).hexdigest()[:32]}"
@@ -292,15 +287,14 @@ def _derive_responses_function_call_id(call_id: str, response_item_id: Optional[
def _responses_tools(tools: Optional[List[Dict[str, Any]]] = None) -> Optional[List[Dict[str, Any]]]:
"""Convert chat-completions tool schemas to Responses function-tool schemas."""
- converted: List[Dict[str, Any]] = []
- for item in tools or []:
- fn = item.get("function", {}) if isinstance(item, dict) else {}
- name = fn.get("name")
- if _nonblank(name):
- converted.append({
- "type": "function", "name": name, "description": fn.get("description", ""), "strict": False,
- "parameters": fn.get("parameters", {"type": "object", "properties": {}}),
- })
+ fns = [item.get("function", {}) if isinstance(item, dict) else {} for item in tools or []]
+ converted = [
+ {
+ "type": "function", "name": fn["name"], "description": fn.get("description", ""), "strict": False,
+ "parameters": fn.get("parameters", {"type": "object", "properties": {}}),
+ }
+ for fn in fns if _nonblank(fn.get("name"))
+ ]
return converted or None
@@ -326,9 +320,8 @@ def _message_item(
def _assistant_message_item(raw: Dict[str, Any], content: List[Dict[str, Any]], *, is_github_responses: bool) -> Dict[str, Any]:
- """Replayable assistant ``message`` item from a stored one. ``id`` is kept only when
- short enough and never for GitHub Copilot (ids bind to a backend connection; stale →
- 401); ``phase`` is preserved per OpenAI's cache guidance."""
+ """Replayable assistant ``message`` item from a stored one. ``id`` is kept only when short enough and never for
+ GitHub Copilot (ids bind to a backend connection; stale → 401); ``phase`` is preserved per OpenAI's cache guidance."""
item_id, phase = raw.get("id"), raw.get("phase")
keep_id = not is_github_responses and _nonblank(item_id) and len(item_id.strip()) <= _MAX_RESPONSES_ITEM_ID_LENGTH
return _message_item(
@@ -395,9 +388,8 @@ def _replay_tool_call_items(msg: Dict[str, Any], *, start_index: int) -> List[Di
fn_name, arguments = fn.get("name"), fn.get("arguments", "{}")
if not _nonblank(fn_name):
continue
- call_id = _resolve_call_id(
- tc.get("call_id"), tc.get("id"), fn_name, str(arguments), start_index + len(replayed), canonicalize_fc=True,
- )
+ index = start_index + len(replayed)
+ call_id = _resolve_call_id(tc.get("call_id"), tc.get("id"), fn_name, str(arguments), index, canonicalize_fc=True)
replayed.append({
"type": "function_call", "call_id": _clamp_responses_call_id(call_id),
"name": _sanitize_replayed_fn_name(fn_name), "arguments": _coerce_arguments(arguments),
@@ -419,10 +411,8 @@ def _tool_output_items(msg: Dict[str, Any]) -> List[Dict[str, Any]]:
return []
# ``output`` may be a string or an ``input_text``/``input_image`` array.
tool_content = msg.get("content")
- output_value: Any = (
- (_chat_content_to_responses_parts(tool_content, role="user") or "")
- if isinstance(tool_content, list) else str(tool_content or "")
- )
+ is_parts = isinstance(tool_content, list)
+ output_value: Any = (_chat_content_to_responses_parts(tool_content) or "") if is_parts else str(tool_content or "")
return [{"type": "function_call_output", "call_id": _clamp_responses_call_id(call_id), "output": output_value}]
@@ -438,10 +428,10 @@ def _chat_messages_to_responses_input(
``AIAgent._disable_codex_reasoning_replay`` after an ``invalid_encrypted_content`` 400.
``is_github_responses``: drops ``id`` from replayed message items (Copilot 401s on stale ids).
``current_issuer_kind``: cross-issuer guard; foreign-stamped items drop, legacy items replay.
- ``native_compaction_eligible``: THIS request carries ``context_management``; gates both replaying
- ``compaction`` checkpoints and ``prune_pre_checkpoint_items``. Checkpoints persist across model
- swaps / compression flips / resume, so without the gate one checkpoint would delete pre-checkpoint
- history on a model that cannot decrypt it. Dropping it is lossless: local history is never truncated."""
+ ``native_compaction_eligible``: THIS request carries ``context_management``; gates both replaying ``compaction``
+ checkpoints and ``prune_pre_checkpoint_items``. Checkpoints persist across model swaps / compression flips / resume,
+ so without the gate one checkpoint would erase pre-checkpoint history on a model that cannot decrypt it (lossless:
+ local history is never truncated)."""
items: List[Dict[str, Any]] = []
# Parallel to ``items``: source chat message per item. Pruning reads a summary
# carrier's provenance from the source; the converted item may be a lossy shape.
@@ -519,9 +509,8 @@ def classify_responses_route(agent: Any) -> ResponsesRouteFlags:
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 (the full transcript
- overstates a natively compacted session and fires local compression needlessly).
- None when native compaction is not proven eligible or conversion fails."""
+ """Estimate tokens for the checkpoint-pruned Responses payload (the full transcript overstates a natively compacted
+ session and fires local compression needlessly). None when native compaction is not proven eligible or conversion fails."""
if getattr(agent, "api_mode", None) != "codex_responses" or not isinstance(messages, list):
return None
route = classify_responses_route(agent)._asdict()
@@ -544,11 +533,9 @@ def estimate_native_responses_preflight_tokens(
# --- Input preflight / validation --------------------------------------------
-class _PreflightCtx(NamedTuple):
- sanitize_text: Callable[[str], str]
- sanitize_harmony_tokens: bool
- is_github_responses: bool
- seen_ids: set
+_PreflightCtx = NamedTuple("_PreflightCtx", [
+ ("sanitize_text", Callable[[str], str]), ("sanitize_harmony_tokens", bool), ("is_github_responses", bool), ("seen_ids", set),
+])
def _preflight_function_call(item: Dict[str, Any], idx: int, ctx: _PreflightCtx) -> Dict[str, Any]:
@@ -765,13 +752,12 @@ def _preflight_codex_api_kwargs(
value = api_kwargs.get(key)
if accept(value):
normalized[key] = coerce(value) if coerce else value
- extra_headers = _optional_dict(api_kwargs, "extra_headers")
- if extra_headers is not None:
- if not all(_nonblank(key) for key in extra_headers):
- raise ValueError("Codex Responses request 'extra_headers' keys must be non-empty strings.")
- normalized_headers = {key.strip(): str(value) for key, value in extra_headers.items() if value is not None}
- if normalized_headers:
- normalized["extra_headers"] = normalized_headers
+ extra_headers = _optional_dict(api_kwargs, "extra_headers") or {}
+ if not all(_nonblank(key) for key in extra_headers):
+ raise ValueError("Codex Responses request 'extra_headers' keys must be non-empty strings.")
+ normalized_headers = {key.strip(): str(value) for key, value in extra_headers.items() if value is not None}
+ if normalized_headers:
+ normalized["extra_headers"] = normalized_headers
# extra_body is verbatim: xAI carries ``prompt_cache_key`` as a body-level
# field, and the SDK serializes extra_body without per-field checks.
extra_body = _optional_dict(api_kwargs, "extra_body")
@@ -841,9 +827,7 @@ def _response_tool_call(item: Any, item_type: str, index: int) -> SimpleNamespac
if not isinstance(arguments, str):
arguments = json.dumps(arguments, ensure_ascii=False)
raw_item_id = getattr(item, "id", None)
- call_id = _resolve_call_id(
- getattr(item, "call_id", None), raw_item_id, fn_name, arguments, index, canonicalize_fc=False,
- )
+ call_id = _resolve_call_id(getattr(item, "call_id", None), raw_item_id, fn_name, arguments, index, canonicalize_fc=False)
fc_id = _derive_responses_function_call_id(call_id, raw_item_id if isinstance(raw_item_id, str) else None)
return SimpleNamespace(
id=call_id, call_id=call_id, response_item_id=fc_id, type="function",
@@ -870,9 +854,8 @@ def _capture_encrypted_item(item: Any, item_type: str, issuer_kind: Optional[str
raw_item["id"] = item_id
summary = getattr(item, "summary", None)
if isinstance(summary, list):
- raw_item["summary"] = [
- {"type": "summary_text", "text": text} for text in (getattr(part, "text", None) for part in summary) if isinstance(text, str)
- ]
+ texts = (getattr(part, "text", None) for part in summary)
+ raw_item["summary"] = [{"type": "summary_text", "text": text} for text in texts if isinstance(text, str)]
return raw_item
@@ -880,11 +863,8 @@ class _OutputScan:
"""Accumulated view of one Responses ``output`` list (phase 1 of normalization)."""
def __init__(self, response_status: Optional[str]) -> None:
- self.content_parts: List[str] = []
- self.reasoning_parts: List[str] = []
- self.reasoning_items_raw: List[Dict[str, Any]] = []
- self.message_items_raw: List[Dict[str, Any]] = []
- self.tool_calls: List[Any] = []
+ self.content_parts, self.reasoning_parts, self.tool_calls = [], [], []
+ self.reasoning_items_raw, self.message_items_raw = [], []
self.has_incomplete_items = response_status in _INCOMPLETE_STATUSES
self.saw_streaming_or_item_incomplete = response_status in {"queued", "in_progress"}
self.saw_commentary_phase = self.saw_final_answer_phase = self.saw_reasoning_item = False
@@ -944,12 +924,11 @@ def _normalize_codex_response(response: Any, *, issuer_kind: Optional[str] = Non
if not isinstance(output, list) or not output:
# Codex can deliver the whole answer via stream events with an empty output.
out_text = getattr(response, "output_text", None)
- if isinstance(out_text, str) and out_text.strip():
- logger.debug(
- "Codex response has empty output but output_text is present (%d chars); synthesizing output item.",
- len(out_text.strip()),
- )
- content: List[Any] = [SimpleNamespace(type="output_text", text=out_text.strip())]
+ out_text = out_text.strip() if isinstance(out_text, str) else ""
+ if out_text:
+ msg = "Codex response has empty output but output_text is present (%d chars); synthesizing output item."
+ logger.debug(msg, len(out_text))
+ content: List[Any] = [SimpleNamespace(type="output_text", text=out_text)]
elif response_incomplete_content_filter:
# Provider safety block, not a partial answer: finish content_filter, not incomplete.
content = []
@@ -967,9 +946,8 @@ def _normalize_codex_response(response: Any, *, issuer_kind: Optional[str] = Non
if not final_text and (scan.saw_final_answer_phase or not scan.saw_commentary_phase):
out_text = getattr(response, "output_text", "")
final_text = out_text.strip() if isinstance(out_text, str) else final_text
- # Tool-call leak recovery: gpt-5.x sometimes emits the intended ``function_call`` as
- # plain Harmony text (``to=functions.foo {json}``). Treat as incomplete so the
- # continuation re-elicits a real call; clear the text so the garbage is not surfaced.
+ # Tool-call leak recovery: gpt-5.x sometimes emits the intended ``function_call`` as plain Harmony text
+ # (``to=functions.foo {json}``). Treat as incomplete so the continuation re-elicits a real call; clear the garbage.
leaked_tool_call_text = bool(final_text and not tool_calls and _TOOL_CALL_LEAK_PATTERN.search(final_text))
if leaked_tool_call_text:
logger.warning(
@@ -978,31 +956,28 @@ def _normalize_codex_response(response: Any, *, issuer_kind: Optional[str] = Non
"Leaked snippet: %r", final_text[:300],
)
final_text = ""
- # xAI grok-4.x sometimes puts the final answer inside the reasoning item after a
- # ``<response>`` delimiter; without salvage the reasoning-only rule marks the turn
- # incomplete and every continuation is byte-identical. Promote the tail to content.
+ # xAI grok-4.x sometimes puts the final answer inside the reasoning item after a ``<response>`` delimiter; without
+ # salvage the reasoning-only rule marks the turn incomplete and every continuation is byte-identical. Promote the tail.
if issuer_kind == "xai_responses" and not final_text and not tool_calls and reasoning_parts:
joined_reasoning = "\n\n".join(reasoning_parts)
marker = joined_reasoning.rfind("<response>")
- if marker != -1:
- salvaged = joined_reasoning[marker + len("<response>"):].split("</response>", 1)[0].strip()
- if salvaged:
- logger.warning(
- "xAI response delivered its final answer inside the reasoning channel "
- "(<response> delimiter); promoting %d chars to assistant content.", len(salvaged),
- )
- final_text = salvaged
- reasoning_prefix = joined_reasoning[:marker].strip()
- reasoning_parts = [reasoning_prefix] if reasoning_prefix else []
+ salvaged = joined_reasoning[marker + len("<response>"):].split("</response>", 1)[0].strip() if marker != -1 else ""
+ if salvaged:
+ logger.warning(
+ "xAI response delivered its final answer inside the reasoning channel "
+ "(<response> delimiter); promoting %d chars to assistant content.", len(salvaged),
+ )
+ final_text = salvaged
+ reasoning_prefix = joined_reasoning[:marker].strip()
+ reasoning_parts = [reasoning_prefix] if reasoning_prefix else []
assistant_message = SimpleNamespace(
content=final_text, tool_calls=tool_calls,
reasoning="\n\n".join(reasoning_parts).strip() if reasoning_parts else None,
reasoning_content=None, reasoning_details=None,
codex_reasoning_items=scan.reasoning_items_raw or None, codex_message_items=scan.message_items_raw or None,
)
- # Reasoning-only: for Codex/xAI/GitHub, status=completed means "still thinking" →
- # incomplete so the continuation retries. Other backends trust response.status —
- # forcing incomplete there stalls for minutes on a legitimately final state.
+ # Reasoning-only: for Codex/xAI/GitHub, status=completed means "still thinking" → incomplete so the continuation
+ # retries. Other backends trust response.status — forcing incomplete there stalls for minutes on a final state.
reasoning_only = (scan.reasoning_items_raw or reasoning_parts or scan.saw_reasoning_item) and not final_text
trusted_final = (
response_status == "completed" and issuer_kind not in ("codex_backend", "xai_responses", "github_responses")