Skip to content

The agent that grows with you

fix(ux): plain-language, actionable user-facing messages (core)

teknium123036e20a665
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.py
index 0a17862aae1..8fdc0f2ac41 100644
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@ -2107,7 +2107,8 @@ def handle_max_iterations(agent, messages: list, api_call_count: int) -> str:
except Exception as e:
logger.warning("Failed to get summary response: %s", e)
- final_response = f"I reached the maximum iterations ({agent.max_iterations}) but couldn't summarize. Error: {str(e)}"
+ from agent.turn_failure_copy import site_copy
+ final_response = site_copy("max_iterations_no_summary", limit=agent.max_iterations)
finally:
from agent import relay_llm
relay_llm.complete_logical_call(summary_api_request_id, outcome=summary_call_outcome)
diff --git a/agent/conversation_compression.py b/agent/conversation_compression.py
index 2cf2eaec0a7..52778a4e3f6 100644
--- a/agent/conversation_compression.py
+++ b/agent/conversation_compression.py
@@ -1808,15 +1808,14 @@ def check_compression_model_feasibility(agent: Any) -> None:
if client is None or not aux_model:
if _aux_cfg_provider and _aux_cfg_provider != "auto":
msg = (
- "⚠ Configured auxiliary compression provider "
- f"'{_aux_cfg_provider}' is unavailable — context "
- "compression will drop middle turns without a summary. "
- "Check auxiliary.compression in config.yaml and reauthenticate that provider."
+ f"⚠ Configured auxiliary compression provider '{_aux_cfg_provider}' is unavailable, "
+ "so older messages in long chats will be cut without a summary. Sign in to that "
+ "provider again, or change auxiliary.compression in your config."
)
else:
msg = (
- "⚠ No auxiliary LLM provider configured — context compression will drop middle turns without a summary. "
- "Run `hermes setup` or set OPENROUTER_API_KEY."
+ "⚠ No auxiliary LLM provider configured: Hermes has no helper model for summarising "
+ "long chats, so older messages will be cut without a summary. Run `hermes setup` to add one."
)
agent._compression_warning = msg
agent._emit_status(msg)
@@ -3033,10 +3032,13 @@ def _warn_summary_or_aux_fallback(agent: Any) -> None:
_aux_key = (_aux_fail_model, _aux_fail_err)
if _aux_fail_model and getattr(agent, "_last_aux_fallback_warning_key", None) != _aux_key:
agent._last_aux_fallback_warning_key = _aux_key
+ logger.warning(
+ "Configured compression model %r failed (%s); recovered using the main model.",
+ _aux_fail_model, _aux_fail_err or "unknown error",
+ )
agent._emit_warning(
- f"ℹ Configured compression model '{_aux_fail_model}' failed "
- f"({_aux_fail_err or 'unknown error'}). Recovered using main model — "
- "check auxiliary.compression.model in config.yaml."
+ f"ℹ Configured compression model '{_aux_fail_model}' failed, so Hermes summarised "
+ "with your main model instead. Check auxiliary.compression.model in your config."
)
diff --git a/agent/conversation_loop.py b/agent/conversation_loop.py
index 6739c096e40..ba97085508a 100644
--- a/agent/conversation_loop.py
+++ b/agent/conversation_loop.py
@@ -39,6 +39,7 @@ from agent.turn_retry_state import TurnRetryState
from agent.turn_api_call import handle_api_interrupt, nous_rate_limit_guard, perform_api_call
from agent.turn_api_error import handle_api_error
from agent.turn_api_request import build_api_request
+from agent.turn_failure_copy import site_copy
from agent.turn_final_response import finish_text_response
from agent.turn_finalizer import finalize_turn
from agent.turn_iteration_prep import (
@@ -876,11 +877,6 @@ _EMPTY_TOOL_RESPONSE_NUDGE = (
)
-# Shared trailer for both content-policy refusal paths so guidance cannot drift.
-_CONTENT_POLICY_RECOVERY_HINT = (
- "Try rephrasing the request, narrowing the context, or adding a fallback provider with "
- "`hermes fallback add`."
-)
# Memo for send-path tool-call argument canonicalization (re-run on every historical call
@@ -970,6 +966,7 @@ def _content_policy_blocked_result(
return {
"final_response": final_response, "messages": messages, "api_calls": api_call_count,
"completed": False, "failed": True, "error": f"content_policy_blocked: {error_detail}",
+ "failure_reason": "content_policy_blocked", "failure_retryable": False,
}
@@ -1040,9 +1037,10 @@ def _provider_overflow_exhausted_result(
# providers.
agent._persist_session(messages, conversation_history)
return _partial_turn_result(
- "Context length exceeded: compression could not reduce the rebuilt request below the safe threshold.",
+ site_copy("context_overflow", model=agent.model),
messages, api_call_count, failed=True, compression_exhausted=True,
turn_exit_reason="context_compression_exhausted",
+ failure_reason="context_overflow", failure_retryable=False,
)
@@ -1268,6 +1266,7 @@ def _preflight_timeout_result(agent, exc, conversation_history) -> Dict[str, Any
return _partial_turn_result(
str(exc), list(conversation_history or []), 0,
failed=True, compression_exhausted=True, turn_exit_reason="context_compression_timeout",
+ failure_reason="context_overflow", failure_retryable=False,
)
diff --git a/agent/display.py b/agent/display.py
index 75ca37a474d..afa23fe107f 100644
--- a/agent/display.py
+++ b/agent/display.py
@@ -888,6 +888,8 @@ class KawaiiSpinner:
# ── Cute tool message (completion line that replaces the spinner) ─────────
_ERROR_SUFFIX_MAX_LEN = 48
+# A degraded backend (Docker down, SSH host unreachable) needs the whole reason plus the fix hint.
+_DEGRADED_SUFFIX_MAX_LEN = 200
def _trim_error(msg: str) -> str:
@@ -900,17 +902,32 @@ def _trim_error(msg: str) -> str:
return _tail_trunc(msg, _ERROR_SUFFIX_MAX_LEN)
+def _degraded_suffix(data: dict) -> str:
+ """`` [<reason> — <retry_hint>]`` for a ``status: degraded`` terminal result (hint omitted when empty)."""
+ reason = str(data.get("reason") or data.get("error") or "terminal backend unavailable").strip()
+ hint = str(data.get("retry_hint") or "").strip()
+ text = f"{reason} — {hint}" if hint else reason
+ return f" [{_tail_trunc(text, _DEGRADED_SUFFIX_MAX_LEN)}]"
+
+
def _detect_tool_failure(tool_name: str, result: str | None) -> tuple[bool, str]:
"""Return ``(is_failure, suffix)`` for a tool result, e.g. ``(True, " [exit 1]")``."""
if result is None or file_mutation_result_landed(tool_name, result):
return False, ""
data = safe_json_loads(result)
+ # A denied/timed-out approval carries one human sentence; show it instead of the model-facing
+ # "BLOCKED: ... Do NOT retry" text (which stays in the JSON for the model).
+ if isinstance(data, dict) and data.get("user_summary"):
+ return True, f" [{_tail_trunc(str(data['user_summary']), _DEGRADED_SUFFIX_MAX_LEN)}]"
+
# Terminal: non-zero exit code is the canonical failure signal.
if tool_name == "terminal":
exit_code = data.get("exit_code") if isinstance(data, dict) else None
if exit_code is None or exit_code == 0:
return False, ""
+ if data.get("status") == "degraded":
+ return True, _degraded_suffix(data)
err_msg = data.get("error")
return True, f" [{_trim_error(str(err_msg))}]" if err_msg else f" [exit {exit_code}]"
diff --git a/agent/error_surface.py b/agent/error_surface.py
index 95fbdadd034..48b613a7912 100644
--- a/agent/error_surface.py
+++ b/agent/error_surface.py
@@ -28,9 +28,17 @@ LAYER_GATEWAY = "gateway"
LAYER_DISK = "disk"
# failure_reason → UI layer. Unlisted reasons fall back to LAYER_PROVIDER:
-# every FailoverReason comes from classifying a provider call.
+# every FailoverReason comes from classifying a provider call. Loop-site codes
+# (agent/turn_failure_copy.py::SITE_FAILURE_CODES) are listed explicitly: the
+# ones that are not provider verdicts map to the gateway layer so the client
+# does not offer "Switch provider"; the ones the model/provider caused
+# (cut-off output, empty or broken reply) stay on the provider layer, where the
+# clients' per-code copy names the real fix (`continue`, smaller steps, /retry).
_REASON_TO_LAYER = {
"auth": LAYER_AUTH, "auth_permanent": LAYER_AUTH, "billing": LAYER_BILLING, "billing_unverified": LAYER_BILLING,
+ "loop_error": LAYER_GATEWAY, "interpreter_shutdown": LAYER_GATEWAY, "session_busy": LAYER_GATEWAY,
+ "truncated": LAYER_PROVIDER, "empty_response": LAYER_PROVIDER, "invalid_response": LAYER_PROVIDER,
+ "context_overflow": LAYER_PROVIDER, # a bigger-window model IS the fix, so Switch provider applies
}
# Failures between us and the base_url (not a provider verdict); on a
@@ -43,6 +51,7 @@ _TRANSPORT_REASONS = {"timeout", "ssl_cert_verification"}
_NON_RETRYABLE_REASONS = {
"auth", "auth_permanent", "billing", "billing_unverified", "content_policy_blocked",
"provider_policy_blocked", "model_not_found", "format_error", "ssl_cert_verification",
+ "context_overflow", "interpreter_shutdown",
}
# Providers whose base_url is user-supplied rather than a known vendor.
@@ -82,7 +91,7 @@ def _surface(layer: str, code: str, retryable: bool, provider: str = "", model:
# OAuth providers are fixed by signing in again; API-key providers by
# replacing the key. The client's one-click recovery needs to know which
# and how to name the account it re-opens.
- surface["auth_kind"] = _auth_kind(provider)
+ surface["auth_kind"] = auth_kind(provider)
surface["provider_label"] = _provider_label(provider)
return surface
@@ -96,7 +105,7 @@ def _provider_label(provider: str) -> str:
return provider
-def _auth_kind(provider: Optional[str]) -> str:
+def auth_kind(provider: Optional[str]) -> str:
"""``"oauth"`` for providers whose credential is an OAuth/subscription grant
(desktop Accounts tab), ``"api_key"`` for everything else."""
try:
diff --git a/agent/secret_scope.py b/agent/secret_scope.py
index 25961eb7d8c..8446cdec5a5 100644
--- a/agent/secret_scope.py
+++ b/agent/secret_scope.py
@@ -23,14 +23,6 @@ from typing import Dict, Mapping, Optional
# at gateway startup when gateway.multiplex_profiles is true.
_MULTIPLEX_ACTIVE: bool = False
-# Context-local counterpart: a task serving a profile OTHER than the process's own, inside a
-# process that is not a multiplexer as a whole — the desktop backend's cron ticker firing a
-# sibling profile's job. Every isolation keyed on ``is_multiplex_active()`` (the routed-dotenv
-# guard, ``get_secret``'s fail-closed miss, subprocess scrubbing, passthrough) applies inside
-# it while the process's own turns keep single-profile semantics. A contextvar, so it reaches
-# the pool worker together with the home override via ``copy_context()``.
-_MULTIPLEX_CONTEXT: ContextVar[bool] = ContextVar("_MULTIPLEX_CONTEXT", default=False)
-
def set_multiplex_active(active: bool) -> None:
"""Mark whether the process is a profile multiplexer (get_secret fails closed)."""
@@ -38,19 +30,8 @@ def set_multiplex_active(active: bool) -> None:
_MULTIPLEX_ACTIVE = bool(active)
-def set_multiplex_context(active: bool) -> Token:
- """Run the current task under multiplex semantics regardless of the process flag.
- Returns a reset token; pair with :func:`reset_multiplex_context` in a ``finally``."""
- return _MULTIPLEX_CONTEXT.set(bool(active))
-
-
-def reset_multiplex_context(token: Token) -> None:
- _MULTIPLEX_CONTEXT.reset(token)
-
-
def is_multiplex_active() -> bool:
- """True in a multiplexing process, or for a task running under multiplex semantics."""
- return _MULTIPLEX_ACTIVE or _MULTIPLEX_CONTEXT.get()
+ return _MULTIPLEX_ACTIVE
_SECRET_SCOPE: ContextVar[Optional[Mapping[str, str]]] = ContextVar("_SECRET_SCOPE", default=None)
@@ -61,8 +42,28 @@ class UnscopedSecretError(RuntimeError):
The fix is to wrap the call path in ``set_secret_scope(...)`` (the per-turn
/ per-adapter profile scope), not to widen the global allowlist.
+
+ ``str(exc)`` is the ONE sentence an end user can act on; the developer diagnosis
+ (which secret, which doc) rides ``__notes__`` so tracebacks and logs keep it.
"""
+ def __init__(self, secret_name: str = "", developer_detail: str = ""):
+ # Older callers passed the whole developer sentence positionally
+ # (``UnscopedSecretError("get_secret('X') called with no scope ...")``); a secret
+ # name never contains whitespace, so treat such a string as the detail.
+ if secret_name and not developer_detail and any(ch.isspace() for ch in secret_name):
+ secret_name, developer_detail = "", secret_name
+ what = f"this profile's {secret_name}" if secret_name else "this profile's API key"
+ super().__init__(
+ f"Hermes could not read {what} (an internal profile-scoping bug on the multiplexed "
+ "gateway, not your configuration). Run `hermes gateway restart`; if it keeps happening, "
+ "report it with `hermes debug share`."
+ )
+ self.secret_name = secret_name
+ self.developer_detail = developer_detail
+ if developer_detail:
+ self.add_note(developer_detail)
+
def set_secret_scope(secrets: Optional[Mapping[str, str]]) -> Token:
"""Install the active profile's secret mapping; ``None`` clears. Returns a reset token."""
@@ -144,15 +145,16 @@ def get_secret(name: str, default: Optional[str] = None) -> Optional[str]:
val = scope.get(name)
if val is not None:
return val
- return default if is_multiplex_active() else _environ_or(name, default)
- if is_multiplex_active():
+ return default if _MULTIPLEX_ACTIVE else _environ_or(name, default)
+ if _MULTIPLEX_ACTIVE:
raise UnscopedSecretError(
+ name,
f"get_secret({name!r}) called with no profile secret scope active "
f"while multiplexing is on. This credential read must run inside a "
f"set_secret_scope(...) block (the per-turn / per-adapter profile "
f"scope). Reading os.environ here would risk leaking another "
f"profile's value. See website/docs/developer-guide/multiplexing-gateway.md "
- f"(Workstream A)."
+ f"(Workstream A).",
)
return _environ_or(name, default)
@@ -248,36 +250,4 @@ def build_profile_secret_scope(hermes_home: Path) -> Dict[str, str]:
except Exception:
external_secrets = {}
secrets.update((k, v) for k, v in external_secrets.items() if not _is_global_env(k))
- # Administrator-managed ``.env`` LAST, with override: the launch process applies it that way
- # (``env_loader._apply_managed_env``) so policy beats a user's own value. Under multiplex
- # semantics ``get_secret`` never reads ``os.environ`` on a scope miss, so a scope built from
- # the profile files alone would drop a managed-only credential and let the user's value win a
- # managed-vs-user collision (#111187 review). Every multiplex-authoritative scope — gateway
- # turn, routed cron fire, external worker — is built here, so managed authority is composed
- # once, not restored by each consumer.
- from hermes_cli.managed_scope import load_managed_env # fail-open: {} when no managed scope
-
- secrets.update((k, v) for k, v in load_managed_env().items() if not _is_global_env(k))
return secrets
-
-
-def refresh_installed_secret_scope(hermes_home: Path) -> bool:
- """Fold a fresh build of *hermes_home*'s secrets into the INSTALLED scope, in place.
-
- A scope is frozen when installed, but a fire can learn of new values afterwards: a routed cron
- fire's first agent build discovers plugin secret sources, and under multiplex semantics the
- reload that follows is hydrate-only (never ``os.environ``), so nothing else would carry those
- values into the scope this fire already holds. The caller names the home the installed scope
- was built for. True when a scope was updated; False when none is installed."""
- scope = _SECRET_SCOPE.get()
- if not isinstance(scope, dict):
- return False
- # REPLACE, don't merge: the rebuild is the profile's current truth, so a name a source has
- # stopped supplying (rotated, revoked, source removed) must disappear from the fire's scope
- # rather than survive as the stale value dict.update() would keep.
- rebuilt = build_profile_secret_scope(hermes_home)
- # Update first, then drop what is gone: a concurrent reader never sees an emptied scope.
- scope.update(rebuilt)
- for name in [n for n in scope if n not in rebuilt]:
- scope.pop(name, None)
- return True
diff --git a/agent/thinking_timeout_guidance.py b/agent/thinking_timeout_guidance.py
index 074097ff9ca..29eeab2ba7a 100644
--- a/agent/thinking_timeout_guidance.py
+++ b/agent/thinking_timeout_guidance.py
@@ -36,17 +36,16 @@ def is_thinking_timeout(classified: object, model: str, error_msg: str) -> bool:
def build_thinking_timeout_guidance(provider: str, model: str, model_label: Optional[str] = None) -> str:
- """User-facing guidance appended to the final response. ``model`` is used verbatim in
- the config snippet so it is copy-pasteable; ``model_label`` is the optional prose name."""
+ """User-facing guidance appended to the final response: easiest fix first (``/reasoning
+ low``), the config knob last. ``model`` is used verbatim in the config path so it is
+ copy-pasteable; ``model_label`` is the optional prose name."""
+ from hermes_constants import display_hermes_home
+
label = model_label or model
return (
- "\n\nThe model's thinking phase exceeded the upstream proxy's idle timeout before the first content token "
- "arrived. This is a "
- f"known issue with reasoning models (like {label}) behind cloud "
- "gateways (NVIDIA NIM, OpenAI, Anthropic, DeepSeek). Workarounds in priority order:\n"
- f"1. Set `providers.{provider}.models.{model}.stale_timeout_seconds: 900` "
- "in `~/.hermes/config.yaml` to extend the per-call timeout. (Hermes's built-in floor is 600s for known "
- "reasoning models — if you still see this after raising, the upstream cap is even shorter.)\n2. Lower "
- "`reasoning_budget` or set `reasoning_effort: medium` on this model if the provider supports it.\n3. Use a "
- "smaller / faster reasoning model if the task doesn't require deep thinking."
+ f"{label} was thinking for so long that the connection timed out before it wrote anything "
+ "(common for reasoning models behind cloud gateways such as NVIDIA NIM, OpenAI, Anthropic, "
+ "DeepSeek). Easiest fixes: `/reasoning low`, or switch to a faster model with /model. "
+ f"Advanced: set `providers.{provider}.models.{model}.stale_timeout_seconds: 900` in "
+ f"`{display_hermes_home()}/config.yaml` to allow a longer wait."
)
diff --git a/agent/turn_api_call.py b/agent/turn_api_call.py
index 379a5e45093..4649ccfff21 100644
--- a/agent/turn_api_call.py
+++ b/agent/turn_api_call.py
@@ -14,7 +14,9 @@ import logging
import time
from typing import Any, Dict, Optional
+from agent.error_classifier import FailoverReason
from agent.message_metadata import append_message
+from agent.turn_failure_copy import site_copy, stamp_failure
logger = logging.getLogger("agent.conversation_loop")
@@ -237,7 +239,7 @@ def nous_rate_limit_guard(
if anon_auth.route_is_welcome_host(getattr(agent, "base_url", "")):
_nous_msg = anon_auth.FREE_TIER_RATE_LIMIT_CHAT.format(reset=reset)
else:
- _nous_msg = f"Nous Portal rate limit active — resets in {reset}."
+ _nous_msg = f"Your Nous account has hit its rate limit; it resets in {reset}."
agent._buffer_vprint(f"⏳ {_nous_msg} Trying fallback...")
agent._buffer_status(f"⏳ {_nous_msg}")
if agent._try_activate_fallback():
@@ -249,18 +251,14 @@ def nous_rate_limit_guard(
# No fallback — surface the buffered rate-limit context that led here.
agent._flush_status_buffer()
agent._persist_session(messages, conversation_history)
- return _verdict("return", {
- "final_response": (
- f"⏳ {_nous_msg}\n\n"
- "No fallback provider available. Try again after the reset, or add a "
- "fallback provider in config.yaml."
- ),
+ return _verdict("return", stamp_failure({
+ "final_response": f"⏳ {_nous_msg}\n\n{site_copy('nous_rate_limit')}",
"messages": messages,
"api_calls": api_call_count,
"completed": False,
"failed": True,
"error": _nous_msg,
- })
+ }, FailoverReason.rate_limit.value, True))
except Exception:
pass # Never let rate guard break the agent loop
return _verdict("fallthrough")
diff --git a/agent/turn_empty_response.py b/agent/turn_empty_response.py
index 026cfbea5b7..813c53b43da 100644
--- a/agent/turn_empty_response.py
+++ b/agent/turn_empty_response.py
@@ -16,6 +16,7 @@ from typing import Any, Dict, List, Optional
from agent import empty_response_guard as _empty_guard
from agent.message_metadata import append_message
+from agent.turn_failure_copy import site_copy
from agent.turn_recovery import interruptible_backoff_sleep
logger = logging.getLogger("agent.conversation_loop")
@@ -131,11 +132,7 @@ def _terminal_empty(agent: Any, assistant_message: Any, finish_reason: str, mess
agent._emit_status(
"⚠️ Model produced reasoning but no visible response after all retries. Returning empty."
)
- return (
- "⚠️ The model produced only internal reasoning and no final answer, despite retries"
- + (" and fallback" if agent._fallback_chain else "")
- + ". Its last reasoning, which may contain the answer:\n\n" + reasoning_preview
- )
+ return site_copy("reasoning_only", model=agent.model, preview=reasoning_preview)
def recover_empty_response(
diff --git a/agent/turn_explainers.py b/agent/turn_explainers.py
index 8d78279a31a..9d7252ddbd1 100644
--- a/agent/turn_explainers.py
+++ b/agent/turn_explainers.py
@@ -17,17 +17,19 @@ from agent.tool_result_classification import (
_NO_REPLY = "⚠️ No reply: "
+# One text for "the model produced nothing after retries" on every surface (CLI explainer,
+# gateway ``(empty)`` rewrite, desktop); the model name is filled in by the explainer.
+EMPTY_RESPONSE_EXPLANATION = (
+ "{model} didn't produce a reply this time, even after retries. "
+ "Send `continue` to try again, or switch models with /model."
+)
+
# Exact ``turn_exit_reason`` → explanation body (prefixed with ``_NO_REPLY``).
_EXIT_REASON_EXPLANATIONS: Dict[str, str] = {
- "empty_response_exhausted": (
- "the model returned empty content after retries and any "
- "fallback providers. Try `continue`, switch model/provider, "
- "or inspect the tool output above."
- ),
+ "empty_response_exhausted": EMPTY_RESPONSE_EXPLANATION,
"all_retries_exhausted_no_response": (
- "all API retries were exhausted before a response was "
- "produced (provider errors / rate limits). Try `continue` "
- "or switch provider."
+ "the model provider didn't answer after all retries. "
+ "Send /retry, or switch models with /model."
),
"partial_stream_recovery": (
"streaming stopped early and only a partial response was "
@@ -110,29 +112,20 @@ _PERSISTENCE_CAUSE_EXPLANATIONS: Dict[str, str] = {
"database). Your message should already be saved — "
"please send it again in a moment."
),
+ # The forensic runbook for both (WAL generations, manifest.json, sidecars) lives in the
+ # logger.error at hermes_state.py::_raise_if_db_replaced — never in the chat reply.
"replaced": (
- "the turn was stopped because the state database file "
- "was replaced underneath this process. Do not run "
- "`hermes doctor --fix` or in-place FTS repair — stop "
- "the process, restore the intended state.db, then "
- "restart. Unwritten messages were diverted to "
- "sessions/<session_id>.jsonl and, on the gateway, "
- "pending_messages/pending-*.json."
+ "the session database file was replaced while Hermes was running, so this "
+ "message was not saved (a copy is kept in {home}/sessions/). Stop Hermes "
+ "(`hermes gateway stop`), run `hermes doctor` — not `hermes doctor --fix`, which "
+ "would repair the wrong file in place — then start it again and send your message "
+ "once more. Advanced recovery steps are in the log."
),
"deleted_wal": (
- "the turn was stopped because a live Hermes process held a retired "
- "state.db-wal generation after its pathname was deleted or "
- "replaced. Stop the gateway, dashboard, and cron writers; "
- "do not overwrite the current state.db or delete its sidecars. "
- "Check the logs for whether Hermes captured the retired generation, "
- "then read the adjacent state.db.retired-wal-*/manifest.json. If "
- "manifest.main.mode is `copied`, inspect that artifact with `hermes "
- "sessions recover --source <state.db.retired-wal-*/state.db> "
- "--inspect-only` before deciding whether its committed frames belong "
- "on the current database. A `header_only` artifact is forensic and "
- "does not contain a copied state.db to inspect. Unwritten messages "
- "were diverted to sessions/<session_id>.jsonl and, on the gateway, "
- "pending_messages/pending-*.json."
+ "the session database was changed or replaced while Hermes was running, so this "
+ "message was not saved (a copy is kept in {home}/sessions/). Stop Hermes "
+ "(`hermes gateway stop`), run `hermes doctor`, then start it again and send your "
+ "message once more. Advanced recovery steps are in the log."
),
"corrupt": (
"the turn was stopped because the state database "
@@ -162,18 +155,16 @@ _PERSISTENCE_CAUSE_EXPLANATIONS: Dict[str, str] = {
"send your message again."
),
"disk": (
- "the turn was stopped because session storage could not "
- "be written (the transcript would have been lost on "
- "restart). This is often a full disk — free some space "
- "(or fix state.db permissions), then send your message "
- "again."
+ "Hermes couldn't save this conversation to disk, so it stopped rather than lose "
+ "your messages. The disk is probably full: free some space (or fix the permissions "
+ "on {home}/state.db), then send your message again."
),
}
_PERSISTENCE_DEFAULT_EXPLANATION = (
- "the turn was stopped because session storage could not be "
- "written (the transcript would have been lost on restart). "
- "Check the state database health (`hermes doctor`), then "
- "send your message again."
+ "Hermes couldn't save this conversation, so it stopped rather than lose your messages. "
+ "Possible causes: the drive is out of room, or another Hermes process is holding the "
+ "database. Close other Hermes windows, run `hermes doctor` to check storage, then send "
+ "your message again."
)
@@ -306,7 +297,7 @@ class TurnExplainersMixin:
@staticmethod
def _format_turn_completion_explanation(
- turn_exit_reason: str, persistence_cause: Optional[str] = None, db_path=None
+ turn_exit_reason: str, persistence_cause: Optional[str] = None, db_path=None, model: str = "",
) -> str:
"""User-facing explanation for an abnormal turn ending, or "" for normal / unknown reasons.
@@ -324,10 +315,14 @@ class TurnExplainersMixin:
if reason.startswith(prefix):
body = text
break
+ if body is not None and "{model}" in body:
+ body = body.format(model=model or "The model")
if body is None and reason == "session_persistence_failed":
+ from hermes_constants import display_hermes_home
+
body = _PERSISTENCE_CAUSE_EXPLANATIONS.get(
persistence_cause or "unknown", _PERSISTENCE_DEFAULT_EXPLANATION
- )
+ ).replace("{home}", display_hermes_home())
if persistence_cause in ("corrupt", "fts_index"):
# Copy-pasteable, so name the store that actually failed and pin the profile:
# a multi-profile backend (Desktop serve) hosts sessions whose state.db is NOT
diff --git a/agent/turn_facade_lease.py b/agent/turn_facade_lease.py
index 9ae9c93a02e..d15727d8885 100644
--- a/agent/turn_facade_lease.py
+++ b/agent/turn_facade_lease.py
@@ -334,9 +334,12 @@ def _lease_not_acquired_result(agent, session_id: str, conversation_history) ->
agent._emit_warning(timeout_msg)
except Exception:
logger.debug("Failed to emit session turn lease timeout warning", exc_info=True)
+ # Stamped so Desktop/TUI show "session busy, send again" instead of code="unknown".
return {
"final_response": timeout_msg,
**base,
"failed": True,
"error": f"session_turn_lease_timeout:{session_id}",
+ "failure_reason": "session_busy",
+ "failure_retryable": True,
}
diff --git a/agent/turn_failure_copy.py b/agent/turn_failure_copy.py
new file mode 100644
index 00000000000..1b1e894d75c
--- /dev/null
+++ b/agent/turn_failure_copy.py
@@ -0,0 +1,311 @@
+"""User-facing copy and ``failure_reason`` stamping for terminal failed-turn results.
+
+Every terminal result dict the turn loop returns must carry ``failure_reason`` (a
+``FailoverReason`` value or one of :data:`SITE_FAILURE_CODES`) and ``failure_retryable`` so
+``agent/error_surface.py`` yields a specific descriptor instead of ``unknown``. The copy
+tables here say WHAT happened and WHAT TO DO in plain words; raw provider detail rides a
+trailing "Provider said:" / "Details:" line.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict, NamedTuple, Optional, Tuple
+
+from agent.error_classifier import FailoverReason
+from hermes_constants import display_hermes_home
+
+# Failure codes minted by loop sites that are not provider verdicts (see module docstring).
+SITE_FAILURE_CODES = frozenset({
+ "context_overflow", "truncated", "invalid_response", "empty_response", "loop_error",
+ "interpreter_shutdown", "session_busy",
+})
+
+
+def stamp_failure(result: Dict[str, Any], reason: str, retryable: bool) -> Dict[str, Any]:
+ """Stamp the UI verdict fields on a terminal result (in place; returns it)."""
+ result["failure_reason"] = reason
+ result["failure_retryable"] = bool(retryable)
+ return result
+
+
+def provider_label_for(provider: Any) -> str:
+ """Human-friendly provider name for chat copy (``"OpenRouter"``, ``"Nous Portal"``…)."""
+ from hermes_cli.models import provider_label
+
+ return provider_label(str(provider or ""))
+
+
+# ---- turn_exit_reason → failure verdict (finalize_turn stamps these) --------------------------
+
+class ExitFailure(NamedTuple):
+ """Verdict for a loop exit. ``fails_turn`` False = advisory: the descriptor fields are
+ stamped so Desktop/TUI show a specific code, but ``failed``/``completed`` keep the values
+ the loop chose — cron silence, the kanban dispatcher breaker and gateway transcript
+ persistence all key on ``failed`` and must not change because a code was added."""
+
+ reason: str
+ retryable: bool
+ fails_turn: bool = True
+
+
+# (exit-reason prefix, failure_reason, retryable, fails_turn). Prefix match: several reasons
+# carry a parenthesised detail (``local_processing_error(...)``).
+_EXIT_REASON_FAILURES: Tuple[Tuple[str, str, bool, bool], ...] = (
+ # Advisory: the reasoning-only text may literally be the answer, and cron stays silent.
+ ("empty_response_exhausted", "empty_response", True, False),
+ ("all_retries_exhausted_no_response", FailoverReason.server_error.value, True, True),
+ ("interpreter_shutdown", "interpreter_shutdown", False, True),
+ # Advisory: a deterministic local bug is not a task failure for the kanban breaker.
+ ("local_processing_error", "loop_error", False, False),
+ ("repeated_outer_errors", "loop_error", True, True),
+ ("error_near_max_iterations", "loop_error", True, True),
+ ("context_compression_timeout", "context_overflow", False, True),
+ ("context_compression_exhausted", "context_overflow", False, True),
+ ("ollama_runtime_context_too_small", "context_overflow", False, True),
+ # Advisory: the loop ends these as an incomplete (not failed) turn with an explainer.
+ ("redirect_restart_limit_exceeded", "loop_error", True, False),
+ ("rebuilt_restart_limit_exceeded", "loop_error", True, False),
+)
+
+
+# Provider error code carried inside an HTTP-200 body → classifier reason.
+_INVALID_RESPONSE_CODES: Dict[int, str] = {
+ 429: FailoverReason.rate_limit.value,
+ 500: FailoverReason.server_error.value, 502: FailoverReason.server_error.value,
+ 503: FailoverReason.overloaded.value, 529: FailoverReason.overloaded.value,
+ 504: FailoverReason.timeout.value, 524: FailoverReason.timeout.value,
+}
+
+
+def invalid_response_failure_reason(response: Any) -> str:
+ """``failure_reason`` for an empty/malformed HTTP-200 body: the embedded provider error
+ code when there is one (so the desktop shows Retry + Switch provider consistently), else
+ the ``invalid_response`` site code."""
+ err = getattr(response, "error", None) if response is not None else None
+ code = getattr(err, "code", None) if err is not None else None
+ if code is None and isinstance(err, dict):
+ code = err.get("code")
+ try:
+ return _INVALID_RESPONSE_CODES.get(int(code), "invalid_response") if code is not None else "invalid_response"
+ except (TypeError, ValueError):
+ return "invalid_response"
+
+
+def exit_reason_failure(turn_exit_reason: Any) -> Optional[ExitFailure]:
+ """:class:`ExitFailure` for a loop exit that carries a failure verdict, else None."""
+ reason = str(turn_exit_reason or "")
+ for prefix, code, retryable, fails_turn in _EXIT_REASON_FAILURES:
+ if reason.startswith(prefix):
+ return ExitFailure(code, retryable, fails_turn)
+ return None
+
+
+# ---- chat copy tables -----------------------------------------------------------------------
+
+_NEXT_STEPS_RETRY = "Wait a minute and send /retry, or switch models with /model."
+_NEXT_STEPS_LOOP = (
+ "Your message is saved. Send `continue` to try again, or start a new session with /new. "
+ "If it happens again, run `hermes doctor` and share the error details."
+)
+
+# Lead sentence per classifier reason once retries and fallback are exhausted.
+_EXHAUSTED_LEADS: Dict[str, str] = {
+ FailoverReason.rate_limit.value: "{label} rate-limited every one of {attempts} attempts",
+ FailoverReason.upstream_rate_limit.value: "{label} rate-limited every one of {attempts} attempts",
+ FailoverReason.overloaded.value: "{label} reported it was overloaded on all {attempts} attempts",
+ FailoverReason.server_error.value: "{label} returned a server error on all {attempts} attempts",
+ FailoverReason.timeout.value: "{label} didn't respond in time on any of {attempts} attempts",
+}
+_EXHAUSTED_DEFAULT_LEAD = "{label} didn't answer after {attempts} attempts"
+
+# Terminal copy for a non-retryable provider rejection, keyed by classifier reason.
+_NONRETRYABLE_COPY: Dict[str, str] = {
+ FailoverReason.model_not_found.value: (
+ "Model '{model}' isn't available on {label}. Pick a different model with /model "
+ "(or `hermes model` in a terminal).{prefix_hint}"
+ ),
+ FailoverReason.format_error.value: (
+ "{label} rejected this request as malformed, so the model didn't answer. Start a clean "
+ "session with /new or switch models with /model; if it keeps happening, run `hermes doctor`."
+ ),
+ FailoverReason.ssl_cert_verification.value: (
+ "Hermes couldn't verify {label}'s security certificate, so the connection was refused. "
+ "This is usually a corporate proxy or an outdated certificate store on this computer — "
+ "see the terminal or `{home}/logs/agent.log` for the exact fix, or try another provider "
+ "with /model."
+ ),
+ FailoverReason.provider_policy_blocked.value: (
+ "{label}'s account settings don't allow this model for your request, so it didn't "
+ "answer. Check the provider's data/privacy settings, or switch models with /model."
+ ),
+}
+_NONRETRYABLE_DEFAULT_COPY = (
+ "{label} rejected the request and retrying won't help. Pick another model with /model, "
+ "or check the details in `{home}/logs/agent.log`."
+)
+_AUTH_COPY: Dict[str, str] = {
+ "oauth": (
+ "{label} rejected your sign-in, so the model can't be reached. Sign in again: "
+ "`hermes portal` for Nous, `hermes auth add <provider> --type oauth` for other accounts."
+ ),
+ "api_key": (
+ "{label} rejected your API key, so the model can't be reached. Update it in "
+ "Settings → Providers, or run `hermes setup` in a terminal."
+ ),
+}
+
+CONTENT_POLICY_NEXT_STEPS = (
+ "Try rewording your message or removing sensitive attachments, or switch to another "
+ "model with /model."
+)
+
+# ---- one reason → "what happened" gloss, shared by cron, subagent and chat notices ------------
+
+# FailoverReason / site code → one clause (no HTTP codes, no "provider" jargon). ``{subject}``
+# is who was asking ("the job", "it"), ``{possessive}`` its possessive ("the job's", "its").
+# Reasons absent here are NOT provider-shaped; callers fall back to the raw error text.
+FAILURE_CAUSE_GLOSS: Dict[str, str] = {
+ FailoverReason.timeout.value: "the AI model service did not respond in time",
+ FailoverReason.rate_limit.value: "the AI model service was rate-limited (too many requests)",
+ FailoverReason.upstream_rate_limit.value: "the AI model service was rate-limited (too many requests)",
+ FailoverReason.overloaded.value: "the AI model service is overloaded right now",
+ FailoverReason.server_error.value: "the AI model service returned an internal error",
+ FailoverReason.billing.value: "the AI model service says the account's usage or credit limit is reached",
+ # Wire-level billing code (not a FailoverReason) that error_surface routes to the billing layer.
+ "billing_unverified": "the AI model service says the account's usage or credit limit is reached",
+ FailoverReason.auth.value: "the AI model service rejected the sign-in",
+ FailoverReason.auth_permanent.value: "the AI model service rejected the sign-in",
+ FailoverReason.model_not_found.value: "the model {subject} uses was not found at the AI model service",
+ FailoverReason.content_policy_blocked.value: "the AI model service's safety filter rejected the request",
+ "context_overflow": "{possessive} request grew too large for the model",
+ "payload_too_large": "{possessive} request grew too large for the model",
+}
+
+
+def failure_cause_gloss(reason: Any, *, subject: str = "it", possessive: str = "its") -> Optional[str]:
+ """Plain clause for a classified ``failure_reason``; None when the reason has no gloss."""
+ template = FAILURE_CAUSE_GLOSS.get(str(reason or ""))
+ return template.format(subject=subject, possessive=possessive) if template else None
+
+
+# ---- site-code copy -------------------------------------------------------------------------
+
+# Chat copy for the codes in SITE_FAILURE_CODES that a loop site renders itself
+# (``empty_response`` is worded by agent/turn_explainers.py, ``session_busy`` by the lease).
+_FAILURE_CODE_COPY: Dict[str, str] = {
+ "context_overflow": (
+ "This conversation has grown too long for {model} to read, and Hermes couldn't shrink "
+ "it enough automatically. Start a new session with /new (your history is kept), or try "
+ "/compress once more. Switching to a model with a bigger context window also works."
+ ),
+ "truncated": (
+ "The model's reply was cut off before it finished (it hit its output length limit), so "
+ "Hermes didn't run the incomplete action. Nothing was changed. Send `continue`, ask for "
+ "the work in smaller steps, or raise max_tokens for this model."
+ ),
+ "invalid_response": (
+ "{label} sent back an empty or broken reply {attempts} times — it is probably overloaded "
+ "or rate-limiting you. " + _NEXT_STEPS_RETRY + "\n\nDetails: {detail}"
+ ),
+ "loop_error": (
+ "Hermes hit repeated errors and stopped this turn so it wouldn't keep retrying. "
+ + _NEXT_STEPS_LOOP + "\n\nDetails: {detail}"
+ ),
+ "interpreter_shutdown": (
+ "Hermes was shutting down and stopped this turn. Your conversation is saved — reopen "
+ "it{resume} and send your message again."
+ ),
+}
+
+# One-off outcome strings: deterministic loop exits that are NOT failure codes (the result
+# they ride carries a code from the table above, or none at all).
+_ONE_OFF_COPY: Dict[str, str] = {
+ "payload_too_large": (
+ "This conversation (including attachments) has grown too large to send to {model}, and "
+ "Hermes couldn't shrink it enough automatically. Start a new session with /new (your "
+ "history is kept), or try /compress once more."
+ ),
+ "compression_disabled": (
+ "This conversation is too long for {model} and automatic shrinking is turned off in "
+ "your settings (compression.enabled). Run /compress to shrink it now, /new to start "
+ "fresh, or pick a model with a bigger context window."
+ ),
+ "stream_dropped_tool_call": (
+ "The connection to {label} kept dropping while the model was writing a large action, "
+ "so nothing was run. Check your network and send /retry; asking for the file in smaller "
+ "pieces also helps."
+ ),
+ # Rides failure_reason="loop_error" (advisory; the turn is incomplete, not failed).
+ "local_processing_error": (
+ "Hermes hit an internal error while handling the model's reply and stopped this turn. "
+ + _NEXT_STEPS_LOOP + "\n\nDetails: {detail}"
+ ),
+ "reasoning_only": (
+ "⚠️ {model} spent all of its output budget thinking and never wrote an answer. Lower "
+ "its reasoning effort with `/reasoning low`, or switch to a different model with /model. "
+ "Its last thoughts, which may contain the answer:\n\n{preview}"
+ ),
+ "max_iterations_no_summary": (
+ "I ran out of steps for this turn ({limit} tool calls) before finishing, and couldn't "
+ "produce a summary. Send `continue` to keep going, or raise `max_iterations` in your config."
+ ),
+ "nous_rate_limit": (
+ "Wait for the reset and send /retry, or switch models with /model. To avoid waits, add "
+ "a backup provider with `hermes fallback add`."
+ ),
+}
+_SITE_COPY: Dict[str, str] = {**_FAILURE_CODE_COPY, **_ONE_OFF_COPY}
+
+
+def site_copy(code: str, **fields: Any) -> str:
+ """Chat copy for a failure code or one-off loop outcome; unknown fields default to empty strings."""
+ fields.setdefault("home", display_hermes_home())
+ return _SITE_COPY[code].format_map(_Defaults(fields))
+
+
+def exhausted_copy(reason: str, *, label: str, attempts: int, summary: str) -> str:
+ """Chat copy once retries + fallback are exhausted (``max_retries_exhausted_result``)."""
+ lead = _EXHAUSTED_LEADS.get(reason, _EXHAUSTED_DEFAULT_LEAD).format(label=label, attempts=attempts)
+ return (
+ f"{lead} — it looks temporarily unavailable. {_NEXT_STEPS_RETRY} To avoid this in future, "
+ f"add a backup provider with `hermes fallback add`.\n\nProvider said: {summary}"
+ )
+
+
+def nonretryable_copy(
+ classified: Any, *, provider: Any, model: Any, summary: str, prefix_suggestion: Optional[str] = None,
+) -> str:
+ """Chat copy for a terminal non-retryable rejection (auth, model missing, TLS, generic 4xx)."""
+ label = provider_label_for(provider)
+ if getattr(classified, "is_auth", False):
+ from agent.error_surface import auth_kind
+
+ template = _AUTH_COPY[auth_kind(str(provider or ""))]
+ else:
+ template = _NONRETRYABLE_COPY.get(classified.reason.value, _NONRETRYABLE_DEFAULT_COPY)
+ prefix_hint = (
+ f" If you typed the name yourself it may be missing its vendor prefix — did you mean "
+ f"'{prefix_suggestion}'?"
+ if prefix_suggestion else ""
+ )
+ body = template.format(label=label, model=model, home=display_hermes_home(), prefix_hint=prefix_hint)
+ return f"{body}\n\nProvider said: {summary}"
+
+
+def content_policy_copy(*, label: str, summary: str) -> str:
+ return (
+ f"{label}'s safety filter refused this request, so the model didn't answer. "
+ f"{CONTENT_POLICY_NEXT_STEPS}\n\nProvider said: {summary}"
+ )
+
+
+def short_detail(exc: Any, limit: int = 200) -> str:
+ """First line of an exception's text, capped, for a trailing ``Details:`` line."""
+ text = (str(exc) or type(exc).__name__).strip().splitlines()
+ first = text[0] if text else type(exc).__name__
+ return first if len(first) <= limit else first[: limit - 1] + "…"
+
+
+class _Defaults(dict):
+ def __missing__(self, key: str) -> str:
+ return ""
diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.py
index 67a4024de84..65dda75a7bd 100644
--- a/agent/turn_finalizer.py
+++ b/agent/turn_finalizer.py
@@ -12,6 +12,7 @@ from contextlib import suppress
from typing import Any, Callable, List, Optional, Tuple
from agent.codex_responses_adapter import _summarize_user_message_for_log
+from agent.turn_failure_copy import exit_reason_failure, stamp_failure
from agent.context_compressor import _DB_PERSISTED_MARKER
from agent.message_content import flatten_message_text
from agent.message_metadata import append_message, stamp_message_timestamp
@@ -377,6 +378,7 @@ def _explain_abnormal_exit(agent, final_response, _turn_exit_reason, preserved_v
_explanation = agent._format_turn_completion_explanation(
_turn_exit_reason, getattr(agent, "_last_persistence_error_cause", None),
db_path=getattr(getattr(agent, "_session_db", None), "db_path", None),
+ model=str(getattr(agent, "model", "") or ""),
)
if _explanation:
# Replace the bare sentinel; keep a partial fragment and append why.
@@ -451,6 +453,15 @@ def finalize_turn(
logger=logger,
)
+ # Loop exits that are failures in their own right (outer-loop error cap, shutdown, context
+ # that could not be shrunk) carry the verdict the UI descriptor needs; a bare
+ # ``turn_exit_reason`` collapsed to code="unknown", retryable=True on every surface.
+ # Advisory verdicts (``fails_turn=False``) only add the code: ``failed``/``completed`` keep
+ # the loop's values so cron, kanban and transcript persistence behave as before.
+ _exit_failure = None if interrupted else exit_reason_failure(_turn_exit_reason)
+ if _exit_failure is not None and _exit_failure.fails_turn:
+ failed = True
+
completed = (
final_response is not None
and not failed
@@ -578,6 +589,10 @@ def finalize_turn(
)
_cause = getattr(agent, "_last_persistence_error_cause", None)
result["failure_reason"] = "session_persistence_failed:" + (_cause or "unknown")
+ elif _exit_failure is not None:
+ if failed:
+ result["error"] = final_response or str(_turn_exit_reason)
+ stamp_failure(result, _exit_failure.reason, _exit_failure.retryable)
# Cleanup failures are surfaced, but the response is returned either way (#8049).
if _cleanup_errors:
result["cleanup_errors"] = _cleanup_errors
diff --git a/agent/turn_iteration_prep.py b/agent/turn_iteration_prep.py
index 9d7daee131d..7fb1cf19afb 100644
--- a/agent/turn_iteration_prep.py
+++ b/agent/turn_iteration_prep.py
@@ -507,7 +507,7 @@ def apply_retry_restarts(
# All retries may exhaust with `response` still None; break out cleanly.
if response is None:
_turn_exit_reason = "all_retries_exhausted_no_response"
- print(f"{agent.log_prefix}❌ All API retries exhausted with no successful response.")
+ agent._emit_status("❌ The model provider didn't answer after all retries. Send /retry, or switch models with /model.")
agent._persist_session(messages, conversation_history)
return _verdict("break")
return _verdict("fallthrough")
diff --git a/agent/turn_loop_errors.py b/agent/turn_loop_errors.py
index 8ebcb669c60..09f69819360 100644
--- a/agent/turn_loop_errors.py
+++ b/agent/turn_loop_errors.py
@@ -14,6 +14,7 @@ import sys
from typing import Any
from agent.message_metadata import append_message
+from agent.turn_failure_copy import short_detail, site_copy
logger = logging.getLogger("agent.conversation_loop")
@@ -81,7 +82,11 @@ def handle_outer_loop_error(
except Exception:
pass
_turn_exit_reason = "interpreter_shutdown"
- final_response = "Session is shutting down. Your conversation can be resumed with: hermes --resume <session-id>"
+ failed = True
+ _sid = getattr(agent, "session_id", None)
+ final_response = site_copy(
+ "interpreter_shutdown", resume=f" (CLI: `hermes --resume {_sid}`)" if _sid else "",
+ )
return _verdict("break")
# Deterministic local post-processing bugs (traceback via local helpers, never API
@@ -96,9 +101,9 @@ def handle_outer_loop_error(
)
if _is_local_processing_error:
- error_msg = f"Error during local message processing after OpenAI-compatible API call #{api_call_count}: {str(e)}"
+ error_msg = f"Error during local message processing after API call #{api_call_count}: {str(e)}"
else:
- error_msg = f"Error during OpenAI-compatible API call #{api_call_count}: {str(e)}"
+ error_msg = f"Error during API call #{api_call_count}: {str(e)}"
# Honor the _vprint contract: suppress_status_output silences hard failures;
# quiet_mode -q still shows them. Traceback is logged below.
if getattr(agent, "suppress_status_output", False):
@@ -147,15 +152,20 @@ def handle_outer_loop_error(
or api_call_count >= agent.max_iterations - 1
or _outer_error_count >= _outer_error_cap
):
+ # finalize_turn stamps failure_reason=loop_error from the exit reason so the desktop
+ # card stops reading these as "unknown"/retryable. The deterministic local bug keeps
+ # ``failed`` as it was (an incomplete, not failed, turn): flipping it made every such
+ # child run a strike against the kanban dispatcher breaker.
+ detail = short_detail(e)
if _is_local_processing_error:
_turn_exit_reason = f"local_processing_error({error_msg[:80]})"
- final_response = f"I apologize, but I encountered an error while processing the model response: {error_msg}"
+ final_response = site_copy("local_processing_error", detail=detail)
elif _outer_error_count >= _outer_error_cap:
failed = True
_turn_exit_reason = f"repeated_outer_errors({error_msg[:80]})"
- final_response = f"I apologize, but I encountered repeated errors: {error_msg}"
+ final_response = site_copy("loop_error", detail=detail)
else:
_turn_exit_reason = f"error_near_max_iterations({error_msg[:80]})"
- final_response = f"I apologize, but I encountered repeated errors: {error_msg}"
+ final_response = site_copy("loop_error", detail=detail)
return _verdict("break")
return _verdict("fallthrough")
diff --git a/agent/turn_overflow.py b/agent/turn_overflow.py
index c11f783e0f5..29df54a4d63 100644
--- a/agent/turn_overflow.py
+++ b/agent/turn_overflow.py
@@ -25,6 +25,7 @@ from agent.model_metadata import (
get_context_length_from_provider_error, is_output_cap_error,
parse_available_output_tokens_from_error,
)
+from agent.turn_failure_copy import site_copy, stamp_failure
from agent.turn_retry_state import TurnRetryState
from utils import base_url_host_matches
@@ -99,7 +100,7 @@ class _Recovery(OverflowVerdict):
if log:
logger.error(*log)
agent._persist_session(self.messages, self.conversation_history)
- result = {
+ result = stamp_failure({
"final_response": final_response,
"messages": self.messages,
"completed": False,
@@ -107,7 +108,7 @@ class _Recovery(OverflowVerdict):
"error": final_response,
"partial": True,
"failed": True,
- }
+ }, "context_overflow", False)
if compression_exhausted:
# Reuse the gateway's existing context-recovery contract (#98722, salvaged from #98741). The
# bloated transcript remains intact while future input can move to a clean session instead of
@@ -124,7 +125,7 @@ class _Recovery(OverflowVerdict):
return None
if payload_too_large:
return self.fail_turn(
- f"Request payload too large: max compression attempts ({cap}) reached.",
+ site_copy("payload_too_large", model=self.agent.model),
notices=(
f"❌ Max compression attempts ({cap}) reached for payload-too-large error.",
_RETRY_HINT,
@@ -132,7 +133,7 @@ class _Recovery(OverflowVerdict):
log=("%s413 compression failed after %d attempts.", self.agent.log_prefix, cap),
)
return self.fail_turn(
- f"Context length exceeded: max compression attempts ({cap}) reached.",
+ site_copy("context_overflow", model=self.agent.model),
notices=(f"❌ Max compression attempts ({cap}) reached.", _RETRY_HINT),
log=("%sContext compression failed after %d attempts.", self.agent.log_prefix, cap),
)
@@ -268,7 +269,7 @@ def _recover_payload_too_large(st: _Recovery, _retry: TurnRetryState) -> Overflo
return st.done("continue")
return st.fail_turn(
- "Request payload too large (413). Cannot compress further.",
+ site_copy("payload_too_large", model=agent.model),
notices=("❌ Payload too large and cannot compress further.", _RETRY_HINT),
log=("%s413 payload too large. Cannot compress further.", agent.log_prefix),
)
@@ -407,10 +408,10 @@ def _recover_context_length(st: _Recovery, _retry: TurnRetryState, error_msg: st
# Can't compress further and already at minimum tier.
return st.fail_turn(
- f"Context length exceeded ({new_tokens:,} tokens). Cannot compress further.",
+ site_copy("context_overflow", model=agent.model),
notices=(
- "❌ Context length exceeded and cannot compress further.",
- " 💡 The conversation has accumulated too much content. Try /new to start fresh, or /compress to manually trigger compression.",
+ f"❌ The conversation is too long for the model ({new_tokens:,} tokens) and cannot be shrunk further.",
+ _RETRY_HINT,
),
log=("%sContext length exceeded: %s tokens. Cannot compress further.", agent.log_prefix, f"{new_tokens:,}"),
)
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index 9104185887d..a8894656467 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -27,7 +27,12 @@ from agent.message_sanitization import (
close_interrupted_tool_sequence,
)
from agent.thinking_timeout_guidance import build_thinking_timeout_guidance, is_thinking_timeout
+from agent.turn_failure_copy import (
+ CONTENT_POLICY_NEXT_STEPS, content_policy_copy, exhausted_copy, nonretryable_copy, provider_label_for,
+ site_copy, stamp_failure,
+)
from agent.turn_retry_state import TurnRetryState
+from hermes_constants import display_hermes_home
from utils import base_url_host_matches
logger = logging.getLogger("agent.conversation_loop")
@@ -663,11 +668,23 @@ def _welcome_tier_guidance(classified: Any, *, model: Any, in_chat: bool) -> str
# Terminal status label per non-retryable reason (default names the HTTP status).
_NONRETRYABLE_LABELS = {
- FailoverReason.content_policy_blocked: "Provider safety filter blocked this request",
- FailoverReason.ssl_cert_verification: "TLS certificate verification failed",
+ FailoverReason.content_policy_blocked: "The provider's safety filter refused this request",
+ FailoverReason.ssl_cert_verification: "The provider's security certificate could not be verified",
}
+def _missing_vendor_prefix_suggestion(api_error: Exception, provider: Any, model: Any) -> Optional[str]:
+ """Prefixed catalogue id when a bare 404 most likely means ``vendor/model`` lost its prefix."""
+ if getattr(api_error, "status_code", None) != 404:
+ return None
+ try:
+ from hermes_cli.model_normalize import suggest_prefixed_model_id
+
+ return suggest_prefixed_model_id(str(provider or ""), str(model or ""))
+ except Exception:
+ return None
+
+
def nonretryable_client_error_result(
agent: Any, api_error: Exception, classified: Any, *, status_code: Optional[int],
api_kwargs: Any, api_messages: Any, messages: List[Dict[str, Any]], conversation_history: Any,
@@ -677,9 +694,7 @@ def nonretryable_client_error_result(
the retry trace, print auth / billing / content-policy / TLS guidance, persist (skipped
for likely context-overflow 400s so the failure does not grow the session), build result."""
# Result/guidance helpers stay in the loop module (tests import + patch them there).
- from agent.conversation_loop import (
- _CONTENT_POLICY_RECOVERY_HINT, _billing_failure_result, _content_policy_blocked_result,
- )
+ from agent.conversation_loop import _billing_failure_result, _content_policy_blocked_result
if api_kwargs is not None:
agent._dump_api_request_debug(api_kwargs, reason="non_retryable_client_error", error=api_error)
@@ -688,15 +703,18 @@ def nonretryable_client_error_result(
# Summarize once: Cloudflare/proxy HTML pages and raw provider bodies must be
# collapsed here or they leak verbatim via the ``error`` field.
_nonretryable_summary = agent._summarize_api_error(api_error)
- _label = _NONRETRYABLE_LABELS.get(classified.reason, f"Non-retryable error (HTTP {status_code})")
+ _plabel = provider_label_for(provider)
+ _label = _NONRETRYABLE_LABELS.get(classified.reason, f"{_plabel} rejected the request and retrying won't help")
agent._emit_status(f"❌ {_label}: {_nonretryable_summary}")
- _vlines(
- agent,
- f"❌ Non-retryable client error (HTTP {status_code}). Aborting.",
- f" 🔌 Provider: {provider} Model: {model}",
- f" 🌐 Endpoint: {base_url}",
- )
+ # The endpoint/status trace is developer detail: verbose only (the log has it always).
+ if getattr(agent, "verbose_logging", False):
+ _vlines(
+ agent,
+ f" 🔌 Provider: {provider} Model: {model} (HTTP {status_code})",
+ f" 🌐 Endpoint: {base_url}",
+ )
_welcome_hint = _welcome_tier_guidance(classified, model=model, in_chat=False)
+ _prefix_suggestion = _missing_vendor_prefix_suggestion(api_error, provider, model)
if _welcome_hint:
# A free-tier gate or a wrong-host refusal: the way forward is a sign-in or another
# provider, never the key/credits advice below.
@@ -705,28 +723,30 @@ def nonretryable_client_error_result(
_print_nonretryable_auth_guidance(
agent, classified, status_code=status_code, provider=provider, base_url=base_url, model=model
)
- else:
- _vlines(agent, " 💡 This type of error won't be fixed by retrying.")
+ elif classified.reason == FailoverReason.model_not_found:
+ _vlines(agent, f" 💡 Model '{model}' isn't available on {_plabel}. Pick another with /model.")
+ if _prefix_suggestion:
+ _vlines(agent, f" Did you mean '{_prefix_suggestion}'? It looks like the vendor prefix is missing.")
+ elif classified.reason not in _NONRETRYABLE_LABELS:
+ _vlines(agent, f" 💡 Fix: pick another model (/model), or check `{display_hermes_home()}/logs/agent.log`.")
# Content-policy blocks: the provider refused this prompt, so recovery is a rephrase
# or another model, not key/retry advice.
if classified.reason == FailoverReason.content_policy_blocked:
_vlines(
agent,
- " 💡 The provider's safety filter rejected this specific prompt.",
- " • Try rephrasing the request, narrowing the context, or splitting into smaller steps.",
- " • Configure a fallback provider so future blocks route automatically:",
- " hermes fallback add (interactive picker — same as `hermes model`)",
+ f" 💡 {CONTENT_POLICY_NEXT_STEPS}",
+ " To route future blocks to another provider automatically: hermes fallback add",
)
# TLS certificate failures are environment problems — name the knobs for each cause.
if classified.reason == FailoverReason.ssl_cert_verification:
_vlines(
agent,
- " 💡 The TLS certificate chain could not be verified. This fails the same",
+ " 💡 Hermes couldn't verify the provider's security certificate. This fails the same",
" way on every retry — fix the environment, then try again:",
" • Corporate TLS-inspecting proxy? Point Python at its CA bundle:",
" export SSL_CERT_FILE=/path/to/corp-ca.pem (also REQUESTS_CA_BUNDLE)",
- " • Missing/stale system CA store? Install/refresh it:",
- " pip install --upgrade certifi (macOS: run 'Install Certificates.command')",
+ " • Missing/stale system CA store? Refresh it (in Hermes's venv: `uv pip install",
+ " --upgrade certifi`; macOS: run 'Install Certificates.command').",
" • Self-signed local endpoint (llama.cpp, LM Studio, vLLM)? Use http://",
" for localhost, or add the server's cert to your trust store.",
)
@@ -740,14 +760,10 @@ def nonretryable_client_error_result(
else:
agent._persist_session(messages, conversation_history)
if classified.reason == FailoverReason.content_policy_blocked:
- _policy_response = (
- "⚠️ The model provider's safety filter blocked this request "
- "(not a Hermes/gateway failure).\n\n"
- f"Provider message: {_nonretryable_summary}\n\n"
- f"{_CONTENT_POLICY_RECOVERY_HINT}"
- )
return _content_policy_blocked_result(
- messages, api_call_count, final_response=_policy_response, error_detail=_nonretryable_summary,
+ messages, api_call_count,
+ final_response="⚠️ " + content_policy_copy(label=_plabel, summary=_nonretryable_summary),
+ error_detail=_nonretryable_summary,
)
# Billing walls get the same structured recovery descriptor as the max-retries path
# so every surface renders one consistent signal.
@@ -756,9 +772,14 @@ def nonretryable_client_error_result(
classified=classified, summary=_nonretryable_summary, messages=messages,
api_call_count=api_call_count, provider=provider, base_url=base_url, model=model,
)
- _final_response = _nonretryable_summary
if _welcome_hint:
- _final_response += f"\n\n{_welcome_tier_guidance(classified, model=model, in_chat=True)}"
+ _final_response = f"{_nonretryable_summary}\n\n{_welcome_tier_guidance(classified, model=model, in_chat=True)}"
+ else:
+ # Every surface reads final_response; the CLI hint lines above never reach chat.
+ _final_response = nonretryable_copy(
+ classified, provider=provider, model=model, summary=_nonretryable_summary,
+ prefix_suggestion=_prefix_suggestion,
+ )
result = _failed_turn_result(_final_response, messages, api_call_count, _nonretryable_summary)
# Same verdict fields as the max-retries path: without them the UI descriptor
# (agent/error_surface.py) reads a rejected OAuth token as a retryable
@@ -839,18 +860,7 @@ def max_retries_exhausted_result(
# Distinct from _is_stream_drop; detection lives in agent.thinking_timeout_guidance.
_is_thinking_timeout = is_thinking_timeout(classified, model, error_msg)
if _is_thinking_timeout:
- _vlines(
- agent,
- " 💡 The model's thinking phase exceeded the upstream proxy's idle "
- "timeout before the first content token arrived. This is a known issue with "
- "reasoning models behind cloud gateways (NVIDIA NIM, OpenAI, Anthropic, DeepSeek).",
- " Workarounds in priority order:",
- f" 1. Set `providers.{provider}.models.{model}.stale_timeout_seconds: 900` "
- "in `~/.hermes/config.yaml` to extend the per-call timeout. (Hermes's built-in floor is 600s for "
- "known reasoning models — if you still see this after raising, the upstream cap is even shorter.)",
- " 2. Lower `reasoning_budget` or set `reasoning_effort: medium` on this model if the provider supports it.",
- " 3. Use a smaller / faster reasoning model if the task doesn't require deep thinking.",
- )
+ _vlines(agent, f" 💡 {build_thinking_timeout_guidance(provider=provider, model=model).strip()}")
logger.error(
"%sAPI call failed after %s retries. %s | provider=%s model=%s msgs=%s tokens=~%s",
@@ -872,21 +882,23 @@ def max_retries_exhausted_result(
provider, base_url, model, _billing_guidance, unverified=_billing_unverified
)
else:
- _final_response = f"API call failed after {max_retries} retries: {_final_summary}"
+ # Every surface reads final_response (the 💡 lines above are CLI-only), so the chat
+ # text carries the plain what-happened + next step itself.
+ _final_response = exhausted_copy(
+ classified.reason.value, label=provider_label_for(provider), attempts=max_retries,
+ summary=_final_summary,
+ )
if _welcome_hint:
_final_response += f"\n\n{_welcome_tier_guidance(classified, model=model, in_chat=True)}"
if _is_thinking_timeout:
# Thinking-timeout guidance overrides stream-drop guidance, which would wrongly
# suggest splitting large file writes.
- _final_response += build_thinking_timeout_guidance(provider=provider, model=model)
+ _final_response += "\n\n" + build_thinking_timeout_guidance(provider=provider, model=model)
elif _is_stream_drop:
_final_response += (
- "\n\nThe provider's stream connection keeps "
- "dropping — this often happens when generating "
- "very large tool call responses (e.g. write_file "
- "with long content). Try asking me to use "
- "execute_code with Python's open() for large "
- "files, or to write in smaller sections."
+ "\n\nThe connection kept dropping while the model was writing — this often "
+ "happens when it writes a very large file in one go. Ask me to write the file in "
+ "smaller sections (or via execute_code with Python's open())."
)
result = _failed_turn_result(_final_response, messages, api_call_count, _final_summary)
result.update({
@@ -921,20 +933,21 @@ def log_api_error_attempt(
_provider = getattr(agent, "provider", "unknown")
_base = getattr(agent, "base_url", "unknown")
_model = getattr(agent, "model", "unknown")
- _status_code_str = f" [HTTP {status_code}]" if status_code else ""
- _blines(
- agent,
- f"⚠️ API call failed (attempt {retry_count}/{max_retries}): {error_type}{_status_code_str}",
- f" 🔌 Provider: {_provider} Model: {_model}",
- f" 🌐 Endpoint: {_base}",
- f" 📝 Error: {_error_summary}",
- )
- if status_code and status_code < 500:
- _err_body = getattr(api_error, "body", None)
- _err_body_str = str(_err_body)[:300] if _err_body else None
- if _err_body_str:
- _blines(agent, f" 📋 Details: {_err_body_str}")
- _blines(agent, f" ⏱️ Elapsed: {elapsed_time:.2f}s Context: {len(api_messages)} msgs, ~{approx_tokens:,} tokens")
+ _blines(agent, f"⚠️ Attempt {retry_count}/{max_retries} failed: {_error_summary}")
+ # Exception class, endpoint, raw body and token counts are developer detail: verbose only.
+ if getattr(agent, "verbose_logging", False):
+ _status_code_str = f" [HTTP {status_code}]" if status_code else ""
+ _blines(
+ agent,
+ f" 🔌 {error_type}{_status_code_str} Provider: {_provider} Model: {_model}",
+ f" 🌐 Endpoint: {_base}",
+ )
+ if status_code and status_code < 500:
+ _err_body = getattr(api_error, "body", None)
+ _err_body_str = str(_err_body)[:300] if _err_body else None
+ if _err_body_str:
+ _blines(agent, f" 📋 Details: {_err_body_str}")
+ _blines(agent, f" ⏱️ Elapsed: {elapsed_time:.2f}s Context: {len(api_messages)} msgs, ~{approx_tokens:,} tokens")
if agent._is_openrouter_url() and "support tool use" in error_msg:
_blines(agent, f" 💡 No OpenRouter providers for {_model} support tool calling with your current settings.")
@@ -949,19 +962,13 @@ def log_api_error_attempt(
# Bare 404 on a ``vendor/model`` catalogue usually means the id lost its prefix; the
# provider never names the model, so we do.
- if getattr(api_error, "status_code", None) == 404:
- try:
- from hermes_cli.model_normalize import suggest_prefixed_model_id
-
- _suggestion = suggest_prefixed_model_id(_provider, _model)
- except Exception:
- _suggestion = None
- if _suggestion:
- _blines(
- agent,
- f" 💡 Model '{_model}' is not a valid id for provider {_provider} — it is missing its vendor prefix.",
- f" Did you mean '{_suggestion}'? Re-pick it with `hermes model`.",
- )
+ _suggestion = _missing_vendor_prefix_suggestion(api_error, _provider, _model)
+ if _suggestion:
+ _blines(
+ agent,
+ f" 💡 Model '{_model}' is not a valid id for provider {_provider} — it is missing its vendor prefix.",
+ f" Did you mean '{_suggestion}'? Re-pick it with /model.",
+ )
return error_type, error_msg, _provider, _base, _model
@@ -1363,25 +1370,21 @@ def route_classified_error(
agent._flush_status_buffer()
_vlines(
agent,
- "❌ Context overflow, but auto-compaction is disabled (compression.enabled: false).",
- " 💡 Run /compress to compact manually, /new to start fresh, "
- "switch to a larger-context model, or reduce attachments.",
+ "❌ The conversation is too long for the model and automatic shrinking is off (compression.enabled: false).",
+ " 💡 Run /compress to shrink it now, /new to start fresh, "
+ "pick a model with a bigger context window, or remove attachments.",
)
logger.error(
f"{agent.log_prefix}Context overflow ({classified.reason.value}) with "
f"auto-compaction disabled — not compressing."
)
agent._persist_session(messages, conversation_history)
- _final_response = (
- "Context overflow and auto-compaction is disabled "
- "(compression.enabled: false). Run /compress to compact manually, "
- "/new to start fresh, or switch to a larger-context model."
- )
- return _verdict("return", {
+ _final_response = site_copy("compression_disabled", model=agent.model)
+ return _verdict("return", stamp_failure({
"final_response": _final_response, "messages": messages, "completed": False,
"api_calls": api_call_count, "error": _final_response, "partial": True, "failed": True,
"compaction_disabled": True,
- })
+ }, "context_overflow", False))
# Anthropic 429 "Extra usage is required for long context requests" is a
# subscription-tier limit, not transient: cap at 200k and compress.
diff --git a/agent/turn_response_check.py b/agent/turn_response_check.py
index a0847ae1cbe..cd63090a410 100644
--- a/agent/turn_response_check.py
+++ b/agent/turn_response_check.py
@@ -14,6 +14,7 @@ import time
from typing import Any, Dict, Optional
from agent.turn_api_call import stop_thinking_spinner
+from agent.turn_failure_copy import invalid_response_failure_reason, provider_label_for, site_copy, stamp_failure
from agent.turn_truncation import handle_content_policy_refusal, recover_from_truncation
from agent.turn_usage import record_response_usage
@@ -287,15 +288,23 @@ def retry_invalid_response(
agent._emit_status(f"❌ Max retries ({max_retries}) exceeded for invalid responses. Giving up.")
logger.error("%sInvalid API response after %d retries.", agent.log_prefix, max_retries)
agent._persist_session(messages, conversation_history)
- _final_response = f"Invalid API response after {max_retries} retries: {_failure_hint}"
- return _verdict("return", {
+ # "model=<id>" is describe_invalid_response's OpenRouter fallback, not a provider name.
+ _label = (
+ provider_label_for(agent.provider)
+ if provider_name in ("Unknown", "") or provider_name.startswith("model=")
+ else provider_name
+ )
+ _final_response = site_copy(
+ "invalid_response", label=_label, attempts=max_retries, detail=_failure_hint,
+ )
+ return _verdict("return", stamp_failure({
"final_response": _final_response,
"messages": messages,
"completed": False,
"api_calls": api_call_count,
- "error": _final_response,
+ "error": f"Invalid API response after {max_retries} retries: {_failure_hint}",
"failed": True,
- })
+ }, invalid_response_failure_reason(response), True))
wait_time = jittered_backoff(retry_count, base_delay=5.0, max_delay=120.0)
agent._buffer_vprint(f"⏳ Retrying in {wait_time:.1f}s ({_failure_hint})...")
diff --git a/agent/turn_tool_validation.py b/agent/turn_tool_validation.py
index db3e89334eb..56d8154bc03 100644
--- a/agent/turn_tool_validation.py
+++ b/agent/turn_tool_validation.py
@@ -16,6 +16,7 @@ from typing import Any, Dict, List, Optional
from agent.message_metadata import append_message
from agent.message_sanitization import close_interrupted_tool_sequence, coalesce_tool_call_id
+from agent.turn_failure_copy import site_copy, stamp_failure
logger = logging.getLogger("agent.conversation_loop")
@@ -56,14 +57,14 @@ def _partial_exit(agent, messages, conversation_history, api_call_count, final_r
This path never reaches finalize_turn, so persist here."""
close_interrupted_tool_sequence(messages, final_response)
agent._persist_session(messages, conversation_history)
- return {
+ return stamp_failure({
"final_response": final_response,
"messages": messages,
"api_calls": api_call_count,
"completed": False,
"partial": True,
"error": final_response,
- }
+ }, "truncated", True)
def validate_tool_calls(
@@ -176,8 +177,7 @@ def validate_tool_calls(
agent._invalid_json_retries = 0
agent._cleanup_task_resources(effective_task_id)
return _verdict("return", _partial_exit(
- agent, messages, conversation_history, api_call_count,
- "Response truncated due to output length limit",
+ agent, messages, conversation_history, api_call_count, site_copy("truncated"),
))
agent._invalid_json_retries += 1
diff --git a/agent/turn_truncation.py b/agent/turn_truncation.py
index 335cb1c3c79..5e806746bb5 100644
--- a/agent/turn_truncation.py
+++ b/agent/turn_truncation.py
@@ -12,13 +12,14 @@ from __future__ import annotations
import logging
import re
from dataclasses import dataclass
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Optional, Tuple
from agent.error_classifier import FailoverReason
from agent.message_metadata import append_message
from agent.message_sanitization import close_interrupted_tool_sequence
from agent.repetition_guard import is_repetition_dominated
from agent.turn_api_call import stop_thinking_spinner
+from agent.turn_failure_copy import content_policy_copy, provider_label_for, site_copy, stamp_failure
from agent.turn_retry_state import TurnRetryState
from agent.usage_pricing import normalize_usage
from hermes_constants import PARTIAL_STREAM_STUB_ID
@@ -27,8 +28,8 @@ logger = logging.getLogger("agent.conversation_loop")
_CONTINUABLE_MODES = {"chat_completions", "bedrock_converse", "anthropic_messages"}
_THINK_TAG_RE = re.compile(r'<(?:think|thinking|reasoning|REASONING_SCRATCHPAD)[^>]*>', re.IGNORECASE)
-_TRUNCATED_FINAL = "Response truncated due to output length limit"
-_FIRST_TRUNCATED_FINAL = "First response truncated due to output length limit"
+_TRUNCATED_FINAL = site_copy("truncated")
+_FIRST_TRUNCATED_FINAL = _TRUNCATED_FINAL
# #106260: a stream that died on a context-overflow error after partial delivery must not seed a
# continuation — the transcript already cannot fit, and appending the partial stub grows every
# later request into the same overflow. End the turn via the recovery contract instead.
@@ -157,20 +158,22 @@ class _Trunc(TruncationVerdict):
self, final_response: str, error: Optional[str] = None, *,
result_messages: Optional[List[Dict[str, Any]]] = None, cleanup: bool = True,
failed: bool = False, compression_exhausted: bool = False,
+ failure: Tuple[str, bool] = ("truncated", True),
) -> TruncationVerdict:
"""Persist and end the turn as partial (or ``failed``).
``compression_exhausted`` forwards the #98722 typed bit so the gateway can
- move future input off a bloated session (run_turn.py consumes it).
+ move future input off a bloated session (run_turn.py consumes it). ``failure`` is
+ the ``(failure_reason, retryable)`` verdict for the UI descriptor.
"""
agent = self.agent
if cleanup:
agent._cleanup_task_resources(self.effective_task_id)
agent._persist_session(self.messages, self.conversation_history)
- return self.done("return", partial_result(
+ return self.done("return", stamp_failure(partial_result(
self.messages if result_messages is None else result_messages, self.api_call_count,
final_response, error, failed=failed, compression_exhausted=compression_exhausted,
- ))
+ ), *failure))
@property
def is_stub(self) -> bool:
@@ -334,7 +337,7 @@ def _retry_truncated_tool_call(st: _Trunc, api_kwargs: Any) -> TruncationVerdict
f"{agent.log_prefix}⚠️ Stream kept dropping mid tool-call after 4 retries — the action was not executed.",
force=True,
)
- _final_response = "Stream repeatedly dropped mid tool-call (network); the tool was not executed"
+ _final_response = site_copy("stream_dropped_tool_call", label=provider_label_for(agent.provider))
else:
agent._vprint(
f"{agent.log_prefix}⚠️ Truncated tool call response detected again — refusing to execute incomplete tool arguments.",
@@ -344,7 +347,10 @@ def _retry_truncated_tool_call(st: _Trunc, api_kwargs: Any) -> TruncationVerdict
agent._cleanup_task_resources(st.effective_task_id)
# Prior tool batches can leave a tool-result tail; this path never reaches finalize_turn.
close_interrupted_tool_sequence(st.messages, _final_response)
- return st.end_turn(_final_response, cleanup=False)
+ return st.end_turn(
+ _final_response, cleanup=False,
+ failure=(FailoverReason.timeout.value if st.is_stub else "truncated", True),
+ )
def recover_from_truncation(
@@ -403,6 +409,7 @@ def recover_from_truncation(
error=_CONTEXT_OVERFLOW_PARTIAL_FINAL,
failed=True,
compression_exhausted=True,
+ failure=("context_overflow", False),
)
_trunc_msg = normalize_response_for_agent(agent, response)
@@ -557,9 +564,7 @@ def handle_content_policy_refusal(
"""HTTP-200 refusal (``finish_reason`` ``content_filter`` / ``guardrail_intervened``).
Deterministic for the unchanged prompt — never retried: one configured-fallback try,
else surface the refusal (explanation may live only in the reasoning channel)."""
- from agent.conversation_loop import (
- _CONTENT_POLICY_RECOVERY_HINT, _arm_fallback_restart, _content_policy_blocked_result
- )
+ from agent.conversation_loop import _arm_fallback_restart, _content_policy_blocked_result
_refusal_result = normalize_response_for_agent(agent, response)
_refusal_text = (getattr(_refusal_result, "content", None) or "").strip()
@@ -590,13 +595,9 @@ def handle_content_policy_refusal(
_refusal_log or "(no text)",
)
agent._emit_status("⚠️ The model declined to respond to this request (safety refusal).")
- _refusal_detail = (
- f"Model's explanation: {_refusal_text}" if _refusal_text else "The model returned no explanation."
- )
- _refusal_response = (
- "⚠️ The model declined to respond to this request (safety refusal — not a Hermes/gateway failure).\n\n"
- f"{_refusal_detail}\n\n"
- f"{_CONTENT_POLICY_RECOVERY_HINT}"
+ _refusal_response = "⚠️ " + content_policy_copy(
+ label=provider_label_for(agent.provider),
+ summary=_refusal_text or "the model returned no explanation",
)
agent._cleanup_task_resources(effective_task_id)
agent._persist_session(messages, conversation_history)
diff --git a/cli.py b/cli.py
index 53dba6825cd..3e0f3723754 100644
--- a/cli.py
+++ b/cli.py
@@ -2860,18 +2860,21 @@ class HermesCLI(CLIProcessNotificationsMixin, CLIAgentSetupMixin, CLICommandsMix
# the store before relying on resume.
self._session_db_unavailable = True
logger.warning("Failed to initialize SessionDB — session will NOT be indexed for search: %s", e)
+ from hermes_state_user_copy import describe_storage_failure, storage_failure_details
+ failure = describe_storage_failure(e)
try:
Console(stderr=True).print(
"[bold yellow]⚠ Session store unavailable[/bold yellow] — "
- "this conversation will [bold]NOT be saved[/bold] to disk and "
- "cannot be resumed later. Searching past sessions is also disabled.\n"
- f" Reason: {e}\n"
- " Fix the state.db store (e.g. `hermes update` to rebuild the venv) to restore persistence."
+ "this conversation will [bold]NOT be saved[/bold] and cannot be resumed later. "
+ "Searching past sessions is also disabled.\n"
+ f" Reason: {failure.gloss}.\n"
+ f" {failure.action}\n"
+ f" [dim]Details: {storage_failure_details(e)}[/dim]"
)
except Exception:
print(
"WARNING: Session store unavailable — this conversation will NOT be "
- f"saved to disk and cannot be resumed later. Reason: {e}"
+ f"saved and cannot be resumed later. Reason: {failure.gloss}. {failure.action}"
)
_run_state_db_auto_maintenance(self._session_db)
_run_checkpoint_auto_maintenance()
@@ -3110,19 +3113,30 @@ class HermesCLI(CLIProcessNotificationsMixin, CLIAgentSetupMixin, CLICommandsMix
self.preloaded_skills += [name for name in loaded_skills if name not in self.preloaded_skills]
def _show_tool_availability_warnings(self):
- """Warn about tools disabled by missing API keys (not system deps)."""
+ """Warn about toolsets switched off at startup (missing API keys, unusable terminal backend)."""
try:
+ # Runs on a daemon thread on the snapshot fast path: keep the imports to modules the
+ # registry walk already loaded plus the pure notices module (a heavy import here races
+ # importlib's module locks against the main thread).
from model_tools import check_tool_availability
-
- available, unavailable = check_tool_availability()
- api_key_missing = [u for u in unavailable if u["missing_vars"]]
-
- if api_key_missing:
+ from hermes_cli.tool_availability_notices import (
+ current_terminal_backend, filter_to_enabled_toolsets, tool_availability_warning_lines,
+ )
+ from tools.terminal_tool import terminal_backend_unavailable_reason
+ from toolsets import resolve_toolset
+
+ _, unavailable = check_tool_availability()
+ # Only toolsets this CLI session actually has. The selection is usually a composite bundle
+ # (``hermes-cli``), so expand it to tool names before matching — a raw name comparison
+ # matched nothing on a default install and silently dropped the terminal notice.
+ unavailable = filter_to_enabled_toolsets(unavailable, self.enabled_toolsets or [], resolve_toolset)
+ lines = tool_availability_warning_lines(
+ unavailable, terminal_reason=terminal_backend_unavailable_reason(),
+ terminal_backend=current_terminal_backend())
+ if lines:
self._console_print()
- self._console_print("[yellow]⚠️ Some tools disabled (missing API keys):[/]")
- for item in api_key_missing:
- self._console_print(f" [dim]• {item['name']}[/] [dim italic]({', '.join(item['missing_vars'])})[/]")
- self._console_print("[dim] Run 'hermes setup' to configure[/]")
+ for line in lines:
+ self._console_print(line)
except Exception:
pass
@@ -3398,8 +3412,10 @@ class HermesCLI(CLIProcessNotificationsMixin, CLIAgentSetupMixin, CLICommandsMix
_cprint(f"{_DIM}Did you mean: {', '.join(sorted(matches))}?{_RST}")
else:
# Exact token with no handler (never re-dispatch the same token: recursion), or no match.
- _cprint(f"\033[1;31mUnknown command: {cmd_lower}{_RST}")
- _cprint(f"{_DIM}{_ACCENT}Type /help for available commands{_RST}")
+ from hermes_cli.cli_unknown_command import unknown_command_lines
+ lead, pointer = unknown_command_lines(cmd_lower, all_known)
+ _cprint(f"\033[1;31m{lead}{_RST}")
+ _cprint(f"{_DIM}{_ACCENT}{pointer}{_RST}")
return True
def _drain_interrupt_queue_to_pending_input(self) -> None:
diff --git a/cron/scheduler.py b/cron/scheduler.py
index 52ee342b62c..e47a517ff56 100644
--- a/cron/scheduler.py
+++ b/cron/scheduler.py
@@ -99,19 +99,20 @@ def _set_cron_session_title(session_db, session_id, base_title):
def _fallback_chain_phrase() -> str:
- """Fallback-chain clause for a provider-failure message: "exhausted" vs "none configured" (most
- installs). Fails open to the ambiguous wording if config can't be read — never crash delivery.
+ """Backup-provider clause for a provider-failure notice: "the backups failed too" vs "none
+ configured" (most installs). Fails open to the former if config can't be read — never crash
+ delivery.
"""
try:
cfg = load_config() or {}
chain = get_fallback_chain(cfg)
except Exception:
- return "Fallback chain was exhausted or unavailable."
+ return "No backup provider succeeded either."
if chain:
- return "Fallback chain was exhausted or unavailable."
+ return "No backup provider succeeded either."
return (
- "No fallback chain configured — add one with `hermes fallback add`, "
- "or set a cron fleet default via `cron.model` + `cron.model_provider` in config.yaml."
+ "No backup provider is configured — add one with `hermes fallback add`, "
+ "or set a cron-wide default via `cron.model` + `cron.model_provider` in config.yaml."
)
@@ -216,100 +217,57 @@ def _log_tick_yield_once(reason: str) -> None:
def _summarize_cron_failure_for_delivery(job: dict, error: str | None) -> str:
- """Compact one-line failure message for chat delivery (full details stay in cron output)."""
+ """One-line failure notice for chat delivery (full details stay in the run output).
+
+ Deterministic scheduler/script shapes are matched first (their text can contain "timed out"
+ and would otherwise be blamed on the model service); everything else goes through the shared
+ ``classify_api_error`` verdict and the copy table in ``scheduler_failure_copy``."""
+ from cron.scheduler_failure_copy import (
+ classify_cron_failure_reason, generic_failure_notice, inactivity_notice,
+ provider_failure_notice, script_timeout_notice)
+
job_name = job.get("name") or job.get("id") or "cron job"
+ job_id = job.get("id") or job_name
text = (error or "unknown error").strip()
lower = text.lower()
- # no_agent jobs never reach a model, so provider errors are structurally impossible for them.
- # Gate on job MODE before substring matching, or a script's own wording ("timed out", "429")
- # would blame the wrong subsystem; the generic cleaner below reports what actually happened.
- provider_reachable = not job.get("no_agent")
-
# Script runner contract ("Script timed out after {n}s: {path}") — also for agent jobs with a
- # context script. Must precede generic timeout matching so it never claims a provider fallback.
+ # context script. Must precede provider classification so it never claims a model failure.
# See #78503, #82460.
if lower.startswith("script timed out"):
- return (
- f"⚠️ Cron '{job_name}' failed: script timed out. "
- "No model was invoked. Full details saved in cron output."
- )
-
- # Whole-token 429: substrings in job ids/ports/hashes tripped false rate-limit alerts.
- if provider_reachable and (
- # Provider/API failures are the common noisy path. Keep these short. Match 429 as a whole token
- # (#83188 @cation98): bare substring matching let identifiers containing those digits (job ids,
- # ports, hashes) trip a false "provider rate limit" alert.
- re.search(r"\b429\b", text) or "rate limit" in lower or "usage limit" in lower
- ):
- reason = "rate limit"
- if "weekly usage limit" in lower:
- reason = "weekly usage limit"
- elif "quota" in lower:
- reason = "quota limit"
- return (
- f"⚠️ Cron '{job_name}' failed: provider {reason}. "
- f"{_fallback_chain_phrase()} "
- "Full details saved in cron output."
- )
+ return script_timeout_notice(job_name, job_id)
- # Scheduler inactivity watchdog shape ("idle for {n}s (limit {m}s)"). Must precede the generic
- # provider-timeout branch: the job's own tool going quiet involves no provider/fallback chain.
- # The scheduler's own inactivity watchdog (see the TimeoutError raised above at "Cron job '{job_name}'
- # idle for {secs}s (limit {limit}s) — last activity: {desc}") produces a message that contains the
- # substring "timed out"/"timeout" nowhere, but DOES contain "idle for ... (limit ...)" — however
- # older/other call sites can still phrase an inactivity abort using "timed out" wording, so match on the
- # "idle for Ns (limit" shape specifically (case-insensitive) BEFORE the generic provider- timeout branch
- # below. Without this, an inactivity timeout — the job's OWN tool call/turn going quiet, no provider or
- # fallback chain ever involved — gets rewritten into a misleading "provider timeout / fallback chain
- # exhausted" message, sending the operator to debug the wrong system entirely (field-reported: a stuck
- # `terminal` tool call tripped the 600s inactivity limit and was reported as a provider/fallback
- # failure). Mirrors the same reordering fix upstream issue #59549 applied for script timeouts vs
- # provider timeouts — check the more specific, deterministic signature first.
+ # Scheduler inactivity watchdog ("idle for {n}s (limit {m}s)"): the job's OWN tool call went
+ # quiet, no model service involved. Its text may still contain "timed out", so it must be
+ # recognised before the classifier (field-reported: a stuck `terminal` call was blamed on the
+ # provider and the operator debugged the wrong system).
if re.search(r"idle for \d+s\s*\(limit \d+s\)", lower):
- return (
- f"⚠️ Cron '{job_name}' failed: the job itself stalled — no tool/API "
- "activity for the configured inactivity window. Not a provider or "
- "fallback-chain issue; check what the job was doing when it went "
- "quiet. Full details saved in cron output."
- )
+ return inactivity_notice(job_name, job_id)
- if provider_reachable and (
- "readtimeout" in lower or "timed out" in lower or "timeout" in lower
- ):
- return (
- f"⚠️ Cron '{job_name}' failed: provider timeout. "
- f"{_fallback_chain_phrase()} "
- "Full details saved in cron output."
- )
-
- # Whole-token 401/403 and auth wording so "oauth", "4015" etc. don't trip a false auth message.
- if provider_reachable and (
- re.search(r"authenticat|authoriz", lower) or re.search(r"\b(401|403)\b", text)
- ):
- return (
- f"⚠️ Cron '{job_name}' failed: provider authentication error. "
- "Full details saved in cron output."
- )
+ # no_agent jobs never reach a model, so provider errors are structurally impossible for them:
+ # gate on job MODE before classifying, or a script's own wording ("429", "timed out") would
+ # blame the wrong subsystem.
+ 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())
+ if notice is not None:
+ return notice
# Strip exception wrappers; bound input first so a multi-KB blob can't slow the regexes.
cleaned = re.sub(r"^(RuntimeError|Exception|ValueError|HTTPStatusError):\s*", "", text[:2000])
- cleaned = re.sub(r"\s+", " ", cleaned).strip()
+ cleaned = re.sub(r"\s+", " ", cleaned).strip().rstrip(".")
if len(cleaned) > 180:
cleaned = cleaned[:177].rstrip() + "..."
- message = f"⚠️ Cron '{job_name}' failed: {cleaned}"
-
- # Import-class failures in a gateway whose checkout changed underneath it (mixed sys.modules)
- # read like code bugs. When boot SHA ≠ disk HEAD, APPEND cause + fix — never replace the raw
- # error, which carries the failing symbol. Fail-safe: skew is None on non-git/no-fingerprint
- # (message unchanged); no_agent jobs excluded via the same mode gate (a fresh subprocess
- # resolves imports against disk, so its ImportError is the script's own problem).
- # Import-class failures (#95294 part 3): a long-lived gateway whose checkout was updated underneath it
- # (interrupted `hermes update`, manual git pull) serves MIXED modules — old entries frozen in
- # sys.modules, new files loaded by lazy imports — and every agent cron job then dies with `cannot import
- # name X` / ModuleNotFoundError. The error itself reads like a code bug, so operators debug the wrong
- # thing (2 days on the reporting incident, 15 missed jobs).
- if provider_reachable and re.search(
+ message = generic_failure_notice(job_name, job_id, cleaned)
+
+ # Import-class failures (#95294 part 3): a long-lived gateway whose checkout was updated
+ # underneath it (interrupted `hermes update`, manual git pull) serves MIXED modules and every
+ # agent cron job dies with `cannot import name X`. The error reads like a code bug, so APPEND
+ # cause + fix — never replace the raw error, which carries the failing symbol. Fail-safe: skew
+ # is None on non-git/no-fingerprint; no_agent jobs excluded (a fresh subprocess resolves
+ # imports against disk, so its ImportError is the script's own problem).
+ if not job.get("no_agent") and re.search(
r"cannot import name|modulenotfounderror|importerror", lower
):
try:
@@ -1505,12 +1463,12 @@ def _blocked_config_result(job_id: str, job_name: str, _pf_reason: str) -> tuple
f"**Job ID:** {job_id}\n"
f"**Run Time:** {_hermes_now().strftime('%Y-%m-%d %H:%M:%S')}\n"
f"**Status:** BLOCKED (configuration)\n\n"
- "Pre-dispatch validation found a configuration problem and "
- "the agent was NOT run (no tokens spent).\n\n"
+ "The pre-run configuration check found a problem, so the agent did not run "
+ "(nothing was charged).\n\n"
f"**Reason:** {_pf_reason}\n\n"
- "The job will stay blocked (without re-alerting) until the "
- "configuration is fixed; the next healthy run clears this "
- "state. Set `cron.preflight: false` in config.yaml to disable this validation."
+ "Hermes tries again at the next scheduled time and clears this state on the first healthy "
+ "run; this alert is not repeated. Check with `hermes cron doctor`. Set `cron.preflight: "
+ "false` in config.yaml to disable this check."
)
return False, blocked_doc, "", f"{marker} {_pf_reason}"
@@ -1837,18 +1795,22 @@ def _final_response_from_result(result: dict, job_id: str, job_name: str, AIAgen
from hermes_state_errors import PERSISTENCE_ERROR_CAUSES as _causes
except Exception:
_causes = ("locked", "disk", "unknown")
+ # The finalizer fills the model name into the explainer; render with the same name (and
+ # the bare form) or the comparison below misses and the warning is delivered.
+ _model = str(result.get("model") or "")
for _cause in (None, *_causes):
- try:
- _variant = AIAgent._format_turn_completion_explanation(turn_exit_reason, _cause)
- except TypeError:
+ for _kwargs in ({"model": _model}, {}):
try:
- _variant = AIAgent._format_turn_completion_explanation(turn_exit_reason)
+ _variant = AIAgent._format_turn_completion_explanation(turn_exit_reason, _cause, **_kwargs)
+ except TypeError:
+ try:
+ _variant = AIAgent._format_turn_completion_explanation(turn_exit_reason)
+ except Exception:
+ _variant = ""
except Exception:
_variant = ""
- except Exception:
- _variant = ""
- if _variant:
- _explainer_variants.append(_variant.strip())
+ if _variant:
+ _explainer_variants.append(_variant.strip())
if final_response.strip() in _explainer_variants:
logger.info(
"Job '%s': abnormal empty turn (%s) — suppressing explainer for cron delivery",
@@ -2598,12 +2560,8 @@ def _compose_run_delivery(
if blocked_config and not success:
# Bypass the generic failure summarizer (its auth/timeout heuristics would mislabel this).
_pf_text = re.sub(r"\[blocked_config[^\]]*\]\s*", "", err).strip()
- deliver_content = (
- f"⛔ Cron '{job.get('name') or job['id']}' blocked by "
- f"configuration validation (no LLM call was made): "
- f"{_pf_text} "
- "This alert is sent once; the job stays blocked until the configuration is fixed."
- )
+ from cron.scheduler_failure_copy import blocked_config_notice
+ deliver_content = blocked_config_notice(job.get("name") or job["id"], _pf_text)
elif success:
deliver_content = final_response
_resolve_incidents_for_recovered_job(job)
@@ -2861,44 +2819,6 @@ def _deliver_crash_failure(
-def _install_fire_secret_scope() -> "tuple[contextvars.Token, Optional[contextvars.Token]]":
- """Install the firing profile's secret scope for the span ``_run_one_job_body`` runs, delivery
- included, and return the tokens ``_reset_fire_secret_scope`` needs.
-
- Hydrate the profile's external secret sources BEFORE freezing the scope — the order
- gateway/run.py and the external cron worker already use: ``build_profile_secret_scope`` only
- READS the per-home source map, so a scope frozen first would carry no vault-backed value.
-
- For a fire routed to a profile other than the process's own (marked by
- ``cron.scheduler_provider._profile_cron_scope``) also run under multiplex semantics — for
- exactly this span and no wider. The desktop backend ticks every local profile from a process
- that is not a multiplexer, so nothing else isolates that fire; and switching the context on
- here rather than at the tick means no read is ever fail-closed without a scope to read — the
- restart-safe handoff in ``run_one_job`` runs before this and keeps today's semantics (#107692).
- """
- from agent.secret_scope import (
- build_profile_secret_scope, set_multiplex_context, set_secret_scope)
- from cron.scheduler_provider import routed_profile_fire
- from hermes_cli.env_loader import hydrate_profile_secret_sources
-
- home = Path(_get_hermes_home())
- hydrate_profile_secret_sources(home)
- scope_token = set_secret_scope(build_profile_secret_scope(home))
- context_token = set_multiplex_context(True) if routed_profile_fire() else None
- return scope_token, context_token
-
-
-def _reset_fire_secret_scope(tokens: "tuple[contextvars.Token, Optional[contextvars.Token]]") -> None:
- """Undo ``_install_fire_secret_scope`` — the context first, so multiplex semantics never
- outlive the scope they depend on."""
- from agent.secret_scope import reset_multiplex_context, reset_secret_scope
-
- scope_token, context_token = tokens
- if context_token is not None:
- reset_multiplex_context(context_token)
- reset_secret_scope(scope_token)
-
-
def _run_one_job_body(
job: dict, *, adapters=None, loop=None, verbose: bool = False,
extra_prompt: Optional[str] = None, fire_claim_lost: Optional[_CancelEventLike] = None,
@@ -2915,8 +2835,10 @@ def _run_one_job_body(
job["id"], source="direct", scheduled_instant=job.get("_scheduled_instant"))["id"]
delivery_attempted = False
delivery_error = None
+ from agent.secret_scope import (
+ build_profile_secret_scope, reset_secret_scope, set_secret_scope)
- _fire_scope_tokens = None
+ _scope_token = None
_terminal_scope_token = None
try:
# Commit a finite one-shot's dispatch BEFORE its side effect so a tick dying mid-run cannot
@@ -2942,7 +2864,7 @@ def _run_one_job_body(
# get_secret() fails closed outside a scope; the ticker thread has none. Delivery adapters
# resolve credentials, so the scope must span delivery too (reset in the outer finally).
- _fire_scope_tokens = _install_fire_secret_scope()
+ _scope_token = set_secret_scope(build_profile_secret_scope(_get_hermes_home()))
# Same for terminal policy (gateway/run.py _profile_runtime_scope): else the ticker reads
# process-global TERMINAL_* env a concurrent profile pinned. Resolution failure installs a
# refusal scope — terminal execution raises instead of using the launch process's policy.
@@ -3084,8 +3006,8 @@ def _run_one_job_body(
finally:
# Function-level on purpose: must scope delivery, deferred teardown, claim-loss handling and
# bookkeeping — not just run_job. Do not move into the run block's finally.
- if _fire_scope_tokens is not None:
- _reset_fire_secret_scope(_fire_scope_tokens)
+ if _scope_token is not None:
+ reset_secret_scope(_scope_token)
if _terminal_scope_token is not None:
from tools.terminal_scope import reset_terminal_scope
@@ -3170,12 +3092,6 @@ def _launch_external_cron_worker(job: dict) -> bool:
ownership handoff: in a transient user scope, or — when no user D-Bus
session exists and ``cron.require_restart_safe_scope`` is false — as a
direct subprocess (process separation kept, cgroup isolation lost).
-
- A fire routed to a profile other than the process's own is multiplexed at THIS boundary too.
- ``run_one_job`` switches the context on in ``_install_fire_secret_scope``, which runs AFTER
- this handoff, so a routed desktop fire on the managed path serialized ``multiplex_active=False``
- and built the worker environment with the launch profile's residue and no scrub (review on
- f5f88d5058). Enable it for exactly this span; the worker then re-establishes it from the payload.
"""
execution_id = str(job["execution_id"])
job_id = str(job["id"])
@@ -3192,25 +3108,26 @@ def _launch_external_cron_worker(job: dict) -> bool:
str(ack_path),
]
- from agent.secret_scope import is_multiplex_active
- from cron.scheduler_provider import routed_profile_fire
+ from agent.secret_scope import (
+ build_profile_secret_scope,
+ is_multiplex_active,
+ reset_secret_scope,
+ set_secret_scope,
+ )
+ from hermes_cli.env_loader import hydrate_profile_secret_sources
from tools.environments.local import build_subprocess_env, strip_launch_profile_env
from tools.process_registry import (
restart_safe_gateway_child_argv,
systemd_user_bus_env,
)
- # A fire routed to another profile is multiplexed at this handoff even when the process flag is
- # off (the desktop ticker is not a multiplexer): the payload says so, and the worker env is built
- # under that context so the scrub and the launch-residue strip both apply. The context is set
- # for exactly the env build; nothing else here reads it.
- multiplex_active = is_multiplex_active() or routed_profile_fire()
try:
require_restart_safe_scope = bool(
(load_config_readonly().get("cron") or {}).get("require_restart_safe_scope", False)
)
except Exception:
require_restart_safe_scope = False
+ multiplex_active = is_multiplex_active()
dispatch = restart_safe_gateway_child_argv(
command,
unit_suffix=f"cron-{job_id}-exec-{execution_id}",
@@ -3247,19 +3164,16 @@ def _launch_external_cron_worker(job: dict) -> bool:
raise
profile_home = _get_hermes_home().resolve()
- # Same hydrate -> scope -> (routed) multiplex-context install the in-process fire uses, for exactly
- # the env build; the helper's reset order keeps the context from outliving its scope.
- fire_scope_tokens = _install_fire_secret_scope()
+ hydrate_profile_secret_sources(profile_home)
+ secret_token = set_secret_scope(build_profile_secret_scope(profile_home))
try:
- # No restore_managed_env here: the worker re-runs load_hermes_dotenv -> _apply_managed_env at
- # import, and strip_launch_profile_env leaves managed keys in place.
worker_env = strip_launch_profile_env(build_subprocess_env(
scrub_secrets=multiplex_active,
inherit_profile_home=True,
extra={"HERMES_HOME": str(profile_home)},
))
finally:
- _reset_fire_secret_scope(fire_scope_tokens)
+ reset_secret_scope(secret_token)
worker_env = systemd_user_bus_env(worker_env)
# Unattended worker: the gateway sets HERMES_EXEC_ASK at startup (interactive launches set
# the other two), and an inherited presence var makes every env-fallback consumer in the
diff --git a/cron/scheduler_delivery.py b/cron/scheduler_delivery.py
index 459772d88d7..3842c87b6db 100644
--- a/cron/scheduler_delivery.py
+++ b/cron/scheduler_delivery.py
@@ -746,7 +746,8 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Opt
except Exception:
found = False
if not found:
- return "bot-chat delivery failed: hermes CLI not resolvable"
+ return ("Hermes could not deliver this result to Bot Chat: the `hermes` command was not found. "
+ "The result is saved; run `hermes cron runs` to see it, or `hermes doctor` if this keeps happening")
argv = [sys.executable, "-m", "hermes_cli.main"]
def _fail(msg: str, **log_kwargs) -> str:
@@ -781,9 +782,13 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Opt
creationflags=windows_hide_flags())
if result.returncode != 0:
tail = (result.stderr or result.stdout or "").strip()[-500:]
- return _fail(
- f"bot-chat delivery to profile '{profile_label}' failed (exit {result.returncode}) at {home}"
- + (f": {tail}" if tail else ""))
+ logger.warning(
+ "Job '%s': bot-chat delivery to profile '%s' failed (exit %s) at %s%s",
+ job_id, profile_label, result.returncode, home, f": {tail}" if tail else "")
+ return (
+ f"Hermes could not deliver this result to Bot Chat (profile '{profile_label}'). "
+ "The result is saved; run `hermes cron runs` to see it, or `hermes doctor` if this keeps happening"
+ + (f". Details: {tail[-200:]}" if tail else ""))
logger.info("Job '%s': delivered to Bot Chat of profile '%s'", job_id, profile_label)
return None
except subprocess.TimeoutExpired:
@@ -793,7 +798,12 @@ def _deliver_to_bot_chat(job: dict, content: str, profile: str, *, deferred: Opt
"still complete; raise cron.bot_chat_delivery_timeout_seconds if "
"this recurs)")
except Exception as e:
- return _fail(f"bot-chat delivery failed: {str(e) or type(e).__name__}", exc_info=True)
+ logger.warning(
+ "Job '%s': bot-chat delivery to profile '%s' failed: %s", job_id, profile_label,
+ str(e) or type(e).__name__, exc_info=True)
+ return (
+ f"Hermes could not deliver this result to Bot Chat (profile '{profile_label}'). "
+ "The result is saved; run `hermes cron runs` to see it, or `hermes doctor` if this keeps happening")
finally:
if query_file:
with contextlib.suppress(OSError):
diff --git a/cron/scheduler_failure_copy.py b/cron/scheduler_failure_copy.py
new file mode 100644
index 00000000000..82d6c2b6953
--- /dev/null
+++ b/cron/scheduler_failure_copy.py
@@ -0,0 +1,135 @@
+"""Plain-language copy for the one-line cron failure notice delivered to a job's chat.
+
+The scheduler classifies the failure text through ``agent.error_classifier.classify_api_error``
+(one classifier for the whole app, no cron-local regex ladder) and looks the verdict up here.
+Every notice says WHAT happened and WHAT TO DO, and names the exact ``hermes cron`` command plus
+the real output directory — "cron output" alone sent operators hunting.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import Optional
+
+from hermes_constants import display_hermes_home
+
+
+def cron_output_dir_display(job_id: str) -> str:
+ """User-facing path of a job's saved run output (profile-aware)."""
+ return f"{display_hermes_home()}/cron/output/{job_id}/"
+
+
+_HTTP_STATUS_IN_TEXT = re.compile(r"(?:\bHTTP\b|\bError code\b|\bstatus(?: code)?\b)\W{0,3}(\b[45]\d\d\b)", re.I)
+_LEADING_EXC_TYPE = re.compile(r"^(?:[\w.]+\.)?([A-Z]\w*(?:Error|Timeout|Exception))\s*:")
+
+
+def classify_cron_failure_reason(text: str) -> str:
+ """``FailoverReason`` value for a cron failure string (``"unknown"`` when unclassifiable).
+
+ The scheduler only has ``str(exc)``, so the status code and exception type the classifier
+ keys on are rebuilt from the text: a whole-token HTTP code after ``HTTP`` / ``Error code`` /
+ ``status`` (a bare ``429`` inside a job id or hash never counts, #83188) and a leading
+ ``ReadTimeout:``-style type prefix."""
+ from agent.error_classifier import classify_api_error
+
+ status = _HTTP_STATUS_IN_TEXT.search(text)
+ type_name = _LEADING_EXC_TYPE.match(text)
+ exc_cls = type(type_name.group(1), (Exception,), {}) if type_name else Exception
+ exc = exc_cls(text)
+ if status:
+ exc.status_code = int(status.group(1))
+ return classify_api_error(exc).reason.value
+
+
+# What happened, per reason: the one gloss table shared with subagent notices lives in
+# agent/turn_failure_copy.py so the two never drift; the job is the subject here.
+def _provider_failure_cause(reason: str) -> Optional[str]:
+ from agent.turn_failure_copy import failure_cause_gloss
+
+ return failure_cause_gloss(reason, subject="this job", possessive="the job's")
+
+
+_TRANSIENT_REASONS = frozenset({"timeout", "rate_limit", "upstream_rate_limit", "overloaded", "server_error"})
+
+# Reason -> what to do. Transient reasons get the backup-provider clause from the scheduler
+# (it knows whether a fallback chain is configured) instead of a fixed sentence.
+_PROVIDER_FAILURE_ACTION: dict[str, str] = {
+ "billing": (
+ "Top up or wait for the limit to reset, or pin another provider with "
+ "`hermes cron edit {job_id} --provider <name>`."
+ ),
+ "auth": (
+ "Sign in again with /login (or `hermes auth add <provider>` in a terminal), or pin a "
+ "working provider with `hermes cron edit {job_id} --provider <name>`, then "
+ "`hermes cron run {job_id}` to retry."
+ ),
+ "model_not_found": "Pick another model with `hermes cron edit {job_id} --model <name>`.",
+ "context_overflow": "Shorten the job's prompt with `hermes cron edit {job_id} --prompt <text>`.",
+}
+_PROVIDER_FAILURE_ACTION["auth_permanent"] = _PROVIDER_FAILURE_ACTION["auth"]
+_PROVIDER_FAILURE_ACTION["billing_unverified"] = _PROVIDER_FAILURE_ACTION["billing"]
+_PROVIDER_FAILURE_ACTION["payload_too_large"] = _PROVIDER_FAILURE_ACTION["context_overflow"]
+_PROVIDER_FAILURE_ACTION["content_policy_blocked"] = (
+ "Reword the job's prompt with `hermes cron edit {job_id} --prompt <text>`, or pick another "
+ "model with `hermes cron edit {job_id} --model <name>`."
+)
+_DEFAULT_FAILURE_ACTION = "Run it again with `hermes cron run {job_id}`, or edit it with `hermes cron edit {job_id}`."
+
+
+def provider_failure_notice(
+ job_name: str, job_id: str, reason: str, *, backup_provider_phrase: str,
+) -> Optional[str]:
+ """The notice for a provider-shaped ``reason``, or None when the reason is not one."""
+ cause = _provider_failure_cause(reason)
+ if cause is None:
+ return None
+ if reason in _TRANSIENT_REASONS:
+ action = (
+ f"{backup_provider_phrase} It will run again at its next scheduled time; "
+ f"`hermes cron run {job_id}` tries now."
+ )
+ else:
+ action = _PROVIDER_FAILURE_ACTION.get(reason, _DEFAULT_FAILURE_ACTION).format(job_id=job_id)
+ return (
+ f"⚠️ Cron '{job_name}' failed: {cause}. {action} "
+ f"Run log: `hermes cron runs {job_id}`."
+ )
+
+
+def generic_failure_notice(job_name: str, job_id: str, cleaned_error: str) -> str:
+ """Unclassified failure: the cleaned error text plus where to look and what to do."""
+ return (
+ f"⚠️ Cron '{job_name}' failed: {cleaned_error}. "
+ f"See the full run with `hermes cron runs {job_id}` (output saved under "
+ f"{cron_output_dir_display(job_id)}); run it again with `hermes cron run {job_id}`, "
+ f"edit it with `hermes cron edit {job_id}`, or pause it with `hermes cron pause {job_id}`."
+ )
+
+
+def script_timeout_notice(job_name: str, job_id: str) -> str:
+ return (
+ f"⚠️ Cron '{job_name}' failed: its script timed out. No model was invoked. "
+ f"Check the script's output under {cron_output_dir_display(job_id)} or `hermes cron runs {job_id}`, "
+ f"then run it again with `hermes cron run {job_id}`."
+ )
+
+
+def inactivity_notice(job_name: str, job_id: str) -> str:
+ return (
+ f"⚠️ Cron '{job_name}' failed: the job stalled — it stopped doing anything for too long "
+ f"and was cut off. Check what it was doing in the saved output under "
+ f"{cron_output_dir_display(job_id)} (`hermes cron runs {job_id}`), then run it again with "
+ f"`hermes cron run {job_id}`."
+ )
+
+
+def blocked_config_notice(job_name: str, reason: str) -> str:
+ """One-time notice when the pre-run configuration check refused to start the job."""
+ reason = reason.rstrip()
+ if reason and reason[-1] not in ".!?":
+ reason += "."
+ return (
+ f"⛔ Cron '{job_name}' did not run: {reason} Nothing was charged. Hermes will try again at "
+ "the next scheduled time once this is fixed and will not repeat this alert; check with "
+ "`hermes cron doctor`."
+ )
diff --git a/cron/scheduler_provider.py b/cron/scheduler_provider.py
index 4612d089a03..9ec19c0fded 100644
--- a/cron/scheduler_provider.py
+++ b/cron/scheduler_provider.py
@@ -6,7 +6,6 @@ execution + delivery stay in cron.scheduler.run_job / _deliver_result; never rei
from __future__ import annotations
import contextlib
-from contextvars import ContextVar
import inspect
import logging
import threading
@@ -92,38 +91,12 @@ def _existing_profile_homes(profile_homes: list) -> list:
return [entry for entry in profile_homes if Path(_profile_entry(entry)[1]).is_dir()]
-# Set by _profile_cron_scope: this task fires a profile OTHER than the process's own. A marker only.
-# Multiplex semantics are switched on where the profile's secret scope is installed
-# (cron.scheduler._install_fire_secret_scope) and off with it — never at the tick — so no read can
-# be fail-closed without a scope to read: run_one_job's restart-safe handoff runs before that
-# scope and keeps today's semantics (its own scope is #107413 / #106050's seam).
-_ROUTED_PROFILE_FIRE: ContextVar[bool] = ContextVar("_ROUTED_PROFILE_FIRE", default=False)
-
-
-def routed_profile_fire() -> bool:
- """True inside a tick for a profile other than the process's own (marker, see above)."""
- return _ROUTED_PROFILE_FIRE.get()
-
-
@contextlib.contextmanager
def _profile_cron_scope(home):
- """Scope the calling thread to one profile's home + cron store for the block.
-
- A profile OTHER than the process's own is MARKED as a routed fire (``routed_profile_fire``).
- The desktop backend ticks every local profile from one process "like a multiplex gateway"
- without setting the process-global multiplex flag, so every isolation keyed on
- ``is_multiplex_active()`` was inert for those fires: a sibling profile's ``.env`` landed in
- the shared ``os.environ`` with ``override=True`` and a scope miss read the launch profile's
- credentials (#107692). ``cron.scheduler._install_fire_secret_scope`` turns the marker into
- multiplex semantics for exactly the span the profile's secret scope covers. The process's own
- profile keeps single-profile semantics. The override and the marker both reach the pool
- worker via ``copy_context()``. Under a real multiplexer the process flag is already on."""
+ """Scope the calling thread to one profile's home + cron store for the block."""
from cron.jobs import use_cron_store
- from hermes_constants import (
- get_process_hermes_home, reset_hermes_home_override, set_hermes_home_override)
+ from hermes_constants import set_hermes_home_override, reset_hermes_home_override
- routed = Path(home).resolve() != get_process_hermes_home().resolve()
- routed_token = _ROUTED_PROFILE_FIRE.set(routed)
# Record per-profile heartbeat after each tick cycle. Distinguish a COMPLETED cycle (``_tick_error``
# unset) — where each profile's beat reflects its own outcome, so a yielding profile does not darken
# healthy siblings — from an aborted one (exception), where no profile completed and all beats are
@@ -134,7 +107,6 @@ def _profile_cron_scope(home):
yield
finally:
reset_hermes_home_override(home_token)
- _ROUTED_PROFILE_FIRE.reset(routed_token)
class CronScheduler(ABC):
diff --git a/cron/scheduler_script.py b/cron/scheduler_script.py
index 1c1743e3e9c..074f4fa987b 100644
--- a/cron/scheduler_script.py
+++ b/cron/scheduler_script.py
@@ -349,24 +349,7 @@ def _run_job_script(
# reader threads on non-UTF-8 Windows (#45099).
"encoding": "utf-8",
"errors": "replace"}
- # A routed profile's script (desktop multi-profile ticker, multiplex gateway) must see ITS
- # profile's .env + vault values — the process env holds the launch profile's. Drop the
- # launch profile's dotenv-owned residue first (a name only the launch .env defines must
- # come through UNSET, not with the launch value — the scrub only knows classified secrets),
- # then overlay the installed scope, then sanitize, so routed values pass the same scrub /
- # passthrough rules as any other. No-op outside multiplex or for the launch profile's own
- # fires; the parent process is never mutated.
- from agent.secret_scope import current_secret_scope, is_multiplex_active
- from tools.environments.local import restore_managed_env, strip_launch_profile_env
- base = strip_launch_profile_env(dict(os.environ))
- if is_multiplex_active():
- # Single-profile: the scope IS os.environ, so overlaying it would only re-sanitize
- # values the child already inherits byte-identical.
- base.update(current_secret_scope() or {})
- # Administrator-managed values keep their precedence over the routed profile's own .env,
- # exactly as they do in the launch process (``_apply_managed_env`` applies them last).
- restore_managed_env(base)
- env = build_subprocess_env(base=base)
+ env = build_subprocess_env()
env.update(env_overlay)
# Subprocess cwd only (default: scripts-dir parent). NEVER os.chdir() the process.
# Use the job's workdir as the subprocess cwd when configured, otherwise default to the scripts-dir
diff --git a/gateway/kanban_watchers_notifier.py b/gateway/kanban_watchers_notifier.py
index 06674d233a8..9be3d05c584 100644
--- a/gateway/kanban_watchers_notifier.py
+++ b/gateway/kanban_watchers_notifier.py
@@ -387,19 +387,37 @@ def _fmt_block_loop_detected(ev, n) -> tuple:
return msg, None, None
+def _fmt_gave_up(ev, n) -> tuple:
+ # The dispatcher auto-blocked the task after ``failures`` consecutive non-success attempts
+ # (spawn failure, crash, or timeout alike): it is now Blocked and waiting for a human.
+ failures = _payload(ev, "failures")
+ count = f"it failed {int(failures)} times in a row" if failures else "it kept failing"
+ last = _clip(ev, "error", " (last: {})", 160)
+ return (
+ f"⛔ {n.head} is now blocked: {count}{last}. Fix the cause, then `hermes kanban unblock "
+ f"{n.task_id}` (or `hermes kanban reassign {n.task_id}`). Logs: `hermes kanban log {n.task_id}`.",
+ None, None,
+ )
+
+
+def _fmt_timed_out(ev, n) -> tuple:
+ limit = int(_payload(ev, "limit_seconds") or 0)
+ minutes = max(1, round(limit / 60)) if limit else 0
+ span = f"its {minutes}-minute limit" if minutes else "its time limit"
+ return f"⏱ {n.head} ran past {span} and was stopped; it will be retried automatically.", None, None
+
+
# archived / unblocked are claimed (so the cursor advances past them) but
# intentionally silent (no formatter), and excluded from _WAKE_KINDS so they
# never wake the creator.
_EVENT_FORMATTERS: dict[str, Callable[[Any, "_KanbanNotification"], tuple]] = {
"completed": _fmt_completed,
"blocked": lambda ev, n: (f"⏸ {n.head} blocked{_clip(ev, 'reason', ': {}', 160)}", None, None),
- "gave_up": lambda ev, n: (
- f"✖ {n.head} gave up after repeated spawn failures{_clip(ev, 'error', _NL, 200)}", None, None,
- ),
- "crashed": lambda ev, n: (f"✖ {n.head} worker crashed (pid gone); dispatcher will retry", None, None),
- "timed_out": lambda ev, n: (
- f"⏱ {n.head} timed out (max_runtime={int(_payload(ev, 'limit_seconds') or 0)}s); will retry", None, None,
+ "gave_up": _fmt_gave_up,
+ "crashed": lambda ev, n: (
+ f"✖ {n.head} — its worker stopped unexpectedly; it will be retried automatically.", None, None,
),
+ "timed_out": _fmt_timed_out,
"status": lambda ev, n: (f"🔄 {n.head} → {_payload(ev, 'status') or ''}", None, None),
"review_requested": _fmt_review_requested,
"changes_requested": _fmt_changes_requested,
diff --git a/gateway/platforms/base.py b/gateway/platforms/base.py
index 55298cd5583..535b1191cdb 100644
--- a/gateway/platforms/base.py
+++ b/gateway/platforms/base.py
@@ -384,6 +384,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
from gateway.config import Platform, PlatformConfig
from gateway.platforms.helpers import fence_state_after
+from gateway.platforms.base_exec_approval import (
+ EA_HEADER_TEXT, EA_REASON_LABEL_TEXT, approval_timeout_seconds, format_approval_deadline_line)
from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcome
from gateway.session import SessionSource, build_session_key
from gateway.session_transcript import TranscriptReadError
@@ -437,6 +439,20 @@ GATEWAY_SECRET_CAPTURE_UNSUPPORTED_MESSAGE = (
"Secure secret entry is not supported over messaging. "
"Load this skill in the local CLI to be prompted, or add the key to ~/.hermes/.env manually.")
+# One sentence for every "you may not press/run this" refusal on every platform (slash commands,
+# approval buttons, pickers, prompts). ``{platform}`` is the ``Platform.value`` for the
+# ``hermes pairing approve`` command (hermes_cli/subcommands/pairing.py) that lets the owner fix it.
+# Kept under 200 chars: Telegram's answerCallbackQuery truncates longer text.
+UNAUTHORIZED_ACTION_NOTICE = (
+ "This bot is private and you're not on its allowed list. If you own it, run "
+ "`hermes pairing approve {platform} <request-id>` on the host (`hermes pairing list` shows the id).")
+
+
+def unauthorized_action_notice(platform: Any) -> str:
+ """``UNAUTHORIZED_ACTION_NOTICE`` for a ``Platform`` member or its string name."""
+ name = getattr(platform, "value", platform)
+ return UNAUTHORIZED_ACTION_NOTICE.format(platform=str(name or "<platform>"))
+
def safe_url_for_log(url: str, max_len: int = 80) -> str:
"""Return a URL string safe for logs (no query/fragment/userinfo)."""
@@ -2514,11 +2530,14 @@ class BasePlatformAdapter(ABC):
# No running loop (unit tests): close the coroutine to avoid a never-awaited warning.
coro.close()
- # ── ``_format_exec_approval`` templates; adapters override to keep historical wording.
- _EA_HEADER: str = "⚠️ Command Approval Required\n\n"
+ # ── ``_format_exec_approval`` templates; adapters override only the MARKUP (bold, HTML,
+ # fences) — the words come from ``gateway.platforms.base_exec_approval`` so every surface
+ # says the same thing.
+ _EA_HEADER: str = f"⚠️ {EA_HEADER_TEXT}\n\n"
_EA_CODE_OPEN: str = "```\n"
_EA_CODE_CLOSE: str = "\n```\n"
- _EA_REASON_LABEL: str = "Reason: "
+ _EA_REASON_LABEL: str = f"{EA_REASON_LABEL_TEXT}: "
+ _EA_DEADLINE_PREFIX: str = "\n\n" # separates the deadline line from the reason line
_EA_SMART_DENY_LINE: str = "\n\nSmart DENY: owner override applies to this one operation only."
_EA_CMD_BUDGET: int = 3000
_EA_REASON_BUDGET: int = 0 # 0 = the reason is never truncated
@@ -2537,17 +2556,23 @@ class BasePlatformAdapter(ABC):
"""Chars of command preview that fit; platforms with a hard message cap compute it."""
return self._EA_CMD_BUDGET
+ def _ea_deadline_line(self) -> str:
+ """The "doing nothing means it will NOT run" line, with the configured approvals.timeout."""
+ return self._EA_DEADLINE_PREFIX + self._ea_escape(format_approval_deadline_line(approval_timeout_seconds()))
+
def _format_exec_approval(
self, command: str, description: str = "dangerous command", smart_denied: bool = False) -> str:
- """Shared exec-approval prompt text: header + fenced (truncated) command + reason,
- plus the smart-deny line. Buttons/trailing instructions stay platform-local."""
+ """Shared exec-approval prompt text: header + fenced (truncated) command + why it was
+ flagged + the deadline line, plus the smart-deny line. Buttons/trailing instructions stay
+ platform-local."""
if self._EA_REASON_BUDGET:
description = self._truncate_preview(str(description or ""), self._EA_REASON_BUDGET)
cmd_preview = self._truncate_preview(
str(command or ""), self._exec_approval_cmd_budget(description, smart_denied))
text = (f"{self._EA_HEADER}"
f"{self._EA_CODE_OPEN}{self._ea_escape(cmd_preview)}{self._EA_CODE_CLOSE}"
- f"{self._EA_REASON_LABEL}{self._ea_escape(description)}")
+ f"{self._EA_REASON_LABEL}{self._ea_escape(description)}"
+ f"{self._ea_deadline_line()}")
return text + self._EA_SMART_DENY_LINE if smart_denied else text
# ── Exec-approval prompt (template method). The choice set is one rule for every button
diff --git a/gateway/platforms/base_exec_approval.py b/gateway/platforms/base_exec_approval.py
new file mode 100644
index 00000000000..80191ca7070
--- /dev/null
+++ b/gateway/platforms/base_exec_approval.py
@@ -0,0 +1,43 @@
+"""Shared wording for the exec-approval prompt every messaging surface renders.
+
+The button card (``BasePlatformAdapter._format_exec_approval``) and the plain-text
+``/approve`` fallback (``gateway.run._format_exec_approval_fallback``) must tell the user
+the same three things: what Hermes wants to run, why it was flagged, and that silence means
+the command does NOT run once ``approvals.timeout`` elapses. Keeping the text here means one
+edit changes every platform; adapters only wrap these strings in their own markup.
+
+No imports from ``gateway.platforms.base`` or ``gateway.run`` — both import this module.
+"""
+
+from __future__ import annotations
+
+# Bare strings; adapters add their own bold/HTML around them.
+EA_HEADER_TEXT = "Hermes wants to run a command that needs your OK"
+EA_REASON_LABEL_TEXT = "Why it was flagged"
+
+# Timeout notice posted when nobody answered the prompt (``{window}`` = "5 minutes").
+APPROVAL_TIMED_OUT_NOTICE = (
+ "⌛ Approval timed out after {window} — the command was NOT run. "
+ "Ask me to try again if you still want it, or raise approvals.timeout in config.yaml.")
+
+
+def approval_timeout_seconds() -> int:
+ """The configured ``approvals.timeout`` (default 300s); module attribute so tests can pin it."""
+ from tools.approval_context import _get_approval_timeout
+ return _get_approval_timeout()
+
+
+def format_approval_window(seconds: int) -> str:
+ """Human wording for a timeout (300 → "5 minutes"); one formatter shared with the CLI notice and
+ the tool result's ``user_summary`` — see ``tools.approval_context.format_approval_window``."""
+ from tools.approval_context import format_approval_window as _shared
+ return _shared(seconds)
+
+
+def format_approval_deadline_line(timeout_s: int) -> str:
+ """The last line of every approval prompt: doing nothing is a safe no."""
+ return f"If you don't answer within {format_approval_window(timeout_s)} it will NOT run."
+
+
+def format_approval_timed_out_notice(timeout_s: int) -> str:
+ return APPROVAL_TIMED_OUT_NOTICE.format(window=format_approval_window(timeout_s))
diff --git a/gateway/platforms/whatsapp_cloud.py b/gateway/platforms/whatsapp_cloud.py
index 1830607317c..3e82233d358 100644
--- a/gateway/platforms/whatsapp_cloud.py
+++ b/gateway/platforms/whatsapp_cloud.py
@@ -40,6 +40,7 @@ except ImportError:
from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import BasePlatformAdapter, ExecApprovalPrompt, SendResult, transcode_to_ogg_opus
+from gateway.platforms.base_exec_approval import EA_HEADER_TEXT
from gateway.platforms.helpers import bounded_put
from gateway.platforms.event import MessageEvent, MessageType
from gateway.platforms.whatsapp_common import WhatsAppBehaviorMixin, _get_wsecret
@@ -467,7 +468,7 @@ class WhatsAppCloudAdapter(WhatsAppBehaviorMixin, BasePlatformAdapter):
interactive = {"type": "list", "body": {"text": body_text}, "action": {"button": "Choose", "sections": [{"title": "Options", "rows": rows}]}}
return await self._send_interactive(chat_id, interactive, metadata, self._clarify_state, clarify_id, session_key)
- _EA_HEADER = "⚠️ *Command Approval Required*\n\n"
+ _EA_HEADER = f"⚠️ *{EA_HEADER_TEXT}*\n\n"
_EA_CODE_CLOSE = "\n```\n\n"
_EA_CMD_BUDGET = 800 # body caps at 1024; leave room for the framing prose
diff --git a/gateway/relay/adapter.py b/gateway/relay/adapter.py
index 1f6db75667f..fe7afc5d6d8 100644
--- a/gateway/relay/adapter.py
+++ b/gateway/relay/adapter.py
@@ -24,6 +24,7 @@ from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import (
BasePlatformAdapter, ExecApprovalPrompt, SendResult,
)
+from gateway.platforms.base_exec_approval import EA_HEADER_TEXT
from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcome
from gateway.relay.descriptor import CapabilityDescriptor
from gateway.relay.egress import (
@@ -1991,7 +1992,7 @@ class RelayAdapter(BasePlatformAdapter):
_PROMPT_UNAVAILABLE = SendResult(success=False, error="relay prompt op unavailable")
- _EA_HEADER = "⚠️ **Command Approval Required**\n\n"
+ _EA_HEADER = f"⚠️ **{EA_HEADER_TEXT}**\n\n"
_EA_SMART_DENY_LINE = "\n\n**Smart DENY:** owner override applies to this one operation only."
_EA_CMD_BUDGET = 1500
diff --git a/gateway/run.py b/gateway/run.py
index 8a1fecf6f25..2ff17be402e 100644
--- a/gateway/run.py
+++ b/gateway/run.py
@@ -189,18 +189,15 @@ def hygiene_compaction_recovered(
def _hygiene_compression_timeout_message(
*, total_exhausted: bool, elapsed: float, idle_timeout: float, progress_observed: bool) -> str:
- """Describe the host timeout that actually ended hygiene compression."""
+ """Describe the host timeout that actually ended hygiene compression. Chat users cannot edit
+ model config, so the copy names /compress, /new and `hermes doctor`, never a config key or the
+ raw second counts (those stay in the gateway log)."""
+ lead = (
+ "⚠️ Shortening the conversation history took too long, so I skipped it and kept "
+ "everything as-is. Run /compress to try again or /new to start fresh.")
if total_exhausted:
- progress = " after summary output was observed" if progress_observed else ""
- return (
- "⚠️ Context compression reached its total ceiling after "
- f"{elapsed:.1f}s{progress}. No messages were dropped — continuing "
- "without compression. Run /compress to retry or /reset for a clean session.")
- return (
- f"⚠️ Context compression timed out after {idle_timeout:.1f}s with no "
- "output from the summary model. No messages were dropped — continuing "
- "without compression. Run /compress to retry, /reset for a clean "
- "session, or check your auxiliary.compression model configuration.")
+ return lead
+ return lead + " If this keeps happening, run `hermes doctor` on the host."
def _cached_agent_for_hygiene(gateway, session_key: str):
@@ -562,30 +559,44 @@ def _redact_approval_command(cmd: "str | None") -> str:
def _format_exec_approval_fallback(
command: str, description: str, command_prefix: str, *, allow_permanent: bool = True,
allow_session: bool = True, smart_denied: bool = False) -> str:
- """Render the text fallback from approval capabilities, not platform names."""
+ """Render the text fallback from approval capabilities, not platform names. Same words as
+ the button card (``BasePlatformAdapter._format_exec_approval``), plus the typed ``/approve``
+ steps a surface without buttons needs."""
+ from gateway.platforms.base_exec_approval import (
+ EA_HEADER_TEXT, EA_REASON_LABEL_TEXT, approval_timeout_seconds, format_approval_deadline_line)
cmd_preview = command[:200] + "..." if len(command) > 200 else command
heading = ("⚠️ **Smart DENY — owner override for one operation:**" if smart_denied
- else "⚠️ **Dangerous command requires approval:**")
+ else f"⚠️ **{EA_HEADER_TEXT}**")
- choices = [f"Reply `{command_prefix}approve` to execute this one operation"]
+ choices = [f"Reply `{command_prefix}approve` to run it once"]
if not smart_denied and allow_session:
- choices.append(f"`{command_prefix}approve session` to approve this pattern for the session")
+ choices.append(f"`{command_prefix}approve session` to allow this pattern for the rest of this session")
if allow_permanent:
- choices.append(f"`{command_prefix}approve always` to approve permanently")
+ choices.append(f"`{command_prefix}approve always` to allow it permanently")
choices.append(f"`{command_prefix}deny` to cancel")
return (
- f"{heading}\n```\n{cmd_preview}\n```\nReason: {description}\n\n"
- + ", ".join(choices[:-1]) + f", or {choices[-1]}.")
+ f"{heading}\n```\n{cmd_preview}\n```\n{EA_REASON_LABEL_TEXT}: {description}\n\n"
+ + ", ".join(choices[:-1]) + f", or {choices[-1]}.\n"
+ + format_approval_deadline_line(approval_timeout_seconds()))
-# Ordered: auth beats policy beats rate-limit beats connection; first match wins.
+# Ordered: auth beats policy beats rate-limit beats connection; first match wins. Copy names the
+# slash command the chat user can run; raw provider text stays in the gateway log (`hermes logs`).
_PROVIDER_ERROR_REPLIES = (
- (_GATEWAY_AUTH_ERROR_RE, "⚠️ Provider authentication failed. Check the configured credentials; "
- "raw provider details are in the gateway logs."),
- (_GATEWAY_PROVIDER_POLICY_RE, "⚠️ The model provider rejected the request. I kept the raw provider "
- "error out of chat; check gateway logs for details or try rephrasing."),
- (_GATEWAY_RATE_LIMIT_RE, "⏱️ The model provider is rate-limiting requests. Please wait a moment and try again."),
- (_GATEWAY_CONNECTION_ERROR_RE, "⚠️ The model server is not responding — it looks like the configured "
- "model endpoint is not running or is unreachable."))
+ (_GATEWAY_AUTH_ERROR_RE, "⚠️ Sign-in to the AI model service failed. Use /login to sign in again, "
+ "or ask whoever runs this bot to run `hermes doctor` on the host."),
+ (_GATEWAY_PROVIDER_POLICY_RE, "⚠️ The AI model service rejected this request. Try rephrasing your "
+ "message, or use /model to switch models."),
+ (_GATEWAY_RATE_LIMIT_RE, "⏱️ The AI model service is rate-limiting requests. Wait a moment, then use /retry."),
+ (_GATEWAY_CONNECTION_ERROR_RE, "⚠️ The AI model service isn't reachable right now — the configured model "
+ "endpoint is not running or is unreachable. Wait a moment and use /retry; "
+ "if it persists, run `hermes doctor` on the host."))
+
+
+# Shared by the failed-turn normalizer and ``run_turn._hmwa_agent_error_reply``; canonical
+# commands (/compress, /new) — the /compact and /reset aliases are absent from /help.
+_CONTEXT_OVERFLOW_REPLY = (
+ "⚠️ This conversation has grown too long for me to read all at once. "
+ "Use /compress to shorten the history, or /new to start a fresh conversation.")
def _gateway_provider_error_reply(text: str) -> str:
@@ -594,8 +605,8 @@ def _gateway_provider_error_reply(text: str) -> str:
if pattern.search(text):
return reply
return (
- "⚠️ The model provider failed after retries. I kept raw provider details "
- "out of chat; check gateway logs for diagnostics.")
+ "⚠️ The AI model service kept failing. Use /retry to try again, or /model to switch "
+ "models. Details are in the gateway log (`hermes logs`).")
# Provider/API failure envelope preambles (not ordinary assistant prose), anchored at line start.
@@ -2908,20 +2919,23 @@ def _format_concise_process_notification(
"""One-line completion message for ``concise`` display mode; failure appends a short output tail."""
ok = exit_code in {0, None}
icon = "✅" if ok else "❌"
- verb = "finished" if ok else f"failed (exit {exit_code})"
- parts = [f"{icon} Background task {verb}"]
+ parts = [f"{icon} Background task {'finished' if ok else 'failed'}"]
short_cmd = _shorten_command_for_display(command)
if short_cmd:
parts.append(f"— `{short_cmd}`")
+ details = []
if isinstance(duration_seconds, (int, float)) and duration_seconds >= 0:
secs = int(duration_seconds)
if secs >= 3600:
- dur = f"{secs // 3600}h {(secs % 3600) // 60}m"
+ details.append(f"{secs // 3600}h {(secs % 3600) // 60}m")
elif secs >= 60:
- dur = f"{secs // 60}m {secs % 60}s"
+ details.append(f"{secs // 60}m {secs % 60}s")
else:
- dur = f"{secs}s"
- parts.append(f"({dur})")
+ details.append(f"{secs}s")
+ if not ok:
+ details.append(f"exit {exit_code}")
+ if details:
+ parts.append(f"({', '.join(details)})")
text = " ".join(parts)
if not ok and output:
tail_lines = [ln for ln in output.strip().splitlines() if ln.strip()][-5:]
@@ -2929,7 +2943,9 @@ def _format_concise_process_notification(
if len(tail) > 500:
tail = tail[-500:]
if tail:
- text += f"\n```\n{tail}\n```"
+ text += f". Last output:\n```\n{tail}\n```"
+ if not ok:
+ text += "\nAsk me to rerun it or show the full log."
return text
@@ -3027,12 +3043,13 @@ def _normalize_empty_agent_response(
"turn was stopped to protect your conversation history. "
"Your message should already be saved — please send it again in a moment.")
if is_overflow:
- return (
- "⚠️ Session too large for the model's context window.\n"
- "Use /compact to compress the conversation, or /reset to start fresh.")
+ return _CONTEXT_OVERFLOW_REPLY
+ # Raw exception text (class names, JSON bodies, URLs) stays in the gateway log.
+ logger.warning("Agent turn failed; reply sanitized for chat. Detail: %s", str(error_detail)[:500])
return (
- f"The request failed: {str(error_detail)[:300]}\n"
- "Try again or use /reset to start a fresh session.")
+ "⚠️ Something went wrong and I couldn't finish this reply. Use /retry to try again, "
+ "or /new to start a fresh conversation. Technical details are in the gateway log "
+ "(`hermes logs`).")
api_calls = int(agent_result.get("api_calls", 0) or 0)
if agent_result.get("interrupted"):
@@ -3061,8 +3078,24 @@ def _normalize_empty_agent_response(
if _is_gateway_hidden_reasoning_incomplete_turn(agent_result):
return ""
if agent_result.get("partial"):
- err = agent_result.get("error", "processing incomplete")
- return f"⚠️ Processing stopped: {str(err)[:200]}. Try again."
+ # ``error`` mirrors the loop's own final text (curated, e.g. "Response truncated due to
+ # output length limit") and is kept; a raw provider envelope goes to the log instead.
+ err = str(agent_result.get("error") or "processing incomplete")
+ # A loop site code (truncated, context_overflow, ...) already wrote the full
+ # what-happened / what-to-do sentence: deliver it verbatim. Wrapping it would cut it
+ # mid-sentence at 200 chars and append a second, conflicting set of instructions.
+ from agent.turn_failure_copy import SITE_FAILURE_CODES
+ if (str(agent_result.get("failure_reason") or "") in SITE_FAILURE_CODES
+ and err.strip() and not _looks_like_gateway_provider_error(err)):
+ return err if err.startswith("⚠️") else f"⚠️ {err}"
+ if _looks_like_gateway_provider_error(err):
+ logger.warning("Agent turn ended partially; reply sanitized for chat. Detail: %s", err[:500])
+ reason = ""
+ else:
+ reason = f": {err[:200]}"
+ return (
+ f"⚠️ I had to stop before finishing{reason}. Use /retry to try again, or /compress "
+ "if this conversation has grown very long.")
return (
"⚠️ Processing completed but no response was generated. "
"This may be a transient error — try sending your message again.")
diff --git a/gateway/run_inbound.py b/gateway/run_inbound.py
index ac7d4fe3ee8..c4f82922849 100644
--- a/gateway/run_inbound.py
+++ b/gateway/run_inbound.py
@@ -21,6 +21,10 @@ from gateway.config import Platform
from gateway.platforms.base import EphemeralReply
from gateway.platforms.event import MessageEvent, MessageType
from gateway.run_common import _UNSET
+from gateway.run_inbound_unauthorized import (
+ PAIRING_RATE_LIMITED_REPLY, UnauthorizedOwnerNotifier, pairing_code_reply, pairing_profile_arg,
+ unauthorized_owner_hint,
+)
from gateway.session import (
SessionSource, is_shared_multi_user_session, neutralize_untrusted_inline_text
)
@@ -88,21 +92,9 @@ class GatewayInboundMixin:
code = pairing_store.generate_code(platform_name, source.user_id, source.user_name or "")
adapter = self._adapter_for_source(source)
if code:
- store_profile = getattr(pairing_store, "profile", None)
- profile_arg = (
- f"-p {store_profile} "
- if isinstance(store_profile, str) and store_profile and store_profile != "default"
- else ""
- )
- reply = (
- f"Hi~ I don't recognize you yet!\n\n"
- f"Here's your pairing code: `{code}`\n\n"
- f"Ask the bot owner to run:\n"
- f"`hermes {profile_arg}pairing approve "
- f"{platform_name} {code}`"
- )
+ reply = pairing_code_reply(platform_name, code, pairing_profile_arg(pairing_store))
else:
- reply = "Too many pairing requests right now~ Please try again later!"
+ reply = PAIRING_RATE_LIMITED_REPLY
if adapter:
await adapter.send(source.chat_id, reply)
if not code:
@@ -129,6 +121,21 @@ class GatewayInboundMixin:
except Exception:
logger.warning("Failed to deliver unauthorized-DM decline on %s", platform_name, exc_info=True)
+ async def _hm_report_ignored_dm(self, source: SessionSource) -> None:
+ """Unauthorized DM under behaviour ``ignore``: nothing goes to the sender. The owner gets the
+ sender's ID and the allowlist fix in the WARNING log and, once per sender, in the home channel."""
+ from hermes_constants import display_hermes_home
+ platform_name = source.platform.value if source.platform else "unknown"
+ hint = unauthorized_owner_hint(
+ platform_name, source.user_id, source.user_name or "", hermes_home=display_hermes_home(),
+ )
+ logger.warning("Unauthorized user (ignored): %s", hint)
+ notifier = getattr(self, "_unauthorized_owner_notifier", None)
+ if notifier is None:
+ notifier = self._unauthorized_owner_notifier = UnauthorizedOwnerNotifier()
+ if notifier.first_time(platform_name, source.user_id) and getattr(self, "config", None) is not None:
+ await notifier.notify(self, source, hint)
+
async def _hm_admit_event(
self, event: "MessageEvent"
) -> Optional[Tuple["MessageEvent", SessionSource, bool]]:
@@ -214,15 +221,20 @@ class GatewayInboundMixin:
# posts, sender_chat): can't be paired but may be authorized via a chat allowlist.
logger.debug("Ignoring message with no user_id from %s", source.platform.value)
return None
- logger.warning("Unauthorized user: %s (%s) on %s", source.user_id, source.user_name, source.platform.value)
# DMs get a pairing code or a one-time decline, groups are ignored. A bot cannot pair, and
# answering one mid-cooldown is outbound traffic.
- if source.chat_type == "dm" and not getattr(source, "is_bot", False):
- behavior = self._get_unauthorized_dm_behavior(source.platform, profile=source.profile)
- if behavior == "pair":
- await self._hm_offer_pairing_code(source)
- elif behavior == "decline":
- await self._hm_send_unauthorized_decline(source)
+ pairable_dm = source.chat_type == "dm" and not getattr(source, "is_bot", False)
+ behavior = self._get_unauthorized_dm_behavior(source.platform, profile=source.profile) if pairable_dm else None
+ if behavior == "pair":
+ logger.warning("Unauthorized user: %s (%s) on %s", source.user_id, source.user_name, source.platform.value)
+ await self._hm_offer_pairing_code(source)
+ elif behavior == "decline":
+ logger.warning("Unauthorized user: %s (%s) on %s", source.user_id, source.user_name, source.platform.value)
+ await self._hm_send_unauthorized_decline(source)
+ elif pairable_dm:
+ await self._hm_report_ignored_dm(source)
+ else:
+ logger.warning("Unauthorized user: %s (%s) on %s", source.user_id, source.user_name, source.platform.value)
return None
# The busy path charged this event on arrival; a drained follow-up must not pay twice.
if not getattr(event, "_bot_loop_admitted", False) and not self._admit_bot_message_for_source(source):
diff --git a/gateway/run_inbound_unauthorized.py b/gateway/run_inbound_unauthorized.py
new file mode 100644
index 00000000000..4276d81a49a
--- /dev/null
+++ b/gateway/run_inbound_unauthorized.py
@@ -0,0 +1,118 @@
+"""Copy and owner-side signalling for unauthorized inbound senders.
+
+Two audiences, two rules:
+
+* The **stranger** gets either a pairing code (behaviour ``pair``) or nothing at all (behaviour
+ ``ignore``: an allowlist is configured, so any reply would leak that the bot exists).
+* The **owner** is the one who can fix a mis-typed allowlist, so an ignored DM is logged at
+ WARNING with the sender's ID and the allowlist / pairing-mode fix, and surfaced once per
+ (platform, user) per gateway process in the platform's home channel when one is configured.
+ No pairing request is minted for an ignored sender: strangers must not create server state
+ when the owner has restricted access.
+"""
+
+from __future__ import annotations
+
+import logging
+from collections import OrderedDict
+
+from gateway.pairing import CODE_TTL_SECONDS, _allowlist_env_for_platform
+
+# Display names come from the stranger. Bound them and keep the mention/markdown surface small in
+# the owner's channel: a name is never a reason to render a link, mention or new section.
+_MAX_SENDER_NAME_CHARS = 64
+# Distinct (platform, user_id) senders remembered per process; a bot rotating IDs evicts the oldest
+# instead of growing the set without limit.
+_MAX_SEEN_SENDERS = 2048
+
+logger = logging.getLogger("gateway.run")
+
+
+def pairing_profile_arg(pairing_store) -> str:
+ """``-p <profile> `` when the store belongs to a non-default profile, else ``""``."""
+ store_profile = getattr(pairing_store, "profile", None)
+ if isinstance(store_profile, str) and store_profile and store_profile != "default":
+ return f"-p {store_profile} "
+ return ""
+
+
+def pairing_code_reply(platform_name: str, code: str, profile_arg: str = "") -> str:
+ """The DM a first-time sender receives: what happened, how long the code lives, what to do
+ whether they are the owner or a guest, and that they must message again after approval."""
+ hours = max(1, CODE_TTL_SECONDS // 3600)
+ validity = f"{hours} hour" if hours == 1 else f"{hours} hours"
+ approve_cmd = f"hermes {profile_arg}pairing approve {platform_name} {code}"
+ return (
+ "Hi! I don't recognize you yet, so I can't reply until the person running this bot "
+ "approves you.\n\n"
+ f"Your pairing code: `{code}` (valid for {validity})\n\n"
+ f"If you run this bot, open a terminal and run: `{approve_cmd}`. "
+ "Otherwise send that command to the bot owner. After approval, send your message again."
+ )
+
+
+PAIRING_RATE_LIMITED_REPLY = (
+ "Too many pairing requests right now. Wait a few minutes, then send your message again.")
+
+
+def unauthorized_owner_hint(
+ platform_name: str, user_id: str, user_name: str = "", *, hermes_home: str,
+) -> str:
+ """One-line hint for the owner (log + home channel): who was dropped and how to let them in.
+ No pairing request is minted for an ignored sender (a configured allowlist means the owner chose
+ to restrict access), so the ways in are the allowlist itself or switching the platform to
+ pairing mode."""
+ from gateway.session import neutralize_untrusted_inline_text
+
+ safe_name = neutralize_untrusted_inline_text(user_name or "", max_chars=_MAX_SENDER_NAME_CHARS)
+ # Mention and link sigils are stripped so a hostile display name cannot ping the channel or
+ # smuggle a link; the ID next to it is the value the owner actually acts on.
+ safe_name = "".join(ch for ch in safe_name if ch not in "@<>[]()`*_~#").strip()
+ who = f"{safe_name} ({user_id})" if safe_name else str(user_id)
+ env_var = _allowlist_env_for_platform(platform_name)
+ allowlist = (
+ f"add the ID to {env_var} in {hermes_home}/.env and restart the gateway"
+ if env_var else "add the ID to this platform's allowed-users list and restart the gateway"
+ )
+ return (
+ f"Dropped a message from unrecognized {platform_name} user {who}. If that is you or someone "
+ f"you trust, {allowlist}; or set `unauthorized_dm_behavior: pair` for {platform_name} in "
+ f"{hermes_home}/config.yaml so unknown senders receive a pairing code you can approve with "
+ f"`hermes pairing approve {platform_name} <code>`."
+ )
+
+
+class UnauthorizedOwnerNotifier:
+ """Tells the owner's home channel about the first drop of each unrecognized DM sender.
+
+ One notice per (platform, user_id) per gateway process: the first drop is the useful signal (an
+ owner who typo'd their own ID); repeats would only let a stranger spam the home channel.
+ """
+
+ def __init__(self, max_seen: int = _MAX_SEEN_SENDERS) -> None:
+ self._seen: OrderedDict[tuple[str, str], None] = OrderedDict()
+ self._max_seen = max(1, int(max_seen))
+
+ def first_time(self, platform_name: str, user_id: str) -> bool:
+ key = (platform_name, str(user_id))
+ if key in self._seen:
+ self._seen.move_to_end(key)
+ return False
+ self._seen[key] = None
+ while len(self._seen) > self._max_seen:
+ self._seen.popitem(last=False)
+ return True
+
+ async def notify(self, runner, source, hint: str) -> None:
+ """Best-effort post to the source platform's home channel; silent when none is configured."""
+ for platform, _cfg, home, transport in runner._home_channel_transports():
+ if platform != source.platform:
+ continue
+ if str(home.chat_id) == str(source.chat_id):
+ # The stranger's DM *is* the home channel (misconfiguration); posting there would
+ # answer the unauthorized user, which the ignore behaviour exists to prevent.
+ return
+ await runner._send_home_channel_message(
+ platform, home, transport, f"⚠️ {hint}", "unauthorized-sender notice failed for %s:%s: %s",
+ )
+ return
diff --git a/gateway/run_notifications.py b/gateway/run_notifications.py
index 1fa8c80267f..5242a711d3a 100644
--- a/gateway/run_notifications.py
+++ b/gateway/run_notifications.py
@@ -26,6 +26,18 @@ from gateway.run_shutdown import _log_suppressed, _notice_target_key, _send_erro
# Log-record parity with the origin module.
logger = logging.getLogger("gateway.run")
+# A failed /update leaves the previous version running; the full pip/git log stays on the host
+# (`hermes update` re-runs it in the terminal) and only a short tail is quoted in chat.
+_UPDATE_FAILED_NOTICE = (
+ "❌ Hermes update failed; the previous version is still running. Run `hermes update` on the "
+ "host to see the full error, or try /update again later.")
+
+
+def _update_output_tail(output: str, limit: int) -> str:
+ """Last ``limit`` chars of an update log, prefixed with an ellipsis when cut."""
+ return output if len(output) <= limit else "…" + output[-limit:]
+
+
_VIDEO_EXTS = {'.mp4', '.mov', '.avi', '.mkv', '.webm', '.3gp'}
# Routing fields copied verbatim from a process watcher onto its synthetic completion event.
_WATCHER_ROUTE_FIELDS = ("session_key", "platform", "chat_type", "chat_id", "thread_id", "user_id", "user_name")
@@ -584,8 +596,7 @@ class GatewayNotificationsMixin:
with _log_suppressed(logging.WARNING, "Update final notification failed: %s"):
exit_code = self._update_exit_code(paths)
await target.send(
- "✅ Hermes update finished." if exit_code == 0
- else "❌ Hermes update failed (exit code {}).".format(exit_code)
+ "✅ Hermes update finished." if exit_code == 0 else _UPDATE_FAILED_NOTICE
)
logger.info("Update finished (exit=%s), notified %s", exit_code, session_key)
self._clear_update_markers(paths, session_key)
@@ -661,16 +672,14 @@ class GatewayNotificationsMixin:
metadata = self._pending_marker_metadata(platform, chat_id, pending, adapter)
from tools.ansi_strip import strip_ansi
output = strip_ansi(output).strip()
- if output:
- if len(output) > 3500:
- output = "…" + output[-3500:]
- status = "✅ Hermes update finished." if exit_code == 0 else "❌ Hermes update failed."
- msg = f"{status}\n\n```\n{output}\n```"
+ if exit_code == 0:
+ msg = "✅ Hermes update finished successfully."
+ if output:
+ msg = f"{msg}\n\n```\n{_update_output_tail(output, 3500)}\n```"
else:
- msg = (
- "✅ Hermes update finished successfully." if exit_code == 0 else
- "❌ Hermes update failed. Check the gateway logs or run `hermes update` manually for details."
- )
+ msg = _UPDATE_FAILED_NOTICE
+ if output:
+ msg = f"{msg}\n\nLast lines:\n```\n{_update_output_tail(output, 800)}\n```"
await adapter.send(chat_id, msg, metadata=_non_conversational_metadata(metadata, platform=platform))
logger.info("Sent post-update notification to %s:%s (exit=%s)", platform_str, chat_id, exit_code)
except Exception as e:
@@ -844,7 +853,7 @@ class GatewayNotificationsMixin:
logger.info("state.db recovered before the home-channel warning went out; not broadcasting")
return
from hermes_constants import get_default_hermes_root, profile_cli_selector
- from hermes_state import _default_db_path, classify_persistence_error, format_session_db_unavailable
+ from hermes_state import _default_db_path, classify_persistence_error
cause = classify_persistence_error(error)
# Copy-pasteable, so name the real store and pin the profile: a bare `hermes` follows
# active_profile, which may be a different database (#105887).
@@ -877,9 +886,12 @@ class GatewayNotificationsMixin:
"recovery tools or restore a backup unless `hermes doctor` confirms damage."
)
else:
+ from hermes_state_user_copy import describe_storage_failure
+ failure = describe_storage_failure(error)
message = (
- f"⚠️ Session database unavailable — messages may not be persisted. "
- f"{format_session_db_unavailable()}\nRun `hermes doctor` for diagnostics."
+ "⚠️ Session database unavailable — messages may not be saved and /resume will be "
+ f"empty. Cause: {failure.gloss}. Run `hermes {profile_arg}doctor --fix` on the "
+ "gateway machine, then `hermes gateway restart`."
)
logger.warning("Broadcasting state.db failure warning to home channels: %s", error)
for platform, _platform_cfg, home, transport in self._home_channel_transports():
diff --git a/gateway/run_shutdown.py b/gateway/run_shutdown.py
index dcd93ff6936..d148d40ccef 100644
--- a/gateway/run_shutdown.py
+++ b/gateway/run_shutdown.py
@@ -847,10 +847,11 @@ class GatewayShutdownMixin:
except Exception as e:
logger.debug("Cron interrupt targets unresolved for %s: %s", job_id, e)
continue
+ job_name = job.get("name") or job_id
msg = (
- f"⚠️ Cron job '{job.get('name') or job_id}' was interrupted — "
- f"the gateway is {action} and killed the run before it "
- "finished. No result was produced for this run."
+ f"⚠️ Scheduled job '{job_name}' was cut short because Hermes is {action}; "
+ "no result this run. It will run again on schedule, or run it now with "
+ f"`hermes cron run {job_name}` once Hermes is back."
)
for target in targets or ():
try:
@@ -931,11 +932,14 @@ class GatewayShutdownMixin:
Called at the start of stop() while adapters are connected; send failures never block shutdown.
"""
restart_source = self._restart_command_source if self._restart_requested else None
- msg = "⚠️ Gateway shutting down — Your current task will be interrupted."
+ msg = (
+ "⚠️ Hermes is shutting down — your current task will be interrupted. "
+ "When it is back online, send any message and I'll try to pick up where we left off."
+ )
if self._restart_requested:
msg = (
- "⚠️ Gateway restarting — Your current task will be interrupted. "
- "Send any message after restart and I'll try to resume where you left off."
+ "⚠️ Hermes is restarting — your current task will be interrupted. "
+ "Send any message after the restart and I'll try to resume where you left off."
)
restart_key = None
if restart_source is not None:
diff --git a/gateway/run_turn.py b/gateway/run_turn.py
index ec69fa87f6c..3dc99cbb0ee 100644
--- a/gateway/run_turn.py
+++ b/gateway/run_turn.py
@@ -58,6 +58,12 @@ _UNEXPECTED_SILENCE_REPLY = (
)
+def _bg_prompt_preview(prompt: str, limit: int = 60) -> str:
+ """Short single-line quote of a /bg prompt for its failure notice (the task id means nothing to the user)."""
+ text = " ".join(str(prompt or "").split())
+ return text if len(text) <= limit else text[: limit - 1].rstrip() + "…"
+
+
def is_context_overflow_failure_result(agent_result: dict, history_len: int) -> bool:
"""One verdict for "this failed turn is a context overflow", shared by transcript persistence
(#1630 skip) and the user-facing reply so the two can never disagree.
@@ -1085,11 +1091,12 @@ class GatewayTurnMixin:
# Force-redact: provider exception text may contain credentials; this reaches users.
from agent.redact import redact_sensitive_text
_err = redact_sensitive_text(getattr(_comp, "_last_summary_error", None) or "unknown error", force=True)
+ logger.warning("Session hygiene compression aborted: %s", _err)
await self._hmwa_hygiene_notify(
- source, attempt.meta, "⚠️ Context compression aborted "
- f"({_err}). No messages were dropped — "
- "conversation is unchanged. Run /compress to retry, /reset for a clean "
- "session, or check your auxiliary.compression model configuration.",
+ source, attempt.meta,
+ "⚠️ Shortening the conversation history failed, so I kept everything as-is. "
+ "Run /compress to try again or /new to start fresh. If this keeps happening, "
+ "run `hermes doctor` on the host.",
"compression-failure warning",
)
# Configured aux model failed, recovered on the main model: only the user can fix that config.
@@ -1395,12 +1402,14 @@ class GatewayTurnMixin:
_intentional_silence = False
response = _UNEXPECTED_SILENCE_REPLY
- # "(empty)" = the model produced no visible content after exhausting all retries.
+ # "(empty)" = the model produced no visible content after exhausting all retries. One
+ # text with the CLI explainer and the desktop (agent/turn_explainers.py) so the user
+ # reads the same words on every surface.
if response == "(empty)" and not _intentional_silence:
- response = (
- "⚠️ The model returned no response after processing tool results. This can happen "
- "with some models — try again or rephrase your question."
- )
+ from agent.turn_explainers import EMPTY_RESPONSE_EXPLANATION
+
+ _model = str(agent_result.get("model") or "").strip() or "The model"
+ response = "⚠️ " + EMPTY_RESPONSE_EXPLANATION.format(model=_model)
agent_messages = agent_result.get("messages", [])
logger.info(
"response ready: platform=%s chat=%s time=%.1fs api_calls=%d response=%d chars",
@@ -1814,10 +1823,13 @@ class GatewayTurnMixin:
return response
+ # Chat-side next steps keyed by HTTP status; Hermes commands only (/login is the gateway's own
+ # sign-in, `hermes login` / `hermes auth` the host equivalents).
_STATUS_HINTS = {
- 401: " Check your API key or run `claude /login` to refresh OAuth credentials.",
- 402: " Your API balance or quota is exhausted. Check your provider dashboard.",
- 529: " The API is temporarily overloaded. Please try again shortly.",
+ 401: (" Your sign-in to the AI model service has expired or the API key is wrong. "
+ "Use /login here, or run `hermes login` / `hermes auth` 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.",
}
async def _hmwa_agent_error_reply(self, e, event, source, session_entry, session_key, prepared):
@@ -1830,10 +1842,8 @@ class GatewayTurnMixin:
if status_code in {400, 500} and len(prepared.history) > 50:
# Context overflow / payload too large: a deterministic rejection (#107567), and the same
# no-grow rule as the persist path (#1630) — nothing is written into an oversized session.
- return (
- "⚠️ Session too large for the model's context window.\nUse /compact to "
- "compress the conversation, or /reset to start fresh."
- )
+ from gateway.run import _CONTEXT_OVERFLOW_REPLY
+ return _CONTEXT_OVERFLOW_REPLY
# Replay can coalesce inputs; only this input's durable marker establishes ownership.
try:
if prepared.message_text is not None and session_entry is not None:
@@ -1866,10 +1876,11 @@ class GatewayTurnMixin:
else:
status_hint = " Your plan's usage limit has been reached. Please wait until it resets."
elif status_code == 400:
- status_hint = " The request was rejected by the API."
+ status_hint = " The AI model service rejected the request."
return self._hmwa_add_failed_turn_notice(
- f"Sorry, I encountered an unexpected error.{status_hint}\n"
- "Try again or use /reset to start a fresh session.",
+ f"⚠️ Something went wrong and I couldn't finish this reply.{status_hint}\n"
+ "Use /retry to try again, or /new to start a fresh conversation. "
+ "Technical details are in the gateway log (`hermes logs`).",
self._PARTIAL_FAILED_TURN_NOTICE,
)
@@ -2214,7 +2225,8 @@ class GatewayTurnMixin:
if not runtime_kwargs.get("api_key"):
await adapter.send(
source.chat_id,
- f"❌ Background task {task_id} failed: no provider credentials configured.",
+ "❌ The background task couldn't start because no AI model sign-in is "
+ "configured. Use /login, or run `hermes setup` on the host.",
metadata=_thread_metadata,
)
return
@@ -2325,7 +2337,9 @@ class GatewayTurnMixin:
logger.exception("Background task %s failed", task_id)
with suppress(Exception):
await adapter.send(
- chat_id=source.chat_id, content=f"❌ Background task {task_id} failed: {e}",
+ chat_id=source.chat_id,
+ content=(f"❌ Your background task \"{_bg_prompt_preview(prompt)}\" failed before finishing. "
+ "Send /bg again to retry, or /agents to see what is still running."),
metadata=_thread_metadata,
)
@@ -3286,10 +3300,10 @@ class GatewayTurnMixin:
return
try:
await _warn_adapter.send(
- source.chat_id, f"⚠️ No activity for {int(worker.agent_warning // 60) or 1} min. "
- "If the agent does not respond soon, it will be timed out in "
- f"{int((worker.agent_timeout - worker.agent_warning) // 60) or 1} min. "
- "You can continue waiting or use /reset.",
+ source.chat_id, f"⚠️ I seem to be stuck (no activity for {int(worker.agent_warning // 60) or 1} min). "
+ "If nothing happens in the next "
+ f"{int((worker.agent_timeout - worker.agent_warning) // 60) or 1} min I'll give up on this task. "
+ "You can keep waiting, send /stop to cancel it, or /new to start a fresh conversation.",
metadata=_interim_metadata(_status_thread_metadata),
)
except Exception as _warn_err:
diff --git a/gateway/run_turn_runner.py b/gateway/run_turn_runner.py
index cc0824db66c..5713ad772f5 100644
--- a/gateway/run_turn_runner.py
+++ b/gateway/run_turn_runner.py
@@ -176,7 +176,7 @@ class TurnRunner:
if status in SUBAGENT_FAILURE_STATUSES and ctx._run_still_current():
line = format_subagent_failure_line(
kwargs.get("goal"), status, error=kwargs.get("summary") or preview,
- duration_seconds=kwargs.get("duration_seconds"),
+ duration_seconds=kwargs.get("duration_seconds"), failure_reason=kwargs.get("failure_reason"),
)
self._schedule(self._runner._deliver_platform_notice(ctx.source, line), "subagent failure notice scheduling error")
except Exception:
@@ -1351,6 +1351,7 @@ class TurnRunner:
"""Send the approval request from the agent thread: the adapter's interactive button
approvals (``send_exec_approval``) when available, else plain text with ``/approve`` steps."""
from gateway.run import _approval_send_outcome, _format_exec_approval_fallback, _interim_metadata, _redact_approval_command
+ from gateway.run_turn_runner_approval_settle import register_timeout_notice
ctx = self._ctx
adapter = ctx._status_adapter
# Slack's assistant_threads_setStatus disables the compose box, so the user can't type
@@ -1377,6 +1378,11 @@ class TurnRunner:
raise RuntimeError("send_exec_approval: loop unavailable")
outcome = _approval_send_outcome(fut, timeout=15)
if outcome == "sent":
+ # Without this, a card whose timer runs out keeps live buttons and nobody
+ # learns the command did NOT run (only the TUI registered a settle hook).
+ register_timeout_notice(
+ self, approval_data, command=cmd,
+ card_message_id=getattr(fut.result(timeout=0), "message_id", None))
return
if outcome == "ambiguous":
# Timeout ≠ failure: the card may have posted with a late ack. The prompt
@@ -1432,6 +1438,9 @@ class TurnRunner:
)
if fut is not None:
fut.result(timeout=15)
+ # No card to edit on the text path: the prompt has no buttons to drop and carries
+ # the /approve instructions, so the timeout notice is posted as a new message.
+ register_timeout_notice(self, approval_data, command=cmd, card_message_id=None)
except Exception as e:
logger.error("Failed to send approval request: %s", e)
@@ -1785,7 +1794,16 @@ class TurnRunner:
model, runtime_kwargs.get("provider"), ctx.session_key or "",
)
except Exception as exc:
- return {"final_response": f"⚠️ Provider authentication failed: {exc}", "messages": [], "api_calls": 0, "tools": []}
+ # Model/credential resolution failed before the turn began; the raw text (URLs, status
+ # codes) belongs in the log, and the chat gets the commands that fix it.
+ logger.warning("Model resolution failed for session %s: %s", ctx.session_key or "", exc)
+ return {
+ "final_response": (
+ "⚠️ I couldn't connect to the AI model service, so this message wasn't processed. "
+ "Use /login to sign in again, or /model to pick a different model. If it keeps "
+ "failing, run `hermes doctor` on the host."),
+ "messages": [], "api_calls": 0, "tools": [],
+ }
pr = runner._provider_routing
reasoning_config = runner._resolve_session_reasoning_config(source=ctx.source, session_key=ctx.session_key, model=model)
runner._reasoning_config = reasoning_config
diff --git a/gateway/run_turn_runner_approval_settle.py b/gateway/run_turn_runner_approval_settle.py
new file mode 100644
index 00000000000..6020209b3f0
--- /dev/null
+++ b/gateway/run_turn_runner_approval_settle.py
@@ -0,0 +1,81 @@
+"""Tell the chat when an exec-approval prompt times out (messaging platforms).
+
+``tools.approval_gateway_wait._await_gateway_decision`` calls ``entry.settle(reason)`` once the
+wait ends. Only the TUI registered such a hook, so on Telegram / Slack / WhatsApp a card whose
+timer ran out kept live buttons and the user never learned the command did NOT run. The turn
+runner registers the hook here right after the prompt was delivered.
+
+Best-effort by design: a failed notice is logged at debug — the approval already resolved as
+"no", and nothing here may block the agent thread.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Callable, Optional
+
+from gateway.platforms.base_exec_approval import approval_timeout_seconds, format_approval_timed_out_notice
+
+logger = logging.getLogger(__name__)
+
+
+def register_timeout_notice(
+ runner, approval_data: dict, *, command: str, card_message_id: Optional[str]) -> None:
+ """Arm a settle hook that posts the timed-out notice for ``approval_data['request_id']``.
+
+ ``runner`` is the ``TurnRunner`` (for ``_ctx`` and ``_schedule``); ``card_message_id`` is the
+ delivered BUTTON card's id when the adapter returned one, so the card itself is edited in place
+ (which also drops its buttons). The plain-text prompt passes ``None``: it has no buttons to
+ drop and rewriting it would erase the record of what was asked. ``command`` is the
+ already-redacted command shown to the user. The notice is skipped when the run is no longer
+ current (``ctx._run_still_current``).
+ """
+ from tools.approval import register_gateway_settle
+
+ request_id = approval_data.get("request_id")
+ session_key = runner._ctx.session_key or ""
+ if not request_id or not session_key:
+ return
+ timeout_s = approval_timeout_seconds()
+
+ def settle(reason: str) -> None:
+ if reason != "timeout":
+ return # answered / interrupted / notify_failed already produced their own feedback
+ # Same guard as every other late notice in TurnRunner: after /stop, /new or a restart the
+ # turn is over and this chat belongs to a newer run — do not edit or post into it.
+ still_current = getattr(runner._ctx, "_run_still_current", None)
+ if callable(still_current) and not still_current():
+ return
+ runner._schedule(
+ _post_timeout_notice(runner._ctx, command, card_message_id, timeout_s),
+ "Approval timeout notice scheduling error")
+
+ register_gateway_settle(session_key, request_id, settle)
+
+
+async def _post_timeout_notice(ctx, command: str, card_message_id: Optional[str], timeout_s: int) -> None:
+ from gateway.run import _interim_metadata
+
+ adapter = ctx._status_adapter
+ notice = format_approval_timed_out_notice(timeout_s)
+ metadata = _interim_metadata(ctx._status_thread_metadata)
+ try:
+ # Plain markdown, not the card's platform markup: ``edit_message`` re-formats it itself.
+ if card_message_id and await _edit_card(adapter, ctx._status_chat_id, card_message_id, f"{notice}\n```\n{command}\n```"):
+ return
+ await adapter.send(ctx._status_chat_id, notice, metadata=metadata)
+ except Exception:
+ logger.debug("Approval timeout notice failed", exc_info=True)
+
+
+async def _edit_card(adapter, chat_id: str, message_id: str, content: str) -> bool:
+ """Edit the card in place (drops the buttons on platforms whose edit replaces the markup)."""
+ edit: Optional[Callable[..., Any]] = getattr(adapter, "edit_message", None)
+ if edit is None:
+ return False
+ try:
+ result = await edit(chat_id, message_id, content)
+ except Exception:
+ logger.debug("Approval card edit failed; sending the notice as a new message", exc_info=True)
+ return False
+ return bool(getattr(result, "success", False))
diff --git a/gateway/session_stall.py b/gateway/session_stall.py
index 413176b09c8..9077c0a9de1 100644
--- a/gateway/session_stall.py
+++ b/gateway/session_stall.py
@@ -40,7 +40,8 @@ def format_session_stall_notification(idle_seconds: float) -> str:
See #72016.
"""
mins = max(1, int(idle_seconds // 60))
- return f"⚠️ Agent session appears stalled (last activity {mins} min ago). Try /new to reset."
+ return (f"⚠️ I seem to be stuck (no activity for {mins} min). Send /stop to cancel the current "
+ "task, or /new to start a fresh conversation.")
def _finite_float(value: Any) -> Optional[float]:
diff --git a/gateway/slash_commands_status.py b/gateway/slash_commands_status.py
index 5fe68be0a0b..f5de9c59084 100644
--- a/gateway/slash_commands_status.py
+++ b/gateway/slash_commands_status.py
@@ -68,8 +68,9 @@ async def _quiet(call, default=None):
return default
-HISTORY_UNREADABLE = ("⚠️ Conversation history is unreadable (state.db). "
- "This is not a new conversation — earlier messages exist but cannot be loaded.")
+HISTORY_UNREADABLE = ("⚠️ I can't read this conversation's history right now (your earlier messages "
+ "exist but cannot be loaded). Run `hermes doctor --fix` on the host, or use /new "
+ "to start fresh.")
def _quiet_sync(call, default=None):
diff --git a/hermes_cli/_parser.py b/hermes_cli/_parser.py
index ff726824181..a9067f50143 100644
--- a/hermes_cli/_parser.py
+++ b/hermes_cli/_parser.py
@@ -6,6 +6,8 @@ gateway, sessions, …) is built by ``hermes_cli/subcommands/<group>.py`` and wi
"""
import argparse
+import difflib
+import re
from functools import lru_cache
# `--profile` / `-p` is consumed by ``main._apply_profile_override`` before argparse runs
@@ -24,6 +26,13 @@ _VALUE_FLAGS_FALLBACK: frozenset[str] = frozenset({
_OPTIONAL_VALUE_FLAGS_FALLBACK: frozenset[str] = frozenset({"-c", "--continue"})
+def _cfg_path() -> str:
+ """``~/.hermes/config.yaml`` spelled for the active profile, for help text."""
+ from hermes_constants import display_hermes_home
+
+ return f"{display_hermes_home()}/config.yaml"
+
+
@lru_cache(maxsize=1)
def top_level_value_flag_sets() -> tuple[frozenset[str], frozenset[str]]:
"""(required-value, optional-value) top-level flags, derived from the REAL parser.
@@ -163,7 +172,7 @@ def _add_top_level_flags(parser: argparse.ArgumentParser) -> None:
inherited(parser, "--pass-session-id", action="store_true", default=False,
help="Include the session ID in the agent's system prompt")
inherited(parser, "--ignore-user-config", action="store_true", default=False,
- help="Ignore ~/.hermes/config.yaml and fall back to built-in defaults (credentials in .env are still loaded)")
+ help=f"Ignore {_cfg_path()} and fall back to built-in defaults (credentials in .env are still loaded)")
inherited(parser, "--ignore-rules", action="store_true", default=False,
help="Skip auto-injection of AGENTS.md, SOUL.md, .cursorrules, memory, and preloaded skills")
inherited(parser, "--safe-mode", action="store_true", default=False,
@@ -264,7 +273,7 @@ def _build_chat_parser(subparsers) -> argparse.ArgumentParser:
inherited(chat_parser, "--pass-session-id", action="store_true", default=SUPPRESS,
help="Include the session ID in the agent's system prompt")
inherited(chat_parser, "--ignore-user-config", action="store_true", default=SUPPRESS,
- help="Ignore ~/.hermes/config.yaml and fall back to built-in defaults (credentials in .env are still loaded). Useful for isolated CI runs, reproduction, and third-party integrations.")
+ help=f"Ignore {_cfg_path()} and fall back to built-in defaults (credentials in .env are still loaded). Useful for isolated CI runs, reproduction, and third-party integrations.")
inherited(chat_parser, "--ignore-rules", action="store_true", default=SUPPRESS,
help="Skip auto-injection of AGENTS.md, SOUL.md, .cursorrules, memory, and preloaded skills. Combine with --ignore-user-config for a fully isolated run.")
inherited(chat_parser, "--safe-mode", action="store_true", default=SUPPRESS,
@@ -280,6 +289,28 @@ def _build_chat_parser(subparsers) -> argparse.ArgumentParser:
return chat_parser
+class HermesArgumentParser(argparse.ArgumentParser):
+ """argparse parser whose unknown-subcommand error is three short lines, not a 70-name dump.
+
+ Stock argparse prints the full usage block plus ``(choose from 'chat', 'model', …)`` when
+ the first positional is not a registered subcommand. That buries the only useful fact
+ (the word is not a command) and offers no closest match. Every other error keeps the
+ stock usage + message shape.
+ """
+
+ def _check_value(self, action, value):
+ if isinstance(action, argparse._SubParsersAction) and value not in action.choices:
+ # ``self.prog`` is "hermes" at the top level and "hermes gateway" for a nested group
+ # (argparse hands add_parser() the parent's class), so the copy stays correct for both.
+ lines = [f"{self.prog}: '{value}' is not a `{self.prog}` command."]
+ close = difflib.get_close_matches(str(value), list(action.choices), n=3, cutoff=0.6)
+ if close:
+ lines.append(f"Did you mean: {', '.join(close)}?")
+ lines.append(f"Run `{self.prog} --help` to see all commands.")
+ self.exit(2, "\n".join(lines) + "\n")
+ super()._check_value(action, value)
+
+
def build_top_level_parser():
"""Build the top-level parser, the subparsers action, and the ``chat`` subparser.
@@ -287,9 +318,11 @@ def build_top_level_parser():
``chat_parser.set_defaults(func= cmd_chat)`` and registers further subparsers via
``subparsers.add_parser(...)``.
"""
- parser = argparse.ArgumentParser(
+ parser = HermesArgumentParser(
prog="hermes", description="Hermes Agent - AI assistant with tool-calling capabilities",
formatter_class=argparse.RawDescriptionHelpFormatter, epilog=_EPILOGUE)
_add_top_level_flags(parser)
- subparsers = parser.add_subparsers(dest="command", help="Command to run")
+ # metavar keeps the usage line to ``hermes [...] <command>`` instead of the brace list of
+ # every subcommand name; ``hermes --help`` still lists each command with its help row.
+ subparsers = parser.add_subparsers(dest="command", help="Command to run", metavar="<command>")
return parser, subparsers, _build_chat_parser(subparsers)
diff --git a/hermes_cli/active_sessions.py b/hermes_cli/active_sessions.py
index f159d64d09d..4247b3f3440 100644
--- a/hermes_cli/active_sessions.py
+++ b/hermes_cli/active_sessions.py
@@ -149,15 +149,17 @@ def _is_same_writer(entry: dict[str, Any], metadata: Optional[dict[str, Any]]) -
def session_already_owned_message(session_id: str, entry: dict[str, Any]) -> str:
+ """Refusal text for a session another live process holds.
+
+ Contract shared with the TUI/Desktop surfaces: the FIRST line is the plain user sentence
+ (no lease/pid/owner jargon); the second line is ``Details: ...`` for logs and bug reports.
+ """
surface = str(entry.get("surface") or "another surface")
- pid = entry.get("pid")
started = _optional_float(entry.get("started_at"))
- age = f", lease age {format_age(time.time() - started)}" if started else ""
+ age = f" {format_age(time.time() - started)} ago" if started else ""
return (
- f"Session {session_id} already has a live owner ({surface}, pid {pid}{age}). "
- "Its turn activity is unknown; an open lease does not mean a turn is running. "
- "Attach through a compatible owner, or close the session in its owning surface "
- "before resuming here. Do not delete a live owner's lease to force a takeover."
+ "This chat is open in another Hermes window/terminal. Use it there, or start a new chat here.\n"
+ f"Details: session {session_id} opened by {surface}{age}."
)
diff --git a/hermes_cli/auth.py b/hermes_cli/auth.py
index d4c15bb5e10..a66d94afcc9 100644
--- a/hermes_cli/auth.py
+++ b/hermes_cli/auth.py
@@ -1505,10 +1505,12 @@ def resolve_provider(
return "bedrock"
except ImportError:
pass # boto3 not installed
+ from hermes_constants import display_hermes_home
raise AuthError(
- "No inference provider configured. Run 'hermes model' to choose a "
- "provider and model, or set an API key (OPENROUTER_API_KEY, "
- "OPENAI_API_KEY, etc.) in ~/.hermes/.env.",
+ "Hermes is not connected to any AI provider yet. Run `hermes model` to pick one (the free "
+ "Nous tier needs no API key), type `/login` in chat, or add a key with "
+ f"`hermes auth add <provider>`. (Advanced: put an API key such as OPENROUTER_API_KEY in "
+ f"{display_hermes_home()}/.env.)",
code="no_provider_configured")
diff --git a/hermes_cli/auth_commands.py b/hermes_cli/auth_commands.py
index 93833f4841c..15383a8e747 100644
--- a/hermes_cli/auth_commands.py
+++ b/hermes_cli/auth_commands.py
@@ -131,6 +131,18 @@ def _is_known_provider(provider: str, configured_provider: dict | None) -> bool:
or provider.startswith(CUSTOM_POOL_PREFIX) or configured_provider is not None)
+def _unknown_provider_exit(provider: str) -> SystemExit:
+ """Did-you-mean over the known provider ids plus the two commands that list/pick them."""
+ import difflib
+ known = sorted(set(PROVIDER_REGISTRY) | {"openrouter"}
+ | {entry["name"] for entry in _get_custom_provider_entries()})
+ close = difflib.get_close_matches(provider, known, n=3, cutoff=0.5)
+ hint = f" Did you mean {', '.join(close)}?" if close else ""
+ return SystemExit(
+ f"Unknown provider '{provider}'.{hint} Run `hermes auth` to see the provider list, or "
+ "`hermes model` to pick one interactively.")
+
+
def _display_source(source: str) -> str:
return source.split(":", 1)[1] if source.startswith("manual:") else source
@@ -348,7 +360,7 @@ def auth_add_command(args) -> None:
provider = _normalize_provider(getattr(args, "provider", ""))
configured_provider = _configured_provider_entry(provider)
if not _is_known_provider(provider, configured_provider):
- raise SystemExit(f"Unknown provider: {provider}")
+ raise _unknown_provider_exit(provider)
if configured_provider is not None:
_migrate_legacy_custom_pool_key(provider, configured_provider["pool_key"])
@@ -573,10 +585,12 @@ def auth_refresh_command(args) -> None:
refreshed = pool.try_refresh_matching(credential_id=matched.id)
if refreshed is None:
after = next((e for e in pool.entries() if e.id == matched.id), None)
- state = "removed from pool" if after is None else (after.last_status or "unknown")
+ label = PROVIDER_REGISTRY[provider].name if provider in PROVIDER_REGISTRY else provider
+ state = ("it was removed from the pool" if after is None
+ else "the saved session is no longer valid")
raise SystemExit(
- f"Refresh failed for {provider} credential #{index} ({matched.label}); "
- f"status now: {state}.")
+ f"Could not renew the {label} sign-in for credential #{index} ({matched.label}); {state}. "
+ f"Sign in again with `hermes auth add {provider} --type oauth`.")
status = refreshed.last_status or "ok"
if status == "ok":
print(f"Refreshed {provider} credential #{index} ({refreshed.label}); status: ok")
@@ -721,7 +735,7 @@ def _interactive_add() -> None:
provider = _pick_provider("Provider to add credential for")
configured_provider = _configured_provider_entry(provider)
if not _is_known_provider(provider, configured_provider):
- raise SystemExit(f"Unknown provider: {provider}")
+ raise _unknown_provider_exit(provider)
auth_type = "api_key"
if provider in _OAUTH_CAPABLE_PROVIDERS:
diff --git a/hermes_cli/auth_device_flow.py b/hermes_cli/auth_device_flow.py
index ccd5b1b41b5..44367552940 100644
--- a/hermes_cli/auth_device_flow.py
+++ b/hermes_cli/auth_device_flow.py
@@ -358,9 +358,11 @@ def _poll_for_token(
raise ValueError("Token response did not include access_token")
def _error(_response, error_payload) -> Exception:
- error_code = error_payload.get("error", "")
- description = error_payload.get("error_description") or "Unknown authentication error"
- return RuntimeError(f"{error_code}: {description}")
+ # Plain copy per OAuth error code; the raw ``code: description`` stays on a Details line.
+ from hermes_cli.auth_error_copy import device_flow_error
+ return device_flow_error(
+ str(error_payload.get("error", "") or ""),
+ str(error_payload.get("error_description") or "Unknown authentication error"))
return _poll_device_token_generic(
lambda: client.post(
diff --git a/hermes_cli/auth_error_copy.py b/hermes_cli/auth_error_copy.py
new file mode 100644
index 00000000000..17a8e9da344
--- /dev/null
+++ b/hermes_cli/auth_error_copy.py
@@ -0,0 +1,118 @@
+"""Plain-language copy for sign-in and provider-setup failures (CLI).
+
+One table of ``(predicate, lead sentence)`` classifies an exception into a sentence a first-time
+user can act on; the raw exception is demoted to a ``Details:`` line so nothing is lost for
+support. Callers print ``sign_in_failure_lines(...)`` / ``provider_setup_failure_lines(...)``
+line by line.
+"""
+
+from __future__ import annotations
+
+from typing import Callable, Sequence, Tuple
+
+# httpx class names and stdlib bases that mean "the request never got a usable answer".
+_NETWORK_ERROR_TYPES = frozenset({
+ "ConnectError", "ConnectTimeout", "ReadTimeout", "PoolTimeout", "WriteTimeout", "TimeoutException",
+ "RemoteProtocolError", "ReadError", "ProxyError", "UnsupportedProtocol", "NetworkError",
+})
+
+# OAuth device-flow error codes (RFC 8628 §3.5) -> plain copy. ``{retry}`` is the retry command.
+DEVICE_FLOW_ERROR_COPY = {
+ "expired_token": (
+ "The sign-in code expired before it was approved in the browser. Run `{retry}` to get a new code."),
+ "access_denied": (
+ "Sign-in was declined in the browser. Run `{retry}` to try again, or `hermes model` to pick a "
+ "different provider."),
+ "invalid_grant": (
+ "The sign-in code was not accepted by the server. Run `{retry}` to get a new code."),
+ "invalid_client": (
+ "The server did not recognize this copy of Hermes. Run `hermes update`, then `{retry}` again."),
+}
+
+
+class SignInCopyError(RuntimeError):
+ """Exception whose ``str()`` is already user copy (lead line + ``Details:`` line)."""
+
+ def __init__(self, message: str, *, oauth_error_code: str = "") -> None:
+ super().__init__(message)
+ self.oauth_error_code = oauth_error_code
+
+
+def is_network_error(exc: BaseException) -> bool:
+ """True for connection/DNS/timeout failures from httpx, requests or the stdlib."""
+ if isinstance(exc, SignInCopyError):
+ return False
+ names = {cls.__name__ for cls in type(exc).__mro__}
+ return bool(names & _NETWORK_ERROR_TYPES) or isinstance(exc, (ConnectionError, TimeoutError))
+
+
+def is_cancelled(exc: BaseException) -> bool:
+ return isinstance(exc, (KeyboardInterrupt, EOFError)) or (
+ isinstance(exc, SystemExit) and exc.code in (130, None, 0))
+
+
+def device_flow_error(code: str, description: str, *, retry_command: str = "hermes portal") -> SignInCopyError:
+ """Exception for an OAuth device-flow error code whose text is already user-facing.
+
+ Unknown codes keep the server's description as the lead (it is the only information available)
+ but still name the retry command.
+ """
+ lead = DEVICE_FLOW_ERROR_COPY.get(code, "").format(retry=retry_command)
+ if not lead:
+ lead = (f"Sign-in did not complete: {description or 'the server rejected the request'}. "
+ f"Run `{retry_command}` to try again.")
+ details = f"{code}: {description}" if code else description
+ return SignInCopyError(f"{lead}\n Details: {details}" if details else lead, oauth_error_code=code)
+
+
+def _details_line(exc: BaseException) -> str:
+ text = str(exc).strip() or type(exc).__name__
+ return f" Details: {text}"
+
+
+_Rule = Tuple[Callable[[BaseException], bool], str]
+
+
+def _classify(exc: BaseException, rules: Sequence[_Rule], other: str) -> str:
+ return next((copy for pred, copy in rules if pred(exc)), other)
+
+
+def sign_in_failure_lines(
+ exc: BaseException, *, service_host: str = "portal.nousresearch.com", retry_command: str = "hermes portal",
+) -> list:
+ """Lines to print when a device-code / browser sign-in fails for any non-timeout reason."""
+ if isinstance(exc, SignInCopyError):
+ return str(exc).splitlines()
+ rules: Sequence[_Rule] = (
+ (is_cancelled, "Sign-in was cancelled. Run `{retry}` when you want to try again."),
+ (is_network_error,
+ "Could not sign in: Hermes could not reach {host}. Check your internet connection or proxy, "
+ "then run `{retry}` again."),
+ )
+ lead = _classify(
+ exc, rules,
+ "Could not sign in. Run `{retry}` to try again, or `hermes model` to pick a different provider.")
+ lines = [lead.format(host=service_host, retry=retry_command)]
+ if not is_cancelled(exc):
+ lines.append(_details_line(exc))
+ return lines
+
+
+def provider_setup_failure_lines(exc: BaseException, *, retry_command: str = "hermes model") -> list:
+ """Lines to print when the setup wizard's provider step fails: reason, that nothing was saved,
+ and how to retry."""
+ nothing_saved = (
+ "Your provider settings were not changed. Continue the wizard now and run "
+ f"`{retry_command}` afterwards to try again.")
+ if isinstance(exc, SignInCopyError):
+ lead, *details = str(exc).splitlines()
+ return [f"Could not finish connecting a provider: {lead[0].lower()}{lead[1:]}", nothing_saved, *details]
+ rules: Sequence[_Rule] = (
+ (is_cancelled, "sign-in was cancelled"),
+ (is_network_error, "no internet connection, or the provider could not be reached"),
+ )
+ reason = _classify(exc, rules, "something went wrong while talking to the provider")
+ lines = [f"Could not finish connecting a provider ({reason}).", nothing_saved]
+ if not is_cancelled(exc):
+ lines.append(_details_line(exc))
+ return lines
diff --git a/hermes_cli/auth_nous.py b/hermes_cli/auth_nous.py
index 698d19c3a21..4202b95a3ca 100644
--- a/hermes_cli/auth_nous.py
+++ b/hermes_cli/auth_nous.py
@@ -1582,5 +1582,13 @@ def _login_nous(args, pconfig: ProviderConfig) -> None:
print("\nLogin cancelled.")
raise SystemExit(130)
except Exception as exc:
- print(f"Login failed: {exc}")
+ from hermes_cli.auth_error_copy import sign_in_failure_lines
+ logger.debug("nous login failed: %r", exc)
+ print()
+ for line in sign_in_failure_lines(exc, service_host=_portal_host(getattr(args, "portal_url", None))):
+ print(line)
raise SystemExit(1)
+
+
+def _portal_host(portal_url: Optional[str]) -> str:
+ return urlparse(portal_url or DEFAULT_NOUS_PORTAL_URL).hostname or "portal.nousresearch.com"
diff --git a/hermes_cli/backup.py b/hermes_cli/backup.py
index a7cf772bd8e..d05d3c592d3 100644
--- a/hermes_cli/backup.py
+++ b/hermes_cli/backup.py
@@ -35,6 +35,13 @@ logger = logging.getLogger(__name__)
# snapshots (see ``create_quick_snapshot``); defined here because the exclusion set needs it.
_QUICK_SNAPSHOTS_DIR = "state-snapshots"
+
+def _snapshot_recovery_hint() -> str:
+ """How to restore a state snapshot. There is no `hermes snapshot` subcommand — only the /snapshot
+ slash command inside a `hermes` session (hermes_cli/commands.py)."""
+ return ("To restore a newer snapshot, start `hermes` in a terminal and run `/snapshot list`, then "
+ "`/snapshot restore <id>` (CLI only).")
+
# Directory names to skip (matched against each path component). ``hermes-agent`` only matches at
# the root (``_should_exclude``) so skill dirs like ``skills/.../hermes-agent/`` survive. The
# dependency/cache entries matter: one plugin venv or pip/uv cache under HERMES_HOME walked
@@ -1002,8 +1009,7 @@ def run_import(args) -> None:
for rel, before, after in db_shrunk:
print(f" {rel}: {before[0]} session(s) / {before[1]} message(s)"
f" -> {after[0]} / {after[1]}")
- print(" Anything recorded after the backup was taken is not in it. "
- "Recover from a newer backup or snapshot: hermes snapshot list")
+ print(f" Anything recorded after the backup was taken is not in it. {_snapshot_recovery_hint()}")
if skipped_runtime:
_print_capped(f"\n Preserved {len(skipped_runtime)} runtime state "
f"file(s) (kept this machine's, not the backup's):",
@@ -1229,7 +1235,7 @@ def _create_quick_snapshot_locked(
# Surface on stdout: a log-and-continue made a missing state.db backup look like a
# successful pre-update snapshot (#68474).
print(f" ⚠ CRITICAL: could not snapshot DB file(s): {', '.join(failed_dbs)}\n"
- f" ⚠ If sessions disappear after update, check {root} and run: hermes snapshot list")
+ f" ⚠ If sessions disappear after the update, check {root}. {_snapshot_recovery_hint()}")
logger.error("Quick snapshot failed to capture DB file(s): %s", ", ".join(failed_dbs))
if not manifest:
shutil.rmtree(staging_dir, ignore_errors=True)
diff --git a/hermes_cli/banner.py b/hermes_cli/banner.py
index 106fd0a6688..1ffce168d84 100644
--- a/hermes_cli/banner.py
+++ b/hermes_cli/banner.py
@@ -2,6 +2,7 @@
import json
import logging
import os
+import re
import shutil
import subprocess
import sys
@@ -756,7 +757,18 @@ def _mcp_server_line(srv: dict, *, dim: str, text: str) -> str:
"configured": f"[dim {dim}]— configured[/]"}.get(status)
if suffix is not None:
return f"[dim {dim}]{name}[/] [dim]({transport})[/] {suffix}"
- return f"[red]{name}[/] [dim]({transport})[/] [red]— failed[/]"
+ return _mcp_failed_line(name, transport, srv.get("error"))
+
+
+def _mcp_failed_line(name: str, transport: str, error: Optional[str]) -> str:
+ """Failed MCP connect: the short reason (already humanised by ``_format_connect_error``) and the
+ exact next command, so 'failed' is never the whole story."""
+ from rich.markup import escape
+ reason = escape(" ".join(str(error or "").split())[:120]) or "no details recorded"
+ next_cmd = (f"hermes mcp login {name}" if re.search(r"\b401\b|unauthori[sz]ed", reason, re.I)
+ else f"hermes mcp test {name}")
+ return (f"[red]{name}[/] [dim]({transport})[/] [red]— could not connect:[/] {reason} "
+ f"[dim]— run `{next_cmd}`[/]")
def _truncate_tool_names(tool_names: List[str]) -> List[Optional[str]]:
diff --git a/hermes_cli/cli_agent_setup_mixin.py b/hermes_cli/cli_agent_setup_mixin.py
index c780085ff71..3fedeb9be7a 100644
--- a/hermes_cli/cli_agent_setup_mixin.py
+++ b/hermes_cli/cli_agent_setup_mixin.py
@@ -613,7 +613,8 @@ class CLIAgentSetupMixin:
return True
except Exception as e:
console = ChatConsole()
- console.print(f"[bold red]Failed to initialize agent: {e}[/]")
+ from hermes_cli.cli_chat_error_copy import agent_init_failure_message
+ console.print(f"[bold red]{_escape(agent_init_failure_message(e))}[/]")
from hermes_constants import partial_update_hint
for line in partial_update_hint(e):
console.print(line)
diff --git a/hermes_cli/cli_chat_error_copy.py b/hermes_cli/cli_chat_error_copy.py
new file mode 100644
index 00000000000..2327b21616b
--- /dev/null
+++ b/hermes_cli/cli_chat_error_copy.py
@@ -0,0 +1,65 @@
+"""Plain-language copy for chat-turn failures shown in the CLI response panel.
+
+The chat panel used to echo ``Error: HTTP 401: Invalid API key`` as the assistant's answer. These
+helpers map the classifier verdict (``agent/error_classifier.py``) to WHAT happened + WHAT TO DO,
+and demote the raw provider text to a ``Details:`` line.
+"""
+
+from __future__ import annotations
+
+_SUMMARY_LIMIT = 120
+
+# FailoverReason.value -> plain copy. ``{provider}`` / ``{model}`` are filled at render time.
+_REASON_COPY: dict[str, str] = {
+ "auth": "Your {provider} key was rejected. Run `hermes model` to re-enter it.",
+ "auth_permanent": "Your {provider} key was rejected. Run `hermes model` to re-enter it.",
+ "billing": "Your {provider} account is out of credit. Top up at the provider, or run /model to switch.",
+ "model_not_found": "'{model}' isn't available on {provider}. Run /model to pick a valid model.",
+ "rate_limit": "Rate limited by {provider}; wait a minute or /model to switch.",
+ "upstream_rate_limit": "Rate limited by {provider}; wait a minute or /model to switch.",
+ "overloaded": "{provider} is overloaded right now. Send /retry in a moment, or /model to switch.",
+ "server_error": "{provider} had an internal error. Send /retry in a moment, or /model to switch.",
+ "timeout": "{provider} did not answer in time. Send /retry, or /model to switch.",
+}
+_UNKNOWN_COPY = "The model request failed. Run /model to switch or `hermes doctor` to check the setup."
+
+
+def _short(text: str, limit: int = _SUMMARY_LIMIT) -> str:
+ first = (text or "").strip().splitlines()[0] if (text or "").strip() else ""
+ return first if len(first) <= limit else first[: limit - 1].rstrip() + "…"
+
+
+def chat_error_response(
+ error: Exception | str, *, provider: str = "", model: str = "", failure_reason: str | None = None,
+) -> str:
+ """Two-line panel text: plain sentence with the fix command, then ``Details: <raw>``.
+
+ ``failure_reason`` is the verdict the turn loop already stamped on its result
+ (``agent/turn_failure_copy.stamp_failure``). When present it is used as-is instead of
+ re-classifying a summarised string (which has no status code and almost always lands on
+ 'unknown'); for the loop's own site codes the ``error`` text is already the user-facing copy,
+ so it is returned verbatim rather than wrapped and demoted to a Details line."""
+ reason = str(failure_reason or "").strip()
+ if reason:
+ from agent.turn_failure_copy import SITE_FAILURE_CODES
+
+ text = str(error or "").strip()
+ if reason in SITE_FAILURE_CODES and text:
+ return text
+ else:
+ from agent.error_classifier import classify_api_error
+
+ exc = error if isinstance(error, Exception) else Exception(str(error))
+ reason = classify_api_error(exc, provider=provider or "", model=model or "").reason.value
+ copy = _REASON_COPY.get(reason, _UNKNOWN_COPY)
+ lead = copy.format(provider=provider or "the provider", model=model or "the current model")
+ return f"{lead}\nDetails: {_short(str(error), 300)}"
+
+
+def agent_init_failure_message(error: BaseException) -> str:
+ """Copy for a failed AIAgent build on first message: the user's turn was dropped."""
+ return (
+ f"Hermes couldn't start the model connection: {_short(str(error)) or type(error).__name__}. "
+ "Your message was not sent. Run `hermes doctor` to check the setup, "
+ "or /model to pick a different provider."
+ )
diff --git a/hermes_cli/cli_chat_turn_mixin.py b/hermes_cli/cli_chat_turn_mixin.py
index e5e17e9726c..ef0070a4e02 100644
--- a/hermes_cli/cli_chat_turn_mixin.py
+++ b/hermes_cli/cli_chat_turn_mixin.py
@@ -331,8 +331,12 @@ class CLIChatTurnMixin:
except Exception as exc:
logging.error("run_conversation raised: %s", exc, exc_info=True)
_summary = getattr(self.agent, '_summarize_api_error', lambda e: str(e)[:300])(exc)
+ from hermes_cli.cli_chat_error_copy import chat_error_response
turn.result = {
- "final_response": f"Error: {_summary}", "messages": [], "api_calls": 0,
+ "final_response": chat_error_response(
+ exc, provider=str(getattr(self.agent, "provider", "") or self.provider or ""),
+ model=str(getattr(self.agent, "model", "") or self.model or "")),
+ "messages": [], "api_calls": 0,
"completed": False, "failed": True, "error": _summary,
}
finally:
@@ -476,7 +480,12 @@ class CLIChatTurnMixin:
response = turn.result.get("final_response", "") if turn.result else ""
# "failed"/"partial" with an empty final_response: no usable answer.
if turn.result and (turn.result.get("failed") or turn.result.get("partial")) and not response:
- response = f"Error: {turn.result.get('error', 'Unknown error')}"
+ from hermes_cli.cli_chat_error_copy import chat_error_response
+ response = chat_error_response(
+ str(turn.result.get("error") or "Unknown error"),
+ provider=str(getattr(self.agent, "provider", "") or self.provider or ""),
+ model=str(getattr(self.agent, "model", "") or self.model or ""),
+ failure_reason=turn.result.get("failure_reason"))
# Stop continuous voice on persistent errors (e.g. 429) — else error→record→error loops.
if self._voice_continuous:
self._voice_continuous = False
diff --git a/hermes_cli/cli_commands_mixin.py b/hermes_cli/cli_commands_mixin.py
index d0e050471d0..b7c0c9c0a9a 100644
--- a/hermes_cli/cli_commands_mixin.py
+++ b/hermes_cli/cli_commands_mixin.py
@@ -357,7 +357,7 @@ def _without_session_meta(messages) -> list:
def _db_unavailable_line() -> str:
from hermes_state import format_session_db_unavailable
- return f" {format_session_db_unavailable()}"
+ return f" {format_session_db_unavailable(details=True)}"
def _print_side_result_panel(cli, *, header_lines, body, title_suffix, empty_note, console=None) -> None:
diff --git a/hermes_cli/cli_loops_mixin.py b/hermes_cli/cli_loops_mixin.py
index 75c35b2cc40..29f3ba824fb 100644
--- a/hermes_cli/cli_loops_mixin.py
+++ b/hermes_cli/cli_loops_mixin.py
@@ -116,7 +116,7 @@ class CLILoopsMixin:
if len(parts) == 1:
# No argument: show current title and session ID.
if not self._session_db:
- _cprint(f" {format_session_db_unavailable()}")
+ _cprint(f" {format_session_db_unavailable(details=True)}")
return
_cprint(f" Session ID: {self.session_id}")
session = self._session_db.get_session(self.session_id)
@@ -132,7 +132,7 @@ class CLILoopsMixin:
_cprint(" Usage: /title <your session title>")
return
if not self._session_db:
- _cprint(f" {format_session_db_unavailable()}")
+ _cprint(f" {format_session_db_unavailable(details=True)}")
return
# Sanitize early so feedback matches what gets stored. A rejection (e.g. too
# long) prints that one reason and stops — never a second, contradictory
diff --git a/hermes_cli/cli_unknown_command.py b/hermes_cli/cli_unknown_command.py
new file mode 100644
index 00000000000..2c955494c38
--- /dev/null
+++ b/hermes_cli/cli_unknown_command.py
@@ -0,0 +1,19 @@
+"""Copy for an unknown slash command: says nothing was sent and suggests a near-miss."""
+
+from __future__ import annotations
+
+import difflib
+from collections.abc import Iterable
+
+
+def unknown_command_lines(typed: str, known: Iterable[str]) -> tuple[str, str]:
+ """(lead line, pointer line) for a slash token with no handler.
+
+ ``known`` holds names WITH the leading slash (``hermes_cli.commands.COMMANDS`` keys plus skill
+ commands). A close match (typo) becomes ``Did you mean /model?``; prefix expansion already ran
+ before this, so only fuzzy matches are considered here.
+ """
+ base = typed.split()[0] if typed.split() else typed
+ close = difflib.get_close_matches(base, list(known), n=1, cutoff=0.6)
+ hint = f" Did you mean {close[0]}?" if close else ""
+ return (f"Unknown command {base} — nothing was sent.{hint}", "Type /help for the full list.")
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index d5d26ac68b0..8db76528c96 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -50,18 +50,36 @@ class InvalidUserConfigError(RuntimeError):
_PARSE_FAILURE_FALLBACK_MSG = {
- "last-known-good": (
- "Keeping the previously loaded config for this process — "
- "edits to config.yaml are being IGNORED until the YAML is fixed."),
- "last-known-good-backup": (
- "Loading the LAST KNOWN GOOD copy from backups/config/ instead — edits to config.yaml "
- "since that copy are being IGNORED until the YAML is fixed."),
- "refuse-write": (
- "REFUSING to write config.yaml so the existing file is preserved. "
- "Fix the YAML (hermes config edit) and retry.")}
+ "last-known-good": "Hermes is running on the settings it loaded before the edit until it is fixed, so recent changes are not applied.",
+ "last-known-good-backup": "Hermes is running on your last good settings until it is fixed, so recent changes are not applied.",
+ "refuse-write": "Nothing was written, so the existing file is preserved."}
_PARSE_FAILURE_DEFAULTS_MSG = (
- "Falling back to default config — every user override (auxiliary providers, fallback chain, "
- "model settings) is being IGNORED. Fix the YAML and restart.")
+ "Hermes is running on default settings until it is fixed, so none of your saved settings are applied.")
+_PARSE_FAILURE_REPAIR_MSG = "Open it with `hermes config edit`, fix {where}, then run `hermes config check`."
+
+
+def _yaml_error_location(exc: Exception) -> str:
+ """``"line 12"`` from a PyYAML problem mark (1-based), else ``""``."""
+ mark = getattr(exc, "problem_mark", None) or getattr(exc, "context_mark", None)
+ line = getattr(mark, "line", None)
+ return f"line {line + 1}" if isinstance(line, int) else ""
+
+
+def _yaml_error_details(exc: Exception) -> str:
+ """Single-line ``Details:`` text: the PyYAML problem, or the exception's first line."""
+ problem = getattr(exc, "problem", None)
+ text = f"{problem}" if problem else str(exc).strip()
+ return " ".join(text.split())
+
+
+def format_config_parse_failure(config_path: Path, exc: Exception, *, fallback: str = "defaults") -> str:
+ """User copy for an unparseable config.yaml: what happened, what Hermes is doing, how to fix.
+ Only the problem line/column is printed; the raw PyYAML text goes to a ``Details:`` line."""
+ where = _yaml_error_location(exc)
+ at = f" at {where}" if where else ""
+ fallback_msg = _PARSE_FAILURE_FALLBACK_MSG.get(fallback, _PARSE_FAILURE_DEFAULTS_MSG)
+ repair = _PARSE_FAILURE_REPAIR_MSG.format(where=where or "the problem")
+ return f"Your settings file ({config_path}) has a formatting error{at}. {fallback_msg} {repair}"
def _warn_config_parse_failure(
@@ -84,13 +102,12 @@ def _warn_config_parse_failure(
_CONFIG_PARSE_WARNED.add(key)
from hermes_cli.config_backups import backup_config
backup_path = backup_config(config_path, "corrupt")
- msg = f"Failed to parse {config_path}: {exc}. " + _PARSE_FAILURE_FALLBACK_MSG.get(
- fallback, _PARSE_FAILURE_DEFAULTS_MSG)
+ msg = format_config_parse_failure(config_path, exc, fallback=fallback)
if backup_path is not None:
- msg += f" A copy of the corrupted file was saved to {backup_path}."
- logger.warning(msg)
+ msg += f" A copy of the broken file was saved to {backup_path}."
+ logger.warning("%s Details: %s", msg, _yaml_error_details(exc))
try:
- sys.stderr.write(f"⚠️ hermes config: {msg}\n")
+ sys.stderr.write(f"⚠️ hermes config: {msg}\n Details: {_yaml_error_details(exc)}\n")
sys.stderr.flush()
except Exception:
pass
@@ -495,12 +512,14 @@ def require_parseable_user_config(*, ignore_user_config: bool = False) -> None:
from hermes_cli.config_backups import backup_config
backup_path = backup_config(config_path, "corrupt")
+ where = _yaml_error_location(parse_error)
message = (
- f"Refusing non-interactive startup because {config_path} is invalid: "
- f"{parse_error}. Repair the file or pass --ignore-user-config to "
- "intentionally run with built-in defaults.")
+ f"Hermes stopped because your settings file ({config_path}) has a formatting error"
+ f"{f' at {where}' if where else ''}. Fix it with `hermes config edit` and check with "
+ "`hermes config check`, or add --ignore-user-config to run once with default settings.")
if backup_path is not None:
- message += f" A copy was saved to {backup_path}."
+ message += f" A copy of the broken file is at {backup_path}."
+ message += f" Details: {_yaml_error_details(parse_error)}"
logger.error(message)
raise InvalidUserConfigError(message) from parse_error
@@ -1935,11 +1954,23 @@ def read_raw_config_readonly() -> Dict[str, Any]:
def _refuse_overwrite(config_path: Path, reason: str, exc: Exception, fix: str) -> RuntimeError:
- return RuntimeError(f"Refusing to overwrite {config_path}: existing config.yaml {reason} ({exc}). {fix}")
+ """Error for a write that must not replace an existing config.yaml. Plain lead + ``Details:``."""
+ where = _yaml_error_location(exc)
+ at = f" ({where})" if where else ""
+ return RuntimeError(
+ f"Your settings file ({config_path}) {reason}{at}, so this change was not saved. {fix} "
+ f"Details: {_yaml_error_details(exc)}")
+
+
+def _backups_dir_display() -> str:
+ from hermes_constants import display_hermes_home
+ return f"{display_hermes_home()}/backups/config/"
_FIX_PERMS = "Fix the file permissions or move it aside first."
-_FIX_YAML = "Fix the file or restore a copy from backups/config/ first."
+_FIX_YAML = (
+ "Fix it with `hermes config edit` and check with `hermes config check`, or copy the newest good "
+ "file from {backups} over config.yaml.")
def require_readable_config_before_write(config_path: Optional[Path] = None) -> Dict[str, Any]:
@@ -1964,16 +1995,16 @@ def require_readable_config_before_write(config_path: Optional[Path] = None) ->
raise _refuse_overwrite(config_path, "cannot be read", exc, _FIX_PERMS) from exc
except Exception as exc:
_warn_config_parse_failure(config_path, exc, fallback="refuse-write")
- raise _refuse_overwrite(config_path, "is not valid YAML", exc, _FIX_YAML) from exc
+ raise _refuse_overwrite(
+ config_path, "has a formatting error", exc, _FIX_YAML.format(backups=_backups_dir_display())) from exc
if loaded is None:
return {}
if not isinstance(loaded, dict):
exc = TypeError(f"top-level YAML must be a mapping, got {type(loaded).__name__}")
_warn_config_parse_failure(config_path, exc, fallback="refuse-write")
- raise RuntimeError(
- f"Refusing to overwrite {config_path}: top-level YAML must be a mapping, got "
- f"{type(loaded).__name__}. Fix the file or restore a copy from backups/config/ first."
- ) from exc
+ raise _refuse_overwrite(
+ config_path, f"must start with settings names, but its top level is a {type(loaded).__name__}",
+ exc, _FIX_YAML.format(backups=_backups_dir_display())) from exc
return loaded
diff --git a/hermes_cli/cron.py b/hermes_cli/cron.py
index d2258589c96..fc58215cd95 100644
--- a/hermes_cli/cron.py
+++ b/hermes_cli/cron.py
@@ -168,10 +168,11 @@ def _last_run_display(job: Dict[str, Any]) -> str:
if last_status == "ok":
return color("ok", Colors.GREEN)
if last_status == "delivery_queued":
- return color("delivery_queued: completion unverified; do not resend", Colors.YELLOW)
+ return color("finished; delivery is still in progress", Colors.YELLOW)
if last_status == "delivery_failed":
# Agent succeeded but the result never reached the user — not green; last_error is None.
- return color(f"delivery_failed: {job.get('last_delivery_error') or '?'}", Colors.YELLOW)
+ return color(f"ran, but the result was not delivered ({_short_reason(job.get('last_delivery_error'))}). "
+ f"{_delivery_fix_hint(job)}", Colors.YELLOW)
display = color(f"{last_status}: {job.get('last_error', '?')}", Colors.RED)
streak = int(job.get("failure_streak") or 0)
if streak >= 2:
@@ -215,13 +216,36 @@ def _job_rows(job: Dict[str, Any]) -> List[tuple[str, str]]:
] + [(label, value) for label, value in optional if value]
+def _short_reason(text: Any, limit: int = 120) -> str:
+ """First line of an adapter/error blob, whitespace-collapsed and capped, or 'no details'."""
+ first = str(text or "").strip().splitlines()
+ reason = " ".join(first[0].split()) if first else ""
+ return (reason[: limit - 1] + "…") if len(reason) > limit else (reason or "no details")
+
+
+def _delivery_fix_hint(job: Dict[str, Any]) -> str:
+ return (f"Check the target with `hermes cron status` or change it with "
+ f"`hermes cron edit {job.get('id', '<id>')} --deliver <target>`.")
+
+
+def _missed_fire_line(job: Dict[str, Any], fire_err: Dict[str, Any]) -> str:
+ """A scheduled fire that never reached the runner: what was skipped, when, and how to run it now.
+
+ The stored ``detail`` is operator text (loopback / api_server adapter); keep it as a dim
+ second sentence and lead with the human cause (the gateway was unreachable)."""
+ return (f"{color('⚠ A scheduled run was skipped', Colors.RED)} at {fire_err.get('at', '?')}: the messaging "
+ f"gateway was unreachable. Run `hermes gateway restart`, then `hermes cron run {job.get('id', '<id>')}` "
+ f"to run it now. {color('Details: ' + _short_reason(fire_err.get('detail')), Colors.DIM)}")
+
+
def _job_warnings(job: Dict[str, Any]) -> List[str]:
"""Delivery / fire warning lines for one job in ``cron list``."""
lines = []
if queued := job.get("last_delivery_queued"):
- lines.append(f"Delivery queued (completion unverified; do not resend): {queued}")
+ lines.append(f"Delivery still in progress (the result was handed off but not confirmed yet): {queued}")
if job.get("last_delivery_error"):
- lines.append(f"{color('⚠ Delivery failed:', Colors.YELLOW)} {job['last_delivery_error']}")
+ lines.append(f"{color('⚠ The result was not delivered:', Colors.YELLOW)} "
+ f"{_short_reason(job['last_delivery_error'])}. {_delivery_fix_hint(job)}")
# A live adapter acked the last send but returned no message_id / raw_response
# (Slack/Matrix/Mattermost shape): accepted as delivered, but say so here.
if unverified := job.get("last_delivery_unverified"):
@@ -229,8 +253,7 @@ def _job_warnings(job: Dict[str, Any]) -> List[str]:
f"{_unverified_targets(unverified)} without message_id/raw_response")
fire_err = job.get("last_fire_error")
if isinstance(fire_err, dict) and fire_err.get("detail"):
- lines.append(f"{color('⚠ Missed scheduled fire:', Colors.RED)} "
- f"{fire_err.get('at', '?')} {fire_err['detail']}")
+ lines.append(_missed_fire_line(job, fire_err))
return lines
@@ -469,7 +492,7 @@ def _script_health_issue(script: str) -> Optional[str]:
try:
path.relative_to(scripts_dir)
except ValueError:
- return f"script resolves outside HERMES_HOME/scripts: {script!r}"
+ return f"script resolves outside {scripts_dir}: {script!r}"
if not path.exists():
return f"script not found: {path}"
if not path.is_file():
@@ -505,7 +528,8 @@ def _cron_doctor_issues_for_job(job: Dict[str, Any]) -> List[str]:
if last_status and last_status not in {"ok", "delivery_failed", "delivery_queued"}:
issues.append(f"last run failed: {str(job.get('last_error') or 'unknown error').strip()}")
if delivery_err := str(job.get("last_delivery_error") or "").strip():
- issues.append(f"last delivery failed: {delivery_err}")
+ issues.append(f"last run finished but the result was not delivered ({_short_reason(delivery_err)}). "
+ f"{_delivery_fix_hint(job)}")
if unverified := job.get("last_delivery_unverified"):
issues.append("last delivery unverified (adapter acked without evidence): "
+ _unverified_targets(unverified))
diff --git a/hermes_cli/doctor.py b/hermes_cli/doctor.py
index 3c9b9da0972..3d7cd834d60 100644
--- a/hermes_cli/doctor.py
+++ b/hermes_cli/doctor.py
@@ -132,7 +132,9 @@ def _ack_advisory(ack_target: str) -> None:
if ack_advisory(ack_target):
print(color(f" ✓ Acknowledged advisory {ack_target}. It will no longer trigger startup banners.", Colors.GREEN))
else:
- print(color(f" ✗ Failed to persist ack for {ack_target}. Check ~/.hermes/config.yaml is writable.", Colors.RED))
+ print(color(f" ✗ Could not save the acknowledgement for {ack_target}. Make sure {_DHH}/config.yaml is "
+ f"writable (`hermes config path` prints the exact file), then re-run "
+ f"`hermes doctor --ack {ack_target}`.", Colors.RED))
sys.exit(1)
diff --git a/hermes_cli/doctor_config.py b/hermes_cli/doctor_config.py
index ddc0e4fb463..9ee3b4604a3 100644
--- a/hermes_cli/doctor_config.py
+++ b/hermes_cli/doctor_config.py
@@ -256,7 +256,7 @@ def _validate_model_config(config_path, issues: list) -> None:
with warn_on_error(""):
if not _provider_has_credentials(runtime_provider):
_fail_and_issue(f"model.provider '{runtime_provider}' is set but no API key is configured",
- "(check ~/.hermes/.env or run 'hermes setup')",
+ f"(add it to {_DHH}/.env or run 'hermes setup')",
f"No credentials found for provider '{runtime_provider}'. Run 'hermes setup' or set the provider's "
f"API key in {_DHH}/.env, or switch providers with 'hermes config set model.provider <name>'", issues)
diff --git a/hermes_cli/doctor_tools.py b/hermes_cli/doctor_tools.py
index ae20745f13f..0bba3cf52d3 100644
--- a/hermes_cli/doctor_tools.py
+++ b/hermes_cli/doctor_tools.py
@@ -148,13 +148,15 @@ _BUILTIN_TERMINAL_BACKENDS = {"local", "docker", "singularity", "modal", "manage
def _check_docker_backend(terminal_env: str, running_in_container: bool, issues: list[str]) -> None:
if terminal_env == "docker":
if not _safe_which("docker"):
- _fail_and_issue("docker not found", "(required for TERMINAL_ENV=docker)", "Install Docker or change TERMINAL_ENV", issues)
+ _fail_and_issue("Docker not installed", "(needed for the 'docker' terminal backend)",
+ "Install Docker, or run `hermes setup terminal` to switch backend.", issues)
else:
# `docker version` hits /version, which socket proxies (tecnativa) allow by default; `docker info`
# needs /info and is commonly blocked, giving a false "daemon not running". The backend itself
# probes with `docker version` too (environments/docker.py).
- _require(_run_ok(["docker", "version"], timeout=10), ("docker", "(daemon running)"), ("docker daemon not running", ""),
- "Start Docker daemon", issues)
+ _require(_run_ok(["docker", "version"], timeout=10), ("docker", "(daemon running)"),
+ ("Docker daemon not running", "(needed for the 'docker' terminal backend)"),
+ "Start Docker, or run `hermes setup terminal` to switch backend.", issues)
elif _safe_which("docker"):
check_ok("docker", "(optional)")
elif _is_termux():
@@ -166,7 +168,8 @@ def _check_docker_backend(terminal_env: str, running_in_container: bool, issues:
def _check_ssh_backend(issues: list[str]) -> None:
ssh_host = os.getenv("TERMINAL_SSH_HOST")
if not ssh_host:
- return _fail_and_issue("TERMINAL_SSH_HOST not set", "(required for TERMINAL_ENV=ssh)", "Set TERMINAL_SSH_HOST in .env", issues)
+ return _fail_and_issue("SSH host not configured", "(needed for the 'ssh' terminal backend)",
+ "run `hermes setup terminal` and enter the SSH host and user.", issues)
ssh_user, ssh_port, ssh_key = (os.getenv(f"TERMINAL_SSH_{k}") for k in ("USER", "PORT", "KEY"))
cmd = ["ssh", "-o", "ConnectTimeout=5", "-o", "BatchMode=yes"]
if ssh_port:
@@ -186,7 +189,8 @@ def _require(cond, ok, bad, issue: str, issues: list[str]) -> None:
def _check_daytona_backend(issues: list[str]) -> None:
_require(os.getenv("DAYTONA_API_KEY"), ("Daytona API key", "(configured)"),
- ("DAYTONA_API_KEY not set", "(required for TERMINAL_ENV=daytona)"), "Set DAYTONA_API_KEY environment variable", issues)
+ ("Daytona API key missing", "(needed for the 'daytona' terminal backend)"),
+ "run `hermes setup terminal` (Daytona) to enter it.", issues)
try:
from daytona import Daytona # noqa: F401 — SDK presence check
check_ok("daytona SDK", "(installed)")
diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.py
index 60d7f7a7407..2f2f895eb54 100644
--- a/hermes_cli/env_loader.py
+++ b/hermes_cli/env_loader.py
@@ -28,20 +28,6 @@ _SCOPED_SKIP_LOGGED: set[str] = set() # routed profile homes whose multiplex d
# env-var name → source label ("bitwarden", …) for externally injected credentials; setup / `hermes
# model` tell users WHERE a key came from when .env lacks it.
_SECRET_SOURCES: dict[str, str] = {}
-# Every env-var name an external source SUPPLIED for some home, whether it was applied or lost to a
-# pre-existing process value (``skipped_existing``). ``_SECRET_SOURCES`` is provenance metadata and only
-# names applied values; the scrub that keeps a launch profile's source-supplied names out of a routed
-# child must see the skipped ones too, or a name already in the process env leaks with the launch value.
-_SOURCE_SUPPLIED_NAMES: set[str] = set()
-# Every KEY name a dotenv file loaded into ``os.environ`` during this process's lifetime. A key removed
-# or renamed in the launch ``.env`` after boot stays in ``os.environ`` (dotenv never unsets), but a
-# re-parse of the current file no longer names it — so the launch-residue strip for a routed child must
-# work from what was LOADED, not from what the file says now. Additive for the process lifetime.
-_LOADED_DOTENV_KEYS: set[str] = set()
-# KEY names loaded from the administrator-managed ``.env`` (``_apply_managed_env``). Kept OUT of the launch
-# residue: those values are policy that beats the user's own ``.env`` for every profile, so a routed child
-# must keep them — and keep them LAST, over the routed profile's scope (review on f5f88d5058).
-_MANAGED_DOTENV_KEYS: set[str] = set()
# Immutable per-home snapshots: os.environ is shared across profiles and a later home's apply may overwrite it.
_SECRET_SOURCE_VALUES_BY_HOME: dict[str, dict[str, str]] = {}
# HERMES_HOME paths already pulled external secrets for: load_hermes_dotenv() runs at import time from
@@ -89,43 +75,12 @@ def get_secret_source(env_var: str) -> str | None:
return _SECRET_SOURCES.get(env_var)
-def _record_supplied_names(report) -> set[str]:
- """Every name *report*'s sources supplied — applied, or skipped because a value already existed —
- recorded into ``_SOURCE_SUPPLIED_NAMES`` so the routed-child scrub knows the source owns it."""
- supplied = set(report.provenance)
- for src in report.sources:
- supplied.update(src.skipped_existing)
- _SOURCE_SUPPLIED_NAMES.update(supplied)
- return supplied
-
-
def secret_source_names() -> tuple[str, ...]:
- """Every env-var name some profile's external secret source APPLIED (names only — the map is
- process-wide, so a value must be resolved through the active profile's secret scope). Consumers that
- forward source values into a child (MCP stdio env) want exactly these; see ``source_supplied_names``
- for the wider set the routed-child scrub needs."""
+ """Every env-var name some profile's external secret source supplied (names only — the map is
+ process-wide, so a value must be resolved through the active profile's secret scope)."""
return tuple(_SECRET_SOURCES)
-def source_supplied_names() -> tuple[str, ...]:
- """Every env-var name an external source supplied for any home — applied, or lost to a pre-existing
- process value (``skipped_existing``). The launch value in ``os.environ`` is still not a routed
- profile's to inherit, so the strip must see the skipped names too."""
- return tuple(sorted(set(_SECRET_SOURCES) | _SOURCE_SUPPLIED_NAMES))
-
-
-def launch_dotenv_keys() -> frozenset[str]:
- """KEY names any NON-managed dotenv file loaded into this process's ``os.environ`` so far (see
- ``_LOADED_DOTENV_KEYS``); the launch profile's residue set for routed children."""
- return frozenset(_LOADED_DOTENV_KEYS)
-
-
-def managed_dotenv_keys() -> frozenset[str]:
- """KEY names the administrator-managed ``.env`` loaded (see ``_MANAGED_DOTENV_KEYS``). Policy for
- every profile: never stripped from a routed child, and re-applied over the routed scope."""
- return frozenset(_MANAGED_DOTENV_KEYS)
-
-
def get_secret_source_values(hermes_home: str | os.PathLike) -> dict[str, str]:
"""Return the external-secret value snapshot for ``hermes_home``."""
return dict(_SECRET_SOURCE_VALUES_BY_HOME.get(str(Path(hermes_home).resolve()), {}))
@@ -184,10 +139,6 @@ def _hydrate_profile_secret_sources(home: Path) -> dict[str, str]:
# mixed report are still snapshotted below and can be used while the failed source recovers.
if all(src.result.ok for src in report.sources):
_APPLIED_HOMES.add(home_key)
- # Same ownership bookkeeping as the process-global path: a name this profile's source supplied — applied,
- # or skipped because the private mapping already had it — is a source-owned name the routed-child scrub
- # must know about, or a sibling still inherits the launch value for it (review on f5f88d5058).
- _record_supplied_names(report)
values: dict[str, str] = {}
for name, applied in report.provenance.items():
value = local_env.get(name)
@@ -209,7 +160,6 @@ def reset_secret_source_cache(hermes_home: str | os.PathLike | None = None) -> N
if hermes_home is None:
_APPLIED_HOMES.clear()
_SECRET_SOURCES.clear()
- _SOURCE_SUPPLIED_NAMES.clear()
_SECRET_SOURCE_VALUES_BY_HOME.clear()
return
home_key = str(Path(hermes_home).resolve())
@@ -284,7 +234,7 @@ def _sanitize_loaded_credentials() -> None:
)
-def _load_dotenv_with_fallback(path: Path, *, override: bool, managed: bool = False) -> None:
+def _load_dotenv_with_fallback(path: Path, *, override: bool) -> None:
try:
# utf-8-sig strips a leading BOM (PowerShell 5.1 / Notepad); plain utf-8 would keep U+FEFF on the
# first key name and silently drop it from os.environ under its canonical name.
@@ -294,9 +244,6 @@ def _load_dotenv_with_fallback(path: Path, *, override: bool, managed: bool = Fa
if raw.startswith(codecs.BOM_UTF8):
raw = raw[len(codecs.BOM_UTF8) :]
load_dotenv(stream=io.StringIO(raw.decode("latin-1")), override=override)
- # Same scanner both branches: it re-reads the file with the same latin-1 fallback. Managed keys are
- # recorded separately: they are administrator policy, not launch-profile residue.
- (_MANAGED_DOTENV_KEYS if managed else _LOADED_DOTENV_KEYS).update(_env_keys_defined_in_dotenv(path))
_sanitize_loaded_credentials() # httpx encodes headers as ASCII
@@ -387,8 +334,6 @@ def load_hermes_dotenv(
# Multiplex gateway: while a routed profile-home override is active, copying that profile's .env
# into os.environ would expose its credentials to sibling turns and every spawned child. Unscoped
# startup loads keep the normal path; external sources still refresh against the profile mapping.
- # (``is_multiplex_active()`` is also true, context-locally, for a routed cron fire in the desktop
- # backend — see ``cron.scheduler_provider._profile_cron_scope``.)
from agent.secret_scope import is_multiplex_active
from hermes_constants import get_hermes_home_override
@@ -490,7 +435,7 @@ def _apply_managed_env() -> None:
if not managed_env.exists():
return
_sanitize_env_file_if_needed(managed_env)
- _load_dotenv_with_fallback(managed_env, override=True, managed=True)
+ _load_dotenv_with_fallback(managed_env, override=True)
def _apply_external_secret_sources(home_path: Path) -> None:
@@ -551,7 +496,9 @@ def _apply_external_secret_sources(home_path: Path) -> None:
# ``EnvironmentFile=``. Under multiplex the scope is the only credential source, so an empty
# snapshot failed every default-profile turn for the process lifetime (#102041).
values: dict[str, str] = {}
- supplied = _record_supplied_names(report)
+ supplied = set(report.provenance)
+ for src in report.sources:
+ supplied.update(src.skipped_existing)
for name in supplied:
if name in os.environ:
values[name] = os.environ[name]
diff --git a/hermes_cli/gateway.py b/hermes_cli/gateway.py
index 39a6ef0ab8f..4c7e7c0d511 100644
--- a/hermes_cli/gateway.py
+++ b/hermes_cli/gateway.py
@@ -2289,7 +2289,8 @@ def _run_systemctl(args: list[str], *, system: bool = False, **kwargs) -> subpro
try:
return subprocess.run(_systemctl_cmd(system) + args, **kwargs)
except FileNotFoundError:
- raise RuntimeError("systemctl is not available on this system") from None
+ from hermes_cli.gateway_command_errors import SystemctlUnavailableError
+ raise SystemctlUnavailableError() from None
def _service_scope_label(system: bool = False) -> str:
@@ -4586,10 +4587,10 @@ def _guard_existing_gateway_process_conflict(replace: bool = False) -> None:
pass
return
- print_error(f"Another gateway instance is already running (PID {pid}).")
- print(" Use 'hermes gateway restart' to replace it,")
- print(" or 'hermes gateway stop' first.")
- print(" Or use 'hermes gateway run --replace' to auto-replace.")
+ print_error(f"A gateway is already running (PID {pid}), so your bots are most likely online already.")
+ print(" Check with `hermes gateway status`.")
+ print(" To restart it: `hermes gateway restart`. To stop it: `hermes gateway stop`.")
+ print(" To replace it from here: `hermes gateway run --replace`.")
sys.exit(1)
@@ -5899,6 +5900,15 @@ def gateway_command(args):
# System-scope action typed without sudo; the wizard intercepts this earlier with guidance.
print(str(e))
sys.exit(1)
+ except (subprocess.CalledProcessError, RuntimeError) as e:
+ # systemctl exited non-zero or is missing entirely: guidance, not a traceback.
+ from hermes_cli.gateway_command_errors import explain_service_failure
+ lines = explain_service_failure(e)
+ if lines is None:
+ raise
+ print_error(lines[0])
+ _print_indented("\n".join(lines[1:]))
+ sys.exit(1)
def _maybe_redirect_run_to_s6_supervision(args) -> bool:
@@ -6079,7 +6089,10 @@ _NO_BACKEND_MESSAGES = {
"Service uninstall is not applicable inside a Docker container.",
"To stop the gateway, stop or remove the container:", "",
" docker stop <container>", " docker rm <container>"),
- ("uninstall", "unsupported"): (1, "Not supported on this platform."),
+ ("uninstall", "unsupported"): (1,
+ "Running the gateway as a background service is not available on this platform "
+ "(no systemd, launchd or Scheduled Tasks), so there is nothing to uninstall.",
+ "Stop a manually started gateway with: hermes gateway stop"),
("start", "termux"): (1,
"Gateway service start is not supported on Termux because there is no system service manager.",
"Run manually: hermes gateway"),
@@ -6093,7 +6106,10 @@ _NO_BACKEND_MESSAGES = {
" docker start <container> # start a stopped container",
" docker restart <container> # restart a running container", "",
"Or run the gateway directly: hermes gateway run"),
- ("start", "unsupported"): (1, "Not supported on this platform."),
+ ("start", "unsupported"): (1,
+ "Running the gateway as a background service is not available on this platform "
+ "(no systemd, launchd or Scheduled Tasks).",
+ "Run it directly with: hermes gateway run"),
}
diff --git a/hermes_cli/gateway_command_errors.py b/hermes_cli/gateway_command_errors.py
new file mode 100644
index 00000000000..67349b118da
--- /dev/null
+++ b/hermes_cli/gateway_command_errors.py
@@ -0,0 +1,51 @@
+"""User-facing copy for ``hermes gateway start/stop/restart`` failures on systemd hosts.
+
+``hermes_cli/gateway.py`` is a facade; this sibling owns the small exception -> guidance table so
+the most common Linux service failures (``systemctl`` exited non-zero, or there is no ``systemctl``
+at all) end as a next step instead of a traceback.
+"""
+
+from __future__ import annotations
+
+import subprocess
+
+
+class SystemctlUnavailableError(RuntimeError):
+ """``systemctl`` is not installed (Alpine, minimal containers, some WSL setups)."""
+
+ def __init__(self) -> None:
+ super().__init__("systemctl is not available on this system")
+
+
+_JOURNAL_HINT = 'journalctl --user -u hermes-gateway --since "5 min ago"'
+
+_SYSTEMCTL_FAILED_LINES = (
+ "Could not {verb} the gateway service; systemd reported an error.",
+ "See why with `hermes gateway status --deep` or `{journal}`.",
+ "To reinstall the service run `hermes gateway install --force`.",
+)
+
+_NO_SYSTEMCTL_LINES = (
+ "This system has no systemd, so Hermes cannot install a background service here.",
+ "Run the gateway directly with `hermes gateway run` (keep it alive with tmux or screen).",
+)
+
+
+def _verb_for(exc: subprocess.CalledProcessError) -> str:
+ cmd = exc.cmd if isinstance(exc.cmd, (list, tuple)) else str(exc.cmd).split()
+ for token in cmd:
+ if token in ("start", "stop", "restart"):
+ return token
+ return "start"
+
+
+def explain_service_failure(exc: BaseException) -> list[str] | None:
+ """Lines to print for a systemd service failure escaping the gateway command, or None
+ when *exc* is not one this module knows how to explain (callers re-raise)."""
+ if isinstance(exc, SystemctlUnavailableError):
+ return list(_NO_SYSTEMCTL_LINES)
+ if isinstance(exc, subprocess.CalledProcessError):
+ lines = [line.format(verb=_verb_for(exc), journal=_JOURNAL_HINT) for line in _SYSTEMCTL_FAILED_LINES]
+ lines.append(f"Details: {exc}")
+ return lines
+ return None
diff --git a/hermes_cli/main.py b/hermes_cli/main.py
index 70182df53d4..ea237c953c8 100644
--- a/hermes_cli/main.py
+++ b/hermes_cli/main.py
@@ -416,32 +416,68 @@ def _inside_mcp_add_args(argv: list, index: int) -> bool:
return True
+def _looks_like_hermes_invocation() -> bool:
+ """False when ``sys.argv`` belongs to a test runner rather than a ``hermes`` run.
+
+ pytest's own ``-p no:xdist`` reaches ``_scan_profile_flag`` through ``sys.argv`` at import
+ time; it must stay a silent skip, while a real ``hermes -p 'Work Bot'`` must fail loudly.
+ """
+ return "pytest" not in (sys.argv[0] or "")
+
+
+def _exit_invalid_profile_name(value: str) -> None:
+ from hermes_cli.profiles import _invalid_profile_name_error
+
+ print(f"Error: {_invalid_profile_name_error(value)}", file=sys.stderr)
+ print("Run `hermes profile list` to see your profiles.", file=sys.stderr)
+ sys.exit(2)
+
+
+def _looks_like_option_value(value: str) -> bool:
+ """A ``-p`` value that clearly belongs to some other tool (pytest's ``-p no:xdist``, a
+ third-party ``-p --flag``), never a mistyped profile name."""
+ return value.startswith("-") or ":" in value
+
+
def _scan_profile_flag(argv: list) -> tuple:
"""Find -p/--profile/--profile= in argv -> (name, tokens_consumed, index).
Historically the flag worked even after the subcommand (`hermes chat -p
coder`), so scan broadly; stop at ``--`` and at the `mcp add --args`
- passthrough region. Values that can't be profile names (pytest's
- ``-p no:xdist``) are rejected so resolve_profile_env never sys.exits on them.
+ passthrough region. The value is normalised (strip + casefold, matching
+ ``profiles.normalize_profile_name``) before validation so ``-p Work`` selects
+ ``work``. A value that cannot be a profile name is rejected so
+ resolve_profile_env never sys.exits on it; the rejection is explained (exit 2)
+ only when the flag comes BEFORE the first subcommand token under a real
+ ``hermes`` run — after a subcommand, ``-p`` may belong to that subcommand or a
+ plugin (`hermes kanban ... -p 8080`), and option-looking values (``no:xdist``,
+ ``--flag``) are always a silent skip.
"""
from hermes_cli._parser import top_level_value_flag_sets
value_flags, optional_value_flags = top_level_value_flag_sets()
i = 0
+ saw_subcommand = False
while i < len(argv):
arg = argv[i]
if arg == "--" or (arg == "--args" and _inside_mcp_add_args(argv, i)):
break
if arg in {"--profile", "-p"} and i + 1 < len(argv):
- if re.match(_PROFILE_NAME_RE, argv[i + 1]):
- return argv[i + 1], 2, i
+ raw = argv[i + 1]
+ value = raw.strip().casefold()
+ if re.match(_PROFILE_NAME_RE, value):
+ return value, 2, i
+ if not saw_subcommand and not _looks_like_option_value(raw) and _looks_like_hermes_invocation():
+ _exit_invalid_profile_name(raw)
break
if arg.startswith("--profile="):
- return arg.split("=", 1)[1], 1, i
+ return arg.split("=", 1)[1].strip().casefold(), 1, i
takes_value = "=" not in arg and i + 1 < len(argv) and (
arg in value_flags
or (arg in optional_value_flags and not argv[i + 1].startswith("-"))
)
+ if not takes_value and not arg.startswith("-"):
+ saw_subcommand = True
i += 2 if takes_value else 1
return None, 0, None
@@ -1421,7 +1457,11 @@ def _resolve_continue_arg(args, *, use_tui: bool) -> None:
args.resume = last_id
else:
kind = "TUI" if use_tui else "CLI"
- print(f"No previous {kind} session found to continue.")
+ print(
+ f"No previous {kind} session to continue. Start a new one with "
+ "`hermes`, or list sessions with `hermes sessions list`.",
+ file=sys.stderr,
+ )
sys.exit(1)
@@ -1919,7 +1959,11 @@ def _resolve_active_provider(config, model_cfg, effective_provider, custom_provi
try:
active = resolve_provider("auto")
except AuthError as exc:
- if effective_provider == "auto":
+ if exc.code == "no_provider_configured":
+ # The picker that is about to open IS the fix; a warning that says
+ # "run `hermes model`" from inside `hermes model` is circular.
+ print("No provider is set up yet — pick one below. (Nous Portal works without an API key.)")
+ elif effective_provider == "auto":
print(f"Warning: {format_auth_error(exc)} Falling back to auto provider detection.")
active = None # no provider yet; default to first in list
@@ -2466,14 +2510,10 @@ def _dashboard_prepare_runtime(args, headless_backend) -> bool:
import fastapi # noqa: F401
import uvicorn # noqa: F401
except ImportError as e:
- print("Web UI dependencies not installed (need fastapi + uvicorn).")
- print(
- f"Re-install the package into this interpreter so metadata updates apply:\n"
- f" cd {PROJECT_ROOT}\n"
- f" {sys.executable} -m pip install -e .\n"
- "If `pip` is missing in this venv, use: uv pip install -e ."
- )
- print(f"Import error: {e}")
+ from hermes_cli.main_dep_hints import missing_optional_deps_message
+
+ print(missing_optional_deps_message("dashboard", "its web-server packages (fastapi, uvicorn)", "all"))
+ print(f"Details: {e}")
sys.exit(1)
# Seed bundled skills on first dashboard launch so the desktop GUI's
diff --git a/hermes_cli/main_agent_cmds.py b/hermes_cli/main_agent_cmds.py
index 4efc80e597a..7dd3f5d061e 100644
--- a/hermes_cli/main_agent_cmds.py
+++ b/hermes_cli/main_agent_cmds.py
@@ -81,9 +81,11 @@ def cmd_acp(args):
try:
from acp_adapter.entry import main as acp_main
acp_main([flag for attr, flag in _ACP_FLAGS if getattr(args, attr, False)])
- except ImportError:
- print("ACP dependencies not installed.", file=sys.stderr)
- print("Install them with: pip install -e '.[acp]'", file=sys.stderr)
+ except ImportError as e:
+ from hermes_cli.main_dep_hints import missing_optional_deps_message
+
+ print(missing_optional_deps_message("ACP server", "its protocol packages", "acp"), file=sys.stderr)
+ print(f"Details: {e}", file=sys.stderr)
sys.exit(1)
diff --git a/hermes_cli/main_dep_hints.py b/hermes_cli/main_dep_hints.py
new file mode 100644
index 00000000000..e4dafc11aaa
--- /dev/null
+++ b/hermes_cli/main_dep_hints.py
@@ -0,0 +1,22 @@
+"""Plain-language copy for surfaces that cannot start because an optional dependency group is missing.
+
+``hermes dashboard`` (fastapi + uvicorn) and ``hermes acp`` (agent-client-protocol) are installed by
+the ``[all]`` / ``[acp]`` extras. A partial install, a pip-less uv venv or an interrupted update can
+leave them out; the built-in repair is ``hermes update``, which reinstalls the extras into the same
+interpreter. The manual fallback names the checkout directory and interpreter explicitly because a bare
+``pip install -e '.[acp]'`` fails on PEP 668 systems and in venvs without pip.
+"""
+
+import sys
+
+
+def missing_optional_deps_message(surface: str, what: str, extra: str) -> str:
+ """``surface`` = "dashboard"/"ACP server"; ``what`` = "its web-server packages"; ``extra`` = "all"/"acp"."""
+ from hermes_cli.main import PROJECT_ROOT
+
+ return (
+ f"The {surface} can't start: {what} are missing from this install.\n"
+ "Run `hermes update` to reinstall dependencies. If that fails, run manually:\n"
+ f" cd {PROJECT_ROOT} && {sys.executable} -m pip install -e '.[{extra}]'\n"
+ f" (no pip in this venv: uv pip install -e '.[{extra}]')"
+ )
diff --git a/hermes_cli/main_tui_launch.py b/hermes_cli/main_tui_launch.py
index b3e27456081..4dc448a60f1 100644
--- a/hermes_cli/main_tui_launch.py
+++ b/hermes_cli/main_tui_launch.py
@@ -454,7 +454,11 @@ def _tui_node_bin(bin: str) -> str:
if ensure_dependency("node"):
path = find_node_executable("node")
if not path:
- print(f"{bin} not found — install Node.js to use the TUI.")
+ print(
+ f"Node.js is required for the TUI but `{bin}` was not found. Install it from "
+ "https://nodejs.org (run `hermes doctor` for the install hint for your OS), then "
+ "retry `hermes --tui`. To keep working now, run `hermes --cli`."
+ )
sys.exit(1)
return path
diff --git a/hermes_cli/mcp_config.py b/hermes_cli/mcp_config.py
index d0f9573fabc..32bc7247c33 100644
--- a/hermes_cli/mcp_config.py
+++ b/hermes_cli/mcp_config.py
@@ -644,7 +644,8 @@ def cmd_mcp_add(args):
try:
tools = _probe_single_server(name, server_config)
except Exception as exc:
- _error(f"Failed to connect: {redact_mcp_probe_text(exc)}")
+ _error(f"Failed to connect: {_probe_failure_reason(exc)}")
+ _info(_probe_failure_next_step(name, exc))
if _confirm("Save config anyway (you can test later)?", default=False):
server_config["enabled"] = False
if _save_mcp_server(name, server_config):
@@ -738,6 +739,25 @@ def cmd_mcp_list(args=None):
print()
+def _probe_failure_reason(exc: BaseException) -> str:
+ """Plain reason for a failed probe: ``_format_connect_error`` unwraps ExceptionGroups and names a
+ missing executable; the result is redacted like every other probe string."""
+ from tools.mcp_tool_errors import _format_connect_error
+ return redact_mcp_probe_text(_format_connect_error(exc))
+
+
+def _probe_failure_next_step(name: str, exc: BaseException) -> str:
+ """The one command that fixes the common probe failures (sign-in, missing command, everything else)."""
+ from tools.mcp_tool_errors import _format_connect_error, _is_auth_error, _unwrap_exception_group
+ root = _unwrap_exception_group(exc)
+ if _is_auth_error(root) or getattr(getattr(root, "response", None), "status_code", None) in (401, 403):
+ return f"The server rejected the sign-in. Run: hermes mcp login {name}"
+ if "missing executable" in _format_connect_error(exc):
+ return (f"Install that command, or set mcp_servers.{name}.command in {display_hermes_home()}/config.yaml "
+ "to its full path.")
+ return f"Check the server is running and the URL/command in its config, then run: hermes mcp test {name}"
+
+
def cmd_mcp_test(args):
"""Test connection to an MCP server."""
name = args.name
@@ -767,7 +787,9 @@ def cmd_mcp_test(args):
try:
tools = _probe_single_server(name, cfg)
except Exception as exc:
- _error(f"Connection failed ({(time.monotonic() - start) * 1000:.0f}ms): {redact_mcp_probe_text(exc)}")
+ elapsed = time.monotonic() - start
+ _error(f"Connection failed ({elapsed:.1f}s): {_probe_failure_reason(exc)}")
+ _info(_probe_failure_next_step(name, exc))
return
_success(f"Connected ({(time.monotonic() - start) * 1000:.0f}ms)")
_success(f"Tools discovered: {len(tools)}")
diff --git a/hermes_cli/model_setup_flows_common.py b/hermes_cli/model_setup_flows_common.py
index f0bd1bb17c6..b9dd62d5874 100644
--- a/hermes_cli/model_setup_flows_common.py
+++ b/hermes_cli/model_setup_flows_common.py
@@ -10,6 +10,7 @@ from __future__ import annotations
import contextlib
import subprocess
+from urllib.parse import urlparse
from hermes_cli.cli_output import line_input
from hermes_cli.config import clear_model_endpoint_credentials
@@ -156,16 +157,45 @@ def _pick_model_or_prompt(model_list, prompt: str, **kwargs):
return _ask(prompt, cancel_msg=None)
+def _login_retry_context(args) -> tuple[str, str]:
+ """(retry_command, service_host) for a login helper's failure copy, from the ``ProviderConfig``
+ among its positional args. Nous keeps ``hermes portal``; every other OAuth provider is retried
+ with ``hermes auth add <provider>`` and named by its own portal host (``hermes login`` no longer
+ exists). Falls back to ``hermes model`` when no provider config is in play."""
+ pconfig = next((a for a in args if hasattr(a, "id") and hasattr(a, "portal_base_url")), None)
+ if pconfig is None:
+ return "hermes model", "the sign-in service"
+ provider_id = str(getattr(pconfig, "id", "") or "")
+ host = urlparse(str(getattr(pconfig, "portal_base_url", "") or "")).hostname or "the sign-in service"
+ if provider_id == "nous":
+ return "hermes portal", host
+ return (f"hermes auth add {provider_id}" if provider_id else "hermes model"), host
+
+
def _run_login(login_fn, *args, **kwargs) -> bool:
- """Run an OAuth login helper; print the standard failure line and return False
- on SystemExit / any exception."""
+ """Run an OAuth login helper; print plain failure copy (what happened + retry command) and
+ return False on SystemExit / any exception. The retry command and service host come from the
+ provider config passed to the helper, so a MiniMax failure never says ``hermes portal`` /
+ ``portal.nousresearch.com``. Helpers that print their own copy raise ``SystemExit(1)`` with no
+ message, which stays silent; a SystemExit that carries a message (or a non-cancel code from a
+ helper that printed nothing) gets a one-line explanation so the user is never left with no
+ output."""
+ from hermes_cli.auth_error_copy import sign_in_failure_lines
+ retry_command, service_host = _login_retry_context(args)
try:
login_fn(*args, **kwargs)
- except SystemExit:
- print("Login cancelled or failed.")
+ except SystemExit as exc:
+ if exc.code in (130, None, 0):
+ print("Sign-in was cancelled.")
+ elif isinstance(exc.code, str) and exc.code.strip():
+ print(f"Sign-in did not complete: {exc.code.strip()}")
+ print(f"Run `{retry_command}` to try again.")
+ else:
+ print(f"Sign-in did not complete; run `{retry_command}` to try again.")
return False
except Exception as exc:
- print(f"Login failed: {exc}")
+ for line in sign_in_failure_lines(exc, service_host=service_host, retry_command=retry_command):
+ print(line)
return False
return True
diff --git a/hermes_cli/model_switch.py b/hermes_cli/model_switch.py
index 8d873ff7656..410d7483680 100644
--- a/hermes_cli/model_switch.py
+++ b/hermes_cli/model_switch.py
@@ -1312,7 +1312,10 @@ def _creds_for_switched_provider(st: _Switch) -> Optional[ModelSwitchResult]:
try:
st.resolve_runtime(requested=st.target_provider)
except Exception as e:
- return st.fail_on_target(f"Could not resolve credentials for provider '{st.provider_label}': {e}")
+ return st.fail_on_target(
+ f"{st.provider_label} is not connected: no API key or login was found for it. Add one with "
+ f"`hermes auth add {st.target_provider}`, or pick a connected provider in /model.\n"
+ f" Details: {e}")
return None
diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.py
index 553f80a73b5..a979c394918 100644
--- a/hermes_cli/plugins.py
+++ b/hermes_cli/plugins.py
@@ -1129,10 +1129,6 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
self.home_path = Path(self.scope_key)
self._discovery_lock = threading.RLock()
self._discovered: bool = False
- # True once a discovery re-applied plugin secret sources for this home: the per-home snapshot and
- # the installed scope may then hold plugin-supplied names, and a later discovery that finds NO
- # enabled plugin source (plugin removed / disabled) must still reconcile once to drop them.
- self._plugin_secret_sources_reconciled: bool = False
self._cli_ref = None # Set by CLI after plugin discovery
self._gateway_message_injector: tuple[object, Callable] | None = None
self._context_engine = None # Set by a plugin via register_context_engine()
@@ -1272,34 +1268,24 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
plugin_sources = list_plugin_sources()
except Exception:
return
- enabled_names: list[str] = []
- if plugin_sources:
+ if not plugin_sources:
+ return
+ try:
+ from hermes_cli.config import load_config
+ secrets = (load_config() or {}).get("secrets") or {}
+ except Exception:
+ secrets = {}
+
+ def _enabled(source) -> bool:
+ section = secrets.get(getattr(source, "name", ""))
try:
- from hermes_cli.config import load_config
- secrets = (load_config() or {}).get("secrets") or {}
+ return bool(source.is_enabled(section if isinstance(section, dict) else {}))
except Exception:
- secrets = {}
+ return False # mirrors the orchestrator: a raising is_enabled() is skipped
- def _enabled(source) -> bool:
- section = secrets.get(getattr(source, "name", ""))
- try:
- return bool(source.is_enabled(section if isinstance(section, dict) else {}))
- except Exception:
- return False # mirrors the orchestrator: a raising is_enabled() is skipped
-
- enabled_names = [getattr(s, "name", "") for s in plugin_sources if _enabled(s)]
+ enabled_names = [getattr(s, "name", "") for s in plugin_sources if _enabled(s)]
if not enabled_names:
- # Nothing enabled now. If an earlier discovery re-applied plugin sources for this home, the
- # snapshot and installed scope still carry that plugin's names (force-reload unloads the
- # registration first, so this is exactly the "last plugin source removed" path) — reconcile
- # once so they drop out. A home that never had one stays a no-op: no re-pull, no re-load.
- if not self._plugin_secret_sources_reconciled:
- return
- # The marker is cleared only AFTER the cleanup below succeeds: reset/reload/refresh are
- # fallible, and clearing first left the stale credential active with no retry on the next
- # discovery (review on f5f88d5058).
- else:
- self._plugin_secret_sources_reconciled = True
+ return
try:
# Reset and reload the SAME home the process (or routed turn) resolves to: under multiplex this
# runs at gateway boot after sibling profiles may already have hydrated, and a global clear
@@ -1308,16 +1294,8 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):
home = get_hermes_home()
reset_secret_source_cache(home)
load_hermes_dotenv(hermes_home=home)
- # A scope installed for this home was frozen BEFORE these sources existed — a routed cron
- # fire builds its scope in run_one_job and only then, on its first agent build, discovers
- # plugins; under multiplex semantics the load above is hydrate-only, so fold the values
- # into the installed scope or THIS fire never sees the plugin credential.
- from agent.secret_scope import refresh_installed_secret_scope
- refresh_installed_secret_scope(Path(home))
- if not enabled_names:
- self._plugin_secret_sources_reconciled = False # cleanup succeeded; nothing left to drop
logger.debug("Re-applied secret sources after plugin discovery for: %s",
- ", ".join(sorted(enabled_names)) or "<none — reconciled removed plugin sources>")
+ ", ".join(sorted(enabled_names)))
except Exception as exc:
logger.debug("secret source re-apply after discovery failed: %s", exc)
diff --git a/hermes_cli/plugins_cmd.py b/hermes_cli/plugins_cmd.py
index 4d946012c71..f4fcc570ed2 100644
--- a/hermes_cli/plugins_cmd.py
+++ b/hermes_cli/plugins_cmd.py
@@ -404,6 +404,18 @@ def _display_after_install(plugin_dir: Path, identifier: str) -> None:
console.print()
+def _clone_failure_message(git_url: str, git_error: str) -> str:
+ """Plain-words clone failure: what to check (address, network, private repo), raw git text last.
+
+ The text reaches ``_fail`` -> Rich ``console.print``: escape the git output so ``[...]`` in it is
+ not parsed as markup."""
+ from rich.markup import escape
+ return (f"Could not download the plugin from {git_url}. Check the address (browse the catalog "
+ "with `hermes plugins search`), check your internet connection, or, if the repository "
+ "is private, sign in first with `gh auth login` (or set GITHUB_TOKEN in your .env).\n"
+ f"Details: {escape(git_error.strip())}")
+
+
def _require_installed_plugin(name: str, plugins_dir: Path, console) -> Path:
"""The plugin path if it exists; else exit 1 (invalid name, or a listing of installed plugins)."""
try:
@@ -411,11 +423,19 @@ def _require_installed_plugin(name: str, plugins_dir: Path, console) -> Path:
except ValueError as e:
_fail(console, f"[red]Error:[/red] {e}")
if not target.exists():
- installed = ", ".join(d.name for d in plugins_dir.iterdir() if d.is_dir()) or "(none)"
- _fail(console, f"[red]Error:[/red] Plugin '{name}' not found in {plugins_dir}.\nInstalled plugins: {installed}")
+ _fail(console, _unknown_plugin_message(name, downloaded_only=True))
return target
+def _unknown_plugin_message(name: str, *, downloaded_only: bool = False) -> str:
+ """``No plugin named ...`` with the exact-name rule and the two commands that resolve it."""
+ scope = (" This command only works on downloaded plugins; bundled ones can only be enabled or disabled."
+ if downloaded_only else " Bundled plugins can only be enabled or disabled.")
+ return (f"[red]No plugin named '{name}'.[/red] Run `hermes plugins list` to see the exact names "
+ f"(nested plugins use their full key, e.g. web/firecrawl).{scope} "
+ "To add one: `hermes plugins install <owner/repo>`.")
+
+
# ── Install metadata + git plumbing ─────────────────────────────────────────────────────────
_EXACT_COMMIT_RE = re.compile(r"^[0-9a-fA-F]{40}$")
@@ -569,12 +589,7 @@ def _clone_plugin_repo(tmp_clone: Path, git_url: str, revision: Optional[str]) -
except subprocess.TimeoutExpired as e:
raise PluginOperationError("Git clone timed out after 60 seconds.") from e
if result.returncode != 0:
- error = _safe_git_error(result, git_url)
- if re.search(r"could not read Username|Authentication failed|Repository not found", error):
- error += (
- "\n\nIf this repository is private, authenticate first: run `gh auth login`, set GITHUB_TOKEN "
- "(or GH_TOKEN) in your .env, or store a credential in git's credential helper for this host.")
- raise PluginOperationError(f"Git clone failed:\n{error}")
+ raise PluginOperationError(_clone_failure_message(git_url, _safe_git_error(result, git_url)))
_scrub_cloned_origin(tmp_clone, git_exe, git_url)
if revision:
_checkout_exact_revision(tmp_clone, git_exe, revision, source_url=git_url)
@@ -1006,7 +1021,7 @@ def cmd_enable(name: str, allow_tool_override: Optional[bool] = None) -> None:
_refuse_legacy_relay(name)
resolved = _resolve_plugin_key_and_source(name)
if resolved is None:
- _fail(console, f"[red]Plugin '{name}' is not installed or bundled.[/red]")
+ _fail(console, _unknown_plugin_message(name))
key, source = resolved
_refuse_legacy_relay(key)
@@ -1137,7 +1152,7 @@ def cmd_capabilities(name: Optional[str] = None) -> None:
rows.append((key, entry[3], declared, granted, effective))
if name is not None and not rows:
- _fail(console, f"[red]Plugin '{name}' is not installed or bundled.[/red]")
+ _fail(console, _unknown_plugin_message(name))
if not rows:
console.print("[dim]No plugins declare or hold capabilities.[/dim]")
return
@@ -1188,7 +1203,7 @@ def cmd_disable(name: str) -> None:
console = _console()
key = _resolve_plugin_key(name)
if key is None:
- _fail(console, f"[red]Plugin '{name}' is not installed or bundled.[/red]")
+ _fail(console, _unknown_plugin_message(name))
enabled = _get_enabled_set()
disabled = _get_disabled_set()
if key not in enabled and key in disabled:
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py
index e5fa6d4483c..e8c5d5fe602 100644
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@ -186,6 +186,38 @@ def _missing_profile_error(canon: str) -> FileNotFoundError:
return FileNotFoundError(f"Profile '{canon}' does not exist. Create it with: hermes profile create {canon}")
+def _unknown_profile_error(canon: str) -> FileNotFoundError:
+ """For delete/rename/export of a name that matches no profile (likely a typo)."""
+ return FileNotFoundError(f"No profile named '{canon}'. See your profiles with: hermes profile list")
+
+
+def _profile_exists_error(canon: str) -> FileExistsError:
+ return FileExistsError(
+ f"A profile named '{canon}' already exists. Switch to it with `hermes profile use {canon}`, "
+ "see all profiles with `hermes profile list`, or choose a different name."
+ )
+
+
+_PROFILE_NAME_RULE = (
+ "Use lowercase letters, numbers, '-' or '_', starting with a letter or number, "
+ "up to 64 characters"
+)
+
+
+def _suggest_profile_name(name: str) -> str:
+ """Best-effort valid id derived from *name* (``'My Work'`` -> ``'my-work'``); ``my-work`` if nothing usable."""
+ candidate = re.sub(r"[^a-z0-9_-]+", "-", name.strip().lower()).strip("-_")[:64]
+ return candidate if _PROFILE_ID_RE.match(candidate) else "my-work"
+
+
+def _invalid_profile_name_error(name: str) -> ValueError:
+ suggestion = _suggest_profile_name(name)
+ return ValueError(
+ f"{name!r} is not a valid profile name. {_PROFILE_NAME_RULE} (for example: {suggestion}). "
+ f"Then run `hermes profile create {suggestion}`."
+ )
+
+
# Validation
def normalize_profile_name(name: str) -> str:
@@ -216,7 +248,7 @@ def validate_profile_name(name: str) -> None:
if name == "default":
return # special alias for ~/.hermes
if not _PROFILE_ID_RE.match(name):
- raise ValueError(f"Invalid profile name {name!r}. Must match [a-z0-9][a-z0-9_-]{{0,63}}")
+ raise _invalid_profile_name_error(name)
if name in _RESERVED_NAMES:
raise ValueError(
f"Profile name {name!r} is reserved — it collides with either "
@@ -229,7 +261,7 @@ def validate_alias_name(name: str) -> None:
"""Raise ``ValueError`` unless *name* is a safe wrapper filename: it is used verbatim
under ``~/.local/bin``, so ``../../.bashrc`` must never escape the wrapper dir."""
if not _PROFILE_ID_RE.match(name):
- raise ValueError(f"Invalid alias name {name!r}. Must match [a-z0-9][a-z0-9_-]{{0,63}}")
+ raise ValueError(f"Invalid alias name {name!r}. {_PROFILE_NAME_RULE}.")
def _canon_valid(name: str) -> str:
@@ -244,7 +276,7 @@ def _existing_profile_dir(name: str) -> Tuple[str, Path]:
canon = _canon_valid(name)
profile_dir = get_profile_dir(canon)
if not profile_dir.is_dir():
- raise FileNotFoundError(f"Profile '{canon}' does not exist.")
+ raise _unknown_profile_error(canon)
return canon, profile_dir
@@ -259,7 +291,7 @@ def get_profile_dir(name: str) -> Path:
# regex only, not _RESERVED_NAMES: a pre-reserved-list dir like
# profiles/hermes may still exist and must keep resolving.
if not _PROFILE_ID_RE.match(canon):
- raise ValueError(f"Invalid profile name {canon!r}. Must match [a-z0-9][a-z0-9_-]{{0,63}}")
+ raise _invalid_profile_name_error(canon)
return _get_profiles_root() / canon
@@ -880,10 +912,10 @@ def create_profile(
# Empty shells left by post-delete mkdir may be replaced. Identity files mean the
# leftover is not a shell — fail closed, no rmtree.
if (profile_dir / "config.yaml").exists() or (profile_dir / ".env").exists():
- raise FileExistsError(f"Profile '{canon}' already exists at {profile_dir}")
+ raise _profile_exists_error(canon)
shutil.rmtree(profile_dir)
if profile_dir.exists():
- raise FileExistsError(f"Profile '{canon}' already exists at {profile_dir}")
+ raise _profile_exists_error(canon)
source_dir = _resolve_clone_source(clone_from) if cloning else None
if source_dir is not None and clone_channels:
from hermes_cli.profile_channels import clone_channels_refusal
@@ -1666,7 +1698,7 @@ def import_profile(archive_path: str, name: Optional[str] = None) -> Path:
)
profile_dir = get_profile_dir(canon)
if profile_dir.exists():
- raise FileExistsError(f"Profile '{canon}' already exists at {profile_dir}")
+ raise _profile_exists_error(canon)
_get_profiles_root().mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix="hermes_profile_import_") as tmpdir:
staging_root = Path(tmpdir)
@@ -1749,9 +1781,9 @@ def rename_profile(old_name: str, new_name: str) -> Path:
old_dir = get_profile_dir(old_canon)
new_dir = get_profile_dir(new_canon)
if not old_dir.is_dir():
- raise FileNotFoundError(f"Profile '{old_canon}' does not exist.")
+ raise _unknown_profile_error(old_canon)
if new_dir.exists():
- raise FileExistsError(f"Profile '{new_canon}' already exists.")
+ raise _profile_exists_error(new_canon)
# 1. Stop gateway if running
if _check_gateway_running(old_dir):
diff --git a/hermes_cli/security_advisories.py b/hermes_cli/security_advisories.py
index f1c4f6f708b..7ffcbedb9c5 100644
--- a/hermes_cli/security_advisories.py
+++ b/hermes_cli/security_advisories.py
@@ -13,6 +13,8 @@ from dataclasses import dataclass
from pathlib import Path
from typing import Iterable, Optional
+from hermes_constants import display_hermes_home
+
logger = logging.getLogger(__name__)
@@ -26,7 +28,9 @@ logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class Advisory:
"""``id`` is lowercase-hyphen, stable and never reused (it is what acks key on). ``remediation``
- is ordered: uninstall command first, then credential audit/rotation guidance.
+ is ordered: uninstall command first, then credential audit/rotation guidance. Steps may use
+ ``{hermes_home}``; ``full_remediation_text`` fills it with ``display_hermes_home()`` at render
+ time so a profile / HERMES_HOME user is sent to their own .env.
"""
id: str
@@ -59,7 +63,7 @@ ADVISORIES: tuple[Advisory, ...] = (
compromised=(("mistralai", frozenset({"2.4.6"})),),
remediation=(
"Run: pip uninstall -y mistralai (or: uv pip uninstall mistralai)",
- "Rotate API keys in ~/.hermes/.env (OpenRouter, Anthropic, OpenAI, "
+ "Rotate API keys in {hermes_home}/.env (OpenRouter, Anthropic, OpenAI, "
"Nous, GitHub, AWS, Google, Mistral, etc.).",
"Audit ~/.npmrc, ~/.pypirc, ~/.aws/credentials, ~/.config/gh/hosts.yml, "
"and any other credential files for tokens that may have been read.",
@@ -186,7 +190,7 @@ def full_remediation_text(hit: AdvisoryHit) -> list[str]:
a.summary,
"",
"Remediation:",
- *(f" {i}. {step}" for i, step in enumerate(a.remediation, 1)),
+ *(f" {i}. {step.format(hermes_home=display_hermes_home())}" for i, step in enumerate(a.remediation, 1)),
]
diff --git a/hermes_cli/sessions_cmd.py b/hermes_cli/sessions_cmd.py
index 1a53aea2862..6a8ab05b491 100644
--- a/hermes_cli/sessions_cmd.py
+++ b/hermes_cli/sessions_cmd.py
@@ -45,7 +45,7 @@ def _confirm_prompt(prompt: str) -> bool:
def _not_found(session_id) -> int:
- print(f"Session '{session_id}' not found.")
+ print(f"No session '{session_id}'. Run: hermes sessions list to find the id.")
return 1
@@ -988,7 +988,9 @@ def cmd_sessions(args, sessions_parser=None):
# mode=ro cannot create the store; a reader on a fresh profile reports empty rather than failing.
if observational and not _default_db_path().exists():
return _print_empty_store(action, args)
- print(f"Error: Could not open session database: {e}")
+ print("Could not open your session history database. "
+ "Run: hermes sessions repair to fix it (a backup is made first).")
+ print(f"Details: {e}")
return 1
try:
handler = _DB_HANDLERS.get(action)
diff --git a/hermes_cli/setup.py b/hermes_cli/setup.py
index 6d89bb4ad14..62bc64e8aba 100644
--- a/hermes_cli/setup.py
+++ b/hermes_cli/setup.py
@@ -380,8 +380,11 @@ def setup_model_provider(config: dict, *, quick: bool = False):
_info(None, "Provider setup skipped.")
except Exception as exc:
logger.debug("select_provider_and_model error during setup: %s", exc)
- print_warning(f"Provider setup encountered an error: {exc}")
- print_info("You can try again later with: hermes model")
+ from hermes_cli.auth_error_copy import provider_setup_failure_lines
+ lead, *rest = provider_setup_failure_lines(exc, retry_command="hermes model")
+ print_warning(lead)
+ for line in rest:
+ print_info(line)
# Re-sync from disk in place: cmd_model saved via its own load/save cycle and the wizard's
# final save_config(config) must not clobber it with stale values. Rotation, vision and TTS
diff --git a/hermes_cli/setup_quick.py b/hermes_cli/setup_quick.py
index 0b0f4623ea8..1696d1603c2 100644
--- a/hermes_cli/setup_quick.py
+++ b/hermes_cli/setup_quick.py
@@ -64,9 +64,12 @@ def _run_portal_one_shot(config: dict) -> None:
" Sign up: https://portal.nousresearch.com/manage-subscription", None)
def _on_error(exc: Exception) -> None:
+ from hermes_cli.auth_error_copy import provider_setup_failure_lines
print()
- print_error(f" Nous Portal setup encountered an error: {exc}")
- print_info(" You can retry later with `hermes portal`.")
+ lead, *rest = provider_setup_failure_lines(exc, retry_command="hermes portal")
+ print_error(f" {lead}")
+ for line in rest:
+ print_info(f" {line}")
if not _run_nous_flow(config, context="`hermes portal`", cancel_exc=(KeyboardInterrupt, EOFError, SystemExit),
cancel_lines=(None, " Setup cancelled.", " You can retry later with `hermes portal`."),
@@ -95,8 +98,11 @@ def _run_first_time_quick_setup(config: dict, hermes_home, is_existing: bool):
"Sign up: https://portal.nousresearch.com/manage-subscription", None)
def _on_error(exc: Exception) -> None:
- print_warning(f"Nous Portal setup encountered an error: {exc}")
- print_info("You can try again later with: hermes model")
+ from hermes_cli.auth_error_copy import provider_setup_failure_lines
+ lead, *rest = provider_setup_failure_lines(exc, retry_command="hermes model")
+ print_warning(lead)
+ for line in rest:
+ print_info(line)
_run_nous_flow(config, context="quick setup", cancel_exc=(KeyboardInterrupt, EOFError),
cancel_lines=(None, "Nous Portal setup cancelled."), print_error=_on_error)
diff --git a/hermes_cli/skills_hub.py b/hermes_cli/skills_hub.py
index 8da9a77c442..e46e1725b60 100644
--- a/hermes_cli/skills_hub.py
+++ b/hermes_cli/skills_hub.py
@@ -304,7 +304,7 @@ def _prompt_for_category(c: Console, existing: List[str]) -> str:
c.print(f"[dim]Existing: {', '.join(existing)}[/]")
else:
c.print("[bold]Category[/] "
- "[dim](optional — press Enter to install flat at ~/.hermes/skills/<name>/)[/]")
+ f"[dim](optional — press Enter to install flat at {display_hermes_home()}/skills/<name>/)[/]")
answer = _line_input("Category: ")
if answer and not _VALID_CATEGORY_RE.match(answer):
c.print(f"[dim]Invalid category {answer!r} — installing flat.[/]")
@@ -491,15 +491,31 @@ def inspect_skill(identifier: str) -> Optional[dict]:
# --- install ---
def _install_blocked(c: Console, bundle, message: str, verdict: str, detail: str,
- q_path: Optional[Path] = None, lead: str = "") -> None:
+ q_path: Optional[Path] = None, lead: str = "", label: str = "Installation blocked:") -> None:
"""Print the blocked-install line, drop the quarantine copy, append the audit row."""
- c.print(f"{lead}[bold red]Installation blocked:[/] {message}")
+ c.print(f"{lead}[bold red]{label}[/] {message}")
if q_path is not None:
shutil.rmtree(q_path, ignore_errors=True)
from tools.skills_hub import append_audit_log
append_audit_log("BLOCKED", bundle.name, bundle.source, bundle.trust_level, verdict, detail)
+def _scan_block_message(result, identifier: str) -> str:
+ """User-facing sentence for a scan-blocked install (the audit row keeps the scanner's raw reason).
+
+ Says what happened (not installed), why in plain words (high-risk patterns), whether ``--force``
+ can help, and the read-only next step (``hermes skills inspect``). The hard-block rule mirrors
+ ``tools.skills_guard.should_allow_install``: a dangerous verdict on a non-official source."""
+ n = len(result.findings)
+ findings = f"{n} high-risk pattern(s)" if n else "high-risk patterns"
+ hard_block = result.verdict == "dangerous" and result.trust_level in ("community", "trusted")
+ policy = ("Hermes never installs unverified skills with high-risk findings, even with --force."
+ if hard_block else "Re-run with --force to install anyway.")
+ return (f"the security scan found {findings} in '{identifier}' (listed above). "
+ f"{policy} Review the findings or ask the author to fix them; to read the skill without "
+ f"installing, run `hermes skills inspect {identifier}`.")
+
+
def _invalid_path(c: Console, bundle, exc: ValueError, q_path: Optional[Path] = None) -> None:
_install_blocked(c, bundle, f"{exc}\n", "invalid_path", str(exc), q_path=q_path)
@@ -598,14 +614,15 @@ def _print_fetch_failure(c: Console, sources, identifier: str, meta=None, source
c.print("[dim]Stale index entry: the skill was likely renamed or removed by "
"its author. Try `hermes skills search` for an alternative.[/]\n")
return
- c.print(f"[bold red]Error:[/] Could not fetch '{identifier}' from any source.")
+ c.print(f"[bold red]Error:[/] Could not download '{identifier}'.")
if rate_limited:
c.print("[yellow]Hint:[/] GitHub API rate limit exhausted "
"(unauthenticated: 60 requests/hour).\n"
"Set [bold]GITHUB_TOKEN[/] in your .env or install the [bold]gh[/] CLI and run "
"[bold]gh auth login[/] to raise the limit to 5,000/hr.\n")
else:
- c.print()
+ c.print(f"Check the name with [bold]hermes skills search {identifier.rsplit('/', 1)[-1]}[/] "
+ "and check your internet connection. If it keeps failing, run [bold]hermes doctor[/].\n")
def _scan_quarantined(c: Console, q_path: Path, bundle, meta, identifier: str):
@@ -703,10 +720,10 @@ def do_install(identifier: str, category: str = "", force: bool = False,
c.print(f"[dim]Quarantined to {q_path.relative_to(q_path.parent.parent.parent)}[/]")
result = _scan_quarantined(c, q_path, bundle, meta, identifier)
- allowed, reason = should_allow_install(result, force=force)
+ allowed, _reason = should_allow_install(result, force=force)
if not allowed:
- _install_blocked(c, bundle, reason, result.verdict, f"{len(result.findings)}_findings",
- q_path=q_path, lead="\n")
+ _install_blocked(c, bundle, _scan_block_message(result, identifier), result.verdict,
+ f"{len(result.findings)}_findings", q_path=q_path, lead="\n", label="Not installed:")
return
# Advisory second opinion — warn-and-continue by design (PII-class findings are
# informational); the install confirmation below is where the user decides.
diff --git a/hermes_cli/tool_availability_notices.py b/hermes_cli/tool_availability_notices.py
new file mode 100644
index 00000000000..4a68a125d6d
--- /dev/null
+++ b/hermes_cli/tool_availability_notices.py
@@ -0,0 +1,82 @@
+"""Startup notice lines for toolsets that are switched off because their requirements are not met.
+
+Pure rendering: ``cli.py::_show_tool_availability_warnings`` feeds it the ``unavailable`` list from
+``check_tool_availability()`` (entries carry ``name`` / ``env_vars`` / ``tools``) and prints the lines.
+Each line says what is off and the exact command that fixes it, in plain words; env-var names only
+appear as secondary detail for toolsets with a single obvious key.
+"""
+
+from __future__ import annotations
+
+from typing import Callable, Iterable, Optional
+
+# Toolsets whose ``env_vars`` list is a multi-provider dump that means nothing to a user; render one
+# sentence per toolset instead. Provider names must exist under plugins/web/ (or be the Nous-managed row).
+_MULTI_PROVIDER_NOTICES: dict[str, str] = {
+ "web": ("[yellow]⚠ Web search is off[/] — no search provider is set up yet (any one of Nous subscription, Exa, "
+ "Tavily, Firecrawl, Brave, or free DuckDuckGo works). Run [bold]hermes setup tools[/] and set one up under "
+ "\"Web Search & Scraping\"."),
+}
+
+_GENERIC_FOOTER = "[dim] Run 'hermes setup tools' to configure[/]"
+
+
+def filter_to_enabled_toolsets(unavailable: list[dict], enabled: Iterable[str],
+ resolve: Callable[[str], Iterable[str]]) -> list[dict]:
+ """Keep only the *unavailable* entries this session would actually load.
+
+ ``enabled`` is the CLI's toolset selection as configured — on a default install that is a
+ composite bundle such as ``["hermes-cli"]``, never the individual names ``check_tool_availability``
+ reports — so each entry is expanded to tool names through ``resolve`` (``toolsets.resolve_toolset``)
+ and an unavailable toolset counts as enabled when its name is listed directly or any of its tools
+ is inside the expansion. An empty selection means "everything", so nothing is filtered."""
+ names = [str(t) for t in (enabled or []) if str(t)]
+ if not names:
+ return list(unavailable)
+ enabled_tools: set[str] = set()
+ for name in names:
+ try:
+ enabled_tools.update(str(t) for t in (resolve(name) or ()))
+ except Exception:
+ continue
+ name_set = set(names)
+
+ def _kept(item: dict) -> bool:
+ if str(item.get("name") or "") in name_set:
+ return True
+ return any(str(t) in enabled_tools for t in (item.get("tools") or ()))
+
+ return [item for item in unavailable if _kept(item)]
+
+
+def current_terminal_backend() -> str:
+ """The terminal backend selected for this process (``terminal.backend`` / TERMINAL_ENV), e.g. 'docker'."""
+ from tools.terminal_tool import _get_env_config
+ return str(_get_env_config().get("env_type") or "local")
+
+
+def _terminal_line(backend: str, reason: Optional[str]) -> str:
+ detail = f" ({reason})" if reason else ""
+ return (f"[yellow]⚠ Terminal tool disabled:[/] the '{backend}' backend is not usable{detail}. "
+ "Run [bold]hermes doctor[/] for details, or [bold]hermes setup terminal[/] to pick another backend.")
+
+
+def tool_availability_warning_lines(unavailable: list[dict], *, terminal_reason: Optional[str],
+ terminal_backend: str = "local") -> list[str]:
+ """Rich-markup lines to print at CLI startup for *unavailable* toolsets; ``[]`` when there is nothing
+ worth saying. ``terminal_reason`` is ``terminal_backend_unavailable_reason()`` (None when unknown)."""
+ lines: list[str] = []
+ generic: list[dict] = []
+ for item in unavailable:
+ name = str(item.get("name") or "")
+ if name == "terminal":
+ lines.append(_terminal_line(terminal_backend, terminal_reason))
+ elif name in _MULTI_PROVIDER_NOTICES:
+ lines.append(_MULTI_PROVIDER_NOTICES[name])
+ elif item.get("env_vars"):
+ generic.append(item)
+ if generic:
+ lines.append("[yellow]⚠️ Some tools disabled (missing API keys):[/]")
+ lines.extend(f" [dim]• {item['name']}[/] [dim italic]({', '.join(item['env_vars'])})[/]" for item in generic)
+ lines.append(_GENERIC_FOOTER)
+ return lines
diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.py
index 67cd72017af..38e36487843 100644
--- a/hermes_cli/update_cmd.py
+++ b/hermes_cli/update_cmd.py
@@ -1151,17 +1151,21 @@ def _handle_update_called_process_error(
if gateway_mode:
_write_gateway_update_exit_code(desktop_build_ok)
else:
- print(f"✗ {stage}: {e}")
- _print_called_process_error_tail(e)
if _called_process_error_is_python_dep_install(e):
- print(
- " The git update already finished. Re-downloading the source "
- "ZIP cannot fix a dependency install error and would overwrite local files.")
+ print(f"✗ {stage} (the code update itself succeeded).")
+ _print_called_process_error_tail(e)
+ print()
+ print(" Hermes may not start until the dependencies are installed. Fix the error above")
+ print(" (usually network or disk space), then run `hermes update` again.")
if _m()._is_windows():
- print(" Retry through the venv interpreter:")
+ print(" If `hermes update` itself will not start, retry through the venv interpreter:")
print(
' venv\\Scripts\\python.exe -c '
'"from hermes_cli.main import main; main()" update --yes')
+ else:
+ print(f"✗ {stage}.")
+ print(f" Details: {e}")
+ _print_called_process_error_tail(e)
_finalize_receipt("failed", 'Update receipt finalize failed: %s')
sys.exit(1)
diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.py
index 11078636179..78e995d99e1 100644
--- a/hermes_cli/update_cmd_maint.py
+++ b/hermes_cli/update_cmd_maint.py
@@ -46,7 +46,25 @@ _PRE_UPDATE_SNAPSHOT_KEEP = 1
# small hard-to-regenerate state, not a multi-GB state.db (24 GB cost ~60s + 24 GB/update).
_PRE_UPDATE_SNAPSHOT_MAX_FILE_SIZE = 1 << 30 # 1 GiB
-_SQLITE_WAL_BUG_DETAIL = "SQLite {} still has the WAL-reset corruption bug"
+#: Reinstalling through the official installer swaps in a Python whose SQLite is safe; the
+#: one-liner differs per OS (mirrors ``uninstall._REINSTALL_HINT``). windows -> command
+_REINSTALL_ONE_LINER = {
+ True: "iex (irm https://hermes-agent.nousresearch.com/install.ps1)",
+ False: "curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash",
+}
+
+
+def _sqlite_partial_completion_lines(sqlite_version: str) -> list[str]:
+ """Shared ``⚠ Update partially complete`` wording for a vulnerable post-update SQLite, so the
+ two completion banners cannot drift. The lead names the consequence, the second line the
+ exact fix command."""
+ from hermes_cli.update_cmd import _m
+ return [
+ f"⚠ Update partially complete — your Python's SQLite ({sqlite_version}) has a known "
+ "corruption bug. Hermes works, but sessions could be damaged.",
+ f" Fix: run the installer again ({_REINSTALL_ONE_LINER[bool(_m()._is_windows())]}) "
+ "which installs a safe Python, then run `hermes doctor` to confirm.",
+ ]
def _load_updates_cfg() -> dict:
@@ -405,8 +423,8 @@ def _print_verified_update_completion(message: str) -> bool:
_print_update_completion(message)
return True
print()
- print(f"⚠ Update partially complete — {_SQLITE_WAL_BUG_DETAIL.format(sqlite_info.sqlite_version_string)}.")
- print(" Rebuild the Hermes venv with a uv-managed Python, restart Hermes, then verify with `hermes doctor`.")
+ for line in _sqlite_partial_completion_lines(sqlite_info.sqlite_version_string):
+ print(line)
return False
@@ -440,21 +458,16 @@ def _print_update_summary(*, node_failures: list, desktop_build_ok: bool, pre_up
parts.append(f"Node.js dependencies for {', '.join(node_failures)} did not refresh")
if not desktop_build_ok:
parts.append("the desktop app was not rebuilt and is still on the previous build")
- if not sqlite_runtime_ok and sqlite_info is not None:
- parts.append(_SQLITE_WAL_BUG_DETAIL.format(sqlite_info.sqlite_version_string))
- print("⚠ Update partially complete — " + "; ".join(parts) + ".")
+ if parts:
+ print("⚠ Update partially complete — " + "; ".join(parts) + ".")
if node_failures:
print(" Code and Python deps are updated, but the dashboard/TUI may")
print(" be in a mixed state until the Node deps are rebuilt.")
if not desktop_build_ok:
print(" Run `hermes desktop` to retry the desktop rebuild.")
if not sqlite_runtime_ok:
- print(
- " The Python runtime remediation did not complete. Run `hermes "
- "update` again; if SQLite is unchanged, rebuild the Hermes venv "
- "with a uv-managed Python, restart Hermes, then verify with "
- "`hermes doctor`."
- )
+ for line in _sqlite_partial_completion_lines(sqlite_info.sqlite_version_string):
+ print(line)
else:
_print_update_completion(_update_complete_message(pre_update_version))
return desktop_build_ok and sqlite_runtime_ok
diff --git a/hermes_cli/update_lock.py b/hermes_cli/update_lock.py
index 871093acd75..4e8c74a28cc 100644
--- a/hermes_cli/update_lock.py
+++ b/hermes_cli/update_lock.py
@@ -134,12 +134,12 @@ def describe_holder(holder: UpdateHolder) -> str:
minutes, seconds = divmod(int(max(holder.age_seconds, 0)), 60)
elapsed = f"{minutes}m {seconds}s" if minutes else f"{seconds}s"
return (
- f"✗ Another Hermes update is already running (PID {holder.pid}, "
- f"started {elapsed} ago).\n"
+ f"✗ Another Hermes update is already running (started {elapsed} ago, "
+ f"process {holder.pid}).\n"
"\n"
- " Two updates mutating the same checkout corrupt it: one rewrites\n"
- " source while the other is mid-install. Wait for it to finish, or\n"
- " close the window/dashboard tab that started it, then retry."
+ " Running two at once would corrupt the install. Wait for it to finish\n"
+ " (watch `hermes logs`), or close the Desktop/dashboard window that\n"
+ " started it, then run `hermes update` again."
)
diff --git a/hermes_cli/update_receipt.py b/hermes_cli/update_receipt.py
index 399e0407f3b..e13f04d0ffb 100644
--- a/hermes_cli/update_receipt.py
+++ b/hermes_cli/update_receipt.py
@@ -379,13 +379,19 @@ def print_fleet_version_matrix(fleet: list[dict[str, Any]]) -> bool:
print(_FLEET_ROW_LINES.get(entry.get("state"), _FLEET_ROW_UNKNOWN).format(
profile=entry.get("profile"), pid=entry.get("pid"), short=sha[:8] if isinstance(sha, str) and sha else "?",
))
- any_stale, any_down = "stale" in states, "down" in states
- if any_stale or any_down:
+ stale_or_down = sum(1 for entry in fleet if entry.get("state") in ("stale", "down"))
+ if stale_or_down:
print()
- if any_stale:
- print(" ⚠ Stale gateways keep serving pre-update code until restarted:")
- if any_down:
- print(" ⚠ Down gateways stopped serving messaging entirely — restart them:")
- print(" hermes gateway restart # active profile")
- print(" hermes -p <profile> gateway restart # named profile")
- return any_stale or any_down
+ if "stale" in states:
+ print(" ⚠ Stale gateways keep serving pre-update code until restarted.")
+ if "down" in states:
+ print(" ⚠ Down gateways stopped serving messaging entirely.")
+ # ``✓ Update complete!`` was already printed before the restart phase (the exit code
+ # must land before a systemd restart can kill this process), so this verdict has to
+ # supersede it explicitly — otherwise the output says success while the exit code is 1.
+ print()
+ print(
+ f"✗ Update not complete: {stale_or_down} gateway(s) still running the old code (or stopped).")
+ print(" Run `hermes gateway restart` (or `hermes -p <profile> gateway restart` for a named")
+ print(" profile), then `hermes gateway status` to confirm.")
+ return stale_or_down > 0
diff --git a/hermes_state.py b/hermes_state.py
index a977424915a..87b143017c4 100644
--- a/hermes_state.py
+++ b/hermes_state.py
@@ -103,10 +103,11 @@ class SessionResumeTooLargeError(ValueError):
self, message_count: int, limit: int = _MAX_SAFE_MESSAGES, scope: str = "across its lineage",
):
self.message_count, self.limit = message_count, limit
+ self.scope = scope
super().__init__(
- f"session has at least {message_count} active messages {scope}; "
- f"safe resume limit is {limit}. Export the session instead, or set "
- "sessions.max_resume_messages: 0 in config.yaml to disable the guard."
+ f"This session is too long to reload safely ({message_count} messages; limit {limit}). "
+ "Start a fresh chat and use `hermes sessions export` to keep a copy, or raise the limit "
+ "with `hermes config set sessions.max_resume_messages 0`."
)
@@ -336,13 +337,43 @@ def _strip_stale_tool_call_markers(messages: List[Dict[str, Any]]) -> List[Dict[
return messages
-def format_session_db_unavailable(prefix: str = "Session database not available") -> str:
- """User-facing message with the captured init cause (+ WAL-docs hint for NFS/SMB locking failures)."""
+_SESSION_DB_CONSEQUENCE = "Sessions will not be saved until this is fixed."
+_NETWORK_DRIVE_HINT = " If the database lives on a network drive, move it to a local disk."
+_NETWORK_DRIVE_GLOSS = "the session database could not be opened; it may be on a network or unsupported drive"
+_NETWORK_DRIVE_ACTION = (
+ "Move it to a local disk (`hermes doctor` shows where it is), then start Hermes again."
+)
+
+
+def format_session_db_unavailable(
+ prefix: str = "Hermes can't open its session history right now",
+ *,
+ details: bool = False,
+) -> str:
+ """User-facing one-liner: ``<prefix>: <gloss>. <consequence> <action>[ network hint]``.
+
+ The cause table lives in ``hermes_state_user_copy`` so CLI, gateway and TUI agree. Chat
+ surfaces (gateway, TUI) get the one-liner; ``details=True`` (the CLI banner) appends a
+ ``Details: <raw cause>`` line for the raw SQLite text. Network filesystems (NFS/SMB/FUSE/ZFS)
+ cannot host SQLite's write-ahead log: when the raw cause carries one of those markers the
+ message names the network-drive suspicion, because ``hermes doctor --fix`` cannot repair a
+ mount — only moving the file can."""
cause = get_last_init_error()
if not cause:
- return f"{prefix}."
- hint = " (state.db may be on NFS/SMB/FUSE/ZFS — see https://www.sqlite.org/wal.html)"
- return f"{prefix}: {cause}{hint if any(m in cause.lower() for m in _WAL_INCOMPAT_MARKERS) else ''}."
+ return f"{prefix}. {_SESSION_DB_CONSEQUENCE} Run `hermes doctor` to check the storage location."
+ from hermes_state_user_copy import describe_storage_failure
+ failure = describe_storage_failure(cause)
+ gloss, action, hint = failure.gloss, failure.action, ""
+ if any(m in cause.lower() for m in _WAL_INCOMPAT_MARKERS):
+ if failure.cause == "unknown":
+ gloss, action = _NETWORK_DRIVE_GLOSS, _NETWORK_DRIVE_ACTION
+ else:
+ hint = _NETWORK_DRIVE_HINT
+ text = f"{prefix}: {gloss}. {_SESSION_DB_CONSEQUENCE} {action}{hint}"
+ if details:
+ from hermes_state_user_copy import storage_failure_details
+ text += f"\nDetails: {storage_failure_details(cause)}"
+ return text
# Auto-repair at most once per DB path per process (no repair loops; serialises concurrent
@@ -664,13 +695,12 @@ class SessionDB(
except OSError:
zsize = -1
qpath = quarantine_invalid_state_db(self.db_path, already_locked=already_locked)
+ where = f"moved aside to {qpath}" if qpath else "left in place (it could not be moved aside)"
msg = (
- f"state.db has no SQLite header ({zsize} bytes). "
- f"Preserved at {qpath or '(quarantine failed — file left in place)'}. "
- f"Restore from {self.db_path.parent / 'state-snapshots'} via `hermes snapshot list` / "
- f"`hermes snapshot restore <id>` if available, or salvage the preserved bytes with "
- f"`hermes sessions recover --source {qpath or self.db_path}`. "
- "Opening a fresh empty database so the agent can start."
+ f"state.db was empty or damaged ({zsize} bytes) and has been {where}; Hermes started with a "
+ "fresh, empty session database. To bring old sessions back, run "
+ f"`hermes sessions recover --source {qpath or self.db_path} --inspect-only`, or restore a "
+ "snapshot with `/snapshot list` then `/snapshot restore <id>` (terminal `hermes` chat only)."
)
logger.error(msg)
_set_last_init_error(msg)
diff --git a/hermes_state_dbfile.py b/hermes_state_dbfile.py
index 4a96cff79ee..1aff9c790e4 100644
--- a/hermes_state_dbfile.py
+++ b/hermes_state_dbfile.py
@@ -690,8 +690,9 @@ def quarantine_invalid_state_db(path: Path, *, already_locked: bool = False) ->
if not acquired:
logger.error("quarantine lock for %s not acquired within 5s — refusing to "
"quarantine without the cross-process lock. The invalid file "
- "is left in place. If sessions fail to load, restore from "
- "state-snapshots via `hermes snapshot list` / `hermes snapshot restore <id>`.",
+ "is left in place. If sessions fail to load, run `hermes sessions recover "
+ "--source <state.db> --inspect-only`, or restore a snapshot with "
+ "`/snapshot list` / `/snapshot restore <id>` (terminal `hermes` chat only).",
path)
return None
return _do_quarantine()
diff --git a/hermes_state_user_copy.py b/hermes_state_user_copy.py
new file mode 100644
index 00000000000..df4e9389739
--- /dev/null
+++ b/hermes_state_user_copy.py
@@ -0,0 +1,96 @@
+"""Plain-language copy for "session storage is unavailable / could not be written" notices.
+
+One table keyed by ``classify_persistence_error``'s cause bucket feeds every surface (CLI banner,
+gateway home-channel warning, TUI/Desktop RPC errors) so they agree on what happened, what to do,
+and a machine-readable ``code`` a GUI can attach a "Run doctor" button to.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+from hermes_state_errors import classify_persistence_error, is_disk_full_error
+
+
+@dataclass(frozen=True)
+class StorageFailure:
+ cause: str # classify_persistence_error bucket
+ code: str # machine-readable, stable: storage_locked | storage_readonly | storage_corrupt | disk_full | ...
+ gloss: str # what happened, one clause, lowercase start
+ action: str # what to do, one sentence naming the exact command
+
+
+_DOCTOR = "Run `hermes doctor --fix` to diagnose and repair."
+
+# cause -> (code, gloss, action). "disk" is split by is_disk_full_error at lookup time.
+_STORAGE_FAILURES: dict[str, tuple[str, str, str]] = {
+ "locked": (
+ "storage_locked",
+ "the session database is locked by another Hermes process",
+ "Wait a moment and try again; if it persists, stop the other Hermes process (`hermes gateway stop`).",
+ ),
+ "disk_full": (
+ "disk_full",
+ "the disk is full",
+ "Free some disk space, then try again.",
+ ),
+ "disk": (
+ "storage_readonly",
+ "the session database file is read-only or not writable",
+ _DOCTOR,
+ ),
+ "corrupt": (
+ "storage_corrupt",
+ "the session database file is damaged",
+ f"{_DOCTOR} Recovery: `hermes sessions recover --source <state.db> --inspect-only`.",
+ ),
+ "fts_index": (
+ "storage_index_corrupt",
+ "the session search index is damaged (the messages themselves are intact)",
+ "Run `hermes doctor --fix` (or `hermes sessions repair`) to rebuild it.",
+ ),
+ "replaced": (
+ "storage_replaced",
+ "the session database file was replaced while Hermes was running",
+ "Stop Hermes (`hermes gateway stop`), run `hermes doctor`, then start it again.",
+ ),
+ "deleted_wal": (
+ "storage_replaced",
+ "the session database file was changed or replaced while Hermes was running",
+ "Stop Hermes (`hermes gateway stop`), run `hermes doctor`, then start it again.",
+ ),
+ "compression": (
+ "storage_busy",
+ "another process is compressing this session",
+ "Send your message again once compression finishes.",
+ ),
+ "compression_closed": (
+ "storage_session_rotated",
+ "this session was rotated by context compression",
+ "Refresh the client (or start a new turn) and send your message again.",
+ ),
+ "turn_lease": (
+ "storage_busy",
+ "another Hermes process took over this session",
+ "Wait for it to finish, then send your message again.",
+ ),
+ "unknown": (
+ "storage_unavailable",
+ "the session database could not be opened",
+ _DOCTOR,
+ ),
+}
+
+
+def describe_storage_failure(exc_or_str) -> StorageFailure:
+ """Plain-language description of a persistence failure (never raises)."""
+ cause = classify_persistence_error(exc_or_str)
+ key = "disk_full" if cause == "disk" and is_disk_full_error(exc_or_str) else cause
+ code, gloss, action = _STORAGE_FAILURES.get(key, _STORAGE_FAILURES["unknown"])
+ return StorageFailure(cause=cause, code=code, gloss=gloss, action=action)
+
+
+def storage_failure_details(exc_or_str, limit: int = 200) -> str:
+ """Raw cause for a trailing, secondary "Details:" line (never the lead sentence)."""
+ text = " ".join(str(exc_or_str or "").split())
+ return text if len(text) <= limit else text[: limit - 3].rstrip() + "..."
diff --git a/locales/af.yaml b/locales/af.yaml
index a9f6d4ec5ee..65c90b2bf9c 100644
--- a/locales/af.yaml
+++ b/locales/af.yaml
@@ -11,7 +11,7 @@ approval:
prompt_smart_deny: " Keuse [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ Tyd verstreke - opdrag word geweier"
+ timeout: " ⏱ Geen antwoord binne {waited} — die opdrag is nie uitgevoer nie. Vra weer om te herprobeer, of verhoog die limiet: hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ Eenmalig toegelaat"
allowed_session: " ✓ Vir hierdie sessie toegelaat"
allowed_always: " ✓ By permanente toelaatlys gevoeg"
diff --git a/locales/ar.yaml b/locales/ar.yaml
index 1fb91719b44..7264ca816fc 100644
--- a/locales/ar.yaml
+++ b/locales/ar.yaml
@@ -16,7 +16,7 @@ approval:
prompt_smart_deny: " الاختيار [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ انتهت المهلة - يتم رفض الأمر"
+ timeout: " ⏱ لا توجد إجابة خلال {waited} — لم يتم تنفيذ الأمر. اطلب مرة أخرى لإعادة المحاولة، أو ارفع الحد: hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ مسموح مرة واحدة"
allowed_session: " ✓ مسموح لهذه الجلسة"
allowed_always: " ✓ أُضيف إلى قائمة السماح الدائمة"
diff --git a/locales/de.yaml b/locales/de.yaml
index 953f841ec34..90f41cd9b30 100644
--- a/locales/de.yaml
+++ b/locales/de.yaml
@@ -11,7 +11,7 @@ approval:
prompt_smart_deny: " Auswahl [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ Zeitüberschreitung – Befehl wird abgelehnt"
+ timeout: " ⏱ Keine Antwort innerhalb von {waited} — der Befehl wurde nicht ausgeführt. Erneut anfragen, um es noch einmal zu versuchen, oder das Limit erhöhen: hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ Einmalig erlaubt"
allowed_session: " ✓ Für diese Sitzung erlaubt"
allowed_always: " ✓ Zur dauerhaften Erlaubnisliste hinzugefügt"
diff --git a/locales/en.yaml b/locales/en.yaml
index 6c4c84b7396..63be6f188a2 100644
--- a/locales/en.yaml
+++ b/locales/en.yaml
@@ -21,7 +21,7 @@ approval:
prompt_smart_deny: " Choice [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ Timeout - denying command"
+ timeout: " ⏱ No answer in {waited} — the command was not run. Ask again to retry, or raise the limit: hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ Allowed once"
allowed_session: " ✓ Allowed for this session"
allowed_always: " ✓ Added to permanent allowlist"
diff --git a/locales/es.yaml b/locales/es.yaml
index 926019b20b5..afbcc11c16d 100644
--- a/locales/es.yaml
+++ b/locales/es.yaml
@@ -11,7 +11,7 @@ approval:
prompt_smart_deny: " Opción [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ Tiempo agotado — comando denegado"
+ timeout: " ⏱ Sin respuesta en {waited} — el comando no se ejecutó. Pide de nuevo para reintentar, o sube el límite: hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ Permitido una vez"
allowed_session: " ✓ Permitido en esta sesión"
allowed_always: " ✓ Añadido a la lista de permitidos permanente"
diff --git a/locales/fr.yaml b/locales/fr.yaml
index 94b2633567c..55a908d8ee2 100644
--- a/locales/fr.yaml
+++ b/locales/fr.yaml
@@ -11,7 +11,7 @@ approval:
prompt_smart_deny: " Choix [o/R] : "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "r,refuser"
- timeout: " ⏱ Délai dépassé — commande refusée"
+ timeout: " ⏱ Aucune réponse en {waited} — la commande n'a pas été exécutée. Redemandez pour réessayer, ou augmentez la limite : hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ Autorisé une fois"
allowed_session: " ✓ Autorisé pour cette session"
allowed_always: " ✓ Ajouté à la liste d'autorisation permanente"
diff --git a/locales/ga.yaml b/locales/ga.yaml
index e2315e945fe..47a7ab9c530 100644
--- a/locales/ga.yaml
+++ b/locales/ga.yaml
@@ -15,7 +15,7 @@ approval:
prompt_smart_deny: " Rogha [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ Am istigh — ag diúltú don ordú"
+ timeout: " ⏱ Gan freagra laistigh de {waited} — níor ritheadh an t-ordú. Iarr arís le triail eile a bhaint as, nó ardaigh an teorainn: hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ Ceadaithe uair amháin"
allowed_session: " ✓ Ceadaithe don seisiún seo"
allowed_always: " ✓ Curtha leis an liosta ceadaithe buan"
diff --git a/locales/hu.yaml b/locales/hu.yaml
index ac56e9e767e..a7a166eebe9 100644
--- a/locales/hu.yaml
+++ b/locales/hu.yaml
@@ -11,7 +11,7 @@ approval:
prompt_smart_deny: " Választás [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ Időtúllépés - parancs elutasítva"
+ timeout: " ⏱ Nem érkezett válasz {waited} alatt — a parancs nem futott le. Kérd újra a megismétléshez, vagy növeld a határt: hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ Egyszer engedélyezve"
allowed_session: " ✓ Engedélyezve ehhez a munkamenethez"
allowed_always: " ✓ Hozzáadva az állandó engedélylistához"
diff --git a/locales/it.yaml b/locales/it.yaml
index fee3d15782b..26c760e9a26 100644
--- a/locales/it.yaml
+++ b/locales/it.yaml
@@ -11,7 +11,7 @@ approval:
prompt_smart_deny: " Scelta [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ Tempo scaduto — comando negato"
+ timeout: " ⏱ Nessuna risposta entro {waited} — il comando non è stato eseguito. Richiedi di nuovo per riprovare, oppure aumenta il limite: hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ Consentito una volta"
allowed_session: " ✓ Consentito per questa sessione"
allowed_always: " ✓ Aggiunto alla lista permessi permanente"
diff --git a/locales/ja.yaml b/locales/ja.yaml
index 916dbe803ce..ab072669a04 100644
--- a/locales/ja.yaml
+++ b/locales/ja.yaml
@@ -11,7 +11,7 @@ approval:
prompt_smart_deny: " 選択 [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ タイムアウト — コマンドを拒否しました"
+ timeout: " ⏱ {waited} 以内に応答がなかったため、コマンドは実行されませんでした。もう一度依頼して再試行するか、制限を引き上げてください: hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ 今回のみ許可"
allowed_session: " ✓ このセッション中は許可"
allowed_always: " ✓ 永続的な許可リストに追加"
diff --git a/locales/ko.yaml b/locales/ko.yaml
index c1aacbfbacf..122e5abeb3c 100644
--- a/locales/ko.yaml
+++ b/locales/ko.yaml
@@ -11,7 +11,7 @@ approval:
prompt_smart_deny: " 선택 [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ 시간 초과 - 명령을 거부합니다"
+ timeout: " ⏱ {waited} 동안 응답이 없어 명령을 실행하지 않았습니다. 다시 요청해 재시도하거나 제한을 늘리세요: hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ 한 번 허용됨"
allowed_session: " ✓ 이 세션에서 허용됨"
allowed_always: " ✓ 영구 허용 목록에 추가됨"
diff --git a/locales/pt.yaml b/locales/pt.yaml
index f326cf36a34..b374d85160c 100644
--- a/locales/pt.yaml
+++ b/locales/pt.yaml
@@ -11,7 +11,7 @@ approval:
prompt_smart_deny: " Escolha [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ Tempo esgotado — comando negado"
+ timeout: " ⏱ Sem resposta em {waited} — o comando não foi executado. Peça novamente para tentar de novo, ou aumente o limite: hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ Permitido uma vez"
allowed_session: " ✓ Permitido nesta sessão"
allowed_always: " ✓ Adicionado à lista de permissões permanente"
diff --git a/locales/ru.yaml b/locales/ru.yaml
index e24ec940634..7d5979cbf48 100644
--- a/locales/ru.yaml
+++ b/locales/ru.yaml
@@ -11,7 +11,7 @@ approval:
prompt_smart_deny: " Выбор [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ Время ожидания истекло — команда отклонена"
+ timeout: " ⏱ Нет ответа в течение {waited} — команда не была выполнена. Попросите снова, чтобы повторить, или увеличьте лимит: hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ Разрешено один раз"
allowed_session: " ✓ Разрешено для этого сеанса"
allowed_always: " ✓ Добавлено в постоянный список разрешённых"
diff --git a/locales/tr.yaml b/locales/tr.yaml
index 6809686bf0f..f246c4f0ad2 100644
--- a/locales/tr.yaml
+++ b/locales/tr.yaml
@@ -11,7 +11,7 @@ approval:
prompt_smart_deny: " Seçim [b/R]: "
smart_deny_once_inputs: "b,bir kez"
smart_deny_deny_inputs: "r,reddet"
- timeout: " ⏱ Zaman aşımı — komut reddedildi"
+ timeout: " ⏱ {waited} içinde yanıt gelmedi — komut çalıştırılmadı. Yeniden denemek için tekrar isteyin veya sınırı yükseltin: hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ Bir kez izin verildi"
allowed_session: " ✓ Bu oturum için izin verildi"
allowed_always: " ✓ Kalıcı izin listesine eklendi"
diff --git a/locales/uk.yaml b/locales/uk.yaml
index f905eaa949d..e40ad030415 100644
--- a/locales/uk.yaml
+++ b/locales/uk.yaml
@@ -11,7 +11,7 @@ approval:
prompt_smart_deny: " Вибір [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ Час очікування вичерпано — команду відхилено"
+ timeout: " ⏱ Немає відповіді протягом {waited} — команду не виконано. Попросіть знову, щоб повторити, або збільште ліміт: hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ Дозволено один раз"
allowed_session: " ✓ Дозволено для цього сеансу"
allowed_always: " ✓ Додано до постійного списку дозволених команд"
diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yaml
index cd7b3b1648e..e8f43db4fcc 100644
--- a/locales/zh-hant.yaml
+++ b/locales/zh-hant.yaml
@@ -11,7 +11,7 @@ approval:
prompt_smart_deny: " 選擇 [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ 逾時 — 已拒絕指令"
+ timeout: " ⏱ {waited} 內沒有回應——未執行該指令。再次要求即可重試,或提高上限:hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ 本次允許"
allowed_session: " ✓ 本次工作階段內允許"
allowed_always: " ✓ 已加入永久允許清單"
diff --git a/locales/zh.yaml b/locales/zh.yaml
index 545d0528271..5fb003cf5ac 100644
--- a/locales/zh.yaml
+++ b/locales/zh.yaml
@@ -11,7 +11,7 @@ approval:
prompt_smart_deny: " 选择 [o/D]: "
smart_deny_once_inputs: "o,once"
smart_deny_deny_inputs: "d,deny"
- timeout: " ⏱ 超时 — 已拒绝命令"
+ timeout: " ⏱ {waited} 内没有回应——未执行该命令。再次请求即可重试,或提高上限:hermes config set approvals.timeout {suggested}"
allowed_once: " ✓ 本次允许"
allowed_session: " ✓ 本次会话内允许"
allowed_always: " ✓ 已加入永久允许列表"
diff --git a/plugins/platforms/discord/adapter.py b/plugins/platforms/discord/adapter.py
index dc16eb1b417..60e8f017c04 100644
--- a/plugins/platforms/discord/adapter.py
+++ b/plugins/platforms/discord/adapter.py
@@ -262,8 +262,9 @@ from gateway.platforms.helpers import (
)
from gateway.platforms.helpers import cancel_task
from utils import atomic_json_write, env_float
+from gateway.platforms.base_exec_approval import EA_HEADER_TEXT, EA_REASON_LABEL_TEXT
from gateway.platforms.base import (
- BasePlatformAdapter, ExecApprovalPrompt, SendResult,
+ BasePlatformAdapter, ExecApprovalPrompt, SendResult, unauthorized_action_notice,
cache_image_from_url, cache_image_from_bytes_async, cache_audio_from_url, cache_audio_from_bytes_async,
cache_document_from_bytes_async, SUPPORTED_DOCUMENT_TYPES, _TEXT_INJECT_EXTENSIONS,
_prefix_within_utf16_limit, utf16_len, validate_inbound_media_size,
@@ -275,6 +276,9 @@ from gateway.platforms._shared import (
platform_gate_env as _scoped_gate_env, send_error, yaml_env_setter as _yaml_env_setter
)
+# Every refusal (slash command, approval button, picker, prompt) says the same thing.
+_UNAUTHORIZED = unauthorized_action_notice(Platform.DISCORD)
+
async def _read_url_image_with_redirect_guard(
session: Any, url: str, *, timeout: Any, request_kwargs: Dict[str, Any],
@@ -3971,7 +3975,7 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
)
try:
await interaction.response.send_message(
- "You're not authorized to use this command.", ephemeral=True,
+ _UNAUTHORIZED, ephemeral=True,
)
except Exception as e:
# Interaction may already be responded to (caller deferred, Discord retry).
@@ -5302,19 +5306,19 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
return text if len(text) <= limit else text[: limit - 3] + "..."
# Payload lives in plain content: embeds can be invisible/detached on web/mobile.
- _EA_HEADER = ("⚠️ **Command Approval Required**\n\n"
+ _EA_HEADER = (f"⚠️ **{EA_HEADER_TEXT}**\n\n"
"Do you want Hermes to run this command?\n\n"
"**Requested command:**\n")
_EA_CODE_OPEN = "```bash\n"
_EA_CODE_CLOSE = "\n```\n"
- _EA_REASON_LABEL = "**Reason:** "
+ _EA_REASON_LABEL = f"**{EA_REASON_LABEL_TEXT}:** "
_EA_SMART_DENY_LINE = "\n\n**Smart DENY:** owner override applies to this one operation only."
_EA_REASON_BUDGET = 300
def _exec_approval_cmd_budget(self, description: str, smart_denied: bool) -> int:
# Mentions ride in front of the content and count against the 2000-char message cap too.
fixed = (len(self._EA_HEADER) + len(self._EA_CODE_OPEN) + len(self._EA_CODE_CLOSE)
- + len(self._EA_REASON_LABEL) + len(description) + len("...")
+ + len(self._EA_REASON_LABEL) + len(description) + len("...") + len(self._ea_deadline_line())
+ (len(self._EA_SMART_DENY_LINE) if smart_denied else 0)
+ len(self._approval_mention_content() or "") + 1)
return max(0, self.MAX_MESSAGE_LENGTH - fixed)
@@ -5327,11 +5331,11 @@ class DiscordAdapter(DiscordMediaMixin, BasePlatformAdapter):
if mention_content:
content = f"{mention_content}\n{content}"
embed = discord.Embed(
- title="⚠️ Command Approval Required",
+ title=f"⚠️ {EA_HEADER_TEXT}",
description=f"```\n{self._embed_body(prompt.command)}\n```",
color=discord.Color.orange(),
)
- embed.add_field(name="Reason", value=self._truncate_preview(prompt.description, self._EA_REASON_BUDGET), inline=False)
+ embed.add_field(name=EA_REASON_LABEL_TEXT, value=self._truncate_preview(prompt.description, self._EA_REASON_BUDGET), inline=False)
require_admin, admin_user_ids = _resolve_exec_approval_admin_gate(getattr(self.config, "extra", None))
choices = set(prompt.choices)
view = ExecApprovalView(
@@ -6123,7 +6127,7 @@ def _define_discord_view_classes() -> None:
"""Resolve the approval via the gateway approval queue and update the embed."""
if not await self._gate(
interaction, resolved_msg="This approval has already been resolved~",
- unauth_msg="You're not authorized to approve commands~",
+ unauth_msg=_UNAUTHORIZED,
):
return
self.resolved = True
@@ -6173,7 +6177,7 @@ def _define_discord_view_classes() -> None:
async def _resolve(self, interaction: discord.Interaction, choice: str, color: discord.Color, label: str):
if not await self._gate(
interaction, resolved_msg="This prompt has already been resolved~",
- unauth_msg="You're not authorized to answer this prompt~",
+ unauth_msg=_UNAUTHORIZED,
):
return
await self._finalize_embed(interaction, color, f"{label} by {interaction.user.display_name}")
@@ -6212,7 +6216,7 @@ def _define_discord_view_classes() -> None:
self.session_key = session_key
async def _respond(self, interaction: discord.Interaction, answer: str, color: discord.Color, label: str):
- if not await self._gate(interaction, resolved_msg="Already answered~", unauth_msg="You're not authorized~"):
+ if not await self._gate(interaction, resolved_msg="Already answered~", unauth_msg=_UNAUTHORIZED):
return
await self._finalize_embed(interaction, color, f"{label} by {interaction.user.display_name}")
try:
@@ -6334,7 +6338,7 @@ def _define_discord_view_classes() -> None:
return discord.Embed(title=title, description=description, color=discord.Color.blue() if color is None else color)
async def _on_provider_selected(self, interaction: discord.Interaction):
- if not await self._gate(interaction, resolved_msg=None, unauth_msg="You're not authorized~"):
+ if not await self._gate(interaction, resolved_msg=None, unauth_msg=_UNAUTHORIZED):
return
provider_slug = interaction.data["values"][0]
self._selected_provider = provider_slug
@@ -6348,7 +6352,7 @@ def _define_discord_view_classes() -> None:
await self._edit(interaction, f"Provider: **{pname}**\nSelect a model:{extra}")
async def _switch_selected_model(self, interaction: discord.Interaction, model_id: str):
- if not await self._gate(interaction, resolved_msg="Already resolved~", unauth_msg="You're not authorized~"):
+ if not await self._gate(interaction, resolved_msg="Already resolved~", unauth_msg=_UNAUTHORIZED):
return
self.resolved = True
self.clear_items()
@@ -6363,7 +6367,7 @@ def _define_discord_view_classes() -> None:
)
async def _on_model_selected(self, interaction: discord.Interaction):
- if not await self._gate(interaction, resolved_msg="Already resolved~", unauth_msg="You're not authorized~"):
+ if not await self._gate(interaction, resolved_msg="Already resolved~", unauth_msg=_UNAUTHORIZED):
return
model_id = interaction.data["values"][0]
warning = await self._expensive_warning_for(model_id)
@@ -6374,7 +6378,7 @@ def _define_discord_view_classes() -> None:
await self._switch_selected_model(interaction, model_id)
async def _on_expensive_confirm(self, interaction: discord.Interaction):
- if not await self._gate(interaction, resolved_msg=None, unauth_msg="You're not authorized~"):
+ if not await self._gate(interaction, resolved_msg=None, unauth_msg=_UNAUTHORIZED):
return
if not self._pending_expensive_model:
await interaction.response.send_message("Model selection expired.", ephemeral=True)
@@ -6382,7 +6386,7 @@ def _define_discord_view_classes() -> None:
await self._switch_selected_model(interaction, self._pending_expensive_model)
async def _on_back(self, interaction: discord.Interaction):
- if not await self._gate(interaction, resolved_msg=None, unauth_msg="You're not authorized~"):
+ if not await self._gate(interaction, resolved_msg=None, unauth_msg=_UNAUTHORIZED):
return
self._build_provider_select()
try:
@@ -6434,7 +6438,7 @@ def _define_discord_view_classes() -> None:
async def _on_select(self, interaction: discord.Interaction):
if not self._check_auth(interaction):
- await interaction.response.send_message("⛔ You are not authorized to change this setting.", ephemeral=True)
+ await interaction.response.send_message(_UNAUTHORIZED, ephemeral=True)
return
if self.resolved:
await interaction.response.defer()
@@ -6535,7 +6539,7 @@ def _define_discord_view_classes() -> None:
"""Resolve the clarify with a chosen option."""
if not await self._gate(
interaction, resolved_msg="This prompt has already been answered~",
- unauth_msg="You're not authorized to answer this prompt~",
+ unauth_msg=_UNAUTHORIZED,
):
return
display_name = getattr(getattr(interaction, "user", None), "display_name", "user")
@@ -6566,7 +6570,7 @@ def _define_discord_view_classes() -> None:
"""Flip the clarify entry into text-capture mode."""
if not await self._gate(
interaction, resolved_msg="This prompt has already been answered~",
- unauth_msg="You're not authorized to answer this prompt~",
+ unauth_msg=_UNAUTHORIZED,
):
return
# Don't pop: the gateway text-intercept needs the entry until the user types.
diff --git a/plugins/platforms/feishu/adapter.py b/plugins/platforms/feishu/adapter.py
index 7a7de539360..59e7225c8c5 100644
--- a/plugins/platforms/feishu/adapter.py
+++ b/plugins/platforms/feishu/adapter.py
@@ -82,6 +82,7 @@ FEISHU_WEBSOCKET_AVAILABLE = websockets is not None
FEISHU_WEBHOOK_AVAILABLE = aiohttp is not None
from gateway.config import Platform, PlatformConfig
+from gateway.platforms.base_exec_approval import EA_HEADER_TEXT, EA_REASON_LABEL_TEXT
from gateway.platforms.base import (
BasePlatformAdapter, ExecApprovalPrompt, SendResult,
SUPPORTED_DOCUMENT_TYPES, cache_document_from_bytes_async, cache_image_from_url,
@@ -1644,7 +1645,7 @@ class FeishuAdapter(BasePlatformAdapter):
# Template attrs for the shared _format_exec_approval core. The card
# header carries the title, so the text core starts at the code fence.
_EA_HEADER = ""
- _EA_REASON_LABEL = "**Reason:** "
+ _EA_REASON_LABEL = f"**{EA_REASON_LABEL_TEXT}:** "
_EA_SMART_DENY_LINE = "\n\n**Smart DENY:** owner override applies to this one operation only."
_EA_CMD_BUDGET = 3000
@@ -1662,7 +1663,7 @@ class FeishuAdapter(BasePlatformAdapter):
_card_button(label, style or "default",
{"hermes_action": self._EA_CARD_ACTIONS[choice], "approval_id": approval_id})
for label, choice, style in prompt.actions]
- card = _card("⚠️ Command Approval Required", "orange", prompt.text, actions=actions)
+ card = _card(f"⚠️ {EA_HEADER_TEXT}", "orange", prompt.text, actions=actions)
return await self._send_interactive_card(
prompt.chat_id, card, prompt.metadata, "send_exec_approval failed",
state_map=self._approval_state, state_id=approval_id, session_key=prompt.session_key,
diff --git a/plugins/platforms/matrix/adapter.py b/plugins/platforms/matrix/adapter.py
index d2df6d7b2cd..c614a63db8a 100644
--- a/plugins/platforms/matrix/adapter.py
+++ b/plugins/platforms/matrix/adapter.py
@@ -61,6 +61,7 @@ except ImportError:
TrustState = type("_TrustStateStub", (), {"UNVERIFIED": 0, "VERIFIED": 1}) # type: ignore[misc,assignment]
from gateway.config import Platform, PlatformConfig
+from gateway.platforms.base_exec_approval import EA_HEADER_TEXT
from gateway.platforms.base import (
gateway_trust_env, BasePlatformAdapter, ExecApprovalPrompt,
SendResult, resolve_proxy_url, proxy_kwargs_for_aiohttp, _ssrf_redirect_guard,
@@ -1582,7 +1583,7 @@ class MatrixAdapter(BasePlatformAdapter):
# Template attrs for the shared _format_exec_approval core (header + fence + reason only;
# the smart-deny/scope wording lives in the reaction legend below).
- _EA_HEADER = "⚠️ **Dangerous command requires approval**\n"
+ _EA_HEADER = f"⚠️ **{EA_HEADER_TEXT}**\n"
_EA_CMD_BUDGET = 2000
async def _send_reaction_prompt(
diff --git a/plugins/platforms/slack/adapter.py b/plugins/platforms/slack/adapter.py
index 41d1f70ae71..143fb03bced 100644
--- a/plugins/platforms/slack/adapter.py
+++ b/plugins/platforms/slack/adapter.py
@@ -41,6 +41,7 @@ from gateway.platforms._shared import (
platform_gate_env as _scoped_gate_env, send_error
)
from gateway.platforms.helpers import MessageDeduplicator
+from gateway.platforms.base_exec_approval import EA_HEADER_TEXT
from gateway.platforms.base import (
gateway_trust_env, BasePlatformAdapter, ExecApprovalPrompt,
SendResult, SUPPORTED_DOCUMENT_TYPES, SUPPORTED_VIDEO_TYPES, _TEXT_INJECT_EXTENSIONS,
@@ -4710,7 +4711,7 @@ class SlackAdapter(BasePlatformAdapter):
logger.error("[Slack] %s failed: %s", label, e, exc_info=True)
return SendResult(success=False, error=str(e))
- _EA_HEADER = ":warning: *Command Approval Required*\n"
+ _EA_HEADER = f":warning: *{EA_HEADER_TEXT}*\n"
_EA_CODE_OPEN = "```"
_EA_CODE_CLOSE = "```\n"
_EA_SMART_DENY_LINE = "\n*Smart DENY:* owner override applies to this one operation only."
@@ -4722,7 +4723,7 @@ class SlackAdapter(BasePlatformAdapter):
def _exec_approval_cmd_budget(self, description: str, smart_denied: bool) -> int:
# execute_code approvals embed the whole script, so budget the preview against the cap.
fixed = (len(self._EA_HEADER) + len(self._EA_CODE_OPEN) + len(self._EA_CODE_CLOSE)
- + len(self._EA_REASON_LABEL) + len(description) + len("...")
+ + len(self._EA_REASON_LABEL) + len(description) + len("...") + len(self._ea_deadline_line())
+ (len(self._EA_SMART_DENY_LINE) if smart_denied else 0))
return max(0, self._EA_SECTION_CAP - fixed)
diff --git a/plugins/platforms/teams/adapter.py b/plugins/platforms/teams/adapter.py
index a8201ac2c02..661659661d3 100644
--- a/plugins/platforms/teams/adapter.py
+++ b/plugins/platforms/teams/adapter.py
@@ -56,6 +56,8 @@ from gateway.platforms.helpers import MessageDeduplicator
from gateway.platforms.base import (
gateway_trust_env, BasePlatformAdapter, ExecApprovalPrompt, SendResult, cache_image_from_url, cache_media_bytes_async,
)
+from gateway.platforms.base_exec_approval import (
+ EA_HEADER_TEXT, EA_REASON_LABEL_TEXT, approval_timeout_seconds, format_approval_deadline_line)
from gateway.platforms.event import MessageEvent, MessageType
from gateway.platforms._shared import (
coerce_port, get_scoped_secret as _get_scoped_secret, seed_extra_from_env as _seed_extra_from_env, send_error
@@ -325,10 +327,10 @@ def _approval_body(cmd: str, desc: str, *, always: bool = False) -> list:
"""Adaptive Card body blocks for an approval prompt; unless ``always``, empty ``cmd``/``desc`` omit their blocks."""
body = []
if cmd or always:
- body.append(TextBlock(text="⚠️ Command Approval Required", wrap=True, weight="Bolder"))
+ body.append(TextBlock(text=f"⚠️ {EA_HEADER_TEXT}", wrap=True, weight="Bolder"))
body.append(TextBlock(text=f"```\n{cmd}\n```", wrap=True))
if desc or always:
- body.append(TextBlock(text=f"Reason: {desc}", wrap=True, isSubtle=True))
+ body.append(TextBlock(text=f"{EA_REASON_LABEL_TEXT}: {desc}", wrap=True, isSubtle=True))
return body
@@ -634,6 +636,7 @@ class TeamsAdapter(BasePlatformAdapter):
title=label, verb="hermes_approve",
data={**btn_data_base, "hermes_action": self._EA_CARD_ACTIONS[choice]}, **kw))
body = _approval_body(self._truncate_preview(prompt.command, self._EA_CMD_BUDGET), prompt.description, always=True)
+ body.append(TextBlock(text=format_approval_deadline_line(approval_timeout_seconds()), wrap=True))
if prompt.smart_denied:
body.append(TextBlock(text=self._EA_SMART_DENY_LINE.strip(), wrap=True))
card = AdaptiveCard().with_version("1.4").with_body(body).with_actions(actions)
diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py
index 6de3c164e68..59b91ab5cc1 100644
--- a/plugins/platforms/telegram/adapter.py
+++ b/plugins/platforms/telegram/adapter.py
@@ -131,11 +131,16 @@ sys.path.insert(0, str(_Path(__file__).resolve().parents[3]))
from gateway.authz_mixin import _coerce_allow_set
from gateway.config import Platform, PlatformConfig
+from gateway.platforms.base_exec_approval import EA_HEADER_TEXT
from gateway.platforms.base import (
- BasePlatformAdapter, ExecApprovalPrompt, SendResult, classify_send_error,
+ BasePlatformAdapter, ExecApprovalPrompt, SendResult, classify_send_error, unauthorized_action_notice,
cache_image_from_bytes_async, cache_audio_from_bytes_async, cache_video_from_bytes_async, resolve_proxy_url, SUPPORTED_VIDEO_TYPES,
SUPPORTED_DOCUMENT_TYPES, SUPPORTED_IMAGE_DOCUMENT_TYPES, _TEXT_INJECT_EXTENSIONS, utf16_len,
)
+
+# Every refused button tap answers with the same sentence.
+_UNAUTHORIZED = unauthorized_action_notice(Platform.TELEGRAM)
+
from gateway.platforms.event import MessageEvent, MessageType, ProcessingOutcome
from plugins.platforms.telegram.telegram_entities import expand_link_entities
from plugins.platforms.telegram.telegram_ids import normalize_telegram_chat_id
@@ -3834,7 +3839,7 @@ class TelegramAdapter(BasePlatformAdapter):
"send_update_prompt", chat_id, metadata, build, thread_id=self._metadata_thread_id(metadata), reply_to_mode=self._reply_to_mode)
# Template attrs for the shared _format_exec_approval core (HTML mode).
- _EA_HEADER = "⚠️ <b>Command Approval Required</b>\n\n"
+ _EA_HEADER = f"⚠️ <b>{EA_HEADER_TEXT}</b>\n\n"
_EA_CODE_OPEN = "<pre>"
_EA_CODE_CLOSE = "</pre>\n\n"
_EA_SMART_DENY_LINE = "\n\n<b>Smart DENY:</b> owner override applies to this one operation only."
@@ -3966,7 +3971,7 @@ class TelegramAdapter(BasePlatformAdapter):
await query.answer(text="Picker expired — run the command again.")
return
# Same auth gate as approval buttons: strangers in a shared group must not flip session state.
- if not await self._callback_authorized(query, self._callback_ctx(query), "⛔ You are not authorized to change this setting."):
+ if not await self._callback_authorized(query, self._callback_ctx(query), _UNAUTHORIZED):
return
try:
choice = state["choices"][int(data[3:])]
@@ -4327,7 +4332,7 @@ class TelegramAdapter(BasePlatformAdapter):
await query.answer(text="Invalid approval data.")
return
session_key = await self._claim_callback_state(
- query, cb, self._approval_state, approval_id, "⛔ You are not authorized to approve commands.",
+ query, cb, self._approval_state, approval_id, _UNAUTHORIZED,
"This approval has already been resolved.")
if not session_key:
return
@@ -4368,7 +4373,7 @@ class TelegramAdapter(BasePlatformAdapter):
choice = parts[1] # once, always, cancel
confirm_id = parts[2]
session_key = await self._claim_callback_state(
- query, cb, self._slash_confirm_state, confirm_id, "⛔ You are not authorized to answer this prompt.",
+ query, cb, self._slash_confirm_state, confirm_id, _UNAUTHORIZED,
"This prompt has already been resolved.")
if not session_key:
return
@@ -4414,7 +4419,7 @@ class TelegramAdapter(BasePlatformAdapter):
clarify_id = parts[1]
choice_token = parts[2]
session_key = await self._claim_callback_state(
- query, cb, self._clarify_state, clarify_id, "⛔ You are not authorized to answer this prompt.",
+ query, cb, self._clarify_state, clarify_id, _UNAUTHORIZED,
"This prompt has already been resolved.", pop=False)
if not session_key:
return
@@ -4474,7 +4479,7 @@ class TelegramAdapter(BasePlatformAdapter):
async def _handle_update_prompt_callback(self, query, data: str, cb: Dict[str, Any]) -> None:
"""``update_prompt:<y|n>`` — forward the answer to the update process."""
answer = data.split(":", 1)[1] # "y" or "n"
- if not await self._callback_authorized(query, cb, "⛔ You are not authorized to answer update prompts."):
+ if not await self._callback_authorized(query, cb, _UNAUTHORIZED):
return
await query.answer(text=f"Sent '{answer}' to the update process.")
await self._edit_md_quiet(query, f"☤ Update prompt answered: *{'Yes' if answer == 'y' else 'No'}*")
@@ -4510,7 +4515,7 @@ class TelegramAdapter(BasePlatformAdapter):
await query.answer(text="Invalid gmail-triage data.")
return
verb, arg = parts[1], parts[2]
- if not await self._callback_authorized(query, cb, "⛔ You are not authorized to act on this email."):
+ if not await self._callback_authorized(query, cb, _UNAUTHORIZED):
return
entry = self._GT_VERB_DISPATCH.get(verb)
if not entry:
diff --git a/run_agent.py b/run_agent.py
index 97328216a95..7b0a038d62c 100644
--- a/run_agent.py
+++ b/run_agent.py
@@ -1222,11 +1222,12 @@ class AIAgent(
self._tool_guardrail_halt_decision = decision
def _toolguard_controlled_halt_response(self, decision: ToolGuardrailDecision) -> str:
+ # Shown to the user as the reply, so no decision codes; the code stays in result["guardrail"].
return (
- f"I stopped retrying {decision.tool_name or 'a tool'} because it hit the tool-call guardrail "
- f"({decision.code}) after {decision.count} repeated non-progressing "
- "attempts. The last tool result explains the blocker; the next step is "
- "to change strategy instead of repeating the same call."
+ f"I stopped retrying because I kept running {decision.tool_name or 'the same tool'} "
+ f"{decision.count} times without making progress. The last result above shows what "
+ "blocked it. Tell me how you'd like to proceed, or send `continue` and I'll try a "
+ "different approach."
)
def _append_guardrail_observation(self, tool_name: str, function_args: dict, function_result: str, *,
diff --git a/tests/agent/test_413_compression.py b/tests/agent/test_413_compression.py
index 7bcc97c05ad..464cef6c793 100644
--- a/tests/agent/test_413_compression.py
+++ b/tests/agent/test_413_compression.py
@@ -1529,4 +1529,5 @@ class TestOverflowWithCompactionDisabled:
mock_persist.assert_called()
assert result.get("failed") is True
assert result.get("compaction_disabled") is True
- assert "auto-compaction is disabled" in result["error"]
+ assert result["failure_reason"] == "context_overflow" and result["failure_retryable"] is False
+ assert "/compress" in result["error"] and "compression.enabled" in result["error"]
diff --git a/tests/agent/test_compression_closed_adoption.py b/tests/agent/test_compression_closed_adoption.py
index 430523abf92..19909c3d7ff 100644
--- a/tests/agent/test_compression_closed_adoption.py
+++ b/tests/agent/test_compression_closed_adoption.py
@@ -237,4 +237,4 @@ def test_disk_cause_keeps_disk_guidance() -> None:
text = AIAgent._format_turn_completion_explanation(
"session_persistence_failed", persistence_cause="disk"
)
- assert "full disk" in text, "real disk failures must keep disk guidance"
+ assert "disk" in text.lower() and "free some space" in text.lower(), "real disk failures must keep disk guidance"
diff --git a/tests/agent/test_display_tool_failure.py b/tests/agent/test_display_tool_failure.py
index a813a3ceb26..70dea379c03 100644
--- a/tests/agent/test_display_tool_failure.py
+++ b/tests/agent/test_display_tool_failure.py
@@ -57,7 +57,27 @@ class TestDetectToolFailureTerminal:
assert suffix.startswith(" [")
assert suffix.endswith("]")
-
+ def test_degraded_backend_shows_full_reason_and_retry_hint(self):
+ """A degraded backend (Docker down, SSH host unreachable) is an infrastructure problem: the user
+ needs the whole reason plus the fix hint, not the 48-char trimmed 'Terminal backend degraded: ...'."""
+ result = json.dumps({
+ "output": "", "exit_code": -1, "status": "degraded",
+ "reason": "Docker daemon is not reachable at unix:///var/run/docker.sock",
+ "retry_hint": "Start Docker, or run `hermes setup terminal` to switch to Local, then retry",
+ "error": "Terminal backend degraded: Docker daemon is not reachable at unix:///var/run/docker.sock",
+ })
+ is_failure, suffix = _detect_tool_failure("terminal", result)
+ assert is_failure is True
+ assert "unix:///var/run/docker.sock" in suffix
+ assert "hermes setup terminal" in suffix
+ assert "Terminal backend degraded:" not in suffix
+
+ def test_degraded_backend_without_hint_shows_reason_alone(self):
+ result = json.dumps({"output": "", "exit_code": -1, "status": "degraded",
+ "reason": "SSH connection to bob@host timed out", "retry_hint": "",
+ "error": "Terminal backend degraded: SSH connection to bob@host timed out"})
+ _, suffix = _detect_tool_failure("terminal", result)
+ assert suffix == " [SSH connection to bob@host timed out]"
class TestDetectToolFailureMemory:
diff --git a/tests/agent/test_failed_turn_chat_copy.py b/tests/agent/test_failed_turn_chat_copy.py
new file mode 100644
index 00000000000..d99ef570d88
--- /dev/null
+++ b/tests/agent/test_failed_turn_chat_copy.py
@@ -0,0 +1,189 @@
+"""Terminal failed-turn results carry a specific ``failure_reason`` and plain-language chat
+copy on every surface (the CLI-only 💡 hints used to be the only place with a next step).
+
+Behaviour contracts, not snapshots: each test asserts the relationship between a result
+and what ``agent/error_surface.py`` derives from it, plus the presence of the exact command
+the user is told to run.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from agent.error_classifier import classify_api_error
+from agent.error_surface import LAYER_GATEWAY, LAYER_PROVIDER, build_error_surface_from_result
+from agent.turn_loop_errors import handle_outer_loop_error
+from agent.turn_recovery import max_retries_exhausted_result, nonretryable_client_error_result
+from agent.turn_failure_copy import SITE_FAILURE_CODES, provider_label_for
+from agent.turn_response_check import retry_invalid_response
+
+
+class _Agent:
+ log_prefix = ""
+ verbose = False
+ verbose_logging = False
+ provider = "openrouter"
+ model = "gpt-5-turbo"
+ base_url = "https://openrouter.ai/api/v1"
+ max_iterations = 30
+ suppress_status_output = True
+ _fallback_chain = ()
+ _fallback_index = 0
+
+ def _summarize_api_error(self, error):
+ return str(error)
+
+ def _clean_error_message(self, msg):
+ return msg
+
+ def _has_pending_fallback(self):
+ return False
+
+ def _try_activate_fallback(self):
+ return False
+
+ def __getattr__(self, name):
+ return lambda *args, **kwargs: None
+
+
+class _Http(Exception):
+ def __init__(self, status_code, message):
+ super().__init__(message)
+ self.status_code = status_code
+
+
+def _nonretryable(status, message, provider="openrouter", model="gpt-5-turbo"):
+ error = _Http(status, message)
+ classified = classify_api_error(error, provider=provider, model=model)
+ return nonretryable_client_error_result(
+ _Agent(), error, classified, status_code=status, api_kwargs=None, api_messages=[], messages=[],
+ conversation_history=None, api_call_count=1, approx_tokens=10, provider=provider,
+ base_url="https://openrouter.ai/api/v1", model=model,
+ )
+
+
+def test_model_not_found_chat_text_points_at_model_picker_not_http():
+ result = _nonretryable(404, "HTTP 404: The model `gpt-5-turbo` does not exist")
+ text = result["final_response"]
+ assert "/model" in text and "gpt-5-turbo" in text
+ assert not text.startswith("HTTP")
+ assert result["failure_reason"] == "model_not_found"
+ assert build_error_surface_from_result(result, provider="openrouter")["retryable"] is False
+
+
+def test_api_key_rejection_chat_text_names_the_fix_and_the_provider_label():
+ result = _nonretryable(401, "HTTP 401: Invalid API key provided")
+ text = result["final_response"]
+ assert "hermes setup" in text and "OpenRouter" in text
+ assert "Provider said:" in text # raw detail demoted to a trailing line
+ assert text.index("hermes setup") < text.index("Provider said:")
+
+
+def test_max_retries_exhausted_chat_text_has_next_step_and_no_mechanism_lead():
+ error = _Http(503, "HTTP 503: upstream unavailable")
+ classified = classify_api_error(error, provider="openrouter", model="m")
+ result = max_retries_exhausted_result(
+ _Agent(), error, classified, max_retries=3, is_rate_limited=False, error_msg=str(error).lower(),
+ api_kwargs=None, api_messages=[], messages=[], conversation_history=None, api_call_count=1,
+ approx_tokens=10, provider="openrouter", base_url="https://openrouter.ai/api/v1", model="m",
+ )
+ text = result["final_response"]
+ assert "/retry" in text and "/model" in text and "hermes fallback add" in text
+ assert not text.startswith("API call failed")
+ assert result["failure_reason"] == classified.reason.value
+ assert result["failure_retryable"] is True
+
+
+def test_invalid_response_stamps_reason_from_embedded_provider_code():
+ """An HTTP-200 body carrying a 429 is rate limiting for the UI, not 'unknown'."""
+ agent = _Agent()
+ response = SimpleNamespace(error=SimpleNamespace(code=429, metadata={"provider_name": "Acme"}), choices=[])
+ verdict = retry_invalid_response(
+ agent, response=response, error_details=["no choices"],
+ _retry=SimpleNamespace(restart_with_redirected_messages=False), thinking_spinner=None,
+ messages=[], api_messages=[], api_kwargs=None, active_system_prompt=None, conversation_history=None,
+ retry_count=2, max_retries=3, compression_attempts=0, api_call_count=1, api_request_id="r",
+ api_start_time=0.0, api_duration=0.4, effective_task_id="t", turn_id="turn",
+ )
+ assert verdict.action == "return"
+ result = verdict.result
+ assert result["failure_reason"] == "rate_limit"
+ assert "/retry" in result["final_response"] and "Acme" in result["final_response"]
+ assert "Invalid API response" not in result["final_response"]
+
+
+def test_outer_loop_error_copy_has_no_apology_and_routes_to_gateway_layer():
+ """Deterministic local bugs are failed, non-retryable turns with a plain what-now."""
+ agent = _Agent()
+ try:
+ raise TypeError("expected str, got list")
+ except TypeError as exc:
+ verdict = handle_outer_loop_error(
+ agent, e=exc, _outer_error_count=7, api_call_count=2, messages=[], conversation_history=None,
+ _turn_exit_reason="unknown", failed=False, final_response=None,
+ )
+ assert verdict.action == "break" and verdict.failed is True
+ text = verdict.final_response
+ assert "apologize" not in text.lower() and "OpenAI-compatible" not in text
+ assert "hermes doctor" in text and "/new" in text
+ assert text.rstrip().endswith("expected str, got list") # raw detail last, not first
+ from agent.turn_failure_copy import exit_reason_failure
+
+ exit_failure = exit_reason_failure(verdict._turn_exit_reason)
+ assert exit_failure.fails_turn is True # the outer-error cap IS a failed turn
+ surface = build_error_surface_from_result(
+ {"failed": True, "error": text, "failure_reason": exit_failure.reason,
+ "failure_retryable": exit_failure.retryable}
+ )
+ assert surface["layer"] == LAYER_GATEWAY and surface["code"] == "loop_error"
+
+
+def test_invalid_response_copy_never_names_a_model_id_as_the_provider():
+ """describe_invalid_response falls back to 'model=<id>' for OpenRouter bodies; that is not a
+ provider name and must not be spliced into the sentence."""
+ agent = _Agent()
+ response = SimpleNamespace(error=None, choices=[], model="anthropic/claude-opus")
+ verdict = retry_invalid_response(
+ agent, response=response, error_details=["no choices"],
+ _retry=SimpleNamespace(restart_with_redirected_messages=False), thinking_spinner=None,
+ messages=[], api_messages=[], api_kwargs=None, active_system_prompt=None, conversation_history=None,
+ retry_count=2, max_retries=3, compression_attempts=0, api_call_count=1, api_request_id="r",
+ api_start_time=0.0, api_duration=0.4, effective_task_id="t", turn_id="turn",
+ )
+ text = verdict.result["final_response"]
+ assert "model=" not in text
+ assert text.startswith(provider_label_for(agent.provider))
+
+
+def test_interpreter_shutdown_copy_substitutes_the_real_session_id():
+ agent = _Agent()
+ agent.session_id = "20260914_abc"
+ verdict = handle_outer_loop_error(
+ agent, e=RuntimeError("cannot schedule new futures after interpreter shutdown"),
+ _outer_error_count=0, api_call_count=1, messages=[], conversation_history=None,
+ _turn_exit_reason="unknown", failed=False, final_response=None,
+ )
+ assert "hermes --resume 20260914_abc" in verdict.final_response
+ assert "<session-id>" not in verdict.final_response
+
+
[email protected]("code", sorted(SITE_FAILURE_CODES))
+def test_site_failure_codes_never_collapse_to_unknown(code):
+ """Every site code is listed in error_surface's layer table (no fall-through guesswork)."""
+ from agent.error_surface import _REASON_TO_LAYER
+
+ surface = build_error_surface_from_result({"failed": True, "error": "x", "failure_reason": code})
+ assert surface["code"] == code
+ assert code in _REASON_TO_LAYER
+ assert surface["layer"] in (LAYER_GATEWAY, LAYER_PROVIDER)
+
+
+def test_model_caused_codes_stay_on_the_provider_layer_and_runtime_codes_on_gateway():
+ """Cut-off / empty / broken replies come from the model (provider layer, so the client's
+ per-code copy applies); a busy session or loop bug is Hermes-side (gateway layer, so the
+ client never offers Switch provider for it)."""
+ layers = {c: build_error_surface_from_result({"failed": True, "error": "x", "failure_reason": c})["layer"]
+ for c in ("truncated", "empty_response", "invalid_response", "session_busy", "loop_error")}
+ assert layers["truncated"] == layers["empty_response"] == layers["invalid_response"] == LAYER_PROVIDER
+ assert layers["session_busy"] == layers["loop_error"] == LAYER_GATEWAY
diff --git a/tests/agent/test_failed_turn_site_codes.py b/tests/agent/test_failed_turn_site_codes.py
new file mode 100644
index 00000000000..afeed1cf39c
--- /dev/null
+++ b/tests/agent/test_failed_turn_site_codes.py
@@ -0,0 +1,112 @@
+"""Deterministic loop outcomes (context overflow, empty reply, persistence failure) end as
+failed turns whose chat copy names the slash command to run, and whose ``failure_reason``
+lets the desktop card pick a code-specific action instead of a blind Retry.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from agent.error_surface import build_error_surface_from_result
+from agent.turn_explainers import EMPTY_RESPONSE_EXPLANATION, TurnExplainersMixin
+from agent.turn_failure_copy import (
+ SITE_FAILURE_CODES, exit_reason_failure, failure_cause_gloss, site_copy,
+)
+from agent.turn_overflow import _Recovery
+
+
+def _recovery():
+ agent = SimpleNamespace(
+ model="gpt-5", log_prefix="", _flush_status_buffer=lambda: None, _vprint=lambda *a, **k: None,
+ _persist_session=lambda *a, **k: None,
+ )
+ return _Recovery(
+ agent=agent, api_messages=[], system_message=None, effective_task_id="t", api_call_count=2,
+ max_compression_attempts=3, messages=[], active_system_prompt=None, conversation_history=None,
+ approx_tokens=200_000, compression_attempts=3,
+ )
+
+
+def test_overflow_exhaustion_is_non_retryable_context_overflow_with_slash_commands():
+ verdict = _recovery().count_attempt()
+ result = verdict.result
+ assert result["failed"] is True and result["compression_exhausted"] is True
+ assert result["failure_reason"] == "context_overflow" and result["failure_retryable"] is False
+ text = result["final_response"]
+ assert "/new" in text and "/compress" in text and "gpt-5" in text
+ for jargon in ("compression attempts", "Context length exceeded", "safe threshold"):
+ assert jargon not in text
+ assert build_error_surface_from_result(result)["code"] == "context_overflow"
+
+
+def test_payload_and_context_overflow_share_one_next_step():
+ """413 and context-length exhaustion differ in cause text but never in what to do."""
+ a = _recovery().count_attempt(payload_too_large=True).result["final_response"]
+ b = _recovery().count_attempt().result["final_response"]
+ assert ("/new" in a) and ("/compress" in a) and ("/new" in b) and ("/compress" in b)
+
+
+def test_empty_response_exhaustion_has_one_text_everywhere():
+ """One constant feeds the CLI explainer and the gateway '(empty)' rewrite; no surface
+ asserts 'after processing tool results' or 'inspect the tool output above'."""
+ verdict = exit_reason_failure("empty_response_exhausted")
+ assert (verdict.reason, verdict.retryable) == ("empty_response", True)
+ text = TurnExplainersMixin._format_turn_completion_explanation("empty_response_exhausted", model="llama3")
+ assert text.startswith("⚠️ No reply: ") and "llama3" in text
+ assert "/model" in text and "continue" in text
+ assert "tool" not in text
+ assert EMPTY_RESPONSE_EXPLANATION.format(model="llama3") in text
+
+
+def test_persistence_failure_default_copy_is_actionable_and_profile_aware(monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", "/srv/hermes-profile")
+ text = TurnExplainersMixin._format_turn_completion_explanation("session_persistence_failed", "replaced")
+ assert "hermes gateway stop" in text and "hermes doctor" in text
+ assert "~/.hermes" not in text and "/srv/hermes-profile" in text
+ assert "manifest" not in text # the runbook stays in logger.error at hermes_state
+
+
+def test_reasoning_only_copy_gives_the_fix_before_the_scratchpad():
+ text = site_copy("reasoning_only", model="r1", preview="the answer is 42")
+ assert text.index("/reasoning low") < text.index("the answer is 42")
+ assert "/model" in text
+
+
[email protected]("exit_reason", ["empty_response_exhausted", "local_processing_error(TypeError)"])
+def test_advisory_exit_reasons_stamp_a_code_but_never_flip_failed(exit_reason):
+ """Cron silence, the kanban dispatcher breaker and gateway transcript persistence all key
+ on ``failed``; these two exits must keep failed=False and only gain the descriptor code."""
+ verdict = exit_reason_failure(exit_reason)
+ assert verdict is not None and verdict.fails_turn is False
+ assert verdict.reason in SITE_FAILURE_CODES
+
+
[email protected]("exit_reason, code", [
+ ("context_compression_timeout", "context_overflow"),
+ ("ollama_runtime_context_too_small", "context_overflow"),
+ ("redirect_restart_limit_exceeded", "loop_error"),
+ ("rebuilt_restart_limit_exceeded", "loop_error"),
+])
+def test_previously_bare_exit_reasons_now_carry_a_code(exit_reason, code):
+ verdict = exit_reason_failure(exit_reason)
+ assert verdict is not None and verdict.reason == code
+ assert build_error_surface_from_result(
+ {"failed": True, "error": "x", "failure_reason": verdict.reason, "failure_retryable": verdict.retryable}
+ )["code"] == code
+
+
+def test_every_failure_code_copy_key_is_a_failure_code():
+ """The copy table split: keys of the failure-code table are exactly codes the descriptor
+ contract lists (one-off strings live in their own table)."""
+ from agent.turn_failure_copy import _FAILURE_CODE_COPY, _ONE_OFF_COPY
+
+ assert set(_FAILURE_CODE_COPY) <= SITE_FAILURE_CODES
+ assert not (set(_ONE_OFF_COPY) & SITE_FAILURE_CODES)
+ assert "loop_error" in _FAILURE_CODE_COPY and "local_processing_error" in _ONE_OFF_COPY
+
+
+def test_cause_gloss_substitutes_the_subject_and_skips_unknown_reasons():
+ assert "the job's" in failure_cause_gloss("context_overflow", subject="this job", possessive="the job's")
+ assert failure_cause_gloss("model_not_found").startswith("the model it uses")
+ assert failure_cause_gloss("unknown") is None and failure_cause_gloss(None) is None
diff --git a/tests/agent/test_nous_rate_guard.py b/tests/agent/test_nous_rate_guard.py
index 2e68b2f4d1b..91e75bab29f 100644
--- a/tests/agent/test_nous_rate_guard.py
+++ b/tests/agent/test_nous_rate_guard.py
@@ -314,7 +314,7 @@ class TestWelcomeRouteCopy:
"https://inference-api.nousresearch.com/v1", monkeypatch
)
- expected = "Nous Portal rate limit active — resets in 10m."
+ expected = "Your Nous account has hit its rate limit; it resets in 10m."
assert verdict.action == "return"
assert statuses == [f"⏳ {expected}"]
assert verdict.result["final_response"].startswith(f"⏳ {expected}\n\n")
diff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.py
index e85a1c1c057..29f4abbbddc 100644
--- a/tests/agent/test_run_agent.py
+++ b/tests/agent/test_run_agent.py
@@ -2769,8 +2769,9 @@ class TestHandleMaxIterations:
with patch("agent.relay_llm.complete_logical_call") as complete_logical:
result = agent._handle_max_iterations(messages, 60)
assert isinstance(result, str)
- assert "error" in result.lower()
- assert "API down" in result
+ # Plain what-now for the user; the raw exception stays in the log, not the reply.
+ assert "continue" in result and "max_iterations" in result
+ assert "API down" not in result
complete_logical.assert_called_once()
assert complete_logical.call_args.kwargs == {"outcome": "failed"}
@@ -3619,7 +3620,11 @@ class TestRunConversation:
patch.object(agent, "_cleanup_task_resources"),
):
result = agent.run_conversation("answer me")
- assert result["completed"] is True
+ # Empty after retries keeps the pre-existing status (not a failed turn: cron stays silent,
+ # the transcript keeps the text) and only gains the descriptor code for Desktop/TUI.
+ assert result["failed"] is False and result["completed"] is True
+ assert result["failure_reason"] == "empty_response"
+ assert result["failure_reason"] == "empty_response"
# #34452: explanation replaces the bare "(empty)" sentinel.
assert result["final_response"] != "(empty)"
assert "No reply:" in result["final_response"]
@@ -3648,7 +3653,11 @@ class TestRunConversation:
patch.object(agent, "_cleanup_task_resources"),
):
result = agent.run_conversation("answer me")
- assert result["completed"] is True
+ # Empty after retries keeps the pre-existing status (not a failed turn: cron stays silent,
+ # the transcript keeps the text) and only gains the descriptor code for Desktop/TUI.
+ assert result["failed"] is False and result["completed"] is True
+ assert result["failure_reason"] == "empty_response"
+ assert result["failure_reason"] == "empty_response"
assert result["final_response"] != "(empty)"
# 1 original + 1 retry: the second identical zero-output empty
# proves determinism, remaining retries are skipped.
@@ -3676,7 +3685,11 @@ class TestRunConversation:
patch.object(agent, "_cleanup_task_resources"),
):
result = agent.run_conversation("answer me")
- assert result["completed"] is True
+ # Empty after retries keeps the pre-existing status (not a failed turn: cron stays silent,
+ # the transcript keeps the text) and only gains the descriptor code for Desktop/TUI.
+ assert result["failed"] is False and result["completed"] is True
+ assert result["failure_reason"] == "empty_response"
+ assert result["failure_reason"] == "empty_response"
assert result["api_calls"] == 4 # legacy: 1 original + 3 retries
def test_empty_without_usage_stops_after_one_retry_and_logs_calls(
@@ -3695,7 +3708,11 @@ class TestRunConversation:
caplog.at_level(logging.INFO, logger="agent.conversation_loop"),
):
result = agent.run_conversation("answer me")
- assert result["completed"] is True
+ # Empty after retries keeps the pre-existing status (not a failed turn: cron stays silent,
+ # the transcript keeps the text) and only gains the descriptor code for Desktop/TUI.
+ assert result["failed"] is False and result["completed"] is True
+ assert result["failure_reason"] == "empty_response"
+ assert result["failure_reason"] == "empty_response"
assert result["api_calls"] == 2
assert agent.session_api_calls == 2
assert caplog.text.count("usage=unavailable") == 2
@@ -3835,7 +3852,11 @@ class TestRunConversation:
patch.object(agent, "_try_activate_fallback", side_effect=_mock_fallback),
):
result = agent.run_conversation("answer me")
- assert result["completed"] is True
+ # Empty after retries keeps the pre-existing status (not a failed turn: cron stays silent,
+ # the transcript keeps the text) and only gains the descriptor code for Desktop/TUI.
+ assert result["failed"] is False and result["completed"] is True
+ assert result["failure_reason"] == "empty_response"
+ assert result["failure_reason"] == "empty_response"
# #34452: explanation replaces the bare "(empty)" sentinel.
assert result["final_response"] != "(empty)"
assert "No reply:" in result["final_response"]
@@ -4540,7 +4561,8 @@ class TestRunConversation:
assert result["completed"] is False
assert result["partial"] is True
- assert "truncated due to output length limit" in result["error"]
+ assert result["failure_reason"] == "truncated"
+ assert "cut off" in result["error"]
mock_handle_function_call.assert_not_called()
def test_truncated_tool_call_retries_once_before_refusing(self, agent):
@@ -4700,7 +4722,7 @@ class TestRunConversation:
assert result.get("partial") is True
msgs = result.get("messages") or []
assert msgs[-1].get("role") == "assistant"
- assert "truncated" in (msgs[-1].get("content") or "").lower()
+ assert "cut off" in (msgs[-1].get("content") or "").lower()
assert any(isinstance(m, dict) and m.get("role") == "tool" for m in msgs)
@@ -5236,7 +5258,10 @@ class TestRetryExhaustion:
assert result.get("failed") is True
assert "error" in result
assert "Invalid API response" in result["error"]
- assert result.get("final_response") == result["error"]
+ # The chat text names the provider and a next step instead of the mechanism.
+ assert "/retry" in result["final_response"] and "/model" in result["final_response"]
+ assert result["failure_reason"] == "invalid_response"
+ assert result["failure_retryable"] is True
def test_invalid_response_retry_completes_one_logical_call(self, agent):
self._setup_agent(agent)
diff --git a/tests/agent/test_secret_scope.py b/tests/agent/test_secret_scope.py
index 5a42f842d83..c37c2efcd1b 100644
--- a/tests/agent/test_secret_scope.py
+++ b/tests/agent/test_secret_scope.py
@@ -378,3 +378,18 @@ class TestSecretScopeAcrossExecutorThreads:
finally:
pool.shutdown(wait=True)
ss.reset_secret_scope(token)
+
+
+class TestUnscopedSecretErrorSignature:
+ def test_named_secret_leads_the_user_sentence(self):
+ err = ss.UnscopedSecretError("SURPLUS_API_KEY", "get_secret('SURPLUS_API_KEY') with no scope")
+ assert err.secret_name == "SURPLUS_API_KEY" and "SURPLUS_API_KEY" in str(err)
+ assert err.developer_detail in getattr(err, "__notes__", [])
+ assert "hermes gateway restart" in str(err)
+
+ def test_legacy_single_message_positional_is_the_developer_detail(self):
+ """Older callers passed the whole sentence positionally; it must not be read as a name."""
+ err = ss.UnscopedSecretError("get_secret('X') called with no profile secret scope active.")
+ assert err.secret_name == ""
+ assert err.developer_detail.startswith("get_secret('X')")
+ assert "get_secret" not in str(err) and "API key" in str(err)
diff --git a/tests/agent/test_secret_scope_user_message.py b/tests/agent/test_secret_scope_user_message.py
new file mode 100644
index 00000000000..cd9e84e959e
--- /dev/null
+++ b/tests/agent/test_secret_scope_user_message.py
@@ -0,0 +1,28 @@
+"""UnscopedSecretError reaches end users verbatim (compression-aborted replies, cron notices), so
+`str(exc)` must be the one actionable sentence; the developer diagnosis stays in `__notes__`/logs.
+"""
+
+import pytest
+
+import agent.secret_scope as ss
+
+
+def multiplex_on():
+ ss.set_multiplex_active(True)
+ try:
+ yield
+ finally:
+ ss.set_multiplex_active(False)
+
+
+def test_str_is_a_user_sentence_and_developer_detail_rides_the_notes(multiplex_on):
+ with pytest.raises(ss.UnscopedSecretError) as info:
+ ss.get_secret("OPENROUTER_API_KEY")
+ exc = info.value
+ text = str(exc)
+ assert "OPENROUTER_API_KEY" in text # still names what could not be read
+ assert "hermes gateway restart" in text and "hermes debug share" in text
+ for jargon in ("set_secret_scope", "Workstream", "developer-guide", "os.environ"):
+ assert jargon not in text
+ assert any("set_secret_scope" in note for note in exc.__notes__)
diff --git a/tests/agent/test_turn_completion_explainer.py b/tests/agent/test_turn_completion_explainer.py
index 160bc18dc0d..ac5a7ad21df 100644
--- a/tests/agent/test_turn_completion_explainer.py
+++ b/tests/agent/test_turn_completion_explainer.py
@@ -204,19 +204,20 @@ def test_explanation_persistence_replaced_cause_forbids_inplace_repair():
assert "full disk" not in lower
-def test_deleted_wal_cause_is_enumerated_and_points_to_retired_capture():
+def test_deleted_wal_cause_is_plain_first_steps_not_a_forensic_runbook():
+ """The WAL-generation runbook lives in the logger.error at hermes_state; the chat reply
+ gives the two steps a user can take (stop, doctor) and points at the log."""
from hermes_state_errors import PERSISTENCE_ERROR_CAUSES
out = AIAgent._format_turn_completion_explanation(
"session_persistence_failed", "deleted_wal"
).lower()
assert "deleted_wal" in PERSISTENCE_ERROR_CAUSES
- assert "retired-wal-*/manifest.json" in out
- assert "manifest.main.mode" in out
- assert "sessions recover" in out and "--inspect-only" in out
- assert "header_only" in out and "does not contain a copied state.db" in out
- assert "check the logs for whether" in out
- assert "restore the intended state.db" not in out
+ assert "hermes gateway stop" in out and "hermes doctor" in out
+ assert "send your message once more" in out
+ for jargon in ("manifest", "state.db-wal", "sidecar", "header_only", "--inspect-only", "generation"):
+ assert jargon not in out, jargon
+ assert "~/.hermes" not in out # display_hermes_home(), never a hardcoded path
def test_explanation_persistence_unknown_cause_is_neutral():
@@ -237,7 +238,7 @@ def test_explanation_persistence_one_arg_backward_compat():
"""Existing one-arg callers must keep working (optional second param)."""
out = AIAgent._format_turn_completion_explanation("session_persistence_failed")
assert out.strip() != ""
- assert "session storage" in out.lower()
+ assert "couldn't save" in out.lower() and "hermes doctor" in out.lower()
def test_explanation_cause_ignored_for_other_reasons():
diff --git a/tests/agent/test_turn_facade_lease.py b/tests/agent/test_turn_facade_lease.py
index 689a59e57cb..85dba7cdbae 100644
--- a/tests/agent/test_turn_facade_lease.py
+++ b/tests/agent/test_turn_facade_lease.py
@@ -101,6 +101,9 @@ def test_timeout_and_interrupt_early_results():
assert admission.lease is None
assert admission.early_result["failed"] is True
assert admission.early_result["error"] == "session_turn_lease_timeout:s1"
+ # Stamped so UI descriptors show "session busy" instead of code="unknown".
+ assert admission.early_result["failure_reason"] == "session_busy"
+ assert admission.early_result["failure_retryable"] is True
assert admission.early_result["messages"] == [{"role": "user", "content": "x"}]
agent = _agent(_Db(acquired=False), _interrupt_requested=True, _interrupt_message="stop")
diff --git a/tests/agent/test_turn_finalizer_final_response_persistence.py b/tests/agent/test_turn_finalizer_final_response_persistence.py
index 31fe400ea5a..d705768d677 100644
--- a/tests/agent/test_turn_finalizer_final_response_persistence.py
+++ b/tests/agent/test_turn_finalizer_final_response_persistence.py
@@ -447,3 +447,35 @@ def test_delivery_only_reasoning_excerpt_does_not_fill_blank_assistant(monkeypat
for m in result["messages"]
)
+
+
+def _finalize(agent, *, exit_reason, final_response, failed=False, api_calls=3):
+ return finalize_turn(
+ agent, final_response=final_response, api_call_count=api_calls, interrupted=False, failed=failed,
+ messages=[{"role": "user", "content": "q"}, {"role": "assistant", "content": final_response or ""}],
+ conversation_history=[], effective_task_id="task", turn_id="turn", user_message="q",
+ original_user_message="q", _should_review_memory=False, _turn_exit_reason=exit_reason,
+ )
+
+
+def test_advisory_exit_reasons_keep_failed_false_but_carry_a_failure_code(monkeypatch):
+ """empty_response_exhausted / local_processing_error: Desktop and TUI get a specific code, yet
+ ``failed`` stays False so cron silence, the kanban breaker and gateway transcript persistence
+ behave exactly as before the code was added."""
+ monkeypatch.setattr("hermes_cli.plugins.invoke_hook", lambda *_a, **_kw: [])
+ agent_max = FakeAgent().max_iterations
+ for exit_reason, code in (("empty_response_exhausted", "empty_response"),
+ ("local_processing_error(TypeError: x)", "loop_error")):
+ result = _finalize(FakeAgent(), exit_reason=exit_reason, final_response="the model's last thoughts")
+ assert result["failed"] is False, exit_reason
+ # ``completed`` follows the ordinary rule for a non-failed turn (not forced False here).
+ assert result["completed"] == (result["final_response"] is not None and 3 < agent_max), exit_reason
+ assert result["failure_reason"] == code and isinstance(result["failure_retryable"], bool)
+ assert "error" not in result # not a failed turn: no error text for the gateway to append a notice to
+
+
+def test_hard_failure_exit_reasons_still_fail_the_turn(monkeypatch):
+ monkeypatch.setattr("hermes_cli.plugins.invoke_hook", lambda *_a, **_kw: [])
+ result = _finalize(FakeAgent(), exit_reason="repeated_outer_errors(RuntimeError)", final_response="stopped")
+ assert result["failed"] is True and result["completed"] is False
+ assert result["failure_reason"] == "loop_error" and result["error"] == "stopped"
diff --git a/tests/cron/test_cron_empty_turn_stays_silent.py b/tests/cron/test_cron_empty_turn_stays_silent.py
new file mode 100644
index 00000000000..21a724a4316
--- /dev/null
+++ b/tests/cron/test_cron_empty_turn_stays_silent.py
@@ -0,0 +1,31 @@
+"""An abnormal empty turn (``empty_response_exhausted``) is delivered as silence, not as a
+'⚠️ Cron ... failed' alert: the finalizer stamps ``failure_reason`` for the UI but keeps
+``failed`` False, and the scheduler recognises the model-named explainer text."""
+
+import pytest
+
+from agent.turn_explainers import TurnExplainersMixin
+from cron.scheduler import _final_response_from_result
+
+
+class _AIAgent:
+ _format_turn_completion_explanation = staticmethod(TurnExplainersMixin._format_turn_completion_explanation)
+
+
+def test_empty_response_exhausted_turn_delivers_silence_not_a_failure_alert():
+ explainer = TurnExplainersMixin._format_turn_completion_explanation("empty_response_exhausted", model="llama3")
+ result = {
+ # finalize_turn leaves ``failed`` False for this exit reason (and ``completed`` follows the
+ # ordinary rule); only the descriptor code is stamped.
+ "final_response": explainer, "failed": False, "completed": True, "model": "llama3",
+ "turn_exit_reason": "empty_response_exhausted", "failure_reason": "empty_response",
+ "failure_retryable": True, "messages": [], "api_calls": 3,
+ }
+ assert _final_response_from_result(result, "job1", "Morning brief", _AIAgent) == ""
+
+
+def test_a_failed_turn_still_raises_so_the_job_is_marked_failed():
+ result = {"final_response": "stopped", "failed": True, "completed": False, "error": "boom",
+ "turn_exit_reason": "repeated_outer_errors(x)", "messages": [], "api_calls": 3}
+ with pytest.raises(RuntimeError):
+ _final_response_from_result(result, "job1", "Morning brief", _AIAgent)
diff --git a/tests/cron/test_cron_failure_alert_remediation_hint.py b/tests/cron/test_cron_failure_alert_remediation_hint.py
index bc9308b3908..545fa4343ac 100644
--- a/tests/cron/test_cron_failure_alert_remediation_hint.py
+++ b/tests/cron/test_cron_failure_alert_remediation_hint.py
@@ -18,7 +18,7 @@ def test_empty_chain_alert_names_the_remediation_commands(monkeypatch):
monkeypatch.setattr(scheduler, "get_fallback_chain", lambda cfg: [])
job = {"name": "semi-analyst-radar", "id": "aaa111"}
msg = _summarize_cron_failure_for_delivery(job, "Request timed out.")
- assert "No fallback chain configured" in msg
+ assert "No backup provider is configured" in msg
assert "hermes fallback add" in msg
assert "cron.model_provider" in msg
@@ -34,7 +34,7 @@ def test_exhausted_chain_alert_does_not_carry_the_config_hint(monkeypatch):
)
job = {"name": "semi-analyst-radar", "id": "aaa111"}
msg = _summarize_cron_failure_for_delivery(job, "Request timed out.")
- assert "Fallback chain was exhausted or unavailable." in msg
+ assert "No backup provider succeeded either." in msg
assert "hermes fallback add" not in msg
@@ -43,5 +43,5 @@ def test_rate_limit_empty_chain_also_carries_the_hint(monkeypatch):
monkeypatch.setattr(scheduler, "get_fallback_chain", lambda cfg: [])
job = {"name": "kz-coverage", "id": "bbb222"}
msg = _summarize_cron_failure_for_delivery(job, "HTTP 429: rate limit exceeded")
- assert "No fallback chain configured" in msg
+ assert "No backup provider is configured" in msg
assert "hermes fallback add" in msg
diff --git a/tests/cron/test_cron_failure_notice_copy.py b/tests/cron/test_cron_failure_notice_copy.py
new file mode 100644
index 00000000000..ee83d8e2b1f
--- /dev/null
+++ b/tests/cron/test_cron_failure_notice_copy.py
@@ -0,0 +1,89 @@
+"""User-facing cron failure notices: plain words, the real output path, and the exact `hermes cron`
+command to act on. Contract tests, not snapshots (root AGENTS.md).
+
+The classifier is `agent.error_classifier.classify_api_error`; these tests pin what the copy table
+does with its verdict, not the verdict itself.
+"""
+
+import re
+
+import cron.scheduler as scheduler
+from cron.scheduler import _compose_run_delivery, _summarize_cron_failure_for_delivery
+from hermes_constants import display_hermes_home
+
+JOB = {"name": "Morning brief", "id": "ab12cd34"}
+_HTTP_LEAD = re.compile(r"failed: (HTTP|Error code:|provider )")
+
+
+def _no_chain(monkeypatch):
+ monkeypatch.setattr(scheduler, "load_config", lambda: {})
+ monkeypatch.setattr(scheduler, "get_fallback_chain", lambda cfg: [])
+
+
+def test_generic_failure_names_runs_and_pause_commands_and_the_real_output_dir():
+ msg = _summarize_cron_failure_for_delivery(JOB, "[Errno 2] No such file or directory: '/x.py'")
+ assert "/x.py" in msg # the raw detail survives as the cause
+ for cmd in ("hermes cron runs ab12cd34", "hermes cron run ab12cd34", "hermes cron pause ab12cd34"):
+ assert f"`{cmd}`" in msg
+ assert f"{display_hermes_home()}/cron/output/ab12cd34/" in msg
+ assert "cron output" not in msg # the unnamed internal location is gone
+
+
+def test_auth_failure_points_at_login_and_a_retry_command(monkeypatch):
+ _no_chain(monkeypatch)
+ msg = _summarize_cron_failure_for_delivery(JOB, "Error code: 401 - Unauthorized")
+ assert "/login" in msg and "`hermes auth add <provider>`" in msg
+ assert "hermes login" not in msg # that command was removed
+ assert "`hermes cron run ab12cd34`" in msg
+ assert not _HTTP_LEAD.search(msg)
+ assert "401" not in msg
+
+
+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."""
+ _no_chain(monkeypatch)
+ for text in (
+ "Nous Portal rate limit active until 15:00",
+ "RuntimeError: usage limit reached for this key",
+ "You have hit your weekly usage limit",
+ "insufficient quota",
+ ):
+ msg = _summarize_cron_failure_for_delivery(JOB, text)
+ assert "limit" in msg.lower(), msg
+ assert not _HTTP_LEAD.search(msg), msg
+ assert "`hermes cron run ab12cd34`" in msg or "`hermes cron edit ab12cd34" in msg, msg
+
+
+def test_cron_cause_gloss_is_the_shared_table():
+ """Cron, subagent and chat notices read one reason->cause table (agent/turn_failure_copy.py)."""
+ from agent.turn_failure_copy import FAILURE_CAUSE_GLOSS
+ from cron.scheduler_failure_copy import provider_failure_notice
+
+ for reason in FAILURE_CAUSE_GLOSS:
+ notice = provider_failure_notice("Morning brief", "ab12cd34", reason, backup_provider_phrase="x.")
+ assert notice is not None and "`hermes cron" in notice, reason
+ assert provider_failure_notice("Morning brief", "ab12cd34", "unknown", backup_provider_phrase="x.") is None
+
+
+def test_transient_provider_failures_never_lead_with_jargon(monkeypatch):
+ _no_chain(monkeypatch)
+ for err in ("Request timed out.", "HTTP 429: Too Many Requests"):
+ msg = _summarize_cron_failure_for_delivery(JOB, err)
+ assert not _HTTP_LEAD.search(msg), msg
+ assert "fallback chain" not in msg.lower()
+ assert "`hermes cron run ab12cd34`" in msg
+ assert "`hermes cron runs ab12cd34`" in msg
+
+
+def test_blocked_config_notice_says_it_did_not_run_and_will_self_heal():
+ text, blocked, *_ = _compose_run_delivery(
+ JOB, success=False, error="[blocked_config] provider credential missing: no key",
+ final_response="", output_file=None)
+ assert blocked is True
+ assert "did not run" in text
+ assert "provider credential missing: no key" in text
+ assert "Nothing was charged" in text
+ assert "`hermes cron doctor`" in text
+ for jargon in ("configuration validation", "LLM call", "pre-dispatch"):
+ assert jargon not in text
diff --git a/tests/cron/test_cron_failure_summarizer_inactivity.py b/tests/cron/test_cron_failure_summarizer_inactivity.py
index 301c194fc96..5205010a24d 100644
--- a/tests/cron/test_cron_failure_summarizer_inactivity.py
+++ b/tests/cron/test_cron_failure_summarizer_inactivity.py
@@ -31,8 +31,8 @@ def test_inactivity_timeout_is_not_reported_as_provider_timeout():
"(limit 600s) — last activity: terminal command running (30s elapsed)"
)
msg = _summarize_cron_failure_for_delivery(job, error)
- assert "provider timeout" not in msg
- assert "fallback chain" not in msg.lower()
+ assert "did not respond in time" not in msg
+ assert "backup provider" not in msg.lower()
assert "stalled" in msg.lower()
assert "Daily Repo Sweep" in msg
@@ -43,9 +43,9 @@ def test_genuine_provider_timeout_with_no_fallback_configured(monkeypatch):
job = {"name": "CI Autofix Poller", "id": "f7fe78574bda"}
error = "Request timed out."
msg = _summarize_cron_failure_for_delivery(job, error)
- assert "provider timeout" in msg
- assert "No fallback chain configured" in msg
- assert "exhausted or unavailable" not in msg
+ assert "did not respond in time" in msg
+ assert "No backup provider is configured" in msg
+ assert "succeeded either" not in msg
def test_genuine_provider_timeout_with_fallback_configured(monkeypatch):
@@ -60,9 +60,9 @@ def test_genuine_provider_timeout_with_fallback_configured(monkeypatch):
job = {"name": "CI Autofix Poller", "id": "f7fe78574bda"}
error = "Request timed out."
msg = _summarize_cron_failure_for_delivery(job, error)
- assert "provider timeout" in msg
- assert "Fallback chain was exhausted or unavailable." in msg
- assert "No fallback chain configured" not in msg
+ assert "did not respond in time" in msg
+ assert "No backup provider succeeded either." in msg
+ assert "No backup provider is configured" not in msg
def test_fallback_chain_phrase_fails_open_on_config_error(monkeypatch):
@@ -70,7 +70,7 @@ def test_fallback_chain_phrase_fails_open_on_config_error(monkeypatch):
raise RuntimeError("config unreadable")
monkeypatch.setattr(scheduler, "load_config", _raise)
- assert scheduler._fallback_chain_phrase() == "Fallback chain was exhausted or unavailable."
+ assert scheduler._fallback_chain_phrase() == "No backup provider succeeded either."
def test_readtimeout_error_still_classified_as_provider_timeout(monkeypatch):
@@ -79,7 +79,7 @@ def test_readtimeout_error_still_classified_as_provider_timeout(monkeypatch):
job = {"name": "some-job", "id": "abc123"}
error = "httpx.ReadTimeout: The read operation timed out"
msg = _summarize_cron_failure_for_delivery(job, error)
- assert "provider timeout" in msg
+ assert "did not respond in time" in msg
def test_rate_limit_classification_still_takes_priority_over_inactivity_text(monkeypatch):
@@ -92,5 +92,7 @@ def test_rate_limit_classification_still_takes_priority_over_inactivity_text(mon
job = {"name": "some-job", "id": "abc123"}
error = "HTTP 429: weekly usage limit exceeded"
msg = _summarize_cron_failure_for_delivery(job, error)
- assert "weekly usage limit" in msg
- assert "No fallback chain configured" in msg
+ # A usage-limit wall is a billing verdict: it names the limit and the provider-pin fix,
+ # never the transient "backup provider" retry clause.
+ assert "usage or credit limit" in msg
+ assert "hermes cron edit abc123 --provider" in msg
diff --git a/tests/cron/test_cron_multiplex_desktop_ticker_scope.py b/tests/cron/test_cron_multiplex_desktop_ticker_scope.py
index 9be477c8ca2..31d5dc22da8 100644
--- a/tests/cron/test_cron_multiplex_desktop_ticker_scope.py
+++ b/tests/cron/test_cron_multiplex_desktop_ticker_scope.py
@@ -150,88 +150,3 @@ def test_desktop_ticker_gates_on_profile_gateway_running(tmp_path, monkeypatch,
assert all(gate(name, home) for name, home in homes)
running.update(home for _, home in homes)
assert not any(gate(name, home) for name, home in homes)
-
-
-def test_a_routed_profile_fire_runs_under_multiplex_semantics_for_exactly_its_scope(tmp_path, monkeypatch):
- """The desktop ticker fires a SIBLING profile's job from a process that is not a multiplexer.
- The tick only MARKS the fire as routed; multiplex semantics switch on where run_one_job
- installs the profile's secret scope and off with it — so the routed .env stays out of the
- shared os.environ, a scope miss never falls back to the launch profile's credentials, and
- the parent process env is byte-identical after the tick (#107692)."""
- import os
-
- import cron.scheduler as scheduler
- from agent import secret_scope
- from cron.scheduler_provider import _profile_cron_scope, routed_profile_fire
- from hermes_cli.env_loader import load_hermes_dotenv
-
- launch, routed = tmp_path / "launch", tmp_path / "launch" / "profiles" / "ops"
- for home in (launch, routed):
- (home / "cron").mkdir(parents=True)
- (launch / ".env").write_text("XAI_API_KEY=launch-key\nDISCORD_BOT_TOKEN=launch-bot\n", encoding="utf-8")
- (routed / ".env").write_text("XAI_API_KEY=routed-key\nROUTED_ONLY=routed-only\n", encoding="utf-8")
- monkeypatch.setenv("HERMES_HOME", str(launch))
- monkeypatch.setenv("XAI_API_KEY", "launch-key")
- monkeypatch.setenv("DISCORD_BOT_TOKEN", "launch-bot")
- monkeypatch.delenv("ROUTED_ONLY", raising=False)
- secret_scope.set_multiplex_active(False) # the desktop backend never sets the process flag
- environ_before = dict(os.environ)
-
- with _profile_cron_scope(routed):
- # Before the scope exists — where run_one_job's restart-safe handoff runs — the marker is
- # set, the semantics are not.
- assert routed_profile_fire() is True
- assert secret_scope.is_multiplex_active() is False
-
- tokens = scheduler._install_fire_secret_scope()
- try:
- assert secret_scope.is_multiplex_active() is True
- # The job's per-run dotenv reload, exactly as cron/scheduler does it: hydrate-only.
- assert load_hermes_dotenv(hermes_home=routed, load_external_secrets=False) == []
- assert secret_scope.get_secret("XAI_API_KEY") == "routed-key"
- assert secret_scope.get_secret("DISCORD_BOT_TOKEN") is None # never the launch bot
- finally:
- scheduler._reset_fire_secret_scope(tokens)
- assert secret_scope.is_multiplex_active() is False # off with the scope, not later
-
- assert routed_profile_fire() is False
- assert dict(os.environ) == environ_before
-
-
- ("routed_env_line", "expected"),
- [
- ("", "managed-key"), # managed-only credential: resolvable, not absent
- ("ORG_API_KEY=user-key\n", "managed-key"), # managed-vs-user collision: policy wins
- ],
- ids=["managed-only", "managed-beats-user"],
-)
-def test_routed_fire_scope_carries_managed_env_authority(tmp_path, monkeypatch, routed_env_line, expected):
- """Under multiplex semantics get_secret never falls back to os.environ, so the routed fire's
- scope itself must carry the administrator-managed .env with the precedence _apply_managed_env
- gives it in the launch process: a managed-only key is present and a managed value beats the
- routed profile's own (#111187 review)."""
- import cron.scheduler as scheduler
- from agent import secret_scope
- from cron.scheduler_provider import _profile_cron_scope
- from hermes_cli import managed_scope
-
- launch, routed = tmp_path / "launch", tmp_path / "launch" / "profiles" / "ops"
- managed = tmp_path / "managed"
- for home in (launch, routed, managed):
- (home / "cron").mkdir(parents=True)
- (routed / ".env").write_text(routed_env_line, encoding="utf-8")
- (managed / ".env").write_text("ORG_API_KEY=managed-key\n", encoding="utf-8")
- monkeypatch.setenv("HERMES_HOME", str(launch))
- monkeypatch.setenv("HERMES_MANAGED_DIR", str(managed))
- monkeypatch.setenv("ORG_API_KEY", "managed-key") # what _apply_managed_env left in the launch env
- managed_scope.invalidate_managed_cache()
- secret_scope.set_multiplex_active(False)
-
- with _profile_cron_scope(routed):
- tokens = scheduler._install_fire_secret_scope()
- try:
- assert secret_scope.is_multiplex_active() is True
- assert secret_scope.get_secret("ORG_API_KEY") == expected
- finally:
- scheduler._reset_fire_secret_scope(tokens)
diff --git a/tests/cron/test_cron_no_agent.py b/tests/cron/test_cron_no_agent.py
index 0302277b52d..cb51a046403 100644
--- a/tests/cron/test_cron_no_agent.py
+++ b/tests/cron/test_cron_no_agent.py
@@ -234,10 +234,10 @@ def test_agent_provider_timeout_delivery_keeps_fallback_guidance(hermes_env, mon
assert scheduler.run_one_job(job) is True
assert len(delivered) == 1
- assert "provider timeout" in delivered[0].lower()
- # Chain wording is now honest (#85508): exhausted when configured,
- # "no fallback chain configured" guidance otherwise.
- assert "fallback chain" in delivered[0].lower()
+ assert "did not respond in time" in delivered[0].lower()
+ # Chain wording is honest (#85508): "no backup provider succeeded" when configured,
+ # "no backup provider is configured" guidance otherwise.
+ assert "backup provider" in delivered[0].lower()
# ---------------------------------------------------------------------------
@@ -348,8 +348,8 @@ def test_no_agent_failure_never_blamed_on_a_provider(error):
job = {"name": "nightly-job", "no_agent": True, "script": "nightly.sh"}
msg = _summarize_cron_failure_for_delivery(job, error)
- assert "provider" not in msg.lower()
- assert "fallback chain" not in msg.lower()
+ assert "ai model service" not in msg.lower()
+ assert "backup provider" not in msg.lower()
# The operator must be pointed at what actually failed.
assert "script" in msg.lower()
@@ -357,9 +357,9 @@ def test_no_agent_failure_never_blamed_on_a_provider(error):
@pytest.mark.parametrize(
("error", "expected"),
[
- ("ReadTimeout: provider did not respond", "provider timeout"),
- ("HTTP 429 rate limit exceeded", "provider rate limit"),
- ("HTTP 401 authentication failed", "provider authentication error"),
+ ("ReadTimeout: provider did not respond", "did not respond in time"),
+ ("HTTP 429 rate limit exceeded", "rate-limited"),
+ ("HTTP 401 authentication failed", "rejected the sign-in"),
],
)
def test_agent_job_provider_classification_unchanged(error, expected):
@@ -368,105 +368,3 @@ def test_agent_job_provider_classification_unchanged(error, expected):
job = {"name": "daily-digest", "no_agent": False}
assert expected in _summarize_cron_failure_for_delivery(job, error)
-
-
-def test_a_routed_profile_script_never_receives_a_launch_only_name(hermes_env, monkeypatch):
- """A no_agent script fired for a SIBLING profile runs with that profile's scope overlaid and
- NONE of the launch profile's residue (#107695 review): a name the launch ``.env`` defines, and a
- name a launch external source SUPPLIED — applied, or skipped because a process value already won
- (``skipped_existing``, so it never entered the provenance map) — reach the child unset. The
- routed profile's own values come through, and the parent ``os.environ`` is never mutated."""
- import os
-
- from agent import secret_scope
- from agent.secret_sources import registry as reg_module
- from agent.secret_sources.base import FetchResult
- from agent.secret_sources.registry import ApplyReport, SourceReport
- from cron.scheduler_script import _run_job_script
- from hermes_cli import env_loader
- from hermes_constants import get_process_hermes_home, reset_hermes_home_override, set_hermes_home_override
-
- launch = get_process_hermes_home()
- (launch / ".env").write_text("LAUNCH_ONLY_VALUE=launch-only\nCUSTOM_CRON_VALUE=launch\n", encoding="utf-8")
- (launch / "config.yaml").write_text("secrets:\n test-source:\n enabled: true\n", encoding="utf-8")
- for name, value in (("LAUNCH_ONLY_VALUE", "launch-only"), ("CUSTOM_CRON_VALUE", "launch"),
- ("LAUNCH_VAULT_ONLY", "launch-vault-value"), ("LAUNCH_SKIPPED_SECRET", "launch-value")):
- monkeypatch.setenv(name, value)
- monkeypatch.setattr(env_loader, "_SOURCE_SUPPLIED_NAMES", set())
- monkeypatch.setattr(env_loader, "_SECRET_SOURCES", {"LAUNCH_VAULT_ONLY": "vault", "ROUTED_VAULT_ONLY": "vault"})
- monkeypatch.setattr(env_loader, "_APPLIED_HOMES", set())
- monkeypatch.setattr(env_loader, "_SECRET_SOURCE_VALUES_BY_HOME", {})
- monkeypatch.setattr(reg_module, "apply_all", lambda _cfg, home_path, **_kw: ApplyReport(
- sources=[SourceReport(name="test-source", label="Test Source", result=FetchResult(),
- applied=[], skipped_existing=["LAUNCH_SKIPPED_SECRET"])],
- provenance={}))
- env_loader._apply_external_secret_sources(launch) # the real registry path; the source loses to the env
- environ_before = dict(os.environ)
-
- routed = launch / "profiles" / "ops"
- (routed / "scripts").mkdir(parents=True, exist_ok=True)
- # Under the routed home override the runner resolves scripts against THAT profile's scripts dir.
- script = routed / "scripts" / "probe_launch_only.sh"
- script.write_text(
- '#!/bin/bash\necho "${CUSTOM_CRON_VALUE}|${ROUTED_VAULT_ONLY}|${LAUNCH_ONLY_VALUE:-<unset>}'
- '|${LAUNCH_VAULT_ONLY:-<unset>}|${LAUNCH_SKIPPED_SECRET:-<unset>}"\n'
- )
-
- home_token = set_hermes_home_override(str(routed))
- context_token = secret_scope.set_multiplex_context(True)
- scope_token = secret_scope.set_secret_scope(
- {"CUSTOM_CRON_VALUE": "routed", "ROUTED_VAULT_ONLY": "routed-vault-value"})
- try:
- ok, output = _run_job_script("probe_launch_only.sh")
- finally:
- secret_scope.reset_secret_scope(scope_token)
- secret_scope.reset_multiplex_context(context_token)
- reset_hermes_home_override(home_token)
-
- assert ok, output
- assert output.strip() == "routed|routed-vault-value|<unset>|<unset>|<unset>"
- assert dict(os.environ) == environ_before
-
-
-def test_a_routed_profile_script_keeps_administrator_managed_values_over_its_own(hermes_env, monkeypatch):
- """Managed-scope precedence (#107695 review on f5f88d5058): the administrator's managed ``.env`` is
- applied LAST with override in the launch process, so it beats the user's own ``.env``. Managed keys
- are not launch residue, and they are re-applied over the routed scope so the child sees the same
- precedence the launch process does."""
- import os
-
- from agent import secret_scope
- from cron.scheduler_script import _run_job_script
- from hermes_cli import env_loader, managed_scope
- from hermes_constants import get_process_hermes_home, reset_hermes_home_override, set_hermes_home_override
-
- launch = get_process_hermes_home()
- managed = launch / "managed"
- managed.mkdir()
- (managed / ".env").write_text("ORG_POLICY_FLAG=managed-value\n", encoding="utf-8")
- monkeypatch.setattr(env_loader, "_LOADED_DOTENV_KEYS", set(env_loader._LOADED_DOTENV_KEYS))
- monkeypatch.setattr(env_loader, "_MANAGED_DOTENV_KEYS", set())
- monkeypatch.setattr(managed_scope, "get_managed_dir", lambda: managed)
- monkeypatch.setenv("ORG_POLICY_FLAG", "placeholder")
- env_loader._apply_managed_env() # the boot-time managed load
- assert os.environ["ORG_POLICY_FLAG"] == "managed-value"
-
- routed = launch / "profiles" / "ops"
- (routed / "scripts").mkdir(parents=True, exist_ok=True)
- script = routed / "scripts" / "probe_policy.sh"
- script.write_text('#!/bin/bash\necho "${ORG_POLICY_FLAG:-<unset>}"\n')
-
- home_token = set_hermes_home_override(str(routed))
- context_token = secret_scope.set_multiplex_context(True)
- # The routed user's own .env carries a competing value for the managed key.
- scope_token = secret_scope.set_secret_scope({"ORG_POLICY_FLAG": "user-value"})
- try:
- ok, output = _run_job_script("probe_policy.sh")
- finally:
- secret_scope.reset_secret_scope(scope_token)
- secret_scope.reset_multiplex_context(context_token)
- reset_hermes_home_override(home_token)
-
- assert ok, output
- assert output.strip() == "managed-value"
- assert os.environ["ORG_POLICY_FLAG"] == "managed-value" # parent untouched
diff --git a/tests/cron/test_preflight_config.py b/tests/cron/test_preflight_config.py
index 273d5b9a315..1847bcd2925 100644
--- a/tests/cron/test_preflight_config.py
+++ b/tests/cron/test_preflight_config.py
@@ -159,7 +159,7 @@ class TestMissingProviderKeyBlocks:
f"expected exactly one alert across two ticks, got {len(deliveries)}: "
f"{deliveries!r}"
)
- assert "blocked" in deliveries[0].lower()
+ assert "did not run" in deliveries[0].lower()
def test_fallback_chain_rescues_missing_primary_key(self, tmp_path):
"""A configured fallback chain means a missing primary key does NOT
diff --git a/tests/cron/test_restart_safe_worker.py b/tests/cron/test_restart_safe_worker.py
index 8b9032d1da7..b7e55bbf142 100644
--- a/tests/cron/test_restart_safe_worker.py
+++ b/tests/cron/test_restart_safe_worker.py
@@ -258,49 +258,6 @@ def _stub_external_worker_launch(scheduler, monkeypatch):
return spawned, payloads, handoff, get
-def test_launch_external_worker_treats_a_routed_fire_as_multiplexed(tmp_path, monkeypatch):
- """A fire routed to another profile is multiplexed at the handoff boundary (#107695 review on
- f5f88d5058). ``run_one_job`` only enables the context in ``_install_fire_secret_scope``, which runs
- AFTER this handoff, so a routed desktop fire on the managed path serialized ``multiplex_active=False``
- and the worker inherited the launch profile's residue. The payload must carry ``True`` and the
- worker env must not carry a launch-only value — and the context must not outlive the handoff."""
- import cron.scheduler as scheduler
- import hermes_constants
- from agent import secret_scope
- from hermes_constants import reset_hermes_home_override, set_hermes_home_override
- from tools.process_registry import GatewayChildDispatch
-
- launch = tmp_path / "launch"
- routed = tmp_path / "routed"
- launch.mkdir()
- routed.mkdir()
- (launch / ".env").write_text("LAUNCH_ONLY_SECRET=launch-secret\n", encoding="utf-8")
- (routed / ".env").write_text("", encoding="utf-8")
- monkeypatch.setenv("LAUNCH_ONLY_SECRET", "launch-secret")
- monkeypatch.setattr(scheduler, "_get_hermes_home", lambda: routed)
- monkeypatch.setattr(hermes_constants, "get_process_hermes_home", lambda: launch)
- monkeypatch.setattr("cron.scheduler_provider.routed_profile_fire", lambda: True)
- monkeypatch.setattr(
- "tools.process_registry.restart_safe_gateway_child_argv",
- lambda command, *, unit_suffix, require_restart_safe_scope=False: GatewayChildDispatch(
- "scoped", ["scope", "--", *command]),
- )
- spawned, payloads, _handoff, _get = _stub_external_worker_launch(scheduler, monkeypatch)
-
- assert not secret_scope.is_multiplex_active() # the desktop tick itself is NOT a multiplexer
- home_token = set_hermes_home_override(str(routed))
- try:
- assert scheduler._launch_external_cron_worker(
- {"id": "job-r", "execution_id": "exec-1", "prompt": "work"}) is True
- finally:
- reset_hermes_home_override(home_token)
-
- assert payloads[0]["multiplex_active"] is True
- assert "LAUNCH_ONLY_SECRET" not in spawned[0][1]["env"]
- assert not secret_scope.is_multiplex_active() # enabled for the handoff span only
- assert os.environ["LAUNCH_ONLY_SECRET"] == "launch-secret" # parent untouched
-
-
def test_launch_external_worker_uses_restart_safe_scope_and_acknowledges(
tmp_path, monkeypatch
):
diff --git a/tests/cron/test_run_one_job.py b/tests/cron/test_run_one_job.py
index 9b241de1b63..318ad5b17fa 100644
--- a/tests/cron/test_run_one_job.py
+++ b/tests/cron/test_run_one_job.py
@@ -115,9 +115,14 @@ def test_run_one_job_exception_delivers_failure_alert(monkeypatch):
ok = s.run_one_job({"id": "j3", "name": "morning", "deliver": "telegram"})
assert ok is False
- assert delivered == [
- ("j3", "⚠️ Cron 'morning' failed: Gemini HTTP 503 (UNAVAILABLE)")
- ]
+ assert len(delivered) == 1 and delivered[0][0] == "j3"
+ # The notice carries the classifier verdict's gloss from the copy table (whatever its wording),
+ # never the raw HTTP code as the lead, plus a retry command.
+ from cron.scheduler_failure_copy import _provider_failure_cause, classify_cron_failure_reason
+ gloss = _provider_failure_cause(classify_cron_failure_reason("Gemini HTTP 503 (UNAVAILABLE)"))
+ assert gloss and gloss in delivered[0][1]
+ assert not delivered[0][1].lstrip("⚠️ ").startswith("Gemini HTTP 503")
+ assert "hermes cron run j3" in delivered[0][1]
assert marked == [
(("j3", False, "Gemini HTTP 503 (UNAVAILABLE)"), {"delivery_error": None})
]
@@ -234,7 +239,9 @@ def test_escaped_failure_delivery_stays_quiet_below_the_threshold(monkeypatch):
)
assert ok is False
- assert delivered == ["⚠️ Cron 'scout' failed: provider failed"]
+ assert len(delivered) == 1
+ assert delivered[0].startswith("⚠️ Cron 'scout' failed: provider failed")
+ assert "hermes cron runs j6" in delivered[0]
def test_run_one_job_exception_after_delivery_does_not_redeliver(monkeypatch):
diff --git a/tests/cron/test_scheduler.py b/tests/cron/test_scheduler.py
index 483209d6770..b89c027a647 100644
--- a/tests/cron/test_scheduler.py
+++ b/tests/cron/test_scheduler.py
@@ -48,7 +48,7 @@ class TestSummarizeCronFailureForDelivery:
"Script failed: path/hash429abc.md source snapshot failure",
)
- assert "provider rate limit" not in summary
+ assert "rate-limited" not in summary
assert "hash429abc.md" in summary
def test_http_429_is_still_classified_as_a_rate_limit(self):
@@ -57,10 +57,10 @@ class TestSummarizeCronFailureForDelivery:
"HTTP 429: Too Many Requests",
)
- assert "provider rate limit" in summary
- # Chain wording is now honest (#85508): either the exhausted phrase
- # (chain configured) or the "No fallback chain configured" guidance.
- assert "fallback chain" in summary.lower()
+ assert "rate-limited" in summary
+ # Chain wording is honest (#85508): either "no backup provider succeeded" (chain
+ # configured) or the "no backup provider is configured" guidance.
+ assert "backup provider" in summary.lower()
def test_no_agent_rate_limit_does_not_claim_a_fallback_chain(self):
summary = _summarize_cron_failure_for_delivery(
@@ -71,8 +71,8 @@ class TestSummarizeCronFailureForDelivery:
# Composed with #77648: a no_agent job never gets provider-shaped
# classification at all — the generic cleaner reports the script's
# own error instead.
- assert "provider" not in summary.lower()
- assert "fallback chain" not in summary.lower()
+ assert "ai model service" not in summary.lower()
+ assert "backup provider" not in summary.lower()
def test_no_agent_timeout_is_identified_as_a_script_timeout(self):
summary = _summarize_cron_failure_for_delivery(
@@ -82,8 +82,8 @@ class TestSummarizeCronFailureForDelivery:
assert "script timed out" in summary
assert "No model was invoked" in summary
- assert "provider timeout" not in summary
- assert "fallback chain" not in summary.lower()
+ assert "did not respond in time" not in summary
+ assert "backup provider" not in summary.lower()
class TestPerJobToolsetMcpMerge:
@@ -1137,7 +1137,7 @@ class TestRunJobConfigLogging:
with caplog.at_level(logging.WARNING):
run_job(job)
- assert any("Failed to parse" in r.message and "config.yaml" in r.message for r in caplog.records), \
+ assert any("formatting error" in r.message and "config.yaml" in r.message for r in caplog.records), \
f"Expected a config.yaml parse warning in logs, got: {[r.message for r in caplog.records]}"
diff --git a/tests/gateway/test_approval_prompt_redaction.py b/tests/gateway/test_approval_prompt_redaction.py
index 592a71dcbf4..0f283de046c 100644
--- a/tests/gateway/test_approval_prompt_redaction.py
+++ b/tests/gateway/test_approval_prompt_redaction.py
@@ -138,3 +138,15 @@ class TestApprovalTextFallbackContract:
assert "approve session" not in text
assert "approve always" not in text
+ def test_text_fallback_says_silence_means_no(self, monkeypatch):
+ """Surfaces without buttons get the same deadline line as the button card."""
+ from gateway.run import _format_exec_approval_fallback
+
+ monkeypatch.setattr("gateway.platforms.base_exec_approval.approval_timeout_seconds", lambda: 300)
+ text = _format_exec_approval_fallback("rm -rf /", "recursive delete", "/")
+ assert "Hermes wants to run a command that needs your OK" in text
+ assert "Why it was flagged: recursive delete" in text
+ assert "If you don't answer within 5 minutes it will NOT run." in text
+ for step in ("`/approve`", "`/approve session`", "`/approve always`", "`/deny`"):
+ assert step in text
+
diff --git a/tests/gateway/test_approval_timeout_notice.py b/tests/gateway/test_approval_timeout_notice.py
new file mode 100644
index 00000000000..b283503e772
--- /dev/null
+++ b/tests/gateway/test_approval_timeout_notice.py
@@ -0,0 +1,63 @@
+"""Invariants for the exec-approval timeout notice hook (gateway/run_turn_runner_approval_settle.py)."""
+
+from types import SimpleNamespace
+
+import pytest
+
+from gateway import run_turn_runner_approval_settle as settle_mod
+
+
+class _Runner:
+ def __init__(self, *, current: bool):
+ self.scheduled = []
+ self._ctx = SimpleNamespace(session_key="telegram:1", _run_still_current=lambda: current)
+
+ def _schedule(self, coro, label):
+ coro.close()
+ self.scheduled.append(label)
+ return None
+
+
+def _capture_settle(monkeypatch):
+ hooks = {}
+ monkeypatch.setattr("tools.approval.register_gateway_settle", lambda sk, rid, fn: hooks.__setitem__(rid, fn))
+ return hooks
+
+
[email protected]("current, expected", [(True, 1), (False, 0)])
+def test_timeout_notice_is_gated_on_the_run_still_being_current(monkeypatch, current, expected):
+ hooks = _capture_settle(monkeypatch)
+ runner = _Runner(current=current)
+ settle_mod.register_timeout_notice(runner, {"request_id": "r1"}, command="rm -rf x", card_message_id="42")
+ hooks["r1"]("timeout")
+ assert len(runner.scheduled) == expected
+
+
+def test_non_timeout_reasons_never_post(monkeypatch):
+ hooks = _capture_settle(monkeypatch)
+ runner = _Runner(current=True)
+ settle_mod.register_timeout_notice(runner, {"request_id": "r2"}, command="ls", card_message_id=None)
+ for reason in ("answered", "interrupted", "notify_failed"):
+ hooks["r2"](reason)
+ assert runner.scheduled == []
+
+
+async def test_text_prompt_is_never_edited_in_place():
+ """card_message_id=None (the text-fallback path) must send a new message, not rewrite the prompt."""
+ calls = []
+
+ class _Adapter:
+ async def edit_message(self, chat_id, message_id, content):
+ calls.append(("edit", message_id))
+ return SimpleNamespace(success=True)
+
+ async def send(self, chat_id, content, metadata=None):
+ calls.append(("send", content))
+ return SimpleNamespace(success=True)
+
+ ctx = SimpleNamespace(_status_adapter=_Adapter(), _status_chat_id="c", _status_thread_metadata=None)
+ await settle_mod._post_timeout_notice(ctx, "ls", None, 300)
+ assert [kind for kind, _ in calls] == ["send"]
+ await settle_mod._post_timeout_notice(ctx, "ls", "card-9", 300)
+ assert ("edit", "card-9") in calls
diff --git a/tests/gateway/test_approve_deny_commands.py b/tests/gateway/test_approve_deny_commands.py
index 3aa2dc07668..8733097337c 100644
--- a/tests/gateway/test_approve_deny_commands.py
+++ b/tests/gateway/test_approve_deny_commands.py
@@ -468,7 +468,7 @@ class TestCrossSessionApprovalIsolation:
a concurrent gateway session (e.g. a second Discord thread) clobbered
the value, and a tool worker thread whose approval contextvar was unset
fell back to ``os.environ`` and read the *wrong* session key — routing
- the "Command Approval Required" prompt to the wrong thread.
+ the approval prompt to the wrong thread.
The fix removes that ``os.environ`` write; routing is driven solely by
the ``_approval_session_key`` contextvar. These tests assert that a
diff --git a/tests/gateway/test_background_command.py b/tests/gateway/test_background_command.py
index 54d34e64dd0..85071be9a9a 100644
--- a/tests/gateway/test_background_command.py
+++ b/tests/gateway/test_background_command.py
@@ -108,7 +108,8 @@ class TestRunBackgroundTask:
# Should have sent an error message
mock_adapter.send.assert_called_once()
call_args = mock_adapter.send.call_args
- assert "failed" in call_args[1].get("content", call_args[0][1] if len(call_args[0]) > 1 else "").lower()
+ content = call_args[1].get("content", call_args[0][1] if len(call_args[0]) > 1 else "")
+ assert "couldn't start" in content and "/login" in content
@pytest.mark.asyncio
async def test_successful_task_sends_result(self):
diff --git a/tests/gateway/test_background_process_notifications.py b/tests/gateway/test_background_process_notifications.py
index 716a67e70c0..c32a11f29d1 100644
--- a/tests/gateway/test_background_process_notifications.py
+++ b/tests/gateway/test_background_process_notifications.py
@@ -404,8 +404,9 @@ class TestConciseFormatter:
text = _format_concise_process_notification(
"proc_abc", "make build", 2, out,
)
- assert text.startswith("❌ Background task failed (exit 2)")
- assert "Traceback: boom" in text
+ assert text.startswith("❌ Background task failed")
+ assert "exit 2" in text and "Traceback: boom" in text
+ assert "rerun" in text
# Only a short tail, not the whole output
assert "line0" not in text
@@ -472,7 +473,7 @@ async def test_concise_mode_failure_includes_tail(monkeypatch, tmp_path):
adapter.send.assert_awaited_once()
sent_text = adapter.send.await_args.args[1]
- assert sent_text.startswith("❌ Background task failed (exit 128)")
+ assert sent_text.startswith("❌ Background task failed") and "exit 128" in sent_text
assert "fatal: repo not found" in sent_text
@@ -796,7 +797,7 @@ async def test_raw_output_modes_are_human_facing(monkeypatch, tmp_path):
assert len(sent) == 2
interim, final = sent
assert interim.startswith("⏳ Background task still running") and "step 1 ok" in interim
- assert final.startswith("❌ Background task failed (exit 2)") and "linker error" in final
+ assert final.startswith("❌ Background task failed") and "exit 2" in final and "linker error" in final
for text in sent:
assert "proc_deadbeef" not in text and "[Background process" not in text and "~" not in text
assert "\x1b[" not in text
diff --git a/tests/gateway/test_cron_interrupt_notification.py b/tests/gateway/test_cron_interrupt_notification.py
index 060706d1b6c..0784d7bf9ed 100644
--- a/tests/gateway/test_cron_interrupt_notification.py
+++ b/tests/gateway/test_cron_interrupt_notification.py
@@ -73,7 +73,8 @@ class TestNotifyInterruptedCronJobs:
assert len(adapter.sent) == 1
body = adapter.sent[0]
assert "daily-digest" in body
- assert "interrupted" in body.lower()
+ assert "cut short" in body.lower()
+ assert "hermes cron run daily-digest" in body
assert adapter.sent_calls[0][0] == "123456"
@pytest.mark.asyncio
@@ -215,7 +216,7 @@ class TestShutdownDeliversNoticeBeforeDisconnect:
real_send = adapter.send
async def _tracking_send(chat_id, content, reply_to=None, metadata=None):
- if "was interrupted" in content:
+ if "was cut short" in content:
events.append("cron_notice")
return await real_send(chat_id, content, reply_to=reply_to, metadata=metadata)
diff --git a/tests/gateway/test_discord_approval_mentions.py b/tests/gateway/test_discord_approval_mentions.py
index f8da4584c65..2099cdbcfaa 100644
--- a/tests/gateway/test_discord_approval_mentions.py
+++ b/tests/gateway/test_discord_approval_mentions.py
@@ -50,7 +50,7 @@ async def test_exec_approval_mentions_allowed_users_when_enabled(monkeypatch):
assert channel.sent_kwargs["content"].startswith("<@111> <@222>\n")
assert "make check" in channel.sent_kwargs["content"]
assert "allowed_mentions" in channel.sent_kwargs
- assert channel.sent_kwargs["embed"].title.endswith("Command Approval Required")
+ assert channel.sent_kwargs["embed"].title.endswith("Hermes wants to run a command that needs your OK")
def test_yaml_config_seeds_websocket_health_with_primary_precedence(monkeypatch):
diff --git a/tests/gateway/test_discord_exec_approval_content.py b/tests/gateway/test_discord_exec_approval_content.py
index 55bc787d60a..9d2f3a97925 100644
--- a/tests/gateway/test_discord_exec_approval_content.py
+++ b/tests/gateway/test_discord_exec_approval_content.py
@@ -40,11 +40,12 @@ async def test_exec_approval_prompt_uses_visible_content_with_command_and_reason
assert sent["embed"] is not None
prompt_text = sent["content"]
- assert "Command Approval Required" in prompt_text
+ assert "Hermes wants to run a command that needs your OK" in prompt_text
assert "Do you want Hermes to run this command?" in prompt_text
assert "Requested command" in prompt_text
assert command in prompt_text
- assert "Reason" in prompt_text
+ assert "Why it was flagged" in prompt_text
assert "script execution via -c flag" in prompt_text
+ assert "it will NOT run" in prompt_text
diff --git a/tests/gateway/test_discord_slash_auth.py b/tests/gateway/test_discord_slash_auth.py
index f935bdc2920..afcd12dc74d 100644
--- a/tests/gateway/test_discord_slash_auth.py
+++ b/tests/gateway/test_discord_slash_auth.py
@@ -514,9 +514,9 @@ async def test_skill_handler_rejects_before_dispatch_for_unauthorized(
interaction.response.send_message.assert_awaited_once()
args, kwargs = interaction.response.send_message.call_args
assert kwargs.get("ephemeral") is True
- assert "not authorized" in (
+ assert "hermes pairing approve discord" in (
args[0] if args else kwargs.get("content", "")
- ).lower()
+ )
# Critically: nothing was dispatched, and the auth message did NOT
# mention the skill name "alpha" (no catalog leak).
assert dispatched == []
diff --git a/tests/gateway/test_discord_view_base_parity.py b/tests/gateway/test_discord_view_base_parity.py
index ffcd26e2ed2..d21a1747a8c 100644
--- a/tests/gateway/test_discord_view_base_parity.py
+++ b/tests/gateway/test_discord_view_base_parity.py
@@ -49,25 +49,30 @@ def _views():
@pytest.mark.asyncio
@pytest.mark.parametrize(
- "name,call,expected",
+ "name,call",
[
- ("exec", lambda v, i: v._resolve(i, "once", None, "x"), "You're not authorized to approve commands~"),
- ("slash", lambda v, i: v._resolve(i, "once", None, "x"), "You're not authorized to answer this prompt~"),
- ("update", lambda v, i: v._respond(i, "y", None, "x"), "You're not authorized~"),
- ("clarify", lambda v, i: v._resolve_choice(i, 0, "a"), "You're not authorized to answer this prompt~"),
- ("clarify", lambda v, i: v._on_other(i), "You're not authorized to answer this prompt~"),
- ("model", lambda v, i: v._on_provider_selected(i), "You're not authorized~"),
- ("model", lambda v, i: v._on_back(i), "You're not authorized~"),
- ("choice", lambda v, i: v._on_select(i), "⛔ You are not authorized to change this setting."),
+ ("exec", lambda v, i: v._resolve(i, "once", None, "x")),
+ ("slash", lambda v, i: v._resolve(i, "once", None, "x")),
+ ("update", lambda v, i: v._respond(i, "y", None, "x")),
+ ("clarify", lambda v, i: v._resolve_choice(i, 0, "a")),
+ ("clarify", lambda v, i: v._on_other(i)),
+ ("model", lambda v, i: v._on_provider_selected(i)),
+ ("model", lambda v, i: v._on_back(i)),
+ ("choice", lambda v, i: v._on_select(i)),
],
)
-async def test_unauthorized_click_strings_preserved(monkeypatch, name, call, expected):
+async def test_unauthorized_click_uses_the_shared_notice(monkeypatch, name, call):
+ """Every view refuses a stranger with the ONE gateway-wide sentence that names the fix command."""
+ from gateway.platforms.base import unauthorized_action_notice
+
monkeypatch.delenv("DISCORD_ALLOW_ALL_USERS", raising=False)
monkeypatch.delenv("GATEWAY_ALLOW_ALL_USERS", raising=False)
monkeypatch.delenv("GATEWAY_ALLOWED_USERS", raising=False)
view = _views()[name]
interaction = _interaction()
await call(view, interaction)
+ expected = unauthorized_action_notice("discord")
+ assert "hermes pairing approve discord" in expected
interaction.response.send_message.assert_awaited_once_with(expected, ephemeral=True)
interaction.response.edit_message.assert_not_called()
assert view.resolved is False
diff --git a/tests/gateway/test_empty_sentinel_rewrite_copy.py b/tests/gateway/test_empty_sentinel_rewrite_copy.py
new file mode 100644
index 00000000000..87fa38d726d
--- /dev/null
+++ b/tests/gateway/test_empty_sentinel_rewrite_copy.py
@@ -0,0 +1,37 @@
+"""The gateway's ``(empty)`` sentinel rewrite reads from the same constant as the CLI explainer
+(``agent.turn_explainers.EMPTY_RESPONSE_EXPLANATION``), so a chat user and a terminal user see one
+text for "the model produced nothing after retries"."""
+
+from types import SimpleNamespace
+
+import pytest
+
+from agent.turn_explainers import EMPTY_RESPONSE_EXPLANATION
+from gateway.run_turn import GatewayTurnMixin
+
+
+class _Runner(GatewayTurnMixin):
+ def __init__(self):
+ self.async_session_store = SimpleNamespace(clear_resume_pending=self._noop)
+
+ async def _noop(self, *_a, **_k):
+ return None
+
+ async def _clear_restart_failure_count(self, *_a, **_k):
+ return None
+
+
+async def test_empty_sentinel_rewrite_uses_the_shared_explanation_with_the_model_name():
+ runner = _Runner()
+ agent_result = {"final_response": "(empty)", "model": "llama3", "messages": [], "api_calls": 2}
+ source = SimpleNamespace(chat_id="c1", platform=SimpleNamespace(value="telegram"))
+ response, silent, _messages = await runner._hmwa_shape_agent_response(
+ agent_result, source, history=[], session_entry=SimpleNamespace(session_id="s"), session_key=None,
+ _quick_key=None, run_generation=0, _run_start_session_id="s", _platform_name="telegram",
+ _msg_start_time=0.0,
+ )
+ assert silent is False
+ assert EMPTY_RESPONSE_EXPLANATION.format(model="llama3") in response
+ assert "after processing tool results" not in response
+ assert "/model" in response and "continue" in response
diff --git a/tests/gateway/test_exec_approval_timeout_notice.py b/tests/gateway/test_exec_approval_timeout_notice.py
new file mode 100644
index 00000000000..14dcb3a2af6
--- /dev/null
+++ b/tests/gateway/test_exec_approval_timeout_notice.py
@@ -0,0 +1,111 @@
+"""When a messaging-platform approval prompt times out, the chat must say so.
+
+``_await_gateway_decision`` fires ``entry.settle("timeout")`` when nobody answers within
+``approvals.timeout``; only the TUI server registered a settle hook, so on Telegram / Slack /
+WhatsApp the card kept live buttons and the user never learned the command did NOT run.
+These tests drive the real ``TurnRunner._approval_notify_sync`` with a fake adapter.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from types import SimpleNamespace
+from typing import Any, List
+
+import pytest
+
+from gateway.platforms.base import SendResult
+from tools import approval as _approval
+from tools.approval_gateway_wait import _ApprovalEntry
+
+SESSION = "agent:main:telegram:dm:1"
+APPROVAL = {"command": "rm -rf /tmp/x", "description": "recursive delete", "pattern_key": "k"}
+
+
+class _ButtonAdapter:
+ """Renders native buttons and remembers the posted card id; records edits and sends."""
+
+ typed_command_prefix = "/"
+
+ def __init__(self, *, editable: bool = True) -> None:
+ self.sends: List[str] = []
+ self.edits: List[tuple] = []
+ self._editable = editable
+
+ def pause_typing_for_chat(self, chat_id: str) -> None:
+ return None
+
+ async def send_exec_approval(self, *a: Any, **k: Any) -> SendResult:
+ return SendResult(success=True, message_id="card-1")
+
+ async def send(self, chat_id: str, message: str, **k: Any) -> SendResult:
+ self.sends.append(message)
+ return SendResult(success=True, message_id="m2")
+
+ async def edit_message(self, chat_id: str, message_id: str, content: str, **k: Any) -> SendResult:
+ self.edits.append((message_id, content))
+ return SendResult(success=self._editable, error=None if self._editable else "cannot edit")
+
+
+def _runner(adapter):
+ from gateway.run_turn_runner import TurnRunner
+
+ runner = object.__new__(TurnRunner)
+ runner._ctx = SimpleNamespace(
+ _status_adapter=adapter, _status_chat_id="C1", _status_thread_metadata={"thread_id": "t1"},
+ session_key=SESSION, source=SimpleNamespace(chat_id="C1", platform="telegram", session_key=SESSION),
+ )
+
+ class _Fut:
+ def __init__(self, result): self._r = result
+ def result(self, timeout=None): return self._r
+
+ runner._schedule = lambda coro, _label: _Fut(asyncio.run(coro))
+ runner._close_native_stream_boundary = lambda _why: None
+ return runner
+
+
+def pending_entry(monkeypatch):
+ """A queued approval entry exactly as ``_await_gateway_decision`` registers it."""
+ monkeypatch.setattr("gateway.platforms.base_exec_approval.approval_timeout_seconds", lambda: 300)
+ entry = _ApprovalEntry(dict(APPROVAL))
+ with _approval._lock:
+ _approval._gateway_queues[SESSION] = [entry]
+ yield entry
+ with _approval._lock:
+ _approval._gateway_queues.pop(SESSION, None)
+
+
+def test_timeout_edits_the_card_to_say_the_command_did_not_run(pending_entry):
+ adapter = _ButtonAdapter()
+ _runner(adapter)._approval_notify_sync(dict(pending_entry.data)) # what notify_cb receives
+
+ assert pending_entry.settle is not None, "settle hook must be registered for the request_id"
+ pending_entry.settle("timeout")
+
+ assert len(adapter.edits) == 1
+ message_id, content = adapter.edits[0]
+ assert message_id == "card-1"
+ assert "NOT run" in content and "5 minutes" in content
+ assert adapter.sends == [], "an editable card needs no extra message"
+
+
+def test_timeout_falls_back_to_a_new_message_when_the_card_cannot_be_edited(pending_entry):
+ adapter = _ButtonAdapter(editable=False)
+ _runner(adapter)._approval_notify_sync(dict(pending_entry.data)) # what notify_cb receives
+
+ pending_entry.settle("timeout")
+
+ assert len(adapter.sends) == 1
+ assert "NOT run" in adapter.sends[0]
+
+
[email protected]("reason", ["answered", "interrupted", "notify_failed"])
+def test_other_settle_reasons_post_nothing(pending_entry, reason):
+ adapter = _ButtonAdapter()
+ _runner(adapter)._approval_notify_sync(dict(pending_entry.data)) # what notify_cb receives
+
+ pending_entry.settle(reason)
+
+ assert adapter.edits == [] and adapter.sends == []
diff --git a/tests/gateway/test_failure_writer_ownership.py b/tests/gateway/test_failure_writer_ownership.py
index 51ce576323a..24a235654ae 100644
--- a/tests/gateway/test_failure_writer_ownership.py
+++ b/tests/gateway/test_failure_writer_ownership.py
@@ -155,14 +155,14 @@ def test_context_overflow_exception_persists_nothing(tmp_path):
err, MessageEvent(text="x", source=source, message_id="m-overflow"), source, entry, entry.session_key, prepared,
)
assert db.message_count() == before
- assert reply.startswith("⚠️ Session too large for the model's context window.")
+ assert "/compress" in reply and "/new" in reply
db.close()
asyncio.run(check())
def test_context_overflow_error_reply_carries_no_partial_effect_notice():
- """Overflow is a deterministic rejection (#107567); the reply must stay the /compact
+ """Overflow is a deterministic rejection (#107567); the reply must stay the /compress
guidance alone rather than inherit the indeterminate "actions may have run" warning."""
import asyncio
from gateway.config import Platform
@@ -185,8 +185,8 @@ def test_context_overflow_error_reply_carries_no_partial_effect_notice():
err, MessageEvent(text="x", source=source), source, None, "k", prepared,
))
- assert reply.startswith("⚠️ Session too large for the model's context window.")
- assert reply.endswith("or /reset to start fresh.")
+ from gateway.run import _CONTEXT_OVERFLOW_REPLY
+ assert reply == _CONTEXT_OVERFLOW_REPLY
assert runner._PARTIAL_FAILED_TURN_NOTICE not in reply
diff --git a/tests/gateway/test_gateway_shutdown.py b/tests/gateway/test_gateway_shutdown.py
index cd062ca447b..0bbd47f1ee9 100644
--- a/tests/gateway/test_gateway_shutdown.py
+++ b/tests/gateway/test_gateway_shutdown.py
@@ -243,7 +243,7 @@ async def test_in_chat_restart_skips_home_shutdown_even_with_active_session():
assert len(adapter.sent_calls) == 1
chat_id, message, metadata = adapter.sent_calls[0]
assert chat_id == source.chat_id
- assert "Gateway restarting" in message
+ assert "Hermes is restarting" in message
assert metadata["telegram_reply_to_message_id"] == "restart-command"
diff --git a/tests/gateway/test_interactive_prompt_base.py b/tests/gateway/test_interactive_prompt_base.py
index 1894dba9e8f..4bb3549a91c 100644
--- a/tests/gateway/test_interactive_prompt_base.py
+++ b/tests/gateway/test_interactive_prompt_base.py
@@ -41,15 +41,26 @@ class TestTruncatePreview:
class TestFormatExecApproval:
- def test_default_template(self):
+ def test_default_template(self, monkeypatch):
+ monkeypatch.setattr("gateway.platforms.base.approval_timeout_seconds", lambda: 300)
ad = _bare(_DefaultAdapter)
text = ad._format_exec_approval("rm -rf /", "scary")
assert text == (
- "⚠️ Command Approval Required\n\n"
+ "⚠️ Hermes wants to run a command that needs your OK\n\n"
"```\nrm -rf /\n```\n"
- "Reason: scary"
+ "Why it was flagged: scary\n\n"
+ "If you don't answer within 5 minutes it will NOT run."
)
+ def test_deadline_line_tracks_configured_timeout(self, monkeypatch):
+ """The card must say how long the user has and that silence means NO — for any timeout."""
+ monkeypatch.setattr("gateway.platforms.base.approval_timeout_seconds", lambda: 90)
+ text = _bare(_DefaultAdapter)._format_exec_approval("rm -rf /", "scary")
+ assert "within 90 seconds it will NOT run" in text
+ monkeypatch.setattr("gateway.platforms.base.approval_timeout_seconds", lambda: 7200)
+ text = _bare(_DefaultAdapter)._format_exec_approval("rm -rf /", "scary")
+ assert "within 2 hours it will NOT run" in text
+
def test_escape_hook_applied_to_command_and_reason(self):
class Escaping(_DefaultAdapter):
diff --git a/tests/gateway/test_kanban_notice_copy.py b/tests/gateway/test_kanban_notice_copy.py
new file mode 100644
index 00000000000..87ed9458b92
--- /dev/null
+++ b/tests/gateway/test_kanban_notice_copy.py
@@ -0,0 +1,38 @@
+"""Kanban terminal-event pings must say what state the task is in and name the next command.
+
+`gave_up` means the dispatcher auto-blocked the task (spawn failure, crash or timeout alike) and a
+human must act; `crashed`/`timed_out` retry on their own. Contract tests over
+`_EVENT_FORMATTERS`, never whole-string snapshots.
+"""
+
+from types import SimpleNamespace
+
+from gateway.kanban_watchers_notifier import _EVENT_FORMATTERS
+
+
+def _names(task_id="T-123"):
+ return SimpleNamespace(task_id=task_id, head=f"[board] Kanban {task_id}", title="Ship it", board_tag="[board] ")
+
+
+def _event(**payload):
+ return SimpleNamespace(payload=payload)
+
+
+def test_gave_up_says_blocked_and_names_unblock_log_reassign():
+ msg, _wake, _reason = _EVENT_FORMATTERS["gave_up"](
+ _event(failures=3, error="spawn: profile 'coder' not found"), _names())
+ assert "blocked" in msg.lower()
+ assert "3 times" in msg
+ assert "spawn: profile 'coder' not found" in msg
+ for cmd in ("hermes kanban unblock T-123", "hermes kanban log T-123", "hermes kanban reassign T-123"):
+ assert f"`{cmd}`" in msg
+ assert "spawn failures" not in msg # wrong for crash/timeout-triggered trips
+
+
+def test_crashed_and_timed_out_say_retry_and_hide_internals():
+ crashed, *_ = _EVENT_FORMATTERS["crashed"](_event(), _names())
+ timed_out, *_ = _EVENT_FORMATTERS["timed_out"](_event(limit_seconds=1800), _names())
+ for msg in (crashed, timed_out):
+ assert "retried automatically" in msg
+ assert "pid" not in msg and "max_runtime" not in msg
+ assert "30-minute" in timed_out
diff --git a/tests/gateway/test_kanban_notifier.py b/tests/gateway/test_kanban_notifier.py
index ce5683902fe..f14f9c543d3 100644
--- a/tests/gateway/test_kanban_notifier.py
+++ b/tests/gateway/test_kanban_notifier.py
@@ -326,7 +326,7 @@ def test_notifier_redelivers_same_kind_on_dispatch_cycle(tmp_path, monkeypatch):
# First crash delivered.
assert len(adapter.sent) == 1
- assert "crashed" in adapter.sent[0]["text"].lower()
+ assert "stopped unexpectedly" in adapter.sent[0]["text"].lower()
# Subscription survives — the cursor advanced past event #1, but the
# row is still there.
@@ -354,7 +354,7 @@ def test_notifier_redelivers_same_kind_on_dispatch_cycle(tmp_path, monkeypatch):
f"Second crashed event should also notify; got {len(adapter.sent)} "
f"deliveries (texts: {[d['text'] for d in adapter.sent]})"
)
- assert "crashed" in adapter.sent[1]["text"].lower()
+ assert "stopped unexpectedly" in adapter.sent[1]["text"].lower()
def test_notifier_subscription_survives_done_reopen_until_archive(
diff --git a/tests/gateway/test_local_model_connection_reply.py b/tests/gateway/test_local_model_connection_reply.py
index ae52e318a71..cf0f64f0eda 100644
--- a/tests/gateway/test_local_model_connection_reply.py
+++ b/tests/gateway/test_local_model_connection_reply.py
@@ -21,8 +21,8 @@ class TestGatewayConnectionErrorReply:
for text in samples:
assert _looks_like_gateway_provider_error(text), text
reply = _gateway_provider_error_reply(text)
- assert "not responding" in reply.lower(), text
assert "not running or is unreachable" in reply, text
+ assert "/retry" in reply, text
def test_broad_connection_phrases_still_map_once_classified(self):
"""Reply selector keeps the full phrase set; the gate does not."""
@@ -55,9 +55,17 @@ class TestGatewayConnectionErrorReply:
assert not _GATEWAY_CONNECTION_ERROR_RE.search("Provider authentication failed")
def test_auth_and_rate_limit_preserved(self):
- assert "authentication" in _gateway_provider_error_reply(
- "provider authentication failed"
- ).lower()
+ auth_reply = _gateway_provider_error_reply("provider authentication failed")
+ assert "sign-in" in auth_reply.lower() and "/login" in auth_reply
assert "rate-limiting" in _gateway_provider_error_reply(
"rate limited after 3 retries"
).lower()
+
+ def test_every_reply_names_a_slash_command_and_no_jargon(self):
+ """Each shaped reply must give the chat user something they can run; 'provider' and
+ 'gateway logs' are operator words (the log pointer is the `hermes logs` command)."""
+ from gateway.run import _PROVIDER_ERROR_REPLIES
+ replies = [reply for _, reply in _PROVIDER_ERROR_REPLIES] + [_gateway_provider_error_reply("zzz")]
+ for reply in replies:
+ assert any(cmd in reply for cmd in ("/login", "/retry", "/model")), reply
+ assert "provider" not in reply.lower(), reply
diff --git a/tests/gateway/test_normalize_empty_agent_response.py b/tests/gateway/test_normalize_empty_agent_response.py
index 46ea8416b57..9559ae21ce5 100644
--- a/tests/gateway/test_normalize_empty_agent_response.py
+++ b/tests/gateway/test_normalize_empty_agent_response.py
@@ -93,26 +93,44 @@ class TestExplicitNoneErrorIsNoneSafe:
response = _normalize_empty_agent_response(agent_result, "", history_len=10)
assert "None" not in response
- # Non-persistence generic failures may legitimately say
- # 'unknown error' — the defect is rendering the literal None.
- assert "unknown error" in response.lower()
+ # The generic failure copy names the recovery commands; the detail stays in the log.
+ assert "/retry" in response and "/new" in response
class TestGenericFailureRegression:
- """Non-persistence failures keep the existing byte-identical message."""
+ """Non-persistence failures get a plain reply that names /retry and /new; the raw exception
+ text never reaches the chat (it goes to the gateway log)."""
- def test_provider_error_still_formats_request_failed(self):
+ def test_provider_error_hides_raw_detail_and_names_retry(self):
agent_result = {
"final_response": "",
"failed": True,
- "error": "provider exploded",
+ "error": "ValueError: provider exploded {\"code\": 502}",
"api_calls": 1,
}
response = _normalize_empty_agent_response(agent_result, "", history_len=10)
- assert "The request failed: provider exploded" in response
- assert "/reset" in response
+ assert "provider exploded" not in response and "ValueError" not in response
+ assert "/retry" in response and "/new" in response
+ assert "hermes logs" in response
+
+ def test_partial_turn_hides_provider_envelope_and_names_retry(self):
+ raw = "API call failed after 3 retries: HTTP 500 internal server error"
+ agent_result = {"final_response": "", "partial": True, "error": raw, "api_calls": 2}
+
+ response = _normalize_empty_agent_response(agent_result, "", history_len=10)
+
+ assert "HTTP 500" not in response
+ assert "/retry" in response and "/compress" in response
+
+ def test_partial_turn_keeps_curated_loop_text(self):
+ curated = "Response truncated due to output length limit"
+ agent_result = {"final_response": "", "partial": True, "error": curated, "api_calls": 2}
+
+ response = _normalize_empty_agent_response(agent_result, "", history_len=10)
+
+ assert curated in response and "/retry" in response
def test_context_failure_branch_unchanged(self):
agent_result = {
@@ -124,8 +142,8 @@ class TestGenericFailureRegression:
response = _normalize_empty_agent_response(agent_result, "", history_len=60)
- assert "context window" in response
- assert "/compact" in response
+ assert "too long" in response
+ assert "/compress" in response and "/new" in response
class TestNonempty400EnvelopeOverflowReply:
@@ -142,8 +160,8 @@ class TestNonempty400EnvelopeOverflowReply:
response = _normalize_empty_agent_response(
self._failed(self._ENVELOPE), self._ENVELOPE, history_len=138,
)
- assert "context window" in response.lower()
- assert "/compact" in response
+ assert "too long" in response.lower()
+ assert "/compress" in response
assert self._ENVELOPE not in response
@pytest.mark.parametrize("text", [
diff --git a/tests/gateway/test_restart_notification.py b/tests/gateway/test_restart_notification.py
index e3fd7693982..1b81cb41883 100644
--- a/tests/gateway/test_restart_notification.py
+++ b/tests/gateway/test_restart_notification.py
@@ -385,11 +385,11 @@ async def test_shutdown_notifications_use_cached_live_thread_source_when_origin_
await runner._notify_active_sessions_of_shutdown()
- adapter.send.assert_awaited_once_with(
- "parent-42",
- "⚠️ Gateway shutting down — Your current task will be interrupted.",
- metadata={"thread_id": "topic-7"},
- )
+ adapter.send.assert_awaited_once()
+ chat_id, message = adapter.send.await_args.args
+ assert chat_id == "parent-42"
+ assert "shutting down" in message and "send any message" in message.lower()
+ assert adapter.send.await_args.kwargs == {"metadata": {"thread_id": "topic-7"}}
@pytest.mark.asyncio
diff --git a/tests/gateway/test_restart_resume_pending.py b/tests/gateway/test_restart_resume_pending.py
index 89ee4705cd8..b3211780b62 100644
--- a/tests/gateway/test_restart_resume_pending.py
+++ b/tests/gateway/test_restart_resume_pending.py
@@ -875,10 +875,8 @@ async def test_restart_notifies_home_channel_even_without_active_sessions():
await runner._notify_active_sessions_of_shutdown()
- assert adapter.sent == [
- "⚠️ Gateway restarting — Your current task will be interrupted. "
- "Send any message after restart and I'll try to resume where you left off."
- ]
+ assert len(adapter.sent) == 1
+ assert "restarting" in adapter.sent[0] and "Send any message" in adapter.sent[0]
@pytest.mark.asyncio
diff --git a/tests/gateway/test_run_progress_interrupt.py b/tests/gateway/test_run_progress_interrupt.py
index 94c8e5ef859..30fa2d51ca5 100644
--- a/tests/gateway/test_run_progress_interrupt.py
+++ b/tests/gateway/test_run_progress_interrupt.py
@@ -211,7 +211,7 @@ async def test_partial_empty_agent_response_is_normalized(monkeypatch, tmp_path)
monkeypatch, tmp_path, PartialTruncationAgent, "sess-partial-empty"
)
- assert result["final_response"].startswith("⚠️ Processing stopped:")
+ assert result["final_response"].startswith("⚠️ I had to stop before finishing")
assert "Response truncated due to output length limit" in result["final_response"]
assert result["final_response"] != "⚠️ Response truncated due to output length limit"
assert result["partial"] is True
@@ -249,3 +249,25 @@ async def test_progress_suppressed_when_agent_is_interrupted(monkeypatch, tmp_pa
f"event '{leaked_query}' leaked into the UI after interrupt — "
f"progress_callback / drain loop is not checking is_interrupted"
)
+
+
+def test_partial_site_code_result_is_delivered_verbatim_not_double_wrapped():
+ """A truncated-tool-call exit already carries the curated site copy; the gateway must not
+ prefix it with 'I had to stop before finishing:' and cut it at 200 chars."""
+ from agent.turn_failure_copy import site_copy
+ from gateway.run import _normalize_empty_agent_response
+ curated = site_copy("truncated")
+ result = {"final_response": None, "messages": [], "api_calls": 2, "completed": False, "partial": True,
+ "error": curated, "failure_reason": "truncated", "failure_retryable": True}
+ text = _normalize_empty_agent_response(result, "", history_len=0)
+ assert curated in text
+ assert "I had to stop before finishing" not in text
+ assert text.count("continue") == curated.count("continue")
+
+
+def test_partial_without_site_code_keeps_the_generic_wrapper():
+ from gateway.run import _normalize_empty_agent_response
+ result = {"final_response": None, "messages": [], "api_calls": 2, "completed": False, "partial": True,
+ "error": "Response truncated due to output length limit"}
+ text = _normalize_empty_agent_response(result, "", history_len=0)
+ assert text.startswith("⚠️ I had to stop before finishing")
diff --git a/tests/gateway/test_run_progress_topics.py b/tests/gateway/test_run_progress_topics.py
index 9e6846529a3..4a79ef4bc5b 100644
--- a/tests/gateway/test_run_progress_topics.py
+++ b/tests/gateway/test_run_progress_topics.py
@@ -1538,7 +1538,9 @@ async def test_run_agent_sends_normalized_failure_before_queued_followup(
sent_texts = [call["content"] for call in adapter.sent]
assert QueuedFailedEmptyAgent.calls == 2
assert result["final_response"] == "follow-up processed"
- assert any("The request failed: provider exploded" in text for text in sent_texts)
+ # Sanitized failure copy (raw "provider exploded" stays in the log), then the queued follow-up.
+ assert any("couldn't finish this reply" in text and "/retry" in text for text in sent_texts)
+ assert not any("provider exploded" in text for text in sent_texts)
@pytest.mark.asyncio
diff --git a/tests/gateway/test_session_hygiene.py b/tests/gateway/test_session_hygiene.py
index 8128e5c56ab..bbe7d357521 100644
--- a/tests/gateway/test_session_hygiene.py
+++ b/tests/gateway/test_session_hygiene.py
@@ -150,20 +150,19 @@ class TestSessionHygieneThresholds:
assert approx_tokens < huge_model_threshold
-def test_hygiene_total_ceiling_warning_reports_elapsed_and_progress():
[email protected]("total_exhausted", [True, False])
+def test_hygiene_timeout_warning_names_chat_commands_not_config(total_exhausted):
+ """The chat user cannot edit model config or read second counts; the notice names the
+ slash commands they can run and keeps the timing detail in the log."""
from gateway.run import _hygiene_compression_timeout_message
warning = _hygiene_compression_timeout_message(
- total_exhausted=True,
- elapsed=600.4,
- idle_timeout=30.0,
- progress_observed=True,
+ total_exhausted=total_exhausted, elapsed=600.4, idle_timeout=30.0, progress_observed=True,
)
- assert "total ceiling after 600.4s" in warning
- assert "summary output was observed" in warning
- assert "30.0s" not in warning
- assert "no output" not in warning
+ assert "/compress" in warning and "/new" in warning
+ assert "600.4" not in warning and "30.0" not in warning
+ assert "auxiliary" not in warning and "/reset" not in warning
class TestSessionHygieneWarnThreshold:
@@ -631,7 +630,7 @@ async def test_session_hygiene_timeout_continues_to_agent_and_sets_cooldown(monk
_cd_args = fake_db.record_compression_failure_cooldown.call_args[0]
assert _cd_args[0] == "sess-timeout"
assert _cd_args[1] > time.time()
- timeout_warnings = [s for s in adapter.sent if "Context compression timed out" in s["content"]]
+ timeout_warnings = [s for s in adapter.sent if "took too long" in s["content"]]
assert len(timeout_warnings) == 1
fake_db.archive_and_compact.assert_not_called()
assert lease_released.is_set()
@@ -808,8 +807,9 @@ async def test_session_hygiene_turn_hold_budget_abandons_streaming_wait(
# Behavior witness 1: turn-hold expiry must NOT stamp the idle-timeout
# provenance or send the "no output" user message.
sent_contents = [m["content"] for m in adapter.sent]
+ # The idle-timeout copy is the only one that adds the `hermes doctor` pointer.
assert not any(
- "timed out" in c.lower() and "no output" in c.lower()
+ "took too long" in c.lower() and "hermes doctor" in c.lower()
for c in sent_contents
), f"turn-hold must not send idle-timeout message, got: {sent_contents}"
assert any(
@@ -843,7 +843,7 @@ async def test_session_hygiene_turn_hold_budget_abandons_streaming_wait(
# timeout, not a turn-hold deferral. The turn-hold path must use a
# distinct provenance stamp.
# (Verified indirectly: the idle-timeout path would have sent the
- # "no output" message, which we already asserted absent above.)
+ # idle-timeout message, which we already asserted absent above.)
@pytest.mark.asyncio
@@ -975,12 +975,12 @@ async def test_session_hygiene_idle_timeout_still_takes_failure_path(
assert worker_started.is_set()
assert runner._run_agent.await_count == 1
- # Behavior witness: idle timeout MUST send the "no output" message.
+ # Behavior witness: idle timeout MUST send the idle-timeout message (with the `hermes doctor` pointer).
sent_contents = [m["content"] for m in adapter.sent]
assert any(
- "timed out" in c.lower() and "no output" in c.lower()
+ "took too long" in c.lower() and "hermes doctor" in c.lower()
for c in sent_contents
- ), f"idle timeout must send 'no output' message, got: {sent_contents}"
+ ), f"idle timeout must send the took-too-long + hermes doctor message, got: {sent_contents}"
# Behavior witness: idle timeout MUST advance the failure cooldown.
# The gateway calls _hygiene_cooldown_for_failure + _record_hygiene_cooldown.
@@ -1614,7 +1614,7 @@ async def test_hygiene_fence_cancel_records_cooldown_without_abort_flag(
f"got {state!r}"
)
assert not any(
- "Context compression aborted" in s["content"] for s in adapter1.sent
+ "Shortening the conversation history failed" in s["content"] for s in adapter1.sent
), "fence-cancel during /stop or /restart must not toast an abort"
class ShouldNotRunAgent:
@@ -1713,7 +1713,7 @@ async def test_hygiene_does_not_wait_ceiling_after_fence_cancel(
state = db.get_compression_failure_cooldown(session_id)
assert state is not None and state["remaining_seconds"] > 0
assert not any(
- "Context compression timed out" in s["content"] for s in adapter.sent
+ "took too long" in s["content"] for s in adapter.sent
), "fence-cancel is not a summary-model timeout; no timeout toast"
release_worker.set()
await asyncio.wait_for(asyncio.to_thread(cleanup_done.wait), timeout=2)
diff --git a/tests/gateway/test_session_stall_watchdog.py b/tests/gateway/test_session_stall_watchdog.py
index 8336212a709..2a49893a465 100644
--- a/tests/gateway/test_session_stall_watchdog.py
+++ b/tests/gateway/test_session_stall_watchdog.py
@@ -119,9 +119,10 @@ def test_should_clear_holds_latch_when_idle_unknown():
def test_format_session_stall_notification_minutes():
msg = format_session_stall_notification(125)
- assert "2 min ago" in msg
- assert "/new" in msg
- assert format_session_stall_notification(30).count("1 min ago") == 1
+ assert "2 min" in msg
+ # /stop (cancel the task) is offered before /new (discards the conversation).
+ assert "/stop" in msg and "/new" in msg and msg.index("/stop") < msg.index("/new")
+ assert format_session_stall_notification(30).count("1 min") == 1
def test_resolve_idle_uses_shared_activity_snapshot_only():
diff --git a/tests/gateway/test_subagent_failure_notice.py b/tests/gateway/test_subagent_failure_notice.py
index a713f93c0ae..4938ef8fe8c 100644
--- a/tests/gateway/test_subagent_failure_notice.py
+++ b/tests/gateway/test_subagent_failure_notice.py
@@ -65,7 +65,8 @@ class TestFormatSubagentFailureLine:
assert line.startswith("⚠️ Subagent failed")
assert '"research competitor pricing"' in line
assert "404" in line
- assert "(after 12s)" in line
+ assert "after 12s" in line
+ assert "/agents" in line
def test_timeout_verb(self):
line = format_subagent_failure_line("do a thing", "timeout")
@@ -78,7 +79,8 @@ class TestFormatSubagentFailureLine:
def test_no_goal_no_error(self):
line = format_subagent_failure_line(None, "error")
- assert line == "⚠️ Subagent failed"
+ assert line.startswith("⚠️ Subagent failed. ")
+ assert '"' not in line # no empty goal quotes
def test_multiline_goal_flattened(self):
line = format_subagent_failure_line("a\nb", "failed")
@@ -129,8 +131,13 @@ class TestGatewayFailureNotice:
)
assert len(captured) == 1
assert "Subagent" in captured[0]
- assert "404" in captured[0]
assert '"scan the repo"' in captured[0]
+ if status == "timeout":
+ # A timeout's error text is scheduler boilerplate; the notice says the outcome and the knob.
+ assert "timed out" in captured[0]
+ assert "delegation.child_timeout_seconds" in captured[0]
+ else:
+ assert "404" in captured[0]
@pytest.mark.parametrize("status", ["completed", "interrupted", None])
def test_non_failure_statuses_stay_silent(self, monkeypatch, status):
diff --git a/tests/gateway/test_telegram_approval_buttons.py b/tests/gateway/test_telegram_approval_buttons.py
index c9dcf38edd4..980675cd6a8 100644
--- a/tests/gateway/test_telegram_approval_buttons.py
+++ b/tests/gateway/test_telegram_approval_buttons.py
@@ -8,6 +8,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from gateway.platforms.base import unauthorized_action_notice
+
# ---------------------------------------------------------------------------
# Ensure the repo root is importable
# ---------------------------------------------------------------------------
@@ -293,7 +295,7 @@ class TestTelegramApprovalCallback:
await adapter._handle_callback_query(update, context)
query.answer.assert_called_once()
- assert "not authorized" in query.answer.call_args[1]["text"].lower()
+ assert query.answer.call_args[1]["text"] == unauthorized_action_notice("telegram")
query.edit_message_text.assert_not_called()
assert not (tmp_path / ".update_response").exists()
@@ -323,7 +325,7 @@ class TestTelegramApprovalCallback:
await adapter._handle_callback_query(update, context)
query.answer.assert_called_once()
- assert "not authorized" in query.answer.call_args[1]["text"].lower()
+ assert query.answer.call_args[1]["text"] == unauthorized_action_notice("telegram")
query.edit_message_text.assert_not_called()
assert not (tmp_path / ".update_response").exists()
assert runner.last_source is not None
diff --git a/tests/gateway/test_telegram_clarify_buttons.py b/tests/gateway/test_telegram_clarify_buttons.py
index a8a02f07659..0b1ec990e2c 100644
--- a/tests/gateway/test_telegram_clarify_buttons.py
+++ b/tests/gateway/test_telegram_clarify_buttons.py
@@ -11,6 +11,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from gateway.platforms.base import unauthorized_action_notice
+
# ---------------------------------------------------------------------------
# Ensure the repo root is importable
# ---------------------------------------------------------------------------
@@ -205,7 +207,7 @@ class TestTelegramClarifyCallback:
assert entry is not None
assert not entry.event.is_set()
query.answer.assert_called_once()
- assert "not authorized" in query.answer.call_args[1]["text"].lower()
+ assert query.answer.call_args[1]["text"] == unauthorized_action_notice("telegram")
# State preserved
assert adapter._clarify_state["cidC"] == "sk-auth"
diff --git a/tests/gateway/test_telegram_noise_filter.py b/tests/gateway/test_telegram_noise_filter.py
index b46613e2756..bb453783a68 100644
--- a/tests/gateway/test_telegram_noise_filter.py
+++ b/tests/gateway/test_telegram_noise_filter.py
@@ -195,8 +195,8 @@ def test_chat_gateways_redact_secret_in_provider_error(platform):
assert "sk-ABCDEF0123456789abcdef0123" not in sanitized
assert "sk-ABCDEF" not in sanitized
assert "HTTP 401" not in sanitized
- # The user gets the safe provider-error category instead of the raw body.
- assert "provider" in sanitized.lower()
+ # The user gets the safe error category and a command to run instead of the raw body.
+ assert "sign-in" in sanitized.lower() and "/login" in sanitized
@pytest.mark.parametrize("platform", ["slack", "matrix"])
@@ -263,7 +263,7 @@ def test_telegram_status_sanitizes_raw_provider_security_errors():
sanitized = _prepare_gateway_status_message(Platform.TELEGRAM, "lifecycle", raw)
assert sanitized is not None
- assert "provider rejected" in sanitized.lower()
+ assert "rejected this request" in sanitized.lower()
assert "cybersecurity risk" not in sanitized.lower()
assert "HTTP 400" not in sanitized
assert "req_123" not in sanitized
@@ -278,7 +278,7 @@ def test_telegram_final_response_sanitizes_raw_provider_errors():
sanitized = _sanitize_gateway_final_response(Platform.TELEGRAM, raw)
- assert "provider rejected" in sanitized.lower()
+ assert "rejected this request" in sanitized.lower()
assert "cybersecurity risk" not in sanitized.lower()
assert "HTTP 400" not in sanitized
assert "req_abc" not in sanitized
@@ -293,8 +293,8 @@ def test_telegram_final_response_redacts_auth_secrets():
sanitized = _sanitize_gateway_final_response(Platform.TELEGRAM, raw)
- assert "authentication failed" in sanitized.lower()
- assert "check the configured credentials" in sanitized.lower()
+ assert "sign-in" in sanitized.lower()
+ assert "/login" in sanitized
assert "sk-live" not in sanitized
diff --git a/tests/gateway/test_transcript_read_failure.py b/tests/gateway/test_transcript_read_failure.py
index a74211da9f3..981c8600ce9 100644
--- a/tests/gateway/test_transcript_read_failure.py
+++ b/tests/gateway/test_transcript_read_failure.py
@@ -86,8 +86,10 @@ class TestSlashCommandsOnUnreadableTranscript:
def test_history_unreadable_text_is_explicit(self):
from gateway.slash_commands_status import HISTORY_UNREADABLE
- assert "unreadable" in HISTORY_UNREADABLE
- assert "not a new conversation" in HISTORY_UNREADABLE
+ # Says the history exists (not a fresh chat), avoids the internal file name, and names a fix.
+ assert "earlier messages exist" in HISTORY_UNREADABLE
+ assert "state.db" not in HISTORY_UNREADABLE
+ assert "hermes doctor --fix" in HISTORY_UNREADABLE and "/new" in HISTORY_UNREADABLE
@pytest.mark.asyncio
async def test_btw_replies_history_unreadable_on_read_failure(self):
diff --git a/tests/gateway/test_unauthorized_sender_notices.py b/tests/gateway/test_unauthorized_sender_notices.py
new file mode 100644
index 00000000000..df8d8cb09b9
--- /dev/null
+++ b/tests/gateway/test_unauthorized_sender_notices.py
@@ -0,0 +1,78 @@
+"""Unauthorized-sender copy: the pairing DM tells a stranger what happens next, and an ignored DM
+(allowlist configured) stays silent toward the stranger while the owner gets the approve command in
+the log and, once, in the home channel."""
+
+import logging
+
+import pytest
+
+from gateway.config import HomeChannel, Platform
+from gateway.pairing import PairingStore
+from gateway.run import GatewayRunner
+from gateway.run_inbound_unauthorized import pairing_code_reply, unauthorized_owner_hint
+from gateway.session import SessionSource
+from tests.gateway.restart_test_helpers import make_restart_runner
+
+
+def test_pairing_reply_states_expiry_owner_path_and_resend():
+ reply = pairing_code_reply("telegram", "ABCD1234", "")
+ assert "valid for 1 hour" in reply
+ assert "`hermes pairing approve telegram ABCD1234`" in reply
+ assert "send your message again" in reply
+ assert "~" not in reply
+
+
+def test_pairing_reply_pins_profile_in_approve_command():
+ reply = pairing_code_reply("discord", "ZZZZ9999", "-p work ")
+ assert "`hermes -p work pairing approve discord ZZZZ9999`" in reply
+
+
+def test_owner_hint_names_sender_allowlist_and_pairing_switch():
+ hint = unauthorized_owner_hint("telegram", "4242", "Ada", hermes_home="~/.hermes")
+ assert "Ada (4242)" in hint
+ assert "TELEGRAM_ALLOWED_USERS" in hint and "~/.hermes/.env" in hint
+ assert "unauthorized_dm_behavior: pair" in hint
+ assert "hermes pairing approve telegram" in hint
+
+
+async def test_ignored_dm_sends_nothing_to_stranger_and_notifies_owner_once(tmp_path, monkeypatch, caplog):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ runner, adapter = make_restart_runner()
+ runner.pairing_store = PairingStore()
+ runner.pairing_stores = {}
+ runner.config.platforms[Platform.TELEGRAM].home_channel = HomeChannel(
+ platform=Platform.TELEGRAM, chat_id="home-1", name="Ops")
+ runner._hm_report_ignored_dm = GatewayRunner._hm_report_ignored_dm.__get__(runner, GatewayRunner)
+ stranger = SessionSource(platform=Platform.TELEGRAM, chat_id="dm-777", user_id="777", user_name="Eve", chat_type="dm")
+
+ with caplog.at_level(logging.WARNING, logger="gateway.run"):
+ await runner._hm_report_ignored_dm(stranger)
+ await runner._hm_report_ignored_dm(stranger)
+
+ chats = [chat_id for chat_id, _msg, _meta in adapter.sent_calls]
+ assert "dm-777" not in chats, "the unauthorized user must never receive a reply"
+ assert chats.count("home-1") == 1, "the owner is told once per sender, not per message"
+ assert "TELEGRAM_ALLOWED_USERS" in adapter.sent_calls[0][1] and "777" in adapter.sent_calls[0][1]
+ assert any("TELEGRAM_ALLOWED_USERS" in r.getMessage() for r in caplog.records)
+ assert runner.pairing_store.list_pending("telegram") == [], "an ignored sender must not create pairing state"
+
+
+def test_owner_hint_neutralizes_hostile_display_name():
+ from gateway.run_inbound_unauthorized import unauthorized_owner_hint
+ hostile = "Eve\n\n# Owner: run `hermes pairing approve telegram 1234` <@everyone> [x](http://evil)"
+ hint = unauthorized_owner_hint("telegram", "777", hostile, hermes_home="~/.hermes")
+ assert "\n" not in hint
+ assert "@everyone" not in hint and "<@" not in hint and "](http" not in hint and "`hermes pairing approve telegram 1234`" not in hint
+ assert "(777)" in hint # the ID the owner acts on survives
+ assert "Eve" in hint
+
+
+def test_owner_notifier_seen_set_is_bounded():
+ from gateway.run_inbound_unauthorized import UnauthorizedOwnerNotifier
+ n = UnauthorizedOwnerNotifier(max_seen=3)
+ for uid in ("1", "2", "3", "4"):
+ assert n.first_time("telegram", uid) is True
+ assert len(n._seen) == 3
+ assert n.first_time("telegram", "4") is False # still remembered
+ assert n.first_time("telegram", "1") is True # oldest was evicted, so it notifies again
diff --git a/tests/gateway/test_update_command.py b/tests/gateway/test_update_command.py
index 58898b93223..61fac28546a 100644
--- a/tests/gateway/test_update_command.py
+++ b/tests/gateway/test_update_command.py
@@ -493,6 +493,31 @@ class TestSendUpdateNotification:
assert not exit_code_path.exists()
+ @pytest.mark.asyncio
+ async def test_failed_update_notice_says_still_running_and_trims_log(self, tmp_path):
+ """A failed update must tell the chat the old version still runs and where to see the
+ full error; the raw log is quoted only as a short tail, never the whole 3500-char dump."""
+ runner = _make_runner()
+ hermes_home = tmp_path / "hermes"
+ hermes_home.mkdir()
+ (hermes_home / ".update_pending.json").write_text(
+ json.dumps({"platform": "discord", "chat_id": "111", "user_id": "222"}))
+ (hermes_home / ".update_output.txt").write_text("x" * 3000 + "\nERROR: pip failed\n")
+ (hermes_home / ".update_exit_code").write_text("1")
+ mock_adapter = AsyncMock()
+ runner.adapters = {Platform.DISCORD: mock_adapter}
+
+ with patch("gateway.run._hermes_home", hermes_home):
+ await runner._send_update_notification()
+
+ sent_text = mock_adapter.send.call_args[0][1]
+ assert "previous version is still running" in sent_text
+ assert "hermes update" in sent_text and "/update" in sent_text
+ assert "ERROR: pip failed" in sent_text
+ assert len(sent_text) < 1200
+ assert "exit code" not in sent_text.lower()
+
+
# ---------------------------------------------------------------------------
# /update in help and known_commands
# ---------------------------------------------------------------------------
diff --git a/tests/hermes_cli/test_api_key_providers.py b/tests/hermes_cli/test_api_key_providers.py
index 1dd8abb4ddc..eb227457c87 100644
--- a/tests/hermes_cli/test_api_key_providers.py
+++ b/tests/hermes_cli/test_api_key_providers.py
@@ -306,7 +306,7 @@ class TestResolveProvider:
lambda env=None: False,
)
monkeypatch.setenv("GITHUB_TOKEN", "gh-test-token")
- with pytest.raises(AuthError, match="No inference provider configured"):
+ with pytest.raises(AuthError, match="not connected to any AI provider"):
resolve_provider("auto")
diff --git a/tests/hermes_cli/test_auth_pool_operations.py b/tests/hermes_cli/test_auth_pool_operations.py
index d717718688b..d9b786d27ba 100644
--- a/tests/hermes_cli/test_auth_pool_operations.py
+++ b/tests/hermes_cli/test_auth_pool_operations.py
@@ -60,7 +60,7 @@ def test_refresh_uses_target_grant_and_preserves_sibling(monkeypatch, status):
if status == 200:
auth_commands.auth_refresh_command(args)
else:
- with pytest.raises(SystemExit, match="Refresh failed"):
+ with pytest.raises(SystemExit, match="Could not renew"):
auth_commands.auth_refresh_command(args)
after = {e["id"]: e for e in read_credential_pool("openai-codex")}
assert requests == [{"grant_type": ["refresh_token"], "refresh_token": ["fixture-refresh-1"],
diff --git a/tests/hermes_cli/test_cli_command_messages.py b/tests/hermes_cli/test_cli_command_messages.py
new file mode 100644
index 00000000000..e9d67dbd0d9
--- /dev/null
+++ b/tests/hermes_cli/test_cli_command_messages.py
@@ -0,0 +1,154 @@
+"""User-facing message contracts for `hermes skills/plugins/mcp/cron/doctor` failure paths.
+
+Every failure line must say what happened and name an existing command to type next; none may
+lead with a raw exception, a status literal, or a hardcoded ``~/.hermes`` path (UX message audit,
+findings cli-08/20/21/23/26/34, tools-runtime-13/14/20/27).
+"""
+
+from __future__ import annotations
+
+import io
+import re
+from types import SimpleNamespace
+
+from rich.console import Console
+
+
+def _console():
+ buf = io.StringIO()
+ return Console(file=buf, force_terminal=False, width=200, highlight=False, markup=True), buf
+
+
+# ── skills hub ────────────────────────────────────────────────────────────────────────────────
+
+def test_skill_fetch_failure_names_search_and_doctor():
+ from hermes_cli.skills_hub import _print_fetch_failure
+ c, buf = _console()
+ _print_fetch_failure(c, sources=[], identifier="someone/typo-skill")
+ out = buf.getvalue()
+ assert "hermes skills search typo-skill" in out
+ assert "hermes doctor" in out
+ assert "from any source" not in out
+
+
+def test_scan_block_message_explains_force_and_points_at_inspect():
+ from hermes_cli.skills_hub import _scan_block_message
+ result = SimpleNamespace(verdict="dangerous", trust_level="community", findings=[1, 2, 3])
+ msg = _scan_block_message(result, "acme/evil-skill")
+ assert "3 high-risk pattern(s)" in msg
+ assert "even with --force" in msg
+ assert "hermes skills inspect acme/evil-skill" in msg
+ assert "verdict" not in msg # scanner jargon stays in the audit log
+
+ soft = _scan_block_message(SimpleNamespace(verdict="suspicious", trust_level="community", findings=[1]),
+ "acme/meh")
+ assert "Re-run with --force" in soft
+
+
+# ── plugins ───────────────────────────────────────────────────────────────────────────────────
+
+def test_plugin_clone_failure_leads_with_next_steps_and_escapes_git_output():
+ from hermes_cli.plugins_cmd import _clone_failure_message
+ msg = _clone_failure_message("https://github.com/acme/nope", "fatal: repository '[x]' not found")
+ assert msg.startswith("Could not download the plugin from https://github.com/acme/nope")
+ assert "hermes plugins search" in msg and "gh auth login" in msg
+ assert "Details:" in msg
+ assert "\\[x]" in msg # Rich markup escaped so the raw git text renders verbatim
+
+
+def test_unknown_plugin_message_points_at_list_and_full_key_rule():
+ from hermes_cli.plugins_cmd import _unknown_plugin_message
+ msg = _unknown_plugin_message("firecrawl")
+ assert "No plugin named 'firecrawl'" in msg
+ assert "hermes plugins list" in msg and "web/firecrawl" in msg and "hermes plugins install" in msg
+ assert "(none)" not in msg
+
+
+# ── MCP ───────────────────────────────────────────────────────────────────────────────────────
+
+def test_banner_failed_mcp_line_shows_reason_and_command():
+ from hermes_cli.banner import _mcp_server_line
+ line = _mcp_server_line({"name": "gh", "transport": "stdio", "connected": False, "status": "failed",
+ "error": "missing executable 'npx' (ensure Node.js is installed)"}, dim="grey", text="white")
+ assert "could not connect" in line and "missing executable 'npx'" in line
+ assert "hermes mcp test gh" in line
+
+ auth = _mcp_server_line({"name": "linear", "transport": "http", "connected": False, "status": "failed",
+ "error": "Client error '401 Unauthorized' for url"}, dim="grey", text="white")
+ assert "hermes mcp login linear" in auth
+
+
+def test_mcp_probe_failure_unwraps_group_and_points_at_login_for_401():
+ from hermes_cli.mcp_config import _probe_failure_next_step, _probe_failure_reason
+
+ class _Resp:
+ status_code = 401
+
+ class _HttpErr(Exception):
+ response = _Resp()
+
+ group = ExceptionGroup("unhandled errors in a TaskGroup", [_HttpErr("Client error '401 Unauthorized'")])
+ assert "ExceptionGroup" not in _probe_failure_reason(group)
+ assert "401" in _probe_failure_reason(group)
+ assert "hermes mcp login linear" in _probe_failure_next_step("linear", group)
+
+ missing = FileNotFoundError(2, "No such file or directory", "npx")
+ assert "config.yaml" in _probe_failure_next_step("gh", missing)
+ assert "~/.hermes" not in _probe_failure_next_step("gh", missing) or "profiles" in _probe_failure_next_step("gh", missing)
+
+
+# ── cron ──────────────────────────────────────────────────────────────────────────────────────
+
+def test_cron_delivery_failure_lines_have_no_status_literals_and_name_the_fix():
+ from hermes_cli.cron import _cron_doctor_issues_for_job, _job_warnings, _last_run_display
+ job = {"id": "job42", "last_status": "delivery_failed", "last_error": None,
+ "last_delivery_error": "telegram: 502 Bad Gateway\nsecond raw line", "enabled": False,
+ "last_fire_error": {"at": "2026-09-01T07:00:00+00:00",
+ "detail": "scheduled fire could not be forwarded to the gateway api_server"}}
+ texts = [_last_run_display(job), *_job_warnings(job), *_cron_doctor_issues_for_job(job)]
+ joined = "\n".join(texts)
+ assert "delivery_failed" not in joined and "delivery_queued" not in joined
+ assert "second raw line" not in joined # only the first line of the raw blob is shown
+ assert "hermes cron edit job42 --deliver" in joined
+ assert "hermes gateway restart" in joined and "hermes cron run job42" in joined
+ assert "gateway was unreachable" in joined
+
+
+def test_cron_queued_status_reads_as_in_progress():
+ from hermes_cli.cron import _last_run_display
+ assert "in progress" in _last_run_display({"last_status": "delivery_queued"})
+
+
+# ── doctor / advisories / paths ───────────────────────────────────────────────────────────────
+
+def test_advisory_remediation_uses_active_hermes_home(monkeypatch, tmp_path):
+ from hermes_cli import security_advisories as sa
+ monkeypatch.setattr(sa, "display_hermes_home", lambda: "~/.hermes/profiles/work")
+ hit = SimpleNamespace(advisory=sa.ADVISORIES[0], package="mistralai", installed_version="2.4.6")
+ text = "\n".join(sa.full_remediation_text(hit))
+ assert "~/.hermes/profiles/work/.env" in text
+ assert "{hermes_home}" not in text
+ assert not re.search(r"~/\.hermes/\.env", text)
+
+
+def test_doctor_ack_failure_names_config_path_and_retry(monkeypatch, capsys):
+ import hermes_cli.doctor as doctor
+ monkeypatch.setattr("hermes_cli.security_advisories.ack_advisory", lambda _id: False)
+ monkeypatch.setattr(doctor, "_DHH", "~/.hermes/profiles/work")
+ from hermes_cli.security_advisories import ADVISORIES
+ try:
+ doctor._ack_advisory(ADVISORIES[0].id)
+ except SystemExit as exc:
+ assert exc.code == 1
+ out = capsys.readouterr().out
+ assert "~/.hermes/profiles/work/config.yaml" in out
+ assert "hermes config path" in out and f"hermes doctor --ack {ADVISORIES[0].id}" in out
+ assert "Failed to persist" not in out
+
+
+def test_backup_recovery_hint_cites_the_slash_command_not_a_fake_subcommand():
+ from hermes_cli.backup import _snapshot_recovery_hint
+ hint = _snapshot_recovery_hint()
+ assert "/snapshot list" in hint and "/snapshot restore" in hint
+ assert "hermes snapshot" not in hint # `hermes snapshot` is not a CLI subcommand
+ assert "CLI only" in hint # /snapshot is cli_only; Desktop/gateway readers must not go looking for it
diff --git a/tests/hermes_cli/test_computer_use_cli.py b/tests/hermes_cli/test_computer_use_cli.py
index a3e17aade14..756a26df268 100644
--- a/tests/hermes_cli/test_computer_use_cli.py
+++ b/tests/hermes_cli/test_computer_use_cli.py
@@ -46,7 +46,8 @@ def test_computer_use_rejects_removed_browser_approve_command() -> None:
result = _run("browser-approve", "--pid", "123")
assert result.returncode == 2
- assert "invalid choice: 'browser-approve'" in result.stderr
+ assert "'browser-approve' is not a `hermes computer-use` command" in result.stderr
+ assert "choose from" not in result.stderr
def test_computer_use_status_returns_zero_for_compatible_driver(
diff --git a/tests/hermes_cli/test_config.py b/tests/hermes_cli/test_config.py
index 8dc3ea42743..ff1a137163c 100644
--- a/tests/hermes_cli/test_config.py
+++ b/tests/hermes_cli/test_config.py
@@ -226,7 +226,7 @@ class TestLoadConfigParseFailure:
assert after["approvals"]["deny"] == ["curl*evil.com*"]
# Warning says we kept the previous config, not defaults
err = capsys.readouterr().err
- assert "previously loaded config" in err
+ assert "settings it loaded before the edit" in err
@@ -294,7 +294,7 @@ class TestSaveAndLoadRoundtrip:
with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):
with patch("builtins.open", side_effect=self._deny_config_reads(config_path)):
- with pytest.raises(RuntimeError, match="Refusing to overwrite"):
+ with pytest.raises(RuntimeError, match="this change was not saved"):
save_config({"model": "test/replacement"})
assert config_path.read_text(encoding="utf-8") == original
@@ -327,7 +327,7 @@ class TestSaveAndLoadRoundtrip:
config_path.write_text(original, encoding="utf-8")
with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):
- with pytest.raises(RuntimeError, match="not valid YAML"):
+ with pytest.raises(RuntimeError, match="formatting error"):
set_config_value("model.default", "gpt-4o")
assert config_path.read_text(encoding="utf-8") == original
@@ -343,7 +343,7 @@ class TestSaveAndLoadRoundtrip:
(tmp_path / ".env").write_text("TERMINAL_TIMEOUT=30\n", encoding="utf-8")
with patch.dict(os.environ, {"HERMES_HOME": str(tmp_path)}):
- with pytest.raises(RuntimeError, match="not valid YAML"):
+ with pytest.raises(RuntimeError, match="formatting error"):
unset_config_value("terminal.timeout")
assert config_path.read_text(encoding="utf-8") == original
@@ -399,7 +399,7 @@ class TestSaveAndLoadRoundtrip:
original = "broken: [unterminated\n"
config_path.write_text(original, encoding="utf-8")
- with pytest.raises(RuntimeError, match="not valid YAML"):
+ with pytest.raises(RuntimeError, match="formatting error"):
atomic_config_write(config_path, {"model": {"provider": "openai"}})
assert config_path.read_text(encoding="utf-8") == original
@@ -1908,7 +1908,7 @@ class TestConfigCommandFailClosedSurface:
assert excinfo.value.code == 1
err = capsys.readouterr().err
- assert "not valid YAML" in err
+ assert "formatting error" in err and "`hermes config edit`" in err
assert config_path.read_text(encoding="utf-8") == original
def test_config_command_unset_exits_cleanly_on_broken_yaml(self, tmp_path, capsys):
@@ -1923,7 +1923,7 @@ class TestConfigCommandFailClosedSurface:
config_command(self._args(config_command="unset", key="model.default"))
assert excinfo.value.code == 1
- assert "not valid YAML" in capsys.readouterr().err
+ assert "formatting error" in capsys.readouterr().err
assert config_path.read_text(encoding="utf-8") == original
diff --git a/tests/hermes_cli/test_config_guard_surfaces.py b/tests/hermes_cli/test_config_guard_surfaces.py
index 8721f01a827..bc596b7f62c 100644
--- a/tests/hermes_cli/test_config_guard_surfaces.py
+++ b/tests/hermes_cli/test_config_guard_surfaces.py
@@ -35,7 +35,7 @@ class TestGatewayGuard:
_guard_corrupt_user_config()
assert exc_info.value.code == 2
- assert "Refusing non-interactive startup" in capsys.readouterr().err
+ assert "Hermes stopped because your settings file" in capsys.readouterr().err
def test_gateway_allows_valid_config(self, tmp_path):
from gateway.run import _guard_corrupt_user_config
@@ -71,7 +71,7 @@ class TestCronRunJobGuard:
assert success is False
assert error is not None
- assert "Refusing non-interactive startup" in error
+ assert "Hermes stopped because your settings file" in error
assert "config.yaml" in error
assert final_response == ""
@@ -88,7 +88,7 @@ class TestCronRunJobGuard:
success, output_doc, final_response, error = run_job(
self._job(no_agent=True, script="true", deliver="none")
)
- assert "Refusing non-interactive startup" not in (error or "")
+ assert "Hermes stopped because your settings file" not in (error or "")
def test_run_job_no_agent_exempt(self, tmp_path):
from cron.scheduler import run_job
@@ -98,7 +98,7 @@ class TestCronRunJobGuard:
success, output_doc, final_response, error = run_job(
self._job(no_agent=True, script="true", deliver="none")
)
- assert "Refusing non-interactive startup" not in (error or "")
+ assert "Hermes stopped because your settings file" not in (error or "")
class TestServeGuard:
@@ -122,7 +122,7 @@ class TestServeGuard:
main_mod.cmd_dashboard(args)
assert exc_info.value.code == 2
- assert "Refusing non-interactive startup" in capsys.readouterr().err
+ assert "Hermes stopped because your settings file" in capsys.readouterr().err
def test_serve_escape_hatch_passes_guard(self, tmp_path, monkeypatch):
"""--ignore-user-config lets serve get past the corrupt-config guard."""
diff --git a/tests/hermes_cli/test_config_lkg_backup.py b/tests/hermes_cli/test_config_lkg_backup.py
index f5f8af344be..732e7e5c16f 100644
--- a/tests/hermes_cli/test_config_lkg_backup.py
+++ b/tests/hermes_cli/test_config_lkg_backup.py
@@ -44,7 +44,7 @@ def test_fresh_process_recovers_last_good_config_and_leaves_broken_file_alone(tm
assert recovered["approvals"]["deny"] == ["curl*evil*"]
assert recovered["model"]["default"] == "test/secure"
assert recovered["custom_providers"][0]["api_key"] == "expanded-secret"
- assert "LAST KNOWN GOOD" in stderr
+ assert "last good settings" in stderr
assert config_path.read_text(encoding="utf-8") == BROKEN
diff --git a/tests/hermes_cli/test_console_engine.py b/tests/hermes_cli/test_console_engine.py
index 67a7c0c6da4..a50546f8f50 100644
--- a/tests/hermes_cli/test_console_engine.py
+++ b/tests/hermes_cli/test_console_engine.py
@@ -602,6 +602,6 @@ def test_config_set_on_unparseable_yaml_reports_error_not_crash(tmp_path, monkey
)
assert result.status == "error"
- assert "not valid YAML" in (result.output or "") or "Failed to parse" in (result.output or "")
+ assert "formatting error" in (result.output or "")
# The broken-but-recoverable file must survive untouched.
assert config_path.read_text(encoding="utf-8") == original
diff --git a/tests/hermes_cli/test_cron.py b/tests/hermes_cli/test_cron.py
index 1712e0ddab6..feb3bc61ce3 100644
--- a/tests/hermes_cli/test_cron.py
+++ b/tests/hermes_cli/test_cron.py
@@ -183,7 +183,8 @@ class TestCronDoctor:
assert "Cron doctor found 3 issue(s)" in out
assert job["id"] in out
assert "last run failed: Provider returned error" in out
- assert "last delivery failed: telegram timeout" in out
+ assert "was not delivered (telegram timeout)" in out
+ assert "hermes cron edit" in out
assert "script not found" in out
def test_doctor_reports_healthy_jobs(self, tmp_cron_dir, capsys):
@@ -216,7 +217,8 @@ class TestCronDoctor:
out = capsys.readouterr().out
assert rc == 1
- assert "last delivery failed: telegram timeout" in out
+ assert "was not delivered (telegram timeout)" in out
+ assert "hermes cron edit" in out
assert "last run failed" not in out
assert "unknown error" not in out
@@ -272,7 +274,7 @@ class TestCronListStatusRendering:
out = capsys.readouterr().out
last_run_line = next(l for l in out.splitlines() if "Last run:" in l)
- assert "delivery_failed" in last_run_line
+ assert "was not delivered" in last_run_line
assert "telegram timeout" in last_run_line, (
"the delivery detail lives in last_delivery_error, not last_error"
)
@@ -292,7 +294,7 @@ class TestCronListStatusRendering:
out = capsys.readouterr().out
last_run_line = next(l for l in out.splitlines() if "Last run:" in l)
assert f"{cron_cli.Colors.GREEN}ok" in last_run_line
- assert "delivery_failed" not in last_run_line
+ assert "not delivered" not in last_run_line
class TestGatewayNotRunningWarning:
diff --git a/tests/hermes_cli/test_doctor_terminal_backends.py b/tests/hermes_cli/test_doctor_terminal_backends.py
new file mode 100644
index 00000000000..7cb83026fe2
--- /dev/null
+++ b/tests/hermes_cli/test_doctor_terminal_backends.py
@@ -0,0 +1,51 @@
+"""Invariants for the terminal-backend doctor lines (tools-runtime-30): each failure names the backend in
+plain words and points at `hermes setup terminal`, never at raw TERMINAL_* env vars."""
+
+import pytest
+
+from hermes_cli import doctor_tools
+
+
+def issues():
+ return []
+
+
+def _joined(capsys) -> str:
+ return capsys.readouterr().out
+
+
+def test_docker_missing_line_names_backend_and_setup_command(monkeypatch, capsys, issues):
+ monkeypatch.setattr(doctor_tools, "_safe_which", lambda name: None)
+ doctor_tools._check_docker_backend("docker", False, issues)
+ out = _joined(capsys)
+ assert "Docker not installed" in out and "'docker' terminal backend" in out
+ assert "TERMINAL_ENV" not in out
+ assert issues and "hermes setup terminal" in issues[0] and "Install Docker" in issues[0]
+
+
+def test_docker_daemon_down_line_says_start_docker_or_switch(monkeypatch, capsys, issues):
+ monkeypatch.setattr(doctor_tools, "_safe_which", lambda name: "/usr/bin/docker")
+ monkeypatch.setattr(doctor_tools, "_run_ok", lambda cmd, timeout, **kw: False)
+ doctor_tools._check_docker_backend("docker", False, issues)
+ out = _joined(capsys)
+ assert "Docker daemon not running" in out and "'docker' terminal backend" in out
+ assert issues and "Start Docker" in issues[0] and "hermes setup terminal" in issues[0]
+
+
+def test_ssh_host_missing_line_points_at_setup_terminal(monkeypatch, capsys, issues):
+ monkeypatch.delenv("TERMINAL_SSH_HOST", raising=False)
+ doctor_tools._check_ssh_backend(issues)
+ out = _joined(capsys)
+ assert "SSH host not configured" in out and "'ssh' terminal backend" in out
+ assert "TERMINAL_SSH_HOST" not in out
+ assert issues and "hermes setup terminal" in issues[0] and "SSH host and user" in issues[0]
+
+
+def test_daytona_key_missing_line_points_at_setup_terminal(monkeypatch, capsys, issues):
+ monkeypatch.delenv("DAYTONA_API_KEY", raising=False)
+ doctor_tools._check_daytona_backend(issues)
+ out = _joined(capsys)
+ assert "Daytona API key missing" in out and "'daytona' terminal backend" in out
+ assert "DAYTONA_API_KEY" not in out
+ assert issues and "hermes setup terminal" in issues[0]
diff --git a/tests/hermes_cli/test_gateway_service.py b/tests/hermes_cli/test_gateway_service.py
index 5f91c8e81eb..772ac6a920c 100644
--- a/tests/hermes_cli/test_gateway_service.py
+++ b/tests/hermes_cli/test_gateway_service.py
@@ -1825,7 +1825,9 @@ class TestDockerAwareGateway:
monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
- with pytest.raises(RuntimeError, match="systemctl is not available"):
+ from hermes_cli.gateway_command_errors import SystemctlUnavailableError
+
+ with pytest.raises(SystemctlUnavailableError):
gateway_cli._run_systemctl(["start", "hermes-gateway"])
def test_run_systemctl_passes_through_on_success(self, monkeypatch):
diff --git a/tests/hermes_cli/test_kanban_notify.py b/tests/hermes_cli/test_kanban_notify.py
index 6f4e2b656ed..f73110869ba 100644
--- a/tests/hermes_cli/test_kanban_notify.py
+++ b/tests/hermes_cli/test_kanban_notify.py
@@ -590,7 +590,11 @@ async def test_notifier_unsubs_after_abnormal_events(kind, kanban_home):
# The user is notified about the abnormal event...
fake_adapter.send.assert_called_once()
- assert kind.replace('_', ' ') in fake_adapter.send.call_args[0][1]
+ sent = fake_adapter.send.call_args[0][1]
+ assert tid in sent
+ # Plain-language outcome per event kind (no internal event names).
+ expected = {"crashed": "stopped unexpectedly", "gave_up": "blocked", "timed_out": "time limit"}[kind]
+ assert expected in sent
# ...but the subscription survives so a respawn-then-same-event cycle
# reaches the user too. The cursor (last_event_id) advanced inside
diff --git a/tests/hermes_cli/test_mcp_probe_redaction.py b/tests/hermes_cli/test_mcp_probe_redaction.py
index bc04f089d88..5b60e3a6929 100644
--- a/tests/hermes_cli/test_mcp_probe_redaction.py
+++ b/tests/hermes_cli/test_mcp_probe_redaction.py
@@ -368,7 +368,7 @@ class TestCmdMcpTestRedaction:
out = capsys.readouterr().out
_assert_fully_redacted(out)
assert "Connection failed" in out
- assert "Bearer ***" in out
+ assert "***" in out # credential span masked, whichever redactor got it first
class TestDashboardMcpTestRedaction:
@@ -452,7 +452,7 @@ class TestSiblingProbeConsumersRedact:
out = capsys.readouterr().out
_assert_fully_redacted(out)
assert "Failed to connect" in out
- assert "Bearer ***" in out
+ assert "***" in out # credential span masked, whichever redactor got it first
def test_mcp_login_redacts_probe_exception(self, tmp_path, capsys, monkeypatch):
_seed_config(tmp_path, {
diff --git a/tests/hermes_cli/test_noninteractive_config_guard.py b/tests/hermes_cli/test_noninteractive_config_guard.py
index 1c4ef89c99b..a6ea952ca51 100644
--- a/tests/hermes_cli/test_noninteractive_config_guard.py
+++ b/tests/hermes_cli/test_noninteractive_config_guard.py
@@ -54,10 +54,10 @@ def test_noninteractive_guard_rejects_malformed_yaml(args, tmp_path, caplog, cap
main_mod._guard_noninteractive_user_config(args)
assert exc_info.value.code == 2
- assert "Refusing non-interactive startup" in capsys.readouterr().err
+ assert "Hermes stopped because your settings file" in capsys.readouterr().err
assert any(
record.levelno == logging.ERROR
- and "Refusing non-interactive startup" in record.getMessage()
+ and "Hermes stopped because your settings file" in record.getMessage()
for record in caplog.records
)
assert config_path.read_text(encoding="utf-8") == broken
diff --git a/tests/hermes_cli/test_profile_distribution.py b/tests/hermes_cli/test_profile_distribution.py
index 43b4dbad627..0a542307560 100644
--- a/tests/hermes_cli/test_profile_distribution.py
+++ b/tests/hermes_cli/test_profile_distribution.py
@@ -450,7 +450,7 @@ class TestDescribe:
def test_describe_missing_profile_raises(self, profile_env):
- with pytest.raises(DistributionError, match="does not exist"):
+ with pytest.raises(DistributionError, match="No profile named .*hermes profile list"):
describe_distribution("nonexistent")
diff --git a/tests/hermes_cli/test_resume_display.py b/tests/hermes_cli/test_resume_display.py
index e1c8fb2e5b7..274e9568613 100644
--- a/tests/hermes_cli/test_resume_display.py
+++ b/tests/hermes_cli/test_resume_display.py
@@ -320,7 +320,8 @@ class TestPreloadResumedSession:
result = cli._preload_resumed_session()
assert result is False
- assert "safe resume limit is 20000" in output.getvalue()
+ assert "too long to reload safely" in output.getvalue()
+ assert "limit 20000" in output.getvalue()
mock_db.get_resume_conversations.assert_not_called()
def test_tip_only_guard_goes_through_the_shared_resume_guard(self):
@@ -342,7 +343,7 @@ class TestPreloadResumedSession:
20_001, 20_000, scope="in its tip segment"
)
error = cli._resume_history_limit_error(tip_only=True)
- assert error and "in its tip segment" in error
+ assert error and "20001" in error and "too long to reload safely" in error
diff --git a/tests/hermes_cli/test_sessions_error_exit_codes.py b/tests/hermes_cli/test_sessions_error_exit_codes.py
index e8ff6e5d36e..fad72e02082 100644
--- a/tests/hermes_cli/test_sessions_error_exit_codes.py
+++ b/tests/hermes_cli/test_sessions_error_exit_codes.py
@@ -31,7 +31,8 @@ def test_delete_missing_returns_1(tmp_path, monkeypatch, capsys):
SessionDB(tmp_path / "state.db") # initialize an empty store
rc = sc.cmd_sessions(_args("delete", session_id="nope_xyz"))
assert rc == 1
- assert "not found" in capsys.readouterr().out.lower()
+ out = capsys.readouterr().out
+ assert "No session 'nope_xyz'" in out and "hermes sessions list" in out
def test_rename_missing_returns_1(tmp_path, monkeypatch):
diff --git a/tests/hermes_cli/test_sessions_pin.py b/tests/hermes_cli/test_sessions_pin.py
index 17443197d63..42145e2f7eb 100644
--- a/tests/hermes_cli/test_sessions_pin.py
+++ b/tests/hermes_cli/test_sessions_pin.py
@@ -74,7 +74,7 @@ def test_pin_multiple_ids_one_missing(monkeypatch, capsys):
code, out = _run(monkeypatch, capsys, ["pin", "aaa", "nope", "bbb"], db)
assert ("aaa111", True) in db.pin_calls
assert ("bbb222", True) in db.pin_calls
- assert "Session 'nope' not found." in out
+ assert "No session 'nope'" in out and "hermes sessions list" in out
assert code == 1
diff --git a/tests/hermes_cli/test_set_config_value.py b/tests/hermes_cli/test_set_config_value.py
index ac7211cbc07..f1fc63dc815 100644
--- a/tests/hermes_cli/test_set_config_value.py
+++ b/tests/hermes_cli/test_set_config_value.py
@@ -709,12 +709,12 @@ class TestMalformedYAMLConfigPreservation:
"""set_config_value must raise, not overwrite the broken config."""
self._write_broken_config(_isolated_hermes_home)
- with pytest.raises(RuntimeError, match="not valid YAML"):
+ with pytest.raises(RuntimeError, match="formatting error"):
set_config_value("agent.max_turns", "50")
captured = capsys.readouterr()
combined = captured.out + captured.err
- assert "Failed to parse" in combined or "not valid YAML" in combined
+ assert "formatting error" in combined and "`hermes config edit`" in combined
# Original config must remain intact
raw = _read_config(_isolated_hermes_home)
assert raw == self.BROKEN_CONFIG, f"Config was overwritten:\n{raw}"
@@ -725,12 +725,12 @@ class TestMalformedYAMLConfigPreservation:
self._write_broken_config(_isolated_hermes_home)
- with pytest.raises(RuntimeError, match="not valid YAML"):
+ with pytest.raises(RuntimeError, match="formatting error"):
unset_config_value("model")
captured = capsys.readouterr()
combined = captured.out + captured.err
- assert "Failed to parse" in combined or "not valid YAML" in combined
+ assert "formatting error" in combined and "`hermes config edit`" in combined
raw = _read_config(_isolated_hermes_home)
assert raw == self.BROKEN_CONFIG
diff --git a/tests/hermes_cli/test_shared_owner_message.py b/tests/hermes_cli/test_shared_owner_message.py
index ab53a137ce9..600f65ce27c 100644
--- a/tests/hermes_cli/test_shared_owner_message.py
+++ b/tests/hermes_cli/test_shared_owner_message.py
@@ -1,13 +1,15 @@
-"""Ownership age is not evidence that a model turn is running."""
+"""The owner refusal never claims a turn is running, and leads with plain words."""
from hermes_cli.active_sessions import session_already_owned_message
-def test_owner_refusal_distinguishes_lease_age_from_turn_activity():
+def test_owner_refusal_is_plain_and_never_claims_a_running_turn():
message = session_already_owned_message("session", {
"surface": "desktop", "pid": 123, "started_at": 1,
})
- assert "lease age" in message
- assert "turn activity is unknown" in message
- assert "close the session in its owning surface" in message
+ first, details = message.splitlines()
+ assert first.startswith("This chat is open in another Hermes window/terminal.")
+ assert "start a new chat here" in first
+ assert details.startswith("Details: ") and "desktop" in details and "ago" in details
assert "running " not in message
+ assert "lease" not in message and "pid" not in message
diff --git a/tests/hermes_cli/test_skills_hub.py b/tests/hermes_cli/test_skills_hub.py
index f607ff9430e..088130671e2 100644
--- a/tests/hermes_cli/test_skills_hub.py
+++ b/tests/hermes_cli/test_skills_hub.py
@@ -562,6 +562,6 @@ def test_do_install_generic_when_no_index_hit_or_rate_limited(monkeypatch, meta_
do_install("skills-sh/org/gone-skill", console=console, skip_confirm=True)
out = sink.getvalue()
- assert "Could not fetch" in out
+ assert "Could not download" in out
assert "Stale index entry" not in out
assert ("rate limit" in out) is meta_hit
diff --git a/tests/hermes_cli/test_tool_availability_notices.py b/tests/hermes_cli/test_tool_availability_notices.py
new file mode 100644
index 00000000000..366997dff68
--- /dev/null
+++ b/tests/hermes_cli/test_tool_availability_notices.py
@@ -0,0 +1,76 @@
+"""Invariants for the CLI startup 'some tools disabled' notice (tools-runtime-01 / -02)."""
+
+from hermes_cli.tool_availability_notices import filter_to_enabled_toolsets, tool_availability_warning_lines
+
+_TERMINAL = {"name": "terminal", "env_vars": [], "tools": ["terminal", "process_manage"]}
+_WEB = {"name": "web", "env_vars": ["EXA_API_KEY", "TAVILY_API_KEY"], "tools": ["web_search"]}
+_RL = {"name": "rl", "env_vars": ["TINKER_API_KEY"], "tools": ["rl_tool"]}
+
+
+def test_terminal_line_names_backend_reason_and_fix_commands():
+ lines = tool_availability_warning_lines(
+ [_TERMINAL], terminal_reason="Docker is installed but the Docker daemon is not running",
+ terminal_backend="docker")
+ text = "\n".join(lines)
+ assert "Terminal tool disabled" in text
+ assert "'docker'" in text
+ assert "Docker daemon is not running" in text
+ assert "hermes doctor" in text and "hermes setup terminal" in text
+ assert "TERMINAL_ENV" not in text
+
+
+def test_terminal_without_reason_still_gets_a_line():
+ lines = tool_availability_warning_lines([_TERMINAL], terminal_reason=None, terminal_backend="ssh")
+ assert any("Terminal tool disabled" in line and "'ssh'" in line for line in lines)
+
+
+def test_web_collapses_env_dump_into_one_provider_sentence():
+ lines = tool_availability_warning_lines([_WEB], terminal_reason=None, terminal_backend="local")
+ text = "\n".join(lines)
+ assert "EXA_API_KEY" not in text
+ assert "Web search is off" in text and "hermes setup tools" in text
+
+
+def test_generic_toolset_lists_vars_and_setup_hint():
+ lines = tool_availability_warning_lines([_RL], terminal_reason=None, terminal_backend="local")
+ text = "\n".join(lines)
+ assert "rl" in text and "TINKER_API_KEY" in text and "hermes setup" in text
+
+
+def test_nothing_to_report_returns_no_lines():
+ assert tool_availability_warning_lines([], terminal_reason=None, terminal_backend="local") == []
+ # A toolset with no env vars and no special notice (e.g. lazy check_fn) stays silent.
+ assert tool_availability_warning_lines([{"name": "honcho", "env_vars": [], "tools": []}],
+ terminal_reason=None, terminal_backend="local") == []
+
+
+def test_web_notice_cites_setup_tools_not_the_toggle_menu():
+ # `hermes tools` with no subcommand is the enable/disable menu; providers live under `hermes setup tools`.
+ lines = tool_availability_warning_lines([_WEB], terminal_reason=None, terminal_backend="local")
+ text = "\n".join(lines)
+ assert "hermes setup tools" in text
+ assert "hermes tools[/]" not in text
+
+
+class TestFilterToEnabledToolsets:
+ _BUNDLE = {"hermes-cli": ["terminal", "process_manage", "web_search", "read_file"],
+ "terminal": ["terminal", "process_manage"]}
+
+ def _resolve(self, name):
+ return self._BUNDLE.get(name, [])
+
+ def test_composite_bundle_keeps_terminal_notice_on_default_install(self):
+ kept = filter_to_enabled_toolsets([_TERMINAL, _WEB, _RL], ["hermes-cli"], self._resolve)
+ assert [k["name"] for k in kept] == ["terminal", "web"]
+
+ def test_direct_toolset_name_and_unknown_bundle(self):
+ assert [k["name"] for k in filter_to_enabled_toolsets([_TERMINAL, _RL], ["terminal"], self._resolve)] == ["terminal"]
+ assert filter_to_enabled_toolsets([_TERMINAL], ["no-such-bundle"], self._resolve) == []
+
+ def test_empty_selection_means_everything(self):
+ assert filter_to_enabled_toolsets([_TERMINAL, _RL], [], self._resolve) == [_TERMINAL, _RL]
+
+ def test_resolver_error_is_not_fatal(self):
+ def boom(name):
+ raise RuntimeError("registry not ready")
+ assert filter_to_enabled_toolsets([_TERMINAL], ["hermes-cli"], boom) == []
diff --git a/tests/hermes_cli/test_update_messages.py b/tests/hermes_cli/test_update_messages.py
new file mode 100644
index 00000000000..babf24a6350
--- /dev/null
+++ b/tests/hermes_cli/test_update_messages.py
@@ -0,0 +1,75 @@
+"""User-facing wording contracts for ``hermes update`` failure/partial output.
+
+Invariants only (what the user must be able to read and act on), never whole-string snapshots.
+"""
+
+from __future__ import annotations
+
+import subprocess
+
+import pytest
+
+from hermes_cli import update_cmd
+import hermes_cli.update_receipt as ur
+
+
+class TestFleetMatrixVerdict:
+ """cli-09: a stale/down fleet must end with an explicit "not complete" verdict, because
+ ``✓ Update complete!`` was already printed before the restart phase."""
+
+ def test_stale_rows_print_counted_verdict_with_commands(self, capsys):
+ fleet = [
+ {"profile": "default", "pid": 1234, "code_sha": "abc12345ff", "state": "stale"},
+ {"profile": "work", "pid": 99, "code_sha": None, "state": "down"},
+ {"profile": "ok", "pid": 7, "code_sha": "a" * 40, "state": "current"},
+ ]
+ assert ur.print_fleet_version_matrix(fleet) is True
+ out = capsys.readouterr().out
+ verdict = [line for line in out.splitlines() if "Update not complete" in line]
+ assert len(verdict) == 1
+ assert verdict[0].startswith("✗")
+ assert "2 gateway" in out
+ assert "hermes gateway restart" in out
+ assert "hermes -p <profile> gateway restart" in out
+ assert "hermes gateway status" in out
+
+ def test_unknown_rows_print_no_verdict(self, capsys):
+ fleet = [{"profile": "default", "pid": 1, "code_sha": None, "state": "unknown"}]
+ assert ur.print_fleet_version_matrix(fleet) is False
+ assert "Update not complete" not in capsys.readouterr().out
+
+
+class TestCalledProcessErrorMessage:
+ """cli-10: a dependency-install failure leads with a plain sentence, not the exception repr."""
+
+ @pytest.fixture
+ def no_exit(self, monkeypatch):
+ monkeypatch.setattr(update_cmd, "_finalize_receipt", lambda *_a, **_k: None)
+ monkeypatch.setattr(update_cmd.sys, "exit", lambda code=0: (_ for _ in ()).throw(SystemExit(code)))
+
+ def test_dep_install_failure_lead_and_next_step(self, capsys, no_exit, monkeypatch):
+ monkeypatch.setattr(update_cmd._m(), "_is_windows", lambda: False)
+ exc = subprocess.CalledProcessError(1, ["uv", "pip", "install", "-e", ".[all]"], stderr="error: disk full")
+ with pytest.raises(SystemExit) as info:
+ update_cmd._handle_update_called_process_error(exc, object(), False, False)
+ assert info.value.code == 1
+ out = capsys.readouterr().out
+ lines = [line for line in out.splitlines() if line.strip()]
+ assert lines[0].startswith("✗ Python dependency install failed")
+ assert "code update itself succeeded" in lines[0]
+ assert "returned non-zero exit status" not in lines[0]
+ assert "disk full" in out
+ assert "hermes update" in out
+ assert "Re-downloading" not in out
+
+ def test_non_dep_failure_moves_repr_to_details_line(self, capsys, no_exit, monkeypatch):
+ monkeypatch.setattr(update_cmd._m(), "_is_windows", lambda: False)
+ exc = subprocess.CalledProcessError(128, ["git", "pull"], stderr="fatal: not a git repository")
+ with pytest.raises(SystemExit):
+ update_cmd._handle_update_called_process_error(exc, object(), False, False)
+ out = capsys.readouterr().out
+ lines = [line for line in out.splitlines() if line.strip()]
+ assert lines[0].startswith("✗ Git update failed")
+ assert "returned non-zero exit status" not in lines[0]
+ assert any(line.strip().startswith("Details:") and "returned non-zero exit status 128" in line
+ for line in lines)
diff --git a/tests/hermes_cli/test_update_sqlite_remediation.py b/tests/hermes_cli/test_update_sqlite_remediation.py
index e0dae080442..4efc2f501cf 100644
--- a/tests/hermes_cli/test_update_sqlite_remediation.py
+++ b/tests/hermes_cli/test_update_sqlite_remediation.py
@@ -59,12 +59,37 @@ def test_summary_withholds_success_when_sqlite_remediation_failed(capsys, monkey
out = capsys.readouterr().out
assert complete is False
assert "Update complete" not in out
- assert "SQLite 3.46.1" in out
- assert "WAL-reset" in out
- assert "uv-managed Python" in out
+ assert "SQLite (3.46.1)" in out
+ assert "WAL" not in out
+ assert "venv" not in out
+ assert "install.sh | bash" in out
assert "hermes doctor" in out
+def test_sqlite_partial_message_is_shared_and_names_windows_installer(capsys, monkeypatch):
+ """Both partial-completion paths print the same fix, and Windows gets the PowerShell one-liner."""
+ for module in (update_cmd, update_cmd_maint):
+ monkeypatch.setattr(
+ module,
+ "_post_update_sqlite_runtime_status",
+ lambda: (False, SimpleNamespace(sqlite_version_string="3.46.1")),
+ )
+ monkeypatch.setattr(update_cmd._m(), "_is_windows", lambda: True)
+
+ update_cmd._print_verified_update_completion("✓ Update complete!")
+ verified_out = capsys.readouterr().out
+ update_cmd._print_update_summary(node_failures=[], desktop_build_ok=True, pre_update_version=None)
+ summary_out = capsys.readouterr().out
+
+ for out in (verified_out, summary_out):
+ assert "known corruption bug" in out
+ assert "install.ps1" in out
+ assert "install.sh" not in out
+ assert "hermes doctor" in out
+ fix_line = next(line for line in verified_out.splitlines() if "install.ps1" in line)
+ assert fix_line in summary_out.splitlines()
+
+
def test_current_checkout_completion_is_verified_before_success(capsys, monkeypatch):
monkeypatch.setattr(
update_cmd,
@@ -82,7 +107,8 @@ def test_current_checkout_completion_is_verified_before_success(capsys, monkeypa
out = capsys.readouterr().out
assert complete is False
assert "Already up to date" not in out
- assert "SQLite 3.46.1" in out
+ assert "SQLite (3.46.1)" in out
+ assert "hermes doctor" in out
def test_current_checkout_repair_returns_verified_completion_result(monkeypatch):
diff --git a/tests/hermes_cli/test_ux_messages_auth_config.py b/tests/hermes_cli/test_ux_messages_auth_config.py
new file mode 100644
index 00000000000..fea9795827f
--- /dev/null
+++ b/tests/hermes_cli/test_ux_messages_auth_config.py
@@ -0,0 +1,330 @@
+"""Message contracts for the config-parse and sign-in failure copy (CLI startup UX campaign).
+
+Every test asserts the contract (plain lead sentence + the exact command pointer, raw exception
+kept out of the lead) rather than the whole string.
+"""
+
+from __future__ import annotations
+
+import logging
+from types import SimpleNamespace
+
+import httpx
+import pytest
+import yaml
+
+
+def _yaml_error(text: str = "model:\n default: x\n bad: [unterminated\n") -> Exception:
+ try:
+ yaml.safe_load(text)
+ except yaml.YAMLError as exc:
+ return exc
+ raise AssertionError("expected a YAML error")
+
+
+# ── cli-03: config.yaml parse failure at startup ─────────────────────────────────────────────
+
+
+class TestConfigParseWarning:
+ @pytest.mark.parametrize("fallback", ["defaults", "last-known-good-backup", "refuse-write"])
+ def test_warning_names_repair_commands_and_line(self, tmp_path, monkeypatch, capsys, fallback):
+ from hermes_cli import config as config_mod
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ config_mod._CONFIG_PARSE_WARNED.clear()
+ config_path = tmp_path / "config.yaml"
+ config_path.write_text("model:\n default: x\n bad: [unterminated\n", encoding="utf-8")
+
+ config_mod._warn_config_parse_failure(config_path, _yaml_error(), fallback=fallback)
+
+ err = capsys.readouterr().err
+ assert "formatting error" in err
+ assert "line " in err
+ assert "`hermes config edit`" in err and "`hermes config check`" in err
+ assert "IGNORED" not in err and "LAST KNOWN GOOD" not in err
+ # The raw PyYAML text is demoted to a Details line, never the lead sentence.
+ lead = err.strip().splitlines()[0]
+ assert "expected <block end>" not in lead.split("Details:")[0]
+
+
+# ── cli-33: refuse-to-write and non-interactive startup guard ────────────────────────────────
+
+
+class TestConfigGuardCopy:
+ def test_require_parseable_user_config_says_what_happened_and_how_to_fix(self, tmp_path, monkeypatch):
+ from hermes_cli import config as config_mod
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ (tmp_path / "config.yaml").write_text("model: [unterminated\n", encoding="utf-8")
+
+ with pytest.raises(config_mod.InvalidUserConfigError) as excinfo:
+ config_mod.require_parseable_user_config()
+
+ msg = str(excinfo.value)
+ assert msg.startswith("Hermes stopped because your settings file")
+ assert "`hermes config edit`" in msg and "--ignore-user-config" in msg
+ assert "non-interactive" not in msg and "built-in defaults" not in msg
+ assert "Details:" in msg
+
+ def test_refuse_write_names_repair_commands_and_absolute_backup_dir(self, tmp_path, monkeypatch):
+ from hermes_cli import config as config_mod
+ from hermes_constants import display_hermes_home
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ config_mod._CONFIG_PARSE_WARNED.clear()
+ (tmp_path / "config.yaml").write_text("model: [unterminated\n", encoding="utf-8")
+
+ with pytest.raises(RuntimeError) as excinfo:
+ config_mod.require_readable_config_before_write()
+
+ msg = str(excinfo.value)
+ assert "this change was not saved" in msg
+ assert "`hermes config edit`" in msg and "`hermes config check`" in msg
+ assert f"{display_hermes_home()}/backups/config/" in msg
+ assert not msg.startswith("Refusing")
+
+
+# ── cli-04: no provider configured ───────────────────────────────────────────────────────────
+
+
+def test_no_provider_configured_points_at_model_login_and_auth_add(monkeypatch, tmp_path):
+ from hermes_cli.auth import AuthError, resolve_provider
+ from hermes_constants import display_hermes_home
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ monkeypatch.setattr("agent.bedrock_adapter.has_aws_credentials", lambda env=None: False)
+
+ with pytest.raises(AuthError) as excinfo:
+ resolve_provider("auto")
+
+ msg = str(excinfo.value)
+ assert excinfo.value.code == "no_provider_configured"
+ assert "`hermes model`" in msg and "`/login`" in msg and "`hermes auth add <provider>`" in msg
+ assert "~/.hermes/.env" not in msg or display_hermes_home() == "~/.hermes"
+ assert f"{display_hermes_home()}/.env" in msg
+ assert "inference provider" not in msg
+
+
+# ── cli-07: Nous device-code sign-in failures ────────────────────────────────────────────────
+
+
+class TestSignInFailureCopy:
+ @pytest.mark.parametrize("code, pointer", [
+ ("expired_token", "`hermes portal`"),
+ ("access_denied", "`hermes model`"),
+ ])
+ def test_poll_error_codes_map_to_plain_copy(self, code, pointer):
+ from hermes_cli import auth_device_flow
+
+ class _Client:
+ def post(self, url, data=None):
+ request = httpx.Request("POST", url)
+ return httpx.Response(400, json={"error": code, "error_description": "server text"}, request=request)
+
+ with pytest.raises(RuntimeError) as excinfo:
+ auth_device_flow._poll_for_token(
+ client=_Client(), portal_base_url="https://portal.nousresearch.com", client_id="hermes-cli",
+ device_code="device", expires_in=5, poll_interval=1)
+
+ msg = str(excinfo.value)
+ assert not msg.startswith(code)
+ assert "`hermes portal`" in msg and pointer in msg
+
+ def test_network_failure_names_host_and_retry_command(self):
+ from hermes_cli.auth_error_copy import sign_in_failure_lines
+
+ lines = sign_in_failure_lines(httpx.ConnectError("[Errno -2] Name or service not known"),
+ service_host="portal.nousresearch.com")
+
+ assert lines[0].startswith("Could not sign in")
+ assert "portal.nousresearch.com" in lines[0] and "`hermes portal`" in lines[0]
+ assert "Errno" not in lines[0]
+ assert any(line.strip().startswith("Details:") for line in lines[1:])
+
+ def test_run_login_prints_plain_copy_not_raw_exception(self, capsys):
+ from hermes_cli.model_setup_flows_common import _run_login
+
+ def _boom(*_a, **_k):
+ raise httpx.ConnectError("[Errno -2] Name or service not known")
+
+ assert _run_login(_boom) is False
+ out = capsys.readouterr().out
+ assert "Could not sign in" in out
+ assert not out.lstrip().startswith("Login failed:")
+
+ def test_login_nous_prints_plain_copy(self, monkeypatch, capsys):
+ from hermes_cli import auth_nous
+
+ def _boom(**_k):
+ raise httpx.ConnectError("[Errno -2] Name or service not known")
+
+ monkeypatch.setattr(auth_nous, "_offer_shared_nous_import", lambda *_a, **_k: None, raising=False)
+ monkeypatch.setattr("hermes_cli.auth._nous_device_code_login", _boom)
+ args = SimpleNamespace(timeout=1.0, portal_url=None, inference_url=None, client_id=None, scope=None,
+ no_browser=True, insecure=False, ca_bundle=None)
+ from hermes_cli.auth import PROVIDER_REGISTRY
+
+ with pytest.raises(SystemExit) as excinfo:
+ auth_nous._login_nous(args, PROVIDER_REGISTRY["nous"])
+
+ assert excinfo.value.code == 1
+ out = capsys.readouterr().out
+ assert "Could not sign in" in out and "`hermes portal`" in out
+ assert "Login failed:" not in out
+
+
+# ── cli-25: auth refresh / unknown provider ──────────────────────────────────────────────────
+
+
+class TestAuthCommandsCopy:
+ def test_unknown_provider_offers_did_you_mean_and_pointers(self, monkeypatch):
+ from hermes_cli import auth_commands
+
+ monkeypatch.setattr(auth_commands, "_configured_provider_entry", lambda _p: None)
+ with pytest.raises(SystemExit) as excinfo:
+ auth_commands.auth_add_command(SimpleNamespace(provider="openai"))
+
+ msg = str(excinfo.value)
+ assert "Unknown provider 'openai'" in msg
+ assert "Did you mean" in msg and "openai-codex" in msg
+ assert "`hermes auth`" in msg and "`hermes model`" in msg
+
+ def test_refresh_failure_names_relogin_command(self, monkeypatch):
+ from hermes_cli import auth_commands
+
+ from agent.credential_pool import AUTH_TYPE_OAUTH
+
+ matched = SimpleNamespace(id="abc", label="device-code", source="device_code", provider="nous",
+ auth_type=AUTH_TYPE_OAUTH, refresh_token="rt", last_status="ok")
+
+ class _Pool:
+ def entries(self):
+ return [matched]
+
+ def try_refresh_matching(self, credential_id=None):
+ matched.last_status = "refresh_failed"
+ return None
+
+ monkeypatch.setattr(auth_commands, "load_pool", lambda _provider: _Pool())
+ with pytest.raises(SystemExit) as excinfo:
+ auth_commands.auth_refresh_command(SimpleNamespace(provider="nous", target=None))
+
+ msg = str(excinfo.value)
+ assert "refresh_failed" not in msg and "status now" not in msg
+ assert "`hermes auth add nous --type oauth`" in msg
+
+
+# ── cli-24: /model onto a provider without credentials ───────────────────────────────────────
+
+
+def test_creds_for_target_provider_names_auth_add_and_model(monkeypatch):
+ from hermes_cli import model_switch
+
+ st = model_switch._Switch(
+ raw_input="kimi-coding:x", current_provider="openrouter", current_model="m", current_base_url="",
+ current_api_key="", is_global=False, explicit_provider="", user_providers=None, custom_providers=None,
+ target_provider="kimi-coding", provider_label="Kimi")
+
+ def _fail(**_k):
+ raise RuntimeError("KIMI_API_KEY missing (raw resolver text)")
+
+ monkeypatch.setattr(st, "resolve_runtime", _fail, raising=False)
+ result = model_switch._creds_for_switched_provider(st)
+
+ assert result is not None and result.success is False
+ msg = result.error_message
+ assert msg.startswith("Kimi is not connected")
+ assert "`hermes auth add kimi-coding`" in msg and "/model" in msg
+ assert "Could not resolve credentials" not in msg
+ assert "Details:" in msg
+
+
+# ── cli-16: setup wizard provider step failure ───────────────────────────────────────────────
+
+
+class TestProviderSetupFailureCopy:
+ def test_setup_provider_step_reports_reason_and_that_nothing_changed(self, monkeypatch, capsys, tmp_path):
+ from hermes_cli import setup as setup_mod
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+
+ def _boom(*_a, **_k):
+ raise httpx.ConnectError("[Errno -2] Name or service not known")
+
+ monkeypatch.setattr("hermes_cli.main.select_provider_and_model", _boom)
+ monkeypatch.setattr(setup_mod, "print_header", lambda *_a, **_k: None)
+ monkeypatch.setattr(setup_mod, "_info", lambda *_a, **_k: None)
+ monkeypatch.setattr("hermes_cli.config.load_config", lambda: {})
+ setup_mod.setup_model_provider({}, quick=True)
+
+ out = capsys.readouterr().out
+ assert "Could not finish connecting a provider" in out
+ assert "internet" in out
+ assert "not changed" in out or "Nothing was saved" in out
+ assert "hermes model" in out
+ assert "encountered an error" not in out and "Errno" not in out.split("Details:")[0]
+
+ def test_quick_setup_error_hook_uses_same_copy(self, capsys):
+ from hermes_cli.auth_error_copy import provider_setup_failure_lines
+
+ lines = provider_setup_failure_lines(RuntimeError("keyring locked"), retry_command="hermes portal")
+ assert lines[0].startswith("Could not finish connecting a provider")
+ assert "hermes portal" in " ".join(lines)
+ assert any(line.strip().startswith("Details:") for line in lines)
+
+
+class TestRunLoginProviderAwareCopy:
+ def test_minimax_failure_names_minimax_retry_not_portal(self, capsys):
+ from hermes_cli.auth import PROVIDER_REGISTRY
+ from hermes_cli.model_setup_flows_common import _run_login
+
+ def _boom(*_a, **_k):
+ raise httpx.ConnectError("[Errno -2] Name or service not known")
+
+ assert _run_login(_boom, SimpleNamespace(), PROVIDER_REGISTRY["minimax-oauth"]) is False
+ out = capsys.readouterr().out
+ assert "hermes auth add minimax-oauth" in out
+ assert "hermes portal" not in out and "portal.nousresearch.com" not in out
+ assert "hermes login" not in out
+
+ def test_nous_failure_keeps_portal_retry(self, capsys):
+ from hermes_cli.auth import PROVIDER_REGISTRY
+ from hermes_cli.model_setup_flows_common import _run_login
+
+ def _boom(*_a, **_k):
+ raise httpx.ConnectError("boom")
+
+ assert _run_login(_boom, SimpleNamespace(), PROVIDER_REGISTRY["nous"]) is False
+ out = capsys.readouterr().out
+ assert "hermes portal" in out and "portal.nousresearch.com" in out
+
+ def test_silent_nonzero_system_exit_still_tells_user_how_to_retry(self, capsys):
+ from hermes_cli.auth import PROVIDER_REGISTRY
+ from hermes_cli.model_setup_flows_common import _run_login
+
+ def _quiet_exit(*_a, **_k):
+ raise SystemExit(1)
+
+ assert _run_login(_quiet_exit, SimpleNamespace(), PROVIDER_REGISTRY["openai-codex"]) is False
+ out = capsys.readouterr().out
+ assert "Sign-in did not complete" in out and "hermes auth add openai-codex" in out
+
+ def test_system_exit_with_message_surfaces_the_message(self, capsys):
+ from hermes_cli.model_setup_flows_common import _run_login
+
+ def _exit_msg(*_a, **_k):
+ raise SystemExit("token endpoint returned 400")
+
+ assert _run_login(_exit_msg) is False
+ out = capsys.readouterr().out
+ assert "token endpoint returned 400" in out and "hermes model" in out
+
+ def test_cancel_codes_stay_a_single_cancel_line(self, capsys):
+ from hermes_cli.model_setup_flows_common import _run_login
+
+ def _cancel(*_a, **_k):
+ raise SystemExit(130)
+
+ assert _run_login(_cancel) is False
+ out = capsys.readouterr().out
+ assert "cancelled" in out.lower() and "did not complete" not in out
diff --git a/tests/hermes_cli/test_ux_messages_chat_sessions.py b/tests/hermes_cli/test_ux_messages_chat_sessions.py
new file mode 100644
index 00000000000..cd2813d3cfb
--- /dev/null
+++ b/tests/hermes_cli/test_ux_messages_chat_sessions.py
@@ -0,0 +1,132 @@
+"""Plain-language contracts for chat/session failure copy (CLI UX message campaign, cluster D).
+
+Each test asserts the CONTRACT (what happened + the exact command pointer, raw detail demoted to a
+``Details:`` line), never the whole string.
+"""
+
+import pytest
+
+from hermes_cli.active_sessions import session_already_owned_message
+from hermes_cli.cli_chat_error_copy import agent_init_failure_message, chat_error_response
+from hermes_cli.cli_unknown_command import unknown_command_lines
+
+
+class _StatusError(Exception):
+ def __init__(self, message: str, status_code: int):
+ super().__init__(message)
+ self.status_code = status_code
+
+
+# ── cli-02: failed model request in the chat panel ──────────────────────────
+
[email protected]("exc, pointer, absent", [
+ (_StatusError("HTTP 401: Invalid API key", 401), "hermes model", "HTTP 401"),
+ (Exception("Error code: 402 - insufficient credits"), "/model", "402"),
+ (Exception("HTTP 404: model not found"), "/model", "HTTP 404"),
+ (_StatusError("rate limit exceeded", 429), "/model", "429"),
+ (Exception("Unknown error"), "hermes doctor", "Unknown error"),
+])
+def test_chat_error_response_leads_with_plain_copy_and_pointer(exc, pointer, absent):
+ text = chat_error_response(exc, provider="openrouter", model="foo/bar")
+ lead = text.splitlines()[0]
+ assert pointer in lead
+ assert absent not in lead, "raw HTTP code/exception text must not be the lead sentence"
+ assert not lead.startswith("Error:")
+ assert "Details: " in text and str(exc) in text
+
+
+def test_chat_error_response_names_provider_and_model():
+ text = chat_error_response(Exception("HTTP 404: model not found"), provider="openrouter", model="foo/bar")
+ assert "foo/bar" in text.splitlines()[0]
+ assert "openrouter" in text.splitlines()[0]
+
+
+def test_chat_error_response_accepts_plain_string_summary():
+ text = chat_error_response("HTTP 401: Invalid API key", provider="nous", model="m")
+ assert "hermes model" in text.splitlines()[0]
+
+
+def test_chat_error_response_trusts_stamped_provider_verdict_over_reclassifying_text():
+ # The loop stamped 'rate_limit'; the summarised text alone would classify as unknown.
+ text = chat_error_response("upstream said no", provider="openrouter", model="m", failure_reason="rate_limit")
+ assert "Rate limited" in text.splitlines()[0]
+ assert "Details: upstream said no" in text
+
+
+def test_chat_error_response_returns_site_copy_verbatim_instead_of_double_wrapping():
+ curated = "The model's reply was cut off before it finished. Send `continue`."
+ text = chat_error_response(curated, provider="openrouter", model="m", failure_reason="truncated")
+ assert text == curated
+ assert "Details:" not in text
+
+
+# ── cli-06: agent could not be built on first message ──────────────────────
+
+def test_agent_init_failure_message_says_message_not_sent_and_points_to_doctor():
+ exc = RuntimeError("Unsupported api_mode 'weird' for provider x\nsecond line of traceback noise " + "x" * 300)
+ text = agent_init_failure_message(exc)
+ assert "not sent" in text
+ assert "hermes doctor" in text and "/model" in text
+ assert not text.startswith("Failed to initialize agent")
+ assert "second line" not in text, "only the first line of the exception is shown"
+ assert len(text) < 400, "the exception summary is truncated"
+
+
+# ── cli-11: session held by another window ─────────────────────────────────
+
+def test_owned_message_first_line_is_plain_and_details_follow():
+ message = session_already_owned_message("session-1", {
+ "surface": "desktop", "pid": 123, "started_at": 1,
+ })
+ first, *rest = message.splitlines()
+ assert first == ("This chat is open in another Hermes window/terminal. "
+ "Use it there, or start a new chat here.")
+ for jargon in ("lease", "pid", "owner", "takeover"):
+ assert jargon not in first.lower()
+ assert rest and rest[0].startswith("Details: ")
+ assert "desktop" in rest[0]
+
+
+# ── cli-30: hermes sessions with a bad id / unopenable DB ──────────────────
+
+def test_sessions_not_found_points_to_list(capsys):
+ from hermes_cli.sessions_cmd import _not_found
+ assert _not_found("abc") == 1
+ out = capsys.readouterr().out
+ assert "No session 'abc'" in out
+ assert "hermes sessions list" in out
+
+
+def test_sessions_db_open_failure_points_to_repair(monkeypatch, capsys):
+ import hermes_cli.sessions_cmd as sessions_cmd
+
+ class _Boom:
+ def __init__(self, *a, **k):
+ raise RuntimeError("database disk image is malformed")
+
+ monkeypatch.setattr("hermes_state.SessionDB", _Boom)
+ import argparse
+ parser = argparse.ArgumentParser()
+ args = argparse.Namespace(sessions_action="list", session_id=None)
+ code = sessions_cmd.cmd_sessions(args, parser)
+ out = capsys.readouterr().out
+ assert code == 1
+ assert "hermes sessions repair" in out
+ assert out.splitlines()[0].startswith("Could not open your session history database")
+ assert "Details: database disk image is malformed" in out
+
+
+# ── cli-31: unknown slash command ──────────────────────────────────────────
+
+def test_unknown_command_suggests_close_match_and_says_nothing_sent():
+ lead, pointer = unknown_command_lines("/modle", {"/model", "/help", "/quit"})
+ assert "/modle" in lead
+ assert "nothing was sent" in lead
+ assert "Did you mean /model?" in lead
+ assert "/help" in pointer
+
+
+def test_unknown_command_without_close_match_has_no_suggestion():
+ lead, pointer = unknown_command_lines("/zzzzzz", {"/model", "/help"})
+ assert "Did you mean" not in lead
+ assert "/help" in pointer
diff --git a/tests/hermes_cli/test_ux_messages_gateway_profiles.py b/tests/hermes_cli/test_ux_messages_gateway_profiles.py
new file mode 100644
index 00000000000..b0892c5da38
--- /dev/null
+++ b/tests/hermes_cli/test_ux_messages_gateway_profiles.py
@@ -0,0 +1,120 @@
+"""Invariant tests for the user-facing copy of gateway/profile/update-lock failures.
+
+Contract, not snapshots: each message leads with plain words (never a raw exception), names the
+next command, and every ``hermes <sub> <cmd>`` it cites is a registered subcommand.
+"""
+
+import subprocess
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_cli import gateway as gateway_cli
+from hermes_cli import profiles
+from hermes_cli.update_lock import UpdateHolder, describe_holder
+
+
+# --- cli-05: gateway start/stop/restart failures leave gateway_command() as guidance ------------
+
+
+def _run_gateway_command_raising(monkeypatch, capsys, exc):
+ monkeypatch.setattr(gateway_cli, "_gateway_command_inner", lambda args: (_ for _ in ()).throw(exc))
+ with pytest.raises(SystemExit) as info:
+ gateway_cli.gateway_command(SimpleNamespace(gateway_command="start"))
+ assert info.value.code == 1
+ return capsys.readouterr().out
+
+
+def test_systemctl_failure_is_explained_not_tracebacked(monkeypatch, capsys):
+ exc = subprocess.CalledProcessError(1, ["systemctl", "--user", "start", "hermes-gateway"])
+ out = _run_gateway_command_raising(monkeypatch, capsys, exc)
+ assert not out.lstrip().startswith("Command '")
+ assert "hermes gateway status --deep" in out
+ assert "hermes gateway install --force" in out
+ assert "journalctl" in out
+ # The raw detail survives as a secondary line, not the lead sentence.
+ assert "Details:" in out
+
+
+def test_missing_systemctl_points_at_foreground_run(monkeypatch, capsys):
+ def fake_run(cmd, **kwargs):
+ raise FileNotFoundError("systemctl")
+
+ monkeypatch.setattr(gateway_cli.subprocess, "run", fake_run)
+ with pytest.raises(RuntimeError) as info:
+ gateway_cli._run_systemctl(["start", "hermes-gateway"])
+ out = _run_gateway_command_raising(monkeypatch, capsys, info.value)
+ assert "hermes gateway run" in out
+ assert "systemd" in out
+ assert not out.lstrip().startswith("systemctl is not available")
+
+
+# --- cli-15: already-running guard and no-backend copy ---------------------------------------
+
+
+def test_existing_gateway_guard_says_bots_are_online_and_names_status(monkeypatch, capsys):
+ import gateway.status as status_mod
+
+ monkeypatch.setattr(gateway_cli, "_running_under_gateway_supervisor", lambda: False)
+ monkeypatch.setattr(status_mod, "get_running_pid", lambda: 12345)
+ with pytest.raises(SystemExit):
+ gateway_cli._guard_existing_gateway_process_conflict()
+ out = capsys.readouterr().out
+ assert "12345" in out
+ assert "online" in out
+ for cmd in ("hermes gateway status", "hermes gateway restart", "hermes gateway stop"):
+ assert cmd in out
+ assert "Another gateway instance" not in out
+
+
[email protected]("subcommand", ["start", "uninstall"])
+def test_unsupported_platform_copy_says_what_is_unsupported(subcommand):
+ _code, *lines = gateway_cli._NO_BACKEND_MESSAGES[(subcommand, "unsupported")]
+ text = "\n".join(lines)
+ assert text != "Not supported on this platform."
+ assert "background service" in text
+ assert "hermes gateway run" in text or subcommand == "uninstall"
+
+
+# --- cli-13 / cli-14: profile name errors -----------------------------------------------------
+
+
+def test_invalid_profile_name_explains_rule_in_words_with_example():
+ with pytest.raises(ValueError) as info:
+ profiles.validate_profile_name("My Work")
+ msg = str(info.value)
+ assert "Must match" not in msg and "[a-z0-9]" not in msg
+ assert "lowercase" in msg
+ assert "my-work" in msg
+ assert "hermes profile create my-work" in msg
+
+
+def test_existing_profile_error_offers_use_and_list(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ profiles.create_profile("work", no_alias=True, no_skills=True)
+ with pytest.raises(FileExistsError) as info:
+ profiles.create_profile("work", no_alias=True, no_skills=True)
+ msg = str(info.value)
+ assert "already exists at" not in msg
+ assert "hermes profile use work" in msg
+ assert "hermes profile list" in msg
+
+
+def test_missing_profile_error_points_at_list(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))
+ with pytest.raises(FileNotFoundError) as info:
+ profiles.delete_profile("wrk")
+ msg = str(info.value)
+ assert "No profile named 'wrk'" in msg
+ assert "hermes profile list" in msg
+
+
+# --- cli-28: concurrent update refusal ---------------------------------------------------------
+
+
+def test_describe_holder_avoids_jargon_and_names_next_steps():
+ message = describe_holder(UpdateHolder(pid=4242, age_seconds=190))
+ assert "4242" in message and "3m 10s" in message
+ assert "PID" not in message and "checkout" not in message
+ assert "hermes logs" in message
+ assert "hermes update" in message
diff --git a/tests/hermes_cli/test_ux_messages_startup.py b/tests/hermes_cli/test_ux_messages_startup.py
new file mode 100644
index 00000000000..27cd984aed6
--- /dev/null
+++ b/tests/hermes_cli/test_ux_messages_startup.py
@@ -0,0 +1,163 @@
+"""Invariant tests for the plain-language startup messages of the ``hermes`` CLI.
+
+Contracts (not snapshots): a mistyped subcommand names the typo, offers the closest
+match and ``hermes --help`` without dumping the 70-entry choice list; a rejected
+profile name explains the rule; missing optional dependencies point at ``hermes update``.
+"""
+
+import io
+import sys
+from contextlib import redirect_stderr, redirect_stdout
+from types import SimpleNamespace
+
+import pytest
+
+from hermes_cli._parser import build_top_level_parser
+
+
+def _parse_error(argv: list[str]) -> str:
+ parser, subparsers, _chat = build_top_level_parser()
+ for name in ("sessions", "model", "profile"):
+ subparsers.add_parser(name)
+ gw = subparsers.add_parser("gateway").add_subparsers(dest="gateway_action", metavar="<action>")
+ for name in ("start", "stop", "status"):
+ gw.add_parser(name)
+ err = io.StringIO()
+ with redirect_stderr(err), pytest.raises(SystemExit) as exc:
+ parser.parse_args(argv)
+ assert exc.value.code == 2
+ return err.getvalue()
+
+
+def test_unknown_subcommand_names_typo_suggests_closest_and_hides_choice_list():
+ text = _parse_error(["sesions"])
+ assert "'sesions' is not a `hermes` command" in text
+ assert "Did you mean: sessions" in text
+ assert "hermes --help" in text
+ assert "choose from" not in text
+ assert "invalid choice" not in text
+
+
+def test_unknown_subcommand_without_close_match_still_points_at_help():
+ text = _parse_error(["zzqx"])
+ assert "'zzqx' is not a `hermes` command" in text
+ assert "Did you mean" not in text
+ assert "hermes --help" in text
+
+
+def test_nested_group_typo_names_the_group_and_suggests():
+ text = _parse_error(["gateway", "stat"])
+ assert "'stat' is not a `hermes gateway` command" in text
+ assert "Did you mean:" in text and "status" in text
+
+
+def test_non_choice_errors_keep_argparse_usage_line():
+ text = _parse_error(["--no-such-flag"])
+ assert text.startswith("usage: hermes")
+ assert "--no-such-flag" in text
+
+
+def test_top_level_usage_hides_subcommand_brace_list():
+ parser, _sub, _chat = build_top_level_parser()
+ assert "{chat" not in parser.format_usage()
+ assert "<command>" in parser.format_usage()
+
+
+def test_invalid_profile_flag_value_explains_rule_and_exits(monkeypatch):
+ from hermes_cli import main as _main
+
+ monkeypatch.setattr(sys, "argv", ["hermes", "-p", "Work Bot", "status"])
+ err = io.StringIO()
+ with redirect_stderr(err), pytest.raises(SystemExit) as exc:
+ _main._apply_profile_override()
+ assert exc.value.code == 2
+ text = err.getvalue()
+ assert "'Work Bot' is not a valid profile name" in text
+ assert "hermes profile list" in text
+ assert "Must match" not in text
+
+
+def test_pytest_style_dash_p_is_still_ignored(monkeypatch):
+ from hermes_cli import main as _main
+
+ monkeypatch.setattr(sys, "argv", ["pytest", "-p", "no:xdist", "tests/"])
+ assert _main._scan_profile_flag(sys.argv[1:]) == (None, 0, None)
+
+
+def test_option_looking_dash_p_value_is_a_silent_skip_even_under_hermes(monkeypatch):
+ from hermes_cli import main as _main
+
+ # `-p no:xdist` reaching us through a differently named runner (tox, nox, python -m) must not exit.
+ monkeypatch.setattr(sys, "argv", ["hermes", "-p", "no:xdist", "tests/"])
+ assert _main._scan_profile_flag(sys.argv[1:]) == (None, 0, None)
+ monkeypatch.setattr(sys, "argv", ["hermes", "-p", "--flag"])
+ assert _main._scan_profile_flag(sys.argv[1:]) == (None, 0, None)
+
+
+def test_title_cased_profile_label_is_normalised_not_rejected(monkeypatch):
+ from hermes_cli import main as _main
+
+ assert _main._scan_profile_flag(["-p", " Work ", "status"]) == ("work", 2, 0)
+ assert _main._scan_profile_flag(["--profile=Work", "status"]) == ("work", 1, 0)
+
+
+def test_invalid_dash_p_after_a_subcommand_is_left_to_that_subcommand(monkeypatch):
+ from hermes_cli import main as _main
+
+ # A plugin/subcommand flag such as `hermes kanban serve -p "Work Bot"` is not our profile selector.
+ monkeypatch.setattr(sys, "argv", ["hermes", "kanban", "serve", "-p", "Work Bot"])
+ assert _main._scan_profile_flag(sys.argv[1:]) == (None, 0, None)
+
+
+def test_bare_continue_with_no_session_names_the_next_step(monkeypatch):
+ from hermes_cli import main as _main
+
+ monkeypatch.setattr(_main, "_latest_session_id", lambda _tui: None)
+ monkeypatch.setattr(
+ "hermes_cli.terminal_breadcrumbs.resolve_breadcrumb_session", lambda: None, raising=False
+ )
+ out = io.StringIO()
+ args = SimpleNamespace(continue_last=True, resume=None, create_if_missing=False)
+ with redirect_stdout(out), redirect_stderr(out), pytest.raises(SystemExit):
+ _main._resolve_continue_arg(args, use_tui=False)
+ text = out.getvalue()
+ assert "hermes sessions list" in text
+ assert "No previous CLI session" in text
+
+
+def test_model_picker_does_not_warn_about_missing_provider(monkeypatch, capsys):
+ from hermes_cli import main as _main
+ from hermes_cli.auth import AuthError
+
+ def _raise(_slug):
+ raise AuthError("nothing configured", code="no_provider_configured")
+
+ monkeypatch.setattr("hermes_cli.auth.resolve_provider", _raise)
+ active = _main._resolve_active_provider({}, {}, "auto", {})
+ out = capsys.readouterr().out
+ assert active is None
+ assert "Warning" not in out
+ assert "Falling back to auto provider detection" not in out
+ assert "pick one below" in out
+
+
+def test_missing_dashboard_deps_point_at_hermes_update():
+ from hermes_cli.main_dep_hints import missing_optional_deps_message
+
+ text = missing_optional_deps_message("dashboard", "its web-server packages", "all")
+ assert "hermes update" in text
+ assert "-m pip install -e '.[all]'" in text
+ assert "metadata" not in text
+
+
+def test_missing_node_message_names_cli_fallback(monkeypatch, capsys):
+ from hermes_cli import main_tui_launch as _tui
+
+ monkeypatch.setattr("hermes_constants.find_node_executable", lambda _b: None)
+ monkeypatch.setattr("hermes_cli.dep_ensure.ensure_dependency", lambda _n: False, raising=False)
+ monkeypatch.delenv("HERMES_NODE", raising=False)
+ with pytest.raises(SystemExit):
+ _tui._tui_node_bin("node")
+ text = capsys.readouterr().out
+ assert "hermes --cli" in text
+ assert "Node.js" in text
diff --git a/tests/hermes_state/test_hermes_state.py b/tests/hermes_state/test_hermes_state.py
index 8b78aa7aac6..784ba26e97b 100644
--- a/tests/hermes_state/test_hermes_state.py
+++ b/tests/hermes_state/test_hermes_state.py
@@ -5396,12 +5396,12 @@ class TestGetMessagesPagination:
assert db.get_resume_message_count("seg-5", tip_only=True) == 4
with pytest.raises(hermes_state.SessionResumeTooLargeError) as full:
db.assert_resume_safe("seg-5", max_messages=10)
- assert "across its lineage" in str(full.value)
+ assert full.value.scope == "across its lineage"
assert db.assert_resume_safe("seg-5", max_messages=10, tip_only=True) == 4
with pytest.raises(hermes_state.SessionResumeTooLargeError) as tip:
db.assert_resume_safe("seg-5", max_messages=3, tip_only=True)
assert tip.value.message_count == 4
- assert "in its tip segment" in str(tip.value)
+ assert tip.value.scope == "in its tip segment"
def test_resume_guard_counts_exactly_what_a_branch_resume_loads(self, db):
"""An explicit /branch copy owns its transcript: the guard and the
diff --git a/tests/hermes_state/test_hermes_state_ux_messages.py b/tests/hermes_state/test_hermes_state_ux_messages.py
new file mode 100644
index 00000000000..76ae16bd970
--- /dev/null
+++ b/tests/hermes_state/test_hermes_state_ux_messages.py
@@ -0,0 +1,63 @@
+"""Plain-language contracts for hermes_state user-facing errors (CLI UX message campaign, cluster D)."""
+
+import hermes_state
+from hermes_state import SessionResumeTooLargeError, format_session_db_unavailable
+
+
+def test_resume_too_large_names_export_and_config_commands():
+ text = str(SessionResumeTooLargeError(4312, 4000))
+ assert "4312" in text and "4000" in text
+ assert "hermes sessions export" in text
+ assert "hermes config set sessions.max_resume_messages 0" in text
+ for jargon in ("lineage", "guard", "safe resume limit"):
+ assert jargon not in text
+
+
+def test_resume_too_large_keeps_structured_fields():
+ exc = SessionResumeTooLargeError(20_001, 20_000, scope="in its tip segment")
+ assert (exc.message_count, exc.limit) == (20_001, 20_000)
+ assert isinstance(exc, ValueError)
+
+
+def test_db_unavailable_points_to_doctor_without_sqlite_internals():
+ hermes_state._set_last_init_error("OperationalError: database is locked")
+ try:
+ text = format_session_db_unavailable(details=True)
+ finally:
+ hermes_state._set_last_init_error(None)
+ lead, *rest = text.splitlines()
+ assert "session history" in lead
+ assert "will not be saved" in lead.lower()
+ for internal in ("sqlite.org", "WAL", "NFS/SMB/FUSE/ZFS"):
+ assert internal not in lead
+ assert rest and rest[0].startswith("Details: ") and "database is locked" in rest[0]
+
+
+def test_db_unavailable_is_one_line_for_chat_surfaces_by_default():
+ hermes_state._set_last_init_error("OperationalError: database is locked")
+ try:
+ text = format_session_db_unavailable(prefix="Cannot resume")
+ finally:
+ hermes_state._set_last_init_error(None)
+ assert "\n" not in text
+ assert "Details:" not in text
+ assert text.startswith("Cannot resume:")
+
+
+def test_db_unavailable_unknown_cause_on_network_drive_points_at_moving_not_doctor_fix():
+ hermes_state._set_last_init_error("OperationalError: locking protocol")
+ try:
+ text = format_session_db_unavailable()
+ finally:
+ hermes_state._set_last_init_error(None)
+ assert "network" in text
+ assert "local disk" in text
+ assert "hermes doctor --fix" not in text
+
+
+def test_db_unavailable_without_cause_still_names_doctor():
+ hermes_state._set_last_init_error(None)
+ text = format_session_db_unavailable(details=True)
+ assert "hermes doctor" in text
+ assert "will not be saved" in text.lower()
+ assert "Details:" not in text
diff --git a/tests/hermes_state/test_hermes_state_wal_fallback.py b/tests/hermes_state/test_hermes_state_wal_fallback.py
index f993dea24a6..5ca78dcbbaf 100644
--- a/tests/hermes_state/test_hermes_state_wal_fallback.py
+++ b/tests/hermes_state/test_hermes_state_wal_fallback.py
@@ -589,22 +589,37 @@ class TestFormatSessionDbUnavailable:
def test_bare_message_when_no_cause(self):
"""No init error recorded → generic message."""
hermes_state._set_last_init_error(None)
- assert format_session_db_unavailable() == "Session database not available."
-
+ msg = format_session_db_unavailable()
+ assert "hermes doctor" in msg
+ assert "Details:" not in msg
def test_adds_nfs_hint_for_locking_protocol(self):
- """Locking-protocol cause gets an NFS/SMB pointer for the user."""
+ """Locking-protocol cause gets a network-drive pointer for the user."""
hermes_state._set_last_init_error("OperationalError: locking protocol")
+ msg = format_session_db_unavailable(details=True)
+ # The raw sqlite phrase stays in the Details line; the user gets the network-drive cause and
+ # a move-it action (`hermes doctor --fix` cannot repair a mount; a WAL-docs link is not
+ # something a chat user can act on).
+ lead, details = msg.splitlines()
+ assert "network" in lead
+ assert "local disk" in lead
+ assert "hermes doctor --fix" not in lead
+ assert details.startswith("Details: ") and "locking protocol" in details
+ assert "sqlite.org" not in msg
+
+ def test_known_bucket_keeps_table_action_and_appends_network_hint(self):
+ """disk i/o error is a known bucket: its table action stays, the network hint is appended."""
+ hermes_state._set_last_init_error("OperationalError: disk I/O error")
msg = format_session_db_unavailable()
- assert "locking protocol" in msg
- assert "NFS/SMB" in msg
- assert "sqlite.org/wal.html" in msg
+ assert "network drive" in msg
+ assert "\n" not in msg
def test_custom_prefix(self):
"""Callers can customize the prefix for context-specific messages."""
hermes_state._set_last_init_error("OperationalError: locking protocol")
msg = format_session_db_unavailable(prefix="Cannot /resume")
assert msg.startswith("Cannot /resume:")
+ assert "Details:" not in msg
class TestSessionDbUsesWalFallback:
diff --git a/tests/hermes_state/test_named_profile_session_db.py b/tests/hermes_state/test_named_profile_session_db.py
index 7513e4b75e4..11bb9b8e8a3 100644
--- a/tests/hermes_state/test_named_profile_session_db.py
+++ b/tests/hermes_state/test_named_profile_session_db.py
@@ -155,7 +155,7 @@ def test_deferred_build_fails_closed_when_profile_store_unopenable(homes, monkey
assert session.get("agent") is None
assert "profile session store unavailable" in str(session.get("agent_error"))
assert any(
- evt == "error" and "agent init failed" in str((payload or {}).get("message"))
+ evt == "error" and "could not start the assistant" in str((payload or {}).get("message"))
for evt, _s, payload in events
)
# And nothing bled into the launch store.
diff --git a/tests/hermes_state/test_storage_failure_copy.py b/tests/hermes_state/test_storage_failure_copy.py
new file mode 100644
index 00000000000..0a6fb9de249
--- /dev/null
+++ b/tests/hermes_state/test_storage_failure_copy.py
@@ -0,0 +1,35 @@
+"""One copy table for "session storage unavailable / not written" across CLI, gateway and RPC.
+
+Contract: the user gets a plain cause + the exact repair command, never the raw sqlite text as the
+lead, plus a stable machine-readable `code` a GUI can key a "Run doctor" button on.
+"""
+
+import sqlite3
+
+import pytest
+
+from hermes_state_user_copy import describe_storage_failure, storage_failure_details
+
+
+ ("exc", "code", "command"),
+ [
+ (sqlite3.OperationalError("database is locked"), "storage_locked", "try again"),
+ (sqlite3.OperationalError("attempt to write a readonly database"), "storage_readonly", "hermes doctor --fix"),
+ (sqlite3.DatabaseError("database disk image is malformed"), "storage_corrupt", "hermes doctor --fix"),
+ (OSError(28, "No space left on device"), "disk_full", "Free some disk space"),
+ (None, "storage_unavailable", "hermes doctor --fix"),
+ ],
+)
+def test_each_cause_has_a_stable_code_and_an_action(exc, code, command):
+ failure = describe_storage_failure(exc)
+ assert failure.code == code
+ assert command in failure.action
+ assert failure.gloss and failure.gloss[0].islower() # a clause that follows "Cause:"
+ # The raw sqlite wording never leaks into the user-facing gloss.
+ assert "sqlite" not in failure.gloss.lower() and "OperationalError" not in failure.gloss
+
+
+def test_details_line_is_flattened_and_bounded():
+ details = storage_failure_details("line one\n line two " + "x" * 400, limit=60)
+ assert "\n" not in details and len(details) == 60 and details.endswith("...")
diff --git a/tests/test_utils_atomic_roundtrip_yaml_save.py b/tests/test_utils_atomic_roundtrip_yaml_save.py
index ff89258b814..729182ca7d0 100644
--- a/tests/test_utils_atomic_roundtrip_yaml_save.py
+++ b/tests/test_utils_atomic_roundtrip_yaml_save.py
@@ -248,7 +248,7 @@ class TestAtomicRoundtripYamlSave:
from utils import atomic_roundtrip_yaml_save
with patch("builtins.open", side_effect=self._deny_config_reads(config_path)):
- with pytest.raises(RuntimeError, match="Refusing to overwrite"):
+ with pytest.raises(RuntimeError, match="this change was not saved"):
atomic_roundtrip_yaml_save(config_path, {"model": {"default": "replacement"}})
assert config_path.read_text(encoding="utf-8") == original
diff --git a/tests/tools/test_approval_user_summary.py b/tests/tools/test_approval_user_summary.py
new file mode 100644
index 00000000000..02a5248c41d
--- /dev/null
+++ b/tests/tools/test_approval_user_summary.py
@@ -0,0 +1,83 @@
+"""Approval and background-task outcomes carry one plain sentence for the person at the keyboard.
+
+The model-facing ``BLOCKED: ... Do NOT retry`` text is unchanged; surfaces render ``user_summary``
+first (UX message audit, findings tools-runtime-15, -26, -31).
+"""
+
+from __future__ import annotations
+
+import json
+
+
+def test_denied_result_carries_a_user_summary_beside_the_model_text(monkeypatch):
+ from tools import approval
+ monkeypatch.setattr("tools.approval_context._get_approval_timeout", lambda: 300)
+ res = approval._denied("BLOCKED: User denied this command. Do NOT retry.", pattern_key="rm",
+ description="delete files", outcome="denied")
+ assert res["message"].startswith("BLOCKED") # model contract untouched
+ assert res["user_summary"] == "You denied this command — it did not run."
+ timed = approval._denied("BLOCKED: timed out", pattern_key="rm", description="d", outcome="timeout", noun="code")
+ assert "5 minutes" in timed["user_summary"] and "did not run" in timed["user_summary"]
+ assert "BLOCKED" not in timed["user_summary"] and "NOT" not in timed["user_summary"]
+
+
+def test_cli_completion_line_prefers_user_summary_over_blocked_text():
+ from agent.display import _detect_tool_failure
+ result = json.dumps({"output": "", "exit_code": -1, "status": "blocked",
+ "error": "BLOCKED: User denied this command. The user has NOT consented ...",
+ "user_summary": "You denied this command — it did not run."})
+ failed, suffix = _detect_tool_failure("terminal", result)
+ assert failed and "You denied this command" in suffix and "BLOCKED" not in suffix
+
+
+def test_timeout_notice_names_wait_and_config_command(monkeypatch):
+ from agent.i18n import t
+ from tools import approval_context as ctx
+ monkeypatch.setattr(ctx, "_get_approval_timeout", lambda: 300)
+ text = t("approval.timeout", **ctx.approval_timeout_notice_kwargs())
+ assert "5 minutes" in text and "was not run" in text
+ assert "hermes config set approvals.timeout 900" in text
+ assert "{" not in text # every placeholder filled
+
+
+def test_stalled_delegation_text_has_no_issue_numbers_or_worker_jargon():
+ from tools.async_delegation import _stalled_error_text
+ text = _stalled_error_text({"goal": "Summarise the weekly report", "_stall_quiet_seconds": 610.0})
+ assert text.startswith('Background task "Summarise the weekly report"')
+ assert "10 min" in text and "run it again" in text
+ for banned in ("#60203", "completion event", "wedged", "Re-dispatch", "delegation"):
+ assert banned not in text
+
+
+def test_prompt_title_reaches_the_plain_prompt_and_only_title_aware_callbacks(monkeypatch, capsys):
+ from tools import approval_prompt as ap
+ seen = {}
+
+ def legacy_cb(command, description, *, allow_permanent=True):
+ seen["legacy"] = (command, description)
+ return "once"
+
+ def aware_cb(command, description, *, allow_permanent=True, title=None):
+ seen["title"] = title
+ return "once"
+
+ assert ap.prompt_dangerous_approval("x", "d", approval_callback=legacy_cb, title="Save to memory?") == "once"
+ assert ap.prompt_dangerous_approval("x", "d", approval_callback=aware_cb, title="Save to memory?") == "once"
+ assert seen["title"] == "Save to memory?"
+
+ monkeypatch.setattr(ap, "_read_choice", lambda *_a, **_k: "d")
+ monkeypatch.setattr("prompt_toolkit.application.current.get_app_or_none", lambda: None)
+ ap.prompt_dangerous_approval("x", "d", title="MCP server 'gh' is asking")
+ out = capsys.readouterr().out
+ assert "MCP server 'gh' is asking" in out and "DANGEROUS COMMAND" not in out
+
+
+def test_every_surface_renders_the_timeout_window_with_one_formatter(monkeypatch):
+ """CLI notice, tool user_summary and gateway card must agree on the wording of the same window."""
+ from tools import approval, approval_context as ctx
+ from gateway.platforms.base_exec_approval import format_approval_timed_out_notice
+ monkeypatch.setattr(ctx, "_get_approval_timeout", lambda: 90)
+ window = ctx.format_approval_window(90)
+ assert window in ctx.approval_timeout_notice_kwargs()["waited"]
+ assert window in approval._user_summary("timeout")
+ assert window in format_approval_timed_out_notice(90)
diff --git a/tests/tools/test_async_delegation.py b/tests/tools/test_async_delegation.py
index 8437c61c41d..74701f39048 100644
--- a/tests/tools/test_async_delegation.py
+++ b/tests/tools/test_async_delegation.py
@@ -322,7 +322,7 @@ def test_stalled_runner_is_interrupted_then_finalized(monkeypatch):
assert evt["status"] == "stalled"
assert evt["delegation_id"] == res["delegation_id"]
assert evt["api_calls"] == 0
- assert "stalled" in evt["error"]
+ assert "stopped responding" in evt["error"] # status carries "stalled"; the text is for the user
# Interrupt was requested BEFORE force-finalization (grace window).
assert interrupted["count"] >= 1
assert ad.active_count() == 0
diff --git a/tests/tools/test_delegate_failure_copy.py b/tests/tools/test_delegate_failure_copy.py
new file mode 100644
index 00000000000..eefbd7f4a89
--- /dev/null
+++ b/tests/tools/test_delegate_failure_copy.py
@@ -0,0 +1,29 @@
+"""Subagent failure lines gloss the classified `failure_reason` instead of echoing the child's raw
+exception, and always name the next step (/agents). Contract tests, not snapshots.
+"""
+
+from tools.delegate_tool_progress import describe_subagent_failure, format_subagent_failure_line
+
+
+def test_classified_reason_replaces_raw_exception_text():
+ line = format_subagent_failure_line(
+ "research pricing", "failed", error="Error code: 429 - {'error': 'rate limited'}",
+ duration_seconds=12, failure_reason="rate_limit")
+ assert "rate-limited" in line
+ assert "Error code" not in line and "429" not in line
+ assert "/agents" in line
+
+
+def test_unclassified_failure_keeps_the_cleaned_error_as_cause():
+ assert describe_subagent_failure(None, "Traceback...\nKeyError: 'x'") == "KeyError: 'x'"
+ line = format_subagent_failure_line("g", "failed", error="KeyError: 'x'")
+ assert "KeyError: 'x'" in line and "/agents" in line
+
+
+def test_timeout_line_names_outcome_and_the_timeout_setting_without_duplicating_duration():
+ raw = "Subagent timed out after 600s with 4 API call(s) completed — likely stuck on a slow API call."
+ line = format_subagent_failure_line("scan the repo", "timeout", error=raw, duration_seconds=600)
+ assert "delegation.child_timeout_seconds" in line
+ assert "carry on without it" in line
+ assert line.count("600") == 0 and "10 min" in line
+ assert "API call" not in line
diff --git a/tests/tools/test_terminal_backend_unavailable_reason.py b/tests/tools/test_terminal_backend_unavailable_reason.py
new file mode 100644
index 00000000000..1353b185c2e
--- /dev/null
+++ b/tests/tools/test_terminal_backend_unavailable_reason.py
@@ -0,0 +1,50 @@
+"""Invariant: when a terminal backend's requirements check fails, the human reason is captured so the
+CLI startup notice / doctor can tell the user WHY the terminal tool is missing (tools-runtime-01)."""
+
+import subprocess
+
+import pytest
+
+import tools.terminal_tool as terminal_tool
+import tools.terminal_tool_backends as backends
+
+
[email protected](autouse=True)
+def _reset_reason():
+ backends._last_unavailable_reason = None
+ yield
+ backends._last_unavailable_reason = None
+
+
+def test_docker_binary_missing_captures_reason(monkeypatch):
+ monkeypatch.setitem(backends._BACKEND_SPECS, "docker",
+ {"binary": (lambda: None, "version", backends._BACKEND_SPECS["docker"]["binary"][2])})
+ assert backends._check_requirements("docker", {}) is False
+ reason = backends.terminal_backend_unavailable_reason()
+ assert reason and "Docker" in reason
+
+
+def test_docker_daemon_probe_failure_captures_daemon_reason(monkeypatch):
+ monkeypatch.setitem(backends._BACKEND_SPECS, "docker",
+ {"binary": (lambda: "/usr/bin/docker", "version", "unused")})
+ monkeypatch.setattr(backends.subprocess, "run",
+ lambda *a, **k: subprocess.CompletedProcess(a[0], 1, b"", b""))
+ assert backends._check_requirements("docker", {}) is False
+ assert "daemon is not running" in backends.terminal_backend_unavailable_reason()
+
+
+def test_ssh_unconfigured_captures_reason():
+ assert backends._check_requirements("ssh", {"ssh_host": "", "ssh_user": ""}) is False
+ assert "SSH host and user are not configured" in backends.terminal_backend_unavailable_reason()
+
+
+def test_successful_check_clears_reason():
+ backends._last_unavailable_reason = "stale"
+ assert backends._check_requirements("local", {}) is True
+ assert backends.terminal_backend_unavailable_reason() is None
+
+
+def test_check_terminal_requirements_exception_captures_reason(monkeypatch):
+ monkeypatch.setattr(terminal_tool, "_get_env_config", lambda: (_ for _ in ()).throw(RuntimeError("boom")))
+ assert terminal_tool.check_terminal_requirements() is False
+ assert "boom" in terminal_tool.terminal_backend_unavailable_reason()
diff --git a/tests/tui_gateway/test_lazy_session_regressions.py b/tests/tui_gateway/test_lazy_session_regressions.py
index 55288bd6632..3ffbe551910 100644
--- a/tests/tui_gateway/test_lazy_session_regressions.py
+++ b/tests/tui_gateway/test_lazy_session_regressions.py
@@ -295,8 +295,9 @@ class TestGatewaySurfacesNullResponse:
agent_result, response, history_len=5,
)
- assert "500 Internal Server Error" in response
- assert "/reset" in response
+ # Plain outcome plus the way forward; the raw provider text stays in the log.
+ assert "500 Internal Server Error" not in response
+ assert "/retry" in response and "/new" in response
def test_silent_drop_after_stop_surfaces_hint(self):
diff --git a/tests/tui_gateway/test_protocol.py b/tests/tui_gateway/test_protocol.py
index d94370a1f38..9ba50ac3fc8 100644
--- a/tests/tui_gateway/test_protocol.py
+++ b/tests/tui_gateway/test_protocol.py
@@ -650,7 +650,8 @@ def test_session_resume_rejects_runaway_transcript_before_history_load(
)
assert response["error"]["code"] == 4130
- assert "safe resume limit is 20000" in response["error"]["message"]
+ assert "limit 20000" in response["error"]["message"]
+ assert "hermes sessions export" in response["error"]["message"]
def test_session_resume_deferred_and_omitted_paths_guard_the_tip_only(server, monkeypatch):
diff --git a/tests/tui_gateway/test_session_resume_db_ownership.py b/tests/tui_gateway/test_session_resume_db_ownership.py
index 404a54344b1..547db559880 100644
--- a/tests/tui_gateway/test_session_resume_db_ownership.py
+++ b/tests/tui_gateway/test_session_resume_db_ownership.py
@@ -171,7 +171,9 @@ def test_resume_closes_profile_db_when_reopen_fails(profile_dbs, monkeypatch):
resp = _resume(session_id="s1", profile="work")
assert resp["error"]["code"] == 5000
- assert "resume failed" in resp["error"]["message"]
+ # Plain "could not reopen" lead; the raw cause survives on the Details line.
+ assert "Could not reopen" in resp["error"]["message"]
+ assert "database is locked" in resp["error"]["message"]
assert profile_dbs[0].closed == 1
diff --git a/tests/tui_gateway/test_tui_gateway_server.py b/tests/tui_gateway/test_tui_gateway_server.py
index acc05d8f008..7860a7d560a 100644
--- a/tests/tui_gateway/test_tui_gateway_server.py
+++ b/tests/tui_gateway/test_tui_gateway_server.py
@@ -9128,6 +9128,20 @@ def test_setup_status_answers_from_the_bootstrap_record_once_it_exists(monkeypat
fb.reset_for_tests()
+def test_invalid_params_and_unknown_method_name_the_version_skew_fix():
+ """The only signal of a TUI/backend version mismatch; the lead phrases stay for clients."""
+ resp = server.handle_request({"id": "1", "method": "no.such.method", "params": {}})
+ assert resp["error"]["code"] == -32601
+ assert resp["error"]["message"].startswith("unknown method: no.such.method")
+ assert "hermes update" in resp["error"]["message"]
+
+ resp = server.handle_request(
+ {"id": "2", "method": "session.status", "params": {"session_id": "x", "turn_author": "y"}})
+ assert resp["error"]["code"] == 4000
+ assert resp["error"]["message"].startswith("invalid params for session.status: turn_author")
+ assert "hermes update" in resp["error"]["message"]
+
+
def test_probe_credentials_emits_exact_empty_key_warning():
agent = types.SimpleNamespace(api_key="", provider="openrouter")
@@ -14951,7 +14965,11 @@ def test_prompt_submit_fails_loudly_when_store_unavailable(monkeypatch):
server._sessions.pop("lost-sid", None)
assert resp["error"]["code"] == 5072
- assert "session storage unavailable" in resp["error"]["message"]
+ msg = resp["error"]["message"]
+ assert "not saved" in msg and "hermes doctor --fix" in msg
+ assert "utf-8 decode failure" not in msg # raw cause rides `data.details`, never the lead
+ assert resp["error"]["data"]["code"] == "storage_unavailable"
+ assert "utf-8 decode failure" in resp["error"]["data"]["details"]
@pytest.mark.real_agent_prewarm
@@ -15068,7 +15086,11 @@ def test_session_list_returns_clean_error_when_state_db_is_unavailable(monkeypat
resp = server.handle_request({"id": "1", "method": "session.list", "params": {}})
assert "error" in resp
- assert "state.db unavailable: locking protocol" in resp["error"]["message"]
+ # Plain cause + repair command; the machine-readable code lets a GUI attach "Run doctor".
+ assert "Session storage is unavailable" in resp["error"]["message"]
+ assert "hermes doctor --fix" in resp["error"]["message"]
+ assert resp["error"]["data"]["code"] == "storage_unavailable"
+ assert resp["error"]["data"]["details"] == "locking protocol"
# --------------------------------------------------------------------------
@@ -15103,7 +15125,8 @@ def test_session_delete_returns_db_unavailable_when_no_db(monkeypatch):
assert "error" in resp
assert resp["error"]["code"] == 5036
- assert "state.db unavailable" in resp["error"]["message"]
+ assert "Session storage is unavailable" in resp["error"]["message"]
+ assert resp["error"]["data"]["code"] == "storage_locked"
def test_session_delete_refuses_active_session(monkeypatch):
@@ -16784,8 +16807,13 @@ def test_prompt_submit_surfaces_backend_error_as_visible_text(monkeypatch):
assert complete_events, "expected message.complete to be emitted"
payload = complete_events[-1][2]
assert payload.get("status") == "error"
- assert payload.get("text", "").startswith("Error:")
- assert "kimi-k2.6" in payload.get("text", "")
+ text = payload.get("text", "")
+ # Plain title first, the raw provider body demoted to a Details line, and a next step —
+ # never the bare "Error: <body>" as if it were the assistant's reply.
+ assert not text.startswith("Error:")
+ assert "Details: HTTP 400: invalid model id 'kimi-k2.6'" in text
+ assert "/retry" in text or "/model" in text
+ assert payload.get("error") == "HTTP 400: invalid model id 'kimi-k2.6'"
def test_prompt_submit_preserves_empty_response_without_error(monkeypatch):
diff --git a/tests/tui_gateway/test_user_messages.py b/tests/tui_gateway/test_user_messages.py
new file mode 100644
index 00000000000..371a0e1620a
--- /dev/null
+++ b/tests/tui_gateway/test_user_messages.py
@@ -0,0 +1,61 @@
+"""Behaviour contracts for the user-facing copy the gateway sends to the TUI / Desktop.
+
+Each test asserts the message says WHAT happened and WHICH command to run next, and that
+the lead phrases clients pattern-match on (``session busy``, ``unknown method:``,
+``invalid params for``) survive the rewording.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from tui_gateway import user_messages as um
+
+
+def test_turn_error_text_leads_with_a_plain_title_and_keeps_the_raw_body_on_a_details_line():
+ raw = 'Error code: 401 - {"error": {"message": "Incorrect API key provided", "type": "invalid_request_error"}}'
+ text = um.turn_error_text(raw, {"layer": "auth", "code": "auth", "retryable": False, "provider": "openai"})
+ title, details, hint = text.split("\n")
+
+ assert not title.startswith("Error")
+ assert "401" not in title and "{" not in title
+ assert "API key" in title and "openai" in title
+ assert details.startswith("Details: ") and "Incorrect API key provided" in details
+ assert "/model" in hint and "/retry" in hint
+
+
+def test_turn_error_text_without_a_surface_still_names_the_next_step():
+ text = um.turn_error_text("HTTP 400: invalid model id 'kimi-k2.6'")
+
+ assert "kimi-k2.6" in text
+ assert "/retry" in text or "/model" in text
+ assert not text.startswith("Error:")
+
+
[email protected]("command", ["undo", "compress", "reload-mcp", "rollback restore"])
+def test_busy_message_names_the_real_gesture_not_a_missing_slash_command(command):
+ text = um.busy_message(command)
+
+ assert text.startswith("session busy") # clients match this lead phrase (4009)
+ assert "/interrupt" not in text
+ # Shared gateway: name both gestures, never state the terminal one as the only option.
+ assert "Ctrl+C" in text and "Stop button" in text
+ assert "Press Ctrl+C" not in text
+ assert f"/{command}" in text
+
+
+def test_agent_init_and_resume_failures_point_at_existing_commands():
+ init = um.agent_init_failed_message(RuntimeError("Unknown provider 'openrouterr'"))
+ assert not init.startswith("agent init failed")
+ assert "openrouterr" in init and "/model" in init and "hermes setup" in init
+ assert "/setup" not in init # ui-tui-only launcher; Desktop has no such command
+
+ resume = um.resume_failed_message(ValueError("corrupt row"))
+ assert not resume.startswith("resume failed")
+ assert "corrupt row" in resume and "/sessions" in resume and "/new" in resume
+ assert "/sessions new" not in resume # ui-tui-only alias; Desktop ignores the argument
+
+
+def test_still_starting_copy_is_not_phrased_as_fatal():
+ assert "timed out" not in um.AGENT_STILL_STARTING
+ assert "try again" in um.AGENT_STILL_STARTING.lower()
diff --git a/tools/approval.py b/tools/approval.py
index f5082238d92..6f10dc70f9a 100644
--- a/tools/approval.py
+++ b/tools/approval.py
@@ -468,10 +468,30 @@ def _approved() -> dict:
return {"approved": True, "message": None}
-def _denied(message: str, *, pattern_key: str, description: str, outcome: str, **extra) -> dict:
- """Standard non-consent result: the agent must not retry or rephrase."""
+# ``outcome`` -> one plain sentence for the person who just answered (or did not). ``message`` is
+# addressed to the model ("Do NOT retry ..."); surfaces render ``user_summary`` first and fold the
+# model text away, so a Reject click does not read like an error the user caused.
+_USER_SUMMARIES = {
+ "denied": "You denied this {noun} — it did not run.",
+ "timeout": "No answer within {minutes} — the {noun} did not run.",
+ "notify_failed": "The approval request could not be delivered — the {noun} did not run.",
+ "blocked": "This {noun} is not allowed in an unattended session — it did not run.",
+}
+
+
+def _user_summary(outcome: str, noun: str = "command") -> str:
+ from tools.approval_context import _get_approval_timeout, format_approval_window
+ window = format_approval_window(_get_approval_timeout())
+ return _USER_SUMMARIES.get(outcome, "This {noun} did not run.").format(noun=noun, minutes=window)
+
+
+def _denied(message: str, *, pattern_key: str, description: str, outcome: str, noun: str = "command",
+ **extra) -> dict:
+ """Standard non-consent result: the agent must not retry or rephrase. ``user_summary`` is the
+ one-line human reading of the same outcome (see ``_USER_SUMMARIES``)."""
return {"approved": False, "message": message, "pattern_key": pattern_key,
- "description": description, "outcome": outcome, "user_consent": False, **extra}
+ "description": description, "outcome": outcome, "user_consent": False,
+ "user_summary": _user_summary(outcome, noun), **extra}
def _blocked(message: str, *, pattern_key: str, description: str) -> dict:
@@ -770,7 +790,7 @@ def _human_decision(spec: _GateSpec, *, command: str, description: str,
extra = {"deny_reason": deny_reason} if "reason" in fmt else {}
return _denied(template.format(description=description, breaker=breaker, **fmt),
pattern_key=pattern_key, description=description,
- outcome=outcome, **extra)
+ outcome=outcome, noun=spec.noun, **extra)
def grant(choice: str) -> dict:
# A smart-DENY owner override is always one operation, even if an older client returns "session" or "always".
@@ -818,7 +838,7 @@ def _human_decision(spec: _GateSpec, *, command: str, description: str,
decision = _await_gateway_decision(session_key, notify_cb, data, surface="gateway")
if decision.get("notify_failed"):
return _denied(spec.notify_failed, pattern_key=pattern_key,
- description=description, outcome="notify_failed")
+ description=description, outcome="notify_failed", noun=spec.noun)
# Consent contract: silence is NOT consent, and an explicit deny is a hard
# halt — both produce a BLOCKED outcome. ``/deny <reason>`` free text is
# relayed verbatim so the agent can adapt rather than only hearing "denied".
@@ -1186,7 +1206,7 @@ def check_execute_code_guard(code: str, env_type: str, has_host_access: bool = F
return _denied(
"BLOCKED: execute_code runs arbitrary local Python (including "
"subprocess calls that bypass shell-string approval checks). " + ctx.exec_tail,
- pattern_key=pattern_key, description=description, outcome="blocked",
+ pattern_key=pattern_key, description=description, outcome="blocked", noun="code",
)
return _approved()
diff --git a/tools/approval_context.py b/tools/approval_context.py
index 7bcaca32c83..eac2dcb567c 100644
--- a/tools/approval_context.py
+++ b/tools/approval_context.py
@@ -257,6 +257,27 @@ def _get_approval_timeout() -> int:
return min(raw, safe_cap)
+def format_approval_window(seconds: int) -> str:
+ """The ONE human wording for an approval timeout window, shared by the CLI timeout notice,
+ the tool result's ``user_summary`` and the gateway card copy so every surface agrees:
+ 300 → "5 minutes", 90 → "90 seconds", 7200 → "2 hours"."""
+ seconds = max(int(seconds or 0), 0)
+ if seconds and seconds % 3600 == 0:
+ count, unit = seconds // 3600, "hour"
+ elif seconds and seconds % 60 == 0:
+ count, unit = seconds // 60, "minute"
+ else:
+ count, unit = seconds, "second"
+ return f"{count} {unit}" if count == 1 else f"{count} {unit}s"
+
+
+def approval_timeout_notice_kwargs() -> dict:
+ """``{waited, suggested}`` for the ``approval.timeout`` copy: how long we waited (``5 minutes`` /
+ ``90 seconds``) and a tripled ``approvals.timeout`` value the user can paste into ``hermes config set``."""
+ seconds = _get_approval_timeout()
+ return {"waited": format_approval_window(seconds), "suggested": seconds * 3}
+
+
def _binary_approval_mode(key: str) -> str:
"""Read ``approvals.<key>`` as 'approve' or 'deny' (default deny)."""
try:
diff --git a/tools/approval_prompt.py b/tools/approval_prompt.py
index c216d9b0ef5..c1e7f93c935 100644
--- a/tools/approval_prompt.py
+++ b/tools/approval_prompt.py
@@ -19,7 +19,8 @@ logger = logging.getLogger("tools.approval")
def prompt_dangerous_approval(command: str, description: str, timeout_seconds: int | None = None,
allow_permanent: bool = True, approval_callback=None,
- *, allow_session: bool = True, smart_denied: bool = False) -> str:
+ *, allow_session: bool = True, smart_denied: bool = False,
+ title: str | None = None) -> str:
"""Prompt the user to approve a dangerous command (CLI only).
allow_permanent=False hides [a]lways (tirith warnings present: broad permanent
@@ -28,6 +29,8 @@ def prompt_dangerous_approval(command: str, description: str, timeout_seconds: i
protected agent-instruction gate in ``tools/file_tools.py``); offering a scope
the caller discards makes every later write re-prompt and reads as broken.
smart_denied: owner override of a Smart DENY, offer only once/deny.
+ title: header for the plain-input prompt when the question is not a dangerous command
+ ("Save to memory?", "<server> is asking"); the default header stays the dangerous-command one.
approval_callback: CLI prompt_toolkit callback ``(command, description, *,
allow_permanent=True, allow_session=True, smart_denied=False) -> str``; legacy
signatures keep working while both keywords hold their defaults.
@@ -45,7 +48,7 @@ def prompt_dangerous_approval(command: str, description: str, timeout_seconds: i
# See #79719.
with human_wait_window():
return _ask_human(command, description, timeout_seconds, allow_permanent,
- approval_callback, allow_session, smart_denied)
+ approval_callback, allow_session, smart_denied, title=title)
_CLI_CHOICE_ALIASES = {
@@ -78,8 +81,19 @@ def _read_choice(prompt: str, timeout_seconds: int) -> str | None:
return None if thread.is_alive() else result["choice"]
+def callback_accepts(callback, keyword: str) -> bool:
+ """True when *callback* takes ``keyword`` (or ``**kwargs``); approval callbacks predate ``title``
+ and a TypeError inside the callback would read as a deny."""
+ import inspect
+ try:
+ params = inspect.signature(callback).parameters
+ except (TypeError, ValueError):
+ return False
+ return keyword in params or any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values())
+
+
def _ask_human(command: str, description: str, timeout_seconds: int, allow_permanent: bool,
- approval_callback, allow_session: bool, smart_denied: bool) -> str:
+ approval_callback, allow_session: bool, smart_denied: bool, title: str | None = None) -> str:
# Redact before any user-visible rendering; the original `command` still executes after approval. Same redactor as
# memory/log sanitization so tokens mask consistently across surfaces.
from agent.redact import redact_sensitive_text
@@ -93,7 +107,8 @@ def _ask_human(command: str, description: str, timeout_seconds: int, allow_perma
# Non-default scopes only: legacy callbacks lack the newer keywords.
callback_kwargs = {"allow_permanent": allow_permanent,
**({"allow_session": False} if not allow_session else {}),
- **({"smart_denied": True} if smart_denied else {})}
+ **({"smart_denied": True} if smart_denied else {}),
+ **({"title": title} if title and callback_accepts(approval_callback, "title") else {})}
return approval_callback(display_command, display_description, **callback_kwargs)
except Exception as e:
logger.error("Approval callback failed: %s", e, exc_info=True)
@@ -124,12 +139,13 @@ def _ask_human(command: str, description: str, timeout_seconds: int, allow_perma
# (prompt key, menu key) by menu shape: once/deny, full, or no [a]lways.
shape = "smart_deny" if once_only else "long" if allow_permanent else "short"
prompt_key, menu_key = f"approval.prompt_{shape}", f"approval.choose_{shape}"
- print(f"\n {t('approval.dangerous_header', description=display_description)}"
+ header = title or t('approval.dangerous_header', description=display_description)
+ print(f"\n {header}"
f"\n {display_command}\n\n{t(menu_key)}\n")
sys.stdout.flush()
choice = _read_choice(t(prompt_key), timeout_seconds)
if choice is None:
- print("\n" + t("approval.timeout"))
+ print("\n" + t("approval.timeout", **_ctx.approval_timeout_notice_kwargs()))
return "timeout" # distinct from deny: the user never answered
if once_only:
decision = {**dict.fromkeys(t("approval.smart_deny_once_inputs").split(","), "once"),
@@ -252,7 +268,7 @@ def _consent(choice, unresolved: str) -> str:
def request_elicitation_consent(message: str, description: str, *,
timeout_seconds: int | None = None,
- surface: str = "mcp-elicitation") -> str:
+ surface: str = "mcp-elicitation", title: str = "Confirm this action?") -> str:
"""Route an MCP elicitation request to the surface owning the active session:
gateway sessions through ``_await_gateway_decision``, CLI/TUI through
``prompt_dangerous_approval``. Always fails closed: a missing notify_cb in a
@@ -289,7 +305,7 @@ def request_elicitation_consent(message: str, description: str, *,
# allow_permanent=False: elicitation is a per-call confirmation — no pattern to remember.
try:
choice = prompt_dangerous_approval(message, description, timeout_seconds=timeout_seconds,
- allow_permanent=False)
+ allow_permanent=False, title=title)
except Exception as exc:
logger.error("Elicitation CLI prompt failed: %s", exc, exc_info=True)
return "decline"
diff --git a/tools/async_delegation.py b/tools/async_delegation.py
index 0069015e7e3..23a82dcc76e 100644
--- a/tools/async_delegation.py
+++ b/tools/async_delegation.py
@@ -852,15 +852,23 @@ def _stale_monitor_loop() -> None:
return
+def _stalled_error_text(event_record: Dict[str, Any]) -> str:
+ """Human wording for a force-finalized stall. This string reaches the user (CLI timeline, Desktop
+ async-result card), so it names the task, how long it was silent, and what to do — no issue
+ numbers or worker internals (those stay in the log line and the stall_* metadata)."""
+ goal = " ".join(str(event_record.get("goal") or "").split())
+ label = f'Background task "{goal[:120]}"' if goal else "The background task"
+ quiet = float(event_record.get("_stall_quiet_seconds") or 0)
+ silence = f" after {round(quiet / 60)} min of no progress" if quiet >= 60 else ""
+ return (f"{label} stopped responding{silence} and was cancelled. Nothing else was affected; "
+ "ask me to run it again if you still need it.")
+
+
def _stalled_result(delegation_id: str, event_record: Dict[str, Any]) -> Dict[str, Any]:
"""Synthetic terminal result for a stalling delegation whose runner never returned."""
completed_at = event_record.get("completed_at") or time.time()
duration = round(completed_at - (event_record.get("dispatched_at") or completed_at), 2)
- error = (
- f"Async delegation {delegation_id} stalled: the detached subagent stopped making progress "
- "(no new API calls, tool activity, or streamed tokens), did not respond to interruption, and never "
- "produced a completion event. The worker may be wedged inside a model API call — this is a known "
- "failure mode of long-lived gateway processes (#60203). Re-dispatch the task if it is still needed.")
+ error = _stalled_error_text(event_record)
logger.error("Async delegation %s force-finalized as stalled after %.0fs", delegation_id, duration)
# Structured stall metadata lets parents/UIs distinguish a stall-monitor
# kill from other failures without parsing the error string.
diff --git a/tools/browser_vault_tool.py b/tools/browser_vault_tool.py
index a32e630b540..6210b459b8b 100644
--- a/tools/browser_vault_tool.py
+++ b/tools/browser_vault_tool.py
@@ -557,7 +557,7 @@ def _confirm_payment_fill(label: str, origin: str) -> bool:
f"Fill payment card '{label}' on {origin}",
"The agent wants to enter your saved card details into this checkout page. The card number and "
"CVC never enter the conversation. Approve only if you intend to pay here.",
- surface="vault-payment") == "accept"
+ surface="vault-payment", title="Confirm payment card fill?") == "accept"
# ---------------------------------------------------------------------------
diff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.py
index 37799acc918..2fca286b824 100644
--- a/tools/code_execution_tool.py
+++ b/tools/code_execution_tool.py
@@ -495,9 +495,12 @@ def _with_timeout_notice(stdout_text: str, timeout_msg: str) -> str:
return stdout_text + f"\n\n⏰ {timeout_msg}" if stdout_text else f"⏰ {timeout_msg}"
-def _error_result(error: str, *, tool_calls_made: int = 0, duration: float = 0) -> str:
- return json.dumps({"status": "error", "error": error, "tool_calls_made": tool_calls_made,
- "duration_seconds": duration}, ensure_ascii=False)
+def _error_result(error: str, *, tool_calls_made: int = 0, duration: float = 0,
+ user_summary: Optional[str] = None) -> str:
+ body = {"status": "error", "error": error, "tool_calls_made": tool_calls_made, "duration_seconds": duration}
+ if user_summary:
+ body["user_summary"] = user_summary # one human sentence; surfaces show it before the model text
+ return json.dumps(body, ensure_ascii=False)
def _remote_failure(exc: BaseException, exec_start: float, tool_calls_made: int) -> str:
@@ -711,7 +714,8 @@ def execute_code(
from tools.approval import check_execute_code_guard
_guard = check_execute_code_guard(code, env_type, has_host_access=_docker_has_host_access(_env_config))
if not _guard.get("approved", False):
- return _error_result(_guard.get("message") or "execute_code blocked by approval guard.")
+ return _error_result(_guard.get("message") or "execute_code blocked by approval guard.",
+ user_summary=_guard.get("user_summary"))
# Clear a stale interrupt bit that landed during the blocking approval-wait so it can't
# kill the just-approved run on the first poll. A genuine post-clear interrupt re-sets it.
if _guard.get("user_approved"):
diff --git a/tools/delegate_tool_child_run.py b/tools/delegate_tool_child_run.py
index a9648e4e367..1b3a6f30f89 100644
--- a/tools/delegate_tool_child_run.py
+++ b/tools/delegate_tool_child_run.py
@@ -860,6 +860,9 @@ class _ChildRun:
"files_written": sorted({p for tid, paths in _files_written_map.items() if tid == self.child_task_id for p in paths})[:40],
"output_tail": _extract_output_tail(result, max_entries=8, max_chars=600),
}
+ if entry.get("failure_reason"):
+ # Classified verdict rides the event so every surface glosses the failure the same way.
+ complete_kwargs["failure_reason"] = entry["failure_reason"]
_cost_usd = getattr(child, "session_estimated_cost_usd", None)
if _cost_usd is not None:
with _quiet(None):
diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py
index f2043da500c..f6b86293a3c 100644
--- a/tools/delegate_tool_dispatch.py
+++ b/tools/delegate_tool_dispatch.py
@@ -16,7 +16,7 @@ from typing import Any, Dict, List, Optional
from tools.async_delegation import _new_delegation_id, record_unit_child
from tools.delegate_tool_child_run import _attach_child, _detach_child, _fabricated_entry, _signal_child_stop
from tools.delegate_tool_progress import (
- SUBAGENT_FAILURE_STATUSES, _clean_error_text, _print_completion_line, _quiet, format_batch_tag,
+ SUBAGENT_FAILURE_STATUSES, _print_completion_line, _quiet, describe_subagent_failure, format_batch_tag,
)
from tools.delegate_tool_registry import _capture_gateway_steer_authority
from tools.delegate_tool_results import _finalize_child_results
@@ -94,7 +94,9 @@ def _report_child_done(parent_agent, spinner_ref, entry, tag, task_labels, n_tas
schema_invalid = entry.get("schema_valid") is False and status == "completed"
icon = "⚠" if schema_invalid else ("✓" if status == "completed" else "✗")
completion_line = f"{icon} [{_slot}] {label} ({entry.get('duration_seconds', 0)}s)"
- _err_line = _clean_error_text(entry.get("error"), max_chars=120) if status in SUBAGENT_FAILURE_STATUSES else ""
+ _err_line = (
+ describe_subagent_failure(entry.get("failure_reason"), entry.get("error"), max_chars=120)
+ if status in SUBAGENT_FAILURE_STATUSES else "")
if schema_invalid:
_err_line = "output_schema not satisfied — raw text returned (schema_valid=false)"
if _err_line:
diff --git a/tools/delegate_tool_progress.py b/tools/delegate_tool_progress.py
index 46e913f88e6..cf0121876d9 100644
--- a/tools/delegate_tool_progress.py
+++ b/tools/delegate_tool_progress.py
@@ -44,24 +44,53 @@ def _clean_error_text(error: Any, max_chars: int = 200) -> str:
line = lines[-1] if lines[0].startswith("Traceback") else lines[0]
return line[: max_chars - 3] + "..." if len(line) > max_chars else line
+
+def describe_subagent_failure(failure_reason: Any, error: Any, max_chars: int = 200) -> str:
+ """Plain-language reason for a failed child: the classified ``failure_reason`` gloss when there is one,
+ else the child's own error text reduced to one clean line."""
+ # One gloss table for every surface (agent/turn_failure_copy.py); the child is the subject.
+ from agent.turn_failure_copy import failure_cause_gloss
+
+ gloss = failure_cause_gloss(failure_reason, subject="it", possessive="its")
+ return gloss or _clean_error_text(error, max_chars)
+
+
+def _format_duration(seconds: Any) -> str:
+ if not isinstance(seconds, (int, float)) or seconds <= 0:
+ return ""
+ return f"{round(seconds / 60)} min" if seconds >= 120 else f"{round(seconds)}s"
+
+
def format_subagent_failure_line(
goal: Optional[str], status: Optional[str], error: Any = None, duration_seconds: Any = None,
+ failure_reason: Any = None,
) -> str:
- """One clean, human-readable line describing a failed subagent, rendered
- directly to the user (CLI spinner echo, gateway platform notice), e.g.
- ``⚠️ Subagent failed — "research competitor pricing": Error code: 404 (after 12s)``."""
+ """One clean, human-readable line describing a failed subagent, rendered directly to the user (CLI spinner
+ echo, gateway platform notice). Says what happened and what to do next; never the raw exception when the
+ child loop classified the failure, e.g.
+ ``⚠️ Subagent failed — "research competitor pricing" after 12s: the model it was given was not found at the
+ AI model service. Details: /agents, or ask me to retry with a smaller task.``"""
goal_label = (goal or "").strip().replace("\n", " ")
if len(goal_label) > 60:
goal_label = goal_label[:57] + "..."
- line = f"⚠️ Subagent {'timed out' if status == 'timeout' else 'failed'}"
- if goal_label:
- line += f' — "{goal_label}"'
- err = _clean_error_text(error)
- if err:
- line += f": {err}"
- if isinstance(duration_seconds, (int, float)) and duration_seconds > 0:
- line += f" (after {round(duration_seconds)}s)"
- return line
+ goal_part = f' — "{goal_label}"' if goal_label else ""
+ elapsed = _format_duration(duration_seconds)
+ if status == "timeout":
+ # The child's own timeout text repeats the duration and names mechanisms (API/tool calls); the
+ # user needs the outcome and the knob.
+ after = f" after {elapsed}" if elapsed else ""
+ return (
+ f"⚠️ Subagent timed out{goal_part}{after} without finishing. I will carry on without it; ask me to "
+ "retry it, or raise delegation.child_timeout_seconds in config.yaml if these tasks legitimately "
+ "take longer."
+ )
+ line = f"⚠️ Subagent failed{goal_part}"
+ if elapsed:
+ line += f" after {elapsed}"
+ reason = describe_subagent_failure(failure_reason, error)
+ if reason:
+ line += f": {reason.rstrip('.')}"
+ return line + ". Details: /agents, or ask me to retry with a smaller task."
class DelegateEvent(str, enum.Enum):
@@ -323,7 +352,7 @@ class _ChildProgressRelay:
if kwargs.get("status") in SUBAGENT_FAILURE_STATUSES:
self._tree_line(format_subagent_failure_line(
self.goal_label, kwargs.get("status"), error=kwargs.get("summary") or preview,
- duration_seconds=kwargs.get("duration_seconds"),
+ duration_seconds=kwargs.get("duration_seconds"), failure_reason=kwargs.get("failure_reason"),
))
self._relay("subagent.complete", preview=preview, **kwargs)
diff --git a/tools/environments/docker.py b/tools/environments/docker.py
index 0315b3810e3..69417c5908e 100644
--- a/tools/environments/docker.py
+++ b/tools/environments/docker.py
@@ -399,7 +399,7 @@ def _ensure_docker_available() -> None:
"or known install locations. Install Docker Desktop and ensure the CLI is available.",
error="Docker executable not found in PATH or known install locations. "
"Install Docker and ensure the 'docker' command is available.",
- hint="Install Docker (or fix PATH) and retry, or switch terminal.backend to 'local'.")
+ hint="Install Docker (or fix PATH) and retry, or run `hermes setup terminal` to switch to Local.")
try:
result = run_capture([docker_exe, "version"], timeout=5)
except FileNotFoundError:
@@ -413,8 +413,8 @@ def _ensure_docker_available() -> None:
"Docker backend selected but '%s version' timed out. The Docker daemon may not be running.",
docker_exe, exc_info=True,
error="Docker daemon is not responding. Ensure Docker is running and try again.",
- hint="Start the Docker daemon (e.g. `systemctl start docker` or "
- "launch Docker Desktop), then retry the same command.")
+ hint="Start Docker (e.g. `systemctl start docker` or launch Docker Desktop), then retry — "
+ "or run `hermes setup terminal` to switch to Local.")
except Exception:
logger.error("Unexpected error while checking Docker availability.", exc_info=True)
raise
@@ -423,8 +423,8 @@ def _ensure_docker_available() -> None:
"Docker backend selected but '%s version' failed (exit code %d, stderr=%s)",
docker_exe, result.returncode, result.stderr.strip(),
error="Docker command is available but 'docker version' failed. Check your Docker installation.",
- hint="The Docker daemon may be down or the current user lacks "
- "permission (docker group). Fix and retry.")
+ hint="Start Docker, or add your user to the docker group, then retry — "
+ "or run `hermes setup terminal` to switch to Local.")
def _name_only_env_args(names) -> list[str]:
diff --git a/tools/environments/local.py b/tools/environments/local.py
index 5fccddd0bd2..fd67f7086e7 100644
--- a/tools/environments/local.py
+++ b/tools/environments/local.py
@@ -381,36 +381,12 @@ def strip_launch_profile_env(env: dict, target_home: "str | Path | None" = None)
if Path(target).resolve() == launch_home.resolve():
return env
from hermes_cli.config import TERMINAL_CONFIG_ENV_MAP
- from hermes_cli.env_loader import launch_dotenv_keys, managed_dotenv_keys, source_supplied_names
- # Current file AND every key any dotenv load put into os.environ this process lifetime: a key
- # removed or renamed in the launch .env after boot is still in os.environ with the old value, and
- # a re-parse of the file alone no longer names it (#107695 review). External secret sources
- # (vault, 1Password, ...) write their names into the same shared os.environ, and a name the
- # LAUNCH profile's source supplied is not the target profile's to see; the caller's scope
- # overlay puts back exactly the ones the target's own sources supply. The administrator-managed
- # .env is NOT residue: its values are policy for every profile (``_apply_managed_env`` applies
- # it last, with override, so it beats the user's own .env) — leave them in place.
- residue = set(load_env_file(launch_home / ".env")) | set(launch_dotenv_keys()) | set(TERMINAL_CONFIG_ENV_MAP.values())
- residue |= set(source_supplied_names())
- residue -= set(managed_dotenv_keys())
- for key in residue:
+ for key in set(load_env_file(launch_home / ".env")) | set(TERMINAL_CONFIG_ENV_MAP.values()):
if not _is_global_env(key) or key.startswith("TERMINAL_"):
env.pop(key, None)
return env
-def restore_managed_env(env: dict) -> dict:
- """Re-apply the administrator-managed ``.env`` values over *env* — call AFTER a routed profile's scope
- has been overlaid. ``_apply_managed_env`` gives those keys precedence over the user's own ``.env`` in
- the launch process; a routed child must see the same precedence, or the routed user's value for a
- managed key (``ORG_POLICY_FLAG=user-value``) silently wins over policy."""
- from hermes_cli.env_loader import managed_dotenv_keys
- for key in managed_dotenv_keys():
- if key in os.environ:
- env[key] = os.environ[key]
- return env
-
-
# --- Shell discovery ---
def _windows_bash_candidates(custom: "str | None") -> list[str]:
"""Ordered bash.exe candidates on Windows: HERMES_GIT_BASH_PATH, our portable Git
diff --git a/tools/environments/ssh.py b/tools/environments/ssh.py
index 434882b0da9..0b6a50afad8 100644
--- a/tools/environments/ssh.py
+++ b/tools/environments/ssh.py
@@ -137,15 +137,15 @@ class SSHEnvironment(BaseEnvironment):
except subprocess.TimeoutExpired:
raise EnvironmentConnectionError(
f"SSH connection to {self.user}@{self.host} timed out",
- retry_hint=(f"Check network connectivity to {self.host}:{self.port} "
- "and that sshd is accepting connections, then retry."))
+ retry_hint=(f"Check that {self.host} is up and reachable on port {self.port} "
+ "and that sshd is running, then retry."))
if result.returncode != 0:
error_msg = result.stderr.strip() or result.stdout.strip()
raise EnvironmentConnectionError(
f"SSH connection failed: {error_msg}",
- retry_hint=(f"Verify {self.user}@{self.host}:{self.port} is reachable "
- "(host up, sshd running, key/agent auth working), then "
- "retry — the connection is re-established automatically."))
+ retry_hint=(f"Check that {self.host} is up, sshd is running on port {self.port}, and "
+ f"{self.user} can log in with the configured key, then retry — "
+ "the connection is re-established automatically."))
def _detect_remote_home(self) -> str:
"""Detect the remote user's home directory."""
diff --git a/tools/mcp_tool_handlers.py b/tools/mcp_tool_handlers.py
index 65667691ba9..78025d29097 100644
--- a/tools/mcp_tool_handlers.py
+++ b/tools/mcp_tool_handlers.py
@@ -67,7 +67,7 @@ def _trust_gate_check(server_name: str, tool_name: str) -> Optional[str]:
f"(no readOnlyHint=true annotation) and may modify external state.",
f"Server '{server_name}' is configured 'trust: untrusted'. "
f"Approve to run '{tool_name}' once, or deny to block it.",
- surface=f"mcp-trust/{server_name}")
+ surface=f"mcp-trust/{server_name}", title=f"MCP server '{server_name}' is asking")
except Exception as exc:
logger.error("MCP trust gate: approval check failed for %s.%s: %s", server_name, tool_name, exc, exc_info=True)
return tool_error(f"MCP tool '{tool_name}' on untrusted server '{server_name}' was blocked: the approval "
diff --git a/tools/terminal_tool.py b/tools/terminal_tool.py
index 1fc0003939e..4e9b7fc75ac 100644
--- a/tools/terminal_tool.py
+++ b/tools/terminal_tool.py
@@ -49,6 +49,7 @@ from tools.terminal_tool_config import (
)
from tools.terminal_tool_backends import (
_REQUIREMENT_CHECKERS, _VERCEL_SANDBOX_DEFAULT_CWD, _check_plugin_requirements,
+ _record_unavailable_reason, terminal_backend_unavailable_reason, # noqa: F401 — re-exported
)
# display_hermes_home imported lazily at call site (stale-module safety during hermes update)
from tools.tool_backend_helpers import coerce_modal_mode, managed_nous_tools_enabled
@@ -870,7 +871,8 @@ def _run_approval_guards(command: str, env_type: str, config: Dict[str, Any], *,
f"Command denied: {desc}. "
"Use the approval prompt to allow it, or rephrase the command."
)
- raise _Rejected(_error_json(approval.get("message", fallback_msg), status="blocked"))
+ raise _Rejected(_error_json(approval.get("message", fallback_msg), status="blocked",
+ **({"user_summary": approval["user_summary"]} if approval.get("user_summary") else {})))
desc = approval.get("description", "flagged as dangerous")
if approval.get("user_approved"):
return _ApprovalVerdict(
@@ -1255,13 +1257,15 @@ def terminal_tool(
def check_terminal_requirements() -> bool:
- """Check if all requirements for the terminal tool are met."""
+ """Check if all requirements for the terminal tool are met. The reason for a failure is kept for
+ :func:`terminal_backend_unavailable_reason` (CLI startup notice / doctor)."""
try:
config = _get_env_config()
checker = _REQUIREMENT_CHECKERS.get(config["env_type"], _check_plugin_requirements)
return checker(config)
except Exception as e:
logger.error("Terminal requirements check failed: %s", e, exc_info=True)
+ _record_unavailable_reason(f"the requirements check failed: {e}")
return False
diff --git a/tools/terminal_tool_backends.py b/tools/terminal_tool_backends.py
index 335bb1c3048..8ce7bfd76c4 100644
--- a/tools/terminal_tool_backends.py
+++ b/tools/terminal_tool_backends.py
@@ -24,6 +24,31 @@ from tools.tool_backend_helpers import (has_direct_modal_credentials, managed_no
# Log-record parity with the origin module.
logger = logging.getLogger("tools.terminal_tool")
+# Human reason for the most recent failed requirements check (None after a passing one). The CLI
+# startup notice and `hermes doctor` read it through terminal_backend_unavailable_reason() so the user
+# hears WHY the terminal tool is missing instead of discovering it on first use.
+_last_unavailable_reason: Optional[str] = None
+
+
+def _reject(reason: str) -> bool:
+ """Log *reason*, remember it for the user-facing notice, and return False for the checker."""
+ global _last_unavailable_reason
+ _last_unavailable_reason = reason
+ logger.error(reason)
+ return False
+
+
+def _record_unavailable_reason(reason: Optional[str]) -> None:
+ """Store (or clear) the last failure reason without logging; used by check_terminal_requirements."""
+ global _last_unavailable_reason
+ _last_unavailable_reason = reason
+
+
+def terminal_backend_unavailable_reason() -> Optional[str]:
+ """Why the last terminal requirements check failed, in plain words; None when it passed."""
+ return _last_unavailable_reason
+
+
_VERCEL_SANDBOX_DEFAULT_CWD = "/vercel/sandbox"
_SUPPORTED_VERCEL_RUNTIMES = ("node24", "node22", "python3.13")
_BUILTIN_BACKENDS = "local, docker, singularity, modal, daytona, vercel_sandbox, ssh"
@@ -229,16 +254,13 @@ def _check_vercel(config: Dict[str, Any]) -> bool:
runtime = (config.get("vercel_runtime") or "").strip()
disk = config.get("container_disk", 51200)
if not _is_supported_vercel_runtime(runtime):
- logger.error("Vercel Sandbox runtime %r is not supported. Set TERMINAL_VERCEL_RUNTIME to one of: %s.",
- runtime, ", ".join(_SUPPORTED_VERCEL_RUNTIMES))
- return False
+ return _reject(f"Vercel Sandbox runtime {runtime!r} is not supported. Set TERMINAL_VERCEL_RUNTIME to one of: "
+ f"{', '.join(_SUPPORTED_VERCEL_RUNTIMES)}.")
if disk not in {0, 51200}:
- logger.error("Vercel Sandbox does not support custom TERMINAL_CONTAINER_DISK=%s. "
- "Use the default shared setting (51200 MB).", disk)
- return False
+ return _reject(f"Vercel Sandbox does not support custom TERMINAL_CONTAINER_DISK={disk}. "
+ "Use the default shared setting (51200 MB).")
if importlib.util.find_spec("vercel") is None:
- logger.error("vercel is required for the Vercel Sandbox terminal backend: pip install vercel")
- return False
+ return _reject("vercel is required for the Vercel Sandbox terminal backend: pip install vercel")
from agent.secret_scope import get_secret
if get_secret("VERCEL_OIDC_TOKEN"):
return True
@@ -249,8 +271,7 @@ def _check_vercel(config: Dict[str, Any]) -> bool:
"set together." if any(present) else
"selected but no supported auth configuration was found. Set VERCEL_TOKEN, VERCEL_PROJECT_ID, "
"and VERCEL_TEAM_ID for normal use.")
- logger.error(f"Vercel Sandbox backend {head} VERCEL_OIDC_TOKEN is supported for one-off local development only.")
- return False
+ return _reject(f"Vercel Sandbox backend {head} VERCEL_OIDC_TOKEN is supported for one-off local development only.")
def _modal_pre(config: Dict[str, Any]) -> Optional[bool]:
@@ -258,17 +279,15 @@ def _modal_pre(config: Dict[str, Any]) -> Optional[bool]:
if modal_state["selected_backend"] == "managed":
return True
if modal_state["selected_backend"] != "direct":
- logger.error(_modal_unavailable_reason(modal_state)[0])
- return False
+ return _reject(_modal_unavailable_reason(modal_state)[0])
return None
def _ssh_pre(config: Dict[str, Any]) -> bool:
if config.get("ssh_host") and config.get("ssh_user"):
return True
- logger.error("SSH backend selected but TERMINAL_SSH_HOST and TERMINAL_SSH_USER "
- "are not both set. Configure both or switch TERMINAL_ENV to 'local'.")
- return False
+ return _reject("the SSH host and user are not configured (TERMINAL_SSH_HOST / TERMINAL_SSH_USER); "
+ "run `hermes setup terminal` to enter them or pick the 'local' backend")
def _daytona_post(config: Dict[str, Any]) -> bool:
@@ -280,7 +299,7 @@ def _daytona_post(config: Dict[str, Any]) -> bool:
_BACKEND_SPECS: Dict[str, Dict[str, Any]] = {
"local": {},
"docker": {"binary": (lambda: importlib.import_module("tools.environments.docker").find_docker(), "version",
- "Docker executable not found in PATH or common install locations")},
+ "Docker is not installed — no docker executable in PATH or the usual install locations")},
"singularity": {"binary": (lambda: shutil.which("apptainer") or shutil.which("singularity"), "--version", None)},
"ssh": {"pre": _ssh_pre},
"modal": {"pre": _modal_pre,
@@ -290,7 +309,14 @@ _BACKEND_SPECS: Dict[str, Dict[str, Any]] = {
}
+_PROBE_FAILED_REASONS = {
+ "docker": "Docker is installed but the Docker daemon is not running",
+ "singularity": "Apptainer/Singularity is installed but `--version` failed, so the install looks broken",
+}
+
+
def _check_requirements(env_type: str, config: Dict[str, Any]) -> bool:
+ _record_unavailable_reason(None)
spec = _BACKEND_SPECS[env_type]
verdict = spec["pre"](config) if "pre" in spec else None
if verdict is not None:
@@ -299,25 +325,26 @@ def _check_requirements(env_type: str, config: Dict[str, Any]) -> bool:
finder, arg, missing_msg = spec["binary"]
executable = finder()
if not executable:
- if missing_msg:
- logger.error(missing_msg)
- return False
+ return _reject(missing_msg or f"the {env_type!r} backend's executable was not found")
probe = subprocess.run([executable, arg], capture_output=True, timeout=5, stdin=subprocess.DEVNULL)
- return probe.returncode == 0
+ if probe.returncode != 0:
+ return _reject(f"{_PROBE_FAILED_REASONS[env_type]} (`{executable} {arg}` exited with code {probe.returncode})")
+ return True
if "module" in spec and importlib.util.find_spec(spec["module"][0]) is None:
- logger.error(spec["module"][1])
- return False
- return spec["post"](config) if "post" in spec else True
+ return _reject(spec["module"][1])
+ if "post" in spec and not spec["post"](config):
+ return _reject(f"the {env_type!r} backend is missing its API key or SDK")
+ return True
def _check_plugin_requirements(config: Dict[str, Any]) -> bool:
+ _record_unavailable_reason(None)
env_type = config["env_type"]
provider = _get_plugin_env_provider(env_type)
if provider is not None:
- return bool(provider.check_requirements(config))
- logger.error("Unknown TERMINAL_ENV '%s'. Use one of: %s, or a plugin-registered backend.",
- env_type, _BUILTIN_BACKENDS)
- return False
+ ok = bool(provider.check_requirements(config))
+ return ok or _reject(f"the {env_type!r} plugin backend reported its requirements are not met")
+ return _reject(f"Unknown TERMINAL_ENV '{env_type}'. Use one of: {_BUILTIN_BACKENDS}, or a plugin-registered backend.")
# Built-in backend -> requirements checker; unknown backends go to the plugin registry.
diff --git a/tools/write_approval.py b/tools/write_approval.py
index 39c9a4cda86..c519bf939a3 100644
--- a/tools/write_approval.py
+++ b/tools/write_approval.py
@@ -199,7 +199,9 @@ def _prompt_inline_memory_approval(summary: str, detail: str) -> Optional[bool]:
return None
header = summary.strip() or "Save to memory?"
try:
- choice = callback(detail.strip() or header, f"Save to memory: {header}", allow_permanent=False)
+ from tools.approval_prompt import callback_accepts
+ extra = {"title": "Save to memory?"} if callback_accepts(callback, "title") else {}
+ choice = callback(detail.strip() or header, f"Save to memory: {header}", allow_permanent=False, **extra)
except Exception as e:
logger.error("Inline memory approval prompt failed: %s", e)
return None
diff --git a/tui_gateway/contracts/registry.py b/tui_gateway/contracts/registry.py
index 2c350e6478a..5e7d18fd651 100644
--- a/tui_gateway/contracts/registry.py
+++ b/tui_gateway/contracts/registry.py
@@ -109,7 +109,9 @@ def validate_params(contract: MethodContract | ServerRequestContract, params: di
for err in exc.errors():
if err.get("type") == "extra_forbidden":
loc = ".".join(str(p) for p in err.get("loc", ())) or "params"
- return None, f"invalid params for {contract.name}: {loc}: {err.get('msg')}"
+ return None, (f"invalid params for {contract.name}: {loc}: {err.get('msg')} — the client and "
+ "the Hermes backend are out of sync (different versions); run `hermes update` "
+ "and restart both")
return params, None
diff --git a/tui_gateway/methods_config_set.py b/tui_gateway/methods_config_set.py
index 3163089bc80..4e89aa0806f 100644
--- a/tui_gateway/methods_config_set.py
+++ b/tui_gateway/methods_config_set.py
@@ -122,7 +122,7 @@ def _set_model(rid, params, key, value, session):
if failed_ready is None:
return _err(rid, 5032, session.get("agent_error") or "agent initialization failed")
if not failed_ready.wait(timeout=30.0):
- return _err(rid, 5032, "agent initialization timed out")
+ return _err(rid, 5032, AGENT_STILL_STARTING)
failed_agent_init = (
failed_agent_init and session.get("agent") is None and session.get("agent_error") is not None
and session.get("agent_ready") is failed_ready and failed_ready.is_set())
diff --git a/tui_gateway/methods_prompt.py b/tui_gateway/methods_prompt.py
index 4503c7b71cb..dde0620f744 100644
--- a/tui_gateway/methods_prompt.py
+++ b/tui_gateway/methods_prompt.py
@@ -438,28 +438,42 @@ def _truncate_history_for_submit(rid, sid, session, params, requested_rebind_ids
return None, fields
+def _storage_error_data(failure, raw) -> dict:
+ """Machine-readable error data: ``code`` lets a GUI pick a "Run doctor" / "Retry" action."""
+ from hermes_state_user_copy import storage_failure_details
+ return {"code": failure.code, "cause": failure.cause, "details": storage_failure_details(raw)}
+
+
def _persist_session_row_for_submit(rid, session):
"""Lazily persist the DB row now that the user sent a message (a branch becomes real
here); the error reply is the only user-visible signal (desktop maps it to a toast)."""
+ from hermes_state_user_copy import describe_storage_failure
try:
if _ensure_session_db_row(session) is False:
+ failure = describe_storage_failure(_db_error)
error = _err(
rid, 5072,
- "session storage unavailable: "
- f"{_db_error or 'state.db could not be opened'} — the message "
- "was not saved; repair state.db and try again")
+ f"Session storage is unavailable, so this message was not saved. Cause: {failure.gloss}. "
+ f"{failure.action} Then send your message again.",
+ data=_storage_error_data(failure, _db_error))
else:
_persist_branch_seed(session)
return None
except Exception as exc:
- from hermes_state_errors import is_disk_full_error
- if is_disk_full_error(exc):
+ failure = describe_storage_failure(exc)
+ if failure.code == "disk_full":
error = _err(
rid, 5070,
- "disk full: session storage could not be written — free some disk space and try again")
+ "Session storage could not be written, so this message was not saved: the disk is full. "
+ "Free some disk space, then send your message again.",
+ data=_storage_error_data(failure, exc))
else:
logger.warning("prompt.submit: session persist failed: %s", exc, exc_info=True)
- error = _err(rid, 5071, f"session storage could not be written: {exc}")
+ error = _err(
+ rid, 5071,
+ f"Session storage could not be written, so this message was not saved. Cause: {failure.gloss}. "
+ f"{failure.action} Then send your message again.",
+ data=_storage_error_data(failure, exc))
# No turn thread will start, so neither resume nor the busy queue may see
# this rejected prompt as live. Release the slot a turn would normally own.
with session["history_lock"]:
diff --git a/tui_gateway/methods_session.py b/tui_gateway/methods_session.py
index cf4e17bbb05..e15fcd3b879 100644
--- a/tui_gateway/methods_session.py
+++ b/tui_gateway/methods_session.py
@@ -726,7 +726,7 @@ def _resume_lazy(ctx: _Resume) -> dict:
# repair_alternation heals a durable ``user;user`` once here.
history = ctx.child_history(repair=True)
except Exception as e:
- return _err(ctx.rid, 5000, f"resume failed: {e}")
+ return _err(ctx.rid, 5000, resume_failed_message(e))
record = ctx.record(source, cwd, history, lazy=True, todo_state=_todo_state_from_history(history))
if (reused := ctx.claim(sid, record)) is not None:
return reused
@@ -767,7 +767,7 @@ def _resume_cold(ctx: _Resume) -> dict:
try:
history, display_history, raw_history = ctx.restore()
except Exception as e:
- return _err(ctx.rid, 5000, f"resume failed: {e}")
+ return _err(ctx.rid, 5000, resume_failed_message(e))
overrides = _stored_session_runtime_overrides(ctx.found)
record = ctx.record(source, cwd, history, overrides, display_history_prefix=ctx.display_prefix(),
todo_state=_todo_state_from_history(history))
@@ -795,7 +795,7 @@ def _resume_eager(ctx: _Resume) -> dict:
context_cwd_is_launch_artifact=(source in _LAUNCH_CWD_NOT_A_WORKSPACE and not ctx.profile_resume_cwd),
auth_user_id=_transport_auth_user_id(current_transport()), **stored_runtime_overrides)
except Exception as e:
- return _err(ctx.rid, 5000, f"resume failed: {e}")
+ return _err(ctx.rid, 5000, resume_failed_message(e))
with _session_resume_lock:
live = _find_live_session_by_key(ctx.target, ctx.profile_home)
if live is not None:
@@ -826,7 +826,7 @@ def _resume_eager(ctx: _Resume) -> dict:
if ctx.owns_db:
with _sessions_lock:
_sessions.pop(sid, None)
- return _err(ctx.rid, 5000, f"resume failed: {e}")
+ return _err(ctx.rid, 5000, resume_failed_message(e))
session = _sessions.get(sid) or {}
return _resume_response(
ctx, sid, session, info=_session_info(agent, session), display=display_history, count_source=raw_history,
@@ -1727,8 +1727,8 @@ def _(rid, params: dict, session: dict) -> dict:
@_session_method("session.undo", live=True)
def _(rid, params: dict, session: dict) -> dict:
- # Under a running turn the post-run write would clobber the undo — /interrupt first.
- busy = _err(rid, 4009, "session busy — /interrupt the current turn before /undo")
+ # Under a running turn the post-run write would clobber the undo — stop the reply first.
+ busy = _err(rid, 4009, busy_message("undo"))
if session.get("running"):
return busy
removed = 0
@@ -1859,7 +1859,7 @@ def _(rid, params: dict) -> dict:
if err:
return err
if session.get("running"):
- return _err(rid, 4009, "session busy — /interrupt the current turn before /compress")
+ return _err(rid, 4009, busy_message("compress"))
sid = params.get("session_id", "")
try:
return _compress_live(rid, sid, session, _str_param(params, "focus_topic"))
diff --git a/tui_gateway/methods_slash.py b/tui_gateway/methods_slash.py
index 25d27ba1117..aeebe537bd6 100644
--- a/tui_gateway/methods_slash.py
+++ b/tui_gateway/methods_slash.py
@@ -386,7 +386,7 @@ def _mirror_slash_side_effects(sid: str, session: dict, command: str) -> str:
if _session_uses_compute_host(session):
return _compute_host_slash(sid, session, name, command)[1]
if session.get("running"):
- return f"session busy — /interrupt the current turn before running /{name}"
+ return busy_message(name)
if (mirror := _SLASH_MIRRORS.get(name)) is None:
return ""
try:
diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.py
index 70dbbce39ec..59616b394c6 100644
--- a/tui_gateway/methods_tools.py
+++ b/tui_gateway/methods_tools.py
@@ -119,7 +119,7 @@ def _mcp_named_server(rid, params):
def _busy_error(rid, session, cmd: str):
if session.get("running"):
- return _err(rid, 4009, f"session busy — /interrupt the current turn before /{cmd}")
+ return _err(rid, 4009, busy_message(cmd))
return None
@@ -946,7 +946,7 @@ def _(rid, params: dict, session) -> dict:
# Full-history rollback mutates session history → rejected mid-turn (prompt.submit
# would drop the agent's output or clobber it). File-scoped only touches disk.
if not file_path and session.get("running"):
- return _err(rid, 4009, "session busy — /interrupt the current turn before full rollback.restore")
+ return _err(rid, 4009, busy_message("rollback restore"))
def go(mgr, cwd):
result = mgr.restore(cwd, _resolve_checkpoint_hash(mgr, cwd, target), file_path=file_path or None)
diff --git a/tui_gateway/prompt_turn.py b/tui_gateway/prompt_turn.py
index d314dc0942b..97f9b90fbe1 100644
--- a/tui_gateway/prompt_turn.py
+++ b/tui_gateway/prompt_turn.py
@@ -251,16 +251,17 @@ def _result_status(result: dict) -> str:
else "error" if result.get("error") else "complete")
-def _turn_outcome(result: Any) -> tuple[Any, str, str | None]:
+def _turn_outcome(result: Any, error_surface: dict | None = None) -> tuple[Any, str, str | None]:
"""Reduce a run_conversation result to ``(raw_text, status, last_reasoning)``."""
if not isinstance(result, dict):
return str(result), "complete", None
raw = result.get("final_response", "")
status = _result_status(result)
- # No visible response AND a real error: surface the error as the text (classic CLI
- # parity). An empty successful turn still renders as empty.
+ # No visible response AND a real error: the assistant slot carries a plain account of the
+ # failure (title from ``error_surface``, raw provider detail on a ``Details:`` line, next
+ # step) rather than the bare provider body. An empty successful turn still renders as empty.
if (not raw) and result.get("error") and (result.get("failed") or result.get("partial")):
- raw = f"Error: {result.get('error')}"
+ raw = turn_error_text(result.get("error"), error_surface)
# "Operation interrupted: waiting for model response (…)" is cancellation
# metadata, not assistant prose (gateway/run.py and ACP suppress it too).
# "Operation interrupted: waiting for model response (…)" is cancellation metadata, not assistant prose.
@@ -625,7 +626,18 @@ def _complete_turn_payload(session: dict, st: _TurnRun, status_note: str | None,
"""``(payload, raw, status)`` for message.complete; retains/clears the inflight turn and
settles the hosted-room terminal receipt."""
result, agent = st.result, st.agent
- raw, status, last_reasoning = _turn_outcome(result)
+ # Advisory {layer, code, retryable} descriptor; computed before the retain so resume
+ # replay carries the same one, and before the text so the fallback copy can use it.
+ _error_surface = None
+ if _result_status(result) == "error":
+ try:
+ from agent.error_surface import build_error_surface_from_result
+ _error_surface = build_error_surface_from_result(
+ result, provider=str(getattr(agent, "provider", "") or ""),
+ model=str(getattr(agent, "model", "") or ""))
+ except Exception:
+ _error_surface = None
+ raw, status, last_reasoning = _turn_outcome(result, _error_surface)
payload = {"text": raw, "usage": _get_usage(agent), "status": status}
if last_reasoning:
payload["reasoning"] = last_reasoning
@@ -639,17 +651,6 @@ def _complete_turn_payload(session: dict, st: _TurnRun, status_note: str | None,
payload["failure_reason"] = result.get("failure_reason")
if rendered := render_message(raw, cols):
payload["rendered"] = rendered
- # Advisory {layer, code, retryable} descriptor; computed before the retain so resume
- # replay carries the same one.
- _error_surface = None
- if status == "error":
- try:
- from agent.error_surface import build_error_surface_from_result
- _error_surface = build_error_surface_from_result(
- result, provider=str(getattr(agent, "provider", "") or ""),
- model=str(getattr(agent, "model", "") or ""))
- except Exception:
- _error_surface = None
error_value = result.get("error")
with session["history_lock"]:
if status == "error":
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index cacf2eae97a..0787278f1b5 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -37,6 +37,9 @@ from tui_gateway import git_probe
from tui_gateway._env import env_float, env_int
from tui_gateway.turn_marker import clear_turn_marker, read_turn_marker, record_turn_start # noqa: F401
from tui_gateway.contracts import registry as _contracts
+# User-facing copy shared with the split method modules (they close over this namespace).
+from tui_gateway.user_messages import ( # noqa: F401
+ AGENT_STILL_STARTING, agent_init_failed_message, busy_message, resume_failed_message, turn_error_text)
from tui_gateway.transport import (FanoutTransport, StdioTransport, Transport, bind_transport,
current_transport, reset_transport)
@@ -483,7 +486,12 @@ def _response_profile_name(profile: str | None = None) -> str:
def _db_unavailable_error(rid, *, code: int):
- return _err(rid, code, f"state.db unavailable: {_db_error or 'state.db unavailable'}")
+ from hermes_state_user_copy import describe_storage_failure, storage_failure_details
+ failure = describe_storage_failure(_db_error)
+ return _err(
+ rid, code,
+ f"Session storage is unavailable: {failure.gloss}. {failure.action}",
+ data={"code": failure.code, "cause": failure.cause, "details": storage_failure_details(_db_error)})
# ── Per-session profile scoping: the desktop's app-global remote mode points every profile at this
@@ -806,7 +814,8 @@ def handle_request(req: dict) -> dict | None:
return normalized
rid, method, params = normalized
if not (fn := _methods.get(method)):
- return _err(rid, -32601, f"unknown method: {method}")
+ return _err(rid, -32601, f"unknown method: {method} — the client and the Hermes backend are out of sync "
+ "(different versions); run `hermes update` and restart both")
# Test doubles register straight into ``_methods`` without a contract; every production
# handler comes through ``register_method`` and therefore has one.
contract = _contracts.METHODS.get(method)
@@ -886,7 +895,7 @@ def dispatch(req: dict, transport: Optional[Transport] = None) -> dict | None:
def _wait_agent(session: dict, rid: str, timeout: float = 30.0) -> dict | None:
ready = session.get("agent_ready")
if ready is not None and not ready.wait(timeout=timeout):
- return _err(rid, 5032, "agent initialization timed out")
+ return _err(rid, 5032, AGENT_STILL_STARTING)
return _err(rid, 5032, err) if (err := session.get("agent_error")) else None
@@ -1130,7 +1139,7 @@ def _start_agent_build(sid: str, session: dict) -> None:
_announce_built_agent(sid, key, current, agent)
except Exception as e:
current["agent_error"] = str(e)
- _emit("error", sid, {"message": f"agent init failed: {e}"})
+ _emit("error", sid, {"message": agent_init_failed_message(e)})
finally:
_finish_agent_build(
sid, key, current, notify_registered=notify_registered, scopes=scopes, session_db=session_db)
@@ -2619,7 +2628,7 @@ def _schedule_resume_hydration(sid: str, stored_id: str, db, *, close_db: bool =
except Exception as exc:
if _sessions.get(sid) is not session:
return
- message = f"resume failed: {exc}"
+ message = resume_failed_message(exc)
session.update(resume_hydrating=False, resume_history_error=message, agent_error=message)
session["resume_history_ready"].set()
session["agent_ready"].set()
diff --git a/tui_gateway/session_auto_continue.py b/tui_gateway/session_auto_continue.py
index fb550c9e1ed..e82850ab01f 100644
--- a/tui_gateway/session_auto_continue.py
+++ b/tui_gateway/session_auto_continue.py
@@ -379,7 +379,7 @@ def _emit_terminal_turn_error(
turn = session.get("inflight_turn") or {}
message, partial = str(turn.get("error") or "turn failed"), str(turn.get("assistant") or "")
cols = int(session.get("cols", 80))
- text = partial or f"Error: {message}"
+ text = partial or turn_error_text(message, error_surface)
rendered = ""
with contextlib.suppress(Exception):
rendered = render_message(text, cols)
diff --git a/tui_gateway/user_messages.py b/tui_gateway/user_messages.py
new file mode 100644
index 00000000000..a017d82eb9d
--- /dev/null
+++ b/tui_gateway/user_messages.py
@@ -0,0 +1,105 @@
+"""User-facing copy for gateway refusals and session-level failures.
+
+One place for the sentences the TUI, Desktop and dashboard print verbatim, so the
+"what happened / what to do" shape stays consistent and the slash commands cited
+(`/model`, `/new`, `/sessions`, `/retry`) exist on EVERY client this gateway serves (TUI,
+Desktop, dashboard) — no client-only forms (`/sessions new`, `/setup`) and no single-surface
+gestures stated as fact (Ctrl+C is copy on Desktop). Lead phrases that clients pattern-match
+on (``Session busy``) are part of the wire contract — keep them.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+# Provider-layer failure codes → (title, hint). Codes are ``agent.error_classifier.FailoverReason``
+# values carried in ``error_surface.code``; anything unlisted falls back on the layer table.
+_TURN_ERROR_CODE_COPY: dict[str, tuple[str, str]] = {
+ "auth": ("The model provider rejected the API key", "Fix the key with /model, then /retry."),
+ "auth_permanent": ("The model provider rejected the API key", "Fix the key with /model, then /retry."),
+ "billing": ("The model provider reports no credit left", "Top up the account or switch with /model."),
+ "billing_unverified": ("The model provider reports no credit left", "Top up the account or switch with /model."),
+ "rate_limit": ("The model provider is rate-limiting requests", "Wait a moment, then /retry."),
+ "upstream_rate_limit": ("The model provider is rate-limiting requests", "Wait a moment, then /retry."),
+ "overloaded": ("The model provider is overloaded", "Wait a moment, then /retry."),
+ "server_error": ("The model provider had an internal error", "Wait a moment, then /retry."),
+ "timeout": ("The model provider did not answer in time", "Try /retry; if it keeps happening, switch with /model."),
+ "context_overflow": ("The conversation is too long for this model", "Run /compress, then /retry."),
+ "payload_too_large": ("The request was too large for this model", "Run /compress, then /retry."),
+ "model_not_found": ("The model provider does not know this model", "Pick another model with /model."),
+ "content_policy_blocked": ("The model provider refused this request (content policy)", "Rephrase and send again."),
+ "provider_policy_blocked": ("The model provider refused this request (account policy)", "Switch with /model."),
+ "format_error": ("The model provider rejected the request format", "Try /retry; if it persists, switch with /model."),
+ "ssl_cert_verification": ("The connection to the model provider could not be verified (TLS)",
+ "Check the endpoint's certificate, then /retry."),
+}
+
+_TURN_ERROR_LAYER_COPY: dict[str, tuple[str, str]] = {
+ "auth": ("The model provider rejected the credentials", "Fix them with /model, then /retry."),
+ "billing": ("The model provider reports no credit left", "Top up the account or switch with /model."),
+ "endpoint": ("Your custom model endpoint did not answer", "Check the endpoint is running, then /retry."),
+ "streaming": ("The connection to the model provider dropped mid-reply", "Send /retry."),
+ "disk": ("The disk is full, so Hermes could not save the turn", "Free some space, then /retry."),
+ "gateway": ("Hermes hit an internal error while running this turn", "Send /retry; type /logs for the trace."),
+ "provider": ("The model provider returned an error", "Send /retry, or switch with /model."),
+}
+
+_TURN_ERROR_DEFAULT = ("The request failed", "Send /retry, or switch with /model.")
+
+_DETAIL_LIMIT = 400
+
+
+def _identity(surface: dict | None) -> str:
+ provider = str((surface or {}).get("provider") or "").strip()
+ return f" ({provider})" if provider else ""
+
+
+def turn_error_title(surface: dict | None) -> str:
+ """Plain title for a failed turn, picked from ``error_surface`` code then layer."""
+ surface = surface if isinstance(surface, dict) else {}
+ title, _ = _TURN_ERROR_CODE_COPY.get(str(surface.get("code") or "")) \
+ or _TURN_ERROR_LAYER_COPY.get(str(surface.get("layer") or "")) or _TURN_ERROR_DEFAULT
+ return f"{title}{_identity(surface)}"
+
+
+def turn_error_hint(surface: dict | None, recoverable: bool = True) -> str:
+ surface = surface if isinstance(surface, dict) else {}
+ _, hint = _TURN_ERROR_CODE_COPY.get(str(surface.get("code") or "")) \
+ or _TURN_ERROR_LAYER_COPY.get(str(surface.get("layer") or "")) or _TURN_ERROR_DEFAULT
+ return hint if recoverable else hint.replace("Send /retry", "Pick another model with /model")
+
+
+def turn_error_text(error: Any, surface: dict | None = None, *, recoverable: bool = True) -> str:
+ """The assistant-slot text for a turn that produced no reply: title, what it means for the
+ user, the raw provider detail on its own dimmed-able line, and the next step."""
+ detail = " ".join(str(error or "").split())
+ if len(detail) > _DETAIL_LIMIT:
+ detail = detail[:_DETAIL_LIMIT - 1] + "…"
+ lines = [f"{turn_error_title(surface)}. Your message was not answered."]
+ if detail:
+ lines.append(f"Details: {detail}")
+ lines.append(turn_error_hint(surface, recoverable))
+ return "\n".join(lines)
+
+
+def busy_message(command: str) -> str:
+ """4009 refusal for a history-mutating command while a reply is streaming. There is no
+ ``/interrupt`` slash command on any client: Desktop has a Stop button, the terminal TUI uses
+ Ctrl+C — name both without assuming which one the reader has."""
+ return (f"session busy — Hermes is still replying. Stop the current reply first (Stop button, "
+ f"or Ctrl+C in a terminal), then run /{command.lstrip('/')}.")
+
+
+def agent_init_failed_message(exc: Any) -> str:
+ return (f"Hermes could not start the assistant for this session. Details: {exc}. "
+ "Check the model and provider with /model, or run `hermes setup` in a terminal to reconfigure.")
+
+
+AGENT_STILL_STARTING = (
+ "Hermes is still starting this session (loading tools), so this command could not run yet. "
+ "Wait for the status bar to show ready and try again.")
+
+
+def resume_failed_message(exc: Any) -> str:
+ return (f"Could not reopen that session (its transcript could not be read). Details: {exc}. "
+ "Start a new session (/new), or pick another from /sessions.")