Files
hermes-agent/tools/toolsets.py
alt-glitch 54bcf3c497 refactor(agent): four agent helpers move from tools/ to agent/
tools/daemon_pool.py, tools/interpreter_shutdown.py and tools/hook_output_spill.py
keep their names under agent/; tools/mcp_tool_agent.py becomes agent/tool_snapshot.py,
because it keeps a live agent's tools[] snapshot stable (refresh, publish, pin,
restore) for every tool, not only MCP ones. Each file moves whole with no line
changed; importers use the new names. agent/ calls all four, and none is a model tool.

Old names stay importable. tools.daemon_pool, tools.interpreter_shutdown and
tools.mcp_tool_agent get a MOVES key, a REQUIRED_NAMES row and a generated file at the
old path: releases v0.21.6 to v0.23.5 import them inside functions on compression,
API-error and tool-list restore paths, which a process left open across an update
reaches without having loaded them. tools.hook_output_spill gets a MOVES key and a
plugin-guide row, because the pinned catalog plugin epistemic-harness imports it.

hook_output_spill logs through getLogger(__name__), so its lines now fall under the agent
log component. tool_snapshot keeps its literal tools.mcp.client logger, a module that
stays. The other two have no logger.
2026-12-01 23:46:17 +05:30

1096 lines
59 KiB
Python

"""Named groups of tools, and which of them a session and a platform get.
**Toolsets.** The static ``TOOLSETS`` plus the toolsets plugins and MCP servers register: get, resolve,
validate.
**Selection.** ``_select_tool_names``: the tool names a session's enabled and disabled toolset lists come
to, before availability checks.
**Platform resolver.** ``_get_platform_tools``: the toolsets a platform gets from config.yaml (a saved
list, the platform's composite, plugin toolsets, MCP servers, ``agent.disabled_toolsets``).
"""
import logging
import os
from typing import Dict, List, Any, Set, Optional, Tuple
from hermes_cli.config import get_env_value
from hermes_cli.platforms import PLATFORMS as _PLATFORMS_REGISTRY
from hermes_cli.toolset_scope import (
_TOOLSET_PLATFORM_RESTRICTIONS, toolset_allowed_for_platform as _toolset_allowed_for_platform)
from hermes_cli.toolset_validation import parse_platform_toolsets_value
from tools.registry import registry as tool_registry
logger = logging.getLogger(__name__)
# Shared tool list for CLI and all messaging platform toolsets (edit once, all
# platforms follow). Desktop GUI affordances are deliberately NOT here: they live
# in `desktop_ui`/`project`, enabled per desktop-sourced session by the GUI gateway
# (tui_gateway/server.py::_load_enabled_toolsets). HA, kanban and computer_use
# entries are further gated by their tools' check_fns.
_HERMES_CORE_TOOLS = [
"web_search", "web_extract",
"terminal", "process_manage",
"read_file", "write_file", "patch", "search_files",
"vision_analyze", "image_generate",
"skills_list", "skill_view", "skill_manage",
"browser_exec", # THE browser: Python over CDP (browser-harness)
"browser_cdp", "browser_dialog",
"browser_vault", # rides with the browser; deferred by default (tools.tool_search.defer)
"text_to_speech",
"todo_list", "memory",
"session_search",
"clarify",
"execute_code", "delegate_task",
"cronjob_manage",
"kanban_show", "kanban_list",
"kanban_complete", "kanban_block", "kanban_request_review",
"kanban_request_changes",
"kanban_heartbeat",
"kanban_comment", "kanban_create", "kanban_link",
"kanban_unblock",
"kanban_attach", "kanban_attach_url", "kanban_attachments",
"computer_use",
# Service-gated connector account status and authorization links.
"manage_connections",
]
# An assignment and not a method call: a process that started on a release up to v0.23.5 keeps its
# loaded registry after an update and imports this file against it.
tool_registry.core_tool_names = frozenset(_HERMES_CORE_TOOLS)
# Webhook payloads are untrusted third-party content: no file/system execution.
_HERMES_WEBHOOK_SAFE_TOOLS = ["web_search", "web_extract", "vision_analyze", "clarify"]
def _ts(description, tools=(), includes=(), **extra):
"""One TOOLSETS entry (fresh lists per entry; extra keys such as posture pass through)."""
return {"description": description, "tools": list(tools), "includes": list(includes), **extra}
def _bundle(description, extras=()):
"""A `hermes-*` platform bundle: the shared core tools plus optional platform extras."""
return _ts(description, _HERMES_CORE_TOOLS + list(extras))
def _core_without(*excluded, kanban=True):
"""_HERMES_CORE_TOOLS minus *excluded* (and, unless kanban=True, every kanban_* tool); order preserved."""
return [t for t in _HERMES_CORE_TOOLS if t not in excluded and (kanban or not t.startswith("kanban_"))]
# Coding posture: everything you reach for while pairing on code; drops messaging,
# tts, image_gen, cron, kanban and computer-use.
_CODING_TOOLS = _core_without("image_generate", "text_to_speech", "cronjob_manage", "computer_use", kanban=False)
# Toolsets a CLIENT adds to its own sessions (tui_gateway/server.py::_gui_surface_toolsets), never
# config: another surface lacking them made no configuration choice.
CLIENT_SURFACE_TOOLSETS = frozenset({"project", "desktop_ui", "catalog"})
# Core toolset definitions: individual tools or references to other toolsets.
TOOLSETS = {
# Basic toolsets - individual tool categories
"web": _ts("Web research and content extraction tools", ["web_search", "web_extract"]),
"search": _ts("Web search only (no content extraction/scraping)", ["web_search"]),
"x_search": _ts(
"Search X (Twitter) posts and threads via xAI's built-in x_search Responses "
"tool. Read-only public X discovery; use the xurl skill for authenticated X "
"API reads and account actions. Available when xAI credentials are configured "
"(SuperGrok OAuth or XAI_API_KEY). Off by default; enable in `hermes tools` → "
"X (Twitter) Search.",
["x_search"],
),
"vision": _ts("Image analysis and vision tools", ["vision_analyze"]),
"video": _ts("Video analysis and understanding tools (opt-in, not in default toolset)", ["video_analyze"]),
"image_gen": _ts("Creative generation tools (images)", ["image_generate"]),
"video_gen": _ts(
"Video generation tools. Single ``video_generate`` tool covers text-to-video "
"(prompt only) and image-to-video (prompt + image_url), plus "
"reference-to-video. Provider-specific edit/extend workflows may appear as "
"separate tools. Configure via ``hermes tools`` → Video Generation.",
["video_generate", "xai_video_edit", "xai_video_extend"],
),
"computer_use": _ts(
"Background desktop control via cua-driver (macOS/Windows/Linux) — "
"screenshots, mouse, keyboard, scroll, drag. Does NOT steal the user's cursor "
"or keyboard focus. Works with any tool-capable model.",
["computer_use"],
),
"terminal": _ts("Terminal/command execution and process management tools", ["terminal", "process_manage"]),
"skills": _ts(
"Access, create, edit, and manage skill documents with specialized "
"instructions and knowledge",
["skills_list", "skill_view", "skill_manage"],
),
# web_search belongs to `web`/`search` only. Listing it here too let
# `disabled_toolsets: [browser]` (headless/Docker deployments) strip
# web_search from every session, because disabled toolsets are a strict
# end-of-pipeline subtraction (#17309, #64503).
"browser": _ts(
"Browser automation: drive a real browser with Python over CDP (navigate, "
"click, type, extract, screenshots), raw CDP, dialogs and vault logins",
[t for t in _HERMES_CORE_TOOLS if t.startswith("browser_")],
),
"cronjob": _ts(
"Cronjob management tool - create, list, update, pause, resume, remove, and "
"trigger scheduled tasks",
["cronjob_manage"],
),
"file": _ts(
"File manipulation tools: read, write, patch (with fuzzy matching), and "
"search (content + files)",
["read_file", "write_file", "patch", "search_files"],
),
"tts": _ts("Text-to-speech: convert text to audio with Edge TTS (free), ElevenLabs, OpenAI, or xAI", ["text_to_speech"]),
"todo": _ts("Task planning and tracking for multi-step work", ["todo_list"]),
"memory": _ts("Persistent memory across sessions (personal notes + user profile)", ["memory"]),
"context_engine": _ts("Runtime tools exposed by the active context engine"),
"session_search": _ts("Search and recall past conversations with summarization", ["session_search"]),
"connections": _ts("Remote connector discovery, execution, and account authorization", ["manage_connections"]),
"project": _ts("Desktop Projects — create/switch named workspaces (GUI sessions only)", ["desktop_project"]),
"bot_room": _ts("Verified text-only Group Chat turn capabilities"),
# GUI-renderer affordances, enabled per desktop-sourced SESSION by the GUI
# gateway (tui_gateway/server.py::_load_enabled_toolsets) — never by a
# process env var, which is blind to a desktop client on a remote backend.
"desktop_ui": _ts(
"Desktop GUI affordances — in-app terminal/browser panes, pane focus, "
"reactions, appearance (GUI sessions only)",
["read_terminal", "close_terminal", "desktop_preview", "drive_preview",
"annotate_preview", "read_window_below", "focus_pane", "react_to_message",
"gui_tour", "show_tip", "set_theme"],
),
"onboarding": _ts("First-run onboarding cards; folded in only for the onboarding chat (tui_gateway/methods_onboarding.py)",
["setup_beat"], platforms=frozenset({"desktop"})),
# ``platforms``: the session platforms this toolset exists for (TOOLSET_SESSION_PLATFORMS).
"catalog": _ts(
"Desktop catalog plugin/skill install requests through the approval card (GUI sessions only)",
["manage_catalog"],
platforms=frozenset({"desktop"}),
),
"clarify": _ts("Ask the user clarifying questions (multiple-choice or open-ended)", ["clarify"]),
"code_execution": _ts("Run Python scripts that call tools programmatically (reduces LLM round trips)", ["execute_code"]),
"delegation": _ts("Spawn subagents with isolated context for complex subtasks", ["delegate_task"]),
"kanban": _ts(
"Kanban multi-agent coordination — only active when the agent is spawned by "
"the kanban dispatcher (HERMES_KANBAN_TASK env set). The dispatcher runs "
"inside the gateway by default; see `kanban.dispatch_in_gateway` in "
"config.yaml. Lets workers mark tasks done with structured handoffs, enter "
"first-class review (request_review — not a block), return review changes, "
"block for human input, heartbeat during long ops, comment on threads, attach "
"files, and (for orchestrators) list, unblock, and fan out tasks.",
[t for t in _HERMES_CORE_TOOLS if t.startswith("kanban_")],
),
"discord": _ts("Discord read and participate tools (fetch messages, search members, create threads)", ["discord"]),
"discord_admin": _ts("Discord server management (list channels/roles, pin messages, assign roles)", ["discord_admin"]),
# Scenario-specific toolsets
"debugging": _ts("Debugging and troubleshooting toolkit", ["terminal", "process_manage"], includes=["web", "file"]),
"safe": _ts("Safe toolkit without terminal access", [], includes=["web", "vision", "image_gen"]),
# Coding posture, auto-selected in a code workspace (agent/coding_context.py).
# `desktop_ui` is folded in separately by the GUI gateway for desktop sessions.
# posture=True: per-session posture, never auto-recovered into platform tool
# config (see _recover_platform_native_toolsets below).
"coding": _ts(
"Coding-focused toolset: files, terminal, search, web docs, skills, todo, "
"delegate, vision, browser",
_CODING_TOOLS,
posture=True,
),
# Full Hermes toolsets (CLI + messaging platforms). All share the core tools;
# there is deliberately no agent-callable send_message tool. hermes-acp is the
# coding posture minus the interactive clarify UI.
"hermes-acp": _ts(
"Editor integration (VS Code, Zed, JetBrains) — coding-focused tools without "
"messaging, audio, or clarify UI",
[t for t in _CODING_TOOLS if t != "clarify"],
),
"hermes-api-server": _ts(
"OpenAI-compatible API server — full agent tools accessible via HTTP (no "
"interactive UI tools like clarify or send_message)",
_core_without("text_to_speech", "clarify", "computer_use", kanban=False),
),
"hermes-cli": _bundle("Full interactive CLI toolset - all default tools plus cronjob management"),
# Mirrors hermes-cli; `hermes tools` platform config filters it down and
# _get_platform_tools() drops _DEFAULT_OFF_TOOLSETS unless user-enabled.
"hermes-cron": _bundle("Default cron toolset - same core tools as hermes-cli; gated by `hermes tools`"),
"hermes-telegram": _bundle("Telegram bot toolset - full access for personal use (terminal has safety checks)"),
"hermes-discord": _bundle(
"Discord bot toolset - full access (terminal has safety checks via dangerous "
"command approval)",
["discord", "discord_admin"],
),
"hermes-whatsapp": _bundle("WhatsApp bot toolset - similar to Telegram (personal messaging, more trusted)"),
"hermes-slack": _bundle("Slack bot toolset - full access for workspace use (terminal has safety checks)"),
"hermes-signal": _bundle("Signal bot toolset - encrypted messaging platform (full access)"),
"hermes-bluebubbles": _bundle("BlueBubbles iMessage bot toolset - Apple iMessage via local BlueBubbles server"),
"hermes-email": _bundle("Email bot toolset - interact with Hermes via email (IMAP/SMTP)"),
"hermes-mattermost": _bundle("Mattermost bot toolset - self-hosted team messaging (full access)"),
"hermes-matrix": _bundle("Matrix bot toolset - decentralized encrypted messaging (full access)"),
"hermes-sms": _bundle("SMS bot toolset - interact with Hermes via SMS (Twilio)"),
"hermes-webhook": _ts("Webhook toolset - receive and process external webhook events", _HERMES_WEBHOOK_SAFE_TOOLS),
"hermes-gateway": _ts(
"Gateway toolset - union of all messaging platform tools",
[],
includes=[
"hermes-telegram", "hermes-discord", "hermes-whatsapp", "hermes-slack",
"hermes-signal", "hermes-bluebubbles", "hermes-email",
"hermes-sms", "hermes-mattermost", "hermes-matrix",
"hermes-webhook",
],
),
}
# Core-tools-only ``hermes-<platform>`` bundles of platforms that left core (their plugin registers no toolset).
# A saved selection naming one (a cron job's ``enabled_toolsets``, a ``platform_toolsets`` row, delegation) still
# resolves to the core tools it carried; they stay out of TOOLSETS, ``hermes-gateway`` and every listing so no
# surface advertises an adapter core no longer ships.
RETIRED_CORE_BUNDLES = {"hermes-weixin": _bundle("Weixin toolset (retired; Weixin is the weixin plugin)"),
"hermes-qqbot": _bundle("QQ Bot toolset (retired; QQ Bot is the qqbot plugin)")}
# Toolset -> the session platforms it exists for, from the specs that carry ``platforms``.
TOOLSET_SESSION_PLATFORMS = {name: spec["platforms"] for name, spec in TOOLSETS.items() if "platforms" in spec}
# Captured before create_custom_toolset() can add user-named tools: shared metrics may export only
# these names, so a plugin, MCP server or custom toolset name never leaves the machine.
BUILTIN_TOOL_NAMES = frozenset(tool for spec in TOOLSETS.values() for tool in spec["tools"])
BUILTIN_TOOLSET_NAMES = frozenset(TOOLSETS)
def _registry():
"""Live tool registry, or None when tools.registry can't be imported."""
try:
from tools.registry import registry
return registry
except Exception:
return None
def _registry_call(method: str, default):
"""registry.<method>() or *default* when the registry is unavailable or the call fails."""
try:
return getattr(_registry(), method)()
except Exception: # registry None (AttributeError) or the call failed
return default
def _registry_generation() -> tuple[int, int]:
reg = _registry()
return (id(reg), getattr(reg, "_generation", 0)) if reg is not None else (0, 0)
def _left_core_bundle(name: str, registry: Any) -> Optional[dict[str, Any]]:
"""Core's ``hermes-<platform>`` bundle for a platform that left core with tools (``hermes-feishu``: the core
tools plus feishu_doc + feishu_drive), so a saved explicit selection keeps resolving. Only in a profile where
the plugin registered every one of those toolsets; elsewhere the name stays unknown, as no bundled code is
left to back it."""
from hermes_cli.left_core_migration import legacy_bundle_toolsets
includes = legacy_bundle_toolsets(name)
if not includes or not all(registry.get_tool_names_for_toolset(part) for part in includes):
return None
return _ts(f"Platform bundle from before {name[len('hermes-'):]} left core", _HERMES_CORE_TOOLS, includes)
def get_toolset(name: str, *, include_registry: bool = True) -> Optional[dict[str, Any]]:
"""Toolset definition, or None if unknown.
include_registry=True merges plugin/overlay tools registered into this toolset
and resolves registry-only (plugin/MCP) toolsets and aliases; False returns a
copy of the static TOOLSETS entry only, so platform reverse-mapping is
unaffected by registry additions.
Args: name (str): Name of the toolset include_registry (bool): When True (default), merge in tools that
plugins/overlays registered into this toolset via the registry. Platform reverse-mapping in
``_get_platform_tools`` uses False so that a tool registered into a toolset but absent from a platform's
static composite does not drop the whole toolset from inference. See issue #49622.
"""
toolset = TOOLSETS.get(name) or RETIRED_CORE_BUNDLES.get(name)
if not include_registry:
return {**toolset, "tools": list(toolset.get("tools", [])), "includes": list(toolset.get("includes", []))} if toolset else None
registry = _registry()
if registry is None:
return toolset if toolset else None
if toolset:
merged_tools = set(toolset.get("tools", [])) | set(registry.get_tool_names_for_toolset(name))
# An MCP server named like a built-in toolset ("browser", "memory") registers a bare
# alias to its `mcp-<name>` toolset; without this union the static entry shadows it and the
# server's tools never reach the model even though discovery registered them.
alias_target = registry.get_toolset_alias_target(name)
if alias_target and alias_target != name:
merged_tools |= set(registry.get_tool_names_for_toolset(alias_target))
return {**toolset, "tools": sorted(merged_tools)}
if name in _get_plugin_toolset_names():
# Plugin toolset; shown as its MCP server alias when one exists.
registry_toolset = name
alias = _display_alias(name, _get_registry_toolset_aliases())
description = f"MCP server '{alias}' tools" if alias else f"Plugin toolset: {name}"
else:
registry_toolset = registry.get_toolset_alias_target(name)
if not registry_toolset:
return _left_core_bundle(name, registry)
description = f"MCP server '{name}' tools"
return {"description": description, "tools": registry.get_tool_names_for_toolset(registry_toolset), "includes": []}
def bundle_non_core_tools(toolset_name: str) -> set[str]:
"""A bundle's tools minus _HERMES_CORE_TOOLS (one level of includes).
Disabling a `core + extras` bundle must not strip the core tools every other
toolset shares. One `includes` pass suffices (only hermes-gateway nests
bundles). Unknown names: full resolution minus core.
"""
core = set(_HERMES_CORE_TOOLS)
ts_def = get_toolset(toolset_name)
if not (ts_def and "tools" in ts_def):
return set(resolve_toolset(toolset_name)) - core
to_remove = set(ts_def["tools"])
for inc_def in map(get_toolset, ts_def.get("includes", [])):
if inc_def and "tools" in inc_def:
to_remove.update(inc_def["tools"])
return to_remove - core
# Memo keyed on (name, include_registry, id(registry), registry generation, profile scope);
# engages only at the public entry (visited is None). The scope is part of the key because a
# multiplexed process resolves ``mcp-<server>`` per profile overlay: without it profile B got
# profile A's tool names for a server B never connected (#106005).
_resolve_toolset_memo: dict[tuple[str, bool, int, int, str], list[str]] = {}
def _plugin_platform_bundle(name: str) -> list[str]:
"""Implicit `hermes-<platform>` bundle for a registered plugin platform: core
tools plus whatever the plugin registered under the platform name. [] otherwise."""
if not name.startswith("hermes-"):
return []
platform_name = name[len("hermes-"):]
try:
from gateway.platform_registry import platform_registry
if not platform_registry.is_registered(platform_name):
# ``hermes-wecom-callback`` names platform ``wecom_callback``: toolset names use dashes
# where platform names use underscores (the name core's built-in bundle had).
platform_name = platform_name.replace("-", "_")
if not platform_registry.is_registered(platform_name):
return []
except Exception:
return []
tools = set(_HERMES_CORE_TOOLS)
try:
tools.update(e.name for e in _registry_call("get_all_entries", ()) if e.toolset == platform_name)
except Exception:
pass
return list(tools)
def resolve_toolset(name: str, visited: set[str] | None = None, *, include_registry: bool = True) -> list[str]:
"""Recursively resolve a toolset (and its includes) to a sorted tool-name list.
include_registry=False resolves the static TOOLSETS view only.
Args: name (str): Name of the toolset to resolve visited (Set[str]): Set of already visited toolsets
(for cycle detection) include_registry (bool): When True (default), include tools that plugins/overlays
registered into a toolset. Platform reverse-mapping uses False so a registry-added tool cannot drop the
whole toolset from inference (see #49622 and ``_get_platform_tools``).
"""
external_call = visited is None
if external_call:
memo_key = (name, include_registry, *_registry_generation(), _registry_call("current_scope_key", ""))
cached = _resolve_toolset_memo.get(memo_key)
if cached is not None:
return list(cached)
visited = set()
# "all"/"*" span every toolset so new toolsets are included automatically, except the ones a
# session platform gates: a profile gets those only when its config names them.
if name in {"all", "*"}:
all_tools: set[str] = set()
for toolset_name in get_toolset_names():
if toolset_name not in TOOLSET_SESSION_PLATFORMS:
all_tools.update(resolve_toolset(toolset_name, visited.copy(), include_registry=include_registry))
return sorted(all_tools)
# Diamond include or cycle: [] silently — the tools are collected via another path.
if name in visited:
return []
visited.add(name)
toolset = get_toolset(name, include_registry=include_registry)
if not toolset:
return _plugin_platform_bundle(name) if include_registry else []
tools = set(toolset.get("tools", []))
for included_name in toolset.get("includes", []):
tools.update(resolve_toolset(included_name, visited, include_registry=include_registry))
result = sorted(tools)
if external_call:
if len(_resolve_toolset_memo) >= 256: # stale-generation entries are never hit again
_resolve_toolset_memo.clear()
_resolve_toolset_memo[memo_key] = list(result)
return result
def _get_plugin_toolset_names() -> set[str]:
"""Registry toolset names absent from the static TOOLSETS dict."""
return {n for n in _registry_call("get_registered_toolset_names", ()) if n not in TOOLSETS}
def _get_registry_toolset_aliases() -> dict[str, str]:
return _registry_call("get_registered_toolset_aliases", {})
def _display_alias(ts_name: str, aliases: dict[str, str]) -> Optional[str]:
"""First non-static alias pointing at *ts_name*, or None."""
return next((a for a, canonical in aliases.items() if canonical == ts_name and a not in TOOLSETS), None)
def _plugin_display_names() -> list[str]:
"""Plugin toolset names, shown under their first non-static alias when one exists."""
aliases = _get_registry_toolset_aliases()
return [_display_alias(n, aliases) or n for n in _get_plugin_toolset_names()]
def get_all_toolsets() -> dict[str, dict[str, Any]]:
"""All toolset definitions: static plus plugin-registered."""
result = dict(TOOLSETS)
aliases = _get_registry_toolset_aliases()
for display_name in _plugin_display_names():
toolset = None if display_name in result else get_toolset(display_name)
if toolset:
result[display_name] = toolset
# Static names an MCP server also aliases show the merged view get_toolset() resolves.
for name in TOOLSETS.keys() & aliases.keys():
result[name] = get_toolset(name) or result[name]
return result
def get_toolset_names() -> list[str]:
"""Sorted names of all toolsets (static + plugin), excluding aliases."""
return sorted(set(TOOLSETS.keys()) | set(_plugin_display_names()))
def session_platform_tool_drops(platform: Optional[str]) -> frozenset:
"""Tools of every platform-gated toolset that a session on *platform* does not get."""
return frozenset(tool for name, platforms in TOOLSET_SESSION_PLATFORMS.items() if platform not in platforms
for tool in resolve_toolset(name))
def session_disabled_toolsets(
disabled: Optional[list[str]], platform: Optional[str], *, oneshot: bool = False,
) -> Optional[list[str]]:
"""*disabled* plus every platform-gated toolset a session on *platform* does not get, and for a *oneshot*
session the toolsets nobody is there to use (``agent.oneshot_footprint.ONESHOT_DISABLED_TOOLSETS``). An agent
stores this as its ``disabled_toolsets``, so the tool list, the tool_search listing and bridge, MCP refreshes
and delegate children (which inherit it) all subtract the gated tools in ``_select_tool_names``."""
from agent.oneshot_footprint import ONESHOT_DISABLED_TOOLSETS
gated = [name for name, platforms in TOOLSET_SESSION_PLATFORMS.items() if platform not in platforms]
gated += ONESHOT_DISABLED_TOOLSETS if oneshot else ()
gated = [name for name in gated if name not in (disabled or ())]
return [*(disabled or ()), *gated] if gated else disabled
def tool_selection_key(enabled: Optional[list[str]], disabled: Optional[list[str]]) -> tuple:
"""The toolset selection a tools[] snapshot was built from, order-free. Recorded next to the registry
generation: the tools[] freeze (``agent.tool_snapshot``) holds new tools back only while neither moved."""
return frozenset(enabled) if enabled is not None else None, frozenset(disabled or ())
def agent_tool_drops(agent: Any) -> frozenset:
"""Tool names *agent* never carries, whatever its toolsets resolved to: the side-agent drops and
the toolsets its session platform does not get. Applied at load, MCP refresh and prefix restore."""
from tools.connectors.turn import side_agent_tool_drops
return side_agent_tool_drops(agent) | session_platform_tool_drops(getattr(agent, "platform", None))
def agent_tool_surface(agent: Any, tools: list[dict[str, Any]]) -> list[dict[str, Any]]:
"""*tools* as *agent* carries them: :func:`agent_tool_drops` removed and, in a one-shot session or a gateway
session that joins its delegations in the turn (``delegation.gateway_mode``), the joined ``delegate_task``
variant (``agent.oneshot_footprint.oneshot_tool_schemas``). Applied to FRESH definitions (load, MCP refresh)
before any merge: a pinned or carried entry keeps the bytes already sent."""
from agent.oneshot_footprint import agent_is_oneshot, oneshot_tool_schemas
from agent.subagents.config import agent_joins_delegation
drops = agent_tool_drops(agent)
tools = [tool for tool in tools if (tool.get("function") or {}).get("name") not in drops] if drops else list(tools)
return oneshot_tool_schemas(tools) if agent_is_oneshot(agent) or agent_joins_delegation(agent) else tools
def validate_toolset(name: str) -> bool:
return (name in {"all", "*"} or name in TOOLSETS or name in RETIRED_CORE_BUNDLES
or name in _get_plugin_toolset_names() or name in _get_registry_toolset_aliases()
or (name.startswith("hermes-") and get_toolset(name) is not None))
def create_custom_toolset(name: str, description: str, tools: list[str] | None = None, includes: list[str] | None = None) -> None:
"""Register a runtime toolset in TOOLSETS."""
TOOLSETS[name] = _ts(description, tools or [], includes or [])
def get_toolset_info(name: str) -> dict[str, Any]:
"""Toolset definition plus its resolved tools, or None if unknown."""
toolset = get_toolset(name)
if not toolset:
return None
resolved_tools = resolve_toolset(name)
return {
"name": name, "description": toolset["description"],
"direct_tools": toolset["tools"], "includes": toolset["includes"],
"resolved_tools": resolved_tools, "tool_count": len(resolved_tools),
"is_composite": bool(toolset["includes"]),
}
# --- Selection: toolset lists to tool names ---------------------------------------------------
# Platform-bundle names already flagged in disabled_toolsets (advisory logged once per name).
_WARNED_DISABLED_BUNDLES: set = set()
def _is_delegated_child_context() -> bool:
try:
from agent.delegation_context import is_delegated_child_context
return is_delegated_child_context()
except Exception:
return False
def _is_dispatcher_owned_worker() -> bool:
"""False when HERMES_KANBAN_* is present but this execution does not own it
(delegate_task child, or a cron job fired in-process from a worker)."""
try:
from agent.delegation_context import is_dispatcher_owned_worker_context
return is_dispatcher_owned_worker_context()
except Exception:
return True
# Legacy toolset names (old _tools-suffixed names -> tool name lists)
_LEGACY_TOOLSET_MAP = {
"web_tools": ["web_search", "web_extract"],
"terminal_tools": ["terminal"],
"vision_tools": ["vision_analyze"],
"image_tools": ["image_generate"],
"skills_tools": ["skills_list", "skill_view", "skill_manage"],
"cronjob_tools": ["cronjob_manage"],
"file_tools": ["read_file", "write_file", "patch", "search_files"],
"tts_tools": ["text_to_speech"],
}
def _apply_toolset_selection(tools: set, names: list[str], quiet_mode: bool, *, disable: bool) -> None:
"""Add (or subtract) every toolset in *names* to/from *tools*, printing the selection unless quiet."""
verb, icon = ("Disabled", "🚫") if disable else ("Enabled", "✅")
for name in names:
if validate_toolset(name):
label = f"{verb} toolset"
if disable and (name.startswith("hermes-") or (get_toolset(name) or {}).get("posture")):
# Bundles/postures re-list the core tools without owning them;
# subtracting the whole set would empty the list — remove only the non-core delta.
resolved = sorted(bundle_non_core_tools(name))
if not quiet_mode and name.startswith("hermes-") and name not in _WARNED_DISABLED_BUNDLES:
_WARNED_DISABLED_BUNDLES.add(name)
logger.info(
"agent.disabled_toolsets contains platform-bundle name '%s'; core tools are "
"preserved and only its platform-specific tools (%s) are removed. Bundle names "
"usually belong in `toolsets:`, not `disabled_toolsets` (#33924).",
name, ", ".join(resolved) if resolved else "none",
)
else:
resolved = resolve_toolset(name)
elif name in _LEGACY_TOOLSET_MAP:
label = f"{verb} legacy toolset"
resolved = _LEGACY_TOOLSET_MAP[name]
else:
if not quiet_mode:
print(f"⚠️ Unknown toolset: {name}")
continue
(tools.difference_update if disable else tools.update)(resolved)
if not quiet_mode:
print(f"{icon} {label} '{name}': {', '.join(resolved) if resolved else 'no tools'}")
def _select_tool_names(enabled_toolsets: Optional[list[str]], disabled_toolsets: Optional[list[str]], quiet_mode: bool) -> set:
"""Tool names requested by the toolset selection (before check_fn filtering)."""
tools: set = set()
if enabled_toolsets is not None:
enabled = list(enabled_toolsets)
# Dispatcher-spawned kanban workers always get the lifecycle handoff
# tools, even when the assignee profile restricts its chat toolsets.
if (os.environ.get("HERMES_KANBAN_TASK") and not _is_delegated_child_context()
and _is_dispatcher_owned_worker() and "kanban" not in enabled):
enabled.append("kanban")
_apply_toolset_selection(tools, enabled, quiet_mode, disable=False)
else:
for ts_name in get_all_toolsets():
if ts_name not in TOOLSET_SESSION_PLATFORMS:
tools.update(resolve_toolset(ts_name))
# Disabled toolsets are always subtracted LAST, so a tool in a disabled
# toolset is stripped even when a composite (hermes-cli) re-enables it.
# This ensures that even if a composite toolset (like hermes-cli) is enabled, any tools belonging to a
# disabled toolset are strictly stripped out. See issue #17309.
if disabled_toolsets:
_apply_toolset_selection(tools, disabled_toolsets, quiet_mode, disable=True)
return tools
# --- Platform resolver: which toolsets a platform gets -------------------------------------------
# Platforms already warned about an all-invalid platform_toolsets list (warn once, not per resolution).
_warned_invalid_platform_toolsets: set[str] = set()
# Platform display config derived from the canonical registry (dict-of-dicts for ``PLATFORMS[key]["label"]``).
PLATFORMS = {k: {"label": info.label, "default_toolset": info.default_toolset} for k, info in _PLATFORMS_REGISTRY.items()}
# --- Toolset Registry ---
# Toolsets shown in the configurator: (toolset key in TOOLSETS, label, description).
CONFIGURABLE_TOOLSETS = [
("web", "🔍 Web Search & Scraping", "web_search, web_extract"),
("browser", "🌐 Browser Automation", "navigate, click, type, scroll"),
("terminal", "💻 Terminal & Processes", "terminal, process"),
("file", "📁 File Operations", "read, write, patch, search"),
("code_execution", "⚡ Code Execution", "execute_code"),
("vision", "👁️ Vision / Image Analysis", "vision_analyze"),
("video", "🎬 Video Analysis", "video_analyze (requires video-capable model)"),
("image_gen", "🎨 Image Generation", "image_generate"),
("video_gen", "🎬 Video Generation", "video_generate (text/image/reference)"),
("x_search", "🐦 X (Twitter) Search", "x_search (requires xAI OAuth or XAI_API_KEY)"),
("tts", "🔊 Text-to-Speech", "text_to_speech"),
("stt", "🎙️ Speech-to-Text", "voice transcription (gateway voice messages + voice mode)"),
("skills", "📚 Skills", "list, view, manage"),
("todo", "📋 Task Planning", "todo_list"),
("kanban", "📌 Kanban", "opt-in task board tools for this platform"),
("memory", "💾 Memory", "persistent memory across sessions"),
("context_engine", "🧩 Context Engine", "runtime tools from the active context engine"),
("session_search", "🔎 Session Search", "search past conversations"),
("connections", "🔌 Connections", "remote connector tools and account authorization"),
("clarify", "❓ Clarifying Questions", "clarify"),
("delegation", "👥 Task Delegation", "delegate_task"),
("cronjob", "⏰ Cron Jobs", "create/list/update/pause/resume/run, with optional attached skills"),
("discord", "💬 Discord (read/participate)", "fetch messages, search members, create thread"),
("discord_admin", "🛡️ Discord Server Admin", "list channels/roles, pin, assign roles"),
("computer_use", "🖱️ Computer Use (macOS/Windows/Linux)", "background desktop control via cua-driver"),
]
# OFF by default for new installs (still in _HERMES_CORE_TOOLS; the checklist won't pre-select them). x_search
# auto-enables when xAI creds exist; its check_fn still gates the schema. ``spotify`` and ``a2a`` are plugin
# toolsets (catalog / bundled plugin) that stay opt-in once installed.
_DEFAULT_OFF_TOOLSETS = {"spotify", "discord", "discord_admin", "video", "video_gen", "x_search", "a2a", "kanban"}
def _xai_credentials_present() -> bool:
"""Cheap offline check for xAI credentials (auth store + env only); the runtime ``check_fn`` still gates
schema registration if creds expire. Also used by ``provider_readiness_status`` for ``xai_grok`` rows."""
try:
from hermes_cli.auth import _read_xai_oauth_tokens
_read_xai_oauth_tokens()
return True
except Exception:
pass
if str(get_env_value("XAI_API_KEY") or "").strip():
return True
try:
from agent.secret_scope import get_secret
except ImportError: # pragma: no cover — secret_scope is in-repo
get_secret = os.environ.get
return bool(str(get_secret("XAI_API_KEY") or "").strip())
# A classic CLI on a gateway session reads plugin toolsets from the gateway instead of loading plugins
# (installed by ``_ensure_gateway_session``): ``() -> ([(key, label, description)], {portable MCP})`` or
# None (off the gateway: this process's own registry).
_gateway_plugin_toolsets = None
_gateway_plugin_toolset_platforms = None # same, for ``{toolset: default platforms}``
def _projected_plugin_toolsets():
provider = _gateway_plugin_toolsets
return provider() if provider is not None else None
def _get_plugin_toolset_keys() -> set:
"""Return the set of toolset keys provided by plugins."""
try:
if (projected := _projected_plugin_toolsets()) is not None:
return {key for key, _, _ in projected[0]}
# Non-blocking on CLI startup: while background discovery is still importing, serve last
# launch's persisted key set instead of joining the discovery thread.
from hermes_cli.plugins import get_plugin_toolset_keys_nowait
return get_plugin_toolset_keys_nowait()
except Exception:
return set()
def _plugin_toolset_default_platforms() -> dict[str, frozenset[str]]:
"""Plugin toolsets that default on only for some platforms (``register_tool(default_platforms=...)``)."""
if _projected_plugin_toolsets() is not None:
provider = _gateway_plugin_toolset_platforms
return provider() if provider is not None else {}
from hermes_cli.plugins import get_plugin_toolset_default_platforms_nowait
return get_plugin_toolset_default_platforms_nowait()
def _plugin_toolset_view() -> tuple[set[str], dict[str, frozenset[str]]]:
"""Plugin toolset keys and their ``default_platforms`` read once, from one source (gateway, live registry
or last launch's cache)."""
try:
if (projected := _projected_plugin_toolsets()) is not None:
provider = _gateway_plugin_toolset_platforms
return {key for key, _, _ in projected[0]}, (provider() if provider is not None else {})
from hermes_cli.plugins import get_plugin_toolset_view_nowait
return get_plugin_toolset_view_nowait()
except Exception: # health: allow BLE001 -- same fail-soft as _get_plugin_toolset_keys
return set(), {}
def _platform_default_toolset(platform: str) -> str:
"""Composite toolset a platform falls back to (plugin platforms derive ``hermes-<platform>``)."""
return PLATFORMS[platform]["default_toolset"] if platform in PLATFORMS else f"hermes-{platform}"
def enabled_mcp_server_names(config: dict) -> set[str]:
"""MCP servers globally enabled in config.yaml or by a plugin (shared by platform + cron resolvers). Enabled
unless ``enabled`` is explicitly falsey; portable-plugin servers (in-memory) count — enabling the plugin is
the opt-in."""
from tools.mcp.common import mcp_server_enabled
mcp_servers = (config or {}).get("mcp_servers") or {}
names = {
str(name) for name, server_cfg in mcp_servers.items()
if isinstance(server_cfg, dict) and mcp_server_enabled(server_cfg)
}
try:
projected = _projected_plugin_toolsets()
if projected is None:
from hermes_cli.plugins import get_portable_mcp_server_names_nowait
portable = projected[1] if projected is not None else get_portable_mcp_server_names_nowait()
names |= portable - set(mcp_servers) # native config wins on a name collision (mirrors _load_mcp_config)
except Exception:
logger.debug("Failed to include portable MCP servers", exc_info=True)
return names
#: Toolsets young enough that absence from a saved ``platform_toolsets`` list means "never offered", not
#: "declined": saving ``hermes tools`` freezes a platform's composite into an explicit list nothing adds to, so
#: a later toolset stays off forever for picker users while ``[hermes-cli]`` users inherit it.
#: MUST ship in the same release as the toolset and be emptied in the next: once a released build has put the
#: toolset on a checklist, an unchecking user's config is byte-identical to one saved before it existed and this
#: rule would turn the opt-out back on (stuck checkbox). ``check_fn``-gated toolsets cost nothing here; never
#: probe a remote service from this path — it runs on every CLI start, gateway session and cron tick.
_RECENTLY_SHIPPED_TOOLSETS: frozenset = frozenset()
def _enable_recently_shipped_toolsets(enabled_toolsets: set[str], config: dict, platform: str) -> None:
"""Turn on toolsets that shipped after this platform's saved list (mutates ``enabled_toolsets``). Both "no"s
outlive this: unchecking records ``known_builtin_toolsets`` (declined), and ``agent.disabled_toolsets`` is
subtracted last in :func:`_get_platform_tools`."""
offered = (config.get("known_builtin_toolsets") or {}).get(platform)
declined = {str(ts) for ts in offered} if isinstance(offered, list) else set()
default_ts = _platform_default_toolset(platform)
composite_tools = None
for ts_key in sorted(_RECENTLY_SHIPPED_TOOLSETS):
if ts_key in enabled_toolsets or ts_key in declined or not _toolset_allowed_for_platform(ts_key, platform):
continue
# Only enable where staying on the composite would have enabled it anyway; deliberately narrow
# composites (hermes-acp, hermes-webhook) stay narrow.
ts_tools = set(resolve_toolset(ts_key, include_registry=False))
if composite_tools is None:
composite_tools = set(resolve_toolset(default_ts))
if not ts_tools or not ts_tools.issubset(composite_tools):
continue
enabled_toolsets.add(ts_key)
def _configurable_subset_of(tool_names: set[str], platform: str) -> set[str]:
"""Configurable toolsets whose STATIC membership is within ``tool_names`` (``include_registry=False``: a
runtime-registered tool the composite never listed must not drop the whole toolset)."""
return {
ts_key for ts_key, _, _ in CONFIGURABLE_TOOLSETS if _toolset_allowed_for_platform(ts_key, platform)
and (ts_tools := set(resolve_toolset(ts_key, include_registry=False))) and ts_tools <= tool_names}
def _default_off_toolsets(platform: str, explicitly_configured: bool) -> set[str]:
"""Toolsets to strip from an implicit (composite-derived) enable set. A platform named after a default-off
toolset keeps it, except platform-restricted ones (``discord`` on discord stays OFF).
Platform-native default-off toolsets (``discord`` on discord) are off for unconfigured platforms as a
security opt-in — an explicitly saved list IS that opt-in and lets them through."""
default_off = set(_DEFAULT_OFF_TOOLSETS)
if platform in default_off and platform not in _TOOLSET_PLATFORM_RESTRICTIONS:
default_off.remove(platform)
if explicitly_configured:
default_off -= {ts for ts in default_off if platform in (_TOOLSET_PLATFORM_RESTRICTIONS.get(ts) or ())}
return default_off
def _configurable_keys() -> set[str]:
return {ts_key for ts_key, _, _ in CONFIGURABLE_TOOLSETS}
def _left_core_core_bundles() -> set[str]:
"""``tools.toolsets.RETIRED_CORE_BUNDLES`` (``hermes-weixin``, ``hermes-qqbot``): core's bundle carried only core
tools, so it still reads as them and the picker still treats it as a preset."""
return set(RETIRED_CORE_BUNDLES)
def _resolve_preset(name: str) -> list[str]:
"""``resolve_toolset``, except a left-core core-tools bundle (:func:`_left_core_core_bundles`): the core
tools it carried, plugin loaded or not, and ahead of a same-named MCP server or plugin toolset, as when
it was a static ``TOOLSETS`` entry. Both picker paths read it the same way."""
retired = RETIRED_CORE_BUNDLES.get(name) # the bundle's own definition: what a saved selection runs
return list(retired["tools"]) if retired else resolve_toolset(name)
def _platform_default_keys() -> set[str]:
return {p["default_toolset"] for p in PLATFORMS.values()} | _left_core_core_bundles()
def _explicit_toolsets(
toolset_names: list[str], explicit_known_keys: set[str], config: dict, platform: str,
explicitly_configured: bool) -> set[str]:
"""Enabled set when the saved list names configurable/plugin keys directly (subset inference over
``hermes-cli`` would re-enable disabled toolsets). A mixed list (``[hermes-cli, discord]``) still expands the
composite; _DEFAULT_OFF_TOOLSETS applies to that implicit expansion only."""
enabled = {ts for ts in toolset_names if ts in explicit_known_keys and _toolset_allowed_for_platform(ts, platform)}
composite_tools = {
t for ts_name in toolset_names if ts_name not in explicit_known_keys
and (ts_name in TOOLSETS or ts_name in _left_core_core_bundles())
for t in _resolve_preset(ts_name)}
if composite_tools:
enabled |= _configurable_subset_of(composite_tools, platform) - _default_off_toolsets(platform, explicitly_configured)
_enable_recently_shipped_toolsets(enabled, config, platform)
return enabled
def _composite_toolsets(toolset_names: list[str], platform: str, explicitly_configured: bool) -> set[str]:
"""Enabled set inferred from composite names by reverse-mapping tool names (only while no explicit list is
saved). ``x_search`` is not in any composite, so inject it when xAI creds exist and exempt it from default-off."""
all_tool_names = {t for ts_name in toolset_names for t in _resolve_preset(ts_name)}
enabled = _configurable_subset_of(all_tool_names, platform)
default_off = _default_off_toolsets(platform, explicitly_configured)
if _toolset_allowed_for_platform("x_search", platform) and _xai_credentials_present():
enabled.add("x_search")
default_off.discard("x_search")
return enabled - default_off
def _enabled_plugin_toolsets(config: dict, platform: str, toolset_names: list[str], plugin_ts_keys: set[str],
scoped: Optional[dict[str, frozenset[str]]] = None) -> set[str]:
"""Plugin toolsets: on by default unless default-off (catalog spotify), registered with
``default_platforms`` that leave out this platform, or "known" for this platform
(``known_plugin_toolsets``, written on every save) and absent from the saved list."""
known_for_platform = set((config.get("known_plugin_toolsets", {}) or {}).get(platform, []) or [])
scoped = _plugin_toolset_default_platforms() if scoped is None else scoped
return {
pts for pts in plugin_ts_keys
if pts in toolset_names or (
pts not in _DEFAULT_OFF_TOOLSETS and pts not in known_for_platform and platform in scoped.get(pts, {platform}))
}
def _context_engine_active(config: dict) -> bool:
context_cfg = config.get("context") or {}
name = str(context_cfg.get("engine") or "compressor").strip().lower() if isinstance(context_cfg, dict) else "compressor"
return bool(name) and name != "compressor"
def _coerce_platform_toolsets_value(value, platform: str):
"""Read a list-literal string saved for ``platform_toolsets.<platform>`` as the list it encodes.
The parser is shared with ``hermes doctor`` and ``hermes plugins`` (``toolset_validation``
``parse_platform_toolsets_value``) so every surface agrees on the user's selection (#115866).
Any other non-list value is warned about once (naming the expected shape) and left as-is, so
the default fallback below is loud rather than silent.
"""
if value is None:
return None
parsed = parse_platform_toolsets_value(value)
if parsed is not None:
return parsed
if platform not in _warned_invalid_platform_toolsets:
_warned_invalid_platform_toolsets.add(platform)
logger.warning(
"platform_toolsets.%s is %r, expected a YAML list of toolset names "
"(e.g. [terminal, file, web]) - falling back to the platform default. "
"Run `hermes tools` to reconfigure.", platform, value)
return value
def _get_platform_tools(config: dict, platform: str, *, include_default_mcp_servers: bool = True) -> set[str]:
"""Resolve which individual toolset names are enabled for a platform."""
platform_toolsets = config.get("platform_toolsets") or {}
toolset_names = _coerce_platform_toolsets_value(platform_toolsets.get(platform), platform)
# An explicitly saved list (even a composite like ``hermes-discord``) is an opt-in to the platform's
# native default-off toolsets — see _default_off_toolsets.
# Track whether the user explicitly saved a toolset list for this platform (vs. falling back to the
# platform default). See #35527.
explicitly_configured = isinstance(toolset_names, list)
if not explicitly_configured:
toolset_names = [_platform_default_toolset(platform)]
# YAML may parse bare numeric names (``12306:``) as int; normalise so sorted() never mixes types.
toolset_names = [str(ts) for ts in toolset_names]
# Expand legacy toolset aliases. Older Hermes versions and clients used
# bare ``"hermes"`` as a composite toolset covering both the CLI and the
# API-server surface. Modern code expects ``"hermes-cli"`` (and
# ``"hermes-api-server"`` for the HTTP endpoint), so configs persisted
# by those older versions still carry the legacy name; without expansion
# ``resolve_toolset("hermes")`` returns ``[]`` — all tools silently
# disappear.
_LEGACY_TOOLSET_ALIASES: dict = {
"hermes": ("hermes-cli", "hermes-api-server"),
}
expanded: list = []
for name in toolset_names:
aliases = _LEGACY_TOOLSET_ALIASES.get(name)
if aliases:
expanded.extend(aliases)
else:
expanded.append(name)
toolset_names = expanded
configurable_keys = _configurable_keys()
plugin_ts_keys, scoped = _plugin_toolset_view()
platform_default_keys = _platform_default_keys()
# Plugin toolsets are first-class on a saved list: ``[hermes-cli, a2a]`` must survive filtering.
# Plugin-provided toolsets are first-class on a platform-toolsets list — explicit config like
# ``[hermes-cli, a2a]`` must survive filtering just like a built-in configurable toolset would. See
# issue #81163.
explicit_known_keys = configurable_keys | plugin_ts_keys
if any(ts in explicit_known_keys for ts in toolset_names):
enabled_toolsets = _explicit_toolsets(toolset_names, explicit_known_keys, config, platform, explicitly_configured)
else:
enabled_toolsets = _composite_toolsets(toolset_names, platform, explicitly_configured)
_recover_platform_native_toolsets(enabled_toolsets, platform, skip=configurable_keys | plugin_ts_keys | platform_default_keys)
if plugin_ts_keys:
enabled_toolsets |= _enabled_plugin_toolsets(config, platform, toolset_names, plugin_ts_keys, scoped)
# Context-engine tools are runtime-provided, not in any static composite: keep them for a non-default
# engine even after an explicit save. An explicit EMPTY list means none, unless ``context_engine`` is added by hand.
if _context_engine_active(config) and not (explicitly_configured and not toolset_names):
enabled_toolsets.add("context_engine")
# Explicit non-configurable entries (custom toolsets, MCP server names) pass through.
explicit_passthrough = {ts for ts in toolset_names if ts not in explicit_known_keys and ts not in platform_default_keys}
# An explicitly saved empty list means zero toolsets with no MCP merge
# (#82010); falling through to every enabled server would be fail-open.
if not (explicitly_configured and not toolset_names):
enabled_toolsets |= _merge_mcp_servers(config, toolset_names, explicit_passthrough, include_default_mcp_servers)
# Legacy profile opt-in is a fallback only. A saved platform list (even
# empty) is authoritative, so a later disable cannot silently re-enable it.
if not explicitly_configured and "kanban" in (config.get("toolsets") or []):
enabled_toolsets.add("kanban")
# agent.disabled_toolsets is a global suppression list (#86661) and runs LAST so it overrides everything
# above. It may arrive as a JSON-array string ("['memory']") from `hermes config set` or a JSON-mode editor.
disabled_toolsets = (config.get("agent") or {}).get("disabled_toolsets")
if disabled_toolsets:
from agent.skill_utils import parse_config_string_list
disabled_names = [name.strip() for name in parse_config_string_list(disabled_toolsets) if name.strip()]
enabled_toolsets = _prune_toolsets_stripped_by_disabled(enabled_toolsets, disabled_names)
if explicitly_configured and toolset_names:
_warn_all_invalid_platform_toolsets(platform, toolset_names, config)
return enabled_toolsets
def _prune_toolsets_stripped_by_disabled(enabled_toolsets: set[str], disabled_names: list[str]) -> set[str]:
"""Drop disabled names AND every toolset whose tools the runtime would strip anyway.
The agent subtracts ``agent.disabled_toolsets`` at TOOL granularity (``_select_tool_names``),
so disabling a composite like ``debugging`` removes the terminal/web/file tools even though those names
never appear in the list. A name-only subtraction here left inspection surfaces (``hermes tools
--summary``, banner, ``/tools``) showing toolsets as enabled that no session could call (#97015).
Passthrough entries (MCP server names) and toolsets with no static tools (``context_engine``) are kept.
"""
remaining = enabled_toolsets - set(disabled_names)
resolved = {name: set(resolve_toolset(name)) if validate_toolset(name) else set() for name in remaining}
surviving: set[str] = set().union(*resolved.values())
_apply_toolset_selection(surviving, disabled_names, quiet_mode=True, disable=True)
return {name for name, tools in resolved.items() if not tools or tools & surviving}
def _recover_platform_native_toolsets(enabled_toolsets: set[str], platform: str, *, skip: set[str]) -> None:
"""Add non-configurable platform toolsets (discord, a plugin platform's own) in place: in the default composite but not in
CONFIGURABLE_TOOLSETS, so never in a checklist or saved list. Runs for BOTH ``_get_platform_tools`` branches."""
platform_tool_universe = set(resolve_toolset(_platform_default_toolset(platform)))
configurable_tool_universe = {t for ts_key, _, _ in CONFIGURABLE_TOOLSETS for t in resolve_toolset(ts_key)}
claimed = {t for ts_key in enabled_toolsets for t in resolve_toolset(ts_key)}
skip = skip | {k for k in TOOLSETS if k.startswith("hermes-")} | (set(_DEFAULT_OFF_TOOLSETS) - {platform})
for ts_key, ts_def in TOOLSETS.items():
# Posture toolsets (``coding``) are session-level selections made by agent/coding_context.py, not
# per-platform capabilities to recover.
if ts_key in skip or ts_def.get("includes") or ts_def.get("posture"):
continue
# Static membership: a registry-added tool absent from the platform composite must not block recovery
# of a non-configurable toolset whose authored tools the composite lists.
ts_tools = set(resolve_toolset(ts_key, include_registry=False))
if not ts_tools or not ts_tools <= platform_tool_universe or ts_tools <= configurable_tool_universe:
continue
if not ts_tools <= claimed:
enabled_toolsets.add(ts_key)
claimed.update(ts_tools)
def _merge_mcp_servers(
config: dict, toolset_names: list[str], explicit_passthrough: set[str], include_default_mcp_servers: bool
) -> set[str]:
"""Explicit passthrough entries plus this platform's MCP servers: listed names form an allowlist, else every
globally enabled server (when ``include_default_mcp_servers``); the ``no_mcp`` sentinel disables all."""
enabled_mcp_servers = enabled_mcp_server_names(config)
configured = config.get("mcp_servers") if isinstance(config.get("mcp_servers"), dict) else {}
known = enabled_mcp_servers | {str(name) for name in configured}
# ``mcp-<server>`` names the same server as its bare alias: either spelling selects only that server
# (unless a server is literally named ``mcp-<server>``).
explicit_passthrough = {ts[4:] if ts.startswith("mcp-") and ts not in known
and ts[4:] in known else ts for ts in explicit_passthrough}
result = explicit_passthrough - known
if "no_mcp" in toolset_names:
return result - {"no_mcp"}
explicit_mcp_servers = explicit_passthrough & enabled_mcp_servers
# A listed server that is configured but disabled is still the user's server selection: it stays
# off, and it must not fall through to every enabled server.
if include_default_mcp_servers and not explicit_passthrough & known:
return result | enabled_mcp_servers
return result | explicit_mcp_servers
def _warn_all_invalid_platform_toolsets(platform: str, explicit: list, config: dict) -> None:
"""Warn once when an explicit platform list has only invalid names (``hermes`` for ``hermes-cli`` → no
native tools), at session tool resolution rather than only in update/doctor. Names are judged the way
``hermes config check`` judges them, and a known platform's own ``hermes-<platform>`` bundle always
counts (``is_known_platform_bundle``): a plugin platform has no sessions to leave toolless until its
plugin loads, and once it loads the registry resolves the bundle.
The own-bundle and registered-toolset checks run first because this is reached on every schema build
(the kanban gate resolves every saved platform row) and on bypass launches that must not read profile
plugin state; the resolver's manifest scan and plugin lookup run only for names those cannot place."""
from hermes_cli.toolset_validation import is_known_platform_bundle, saved_toolset_resolver
if platform in _warned_invalid_platform_toolsets:
return
named = [str(t) for t in explicit if isinstance(t, str) and t]
if not named or any(validate_toolset(t) or is_known_platform_bundle(platform, t) for t in named):
return
is_valid_toolset = saved_toolset_resolver(config)
if not any(is_valid_toolset(t) for t in named):
_warned_invalid_platform_toolsets.add(platform)
logger.warning(
"platform '%s' has no valid toolsets configured (unknown "
"name(s): %s) - tools will be unavailable. Run `hermes tools` "
"to reconfigure. See issue #38798.",
platform, ", ".join(named))