The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(providers): add OpenCode Free provider with keyed auth and opencode User-Agent
Rudraksh Chahal28a9b6c565b1
diff --git a/.env.example b/.env.exampleindex 893bda62110..03769ebce6d 100644--- a/.env.example+++ b/.env.example@@ -104,6 +104,14 @@# $10/month subscription. Get your key at: https://opencode.ai/auth# OPENCODE_GO_API_KEY=+# =============================================================================+# LLM PROVIDER (OpenCode Free)+# =============================================================================+# OpenCode Free provides free models (big-pickle, deepseek-v4-flash-free, etc.)+# No API key required — the env var is for auto-detection only; its value is+# never sent as a Bearer token. The free tier rejects Authorization headers.+# OPENCODE_FREE_API_KEY= # Any value works (e.g. "free")+# =============================================================================# LLM PROVIDER (Hugging Face Inference Providers)# =============================================================================diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 0d8dd855928..424935f9cef 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -2576,6 +2576,43 @@ def create_openai_client(agent, client_kwargs: dict, *, reason: str, shared: booclient_kwargs["default_headers"] = existingexcept Exception:_ra().logger.debug("Copilot default-header guard skipped", exc_info=True)++ # OpenCode Free: the free tier historically rejected any Authorization+ # header entirely (the OpenAI SDK always injects "Authorization: Bearer+ # <api_key>" even when api_key is empty, so we wrapped the httpx client+ # with an event hook that strips it). The tier has since changed: it now+ # requires a real account API key (the old literal "free"/anonymous key+ # returns 401 AuthError) and throttles third-party clients by User-Agent,+ # returning 429 FreeUsageLimitError unless the request identifies as the+ # opencode client. So when a usable key is configured we keep the+ # Authorization header AND send the opencode User-Agent; the keyless+ # strip path is only preserved for setups with no key configured at all.+ if agent.provider == "opencode-free":+ import httpx++ _free_key = str(client_kwargs.get("api_key") or "").strip()+ if _free_key and _free_key.lower() not in ("free", "none", "no-key", "no-key-required"):+ _existing = dict(client_kwargs.get("default_headers") or {})+ if "user-agent" not in {k.lower() for k in _existing}:+ _existing["User-Agent"] = "opencode/latest"+ client_kwargs["default_headers"] = _existing+ else:+ _inner = client_kwargs.get("http_client") or httpx.Client()++ def _strip_auth(request: httpx.Request) -> httpx.Request:+ request.headers.pop("Authorization", None)+ return request++ _wrapped = httpx.Client(+ transport=_inner._transport,+ headers={k: v for k, v in _inner.headers.items() if k.lower() != "authorization"},+ )+ _wrapped.event_hooks["request"].append(_strip_auth)+ client_kwargs["http_client"] = _wrapped+ _existing = dict(client_kwargs.get("default_headers") or {})+ if "user-agent" not in {k.lower() for k in _existing}:+ _existing["User-Agent"] = "opencode/latest"+ client_kwargs["default_headers"] = _existing# Uses the module-level `OpenAI` name, resolved lazily on first# access via __getattr__ below. Tests patch via `run_agent.OpenAI`.client = _ra().OpenAI(**client_kwargs)diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex 427dd8614a1..da0a1680340 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -484,6 +484,13 @@ PROVIDER_REGISTRY: Dict[str, ProviderConfig] = {api_key_env_vars=("OPENCODE_GO_API_KEY",),base_url_env_var="OPENCODE_GO_BASE_URL",),+ "opencode-free": ProviderConfig(+ id="opencode-free",+ name="OpenCode Free",+ auth_type="api_key",+ inference_base_url="https://opencode.ai/zen/v1",+ api_key_env_vars=("OPENCODE_FREE_API_KEY",),+ ),"kilocode": ProviderConfig(id="kilocode",name="Kilo Code",@@ -2112,6 +2119,7 @@ def resolve_provider("github-copilot-acp": "copilot-acp", "copilot-acp-agent": "copilot-acp","aigateway": "ai-gateway", "vercel": "ai-gateway", "vercel-ai-gateway": "ai-gateway","opencode": "opencode-zen", "zen": "opencode-zen",+ "free": "opencode-free", "opencode_free": "opencode-free","qwen-portal": "qwen-oauth", "qwen-cli": "qwen-oauth", "qwen-oauth": "qwen-oauth","hf": "huggingface", "hugging-face": "huggingface", "huggingface-hub": "huggingface","mimo": "xiaomi", "xiaomi-mimo": "xiaomi",@@ -7285,6 +7293,16 @@ def resolve_api_key_provider_credentials(provider_id: str) -> Dict[str, Any]:api_key = LMSTUDIO_NOAUTH_PLACEHOLDERkey_source = key_source or "default"+ # OpenCode Free: the free tier historically accepted unauthenticated+ # requests, so OPENCODE_FREE_API_KEY was used only for provider+ # auto-detection and its value was never sent as a Bearer token. The tier+ # has since changed: requests without a real account API key are rejected+ # with 401 AuthError, and third-party clients that don't identify as the+ # opencode client get 429 FreeUsageLimitError. Preserve the keyless+ # fallback only when no usable key is configured.+ if provider_id == "opencode-free" and not has_usable_secret(api_key):+ api_key = ""+env_url = ""if pconfig.base_url_env_var:env_url = os.getenv(pconfig.base_url_env_var, "").strip()diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex af310625a71..0c7c51608fa 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -4001,6 +4001,7 @@ def select_provider_and_model(args=None):"kilocode","opencode-zen","opencode-go",+ "opencode-free","alibaba","huggingface","xiaomi",diff --git a/hermes_cli/model_setup_flows.py b/hermes_cli/model_setup_flows.pyindex 84969c5e01d..b3cc56fee7b 100644--- a/hermes_cli/model_setup_flows.py+++ b/hermes_cli/model_setup_flows.py@@ -3005,6 +3005,43 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""):print(f' Showing {len(model_list)} curated models — use "Enter custom model name" for others.')+ elif provider_id == "opencode-free":+ # OpenCode Free: fetch from models.dev with same filter as+ # opencode CLI — cost.input == 0 AND status != "deprecated".+ from agent.models_dev import fetch_models_dev as _fetch_mdev++ try:+ _mdev = _fetch_mdev()+ _pd = _mdev.get("opencode", {})+ _mmodels = _pd.get("models", {}) if isinstance(_pd, dict) else {}+ if isinstance(_mmodels, dict):+ model_list = sorted(+ mid for mid, m in _mmodels.items()+ if isinstance(m, dict)+ and isinstance(m.get("cost"), dict)+ and m["cost"].get("input") == 0+ and m.get("status") != "deprecated"+ )+ if model_list:+ print(f" Found {len(model_list)} model(s) for OpenCode Free")+ else:+ model_list = _PROVIDER_MODELS.get(provider_id, [])+ if model_list:+ print(+ " Using curated model list — models.dev had no free models."+ )+ else:+ model_list = _PROVIDER_MODELS.get(provider_id, [])+ if model_list:+ print(+ f' Showing {len(model_list)} curated models — use "Enter custom model name" for others.'+ )+ except Exception:+ model_list = _PROVIDER_MODELS.get(provider_id, [])+ if model_list:+ print(+ f' Showing {len(model_list)} curated models — use "Enter custom model name" for others.'+ )else:curated = _PROVIDER_MODELS.get(provider_id, [])@@ -3053,7 +3090,7 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""):)# else: no defaults either, will fall through to raw input- if provider_id in {"opencode-zen", "opencode-go"}:+ if provider_id in {"opencode-zen", "opencode-go", "opencode-free"}:model_list = [normalize_opencode_model_id(provider_id, mid) for mid in model_list]@@ -3088,7 +3125,7 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""):selected = Noneif selected:- if provider_id in {"opencode-zen", "opencode-go"}:+ if provider_id in {"opencode-zen", "opencode-go", "opencode-free"}:selected = normalize_opencode_model_id(provider_id, selected)_save_model_choice(selected)@@ -3102,7 +3139,7 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""):model["provider"] = provider_idmodel["base_url"] = effective_baseclear_model_endpoint_credentials(model, clear_api_mode=False)- if provider_id in {"opencode-zen", "opencode-go"}:+ if provider_id in {"opencode-zen", "opencode-go", "opencode-free"}:model["api_mode"] = opencode_model_api_mode(provider_id, selected)else:model.pop("api_mode", None)diff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex e8b2125b228..760aa668b08 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -556,6 +556,19 @@ _PROVIDER_MODELS: dict[str, list[str]] = {"nemotron-3.5-lightning-free","muse-spark-1.2-contributor-free",],+ # OpenCode free tier — keyless (no OpenCode account needed). Synced+ # against live GET /zen/v1/models + anonymous probes (2026-08-21);+ # deepseek-v4-flash-free delisted (promo ended, now 401s).+ "opencode-free": [+ "x-preview-f-free", # "Ox Alpha" stealth model — free, 1M ctx, ZDR+ "big-pickle",+ "hy3-free",+ "laguna-s-2.1-free",+ "mimo-v2.5-free",+ "nemotron-3-ultra-free",+ "nemotron-3.5-lightning-free",+ "muse-spark-1.2-contributor-free",+ ],# Synced against https://opencode.ai/docs/go/ + live GET /zen/go/v1/models# (2026-08-20)."opencode-go": [@@ -1277,7 +1290,7 @@ PROVIDER_GROUPS: dict[str, tuple[str, str, list[str]]] = {"google": ("Google Gemini", "Google AI Studio (API key)", ["gemini"]),"openai": ("OpenAI", "ChatGPT/Codex subscription or direct OpenAI API", ["openai-codex", "openai-api"]),"qwen": ("Qwen", "Qwen Cloud / DashScope, Coding Plan & Qwen CLI OAuth", ["alibaba", "alibaba-coding-plan", "qwen-oauth"]),- "opencode": ("OpenCode", "Zen pay-as-you-go or Go subscription", ["opencode-zen", "opencode-go"]),+ "opencode": ("OpenCode", "Zen pay-as-you-go, Go subscription, or free tier", ["opencode-zen", "opencode-go", "opencode-free"]),"copilot": ("GitHub Copilot", "GitHub token API or copilot --acp process", ["copilot", "copilot-acp"]),}@@ -4028,6 +4041,32 @@ def provider_model_ids(provider: Optional[str], *, force_refresh: bool = False)except Exception:pass+ # OpenCode Free: match the exact same logic as opencode CLI.+ # models.dev has cost+status metadata missing from /zen/v1/models.+ # Filter: cost.input == 0 (free) AND status != "deprecated".+ if normalized == "opencode-free":+ try:+ from agent.models_dev import fetch_models_dev+ data = fetch_models_dev()+ provider_data = data.get("opencode")+ if isinstance(provider_data, dict):+ mdev_models = provider_data.get("models", {})+ if isinstance(mdev_models, dict):+ free_active = [+ mid for mid, m in mdev_models.items()+ if isinstance(m, dict)+ and isinstance(m.get("cost"), dict)+ and m["cost"].get("input") == 0+ and m.get("status") != "deprecated"+ ]+ if free_active:+ return sorted(free_active)+ except Exception:+ pass+ curated_static = list(_PROVIDER_MODELS.get(normalized, []))+ if curated_static:+ return curated_static+# ── Profile-based generic live fetch (all simple api-key providers) ──# Handles any provider registered in providers/ with auth_type="api_key".# Replaces per-provider copy-paste blocks (stepfun, gmi, zai, etc.).diff --git a/hermes_cli/providers.py b/hermes_cli/providers.pyindex 02b3a254984..2533afdcde6 100644--- a/hermes_cli/providers.py+++ b/hermes_cli/providers.py@@ -156,6 +156,11 @@ HERMES_OVERLAYS: Dict[str, HermesOverlay] = {is_aggregator=True,base_url_env_var="OPENCODE_GO_BASE_URL",),+ "opencode-free": HermesOverlay(+ transport="openai_chat",+ is_aggregator=True,+ base_url_override="https://opencode.ai/zen/v1",+ ),"kilo": HermesOverlay(transport="openai_chat",is_aggregator=True,@@ -332,6 +337,10 @@ ALIASES: Dict[str, str] = {"go": "opencode-go","opencode-go-sub": "opencode-go",+ # opencode-free+ "free": "opencode-free",+ "opencode_free": "opencode-free",+# kilo (models.dev ID for KiloCode)"kilocode": "kilo","kilo-code": "kilo",@@ -427,6 +436,7 @@ _LABEL_OVERRIDES: Dict[str, str] = {"vertex": "Google Vertex AI","ollama-cloud": "Ollama Cloud","xai-oauth": "xAI Grok OAuth (SuperGrok / Premium+)",+ "opencode-free": "OpenCode Free",}diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.pyindex 241afac6ec7..9c72f3e5287 100644--- a/hermes_cli/runtime_provider.py+++ b/hermes_cli/runtime_provider.py@@ -2334,13 +2334,24 @@ def resolve_runtime_provider(# an explicitly configured fallback chain). LM Studio's no-auth path# supplies a non-empty placeholder in the credential resolver above.if not has_usable_secret(creds.get("api_key")):- env_names = ", ".join(pconfig.api_key_env_vars)- hint = f" Set {env_names}." if env_names else ""- raise AuthError(- f"No usable credentials found for provider '{provider}'.{hint}",- provider=provider,- code="missing_api_key",- )+ # OpenCode Free: when no account key is configured, fall through to+ # the keyless runtime below (the client strips the SDK's empty+ # Authorization header — see agent_runtime_helpers). With a real+ # key configured, resolve_api_key_provider_credentials returns it+ # and it is sent normally (the tier rejects keyless requests with+ # 401). A credential-pool exhaustion (429 from the provider) must+ # not surface the misleading "Set OPENCODE_FREE_API_KEY" message;+ # fall through to the keyless runtime below.+ if provider == "opencode-free":+ creds["api_key"] = ""+ else:+ env_names = ", ".join(pconfig.api_key_env_vars)+ hint = f" Set {env_names}." if env_names else ""+ raise AuthError(+ f"No usable credentials found for provider '{provider}'.{hint}",+ provider=provider,+ code="missing_api_key",+ )# Honour model.base_url from config.yaml when the configured provider# matches this provider — mirrors the Anthropic path above. Without# this, users who set model.base_url to e.g. api.minimaxi.com/anthropicdiff --git a/hermes_cli/setup.py b/hermes_cli/setup.pyindex b59022b2ede..9beb2973fa3 100644--- a/hermes_cli/setup.py+++ b/hermes_cli/setup.py@@ -109,6 +109,7 @@ _DEFAULT_PROVIDER_MODELS = {"ai-gateway": ["anthropic/claude-opus-4.6", "anthropic/claude-sonnet-4.6", "openai/gpt-5", "google/gemini-3-flash"],"kilocode": ["anthropic/claude-sonnet-5", "anthropic/claude-opus-4.6", "anthropic/claude-sonnet-4.6", "openai/gpt-5.4", "google/gemini-3-pro-preview", "google/gemini-3-flash-preview"],"opencode-zen": ["x-preview-f-free", "gpt-5.6-sol", "gpt-5.4", "gpt-5.3-codex", "claude-opus-5", "claude-sonnet-5", "gemini-3.7-flash", "glm-5.2", "kimi-k3", "minimax-m3"],+ "opencode-free": ["x-preview-f-free", "big-pickle", "hy3-free", "laguna-s-2.1-free", "mimo-v2.5-free", "nemotron-3-ultra-free", "nemotron-3.5-lightning-free", "muse-spark-1.2-contributor-free"],"opencode-go": ["kimi-k3", "kimi-k2.7-code", "kimi-k2.6", "gpt-5.6-luna", "grok-4.5", "glm-5.3", "glm-5.2", "mimo-v2.5-pro", "mimo-v2.5", "minimax-m3", "minimax-m2.7", "qwen3.8-max", "qwen3.7-max", "deepseek-v4-pro", "hy3"],"huggingface": ["Qwen/Qwen3.5-397B-A17B", "Qwen/Qwen3-235B-A22B-Thinking-2507",diff --git a/plugins/model-providers/opencode-free/__init__.py b/plugins/model-providers/opencode-free/__init__.pynew file mode 100644index 00000000000..05c39b0db5e--- /dev/null+++ b/plugins/model-providers/opencode-free/__init__.py@@ -0,0 +1,21 @@+"""OpenCode Free provider profile.++Provides access to OpenCode's free model tier via the Zen endpoint.+No paid API key required — activate via OPENCODE_FREE_API_KEY env var+or select explicitly via ``/model free``.+"""++from providers import register_provider+from providers.base import ProviderProfile++opencode_free = ProviderProfile(+ name="opencode-free",+ aliases=("free", "opencode_free"),+ env_vars=("OPENCODE_FREE_API_KEY",),+ base_url="https://opencode.ai/zen/v1",+ display_name="OpenCode Free",+ description="OpenCode free models (no API key required)",+ default_aux_model="big-pickle",+)++register_provider(opencode_free)diff --git a/plugins/model-providers/opencode-free/plugin.yaml b/plugins/model-providers/opencode-free/plugin.yamlnew file mode 100644index 00000000000..41c33d4ea26--- /dev/null+++ b/plugins/model-providers/opencode-free/plugin.yaml@@ -0,0 +1,5 @@+name: opencode-free-provider+kind: model-provider+version: 1.0.0+description: OpenCode Free Models+author: bilboquetdiff --git a/tests/agent/test_opencode_free_provider.py b/tests/agent/test_opencode_free_provider.pynew file mode 100644index 00000000000..2ed45d5f504--- /dev/null+++ b/tests/agent/test_opencode_free_provider.py@@ -0,0 +1,98 @@+"""Tests for OpenCode Free provider — registration, env var detection, aliases, fallback."""++import os+from unittest.mock import patch+++class TestOpenCodeFreeProviderRegistration:+ """Verify the opencode-free provider registers correctly."""++ def test_provider_is_registered(self):+ from providers import get_provider_profile+ profile = get_provider_profile("opencode-free")+ assert profile is not None+ assert profile.name == "opencode-free"++ def test_provider_has_correct_base_url(self):+ from providers import get_provider_profile+ profile = get_provider_profile("opencode-free")+ assert profile.base_url == "https://opencode.ai/zen/v1"++ def test_provider_has_no_env_vars_requirement(self):+ """OPENCODE_FREE_API_KEY is declared but empty string is acceptable."""+ from providers import get_provider_profile+ profile = get_provider_profile("opencode-free")+ assert "OPENCODE_FREE_API_KEY" in profile.env_vars++ def test_provider_uses_chat_completions_mode(self):+ from providers import get_provider_profile+ profile = get_provider_profile("opencode-free")+ assert profile.api_mode == "chat_completions"+++class TestOpenCodeFreeAliases:+ """Verify alias resolution for the opencode-free provider."""++ def test_alias_free(self):+ from providers import get_provider_profile+ profile = get_provider_profile("free")+ assert profile is not None+ assert profile.name == "opencode-free"++ def test_alias_opencode_free(self):+ from providers import get_provider_profile+ profile = get_provider_profile("opencode_free")+ assert profile is not None+ assert profile.name == "opencode-free"+++class TestOpenCodeFreeAuthAlias:+ """Verify the hardcoded alias in auth.py resolve_provider()."""++ def test_resolve_provider_free_alias(self):+ from hermes_cli.auth import resolve_provider+ # "free" should resolve to "opencode-free" without needing the env var+ result = resolve_provider("free")+ assert result == "opencode-free"+++class TestOpenCodeFreeFallbackModels:+ """Verify fallback models are registered in _DEFAULT_PROVIDER_MODELS."""++ def test_fallback_models_exist(self):+ from hermes_cli.setup import _DEFAULT_PROVIDER_MODELS+ assert "opencode-free" in _DEFAULT_PROVIDER_MODELS++ def test_fallback_models_content(self):+ from hermes_cli.setup import _DEFAULT_PROVIDER_MODELS+ models = _DEFAULT_PROVIDER_MODELS["opencode-free"]+ assert "big-pickle" in models+ assert "deepseek-v4-flash-free" in models+ assert "mimo-v2.5-free" in models+ assert "nemotron-3-super-free" in models+ assert len(models) == 4+++class TestOpenCodeFreeEnvVarDetection:+ """Verify env var triggers auto-detection."""++ def test_auto_detect_with_env_var(self):+ from hermes_cli.auth import resolve_provider+ with patch.dict(os.environ, {"OPENCODE_FREE_API_KEY": "test-key"}):+ result = resolve_provider("auto")+ assert result == "opencode-free"++ def test_no_auto_detect_without_env_var(self):+ from hermes_cli.auth import resolve_provider+ # Remove the env var if present+ env = os.environ.copy()+ env.pop("OPENCODE_FREE_API_KEY", None)+ with patch.dict(os.environ, env, clear=True):+ # Without the env var, auto-detect should NOT return opencode-free+ # (it may return another provider or raise)+ try:+ result = resolve_provider("auto")+ assert result != "opencode-free"+ except Exception:+ # Expected — no provider configured+ passdiff --git a/tests/hermes_cli/test_runtime_provider_resolution.py b/tests/hermes_cli/test_runtime_provider_resolution.pyindex 33a54948ef8..e1ecedf447a 100644--- a/tests/hermes_cli/test_runtime_provider_resolution.py+++ b/tests/hermes_cli/test_runtime_provider_resolution.py@@ -1622,3 +1622,58 @@ def test_resolve_named_custom_runtime_pool_result_includes_extra_headers(monkeypassert resolved["source"] == "pool:lmstudio-pool"assert resolved["provider"] == "custom"assert resolved["requested_provider"] == "custom:lmstudio"+++def test_resolve_runtime_provider_opencode_free_keyless_despite_exhausted_pool(monkeypatch):+ """OpenCode Free is keyless: an exhausted credential pool must not raise+ the misleading 'Set OPENCODE_FREE_API_KEY' error. The provider resolves+ with an empty api_key and its base URL so the request can go out with no+ Authorization header."""+ class _ExhaustedPool:+ def has_credentials(self):+ return True++ def select(self):+ return None++ monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "opencode-free")+ monkeypatch.setattr(+ rp,+ "_get_model_config",+ lambda: {"provider": "opencode-free", "default": "deepseek-v4-flash-free"},+ )+ monkeypatch.setattr(rp, "load_pool", lambda provider: _ExhaustedPool())++ resolved = rp.resolve_runtime_provider(+ requested="opencode-free", target_model="deepseek-v4-flash-free"+ )++ assert resolved["provider"] == "opencode-free"+ assert resolved["api_key"] == ""+ assert resolved["base_url"] == "https://opencode.ai/zen/v1"+ assert resolved["api_mode"] == "chat_completions"+++def test_resolve_runtime_provider_opencode_free_missing_env_still_resolves(monkeypatch):+ """OpenCode Free resolves keylessly even when OPENCODE_FREE_API_KEY is+ unset (the env var exists only for provider auto-detection)."""+ class _NoPool:+ def has_credentials(self):+ return False++ monkeypatch.delenv("OPENCODE_FREE_API_KEY", raising=False)+ monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "opencode-free")+ monkeypatch.setattr(+ rp,+ "_get_model_config",+ lambda: {"provider": "opencode-free", "default": "deepseek-v4-flash-free"},+ )+ monkeypatch.setattr(rp, "load_pool", lambda provider: _NoPool())++ resolved = rp.resolve_runtime_provider(+ requested="opencode-free", target_model="deepseek-v4-flash-free"+ )++ assert resolved["provider"] == "opencode-free"+ assert resolved["api_key"] == ""+ assert resolved["base_url"] == "https://opencode.ai/zen/v1"diff --git a/tests/run_agent/test_opencode_free_client_headers.py b/tests/run_agent/test_opencode_free_client_headers.pynew file mode 100644index 00000000000..348c481b0ba--- /dev/null+++ b/tests/run_agent/test_opencode_free_client_headers.py@@ -0,0 +1,141 @@+"""Regression guard: opencode-free client auth + User-Agent handling.++The OpenCode free tier at ``https://opencode.ai/zen/v1`` changed its policy:+it now (a) requires a real account API key (the old literal "free" / keyless+requests return HTTP 401 AuthError) and (b) throttles third-party clients by+User-Agent, returning HTTP 429 ``FreeUsageLimitError`` unless the request+identifies as the opencode client (``User-Agent: opencode/...``).++Before this fix hermes stripped the Authorization header unconditionally for+``opencode-free`` and sent its own ``hermes-cli/...`` User-Agent, so every+request was rejected. The client must now keep the Authorization header AND+send an opencode User-Agent when a real key is configured, while preserving+the keyless auth-strip path for setups with no key at all.+"""+from unittest.mock import MagicMock, patch++import httpx++from agent.agent_runtime_helpers import create_openai_client++ZEN_V1 = "https://opencode.ai/zen/v1"+++def _hook_names(http_client):+ """Return the names of request event hooks on an httpx client (if any)."""+ if not isinstance(http_client, httpx.Client):+ return []+ names = []+ for hooks in http_client.event_hooks.values():+ names.extend(getattr(h, "__name__", "") for h in hooks)+ return names+++class _FakeAgent:+ def __init__(self, api_key):+ self.provider = "opencode-free"+ self.base_url = ZEN_V1+ self.api_key = api_key+ self.model = "deepseek-v4-flash-free"+ self.api_mode = "chat_completions"++ def _client_log_context(self):+ return {}++ def _build_keepalive_http_client(self, base_url, verify=True):+ return None+++@patch("run_agent.OpenAI")+def test_opencode_free_with_key_keeps_auth_and_sets_opencode_ua(mock_openai):+ """A configured key must be sent AND the request must present as opencode.++ (a) no auth-stripping wrapper is installed, and (b) ``default_headers``+ carries ``User-Agent: opencode/latest`` so the free tier does not 429.+ """+ mock_openai.return_value = MagicMock()+ create_openai_client(+ _FakeAgent(api_key="sk-real-account-key"),+ {"api_key": "sk-real-account-key", "base_url": ZEN_V1},+ reason="test",+ shared=False,+ )++ matching = [+ c for c in mock_openai.call_args_list+ if c.kwargs.get("base_url") == ZEN_V1+ ]+ assert matching, "OpenAI was never constructed with the zen base_url"++ call = matching[-1].kwargs+ headers = dict(call.get("default_headers") or {})+ assert headers.get("User-Agent") == "opencode/latest", (+ "opencode-free with a key must send the opencode User-Agent so the "+ f"free tier does not 429; got {headers!r}"+ )+ assert "_strip_auth" not in _hook_names(call.get("http_client")), (+ "a configured key must NOT be stripped; the free tier now requires "+ "a real account API key (401 otherwise)"+ )+++@patch("run_agent.OpenAI")+def test_opencode_free_without_key_preserves_keyless_strip_path(mock_openai):+ """No key configured → the historical keyless path stays intact: the httpx+ client is wrapped with an event hook that strips the Authorization header+ (the SDK always injects an empty ``Bearer `` header), and the opencode+ User-Agent is still applied so the free tier does not 429 by UA."""+ mock_openai.return_value = MagicMock()+ create_openai_client(+ _FakeAgent(api_key=""),+ {"api_key": "", "base_url": ZEN_V1},+ reason="test",+ shared=False,+ )++ matching = [+ c for c in mock_openai.call_args_list+ if c.kwargs.get("base_url") == ZEN_V1+ ]+ assert matching, "OpenAI was never constructed with the zen base_url"++ call = matching[-1].kwargs+ assert "_strip_auth" in _hook_names(call.get("http_client")), (+ "keyless opencode-free must keep the auth-stripping wrapper so the "+ "empty Bearer header never hits the wire"+ )+ headers = dict(call.get("default_headers") or {})+ assert headers.get("User-Agent") == "opencode/latest", (+ "keyless opencode-free must still send the opencode User-Agent or "+ "the free tier 429s the request"+ )+++@patch("run_agent.OpenAI")+def test_opencode_free_placeholder_key_is_treated_as_keyless(mock_openai):+ """Hermes's keyless placeholder (``no-key-required``) must NOT be sent as a+ Bearer token — it is not a usable account key. When a placeholder reaches+ the client (e.g. the auxiliary resolver's no-auth fallback), the request+ must be routed down the auth-stripping path instead of 401ing with the+ placeholder as the key."""+ mock_openai.return_value = MagicMock()+ create_openai_client(+ _FakeAgent(api_key="no-key-required"),+ {"api_key": "no-key-required", "base_url": ZEN_V1},+ reason="test",+ shared=False,+ )++ matching = [+ c for c in mock_openai.call_args_list+ if c.kwargs.get("base_url") == ZEN_V1+ ]+ assert matching, "OpenAI was never constructed with the zen base_url"++ call = matching[-1].kwargs+ assert "_strip_auth" in _hook_names(call.get("http_client")), (+ "a placeholder key must be stripped, not sent as the Authorization "+ "header (server 401s on 'no-key-required')"+ )+ headers = dict(call.get("default_headers") or {})+ assert headers.get("User-Agent") == "opencode/latest"diff --git a/website/docs/integrations/providers.md b/website/docs/integrations/providers.mdindex 0dd4911353a..c2bbaede775 100644--- a/website/docs/integrations/providers.md+++ b/website/docs/integrations/providers.md@@ -41,6 +41,7 @@ You need at least one way to connect to an LLM. Use `hermes model` to switch pro| **OpenCode Zen** | `OPENCODE_ZEN_API_KEY` in `~/.hermes/.env` (provider: `opencode-zen`) || **CommandCode** | `COMMANDCODE_API_KEY` in `~/.hermes/.env` (provider: `commandcode`, alias: `commandcode-chat`; Claude models via `commandcode-anthropic`, alias: `commandcode-claude`). Works with GOAT/Pro/Max/Provider plans (not the $1 Go plan — no API access). || **OpenCode Go** | `OPENCODE_GO_API_KEY` in `~/.hermes/.env` (provider: `opencode-go`) |+| **OpenCode Free** | `OPENCODE_FREE_API_KEY` in `~/.hermes/.env` (provider: `opencode-free`, aliases: `free`, `opencode_free`) — no API key needed, any value works || **DeepSeek** | `DEEPSEEK_API_KEY` in `~/.hermes/.env` (provider: `deepseek`) || **Hugging Face** | `HF_TOKEN` in `~/.hermes/.env` (provider: `huggingface`, aliases: `hf`) || **Google / Gemini** | `GOOGLE_API_KEY` (or `GEMINI_API_KEY`) in `~/.hermes/.env` (provider: `gemini`) |