Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(providers): add OpenCode provider and send x-opencode-session

Antonio999c3a7f9b8e
diff --git a/README.md b/README.md
index 0d02e46c1..669635069 100644
--- a/README.md
+++ b/README.md
@@ -831,7 +831,7 @@ vibe-trading-mcp # start MCP server (stdio)
- OpenAI Codex can also be used with ChatGPT OAuth: set `LANGCHAIN_PROVIDER=openai-codex`, then run `vibe-trading provider login openai-codex`. This does not use `OPENAI_API_KEY`.
- GitHub Copilot can be used with an active Copilot subscription instead of a separately billed LLM API key. See [GitHub Copilot SDK provider](#github-copilot-sdk-provider).
-> **Supported LLM providers:** OpenRouter, Requesty, OpenAI, Anthropic (native Messages API), DeepSeek, Gemini, Groq, DashScope/Qwen, Zhipu, Moonshot/Kimi, MiniMax, SiliconFlow (CN + Global), Xiaomi MIMO, Novita AI, iFlytek Spark, Z.ai, NVIDIA NIM, ModelScope, GitHub Copilot, Ollama (local). When no `*_BASE_URL` is set, each provider falls back to its canonical endpoint, so just a key is enough. See `.env.example` for config.
+> **Supported LLM providers:** OpenRouter, Requesty, OpenAI, Anthropic (native Messages API), DeepSeek, OpenCode (Go / Zen), Gemini, Groq, DashScope/Qwen, Zhipu, Moonshot/Kimi, MiniMax, SiliconFlow (CN + Global), Xiaomi MIMO, Novita AI, iFlytek Spark, Z.ai, NVIDIA NIM, ModelScope, GitHub Copilot, Ollama (local). When no `*_BASE_URL` is set, each provider falls back to its canonical endpoint, so just a key is enough. See `.env.example` for config.
> **Tip:** All markets work without any API keys thanks to automatic fallback. yfinance/Yahoo (HK/US/Canada/UK), OKX (crypto), mootdx (A-shares, TCP-direct, no IP throttle), and AKShare (A-shares, US, HK, futures, forex) are all free. LSE `.L` quotes must declare GBP or GBp so pence can be normalized before GBP accounting. Tushare token is optional — mootdx is the preferred no-token A-share fallback, with AKShare as a broader backup.
diff --git a/agent/.env.example b/agent/.env.example
index a23f22bbe..79ca7ed84 100644
--- a/agent/.env.example
+++ b/agent/.env.example
@@ -60,6 +60,15 @@ OPENROUTER_BASE_URL=https://openrouter.ai/api/v1
# pip install "vibe-trading-ai[deepseek]"
# VIBE_TRADING_DEEPSEEK_ADAPTER=auto
+# --- OpenCode (Go / Zen) ---
+# One key for DeepSeek, GLM, Kimi, Qwen and more via https://opencode.ai.
+# Go requires a per-conversation x-opencode-session header; Vibe-Trading sends
+# the active session id automatically. Use https://opencode.ai/zen/v1 for Zen.
+# LANGCHAIN_PROVIDER=opencode
+# LANGCHAIN_MODEL_NAME=deepseek-v4.1-flash
+# OPENCODE_API_KEY=sk-xxx
+# OPENCODE_BASE_URL=https://opencode.ai/zen/go/v1
+
# --- NVIDIA NIM (hosted API catalog) ---
# LANGCHAIN_PROVIDER=nvidia
# LANGCHAIN_MODEL_NAME=nvidia/nemotron-3-ultra-550b-a55b
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index c0befd8b1..d31d8f8f0 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -5569,6 +5569,16 @@ _PROVIDER_CHOICES: list[dict[str, str | None]] = [
"key_prefix": "sk-",
"key_placeholder": "sk-...",
},
+ {
+ "label": "OpenCode (Go / Zen)",
+ "provider": "opencode",
+ "key_env": "OPENCODE_API_KEY",
+ "base_env": "OPENCODE_BASE_URL",
+ "base_url": "https://opencode.ai/zen/go/v1",
+ "model": "deepseek-v4.1-flash",
+ "key_prefix": "sk-",
+ "key_placeholder": "sk-...",
+ },
{
"label": "SiliconFlow (CN)",
"provider": "siliconflow-cn",
diff --git a/agent/cli/onboard.py b/agent/cli/onboard.py
index 1b217c914..366913548 100644
--- a/agent/cli/onboard.py
+++ b/agent/cli/onboard.py
@@ -80,6 +80,10 @@ PROVIDERS: Final[tuple[Provider, ...]] = (
"deepseek-v4-pro", "DEEPSEEK_API_KEY", "DEEPSEEK_BASE_URL",
"https://api.deepseek.com/v1", "sk-",
("deepseek-v4-pro", "deepseek-v4-flash")),
+ Provider("opencode", "OpenCode", "Go / Zen relay — DeepSeek, GLM, Kimi, Qwen under one key",
+ "deepseek-v4.1-flash", "OPENCODE_API_KEY", "OPENCODE_BASE_URL",
+ "https://opencode.ai/zen/go/v1", "sk-",
+ ("deepseek-v4.1-flash", "deepseek-v4-pro", "glm-5.3-flash")),
Provider("siliconflow-cn", "SiliconFlow (CN)", "OpenAI-compatible MaaS endpoint in China",
"deepseek-ai/DeepSeek-V3.1-Terminus",
"SILICONFLOW_API_KEY", "SILICONFLOW_BASE_URL",
diff --git a/agent/src/agent/loop.py b/agent/src/agent/loop.py
index 2e61814d0..57bad15f0 100644
--- a/agent/src/agent/loop.py
+++ b/agent/src/agent/loop.py
@@ -42,6 +42,7 @@ from src.goal.context import (
goal_progress_tuple,
)
from src.providers.chat import ChatLLM, LLMRuntimeSnapshot, ProviderStreamError
+from src.providers.session_context import bind_llm_session_id, reset_llm_session_id
from src.providers.content_filter import (
CONTENT_FILTER_SKIP_MESSAGE,
MAX_CONSECUTIVE_CONTENT_FILTER_SKIPS,
@@ -1181,6 +1182,27 @@ class AgentLoop:
def run(self, user_message: str, history: Optional[List[Dict[str, Any]]] = None, session_id: str = "") -> Dict[str, Any]:
"""Run the ReAct loop synchronously.
+ Binds ``session_id`` as the active LLM session for the whole run so
+ provider adapters that need a stable per-conversation identity
+ (OpenCode Go's ``x-opencode-session``) can read it at request time.
+
+ Args:
+ user_message: User message.
+ history: Prior conversation messages.
+ session_id: Session ID.
+
+ Returns:
+ Execution result dict.
+ """
+ token = bind_llm_session_id(session_id)
+ try:
+ return self._run_bound(user_message, history, session_id)
+ finally:
+ reset_llm_session_id(token)
+
+ def _run_bound(self, user_message: str, history: Optional[List[Dict[str, Any]]] = None, session_id: str = "") -> Dict[str, Any]:
+ """Run the ReAct loop with the LLM session already bound.
+
Args:
user_message: User message.
history: Prior conversation messages.
diff --git a/agent/src/providers/capabilities.py b/agent/src/providers/capabilities.py
index 46fc1b6ca..03e6fce85 100644
--- a/agent/src/providers/capabilities.py
+++ b/agent/src/providers/capabilities.py
@@ -111,6 +111,21 @@ _NVIDIA_CAPABILITIES = ProviderCapabilities(
default_headers={"User-Agent": _VIBE_USER_AGENT},
)
+
+# OpenCode Go / Zen relay (opencode.ai). Speaks the OpenAI wire format and
+# serves DeepSeek/GLM/Kimi models that stream ``reasoning_content``. OpenCode
+# Go additionally requires a stable per-conversation ``x-opencode-session``
+# header (400 ``MissingSessionID`` without it); that value depends on the
+# active session and is injected at request time in ``llm.py``. The
+# User-Agent is the client identification the service asks for.
+_OPENCODE_CAPABILITIES = ProviderCapabilities(
+ "opencode",
+ "OPENCODE_API_KEY",
+ "OPENCODE_BASE_URL",
+ capture_reasoning=True,
+ default_headers={"User-Agent": _VIBE_USER_AGENT},
+)
+
# GLM thinking models (glm-4.5+/glm-5.x) stream the chain-of-thought as
# ``reasoning_content`` with the final answer in ``content``. Capture the
# reasoning like DeepSeek; do NOT replay it on assistant turns —
@@ -236,6 +251,7 @@ _PROVIDERS: dict[str, ProviderCapabilities] = {
"github-copilot": _COPILOT_CAPABILITIES,
"openai-codex": _OPENAI_CODEX_CAPABILITIES,
"openai_codex": _OPENAI_CODEX_CAPABILITIES,
+ "opencode": _OPENCODE_CAPABILITIES,
"opencode-zen": ProviderCapabilities(
"opencode-zen", "OPENAI_API_KEY", "OPENAI_BASE_URL"
),
diff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.py
index 526254800..42695cd6c 100644
--- a/agent/src/providers/llm.py
+++ b/agent/src/providers/llm.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import logging
import os
+import uuid
from copy import copy
from urllib.parse import urlparse
import re
@@ -17,6 +18,7 @@ from urllib.parse import urlsplit
from pydantic import PrivateAttr
from src.config.accessor import get_env_config, reset_env_config
+from src.providers.session_context import current_llm_session_id
from src.providers.capabilities import (
ProviderCapabilities,
get_llm_credentials,
@@ -70,6 +72,27 @@ def _build_proxy_free_http_clients() -> tuple[Any, Any]:
)
+_OPENCODE_PROVIDER_NAMES = frozenset({"opencode", "opencode-go", "opencode-zen"})
+_OPENCODE_SESSION_HEADER = "x-opencode-session"
+
+
+def _targets_opencode(provider: str | None, base_url: str | None) -> bool:
+ """Report whether requests go to the OpenCode relay.
+
+ True for the ``opencode*`` provider names and for any provider whose base
+ URL points at ``opencode.ai`` (e.g. ``deepseek`` re-pointed at the Go
+ endpoint), so the session header follows the endpoint, not the label.
+ """
+ normalized = (provider or "").strip().lower().replace("_", "-")
+ if normalized in _OPENCODE_PROVIDER_NAMES:
+ return True
+ raw = (base_url or "").strip()
+ if not raw:
+ return False
+ host = (urlparse(raw if "//" in raw else f"https://{raw}").hostname or "").lower()
+ return host == "opencode.ai" or host.endswith(".opencode.ai")
+
+
_AMBIENT_OPENAI_HEADER_ENV_VARS = (
"OPENAI_CUSTOM_HEADERS",
"OPENAI_ORG_ID",
@@ -266,6 +289,7 @@ if ChatOpenAI is not None:
_vibe_ambient_header_names: tuple[str, ...] = PrivateAttr(default=())
_vibe_has_explicit_authorization: bool = PrivateAttr(default=False)
_vibe_owned_http_clients: tuple[Any, ...] = PrivateAttr(default=())
+ _vibe_fallback_session_id: str = PrivateAttr(default="")
def __init__(
self,
@@ -290,6 +314,10 @@ if ChatOpenAI is not None:
self._vibe_provider = vibe_provider
self._vibe_api_key = vibe_api_key or ""
self._vibe_owned_http_clients = tuple(vibe_owned_http_clients or ())
+ # One id per adapter: outside a bound Vibe session (swarm workers,
+ # scheduled research, CLI) every request from this adapter still
+ # shares a stable conversation identity.
+ self._vibe_fallback_session_id = uuid.uuid4().hex
self._vibe_ambient_header_names = tuple(
name for name in ambient_names if name not in explicit_names
)
@@ -297,6 +325,21 @@ if ChatOpenAI is not None:
"authorization" in explicit_names_lower
)
+ def _opencode_session_headers(self) -> dict[str, str]:
+ """Return the ``x-opencode-session`` header for opencode.ai relays.
+
+ OpenCode Go rejects requests without a stable per-conversation id
+ (400 ``MissingSessionID``) and uses it for routing and prompt
+ caching. The agent loop binds the active Vibe session id via
+ ``src.providers.session_context``; the per-adapter fallback keeps
+ one conversation stable when no session is bound.
+ """
+ base_url = getattr(self, "openai_api_base", None)
+ if not _targets_opencode(self._vibe_provider, base_url):
+ return {}
+ session_id = current_llm_session_id() or self._vibe_fallback_session_id
+ return {_OPENCODE_SESSION_HEADER: session_id} if session_id else {}
+
def _provider_scoped_extra_headers(self) -> dict[str, Any]:
"""Remove ambient OpenAI-only headers from named relay requests."""
provider = (self._vibe_provider or "").strip().lower()
@@ -720,6 +763,17 @@ if ChatOpenAI is not None:
if isinstance(existing_headers, Mapping):
scoped_headers.update(existing_headers)
payload["extra_headers"] = scoped_headers
+ session_headers = self._opencode_session_headers()
+ if session_headers:
+ existing_headers = payload.get("extra_headers")
+ merged: dict[str, Any] = (
+ dict(existing_headers) if isinstance(existing_headers, Mapping) else {}
+ )
+ present = {str(name).lower() for name in merged}
+ for name, value in session_headers.items():
+ if name.lower() not in present:
+ merged[name] = value
+ payload["extra_headers"] = merged
return payload
else:
diff --git a/agent/src/providers/llm_providers.json b/agent/src/providers/llm_providers.json
index d13a869ce..b9417f96c 100644
--- a/agent/src/providers/llm_providers.json
+++ b/agent/src/providers/llm_providers.json
@@ -55,6 +55,19 @@
"default_base_url": "https://api.deepseek.com/v1",
"api_key_required": true
},
+ {
+ "name": "opencode",
+ "label": "OpenCode (Go / Zen)",
+ "api_key_env": "OPENCODE_API_KEY",
+ "base_url_env": "OPENCODE_BASE_URL",
+ "default_model": "deepseek-v4.1-flash",
+ "default_base_url": "https://opencode.ai/zen/go/v1",
+ "base_url_options": [
+ "https://opencode.ai/zen/go/v1",
+ "https://opencode.ai/zen/v1"
+ ],
+ "api_key_required": true
+ },
{
"name": "siliconflow-cn",
"label": "SiliconFlow (CN)",
diff --git a/agent/src/providers/session_context.py b/agent/src/providers/session_context.py
new file mode 100644
index 000000000..9e31965ad
--- /dev/null
+++ b/agent/src/providers/session_context.py
@@ -0,0 +1,39 @@
+"""Per-conversation LLM session identity.
+
+Some relays require a stable per-conversation identifier on every request.
+OpenCode Go rejects calls that lack ``x-opencode-session`` (HTTP 400
+``MissingSessionID``) because it uses the id for routing and prompt caching.
+
+The agent loop binds the active Vibe session id here for the duration of a
+run; provider adapters read it at request time. A ``ContextVar`` keeps the
+binding thread- and task-local, so concurrent sessions never see each other's
+id and nothing has to be threaded through every LangChain call site.
+"""
+
+from __future__ import annotations
+
+from contextvars import ContextVar, Token
+
+_LLM_SESSION_ID: ContextVar[str] = ContextVar("vibe_llm_session_id", default="")
+
+
+def bind_llm_session_id(session_id: str | None) -> Token[str]:
+ """Bind ``session_id`` as the active LLM session in the current context.
+
+ Args:
+ session_id: Vibe session id; empty or ``None`` clears the binding.
+
+ Returns:
+ Token to pass to :func:`reset_llm_session_id` when the run ends.
+ """
+ return _LLM_SESSION_ID.set((session_id or "").strip())
+
+
+def reset_llm_session_id(token: Token[str]) -> None:
+ """Restore the binding that was active before :func:`bind_llm_session_id`."""
+ _LLM_SESSION_ID.reset(token)
+
+
+def current_llm_session_id() -> str:
+ """Return the active LLM session id, or ``""`` outside a bound run."""
+ return _LLM_SESSION_ID.get()
diff --git a/agent/src/swarm/models.py b/agent/src/swarm/models.py
index 4e1205e8d..8c01ece8f 100644
--- a/agent/src/swarm/models.py
+++ b/agent/src/swarm/models.py
@@ -38,6 +38,7 @@ _PUBLIC_PROVIDERS = frozenset(
"openai",
"openai-codex",
"openai_codex",
+ "opencode",
"opencode-go",
"opencode-zen",
"openrouter",
diff --git a/agent/tests/test_opencode_provider.py b/agent/tests/test_opencode_provider.py
new file mode 100644
index 000000000..6dede44f1
--- /dev/null
+++ b/agent/tests/test_opencode_provider.py
@@ -0,0 +1,279 @@
+"""OpenCode Go / Zen provider: catalog entry and x-opencode-session header."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import httpx
+import pytest
+
+from src.providers.capabilities import get_llm_credentials, get_provider_capabilities
+from src.providers.llm import ChatOpenAIWithReasoning, _targets_opencode
+from src.providers.session_context import (
+ bind_llm_session_id,
+ current_llm_session_id,
+ reset_llm_session_id,
+)
+
+_PROVIDERS_JSON = (
+ Path(__file__).resolve().parents[1] / "src" / "providers" / "llm_providers.json"
+)
+_GO_URL = "https://opencode.ai/zen/go/v1"
+
+
+def _completion_body(model: str) -> dict:
+ return {
+ "id": "chatcmpl-test",
+ "object": "chat.completion",
+ "created": 0,
+ "model": model,
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": "ok"},
+ "finish_reason": "stop",
+ }
+ ],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ }
+
+
+# ---------------------------------------------------------------------------
+# Registration surfaces
+# ---------------------------------------------------------------------------
+
+
+def test_catalog_lists_opencode_with_go_default_and_zen_option() -> None:
+ catalog = {
+ item["name"]: item
+ for item in json.loads(_PROVIDERS_JSON.read_text(encoding="utf-8"))
+ }
+ entry = catalog["opencode"]
+ assert entry["api_key_env"] == "OPENCODE_API_KEY"
+ assert entry["base_url_env"] == "OPENCODE_BASE_URL"
+ assert entry["default_base_url"] == _GO_URL
+ assert "https://opencode.ai/zen/v1" in entry["base_url_options"]
+ assert entry["api_key_required"] is True
+
+
+def test_capabilities_resolve_opencode_provider() -> None:
+ caps = get_provider_capabilities("opencode", "deepseek-v4.1-flash")
+ assert caps.name == "opencode"
+ assert caps.api_key_env == "OPENCODE_API_KEY"
+ assert caps.base_url_env == "OPENCODE_BASE_URL"
+ assert caps.capture_reasoning is True
+ assert caps.default_headers["User-Agent"].startswith("Vibe-Trading/")
+
+
[email protected]("name", ["opencode-go", "opencode-zen"])
+def test_legacy_opencode_spellings_keep_openai_env(name: str) -> None:
+ """Upstream contract: the older names ride the OPENAI_* variables."""
+ caps = get_provider_capabilities(name, "deepseek-v4.1-flash")
+ assert caps.name == name
+ assert (caps.api_key_env, caps.base_url_env) == (
+ "OPENAI_API_KEY",
+ "OPENAI_BASE_URL",
+ )
+
+
+def test_credentials_fall_back_to_go_endpoint(monkeypatch: pytest.MonkeyPatch) -> None:
+ for var in (
+ "OPENCODE_BASE_URL",
+ "OPENAI_BASE_URL",
+ "OPENAI_API_BASE",
+ "OPENAI_API_KEY",
+ ):
+ monkeypatch.delenv(var, raising=False)
+ monkeypatch.setenv("OPENCODE_API_KEY", "sk-opencode-test")
+ creds = get_llm_credentials("opencode", "deepseek-v4.1-flash")
+ assert creds["api_key"] == "sk-opencode-test"
+ assert creds["base_url"] == _GO_URL
+
+
+def test_swarm_public_provider_allowlist_includes_opencode() -> None:
+ from src.swarm.models import _PUBLIC_PROVIDERS
+
+ assert "opencode" in _PUBLIC_PROVIDERS
+
+
+def test_cli_onboarding_surfaces_agree() -> None:
+ import cli
+ from cli.onboard import PROVIDERS
+
+ onboard = next(p for p in PROVIDERS if p.key == "opencode")
+ legacy = next(
+ item for item in cli._PROVIDER_CHOICES if item["provider"] == "opencode"
+ )
+ assert onboard.key_env == legacy["key_env"] == "OPENCODE_API_KEY"
+ assert onboard.base_env == legacy["base_env"] == "OPENCODE_BASE_URL"
+ assert onboard.base_url == legacy["base_url"] == _GO_URL
+ assert onboard.default_model == legacy["model"]
+
+
+# ---------------------------------------------------------------------------
+# Endpoint detection
+# ---------------------------------------------------------------------------
+
+
+ ("provider", "base_url", "expected"),
+ [
+ ("opencode", None, True),
+ ("opencode-go", "", True),
+ ("opencode_zen", "https://example.invalid/v1", True),
+ ("deepseek", _GO_URL, True),
+ ("openai", "https://opencode.ai/zen/v1", True),
+ ("openai", "opencode.ai/zen/go/v1", True),
+ ("deepseek", "https://api.deepseek.com/v1", False),
+ ("openai", "https://api.openai.com/v1", False),
+ ("openai", "https://notopencode.ai/v1", False),
+ ("openai", None, False),
+ ],
+)
+def test_targets_opencode(provider: str, base_url: str | None, expected: bool) -> None:
+ assert _targets_opencode(provider, base_url) is expected
+
+
+# ---------------------------------------------------------------------------
+# Session context
+# ---------------------------------------------------------------------------
+
+
+def test_session_binding_is_scoped_and_reset() -> None:
+ assert current_llm_session_id() == ""
+ token = bind_llm_session_id(" sess-1 ")
+ try:
+ assert current_llm_session_id() == "sess-1"
+ inner = bind_llm_session_id(None)
+ assert current_llm_session_id() == ""
+ reset_llm_session_id(inner)
+ assert current_llm_session_id() == "sess-1"
+ finally:
+ reset_llm_session_id(token)
+ assert current_llm_session_id() == ""
+
+
+# ---------------------------------------------------------------------------
+# Wire behaviour
+# ---------------------------------------------------------------------------
+
+pytestmark_wire = pytest.mark.skipif(
+ ChatOpenAIWithReasoning is None, reason="langchain-openai is not installed"
+)
+
+
+def _adapter(
+ client: httpx.Client, *, provider: str, base_url: str
+) -> ChatOpenAIWithReasoning:
+ return ChatOpenAIWithReasoning(
+ model="deepseek-v4.1-flash",
+ api_key="sk-test",
+ base_url=base_url,
+ temperature=0.0,
+ http_client=client,
+ default_headers={"User-Agent": "Vibe-Trading/test"},
+ vibe_provider=provider,
+ vibe_api_key="sk-test",
+ )
+
+
+@pytestmark_wire
+def test_bound_session_id_is_sent_to_opencode() -> None:
+ seen: list[httpx.Headers] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request.headers)
+ return httpx.Response(200, json=_completion_body("deepseek-v4.1-flash"))
+
+ token = bind_llm_session_id("vibe-session-42")
+ try:
+ with httpx.Client(transport=httpx.MockTransport(handler)) as client:
+ llm = _adapter(client, provider="opencode", base_url=_GO_URL)
+ assert llm.invoke("hello").content == "ok"
+ assert llm.invoke("hello again").content == "ok"
+ finally:
+ reset_llm_session_id(token)
+
+ assert len(seen) == 2
+ for headers in seen:
+ assert headers["x-opencode-session"] == "vibe-session-42"
+ assert headers["user-agent"].startswith("Vibe-Trading/")
+
+
+@pytestmark_wire
+def test_unbound_requests_share_a_stable_fallback_id() -> None:
+ seen: list[str] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request.headers["x-opencode-session"])
+ return httpx.Response(200, json=_completion_body("deepseek-v4.1-flash"))
+
+ assert current_llm_session_id() == ""
+ with httpx.Client(transport=httpx.MockTransport(handler)) as client:
+ first = _adapter(client, provider="opencode-go", base_url=_GO_URL)
+ first.invoke("a")
+ first.invoke("b")
+ second = _adapter(client, provider="opencode-go", base_url=_GO_URL)
+ second.invoke("c")
+
+ assert seen[0] == seen[1]
+ assert seen[2] != seen[0]
+ assert all(len(value) >= 16 for value in seen)
+
+
+@pytestmark_wire
+def test_deepseek_label_pointed_at_opencode_still_gets_header() -> None:
+ seen: list[httpx.Headers] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request.headers)
+ return httpx.Response(200, json=_completion_body("deepseek-v4.1-flash"))
+
+ token = bind_llm_session_id("legacy-config")
+ try:
+ with httpx.Client(transport=httpx.MockTransport(handler)) as client:
+ _adapter(client, provider="deepseek", base_url=_GO_URL).invoke("hi")
+ finally:
+ reset_llm_session_id(token)
+
+ assert seen[0]["x-opencode-session"] == "legacy-config"
+
+
+@pytestmark_wire
+def test_non_opencode_endpoints_do_not_get_header() -> None:
+ seen: list[httpx.Headers] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request.headers)
+ return httpx.Response(200, json=_completion_body("deepseek-v4.1-flash"))
+
+ token = bind_llm_session_id("should-not-leak")
+ try:
+ with httpx.Client(transport=httpx.MockTransport(handler)) as client:
+ _adapter(
+ client, provider="deepseek", base_url="https://api.deepseek.com/v1"
+ ).invoke("hi")
+ finally:
+ reset_llm_session_id(token)
+
+ assert "x-opencode-session" not in seen[0]
+
+
+@pytestmark_wire
+def test_explicit_extra_header_wins_over_injected_session() -> None:
+ seen: list[httpx.Headers] = []
+
+ def handler(request: httpx.Request) -> httpx.Response:
+ seen.append(request.headers)
+ return httpx.Response(200, json=_completion_body("deepseek-v4.1-flash"))
+
+ token = bind_llm_session_id("bound")
+ try:
+ with httpx.Client(transport=httpx.MockTransport(handler)) as client:
+ llm = _adapter(client, provider="opencode", base_url=_GO_URL)
+ llm.invoke("hi", extra_headers={"X-OpenCode-Session": "caller-wins"})
+ finally:
+ reset_llm_session_id(token)
+
+ assert seen[0]["x-opencode-session"] == "caller-wins"