The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(solstice): rebuild the provider as a standard model-provider plugin
Teknium22bc7eac7130
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex 012a0e11154..16a95fb3519 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -2012,33 +2012,6 @@ 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,@@ -2103,9 +2076,6 @@ 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.pydeleted file mode 100644index 62c0a3e1a08..00000000000--- a/agent/solstice_adapter.py+++ /dev/null@@ -1,257 +0,0 @@-"""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/main.py b/hermes_cli/main.pyindex d5dec53a1f4..8d1dc1172a5 100644--- a/hermes_cli/main.py+++ b/hermes_cli/main.py@@ -775,7 +775,6 @@ 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,@@ -2021,7 +2020,6 @@ _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 dbc13c8f1ae..64dbb38181c 100644--- a/hermes_cli/model_setup_flows.py+++ b/hermes_cli/model_setup_flows.py@@ -480,36 +480,6 @@ 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/runtime_provider.py b/hermes_cli/runtime_provider.pyindex 2cd78c9cea4..2e1f9d26302 100644--- a/hermes_cli/runtime_provider.py+++ b/hermes_cli/runtime_provider.py@@ -860,9 +860,6 @@ 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")@@ -942,16 +939,6 @@ 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.pydeleted file mode 100644index 1b66a49b5e8..00000000000--- a/hermes_cli/solstice.py+++ /dev/null@@ -1,795 +0,0 @@-"""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__.pyindex e45953d3456..f603c21fa37 100644--- a/plugins/model-providers/solstice/__init__.py+++ b/plugins/model-providers/solstice/__init__.py@@ -1,99 +1,60 @@-"""Solstice provider profile (pre-release — hidden by default).+"""Solstice provider profile: a user's own per-user-quota Gemini subscription, signed in with OAuth.-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.+Pre-release (``hidden=True``): no picker, setup list or accounts tab offers it until the user signs in+by name (``hermes auth add solstice``); after that it lists like any signed-in provider. Login and+token refresh go through the generic PKCE plugin flow with a Nous-portal broker as the token endpoint+(``auth.py``); inference goes straight to Google on the per-user-quota methods (``transport.py``)."""+from __future__ import annotations++from dataclasses import replacefrom typing import Any-from providers import register_hidden_provider_gate, register_provider+from hermes_cli.auth_oauth_pkce_plugin import OAuthPKCEConfig, pkce_auth_handler, pkce_refresh_credential+from providers import register_providerfrom providers.base import ProviderProfile+from .auth import broker_token_request, discover_client+from .transport import INFERENCE_BASE_URL, SolsticeClient-# 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,-)+# Verified on the per-user-quota endpoint, which has no model listing a user token may read (its+# /models answers 403 ACCESS_TOKEN_SCOPE_INSUFFICIENT). Quota is per model, so lite stays last as the+# reserve once the flash family is exhausted.+FALLBACK_MODELS = ("gemini-3.5-flash", "gemini-flash-latest", "gemini-flash-lite-latest")-# 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",+# The broker owns client_id/scope (discovered per login); refresh needs neither, the broker adds them.+_BASE_CFG = OAuthPKCEConfig(+ client_id="", authorize_url="", token_url="", label="Solstice",+ redirect_path="/gemini-auth/callback", token_request=broker_token_request,+ # A refresh token is issued only for offline access, and Google omits it on a repeat consent.+ extra_authorize_params={"access_type": "offline", "prompt": "consent"},)-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+def _auth_handler(action: str, args: Any) -> bool:+ cfg = _BASE_CFG+ if action == "add":+ client = discover_client()+ cfg = replace(_BASE_CFG, client_id=client["client_id"], authorize_url=client["authorize_url"],+ scopes=tuple(client["scope"].split()))+ return pkce_auth_handler(cfg)(action, args)-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+class SolsticeProfile(ProviderProfile):+ def create_client(self, **client_kwargs: Any) -> Any:+ allowed = {"api_key", "base_url", "default_headers", "timeout", "http_client"}+ return SolsticeClient(**{k: v for k, v in client_kwargs.items() if k in allowed})- return solstice_enabled()+ def get_max_tokens(self, model: str | None) -> int | None:+ return None # output caps are the backend's; a Hermes default would truncate long answers-register_hidden_provider_gate("solstice", _solstice_gate)+register_provider(SolsticeProfile(+ name="solstice", aliases=("solstice-oauth",), display_name="Solstice",+ description="Solstice (your own per-user quota, OAuth sign-in)",+ auth_type="oauth_external", base_url=INFERENCE_BASE_URL, hidden=True,+ supports_health_check=False, supports_model_listing=False, supports_vision=True,+ fallback_models=FALLBACK_MODELS, default_aux_model="gemini-flash-lite-latest",+ auth_handler=_auth_handler, refresh_credential=pkce_refresh_credential(_BASE_CFG),+))diff --git a/plugins/model-providers/solstice/auth.py b/plugins/model-providers/solstice/auth.pynew file mode 100644index 00000000000..a617fa564a8--- /dev/null+++ b/plugins/model-providers/solstice/auth.py@@ -0,0 +1,76 @@+"""Solstice sign-in: browser PKCE with a loopback redirect, token exchange and refresh brokered by the+Nous portal (NAS), which holds the confidential client secret. Hermes keeps its own PKCE verifier and+the user's tokens; NAS never sees a prompt.++The generic ``hermes_cli.auth_oauth_pkce_plugin`` flow runs the browser leg, the credential-pool row+and the single-use-safe refresh. This module supplies only what is NAS-specific: the client config it+discovers and the token POSTs it brokers. Every NAS call carries the user's Nous access token.+"""++from __future__ import annotations++from typing import Any, Dict, Mapping++DEFAULT_NAS_BASE_URL = "https://portal.nousresearch.com"+_CONFIG_PATH = "/api/oauth/gemini-auth/config"+_TOKEN_PATHS = {"authorization_code": "/api/oauth/gemini-auth/exchange", "refresh_token": "/api/oauth/gemini-auth/refresh"}+_TIMEOUT_SECONDS = 30.0+++def _err(message: str, code: str, *, relogin: bool = False):+ from hermes_cli.auth_constants import AuthError+ return AuthError(f"solstice: {message}", provider="solstice", code=code, relogin_required=relogin)+++def _nas_base_url() -> str:+ """The Nous portal the user is signed into (``HERMES_PORTAL_BASE_URL`` override first)."""+ from hermes_cli.auth import _nous_portal_base_url, get_provider_auth_state+ return _nous_portal_base_url(get_provider_auth_state("nous") or {})+++def _nas_request(method: str, path: str, *, json: Mapping[str, Any] | None = None) -> Dict[str, Any]:+ from hermes_cli.auth import _default_verify, resolve_nous_access_token+ from hermes_cli.auth_constants import httpx++ try:+ token = resolve_nous_access_token()+ except Exception as exc:+ raise _err("sign in to Nous Portal first (`hermes auth add nous`).", "solstice_nous_login_required",+ relogin=True) from exc+ try:+ response = httpx.request(method, _nas_base_url() + path, json=json, timeout=_TIMEOUT_SECONDS,+ headers={"Accept": "application/json", "Authorization": f"Bearer {token}"},+ verify=_default_verify())+ except Exception as exc:+ raise _err(f"Nous portal request failed: {type(exc).__name__}", "solstice_broker_unreachable") from exc+ if response.status_code == 404:+ raise _err("not available on this Nous account yet.", "solstice_not_configured")+ if response.status_code >= 400:+ raise _err(f"Nous portal returned HTTP {response.status_code}.", "solstice_broker_failed")+ return response.json()+++def discover_client() -> Dict[str, str]:+ """``client_id`` / ``authorize_url`` / ``scope`` NAS serves for the shared Google client."""+ payload = _nas_request("GET", _CONFIG_PATH)+ missing = [k for k in ("client_id", "authorize_url", "scope") if not str(payload.get(k) or "").strip()]+ if missing:+ raise _err(f"Nous portal config is missing {', '.join(missing)}.", "solstice_config_invalid")+ return {k: str(payload[k]).strip() for k in ("client_id", "authorize_url", "scope")}+++def broker_token_request(grant: Mapping[str, str]) -> Mapping[str, Any]:+ """``OAuthPKCEConfig.token_request``: send the grant to NAS, which adds the client secret.++ NAS folds every Google token-endpoint failure into HTTP 502, so a refresh it rejects is treated as+ a dead grant (re-login) rather than retried against a token Google already refused.+ """+ path = _TOKEN_PATHS[grant["grant_type"]]+ body = {k: v for k, v in grant.items() if k in ("code", "code_verifier", "redirect_uri", "refresh_token")}+ try:+ return _nas_request("POST", path, json=body)+ except Exception as exc:+ if grant["grant_type"] == "refresh_token" and getattr(exc, "code", "") == "solstice_broker_failed":+ raise _err("the stored sign-in was rejected; run `hermes auth add solstice` again.",+ "invalid_grant", relogin=True) from exc+ raisediff --git a/plugins/model-providers/solstice/plugin.yaml b/plugins/model-providers/solstice/plugin.yamlindex 13edd9b64ff..be943a1fc4f 100644--- a/plugins/model-providers/solstice/plugin.yaml+++ b/plugins/model-providers/solstice/plugin.yaml@@ -1,5 +1,5 @@name: solstice-providerkind: model-providerversion: 0.1.0-description: Solstice (per-user-quota OAuth)+description: Solstice (per-user-quota OAuth, pre-release)author: Nous Researchdiff --git a/plugins/model-providers/solstice/transport.py b/plugins/model-providers/solstice/transport.pynew file mode 100644index 00000000000..d566b74a923--- /dev/null+++ b/plugins/model-providers/solstice/transport.py@@ -0,0 +1,32 @@+"""Solstice inference transport: the native Gemini wire on the per-user-quota methods, with the user's+OAuth access token as a Bearer instead of an API key.++Everything else (request building, tool-call ids, thinking config, streaming, error mapping) is the+native adapter's, so a fix there reaches this provider too.+"""++from __future__ import annotations++from typing import Any, Dict++from agent.gemini_native_adapter import GeminiAPIError, GeminiNativeClient, gemini_http_error++INFERENCE_BASE_URL = "https://generativelanguage.googleapis.com/v1alpha"+++class SolsticeClient(GeminiNativeClient):+ """``GeminiNativeClient`` on ``:generateContentPerUserQuota`` / ``:streamGenerateContentPerUserQuota``."""++ GENERATE_METHOD, STREAM_METHOD = "generateContentPerUserQuota", "streamGenerateContentPerUserQuota"+ MISSING_KEY_ERROR = "Solstice needs a signed-in account. Run `hermes auth add solstice`."++ def __init__(self, *, base_url: Any = None, **kwargs: Any) -> None:+ # No base means this endpoint, never the generic Gemini default (a different API surface).+ super().__init__(base_url=base_url or INFERENCE_BASE_URL, **kwargs)++ def _auth_headers(self) -> Dict[str, str]:+ return {"Authorization": f"Bearer {self.api_key}"}++ def _http_error(self, response: Any, body_text: Any = None) -> GeminiAPIError:+ # The API-key remedies (free tier, Standard key, wrong key surface) do not apply to a bearer.+ return gemini_http_error(response, body_text=body_text, base_url=self.base_url, key_guidance=False)diff --git a/tests/agent/test_solstice_adapter.py b/tests/agent/test_solstice_adapter.pydeleted file mode 100644index 2fc3ccdf69d..00000000000--- a/tests/agent/test_solstice_adapter.py+++ /dev/null@@ -1,205 +0,0 @@-"""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 b069605e9ce..04c24f5537c 100644--- a/tests/hermes_cli/test_runtime_provider_resolution.py+++ b/tests/hermes_cli/test_runtime_provider_resolution.py@@ -311,45 +311,6 @@ 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.pydeleted file mode 100644index bb8e4a90d2d..00000000000--- a/tests/hermes_cli/test_solstice.py+++ /dev/null@@ -1,301 +0,0 @@-"""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/plugins/model_providers/test_solstice_profile.py b/tests/plugins/model_providers/test_solstice_profile.pynew file mode 100644index 00000000000..772b167b539--- /dev/null+++ b/tests/plugins/model_providers/test_solstice_profile.py@@ -0,0 +1,100 @@+"""Solstice invariants: a pre-release provider stays off every discovery surface until signed in, and a+brokered OAuth row with an opaque bearer rotates on its stored expiry."""++from __future__ import annotations++import json+import time++import hermes_cli.auth+import providers+from hermes_cli import auth_oauth_pkce_plugin as pkce+from providers import register_provider+from providers.base import ProviderProfile+++def _pool_row(provider: str, *, access: str, expires_at_ms: int) -> dict:+ return {"id": "abc123", "label": provider, "auth_type": "oauth", "priority": 0, "source": pkce.POOL_SOURCE,+ "access_token": access, "refresh_token": "1//rt-0", "expires_at_ms": expires_at_ms}+++def _write_pool(home, provider: str, row: dict) -> None:+ (home / "auth.json").write_text(json.dumps({"version": 1, "credential_pool": {provider: [row]}}))+++def test_solstice_is_off_every_discovery_surface_until_signed_in_but_always_resolves(monkeypatch, tmp_path):+ home = tmp_path / "hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ from hermes_cli.models import list_available_providers+ from hermes_cli.models_catalog_static import listed_canonical_providers+ from hermes_cli.provider_catalog import provider_catalog+ from hermes_cli.web_routers.oauth import _build_oauth_catalog++ def surfaces() -> dict[str, bool]:+ return {+ "canonical": any(p.slug == "solstice" for p in listed_canonical_providers()),+ "provider_list": any(r["id"] == "solstice" for r in list_available_providers()),+ "setup_catalog": any(d.slug == "solstice" for d in provider_catalog()),+ "accounts_tab": any(r["id"] == "solstice" for r in _build_oauth_catalog()),+ }++ assert providers.get_provider_profile("solstice").hidden is True+ assert surfaces() == dict.fromkeys(surfaces(), False)+ # Typed paths never consult the gate: a user who names it can sign in and run it.+ assert hermes_cli.auth.resolve_provider("solstice") == "solstice"+ assert hermes_cli.auth.resolve_provider("solstice-oauth") == "solstice"++ _write_pool(home, "solstice", _pool_row("solstice", access="ya29.x", expires_at_ms=int(time.time() * 1000) + 3_600_000))+ assert surfaces() == dict.fromkeys(surfaces(), True)+++def test_brokered_opaque_bearer_rotates_on_stored_expiry_and_keeps_the_refresh_token(monkeypatch, tmp_path, request):+ """Google access tokens are opaque (no JWT ``exp``): the pool must rotate on ``expires_at_ms``, through the+ plugin's broker instead of a token URL, and keep the refresh token when the response omits it."""+ from agent.credential_pool import load_pool++ home = tmp_path / "hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ grants: list[dict] = []++ def broker(grant: dict) -> dict:+ grants.append(grant)+ return {"access_token": f"ya29.fresh-{len(grants)}", "expires_in": 3600}++ name = "example-brokered"+ cfg = pkce.OAuthPKCEConfig(client_id="", authorize_url="", token_url="", token_request=broker)+ register_provider(ProviderProfile(name=name, auth_type="oauth_external", base_url="https://example.invalid/v1",+ auth_handler=pkce.pkce_auth_handler(cfg), refresh_credential=pkce.pkce_refresh_credential(cfg)))+ request.addfinalizer(lambda: (providers._REGISTRY.pop(name, None), hermes_cli.auth.PROVIDER_REGISTRY.pop(name, None)))++ now_ms = int(time.time() * 1000)+ _write_pool(home, name, _pool_row(name, access="ya29.live", expires_at_ms=now_ms + 3_600_000))+ assert load_pool(name).select().access_token == "ya29.live" and grants == [] # fresh: no broker call++ _write_pool(home, name, _pool_row(name, access="ya29.stale", expires_at_ms=now_ms - 1000))+ leased = load_pool(name).select()+ assert leased.access_token == "ya29.fresh-1"+ assert grants == [{"grant_type": "refresh_token", "refresh_token": "1//rt-0"}]+ disk = json.loads((home / "auth.json").read_text())["credential_pool"][name][0]+ assert (disk["access_token"], disk["refresh_token"]) == ("ya29.fresh-1", "1//rt-0")+ assert disk["expires_at_ms"] > now_ms + 3_000_000++ # A grant the broker rejects is DEAD and stays DEAD through the inference 401 that follows (never re-benched+ # as EXHAUSTED, which would replay the dead token every cooldown).+ from agent.credential_pool import STATUS_DEAD+ from hermes_cli.auth_constants import AuthError++ def dead_broker(grant: dict) -> dict:+ raise AuthError("rejected", provider=name, code="invalid_grant", relogin_required=True)++ cfg_dead = pkce.OAuthPKCEConfig(client_id="", authorize_url="", token_url="", token_request=dead_broker)+ providers._REGISTRY[name] = ProviderProfile(name=name, auth_type="oauth_external", base_url="https://example.invalid/v1",+ refresh_credential=pkce.pkce_refresh_credential(cfg_dead))+ _write_pool(home, name, _pool_row(name, access="ya29.revoked", expires_at_ms=now_ms + 3_600_000))+ pool = load_pool(name)+ pool.select()+ assert pool.try_refresh_current() is None+ pool.mark_exhausted_and_rotate(status_code=401, api_key_hint="ya29.revoked")+ assert json.loads((home / "auth.json").read_text())["credential_pool"][name][0]["last_status"] == STATUS_DEADdiff --git a/tests/providers/test_solstice_gate.py b/tests/providers/test_solstice_gate.pydeleted file mode 100644index 4f5e482e4e6..00000000000--- a/tests/providers/test_solstice_gate.py+++ /dev/null@@ -1,100 +0,0 @@-"""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