Skip to content

The agent that grows with you

fix(providers): route api.meta.ai through Responses API for prompt caching

Lavie24545418eb6a
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 248387b96ab..b0b69b41d5d 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -671,43 +671,55 @@ def init_agent(
agent.acp_args = list(acp_args or args or [])
if api_mode in {"chat_completions", "codex_responses", "anthropic_messages", "bedrock_converse", "codex_app_server"}:
agent.api_mode = api_mode
- elif agent.provider == "openai-codex":
- agent.api_mode = "codex_responses"
- elif agent.provider in {"xai", "xai-oauth"}:
- agent.api_mode = "codex_responses"
- elif (provider_name is None) and (
- agent._base_url_hostname == "chatgpt.com"
- and "/backend-api/codex" in agent._base_url_lower
- ):
- agent.api_mode = "codex_responses"
- agent.provider = "openai-codex"
- elif (provider_name is None) and agent._base_url_hostname == "api.x.ai":
- agent.api_mode = "codex_responses"
- agent.provider = "xai"
- elif agent.provider == "anthropic" or (provider_name is None and agent._base_url_hostname == "api.anthropic.com"):
- agent.api_mode = "anthropic_messages"
- agent.provider = "anthropic"
- elif agent._base_url_lower.rstrip("/").endswith("/anthropic"):
- # Third-party Anthropic-compatible endpoints (e.g. MiniMax, DashScope)
- # use a URL convention ending in /anthropic. Auto-detect these so the
- # Anthropic Messages API adapter is used instead of chat completions.
- agent.api_mode = "anthropic_messages"
- elif agent.provider == "bedrock" or (
- agent._base_url_hostname.startswith("bedrock-runtime.")
- and base_url_host_matches(agent._base_url_lower, "amazonaws.com")
- ):
- # AWS Bedrock — auto-detect from provider name or base URL
- # (bedrock-runtime.<region>.amazonaws.com).
- agent.api_mode = "bedrock_converse"
- elif agent.provider in {"nous", "nous-portal", "nousresearch"}:
- # Portal is dual-wire: anthropic/* → Messages, everything else →
- # chat_completions. Callers that already pass api_mode win above;
- # this covers direct AIAgent construction without a resolved runtime.
- from hermes_cli.providers import nous_api_mode
-
- agent.api_mode = nous_api_mode(agent.model)
else:
- agent.api_mode = "chat_completions"
+ # Host-mandated wire check (single source of truth via providers.host_mandated_api_mode).
+ # Covers api.meta.ai → codex_responses for prompt caching (0% on chat vs 93-99% on responses)
+ # and any future host mandates. Lazy import to avoid circular imports.
+ try:
+ from hermes_cli.providers import host_mandated_api_mode as _host_mandated_api_mode
+
+ _mandated = _host_mandated_api_mode(base_url or "")
+ except Exception:
+ _mandated = None
+ if _mandated is not None:
+ agent.api_mode = _mandated
+ elif agent.provider == "openai-codex":
+ agent.api_mode = "codex_responses"
+ elif agent.provider in {"xai", "xai-oauth"}:
+ agent.api_mode = "codex_responses"
+ elif (provider_name is None) and (
+ agent._base_url_hostname == "chatgpt.com"
+ and "/backend-api/codex" in agent._base_url_lower
+ ):
+ agent.api_mode = "codex_responses"
+ agent.provider = "openai-codex"
+ elif (provider_name is None) and agent._base_url_hostname == "api.x.ai":
+ agent.api_mode = "codex_responses"
+ agent.provider = "xai"
+ elif agent.provider == "anthropic" or (provider_name is None and agent._base_url_hostname == "api.anthropic.com"):
+ agent.api_mode = "anthropic_messages"
+ agent.provider = "anthropic"
+ elif agent._base_url_lower.rstrip("/").endswith("/anthropic"):
+ # Third-party Anthropic-compatible endpoints (e.g. MiniMax, DashScope)
+ # use a URL convention ending in /anthropic. Auto-detect these so the
+ # Anthropic Messages API adapter is used instead of chat completions.
+ agent.api_mode = "anthropic_messages"
+ elif agent.provider == "bedrock" or (
+ agent._base_url_hostname.startswith("bedrock-runtime.")
+ and base_url_host_matches(agent._base_url_lower, "amazonaws.com")
+ ):
+ # AWS Bedrock — auto-detect from provider name or base URL
+ # (bedrock-runtime.<region>.amazonaws.com).
+ agent.api_mode = "bedrock_converse"
+ elif agent.provider in {"nous", "nous-portal", "nousresearch"}:
+ # Portal is dual-wire: anthropic/* → Messages, everything else →
+ # chat_completions. Callers that already pass api_mode win above;
+ # this covers direct AIAgent construction without a resolved runtime.
+ from hermes_cli.providers import nous_api_mode
+
+ agent.api_mode = nous_api_mode(agent.model)
+ else:
+ agent.api_mode = "chat_completions"
# Credential-pool validation runs AFTER provider auto-detection so
# a pool scoped to e.g. "anthropic" is not rejected when the agent
diff --git a/agent/transports/codex.py b/agent/transports/codex.py
index 6f6d255d61f..9a866225b01 100644
--- a/agent/transports/codex.py
+++ b/agent/transports/codex.py
@@ -115,10 +115,16 @@ def _default_prompt_cache_retention_for_request(
model: str,
base_url: Any,
) -> Optional[str]:
- """Return ``24h`` for supported models on Amazon Bedrock Mantle."""
+ """Return ``24h`` for supported hosts/models (Bedrock Mantle, Meta)."""
from utils import base_url_hostname
- hostname_parts = base_url_hostname(str(base_url or "")).split(".")
+ hostname = base_url_hostname(str(base_url or "")).lower()
+ # Meta Model API: prompt caching is opt-in via prompt_cache_retention.
+ # Measured 0% hits on /chat/completions vs 93-99% on /responses with 24h.
+ if hostname == "api.meta.ai":
+ return "24h"
+
+ hostname_parts = hostname.split(".")
is_bedrock_mantle = (
len(hostname_parts) == 4
and hostname_parts[0] == "bedrock-mantle"
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index 5d8461431cf..1ce7b3903f3 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -132,6 +132,12 @@ model:
# CF-Access-Client-Id: "xxxx.access"
# CF-Access-Client-Secret: "${CF_ACCESS_SECRET}"
# X-Client-Name: "hermes-agent"
+# providers:
+# meta:
+# base_url: https://api.meta.ai/v1
+# api_key: ${META_API_KEY}
+# # api_mode auto-detected as codex_responses for api.meta.ai; no need to set
+
# Command-minted credentials (optional): key_cmd
# ------------------------------------------------------------------
diff --git a/hermes_cli/providers.py b/hermes_cli/providers.py
index 20884cb3aee..edaeb08a237 100644
--- a/hermes_cli/providers.py
+++ b/hermes_cli/providers.py
@@ -617,6 +617,9 @@ def host_mandated_api_mode(base_url: str = "") -> Optional[str]:
Some hosts only accept one API mode and reject the others outright:
- api.openai.com only accepts the Responses API for its (reasoning)
models when tools + reasoning are in play (chat/completions 400s).
+ - api.meta.ai only achieves KV-cache hits on /v1/responses with
+ prompt_cache_retention; /v1/chat/completions returns 0 cached
+ tokens (measured 0% vs 93-99% on /responses with retention).
- api.anthropic.com / ``…/anthropic`` suffixes speak native Messages.
- Kimi's ``/coding`` endpoint speaks native Messages.
- AWS Bedrock runtime hosts speak Converse.
@@ -644,6 +647,11 @@ def host_mandated_api_mode(base_url: str = "") -> Optional[str]:
# catalog filtering and listing authority.
if is_official_openai_host(base_url):
return "codex_responses"
+ # Meta Model API (api.meta.ai) only achieves prompt-cache hits on the
+ # Responses API with prompt_cache_retention; chat/completions stays
+ # cache-cold (0% vs 93-99% measured). Exact-hostname match per #32243.
+ if hostname == "api.meta.ai":
+ return "codex_responses"
if hostname.startswith("bedrock-runtime.") and base_url_host_matches(base_url, "amazonaws.com"):
return "bedrock_converse"
return None
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.py
index 888175a701e..66a9d8de0c3 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -134,6 +134,11 @@ def _detect_api_mode_for_url(base_url: str) -> Optional[str]:
# providers.is_official_openai_host for the spoof-rejection contract.
if is_official_openai_host(base_url):
return "codex_responses"
+ # Meta Model API: prompt caching only on Responses API (0% on
+ # chat/completions vs 93-99% on /responses with retention). Exact
+ # hostname per #32243.
+ if hostname == "api.meta.ai":
+ return "codex_responses"
if hostname == "api.actual.inc":
return "codex_responses"
# Direct native Anthropic host: realign with providers.determine_api_mode,
diff --git a/tests/agent/test_meta_agent_init.py b/tests/agent/test_meta_agent_init.py
new file mode 100644
index 00000000000..de9e790bf5d
--- /dev/null
+++ b/tests/agent/test_meta_agent_init.py
@@ -0,0 +1,83 @@
+"""Tests for AIAgent provider=meta host-mandated api_mode."""
+
+import pytest
+
+
+def test_agent_init_meta_base_url_implies_codex_responses():
+ from run_agent import AIAgent
+
+ agent = AIAgent(
+ provider="meta",
+ base_url="https://api.meta.ai/v1",
+ api_key="sk-test-meta",
+ model="muse-spark-1.2",
+ api_mode=None,
+ quiet_mode=True,
+ skip_context_files=True,
+ skip_memory=True,
+ )
+ assert agent.api_mode == "codex_responses"
+ assert agent.provider == "meta"
+
+
+def test_agent_init_explicit_chat_wins_over_mandate():
+ from run_agent import AIAgent
+
+ agent = AIAgent(
+ provider="meta",
+ base_url="https://api.meta.ai/v1",
+ api_key="sk-test-meta",
+ model="muse-spark-1.2",
+ api_mode="chat_completions",
+ quiet_mode=True,
+ skip_context_files=True,
+ skip_memory=True,
+ )
+ assert agent.api_mode == "chat_completions"
+ assert agent.provider == "meta"
+
+
+def test_agent_init_meta_provider_stays_meta():
+ from run_agent import AIAgent
+
+ agent = AIAgent(
+ provider="meta",
+ base_url="https://api.meta.ai/v1",
+ api_key="sk-test-meta",
+ model="muse-spark-1.2",
+ quiet_mode=True,
+ skip_context_files=True,
+ skip_memory=True,
+ )
+ assert agent.provider == "meta"
+ assert agent.provider != "custom"
+
+
+def test_agent_init_custom_with_meta_url_also_mandates():
+ from run_agent import AIAgent
+
+ agent = AIAgent(
+ provider="custom",
+ base_url="https://api.meta.ai/v1",
+ api_key="sk-test-meta",
+ model="muse-spark-1.2",
+ quiet_mode=True,
+ skip_context_files=True,
+ skip_memory=True,
+ )
+ assert agent.api_mode == "codex_responses"
+
+
+def test_agent_init_meta_url_case_insensitive():
+ from run_agent import AIAgent
+
+ agent = AIAgent(
+ provider="meta",
+ base_url="https://API.META.AI/v1",
+ api_key="sk-test-meta",
+ model="muse-spark-1.2",
+ quiet_mode=True,
+ skip_context_files=True,
+ skip_memory=True,
+ )
+ assert agent.api_mode == "codex_responses"
diff --git a/tests/agent/test_meta_usage_cache_reporting.py b/tests/agent/test_meta_usage_cache_reporting.py
new file mode 100644
index 00000000000..52034d2d8fd
--- /dev/null
+++ b/tests/agent/test_meta_usage_cache_reporting.py
@@ -0,0 +1,46 @@
+"""Usage cache reporting for Meta Responses path."""
+
+from types import SimpleNamespace
+
+from agent.usage_pricing import normalize_usage
+
+
+def test_meta_cached_tokens_flows_to_cache_read():
+ usage = SimpleNamespace(
+ input_tokens=4000,
+ output_tokens=100,
+ input_tokens_details=SimpleNamespace(cached_tokens=3920, cache_creation_tokens=0),
+ output_tokens_details=None,
+ prompt_tokens=None,
+ completion_tokens=None,
+ )
+ cu = normalize_usage(usage, api_mode="codex_responses")
+ assert cu.cache_read_tokens == 3920
+ assert cu.input_tokens == 80 # 4000 - 3920
+ # rendered cache line would be cache=3920/4000 (98%)
+ total = cu.prompt_tokens
+ assert total == 4000
+ pct = (cu.cache_read_tokens / total * 100) if total else 0
+ assert 97 <= pct <= 99
+ rendered = f"cache={cu.cache_read_tokens}/{total} ({pct:.0f}%)"
+ assert rendered == "cache=3920/4000 (98%)"
+
+
+def test_meta_cache_write_tokens():
+ first = SimpleNamespace(
+ input_tokens=4000,
+ output_tokens=100,
+ input_tokens_details=SimpleNamespace(cached_tokens=0, cache_creation_tokens=4000),
+ )
+ cu1 = normalize_usage(first, api_mode="codex_responses")
+ assert cu1.cache_write_tokens == 4000
+ assert cu1.cache_read_tokens == 0
+
+ second = SimpleNamespace(
+ input_tokens=4000,
+ output_tokens=100,
+ input_tokens_details=SimpleNamespace(cached_tokens=3920, cache_creation_tokens=0),
+ )
+ cu2 = normalize_usage(second, api_mode="codex_responses")
+ assert cu2.cache_read_tokens == 3920
+ assert cu2.cache_write_tokens == 0
diff --git a/tests/agent/transports/test_meta_codex_cache.py b/tests/agent/transports/test_meta_codex_cache.py
new file mode 100644
index 00000000000..5dcb0ced8e4
--- /dev/null
+++ b/tests/agent/transports/test_meta_codex_cache.py
@@ -0,0 +1,114 @@
+"""Tests for Meta api.meta.ai prompt_cache_retention and transport plumbing."""
+
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from agent.transports import get_transport
+from agent.transports.codex import _default_prompt_cache_retention_for_request
+
+
+def transport():
+ import agent.transports.codex # noqa: F401
+ return get_transport("codex_responses")
+
+
+class TestMetaRetention:
+ def test_meta_retention_24h(self, transport):
+ kw = transport.build_kwargs(
+ model="muse-spark-1.2",
+ messages=[{"role": "user", "content": "Hi"}],
+ tools=[],
+ base_url="https://api.meta.ai/v1",
+ session_id="test-session",
+ )
+ assert kw.get("prompt_cache_retention") == "24h"
+
+ def test_meta_retention_also_for_generic_model_name(self, transport):
+ for model in ["muse-spark", "meta/muse-spark-1.2-2026-04-01", "gpt-5.4", ""]:
+ kw = transport.build_kwargs(
+ model=model,
+ messages=[{"role": "user", "content": "Hi"}],
+ tools=[],
+ base_url="https://api.meta.ai/v1",
+ session_id="sid",
+ )
+ assert kw.get("prompt_cache_retention") == "24h", f"model={model!r}"
+
+ def test_meta_retention_helper_direct(self):
+ assert _default_prompt_cache_retention_for_request("muse-spark-1.2", "https://api.meta.ai/v1") == "24h"
+ assert _default_prompt_cache_retention_for_request("muse-spark-1.2", "https://API.META.AI/v1") == "24h"
+ assert _default_prompt_cache_retention_for_request("muse-spark-1.2", "https://api.meta.ai:443/v1") == "24h"
+
+ def test_meta_retention_not_sent_when_overridden(self, transport):
+ kw = transport.build_kwargs(
+ model="muse-spark-1.2",
+ messages=[{"role": "user", "content": "Hi"}],
+ tools=[],
+ base_url="https://api.meta.ai/v1",
+ session_id="sid",
+ request_overrides={"prompt_cache_retention": "in_memory"},
+ )
+ assert kw.get("prompt_cache_retention") == "in_memory"
+
+ def test_non_meta_no_retention(self, transport):
+ kw = transport.build_kwargs(
+ model="muse-spark-1.2",
+ messages=[{"role": "user", "content": "Hi"}],
+ tools=[],
+ base_url="https://generic.example.com/v1",
+ session_id="sid",
+ )
+ assert "prompt_cache_retention" not in kw
+
+ def test_non_meta_no_retention_helper(self):
+ assert _default_prompt_cache_retention_for_request("muse-spark-1.2", "https://generic.example.com/v1") is None
+
+ def test_meta_prompt_cache_key_is_content_addressed(self, transport):
+ messages = [{"role": "user", "content": "Hi"}]
+ kw = transport.build_kwargs(
+ model="muse-spark-1.2",
+ messages=messages,
+ tools=[],
+ base_url="https://api.meta.ai/v1",
+ session_id="cron_job_xxx_20260624_143000",
+ )
+ pck = kw.get("prompt_cache_key", "")
+ assert pck.startswith("pck_")
+ # stable across different cron fire timestamps (same scope)
+ kw2 = transport.build_kwargs(
+ model="muse-spark-1.2",
+ messages=messages,
+ tools=[],
+ base_url="https://api.meta.ai/v1",
+ session_id="cron_job_xxx_20260624_143500",
+ )
+ assert kw["prompt_cache_key"] == kw2["prompt_cache_key"]
+
+ def test_meta_reasoning_effort_passthrough(self, transport):
+ kw = transport.build_kwargs(
+ model="muse-spark-1.2",
+ messages=[{"role": "user", "content": "Hi"}],
+ tools=[],
+ base_url="https://api.meta.ai/v1",
+ session_id="sid",
+ reasoning_config={"effort": "high", "enabled": True},
+ )
+ assert kw.get("reasoning") == {"effort": "high", "summary": "auto"}
+
+ def test_meta_request_hits_responses_plan(self, transport):
+ # Transport api_mode must be codex_responses so conversation_loop hits /v1/responses
+ assert transport.api_mode == "codex_responses"
+ kw = transport.build_kwargs(
+ model="muse-spark-1.2",
+ messages=[{"role": "user", "content": "Hi"}],
+ tools=[{"type": "function", "function": {"name": "terminal", "description": "x", "parameters": {"type": "object", "properties": {"command": {"type": "string"}}}}}],
+ base_url="https://api.meta.ai/v1",
+ session_id="sid",
+ )
+ # Ensure instructions/input/tools and retention present - i.e., responses shape
+ assert "instructions" in kw or "input" in kw
+ assert kw.get("prompt_cache_retention") == "24h"
+ assert "prompt_cache_key" in kw
diff --git a/tests/hermes_cli/test_meta_prompt_cache.py b/tests/hermes_cli/test_meta_prompt_cache.py
new file mode 100644
index 00000000000..662088b2a4c
--- /dev/null
+++ b/tests/hermes_cli/test_meta_prompt_cache.py
@@ -0,0 +1,102 @@
+"""Behavior contracts for Meta Muse prompt-caching host mandate."""
+
+import pytest
+
+from hermes_cli.providers import determine_api_mode, host_mandated_api_mode
+from hermes_cli import runtime_provider as rp
+
+
+class TestHostMandatedMetaResponses:
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "https://api.meta.ai/v1",
+ "https://api.meta.ai/v1/",
+ "https://api.meta.ai/v1/chat/completions",
+ "https://API.META.AI/v1",
+ "https://api.meta.ai",
+ "https://api.meta.ai:443/v1",
+ "https://api.meta.ai./v1",
+ "https://[email protected]/v1",
+ ],
+ )
+ def test_host_mandated_meta_returns_codex_responses(self, url):
+ assert host_mandated_api_mode(url) == "codex_responses"
+
+ @pytest.mark.parametrize(
+ "url",
+ [
+ "https://api.meta.ai.attacker.test/v1",
+ "https://proxy.test/api.meta.ai/v1",
+ "https://api.meta.ai.evil/v1",
+ "https://meta.ai/v1",
+ "https://www.meta.ai/v1",
+ "https://api.meta.com/v1",
+ "https://[::1]/v1",
+ "https://generic.example.com/v1",
+ "",
+ ],
+ )
+ def test_host_mandated_meta_rejects_spoofs(self, url):
+ assert host_mandated_api_mode(url) != "codex_responses"
+ # Must be None for generic/unrelated hosts (contract: no clobber)
+ if url in (
+ "https://generic.example.com/v1",
+ "https://[::1]/v1",
+ "",
+ "https://meta.ai/v1",
+ "https://api.meta.ai.attacker.test/v1",
+ "https://proxy.test/api.meta.ai/v1",
+ ):
+ assert host_mandated_api_mode(url) is None
+
+ def test_determine_api_mode_meta_via_named_custom(self):
+ assert determine_api_mode("meta", "https://api.meta.ai/v1") == "codex_responses"
+ assert determine_api_mode("custom", "https://api.meta.ai/v1") == "codex_responses"
+ assert determine_api_mode("generic", "https://generic.example.com/v1") == "chat_completions"
+
+ def test_determine_api_mode_meta_with_trailing_slash(self):
+ assert determine_api_mode("meta", "https://api.meta.ai/v1/") == "codex_responses"
+
+ def test_runtime_detect_meta(self):
+ assert rp._detect_api_mode_for_url("https://api.meta.ai/v1") == "codex_responses"
+ assert rp._detect_api_mode_for_url("https://api.meta.ai/v1/chat/completions") == "codex_responses"
+ assert rp._detect_api_mode_for_url("https://API.META.AI/v1") == "codex_responses"
+
+ def test_runtime_detect_meta_rejects_spoofs(self):
+ assert rp._detect_api_mode_for_url("https://api.meta.ai.attacker.test/v1") is None
+ assert rp._detect_api_mode_for_url("https://proxy.test/api.meta.ai/v1") is None
+ assert rp._detect_api_mode_for_url("https://meta.ai/v1") is None
+ assert rp._detect_api_mode_for_url("https://generic.example.com/v1") is None
+
+ def test_fallback_api_mode_meta(self):
+ assert rp._fallback_api_mode("meta", "https://api.meta.ai/v1", "muse-spark-1.2") == "codex_responses"
+ assert rp._fallback_api_mode("custom", "https://api.meta.ai/v1", "muse-spark-1.2") == "codex_responses"
+ # generic still chat
+ assert rp._fallback_api_mode("custom", "https://generic.example.com/v1", "muse-spark-1.2") == "chat_completions"
+
+
+class TestMetaConfigRoundtrip:
+ def test_providers_meta_api_mode_roundtrip(self):
+ from hermes_cli.config import _normalize_custom_provider_entry
+
+ entry = {"name": "Meta", "base_url": "https://api.meta.ai/v1", "api_mode": "codex_responses"}
+ normalized = _normalize_custom_provider_entry(entry)
+ assert normalized.get("api_mode") == "codex_responses"
+
+ entry2 = {"name": "Meta", "base_url": "https://api.meta.ai/v1", "transport": "codex_responses"}
+ normalized2 = _normalize_custom_provider_entry(entry2)
+ # transport is lifted to api_mode via _normalize path or at least preserved
+ assert normalized2.get("api_mode") == "codex_responses" or normalized2.get("transport") == "codex_responses"
+
+ def test_providers_dict_to_custom_providers_preserves_meta_without_explicit_mode(self):
+ # Without explicit api_mode, host mandate resolves via providers.determine_api_mode
+ # This test ensures the providers entry survives normalization and the host still mandates
+ from hermes_cli.providers import host_mandated_api_mode
+
+ assert host_mandated_api_mode("https://api.meta.ai/v1") == "codex_responses"
+ # Simulate providers dict path: providers.meta.base_url stored, no api_mode field
+ # The resolution layer (determine_api_mode / runtime_provider) must mandate.
+ from hermes_cli.providers import determine_api_mode
+
+ assert determine_api_mode("meta", "https://api.meta.ai/v1", "muse-spark-1.2") == "codex_responses"
diff --git a/tests/hermes_cli/test_model_switch_openai_api_mode.py b/tests/hermes_cli/test_model_switch_openai_api_mode.py
index 09357ffe93f..fe649b8ff92 100644
--- a/tests/hermes_cli/test_model_switch_openai_api_mode.py
+++ b/tests/hermes_cli/test_model_switch_openai_api_mode.py
@@ -100,3 +100,41 @@ def test_generic_endpoint_keeps_explicit_api_mode():
# The real endpoints are mandated.
assert host_mandated_api_mode("https://api.openai.com/v1") == "codex_responses"
assert host_mandated_api_mode("https://api.anthropic.com") == "anthropic_messages"
+
+def test_stale_chat_overridden_on_meta_direct():
+ """Stale chat_completions on api.meta.ai → codex_responses (like openai direct).
+
+ Switching from openrouter/chat_completions to muse-spark on meta's
+ endpoint must flip to Responses API for caching (0% vs 93-99%).
+ """
+ result = _run_openai_switch(
+ raw_input="muse-spark-1.2",
+ current_provider="openrouter",
+ current_model="anthropic/claude-opus-4.8",
+ explicit_provider="meta",
+ runtime_api_mode="chat_completions", # stale
+ runtime_base_url="https://api.meta.ai/v1",
+ )
+ assert result.success, f"switch_model failed: {result.error_message}"
+ assert result.target_provider == "meta"
+ assert result.new_model == "muse-spark-1.2"
+ assert result.api_mode == "codex_responses"
+
+
+def test_generic_relay_not_clobbered_on_meta_switch():
+ """Generic relay does not pick up Meta mandate."""
+ assert __import__("hermes_cli.providers", fromlist=["host_mandated_api_mode"]).host_mandated_api_mode(
+ "https://generic.example.com/v1"
+ ) is None
+ result = _run_openai_switch(
+ raw_input="some-model",
+ current_provider="meta",
+ current_model="muse-spark-1.2",
+ explicit_provider="openrouter",
+ runtime_api_mode="chat_completions",
+ runtime_base_url="https://generic.example.com/v1",
+ )
+ # For generic endpoint, resolver api_mode is chat_completions and host_mandated is None,
+ # so it stays chat_completions (not forced to codex_responses).
+ assert result.success
+ assert result.api_mode == "chat_completions"
diff --git a/website/docs/developer-guide/adding-providers.md b/website/docs/developer-guide/adding-providers.md
index fa7adbe73c8..203fd43d0e7 100644
--- a/website/docs/developer-guide/adding-providers.md
+++ b/website/docs/developer-guide/adding-providers.md
@@ -34,7 +34,7 @@ A built-in provider has to line up across a few layers:
The important abstraction is `api_mode`.
- Most providers use `chat_completions`.
-- Codex uses `codex_responses`.
+- Codex and Meta Model API (`api.meta.ai` — Muse Spark) use `codex_responses` (auto-sends `prompt_cache_retention: 24h` for prompt caching; `api.meta.ai` achieves 93–99% cache hits only on `/v1/responses`).
- Anthropic uses `anthropic_messages`.
- A new non-OpenAI protocol usually means adding a new adapter and a new `api_mode` branch.
@@ -65,7 +65,7 @@ Use this when the provider does not behave like OpenAI chat completions.
Examples in-tree today:
-- `codex_responses`
+- `codex_responses` (OpenAI Codex, xAI Grok, and Meta Muse Spark via `api.meta.ai` — the latter auto-sends `prompt_cache_retention: 24h`)
- `anthropic_messages`
This path includes everything from Path A plus: