welcome_trial.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. """The desktop's welcome trial: free inference on ``nous/welcome`` for a first install, once per OS user.
  2. Only the backend the desktop spawned on this machine can claim it, only when this OS user has never
  3. used Hermes here (``install_state``), and only with no provider and no Nous identity yet. The claim
  4. mints a guest stamped with ``WELCOME_CLAIM_FLAG`` in the mint's own write and writes the OS user's
  5. marker, so the trial is never claimed twice for that user. Another OS account on the same computer is
  6. a separate first install. A claim that is lost later (the guest is reaped, ``auth.json`` is
  7. deleted, the user signs in) is never made again: that user lands on provider setup and sign-in like
  8. anyone else.
  9. Enforcement is client-side; the account service's own entitlement check follows separately.
  10. """
  11. from __future__ import annotations
  12. import logging
  13. from dataclasses import dataclass
  14. from collections.abc import Callable
  15. from typing import Any, Optional
  16. from hermes_cli import anon_auth
  17. logger = logging.getLogger("hermes_cli.auth")
  18. def _has_nous_identity() -> bool:
  19. from hermes_cli.auth_nous import _read_shared_nous_state
  20. return anon_auth.current_nous_state() is not None or _read_shared_nous_state() is not None
  21. def provider_configured() -> bool:
  22. """Something besides the welcome trial carries inference: a key, a config pin, a sign-in, a host
  23. credential. The resolver itself answers, with the free-tier rung hidden."""
  24. from hermes_cli.auth import resolve_provider
  25. from hermes_cli.auth_constants import AuthError
  26. try:
  27. provider = resolve_provider("auto", skip_free_tier=True)
  28. except AuthError: # no_provider_configured
  29. return False
  30. return provider != "nous" or not anon_auth.has_guest()
  31. def inference_available(*, assume_fresh: bool = False) -> bool:
  32. """Something can carry a first chat on this backend: the trial (claimed, or claimable now) or a
  33. configured provider. One walk of the provider ladder answers both halves."""
  34. if anon_auth.free_inference_active():
  35. return True
  36. configured = provider_configured()
  37. return configured or claim_blocker(assume_fresh=assume_fresh, configured=configured) is None
  38. def _machine_is_used(assume_fresh: bool) -> bool:
  39. from hermes_cli.install_state import probe, trial_reserved
  40. return not assume_fresh and probe().existing and not trial_reserved()
  41. @dataclass(frozen=True, slots=True)
  42. class _Ask:
  43. assume_fresh: bool
  44. configured: Optional[bool] # the caller's provider_configured() answer, when it has one
  45. # Cheapest first; the last one reads the disk. Each is a reason the trial cannot be claimed.
  46. _CLAIM_BLOCKERS: tuple[tuple[str, Callable[[_Ask], bool]], ...] = (
  47. ("not the desktop's local backend", lambda _ask: not anon_auth.on_local_desktop_backend()),
  48. ("guests are switched off", lambda _ask: not anon_auth.guest_allowed()),
  49. ("a Nous identity exists", lambda _ask: _has_nous_identity()),
  50. ("a provider is configured",
  51. lambda ask: provider_configured() if ask.configured is None else ask.configured),
  52. ("Hermes was used on this machine", lambda ask: _machine_is_used(ask.assume_fresh)),
  53. )
  54. def claim_blocker(*, assume_fresh: bool = False, configured: Optional[bool] = None) -> Optional[str]:
  55. """Why the trial cannot be claimed here, or None when it can. *assume_fresh* is the unpackaged
  56. desktop's ``--fresh-install`` switch: it skips only the machine check. *configured* is a
  57. ``provider_configured()`` answer the caller already has, so the ladder is not walked twice."""
  58. ask = _Ask(assume_fresh, configured)
  59. return next((reason for reason, blocks in _CLAIM_BLOCKERS if blocks(ask)), None)
  60. def claim_desktop_free_tier(*, assume_fresh: bool = False, force: bool = False) -> Optional[dict[str, Any]]:
  61. """Claim the trial when nothing blocks it: mint the guest, stamp the claim, mark the machine.
  62. Returns the claimed state, or None when the trial is not available here. A failed mint raises
  63. the coded ``AuthError`` from :func:`anon_auth.ensure_portal_identity` (memoised with its cooldown;
  64. *force* is the user's own retry). Held under the OS user's claim lock from the checks to the
  65. marker write, so two installs starting together claim once."""
  66. from hermes_cli import install_state
  67. with install_state.claim_lock():
  68. install_state.probe.cache_clear() # another install may have claimed since this process looked
  69. settle_interrupted_claim()
  70. if reason := claim_blocker(assume_fresh=assume_fresh):
  71. logger.debug("welcome trial not claimed: %s", reason)
  72. return None
  73. state = anon_auth.ensure_portal_identity(explicit=True, force=force, welcome_claim=True)
  74. if state is None: # still inside the cooldown of the last failure
  75. failure = anon_auth.last_mint_failure() or {}
  76. raise anon_auth._anon_err(
  77. str(failure.get("error") or anon_auth.ANON_FAILURE_COPY[anon_auth.ANON_SERVER_ERROR]),
  78. str(failure.get("error_code") or anon_auth.ANON_SERVER_ERROR),
  79. retry_after=failure.get("retry_after"))
  80. install_state.mark_machine_used()
  81. logger.info("Nous free tier: welcome trial claimed on this machine")
  82. return state
  83. def settle_interrupted_claim() -> bool:
  84. """A claim cut off between its guest write and its marker write leaves the reservation behind.
  85. The stamped guest is the claim, so the reservation goes: kept, it would let a second trial through
  86. once that guest is reaped or deleted. Runs before every claim and at serve boot; True when it did."""
  87. from hermes_cli.auth_nous import _read_shared_nous_state
  88. from hermes_cli.install_state import mark_machine_used, trial_reserved
  89. if not trial_reserved():
  90. return False
  91. stores = (anon_auth.current_nous_state(), _read_shared_nous_state())
  92. if not any(anon_auth.is_guest_state(s) and s.get(anon_auth.WELCOME_CLAIM_FLAG) is True for s in stores):
  93. return False
  94. mark_machine_used()
  95. logger.info("Nous free tier: an interrupted welcome-trial claim was settled")
  96. return True