turn_failure_copy.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. """User-facing copy and ``failure_reason`` stamping for terminal failed-turn results.
  2. Every terminal result dict the turn loop returns must carry ``failure_reason`` (a
  3. ``FailoverReason`` value or one of :data:`SITE_FAILURE_CODES`) and ``failure_retryable`` so
  4. ``agent/error_surface.py`` yields a specific descriptor instead of ``unknown``. The copy
  5. tables here say WHAT happened and WHAT TO DO in plain words; raw provider detail rides a
  6. trailing "Provider said:" / "Details:" line.
  7. """
  8. from __future__ import annotations
  9. import time
  10. from typing import Any, Dict, NamedTuple, Optional, Tuple
  11. from agent.error_classifier import FailoverReason
  12. from agent.stream_max_lifetime import StreamLifetimeExceeded
  13. from hermes_constants import display_hermes_home
  14. # Failure codes minted by loop sites that are not provider verdicts (see module docstring).
  15. SITE_FAILURE_CODES = frozenset({
  16. "context_overflow", "truncated", "invalid_response", "empty_response", "loop_error",
  17. "interpreter_shutdown", "session_busy", "gateway_connection", "host_error",
  18. })
  19. def launch_credentials_copy(error: Any) -> str:
  20. """The refusal for a session whose own launch/route API key changed or is gone (``RuntimeStoreError``
  21. or an RPC refusal carrying ``field``/``detail``). A session never sends a different key than it
  22. started with, so /retry repeats the refusal: the copy names /new on every surface."""
  23. from agent.i18n import t
  24. data = getattr(error, "data", None)
  25. data = data if isinstance(data, dict) else {}
  26. field = getattr(error, "field", None) or data.get("field")
  27. detail = getattr(error, "detail", None) or data.get("detail")
  28. named = f" ({field}: {detail or 'unavailable'})" if field else ""
  29. text = t("gateway.errors.launch_credentials_unavailable", detail=named)
  30. # The raw code + field stay greppable for bug reports and log matching (untranslated, last line).
  31. return f"{text}\n\nDetails: launch_credentials_unavailable{named}" if field else text
  32. def stamp_failure(result: dict[str, Any], reason: str, retryable: bool) -> dict[str, Any]:
  33. """Stamp the UI verdict fields on a terminal result (in place; returns it)."""
  34. result["failure_reason"] = reason
  35. result["failure_retryable"] = bool(retryable)
  36. return result
  37. # ---- failed-turn transcript boundary ----------------------------------------------------------
  38. # The Hermes-authored assistant row that closes a durable turn which ended without one. A
  39. # transcript boundary, NOT the model's answer: no provider/model error or refusal detail is
  40. # ever interpolated (that rides ``final_response``). Owned here so the core closer
  41. # (``agent/conversation_loop.py::run_conversation``) and the gateway's own writer
  42. # (``gateway/run_turn.py::_hmwa_close_failed_turn``) say the same thing.
  43. FAILED_TURN_NOTICE = (
  44. "Your request was not processed. Send it again if you still want me to carry it out."
  45. )
  46. PARTIAL_FAILED_TURN_NOTICE = (
  47. "This turn did not complete. Some actions may already have run; verify their effects "
  48. "before resending."
  49. )
  50. # A turn no person sent (a cron run, a process completion, a webhook delivery) lost across a gateway
  51. # restart, or fenced inside the running owner (a lost managed worker): it settles interrupted and is
  52. # never re-run, so nobody is asked to resend it (#134889 GW-10). Neutral: not every path restarted.
  53. AUTOMATION_INTERRUPTED_NOTICE = (
  54. "An automated delivery was interrupted and was not run again. Some "
  55. "actions may already have run; verify their effects."
  56. )
  57. # Durable tail roles a failed turn leaves open: its accepted ``user`` row, or the ``tool`` row of a
  58. # call that ran before the failure. An ``assistant`` tail is already closed (a reply or a boundary).
  59. OPEN_TURN_TAIL_ROLES = frozenset({"user", "tool"})
  60. # ``messages.display_kind`` of that row: display-only (stripped before every provider request),
  61. # so renderers show a Hermes notice and room pollers never read it as the model's reply.
  62. FAILED_TURN_DISPLAY_KIND = "failed_turn"
  63. def untyped_failed_turn_display_kind(role: Any, content: Any) -> Optional[str]:
  64. """``FAILED_TURN_DISPLAY_KIND`` for a boundary row persisted before the closers typed it
  65. (exact notice text, so a real reply quoting it stays a reply); read-side only."""
  66. if role == "assistant" and isinstance(content, str) and content.strip() in (
  67. FAILED_TURN_NOTICE, PARTIAL_FAILED_TURN_NOTICE, AUTOMATION_INTERRUPTED_NOTICE,
  68. ):
  69. return FAILED_TURN_DISPLAY_KIND
  70. return None
  71. def failed_turn_notice(turn_messages: Any) -> str:
  72. """Boundary copy for a failed turn: never claim "not processed" when a tool may have run."""
  73. for row in turn_messages or ():
  74. if isinstance(row, dict) and (
  75. row.get("role") == "tool" or (row.get("role") == "assistant" and row.get("tool_calls"))
  76. ):
  77. return PARTIAL_FAILED_TURN_NOTICE
  78. return FAILED_TURN_NOTICE
  79. def provider_label_for(provider: Any) -> str:
  80. """Human-friendly provider name for chat copy (``"OpenRouter"``, ``"Nous Portal"``…)."""
  81. from hermes_cli.models import provider_label
  82. return provider_label(str(provider or ""))
  83. # ---- turn_exit_reason → failure verdict (finalize_turn stamps these) --------------------------
  84. class ExitFailure(NamedTuple):
  85. """Verdict for a loop exit. ``fails_turn`` False = advisory: the descriptor fields are
  86. stamped so Desktop/TUI show a specific code, but ``failed``/``completed`` keep the values
  87. the loop chose — cron silence, the kanban dispatcher breaker and gateway transcript
  88. persistence all key on ``failed`` and must not change because a code was added."""
  89. reason: str
  90. retryable: bool
  91. fails_turn: bool = True
  92. # (exit-reason prefix, failure_reason, retryable, fails_turn). Prefix match: several reasons
  93. # carry a parenthesised detail (``local_processing_error(...)``).
  94. _EXIT_REASON_FAILURES: tuple[tuple[str, str, bool, bool], ...] = (
  95. # Advisory: the reasoning-only text may literally be the answer, and cron stays silent.
  96. ("empty_response_exhausted", "empty_response", True, False),
  97. ("all_retries_exhausted_no_response", FailoverReason.server_error.value, True, True),
  98. # #55316/#54756: the loop stopped on a tool tail with no follow-up text; the
  99. # finalizer synthesizes the visible close and fails the turn.
  100. ("pending_tool_result", "loop_error", True, True),
  101. ("interpreter_shutdown", "interpreter_shutdown", False, True),
  102. # Advisory: a deterministic local bug is not a task failure for the kanban breaker.
  103. ("local_processing_error", "loop_error", False, False),
  104. ("repeated_outer_errors", "loop_error", True, True),
  105. ("error_near_max_iterations", "loop_error", True, True),
  106. ("context_compression_timeout", "context_overflow", False, True),
  107. ("context_compression_exhausted", "context_overflow", False, True),
  108. ("ollama_runtime_context_too_small", "context_overflow", False, True),
  109. # Advisory: the loop ends these as an incomplete (not failed) turn with an explainer.
  110. ("redirect_restart_limit_exceeded", "loop_error", True, False),
  111. ("rebuilt_restart_limit_exceeded", "loop_error", True, False),
  112. )
  113. # Provider error code carried inside an HTTP-200 body → classifier reason.
  114. _INVALID_RESPONSE_CODES: dict[int, str] = {
  115. 429: FailoverReason.rate_limit.value,
  116. 500: FailoverReason.server_error.value, 502: FailoverReason.server_error.value,
  117. 503: FailoverReason.overloaded.value, 529: FailoverReason.overloaded.value,
  118. 504: FailoverReason.timeout.value, 524: FailoverReason.timeout.value,
  119. }
  120. def invalid_response_failure_reason(response: Any) -> str:
  121. """``failure_reason`` for an empty/malformed HTTP-200 body: the embedded provider error
  122. code when there is one (so the desktop shows Retry + Switch provider consistently), else
  123. the ``invalid_response`` site code."""
  124. err = getattr(response, "error", None) if response is not None else None
  125. code = getattr(err, "code", None) if err is not None else None
  126. if code is None and isinstance(err, dict):
  127. code = err.get("code")
  128. try:
  129. return _INVALID_RESPONSE_CODES.get(int(code), "invalid_response") if code is not None else "invalid_response"
  130. except (TypeError, ValueError):
  131. return "invalid_response"
  132. def exit_reason_failure(turn_exit_reason: Any) -> Optional[ExitFailure]:
  133. """:class:`ExitFailure` for a loop exit that carries a failure verdict, else None."""
  134. reason = str(turn_exit_reason or "")
  135. for prefix, code, retryable, fails_turn in _EXIT_REASON_FAILURES:
  136. if reason.startswith(prefix):
  137. return ExitFailure(code, retryable, fails_turn)
  138. return None
  139. def is_max_iteration_handoff(result: Any) -> bool:
  140. """A non-failed, non-interrupted ``max_iterations_reached(N/N)`` result that still carries a
  141. summary. ``completed`` is False because the work did not finish in that turn, but the turn
  142. itself is a resumable boundary — not a failure — so cron delivers the summary and an active
  143. ``/goal`` may judge it (#102213). Provider/API failures never match (cf. #63180)."""
  144. if not isinstance(result, dict):
  145. return False
  146. if result.get("failed") is True or result.get("interrupted") is True:
  147. return False
  148. if result.get("completed") is not False:
  149. return False
  150. reason = result.get("turn_exit_reason")
  151. if not (isinstance(reason, str) and reason.startswith("max_iterations_reached(")):
  152. return False
  153. return bool(str(result.get("final_response") or "").strip())
  154. # ---- chat copy tables -----------------------------------------------------------------------
  155. _NEXT_STEPS_RETRY = "Wait a minute and send /retry, or switch models with /model."
  156. _NEXT_STEPS_LOOP = (
  157. "Your message is saved. Send `continue` to try again, or start a new session with /new. "
  158. "If it happens again, run `hermes doctor` and share the error details."
  159. )
  160. # Lead sentence per classifier reason once retries and fallback are exhausted.
  161. _EXHAUSTED_LEADS: dict[str, str] = {
  162. FailoverReason.rate_limit.value: "{label} rate-limited every one of {attempts} attempts",
  163. FailoverReason.upstream_rate_limit.value: "{label} rate-limited every one of {attempts} attempts",
  164. FailoverReason.overloaded.value: "{label} reported it was overloaded on all {attempts} attempts",
  165. FailoverReason.server_error.value: "{label} returned a server error on all {attempts} attempts",
  166. FailoverReason.timeout.value: "{label} didn't respond in time on any of {attempts} attempts",
  167. }
  168. _EXHAUSTED_DEFAULT_LEAD = "{label} didn't answer after {attempts} attempts"
  169. # One attempt: an attended free-tier session ended the cycle on a cooldown longer than it waits.
  170. _EXHAUSTED_FIRST_ATTEMPT_LEADS: dict[str, str] = {
  171. FailoverReason.rate_limit.value: "{label} is rate-limiting requests right now",
  172. FailoverReason.upstream_rate_limit.value: "{label} is rate-limiting requests right now",
  173. }
  174. # Terminal copy for a non-retryable provider rejection, keyed by classifier reason.
  175. _NONRETRYABLE_COPY: dict[str, str] = {
  176. FailoverReason.model_not_found.value: (
  177. "Model '{model}' isn't available on {label}. Pick a different model with /model "
  178. "(or `hermes model` in a terminal).{prefix_hint}"
  179. ),
  180. FailoverReason.format_error.value: (
  181. "{label} rejected this request as malformed, so the model didn't answer. Start a clean "
  182. "session with /new or switch models with /model; if it keeps happening, run `hermes doctor`."
  183. ),
  184. FailoverReason.role_alternation.value: (
  185. "{label} requires user and assistant turns to strictly alternate and rejected this "
  186. "conversation's shape. Start a clean session with /new or switch models with /model."
  187. ),
  188. FailoverReason.ssl_cert_verification.value: (
  189. "Hermes couldn't verify {label}'s security certificate, so the connection was refused. "
  190. "This is usually a corporate proxy or an outdated certificate store on this computer — "
  191. "see the terminal or `{home}/logs/agent.log` for the exact fix, or try another provider "
  192. "with /model."
  193. ),
  194. FailoverReason.provider_policy_blocked.value: (
  195. "{label} refused this request because of a policy on your account (its data/privacy "
  196. "settings, or a block the model's upstream provider placed on the account), so the model "
  197. "didn't answer and retrying won't help. Check the account with the provider, or switch "
  198. "models with /model."
  199. ),
  200. FailoverReason.data_policy_denied.value: (
  201. "This conversation holds a result from a connected app that may only go to a model that "
  202. "does not train on your data, and '{model}' on {label} can't promise that. Switch models "
  203. "with /model, run /compress to summarize the result away, or start fresh with /new. If you "
  204. "are on the free tier, no free model can take this content: upgrade, or use /compress or /new."
  205. ),
  206. FailoverReason.upstream_blocked.value: (
  207. "A firewall/CDN in front of {label} blocked the request before it reached the model, so "
  208. "your key is probably fine. Set a custom User-Agent via the provider's extra_headers, check "
  209. "the proxy/WAF rules, or switch providers with /model."
  210. ),
  211. }
  212. _NONRETRYABLE_DEFAULT_COPY = (
  213. "{label} rejected the request and retrying won't help. Pick another model with /model, "
  214. "or check the details in `{home}/logs/agent.log`."
  215. )
  216. _AUTH_COPY: dict[str, str] = {
  217. "oauth": "{label} rejected your sign-in, so the model can't be reached. Sign in again: `{relogin}`.",
  218. "api_key": (
  219. "{label} rejected your API key, so the model can't be reached. Update it in "
  220. "Settings → Providers, or run `hermes setup` in a terminal."
  221. ),
  222. }
  223. CONTENT_POLICY_NEXT_STEPS = (
  224. "Try rewording your message or removing sensitive attachments, or switch to another "
  225. "model with /model."
  226. )
  227. # ---- one reason → "what happened" gloss, shared by cron, subagent and chat notices ------------
  228. # FailoverReason / site code → one clause (no HTTP codes, no "provider" jargon). ``{subject}``
  229. # is who was asking ("the job", "it"), ``{possessive}`` its possessive ("the job's", "its").
  230. # Reasons absent here are NOT provider-shaped; callers fall back to the raw error text.
  231. FAILURE_CAUSE_GLOSS: dict[str, str] = {
  232. FailoverReason.timeout.value: "the AI model service did not respond in time",
  233. FailoverReason.rate_limit.value: "the AI model service was rate-limited (too many requests)",
  234. FailoverReason.upstream_rate_limit.value: "the AI model service was rate-limited (too many requests)",
  235. FailoverReason.overloaded.value: "the AI model service is overloaded right now",
  236. FailoverReason.server_error.value: "the AI model service returned an internal error",
  237. FailoverReason.billing.value: "the AI model service says the account's usage or credit limit is reached",
  238. # Wire-level billing code (not a FailoverReason) that error_surface routes to the billing layer.
  239. "billing_unverified": "the AI model service says the account's usage or credit limit is reached",
  240. FailoverReason.auth.value: "the AI model service rejected the sign-in",
  241. FailoverReason.auth_permanent.value: "the AI model service rejected the sign-in",
  242. FailoverReason.upstream_blocked.value: "a firewall/CDN in front of the AI model service blocked the request",
  243. FailoverReason.model_not_found.value: "the model {subject} uses was not found at the AI model service",
  244. FailoverReason.content_policy_blocked.value: "the AI model service's safety filter rejected the request",
  245. FailoverReason.provider_policy_blocked.value: (
  246. "the AI model service refused the request because of a policy on the account"
  247. ),
  248. FailoverReason.data_policy_denied.value: (
  249. "{possessive} context holds a connected-app result that needs a model that does not train on data"
  250. ),
  251. "context_overflow": "{possessive} request grew too large for the model",
  252. "payload_too_large": "{possessive} request grew too large for the model",
  253. }
  254. def failure_cause_gloss(reason: Any, *, subject: str = "it", possessive: str = "its") -> Optional[str]:
  255. """Plain clause for a classified ``failure_reason``; None when the reason has no gloss."""
  256. template = FAILURE_CAUSE_GLOSS.get(str(reason or ""))
  257. return template.format(subject=subject, possessive=possessive) if template else None
  258. # ---- site-code copy -------------------------------------------------------------------------
  259. # Chat copy for the codes in SITE_FAILURE_CODES that a loop site renders itself
  260. # (``empty_response`` is worded by agent/turn_explainers.py, ``session_busy`` by the lease).
  261. _FAILURE_CODE_COPY: dict[str, str] = {
  262. "context_overflow": (
  263. "This conversation has grown too long for {model} to read, and Hermes couldn't shrink "
  264. "it enough automatically. Start a new session with /new (your history is kept), or try "
  265. "/compress once more. Switching to a model with a bigger context window also works."
  266. ),
  267. "truncated": (
  268. "The model's reply was cut off before it finished (it hit its output length limit), so "
  269. "Hermes didn't run the incomplete action. Nothing was changed. Send `continue`, ask for "
  270. "the work in smaller steps, or raise max_tokens for this model."
  271. ),
  272. "invalid_response": (
  273. "{label} sent back an empty or broken reply {attempts} times — it is probably overloaded "
  274. "or rate-limiting you. " + _NEXT_STEPS_RETRY + "\n\nDetails: {detail}"
  275. ),
  276. "loop_error": (
  277. "Hermes hit repeated errors and stopped this turn so it wouldn't keep retrying. "
  278. + _NEXT_STEPS_LOOP + "\n\nDetails: {detail}"
  279. ),
  280. "interpreter_shutdown": (
  281. "Hermes was shutting down and stopped this turn. Your conversation is saved — reopen "
  282. "it{resume} and send your message again."
  283. ),
  284. }
  285. # One-off outcome strings: deterministic loop exits that are NOT failure codes (the result
  286. # they ride carries a code from the table above, or none at all).
  287. _ONE_OFF_COPY: dict[str, str] = {
  288. "payload_too_large": (
  289. "This conversation (including attachments) has grown too large to send to {model}, and "
  290. "Hermes couldn't shrink it enough automatically. Start a new session with /new (your "
  291. "history is kept), or try /compress once more."
  292. ),
  293. "compression_disabled": (
  294. "This conversation is too long for {model} and automatic shrinking is turned off in "
  295. "your settings (compression.enabled). Run /compress to shrink it now, /new to start "
  296. "fresh, or pick a model with a bigger context window."
  297. ),
  298. # Wording deliberately avoids the overflow phrases gateway/run_turn.py matches on
  299. # (``_CONTEXT_OVERFLOW_ERROR_PHRASES``): this failure is transient, so the user's
  300. # message must stay in the transcript and the session must not be auto-reset.
  301. "server_context_rejection": (
  302. "The model server rejected this request as too large, but this conversation is only "
  303. "about {tokens:,} tokens — well under the {window:,}-token window Hermes knows for "
  304. "{model} — so shrinking it would not help. Another request on the same server (for "
  305. "example a background memory review from an earlier session) was probably holding its "
  306. "capacity, or the server runs {model} with a smaller window than Hermes assumes. Wait a "
  307. "moment and send /retry; if it keeps happening, check the server's context setting."
  308. ),
  309. # Rides failure_reason="truncated": args were cut mid-JSON but the model never reported
  310. # an output-length stop, so don't claim it hit one (#91717).
  311. "truncated_unreported": (
  312. "The model's action arrived cut off partway through, so Hermes didn't run it. Nothing was changed. The model didn't report hitting its output "
  313. "limit, so this was most likely a dropped connection or a provider/router cutting the "
  314. "reply short. Send /retry; if it keeps happening, ask for the work in smaller steps."
  315. ),
  316. "stream_dropped_tool_call": (
  317. "The connection to {label} kept dropping while the model was writing a large action, "
  318. "so nothing was run. Check your network and send /retry; asking for the file in smaller "
  319. "pieces also helps."
  320. ),
  321. # Rides failure_reason="truncated": clean EOF (no transport error, no finish_reason)
  322. # mid tool-call, retries exhausted — not a network problem on the user's side (#102766).
  323. "stream_closed_tool_call": (
  324. "{label} kept closing the stream before the model finished writing its action, without "
  325. "reporting an error, so nothing was run. This is usually the provider or a proxy in front "
  326. "of it cutting long replies short. Send /retry; asking for the work in smaller steps also helps."
  327. ),
  328. # Rides failure_reason="loop_error" (advisory; the turn is incomplete, not failed).
  329. "local_processing_error": (
  330. "Hermes hit an internal error while handling the model's reply and stopped this turn. "
  331. + _NEXT_STEPS_LOOP + "\n\nDetails: {detail}"
  332. ),
  333. "max_iterations_no_summary": (
  334. "I ran out of steps for this turn ({limit} tool calls) before finishing, and couldn't "
  335. "produce a summary. Send `continue` to keep going, or raise `max_iterations` in your config."
  336. ),
  337. "nous_rate_limit": (
  338. "Wait for the reset and send /retry, or switch models with /model. To avoid waits, add "
  339. "a backup provider with `hermes fallback add`."
  340. ),
  341. }
  342. _SITE_COPY: dict[str, str] = {**_FAILURE_CODE_COPY, **_ONE_OFF_COPY}
  343. def site_copy(code: str, **fields: Any) -> str:
  344. """Chat copy for a failure code or one-off loop outcome; unknown fields default to empty strings."""
  345. fields.setdefault("home", display_hermes_home())
  346. return _SITE_COPY[code].format_map(_Defaults(fields))
  347. def exhausted_copy(reason: str, *, label: str, attempts: int, summary: str, reset_seconds: Optional[float] = None,
  348. error: Any = None) -> str:
  349. """Chat copy once retries + fallback are exhausted (``max_retries_exhausted_result``). A rate
  350. limit whose reset window is known names it: an 8.6h plan quota is not "wait a minute" (#89401).
  351. A stream cut by ``agent.stream_max_lifetime`` names the setting: the provider was responding,
  352. so neither waiting nor a backup provider helps."""
  353. if isinstance(error, StreamLifetimeExceeded):
  354. return (f"The response was still streaming when agent.stream_max_lifetime ({error.cap:g}s) cut it, "
  355. f"on all {attempts} attempts. Raise agent.stream_max_lifetime, or set it to 0 to turn the "
  356. "cap off, if this model legitimately streams this long.")
  357. first_attempt = attempts == 1 and reason in _EXHAUSTED_FIRST_ATTEMPT_LEADS
  358. lead = (_EXHAUSTED_FIRST_ATTEMPT_LEADS if first_attempt else _EXHAUSTED_LEADS).get(
  359. reason, _EXHAUSTED_DEFAULT_LEAD).format(label=label, attempts=attempts)
  360. # The free-tier cutoff (one attempt) fires on any cooldown over a minute, so it always names the reset.
  361. if reset_seconds is not None and (reset_seconds >= 120 or first_attempt and reset_seconds > 0):
  362. from agent.retry_utils import format_reset_window
  363. situation = (f"its usage limit resets in {format_reset_window(reset_seconds)}. "
  364. "Send /retry after that, or switch models with /model.")
  365. else:
  366. situation = f"it looks temporarily unavailable. {_NEXT_STEPS_RETRY}"
  367. return (
  368. f"{lead} — {situation} To avoid this in future, "
  369. f"add a backup provider with `hermes fallback add`.\n\nProvider said: {summary}"
  370. )
  371. def limit_reset_copy(resets_at: float, now: Optional[float] = None) -> str:
  372. """One chat/CLI line naming when the provider says the limit lifts (#98852): the Retry-After
  373. / ``resets_at`` the loop already honours for backoff, shown to the user instead of a bare
  374. "wait a minute". Local wall-clock time plus the remaining wait; empty once it has passed."""
  375. now = time.time() if now is None else now
  376. remaining = int(resets_at - now)
  377. if remaining <= 0:
  378. return ""
  379. hours, minutes = divmod((remaining + 59) // 60, 60)
  380. wait = f"{hours}h {minutes:02d}m" if hours else f"{minutes}m"
  381. return f"Limit resets at {time.strftime('%H:%M', time.localtime(resets_at))} (in {wait})."
  382. def oauth_relogin_command(provider: Any) -> str:
  383. """The exact re-login command for a rejected OAuth grant, naming the provider slug and the active
  384. named profile: a profile's credentials are its own (93889b770da), so a bare ``hermes auth`` from
  385. the root profile re-signs the wrong store and the goal judge, reading a bare 401, guesses which
  386. service revoked the token (#114012)."""
  387. from hermes_constants import profile_cli_selector
  388. slug = str(provider or "").strip().lower()
  389. if slug == "nous":
  390. return f"hermes {profile_cli_selector()}portal"
  391. return f"hermes {profile_cli_selector()}auth add {slug} --type oauth"
  392. def relogin_command_hint(provider: Any) -> str:
  393. """Re-sign-in command for a rejected credential on surfaces that may not know the provider:
  394. the exact OAuth command for a known OAuth slug, ``hermes auth add <slug>`` for a known API-key
  395. slug, and the ``<provider>`` placeholder when the slug is unknown — always carrying the
  396. ``-p <profile>`` selector so a profile user never re-signs the ROOT store (#114012)."""
  397. from hermes_constants import profile_cli_selector
  398. slug = str(provider or "").strip().lower()
  399. if not slug:
  400. return f"hermes {profile_cli_selector()}auth add <provider>"
  401. from agent.error_surface import auth_kind
  402. if auth_kind(slug) == "oauth":
  403. return oauth_relogin_command(slug)
  404. return f"hermes {profile_cli_selector()}auth add {slug}"
  405. def nonretryable_copy(
  406. classified: Any, *, provider: Any, model: Any, summary: str, prefix_suggestion: Optional[str] = None,
  407. ) -> str:
  408. """Chat copy for a terminal non-retryable rejection (auth, model missing, TLS, generic 4xx)."""
  409. label = provider_label_for(provider)
  410. if getattr(classified, "is_auth", False):
  411. from agent.error_surface import auth_kind
  412. template = _AUTH_COPY[auth_kind(str(provider or ""))]
  413. else:
  414. template = _NONRETRYABLE_COPY.get(classified.reason.value, _NONRETRYABLE_DEFAULT_COPY)
  415. prefix_hint = (
  416. f" If you typed the name yourself it may be missing its vendor prefix — did you mean "
  417. f"'{prefix_suggestion}'?"
  418. if prefix_suggestion else ""
  419. )
  420. body = template.format(label=label, model=model, home=display_hermes_home(), prefix_hint=prefix_hint,
  421. relogin=oauth_relogin_command(provider))
  422. return f"{body}\n\nProvider said: {summary}"
  423. def content_policy_copy(*, label: str, summary: str) -> str:
  424. return (
  425. f"{label}'s safety filter refused this request, so the model didn't answer. "
  426. f"{CONTENT_POLICY_NEXT_STEPS}\n\nProvider said: {summary}"
  427. )
  428. def short_detail(exc: Any, limit: int = 200) -> str:
  429. """First line of an exception's text, capped, for a trailing ``Details:`` line."""
  430. text = (str(exc) or type(exc).__name__).strip().splitlines()
  431. first = text[0] if text else type(exc).__name__
  432. return first if len(first) <= limit else first[: limit - 1] + "…"
  433. class _Defaults(dict):
  434. def __missing__(self, key: str) -> str:
  435. return ""