tools_config.py 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  1. """Unified tool configuration for Hermes Agent."""
  2. import json as _json
  3. import logging
  4. import os
  5. from pathlib import Path
  6. from typing import Dict, List, NoReturn, Optional, Set
  7. from hermes_cli.cli_output import print_info as _print_info
  8. from hermes_cli.colors import Colors, color
  9. from hermes_cli.config import cfg_get, load_config, save_config, get_env_value
  10. from hermes_cli.nous_subscription import (
  11. NousSubscriptionFeatures, apply_nous_managed_defaults, get_nous_subscription_features)
  12. from hermes_cli.platforms import PLATFORMS as _PLATFORMS_REGISTRY
  13. from hermes_cli.toolset_scope import (
  14. _TOOLSET_PLATFORM_RESTRICTIONS, toolset_allowed_for_platform as _toolset_allowed_for_platform)
  15. from hermes_cli.toolset_validation import parse_platform_toolsets_value
  16. # Re-exports: keep ``hermes_cli.tools_config.X`` callers and test patch targets resolving.
  17. from hermes_cli.tools_config_cua import (
  18. _post_setup_no_window_flags, _cua_driver_cmd, _cua_version_summary, _resolved_cua_driver_cmd, _cua_driver_env,
  19. _cua_driver_contract_status, _cua_driver_install_ready)
  20. from hermes_cli.tools_config_post_setup import (
  21. _ensure_browser_use_cli, _run_post_setup, valid_post_setup_keys, run_post_setup_command, _POST_SETUP_INSTALLED,
  22. _post_setup_already_installed, _module_installed, _POST_SETUP_READY)
  23. from hermes_cli.tools_config_providers import (
  24. _plugin_image_gen_providers, _plugin_video_gen_providers, _plugin_web_search_providers, _plugin_browser_providers,
  25. _plugin_tts_providers, web_provider_capabilities, _visible_providers, provider_readiness_status,
  26. _toolset_needs_configuration_prompt, _configure_tool_category, _web_tier_matches, _is_provider_active,
  27. _detect_active_provider_index, IMAGEGEN_BACKENDS, _plugin_image_gen_catalog, _plugin_video_gen_catalog,
  28. _configure_imagegen_model, _configure_imagegen_model_for_plugin, _configure_videogen_model_for_plugin,
  29. _select_plugin_image_gen_provider, _select_plugin_video_gen_provider, STT_MODEL_CATALOG, _configure_stt_model,
  30. _write_provider_config, apply_provider_selection, _configure_provider, _reconfigure_provider,
  31. _configure_vision_backend, _configure_vision_provider_model, _configure_simple_requirements)
  32. from hermes_cli.tools_config_mcp import (
  33. _configure_mcp_tools_interactive, _apply_toolset_change, _apply_mcp_change, tools_disable_enable_command)
  34. def _pip_install(
  35. args: list[str], *, timeout: int = 300, capture_output: bool = True
  36. ) -> NoReturn:
  37. # Shim to suppress old updater work until relaunch, not install or report success.
  38. from hermes_cli._old_updater import stop_for_relaunch
  39. stop_for_relaunch()
  40. logger = logging.getLogger(__name__)
  41. def install_cua_driver(*args, **kwargs) -> NoReturn:
  42. # A running pre-PM updater can still import the vendor installer here.
  43. # Stop it before any old retry or completion branch can run.
  44. from hermes_cli._old_updater import stop_for_relaunch
  45. stop_for_relaunch()
  46. # Platforms already warned about an all-invalid platform_toolsets list (warn once, not per resolution).
  47. _warned_invalid_platform_toolsets: set[str] = set()
  48. PROJECT_ROOT = Path(__file__).parent.parent.resolve()
  49. # Platform display config derived from the canonical registry (dict-of-dicts for ``PLATFORMS[key]["label"]``).
  50. PLATFORMS = {k: {"label": info.label, "default_toolset": info.default_toolset} for k, info in _PLATFORMS_REGISTRY.items()}
  51. # --- Toolset Registry ---
  52. # Toolsets shown in the configurator: (toolset key in toolsets.py TOOLSETS, label, description).
  53. CONFIGURABLE_TOOLSETS = [
  54. ("web", "🔍 Web Search & Scraping", "web_search, web_extract"),
  55. ("browser", "🌐 Browser Automation", "navigate, click, type, scroll"),
  56. ("terminal", "💻 Terminal & Processes", "terminal, process"),
  57. ("file", "📁 File Operations", "read, write, patch, search"),
  58. ("code_execution", "⚡ Code Execution", "execute_code"),
  59. ("vision", "👁️ Vision / Image Analysis", "vision_analyze"),
  60. ("video", "🎬 Video Analysis", "video_analyze (requires video-capable model)"),
  61. ("image_gen", "🎨 Image Generation", "image_generate"),
  62. ("video_gen", "🎬 Video Generation", "video_generate (text/image/reference)"),
  63. ("x_search", "🐦 X (Twitter) Search", "x_search (requires xAI OAuth or XAI_API_KEY)"),
  64. ("tts", "🔊 Text-to-Speech", "text_to_speech"),
  65. ("stt", "🎙️ Speech-to-Text", "voice transcription (gateway voice messages + voice mode)"),
  66. ("skills", "📚 Skills", "list, view, manage"),
  67. ("todo", "📋 Task Planning", "todo_list"),
  68. ("kanban", "📌 Kanban", "opt-in task board tools for this platform"),
  69. ("memory", "💾 Memory", "persistent memory across sessions"),
  70. ("context_engine", "🧩 Context Engine", "runtime tools from the active context engine"),
  71. ("session_search", "🔎 Session Search", "search past conversations"),
  72. ("connections", "🔌 Connections", "remote connector tools and account authorization"),
  73. ("clarify", "❓ Clarifying Questions", "clarify"),
  74. ("delegation", "👥 Task Delegation", "delegate_task"),
  75. ("cronjob", "⏰ Cron Jobs", "create/list/update/pause/resume/run, with optional attached skills"),
  76. ("discord", "💬 Discord (read/participate)", "fetch messages, search members, create thread"),
  77. ("discord_admin", "🛡️ Discord Server Admin", "list channels/roles, pin, assign roles"),
  78. ("yuanbao", "🤖 Yuanbao", "group info, member queries, DM"),
  79. ("computer_use", "🖱️ Computer Use (macOS/Windows/Linux)", "background desktop control via cua-driver"),
  80. ]
  81. def gui_toolset_label(label: str) -> str:
  82. """Strip the leading ``<emoji>`` from a toolset title for GUI surfaces (plugins prefix ``🔌``).
  83. CLI/TUI keeps the raw label — only HTTP APIs call this."""
  84. text = (label or "").strip()
  85. parts = text.split(None, 1)
  86. if len(parts) == 2 and not any(ch.isascii() and ch.isalnum() for ch in parts[0]):
  87. return parts[1].strip()
  88. return text
  89. # OFF by default for new installs (still in _HERMES_CORE_TOOLS; the checklist won't pre-select them). x_search
  90. # auto-enables when xAI creds exist; its check_fn still gates the schema. ``spotify`` and ``a2a`` are plugin
  91. # toolsets (catalog / bundled plugin) that stay opt-in once installed.
  92. _DEFAULT_OFF_TOOLSETS = {"spotify", "discord", "discord_admin", "video", "video_gen", "x_search", "a2a", "kanban"}
  93. # Config-only capabilities: provider setup in `hermes tools` (TOOL_CATEGORIES) but not model toolsets — zero
  94. # schemas, own switch (``stt.enabled``), never in ``platform_toolsets`` or the per-platform checklist.
  95. _CONFIG_ONLY_TOOLSETS = {"stt"}
  96. def _xai_credentials_present() -> bool:
  97. """Cheap offline check for xAI credentials (auth store + env only); the runtime ``check_fn`` still gates
  98. schema registration if creds expire. Also used by ``provider_readiness_status`` for ``xai_grok`` rows."""
  99. try:
  100. from hermes_cli.auth import _read_xai_oauth_tokens
  101. _read_xai_oauth_tokens()
  102. return True
  103. except Exception:
  104. pass
  105. if str(get_env_value("XAI_API_KEY") or "").strip():
  106. return True
  107. try:
  108. from agent.secret_scope import get_secret
  109. except ImportError: # pragma: no cover — secret_scope is in-repo
  110. get_secret = os.environ.get
  111. return bool(str(get_secret("XAI_API_KEY") or "").strip())
  112. def _toolset_configuration_platform(ts_key: str, default: str = "cli") -> str:
  113. """Platform a platform-less configuration UI should target: a toolset restricted away from ``default``
  114. must be configured on a supported platform, else the save helper drops it and the UI reports a no-op."""
  115. allowed = _TOOLSET_PLATFORM_RESTRICTIONS.get(ts_key)
  116. return default if not allowed or default in allowed else min(allowed)
  117. # A classic CLI on a gateway session reads plugin toolsets from the gateway instead of loading plugins
  118. # (installed by ``_ensure_gateway_session``): ``() -> ([(key, label, description)], {portable MCP})`` or
  119. # None (off the gateway: this process's own registry).
  120. _gateway_plugin_toolsets = None
  121. def _projected_plugin_toolsets():
  122. provider = _gateway_plugin_toolsets
  123. return provider() if provider is not None else None
  124. def _get_effective_configurable_toolsets():
  125. """CONFIGURABLE_TOOLSETS + plugin toolsets (appended after built-ins; a plugin key already built-in is skipped)."""
  126. result = list(CONFIGURABLE_TOOLSETS)
  127. seen = {ts_key for ts_key, _, _ in result}
  128. try:
  129. projected = _projected_plugin_toolsets()
  130. if projected is None:
  131. from hermes_cli.plugins import discover_plugins, get_plugin_toolsets
  132. discover_plugins() # idempotent — ensures plugins are loaded
  133. for entry in projected[0] if projected is not None else get_plugin_toolsets():
  134. if entry[0] not in seen:
  135. seen.add(entry[0])
  136. result.append(entry)
  137. except Exception:
  138. pass
  139. return result
  140. def _get_plugin_toolset_keys() -> set:
  141. """Return the set of toolset keys provided by plugins."""
  142. try:
  143. if (projected := _projected_plugin_toolsets()) is not None:
  144. return {key for key, _, _ in projected[0]}
  145. # Non-blocking on CLI startup: while background discovery is still importing, serve last
  146. # launch's persisted key set instead of joining the discovery thread.
  147. from hermes_cli.plugins import get_plugin_toolset_keys_nowait
  148. return get_plugin_toolset_keys_nowait()
  149. except Exception:
  150. return set()
  151. def _checklist_toolset_keys(platform: str) -> set[str]:
  152. """Toolset keys the ``hermes tools`` checklist offers for ``platform`` (mirrors ``_prompt_toolset_checklist``);
  153. read-time-resolved toolsets (recovered composites, MCP names) are NOT here."""
  154. return {
  155. ts_key for ts_key, _, _ in _get_effective_configurable_toolsets()
  156. if _toolset_allowed_for_platform(ts_key, platform) and ts_key not in _CONFIG_ONLY_TOOLSETS}
  157. def _platform_default_toolset(platform: str) -> str:
  158. """Composite toolset a platform falls back to (plugin platforms derive ``hermes-<platform>``)."""
  159. return PLATFORMS[platform]["default_toolset"] if platform in PLATFORMS else f"hermes-{platform}"
  160. def _cfg_section(config: dict, key: str) -> dict:
  161. """Return ``config[key]`` as a dict, replacing a missing or non-dict value with ``{}``."""
  162. section = config.setdefault(key, {})
  163. if not isinstance(section, dict):
  164. section = {}
  165. config[key] = section
  166. return section
  167. def _is_configurable(ts_key: str) -> bool:
  168. """True when the toolset has provider options or simple env-var requirements to prompt for."""
  169. return bool(TOOL_CATEGORIES.get(ts_key) or TOOLSET_ENV_REQUIREMENTS.get(ts_key))
  170. def _toolset_label(ts_key: str) -> str:
  171. """Display label for a toolset key (built-in or plugin), falling back to the key itself."""
  172. return next((l for k, l, _ in _get_effective_configurable_toolsets() if k == ts_key), ts_key)
  173. # --- Tool Categories: toolset key -> provider options shown when newly enabled. Toolsets not in this map
  174. # either need no config or use the TOOLSET_ENV_REQUIREMENTS fallback.
  175. def _key(key: str, prompt: str, url: str = "", **extra) -> dict:
  176. """One ``env_vars`` entry for a provider row (key order matters for the GUI JSON)."""
  177. return {"key": key, "prompt": prompt, **extra, **({"url": url} if url else {})}
  178. def _row(name: str, badge: str = "", tag: str = "", env_vars: list = (), **markers) -> dict:
  179. """One TOOL_CATEGORIES provider row; ``markers`` are the ``*_provider`` / ``post_setup`` / Nous keys."""
  180. row = {"name": name}
  181. if badge:
  182. row["badge"] = badge
  183. if tag:
  184. row["tag"] = tag
  185. row["env_vars"] = list(env_vars)
  186. row.update(markers)
  187. return row
  188. _NOUS = {"requires_nous_auth": True}
  189. _OPENAI_VOICE_KEY = _key("VOICE_TOOLS_OPENAI_KEY", "OpenAI API key", "https://platform.openai.com/api-keys")
  190. _ELEVENLABS_KEY = _key("ELEVENLABS_API_KEY", "ElevenLabs API key", "https://elevenlabs.io/app/settings/api-keys")
  191. _DEEPINFRA_KEY = _key("DEEPINFRA_API_KEY", "DeepInfra API key", "https://deepinfra.com/dash/api_keys")
  192. TOOL_CATEGORIES = {
  193. "tts": {
  194. "name": "Text-to-Speech", "icon": "🔊",
  195. "providers": [
  196. _row("Microsoft Edge TTS", "★ recommended · free", "Good quality, no API key needed", tts_provider="edge"),
  197. _row("Nous Subscription", "subscription", "Managed OpenAI TTS billed to your subscription", tts_provider="openai",
  198. **_NOUS, managed_nous_feature="tts", override_env_vars=["VOICE_TOOLS_OPENAI_KEY", "OPENAI_API_KEY"]),
  199. _row("OpenAI TTS", "paid", "High quality voices", [_OPENAI_VOICE_KEY], tts_provider="openai"),
  200. _row("xAI TTS", tag="Grok voices — uses xAI Grok OAuth or XAI_API_KEY", tts_provider="xai", post_setup="xai_grok"),
  201. _row("ElevenLabs", "paid", "Most natural voices", [_ELEVENLABS_KEY], tts_provider="elevenlabs"),
  202. # Mistral Voxtral TTS — `mistralai` SDK lazy-installs on first use.
  203. _row("Mistral (Voxtral TTS)", "paid", "Multilingual, native Opus",
  204. [_key("MISTRAL_API_KEY", "Mistral API key", "https://console.mistral.ai/")], tts_provider="mistral"),
  205. _row("Google Gemini TTS", "preview", "30 prebuilt voices, controllable via prompts",
  206. [_key("GEMINI_API_KEY", "Gemini API key", "https://aistudio.google.com/app/apikey")], tts_provider="gemini"),
  207. _row("KittenTTS", "local · free", "Lightweight local ONNX TTS (~25MB), no API key", tts_provider="kittentts",
  208. post_setup="kittentts"),
  209. _row("Piper", "local · free", "Local neural TTS, 44 languages (voices ~20-90MB)", tts_provider="piper",
  210. post_setup="piper"),
  211. _row("DeepInfra TTS", "paid", "Chatterbox, Qwen3-TTS, … — live catalog from api.deepinfra.com", [_DEEPINFRA_KEY],
  212. tts_provider="deepinfra"),
  213. ],
  214. },
  215. "stt": {
  216. "name": "Speech-to-Text", "icon": "🎙️",
  217. "providers": [
  218. _row("Local Whisper", "★ recommended · free", "faster-whisper on-device, no API key", stt_provider="local",
  219. post_setup="faster_whisper"),
  220. _row("Nous Subscription", "subscription", "Managed OpenAI transcription billed to your subscription",
  221. stt_provider="openai", **_NOUS, managed_nous_feature="stt",
  222. override_env_vars=["VOICE_TOOLS_OPENAI_KEY", "OPENAI_API_KEY"]),
  223. _row("OpenAI", "paid", "whisper-1, gpt-4o-transcribe, gpt-transcribe", [_OPENAI_VOICE_KEY], stt_provider="openai"),
  224. _row("Groq", "free tier", "whisper-large-v3-turbo, whisper-large-v3 — very fast",
  225. [_key("GROQ_API_KEY", "Groq API key", "https://console.groq.com/keys")], stt_provider="groq"),
  226. _row("xAI", tag="Grok Voice Transcribe — uses xAI Grok OAuth or XAI_API_KEY", stt_provider="xai", post_setup="xai_grok"),
  227. _row("ElevenLabs Scribe", "paid", "scribe_v2 — diarization + audio-event tagging", [_ELEVENLABS_KEY],
  228. stt_provider="elevenlabs"),
  229. _row("Mistral Voxtral", "paid", "voxtral-mini-latest — multilingual",
  230. [_key("MISTRAL_API_KEY", "Mistral API key", "https://console.mistral.ai/")], stt_provider="mistral"),
  231. _row("DeepInfra", "paid", "Live STT catalog from api.deepinfra.com", [_DEEPINFRA_KEY], stt_provider="deepinfra"),
  232. ],
  233. },
  234. "web": {
  235. "name": "Web Search & Extract", "setup_title": "Select Search Provider",
  236. "setup_note": "A free DuckDuckGo search skill is also included — skip this if you don't need a premium provider.",
  237. "icon": "🔍",
  238. # Provider rows come from plugins.web.<vendor> via _plugin_web_search_providers(). Only the two
  239. # non-provider firecrawl setup-flow rows live here: managed via Nous subscription, and self-hosted.
  240. "providers": [
  241. {"name": "Nous Subscription", "badge": "subscription", "tag": "Managed web search and extract billed to your subscription",
  242. "web_backend": "firecrawl", "env_vars": [], **_NOUS, "managed_nous_feature": "web",
  243. "override_env_vars": ["FIRECRAWL_API_KEY", "FIRECRAWL_API_URL", "PERPLEXITY_API_KEY"]},
  244. {"name": "Firecrawl Self-Hosted", "badge": "free · self-hosted", "tag": "Run your own Firecrawl instance (Docker)",
  245. "web_backend": "firecrawl",
  246. "env_vars": [_key("FIRECRAWL_API_URL", "Your Firecrawl instance URL (e.g., http://localhost:3002)")]},
  247. ],
  248. },
  249. "image_gen": {
  250. "name": "Image Generation", "icon": "🎨",
  251. # Provider rows (FAL, OpenAI, OpenAI Codex, xAI, Krea, …) come from plugins.image_gen.<vendor> via
  252. # _plugin_image_gen_providers(). Only the managed "Nous Subscription" row lives here: ONE row for the
  253. # FAL, Krea and Portal gateways, whose union catalog is `imagegen_backend: "nous"`; the stored model id
  254. # picks the gateway at run time (tools/image_generation_managed.py).
  255. "providers": [
  256. _row("Nous Subscription", "subscription",
  257. "Managed image generation (FAL, Krea 3 and Krea 2, Nous Portal models) billed to your subscription", **_NOUS,
  258. managed_nous_feature="image_gen", override_env_vars=["FAL_KEY"], imagegen_backend="nous"),
  259. ],
  260. },
  261. "video_gen": {
  262. "name": "Video Generation", "icon": "🎬",
  263. # Mirrors image_gen: managed FAL video billed via the Nous Portal. Plugin-backed rows (FAL BYOK, xAI, …)
  264. # are injected at runtime by ``_plugin_video_gen_providers()`` in ``_visible_providers``. Picking this row
  265. # sets video_gen.provider = "fal" + use_gateway so the FAL plugin routes through the managed queue gateway.
  266. "providers": [
  267. _row("Nous Subscription", "subscription", "Managed FAL video generation billed to your subscription", **_NOUS,
  268. managed_nous_feature="video_gen", override_env_vars=["FAL_KEY"], video_gen_plugin_name="fal"),
  269. ],
  270. },
  271. "x_search": {
  272. "name": "X (Twitter) Search", "setup_title": "Select xAI Credential Source",
  273. "setup_note": (
  274. "Hermes routes X searches through xAI's built-in x_search Responses tool for read-only public X "
  275. "discovery. Use the xurl skill for authenticated X API reads and account actions. Both credential "
  276. "sources hit the same https://api.x.ai/v1/responses endpoint — pick whichever you already have. "
  277. "SuperGrok OAuth is preferred when both are set (uses your subscription quota instead of API spend)."
  278. ),
  279. "icon": "🐦",
  280. "providers": [
  281. _row("xAI Grok OAuth (SuperGrok / Premium+)", "subscription", "Browser login at accounts.x.ai — no API key required",
  282. post_setup="xai_grok"),
  283. _row("xAI API key", "paid", "Direct xAI API billing via XAI_API_KEY",
  284. [_key("XAI_API_KEY", "xAI API key", "https://console.x.ai/")]),
  285. ],
  286. },
  287. "browser": {
  288. "name": "Browser Automation", "icon": "🌐",
  289. # Cloud provider rows (Browserbase, Browser Use, Firecrawl) come from plugins.browser.<vendor> via
  290. # _plugin_browser_providers(); only non-provider setup-flow rows live here. "Local Browser" MUST stay
  291. # first so a fresh install's Enter lands on the free local backend (index 0), never on the paid Nous row.
  292. # Lightpanda is local too (cloud_provider: local, browser.engine: lightpanda — browser_exec spawns
  293. # ``lightpanda serve``; no Chromium).
  294. "providers": [
  295. _row("Local Browser", "★ recommended · free", "Headless Chromium, no API key needed", browser_provider="local",
  296. browser_engine="auto", post_setup="chromium"),
  297. _row("Lightpanda", "free · local · no Chromium", "Zig headless browser spawned by Hermes, text-only (no screenshots)",
  298. browser_provider="local", browser_engine="lightpanda", post_setup="lightpanda"),
  299. # Browser Use hosts its own Chromium, so the local-Chromium install and readiness gate must not
  300. # apply (with "chromium" this row read "needs setup" forever on machines without a local build).
  301. _row("Nous Subscription (Browser Use cloud)", "subscription", "Managed Browser Use billed to your subscription",
  302. browser_provider="browser-use", **_NOUS, managed_nous_feature="browser",
  303. override_env_vars=["BROWSER_USE_API_KEY"], post_setup="browserbase"),
  304. ],
  305. },
  306. "computer_use": {
  307. "name": "Computer Use (macOS/Windows/Linux)", "icon": "🖱️",
  308. # Runtime backends ship for macOS, Windows, Linux (X11; Wayland via XWayland). Gaps surface via `computer-use doctor`.
  309. "platform_gate": ["darwin", "win32", "linux"],
  310. # cua-driver reads HOME/TMPDIR from the process env; HERMES_CUA_DRIVER_CMD selects a specific
  311. # binary (e.g. a local build). There is no version-pin env var.
  312. "providers": [
  313. _row("cua-driver (background)", "★ recommended · free · local",
  314. "Background computer-use via cua-driver — does NOT steal your cursor or focus. Works with any model.",
  315. computer_use_backend="cua", post_setup="cua_driver"),
  316. ],
  317. },
  318. }
  319. # Env-var fallback for toolsets NOT in TOOL_CATEGORIES. `vision` is only a presence marker (reconfigure menu +
  320. # "[no API key]" suffix): setup runs `_configure_vision_backend()` and `_toolset_has_keys("vision")` uses
  321. # `resolve_vision_provider_client()` — never forcing OpenRouter.
  322. TOOLSET_ENV_REQUIREMENTS = {"vision": [("OPENROUTER_API_KEY", "https://openrouter.ai/keys")]}
  323. # --- Platform / Toolset Helpers ---
  324. _PLATFORM_ENABLE_ENV_VARS = (
  325. ("telegram", "TELEGRAM_BOT_TOKEN"), ("discord", "DISCORD_BOT_TOKEN"), ("slack", "SLACK_BOT_TOKEN"),
  326. ("whatsapp", "WHATSAPP_ENABLED"), ("qqbot", "QQ_APP_ID"))
  327. def _get_enabled_platforms() -> list[str]:
  328. """Return platform keys that are configured (have tokens or are CLI)."""
  329. return ["cli"] + [platform for platform, env_var in _PLATFORM_ENABLE_ENV_VARS if get_env_value(env_var)]
  330. def _platform_toolset_summary(config: dict, platforms: Optional[list[str]] = None) -> dict[str, set[str]]:
  331. """Enabled toolsets per platform (``platforms`` defaults to ``_get_enabled_platforms()``)."""
  332. if platforms is None:
  333. platforms = _get_enabled_platforms()
  334. return {pkey: _get_platform_tools(config, pkey) for pkey in platforms}
  335. def _parse_enabled_flag(value, default: bool = True) -> bool:
  336. """Parse bool-like config values used by tool/platform settings."""
  337. if isinstance(value, (bool, int)):
  338. return bool(value)
  339. if isinstance(value, str):
  340. lowered = value.strip().lower()
  341. if lowered in {"true", "1", "yes", "on", "false", "0", "no", "off"}:
  342. return lowered in {"true", "1", "yes", "on"}
  343. return default
  344. def enabled_mcp_server_names(config: dict) -> set[str]:
  345. """MCP servers globally enabled in config.yaml or by a plugin (shared by platform + cron resolvers). Enabled
  346. unless ``enabled`` is explicitly falsey; portable-plugin servers (in-memory) count — enabling the plugin is
  347. the opt-in."""
  348. from tools.mcp_tool_common import mcp_server_enabled
  349. mcp_servers = (config or {}).get("mcp_servers") or {}
  350. names = {
  351. str(name) for name, server_cfg in mcp_servers.items()
  352. if isinstance(server_cfg, dict) and mcp_server_enabled(server_cfg)
  353. }
  354. try:
  355. projected = _projected_plugin_toolsets()
  356. if projected is None:
  357. from hermes_cli.plugins import get_portable_mcp_server_names_nowait
  358. portable = projected[1] if projected is not None else get_portable_mcp_server_names_nowait()
  359. names |= portable - set(mcp_servers) # native config wins on a name collision (mirrors _load_mcp_config)
  360. except Exception:
  361. logger.debug("Failed to include portable MCP servers", exc_info=True)
  362. return names
  363. #: Toolsets young enough that absence from a saved ``platform_toolsets`` list means "never offered", not
  364. #: "declined": saving ``hermes tools`` freezes a platform's composite into an explicit list nothing adds to, so
  365. #: a later toolset stays off forever for picker users while ``[hermes-cli]`` users inherit it.
  366. #: MUST ship in the same release as the toolset and be emptied in the next: once a released build has put the
  367. #: toolset on a checklist, an unchecking user's config is byte-identical to one saved before it existed and this
  368. #: rule would turn the opt-out back on (stuck checkbox). ``check_fn``-gated toolsets cost nothing here; never
  369. #: probe a remote service from this path — it runs on every CLI start, gateway session and cron tick.
  370. _RECENTLY_SHIPPED_TOOLSETS: frozenset = frozenset()
  371. def _enable_recently_shipped_toolsets(enabled_toolsets: set[str], config: dict, platform: str) -> None:
  372. """Turn on toolsets that shipped after this platform's saved list (mutates ``enabled_toolsets``). Both "no"s
  373. outlive this: unchecking records ``known_builtin_toolsets`` (declined), and ``agent.disabled_toolsets`` is
  374. subtracted last in :func:`_get_platform_tools`."""
  375. from toolsets import resolve_toolset
  376. offered = (config.get("known_builtin_toolsets") or {}).get(platform)
  377. declined = {str(ts) for ts in offered} if isinstance(offered, list) else set()
  378. default_ts = _platform_default_toolset(platform)
  379. composite_tools = None
  380. for ts_key in sorted(_RECENTLY_SHIPPED_TOOLSETS):
  381. if ts_key in enabled_toolsets or ts_key in declined or not _toolset_allowed_for_platform(ts_key, platform):
  382. continue
  383. # Only enable where staying on the composite would have enabled it anyway; deliberately narrow
  384. # composites (hermes-acp, hermes-webhook) stay narrow.
  385. ts_tools = set(resolve_toolset(ts_key, include_registry=False))
  386. if composite_tools is None:
  387. composite_tools = set(resolve_toolset(default_ts))
  388. if not ts_tools or not ts_tools.issubset(composite_tools):
  389. continue
  390. enabled_toolsets.add(ts_key)
  391. def _configurable_subset_of(tool_names: set[str], platform: str) -> set[str]:
  392. """Configurable toolsets whose STATIC membership is within ``tool_names`` (``include_registry=False``: a
  393. runtime-registered tool the composite never listed must not drop the whole toolset)."""
  394. from toolsets import resolve_toolset
  395. return {
  396. ts_key for ts_key, _, _ in CONFIGURABLE_TOOLSETS if _toolset_allowed_for_platform(ts_key, platform)
  397. and (ts_tools := set(resolve_toolset(ts_key, include_registry=False))) and ts_tools <= tool_names}
  398. def _default_off_toolsets(platform: str, explicitly_configured: bool) -> set[str]:
  399. """Toolsets to strip from an implicit (composite-derived) enable set. A platform named after a default-off
  400. toolset keeps it, except platform-restricted ones (``discord`` on discord stays OFF).
  401. Platform-native default-off toolsets (``discord`` on discord) are off for unconfigured platforms as a
  402. security opt-in — an explicitly saved list IS that opt-in and lets them through."""
  403. default_off = set(_DEFAULT_OFF_TOOLSETS)
  404. if platform in default_off and platform not in _TOOLSET_PLATFORM_RESTRICTIONS:
  405. default_off.remove(platform)
  406. if explicitly_configured:
  407. default_off -= {ts for ts in default_off if platform in (_TOOLSET_PLATFORM_RESTRICTIONS.get(ts) or ())}
  408. return default_off
  409. def _configurable_keys() -> set[str]:
  410. return {ts_key for ts_key, _, _ in CONFIGURABLE_TOOLSETS}
  411. def _platform_default_keys() -> set[str]:
  412. return {p["default_toolset"] for p in PLATFORMS.values()}
  413. def _explicit_toolsets(
  414. toolset_names: list[str], explicit_known_keys: set[str], config: dict, platform: str,
  415. explicitly_configured: bool) -> set[str]:
  416. """Enabled set when the saved list names configurable/plugin keys directly (subset inference over
  417. ``hermes-cli`` would re-enable disabled toolsets). A mixed list (``[hermes-cli, discord]``) still expands the
  418. composite; _DEFAULT_OFF_TOOLSETS applies to that implicit expansion only."""
  419. from toolsets import resolve_toolset, TOOLSETS
  420. enabled = {ts for ts in toolset_names if ts in explicit_known_keys and _toolset_allowed_for_platform(ts, platform)}
  421. composite_tools = {
  422. t for ts_name in toolset_names if ts_name not in explicit_known_keys and ts_name in TOOLSETS
  423. for t in resolve_toolset(ts_name)}
  424. if composite_tools:
  425. enabled |= _configurable_subset_of(composite_tools, platform) - _default_off_toolsets(platform, explicitly_configured)
  426. _enable_recently_shipped_toolsets(enabled, config, platform)
  427. return enabled
  428. def _composite_toolsets(toolset_names: list[str], platform: str, explicitly_configured: bool) -> set[str]:
  429. """Enabled set inferred from composite names by reverse-mapping tool names (only while no explicit list is
  430. saved). ``x_search`` is not in any composite, so inject it when xAI creds exist and exempt it from default-off."""
  431. from toolsets import resolve_toolset
  432. all_tool_names = {t for ts_name in toolset_names for t in resolve_toolset(ts_name)}
  433. enabled = _configurable_subset_of(all_tool_names, platform)
  434. default_off = _default_off_toolsets(platform, explicitly_configured)
  435. if _toolset_allowed_for_platform("x_search", platform) and _xai_credentials_present():
  436. enabled.add("x_search")
  437. default_off.discard("x_search")
  438. return enabled - default_off
  439. def _enabled_plugin_toolsets(config: dict, platform: str, toolset_names: list[str], plugin_ts_keys: set[str]) -> set[str]:
  440. """Plugin toolsets: on by default unless default-off (catalog spotify) or "known" for this platform
  441. (``known_plugin_toolsets``, written on every save) and absent from the saved list."""
  442. known_for_platform = set((config.get("known_plugin_toolsets", {}) or {}).get(platform, []) or [])
  443. return {
  444. pts for pts in plugin_ts_keys
  445. if pts in toolset_names or (pts not in _DEFAULT_OFF_TOOLSETS and pts not in known_for_platform)
  446. }
  447. def _context_engine_active(config: dict) -> bool:
  448. context_cfg = config.get("context") or {}
  449. name = str(context_cfg.get("engine") or "compressor").strip().lower() if isinstance(context_cfg, dict) else "compressor"
  450. return bool(name) and name != "compressor"
  451. def _coerce_platform_toolsets_value(value, platform: str):
  452. """Read a list-literal string saved for ``platform_toolsets.<platform>`` as the list it encodes.
  453. The parser is shared with ``hermes doctor`` and ``hermes plugins`` (``toolset_validation``
  454. ``parse_platform_toolsets_value``) so every surface agrees on the user's selection (#115866).
  455. Any other non-list value is warned about once (naming the expected shape) and left as-is, so
  456. the default fallback below is loud rather than silent.
  457. """
  458. if value is None:
  459. return None
  460. parsed = parse_platform_toolsets_value(value)
  461. if parsed is not None:
  462. return parsed
  463. if platform not in _warned_invalid_platform_toolsets:
  464. _warned_invalid_platform_toolsets.add(platform)
  465. logger.warning(
  466. "platform_toolsets.%s is %r, expected a YAML list of toolset names "
  467. "(e.g. [terminal, file, web]) - falling back to the platform default. "
  468. "Run `hermes tools` to reconfigure.", platform, value)
  469. return value
  470. def _platform_toolsets_explicitly_saved(config: dict, platform: str) -> bool:
  471. """True when ``platform_toolsets.<platform>`` holds an explicitly saved LIST (even ``[]``).
  472. ``_get_platform_tools``'s ``explicitly_configured`` flag without re-running the resolver
  473. (post-coercion, so a list-literal string counts too): an unset key or a non-list value
  474. falls back to the platform default. Callers use this to tell an explicit zero-tool
  475. selection (fail closed, #82010) from an absent one ("no restriction").
  476. """
  477. platform_toolsets = config.get("platform_toolsets") or {}
  478. raw = platform_toolsets.get(platform)
  479. return isinstance(_coerce_platform_toolsets_value(raw, platform), list)
  480. def _get_platform_tools(config: dict, platform: str, *, include_default_mcp_servers: bool = True) -> set[str]:
  481. """Resolve which individual toolset names are enabled for a platform."""
  482. platform_toolsets = config.get("platform_toolsets") or {}
  483. toolset_names = _coerce_platform_toolsets_value(platform_toolsets.get(platform), platform)
  484. # An explicitly saved list (even a composite like ``hermes-discord``) is an opt-in to the platform's
  485. # native default-off toolsets — see _default_off_toolsets.
  486. # Track whether the user explicitly saved a toolset list for this platform (vs. falling back to the
  487. # platform default). See #35527.
  488. explicitly_configured = isinstance(toolset_names, list)
  489. if not explicitly_configured:
  490. toolset_names = [_platform_default_toolset(platform)]
  491. # YAML may parse bare numeric names (``12306:``) as int; normalise so sorted() never mixes types.
  492. toolset_names = [str(ts) for ts in toolset_names]
  493. # Expand legacy toolset aliases. Older Hermes versions and clients used
  494. # bare ``"hermes"`` as a composite toolset covering both the CLI and the
  495. # API-server surface. Modern code expects ``"hermes-cli"`` (and
  496. # ``"hermes-api-server"`` for the HTTP endpoint), so configs persisted
  497. # by those older versions still carry the legacy name; without expansion
  498. # ``resolve_toolset("hermes")`` returns ``[]`` — all tools silently
  499. # disappear.
  500. _LEGACY_TOOLSET_ALIASES: dict = {
  501. "hermes": ("hermes-cli", "hermes-api-server"),
  502. }
  503. expanded: list = []
  504. for name in toolset_names:
  505. aliases = _LEGACY_TOOLSET_ALIASES.get(name)
  506. if aliases:
  507. expanded.extend(aliases)
  508. else:
  509. expanded.append(name)
  510. toolset_names = expanded
  511. configurable_keys = _configurable_keys()
  512. plugin_ts_keys = _get_plugin_toolset_keys()
  513. platform_default_keys = _platform_default_keys()
  514. # Plugin toolsets are first-class on a saved list: ``[hermes-cli, a2a]`` must survive filtering.
  515. # Plugin-provided toolsets are first-class on a platform-toolsets list — explicit config like
  516. # ``[hermes-cli, a2a]`` must survive filtering just like a built-in configurable toolset would. See
  517. # issue #81163.
  518. explicit_known_keys = configurable_keys | plugin_ts_keys
  519. if any(ts in explicit_known_keys for ts in toolset_names):
  520. enabled_toolsets = _explicit_toolsets(toolset_names, explicit_known_keys, config, platform, explicitly_configured)
  521. else:
  522. enabled_toolsets = _composite_toolsets(toolset_names, platform, explicitly_configured)
  523. _recover_platform_native_toolsets(enabled_toolsets, platform, skip=configurable_keys | plugin_ts_keys | platform_default_keys)
  524. if plugin_ts_keys:
  525. enabled_toolsets |= _enabled_plugin_toolsets(config, platform, toolset_names, plugin_ts_keys)
  526. # Context-engine tools are runtime-provided, not in any static composite: keep them for a non-default
  527. # engine even after an explicit save. An explicit EMPTY list means none, unless ``context_engine`` is added by hand.
  528. if _context_engine_active(config) and not (explicitly_configured and not toolset_names):
  529. enabled_toolsets.add("context_engine")
  530. # Explicit non-configurable entries (custom toolsets, MCP server names) pass through.
  531. explicit_passthrough = {ts for ts in toolset_names if ts not in explicit_known_keys and ts not in platform_default_keys}
  532. enabled_toolsets |= _merge_mcp_servers(config, toolset_names, explicit_passthrough, include_default_mcp_servers)
  533. # Legacy profile opt-in is a fallback only. A saved platform list (even
  534. # empty) is authoritative, so a later disable cannot silently re-enable it.
  535. if not explicitly_configured and "kanban" in (config.get("toolsets") or []):
  536. enabled_toolsets.add("kanban")
  537. # agent.disabled_toolsets is a global suppression list (#86661) and runs LAST so it overrides everything
  538. # above. It may arrive as a JSON-array string ("['memory']") from `hermes config set` or a JSON-mode editor.
  539. disabled_toolsets = (config.get("agent") or {}).get("disabled_toolsets")
  540. if disabled_toolsets:
  541. from agent.skill_utils import parse_config_string_list
  542. disabled_names = [name.strip() for name in parse_config_string_list(disabled_toolsets) if name.strip()]
  543. enabled_toolsets = _prune_toolsets_stripped_by_disabled(enabled_toolsets, disabled_names)
  544. if explicitly_configured and toolset_names:
  545. _warn_all_invalid_platform_toolsets(platform, toolset_names, config)
  546. return enabled_toolsets
  547. def _prune_toolsets_stripped_by_disabled(enabled_toolsets: set[str], disabled_names: list[str]) -> set[str]:
  548. """Drop disabled names AND every toolset whose tools the runtime would strip anyway.
  549. The agent subtracts ``agent.disabled_toolsets`` at TOOL granularity (``model_tools._select_tool_names``),
  550. so disabling a composite like ``debugging`` removes the terminal/web/file tools even though those names
  551. never appear in the list. A name-only subtraction here left inspection surfaces (``hermes tools
  552. --summary``, banner, ``/tools``) showing toolsets as enabled that no session could call (#97015).
  553. Passthrough entries (MCP server names) and toolsets with no static tools (``context_engine``) are kept.
  554. """
  555. from model_tools import _apply_toolset_selection
  556. from toolsets import resolve_toolset, validate_toolset
  557. remaining = enabled_toolsets - set(disabled_names)
  558. resolved = {name: set(resolve_toolset(name)) if validate_toolset(name) else set() for name in remaining}
  559. surviving: set[str] = set().union(*resolved.values())
  560. _apply_toolset_selection(surviving, disabled_names, quiet_mode=True, disable=True)
  561. return {name for name, tools in resolved.items() if not tools or tools & surviving}
  562. def _disabled_entry_tools(name: str) -> set[str]:
  563. """Tools one ``agent.disabled_toolsets`` entry removes at runtime: legacy names (``terminal_tools``)
  564. and the bundle/posture non-core delta included, which ``resolve_toolset`` alone gets wrong."""
  565. from model_tools import _LEGACY_TOOLSET_MAP, _apply_toolset_selection
  566. from toolsets import resolve_toolset
  567. universe = set(resolve_toolset(name)) | set(_LEGACY_TOOLSET_MAP.get(name, ()))
  568. kept = set(universe)
  569. _apply_toolset_selection(kept, [name], quiet_mode=True, disable=True)
  570. return universe - kept
  571. def toolsets_partially_stripped(config: dict, enabled_toolsets: set[str]) -> dict[str, tuple[list[str], list[str], str]]:
  572. """``{toolset: (stripped tools, disabled entries stripping them, repair hint)}`` for enabled toolsets
  573. that ``agent.disabled_toolsets`` cuts down without removing (``web`` minus ``web_search`` via ``search``,
  574. #134593). ``_prune_toolsets_stripped_by_disabled`` keeps such a toolset "enabled" because some of its
  575. tools survive, so inspection surfaces need this to say which ones did not. The hint offers
  576. ``hermes tools enable`` only when that save clears every entry (``_save_platform_tools`` coverage)."""
  577. from agent.skill_utils import parse_config_string_list
  578. from model_tools import _apply_toolset_selection
  579. from toolsets import resolve_toolset, validate_toolset
  580. disabled = [n.strip() for n in parse_config_string_list((config.get("agent") or {}).get("disabled_toolsets")) if n.strip()]
  581. report: dict[str, tuple[list[str], list[str]]] = {}
  582. for name in sorted(enabled_toolsets):
  583. tools = set(resolve_toolset(name)) if validate_toolset(name) else set()
  584. by: dict[str, set[str]] = {}
  585. for entry in disabled:
  586. kept = set(tools)
  587. _apply_toolset_selection(kept, [entry], quiet_mode=True, disable=True)
  588. if tools - kept:
  589. by[entry] = tools - kept
  590. if by:
  591. entries = sorted(by)
  592. clears = all(_disabled_entry_tools(e) <= tools for e in entries)
  593. hint = (f"run `hermes tools enable {name}` to restore" if clears
  594. else f"remove {', '.join(entries)} from agent.disabled_toolsets to restore")
  595. report[name] = (sorted(set().union(*by.values())), entries, hint)
  596. return report
  597. def _recover_platform_native_toolsets(enabled_toolsets: set[str], platform: str, *, skip: set[str]) -> None:
  598. """Add non-configurable platform toolsets (discord, feishu_*) in place: in the default composite but not in
  599. CONFIGURABLE_TOOLSETS, so never in a checklist or saved list. Runs for BOTH ``_get_platform_tools`` branches."""
  600. from toolsets import resolve_toolset, TOOLSETS
  601. platform_tool_universe = set(resolve_toolset(_platform_default_toolset(platform)))
  602. configurable_tool_universe = {t for ts_key, _, _ in CONFIGURABLE_TOOLSETS for t in resolve_toolset(ts_key)}
  603. claimed = {t for ts_key in enabled_toolsets for t in resolve_toolset(ts_key)}
  604. skip = skip | {k for k in TOOLSETS if k.startswith("hermes-")} | (set(_DEFAULT_OFF_TOOLSETS) - {platform})
  605. for ts_key, ts_def in TOOLSETS.items():
  606. # Posture toolsets (``coding``) are session-level selections made by agent/coding_context.py, not
  607. # per-platform capabilities to recover.
  608. if ts_key in skip or ts_def.get("includes") or ts_def.get("posture"):
  609. continue
  610. # Static membership: a registry-added tool absent from the platform composite must not block recovery
  611. # of a non-configurable toolset whose authored tools the composite lists.
  612. ts_tools = set(resolve_toolset(ts_key, include_registry=False))
  613. if not ts_tools or not ts_tools <= platform_tool_universe or ts_tools <= configurable_tool_universe:
  614. continue
  615. if not ts_tools <= claimed:
  616. enabled_toolsets.add(ts_key)
  617. claimed.update(ts_tools)
  618. def _merge_mcp_servers(
  619. config: dict, toolset_names: list[str], explicit_passthrough: set[str], include_default_mcp_servers: bool
  620. ) -> set[str]:
  621. """Explicit passthrough entries plus this platform's MCP servers: listed names form an allowlist, else every
  622. globally enabled server (when ``include_default_mcp_servers``); the ``no_mcp`` sentinel disables all."""
  623. enabled_mcp_servers = enabled_mcp_server_names(config)
  624. configured = config.get("mcp_servers") if isinstance(config.get("mcp_servers"), dict) else {}
  625. known = enabled_mcp_servers | {str(name) for name in configured}
  626. # ``mcp-<server>`` names the same server as its bare alias: either spelling selects only that server
  627. # (unless a server is literally named ``mcp-<server>``).
  628. explicit_passthrough = {ts[4:] if ts.startswith("mcp-") and ts not in known
  629. and ts[4:] in known else ts for ts in explicit_passthrough}
  630. result = explicit_passthrough - known
  631. if "no_mcp" in toolset_names:
  632. return result - {"no_mcp"}
  633. explicit_mcp_servers = explicit_passthrough & enabled_mcp_servers
  634. # A listed server that is configured but disabled is still the user's server selection: it stays
  635. # off, and it must not fall through to every enabled server.
  636. if include_default_mcp_servers and not explicit_passthrough & known:
  637. return result | enabled_mcp_servers
  638. return result | explicit_mcp_servers
  639. def _warn_all_invalid_platform_toolsets(platform: str, explicit: list, config: dict) -> None:
  640. """Warn once when an explicit platform list has only invalid names (``hermes`` for ``hermes-cli`` → no
  641. native tools), at session tool resolution rather than only in update/doctor. Names are judged the way
  642. ``hermes config check`` judges them, and a known platform's own ``hermes-<platform>`` bundle always
  643. counts (``is_known_platform_bundle``): a plugin platform has no sessions to leave toolless until its
  644. plugin loads, and once it loads the registry resolves the bundle.
  645. The own-bundle and registered-toolset checks run first because this is reached on every schema build
  646. (the kanban gate resolves every saved platform row) and on bypass launches that must not read profile
  647. plugin state; the resolver's manifest scan and plugin lookup run only for names those cannot place."""
  648. from hermes_cli.toolset_validation import is_known_platform_bundle, saved_toolset_resolver
  649. from toolsets import validate_toolset
  650. if platform in _warned_invalid_platform_toolsets:
  651. return
  652. named = [str(t) for t in explicit if isinstance(t, str) and t]
  653. if not named or any(validate_toolset(t) or is_known_platform_bundle(platform, t) for t in named):
  654. return
  655. is_valid_toolset = saved_toolset_resolver(config)
  656. if not any(is_valid_toolset(t) for t in named):
  657. _warned_invalid_platform_toolsets.add(platform)
  658. logger.warning(
  659. "platform '%s' has no valid toolsets configured (unknown "
  660. "name(s): %s) - tools will be unavailable. Run `hermes tools` "
  661. "to reconfigure. See issue #38798.",
  662. platform, ", ".join(named))
  663. def _save_platform_tools(config: dict, platform: str, enabled_toolset_keys: set[str]):
  664. """Save the selected toolset keys for a platform to config."""
  665. config.setdefault("platform_toolsets", {})
  666. # Drop platform-scoped toolsets that don't apply here, so the "Configure all platforms" checklist (or a
  667. # hand-edited config.yaml) can't turn on `discord` for Telegram.
  668. enabled_toolset_keys = {ts for ts in enabled_toolset_keys if _toolset_allowed_for_platform(ts, platform)}
  669. plugin_keys = _get_plugin_toolset_keys()
  670. # Preserve only existing entries that are neither configurable nor platform defaults (i.e. MCP server
  671. # names): platform defaults (hermes-cli, ...) resolve to ALL tools and would silently override the user's
  672. # unchecked selections on the next read. Saving from the picker is consent to clear the "no_mcp" sentinel
  673. # (no checkbox for it; users who once set it by hand could otherwise never re-enable MCP via the UI).
  674. drop = _configurable_keys() | plugin_keys | _platform_default_keys() | {"no_mcp"}
  675. existing_toolsets = _coerce_platform_toolsets_value(
  676. cfg_get(config, "platform_toolsets", platform, default=[]), platform
  677. )
  678. preserved_entries = {str(e) for e in (existing_toolsets if isinstance(existing_toolsets, list) else [])
  679. if str(e) not in drop}
  680. config["platform_toolsets"][platform] = sorted(enabled_toolset_keys | preserved_entries)
  681. # Record which plugin toolsets this platform "knows" (distinguishes "new plugin, default enabled" from
  682. # "user disabled it"). _cfg_section normalizes a present-but-null key that setdefault alone would not replace.
  683. if plugin_keys:
  684. _cfg_section(config, "known_plugin_toolsets")[platform] = sorted(plugin_keys)
  685. # Same record for builtin toolsets the checklist offered; without it an unchecked toolset is
  686. # indistinguishable from one shipped after the save and _enable_recently_shipped_toolsets re-enables it.
  687. _cfg_section(config, "known_builtin_toolsets")[platform] = sorted(_configurable_keys())
  688. # Reconcile with agent.disabled_toolsets, which _get_platform_tools applies as a final override: a toolset
  689. # listed there stays OFF no matter what this writes (Blank Slate installs pre-populate ~27 entries, making
  690. # the desktop Toolsets UI unable to re-enable anything). Only toolsets just explicitly enabled FOR THIS
  691. # PLATFORM are cleared, so the list keeps working as a cross-platform suppression list for everything else.
  692. # See #49995.
  693. agent_cfg = config.get("agent")
  694. newly_enabled = enabled_toolset_keys - preserved_entries
  695. if isinstance(agent_cfg, dict) and agent_cfg.get("disabled_toolsets") and newly_enabled:
  696. from agent.skill_utils import parse_config_string_list
  697. parsed_disabled = parse_config_string_list(agent_cfg["disabled_toolsets"])
  698. # Also clear entries whose tools are entirely covered by a newly enabled toolset: Blank Slate writes
  699. # subset toolsets like `search` (only web_search), which have no checklist row, so enabling `web`
  700. # left web_search stripped with no supported way to undo it (#134593).
  701. from toolsets import resolve_toolset
  702. covered: set[str] = set()
  703. for ts in newly_enabled:
  704. covered.update(resolve_toolset(ts)) # [] for unknown names; never raises
  705. def _covered(ts: str) -> bool:
  706. tools = _disabled_entry_tools(ts)
  707. return bool(tools) and tools <= covered
  708. remaining = [ts for ts in parsed_disabled if ts not in newly_enabled and not _covered(ts)]
  709. if remaining != parsed_disabled:
  710. agent_cfg["disabled_toolsets"] = remaining
  711. save_config(config)
  712. def _provider_env_ready(provider: dict) -> bool:
  713. """True when every env var a provider row declares is set (trivially true for no-key rows)."""
  714. return all(get_env_value(e["key"]) for e in provider.get("env_vars", []))
  715. def _toolset_has_keys(
  716. ts_key: str, config: dict | None = None, *, force_fresh: bool = False, features: Optional[NousSubscriptionFeatures] = None,
  717. ) -> bool:
  718. """Check if a toolset's required API keys are configured."""
  719. if config is None:
  720. config = load_config()
  721. if ts_key == "vision":
  722. try:
  723. from agent.auxiliary_client import resolve_vision_provider_client
  724. return resolve_vision_provider_client()[1] is not None
  725. except Exception:
  726. return False
  727. if ts_key in {"web", "image_gen", "video_gen", "tts", "stt", "browser"}:
  728. if features is None:
  729. features = get_nous_subscription_features(config, force_fresh=force_fresh)
  730. feature = features.features.get(ts_key)
  731. if feature and (feature.available or feature.managed_by_nous):
  732. return True
  733. # Provider-aware categories first: a no-key provider (Local Browser, Edge TTS) counts as configured.
  734. cat = TOOL_CATEGORIES.get(ts_key)
  735. if cat:
  736. return any(_provider_env_ready(p) for p in _visible_providers(cat, config, force_fresh=force_fresh, features=features))
  737. return all(get_env_value(var) for var, _ in TOOLSET_ENV_REQUIREMENTS.get(ts_key, []))
  738. def _prompt_choice(question: str, choices: list, default: int = 0) -> int:
  739. """Single-select menu (arrow keys). Delegates to curses_radiolist."""
  740. from hermes_cli.curses_ui import curses_radiolist
  741. return curses_radiolist(question, choices, selected=default, cancel_returns=default)
  742. # --- Token Estimation ---
  743. # Profile-keyed cache so one process can serve distinct plugin tool catalogs.
  744. _tool_token_cache: Optional[dict[tuple[str, int], dict[str, int]]] = None
  745. def _estimate_tool_tokens() -> dict[str, int]:
  746. """tiktoken (cl100k_base) tokens per tool name from the serialised OpenAI schema; cached per process and
  747. registry generation, {} if tiktoken/registry unavailable."""
  748. global _tool_token_cache
  749. from hermes_constants import hermes_home_key
  750. scope = hermes_home_key()
  751. _tool_token_cache = _tool_token_cache or {}
  752. try:
  753. import model_tools
  754. from tools.registry import registry
  755. cache_key = (scope, registry._generation)
  756. except Exception:
  757. logger.debug("Tool registry unavailable; skipping token estimation")
  758. return _tool_token_cache.setdefault((scope, -1), {})
  759. if cache_key in _tool_token_cache:
  760. return _tool_token_cache[cache_key]
  761. try:
  762. import tiktoken
  763. enc = tiktoken.get_encoding("cl100k_base")
  764. except Exception:
  765. logger.debug("tiktoken unavailable; skipping tool token estimation")
  766. return _tool_token_cache.setdefault(cache_key, {})
  767. # Mirror the wire shape sent to the API.
  768. counts = {
  769. name: len(enc.encode(_json.dumps({"type": "function", "function": schema})))
  770. for name in registry.get_all_tool_names() if (schema := registry.get_schema(name))}
  771. _tool_token_cache[cache_key] = counts
  772. return counts
  773. def _prompt_toolset_checklist(platform_label: str, enabled: set[str], platform: str = "cli", *, force_fresh: bool = True) -> set[str]:
  774. """Multi-select checklist of toolsets. Returns set of selected toolset keys."""
  775. from hermes_cli.curses_ui import curses_checklist
  776. from toolsets import resolve_toolset
  777. tool_tokens = _estimate_tool_tokens()
  778. # Drop platform-scoped toolsets that don't apply here and config-only capabilities (stt).
  779. effective = [
  780. (k, l, d) for (k, l, d) in _get_effective_configurable_toolsets()
  781. if _toolset_allowed_for_platform(k, platform) and k not in _CONFIG_ONLY_TOOLSETS]
  782. labels = [
  783. f"{ts_label} ({ts_desc})"
  784. + (" [no API key]" if not _toolset_has_keys(ts_key, force_fresh=force_fresh) and _is_configurable(ts_key) else "")
  785. for ts_key, ts_label, ts_desc in effective]
  786. pre_selected = {i for i, (ts_key, _, _) in enumerate(effective) if ts_key in enabled}
  787. status_fn = None
  788. if tool_tokens:
  789. ts_keys = [ts_key for ts_key, _, _ in effective]
  790. def status_fn(chosen: set) -> str:
  791. """Deduplicated token cost of the selected toolsets."""
  792. all_tools: set = set()
  793. for idx in chosen:
  794. all_tools.update(resolve_toolset(ts_keys[idx]))
  795. total = sum(tool_tokens.get(name, 0) for name in all_tools)
  796. return f"Est. tool context: ~{total / 1000:.1f}k tokens" if total >= 1000 else f"Est. tool context: ~{total} tokens"
  797. chosen = curses_checklist(
  798. f"Tools for {platform_label}", labels, pre_selected, cancel_returns=pre_selected, status_fn=status_fn,
  799. )
  800. return {effective[i][0] for i in chosen}
  801. # --- Provider-Aware Configuration ---
  802. def _configure_toolset(ts_key: str, config: dict, *, force_fresh: bool = True, reconfigure: bool = False):
  803. """Configure a toolset: provider selection + API keys (TOOL_CATEGORIES), else simple env-var prompts."""
  804. cat = TOOL_CATEGORIES.get(ts_key)
  805. if cat:
  806. _configure_tool_category(ts_key, cat, config, force_fresh=force_fresh, reconfigure=reconfigure)
  807. else:
  808. _configure_simple_requirements(ts_key, reconfigure=reconfigure)
  809. def _reconfigure_tool(config: dict, *, force_fresh: bool = True):
  810. """Let user reconfigure an existing tool's provider or API key."""
  811. configurable = [
  812. (ts_key, ts_label)
  813. for ts_key, ts_label, _ in _get_effective_configurable_toolsets()
  814. if _is_configurable(ts_key) and (
  815. _toolset_has_keys(ts_key, config, force_fresh=force_fresh)
  816. or _toolset_enabled_for_reconfigure(ts_key, config))]
  817. if not configurable:
  818. _print_info("No configured tools to reconfigure.")
  819. return
  820. choices = [label for _, label in configurable] + ["Cancel"]
  821. idx = _prompt_choice(" Which tool would you like to reconfigure?", choices, len(choices) - 1)
  822. if idx >= len(configurable):
  823. return
  824. _configure_toolset(configurable[idx][0], config, force_fresh=force_fresh, reconfigure=True)
  825. save_config(config)
  826. def _toolset_enabled_for_reconfigure(ts_key: str, config: dict) -> bool:
  827. """True if the toolset is enabled on any platform, so reconfigure covers enabled-but-unconfigured ones."""
  828. for platform in filter(lambda p: _toolset_allowed_for_platform(ts_key, p), PLATFORMS):
  829. try:
  830. if ts_key in _current_platform_tools(config, platform):
  831. return True
  832. except Exception:
  833. continue
  834. return False
  835. # --- Main Entry Point ---
  836. def _shared_metrics_state(config: dict) -> tuple[bool, bool]:
  837. """Return (collection_enabled, send_enabled) from a config dict."""
  838. telemetry = config.get("telemetry")
  839. shared = telemetry.get("shared_metrics") if isinstance(telemetry, dict) else None
  840. shared = shared if isinstance(shared, dict) else {}
  841. return shared.get("enabled") is True, shared.get("send") is True
  842. def _shared_metrics_menu_label(config: dict) -> str:
  843. """Menu row for shared metrics. Collect-only is an answer the offer no longer has; a profile
  844. that chose it earlier keeps it, and the row names it rather than reading "off" while it collects."""
  845. enabled, send = _shared_metrics_state(config)
  846. state = "off" if not enabled else ("sending to Nous" if send else "collecting locally")
  847. return f"Configure shared metrics ({state})"
  848. def _configure_shared_metrics_interactive(config: dict) -> None:
  849. """Toggle shared-metrics collection/sending via the setup wizard prompt (single home for the consent rules)."""
  850. from hermes_cli.setup import setup_telemetry
  851. before = _shared_metrics_state(config)
  852. setup_telemetry(config)
  853. if _shared_metrics_state(config) != before:
  854. save_config(config)
  855. def _print_toolset_diff(added: set[str], removed: set[str], *, indent: str = " ") -> None:
  856. """Print ``+ label`` / ``- label`` lines for a checklist change."""
  857. for ts in sorted(added):
  858. print(color(f"{indent}+ {_toolset_label(ts)}", Colors.GREEN))
  859. for ts in sorted(removed):
  860. print(color(f"{indent}- {_toolset_label(ts)}", Colors.RED))
  861. def _toolsets_needing_setup(new_enabled: set[str], config: dict) -> list[str]:
  862. """Selected toolsets still missing provider/API-key setup, sorted (opened even when the selection is unchanged)."""
  863. return [
  864. ts_key for ts_key in sorted(new_enabled)
  865. if _is_configurable(ts_key) and _toolset_needs_configuration_prompt(ts_key, config, force_fresh=True)
  866. ]
  867. def _configure_newly_added(added: set[str], already: set[str], config: dict) -> None:
  868. """Configure newly enabled toolsets that need keys, skipping those already handled."""
  869. for ts_key in _toolsets_needing_setup(added - already, config):
  870. _configure_toolset(ts_key, config)
  871. def _platform_menu_label(config: dict, pkey: str) -> str:
  872. count = len(_current_platform_tools(config, pkey))
  873. total = len(_get_effective_configurable_toolsets())
  874. return f"Configure {PLATFORMS[pkey]['label']} ({count}/{total} enabled)"
  875. def _print_tools_summary(config: dict, enabled_platforms: list[str]) -> None:
  876. """``hermes tools --summary``: enabled toolsets per platform, non-interactive."""
  877. total = len(_get_effective_configurable_toolsets())
  878. print(color("☤ Tool Summary", Colors.CYAN, Colors.BOLD))
  879. print()
  880. for pkey, enabled in _platform_toolset_summary(config, enabled_platforms).items():
  881. print(color(f" {PLATFORMS[pkey]['label']}", Colors.BOLD) + color(f" ({len(enabled)}/{total})", Colors.DIM))
  882. for ts_key in sorted(enabled):
  883. print(color(f" ✓ {_toolset_label(ts_key)}", Colors.GREEN))
  884. if not enabled:
  885. print(color(" (none enabled)", Colors.DIM))
  886. print()
  887. def _configure_list(to_configure: list[str], config: dict, *, selected: bool = True) -> None:
  888. """Announce then configure each toolset in ``to_configure``."""
  889. if not to_configure:
  890. return
  891. print()
  892. what = "selected tool(s)" if selected else "tool(s)"
  893. print(color(f" Configuring {len(to_configure)} {what}:", Colors.YELLOW))
  894. for ts_key in to_configure:
  895. print(color(f" • {_toolset_label(ts_key)}", Colors.DIM))
  896. print(color(" You can skip any tool you don't need right now.", Colors.DIM))
  897. print()
  898. for ts_key in to_configure:
  899. _configure_toolset(ts_key, config)
  900. def _checklist_diff(new_enabled: set[str], prev: set[str], platform: str) -> tuple[set[str], set[str]]:
  901. """``(added, removed)`` scoped to the checklist universe, so read-time toolsets (MCP names) the user never
  902. saw a checkbox for don't print as spurious removals."""
  903. universe = _checklist_toolset_keys(platform)
  904. return (new_enabled - prev) & universe, (prev - new_enabled) & universe
  905. def _first_install_flow(config: dict, enabled_platforms: list[str]) -> None:
  906. """Fresh install: one checklist per platform, no menu, keys prompted for every enabled tool."""
  907. for pkey in enabled_platforms:
  908. pinfo = PLATFORMS[pkey]
  909. current_enabled = _current_platform_tools(config, pkey)
  910. new_enabled = _prompt_toolset_checklist(pinfo["label"], current_enabled - _DEFAULT_OFF_TOOLSETS, pkey)
  911. _print_toolset_diff(*_checklist_diff(new_enabled, current_enabled, pkey))
  912. auto_configured = apply_nous_managed_defaults(config, enabled_toolsets=new_enabled, force_fresh=True)
  913. for ts_key in sorted(auto_configured):
  914. label = next((l for k, l, _ in CONFIGURABLE_TOOLSETS if k == ts_key), ts_key)
  915. print(color(f" ✓ {label}: using your Nous subscription defaults", Colors.GREEN))
  916. # Walk through ALL selected tools with provider options or key requirements, so browser (Local vs
  917. # Browserbase), TTS (Edge vs OpenAI vs ElevenLabs), etc. are shown even when a free provider exists.
  918. _configure_list(
  919. [ts for ts in sorted(new_enabled) if _is_configurable(ts) and ts not in auto_configured],
  920. config, selected=False)
  921. _save_platform_tools(config, pkey, new_enabled)
  922. save_config(config)
  923. print(color(f" ✓ Saved {pinfo['label']} tool configuration", Colors.GREEN))
  924. print()
  925. def _current_platform_tools(config: dict, pkey: str) -> set[str]:
  926. return _get_platform_tools(config, pkey, include_default_mcp_servers=False)
  927. def _apply_platform_checklist(config: dict, pkey: str, new_enabled: set[str], prev: set[str], already: set[str],
  928. *, indent: str = " ", header: bool = False) -> None:
  929. """Print the diff, configure newly added toolsets not in ``already``, and write the platform list.
  930. Keys for newly enabled tools not already handled by the selected-tool pass, so a tool enabled globally
  931. but lacking provider config doesn't drop the user back to the main menu."""
  932. added, removed = _checklist_diff(new_enabled, prev, pkey)
  933. if header and (added or removed):
  934. print(color(f" {PLATFORMS[pkey]['label']}:", Colors.DIM))
  935. _print_toolset_diff(added, removed, indent=indent)
  936. _configure_newly_added(added, already, config)
  937. _save_platform_tools(config, pkey, new_enabled)
  938. def _configure_platforms(config: dict, platform_keys: list[str], *, all_platforms: bool = False) -> bool:
  939. """Checklist + key setup + save for one platform, or for every platform at once (the 'Configure all
  940. platforms (global)' menu entry). Returns True when config was saved."""
  941. label = "All platforms" if all_platforms else PLATFORMS[platform_keys[0]]["label"]
  942. current = {pk: _current_platform_tools(config, pk) for pk in platform_keys}
  943. all_current = set().union(*current.values())
  944. new_enabled = _prompt_toolset_checklist(label, all_current, force_fresh=True)
  945. selected_to_configure = _toolsets_needing_setup(new_enabled, config)
  946. _configure_list(selected_to_configure, config)
  947. if new_enabled == all_current and not selected_to_configure:
  948. print(color(" No changes" if all_platforms else f" No changes to {label}", Colors.DIM))
  949. return False
  950. for pk in platform_keys:
  951. # Global: re-read after each save — reconciling agent.disabled_toolsets for one platform can change
  952. # what the next platform resolves to. Single platform: diff against the pre-checklist snapshot.
  953. prev = _current_platform_tools(config, pk) if all_platforms else current[pk]
  954. _apply_platform_checklist(config, pk, new_enabled, prev, set(selected_to_configure),
  955. indent=" " if all_platforms else " ", header=all_platforms)
  956. save_config(config)
  957. print(color(" ✓ Saved configuration for all platforms" if all_platforms else f" ✓ Saved {label} configuration",
  958. Colors.GREEN))
  959. return True
  960. def tools_command(args=None, first_install: bool = False, config: dict | None = None):
  961. """Entry point for `hermes tools` / `hermes setup tools`. ``first_install`` skips the menu (checklist + key
  962. prompts); a wizard-passed ``config`` receives platform_toolsets so its final save_config() keeps them."""
  963. if config is None:
  964. config = load_config()
  965. enabled_platforms = _get_enabled_platforms()
  966. print()
  967. if getattr(args, "summary", False):
  968. _print_tools_summary(config, enabled_platforms)
  969. return
  970. print(color("☤ Hermes Tool Configuration", Colors.CYAN, Colors.BOLD))
  971. print(color(" Enable or disable tools per platform.", Colors.DIM))
  972. print(color(" Tools that need API keys will be configured when enabled.", Colors.DIM))
  973. print(color(" Guide: https://hermes-agent.nousresearch.com/docs/user-guide/features/tools", Colors.DIM))
  974. print()
  975. if first_install:
  976. _first_install_flow(config, enabled_platforms)
  977. return
  978. # Returning user: platform menu loop. Per-platform rows first, then the extras in this order.
  979. platform_keys = list(enabled_platforms)
  980. platform_choices = [_platform_menu_label(config, pkey) for pkey in platform_keys]
  981. def _add_row(label: str, present: bool = True) -> int:
  982. if not present:
  983. return -1
  984. platform_choices.append(label)
  985. return len(platform_choices) - 1
  986. global_idx = _add_row("Configure all platforms (global)", len(platform_keys) > 1)
  987. reconfig_idx = _add_row("Reconfigure an existing tool's provider or API key")
  988. metrics_idx = _add_row(_shared_metrics_menu_label(config))
  989. mcp_idx = _add_row("Configure MCP server tools", bool(config.get("mcp_servers")))
  990. done_idx = _add_row("Done")
  991. while True:
  992. idx = _prompt_choice("Select an option:", platform_choices, default=0)
  993. if idx == done_idx:
  994. break
  995. if idx == reconfig_idx:
  996. _reconfigure_tool(config, force_fresh=True)
  997. elif idx == metrics_idx:
  998. _configure_shared_metrics_interactive(config)
  999. platform_choices[metrics_idx] = _shared_metrics_menu_label(config)
  1000. elif idx == mcp_idx:
  1001. _configure_mcp_tools_interactive(config)
  1002. elif idx == global_idx:
  1003. if _configure_platforms(config, platform_keys, all_platforms=True):
  1004. for ci, pk in enumerate(platform_keys):
  1005. platform_choices[ci] = _platform_menu_label(config, pk)
  1006. else:
  1007. _configure_platforms(config, [platform_keys[idx]])
  1008. platform_choices[idx] = _platform_menu_label(config, platform_keys[idx])
  1009. print()
  1010. print()
  1011. from hermes_constants import display_hermes_home
  1012. print(color(f" Tool configuration saved to {display_hermes_home()}/config.yaml", Colors.DIM))
  1013. print(color(" Changes take effect on next 'hermes' or gateway restart.", Colors.DIM))
  1014. print()