tools.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. """Toolset / terminal-backend dashboard routes.
  2. The toolset/terminal catalogs and helpers stay in web_server (some are defined
  3. *after* this router's mount point) — reached via the late-binding seam so
  4. monkeypatching on web_server stays authoritative.
  5. """
  6. import asyncio
  7. import subprocess
  8. import sys
  9. from typing import Any, Dict, List, Optional
  10. from fastapi import APIRouter, HTTPException
  11. from hermes_cli.web_deps import late
  12. from hermes_cli.web_server_profiles import _plugin_terminal_backend_rows
  13. from starlette.concurrency import run_in_threadpool
  14. from hermes_cli.web_models import (
  15. TerminalBackendSelect, ToolsetEnvUpdate, ToolsetModelSelect, ToolsetPostSetup,
  16. ToolsetProviderSelect, ToolsetToggle)
  17. from hermes_cli.web_routers._common import (
  18. _CONFIG_MUTATION_LOCK, _profile_cli_args, _profile_scope, _spawn_hermes_action,
  19. config_write_scope, log as _log, scoped_to_thread, spawn_profile_action)
  20. router = APIRouter()
  21. load_config = late("load_config", "hermes_cli.config")
  22. save_config = late("save_config", "hermes_cli.config")
  23. def _env_value(name: str) -> str:
  24. """``get_env_value`` that never raises (empty string on any failure)."""
  25. try:
  26. from hermes_cli.config import get_env_value
  27. return get_env_value(name) or ""
  28. except Exception:
  29. return ""
  30. def _terminal_cfg_value(terminal_cfg: dict, key: str, env_var: str) -> str:
  31. """Read a terminal.* setting from config.yaml, falling back to its env var."""
  32. value = terminal_cfg.get(key)
  33. if value is not None and str(value).strip():
  34. return str(value).strip()
  35. return _env_value(env_var).strip()
  36. def _terminal_backend_rows() -> list[dict[str, str]]:
  37. """Built-in picker rows plus plugin-registered backends, computed per request
  38. so a plugin installed after server start still shows up."""
  39. from hermes_cli.web_server_profiles import _TERMINAL_BACKENDS
  40. return [*_TERMINAL_BACKENDS, *_plugin_terminal_backend_rows()]
  41. def _probe_docker_backend(_cfg) -> tuple:
  42. """Health-check the docker terminal backend the same way the agent resolves it.
  43. ``find_docker()`` honors ``HERMES_DOCKER_BINARY``, then ``docker`` / ``podman``
  44. on PATH. The probe uses ``version`` (not ``info --format {{.ServerVersion}}``)
  45. because Podman has no ServerVersion field and the agent already probes with
  46. ``version``.
  47. """
  48. from tools.environments.docker import docker_runtime_name, docker_runtime_start_hint, find_docker
  49. from tools.environments.remote_common import run_capture
  50. docker_exe = find_docker()
  51. if not docker_exe:
  52. return (
  53. "needs_setup",
  54. "Docker CLI not found — install Docker Desktop, docker-ce, or Podman.",
  55. )
  56. runtime = docker_runtime_name(docker_exe)
  57. try:
  58. if run_capture([docker_exe, "version"], timeout=2).returncode == 0:
  59. return ("ready", "")
  60. return ("needs_setup", f"{runtime} not reachable — {docker_runtime_start_hint(docker_exe)}.")
  61. except subprocess.TimeoutExpired:
  62. return ("needs_setup", f"{runtime} not responding (timed out).")
  63. except Exception as exc:
  64. return ("unavailable", f"{runtime} probe failed: {exc}")
  65. def _probe_ssh_backend(terminal_cfg: dict) -> tuple:
  66. host = _terminal_cfg_value(terminal_cfg, "ssh_host", "TERMINAL_SSH_HOST")
  67. user = _terminal_cfg_value(terminal_cfg, "ssh_user", "TERMINAL_SSH_USER")
  68. missing = [k for k, v in (("terminal.ssh_host", host), ("terminal.ssh_user", user)) if not v]
  69. if missing:
  70. return (
  71. "needs_setup",
  72. f"Set {' and '.join(missing)} in config.yaml (or the matching TERMINAL_SSH_* env vars).",
  73. )
  74. return ("ready", f"{user}@{host}")
  75. def _probe_modal_backend(_cfg) -> tuple:
  76. try:
  77. from tools.tool_backend_helpers import has_direct_modal_credentials
  78. if has_direct_modal_credentials():
  79. return ("ready", "")
  80. except Exception:
  81. pass
  82. if _env_value("MODAL_TOKEN_ID") and _env_value("MODAL_TOKEN_SECRET"):
  83. return ("ready", "")
  84. return (
  85. "needs_setup",
  86. "Modal credentials not found — set MODAL_TOKEN_ID and MODAL_TOKEN_SECRET (or run `modal setup`).",
  87. )
  88. def _probe_daytona_backend(_cfg) -> tuple:
  89. if _env_value("DAYTONA_API_KEY"):
  90. return ("ready", "")
  91. return ("needs_setup", "Set DAYTONA_API_KEY to use the Daytona backend.")
  92. _BACKEND_PROBES = {
  93. "local": lambda _cfg: ("ready", ""),
  94. "docker": _probe_docker_backend,
  95. "ssh": _probe_ssh_backend,
  96. "modal": _probe_modal_backend,
  97. "daytona": _probe_daytona_backend,
  98. }
  99. def _probe_terminal_backend(name: str, terminal_cfg: dict) -> tuple:
  100. """Return ``(status, detail)`` for one backend. Never raises."""
  101. try:
  102. probe = _BACKEND_PROBES.get(name)
  103. if probe is not None:
  104. return probe(terminal_cfg)
  105. try:
  106. from agent.terminal_env_registry import get_provider
  107. provider = get_provider(name)
  108. if provider is not None:
  109. return provider.probe()
  110. except Exception:
  111. pass
  112. return ("unavailable", f"Unknown backend: {name}")
  113. except Exception as exc: # pragma: no cover — belt-and-braces guard
  114. return ("unavailable", f"Probe failed: {exc}")
  115. # Toolsets whose backends carry a selectable model catalog, mapped to the
  116. # config.yaml section their `model` key lives in. Mirrors the CLI's
  117. # post-selection model pickers in tools_config.py.
  118. _MODEL_CATALOG_TOOLSETS = {"image_gen": "image_gen", "video_gen": "video_gen"}
  119. def _resolve_toolset_model_plugin(ts_key: str, provider_row: dict) -> Optional[str]:
  120. """Map a provider picker row to its model-catalog plugin name.
  121. Plugin-backed rows carry ``image_gen_plugin_name`` / ``video_gen_plugin_name``;
  122. a managed image row's ``imagegen_backend`` names its catalog plugin.
  123. """
  124. if ts_key == "image_gen":
  125. return provider_row.get("image_gen_plugin_name") or provider_row.get("imagegen_backend")
  126. if ts_key == "video_gen":
  127. return provider_row.get("video_gen_plugin_name")
  128. return None
  129. def _toolset_model_catalog(ts_key: str, plugin_name: str, config: dict):
  130. """Return ``(catalog_dict, default_model)`` for a toolset's plugin backend or, for an image row's
  131. ``imagegen_backend`` (``fal``, the managed ``nous`` union), that backend's catalog."""
  132. from hermes_cli.tools_config import IMAGEGEN_BACKENDS, _plugin_image_gen_catalog, _plugin_video_gen_catalog
  133. if ts_key == "image_gen":
  134. backend = IMAGEGEN_BACKENDS.get(plugin_name)
  135. if backend:
  136. return backend["catalog_fn"](config)
  137. return _plugin_image_gen_catalog(plugin_name)
  138. return _plugin_video_gen_catalog(plugin_name)
  139. def _category_providers(ts_key: str, config: dict) -> list:
  140. """Visible provider rows for a toolset's category (fresh entitlement read)."""
  141. from hermes_cli.tools_config import TOOL_CATEGORIES, _visible_providers
  142. cat = TOOL_CATEGORIES.get(ts_key)
  143. return _visible_providers(cat, config, force_fresh=True) if cat else []
  144. def _find_toolset_provider_row(
  145. ts_key: str, config: dict, provider: Optional[str]) -> Optional[dict]:
  146. """Resolve a provider picker row by name, or the active row when omitted."""
  147. from hermes_cli.tools_config import _is_provider_active
  148. rows = _category_providers(ts_key, config)
  149. if provider:
  150. return next((p for p in rows if p.get("name") == provider), None)
  151. return next((p for p in rows if _is_provider_active(p, config, force_fresh=True)), None)
  152. def _require_known_toolset(name: str) -> None:
  153. """400 for toolset keys outside the effective configurable set. Call it inside the target
  154. profile's scope, like ``GET /api/tools/toolsets``: plugin toolsets are registered per profile."""
  155. from hermes_cli.tools_config import _get_effective_configurable_toolsets
  156. if name not in {ts_key for ts_key, _, _ in _get_effective_configurable_toolsets()}:
  157. raise _bad_request(f"Unknown toolset: {name}")
  158. def _dict_section(config: dict, key: str) -> dict:
  159. """``config[key]`` as a dict, replacing a non-dict value in place."""
  160. section = config.setdefault(key, {})
  161. if not isinstance(section, dict):
  162. section = {}
  163. config[key] = section
  164. return section
  165. def _bad_request(detail: str) -> HTTPException:
  166. return HTTPException(status_code=400, detail=detail)
  167. def _no_models(name: str) -> dict:
  168. return {"name": name, "has_models": False, "models": [], "current": None, "default": None}
  169. @router.get("/api/tools/toolsets")
  170. async def get_toolsets(profile: Optional[str] = None):
  171. from hermes_cli.tools_config import (
  172. _CONFIG_ONLY_TOOLSETS, _get_effective_configurable_toolsets, _get_platform_tools,
  173. _toolset_configuration_platform, _toolset_has_keys, get_nous_subscription_features,
  174. gui_toolset_label)
  175. from hermes_cli.platforms import platform_label
  176. from toolsets import resolve_toolset
  177. from utils import is_truthy_value
  178. def _read():
  179. with _profile_scope(profile):
  180. config = load_config()
  181. toolset_rows = _get_effective_configurable_toolsets()
  182. target_platforms = {
  183. _toolset_configuration_platform(name) for name, _, _ in toolset_rows}
  184. enabled_by_platform = {
  185. platform: _get_platform_tools(config, platform, include_default_mcp_servers=False)
  186. for platform in target_platforms}
  187. features = get_nous_subscription_features(config)
  188. # Credential presence resolves through the profile's secret scope: outside this block
  189. # it read the dashboard process env (another profile's keys) or fails closed.
  190. configured = {name: _toolset_has_keys(name, config, features=features) for name, _, _ in toolset_rows}
  191. return config, toolset_rows, enabled_by_platform, configured
  192. config, toolset_rows, enabled_by_platform, configured = await run_in_threadpool(_read)
  193. result = []
  194. for name, label, desc in toolset_rows:
  195. try:
  196. tools = sorted(set(resolve_toolset(name)))
  197. except Exception:
  198. tools = []
  199. target_platform = _toolset_configuration_platform(name)
  200. if name in _CONFIG_ONLY_TOOLSETS:
  201. # Config-only capabilities (stt) have no per-platform toolset —
  202. # their switch is their own config section (e.g. stt.enabled).
  203. section = config.get(name)
  204. section = section if isinstance(section, dict) else {}
  205. is_enabled = is_truthy_value(section.get("enabled", True), default=True)
  206. else:
  207. is_enabled = name in enabled_by_platform[target_platform]
  208. result.append({
  209. "name": name, "label": gui_toolset_label(label), "description": desc,
  210. "platform": target_platform,
  211. "platform_label": gui_toolset_label(platform_label(target_platform, target_platform)),
  212. "enabled": is_enabled, "available": is_enabled,
  213. "configured": configured[name], "tools": tools})
  214. return result
  215. @router.put("/api/tools/toolsets/{name}")
  216. async def toggle_toolset(name: str, body: ToolsetToggle, profile: Optional[str] = None):
  217. """Enable/disable a configurable toolset for its configuration platform
  218. (``platform_toolsets.cli`` for most; platform-restricted toolsets target
  219. their own platform) via the same ``_save_platform_tools`` the CLI uses."""
  220. from hermes_cli.tools_config import (
  221. _CONFIG_ONLY_TOOLSETS, _get_platform_tools, _save_platform_tools,
  222. _toolset_configuration_platform)
  223. target_platform = _toolset_configuration_platform(name)
  224. scope_profile = body.profile or profile
  225. def _run():
  226. with config_write_scope(scope_profile):
  227. _require_known_toolset(name)
  228. config = load_config()
  229. if name in _CONFIG_ONLY_TOOLSETS:
  230. # Config-only capabilities (stt) toggle their own section's
  231. # ``enabled`` flag — there is no platform_toolsets entry.
  232. _dict_section(config, name)["enabled"] = bool(body.enabled)
  233. save_config(config)
  234. return
  235. enabled = set(
  236. _get_platform_tools(config, target_platform, include_default_mcp_servers=False))
  237. if body.enabled:
  238. enabled.add(name)
  239. else:
  240. enabled.discard(name)
  241. _save_platform_tools(config, target_platform, enabled)
  242. await asyncio.to_thread(_run)
  243. # Install-on-enable: a provider whose post_setup install predicate is
  244. # UNSATISFIED (cua-driver binary missing, etc.) gets the same background
  245. # install `hermes tools` runs — otherwise the toggle "saves" but the tool
  246. # never appears. Best-effort: a spawn failure never fails the toggle.
  247. post_setup_started: Optional[str] = None
  248. if body.enabled and name not in _CONFIG_ONLY_TOOLSETS:
  249. def _pending_install_key() -> Optional[str]:
  250. from hermes_cli.tools_config import (
  251. TOOL_CATEGORIES, _post_setup_already_installed, _visible_providers)
  252. cat = TOOL_CATEGORIES.get(name)
  253. if not cat:
  254. return None
  255. with _profile_scope(scope_profile):
  256. config = load_config()
  257. keys = [prov.get("post_setup") for prov in _visible_providers(cat, config)]
  258. return next((k for k in keys if k and not _post_setup_already_installed(k)), None)
  259. try:
  260. pending_key = await asyncio.to_thread(_pending_install_key)
  261. if pending_key:
  262. _spawn_hermes_action(
  263. _profile_cli_args(scope_profile) + ["tools", "post-setup", pending_key],
  264. "tools-post-setup")
  265. post_setup_started = pending_key
  266. except Exception:
  267. _log.exception("install-on-enable post-setup spawn failed for %s", name)
  268. return {
  269. "ok": True, "name": name, "platform": target_platform, "enabled": body.enabled,
  270. "post_setup_started": post_setup_started}
  271. @router.get("/api/tools/toolsets/{name}/config")
  272. async def get_toolset_config(name: str, profile: Optional[str] = None):
  273. """Provider matrix + key status for a toolset's config panel (the CLI picker
  274. rows, each env var annotated ``is_set``); no category -> ``has_category: false``."""
  275. from hermes_cli.tools_config import (
  276. TOOL_CATEGORIES, _is_provider_active, _visible_providers, provider_readiness_status,
  277. web_provider_capabilities)
  278. from hermes_cli.config import get_env_value
  279. from hermes_cli.nous_subscription import get_nous_subscription_features
  280. def _read():
  281. with _profile_scope(profile):
  282. _require_known_toolset(name)
  283. config = load_config()
  284. cat = TOOL_CATEGORIES.get(name)
  285. providers = []
  286. active_provider = None
  287. if cat:
  288. # Entitlement state fetched once for the whole matrix.
  289. features = get_nous_subscription_features(config, force_fresh=True)
  290. for prov in _visible_providers(cat, config, force_fresh=True):
  291. env_vars = [
  292. {
  293. "key": e["key"], "prompt": e.get("prompt", e["key"]),
  294. "url": e.get("url"), "default": e.get("default"),
  295. "is_set": bool(get_env_value(e["key"]))}
  296. for e in prov.get("env_vars", [])]
  297. # Same active-provider determination as the CLI picker, so the
  298. # GUI highlights the provider actually written to config.
  299. is_active = _is_provider_active(prov, config, force_fresh=True)
  300. if is_active and active_provider is None:
  301. active_provider = prov["name"]
  302. row = {
  303. "name": prov["name"],
  304. "badge": prov.get("badge", ""),
  305. "tag": prov.get("tag", ""),
  306. "env_vars": env_vars,
  307. "post_setup": prov.get("post_setup"),
  308. "requires_nous_auth": bool(prov.get("requires_nous_auth")),
  309. # Set on the "Nous Subscription" rows: the GUI tells the gateway row apart
  310. # from a BYOK row of the same vendor (both carry web_backend "firecrawl").
  311. "managed_nous_feature": prov.get("managed_nous_feature"),
  312. "is_active": is_active,
  313. # Server-side readiness: zero-env-var rows are NOT
  314. # automatically ready (logged-out Nous rows, never-run
  315. # post_setup installs).
  316. "status": provider_readiness_status(
  317. prov, config, features=features, is_active=is_active)}
  318. if name == "web" and prov.get("web_backend"):
  319. # web is two capabilities (search/extract); surface each
  320. # row's backend key + capabilities for per-capability selection.
  321. row["web_backend"] = prov["web_backend"]
  322. row["capabilities"] = web_provider_capabilities(prov["web_backend"])
  323. if name == "tts" and prov.get("tts_provider"):
  324. # Key written to tts.provider; doubles as the config section
  325. # (tts.<key>.*) holding the provider's voice/model settings.
  326. row["tts_provider"] = prov["tts_provider"]
  327. providers.append(row)
  328. payload = {
  329. "name": name, "has_category": cat is not None, "providers": providers,
  330. "active_provider": active_provider}
  331. if name == "web":
  332. # Resolve active backends exactly as the web_search/web_extract dispatchers do, so badges
  333. # reflect what a call would hit now — plus whether that call rides the Nous Tool Gateway
  334. # or the user's own key (the managed and BYOK Firecrawl rows share one backend name).
  335. try:
  336. from plugins.web.firecrawl.provider import is_managed_route
  337. from tools.web_tools import _get_extract_backend, _get_search_backend, _managed_web_search
  338. search_backend = _get_search_backend()
  339. extract_backend = _get_extract_backend()
  340. search_managed = _managed_web_search() or (
  341. search_backend == "firecrawl" and is_managed_route("search"))
  342. extract_managed = extract_backend == "firecrawl" and is_managed_route("extract")
  343. except Exception:
  344. search_backend = extract_backend = None
  345. search_managed = extract_managed = False
  346. payload["active_search_backend"] = search_backend
  347. payload["active_extract_backend"] = extract_backend
  348. payload["search_via_nous"] = bool(search_managed)
  349. payload["extract_via_nous"] = bool(extract_managed)
  350. return payload
  351. return await asyncio.to_thread(_read)
  352. @router.get("/api/tools/toolsets/{name}/models")
  353. async def get_toolset_models(
  354. name: str, provider: Optional[str] = None, profile: Optional[str] = None):
  355. """Model catalog for a toolset backend (image/video gen) — the GUI
  356. counterpart of the CLI model picker. ``provider`` names a picker row
  357. (default: the active provider); no catalog -> ``has_models: false``."""
  358. section = _MODEL_CATALOG_TOOLSETS.get(name)
  359. if section is None:
  360. return _no_models(name)
  361. def _read():
  362. with _profile_scope(profile):
  363. config = load_config()
  364. row = _find_toolset_provider_row(name, config, provider)
  365. plugin = _resolve_toolset_model_plugin(name, row) if row else None
  366. if not plugin:
  367. return None
  368. catalog, default_model = _toolset_model_catalog(name, plugin, config)
  369. section_cfg = config.get(section)
  370. current = None
  371. if isinstance(section_cfg, dict):
  372. raw = section_cfg.get("model")
  373. if isinstance(raw, str) and raw.strip():
  374. current = raw.strip()
  375. if current not in catalog:
  376. current = default_model if default_model in catalog else None
  377. models = [
  378. {
  379. "id": model_id, "display": meta.get("display", model_id),
  380. "speed": meta.get("speed", ""), "strengths": meta.get("strengths", ""),
  381. "price": meta.get("price", "")}
  382. for model_id, meta in catalog.items()]
  383. return {
  384. "name": name, "has_models": bool(models), "provider": row.get("name"),
  385. "plugin": plugin, "models": models, "current": current, "default": default_model}
  386. return await asyncio.to_thread(_read) or _no_models(name)
  387. @router.put("/api/tools/toolsets/{name}/model")
  388. async def select_toolset_model(
  389. name: str, body: ToolsetModelSelect, profile: Optional[str] = None):
  390. """Persist a backend model selection (``image_gen.model`` /
  391. ``video_gen.model``), validated against the resolved backend's catalog."""
  392. section = _MODEL_CATALOG_TOOLSETS.get(name)
  393. if section is None:
  394. raise _bad_request(f"Toolset has no model catalog: {name}")
  395. model_id = (body.model or "").strip()
  396. if not model_id:
  397. raise _bad_request("model is required")
  398. def _run():
  399. with config_write_scope(body.profile or profile):
  400. config = load_config()
  401. row = _find_toolset_provider_row(name, config, body.provider)
  402. plugin = _resolve_toolset_model_plugin(name, row) if row else None
  403. if not plugin:
  404. raise _bad_request(f"No model-capable backend is active for {name}")
  405. catalog, _default = _toolset_model_catalog(name, plugin, config)
  406. if model_id not in catalog:
  407. raise _bad_request(f"Unknown model {model_id!r} for backend {plugin!r}")
  408. _dict_section(config, section)["model"] = model_id
  409. save_config(config)
  410. return plugin
  411. plugin = await asyncio.to_thread(_run)
  412. return {"ok": True, "name": name, "model": model_id, "plugin": plugin}
  413. @router.put("/api/tools/toolsets/{name}/provider")
  414. async def select_toolset_provider(
  415. name: str, body: ToolsetProviderSelect, profile: Optional[str] = None):
  416. """Persist a provider selection via ``apply_provider_selection`` (shared with
  417. ``hermes tools``, so both write identical keys).
  418. ``web`` only: ``capability`` ('search' | 'extract') writes
  419. ``web.<capability>_backend`` (the override the dispatchers resolve first);
  420. omitted -> legacy ``web.backend``. Managed Nous rows report Portal
  421. entitlement (``needs_nous_auth`` + ``feature``): the GUI has no inline
  422. login, so an unentitled selection would write config and never activate.
  423. """
  424. from hermes_cli.tools_config import apply_provider_selection, web_provider_capabilities
  425. from hermes_cli.nous_subscription import (
  426. MANAGED_FEATURE_COVERAGE_CATEGORY, get_nous_subscription_features)
  427. if body.capability is not None:
  428. if name != "web":
  429. raise _bad_request("capability selection is only supported for the web toolset")
  430. if body.capability not in ("search", "extract"):
  431. raise _bad_request(
  432. f"Unknown capability: {body.capability!r} (expected 'search' or 'extract')")
  433. def _provider_row(config):
  434. return next(
  435. (p for p in _category_providers(name, config) if p.get("name") == body.provider), None)
  436. def _run():
  437. with _profile_scope(body.profile or profile):
  438. _require_known_toolset(name)
  439. with _CONFIG_MUTATION_LOCK:
  440. config = load_config()
  441. if body.capability is not None:
  442. # Per-capability path writes web.<capability>_backend only —
  443. # web.backend is untouched so the other capability keeps
  444. # resolving through the shared fallback chain.
  445. prov = _provider_row(config)
  446. if prov is None:
  447. raise _bad_request(
  448. f"Unknown provider {body.provider!r} for toolset {name!r}")
  449. backend = prov.get("web_backend")
  450. if not backend:
  451. raise _bad_request(f"Provider {body.provider!r} has no web backend key")
  452. if body.capability not in web_provider_capabilities(backend):
  453. raise _bad_request(f"{body.provider} does not support {body.capability}")
  454. # The managed row's web_backend names the vendor serving it ("firecrawl"); writing that
  455. # would read as the user's OWN Firecrawl key. Its pin is "nous" (gateway route).
  456. from tools.tool_backend_helpers import NOUS_MANAGED_PROVIDER
  457. _dict_section(config, "web")[f"{body.capability}_backend"] = (
  458. NOUS_MANAGED_PROVIDER if prov.get("managed_nous_feature") else backend)
  459. else:
  460. try:
  461. apply_provider_selection(name, body.provider, config)
  462. except KeyError as exc:
  463. raise _bad_request(str(exc).strip('"'))
  464. save_config(config)
  465. response: dict[str, Any] = {"ok": True, "name": name, "provider": body.provider}
  466. if body.capability is not None:
  467. response["capability"] = body.capability
  468. # Entitlement check for managed Nous rows (mirrors the CLI's
  469. # ensure_nous_portal_access gate). Hits the Portal, so it runs AFTER
  470. # releasing the mutation lock — still in the worker thread + scope.
  471. row = _provider_row(config)
  472. managed_feature = (row or {}).get("managed_nous_feature")
  473. if managed_feature:
  474. features = get_nous_subscription_features(config, force_fresh=True)
  475. acct = features.account_info
  476. category = MANAGED_FEATURE_COVERAGE_CATEGORY.get(managed_feature)
  477. entitled = bool(
  478. acct
  479. and acct.logged_in
  480. and (
  481. acct.tool_gateway_entitled_for(category)
  482. if category
  483. else acct.tool_gateway_entitled))
  484. if not entitled:
  485. response["needs_nous_auth"] = True
  486. response["feature"] = managed_feature
  487. return response
  488. return await asyncio.to_thread(_run)
  489. @router.put("/api/tools/toolsets/{name}/env")
  490. async def save_toolset_env(name: str, body: ToolsetEnvUpdate, profile: Optional[str] = None):
  491. """Persist API keys to ``.env`` via ``save_env_value``. Keys are validated
  492. against the union of the category's visible-provider ``env_vars`` so this
  493. can't write arbitrary env vars; a blank value means "leave unchanged"."""
  494. from hermes_cli.config import get_env_value, save_env_value
  495. def _run():
  496. with _profile_scope(body.profile or profile):
  497. _require_known_toolset(name)
  498. config = load_config()
  499. allowed: set[str] = {
  500. e["key"]
  501. for prov in _category_providers(name, config)
  502. for e in prov.get("env_vars", [])}
  503. unknown = [k for k in body.env if k not in allowed]
  504. if unknown:
  505. raise _bad_request(
  506. f"Unknown env var(s) for toolset {name}: {', '.join(sorted(unknown))}")
  507. saved: list[str] = []
  508. skipped: list[str] = []
  509. for key, value in body.env.items():
  510. if value and value.strip():
  511. try:
  512. save_env_value(key, value.strip())
  513. except ValueError as exc:
  514. raise _bad_request(str(exc))
  515. saved.append(key)
  516. else:
  517. skipped.append(key)
  518. status = {k: bool(get_env_value(k)) for k in allowed}
  519. return saved, skipped, status
  520. saved, skipped, status = await asyncio.to_thread(_run)
  521. return {"ok": True, "name": name, "saved": saved, "skipped": skipped, "is_set": status}
  522. @router.post("/api/tools/toolsets/{name}/post-setup")
  523. async def run_toolset_post_setup(
  524. name: str, body: ToolsetPostSetup, profile: Optional[str] = None):
  525. """Spawn ``hermes tools post-setup <key>`` (long-running installs) as a
  526. background action tailed via ``GET /api/actions/tools-post-setup/status``;
  527. ``profile`` is threaded so hooks see the drawer's HERMES_HOME."""
  528. from hermes_cli.tools_config import valid_post_setup_keys
  529. scope_profile = body.profile or profile
  530. def _validate():
  531. # Plugin toolsets and plugin providers' post-setup keys are both per profile.
  532. _require_known_toolset(name)
  533. if body.key not in valid_post_setup_keys():
  534. raise _bad_request(f"Unknown post-setup key: {body.key}")
  535. await scoped_to_thread(scope_profile, _validate)
  536. result = spawn_profile_action(
  537. scope_profile, ["tools", "post-setup", body.key], "tools-post-setup",
  538. log_msg="Failed to spawn tools post-setup", prefix="Failed to run post-setup")
  539. result["key"] = body.key
  540. return result
  541. @router.get("/api/tools/terminal/backends")
  542. async def get_terminal_backends(profile: Optional[str] = None):
  543. """Terminal backend rows with health probes: ``status`` is ``ready`` /
  544. ``needs_setup`` / ``unavailable``; a probe failure is a status, never an
  545. error response."""
  546. def _read():
  547. with _profile_scope(profile):
  548. config = load_config()
  549. terminal_cfg = config.get("terminal")
  550. if not isinstance(terminal_cfg, dict):
  551. terminal_cfg = {}
  552. rows = _terminal_backend_rows()
  553. active = str(terminal_cfg.get("backend") or "local").strip().lower()
  554. if active not in {row["name"] for row in rows}:
  555. active = "local"
  556. backends = []
  557. for row in rows:
  558. status, detail = _probe_terminal_backend(row["name"], terminal_cfg)
  559. backends.append({
  560. "name": row["name"], "label": row["label"], "description": row["description"],
  561. "active": row["name"] == active, "status": status, "detail": detail})
  562. return {"active": active, "backends": backends}
  563. return await asyncio.to_thread(_read)
  564. @router.put("/api/tools/terminal/backend")
  565. async def select_terminal_backend(
  566. body: TerminalBackendSelect, profile: Optional[str] = None):
  567. """Persist ``terminal.backend``. A backend that still needs setup is
  568. allowed — the picker shows guidance instead of blocking, like the CLI.
  569. Validated inside the target profile's scope, like the GET: plugin backends
  570. are registered per profile."""
  571. backend = (body.backend or "").strip().lower()
  572. def _run():
  573. with config_write_scope(body.profile or profile):
  574. valid_names = {row["name"] for row in _terminal_backend_rows()}
  575. if backend not in valid_names:
  576. raise _bad_request(
  577. f"Unknown terminal backend: {body.backend!r}. "
  578. f"Use one of: {', '.join(sorted(valid_names))}")
  579. config = load_config()
  580. _dict_section(config, "terminal")["backend"] = backend
  581. save_config(config)
  582. await asyncio.to_thread(_run)
  583. return {"ok": True, "backend": backend}
  584. @router.get("/api/tools/computer-use/status")
  585. async def get_computer_use_status(profile: Optional[str] = None):
  586. """Computer Use readiness for the desktop card (payload shape: see
  587. ``tools.computer_use.permissions.computer_use_status``)."""
  588. from tools.computer_use.permissions import computer_use_status
  589. return await scoped_to_thread(profile, computer_use_status)
  590. @router.post("/api/tools/computer-use/permissions/grant")
  591. async def grant_computer_use_permissions(profile: Optional[str] = None):
  592. """Spawn ``hermes computer-use permissions grant`` (macOS-only: launches
  593. CuaDriver via LaunchServices so the TCC dialog is attributed correctly).
  594. The frontend polls ``GET /api/actions/computer-use-grant/status``."""
  595. if sys.platform != "darwin":
  596. raise _bad_request("Computer Use permission grants are a macOS concept.")
  597. return spawn_profile_action(
  598. profile, ["computer-use", "permissions", "grant"], "computer-use-grant",
  599. log_msg="Failed to spawn computer-use permissions grant",
  600. prefix="Failed to request permissions")