The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(cli): the gateway-backed CLI routes Vertex without minting a second token
Teknium72aa6fdb4679
diff --git a/agent/vertex_adapter.py b/agent/vertex_adapter.pyindex 381d1562408..26c4851860c 100644--- a/agent/vertex_adapter.py+++ b/agent/vertex_adapter.py@@ -145,6 +145,21 @@ def _needs_refresh(creds) -> bool:)+def _cached_credentials(resolved_path: Optional[str], sa_raw: Optional[bytes], cache_key: tuple[Any, ...]):+ """(credentials, project_id) from the per-content cache, loading on a miss; None when refused."""+ cached = _creds_cache.get(cache_key)+ if cached is None:+ cached = _load_credentials(resolved_path, sa_raw)+ if cached is None:+ return None+ _creds_cache[cache_key] = cached+ # A rotation leaves the old signature's entry behind; keep at most+ # one Credentials per file so stale identities can't be reused.+ for k in [k for k in _creds_cache if k != cache_key and k[0] == cache_key[0]]:+ _creds_cache.pop(k, None)+ return cached++def get_vertex_credentials(credentials_path: Optional[str] = None) -> tuple[Optional[str], Optional[str]]:"""Return (fresh access_token, project_id) or (None, None); Credentials cached per file content."""if not _ensure_google_auth():@@ -155,16 +170,9 @@ def get_vertex_credentials(credentials_path: Optional[str] = None) -> tuple[Optisa_raw, cache_key = _sa_snapshot(resolved_path)try:- cached = _creds_cache.get(cache_key)+ cached = _cached_credentials(resolved_path, sa_raw, cache_key)if cached is None:- cached = _load_credentials(resolved_path, sa_raw)- if cached is None:- return None, None- _creds_cache[cache_key] = cached- # A rotation leaves the old signature's entry behind; keep at most- # one Credentials per file so stale identities can't be reused.- for k in [k for k in _creds_cache if k != cache_key and k[0] == cache_key[0]]:- _creds_cache.pop(k, None)+ return None, Nonecreds, project_id = cachedif _needs_refresh(creds):creds.refresh(google.auth.transport.requests.Request())@@ -197,6 +205,33 @@ def get_vertex_config(return token, build_vertex_base_url(project_id, _resolve_region(region))+def get_vertex_base_url(credentials_path: Optional[str] = None, region: Optional[str] = None) -> Optional[str]:+ """The Vertex base_url WITHOUT minting a token (no OAuth exchange), or None when the credentials+ cannot be loaded or no project resolves. For processes that route but never send — the+ gateway-backed CLI, whose gateway session mints its own token for the turn."""+ if not _ensure_google_auth():+ return None+ resolved_path = _resolve_credentials_path(credentials_path)+ sa_raw, cache_key = _sa_snapshot(resolved_path)+ try:+ cached = _cached_credentials(resolved_path, sa_raw, cache_key)+ except Exception: # health: allow BLE001 -- same boundary as get_vertex_credentials: unloadable credentials are main's AuthError copy+ logger.debug("Vertex AI credentials could not be loaded", exc_info=True)+ _creds_cache.pop(cache_key, None)+ return None+ project_id = _resolve_project_override() or (cached[1] if cached else None)+ return build_vertex_base_url(project_id, _resolve_region(region)) if cached and project_id else None+++def vertex_access_token() -> str:+ """Callable API key: a fresh Vertex token, minted on first use and reused until near expiry.+ One stable object, so a credential re-resolution never reads as a key change."""+ token, _project_id = get_vertex_credentials()+ if not token:+ raise RuntimeError("Vertex AI OAuth token could not be minted (see the Vertex credential settings)")+ return token++def has_vertex_credentials() -> bool:"""Fast check (no network): a resolvable SA JSON path, or an explicit project ID (implies ADC)."""return bool(_resolve_credentials_path(None) or _resolve_project_override())diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.pyindex 760639a9840..79def48dbb2 100644--- a/hermes_cli/cli_agent_setup_mixin.py+++ b/hermes_cli/cli_agent_setup_mixin.py@@ -233,26 +233,30 @@ class CLIAgentSetupMixin:"""Re-resolve provider credentials before agent use so key rotation / tokenrefresh are picked up without restarting the CLI. False on auth failure."""from cli import ChatConsole, logger- from hermes_cli.runtime_provider import resolve_runtime_provider, format_runtime_provider_error+ from hermes_cli.runtime_provider import (+ deferred_token_mint, format_runtime_provider_error, resolve_runtime_provider)_primary_exc = Noneruntime = None_model_at_entry = self.modelself._credentials_rate_limited = Falseself._credentials_terminal = False- try:- # target_model: the ladder's model-keyed rungs (Zen/Go api_mode, Copilot/Nous- # api_mode) must see the model this CLI will actually send, not config's `default`,- # or `hermes -m mimo-v2.5 --provider opencode-go` resolves an api_mode/base_url the- # sent model cannot use (#112600).- runtime = resolve_runtime_provider(- requested=self.requested_provider, explicit_api_key=self._explicit_api_key,- explicit_base_url=self._explicit_base_url, target_model=self.model or None)- except Exception as exc:- _primary_exc = exc- if _primary_exc is not None:- runtime = self._resolve_fallback_runtime(_primary_exc)- if runtime is not None:- _primary_exc = None+ # The gateway session runs the turn and mints its own short-lived OAuth token (Vertex); this+ # process only routes, so it must not run a second JWT exchange per launch.+ with deferred_token_mint():+ try:+ # target_model: the ladder's model-keyed rungs (Zen/Go api_mode, Copilot/Nous+ # api_mode) must see the model this CLI will actually send, not config's `default`,+ # or `hermes -m mimo-v2.5 --provider opencode-go` resolves an api_mode/base_url the+ # sent model cannot use (#112600).+ runtime = resolve_runtime_provider(+ requested=self.requested_provider, explicit_api_key=self._explicit_api_key,+ explicit_base_url=self._explicit_base_url, target_model=self.model or None)+ except Exception as exc:+ _primary_exc = exc+ if _primary_exc is not None:+ runtime = self._resolve_fallback_runtime(_primary_exc)+ if runtime is not None:+ _primary_exc = Noneif runtime is None:from hermes_cli.auth import AuthError, is_rate_limited_auth_errorself._credentials_rate_limited = bool(_primary_exc) and is_rate_limited_auth_error(_primary_exc)@@ -417,11 +421,12 @@ class CLIAgentSetupMixin:"""``(ready, error)``: *error* is the exception that stopped resolution — raised, orswallowed by the "auto" ladder and stamped on a keyless fallback — ``None`` when a providerresolved (usable or merely keyless). Never prints or mutates CLI state."""- from hermes_cli.runtime_provider import resolve_runtime_provider+ from hermes_cli.runtime_provider import deferred_token_mint, resolve_runtime_providertry:- runtime = resolve_runtime_provider(- requested=self.requested_provider, explicit_api_key=self._explicit_api_key,- explicit_base_url=self._explicit_base_url)+ with deferred_token_mint(): # a readiness probe never needs a live token+ runtime = resolve_runtime_provider(+ requested=self.requested_provider, explicit_api_key=self._explicit_api_key,+ explicit_base_url=self._explicit_base_url)except Exception as exc:return False, excif not isinstance(runtime, dict):diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.pyindex 73b17641a31..8593a3a4342 100644--- a/hermes_cli/runtime_provider.py+++ b/hermes_cli/runtime_provider.py@@ -58,6 +58,21 @@ def frozen_runtime_config(config: dict[str, Any]):_FROZEN_RUNTIME_CONFIG.reset(token)+_DEFER_TOKEN_MINT: ContextVar[bool] = ContextVar("_DEFER_TOKEN_MINT", default=False)+++@contextmanager+def deferred_token_mint():+ """Resolve the route without exchanging short-lived OAuth tokens up front (Vertex today): the+ resolved ``api_key`` is a callable that mints on first use. For the gateway-backed classic+ CLI, whose gateway session mints its own token for every turn it runs."""+ token = _DEFER_TOKEN_MINT.set(True)+ try:+ yield+ finally:+ _DEFER_TOKEN_MINT.reset(token)++# Late-bound delegates, deliberately NOT module-level from-imports: this module is often imported# lazily, so its first import can happen while a test has ``hermes_cli.config.load_config`` patched# — a from-import would bind the MagicMock permanently and poison every later caller.@@ -944,9 +959,14 @@ def _raise_if_local_alias_missing_endpoint(requested_provider: str, explicit_basdef _resolve_vertex_runtime(requested_provider: str) -> dict[str, Any]:"""Vertex AI (OAuth2). The credential *path* (GOOGLE_APPLICATION_CREDENTIALS) must never betreated as a static API key; a short-lived token is minted per call, and mid-session expiry is- recovered on 401 by run_agent._try_refresh_vertex_client_credentials()."""- from agent.vertex_adapter import get_vertex_config- token, base_url = get_vertex_config()+ recovered on 401 by run_agent._try_refresh_vertex_client_credentials(). Under+ :func:`deferred_token_mint` the credentials are loaded (same failure copy) but the token is a+ callable minted on first use, so a process that only routes never exchanges a JWT."""+ from agent.vertex_adapter import get_vertex_base_url, get_vertex_config, vertex_access_token+ if _DEFER_TOKEN_MINT.get():+ token, base_url = vertex_access_token, get_vertex_base_url()+ else:+ token, base_url = get_vertex_config()if not token or not base_url:raise AuthError("Vertex AI credentials could not be resolved. Vertex uses OAuth2 (not a static API key): provide a ""service-account JSON via GOOGLE_APPLICATION_CREDENTIALS (or VERTEX_CREDENTIALS_PATH) in ~/.hermes/.env, "diff --git a/tests/hermes_cli/test_vertex_provider.py b/tests/hermes_cli/test_vertex_provider.pyindex 34feffcde1a..2820141f37d 100644--- a/tests/hermes_cli/test_vertex_provider.py+++ b/tests/hermes_cli/test_vertex_provider.py@@ -46,3 +46,74 @@ def test_vertex_registered_in_hermes_overlays():resolved = get_provider("vertex")assert resolved is not Noneassert resolved.auth_type == "vertex"+++class _CountingCreds:+ """google-auth Credentials stand-in: every refresh() is one OAuth JWT exchange (a mint)."""++ def __init__(self, mints: list):+ self.token, self.expired, self.expiry, self._mints = None, False, None, mints++ def refresh(self, _request):+ self._mints.append(1)+ self.token = f"ya29.minted-{len(self._mints)}"+++def _vertex_cli_shell(monkeypatch, tmp_path, *, loadable: bool):+ import types++ import agent.vertex_adapter as va+ from hermes_cli.cli_agent_setup_mixin import CLIAgentSetupMixin++ home = tmp_path / "hermes"+ home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(home))+ mints: list = []+ sa = tmp_path / "sa.json"+ sa.write_text('{"project_id": "sa-proj"}')+ va._creds_cache.clear()+ monkeypatch.setattr(va, "_ensure_google_auth", lambda: True)+ request_mod = types.SimpleNamespace(Request=lambda: None)+ monkeypatch.setattr(va, "google", types.SimpleNamespace(auth=types.SimpleNamespace(+ transport=types.SimpleNamespace(requests=request_mod))), raising=False)+ monkeypatch.setattr(va, "_resolve_credentials_path", lambda explicit=None: str(sa))+ monkeypatch.setattr(va, "_vertex_config", lambda: {"region": "us-central1"})+ monkeypatch.setattr(va, "_load_credentials",+ lambda path, raw: (_CountingCreds(mints), "sa-proj") if loadable else None)++ shell = CLIAgentSetupMixin.__new__(CLIAgentSetupMixin)+ shell.model, shell.requested_provider = "google/gemini-3-flash-preview", "vertex"+ shell._explicit_api_key = shell._explicit_base_url = None+ shell._fallback_model = []+ shell.tool_progress_mode = "off"+ shell.agent = shell.api_key = shell.base_url = shell.provider = shell.acp_command = None+ shell.api_mode, shell.acp_args = "chat_completions", []+ shell._normalize_model_for_provider = lambda _provider: False+ shell._maybe_print_free_tier_available_notice = lambda: None+ return shell, mints+++def test_gateway_backed_cli_resolves_vertex_route_without_minting(monkeypatch, tmp_path):+ """The classic CLI is a thin client: the gateway session mints the Vertex token for the turn it+ runs. Resolving the CLI's route must not run a second OAuth exchange per launch."""+ shell, mints = _vertex_cli_shell(monkeypatch, tmp_path, loadable=True)++ assert shell._ensure_runtime_credentials() is True+ assert mints == [], "the CLI process minted a Vertex token the gateway mints again"+ assert shell.provider == "vertex"+ assert shell.base_url == (+ "https://us-central1-aiplatform.googleapis.com/v1beta1/projects/sa-proj/locations/us-central1/endpoints/openapi")+ assert callable(shell.api_key)+ # A caller that really sends from this process still gets a token, minted once and reused.+ assert shell.api_key() == shell.api_key() == "ya29.minted-1"+ assert mints == [1]+++def test_gateway_backed_cli_keeps_vertex_credential_failure_copy(monkeypatch, tmp_path, capsys):+ """Unloadable Vertex credentials still fail in the CLI with main's actionable copy."""+ shell, mints = _vertex_cli_shell(monkeypatch, tmp_path, loadable=False)++ assert shell._ensure_runtime_credentials() is False+ err = capsys.readouterr().err+ assert "Vertex AI credentials could not be resolved" in err and "VERTEX_CREDENTIALS_PATH" in err, err+ assert mints == []