Skip to content

The agent that grows with you

fix(gateway,cron): 401 sign-in hints name the provider and the failing profile

teknium1d6a58adbc53e
diff --git a/agent/turn_failure_copy.py b/agent/turn_failure_copy.py
index b3307204bad..ea3e8803288 100644
--- a/agent/turn_failure_copy.py
+++ b/agent/turn_failure_copy.py
@@ -282,6 +282,23 @@ def oauth_relogin_command(provider: Any) -> str:
return f"hermes {profile_cli_selector()}auth add {slug} --type oauth"
+def relogin_command_hint(provider: Any) -> str:
+ """Re-sign-in command for a rejected credential on surfaces that may not know the provider:
+ the exact OAuth command for a known OAuth slug, ``hermes auth add <slug>`` for a known API-key
+ slug, and the ``<provider>`` placeholder when the slug is unknown — always carrying the
+ ``-p <profile>`` selector so a profile user never re-signs the ROOT store (#114012)."""
+ from hermes_constants import profile_cli_selector
+
+ slug = str(provider or "").strip().lower()
+ if not slug:
+ return f"hermes {profile_cli_selector()}auth add <provider>"
+ from agent.error_surface import auth_kind
+
+ if auth_kind(slug) == "oauth":
+ return oauth_relogin_command(slug)
+ return f"hermes {profile_cli_selector()}auth add {slug}"
+
+
def nonretryable_copy(
classified: Any, *, provider: Any, model: Any, summary: str, prefix_suggestion: Optional[str] = None,
) -> str:
diff --git a/cron/scheduler.py b/cron/scheduler.py
index a469c49a4b7..a38c17bc93a 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -250,7 +250,7 @@ def _summarize_cron_failure_for_delivery(job: dict, error: str | None) -> str:
if not job.get("no_agent"):
notice = provider_failure_notice(
job_name, job_id, classify_cron_failure_reason(text),
- backup_provider_phrase=_fallback_chain_phrase())
+ backup_provider_phrase=_fallback_chain_phrase(), provider=job.get("provider"))
if notice is not None:
return notice
diff --git a/cron/scheduler_failure_copy.py b/cron/scheduler_failure_copy.py
index 5612ee659b9..d909b8b2b4a 100644
--- a/cron/scheduler_failure_copy.py
+++ b/cron/scheduler_failure_copy.py
@@ -9,7 +9,7 @@ the real output directory — "cron output" alone sent operators hunting.
from __future__ import annotations
import re
-from typing import Optional
+from typing import Any, Optional
from hermes_constants import display_hermes_home
@@ -59,7 +59,7 @@ _PROVIDER_FAILURE_ACTION: dict[str, str] = {
"`hermes cron edit {job_id} --provider <name>`."
),
"auth": (
- "Sign in again with /login (or `hermes auth add <provider>` in a terminal), or pin a "
+ "Sign in again with /login (or `{relogin}` in a terminal), or pin a "
"working provider with `hermes cron edit {job_id} --provider <name>`, then "
"`hermes cron run {job_id}` to retry."
),
@@ -77,9 +77,10 @@ _DEFAULT_FAILURE_ACTION = "Run it again with `hermes cron run {job_id}`, or edit
def provider_failure_notice(
- job_name: str, job_id: str, reason: str, *, backup_provider_phrase: str,
+ job_name: str, job_id: str, reason: str, *, backup_provider_phrase: str, provider: Any = None,
) -> Optional[str]:
- """The notice for a provider-shaped ``reason``, or None when the reason is not one."""
+ """The notice for a provider-shaped ``reason``, or None when the reason is not one.
+ ``provider`` is the job's pinned slug (if any) so the auth action names its exact sign-in."""
cause = _provider_failure_cause(reason)
if cause is None:
return None
@@ -89,7 +90,10 @@ def provider_failure_notice(
f"`hermes cron run {job_id}` tries now."
)
else:
- action = _PROVIDER_FAILURE_ACTION.get(reason, _DEFAULT_FAILURE_ACTION).format(job_id=job_id)
+ from agent.turn_failure_copy import relogin_command_hint
+
+ action = _PROVIDER_FAILURE_ACTION.get(reason, _DEFAULT_FAILURE_ACTION).format(
+ job_id=job_id, relogin=relogin_command_hint(provider))
return (
f"⚠️ Cron '{job_name}' failed: {cause}. {action} "
f"Run log: `hermes cron runs {job_id}`."
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index 86d288f1ea6..f0afcd6bf22 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -1887,10 +1887,10 @@ class GatewayTurnMixin:
return response
# Chat-side next steps keyed by HTTP status; Hermes commands only (/login is the gateway's own
- # sign-in, `hermes auth add <provider>` the host equivalent).
+ # sign-in, `{relogin}` the profile-aware host equivalent, filled from the turn's agent provider).
_STATUS_HINTS = {
401: (" Your sign-in to the AI model service has expired or the API key is wrong. "
- "Use /login here, or run `hermes auth add <provider>` on the host."),
+ "Use /login here, or run `{relogin}` on the host."),
402: " Your AI model service balance or quota is used up. Top it up on the service's website, or use /model to switch models.",
529: " The AI model service is temporarily overloaded. Wait a moment, then use /retry.",
}
@@ -1923,7 +1923,12 @@ class GatewayTurnMixin:
logger.debug("Failed to persist inbound user message after agent exception", exc_info=True)
# Never expose raw exception types/messages to end users (info-leakage risk).
status_hint = self._STATUS_HINTS.get(status_code, "")
- if status_code == 429:
+ if status_code == 401:
+ from agent.turn_failure_copy import relogin_command_hint
+
+ _turn_agent = getattr(self._session_state(session_key).turn, "agent", None)
+ status_hint = status_hint.format(relogin=relogin_command_hint(getattr(_turn_agent, "provider", None)))
+ elif status_code == 429:
# Plan usage limit (resets on a schedule) vs a transient rate limit
_err_json = {}
with suppress(Exception):
diff --git a/tests/cron/test_cron_failure_notice_copy.py b/tests/cron/test_cron_failure_notice_copy.py
index 670101d2fb2..9d01cc96ee5 100644
--- a/tests/cron/test_cron_failure_notice_copy.py
+++ b/tests/cron/test_cron_failure_notice_copy.py
@@ -39,6 +39,22 @@ def test_auth_failure_points_at_login_and_a_retry_command(monkeypatch):
assert "401" not in msg
+def test_auth_failure_names_the_pinned_provider_and_the_failing_profile(monkeypatch, tmp_path):
+ """A profile's credentials are its own (93889b770da): the notice must send the operator to
+ THIS profile's sign-in for the job's pinned provider, never a bare placeholder (#114012)."""
+ _no_chain(monkeypatch)
+ profile_home = tmp_path / ".hermes" / "profiles" / "ops"
+ profile_home.mkdir(parents=True)
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_HOME", str(profile_home))
+ msg = _summarize_cron_failure_for_delivery(
+ {**JOB, "provider": "openai-codex"}, "Error code: 401 - Unauthorized")
+ assert "`hermes -p ops auth add openai-codex --type oauth`" in msg, msg
+ assert "<provider>" not in msg
+ unpinned = _summarize_cron_failure_for_delivery(JOB, "Error code: 401 - Unauthorized")
+ assert "`hermes -p ops auth add <provider>`" in unpinned, unpinned
+
+
def test_rate_and_usage_limit_phrases_still_yield_a_provider_notice(monkeypatch):
"""The old cron regex ladder matched these substrings; the shared classifier must too, or a
Nous Portal limit turns into a raw generic notice."""
diff --git a/tests/gateway/test_agent_error_reply_401_hint.py b/tests/gateway/test_agent_error_reply_401_hint.py
new file mode 100644
index 00000000000..f5a7dc8dfaa
--- /dev/null
+++ b/tests/gateway/test_agent_error_reply_401_hint.py
@@ -0,0 +1,45 @@
+"""The gateway's 401 exception reply names the turn's provider and the failing profile's own
+sign-in (93889b770da: a bare ``hermes auth add <provider>`` from a named profile re-signs the
+ROOT store — the loop #114012 measured)."""
+
+import asyncio
+from types import SimpleNamespace
+
+from gateway.config import Platform
+from gateway.platforms.event import MessageEvent
+from gateway.run import GatewayRunner
+from gateway.session import SessionSource
+
+
+def _reply_for_401(provider):
+ runner = object.__new__(GatewayRunner)
+
+ async def stop_typing(event, source):
+ return None
+
+ runner._hmwa_stop_typing_for_turn = stop_typing
+ runner._session_state = lambda key: SimpleNamespace(
+ turn=SimpleNamespace(agent=SimpleNamespace(provider=provider) if provider else None))
+ source = SessionSource(platform=Platform.TELEGRAM, chat_id="c", user_id="u")
+ prepared = runner._PreparedTurn([], "", None, None, None, None)
+ err = RuntimeError("HTTP 401: token_revoked")
+ err.status_code = 401
+ return asyncio.run(runner._hmwa_agent_error_reply(
+ err, MessageEvent(text="x", source=source), source, None, "k", prepared,
+ ))
+
+
+def test_gateway_401_reply_names_the_provider_and_the_profile(monkeypatch, tmp_path):
+ profile_home = tmp_path / ".hermes" / "profiles" / "codex"
+ profile_home.mkdir(parents=True)
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setenv("HERMES_HOME", str(profile_home))
+
+ known = _reply_for_401("openai-codex")
+ assert "/login" in known
+ assert "`hermes -p codex auth add openai-codex --type oauth`" in known, known
+ assert "<provider>" not in known and "{relogin}" not in known
+
+ # No agent yet (failure before the turn claimed one): keep the placeholder, still profile-pinned.
+ unknown = _reply_for_401(None)
+ assert "`hermes -p codex auth add <provider>`" in unknown, unknown