Skip to content

The agent that grows with you

feat: opencode-free is fully keyless — no env var, no account, anonymous wire

Tekniumca06b8768999
diff --git a/.env.example b/.env.example
index 03769ebce6d..748f2ccf9ec 100644
--- a/.env.example
+++ b/.env.example
@@ -107,10 +107,10 @@
# =============================================================================
# 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")
+# OpenCode Free provides keyless free models (Ox Alpha / x-preview-f-free,
+# big-pickle, etc.). NO env var and NO account needed — requests are sent
+# anonymously (the free tier rejects any unrecognized Authorization header).
+# Select it with `hermes model` or `/model free`.
# =============================================================================
# LLM PROVIDER (Hugging Face Inference Providers)
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index 424935f9cef..1c89288330f 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -2577,42 +2577,17 @@ def create_openai_client(agent, client_kwargs: dict, *, reason: str, shared: boo
except 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.
+ # OpenCode Free: the tier is served ANONYMOUSLY — any bearer the relay
+ # doesn't recognize (including placeholders) is a 401. Route every
+ # opencode-free client through the shared keyless header policy: an
+ # empty Authorization default_header overrides the SDK's
+ # "Bearer <api_key>" so no credential ever reaches the wire.
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
+ from hermes_cli.models import opencode_zen_free_headers
- _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
+ _existing = dict(client_kwargs.get("default_headers") or {})
+ _existing.update(opencode_zen_free_headers())
+ 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.py
index da0a1680340..fcfc602788c 100644
--- a/hermes_cli/auth.py
+++ b/hermes_cli/auth.py
@@ -489,7 +489,10 @@ PROVIDER_REGISTRY: Dict[str, ProviderConfig] = {
name="OpenCode Free",
auth_type="api_key",
inference_base_url="https://opencode.ai/zen/v1",
- api_key_env_vars=("OPENCODE_FREE_API_KEY",),
+ # Deliberately NO api_key_env_vars: the free tier is served
+ # anonymously (any unrecognized bearer is a 401), so there is no
+ # secret to configure. Select via `hermes model` / `/model free`.
+ api_key_env_vars=(),
),
"kilocode": ProviderConfig(
id="kilocode",
@@ -7293,16 +7296,6 @@ def resolve_api_key_provider_credentials(provider_id: str) -> Dict[str, Any]:
api_key = LMSTUDIO_NOAUTH_PLACEHOLDER
key_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/model_setup_flows.py b/hermes_cli/model_setup_flows.py
index b3cc56fee7b..fbb6f35c948 100644
--- a/hermes_cli/model_setup_flows.py
+++ b/hermes_cli/model_setup_flows.py
@@ -2826,17 +2826,23 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""):
key_env = pconfig.api_key_env_vars[0] if pconfig.api_key_env_vars else ""
base_url_env = pconfig.base_url_env_var or ""
- # Check / prompt for API key
- existing_key, existing_source = _existing_api_key_for_model_flow(provider_id, pconfig)
-
- existing_key, abort = _prompt_api_key(
- pconfig,
- existing_key,
- provider_id=provider_id,
- existing_source=existing_source,
- )
- if abort:
- return
+ # OpenCode Free is keyless — the tier is served anonymously and any
+ # unrecognized bearer 401s, so there is no key to prompt for.
+ if provider_id == "opencode-free":
+ print(" OpenCode Free is keyless — no API key or account needed.")
+ existing_key = ""
+ else:
+ # Check / prompt for API key
+ existing_key, existing_source = _existing_api_key_for_model_flow(provider_id, pconfig)
+
+ existing_key, abort = _prompt_api_key(
+ pconfig,
+ existing_key,
+ provider_id=provider_id,
+ existing_source=existing_source,
+ )
+ if abort:
+ return
# Gemini free-tier gate: free-tier daily quotas (<= 250 RPD for Flash)
# are exhausted in a handful of agent turns, so refuse to wire up the
@@ -3006,42 +3012,15 @@ def _model_flow_api_key_provider(config, provider_id, current_model=""):
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.'
- )
+ # Keyless free tier: the curated list is synced against anonymous
+ # live probes (models.dev's cost.input==0 filter lags reality —
+ # e.g. deepseek-v4-flash-free stayed "free" there after its promo
+ # ended and the relay started 401ing it keyless).
+ model_list = _PROVIDER_MODELS.get(provider_id, [])
+ if model_list:
+ print(
+ f' Showing {len(model_list)} keyless free models — use "Enter custom model name" for others.'
+ )
else:
curated = _PROVIDER_MODELS.get(provider_id, [])
diff --git a/hermes_cli/models.py b/hermes_cli/models.py
index 760aa668b08..3048bdb0dca 100644
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@ -1410,6 +1410,8 @@ _PROVIDER_ALIASES = {
"zen": "opencode-zen",
"go": "opencode-go",
"opencode-go-sub": "opencode-go",
+ "free": "opencode-free",
+ "opencode_free": "opencode-free",
"aigateway": "ai-gateway",
"vercel": "ai-gateway",
"vercel-ai-gateway": "ai-gateway",
@@ -4041,31 +4043,12 @@ 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".
+ # OpenCode Free: curated keyless list only. models.dev's cost.input==0
+ # filter lags reality (deepseek-v4-flash-free stayed "free" there after
+ # its promo ended and the relay began 401ing keyless requests), so the
+ # curated list — synced against anonymous live probes — is authoritative.
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
+ return list(_PROVIDER_MODELS.get(normalized, []))
# ── Profile-based generic live fetch (all simple api-key providers) ──
# Handles any provider registered in providers/ with auth_type="api_key".
@@ -5329,8 +5312,10 @@ def opencode_provider_family(provider_id: Optional[str]) -> Optional[str]:
if not raw:
return None
canonical = normalize_provider(provider_id)
- if canonical in {"opencode-zen", "opencode-go"}:
+ if canonical in {"opencode-zen", "opencode-go", "opencode-free"}:
return canonical
+ if raw.startswith("opencode-free"):
+ return "opencode-free"
if raw.startswith("opencode-go"):
return "opencode-go"
if raw.startswith("opencode-zen"):
@@ -5355,25 +5340,34 @@ def normalize_opencode_model_id(provider_id: Optional[str], model_id: Optional[s
# OpenCode Zen free-tier models (``*-free`` slugs, e.g. x-preview-f-free /
-# "Ox Alpha") are served ANONYMOUSLY on the Zen relay: a request with no
-# Authorization header succeeds, while ANY non-empty bearer the relay doesn't
-# recognize is rejected with 401 "Invalid API key" — including our
-# "no-key-required" placeholder and OpenCode GO subscription keys (the Go
-# relay doesn't serve the free tier at all: "Model x is not supported").
+# "Ox Alpha", plus unsuffixed free models like big-pickle) are served
+# ANONYMOUSLY on the Zen relay: a request with no Authorization header
+# succeeds, while ANY non-empty bearer the relay doesn't recognize is
+# rejected with 401 "Invalid API key" — including our "no-key-required"
+# placeholder and OpenCode GO subscription keys (the Go relay doesn't serve
+# the free tier at all: "Model x is not supported").
# Verified live 2026-08-21 against POST /zen/v1/chat/completions.
OPENCODE_ZEN_FREE_KEYLESS_PLACEHOLDER = "opencode-zen-free-keyless"
_OPENCODE_ZEN_FREE_BASE_URL = "https://opencode.ai/zen/v1"
+# Free-tier models whose slug does NOT carry the ``-free`` suffix.
+# (big-pickle is OpenCode's rotating free stealth slot.)
+_OPENCODE_KEYLESS_EXTRA_SLUGS = frozenset({"big-pickle"})
+
def is_opencode_zen_free_model(model_id: Optional[str]) -> bool:
- """True when ``model_id`` is an OpenCode Zen free-tier slug (``*-free``).
+ """True when ``model_id`` is an OpenCode Zen free-tier slug.
- Tolerates provider-prefixed ids (``opencode-zen/x-preview-f-free``).
- The Go catalog serves no ``-free`` models (verified 2026-08-21), so the
- suffix alone identifies the Zen free tier across the OpenCode family.
+ Matches the ``*-free`` suffix plus the known unsuffixed free slugs
+ (``big-pickle``). Tolerates provider-prefixed ids
+ (``opencode-zen/x-preview-f-free``). The Go catalog serves no free
+ models (verified 2026-08-21), so this identifies the Zen free tier
+ across the OpenCode family.
"""
bare = str(model_id or "").strip().rsplit("/", 1)[-1].lower()
- return bool(bare) and bare.endswith("-free")
+ if not bare:
+ return False
+ return bare.endswith("-free") or bare in _OPENCODE_KEYLESS_EXTRA_SLUGS
def opencode_zen_free_headers() -> dict:
@@ -5400,13 +5394,18 @@ def opencode_zen_free_runtime(provider_id: Optional[str], model_id: Optional[str
"""Keyless runtime entry for an OpenCode Zen free-tier model, or None.
Returns a resolve_runtime_provider-shaped dict pinning the request to the
- Zen relay with the keyless placeholder whenever ``model_id`` is a
- ``*-free`` slug and ``provider_id`` is in the OpenCode family. Free-tier
- slugs live only on the Zen relay, so this also heals a selection made
- under the opencode-go provider (the Go relay rejects them).
+ Zen relay with the keyless placeholder whenever:
+
+ - ``provider_id`` is ``opencode-free`` (the dedicated keyless provider —
+ EVERY model on it routes anonymously; that is the provider's contract), or
+ - ``provider_id`` is any other OpenCode-family provider and ``model_id``
+ is a free-tier slug (heals a free-model selection made under
+ opencode-zen/opencode-go, whose keys the free tier rejects).
"""
family = opencode_provider_family(provider_id)
- if family is None or not is_opencode_zen_free_model(model_id):
+ if family is None:
+ return None
+ if family != "opencode-free" and not is_opencode_zen_free_model(model_id):
return None
normalized = normalize_opencode_model_id(provider_id, model_id)
api_mode = opencode_model_api_mode("opencode-zen", normalized)
@@ -5442,6 +5441,10 @@ def opencode_model_api_mode(provider_id: Optional[str], model_id: Optional[str])
(https://opencode.ai/docs/zen/ and https://opencode.ai/docs/go/).
"""
family = opencode_provider_family(provider_id)
+ # opencode-free is Zen-hosted (the free tier lives on the Zen relay),
+ # so it shares Zen's per-model endpoint routing.
+ if family == "opencode-free":
+ family = "opencode-zen"
normalized = normalize_opencode_model_id(provider_id, model_id).lower()
if not normalized:
return "chat_completions"
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.py
index 9c72f3e5287..241afac6ec7 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -2334,24 +2334,13 @@ 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")):
- # 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",
- )
+ 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/anthropic
diff --git a/plugins/model-providers/opencode-free/__init__.py b/plugins/model-providers/opencode-free/__init__.py
index 05c39b0db5e..8d8c1a67ef4 100644
--- a/plugins/model-providers/opencode-free/__init__.py
+++ b/plugins/model-providers/opencode-free/__init__.py
@@ -1,20 +1,36 @@
"""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``.
+OpenCode's free model tier on the Zen relay (https://opencode.ai/zen/v1).
+KEYLESS: the relay serves free-tier models anonymously and rejects any
+Authorization bearer it doesn't recognize with 401 — so this provider
+never sends a credential at all (the runtime resolver pins the keyless
+placeholder and an empty Authorization header; see
+hermes_cli.models.opencode_zen_free_runtime). No OpenCode account needed.
+Select via ``hermes model`` or ``/model free``.
"""
+from hermes_cli import __version__ as _HERMES_VERSION
from providers import register_provider
from providers.base import ProviderProfile
+# Attribution headers, same values as the opencode-zen/go profiles, plus the
+# empty Authorization override that keeps the SDK's "Bearer <placeholder>"
+# off the wire (the free tier 401s any unrecognized bearer).
+_KEYLESS_HEADERS = {
+ "Authorization": "",
+ "HTTP-Referer": "https://hermes-agent.nousresearch.com",
+ "X-Title": "Hermes Agent",
+ "User-Agent": f"HermesAgent/{_HERMES_VERSION}",
+}
+
opencode_free = ProviderProfile(
name="opencode-free",
aliases=("free", "opencode_free"),
- env_vars=("OPENCODE_FREE_API_KEY",),
+ env_vars=(), # keyless — nothing to configure
base_url="https://opencode.ai/zen/v1",
display_name="OpenCode Free",
- description="OpenCode free models (no API key required)",
+ description="OpenCode free models — keyless, no account needed",
+ default_headers=dict(_KEYLESS_HEADERS),
default_aux_model="big-pickle",
)
diff --git a/tests/agent/test_opencode_free_provider.py b/tests/agent/test_opencode_free_provider.py
index 2ed45d5f504..8af541971bc 100644
--- a/tests/agent/test_opencode_free_provider.py
+++ b/tests/agent/test_opencode_free_provider.py
@@ -1,4 +1,10 @@
-"""Tests for OpenCode Free provider — registration, env var detection, aliases, fallback."""
+"""Tests for OpenCode Free provider — registration, keyless contract, aliases.
+
+The provider is KEYLESS: OpenCode's free tier is served anonymously and
+rejects any unrecognized Authorization bearer with 401, so the provider
+declares no env vars and every request goes out with an empty Authorization
+header (see hermes_cli.models.opencode_zen_free_runtime).
+"""
import os
from unittest.mock import patch
@@ -18,11 +24,18 @@ class TestOpenCodeFreeProviderRegistration:
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."""
+ def test_provider_is_keyless(self):
+ """No env vars declared — the free tier requires no credential."""
from providers import get_provider_profile
profile = get_provider_profile("opencode-free")
- assert "OPENCODE_FREE_API_KEY" in profile.env_vars
+ assert profile.env_vars == ()
+
+ def test_provider_headers_override_sdk_bearer(self):
+ """The profile's default headers blank Authorization so the SDK's
+ Bearer never reaches the wire (the free tier 401s unknown bearers)."""
+ from providers import get_provider_profile
+ profile = get_provider_profile("opencode-free")
+ assert profile.default_headers.get("Authorization") == ""
def test_provider_uses_chat_completions_mode(self):
from providers import get_provider_profile
@@ -51,48 +64,57 @@ class TestOpenCodeFreeAuthAlias:
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
+ # "free" should resolve to "opencode-free" without any credential
result = resolve_provider("free")
assert result == "opencode-free"
-class TestOpenCodeFreeFallbackModels:
- """Verify fallback models are registered in _DEFAULT_PROVIDER_MODELS."""
+class TestOpenCodeFreeModelLists:
+ """Curated keyless model lists exist and stay in sync."""
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):
+ def test_setup_list_matches_curated_catalog(self):
+ """setup.py sample list must be a subset of the curated catalog
+ (behavior contract, not a frozen snapshot)."""
+ from hermes_cli.models import _PROVIDER_MODELS
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
- pass
+ curated = set(_PROVIDER_MODELS["opencode-free"])
+ assert set(_DEFAULT_PROVIDER_MODELS["opencode-free"]) <= curated
+
+ def test_every_curated_model_is_keyless(self):
+ """Every model in the opencode-free catalog must satisfy the keyless
+ predicate — a paid slug here would route with no auth and 401."""
+ from hermes_cli.models import _PROVIDER_MODELS, is_opencode_zen_free_model
+ for mid in _PROVIDER_MODELS["opencode-free"]:
+ assert is_opencode_zen_free_model(mid), mid
+
+ def test_ox_alpha_is_listed(self):
+ from hermes_cli.models import _PROVIDER_MODELS
+ assert "x-preview-f-free" in _PROVIDER_MODELS["opencode-free"]
+
+
+class TestOpenCodeFreeRuntimeKeyless:
+ """The runtime resolver pins every opencode-free model keyless."""
+
+ def test_free_provider_any_model_routes_keyless(self):
+ from hermes_cli.models import (
+ OPENCODE_ZEN_FREE_KEYLESS_PLACEHOLDER,
+ opencode_zen_free_runtime,
+ )
+ rt = opencode_zen_free_runtime("opencode-free", "big-pickle")
+ assert rt is not None
+ assert rt["api_key"] == OPENCODE_ZEN_FREE_KEYLESS_PLACEHOLDER
+ assert rt["base_url"] == "https://opencode.ai/zen/v1"
+ assert rt["default_headers"]["Authorization"] == ""
+
+ def test_free_provider_muse_routes_responses(self):
+ """opencode-free inherits Zen's per-model endpoint routing."""
+ from hermes_cli.models import opencode_zen_free_runtime
+ rt = opencode_zen_free_runtime(
+ "opencode-free", "muse-spark-1.2-contributor-free"
+ )
+ assert rt is not None
+ assert rt["api_mode"] == "codex_responses"
diff --git a/tests/hermes_cli/test_runtime_provider_resolution.py b/tests/hermes_cli/test_runtime_provider_resolution.py
index e1ecedf447a..fc42da1c01e 100644
--- a/tests/hermes_cli/test_runtime_provider_resolution.py
+++ b/tests/hermes_cli/test_runtime_provider_resolution.py
@@ -1626,9 +1626,9 @@ def test_resolve_named_custom_runtime_pool_result_includes_extra_headers(monkeyp
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."""
+ a missing-credential error. The provider resolves with the keyless
+ placeholder + empty-Authorization headers so the request goes out
+ anonymously."""
class _ExhaustedPool:
def has_credentials(self):
return True
@@ -1640,40 +1640,40 @@ def test_resolve_runtime_provider_opencode_free_keyless_despite_exhausted_pool(m
monkeypatch.setattr(
rp,
"_get_model_config",
- lambda: {"provider": "opencode-free", "default": "deepseek-v4-flash-free"},
+ lambda: {"provider": "opencode-free", "default": "x-preview-f-free"},
)
monkeypatch.setattr(rp, "load_pool", lambda provider: _ExhaustedPool())
resolved = rp.resolve_runtime_provider(
- requested="opencode-free", target_model="deepseek-v4-flash-free"
+ requested="opencode-free", target_model="x-preview-f-free"
)
assert resolved["provider"] == "opencode-free"
- assert resolved["api_key"] == ""
+ assert resolved["api_key"] == "opencode-zen-free-keyless"
assert resolved["base_url"] == "https://opencode.ai/zen/v1"
assert resolved["api_mode"] == "chat_completions"
+ assert resolved["default_headers"]["Authorization"] == ""
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)."""
+ """OpenCode Free resolves keylessly with no env var configured at all —
+ the provider declares no credentials."""
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"},
+ lambda: {"provider": "opencode-free", "default": "x-preview-f-free"},
)
monkeypatch.setattr(rp, "load_pool", lambda provider: _NoPool())
resolved = rp.resolve_runtime_provider(
- requested="opencode-free", target_model="deepseek-v4-flash-free"
+ requested="opencode-free", target_model="x-preview-f-free"
)
assert resolved["provider"] == "opencode-free"
- assert resolved["api_key"] == ""
+ assert resolved["api_key"] == "opencode-zen-free-keyless"
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.py
index 348c481b0ba..232c5bd3cff 100644
--- a/tests/run_agent/test_opencode_free_client_headers.py
+++ b/tests/run_agent/test_opencode_free_client_headers.py
@@ -1,42 +1,28 @@
-"""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.
+"""Regression guard: opencode-free client keyless header handling.
+
+OpenCode's free tier at ``https://opencode.ai/zen/v1`` is served ANONYMOUSLY:
+requests with no recognizable Authorization bearer succeed, while any bearer
+the relay doesn't recognize — placeholders included — is rejected with 401
+"Invalid API key" (verified live 2026-08-21).
+
+The client therefore must ship an EMPTY ``Authorization`` default header for
+every opencode-free build, which overrides the OpenAI SDK's always-injected
+``Authorization: Bearer <api_key>`` so no credential-shaped value ever
+reaches the wire.
"""
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.model = "x-preview-f-free"
self.api_mode = "chat_completions"
def _client_log_context(self):
@@ -46,96 +32,65 @@ class _FakeAgent:
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,
- )
-
+def _zen_call_headers(mock_openai):
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"
+ return dict(matching[-1].kwargs.get("default_headers") or {})
- 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_blanks_authorization_header(mock_openai):
+ """Whatever api_key value reaches the client build (placeholder, stale
+ key, empty), the Authorization default header must be blanked so the
+ SDK's Bearer never hits the wire."""
+ mock_openai.return_value = MagicMock()
+ for key in ("opencode-zen-free-keyless", "no-key-required", "", "sk-stale"):
+ mock_openai.reset_mock()
+ create_openai_client(
+ _FakeAgent(api_key=key),
+ {"api_key": key, "base_url": ZEN_V1},
+ reason="test",
+ shared=False,
+ )
+ headers = _zen_call_headers(mock_openai)
+ assert headers.get("Authorization") == "", (
+ f"opencode-free with api_key={key!r} must blank Authorization; "
+ f"got {headers!r}"
+ )
@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."""
+def test_opencode_free_sends_hermes_attribution(mock_openai):
+ """Keyless requests still identify as Hermes (attribution headers match
+ the opencode zen/go profiles)."""
mock_openai.return_value = MagicMock()
create_openai_client(
- _FakeAgent(api_key=""),
- {"api_key": "", "base_url": ZEN_V1},
+ _FakeAgent(api_key="opencode-zen-free-keyless"),
+ {"api_key": "opencode-zen-free-keyless", "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"
- )
+ headers = _zen_call_headers(mock_openai)
+ assert headers.get("X-Title") == "Hermes Agent"
+ assert str(headers.get("User-Agent", "")).startswith("HermesAgent/")
@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."""
+def test_other_providers_unaffected(mock_openai):
+ """The opencode-free header policy must not leak to other providers."""
mock_openai.return_value = MagicMock()
+ agent = _FakeAgent(api_key="sk-real")
+ agent.provider = "opencode-zen"
create_openai_client(
- _FakeAgent(api_key="no-key-required"),
- {"api_key": "no-key-required", "base_url": ZEN_V1},
+ agent,
+ {"api_key": "sk-real", "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 = _zen_call_headers(mock_openai)
+ assert "Authorization" not in headers, (
+ "opencode-zen (keyed) must not have its Authorization header blanked"
)
- 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.md
index c2bbaede775..042b5411181 100644
--- a/website/docs/integrations/providers.md
+++ b/website/docs/integrations/providers.md
@@ -41,7 +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 |
+| **OpenCode Free** | Keyless — no API key or account needed (provider: `opencode-free`, aliases: `free`, `opencode_free`). Select via `hermes model` or `/model free`; requests are sent anonymously |
| **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`) |