cli_chat_error_copy.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. """Plain-language copy for chat-turn failures shown in the CLI response panel.
  2. The chat panel used to echo ``Error: HTTP 401: Invalid API key`` as the assistant's answer. These
  3. helpers map the classifier verdict (``agent/error_classifier.py``) to WHAT happened + WHAT TO DO,
  4. and demote the raw provider text to a ``Details:`` line. Copy lives in the i18n catalog under
  5. ``cli.error.*`` and is resolved at render time for the active language.
  6. """
  7. from __future__ import annotations
  8. from agent.i18n import t
  9. _SUMMARY_LIMIT = 120
  10. # FailoverReason.value -> catalog key suffix. Reasons sharing copy point at one key.
  11. _REASON_KEYS: dict[str, str] = {
  12. "auth": "auth",
  13. "auth_permanent": "auth",
  14. "billing": "billing",
  15. "model_not_found": "model_not_found",
  16. "rate_limit": "rate_limit",
  17. "upstream_rate_limit": "rate_limit",
  18. "upstream_blocked": "upstream_blocked",
  19. "overloaded": "overloaded",
  20. "server_error": "server_error",
  21. "timeout": "timeout",
  22. }
  23. _UNKNOWN_KEY = "unknown"
  24. def _short(text: str, limit: int | None = _SUMMARY_LIMIT) -> str:
  25. first = (text or "").strip().splitlines()[0] if (text or "").strip() else ""
  26. return first if limit is None or len(first) <= limit else first[: limit - 1].rstrip() + "…"
  27. def refusal_text(error: BaseException | str) -> str:
  28. """The refusal as the client shows it: the reason code, plus the check that fired when the owner
  29. named one (``invalid_params (toolsets: unknown or invalid toolset name: 'mcp-codegraph')``).
  30. The gateway sends ``field``/``detail`` in the JSON-RPC error's ``data``
  31. (``gateway/session_controls.py``), and ``hermes_cli.gateway_client.rpc_error`` carries the
  32. bounded scalars onto ``GatewayRPCError.data``. A refusal from anywhere else has no ``data`` and
  33. reads exactly as before."""
  34. if str(error) == "launch_credentials_unavailable":
  35. # The chat's launch key changed: every retry repeats the refusal, so name the way out.
  36. from agent.turn_failure_copy import launch_credentials_copy
  37. return launch_credentials_copy(error)
  38. data = getattr(error, "data", None)
  39. data = data if isinstance(data, dict) else {}
  40. field, detail = str(data.get("field") or "").strip(), str(data.get("detail") or "").strip()
  41. if not field and not detail:
  42. return str(error)
  43. return f"{error} ({field or 'unnamed field'}{': ' + detail if detail else ''})"
  44. def chat_error_response(
  45. error: Exception | str, *, provider: str = "", model: str = "", failure_reason: str | None = None,
  46. ) -> str:
  47. """Two-line panel text: plain sentence with the fix command, then ``Details: <raw>``.
  48. ``failure_reason`` is the verdict the turn loop already stamped on its result
  49. (``agent/turn_failure_copy.stamp_failure``). When present it is used as-is instead of
  50. re-classifying a summarised string (which has no status code and almost always lands on
  51. 'unknown'); for the loop's own site codes the ``error`` text is already the user-facing copy,
  52. so it is returned verbatim rather than wrapped and demoted to a Details line."""
  53. reason = str(failure_reason or "").strip()
  54. if reason:
  55. from agent.turn_failure_copy import SITE_FAILURE_CODES
  56. text = str(error or "").strip()
  57. if reason in SITE_FAILURE_CODES and text:
  58. return text
  59. else:
  60. from agent.error_classifier import classify_api_error
  61. exc = error if isinstance(error, Exception) else Exception(str(error))
  62. reason = classify_api_error(exc, provider=provider or "", model=model or "").reason.value
  63. lead = t(
  64. f"cli.error.{_REASON_KEYS.get(reason, _UNKNOWN_KEY)}",
  65. provider=provider or t("cli.error.the_provider"),
  66. model=model or t("cli.error.the_current_model"),
  67. )
  68. return t("cli.error.with_details", lead=lead, details=_short(refusal_text(error), 300))
  69. def agent_init_failure_message(error: BaseException) -> str:
  70. """Copy for a failed AIAgent build on first message: the user's turn was dropped.
  71. A gateway that cannot be reached keeps its whole first line: its discovery detail is already
  72. bounded (``DiscoveryError.bounded_detail``) and ends in the repair command, which the summary
  73. limit would cut mid-path."""
  74. from hermes_cli.gateway_client import GatewayUnavailableError
  75. limit = None if isinstance(error, GatewayUnavailableError) else _SUMMARY_LIMIT
  76. return t("cli.error.agent_init_failed", error=_short(refusal_text(error), limit) or type(error).__name__)