The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/bedrock_adapter,codex_responses_adapter): compact docstrings/comments, keep every WHY (-150 LOC)
Teknium98ec26620c31
diff --git a/agent/bedrock_adapter.py b/agent/bedrock_adapter.pyindex f5f65ddb8a7..448ac71a1da 100644--- a/agent/bedrock_adapter.py+++ b/agent/bedrock_adapter.py@@ -1,11 +1,9 @@-"""AWS Bedrock Converse API adapter for Hermes Agent.--Talks to Bedrock through the native Converse API (boto3) so the AWS credential-chain (IAM roles, SSO profiles, env vars, instance metadata), cross-region-inference profiles, guardrails and control-plane model discovery all work-without API keys. OpenAI-format messages/tools are converted to Converse format-on the way in and responses normalized back to OpenAI-shaped objects.-Requires ``boto3`` (optional dependency).+"""AWS Bedrock Converse API adapter (boto3, optional dependency).++The AWS credential chain, cross-region inference profiles, guardrails and+control-plane model discovery all work without API keys. OpenAI-format+messages/tools are converted to Converse on the way in and responses normalized+back to OpenAI-shaped objects."""import base64@@ -32,9 +30,8 @@ except Exception:_bedrock_runtime_client_cache: Dict[str, Any] = {}_bedrock_control_client_cache: Dict[str, Any] = {}-# Bedrock-hosted OpenAI GPT-5.x models are served from the Bedrock Mantle-# OpenAI-compatible Responses endpoint, not Converse. Keep the allowlist narrow-# so Converse-capable GPT-OSS models stay on the native path.+# Bedrock-hosted GPT-5.x models are served from the Bedrock Mantle OpenAI-compatible+# endpoint, not Converse. Narrow allowlist so GPT-OSS models stay on the native path.BEDROCK_OPENAI_RESPONSES_MODEL_IDS: Tuple[str, ...] = ("openai.gpt-5.5","openai.gpt-5.6-sol",@@ -161,7 +158,7 @@ class BedrockOpenAISigV4Auth(httpx.Auth):"Configure AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY, AWS_PROFILE, ""SSO, or an instance/task role.")- # SigV4 must own Authorization: drop the SDK's placeholder bearer header, keep the rest.+ # SigV4 must own Authorization: drop the SDK's placeholder bearer header.headers = {str(k): str(v)for k, v in request.headers.items()@@ -184,11 +181,8 @@ def build_bedrock_openai_http_client(region: str, *, timeout: Optional[float] =def configure_bedrock_openai_client_kwargs(client_kwargs: Dict[str, Any], *, timeout: Optional[float] = None,) -> Dict[str, Any]:- """Install SigV4 auth on OpenAI SDK kwargs for Bedrock Mantle.-- Real API keys (``AWS_BEARER_TOKEN_BEDROCK``) keep the SDK's bearer auth; the- ``aws-sdk``/``no-key-required`` placeholders mean IAM credential-chain auth.- """+ """Install SigV4 auth on OpenAI SDK kwargs for Bedrock Mantle. Real API keys keep the+ SDK's bearer auth; the ``aws-sdk``/``no-key-required`` placeholders mean IAM chain auth."""base_url = str(client_kwargs.get("base_url") or "")if not is_bedrock_openai_base_url(base_url):return client_kwargs@@ -202,11 +196,9 @@ def configure_bedrock_openai_client_kwargs(# --- Stale-connection detection ----# boto3 caches its HTTPS pool inside the client. A pooled connection killed out-# from under us (NAT timeout, VPN flap, RST) surfaces as botocore-# ConnectionClosedError / urllib3 ProtocolError, or as a bare AssertionError from-# urllib3's pool-state checks. Retrying with the same client reproduces the-# failure, so the fix is to evict the client.+# A pooled connection killed under boto3 (NAT timeout, VPN flap, RST) surfaces as a+# botocore/urllib3 transport error or a bare AssertionError from urllib3's pool+# checks; retrying the same client reproduces it, so the fix is to evict the client._STALE_LIB_MODULE_PREFIXES = ("urllib3.", "botocore.", "boto3.")@@ -242,12 +234,9 @@ def is_stale_connection_error(exc: BaseException) -> bool:def is_streaming_access_denied_error(exc: BaseException) -> bool:- """True when IAM denied ``bedrock:InvokeModelWithResponseStream``.-- InvokeModel-only policies reject converse_stream() permanently, so callers- should fall back to non-streaming converse(). Message-based because the- AnthropicBedrock SDK wraps the same AWS response but preserves the action name.- """+ """True when IAM denied ``bedrock:InvokeModelWithResponseStream`` (permanent: callers+ fall back to non-streaming converse()). Message-based because the AnthropicBedrock SDK+ wraps the same AWS response but preserves the action name."""msg = str(exc).lower()if "invokemodelwithresponsestream" not in msg:return False@@ -317,12 +306,9 @@ def resolve_bedrock_region(env: Optional[Dict[str, str]] = None) -> str:def resolve_bedrock_runtime_region(config: Optional[Dict[str, Any]] = None) -> str:- """``bedrock.region`` from config.yaml, else :func:`resolve_bedrock_region`.-- Every non-runtime Bedrock endpoint (auxiliary clients, picker discovery) must- use this so auxiliary calls never leave the primary runtime's region when- config and ambient AWS env/profile disagree. Pass *config* to avoid a disk read.- """+ """``bedrock.region`` from config.yaml, else :func:`resolve_bedrock_region`. Every+ non-runtime Bedrock endpoint must use this so auxiliary calls never leave the primary+ runtime's region when config and ambient AWS env disagree. Pass *config* to skip disk."""if config is None:try:from hermes_cli.config import load_config_readonly@@ -346,8 +332,7 @@ def bedrock_model_ids_or_none() -> Optional[List[str]]:# --- Tool-calling / prompt-cache capability detection ----# Models known to reject toolConfig with a ValidationException. Unknown models-# are assumed to support tools.+# Models known to reject toolConfig with a ValidationException; unknown models assumed OK._NON_TOOL_CALLING_PATTERNS = ["deepseek.r1", # DeepSeek R1 — reasoning only"deepseek-r1", # Alternate ID format@@ -356,10 +341,8 @@ _NON_TOOL_CALLING_PATTERNS = ["amazon.titan-embed", # Embeddings]-# cachePoint allowlist — inverted policy vs tools: an unsupported model rejects-# cachePoint with a ValidationException, so unknown models get NO cache markers.-# Claude normally uses the AnthropicBedrock SDK path and only reaches-# build_converse_kwargs under bearer-token auth.+# cachePoint allowlist — inverted policy vs tools: unknown models get NO cache markers+# (they reject cachePoint). Claude only reaches build_converse_kwargs under bearer auth._CACHE_POINT_PATTERNS = ["anthropic.claude", # bearer-token fallback path"amazon.nova",@@ -378,11 +361,10 @@ def _model_supports_prompt_cache(model_id: str) -> bool:# --- Server-verdict cachePoint suppression ----# Bedrock's real cachePoint rule is per-family AND per-field (Nova accepts it in-# system/messages but hard-fails on toolConfig.tools), and any static table-# drifts as AWS ships new families. So when Bedrock names a placement as-# unpermitted we record that verdict, drop the marker from that placement for-# the rest of the process, and retry the rejected request once without it.+# Bedrock's cachePoint rule is per-family AND per-field (Nova accepts it in+# system/messages but hard-fails on toolConfig.tools) and any static table drifts, so+# when Bedrock names a placement as unpermitted we record the verdict, drop the marker+# there for the rest of the process, and retry once without it.CACHE_POINT_PLACEMENTS = ("tools", "system", "messages")@@ -395,13 +377,9 @@ _CACHE_POINT = {"cachePoint": {"type": "default"}}def cache_point_rejection_placement(exc: BaseException) -> Optional[str]:- """Return the Converse section whose cachePoint Bedrock refused, or None.-- Message-based on purpose: the JSON pointer in the ValidationException is the- only thing that says *which* section was rejected, and the same wording- arrives raw from botocore and wrapped by SDKs. An unlocalisable rejection- maps to "tools" — the only placement a supported family is known to refuse.- """+ """Converse section whose cachePoint Bedrock refused, or None. Message-based: the JSON+ pointer in the ValidationException is the only thing naming the section, and the same+ wording arrives raw or SDK-wrapped. Unlocalisable → "tools" (the only known refusal)."""msg = str(exc)lowered = msg.lower()if "cachepoint" not in lowered or ("not permitted" not in lowered and "extraneous" not in lowered):@@ -441,11 +419,8 @@ def _without_cache_points(blocks: Any) -> Optional[list]:def strip_cache_points(kwargs: Dict[str, Any], placement: str) -> Dict[str, Any]:- """Copy of Converse kwargs with ``placement``'s cachePoint removed.-- Returns the input unchanged (same object) when there was nothing to strip,- which is what callers use to decide a retry cannot help.- """+ """Copy of Converse kwargs with ``placement``'s cachePoint removed; the SAME object+ back when nothing was stripped (callers use identity to decide a retry cannot help)."""if placement == "system":cleaned = _without_cache_points(kwargs.get("system"))return kwargs if cleaned is None else {**kwargs, "system": cleaned}@@ -467,11 +442,8 @@ def strip_cache_points(kwargs: Dict[str, Any], placement: str) -> Dict[str, Any]def recover_from_cache_point_rejection(exc: BaseException, kwargs: Dict[str, Any]) -> Optional[Dict[str, Any]]:- """Record Bedrock's cachePoint verdict and return retry kwargs, or None.-- None means the error was not a cachePoint rejection, or the marker was- already absent — retrying cannot change the outcome; caller must re-raise.- """+ """Record Bedrock's cachePoint verdict and return retry kwargs, or None when the error+ was not a cachePoint rejection / the marker was already absent (caller re-raises)."""placement = cache_point_rejection_placement(exc)if placement is None:return None@@ -493,11 +465,8 @@ _REGIONAL_PREFIXES = ("global.", "us.", "eu.", "apac.", "ap.", "au.", "jp.", "cadef is_anthropic_bedrock_model(model_id: str) -> bool:- """True for Claude on Bedrock (``anthropic.claude-*`` with any regional prefix).-- These use the AnthropicBedrock SDK path (prompt caching, thinking budgets);- non-Claude models use the Converse path.- """+ """True for Claude on Bedrock (``anthropic.claude-*`` with any regional prefix); these+ use the AnthropicBedrock SDK path, everything else the Converse path."""model_lower = model_id.lower()for prefix in _REGIONAL_PREFIXES:if model_lower.startswith(prefix):@@ -536,11 +505,8 @@ def _safe_text(text) -> str:def _image_block_from_data_url(url: str) -> Dict:- """``data:<mime>;base64,...`` → Converse image block with RAW bytes.-- boto3 base64-encodes at the wire layer, so passing the base64 string through- double-encodes and Bedrock rejects it ("Failed to sanitize image").- """+ """``data:<mime>;base64,...`` → Converse image block with RAW bytes (boto3 base64-encodes+ at the wire layer; passing the string through double-encodes and Bedrock rejects it)."""header, _, data = url.partition(",")media_type = (header[5:].split(";")[0] if header.startswith("data:") else "") or "image/jpeg"try:@@ -554,11 +520,8 @@ def _image_block_from_data_url(url: str) -> Dict:def _convert_content_to_converse(content) -> List[Dict]:- """OpenAI message content (str or parts list) → Converse content blocks.-- Empty/whitespace text becomes the placeholder; remote image URLs (unsupported- by Converse) become a text reference.- """+ """OpenAI message content → Converse blocks. Blank text becomes the placeholder; remote+ image URLs (unsupported by Converse) become a text reference."""if not isinstance(content, list):return [{"text": _safe_text(content)}]blocks = []@@ -602,11 +565,8 @@ def _decode_redacted(encoded) -> Optional[bytes]:def _replay_ordered_blocks(ordered_blocks: List) -> List[Dict]:- """Rebuild the exact Bedrock block sequence captured at normalization time.-- Redacted reasoning bytes are stored base64-encoded (JSON-safe sidecar);- undecodable entries are skipped.- """+ """Rebuild the exact Bedrock block sequence captured at normalization time; redacted+ reasoning is stored base64 (JSON-safe sidecar) and undecodable entries are skipped."""content_blocks: List[Dict] = []for block in ordered_blocks:if not isinstance(block, dict):@@ -643,12 +603,9 @@ def _parse_tool_args(args) -> Any:def _assistant_blocks(msg: Dict, content) -> List[Dict]:- """Assistant message → Converse blocks.-- An ordered ``bedrock_content_blocks`` sidecar is authoritative and replayed- verbatim. Otherwise: redacted thinking from ``reasoning_details`` (so opaque- encrypted reasoning round-trips byte-for-byte), then text, then tool calls.- """+ """Assistant message → Converse blocks. An ordered ``bedrock_content_blocks`` sidecar is+ authoritative; otherwise redacted thinking from ``reasoning_details`` (byte-for-byte+ round-trip), then text, then tool calls."""ordered_blocks = msg.get("bedrock_content_blocks")if isinstance(ordered_blocks, list) and ordered_blocks:content_blocks = _replay_ordered_blocks(ordered_blocks)@@ -671,13 +628,9 @@ def _assistant_blocks(msg: Dict, content) -> List[Dict]:def convert_messages_to_converse(messages: List[Dict]) -> Tuple[Optional[List[Dict]], List[Dict]]:- """OpenAI messages → ``(system_blocks_or_None, converse_messages)``.-- System messages become the system prompt; tool results become ``toolResult``- blocks in a user turn. Converse requires strict user/assistant alternation- with a user turn first and last, so same-role neighbours are merged and- placeholder user turns are inserted at the ends.- """+ """OpenAI messages → ``(system_blocks_or_None, converse_messages)``. Tool results become+ ``toolResult`` user blocks. Converse requires strict user/assistant alternation with a+ user turn first and last: same-role neighbours merge, placeholder user turns pad the ends."""system_blocks: List[Dict] = []converse_msgs: List[Dict] = []@@ -748,12 +701,8 @@ class _ResponseParts:self.reasoning_details.append({"type": "redacted_thinking", "data": encoded})def build(self, ordered_blocks: List[Dict[str, Any]], usage_data: Dict[str, int], stop_reason: str, model: str) -> SimpleNamespace:- """Assemble the OpenAI-shaped response.-- Converse's inputTokens EXCLUDES cache read/write tokens (OpenAI's- prompt_tokens includes them), so they are added back here and the- Anthropic-named cache fields are surfaced for downstream normalize_usage().- """+ """Assemble the OpenAI-shaped response. Converse's inputTokens EXCLUDES cache+ read/write tokens (OpenAI's prompt_tokens includes them), so they are added back."""msg = SimpleNamespace(role="assistant",content="\n".join(self.text_parts) if self.text_parts else None,@@ -782,11 +731,9 @@ class _ResponseParts:def normalize_converse_response(response: Dict) -> SimpleNamespace:- """Bedrock Converse response → OpenAI ``ChatCompletion``-shaped SimpleNamespace.-- Exposes ``.choices[0].message.{content,tool_calls,reasoning_content,- reasoning_details,bedrock_content_blocks}``, ``.choices[0].finish_reason``, ``.usage``.- """+ """Bedrock Converse response → OpenAI ``ChatCompletion``-shaped SimpleNamespace+ (``.choices[0].message.{content,tool_calls,reasoning_content,reasoning_details,+ bedrock_content_blocks}``, ``.choices[0].finish_reason``, ``.usage``)."""parts = _ResponseParts()ordered_blocks = []for block in response.get("output", {}).get("message", {}).get("content", []):@@ -833,15 +780,11 @@ def stream_converse_with_callbacks(on_interrupt_check=None,on_event=None,) -> SimpleNamespace:- """Process a boto3 ``converse_stream()`` response with real-time callbacks.-- ``on_text_delta`` only fires while no toolUse block has been seen (same- semantics as the Anthropic/chat_completions paths). ``on_interrupt_check``- runs per event; True stops streaming. ``on_event`` is a wire-level liveness- signal fired for EVERY event before any branching; its exceptions are- swallowed so it can never abort the stream. Returns the- ``normalize_converse_response()`` shape.- """+ """Process a boto3 ``converse_stream()`` response with callbacks → the+ ``normalize_converse_response()`` shape. ``on_text_delta`` only fires while no toolUse+ block has been seen (as on the Anthropic/chat_completions paths); ``on_interrupt_check``+ True stops streaming; ``on_event`` fires for EVERY event before branching and its+ exceptions are swallowed so a watchdog hook can never abort the stream."""parts = _ResponseParts()stream_blocks: Dict[int, Dict[str, Any]] = {}current_block_index: Optional[int] = None@@ -941,12 +884,10 @@ def build_converse_kwargs() -> Dict[str, Any]:"""Build kwargs for ``bedrock-runtime.converse()`` / ``converse_stream()``.- ``max_tokens=None`` omits ``inferenceConfig.maxTokens`` so Bedrock uses the- model's maximum output (default stays 4096). cachePoint markers go on system,- tools and the second-newest message (so the marker survives as only the tail- grows — mirrors the Anthropic system_and_3 strategy), each only if the model- supports caching and Bedrock has not rejected that placement.- """+ ``max_tokens=None`` omits ``maxTokens`` (model maximum; default stays 4096). cachePoint+ markers go on system, tools and the second-newest message (survives as the tail grows —+ mirrors Anthropic system_and_3), each only if the model supports caching and Bedrock has+ not rejected that placement."""system_prompt, converse_messages = convert_messages_to_converse(messages)cache_enabled = _model_supports_prompt_cache(model)@@ -968,8 +909,7 @@ def build_converse_kwargs(inference_config["stopSequences"] = stop_sequencesconverse_tools = convert_tools_to_converse(tools) if tools else []if converse_tools:- # Non-tool-calling models (e.g. DeepSeek R1) reject toolConfig with a- # ValidationException → retry loop → failure. Strip tools and warn.+ # Non-tool-calling models reject toolConfig (ValidationException → retry loop): strip and warn.if _model_supports_tool_use(model):if cache_here("tools"):converse_tools = converse_tools + [dict(_CACHE_POINT)]@@ -1001,11 +941,8 @@ def call_converse(stop_sequences: Optional[List[str]] = None,guardrail_config: Optional[Dict] = None,) -> SimpleNamespace:- """Non-streaming Converse call → OpenAI-compatible response.-- Retries once without the rejected cachePoint placement; evicts the cached- client on stale-connection errors before re-raising.- """+ """Non-streaming Converse call → OpenAI-compatible response. Retries once without a+ rejected cachePoint placement; evicts the cached client on stale-connection errors."""client = _get_bedrock_runtime_client(region)kwargs = build_converse_kwargs(model, messages, tools, max_tokens, temperature, top_p, stop_sequences, guardrail_config,@@ -1093,13 +1030,8 @@ def _list_inference_profiles(client, filter_set: set, models: List[Dict[str, Anydef discover_bedrock_models(region: str, provider_filter: Optional[List[str]] = None) -> List[Dict[str, Any]]:- """Discover Bedrock foundation models + inference profiles (cached 1h per region/filter).-- Each entry has ``id``, ``name``, ``provider`` ("inference-profile" for- profiles), ``input_modalities``, ``output_modalities``, ``streaming``.- Sorted with ``global.`` cross-region profiles first, then by name.- Returns [] when the client cannot be built.- """+ """Discover foundation models + inference profiles (cached 1h per region/filter), sorted+ ``global.`` profiles first then by name; [] when the client cannot be built."""import timecache_key = f"{region}:{','.join(sorted(provider_filter or []))}"cached = _discovery_cache.get(cache_key)@@ -1132,15 +1064,12 @@ def _extract_provider_from_arn(arn: str) -> str:# --- Bedrock model context lengths ----# Static fallback for when the live probe is unavailable (used by-# agent/model_metadata.py). Keys match by longest substring, so versioned entries-# (opus-4-6/4-7/4-8) win over the generic "anthropic.claude-opus-4".+# Static fallback when the live probe is unavailable (agent/model_metadata.py). Keys match+# by longest substring, so versioned entries win over the generic "anthropic.claude-opus-4".BEDROCK_CONTEXT_LENGTHS: Dict[str, int] = {- # Anthropic Claude. Fable / Sonnet 5 / Opus 4.8-4.6 / Sonnet 4.6 are 1M GA;- # Sonnet 4.5 / Sonnet 4 lost their 1M beta and are 200K; Haiku 4.5 is 200K.- # The 1M entries must match agent/model_metadata.py DEFAULT_CONTEXT_LENGTHS- # or context compresses early.+ # Anthropic Claude: 1M GA vs 200K. The 1M entries must match+ # agent/model_metadata.py DEFAULT_CONTEXT_LENGTHS or context compresses early.**dict.fromkeys(("anthropic.claude-fable-5", "anthropic.claude-fable", "anthropic.claude-sonnet-5","anthropic.claude-opus-4-8", "anthropic.claude-opus-4-7", "anthropic.claude-opus-4-6",@@ -1168,23 +1097,17 @@ BEDROCK_CONTEXT_LENGTHS: Dict[str, int] = {# Default for unknown Bedrock modelsBEDROCK_DEFAULT_CONTEXT_LENGTH = 128_000-# Probe padding targets (tokens). Tiered because a wildly oversized payload (5M-# tokens) yields an opaque InternalServerException instead of a clean-# ValidationException; stepping up discovers 2M+ windows without over-padding.+# Probe padding tiers (tokens): a wildly oversized payload yields an opaque+# InternalServerException instead of a clean ValidationException._BEDROCK_PROBE_TIERS = (1_300_000, 2_200_000)_WORDS_PER_TOKEN = 0.9 # conservative: ensures the padded prompt clears the tierdef probe_bedrock_context_length(model_id: str, region: str) -> Optional[int]:- """Discover a model's real context window by provoking a length error.-- No Bedrock metadata API exposes the window; the only authoritative source is- the ValidationException for an oversized prompt ("prompt is too long: 1300032- tokens > 1000000 maximum"). Length validation happens before inference, so- the probe costs nothing. If a tier is accepted, that tier is returned as a- safe lower bound. Returns None if the probe could not run (no credentials,- network error, no parseable limit) so the caller falls back to the static table.- """+ """Discover a model's real context window by provoking a length error — the only+ authoritative source ("prompt is too long: 1300032 tokens > 1000000 maximum"); length+ validation runs before inference so the probe costs nothing. An accepted tier is+ returned as a safe lower bound; None (no creds / network / unparseable) → static table."""try:from agent.model_metadata import parse_context_limit_from_errorexcept ImportError: # pragma: no cover — same package@@ -1220,13 +1143,9 @@ def probe_bedrock_context_length(model_id: str, region: str) -> Optional[int]:def get_bedrock_context_length(model_id: str, region: str = "", probe: bool = True) -> int:- """Context window: live probe (if ``probe`` and ``region``) → static table → default.-- The static table is a fallback only: AWS ships new versions faster than the- table tracks, and a stale substring match silently caps the window (e.g. a 1M- Opus pinned to 200K via "opus-4"). ``probe=False`` or an empty region skips- the network call for offline/display paths.- """+ """Context window: live probe (if ``probe`` and ``region``) → static table → default. The+ table is fallback only: a stale substring match silently caps the window (a 1M Opus+ pinned to 200K via "opus-4"). ``probe=False`` / empty region skips the network call."""if probe and region:probed = probe_bedrock_context_length(model_id, region)if probed:diff --git a/agent/codex_responses_adapter.py b/agent/codex_responses_adapter.pyindex a1b5ecdb0b9..d71ec7d77ad 100644--- a/agent/codex_responses_adapter.py+++ b/agent/codex_responses_adapter.py@@ -25,12 +25,9 @@ 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 (replaying across endpoints yields HTTP 400- ``invalid_encrypted_content``); stamping items 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`` across endpoints), so+ stamping lets replay drop foreign blobs after a mid-conversation 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@@ -40,13 +37,11 @@ def _classify_responses_issuer(# 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``.+# Codex/Harmony tool-call serialization leaked into assistant text (no structured function_call)._TOOL_CALL_LEAK_PATTERN = re.compile(r"(?:^|[\s>|])to=functions\.[A-Za-z_][\w.]*", re.IGNORECASE)-# The Codex backend rejects requests containing these literal Harmony wire-# tokens (``invalid_prompt: Request blocked.``). Fullwidth bars survive-# format-character stripping while keeping the text legible.+# The Codex backend rejects literal Harmony wire tokens (``invalid_prompt: Request+# blocked.``). Fullwidth bars survive format-character stripping and stay legible._HARMONY_CONTROL_TOKEN_RE = re.compile(r"<\|(start|end|channel|message|constrain|return|call)\|>")_FULLWIDTH_PIPE = "\uff5c"@@ -57,24 +52,21 @@ _ASSISTANT_IMAGE_PLACEHOLDER = "[Assistant image omitted during replay]"_INCOMPLETE_STATUSES = {"queued", "in_progress", "incomplete"}_RESPONSE_MESSAGE_STATUSES = {"completed", "incomplete", "in_progress"}-# 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.+# input[].id / function names longer than this are a non-retryable 400 ("string too+# long"). Codex message ids can run 400+ chars; Hermes ``msg_...`` ids stay under the cap._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 and-# run server-side, reporting via the ``*_call`` output items below. Preflight-# passes them through instead of rejecting them as "unsupported type".+# Provider-executed built-in tools: declared by ``type`` alone, run server-side,+# reported via the ``*_call`` output items below; preflight passes them through._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``, so they must-# NOT flip the incomplete verdict — otherwise every server-search turn burns 3-# fruitless continuation retries.+# Server-side ``*_call`` output items. xAI leaves these ``in_progress`` even when the+# response is ``completed``, so they must NOT flip the incomplete verdict (else every+# server-search turn burns 3 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",@@ -126,9 +118,8 @@ def _neutralize_harmony_tokens(text: str) -> str:replacement = rf"<{_FULLWIDTH_PIPE}\1{_FULLWIDTH_PIPE}>"if not any(unicodedata.category(char) == "Cf" for char in text):return _HARMONY_CONTROL_TOKEN_RE.sub(replacement, text)- # The backend strips Unicode format controls (e.g. U+200B) before its- # reserved-token check, so match on the visible text and rewrite the- # original spans — any Cf-hidden variant is neutralized the same way.+ # The backend strips Unicode format controls (e.g. U+200B) before its reserved-token+ # 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] = []@@ -142,11 +133,8 @@ def _neutralize_harmony_tokens(text: str) -> str:def _neutralize_harmony_structure(value: Any) -> Any:- """Neutralize JSON-like values; normalize tuples to lists.-- A reserved token in an object *key* is rejected rather than rewritten —- renaming a key could desynchronize a tool schema from the executor contract.- """+ """Neutralize JSON-like values (tuples → lists). A reserved token in an object *key* is+ rejected, not rewritten — renaming could desync a tool schema from the executor contract."""if isinstance(value, str):return _neutralize_harmony_tokens(value)if isinstance(value, (list, tuple)):@@ -194,14 +182,11 @@ def _input_image_part(url: str, detail: Any) -> Dict[str, Any]:def _chat_content_to_responses_parts(content: Any, *, role: str = "user") -> List[Dict[str, Any]]:- """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. ``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.- """+ """Chat-style multimodal content → Responses API input parts ([] if not a list).++ Text becomes ``input_text`` (user) or ``output_text`` (assistant) — the API rejects+ the wrong type per role. ``input_image`` is only legal on user messages; on assistant+ messages it becomes a text marker (an assistant ``input_image`` 400s every replay)."""text_type = _text_type_for(role)converted: List[Dict[str, Any]] = []for kind, payload in _iter_content_parts(content if isinstance(content, list) else []):@@ -217,13 +202,9 @@ def _chat_content_to_responses_parts(content: Any, *, role: str = "user") -> Lisdef _summarize_user_message_for_log(content: Any, *, sep: str = " ") -> str:- """Flatten message content to plain text.-- 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. ``""`` for None/empty lists,- ``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/empty, ``str(content)`` for other scalars."""if content is None:return ""if isinstance(content, str):@@ -251,25 +232,19 @@ def _deterministic_call_id(fn_name: str, arguments: str, index: int = 0) -> str: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 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.- """+ """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."""if len(call_id) <= _MAX_RESPONSES_ITEM_ID_LENGTH:return call_idreturn 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 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.- """+ """Coerce a *replayed* ``function_call.name`` to ``^[a-zA-Z0-9_-]{1,64}$`` (an invalid+ stored name 400s every later turn). Invalid runs collapse to ``_``; all-invalid → "fn".+ Apply ONLY to replayed items, never 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):@@ -279,11 +254,8 @@ def _sanitize_replayed_fn_name(name: str) -> str: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.- """+ """Map an ``fc_…`` item id to its canonical ``call_<suffix>``. Both sides of a replayed+ pair must derive the SAME call_id, or an oversized pair clamps to two 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:]}"return None@@ -374,12 +346,9 @@ 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, which- binds ids to a backend connection and 401s on a stale one; ``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_LENGTHreturn _message_item(@@ -393,13 +362,10 @@ def _replay_reasoning_items() -> List[Dict[str, Any]]:"""Replay persisted encrypted reasoning/compaction items for one assistant turn.- Skips: duplicate ids; ``compaction`` checkpoints unless THIS request carries- ``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.- """+ Skips duplicate ids, ``compaction`` checkpoints unless THIS request carries+ ``context_management`` (else a persisted checkpoint erases pre-checkpoint history on a+ model that cannot decrypt it), and items stamped by another issuer (HTTP 400).+ Unstamped legacy items pass. ``id`` (store=False lookups 404) and ``_issuer_kind`` are stripped."""global _CROSS_ISSUER_WARN_EMITTEDcodex_reasoning = msg.get("codex_reasoning_items")if not isinstance(codex_reasoning, list):@@ -506,31 +472,19 @@ def _chat_messages_to_responses_input() -> List[Dict[str, Any]]:"""Convert internal chat-style messages to Responses input items.- ``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 threads False here.-- ``is_github_responses``: drops ``id`` from replayed message items regardless- of length — Copilot binds ids to a backend connection (HTTP 401 on stale).-- ``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``: 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.- """+ ``is_xai_responses``: signature compatibility only (xAI DOES replay encrypted reasoning).+ ``replay_encrypted_reasoning``: per-session kill switch, threaded False by+ ``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 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 provenance-tagged content from the source, since- # the converted item may be a lossy shape that no longer carries it.+ # 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.item_sources: List[Optional[Dict[str, Any]]] = []seen_item_ids: set = set()@@ -571,11 +525,10 @@ def _chat_messages_to_responses_input(if fallback is not None:emit([{"role": "assistant", "content": fallback}], msg)emit(_replay_tool_call_items(msg, start_index=len(items)), msg)- # 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.+ # The server renders nothing placed before a compaction item, so pre-checkpoint+ # history is dead weight and plaintext asks / merged summaries silently vanish. Keep+ # the newest checkpoint first, retain pre-checkpoint USER and SUMMARY messages within+ # a token budget, leave the tail untouched.if not native_compaction_eligible:return itemsfrom agent.native_compaction import prune_pre_checkpoint_items@@ -583,11 +536,8 @@ 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 must call- :func:`classify_responses_route` — inline string comparisons drift.- """+ """Which special Responses-API route an agent is talking to. Single owner of the+ codex/xai/github predicates — every site must call :func:`classify_responses_route`."""is_codex_backend: boolis_xai_responses: bool@@ -595,11 +545,8 @@ class ResponsesRouteFlags(NamedTuple):def classify_responses_route(agent: Any) -> ResponsesRouteFlags:- """Classify the agent's Responses route from provider + base URL.-- Host checks are exact-host-or-subdomain, never substring —- ``https://evil.com/models.github.ai`` must not classify as GitHub.- """+ """Classify the agent's Responses route from provider + base URL. Host checks are+ exact-host-or-subdomain, never substring (``evil.com/models.github.ai`` is not GitHub)."""from utils import base_url_hostnameprovider = getattr(agent, "provider", None)base_url = str(getattr(agent, "base_url", "") or "")@@ -622,13 +569,9 @@ def estimate_native_responses_preflight_tokens(system_prompt: str = "",tools: Optional[List[Dict[str, Any]]] = None,) -> 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. None when native compaction is not proven eligible or- conversion fails — caller falls back to the generic (conservative) estimate.- """+ """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 Noneis_codex_backend, is_xai_responses, is_github_responses = classify_responses_route(agent)@@ -842,8 +785,8 @@ def _preflight_tool(tool: Any, idx: int) -> Dict[str, Any]:}-# Optional scalar request fields, in wire order: (key, accept(value), coerce).-# Values failing ``accept`` are silently dropped (never an error).+# Optional scalar request fields, in wire order: (key, accept(value), coerce). Values+# failing ``accept`` are silently dropped._PREFLIGHT_OPTIONAL_FIELDS: tuple[tuple[str, Callable[[Any], bool], Optional[Callable[[Any], Any]]], ...] = (("reasoning", lambda v: isinstance(v, dict), None),("include", lambda v: isinstance(v, list), None),@@ -937,8 +880,8 @@ def _preflight_codex_api_kwargs(allowed_keys.add("stream")elif "stream" in 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). Gated on the model name because native Codex accepts slashes.+ # Defense-in-depth slash-enum strip for xAI (rejects ``Qwen/Qwen3.5`` 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:@@ -979,8 +922,8 @@ def _extract_responses_reasoning_text(item: Any) -> str:def _format_responses_error(error_obj: Any, response_status: str) -> str:- """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."""+ """``"<code>: <message>"`` for a ``response.error`` payload (dict or object), else whichever+ is present, else ``str(error_obj)``, else 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 ""@@ -1014,8 +957,7 @@ def _response_tool_call(item: Any, item_type: str, index: int) -> SimpleNamespacdef _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`` lets a later model swap detect an endpoint that cannot decrypt the blob."""+ """``{type, encrypted_content[, _issuer_kind]}`` for replay, or None without a blob."""encrypted = getattr(item, "encrypted_content", None)if not _nonempty_str(encrypted):return None@@ -1078,8 +1020,8 @@ class _OutputScan: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.+ # Compaction checkpoints ride the codex_reasoning_items sidecar (persistence,+ # replay, cross-issuer guard and kill switch for free).raw_item = _stamped_encrypted_item(item, "compaction", issuer_kind)if raw_item is not None:self.reasoning_items_raw.append(raw_item)@@ -1100,9 +1042,8 @@ class _OutputScan: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.+ # commentary/analysis text is mid-turn narration, never the final answer: route it+ # to the reasoning channel; the exact item is still preserved for replay/cache.(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(@@ -1113,11 +1054,8 @@ class _OutputScan: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.-- ``issuer_kind`` is stamped onto captured reasoning items so replay can drop- them once the active endpoint differs from the one that minted the blob.- """+ """Normalize a Responses API object to ``(assistant_message, finish_reason)``.+ ``issuer_kind`` is stamped onto captured reasoning items for cross-issuer replay drops."""response_status = _lower_or_none(getattr(response, "status", None))incomplete_reason = _field(getattr(response, "incomplete_details", None), "reason", "")response_incomplete_content_filter = (@@ -1125,8 +1063,7 @@ def _normalize_codex_response(response: Any, *, issuer_kind: Optional[str] = Non)output = getattr(response, "output", None)if not isinstance(output, list) or not output:- # Codex can deliver the whole answer via stream events and return an- # empty output; fall back to output_text before raising.+ # 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(@@ -1135,8 +1072,7 @@ 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: an empty- # message makes finish_reason content_filter instead of burning continuations.+ # Provider safety block, not a partial answer: finish content_filter, not incomplete.output = [_synthetic_message([])]else:raise RuntimeError("Responses API returned no output items")@@ -1150,11 +1086,9 @@ def _normalize_codex_response(response: Any, *, issuer_kind: Optional[str] = Nonif 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}``) 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).+ # 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.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(@@ -1163,11 +1097,9 @@ def _normalize_codex_response(response: Any, *, issuer_kind: Optional[str] = Non"Leaked snippet: %r", final_text[:300],)final_text = ""- # 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.+ # 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.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>")@@ -1201,9 +1133,8 @@ def _normalize_codex_response(response: Any, *, issuer_kind: Optional[str] = Non):finish_reason = "incomplete"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 —+ # 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.trusted_final = (response_status == "completed" and issuer_kind not in ("codex_backend", "xai_responses", "github_responses")