usage_gauges.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. """Usage-window allowances as the server sends them: one list, in display order.
  2. The Portal account (``usage_window.gauges``) and the API (``x-nous-credits-window-gauges``, also on the 402)
  3. send the same shape, so Hermes draws whatever arrives and a new allowance needs no Hermes release.
  4. ``scope`` says which models a full gauge stops: ``all`` = every paid model, ``top_tier`` = the models the
  5. gateway marks top tier. Free models draw on nothing.
  6. Hermes keeps only its own words for the ids it knows (they are translated and fitted to each surface);
  7. any other id shows the server's ``label``.
  8. """
  9. from __future__ import annotations
  10. import json
  11. import time
  12. from dataclasses import dataclass
  13. from typing import Any, Iterable, Optional
  14. BP_FULL = 10_000
  15. SCOPE_ALL = "all"
  16. SCOPE_TOP_TIER = "top_tier"
  17. _SCOPES = frozenset({SCOPE_ALL, SCOPE_TOP_TIER})
  18. # The pause reasons that mean the subscription payment failed. Any other reason (including "unknown",
  19. # sent for a malformed one) is still a pause, with copy that does not claim a payment failed.
  20. PAYMENT_PAUSE_REASONS = frozenset({"payment_past_due"})
  21. def paused_for_payment(reason: Any) -> bool:
  22. return reason in PAYMENT_PAUSE_REASONS
  23. @dataclass(frozen=True)
  24. class WindowGauge:
  25. id: str
  26. scope: str # SCOPE_ALL | SCOPE_TOP_TIER
  27. label: str # the server's display fallback
  28. used_bp: int # 0..10000
  29. resets_at_ms: Optional[int] = None
  30. @property
  31. def full(self) -> bool:
  32. return self.used_bp >= BP_FULL
  33. @property
  34. def used_fraction(self) -> float:
  35. return min(1.0, max(0.0, self.used_bp / BP_FULL))
  36. def parse_gauges(value: Any) -> Optional[tuple[WindowGauge, ...]]:
  37. """The wire list (a JSON array, or its string form from a header) → gauges in order. None when absent,
  38. unreadable or empty. An entry with an unknown scope, a repeated id or a bad percent is dropped: an
  39. older Hermes must never misread a kind of limit it does not know."""
  40. if isinstance(value, tuple) and all(isinstance(g, WindowGauge) for g in value):
  41. return value or None
  42. if isinstance(value, str):
  43. try:
  44. value = json.loads(value)
  45. except ValueError:
  46. return None
  47. if not isinstance(value, list):
  48. return None
  49. out: list[WindowGauge] = []
  50. seen: set[str] = set()
  51. for item in value:
  52. if not isinstance(item, dict):
  53. continue
  54. gid, scope, bp = item.get("id"), item.get("scope"), item.get("used_bp")
  55. if not isinstance(gid, str) or not gid or gid in seen or scope not in _SCOPES:
  56. continue
  57. if isinstance(bp, bool) or not isinstance(bp, int) or not 0 <= bp <= BP_FULL:
  58. continue
  59. reset = _plausible_reset_ms(item.get("resets_at_ms"))
  60. label = item.get("label")
  61. seen.add(gid)
  62. out.append(WindowGauge(gid, scope, label.strip() if isinstance(label, str) and label.strip() else gid,
  63. bp, reset))
  64. return tuple(out) or None
  65. # A reset more than a year ahead is a bad stamp (the longest allowance is a month): shown as unknown, never
  66. # as a date or a duration decades away. A past stamp needs no bound: it already reads "shortly".
  67. _RESET_MAX_AHEAD_MS = 366 * 86_400_000
  68. def _plausible_reset_ms(value: Any) -> Optional[int]:
  69. if not isinstance(value, int) or isinstance(value, bool):
  70. return None
  71. return value if 0 < value <= time.time() * 1000 + _RESET_MAX_AHEAD_MS else None
  72. def all_scope(gauges: Iterable[WindowGauge]) -> tuple[WindowGauge, ...]:
  73. return tuple(g for g in gauges if g.scope == SCOPE_ALL)
  74. def top_tier_gauge(gauges: Iterable[WindowGauge]) -> Optional[WindowGauge]:
  75. return next((g for g in gauges if g.scope == SCOPE_TOP_TIER), None)
  76. def binding_gauge(gauges: Iterable[WindowGauge]) -> Optional[WindowGauge]:
  77. """The all-scope gauge that binds: of the full ones, the one that frees up LAST (with the day and the
  78. week both full, the day's reset alone lets nothing through); else the fullest (ties → first listed)."""
  79. alls = all_scope(gauges)
  80. if not alls:
  81. return None
  82. full = [g for g in alls if g.full]
  83. if full:
  84. return max(full, key=lambda g: g.resets_at_ms or 0)
  85. return max(alls, key=lambda g: g.used_bp)
  86. # Hermes's words for the ids it knows: (row title, "for <phrase>", "your <name> limit", picker short name).
  87. _WORDS: dict[str, tuple[str, str, str, str]] = {
  88. "day": ("Today", "today", "daily", "today"),
  89. "week": ("This week", "this week", "weekly", "week"),
  90. "month": ("This month", "this month", "monthly", "month"),
  91. "top_tier": ("Large models (monthly)", "your monthly large-model usage", "monthly large-model", "large models (monthly)"),
  92. }
  93. def _words(g: WindowGauge) -> Optional[tuple[str, str, str, str]]:
  94. return _WORDS.get(g.id)
  95. def gauge_title(g: WindowGauge) -> str:
  96. """Row title in ``/usage``: ``Today``; an unknown id shows the server's label."""
  97. return w[0] if (w := _words(g)) else g.label
  98. def gauge_limit_name(g: WindowGauge) -> str:
  99. """``You've hit your <name> limit``: ``daily``; an unknown id shows the server's label."""
  100. return w[2] if (w := _words(g)) else g.label
  101. def gauge_short(g: WindowGauge) -> str:
  102. """Picker summary row name: ``today``; an unknown id shows the server's label."""
  103. return w[3] if (w := _words(g)) else g.label