The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
perf(prompt-caching): preserve tool-loop cache boundaries (#20880)
Rod Boev9fc12bf7a4bc
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex a8a55fc57a8..2aba754b5fd 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -1840,6 +1840,23 @@ def dump_api_request_debug(+def _direct_native_anthropic_tool_cache_capability(+ agent,+ *,+ provider: Optional[str] = None,+ base_url: Optional[str] = None,+ api_mode: Optional[str] = None,+ model: Optional[str] = None,+) -> bool:+ """Return whether this resolved destination accepts native tool markers."""+ eff_base_url = base_url if base_url is not None else (agent.base_url or "")+ eff_api_mode = api_mode if api_mode is not None else (agent.api_mode or "")+ return (+ eff_api_mode == "anthropic_messages"+ and base_url_hostname(eff_base_url) == "api.anthropic.com"+ )++def anthropic_prompt_cache_policy(agent,*,diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 88b206be7c3..9d26d1bf611 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -42,6 +42,7 @@ Payment / credit exhaustion fallback:import contextlibimport contextvars+import copyimport functoolsimport hashlibimport inspect@@ -54,7 +55,7 @@ import timeimport uuidfrom pathlib import Path # noqa: F401 — used by test mocksfrom types import SimpleNamespace-from typing import Any, Callable, Dict, List, Optional, Tuple, TYPE_CHECKING+from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, TYPE_CHECKINGfrom urllib.parse import urlparse, parse_qs, urlunparse# NOTE: `from openai import OpenAI` is deliberately NOT at module top — the@@ -4214,6 +4215,133 @@ def _fallback_entry_timeout(task: Optional[str], fb_label: str) -> Optional[floareturn None+def _fallback_provider_from_label(label: str) -> str:+ """Recover the provider identifier from a fallback display label."""+ match = re.match(r"(?:fallback_chain\[\d+\]|main-agent)\(([^)]+)\)$", label or "")+ return match.group(1).strip() if match else str(label or "").strip()+++class _FallbackDestination(NamedTuple):+ provider: str+ base_url: str+ api_mode: Optional[str]+ model: Optional[str]+++def _complete_fallback_destination(+ provider: str,+ base_url: str,+ api_mode: Optional[str],+ model: Optional[str],+) -> _FallbackDestination:+ if not api_mode:+ if _endpoint_speaks_anthropic_messages(base_url):+ api_mode = "anthropic_messages"+ else:+ try:+ from hermes_cli.runtime_provider import resolve_runtime_provider++ runtime = resolve_runtime_provider(+ requested=provider,+ explicit_base_url=base_url or None,+ target_model=model or "",+ )+ api_mode = str(runtime.get("api_mode") or "").strip() or None+ except Exception:+ pass+ return _FallbackDestination(provider, base_url, api_mode, model)+++def _fallback_destination_from_entry(+ entry: Dict[str, Any],+ fb_client: Any,+ fb_model: Optional[str],+) -> _FallbackDestination:+ provider = str(entry.get("provider") or "").strip()+ base_url = str(+ entry.get("base_url") or getattr(fb_client, "base_url", "") or ""+ ).strip()+ api_mode = str(+ entry.get("api_mode") or entry.get("transport") or ""+ ).strip() or None+ model = fb_model or str(entry.get("model") or "").strip() or None+ return _complete_fallback_destination(provider, base_url, api_mode, model)+++def _fallback_destination(+ task: Optional[str],+ fb_client: Any,+ fb_model: Optional[str],+ fb_label: str,+) -> _FallbackDestination:+ """Return the resolved route identity used by a fallback request."""+ attached = getattr(fb_client, "_hermes_fallback_destination", None)+ if isinstance(attached, _FallbackDestination):+ return attached++ provider = _fallback_provider_from_label(fb_label)+ base_url = str(getattr(fb_client, "base_url", "") or "")+ api_mode = None+ model = fb_model++ match = re.match(r"fallback_chain\[(\d+)\]", fb_label or "")+ if match and task:+ try:+ chain = _get_auxiliary_task_config(task).get("fallback_chain")+ entry = chain[int(match.group(1))] if isinstance(chain, list) else None+ except Exception:+ entry = None+ if isinstance(entry, dict):+ return _fallback_destination_from_entry(entry, fb_client, fb_model)++ return _complete_fallback_destination(provider, base_url, api_mode, model)+++def _replan_synchronous_cache_sections(+ messages: list,+ tools: Optional[list],+ *,+ destination: _FallbackDestination,+) -> tuple[list, list]:+ """Strip source decoration and plan one synchronous destination locally."""+ from agent.agent_runtime_helpers import (+ _direct_native_anthropic_tool_cache_capability,+ anthropic_prompt_cache_policy,+ )+ from agent.prompt_caching import (+ build_prompt_cache_plan,+ strip_anthropic_cache_control,+ strip_anthropic_tool_cache_control,+ )++ canonical_messages = copy.deepcopy(messages or [])+ strip_anthropic_cache_control(canonical_messages)+ canonical_tools = strip_anthropic_tool_cache_control(tools)+ stub = SimpleNamespace(provider="", base_url="", api_mode="", model="")+ should_cache, native_layout = anthropic_prompt_cache_policy(+ stub,+ provider=destination.provider,+ base_url=destination.base_url,+ api_mode=destination.api_mode or "",+ model=destination.model or "",+ )+ if not should_cache:+ return canonical_messages, canonical_tools+ plan = build_prompt_cache_plan(+ canonical_messages,+ canonical_tools,+ native_anthropic=native_layout,+ direct_native_tool_cache=_direct_native_anthropic_tool_cache_capability(+ stub,+ provider=destination.provider,+ base_url=destination.base_url,+ api_mode=destination.api_mode or "",+ model=destination.model or "",+ ),+ )+ return plan.messages, plan.tools++def _call_fallback_candidate_sync(fb_client: Any,fb_model: Optional[str],@@ -4256,36 +4384,70 @@ def _call_fallback_candidate_sync(task or "call", fb_label, fb_timeout, effective_timeout,)effective_timeout = fb_timeout- fb_base = str(getattr(fb_client, "base_url", "") or "")+ destination = _fallback_destination(task, fb_client, fb_model, fb_label)+ fallback_messages, fallback_tools = _replan_synchronous_cache_sections(+ messages,+ tools,+ destination=destination,+ )fb_kwargs = _build_call_kwargs(- fb_label, fb_model, messages,+ destination.provider, destination.model, fallback_messages,temperature=temperature, max_tokens=max_tokens,- tools=tools, timeout=effective_timeout,+ tools=fallback_tools, timeout=effective_timeout,extra_body=effective_extra_body, reasoning_config=reasoning_config,- base_url=fb_base, task=task)+ base_url=destination.base_url, task=task)try:return _validate_llm_response(- _relay_sync_completion(fb_client, fb_kwargs, provider=fb_label), task)+ _relay_sync_completion(+ fb_client,+ fb_kwargs,+ provider=destination.provider,+ api_mode=destination.api_mode,+ ),+ task,+ )except Exception as fb_err:if not _is_auth_error(fb_err):raise- fb_provider = _auth_refresh_provider_for_route(fb_label, fb_base)+ fb_provider = _auth_refresh_provider_for_route(+ destination.provider, destination.base_url+ )if fb_provider not in {"auto", "", None} and _refresh_provider_credentials(fb_provider):- retry_client, retry_model = _get_cached_client(fb_provider, fb_model)+ retry_client, retry_model = _get_cached_client(+ fb_provider,+ destination.model,+ base_url=destination.base_url or None,+ api_mode=destination.api_mode,+ )if retry_client is not None:+ retry_destination = _FallbackDestination(+ fb_provider,+ destination.base_url+ or str(getattr(retry_client, "base_url", "") or ""),+ destination.api_mode,+ retry_model or destination.model,+ )+ retry_messages, retry_tools = _replan_synchronous_cache_sections(+ messages,+ tools,+ destination=retry_destination,+ )retry_kwargs = _build_call_kwargs(- fb_provider, retry_model or fb_model, messages,+ retry_destination.provider,+ retry_destination.model,+ retry_messages,temperature=temperature, max_tokens=max_tokens,- tools=tools, timeout=effective_timeout,+ tools=retry_tools, timeout=effective_timeout,extra_body=effective_extra_body,reasoning_config=reasoning_config,- base_url=str(getattr(retry_client, "base_url", "") or fb_base), task=task)+ base_url=retry_destination.base_url, task=task)try:return _validate_llm_response(_relay_sync_completion(retry_client,retry_kwargs,- provider=fb_provider,+ provider=retry_destination.provider,+ api_mode=retry_destination.api_mode,),task,)@@ -4761,13 +4923,21 @@ def _resolve_fallback_entry(entry: Dict[str, Any]) -> Tuple[Optional[Any], Optiobase_url = str(entry.get("base_url") or "").strip() or Noneapi_key = _fallback_entry_api_key(entry)api_mode = str(entry.get("api_mode") or entry.get("transport") or "").strip() or None- return resolve_provider_client(+ client, resolved_model = resolve_provider_client(provider,model=model,explicit_base_url=base_url,explicit_api_key=api_key,api_mode=api_mode,)+ if client is not None:+ try:+ client._hermes_fallback_destination = _fallback_destination_from_entry(+ entry, client, resolved_model+ )+ except Exception:+ pass+ return client, resolved_modeldef _try_main_fallback_chain(diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex a025f58f5a2..e40333f0e60 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -1120,9 +1120,10 @@ def interruptible_api_call(agent, api_kwargs: dict):-def build_api_kwargs(agent, api_messages: list) -> dict:+def build_api_kwargs(agent, api_messages: list, tools_for_api: list | None = None) -> dict:"""Build the keyword arguments dict for the active API mode."""- tools_for_api = agent.tools+ if tools_for_api is None:+ tools_for_api = agent.toolsif agent.api_mode == "anthropic_messages":_transport = agent._get_transport()diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 9da3b3e2d5f..b7e3f9afc1c 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -70,8 +70,9 @@ from agent.model_metadata import ()from agent.process_bootstrap import _install_safe_stdiofrom agent.prompt_caching import (- apply_anthropic_cache_control,+ build_prompt_cache_plan,strip_anthropic_cache_control,+ strip_anthropic_tool_cache_control,)from agent.retry_utils import (adaptive_rate_limit_backoff,@@ -941,7 +942,8 @@ def _redecorate_prompt_cache_for_provider(*,system_message=None,moa_prepared: Optional[Dict[str, Any]] = None,-) -> tuple[List[Dict[str, Any]], Optional[Dict[str, Any]]]:+ tools_for_api: Optional[List[Dict[str, Any]]] = None,+) -> tuple[List[Dict[str, Any]], Optional[Dict[str, Any]]] | tuple[List[Dict[str, Any]], Optional[Dict[str, Any]], List[Dict[str, Any]]]:"""Strip and re-apply cache_control for the *current* provider policy.Decoration runs once per call block before the retry loop for the primary@@ -951,10 +953,9 @@ def _redecorate_prompt_cache_for_provider(by reshaping at the top of each retry attempt.The source list is the mutated in-flight request (image shrink / ASCII /- reasoning_details recoveries already applied) — never a pristine- pre-decoration snapshot. MoA guidance is peeled, the base is redecorated,- then ``rebase_prepared_request`` re-attaches guidance outside the cached- span.+ reasoning_details recoveries already applied), never a pristine+ pre-decoration snapshot. MoA guidance is peeled and rebased without+ decoration; the acting aggregator plans its resolved destination later."""messages: List[Dict[str, Any]] = [dict(m) if isinstance(m, dict) else m for m in (api_messages or [])@@ -965,6 +966,21 @@ def _redecorate_prompt_cache_for_provider(messages = _peel_moa_guidance(messages, guidance)strip_anthropic_cache_control(messages)+ planned_tools = strip_anthropic_tool_cache_control(+ tools_for_api if tools_for_api is not None else getattr(agent, "tools", [])+ )++ if prepared is not None and getattr(agent, "provider", None) == "moa":+ # Prepared MoA state is canonical: the synchronous acting-aggregator+ # sender owns its destination-local cache plan after it resolves the slot.+ completions = getattr(getattr(agent.client, "chat", None), "completions", None)+ rebase = getattr(completions, "rebase_prepared_request", None)+ if callable(rebase):+ prepared = rebase(prepared, messages)+ messages = prepared["messages"]+ if tools_for_api is None:+ return messages, prepared+ return messages, prepared, planned_tools# Direct attribute access matches the call-block decoration site — the# flags are unconditionally initialized on AIAgent, and a getattr@@ -972,31 +988,25 @@ def _redecorate_prompt_cache_for_provider(if agent._use_prompt_caching:_ensure_cached_system_prompt_static(agent, system_message=system_message)static = getattr(agent, "_cached_system_prompt_static", None)- messages = apply_anthropic_cache_control(+ direct_tool_cache = getattr(+ agent,+ "_direct_native_anthropic_tool_cache_capability",+ lambda: False,+ )()+ plan = build_prompt_cache_plan(messages,+ planned_tools,cache_ttl=agent._cache_ttl,native_anthropic=agent._use_native_cache_layout,static_system_prefix=static if isinstance(static, str) else None,+ direct_native_tool_cache=direct_tool_cache,)+ messages = plan.messages+ planned_tools = plan.tools- if (- prepared is not None- and getattr(agent, "provider", None) == "moa"- ):- # No `and guidance` here: guidance=None is a real prepared shape- # (all-references-failed / silent degraded policy builds the- # prepared request without attaching guidance), and the MoA facade- # sends prepared["messages"] — not api_kwargs["messages"] — so the- # rebase must refresh the prepared object even when there is no- # guidance to re-attach. rebase_prepared_request handles falsy- # guidance by copying the messages and skipping the attach.- completions = getattr(getattr(agent.client, "chat", None), "completions", None)- rebase = getattr(completions, "rebase_prepared_request", None)- if callable(rebase):- prepared = rebase(prepared, messages)- messages = prepared["messages"]-- return messages, prepared+ if tools_for_api is None:+ return messages, prepared+ return messages, prepared, planned_toolsdef _apply_context_engine_selection(@@ -1748,12 +1758,8 @@ def run_conversation(# regardless of ordering (a single-space pad here previously had to# be sequenced after normalization to survive, forking the concept).- # Apply Anthropic prompt caching for Claude models on native- # Anthropic, OpenRouter, and third-party Anthropic-compatible- # gateways. Auto-detected: if ``_use_prompt_caching`` is set, inject- # cache_control breakpoints for the static system prefix, full system- # prompt, and last two messages (or the legacy system-and-3 layout- # when no static prefix is available).+ # Build the request-local cache sections only after every transcript+ # mutation. The canonical tool registry stays undecorated.## Runs LAST, after every message mutation above. Marking earlier# defeats the prefix stability the mutations exist to create:@@ -1768,10 +1774,12 @@ def run_conversation(# exactly the point the breakpoints were meant to protect. Marking# last also keeps breakpoints off messages that the orphan sweep or# the thinking-only drop is about to remove or merge away.- if agent._use_prompt_caching:+ tools_for_api = agent.tools+ if agent._use_prompt_caching and agent.provider != "moa":_static_system_prefix = getattr(agent, "_cached_system_prompt_static", None)- api_messages = apply_anthropic_cache_control(+ _initial_cache_plan = build_prompt_cache_plan(api_messages,+ tools_for_api,cache_ttl=agent._cache_ttl,native_anthropic=agent._use_native_cache_layout,static_system_prefix=(@@ -1779,7 +1787,10 @@ def run_conversation(if isinstance(_static_system_prefix, str)else None),+ direct_native_tool_cache=agent._direct_native_anthropic_tool_cache_capability(),)+ api_messages = _initial_cache_plan.messages+ tools_for_api = _initial_cache_plan.tools# Build a persistent-MoA request before measuring compression pressure.# MoA reference output is injected into the aggregator prompt, but it@@ -2115,15 +2126,22 @@ def run_conversation(# fallback refreshes the policy flags, but the decorated list# still carries the primary's breakpoints (or none). Strip and# re-render for the current provider before building kwargs.- api_messages, _moa_prepared_request = (+ api_messages, _moa_prepared_request, tools_for_api = (_redecorate_prompt_cache_for_provider(agent,api_messages,system_message=system_message,moa_prepared=_moa_prepared_request,+ tools_for_api=tools_for_api,))- api_kwargs = agent._build_api_kwargs(api_messages)+ if tools_for_api == agent.tools:+ api_kwargs = agent._build_api_kwargs(api_messages)+ else:+ api_kwargs = agent._build_api_kwargs(+ api_messages,+ tools_for_api=tools_for_api,+ )if agent._force_ascii_payload:_sanitize_structure_non_ascii(api_kwargs)if agent.api_mode == "codex_responses":diff --git a/agent/moa_loop.py b/agent/moa_loop.pyindex 42d0c29bca5..671827e7fd8 100644--- a/agent/moa_loop.py+++ b/agent/moa_loop.py@@ -8,6 +8,7 @@ iteration.from __future__ import annotations+import copyimport hashlibimport loggingimport re@@ -1657,6 +1658,59 @@ class MoAChatCompletions:max_tokens: Any = agg_kwargs.get("max_tokens")tools: Any = agg_kwargs.get("tools")extra_body: Any = agg_kwargs.get("extra_body")+ agg_runtime = _slot_runtime(aggregator)+ try:+ from types import SimpleNamespace++ from agent.agent_runtime_helpers import (+ _direct_native_anthropic_tool_cache_capability,+ anthropic_prompt_cache_policy,+ )+ from agent.prompt_caching import (+ build_prompt_cache_plan,+ strip_anthropic_cache_control,+ strip_anthropic_tool_cache_control,+ )++ guidance = prepared.get("guidance")+ canonical_messages = copy.deepcopy(agg_messages)+ if guidance:+ canonical_messages = peel_reference_guidance(+ canonical_messages,+ str(guidance),+ )+ strip_anthropic_cache_control(canonical_messages)+ canonical_tools = strip_anthropic_tool_cache_control(tools)+ cache_stub = SimpleNamespace(provider="", base_url="", api_mode="", model="")+ should_cache, native_layout = anthropic_prompt_cache_policy(+ cache_stub,+ provider=agg_runtime.get("provider") or "",+ base_url=agg_runtime.get("base_url") or "",+ api_mode=agg_runtime.get("api_mode") or "",+ model=agg_runtime.get("model") or "",+ )+ if should_cache:+ plan = build_prompt_cache_plan(+ canonical_messages,+ canonical_tools,+ native_anthropic=native_layout,+ direct_native_tool_cache=_direct_native_anthropic_tool_cache_capability(+ cache_stub,+ provider=agg_runtime.get("provider") or "",+ base_url=agg_runtime.get("base_url") or "",+ api_mode=agg_runtime.get("api_mode") or "",+ model=agg_runtime.get("model") or "",+ ),+ )+ agg_messages = plan.messages+ tools = plan.tools+ else:+ agg_messages = canonical_messages+ tools = canonical_tools+ if guidance:+ _attach_reference_guidance(agg_messages, str(guidance))+ except Exception as exc: # pragma: no cover - cache planning must not block MoA+ logger.debug("MoA aggregator cache plan skipped: %s", exc)# Record the exact aggregator INPUT (incl. the injected reference# context) into the pending trace so a trace captures what the# aggregator actually saw, not a reconstruction. Traces are a@@ -1697,7 +1751,6 @@ class MoAChatCompletions:# actually governs the aggregator stream, not just call_llm's default.if api_kwargs.get("timeout") is not None:stream_kwargs["timeout"] = api_kwargs["timeout"]- agg_runtime = _slot_runtime(aggregator)# _slot_runtime may carry the provider's request_overrides.extra_body;# pop it and merge with the caller's extra_body (caller wins) so the# explicit kwarg below never collides with **agg_runtime.diff --git a/agent/prompt_caching.py b/agent/prompt_caching.pyindex 1a0326c79df..719bd58e4af 100644--- a/agent/prompt_caching.py+++ b/agent/prompt_caching.py@@ -11,9 +11,19 @@ Pure functions -- no class state, no AIAgent dependency."""import copy+from dataclasses import dataclassfrom typing import Any, Dict, List+@dataclass(frozen=True)+class PromptCachePlan:+ """Request-local message and tool sections with their cache markers."""++ messages: List[Dict[str, Any]]+ tools: List[Dict[str, Any]]+ marker_count: int++def _apply_cache_marker(msg: dict, cache_marker: dict, native_anthropic: bool = False) -> None:"""Add cache_control to a single message, handling all format variations."""role = msg.get("role", "")@@ -172,6 +182,152 @@ def strip_anthropic_cache_control(return api_messages+def strip_anthropic_tool_cache_control(tools: List[Dict[str, Any]] | None) -> List[Dict[str, Any]]:+ """Return copied tools without request-local Anthropic cache markers."""+ cleaned = copy.deepcopy(tools or [])+ for tool in cleaned:+ if isinstance(tool, dict):+ tool.pop("cache_control", None)+ return cleaned+++def _count_cache_markers(messages: List[Dict[str, Any]], tools: List[Dict[str, Any]]) -> int:+ """Count the wire-visible cache markers in a request-local plan."""+ count = sum(+ 1+ for message in messages+ if isinstance(message, dict) and "cache_control" in message+ )+ count += sum(+ 1+ for message in messages+ if isinstance(message, dict) and isinstance(message.get("content"), list)+ for part in message["content"]+ if isinstance(part, dict) and "cache_control" in part+ )+ return count + sum(+ 1 for tool in tools if isinstance(tool, dict) and "cache_control" in tool+ )+++def _completed_transaction_endpoint_indexes(+ messages: List[Dict[str, Any]], *, native_anthropic: bool,+) -> List[int]:+ """Select legal ends of completed tool runs and ordinary turns."""+ endpoints: List[int] = []+ index = 0+ while index < len(messages):+ message = messages[index]+ if not isinstance(message, dict) or message.get("role") == "system":+ index += 1+ continue++ if message.get("role") == "assistant" and message.get("tool_calls"):+ result_start = index + 1+ result_end = result_start+ while result_end < len(messages):+ result = messages[result_end]+ if not isinstance(result, dict) or result.get("role") != "tool":+ break+ result_end += 1+ if result_end > result_start:+ endpoint = result_end - 1+ if _can_carry_marker(messages[endpoint], native_anthropic):+ endpoints.append(endpoint)+ index = result_end+ continue++ if message.get("role") == "tool":+ while index < len(messages):+ result = messages[index]+ if not isinstance(result, dict) or result.get("role") != "tool":+ break+ index += 1+ continue++ if message.get("role") == "user" and index + 1 < len(messages):+ index += 1+ continue++ if (+ message.get("role") == "assistant"+ and message.get("content") in (None, "")+ ):+ index += 1+ continue++ if _can_carry_marker(message, native_anthropic):+ endpoints.append(index)+ index += 1+ return endpoints+++def _apply_static_prefix_marker(+ messages: List[Dict[str, Any]],+ cache_marker: Dict[str, str],+ static_system_prefix: str | None,+) -> None:+ """Mark only the reusable static system prefix for a tool-cache plan."""+ if not messages or not isinstance(static_system_prefix, str) or not static_system_prefix:+ return+ system = messages[0]+ if not isinstance(system, dict):+ return+ content = system.get("content")+ if system.get("role") != "system" or not isinstance(content, str):+ return+ if not content.startswith(static_system_prefix):+ return+ suffix = content[len(static_system_prefix):]+ system["content"] = [+ {"type": "text", "text": static_system_prefix, "cache_control": cache_marker},+ {"type": "text", "text": suffix},+ ]+++def build_prompt_cache_plan(+ api_messages: List[Dict[str, Any]],+ tools: List[Dict[str, Any]] | None,+ *,+ cache_ttl: str = "5m",+ native_anthropic: bool = False,+ static_system_prefix: str | None = None,+ direct_native_tool_cache: bool = False,+) -> PromptCachePlan:+ """Build isolated cache sections for one resolved request destination."""+ messages = copy.deepcopy(api_messages or [])+ strip_anthropic_cache_control(messages)+ planned_tools = strip_anthropic_tool_cache_control(tools)++ if not direct_native_tool_cache or not planned_tools:+ planned_messages = apply_anthropic_cache_control(+ messages,+ cache_ttl=cache_ttl,+ native_anthropic=native_anthropic,+ static_system_prefix=static_system_prefix,+ )+ return PromptCachePlan(+ messages=planned_messages,+ tools=planned_tools,+ marker_count=_count_cache_markers(planned_messages, planned_tools),+ )++ marker = _build_marker(cache_ttl)+ _apply_static_prefix_marker(messages, marker, static_system_prefix)+ planned_tools[-1]["cache_control"] = dict(marker)+ for endpoint in _completed_transaction_endpoint_indexes(+ messages,+ native_anthropic=True,+ )[-2:]:+ _apply_cache_marker(messages[endpoint], marker, native_anthropic=True)++ return PromptCachePlan(+ messages=messages,+ tools=planned_tools,+ marker_count=_count_cache_markers(messages, planned_tools),+ )++def apply_anthropic_cache_control(api_messages: List[Dict[str, Any]],cache_ttl: str = "5m",diff --git a/run_agent.py b/run_agent.pyindex aef9faf2068..9a654292598 100644--- a/run_agent.py+++ b/run_agent.py@@ -1521,6 +1521,24 @@ class AIAgent:from agent.agent_runtime_helpers import anthropic_prompt_cache_policyreturn anthropic_prompt_cache_policy(self, provider=provider, base_url=base_url, api_mode=api_mode, model=model)+ def _direct_native_anthropic_tool_cache_capability(+ self,+ *,+ provider: Optional[str] = None,+ base_url: Optional[str] = None,+ api_mode: Optional[str] = None,+ model: Optional[str] = None,+ ) -> bool:+ """Forwarder for the request-local native Anthropic tool capability."""+ from agent.agent_runtime_helpers import _direct_native_anthropic_tool_cache_capability+ return _direct_native_anthropic_tool_cache_capability(+ self,+ provider=provider,+ base_url=base_url,+ api_mode=api_mode,+ model=model,+ )+@staticmethoddef _model_requires_responses_api(model: str) -> bool:"""Return True for models that require the Responses API path.@@ -6551,10 +6569,10 @@ class AIAgent:content[-1]["cache_control"] = {"type": "ephemeral"}break- def _build_api_kwargs(self, api_messages: list) -> dict:+ def _build_api_kwargs(self, api_messages: list, tools_for_api: Optional[list] = None) -> dict:"""Forwarder — see ``agent.chat_completion_helpers.build_api_kwargs``."""from agent.chat_completion_helpers import build_api_kwargs- return build_api_kwargs(self, api_messages)+ return build_api_kwargs(self, api_messages, tools_for_api=tools_for_api)def _supports_reasoning_extra_body(self) -> bool:"""Return True when reasoning extra_body is safe to send for this route/model.diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.pyindex 73558302b66..0e60ea3dd70 100644--- a/tests/agent/test_auxiliary_client.py+++ b/tests/agent/test_auxiliary_client.py@@ -4120,3 +4120,96 @@ class TestMoaAggregatorStreamingBypass:assert result is completeddirect_create.assert_called_once()relay_stream.assert_not_called()+++class TestSynchronousFallbackCachePlans:+ @staticmethod+ def _run_configured_fallback(monkeypatch, entry):+ from agent.auxiliary_client import (+ _call_fallback_candidate_sync,+ _try_configured_fallback_chain,+ )++ client = MagicMock()+ client.base_url = entry["base_url"]+ client.chat.completions.create.return_value = _DummyResponse()+ resolved_calls = []++ def resolve(provider, model=None, **kwargs):+ resolved_calls.append((provider, model, kwargs))+ return client, model++ monkeypatch.setattr("agent.auxiliary_client.resolve_provider_client", resolve)+ monkeypatch.setattr(+ "agent.auxiliary_client._get_auxiliary_task_config",+ lambda task: {"fallback_chain": [entry]},+ )+ fallback_client, fallback_model, label = _try_configured_fallback_chain(+ task="moa_aggregator",+ failed_provider="primary",+ )+ tools = [{+ "type": "function",+ "function": {+ "name": "lookup",+ "parameters": {"type": "object", "properties": {}},+ },+ }]+ _call_fallback_candidate_sync(+ fallback_client,+ fallback_model,+ label,+ task="moa_aggregator",+ messages=[+ {"role": "system", "content": "stable prefix"},+ {"role": "user", "content": "lookup"},+ ],+ temperature=None,+ max_tokens=None,+ tools=tools,+ effective_timeout=30.0,+ effective_extra_body={},+ reasoning_config=None,+ )+ return client, resolved_calls, tools++ def test_direct_anthropic_fallback_uses_entry_destination_for_tool_marker(self, monkeypatch):+ client, resolved_calls, tools = self._run_configured_fallback(monkeypatch, {+ "provider": "anthropic",+ "model": "claude-sonnet-4-6",+ "base_url": "https://api.anthropic.com",+ "api_mode": "anthropic_messages",+ })++ assert resolved_calls == [(+ "anthropic",+ "claude-sonnet-4-6",+ {+ "explicit_base_url": "https://api.anthropic.com",+ "explicit_api_key": None,+ "api_mode": "anthropic_messages",+ },+ )]+ wire_tools = client.chat.completions.create.call_args.kwargs["tools"]+ assert "cache_control" in wire_tools[-1]+ assert "cache_control" not in tools[-1]++ def test_third_party_anthropic_fallback_keeps_message_markers_without_tool_marker(self, monkeypatch):+ client, resolved_calls, tools = self._run_configured_fallback(monkeypatch, {+ "provider": "custom",+ "model": "claude-sonnet-4-6",+ "base_url": "https://api.minimax.io/anthropic",+ "api_mode": "anthropic_messages",+ })++ assert resolved_calls[0][2]["explicit_base_url"] == "https://api.minimax.io/anthropic"+ assert resolved_calls[0][2]["api_mode"] == "anthropic_messages"+ wire_request = client.chat.completions.create.call_args.kwargs+ assert "cache_control" not in wire_request["tools"][-1]+ assert "cache_control" not in tools[-1]+ assert any(+ isinstance(part, dict) and "cache_control" in part+ for message in wire_request["messages"]+ for part in (message.get("content") if isinstance(message.get("content"), list) else [])+ )+diff --git a/tests/agent/test_failover_identity.py b/tests/agent/test_failover_identity.pyindex 48d33b64b85..0a7d0af828b 100644--- a/tests/agent/test_failover_identity.py+++ b/tests/agent/test_failover_identity.py@@ -58,6 +58,8 @@ def _cache_agent(static=None,cache_ttl="5m",provider="openai",+ tools=None,+ direct_tool_cache=False,):return SimpleNamespace(_cached_system_prompt=prompt,@@ -67,6 +69,8 @@ def _cache_agent(_use_native_cache_layout=native,_cache_ttl=cache_ttl,provider=provider,+ tools=tools or [],+ _direct_native_anthropic_tool_cache_capability=lambda: direct_tool_cache,client=None,)@@ -212,6 +216,46 @@ class TestRedecoratePromptCacheOnPolicyChange:assert isinstance(decorated[0]["content"], list)assert decorated[0]["content"][0]["text"] == self._STATIC+ def test_replans_tools_for_the_active_destination(self):+ from agent.prompt_caching import build_prompt_cache_plan++ tools = [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object", "properties": {}}}}]+ messages = [+ {"role": "system", "content": self._STATIC + "volatile"},+ {"role": "user", "content": "lookup"},+ ]+ source = build_prompt_cache_plan(+ messages,+ tools,+ native_anthropic=True,+ static_system_prefix=self._STATIC,+ direct_native_tool_cache=True,+ )+ agent = _cache_agent(+ use_caching=True,+ native=False,+ prompt=messages[0]["content"],+ static=self._STATIC,+ provider="openrouter",+ tools=tools,+ direct_tool_cache=False,+ )++ fallback_messages, _, fallback_tools = _redecorate_prompt_cache_for_provider(+ agent,+ source.messages,+ tools_for_api=source.tools,+ )++ assert "cache_control" in source.tools[-1]+ assert "cache_control" not in fallback_tools[-1]+ assert "cache_control" not in tools[-1]+ assert all(+ part.get("cache_control")+ for part in fallback_messages[0]["content"]+ if isinstance(part, dict)+ )+diff --git a/tests/agent/test_moa_aggregator_cache_control.py b/tests/agent/test_moa_aggregator_cache_control.pyindex 0c7baf441f1..544a7390ff9 100644--- a/tests/agent/test_moa_aggregator_cache_control.py+++ b/tests/agent/test_moa_aggregator_cache_control.py@@ -15,6 +15,7 @@ even when the resolved aggregator slot is a cache-honoring route.from __future__ import annotations+import copyfrom types import SimpleNamespaceimport pytest@@ -112,3 +113,41 @@ def test_aggregator_synthesis_untouched_on_non_caching_route(agg_kwargs = _aggregator_kwargs(captured_calls)synth_message = agg_kwargs["messages"][0]assert isinstance(synth_message["content"], str), "must stay undecorated (plain string content)"+++def test_prepared_aggregator_plans_tools_without_decorating_prepared_state(monkeypatch):+ from agent import moa_loop++ calls = []+ monkeypatch.setattr(moa_loop, "call_llm", lambda **kwargs: calls.append(kwargs) or _response())+ monkeypatch.setattr(+ moa_loop,+ "_slot_runtime",+ lambda slot: {+ "provider": "anthropic",+ "model": "claude-sonnet-4-6",+ "base_url": "https://api.anthropic.com",+ "api_mode": "anthropic_messages",+ },+ )+ completions = moa_loop.MoAChatCompletions.__new__(moa_loop.MoAChatCompletions)+ completions._pending_trace = None+ prepared = {+ "messages": [+ {"role": "system", "content": "system"},+ {"role": "user", "content": "lookup"},+ {"role": "assistant", "content": "", "tool_calls": [{"id": "lookup", "function": {"name": "lookup", "arguments": "{}"}}]},+ {"role": "tool", "tool_call_id": "lookup", "content": "result"},+ ],+ "guidance": None,+ "aggregator": {"provider": "anthropic", "model": "claude-sonnet-4-6"},+ "aggregator_temperature": None,+ }+ canonical_prepared = copy.deepcopy(prepared)+ tools = [{"type": "function", "function": {"name": "lookup", "parameters": {"type": "object", "properties": {}}}}]++ completions._call_prepared_aggregator(prepared, {"tools": tools})++ assert "cache_control" in calls[0]["tools"][-1]+ assert "cache_control" not in tools[-1]+ assert prepared == canonical_prepareddiff --git a/tests/agent/test_prompt_caching.py b/tests/agent/test_prompt_caching.pyindex 3a8197c6ee1..d67adffc0b4 100644--- a/tests/agent/test_prompt_caching.py+++ b/tests/agent/test_prompt_caching.py@@ -6,13 +6,139 @@ from agent.prompt_caching import (_build_marker,_can_carry_marker,apply_anthropic_cache_control,+ build_prompt_cache_plan,strip_anthropic_cache_control,+ strip_anthropic_tool_cache_control,)MARKER = {"type": "ephemeral"}+def _native_marker_indexes(messages):+ return {+ index+ for index, message in enumerate(messages)+ if isinstance(message, dict)+ and (+ "cache_control" in message+ or any(+ isinstance(part, dict) and "cache_control" in part+ for part in (message.get("content") if isinstance(message.get("content"), list) else [])+ )+ )+ }+++def _tool_heavy_native_history():+ return [+ {"role": "system", "content": "stable prefix\nvolatile suffix"},+ {"role": "user", "content": "first request"},+ {"role": "assistant", "content": "", "tool_calls": [{"id": "first", "function": {"name": "tool_00", "arguments": "{}"}}]},+ {"role": "tool", "tool_call_id": "first", "content": "first result"},+ {"role": "user", "content": "second request"},+ {"role": "assistant", "content": "", "tool_calls": [{"id": "second", "function": {"name": "tool_01", "arguments": "{}"}}]},+ {"role": "tool", "tool_call_id": "second", "content": "second result"},+ ]+++def _tool_heavy_native_tools():+ return [+ {+ "type": "function",+ "function": {+ "name": f"tool_{index:02d}",+ "description": f"Deterministic tool {index}",+ "parameters": {"type": "object", "properties": {}},+ },+ }+ for index in range(28)+ ]+++def test_t20880_tool_heavy_native_loop_reproduction():+ """A 28-tool native loop needs a tool marker and a retained transaction endpoint."""+ tools = _tool_heavy_native_tools()+ before_exchange = build_prompt_cache_plan(+ _tool_heavy_native_history(),+ tools,+ native_anthropic=True,+ static_system_prefix="stable prefix",+ direct_native_tool_cache=True,+ )+ after_exchange = build_prompt_cache_plan(+ _tool_heavy_native_history() + [+ {"role": "user", "content": "third request"},+ {"role": "assistant", "content": "", "tool_calls": [{"id": "third", "function": {"name": "tool_02", "arguments": "{}"}}]},+ {"role": "tool", "tool_call_id": "third", "content": "third result"},+ ],+ tools,+ native_anthropic=True,+ static_system_prefix="stable prefix",+ direct_native_tool_cache=True,+ )++ before_markers = _native_marker_indexes(before_exchange.messages)+ after_markers = _native_marker_indexes(after_exchange.messages)+ final_tool_marked = "cache_control" in after_exchange.tools[-1]+ shared_transaction_endpoint = bool((before_markers - {0}) & (after_markers - {0}))++ assert final_tool_marked+ assert shared_transaction_endpoint+ assert after_exchange.marker_count <= 4+++class TestPromptCachePlan:+ def test_copies_sections_and_keeps_canonical_tools_plain(self):+ import copy++ messages = _tool_heavy_native_history()+ tools = _tool_heavy_native_tools()+ original_messages = copy.deepcopy(messages)+ original_tools = copy.deepcopy(tools)++ plan = build_prompt_cache_plan(+ messages,+ tools,+ native_anthropic=True,+ static_system_prefix="stable prefix",+ direct_native_tool_cache=True,+ )++ assert messages == original_messages+ assert tools == original_tools+ assert plan.messages is not messages+ assert plan.tools is not tools+ assert "cache_control" not in tools[-1]+ assert plan.tools[-1]["cache_control"] == MARKER+ assert plan.marker_count == 4++ def test_unmarkable_endpoint_does_not_consume_a_slot(self):+ messages = [+ {"role": "system", "content": "stable prefix\nvolatile"},+ {"role": "assistant", "content": "", "tool_calls": [{"id": "pending", "function": {"name": "tool_00", "arguments": "{}"}}]},+ ]+ plan = build_prompt_cache_plan(+ messages,+ _tool_heavy_native_tools(),+ native_anthropic=True,+ static_system_prefix="stable prefix",+ direct_native_tool_cache=True,+ )++ assert plan.marker_count == 2+ assert "cache_control" not in plan.messages[-1]++ def test_tool_strip_is_request_local(self):+ tools = _tool_heavy_native_tools()+ tools[-1]["cache_control"] = MARKER++ stripped = strip_anthropic_tool_cache_control(tools)++ assert "cache_control" in tools[-1]+ assert "cache_control" not in stripped[-1]++class TestApplyCacheMarker:def test_tool_message_gets_top_level_marker_on_native_anthropic(self):"""Native Anthropic path: cache_control injected top-level (adapter moves it inside tool_result)."""@@ -248,10 +374,9 @@ class TestNormalizationOrdering:from agent import conversation_loopsrc = inspect.getsource(conversation_loop)- # Anchor on the call-block decoration (before the retry loop), not the- # mid-failover redecoration helper which also calls apply_*.- anchor = src.index("Runs LAST, after every message mutation above")- mark = src.index("apply_anthropic_cache_control(\n", anchor)+ # Anchor on the call-block request plan, not the retry helper.+ anchor = src.index("Build the request-local cache sections")+ mark = src.index("build_prompt_cache_plan(\n", anchor)for earlier in ('am["content"].strip()', # whitespace normalization"_sanitize_api_messages(api_messages)", # orphan sweepdiff --git a/tests/run_agent/test_anthropic_prompt_cache_policy.py b/tests/run_agent/test_anthropic_prompt_cache_policy.pyindex f456c107eef..687a65f2518 100644--- a/tests/run_agent/test_anthropic_prompt_cache_policy.py+++ b/tests/run_agent/test_anthropic_prompt_cache_policy.py@@ -43,6 +43,38 @@ class TestNativeAnthropic:)assert agent._anthropic_prompt_cache_policy() == (True, True)+ def test_anthropic_provider_on_third_party_host_stays_message_only(self):+ agent = _make_agent(+ provider="anthropic",+ base_url="https://api.minimax.io/anthropic",+ api_mode="anthropic_messages",+ model="claude-sonnet-4-6",+ )+ assert agent._anthropic_prompt_cache_policy() == (True, True)+ assert agent._direct_native_anthropic_tool_cache_capability() is False++ def test_only_direct_native_anthropic_enables_tool_markers(self):+ agent = _make_agent(+ provider="anthropic",+ base_url="https://api.anthropic.com",+ api_mode="anthropic_messages",+ model="claude-sonnet-4-6",+ )+ assert agent._direct_native_anthropic_tool_cache_capability() is True++ assert agent._direct_native_anthropic_tool_cache_capability(+ provider="custom",+ base_url="https://api.minimax.io/anthropic",+ api_mode="anthropic_messages",+ model="claude-sonnet-4-6",+ ) is False+ assert agent._direct_native_anthropic_tool_cache_capability(+ provider="openrouter",+ base_url="https://openrouter.ai/api/v1",+ api_mode="chat_completions",+ model="anthropic/claude-sonnet-4.6",+ ) is False+class TestOpenRouter:diff --git a/tests/run_agent/test_run_agent.py b/tests/run_agent/test_run_agent.pyindex 6e99fa59f58..aa33253858e 100644--- a/tests/run_agent/test_run_agent.py+++ b/tests/run_agent/test_run_agent.py@@ -1209,6 +1209,38 @@ class TestBuildApiKwargs:assert kwargs["messages"] is messagesassert kwargs["timeout"] == 1800.0+ def test_explicit_request_local_tools_reach_native_transport(self, agent, monkeypatch):+ from agent.prompt_caching import build_prompt_cache_plan++ canonical_tools = [+ {+ "type": "function",+ "function": {+ "name": "lookup",+ "parameters": {"type": "object", "properties": {}},+ },+ }+ ]+ plan = build_prompt_cache_plan(+ [{"role": "system", "content": "stable\nvolatile"}, {"role": "user", "content": "lookup"}],+ canonical_tools,+ native_anthropic=True,+ static_system_prefix="stable",+ direct_native_tool_cache=True,+ )+ transport = MagicMock()+ transport.build_kwargs.side_effect = lambda **kwargs: kwargs+ agent.api_mode = "anthropic_messages"+ agent.provider = "anthropic"+ agent.base_url = "https://api.anthropic.com"+ monkeypatch.setattr(agent, "_get_transport", lambda: transport)+ monkeypatch.setattr(agent, "_prepare_anthropic_messages_for_api", lambda messages: messages)++ kwargs = agent._build_api_kwargs(plan.messages, tools_for_api=plan.tools)++ assert "cache_control" not in canonical_tools[-1]+ assert kwargs["tools"][-1]["cache_control"] == {"type": "ephemeral"}+def test_public_moonshot_kimi_k2_5_omits_temperature(self, agent):"""Kimi models should NOT have client-side temperature overrides.