The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/transports): trim narrative docstrings/comments in codex, chat_completions, app-server session (WHYs kept)
Teknium18e73f891e9b
diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.pyindex 4bde5cebb4f..33aa565b2b6 100644--- a/agent/transports/chat_completions.py+++ b/agent/transports/chat_completions.py@@ -18,9 +18,8 @@ from agent.prompt_builder import DEVELOPER_ROLE_MODELSfrom agent.transports.base import ProviderTransportfrom agent.transports.types import NormalizedResponse, ToolCall, Usage-# xAI reserves ``tool_search`` for its server-side tool and rejects client-# declarations of it (HTTP 400); alias it on the wire and map back in-# normalize_response. Value matches the Codex-side alias.+# xAI reserves ``tool_search`` for its server-side tool (HTTP 400 on client+# declarations); aliased on the wire, mapped back in normalize_response._XAI_TOOL_SEARCH_ALIAS = "hermes_tool_search"# Persistence-only / cross-transport message keys that strict OpenAI-compatible@@ -68,10 +67,9 @@ def _add_prompt_cache_key("""Add a content-addressed ``prompt_cache_key`` only for a capable endpoint.``cache_scope_id`` (compression-lineage root) beats ``session_id`` so the key- survives context-compression session rotation. A caller-supplied key is- authoritative but is bounded to OpenAI's 64-char wire cap in place. Shares the- Responses transport's hash + scope normalization so equivalent prefixes hit- one bucket across modes.+ survives compression rotation. A caller-supplied key is authoritative but is+ bounded to OpenAI's 64-char cap in place. Shares the Responses transport's hash+ so equivalent prefixes hit one bucket across modes."""from agent.transports.codex import (_bound_prompt_cache_key_field, _cache_scope_from_session_id, _content_cache_key@@ -105,8 +103,7 @@ def _build_gemini_thinking_config(model: str, reasoning_config: dict | None) ->if not isinstance(reasoning_config, dict):return Nonenormalized_model = (model or "").strip().lower().removeprefix("google/")- # ``thinking_config`` is Gemini-only; Gemma/PaLM on the same provider reject- # the field with HTTP 400 even as ``{"includeThoughts": False}``.+ # Gemini-only; Gemma/PaLM on the same provider 400 on the field even as ``{"includeThoughts": False}``.if not normalized_model.startswith("gemini"):return Noneeffort = str(reasoning_config.get("effort", "medium") or "medium").strip().lower()@@ -162,8 +159,7 @@ def _is_gemini_openai_compat_base_url(base_url: Any) -> bool:def _is_openai_api_base_url(base_url: Any) -> bool:"""True only for the exact api.openai.com host (implies ``prompt_cache_key`` support).- Not a substring match: Azure / strict OpenAI-compat endpoints may reject the- field and must stay opt-in via ``supports_prompt_cache_key``.+ Not a substring match: Azure / strict compat endpoints stay opt-in via ``supports_prompt_cache_key``."""try:return (urlparse(str(base_url or "").strip()).hostname or "").lower() == "api.openai.com"@@ -174,8 +170,7 @@ def _is_openai_api_base_url(base_url: Any) -> bool:def _model_consumes_thought_signature(model: Any) -> bool:"""True for Gemini-family targets, which require tool-call ``extra_content`` (thought_signature) replay.- Every other strict provider rejects a request containing it, so it is kept- only for Gemini targets and stripped otherwise (incl. stale inherited copies).+ Every other strict provider rejects it, so it is stripped for non-Gemini targets."""m = str(model or "").lower()return "gemini" in m or "gemma" in m@@ -207,8 +202,7 @@ def _apply_max_tokens(api_kwargs: dict, model: str, reasoning_config: Any, paramdef _base_kwargs(model: str, sanitized: list, tools: Any, params: dict, profile: Any = None) -> dict[str, Any]:"""Shared ``{model, messages[, temperature][, timeout][, tools]}`` scaffold for both build paths.- ``temperature`` is profile-path only: a profile's ``fixed_temperature`` wins- over the caller's, and ``OMIT_TEMPERATURE`` sends none at all.+ ``temperature`` is profile-path only: ``fixed_temperature`` beats the caller's; ``OMIT_TEMPERATURE`` sends none."""api_kwargs: dict[str, Any] = {"model": model, "messages": sanitized}if profile is not None:@@ -240,9 +234,9 @@ def _finish_kwargs(api_kwargs: dict[str, Any], sanitized: list, params: dict, *,def _sanitize_message(msg: Any, strip_extra_content: bool) -> dict | None:"""Sanitized copy of ``msg``, or None when nothing needs stripping.- Drops persistence sidecars, ``_``-prefixed Hermes scaffolding markers, tool-call- ``call_id``/``response_item_id`` (and ``extra_content`` unless a Gemini target),- and an assistant ``tool_calls: []`` / ``null`` (strict providers reject both).+ Drops persistence sidecars, ``_``-prefixed scaffolding markers, tool-call ``call_id`` /+ ``response_item_id`` (and ``extra_content`` unless Gemini), and an assistant+ ``tool_calls: []`` / ``null`` (strict providers reject both)."""if not isinstance(msg, dict):return None@@ -272,9 +266,8 @@ def _sanitize_message(msg: Any, strip_extra_content: bool) -> dict | None:class ChatCompletionsTransport(ProviderTransport):"""Transport for api_mode='chat_completions'."""- # Wire-alias provenance of the most recent request: ``{alias: original}``.- # ``None`` = no request recorded (normalize-only call sites) -> fall back to- # the static alias; ``{}`` = last request emitted no aliases.+ # ``{alias: original}`` of the most recent request. ``None`` = no request recorded+ # (normalize-only call sites) -> static alias; ``{}`` = no aliases emitted._last_wire_aliases: dict[str, str] | None = None@property@@ -301,9 +294,8 @@ class ChatCompletionsTransport(ProviderTransport):) -> dict[str, Any]:"""Build chat.completions.create() kwargs.- With ``provider_profile`` every quirk comes from the profile- (_build_kwargs_from_profile). The legacy flag path below (is_kimi,- is_openrouter, is_lmstudio, ...) is only reached for unregistered providers.+ With ``provider_profile`` every quirk comes from the profile; the legacy flag+ path below (is_kimi, is_openrouter, ...) is only reached for unregistered providers."""sanitized = self.convert_messages(messages, model=model)_profile = params.get("provider_profile")@@ -443,9 +435,8 @@ class ChatCompletionsTransport(ProviderTransport):def normalize_response(self, response: Any, **kwargs) -> NormalizedResponse:"""Normalize an OpenAI ChatCompletion.- Gemini ``extra_content`` rides on ToolCall.provider_data; ``reasoning_content``- (DeepSeek/Moonshot) and ``reasoning_details`` (OpenRouter) are kept apart in- provider_data because downstream reads them distinctly.+ Gemini ``extra_content`` rides on ToolCall.provider_data; ``reasoning_content`` and+ ``reasoning_details`` stay distinct in provider_data because downstream reads them so."""choice = response.choices[0]msg = getattr(choice, "message", None)@@ -463,8 +454,7 @@ class ChatCompletionsTransport(ProviderTransport):# Match Relay's codec: skip absent function/name, keep an explicit blank name.if tc_function is None or function_name is None:continue- # Reverse only aliases THIS request emitted; a real tool named- # ``hermes_tool_search`` dispatches as itself when none were.+ # Reverse only aliases THIS request emitted; a real ``hermes_tool_search`` tool stays itself.if _alias_map is None:if function_name == _XAI_TOOL_SEARCH_ALIAS:function_name = "tool_search"@@ -507,8 +497,7 @@ class ChatCompletionsTransport(ProviderTransport):if getattr(msg, "reasoning_details", None):provider_data["reasoning_details"] = msg.reasoning_details- # OpenAI structured refusal: ``message.refusal`` set, ``content`` empty.- # Proxies fronting Anthropic/Bedrock surface Claude refusals this way; without+ # OpenAI structured refusal (``message.refusal`` set, ``content`` empty); without# promotion the loop retries a deterministic refusal as an empty response.content = getattr(msg, "content", None)refusal = getattr(msg, "refusal", None)@@ -516,8 +505,7 @@ class ChatCompletionsTransport(ProviderTransport):refusal = model_extra.get("refusal")if isinstance(refusal, str) and refusal.strip():provider_data["refusal"] = refusal- # Promote to a terminal ``content_filter`` only when the refusal is the- # sole payload — real text or tool calls alongside it is a usable turn.+ # Terminal ``content_filter`` only when the refusal is the sole payload.if not (isinstance(content, str) and content.strip()) and not tool_calls:content = refusalif finish_reason in (None, "stop"):diff --git a/agent/transports/codex.py b/agent/transports/codex.pyindex abb842d70cc..5538c26ae91 100644--- a/agent/transports/codex.py+++ b/agent/transports/codex.py@@ -57,21 +57,19 @@ def _merge_extra_headers(kwargs: dict[str, Any], **headers: str) -> None:kwargs["extra_headers"] = merged-# Client-side ``web_search`` on xAI Responses collides with Grok's native-# server-side tool (incomplete hang / HTTP 400); it goes on the wire under this-# alias and is mapped back in normalize_response.+# Client-side ``web_search`` on xAI Responses collides with Grok's native tool+# (incomplete hang / HTTP 400); it goes on the wire under this alias._XAI_CLIENT_WEB_SEARCH_ALIAS = "hermes_web_search"# OpenCode /v1/responses rejects client tools using these names (HTTP 400-# "custom function name 'X' is reserved"); xAI rejects ``tool_search``-# (reserved for Grok's native Tool Search). Aliased as hermes_<name>.+# "custom function name 'X' is reserved"); xAI reserves ``tool_search`` for+# Grok's native Tool Search. Aliased as hermes_<name>._OPENCODE_RESERVED_TOOL_NAMES = ("web_search", "search_files")_XAI_RESERVED_TOOL_NAMES = ("tool_search",)_RESERVED_TOOL_ALIAS_PREFIX = "hermes_"# Reverse map used ONLY when normalize_response runs on a transport that never-# built a request; real requests carry request-local ``_last_wire_aliases`` so a-# genuine tool named ``hermes_tool_search`` is never silently rewritten.+# built a request; real requests carry request-local ``_last_wire_aliases``._LEGACY_ALIAS_FALLBACK = {f"{_RESERVED_TOOL_ALIAS_PREFIX}{name}": namefor name in (*_OPENCODE_RESERVED_TOOL_NAMES, *_XAI_RESERVED_TOOL_NAMES)@@ -101,12 +99,10 @@ def _alias_reserved_tools(name_of: Callable[[dict], Any] = lambda t: t.get("name"),rename: Callable[[dict, str], dict] = lambda t, alias: {**t, "name": alias},) -> tuple[list[dict[str, Any]], dict[str, str]]:- """Alias provider-reserved function names on the wire.+ """Alias provider-reserved function names on the wire; returns ``(tools, {alias: original_name})``.- Returns ``(rewritten_tools, {alias: original_name})``. An alias that is- already taken by a real tool gets a ``_2``/``_3`` suffix rather than- duplicating a wire name. ``name_of``/``rename`` adapt the tool shape- (Responses ``{name}`` by default; chat_completions passes ``function.name``).+ An alias already taken by a real tool gets a ``_2``/``_3`` suffix. ``name_of``/``rename``+ adapt the tool shape (Responses ``{name}`` by default; chat_completions passes ``function.name``)."""rewritten: list[dict[str, Any]] = []alias_map: dict[str, str] = {}@@ -130,9 +126,7 @@ def _alias_reserved_tools(def _xai_prefers_native_web_search() -> bool:"""True when xAI Responses should use Grok's native ``web_search`` built-in.- Resolves via the web-search registry (config ``web.search_backend`` /- ``web.backend``), falling back to the legacy ``_get_search_backend`` probe.- Fails closed to native (True) on any error.+ Web-search registry first, then the legacy ``_get_search_backend`` probe; fails closed to native (True)."""try:from agent.web_search_registry import get_active_search_provider@@ -149,12 +143,10 @@ def _xai_prefers_native_web_search() -> bool:def _alias_wire_tools(response_tools: Any, params: dict[str, Any], is_xai_responses: bool) -> tuple[Any, dict[str, str]]:- """Apply provider-reserved tool-name aliasing; returns ``(tools, {alias: original})``.+ """Apply provider-reserved tool-name aliasing; returns ``(tools, {alias: original})`` for THIS request.- The alias map is wire provenance for THIS request — normalize_response- reverses only these. xAI: a client function named ``web_search`` collides- with Grok's native search; native mode swaps it 1:1 for the built-in,- client mode keeps Hermes dispatch under an alias.+ xAI: a client ``web_search`` collides with Grok's native search — native mode+ swaps it 1:1 for the built-in, client mode keeps Hermes dispatch under an alias."""wire_aliases: dict[str, str] = {}@@ -179,11 +171,9 @@ def _alias_wire_tools(response_tools: Any, params: dict[str, Any], is_xai_respondef _resolve_reasoning(model: str, params: dict[str, Any]) -> tuple[Any, bool]:- """``(effort, enabled)`` for the request, effort clamped to the endpoint's vocabulary.+ """``(effort, enabled)`` for the request, effort clamped (never escalated) to the endpoint's vocabulary.- Wire vocabularies live in agent.reasoning_effort; clamp_effort picks the- nearest weaker supported level and never escalates. A profile-declared- ``()`` means "no reasoning parameters accepted" (such backends 400 on any+ A profile-declared ``()`` means "no reasoning parameters accepted" (400 on anyreasoning field) and disables reasoning outright."""reasoning_effort, reasoning_enabled = "medium", True@@ -239,8 +229,7 @@ def _default_prompt_cache_retention_for_request(model: str, base_url: Any) -> Opdef _content_cache_key(instructions: str, tools: Optional[list[dict[str, Any]]], scope_id: str = "") -> Optional[str]:"""``pck_<sha256[:24]>`` of (scope_id, instructions, name-sorted tools), or None if nothing static.- The key is a routing hint only. ``scope_id`` keeps unrelated sessions off one- bucket while letting timestamped cron fires of one job share a warm prefix.+ Routing hint only; ``scope_id`` keeps unrelated sessions off one bucket."""if not instructions and not tools:return None@@ -258,9 +247,8 @@ def _content_cache_key(instructions: str, tools: Optional[list[dict[str, Any]]],def _profile_declared_efforts(provider: Any, model: Optional[str], base_url: Any = None) -> Optional[tuple]:"""Provider-profile-declared reasoning-effort vocabulary, or None (fail-open).- Resolves by provider name, then by endpoint host (a custom provider pointed- at a known host gets that host's vocabulary). Lazy import: provider plugins- import this transport during registry discovery.+ Resolves by provider name, then by endpoint host. Lazy import: provider+ plugins import this transport during registry discovery."""try:from providers import get_provider_profile@@ -294,11 +282,9 @@ def _is_azure_foundry_responses(params: dict[str, Any]) -> bool:def _is_post_tool_replay(messages: Optional[list[dict[str, Any]]]) -> bool:"""True when ``messages`` end on a tool-result run issued by the preceding assistant turn.- Azure Foundry rejects only this post-tool follow-up shape when encrypted- reasoning is replayed, so the check is on the *trailing* messages (a whole-- history scan would make suppression sticky). Call ids are resolved the same- way ``_chat_messages_to_responses_input`` does (``call_id``, ``id``,- composite ``call_x|fc_y``, bare ``fc_`` item ids).+ Azure Foundry rejects only this post-tool shape when encrypted reasoning is+ replayed, so only the *trailing* messages are checked (a whole-history scan+ would make suppression sticky). Call ids resolve like ``_chat_messages_to_responses_input``."""from agent.codex_responses_adapter import _canonical_call_id_from_fc, _split_responses_tool_id@@ -339,8 +325,8 @@ def _is_post_tool_replay(messages: Optional[list[dict[str, Any]]]) -> bool:def _native_compaction_active(context_management: Any) -> bool:"""True only when the caller's eligibility gate produced a non-empty payload.- Every native-compaction wire effect hangs off this one predicate, so a- persisted checkpoint cannot keep reshaping requests after the gate closes.+ Every native-compaction wire effect hangs off this predicate, so a persisted+ checkpoint cannot keep reshaping requests after the gate closes."""return isinstance(context_management, list) and bool(context_management)@@ -358,11 +344,9 @@ class ResponsesApiTransport(ProviderTransport):# Codex response.status -> OpenAI finish_reason (caller checks incomplete_details)._STOP_REASON_MAP = {"completed": "stop", "incomplete": "length", "failed": "stop", "cancelled": "stop"}- # Issuer kind of the most recent build_kwargs/convert_messages call; fallback- # for normalize_response so captured reasoning items are stamped correctly.+ # Issuer kind of the most recent build_kwargs/convert_messages call (normalize_response fallback)._last_issuer_kind: Optional[str] = None- # ``{wire_alias: original_name}`` of the most recent build_kwargs call. None- # = no request built (use legacy map); {} = no aliases sent, no reverse rewrite.+ # ``{wire_alias: original}`` of the most recent build_kwargs. None = no request built (legacy map)._last_wire_aliases: Optional[dict[str, str]] = None@property@@ -404,12 +388,11 @@ class ResponsesApiTransport(ProviderTransport):) -> dict[str, Any]:"""Build Responses API kwargs (calls convert_messages/convert_tools internally).- params: instructions, reasoning_config ({effort, enabled}), session_id- (transcript id; Codex ``session_id`` header; cache-scope fallback),- cache_scope_id (rotation-stable logical scope, preferred for the cache- key / xAI conv header), max_tokens, timeout, request_overrides, provider,- base_url, is_github_responses, is_codex_backend, is_xai_responses,- github_reasoning_extra, context_management, replay_encrypted_reasoning.+ params: instructions, reasoning_config ({effort, enabled}), session_id (transcript id;+ Codex header; cache-scope fallback), cache_scope_id (rotation-stable scope for the+ cache key / xAI conv header), max_tokens, timeout, request_overrides, provider, base_url,+ is_github_responses, is_codex_backend, is_xai_responses, github_reasoning_extra,+ context_management, replay_encrypted_reasoning."""from run_agent import DEFAULT_AGENT_IDENTITY@@ -423,13 +406,11 @@ class ResponsesApiTransport(ProviderTransport):is_github_responses = params.get("is_github_responses") is Trueis_codex_backend = params.get("is_codex_backend") is Trueis_xai_responses = params.get("is_xai_responses") is True- # Foundry 400s on encrypted-reasoning replay only in the post-tool- # follow-up turn; suppress replay for exactly that shape.+ # Foundry 400s on encrypted-reasoning replay only in the post-tool follow-up turn.replay_encrypted_reasoning = bool(params.get("replay_encrypted_reasoning", True)) and not (_is_azure_foundry_responses(params) and _is_post_tool_replay(payload_messages))- # Single source of truth: the same predicate decides whether- # context_management goes out AND whether the converter may replay a checkpoint.+ # One predicate decides whether context_management goes out AND whether the converter may replay a checkpoint.context_management = params.get("context_management")native_compaction_active = _native_compaction_active(context_management)@@ -449,8 +430,7 @@ class ResponsesApiTransport(ProviderTransport):),"store": False,}- # ``tools`` MUST be omitted when empty: the openai SDK iterates it without- # a None guard before any HTTP request.+ # ``tools`` MUST be omitted when empty: the openai SDK iterates it without a None guard.if response_tools:kwargs["tools"] = response_toolskwargs["tool_choice"] = "auto"@@ -459,10 +439,8 @@ class ResponsesApiTransport(ProviderTransport):kwargs["context_management"] = context_managementsession_id = params.get("session_id")- # Cache key is content-addressed (instructions + tools) within a logical- # scope — cache_scope_id survives compression rotation, and the cron- # per-fire timestamp is stripped. session_id itself stays untouched for- # transcript isolation (Codex ``session_id`` header below).+ # Content-addressed (instructions + tools) within a logical scope that survives+ # compression rotation; session_id itself stays untouched for transcript isolation._cache_scope = _cache_scope_from_session_id(params.get("cache_scope_id") or session_id)cache_key = _content_cache_key(instructions, response_tools, _cache_scope) or _cache_scope# xAI takes prompt_cache_key in extra_body (below); GitHub Models opts out entirely.@@ -496,8 +474,7 @@ class ResponsesApiTransport(ProviderTransport):_bound_prompt_cache_key_field(kwargs)- # Older xAI models reject ``service_tier`` (HTTP 400); only Grok 4.6- # accepts Priority Processing.+ # Older xAI models reject ``service_tier`` (HTTP 400); only Grok 4.6 accepts Priority Processing.if is_xai_responses:from agent.model_metadata import is_grok_46_family@@ -512,9 +489,8 @@ class ResponsesApiTransport(ProviderTransport):kwargs.pop("timeout", None)if is_codex_backend:- # Codex rejects body-level extra_headers, but the SDK kwarg maps to- # HTTP headers. ``session_id`` = raw physical id (transcript identity);- # ``x-client-request-id`` mirrors the body cache key so both agree.+ # SDK kwarg -> HTTP headers. ``session_id`` = raw physical id (transcript+ # identity); ``x-client-request-id`` mirrors the body cache key so both agree.final_cache_key = kwargs.get("prompt_cache_key") or _bounded_prompt_cache_key(_cache_scope)headers = {}if session_id:@@ -527,12 +503,10 @@ class ResponsesApiTransport(ProviderTransport):kwargs["max_output_tokens"] = params["max_tokens"]if is_xai_responses and session_id:- # Scoped like the body key so cron's per-fire timestamp doesn't pin- # each fire to a different xAI backend server.+ # Scoped like the body key so cron fires don't each pin a different xAI backend server._merge_extra_headers(kwargs, **{"x-grok-conv-id": _cache_scope})- # xAI reads prompt_cache_key from the body; sent via extra_body so it- # survives SDK builds whose Responses.stream() dropped the typed kwarg.- # An explicit request_overrides value (top-level kwarg) wins.+ # xAI reads prompt_cache_key from the body; extra_body survives SDK builds whose+ # Responses.stream() dropped the typed kwarg. An explicit request_overrides value wins.existing_extra_body = kwargs.get("extra_body")kwargs["extra_body"] = dict(existing_extra_body) if isinstance(existing_extra_body, dict) else {}kwargs["extra_body"].setdefault("prompt_cache_key", kwargs.get("prompt_cache_key", cache_key))@@ -544,10 +518,9 @@ class ResponsesApiTransport(ProviderTransport):"""Normalize Codex Responses API response to NormalizedResponse."""from agent.codex_responses_adapter import _normalize_codex_response- # Explicit issuer if the caller knows it, else the stash from the paired- # build_kwargs/convert_messages call.- issuer_kind = kwargs.get("issuer_kind") or self._last_issuer_kind- msg, finish_reason = _normalize_codex_response(response, issuer_kind=issuer_kind)+ msg, finish_reason = _normalize_codex_response(+ response, issuer_kind=kwargs.get("issuer_kind") or self._last_issuer_kind+ )tool_calls = Noneif msg and msg.tool_calls:@@ -559,8 +532,7 @@ class ResponsesApiTransport(ProviderTransport):}has_fn = hasattr(tc, "function")name = tc.function.name if has_fn else getattr(tc, "name", "")- # Undo only aliases THIS request emitted; the legacy map applies- # solely to normalize-only call sites that never built a request.+ # Undo only aliases THIS request emitted; the legacy map is for normalize-only call sites.if alias_map is None:name = _LEGACY_ALIAS_FALLBACK.get(name, name)elif name in alias_map:@@ -571,17 +543,13 @@ class ResponsesApiTransport(ProviderTransport):provider_data=provider_data or None,))- provider_data = {}- if msg:- for key in ("codex_reasoning_items", "codex_message_items", "reasoning_details"):- value = getattr(msg, key, None)- if value:- provider_data[key] = value-+ provider_data = {+ key: getattr(msg, key, None)+ for key in ("codex_reasoning_items", "codex_message_items", "reasoning_details")+ if msg and getattr(msg, key, None)+ }return NormalizedResponse(- content=msg.content if msg else None,- tool_calls=tool_calls,- finish_reason=finish_reason or "stop",+ content=msg.content if msg else None, tool_calls=tool_calls, finish_reason=finish_reason or "stop",reasoning=getattr(msg, "reasoning", None) if msg else None,usage=None, # Codex usage is extracted separately in normalize_usage()provider_data=provider_data or None,@@ -590,9 +558,8 @@ class ResponsesApiTransport(ProviderTransport):def validate_response(self, response: Any) -> bool:"""True if response.output is a non-empty list, or a terminal content_filter refusal.- A status=incomplete / reason=content_filter response with no output is a- provider refusal signal that must reach normalization, not a retry.- Does NOT check output_text fallback — the caller handles that.+ An incomplete/content_filter response with no output must reach normalization,+ not a retry. Does NOT check output_text fallback — the caller handles that."""if response is None:return False@@ -610,8 +577,7 @@ class ResponsesApiTransport(ProviderTransport):) -> dict:"""Validate and sanitize Codex API kwargs before the call.- ``sanitize_harmony_tokens`` is enabled only for the ChatGPT Codex- backend, which rejects literal reserved Harmony wire tokens in text.+ ``sanitize_harmony_tokens`` is for the ChatGPT Codex backend only (rejects literal Harmony tokens)."""from agent.codex_responses_adapter import _preflight_codex_api_kwargsdiff --git a/agent/transports/codex_app_server_session.py b/agent/transports/codex_app_server_session.pyindex a4d3b77a5b6..d00d567e8c2 100644--- a/agent/transports/codex_app_server_session.py+++ b/agent/transports/codex_app_server_session.py@@ -3,9 +3,8 @@Owns one Codex thread per Hermes session: drives ``turn/start``, consumesstreaming notifications via CodexEventProjector, bridges server-initiatedapproval requests, translates cancellation, and returns a TurnResult that-AIAgent.run_conversation() splices into ``messages``. Synchronous from the-caller's view: the client's reader threads feed blocking-with-timeout queues-that this adapter polls, matching AIAgent's chat_completions loop.+AIAgent.run_conversation() splices into ``messages``. Synchronous: the client's+reader threads feed queues that this adapter polls, like the chat_completions loop."""from __future__ import annotations@@ -25,9 +24,7 @@ from agent.transports.codex_event_projector import CodexEventProjector, Projectilogger = logging.getLogger(__name__)-# Tail of codex stderr attached to generic user-facing errors: small enough to-# stay legible, large enough to surface a config/provider/auth diagnostic.-_STDERR_TAIL_LINES = 12+_STDERR_TAIL_LINES = 12 # stderr tail on generic errors: legible, yet enough for a config/auth diagnostic# Hermes' tools.terminal.security_mode -> Codex permissions profile id.# Missing config -> workspace-write (Codex's own default).@@ -45,14 +42,13 @@ class TurnResult:projected_messages: list[dict] = field(default_factory=list)tool_iterations: int = 0interrupted: bool = False- error: Optional[str] = None # Set if turn ended in a non-recoverable error+ error: Optional[str] = None # non-recoverable turn errorturn_id: Optional[str] = Nonethread_id: Optional[str] = Nonetoken_usage_last: Optional[dict[str, Any]] = Nonemodel_context_window: Optional[int] = Nonecompacted: bool = False- # Codex subprocess is likely wedged (turn timeout, post-tool watchdog, token- # refresh failure): caller should retire the session so the next turn respawns.+ # Codex likely wedged (turn timeout, watchdog, token refresh failure): caller respawns next turn.should_retire: bool = False@@ -86,9 +82,9 @@ def _notification_scope_ids(note: dict) -> tuple[Optional[str], Optional[str]]:def _notification_belongs_to_turn(note: dict, *, thread_id: Optional[str], turn_id: Optional[str]) -> bool:"""Whether a multiplexed notification belongs to this turn.- One JSON-RPC connection can carry parent and hosted subagent threads; an- explicitly foreign thread/turn event must not mutate this transcript.- Unscoped notifications remain accepted for protocol compatibility.+ One connection can carry parent and hosted subagent threads; an explicitly+ foreign thread/turn event must not mutate this transcript. Unscoped+ notifications remain accepted for protocol compatibility."""if not isinstance(note, dict):return False@@ -100,11 +96,7 @@ def _notification_belongs_to_turn(note: dict, *, thread_id: Optional[str], turn_def _coerce_turn_input_text(user_input: Any) -> str:- """Collapse Hermes/OpenAI rich content parts into app-server text input.-- ``turn/start`` sends text items only; TUI image attachments arrive as content- parts, so keep text and replace image payloads with a marker.- """+ """Collapse rich content parts into app-server text (``turn/start`` is text-only; images become a marker)."""if isinstance(user_input, str):return user_inputif not isinstance(user_input, list):@@ -127,8 +119,7 @@ def _coerce_turn_input_text(user_input: Any) -> str:# Substrings in codex stderr / JSON-RPC errors signalling expired OAuth creds.-# Conservative on purpose: only redirect to `codex login` on a strong signal,-# otherwise the original error surfaces verbatim.+# Conservative: only redirect to `codex login` on a strong signal._OAUTH_REFRESH_FAILURE_HINTS = ("invalid_grant", "invalid grant", "refresh token", "refresh_token", "token refresh", "token_refresh","token has expired", "expired_token", "expired token", "not authenticated", "unauthenticated", "unauthorized",@@ -150,22 +141,14 @@ def _classify_oauth_failure(*parts: str) -> Optional[str]:@dataclassclass _ServerRequestRouting:- """Default approval policies when no interactive callback is wired in.-- Used by tests + cron / non-interactive contexts; the live CLI passes an- approval_callback that defers to tools.approval.prompt_dangerous_approval().- """+ """Default approval policies when no interactive approval_callback is wired in (tests, cron)."""auto_approve_exec: bool = Falseauto_approve_apply_patch: bool = Falseclass CodexAppServerSession:- """One Codex thread per Hermes session, lifetime owned by AIAgent.-- Not thread-safe: one caller drives it at a time (projector, thread_id and- turn state are owned by the caller thread), like AIAgent.run_conversation().- """+ """One Codex thread per Hermes session, lifetime owned by AIAgent. Not thread-safe: one caller at a time."""def __init__(self, *, cwd: Optional[str] = None, codex_bin: str = "codex",@@ -203,10 +186,8 @@ class CodexAppServerSession:if self._client is None:self._client = self._client_factory(codex_bin=self._codex_bin, codex_home=self._codex_home)self._client.initialize(client_name="hermes", client_title="Hermes Agent", client_version=_get_hermes_version())- # Permissions are intentionally NOT sent on thread/start: on codex 0.130- # ``thread/start.permissions`` is gated behind experimentalApi and also- # requires a matching ``[permissions]`` table in ~/.codex/config.toml.- # Users configure a write-capable profile there, as for any codex use.+ # Permissions are NOT sent on thread/start: codex gates ``thread/start.permissions``+ # behind experimentalApi + a matching ``[permissions]`` table in ~/.codex/config.toml.result = self._client.request("thread/start", {"cwd": self._cwd}, timeout=15)# Different codex versions serialize the id under thread.id / sessionId / threadId.thread_obj = result.get("thread") or {}@@ -258,11 +239,7 @@ class CodexAppServerSession:return accepted_turn_id in {None, turn_id}def _format_error_with_stderr(self, prefix: str, exc: Any = "", *, tail_lines: int = _STDERR_TAIL_LINES) -> str:- """User-facing error string for generic codex failures, plus the redacted stderr tail.-- force=True redaction keeps provider/auth secrets out of chat output while- making codex's opaque 'Internal error' diagnosable.- """+ """User-facing error string plus the force-redacted stderr tail (keeps secrets out of chat output)."""exc_str = "" if exc is None else str(exc)base = f"{prefix}: {exc_str}" if exc_str else prefixtry:@@ -284,8 +261,7 @@ class CodexAppServerSession:result.should_retire = Truedef _set_classified_error(self, result: TurnResult, prefix: str, classify_text: str, detail: Any) -> None:- """OAuth failures become the re-auth hint AND retire the session (token store- is broken even though JSON-RPC is fine); everything else gets the stderr tail."""+ """OAuth failures -> re-auth hint AND retire (token store broken though JSON-RPC is fine); else stderr tail."""hint = _classify_oauth_failure(classify_text, self._stderr_blob(40))if hint is not None:self._retire(result, hint)@@ -293,8 +269,7 @@ class CodexAppServerSession:result.error = self._format_error_with_stderr(prefix, detail)def _start_for(self, result: TurnResult) -> bool:- """ensure_started() into ``result``; startup failures surface as TurnResult.error- (retiring the session) instead of raw codex exceptions reaching AIAgent."""+ """ensure_started(); startup failures become a retiring TurnResult.error instead of raw exceptions."""try:self.ensure_started()except (CodexAppServerError, TimeoutError) as exc:@@ -305,8 +280,7 @@ class CodexAppServerSession:return Truedef _request_for(self, result: TurnResult, method: str, params: dict, label: str) -> Optional[dict]:- """Issue ``method``; on failure fill ``result.error`` and return None.- A timeout is a strong wedge signal and always retires the session."""+ """Issue ``method``; on failure fill ``result.error`` and return None. A timeout always retires."""try:return self._client.request(method, params, timeout=10)except CodexAppServerError as exc:@@ -327,9 +301,10 @@ class CodexAppServerSession:def _absorb_notification(self, result: TurnResult, projector: CodexEventProjector, note: dict) -> tuple[ProjectionResult, bool]:- """Fan one in-scope notification out to display, accounting, file-change- tracking and the projector. Returns (projection, aborted) where aborted- means the agent text carried a ``<turn_aborted>`` marker (terminal)."""+ """Fan one in-scope notification out to display, accounting, file-change tracking and the projector.++ Returns (projection, aborted); aborted = agent text carried a terminal ``<turn_aborted>`` marker.+ """if self._on_event is not None:try:self._on_event(note)@@ -357,11 +332,9 @@ class CodexAppServerSession:self, user_input: Any, *, turn_timeout: float = 600.0,notification_poll_timeout: float = 0.25, post_tool_quiet_timeout: float = 90.0,) -> TurnResult:- """Send a user message and block until turn/completed, bridging approvals- and projecting items into Hermes' messages shape.+ """Send a user message and block until turn/completed, bridging approvals and projecting items.- post_tool_quiet_timeout: if codex completes a tool and then stays silent- this long, fast-fail and retire instead of burning the full turn deadline.+ post_tool_quiet_timeout: silence this long after a tool completes fast-fails and retires."""result = TurnResult()if self._start_for(result):@@ -402,9 +375,8 @@ class CodexAppServerSession:def on_server_request(sreq: dict) -> bool:nonlocal last_tool_completion_at- # Drain pending notifications first (bounded) so per-turn state such- # as _pending_file_changes is current for the approval decision, and- # so display events around approvals still reach on_event.+ # Drain pending notifications first (bounded) so _pending_file_changes is+ # current for the approval decision and display events still reach on_event.turn_complete = Falsefor _ in range(8):pending = self._client.take_notification(timeout=0)@@ -456,11 +428,10 @@ class CodexAppServerSession:"""Shared poll loop for run_turn / compact_thread until turn/completed or deadline.Per iteration: interrupt -> subprocess death -> ``before_poll`` (watchdog) ->- server requests (answered before notifications so codex isn't blocked) ->- one notification, filtered by ``pre_scope_filter`` then by turn scope, handed- to ``on_note``. Hooks return True to mark the turn complete / stop the loop.- A deadline without completion interrupts and retires the session — a turn- that never finished is a strong sign the next turn shouldn't inherit this codex.+ server requests (answered first so codex isn't blocked) -> one notification,+ filtered by ``pre_scope_filter`` then turn scope, handed to ``on_note``. Hooks+ return True to complete the turn. Deadline without completion interrupts and+ retires the session."""deadline = time.monotonic() + turn_timeoutturn_complete = False@@ -507,9 +478,8 @@ class CodexAppServerSession:) -> TurnResult:"""Trigger Codex-native history compaction for the current thread.- ``thread/compact/start`` returns immediately (with no turn id); progress- streams through normal turn/item notifications, so we wait for the- matching ``turn/completed`` to treat the return as a compaction boundary.+ ``thread/compact/start`` returns immediately with no turn id; progress streams+ as normal turn/item notifications, so wait for the matching ``turn/completed``."""result = TurnResult()if not self._start_for(result):@@ -533,8 +503,7 @@ class CodexAppServerSession:return Falseresult.turn_id = str(observed_turn_id)elif observed_turn_id is not None or method in {"item/completed", "turn/completed"}:- # Until the new turn/started arrives, terminal/projectable- # events are stale or can't be attributed to this compaction.+ # Before the new turn/started, terminal/projectable events are stale or unattributable.logger.debug("ignoring codex notification before compact turn start: method=%s", method)return Falsereturn True@@ -581,9 +550,8 @@ class CodexAppServerSession:def _handle_server_request(self, req: dict) -> None:"""Answer a codex server request (approval / elicitation) via Hermes' approval flow.- Method names verified live against codex 0.130.0. Permission escalations- are always declined: the user chose their profile in ~/.codex/config.toml.- Unknown methods get a clean JSON-RPC error so codex doesn't hang.+ Permission escalations are always declined (the user chose their profile in+ ~/.codex/config.toml); unknown methods get a JSON-RPC error so codex doesn't hang."""if self._client is None:return@@ -598,10 +566,8 @@ class CodexAppServerSession:self._client.respond(rid, handler(self, params))def _respond_elicitation(self, params: dict) -> dict:- """MCP elicitation (tool confirmation, OAuth, form data): auto-accept for our- own hermes-tools server (the user opted in by enabling the runtime; it exposes- nothing codex's shell can't already do); decline others so the user opts in- via codex's own auth flow."""+ """MCP elicitation: auto-accept our own hermes-tools server (opted in by enabling the runtime;+ exposes nothing codex's shell can't do); decline others so the user opts in via codex's own flow."""action = "accept" if (params.get("serverName") or "") == "hermes-tools" else "decline"return {"action": action, "content": None, "_meta": None}@@ -621,11 +587,10 @@ class CodexAppServerSession:return "decline"def _decide_exec_approval(self, params: dict) -> str:- """Decide a Codex exec approval request — protocol-level routing only.+ """Decide a Codex exec approval — protocol routing only.- Hermes approval mode/timeout resolution lives upstream: codex_runtime.py- derives ``auto_approve_exec`` from tools.approval, and the callback runs- the shared approval gate. Do not re-read approval config here.+ Approval mode/timeout resolution lives upstream (codex_runtime.py derives+ ``auto_approve_exec``; the callback runs the shared gate). Do not re-read config here."""if self._routing.auto_approve_exec:return "accept"@@ -643,8 +608,7 @@ class CodexAppServerSession:return "accept"if self._approval_callback is None:return "decline"- # Params carry reason + grantRoot only; the changeset comes from the- # fileChange item cached by _track_pending_file_change.+ # Params carry reason + grantRoot only; the changeset comes from _track_pending_file_change.reason = params.get("reason")grant_root = params.get("grantRoot")change_summary = self._pending_file_changes.get(params.get("itemId") or "") or None@@ -654,8 +618,7 @@ class CodexAppServerSession:return self._run_approval_callback(f"apply_patch: {detail}" if detail else "apply_patch", description, "apply_patch")def _track_pending_file_change(self, note: dict) -> None:- """Maintain _pending_file_changes from item/started + item/completed so the- apply_patch approval prompt can show what's actually changing."""+ """Track fileChange items (item/started -> item/completed) so the apply_patch prompt can show the changeset."""method = note.get("method", "")item = (note.get("params") or {}).get("item") or {}item_id = item.get("id") or ""@@ -685,24 +648,21 @@ def _summarize_file_changes(raw_changes: list) -> str:def _apply_token_usage_notification(result: TurnResult, note: dict) -> None:- """Capture token usage: codex emits it as a separate thread/tokenUsage/updated- notification (cumulative totals + last-turn breakdown), not on turn/completed."""+ """Capture token usage (codex emits it as thread/tokenUsage/updated, not on turn/completed)."""if not isinstance(note, dict) or note.get("method") != "thread/tokenUsage/updated":returntoken_usage = (note.get("params") or {}).get("tokenUsage") or {}if not isinstance(token_usage, dict):return- last = token_usage.get("last")+ last, window = token_usage.get("last"), token_usage.get("modelContextWindow")if isinstance(last, dict):result.token_usage_last = dict(last)- window = token_usage.get("modelContextWindow")if isinstance(window, int) and window > 0:result.model_context_window = windowdef _apply_compaction_notification(result: TurnResult, note: dict) -> None:- """Capture Codex-native compaction boundaries: a contextCompaction item- (recent builds) or the deprecated thread/compacted notification (older builds)."""+ """Capture compaction boundaries: a contextCompaction item (recent) or deprecated thread/compacted (older)."""if not isinstance(note, dict):returnmethod = note.get("method") or ""@@ -717,9 +677,7 @@ def _apply_compaction_notification(result: TurnResult, note: dict) -> None:result.turn_id = params.get("turnId") or result.turn_id-# Hermes 'once'/'session'/'always'/'deny'(/'timeout') -> codex approval decisions-# (codex-rs app-server-protocol v2). Only the wire translation lives here; the-# approval mode/timeout resolution stays in tools/approval.py. "deny" and+# Hermes approval choice -> codex decision (app-server-protocol v2). "deny" and# "timeout" both decline — codex has no "prompt expired" wire value._APPROVAL_CHOICE_TO_DECISION = {"once": "accept", "session": "acceptForSession", "always": "acceptForSession"}