Skip to content

The agent that grows with you

feat: slim the per-provider session header to the route seam and document it

teknium12828e19a029e
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index d058ca68704..3ed52ee3516 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -6486,10 +6486,10 @@ def _build_call_kwargs(
or _endpoint_speaks_anthropic_messages(raw_base) or _is_anthropic_compat_endpoint(provider_norm, raw_base)
):
kwargs["_reasoning_config"] = dict(reasoning_config)
- # OpenCode relay session affinity — same key as the main turn so compression/title/vision
- # calls stay on the conversation's warm backend.
- from agent.opencode_affinity import merge_opencode_session_headers
- return merge_opencode_session_headers(kwargs, provider, base_url, _runtime_main_value("session_id") or None)
+ # Conversation affinity (OpenCode relay, opt-in custom-provider header) — same key as the main
+ # turn so compression/title/vision calls stay on the conversation's warm backend.
+ from agent.opencode_affinity import merge_session_affinity_headers
+ return merge_session_affinity_headers(kwargs, provider, base_url, _runtime_main_value("session_id") or None)
def _validate_llm_response(
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index f1a9d4541af..4ed54aab279 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -1432,15 +1432,15 @@ def _build_chat_completions_kwargs(agent, api_messages, tools_for_api, reasoning
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.
- Wraps the per-api_mode builder so the OpenCode ``x-opencode-session``
- affinity header rides on every OpenCode request regardless of transport
- (chat_completions / codex_responses / anthropic_messages all route
- OpenCode models). No-op for every other provider.
+ Wraps the per-api_mode builder so the conversation-affinity headers (OpenCode's
+ ``x-opencode-session``, a custom provider's opt-in ``session_affinity_header``) ride on
+ every request regardless of transport (chat_completions / codex_responses /
+ anthropic_messages). No-op for every other provider.
"""
- from agent.opencode_affinity import merge_opencode_session_headers
+ from agent.opencode_affinity import merge_session_affinity_headers
kwargs = _build_api_kwargs_for_mode(agent, api_messages, tools_for_api)
- return merge_opencode_session_headers(
+ return merge_session_affinity_headers(
kwargs,
getattr(agent, "provider", None),
getattr(agent, "base_url", None),
diff --git a/agent/opencode_affinity.py b/agent/opencode_affinity.py
index 63e533052e7..afe2a32cb7b 100644
--- a/agent/opencode_affinity.py
+++ b/agent/opencode_affinity.py
@@ -1,23 +1,30 @@
-"""``x-opencode-session`` — OpenCode relay session-affinity header.
-
-OpenCode (opencode.ai Zen/Go relay) pins requests that share an
-``x-opencode-session`` value to the same upstream backend, which is what
-keeps its prompt cache warm across the turns of one conversation. The value
-only has to be opaque and consistent per conversation, so it is derived the
-same way as the other conversation-affinity hints Hermes already sends
-(OpenRouter's sticky ``session_id``, xAI's ``x-grok-conv-id``): the
-host-declared routing scope first, then the ambient conversation root, then
-the physical session id — normalized through ``_cache_scope_from_session_id``
-so cron fires of one job share a scope.
-
-Every OpenCode request — main turn on any transport, auxiliary calls
-(compression, titles, vision, MoA) — goes through :func:`opencode_session_headers`
-so the header cannot drift per code path.
+"""Conversation-affinity request headers for session-aware relays and proxies.
+
+Two sources, one merge point:
+
+* ``x-opencode-session`` — OpenCode (opencode.ai Zen/Go relay) pins requests that share this
+ value to the same upstream backend, which keeps its prompt cache warm across the turns of one
+ conversation. Always sent to OpenCode targets.
+* ``providers.<name>.session_affinity_header`` — an opt-in header NAME on a custom provider entry
+ (default off). Session-aware proxies fronting a stateful backend (LiteLLM's ``x-litellm-session-id``,
+ self-hosted Claude/OpenAI gateways) otherwise classify an agent-loop request whose last message is
+ a ``tool_result`` as a new conversation and replay the whole history upstream (#86241, #104449).
+
+The value only has to be opaque and consistent per conversation, so it is derived the same way as
+the other affinity hints Hermes already sends (OpenRouter's sticky ``session_id``, xAI's
+``x-grok-conv-id``): the host-declared routing scope first (a host that names its own conversation,
+#96811), then the ambient conversation ROOT (stable across compaction rotation and delegate trees),
+then the physical session id — normalized through ``_cache_scope_from_session_id`` so cron fires of
+one job share a scope. Auxiliary calls (compression, titles, vision, MoA) have no session handle and
+resolve the ambient value, so they stay on the conversation's backend too (#70820).
+
+Every request — main turn on any transport, auxiliary calls — goes through
+:func:`merge_session_affinity_headers` so the headers cannot drift per code path.
"""
from __future__ import annotations
-from typing import Any, Dict, List, Optional
+from typing import Any, Optional
OPENCODE_SESSION_HEADER = "x-opencode-session"
@@ -44,14 +51,12 @@ def is_opencode_target(provider: Optional[str], base_url: Optional[str]) -> bool
def resolve_affinity_key(session_id: Optional[str] = None) -> str:
- """Return the normalized rotation-stable conversation affinity key."""
+ """Return the normalized rotation-stable conversation affinity key ("" when unknown)."""
try:
from agent.portal_tags import get_affinity_scope, get_conversation_context
from agent.transports.codex import _cache_scope_from_session_id
- return _cache_scope_from_session_id(
- get_affinity_scope() or get_conversation_context() or session_id
- )
+ return _cache_scope_from_session_id(get_affinity_scope() or get_conversation_context() or session_id)
except Exception:
return str(session_id or "")
@@ -69,45 +74,35 @@ def opencode_session_headers(
def custom_provider_session_affinity_headers(
- provider: Optional[str],
base_url: Optional[str],
session_id: Optional[str] = None,
- custom_providers: Optional[List[Dict[str, Any]]] = None,
) -> dict[str, str]:
- """Return ``{<session_affinity_header>: <key>}`` for custom providers declaring one, else ``{}``."""
+ """Return ``{<session_affinity_header>: <key>}`` when the route's provider entry declares one, else ``{}``."""
try:
- from hermes_cli.config_providers import get_custom_provider_session_affinity_header
-
- header = get_custom_provider_session_affinity_header(
- base_url=base_url,
- provider=provider,
- custom_providers=custom_providers,
- )
- if not header:
- return {}
- key = resolve_affinity_key(session_id)
- return {header: key} if key else {}
+ from hermes_cli.config import get_custom_provider_session_affinity_header
+
+ header = get_custom_provider_session_affinity_header(str(base_url or ""))
except Exception:
return {}
+ if not header:
+ return {}
+ key = resolve_affinity_key(session_id)
+ return {header: key} if key else {}
-def merge_opencode_session_headers(
+def merge_session_affinity_headers(
kwargs: dict[str, Any],
provider: Optional[str],
base_url: Optional[str],
session_id: Optional[str] = None,
- custom_providers: Optional[List[Dict[str, Any]]] = None,
) -> dict[str, Any]:
- """Merge OpenCode or custom provider affinity headers into ``kwargs["extra_headers"]`` (in place).
+ """Merge the affinity header(s) into ``kwargs["extra_headers"]`` (in place).
Existing per-request headers win, so a caller-pinned value is preserved.
- Non-OpenCode and non-affinity targets are left untouched.
+ Targets with neither source configured are left untouched.
"""
headers = opencode_session_headers(provider, base_url, session_id)
- if not headers:
- headers = custom_provider_session_affinity_headers(
- provider, base_url, session_id, custom_providers=custom_providers
- )
+ headers.update(custom_provider_session_affinity_headers(base_url, session_id))
if headers:
existing = kwargs.get("extra_headers")
merged = dict(existing) if isinstance(existing, dict) else {}
@@ -115,7 +110,3 @@ def merge_opencode_session_headers(
merged.setdefault(key, value)
kwargs["extra_headers"] = merged
return kwargs
-
-
-# Alias for callers naming the generalized capability
-merge_session_affinity_headers = merge_opencode_session_headers
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index 46e1712b89b..8e77e37d2f6 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -154,6 +154,16 @@ model:
# CF-Access-Client-Id: "xxxx.access"
# CF-Access-Client-Secret: "${CF_ACCESS_SECRET}"
# X-Client-Name: "hermes-agent"
+ #
+ # session_affinity_header: NAME of a header that carries Hermes' conversation
+ # id on every request to that provider (all api_modes + auxiliary calls). Off
+ # unless set. For session-aware proxies that otherwise treat each agent-loop
+ # request as a new conversation and replay the whole history upstream.
+ #
+ # providers:
+ # my-proxy:
+ # base_url: "http://127.0.0.1:4000/v1"
+ # session_affinity_header: x-litellm-session-id
# providers:
# meta:
# base_url: https://api.meta.ai/v1
diff --git a/hermes_cli/config_providers.py b/hermes_cli/config_providers.py
index a1900eec975..19eeab13a0b 100644
--- a/hermes_cli/config_providers.py
+++ b/hermes_cli/config_providers.py
@@ -491,43 +491,19 @@ def apply_custom_provider_extra_headers_to_client_kwargs(
def get_custom_provider_session_affinity_header(
- base_url: Optional[str] = None,
+ base_url: str,
custom_providers: Optional[List[Dict[str, Any]]] = None,
- config: Optional[Dict[str, Any]] = None,
- provider: Optional[str] = None) -> Optional[str]:
- """Return the declared ``session_affinity_header`` for a provider or route, or None."""
- from hermes_cli.config import get_compatible_custom_providers
- if custom_providers is None:
- try:
- custom_providers = get_compatible_custom_providers(config)
- except Exception:
- custom_providers = []
- if not isinstance(custom_providers, list):
- return None
+ config: Optional[Dict[str, Any]] = None) -> str:
+ """Header NAME declared as ``session_affinity_header`` on the route-matching entry, else "".
- want_p = str(provider or "").strip().lower()
- target_url = normalize_route_base_url(base_url) if base_url else ""
-
- for entry in custom_providers:
- if not isinstance(entry, dict):
- continue
+ Opt-in per provider (default off): Hermes never ships a session identifier to an endpoint
+ that did not ask for one (#86241).
+ """
+ for entry in _entries_for_route(base_url, custom_providers, config):
header = entry.get("session_affinity_header")
- if not (isinstance(header, str) and header.strip()):
- continue
- header_clean = header.strip()
-
- if want_p:
- entry_p = str(entry.get("provider_key") or "").strip().lower()
- entry_n = str(entry.get("name") or "").strip().lower()
- if want_p == entry_p or want_p == entry_n:
- return header_clean
-
- if target_url:
- entry_url = normalize_route_base_url(entry.get("base_url"))
- if entry_url and entry_url == target_url:
- return header_clean
-
- return None
+ if isinstance(header, str) and header.strip():
+ return header.strip()
+ return ""
def get_custom_provider_context_length(
diff --git a/tests/agent/test_session_affinity_header.py b/tests/agent/test_session_affinity_header.py
index 4013e7f908e..896ff57fecb 100644
--- a/tests/agent/test_session_affinity_header.py
+++ b/tests/agent/test_session_affinity_header.py
@@ -1,172 +1,62 @@
-"""Tests for per-provider session_affinity_header in agent and auxiliary requests.
+"""Per-provider ``session_affinity_header`` (#86241, #104449).
-Closes #104449: custom gateways (such as LiteLLM x-litellm-session-id) receive
-the turn's affinity scope to pin requests to warm prompt caches.
+A custom provider entry may name a header that carries Hermes' conversation id so a
+session-aware proxy can correlate the requests of one agent loop. Off unless configured.
"""
from __future__ import annotations
from unittest.mock import patch
-import pytest
from agent import auxiliary_client as aux
from agent.chat_completion_helpers import build_api_kwargs
-from hermes_cli.config_providers import (
- _normalize_custom_provider_entry,
- get_custom_provider_session_affinity_header,
-)
from run_agent import AIAgent
_MSGS = [{"role": "user", "content": "hello"}]
+_BASE = "http://localhost:4000/v1"
+_HEADER = "x-litellm-session-id"
-def _agent(provider, model, base_url, api_mode=None, session_id="sess-affinity-test-1"):
+def _agent(session_id, api_mode="chat_completions"):
agent = AIAgent(
- api_key="test-key",
- base_url=base_url,
- model=model,
- provider=provider,
- quiet_mode=True,
- skip_context_files=True,
- skip_memory=True,
+ api_key="test-key", base_url=_BASE, model="claude-3-5-sonnet", provider="litellm-lan",
+ api_mode=api_mode, quiet_mode=True, skip_context_files=True, skip_memory=True,
session_id=session_id,
)
- if api_mode:
- agent.api_mode = api_mode
- agent._transport = None
- agent._anthropic_base_url = base_url
+ agent._anthropic_base_url = _BASE
return agent
-def test_normalization_and_camel_case_alias():
- entry = _normalize_custom_provider_entry(
- {
- "name": "litellm-lan",
- "base_url": "http://localhost:4000/v1",
- "sessionAffinityHeader": "x-litellm-session-id",
- }
- )
- assert entry is not None
- assert entry.get("session_affinity_header") == "x-litellm-session-id"
-
-
-def test_lookup_by_provider_or_base_url():
- custom_providers = [
- {
- "name": "litellm-lan",
- "provider_key": "litellm-lan",
- "base_url": "http://localhost:4000/v1",
- "session_affinity_header": "x-litellm-session-id",
- }
- ]
- # Matched by provider name
- assert (
- get_custom_provider_session_affinity_header(
- provider="litellm-lan", custom_providers=custom_providers
- )
- == "x-litellm-session-id"
- )
- # Matched by base_url
- assert (
- get_custom_provider_session_affinity_header(
- base_url="http://localhost:4000/v1", custom_providers=custom_providers
- )
- == "x-litellm-session-id"
- )
- # Unmatched
- assert (
- get_custom_provider_session_affinity_header(
- provider="unconfigured",
- base_url="http://other:8000/v1",
- custom_providers=custom_providers,
- )
- is None
- )
+def _providers(with_header: bool):
+ entry = {"name": "litellm-lan", "provider_key": "litellm-lan", "base_url": _BASE}
+ if with_header:
+ entry["session_affinity_header"] = _HEADER
+ return patch("hermes_cli.config.get_compatible_custom_providers", return_value=[entry])
-def test_main_turn_sends_session_affinity_header():
- mock_providers = [
- {
- "name": "litellm-lan",
- "provider_key": "litellm-lan",
- "base_url": "http://localhost:4000/v1",
- "session_affinity_header": "x-litellm-session-id",
- }
- ]
- agent = _agent("litellm-lan", "claude-3-5-sonnet", "http://localhost:4000/v1")
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=mock_providers,
- ):
- kwargs = build_api_kwargs(agent, _MSGS)
- extra = kwargs.get("extra_headers") or {}
- assert extra.get("x-litellm-session-id") == "sess-affinity-test-1"
-
-
-def test_auxiliary_call_inherits_session_affinity_header():
- mock_providers = [
- {
- "name": "litellm-lan",
- "provider_key": "litellm-lan",
- "base_url": "http://localhost:4000/v1",
- "session_affinity_header": "x-litellm-session-id",
- }
- ]
- token = aux.set_runtime_main(
- "litellm-lan",
- "claude-3-5-sonnet",
- base_url="http://localhost:4000/v1",
- session_id="sess-affinity-test-1",
- )
+def _aux_headers(session_id):
+ token = aux.set_runtime_main("litellm-lan", "claude-3-5-sonnet", base_url=_BASE, session_id=session_id)
try:
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=mock_providers,
- ):
- kwargs = aux._build_call_kwargs(
- "litellm-lan",
- "claude-3-5-sonnet",
- _MSGS,
- base_url="http://localhost:4000/v1",
- )
- extra = kwargs.get("extra_headers") or {}
- assert extra.get("x-litellm-session-id") == "sess-affinity-test-1"
+ return aux._build_call_kwargs("litellm-lan", "claude-3-5-sonnet", _MSGS, base_url=_BASE).get("extra_headers") or {}
finally:
aux._RUNTIME_MAIN_CONTEXT.reset(token)
-def test_unconfigured_custom_provider_does_not_inject_header():
- mock_providers = [
- {
- "name": "plain-proxy",
- "base_url": "http://localhost:5000/v1",
- }
- ]
- agent = _agent("plain-proxy", "model-a", "http://localhost:5000/v1")
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=mock_providers,
- ):
- kwargs = build_api_kwargs(agent, _MSGS)
- extra = kwargs.get("extra_headers") or {}
- assert "x-litellm-session-id" not in extra
- assert "x-opencode-session" not in extra
-
-
-def test_caller_pinned_header_wins():
- mock_providers = [
- {
- "name": "litellm-lan",
- "base_url": "http://localhost:4000/v1",
- "session_affinity_header": "x-litellm-session-id",
- }
- ]
- agent = _agent("litellm-lan", "claude-3-5-sonnet", "http://localhost:4000/v1")
- agent.request_overrides = {"extra_headers": {"x-litellm-session-id": "pinned-by-caller"}}
- with patch(
- "hermes_cli.config.get_compatible_custom_providers",
- return_value=mock_providers,
- ):
- kwargs = build_api_kwargs(agent, _MSGS)
- extra = kwargs.get("extra_headers") or {}
- assert extra.get("x-litellm-session-id") == "pinned-by-caller"
+def test_configured_header_carries_one_value_per_conversation_on_every_path():
+ with _providers(True):
+ chat = build_api_kwargs(_agent("sess-A"), _MSGS)["extra_headers"][_HEADER]
+ anthropic = build_api_kwargs(_agent("sess-A", api_mode="anthropic_messages"), _MSGS)["extra_headers"][_HEADER]
+ assert chat == anthropic == _aux_headers("sess-A")[_HEADER] == "sess-A"
+ assert build_api_kwargs(_agent("sess-B"), _MSGS)["extra_headers"][_HEADER] == "sess-B"
+ # A caller-pinned value is preserved.
+ pinned = _agent("sess-A")
+ pinned.request_overrides = {"extra_headers": {_HEADER: "pinned-by-caller"}}
+ assert build_api_kwargs(pinned, _MSGS)["extra_headers"][_HEADER] == "pinned-by-caller"
+
+
+def test_unconfigured_provider_sends_no_session_header():
+ with _providers(False):
+ for agent in (_agent("sess-A"), _agent("sess-A", api_mode="anthropic_messages")):
+ headers = build_api_kwargs(agent, _MSGS).get("extra_headers") or {}
+ assert _HEADER not in headers and "x-opencode-session" not in headers
+ assert _HEADER not in _aux_headers("sess-A")
diff --git a/website/docs/integrations/providers.md b/website/docs/integrations/providers.md
index 785dbb8256d..f51b5ae9363 100644
--- a/website/docs/integrations/providers.md
+++ b/website/docs/integrations/providers.md
@@ -1344,7 +1344,7 @@ providers:
transport: anthropic_messages # for Anthropic-compatible proxies
```
-Each entry accepts: `api` (the endpoint base URL — `base_url`/`url` are accepted aliases), `name` (optional display name; defaults to the dict key), `key_env` or inline `api_key` or `key_cmd` (see below), `transport` (`chat_completions` / `anthropic_messages` / `codex_responses`), `default_model`, `models`, `context_length`, `discover_models`, `extra_body`, `extra_headers`, `ssl_ca_cert` / `ssl_verify`, `catalog_provider` (see below), and `enabled: false` to hide an entry without deleting it.
+Each entry accepts: `api` (the endpoint base URL — `base_url`/`url` are accepted aliases), `name` (optional display name; defaults to the dict key), `key_env` or inline `api_key` or `key_cmd` (see below), `transport` (`chat_completions` / `anthropic_messages` / `codex_responses`), `default_model`, `models`, `context_length`, `discover_models`, `extra_body`, `extra_headers`, `session_affinity_header` (name of a header that carries the conversation id, for session-aware proxies; off unless set), `ssl_ca_cert` / `ssl_verify`, `catalog_provider` (see below), and `enabled: false` to hide an entry without deleting it.
#### Command-minted credentials (`key_cmd`)
diff --git a/website/docs/user-guide/configuring-models.md b/website/docs/user-guide/configuring-models.md
index 94345b2d619..645ea368b93 100644
--- a/website/docs/user-guide/configuring-models.md
+++ b/website/docs/user-guide/configuring-models.md
@@ -194,6 +194,16 @@ providers:
Header values routinely carry credentials — Hermes never logs them. `extra_headers` applies to OpenAI-compatible routes; the `anthropic_messages` and `bedrock_converse` API modes do not use it.
+**`session_affinity_header`** — the NAME of a header that carries Hermes' conversation id on every request to that provider (main turn on `chat_completions`, `anthropic_messages` and `codex_responses`, plus auxiliary calls such as compression and titles). Off unless set — Hermes never sends a session identifier to an endpoint that did not ask for one. Session-aware proxies fronting a stateful backend (LiteLLM's `x-litellm-session-id`, self-hosted Claude/OpenAI gateways) otherwise have nothing to correlate an agent loop on and treat nearly every request as a new conversation, re-sending the whole history upstream on each turn. The value is opaque, stable across the turns of one conversation (including compaction), and different for every conversation:
+
+```yaml
+providers:
+ my-proxy:
+ api: http://127.0.0.1:4000/v1
+ api_key: sk-...
+ session_affinity_header: x-litellm-session-id
+```
+
**`discover_models`** — set to `false` (default `true`) to skip querying the endpoint's `/models` listing and use only the `models` you configured on the entry. Handy for gateways whose model listing is slow, unreliable, or noisy:
```yaml