free_tier_offer.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. """When a free-tier "sign in" offer is due: after finished tasks, backing off.
  2. Two offers share one schedule. ``trial`` is the welcome trial's "sign in for more"; a finished task
  3. is ``tui_gateway.free_tier_task_done``'s call. ``connector`` is for a guest that has connected an app
  4. on its own model key; each app that connects counts as a finished task (``note_app_connected``).
  5. The first offer comes ``OFFER_DELAY_S`` after the first finished task. Each later offer needs another
  6. finished task after the previous offer, comes ``OFFER_DELAY_S`` after that task, and never sooner than
  7. ``REOFFER_AFTER_S[n]`` after the previous offer, so a user who keeps saying "Not now" hears it less
  8. often. Each record is install-wide, under ``<default root>/free_tier/``. Signing in ends the guest,
  9. and with it every offer.
  10. """
  11. from __future__ import annotations
  12. import json
  13. import logging
  14. import math
  15. import threading
  16. import time
  17. from contextlib import contextmanager
  18. from typing import Any, Iterator, Optional
  19. logger = logging.getLogger(__name__)
  20. OFFER_DELAY_S = 180
  21. REOFFER_AFTER_S = (60 * 60, 4 * 60 * 60, 24 * 60 * 60) # after the 1st, 2nd, then every later offer
  22. TRIAL = "trial"
  23. CONNECTOR = "connector"
  24. CONNECTED_APP_FLAG = "has_connected_app"
  25. _RECORDS = {TRIAL: "sign_in_offer.json", CONNECTOR: "connector_offer.json"}
  26. _LOCK = threading.local()
  27. _clock = time.time # tests swap this for a fake clock
  28. def _path(kind: str):
  29. from hermes_constants import get_default_hermes_root
  30. return get_default_hermes_root() / "free_tier" / _RECORDS[kind]
  31. def _read(kind: str) -> dict[str, Any]:
  32. try:
  33. data = json.loads(_path(kind).read_text(encoding="utf-8-sig"))
  34. except (OSError, ValueError):
  35. return {}
  36. return data if isinstance(data, dict) and isinstance(data.get("first_task_at"), (int, float)) else {}
  37. @contextmanager
  38. def _transaction(kind: str) -> Iterator[tuple[dict[str, Any], Any]]:
  39. from hermes_cli.auth import _file_lock
  40. from utils import atomic_write_text
  41. path = _path(kind)
  42. with _file_lock(path.with_suffix(".lock"), _LOCK, 5.0, f"Timed out waiting for the sign-in offer record ({path})"):
  43. yield _read(kind), lambda data: atomic_write_text(path, json.dumps(data))
  44. def _eligible(kind: str) -> bool:
  45. """``trial``: the welcome trial carries inference. ``connector``: a guest that connected an app,
  46. guests are still allowed (``nous.guest``), and no trial makes its own offer."""
  47. from hermes_cli import anon_auth
  48. if kind == TRIAL:
  49. return anon_auth.free_inference_active()
  50. state = anon_auth.current_nous_state()
  51. return (anon_auth.is_guest_state(state) and state.get(CONNECTED_APP_FLAG) is True and anon_auth.guest_allowed()
  52. and not anon_auth.free_inference_active(state))
  53. def _due_at(state: dict[str, Any]) -> Optional[float]:
  54. if not state:
  55. return None
  56. offers = int(state.get("offers") or 0)
  57. last_task = float(state.get("last_task_at") or state["first_task_at"])
  58. if offers == 0:
  59. return float(state["first_task_at"]) + OFFER_DELAY_S
  60. last_offer = float(state.get("last_offered_at") or 0)
  61. if last_task <= last_offer:
  62. return None # nothing finished since the last offer
  63. return max(last_task + OFFER_DELAY_S, last_offer + REOFFER_AFTER_S[min(offers, len(REOFFER_AFTER_S)) - 1])
  64. def _due_in(kind: str, state: dict[str, Any]) -> Optional[int]:
  65. due_at = _due_at(state)
  66. if due_at is None or not _eligible(kind):
  67. return None
  68. return max(0, math.ceil(due_at - _clock()))
  69. def record_task_done(kind: str = TRIAL) -> None:
  70. """A task finished: the first one starts the offer clock, later ones re-arm it."""
  71. with _transaction(kind) as (state, write):
  72. now = _clock()
  73. write({**state, "first_task_at": state.get("first_task_at", now), "last_task_at": now})
  74. def note_app_connected() -> None:
  75. """An app finished connecting. On a guest identity, count a finished task for the connector offer,
  76. then flag the guest (so the flag dies with it). The flag ends list-read sightings, so it is set only
  77. once the task is recorded. Never fails the connection."""
  78. from hermes_cli import anon_auth
  79. try:
  80. if anon_auth.is_guest_state(anon_auth.current_nous_state()):
  81. record_task_done(CONNECTOR)
  82. anon_auth.set_guest_flag(CONNECTED_APP_FLAG)
  83. except Exception:
  84. logger.debug("connector sign-in offer record failed", exc_info=True)
  85. def note_connected_apps_seen(rows: list[Any]) -> None:
  86. """A connector list read (agent status, the Connectors page). The first one that shows a guest an
  87. app connected counts as the connect: a connect by link (messaging, one-shot runs) never passes the
  88. operation watcher, and an older Hermes connected apps without setting the flag."""
  89. from hermes_cli import anon_auth
  90. if not any(isinstance(row, dict) and row.get("connected") for row in rows):
  91. return
  92. state = anon_auth.current_nous_state()
  93. if anon_auth.is_guest_state(state) and not state.get(CONNECTED_APP_FLAG):
  94. note_app_connected()
  95. def offer_due_in(kind: str = TRIAL) -> Optional[int]:
  96. """Seconds until the offer is due (0 = now); None when none is pending or the user is not
  97. eligible for it. A pure read."""
  98. return _due_in(kind, _read(kind))
  99. def claim_offer(kind: str = TRIAL) -> bool:
  100. """Compare-and-set under the lock: True for exactly one caller each time an offer comes due."""
  101. with _transaction(kind) as (state, write):
  102. if _due_in(kind, state) != 0:
  103. return False
  104. write({**state, "offers": int(state.get("offers") or 0) + 1, "last_offered_at": _clock()})
  105. return True