Skip to content

The agent that grows with you

perf(onboarding): one provider walk per due answer, one AWS chain walk, no IMDS on the desktop backend

alt-glitch0fa749103405
diff --git a/agent/bedrock_adapter.py b/agent/bedrock_adapter.py
index 1747e06da17..6e92773da0c 100644
--- a/agent/bedrock_adapter.py
+++ b/agent/bedrock_adapter.py
@@ -347,33 +347,39 @@ _AWS_AUTH_ENV_CHAIN: tuple[tuple[str, ...], ...] = (
)
-def _boto3_chain_has_credentials() -> bool:
- """True if boto3's default chain resolves credentials (IMDS, task role, ...)."""
+def _boto3_chain_has_credentials(*, instance_metadata: bool = True) -> bool:
+ """True if boto3's default chain resolves credentials (IMDS, task role, ...). *instance_metadata*
+ False skips the EC2 metadata lookup (169.254.169.254), which off EC2 only costs its timeout."""
with suppress(Exception):
import botocore.session
- credentials = botocore.session.get_session().get_credentials()
+ session = botocore.session.get_session()
+ if not instance_metadata:
+ session.set_config_variable("ec2_metadata_disabled", "true") # this session only, not os.environ
+ credentials = session.get_credentials()
resolved = credentials.get_frozen_credentials() if credentials is not None else None
return bool(resolved and resolved.access_key)
return False
-def resolve_aws_auth_env_var(env: Optional[dict[str, str]] = None) -> Optional[str]:
+def resolve_aws_auth_env_var(
+ env: Optional[dict[str, str]] = None, *, instance_metadata: bool = True,
+) -> Optional[str]:
"""Name of the active AWS auth source: env vars first (no I/O), then ``"iam-role"`` via boto3's chain, else None."""
env = env if env is not None else os.environ
for group in _AWS_AUTH_ENV_CHAIN:
if all(env.get(var, "").strip() for var in group):
return group[0]
- return "iam-role" if _boto3_chain_has_credentials() else None
+ return "iam-role" if _boto3_chain_has_credentials(instance_metadata=instance_metadata) else None
-def has_aws_credentials(env: Optional[dict[str, str]] = None) -> bool:
+def has_aws_credentials(env: Optional[dict[str, str]] = None, *, instance_metadata: bool = True) -> bool:
"""True if any AWS credential source (env vars or boto3 chain) is detected.
This two-tier approach mirrors the pattern from OpenClaw PR #62673: cloud environments (EC2, ECS,
Lambda) provide credentials via instance metadata, not environment variables. The env-var check is a
fast path for local development; the boto3 fallback covers all cloud deployments.
"""
- return resolve_aws_auth_env_var(env) is not None or _boto3_chain_has_credentials()
+ return resolve_aws_auth_env_var(env, instance_metadata=instance_metadata) is not None
def resolve_bedrock_region(env: Optional[dict[str, str]] = None) -> str:
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.py
index 2d975ad0a9a..eee16ca34a2 100644
--- a/hermes_cli/auth.py
+++ b/hermes_cli/auth.py
@@ -1707,7 +1707,10 @@ def resolve_provider(
# below explicit keys and below the free tier.
try:
from agent.bedrock_adapter import has_aws_credentials
- if has_aws_credentials():
+ from hermes_cli.anon_auth import on_local_desktop_backend
+ # The desktop's own backend runs on the user's computer, where the EC2 metadata lookup only
+ # costs its timeout on every cold resolve.
+ if has_aws_credentials(instance_metadata=not on_local_desktop_backend()):
return "bedrock"
except ImportError:
pass # boto3 not installed
diff --git a/hermes_cli/welcome_trial.py b/hermes_cli/welcome_trial.py
index f79420ede19..d36ea9fb6d1 100644
--- a/hermes_cli/welcome_trial.py
+++ b/hermes_cli/welcome_trial.py
@@ -16,6 +16,7 @@ from __future__ import annotations
import contextlib
import logging
+from dataclasses import dataclass
import sqlite3
from collections.abc import Callable
from pathlib import Path
@@ -47,9 +48,11 @@ def provider_configured() -> bool:
def inference_available(*, assume_fresh: bool = False) -> bool:
"""Something can carry a first chat on this backend: the trial (claimed, or claimable now) or a
- configured provider."""
- return (anon_auth.free_inference_active() or provider_configured()
- or claim_blocker(assume_fresh=assume_fresh) is None)
+ configured provider. One walk of the provider ladder answers both halves."""
+ if anon_auth.free_inference_active():
+ return True
+ configured = provider_configured()
+ return configured or claim_blocker(assume_fresh=assume_fresh, configured=configured) is None
def _machine_is_used(assume_fresh: bool) -> bool:
@@ -58,20 +61,29 @@ def _machine_is_used(assume_fresh: bool) -> bool:
return not assume_fresh and probe().existing and not trial_reserved()
+@dataclass(frozen=True, slots=True)
+class _Ask:
+ assume_fresh: bool
+ configured: Optional[bool] # the caller's provider_configured() answer, when it has one
+
+
# Cheapest first; the last one reads the disk. Each is a reason the trial cannot be claimed.
-_CLAIM_BLOCKERS: tuple[tuple[str, Callable[[bool], bool]], ...] = (
- ("not the desktop's local backend", lambda _fresh: not anon_auth.on_local_desktop_backend()),
- ("guests are switched off", lambda _fresh: not anon_auth.guest_allowed()),
- ("a Nous identity exists", lambda _fresh: _has_nous_identity()),
- ("a provider is configured", lambda _fresh: provider_configured()),
- ("Hermes was used on this machine", _machine_is_used),
+_CLAIM_BLOCKERS: tuple[tuple[str, Callable[[_Ask], bool]], ...] = (
+ ("not the desktop's local backend", lambda _ask: not anon_auth.on_local_desktop_backend()),
+ ("guests are switched off", lambda _ask: not anon_auth.guest_allowed()),
+ ("a Nous identity exists", lambda _ask: _has_nous_identity()),
+ ("a provider is configured",
+ lambda ask: provider_configured() if ask.configured is None else ask.configured),
+ ("Hermes was used on this machine", lambda ask: _machine_is_used(ask.assume_fresh)),
)
-def claim_blocker(*, assume_fresh: bool = False) -> Optional[str]:
+def claim_blocker(*, assume_fresh: bool = False, configured: Optional[bool] = None) -> Optional[str]:
"""Why the trial cannot be claimed here, or None when it can. *assume_fresh* is the unpackaged
- desktop's ``--fresh-install`` switch: it skips only the machine check."""
- return next((reason for reason, blocks in _CLAIM_BLOCKERS if blocks(assume_fresh)), None)
+ desktop's ``--fresh-install`` switch: it skips only the machine check. *configured* is a
+ ``provider_configured()`` answer the caller already has, so the ladder is not walked twice."""
+ ask = _Ask(assume_fresh, configured)
+ return next((reason for reason, blocks in _CLAIM_BLOCKERS if blocks(ask)), None)
def claim_desktop_free_tier(*, assume_fresh: bool = False, force: bool = False) -> Optional[dict[str, Any]]:
diff --git a/tests/agent/test_bedrock_credential_probe.py b/tests/agent/test_bedrock_credential_probe.py
new file mode 100644
index 00000000000..3ccb17ae0a3
--- /dev/null
+++ b/tests/agent/test_bedrock_credential_probe.py
@@ -0,0 +1,38 @@
+"""The AWS credential probe the provider ladder runs: one walk of boto3's chain per question, and no
+instance-metadata lookup from the desktop's own backend (a laptop, where it only costs seconds)."""
+
+from __future__ import annotations
+
+import pytest
+
+from agent import bedrock_adapter
+from tests.hermes_cli.anon_portal import as_local_desktop_backend
+
+_AWS_VARS = ("AWS_BEARER_TOKEN_BEDROCK", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_PROFILE",
+ "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_WEB_IDENTITY_TOKEN_FILE")
+
+
+def chain(monkeypatch):
+ for var in _AWS_VARS:
+ monkeypatch.delenv(var, raising=False)
+ walks: list[dict] = []
+ monkeypatch.setattr(bedrock_adapter, "_boto3_chain_has_credentials",
+ lambda **kw: (walks.append(kw), False)[1])
+ return walks
+
+
+def test_no_credentials_walks_the_chain_once(chain):
+ assert bedrock_adapter.has_aws_credentials() is False
+ assert len(chain) == 1
+
+
+def test_the_desktop_backends_auto_detect_skips_instance_metadata(chain, monkeypatch):
+ from hermes_cli.auth import resolve_provider
+ from hermes_cli.auth_constants import AuthError
+
+ as_local_desktop_backend(monkeypatch)
+ with pytest.raises(AuthError):
+ resolve_provider("auto", skip_free_tier=True)
+
+ assert chain and all(walk.get("instance_metadata") is False for walk in chain)
diff --git a/tests/hermes_cli/anon_portal.py b/tests/hermes_cli/anon_portal.py
index e2d577b152e..81180e2e4b9 100644
--- a/tests/hermes_cli/anon_portal.py
+++ b/tests/hermes_cli/anon_portal.py
@@ -134,7 +134,7 @@ def install_portal(monkeypatch, tmp_path, fake: FakePortal | None = None) -> Fak
kw["transport"] = httpx.MockTransport(fake.handler)
super().__init__(*a, **kw)
monkeypatch.setattr(httpx, "Client", _RoutedClient)
- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)
+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda *_a, **_kw: False)
anon_auth.reset_mint_memo_for_tests()
free_tier_bootstrap.reset_for_tests()
from hermes_cli import anon_challenge
diff --git a/tests/hermes_cli/test_anon_auth_core.py b/tests/hermes_cli/test_anon_auth_core.py
index d667f5010cf..9ecb9016e6e 100644
--- a/tests/hermes_cli/test_anon_auth_core.py
+++ b/tests/hermes_cli/test_anon_auth_core.py
@@ -82,7 +82,7 @@ class TestIdentityLifecycle:
def test_opt_out_bool_disables_everything(self, portal, monkeypatch):
_write_config(monkeypatch, guest=False)
# A developer machine's ~/.aws would answer the Bedrock rung and hide the AuthError.
- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)
+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda *_a, **_kw: False)
assert anon_auth.ensure_portal_identity(explicit=True) is None
assert portal.calls == []
with pytest.raises(anon_auth.AuthError):
@@ -327,7 +327,7 @@ class TestBootstrapNeverCreates:
return fb
def test_bootstrap_on_a_fresh_machine_mints_nothing(self, portal, monkeypatch):
- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)
+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda *_a, **_kw: False)
from tests.hermes_cli.anon_portal import as_local_desktop_backend
as_local_desktop_backend(monkeypatch) # the trial is claimable here; boot still never claims it
record = self._fresh().run_bootstrap(announce=False)
@@ -357,7 +357,7 @@ class TestBootstrapNeverCreates:
def test_reads_never_mint(self, portal, monkeypatch):
"""status, provider resolution and the connector bearer are reads: with no identity they
answer 'nothing' and touch no network."""
- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)
+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda *_a, **_kw: False)
from tools.managed_tool_gateway import read_nous_access_token
assert read_nous_access_token() is None
with pytest.raises(anon_auth.AuthError):
diff --git a/tests/hermes_cli/test_api_key_providers.py b/tests/hermes_cli/test_api_key_providers.py
index 908a18ee944..a9168d196dc 100644
--- a/tests/hermes_cli/test_api_key_providers.py
+++ b/tests/hermes_cli/test_api_key_providers.py
@@ -156,7 +156,7 @@ class TestResolveProvider:
# behavior, not the Bedrock fallback.
monkeypatch.setattr(
"agent.bedrock_adapter.has_aws_credentials",
- lambda env=None: False,
+ lambda env=None, **_kw: False,
)
monkeypatch.setenv("GITHUB_TOKEN", "gh-test-token")
with pytest.raises(AuthError, match="not connected to any AI provider"):
diff --git a/tests/hermes_cli/test_bedrock_model_picker.py b/tests/hermes_cli/test_bedrock_model_picker.py
index b6c39db1ce1..5bae95e1b18 100644
--- a/tests/hermes_cli/test_bedrock_model_picker.py
+++ b/tests/hermes_cli/test_bedrock_model_picker.py
@@ -170,7 +170,7 @@ class TestListAuthenticatedProvidersBedrock:
calls = {"has_aws_credentials": 0}
- def _has_aws_credentials():
+ def _has_aws_credentials(*_a, **_kw):
calls["has_aws_credentials"] += 1
return False
diff --git a/tests/hermes_cli/test_provider_precedence.py b/tests/hermes_cli/test_provider_precedence.py
index 33d92403910..7356dc83948 100644
--- a/tests/hermes_cli/test_provider_precedence.py
+++ b/tests/hermes_cli/test_provider_precedence.py
@@ -25,7 +25,7 @@ def _config(monkeypatch, model_cfg):
def _no_aws(monkeypatch):
# Neutralize any ambient AWS creds so Bedrock auto-detect can't interfere.
- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)
+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda *_a, **_kw: False)
def _clear_provider_env(monkeypatch):
@@ -99,7 +99,7 @@ def _claimed_trial_with_aws(monkeypatch):
_clear_provider_env(monkeypatch)
claimed_trial(monkeypatch)
_never_mint(monkeypatch)
- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: True)
+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda *_a, **_kw: True)
class TestFreeTierBeatsImplicitHostCredentials:
@@ -131,7 +131,7 @@ class TestFreeTierBeatsImplicitHostCredentials:
monkeypatch.delenv("HERMES_DESKTOP", raising=False)
monkeypatch.delenv("HERMES_DASHBOARD_SESSION_TOKEN", raising=False)
assert resolve_provider("auto") == "bedrock"
- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)
+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda *_a, **_kw: False)
with pytest.raises(AuthError):
resolve_provider("auto")
@@ -139,7 +139,7 @@ class TestFreeTierBeatsImplicitHostCredentials:
"""With the free tier hidden, a claimed trial is not an answer and the ladder falls through
to the next real rung."""
_claimed_trial_with_aws(monkeypatch)
- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)
+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda *_a, **_kw: False)
assert resolve_provider("auto") == "nous"
with pytest.raises(AuthError):
resolve_provider("auto", skip_free_tier=True)
diff --git a/tests/hermes_cli/test_resolve_provider_custom_endpoint.py b/tests/hermes_cli/test_resolve_provider_custom_endpoint.py
index ba0b83562d8..65f4c9d1cbc 100644
--- a/tests/hermes_cli/test_resolve_provider_custom_endpoint.py
+++ b/tests/hermes_cli/test_resolve_provider_custom_endpoint.py
@@ -21,7 +21,7 @@ def isolated_home(tmp_path, monkeypatch):
for var in ("OPENAI_API_KEY", "OPENROUTER_API_KEY", "ANTHROPIC_API_KEY", "OPENAI_BASE_URL",
"OPENROUTER_BASE_URL", "HERMES_INFERENCE_PROVIDER", "NOUS_API_KEY"):
monkeypatch.delenv(var, raising=False)
- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)
+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda *_a, **_kw: False)
from hermes_cli import free_tier_bootstrap as fb
fb.reset_for_tests()
return home
diff --git a/tests/hermes_cli/test_runtime_provider_resolution.py b/tests/hermes_cli/test_runtime_provider_resolution.py
index 9282c151faa..8b5c8bc451f 100644
--- a/tests/hermes_cli/test_runtime_provider_resolution.py
+++ b/tests/hermes_cli/test_runtime_provider_resolution.py
@@ -691,7 +691,7 @@ def test_real_openai_key_is_never_routed_or_sent_to_openrouter(monkeypatch):
from hermes_cli.runtime_provider_backends import _resolve_openrouter_runtime
monkeypatch.setattr(rp, "_get_model_config", dict)
monkeypatch.setattr("hermes_cli.config.load_config", lambda: {"model": {}})
- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)
+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda *_a, **_kw: False)
for var in ("OPENAI_BASE_URL", "OPENROUTER_BASE_URL", "OPENROUTER_API_KEY", "CUSTOM_BASE_URL"):
monkeypatch.delenv(var, raising=False)
monkeypatch.setenv("OPENAI_API_KEY", "sk-proj-real-openai-key")
@@ -1978,7 +1978,7 @@ def _patch_bedrock(monkeypatch, config_default=""):
monkeypatch.setattr(rp, "resolve_provider", lambda *a, **k: "bedrock")
monkeypatch.setattr(rp, "_get_model_config", lambda: {"default": config_default})
monkeypatch.setattr(rp, "load_config", lambda: {"bedrock": {}})
- monkeypatch.setattr(ba, "has_aws_credentials", lambda: True)
+ monkeypatch.setattr(ba, "has_aws_credentials", lambda *_a, **_kw: True)
monkeypatch.setattr(ba, "resolve_aws_auth_env_var", lambda: "AWS_PROFILE")
monkeypatch.setattr(ba, "resolve_bedrock_region", lambda: "eu-north-1")
diff --git a/tests/hermes_cli/test_web_server.py b/tests/hermes_cli/test_web_server.py
index 07873e16fac..acf77436924 100644
--- a/tests/hermes_cli/test_web_server.py
+++ b/tests/hermes_cli/test_web_server.py
@@ -1495,7 +1495,7 @@ CONFIG_SCHEMA = ProviderConfigSchema(
fb.reset_for_tests()
monkeypatch.setattr("hermes_cli.model_cost_guard.expensive_model_warning", lambda *_a, **_k: None)
- monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda: False)
+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda *_a, **_kw: False)
broadcasts = []
monkeypatch.setattr(fb, "_broadcast", broadcasts.append)
with fb._lock:
diff --git a/tests/hermes_cli/test_welcome_trial.py b/tests/hermes_cli/test_welcome_trial.py
index b19bb37947f..39968efa8d6 100644
--- a/tests/hermes_cli/test_welcome_trial.py
+++ b/tests/hermes_cli/test_welcome_trial.py
@@ -272,3 +272,14 @@ def test_a_missed_first_launch_stays_due_and_keeps_the_trial(portal, monkeypatch
assert welcome_trial.claim_blocker() is None
assert welcome_trial.claim_desktop_free_tier() is not None
assert welcome_trial.claim_blocker() == "a Nous identity exists"
+
+
+def test_one_due_answer_walks_the_provider_ladder_once(portal, monkeypatch):
+ from hermes_cli import auth
+
+ as_local_desktop_backend(monkeypatch)
+ real, calls = auth.resolve_provider, []
+ monkeypatch.setattr(auth, "resolve_provider", lambda *a, **kw: (calls.append(kw), real(*a, **kw))[1])
+
+ assert welcome_trial.inference_available() is True # fresh: the trial is claimable
+ assert len(calls) == 1