refactor(agent/codex_responses_adapter): extract _OutputScan from _normalize_codex_response, share part-type/text-type/call-id helpers; compact docs (-49 LOC)

This commit is contained in:
Teknium
2026-09-02 18:22:57 -07:00
parent 3b17b4147d
commit ac268d2d7a
+213 -262
View File
@@ -28,8 +28,8 @@ def _classify_responses_issuer(
"""Stable identifier for the endpoint that mints ``reasoning.encrypted_content``.
Blobs are sealed to their issuer (replaying across endpoints yields HTTP 400
``invalid_encrypted_content``); stamping items with the issuer lets replay
drop foreign blobs after a mid-conversation model switch.
``invalid_encrypted_content``); stamping items lets replay drop foreign
blobs after a mid-conversation model switch.
"""
if is_xai_responses:
return "xai_responses"
@@ -40,13 +40,11 @@ def _classify_responses_issuer(
return f"other:{base_url}" if base_url else "other"
# Per-process throttle for the cross-issuer skip warning (long histories can
# carry many stale-issuer reasoning blocks).
# Per-process throttle for the cross-issuer skip warning.
_CROSS_ISSUER_WARN_EMITTED = False
# Codex/Harmony tool-call serialization leaked into assistant text when the
# model fails to emit a structured ``function_call`` (``to=functions.<name>``,
# optionally prefixed by ``assistant`` or a Harmony channel marker).
# model fails to emit a structured ``function_call``.
_TOOL_CALL_LEAK_PATTERN = re.compile(r"(?:^|[\s>|])to=functions\.[A-Za-z_][\w.]*", re.IGNORECASE)
# The Codex backend rejects requests containing these literal Harmony wire
@@ -57,33 +55,29 @@ _FULLWIDTH_PIPE = "\uff5c"
_TEXT_PART_TYPES = {"text", "input_text", "output_text"}
_IMAGE_PART_TYPES = {"image_url", "input_image"}
_OUTPUT_TEXT_TYPES = {"output_text", "text"}
_ASSISTANT_IMAGE_PLACEHOLDER = "[Assistant image omitted during replay]"
_INCOMPLETE_STATUSES = {"queued", "in_progress", "incomplete"}
_RESPONSE_MESSAGE_STATUSES = {"completed", "incomplete", "in_progress"}
# input[].id longer than this is a non-retryable 400 ("string too long").
# Codex-issued assistant message ids can run 400+ chars; Hermes-minted
# ``msg_...`` ids stay under the cap and are kept for prefix-cache hits.
# Function names share the same cap (same non-retryable 400).
# input[].id / function names longer than this are a non-retryable 400
# ("string too long"). Codex-issued assistant message ids can run 400+ chars;
# Hermes-minted ``msg_...`` ids stay under the cap and are kept for cache hits.
_MAX_RESPONSES_ITEM_ID_LENGTH = 64
_VALID_RESPONSES_FN_NAME_RE = re.compile(r"[a-zA-Z0-9_-]{1,64}")
# Provider-executed built-in tools: declared on ``tools`` by ``type`` alone
# (no name/parameters) and run server-side, reporting via the ``*_call``
# output items below. Hermes injects xAI's ``web_search`` in
# agent/transports/codex.py; the rest are listed so preflight passes them
# through instead of rejecting them as "unsupported type".
# Provider-executed built-in tools: declared on ``tools`` by ``type`` alone and
# run server-side, reporting via the ``*_call`` output items below. Preflight
# passes them through instead of rejecting them as "unsupported type".
_RESPONSES_BUILTIN_TOOL_TYPES = {
"web_search", "web_search_preview", "file_search", "code_interpreter",
"image_generation", "computer_use_preview", "local_shell",
}
# Server-side ``*_call`` output items. xAI routinely leaves these at
# ``status="in_progress"`` even when the response is ``completed`` (the search
# finished server-side; the per-item status is never reconciled), so they must
# ``status="in_progress"`` even when the response is ``completed``, so they must
# NOT flip the incomplete verdict — otherwise every server-search turn burns 3
# fruitless continuation retries. Client-side function/custom tool calls keep
# their own in_progress handling.
# fruitless continuation retries.
_SERVER_SIDE_TOOL_CALL_TYPES = {
"web_search_call", "file_search_call", "code_interpreter_call",
"image_generation_call", "computer_call", "local_shell_call", "mcp_call",
@@ -111,6 +105,14 @@ def _field(obj: Any, name: str, default: Any = None) -> Any:
return obj.get(name) if isinstance(obj, dict) else getattr(obj, name, default)
def _part_type(part: Dict[str, Any]) -> str:
return str(part.get("type") or "").strip().lower()
def _text_type_for(role: str) -> str:
return "output_text" if role == "assistant" else "input_text"
def _coerce_arguments(arguments: Any) -> str:
"""Normalize replayed tool-call arguments to a non-empty JSON string."""
if isinstance(arguments, dict):
@@ -155,15 +157,13 @@ def _neutralize_harmony_structure(value: Any) -> Any:
if isinstance(value, (list, tuple)):
return [_neutralize_harmony_structure(item) for item in value]
if isinstance(value, dict):
normalized = {}
for key, item in value.items():
for key in value:
if isinstance(key, str) and _neutralize_harmony_tokens(key) != key:
raise ValueError(
"Reserved Harmony tokens in a JSON object key cannot be "
"neutralized without changing its contract."
)
normalized[key] = _neutralize_harmony_structure(item)
return normalized
return {key: _neutralize_harmony_structure(item) for key, item in value.items()}
return value
@@ -176,7 +176,7 @@ def _iter_content_parts(content: list) -> Iterator[tuple[str, Any]]:
if part:
yield "text", part
elif isinstance(part, dict):
ptype = str(part.get("type") or "").strip().lower()
ptype = _part_type(part)
if ptype in _TEXT_PART_TYPES and _nonempty_str(part.get("text")):
yield "text", part["text"]
elif ptype in _IMAGE_PART_TYPES:
@@ -203,15 +203,12 @@ def _chat_content_to_responses_parts(content: Any, *, role: str = "user") -> Lis
"""Convert chat-style multimodal content to Responses API input parts.
Text becomes ``input_text`` (user) or ``output_text`` (assistant) — the API
rejects the wrong type per role, so callers MUST pass the right role.
``input_image`` is only legal on user messages; on assistant messages the
image is replaced by a text marker (an assistant ``input_image`` 400s on
every replay and bricks the session, and the wire cannot carry it anyway).
Returns an empty list when ``content`` is not a list or has no recognized
parts — callers fall back to the string path.
rejects the wrong type per role. ``input_image`` is only legal on user
messages; on assistant messages the image becomes a text marker (an
assistant ``input_image`` 400s on every replay and bricks the session).
Returns [] when ``content`` is not a list or has no recognized parts.
"""
text_type = "output_text" if role == "assistant" else "input_text"
text_type = _text_type_for(role)
converted: List[Dict[str, Any]] = []
for kind, payload in _iter_content_parts(content if isinstance(content, list) else []):
if kind == "text":
@@ -230,8 +227,8 @@ def _summarize_user_message_for_log(content: Any, *, sep: str = " ") -> str:
Text parts are joined with ``sep`` (``" "`` for logs/spinner/trajectories;
``"\\n"`` for memory providers that feed the text to regexes and text APIs);
images become a ``[N image(s)]`` marker so the attachment is not erased.
Returns ``""`` for None/empty lists and ``str(content)`` for other scalars.
images become a ``[N image(s)]`` marker. ``""`` for None/empty lists,
``str(content)`` for other scalars.
"""
if content is None:
return ""
@@ -255,53 +252,43 @@ def _summarize_user_message_for_log(content: Any, *, sep: str = " ") -> str:
# --- ID helpers ---------------------------------------------------------------
def _deterministic_call_id(fn_name: str, arguments: str, index: int = 0) -> str:
"""Deterministic call_id (random ids would break the prompt-cache prefix).
Thin wrapper over ``agent.message_sanitization.deterministic_call_id``;
kept here because run_agent and tests import it from this module.
"""
"""Deterministic call_id (random ids would break the prompt-cache prefix). Re-exported for run_agent/tests."""
return deterministic_call_id(fn_name, arguments, index)
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 (``codex_mcp__<server>__<tool>_
<id>``) past the cap, and the resulting 400 replays on every turn. The
surrogate is a pure function of the original so a ``function_call`` and its
``function_call_output`` map to the same value; short ids pass through.
The codex app-server namespaces MCP call ids past the cap, and the resulting
400 replays on every turn. The surrogate is a pure function of the original
so a ``function_call`` and its ``function_call_output`` map to the same value.
"""
if len(call_id) <= _MAX_RESPONSES_ITEM_ID_LENGTH:
return call_id
digest = hashlib.sha256(call_id.encode("utf-8", errors="replace")).hexdigest()[:32]
return f"call_{digest}"
return f"call_{hashlib.sha256(call_id.encode('utf-8', errors='replace')).hexdigest()[:32]}"
def _sanitize_replayed_fn_name(name: str) -> str:
"""Coerce a *replayed* ``function_call.name`` to ``^[a-zA-Z0-9_-]{1,64}$``.
An invalid name stored in history (dots, spaces, unicode from a model
degeneration) otherwise 400s every later turn. Invalid runs collapse to
``_``; an all-invalid name degrades to ``"fn"`` rather than an empty string
(which would just trade the 400 for a preflight ValueError). Apply ONLY to
replayed items, never to live tool definitions (schema names must match the
dispatch registry); pairing with the output is by call_id, so renaming is safe.
An invalid name stored in history otherwise 400s every later turn. Invalid
runs collapse to ``_``; an all-invalid name degrades to ``"fn"``. Apply ONLY
to replayed items, never to live tool definitions (schema names must match
the dispatch registry); pairing with the output is by call_id.
"""
if not isinstance(name, str):
return "fn"
if _VALID_RESPONSES_FN_NAME_RE.fullmatch(name):
return name
coerced = re.sub(r"[^A-Za-z0-9_-]", "_", name.strip())
coerced = re.sub(r"_+", "_", coerced).strip("_")
coerced = re.sub(r"_+", "_", re.sub(r"[^A-Za-z0-9_-]", "_", name.strip())).strip("_")
return coerced[:64] or "fn"
def _canonical_call_id_from_fc(response_item_id: Any) -> Optional[str]:
"""Map an ``fc_…`` item id to its canonical ``call_<suffix>``.
Both sides of a replayed pair must derive the SAME call_id from an
fc_-only stored id, or an oversized pair clamps to two different
surrogates. Every caller must go through this helper.
Both sides of a replayed pair must derive the SAME call_id from an fc_-only
stored id, or an oversized pair clamps to two different surrogates.
"""
if isinstance(response_item_id, str) and response_item_id.startswith("fc_") and len(response_item_id) > 3:
return f"call_{response_item_id[3:]}"
@@ -347,7 +334,6 @@ def _derive_responses_function_call_id(call_id: str, response_item_id: Optional[
return f"fc_{candidate[len('call_'):]}"
if sanitized:
return f"fc_{sanitized[:48]}"
seed = source or str(response_item_id or "") or uuid.uuid4().hex
return f"fc_{hashlib.sha1(seed.encode('utf-8')).hexdigest()[:24]}"
@@ -356,30 +342,23 @@ 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."""
if not tools:
return None
converted: List[Dict[str, Any]] = []
for item in tools:
for item in tools or []:
fn = item.get("function", {}) if isinstance(item, dict) else {}
name = fn.get("name")
if not _nonblank(name):
continue
converted.append({
"type": "function", "name": name, "description": fn.get("description", ""), "strict": False,
"parameters": fn.get("parameters", {"type": "object", "properties": {}}),
})
if _nonblank(name):
converted.append({
"type": "function", "name": name, "description": fn.get("description", ""), "strict": False,
"parameters": fn.get("parameters", {"type": "object", "properties": {}}),
})
return converted or None
# --- Message format conversion (chat history -> Responses input) --------------
def _normalize_responses_message_status(value: Any, *, default: str = "completed") -> str:
"""Normalize a replayed assistant message status (completed/incomplete/in_progress).
Preserved modulo case/hyphen spelling so incomplete Codex continuation
turns are not falsely marked completed.
"""
"""Normalize a replayed assistant message status, modulo case/hyphen spelling, so
incomplete Codex continuation turns are not falsely marked completed."""
if isinstance(value, str):
status = value.strip().lower().replace("-", "_").replace(" ", "_")
if status in _RESPONSE_MESSAGE_STATUSES:
@@ -402,11 +381,11 @@ def _message_item(
def _assistant_message_item(
raw: Dict[str, Any], content: List[Dict[str, Any]], *, is_github_responses: bool,
) -> Dict[str, Any]:
"""Build a replayable assistant ``message`` item from a stored one.
"""Replayable assistant ``message`` item from a stored one.
``id`` is kept only when short enough (see _MAX_RESPONSES_ITEM_ID_LENGTH)
and never for GitHub Copilot, which binds ids to a backend connection and
401s on a stale one; ``phase`` is preserved per OpenAI's cache guidance.
``id`` is kept only when short enough and never for GitHub Copilot, which
binds ids to a backend connection and 401s on a stale one; ``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
@@ -422,11 +401,11 @@ def _replay_reasoning_items(
"""Replay persisted encrypted reasoning/compaction items for one assistant turn.
Skips: duplicate ids; ``compaction`` checkpoints unless THIS request carries
``context_management`` (a persisted checkpoint outlives the gate and would
otherwise erase pre-checkpoint history on a model that cannot decrypt it);
items stamped by a different issuer (undecryptable → HTTP 400). Unstamped
legacy items pass through. ``id`` is stripped (store=False lookups 404) along
with the Hermes-only ``_issuer_kind`` stamp.
``context_management`` (a persisted checkpoint would otherwise erase
pre-checkpoint history on a model that cannot decrypt it); items stamped by
a different issuer (undecryptable → HTTP 400). Unstamped legacy items pass
through. ``id`` is stripped (store=False lookups 404) with the Hermes-only
``_issuer_kind`` stamp.
"""
global _CROSS_ISSUER_WARN_EMITTED
codex_reasoning = msg.get("codex_reasoning_items")
@@ -472,7 +451,7 @@ def _replay_message_items(msg: Dict[str, Any], *, is_github_responses: bool) ->
content = [
{"type": "output_text", "text": _str_or_empty(part.get("text", ""))}
for part in raw_item["content"]
if isinstance(part, dict) and str(part.get("type") or "").strip() in {"output_text", "text"}
if isinstance(part, dict) and str(part.get("type") or "").strip() in _OUTPUT_TEXT_TYPES
]
if content:
replayed.append(_assistant_message_item(raw_item, content, is_github_responses=is_github_responses))
@@ -492,7 +471,6 @@ def _replay_tool_call_items(msg: Dict[str, Any], *, start_index: int) -> List[Di
fn_name = fn.get("name")
if not _nonblank(fn_name):
continue
call_id = _resolve_call_id(
tc.get("call_id"), tc.get("id"), fn_name, str(fn.get("arguments", "{}")), start_index + len(replayed),
canonicalize_fc=True,
@@ -537,37 +515,31 @@ def _chat_messages_to_responses_input(
) -> List[Dict[str, Any]]:
"""Convert internal chat-style messages to Responses input items.
``is_xai_responses``: kept for transport signature compatibility; encrypted
reasoning IS replayed on xAI (it relies on cross-turn reasoning threading).
``is_xai_responses``: transport signature compatibility only; encrypted
reasoning IS replayed on xAI (cross-turn reasoning threading).
``replay_encrypted_reasoning``: per-session kill switch. Relays that reject
a replayed blob with HTTP 400 ``invalid_encrypted_content`` trigger
``AIAgent._disable_codex_reasoning_replay``, which strips cached items and
threads False here so later turns send no reasoning items.
``replay_encrypted_reasoning``: per-session kill switch. Relays that reject a
replayed blob with HTTP 400 ``invalid_encrypted_content`` trigger
``AIAgent._disable_codex_reasoning_replay``, which threads False here.
``is_github_responses``: drops ``id`` from replayed message items regardless
of length — Copilot binds ids to a backend connection and rejects a stale
one with HTTP 401 even for short ids. phase/status/content still replay.
of length — Copilot binds ids to a backend connection (HTTP 401 on stale).
``current_issuer_kind``: per-item cross-issuer guard (runs only while replay
is enabled); items stamped by another endpoint are dropped, unstamped legacy
items replay.
``current_issuer_kind``: per-item cross-issuer guard (only while replay is
enabled); items stamped by another endpoint are dropped, legacy items replay.
``native_compaction_eligible``: mirrors, for THIS request, whether
``native_compaction_context_management`` produced a payload. Gates both
replaying ``compaction`` checkpoints and restructuring the wire around them
(``prune_pre_checkpoint_items``). Checkpoints persist in the reasoning
sidecar across model swaps / compression flips / resume; without this gate
one captured checkpoint would delete pre-checkpoint history from every later
request on a model that cannot decrypt it. Default False = pre-feature wire,
correct for callers that never send ``context_management``. Dropping the
checkpoint is lossless: local history is never truncated by native compaction.
``native_compaction_eligible``: whether THIS request carries
``context_management``. Gates both replaying ``compaction`` checkpoints and
``prune_pre_checkpoint_items``. Checkpoints persist in the reasoning sidecar
across model swaps / compression flips / resume; without this gate one
checkpoint would delete pre-checkpoint history from every later request on a
model that cannot decrypt it. Dropping the checkpoint is lossless: local
history is never truncated by native compaction.
"""
items: List[Dict[str, Any]] = []
# Parallel to ``items``: the raw chat message each item came from. Pruning
# reads a summary carrier's up-to-date, provenance-tagged content from the
# source — the converted item may be a lossy shape (stale exact replay, or
# a typed ``function_call_output`` wrapper) that no longer carries it.
# reads a summary carrier's provenance-tagged content from the source, since
# the converted item may be a lossy shape that no longer carries it.
item_sources: List[Optional[Dict[str, Any]]] = []
seen_item_ids: set = set()
@@ -590,10 +562,10 @@ def _chat_messages_to_responses_input(
content = msg.get("content", "")
content_parts = _chat_content_to_responses_parts(content, role=role) # [] unless a list
if isinstance(content, list):
text_type = "output_text" if role == "assistant" else "input_text"
text_type = _text_type_for(role)
content_text = "".join(p["text"] for p in content_parts if p["type"] == text_type)
else:
content_text = "" if content is None else str(content)
content_text = _str_or_empty(content)
if role == "user":
emit([{"role": role, "content": content_parts or content_text}], msg)
@@ -613,18 +585,16 @@ def _chat_messages_to_responses_input(
elif content_text.strip():
emit([{"role": "assistant", "content": content_text}], msg)
elif reasoning_items:
# Every reasoning item needs a following item (else
# missing_following_item); emit an empty message.
# Every reasoning item needs a following item (else missing_following_item).
emit([{"role": "assistant", "content": ""}], msg)
emit(_replay_tool_call_items(msg, start_index=len(items)), msg)
# Native server-side compaction: the server renders nothing placed before a
# compaction item, so pre-checkpoint history is dead upload weight and the
# user's plaintext asks / merged local summaries silently vanish. Keep the
# newest checkpoint first, retain pre-checkpoint USER and compression-SUMMARY
# messages verbatim within a token budget, leave the tail untouched. Gated
# on THIS request's eligibility, not merely on a checkpoint being present.
# Native server-side compaction renders nothing placed before a compaction
# item, so pre-checkpoint history is dead upload weight and the user's
# plaintext asks / merged local summaries silently vanish. Keep the newest
# checkpoint first, retain pre-checkpoint USER and compression-SUMMARY
# messages within a token budget, leave the tail untouched.
if not native_compaction_eligible:
return items
@@ -636,8 +606,7 @@ def _chat_messages_to_responses_input(
class ResponsesRouteFlags(NamedTuple):
"""Which special Responses-API route an agent is talking to.
Single owner of the codex/xai/github predicates: every site (request
kwargs, preflight estimation, silent-reject hints) must call
Single owner of the codex/xai/github predicates: every site must call
:func:`classify_responses_route` — inline string comparisons drift.
"""
@@ -656,18 +625,14 @@ def classify_responses_route(agent: Any) -> ResponsesRouteFlags:
provider = getattr(agent, "provider", None)
base_url = str(getattr(agent, "base_url", "") or "")
hostname = str(getattr(agent, "_base_url_hostname", "") or "").lower()
if not hostname:
hostname = base_url_hostname(base_url)
hostname = str(getattr(agent, "_base_url_hostname", "") or "").lower() or base_url_hostname(base_url)
lower = str(getattr(agent, "_base_url_lower", "") or base_url).lower()
def _host_is(domain: str) -> bool:
return hostname == domain or hostname.endswith("." + domain)
return ResponsesRouteFlags(
is_codex_backend=(
provider == "openai-codex" or (_host_is("chatgpt.com") and "/backend-api/codex" in lower)
),
is_codex_backend=provider == "openai-codex" or (_host_is("chatgpt.com") and "/backend-api/codex" in lower),
is_xai_responses=provider in {"xai", "xai-oauth"} or hostname == "api.x.ai",
is_github_responses=_host_is("models.github.ai") or _host_is("githubcopilot.com"),
)
@@ -682,11 +647,10 @@ def estimate_native_responses_preflight_tokens(
) -> Optional[int]:
"""Estimate tokens for the checkpoint-pruned Responses payload.
Counting the full durable transcript overstates a natively compacted
session several times over and fires local compression against history
the request will never send. Returns None when native compaction is not
proven eligible or conversion fails — caller falls back to the generic
(conservative) estimate.
Counting the full durable transcript overstates a natively compacted session
several times over and fires local compression against history the request
will never send. None when native compaction is not proven eligible or
conversion fails — caller falls back to the generic (conservative) estimate.
"""
if getattr(agent, "api_mode", None) != "codex_responses" or not isinstance(messages, list):
return None
@@ -714,7 +678,6 @@ def estimate_native_responses_preflight_tokens(
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
@@ -732,27 +695,29 @@ class _PreflightCtx(NamedTuple):
seen_ids: set
def _preflight_function_call(item: Dict[str, Any], idx: int, ctx: _PreflightCtx) -> Dict[str, Any]:
def _require_call_id(item: Dict[str, Any], idx: int, kind: str) -> str:
call_id = item.get("call_id")
name = item.get("name")
if not _nonblank(call_id):
raise ValueError(f"Codex Responses input[{idx}] function_call is missing call_id.")
raise ValueError(f"Codex Responses input[{idx}] {kind} is missing call_id.")
return call_id.strip()
def _preflight_function_call(item: Dict[str, Any], idx: int, ctx: _PreflightCtx) -> Dict[str, Any]:
call_id = _require_call_id(item, idx, "function_call")
name = item.get("name")
if not _nonblank(name):
raise ValueError(f"Codex Responses input[{idx}] function_call is missing name.")
return {
"type": "function_call", "call_id": call_id.strip(), "name": _sanitize_replayed_fn_name(name),
"type": "function_call", "call_id": call_id, "name": _sanitize_replayed_fn_name(name),
"arguments": ctx.sanitize_text(_coerce_arguments(item.get("arguments", "{}"))),
}
def _preflight_function_call_output(item: Dict[str, Any], idx: int, ctx: _PreflightCtx) -> Dict[str, Any]:
call_id = item.get("call_id")
if not _nonblank(call_id):
raise ValueError(f"Codex Responses input[{idx}] function_call_output is missing call_id.")
call_id = _require_call_id(item, idx, "function_call_output")
output = item.get("output", "")
if isinstance(output, list):
# Multimodal tool result: keep recognised input_text/input_image
# parts, drop anything else to avoid a 4xx.
# Multimodal tool result: keep recognised input_text/input_image parts, drop the rest (4xx otherwise).
cleaned: List[Dict[str, Any]] = []
for part in output:
ptype = part.get("type") if isinstance(part, dict) else None
@@ -763,15 +728,14 @@ def _preflight_function_call_output(item: Dict[str, Any], idx: int, ctx: _Prefli
output_value: Any = cleaned or ""
else:
output_value = ctx.sanitize_text(_str_or_empty(output))
return {"type": "function_call_output", "call_id": call_id.strip(), "output": output_value}
return {"type": "function_call_output", "call_id": call_id, "output": output_value}
def _preflight_reasoning(item: Dict[str, Any], idx: int, ctx: _PreflightCtx) -> Optional[Dict[str, Any]]:
encrypted = item.get("encrypted_content")
if not _nonempty_str(encrypted):
return None
# ``id`` is used only for local dedup and NOT forwarded: with store=False
# the API resolves ids server-side and 404s.
# ``id`` is used only for local dedup and NOT forwarded (store=False → server-side 404).
item_id = item.get("id")
if _nonempty_str(item_id):
if item_id in ctx.seen_ids:
@@ -803,12 +767,11 @@ def _preflight_message(item: Dict[str, Any], idx: int, ctx: _PreflightCtx) -> Di
if not isinstance(part, dict):
raise ValueError(f"Codex Responses input[{idx}] message content[{part_idx}] must be an object.")
part_type = part.get("type")
if part_type not in {"output_text", "text"}:
if part_type not in _OUTPUT_TEXT_TYPES:
raise ValueError(
f"Codex Responses input[{idx}] message content[{part_idx}] has unsupported type {part_type!r}."
)
text = _str_or_empty(part.get("text", ""))
normalized_content.append({"type": "output_text", "text": ctx.sanitize_text(text)})
normalized_content.append({"type": "output_text", "text": ctx.sanitize_text(_str_or_empty(part.get("text", "")))})
if not normalized_content:
raise ValueError(f"Codex Responses input[{idx}] message item must contain at least one text part.")
return _assistant_message_item(item, normalized_content, is_github_responses=ctx.is_github_responses)
@@ -819,10 +782,9 @@ def _preflight_role_message(item: Dict[str, Any], idx: int, role: str, ctx: _Pre
if not isinstance(content, list):
return {"role": role, "content": ctx.sanitize_text(_str_or_empty(content))}
# Parts are already Responses-shaped; validate and re-type text for the
# role (``output_text`` for assistant, ``input_text`` for user). Unlike
# history conversion, empty text / empty image urls are kept, not dropped.
text_type = "output_text" if role == "assistant" else "input_text"
# Parts are already Responses-shaped; validate and re-type text for the role.
# Unlike history conversion, empty text / empty image urls are kept, not dropped.
text_type = _text_type_for(role)
validated: List[Dict[str, Any]] = []
for part_idx, part in enumerate(content):
if isinstance(part, str):
@@ -831,11 +793,10 @@ def _preflight_role_message(item: Dict[str, Any], idx: int, role: str, ctx: _Pre
continue
if not isinstance(part, dict):
raise ValueError(f"Codex Responses input[{idx}].content[{part_idx}] must be an object or string.")
ptype = str(part.get("type") or "").strip().lower()
ptype = _part_type(part)
if ptype in _TEXT_PART_TYPES:
text = part.get("text", "")
text = text if isinstance(text, str) else str(text or "")
validated.append({"type": text_type, "text": ctx.sanitize_text(text)})
validated.append({"type": text_type, "text": ctx.sanitize_text(text if isinstance(text, str) else str(text or ""))})
elif ptype in _IMAGE_PART_TYPES:
if role == "assistant":
# Same output-message invariant as normal history replay.
@@ -875,7 +836,6 @@ def _preflight_codex_input_items(
for idx, item in enumerate(raw_items):
if not isinstance(item, dict):
raise ValueError(f"Codex Responses input[{idx}] must be an object.")
item_type = item.get("type")
handler = _PREFLIGHT_ITEM_HANDLERS.get(item_type) if isinstance(item_type, str) else None
if handler is not None:
@@ -890,7 +850,6 @@ def _preflight_codex_input_items(
normalized_item = _preflight_role_message(item, idx, role, ctx)
if normalized_item is not None:
normalized.append(normalized_item)
return normalized
@@ -898,13 +857,10 @@ def _preflight_tool(tool: Any, idx: int) -> Dict[str, Any]:
if not isinstance(tool, dict):
raise ValueError(f"Codex Responses tools[{idx}] must be an object.")
tool_type = tool.get("type")
# Provider-executed built-ins carry no name/parameters; pass them through
# verbatim rather than rejecting them below.
if tool_type in _RESPONSES_BUILTIN_TOOL_TYPES:
if tool_type in _RESPONSES_BUILTIN_TOOL_TYPES: # provider-executed built-ins carry no name/parameters
return dict(tool)
if tool_type != "function":
raise ValueError(f"Codex Responses tools[{idx}] has unsupported type {tool.get('type')!r}.")
name = tool.get("name")
parameters = tool.get("parameters")
if not _nonblank(name):
@@ -931,8 +887,7 @@ _PREFLIGHT_OPTIONAL_FIELDS: tuple[tuple[str, Callable[[Any], bool], Optional[Cal
("parallel_tool_calls", lambda v: v is not None, None),
("prompt_cache_key", lambda v: v is not None, None),
("prompt_cache_retention", lambda v: v is not None, None),
# Native compaction directive; eligibility is resolved upstream in
# agent/native_compaction.py — preflight only preserves the shape.
# Native compaction directive; eligibility is resolved in agent/native_compaction.py.
("context_management", lambda v: isinstance(v, list) and bool(v), None),
)
@@ -1006,9 +961,8 @@ def _preflight_codex_api_kwargs(
if extra_body is not None:
if not isinstance(extra_body, dict):
raise ValueError("Codex Responses request 'extra_body' must be an object.")
# Verbatim: xAI carries ``prompt_cache_key`` as a body-level field. The
# SDK serializes extra_body without per-field checks, so it survives
# Responses.stream() kwarg-signature changes.
# Verbatim: xAI carries ``prompt_cache_key`` as a body-level field, and
# the SDK serializes extra_body without per-field checks.
if extra_body:
normalized["extra_body"] = dict(extra_body)
@@ -1024,9 +978,7 @@ def _preflight_codex_api_kwargs(
raise ValueError("Codex Responses stream flag is only allowed in fallback streaming requests.")
# Defense-in-depth slash-enum strip for xAI (rejects ``Qwen/Qwen3.5`` style
# enum values with "Invalid arguments passed to the model"). Gated on the
# model name because native Codex accepts slashes — stripping there would
# silently degrade tool-schema constraints.
# enum values). Gated on the model name because native Codex accepts slashes.
is_xai_model = str(api_kwargs.get("model") or "").lower().startswith(("grok-", "x-ai/grok-"))
if is_xai_model and normalized.get("tools"):
try:
@@ -1038,7 +990,6 @@ def _preflight_codex_api_kwargs(
unexpected = sorted(key for key in api_kwargs if key not in allowed_keys)
if unexpected:
raise ValueError(f"Codex Responses request has unsupported field(s): {', '.join(unexpected)}.")
return normalized
@@ -1058,23 +1009,19 @@ def _text_chunks(parts: Any, types: Optional[set] = None) -> List[str]:
def _extract_responses_message_text(item: Any) -> str:
"""Extract assistant text from a Responses message output item."""
return "".join(_text_chunks(getattr(item, "content", None), {"output_text", "text"})).strip()
return "".join(_text_chunks(getattr(item, "content", None), _OUTPUT_TEXT_TYPES)).strip()
def _extract_responses_reasoning_text(item: Any) -> str:
"""Extract a compact reasoning text from a Responses reasoning item (summary, else ``text``)."""
"""Compact reasoning text from a Responses reasoning item (summary, else ``text``)."""
chunks = _text_chunks(getattr(item, "summary", None))
text = getattr(item, "text", None)
return "\n".join(chunks).strip() if chunks else (text.strip() if isinstance(text, str) else "")
def _format_responses_error(error_obj: Any, response_status: str) -> str:
"""Human-readable string for a ``response.error`` payload (dict or object).
Prefers ``"<code>: <message>"`` so failure modes (rate limit vs context
length vs overloaded) are distinguishable; falls back to whichever is
present, then ``str(error_obj)``, then a status-based default.
"""
"""Human-readable ``"<code>: <message>"`` for a ``response.error`` payload (dict or object),
falling back to whichever is present, then ``str(error_obj)``, then a status-based default."""
def field(name: str) -> str:
value = _field(error_obj, name)
return str(value).strip() if isinstance(value, str) or value else ""
@@ -1112,10 +1059,7 @@ def _response_tool_call(item: Any, item_type: str, index: int) -> SimpleNamespac
def _stamped_encrypted_item(item: Any, item_type: str, issuer_kind: Optional[str]) -> Optional[Dict[str, Any]]:
"""``{type, encrypted_content[, _issuer_kind]}`` for replay, or None without a blob.
``_issuer_kind`` is stamped so a later model swap can detect an endpoint
that cannot decrypt the blob.
"""
``_issuer_kind`` lets a later model swap detect an endpoint that cannot decrypt the blob."""
encrypted = getattr(item, "encrypted_content", None)
if not _nonempty_str(encrypted):
return None
@@ -1147,6 +1091,74 @@ def _capture_reasoning_item(item: Any, issuer_kind: Optional[str]) -> Optional[D
return raw_item
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.has_incomplete_items = response_status in _INCOMPLETE_STATUSES
self.saw_streaming_or_item_incomplete = response_status in {"queued", "in_progress"}
self.saw_commentary_phase = False
self.saw_final_answer_phase = False
self.saw_reasoning_item = False
def scan(self, output: List[Any], issuer_kind: Optional[str]) -> None:
for item in output:
item_type = getattr(item, "type", None)
item_status = _lower_or_none(getattr(item, "status", None))
if item_status in _INCOMPLETE_STATUSES and item_type not in _SERVER_SIDE_TOOL_CALL_TYPES:
self.has_incomplete_items = True
self.saw_streaming_or_item_incomplete = True
if item_type == "message":
self._message(item, item_status)
elif item_type == "reasoning":
self.saw_reasoning_item = True
reasoning_text = _extract_responses_reasoning_text(item)
if reasoning_text:
self.reasoning_parts.append(reasoning_text)
raw_item = _capture_reasoning_item(item, issuer_kind)
if raw_item is not None:
self.reasoning_items_raw.append(raw_item)
elif item_type == "compaction":
# Native compaction checkpoint rides the codex_reasoning_items sidecar
# so it inherits persistence, replay, the cross-issuer guard and the kill switch.
raw_item = _stamped_encrypted_item(item, "compaction", issuer_kind)
if raw_item is not None:
self.reasoning_items_raw.append(raw_item)
logger.info(
"Native Responses compaction item captured (%d chars encrypted).",
len(raw_item["encrypted_content"]),
)
elif item_type in {"function_call", "custom_tool_call"}:
if item_type == "function_call" and item_status in _INCOMPLETE_STATUSES:
continue
self.tool_calls.append(_response_tool_call(item, item_type, len(self.tool_calls)))
def _message(self, item: Any, item_status: Optional[str]) -> None:
normalized_phase = _lower_or_none(getattr(item, "phase", None))
is_commentary_phase = normalized_phase in {"commentary", "analysis"}
self.saw_commentary_phase = self.saw_commentary_phase or is_commentary_phase
self.saw_final_answer_phase = self.saw_final_answer_phase or normalized_phase in {"final_answer", "final"}
message_text = _extract_responses_message_text(item)
if not message_text:
return
# commentary/analysis text is mid-turn narration, never the final answer:
# keep it out of content but surface it via the reasoning channel. The
# exact item is still preserved for replay/cache continuity.
(self.reasoning_parts if is_commentary_phase else self.content_parts).append(message_text)
item_id = getattr(item, "id", None)
self.message_items_raw.append(_message_item(
[{"type": "output_text", "text": message_text}],
status=_normalize_responses_message_status(item_status),
item_id=item_id if isinstance(item_id, str) else None, phase=normalized_phase,
))
def _normalize_codex_response(response: Any, *, issuer_kind: Optional[str] = None) -> tuple[Any, str]:
"""Normalize a Responses API object to an assistant_message-like object.
@@ -1171,9 +1183,8 @@ def _normalize_codex_response(response: Any, *, issuer_kind: Optional[str] = Non
)
output = [_synthetic_message([SimpleNamespace(type="output_text", text=out_text.strip())])]
elif response_incomplete_content_filter:
# Deterministic provider safety block, not a partial answer:
# synthesize an empty message so finish_reason becomes
# content_filter instead of burning continuation attempts.
# Deterministic provider safety block, not a partial answer: an empty
# message makes finish_reason content_filter instead of burning continuations.
output = [_synthetic_message([])]
else:
raise RuntimeError("Responses API returned no output items")
@@ -1182,79 +1193,21 @@ def _normalize_codex_response(response: Any, *, issuer_kind: Optional[str] = Non
if response_status in {"failed", "cancelled"}:
raise RuntimeError(_format_responses_error(getattr(response, "error", None), response_status))
content_parts: List[str] = []
reasoning_parts: List[str] = []
reasoning_items_raw: List[Dict[str, Any]] = []
message_items_raw: List[Dict[str, Any]] = []
tool_calls: List[Any] = []
has_incomplete_items = response_status in _INCOMPLETE_STATUSES
saw_streaming_or_item_incomplete = response_status in {"queued", "in_progress"}
saw_commentary_phase = False
saw_final_answer_phase = False
saw_reasoning_item = False
scan = _OutputScan(response_status)
scan.scan(output, issuer_kind)
tool_calls, reasoning_parts = scan.tool_calls, scan.reasoning_parts
for item in output:
item_type = getattr(item, "type", None)
item_status = _lower_or_none(getattr(item, "status", None))
if item_status in _INCOMPLETE_STATUSES and item_type not in _SERVER_SIDE_TOOL_CALL_TYPES:
has_incomplete_items = True
saw_streaming_or_item_incomplete = True
if item_type == "message":
normalized_phase = _lower_or_none(getattr(item, "phase", None))
is_commentary_phase = normalized_phase in {"commentary", "analysis"}
saw_commentary_phase = saw_commentary_phase or is_commentary_phase
saw_final_answer_phase = saw_final_answer_phase or normalized_phase in {"final_answer", "final"}
message_text = _extract_responses_message_text(item)
if message_text:
# commentary/analysis phase text is mid-turn narration, never
# the final answer: keep it out of content (so it cannot leak
# into the response) but surface it via the reasoning channel.
# The exact item is still preserved for replay/cache continuity.
(reasoning_parts if is_commentary_phase else content_parts).append(message_text)
item_id = getattr(item, "id", None)
message_items_raw.append(_message_item(
[{"type": "output_text", "text": message_text}],
status=_normalize_responses_message_status(item_status),
item_id=item_id if isinstance(item_id, str) else None, phase=normalized_phase,
))
elif item_type == "reasoning":
saw_reasoning_item = True
reasoning_text = _extract_responses_reasoning_text(item)
if reasoning_text:
reasoning_parts.append(reasoning_text)
raw_item = _capture_reasoning_item(item, issuer_kind)
if raw_item is not None:
reasoning_items_raw.append(raw_item)
elif item_type == "compaction":
# Native compaction checkpoint: rides the codex_reasoning_items
# sidecar so it inherits persistence, replay, the cross-issuer
# guard and the kill switch without new state.
raw_item = _stamped_encrypted_item(item, "compaction", issuer_kind)
if raw_item is not None:
reasoning_items_raw.append(raw_item)
logger.info(
"Native Responses compaction item captured (%d chars encrypted).",
len(raw_item["encrypted_content"]),
)
elif item_type in {"function_call", "custom_tool_call"}:
if item_type == "function_call" and item_status in _INCOMPLETE_STATUSES:
continue
tool_calls.append(_response_tool_call(item, item_type, len(tool_calls)))
final_text = "\n".join(content_parts).strip()
if not final_text and hasattr(response, "output_text") and (saw_final_answer_phase or not saw_commentary_phase):
final_text = "\n".join(scan.content_parts).strip()
if not final_text and hasattr(response, "output_text") and (scan.saw_final_answer_phase or not scan.saw_commentary_phase):
out_text = getattr(response, "output_text", "")
if isinstance(out_text, str):
final_text = out_text.strip()
# Tool-call leak recovery: gpt-5.x sometimes emits the intended
# ``function_call`` as plain Harmony text (``to=functions.foo {json}``)
# with no structured item, so ``tool_calls`` is empty and no tool ran.
# Treat as incomplete so the continuation path re-elicits a real call;
# clear the text so the garbage is not surfaced as a summary (encrypted
# reasoning is preserved for the retry).
# ``function_call`` as plain Harmony text (``to=functions.foo {json}``) with
# no structured item. Treat as incomplete so the continuation path
# re-elicits a real call; clear the text so the garbage is not surfaced
# (encrypted reasoning is preserved for the retry).
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(
@@ -1266,10 +1219,9 @@ def _normalize_codex_response(response: Any, *, issuer_kind: Optional[str] = Non
# Reasoning-channel answer salvage (xAI grok): grok-4.x sometimes puts the
# final answer inside the reasoning item after its ``<response>`` delimiter.
# Without salvage the reasoning-only rule marks the turn incomplete, and
# since these items carry no encrypted_content every continuation request
# is byte-identical to the failed one. Promote the delimited tail to
# content and keep the untagged prefix as thinking text.
# Without salvage the reasoning-only rule marks the turn incomplete, and since
# these items carry no encrypted_content every continuation request is
# byte-identical to the failed one. Promote the delimited tail to content.
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>")
@@ -1290,8 +1242,8 @@ def _normalize_codex_response(response: Any, *, issuer_kind: Optional[str] = Non
reasoning="\n\n".join(reasoning_parts).strip() if reasoning_parts else None,
reasoning_content=None,
reasoning_details=None,
codex_reasoning_items=reasoning_items_raw or None,
codex_message_items=message_items_raw or None,
codex_reasoning_items=scan.reasoning_items_raw or None,
codex_message_items=scan.message_items_raw or None,
)
if tool_calls:
@@ -1300,16 +1252,15 @@ def _normalize_codex_response(response: Any, *, issuer_kind: Optional[str] = Non
finish_reason = "content_filter"
elif (
leaked_tool_call_text
or saw_streaming_or_item_incomplete
or ((has_incomplete_items or saw_commentary_phase) and not saw_final_answer_phase)
or scan.saw_streaming_or_item_incomplete
or ((scan.has_incomplete_items or scan.saw_commentary_phase) and not scan.saw_final_answer_phase)
):
finish_reason = "incomplete"
elif (reasoning_items_raw or reasoning_parts or saw_reasoning_item) and not final_text:
elif (scan.reasoning_items_raw or reasoning_parts or scan.saw_reasoning_item) and not final_text:
# Reasoning-only response. For Codex/xAI/GitHub, reasoning-only with
# status=completed means "still thinking, needs another turn" →
# incomplete so the continuation path retries. Other backends: trust
# response.status — forcing incomplete there stalls for minutes
# (3 retries × up to 240s) on a legitimately final state.
# status=completed means "still thinking, needs another turn" → incomplete
# so the continuation path retries. Other backends: trust response.status —
# forcing incomplete there stalls for minutes on a legitimately final state.
trusted_final = (
response_status == "completed" and issuer_kind not in ("codex_backend", "xai_responses", "github_responses")
)