shared_metrics_consent.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  1. """The one shared-metrics consent answer, and the terminal's first-run offer.
  2. Every surface reads and writes the same two keys in the profile's config.yaml:
  3. ``telemetry.shared_metrics.enabled`` (collect) and ``.send`` (upload daily). The offer has two
  4. answers, and each sets both keys: "Share with Nous" turns both on, "No thanks" turns both off. The
  5. question counts as answered once either key is written explicitly; the shipped defaults are not an
  6. answer. Every answer also writes ``offer_version``. A "No thanks" without it predates the type-ahead
  7. fix (an Enter pressed during startup could save it unseen), so that profile is asked once more, with
  8. the reason, and any response (Esc or dismiss included) settles it for good. A collect-only answer
  9. from before the offer dropped that choice stays decided: nothing is sent, and it is not asked again.
  10. Desktop paints the offer as a composer strip (``consent-strip.tsx`` over the ``shared_metrics.*``
  11. RPCs). The terminal asks at the end of every ``hermes setup`` flow and, for a profile that never
  12. answered, once before an interactive ``hermes`` / ``hermes --tui`` chat (which also covers the
  13. dashboard's Chat tab, a PTY-hosted TUI). The messaging gateway never asks: a chat participant is
  14. not the install owner.
  15. """
  16. from __future__ import annotations
  17. import logging
  18. import os
  19. import sys
  20. from typing import Any
  21. logger = logging.getLogger(__name__)
  22. # (label, enabled, send): the offer's two answers, in the order every surface shows them.
  23. OFFER_CHOICES = (
  24. ("Share with Nous", True, True),
  25. ("No thanks", False, False),
  26. )
  27. _NO_THANKS = len(OFFER_CHOICES) - 1
  28. DOCS_URL = "https://hermes-agent.nousresearch.com/docs/developer-guide/relay-shared-metrics"
  29. _OFFER_DESCRIPTION = "\n".join((
  30. "Shared metrics are bounded counters: activity, outcomes, error classes (with a",
  31. "fixed-list reason when a memory write, compression, update or install fails),",
  32. "model routes, token totals, feature use and coarse machine facts. Never prompts,",
  33. "files, paths, setting values or error text. Sharing sends them to Nous once a",
  34. "day. Apart from a one-time install note, data from before you opt in is never",
  35. "sent.",
  36. f"Details: {DOCS_URL}",
  37. "Change it any time: hermes setup telemetry",
  38. ))
  39. _REASK_NOTE = "Asking once more: an earlier version could save \"No thanks\" before you saw this question."
  40. def _section(cfg: Any) -> dict:
  41. telemetry = cfg.get("telemetry") if isinstance(cfg, dict) else None
  42. section = telemetry.get("shared_metrics") if isinstance(telemetry, dict) else None
  43. return section if isinstance(section, dict) else {}
  44. # Bumped only when every earlier answer must be asked again; 2 = after the type-ahead fix.
  45. OFFER_VERSION = 2
  46. def consent_state(raw_cfg: Any) -> dict:
  47. """``{enabled, send, decided, reask}`` from a RAW config mapping (no defaults merged). ``reask``:
  48. an "off" answer from before ``OFFER_VERSION`` that may never have been seen; it reads undecided
  49. so every surface offers it once more. An opt-in was always a deliberate pick and stays, including
  50. a collect-only answer from before the offer dropped that choice."""
  51. section = _section(raw_cfg)
  52. enabled = section.get("enabled") is True
  53. answered = "enabled" in section or "send" in section
  54. reask = answered and not enabled and section.get("offer_version") != OFFER_VERSION
  55. return {
  56. "enabled": enabled,
  57. "send": enabled and section.get("send") is True,
  58. "decided": answered and not reask,
  59. "reask": reask,
  60. }
  61. def _current_state() -> dict:
  62. from hermes_cli.config import read_raw_config
  63. return consent_state(read_raw_config())
  64. def set_answer(target: dict, enabled: bool, send: bool) -> None:
  65. """Write one answer into a config mapping: both opt-ins plus the offer version that settles it."""
  66. telemetry = target.get("telemetry")
  67. if not isinstance(telemetry, dict):
  68. telemetry = target["telemetry"] = {}
  69. section = telemetry.get("shared_metrics")
  70. if not isinstance(section, dict):
  71. section = telemetry["shared_metrics"] = {}
  72. section["enabled"], section["send"] = enabled, enabled and send
  73. section["offer_version"] = OFFER_VERSION
  74. def save_consent(enabled: bool, send: bool, config: dict | None = None) -> None:
  75. """Write both keys into the user's raw config.yaml now. ``save_config`` strips values equal
  76. to the shipped defaults, so a "No thanks" (both false) saved through it vanished and the
  77. profile was asked again on every surface. ``config`` (a caller's in-memory copy, e.g. the
  78. wizard's) gets the same answer so its later save agrees. Sending cannot outlive collection."""
  79. from hermes_cli.config import (
  80. _write_user_config, get_config_path, is_managed, managed_error, require_readable_config_before_write,
  81. )
  82. from hermes_cli.setup import _record_send_consent_change
  83. if is_managed():
  84. managed_error("save configuration")
  85. return
  86. send = enabled and send
  87. config_path = get_config_path()
  88. user_config = require_readable_config_before_write(config_path)
  89. set_answer(user_config, enabled, send)
  90. _write_user_config(config_path, user_config)
  91. if config is not None:
  92. set_answer(config, enabled, send)
  93. # Unconditional: a send key already false may still have an open consent window.
  94. _record_send_consent_change(enabled=send)
  95. if not enabled:
  96. from hermes_constants import get_hermes_home
  97. from .shared_metrics_process import purge_pending_receipts
  98. purge_pending_receipts(get_hermes_home())
  99. def offer_consent(config: dict | None = None, *, reask: bool = False) -> bool:
  100. """Ask once, with the offer's two answers; "No thanks" is the default so Enter never
  101. opts anyone in. Esc leaves a first question open (asked again next time); on a re-ask it keeps
  102. the recorded "No thanks", so nobody is asked a third time. True when answered."""
  103. from hermes_cli.cli_output import print_info, print_success
  104. from hermes_cli.curses_ui import curses_radiolist, flush_stdin
  105. # The offer appears seconds into startup; an Enter typed while Hermes booted would otherwise
  106. # answer it ("No thanks") before it was ever on screen, so the user was never really asked.
  107. flush_stdin()
  108. idx = curses_radiolist(
  109. "Help improve Hermes?", [label for label, _, _ in OFFER_CHOICES], selected=_NO_THANKS, cancel_returns=-1,
  110. description=f"{_REASK_NOTE}\n{_OFFER_DESCRIPTION}" if reask else _OFFER_DESCRIPTION,
  111. )
  112. if idx < 0 and reask:
  113. save_consent(False, False, config)
  114. print_info("Kept \"No thanks\". Change it any time with `hermes setup telemetry`.")
  115. return True
  116. if idx < 0:
  117. print_info("Not answered; Hermes will ask again. Decide any time with `hermes setup telemetry`.")
  118. return False
  119. _, enabled, send = OFFER_CHOICES[idx]
  120. save_consent(enabled, send, config)
  121. outcome = "sent to Nous once a day" if send else "off"
  122. print_success(f"Shared metrics {outcome}. Change it any time with `hermes setup telemetry`.")
  123. return True
  124. def offer_consent_if_undecided(config: dict | None = None) -> None:
  125. """The end-of-setup offer: every ``hermes setup`` flow funnels through the setup-completed
  126. record, so this one call covers Quick, Full, Blank Slate, Portal and ``--quick``."""
  127. from hermes_cli.config import is_managed
  128. from hermes_cli.setup import is_noninteractive
  129. if is_managed() or is_noninteractive() or not sys.stdin.isatty():
  130. return
  131. state = _current_state()
  132. if state["decided"]:
  133. return
  134. try:
  135. offer_consent(config, reask=state["reask"])
  136. except (KeyboardInterrupt, EOFError):
  137. print()
  138. def offer_consent_before_chat(args: Any) -> None:
  139. """One-time offer before an interactive chat on a profile that never answered. Skipped for
  140. anything without a person at a terminal (``-q``, piped or JSON output, spawned actions) and for
  141. a Desktop-spawned pane (the app shows its own strip)."""
  142. from hermes_cli.config import is_managed
  143. from hermes_cli.setup import is_noninteractive
  144. if any(getattr(args, name, None) for name in ("query", "query_file", "oneshot", "oneshot_exit")):
  145. return
  146. if getattr(args, "safe_mode", False) or getattr(args, "ignore_user_config", False):
  147. return
  148. if os.environ.get("HERMES_DESKTOP") or is_noninteractive():
  149. return
  150. if not (sys.stdin.isatty() and sys.stdout.isatty()) or is_managed():
  151. return
  152. try:
  153. state = _current_state()
  154. if state["decided"]:
  155. return
  156. offer_consent(reask=state["reask"])
  157. except (KeyboardInterrupt, EOFError):
  158. print()
  159. except Exception:
  160. logger.debug("shared-metrics offer skipped", exc_info=True)