slash_commands_login.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. """The off-turn, paired-DM-only ``/login`` command."""
  2. from __future__ import annotations
  3. import asyncio
  4. import concurrent.futures
  5. import contextlib
  6. import dataclasses
  7. import logging
  8. import threading
  9. from contextvars import copy_context
  10. from typing import Any
  11. from uuid import uuid4
  12. from agent.i18n import t
  13. from gateway.run_agent_cache import _first_agent
  14. from gateway.slash_access import policy_for_runner_source
  15. from hermes_cli import anon_auth
  16. logger = logging.getLogger("gateway.run")
  17. _LOGIN_SINGLE = "login"
  18. _LOCK_TYPE = type(threading.Lock())
  19. @dataclasses.dataclass
  20. class _SignInAttempt:
  21. attempt_id: str
  22. key: tuple
  23. source: Any
  24. cancelled: bool = False
  25. saving: bool = False # past the final cancel check: the save is committed, a replacement waits
  26. # These adapters use "dm" for a broadcast topic, a channel, or an agent peer. Sending a sign-in
  27. # link and code there would publish them rather than deliver them to one person.
  28. _LOGIN_BLOCKED_PLATFORMS = frozenset({"ntfy", "raft", "a2a"})
  29. def _publish_local_notice(runner, source, text: str) -> bool:
  30. """A LOCAL session's adapter ``send`` is a no-op (viewers read the event stream), so the
  31. sign-in link/code/result reach its viewers as a sticky ``notification.show``. False when
  32. *source* is not a live local session (the platform push applies)."""
  33. from gateway.config import Platform
  34. if getattr(source, "platform", None) != Platform.LOCAL:
  35. return False
  36. from gateway.session_authorities import active_authority
  37. authority = active_authority(runner)
  38. live = authority.sessions.get(source.chat_id) if authority is not None else None
  39. if live is None:
  40. return False
  41. live.event_stream.publish(source.chat_id, {"text": text, "level": "info", "kind": "sticky",
  42. "key": "login:" + uuid4().hex[:8]},
  43. event_type="notification.show")
  44. return True
  45. class GatewayLoginCommandsMixin:
  46. _LOGIN_SINGLE = _LOGIN_SINGLE
  47. def _login_registry(self):
  48. """Return the lazily created registry used by normal and bare test runners."""
  49. lock = getattr(self, "_login_lock", None)
  50. if not isinstance(lock, _LOCK_TYPE):
  51. lock = self._login_lock = threading.Lock()
  52. attempts = getattr(self, "_login_attempts", None)
  53. if not isinstance(attempts, dict):
  54. attempts = self._login_attempts = {}
  55. return lock, attempts
  56. def _login_executor(self):
  57. executor = getattr(self, "_login_exec", None)
  58. if executor is None or getattr(executor, "_shutdown", False):
  59. executor = self._login_exec = concurrent.futures.ThreadPoolExecutor(
  60. max_workers=1, thread_name_prefix="hermes-login")
  61. return executor
  62. async def _run_login_blocking(self, func):
  63. ctx = copy_context()
  64. loop = asyncio.get_running_loop()
  65. return await loop.run_in_executor(self._login_executor(), ctx.run, func)
  66. async def _handle_login_command(self, event) -> str:
  67. src = event.source
  68. platform = str(getattr(src.platform, "value", src.platform)).lower()
  69. paired_dm = (
  70. getattr(src, "chat_type", None) in {"dm", "private"}
  71. and bool(getattr(src, "chat_id", None))
  72. and platform not in _LOGIN_BLOCKED_PLATFORMS
  73. )
  74. if not paired_dm:
  75. return anon_auth.LOGIN_DM_ONLY
  76. policy = policy_for_runner_source(self, src)
  77. if policy.enabled and not policy.is_admin(getattr(src, "user_id", None)):
  78. return anon_auth.LOGIN_NOT_ALLOWED
  79. key = (str(getattr(src.platform, "value", src.platform)), str(src.chat_id),
  80. str(getattr(src, "user_id", "") or ""))
  81. lock, attempts = self._login_registry()
  82. # The private executor has one worker and the live attempt may be polling on it for the
  83. # code's full lifetime. Trip its hook before queueing the local state read, otherwise a
  84. # replacement command would wait behind the very attempt it needs to stop.
  85. with lock:
  86. live = attempts.get(_LOGIN_SINGLE)
  87. if live is not None and (live.key != key or live.saving):
  88. return anon_auth.LOGIN_BUSY_ELSEWHERE
  89. if live is not None:
  90. live.cancelled = True
  91. state = await self._run_login_blocking(anon_auth.current_nous_state)
  92. if state and not anon_auth.is_guest_state(state):
  93. return anon_auth.UPGRADE_ALREADY_SIGNED_IN
  94. with lock:
  95. live = attempts.get(_LOGIN_SINGLE)
  96. if live is not None and (live.key != key or live.saving):
  97. return anon_auth.LOGIN_BUSY_ELSEWHERE
  98. if live is not None:
  99. live.cancelled = True
  100. attempt = _SignInAttempt(
  101. attempt_id=uuid4().hex[:8], key=key, source=src)
  102. attempts[_LOGIN_SINGLE] = attempt
  103. self._retain_background_task(asyncio.create_task(self._run_login(attempt)))
  104. return anon_auth.UPGRADE_START
  105. async def _run_login(self, attempt: _SignInAttempt) -> None:
  106. lock, attempts = self._login_registry()
  107. def _cancelled() -> bool:
  108. with lock:
  109. return attempt.cancelled
  110. @contextlib.contextmanager
  111. def _persist_guard():
  112. # The final cancel check claims the save under the registry lock, so a replacing /login
  113. # either cancels first or is told a sign-in is finishing. The save itself runs outside
  114. # the lock: the event loop takes that lock, and a save can wait on the auth store.
  115. with lock:
  116. if not attempt.cancelled:
  117. attempt.saving = True
  118. may_persist = attempt.saving
  119. yield may_persist
  120. gen = anon_auth.run_sign_in(timeout_seconds=15.0, cancelled=_cancelled, persist_guard=_persist_guard)
  121. pushed_terminal = False
  122. try:
  123. while True:
  124. try:
  125. state = await self._run_login_blocking(lambda: next(gen, None))
  126. except RuntimeError as exc:
  127. logger.warning(
  128. "/login %s: executor unavailable, stopping: %s", attempt.attempt_id, exc)
  129. return
  130. if state is None:
  131. return
  132. await self._render_login_state(attempt, state)
  133. if state.terminal:
  134. pushed_terminal = True
  135. return
  136. except asyncio.CancelledError:
  137. with lock:
  138. attempt.cancelled = True
  139. raise
  140. except Exception:
  141. logger.warning("/login attempt %s failed", attempt.attempt_id, exc_info=True)
  142. if not pushed_terminal:
  143. with contextlib.suppress(Exception):
  144. await self._push_login(attempt, anon_auth.UPGRADE_NOT_COMPLETED)
  145. finally:
  146. with lock:
  147. if attempts.get(_LOGIN_SINGLE) is attempt:
  148. attempts.pop(_LOGIN_SINGLE, None)
  149. with contextlib.suppress(Exception):
  150. gen.close()
  151. async def _push_login(self, attempt: _SignInAttempt, text: str) -> None:
  152. """Push one notice without allowing a transport failure to abort the state drain."""
  153. try:
  154. if _publish_local_notice(self, attempt.source, text):
  155. return
  156. await self._deliver_platform_notice(attempt.source, text)
  157. except Exception:
  158. logger.warning("/login %s: push failed", attempt.attempt_id, exc_info=True)
  159. async def _render_login_state(self, attempt: _SignInAttempt, state) -> None:
  160. if isinstance(state, anon_auth.Code):
  161. await self._push_login(attempt, state.link)
  162. await self._push_login(attempt, state.code)
  163. await self._push_login(attempt, state.copy_with_wait)
  164. return
  165. if isinstance(state, anon_auth.Waiting):
  166. return
  167. if isinstance(state, anon_auth.Completed):
  168. copy = state.copy
  169. if state.model_changed and state.model:
  170. failed = await self._sweep_sessions_off_welcome()
  171. if failed:
  172. copy += t("gateway.login.free_tier_remaining")
  173. await self._push_login(attempt, copy)
  174. return
  175. await self._push_login(attempt, state.copy)
  176. async def _sweep_sessions_off_welcome(self) -> int:
  177. """Clear durable overrides before eviction; return the number of failed clears."""
  178. lock = getattr(self, "_agent_cache_lock", None)
  179. cache = getattr(self, "_agent_cache", None) or {}
  180. with (lock or contextlib.nullcontext()):
  181. entries = list(cache.items())
  182. keys = [
  183. key for key, entry in entries
  184. if (agent := _first_agent(entry)) is not None
  185. and str(getattr(agent, "provider", "")) == "nous"
  186. and str(getattr(agent, "model", "")) == anon_auth.GUEST_MODEL
  187. ]
  188. failed = 0
  189. for key in keys:
  190. overrides = self._session_model_overrides
  191. override = overrides.get(key) or {}
  192. if str(override.get("model") or "") == anon_auth.GUEST_MODEL:
  193. for attempt in range(2):
  194. try:
  195. await self.async_session_store.set_model_override(key, None)
  196. break
  197. except Exception:
  198. if attempt == 1:
  199. logger.warning(
  200. "/login: failed to clear free-tier override for %s", key, exc_info=True)
  201. else:
  202. # Retain the live route while disk still pins it, including on a rebuild.
  203. failed += 1
  204. continue
  205. overrides.pop(key, None)
  206. try:
  207. self._evict_cached_agent(key)
  208. except Exception:
  209. logger.warning("/login: failed to evict free-tier session %s", key, exc_info=True)
  210. return failed