auth_error_copy.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. """Plain-language copy for sign-in and provider-setup failures (CLI).
  2. One table of ``(predicate, lead sentence)`` classifies an exception into a sentence a first-time
  3. user can act on; the raw exception is demoted to a ``Details:`` line so nothing is lost for
  4. support. Callers print ``sign_in_failure_lines(...)`` / ``provider_setup_failure_lines(...)``
  5. line by line.
  6. """
  7. from __future__ import annotations
  8. from typing import Callable, Sequence, Tuple
  9. # httpx class names and stdlib bases that mean "the request never got a usable answer".
  10. _NETWORK_ERROR_TYPES = frozenset({
  11. "ConnectError", "ConnectTimeout", "ReadTimeout", "PoolTimeout", "WriteTimeout", "TimeoutException",
  12. "RemoteProtocolError", "ReadError", "ProxyError", "UnsupportedProtocol", "NetworkError",
  13. })
  14. # OAuth device-flow error codes (RFC 8628 §3.5) -> plain copy. ``{retry}`` is the retry command.
  15. DEVICE_FLOW_ERROR_COPY = {
  16. "expired_token": (
  17. "The sign-in code expired before it was approved in the browser. Run `{retry}` to get a new code."),
  18. "access_denied": (
  19. "Sign-in was declined in the browser. Run `{retry}` to try again, or `hermes model` to pick a "
  20. "different provider."),
  21. "invalid_grant": (
  22. "The sign-in code was not accepted by the server. Run `{retry}` to get a new code."),
  23. "invalid_client": (
  24. "The server did not recognize this copy of Hermes. Run `hermes update`, then `{retry}` again."),
  25. }
  26. class DeviceCodeExpired(TimeoutError):
  27. """The device code ran out before the user approved it in the browser (not a network timeout)."""
  28. code = "device_code_timeout"
  29. # ``AuthError.code`` values the device-code pollers raise when the code runs out.
  30. _DEVICE_CODE_EXPIRED_CODES = frozenset({"device_code_timeout", "timeout"})
  31. class SignInCopyError(RuntimeError):
  32. """Exception whose ``str()`` is already user copy (lead line + ``Details:`` line)."""
  33. def __init__(self, message: str, *, oauth_error_code: str = "") -> None:
  34. super().__init__(message)
  35. self.oauth_error_code = oauth_error_code
  36. def is_network_error(exc: BaseException) -> bool:
  37. """True for connection/DNS/timeout failures from httpx, requests or the stdlib."""
  38. if isinstance(exc, (SignInCopyError, DeviceCodeExpired)):
  39. return False
  40. names = {cls.__name__ for cls in type(exc).__mro__}
  41. return bool(names & _NETWORK_ERROR_TYPES) or isinstance(exc, (ConnectionError, TimeoutError))
  42. def is_device_code_expired(exc: BaseException) -> bool:
  43. """True when a device-code sign-in ended because its code ran out (any provider)."""
  44. return (getattr(exc, "code", None) in _DEVICE_CODE_EXPIRED_CODES
  45. or getattr(exc, "oauth_error_code", "") == "expired_token")
  46. def is_cancelled(exc: BaseException) -> bool:
  47. return isinstance(exc, (KeyboardInterrupt, EOFError)) or (
  48. isinstance(exc, SystemExit) and exc.code in (130, None, 0))
  49. def device_flow_error(code: str, description: str, *, retry_command: str = "hermes portal") -> SignInCopyError:
  50. """Exception for an OAuth device-flow error code whose text is already user-facing.
  51. Unknown codes keep the server's description as the lead (it is the only information available)
  52. but still name the retry command.
  53. """
  54. lead = DEVICE_FLOW_ERROR_COPY.get(code, "").format(retry=retry_command)
  55. if not lead:
  56. lead = (f"Sign-in did not complete: {description or 'the server rejected the request'}. "
  57. f"Run `{retry_command}` to try again.")
  58. details = f"{code}: {description}" if code else description
  59. return SignInCopyError(f"{lead}\n Details: {details}" if details else lead, oauth_error_code=code)
  60. def _details_line(exc: BaseException) -> str:
  61. text = str(exc).strip() or type(exc).__name__
  62. return f" Details: {text}"
  63. _Rule = tuple[Callable[[BaseException], bool], str]
  64. def _classify(exc: BaseException, rules: Sequence[_Rule], other: str) -> str:
  65. return next((copy for pred, copy in rules if pred(exc)), other)
  66. def sign_in_failure_lines(
  67. exc: BaseException, *, service_host: str = "portal.nousresearch.com", retry_command: str = "hermes portal",
  68. ) -> list:
  69. """Lines to print when a device-code / browser sign-in fails for any non-timeout reason."""
  70. from hermes_cli.observability.shared_metrics_setup import note_sign_in_failure
  71. note_sign_in_failure(exc)
  72. if isinstance(exc, SignInCopyError):
  73. return str(exc).splitlines()
  74. rules: Sequence[_Rule] = (
  75. (is_cancelled, "Sign-in was cancelled. Run `{retry}` when you want to try again."),
  76. (is_network_error,
  77. "Could not sign in: Hermes could not reach {host}. Check your internet connection or proxy, "
  78. "then run `{retry}` again."),
  79. )
  80. lead = _classify(
  81. exc, rules,
  82. "Could not sign in. Run `{retry}` to try again, or `hermes model` to pick a different provider.")
  83. lines = [lead.format(host=service_host, retry=retry_command)]
  84. if not is_cancelled(exc):
  85. lines.append(_details_line(exc))
  86. return lines
  87. def provider_setup_failure_lines(exc: BaseException, *, retry_command: str = "hermes model") -> list:
  88. """Lines to print when the setup wizard's provider step fails: reason, that nothing was saved,
  89. and how to retry."""
  90. nothing_saved = (
  91. "Your provider settings were not changed. Continue the wizard now and run "
  92. f"`{retry_command}` afterwards to try again.")
  93. if isinstance(exc, SignInCopyError):
  94. lead, *details = str(exc).splitlines()
  95. return [f"Could not finish connecting a provider: {lead[0].lower()}{lead[1:]}", nothing_saved, *details]
  96. rules: Sequence[_Rule] = (
  97. (is_cancelled, "sign-in was cancelled"),
  98. (is_network_error, "no internet connection, or the provider could not be reached"),
  99. )
  100. reason = _classify(exc, rules, "something went wrong while talking to the provider")
  101. lines = [f"Could not finish connecting a provider ({reason}).", nothing_saved]
  102. if not is_cancelled(exc):
  103. lines.append(_details_line(exc))
  104. return lines
  105. def unknown_provider_hint(provider_name: str) -> str:
  106. """Hint for an ``Unknown provider`` error from the resolver: the install line of a provider that left
  107. core for a plugin, the replacement for a removed provider, else the config issues that cause it."""
  108. from hermes_cli.left_core_migration import provider_install_hint
  109. if moved := provider_install_hint(provider_name):
  110. return moved
  111. if str(provider_name or "").strip().lower() in {"opencode-free", "free", "opencode_free"}:
  112. return ("OpenCode discontinued anonymous free-tier access outside its own client "
  113. "(relay 403s FreeTierError), so the keyless 'opencode-free' provider was removed. "
  114. "Switch to 'opencode-zen' (pay-as-you-go, OPENCODE_ZEN_API_KEY) or 'opencode-go' "
  115. "($10/mo subscription, OPENCODE_GO_API_KEY) via 'hermes model'.")
  116. try:
  117. from hermes_cli.config import validate_config_structure
  118. issues = validate_config_structure()
  119. if not issues:
  120. return ""
  121. lines = ["Config issue detected — run 'hermes doctor' for full diagnostics:"]
  122. for ci in issues:
  123. lines.append(f" [{'ERROR' if ci.severity == 'error' else 'WARNING'}] {ci.message}")
  124. if ci.hint and ci.hint.splitlines()[0]:
  125. lines.append(f" → {ci.hint.splitlines()[0]}")
  126. return "\n".join(lines)
  127. except Exception: # health: allow BLE001 -- moved verbatim from auth.py; a hint never masks the error it explains
  128. return ""