tools_config_providers.py 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. """Provider rows, active-provider detection, model pickers and provider-selection persistence for `hermes tools`."""
  2. from __future__ import annotations
  3. import importlib
  4. import logging
  5. from functools import partial
  6. from typing import Callable, Optional
  7. from hermes_cli.cli_output import (
  8. print_info as _print_info, print_success as _print_success, print_warning as _print_warning, prompt as _prompt,
  9. )
  10. from hermes_cli.colors import Colors, color
  11. from hermes_cli.config import cfg_get, get_env_value, load_config, save_config, save_env_value
  12. from hermes_cli.nous_account import format_nous_portal_entitlement_message
  13. from hermes_cli.nous_subscription import MANAGED_FEATURE_COVERAGE_CATEGORY, NousSubscriptionFeatures
  14. from tools.tool_backend_helpers import NOUS_MANAGED_PROVIDER, fal_key_is_configured
  15. from tools.transcription_common import STT_MODEL_CATALOG, STT_MODEL_CONFIG_KEY
  16. from utils import base_url_hostname, is_truthy_value
  17. logger = logging.getLogger("hermes_cli.tools_config")
  18. # tools_config-internal names (TOOL_CATEGORIES, _cfg_section, _prompt_choice, ...) are imported lazily
  19. # inside the functions that need them: tools_config re-imports this module, and tests patch those names there.
  20. def _plugin_registry(module: str):
  21. """Import a plugin registry module after plugin discovery; ``None`` on any failure."""
  22. try:
  23. registry = importlib.import_module(module)
  24. from hermes_cli.plugins import _ensure_plugins_discovered
  25. _ensure_plugins_discovered()
  26. return registry
  27. except Exception:
  28. return None
  29. def _plugin_provider_rows(
  30. registry_module: str, marker_keys: tuple[str, ...], *, require_name: bool = True, skip_builtin: bool = False,
  31. flatten_variants: bool = False) -> list[dict]:
  32. """Picker-row dicts (TOOL_CATEGORIES-shaped) for a plugin registry's providers.
  33. ``marker_keys`` are all set to the registry name so downstream config/model-picker code routes
  34. through the registry. ``skip_builtin`` drops names shadowing ``_BUILTIN_NAMES``;
  35. ``flatten_variants`` expands a schema's tier ``variants`` into separate rows sharing one backend
  36. name, distinguished by ``web_tier``."""
  37. registry = _plugin_registry(registry_module)
  38. if registry is None:
  39. return []
  40. try:
  41. providers = registry.list_providers()
  42. builtin = registry._BUILTIN_NAMES if skip_builtin else frozenset()
  43. except Exception:
  44. return []
  45. rows: list[dict] = []
  46. for provider in providers:
  47. if require_name:
  48. name = getattr(provider, "name", None)
  49. if not name or (skip_builtin and name.lower().strip() in builtin):
  50. continue
  51. try:
  52. schema = provider.get_setup_schema()
  53. except Exception:
  54. continue
  55. if not isinstance(schema, dict):
  56. continue
  57. if not require_name:
  58. name = provider.name
  59. entries = [schema]
  60. if flatten_variants:
  61. entries += [v for v in (schema.get("variants") or []) if isinstance(v, dict)]
  62. for entry in entries:
  63. row = {"name": entry.get("name", provider.display_name), "badge": entry.get("badge", ""),
  64. "tag": entry.get("tag", ""), "env_vars": entry.get("env_vars", [])}
  65. row.update({key: name for key in marker_keys})
  66. if flatten_variants and entry.get("web_tier"):
  67. row["web_tier"] = entry["web_tier"]
  68. if entry.get("post_setup"):
  69. row["post_setup"] = entry["post_setup"]
  70. rows.append(row)
  71. return rows
  72. # Category -> (registry module, marker keys, _plugin_provider_rows kwargs). ``*_plugin_name`` markers route
  73. # config writes + model pickers through the registry; ``browser_provider`` is the legacy ``browser.cloud_provider``
  74. # key; TTS rows write ``tts.provider: <name>``.
  75. _PLUGIN_PROVIDER_ROW_SPECS = {
  76. "image_gen": ("agent.image_gen_registry", ("image_gen_plugin_name",), {"require_name": False}),
  77. "video_gen": ("agent.video_gen_registry", ("video_gen_plugin_name",), {"require_name": False}),
  78. "web": ("agent.web_search_registry", ("web_backend", "web_search_plugin_name"), {"flatten_variants": True}),
  79. "browser": ("agent.browser_registry", ("browser_provider", "browser_plugin_name"), {}),
  80. "tts": ("agent.tts_registry", ("tts_provider", "tts_plugin_name"), {"skip_builtin": True})}
  81. def _plugin_rows_for(category: str) -> list[dict]:
  82. """Picker rows for the plugin-registered providers of one ``_PLUGIN_PROVIDER_ROW_SPECS`` category."""
  83. module, markers, kwargs = _PLUGIN_PROVIDER_ROW_SPECS[category]
  84. return _plugin_provider_rows(module, markers, **kwargs)
  85. _plugin_image_gen_providers, _plugin_video_gen_providers, _plugin_web_search_providers, \
  86. _plugin_browser_providers, _plugin_tts_providers = (
  87. partial(_plugin_rows_for, cat) for cat in ("image_gen", "video_gen", "web", "browser", "tts"))
  88. def web_provider_capabilities(backend: str) -> list:
  89. """Capabilities (``search`` / ``extract``) a web backend supports, per the registry provider instance.
  90. Lets the Capabilities GUI offer ``web.search_backend`` / ``web.extract_backend`` only where it makes
  91. sense (ddgs and brave-free are search-only). Unknown backend or registry failure -> both."""
  92. try:
  93. from agent.web_search_registry import get_provider
  94. provider = get_provider(backend)
  95. if provider is not None:
  96. return [cap for cap, supported in (("search", provider.supports_search()),
  97. ("extract", provider.supports_extract())) if supported]
  98. except Exception:
  99. pass
  100. return ["search", "extract"]
  101. # TOOL_CATEGORIES[<key>]["name"] -> builder of plugin-registered picker rows.
  102. _PLUGIN_ROW_BUILDERS = {
  103. "Image Generation": _plugin_image_gen_providers,
  104. "Video Generation": _plugin_video_gen_providers,
  105. "Web Search & Extract": _plugin_web_search_providers,
  106. "Browser Automation": _plugin_browser_providers,
  107. "Text-to-Speech": _plugin_tts_providers,
  108. "Computer Use (macOS/Windows/Linux)": lambda: _computer_use_provider_rows()}
  109. def _computer_use_provider_rows() -> list[dict]:
  110. """Rows for installed computer-use providers other than the built-in ``cua`` (hand-written row with its
  111. install post-setup). Read from plugin.yaml without importing: an unselected provider stays dormant."""
  112. from plugins.computer_use import DEFAULT_BACKEND, discover_computer_use_providers
  113. return [{"name": name, "badge": "", "tag": desc, "env_vars": [], "computer_use_backend": name}
  114. for name, desc in discover_computer_use_providers() if name != DEFAULT_BACKEND]
  115. def _visible_providers(
  116. cat: dict, config: dict, *, force_fresh: bool = False, features: Optional[NousSubscriptionFeatures] = None,
  117. ) -> list[dict]:
  118. """Provider entries visible for the current auth/config state.
  119. Nous-managed rows (``managed_nous_feature``) are always shown, even logged-out/unentitled, to
  120. advertise the capability."""
  121. from hermes_cli.tools_config import get_nous_subscription_features
  122. if features is None:
  123. features = get_nous_subscription_features(config, force_fresh=force_fresh)
  124. acct = features.account_info
  125. # Pool-only users (free tool pool, no paid access) get image gen but NOT video gen — the pool doesn't
  126. # fund `fal-video`, so hide the managed video row rather than advertise a denial.
  127. pool_only = bool(acct and acct.logged_in and acct.paid_service_access is not True and acct.tool_gateway_entitled)
  128. visible = []
  129. for provider in cat.get("providers", []):
  130. managed = provider.get("managed_nous_feature")
  131. # Managed rows stay visible regardless of auth (selecting one drives an inline Portal login); a
  132. # `requires_nous_auth` row without a managed feature hides until logged in.
  133. if provider.get("requires_nous_auth") and not managed and not features.nous_auth_present:
  134. continue
  135. if pool_only and managed == "video_gen" and not (acct and acct.tool_gateway_entitled_for("fal-video")):
  136. continue
  137. visible.append(provider)
  138. # Plugin-registered rows render BELOW the hardcoded rows (for web/browser they are the only real provider rows).
  139. builder = _PLUGIN_ROW_BUILDERS.get(cat.get("name"))
  140. if builder is not None:
  141. visible.extend(builder())
  142. return visible
  143. def provider_readiness_status(provider: dict, config: dict, *, features=None, is_active: Optional[bool] = None) -> str:
  144. """Honest readiness state for a provider picker row.
  145. ``features`` avoids re-fetching portal state per row. ``is_active`` is the completed-setup fallback
  146. for post_setup hooks with no registered installed-check (selecting a row runs its hook)."""
  147. from hermes_cli.tools_config import _POST_SETUP_READY, _provider_env_ready, get_nous_subscription_features
  148. from hermes_cli.tools_config_post_setup import _POST_SETUP_AUTH_READY
  149. if provider.get("env_vars", []):
  150. return "ready" if _provider_env_ready(provider) else "needs_keys"
  151. managed_feature = provider.get("managed_nous_feature")
  152. if provider.get("requires_nous_auth") or managed_feature:
  153. if features is None:
  154. features = get_nous_subscription_features(config)
  155. if not features.nous_auth_present:
  156. return "needs_auth"
  157. if managed_feature:
  158. # Same per-category entitlement gate the CLI applies at selection time.
  159. acct = features.account_info
  160. category = MANAGED_FEATURE_COVERAGE_CATEGORY.get(managed_feature)
  161. entitled = bool(acct and acct.logged_in and (
  162. acct.tool_gateway_entitled_for(category) if category else acct.tool_gateway_entitled))
  163. if not entitled:
  164. return "needs_auth"
  165. # Signed in and entitled — fall through: a managed row may still carry a local install hook.
  166. post_setup = provider.get("post_setup")
  167. if post_setup:
  168. auth_predicate = _POST_SETUP_AUTH_READY.get(post_setup)
  169. if auth_predicate is not None:
  170. return "ready" if auth_predicate() else "needs_auth"
  171. predicate = _POST_SETUP_READY.get(post_setup)
  172. if predicate is not None:
  173. try:
  174. return "ready" if predicate() else "needs_setup"
  175. except Exception:
  176. return "ready" # flaky detection must not manufacture a warning state
  177. # No installed-check registered → the active-provider signal means "setup completed".
  178. if is_active is None:
  179. is_active = _is_provider_active(provider, config)
  180. return "ready" if is_active else "needs_setup"
  181. return _web_registry_readiness(provider)
  182. def _web_registry_readiness(provider: dict) -> str:
  183. """Keyless, untiered web rows are ready only when their registry provider is available: the only such
  184. row's ``is_available()`` is an account login (OpenAI Native = openai-codex), hence ``needs_auth``.
  185. Free-tier rows are exempt: they run on the public keyless ring, which ``is_available()`` ignores."""
  186. backend = provider.get("web_backend")
  187. if not backend or provider.get("web_tier"):
  188. return "ready"
  189. from agent.web_search_registry import get_provider
  190. registered = get_provider(backend)
  191. return "ready" if registered is None or registered.is_available() else "needs_auth"
  192. def _toolset_needs_configuration_prompt(ts_key: str, config: dict, *, force_fresh: bool = False) -> bool:
  193. """Return True when enabling this toolset should open provider setup."""
  194. from hermes_cli.tools_config import TOOL_CATEGORIES, _post_setup_already_installed, _toolset_has_keys
  195. cat = TOOL_CATEGORIES.get(ts_key)
  196. if not cat:
  197. return not _toolset_has_keys(ts_key, config, force_fresh=force_fresh)
  198. # An unsatisfied post_setup install-state check (e.g. cua-driver not on PATH yet) forces the
  199. # configuration flow so `_configure_provider` runs the hook and the install actually happens.
  200. for provider in _visible_providers(cat, config, force_fresh=force_fresh):
  201. post_setup = provider.get("post_setup")
  202. if post_setup and not _post_setup_already_installed(post_setup):
  203. return True
  204. # Categories whose "configured" signal is a selected provider key.
  205. selection_key = {"tts": "provider", "web": "backend", "browser": "cloud_provider"}.get(ts_key)
  206. if selection_key:
  207. section = config.get(ts_key, {})
  208. if not isinstance(section, dict):
  209. return True
  210. return selection_key not in section
  211. if ts_key == "image_gen": # in-tree FAL backend OR any available plugin image gen provider satisfies
  212. return not fal_key_is_configured() and not _any_plugin_provider_available("agent.image_gen_registry")
  213. if ts_key == "video_gen": # no in-tree fallback — every video backend is a plugin
  214. return not _any_plugin_provider_available("agent.video_gen_registry")
  215. return not _toolset_has_keys(ts_key, config, force_fresh=force_fresh)
  216. def _any_plugin_provider_available(registry_module: str) -> bool:
  217. """True when any provider in the plugin registry reports ``is_available()``."""
  218. registry = _plugin_registry(registry_module)
  219. try:
  220. for provider in registry.list_providers():
  221. try:
  222. if provider.is_available():
  223. return True
  224. except Exception:
  225. continue
  226. except Exception:
  227. pass
  228. return False
  229. def _configure_tool_category(ts_key: str, cat: dict, config: dict, *, force_fresh: bool = True, reconfigure: bool = False):
  230. """Provider selection for a tool category, then API-key setup for the chosen row.
  231. ``reconfigure`` ("Reconfigure an existing tool"): no setup note / skip row / Nous marker, and the
  232. chosen provider goes through the key-update prompts instead of the new-enable prompts."""
  233. from hermes_cli.tools_config import _prompt_choice, _provider_env_ready, get_nous_subscription_features
  234. name = cat["name"]
  235. providers = _visible_providers(cat, config, force_fresh=force_fresh)
  236. single = len(providers) == 1
  237. title = "Choose a provider" if reconfigure else cat.get("setup_title", "Choose a provider")
  238. print()
  239. heading = f"({providers[0]['name']})" if single else f"- {title}"
  240. print(color(f" --- {cat.get('icon', '')} {name} {heading} ---", Colors.CYAN))
  241. if single and not reconfigure and providers[0].get("tag"):
  242. _print_info(f" {providers[0]['tag']}")
  243. if not reconfigure and cat.get("setup_note"):
  244. _print_info(f" {cat['setup_note']}")
  245. if single:
  246. _configure_provider(providers[0], config, force_fresh=force_fresh, reconfigure=reconfigure)
  247. return
  248. print()
  249. # Logged-in Nous users get a marker on rows included in their subscription (cost-extra vs. included).
  250. _nous_logged_in = False
  251. if not reconfigure:
  252. try:
  253. _nous_logged_in = bool(get_nous_subscription_features(config, force_fresh=force_fresh).nous_auth_present)
  254. except Exception:
  255. pass
  256. provider_choices = [] # plain text labels only (no ANSI codes in menu items)
  257. for p in providers:
  258. badge = f" [{p['badge']}]" if p.get("badge") else ""
  259. tag = f" — {p['tag']}" if p.get("tag") else ""
  260. configured = ""
  261. if _provider_env_ready(p):
  262. if _is_provider_active(p, config, force_fresh=force_fresh):
  263. configured = " [active]"
  264. elif p.get("env_vars", []):
  265. configured = " [configured]"
  266. # Subscribers get the "included" star; everyone else a hint that selecting triggers a Portal login.
  267. sub_marker = ""
  268. if not reconfigure and p.get("managed_nous_feature"):
  269. sub_marker = " ★ Included with your Nous subscription" if _nous_logged_in else " ★ via Nous Portal (login on select)"
  270. provider_choices.append(f"{p['name']}{badge}{tag}{configured}{sub_marker}")
  271. if not reconfigure:
  272. provider_choices.append("Skip — keep defaults / configure later")
  273. default_idx = _detect_active_provider_index(providers, config, force_fresh=force_fresh)
  274. question = " Select provider:" if reconfigure else f" {title}:"
  275. provider_idx = _prompt_choice(question, provider_choices, default_idx)
  276. if provider_idx >= len(providers):
  277. _print_info(f" Skipped {name}")
  278. return
  279. _configure_provider(providers[provider_idx], config, force_fresh=force_fresh, reconfigure=reconfigure)
  280. def _web_tier_matches(provider: dict, config: dict) -> bool:
  281. """True when a web picker row's tier matches the configured tier (``web.provider_tier.<backend>``).
  282. Tiered rows (Exa/Parallel Free vs Paid) share one ``web_backend`` and differ only in ``web_tier``.
  283. No ``web_tier`` on the row → matches; configured tier set → must equal the row's tier; unset →
  284. "auto": paid when the row's key is present, free otherwise (highlight the row the runtime would
  285. actually use)."""
  286. row_tier = provider.get("web_tier")
  287. if not row_tier:
  288. return True
  289. web_cfg = config.get("web") if isinstance(config.get("web"), dict) else {}
  290. tiers = web_cfg.get("provider_tier") if isinstance(web_cfg.get("provider_tier"), dict) else {}
  291. configured = str(tiers.get(provider["web_backend"], "") or "").lower().strip()
  292. if configured in ("free", "paid"):
  293. return configured == row_tier
  294. # Auto: mirror plugins.web.keyless_mcp.use_keyless — key present → paid.
  295. try:
  296. from agent.web_search_provider import get_provider_env
  297. key_var = {"exa": "EXA_API_KEY", "parallel": "PARALLEL_API_KEY"}.get(provider["web_backend"])
  298. has_key = bool(get_provider_env(key_var)) if key_var else False
  299. except Exception:
  300. has_key = False
  301. return row_tier == ("paid" if has_key else "free")
  302. def _web_serving_backends(config: dict) -> set:
  303. """Backend names serving web search / extract as configured: each capability's own
  304. ``web.<cap>_backend`` override first, else the shared ``web.backend`` (``tools/web_tools.py``
  305. dispatch order; legacy ``use_gateway: true`` reads as the managed ``nous`` selection).
  306. Lower-cased and stripped like the dispatchers."""
  307. raw_web_cfg = config.get("web")
  308. web_cfg = raw_web_cfg if isinstance(raw_web_cfg, dict) else {}
  309. def _name(key: str) -> str:
  310. value = web_cfg.get(key)
  311. return value.lower().strip() if isinstance(value, str) else ""
  312. shared = NOUS_MANAGED_PROVIDER if is_truthy_value(web_cfg.get("use_gateway"), default=False) else _name("backend")
  313. serving = {_name(key) or shared for key in ("search_backend", "extract_backend")}
  314. serving.discard("")
  315. return serving
  316. def _web_backend_active(provider: dict, config: dict) -> bool:
  317. """True when a web row's ``web_backend`` serves either capability as configured: a vendor serving
  318. one capability through its override is in use even when the shared key names a different one,
  319. and a shared vendor shadowed by both overrides serves nothing. Managed Nous rows never reach
  320. here — they answer in ``_managed_provider_active``."""
  321. backend = provider.get("web_backend")
  322. if not (backend and backend in _web_serving_backends(config) and _web_tier_matches(provider, config)):
  323. return False
  324. # Rows sharing one backend name (cloud "Firecrawl" vs the "Firecrawl Self-Hosted" setup row) differ only in
  325. # the env var they configure, and the one whose var is set is what serves the call. A setup row needs its
  326. # var; the registry row also stays active keyless (explicit ``firecrawl`` with no key = anonymous cloud)
  327. # unless a sibling setup row's var is set instead.
  328. from hermes_cli.tools_config import TOOL_CATEGORIES, _provider_env_ready
  329. if not provider.get("env_vars") or _provider_env_ready(provider):
  330. return True
  331. return bool(provider.get("web_search_plugin_name")) and not any(
  332. row.get("web_backend") == backend and row.get("env_vars") and _provider_env_ready(row)
  333. for row in TOOL_CATEGORIES["web"]["providers"])
  334. # Managed-row marker -> (config section, key) the pick writes, in check order.
  335. _MANAGED_SELECTION_KEYS: tuple[tuple[str, str, str], ...] = (
  336. ("tts_provider", "tts", "provider"), ("stt_provider", "stt", "provider"),
  337. ("browser_provider", "browser", "cloud_provider"))
  338. def _has_marker(provider: dict, marker: str) -> bool:
  339. """``browser_provider`` is a membership test (a local row carries ``browser_provider: ""``); every other
  340. marker is a truthiness test."""
  341. return marker in provider if marker == "browser_provider" else bool(provider.get(marker))
  342. def _managed_provider_active(provider: dict, config: dict, managed_feature: str, force_fresh: bool) -> bool:
  343. """Active check for a Nous-managed row: the feature must be managed AND the category's selected
  344. provider must be the row's vendor or ``nous``."""
  345. from hermes_cli.tools_config import get_nous_subscription_features
  346. feature = get_nous_subscription_features(config, force_fresh=force_fresh).features.get(managed_feature)
  347. if feature is None:
  348. return False
  349. if managed_feature in ("image_gen", "video_gen"):
  350. gen_cfg = config.get(managed_feature, {})
  351. if isinstance(gen_cfg, dict):
  352. configured_provider = gen_cfg.get("provider")
  353. if configured_provider not in {None, "", "fal", NOUS_MANAGED_PROVIDER}:
  354. return False
  355. if (
  356. configured_provider != NOUS_MANAGED_PROVIDER
  357. and gen_cfg.get("use_gateway") is not None
  358. and not is_truthy_value(gen_cfg.get("use_gateway"), default=False)):
  359. return False
  360. return feature.managed_by_nous
  361. if _has_marker(provider, "web_backend"):
  362. # Search and extract pick their route separately: the managed row serves whichever one
  363. # resolves to the gateway (a ``nous`` override, or the shared ``nous`` selection).
  364. return feature.managed_by_nous and NOUS_MANAGED_PROVIDER in _web_serving_backends(config)
  365. for marker, section, key in _MANAGED_SELECTION_KEYS:
  366. if _has_marker(provider, marker):
  367. current = cfg_get(config, section, key)
  368. return feature.managed_by_nous and current in {provider[marker], NOUS_MANAGED_PROVIDER}
  369. return feature.managed_by_nous
  370. def _browser_provider_active(provider: dict, config: dict) -> bool:
  371. if provider["browser_provider"] != cfg_get(config, "browser", "cloud_provider"):
  372. return False
  373. # Two local rows differ only by engine ("Local Browser" vs "Lightpanda"): config.yaml is the picker's
  374. # source of truth here.
  375. if provider.get("browser_engine"):
  376. engine = str(cfg_get(config, "browser", "engine") or "auto").strip().lower()
  377. return engine == provider["browser_engine"]
  378. return True
  379. def _imagegen_backend_active(provider: dict, config: dict) -> bool:
  380. image_cfg = config.get("image_gen", {})
  381. return (
  382. isinstance(image_cfg, dict)
  383. and provider["imagegen_backend"] == "fal"
  384. and image_cfg.get("provider") in {None, "", "fal"}
  385. and not is_truthy_value(image_cfg.get("use_gateway"), default=False))
  386. # Non-managed active checks, evaluated in order; the first marker the row carries decides (see ``_has_marker``).
  387. # Default stt.provider is "local" — an unset key means Local Whisper.
  388. _ACTIVE_CHECKS: tuple[tuple[str, Callable[[dict, dict], bool]], ...] = (
  389. ("tts_provider", lambda p, c: cfg_get(c, "tts", "provider") == p["tts_provider"]),
  390. ("stt_provider", lambda p, c: (cfg_get(c, "stt", "provider") or "local") == p["stt_provider"]),
  391. ("browser_provider", _browser_provider_active),
  392. ("web_backend", _web_backend_active),
  393. ("computer_use_backend", lambda p, c: cfg_get(c, "computer_use", "backend") == p["computer_use_backend"]),
  394. ("imagegen_backend", _imagegen_backend_active))
  395. def _is_provider_active(provider: dict, config: dict, *, force_fresh: bool = False) -> bool:
  396. """Check if a provider entry matches the currently active config."""
  397. managed_feature = provider.get("managed_nous_feature")
  398. # Managed entries fall through to the managed branch, which also checks use_gateway — otherwise a
  399. # managed FAL pick and a direct-key FAL pick would both report active.
  400. for section in ("image_gen", "video_gen"):
  401. plugin_name = provider.get(f"{section}_plugin_name")
  402. if plugin_name and not managed_feature:
  403. gen_cfg = config.get(section, {})
  404. if not (isinstance(gen_cfg, dict) and gen_cfg.get("provider") == plugin_name):
  405. return False
  406. # A direct-key image gen entry is only active when the managed route is OFF.
  407. return section == "video_gen" or not is_truthy_value(gen_cfg.get("use_gateway"), default=False)
  408. if managed_feature:
  409. return _managed_provider_active(provider, config, managed_feature, force_fresh)
  410. for marker, check in _ACTIVE_CHECKS:
  411. if _has_marker(provider, marker):
  412. return check(provider, config)
  413. return False
  414. def _detect_active_provider_index(providers: list, config: dict, *, force_fresh: bool = False) -> int:
  415. """Return the index of the currently active provider, or 0."""
  416. from hermes_cli.tools_config import _provider_env_ready
  417. for i, p in enumerate(providers):
  418. if _is_provider_active(p, config, force_fresh=force_fresh):
  419. return i
  420. if p.get("env_vars", []) and _provider_env_ready(p): # fallback: env vars present → likely configured
  421. return i
  422. return 0
  423. def _fal_model_catalog(config: dict):
  424. """Lazy-load the FAL model catalog."""
  425. from tools.image_generation_catalog import FAL_MODELS, DEFAULT_MODEL
  426. return FAL_MODELS, DEFAULT_MODEL
  427. def _managed_image_catalog(config: dict):
  428. """The managed row's union catalog (FAL + Krea + Portal), minus the gateways this account cannot use.
  429. A free-pool account is funded for FAL only, so its picker never offers a Krea or Portal model it
  430. would be denied at generation time; a logged-out or paid account sees everything."""
  431. from hermes_cli.tools_config import get_nous_subscription_features
  432. from tools.image_generation_managed import managed_image_catalog
  433. acct = get_nous_subscription_features(config).account_info
  434. pool_only = bool(acct and acct.logged_in and acct.paid_service_access is not True)
  435. return managed_image_catalog(
  436. include_krea=not pool_only or acct.tool_gateway_entitled_for("krea"), include_portal=not pool_only)
  437. # Per-backend model catalog (config_key = top-level config.yaml section, catalog_fn(config) -> ({model_id:
  438. # metadata}, default_model)); a TOOL_CATEGORIES row tagged `imagegen_backend: "<name>"` selects the catalog at
  439. # picker time. "nous" is the single managed row: one catalog spanning the FAL, Krea and Portal gateways.
  440. IMAGEGEN_BACKENDS = {
  441. "fal": {"display": "FAL.ai", "config_key": "image_gen", "catalog_fn": _fal_model_catalog},
  442. "nous": {"display": "Nous Subscription", "config_key": "image_gen", "catalog_fn": _managed_image_catalog}}
  443. def _plugin_model_catalog(registry_module: str, plugin_name: str):
  444. """``(catalog_dict, default_model_id)`` for a plugin provider; ``catalog_dict`` is shaped like the legacy
  445. ``FAL_MODELS`` table so the picker path is shared. ``({}, None)`` if unregistered or no models."""
  446. registry = _plugin_registry(registry_module)
  447. try: # a missing registry / unknown provider surfaces as AttributeError here — same ({}, None) outcome
  448. provider = registry.get_provider(plugin_name)
  449. models = provider.list_models() or []
  450. default = provider.default_model()
  451. except Exception:
  452. return {}, None
  453. return {m["id"]: m for m in models if isinstance(m, dict) and "id" in m}, default
  454. _plugin_image_gen_catalog = partial(_plugin_model_catalog, "agent.image_gen_registry")
  455. _plugin_video_gen_catalog = partial(_plugin_model_catalog, "agent.video_gen_registry")
  456. def _pick_model_from_catalog(
  457. catalog: dict, default_model, cfg_key: str, display: str, config: dict, *, row_indent: str = "",
  458. ) -> None:
  459. """Column-aligned model picker shared by the FAL, plugin image gen and video gen flows.
  460. Writes the choice to ``config[cfg_key]["model"]``. The current model is listed first so the cursor
  461. lands on it; a saved model belonging to another provider (shared config key) or a drifted catalog
  462. default never indexes the catalog. Safe when stdin is not a TTY — curses_radiolist keeps the current
  463. selection."""
  464. from hermes_cli.tools_config import _cfg_section, _prompt_choice
  465. if not catalog:
  466. return
  467. cur_cfg = _cfg_section(config, cfg_key)
  468. current_model = cur_cfg.get("model") or default_model
  469. if current_model not in catalog:
  470. current_model = default_model if default_model in catalog else next(iter(catalog))
  471. model_ids = list(catalog.keys())
  472. ordered = [current_model] + [m for m in model_ids if m != current_model]
  473. widths = {
  474. "model": max(len(m) for m in model_ids),
  475. "speed": max((len(catalog[m].get("speed", "")) for m in model_ids), default=6),
  476. "strengths": max((len(catalog[m].get("strengths", "")) for m in model_ids), default=0)}
  477. print()
  478. header = (f" {'Model':<{widths['model']}} {'Speed':<{widths['speed']}} "
  479. f"{'Strengths':<{widths['strengths']}} Price")
  480. print(color(header, Colors.CYAN))
  481. rows = []
  482. for mid in ordered:
  483. meta = catalog[mid]
  484. row = (f"{row_indent}{mid:<{widths['model']}} {meta.get('speed', ''):<{widths['speed']}} "
  485. f"{meta.get('strengths', ''):<{widths['strengths']}} {meta.get('price', '')}")
  486. if mid == current_model:
  487. row += " ← currently in use"
  488. rows.append(row)
  489. idx = _prompt_choice(f" Choose {display} model:", rows, default=0)
  490. chosen = ordered[idx]
  491. cur_cfg["model"] = chosen
  492. _print_success(f" Model set to: {chosen}")
  493. def _configure_imagegen_model(backend_name: str, config: dict) -> None:
  494. """Prompt for a model of an in-tree imagegen backend (``IMAGEGEN_BACKENDS``)."""
  495. backend = IMAGEGEN_BACKENDS.get(backend_name)
  496. if not backend:
  497. return
  498. catalog, default_model = backend["catalog_fn"](config)
  499. _pick_model_from_catalog(catalog, default_model, backend["config_key"], backend["display"], config)
  500. def _configure_gen_model_for_plugin(section: str, plugin_name: str, config: dict) -> None:
  501. """Prompt for a model from a plugin-registered image/video gen catalog (video rows keep their historical
  502. two-space indent)."""
  503. catalog_fn = _plugin_image_gen_catalog if section == "image_gen" else _plugin_video_gen_catalog
  504. catalog, default_model = catalog_fn(plugin_name)
  505. _pick_model_from_catalog(catalog, default_model, section, plugin_name, config,
  506. row_indent="" if section == "image_gen" else " ")
  507. _configure_imagegen_model_for_plugin = partial(_configure_gen_model_for_plugin, "image_gen")
  508. _configure_videogen_model_for_plugin = partial(_configure_gen_model_for_plugin, "video_gen")
  509. def _configure_xai_imagine_storage(section_name: str, config: dict) -> None:
  510. """Prompt for xAI Imagine stored public URL behavior."""
  511. from hermes_cli.tools_config import _cfg_section, _prompt_choice
  512. storage_cfg = _cfg_section(_cfg_section(_cfg_section(config, section_name), "xai"), "storage")
  513. _print_warning(
  514. " xAI Imagine can store generated media and create reusable public URLs. "
  515. "xAI may bill for stored files and public URL hosting.")
  516. choices = ["Enable public URLs without automatic expiry (recommended)", "Disable stored public URLs",
  517. "Enable public URLs for 2 days"]
  518. idx = _prompt_choice(" Stored public URLs:", choices, default=0)
  519. if idx == 1:
  520. storage_cfg["enabled"] = False
  521. _print_success(" xAI stored public URLs disabled")
  522. return
  523. storage_cfg["enabled"] = True
  524. storage_cfg["public_url"] = True
  525. storage_cfg["expires_after"] = 2 * 24 * 60 * 60 if idx == 2 else None
  526. _print_success(" xAI stored public URLs enabled for 2 days" if idx == 2
  527. else " xAI stored public URLs enabled without automatic expiry")
  528. def _select_into(config: dict, section: str, key: str, vendor, managed) -> dict:
  529. """Write ``config[section][key] = vendor`` (``nous`` for a managed pick) and drop any legacy ``use_gateway``
  530. key so the old read-time shim cannot override the new choice. Returns the section dict."""
  531. from hermes_cli.tools_config import _cfg_section
  532. cfg = _cfg_section(config, section)
  533. cfg[key] = NOUS_MANAGED_PROVIDER if managed else vendor
  534. cfg.pop("use_gateway", None)
  535. return cfg
  536. def _select_plugin_gen_provider(section: str, plugin_name: str, config: dict, *, use_gateway: bool = False) -> None:
  537. """Persist a plugin-backed image/video gen provider selection (``nous`` for a Nous-managed pick, else the
  538. plugin name) and run its model picker."""
  539. cfg = _select_into(config, section, "provider", plugin_name, use_gateway)
  540. _print_success(f" {section}.provider set to: {cfg['provider']}")
  541. _configure_gen_model_for_plugin(section, plugin_name, config)
  542. if plugin_name == "xai":
  543. _configure_xai_imagine_storage(section, config)
  544. _select_plugin_image_gen_provider = partial(_select_plugin_gen_provider, "image_gen")
  545. _select_plugin_video_gen_provider = partial(_select_plugin_gen_provider, "video_gen")
  546. def _configure_stt_model(stt_provider: str, config: dict) -> None:
  547. """Prompt for the STT model after a provider pick (static catalog, or DeepInfra's live one)."""
  548. from hermes_cli.tools_config import _cfg_section, _prompt_choice
  549. catalog = STT_MODEL_CATALOG.get(stt_provider)
  550. if catalog is None and stt_provider == "deepinfra":
  551. from hermes_cli.models import deepinfra_model_ids
  552. catalog = deepinfra_model_ids("stt")
  553. if not catalog:
  554. return
  555. prov_cfg = _cfg_section(_cfg_section(config, "stt"), stt_provider)
  556. model_key = STT_MODEL_CONFIG_KEY.get(stt_provider, "model")
  557. current = str(prov_cfg.get(model_key) or "").strip()
  558. ordered = list(catalog)
  559. chosen = ordered[_prompt_choice(" Select STT model:", ordered, ordered.index(current) if current in ordered else 0)]
  560. prov_cfg[model_key] = chosen
  561. _print_success(f" STT model set to: {chosen}")
  562. # Provider-row marker key -> config section it selects into.
  563. _PROVIDER_MARKER_SECTIONS = {
  564. "tts_provider": "tts", "stt_provider": "stt", "browser_provider": "browser", "web_backend": "web",
  565. "image_gen_plugin_name": "image_gen", "imagegen_backend": "image_gen", "video_gen_plugin_name": "video_gen",
  566. }
  567. def _write_provider_config(provider: dict, config: dict, *, managed_feature) -> None:
  568. """Persist the provider/backend config keys for a selected provider.
  569. Pure, non-interactive core of :func:`_configure_provider` (no env prompts, post-setup hooks, Nous
  570. auth gating or model pickers) shared by the CLI and the GUI ``PUT .../provider`` endpoint. Each pick
  571. writes exactly ONE provider string per category (``nous`` for managed rows) and removes any legacy
  572. ``use_gateway`` key so the read-time shim cannot override the new choice."""
  573. from hermes_cli.tools_config import TOOL_CATEGORIES
  574. for marker, section_key in (("tts_provider", "tts"), ("stt_provider", "stt")):
  575. if provider.get(marker):
  576. _select_into(config, section_key, "provider", provider[marker], managed_feature)
  577. if "browser_provider" in provider:
  578. bp = provider["browser_provider"]
  579. if bp or managed_feature:
  580. _select_into(config, "browser", "cloud_provider", bp, managed_feature)
  581. else:
  582. config.setdefault("browser", {}).pop("use_gateway", None)
  583. # Local engine rows ("Local Browser" resets to auto, "Lightpanda" sets lightpanda).
  584. if provider.get("browser_engine"):
  585. config.setdefault("browser", {})["engine"] = provider["browser_engine"]
  586. if provider.get("web_backend"):
  587. web_cfg = _select_into(config, "web", "backend", provider["web_backend"], managed_feature)
  588. if managed_feature:
  589. # A whole-toolset managed pick governs both capabilities: per-capability pins resolve FIRST,
  590. # so a leftover one would keep outranking the "nous" selection just written.
  591. web_cfg.pop("search_backend", None)
  592. web_cfg.pop("extract_backend", None)
  593. tier = provider.get("web_tier")
  594. tiers = web_cfg.setdefault("provider_tier", {}) if tier else web_cfg.get("provider_tier")
  595. if isinstance(tiers, dict):
  596. if tier:
  597. tiers[provider["web_backend"]] = tier
  598. else:
  599. tiers.pop(provider["web_backend"], None)
  600. if provider.get("computer_use_backend"):
  601. config.setdefault("computer_use", {})["backend"] = provider["computer_use_backend"]
  602. if managed_feature and managed_feature not in {"web", "tts", "stt", "browser"}:
  603. # Managed rows without a marker above (image_gen/video_gen "Nous Subscription" rows carry only
  604. # managed_nous_feature) still persist the "nous" selection.
  605. section = config.setdefault(managed_feature, {})
  606. if isinstance(section, dict):
  607. section["provider"] = NOUS_MANAGED_PROVIDER
  608. section.pop("use_gateway", None)
  609. elif not managed_feature:
  610. # Non-gateway pick — clear any stale legacy use_gateway key on the category. Resolve the category from
  611. # the row's own markers first (plugin-injected rows are NOT in TOOL_CATEGORIES' hardcoded lists), then
  612. # fall back to the category-membership walk.
  613. sections = [section_key for marker, section_key in _PROVIDER_MARKER_SECTIONS.items() if marker in provider]
  614. if not sections:
  615. sections = [cat_key for cat_key, cat in TOOL_CATEGORIES.items() if provider in cat.get("providers", [])][:1]
  616. for section_key in sections:
  617. if isinstance(config.get(section_key), dict):
  618. config[section_key].pop("use_gateway", None)
  619. def apply_provider_selection(ts_key: str, provider_name: str, config: dict) -> None:
  620. """Non-interactively persist a provider selection for a toolset (config keys only — API keys, post-setup
  621. hooks, auth gating and model pickers are separate GUI endpoints). ``provider_name`` is resolved among
  622. :func:`_visible_providers` rows; raises ``KeyError`` for an unknown toolset or provider."""
  623. from hermes_cli.tools_config import TOOL_CATEGORIES
  624. cat = TOOL_CATEGORIES.get(ts_key)
  625. if cat is None:
  626. raise KeyError(f"Toolset has no configurable category: {ts_key}")
  627. providers = _visible_providers(cat, config, force_fresh=True)
  628. provider = next((p for p in providers if p.get("name") == provider_name), None)
  629. if provider is None:
  630. raise KeyError(f"Unknown provider {provider_name!r} for toolset {ts_key!r}")
  631. managed_feature = provider.get("managed_nous_feature")
  632. _write_provider_config(provider, config, managed_feature=managed_feature)
  633. # Plugin image/video gen backends record the provider name in their own section (model choice is a separate
  634. # GUI flow); managed picks store "nous". The in-tree FAL BYOK row always persists an explicit
  635. # ``image_gen.provider: fal`` so a deliberate pick is distinguishable from a never-configured install.
  636. selections = [
  637. ("image_gen", provider.get("image_gen_plugin_name")),
  638. ("video_gen", provider.get("video_gen_plugin_name")),
  639. ("image_gen", "fal" if provider.get("imagegen_backend") and not managed_feature else None)]
  640. for section_key, vendor in selections:
  641. if vendor:
  642. _select_into(config, section_key, "provider", vendor, managed_feature)
  643. def _nous_provider_gate(provider: dict, config: dict, managed_feature, *, force_fresh: bool) -> bool:
  644. """Return False (after printing why) when a Nous-gated row cannot be selected.
  645. Managed Tool Gateway rows are always listed but only *activate* with paid Nous Portal access —
  646. selecting one runs an inline Portal login (auth + entitlement only, no inference-provider switch).
  647. Pure pre-auth UX rows (``requires_nous_auth`` without a managed feature) keep the older logged-in +
  648. entitled gate."""
  649. from hermes_cli.tools_config import get_nous_subscription_features
  650. if managed_feature:
  651. from hermes_cli.nous_subscription import ensure_nous_portal_access
  652. if not ensure_nous_portal_access(
  653. capability=f"{provider.get('name', 'the Nous Tool Gateway')}",
  654. coverage_category=MANAGED_FEATURE_COVERAGE_CATEGORY.get(managed_feature)):
  655. _print_warning(" Not enabled — Nous Portal access is required for this backend.")
  656. return False
  657. return True
  658. if provider.get("requires_nous_auth"):
  659. features = get_nous_subscription_features(config, force_fresh=force_fresh)
  660. entitled = bool(features.account_info and features.account_info.paid_service_access is True)
  661. if not features.nous_auth_present or not entitled:
  662. message = format_nous_portal_entitlement_message(
  663. features.account_info, capability=f"{provider.get('name', 'Nous Subscription')}")
  664. _print_warning(f" {message or 'Nous Subscription is only available after logging into Nous Portal.'}")
  665. return False
  666. return True
  667. def _finish_provider_selection(provider: dict, config: dict, managed_feature) -> None:
  668. """Model pickers that follow a provider pick: plugin image/video gen, in-tree FAL, STT."""
  669. for section in ("image_gen", "video_gen"):
  670. plugin_name = provider.get(f"{section}_plugin_name")
  671. if plugin_name:
  672. _select_plugin_gen_provider(section, plugin_name, config, use_gateway=bool(managed_feature))
  673. return
  674. backend = provider.get("imagegen_backend")
  675. if backend:
  676. _configure_imagegen_model(backend, config)
  677. # "nous" for the managed row (the picked model id chooses the FAL / Krea / Portal gateway at run time),
  678. # "fal" for BYOK, drop legacy use_gateway — never clobber a managed pick back onto direct keys.
  679. _select_into(config, "image_gen", "provider", "fal", managed_feature)
  680. # STT rows prompt for a model after the pick (skipped for managed rows — the gateway pins it).
  681. if provider.get("stt_provider") and not managed_feature:
  682. _configure_stt_model(provider["stt_provider"], config)
  683. def _print_provider_selection(provider: dict, managed_feature, *, reconfigure: bool) -> None:
  684. """Status lines announcing which backend/provider keys a pick writes."""
  685. if reconfigure and provider.get("tts_provider"):
  686. _print_success(f" TTS provider set to: {provider['tts_provider']}")
  687. if provider.get("stt_provider"):
  688. _print_success(f" STT provider set to: {provider['stt_provider']}")
  689. if "browser_provider" in provider:
  690. bp = provider["browser_provider"]
  691. if reconfigure and managed_feature:
  692. _print_success(f" Browser cloud provider set to: {bp or 'nous'}")
  693. elif bp == "local":
  694. _print_success(" Browser set to local mode")
  695. elif bp:
  696. _print_success(f" Browser cloud provider set to: {bp}")
  697. if provider.get("browser_engine") and provider["browser_engine"] != "auto":
  698. _print_success(f" Browser engine set to: {provider['browser_engine']}")
  699. if provider.get("web_backend"):
  700. tier = f" ({provider['web_tier']} tier)" if reconfigure and provider.get("web_tier") else ""
  701. backend = NOUS_MANAGED_PROVIDER if managed_feature else provider["web_backend"]
  702. _print_success(f" Web backend set to: {backend}{tier}")
  703. if reconfigure and provider.get("computer_use_backend"):
  704. _print_success(f" Computer Use backend set to: {provider['computer_use_backend']}")
  705. def _show_portal_hint(provider: dict, config: dict, managed_feature, force_fresh: bool) -> bool:
  706. """True when a BYOK row shares its category with a Nous-managed sibling and the user is not authed to
  707. Nous — a single dim hint tells them the key is avoidable via a Portal subscription."""
  708. from hermes_cli.tools_config import TOOL_CATEGORIES, get_nous_subscription_features
  709. if managed_feature or provider.get("requires_nous_auth"):
  710. return False
  711. try:
  712. for _cat in TOOL_CATEGORIES.values():
  713. _providers = _cat.get("providers", [])
  714. if provider in _providers and any(sib.get("managed_nous_feature") for sib in _providers):
  715. return not get_nous_subscription_features(config, force_fresh=force_fresh).nous_auth_present
  716. except Exception:
  717. pass
  718. return False
  719. def _prompt_secret(
  720. key: str, label: str, url: str, default_val: str, *, reconfigure: bool, url_label: str, strip: bool = False,
  721. ) -> bool:
  722. """One env-var prompt; True unless the new-enable flow skipped the key.
  723. Reconfigure mode shows the current value and re-prompts ("Enter to keep current"); the new-enable
  724. flow prompts with ``default_val`` visible when one exists, else as a password, and ``strip`` decides
  725. whether whitespace is trimmed (and whitespace-only counts as skipped)."""
  726. existing = get_env_value(key) if reconfigure else ""
  727. if existing:
  728. _print_info(f" {key}: configured ({existing[:8]}...)")
  729. if url:
  730. _print_info(f" {url_label}: {url}")
  731. if reconfigure:
  732. value = (_prompt(f" {label} (Enter to keep current)", password=not default_val) or "").strip()
  733. if value:
  734. save_env_value(key, value)
  735. _print_success(" Updated")
  736. else:
  737. _print_info(" Kept current")
  738. return True
  739. value = _prompt(f" {label}", default_val) if default_val else _prompt(f" {label}", password=True)
  740. if strip:
  741. value = (value or "").strip()
  742. if value:
  743. save_env_value(key, value)
  744. _print_success(" Saved")
  745. return True
  746. _print_warning(" Skipped")
  747. return False
  748. def _prompt_env_vars(env_vars: list, *, reconfigure: bool) -> bool:
  749. """Prompt for a provider's env vars; True when every key ended up configured.
  750. Reconfigure mode re-prompts every key and always returns True; the new-enable flow keeps already-set
  751. keys without asking and reports False on any skipped key."""
  752. all_configured = True
  753. for var in env_vars:
  754. if not reconfigure and get_env_value(var["key"]):
  755. _print_success(f" {var['key']}: already configured")
  756. continue
  757. ok = _prompt_secret(var["key"], var.get("prompt", var["key"]), var.get("url", ""), var.get("default", ""),
  758. reconfigure=reconfigure, url_label="Get yours at")
  759. all_configured = all_configured and ok
  760. return all_configured
  761. def _configure_provider(provider: dict, config: dict, *, force_fresh: bool = True, reconfigure: bool = False):
  762. """Configure a single provider - prompt for API keys and set config.
  763. ``reconfigure=False`` (new-enable): already-set keys are kept without asking and the post-setup hook
  764. only runs when every key was provided. ``reconfigure=True`` re-prompts every key and always runs the
  765. hook."""
  766. from hermes_cli.tools_config import _run_post_setup
  767. env_vars = provider.get("env_vars", [])
  768. managed_feature = provider.get("managed_nous_feature")
  769. if not _nous_provider_gate(provider, config, managed_feature, force_fresh=force_fresh):
  770. return
  771. _print_provider_selection(provider, managed_feature, reconfigure=reconfigure)
  772. # Shared with the GUI provider-select endpoint (apply_provider_selection): one source of truth for config writes.
  773. _write_provider_config(provider, config, managed_feature=managed_feature)
  774. if not env_vars:
  775. if provider.get("post_setup"):
  776. _run_post_setup(provider["post_setup"])
  777. _print_success(f" {provider['name']} - no configuration needed!")
  778. if managed_feature:
  779. _print_info(" Requests for this tool will be billed to your Nous subscription.")
  780. _finish_provider_selection(provider, config, managed_feature)
  781. return
  782. if not reconfigure and _show_portal_hint(provider, config, managed_feature, force_fresh):
  783. _print_info(" Available through Nous Portal subscription.")
  784. all_configured = _prompt_env_vars(env_vars, reconfigure=reconfigure)
  785. if provider.get("post_setup") and all_configured:
  786. _run_post_setup(provider["post_setup"])
  787. if all_configured:
  788. if not reconfigure:
  789. _print_success(f" {provider['name']} configured!")
  790. _finish_provider_selection(provider, config, managed_feature)
  791. def _reconfigure_provider(provider: dict, config: dict, *, force_fresh: bool = True):
  792. """Reconfigure a provider - update API keys."""
  793. _configure_provider(provider, config, force_fresh=force_fresh, reconfigure=True)
  794. def _configure_vision_backend() -> None:
  795. """Interactive vision-backend configuration (``auxiliary.vision.{provider,model,base_url}``).
  796. Offers any authenticated provider + model (same surface as ``hermes model``) or a custom endpoint
  797. rather than forcing OpenRouter. "Auto" leaves the keys empty so the resolver uses the main-model
  798. fallback chain."""
  799. from hermes_cli.tools_config import _cfg_section, _prompt_choice
  800. print()
  801. print(color(" Vision / Image Analysis needs a multimodal model.", Colors.YELLOW))
  802. print(color(" Pick any provider + model (like /model), or let it auto-detect.", Colors.DIM))
  803. choices = [
  804. "Auto — use your main model / aggregator fallback (recommended)",
  805. "Pick a provider and model",
  806. "Custom OpenAI-compatible endpoint — base URL, API key, model",
  807. "Skip"]
  808. idx = _prompt_choice(" Configure vision backend", choices, 0)
  809. config = load_config()
  810. vision_cfg = _cfg_section(_cfg_section(config, "auxiliary"), "vision")
  811. if idx == 0:
  812. # Auto: clear any pinned override so the resolver auto-detects.
  813. for key in ("provider", "model", "base_url", "api_key", "api_mode"):
  814. vision_cfg.pop(key, None)
  815. save_config(config)
  816. _print_success(" Vision set to auto (main model / aggregator fallback)")
  817. elif idx == 1:
  818. _configure_vision_provider_model(config, vision_cfg)
  819. elif idx == 2:
  820. base_url = _prompt(" Base URL (blank for OpenAI)").strip() or "https://api.openai.com/v1"
  821. is_native_openai = base_url_hostname(base_url) == "api.openai.com"
  822. key_label = " OPENAI_API_KEY" if is_native_openai else " API key"
  823. api_key = _prompt(key_label, password=True)
  824. if not (api_key and api_key.strip()):
  825. _print_warning(" Skipped")
  826. return
  827. default_model = "gpt-4o-mini" if is_native_openai else ""
  828. model = _prompt(f" Vision model{f' (blank for {default_model})' if default_model else ''}").strip() or default_model
  829. save_env_value("OPENAI_API_KEY", api_key.strip())
  830. # Only base_url + model go to config.yaml; the key is the secret. Pin provider="custom" so the resolver
  831. # routes through this endpoint — at the "auto" default _resolve_task_provider_model ignores base_url
  832. # unless paired with a config api_key.
  833. vision_cfg["provider"] = "custom"
  834. vision_cfg["base_url"] = base_url
  835. if model:
  836. vision_cfg["model"] = model
  837. else:
  838. vision_cfg.pop("model", None)
  839. save_config(config)
  840. _print_success(f" Vision set to custom endpoint{f' ({model})' if model else ''}")
  841. else:
  842. _print_info(" Skipped vision configuration")
  843. def _configure_vision_provider_model(config: dict, vision_cfg: dict) -> None:
  844. """Provider + model picker for vision, mirroring the ``/model`` surface.
  845. Rows come from ``build_aux_picker_rows()`` so this lists exactly what the ``hermes model`` aux-task
  846. picker lists, including user-defined ``providers:`` / ``custom_providers:`` endpoints. Persists
  847. ``auxiliary.vision.provider`` + ``.model``."""
  848. from hermes_cli.tools_config import _prompt_choice
  849. try:
  850. from hermes_cli.inventory import build_aux_picker_rows, format_aux_picker_entries
  851. except Exception as exc: # pragma: no cover - import guard
  852. _print_warning(f" Could not load provider list: {exc}")
  853. return
  854. current_provider = str(vision_cfg.get("provider") or "").strip()
  855. current_model = str(vision_cfg.get("model") or "").strip()
  856. current_base_url = str(vision_cfg.get("base_url") or "").strip()
  857. try:
  858. providers = build_aux_picker_rows(current_provider=current_provider, current_model=current_model,
  859. current_base_url=current_base_url, max_models=40)
  860. except Exception as exc:
  861. _print_warning(f" Could not detect providers: {exc}")
  862. providers = []
  863. if not providers:
  864. _print_warning(" No authenticated providers found. Configure a provider first "
  865. "with `hermes model`, then re-run this.")
  866. return
  867. provider_labels = [label for _slug, label, _models in format_aux_picker_entries(
  868. providers, current_provider=current_provider, current_base_url=current_base_url)] + ["Cancel"]
  869. pidx = _prompt_choice(" Choose vision provider:", provider_labels, 0)
  870. if pidx >= len(providers):
  871. _print_info(" Cancelled")
  872. return
  873. chosen = providers[pidx]
  874. slug = chosen.get("slug")
  875. models = list(chosen.get("models", []))
  876. midx = _prompt_choice(f" Choose vision model for {chosen.get('name') or slug}:", models + ["Type a custom model id…"], 0)
  877. if midx < len(models):
  878. model = models[midx]
  879. else:
  880. model = _prompt(" Model id").strip()
  881. if not model:
  882. _print_warning(" No model entered — cancelled")
  883. return
  884. vision_cfg["provider"] = slug
  885. vision_cfg["model"] = model
  886. # A provider selection supersedes any prior custom endpoint override.
  887. vision_cfg.pop("base_url", None)
  888. vision_cfg.pop("api_key", None)
  889. save_config(config)
  890. _print_success(f" Vision set to {slug} / {model}")
  891. def _configure_simple_requirements(ts_key: str, *, reconfigure: bool = False):
  892. """Fallback for toolsets that just need env vars (no provider selection).
  893. Vision has its own provider/model picker — run it directly so neither flow falls back to the generic
  894. single-key prompt (which would re-ask for OPENROUTER_API_KEY)."""
  895. from hermes_cli.tools_config import TOOLSET_ENV_REQUIREMENTS, _toolset_has_keys, _toolset_label
  896. if ts_key == "vision":
  897. if reconfigure or not _toolset_has_keys("vision"):
  898. _configure_vision_backend()
  899. return
  900. requirements = TOOLSET_ENV_REQUIREMENTS.get(ts_key, [])
  901. if not reconfigure:
  902. requirements = [(var, url) for var, url in requirements if not get_env_value(var)]
  903. if not requirements:
  904. return
  905. ts_label = _toolset_label(ts_key)
  906. print()
  907. if reconfigure:
  908. print(color(f" {ts_label}:", Colors.CYAN))
  909. else:
  910. print(color(f" {ts_label} requires configuration:", Colors.YELLOW))
  911. for var, url in requirements:
  912. _prompt_secret(var, var, url, "", reconfigure=reconfigure, url_label="Get key at", strip=True)