The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(aux): keep the /btw and title snapshots duck-typed; make the out-of-turn header tests discriminating
teknium16f8389d67bfd
diff --git a/agent/turn_context.py b/agent/turn_context.pyindex 1a9e7bbedb6..1847ccd71cf 100644--- a/agent/turn_context.py+++ b/agent/turn_context.py@@ -182,7 +182,12 @@ def _maybe_title_session_at_turn_start(agent: Any, messages: List[Any]) -> None:return# Snapshot runtime identity so the background titler can skip if the user# switches models before it fires.- main_runtime = agent._current_main_runtime()+ # ``session_id`` rides along so the background titler's OpenCode request carries the+ # same ``x-opencode-session`` affinity as the turn it belongs to (#112717).+ main_runtime = {+ k: getattr(agent, k, None)+ for k in ("model", "provider", "base_url", "api_key", "api_mode", "session_id")+ }# See #19027.maybe_auto_title(session_db,diff --git a/tests/agent/test_opencode_session_affinity.py b/tests/agent/test_opencode_session_affinity.pyindex 6b500afd052..e38eaa70b11 100644--- a/tests/agent/test_opencode_session_affinity.py+++ b/tests/agent/test_opencode_session_affinity.py@@ -2,12 +2,12 @@from __future__ import annotations+import asynciofrom types import SimpleNamespaceimport pytestfrom agent import auxiliary_client as aux-from agent import title_generator, turn_contextfrom agent.chat_completion_helpers import build_api_kwargsfrom run_agent import AIAgent@@ -65,54 +65,69 @@ def test_auxiliary_calls_share_the_main_turn_session_key():aux._RUNTIME_MAIN_CONTEXT.reset(token)-def test_auto_title_uses_explicit_main_runtime_session(monkeypatch):- captured = {}+def out_of_turn():+ """No ambient turn context: runtime binding, conversation root and declared affinity scope all unset.- class Completions:- def create(self, **kwargs):- captured.update(kwargs)- return SimpleNamespace(- choices=[SimpleNamespace(message=SimpleNamespace(content="ok"))],- model="glm-5",- )+ Earlier AIAgent-driven tests in this process can leave those contextvars set, which would hand the+ header to an unfixed tree through ``get_conversation_context()`` instead of the explicit runtime."""+ from agent import portal_tags- client = SimpleNamespace(- chat=SimpleNamespace(completions=Completions()),- base_url="https://opencode.ai/zen/v1",+ tokens = (+ aux._RUNTIME_MAIN_CONTEXT.set(None),+ portal_tags.set_conversation_context(None),+ portal_tags.set_affinity_scope(None),)- monkeypatch.setattr(- aux,- "_resolve_task_provider_model",- lambda *_args, **_kwargs: (- "opencode-zen", "glm-5", "https://opencode.ai/zen/v1", "test-key", None,- ),- )- monkeypatch.setattr(aux, "_get_cached_client", lambda *_args, **_kwargs: (client, "glm-5"))- monkeypatch.setattr(title_generator, "_auto_title_enabled", lambda: True)- monkeypatch.setattr(title_generator, "_kanban_task_title", lambda: None)- monkeypatch.setattr(title_generator, "apply_instant_title", lambda *_args, **_kwargs: None)-- def spawn_immediately(target, *, name, args, kwargs):- def start():- token = aux._RUNTIME_MAIN_CONTEXT.set(None)- try:- target(*args, **kwargs)- finally:- aux._RUNTIME_MAIN_CONTEXT.reset(token)-- return SimpleNamespace(start=start)-- monkeypatch.setattr("agent.memory_provider.spawn_context_thread", spawn_immediately)-- session_db = SimpleNamespace(- get_session_title_source=lambda _session_id: None,- get_conversation_root=lambda session_id: session_id,- set_auto_title=lambda *_args, **_kwargs: True,+ try:+ yield+ finally:+ aux._RUNTIME_MAIN_CONTEXT.reset(tokens[0])+ portal_tags.reset_conversation_context(tokens[1])+ portal_tags.reset_affinity_scope(tokens[2])+++_OPENCODE_RUNTIME = {+ "provider": "opencode-zen", "model": "glm-5", "base_url": "https://opencode.ai/zen/v1",+ "api_key": "test-key", "session_id": "sess-affinity-1",+}+++def _route_to_fake_opencode_client(monkeypatch, captured, *, async_mode):+ """Pin the aux resolver on an OpenCode route served by a fake SDK client that records its kwargs."""+ if async_mode:+ async def create(**kwargs):+ captured.update(kwargs)+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content="ok"))], model="glm-5")+ else:+ def create(**kwargs):+ captured.update(kwargs)+ return SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content="ok"))], model="glm-5")+ client = SimpleNamespace(+ chat=SimpleNamespace(completions=SimpleNamespace(create=create)), base_url="https://opencode.ai/zen/v1",)- agent = _agent("opencode-zen", "glm-5", "https://opencode.ai/zen/v1")- agent._session_db = session_db- agent._session_db_created = True+ monkeypatch.setattr(aux, "_resolve_task_provider_model",+ lambda *_a, **_k: ("opencode-zen", "glm-5", "https://opencode.ai/zen/v1", "test-key", None))+ monkeypatch.setattr(aux, "_get_cached_client", lambda *_a, **_k: (client, "glm-5"))+++def test_sync_out_of_turn_call_binds_the_explicit_main_runtime_session(monkeypatch, out_of_turn):+ """#112717: a background/out-of-turn ``call_llm(main_runtime=...)`` (title, approval, skills hub,+ ``/btw``) must send the conversation's ``x-opencode-session`` exactly like the main turn does."""+ captured = {}+ _route_to_fake_opencode_client(monkeypatch, captured, async_mode=False)++ aux.call_llm(task="title_generation", main_runtime=_OPENCODE_RUNTIME, messages=_MSGS)++ assert captured["extra_headers"]["x-opencode-session"] == "sess-affinity-1"+ assert aux._RUNTIME_MAIN_CONTEXT.get() is None # the explicit binding does not leak past the call+++def test_async_out_of_turn_call_binds_the_explicit_main_runtime_session(monkeypatch, out_of_turn):+ """Same contract on the async twin (#112717)."""+ captured = {}+ _route_to_fake_opencode_client(monkeypatch, captured, async_mode=True)- turn_context._maybe_title_session_at_turn_start(agent, _MSGS)+ asyncio.run(aux.async_call_llm(task="approval", main_runtime=_OPENCODE_RUNTIME, messages=_MSGS))assert captured["extra_headers"]["x-opencode-session"] == "sess-affinity-1"+ assert aux._RUNTIME_MAIN_CONTEXT.get() is Nonediff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.pyindex 098a2b5c521..a0b7607a174 100644--- a/tui_gateway/methods_prompt.py+++ b/tui_gateway/methods_prompt.py@@ -1012,7 +1012,9 @@ def _(rid, params: dict) -> dict:return erragent = session.get("agent")snapshot = list(getattr(agent, "_session_messages", None) or session.get("history") or [])- main_runtime = agent._current_main_runtime()+ main_runtime = {+ k: getattr(agent, k, None)+ for k in ("model", "provider", "base_url", "api_key", "api_mode", "session_id")}def body():from agent.side_question import answer_side_questiondiff --git a/website/docs/integrations/providers.md b/website/docs/integrations/providers.mdindex c5dd1989ad6..18d7fdca43f 100644--- a/website/docs/integrations/providers.md+++ b/website/docs/integrations/providers.md@@ -61,7 +61,7 @@ You need at least one way to connect to an LLM. Use `hermes model` to switch pro| **LM Studio** | `hermes model` → "LM Studio" (provider: `lmstudio`, optional `LM_API_KEY`) || **Custom Endpoint** | `hermes model` → choose "Custom endpoint" (saved in `config.yaml`) |-All three OpenCode providers send an opaque, per-conversation `x-opencode-session` header on every request (main turns on every transport plus auxiliary calls such as compression and titles; headless Kanban `specify`/`decompose` and dashboard estimate calls use a per-task key). OpenCode uses it to pin a conversation to one backend so its prompt cache stays warm; the value is derived from the Hermes session id (or the Kanban task id) and carries no personal data.+All three OpenCode providers send an opaque, per-conversation `x-opencode-session` header on every request (main turns on every transport plus auxiliary calls such as compression, titles, approval checks, skills-hub lookups and `/btw` side questions — including the ones that run in the background after the turn has ended; headless Kanban `specify`/`decompose` and dashboard estimate calls use a per-task key). OpenCode uses it to pin a conversation to one backend so its prompt cache stays warm; the value is derived from the Hermes session id (or the Kanban task id) and carries no personal data.For the official API-key path, see the dedicated [Google Gemini guide](/guides/google-gemini).