nous_subscription.py 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. """Helpers for Nous subscription managed-tool capabilities."""
  2. from __future__ import annotations
  3. from dataclasses import dataclass
  4. from typing import Dict, Iterable, Optional, Set
  5. from hermes_cli.config import get_env_value, load_config
  6. from hermes_cli.nous_account import (
  7. NousPortalAccountInfo, format_nous_portal_entitlement_message, get_nous_portal_account_info,
  8. )
  9. from tools.managed_tool_gateway import is_managed_tool_gateway_ready
  10. from utils import is_truthy_value
  11. from tools.tool_backend_helpers import (
  12. fal_key_is_configured, has_direct_modal_credentials, normalize_browser_cloud_provider, normalize_modal_mode,
  13. resolve_modal_backend_state, resolve_openai_audio_api_key
  14. )
  15. _DEFAULT_PLATFORM_TOOLSETS = {"cli": "hermes-cli"}
  16. @dataclass(frozen=True)
  17. class _FeatureSpec:
  18. """Per-feature parameters shared by the status, defaults and Tool Gateway offer surfaces."""
  19. label: str
  20. included_by_default: bool
  21. # Tool-pool coverage category (nous_account.TOOL_COVERAGE_CATEGORIES) gating per backend:
  22. # the free pool funds image but NOT video; STT shares TTS's "openai-audio" category.
  23. coverage: str
  24. gateway: str # managed gateway probed for readiness (video rides image's fal-queue)
  25. # Config (section, selection field) written by apply_gateway_defaults; None = not offered (modal).
  26. section_field: Optional[tuple[str, str]] = None
  27. offer_label: str = ""
  28. direct_label: str = ""
  29. # Direct-credential env vars that stop apply_nous_managed_defaults switching the category to
  30. # managed (tts/stt also honour resolve_openai_audio_api_key()).
  31. default_direct_env: tuple[str, ...] = ()
  32. _FEATURES: dict[str, _FeatureSpec] = {
  33. "web": _FeatureSpec(
  34. "Web tools", True, "firecrawl", "firecrawl", ("web", "backend"),
  35. "Web search & extract", "Firecrawl/Exa/Parallel/Tavily/Perplexity/Keenable key or SearXNG",
  36. ("PARALLEL_API_KEY", "TAVILY_API_KEY", "PERPLEXITY_API_KEY", "FIRECRAWL_API_KEY", "FIRECRAWL_API_URL"),
  37. ),
  38. "image_gen": _FeatureSpec(
  39. "Image generation", True, "fal", "fal-queue", ("image_gen", "provider"), "Image generation", "FAL key",
  40. ),
  41. "video_gen": _FeatureSpec(
  42. "Video generation", False, "fal-video", "fal-queue", ("video_gen", "provider"), "Video generation (FAL)", "FAL key",
  43. ),
  44. "tts": _FeatureSpec(
  45. "OpenAI TTS", True, "openai-audio", "openai-audio", ("tts", "provider"),
  46. "Text-to-speech (OpenAI TTS)", "OpenAI/ElevenLabs key", ("ELEVENLABS_API_KEY",),
  47. ),
  48. "stt": _FeatureSpec(
  49. "Speech-to-text", True, "openai-audio", "openai-audio", ("stt", "provider"),
  50. "Speech-to-text (OpenAI Whisper)", "OpenAI/Groq/Mistral key", ("GROQ_API_KEY", "MISTRAL_API_KEY"),
  51. ),
  52. "browser": _FeatureSpec(
  53. "Browser automation", True, "browser-use", "browser-use", ("browser", "cloud_provider"),
  54. "Browser automation (Browser Use)", "Browser Use/Browserbase key",
  55. ("BROWSER_USE_API_KEY", "BROWSERBASE_API_KEY"),
  56. ),
  57. "modal": _FeatureSpec("Modal execution", False, "modal", "modal"),
  58. }
  59. _FEATURE_ORDER = tuple(_FEATURES)
  60. # Public / test-referenced views over the table.
  61. MANAGED_FEATURE_COVERAGE_CATEGORY: dict[str, str] = {k: s.coverage for k, s in _FEATURES.items()}
  62. _GATEWAY_SECTION_FIELDS = {k: s.section_field for k, s in _FEATURES.items() if s.section_field}
  63. _ALL_GATEWAY_KEYS = tuple(_GATEWAY_SECTION_FIELDS)
  64. _GATEWAY_TOOL_LABELS = {k: _FEATURES[k].offer_label for k in _ALL_GATEWAY_KEYS}
  65. # Sections apply_*_defaults always materialise before writing selections.
  66. _DEFAULT_SECTIONS = ("web", "tts", "stt", "browser")
  67. MANAGED_IMAGE_DEFAULT_KREA_MODEL = "krea-3"
  68. def _uses_gateway(section: object) -> bool:
  69. """True when a config section explicitly opts into the gateway (legacy ``use_gateway: true``)."""
  70. return isinstance(section, dict) and is_truthy_value(section.get("use_gateway"), default=False)
  71. def _selected_provider(section: object, name_key: str = "provider") -> Optional[str]:
  72. """Stored provider for a section (``read_selection`` semantics): ``"nous"`` for the managed
  73. selection (stored ``nous`` or legacy ``use_gateway: true``), a vendor name for BYOK, else None."""
  74. if not isinstance(section, dict):
  75. return None
  76. if _uses_gateway(section):
  77. return "nous"
  78. value = section.get(name_key)
  79. return None if value is None else (str(value).strip().lower() or None)
  80. @dataclass(frozen=True)
  81. class NousFeatureState:
  82. key: str
  83. label: str
  84. included_by_default: bool
  85. available: bool
  86. active: bool
  87. managed_by_nous: bool
  88. direct_override: bool
  89. toolset_enabled: bool
  90. current_provider: str = ""
  91. explicit_configured: bool = False
  92. @dataclass(frozen=True)
  93. class NousSubscriptionFeatures:
  94. subscribed: bool
  95. nous_auth_present: bool
  96. provider_is_nous: bool
  97. features: dict[str, NousFeatureState]
  98. account_info: Optional[NousPortalAccountInfo] = None
  99. def __getattr__(self, name: str) -> NousFeatureState: # ``features.web`` -> per-key state
  100. if name in _FEATURE_ORDER:
  101. return self.features[name]
  102. raise AttributeError(name)
  103. def items(self) -> Iterable[NousFeatureState]:
  104. return (self.features[key] for key in _FEATURE_ORDER)
  105. def _section(config: dict[str, object], key: str) -> dict[str, object]:
  106. """``config[key]`` when it is a dict, else ``{}`` (read-only view)."""
  107. value = config.get(key)
  108. return value if isinstance(value, dict) else {}
  109. def _ensure_section(config: dict[str, object], key: str) -> dict[str, object]:
  110. """Return ``config[key]`` as a dict, creating/replacing it in ``config`` when missing."""
  111. value = config.get(key)
  112. if not isinstance(value, dict):
  113. value = config[key] = {}
  114. return value
  115. def _select_nous(config: dict[str, object], key: str, model: Optional[str] = None) -> None:
  116. """Store the managed ``nous`` selection in the ``key`` section (field per _GATEWAY_SECTION_FIELDS)."""
  117. section_key, field = _GATEWAY_SECTION_FIELDS[key]
  118. section = _ensure_section(config, section_key)
  119. section[field] = "nous"
  120. section.pop("use_gateway", None)
  121. if model:
  122. section["model"] = model
  123. def _norm(value: object, default: str = "") -> str:
  124. return str(value or default).strip().lower()
  125. def _provider_is_nous(config: dict[str, object]) -> bool:
  126. return _norm(_section(config, "model").get("provider")) == "nous"
  127. def _toolset_enabled(config: dict[str, object], toolset_key: str) -> bool:
  128. """True when some platform's configured toolsets cover every tool of ``toolset_key``."""
  129. from toolsets import resolve_toolset
  130. platform_toolsets = config.get("platform_toolsets")
  131. if not isinstance(platform_toolsets, dict) or not platform_toolsets:
  132. platform_toolsets = {"cli": [_DEFAULT_PLATFORM_TOOLSETS["cli"]]}
  133. target_tools = set(resolve_toolset(toolset_key))
  134. if not target_tools:
  135. return False
  136. from hermes_cli.toolset_validation import parse_platform_toolsets_value
  137. for platform, raw_toolsets in platform_toolsets.items():
  138. toolset_names = list(parse_platform_toolsets_value(raw_toolsets) or [])
  139. if not toolset_names:
  140. toolset_names = [t for t in (_DEFAULT_PLATFORM_TOOLSETS.get(platform),) if t]
  141. available_tools: set[str] = set()
  142. for toolset_name in toolset_names:
  143. if isinstance(toolset_name, str) and toolset_name:
  144. try:
  145. available_tools.update(resolve_toolset(toolset_name))
  146. except Exception:
  147. continue
  148. if target_tools.issubset(available_tools):
  149. return True
  150. return False
  151. def _has_browser_harness() -> bool:
  152. """browser_exec's engine (browser-harness, a core venv dependency) is importable: the only local
  153. requirement for a cloud browser provider, which hosts its own Chromium."""
  154. from tools.browser_use_cli import _find_cli
  155. return _find_cli() is not None
  156. def _local_browser_runnable(browser_cfg: dict[str, object]) -> bool:
  157. """True when the *local* browser would actually start: browser-harness plus the engine it attaches
  158. to — ``lightpanda serve`` when ``browser.engine`` selects it, else a Chromium the launcher can run."""
  159. if not _has_browser_harness():
  160. return False
  161. if str(browser_cfg.get("engine") or "auto").strip().lower() == "lightpanda":
  162. return True
  163. from hermes_cli.browser_runtime import chromium_executable
  164. return chromium_executable() is not None
  165. # kind -> (default provider, provider -> display label)
  166. _PROVIDER_LABELS = {
  167. "browser": ("local", {
  168. "browserbase": "Browserbase", "browser-use": "Browser Use", "firecrawl": "Firecrawl",
  169. "local": "Local browser",
  170. }),
  171. "tts": ("edge", {
  172. "openai": "OpenAI TTS", "elevenlabs": "ElevenLabs", "edge": "Edge TTS", "xai": "xAI TTS",
  173. "mistral": "Mistral Voxtral TTS", "neutts": "NeuTTS",
  174. }),
  175. "stt": ("local", {
  176. "openai": "OpenAI Whisper", "groq": "Groq Whisper", "mistral": "Mistral Voxtral Transcribe",
  177. "local": "Local faster-whisper",
  178. }),
  179. }
  180. def _provider_label(kind: str, current_provider: str) -> str:
  181. default, mapping = _PROVIDER_LABELS[kind]
  182. return mapping.get(current_provider or default, current_provider or mapping[default])
  183. def _local_stt_backend_available() -> bool:
  184. """True when faster-whisper imports or a custom local STT command is configured."""
  185. if get_env_value("HERMES_LOCAL_STT_COMMAND"):
  186. return True
  187. try:
  188. from tools.transcription_tools import _HAS_FASTER_WHISPER
  189. return bool(_HAS_FASTER_WHISPER)
  190. except Exception:
  191. return False
  192. def _any_env(*names: str) -> bool:
  193. """True when any of the named env vars (via get_env_value) is set."""
  194. return any(get_env_value(name) for name in names)
  195. def _account_info_or_none(**kwargs) -> Optional[NousPortalAccountInfo]:
  196. """``get_nous_portal_account_info(**kwargs)``, failing closed to ``None`` on any error."""
  197. try:
  198. return get_nous_portal_account_info(**kwargs)
  199. except Exception:
  200. return None
  201. def _state(key: str, **fields) -> NousFeatureState:
  202. spec = _FEATURES[key]
  203. fields.setdefault("direct_override", fields["active"] and not fields["managed_by_nous"])
  204. return NousFeatureState(key, spec.label, spec.included_by_default, **fields)
  205. def _web_feature(web_cfg: dict[str, object], tool_enabled: bool, managed: bool, web_gw: bool, direct_firecrawl: bool) -> NousFeatureState:
  206. # Per-capability overrides decide the active search/extract backend independently of web.backend.
  207. backend, search_backend, extract_backend = (_norm(web_cfg.get(k)) for k in ("backend", "search_backend", "extract_backend"))
  208. # The "nous" selection is serviced by Firecrawl — normalize so downstream vendor checks hold.
  209. if backend == "nous" or web_gw:
  210. backend = "firecrawl"
  211. # Direct readiness per vendor; a stored managed selection suppresses direct credentials.
  212. # Keyless Tavily is opt-in: selecting it writes web.backend (or a per-capability override).
  213. direct = {
  214. "exa": _any_env("EXA_API_KEY") and not web_gw,
  215. "firecrawl": direct_firecrawl,
  216. "parallel": _any_env("PARALLEL_API_KEY") and not web_gw,
  217. "tavily": (_any_env("TAVILY_API_KEY") or "tavily" in {backend, search_backend, extract_backend}) and not web_gw,
  218. "perplexity": _any_env("PERPLEXITY_API_KEY") and not web_gw,
  219. "searxng": _any_env("SEARXNG_URL"),
  220. }
  221. web_managed = managed and (
  222. (backend == "firecrawl" and not direct_firecrawl) or "nous" in {search_backend, extract_backend})
  223. active = web_managed or direct.get(backend) or direct.get(search_backend) or (extract_backend in ("tavily", "perplexity") and direct[extract_backend])
  224. return _state(
  225. "web", available=bool(managed or any(direct.values())), active=bool(tool_enabled and active),
  226. managed_by_nous=web_managed, toolset_enabled=tool_enabled,
  227. current_provider=backend or search_backend or extract_backend or "",
  228. explicit_configured=bool(backend or search_backend or extract_backend),
  229. )
  230. def managed_image_partner(config: dict[str, object]) -> Optional[str]:
  231. """Partner the image request is dispatched to (``"FAL"``, ``"Krea"`` or ``"Nous Portal"``);
  232. ``None`` when a direct vendor owns it. Reads the stored values the way the runtime dispatcher
  233. does, so the label and the route cannot disagree."""
  234. from tools.image_generation_managed import FAL, KREA, PORTAL, managed_route
  235. section = _section(config, "image_gen")
  236. return {FAL: "FAL", KREA: "Krea", PORTAL: "Nous Portal"}.get(
  237. managed_route(section.get("provider"), section.get("model")))
  238. def _fal_feature(key: str, tool_enabled: bool, direct: bool, managed: bool, selected: Optional[str]) -> NousFeatureState:
  239. # image_gen / video_gen: same FAL_KEY, independently gated managed availability.
  240. fal_managed = tool_enabled and managed and not direct
  241. if selected not in (None, "nous") or (selected is None and direct):
  242. label = "FAL"
  243. else:
  244. label = "Nous Subscription" if (fal_managed or selected == "nous") else ""
  245. return _state(
  246. key, available=bool(managed or direct), active=bool(tool_enabled and (fal_managed or direct)),
  247. managed_by_nous=fal_managed, toolset_enabled=tool_enabled, current_provider=label,
  248. explicit_configured=selected is not None or direct,
  249. )
  250. def _audio_provider(cfg: dict[str, object], default: str, gw: bool) -> str:
  251. provider = _norm(cfg.get("provider"), default)
  252. return "openai" if (provider == "nous" or gw) else (provider or default)
  253. def _audio_features(
  254. tts_cfg: dict[str, object], stt_cfg: dict[str, object], tts_tool_enabled: bool,
  255. managed: dict[str, bool], selected: dict[str, Optional[str]], use_gateway: dict[str, bool],
  256. ) -> tuple[NousFeatureState, NousFeatureState]:
  257. tts_gw, stt_gw = use_gateway["tts"], use_gateway["stt"]
  258. # STT default is "local" (faster-whisper, needs a pip install); Nous subscribers are routed to the
  259. # managed audio gateway by apply_nous_managed_defaults. The "nous" selection is serviced by OpenAI
  260. # — normalize so downstream vendor checks hold.
  261. tts_current = _audio_provider(tts_cfg, "edge", tts_gw)
  262. stt_current = _audio_provider(stt_cfg, "local", stt_gw)
  263. # Whisper reuses the TTS audio key (VOICE_TOOLS_OPENAI_KEY, falling back to OPENAI_API_KEY).
  264. audio_key = bool(resolve_openai_audio_api_key())
  265. direct_openai_tts, direct_openai_stt = audio_key and not tts_gw, audio_key and not stt_gw
  266. tts_available = bool({
  267. "edge": True, "neutts": True, "openai": managed["tts"] or direct_openai_tts,
  268. "elevenlabs": _any_env("ELEVENLABS_API_KEY") and not tts_gw, "mistral": _any_env("MISTRAL_API_KEY"),
  269. }.get(tts_current, False))
  270. tts = _state(
  271. "tts", available=tts_available, active=bool(tts_tool_enabled and tts_available),
  272. managed_by_nous=tts_tool_enabled and tts_current == "openai" and managed["tts"] and not direct_openai_tts,
  273. toolset_enabled=tts_tool_enabled, current_provider=_provider_label("tts", tts_current),
  274. # Mirrors the stored selection so status/picker markers stay in lockstep with dispatch.
  275. explicit_configured=selected["tts"] is not None and selected["tts"] != "edge",
  276. )
  277. # STT isn't a model-callable tool (the gateway voice middleware calls it on every inbound voice
  278. # message): "enabled" whenever a usable provider is configured, toolset_enabled reported True so
  279. # status never flags it "tool disabled".
  280. stt_available = bool({
  281. "local": _local_stt_backend_available() and not stt_gw, "openai": managed["stt"] or direct_openai_stt,
  282. "groq": _any_env("GROQ_API_KEY") and not stt_gw, "mistral": _any_env("MISTRAL_API_KEY") and not stt_gw,
  283. }.get(stt_current, False))
  284. stt = _state(
  285. "stt", available=stt_available, active=stt_available, toolset_enabled=True,
  286. managed_by_nous=stt_current == "openai" and managed["stt"] and not direct_openai_stt,
  287. current_provider=_provider_label("stt", stt_current), explicit_configured=selected["stt"] is not None,
  288. )
  289. return tts, stt
  290. def _browser_feature(
  291. browser_cfg: dict[str, object], tool_enabled: bool, managed: bool, browser_gw: bool, direct_firecrawl: bool,
  292. ) -> NousFeatureState:
  293. """Resolve browser availability using the same precedence as runtime."""
  294. explicit = "cloud_provider" in browser_cfg
  295. provider = normalize_browser_cloud_provider(browser_cfg.get("cloud_provider") if explicit else None)
  296. if provider == "nous" or browser_gw:
  297. provider = "browser-use"
  298. direct_browserbase = bool(get_env_value("BROWSERBASE_API_KEY") and get_env_value("BROWSERBASE_PROJECT_ID")) and not browser_gw
  299. direct_browser_use = _any_env("BROWSER_USE_API_KEY") and not browser_gw
  300. local_available = _has_browser_harness()
  301. local_runnable = _local_browser_runnable(browser_cfg)
  302. browser_use_managed = bool(tool_enabled and local_available and managed and not direct_browser_use)
  303. if explicit:
  304. cloud_available = {
  305. "browserbase": local_available and direct_browserbase,
  306. "browser-use": local_available and (managed or direct_browser_use), "firecrawl": local_available and direct_firecrawl,
  307. }
  308. current = provider if provider in cloud_available else "local"
  309. available = bool(cloud_available.get(current, local_runnable))
  310. managed_now = browser_use_managed if current == "browser-use" else False
  311. elif managed or direct_browser_use:
  312. current, available, managed_now = "browser-use", bool(local_available), browser_use_managed
  313. elif direct_browserbase:
  314. current, available, managed_now = "browserbase", bool(local_available), False
  315. else:
  316. current, available, managed_now = "local", bool(local_runnable), False
  317. return _state(
  318. "browser", available=available, active=bool(tool_enabled and available), managed_by_nous=managed_now,
  319. toolset_enabled=tool_enabled, current_provider=_provider_label("browser", current), explicit_configured=explicit,
  320. )
  321. def _modal_feature(terminal_cfg: dict[str, object], tool_enabled: bool, managed: bool, managed_tools_flag: bool) -> NousFeatureState:
  322. terminal_backend = _norm(terminal_cfg.get("backend"), "local")
  323. modal_mode = normalize_modal_mode(terminal_cfg.get("modal_mode"))
  324. direct_modal = has_direct_modal_credentials()
  325. modal_state = resolve_modal_backend_state(modal_mode, has_direct=direct_modal, managed_ready=managed, managed_enabled=managed_tools_flag)
  326. is_modal = terminal_backend == "modal"
  327. # A non-modal terminal backend, or a resolved managed/direct selection, is always "available";
  328. # otherwise report what the mode could use.
  329. selected = modal_state["selected_backend"] if is_modal else None
  330. if not is_modal or selected in ("managed", "direct"):
  331. available, active = True, bool(tool_enabled)
  332. managed_now = selected == "managed" and bool(tool_enabled)
  333. direct_override = is_modal and selected == "direct" and bool(tool_enabled)
  334. else:
  335. managed_now = direct_override = active = False
  336. available = bool({"managed": managed, "direct": direct_modal}.get(modal_mode, managed or direct_modal))
  337. return _state(
  338. "modal", available=available, active=active, managed_by_nous=managed_now, direct_override=direct_override,
  339. toolset_enabled=tool_enabled, current_provider="Modal" if is_modal else terminal_backend or "local",
  340. explicit_configured=is_modal,
  341. )
  342. def get_nous_subscription_features(config: Optional[dict[str, object]] = None, *, force_fresh: bool = False) -> NousSubscriptionFeatures:
  343. if config is None:
  344. config = load_config() or {}
  345. provider_is_nous = _provider_is_nous(config)
  346. account_info = _account_info_or_none(**({"force_fresh": True} if force_fresh else {}))
  347. # Coarse "entitled to any managed tool" gate: paid access OR a live free tool pool. Per-backend
  348. # availability is then narrowed by coverage (the pool funds image but not video, etc.).
  349. nous_auth_present = bool(account_info and account_info.logged_in)
  350. managed_tools_flag = nous_auth_present and account_info.tool_gateway_entitled
  351. enabled = {key: _toolset_enabled(config, key) for key in ("web", "image_gen", "video_gen", "tts", "browser", "terminal")}
  352. # Stored selections (strict model): "nous" = managed gateway; vendor name = that vendor direct;
  353. # None = never configured (autodetect). Lockstep with tool_backend_helpers.read_selection: a
  354. # merged ``stt.provider: local`` here means the raw file holds it — a genuine selection.
  355. selected = {
  356. key: _selected_provider(_section(config, section_key), field)
  357. for key, (section_key, field) in _GATEWAY_SECTION_FIELDS.items()
  358. }
  359. use_gateway = {key: value == "nous" for key, value in selected.items()}
  360. # Managed availability per feature. A stored VENDOR selection pins the category to direct
  361. # credentials — managed availability must not light it up (the runtime errors, not reroutes).
  362. # Features without a config selection field (modal) have no pin and read as unselected.
  363. managed = {
  364. key: (
  365. managed_tools_flag and is_managed_tool_gateway_ready(spec.gateway)
  366. and account_info.tool_gateway_entitled_for(spec.coverage)
  367. and (selected.get(key) is None or use_gateway.get(key, False))
  368. )
  369. for key, spec in _FEATURES.items()
  370. }
  371. direct_firecrawl = _any_env("FIRECRAWL_API_KEY", "FIRECRAWL_API_URL") and not use_gateway["web"]
  372. fal_configured = fal_key_is_configured()
  373. tts, stt = _audio_features(_section(config, "tts"), _section(config, "stt"), enabled["tts"], managed, selected, use_gateway)
  374. def _fal(key: str) -> NousFeatureState:
  375. return _fal_feature(key, enabled[key], fal_configured and not use_gateway[key], managed[key], selected[key])
  376. features = { # insertion order == _FEATURE_ORDER
  377. "web": _web_feature(_section(config, "web"), enabled["web"], managed["web"], use_gateway["web"], direct_firecrawl),
  378. "image_gen": _fal("image_gen"),
  379. "video_gen": _fal("video_gen"),
  380. "tts": tts,
  381. "stt": stt,
  382. "browser": _browser_feature(
  383. _section(config, "browser"), enabled["browser"], managed["browser"], use_gateway["browser"], direct_firecrawl,
  384. ),
  385. "modal": _modal_feature(_section(config, "terminal"), enabled["terminal"], managed["modal"], managed_tools_flag),
  386. }
  387. return NousSubscriptionFeatures(
  388. subscribed=provider_is_nous or nous_auth_present, nous_auth_present=nous_auth_present,
  389. provider_is_nous=provider_is_nous, features=features, account_info=account_info,
  390. )
  391. def _has_managed_default_direct(key: str) -> bool:
  392. return bool(key in ("tts", "stt") and resolve_openai_audio_api_key()) or _any_env(*_FEATURES[key].default_direct_env)
  393. def _krea_image_default(config: dict[str, object], account_info) -> Optional[str]:
  394. """Krea 3 for accounts entitled to Krea when no image model is stored; the free pool is not
  395. entitled and keeps the FAL default."""
  396. if _section(config, "image_gen").get("model") or not (account_info and account_info.tool_gateway_entitled_for("krea")):
  397. return None
  398. return MANAGED_IMAGE_DEFAULT_KREA_MODEL
  399. def apply_nous_managed_defaults(config: dict[str, object], *, enabled_toolsets: Optional[Iterable[str]] = None, force_fresh: bool = False) -> set[str]:
  400. features = get_nous_subscription_features(config, force_fresh=force_fresh)
  401. account_info = features.account_info
  402. if not (account_info and account_info.logged_in and account_info.tool_gateway_entitled and features.provider_is_nous):
  403. return set()
  404. selected_toolsets = set(enabled_toolsets or ())
  405. changed: set[str] = set()
  406. for key in _DEFAULT_SECTIONS:
  407. _ensure_section(config, key)
  408. for key in _DEFAULT_SECTIONS:
  409. if features.features[key].explicit_configured or _has_managed_default_direct(key):
  410. continue
  411. if key == "stt":
  412. # STT is not toolset-gated. Skip when the user has a working local backend (strong signal
  413. # "local" was a choice, not the DEFAULT_CONFIG seed) or isn't entitled to the managed
  414. # "openai-audio" category (flipping would silently break transcription).
  415. if _local_stt_backend_available() or not account_info.tool_gateway_entitled_for("openai-audio"):
  416. continue
  417. elif key not in selected_toolsets:
  418. continue
  419. _select_nous(config, key)
  420. changed.add(key)
  421. # Video gen is not funded by the free tool pool: only wire managed video for entitled (paid) users.
  422. for key, category in (("image_gen", None), ("video_gen", "fal-video")):
  423. if key in selected_toolsets and not fal_key_is_configured() and (category is None or account_info.tool_gateway_entitled_for(category)):
  424. model = None
  425. if key == "image_gen" and not features.features[key].explicit_configured:
  426. model = _krea_image_default(config, account_info)
  427. _select_nous(config, key, model=model)
  428. changed.add(key)
  429. return changed
  430. # Tool Gateway offer — per-tool checklist after model selection
  431. def _get_gateway_direct_credentials() -> dict[str, bool]:
  432. """tool_key -> has_direct_credentials. Env-configured keyless local backends (SearXNG, CAMOFOX_URL)
  433. count as configured so they are never classified "unconfigured" and pre-checked; Whisper shares
  434. the audio key with TTS. CAMOFOX_URL: the home browses through Camofox (the ``camofox`` plugin
  435. since it left core), so the managed browser is offered, not pre-checked over it."""
  436. fal_direct = fal_key_is_configured()
  437. audio_direct = bool(resolve_openai_audio_api_key())
  438. return {
  439. "web": _any_env("FIRECRAWL_API_KEY", "FIRECRAWL_API_URL", "PARALLEL_API_KEY", "TAVILY_API_KEY", "PERPLEXITY_API_KEY", "EXA_API_KEY", "SEARXNG_URL"),
  440. # Env-configured keyless local backend: a reachable self-hosted SearXNG is a working web setup even
  441. # with no stored selection (the autodetect cascade in tools/web_tools.py picks it up), so it must
  442. # not be classified "unconfigured" and pre-checked (#92647).
  443. "image_gen": fal_direct,
  444. "video_gen": fal_direct,
  445. "tts": audio_direct or _any_env("ELEVENLABS_API_KEY"),
  446. "stt": audio_direct or _any_env("GROQ_API_KEY", "MISTRAL_API_KEY"),
  447. "browser": (
  448. _any_env("BROWSER_USE_API_KEY", "CAMOFOX_URL")
  449. or bool(get_env_value("BROWSERBASE_API_KEY") and get_env_value("BROWSERBASE_PROJECT_ID"))
  450. ),
  451. }
  452. def get_gateway_eligible_tools(config: Optional[dict[str, object]] = None, *, force_fresh: bool = False) -> tuple[list[str], list[str], list[str], list[str]]:
  453. """(unconfigured, has_direct, explicit_configured, already_managed) tool key lists: no credentials
  454. and no explicit non-nous selection (safe to pre-check) / own API keys / explicit non-nous selection
  455. stored (e.g. keyless SearXNG) even with nothing to detect / ``use_gateway`` explicitly set."""
  456. # Entitlement gates the offer (paid OR live free pool) and says which categories are covered.
  457. account_info = _account_info_or_none(force_fresh=force_fresh)
  458. if not (account_info and account_info.logged_in and account_info.tool_gateway_entitled):
  459. return [], [], [], []
  460. if config is None:
  461. config = load_config() or {}
  462. if not _provider_is_nous(config):
  463. return [], [], [], []
  464. direct = _get_gateway_direct_credentials()
  465. unconfigured, has_direct, explicit_configured, already_managed = [], [], [], []
  466. for key in _ALL_GATEWAY_KEYS:
  467. # Only offer tools the entitlement covers (free pool: image but not video).
  468. if not account_info.tool_gateway_entitled_for(_FEATURES[key].coverage):
  469. continue
  470. section_key, field = _GATEWAY_SECTION_FIELDS[key]
  471. selected = _selected_provider(config.get(section_key), field)
  472. if _uses_gateway(config.get(key)):
  473. already_managed.append(key)
  474. elif selected is not None and selected != "nous":
  475. explicit_configured.append(key)
  476. elif direct.get(key):
  477. has_direct.append(key)
  478. else:
  479. unconfigured.append(key)
  480. return unconfigured, has_direct, explicit_configured, already_managed
  481. def apply_gateway_defaults(config: dict[str, object], tool_keys: list[str], account_info=None) -> set[str]:
  482. """Store the managed selection for ``tool_keys``; returns the set of tools actually changed."""
  483. for key in _DEFAULT_SECTIONS:
  484. _ensure_section(config, key)
  485. changed = [key for key in _ALL_GATEWAY_KEYS if key in tool_keys] # table order: config key order
  486. for key in changed:
  487. _select_nous(config, key, model=_krea_image_default(config, account_info) if key == "image_gen" else None)
  488. return set(changed)
  489. def prompt_enable_tool_gateway(config: dict[str, object], *, force_fresh: bool = True) -> set[str]:
  490. """If eligible tools exist, show a per-tool checklist to route them through the Tool Gateway.
  491. Triggered by a live free pool or paid access; explicit_configured tools (e.g. ``web.backend:
  492. searxng``) are configured on purpose and never offered, like already_managed."""
  493. unconfigured, has_direct, _explicit, _managed = get_gateway_eligible_tools(config, force_fresh=force_fresh)
  494. if not unconfigured and not has_direct:
  495. return set()
  496. try:
  497. from hermes_cli.setup import prompt_checklist
  498. except Exception:
  499. return set()
  500. # Frame the offer by entitlement: a $0 free-tool-pool user is not on a paid plan.
  501. account_info = _account_info_or_none(force_fresh=False)
  502. pool_only = bool(
  503. account_info and account_info.paid_service_access is not True and account_info.tool_access is not None and account_info.tool_access.enabled
  504. )
  505. source_label = "free tool pool" if pool_only else "Nous subscription"
  506. # Unconfigured tools first (pre-checked for new users), then tools with the user's own key
  507. # (unchecked). Tools previously offered and left unchecked are recorded in
  508. # ``tool_gateway_declined_tools`` and never pre-checked again (no re-fire on every model swap).
  509. # Acceptance used to be sticky while refusal was not, so the identical pre-checked checklist re-fired on
  510. # every Nous model swap. See #92647.
  511. declined_raw = config.get("tool_gateway_declined_tools")
  512. declined: set[str] = {str(k) for k in declined_raw} if isinstance(declined_raw, list) else set()
  513. offer_keys: list[str] = list(unconfigured) + list(has_direct)
  514. labels = [_GATEWAY_TOOL_LABELS[k] for k in unconfigured] + [
  515. f"{_GATEWAY_TOOL_LABELS[k]} — keep using your {_FEATURES[k].direct_label}" for k in has_direct
  516. ]
  517. pre_selected = [i for i, k in enumerate(unconfigured) if k not in declined]
  518. title = (
  519. "Your free Nous tool pool — pick the tools to enable:" if pool_only
  520. else "Your Nous subscription includes the Tool Gateway — pick the tools to enable:"
  521. )
  522. try:
  523. chosen_idx = prompt_checklist(title, labels, pre_selected)
  524. except (KeyboardInterrupt, EOFError, OSError, SystemExit):
  525. return set()
  526. chosen_keys = [offer_keys[i] for i in chosen_idx if 0 <= i < len(offer_keys)]
  527. # Every offered unconfigured tool NOT chosen is a decline; choosing a previously-declined tool
  528. # clears it. Cancel paths above return before this and record nothing.
  529. newly_declined = [k for k in unconfigured if k not in chosen_keys and k not in declined]
  530. if newly_declined or (declined & set(chosen_keys)):
  531. config["tool_gateway_declined_tools"] = sorted((declined | set(newly_declined)) - set(chosen_keys))
  532. changed = apply_gateway_defaults(config, chosen_keys, account_info) if chosen_keys else set()
  533. if changed or newly_declined:
  534. from hermes_cli.config import save_config
  535. save_config(config)
  536. for key in sorted(changed):
  537. print(f" ✓ {_GATEWAY_TOOL_LABELS.get(key, key)}: enabled via {source_label}")
  538. return changed
  539. # Inline Nous Portal login for the Tool Gateway picker (`hermes tools`)
  540. def ensure_nous_portal_access(*, capability: str = "the Nous Tool Gateway", coverage_category: Optional[str] = None) -> bool:
  541. """Make sure the user is entitled to the Nous Tool Gateway, logging in if needed.
  542. Only performs the device-code OAuth (when not logged in) and refreshes entitlement — no model
  543. or provider switch. Entitlement is paid access OR a live free pool; with ``coverage_category``
  544. the pool must cover that category (a pool user selecting ``"fal-video"`` is denied).
  545. """
  546. def _entitled(account) -> bool:
  547. if account is None:
  548. return False
  549. return account.tool_gateway_entitled_for(coverage_category) if coverage_category is not None else account.tool_gateway_entitled
  550. info = _account_info_or_none(force_fresh=True)
  551. if not _entitled(info) and (info is None or not info.logged_in):
  552. if not _run_nous_portal_login_only(capability=capability):
  553. return False
  554. info = _account_info_or_none(force_fresh=True)
  555. if _entitled(info):
  556. return True
  557. # Logged in but not entitled for this capability — neutral billing guidance, do not enable.
  558. message = format_nous_portal_entitlement_message(info, capability=capability, coverage_category=coverage_category)
  559. for line in (message or "").splitlines():
  560. print(f" {line}")
  561. return False
  562. def _confirm(prompt: str) -> Optional[bool]:
  563. """Y/n prompt: True on yes/blank, False on anything else, ``None`` on EOF/Ctrl-C."""
  564. try:
  565. return input(prompt).strip().lower() in {"", "y", "yes"}
  566. except (EOFError, KeyboardInterrupt):
  567. return None
  568. def _run_nous_portal_login_only(*, capability: str) -> bool:
  569. """Run the Nous Portal device-code OAuth and persist credentials only (no model selection, no
  570. provider switch, no Tool Gateway bulk prompt). ``False`` if the user declined or the flow failed."""
  571. try:
  572. from hermes_cli import auth
  573. except Exception as exc: # pragma: no cover - defensive
  574. print(f" Could not start Nous Portal login: {exc}")
  575. return False
  576. print()
  577. print(f" {capability} requires a Nous Portal login.")
  578. proceed = _confirm(" Log in to Nous Portal now? [Y/n]: ")
  579. if proceed is None:
  580. print()
  581. return False
  582. if not proceed:
  583. print(" Skipped Nous Portal login.")
  584. return False
  585. try:
  586. # Snapshot active_provider so a tool-config login never silently switches inference to Nous.
  587. with auth._auth_store_lock():
  588. prior_active_provider = auth._load_auth_store().get("active_provider")
  589. auth_state = None
  590. # Interrupting the import question defaults to importing.
  591. from hermes_cli.anon_auth import is_guest_state
  592. shared = auth._read_shared_nous_state()
  593. if shared and not is_guest_state(shared) and _confirm(" Found existing Nous OAuth credentials. Import them? [Y/n]: ") is not False:
  594. auth_state = auth._try_import_shared_nous_state(timeout_seconds=15.0)
  595. if auth_state is None:
  596. auth_state = auth._nous_device_code_login()
  597. from hermes_cli.anon_auth import settle_after_upgrade
  598. from hermes_cli.guest_handoff import drain, result_lines
  599. with auth._auth_store_lock():
  600. auth_store = auth._load_auth_store()
  601. auth._save_provider_state(auth_store, "nous", auth_state)
  602. if prior_active_provider:
  603. auth_store["active_provider"] = prior_active_provider
  604. else:
  605. auth_store.pop("active_provider", None)
  606. auth._save_auth_store(auth_store)
  607. auth._write_shared_nous_state(auth_state, renewal=False)
  608. handoff = drain() # a replaced free tier hands its apps over once both saves land
  609. auth._sync_nous_pool_from_auth_store()
  610. settle_after_upgrade(auth_state) # a config left on the free tier's route moves to the account
  611. print(" Nous Portal login successful.")
  612. for line in (line for view in handoff for line in result_lines(view)):
  613. print(f" {line}")
  614. return True
  615. except KeyboardInterrupt:
  616. print("\n Login cancelled.")
  617. return False
  618. except SystemExit:
  619. # _nous_device_code_login raises SystemExit on subscription_required (guidance already printed).
  620. return False
  621. except Exception as exc:
  622. print(f" Nous Portal login failed: {exc}")
  623. return False