The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(providers): add Solstice as a secret-launch OAuth inference provider
Ben Barclay8e015f483fc0
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 16a95fb3519..012a0e11154 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -2012,6 +2012,33 @@ def _gemini_native_client(agent, client_kwargs: dict, httpx_verify, *, reason: sreturn client+def _solstice_client(agent, client_kwargs: dict, httpx_verify, *, reason: str, shared: bool):+ """Solstice (per-user-quota) transport client, else None.++ Separate from ``_gemini_native_client``: same request body, but the OAuth bearer token+ replaces the API key and the endpoint is the ``:generateContentPerUserQuota`` variant, so the+ transport must be the Solstice-aware facade rather than the plain native client.+ """+ from agent.solstice_adapter import SOLSTICE_BASE_URL, SolsticeClient+ if getattr(agent, "provider", "") != "solstice":+ return None+ base_url = str(client_kwargs.get("base_url", "") or "").rstrip("/") or SOLSTICE_BASE_URL+ safe_kwargs = {+ k: v for k, v in client_kwargs.items()+ if k in {"api_key", "base_url", "default_headers", "timeout", "http_client", "project"}+ }+ safe_kwargs["base_url"] = base_url+ if "http_client" not in safe_kwargs:+ keepalive_http = agent._build_keepalive_http_client(base_url, verify=httpx_verify)+ if keepalive_http is not None:+ safe_kwargs["http_client"] = keepalive_http+ client = SolsticeClient(**safe_kwargs)+ _ra().logger.info(+ "Solstice client created (%s, shared=%s) %s", reason, shared, agent._client_log_context()+ )+ return client++def create_openai_client(agent, client_kwargs: dict, *, reason: str, shared: bool) -> Any:from agent.auxiliary_client import (_to_openai_base_url,@@ -2076,6 +2103,9 @@ def create_openai_client(agent, client_kwargs: dict, *, reason: str, shared: booclient = _gemini_native_client(agent, client_kwargs, httpx_verify, reason=reason, shared=shared)if client is not None:return client+ client = _solstice_client(agent, client_kwargs, httpx_verify, reason=reason, shared=shared)+ if client is not None:+ return client# TCP keepalives so dead provider connections are detected (~60s) instead of hanging in# CLOSE-WAIT. Injected into the local copy only, so each client gets its own httpx.Client;# pinned by tests/agent/test_create_openai_client_reuse.py. What IS shared across those per-client wrappers is thediff --git a/agent/solstice_adapter.py b/agent/solstice_adapter.pynew file mode 100644index 00000000000..62c0a3e1a08--- /dev/null+++ b/agent/solstice_adapter.py@@ -0,0 +1,257 @@+"""Solstice per-user-quota transport.++Lets a user bring their own Solstice subscription into Hermes. Inference is+authenticated with the user's OAuth access token (Bearer), not a static API+key; the ``peruserquota`` scope maps usage to the signed-in user's own quota.+The wire shape is the ``GenerateContent`` contract served on the+``:generateContentPerUserQuota`` variants.++Reuses the native adapter's message/tool translation, stream handling and HTTP+error mapping wholesale; only auth and the endpoint suffix differ:+ - auth = Bearer OAuth token (the user's OAuth access token), not API key+ - endpoint = ``...:generateContentPerUserQuota`` (non-stream) /+ ``...:streamGenerateContentPerUserQuota`` (stream)+ - base = ``https://generativelanguage.googleapis.com/v1alpha``++Exposes the OpenAI-SDK-compatible facade (``chat.completions.create`` ++``.stream()``) so it drops into the same transport seams, and is constructed by+the same ``agent_runtime_helpers`` seam.+"""++from __future__ import annotations++import logging+from typing import Any, Dict, Iterator, Optional++import httpx++from agent.gemini_native_adapter import (+ GeminiNativeClient,+ _GeminiStreamChunk,+ bare_gemini_model_id,+ build_gemini_request,+)++logger = logging.getLogger(__name__)++# Inference host — single source of truth lives in+# hermes_cli/solstice.py so a launch-time host correction is one edit.+from hermes_cli.solstice import ( # noqa: E402+ SOLSTICE_INFERENCE_BASE_URL as SOLSTICE_BASE_URL,+)++# Per-user-quota variant endpoints. The stream variant follows the native+# ``:streamGenerateContent`` naming convention and is kept as a constant so a+# correction is one line.+SOLSTICE_GENERATE_PATH = ":generateContentPerUserQuota"+SOLSTICE_STREAM_PATH = ":streamGenerateContentPerUserQuota"+++def build_solstice_request(+ *,+ model: str,+ messages: list[Dict[str, Any]],+ tools: Any = None,+ tool_choice: Any = None,+ temperature: Optional[float] = None,+ max_tokens: Optional[int] = None,+ top_p: Optional[float] = None,+ stop: Any = None,+ thinking_config: Any = None,+) -> Dict[str, Any]:+ """Build the standard body for the per-user-quota endpoint.++ Identical to ``build_gemini_request`` (the endpoint takes+ the standard ``GenerateContent`` body); this wrapper exists so the adapter+ has a single, explicit construction point and a stable name.+ """+ return build_gemini_request(+ messages=messages,+ tools=tools,+ tool_choice=tool_choice,+ temperature=temperature,+ max_tokens=max_tokens,+ top_p=top_p,+ stop=stop,+ thinking_config=thinking_config,+ )+++class SolsticeClient:+ """OpenAI-SDK-compatible facade over the per-user-quota API.++ Auth is a **Bearer** OAuth access token (the user's Solstice+ subscription), not an API key. Reuses the native adapter's translation+ wholesale; only the auth and endpoint differ.+ """++ def __init__(+ self,+ *,+ api_key: str, # the OAuth access token (Bearer)+ base_url: Optional[str] = None,+ default_headers: Optional[Dict[str, str]] = None,+ timeout: Any = None,+ http_client: Optional[httpx.Client] = None,+ **_: Any,+ ) -> None:+ if not (api_key or "").strip():+ raise RuntimeError(+ "Solstice client requires an OAuth access token, but none was "+ "provided. Run `hermes auth add solstice` to sign in."+ )+ self.api_key = api_key+ self.base_url = (base_url or SOLSTICE_BASE_URL).rstrip("/")+ self._default_headers = dict(default_headers or {})+ self._http = http_client or httpx.Client(+ timeout=timeout+ or httpx.Timeout(connect=15.0, read=600.0, write=30.0, pool=30.0)+ )+ self.is_closed = False+ self.chat = _SolsticeChatNamespace(self)++ def close(self) -> None:+ self.is_closed = True+ try:+ self._http.close()+ except Exception:+ pass++ def __enter__(self) -> "SolsticeClient":+ return self++ def __exit__(self, exc_type, exc_val, exc_tb) -> None:+ self.close()++ # -- internals ---------------------------------------------------------++ def _headers(self) -> Dict[str, str]:+ headers = {+ "Content-Type": "application/json",+ "Accept": "application/json",+ "Authorization": f"Bearer {self.api_key}",+ }+ headers.update(self._default_headers)+ return headers++ def _create_chat_completion(+ self,+ *,+ model: str = "gemini-flash-latest",+ messages: Optional[list[Dict[str, Any]]] = None,+ stream: bool = False,+ tools: Any = None,+ tool_choice: Any = None,+ temperature: Optional[float] = None,+ max_tokens: Optional[int] = None,+ top_p: Optional[float] = None,+ stop: Any = None,+ extra_body: Optional[Dict[str, Any]] = None,+ timeout: Any = None,+ **_: Any,+ ) -> Any:+ thinking_config = None+ if isinstance(extra_body, dict):+ thinking_config = extra_body.get("thinking_config") or extra_body.get(+ "thinkingConfig"+ )++ body = build_solstice_request(+ model=model,+ messages=messages or [],+ tools=tools,+ tool_choice=tool_choice,+ temperature=temperature,+ max_tokens=max_tokens,+ top_p=top_p,+ stop=stop,+ thinking_config=thinking_config,+ )++ if stream:+ return self._stream_completion(+ model=model, body=body, timeout=timeout+ )++ url = f"{self.base_url}/models/{bare_gemini_model_id(model)}{SOLSTICE_GENERATE_PATH}"+ response = self._http.post(+ url, json=body, headers=self._headers(), timeout=timeout+ )+ if response.status_code != 200:+ from agent.gemini_native_adapter import gemini_http_error++ raise gemini_http_error(response)+ try:+ payload = response.json()+ except ValueError as exc:+ raise RuntimeError(f"Invalid JSON from Solstice API: {exc}") from exc++ from agent.gemini_native_adapter import translate_gemini_response++ return translate_gemini_response(payload, model=model)++ def _stream_completion(+ self, *, model: str, body: Dict[str, Any], timeout: Any = None+ ) -> Iterator[_GeminiStreamChunk]:+ from agent.bounded_response import read_streaming_error_body+ from agent.gemini_native_adapter import (+ _iter_sse_events,+ gemini_http_error,+ translate_stream_event,+ )++ # alt=sse is REQUIRED. Without it the per-user-quota stream endpoint+ # returns a bare JSON array of complete responses (``[{...},{...}]``),+ # not SSE — ``_iter_sse_events`` finds no ``data:`` lines, yields+ # nothing, and the caller reports a bogus EmptyStreamError. With it the+ # response is real ``data: {...}`` SSE, matching the native adapter.+ url = (+ f"{self.base_url}/models/{bare_gemini_model_id(model)}"+ f"{SOLSTICE_STREAM_PATH}?alt=sse"+ )+ stream_headers = dict(self._headers())+ stream_headers["Accept"] = "text/event-stream"++ def _generator() -> Iterator[_GeminiStreamChunk]:+ try:+ with self._http.stream(+ "POST", url, json=body, headers=stream_headers, timeout=timeout+ ) as response:+ if response.status_code != 200:+ body_text = read_streaming_error_body(response)+ raise gemini_http_error(response, body_text=body_text)+ tool_call_indices: Dict[str, Dict[str, Any]] = {}+ for event in _iter_sse_events(response):+ for chunk in translate_stream_event(+ event, model, tool_call_indices+ ):+ yield chunk+ finally:+ pass++ return _generator()+++class _SolsticeChatCompletions:+ """``client.chat.completions`` namespace (sync)."""++ def __init__(self, client: SolsticeClient) -> None:+ self._client = client++ def create(self, **kwargs: Any) -> Any:+ return self._client._create_chat_completion(**kwargs)++ def stream(self, **kwargs: Any) -> Any:+ return self._client._create_chat_completion(stream=True, **kwargs)+++class _SolsticeChatNamespace:+ def __init__(self, client: SolsticeClient) -> None:+ self.completions = _SolsticeChatCompletions(client)+++__all__ = [+ "SolsticeClient",+ "build_solstice_request",+ "SOLSTICE_BASE_URL",+]diff --git a/hermes_cli/auth_commands.py b/hermes_cli/auth_commands.pyindex 75d52b7aa4d..ddf330f0af8 100644--- a/hermes_cli/auth_commands.py+++ b/hermes_cli/auth_commands.py@@ -33,6 +33,8 @@ _OAUTH_CAPABLE_PROVIDERS = {"anthropic", "nous", "openai-codex", "xai-oauth", "q_OAUTH_DEFAULT_PROVIDERS = _OAUTH_CAPABLE_PROVIDERS - {"openrouter"}# Providers whose sibling CLI login Hermes may borrow (``auth.adopt_external_logins``).EXTERNAL_LOGIN_PROVIDERS = {"anthropic", "openai-codex"}+# OAuth-only, but hidden: adding to the set above would advertise it in the interactive type prompt.+_OAUTH_ONLY_HIDDEN_PROVIDERS = {"solstice"}def _get_custom_provider_entries() -> list[dict]:@@ -81,7 +83,13 @@ def _resolve_custom_provider_input(raw: str) -> str | None:_PROVIDER_ALIASES = {"or": "openrouter", "open-router": "openrouter", "grok-oauth": "xai-oauth",- "xai-oauth": "xai-oauth", "x-ai-oauth": "xai-oauth", "xai-grok-oauth": "xai-oauth"}+ "xai-oauth": "xai-oauth", "x-ai-oauth": "xai-oauth", "xai-grok-oauth": "xai-oauth",+ "solstice": "solstice",+ "solstice-oauth": "solstice"}++# Pre-release OAuth providers kept OUT of PROVIDER_REGISTRY so they never surface in pickers,+# `hermes auth list`, or doctor. They remain addable by explicit name (see _is_known_provider).+_HIDDEN_OAUTH_PROVIDERS = {"solstice"}def _normalize_provider(provider: str) -> str:@@ -134,7 +142,8 @@ def _provider_base_url(provider: str) -> str:def _is_known_provider(provider: str, configured_provider: dict | None) -> bool:return (provider in PROVIDER_REGISTRY or provider == "openrouter"- or provider.startswith(CUSTOM_POOL_PREFIX) or configured_provider is not None)+ or provider.startswith(CUSTOM_POOL_PREFIX) or provider in _HIDDEN_OAUTH_PROVIDERS+ or configured_provider is not None)def _unknown_provider_exit(provider: str) -> SystemExit:@@ -242,6 +251,24 @@ def _codex_pool_source(creds: dict) -> str:return SOURCE_MANUAL_DEVICE_CODE+def _solstice_login(args) -> dict:+ """Run the Solstice PKCE loopback login and return its token bundle for the pool entry.++ The full OAuth handshake (NAS-brokered exchange, PKCE verifier, loopback callback) lives in+ ``hermes_cli.solstice``; this only adapts its result to the ``_OAuthAddSpec`` shape.+ """+ from hermes_cli.solstice import SOLSTICE_INFERENCE_BASE_URL, _login_solstice++ _login_solstice(args, None)+ state = auth_mod._load_provider_state(auth_mod._load_auth_store(), "solstice") or {}+ tokens = state.get("tokens") if isinstance(state.get("tokens"), dict) else {}+ return {+ "access_token": str(tokens.get("access_token") or "").strip(),+ "refresh_token": str(tokens.get("refresh_token") or "").strip(),+ "base_url": SOLSTICE_INFERENCE_BASE_URL,+ }++_OAUTH_ADD_SPECS: dict[str, _OAuthAddSpec] = {"anthropic": _OAuthAddSpec(login=_anthropic_oauth_login,@@ -292,6 +319,13 @@ _OAUTH_ADD_SPECS: dict[str, _OAuthAddSpec] = {source=f"{SOURCE_MANUAL}:openrouter_pkce",fields=lambda creds, provider: {"base_url": _provider_base_url(provider)},auth_type=AUTH_TYPE_API_KEY),+ "solstice": _OAuthAddSpec(+ login=_solstice_login,+ token=lambda creds: creds["access_token"],+ source=f"{SOURCE_MANUAL}:solstice_oauth",+ fields=lambda creds, provider: {+ "refresh_token": creds.get("refresh_token") or None,+ "base_url": creds.get("base_url") or _provider_base_url(provider)}),}@@ -392,7 +426,8 @@ def auth_add_command(args) -> None:if requested_type == "api-key":requested_type = AUTH_TYPE_API_KEYelif not requested_type:- oauth_default = provider in _OAUTH_DEFAULT_PROVIDERS and not is_custom+ oauth_default = (provider in _OAUTH_DEFAULT_PROVIDERS+ or provider in _OAUTH_ONLY_HIDDEN_PROVIDERS) and not is_customrequested_type = AUTH_TYPE_OAUTH if oauth_default else AUTH_TYPE_API_KEYpool = load_pool(provider)diff --git a/hermes_cli/main.py b/hermes_cli/main.pyindex 8d1dc1172a5..d5dec53a1f4 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -775,6 +775,7 @@ from hermes_cli.model_setup_flows import (_model_flow_xai_oauth,_model_flow_qwen_oauth,_model_flow_minimax_oauth,+ _model_flow_solstice,_model_flow_custom,_model_flow_azure_foundry,_model_flow_named_custom,@@ -2020,6 +2021,7 @@ _PROVIDER_MODEL_FLOWS = {"xai-oauth": lambda c, m, a: _model_flow_xai_oauth(c, m, args=a),"qwen-oauth": lambda c, m, a: _model_flow_qwen_oauth(c, m),"minimax-oauth": lambda c, m, a: _model_flow_minimax_oauth(c, m, args=a),+ "solstice": lambda c, m, a: _model_flow_solstice(c, m, args=a),"copilot-acp": lambda c, m, a: _model_flow_copilot_acp(c, m),"copilot": lambda c, m, a: _model_flow_copilot(c, m),"custom": lambda c, m, a: _model_flow_custom(c),diff --git a/hermes_cli/model_setup_flows.py b/hermes_cli/model_setup_flows.pyindex 64dbb38181c..dbc13c8f1ae 100644--- a/hermes_cli/model_setup_flows.py+++ b/hermes_cli/model_setup_flows.py@@ -480,6 +480,36 @@ def _model_flow_minimax_oauth(config, current_model="", args=None):_activate_provider_model(selected, "minimax-oauth", creds["base_url"], f"\u2713 Using MiniMax model: {selected}", no_change=None)+def _model_flow_solstice(config, current_model="", args=None):+ """Solstice provider: ensure logged in, then pick model."""+ from hermes_cli.auth import AuthError, format_auth_error, _prompt_model_selection+ from hermes_cli.solstice import (+ SOLSTICE_INFERENCE_BASE_URL, _login_solstice, get_solstice_status,+ resolve_solstice_runtime_credentials)++ if not get_solstice_status().get("logged_in"):+ _say("Not logged into Solstice. Starting OAuth login...", "")+ mock_args = argparse.Namespace(+ no_browser=bool(getattr(args, "no_browser", False)),+ timeout=getattr(args, "timeout", None) or 30.0)+ if not _run_login(_login_solstice, mock_args, None):+ return++ try:+ creds = resolve_solstice_runtime_credentials()+ except AuthError as exc:+ print(format_auth_error(exc))+ return++ base_url = creds.get("base_url") or SOLSTICE_INFERENCE_BASE_URL+ from hermes_cli.models import provider_model_ids+ model_ids = provider_model_ids("solstice")+ selected = _prompt_model_selection(model_ids, current_model, confirm_provider="solstice",+ confirm_base_url=base_url)+ _activate_provider_model(selected, "solstice", base_url,+ f"\u2713 Using Solstice model: {selected}")++def _copilot_model_list(live_ids) -> list:"""Live GitHub Copilot ids, or the curated fallback with a warning."""from hermes_cli.models import _PROVIDER_MODELSdiff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex 8024f3b5634..914e322913b 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -1620,6 +1620,25 @@ def _azure_foundry_catalog(normalized: str, force_refresh: bool) -> Optional[lisreturn None+def _solstice_catalog(normalized: str, force_refresh: bool) -> Optional[list[str]]:+ """Curated picker list for Solstice (per-user-quota).++ The ``:generateContentPerUserQuota`` endpoint has no public model catalog to probe — a+ per-user token gets 403 ACCESS_TOKEN_SCOPE_INSUFFICIENT from ``/v1alpha/models`` — so the+ profile's VERIFIED ``fallback_models`` is the only safe source. Returns None when the+ profile is unavailable so the generic path still runs.+ """+ from providers import get_provider_profile++ try:+ profile = get_provider_profile("solstice")+ except Exception:+ return None+ if profile is not None and profile.fallback_models:+ return list(profile.fallback_models)+ return list(_PROVIDER_MODELS.get("solstice", [])) or None++# Per-provider catalog sources tried before the generic profile fetch. A fetcher returning None# falls through to the profile/curated path; a list is returned as-is (even empty)._PROVIDER_CATALOG_FETCHERS: dict[str, Any] = {@@ -1640,7 +1659,9 @@ _PROVIDER_CATALOG_FETCHERS: dict[str, Any] = {"openai-api": _openai_catalog,"custom": _custom_catalog,"bedrock": _bedrock_catalog,- "azure-foundry": _azure_foundry_catalog}+ "azure-foundry": _azure_foundry_catalog,+ # No live catalog: OAuth-only per-user-quota provider; curated verified ids only.+ "solstice": _solstice_catalog}# ``-free`` slugs the relay still LISTS but no longer serves: the Go-only twin (``ox-alpha-free``)diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.pyindex 2e1f9d26302..2cd78c9cea4 100644--- a/hermes_cli/runtime_provider.py+++ b/hermes_cli/runtime_provider.py@@ -860,6 +860,9 @@ def _api_key_provider_runtime(provider, pconfig, requested_provider, model_cfg,# ── the resolution ladder ──────────────────────────────────────────────────────────────────_VERTEX_NAMES = ("vertex", "google-vertex", "vertex-ai", "gcp-vertex", "vertexai")+# Solstice is a hidden (pre-release) OAuth provider deliberately kept out of PROVIDER_REGISTRY,+# so resolve_provider() would raise "Unknown provider" before any provider-specific rung ran.+_SOLSTICE_NAMES = ("solstice", "solstice-oauth")_LOCAL_BYPASS_CLOUD_HOSTS = ("openrouter.ai", "anthropic.com", "openai.com")@@ -939,6 +942,16 @@ def _resolve_requested_shortcuts(requested_provider, explicit_api_key, explicit_target_model=target_model)if requested_provider in _VERTEX_NAMES:return _resolve_vertex_runtime(requested_provider)+ # Resolve on the REQUESTED name alone: the provider is absent from the registry by design.+ if requested_provider in _SOLSTICE_NAMES:+ from hermes_cli.solstice import resolve_solstice_runtime_credentials++ creds = resolve_solstice_runtime_credentials()+ return _runtime(+ "solstice", "chat_completions", str(creds.get("base_url", "")).rstrip("/"),+ creds.get("api_key", ""), source=creds.get("source", "hermes-auth-store"),+ last_refresh=creds.get("last_refresh"), expires_at_ms=creds.get("expires_at_ms"),+ requested_provider=requested_provider)return Nonediff --git a/hermes_cli/solstice.py b/hermes_cli/solstice.pynew file mode 100644index 00000000000..1b66a49b5e8--- /dev/null+++ b/hermes_cli/solstice.py@@ -0,0 +1,795 @@+"""Solstice OAuth flow — PKCE loopback login, NAS-brokered exchange.++Solstice authenticates with the user's Solstice account. The flow:++1. Hermes generates a PKCE pair + state nonce and opens the authorize+ URL in the browser, with ``redirect_uri`` pointing at a local loopback.+2. The provider redirects the code back to the loopback listener.+3. Hermes POSTs ``{code, code_verifier, redirect_uri}`` to a **NAS broker+ endpoint** which holds the ``client_secret`` (never shipped to+ Hermes) and performs the token exchange.+4. Tokens are stored in ``auth.json`` ``providers.solstice`` (same custody+ model as xai-oauth / qwen-oauth), and refreshed through the NAS broker+ whenever the access token nears expiry.++Inference traffic goes DIRECT from Hermes to+``generativelanguage.googleapis.com`` (the per-user-quota endpoint) with+the access token — NAS is out of the prompt path entirely.++Secret-launch mechanics: the provider is `hidden=True` (out of pickers and auth+lists) but enabled by default once a logged-in Nous user has a reachable NAS+broker; ``hermes auth add solstice`` surfaces it. The module defers to the+single auth-side gate ``solstice_enabled`` (see that function).+"""++from __future__ import annotations++import base64+import hashlib+import logging+import os+import secrets+import time+from datetime import datetime, timezone+from http.server import BaseHTTPRequestHandler, HTTPServer+from typing import Any, Dict, Optional+from urllib.parse import parse_qs, urlencode, urlparse++import httpx++logger = logging.getLogger(__name__)++# ---------------------------------------------------------------------------+# Configuration (env-sourced — NO defaults baked into the tree)+# ---------------------------------------------------------------------------++# Base URL of the NAS broker that holds the client_secret and performs the+# code exchange / refresh, and owns the client config (discovered at+# login). Defaults to the public portal origin.+SOLSTICE_NAS_BASE_URL_ENV = "SOLSTICE_NAS_BASE_URL"+DEFAULT_SOLSTICE_NAS_BASE_URL = "https://portal.nousresearch.com"++SOLSTICE_ACCESS_TOKEN_REFRESH_SKEW_SECONDS = 300 # refresh 5 min before expiry++# NAS broker endpoints.+SOLSTICE_NAS_EXCHANGE_PATH = "/api/oauth/gemini-auth/exchange"+SOLSTICE_NAS_REFRESH_PATH = "/api/oauth/gemini-auth/refresh"+SOLSTICE_NAS_CONFIG_PATH = "/api/oauth/gemini-auth/config"++# Inference base URL — per-user-quota host. SINGLE SOURCE OF TRUTH for+# the inference host: the provider profile (plugins/model-providers/solstice)+# and the transport (agent/solstice_adapter.py) import this constant, so a+# launch-time host correction is a one-line change in exactly one place.+SOLSTICE_INFERENCE_BASE_URL = "https://generativelanguage.googleapis.com/v1alpha"+++class _AuthError(Exception):+ """Local stand-in for ``hermes_cli.auth.AuthError``.++ Deliberately NOT imported from ``hermes_cli.auth`` at module top: this+ module must stay light-importable (std + httpx) because the solstice+ provider plugin imports it during provider discovery, and pulling in+ ``hermes_cli.auth`` there would drag the whole auth subsystem into every+ ``list_providers()`` call. The exception is converted to the real+ ``AuthError`` at the module boundary (``resolve_solstice_runtime_credentials``),+ so callers outside this module always see the canonical type.+ """++ def __init__(+ self,+ message: str,+ *,+ provider: str = "solstice",+ code: str = "solstice_error",+ relogin_required: bool = False,+ ) -> None:+ super().__init__(message)+ self.provider = provider+ self.code = code+ self.relogin_required = relogin_required+++def solstice_enabled() -> bool:+ """True when the Solstice provider is surfaced/usable.++ With NAS owning the client config (discovered at login), there is+ no local enable-gate env var — the provider is enabled by default and+ usable whenever a logged-in Nous user has a reachable NAS broker. The+ provider stays `hidden=True` (out of the default picker) until configured,+ matching the dark-launch intent; once a user runs `hermes auth add+ solstice` it becomes the active provider.+ """+ return True+++def solstice_nas_base_url() -> str:+ """Return the NAS broker base URL (env override or portal default)."""+ return (+ os.getenv(SOLSTICE_NAS_BASE_URL_ENV, "") or ""+ ).strip() or DEFAULT_SOLSTICE_NAS_BASE_URL+++def _validate_broker_url(url: str) -> str:+ """Refuse a non-HTTPS broker URL (MITM → refresh-token leak guard)."""+ parsed = urlparse(url)+ if parsed.scheme != "https":+ raise _AuthError(+ f"Solstice NAS broker URL must be HTTPS: {url!r}",+ code="solstice_broker_invalid",+ )+ if not parsed.hostname:+ raise _AuthError(+ f"Solstice NAS broker URL is missing a hostname: {url!r}",+ code="solstice_broker_invalid",+ )+ return url.rstrip("/")+++# ---------------------------------------------------------------------------+# Token store (auth.json providers.solstice)+# ---------------------------------------------------------------------------+++def _solstice_state_from_store(+ auth_store: Dict[str, Any],+) -> Optional[Dict[str, Any]]:+ from hermes_cli.auth import _load_provider_state++ state = _load_provider_state(auth_store, "solstice")+ if isinstance(state, dict):+ return state+ credential_pool = auth_store.get("credential_pool")+ entries = (+ credential_pool.get("solstice")+ if isinstance(credential_pool, dict)+ else None+ )+ if isinstance(entries, list):+ for entry in entries:+ if not isinstance(entry, dict):+ continue+ access_token = str(entry.get("access_token", "") or "").strip()+ refresh_token = str(entry.get("refresh_token", "") or "").strip()+ if not access_token or not refresh_token:+ continue+ merged = dict(state or {})+ merged["tokens"] = {+ "access_token": access_token,+ "refresh_token": refresh_token,+ "token_type": str(entry.get("token_type") or "Bearer"),+ }+ if entry.get("last_refresh"):+ merged["last_refresh"] = entry.get("last_refresh")+ merged.setdefault("auth_mode", "oauth_pkce")+ return merged+ return state if isinstance(state, dict) else None+++def _solstice_state_has_usable_tokens(state: Optional[Dict[str, Any]]) -> bool:+ tokens = state.get("tokens") if isinstance(state, dict) else None+ return (+ isinstance(tokens, dict)+ and bool(str(tokens.get("access_token", "") or "").strip())+ and bool(str(tokens.get("refresh_token", "") or "").strip())+ )+++def _read_solstice_tokens(*, _lock: bool = True) -> Dict[str, Any]:+ from hermes_cli.auth import (+ _auth_store_lock,+ _load_auth_store,+ _load_global_auth_store,+ )++ if _lock:+ with _auth_store_lock():+ auth_store = _load_auth_store()+ else:+ auth_store = _load_auth_store()+ state = _solstice_state_from_store(auth_store)+ if not _solstice_state_has_usable_tokens(state):+ global_state = _solstice_state_from_store(_load_global_auth_store())+ if _solstice_state_has_usable_tokens(global_state):+ state = global_state+ if not state:+ raise _AuthError(+ "No Solstice credentials stored. Sign in with `hermes auth add solstice`.",+ code="solstice_missing",+ relogin_required=True,+ )+ tokens = state.get("tokens")+ if not isinstance(tokens, dict):+ raise _AuthError(+ "Solstice auth state is missing tokens. Re-authenticate.",+ code="solstice_invalid_shape",+ relogin_required=True,+ )+ return {+ "tokens": tokens,+ "last_refresh": state.get("last_refresh"),+ "redirect_uri": state.get("redirect_uri"),+ "auth_mode": state.get("auth_mode", "oauth_pkce"),+ }+++def _save_solstice_tokens(+ tokens: Dict[str, Any],+ *,+ redirect_uri: str = "",+ last_refresh: Optional[str] = None,+ set_active: bool = True,+) -> None:+ """Persist Solstice tokens into auth.json (with global-root write-through)."""+ from hermes_cli.auth import (+ _auth_store_lock,+ _global_auth_file_path,+ _load_auth_store,+ _load_provider_state_with_source,+ _persist_provider_state_to_store,+ _same_path,+ _save_auth_store,+ _store_provider_state,+ )++ if last_refresh is None:+ last_refresh = datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+ with _auth_store_lock():+ auth_store = _load_auth_store()+ state, source_path = _load_provider_state_with_source(auth_store, "solstice")+ if state is None:+ state = {}+ state["tokens"] = tokens+ state["last_refresh"] = last_refresh+ state["auth_mode"] = "oauth_pkce"+ if redirect_uri:+ state["redirect_uri"] = redirect_uri+ global_root = _global_auth_file_path()+ is_from_root = bool(+ source_path is not None+ and global_root is not None+ and _same_path(source_path, global_root)+ )+ if is_from_root and global_root is not None:+ _persist_provider_state_to_store(+ "solstice", state, global_root, set_active=False+ )+ else:+ _store_provider_state(+ auth_store, "solstice", state, set_active=set_active+ )+ _save_auth_store(auth_store)+++def _solstice_access_token_is_expiring(+ access_token: str, skew_seconds: int = 0+) -> bool:+ """True when a JWT access token's ``exp`` is within *skew_seconds*."""+ if not isinstance(access_token, str) or "." not in access_token:+ return False+ try:+ import base64+ import json++ parts = access_token.split(".")+ if len(parts) < 2:+ return False+ payload_b64 = parts[1]+ payload_b64 += "=" * (-len(payload_b64) % 4)+ payload = json.loads(+ base64.urlsafe_b64decode(payload_b64.encode("ascii")).decode("utf-8")+ )+ exp = payload.get("exp")+ if not isinstance(exp, (int, float)):+ return False+ return float(exp) <= (time.time() + max(0, int(skew_seconds)))+ except Exception:+ return False+++# ---------------------------------------------------------------------------+# NAS broker calls+# ---------------------------------------------------------------------------+++def _nous_bearer_header() -> Dict[str, str]:+ """Resolve the caller's Nous access token and build a Bearer auth header.++ NAS gates the Solstice broker behind a valid Nous token from a logged-in+ user (no specific scope). Lazily imported so this module stays+ light-importable during provider discovery.+ """+ from hermes_cli.auth import resolve_nous_access_token++ token = resolve_nous_access_token()+ return {"Authorization": f"Bearer {token}"}+++def _exchange_code(+ code: str, code_verifier: str, redirect_uri: str, *, timeout: float = 30.0+) -> Dict[str, Any]:+ """POST the authorize code to the NAS broker for token exchange."""+ broker = _validate_broker_url(solstice_nas_base_url())+ url = f"{broker}{SOLSTICE_NAS_EXCHANGE_PATH}"+ headers = {"Accept": "application/json", **_nous_bearer_header()}+ with httpx.Client(timeout=httpx.Timeout(timeout)) as client:+ response = client.post(+ url,+ json={+ "code": code,+ "code_verifier": code_verifier,+ "redirect_uri": redirect_uri,+ },+ headers=headers,+ )+ if response.status_code != 200:+ raise _AuthError(+ f"Solstice OAuth exchange failed (HTTP {response.status_code})."+ + (f" {response.text.strip()}" if response.text else ""),+ code="solstice_exchange_failed",+ )+ payload = response.json()+ for key in ("access_token", "refresh_token"):+ if not str(payload.get(key, "") or "").strip():+ raise _AuthError(+ f"Solstice OAuth exchange response missing {key}.",+ code="solstice_exchange_invalid",+ )+ return payload+++def _refresh_tokens(refresh_token: str, *, timeout: float = 30.0) -> Dict[str, Any]:+ """POST the refresh token to the NAS broker for rotation."""+ broker = _validate_broker_url(solstice_nas_base_url())+ url = f"{broker}{SOLSTICE_NAS_REFRESH_PATH}"+ headers = {"Accept": "application/json", **_nous_bearer_header()}+ with httpx.Client(timeout=httpx.Timeout(timeout)) as client:+ response = client.post(+ url,+ json={"refresh_token": refresh_token},+ headers=headers,+ )+ if response.status_code != 200:+ body = response.text or response.reason_phrase+ relogin = "invalid_grant" in body.lower() or "refresh_token" in body.lower()+ raise _AuthError(+ f"Solstice token refresh failed: {body}",+ code="solstice_refresh_failed",+ relogin_required=relogin,+ )+ payload = response.json()+ if not str(payload.get("access_token", "") or "").strip():+ raise _AuthError(+ "Solstice refresh response missing access_token.",+ code="solstice_refresh_invalid",+ relogin_required=True,+ )+ return payload+++def _fetch_solstice_config(*, timeout: float = 30.0) -> Dict[str, Any]:+ """GET the client config from NAS (client_id, scope, authorize_url).++ NAS is the single source of truth for the client config; the local agent+ builds its authorize URL from this (adding only its own PKCE challenge,+ state, and loopback redirect_uri).+ """+ broker = _validate_broker_url(solstice_nas_base_url())+ url = f"{broker}{SOLSTICE_NAS_CONFIG_PATH}"+ headers = {"Accept": "application/json", **_nous_bearer_header()}+ with httpx.Client(timeout=httpx.Timeout(timeout)) as client:+ response = client.get(url, headers=headers)+ if response.status_code != 200:+ raise _AuthError(+ f"Solstice config fetch failed (HTTP {response.status_code})."+ + (f" {response.text.strip()}" if response.text else ""),+ code="solstice_config_failed",+ )+ payload = response.json()+ for key in ("client_id", "authorize_url", "scope"):+ if not str(payload.get(key, "") or "").strip():+ raise _AuthError(+ f"Solstice config response missing {key}.",+ code="solstice_config_invalid",+ )+ return payload+++# ---------------------------------------------------------------------------+# Login flow (PKCE loopback)+# ---------------------------------------------------------------------------+++def _solstice_pkce_pair() -> tuple[str, str, str]:+ """Return (code_verifier, code_challenge_S256, state) for the Solstice login.++ Self-contained rather than shared: PKCE generation is per-provider on this tree (see+ ``auth_minimax._minimax_pkce_pair`` / ``auth_spotify._spotify_code_verifier``), and this module+ must stay light-importable during provider discovery.+ """+ verifier = secrets.token_urlsafe(64)[:96]+ challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip("=")+ return verifier, challenge, secrets.token_urlsafe(24)+++def _make_solstice_callback_handler(+ expected_path: str,+) -> tuple[type[BaseHTTPRequestHandler], Dict[str, Any]]:+ result: Dict[str, Any] = {+ "code": None,+ "state": None,+ "error": None,+ "error_description": None,+ }++ class _SolsticeCallbackHandler(BaseHTTPRequestHandler):+ def do_GET(self) -> None: # noqa: N802+ parsed = urlparse(self.path)+ if parsed.path != expected_path:+ self.send_response(404)+ self.end_headers()+ self.wfile.write(b"Not found.")+ return+ params = parse_qs(parsed.query)+ result["code"] = params.get("code", [None])[0]+ result["state"] = params.get("state", [None])[0]+ result["error"] = params.get("error", [None])[0]+ result["error_description"] = params.get("error_description", [None])[0]+ self.send_response(200)+ self.send_header("Content-Type", "text/html; charset=utf-8")+ self.end_headers()+ if result["error"]:+ body = "<html><body><h1>Solstice authorization failed.</h1>You can close this tab.</body></html>"+ else:+ body = "<html><body><h1>Solstice authorization received.</h1>You can close this tab.</body></html>"+ self.wfile.write(body.encode("utf-8"))++ def log_message(self, format: str, *args: Any) -> None: # noqa: A003+ return++ return _SolsticeCallbackHandler, result+++def _wait_for_loopback_callback(+ port: int, path: str, *, timeout_seconds: float = 180.0+) -> Dict[str, Any]:+ """Run the loopback listener until the code arrives (or timeout/error)."""+ import threading++ handler_cls, result = _make_solstice_callback_handler(path)++ class _ReuseHTTPServer(HTTPServer):+ allow_reuse_address = True++ try:+ server = _ReuseHTTPServer(("127.0.0.1", port), handler_cls)+ except OSError as exc:+ raise _AuthError(+ f"Could not bind Solstice callback server on 127.0.0.1:{port}: {exc}",+ code="solstice_callback_bind_failed",+ ) from exc++ thread = threading.Thread(+ target=server.serve_forever, kwargs={"poll_interval": 0.1}, daemon=True+ )+ thread.start()+ deadline = time.monotonic() + max(5.0, timeout_seconds)+ try:+ while time.monotonic() < deadline:+ if result["code"] or result["error"]:+ return result+ time.sleep(0.1)+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=1.0)+ raise _AuthError(+ "Solstice authorization timed out waiting for the local callback.",+ code="solstice_callback_timeout",+ )+++def _pick_loopback_port() -> int:+ """Ask the OS for a free loopback port, then release it for the listener."""+ import socket++ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:+ sock.bind(("127.0.0.1", 0))+ return int(sock.getsockname()[1])+++def _login_solstice(+ args: Any,+ pconfig: Any,+ *,+ force_new_login: bool = False,+) -> None:+ """Run the Solstice PKCE loopback login and persist tokens."""+ del pconfig # parity with other provider login helpers++ if not solstice_enabled():+ raise _AuthError(+ "Solstice is not configured. Set SOLSTICE_CLIENT_ID in "+ "~/.hermes/.env and try again.",+ code="solstice_not_configured",+ )++ if not force_new_login:+ try:+ existing = resolve_solstice_runtime_credentials(+ refresh_if_expiring=False+ )+ api_key = existing.get("api_key", "")+ if api_key and not _solstice_access_token_is_expiring(api_key, 60):+ print("Existing Solstice credentials found in Hermes auth store.")+ try:+ reuse = input("Use existing credentials? [Y/n]: ").strip().lower()+ except (EOFError, KeyboardInterrupt):+ reuse = "y"+ if reuse in {"", "y", "yes"}:+ from hermes_cli.auth import _update_config_for_provider++ _update_config_for_provider(+ "solstice",+ existing.get("base_url", SOLSTICE_INFERENCE_BASE_URL),+ )+ print()+ print("Login successful!")+ return+ except Exception:+ pass # no existing creds → fall through to a fresh login++ cfg = _fetch_solstice_config()+ verifier, challenge, state = _solstice_pkce_pair()+ port = _pick_loopback_port()+ redirect_uri = f"http://127.0.0.1:{port}/gemini-auth/callback"++ print()+ print("Signing in to Solstice...")+ print("(Hermes creates its own local OAuth session — tokens stay on this machine)")+ print()++ authorize_params = {+ "client_id": cfg["client_id"],+ "redirect_uri": redirect_uri,+ "response_type": "code",+ "scope": cfg["scope"],+ "code_challenge": challenge,+ "code_challenge_method": "S256",+ "state": state,+ "access_type": "offline",+ "prompt": "consent",+ }+ authorize_url = f"{cfg['authorize_url']}?{urlencode(authorize_params)}"++ open_browser = not bool(getattr(args, "no_browser", False))+ can_open_browser = True+ try:+ from hermes_cli.auth import _can_open_graphical_browser, _is_remote_session++ if _is_remote_session():+ open_browser = False+ if not _can_open_graphical_browser():+ can_open_browser = False+ except Exception:+ pass++ print(f" 1. Open: {authorize_url}")+ if open_browser and can_open_browser:+ import webbrowser++ if webbrowser.open(authorize_url):+ print(" (Opened browser for sign-in)")+ else:+ print(" Could not open a browser automatically — open the URL above.")+ else:+ print(" (Open the URL above and authorize.)")+ print("Waiting for authorization...")++ callback = _wait_for_loopback_callback(port, "/gemini-auth/callback")+ if callback.get("error"):+ raise _AuthError(+ f"Solstice authorization failed: {callback.get('error_description') or callback.get('error')}",+ code="solstice_denied",+ )+ if callback.get("state") != state:+ raise _AuthError(+ "Solstice callback state mismatch — the response may have been tampered with.",+ code="solstice_state_mismatch",+ )+ code = callback.get("code")+ if not code:+ raise _AuthError(+ "Solstice callback did not include an authorization code.",+ code="solstice_callback_no_code",+ )++ token_payload = _exchange_code(code, verifier, redirect_uri)+ expires_in = _coerce_ttl_seconds(token_payload.get("expires_in", 0))+ now = datetime.now(timezone.utc)+ tokens = {+ "access_token": str(token_payload["access_token"]).strip(),+ "refresh_token": str(token_payload["refresh_token"]).strip(),+ "token_type": str(+ token_payload.get("token_type", "Bearer") or "Bearer"+ ).strip(),+ "scope": str(token_payload.get("scope") or "").strip(),+ "obtained_at": now.isoformat(),+ "expires_at": datetime.fromtimestamp(+ now.timestamp() + expires_in, tz=timezone.utc+ ).isoformat(),+ "expires_in": expires_in,+ }+ _save_solstice_tokens(tokens, redirect_uri=redirect_uri, set_active=True)++ from hermes_cli.auth import (+ _update_config_for_provider,+ unsuppress_credential_source,+ )++ unsuppress_credential_source("solstice", "oauth_pkce")+ _update_config_for_provider("solstice", SOLSTICE_INFERENCE_BASE_URL)+ print()+ print("✓ Solstice login successful.")+ print(f" Tokens: {_auth_file_hint()}")+++def _coerce_ttl_seconds(value: Any) -> int:+ try:+ return max(0, int(value))+ except Exception:+ return 0+++def _auth_file_hint() -> str:+ try:+ from hermes_constants import display_hermes_home++ return f"{display_hermes_home()}/auth.json"+ except Exception:+ return "auth.json"+++# ---------------------------------------------------------------------------+# Runtime resolution + status+# ---------------------------------------------------------------------------+++def resolve_solstice_runtime_credentials(+ *,+ refresh_if_expiring: bool = True,+ force_refresh: bool = False,+) -> Dict[str, Any]:+ """Resolve usable Solstice credentials, refreshing via NAS when needed.++ Mirrors resolve_xai_oauth_runtime_credentials: read store → refresh if+ expiring → return dict with api_key/base_url. The ``api_key`` is the+ OAuth access token (Bearer).+ """+ from hermes_cli.auth import AuthError++ try:+ stored = _read_solstice_tokens()+ except _AuthError as exc:+ raise AuthError(+ str(exc),+ provider="solstice",+ code=getattr(exc, "code", "solstice_missing"),+ relogin_required=getattr(exc, "relogin_required", True),+ ) from exc++ tokens = stored["tokens"]+ access_token = str(tokens.get("access_token", "") or "").strip()+ refresh_token = str(tokens.get("refresh_token", "") or "").strip()++ should_refresh = force_refresh or (+ refresh_if_expiring+ and _solstice_access_token_is_expiring(+ access_token, SOLSTICE_ACCESS_TOKEN_REFRESH_SKEW_SECONDS+ )+ )+ if should_refresh:+ if not refresh_token:+ raise AuthError(+ "Solstice access token is expired and no refresh token is stored. Re-login.",+ provider="solstice",+ code="solstice_no_refresh_token",+ relogin_required=True,+ )+ try:+ rotated = _refresh_tokens(refresh_token)+ new_tokens = dict(tokens)+ new_tokens["access_token"] = str(rotated["access_token"]).strip()+ if str(rotated.get("refresh_token", "") or "").strip():+ new_tokens["refresh_token"] = str(rotated["refresh_token"]).strip()+ expires_in = _coerce_ttl_seconds(rotated.get("expires_in", 0))+ now = datetime.now(timezone.utc)+ new_tokens["obtained_at"] = now.isoformat()+ new_tokens["expires_at"] = datetime.fromtimestamp(+ now.timestamp() + expires_in, tz=timezone.utc+ ).isoformat()+ new_tokens["expires_in"] = expires_in+ _save_solstice_tokens(new_tokens, set_active=False)+ tokens = new_tokens+ except _AuthError as exc:+ # Terminal refresh failure (invalid_grant / revoked) — clear the+ # dead tokens from auth.json so subsequent resolutions fail fast+ # without a network retry (mirrors the xai-oauth quarantine).+ try:+ from hermes_cli.auth import (+ _auth_store_lock,+ _load_auth_store,+ _load_provider_state,+ _save_auth_store,+ _store_provider_state,+ )++ with _auth_store_lock():+ _q_store = _load_auth_store()+ _q_state = _load_provider_state(_q_store, "solstice") or {}+ _q_tokens = dict(_q_state.get("tokens") or {})+ _q_tokens.pop("access_token", None)+ _q_tokens.pop("refresh_token", None)+ _q_state["tokens"] = _q_tokens+ _q_state["last_auth_error"] = {+ "provider": "solstice",+ "code": getattr(exc, "code", "solstice_refresh_failed"),+ "message": str(exc),+ "reason": "runtime_refresh_failure",+ "relogin_required": True,+ "at": datetime.now(timezone.utc).isoformat(),+ }+ _store_provider_state(+ _q_store, "solstice", _q_state, set_active=False+ )+ _save_auth_store(_q_store)+ except Exception as _save_exc: # pragma: no cover - best effort+ logger.debug(+ "Solstice OAuth: failed to persist quarantined state: %s",+ _save_exc,+ )+ raise AuthError(+ str(exc),+ provider="solstice",+ code=getattr(exc, "code", "solstice_refresh_failed"),+ relogin_required=getattr(exc, "relogin_required", True),+ ) from exc++ return {+ "provider": "solstice",+ "api_mode": "chat_completions",+ "base_url": SOLSTICE_INFERENCE_BASE_URL,+ "api_key": str(tokens.get("access_token", "") or "").strip(),+ "source": "hermes-auth-store",+ "last_refresh": stored.get("last_refresh"),+ "expires_at_ms": _token_expiry_ms(tokens.get("expires_at")),+ }+++def _token_expiry_ms(expires_at: Any) -> Optional[int]:+ try:+ dt = datetime.fromisoformat(str(expires_at).replace("Z", "+00:00"))+ return int(dt.timestamp() * 1000)+ except Exception:+ return None+++def get_solstice_status() -> Dict[str, Any]:+ """Return auth status dict (logged_in, account hints, error)."""+ try:+ creds = resolve_solstice_runtime_credentials(refresh_if_expiring=False)+ access = creds.get("api_key", "")+ expired = _solstice_access_token_is_expiring(access, 0)+ return {+ "provider": "solstice",+ "logged_in": bool(access),+ "configured": True,+ "access_token_expired": expired,+ "expires_at_ms": creds.get("expires_at_ms"),+ }+ except Exception as exc:+ return {+ "provider": "solstice",+ "logged_in": False,+ "configured": True,+ "error": str(exc),+ }diff --git a/plugins/model-providers/solstice/__init__.py b/plugins/model-providers/solstice/__init__.pynew file mode 100644index 00000000000..e45953d3456--- /dev/null+++ b/plugins/model-providers/solstice/__init__.py@@ -0,0 +1,99 @@+"""Solstice provider profile (pre-release — hidden by default).++Solstice is a consumer subscription carried into Hermes. Inference goes to+``generativelanguage.googleapis.com`` on the ``:generateContentPerUserQuota``+endpoint, authenticated with the user's own OAuth token so usage maps to their+Solstice quota.++This profile is declarative metadata only — the transport lives in+``agent/solstice_adapter.py`` (per-user-quota endpoint + Bearer auth over+the native request builder) and the OAuth flow lives in+``hermes_cli/solstice.py`` (PKCE loopback → NAS-brokered code+exchange → direct inference).++Secret-launch mechanics:+- ``hidden=True`` keeps the provider out of the default discovery surfaces+ (``/model`` picker, setup wizard, ``hermes auth`` lists, doctor) until it is+ explicitly configured. With NAS owning the client config (discovered+ at login via ``/api/oauth/gemini-auth/config``), the provider is enabled by+ default and surfaced once a logged-in Nous user runs ``hermes auth add+ solstice``. The visibility gate defers to+ ``hermes_cli.solstice.solstice_enabled()`` (registered below).+- The provider still resolves by name via ``get_provider_profile()`` so an+ explicit ``model.provider: solstice`` in config.yaml works.+"""++from typing import Any++from providers import register_hidden_provider_gate, register_provider+from providers.base import ProviderProfile+++# Inference host — the per-user-quota backend behind Solstice. The+# standard request body (built by+# agent/gemini_native_adapter.build_gemini_request) is sent to the+# ``:generateContentPerUserQuota`` variant at this host. Imported from+# hermes_cli/solstice.py so the host has a single source of truth.+from hermes_cli.solstice import (+ SOLSTICE_INFERENCE_BASE_URL as SOLSTICE_BASE_URL,+)++# Curated model list shown when live discovery is unavailable, verified+# present on the per-user-quota endpoint (2026-09). The endpoint serves a+# closed set, so the fallback lists only those confirmed to resolve.+#+# Order matters: the first entry is the default. lite is listed last as the+# reserve — the per-user quota is enforced PER MODEL, so when the flash/pro+# family is exhausted lite still answers.+SOLSTICE_FALLBACK_MODELS = (+ "gemini-3.5-flash",+ "gemini-flash-latest",+ "gemini-flash-lite-latest",+)+++class SolsticeProfile(ProviderProfile):+ """Solstice — per-user-quota OAuth provider."""++ def build_extra_body(+ self, *, session_id: str | None = None, **context: Any+ ) -> dict[str, Any]:+ """No extra_body: the transport client builds the request envelope."""+ return {}++ def get_max_tokens(self, model: str | None) -> int | None:+ # Solstice model output caps are enforced by the backend; do not+ # impose a Hermes-side default cap.+ return None+++solstice_profile = SolsticeProfile(+ name="solstice",+ aliases=("solstice-oauth",),+ display_name="Solstice",+ description="Solstice (per-user-quota OAuth)",+ api_mode="chat_completions",+ auth_type="oauth_external",+ base_url=SOLSTICE_BASE_URL,+ env_vars=(),+ hidden=True,+ supports_health_check=False,+ fallback_models=SOLSTICE_FALLBACK_MODELS,+)++register_provider(solstice_profile)+++def _solstice_gate() -> bool:+ """Enable predicate — defers to the single auth-side gate.++ Registered so ``list_providers()`` and ``solstice_enabled()`` read the+ SAME credential resolver, keeping the provider's visibility and its+ auth/runtime usability in lockstep (never surfaced-but-dead).+ """+ from hermes_cli.solstice import solstice_enabled++ return solstice_enabled()+++register_hidden_provider_gate("solstice", _solstice_gate)diff --git a/plugins/model-providers/solstice/plugin.yaml b/plugins/model-providers/solstice/plugin.yamlnew file mode 100644index 00000000000..13edd9b64ff--- /dev/null+++ b/plugins/model-providers/solstice/plugin.yaml@@ -0,0 +1,5 @@+name: solstice-provider+kind: model-provider+version: 0.1.0+description: Solstice (per-user-quota OAuth)+author: Nous Researchdiff --git a/providers/__init__.py b/providers/__init__.pyindex 3e69b1b3868..adf08df58b4 100644--- a/providers/__init__.py+++ b/providers/__init__.py@@ -271,9 +271,81 @@ def list_providers() -> list[ProviderProfile]:_PROVIDER_LIST_CACHE = cacheresult = [p for p in _PROVIDER_LIST_CACHE if p.name not in layer.registry]result.extend({id(p): p for p in layer.registry.values()}.values())+ # Hidden profiles are excluded unless their enable gate / credential check+ # surfaces them; the filter runs per call so a gate flip needs no cache reset.+ if any(getattr(p, "hidden", False) for p in result):+ result = [p for p in result+ if not getattr(p, "hidden", False) or _hidden_provider_enabled(p.name)]return result+def _hidden_provider_enabled(name: str) -> bool:+ """Return True when a hidden provider should be surfaced after all.++ A hidden provider stays hidden unless something explicitly enables it.+ The default enable predicate is credential presence: if any of the+ provider's ``env_vars`` resolves to a usable value in the environment+ (or ``~/.hermes/.env``), the provider is considered enabled. Providers+ can register a richer predicate via ``register_hidden_provider_gate``.++ This mirrors the house "feature registers when configured" pattern+ (relay_url / proxy_url): absence = invisible + inert, presence = active.+ """+ try:+ gate = _HIDDEN_GATES.get(name)+ if gate is not None:+ return bool(gate())+ except Exception:+ logger.debug("hidden gate %s raised; treating as disabled", name, exc_info=True)+ return False++ profile = _REGISTRY.get(name)+ if profile is None:+ return False+ try:+ from hermes_cli.auth import has_usable_secret++ for var in profile.env_vars or ():+ if var and has_usable_secret(_resolve_env_var(var)):+ return True+ except Exception:+ logger.debug(+ "hidden env check for %s failed; staying hidden", name, exc_info=True+ )+ return False+++def _resolve_env_var(var: str) -> str:+ """Resolve an env var using the canonical Hermes credential resolver.++ ``get_env_value_prefer_dotenv`` prefers ``~/.hermes/.env`` (honoring the+ documented ``export VAR=`` forms) then falls back to ``os.environ`` — so+ hidden-provider enable checks read the same source a user is told to+ configure.+ """+ try:+ from hermes_cli.config import get_env_value_prefer_dotenv++ return get_env_value_prefer_dotenv(var) or ""+ except Exception:+ import os++ return os.getenv(var, "")+++_HIDDEN_GATES: dict[str, Any] = {}+++def register_hidden_provider_gate(name: str, predicate) -> None:+ """Register a callable predicate that decides when *name* is surfaced.++ ``predicate`` takes no args and returns a truthy value when the hidden+ provider should appear in ``list_providers()`` output. Useful when+ credential presence isn't the right signal (e.g. a config flag or a+ combination of settings). Overrides the default env-var check.+ """+ _HIDDEN_GATES[name] = predicate+def _home_layer(*, force_stamp_check: bool = False) -> _HomeLayer:"""The layer for the home bound right now, importing plugin dirs it has not seen yet."""layer, home, key = _bound_home_layer()diff --git a/providers/base.py b/providers/base.pyindex 8fd9e1f2f9f..1d495baa9e8 100644--- a/providers/base.py+++ b/providers/base.py@@ -52,6 +52,14 @@ class ProviderProfile:description: str = "" # e.g. "GMI Cloud (multi-model direct API)" — picker subtitlesignup_url: str = "" # e.g. "https://www.gmicloud.ai/" — shown during setup+ # True when the provider is pre-release / not for public listing.+ # list_providers() excludes hidden profiles unless the provider's own+ # enable predicate passes (see providers/__init__._hidden_provider_enabled).+ # The provider still resolves by name via get_provider_profile() when the+ # user configures it explicitly — hiding is about *discovery surfaces*+ # (picker, setup, auth lists), not about blocking direct config.+ hidden: bool = False+# ── Auth & endpoints ─────────────────────────────────────env_vars: tuple = ()base_url: str = ""diff --git a/tests/agent/test_solstice_adapter.py b/tests/agent/test_solstice_adapter.pynew file mode 100644index 00000000000..2fc3ccdf69d--- /dev/null+++ b/tests/agent/test_solstice_adapter.py@@ -0,0 +1,205 @@+"""Tests for the Solstice per-user-quota transport.++Verifies the request goes to the ``:generateContentPerUserQuota`` /+``:streamGenerateContentPerUserQuota`` endpoints with a standard body and+Bearer auth (not API key), and the response/stream translation matches the+native shape.+"""++from __future__ import annotations++import json++import pytest++from agent.solstice_adapter import (+ SOLSTICE_BASE_URL,+ SOLSTICE_GENERATE_PATH,+ SOLSTICE_STREAM_PATH,+ SolsticeClient,+ build_solstice_request,+)+++class _FakePerUserQuota:+ """Minimal fake per-user-quota server: generate + stream."""++ def __init__(self):+ import http.server+ import socketserver+ import threading++ self.gen_req = None+ self.stream_req = None+ self.stream_query: str | None = None+ self.auth_header: str | None = None++ class Handler(http.server.BaseHTTPRequestHandler):+ def do_POST(self): # noqa: N802+ body = self.rfile.read(int(self.headers.get("Content-Length", 0)))+ obj = json.loads(body)+ outer.auth_header = self.headers.get("Authorization")+ # The stream/serve paths carry a query string (?alt=sse); split+ # it off before matching and record it as part of the contract.+ path, _, query = self.path.partition("?")+ if path.endswith(SOLSTICE_GENERATE_PATH):+ outer.gen_req = obj+ payload = {+ "candidates": [+ {+ "content": {+ "parts": [{"text": "hello from solstice"}]+ },+ "finishReason": "STOP",+ }+ ]+ }+ self._json(payload)+ return+ if path.endswith(SOLSTICE_STREAM_PATH):+ outer.stream_req = obj+ outer.stream_query = query+ # Two SSE events: a text chunk then a finishReason chunk.+ events = [+ {+ "candidates": [+ {+ "content": {"parts": [{"text": "stream"}]},+ "finishReason": "",+ }+ ]+ },+ {+ "candidates": [+ {+ "content": {"parts": [{"text": " complete"}]},+ "finishReason": "STOP",+ }+ ],+ "usageMetadata": {+ "promptTokenCount": 5,+ "candidatesTokenCount": 2,+ "totalTokenCount": 7,+ },+ },+ ]+ sse = "".join(+ f"data: {json.dumps(ev)}\n\n" for ev in events+ ).encode()+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Content-Length", str(len(sse)))+ self.end_headers()+ self.wfile.write(sse)+ return+ self.send_response(404)+ self.end_headers()++ def _json(self, payload):+ data = json.dumps(payload).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def log_message(self, format, *args): # noqa: A002+ return++ self.server = socketserver.TCPServer(("127.0.0.1", 0), Handler)+ outer = self+ self.port = self.server.server_address[1]+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)+ self.thread.start()++ @property+ def base_url(self) -> str:+ return f"http://127.0.0.1:{self.port}"++ def close(self):+ self.server.shutdown()+ self.server.server_close()+++def fake_api():+ srv = _FakePerUserQuota()+ yield srv+ srv.close()+++def test_build_solstice_request_is_standard_body():+ body = build_solstice_request(+ model="solstice-test-model",+ messages=[{"role": "user", "content": "hi"}],+ tools=[{"type": "function", "function": {"name": "f", "parameters": {}}}],+ max_tokens=100,+ )+ # Standard GenerateContent body.+ assert body["contents"][0]["parts"][0]["text"] == "hi"+ assert body["generationConfig"]["maxOutputTokens"] == 100+ assert body["tools"]+++def test_client_sends_to_per_user_quota_endpoint_with_bearer(fake_api):+ client = SolsticeClient(api_key="test-oauth-token", base_url=fake_api.base_url)+ resp = client.chat.completions.create(+ model="solstice-test-model", messages=[{"role": "user", "content": "hi"}]+ )+ assert resp.choices[0].message.content == "hello from solstice"+ # Standard body on the per-user-quota endpoint, Bearer auth.+ assert fake_api.gen_req["contents"][0]["parts"][0]["text"] == "hi"+ assert fake_api.auth_header == "Bearer test-oauth-token"+++def test_client_requires_token():+ with pytest.raises(RuntimeError, match="access token"):+ SolsticeClient(api_key="")+++def test_client_streams_sse(fake_api):+ """The streaming path parses SSE events into text + finish chunks."""+ client = SolsticeClient(api_key="test-oauth-token", base_url=fake_api.base_url)+ stream = client.chat.completions.stream(+ model="solstice-test-model", messages=[{"role": "user", "content": "hi"}]+ )+ text = []+ finish_reason = None+ usage = None+ for chunk in stream:+ for choice in getattr(chunk, "choices", []) or []:+ delta = getattr(choice, "delta", None)+ if getattr(delta, "content", None):+ text.append(delta.content)+ if getattr(choice, "finish_reason", None):+ finish_reason = choice.finish_reason+ if getattr(chunk, "usage", None):+ usage = chunk.usage+ assert "".join(text) == "stream complete"+ assert finish_reason == "stop"+ assert usage is not None and usage.total_tokens == 7+ # Stream request carried the standard body + Bearer auth.+ assert fake_api.stream_req["contents"][0]["parts"][0]["text"] == "hi"+ assert fake_api.auth_header == "Bearer test-oauth-token"+ # alt=sse is required: without it the endpoint returns a bare JSON array+ # instead of SSE and the stream yields nothing (EmptyStreamError).+ assert fake_api.stream_query == "alt=sse"+++def test_inference_base_url_single_source_of_truth():+ """The inference host is defined once (in solstice) and shared.++ The provider profile, the transport, and the runtime resolution all import+ the same constant — a launch-time host correction is one edit. Assert the+ three consumers agree rather than pinning the literal (which only passes+ if the constant and the test were edited together).+ """+ from agent.solstice_adapter import SOLSTICE_BASE_URL+ from hermes_cli.solstice import SOLSTICE_INFERENCE_BASE_URL+ from providers import get_provider_profile++ prof = get_provider_profile("solstice")+ assert prof is not None+ assert SOLSTICE_BASE_URL == SOLSTICE_INFERENCE_BASE_URL == prof.base_url+ assert SOLSTICE_BASE_URL.startswith("https://")+ assert "generativelanguage.googleapis.com" in SOLSTICE_BASE_URLdiff --git a/tests/hermes_cli/test_runtime_provider_resolution.py b/tests/hermes_cli/test_runtime_provider_resolution.pyindex 04c24f5537c..b069605e9ce 100644--- a/tests/hermes_cli/test_runtime_provider_resolution.py+++ b/tests/hermes_cli/test_runtime_provider_resolution.py@@ -311,6 +311,45 @@ def test_qwen_oauth_auto_fallthrough_on_auth_failure(monkeypatch):assert resolved["provider"] != "qwen-oauth"+def test_resolve_runtime_provider_solstice(monkeypatch):+ """runtime_provider returns the solstice dict from the auth module."""+ from hermes_cli import solstice as aa++ monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "solstice")+ monkeypatch.setattr(aa, "solstice_enabled", lambda: True)+ monkeypatch.setattr(+ aa,+ "resolve_solstice_runtime_credentials",+ lambda **kw: {+ "provider": "solstice",+ "api_mode": "chat_completions",+ "base_url": "https://generativelanguage.googleapis.com/v1alpha",+ "api_key": "oauth-at-1",+ "source": "hermes-auth-store",+ },+ )++ resolved = rp.resolve_runtime_provider(requested="solstice")++ assert resolved["provider"] == "solstice"+ assert resolved["api_mode"] == "chat_completions"+ assert resolved["api_key"] == "oauth-at-1"+ assert "generativelanguage.googleapis.com" in resolved["base_url"]+++def test_resolve_runtime_provider_solstice_disabled(monkeypatch):+ """When solstice is not configured, auto-resolution falls through."""+ from hermes_cli import solstice as aa++ monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "solstice")+ monkeypatch.setattr(aa, "solstice_enabled", lambda: False)+ monkeypatch.setenv("OPENROUTER_API_KEY", "test-or-key")++ resolved = rp.resolve_runtime_provider(requested="auto")++ assert resolved["provider"] != "solstice"++def test_resolve_runtime_provider_ai_gateway(monkeypatch):monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "ai-gateway")monkeypatch.setattr(rp, "_get_model_config", lambda: {})diff --git a/tests/hermes_cli/test_solstice.py b/tests/hermes_cli/test_solstice.pynew file mode 100644index 00000000000..bb8e4a90d2d--- /dev/null+++ b/tests/hermes_cli/test_solstice.py@@ -0,0 +1,301 @@+"""Tests for the Solstice OAuth flow (PKCE loopback, NAS-brokered exchange).++Verifies the enable gate, PKCE pair generation, token store round-trip,+NAS exchange/refresh contract, runtime resolution, and the login flow+against a fake NAS broker.+"""++from __future__ import annotations++import json+import threading+from http.server import BaseHTTPRequestHandler+from socketserver import TCPServer+from types import SimpleNamespace+from unittest import mock++import pytest++import hermes_cli.solstice as aa+++class _FakeNAS:+ """Fake NAS broker: records exchange/refresh bodies, returns canned tokens."""++ def __init__(self, exchange_payload=None, refresh_payload=None):+ self.exchange_body = None+ self.refresh_body = None+ self.config_payload = {+ "client_id": "solstice-client-123",+ "authorize_url": "https://accounts.google.com/o/oauth2/v2/auth",+ "scope": "openid email profile https://www.googleapis.com/auth/generative-language.peruserquota",+ }+ self.exchange_payload = exchange_payload or {+ "access_token": "at-1",+ "refresh_token": "rt-1",+ "expires_in": 3600,+ "token_type": "Bearer",+ }+ self.refresh_payload = refresh_payload or {+ "access_token": "at-2",+ "refresh_token": "rt-2",+ "expires_in": 3600,+ }++ class Handler(BaseHTTPRequestHandler):+ def do_GET(self): # noqa: N802+ if self.path == aa.SOLSTICE_NAS_CONFIG_PATH:+ data = json.dumps(outer.config_payload).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)+ else:+ self.send_response(404)+ self.end_headers()++ def do_POST(self): # noqa: N802+ body = self.rfile.read(int(self.headers.get("Content-Length", 0)))+ obj = json.loads(body)+ if self.path == aa.SOLSTICE_NAS_EXCHANGE_PATH:+ outer.exchange_body = obj+ payload = outer.exchange_payload+ elif self.path == aa.SOLSTICE_NAS_REFRESH_PATH:+ outer.refresh_body = obj+ payload = outer.refresh_payload+ else:+ self.send_response(404)+ self.end_headers()+ return+ data = json.dumps(payload).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(data)))+ self.end_headers()+ self.wfile.write(data)++ def log_message(self, format, *args): # noqa: A002+ return++ self.server = TCPServer(("127.0.0.1", 0), Handler)+ outer = self+ self.port = self.server.server_address[1]+ self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)+ self.thread.start()++ @property+ def base_url(self) -> str:+ return f"http://127.0.0.1:{self.port}"++ def close(self):+ self.server.shutdown()+ self.server.server_close()+++def fake_nas():+ srv = _FakeNAS()+ yield srv+ srv.close()+++def broker_env(fake_nas, monkeypatch):+ """Point the broker at the fake NAS and skip the HTTPS guard (test-only)."""+ monkeypatch.setattr(aa, "solstice_nas_base_url", lambda: fake_nas.base_url)+ monkeypatch.setattr(aa, "_validate_broker_url", lambda url: url.rstrip("/"))+ # NAS broker calls require a valid Nous token; provide a fake one.+ monkeypatch.setattr(+ aa, "_nous_bearer_header", lambda: {"Authorization": "Bearer fake-nous-token"}+ )+ return fake_nas+++def clean_home(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ yield+++def test_enable_gate(monkeypatch):+ # Provider is enabled by default; no local client_id gate anymore+ # (NAS owns the client config, discovered at login).+ monkeypatch.delenv("SOLSTICE_CLIENT_ID", raising=False)+ assert aa.solstice_enabled() is True+++def test_client_id_comes_from_nas_discovery(monkeypatch):+ # The login flow fetches client config from NAS discovery, not local env.+ monkeypatch.delenv("SOLSTICE_CLIENT_ID", raising=False)+ assert hasattr(aa, "_fetch_solstice_config")+++def test_pkce_pair_shape():+ verifier, challenge, state = aa._solstice_pkce_pair()+ assert verifier and challenge and state+ assert "." not in challenge # base64url, no padding+ assert len(verifier) >= 43+++def test_broker_rejects_plain_http():+ with pytest.raises(aa._AuthError, match="HTTPS"):+ aa._validate_broker_url("http://127.0.0.1:1234")+++def test_exchange_contract(broker_env, fake_nas):+ payload = aa._exchange_code("code-xyz", "verifier-abc", "http://127.0.0.1:9999/cb")+ assert payload["access_token"] == "at-1"+ assert fake_nas.exchange_body == {+ "code": "code-xyz",+ "code_verifier": "verifier-abc",+ "redirect_uri": "http://127.0.0.1:9999/cb",+ }+++def test_token_store_round_trip(clean_home, monkeypatch):+ monkeypatch.setenv("SOLSTICE_CLIENT_ID", "client-123")+ tokens = {+ "access_token": "at-1",+ "refresh_token": "rt-1",+ "token_type": "Bearer",+ "expires_in": 3600,+ }+ aa._save_solstice_tokens(tokens, redirect_uri="http://127.0.0.1:9999/cb")+ stored = aa._read_solstice_tokens()+ assert stored["tokens"]["access_token"] == "at-1"+ assert stored["redirect_uri"] == "http://127.0.0.1:9999/cb"+ assert stored["auth_mode"] == "oauth_pkce"+++def test_refresh_contract(broker_env, fake_nas):+ rotated = aa._refresh_tokens("rt-1")+ assert rotated["access_token"] == "at-2"+ assert fake_nas.refresh_body == {"refresh_token": "rt-1"}+++def test_runtime_resolution_refreshes_via_broker(clean_home, broker_env, monkeypatch):+ monkeypatch.setenv("SOLSTICE_CLIENT_ID", "client-123")+ tokens = {+ "access_token": "at-1",+ "refresh_token": "rt-1",+ "token_type": "Bearer",+ "expires_in": 3600,+ }+ aa._save_solstice_tokens(tokens)+ creds = aa.resolve_solstice_runtime_credentials(force_refresh=True)+ assert creds["api_key"] == "at-2"+ assert creds["base_url"] == "https://generativelanguage.googleapis.com/v1alpha"+ assert creds["api_mode"] == "chat_completions"+ assert creds["provider"] == "solstice"+++def test_login_flow(clean_home, broker_env, monkeypatch):+ """End-to-end login: PKCE pair → loopback callback → NAS exchange → store."""+ monkeypatch.setenv("SOLSTICE_CLIENT_ID", "client-123")++ state_holder: dict = {}+ real_pair = aa._solstice_pkce_pair++ def fake_pair():+ v, c, s = real_pair()+ state_holder["expected_state"] = s+ return v, c, s++ def fake_wait(port, path, *, timeout_seconds=180.0):+ return {+ "code": "auth-code-123",+ "state": state_holder["expected_state"],+ "error": None,+ }++ args = SimpleNamespace(no_browser=True, timeout=30.0)+ with (+ mock.patch.object(aa, "_solstice_pkce_pair", fake_pair),+ mock.patch.object(aa, "_wait_for_loopback_callback", fake_wait),+ ):+ aa._login_solstice(args, None)++ creds = aa.resolve_solstice_runtime_credentials(refresh_if_expiring=False)+ assert creds["api_key"] == "at-1"+++def test_login_rejects_state_mismatch(clean_home, broker_env, monkeypatch):+ monkeypatch.setenv("SOLSTICE_CLIENT_ID", "client-123")++ def fake_wait(port, path, *, timeout_seconds=180.0):+ return {"code": "x", "state": "wrong-state", "error": None}++ args = SimpleNamespace(no_browser=True, timeout=30.0)+ with mock.patch.object(aa, "_wait_for_loopback_callback", fake_wait):+ with pytest.raises(aa._AuthError, match="state mismatch"):+ aa._login_solstice(args, None)+++def test_status_reflects_gate(monkeypatch):+ monkeypatch.delenv("SOLSTICE_CLIENT_ID", raising=False)+ status = aa.get_solstice_status()+ # Provider is always configured now (NAS owns the client config); logged_in+ # reflects whether tokens are stored.+ assert status["logged_in"] is False+ assert status["configured"] is True+++def test_runtime_resolution_quarantines_on_terminal_refresh_failure(+ clean_home, monkeypatch+):+ """A terminal refresh failure clears dead tokens and marks relogin required."""+ monkeypatch.setenv("SOLSTICE_CLIENT_ID", "client-123")+ tokens = {+ "access_token": "at-1", # not a JWT → would not auto-refresh; use force+ "refresh_token": "rt-expired",+ "token_type": "Bearer",+ "expires_in": 3600,+ }+ aa._save_solstice_tokens(tokens)++ # Make the broker return a 400 invalid_grant on refresh.+ class _FailingNAS:+ base_url = None++ def __init__(self):+ import socketserver++ class H(BaseHTTPRequestHandler):+ def do_POST(self): # noqa: N802+ self.rfile.read(int(self.headers.get("Content-Length", 0)))+ body = b'{"error": "invalid_grant"}'+ self.send_response(400)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, format, *args): # noqa: A002+ return++ self.server = socketserver.TCPServer(("127.0.0.1", 0), H)+ self.base_url = f"http://127.0.0.1:{self.server.server_address[1]}"+ threading.Thread(target=self.server.serve_forever, daemon=True).start()++ def close(self):+ self.server.shutdown()+ self.server.server_close()++ nas = _FailingNAS()+ monkeypatch.setattr(aa, "solstice_nas_base_url", lambda: nas.base_url)+ monkeypatch.setattr(aa, "_validate_broker_url", lambda url: url.rstrip("/"))+ monkeypatch.setattr(+ aa, "_nous_bearer_header", lambda: {"Authorization": "Bearer fake-nous-token"}+ )++ from hermes_cli.auth import AuthError++ with pytest.raises(AuthError) as excinfo:+ aa.resolve_solstice_runtime_credentials(force_refresh=True)+ assert excinfo.value.relogin_required is True+ nas.close()++ # Dead tokens cleared from the store → next resolution fails fast.+ creds = aa.resolve_solstice_runtime_credentials()+ assert creds["api_key"] == "" # quarantined: no usable token remainsdiff --git a/tests/providers/test_solstice_gate.py b/tests/providers/test_solstice_gate.pynew file mode 100644index 00000000000..4f5e482e4e6--- /dev/null+++ b/tests/providers/test_solstice_gate.py@@ -0,0 +1,100 @@+"""Tests for the Solstice provider gate.++With NAS owning the client config, the provider is enabled by default+(no local client_id gate). Verifies:+ 1. The solstice profile is present in list_providers() by default.+ 2. It resolves by name via get_provider_profile() for explicit+ ``model.provider: solstice`` config.+ 3. The profile's auth_type is oauth_external so it is handled as an OAuth+ provider.+"""++from __future__ import annotations++import sys++import pytest+++REPO_ROOT = __file__.rsplit("/tests/providers/", 1)[0]+++def _clear_provider_caches():+ """Force providers/__init__.py to re-discover on next list_providers()."""+ import providers as _pkg++ _pkg._REGISTRY.clear()+ _pkg._ALIASES.clear()+ _pkg._PROVIDER_LIST_CACHE = None+ _pkg._discovered = False+ for mod in list(sys.modules.keys()):+ if mod.startswith("plugins.model_providers") or mod.startswith(+ "_hermes_user_provider"+ ):+ del sys.modules[mod]++[email protected](autouse=True)+def _clean_env(monkeypatch, tmp_path):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ monkeypatch.delenv("SOLSTICE_CLIENT_ID", raising=False)+ _clear_provider_caches()+ yield+ _clear_provider_caches()+++def test_solstice_surfaced_by_default():+ """The provider is enabled by default (no local client_id gate)."""+ from providers import list_providers++ names = {p.name for p in list_providers()}+ assert "solstice" in names+++def test_solstice_resolves_by_name():+ """get_provider_profile() resolves the profile for explicit config."""+ from providers import get_provider_profile++ prof = get_provider_profile("solstice")+ assert prof is not None+ assert prof.name == "solstice"+ assert prof.auth_type == "oauth_external" # OAuth-handled provider+++def test_solstice_surfaced_when_configured(monkeypatch):+ """Regardless of SOLSTICE_CLIENT_ID, the provider is surfaced."""+ monkeypatch.setenv("SOLSTICE_CLIENT_ID", "test-client-id-123")+ from providers import list_providers++ names = {p.name for p in list_providers()}+ assert "solstice" in names+++def test_solstice_surfaced_via_dotenv_only(tmp_path, monkeypatch):+ """A credential in ~/.hermes/.env still surfaces the provider."""+ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir(parents=True)+ (hermes_home / ".env").write_text("SOLSTICE_CLIENT_ID=dotenv-client-id\n")+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))+ monkeypatch.delenv("SOLSTICE_CLIENT_ID", raising=False)++ from providers import list_providers++ names = {p.name for p in list_providers()}+ assert "solstice" in names++ from hermes_cli.solstice import solstice_enabled++ assert solstice_enabled() is True # auth gate agrees with discovery+++def test_solstice_profile_metadata():+ """Profile carries the right endpoints and fallback models."""+ from providers import get_provider_profile++ prof = get_provider_profile("solstice")+ assert prof is not None+ assert "generativelanguage.googleapis.com" in (prof.base_url or "")+ assert prof.env_vars == ()+ assert prof.fallback_models # curated list present for the picker+ assert prof.supports_health_check is False # no /models catalog to probe