| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173 |
- """Validation for the ``platform_toolsets`` config section."""
- import ast
- from functools import cache
- from typing import Callable, List, Optional
- from hermes_cli.platforms import PLATFORMS
- from hermes_cli.toolset_scope import toolset_allowed_for_platform
- _NO_TOOLS = "the agent will have no tools on this platform. Run `hermes tools` to reconfigure."
- def parse_platform_toolsets_value(value: object) -> Optional[list[str]]:
- """The toolset list a saved ``platform_toolsets.<platform>`` value encodes, or None.
- Older ``hermes config set`` builds stored a bare ``[...]`` argument as a plain string, so an
- explicit selection like ``'["browser", "terminal"]'`` parses as str, not list (#115866).
- Every reader and writer of the section goes through this one parser so the runtime,
- ``hermes doctor`` and ``hermes plugins enable`` agree on what the user configured. Any other
- shape (null, scalar, unparseable string) is None: the caller decides how to report it.
- """
- if isinstance(value, list):
- return value
- if isinstance(value, str) and value.strip().startswith("["):
- try:
- parsed = ast.literal_eval(value.strip())
- except (ValueError, SyntaxError):
- return None
- if isinstance(parsed, list):
- return [str(item) for item in parsed]
- return None
- def _platform_default_toolset(platform: object) -> str:
- info = PLATFORMS.get(platform)
- return info.default_toolset if info is not None else f"hermes-{platform}"
- @cache
- def _bundled_platform_names() -> frozenset:
- from hermes_cli.config import _platform_manifest_paths
- return frozenset(name for name, path, _kind, _st in _platform_manifest_paths(source="bundled") if path)
- def is_known_platform_bundle(platform: object, name: str) -> bool:
- """True when ``name`` is the ``hermes-<platform>`` bundle of a platform Hermes knows: builtin, shipped
- under ``plugins/platforms``, a platform that left core for a catalog plugin, or one a loaded plugin
- registered. Installs seeded from cli-config.yaml.example carry such rows for platforms nobody set up
- (teams, google_chat, homeassistant), inert until the plugin loads. A misspelt platform key naming its
- own bundle (``telegarm: [hermes-telegarm]``) is not known, so it is still reported."""
- if name != _platform_default_toolset(platform):
- return False
- key = str(platform)
- if key in PLATFORMS or key in _bundled_platform_names():
- return True
- from hermes_cli.left_core_migration import LEFT_CORE
- if any(feature.platform == key for feature in LEFT_CORE):
- return True
- from gateway.platform_registry import platform_registry
- return platform_registry.is_registered(key)
- def _platform_default_is_valid(
- platform: object, default_toolset: str, is_valid_toolset: Callable[[str], bool],
- is_allowed_for_platform: Callable[[str, str], bool]) -> bool:
- if is_valid_toolset(default_toolset) and is_allowed_for_platform(default_toolset, str(platform)):
- return True
- # Dynamic plugin platforms are resolved by toolsets.resolve_toolset() even though their synthesized
- # hermes-<platform> name is not in TOOLSETS.
- try:
- from gateway.platform_registry import platform_registry
- return platform_registry.is_registered(platform)
- except Exception:
- return False
- def saved_toolset_resolver(config: dict) -> Callable[[str], bool]:
- """``is_valid_toolset`` for a saved ``platform_toolsets`` list, mirroring what
- ``tools_config._get_platform_tools`` lets through: registered toolsets, any configured MCP server by
- its ``mcp-<server>`` toolset name or bare alias (neither is registered before MCP discovery; a
- disabled server is inactive, not a typo), ``hermes-<platform>`` plugin-platform bundles and the
- ``no_mcp`` sentinel. The manifest scan and the plugin lookup (which may run plugin discovery)
- happen only for a name the cheaper checks cannot place."""
- from functools import cache
- from toolsets import validate_toolset
- mcp_servers = config.get("mcp_servers")
- servers = {str(name) for name in mcp_servers} if isinstance(mcp_servers, dict) else set()
- known = servers | {f"mcp-{name}" for name in servers} | {"no_mcp"}
- @cache
- def platform_bundles() -> frozenset:
- from hermes_cli.config import _platform_plugin_manifests
- return frozenset(f"hermes-{name}" for name, _manifest in _platform_plugin_manifests())
- @cache
- def plugin_names() -> frozenset:
- from hermes_cli.plugins import get_plugin_toolset_keys_nowait, get_portable_mcp_server_names_nowait
- portable = get_portable_mcp_server_names_nowait()
- return frozenset(get_plugin_toolset_keys_nowait() | portable | {f"mcp-{name}" for name in portable})
- return lambda name: (validate_toolset(name) or name in known
- or name in platform_bundles() or name in plugin_names())
- def validate_platform_toolsets(
- platform_toolsets: object, is_valid_toolset: Callable[[str], bool],
- is_allowed_for_platform: Callable[[str, str], bool] = toolset_allowed_for_platform,
- ) -> list[str]:
- """Return human-readable warnings for a ``platform_toolsets`` mapping.
- Reports: a toolset name ``is_valid_toolset`` rejects (suggesting ``hermes-<platform>`` when that
- would have been valid); a non-empty mapping resolving to zero valid toolsets (agent would start with
- no tools); a platform with no valid toolsets, checked per-platform because the global net is
- suppressed once any platform is valid; and non-list platform values, which fall back to the platform
- default. ``is_valid_toolset`` is injected so this does no registry imports or I/O."""
- warnings: list[str] = []
- if not isinstance(platform_toolsets, dict) or not platform_toolsets:
- return warnings
- valid_count = 0
- for platform, raw in platform_toolsets.items():
- default = _platform_default_toolset(platform)
- default_valid = _platform_default_is_valid(platform, default, is_valid_toolset, is_allowed_for_platform)
- platform_valid_count = 0
- toolsets = parse_platform_toolsets_value(raw)
- if toolsets is None:
- if default_valid:
- valid_count += 1
- platform_valid_count += 1
- fallback_detail = f"falling back to '{default}'" if default_valid else f"falling back to unknown default '{default}'"
- if raw is None:
- value_detail = "a null toolset value"
- elif isinstance(raw, str):
- value_detail = f"invalid toolset value '{raw}'"
- else:
- value_detail = f"invalid {type(raw).__name__} toolset value"
- warnings.append(
- f"platform '{platform}' has {value_detail} — "
- f"{fallback_detail}. Run `hermes tools` to configure explicitly.")
- if platform_valid_count == 0:
- warnings.append(f"platform '{platform}' has no valid toolsets configured — {_NO_TOOLS}")
- continue
- for name in toolsets:
- if not isinstance(name, str) or not name:
- continue
- if not is_valid_toolset(name) and not is_known_platform_bundle(platform, name):
- hint = f" — did you mean '{default}'?" if default_valid else ""
- warnings.append(f"platform '{platform}' references unknown toolset '{name}'{hint}")
- elif is_allowed_for_platform(name, str(platform)):
- valid_count += 1
- platform_valid_count += 1
- else:
- warnings.append(
- f"platform '{platform}' references toolset '{name}' which is not available on this platform"
- )
- if platform_valid_count == 0:
- reason = "is configured with an empty toolset list" if not toolsets else "has no valid toolsets configured"
- warnings.append(f"platform '{platform}' {reason} — {_NO_TOOLS}")
- if valid_count == 0:
- warnings.append(
- "platform_toolsets resolves to zero valid toolsets — the agent will "
- "have no tools. Run `hermes tools` to reconfigure.")
- return warnings
|