model_picker_usage.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. """Plan-usage chrome for the model pickers (CLI radiolist and the gateway ``model.options`` inventory).
  2. On a usage-window plan every listed model is included, so the picker shows how much of each allowance
  3. is used instead of per-token prices. Each model row carries one word, ``Small`` / ``Medium`` /
  4. ``Large`` / ``Free``, that the gateway sends per caller (``usage_level`` on ``/v1/models``).
  5. Every other account (credit-grant, pay-as-you-go, free tier) gets nothing from here.
  6. """
  7. from __future__ import annotations
  8. import logging
  9. import time
  10. from dataclasses import dataclass
  11. from typing import Any, Literal, Optional
  12. BAR_WIDTH = 10
  13. BAR_FILL = "|"
  14. BAR_EMPTY = " "
  15. GaugeStyle = Literal["green", "yellow", "red"]
  16. # Remaining-fraction thresholds (allowance left). Green under half used, red at 80%+ used.
  17. _YELLOW_BELOW = 0.5
  18. _RED_BELOW = 0.2
  19. # Per-model label on a window plan, as the gateway sends it (``usage_level``). Display words only.
  20. USAGE_LEVELS = ("free", "low", "medium", "top_tier")
  21. # Words, limit lines and switch notices come from ``plan_usage.*`` in locales/ (``usage_level_label``,
  22. # ``_t``); the `hermes model` setup picker passes ``lang="en"`` (its own text is English, as on main).
  23. # One line for that picker, shown only when a Large row is listed.
  24. TOP_TIER_FOOTNOTE = "Large models also use your monthly large-model limit."
  25. # Window pickers split the list here; messaging pickers just order recommended first.
  26. SECTION_RECOMMENDED = "Recommended"
  27. SECTION_OTHER = "Other models"
  28. _BP_FULL = 10_000
  29. # The server's allowance ids Hermes has its own words for (agent/usage_gauges.py); any other id
  30. # renders with the server's label.
  31. GAUGE_TODAY = "day"
  32. GAUGE_WEEK = "week"
  33. GAUGE_MONTH = "month"
  34. GAUGE_TOP_TIER = "top_tier"
  35. @dataclass(frozen=True)
  36. class UsageGauge:
  37. """One server allowance and when it refills, in the server's order. The wire carries ``left_fraction``;
  38. every surface draws it as USED (bar fills 0 → 100, same as the portal's "N% used"). ``scope``: which
  39. models a full one stops (``all`` / ``top_tier``). ``title``: the server's display fallback."""
  40. label: str # the server's id
  41. left_fraction: float
  42. resets_at_ms: Optional[int] = None
  43. scope: str = "all"
  44. title: str = ""
  45. @property
  46. def used_fraction(self) -> float:
  47. return 1.0 - clamp_fraction(self.left_fraction)
  48. @property
  49. def style(self) -> GaugeStyle:
  50. return gauge_style(self.left_fraction)
  51. @property
  52. def bar(self) -> str:
  53. return render_bar(self.used_fraction)
  54. @property
  55. def percent_used(self) -> str:
  56. return format_percent_used(self.used_fraction)
  57. @dataclass(frozen=True)
  58. class PickerUsage:
  59. """What the pickers need to draw a usage-window plan, derived from the portal account snapshot.
  60. Window plans only: other accounts (credit-grant, pay-as-you-go, free) get no plan chrome."""
  61. plan: Optional[str]
  62. gauges: tuple[UsageGauge, ...]
  63. paused_reason: Optional[str] = None
  64. # Window only: our picks, in order; pickers list them first. Every model is usable.
  65. featured_model_ids: tuple[str, ...] = ()
  66. # Window only: model ids the gateway labels Large in this caller's ``/v1/models``. Empty until applied.
  67. top_tier_ids: frozenset[str] = frozenset()
  68. # Window only: model ids that draw on nothing (the gateway's ``free`` word or a free catalog row). A full
  69. # allowance never blocks them. Empty until applied.
  70. free_ids: frozenset[str] = frozenset()
  71. # Window only: model ids the gateway bills to a subscription the account holds (``billing_mode:
  72. # subscription``). They stay in ``free_ids`` (they draw on nothing, so nothing dims them); this set only
  73. # keeps the word "Free" off them, since that subscription pays. Empty until applied.
  74. subscription_ids: frozenset[str] = frozenset()
  75. # Window only: past a full allowance, does the turn bill top-up credits (pay as you go)? True: "Keep
  76. # going on credits" is on and there is a top-up balance. False: it stops. None: unknown (older portal).
  77. credits_pay: Optional[bool] = None
  78. def gauge(self, label: str) -> Optional[UsageGauge]:
  79. return next((g for g in self.gauges if g.label == label), None)
  80. def is_top_tier(self, model_id: str) -> bool:
  81. """The gateway's ``top_tier`` mark. Unmarked: not top tier (fail open)."""
  82. return model_id in self.top_tier_ids
  83. def with_pricing(self, pricing: Optional[dict[str, dict[str, Any]]]) -> PickerUsage:
  84. """A copy that reads the gateway's ``top_tier`` marks from *pricing* (picker pricing shape)."""
  85. if not pricing:
  86. return self
  87. levels = usage_levels(list(pricing), pricing) # same rule as the tags and agent.plan_limits.is_top_tier
  88. free = frozenset(m for m, level in levels.items() if level == "free")
  89. marked = frozenset(m for m, level in levels.items() if level == "top_tier")
  90. subscribed = frozenset(m for m in pricing if is_subscription_billed_row(pricing.get(m)))
  91. from dataclasses import replace
  92. return replace(self, top_tier_ids=marked, free_ids=free, subscription_ids=subscribed)
  93. def exhausted_gauge(self, model_id: str) -> Optional[UsageGauge]:
  94. """Window only: the spent allowance that stops this model (an all-scope one, or the top-tier one for a
  95. top-tier model; of several, the one that frees up last), or None while it still has included room. A
  96. free model is never stopped. Same rule as agent/plan_limits.py ``blocking_gauge``."""
  97. if model_id in self.free_ids or model_id.endswith(":free"):
  98. return None
  99. spent = [g for g in self.gauges_for_model(model_id) if g.left_fraction <= 0.0]
  100. return max(spent, key=lambda g: g.resets_at_ms or 0) if spent else None
  101. def blocks(self, model_id: str) -> bool:
  102. """Window only: a full allowance stops this model and top-up credits won't pay for it, so a picker
  103. dims the row (the limit line says why, once). Same rule as apps/shared ``planBlocks``."""
  104. return self.credits_pay is not True and self.exhausted_gauge(model_id) is not None
  105. def _full_all_gauge(self) -> Optional[UsageGauge]:
  106. spent = [g for g in self.gauges if g.scope == "all" and g.left_fraction <= 0.0]
  107. return max(spent, key=lambda g: g.resets_at_ms or 0) if spent else None
  108. def limit_line(self, lang: Optional[str] = None) -> Optional[str]:
  109. """One line for the top of a window-plan picker once an allowance is full, saying what happens
  110. next: ``Weekly limit reached · resets in 21h · paid models now use your credits (pay as you go)``.
  111. None while nothing is full (and while paused: the plan header already says so)."""
  112. if self.paused_reason:
  113. return None
  114. full = self._full_all_gauge()
  115. top = None if full is not None else next(
  116. (g for g in self.gauges if g.scope == GAUGE_TOP_TIER and g.left_fraction <= 0.0), None)
  117. g = full or top
  118. if g is None:
  119. return None
  120. head = _capitalize(_t("limit_reached", lang, name=_limit_name(g, lang), resets=_resets(g.resets_at_ms, lang)))
  121. large = "" if full is not None else "_large"
  122. if self.credits_pay:
  123. return f"{head} · {_t('then_credits' + large, lang)}"
  124. if self.credits_pay is False:
  125. return f"{head} · {_t('then_wait' + large, lang)}"
  126. return head
  127. def large_model_notice(self, model_id: str, *, detail: bool = True, lang: Optional[str] = None) -> str:
  128. """The warning shown when someone switches to a Large model (never a confirm). ``detail`` adds the
  129. allowance state; pass False for a stale snapshot, whose percents could mislead."""
  130. g = self.exhausted_gauge(model_id) if detail and not self.paused_reason else None
  131. if g is not None:
  132. if self.credits_pay:
  133. return _t("large_notice_credits", lang)
  134. key = "large_notice_limit_stops" if self.credits_pay is False else "large_notice_limit"
  135. return _t(key, lang, name=_limit_name(g, lang), resets=_resets(g.resets_at_ms, lang))
  136. top = next((g for g in self.gauges if g.scope == GAUGE_TOP_TIER), None) if detail else None
  137. if top is not None:
  138. return _t("large_notice_percent", lang, percent=top.percent_used)
  139. return _t("large_notice", lang)
  140. @property
  141. def included_summary(self) -> str:
  142. """Header suffix: every row is included, unless an allowance is full (then what happens next) or the
  143. plan is paused."""
  144. if self.paused_reason:
  145. return "included usage paused"
  146. # Only the `hermes model` setup picker shows this, and its own text is English.
  147. return self.limit_line(lang="en") or "every model below is included"
  148. def gauges_for_model(self, model_id: str) -> tuple[UsageGauge, ...]:
  149. """Every all-scope allowance, plus the top-tier ones when the model draws on them."""
  150. top = self.is_top_tier(model_id)
  151. return tuple(g for g in self.gauges if g.scope == "all" or (g.scope == "top_tier" and top))
  152. def to_payload(self) -> dict[str, Any]:
  153. """Wire shape for ``model.options`` (``ModelOptionProvider.plan_usage``)."""
  154. return {
  155. "kind": "usage_window",
  156. "plan": self.plan,
  157. "gauges": [
  158. {"label": g.label, "left_fraction": round(g.left_fraction, 4), "style": g.style,
  159. "resets_at_ms": g.resets_at_ms, "scope": g.scope, "title": g.title}
  160. for g in self.gauges
  161. ],
  162. # The gateway's marks (what the desktop's used-up notes read).
  163. "top_tier_model_ids": sorted(self.top_tier_ids),
  164. # Subscription-billed: still ``free`` in ``usage_levels`` (never dimmed), but
  165. # pickers show no "Free" tag on them (``plan-usage.ts`` ``usageTag``).
  166. "subscription_model_ids": sorted(self.subscription_ids),
  167. "featured_model_ids": list(self.featured_model_ids),
  168. "paused_reason": self.paused_reason,
  169. "credits_pay": self.credits_pay,
  170. }
  171. def clamp_fraction(value: float) -> float:
  172. return 0.0 if value < 0.0 else min(value, 1.0)
  173. def gauge_style(left_fraction: float) -> GaugeStyle:
  174. """Allowance color: green under half used, yellow from 50%, red once 80%+ is used."""
  175. left = clamp_fraction(left_fraction)
  176. if left < _RED_BELOW:
  177. return "red"
  178. if left < _YELLOW_BELOW:
  179. return "yellow"
  180. return "green"
  181. def _filled_cells(fraction: float, width: int) -> int:
  182. value = clamp_fraction(fraction)
  183. filled = round(value * width)
  184. if value > 0.0 and filled == 0:
  185. filled = 1
  186. if value < 1.0 and filled == width:
  187. filled = width - 1
  188. return filled
  189. def render_bar(fraction: float, width: int = BAR_WIDTH) -> str:
  190. """``[|||| ]`` — filled cells are *fraction* (usage gauges pass the USED fraction; cost bars
  191. their intensity). Any non-zero value shows at least one cell and a non-full one always leaves one
  192. empty, so "barely used" never reads as untouched and "almost out" never reads as exhausted."""
  193. filled = _filled_cells(fraction, width)
  194. return f"[{BAR_FILL * filled}{BAR_EMPTY * (width - filled)}]"
  195. def featured_first(model_ids: list[str], featured: tuple[str, ...] | list[str]) -> list[str]:
  196. """The plan's featured picks first (plan order, only those listed), then the rest unchanged."""
  197. head, rest = split_recommended(model_ids, featured)
  198. return head + rest
  199. def split_recommended(
  200. model_ids: list[str], featured: tuple[str, ...] | list[str],
  201. ) -> tuple[list[str], list[str]]:
  202. """``(recommended, other)``: the plan's featured picks that are listed (plan order), then every
  203. other listed model in its catalog order. No featured picks: ``([], model_ids)``."""
  204. listed = set(model_ids)
  205. head = [m for m in dict.fromkeys(featured or ()) if m in listed]
  206. seen = set(head)
  207. return head, [m for m in model_ids if m not in seen]
  208. def usage_levels(model_ids: list[str], pricing: Optional[dict[str, dict[str, Any]]]) -> dict[str, str]:
  209. """``{model: "free" | "low" | "medium" | "top_tier"}`` from what the gateway stamped on this
  210. caller's catalog. An older gateway sends no ``usage_level``: then only what it does send is used
  211. (its ``top_tier`` mark, and a $0/$0 row is ``free``); every other row gets no label."""
  212. from agent.plan_limits import is_free
  213. out: dict[str, str] = {}
  214. for mid in model_ids:
  215. row = (pricing or {}).get(mid) or {}
  216. level = row.get("usage_level")
  217. if is_free(mid, pricing):
  218. out[mid] = "free"
  219. elif level in USAGE_LEVELS:
  220. out[mid] = level
  221. elif row.get("top_tier") is True:
  222. out[mid] = "top_tier"
  223. return out
  224. def is_subscription_billed_row(pricing_row: Any) -> bool:
  225. """The gateway bills this catalog row to a subscription the account holds (``billing_mode: subscription``)."""
  226. from hermes_cli.models import _is_subscription_billed
  227. return _is_subscription_billed(pricing_row)
  228. def usage_tag_levels(model_ids: list[str], pricing: Optional[dict[str, dict[str, Any]]]) -> dict[str, str]:
  229. """The levels a picker row shows a tag for: :func:`usage_levels` without the subscription-billed rows.
  230. Those still draw nothing from the window (``usage_levels`` keeps them ``free``, which is what keeps a full
  231. allowance from dimming them), but "Free" would read as free of charge when that subscription pays. The
  232. gateway gives them no plan label either. Display only."""
  233. levels = usage_levels(model_ids, pricing)
  234. return {m: lv for m, lv in levels.items() if not is_subscription_billed_row((pricing or {}).get(m))}
  235. def is_free_model(pricing_row: Optional[dict[str, Any]]) -> bool:
  236. """True when the catalog lists the model at $0 in and $0 out (``:free`` / natively free). A row
  237. with no pricing is NOT free — unknown price is not a promise."""
  238. from hermes_cli.models_pricing import _price_float
  239. if not pricing_row:
  240. return False
  241. inp = _price_float(pricing_row.get("prompt"), positive=False)
  242. out = _price_float(pricing_row.get("completion"), positive=False)
  243. return inp is not None and out is not None and inp <= 0.0 and out <= 0.0
  244. def format_percent_used(used_fraction: float) -> str:
  245. """Whole-percent used, same rule as the portal (``formatUsedPercentLabel``): floor, any sliver
  246. reads ``<1%`` (never ``0%``), and ``100%`` only once the allowance is actually exhausted."""
  247. # round() first: used = 1 - left can land a hair under an exact basis point (0.00999…).
  248. bp = int(round(clamp_fraction(used_fraction) * _BP_FULL, 6))
  249. if bp <= 0:
  250. return "0%"
  251. if bp < 100:
  252. return "<1%"
  253. return f"{bp // 100}%"
  254. def compact_duration(resets_at_ms: Optional[int], now_ms: Optional[int] = None) -> str:
  255. """``"5h"`` / ``"2d 3h"`` / ``"12m"`` until *resets_at_ms*; ``""`` when past, under a minute or unknown."""
  256. if not isinstance(resets_at_ms, int):
  257. return ""
  258. now = int(time.time() * 1000) if now_ms is None else now_ms
  259. seconds = max(0, (resets_at_ms - now) // 1000)
  260. if seconds < 60:
  261. return ""
  262. days, rem = divmod(seconds, 86_400)
  263. hours, rem = divmod(rem, 3_600)
  264. minutes = rem // 60
  265. if days:
  266. return f"{days}d {hours}h" if hours else f"{days}d"
  267. return f"{hours}h" if hours else f"{minutes}m"
  268. def format_resets_in(resets_at_ms: Optional[int], now_ms: Optional[int] = None) -> str:
  269. """``"resets in 5h"`` / ``"resets in 2d 3h"`` / ``"resets soon"`` (past or unknown → soon). English:
  270. ``/usage`` (untranslated, like main's credits lines); pickers use the catalog's words."""
  271. d = compact_duration(resets_at_ms, now_ms)
  272. return f"resets in {d}" if d else "resets soon"
  273. def _t(key: str, lang: Optional[str] = None, **kwargs: Any) -> str:
  274. from agent.i18n import t
  275. return t(f"plan_usage.{key}", lang, **kwargs)
  276. def _resets(resets_at_ms: Optional[int], lang: Optional[str] = None) -> str:
  277. d = compact_duration(resets_at_ms)
  278. return _t("resets_in", lang, duration=d) if d else _t("resets_soon", lang)
  279. def _capitalize(text: str) -> str:
  280. return text[:1].upper() + text[1:]
  281. def _limit_name(g: UsageGauge, lang: Optional[str] = None) -> str:
  282. """``weekly`` for ``Weekly limit reached`` / ``your weekly limit``; an unknown id shows the server's title."""
  283. if g.label in (GAUGE_TODAY, GAUGE_WEEK, GAUGE_MONTH, GAUGE_TOP_TIER):
  284. return _t(f"limit_{g.label}", lang)
  285. return g.title or g.label
  286. # The levels a picker row names: Large (its own monthly limit) and Free (never runs out). Small / Medium
  287. # only change how fast usage drains, so they carry no tag.
  288. SHOWN_USAGE_LEVELS = ("free", "top_tier")
  289. def usage_level_label(level: Optional[str], lang: Optional[str] = None) -> str:
  290. """The row tag in the catalog language (``Large`` / ``Free``); "" for every other level."""
  291. return _t(f"level_{level}", lang) if level in SHOWN_USAGE_LEVELS else ""
  292. def _get(obj: Any, name: str, default: Any = None) -> Any:
  293. if obj is None:
  294. return default
  295. if isinstance(obj, dict):
  296. return obj.get(name, default)
  297. return getattr(obj, name, default)
  298. def picker_usage_from_account(info: Any) -> Optional[PickerUsage]:
  299. """``NousPortalAccountInfo`` (or a dict shaped like one) → PickerUsage, or None when there is nothing to
  300. gauge: only a usage-window plan has plan chrome (credit-grant, pay-as-you-go and free tier get
  301. None, as does an unreadable snapshot). Never raises."""
  302. try:
  303. if info is None or not _get(info, "logged_in", True):
  304. return None
  305. sub = _get(info, "subscription")
  306. plan = _get(sub, "plan")
  307. plan = plan if isinstance(plan, str) and plan else None
  308. window = _get(info, "usage_window")
  309. if window is None:
  310. return None
  311. from agent.usage_gauges import all_scope, parse_gauges
  312. parsed = parse_gauges(_get(window, "gauges"))
  313. if not parsed or not all_scope(parsed):
  314. return None # same requirement as the tracker seed: an allowance that stops every model
  315. gauges = [UsageGauge(g.id, 1.0 - g.used_fraction, g.resets_at_ms, g.scope, g.label) for g in parsed]
  316. featured = tuple(m for m in (_get(window, "featured_model_ids") or ()) if isinstance(m, str) and m)
  317. paused = _get(window, "paused_reason")
  318. return PickerUsage(
  319. plan=plan, gauges=tuple(gauges),
  320. paused_reason=paused if isinstance(paused, str) and paused else None,
  321. featured_model_ids=featured,
  322. credits_pay=_credits_pay(info, window),
  323. )
  324. except Exception:
  325. logging.getLogger(__name__).debug("Plan usage parse failed", exc_info=True)
  326. return None
  327. def _credits_pay(info: Any, window: Any) -> Optional[bool]:
  328. """Past a full allowance, top-up credits pay (pay as you go): "Keep going on credits" is not off AND a
  329. top-up balance is left. Same rule as ``CreditsState.credits_pay``. None when the balance is unknown."""
  330. if _get(window, "keep_going_on_credits") is False:
  331. return False
  332. purchased = _get(_get(info, "paid_service_access_info"), "purchased_credits_remaining")
  333. if not isinstance(purchased, (int, float)) or isinstance(purchased, bool):
  334. return None
  335. return purchased > 0
  336. def nous_picker_usage(*, warm: bool = False, any_age: bool = False) -> Optional[PickerUsage]:
  337. """PickerUsage from the portal account snapshot. Cache-only by default so a picker never adds a
  338. round trip; ``warm=True`` fetches once (fills the 60s cache) so a window plan is known
  339. on a cold start. ``any_age`` reads the last snapshot past the 60s TTL (plan-shape callers only:
  340. its percents may be stale). Never raises."""
  341. try:
  342. from hermes_cli.nous_account import cached_nous_portal_account_info, get_nous_portal_account_info
  343. if warm and cached_nous_portal_account_info() is None:
  344. # A known window plan needs a real fetch: the JWT snapshot carries no gauges and never fills the cache.
  345. from agent.credits_tracker import _window_seed_fields
  346. on_window = _window_seed_fields(_get(cached_nous_portal_account_info(any_age=True), "usage_window")) is not None
  347. get_nous_portal_account_info(force_fresh=on_window)
  348. return picker_usage_from_account(cached_nous_portal_account_info(any_age=any_age))
  349. except Exception:
  350. logging.getLogger(__name__).debug("Nous plan usage unavailable", exc_info=True)
  351. return None
  352. def _nous_catalog(*, fetch: bool = False) -> dict[str, dict[str, Any]]:
  353. """This profile's Nous ``/v1/models`` rows: its resident cache, one fetch only when ``fetch``. Never a
  354. catalog cached for another credential (another profile's plan marks different models Large)."""
  355. from hermes_cli.models_pricing import get_pricing_for_provider
  356. rows = get_pricing_for_provider("nous", cached_only=True) or {}
  357. if not rows and fetch:
  358. rows = get_pricing_for_provider("nous") or {}
  359. return rows
  360. def large_model_notice(
  361. model_id: str, provider: str, *, fetch: bool = False, lang: Optional[str] = None,
  362. ) -> Optional[str]:
  363. """Warning line for a switch to a Large model, or None. Window plans only. The gateway decides "Large"
  364. (``usage_level: top_tier``; older gateways ``top_tier: true``) and stamps it ONLY on a usage-window
  365. caller's catalog, so a marked row is itself proof of a window plan. With a plan snapshot the catalog may
  366. be fetched once (``fetch``); without one only the resident cache is read, so any other account adds no
  367. network call. Never raises."""
  368. try:
  369. if str(provider or "").strip().lower() != "nous" or not model_id:
  370. return None
  371. fresh = nous_picker_usage()
  372. usage = fresh or nous_picker_usage(any_age=True)
  373. rows = _nous_catalog(fetch=fetch and usage is not None)
  374. row = rows.get(model_id)
  375. if not row:
  376. return None
  377. if usage_levels([model_id], {model_id: row}).get(model_id) != "top_tier":
  378. return None
  379. if usage is None:
  380. return _t("large_notice", lang)
  381. return usage.with_pricing({model_id: row}).large_model_notice(model_id, detail=fresh is not None, lang=lang)
  382. except Exception:
  383. logging.getLogger(__name__).debug("Large-model notice unavailable", exc_info=True)
  384. return None
  385. def window_row_labels(provider_row: Any, model_ids: list) -> list[str]:
  386. """CLI picker rows: ``model-b Large`` from the payload's ``usage_levels``, which only a window plan's
  387. row carries (the TUI's rule: Large / Free only). Any other row, or anything unexpected: the bare ids."""
  388. ids = [str(m) for m in model_ids]
  389. plan = provider_row.get("plan_usage") if isinstance(provider_row, dict) else None
  390. levels = provider_row.get("usage_levels") if isinstance(plan, dict) and plan.get("kind") == "usage_window" else None
  391. # Subscription-billed rows keep their ``free`` level but carry no tag.
  392. subscribed = (set(plan.get("subscription_model_ids") or ())
  393. if isinstance(plan, dict) and isinstance(levels, dict) else set())
  394. tags = ([usage_level_label(None if m in subscribed else levels.get(m)) for m in ids]
  395. if isinstance(levels, dict) else [])
  396. if not any(tags):
  397. return ids
  398. width = min(max(len(m) for m in ids), 48)
  399. return [f"{m.ljust(width)} {tag}".rstrip() for m, tag in zip(ids, tags)]
  400. def picker_row_suffix(provider_row: Any, model_id: str) -> str:
  401. """Messaging pickers: ``Large`` / ``Free`` for one row, from the labels
  402. ``model_switch_providers._attach_window_model_notes`` stamps (window plans only); "" otherwise."""
  403. if not isinstance(provider_row, dict):
  404. return ""
  405. return str((provider_row.get("model_labels") or {}).get(model_id) or "")
  406. def _gauge_name(g: UsageGauge) -> str:
  407. from agent.usage_gauges import WindowGauge, gauge_short
  408. return gauge_short(WindowGauge(g.label, g.scope, g.title or g.label, 0))
  409. def plan_gauge_lines(usage: PickerUsage) -> list[str]:
  410. """Stacked plan summary: one line per server allowance, in the server's order, so the picker header
  411. stays readable at a normal terminal width."""
  412. from agent.usage_gauges import paused_for_payment
  413. paused = (" (paused: renewal unpaid)" if paused_for_payment(usage.paused_reason) else " (paused)") if usage.paused_reason else ""
  414. head = (usage.plan or "Hermes plan") + paused
  415. label_w = max((len(_gauge_name(g)) for g in usage.gauges), default=4)
  416. return [head, *(
  417. f"{_gauge_name(g):<{label_w}} {g.bar} {g.percent_used + ' used':<9} {format_resets_in(g.resets_at_ms)}"
  418. for g in usage.gauges
  419. )]
  420. def window_plan_default(model_ids: list[str], pricing: Optional[dict] = None) -> str:
  421. """A usage-window plan's first featured pick that is listed (the picker's top Recommended row), or
  422. "" for every other account. Cache-only: the caller's fresh tier read just filled the snapshot. Never raises."""
  423. try:
  424. usage = nous_picker_usage(any_age=True)
  425. if usage is None:
  426. return ""
  427. recommended, _other = split_recommended(model_ids, usage.featured_model_ids)
  428. rows = pricing or {}
  429. # A default must not spend the Large allowance: skip Large picks (a user can still choose one).
  430. usable = [mid for mid in recommended if not (rows.get(mid) or {}).get("top_tier")
  431. and (rows.get(mid) or {}).get("usage_level") != "top_tier"]
  432. return usable[0] if usable else ""
  433. except Exception:
  434. logging.getLogger(__name__).debug("Window plan default unavailable", exc_info=True)
  435. return ""
  436. def annotate_window_plan_rows(provider_data: dict, model_ids: list) -> tuple[list, Optional[str]]:
  437. """``(labels, limit_line)`` for the /model picker's model stage. On a Nous usage-window plan rows carry
  438. the TUI's ``Large`` / ``Free`` tags, and with a full allowance ``limit_line`` (above the hint) says it
  439. once, with what happens next. Every other account: the bare ids and None. Display only."""
  440. if str((provider_data or {}).get("slug") or "").lower() != "nous":
  441. return list(model_ids), None
  442. try:
  443. usage = nous_picker_usage() # fresh snapshot only: a stale percent would mislabel the line
  444. return window_row_labels(provider_data, model_ids), (usage.limit_line() if usage is not None else None)
  445. except Exception:
  446. logging.getLogger(__name__).debug("Window plan row labels unavailable", exc_info=True)
  447. return list(model_ids), None