Skip to content

The agent that grows with you

refactor(hclib): config — config/config_migrations/tools_config/toolset_* dispatch tables and dedupe

Teknium5d4b97939ed6
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index add9141382a..3bfe8dcb394 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -1,18 +1,4 @@
-"""
-Configuration management for Hermes Agent.
-
-Config files are stored in ~/.hermes/ for easy access:
-- ~/.hermes/config.yaml - All settings (model, toolsets, terminal, etc.)
-- ~/.hermes/.env - API keys and secrets
-
-This module provides:
-- hermes config - Show current configuration
-- hermes config edit - Open config in editor
-- hermes config get - Print a resolved configuration value
-- hermes config set - Set a specific value
-- hermes config unset - Remove a user configuration value
-- hermes config wizard - Re-run setup wizard
-"""
+"""Configuration management for Hermes Agent."""
import copy
from decimal import Decimal, InvalidOperation
@@ -60,23 +46,12 @@ class InvalidUserConfigError(RuntimeError):
def _backup_corrupt_config(config_path: Path) -> Optional[Path]:
"""Preserve a corrupted ``config.yaml`` by copying it to a timestamped ``.bak``.
- When the YAML can't be parsed, ``load_config()`` silently falls back to
- ``DEFAULT_CONFIG`` and the user's broken file stays on disk untouched.
- That file is still the user's only copy of their intended overrides — if
- they re-run the setup wizard or ``hermes config set`` (which rewrites
- ``config.yaml``), the broken-but-recoverable content is gone for good.
-
- This snapshots the corrupted file to ``config.yaml.corrupt.<ts>.bak`` so
- the user can diff/repair it. Unlike Gemini CLI's policy-file recovery
- (which resets the live file to a clean state), we deliberately leave
- ``config.yaml`` in place: hermes never silently mutates the user's config,
- and leaving it means a hand-fixed file is re-read on the next load. The
- backup is best-effort — any failure (permissions, symlink, disk full) is
- swallowed so config loading is never blocked by backup problems.
-
- Returns the backup path on success, else ``None``. Symlinks are not
- followed/copied (mirrors the Gemini #21541 lstat guard) to avoid
- clobbering whatever a malicious/misconfigured symlink points at.
+ When the YAML can't be parsed, ``load_config()`` silently falls back to ``DEFAULT_CONFIG`` and
+ the user's broken file stays on disk untouched.
+
+ Returns the backup path on success, else ``None``. Symlinks are not followed/copied (mirrors the
+ Gemini #21541 lstat guard) to avoid clobbering whatever a malicious/misconfigured symlink points
+ at.
"""
try:
if config_path.is_symlink():
@@ -116,25 +91,9 @@ def _warn_config_parse_failure(
) -> None:
"""Surface a config.yaml parse failure to user, log, and stderr.
- A YAML parse error in ``~/.hermes/config.yaml`` causes ``load_config()``
- to silently fall back to ``DEFAULT_CONFIG``, which means every user
- override (auxiliary providers, fallback chain, model overrides, etc.)
- is dropped. Before this helper that was a one-line ``print(...)`` that
- scrolled off-screen on the first invocation and was never seen again.
-
- Now: warn once per (path, mtime_ns, size) on stderr **and** in
- ``agent.log`` / ``errors.log`` at WARNING level so ``hermes logs``
- surfaces it. Re-warns automatically if the file changes (different
- mtime/size), so users editing the config see the next failure. On the
- first warning for a given broken file we also snapshot it to a
- timestamped ``.bak`` (best-effort) so the user's recoverable content
- survives any later rewrite of ``config.yaml`` by the setup wizard or
- ``hermes config set``.
-
- ``fallback`` selects the message wording: ``"defaults"`` (fresh process,
- nothing else to serve) or ``"last-known-good"`` (in-process retention of
- the previously loaded config — see the codex#31188 port in
- ``_load_config_impl``).
+ A YAML parse error in ``~/.hermes/config.yaml`` causes ``load_config()`` to silently fall back
+ to ``DEFAULT_CONFIG``, which means every user override (auxiliary providers, fallback chain,
+ model overrides, etc.) is dropped.
"""
try:
st = config_path.stat()
@@ -184,18 +143,9 @@ def _warn_config_parse_failure(
def get_active_config_parse_failure() -> Optional[str]:
"""Return the parse-error message if the ACTIVE config.yaml is corrupt.
- Probes the failure record written by :func:`_warn_config_parse_failure`
- for the current :func:`get_config_path` and re-stats the file NOW: the
- recorded error is returned only while the file is byte-identical
- (mtime_ns + size) to the one that failed to parse. The moment the user
- fixes (or deletes) the file, this returns ``None`` without any cache
- invalidation dance.
-
- Consumers: ``hermes_cli.auth.resolve_provider`` uses this to refuse
- env-key/pool auto-adoption of a paid provider while the user's real
- config — which may name a different provider entirely — is unreadable
- (#81952). Returns ``None`` when no failure was ever recorded, when the
- file changed since the failure, or on any stat error.
+ Probes the failure record written by :func:`_warn_config_parse_failure` for the current
+ :func:`get_config_path` and re-stats the file NOW: the recorded error is returned only while the
+ file is byte-identical (mtime_ns + size) to the one that failed to parse.
"""
try:
path = get_config_path()
@@ -214,44 +164,21 @@ def get_active_config_parse_failure() -> Optional[str]:
_IS_WINDOWS = platform.system() == "Windows"
_ENV_VAR_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
-# Env var names that influence how the next subprocess executes —
-# never writable through ``save_env_value``. Anything that controls
-# the loader, interpreter, shell, or replacement editor counts:
-#
-# * ``LD_PRELOAD`` / ``LD_LIBRARY_PATH`` / ``LD_AUDIT`` — Linux dynamic
-# loader. ``DYLD_*`` — macOS equivalent. Planting a path here means
-# the next ``subprocess.run([...])`` Hermes makes loads attacker code
-# before main().
-# * ``PYTHONPATH`` / ``PYTHONHOME`` / ``PYTHONSTARTUP`` /
-# ``PYTHONUSERBASE`` — Python interpreter init. Hermes itself starts
-# from one of these on every restart.
-# * ``NODE_OPTIONS`` / ``NODE_PATH`` — Node interpreter; affects npm,
-# ``hermes update``, the TUI build.
-# * ``PATH`` — too broad to allow. The dashboard never needs to rewrite
-# the operator's PATH; if a tool can't be found, the fix is to add an
-# absolute path in the integration config, not to mutate PATH globally.
-# * ``GIT_SSH_COMMAND`` / ``GIT_EXEC_PATH`` — git rewrites that fire
-# on every plugin install / ``hermes update``.
-# * ``BROWSER`` / ``EDITOR`` / ``VISUAL`` / ``PAGER`` — commands the
-# shell or CLI invokes implicitly. Wrong values here = RCE on next
-# ``$EDITOR``.
-# * ``SHELL`` — what subprocess uses with ``shell=True`` (we try to
-# avoid that, but defense in depth).
-# * ``HERMES_HOME`` / ``HERMES_PROFILE`` / ``HERMES_CONFIG`` /
-# ``HERMES_ENV`` — Hermes runtime location flags. Writing these into
-# ``.env`` would relocate state in ways the user did not request from
-# the dashboard. ``config.yaml`` is the supported surface for these.
+# Env var names that influence how the next subprocess executes — never writable
+# through ``save_env_value``: dynamic loader (LD_*/DYLD_*: attacker code loads
+# before main()), interpreter init (PYTHON*, NODE_*: Hermes restarts through
+# them), PATH (too broad; fix tool lookup with absolute paths in integration
+# config instead), git rewrites (fire on every plugin install / update),
+# implicitly-invoked commands (BROWSER/EDITOR/VISUAL/PAGER = RCE on next $EDITOR),
+# SHELL (shell=True defense in depth), and Hermes runtime-location flags
+# (config.yaml is the supported surface; .env writes would relocate state).
#
-# IMPORTANT: ``HERMES_*`` overall is NOT blocked. Many legitimate
-# integration credentials follow that prefix (HERMES_LANGFUSE_PUBLIC_KEY,
-# HERMES_SPOTIFY_CLIENT_ID, ...). The
-# denylist is name-by-name on purpose so the gate stays narrow and
-# doesn't accidentally break provider setup wizards.
-#
-# This is enforced on *write* only — values already in ``.env`` (set
-# by the operator out-of-band, or pre-existing) keep working. The
-# point is that the dashboard's writable surface cannot escalate by
-# planting them.
+# IMPORTANT: ``HERMES_*`` overall is NOT blocked — many integration credentials
+# use that prefix (HERMES_LANGFUSE_PUBLIC_KEY, HERMES_SPOTIFY_CLIENT_ID, ...).
+# The denylist is name-by-name so the gate stays narrow and cannot break provider
+# setup wizards. Enforced on *write* only: pre-existing/out-of-band ``.env``
+# values keep working; the point is the dashboard's writable surface cannot
+# escalate by planting them.
_ENV_VAR_NAME_DENYLIST: frozenset[str] = frozenset({
# Loader / linker
"LD_PRELOAD", "LD_LIBRARY_PATH", "LD_AUDIT", "LD_DEBUG",
@@ -290,20 +217,16 @@ _ENV_VAR_NAME_DENYLIST: frozenset[str] = frozenset({
def _env_var_policy_name(key: str, *, is_windows: Optional[bool] = None) -> str:
"""Return the name used for environment policy comparisons.
- Windows environment names are case-insensitive; POSIX names are not. The
- explicit override keeps both semantics directly testable without pretending
- the test interpreter is running on another host OS.
+ Windows environment names are case-insensitive; POSIX names are not. The explicit override keeps
+ both semantics directly testable without pretending the test interpreter is running on another
+ host OS.
"""
windows = _IS_WINDOWS if is_windows is None else is_windows
return key.upper() if windows else key
def _reject_denylisted_env_var(key: str) -> None:
- """Raise if ``key`` is in :data:`_ENV_VAR_NAME_DENYLIST`.
-
- Centralised so both the regular and "secure" env writers share the
- same gate, and so the message is consistent for callers.
- """
+ """Raise if ``key`` is in :data:`_ENV_VAR_NAME_DENYLIST`."""
if _env_var_policy_name(key) in _ENV_VAR_NAME_DENYLIST:
raise ValueError(
f"Environment variable {key!r} is on the writer denylist. "
@@ -319,26 +242,23 @@ def _reject_denylisted_env_var(key: str) -> None:
def validate_env_var_name_for_write(key: str) -> None:
"""Validate an environment name before a generic persistence write.
- Exposed separately from :func:`save_env_value` so batch-style callers can
- validate their complete request before writing the first value.
+ Exposed separately from :func:`save_env_value` so batch-style callers can validate their
+ complete request before writing the first value.
"""
if not _ENV_VAR_NAME_RE.match(key):
raise ValueError(f"Invalid environment variable name: {key!r}")
_reject_denylisted_env_var(key)
_LAST_EXPANDED_CONFIG_BY_PATH: Dict[str, Any] = {}
-# (path, mtime_ns, size) -> cached expanded config dict.
-# load_config() returns a deepcopy of the cached value when the file
-# hasn't changed since the last load, skipping yaml.safe_load +
-# _deep_merge + _normalize_* + _expand_env_vars (~13 ms/call).
-# save_config() + migrate_config() write via atomic_yaml_write which
-# produces a fresh inode, so stat() sees a new mtime_ns and the next
-# load repopulates automatically — no explicit invalidation hook.
-# Cached tuple is (user_mtime_ns, user_size, managed_mtime_ns, managed_size,
-# merged_value, env_ref_snapshot) — the managed-file signature is folded in so
-# editing the managed-scope config.yaml invalidates the cache (see
-# managed_scope), and the env snapshot invalidates it when a referenced ${VAR}
-# changes value (late .env load, in-process rotation — #58514).
+# path -> (user_mtime_ns, user_size, managed_mtime_ns, managed_size, merged_value,
+# env_ref_snapshot). load_config() returns a deepcopy of the cached value while
+# the signature matches, skipping safe_load + _deep_merge + _normalize_* +
+# _expand_env_vars (~13 ms/call). save_config()/migrate_config() write via
+# atomic_yaml_write (fresh inode → new mtime_ns), so no explicit invalidation
+# hook is needed. The managed-file signature is folded in so editing the
+# managed-scope config.yaml invalidates the cache, and the env snapshot
+# invalidates it when a referenced ${VAR} changes value (late .env load,
+# in-process rotation).
_LOAD_CONFIG_CACHE: Dict[str, Tuple[int, int, int, int, Dict[str, Any], Dict[str, Optional[str]]]] = {}
# (path, mtime_ns, size) -> cached raw yaml dict. Same pattern as
# _LOAD_CONFIG_CACHE but for read_raw_config() — used when callers want
@@ -355,70 +275,48 @@ _CONFIG_LOCK = threading.RLock()
# Env var names written to .env that aren't in OPTIONAL_ENV_VARS
# (managed by setup/provider flows directly).
_EXTRA_ENV_KEYS = frozenset({
- "OPENAI_API_KEY", "OPENAI_BASE_URL",
- "ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN",
+ "OPENAI_API_KEY", "OPENAI_BASE_URL", "ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN",
"DISCORD_HOME_CHANNEL", "DISCORD_HOME_CHANNEL_NAME",
"TELEGRAM_HOME_CHANNEL", "TELEGRAM_HOME_CHANNEL_NAME",
"SLACK_HOME_CHANNEL", "SLACK_HOME_CHANNEL_NAME",
- "SIGNAL_ACCOUNT", "SIGNAL_HTTP_URL",
- "SIGNAL_ALLOWED_USERS", "SIGNAL_GROUP_ALLOWED_USERS",
- "SIGNAL_HOME_CHANNEL", "SIGNAL_HOME_CHANNEL_NAME",
- "SMS_HOME_CHANNEL", "SMS_HOME_CHANNEL_NAME",
- "DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET",
- "DINGTALK_HOME_CHANNEL", "DINGTALK_HOME_CHANNEL_NAME",
+ "SIGNAL_ACCOUNT", "SIGNAL_HTTP_URL", "SIGNAL_ALLOWED_USERS", "SIGNAL_GROUP_ALLOWED_USERS",
+ "SIGNAL_HOME_CHANNEL", "SIGNAL_HOME_CHANNEL_NAME", "SMS_HOME_CHANNEL", "SMS_HOME_CHANNEL_NAME",
+ "DINGTALK_CLIENT_ID", "DINGTALK_CLIENT_SECRET", "DINGTALK_HOME_CHANNEL", "DINGTALK_HOME_CHANNEL_NAME",
"FEISHU_APP_ID", "FEISHU_APP_SECRET", "FEISHU_ENCRYPT_KEY", "FEISHU_VERIFICATION_TOKEN",
- "FEISHU_HOME_CHANNEL", "FEISHU_HOME_CHANNEL_NAME",
- "YUANBAO_HOME_CHANNEL", "YUANBAO_HOME_CHANNEL_NAME",
- "WECOM_BOT_ID", "WECOM_SECRET",
- "WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET", "WECOM_CALLBACK_AGENT_ID",
- "WECOM_CALLBACK_TOKEN", "WECOM_CALLBACK_ENCODING_AES_KEY",
- "WECOM_CALLBACK_HOST", "WECOM_CALLBACK_PORT",
- "WECOM_HOME_CHANNEL", "WECOM_HOME_CHANNEL_NAME",
+ "FEISHU_HOME_CHANNEL", "FEISHU_HOME_CHANNEL_NAME", "YUANBAO_HOME_CHANNEL", "YUANBAO_HOME_CHANNEL_NAME",
+ "WECOM_BOT_ID", "WECOM_SECRET", "WECOM_CALLBACK_CORP_ID", "WECOM_CALLBACK_CORP_SECRET",
+ "WECOM_CALLBACK_AGENT_ID", "WECOM_CALLBACK_TOKEN", "WECOM_CALLBACK_ENCODING_AES_KEY",
+ "WECOM_CALLBACK_HOST", "WECOM_CALLBACK_PORT", "WECOM_HOME_CHANNEL", "WECOM_HOME_CHANNEL_NAME",
"WEIXIN_ACCOUNT_ID", "WEIXIN_TOKEN", "WEIXIN_BASE_URL", "WEIXIN_CDN_BASE_URL",
"WEIXIN_HOME_CHANNEL", "WEIXIN_HOME_CHANNEL_NAME", "WEIXIN_DM_POLICY", "WEIXIN_GROUP_POLICY",
"WEIXIN_ALLOWED_USERS", "WEIXIN_GROUP_ALLOWED_USERS", "WEIXIN_ALLOW_ALL_USERS",
- "BLUEBUBBLES_SERVER_URL", "BLUEBUBBLES_PASSWORD",
- "BLUEBUBBLES_HOME_CHANNEL", "BLUEBUBBLES_HOME_CHANNEL_NAME",
+ "BLUEBUBBLES_SERVER_URL", "BLUEBUBBLES_PASSWORD", "BLUEBUBBLES_HOME_CHANNEL", "BLUEBUBBLES_HOME_CHANNEL_NAME",
"QQ_APP_ID", "QQ_CLIENT_SECRET", "QQBOT_HOME_CHANNEL", "QQBOT_HOME_CHANNEL_NAME",
"QQ_HOME_CHANNEL", "QQ_HOME_CHANNEL_NAME", # legacy aliases (pre-rename, still read for back-compat)
"QQ_ALLOWED_USERS", "QQ_GROUP_ALLOWED_USERS", "QQ_ALLOW_ALL_USERS", "QQ_MARKDOWN_SUPPORT",
"QQ_STT_API_KEY", "QQ_STT_BASE_URL", "QQ_STT_MODEL",
- "IRC_SERVER", "IRC_PORT", "IRC_NICKNAME", "IRC_CHANNEL",
- "IRC_USE_TLS", "IRC_SERVER_PASSWORD", "IRC_NICKSERV_PASSWORD",
- "TERMINAL_ENV", "TERMINAL_SSH_KEY", "TERMINAL_SSH_PORT",
- # HERMES_TOOL_PROGRESS_MODE is deprecated (replaced by display.tool_progress
- # in config.yaml) but STILL READ at runtime by the gateway as a back-compat
- # fallback, so it must stay known to reload/compat paths. The boolean
- # HERMES_TOOL_PROGRESS variant is fully unsupported since the v12 config
- # support floor retired its only consumer (the v3→4 migration): it is no
- # longer listed here and doctor flags it as ignored.
+ "IRC_SERVER", "IRC_PORT", "IRC_NICKNAME", "IRC_CHANNEL", "IRC_USE_TLS", "IRC_SERVER_PASSWORD",
+ "IRC_NICKSERV_PASSWORD", "TERMINAL_ENV", "TERMINAL_SSH_KEY", "TERMINAL_SSH_PORT",
+ # HERMES_TOOL_PROGRESS_MODE is deprecated (replaced by display.tool_progress) but STILL READ
+ # by the gateway as a back-compat fallback, so it must stay known to reload/compat paths. The
+ # boolean HERMES_TOOL_PROGRESS variant is unsupported since the v12 support floor retired its
+ # only consumer (the v3→4 migration): not listed here; doctor flags it as ignored.
"HERMES_TOOL_PROGRESS_MODE",
"WHATSAPP_MODE", "WHATSAPP_ENABLED",
"MATTERMOST_HOME_CHANNEL", "MATTERMOST_HOME_CHANNEL_NAME", "MATTERMOST_REPLY_MODE",
"MATRIX_PASSWORD", "MATRIX_ENCRYPTION", "MATRIX_DEVICE_ID", "MATRIX_HOME_ROOM",
"MATRIX_REQUIRE_MENTION", "MATRIX_FREE_RESPONSE_ROOMS", "MATRIX_AUTO_THREAD", "MATRIX_DM_AUTO_THREAD",
"MATRIX_RECOVERY_KEY",
- # Langfuse observability plugin — optional tuning keys + standard SDK vars.
- # Activation is via plugins.enabled (opt-in through `hermes plugins enable
- # observability/langfuse` or `hermes tools → Langfuse`); credentials gate
- # the plugin at runtime.
- "HERMES_LANGFUSE_ENV",
- "HERMES_LANGFUSE_RELEASE",
- "HERMES_LANGFUSE_SAMPLE_RATE",
- "HERMES_LANGFUSE_MAX_CHARS",
- "HERMES_LANGFUSE_CAPTURE",
- "HERMES_LANGFUSE_DEBUG",
- "LANGFUSE_PUBLIC_KEY",
- "LANGFUSE_SECRET_KEY",
- "LANGFUSE_BASE_URL",
- # ACP (Agent Client Protocol) keys — profile-isolable so different
- # profiles can use different ACP backends without cross-leak.
- "HERMES_ACP_AUTH_METHOD",
- "HERMES_ACP_AUTO_APPROVE",
- "HERMES_COPILOT_ACP_COMMAND",
- "HERMES_COPILOT_ACP_ARGS",
- "COPILOT_CLI_PATH",
- "COPILOT_ACP_BASE_URL",
+ # Langfuse observability plugin — optional tuning keys + standard SDK vars. Activation is via
+ # plugins.enabled (`hermes plugins enable observability/langfuse` / `hermes tools → Langfuse`);
+ # credentials gate the plugin at runtime.
+ "HERMES_LANGFUSE_ENV", "HERMES_LANGFUSE_RELEASE", "HERMES_LANGFUSE_SAMPLE_RATE",
+ "HERMES_LANGFUSE_MAX_CHARS", "HERMES_LANGFUSE_CAPTURE", "HERMES_LANGFUSE_DEBUG",
+ "LANGFUSE_PUBLIC_KEY", "LANGFUSE_SECRET_KEY", "LANGFUSE_BASE_URL",
+ # ACP (Agent Client Protocol) keys — profile-isolable so different profiles can use
+ # different ACP backends without cross-leak.
+ "HERMES_ACP_AUTH_METHOD", "HERMES_ACP_AUTO_APPROVE", "HERMES_COPILOT_ACP_COMMAND",
+ "HERMES_COPILOT_ACP_ARGS", "COPILOT_CLI_PATH", "COPILOT_ACP_BASE_URL",
})
import yaml
@@ -449,11 +347,8 @@ _IGNORED_MANAGED_VALUES = frozenset({"brew", "homebrew"})
def get_managed_system() -> Optional[str]:
"""Return the package manager owning this install, if any."""
- raw = os.getenv("HERMES_MANAGED", "").strip()
- marker = None
- if raw:
- marker = raw.lower()
- else:
+ marker = os.getenv("HERMES_MANAGED", "").strip().lower() or None
+ if marker is None:
managed_marker = get_hermes_home() / ".managed"
# An interactive shell reads the marker, because it does not see the
# HERMES_MANAGED variable of the service. A marker with content
@@ -464,24 +359,18 @@ def get_managed_system() -> Optional[str]:
except OSError:
marker = ""
- if marker is None:
- return None
-
- if marker in _IGNORED_MANAGED_VALUES:
+ if marker is None or marker in _IGNORED_MANAGED_VALUES:
return None
-
if marker == "" or marker in _MANAGED_TRUE_VALUES:
return _LEGACY_MANAGED_SYSTEM
-
return marker
def is_managed() -> bool:
"""Check if Hermes is running in package-manager-managed mode.
- Two signals: the HERMES_MANAGED env var (set by the systemd service),
- or a .managed marker file in HERMES_HOME (set by the NixOS activation
- script, so interactive shells also see it).
+ Two signals: the HERMES_MANAGED env var (set by the systemd service) or a .managed marker
+ file in HERMES_HOME (set by the NixOS activation script so interactive shells see it too).
"""
return get_managed_system() is not None
@@ -506,61 +395,23 @@ def get_managed_update_command() -> Optional[str]:
def _install_method_project_root(project_root: Optional[Path] = None) -> Path:
"""Resolve the directory that holds the *running code* (the install tree).
- This is the parent of ``hermes_cli/`` — i.e. the git checkout for source
- installs, ``/opt/hermes`` inside the published image. It is a property of
- the running interpreter, NOT of ``$HERMES_HOME``, which is why a
- code-scoped stamp here is immune to two installs sharing one data
- directory.
+ This is the parent of ``hermes_cli/`` — i.e. the git checkout for source installs,
+ ``/opt/hermes`` inside the published image. It is a property of the running interpreter, NOT of
+ ``$HERMES_HOME``, which is why a code-scoped stamp here is immune to two installs sharing one
+ data directory.
"""
- if project_root is not None:
- return project_root
- return Path(__file__).parent.parent.resolve()
+ return project_root if project_root is not None else get_project_root()
def detect_install_method(project_root: Optional[Path] = None) -> str:
- """Detect how Hermes was installed: 'apt', 'docker', 'nix', 'nixos',
- 'home-manager', 'git', or 'unknown'.
-
- Resolution order:
- 1. Code-scoped stamp ``<install tree>/.install_method`` (next to the
- running code) — the authoritative marker.
- 2. Legacy home-scoped stamp ``$HERMES_HOME/.install_method`` — read for
- backward compatibility, but a ``docker`` value is IGNORED when we are
- not actually running inside a container (see below).
- 3. HERMES_MANAGED env / .managed marker (NixOS managed mode)
- 4. /nix/store/ path detection -> 'nix' (nix run / nix profile install)
- 5. .git directory presence -> 'git'
- 6. Fallback -> 'unknown'
-
- Why the stamp is code-scoped, not home-scoped (issue: shared ``~/.hermes``)
- --------------------------------------------------------------------------
- The install method describes *the binary that is running*, but
- ``$HERMES_HOME`` is a shared DATA directory — the Docker docs deliberately
- bind-mount it (``~/.hermes:/opt/data``) so config/sessions/memory persist
- and can be shared with a host-side Desktop/CLI install. When a
- containerised gateway and a host install share one ``$HERMES_HOME``, a
- home-scoped stamp is a single slot describing two different installs:
- the container stamps ``docker`` on every boot, the host install then reads
- ``docker`` and ``hermes update`` refuses to run ("doesn't apply inside the
- Docker container") even though the host binary is a perfectly updatable
- git/pip install. Scoping the stamp to the install tree gives each install
- its own truthful marker.
-
- Self-healing for already-poisoned homes: a legacy ``docker`` value in the
- home-scoped stamp is only honoured when we are genuinely in a container.
- On a host install that read a contaminating ``docker`` stamp, we fall
- through to managed/.git detection instead — so existing shared-home
- setups recover without the user touching anything.
-
- Note: running inside a container is NOT treated as "docker" on its own.
- The supported installs self-identify via the code-scoped stamp:
- - the curl installer (scripts/install.sh, the README/website install
- command) git-clones the repo and stamps ``git`` next to the code;
- - the published ``nousresearch/hermes-agent`` image bakes a ``docker``
- stamp into ``/opt/hermes`` at build time.
- An unsupported manual install dropped into a container (no stamp) falls
- through to the ``.git`` checks and behaves like any off-path install.
- See issue #34397.
+ """Detect how Hermes was installed: apt/docker/nix/nixos/home-manager/git/unknown.
+
+ Order: code-scoped ``<install tree>/.install_method`` stamp (authoritative) -> legacy
+ ``$HERMES_HOME/.install_method`` -> managed marker -> /nix/store path -> .git dir -> unknown.
+ The stamp lives next to the code because HERMES_HOME is shared data: a container and a host
+ install can bind-mount the same home, so a home-scoped ``docker`` stamp would make the host
+ ``hermes update`` refuse to run. A legacy ``docker`` value is therefore ignored unless we are
+ really inside a container, and being in a container alone never implies 'docker'.
"""
root = _install_method_project_root(project_root)
# "apt" is intentionally the Termux APT distribution identifier, not a
@@ -572,29 +423,25 @@ def detect_install_method(project_root: Optional[Path] = None) -> str:
# home-manager install gives "unknown".
supported_methods = {"apt", "docker", "nix", "nixos", "home-manager", "git", "unknown"}
+ def _stamp(path: Path) -> Optional[str]:
+ try:
+ method = path.read_text(encoding="utf-8").strip().lower()
+ except OSError:
+ return None
+ return method if method in supported_methods else None
+
# 1. Code-scoped stamp — authoritative, immune to shared $HERMES_HOME.
- try:
- method = (root / ".install_method").read_text(encoding="utf-8").strip().lower()
- if method in supported_methods:
- return method
- except OSError:
- pass
+ method = _stamp(root / ".install_method")
+ if method:
+ return method
# 2. Legacy home-scoped stamp — back-compat. Ignore a ``docker`` value
# when we are not actually containerised: that is the signature of a
# host install whose shared $HERMES_HOME was stamped by a co-located
# container, and honouring it wrongly blocks ``hermes update``.
- try:
- method = (
- (get_hermes_home() / ".install_method")
- .read_text(encoding="utf-8")
- .strip()
- .lower()
- )
- if method in supported_methods and not (method == "docker" and not _running_in_container()):
- return method
- except OSError:
- pass
+ method = _stamp(get_hermes_home() / ".install_method")
+ if method and not (method == "docker" and not _running_in_container()):
+ return method
managed = get_managed_system()
if managed:
@@ -611,16 +458,14 @@ def detect_install_method(project_root: Optional[Path] = None) -> str:
except OSError:
pass
- # detect git repo installs (normal installer, development env)
+ # detect git repo installs (normal installer, development env) — a .git
+ # directory, or a ``gitdir:`` pointer file for worktrees.
git_path = root / ".git"
if git_path.is_dir():
return "git"
-
- # detect git repo installs from worktrees
if git_path.is_file():
try:
- content = git_path.read_text(encoding="utf-8").strip()
- if content.startswith("gitdir:"):
+ if git_path.read_text(encoding="utf-8").strip().startswith("gitdir:"):
return "git"
except OSError:
pass
@@ -637,33 +482,12 @@ def _running_in_container() -> bool:
return False
-def stamp_install_method(method: str, project_root: Optional[Path] = None) -> None:
- """Write the install method next to the running code (code-scoped stamp).
-
- The stamp lives in the install tree (``<install tree>/.install_method``),
- not in ``$HERMES_HOME``, so that two installs sharing one data directory
- do not overwrite each other's marker. See ``detect_install_method`` for
- the full rationale.
-
- Best-effort: if the install tree is read-only (e.g. the immutable
- ``/opt/hermes`` in the published image, which instead bakes the stamp at
- build time) the write silently no-ops and detection falls back to its
- other signals.
- """
- root = _install_method_project_root(project_root)
- try:
- root.mkdir(parents=True, exist_ok=True)
- (root / ".install_method").write_text(method + "\n", encoding="utf-8")
- except OSError:
- pass
-
-
def is_nix_install_method(method: str) -> bool:
"""Return True for every install method that Nix owns.
- The callers that branch on the install method must treat "nix",
- "nixos" and "home-manager" the same way. One helper keeps the three
- names in one place, so a new Nix shape cannot miss a call site.
+ The callers that branch on the install method must treat "nix", "nixos" and "home-manager" the
+ same way. One helper keeps the three names in one place, so a new Nix shape cannot miss a call
+ site.
"""
return method == "nix" or method in _NIX_MANAGED_SYSTEMS
@@ -693,21 +517,12 @@ def recommended_update_command() -> str:
return recommended_update_command_for_method(method)
-# Long-form text for ``hermes update`` / ``--check`` when running inside the
-# Docker image. Surfaced by ``cmd_update`` and ``_cmd_update_check`` in
-# hermes_cli/main.py; lives here so the wording stays consistent and we
-# don't grow two slightly-different copies.
-#
-# Why this matters:
-# - The published image excludes ``.git`` (see .dockerignore), so the
-# git-based update path can never succeed inside the container.
-# - The pre-existing fallback message ("✗ Not a git repository. Please
-# reinstall: curl ... install.sh") is actively misleading inside Docker
-# — that script installs a *new* host-side Hermes, it doesn't update
-# the running container.
-# - The right action is ``docker pull`` + restart the container; this
-# helper spells that out, with notes on tag pinning and config
-# persistence so users don't get blindsided.
+# Long-form text for ``hermes update`` / ``--check`` inside the Docker image,
+# shared by ``cmd_update`` and ``_cmd_update_check`` (hermes_cli/main.py) so the
+# wording never forks. The published image excludes ``.git`` (.dockerignore), so
+# the git update path can never succeed there, and the generic "Not a git
+# repository, reinstall via install.sh" fallback is misleading (that installs a
+# NEW host-side Hermes). The right action is ``docker pull`` + restart.
_DOCKER_UPDATE_MESSAGE = """\
✗ ``hermes update`` doesn't apply inside the Docker container.
@@ -738,9 +553,8 @@ Notes:
def format_docker_update_message() -> str:
"""Return the user-facing message for ``hermes update`` inside Docker.
- Centralised so ``cmd_update`` (the apply path) and ``_cmd_update_check``
- (the dry-run path) share the same wording. See ``_DOCKER_UPDATE_MESSAGE``
- above for the full rationale.
+ Centralised so ``cmd_update`` (the apply path) and ``_cmd_update_check`` (the dry-run path)
+ share the same wording. See ``_DOCKER_UPDATE_MESSAGE`` above for the full rationale.
"""
return _DOCKER_UPDATE_MESSAGE
@@ -765,13 +579,9 @@ def managed_error(action: str = "modify configuration"):
def get_container_exec_info() -> Optional[dict]:
"""Read container mode metadata from HERMES_HOME/.container-mode.
- Returns a dict with keys: backend, container_name, exec_user, hermes_bin
- or None if container mode is not active, we're already inside the
- container, or HERMES_DEV=1 is set.
-
- The .container-mode file is written by the NixOS activation script when
- container.enable = true. It tells the host CLI to exec into the container
- instead of running locally.
+ Written by the NixOS activation script when container.enable = true; tells the host CLI to
+ exec into the container instead of running locally. Returns None when container mode is off,
+ when already inside the container, or when HERMES_DEV=1 is set.
"""
if os.environ.get("HERMES_DEV") == "1":
return None
@@ -794,16 +604,11 @@ def get_container_exec_info() -> Optional[dict]:
return None
# All other exceptions (PermissionError, malformed data, etc.) propagate
- backend = info.get("backend", "docker")
- container_name = info.get("container_name", "hermes-agent")
- exec_user = info.get("exec_user", "hermes")
- hermes_bin = info.get("hermes_bin", "/data/current-package/bin/hermes")
-
return {
- "backend": backend,
- "container_name": container_name,
- "exec_user": exec_user,
- "hermes_bin": hermes_bin,
+ "backend": info.get("backend", "docker"),
+ "container_name": info.get("container_name", "hermes-agent"),
+ "exec_user": info.get("exec_user", "hermes"),
+ "hermes_bin": info.get("hermes_bin", "/data/current-package/bin/hermes"),
}
@@ -812,7 +617,7 @@ def get_container_exec_info() -> Optional[dict]:
# =============================================================================
# Re-export from hermes_constants — canonical definition lives there.
-from hermes_constants import get_hermes_home, get_process_hermes_home # noqa: F811,E402
+from hermes_constants import get_hermes_home, get_process_hermes_home # noqa: E402,F401
from utils import atomic_replace, fast_safe_load
def get_config_path() -> Path:
@@ -823,13 +628,13 @@ def get_config_path() -> Path:
def require_parseable_user_config(*, ignore_user_config: bool = False) -> None:
"""Reject an existing invalid config before a non-interactive agent run.
- Interactive surfaces retain ``load_config()``'s recovery behavior so the
- operator can repair their configuration. A one-shot or single-query run
- has no such repair opportunity: allowing defaults there can silently pick
- a hosted provider/model and spend against credentials loaded from ``.env``.
+ Interactive surfaces retain ``load_config()``'s recovery behavior so the operator can repair
+ their configuration. A one-shot or single-query run has no such repair opportunity: allowing
+ defaults there can silently pick a hosted provider/model and spend against credentials loaded
+ from ``.env``.
- Missing and empty files remain valid first-run states. The explicit
- ``--ignore-user-config``/safe-mode escape hatch also remains authoritative.
+ Missing and empty files remain valid first-run states. The explicit ``--ignore-user-
+ config``/safe-mode escape hatch also remains authoritative.
"""
if ignore_user_config or os.environ.get("HERMES_IGNORE_USER_CONFIG") == "1":
return
@@ -872,44 +677,27 @@ def get_project_root() -> Path:
def _resolve_hermes_uid_gid() -> tuple[Optional[int], Optional[int]]:
"""Read the HERMES_UID / HERMES_GID env vars set by Docker deployments.
- Docker containers running Hermes commonly set these to map the in-container
- user to a host user so volume-mounted state files end up with the right
- ownership. The entrypoint chowns the top-level HERMES_HOME once, but
- subdirectories created at runtime by ``ensure_hermes_home()`` (especially
- for profile namespaces under ``profiles/<name>/``) need the same chown
- or they land as ``root:root`` and block subsequent uid-mapped workers
- with ``PermissionError [Errno 13]``. See #34107.
-
- Returns ``(uid, gid)`` parsed from the env vars, or ``(None, None)``
- when either is missing/invalid. Returns ``(None, None)`` on Windows
- too (where chown is a no-op anyway).
+ The entrypoint chowns the top-level HERMES_HOME once, but subdirectories created at runtime
+ (notably ``profiles/<name>/``) need the same chown or they land as root:root and block later
+ uid-mapped workers with PermissionError. Returns (None, None) if unset/invalid or on Windows.
"""
if sys.platform == "win32":
return None, None
- uid_str = os.environ.get("HERMES_UID", "").strip()
- gid_str = os.environ.get("HERMES_GID", "").strip()
- try:
- uid = int(uid_str) if uid_str else None
- except ValueError:
- uid = None
- try:
- gid = int(gid_str) if gid_str else None
- except ValueError:
- gid = None
- return uid, gid
+ def _env_int(name: str) -> Optional[int]:
+ raw = os.environ.get(name, "").strip()
+ try:
+ return int(raw) if raw else None
+ except ValueError:
+ return None
+
+ return _env_int("HERMES_UID"), _env_int("HERMES_GID")
def _chown_to_hermes_uid(path) -> None:
"""Chown ``path`` to ``HERMES_UID:HERMES_GID`` if those env vars are set.
- No-op when:
- - Either env var is unset/invalid
- - The current process isn't root (chown will EPERM — silently ignored)
- - On Windows (chown semantics don't apply)
-
- Used by :func:`_secure_dir` to keep ownership consistent across all
- directories created by :func:`ensure_hermes_home` on Docker deployments.
- See #34107.
+ No-op when: - Either env var is unset/invalid - The current process isn't root (chown will EPERM
+ — silently ignored) - On Windows (chown semantics don't apply)
"""
uid, gid = _resolve_hermes_uid_gid()
if uid is None and gid is None:
@@ -931,28 +719,24 @@ def _chown_to_hermes_uid(path) -> None:
def _secure_dir(path):
"""Set directory to owner-only access (0700 by default). No-op on Windows.
- Skipped in managed mode — the NixOS module sets group-readable
- permissions (0750) so interactive users in the hermes group can
- share state with the gateway service.
+ The mode can be overridden via the HERMES_HOME_MODE environment variable (e.g.
+ HERMES_HOME_MODE=0701) for deployments where a web server (nginx, caddy, etc.) needs to traverse
+ HERMES_HOME to reach a served subdirectory. The execute-only bit on a directory permits cd-
+ through without exposing directory listings.
- The mode can be overridden via the HERMES_HOME_MODE environment variable
- (e.g. HERMES_HOME_MODE=0701) for deployments where a web server (nginx,
- caddy, etc.) needs to traverse HERMES_HOME to reach a served subdirectory.
- The execute-only bit on a directory permits cd-through without exposing
- directory listings.
-
- Also applies ``HERMES_UID``/``HERMES_GID``-based ownership when those env
- vars are set (#34107 — Docker deployments need this so profile subdirs
- created at runtime by kanban workers don't land as root:root and block
- subsequent uid-mapped workers).
+ Also applies ``HERMES_UID``/``HERMES_GID``-based ownership when those env vars are set (#34107 —
+ Docker deployments need this so profile subdirs created at runtime by kanban workers don't land
+ as root:root and block subsequent uid-mapped workers).
"""
if is_managed():
return
+ mode = 0o700
try:
mode_str = os.environ.get("HERMES_HOME_MODE", "").strip()
- mode = int(mode_str, 8) if mode_str else 0o700
+ if mode_str:
+ mode = int(mode_str, 8)
except ValueError:
- mode = 0o700
+ pass
try:
os.chmod(path, mode)
except (OSError, NotImplementedError):
@@ -963,10 +747,8 @@ def _secure_dir(path):
def _is_container() -> bool:
"""Detect if we're running inside a Docker/Podman/LXC container.
- When Hermes runs in a container with volume-mounted config files, forcing
- 0o600 permissions breaks multi-process setups where the gateway and
- dashboard run as different UIDs or the volume mount requires broader
- permissions.
+ Used to skip forcing 0o600 on volume-mounted config: in containers the gateway and dashboard
+ may run as different UIDs, or the mount itself needs broader permissions.
"""
# Explicit opt-out
if os.environ.get("HERMES_CONTAINER") or os.environ.get("HERMES_SKIP_CHMOD"):
@@ -988,11 +770,8 @@ def _is_container() -> bool:
def _secure_file(path):
"""Set file to owner-only read/write (0600). No-op on Windows.
- Skipped in managed mode — the NixOS activation script sets
- group-readable permissions (0640) on config files.
-
- Skipped in containers — Docker/Podman volume mounts often need broader
- permissions. Set HERMES_SKIP_CHMOD=1 to force-skip on other systems.
+ Skipped in managed mode (the NixOS activation script sets 0640 group-readable config) and in
+ containers (volume mounts often need broader permissions). HERMES_SKIP_CHMOD=1 forces a skip.
"""
if is_managed() or _is_container():
return
@@ -1006,10 +785,9 @@ def _secure_file(path):
def _ensure_default_soul_md(home: Path) -> None:
"""Seed a default SOUL.md into HERMES_HOME, upgrading legacy empty templates.
- First run: write DEFAULT_SOUL_MD. Existing installs whose SOUL.md is still
- the old comment-only scaffold (seeded by older install.sh / install.ps1 /
- docker images, which shadowed the runtime default) get upgraded in place to
- DEFAULT_SOUL_MD. A SOUL.md the user actually customized is never touched.
+ First run: write DEFAULT_SOUL_MD. Installs whose SOUL.md is still the old comment-only
+ scaffold (seeded by older installers/images, shadowing the runtime default) are upgraded in
+ place. A SOUL.md the user actually customized is never touched.
"""
soul_path = home / "SOUL.md"
if soul_path.exists():
@@ -1033,17 +811,9 @@ _HERMES_HOME_ENSURED: set = set()
def ensure_hermes_home():
"""Ensure ~/.hermes directory structure exists with secure permissions.
- In managed mode (NixOS), dirs are created by the activation script with
- setgid + group-writable (2770). We skip mkdir and set umask(0o007) so
- any files created (e.g. SOUL.md) are group-writable (0660).
-
- Memoized per home path: this runs on EVERY ``load_config()`` (inside the
- config lock), and the ~14 mkdir/chmod syscalls per call made repeated
- config loads the dominant cost of hot read paths like ``model.options``.
- After the first successful pass for a given ``HERMES_HOME`` we only re-run
- the full walk if the home directory itself has vanished (a deleted home is
- recreated on the next load, as before). Profile switches change
- ``get_hermes_home()`` and therefore re-run for the new path.
+ Memoized per home path: this runs on EVERY ``load_config()`` (inside the config lock), and the
+ ~14 mkdir/chmod syscalls per call made repeated config loads the dominant cost of hot read paths
+ like ``model.options``.
"""
home = get_hermes_home()
key = str(home)
@@ -1126,40 +896,23 @@ REQUIRED_ENV_VARS = {}
def get_missing_env_vars(required_only: bool = False) -> List[Dict[str, Any]]:
- """
- Check which environment variables are missing.
-
- Returns list of dicts with var info for missing variables.
- """
- missing = []
-
- # Check required vars
- for var_name, info in REQUIRED_ENV_VARS.items():
- if not get_env_value(var_name):
- missing.append({"name": var_name, **info, "is_required": True})
-
- # Check optional vars (if not required_only)
+ """Check which environment variables are missing."""
+ groups = [(REQUIRED_ENV_VARS, True)]
if not required_only:
- for var_name, info in OPTIONAL_ENV_VARS.items():
- if not get_env_value(var_name):
- missing.append({"name": var_name, **info, "is_required": False})
-
- return missing
+ groups.append((OPTIONAL_ENV_VARS, False))
+ return [
+ {"name": var_name, **info, "is_required": is_required}
+ for table, is_required in groups
+ for var_name, info in table.items()
+ if not get_env_value(var_name)
+ ]
def _split_key_path(key: str) -> list[str]:
"""Split a dotted config-key path, honoring backslash-escaped dots.
- ``hermes config set`` uses ``.`` as the nesting separator, so a key that
- itself contains a literal dot (e.g. provider names like
- ``qwen3.5-397b-wafer``) was silently split into bogus nested segments
- (#84064). A backslash escapes a dot::
-
- _split_key_path("providers.qwen3\\.5-397b.api_key")
- -> ["providers", "qwen3.5-397b", "api_key"]
-
- Backslashes before any other character are preserved verbatim. Keys
- without escapes behave exactly as ``key.split(".")``.
+ Backslashes before any other character are preserved verbatim. Keys without escapes behave
+ exactly as ``key.split(".")``.
"""
parts: list[str] = []
current: list[str] = []
@@ -1184,77 +937,38 @@ def _split_key_path(key: str) -> list[str]:
def _greedy_literal_match(container: dict, parts: list) -> Optional[Tuple[str, int]]:
"""Return ``(literal_key, n_consumed)`` for the longest dotted literal match.
- Dots in config key names are the norm, not the exception — model IDs
- (``grok-4.6``, ``glm-5.3``), Matrix room IDs (``!room:chat.example.cc``),
- and versioned provider names all embed dots. Users typing
- ``providers.myprov.models.grok-4.6.context_length`` do not know the
- escape syntax exists, so when navigating an EXISTING mapping we prefer an
- existing literal key equal to the dot-join of the next N path segments
- (longest match wins) over blindly splitting. See #84064 / #80006 /
- #91095 / #91607 / #99124.
-
- Backward compatible: when no multi-segment literal key exists, the single
- segment ``parts[0]`` is the only candidate, which is exactly the historic
- plain-split behavior. Returns ``None`` when nothing matches.
+ Backward compatible: when no multi-segment literal key exists, the single segment ``parts[0]``
+ is the only candidate, which is exactly the historic plain-split behavior. Returns ``None`` when
+ nothing matches.
"""
if not isinstance(container, dict) or not parts:
return None
- for n in range(len(parts), 0, -1):
- candidate = ".".join(parts[:n])
- if candidate in container:
- return candidate, n
- return None
+ return next(
+ ((".".join(parts[:n]), n) for n in range(len(parts), 0, -1) if ".".join(parts[:n]) in container),
+ None,
+ )
def _phantom_sibling(container: dict, part: str) -> Optional[str]:
"""Return an existing sibling key that ``part`` would shadow, if any.
- Called when a write is about to CREATE a new intermediate mapping named
- ``part``. If the mapping already holds a literal dotted key that starts
- with ``part + "."`` (e.g. creating ``grok-4`` beside an existing
- ``grok-4.5``), the split almost certainly chopped a dotted leaf name and
- the write would produce a phantom sibling the runtime never reads.
- Fail loudly instead of silently corrupting (#84064 discussion).
+ Called before CREATING an intermediate mapping named ``part``. If the mapping already holds
+ a literal dotted key starting with ``part + '.'`` (creating ``grok-4`` beside ``grok-4.5``),
+ the split chopped a dotted leaf and the write would produce a phantom sibling the runtime
+ never reads -- fail loudly instead of silently corrupting.
"""
if not isinstance(container, dict):
return None
prefix = part + "."
- for k in container:
- if isinstance(k, str) and k.startswith(prefix):
- return k
- return None
+ return next((k for k in container if isinstance(k, str) and k.startswith(prefix)), None)
def _set_nested(config, dotted_key: str, value):
"""Set a value at an arbitrarily nested dotted key path.
- Supports both dict and list navigation:
- _set_nested(c, "a.b.c", 1) → c["a"]["b"]["c"] = 1
- _set_nested(c, "a.0.b", 1) → c["a"][0]["b"] = 1
- _set_nested(c, "providers.1", "x") → c["providers"][1] = "x"
-
- Intermediate dicts are created on demand. List indices are parsed
- from numeric path segments; the referenced index must already exist
- (we do not grow lists — the user is navigating into structure they
- wrote themselves). If a segment targets a non-container leaf
- (scalar), the leaf is replaced with a fresh dict so the write can
- proceed — this preserves the pre-existing behavior for bare scalar
- overrides (e.g. setting ``a.b.c`` where ``a.b`` was previously a
- string).
-
- Guards against #17876: before this fix the code unconditionally
- replaced any non-dict value (including lists) with ``{}``, silently
- destroying list-typed config like ``custom_providers`` whenever a
- caller used an indexed path.
-
- Dotted key names (#84064 family): when navigating an existing mapping,
- an existing literal key equal to the dot-join of the next N segments is
- preferred over blind splitting (see ``_greedy_literal_match``), so
- ``models.grok-4.6.supports_vision`` lands on the real ``grok-4.6`` entry.
- And when a write WOULD create a new intermediate mapping that shadows an
- existing dotted sibling (``grok-4`` beside ``grok-4.5``), it raises
- ``ValueError`` instead of silently writing a phantom the runtime never
- reads.
+ Intermediate dicts are created on demand. List indices are parsed from numeric path segments;
+ the referenced index must already exist (we do not grow lists — the user is navigating into
+ structure they wrote themselves).
"""
parts = _split_key_path(dotted_key)
current = config
@@ -1323,11 +1037,10 @@ def clear_model_endpoint_credentials(
) -> Dict[str, Any]:
"""Remove stale inline endpoint credentials from a model config.
- ``model.api_key`` is valid only for explicit custom endpoint assignments.
- Built-in providers resolve credentials from env vars, auth.json, or the
- credential pool. When switching away from a custom endpoint, leaving these
- fields behind keeps secrets in config.yaml and can contaminate later custom
- resolution paths.
+ ``model.api_key`` is valid only for explicit custom endpoint assignments. Built-in providers
+ resolve credentials from env vars, auth.json, or the credential pool. When switching away from a
+ custom endpoint, leaving these fields behind keeps secrets in config.yaml and can contaminate
+ later custom resolution paths.
"""
if not isinstance(model_cfg, dict):
return model_cfg
@@ -1344,86 +1057,67 @@ def clear_model_endpoint_credentials(
_MISSING = object()
-def _get_nested(config, dotted_key: str):
- """Return a dotted-path value from nested dict/list config data.
+def _locate_nested(config, parts: list):
+ """Walk *parts* through nested dicts/lists (escape-aware, greedy-literal like ``_set_nested``).
- Mirrors ``_set_nested``'s navigation: honors backslash-escaped dots and
- prefers an existing literal dotted key over blind splitting, so
- ``config get providers.p.models.grok-4.6.context_length`` reads the real
- ``grok-4.6`` entry instead of reporting the key unset (#84064).
+ Returns ``(parents, container, key)`` where ``container[key]`` is the addressed leaf and
+ ``parents`` lists the ``(container, key)`` hops above it, or ``None`` when any hop is missing,
+ a list index is non-numeric/out of range, or a scalar is hit before the path is consumed.
"""
- parts = _split_key_path(dotted_key)
+ parents = []
current = config
i = 0
- while i < len(parts):
+ while True:
remaining = parts[i:]
if isinstance(current, list):
try:
- current = current[int(remaining[0])]
+ key = int(remaining[0])
+ current[key]
except (TypeError, ValueError, IndexError):
- return _MISSING
- i += 1
+ return None
+ consumed = 1
elif isinstance(current, dict):
match = _greedy_literal_match(current, remaining)
if match is None:
- return _MISSING
+ return None
key, consumed = match
- current = current[key]
- i += consumed
else:
- return _MISSING
- return current
+ return None
+ i += consumed
+ if i == len(parts):
+ return parents, current, key
+ parents.append((current, key))
+ current = current[key]
-def _unset_nested(config, dotted_key: str) -> bool:
- """Remove a dotted-path value from nested dict/list config data.
+def _get_nested(config, dotted_key: str):
+ """Return a dotted-path value from nested dict/list config data.
- Same escape-aware, greedy-literal navigation as ``_set_nested`` /
- ``_get_nested`` (#84064): unsetting an unescaped dotted key removes the
- real literal entry rather than a phantom sibling.
+ Mirrors ``_set_nested`` navigation: honors backslash-escaped dots and prefers an existing
+ literal dotted key over blind splitting, so ``models.grok-4.6.context_length`` reads the real
+ ``grok-4.6`` entry instead of reporting the key unset.
"""
- parts = _split_key_path(dotted_key)
- if not parts:
- return False
+ loc = _locate_nested(config, _split_key_path(dotted_key))
+ if loc is None:
+ return _MISSING
+ _, container, key = loc
+ return container[key]
- parents = []
- current = config
- removed = False
- i = 0
- while i < len(parts):
- remaining = parts[i:]
- if isinstance(current, list):
- part = remaining[0]
- if len(remaining) == 1:
- try:
- current.pop(int(part))
- removed = True
- break
- except (TypeError, ValueError, IndexError):
- return False
- parents.append((current, part))
- try:
- current = current[int(part)]
- except (TypeError, ValueError, IndexError):
- return False
- i += 1
- elif isinstance(current, dict):
- match = _greedy_literal_match(current, remaining)
- if match is None:
- return False
- key, consumed = match
- if i + consumed == len(parts):
- del current[key]
- removed = True
- break
- parents.append((current, key))
- current = current[key]
- i += consumed
- else:
- return False
- if not removed:
+def _unset_nested(config, dotted_key: str) -> bool:
+ """Remove a dotted-path value from nested dict/list config data.
+
+ Same escape-aware, greedy-literal navigation as ``_set_nested`` / ``_get_nested``: unsetting
+ an unescaped dotted key removes the real literal entry rather than a phantom sibling.
+ """
+ loc = _locate_nested(config, _split_key_path(dotted_key))
+ if loc is None:
return False
+ parents, current, key = loc
+ if isinstance(current, list):
+ current.pop(key)
+ else:
+ del current[key]
# Drop empty dict containers left behind by the deletion while preserving
# user-authored empty lists and non-empty sibling branches.
@@ -1431,12 +1125,8 @@ def _unset_nested(config, dotted_key: str) -> bool:
if current != {}:
break
if isinstance(parent, list):
- try:
- idx = int(part)
- except (TypeError, ValueError):
- break
- if 0 <= idx < len(parent) and parent[idx] == {}:
- parent.pop(idx)
+ if 0 <= part < len(parent) and parent[part] == {}:
+ parent.pop(part)
current = parent
continue
elif isinstance(parent, dict) and parent.get(part) == {}:
@@ -1445,7 +1135,7 @@ def _unset_nested(config, dotted_key: str) -> bool:
continue
break
- return removed
+ return True
def _is_env_config_key(key: str) -> bool:
@@ -1474,7 +1164,6 @@ def _is_env_config_key(key: str) -> bool:
def _format_config_get_value(value, *, as_json: bool) -> str:
"""Format a config value for command-line output."""
if as_json:
- import json
return json.dumps(value, ensure_ascii=False)
if isinstance(value, bool):
return "true" if value else "false"
@@ -1486,12 +1175,7 @@ def _format_config_get_value(value, *, as_json: bool) -> str:
def get_missing_config_fields() -> List[Dict[str, Any]]:
- """
- Check which config fields are missing or outdated (recursive).
-
- Walks the DEFAULT_CONFIG tree at arbitrary depth and reports any keys
- present in defaults but absent from the user's loaded config.
- """
+ """Check which config fields are missing or outdated (recursive)."""
config = load_config()
missing = []
@@ -1514,12 +1198,7 @@ def get_missing_config_fields() -> List[Dict[str, Any]]:
def get_missing_skill_config_vars() -> List[Dict[str, Any]]:
- """Return skill-declared config vars that are missing or empty in config.yaml.
-
- Scans all enabled skills for ``metadata.hermes.config`` entries, then checks
- which ones are absent or empty under ``skills.config.<key>`` in the user's
- config.yaml. Returns a list of dicts suitable for prompting.
- """
+ """Return skill-declared config vars that are missing or empty in config.yaml."""
try:
from agent.skill_utils import discover_all_skill_config_vars, SKILL_CONFIG_PREFIX
except Exception:
@@ -1531,10 +1210,7 @@ def get_missing_skill_config_vars() -> List[Dict[str, Any]]:
# A malformed SKILL.md, unreadable external skill dir, or similar
# should never break `hermes update`. Skill-config prompting is a
# post-migration nicety, not a blocker.
- import logging
- logging.getLogger(__name__).debug(
- "discover_all_skill_config_vars failed: %s", e
- )
+ logger.debug("discover_all_skill_config_vars failed: %s", e)
return []
if not all_vars:
return []
@@ -1542,19 +1218,9 @@ def get_missing_skill_config_vars() -> List[Dict[str, Any]]:
config = load_config()
missing: List[Dict[str, Any]] = []
for var in all_vars:
- # Skill config is stored under skills.config.<logical_key>
- storage_key = f"{SKILL_CONFIG_PREFIX}.{var['key']}"
- parts = storage_key.split(".")
- current = config
- value = None
- for part in parts:
- if isinstance(current, dict) and part in current:
- current = current[part]
- value = current
- else:
- value = None
- break
- # Missing = key doesn't exist or is empty string
+ # Skill config is stored under skills.config.<logical_key>;
+ # missing = key doesn't exist or is an empty string.
+ value = cfg_get(config, *f"{SKILL_CONFIG_PREFIX}.{var['key']}".split("."))
if value is None or (isinstance(value, str) and not value.strip()):
missing.append(var)
return missing
@@ -1607,21 +1273,16 @@ _API_MODE_ALIASES = {
def _canonical_api_mode(api_mode: str) -> str:
"""Map legacy/alias ``api_mode`` spellings to canonical transport names.
- Unknown values pass through unchanged (callers keep their existing
- fall-through behavior); known aliases are rewritten so downstream
- consumers (``agent_init``'s accepted-set check, runtime resolution)
- see a canonical name instead of silently discarding the user's intent.
+ Unknown values pass through unchanged (callers keep their existing fall-through behavior); known
+ aliases are rewritten so downstream consumers (``agent_init``'s accepted-set check, runtime
+ resolution) see a canonical name instead of silently discarding the user's intent.
"""
cleaned = api_mode.strip()
return _API_MODE_ALIASES.get(cleaned.lower(), cleaned)
def coerce_provider_id(value: Any) -> str:
- """Provider identity fields are strings.
-
- PyYAML loads unquoted scalars like ``provider: 2070`` / ``2070:`` as int,
- and later ``.strip()`` / ``.lower()`` on that value 500s the Model tab.
- """
+ """Provider identity fields are strings."""
if value is None:
return ""
return str(value).strip()
@@ -1630,9 +1291,8 @@ def coerce_provider_id(value: Any) -> str:
def stringify_provider_map(providers: Any) -> dict:
"""Copy a ``providers:`` mapping so keys are strings.
- Desktop Custom Endpoints store the name as the dict key. An unquoted
- YAML key ``2070:`` loads as int; picker code then calls ``ep_name.lower()``
- and CRUD looks up ``"2070"`` and misses.
+ Desktop Custom Endpoints store the name as the dict key; an unquoted YAML key ``2070:`` loads
+ as int, so picker code calling ``ep_name.lower()`` crashes and CRUD lookups of ``"2070"`` miss.
"""
if not isinstance(providers, dict):
return {}
@@ -1647,8 +1307,7 @@ def stringify_provider_map(providers: Any) -> dict:
def find_provider_entry(providers: Any, key: Any) -> Tuple[Any, Optional[Dict[str, Any]]]:
"""Return ``(stored_key, entry)`` matching *key* by string identity.
- Needed because PyYAML may have stored the key as ``2070`` (int) while
- Desktop looks up ``"2070"``. Prefer an exact string hit, then scan.
+ Prefer an exact string hit, then scan.
"""
if not isinstance(providers, dict):
return None, None
@@ -1664,6 +1323,93 @@ def find_provider_entry(providers: Any, key: Any) -> Tuple[Any, Optional[Dict[st
return None, None
+# camelCase aliases commonly used in hand-written provider configs.
+_CAMEL_ALIASES: Dict[str, str] = {
+ "apiKey": "api_key",
+ "baseUrl": "base_url",
+ "apiMode": "api_mode",
+ "keyEnv": "key_env",
+ "apiKeyEnv": "key_env", # alias — OpenClaw-compatible + docs variant
+ "defaultModel": "default_model",
+ "contextLength": "context_length",
+ "rateLimitDelay": "rate_limit_delay",
+}
+_KNOWN_PROVIDER_KEYS = {
+ # ``provider`` duplicates the ``providers.<name>`` mapping key and is unused
+ # here, but Hermes' own config writer has historically emitted it into
+ # provider entries. Accept it silently so self-written configs don't warn.
+ "provider",
+ "name", "api", "url", "base_url", "api_key", "key_env", "api_key_env", "key_cmd",
+ "api_mode", "transport", "model", "default_model", "models", "models_discovered",
+ "context_length", "rate_limit_delay", "request_timeout_seconds", "stale_timeout_seconds",
+ "discover_models", "extra_body", "extra_headers", "capabilities", "ssl_ca_cert", "ssl_verify",
+}
+
+
+def _pick_provider_base_url(entry: Dict[str, Any], provider_key: str) -> str:
+ """First usable URL among ``base_url``/``url``/``api``, or "".
+
+ URLs containing unresolved placeholder tokens — ``${ENV_VAR}`` env-refs and bare ``{region}``
+ templates — are accepted without validation: they are expanded at runtime, and a caller reaching
+ this normalizer with raw config would otherwise see the provider silently dropped.
+ """
+ from urllib.parse import urlparse
+
+ for url_key in ("base_url", "url", "api"):
+ raw_url = entry.get(url_key)
+ if not (isinstance(raw_url, str) and raw_url.strip()):
+ continue
+ candidate = raw_url.strip()
+ if re.search(r"\{[^}]+\}", candidate):
+ return candidate
+ parsed = urlparse(candidate)
+ if parsed.scheme and parsed.netloc:
+ return candidate
+ logger.warning(
+ "providers.%s: '%s' value '%s' is not a valid URL "
+ "(no scheme or host) — skipped",
+ provider_key or "?", url_key, candidate,
+ )
+ return ""
+
+
+def _normalize_provider_models(models: Any) -> Tuple[Dict[str, Any], bool]:
+ """Normalize an entry's ``models`` to the dict shape downstream expects.
+
+ Returns ``(models_dict, discovered_flag)``. Older Hermes versions wrote an in-mapping
+ ``__discovered_model_catalog__`` sentinel (accepted on read, stripped so sentinel keys never
+ surface as model IDs). Hand-edited/older configs may write a plain list of ids or ``[{id: ...}]``
+ rows; both are converted so /model doesn't show the provider with (0) models.
+ """
+ discovered = False
+ if isinstance(models, dict) and models:
+ # Shallow-copy: `models` may alias a cached config sub-dict, and the
+ # normalized entry escapes into long-lived runtime state.
+ models_copy = dict(models)
+ if models_copy.pop("__discovered_model_catalog__", None) is True:
+ discovered = True
+ models_copy.pop("__explicit_model_allowlist__", None)
+ return models_copy, discovered
+ if isinstance(models, list) and models:
+ normalized_models: Dict[str, Any] = {}
+ for item in models:
+ if isinstance(item, str) and item.strip():
+ normalized_models[item.strip()] = {}
+ continue
+ if not isinstance(item, dict):
+ continue
+ model_id = item.get("id")
+ if not isinstance(model_id, str) or not model_id.strip():
+ model_id = item.get("name")
+ if not isinstance(model_id, str) or not model_id.strip():
+ continue
+ normalized_models[model_id.strip()] = {
+ k: v for k, v in item.items() if k not in {"id", "name"}
+ }
+ return normalized_models, discovered
+ return {}, discovered
+
+
def _normalize_custom_provider_entry(
entry: Any,
*,
@@ -1673,47 +1419,18 @@ def _normalize_custom_provider_entry(
if not isinstance(entry, dict):
return None
- # Shallow-copy before the alias normalization below writes into the
- # entry: callers (get_compatible_custom_providers,
- # providers_dict_to_custom_providers) pass live sub-dicts from
- # load_config_readonly()'s shared cache, and mutating those both
- # violates the cache's no-mutation contract and leaks duplicated
- # alias keys back into config.yaml through any later
- # save_config(load_config()) round-trip.
+ # Shallow-copy before alias normalization writes into the entry: callers
+ # pass live sub-dicts from load_config_readonly()'s shared cache, and
+ # mutating those violates the cache's no-mutation contract and leaks alias
+ # keys back into config.yaml on a later save_config(load_config()).
entry = dict(entry)
provider_key = coerce_provider_id(provider_key)
- # Accept camelCase aliases commonly used in hand-written configs.
- _CAMEL_ALIASES: Dict[str, str] = {
- "apiKey": "api_key",
- "baseUrl": "base_url",
- "apiMode": "api_mode",
- "keyEnv": "key_env",
- "apiKeyEnv": "key_env", # alias — OpenClaw-compatible + docs variant
- "defaultModel": "default_model",
- "contextLength": "context_length",
- "rateLimitDelay": "rate_limit_delay",
- }
# api_key_env is a documented snake_case alias for key_env (see
# website/docs/guides/azure-foundry.md). Normalize it up front so the
# rest of the normalizer treats it as the canonical field.
if "api_key_env" in entry and "key_env" not in entry:
entry["key_env"] = entry["api_key_env"]
- _KNOWN_KEYS = {
- # ``provider`` duplicates the ``providers.<name>`` mapping key and is
- # unused here, but Hermes' own config writer has historically emitted it
- # into provider entries. Accept it silently so those (self-written)
- # configs don't warn on every load.
- "provider",
- "name", "api", "url", "base_url", "api_key", "key_env", "api_key_env",
- "key_cmd",
- "api_mode", "transport", "model", "default_model", "models",
- "models_discovered",
- "context_length", "rate_limit_delay",
- "request_timeout_seconds", "stale_timeout_seconds",
- "discover_models", "extra_body", "extra_headers", "capabilities",
- "ssl_ca_cert", "ssl_verify",
- }
for camel, snake in _CAMEL_ALIASES.items():
if camel in entry and snake not in entry:
_warn_once_per_provider(
@@ -1723,7 +1440,7 @@ def _normalize_custom_provider_entry(
provider_key or "?", camel, snake,
)
entry[snake] = entry[camel]
- unknown = set(entry.keys()) - _KNOWN_KEYS - set(_CAMEL_ALIASES.keys())
+ unknown = set(entry.keys()) - _KNOWN_PROVIDER_KEYS - set(_CAMEL_ALIASES.keys())
if unknown:
_warn_once_per_provider(
provider_key, "unknown:" + ",".join(sorted(unknown)),
@@ -1731,31 +1448,7 @@ def _normalize_custom_provider_entry(
provider_key or "?", ", ".join(sorted(unknown)),
)
- from urllib.parse import urlparse
-
- base_url = ""
- for url_key in ("base_url", "url", "api"):
- raw_url = entry.get(url_key)
- if isinstance(raw_url, str) and raw_url.strip():
- candidate = raw_url.strip()
- # Accept URLs containing unresolved placeholder tokens — both
- # ``${ENV_VAR}`` env-refs and bare ``{region}``-style templates —
- # without URL validation. They are expanded at runtime, so a
- # caller reaching this normalizer with raw (un-expanded) config
- # would otherwise see the provider silently dropped (#14457).
- if re.search(r"\{[^}]+\}", candidate):
- base_url = candidate
- break
- parsed = urlparse(candidate)
- if parsed.scheme and parsed.netloc:
- base_url = candidate
- break
- else:
- logger.warning(
- "providers.%s: '%s' value '%s' is not a valid URL "
- "(no scheme or host) — skipped",
- provider_key or "?", url_key, candidate,
- )
+ base_url = _pick_provider_base_url(entry, provider_key)
if not base_url:
return None
@@ -1772,68 +1465,37 @@ def _normalize_custom_provider_entry(
if provider_key:
normalized["provider_key"] = provider_key
- api_key = entry.get("api_key")
- if isinstance(api_key, str) and api_key.strip():
- normalized["api_key"] = api_key.strip()
+ def _stripped(*keys: str) -> str:
+ val = None
+ for k in keys:
+ val = entry.get(k)
+ if val:
+ break
+ return val.strip() if isinstance(val, str) else ""
+
+ if _stripped("api_key"):
+ normalized["api_key"] = _stripped("api_key")
- key_env = entry.get("key_env") or entry.get("api_key_env")
- if isinstance(key_env, str) and key_env.strip():
- normalized["key_env"] = key_env.strip()
+ key_env = _stripped("key_env", "api_key_env")
+ if key_env:
+ normalized["key_env"] = key_env
if entry.get("api_key_env") and not entry.get("key_env"):
- normalized["api_key_env"] = key_env.strip()
+ normalized["api_key_env"] = key_env
- api_mode = entry.get("api_mode") or entry.get("transport")
- if isinstance(api_mode, str) and api_mode.strip():
+ api_mode = _stripped("api_mode", "transport")
+ if api_mode:
normalized["api_mode"] = _canonical_api_mode(api_mode)
- model_name = entry.get("model") or entry.get("default_model")
- if isinstance(model_name, str) and model_name.strip():
- normalized["model"] = model_name.strip()
-
- # Entry-level marker: the ``models`` mapping was auto-discovered by
- # Hermes (``_save_discovered_models_to_config``), not hand-curated.
- # Older Hermes versions wrote an in-mapping ``__discovered_model_catalog__``
- # sentinel instead; accept it on read and strip it from the models
- # mapping so sentinel keys never surface as model IDs.
- models_discovered = entry.get("models_discovered") is True
-
- models = entry.get("models")
- if isinstance(models, dict) and models:
- # Shallow-copy: `entry` may alias a cached config sub-dict, and the
- # normalized entry escapes into long-lived runtime state
- # (agent._custom_providers) — don't share the cached models mapping.
- models_copy = dict(models)
- if models_copy.pop("__discovered_model_catalog__", None) is True:
- models_discovered = True
- models_copy.pop("__explicit_model_allowlist__", None)
- if models_copy:
- normalized["models"] = models_copy
- elif isinstance(models, list) and models:
- # Hand-edited configs (and older Hermes versions) may write
- # ``models`` as a plain list of ids or as ``[{id: ...}]`` rows.
- # Preserve both by converting to the dict shape downstream code
- # expects; otherwise normalize silently drops the list and /model
- # shows the provider with (0) models.
- normalized_models: Dict[str, Any] = {}
- for item in models:
- if isinstance(item, str) and item.strip():
- normalized_models[item.strip()] = {}
- continue
- if not isinstance(item, dict):
- continue
- model_id = item.get("id")
- if not isinstance(model_id, str) or not model_id.strip():
- model_id = item.get("name")
- if not isinstance(model_id, str) or not model_id.strip():
- continue
- model_meta = {
- k: v for k, v in item.items() if k not in {"id", "name"}
- }
- normalized_models[model_id.strip()] = model_meta
- if normalized_models:
- normalized["models"] = normalized_models
+ model_name = _stripped("model", "default_model")
+ if model_name:
+ normalized["model"] = model_name
- if models_discovered:
+ # Entry-level marker: the ``models`` mapping was auto-discovered by Hermes
+ # (``_save_discovered_models_to_config``), not hand-curated.
+ models_dict, discovered = _normalize_provider_models(entry.get("models"))
+ if models_dict:
+ normalized["models"] = models_dict
+ if entry.get("models_discovered") is True or discovered:
normalized["models_discovered"] = True
capabilities = entry.get("capabilities")
@@ -1854,13 +1516,11 @@ def _normalize_custom_provider_entry(
if isinstance(rate_limit_delay, (int, float)) and rate_limit_delay >= 0:
normalized["rate_limit_delay"] = rate_limit_delay
- discover_models = entry.get("discover_models")
- if isinstance(discover_models, bool):
- normalized["discover_models"] = discover_models
+ if isinstance(entry.get("discover_models"), bool):
+ normalized["discover_models"] = entry["discover_models"]
- extra_body = entry.get("extra_body")
- if isinstance(extra_body, dict):
- normalized["extra_body"] = dict(extra_body)
+ if isinstance(entry.get("extra_body"), dict):
+ normalized["extra_body"] = dict(entry["extra_body"])
# Per-provider extra HTTP headers (proxies, gateways, custom auth).
# Values may carry credentials (e.g. CF-Access-Client-Secret) — never
@@ -1898,18 +1558,9 @@ def _custom_provider_entry_to_provider_config(
provider_entry: Dict[str, Any] = {"api": normalized["base_url"]}
for field in (
- "name",
- "api_key",
- "key_env",
- "models",
- "models_discovered",
- "context_length",
- "rate_limit_delay",
- "discover_models",
- "extra_body",
- "extra_headers",
- "ssl_ca_cert",
- "ssl_verify",
+ "name", "api_key", "key_env", "models", "models_discovered", "context_length",
+ "rate_limit_delay", "discover_models", "extra_body", "extra_headers",
+ "ssl_ca_cert", "ssl_verify",
):
if field in normalized:
provider_entry[field] = normalized[field]
@@ -1945,10 +1596,9 @@ def get_compatible_custom_providers(
) -> List[Dict[str, Any]]:
"""Return a deduplicated custom-provider view across legacy and v12+ config.
- ``custom_providers`` remains the on-disk legacy format, while ``providers``
- is the newer keyed schema. Runtime and picker flows still need a single
- list-shaped view, but we should not materialise that compatibility layer
- back into config.yaml because it duplicates entries in UIs.
+ ``custom_providers`` remains the on-disk legacy format, while ``providers`` is the newer keyed
+ schema. Runtime and picker flows still need a single list-shaped view, but we should not
+ materialise that compatibility layer back into config.yaml because it duplicates entries in UIs.
"""
if config is None:
config = load_config()
@@ -1990,6 +1640,43 @@ def get_compatible_custom_providers(
return compatible
+def _entries_for_route(
+ base_url: str,
+ custom_providers: Optional[List[Dict[str, Any]]],
+ config: Optional[Dict[str, Any]],
+):
+ """Yield custom-provider entries whose normalized route identity equals *base_url*.
+
+ Loads ``get_compatible_custom_providers(config)`` when *custom_providers* is None (failures →
+ no entries). Yields nothing for an empty *base_url* or non-list input.
+ """
+ if custom_providers is None:
+ try:
+ custom_providers = get_compatible_custom_providers(config)
+ except Exception:
+ custom_providers = []
+ if not base_url or not isinstance(custom_providers, list):
+ return
+ target_url = normalize_route_base_url(base_url)
+ if not target_url:
+ return
+ for entry in custom_providers:
+ if not isinstance(entry, dict):
+ continue
+ entry_url = normalize_route_base_url(entry.get("base_url"))
+ if entry_url and entry_url == target_url:
+ yield entry
+
+
+def _route_model_cfg(entry: Dict[str, Any], model: str) -> Optional[Dict[str, Any]]:
+ """Return ``entry.models[model]`` when both are mappings, else None."""
+ models = entry.get("models")
+ if not isinstance(models, dict):
+ return None
+ model_cfg = models.get(model)
+ return model_cfg if isinstance(model_cfg, dict) else None
+
+
def _coerce_ssl_verify(value: Any) -> Optional[bool]:
if value is None:
return None
@@ -2010,21 +1697,7 @@ def get_custom_provider_tls_settings(
config: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Return TLS settings from a matching ``custom_providers`` / ``providers`` entry."""
- if custom_providers is None:
- try:
- custom_providers = get_compatible_custom_providers(config)
- except Exception:
- custom_providers = []
- if not base_url or not isinstance(custom_providers, list):
- return {}
-
- target_url = normalize_route_base_url(base_url)
- for entry in custom_providers:
- if not isinstance(entry, dict):
- continue
- entry_url = normalize_route_base_url(entry.get("base_url"))
- if not entry_url or entry_url != target_url:
- continue
+ for entry in _entries_for_route(base_url, custom_providers, config):
out: Dict[str, Any] = {}
ca = entry.get("ssl_ca_cert")
if isinstance(ca, str) and ca.strip():
@@ -2053,14 +1726,8 @@ def apply_custom_provider_tls_to_client_kwargs(
def normalize_extra_headers(extra_headers: Any) -> Dict[str, str]:
"""Normalize a raw ``extra_headers`` value into a ``dict[str, str]``.
- Stringifies keys and values and drops entries whose value is ``None``.
- Returns ``{}`` for non-dict or empty inputs. This is the single shared
- normalizer for per-provider ``extra_headers`` across config normalization,
- runtime resolution, client construction, and live ``/models`` discovery.
-
- SECURITY: header values routinely carry credentials (Cloudflare Access
- service tokens, proxy auth, custom bearer schemes). Callers must never
- log the returned values.
+ SECURITY: header values routinely carry credentials (Cloudflare Access service tokens, proxy
+ auth, custom bearer schemes). Callers must never log the returned values.
"""
if not isinstance(extra_headers, dict) or not extra_headers:
return {}
@@ -2074,29 +1741,14 @@ def get_custom_provider_extra_headers(
) -> Dict[str, str]:
"""Return ``extra_headers`` from a matching ``providers`` / ``custom_providers`` entry.
- Matches the entry whose normalized route identity equals *base_url*,
- mirroring :func:`get_custom_provider_tls_settings`, and returns its
- ``extra_headers`` dict, or ``{}`` when no entry matches or declares none.
+ Matches the entry whose normalized route identity equals *base_url*, mirroring
+ :func:`get_custom_provider_tls_settings`, and returns its ``extra_headers`` dict, or ``{}`` when
+ no entry matches or declares none.
- SECURITY: header values routinely carry credentials (Cloudflare Access
- service tokens, proxy auth, custom bearer schemes). Callers must never
- log the returned values.
+ SECURITY: header values routinely carry credentials (Cloudflare Access service tokens, proxy
+ auth, custom bearer schemes). Callers must never log the returned values.
"""
- if custom_providers is None:
- try:
- custom_providers = get_compatible_custom_providers(config)
- except Exception:
- custom_providers = []
- if not base_url or not isinstance(custom_providers, list):
- return {}
-
- target_url = normalize_route_base_url(base_url)
- for entry in custom_providers:
- if not isinstance(entry, dict):
- continue
- entry_url = normalize_route_base_url(entry.get("base_url"))
- if not entry_url or entry_url != target_url:
- continue
+ for entry in _entries_for_route(base_url, custom_providers, config):
headers = normalize_extra_headers(entry.get("extra_headers"))
if headers:
return headers
@@ -2111,12 +1763,9 @@ def apply_custom_provider_extra_headers_to_client_kwargs(
) -> None:
"""Merge per-provider ``extra_headers`` onto OpenAI client ``default_headers``.
- Provider-specific headers win over provider/SDK defaults already present in
- ``client_kwargs`` — they are the most specific configuration level. No-op
- when the base_url matches no ``providers`` / ``custom_providers`` entry or
- the entry declares no headers.
-
- SECURITY: values may carry credentials — never log them.
+ Provider-specific headers win over SDK/provider defaults already in ``client_kwargs`` (they
+ are the most specific level). No-op when base_url matches no provider entry or none declares
+ headers. SECURITY: values may carry credentials -- never log them.
"""
extra_headers = get_custom_provider_extra_headers(base_url, custom_providers, config)
if not extra_headers:
@@ -2134,21 +1783,9 @@ def get_custom_provider_context_length(
) -> Optional[int]:
"""Look up a per-model ``context_length`` override from ``custom_providers``.
- Matches any entry whose normalized route identity equals ``base_url`` and
- returns ``custom_providers[i].models.<model>.context_length`` if present and
- valid. Returns ``None`` when no override applies.
-
- This is the single source of truth for custom-provider context overrides,
- used by:
- * ``AIAgent.__init__`` (startup resolution)
- * ``AIAgent.switch_model`` (mid-session ``/model`` switch)
- * ``hermes_cli.model_switch.resolve_display_context_length`` (``/model`` confirmation display)
- * ``gateway.run._format_session_info`` (``/info`` display)
- * ``agent.model_metadata.get_model_context_length`` (when custom_providers is threaded through)
-
- Before this helper existed, the lookup was duplicated in ``run_agent.py``'s
- startup path only; every other path (notably ``/model`` switch) fell back
- to the 128K default. See #15779.
+ Matches any entry whose normalized route identity equals ``base_url`` and returns
+ ``custom_providers[i].models.<model>.context_length`` if present and valid. Returns ``None``
+ when no override applies.
"""
if not model or not base_url:
return None
@@ -2160,24 +1797,10 @@ def get_custom_provider_context_length(
return None
raw = config.get("custom_providers")
custom_providers = raw if isinstance(raw, list) else []
- if not isinstance(custom_providers, list):
- return None
-
- target_url = normalize_route_base_url(base_url)
- if not target_url:
- return None
- for entry in custom_providers:
- if not isinstance(entry, dict):
- continue
- entry_url = normalize_route_base_url(entry.get("base_url"))
- if not entry_url or entry_url != target_url:
- continue
- models = entry.get("models")
- if not isinstance(models, dict):
- continue
- model_cfg = models.get(model)
- if not isinstance(model_cfg, dict):
+ for entry in _entries_for_route(base_url, custom_providers, config):
+ model_cfg = _route_model_cfg(entry, model)
+ if model_cfg is None:
continue
raw_ctx = model_cfg.get("context_length")
if raw_ctx is None:
@@ -2200,9 +1823,9 @@ def get_custom_provider_model_capability(
) -> Optional[bool]:
"""Return an explicit boolean capability for one custom-provider model.
- Matching is scoped to the normalized route and exact runtime model id so
- aliases can declare capabilities without changing the id sent upstream.
- Missing or non-boolean declarations return ``None``.
+ Matching is scoped to the normalized route and exact runtime model id so aliases can declare
+ capabilities without changing the id sent upstream. Missing or non-boolean declarations return
+ ``None``.
"""
if not model or not base_url or not capability:
return None
@@ -2217,24 +1840,10 @@ def get_custom_provider_model_capability(
custom_providers = get_compatible_custom_providers(config)
except Exception:
return None
- if not isinstance(custom_providers, list):
- return None
-
- target_url = normalize_route_base_url(base_url)
- if not target_url:
- return None
- for entry in custom_providers:
- if not isinstance(entry, dict):
- continue
- entry_url = normalize_route_base_url(entry.get("base_url"))
- if not entry_url or entry_url != target_url:
- continue
- models = entry.get("models")
- if not isinstance(models, dict):
- continue
- model_cfg = models.get(model)
- if not isinstance(model_cfg, dict):
+ for entry in _entries_for_route(base_url, custom_providers, config):
+ model_cfg = _route_model_cfg(entry, model)
+ if model_cfg is None:
continue
value = model_cfg.get(capability)
if isinstance(value, bool):
@@ -2256,33 +1865,26 @@ def _coerce_config_version(value: Any) -> int:
def _raw_config_has_explicit_version() -> bool:
"""True when config.yaml exists, parses, and carries a ``_config_version`` key.
- Distinguishes an ANCIENT config (explicit old version → refused by the
- v12 support floor) from a fresh minimal/hand-written/cloned config with
- no version key at all (→ migrated + stamped normally). Missing or
- unparseable files return False so they never trip the floor gate.
+ Distinguishes an ANCIENT config (explicit old version → refused by the v12 support floor) from a
+ fresh minimal/hand-written/cloned config with no version key at all (→ migrated + stamped
+ normally). Missing or unparseable files return False so they never trip the floor gate.
"""
config_path = get_config_path()
if not config_path.exists():
return False
try:
- with open(config_path, encoding="utf-8") as f:
- raw = fast_safe_load(f) or {}
+ raw = read_user_config_raw(config_path)
except Exception:
return False
- return isinstance(raw, dict) and "_config_version" in raw
+ return "_config_version" in raw
def check_config_version() -> Tuple[int, int]:
- """
- Check the raw on-disk config schema version.
-
- ``load_config()`` deliberately starts from ``DEFAULT_CONFIG`` and deep-merges
- the user's file, which is correct for runtime reads but wrong for deciding
- whether the user's persisted schema has been migrated. A config file with no
- raw ``_config_version`` must remain visible as legacy instead of inheriting
- the latest default version in memory.
+ """Check the raw on-disk config schema version; returns (current_version, latest_version).
- Returns (current_version, latest_version).
+ Reads the raw file rather than ``load_config()``, which deep-merges over ``DEFAULT_CONFIG``
+ and would make a file lacking ``_config_version`` inherit the latest version in memory,
+ hiding that the persisted schema was never migrated.
"""
latest = _coerce_config_version(DEFAULT_CONFIG.get("_config_version", 1)) or 1
config_path = get_config_path()
@@ -2367,13 +1969,28 @@ class ConfigIssue:
hint: str
+def _require_fields(
+ issues: List["ConfigIssue"],
+ entry: Dict[str, Any],
+ label: str,
+ fields: Tuple[Tuple[str, str], ...],
+ suffix: str = "",
+) -> None:
+ """Append a warning for every falsy ``field`` of *entry* (message: ``<label> is missing '<f>' field``)."""
+ for field, hint in fields:
+ if not entry.get(field):
+ issues.append(ConfigIssue(
+ "warning",
+ f"{label} is missing '{field}' field{suffix}",
+ hint,
+ ))
+
+
def validate_config_structure(config: Optional[Dict[str, Any]] = None) -> List["ConfigIssue"]:
"""Validate config.yaml structure and return a list of detected issues.
- Catches common YAML formatting mistakes that produce confusing runtime
- errors (like "Unknown provider") instead of clear diagnostics.
-
- Can be called with a pre-loaded config dict, or will load from disk.
+ Catches common YAML formatting mistakes that otherwise surface as confusing runtime errors
+ (like "Unknown provider"). Accepts a pre-loaded config dict or loads from disk.
"""
if config is None:
try:
@@ -2429,18 +2046,10 @@ def validate_config_structure(config: Optional[Dict[str, Any]] = None) -> List["
"Each entry should have at minimum: name, base_url",
))
continue
- if not entry.get("name"):
- issues.append(ConfigIssue(
- "warning",
- f"custom_providers[{i}] is missing 'name' field",
- "Add a name, e.g.: name: my-provider",
- ))
- if not entry.get("base_url"):
- issues.append(ConfigIssue(
- "warning",
- f"custom_providers[{i}] is missing 'base_url' field",
- "Add the API endpoint URL, e.g.: base_url: https://api.example.com/v1",
- ))
+ _require_fields(issues, entry, f"custom_providers[{i}]", (
+ ("name", "Add a name, e.g.: name: my-provider"),
+ ("base_url", "Add the API endpoint URL, e.g.: base_url: https://api.example.com/v1"),
+ ))
# ── fallback_model: single dict OR list of dicts (chain) ─────────────
fb = config.get("fallback_model")
@@ -2455,18 +2064,10 @@ def validate_config_structure(config: Optional[Dict[str, Any]] = None) -> List["
"Each entry needs provider + model",
))
else:
- if not entry.get("provider"):
- issues.append(ConfigIssue(
- "warning",
- f"fallback_model[{i}] is missing 'provider' field",
- "Add: provider: openrouter (or another provider)",
- ))
- if not entry.get("model"):
- issues.append(ConfigIssue(
- "warning",
- f"fallback_model[{i}] is missing 'model' field",
- "Add: model: <model-name>",
- ))
+ _require_fields(issues, entry, f"fallback_model[{i}]", (
+ ("provider", "Add: provider: openrouter (or another provider)"),
+ ("model", "Add: model: <model-name>"),
+ ))
elif not isinstance(fb, dict):
issues.append(ConfigIssue(
"error",
@@ -2477,18 +2078,10 @@ def validate_config_structure(config: Optional[Dict[str, Any]] = None) -> List["
" model: anthropic/claude-sonnet-4",
))
elif fb:
- if not fb.get("provider"):
- issues.append(ConfigIssue(
- "warning",
- "fallback_model is missing 'provider' field — fallback will be disabled",
- "Add: provider: openrouter (or another provider)",
- ))
- if not fb.get("model"):
- issues.append(ConfigIssue(
- "warning",
- "fallback_model is missing 'model' field — fallback will be disabled",
- "Add: model: anthropic/claude-sonnet-4 (or another model)",
- ))
+ _require_fields(issues, fb, "fallback_model", (
+ ("provider", "Add: provider: openrouter (or another provider)"),
+ ("model", "Add: model: anthropic/claude-sonnet-4 (or another model)"),
+ ), suffix=" — fallback will be disabled")
# ── Check for fallback_model accidentally nested inside custom_providers ──
if isinstance(cp, dict) and "fallback_model" not in config and "fallback_model" in (cp or {}):
@@ -2559,9 +2152,8 @@ def validate_config_structure(config: Optional[Dict[str, Any]] = None) -> List["
def print_config_warnings(config: Optional[Dict[str, Any]] = None) -> None:
"""Print config structure warnings to stderr at startup.
- Called early in CLI and gateway init so users see problems before
- they hit cryptic "Unknown provider" errors. Prints nothing if
- config is healthy.
+ Called early in CLI and gateway init so users see problems before they hit cryptic "Unknown
+ provider" errors. Prints nothing if config is healthy.
"""
try:
issues = validate_config_structure(config)
@@ -2581,10 +2173,9 @@ def print_config_warnings(config: Optional[Dict[str, Any]] = None) -> None:
def warn_deprecated_cwd_env_vars() -> None:
"""Warn if MESSAGING_CWD or TERMINAL_CWD is set in .env instead of config.yaml.
- These env vars are deprecated — the canonical setting is terminal.cwd
- in config.yaml. Read the file rather than ``os.environ`` because runtime
- config bridges and session restoration legitimately set ``TERMINAL_CWD``.
- Prints a migration hint to stderr.
+ These env vars are deprecated — the canonical setting is terminal.cwd in config.yaml. Read the
+ file rather than ``os.environ`` because runtime config bridges and session restoration
+ legitimately set ``TERMINAL_CWD``. Prints a migration hint to stderr.
"""
try:
env_map = load_env()
@@ -2623,40 +2214,42 @@ def warn_deprecated_cwd_env_vars() -> None:
def _persist_migration(config: Dict[str, Any]) -> None:
"""Persist a migrated config under the migration write invariant.
- THE INVARIANT (single source of truth for the whole migration pipeline):
- a migration may only persist values that DIFFER from the current schema
- default, plus explicit removals/renames of user data. Pure schema defaults
- are never materialised to disk — ``load_config()``'s deep-merge supplies
- them at read time, so writing them adds nothing and actively shadows future
- default changes (see ``save_config``'s docstring). Materialising defaults on
- every version bump is what rewrote hand-curated configs into full
- DEFAULT_CONFIG dumps (the "hermes update / hermes -p blows up my config"
- reports).
-
- Every migration step MUST route its write through this helper instead of
- calling ``save_config`` directly. It is a thin wrapper over
- ``save_config(config)`` (default-stripping ON, no ``merge_existing``);
- centralising the call makes the invariant impossible to regress one
- migration at a time. Callers must pass the full raw config returned by
- ``read_raw_config()`` after in-place mutations (including key removals);
- deep-merging the on-disk file back in would resurrect keys the migration
- just deleted. Partial-save preservation for unrelated top-level sections
- belongs on ``save_config(..., merge_existing=True)``, not here.
+ THE INVARIANT (single source of truth for the whole migration pipeline): a migration may only
+ persist values that DIFFER from the current schema default, plus explicit removals/renames of
+ user data.
+
+ Every migration step MUST route its write through this helper instead of calling ``save_config``
+ directly. It is a thin wrapper over ``save_config(config)`` (default-stripping ON, no
+ ``merge_existing``); centralising the call makes the invariant impossible to regress one
+ migration at a time.
"""
save_config(config)
+def _prompt_and_save_env(name: str, info: Dict[str, Any], prompt: str, results: Dict[str, Any]) -> bool:
+ """Prompt for one env var (masked when ``info['password']``), save it, record it; False if skipped."""
+ if info.get("password"):
+ value = masked_secret_prompt(prompt)
+ else:
+ value = line_input(prompt).strip()
+ if not value:
+ return False
+ save_env_value(name, value)
+ results["env_added"].append(name)
+ print(f" ✓ Saved {name}")
+ return True
+
+
+def _ask_yes_no(prompt: str) -> bool:
+ try:
+ answer = input(prompt).strip().lower()
+ except (EOFError, KeyboardInterrupt):
+ answer = "n"
+ return answer in {"y", "yes"}
+
+
def migrate_config(interactive: bool = True, quiet: bool = False) -> Dict[str, Any]:
- """
- Migrate config to latest version, prompting for new required fields.
-
- Args:
- interactive: If True, prompt user for missing values
- quiet: If True, suppress output
-
- Returns:
- Dict with migration results: {"env_added": [...], "config_added": [...], "warnings": [...]}
- """
+ """Migrate config to latest version, prompting for new required fields."""
results = {"env_added": [], "config_added": [], "warnings": []}
# ── Always: normalize safe .env line formatting ──
@@ -2670,22 +2263,14 @@ def migrate_config(interactive: bool = True, quiet: bool = False) -> Dict[str, A
# Check config version
current_ver, latest_ver = check_config_version()
- # ── Auto-migration support floor (policy: v12, July 2026) ──
- # A config with an EXPLICIT on-disk ``_config_version`` below the floor is
- # NOT auto-migrated and NOT rewritten: we surface a clear, actionable
- # message and leave the file byte-for-byte untouched. This matches the
- # fail-safe posture for unparseable configs (warn on stderr, continue —
- # load_config() deep-merges defaults at read time), so the CLI never
- # crashes on an ancient config. The floor gate lives here in the wrapper
- # (not in run_migrations) so the registry driver stays a pure mechanism
- # that tests can exercise directly.
- #
- # A config with NO ``_config_version`` key at all is NOT floor-refused:
- # that shape is a fresh minimal config (profile clones write bare keys;
- # users hand-write two-line configs), not an ancient install. Those get
- # the normal ladder (the retired <12 steps were no-ops for configs
- # lacking the legacy keys they migrated) and a fresh version stamp —
- # the historical behavior.
+ # ── Auto-migration support floor (v12) ──
+ # An EXPLICIT on-disk ``_config_version`` below the floor is NOT migrated
+ # and NOT rewritten: surface an actionable message and leave the file
+ # byte-for-byte untouched (fail-safe like unparseable configs; deep-merge
+ # supplies defaults at read time). The gate lives here so run_migrations
+ # stays a pure mechanism tests can drive directly. A config with NO version
+ # key is a fresh minimal config (profile clones, hand-written two-liners),
+ # not an ancient install — it gets the normal ladder and a version stamp.
from hermes_cli.config_migrations import (
SUPPORT_FLOOR_VERSION,
run_migrations,
@@ -2707,69 +2292,13 @@ def migrate_config(interactive: bool = True, quiet: bool = False) -> Dict[str, A
if not quiet:
print(f" ⚠ {msg}")
else:
- # ── Versioned migration ladder (table-driven) ──
- # The per-version steps live in hermes_cli.config_migrations as a
- # (target_version, fn) registry; the driver applies every step whose
- # target exceeds current_ver, in strict ascending order, preserving the
- # original sequential if-block semantics byte-for-byte. Imported lazily
- # to avoid a module-level import cycle (the steps call back into this
- # module for read_raw_config/_persist_migration/etc. at call time).
+ # Versioned ladder: every registered step whose target exceeds
+ # current_ver, in strict ascending order (hermes_cli.config_migrations;
+ # imported lazily because the steps call back into this module).
run_migrations(current_ver, results, quiet)
- # ── Post-migration: disable exfiltration-shaped MCP stdio entries ──
- # Users can hand-edit mcp_servers, and older installs may already contain a
- # malicious entry. Preserve the stanza for auditability but mark it
- # disabled so the next startup will not spawn it. (#45620)
- config = read_raw_config()
- raw_mcp_servers = config.get("mcp_servers")
- if isinstance(raw_mcp_servers, dict):
- try:
- from hermes_cli.mcp_security import validate_mcp_server_entry as _validate_mcp_server_entry
- except Exception:
- _validate_mcp_server_entry = None
- if _validate_mcp_server_entry:
- mcp_touched = False
- for server_name, entry in raw_mcp_servers.items():
- if not isinstance(entry, dict):
- continue
- issues = _validate_mcp_server_entry(server_name, entry)
- if not issues:
- continue
- entry["enabled"] = False
- mcp_touched = True
- results["warnings"].append(
- f"Disabled suspicious MCP server '{server_name}'"
- )
- if not quiet:
- for issue in issues:
- print(f" ⚠ {issue}")
- print(f" ⚠ Disabled MCP server '{server_name}' pending review")
- if mcp_touched:
- config["mcp_servers"] = raw_mcp_servers
- _persist_migration(config)
-
- # ── Always: validate platform_toolsets after migration ──
- # A migration (or hand-edit) that leaves an invalid toolset name in
- # platform_toolsets silently disables the affected tools — resolve_toolset()
- # returns [] for an unknown name, so the agent quietly loses tools with no
- # error or warning. Surface it loudly instead. See #38798.
- try:
- from toolsets import validate_toolset
- from hermes_cli.toolset_validation import validate_platform_toolsets
- from hermes_cli.toolset_scope import toolset_allowed_for_platform
-
- ts_warnings = validate_platform_toolsets(
- read_raw_config().get("platform_toolsets"),
- validate_toolset,
- toolset_allowed_for_platform,
- )
- for w in ts_warnings:
- results["warnings"].append(w)
- if not quiet:
- print(f" ⚠ {w}")
- except Exception as _ts_val_err:
- # best-effort; never block migration on validation
- logger.debug("platform_toolsets validation skipped: %s", _ts_val_err)
+ _disable_suspicious_mcp_servers(results, quiet)
+ _warn_invalid_platform_toolsets(results, quiet)
if current_ver < latest_ver and not quiet and not floor_refused:
print(f"Config version: {current_ver} → {latest_ver}")
@@ -2787,17 +2316,7 @@ def migrate_config(interactive: bool = True, quiet: bool = False) -> Dict[str, A
for var in missing_env:
if var.get("url"):
print(f" Get your key at: {var['url']}")
-
- if var.get("password"):
- value = masked_secret_prompt(f" {var['prompt']}: ")
- else:
- value = line_input(f" {var['prompt']}: ").strip()
-
- if value:
- save_env_value(var["name"], value)
- results["env_added"].append(var["name"])
- print(f" ✓ Saved {var['name']}")
- else:
+ if not _prompt_and_save_env(var["name"], var, f" {var['prompt']}: ", results):
results["warnings"].append(f"Skipped {var['name']} - some features may not work")
print()
@@ -2810,120 +2329,153 @@ def migrate_config(interactive: bool = True, quiet: bool = False) -> Dict[str, A
if v["name"] not in required_names and not v.get("advanced")
]
- # Only offer to configure env vars that are NEW since the user's previous version
- new_var_names = set()
- for ver in range(current_ver + 1, latest_ver + 1):
- new_var_names.update(ENV_VARS_BY_VERSION.get(ver, []))
+ if interactive and not quiet:
+ _offer_new_optional_env_vars(current_ver, latest_ver, results)
- if new_var_names and interactive and not quiet:
- new_and_unset = [
- (name, OPTIONAL_ENV_VARS[name])
- for name in sorted(new_var_names)
- if not get_env_value(name) and name in OPTIONAL_ENV_VARS
- ]
- if new_and_unset:
- print(f"\n {len(new_and_unset)} new optional key(s) in this update:")
- for name, info in new_and_unset:
- print(f" • {name} — {info.get('description', '')}")
- print()
- try:
- answer = input(" Configure new keys? [y/N]: ").strip().lower()
- except (EOFError, KeyboardInterrupt):
- answer = "n"
-
- if answer in {"y", "yes"}:
- print()
- for name, info in new_and_unset:
- if info.get("url"):
- print(f" {info.get('description', name)}")
- print(f" Get your key at: {info['url']}")
- else:
- print(f" {info.get('description', name)}")
- if info.get("password"):
- value = masked_secret_prompt(
- f" {info.get('prompt', name)} (Enter to skip): "
- )
- else:
- value = line_input(f" {info.get('prompt', name)} (Enter to skip): ").strip()
- if value:
- save_env_value(name, value)
- results["env_added"].append(name)
- print(f" ✓ Saved {name}")
- print()
- else:
- print(" Set later with: hermes config set <key> <value>")
-
- # Check for missing config fields.
- #
# New default keys are NOT materialised to disk: load_config() deep-merges
- # DEFAULT_CONFIG at read time, so a missing key already takes effect with
- # its default (see _persist_migration's invariant). We surface the list for
- # the informational "N new config option(s) available" display in
- # `hermes update`, but only the version bump is persisted.
- missing_config = get_missing_config_fields()
- if missing_config:
- results["config_added"].extend(field["key"] for field in missing_config)
+ # DEFAULT_CONFIG at read time (see _persist_migration's invariant). The list
+ # only feeds the informational "N new config option(s)" display; only the
+ # version bump is persisted.
+ results["config_added"].extend(field["key"] for field in get_missing_config_fields())
if current_ver < latest_ver and not floor_refused:
config = read_raw_config()
config["_config_version"] = latest_ver
_persist_migration(config)
- # ── Skill-declared config vars ──────────────────────────────────────
- # Skills can declare config.yaml settings they need via
- # metadata.hermes.config in their SKILL.md frontmatter.
- # Prompt for any that are missing/empty.
+ # Skill-declared config.yaml settings (``metadata.hermes.config`` in SKILL.md).
missing_skill_config = get_missing_skill_config_vars()
if missing_skill_config and interactive and not quiet:
- print(f"\n {len(missing_skill_config)} skill setting(s) not configured:")
- for var in missing_skill_config:
- skill_name = var.get("skill", "unknown")
- print(f" • {var['key']} — {var['description']} (from skill: {skill_name})")
+ _offer_skill_config_vars(missing_skill_config, results)
+
+ return results
+
+
+def _disable_suspicious_mcp_servers(results: Dict[str, Any], quiet: bool) -> None:
+ """Post-migration: disable exfiltration-shaped MCP stdio entries.
+
+ Users can hand-edit mcp_servers, and older installs may already contain a malicious entry.
+ Preserve the stanza for auditability but mark it disabled so the next startup will not spawn it.
+ """
+ config = read_raw_config()
+ raw_mcp_servers = config.get("mcp_servers")
+ if not isinstance(raw_mcp_servers, dict):
+ return
+ try:
+ from hermes_cli.mcp_security import validate_mcp_server_entry
+ except Exception:
+ return
+ mcp_touched = False
+ for server_name, entry in raw_mcp_servers.items():
+ if not isinstance(entry, dict):
+ continue
+ issues = validate_mcp_server_entry(server_name, entry)
+ if not issues:
+ continue
+ entry["enabled"] = False
+ mcp_touched = True
+ results["warnings"].append(f"Disabled suspicious MCP server '{server_name}'")
+ if not quiet:
+ for issue in issues:
+ print(f" ⚠ {issue}")
+ print(f" ⚠ Disabled MCP server '{server_name}' pending review")
+ if mcp_touched:
+ config["mcp_servers"] = raw_mcp_servers
+ _persist_migration(config)
+
+
+def _warn_invalid_platform_toolsets(results: Dict[str, Any], quiet: bool) -> None:
+ """Surface invalid toolset names in platform_toolsets loudly.
+
+ ``resolve_toolset()`` returns [] for an unknown name, so a migration or hand-edit that leaves
+ one behind silently disables the affected tools. Best-effort; never blocks migration.
+ """
+ try:
+ from toolsets import validate_toolset
+ from hermes_cli.toolset_validation import validate_platform_toolsets
+ from hermes_cli.toolset_scope import toolset_allowed_for_platform
+
+ ts_warnings = validate_platform_toolsets(
+ read_raw_config().get("platform_toolsets"),
+ validate_toolset,
+ toolset_allowed_for_platform,
+ )
+ for w in ts_warnings:
+ results["warnings"].append(w)
+ if not quiet:
+ print(f" ⚠ {w}")
+ except Exception as _ts_val_err:
+ logger.debug("platform_toolsets validation skipped: %s", _ts_val_err)
+
+
+def _offer_new_optional_env_vars(current_ver: int, latest_ver: int, results: Dict[str, Any]) -> None:
+ """Interactively offer env vars that are NEW since the user's previous config version."""
+ new_var_names: set = set()
+ for ver in range(current_ver + 1, latest_ver + 1):
+ new_var_names.update(ENV_VARS_BY_VERSION.get(ver, []))
+ if not new_var_names:
+ return
+ new_and_unset = [
+ (name, OPTIONAL_ENV_VARS[name])
+ for name in sorted(new_var_names)
+ if not get_env_value(name) and name in OPTIONAL_ENV_VARS
+ ]
+ if not new_and_unset:
+ return
+ print(f"\n {len(new_and_unset)} new optional key(s) in this update:")
+ for name, info in new_and_unset:
+ print(f" • {name} — {info.get('description', '')}")
+ print()
+ if not _ask_yes_no(" Configure new keys? [y/N]: "):
+ print(" Set later with: hermes config set <key> <value>")
+ return
+ print()
+ for name, info in new_and_unset:
+ print(f" {info.get('description', name)}")
+ if info.get("url"):
+ print(f" Get your key at: {info['url']}")
+ _prompt_and_save_env(name, info, f" {info.get('prompt', name)} (Enter to skip): ", results)
print()
- try:
- answer = input(" Configure skill settings? [y/N]: ").strip().lower()
- except (EOFError, KeyboardInterrupt):
- answer = "n"
- if answer in {"y", "yes"}:
- print()
- config = read_raw_config()
- try:
- from agent.skill_utils import SKILL_CONFIG_PREFIX
- except Exception:
- SKILL_CONFIG_PREFIX = "skills.config"
- for var in missing_skill_config:
- default = var.get("default", "")
- default_hint = f" (default: {default})" if default else ""
- value = line_input(f" {var['prompt']}{default_hint}: ").strip()
- if not value and default:
- value = str(default)
- if value:
- storage_key = f"{SKILL_CONFIG_PREFIX}.{var['key']}"
- _set_nested(config, storage_key, value)
- results["config_added"].append(var["key"])
- print(f" ✓ Saved {var['key']} = {value}")
- else:
- results["warnings"].append(
- f"Skipped {var['key']} — skill '{var.get('skill', '?')}' may ask for it later"
- )
- print()
- _persist_migration(config)
- else:
- print(" Set later with: hermes config set <key> <value>")
- return results
+def _offer_skill_config_vars(missing_skill_config: List[Dict[str, Any]], results: Dict[str, Any]) -> None:
+ """Prompt for skill-declared settings that are missing/empty and persist the answers."""
+ print(f"\n {len(missing_skill_config)} skill setting(s) not configured:")
+ for var in missing_skill_config:
+ print(f" • {var['key']} — {var['description']} (from skill: {var.get('skill', 'unknown')})")
+ print()
+ if not _ask_yes_no(" Configure skill settings? [y/N]: "):
+ print(" Set later with: hermes config set <key> <value>")
+ return
+ print()
+ config = read_raw_config()
+ try:
+ from agent.skill_utils import SKILL_CONFIG_PREFIX
+ except Exception:
+ SKILL_CONFIG_PREFIX = "skills.config"
+ for var in missing_skill_config:
+ default = var.get("default", "")
+ default_hint = f" (default: {default})" if default else ""
+ value = line_input(f" {var['prompt']}{default_hint}: ").strip() or (str(default) if default else "")
+ if value:
+ _set_nested(config, f"{SKILL_CONFIG_PREFIX}.{var['key']}", value)
+ results["config_added"].append(var["key"])
+ print(f" ✓ Saved {var['key']} = {value}")
+ else:
+ results["warnings"].append(
+ f"Skipped {var['key']} — skill '{var.get('skill', '?')}' may ask for it later"
+ )
+ print()
+ _persist_migration(config)
def _merge_partial_save(raw: dict, override: dict) -> dict:
"""Merge *override* over *raw* for partial ``save_config`` writes.
- Top-level sections omitted from *override* are preserved from *raw*.
- Shared top-level dict sections are deep-merged so a caller can update one
- nested key without dropping sibling keys from disk. Intentional key
- removals within a section are not supported here — migration writes must
- route through ``_persist_migration`` with a full ``read_raw_config()`` dict
- instead.
+ Top-level sections omitted from *override* are preserved; shared dict sections are deep-merged
+ so one nested key can be updated without dropping siblings on disk. Intentional key removals
+ are NOT supported here -- migrations must go through ``_persist_migration`` with a full
+ ``read_raw_config()`` dict.
"""
result = copy.deepcopy(override)
for key, value in raw.items():
@@ -2937,15 +2489,9 @@ def _merge_partial_save(raw: dict, override: dict) -> dict:
def _deep_merge(base: dict, override: dict) -> dict:
"""Recursively merge *override* into *base*, preserving nested defaults.
- Keys in *override* take precedence. If both values are dicts the merge
- recurses, so a user who overrides only ``tts.elevenlabs.voice_id`` will
- keep the default ``tts.elevenlabs.model_id`` intact.
-
- An empty section key in config.yaml (``terminal:`` with no value) parses
- as YAML ``None``; treating that as an override would replace the entire
- default dict with ``None`` and crash every downstream consumer that
- expects a mapping (#58277). A ``None`` override of a dict default is
- ignored — same as the key being absent.
+ Keys in *override* take precedence. If both values are dicts the merge recurses, so a user who
+ overrides only ``tts.elevenlabs.voice_id`` will keep the default ``tts.elevenlabs.model_id``
+ intact.
"""
result = base.copy()
for key, value in override.items():
@@ -2965,10 +2511,10 @@ def _deep_merge(base: dict, override: dict) -> dict:
def _strip_dotted_keys(cfg: dict, dotted_keys: set) -> Tuple[dict, set]:
"""Remove the given dotted leaf keys from a nested config dict.
- Returns ``(pruned_cfg, set_of_stripped_keys_that_were_present)``. Used by
- ``save_config`` to drop managed-scope leaves before persisting, so a bulk
- write never writes a user value that would lose to the managed layer on the
- next load. Only keys actually present in ``cfg`` are reported as stripped.
+ Returns ``(pruned_cfg, set_of_stripped_keys_that_were_present)``. Used by ``save_config`` to
+ drop managed-scope leaves before persisting, so a bulk write never writes a user value that
+ would lose to the managed layer on the next load. Only keys actually present in ``cfg`` are
+ reported as stripped.
"""
stripped: set = set()
for dotted in dotted_keys:
@@ -2988,15 +2534,8 @@ def _strip_dotted_keys(cfg: dict, dotted_keys: set) -> Tuple[dict, set]:
def _env_ref_lookup(name: str) -> Optional[str]:
"""Resolve the env var behind a ``${VAR}`` / ``${env:VAR}`` config ref.
- Outside a profile secret scope this is a plain ``os.environ`` read — the
- default profile and every single-profile caller keep their legacy
- behavior. Inside a scope (a multiplexed gateway turn, a secondary
- profile's config load, a cron job) the read goes through
- ``agent.secret_scope.get_secret`` so the ref resolves against *that*
- profile's ``.env``: under multiplexing a miss is a miss, never another
- profile's ``os.environ`` value (#84079 — every profile "had" the default
- profile's ``${MATRIX_ACCESS_TOKEN}`` and fanned out). Same policy as
- ``gateway.config._getenv`` and ``get_env_value``.
+ Outside a profile secret scope this is a plain ``os.environ`` read — the default profile and
+ every single-profile caller keep their legacy behavior.
"""
try:
from agent.secret_scope import current_secret_scope, get_secret as _get_secret
@@ -3010,72 +2549,63 @@ def _env_ref_lookup(name: str) -> Optional[str]:
def _env_expand_match(m: re.Match) -> str:
"""Expand one ``${...}`` config reference.
- Two accepted shapes, matching what MCP server config already resolves
- (``tools/mcp_tool.py::_env_ref_name``):
-
- * ``${VAR}`` — legacy bare name, resolved via ``_env_ref_lookup``
- (``os.environ``, or the active profile secret scope).
- * ``${env:VAR}`` — Cursor-style SecretRef, same resolution after the
- ``env:`` prefix is stripped. Before this, the prefixed form worked in
- MCP config but stayed a literal string in config.yaml — a confusing
- half-support.
+ * ``${VAR}`` — legacy bare name, resolved via ``_env_ref_lookup`` (``os.environ``, or the active
+ profile secret scope). * ``${env:VAR}`` — Cursor-style SecretRef, same resolution after the
+ ``env:`` prefix is stripped.
- Other SecretRef sources (``file:``, ``bitwarden:``, ``vault:``, ...)
- are NOT resolved here — external secret backends inject their values
- into the environment at startup (the ``secrets:`` block), so a config
- ref only ever needs the env shape. Unknown prefixes warn once and stay
+ Other SecretRef sources (``file:``, ``bitwarden:``, ``vault:``, ...) are NOT resolved here —
+ external secret backends inject their values into the environment at startup (the ``secrets:``
+ block), so a config ref only ever needs the env shape. Unknown prefixes warn once and stay
verbatim so callers can detect them.
"""
raw = m.group(0)
inner = m.group(1).strip()
+ name = _env_ref_var_name(inner)
+ if name is None:
+ if not inner.startswith("env:") and _is_non_env_secret_ref(inner):
+ # Values from vault backends arrive via the secrets: block as env
+ # vars — point there instead of silently treating "bitwarden:FOO"
+ # as a var named "bitwarden:FOO".
+ logger.warning(
+ "Config ref %r uses source %r which is not resolvable in "
+ "config.yaml — external secret sources inject env vars at "
+ "startup, so reference the variable as ${env:NAME} instead",
+ raw, inner.split(":", 1)[0],
+ )
+ return raw # non-env source, or empty ``${env:}``
+ val = _env_ref_lookup(name)
+ if val is not None:
+ return val
if inner.startswith("env:"):
- name = inner[len("env:"):].strip()
- if not name:
- return raw
- val = _env_ref_lookup(name)
- if val is not None:
- return val
logger.warning(
"Config ref %r: %s is not set (check ~/.hermes/.env); "
"keeping the literal placeholder", raw, name,
)
- return raw
- if ":" in inner and re.match(r"^[a-z][a-z0-9_-]*:", inner):
- # Looks like a SecretRef with a non-env source. Values from vault
- # backends arrive via the secrets: block as env vars — point there
- # instead of silently treating "bitwarden:FOO" as a var named
- # "bitwarden:FOO".
- logger.warning(
- "Config ref %r uses source %r which is not resolvable in "
- "config.yaml — external secret sources inject env vars at "
- "startup, so reference the variable as ${env:NAME} instead",
- raw, inner.split(":", 1)[0],
- )
- return raw
- # Legacy ``${VAR}`` — bare name.
- val = _env_ref_lookup(inner)
- return val if val is not None else raw
+ return raw
+
+
+def _is_non_env_secret_ref(ref: str) -> bool:
+ """True for a SecretRef body with a non-``env`` source (``bitwarden:FOO``, ``vault:...``)."""
+ return ":" in ref and re.match(r"^[a-z][a-z0-9_-]*:", ref) is not None
def _env_ref_var_name(ref: str) -> Optional[str]:
"""Normalize a ``${...}`` body to the env-var name it reads, or None
- when the ref uses a non-env source and never touches the environment."""
+ when the ref uses a non-env source (or is an empty ``env:``) and never touches the environment."""
ref = ref.strip()
if ref.startswith("env:"):
- name = ref[len("env:"):].strip()
- return name or None
- if ":" in ref and re.match(r"^[a-z][a-z0-9_-]*:", ref):
+ return ref[len("env:"):].strip() or None
+ if _is_non_env_secret_ref(ref):
return None
return ref
def _expand_env_vars(obj):
- """Recursively expand ``${VAR}`` / ``${env:VAR}`` references in config
- values.
+ """Recursively expand ``${VAR}`` / ``${env:VAR}`` references in config values.
- Only string values are processed; dict keys, numbers, booleans, and
- None are left untouched. Unresolved references (variable not in
- ``os.environ``) are kept verbatim so callers can detect them.
+ Only string values are processed; dict keys, numbers, booleans, and None are left untouched.
+ Unresolved references (variable not in ``os.environ``) are kept verbatim so callers can detect
+ them.
"""
if isinstance(obj, str):
return re.sub(r"\${([^}]+)}", _env_expand_match, obj)
@@ -3087,19 +2617,12 @@ def _expand_env_vars(obj):
def _env_ref_snapshot(obj, snapshot=None):
- """Map every ``${VAR}`` / ``${env:VAR}`` name referenced in config values
- to its current ``os.environ`` value (``None`` when unset).
-
- Stored alongside cached ``load_config()`` results so a cache hit can
- detect that the cached expansion was made against a *different*
- environment — e.g. a ``load_config()`` that ran before
- ``load_hermes_dotenv()`` populated the process env, or an env var
- rotated in-process after the first load. File mtime/size alone cannot
- see either case (#58514).
-
- ``${env:VAR}`` refs are tracked under the real variable name; refs
- with a non-env source prefix never read the environment, so they are
- excluded from the snapshot.
+ """Map each ``${VAR}`` / ``${env:VAR}`` referenced in config values to its current env value.
+
+ Stored with cached ``load_config()`` results so a cache hit can detect the expansion was made
+ against a different environment (e.g. a load before ``load_hermes_dotenv()`` ran, or a var
+ rotated in-process) -- file mtime/size alone cannot see either. Refs with a non-env source
+ prefix never read the environment and are excluded.
"""
if snapshot is None:
snapshot = {}
@@ -3135,16 +2658,9 @@ def _items_by_unique_name(items):
def _preserve_env_ref_templates(current, raw, loaded_expanded=None):
"""Restore raw ``${VAR}`` templates when a value is otherwise unchanged.
- ``load_config()`` expands env refs for runtime use. When a caller later
- persists that config after modifying some unrelated setting, keep the
- original on-disk template instead of writing the expanded plaintext
- secret back to ``config.yaml``.
-
- Prefer preserving the raw template when ``current`` still matches either
- the value previously returned by ``load_config()`` for this config path or
- the current environment expansion of ``raw``. This handles env-var
- rotation between load and save while still treating mixed literal/template
- string edits as caller-owned once their rendered value diverges.
+ ``load_config()`` expands env refs for runtime use. When a caller later persists that config
+ after modifying some unrelated setting, keep the original on-disk template instead of writing
+ the expanded plaintext secret back to ``config.yaml``.
"""
if isinstance(current, str) and isinstance(raw, str) and re.search(r"\${[^}]+}", raw):
if current == raw:
@@ -3199,13 +2715,12 @@ def _preserve_env_ref_templates(current, raw, loaded_expanded=None):
def _explicit_config_paths(config: Dict[str, Any]) -> Set[Tuple[str, ...]]:
"""Return leaf paths explicitly present in a raw config dict.
- Computed on the **raw** (un-normalized, un-expanded) config so that
- values injected by normalisation (e.g. ``agent.max_turns`` from
- ``DEFAULT_CONFIG``) are not mistakenly treated as user-set.
+ Computed on the **raw** (un-normalized, un-expanded) config so that values injected by
+ normalisation (e.g. ``agent.max_turns`` from ``DEFAULT_CONFIG``) are not mistakenly treated as
+ user-set.
- Used by ``save_config`` to build the *preserve* set passed to
- ``_strip_default_values`` so only user-authored keys survive the
- defaults-strip pass.
+ Used by ``save_config`` to build the *preserve* set passed to ``_strip_default_values`` so only
+ user-authored keys survive the defaults-strip pass.
"""
paths: Set[Tuple[str, ...]] = set()
@@ -3228,14 +2743,12 @@ def _strip_default_values(
) -> Dict[str, Any]:
"""Return *config* without keys whose values match *defaults*.
- Keys in *preserve_keys* (explicitly present in the user's raw config,
- before any normalisation) are always kept even when they equal the
- default, so user-set values such as ``memory.user_char_limit: 2200``
- survive a ``save_config`` round-trip.
+ Keys in *preserve_keys* (explicitly present in the user's raw config, before any normalisation)
+ are always kept even when they equal the default, so user-set values such as
+ ``memory.user_char_limit: 2200`` survive a ``save_config`` round-trip.
- Nested dicts whose every child is stripped are removed entirely so
- default-only subtrees (e.g. ``gateway``) never bloat ``config.yaml``
- when the user has nothing to say about them.
+ Nested dicts whose every child is stripped are removed entirely so default-only subtrees (e.g.
+ ``gateway``) never bloat ``config.yaml`` when the user has nothing to say about them.
"""
preserve_keys = {("_config_version",)} | set(preserve_keys or ())
@@ -3272,16 +2785,8 @@ def _strip_default_values(
def split_model_config_default(raw_default: Any) -> tuple[str, str]:
"""Canonicalize a config ``model.default``/``model.model`` value.
- A dict-valued default (``model.default: {provider: ..., model: ...}``)
- pairs the model string with the provider it must be routed through. The
- dict is flattened here at the shared boundary so both halves stay
- together through ``HermesCLI`` construction: the model becomes a plain
- string and the provider is returned explicitly instead of being lost to
- the outer merged ``model.provider`` default (often ``"auto"``, which
- runtime resolution treats as authoritative and would otherwise route the
- model through the wrong active provider).
-
- Returns ``(model, provider)``; both are ``""`` when nothing is usable.
+ A dict-valued default (``model.default: {provider: ..., model: ...}``) pairs the model string
+ with the provider it must be routed through.
"""
if isinstance(raw_default, dict):
provider = str(raw_default.get("provider") or "").strip()
@@ -3293,60 +2798,30 @@ def split_model_config_default(raw_default: Any) -> tuple[str, str]:
def _normalize_root_model_keys(config: Dict[str, Any]) -> Dict[str, Any]:
"""Move stale root-level provider/base_url/context_length into model section.
- Some users (or older code) placed ``provider:``, ``base_url:``, or
- ``context_length:`` at the config root instead of inside ``model:``.
- These root-level keys are only used as a fallback when the corresponding
- ``model.*`` key is empty — they never override an existing value.
- After migration the root-level keys are removed so they can't cause
- confusion on subsequent loads.
-
- Also aliases ``api_base`` → ``base_url`` (issue #8919). ``api_base`` is the
- intuitive name OpenAI-SDK / LiteLLM users reach for, and ``hermes config set``
- blindly accepts any dotted key — so ``model.api_base`` got written, confirmed,
- and then silently ignored by the runtime resolver (which reads only
- ``model.base_url``), causing requests to fall back to OpenRouter. We migrate
- the alias to the canonical key (fallback-only — never override an explicit
- ``base_url``) and drop the alias so it can't confuse later loads.
-
- Finally, canonicalizes the model-id key to ``model.default`` (issue #34500).
- The runtime resolver and ~14 other readers select the chat model via
- ``model.default``; ``model.model`` was already aliased inline at some sites
- but ``model.name`` was not, so a custom-provider config like
- ``model: {name: <id>, provider: <custom>}`` resolved to an empty model and
- the API request went out with ``model=`` (HTTP 400 from OpenAI-compatible
- backends) — while display paths (``hermes status``/``dump``) read ``name``
- and *showed* the model, making the failure silent. Normalizing here (the
- single load/save chokepoint) means every reader, present and future, sees a
- populated ``default`` and the stale alias is migrated out of config.yaml on
- the next save. Precedence: ``default`` > ``model`` > ``name`` (never
- overrides an explicit ``default``, so existing configs are unaffected).
+ Some users (or older code) placed ``provider:``, ``base_url:``, or ``context_length:`` at the
+ config root instead of inside ``model:``. These root-level keys are only used as a fallback when
+ the corresponding ``model.*`` key is empty — they never override an existing value.
+
+ ``api_base`` is the intuitive name OpenAI-SDK / LiteLLM users reach for, and ``hermes config
+ set`` blindly accepts any dotted key — so ``model.api_base`` got written, confirmed, and then
+ silently ignored by the runtime resolver (which reads only ``model.base_url``), causing requests
+ to fall back to OpenRouter.
"""
# Only act if there's something to migrate: root-level keys, an api_base
- # alias, or a model dict whose id lives under a non-canonical key.
+ # alias, a dict-valued ``default``/``model``/``name`` (must be flattened at
+ # this single load/save chokepoint so no reader sees a nested dict), or an
+ # id under a non-canonical ``model``/``name`` key (promoted when ``default``
+ # is empty, dropped otherwise so config.yaml ends up canonical).
model_in = config.get("model")
- model_has_alias = isinstance(model_in, dict) and model_in.get("api_base")
- # A dict-valued ``default``/``model`` (``{provider: ..., model: ...}``)
- # must be flattened into ``default`` (string) + ``provider`` here at the
- # single load/save chokepoint, so every reader (doctor, status, fallback
- # picker, prompt-size, context-switch guard, …) sees plain strings instead
- # of a nested dict that crashes ``.strip()``/``.lower()`` or routes the
- # model through the wrong provider.
- _has_nested_default = isinstance(model_in, dict) and (
- isinstance(model_in.get("default"), dict)
- or isinstance(model_in.get("model"), dict)
- or isinstance(model_in.get("name"), dict)
- )
- # A model dict needs canonicalization if its id lives under a non-canonical
- # key (``model``/``name``) — either because ``default`` is empty (we must
- # promote the alias) or because ``default`` is set but a stale alias still
- # lingers (we must drop it so config.yaml ends up canonical).
- model_needs_canon = isinstance(model_in, dict) and (
- model_in.get("model") or model_in.get("name")
+ needs_model_work = isinstance(model_in, dict) and (
+ model_in.get("api_base")
+ or model_in.get("model") or model_in.get("name")
+ or any(isinstance(model_in.get(k), dict) for k in ("default", "model", "name"))
)
has_root = any(
config.get(k) for k in ("provider", "base_url", "context_length", "api_base")
)
- if not has_root and not model_has_alias and not model_needs_canon and not _has_nested_default:
+ if not has_root and not needs_model_work:
return config
config = dict(config)
@@ -3357,13 +2832,10 @@ def _normalize_root_model_keys(config: Dict[str, Any]) -> Dict[str, Any]:
model = dict(model)
config["model"] = model
- # Flatten a dict-valued ``model.default``/``model.model``:
- # ``{provider: <p>, model: <m>}`` -> ``default: "<m>"`` and, when no
- # explicit ``model.provider`` is set, ``provider: "<p>"``. The nested
+ # Flatten ``{provider: <p>, model: <m>}`` -> ``default: "<m>"`` plus
+ # ``provider: "<p>"`` unless an explicit outer provider is set. The nested
# provider must win over the merged default ``"auto"`` (which runtime
- # resolution treats as authoritative and would otherwise route the model
- # through the wrong active provider), but never over an explicitly
- # configured outer provider.
+ # resolution treats as authoritative) but never over a configured one.
for _key in ("default", "model", "name"):
_val = model.get(_key)
if isinstance(_val, dict):
@@ -3388,9 +2860,8 @@ def _normalize_root_model_keys(config: Dict[str, Any]) -> Dict[str, Any]:
config.pop("api_base", None)
model.pop("api_base", None)
- # Canonicalize the model id to ``default``. ``model`` and ``name`` are
- # last-resort aliases (in that order) — only consulted when ``default`` is
- # empty, then dropped so later loads/saves can't reintroduce the ambiguity.
+ # Canonicalize the id to ``default``; ``model``/``name`` are last-resort
+ # aliases (in that order), then dropped so the ambiguity can't return.
if not (model.get("default") or ""):
alias = model.get("model") or model.get("name")
if alias:
@@ -3406,11 +2877,8 @@ def _normalize_root_model_keys(config: Dict[str, Any]) -> Dict[str, Any]:
def _normalize_max_turns_config(config: Dict[str, Any]) -> Dict[str, Any]:
"""Normalize legacy root-level max_turns into agent.max_turns.
- Only injects the schema default when the user actually set max_turns
- somewhere (root level or under ``agent``). A bare ``load_config()``
- call that passes the result straight to ``save_config()`` should not
- materialise ``agent.max_turns`` in config.yaml when the user never set
- it — that makes the default sticky and blocks future schema changes.
+ Only injects the schema default when the user actually set max_turns somewhere (root level or
+ under ``agent``).
"""
config = dict(config)
agent_config = dict(config.get("agent") or {})
@@ -3424,9 +2892,7 @@ def _normalize_max_turns_config(config: Dict[str, Any]) -> Dict[str, Any]:
# Only inject the default when the user explicitly set max_turns
# (either root-level or under agent). Otherwise leave it absent so
# save_config can omit it and the schema default fills in at runtime.
- if not had_root and not had_agent:
- pass # deliberately do not inject DEFAULT_CONFIG default
- elif "max_turns" not in agent_config:
+ if (had_root or had_agent) and "max_turns" not in agent_config:
agent_config["max_turns"] = DEFAULT_CONFIG["agent"]["max_turns"]
config["agent"] = agent_config
@@ -3437,16 +2903,11 @@ def _normalize_max_turns_config(config: Dict[str, Any]) -> Dict[str, Any]:
def is_provider_enabled(provider_cfg: Optional[Dict[str, Any]]) -> bool:
"""Return whether a ``providers.<name>`` config block is enabled.
- A provider is enabled by default. Only an explicit ``enabled: false`` in
- the block hides it from the model picker, ``/models`` listings, the
- runtime resolver and the doctor / status output.
-
- Backward-compat: configs without the ``enabled`` key keep working as
- before — the default is ``True``.
+ A provider is enabled by default. Only an explicit ``enabled: false`` in the block hides it from
+ the model picker, ``/models`` listings, the runtime resolver and the doctor / status output.
- Pass any non-dict (None, list, string) and you get ``True`` too, so
- malformed entries don't disappear silently; they'll still be flagged
- by the existing validation paths.
+ Backward-compat: configs without the ``enabled`` key keep working as before — the default is
+ ``True``.
"""
if not isinstance(provider_cfg, dict):
return True
@@ -3459,16 +2920,11 @@ def is_provider_enabled(provider_cfg: Optional[Dict[str, Any]]) -> bool:
return bool(flag)
-# Sentinel used when the user requests an unlimited turn budget.
-# ``sys.maxsize`` (9,223,372,036,854,775,807) is chosen so it:
-# - survives the ``str() → int()`` round-trip through the HERMES_MAX_ITERATIONS
-# env-var bridge in gateway/run.py,
-# - works correctly in every ``<``, ``>=``, and ``remaining = max - used``
-# comparison in agent/iteration_budget.py and agent/conversation_loop.py
-# without requiring those call sites to learn about a special "unlimited"
-# value, and
-# - is large enough that no real conversation will ever reach it (a turn
-# takes seconds; 9.2e18 turns would take ~10^11 years).
+# Sentinel for an unlimited turn budget. ``sys.maxsize`` survives the str→int
+# round-trip through the HERMES_MAX_ITERATIONS env bridge (gateway/run.py), works
+# in every ``<``/``>=``/``max - used`` comparison in agent/iteration_budget.py and
+# agent/conversation_loop.py without a special "unlimited" case, and is
+# unreachable in practice (9.2e18 turns ≈ 10^11 years).
TURN_LIMIT_UNLIMITED = sys.maxsize
# String spellings that mean "no limit". Lowercased, whitespace-stripped
@@ -3482,26 +2938,8 @@ _UNLIMITED_SPELLINGS = frozenset({
def resolve_turn_limit(raw: Any, default: int = TURN_LIMIT_UNLIMITED) -> int:
"""Normalize a raw ``agent.max_turns`` value into an int iteration cap.
- Accepts:
- - ``int`` / ``float`` → ``int(raw)`` (floats truncated; values ≤ 0 mean
- "no limit" → :data:`TURN_LIMIT_UNLIMITED`).
- - numeric string (``"120"``) → ``int(raw)``.
- - ``"none"`` / ``"null"`` / ``"unlimited"`` / ``"infinite"`` /
- ``"infinity"`` / ``"inf"`` / ``"∞"`` / ``"-1"`` / ``"0"``
- (case-insensitive, whitespace-tolerant) → :data:`TURN_LIMIT_UNLIMITED`.
- - YAML ``None`` / ``null`` / absent value → ``default`` (which is itself
- :data:`TURN_LIMIT_UNLIMITED` — max_turns is unlimited by default).
- - Anything unparseable → ``default`` (with a debug log).
-
- The returned int is always ≥ 1, so loop conditions like
- ``while api_call_count < agent.max_iterations`` behave correctly even when
- the default (unlimited) path is taken.
-
- This is the single normalization point for the turn-limit value type.
- Config-reading sites (cli.py, gateway/run.py, cron/scheduler.py) call this
- instead of bare ``int(...)``, so ``agent.max_turns: none`` in config.yaml
- becomes a first-class supported spelling of "unlimited". max_turns is
- unlimited unless the user sets an explicit positive integer cap.
+ The returned int is always ≥ 1, so loop conditions like ``while api_call_count <
+ agent.max_iterations`` behave correctly even when the default (unlimited) path is taken.
"""
if raw is None:
return default
@@ -3539,36 +2977,13 @@ def resolve_turn_limit(raw: Any, default: int = TURN_LIMIT_UNLIMITED) -> int:
def cfg_get(cfg: Optional[Dict[str, Any]], *keys: str, default: Any = None) -> Any:
"""Traverse nested dict keys safely, returning ``default`` on any miss.
- Canonical helper for the ``cfg.get("X", {}).get("Y", default)`` pattern
- that appears 50+ times across the codebase. Handles three common gotchas
- in one place:
-
- 1. Missing intermediate keys (returns ``default``, no KeyError).
- 2. An intermediate value that's not a dict (e.g. a user wrote a string
- where a section was expected). Returns ``default`` instead of
- AttributeError on ``.get()``.
- 3. ``cfg is None`` (callers sometimes pass ``load_config() or None``).
-
- Named ``cfg_get`` rather than ``cfg_path`` to avoid shadowing the
- ubiquitous ``cfg_path = _hermes_home / "config.yaml"`` local variable
- that appears in gateway/run.py, cron/scheduler.py, main.py, etc.
-
- Explicit ``None`` values are returned as-is (matches ``dict.get(key,
- default)`` semantics — ``default`` is only returned when the key is
- *absent*, not when it's present but set to ``None``).
-
- Examples:
- >>> cfg_get({"agent": {"reasoning_effort": "high"}}, "agent", "reasoning_effort")
- 'high'
- >>> cfg_get({}, "agent", "reasoning_effort", default="medium")
- 'medium'
- >>> cfg_get({"agent": "oops_a_string"}, "agent", "reasoning_effort", default="low")
- 'low'
- >>> cfg_get(None, "anything", default=42)
- 42
- >>> cfg_get({"a": {"b": None}}, "a", "b", default="def") # explicit None preserved
- >>> cfg_get({"a": {"b": False}}, "a", "b", default=True) # falsy values preserved
- False
+ Named ``cfg_get`` rather than ``cfg_path`` to avoid shadowing the ubiquitous ``cfg_path =
+ _hermes_home / "config.yaml"`` local variable that appears in gateway/run.py, cron/scheduler.py,
+ main.py, etc.
+
+ Explicit ``None`` values are returned as-is (matches ``dict.get(key, default)`` semantics —
+ ``default`` is only returned when the key is *absent*, not when it's present but set to
+ ``None``).
"""
if not isinstance(cfg, dict):
return default
@@ -3582,54 +2997,17 @@ def cfg_get(cfg: Optional[Dict[str, Any]], *keys: str, default: Any = None) -> A
return node
-# Back-compat alias — canonical set lives in hermes_cli.personality.
-from hermes_cli.personality import NEUTRAL_PERSONALITY_NAMES as _NEUTRAL_PERSONALITY_NAMES # noqa: F401
-
-
-def _prompt_text(value: Any) -> str:
- """Normalize config prompt values from YAML before handing them to AIAgent.
-
- Delegates to :mod:`hermes_cli.personality` — the single owner of
- personality/overlay semantics. Kept as a re-export for existing importers.
- """
- from hermes_cli.personality import prompt_text
-
- return prompt_text(value)
-
-
-def render_personality_prompt(value: Any) -> str:
- """Render a string or structured personality definition to a prompt."""
- from hermes_cli.personality import render_personality_prompt as _render
-
- return _render(value)
-
-
-def resolve_ephemeral_system_prompt_from_config(cfg: Optional[Dict[str, Any]]) -> str:
- """Resolve the session overlay from config.yaml.
-
- ``display.personality`` is the selected named personality and wins when set.
- Otherwise fall back to the user-owned ``agent.system_prompt``. Callers should
- still prefer ``HERMES_EPHEMERAL_SYSTEM_PROMPT`` when that env var is set.
-
- Delegates to :mod:`hermes_cli.personality` (single owner).
- """
- from hermes_cli.personality import resolve_ephemeral_system_prompt
-
- return resolve_ephemeral_system_prompt(cfg)
-
-
-def read_raw_config() -> Dict[str, Any]:
- """Read ~/.hermes/config.yaml as-is, without merging defaults or migrating.
+# Back-compat re-exports — :mod:`hermes_cli.personality` is the single owner of
+# personality/overlay semantics; these names stay importable from here.
+from hermes_cli.personality import ( # noqa: E402,F401
+ NEUTRAL_PERSONALITY_NAMES as _NEUTRAL_PERSONALITY_NAMES,
+ prompt_text as _prompt_text,
+ render_personality_prompt,
+ resolve_ephemeral_system_prompt as resolve_ephemeral_system_prompt_from_config,
+)
- Returns the raw YAML dict, or ``{}`` if the file doesn't exist or can't
- be parsed. Use this for lightweight config reads where you just need a
- single value and don't want the overhead of ``load_config()``'s deep-merge
- + migration pipeline.
- Cached on the config file's (mtime_ns, size) — same strategy as
- ``load_config()``. Returns a deepcopy on every call since some callers
- mutate the result before passing to ``save_config()``.
- """
+def _read_raw_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:
with _CONFIG_LOCK:
try:
config_path = get_config_path()
@@ -3641,7 +3019,7 @@ def read_raw_config() -> Dict[str, Any]:
path_key = str(config_path)
cached = _RAW_CONFIG_CACHE.get(path_key)
if cached is not None and cached[:2] == cache_key:
- return copy.deepcopy(cached[2])
+ return copy.deepcopy(cached[2]) if want_deepcopy else cached[2]
try:
with open(config_path, encoding="utf-8") as f:
@@ -3652,48 +3030,32 @@ def read_raw_config() -> Dict[str, Any]:
if not isinstance(data, dict):
data = {}
- _RAW_CONFIG_CACHE[path_key] = (cache_key[0], cache_key[1], copy.deepcopy(data))
- return data
+ # The cache stores its own deepcopy. The readonly path returns THAT
+ # object (identity invariant: the first caller must see the exact dict
+ # later cache hits return); the mutable path returns the fresh parse.
+ cached_copy = copy.deepcopy(data)
+ _RAW_CONFIG_CACHE[path_key] = (cache_key[0], cache_key[1], cached_copy)
+ return data if want_deepcopy else cached_copy
+
+
+def read_raw_config() -> Dict[str, Any]:
+ """Read ~/.hermes/config.yaml as-is, without merging defaults or migrating.
+
+ Returns the raw YAML dict, or ``{}`` if the file doesn't exist or can't be parsed. Use this for
+ lightweight config reads where you just need a single value and don't want the overhead of
+ ``load_config()``'s deep-merge + migration pipeline.
+
+ Cached on the config file's (mtime_ns, size) — same strategy as ``load_config()``. Returns a
+ deepcopy on every call since some callers mutate the result before passing to ``save_config()``.
+ """
+ return _read_raw_config_impl(want_deepcopy=True)
def read_user_config_raw(config_path: Optional[Path] = None) -> Dict[str, Any]:
- """Read a user ``config.yaml`` EXACTLY as written on disk.
-
- No DEFAULT_CONFIG merge, no managed-scope overlay, no ``${ENV_VAR}``
- expansion, no migration, no root-model normalization, no caching.
-
- ONLY legal for write-back round-trips and raw-file diagnostics —
- behavioral reads must use load_config()/load_config_readonly().
-
- Legal call sites, exhaustively:
-
- * WRITE-BACK ROUND-TRIPS (read → mutate one key → save): merging
- defaults or the managed overlay here would persist hundreds of
- default keys (or administrator-pinned values) into the user's file
- on the next save. Raw is *correct*, not an optimization.
- * RAW-FILE DIAGNOSTICS (doctor, deprecation sweeps): these inspect
- what the user actually wrote — stale root keys, drift against .env —
- and merged defaults would produce false positives.
- * PRESENCE-SENSITIVE ENV BRIDGES (gateway/send bridges that only
- export a key when the user explicitly set it): a defaults merge
- would make every key "present" and bridge the entire DEFAULT_CONFIG
- into the environment. These sites must still apply
- ``managed_scope.apply_managed_overlay`` + ``_expand_env_vars``
- inline, which they do.
-
- Semantics (deliberately mirrors the bare ``open()+yaml.safe_load()``
- pattern this replaces, so migrated sites keep their exact failure
- behavior):
-
- * missing file → ``{}``
- * unparseable YAML / other I/O errors → raises (callers that want
- fail-open already wrap in try/except; callers with last-known-good
- or warn semantics rely on the exception)
- * non-dict YAML root → ``{}``
-
- ``config_path`` defaults to :func:`get_config_path` (profile-aware).
- Pass an explicit path when the caller resolves its own home (gateway
- ``_hermes_home``, tui profile override, multi-profile probes).
+ """Read a user ``config.yaml`` EXACTLY as written on disk (no defaults/overlay/expansion).
+
+ ONLY legal for write-back round-trips and raw-file diagnostics — behavioral
+ reads must use load_config()/load_config_readonly().
"""
if config_path is None:
config_path = get_config_path()
@@ -3708,46 +3070,15 @@ def read_user_config_raw(config_path: Optional[Path] = None) -> Dict[str, Any]:
def read_raw_config_readonly() -> Dict[str, Any]:
"""Fast-path variant of ``read_raw_config()`` for callers that ONLY READ.
- Returns the cached raw-config dict directly, skipping the per-call
- ``copy.deepcopy`` that ``read_raw_config()`` performs (needed there
- because some callers mutate the result before ``save_config``).
-
- **Mutating the returned dict corrupts the in-process cache for every
- subsequent caller.** Only use on read-only paths — e.g. per-turn policy
- checks like the shared-metrics gate, which runs 2-3x per agent turn and
- was paying a full config deepcopy each time.
+ Returns the cached raw-config dict directly, skipping the per-call ``copy.deepcopy`` that
+ ``read_raw_config()`` performs (needed there because some callers mutate the result before
+ ``save_config``).
- Same (mtime_ns, size) freshness key as ``read_raw_config()`` — an edited
- config.yaml is picked up on the next call.
+ **Mutating the returned dict corrupts the in-process cache for every subsequent caller.** Only
+ use on read-only paths — e.g. per-turn policy checks like the shared-metrics gate, which runs
+ 2-3x per agent turn and was paying a full config deepcopy each time.
"""
- with _CONFIG_LOCK:
- try:
- config_path = get_config_path()
- st = config_path.stat()
- cache_key = (st.st_mtime_ns, st.st_size)
- except (FileNotFoundError, OSError):
- return {}
-
- path_key = str(config_path)
- cached = _RAW_CONFIG_CACHE.get(path_key)
- if cached is not None and cached[:2] == cache_key:
- return cached[2]
-
- try:
- with open(config_path, encoding="utf-8") as f:
- data = fast_safe_load(f) or {}
- except Exception as e:
- _warn_config_parse_failure(config_path, e)
- return {}
-
- if not isinstance(data, dict):
- data = {}
- # Store and return THE SAME object (identity invariant): the first
- # caller must see the exact dict later cache hits return, so a test
- # asserting ``ro1 is ro2`` holds from the very first call.
- cached_copy = copy.deepcopy(data)
- _RAW_CONFIG_CACHE[path_key] = (cache_key[0], cache_key[1], cached_copy)
- return cached_copy
+ return _read_raw_config_impl(want_deepcopy=False)
def require_readable_config_before_write(
@@ -3755,21 +3086,14 @@ def require_readable_config_before_write(
) -> Dict[str, Any]:
"""Refuse to replace an existing config.yaml that cannot be read or parsed.
- Guards two collapse-to-empty failure modes that would otherwise let a
- read-then-write caller silently wipe user overrides:
-
- 1. **Unreadable** (permissions / broken mount) - byte open fails.
- 2. **Unparseable or non-mapping** - YAML load raises, or the root is a
- list/scalar. ``read_user_config_raw()`` / bare ``except`` loaders treat
- both as ``{}``, so a subsequent write would replace the recoverable
- file with only the caller's partial dict.
-
- Returns the loaded mapping (or ``{}`` for a missing / empty / null
- document) so mutation callers can skip a second parse. A valid empty
- mapping (``{}``) is allowed through so first-time installs and
- intentional empty configs still work. On parse failure this also
- snapshots a ``.corrupt.*.bak`` via :func:`_warn_config_parse_failure`
- before raising.
+ Guards two collapse-to-empty failure modes that would otherwise let a read-then-write caller
+ silently wipe user overrides:
+
+ 1. **Unreadable** (permissions / broken mount) - byte open fails. 2. **Unparseable or non-
+ mapping** - YAML load raises, or the root is a list/scalar. ``read_user_config_raw()`` / bare
+ ``except`` loaders treat both as ``{}``, so a subsequent write would replace the recoverable
+ file with only the caller's partial dict. Fails closed (no bare-except to ``{}`` collapse) and
+ returns the parsed mapping so callers do not re-parse.
"""
if config_path is None:
config_path = get_config_path()
@@ -3783,28 +3107,6 @@ def require_readable_config_before_write(
f"({exc}). Fix the file permissions or move it aside first."
) from exc
- try:
- with open(config_path, "rb") as f:
- f.read(1)
- except OSError as exc:
- raise RuntimeError(
- f"Refusing to overwrite {config_path}: existing config.yaml cannot be read "
- f"({exc}). Fix the file permissions or move it aside first."
- ) from exc
-
- return _load_user_config_for_mutation(config_path)
-
-
-def _load_user_config_for_mutation(config_path: Path) -> Dict[str, Any]:
- """Load raw user config for a fail-closed mutation path.
-
- Fail closed on parse / non-mapping (no bare-except to ``{}`` collapse).
- Used by :func:`require_readable_config_before_write` and any caller that
- must re-validate after other work. Distinct from
- :func:`read_user_config_raw`, which collapses non-dict roots to ``{}``.
- """
- if not config_path.exists():
- return {}
try:
with open(config_path, encoding="utf-8") as f:
loaded = fast_safe_load(f)
@@ -3837,23 +3139,10 @@ def _load_user_config_for_mutation(config_path: Path) -> Dict[str, Any]:
def atomic_config_write(config_path: Path, data: Any, **kwargs: Any) -> None:
"""Fail-closed atomic write for ``config.yaml``.
- The single chokepoint every config-update path should use instead of
- calling :func:`utils.atomic_yaml_write` directly. It runs
- :func:`require_readable_config_before_write` first, so a full-file
- replacement can never silently clobber an existing ``config.yaml`` that
- degraded to an empty dict on read (permission error, broken mount,
- transient I/O, unparseable YAML, or a non-mapping root). New-file
- creation still works when the path is absent.
-
- Root cause this guards: ``read_user_config_raw()`` returns ``{}`` for an
- absent file / unreadable path edge cases and collapses non-dict roots.
- Callers that read then overwrite can't tell these apart, so a broken
- config would be replaced with only defaults or the single edited section. Routing every
- write through this helper enforces the invariant in one place rather than
- relying on each of ~15 independent write sites to remember the guard.
-
- ``kwargs`` are forwarded verbatim to ``atomic_yaml_write``
- (``sort_keys``, ``default_flow_style``, ``extra_content``, ...).
+ Root cause this guards: ``read_user_config_raw()`` returns ``{}`` for an absent file /
+ unreadable path edge cases and collapses non-dict roots. Callers that read then overwrite can't
+ tell these apart, so a broken config would be replaced with only defaults or the single edited
+ section.
"""
from utils import atomic_yaml_write
@@ -3864,16 +3153,13 @@ def atomic_config_write(config_path: Path, data: Any, **kwargs: Any) -> None:
def load_config() -> Dict[str, Any]:
"""Load configuration from ~/.hermes/config.yaml.
- Cached on the config file's (mtime_ns, size). Returns a deepcopy of
- the cached value when unchanged, since most call sites mutate the
- result (e.g. ``cfg["model"]["default"] = ...`` before ``save_config``).
- The cache is keyed on ``str(config_path)`` so profile switches
- (which change ``HERMES_HOME`` and therefore ``get_config_path()``)
- don't collide.
+ Cached on the config file's (mtime_ns, size). Returns a deepcopy of the cached value when
+ unchanged, since most call sites mutate the result (e.g. ``cfg["model"]["default"] = ...``
+ before ``save_config``).
- Read-only callers should use ``load_config_readonly()`` to skip the
- defensive deepcopy — that path matters in agent-loop hot spots like
- ``get_provider_request_timeout`` which is called once per API turn.
+ Read-only callers should use ``load_config_readonly()`` to skip the defensive deepcopy — that
+ path matters in agent-loop hot spots like ``get_provider_request_timeout`` which is called once
+ per API turn.
"""
return _load_config_impl(want_deepcopy=True)
@@ -3881,26 +3167,26 @@ def load_config() -> Dict[str, Any]:
def load_config_readonly() -> Dict[str, Any]:
"""Fast-path variant of ``load_config()`` for callers that ONLY READ.
- Returns the cached config dict directly without the defensive deepcopy
- that ``load_config()`` applies. **Mutating the returned dict (or any
- nested structure) corrupts the in-process cache for every subsequent
- caller** — only use this when you are absolutely sure your code path
- will not write to the result. If you need to mutate or pass to
- ``save_config``, call ``load_config()`` instead.
-
- Why this exists: ``load_config()`` cache-hit cost is ~265us per call,
- half of which (~135us) is the defensive deepcopy. The agent loop calls
- into config reads (timeouts, thresholds, feature flags) ~20-50x per
- conversation; skipping deepcopy here removes a measurable allocation
- source and the GC pressure that comes with it.
-
- Note: this returns a plain ``dict`` (not ``MappingProxyType``) so
- existing ``isinstance(x, dict)`` guards downstream keep working. The
- safety guarantee is purely documented, not enforced — be careful.
+ Returns the cached config dict directly without the defensive deepcopy that ``load_config()``
+ applies. **Mutating the returned dict (or any nested structure) corrupts the in-process cache
+ for every subsequent caller** — only use this when you are absolutely sure your code path will
+ not write to the result.
+
+ Why this exists: ``load_config()`` cache-hit cost is ~265us per call, half of which (~135us) is
+ the defensive deepcopy.
"""
return _load_config_impl(want_deepcopy=False)
+def _ensure_dict(parent: Dict[str, Any], key: str) -> Dict[str, Any]:
+ """Return ``parent[key]`` as a dict, replacing a missing or non-dict value with ``{}``."""
+ child = parent.get(key)
+ if not isinstance(child, dict):
+ child = {}
+ parent[key] = child
+ return child
+
+
def write_platform_config_field(
platform_key: str,
field_key: str,
@@ -3910,59 +3196,33 @@ def write_platform_config_field(
) -> None:
"""Persist one scalar field under ``platforms.<platform_key>``.
- ``raw=True`` preserves CLI setup flows that intentionally edit only the
- user's raw config file. Dashboard routes use the default loaded-config path
- so they retain their existing profile-scoped ``load_config`` behavior.
+ ``raw=True`` preserves CLI setup flows that intentionally edit only the user's raw config file.
+ Dashboard routes use the default loaded-config path so they retain their existing profile-scoped
+ ``load_config`` behavior.
"""
config = read_raw_config() if raw else load_config()
- platforms = config.setdefault("platforms", {})
- if not isinstance(platforms, dict):
- platforms = {}
- config["platforms"] = platforms
-
- platform_config = platforms.setdefault(platform_key, {})
- if not isinstance(platform_config, dict):
- platform_config = {}
- platforms[platform_key] = platform_config
-
- platform_config[field_key] = value
+ platforms = _ensure_dict(config, "platforms")
+ _ensure_dict(platforms, platform_key)[field_key] = value
save_config(config)
+# ``terminal.<key>`` -> env var read by tools.terminal_tool. Every key maps to
+# ``TERMINAL_<KEY>`` except ``backend`` (historically ``TERMINAL_ENV``).
TERMINAL_CONFIG_ENV_MAP = {
"backend": "TERMINAL_ENV",
- "modal_mode": "TERMINAL_MODAL_MODE",
- "degraded_mode": "TERMINAL_DEGRADED_MODE",
- "cwd": "TERMINAL_CWD",
- "temp_dir": "TERMINAL_TEMP_DIR",
- "timeout": "TERMINAL_TIMEOUT",
- "lifetime_seconds": "TERMINAL_LIFETIME_SECONDS",
- "docker_image": "TERMINAL_DOCKER_IMAGE",
- "docker_forward_env": "TERMINAL_DOCKER_FORWARD_ENV",
- "singularity_image": "TERMINAL_SINGULARITY_IMAGE",
- "modal_image": "TERMINAL_MODAL_IMAGE",
- "daytona_image": "TERMINAL_DAYTONA_IMAGE",
- "vercel_runtime": "TERMINAL_VERCEL_RUNTIME",
- "ssh_host": "TERMINAL_SSH_HOST",
- "ssh_user": "TERMINAL_SSH_USER",
- "ssh_port": "TERMINAL_SSH_PORT",
- "ssh_key": "TERMINAL_SSH_KEY",
- "container_cpu": "TERMINAL_CONTAINER_CPU",
- "container_memory": "TERMINAL_CONTAINER_MEMORY",
- "container_disk": "TERMINAL_CONTAINER_DISK",
- "container_persistent": "TERMINAL_CONTAINER_PERSISTENT",
- "docker_volumes": "TERMINAL_DOCKER_VOLUMES",
- "docker_env": "TERMINAL_DOCKER_ENV",
- "docker_mount_cwd_to_workspace": "TERMINAL_DOCKER_MOUNT_CWD_TO_WORKSPACE",
- "docker_network": "TERMINAL_DOCKER_NETWORK",
- "docker_extra_args": "TERMINAL_DOCKER_EXTRA_ARGS",
- "docker_shm_size": "TERMINAL_DOCKER_SHM_SIZE",
- "docker_run_as_host_user": "TERMINAL_DOCKER_RUN_AS_HOST_USER",
- "docker_persist_across_processes": "TERMINAL_DOCKER_PERSIST_ACROSS_PROCESSES",
- "docker_shared_container_key": "TERMINAL_DOCKER_SHARED_CONTAINER_KEY",
- "docker_orphan_reaper": "TERMINAL_DOCKER_ORPHAN_REAPER",
- "sandbox_dir": "TERMINAL_SANDBOX_DIR",
- "persistent_shell": "TERMINAL_PERSISTENT_SHELL",
+ **{
+ key: f"TERMINAL_{key.upper()}"
+ for key in (
+ "modal_mode", "degraded_mode", "cwd", "temp_dir", "timeout", "lifetime_seconds",
+ "docker_image", "docker_forward_env", "singularity_image", "modal_image",
+ "daytona_image", "vercel_runtime", "ssh_host", "ssh_user", "ssh_port", "ssh_key",
+ "container_cpu", "container_memory", "container_disk", "container_persistent",
+ "docker_volumes", "docker_env", "docker_mount_cwd_to_workspace", "docker_network",
+ "docker_extra_args", "docker_shm_size", "docker_run_as_host_user",
+ "docker_persist_across_processes", "docker_shared_container_key",
+ "docker_orphan_reaper", "sandbox_dir", "persistent_shell",
+ )
+ },
}
@@ -3974,9 +3234,7 @@ def _terminal_env_value(value: Any) -> str:
def _terminal_config_value_is_bridgeable(key: str, value: Any) -> bool:
"""Return whether a terminal config value owns its mirrored env var."""
- if key == "cwd" and str(value or "").strip() in {".", "auto", "cwd"}:
- return False
- return True
+ return not (key == "cwd" and str(value or "").strip() in {".", "auto", "cwd"})
def terminal_config_owned_env_vars(terminal_config: Any) -> Set[str]:
@@ -4002,9 +3260,8 @@ def terminal_config_env_var_for_key(key: str) -> Optional[str]:
def _is_ssh_remote_tilde_cwd(backend: str, cwd: str) -> bool:
"""Return whether the remote SSH shell must expand *cwd* itself.
- Expanding ``~`` on the Hermes host rewrites it to the host or container
- home before SSH sees it. Preserve ``~`` and ``~/...`` so they follow the
- user selected by the SSH connection.
+ Expanding ``~`` on the Hermes host rewrites it to the host or container home before SSH sees it.
+ Preserve ``~`` and ``~/...`` so they follow the user selected by the SSH connection.
"""
if (backend or "").strip().lower() != "ssh":
return False
@@ -4019,14 +3276,14 @@ def apply_terminal_config_to_env(
) -> Dict[str, str]:
"""Bridge ``terminal.*`` config into the env vars terminal tools read.
- ``tools.terminal_tool`` is intentionally environment-driven because it also
- runs in child processes (TUI, dashboard PTY, gateway workers). This helper
- gives those child-process launch paths the same config bridge as classic
- CLI without importing ``cli.py`` and paying for its startup side effects.
+ ``tools.terminal_tool`` is intentionally environment-driven because it also runs in child
+ processes (TUI, dashboard PTY, gateway workers). This helper gives those child-process launch
+ paths the same config bridge as classic CLI without importing ``cli.py`` and paying for its
+ startup side effects.
- Explicit keys in the user config's ``terminal`` section are authoritative
- and override their matching env values. Merged defaults only backfill
- missing env vars; they never replace unrelated exported/.env values.
+ Explicit keys in the user config's ``terminal`` section are authoritative and override their
+ matching env values. Merged defaults only backfill missing env vars; they never replace
+ unrelated exported/.env values.
"""
target = os.environ if env is None else env
@@ -4047,15 +3304,10 @@ def apply_terminal_config_to_env(
# override existing env values; keys inherited from DEFAULT_CONFIG are
# backfill-only.
explicit_keys = terminal_cfg.keys() if config is not None else raw_terminal_cfg.keys()
- backend_is_explicit = config is not None or "backend" in raw_terminal_cfg
- if backend_is_explicit:
- terminal_backend = str(
- terminal_cfg.get("backend") or target.get("TERMINAL_ENV") or ""
- )
- else:
- terminal_backend = str(
- target.get("TERMINAL_ENV") or terminal_cfg.get("backend") or ""
- )
+ backend_sources = (terminal_cfg.get("backend"), target.get("TERMINAL_ENV"))
+ if not (config is not None or "backend" in raw_terminal_cfg):
+ backend_sources = backend_sources[::-1] # env wins when the file did not set backend
+ terminal_backend = str(backend_sources[0] or backend_sources[1] or "")
for cfg_key, env_var in TERMINAL_CONFIG_ENV_MAP.items():
if cfg_key not in terminal_cfg:
@@ -4074,52 +3326,76 @@ def apply_terminal_config_to_env(
return target
-def _load_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:
- with _CONFIG_LOCK:
- ensure_hermes_home()
- config_path = get_config_path()
- path_key = str(config_path)
+def _load_config_cache_sig(config_path: Path, managed_scope) -> Tuple[Optional[Tuple[int, int]], Optional[Tuple[int, int, int, int]]]:
+ """Return ``(user_sig, cache_sig)`` for ``_LOAD_CONFIG_CACHE``.
- try:
- st = config_path.stat()
- user_sig: Optional[Tuple[int, int]] = (st.st_mtime_ns, st.st_size)
- except FileNotFoundError:
- user_sig = None
+ The managed config file's (mtime, size) is folded in so editing /etc/hermes/config.yaml
+ invalidates the cached merged result ((0, 0) = no managed file). ``cache_sig`` is None only when
+ the user config is absent AND no managed file exists (nothing to cache on).
+ """
+ try:
+ st = config_path.stat()
+ user_sig: Optional[Tuple[int, int]] = (st.st_mtime_ns, st.st_size)
+ except FileNotFoundError:
+ user_sig = None
- # Managed scope: fold the managed config file's (mtime, size) into the
- # cache signature so editing /etc/hermes/config.yaml invalidates the
- # cached merged result. (0, 0) means "no managed config file".
- from hermes_cli import managed_scope
+ managed_dir = managed_scope.get_managed_dir()
+ managed_cfg_path = (managed_dir / "config.yaml") if managed_dir else None
+ try:
+ mst = managed_cfg_path.stat() if managed_cfg_path else None
+ managed_sig = (mst.st_mtime_ns, mst.st_size) if mst else (0, 0)
+ except OSError:
+ managed_sig = (0, 0)
- managed_dir = managed_scope.get_managed_dir()
- managed_cfg_path = (managed_dir / "config.yaml") if managed_dir else None
- try:
- mst = managed_cfg_path.stat() if managed_cfg_path else None
- managed_sig = (mst.st_mtime_ns, mst.st_size) if mst else (0, 0)
- except OSError:
- managed_sig = (0, 0)
+ if user_sig is not None:
+ return user_sig, (*user_sig, *managed_sig)
+ if managed_sig != (0, 0):
+ return None, (0, 0, *managed_sig)
+ return None, None
- # Combined cache signature: user file + managed file. None only when the
- # user config is absent AND no managed file exists (nothing to cache on).
- if user_sig is not None:
- cache_sig: Optional[Tuple[int, int, int, int]] = (
- user_sig[0],
- user_sig[1],
- managed_sig[0],
- managed_sig[1],
- )
- elif managed_sig != (0, 0):
- cache_sig = (0, 0, managed_sig[0], managed_sig[1])
- else:
- cache_sig = None
+
+def _last_known_good_fallback(config_path: Path, path_key: str, cache_sig, exc: Exception) -> Optional[Dict[str, Any]]:
+ """Warn about a parse failure and return the last-known-good config, or None (→ defaults).
+
+ A parse failure must not silently replace the effective config with defaults — that drops EVERY
+ user override, including security-critical ``approvals.deny`` rules (a gateway whose user
+ mid-edits config.yaml into broken YAML would lose them on the next load). Within a running
+ process keep serving the last successfully loaded config until the file is fixed.
+ """
+ lkg = _LAST_EXPANDED_CONFIG_BY_PATH.get(path_key)
+ _warn_config_parse_failure(
+ config_path, exc, fallback="last-known-good" if lkg is not None else "defaults",
+ )
+ if lkg is None:
+ return None
+ # save_config() stores the pre-expansion normalized dict (env-ref templates
+ # preserved); the load path stores the expanded one. Expand defensively —
+ # idempotent when already expanded.
+ lkg_copy: Dict[str, Any] = _expand_env_vars(copy.deepcopy(lkg))
+ if cache_sig is not None:
+ # Cache under the corrupt file's signature (empty env snapshot: always
+ # valid) so repeated loads don't re-parse the broken file; fixing the
+ # file changes the signature and triggers a normal reload.
+ _LOAD_CONFIG_CACHE[path_key] = (*cache_sig, lkg_copy, {})
+ return lkg_copy
+
+
+def _load_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:
+ with _CONFIG_LOCK:
+ ensure_hermes_home()
+ config_path = get_config_path()
+ path_key = str(config_path)
+
+ from hermes_cli import managed_scope
+
+ user_sig, cache_sig = _load_config_cache_sig(config_path, managed_scope)
cached = _LOAD_CONFIG_CACHE.get(path_key)
if cached is not None and cache_sig is not None and cached[:4] == cache_sig:
# File signatures match, but the cached expansion is only valid if
- # every ${VAR} it was expanded against still has the same value.
- # Without this, a load_config() that ran before load_hermes_dotenv()
- # pins unexpanded literals (e.g. auxiliary.<task>.api_key) for the
- # life of the process (#58514).
+ # every ${VAR} it was expanded against still has the same value —
+ # otherwise a load before load_hermes_dotenv() pins unexpanded
+ # literals (e.g. auxiliary.<task>.api_key) for the process lifetime.
env_snapshot = cached[5] if len(cached) > 5 else {}
if all(_env_ref_lookup(k) == v for k, v in env_snapshot.items()):
return copy.deepcopy(cached[4]) if want_deepcopy else cached[4]
@@ -4140,44 +3416,8 @@ def _load_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:
config = _deep_merge(config, user_config)
except Exception as e:
- # Last-known-good fallback (port of openai/codex#31188's
- # invariant: a parse failure in a policy/config file must not
- # silently replace the effective policy with an empty/default
- # one). Falling through to DEFAULT_CONFIG here drops EVERY user
- # override — including security-critical ``approvals.deny``
- # rules, which are supposed to block commands even under yolo.
- # A long-running gateway whose user mid-edits config.yaml into
- # broken YAML would silently lose those rules on the next load.
- # Within a running process we still have the last successfully
- # loaded config — keep serving it until the file is fixed.
- # Fresh processes with no last-known-good keep the existing
- # DEFAULT_CONFIG fallback.
- lkg = _LAST_EXPANDED_CONFIG_BY_PATH.get(path_key)
- _warn_config_parse_failure(
- config_path,
- e,
- fallback="last-known-good" if lkg is not None else "defaults",
- )
- if lkg is not None:
- # save_config() stores the pre-expansion normalized dict
- # (env-ref templates preserved); the load path stores the
- # expanded one. Expand defensively — idempotent when the
- # stored value is already expanded.
- from typing import cast as _cast
- lkg_copy: Dict[str, Any] = _cast(
- Dict[str, Any], _expand_env_vars(copy.deepcopy(lkg))
- )
- if cache_sig is not None:
- # Cache under the corrupt file's signature (empty env
- # snapshot: always valid) so repeated loads don't
- # re-parse the broken file; fixing the file changes the
- # signature and triggers a normal reload.
- _empty_env: Dict[str, Optional[str]] = {}
- _LOAD_CONFIG_CACHE[path_key] = (
- cache_sig[0], cache_sig[1],
- cache_sig[2], cache_sig[3],
- lkg_copy, _empty_env,
- )
+ lkg_copy = _last_known_good_fallback(config_path, path_key, cache_sig, e)
+ if lkg_copy is not None:
return copy.deepcopy(lkg_copy) if want_deepcopy else lkg_copy
normalized = _normalize_root_model_keys(_normalize_max_turns_config(config))
@@ -4189,29 +3429,21 @@ def _load_config_impl(*, want_deepcopy: bool) -> Dict[str, Any]:
# keys the managed layer pins — see docs/design/managed-scope.md §4.1.
managed_config = managed_scope.load_managed_config()
if managed_config:
- # Normalize the managed overlay through the same canonicalization as
- # the user config BEFORE merging (parity with
- # managed_scope.apply_managed_overlay): a dict-valued
- # ``model.default`` (``{provider: ..., model: ...}``) or a bare
- # ``model: <string>`` must be flattened to a string ``default``
- # paired with ``provider`` so the merged result never exposes a
- # nested dict to status/fallback/runtime readers.
+ # Same canonicalization as the user config BEFORE merging (parity
+ # with managed_scope.apply_managed_overlay): a dict-valued
+ # ``model.default`` or bare ``model: <string>`` is flattened so the
+ # merged result never exposes a nested dict to runtime readers.
managed_normalized = _normalize_root_model_keys(managed_config)
if isinstance(managed_normalized.get("model"), str):
managed_normalized = dict(managed_normalized)
managed_normalized["model"] = {"default": managed_normalized["model"]}
- managed_expanded = _expand_env_vars(managed_normalized)
- expanded = _deep_merge(expanded, managed_expanded)
+ expanded = _deep_merge(expanded, _expand_env_vars(managed_normalized))
_LAST_EXPANDED_CONFIG_BY_PATH[path_key] = copy.deepcopy(expanded)
if cache_sig is not None:
- # Cache stores a separate deepcopy so subsequent ``load_config()``
- # (deepcopy=True) callers can mutate freely without affecting the
- # cached value, and ``load_config_readonly()`` (deepcopy=False)
- # callers all see the same stable cached object. The cached tuple is
- # (user_mtime, user_size, managed_mtime, managed_size, value,
- # env_ref_snapshot). The snapshot records the environment values
- # this expansion was made against so later loads can detect env
- # drift (late .env load, in-process rotation) — see cache hit above.
+ # The cache stores its own deepcopy so ``load_config()`` callers can
+ # mutate freely while ``load_config_readonly()`` callers all see the
+ # same stable object. The env snapshot records the values this
+ # expansion was made against so later loads detect env drift.
cached_copy = copy.deepcopy(expanded)
env_snapshot = _env_ref_snapshot(normalized)
if managed_config:
@@ -4275,38 +3507,6 @@ _FALLBACK_COMMENT = """
"""
-_COMMENTED_SECTIONS = """
-# ── Security ──────────────────────────────────────────────────────────
-# Secret redaction is ON by default. Set to false to pass tool output,
-# logs, and chat responses through unmodified (e.g. for redactor dev).
-#
-# security:
-# redact_secrets: true
-
-# ── Fallback Model ────────────────────────────────────────────────────
-# Automatic provider failover when primary is unavailable.
-# Uncomment and configure to enable. Triggers on rate limits (429),
-# overload (529), service errors (503), or connection failures.
-#
-# Supported providers:
-# openrouter (OPENROUTER_API_KEY) — routes to any model
-# openai-codex (OAuth — hermes auth) — OpenAI Codex
-# nous (OAuth — hermes auth) — Nous Portal
-# zai (ZAI_API_KEY) — Z.AI / GLM
-# kimi-coding (KIMI_API_KEY) — Kimi / Moonshot
-# kimi-coding-cn (KIMI_CN_API_KEY) — Kimi / Moonshot (China)
-# minimax (MINIMAX_API_KEY) — MiniMax
-# minimax-cn (MINIMAX_CN_API_KEY) — MiniMax (China)
-# bedrock (AWS IAM / boto3) — AWS Bedrock (Converse API)
-#
-# For custom OpenAI-compatible endpoints, add base_url and key_env.
-#
-# fallback_model:
-# provider: openrouter
-# model: anthropic/claude-sonnet-4
-"""
-
-
def save_config(
config: Dict[str, Any],
*,
@@ -4314,29 +3514,24 @@ def save_config(
preserve_keys: Optional[Set[Tuple[str, ...]]] = None,
merge_existing: bool = False,
):
- """Save configuration to ~/.hermes/config.yaml.\n
+ """Save configuration to ~/.hermes/config.yaml.
- Default values from ``DEFAULT_CONFIG`` are not written to disk unless
- the user explicitly set them (i.e. the path exists in the raw config
- before any normalisation). This prevents config.yaml from being
- contaminated with schema defaults on every save, which makes future
+ Default values from ``DEFAULT_CONFIG`` are not written to disk unless the user explicitly set
+ them (i.e. the path exists in the raw config before any normalisation). This prevents
+ config.yaml from being contaminated with schema defaults on every save, which makes future
default changes invisible to users.
- When ``merge_existing`` is True, the on-disk raw config is deep-merged
- under *config* before writing so partial callers (migration steps via
- ``_persist_migration``) cannot drop unrelated sections the caller omitted.
- Full-document replacement callers (dashboard raw YAML editor, callers that
- already deep-merge) must leave this False so intentional deletions survive.
+ When ``merge_existing`` is True, the on-disk raw config is deep-merged under *config* before
+ writing so partial callers (migration steps via ``_persist_migration``) cannot drop unrelated
+ sections the caller omitted.
"""
with _CONFIG_LOCK:
if is_managed():
managed_error("save configuration")
return
- # Managed scope: strip any leaf the managed layer pins, so a bulk write
- # (wizard / programmatic save) never persists a user value that would
- # silently lose to managed on the next load. Single-key `config set`
- # hard-rejects (see set_config_value); this is the mechanical safety net
- # for bulk writes so the unmanaged remainder still lands.
+ # Managed scope: strip any leaf the managed layer pins so a bulk write
+ # never persists a value that would lose to managed on the next load
+ # (single-key `config set` hard-rejects; this is the bulk safety net).
from hermes_cli import managed_scope
managed_keys = managed_scope.managed_config_keys()
@@ -4353,47 +3548,32 @@ def save_config(
ensure_hermes_home()
config_path = get_config_path()
require_readable_config_before_write(config_path)
- # Compute explicit user paths BEFORE any normalisation --------
- # _normalize_max_turns_config may inject agent.max_turns from
- # DEFAULT_CONFIG; using the raw dict preserves which paths the
- # user actually set so _strip_default_values can keep them.
+ # Explicit user paths are computed from the RAW dict BEFORE any
+ # normalisation (which may inject agent.max_turns from DEFAULT_CONFIG)
+ # so _strip_default_values keeps exactly what the user set.
_raw_for_paths = read_raw_config()
- explicit_raw_paths: Optional[Set[Tuple[str, ...]]] = (
- _explicit_config_paths(_raw_for_paths) if _raw_for_paths else None
- )
if merge_existing and _raw_for_paths:
config = _merge_partial_save(_raw_for_paths, config)
- # ----------------------------------------------------------------
- current_normalized = _normalize_root_model_keys(_normalize_max_turns_config(config))
+ _canon = lambda c: _normalize_root_model_keys(_normalize_max_turns_config(c)) # noqa: E731
+ current_normalized = _canon(config)
normalized = current_normalized
- raw_existing = (
- _normalize_root_model_keys(_normalize_max_turns_config(_raw_for_paths))
- if _raw_for_paths
- else {}
- )
- if raw_existing:
+ if _raw_for_paths:
normalized = _preserve_env_ref_templates(
normalized,
- raw_existing,
+ _canon(_raw_for_paths),
_LAST_EXPANDED_CONFIG_BY_PATH.get(str(config_path)),
)
# Strip schema-default values so the user's custom settings are not
- # silently reset on every save. Keys the user explicitly set (paths
- # from the raw pre-normalisation config) are always preserved.
- effective_preserve_keys: Set[Tuple[str, ...]] = {("_config_version",)}
- if explicit_raw_paths:
- effective_preserve_keys.update(explicit_raw_paths)
- if preserve_keys:
- effective_preserve_keys.update(preserve_keys)
-
- if strip_defaults and effective_preserve_keys:
- # _preserve_env_ref_templates may return Any; cast for type-checker.
- from typing import cast as _cast
- normalized = _cast(Dict[str, Any], normalized)
+ # silently reset on every save; explicitly-set paths always survive.
+ if strip_defaults:
+ effective_preserve_keys: Set[Tuple[str, ...]] = {("_config_version",)}
+ if _raw_for_paths:
+ effective_preserve_keys.update(_explicit_config_paths(_raw_for_paths))
+ effective_preserve_keys.update(preserve_keys or ())
normalized = _strip_default_values(
- normalized, # type: ignore[arg-type]
+ normalized,
DEFAULT_CONFIG,
preserve_keys=effective_preserve_keys,
)
@@ -4405,11 +3585,8 @@ def save_config(
if not sec or sec.get("redact_secrets") is None:
parts.append(_SECURITY_COMMENT)
fb = normalized.get("fallback_model", {})
- fb_is_valid = False
- if isinstance(fb, list):
- fb_is_valid = any(isinstance(e, dict) and e.get("provider") and e.get("model") for e in fb)
- elif isinstance(fb, dict):
- fb_is_valid = bool(fb.get("provider") and fb.get("model"))
+ fb_entries = fb if isinstance(fb, list) else [fb]
+ fb_is_valid = any(isinstance(e, dict) and e.get("provider") and e.get("model") for e in fb_entries)
if not fb_is_valid:
parts.append(_FALLBACK_COMMENT)
@@ -4449,16 +3626,12 @@ def _parse_env_value(raw_value: str) -> str:
def load_env() -> Dict[str, str]:
"""Load environment variables from ~/.hermes/.env.
- Normalizes line endings before parsing while treating each assignment's
- value as opaque data for boundary discovery.
+ Normalizes line endings before parsing while treating each assignment's value as opaque data for
+ boundary discovery.
- The parsed dict is memoised keyed on the .env file mtime, because
- ``get_env_value()`` is called dozens-to-hundreds of times per
- interactive menu render (`hermes tools`, `hermes setup`, status
- panels). Sanitisation is O(lines), so re-parsing the
- same file on every call was burning ~300ms of CPU per `hermes tools`
- menu paint on top of the OAuth-refresh slowness. The mtime check
- invalidates the cache when the user edits .env mid-process.
+ The parsed dict is memoised keyed on the .env file mtime, because ``get_env_value()`` is called
+ dozens-to-hundreds of times per interactive menu render (`hermes tools`, `hermes setup`, status
+ panels).
"""
global _env_cache
env_path = get_env_path()
@@ -4480,15 +3653,7 @@ def load_env() -> Dict[str, str]:
env_vars: Dict[str, str] = {}
if env_path.exists():
- # On Windows, open() defaults to the system locale (cp1252) which can
- # fail on UTF-8 .env files. Always use explicit UTF-8; tolerate BOM
- # via utf-8-sig since users may edit .env in Notepad which adds one.
- open_kw = {"encoding": "utf-8-sig", "errors": "replace"}
- with open(env_path, **open_kw) as f:
- raw_lines = f.readlines()
- # Normalize line endings without interpreting value contents as syntax.
- lines = _sanitize_env_lines(raw_lines)
- for line in lines:
+ for line in _read_env_lines(env_path):
line = line.strip()
if line and not line.startswith('#') and '=' in line:
# Strip the bash-compatible ``export `` prefix so lines like
@@ -4516,10 +3681,9 @@ _env_cache: Optional[Tuple[Tuple[str, Optional[float], Optional[int]], Dict[str,
def invalidate_env_cache() -> None:
"""Clear the load_env() process-level memo.
- Writers that mutate .env (set_env_value, save_env, etc.) call this
- to guarantee the next load_env() sees their change even on
- filesystems with coarse mtime resolution. Reads invalidate naturally
- via the mtime/size check.
+ Writers that mutate .env (set_env_value, save_env, etc.) call this to guarantee the next
+ load_env() sees their change even on filesystems with coarse mtime resolution. Reads invalidate
+ naturally via the mtime/size check.
"""
global _env_cache
_env_cache = None
@@ -4528,9 +3692,9 @@ def invalidate_env_cache() -> None:
def _sanitize_env_lines(lines: list) -> list:
"""Normalize .env line endings without changing assignment semantics.
- Content after the first ``=`` is opaque value data. A known variable name
- embedded in that value must never be reinterpreted as another assignment;
- concatenated assignments are ambiguous and therefore remain on one line.
+ Content after the first ``=`` is opaque value data. A known variable name embedded in that value
+ must never be reinterpreted as another assignment; concatenated assignments are ambiguous and
+ therefore remain on one line.
"""
sanitized: list[str] = []
for line in lines:
@@ -4550,17 +3714,14 @@ def _sanitize_env_lines(lines: list) -> list:
def sanitize_env_file() -> int:
"""Read, sanitize, and rewrite ~/.hermes/.env in place.
- Returns the number of lines whose safe formatting was normalized. Returns
- 0 when no changes are needed.
+ Returns the number of lines whose safe formatting was normalized. Returns 0 when no changes are
+ needed.
"""
env_path = get_env_path()
if not env_path.exists():
return 0
- read_kw = {"encoding": "utf-8-sig", "errors": "replace"}
- write_kw = {"encoding": "utf-8"}
-
- with open(env_path, **read_kw) as f:
+ with open(env_path, encoding="utf-8-sig", errors="replace") as f:
original_lines = f.readlines()
sanitized = _sanitize_env_lines(original_lines)
@@ -4569,15 +3730,41 @@ def sanitize_env_file() -> int:
return 0
# Count lines whose normalized representation differs.
- fixes = abs(len(sanitized) - len(original_lines))
- if fixes == 0:
- fixes = sum(1 for a, b in zip(original_lines, sanitized) if a != b)
- fixes += abs(len(sanitized) - len(original_lines))
+ fixes = abs(len(sanitized) - len(original_lines)) or sum(
+ 1 for a, b in zip(original_lines, sanitized) if a != b
+ )
+
+ _write_env_lines(env_path, sanitized, preserve_mode=False)
+ invalidate_env_cache()
+ return fixes
+
+
+def _read_env_lines(env_path: Path) -> list:
+ """Read ``.env`` lines with the Windows-safe encoding and normalized line formatting."""
+ # On Windows, open() defaults to the system locale (cp1252) which can
+ # fail on UTF-8 .env files. Always use explicit UTF-8; tolerate BOM
+ # via utf-8-sig since users may edit .env in Notepad which adds one.
+ with open(env_path, encoding="utf-8-sig", errors="replace") as f:
+ lines = f.readlines()
+ return _sanitize_env_lines(lines)
+
+
+def _write_env_lines(env_path: Path, lines: list, *, preserve_mode: bool) -> None:
+ """Atomically replace ``.env`` with *lines* (tmp file + fsync + rename).
+ ``preserve_mode`` keeps the original file mode (e.g. 0640 for Docker volume mounts) instead of
+ letting ``_secure_file`` unconditionally tighten to 0600; a new file is always secured.
+ """
+ original_mode = None
+ if preserve_mode:
+ try:
+ original_mode = stat.S_IMODE(env_path.stat().st_mode)
+ except OSError:
+ pass
fd, tmp_path = tempfile.mkstemp(dir=str(env_path.parent), suffix=".tmp", prefix=".env_")
try:
- with os.fdopen(fd, "w", **write_kw) as f:
- f.writelines(sanitized)
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
+ f.writelines(lines)
f.flush()
os.fsync(f.fileno())
atomic_replace(tmp_path, env_path)
@@ -4587,35 +3774,28 @@ def sanitize_env_file() -> int:
except OSError:
pass
raise
- _secure_file(env_path)
- invalidate_env_cache()
- return fixes
+ if original_mode is not None:
+ try:
+ os.chmod(env_path, original_mode)
+ except OSError:
+ pass
+ else:
+ _secure_file(env_path)
def _check_non_ascii_credential(key: str, value: str) -> str:
"""Warn and strip non-ASCII characters from credential values.
- API keys and tokens must be pure ASCII — they are sent as HTTP header
- values which httpx/httpcore encode as ASCII. Non-ASCII characters
- (commonly introduced by copy-pasting from rich-text editors or PDFs
- that substitute lookalike Unicode glyphs for ASCII letters) cause
- ``UnicodeEncodeError: 'ascii' codec can't encode character`` at
- request time.
+ API keys and tokens must be pure ASCII — they are sent as HTTP header values which
+ httpx/httpcore encode as ASCII.
- Returns the sanitized (ASCII-only) value. Prints a warning if any
- non-ASCII characters were found and removed.
+ Returns the sanitized (ASCII-only) value. Prints a warning if any non-ASCII characters were
+ found and removed.
"""
- try:
- value.encode("ascii")
- return value # all ASCII — nothing to do
- except UnicodeEncodeError:
- pass
+ if value.isascii():
+ return value
- # Build a readable list of the offending characters
- bad_chars: list[str] = []
- for i, ch in enumerate(value):
- if ord(ch) > 127:
- bad_chars.append(f" position {i}: {ch!r} (U+{ord(ch):04X})")
+ bad_chars = [f" position {i}: {ch!r} (U+{ord(ch):04X})" for i, ch in enumerate(value) if ord(ch) > 127]
sanitized = value.encode("ascii", errors="ignore").decode("ascii")
print(
@@ -4661,10 +3841,9 @@ def _env_line_defines_key(
) -> bool:
"""True when a .env line assigns ``key`` — plain or ``export``-prefixed.
- ``load_env()`` accepts the bash-compatible ``export KEY=value`` form
- (#6659), so the writers must recognise the same shape. Otherwise a
- hand-added ``export`` line is invisible to save (duplicate appended) and
- remove (line survives → the value resurrects on the next load, #40041).
+ ``load_env()`` accepts the bash-compatible ``export KEY=value`` form (#6659), so the writers
+ must recognise the same shape. Otherwise a hand-added ``export`` line is invisible to save
+ (duplicate appended) and remove (line survives → the value resurrects on the next load, #40041).
"""
stripped = line.strip()
if stripped.startswith("export "):
@@ -4685,15 +3864,10 @@ def _env_line_defines_key(
def _publish_env_value(key: str, value: Optional[str]) -> None:
"""Publish a just-persisted ``.env`` change to the live process.
- ``save_env_value`` / ``remove_env_value`` already target the right file
- (``get_env_path()`` honors the profile-home override), but the in-process
- mirror historically went straight to ``os.environ``. Under a multiplexed
- gateway a routed profile's write (e.g. a ``/pair`` grant mirrored into
- ``DISCORD_ALLOWED_USERS``) would then land in the SHARED process env and
- be visible to every other profile (#88441, #77490). In that case update
- the installed scope mapping instead so same-turn reads see the change,
- and leave ``os.environ`` alone. Every other caller keeps the legacy
- ``os.environ`` publish.
+ Under a multiplexed gateway a routed profile's write (e.g. a ``/pair`` grant mirrored into
+ ``DISCORD_ALLOWED_USERS``) must not land in the SHARED ``os.environ`` where every profile
+ sees it; the installed scope mapping is updated instead so same-turn reads see the change.
+ All other callers keep the legacy ``os.environ`` publish.
"""
try:
from agent.secret_scope import current_secret_scope, is_multiplex_active
@@ -4714,23 +3888,32 @@ def _publish_env_value(key: str, value: Optional[str]) -> None:
os.environ[key] = value
-def save_env_value(key: str, value: str):
- """Save or update a value in ~/.hermes/.env."""
+def _env_write_blocked(key: str, action: str) -> bool:
+ """Shared write-lock check for ``.env`` writers; prints the refusal and returns True when blocked.
+
+ Two distinct locks: ``is_managed()`` (package-manager install) and the managed *scope*
+ (administrator-pinned env key — the managed .env wins at load anyway).
+ """
if is_managed():
- managed_error(f"set {key}")
- return
- # Managed scope guard: a managed env key can't be set by the user — the
- # managed .env wins at load anyway. Distinct from is_managed() above.
+ managed_error(f"{action} {key}")
+ return True
from hermes_cli import managed_scope
if managed_scope.is_env_managed(key):
managed_dir = managed_scope.get_managed_dir()
src = (managed_dir / ".env") if managed_dir else "the managed scope"
print(
- f"Cannot set {key}: it is managed by your administrator ({src}) "
+ f"Cannot {action} {key}: it is managed by your administrator ({src}) "
f"and cannot be changed.",
file=sys.stderr,
)
+ return True
+ return False
+
+
+def save_env_value(key: str, value: str):
+ """Save or update a value in ~/.hermes/.env."""
+ if _env_write_blocked(key, "set"):
return
validate_env_var_name_for_write(key)
value = value.replace("\n", "").replace("\r", "")
@@ -4739,17 +3922,7 @@ def save_env_value(key: str, value: str):
ensure_hermes_home()
env_path = get_env_path()
- # On Windows, open() defaults to the system locale (cp1252) which can
- # cause OSError errno 22 on UTF-8 .env files.
- read_kw = {"encoding": "utf-8-sig", "errors": "replace"}
- write_kw = {"encoding": "utf-8"}
-
- lines = []
- if env_path.exists():
- with open(env_path, **read_kw) as f:
- lines = f.readlines()
- # Normalize safe line formatting without interpreting values as syntax.
- lines = _sanitize_env_lines(lines)
+ lines = _read_env_lines(env_path) if env_path.exists() else []
serialized_value = _quote_env_value(value)
@@ -4771,37 +3944,8 @@ def save_env_value(key: str, value: str):
if lines and not lines[-1].endswith("\n"):
lines[-1] += "\n"
lines.append(f"{key}={serialized_value}\n")
-
- fd, tmp_path = tempfile.mkstemp(dir=str(env_path.parent), suffix='.tmp', prefix='.env_')
- # Preserve original permissions so Docker volume mounts aren't clobbered.
- original_mode = None
- if env_path.exists():
- try:
- original_mode = stat.S_IMODE(env_path.stat().st_mode)
- except OSError:
- pass
- try:
- with os.fdopen(fd, 'w', **write_kw) as f:
- f.writelines(lines)
- f.flush()
- os.fsync(f.fileno())
- atomic_replace(tmp_path, env_path)
- # Preserve the original file mode (e.g. 0640 for Docker volume mounts)
- # instead of letting _secure_file unconditionally tighten to 0600.
- if original_mode is not None:
- try:
- os.chmod(env_path, original_mode)
- except OSError:
- pass
- else:
- _secure_file(env_path)
- except BaseException:
- try:
- os.unlink(tmp_path)
- except OSError:
- pass
- raise
+ _write_env_lines(env_path, lines, preserve_mode=env_path.exists())
_publish_env_value(key, value)
invalidate_env_cache()
@@ -4809,17 +3953,10 @@ def save_env_value(key: str, value: str):
def custom_endpoint_key_env(identity: str) -> str:
"""Env var name holding a custom endpoint's API key.
- ``identity`` is whatever names the endpoint on the calling path — the
- Desktop panel's endpoint id, or ``host:port`` for the CLI setup flow.
- Two properties matter:
-
- - It keys off the endpoint's own identity, not just its hostname, so two
- endpoints on one host (``127.0.0.1:8000`` and ``:8001``) get separate
- slots instead of the second save clobbering the first's credential.
- - The fixed ``HERMES_CUSTOM_`` prefix keeps the result a valid POSIX name
- even when the slug starts with a digit, which every IP-based local
- endpoint does (``127.0.0.1`` → ``127_0_0_1``). ``save_env_value``
- rejects digit-leading names outright.
+ ``identity`` is the endpoint's own id (Desktop endpoint id, or ``host:port`` for CLI setup),
+ not just its hostname, so two endpoints on one host get separate slots. The fixed
+ ``HERMES_CUSTOM_`` prefix keeps the name POSIX-valid when the slug starts with a digit (every
+ IP-based endpoint does) -- ``save_env_value`` rejects digit-leading names.
"""
slug = re.sub(r"[^A-Z0-9]+", "_", str(identity or "").upper()).strip("_")
return f"HERMES_CUSTOM_{slug}_API_KEY" if slug else "HERMES_CUSTOM_API_KEY"
@@ -4830,20 +3967,7 @@ def remove_env_value(key: str) -> bool:
Returns True if the key was found and removed, False otherwise.
"""
- if is_managed():
- managed_error(f"remove {key}")
- return False
- # Managed scope guard: a managed env key can't be removed by the user.
- from hermes_cli import managed_scope
-
- if managed_scope.is_env_managed(key):
- managed_dir = managed_scope.get_managed_dir()
- src = (managed_dir / ".env") if managed_dir else "the managed scope"
- print(
- f"Cannot remove {key}: it is managed by your administrator ({src}) "
- f"and cannot be changed.",
- file=sys.stderr,
- )
+ if _env_write_blocked(key, "remove"):
return False
if not _ENV_VAR_NAME_RE.match(key):
raise ValueError(f"Invalid environment variable name: {key!r}")
@@ -4852,71 +3976,38 @@ def remove_env_value(key: str) -> bool:
_publish_env_value(key, None)
return False
- read_kw = {"encoding": "utf-8-sig", "errors": "replace"}
- write_kw = {"encoding": "utf-8"}
-
- with open(env_path, **read_kw) as f:
- lines = f.readlines()
- lines = _sanitize_env_lines(lines)
-
+ lines = _read_env_lines(env_path)
new_lines = [line for line in lines if not _env_line_defines_key(line, key)]
found = len(new_lines) < len(lines)
-
if found:
- fd, tmp_path = tempfile.mkstemp(dir=str(env_path.parent), suffix='.tmp', prefix='.env_')
- # Preserve original permissions so Docker volume mounts aren't clobbered.
- original_mode = None
- try:
- original_mode = stat.S_IMODE(env_path.stat().st_mode)
- except OSError:
- pass
- try:
- with os.fdopen(fd, 'w', **write_kw) as f:
- f.writelines(new_lines)
- f.flush()
- os.fsync(f.fileno())
- atomic_replace(tmp_path, env_path)
- # Preserve the original file mode (e.g. 0640 for Docker volume
- # mounts) instead of letting _secure_file unconditionally tighten
- # to 0600. Mirrors save_env_value().
- if original_mode is not None:
- try:
- os.chmod(env_path, original_mode)
- except OSError:
- pass
- else:
- _secure_file(env_path)
- except BaseException:
- try:
- os.unlink(tmp_path)
- except OSError:
- pass
- raise
+ _write_env_lines(env_path, new_lines, preserve_mode=True)
_publish_env_value(key, None)
invalidate_env_cache()
return found
+def _write_anthropic_slots(token: str, api_key: str, save_fn=None, *, token_first: bool = True):
+ """Write both Anthropic credential slots (one holds the value, the other is cleared)."""
+ writer = save_fn or save_env_value
+ order = (("ANTHROPIC_TOKEN", token), ("ANTHROPIC_API_KEY", api_key))
+ for name, value in order if token_first else reversed(order):
+ writer(name, value)
+
+
def save_anthropic_oauth_token(value: str, save_fn=None):
"""Persist an Anthropic OAuth/setup token and clear the API-key slot."""
- writer = save_fn or save_env_value
- writer("ANTHROPIC_TOKEN", value)
- writer("ANTHROPIC_API_KEY", "")
+ _write_anthropic_slots(value, "", save_fn)
def use_anthropic_claude_code_credentials(save_fn=None):
"""Use Claude Code's own credential files instead of persisting env tokens."""
- writer = save_fn or save_env_value
- writer("ANTHROPIC_TOKEN", "")
- writer("ANTHROPIC_API_KEY", "")
+ _write_anthropic_slots("", "", save_fn)
def save_anthropic_api_key(value: str, save_fn=None):
"""Persist an Anthropic API key and clear the OAuth/setup-token slot."""
- writer = save_fn or save_env_value
- writer("ANTHROPIC_API_KEY", value)
- writer("ANTHROPIC_TOKEN", "")
+ _write_anthropic_slots("", value, save_fn, token_first=False)
def save_env_value_secure(key: str, value: str) -> Dict[str, Any]:
@@ -4933,13 +4024,12 @@ def save_env_value_secure(key: str, value: str) -> Dict[str, Any]:
}
-
def reload_env() -> int:
"""Re-read ~/.hermes/.env into os.environ. Returns count of vars updated.
- Adds/updates vars that changed and removes vars that were deleted from
- the .env file (but only vars known to Hermes — OPTIONAL_ENV_VARS and
- _EXTRA_ENV_KEYS — to avoid clobbering unrelated environment).
+ Adds/updates vars that changed and removes vars that were deleted from the .env file (but only
+ vars known to Hermes — OPTIONAL_ENV_VARS and _EXTRA_ENV_KEYS — to avoid clobbering unrelated
+ environment).
"""
env_vars = load_env()
known_keys = set(OPTIONAL_ENV_VARS.keys()) | _EXTRA_ENV_KEYS
@@ -4956,18 +4046,12 @@ def reload_env() -> int:
return count
-def get_env_value(key: str) -> Optional[str]:
- """Get a value from ``os.environ`` or ``~/.hermes/.env``, scope-aware.
+def _scoped_environ_get(key: str) -> Optional[str]:
+ """Read ``key`` from ``os.environ`` through ``agent.secret_scope.get_secret``.
- The ``os.environ`` read routes through ``agent.secret_scope.get_secret``
- so that, under an active profile scope (multiplexed gateway turn), this
- is scope-checked rather than leaking another profile's raw ``os.environ``
- value. ``get_secret`` encodes the whole policy: global vars pass through;
- scope is authoritative under multiplexing (miss -> None, no environ
- fallthrough); when multiplexing is off it behaves exactly like the
- legacy ``os.environ`` read. Its siblings ``get_env_value_prefer_dotenv``
- and ``gateway.config._getenv`` already work this way — this was the last
- scope-blind reader of the trio (#67027).
+ Under an active profile scope (multiplexed gateway turn) the read is scope-checked rather than
+ leaking another profile's raw ``os.environ`` value. Falls back to a plain environ read when the
+ scope module is unavailable or fails; ``UnscopedSecretError`` propagates.
"""
try:
from agent.secret_scope import (
@@ -4975,56 +4059,44 @@ def get_env_value(key: str) -> Optional[str]:
get_secret as _get_secret,
)
except Exception:
- if key in os.environ:
- return os.environ[key]
- return load_env().get(key)
+ return os.environ.get(key)
try:
- val = _get_secret(key)
+ return _get_secret(key)
except UnscopedSecretError:
raise
except Exception:
- val = os.environ.get(key)
+ return os.environ.get(key)
+
+
+def get_env_value(key: str) -> Optional[str]:
+ """Get a value from ``os.environ`` or ``~/.hermes/.env``, scope-aware.
+
+ The ``os.environ`` read routes through ``agent.secret_scope.get_secret`` so that, under an
+ active profile scope (multiplexed gateway turn), this is scope-checked rather than leaking
+ another profile's raw ``os.environ`` value.
+ """
+ val = _scoped_environ_get(key)
if val is not None:
return val
-
- # Then check .env file
- env_vars = load_env()
- return env_vars.get(key)
+ return load_env().get(key)
def get_env_value_prefer_dotenv(key: str) -> Optional[str]:
"""Resolve a credential env value, preferring ``~/.hermes/.env`` over ``os.environ``.
- Used for Hermes-managed credentials where a deliberate edit to ``.env``
- must take precedence over a stale value inherited from the parent shell
- (Codex CLI, test scripts, login profile exports). Without this, rotating
- a key in ``.env`` mid-session leaves callers serving the stale shell
- value and produces persistent 401s.
+ Used for Hermes-managed credentials where a deliberate edit to ``.env`` must take precedence
+ over a stale value inherited from the parent shell (Codex CLI, test scripts, login profile
+ exports).
- The ``os.environ`` fallback routes through ``secret_scope.get_secret`` so
- that, under an active profile scope (multiplexed gateway turn), this read
- is scope-checked rather than leaking another profile's raw ``os.environ``
- value — matching the credential-pool seeding path's behaviour.
+ The ``os.environ`` fallback routes through ``secret_scope.get_secret`` so that, under an active
+ profile scope (multiplexed gateway turn), this read is scope-checked rather than leaking another
+ profile's raw ``os.environ`` value — matching the credential-pool seeding path's behaviour.
"""
- env_vars = load_env()
- val = env_vars.get(key)
+ val = load_env().get(key)
if val:
return val
- try:
- from agent.secret_scope import (
- UnscopedSecretError,
- get_secret as _get_secret,
- )
- except Exception:
- return os.environ.get(key)
-
- try:
- return _get_secret(key)
- except UnscopedSecretError:
- raise
- except Exception:
- return os.environ.get(key)
+ return _scoped_environ_get(key)
# =============================================================================
@@ -5032,11 +4104,7 @@ def get_env_value_prefer_dotenv(key: str) -> Optional[str]:
# =============================================================================
def redact_key(key: str) -> str:
- """Redact an API key for display.
-
- Thin wrapper over :func:`agent.redact.mask_secret` — preserves the
- "(not set)" placeholder in dim color for the empty case.
- """
+ """Redact an API key for display."""
from agent.redact import mask_secret
return mask_secret(key, empty=color("(not set)", Colors.DIM))
@@ -5047,35 +4115,19 @@ def redact_key(key: str) -> str:
# (`api_key`) plus the usual token/secret/password shapes. Exact-match only so
# benign keys like `token_count` or `secret_santa` don't get masked.
_SECRET_CONFIG_KEYS = frozenset({
- "api_key",
- "apikey",
- "key",
- "token",
- "access_token",
- "refresh_token",
- "id_token",
- "secret",
- "client_secret",
- "password",
- "passwd",
- "auth",
- "authorization",
- "private_key",
- "bearer",
- "jwt",
+ "api_key", "apikey", "key", "token", "access_token", "refresh_token", "id_token",
+ "secret", "client_secret", "password", "passwd", "auth", "authorization",
+ "private_key", "bearer", "jwt",
})
def redact_config_value(value: Any, _depth: int = 0) -> Any:
"""Return a copy of ``value`` with credential-shaped keys masked for display.
- Recursively walks dicts/lists and replaces the value of any key in
- ``_SECRET_CONFIG_KEYS`` (case-insensitive) with a masked form via
- :func:`agent.redact.mask_secret`. Non-secret keys and scalar values pass
- through unchanged. Use this before ``print``-ing any config sub-tree that
- might carry a custom-provider ``api_key`` — ``print`` bypasses the logging
- redactor, and opaque tokens (e.g. Cloudflare ``cfut_...``) don't match the
- vendor-prefix regexes either, so structural key-name masking is required.
+ Recursively masks values of keys in ``_SECRET_CONFIG_KEYS`` (case-insensitive). Use before
+ ``print``-ing any config sub-tree that may carry an ``api_key``: ``print`` bypasses the logging
+ redactor, and opaque tokens (e.g. Cloudflare ``cfut_...``) miss the vendor-prefix regexes, so
+ structural key-name masking is required.
"""
from agent.redact import mask_secret
@@ -5095,215 +4147,168 @@ def redact_config_value(value: Any, _depth: int = 0) -> Any:
return value
-def show_config():
- """Display current configuration."""
- config = load_config()
-
+def _section(title: str) -> None:
print()
- print(color("┌─────────────────────────────────────────────────────────┐", Colors.CYAN))
- print(color("│ ⚕ Hermes Configuration │", Colors.CYAN))
- print(color("└─────────────────────────────────────────────────────────┘", Colors.CYAN))
+ print(color(f"◆ {title}", Colors.CYAN, Colors.BOLD))
+
+def _show_managed_banner() -> None:
# Managed scope: surface that some settings are administrator-pinned so the
# user understands why their config.yaml value may not be the effective one.
from hermes_cli import managed_scope
- _managed_keys = managed_scope.managed_config_keys()
- _managed_env = managed_scope.load_managed_env()
- if _managed_keys or _managed_env:
- _managed_dir = managed_scope.get_managed_dir()
- print()
- print(color(
- f" ⚷ Some settings are managed by your administrator ({_managed_dir}) "
- f"and cannot be changed",
- Colors.YELLOW,
- Colors.BOLD,
- ))
- if _managed_keys:
- print(color(
- f" Managed config keys: {', '.join(sorted(_managed_keys))}",
- Colors.YELLOW,
- ))
- if _managed_env:
- print(color(
- f" Managed env keys: {', '.join(sorted(_managed_env))}",
- Colors.YELLOW,
- ))
-
- # Paths
- print()
- print(color("◆ Paths", Colors.CYAN, Colors.BOLD))
- print(f" Config: {get_config_path()}")
- print(f" Secrets: {get_env_path()}")
- print(f" Install: {get_project_root()}")
-
- # API Keys
- print()
- print(color("◆ API Keys", Colors.CYAN, Colors.BOLD))
-
- keys = [
- ("OPENROUTER_API_KEY", "OpenRouter"),
- ("VOICE_TOOLS_OPENAI_KEY", "OpenAI (STT/TTS)"),
- ("EXA_API_KEY", "Exa"),
- ("PARALLEL_API_KEY", "Parallel"),
- ("FIRECRAWL_API_KEY", "Firecrawl"),
- ("TAVILY_API_KEY", "Tavily"),
- ("BROWSERBASE_API_KEY", "Browserbase"),
- ("BROWSER_USE_API_KEY", "Browser Use"),
- ("FAL_KEY", "FAL"),
- ]
-
- for env_key, name in keys:
- value = get_env_value(env_key)
- print(f" {name:<14} {redact_key(value)}")
- from hermes_cli.auth import get_anthropic_key
- anthropic_value = get_anthropic_key()
- print(f" {'Anthropic':<14} {redact_key(anthropic_value)}")
-
- # Model settings
+ managed_keys = managed_scope.managed_config_keys()
+ managed_env = managed_scope.load_managed_env()
+ if not managed_keys and not managed_env:
+ return
print()
- print(color("◆ Model", Colors.CYAN, Colors.BOLD))
+ print(color(
+ f" ⚷ Some settings are managed by your administrator ({managed_scope.get_managed_dir()}) "
+ f"and cannot be changed",
+ Colors.YELLOW,
+ Colors.BOLD,
+ ))
+ for label, keys in (("config", managed_keys), ("env", managed_env)):
+ if keys:
+ print(color(f" Managed {label} keys: {', '.join(sorted(keys))}", Colors.YELLOW))
+
+
+_SHOW_CONFIG_API_KEYS = (
+ ("OPENROUTER_API_KEY", "OpenRouter"),
+ ("VOICE_TOOLS_OPENAI_KEY", "OpenAI (STT/TTS)"),
+ ("EXA_API_KEY", "Exa"),
+ ("PARALLEL_API_KEY", "Parallel"),
+ ("FIRECRAWL_API_KEY", "Firecrawl"),
+ ("TAVILY_API_KEY", "Tavily"),
+ ("BROWSERBASE_API_KEY", "Browserbase"),
+ ("BROWSER_USE_API_KEY", "Browser Use"),
+ ("FAL_KEY", "FAL"),
+)
+
+
+def _show_model_section(config: Dict[str, Any]) -> None:
+ _section("Model")
print(f" Model: {redact_config_value(config.get('model', 'not set'))}")
- _cfg_max_turns = config.get('agent', {}).get('max_turns', DEFAULT_CONFIG['agent']['max_turns'])
- print(f" Max turns: {_cfg_max_turns}")
- # Warn on stale HERMES_MAX_ITERATIONS ghost in .env that disagrees with
- # config.yaml (issue #17534). Read the .env FILE directly so we catch the
- # ghost even when the gateway bridge already overrode os.environ.
+ cfg_max_turns = config.get('agent', {}).get('max_turns', DEFAULT_CONFIG['agent']['max_turns'])
+ print(f" Max turns: {cfg_max_turns}")
+ # Warn on a stale HERMES_MAX_ITERATIONS ghost in .env that disagrees with
+ # config.yaml. Read the .env FILE directly so we catch the ghost even when
+ # the gateway bridge already overrode os.environ.
try:
- _env_ghost = load_env().get("HERMES_MAX_ITERATIONS")
- if _env_ghost is not None and str(_env_ghost).strip() != str(_cfg_max_turns).strip():
+ env_ghost = load_env().get("HERMES_MAX_ITERATIONS")
+ if env_ghost is not None and str(env_ghost).strip() != str(cfg_max_turns).strip():
print(color(
- f" ⚠ .env has stale HERMES_MAX_ITERATIONS={_env_ghost} "
+ f" ⚠ .env has stale HERMES_MAX_ITERATIONS={env_ghost} "
f"(run 'hermes doctor --fix' to remove)",
Colors.YELLOW,
))
except Exception:
pass
-
- # Display
- print()
- print(color("◆ Display", Colors.CYAN, Colors.BOLD))
+
+
+def _show_display_section(config: Dict[str, Any]) -> None:
+ _section("Display")
display = config.get('display', {})
try:
from hermes_cli.personality import active_personality_name
- _active_personality = active_personality_name(config) or 'none'
+ active_personality = active_personality_name(config) or 'none'
except Exception:
- _active_personality = display.get('personality') or 'none'
- print(f" Personality: {_active_personality}")
- print(f" Reasoning: {'on' if display.get('show_reasoning', True) else 'off'}")
+ active_personality = display.get('personality') or 'none'
+ on_off = lambda flag: 'on' if flag else 'off' # noqa: E731
+ print(f" Personality: {active_personality}")
+ print(f" Reasoning: {on_off(display.get('show_reasoning', True))}")
print(
- f" Bell: complete={'on' if display.get('bell_on_complete', False) else 'off'}, "
- f"prompt={'on' if display.get('bell_on_prompt', False) else 'off'}"
+ f" Bell: complete={on_off(display.get('bell_on_complete', False))}, "
+ f"prompt={on_off(display.get('bell_on_prompt', False))}"
)
- ump = display.get('user_message_preview', {}) if isinstance(display.get('user_message_preview', {}), dict) else {}
- ump_first = ump.get('first_lines', 2)
- ump_last = ump.get('last_lines', 2)
- print(f" User preview: first {ump_first} line(s), last {ump_last} line(s)")
+ ump = display.get('user_message_preview', {})
+ ump = ump if isinstance(ump, dict) else {}
+ print(f" User preview: first {ump.get('first_lines', 2)} line(s), last {ump.get('last_lines', 2)} line(s)")
- # Terminal
- print()
- print(color("◆ Terminal", Colors.CYAN, Colors.BOLD))
+
+def _show_terminal_section(config: Dict[str, Any]) -> None:
+ _section("Terminal")
terminal = config.get('terminal', {})
print(f" Backend: {terminal.get('backend', 'local')}")
print(f" Working dir: {terminal.get('cwd', '.')}")
print(f" Timeout: {terminal.get('timeout', 60)}s")
-
- if terminal.get('backend') == 'docker':
- print(f" Docker image: {terminal.get('docker_image', 'nikolaik/python-nodejs:python3.11-nodejs20')}")
- elif terminal.get('backend') == 'singularity':
- print(f" Image: {terminal.get('singularity_image', 'docker://nikolaik/python-nodejs:python3.11-nodejs20')}")
- elif terminal.get('backend') == 'modal':
- print(f" Modal image: {terminal.get('modal_image', 'nikolaik/python-nodejs:python3.11-nodejs20')}")
- modal_token = get_env_value('MODAL_TOKEN_ID')
- print(f" Modal token: {'configured' if modal_token else '(not set)'}")
- elif terminal.get('backend') == 'daytona':
- print(f" Daytona image: {terminal.get('daytona_image', 'nikolaik/python-nodejs:python3.11-nodejs20')}")
- daytona_key = get_env_value('DAYTONA_API_KEY')
- print(f" API key: {'configured' if daytona_key else '(not set)'}")
- elif terminal.get('backend') == 'vercel_sandbox':
- print(f" Vercel runtime: {terminal.get('vercel_runtime', 'node24')}")
- print(f" Vercel auth: {'configured' if get_env_value('VERCEL_OIDC_TOKEN') or (get_env_value('VERCEL_TOKEN') and get_env_value('VERCEL_PROJECT_ID') and get_env_value('VERCEL_TEAM_ID')) else '(not set)'}")
- elif terminal.get('backend') == 'ssh':
- ssh_host = get_env_value('TERMINAL_SSH_HOST')
- ssh_user = get_env_value('TERMINAL_SSH_USER')
- print(f" SSH host: {ssh_host or '(not set)'}")
- print(f" SSH user: {ssh_user or '(not set)'}")
-
- # Timezone
- print()
- print(color("◆ Timezone", Colors.CYAN, Colors.BOLD))
- tz = config.get('timezone', '')
- if tz:
- print(f" Timezone: {tz}")
- else:
- print(f" Timezone: {color('(server-local)', Colors.DIM)}")
- # Compression
- print()
- print(color("◆ Context Compression", Colors.CYAN, Colors.BOLD))
+ configured = lambda *names: 'configured' if all(get_env_value(n) for n in names) else '(not set)' # noqa: E731
+ default_img = 'nikolaik/python-nodejs:python3.11-nodejs20'
+ backend_lines = {
+ 'docker': lambda: [f" Docker image: {terminal.get('docker_image', default_img)}"],
+ 'singularity': lambda: [f" Image: {terminal.get('singularity_image', 'docker://' + default_img)}"],
+ 'modal': lambda: [
+ f" Modal image: {terminal.get('modal_image', default_img)}",
+ f" Modal token: {configured('MODAL_TOKEN_ID')}",
+ ],
+ 'daytona': lambda: [
+ f" Daytona image: {terminal.get('daytona_image', default_img)}",
+ f" API key: {configured('DAYTONA_API_KEY')}",
+ ],
+ 'vercel_sandbox': lambda: [
+ f" Vercel runtime: {terminal.get('vercel_runtime', 'node24')}",
+ f" Vercel auth: {'configured' if get_env_value('VERCEL_OIDC_TOKEN') or (get_env_value('VERCEL_TOKEN') and get_env_value('VERCEL_PROJECT_ID') and get_env_value('VERCEL_TEAM_ID')) else '(not set)'}",
+ ],
+ 'ssh': lambda: [
+ f" SSH host: {get_env_value('TERMINAL_SSH_HOST') or '(not set)'}",
+ f" SSH user: {get_env_value('TERMINAL_SSH_USER') or '(not set)'}",
+ ],
+ }
+ for line in backend_lines.get(terminal.get('backend'), list)():
+ print(line)
+
+
+def _show_compression_section(config: Dict[str, Any]) -> None:
+ _section("Context Compression")
compression = config.get('compression', {})
enabled = compression.get('enabled', True)
print(f" Enabled: {'yes' if enabled else 'no'}")
- if enabled:
- print(f" Threshold: {compression.get('threshold', 0.50) * 100:.0f}%")
- _tt = compression.get('threshold_tokens')
- if _tt is not None:
- try:
- _tt = int(_tt)
- if _tt > 0:
- print(f" Token cap: {_tt:,} tokens (takes lower of ratio vs absolute)")
- except (TypeError, ValueError):
- pass
- print(f" Target ratio: {compression.get('target_ratio', 0.20) * 100:.0f}% of threshold preserved")
- print(f" Protect last: {compression.get('protect_last_n', 20)} messages")
- print(f" Protect first: {compression.get('protect_first_n', 3)} non-system head messages")
- _aux_comp = config.get('auxiliary', {}).get('compression', {})
- _sm = _aux_comp.get('model', '') or '(auto)'
- print(f" Model: {_sm}")
- comp_provider = _aux_comp.get('provider', 'auto')
- if comp_provider and comp_provider != 'auto':
- print(f" Provider: {comp_provider}")
-
- # Auxiliary models
+ if not enabled:
+ return
+ print(f" Threshold: {compression.get('threshold', 0.50) * 100:.0f}%")
+ tt = compression.get('threshold_tokens')
+ if tt is not None:
+ try:
+ tt = int(tt)
+ if tt > 0:
+ print(f" Token cap: {tt:,} tokens (takes lower of ratio vs absolute)")
+ except (TypeError, ValueError):
+ pass
+ print(f" Target ratio: {compression.get('target_ratio', 0.20) * 100:.0f}% of threshold preserved")
+ print(f" Protect last: {compression.get('protect_last_n', 20)} messages")
+ print(f" Protect first: {compression.get('protect_first_n', 3)} non-system head messages")
+ aux_comp = config.get('auxiliary', {}).get('compression', {})
+ print(f" Model: {aux_comp.get('model', '') or '(auto)'}")
+ comp_provider = aux_comp.get('provider', 'auto')
+ if comp_provider and comp_provider != 'auto':
+ print(f" Provider: {comp_provider}")
+
+
+def _show_aux_overrides(config: Dict[str, Any]) -> None:
auxiliary = config.get('auxiliary', {})
- aux_tasks = {
- "Vision": auxiliary.get('vision', {}),
+ aux_tasks = {"Vision": auxiliary.get('vision', {})}
+ overrides = {
+ label: (t.get('provider', 'auto'), t.get('model', ''))
+ for label, t in aux_tasks.items()
+ if t.get('provider', 'auto') != 'auto' or t.get('model', '')
}
- has_overrides = any(
- t.get('provider', 'auto') != 'auto' or t.get('model', '')
- for t in aux_tasks.values()
- )
- if has_overrides:
- print()
- print(color("◆ Auxiliary Models (overrides)", Colors.CYAN, Colors.BOLD))
- for label, task_cfg in aux_tasks.items():
- prov = task_cfg.get('provider', 'auto')
- mdl = task_cfg.get('model', '')
- if prov != 'auto' or mdl:
- parts = [f"provider={prov}"]
- if mdl:
- parts.append(f"model={mdl}")
- print(f" {label:12s} {', '.join(parts)}")
-
- # Messaging
- print()
- print(color("◆ Messaging Platforms", Colors.CYAN, Colors.BOLD))
-
- telegram_token = get_env_value('TELEGRAM_BOT_TOKEN')
- discord_token = get_env_value('DISCORD_BOT_TOKEN')
-
- print(f" Telegram: {'configured' if telegram_token else color('not configured', Colors.DIM)}")
- print(f" Discord: {'configured' if discord_token else color('not configured', Colors.DIM)}")
-
- # Skill config
+ if not overrides:
+ return
+ _section("Auxiliary Models (overrides)")
+ for label, (prov, mdl) in overrides.items():
+ parts = [f"provider={prov}"] + ([f"model={mdl}"] if mdl else [])
+ print(f" {label:12s} {', '.join(parts)}")
+
+
+def _show_skill_settings() -> None:
try:
from agent.skill_utils import discover_all_skill_config_vars, resolve_skill_config_values
skill_vars = discover_all_skill_config_vars()
if skill_vars:
resolved = resolve_skill_config_values(skill_vars)
- print()
- print(color("◆ Skill Settings", Colors.CYAN, Colors.BOLD))
+ _section("Skill Settings")
for var in skill_vars:
key = var["key"]
value = resolved.get(key, "")
@@ -5313,13 +4318,53 @@ def show_config():
except Exception:
pass
- print()
- print(color("─" * 60, Colors.DIM))
- print(color(" hermes config edit # Edit config file", Colors.DIM))
- print(color(" hermes config set <key> <value>", Colors.DIM))
- print(color(" hermes setup # Run setup wizard", Colors.DIM))
- print()
-
+
+def show_config():
+ """Display current configuration."""
+ config = load_config()
+
+ print()
+ print(color("┌─────────────────────────────────────────────────────────┐", Colors.CYAN))
+ print(color("│ ⚕ Hermes Configuration │", Colors.CYAN))
+ print(color("└─────────────────────────────────────────────────────────┘", Colors.CYAN))
+ _show_managed_banner()
+
+ _section("Paths")
+ print(f" Config: {get_config_path()}")
+ print(f" Secrets: {get_env_path()}")
+ print(f" Install: {get_project_root()}")
+
+ _section("API Keys")
+ for env_key, name in _SHOW_CONFIG_API_KEYS:
+ print(f" {name:<14} {redact_key(get_env_value(env_key))}")
+ from hermes_cli.auth import get_anthropic_key
+ print(f" {'Anthropic':<14} {redact_key(get_anthropic_key())}")
+
+ _show_model_section(config)
+ _show_display_section(config)
+ _show_terminal_section(config)
+
+ _section("Timezone")
+ tz = config.get('timezone', '')
+ print(f" Timezone: {tz or color('(server-local)', Colors.DIM)}")
+
+ _show_compression_section(config)
+ _show_aux_overrides(config)
+
+ _section("Messaging Platforms")
+ for label, env_key in (("Telegram", "TELEGRAM_BOT_TOKEN"), ("Discord", "DISCORD_BOT_TOKEN")):
+ state = 'configured' if get_env_value(env_key) else color('not configured', Colors.DIM)
+ print(f" {label + ':':<13} {state}")
+
+ _show_skill_settings()
+
+ print()
+ print(color("─" * 60, Colors.DIM))
+ print(color(" hermes config edit # Edit config file", Colors.DIM))
+ print(color(" hermes config set <key> <value>", Colors.DIM))
+ print(color(" hermes setup # Run setup wizard", Colors.DIM))
+ print()
+
def edit_config():
"""Open config file in user's editor."""
@@ -5341,9 +4386,7 @@ def edit_config():
# land on a working editor (notepad) even without Git Bash or nano
# installed. On POSIX, prefer nano/vim over code/notepad because
# it's more likely to be present on headless / server systems.
- import shutil
- import sys as _sys
- if _sys.platform == "win32":
+ if sys.platform == "win32":
candidates = ['notepad', 'code', 'vim', 'vi', 'nano']
else:
candidates = ['nano', 'vim', 'vi', 'code', 'notepad']
@@ -5371,25 +4414,30 @@ def _cron_model_drift_axis_for_config_key(key: str) -> Optional[str]:
return None
-def cron_model_drift_guard_enabled(
- config: Optional[Dict[str, Any]] = None,
-) -> bool:
- """Return whether cron must fail closed on unpinned inference drift.
-
- Only the literal YAML boolean ``false`` disables this spend-safety guard.
- Missing, malformed, or non-boolean values stay fail-closed. When *config*
- is omitted, load the active merged configuration so CLI warnings honor the
- same user/managed setting as the scheduler.
- """
+def _cron_section(config: Optional[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
+ """Return the ``cron`` mapping of *config* (loading the merged config when None), else None."""
if config is None:
try:
config = load_config()
except Exception:
- return True
+ return None
if not isinstance(config, dict):
- return True
+ return None
cron_config = config.get("cron")
- if not isinstance(cron_config, dict):
+ return cron_config if isinstance(cron_config, dict) else None
+
+
+def cron_model_drift_guard_enabled(
+ config: Optional[Dict[str, Any]] = None,
+) -> bool:
+ """Return whether cron must fail closed on unpinned inference drift.
+
+ Only the literal YAML boolean ``false`` disables this spend-safety guard. Missing, malformed, or
+ non-boolean values stay fail-closed. When *config* is omitted, load the active merged
+ configuration so CLI warnings honor the same user/managed setting as the scheduler.
+ """
+ cron_config = _cron_section(config)
+ if cron_config is None:
return True
return cron_config.get("model_drift_guard", True) is not False
@@ -5400,23 +4448,15 @@ def _cron_fleet_default_covers_axis(
) -> bool:
"""True when cron.model / cron.model_provider covers *axis*.
- An axis covered by the explicit cron-fleet default no longer follows the
- global model/provider at fire time, so the drift guard never engages for
- it and switch-time warnings would be false alarms.
+ An axis covered by the explicit cron-fleet default no longer follows the global model/provider
+ at fire time, so the drift guard never engages for it and switch-time warnings would be false
+ alarms.
"""
- if config is None:
- try:
- config = load_config()
- except Exception:
- return False
- if not isinstance(config, dict):
- return False
- cron_config = config.get("cron")
- if not isinstance(cron_config, dict):
+ cron_config = _cron_section(config)
+ if cron_config is None:
return False
key = "model" if axis == "model" else "model_provider"
- value = cron_config.get(key)
- return isinstance(value, str) and bool(value.strip())
+ return bool(_model_assignment_text(cron_config.get(key)))
_CRON_MODEL_IMPACT_JOB_LIMIT = 50
@@ -5436,10 +4476,10 @@ def resolve_cron_model_drift_defaults(
) -> Tuple[str, str]:
"""Resolve the global provider/model values cron compares against snapshots.
- Mirrors the scheduler's global-model precedence: a truthy configured model
- wins ``HERMES_MODEL``; the environment is only a fallback. Per-job and cron
- fleet defaults are handled by the caller/classifier because they suppress a
- drift axis rather than changing the global assignment.
+ Mirrors the scheduler's global-model precedence: a truthy configured model wins
+ ``HERMES_MODEL``; the environment is only a fallback. Per-job and cron fleet defaults are
+ handled by the caller/classifier because they suppress a drift axis rather than changing the
+ global assignment.
"""
env = os.environ if environ is None else environ
provider = ""
@@ -5529,9 +4569,9 @@ def build_cron_model_impact(
) -> Dict[str, Any]:
"""Build a bounded, profile-local summary of jobs blocked by model drift.
- Job-store inspection is deliberately best effort: a model assignment has
- already succeeded by the time Desktop requests this summary, so an unreadable
- store is represented as unavailable instead of failing or rolling back it.
+ Job-store inspection is best effort: the model assignment has already succeeded when Desktop
+ requests this summary, so an unreadable store is reported as unavailable rather than failing
+ or rolling back.
"""
guard_enabled = cron_model_drift_guard_enabled(config)
if jobs is None:
@@ -5588,17 +4628,6 @@ def build_cron_model_impact(
return result
-def _load_cron_jobs_for_config_warning() -> List[Dict[str, Any]]:
- """Best-effort read of the active profile's cron jobs database."""
- try:
- from cron.jobs import load_jobs
-
- jobs = load_jobs()
- return jobs if isinstance(jobs, list) else []
- except Exception:
- return []
-
-
def warn_unpinned_cron_jobs_after_model_config_change(
key: str,
value: Any,
@@ -5616,7 +4645,7 @@ def warn_unpinned_cron_jobs_after_model_config_change(
current_provider=new_value if axis == "provider" else "",
current_model=new_value if axis == "model" else "",
config=config,
- jobs=_load_cron_jobs_for_config_warning(),
+ jobs=None,
)
affected = impact["affected_count"]
if affected <= 0:
@@ -5636,11 +4665,7 @@ def warn_unpinned_cron_jobs_after_model_config_change(
def _default_value_for_key(dotted_key: str):
- """Return the leaf value declared for *dotted_key* in ``DEFAULT_CONFIG``.
-
- Unknown keys and non-leaf paths return ``None`` so they retain the legacy
- best-effort coercion used by ``config set``.
- """
+ """Return the leaf value declared for *dotted_key* in ``DEFAULT_CONFIG``."""
node = DEFAULT_CONFIG
for part in _split_key_path(dotted_key):
if not isinstance(node, dict) or part not in node:
@@ -5655,19 +4680,9 @@ def _default_value_for_key(dotted_key: str):
# without deep checking, so users can set e.g. ``mcp_servers.my-server.command``
# or ``providers.openrouter.api_key`` without us needing to know server names.
_OPEN_DICT_TOP_LEVEL_KEYS = frozenset({
- "providers",
- "credential_pool_strategies",
- "mcp_servers",
- "hooks",
- "quick_commands",
- "personalities",
- "command_allowlist",
- "model_catalog",
- "channel_prompts",
- "server_actions",
- "secrets",
- "goals",
- "loops",
+ "providers", "credential_pool_strategies", "mcp_servers", "hooks", "quick_commands",
+ "personalities", "command_allowlist", "model_catalog", "channel_prompts", "server_actions",
+ "secrets", "goals", "loops",
})
# Top-level keys whose sub-keys are partially schema-defined (e.g. on a
@@ -5695,38 +4710,20 @@ _DYNAMIC_TOP_LEVEL_KEYS = frozenset({
})
# Container keys whose immediate child IS a user-supplied platform name
-# (``platforms.<name>.<field>``). These appear both at the top level and
-# nested under ``gateway`` — current docs configure platforms under
-# ``gateway.platforms.<name>`` (website/docs/developer-guide/
-# adding-platform-adapters.md) and ``gateway/config.py`` also resolves a
-# top-level ``platforms`` map. Anything below the platform-name segment is
-# accepted because ``PlatformConfig`` carries an open ``extra`` mapping.
+# (``platforms.<name>.<field>``), both top-level and under ``gateway``.
+# Anything below the name is accepted (``PlatformConfig`` has an open ``extra``).
_PLATFORM_CONTAINER_KEYS = frozenset({"platforms"})
def _known_top_level_keys() -> set[str]:
- """Return the union of known top-level config keys for validation.
-
- Combines :data:`DEFAULT_CONFIG` with the dynamic categories that
- accept user-supplied child keys. Used by :func:`_validate_config_key`
- to decide whether a ``hermes config set`` invocation is targeting a
- known shape.
- """
- keys = set(DEFAULT_CONFIG.keys())
- keys.update(_OPEN_DICT_TOP_LEVEL_KEYS)
- keys.update(_DYNAMIC_TOP_LEVEL_KEYS)
- keys.update(_SCHEMA_DEFINED_DICT_KEYS)
- return keys
+ """Return the union of known top-level config keys for validation."""
+ return set(DEFAULT_CONFIG) | _OPEN_DICT_TOP_LEVEL_KEYS | _DYNAMIC_TOP_LEVEL_KEYS | _SCHEMA_DEFINED_DICT_KEYS
def _suggest_closest_key(key: str, candidates: set[str], cutoff: float = 0.6) -> Optional[str]:
- """Return the closest valid key name from ``candidates`` if any are
- similar enough to ``key``, else None. Used by ``hermes config set``
- to point users at the right path when they've typo'd a top-level key.
-
- Uses :func:`difflib.get_close_matches` with a conservative cutoff so
- we only suggest when there's a strong match — we'd rather say nothing
- than mislead a user toward a wrong-but-similar key.
+ """Return the closest valid key name from ``candidates`` if any are similar enough to ``key``, else
+ None. Used by ``hermes config set`` to point users at the right path when they've typo'd a
+ top-level key.
"""
import difflib
matches = difflib.get_close_matches(key, sorted(candidates), n=1, cutoff=cutoff)
@@ -5734,22 +4731,10 @@ def _suggest_closest_key(key: str, candidates: set[str], cutoff: float = 0.6) ->
def _validate_config_key(key: str) -> tuple[bool, Optional[str]]:
- """Validate a dotted config-key path against the known schema.
-
- Returns ``(is_known, suggested_alternative_or_None)``. Known keys
- return ``(True, None)``. Unknown keys return ``(False, <suggestion>)``
- where ``<suggestion>`` may be ``None`` if no close match was found.
-
- Validates as deep as DEFAULT_CONFIG can be safely walked, then stops
- at any segment that hits an open-dict container (mcp_servers,
- providers, hooks, etc.) where users define the inner keys themselves.
-
- Headline case from #34067: ``gateway.discord.gateway_restart_notification``
- was silently written, even though ``gateway`` only has 4 known sub-keys
- (``strict``, ``media_delivery_allow_dirs``, ``trust_recent_files``,
- ``trust_recent_files_seconds``). The correct path is
- ``discord.gateway_restart_notification`` (platform configs live at the
- top level, not under a ``platforms`` namespace).
+ """Validate a dotted config-key path against the known schema → ``(is_known, suggestion)``.
+
+ Headline case: ``gateway.discord.gateway_restart_notification`` was silently written even
+ though ``gateway`` has only a handful of known sub-keys.
"""
if not key:
return False, None
@@ -5757,93 +4742,54 @@ def _validate_config_key(key: str) -> tuple[bool, Optional[str]]:
segments = _split_key_path(key)
top = segments[0]
- # ── Underscore-prefixed keys are internal/test markers ───────────
- # A leading underscore on the top-level segment (e.g. ``_test.shim_marker``)
- # signals an intentionally non-schema, internal key. Test harnesses and
- # tooling use these to write a deterministic marker into config.yaml
- # without polluting the user-facing schema (see the Docker privilege-drop
- # shim test, which writes ``_test.shim_marker`` to probe file ownership).
- # Python's own convention treats a leading underscore as "private"; we
- # honour that here so schema validation never blocks deliberately-internal
- # keys. This is narrow: only the FIRST segment is checked, so a real typo
- # like ``agent._max_turns`` still gets caught at the sub-key level.
- if top.startswith("_"):
+ # A leading underscore on the FIRST segment (``_test.shim_marker``) marks an
+ # intentionally non-schema internal key (test harnesses/tooling); only the
+ # first segment is exempt so ``agent._max_turns`` is still caught.
+ # Top-level ``platforms.<name>.<field>`` is a valid shape (gateway/config.py
+ # resolves it alongside ``gateway.platforms``); accept anything below it.
+ if top.startswith("_") or top in _PLATFORM_CONTAINER_KEYS:
return True, None
known = _known_top_level_keys()
-
- # ── First-segment validation ─────────────────────────────────────
- # Top-level ``platforms.<name>.<field>`` is a valid current shape:
- # ``gateway/config.py`` resolves a top-level ``platforms`` map in
- # addition to ``gateway.platforms``. Accept anything below it.
- if top in _PLATFORM_CONTAINER_KEYS:
- return True, None
-
if top not in known:
suggestion = _suggest_closest_key(top, known)
if suggestion is not None:
rest = ".".join(segments[1:])
- suggested_full = f"{suggestion}.{rest}" if rest else suggestion
- return False, suggested_full
-
+ return False, f"{suggestion}.{rest}" if rest else suggestion
return False, None
- # ── Deeper validation ────────────────────────────────────────────
- # Walk DEFAULT_CONFIG along the user's segments. Stop at:
- # - An open-dict container (user-defined inner keys are OK below it)
- # - A schema-defined-but-extensible dict (accept anything below)
- # - A leaf scalar (the user's key is fully consumed and valid)
- # - An unknown sub-key (return False with a same-level suggestion)
+ # Open / dynamic / schema-defined-but-extensible containers: the user
+ # defines the inner shape (mcp_servers.<name>.command, providers.<name>.api_key).
if top in _OPEN_DICT_TOP_LEVEL_KEYS or top in _DYNAMIC_TOP_LEVEL_KEYS or top in _SCHEMA_DEFINED_DICT_KEYS:
- # Any path below these is accepted — the user defines the inner
- # shape themselves (mcp_servers.<name>.command, discord.<extras>,
- # providers.<name>.api_key, etc.).
return True, None
+ # Walk DEFAULT_CONFIG along the segments: a nested ``platforms`` container
+ # or a scalar leaf hit before the path is consumed both accept (the latter
+ # matches set_config_value's leaf→dict replacement); an unknown sub-key
+ # fails with a same-level "did you mean" suggestion.
node: Any = DEFAULT_CONFIG.get(top)
consumed = [top]
for seg in segments[1:]:
- # ``gateway.platforms.<name>.<field>`` (and any other nested
- # ``platforms`` container) — the segment after ``platforms`` is a
- # user-supplied platform name, so accept everything below it.
- if seg in _PLATFORM_CONTAINER_KEYS:
- return True, None
- if not isinstance(node, dict):
- # We hit a scalar leaf before consuming the user's full path —
- # they're trying to set ``foo.bar`` where ``foo`` is a string.
- # Accept it (set_config_value's coercion will replace the
- # leaf with a dict, matching pre-existing behavior).
+ if seg in _PLATFORM_CONTAINER_KEYS or not isinstance(node, dict):
return True, None
if seg not in node:
- # Suggest the closest sibling at this depth.
sibling_suggestion = _suggest_closest_key(seg, set(node.keys()))
if sibling_suggestion is not None:
- fixed_path = ".".join(consumed + [sibling_suggestion])
- return False, fixed_path
+ return False, ".".join(consumed + [sibling_suggestion])
return False, None
consumed.append(seg)
node = node[seg]
-
- # Walked the entire user-supplied path without hitting an unknown
- # segment — it's known.
return True, None
def _looks_structured_value(value: str) -> bool:
"""Return True when *value* plausibly encodes a YAML/JSON list or mapping.
- Used by :func:`set_config_value` to decide whether to attempt a
- ``yaml.safe_load`` structured parse. Deliberately conservative so plain
- scalars are never mangled:
-
- - Flow style: the value starts with ``[`` or ``{`` (JSON is a YAML
- subset, so both ``'["a","b"]'`` and ``'{a: 1}'`` qualify).
- - Block style: the value spans multiple lines AND at least one line is
- shaped like a YAML sequence item (``- item``) or mapping entry
- (``key: value``).
+ Used by :func:`set_config_value` to decide whether to attempt a ``yaml.safe_load`` structured
+ parse. Deliberately conservative so plain scalars are never mangled:
- A bare leading ``-`` is NOT a trigger on its own: ``-5``, ``--flag`` and
- other dash-prefixed single-line scalars must remain strings.
+ A bare leading ``-`` is NOT a trigger on its own: ``-5``, ``--flag`` and other dash-prefixed
+ single-line scalars must remain strings.
"""
stripped = value.lstrip()
if stripped[:1] in ('[', '{'):
@@ -5867,9 +4813,8 @@ def _looks_structured_value(value: str) -> bool:
def _coerce_int(value: str):
"""Return int(value) for a clean integer literal, else None.
- Uses ``int()`` so signs, surrounding whitespace, and underscores parse —
- unlike ``str.isdigit()`` which rejects "-5"/" 5 ". Rejects float-looking
- strings (that's ``_coerce_float``'s job) and bools masquerading as ints.
+ Uses ``int()`` so signs, whitespace, and underscores parse (``str.isdigit()`` rejects "-5").
+ Rejects float-looking strings (``_coerce_float``'s job) and bools masquerading as ints.
"""
try:
return int(value)
@@ -5880,9 +4825,9 @@ def _coerce_int(value: str):
def _coerce_float(value: str):
"""Return ``float(value)`` when conversion preserves its decimal value.
- Decimal-looking identifiers can be much more precise than a binary float.
- Silently rounding one here corrupts it before it reaches ``config.yaml``,
- so values that do not round-trip through ``float`` remain strings.
+ Decimal-looking identifiers can be much more precise than a binary float. Silently rounding one
+ here corrupts it before it reaches ``config.yaml``, so values that do not round-trip through
+ ``float`` remain strings.
"""
try:
f = float(value)
@@ -5900,23 +4845,70 @@ def _coerce_float(value: str):
return f
+_SCALAR_WORDS = {
+ 'true': True, 'yes': True, 'on': True,
+ 'false': False, 'no': False, 'off': False,
+ # YAML null / "off" state. Many DEFAULT_CONFIG leaves default to None and
+ # are documented as "null/absent = off"; without this, ``config set X null``
+ # stored the truthy string "null" and the feature could never be cleared.
+ 'null': None, 'none': None, '~': None,
+}
+
+
+def _coerce_config_set_value(key: str, value: str) -> Any:
+ """Auto-coerce a ``hermes config set`` string to bool/None/int/float/list/dict.
+
+ String-typed settings (per ``DEFAULT_CONFIG``) are preserved verbatim so enum members such as
+ ``approvals.mode="off"`` never become YAML booleans; unknown keys keep best-effort coercion.
+ ``int()`` handles signs/whitespace/underscores (``str.isdigit()`` rejected "-5"). List/mapping
+ literals (``'["file","web"]'`` or a multi-line YAML block) are parsed so isinstance-gated
+ readers see real structures; the trigger is conservative (see ``_looks_structured_value``) so
+ plain scalars like ``-5`` or ``--flag`` never reach the YAML parser.
+ """
+ if isinstance(_default_value_for_key(key), str):
+ return value
+ stripped = value.strip()
+ lower = stripped.lower()
+ if lower in _SCALAR_WORDS:
+ return _SCALAR_WORDS[lower]
+ for coerce in (_coerce_int, _coerce_float):
+ coerced = coerce(stripped)
+ if coerced is not None:
+ return coerced
+ if not _looks_structured_value(value):
+ return value
+ try:
+ parsed = yaml.safe_load(value)
+ except yaml.YAMLError:
+ print(
+ f"Warning: value for '{key}' looks like a list/mapping but is "
+ f"not valid YAML/JSON; storing as string. Most isinstance-gated "
+ f"readers will ignore a string here.",
+ file=sys.stderr,
+ )
+ return value
+ if isinstance(parsed, (list, dict)):
+ return parsed
+ print(
+ f"Warning: value for '{key}' looks like a list/mapping but "
+ f"parsed as {type(parsed).__name__}; storing as string.",
+ file=sys.stderr,
+ )
+ return value
+
+
def _redirect_platform_display_key(key: str) -> tuple[str, Optional[str]]:
"""Canonicalize ``platforms.<name>.<display_setting>`` → ``display.platforms.<name>.<setting>``.
- Per-platform *display* settings (streaming, show_reasoning, tool_progress,
- …) are resolved by the gateway from ``display.platforms.<name>.<setting>``
- (``gateway/display_config.py::resolve_display_setting``), while the
- top-level ``platforms.<name>`` block holds only connection config (token,
- enabled, reply_to_mode, extra, …). Before #71047 a write such as
- ``hermes config set platforms.telegram.streaming false`` landed on a key
- the gateway never reads: ``config get`` echoed the new value back while
- the runtime kept the old ``display.platforms`` one — a silent no-op that
- looks like a duplicated key to the user.
-
- Only known display settings (``OVERRIDEABLE_KEYS``) are redirected so real
- connection keys stay put. Returns ``(canonical_key, note_or_None)``.
- The gateway import is guarded: the CLI must keep working where the
- gateway package is not importable.
+ Per-platform *display* settings (streaming, show_reasoning, tool_progress, …) are resolved by
+ the gateway from ``display.platforms.<name>.<setting>``
+ (``gateway/display_config.py::resolve_display_setting``), while the top-level
+ ``platforms.<name>`` block holds only connection config (token, enabled, reply_to_mode, extra,
+ …).
+
+ Only known display settings (``OVERRIDEABLE_KEYS``) are redirected so real connection keys stay
+ put. Returns ``(canonical_key, note_or_None)``. The gateway import is guarded: the CLI must keep
+ working where the gateway package is not importable.
"""
segs = _split_key_path(key)
if len(segs) != 3 or segs[0] != "platforms":
@@ -5931,54 +4923,109 @@ def _redirect_platform_display_key(key: str) -> tuple[str, Optional[str]]:
return canonical, f" (note: per-platform display setting — saved as {canonical})"
+def _exit_if_key_managed(key: str, action: str) -> None:
+ """Managed scope guard (D2): a key pinned by the managed layer cannot be set/unset by the user —
+ the next load would override/reinstate it anyway. Hard-reject and name the source. Distinct from
+ ``is_managed()`` (the package-manager write-lock). Env-shaped keys route to the .env writers,
+ which carry their own managed-env-key guard; this catches the config.yaml keys.
+ """
+ from hermes_cli import managed_scope
+
+ if managed_scope.is_key_managed(key):
+ managed_dir = managed_scope.get_managed_dir()
+ src = (managed_dir / "config.yaml") if managed_dir else "the managed scope"
+ print(
+ f"Cannot {action} '{key}': it is managed by your administrator ({src}) "
+ f"and cannot be changed. Contact your administrator to modify it.",
+ file=sys.stderr,
+ )
+ sys.exit(1)
+
+
+def _guard_section_overwrite(key: str, value: Any, user_config: Dict[str, Any], force: bool) -> str:
+ """Refuse (or with ``force`` allow) a single-segment key overwriting a mapping section with a scalar.
+
+ Bare ``model`` is a documented shorthand — redirected to ``model.default`` so siblings
+ (provider/context_length/...) survive. Every other mapping section is rejected unless
+ ``--force``. Returns the (possibly redirected) key.
+ """
+ if "." in key:
+ return key
+ existing = user_config.get(key)
+ if not isinstance(existing, dict):
+ return key
+ if key == "model":
+ if force:
+ print(
+ f"⚠ Replacing entire 'model' section with a scalar "
+ f"(discarding {len(existing)} existing sub-key(s))"
+ )
+ return key
+ print(
+ f"✓ Redirecting bare 'model' to 'model.default' "
+ f"(preserving {len(existing)} existing model sub-key(s))"
+ )
+ return "model.default"
+ if force:
+ return key
+ sub = [k for k in existing if isinstance(k, str)]
+ err = [
+ f"✗ Cannot set '{key}' to a scalar — '{key}' is a "
+ f"configuration section with {len(sub)} sub-key(s).",
+ ]
+ if sub:
+ err.append(f" Sub-keys: {', '.join(sub[:8])}")
+ if len(sub) > 8:
+ err.append(f" ... and {len(sub) - 8} more")
+ err += [
+ " Use a dotted path to set a specific leaf key:",
+ f" hermes config set {key}.<sub-key> <value>",
+ " Or use --force to replace the entire section:",
+ f" hermes config set --force {key} {value!r}",
+ ]
+ print("\n".join(err), file=sys.stderr)
+ sys.exit(1)
+
+
+def _touch_skin_file(key: str, value: Any) -> None:
+ """``display.skin`` set is an explicit "apply NOW": bump the skin file's mtime so the gateway
+ watcher's (name, mtime) signature moves even when the name is unchanged. Built-ins have no file;
+ a name switch already moves their signature. Best-effort — the config write already succeeded.
+ """
+ if key == "display.skin" and isinstance(value, str) and value:
+ try:
+ skin_file = get_hermes_home() / "skins" / f"{value}.yaml"
+ if skin_file.exists():
+ skin_file.touch()
+ except Exception:
+ pass
+
+
def set_config_value(key: str, value: str, force: bool = False):
- """Set a configuration value.
-
- Args:
- key: Dotted config path (e.g. ``terminal.backend``).
- value: String value (auto-coerced to bool/int/float when matching).
- force: When True, skip the unknown-key warning — useful for scripted
- writes of keys the running version doesn't recognize yet — AND
- authorize destructive replacement of a mapping section by a
- scalar (e.g. ``--force model gpt-x`` replaces the whole ``model:``
- mapping). Without --force, scalar writes over mapping sections are
- refused (bare ``model`` is redirected to ``model.default``). The
- CLI exposes this via ``hermes config set --force``.
+ """Set a configuration value at a dotted ``key``; ``value`` is auto-coerced to bool/int/float.
+
+ ``force`` skips the unknown-key warning (scripted writes of keys this version doesn't know
+ yet) AND authorizes replacing a mapping section with a scalar. Without it, scalar writes over
+ mappings are refused and bare ``model`` is redirected to ``model.default``.
"""
if is_managed():
managed_error("set configuration values")
return
- # Reject malformed dotted keys with empty segments (leading/trailing/
- # double dots). ``"agent."`` split to ["agent", ""] and _set_nested wrote
- # config["agent"][""] = ..., polluting a live schema section with a
- # garbage empty-string key that round-tripped through get (CFG-04).
+ # Reject malformed dotted keys with empty segments (leading/trailing/double
+ # dots): ``"agent."`` would write config["agent"][""] and pollute a live
+ # schema section with a garbage key that round-trips through get.
if key != key.strip() or not key.strip():
print(f"✗ Invalid config key: {key!r} (empty or surrounding whitespace).",
file=sys.stderr)
sys.exit(1)
- if any(seg == "" for seg in _split_key_path(key)):
+ if "" in _split_key_path(key):
print(
f"✗ Invalid config key: {key!r} — contains an empty path segment "
"(leading, trailing, or doubled '.').",
file=sys.stderr,
)
sys.exit(1)
- # Managed scope guard (D2): a key pinned by the managed layer cannot be set by
- # the user — the next load would override it anyway. Hard-reject and name the
- # source. Distinct from is_managed() above (the package-manager write-lock).
- # Env-shaped keys (API keys / tokens) route to save_env_value below, which has
- # its own managed-env-key guard; this catches the config.yaml keys.
- from hermes_cli import managed_scope
-
- if managed_scope.is_key_managed(key):
- managed_dir = managed_scope.get_managed_dir()
- src = (managed_dir / "config.yaml") if managed_dir else "the managed scope"
- print(
- f"Cannot set '{key}': it is managed by your administrator ({src}) "
- f"and cannot be changed. Contact your administrator to modify it.",
- file=sys.stderr,
- )
- sys.exit(1)
+ _exit_if_key_managed(key, "set")
# Check if it's an API key (goes to .env)
if _is_env_config_key(key):
# Unified lifecycle: also rotates any config.yaml mirror of the old
@@ -5989,170 +5036,38 @@ def set_config_value(key: str, value: str, force: bool = False):
print(f"✓ Set {key} in {get_env_path()}")
return
- # Unknown-key notice (#34067): the key is still written (arbitrary keys
- # are supported — top-level scalars are bridged into os.environ for
- # skills and external apps), but a plausible-but-wrong dotted path like
- # ``gateway.discord.gateway_restart_notification`` previously reported
- # bare success and left the user debugging behavior that never changed.
- # Warn after the write so the user gets immediate feedback plus a
- # "did you mean" hint, without blocking legitimate unknown keys.
- # Per-platform display settings live under display.platforms (#71047,
- # Problem A) — canonicalize BEFORE validation/coercion so the type-aware
- # coercion and the unknown-key hint both see the path the runtime reads.
+ # Unknown-key notice: arbitrary keys are still written (top-level scalars
+ # are bridged into os.environ for skills/external apps), but a
+ # plausible-but-wrong dotted path gets a post-write "did you mean" hint.
+ # Per-platform display settings live under display.platforms — canonicalize
+ # BEFORE validation/coercion so both see the path the runtime reads.
key, _redirect_note = _redirect_platform_display_key(key)
if _redirect_note:
print(_redirect_note)
is_known, suggestion = _validate_config_key(key)
- # Otherwise it goes to config.yaml
- # Read the raw user config (not merged with defaults) to avoid
- # dumping all default values back to the file
+ # Otherwise it goes to config.yaml: read the RAW user config (not merged
+ # with defaults) so defaults are never dumped back to disk; fail-closed on
+ # unparseable / non-mapping files.
config_path = get_config_path()
- # Fail-closed parse via require_readable (unparseable / non-mapping
- # refuse-write); returns the mapping so we do not re-parse / collapse.
user_config = require_readable_config_before_write(config_path)
-
- # Handle nested keys (e.g., "tts.provider") including numeric list
- # indices (e.g., "custom_providers.0.api_key"). Delegates to
- # _set_nested which preserves list-typed nodes; before #17876 the
- # inline navigation here silently overwrote lists with dicts.
-
- # Preserve values for string-typed settings. In particular, enum members
- # such as approvals.mode="off" must not become YAML booleans. Unknown keys
- # retain the historical best-effort coercion behavior.
- coerced_value: Any = value
- if not isinstance(_default_value_for_key(key), str):
- _stripped = value.strip()
- _lower = _stripped.lower()
- if _lower in {'true', 'yes', 'on'}:
- coerced_value = True
- elif _lower in {'false', 'no', 'off'}:
- coerced_value = False
- elif _lower in {'null', 'none', '~'}:
- # YAML null / "off" state. Many DEFAULT_CONFIG leaves default to
- # None and are documented as "null/absent = off"; without this,
- # ``config set X null`` stored the truthy string "null" and the
- # feature could never be cleared via set (CFG-05).
- coerced_value = None
- elif _coerce_int(_stripped) is not None:
- # int() handles signs, surrounding whitespace, and underscores —
- # unlike the old ``value.isdigit()`` which rejected "-5" and " 5 "
- # and silently stored them as strings on int-typed keys (CFG-02).
- coerced_value = _coerce_int(_stripped)
- elif _coerce_float(_stripped) is not None:
- coerced_value = _coerce_float(_stripped)
- elif _looks_structured_value(value):
- # List/mapping literals -- e.g.
- # hermes config set platform_toolsets.line '["file","web"]'
- # or a multi-line YAML block:
- # hermes config set custom_providers '- name: foo
- # base_url: https://...'
- # Without this, such values were stored as a raw STRING, and every
- # reader that gates on isinstance(..., list) (``_get_platform_tools``,
- # ``_get_enabled_set``, ...) silently ignored them and fell back to
- # its default -- the setting looked saved but never took effect.
- # Folded INSIDE the string-typed guard so a genuinely string-typed
- # setting whose value merely starts with '[' or '{' is left intact
- # (preserves the guard added in e4ea0a0ed). The trigger is
- # deliberately conservative (see _looks_structured_value): plain
- # scalars like '-5' or '--flag' never reach the YAML parser.
- try:
- parsed = yaml.safe_load(value)
- if isinstance(parsed, (list, dict)):
- coerced_value = parsed
- else:
- print(
- f"Warning: value for '{key}' looks like a list/mapping but "
- f"parsed as {type(parsed).__name__}; storing as string.",
- file=sys.stderr,
- )
- except yaml.YAMLError:
- print(
- f"Warning: value for '{key}' looks like a list/mapping but is "
- f"not valid YAML/JSON; storing as string. Most isinstance-gated "
- f"readers will ignore a string here.",
- file=sys.stderr,
- )
-
- value = coerced_value
- # Normalize a scalar ``model`` key before writing sub-keys so that
- # ``hermes config set model.provider openai`` doesn't silently
- # destroy the model id when ``model`` is a bare string shorthand
- # (e.g. ``model: gpt-4o``). Without this _set_nested replaces the
- # scalar with an empty dict, dropping the model id permanently.
- _model_key = key.strip().lower()
- if _model_key.startswith("model."):
+ value = _coerce_config_set_value(key, value)
+ # Normalize a scalar ``model`` shorthand (``model: gpt-4o``) before writing
+ # sub-keys; otherwise _set_nested replaces the scalar with an empty dict and
+ # ``config set model.provider openai`` drops the model id permanently.
+ if key.strip().lower().startswith("model."):
_model_val = user_config.get("model")
if isinstance(_model_val, str) and _model_val:
user_config["model"] = {"default": _model_val}
- # Guard against #74995: a single-segment key that names an existing
- # mapping would silently overwrite the entire section with a scalar
- # (e.g. ``hermes config set model gpt-5.6-sol`` when model already
- # contains default/provider/context_length). Bare ``model`` is a
- # documented shorthand — redirect to ``model.default`` and preserve
- # siblings. All other mapping sections are rejected unless --force.
- if "." not in key:
- _existing = user_config.get(key)
- if isinstance(_existing, dict):
- if key == "model":
- if force:
- # --force: allow destructive section overwrite.
- print(
- f"⚠ Replacing entire 'model' section with a scalar "
- f"(discarding {len(_existing)} existing sub-key(s))"
- )
- else:
- # Redirect bare-model shorthand to model.default while
- # keeping every sibling mapping key intact.
- key = "model.default"
- print(
- f"✓ Redirecting bare 'model' to 'model.default' "
- f"(preserving {len(_existing)} existing model sub-key(s))"
- )
- # value was already coerced above; proceed to _set_nested
- elif not force:
- _sub = [k for k in _existing if isinstance(k, str)]
- print(
- f"✗ Cannot set '{key}' to a scalar — '{key}' is a "
- f"configuration section with {len(_sub)} sub-key(s).",
- file=sys.stderr,
- )
- if _sub:
- _sub_list = ", ".join(_sub[:8])
- print(f" Sub-keys: {_sub_list}", file=sys.stderr)
- if len(_sub) > 8:
- print(
- f" ... and {len(_sub) - 8} more",
- file=sys.stderr,
- )
- print(
- " Use a dotted path to set a specific leaf key:",
- file=sys.stderr,
- )
- print(
- f" hermes config set {key}.<sub-key> <value>",
- file=sys.stderr,
- )
- print(
- " Or use --force to replace the entire section:",
- file=sys.stderr,
- )
- print(
- f" hermes config set --force {key} {value!r}",
- file=sys.stderr,
- )
- sys.exit(1)
+ key = _guard_section_overwrite(key, value, user_config, force)
try:
_set_nested(user_config, key, value)
except ValueError as e:
print(f"✗ {e}", file=sys.stderr)
sys.exit(1)
- # Normalize the api_base → base_url alias at set-time too (issue #8919),
- # so a fresh `hermes config set model.api_base ...` lands on the canonical
- # key the runtime resolver actually reads, instead of being silently
- # ignored. Mirrors the load-time migration in _normalize_root_model_keys.
- _alias_norm = key.strip().lower()
- if _alias_norm in ("model.api_base", "api_base"):
+ # Normalize the api_base → base_url alias at set-time too so the value lands
+ # on the key the runtime resolver reads (mirrors _normalize_root_model_keys).
+ if key.strip().lower() in ("model.api_base", "api_base"):
user_config = _normalize_root_model_keys(user_config)
key = "model.base_url"
print(" (note: 'api_base' is an alias — saved as model.base_url)")
@@ -6167,34 +5082,21 @@ def set_config_value(key: str, value: str, force: bool = False):
if env_var and key != "terminal.cwd":
save_env_value(env_var, _terminal_env_value(value))
- # Setting display.skin is an explicit "apply NOW" — bump the skin file's
- # mtime so the gateway watcher's (name, mtime) signature moves even when the
- # name is unchanged (re-affirming the active skin after a surface missed the
- # original activation). Built-ins have no file; a name switch already moves
- # their signature.
- if key == "display.skin" and isinstance(value, str) and value:
- try:
- skin_file = get_hermes_home() / "skins" / f"{value}.yaml"
- if skin_file.exists():
- skin_file.touch()
- except Exception:
- pass # best-effort: the config write above already succeeded
+ _touch_skin_file(key, value)
# Mask the echoed value when the (possibly nested) key is credential-shaped
# — e.g. `hermes config set model.api_key cfut_...` routes to config.yaml
# (lowercase, so it misses the .env api_keys list above) and would otherwise
# print the raw secret to the terminal.
- _leaf_key = key.rsplit(".", 1)[-1].lower()
- if _leaf_key in _SECRET_CONFIG_KEYS and isinstance(value, str) and value:
+ _display_value = value
+ if key.rsplit(".", 1)[-1].lower() in _SECRET_CONFIG_KEYS and isinstance(value, str) and value:
from agent.redact import mask_secret
_display_value = mask_secret(value)
- else:
- _display_value = value
print(f"✓ Set {key} = {_display_value} in {config_path}")
warn_unpinned_cron_jobs_after_model_config_change(key, value, user_config)
- # Post-write unknown-key notice (#34067): value IS saved, but tell the
- # user the runtime may never read it and suggest the likely-intended path.
+ # Post-write unknown-key notice: value IS saved, but tell the user the
+ # runtime may never read it and suggest the likely-intended path.
if not is_known and not force:
print(color(
f"⚠ '{key}' is not a recognized config key — it was saved anyway, "
@@ -6234,19 +5136,7 @@ def unset_config_value(key: str):
if is_managed():
managed_error("unset configuration values")
return
- # Managed scope guard: a key pinned by the managed layer cannot be unset by
- # the user — the next load would reinstate it anyway (mirrors set_config_value).
- from hermes_cli import managed_scope
-
- if managed_scope.is_key_managed(key):
- managed_dir = managed_scope.get_managed_dir()
- src = (managed_dir / "config.yaml") if managed_dir else "the managed scope"
- print(
- f"Cannot unset '{key}': it is managed by your administrator ({src}) "
- f"and cannot be changed. Contact your administrator to modify it.",
- file=sys.stderr,
- )
- sys.exit(1)
+ _exit_if_key_managed(key, "unset")
if _is_env_config_key(key):
# Unified lifecycle: prune env-seeded credential_pool entries and
@@ -6290,182 +5180,197 @@ def unset_config_value(key: str):
# Command handler
# =============================================================================
-def config_command(args):
- """Handle config subcommands."""
- subcmd = getattr(args, 'config_command', None)
-
- if subcmd is None or subcmd == "show":
- show_config()
-
- elif subcmd == "edit":
- edit_config()
-
- elif subcmd == "get":
- key = getattr(args, 'key', None)
- if not key:
- print("Usage: hermes config get <key> [--json]")
- print()
- print("Examples:")
- print(" hermes config get model")
- print(" hermes config get terminal.backend")
- print(" hermes config get skills.config --json")
- sys.exit(1)
- get_config_value(key, as_json=getattr(args, 'json', False))
-
- elif subcmd == "set":
- key = getattr(args, 'key', None)
- value = getattr(args, 'value', None)
- force = bool(getattr(args, 'force', False))
- if not key or value is None:
- print("Usage: hermes config set [--force] <key> <value>")
- print()
- print("Examples:")
- print(" hermes config set model anthropic/claude-sonnet-4")
- print(" hermes config set terminal.backend docker")
- print(" hermes config set OPENROUTER_API_KEY sk-or-...")
- print()
- print(" --force: skip the unknown-key notice for unrecognized keys,")
- print(" and allow a scalar to replace a whole mapping section")
- sys.exit(1)
- try:
- set_config_value(key, value, force=force)
- except RuntimeError as exc:
- # Fail-closed write guard (unparseable / non-mapping / unreadable
- # config.yaml). Surface a clean CLI error instead of a traceback.
- print(f"✗ {exc}", file=sys.stderr)
- sys.exit(1)
+def _usage_exit(usage: str, examples: List[str], extra: Optional[List[str]] = None) -> None:
+ print(usage)
+ print()
+ print("Examples:")
+ for line in examples:
+ print(f" {line}")
+ for line in extra or ():
+ print(line)
+ sys.exit(1)
- elif subcmd == "unset":
- key = getattr(args, 'key', None)
- if not key:
- print("Usage: hermes config unset <key>")
- print()
- print("Examples:")
- print(" hermes config unset model")
- print(" hermes config unset terminal.backend")
- print(" hermes config unset OPENROUTER_API_KEY")
- sys.exit(1)
- try:
- unset_config_value(key)
- except RuntimeError as exc:
- # Same fail-closed guard surface as `config set` above.
- print(f"✗ {exc}", file=sys.stderr)
- sys.exit(1)
-
- elif subcmd == "path":
- print(get_config_path())
-
- elif subcmd == "env-path":
- print(get_env_path())
-
- elif subcmd == "migrate":
- print()
- print(color("🔄 Checking configuration for updates...", Colors.CYAN, Colors.BOLD))
- print()
-
- # Check what's missing
- missing_env = get_missing_env_vars(required_only=False)
- missing_config = get_missing_config_fields()
- current_ver, latest_ver = check_config_version()
-
- if not missing_env and not missing_config and current_ver >= latest_ver:
- print(color("✓ Configuration is up to date!", Colors.GREEN))
- print()
- return
-
- # Show what needs to be updated
- if current_ver < latest_ver:
- print(f" Config version: {current_ver} → {latest_ver}")
-
- if missing_config:
- print(f"\n {len(missing_config)} new config option(s) will be added with defaults")
-
- required_missing = [v for v in missing_env if v.get("is_required")]
- optional_missing = [
- v for v in missing_env
- if not v.get("is_required") and not v.get("advanced")
- ]
-
- if required_missing:
- print(f"\n ⚠️ {len(required_missing)} required API key(s) missing:")
- for var in required_missing:
- print(f" • {var['name']}")
-
- if optional_missing:
- print(f"\n ℹ️ {len(optional_missing)} optional API key(s) not configured:")
- for var in optional_missing:
- tools = var.get("tools", [])
- tools_str = f" (enables: {', '.join(tools[:2])})" if tools else ""
- print(f" • {var['name']}{tools_str}")
-
- print()
-
- # Run migration
- results = migrate_config(interactive=True, quiet=False)
-
- print()
- if results["env_added"] or results["config_added"]:
- print(color("✓ Configuration updated!", Colors.GREEN))
-
- if results["warnings"]:
- print()
- for warning in results["warnings"]:
- print(color(f" ⚠️ {warning}", Colors.YELLOW))
-
- print()
-
- elif subcmd == "check":
- # Non-interactive check for what's missing
- print()
- print(color("📋 Configuration Status", Colors.CYAN, Colors.BOLD))
- print()
-
- current_ver, latest_ver = check_config_version()
- if current_ver >= latest_ver:
- print(f" Config version: {current_ver} ✓")
- else:
- print(color(f" Config version: {current_ver} → {latest_ver} (update available)", Colors.YELLOW))
-
- print()
- print(color(" Required:", Colors.BOLD))
- for var_name in REQUIRED_ENV_VARS:
- if get_env_value(var_name):
- print(f" ✓ {var_name}")
- else:
- print(color(f" ✗ {var_name} (missing)", Colors.RED))
-
+
+def _cmd_config_get(args):
+ key = getattr(args, 'key', None)
+ if not key:
+ _usage_exit("Usage: hermes config get <key> [--json]", [
+ "hermes config get model",
+ "hermes config get terminal.backend",
+ "hermes config get skills.config --json",
+ ])
+ get_config_value(key, as_json=getattr(args, 'json', False))
+
+
+def _cmd_config_set(args):
+ key = getattr(args, 'key', None)
+ value = getattr(args, 'value', None)
+ force = bool(getattr(args, 'force', False))
+ if not key or value is None:
+ _usage_exit("Usage: hermes config set [--force] <key> <value>", [
+ "hermes config set model anthropic/claude-sonnet-4",
+ "hermes config set terminal.backend docker",
+ "hermes config set OPENROUTER_API_KEY sk-or-...",
+ ], [
+ "",
+ " --force: skip the unknown-key notice for unrecognized keys,",
+ " and allow a scalar to replace a whole mapping section",
+ ])
+ try:
+ set_config_value(key, value, force=force)
+ except RuntimeError as exc:
+ # Fail-closed write guard (unparseable / non-mapping / unreadable
+ # config.yaml). Surface a clean CLI error instead of a traceback.
+ print(f"✗ {exc}", file=sys.stderr)
+ sys.exit(1)
+
+
+def _cmd_config_unset(args):
+ key = getattr(args, 'key', None)
+ if not key:
+ _usage_exit("Usage: hermes config unset <key>", [
+ "hermes config unset model",
+ "hermes config unset terminal.backend",
+ "hermes config unset OPENROUTER_API_KEY",
+ ])
+ try:
+ unset_config_value(key)
+ except RuntimeError as exc:
+ # Same fail-closed guard surface as `config set` above.
+ print(f"✗ {exc}", file=sys.stderr)
+ sys.exit(1)
+
+
+def _cmd_config_migrate(args):
+ print()
+ print(color("🔄 Checking configuration for updates...", Colors.CYAN, Colors.BOLD))
+ print()
+
+ # Check what's missing
+ missing_env = get_missing_env_vars(required_only=False)
+ missing_config = get_missing_config_fields()
+ current_ver, latest_ver = check_config_version()
+
+ if not missing_env and not missing_config and current_ver >= latest_ver:
+ print(color("✓ Configuration is up to date!", Colors.GREEN))
print()
- print(color(" Optional:", Colors.BOLD))
- for var_name, info in OPTIONAL_ENV_VARS.items():
- if get_env_value(var_name):
- print(f" ✓ {var_name}")
- else:
- tools = info.get("tools", [])
- tools_str = f" → {', '.join(tools[:2])}" if tools else ""
- print(color(f" ○ {var_name}{tools_str}", Colors.DIM))
-
- missing_config = get_missing_config_fields()
- if missing_config:
- print()
- print(color(f" {len(missing_config)} new config option(s) available", Colors.YELLOW))
- print(" Run 'hermes config migrate' to add them")
-
+ return
+
+ # Show what needs to be updated
+ if current_ver < latest_ver:
+ print(f" Config version: {current_ver} → {latest_ver}")
+
+ if missing_config:
+ print(f"\n {len(missing_config)} new config option(s) will be added with defaults")
+
+ required_missing = [v for v in missing_env if v.get("is_required")]
+ optional_missing = [
+ v for v in missing_env
+ if not v.get("is_required") and not v.get("advanced")
+ ]
+
+ if required_missing:
+ print(f"\n ⚠️ {len(required_missing)} required API key(s) missing:")
+ for var in required_missing:
+ print(f" • {var['name']}")
+
+ if optional_missing:
+ print(f"\n ℹ️ {len(optional_missing)} optional API key(s) not configured:")
+ for var in optional_missing:
+ tools = var.get("tools", [])
+ tools_str = f" (enables: {', '.join(tools[:2])})" if tools else ""
+ print(f" • {var['name']}{tools_str}")
+
+ print()
+
+ # Run migration
+ results = migrate_config(interactive=True, quiet=False)
+
+ print()
+ if results["env_added"] or results["config_added"]:
+ print(color("✓ Configuration updated!", Colors.GREEN))
+
+ if results["warnings"]:
print()
-
+ for warning in results["warnings"]:
+ print(color(f" ⚠️ {warning}", Colors.YELLOW))
+
+ print()
+
+
+def _cmd_config_check(args):
+ # Non-interactive check for what's missing
+ print()
+ print(color("📋 Configuration Status", Colors.CYAN, Colors.BOLD))
+ print()
+
+ current_ver, latest_ver = check_config_version()
+ if current_ver >= latest_ver:
+ print(f" Config version: {current_ver} ✓")
else:
- print(f"Unknown config command: {subcmd}")
+ print(color(f" Config version: {current_ver} → {latest_ver} (update available)", Colors.YELLOW))
+
+ print()
+ print(color(" Required:", Colors.BOLD))
+ for var_name in REQUIRED_ENV_VARS:
+ if get_env_value(var_name):
+ print(f" ✓ {var_name}")
+ else:
+ print(color(f" ✗ {var_name} (missing)", Colors.RED))
+
+ print()
+ print(color(" Optional:", Colors.BOLD))
+ for var_name, info in OPTIONAL_ENV_VARS.items():
+ if get_env_value(var_name):
+ print(f" ✓ {var_name}")
+ else:
+ tools = info.get("tools", [])
+ tools_str = f" → {', '.join(tools[:2])}" if tools else ""
+ print(color(f" ○ {var_name}{tools_str}", Colors.DIM))
+
+ missing_config = get_missing_config_fields()
+ if missing_config:
print()
- print("Available commands:")
- print(" hermes config Show current configuration")
- print(" hermes config edit Open config in editor")
- print(" hermes config get <key> Print a resolved config value")
- print(" hermes config set <key> <value> Set a config value")
- print(" hermes config unset <key> Remove a config value")
- print(" hermes config check Check for missing/outdated config")
- print(" hermes config migrate Update config with new options")
- print(" hermes config path Show config file path")
- print(" hermes config env-path Show .env file path")
- sys.exit(1)
+ print(color(f" {len(missing_config)} new config option(s) available", Colors.YELLOW))
+ print(" Run 'hermes config migrate' to add them")
+
+ print()
+
+
+_CONFIG_SUBCOMMANDS = {
+ None: lambda args: show_config(),
+ "show": lambda args: show_config(),
+ "edit": lambda args: edit_config(),
+ "get": _cmd_config_get,
+ "set": _cmd_config_set,
+ "unset": _cmd_config_unset,
+ "path": lambda args: print(get_config_path()),
+ "env-path": lambda args: print(get_env_path()),
+ "migrate": _cmd_config_migrate,
+ "check": _cmd_config_check,
+}
+
+
+def config_command(args):
+ """Handle config subcommands."""
+ subcmd = getattr(args, 'config_command', None)
+ handler = _CONFIG_SUBCOMMANDS.get(subcmd)
+ if handler is not None:
+ handler(args)
+ return
+ print(f"Unknown config command: {subcmd}")
+ print()
+ print("Available commands:")
+ print(" hermes config Show current configuration")
+ print(" hermes config edit Open config in editor")
+ print(" hermes config get <key> Print a resolved config value")
+ print(" hermes config set <key> <value> Set a config value")
+ print(" hermes config unset <key> Remove a config value")
+ print(" hermes config check Check for missing/outdated config")
+ print(" hermes config migrate Update config with new options")
+ print(" hermes config path Show config file path")
+ print(" hermes config env-path Show .env file path")
+ sys.exit(1)
# ── Profile-driven env var injection ─────────────────────────────────────────
@@ -6473,18 +5378,21 @@ def config_command(args):
# gets its env_vars exposed in OPTIONAL_ENV_VARS without editing this file.
# Runs once at import time.
-_profile_env_vars_injected = False
+def _run_once(fn):
+ """Idempotent module-load injector: the first call runs *fn*, later calls are no-ops."""
+ def wrapper() -> None:
+ if not wrapper.done:
+ wrapper.done = True
+ fn()
+ wrapper.done = False
+ wrapper.__name__ = fn.__name__
+ wrapper.__doc__ = fn.__doc__
+ return wrapper
+@_run_once
def _inject_profile_env_vars() -> None:
- """Populate OPTIONAL_ENV_VARS from provider profiles not already listed.
-
- Called once at module load time. Idempotent — repeated calls are no-ops.
- """
- global _profile_env_vars_injected
- if _profile_env_vars_injected:
- return
- _profile_env_vars_injected = True
+ """Populate OPTIONAL_ENV_VARS from provider profiles not already listed."""
try:
from providers import list_providers
for _pp in list_providers():
@@ -6494,9 +5402,10 @@ def _inject_profile_env_vars() -> None:
if _var in OPTIONAL_ENV_VARS:
continue
_is_key = not _var.endswith("_BASE_URL") and not _var.endswith("_URL")
+ _label = _pp.display_name or _pp.name
OPTIONAL_ENV_VARS[_var] = {
- "description": f"{_pp.display_name or _pp.name} {'API key' if _is_key else 'base URL override'}",
- "prompt": f"{_pp.display_name or _pp.name} {'API key' if _is_key else 'base URL (leave empty for default)'}",
+ "description": f"{_label} {'API key' if _is_key else 'base URL override'}",
+ "prompt": f"{_label} {'API key' if _is_key else 'base URL (leave empty for default)'}",
"url": _pp.signup_url or None,
"password": _is_key,
"category": "provider",
@@ -6530,26 +5439,17 @@ _inject_profile_env_vars()
# An optional ``optional_env`` block surfaces non-required vars the same way
# (e.g. allowlist, home channel).
-_platform_plugin_env_vars_injected = False
-
-
+@_run_once
def _inject_platform_plugin_env_vars() -> None:
"""Populate OPTIONAL_ENV_VARS from bundled platform plugin manifests.
- Called once at module load time. Idempotent — repeated calls are no-ops.
- Failures are swallowed so a malformed plugin.yaml can't break CLI import.
+ Called once at module load time. Idempotent — repeated calls are no-ops. Failures are swallowed
+ so a malformed plugin.yaml can't break CLI import.
"""
- global _platform_plugin_env_vars_injected
- if _platform_plugin_env_vars_injected:
- return
- _platform_plugin_env_vars_injected = True
try:
- import yaml # type: ignore
-
# Resolve the bundled plugins dir from this file's location so the
# injector works regardless of CWD.
- repo_root = Path(__file__).resolve().parents[1]
- platforms_dir = repo_root / "plugins" / "platforms"
+ platforms_dir = get_project_root() / "plugins" / "platforms"
if not platforms_dir.is_dir():
return
for child in platforms_dir.iterdir():
@@ -6567,9 +5467,7 @@ def _inject_platform_plugin_env_vars() -> None:
continue
label = manifest.get("label") or manifest.get("name") or child.name
# Merge required + optional env var declarations.
- entries = list(manifest.get("requires_env") or [])
- entries.extend(manifest.get("optional_env") or [])
- for entry in entries:
+ for entry in [*(manifest.get("requires_env") or []), *(manifest.get("optional_env") or [])]:
if isinstance(entry, str):
name = entry
meta: dict = {}
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 08ab1789e86..0dc0776bcb3 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -1,7 +1,7 @@
"""Default configuration data for Hermes Agent.
-Pure-data leaf module: DEFAULT_CONFIG and OPTIONAL_ENV_VARS, extracted
-verbatim from hermes_cli/config.py. Must not import from hermes_cli.config.
+Pure-data leaf module: DEFAULT_CONFIG and OPTIONAL_ENV_VARS, extracted verbatim from
+hermes_cli/config.py. Must not import from hermes_cli.config.
"""
DEFAULT_CONFIG = {
@@ -2237,7 +2237,6 @@ DEFAULT_CONFIG = {
"max_turns": 20,
},
-
# Loops — /loop recurring in-session wakeups (Claude Code parity).
# A loop re-runs a prompt (or slash command) on a cadence inside the
# live session. Fixed-interval mode fires on the user's clock;
@@ -3757,7 +3756,6 @@ DEFAULT_CONFIG = {
"servers": {},
},
-
# X (Twitter) Search via xAI's built-in x_search Responses tool.
# The tool registers when xAI credentials are available (SuperGrok
# OAuth or XAI_API_KEY) AND the x_search toolset is enabled in
@@ -4056,7 +4054,6 @@ DEFAULT_CONFIG = {
},
},
-
# Google Vertex AI provider (Gemini via the OpenAI-compatible endpoint).
# Auth is OAuth2 (short-lived access tokens minted from a service-account
# JSON or Application Default Credentials) — NOT a static API key. The
diff --git a/hermes_cli/config_migrations.py b/hermes_cli/config_migrations.py
index cb075be302a..62af4c85f42 100644
--- a/hermes_cli/config_migrations.py
+++ b/hermes_cli/config_migrations.py
@@ -1,38 +1,10 @@
"""Table-driven config migration registry.
-This module holds the per-version migration steps that used to live as a
-768-line ladder of ``if current_ver < N:`` blocks inside
-``hermes_cli.config.migrate_config``. Each step is a function
-``_migrate_to_N(results, quiet)`` whose body is copied verbatim from the
-original block; only the shared skeleton (the version gate and the strict
-ascending ordering) lives in the :func:`run_migrations` driver.
+Each step is a function ``_migrate_to_N(results, quiet)`` whose body is copied verbatim from the
+original block; only the shared skeleton (the version gate and the strict ascending ordering) lives
+in the :func:`run_migrations` driver.
Semantics preserved exactly from the original ladder:
-
-* ``current_ver`` is computed ONCE by the caller (``check_config_version``)
- and never advances while the ladder runs — every step compares against the
- same initial value. The driver replicates that: it applies every registry
- entry whose target version is ``> current_ver``, in ascending order.
-* Each step re-reads the raw on-disk config itself (``read_raw_config``) and
- persists via ``_persist_migration`` — steps therefore observe the writes of
- earlier steps through the filesystem, which is why strict ascending order
- is mandatory.
-* All ``results['config_added']`` / ``results['warnings']`` appends and all
- conditional ``print`` output stay inside the step functions, byte-identical
- to the original blocks.
-
-Import direction / cycle avoidance:
-
-``hermes_cli.config`` imports :func:`run_migrations` lazily (inside
-``migrate_config``), and every step function here resolves its helpers
-(``read_raw_config``, ``_persist_migration``, ``get_env_value``, …) lazily
-through the live ``hermes_cli.config`` module object at call time via
-:func:`_cfg`. There is deliberately NO module-level import of
-``hermes_cli.config`` here, so no circular import can form — and, just as
-importantly, tests that monkeypatch helpers on ``hermes_cli.config`` (e.g.
-``patch("hermes_cli.config.read_raw_config", ...)``) keep working, because
-the steps always go through the module attribute rather than a bound-early
-reference.
"""
from __future__ import annotations
@@ -73,12 +45,48 @@ def _cfg():
return config
+def read_raw_config():
+ return _cfg().read_raw_config()
+
+
+def _persist_migration(config):
+ _cfg()._persist_migration(config)
+
+
+def _rewrite_stale_default(
+ results: Dict[str, Any],
+ quiet: bool,
+ *,
+ section: str,
+ key: str,
+ old: Any,
+ new: Any,
+ added: str,
+ message: str,
+ extra_guard: Callable[[Dict[str, Any]], bool] = lambda _m: True,
+) -> None:
+ """Shared step shape: rewrite ``<section>.<key>`` only when it still equals the OLD default.
+
+ Never clobbers a value the user deliberately customized; unset keys inherit the new default at
+ read time. ``new=None`` deletes the key instead of assigning.
+ """
+ config = read_raw_config()
+ raw = config.get(section)
+ if isinstance(raw, dict) and raw.get(key) == old and extra_guard(raw):
+ if new is None:
+ del raw[key]
+ else:
+ raw[key] = new
+ config[section] = raw
+ _persist_migration(config)
+ results["config_added"].append(added)
+ if not quiet:
+ print(message)
+
+
def _migrate_to_12(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 11 → 12: migrate custom_providers list → providers dict ──
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
- _custom_provider_entry_to_provider_config = _c._custom_provider_entry_to_provider_config
+ _custom_provider_entry_to_provider_config = _cfg()._custom_provider_entry_to_provider_config
config = read_raw_config()
custom_list = config.get("custom_providers")
@@ -145,18 +153,14 @@ def _migrate_to_12(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_13(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 12 → 13: clear dead LLM_MODEL / OPENAI_MODEL from .env ──
- # These env vars were written by the old setup wizard but nothing reads
- # them anymore (config.yaml is the sole source of truth since March 2026).
- # Stale entries cause user confusion — see issue report.
+ # Written by the old setup wizard; nothing reads them (config.yaml is the
+ # sole source of truth). Stale entries only confuse users.
_c = _cfg()
- get_env_value = _c.get_env_value
- save_env_value = _c.save_env_value
-
for dead_var in ("LLM_MODEL", "OPENAI_MODEL"):
try:
- old_val = get_env_value(dead_var)
+ old_val = _c.get_env_value(dead_var)
if old_val:
- save_env_value(dead_var, "")
+ _c.save_env_value(dead_var, "")
if not quiet:
print(f" ✓ Cleared {dead_var} from .env (no longer used — config.yaml is source of truth)")
except Exception:
@@ -165,14 +169,8 @@ def _migrate_to_13(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_14(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 13 → 14: migrate legacy flat stt.model to provider section ──
- # Old configs (and cli-config.yaml.example) had a flat `stt.model` key
- # that was provider-agnostic. When the provider was "local" this caused
- # OpenAI model names (e.g. "whisper-1") to be fed to faster-whisper,
- # crashing with "Invalid model size". Move the value into the correct
- # provider-specific section and remove the flat key.
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
+ # A provider-agnostic `stt.model` fed OpenAI names to faster-whisper
+ # ("Invalid model size"). Move it into the provider's section; drop the flat key.
# Read raw config (no defaults merged) to check what the user actually
# wrote, then apply changes to the merged config for saving.
@@ -220,9 +218,6 @@ def _migrate_to_14(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_16(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 15 → 16: migrate tool_progress_overrides into display.platforms ──
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
config = read_raw_config()
display = config.get("display", {})
@@ -249,37 +244,24 @@ def _migrate_to_16(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_17(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 16 → 17: remove legacy compression.summary_* keys ──
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
config = read_raw_config()
comp = config.get("compression", {})
if isinstance(comp, dict):
- s_model = comp.pop("summary_model", None)
- s_provider = comp.pop("summary_provider", None)
- s_base_url = comp.pop("summary_base_url", None)
+ legacy = {k: comp.pop(f"summary_{k}", None) for k in ("model", "provider", "base_url")}
migrated_keys = []
- # Migrate non-empty, non-default values to auxiliary.compression
- if s_model and str(s_model).strip():
- aux = config.setdefault("auxiliary", {})
- aux_comp = aux.setdefault("compression", {})
- if not aux_comp.get("model"):
- aux_comp["model"] = str(s_model).strip()
- migrated_keys.append(f"model={s_model}")
- if s_provider and str(s_provider).strip() not in {"", "auto"}:
- aux = config.setdefault("auxiliary", {})
- aux_comp = aux.setdefault("compression", {})
- if not aux_comp.get("provider") or aux_comp.get("provider") == "auto":
- aux_comp["provider"] = str(s_provider).strip()
- migrated_keys.append(f"provider={s_provider}")
- if s_base_url and str(s_base_url).strip():
- aux = config.setdefault("auxiliary", {})
- aux_comp = aux.setdefault("compression", {})
- if not aux_comp.get("base_url"):
- aux_comp["base_url"] = str(s_base_url).strip()
- migrated_keys.append(f"base_url={s_base_url}")
- if migrated_keys or s_model is not None or s_provider is not None or s_base_url is not None:
+ # Migrate non-empty, non-default values to auxiliary.compression, never
+ # overriding an explicit (non-"auto") aux value.
+ for k, raw in legacy.items():
+ val = str(raw).strip() if raw else ""
+ if not val or (k == "provider" and val == "auto"):
+ continue
+ aux_comp = config.setdefault("auxiliary", {}).setdefault("compression", {})
+ cur = aux_comp.get(k)
+ if not cur or (k == "provider" and cur == "auto"):
+ aux_comp[k] = val
+ migrated_keys.append(f"{k}={raw}")
+ if migrated_keys or any(v is not None for v in legacy.values()):
config["compression"] = comp
_persist_migration(config)
if not quiet:
@@ -291,20 +273,11 @@ def _migrate_to_17(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_21(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 20 → 21: plugins are now opt-in; grandfather existing user plugins ──
- # The loader now requires plugins to appear in ``plugins.enabled`` before
- # loading. Existing installs had all discovered plugins loading by default
- # (minus anything in ``plugins.disabled``). To avoid silently breaking
- # those setups on upgrade, populate ``plugins.enabled`` with the set of
- # currently-installed user plugins that aren't already disabled.
- #
- # Bundled plugins (shipped in the repo itself) are NOT grandfathered —
- # they ship off for everyone, including existing users, so any user who
- # wants one has to opt in explicitly.
+ # The loader requires ``plugins.enabled``; existing installs loaded every
+ # discovered plugin (minus ``plugins.disabled``). Populate the allow-list
+ # with installed user plugins not already disabled. Bundled plugins are NOT
+ # grandfathered — they ship off for everyone and need explicit opt-in.
_c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
- get_hermes_home = _c.get_hermes_home
- fast_safe_load = _c.fast_safe_load
config = read_raw_config()
plugins_cfg = config.get("plugins")
@@ -320,7 +293,7 @@ def _migrate_to_21(results: Dict[str, Any], quiet: bool) -> None:
# Scan ``$HERMES_HOME/plugins/`` for currently installed user plugins.
grandfathered: List[str] = []
try:
- user_plugins_dir = get_hermes_home() / "plugins"
+ user_plugins_dir = _c.get_hermes_home() / "plugins"
if user_plugins_dir.is_dir():
for child in sorted(user_plugins_dir.iterdir()):
if not child.is_dir():
@@ -332,7 +305,7 @@ def _migrate_to_21(results: Dict[str, Any], quiet: bool) -> None:
continue
try:
with open(manifest_file, encoding="utf-8") as _mf:
- manifest = fast_safe_load(_mf) or {}
+ manifest = _c.fast_safe_load(_mf) or {}
except Exception:
manifest = {}
name = manifest.get("name") or child.name
@@ -363,128 +336,77 @@ def _migrate_to_21(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_23(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 22 → 23: seed curator defaults + create logs/curator/ ──
- # The curator (background skill maintenance) was added in PR #16049, but
- # existing configs from before that PR (or before the April 2026
- # unification under `auxiliary.curator`) never wrote the curator section
- # to disk. The runtime deep-merge in `load_config()` fills defaults at
- # read time, so the curator *functions*; but users can't see/edit the
- # settings in their `config.yaml`, and `hermes curator status` has no
- # stable logs dir to point at until the first run mkdir's it.
- #
- # This migration:
- # 1. Writes the `curator` top-level section to config.yaml (enabled,
- # interval_hours, min_idle_hours, stale_after_days, archive_after_days)
- # — only keys the user hasn't already overridden.
- # 2. Writes the `auxiliary.curator` aux-task slot (provider, model,
- # base_url, api_key, timeout, extra_body) — canonical slot for
- # routing the curator fork to a cheaper aux model.
- # 3. Creates `~/.hermes/logs/curator/` if missing (belt-and-suspenders
- # on top of ensure_hermes_home() — old profiles that predate this
- # migration still benefit).
+ # Older configs never wrote the curator section; deep-merge makes it
+ # function, but users could not see/edit it and `hermes curator status`
+ # had no stable logs dir. Writes `curator` and the `auxiliary.curator`
+ # aux-task slot (only keys the user hasn't overridden) and mkdirs
+ # logs/curator/ (belt-and-suspenders over ensure_hermes_home()).
_c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
- get_hermes_home = _c.get_hermes_home
DEFAULT_CONFIG = _c.DEFAULT_CONFIG
try:
- curator_dir = get_hermes_home() / "logs" / "curator"
+ curator_dir = _c.get_hermes_home() / "logs" / "curator"
curator_dir.mkdir(parents=True, exist_ok=True)
except Exception as e:
results["warnings"].append(f"Could not create {curator_dir}: {e}")
config = read_raw_config()
- touched = False
+
+ def _seed_missing(section: Dict[str, Any], defaults: Dict[str, Any]) -> List[str]:
+ added = [k for k in defaults if k not in section]
+ for k in added:
+ section[k] = copy.deepcopy(defaults[k])
+ return added
# (1) Top-level curator section — only add missing keys
- _curator_defaults = DEFAULT_CONFIG.get("curator", {})
raw_curator = config.get("curator")
if not isinstance(raw_curator, dict):
raw_curator = {}
- added_curator: List[str] = []
- for k, v in _curator_defaults.items():
- if k not in raw_curator:
- raw_curator[k] = copy.deepcopy(v)
- added_curator.append(k)
+ added_curator = _seed_missing(raw_curator, DEFAULT_CONFIG.get("curator", {}))
if added_curator:
config["curator"] = raw_curator
- touched = True
# (2) auxiliary.curator task slot
- _aux_curator_defaults = (
- DEFAULT_CONFIG.get("auxiliary", {}).get("curator", {})
- )
raw_aux = config.get("auxiliary")
if not isinstance(raw_aux, dict):
raw_aux = {}
raw_aux_curator = raw_aux.get("curator")
if not isinstance(raw_aux_curator, dict):
raw_aux_curator = {}
- added_aux: List[str] = []
- for k, v in _aux_curator_defaults.items():
- if k not in raw_aux_curator:
- raw_aux_curator[k] = copy.deepcopy(v)
- added_aux.append(k)
+ added_aux = _seed_missing(raw_aux_curator, DEFAULT_CONFIG.get("auxiliary", {}).get("curator", {}))
if added_aux:
raw_aux["curator"] = raw_aux_curator
config["auxiliary"] = raw_aux
- touched = True
- if touched:
+ if added_curator or added_aux:
_persist_migration(config)
- if added_curator:
- results["config_added"].append(
- f"curator ({len(added_curator)} default key(s))"
- )
- if not quiet:
- print(
- " ✓ Curator settings now available "
- f"({', '.join(added_curator)}) — edit via `hermes config set`"
- )
- if added_aux:
- results["config_added"].append(
- f"auxiliary.curator ({len(added_aux)} default key(s))"
- )
+ for label, added in (("curator", added_curator), ("auxiliary.curator", added_aux)):
+ if not added:
+ continue
+ results["config_added"].append(f"{label} ({len(added)} default key(s))")
if not quiet:
print(
- " ✓ auxiliary.curator settings now available "
- f"({', '.join(added_aux)}) — edit via `hermes config set`"
+ f" ✓ {'Curator' if label == 'curator' else label} settings now available "
+ f"({', '.join(added)}) — edit via `hermes config set`"
)
def _migrate_to_25(results: Dict[str, Any], quiet: bool) -> None:
- # ── Version 24 → 25: lower model_catalog TTL 24h → 1h ──
- # The model picker now refreshes its curated list hourly so freshly
- # published model-catalog.json deploys reach users without a day-long
- # stale window. Only rewrite the OLD default (24) — never clobber a
- # value the user deliberately customized.
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
+ # ── Version 24 → 25: lower model_catalog TTL 24h → 1h (only the OLD default 24) ──
- config = read_raw_config()
- raw_mc = config.get("model_catalog")
- if isinstance(raw_mc, dict) and raw_mc.get("ttl_hours") == 24:
- raw_mc["ttl_hours"] = 1
- config["model_catalog"] = raw_mc
- _persist_migration(config)
- results["config_added"].append("model_catalog.ttl_hours 24→1")
- if not quiet:
- print(" ✓ Lowered model_catalog.ttl_hours to 1 (hourly picker refresh)")
+ _rewrite_stale_default(
+ results, quiet, section="model_catalog", key="ttl_hours", old=24, new=1,
+ added="model_catalog.ttl_hours 24→1",
+ message=" ✓ Lowered model_catalog.ttl_hours to 1 (hourly picker refresh)",
+ )
def _migrate_to_29(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 28 → 29: rename memory/skills write_mode → write_approval ──
- # The tri-state write_mode (on|off|approve) was replaced by a clear boolean
- # write_approval (default false = gate off, writes flow freely; true =
- # require approval). Only an explicit "approve" carried gating intent, so
- # it maps to true; everything else (on/off/unset) → false. The old
- # "off = block all writes" mode is dropped — memory_enabled: false disables
- # memory entirely. Only rewrite a key the user actually persisted; never
- # invent one.
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
+ # Tri-state write_mode (on|off|approve) → boolean write_approval. Only
+ # "approve" carried gating intent → true; everything else → false (the old
+ # "off = block writes" mode is dropped; memory_enabled: false disables
+ # memory). Only rewrite a key the user actually persisted.
config = read_raw_config()
touched = False
@@ -507,28 +429,15 @@ def _migrate_to_29(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 29 → 30: curator.consolidate defaults to false ──
-# Consolidation (the LLM umbrella-building fork) is opt-in, OFF by default;
-# the deterministic inactivity prune still runs whenever the curator is
-# enabled. No write is needed: the schema default (curator.consolidate=false)
-# is supplied by load_config()'s deep-merge at read time, and persisting a
-# default-valued key would only bloat a lean config (it gets stripped on
-# save anyway). Existing installs that WANT the old always-consolidate
-# behavior set it to true explicitly via `hermes config set`.
-# (No registry entry: this version bump has no migration step.)
+# Schema-default-only change (deep-merge supplies it at read time; persisting
+# a default would only bloat a lean config). No registry entry.
def _migrate_to_31(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 30 → 31: switch verify_on_stop OFF (one-time) ──
- # verify_on_stop defaulted to the "auto" sentinel (surface-aware: on for
- # interactive coding surfaces). In practice the verification narrative was
- # more noise than signal — it even fired on doc/markdown/skill edits with
- # nothing to verify. The new default is OFF. This migration switches
- # existing installs off ONCE, but only when the user never expressed an
- # explicit preference: we rewrite the value only if it's missing or still
- # the "auto" sentinel. An explicit true/false the user set is preserved.
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
+ # The "auto" sentinel (surface-aware) was more noise than signal; the new
+ # default is OFF. Rewrite only when missing or still "auto" — an explicit
+ # true/false the user set is preserved.
config = read_raw_config()
raw_agent = config.get("agent")
@@ -554,47 +463,29 @@ def _migrate_to_31(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_32(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 31 → 32: flip the BAKED-IN literal true to OFF (one-time) ──
- # The v30→v31 flip above only caught missing/"auto" values. But the very
- # first ship of verify-on-stop (config v30, commit 2f1a47b90) defaulted
- # DEFAULT_CONFIG["agent"]["verify_on_stop"] to a literal True, and
- # migrate_config persists defaults with strip_defaults=False — so every
- # install that updated through v30 got `verify_on_stop: true` written into
- # config.yaml as a literal. v31's guard deliberately preserves an explicit
- # bool, so it skipped that whole population and left them ON. That literal
- # true was never a user choice: the feature had no off-switch worth setting
- # it against until v31 introduced one, so a true persisted before v32 is
- # always the old machine default. Flip it off once here. A true the user
- # sets AFTER v32 (config already at version 32) is never touched.
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
-
- config = read_raw_config()
- raw_agent = config.get("agent")
- if isinstance(raw_agent, dict) and raw_agent.get("verify_on_stop") is True:
- raw_agent["verify_on_stop"] = False
- config["agent"] = raw_agent
- _persist_migration(config)
- results["config_added"].append("agent.verify_on_stop=false")
- if not quiet:
- print(
- " ✓ Turned off verify-on-stop (agent.verify_on_stop: false) — "
- "the old default was written into your config as a literal "
- "true. Set it to true again to re-enable, or \"auto\" for the "
- "legacy surface-aware behavior."
- )
+ # v31 only caught missing/"auto". The first ship (v30) defaulted
+ # verify_on_stop to a literal True and migrate_config persisted defaults,
+ # so every install that updated through v30 has `verify_on_stop: true`
+ # written literally — never a user choice (there was no off-switch until
+ # v31). Flip it once; a true set AFTER v32 is never touched.
+
+ _rewrite_stale_default(
+ results, quiet, section="agent", key="verify_on_stop", old=True, new=False,
+ added="agent.verify_on_stop=false",
+ message=(
+ " ✓ Turned off verify-on-stop (agent.verify_on_stop: false) — "
+ "the old default was written into your config as a literal "
+ "true. Set it to true again to re-enable, or \"auto\" for the "
+ "legacy surface-aware behavior."
+ ),
+ extra_guard=lambda raw: raw.get("verify_on_stop") is True,
+ )
def _migrate_to_33(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 32 → 33: unify delegation concurrency caps ──
- # delegation.max_async_children is deprecated: max_concurrent_children now
- # caps both a single batch's parallelism and concurrent background
- # delegation units. Fold a raised max_async_children into
- # max_concurrent_children (take the max so nobody loses headroom), then
- # drop the stale key.
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
+ # max_async_children is deprecated; fold a raised value into
+ # max_concurrent_children (take the max so nobody loses headroom), drop it.
config = read_raw_config()
raw_deleg = config.get("delegation")
@@ -626,25 +517,16 @@ def _migrate_to_33(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_34(results: Dict[str, Any], quiet: bool) -> None:
- # ── Version 33 → 34: one-time personality reset (post-#81946 unification) ──
- # Personality persistence used to be split per surface: the TUI/desktop
- # wrote the NAME to display.personality while the CLI/gateway wrote the
- # rendered TEXT into agent.system_prompt (and their "/personality none"
- # only blanked the text, leaving the name behind). When #81946 made
- # display.personality authoritative everywhere, stale names written years
- # ago resurrected personalities users had already turned off ("kawaii
- # defaults on after updating"). There is no way to know which of the two
- # divergent fields reflects the user's intent, so reset the selection to
- # none once and tell the user how to re-enable it. Two scrubs:
- #
+ # ── Version 33 → 34: one-time personality reset (post-unification) ──
+ # Persistence used to be split: TUI/desktop wrote the NAME to
+ # display.personality, CLI/gateway wrote rendered TEXT to agent.system_prompt
+ # (and "/personality none" only blanked the text). Once display.personality
+ # became authoritative, stale names resurrected personalities users had
+ # turned off. Neither field is trustworthy, so reset once:
# 1. display.personality → "" (announce the old name).
- # 2. agent.system_prompt → "" ONLY when it verbatim-equals the rendered
- # text of a known personality — that shape was written by the old
- # CLI/gateway /personality, never typed by hand. Any other text is a
- # user-owned manual prompt and is never touched.
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
+ # 2. agent.system_prompt → "" ONLY when it verbatim-equals a known
+ # personality's rendered text (written by the old /personality, never
+ # typed by hand). Any other text is a user-owned prompt, never touched.
from hermes_cli.personality import (
available_personalities,
@@ -701,18 +583,9 @@ def _migrate_to_34(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_35(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 34 → 35: background process notifications → concise ──
- # The old default mode 'all' pushed the raw output tail of every finished
- # background process into the chat ("[Background process proc_x finished
- # with exit code 0~ Here's the final output: ...]" walls). The new
- # 'concise' mode renders a one-line status message instead (with a short
- # output tail on failures) and is the new default. Move users still on
- # 'all' — the old implicit default, almost never chosen on purpose — to
- # 'concise'. Explicit non-default choices (result / error / off) are the
- # user's own and are preserved. Users with the key unset inherit the new
- # default automatically at read time (no write needed).
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
+ # 'all' (old implicit default, rarely chosen on purpose) dumped raw output
+ # walls into chat; 'concise' is the new default. Move 'all' → 'concise';
+ # explicit result/error/off choices are preserved; unset inherits at read.
config = read_raw_config()
raw_display = config.get("display")
@@ -737,71 +610,41 @@ def _migrate_to_35(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_36(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 35 → 36: raise the subagent iteration cap default 50 → 250 ──
- # delegation.max_iterations is the per-subagent tool-call budget. The old
- # default of 50 truncated substantial delegated work (leaf agents spend
- # ~15-20 turns on recon before producing output, then ran out mid-task).
- # The shipped default is now 250. Configs still pinned at exactly the old
- # default 50 — almost always the inherited default rather than a deliberate
- # choice — are lifted to 250 so existing installs get the same headroom on
- # update. Any OTHER explicit value (a deliberate override, high or low) is
- # the user's own and is preserved; unset inherits 250 at read time.
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
-
- config = read_raw_config()
- raw_deleg = config.get("delegation")
- if isinstance(raw_deleg, dict) and raw_deleg.get("max_iterations") == 50:
- raw_deleg["max_iterations"] = 250
- config["delegation"] = raw_deleg
- _persist_migration(config)
- results["config_added"].append("delegation.max_iterations=250 (was: 50)")
- if not quiet:
- print(
- " ✓ Raised delegation.max_iterations from 50 to 250 — subagents "
- "now get a larger per-child tool-call budget so delegated work "
- "finishes instead of truncating. Set delegation.max_iterations "
- "back to 50 to restore the old cap."
- )
+ # 50 truncated substantial delegated work; only a value still pinned at
+ # exactly the old default is lifted. Other explicit values are preserved.
+
+ _rewrite_stale_default(
+ results, quiet, section="delegation", key="max_iterations", old=50, new=250,
+ added="delegation.max_iterations=250 (was: 50)",
+ message=(
+ " ✓ Raised delegation.max_iterations from 50 to 250 — subagents "
+ "now get a larger per-child tool-call budget so delegated work "
+ "finishes instead of truncating. Set delegation.max_iterations "
+ "back to 50 to restore the old cap."
+ ),
+ )
def _migrate_to_37(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 36 → 37: raise the delegation concurrency default 3 → 10 ──
- # delegation.max_concurrent_children caps how many children run in parallel
- # per batch (and concurrent background delegation units). The old default of
- # 3 needlessly serialized independent fan-outs (e.g. reviewing N PRs at
- # once). The shipped default is now 10, which stays at/below the high-cost
- # warning threshold. Configs still pinned at exactly the old default 3 —
- # almost always the inherited default rather than a deliberate choice — are
- # lifted to 10 so existing installs get the wider fan-out on update. Any
- # OTHER explicit value (a deliberate override) is preserved; unset inherits
- # 10 at read time.
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
-
- config = read_raw_config()
- raw_deleg = config.get("delegation")
- if isinstance(raw_deleg, dict) and raw_deleg.get("max_concurrent_children") == 3:
- raw_deleg["max_concurrent_children"] = 10
- config["delegation"] = raw_deleg
- _persist_migration(config)
- results["config_added"].append("delegation.max_concurrent_children=10 (was: 3)")
- if not quiet:
- print(
- " ✓ Raised delegation.max_concurrent_children from 3 to 10 — "
- "independent delegated children now fan out wider in parallel. "
- "Each child consumes API tokens independently; set "
- "delegation.max_concurrent_children back to 3 to restore the old cap."
- )
+ # 3 serialized independent fan-outs; 10 stays at/below the high-cost
+ # warning threshold. Only a value still pinned at exactly 3 is lifted.
+
+ _rewrite_stale_default(
+ results, quiet, section="delegation", key="max_concurrent_children", old=3, new=10,
+ added="delegation.max_concurrent_children=10 (was: 3)",
+ message=(
+ " ✓ Raised delegation.max_concurrent_children from 3 to 10 — "
+ "independent delegated children now fan out wider in parallel. "
+ "Each child consumes API tokens independently; set "
+ "delegation.max_concurrent_children back to 3 to restore the old cap."
+ ),
+ )
def _migrate_to_38(results: Dict[str, Any], quiet: bool) -> None:
# Version 37 → 38: the bundled observability/nemo_relay plugin was
# removed when Relay lifecycle ownership moved into the agent core.
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
from hermes_cli.relay_plugin_cutover import legacy_relay_plugin_keys
@@ -829,16 +672,9 @@ def _migrate_to_38(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_39(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 38 → 39: remove the retired `bfl` toolset from saved lists ──
- # The six bfl_flux3_* core tools shipped for a free FLUX 3 promotional
- # period that has since ended server-side, leaving every Nous-signed-in
- # install paying ~2.7K tokens of schema per API call for tools that can
- # only refuse. They were removed in favor of the standard video_gen
- # provider surface (`video_generate`, `hermes tools` → Video Generation).
- # Strip the toolset key wherever the auto-backfill or a picker save wrote
- # it, so stale config can't resurrect an unknown toolset.
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
+ # The FLUX 3 promo tools were removed in favor of the video_gen provider
+ # surface; strip the key wherever a backfill/picker save wrote it so stale
+ # config can't resurrect an unknown toolset.
config = read_raw_config()
changed = False
@@ -865,24 +701,15 @@ def _migrate_to_39(results: Dict[str, Any], quiet: bool) -> None:
def _migrate_to_40(results: Dict[str, Any], quiet: bool) -> None:
# ── Version 39 → 40: model_catalog.ttl_hours → ttl_minutes (default 20) ──
- # The picker catalogs now refresh every 20 minutes (and the gateway
- # refreshes them in the background on that cadence). Only the OLD default
- # (ttl_hours: 1, written by the v25 migration) is dropped so the new
- # default applies; any other explicit ttl_hours is a deliberate choice
- # and stays honoured by the loader.
- _c = _cfg()
- read_raw_config = _c.read_raw_config
- _persist_migration = _c._persist_migration
-
- config = read_raw_config()
- raw_mc = config.get("model_catalog")
- if isinstance(raw_mc, dict) and raw_mc.get("ttl_hours") == 1 and "ttl_minutes" not in raw_mc:
- del raw_mc["ttl_hours"]
- config["model_catalog"] = raw_mc
- _persist_migration(config)
- results["config_added"].append("model_catalog.ttl_hours 1 → ttl_minutes 20 (default)")
- if not quiet:
- print(" ✓ Model catalog now refreshes every 20 minutes (model_catalog.ttl_minutes)")
+ # Only the OLD default (ttl_hours: 1, written by v25) is dropped; any other
+ # explicit ttl_hours is a deliberate choice the loader still honours.
+
+ _rewrite_stale_default(
+ results, quiet, section="model_catalog", key="ttl_hours", old=1, new=None,
+ added="model_catalog.ttl_hours 1 → ttl_minutes 20 (default)",
+ message=" ✓ Model catalog now refreshes every 20 minutes (model_catalog.ttl_minutes)",
+ extra_guard=lambda raw: "ttl_minutes" not in raw,
+ )
#: Registry of (target_version, migration_fn), strictly ascending. The driver
@@ -919,14 +746,10 @@ MIGRATIONS: Tuple[Tuple[int, Callable[[Dict[str, Any], bool], None]], ...] = (
def run_migrations(current_ver: int, results: Dict[str, Any], quiet: bool) -> None:
"""Apply every registered migration whose target version exceeds *current_ver*.
- Replicates the original ladder's semantics exactly: *current_ver* is the
- on-disk schema version captured ONCE (via ``check_config_version()``)
- before any step runs, and it does not advance between steps — each step
- is gated on the same initial value, exactly like the original sequential
- ``if current_ver < N:`` blocks. Steps run in strict ascending registry
- order and mutate ``results`` in place. The final ``_config_version`` bump
- is NOT performed here; it stays in ``migrate_config`` (persisted once,
- after the informational missing-config scan), matching the original flow.
+ Replicates the original ladder's semantics exactly: *current_ver* is the on-disk schema version
+ captured ONCE (via ``check_config_version()``) before any step runs, and it does not advance
+ between steps — each step is gated on the same initial value, exactly like the original
+ sequential ``if current_ver < N:`` blocks.
"""
for target_ver, migration_fn in MIGRATIONS:
if current_ver < target_ver:
diff --git a/hermes_cli/env_loader.py b/hermes_cli/env_loader.py
index a0e1fbfd95a..a7fe72e20bf 100644
--- a/hermes_cli/env_loader.py
+++ b/hermes_cli/env_loader.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import codecs
import io
+import logging
import os
import sys
import threading
@@ -12,6 +13,7 @@ from pathlib import Path
from dotenv import load_dotenv
from utils import atomic_replace, fast_safe_load
+logger = logging.getLogger(__name__)
# Env var name suffixes that indicate credential values. These are the
# only env vars whose values we sanitize on load — we must not silently
@@ -56,20 +58,6 @@ _SECRET_SOURCE_CACHE_LOCK = threading.RLock()
_SCOPED_SKIP_LOGGED: set[str] = set()
-def _known_hermes_env_keys() -> set[str]:
- """Return the combined set of known Hermes env-var keys.
-
- Includes both ``OPTIONAL_ENV_VARS`` (setup-flow vars with metadata) and
- ``_EXTRA_ENV_KEYS`` (provider/platform keys managed outside the setup
- wizard). Lazy-imported to avoid circular-dependency during early-bootstrap
- ``load_hermes_dotenv()`` calls.
- """
- from hermes_cli.config import _EXTRA_ENV_KEYS
- from hermes_cli.config_defaults import OPTIONAL_ENV_VARS
-
- return set(OPTIONAL_ENV_VARS.keys()) | set(_EXTRA_ENV_KEYS)
-
-
# Behavioral routing keys a parent Hermes process injects into child env and
# that silently redirect a profile onto the wrong provider path (ACP auth
# method, copilot-ACP endpoints). These — and ONLY these — are scrubbed from
@@ -90,10 +78,9 @@ _PROFILE_MANAGED_ENV_KEYS: frozenset[str] = frozenset({
def _env_keys_defined_in_dotenv(path: Path) -> set[str]:
"""Return KEY names assigned in a dotenv file (including empty ``KEY=``).
- Uses a fast line scanner rather than full dotenv parsing so it works
- during early bootstrap without importing python-dotenv. Ignores comment
- and blank lines. Non-ASCII encoding errors fall back to ``latin-1``,
- matching ``_load_dotenv_with_fallback``.
+ A fast line scanner rather than full dotenv parsing, so it works during early bootstrap
+ without importing python-dotenv. Non-ASCII decode errors fall back to ``latin-1``, matching
+ ``_load_dotenv_with_fallback``.
"""
keys: set[str] = set()
try:
@@ -107,9 +94,7 @@ def _env_keys_defined_in_dotenv(path: Path) -> set[str]:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
- if line.startswith("export "):
- line = line[7:]
- key = line.split("=", 1)[0].strip()
+ key = line.removeprefix("export ").split("=", 1)[0].strip()
if key:
keys.add(key)
return keys
@@ -118,28 +103,13 @@ def _env_keys_defined_in_dotenv(path: Path) -> set[str]:
def _clear_known_keys_missing_from_dotenv(path: Path) -> None:
"""Remove inherited profile-managed Hermes keys absent from ``.env``.
- After the profile's ``.env`` has been loaded with ``override=True``,
- scan the file for which profile-managed keys it explicitly defines and
- delete any such key that exists in ``os.environ`` but is *not* present
- in the file.
-
- Scope is deliberately NARROW: only ``_PROFILE_MANAGED_ENV_KEYS`` —
- behavioral routing keys (ACP auth method, copilot-ACP endpoints) that a
- parent Hermes process injects and that silently change *which provider
- path* a profile uses. Provider API keys (OPENAI_API_KEY, …) are
- intentionally excluded: users legitimately export those in their shell
- (``export OPENAI_API_KEY=…`` is a documented flow — see
- ``tests/hermes_cli/test_dump_env_visibility.py``), and a startup scrub
- cannot distinguish a shell export from parent-process leakage. Clearing
- the full known-key set would delete user-exported credentials on every
- ``hermes`` invocation.
-
- Cross-profile *credential* isolation is handled at read time by
- ``agent.secret_scope.get_secret`` (scope authoritative under
- multiplexing), not by mutating ``os.environ`` here.
-
- Does **not** run when the ``.env`` file does not exist (bare-profile
- case, which follows ``#66930`` / ``#67027`` semantics).
+ After the profile's ``.env`` has been loaded with ``override=True``, scan the file for which
+ profile-managed keys it explicitly defines and delete any such key that exists in ``os.environ``
+ but is *not* present in the file.
+
+ Scope is deliberately NARROW: only ``_PROFILE_MANAGED_ENV_KEYS`` — behavioral routing keys (ACP
+ auth method, copilot-ACP endpoints) that a parent Hermes process injects and that silently
+ change *which provider path* a profile uses.
"""
if not path.exists():
return
@@ -152,12 +122,10 @@ def _clear_known_keys_missing_from_dotenv(path: Path) -> None:
def get_secret_source(env_var: str) -> str | None:
"""Return the label of the secret source that supplied ``env_var``, if any.
- Returns ``"bitwarden"`` for keys pulled from Bitwarden Secrets Manager
- during the current process's ``load_hermes_dotenv()`` call. Returns
- ``None`` for keys that came from ``.env``, the shell environment, or
- aren't tracked. The returned label is metadata only: credential-pool
- persistence may store it to explain the origin of a borrowed secret, but
- must never treat it as authorization to persist the raw value.
+ ``"bitwarden"`` for keys pulled during this process's ``load_hermes_dotenv()``; ``None`` for
+ ``.env``/shell keys. The label is metadata only -- credential-pool persistence may store it to
+ explain a borrowed secret's origin but must never treat it as authorization to persist the
+ raw value.
"""
return _SECRET_SOURCES.get(env_var)
@@ -175,15 +143,13 @@ def hydrate_profile_secret_sources(
) -> dict[str, str]:
"""Resolve one profile's configured sources without mutating ``os.environ``.
- Multiplex gateways can route a first turn to a secondary profile that has
- never run the process-global dotenv startup path. Resolve that profile's
- sources against a private mapping seeded from its own ``.env`` and record
- the usual per-home snapshot for ``build_profile_secret_scope()``.
+ Multiplex gateways can route a first turn to a secondary profile that has never run the process-
+ global dotenv startup path. Resolve that profile's sources against a private mapping seeded from
+ its own ``.env`` and record the usual per-home snapshot for ``build_profile_secret_scope()``.
- Fail-open and once-per-home semantics intentionally mirror
- ``_apply_external_secret_sources``. The returned mapping contains only
- values actually contributed by external sources, never the profile's
- plaintext ``.env`` entries.
+ Fail-open and once-per-home semantics intentionally mirror ``_apply_external_secret_sources``.
+ The returned mapping contains only values actually contributed by external sources, never the
+ profile's plaintext ``.env`` entries.
"""
with _SECRET_SOURCE_CACHE_LOCK:
return _hydrate_profile_secret_sources(Path(hermes_home))
@@ -245,12 +211,8 @@ def _hydrate_profile_secret_sources(home: Path) -> dict[str, str]:
def reset_secret_source_cache() -> None:
"""Forget which HERMES_HOME paths have already had external secrets applied.
- The first call to ``_apply_external_secret_sources(home_path)`` in a
- process pulls from Bitwarden (or other configured backend), records the
- applied keys in ``_SECRET_SOURCES``, and remembers ``home_path`` so
- subsequent calls in the same process are no-ops. Call this to force the
- next call to re-pull — useful for tests, and for long-running processes
- that want to refresh after a config change.
+ ``_apply_external_secret_sources(home_path)`` pulls once per process and then no-ops for that
+ home; call this to force a re-pull (tests, long-running processes after a config change).
"""
_APPLIED_HOMES.clear()
_SECRET_SOURCES.clear()
@@ -260,10 +222,8 @@ def reset_secret_source_cache() -> None:
def format_secret_source_suffix(env_var: str) -> str:
"""Return a human-readable suffix like ``" (from Bitwarden)"`` or ``""``.
- Use this when printing a detected credential so the user can see where
- it came from. Empty string when the credential came from ``.env`` or
- the shell — those are the implicit / "default" cases users already
- understand.
+ Empty for ``.env``/shell credentials -- those are the implicit default cases users already
+ understand, so only external sources get called out.
"""
source = get_secret_source(env_var)
if not source:
@@ -302,23 +262,15 @@ def _format_offending_chars(value: str, limit: int = 3) -> str:
def _sanitize_loaded_credentials() -> None:
"""Strip non-ASCII characters from credential env vars in os.environ.
- Called after dotenv loads so the rest of the codebase never sees
- non-ASCII API keys. Only touches env vars whose names end with
- known credential suffixes (``_API_KEY``, ``_TOKEN``, etc.).
-
- Emits a one-line warning to stderr when characters are stripped.
- Silent stripping would mask copy-paste corruption (Unicode lookalike
- glyphs from PDFs / rich-text editors, ZWSP from web pages) as opaque
- provider-side "invalid API key" errors (see #6843).
+ Called after dotenv loads so the rest of the codebase never sees non-ASCII API keys. Only
+ touches env vars whose names end with known credential suffixes (``_API_KEY``, ``_TOKEN``,
+ etc.).
"""
for key, value in list(os.environ.items()):
if not any(key.endswith(suffix) for suffix in _CREDENTIAL_SUFFIXES):
continue
- try:
- value.encode("ascii")
+ if value.isascii():
continue
- except UnicodeEncodeError:
- pass
cleaned = value.encode("ascii", errors="ignore").decode("ascii")
os.environ[key] = cleaned
if key in _WARNED_KEYS:
@@ -367,18 +319,13 @@ def _load_dotenv_with_fallback(path: Path, *, override: bool) -> None:
def _sanitize_env_file_if_needed(path: Path) -> None:
"""Pre-sanitize a .env file before python-dotenv reads it.
- Strips embedded null bytes which crash ``os.environ[k] = v``
- with ``ValueError: embedded null byte`` — typically introduced by
- copy-pasting API keys from terminals or rich-text editors.
+ Encoding: sniffs a leading BOM *before* any text decode. UTF-16 (Notepad "Unicode") is decoded
+ correctly and rewritten as clean UTF-8. UTF-32 is refused (left untouched) so we never fall
+ through to the errors=replace corruption path. Order of BOM checks matters: UTF-32-LE's BOM
+ starts with UTF-16-LE's FF FE.
- Encoding: sniffs a leading BOM *before* any text decode. UTF-16
- (Notepad "Unicode") is decoded correctly and rewritten as clean
- UTF-8. UTF-32 is refused (left untouched) so we never fall through
- to the errors=replace corruption path. Order of BOM checks matters:
- UTF-32-LE's BOM starts with UTF-16-LE's FF FE.
-
- ``hermes_cli.config._sanitize_env_lines`` normalizes line endings while
- treating content after the first ``=`` as opaque for boundary discovery.
+ ``hermes_cli.config._sanitize_env_lines`` normalizes line endings while treating content after
+ the first ``=`` as opaque for boundary discovery.
"""
if not path.exists():
return
@@ -403,9 +350,7 @@ def _sanitize_env_file_if_needed(path: Path) -> None:
path_key = str(path.resolve())
if path_key not in _WARNED_UTF32_PATHS:
_WARNED_UTF32_PATHS.add(path_key)
- import logging
-
- logging.getLogger(__name__).warning(
+ logger.warning(
"Skipping .env sanitize for %s: UTF-32 BOM detected; "
"leaving file untouched to avoid corruption",
path,
@@ -479,17 +424,9 @@ def load_hermes_dotenv(
) -> list[Path]:
"""Load Hermes environment files with user config taking precedence.
- Behavior:
- - `~/.hermes/.env` overrides stale shell-exported values when present.
- - project `.env` acts as a dev fallback and only fills missing values when
- the user env exists.
- - if no user env exists, the project `.env` also overrides stale shell vars.
- - callers that only maintain the installation can set
- ``load_external_secrets=False`` to avoid loading optional secret-manager
- dependencies into the process that replaces that same environment.
- - routed multiplex profile loads hydrate external sources into the
- profile's private secret snapshot without mutating the shared process
- environment; unscoped startup loads retain the normal behavior above.
+ Behavior: - `~/.hermes/.env` overrides stale shell-exported values when present. - project
+ `.env` acts as a dev fallback and only fills missing values when the user env exists. - if no
+ user env exists, the project `.env` also overrides stale shell vars.
"""
home_path = Path(hermes_home or os.getenv("HERMES_HOME", Path.home() / ".hermes"))
@@ -508,9 +445,7 @@ def load_hermes_dotenv(
home_key = str(home_path.resolve())
if home_key not in _SCOPED_SKIP_LOGGED:
_SCOPED_SKIP_LOGGED.add(home_key)
- import logging
-
- logging.getLogger(__name__).debug(
+ logger.debug(
"multiplex: skipping process-global dotenv load for routed "
"profile home %s (credentials resolve via the profile scope)",
home_path,
@@ -594,19 +529,10 @@ def load_hermes_dotenv(
def _reapply_terminal_config_bridge(home_path: Path) -> None:
"""Re-assert config.yaml's explicit ``terminal.*`` keys over reloaded .env.
- Delegates to ``hermes_cli.config.apply_terminal_config_to_env`` — the
- single shared bridge (same one terminal_tool's fallback and the TUI/
- dashboard launchers use) — so key coverage, explicit-keys-only override
- semantics, cwd placeholder handling, and the managed-scope overlay can't
- drift from the other bridge sites. Only keys the user actually wrote in
- config.yaml's ``terminal`` section override env values; a config.yaml
- without a terminal section leaves .env/shell selections untouched.
-
- Scoped to the process HERMES_HOME: the shared bridge reads the
- process-global config, so re-applying it for a *different* profile's
- ``load_hermes_dotenv(hermes_home=...)`` call would bridge the wrong
- profile's config. Fail-open — a config problem must never break dotenv
- loading (the historical env-driven behavior still applies).
+ Delegates to ``hermes_cli.config.apply_terminal_config_to_env`` — the single shared bridge (same
+ one terminal_tool's fallback and the TUI/ dashboard launchers use) — so key coverage, explicit-
+ keys-only override semantics, cwd placeholder handling, and the managed-scope overlay can't
+ drift from the other bridge sites.
"""
try:
if Path(home_path).resolve() != _process_hermes_home().resolve():
@@ -621,19 +547,12 @@ def _reapply_terminal_config_bridge(home_path: Path) -> None:
def _apply_managed_env() -> None:
"""Apply the managed-scope .env last, with override, so it beats user/shell.
- Managed scope is machine-global (independent of HERMES_HOME / profile). v1
- enforcement is "applied last with override=True" — at the end of startup load
- ``os.environ`` holds the managed value for every managed key, beating both the
- user ``.env`` and any pre-existing shell export. This deliberately inverts the
- usual env-over-config precedence for the pinned keys (see
- ``docs/design/managed-scope.md`` §4.1).
-
- This does NOT prevent the agent from later mutating ``os.environ`` in-process
- or ``export``-ing in a subprocess shell; that hard boundary is a documented
- v2 item (design §8.1). v1 relies on filesystem permissions only.
+ This does NOT prevent the agent from later mutating ``os.environ`` in-process or ``export``-ing
+ in a subprocess shell; that hard boundary is a documented v2 item (design §8.1). v1 relies on
+ filesystem permissions only.
- Fail-open: a missing managed dir or .env is the common case and a no-op; any
- error here is swallowed so managed scope can never block startup.
+ Fail-open: a missing managed dir or .env is the common case and a no-op; any error here is
+ swallowed so managed scope can never block startup.
"""
try:
from hermes_cli import managed_scope
@@ -653,25 +572,14 @@ def _apply_managed_env() -> None:
def _apply_external_secret_sources(home_path: Path) -> None:
"""Pull secrets from every enabled external source into env.
- Runs AFTER dotenv loads so .env values are visible (sources use them
- to locate bootstrap tokens) but BEFORE the rest of Hermes reads
- ``os.environ`` for credentials. Any failure here is logged and
- swallowed — external secret sources must never block startup.
-
- The heavy lifting (source ordering, mapped-beats-bulk precedence,
- first-claim-wins conflict handling, override semantics, provenance)
- lives in ``agent.secret_sources.registry.apply_all``; this wrapper
- owns the once-per-HERMES_HOME guard, the post-apply ASCII
- sanitization sweep, the ``_SECRET_SOURCES`` provenance map that
- UI surfaces read, and the startup status lines.
-
- Idempotent within a process: subsequent calls for the same
- ``home_path`` are no-ops. ``load_hermes_dotenv()`` runs at import
- time from several hot modules (cli.py, hermes_cli/main.py,
- run_agent.py, trajectory_compressor.py, ...), so without this guard
- the status lines would print 3-5x per CLI startup. Use
- ``reset_secret_source_cache()`` if you need to force a re-pull
- (tests, long-running processes after a config change).
+ Runs AFTER dotenv loads so .env values are visible (sources use them to locate bootstrap tokens)
+ but BEFORE the rest of Hermes reads ``os.environ`` for credentials. Any failure here is logged
+ and swallowed — external secret sources must never block startup.
+
+ The heavy lifting (source ordering, mapped-beats-bulk precedence, first-claim-wins conflict
+ handling, override semantics, provenance) lives in ``agent.secret_sources.registry.apply_all``;
+ this wrapper owns the once-per-HERMES_HOME guard, the post-apply ASCII sanitization sweep, the
+ ``_SECRET_SOURCES`` provenance map that UI surfaces read, and the startup status lines.
"""
home_key = str(Path(home_path).resolve())
if home_key in _APPLIED_HOMES:
@@ -776,9 +684,8 @@ def _remediation_hint(
) -> str:
"""Ask the failed source for its one-line fix-it hint.
- Defensive wrapper: remediation() is a pure mapping and shouldn't
- raise, but a plugin source could — and startup must never break on
- a status line.
+ Defensive wrapper: remediation() is a pure mapping and shouldn't raise, but a plugin source
+ could — and startup must never break on a status line.
"""
try:
from agent.secret_sources.registry import get_source
@@ -796,8 +703,8 @@ def _remediation_hint(
def _load_secrets_config(home_path: Path) -> dict:
"""Read just the ``secrets:`` section out of config.yaml.
- Imported lazily and isolated from the main config loader so a
- malformed config can't take down dotenv loading entirely.
+ Imported lazily and isolated from the main config loader so a malformed config can't take down
+ dotenv loading entirely.
"""
config_path = home_path / "config.yaml"
if not config_path.exists():
@@ -817,10 +724,6 @@ def _load_secrets_config(home_path: Path) -> dict:
return data.get("secrets") or {}
except Exception:
pass
- try:
- import yaml # type: ignore
- except ImportError:
- return {}
try:
with open(config_path, "r", encoding="utf-8") as f:
data = fast_safe_load(f) or {}
diff --git a/hermes_cli/fallback_config.py b/hermes_cli/fallback_config.py
index 2cce7a2d373..b80e5ca4bd1 100644
--- a/hermes_cli/fallback_config.py
+++ b/hermes_cli/fallback_config.py
@@ -14,18 +14,11 @@ def _normalized_base_url(value: Any) -> str:
def resolve_entry_api_key(entry: dict[str, Any] | None) -> str | None:
"""API key for one fallback entry: inline ``api_key``, else ``key_env``.
- Mirrors the custom-provider convention (``key_env`` names the env var
- holding the key; ``api_key_env`` accepted as an alias). Returns None when
- neither yields a non-empty value, letting ``resolve_runtime_provider``
- fall through to the provider's standard credential resolution.
-
- ``key_env`` is resolved through ``agent.secret_scope.get_secret`` rather
- than a raw ``os.getenv`` — in a multiplexed gateway a bare env read would
- ignore the active profile's scope and can return another profile's
- credential. ``get_secret`` already implements the right fallback: it
- reads ``os.environ`` when there's no active multiplexed scope (matching
- prior single-profile behavior), and fails closed only when multiplexing
- is active with no scope installed.
+ Mirrors the custom-provider convention (``api_key_env`` accepted as alias); None when neither
+ yields a value so ``resolve_runtime_provider`` falls through to standard credential resolution.
+ ``key_env`` goes through ``agent.secret_scope.get_secret``, not raw ``os.getenv``: in a
+ multiplexed gateway a bare env read ignores the active profile's scope and can return another
+ profile's credential.
"""
if not isinstance(entry, dict):
return None
@@ -80,10 +73,10 @@ def _entry_identity(entry: dict[str, Any]) -> tuple[str, str, str]:
def get_fallback_chain(config: dict[str, Any] | None) -> list[dict[str, Any]]:
"""Return the effective fallback chain merged across old and new config keys.
- ``fallback_providers`` remains the primary source of truth and keeps its
- order. Legacy ``fallback_model`` entries are appended afterwards unless
- they target the same provider/model/base_url route as an earlier entry.
- The returned list always contains fresh dict copies.
+ ``fallback_providers`` remains the primary source of truth and keeps its order. Legacy
+ ``fallback_model`` entries are appended afterwards unless they target the same
+ provider/model/base_url route as an earlier entry. The returned list always contains fresh dict
+ copies.
"""
config = config or {}
diff --git a/hermes_cli/mcp_config.py b/hermes_cli/mcp_config.py
index 05adb6bf5be..df6069510f2 100644
--- a/hermes_cli/mcp_config.py
+++ b/hermes_cli/mcp_config.py
@@ -1,12 +1,4 @@
-"""
-MCP Server Management CLI — ``hermes mcp`` subcommand.
-
-Implements ``hermes mcp add/remove/list/test/configure`` for interactive
-MCP server lifecycle management (issue #690 Phase 2).
-
-Relies on tools/mcp_tool.py for connection/discovery and keeps
-configuration in ~/.hermes/config.yaml under the ``mcp_servers`` key.
-"""
+"""MCP Server Management CLI — ``hermes mcp`` subcommand."""
import asyncio
import logging
@@ -85,18 +77,27 @@ def _get_mcp_servers(config: Optional[dict] = None) -> Dict[str, dict]:
return servers
+def _tool_filters(cfg: dict) -> Tuple[Optional[list], Optional[list]]:
+ """Return the ``(include, exclude)`` tool lists from a server config (non-empty lists only)."""
+ tools_cfg = cfg.get("tools", {})
+ if not isinstance(tools_cfg, dict):
+ return None, None
+ include = tools_cfg.get("include")
+ exclude = tools_cfg.get("exclude")
+ return (
+ include if include and isinstance(include, list) else None,
+ exclude if exclude and isinstance(exclude, list) else None,
+ )
+
+
def _save_mcp_server(name: str, server_config: dict) -> bool:
"""Add or update a server entry in config.yaml.
- Returns False when a high-signal exfiltration-shaped stdio command is
- rejected. MCP stdio servers are user-chosen local commands, so this blocks
- shell+egress payloads rather than whitelisting command families.
+ Returns False when a high-signal exfiltration-shaped stdio command is rejected. stdio servers
+ are user-chosen local commands, so this blocks shell+egress payloads rather than whitelisting
+ command families.
"""
- issues = validate_mcp_server_entry(name, server_config)
- if issues:
- for issue in issues:
- _warning(issue)
- _warning(f"Server '{name}' was NOT saved due to suspicious configuration.")
+ if not _validate_or_warn(name, server_config):
return False
config = load_config()
config.setdefault("mcp_servers", {})[name] = server_config
@@ -104,6 +105,26 @@ def _save_mcp_server(name: str, server_config: dict) -> bool:
return True
+def _validate_or_warn(name: str, server_config: dict) -> bool:
+ """Print every suspicious-config issue as a warning; True when the entry is clean."""
+ issues = validate_mcp_server_entry(name, server_config)
+ for issue in issues:
+ _warning(issue)
+ if issues:
+ _warning(f"Server '{name}' was NOT saved due to suspicious configuration.")
+ return not issues
+
+
+def _lookup_server(name: str, servers: Dict[str, dict], available_label: str = "Available servers") -> Optional[dict]:
+ """Return the named server config, or print the not-found hint and return None."""
+ if name in servers:
+ return servers[name]
+ _error(f"Server '{name}' not found in config.")
+ if servers:
+ _info(f"{available_label}: {', '.join(servers)}")
+ return None
+
+
def _remove_mcp_server(name: str) -> bool:
"""Remove a server from config.yaml. Returns True if it existed."""
config = load_config()
@@ -120,16 +141,9 @@ def _remove_mcp_server(name: str) -> bool:
def _replace_mcp_servers(servers: Dict[str, dict]) -> Tuple[bool, List[str]]:
"""Replace the WHOLE ``mcp_servers`` map in config.yaml.
- Unlike ``_save_mcp_server`` (per-key upsert), this sets the entire map so
- the GUI's mcp.json editor can delete servers, drop an ``enabled: false``
- flag (re-enable), or remove nested fields and have those *removals* land on
- disk. A plain ``/api/config`` deep-merge can only add/override keys, never
- delete them — which is why edits appeared to succeed but the old entry
- survived (see MCP tab persistence bug).
-
- Every entry is validated up front; on any suspicious command/args the whole
- save is rejected (returns ``(False, issues)``) so a bad paste can't be
- partially applied. An empty map removes the key entirely.
+ Every entry is validated up front; on any suspicious command/args the whole save is rejected
+ (returns ``(False, issues)``) so a bad paste can't be partially applied. An empty map removes
+ the key entirely.
"""
issues: List[str] = []
for name, cfg in servers.items():
@@ -159,9 +173,8 @@ def _env_key_for_server(name: str) -> str:
def _strip_bearer_prefix(token: str) -> str:
"""Strip a leading ``Bearer `` from a pasted token.
- The header template stores ``Authorization: Bearer ${MCP_X_API_KEY}``, so
- if a user pastes a token that already includes the ``Bearer `` prefix the
- server receives ``Bearer Bearer <jwt>`` → 401. Normalize on save. (#37792)
+ The header template already stores ``Authorization: Bearer ${MCP_X_API_KEY}``; a token pasted
+ with its own prefix would send ``Bearer Bearer <jwt>`` and get a 401, so normalize on save.
"""
if not isinstance(token, str):
return token
@@ -174,9 +187,9 @@ def _strip_bearer_prefix(token: str) -> str:
def _bearer_auth_headers(name: str) -> Dict[str, str]:
"""Build the persisted Authorization header for a named MCP server.
- The secret itself lives in the active profile's ``.env`` file. Keeping
- this template construction beside ``_env_key_for_server`` ensures the CLI
- and Dashboard produce byte-equivalent MCP configuration.
+ The secret itself lives in the active profile's ``.env`` file. Keeping this template
+ construction beside ``_env_key_for_server`` ensures the CLI and Dashboard produce byte-
+ equivalent MCP configuration.
"""
env_key = _env_key_for_server(name)
return {"Authorization": f"Bearer ${{{env_key}}}"}
@@ -185,9 +198,8 @@ def _bearer_auth_headers(name: str) -> Dict[str, str]:
def _save_bearer_auth_token(name: str, token: str) -> Dict[str, str]:
"""Persist a Bearer token in the active profile and return safe headers.
- ``token`` is a one-time provisioning value. It is normalized and written
- only to ``.env``; callers persist the returned interpolation template in
- ``config.yaml``.
+ ``token`` is a one-time provisioning value. It is normalized and written only to ``.env``;
+ callers persist the returned interpolation template in ``config.yaml``.
"""
normalized = _strip_bearer_prefix(token)
if not normalized or normalized.lower() == "bearer":
@@ -254,13 +266,10 @@ def _apply_mcp_preset(
def _resolve_mcp_server_config(config: dict) -> dict:
"""Resolve ``${ENV}`` placeholders in a server config before connecting.
- Mirrors ``_load_mcp_config()`` in ``tools/mcp_tool.py``: load
- ``~/.hermes/.env`` into ``os.environ`` and recursively interpolate any
- ``${VAR}`` placeholders. The CLI builds header templates like
- ``Authorization: Bearer ${MCP_X_API_KEY}`` but the probe path never
- resolved them, so the discovery probe sent the literal placeholder and
- auth-requiring servers (e.g. n8n) returned 401 — while runtime tool
- loading worked because it interpolates. (#37792)
+ Mirrors ``_load_mcp_config()`` in ``tools/mcp_tool.py``: load ``~/.hermes/.env`` and interpolate
+ ``${VAR}`` recursively. Without this the discovery probe sent the literal placeholder in header
+ templates and auth-requiring servers returned 401 while runtime loading (which interpolates)
+ worked.
"""
from tools.mcp_tool import _interpolate_env_vars
@@ -280,12 +289,9 @@ def _probe_single_server(
) -> List[Tuple[str, str]]:
"""Temporarily connect to one MCP server, list its tools, disconnect.
- Returns list of ``(tool_name, description)`` tuples.
- Raises on connection failure.
-
- ``details``: optional dict the probe fills with extra capability counts
- (``prompts``, ``resources``) — an out-param so the return shape stays
- stable for existing CLI callers.
+ Returns ``(tool_name, description)`` tuples; raises on connection failure. ``details`` is an
+ out-param filled with extra capability counts (``prompts``, ``resources``) so the return shape
+ stays stable for existing callers.
"""
issues = validate_mcp_server_entry(name, config)
if issues:
@@ -404,9 +410,9 @@ def _probe_single_server(
def _oauth_tokens_present(name: str) -> bool:
"""Return True if an OAuth token file exists on disk for ``name``.
- Used after ``hermes mcp login`` to distinguish a genuine authentication
- from a probe that succeeded only because the server allowed
- initialize/tools-list without auth (so no token was ever acquired).
+ Used after ``hermes mcp login`` to distinguish a genuine authentication from a probe that
+ succeeded only because the server allowed initialize/tools-list without auth (so no token was
+ ever acquired).
"""
try:
from tools.mcp_oauth import HermesTokenStorage
@@ -420,10 +426,8 @@ def _oauth_tokens_present(name: str) -> bool:
def _unwrap_exception_group(exc: BaseException) -> Exception:
"""Extract the root-cause exception from anyio TaskGroup wrappers.
- The MCP SDK uses anyio task groups, which wrap errors in
- ``BaseExceptionGroup`` / ``ExceptionGroup``. This makes error
- messages opaque ("unhandled errors in a TaskGroup"). We unwrap
- to surface the real cause (e.g. "401 Unauthorized").
+ The MCP SDK's anyio task groups wrap errors in ``ExceptionGroup``, making messages opaque
+ ("unhandled errors in a TaskGroup"); unwrap to surface the real cause, e.g. "401 Unauthorized".
"""
while isinstance(exc, BaseExceptionGroup) and exc.exceptions:
exc = exc.exceptions[0]
@@ -498,11 +502,7 @@ def cmd_mcp_add(args):
if raw_connect_timeout is not None:
server_config["connect_timeout"] = raw_connect_timeout
- issues = validate_mcp_server_entry(name, server_config)
- if issues:
- for issue in issues:
- _warning(issue)
- _warning(f"Server '{name}' was NOT saved due to suspicious configuration.")
+ if not _validate_or_warn(name, server_config):
return
# ── Authentication ────────────────────────────────────────────────
@@ -527,10 +527,8 @@ def cmd_mcp_add(args):
if not oauth_ok:
_info("This server may not support OAuth.")
- if _confirm("Continue without authentication?", default=True):
- # Don't store auth: oauth — server doesn't support it
- pass
- else:
+ # Don't store auth: oauth — server doesn't support it
+ if not _confirm("Continue without authentication?", default=True):
_info("Cancelled.")
return
@@ -542,21 +540,15 @@ def cmd_mcp_add(args):
if needs_auth:
if auth_type == "header" or not auth_type:
env_key = _env_key_for_server(name)
- existing_key = get_env_value(env_key)
- if existing_key:
+ if get_env_value(env_key):
_success(f"{env_key}: already configured")
+ server_config["headers"] = _bearer_auth_headers(name) # env-var interpolation
else:
api_key = _prompt("API key / Bearer token", password=True)
if api_key:
- server_config["headers"] = _save_bearer_auth_token(
- name, api_key
- )
+ server_config["headers"] = _save_bearer_auth_token(name, api_key)
_success(f"Saved to {display_hermes_home()}/.env as {env_key}")
- # Set header with env var interpolation
- if existing_key:
- server_config["headers"] = _bearer_auth_headers(name)
-
# ── Discovery: connect and list tools ─────────────────────────────
print()
@@ -623,13 +615,11 @@ def cmd_mcp_add(args):
chosen_names = [tools[i][0] for i in sorted(chosen)]
server_config.setdefault("tools", {})["include"] = chosen_names
-
tool_count = len(chosen_names)
- total = len(tools)
else:
# Enable all (no filter needed — default behaviour)
tool_count = len(tools)
- total = len(tools)
+ total = len(tools)
# ── Save ──────────────────────────────────────────────────────────
@@ -645,13 +635,7 @@ def cmd_mcp_add(args):
def cmd_mcp_remove(args):
"""Remove an MCP server from config."""
name = args.name
- existing = _get_mcp_servers()
-
- if name not in existing:
- _error(f"Server '{name}' not found in config.")
- servers = list(existing.keys())
- if servers:
- _info(f"Available servers: {', '.join(servers)}")
+ if _lookup_server(name, _get_mcp_servers()) is None:
return
if not _confirm(f"Remove server '{name}'?", default=True):
@@ -699,34 +683,23 @@ def cmd_mcp_list(args=None):
for name, cfg in servers.items():
# Transport info
if "url" in cfg:
- url = cfg["url"]
- # Truncate long URLs
- if len(url) > 28:
- url = url[:25] + "..."
- transport = url
+ transport = cfg["url"]
elif "command" in cfg:
- cmd = cfg["command"]
+ transport = cfg["command"]
cmd_args = cfg.get("args", [])
if isinstance(cmd_args, list) and cmd_args:
- transport = f"{cmd} {' '.join(str(a) for a in cmd_args[:2])}"
- else:
- transport = cmd
- if len(transport) > 28:
- transport = transport[:25] + "..."
+ transport = f"{transport} {' '.join(str(a) for a in cmd_args[:2])}"
else:
transport = "?"
+ if len(transport) > 28:
+ transport = transport[:25] + "..."
# Tool count
- tools_cfg = cfg.get("tools", {})
- if isinstance(tools_cfg, dict):
- include = tools_cfg.get("include")
- exclude = tools_cfg.get("exclude")
- if include and isinstance(include, list):
- tools_str = f"{len(include)} selected"
- elif exclude and isinstance(exclude, list):
- tools_str = f"-{len(exclude)} excluded"
- else:
- tools_str = "all"
+ include, exclude = _tool_filters(cfg)
+ if include:
+ tools_str = f"{len(include)} selected"
+ elif exclude:
+ tools_str = f"-{len(exclude)} excluded"
else:
tools_str = "all"
@@ -746,16 +719,9 @@ def cmd_mcp_list(args=None):
def cmd_mcp_test(args):
"""Test connection to an MCP server."""
name = args.name
- servers = _get_mcp_servers()
-
- if name not in servers:
- _error(f"Server '{name}' not found in config.")
- available = list(servers.keys())
- if available:
- _info(f"Available: {', '.join(available)}")
+ cfg = _lookup_server(name, _get_mcp_servers(), "Available")
+ if cfg is None:
return
-
- cfg = servers[name]
print()
print(color(f" Testing '{name}'...", Colors.CYAN))
@@ -810,10 +776,9 @@ def cmd_mcp_test(args):
def _reauth_oauth_server(name: str, server_config: dict) -> bool:
"""Force a fresh OAuth flow for one server. Returns True on success.
- Wipes cached OAuth state (disk + in-process MCPOAuthManager cache),
- re-probes to trigger the browser flow, and verifies a token actually
- landed before reporting success. Shared by ``hermes mcp login`` and
- ``hermes mcp reauth`` so both behave identically for a single server.
+ Wipes cached OAuth state (disk + in-process MCPOAuthManager cache), re-probes to trigger the
+ browser flow, and verifies a token actually landed before reporting success. Shared by ``hermes
+ mcp login`` and ``hermes mcp reauth`` so both behave identically for a single server.
"""
url = server_config.get("url")
if not url:
@@ -910,40 +875,20 @@ def _reauth_oauth_server(name: str, server_config: dict) -> bool:
def cmd_mcp_login(args):
"""Force re-authentication for an OAuth-based MCP server.
- Deletes cached tokens (both on disk and in the running process's
- MCPOAuthManager cache) and triggers a fresh OAuth flow via the
- existing probe path.
-
- Use this when:
- - Tokens are stuck in a bad state (server revoked, refresh token
- consumed by an external process, etc.)
- - You want to re-authenticate to change scopes or account
- - A tool call returned ``needs_reauth: true``
+ Deletes cached tokens (both on disk and in the running process's MCPOAuthManager cache) and
+ triggers a fresh OAuth flow via the existing probe path.
"""
name = args.name
- servers = _get_mcp_servers()
-
- if name not in servers:
- _error(f"Server '{name}' not found in config.")
- if servers:
- _info(f"Available servers: {', '.join(servers)}")
- return
-
- _reauth_oauth_server(name, servers[name])
+ cfg = _lookup_server(name, _get_mcp_servers())
+ if cfg is not None:
+ _reauth_oauth_server(name, cfg)
def cmd_mcp_reauth(args):
"""Re-authenticate one OAuth MCP server, or all of them sequentially.
- ``hermes mcp reauth <name>`` re-auths a single server (same as ``login``).
- ``hermes mcp reauth --all`` discovers every ``auth: oauth`` server in
- config and re-auths them ONE AT A TIME.
-
- Serial-by-design: a human can only complete one browser OAuth flow at a
- time, so re-authing all servers concurrently would open N tabs at once
- and N-1 would time out. This is the self-service fix for the recurring
- stale-client ritual in GH#36767 (and avoids the startup popup storm when
- several servers go stale at once).
+ Serial-by-design: a human can only complete one browser OAuth flow at a time, so re-authing all
+ servers concurrently would open N tabs at once and N-1 would time out.
"""
servers = _get_mcp_servers()
do_all = getattr(args, "all", False)
@@ -973,13 +918,9 @@ def cmd_mcp_reauth(args):
_error("Specify a server name, or use --all to re-auth every OAuth server.")
_info("Usage: hermes mcp reauth <name> | hermes mcp reauth --all")
return
- if name not in servers:
- _error(f"Server '{name}' not found in config.")
- if servers:
- _info(f"Available servers: {', '.join(servers)}")
- return
-
- _reauth_oauth_server(name, servers[name])
+ cfg = _lookup_server(name, servers)
+ if cfg is not None:
+ _reauth_oauth_server(name, cfg)
# ─── hermes mcp configure ────────────────────────────────────────────────────
@@ -991,17 +932,10 @@ def cmd_mcp_configure(args):
print("Error: 'hermes mcp configure' requires an interactive terminal.", file=_sys.stderr)
_sys.exit(1)
name = args.name
- servers = _get_mcp_servers()
-
- if name not in servers:
- _error(f"Server '{name}' not found in config.")
- available = list(servers.keys())
- if available:
- _info(f"Available: {', '.join(available)}")
+ cfg = _lookup_server(name, _get_mcp_servers(), "Available")
+ if cfg is None:
return
- cfg = servers[name]
-
# Discover all available tools
print()
print(color(f" Connecting to '{name}' to discover tools...", Colors.CYAN))
@@ -1017,13 +951,7 @@ def cmd_mcp_configure(args):
return
# Determine which are currently enabled
- tools_cfg = cfg.get("tools", {})
- if isinstance(tools_cfg, dict):
- include = tools_cfg.get("include")
- exclude = tools_cfg.get("exclude")
- else:
- include = None
- exclude = None
+ include, exclude = _tool_filters(cfg)
tool_names = [t[0] for t in all_tools]
@@ -1035,13 +963,13 @@ def cmd_mcp_configure(args):
def matches_name_filter(tool_name, patterns):
return tool_name in patterns
- if include and isinstance(include, list):
+ if include:
include_set = {str(p) for p in include}
pre_selected = {
i for i, tn in enumerate(tool_names)
if matches_name_filter(tn, include_set)
}
- elif exclude and isinstance(exclude, list):
+ elif exclude:
exclude_set = {str(p) for p in exclude}
pre_selected = {
i for i, tn in enumerate(tool_names)
@@ -1074,7 +1002,7 @@ def cmd_mcp_configure(args):
config = load_config()
server_entry = cfg_get(config, "mcp_servers", name, default={})
- exclude_mode = bool(exclude) and isinstance(exclude, list) and not include
+ exclude_mode = bool(exclude) and not include
if len(chosen) == total and not exclude_mode:
# All selected → remove include/exclude (register all)
diff --git a/hermes_cli/moa_config.py b/hermes_cli/moa_config.py
index 24d36e4a19d..8b1eddc45f5 100644
--- a/hermes_cli/moa_config.py
+++ b/hermes_cli/moa_config.py
@@ -28,152 +28,89 @@ def _default_reference_models() -> list[dict[str, Any]]:
return [{**slot, "enabled": True} for slot in deepcopy(DEFAULT_MOA_REFERENCE_MODELS)]
-def _coerce_float_or_none(value: Any) -> float | None:
- """Coerce to a float, or None when unset/blank/invalid.
+def _coerce_number(value: Any, cast, default=None, *, positive: bool = False):
+ """Coerce ``value`` with ``cast`` (float/int); ``default`` when unset/blank/invalid.
- Used for optional sampling params (reference_temperature /
- aggregator_temperature) where None means 'don't send the parameter —
- provider default applies', matching how a single-model Hermes agent
- never sends temperature unless explicitly configured.
+ ``int`` also accepts float-looking strings ("3.0"). With ``positive`` the result must be > 0
+ (and finite for floats) or ``default`` is returned.
"""
- if value is None or value == "":
- return None
- try:
- return float(value)
- except (TypeError, ValueError):
- return None
-
-
-def _coerce_reference_timeout(value: Any) -> float | None:
- """Return a finite positive advisor timeout, or None to inherit.
-
- ``None`` (the default) means "no per-preset override": the reference
- fan-out inherits the ``auxiliary.moa_reference.timeout`` config value
- (900s by default) via ``call_llm``'s own resolution, exactly like every
- other auxiliary task. An explicit finite positive per-preset value is
- honored as-is — no artificial cap, since long-thinking advisor models
- legitimately run far beyond five minutes.
- """
- if value is None or value == "" or isinstance(value, bool):
- return DEFAULT_MOA_REFERENCE_TIMEOUT
- try:
- timeout = float(value)
- except (TypeError, ValueError):
- return DEFAULT_MOA_REFERENCE_TIMEOUT
- if not math.isfinite(timeout) or timeout <= 0:
- return DEFAULT_MOA_REFERENCE_TIMEOUT
- return timeout
-
-
-def _coerce_degraded_reference_policy(value: Any) -> str:
- """Normalize failed-advisor disclosure policy; unknown values fail loud."""
- policy = str(value or "loud").strip().lower()
- return policy if policy in {"loud", "silent"} else "loud"
-
-
-def _coerce_int(value: Any, default: int) -> int:
if value is None or value == "":
return default
try:
- return int(value)
+ number = cast(value)
except (TypeError, ValueError):
+ if cast is not int:
+ return default
try:
- return int(float(value))
+ number = int(float(value))
except (TypeError, ValueError):
return default
+ if positive and (number <= 0 or (cast is float and not math.isfinite(number))):
+ return default
+ return number
-def _coerce_int_or_none(value: Any) -> int | None:
- """Coerce to a positive int, or None when unset/blank/invalid/non-positive.
+def _coerce_reference_timeout(value: Any) -> float | None:
+ """Finite positive advisor timeout, or None to inherit ``auxiliary.moa_reference.timeout``.
- Used for optional caps (e.g. reference_max_tokens) where None means
- 'no cap' — the safe default that preserves prior uncapped behavior.
+ No artificial cap: long-thinking advisor models legitimately run far beyond five minutes.
"""
- if value is None or value == "":
- return None
- try:
- n = int(value)
- except (TypeError, ValueError):
- try:
- n = int(float(value))
- except (TypeError, ValueError):
- return None
- return n if n > 0 else None
+ if isinstance(value, bool):
+ return DEFAULT_MOA_REFERENCE_TIMEOUT
+ return _coerce_number(value, float, DEFAULT_MOA_REFERENCE_TIMEOUT, positive=True)
def _coerce_fanout(value: Any) -> str:
"""Normalize the fan-out cadence; unknown values fall back to default.
- Canonical values are the strings ``per_iteration``, ``user_turn``, and
- ``every_n:<N>`` (N >= 2). The ``every_n`` cadence also accepts the mapping
- form ``{mode: every_n, n: N}`` from hand-edited YAML and normalizes it to
- the canonical string, so the rest of the pipeline (presets, flattened
- view, runtime) only ever sees one shape. ``every_n:1`` semantically means
- "run every iteration" and collapses to ``per_iteration``; anything
- unparseable falls back to ``user_turn`` (the default — cheapest cadence;
- see #67199).
+ Canonical values are ``per_iteration``, ``user_turn``, and ``every_n:<N>`` (N >= 2); the
+ mapping form ``{mode: every_n, n: N}`` from hand-edited YAML is normalized to the string so the
+ rest of the pipeline sees one shape. ``every_n:1`` collapses to ``per_iteration``; anything
+ unparseable falls back to ``user_turn`` (the cheapest cadence).
"""
+ def _every_n(n: int) -> str:
+ return f"every_n:{n}" if n >= 2 else ("per_iteration" if n == 1 else "user_turn")
+
if isinstance(value, dict):
# Mapping form: {mode: every_n, n: 3}. Non-every_n mapping modes fall
# through to the string path below (e.g. {mode: user_turn}).
mode = str(value.get("mode") or "").strip().lower()
if mode == "every_n":
- n = _coerce_int(value.get("n"), 0)
- if n >= 2:
- return f"every_n:{n}"
- return "per_iteration" if n == 1 else "user_turn"
+ return _every_n(_coerce_number(value.get("n"), int, 0))
value = mode
mode = str(value or "").strip().lower()
if mode in {"per_iteration", "user_turn"}:
return mode
if mode.startswith("every_n"):
_, sep, rest = mode.partition(":")
- n = _coerce_int(rest.strip(), 0) if sep else 0
- if n >= 2:
- return f"every_n:{n}"
- if n == 1:
- return "per_iteration"
+ return _every_n(_coerce_number(rest.strip(), int, 0) if sep else 0)
return "user_turn"
def coerce_privacy_filter(value: Any) -> str:
"""Normalize ``moa.privacy_filter`` to '' (off), 'display', or 'full'.
- - ``''`` (empty string): filter off — the default. ``false``/``None``/
- unknown values land here so a hand-edited config degrades to prior
- behavior (tolerant-read contract).
- - ``'display'``: redact user-visible surfaces only — the reference blocks
- shown in the UI and the saved MoA trace records. The aggregator still
- sees raw advisor text, so answer quality is unaffected.
- - ``'full'``: additionally redact the advisor text injected into the
- aggregator prompt (issue #59959's literal ask). A hand-edited boolean
- ``true`` maps here because the issue framed the toggle as "redact
- before passing to the aggregator".
+ - ``''`` (empty string): filter off — the default. ``false``/``None``/ unknown values land here
+ so a hand-edited config degrades to prior behavior (tolerant-read contract). - ``'display'``:
+ redact user-visible surfaces only — the reference blocks shown in the UI and the saved MoA trace
+ records.
"""
if value is True:
return "full"
if value is None or value is False:
return ""
mode = str(value).strip().lower()
- if mode in {"display", "full"}:
- return mode
- if mode in {"true", "on", "yes", "1"}:
- return "full"
- return ""
+ return mode if mode in {"display", "full"} else ("full" if mode in {"true", "on", "yes", "1"} else "")
def _clean_reasoning_effort(value: Any) -> str | None:
"""Return a canonical per-slot reasoning effort, or None when unset/invalid."""
from hermes_constants import parse_reasoning_effort
- if value is None or value is True:
- return None
- parsed = parse_reasoning_effort(value)
+ parsed = None if value is None or value is True else parse_reasoning_effort(value)
if parsed is None:
return None
- if parsed.get("enabled") is False:
- return "none"
- return parsed.get("effort")
+ return "none" if parsed.get("enabled") is False else parsed.get("effort")
def _coerce_bool(value: Any, default: bool = True) -> bool:
@@ -183,29 +120,42 @@ def _coerce_bool(value: Any, default: bool = True) -> bool:
return value
if isinstance(value, str):
text = value.strip().lower()
- if text in {"0", "false", "no", "off"}:
- return False
- if text in {"1", "true", "yes", "on"}:
- return True
- return default
+ return True if text in {"1", "true", "yes", "on"} else False if text in {"0", "false", "no", "off"} else default
return bool(value)
-def _clean_slot(slot: Any, *, include_enabled: bool = False) -> dict[str, Any] | None:
+def _slot_problem(slot: Any) -> str | None:
+ """Return a human-readable problem for a slot ``_clean_slot`` would drop.
+
+ None means the slot is complete and valid. Mirrors ``_clean_slot`` exactly so the write-boundary
+ validator (``validate_moa_payload``) and the tolerant runtime normalizer can never disagree
+ about what is acceptable.
+ """
if not isinstance(slot, dict):
- return None
+ return "must be an object with 'provider' and 'model'"
provider = str(slot.get("provider") or "").strip()
model = str(slot.get("model") or "").strip()
- if not provider or not model:
- return None
+ if not provider and not model:
+ return "provider and model are required"
+ if not provider:
+ return "provider is required"
+ if not model:
+ return f"model is required (provider '{provider}' has no model selected)"
# MoA is a virtual provider whose presets are themselves MoA runs. Allowing
# one as a reference or aggregator slot would create a recursive MoA tree
# (the runtime guards in moa_loop.py skip references / raise on aggregators,
- # but that surfaces only mid-turn). Reject it here so it can never be saved:
- # an invalid slot is dropped, falling back to the preset's defaults.
+ # but that surfaces only mid-turn). Reject it here so it can never be saved.
if provider.lower() == "moa":
+ return "the Mixture of Agents provider cannot be used inside a preset (recursive MoA)"
+ return None
+
+
+def _clean_slot(slot: Any, *, include_enabled: bool = False) -> dict[str, Any] | None:
+ # Any slot ``_slot_problem`` rejects (non-dict, missing provider/model, recursive
+ # ``moa`` provider) is dropped, falling back to the preset's defaults.
+ if _slot_problem(slot) is not None:
return None
- clean: dict[str, Any] = {"provider": provider, "model": model}
+ clean: dict[str, Any] = {"provider": str(slot["provider"]).strip(), "model": str(slot["model"]).strip()}
effort = _clean_reasoning_effort(slot.get("reasoning_effort"))
if effort:
clean["reasoning_effort"] = effort
@@ -214,7 +164,7 @@ def _clean_slot(slot: Any, *, include_enabled: bool = False) -> dict[str, Any] |
# default) = no cap, so existing slots are unaffected. Allows tuning
# each advisor's output length independently — useful when one model
# is verbose and another is terse.
- slot_mt = _coerce_int_or_none(slot.get("max_tokens"))
+ slot_mt = _coerce_number(slot.get("max_tokens"), int, positive=True)
if slot_mt is not None:
clean["max_tokens"] = slot_mt
if include_enabled:
@@ -222,37 +172,14 @@ def _clean_slot(slot: Any, *, include_enabled: bool = False) -> dict[str, Any] |
return clean
-def _slot_problem(slot: Any) -> str | None:
- """Return a human-readable problem for a slot ``_clean_slot`` would drop.
-
- None means the slot is complete and valid. Mirrors ``_clean_slot`` exactly
- so the write-boundary validator (``validate_moa_payload``) and the
- tolerant runtime normalizer can never disagree about what is acceptable.
- """
- if not isinstance(slot, dict):
- return "must be an object with 'provider' and 'model'"
- provider = str(slot.get("provider") or "").strip()
- model = str(slot.get("model") or "").strip()
- if not provider and not model:
- return "provider and model are required"
- if not provider:
- return "provider is required"
- if not model:
- return f"model is required (provider '{provider}' has no model selected)"
- if provider.lower() == "moa":
- return "the Mixture of Agents provider cannot be used inside a preset (recursive MoA)"
- return None
-
def validate_moa_payload(raw: Any) -> list[str]:
"""Return the problems ``normalize_moa_config`` would silently paper over.
- ``normalize_moa_config`` is deliberately tolerant: at *read* time a
- hand-edited config must degrade to defaults rather than crash the agent.
- That same tolerance at *write* time is a corruption engine — a client that
- sends a half-filled slot gets its whole preset silently replaced with the
- hardcoded defaults (#64156). API write paths call this first and reject
- invalid payloads loudly instead of saving something the user never chose.
+ ``normalize_moa_config`` is deliberately tolerant: at *read* time a hand-edited config must
+ degrade to defaults rather than crash the agent. That same tolerance at *write* time is a
+ corruption engine — a client that sends a half-filled slot gets its whole preset silently
+ replaced with the hardcoded defaults (#64156).
Returns a list of human-readable problems; empty means safe to save.
"""
@@ -260,11 +187,8 @@ def validate_moa_payload(raw: Any) -> list[str]:
return ["MoA config must be an object"]
presets_raw = raw.get("presets")
- if isinstance(presets_raw, dict) and presets_raw:
- presets: dict[Any, Any] = presets_raw
- else:
- # Legacy flat payload: the top-level object is the default preset.
- presets = {DEFAULT_MOA_PRESET_NAME: raw}
+ # Legacy flat payload: the top-level object is the default preset.
+ presets: dict[Any, Any] = presets_raw if isinstance(presets_raw, dict) and presets_raw else {DEFAULT_MOA_PRESET_NAME: raw}
problems: list[str] = []
for name, preset in presets.items():
@@ -276,14 +200,9 @@ def validate_moa_payload(raw: Any) -> list[str]:
refs = preset.get("reference_models")
if not isinstance(refs, list):
refs = [refs] if isinstance(refs, dict) else []
- complete_refs = 0
- for index, slot in enumerate(refs):
- issue = _slot_problem(slot)
- if issue:
- problems.append(f"preset '{label}' reference {index + 1}: {issue}")
- else:
- complete_refs += 1
- if not complete_refs:
+ issues = [(index, _slot_problem(slot)) for index, slot in enumerate(refs)]
+ problems.extend(f"preset '{label}' reference {index + 1}: {issue}" for index, issue in issues if issue)
+ if all(issue for _, issue in issues):
problems.append(f"preset '{label}': needs at least one complete reference model")
agg_issue = _slot_problem(preset.get("aggregator"))
@@ -293,23 +212,6 @@ def validate_moa_payload(raw: Any) -> list[str]:
return problems
-def _default_preset() -> dict[str, Any]:
- return {
- "reference_models": _default_reference_models(),
- "aggregator": deepcopy(DEFAULT_MOA_AGGREGATOR),
- # None = temperature omitted from API calls (provider default),
- # matching single-model agent behavior.
- "reference_temperature": None,
- "aggregator_temperature": None,
- "reference_timeout": DEFAULT_MOA_REFERENCE_TIMEOUT,
- "degraded_reference_policy": "loud",
- "max_tokens": 4096,
- "reference_max_tokens": None,
- "fanout": "user_turn",
- "enabled": True,
- }
-
-
def _normalize_preset(raw: Any) -> dict[str, Any]:
if not isinstance(raw, dict):
raw = {}
@@ -326,24 +228,19 @@ def _normalize_preset(raw: Any) -> dict[str, Any]:
# defaults instead of crashing the iteration, mirroring the tolerance
# for the scalar fields below (reference_temperature / max_tokens).
raw_refs = [raw_refs] if isinstance(raw_refs, dict) else []
- refs = [_clean_slot(item, include_enabled=True) for item in raw_refs]
- refs = [item for item in refs if item is not None]
- if not refs:
- refs = _default_reference_models()
-
- aggregator = _clean_slot(raw.get("aggregator")) or deepcopy(DEFAULT_MOA_AGGREGATOR)
+ refs = [item for item in (_clean_slot(item, include_enabled=True) for item in raw_refs) if item is not None]
return {
"enabled": _coerce_bool(raw.get("enabled"), True),
- "reference_models": refs,
- "aggregator": aggregator,
- "reference_temperature": _coerce_float_or_none(raw.get("reference_temperature")),
- "aggregator_temperature": _coerce_float_or_none(raw.get("aggregator_temperature")),
+ "reference_models": refs or _default_reference_models(),
+ "aggregator": _clean_slot(raw.get("aggregator")) or deepcopy(DEFAULT_MOA_AGGREGATOR),
+ # None means 'don't send it — provider default applies'.
+ "reference_temperature": _coerce_number(raw.get("reference_temperature"), float),
+ "aggregator_temperature": _coerce_number(raw.get("aggregator_temperature"), float),
"reference_timeout": _coerce_reference_timeout(raw.get("reference_timeout")),
- "degraded_reference_policy": _coerce_degraded_reference_policy(
- raw.get("degraded_reference_policy")
- ),
- "max_tokens": _coerce_int(raw.get("max_tokens"), 4096),
+ # Failed-advisor disclosure policy; unknown values fail loud.
+ "degraded_reference_policy": policy if (policy := str(raw.get("degraded_reference_policy") or "loud").strip().lower()) in {"loud", "silent"} else "loud",
+ "max_tokens": _coerce_number(raw.get("max_tokens"), int, 4096),
# Optional cap on how much each reference ADVISOR may generate per turn.
# None (default) = uncapped: advisors write full-length advice, matching
# prior behavior so existing presets are unchanged. Set a value (e.g.
@@ -352,7 +249,7 @@ def _normalize_preset(raw: Any) -> dict[str, Any]:
# tokens), and the aggregator only needs the gist of each advisor's
# judgement, so capping roughly halves per-turn wall time. Does NOT cap
# the acting aggregator (its output is the user-visible answer).
- "reference_max_tokens": _coerce_int_or_none(raw.get("reference_max_tokens")),
+ "reference_max_tokens": _coerce_number(raw.get("reference_max_tokens"), int, positive=True),
# When the reference fan-out runs. "user_turn" (default) runs the
# advisors ONCE per user turn (the original MoA shape, and the
# cheapest cadence — #67199): the aggregator gets their upfront
@@ -369,12 +266,15 @@ def _normalize_preset(raw: Any) -> dict[str, Any]:
}
-def normalize_moa_config(raw: Any) -> dict[str, Any]:
- """Return validated MoA config with named presets.
+_FLAT_PRESET_KEYS = (
+ "reference_models", "aggregator", "reference_temperature", "aggregator_temperature",
+ "reference_timeout", "degraded_reference_policy", "max_tokens", "reference_max_tokens",
+ "fanout", "enabled",
+)
- Backward compatible with the first PR shape where ``moa`` itself contained
- ``reference_models`` and ``aggregator`` directly.
- """
+
+def normalize_moa_config(raw: Any) -> dict[str, Any]:
+ """Return validated MoA config with named presets."""
if not isinstance(raw, dict):
raw = {}
@@ -385,37 +285,23 @@ def normalize_moa_config(raw: Any) -> dict[str, Any]:
clean_name = str(name or "").strip()
if clean_name:
presets[clean_name] = _normalize_preset(preset)
-
- # Legacy flat config becomes the default preset.
- if not presets:
+ if not presets: # Legacy flat config becomes the default preset.
presets[DEFAULT_MOA_PRESET_NAME] = _normalize_preset(raw)
default_name = str(raw.get("default_preset") or "").strip()
if not default_name or default_name not in presets:
- default_name = next(iter(presets), DEFAULT_MOA_PRESET_NAME)
- if default_name not in presets:
- presets[default_name] = _default_preset()
+ default_name = next(iter(presets)) # never empty: legacy flat config seeds the default
active_name = str(raw.get("active_preset") or "").strip()
if active_name not in presets:
active_name = ""
- active = presets[default_name]
return {
"default_preset": default_name,
"active_preset": active_name,
"presets": presets,
# Compatibility/flattened view for existing dashboard/desktop callers.
- "reference_models": deepcopy(active["reference_models"]),
- "aggregator": deepcopy(active["aggregator"]),
- "reference_temperature": active["reference_temperature"],
- "aggregator_temperature": active["aggregator_temperature"],
- "reference_timeout": active["reference_timeout"],
- "degraded_reference_policy": active["degraded_reference_policy"],
- "max_tokens": active["max_tokens"],
- "reference_max_tokens": active.get("reference_max_tokens"),
- "fanout": active.get("fanout", "user_turn"),
- "enabled": active["enabled"],
+ **{key: deepcopy(presets[default_name][key]) for key in _FLAT_PRESET_KEYS},
# MoA-level (not per-preset) toggles ride at the top level alongside
# save_traces. privacy_filter: '' (off, default) | 'display' | 'full'
# — see coerce_privacy_filter for the semantics of each mode.
@@ -423,11 +309,6 @@ def normalize_moa_config(raw: Any) -> dict[str, Any]:
}
-def list_moa_presets(config: Any) -> list[str]:
- cfg = normalize_moa_config(config)
- return list(cfg["presets"].keys())
-
-
def resolve_moa_preset(config: Any, name: str | None = None) -> dict[str, Any]:
cfg = normalize_moa_config(config)
preset_name = str(name or cfg.get("default_preset") or DEFAULT_MOA_PRESET_NAME).strip()
@@ -446,45 +327,16 @@ def resolve_moa_preset(config: Any, name: str | None = None) -> dict[str, Any]:
def exact_moa_preset_name(config: Any, text: str) -> str | None:
"""Return the preset name iff ``text`` exactly matches an *enabled* preset.
- Used by the no-explicit-provider switch path (PATH B in
- ``hermes_cli/model_switch.py``) to recognize a bare ``/model <preset>``
- that the user typed without the ``moa:`` prefix. This is an *implicit*
- match, so it must honor the per-preset ``enabled`` opt-out: a user who set
- ``enabled: false`` to disable a preset must not have a plain model switch
- whose name happens to collide with that preset key silently pivot the
- session onto the MoA virtual provider (issue #55187). Explicit selection
- via ``--provider moa`` / the model picker does not go through here, so a
- disabled preset is still reachable when the user explicitly asks for it.
+ Used by the no-explicit-provider switch path to recognize a bare ``/model <preset>``. Because
+ the match is implicit it honors the per-preset ``enabled`` opt-out: a plain model switch that
+ collides with a disabled preset's name must not silently pivot onto the MoA provider. Explicit
+ ``--provider moa`` / picker selection bypasses this, so disabled presets stay reachable.
"""
wanted = str(text or "").strip()
if not wanted:
return None
- cfg = normalize_moa_config(config)
- preset = cfg["presets"].get(wanted)
- if preset is None or not preset.get("enabled", True):
- return None
- return wanted
-
-
-def set_active_moa_preset(config: Any, name: str | None) -> dict[str, Any]:
- cfg = normalize_moa_config(config)
- clean = str(name or "").strip()
- if clean and clean not in cfg["presets"]:
- raise KeyError(clean)
- cfg["active_preset"] = clean
- return cfg
-
-
-def encode_moa_turn(prompt: str, config: Any = None, preset: str | None = None) -> str:
- """Encode a /moa one-shot turn for frontends that can only send text."""
- payload = {
- "prompt": str(prompt or ""),
- "config": resolve_moa_preset(config or {}, preset),
- }
- encoded = base64.urlsafe_b64encode(
- json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
- ).decode("ascii")
- return f"{MOA_MARKER_PREFIX}{encoded}"
+ preset = normalize_moa_config(config)["presets"].get(wanted)
+ return None if preset is None or not preset.get("enabled", True) else wanted
def decode_moa_turn(message: Any) -> tuple[str, dict[str, Any] | None]:
@@ -496,13 +348,7 @@ def decode_moa_turn(message: Any) -> tuple[str, dict[str, Any] | None]:
payload = json.loads(base64.urlsafe_b64decode(encoded.encode("ascii")).decode("utf-8"))
except Exception:
return message, None
- prompt = str(payload.get("prompt") or "")
- return prompt, _normalize_preset(payload.get("config") or {})
-
-
-def build_moa_turn_prompt(user_prompt: str, config: Any = None, preset: str | None = None) -> str:
- """Build the hidden one-shot payload used by TUI/gateway routing."""
- return encode_moa_turn(user_prompt, config, preset=preset)
+ return str(payload.get("prompt") or ""), _normalize_preset(payload.get("config") or {})
def moa_usage() -> str:
diff --git a/hermes_cli/setup_hidden_env.py b/hermes_cli/setup_hidden_env.py
index cea85b5987e..885821029bb 100644
--- a/hermes_cli/setup_hidden_env.py
+++ b/hermes_cli/setup_hidden_env.py
@@ -1,18 +1,8 @@
"""Which platform env vars the setup surfaces hide.
-Every messaging platform ships the same handful of knobs that are either set
-for the user later or already correct by default. Listing them on a setup form
-turns "paste your bot token" into a five-field interrogation where none of the
-answers are discoverable — the Discord card asked for a home channel ID you
-need Developer Mode to copy, next to a reply-threading preference.
-
-Hiding them is a *presentation* decision only. The env vars keep working
-through ``hermes config set``, ``.env``, and ``config.yaml``; the gateway reads
-them exactly as before. This module just says what a new user is asked during
-setup.
-
-Lives here rather than in ``web_server`` so the CLI wizard can share it without
-importing the dashboard's FastAPI surface.
+Hiding them is a *presentation* decision only. The env vars keep working through ``hermes config
+set``, ``.env``, and ``config.yaml``; the gateway reads them exactly as before. This module just
+says what a new user is asked during setup.
"""
# Suffix match, so plugin adapters nobody enumerated (IRC, SimpleX, LINE, ntfy)
@@ -50,7 +40,7 @@ SETUP_HIDDEN_ENV_SUFFIXES = (
def is_setup_hidden_env(name: str) -> bool:
"""True when a var is self-configuring and shouldn't appear in setup forms.
- Callers must still keep any var a platform lists as *required* — hiding a
- required credential would make that platform unconfigurable from the UI.
+ Callers must still keep any var a platform lists as *required* — hiding a required credential
+ would make that platform unconfigurable from the UI.
"""
return name.endswith(SETUP_HIDDEN_ENV_SUFFIXES)
diff --git a/hermes_cli/skills_config.py b/hermes_cli/skills_config.py
index 4a19e052a6f..8aef1e42937 100644
--- a/hermes_cli/skills_config.py
+++ b/hermes_cli/skills_config.py
@@ -1,16 +1,4 @@
-"""
-Skills configuration for Hermes Agent.
-`hermes skills` enters this module.
-
-Toggle individual skills or categories on/off, globally or per-platform.
-Config stored in ~/.hermes/config.yaml under:
-
- skills:
- disabled: [skill-a, skill-b] # global disabled list
- platform_disabled: # per-platform overrides
- telegram: [skill-c]
- cli: []
-"""
+"""Skills configuration for Hermes Agent. `hermes skills` enters this module."""
from typing import List, Optional, Set
from hermes_cli.config import cfg_get, load_config, save_config
@@ -27,9 +15,8 @@ PLATFORMS = {k: info.label for k, info in _PLATFORMS.items() if k != "api_server
def _normalize_skill_names(values) -> Set[str]:
"""Normalize a config value into a set of skill names.
- Mirrors ``agent.skill_utils._normalize_string_set``: ``None`` (YAML null)
- means empty, a bare scalar (``disabled: my-skill``) means a single-item
- list — NOT a set of its characters (#13026).
+ Mirrors ``agent.skill_utils._normalize_string_set``: ``None`` (YAML null) means empty, and a
+ bare scalar (``disabled: my-skill``) means a single-item list — NOT a set of its characters.
"""
if values is None:
return set()
@@ -42,12 +29,11 @@ def _normalize_skill_names(values) -> Set[str]:
def get_disabled_skills(config: dict, platform: Optional[str] = None) -> Set[str]:
- """Return disabled skill names: the global list unioned with the
- platform-specific list when a platform is given.
+ """Return disabled skill names: the global list unioned with the platform list when given.
- A globally-disabled skill stays disabled on every platform, so the
- platform list adds to the global list rather than replacing it. This
- mirrors ``agent.skill_utils.get_disabled_skill_names``.
+ A globally-disabled skill stays disabled on every platform, so the platform list adds to the
+ global list rather than replacing it (mirrors
+ ``agent.skill_utils.get_disabled_skill_names``).
"""
skills_cfg = config.get("skills") or {}
if not isinstance(skills_cfg, dict):
@@ -67,8 +53,8 @@ def get_disabled_skills(config: dict, platform: Optional[str] = None) -> Set[str
def save_disabled_skills(config: dict, disabled: Set[str], platform: Optional[str] = None):
"""Persist disabled skill names to config.
- Essential skills (e.g. ``hermes-agent``) are silently dropped from the
- list — they cannot be disabled from any surface.
+ Essential skills (e.g. ``hermes-agent``) are silently dropped from the list — they cannot be
+ disabled from any surface.
"""
from agent.skill_utils import ESSENTIAL_SKILLS
disabled = set(disabled) - ESSENTIAL_SKILLS
diff --git a/hermes_cli/tools_config.py b/hermes_cli/tools_config.py
index 71d2ed2593a..163bd705e9a 100644
--- a/hermes_cli/tools_config.py
+++ b/hermes_cli/tools_config.py
@@ -1,13 +1,4 @@
-"""
-Unified tool configuration for Hermes Agent.
-
-`hermes tools` and `hermes setup tools` both enter this module.
-Select a platform → toggle toolsets on/off → for newly enabled tools
-that need API keys, run through provider-aware configuration.
-
-Saves per-platform tool configuration to ~/.hermes/config.yaml under
-the `platform_toolsets` key.
-"""
+"""Unified tool configuration for Hermes Agent."""
import json as _json
import logging
@@ -44,22 +35,11 @@ logger = logging.getLogger(__name__)
def _post_setup_no_window_flags(*, streams_to_console: bool = False) -> int:
"""Win32 creationflags that stop post-setup children flashing a console.
- The dashboard/GUI runs post-setup hooks through a detached, console-less
- ``hermes tools post-setup <key>`` child. On Windows, every console child
- (npm.cmd, npx, pip, powershell, curl) spawned from that console-less
- parent materializes a brand-new console window — the "terminal flash"
- users see when clicking "Run setup". ``CREATE_NO_WINDOW`` (via
- :func:`hermes_cli._subprocess_compat.windows_hide_flags`) suppresses it
- without breaking ``capture_output`` — unlike ``DETACHED_PROCESS``, stdio
- handles stay inheritable. Returns 0 on POSIX, so passing the result
- unconditionally is safe.
-
- ``streams_to_console=True`` marks children spawned WITHOUT stdio
- redirection (live installer output, e.g. the verbose cua-driver install).
- Hiding those in an interactive console session would silently swallow
- their output into an invisible console, so the flag is only applied when
- the current process has no usable console of its own (stdout is a
- pipe/log file — exactly the GUI-spawn case that flashes).
+ The GUI runs post-setup hooks via a console-less child; on Windows every console grandchild
+ (npm, pip, powershell) would flash a new window. CREATE_NO_WINDOW suppresses that while keeping
+ stdio inheritable (unlike DETACHED_PROCESS). Returns 0 on POSIX. ``streams_to_console`` children
+ are only hidden when our own stdout is not a console, so live installer output is never
+ swallowed.
"""
from hermes_cli._subprocess_compat import windows_hide_flags
@@ -130,8 +110,8 @@ CONFIGURABLE_TOOLSETS = [
def gui_toolset_label(label: str) -> str:
"""Strip leading emoji/icons from toolset titles for GUI surfaces.
- Registry labels use ``<emoji> <title>``; plugin toolsets prefix with ``🔌``.
- CLI/TUI keeps the raw ``label`` — only HTTP APIs call this helper.
+ Registry labels use ``<emoji> <title>``; plugin toolsets prefix with ``🔌``. CLI/TUI keeps the
+ raw ``label`` — only HTTP APIs call this helper.
"""
text = (label or "").strip()
if not text:
@@ -171,13 +151,10 @@ _CONFIG_ONLY_TOOLSETS = {"stt"}
def _xai_credentials_present() -> bool:
"""Cheap, side-effect-free check for usable xAI credentials.
- Used to auto-enable the ``x_search`` toolset when the user has either
- completed xAI Grok OAuth (SuperGrok / Premium+) or set
- ``XAI_API_KEY``. Does NOT hit the network — only inspects the local
- auth store and environment. The tool's runtime ``check_fn`` still
- gates schema registration if creds later expire or get revoked.
- Also reused by ``provider_readiness_status`` for ``post_setup:
- "xai_grok"`` picker rows (xAI TTS, Grok OAuth x_search).
+ Does NOT hit the network — only inspects the local auth store and environment. The tool's
+ runtime ``check_fn`` still gates schema registration if creds later expire or get revoked. Also
+ reused by ``provider_readiness_status`` for ``post_setup: "xai_grok"`` picker rows (xAI TTS,
+ Grok OAuth x_search).
"""
try:
from hermes_cli.auth import _read_xai_oauth_tokens
@@ -212,10 +189,9 @@ def _homeassistant_credentials_present() -> bool:
def _toolset_configuration_platform(ts_key: str, default: str = "cli") -> str:
"""Return the platform a platform-less configuration UI should target.
- Most configurable toolsets retain the historical desktop/CLI target. A
- toolset restricted away from that platform must instead be configured on
- one of its supported platforms; otherwise the shared save helper correctly
- drops it and the UI reports a successful no-op.
+ Most configurable toolsets retain the historical desktop/CLI target. A toolset restricted away
+ from that platform must instead be configured on one of its supported platforms; otherwise the
+ shared save helper correctly drops it and the UI reports a successful no-op.
"""
allowed = _TOOLSET_PLATFORM_RESTRICTIONS.get(ts_key)
if not allowed or default in allowed:
@@ -226,13 +202,9 @@ def _toolset_configuration_platform(ts_key: str, default: str = "cli") -> str:
def _get_effective_configurable_toolsets():
"""Return CONFIGURABLE_TOOLSETS + any plugin-provided toolsets.
- Plugin toolsets are appended at the end so they appear after the
- built-in toolsets in the TUI checklist. A plugin whose toolset key
- already appears in ``CONFIGURABLE_TOOLSETS`` is skipped — bundled
- plugins (e.g. ``plugins/spotify``) share their toolset key with the
- built-in entry, and we want the built-in label/description to win.
- Without the dedupe, ``hermes tools`` → "reconfigure existing" would
- list the same toolset twice.
+ Plugin toolsets are appended at the end so they appear after the built-in toolsets in the TUI
+ checklist. A plugin whose toolset key already appears in ``CONFIGURABLE_TOOLSETS`` is skipped —
+ bundled plugins (e.g.
"""
result = list(CONFIGURABLE_TOOLSETS)
seen = {ts_key for ts_key, _, _ in result}
@@ -263,21 +235,16 @@ def _get_plugin_toolset_keys() -> set:
def _checklist_toolset_keys(platform: str) -> Set[str]:
- """Return the toolset keys the ``hermes tools`` checklist actually offers
- for ``platform``.
+ """Return the toolset keys the ``hermes tools`` checklist actually offers for ``platform``.
This mirrors exactly what ``_prompt_toolset_checklist`` renders:
- ``_get_effective_configurable_toolsets()`` (built-in + plugin toolsets),
- filtered by ``_toolset_allowed_for_platform``. The checklist's returned
- selection can therefore only ever be a subset of this universe.
-
- Non-configurable toolsets that ``_get_platform_tools`` resolves at read
- time — ``kanban`` and other check_fn-gated toolsets, recovered platform
- composites, MCP server names — are NOT in this set because the checklist
- never shows them. Use this to scope the added/removed diff the UI prints,
- so ``hermes tools`` never claims to add or remove a toolset the user was
- never given a checkbox for. The underlying config is unaffected — those
- entries are preserved by ``_save_platform_tools`` regardless.
+ ``_get_effective_configurable_toolsets()`` (built-in + plugin toolsets), filtered by
+ ``_toolset_allowed_for_platform``. The checklist's returned selection can therefore only ever be
+ a subset of this universe.
+
+ Non-configurable toolsets that ``_get_platform_tools`` resolves at read time — ``kanban`` and
+ other check_fn-gated toolsets, recovered platform composites, MCP server names — are NOT in this
+ set because the checklist never shows them.
"""
return {
ts_key
@@ -297,6 +264,31 @@ PLATFORMS = {
}
+def _platform_default_toolset(platform: str) -> str:
+ """Composite toolset a platform falls back to (plugin platforms derive ``hermes-<platform>``)."""
+ plat_info = PLATFORMS.get(platform)
+ return plat_info["default_toolset"] if plat_info else f"hermes-{platform}"
+
+
+def _cfg_section(config: dict, key: str) -> dict:
+ """Return ``config[key]`` as a dict, replacing a missing or non-dict value with ``{}``."""
+ section = config.setdefault(key, {})
+ if not isinstance(section, dict):
+ section = {}
+ config[key] = section
+ return section
+
+
+def _is_configurable(ts_key: str) -> bool:
+ """True when the toolset has provider options or simple env-var requirements to prompt for."""
+ return bool(TOOL_CATEGORIES.get(ts_key) or TOOLSET_ENV_REQUIREMENTS.get(ts_key))
+
+
+def _toolset_label(ts_key: str) -> str:
+ """Display label for a toolset key (built-in or plugin), falling back to the key itself."""
+ return next((l for k, l, _ in _get_effective_configurable_toolsets() if k == ts_key), ts_key)
+
+
# ─── Tool Categories (provider-aware configuration) ──────────────────────────
# Maps toolset keys to their provider options. When a toolset is newly enabled,
# we use this to show provider selection and prompt for the right API keys.
@@ -307,162 +299,84 @@ TOOL_CATEGORIES = {
"name": "Text-to-Speech",
"icon": "🔊",
"providers": [
- {
- "name": "Microsoft Edge TTS",
- "badge": "★ recommended · free",
- "tag": "Good quality, no API key needed",
- "env_vars": [],
- "tts_provider": "edge",
- },
- {
- "name": "Nous Subscription",
- "badge": "subscription",
- "tag": "Managed OpenAI TTS billed to your subscription",
- "env_vars": [],
- "tts_provider": "openai",
- "requires_nous_auth": True,
- "managed_nous_feature": "tts",
- "override_env_vars": ["VOICE_TOOLS_OPENAI_KEY", "OPENAI_API_KEY"],
- },
- {
- "name": "OpenAI TTS",
- "badge": "paid",
- "tag": "High quality voices",
- "env_vars": [
- {"key": "VOICE_TOOLS_OPENAI_KEY", "prompt": "OpenAI API key", "url": "https://platform.openai.com/api-keys"},
- ],
- "tts_provider": "openai",
- },
- {
- "name": "xAI TTS",
- "tag": "Grok voices — uses xAI Grok OAuth or XAI_API_KEY",
- "env_vars": [],
- "tts_provider": "xai",
- "post_setup": "xai_grok",
- },
- {
- "name": "ElevenLabs",
- "badge": "paid",
- "tag": "Most natural voices",
- "env_vars": [
- {"key": "ELEVENLABS_API_KEY", "prompt": "ElevenLabs API key", "url": "https://elevenlabs.io/app/settings/api-keys"},
- ],
- "tts_provider": "elevenlabs",
- },
+ {"name": "Microsoft Edge TTS", "badge": "★ recommended · free",
+ "tag": "Good quality, no API key needed", "env_vars": [],
+ "tts_provider": "edge"},
+ {"name": "Nous Subscription", "badge": "subscription",
+ "tag": "Managed OpenAI TTS billed to your subscription", "env_vars": [],
+ "tts_provider": "openai", "requires_nous_auth": True, "managed_nous_feature": "tts",
+ "override_env_vars": ["VOICE_TOOLS_OPENAI_KEY", "OPENAI_API_KEY"]},
+ {"name": "OpenAI TTS", "badge": "paid", "tag": "High quality voices",
+ "env_vars": [
+ {"key": "VOICE_TOOLS_OPENAI_KEY", "prompt": "OpenAI API key", "url": "https://platform.openai.com/api-keys"},
+ ],
+ "tts_provider": "openai"},
+ {"name": "xAI TTS", "tag": "Grok voices — uses xAI Grok OAuth or XAI_API_KEY", "env_vars": [],
+ "tts_provider": "xai", "post_setup": "xai_grok"},
+ {"name": "ElevenLabs", "badge": "paid", "tag": "Most natural voices",
+ "env_vars": [
+ {"key": "ELEVENLABS_API_KEY", "prompt": "ElevenLabs API key", "url": "https://elevenlabs.io/app/settings/api-keys"},
+ ],
+ "tts_provider": "elevenlabs"},
# Mistral Voxtral TTS — `mistralai` SDK lazy-installs on first use.
- {
- "name": "Mistral (Voxtral TTS)",
- "badge": "paid",
- "tag": "Multilingual, native Opus",
- "env_vars": [
- {"key": "MISTRAL_API_KEY", "prompt": "Mistral API key", "url": "https://console.mistral.ai/"},
- ],
- "tts_provider": "mistral",
- },
- {
- "name": "Google Gemini TTS",
- "badge": "preview",
- "tag": "30 prebuilt voices, controllable via prompts",
- "env_vars": [
- {"key": "GEMINI_API_KEY", "prompt": "Gemini API key", "url": "https://aistudio.google.com/app/apikey"},
- ],
- "tts_provider": "gemini",
- },
- {
- "name": "KittenTTS",
- "badge": "local · free",
- "tag": "Lightweight local ONNX TTS (~25MB), no API key",
- "env_vars": [],
- "tts_provider": "kittentts",
- "post_setup": "kittentts",
- },
- {
- "name": "Piper",
- "badge": "local · free",
- "tag": "Local neural TTS, 44 languages (voices ~20-90MB)",
- "env_vars": [],
- "tts_provider": "piper",
- "post_setup": "piper",
- },
- {
- "name": "DeepInfra TTS",
- "badge": "paid",
- "tag": "Chatterbox, Qwen3-TTS, … — live catalog from api.deepinfra.com",
- "env_vars": [
- {"key": "DEEPINFRA_API_KEY", "prompt": "DeepInfra API key", "url": "https://deepinfra.com/dash/api_keys"},
- ],
- "tts_provider": "deepinfra",
- },
+ {"name": "Mistral (Voxtral TTS)", "badge": "paid", "tag": "Multilingual, native Opus",
+ "env_vars": [{"key": "MISTRAL_API_KEY", "prompt": "Mistral API key", "url": "https://console.mistral.ai/"}],
+ "tts_provider": "mistral"},
+ {"name": "Google Gemini TTS", "badge": "preview",
+ "tag": "30 prebuilt voices, controllable via prompts",
+ "env_vars": [
+ {"key": "GEMINI_API_KEY", "prompt": "Gemini API key", "url": "https://aistudio.google.com/app/apikey"},
+ ],
+ "tts_provider": "gemini"},
+ {"name": "KittenTTS", "badge": "local · free",
+ "tag": "Lightweight local ONNX TTS (~25MB), no API key", "env_vars": [],
+ "tts_provider": "kittentts", "post_setup": "kittentts"},
+ {"name": "Piper", "badge": "local · free",
+ "tag": "Local neural TTS, 44 languages (voices ~20-90MB)", "env_vars": [],
+ "tts_provider": "piper", "post_setup": "piper"},
+ {"name": "DeepInfra TTS", "badge": "paid",
+ "tag": "Chatterbox, Qwen3-TTS, … — live catalog from api.deepinfra.com",
+ "env_vars": [
+ {"key": "DEEPINFRA_API_KEY", "prompt": "DeepInfra API key", "url": "https://deepinfra.com/dash/api_keys"},
+ ],
+ "tts_provider": "deepinfra"},
],
},
"stt": {
"name": "Speech-to-Text",
"icon": "🎙️",
"providers": [
- {
- "name": "Local Whisper",
- "badge": "★ recommended · free",
- "tag": "faster-whisper on-device, no API key",
- "env_vars": [],
- "stt_provider": "local",
- "post_setup": "faster_whisper",
- },
- {
- "name": "Nous Subscription",
- "badge": "subscription",
- "tag": "Managed OpenAI transcription billed to your subscription",
- "env_vars": [],
- "stt_provider": "openai",
- "requires_nous_auth": True,
- "managed_nous_feature": "stt",
- "override_env_vars": ["VOICE_TOOLS_OPENAI_KEY", "OPENAI_API_KEY"],
- },
- {
- "name": "OpenAI",
- "badge": "paid",
- "tag": "whisper-1, gpt-4o-transcribe, gpt-transcribe",
- "env_vars": [
- {"key": "VOICE_TOOLS_OPENAI_KEY", "prompt": "OpenAI API key", "url": "https://platform.openai.com/api-keys"},
- ],
- "stt_provider": "openai",
- },
- {
- "name": "Groq",
- "badge": "free tier",
- "tag": "Whisper large-v3 family — very fast",
- "env_vars": [
- {"key": "GROQ_API_KEY", "prompt": "Groq API key", "url": "https://console.groq.com/keys"},
- ],
- "stt_provider": "groq",
- },
- {
- "name": "xAI",
- "tag": "grok-stt — uses xAI Grok OAuth or XAI_API_KEY",
- "env_vars": [],
- "stt_provider": "xai",
- "post_setup": "xai_grok",
- },
- {
- "name": "ElevenLabs Scribe",
- "badge": "paid",
- "tag": "scribe_v2 — diarization + audio-event tagging",
- "env_vars": [
- {"key": "ELEVENLABS_API_KEY", "prompt": "ElevenLabs API key", "url": "https://elevenlabs.io/app/settings/api-keys"},
- ],
- "stt_provider": "elevenlabs",
- },
+ {"name": "Local Whisper", "badge": "★ recommended · free",
+ "tag": "faster-whisper on-device, no API key", "env_vars": [],
+ "stt_provider": "local", "post_setup": "faster_whisper"},
+ {"name": "Nous Subscription", "badge": "subscription",
+ "tag": "Managed OpenAI transcription billed to your subscription", "env_vars": [],
+ "stt_provider": "openai", "requires_nous_auth": True, "managed_nous_feature": "stt",
+ "override_env_vars": ["VOICE_TOOLS_OPENAI_KEY", "OPENAI_API_KEY"]},
+ {"name": "OpenAI", "badge": "paid", "tag": "whisper-1, gpt-4o-transcribe, gpt-transcribe",
+ "env_vars": [
+ {"key": "VOICE_TOOLS_OPENAI_KEY", "prompt": "OpenAI API key", "url": "https://platform.openai.com/api-keys"},
+ ],
+ "stt_provider": "openai"},
+ {"name": "Groq", "badge": "free tier", "tag": "Whisper large-v3 family — very fast",
+ "env_vars": [{"key": "GROQ_API_KEY", "prompt": "Groq API key", "url": "https://console.groq.com/keys"}],
+ "stt_provider": "groq"},
+ {"name": "xAI", "tag": "grok-stt — uses xAI Grok OAuth or XAI_API_KEY", "env_vars": [],
+ "stt_provider": "xai", "post_setup": "xai_grok"},
+ {"name": "ElevenLabs Scribe", "badge": "paid",
+ "tag": "scribe_v2 — diarization + audio-event tagging",
+ "env_vars": [
+ {"key": "ELEVENLABS_API_KEY", "prompt": "ElevenLabs API key", "url": "https://elevenlabs.io/app/settings/api-keys"},
+ ],
+ "stt_provider": "elevenlabs"},
# Mistral Voxtral STT intentionally omitted — mistralai PyPI
# package quarantined (malicious 2.4.6 release, 2026-05-12).
# Restore alongside the dashboard stt.provider option.
- {
- "name": "DeepInfra",
- "badge": "paid",
- "tag": "Live STT catalog from api.deepinfra.com",
- "env_vars": [
- {"key": "DEEPINFRA_API_KEY", "prompt": "DeepInfra API key", "url": "https://deepinfra.com/dash/api_keys"},
- ],
- "stt_provider": "deepinfra",
- },
+ {"name": "DeepInfra", "badge": "paid", "tag": "Live STT catalog from api.deepinfra.com",
+ "env_vars": [
+ {"key": "DEEPINFRA_API_KEY", "prompt": "DeepInfra API key", "url": "https://deepinfra.com/dash/api_keys"},
+ ],
+ "stt_provider": "deepinfra"},
],
},
"web": {
@@ -470,61 +384,32 @@ TOOL_CATEGORIES = {
"setup_title": "Select Search Provider",
"setup_note": "A free DuckDuckGo search skill is also included — skip this if you don't need a premium provider.",
"icon": "🔍",
- # Per-provider rows are injected at runtime from
- # plugins.web.<vendor>.provider via _plugin_web_search_providers()
- # in _visible_providers(). Only non-provider UX setup-flow rows
- # for the firecrawl backend are listed here:
- # - "Nous Subscription" — managed Firecrawl billed via Nous
- # subscription (requires_nous_auth + override_env_vars).
- # - "Firecrawl Self-Hosted" — points firecrawl at a private
- # Docker instance via FIRECRAWL_API_URL only.
- # See PR #25182 for the migration rationale.
+ # Provider rows come from plugins.web.<vendor> via _plugin_web_search_providers()
+ # (PR #25182). Only the two non-provider firecrawl setup-flow rows live here:
+ # managed Firecrawl via Nous subscription, and a self-hosted FIRECRAWL_API_URL.
"providers": [
- {
- "name": "Nous Subscription",
- "badge": "subscription",
- "tag": "Managed Firecrawl billed to your subscription",
- "web_backend": "firecrawl",
- "env_vars": [],
- "requires_nous_auth": True,
- "managed_nous_feature": "web",
- "override_env_vars": ["FIRECRAWL_API_KEY", "FIRECRAWL_API_URL"],
- },
- {
- "name": "Firecrawl Self-Hosted",
- "badge": "free · self-hosted",
- "tag": "Run your own Firecrawl instance (Docker)",
- "web_backend": "firecrawl",
- "env_vars": [
- {"key": "FIRECRAWL_API_URL", "prompt": "Your Firecrawl instance URL (e.g., http://localhost:3002)"},
- ],
- },
+ {"name": "Nous Subscription", "badge": "subscription",
+ "tag": "Managed Firecrawl billed to your subscription", "web_backend": "firecrawl",
+ "env_vars": [],
+ "requires_nous_auth": True, "managed_nous_feature": "web",
+ "override_env_vars": ["FIRECRAWL_API_KEY", "FIRECRAWL_API_URL"]},
+ {"name": "Firecrawl Self-Hosted", "badge": "free · self-hosted",
+ "tag": "Run your own Firecrawl instance (Docker)", "web_backend": "firecrawl",
+ "env_vars": [{"key": "FIRECRAWL_API_URL", "prompt": "Your Firecrawl instance URL (e.g., http://localhost:3002)"}]},
],
},
"image_gen": {
"name": "Image Generation",
"icon": "🎨",
- # Per-provider rows for FAL.ai (`plugins/image_gen/fal`), OpenAI,
- # OpenAI Codex, and xAI are injected at runtime from each
- # ``plugins.image_gen.<vendor>`` package via
- # ``_plugin_image_gen_providers()`` in ``_visible_providers``.
- # Only non-provider UX setup-flow rows remain here:
- # - "Nous Subscription" — managed FAL billed via the Nous
- # subscription (requires_nous_auth + override_env_vars).
- # Uses the fal plugin as the underlying backend but has a
- # distinct setup UX.
- # Mirrors the shape browser/video_gen ship today.
+ # Provider rows (FAL, OpenAI, OpenAI Codex, xAI) come from plugins.image_gen.<vendor>
+ # via _plugin_image_gen_providers(). Only the managed "Nous Subscription" setup-flow row
+ # lives here — it uses the fal plugin as backend but has a distinct UX.
"providers": [
- {
- "name": "Nous Subscription",
- "badge": "subscription",
- "tag": "Managed FAL image generation billed to your subscription",
- "env_vars": [],
- "requires_nous_auth": True,
- "managed_nous_feature": "image_gen",
- "override_env_vars": ["FAL_KEY"],
- "imagegen_backend": "fal",
- },
+ {"name": "Nous Subscription", "badge": "subscription",
+ "tag": "Managed FAL image generation billed to your subscription", "env_vars": [],
+ "requires_nous_auth": True, "managed_nous_feature": "image_gen",
+ "override_env_vars": ["FAL_KEY"],
+ "imagegen_backend": "fal"},
],
},
"video_gen": {
@@ -565,68 +450,31 @@ TOOL_CATEGORIES = {
),
"icon": "🐦",
"providers": [
- {
- "name": "xAI Grok OAuth (SuperGrok / Premium+)",
- "badge": "subscription",
- "tag": "Browser login at accounts.x.ai — no API key required",
- "env_vars": [],
- "post_setup": "xai_grok",
- },
- {
- "name": "xAI API key",
- "badge": "paid",
- "tag": "Direct xAI API billing via XAI_API_KEY",
- "env_vars": [
- {
- "key": "XAI_API_KEY",
- "prompt": "xAI API key",
- "url": "https://console.x.ai/",
- },
- ],
- },
+ {"name": "xAI Grok OAuth (SuperGrok / Premium+)", "badge": "subscription",
+ "tag": "Browser login at accounts.x.ai — no API key required", "env_vars": [],
+ "post_setup": "xai_grok"},
+ {"name": "xAI API key", "badge": "paid", "tag": "Direct xAI API billing via XAI_API_KEY",
+ "env_vars": [{"key": "XAI_API_KEY", "prompt": "xAI API key", "url": "https://console.x.ai/"}]},
],
},
"browser": {
"name": "Browser Automation",
"icon": "🌐",
- # Per-provider rows for Browserbase, Browser Use, and Firecrawl are
- # injected at runtime from plugins.browser.<vendor>.provider via
- # _plugin_browser_providers() in _visible_providers(). Only
- # non-provider UX setup-flow rows remain here. "Local Browser" is
- # listed FIRST so it is the default-highlighted (index 0) choice on a
- # fresh install — pressing Enter must land on the free, no-key local
- # backend, never on the paid Nous Subscription gateway row:
- # - "Local Browser" — non-cloud option, no CloudBrowserProvider.
- # - "Lightpanda" — local too (cloud_provider: local) but with
- # browser.engine: lightpanda; Browser Use mode spawns
- # ``lightpanda serve`` itself, the built-in tools use
- # ``agent-browser --engine lightpanda``. No Chromium needed.
- # - "Nous Subscription (Browser Use cloud)" — managed Browser Use
- # billed via Nous subscription (requires_nous_auth +
- # override_env_vars). Uses the browser-use plugin as the
- # underlying backend but has a distinct setup UX.
- # - "Camofox" — anti-detection local Firefox; short-circuits the
- # cloud-provider dispatch path via _is_camofox_mode().
- # - "Browser Use" — the Browser Use CLI 3.0
+ # Cloud provider rows (Browserbase, Browser Use, Firecrawl) come from
+ # plugins.browser.<vendor> via _plugin_browser_providers() (PR #25214). Only
+ # non-provider setup-flow rows live here. "Local Browser" MUST stay first so a fresh
+ # install's Enter lands on the free local backend (index 0), never on the paid Nous row.
+ # Lightpanda is local too (cloud_provider: local, browser.engine: lightpanda — Browser Use
+ # mode spawns ``lightpanda serve``, built-in tools use ``agent-browser --engine
+ # lightpanda``; no Chromium). Camofox short-circuits the cloud dispatch via
+ # _is_camofox_mode().
"providers": [
- {
- "name": "Local Browser",
- "badge": "★ recommended · free",
- "tag": "Headless Chromium, no API key needed",
- "env_vars": [],
- "browser_provider": "local",
- "browser_engine": "auto",
- "post_setup": "agent_browser",
- },
- {
- "name": "Lightpanda",
- "badge": "free · local · no Chromium",
- "tag": "Zig headless browser spawned by Hermes, text-only (no screenshots)",
- "env_vars": [],
- "browser_provider": "local",
- "browser_engine": "lightpanda",
- "post_setup": "lightpanda",
- },
+ {"name": "Local Browser", "badge": "★ recommended · free",
+ "tag": "Headless Chromium, no API key needed", "env_vars": [],
+ "browser_provider": "local", "browser_engine": "auto", "post_setup": "agent_browser"},
+ {"name": "Lightpanda", "badge": "free · local · no Chromium",
+ "tag": "Zig headless browser spawned by Hermes, text-only (no screenshots)", "env_vars": [],
+ "browser_provider": "local", "browser_engine": "lightpanda", "post_setup": "lightpanda"},
{
"name": "Nous Subscription (Browser Use cloud)",
"badge": "subscription",
@@ -643,51 +491,33 @@ TOOL_CATEGORIES = {
# machines without a local Chromium build.
"post_setup": "browserbase",
},
- {
- "name": "Camofox",
- "badge": "free · local",
- "tag": "Anti-detection browser (Firefox/Camoufox)",
- "env_vars": [
- {"key": "CAMOFOX_URL", "prompt": "Camofox server URL", "default": "http://localhost:9377",
- "url": "https://github.com/jo-inc/camofox-browser"},
- ],
- "browser_provider": "camofox",
- "post_setup": "camofox",
- },
- {
- "name": "Browser Use",
- "badge": "free · local · cloud",
- "tag": "New SOTA web harness (CLI 3.0)",
- "env_vars": [],
- "browser_backend": "browser-use",
- "post_setup": "browser_use_cli",
- },
+ {"name": "Camofox", "badge": "free · local", "tag": "Anti-detection browser (Firefox/Camoufox)",
+ "env_vars": [
+ {"key": "CAMOFOX_URL", "prompt": "Camofox server URL", "default": "http://localhost:9377", "url": "https://github.com/jo-inc/camofox-browser"},
+ ],
+ "browser_provider": "camofox", "post_setup": "camofox"},
+ {"name": "Browser Use", "badge": "free · local · cloud", "tag": "New SOTA web harness (CLI 3.0)",
+ "env_vars": [],
+ "browser_backend": "browser-use", "post_setup": "browser_use_cli"},
],
},
"homeassistant": {
"name": "Smart Home",
"icon": "🏠",
"providers": [
- {
- "name": "Home Assistant",
- "tag": "REST API integration",
- "env_vars": [
- {"key": "HASS_TOKEN", "prompt": "Home Assistant Long-Lived Access Token"},
- {"key": "HASS_URL", "prompt": "Home Assistant URL", "default": "http://homeassistant.local:8123"},
- ],
- },
+ {"name": "Home Assistant", "tag": "REST API integration",
+ "env_vars": [
+ {"key": "HASS_TOKEN", "prompt": "Home Assistant Long-Lived Access Token"},
+ {"key": "HASS_URL", "prompt": "Home Assistant URL", "default": "http://homeassistant.local:8123"},
+ ]},
],
},
"spotify": {
"name": "Spotify",
"icon": "🎵",
"providers": [
- {
- "name": "Spotify Web API",
- "tag": "PKCE OAuth — opens the setup wizard",
- "env_vars": [],
- "post_setup": "spotify",
- },
+ {"name": "Spotify Web API", "tag": "PKCE OAuth — opens the setup wizard", "env_vars": [],
+ "post_setup": "spotify"},
],
},
"computer_use": {
@@ -719,25 +549,19 @@ TOOL_CATEGORIES = {
"name": "Langfuse Observability",
"icon": "📊",
"providers": [
- {
- "name": "Langfuse Cloud",
- "tag": "Hosted Langfuse (cloud.langfuse.com)",
- "env_vars": [
- {"key": "HERMES_LANGFUSE_PUBLIC_KEY", "prompt": "Langfuse public key (pk-lf-...)", "url": "https://cloud.langfuse.com"},
- {"key": "HERMES_LANGFUSE_SECRET_KEY", "prompt": "Langfuse secret key (sk-lf-...)", "url": "https://cloud.langfuse.com"},
- ],
- "post_setup": "langfuse",
- },
- {
- "name": "Langfuse Self-Hosted",
- "tag": "Self-hosted Langfuse instance",
- "env_vars": [
- {"key": "HERMES_LANGFUSE_PUBLIC_KEY", "prompt": "Langfuse public key (pk-lf-...)"},
- {"key": "HERMES_LANGFUSE_SECRET_KEY", "prompt": "Langfuse secret key (sk-lf-...)"},
- {"key": "HERMES_LANGFUSE_BASE_URL", "prompt": "Langfuse server URL (e.g. http://localhost:3000)", "default": "http://localhost:3000"},
- ],
- "post_setup": "langfuse",
- },
+ {"name": "Langfuse Cloud", "tag": "Hosted Langfuse (cloud.langfuse.com)",
+ "env_vars": [
+ {"key": "HERMES_LANGFUSE_PUBLIC_KEY", "prompt": "Langfuse public key (pk-lf-...)", "url": "https://cloud.langfuse.com"},
+ {"key": "HERMES_LANGFUSE_SECRET_KEY", "prompt": "Langfuse secret key (sk-lf-...)", "url": "https://cloud.langfuse.com"},
+ ],
+ "post_setup": "langfuse"},
+ {"name": "Langfuse Self-Hosted", "tag": "Self-hosted Langfuse instance",
+ "env_vars": [
+ {"key": "HERMES_LANGFUSE_PUBLIC_KEY", "prompt": "Langfuse public key (pk-lf-...)"},
+ {"key": "HERMES_LANGFUSE_SECRET_KEY", "prompt": "Langfuse secret key (sk-lf-...)"},
+ {"key": "HERMES_LANGFUSE_BASE_URL", "prompt": "Langfuse server URL (e.g. http://localhost:3000)", "default": "http://localhost:3000"},
+ ],
+ "post_setup": "langfuse"},
],
},
}
@@ -768,12 +592,8 @@ def _cua_driver_cmd() -> str:
def _cua_version_summary(raw: str, *, limit: int = 120) -> str:
"""Reduce a driver's ``--version`` output to one short status line.
- A binary selected by ``HERMES_CUA_DRIVER_CMD`` is not obliged to answer
- ``--version`` the way cua-driver does. Pointing the override at, say,
- ``cmd.exe`` yields a multi-line banner plus a prompt, which used to be
- interpolated verbatim into ``cua-driver: installed at ... (<version>)``
- and shattered the one-line summary. Keep the first non-empty line and
- bound its length.
+ A ``HERMES_CUA_DRIVER_CMD`` override may print a multi-line banner (e.g. cmd.exe); interpolating
+ it verbatim shattered the one-line status summary, so keep the first non-empty line, bounded.
"""
for line in (raw or "").splitlines():
text = line.strip()
@@ -792,10 +612,9 @@ def _resolved_cua_driver_cmd() -> Optional[str]:
def _cua_driver_env() -> dict:
"""cua-driver child env with the Hermes telemetry policy applied.
- Delegates to ``cua_backend.cua_driver_child_env`` (telemetry disabled by
- default; user opt-in via ``computer_use.cua_telemetry``). Falls back to the
- current environment if the helper can't be imported, so install/status
- never break on a telemetry-helper error.
+ Delegates to ``cua_backend.cua_driver_child_env`` (telemetry disabled by default; user opt-in
+ via ``computer_use.cua_telemetry``). Falls back to the current environment if the helper can't
+ be imported, so install/status never break on a telemetry-helper error.
"""
try:
from tools.computer_use.cua_backend import cua_driver_child_env
@@ -843,9 +662,7 @@ def _cua_driver_install_ready() -> bool:
"""Return whether an existing driver needs no install-time repair."""
if not _cua_driver_contract_status().get("ready"):
return False
- if sys.platform == "win32":
- return _cua_driver_autostart_registered_windows()
- return True
+ return sys.platform != "win32" or _cua_driver_autostart_registered_windows()
def _pip_install(
@@ -856,19 +673,13 @@ def _pip_install(
):
"""Install Python packages from a post-setup hook.
- Strategy (in order):
- 1. ``uv pip install`` if uv is on PATH — fast, doesn't need pip in the venv.
- 2. ``python -m pip install`` — works on stdlib venvs.
- 3. ``python -m ensurepip --upgrade`` then retry pip — covers ``uv venv``
- which creates a venv WITHOUT pip.
-
- Why this exists: the Windows installer creates the venv via ``uv venv``,
- which doesn't seed pip. Post-setup hooks that shelled out to
- ``[sys.executable, '-m', 'pip', 'install', ...]`` failed with
- ``No module named pip`` on every fresh install. uv-first sidesteps that.
+ Strategy (in order): 1. ``uv pip install`` if uv is on PATH — fast, doesn't need pip in the
+ venv. 2. ``python -m pip install`` — works on stdlib venvs. 3. ``python -m ensurepip --upgrade``
+ then retry pip — covers ``uv venv`` which creates a venv WITHOUT pip.
- Returns the ``subprocess.CompletedProcess`` from whichever tier succeeded
- (or the last failure for the caller to inspect).
+ Why this exists: the Windows installer creates the venv via ``uv venv``, which doesn't seed pip.
+ Post-setup hooks that shelled out to ``[sys.executable, '-m', 'pip', 'install', ...]`` failed
+ with ``No module named pip`` on every fresh install. uv-first sidesteps that.
"""
venv_root = Path(sys.executable).parent.parent
uv_env = {**os.environ, "VIRTUAL_ENV": str(venv_root)}
@@ -932,47 +743,37 @@ def _pip_install(
)
-
-# The asset-probe that lived here used to hit `/releases/latest` on
-# trycua/cua and inspect the release's asset list before piping the
-# installer to bash. It was broken in two places:
-#
-# 1. cua-driver-rs releases are marked **prerelease** on every cut,
-# and GitHub's `/releases/latest` endpoint explicitly skips
-# prereleases. On the live trycua/cua repo today, `/releases/latest`
-# returns the Python `cua-agent v0.8.3` package (zero binary
-# assets) instead of `cua-driver-rs-v0.6.0` (19 binary assets).
-# The probe then reported "no asset for this arch" and skipped the
-# install on every non-arm64 host — Linux x86_64, Windows, macOS
-# Intel, Linux arm64 — even when the upstream installer would have
-# succeeded.
-# 2. Even with the right endpoint, we'd be duplicating tag-resolution
-# logic the upstream installer already does correctly via
-# `CUA_DRIVER_RS_BAKED_VERSION` (auto-baked by CD on every release,
-# with an API fallback). Drift between our probe and theirs is a
-# maintenance hazard.
-#
-# Resolution: trust the upstream installer. For fresh installs, run
-# install.sh directly — it errors clean if the target arch has no
-# asset. For the upgrade path, `cua_driver_update_check()` (which calls
-# `cua-driver check-update --json`) gives us the canonical update
-# answer from the binary itself — same tag-resolution as the installer,
-# no Python-side duplication.
+# No pre-install release/asset probe: cua-driver-rs releases are all
+# prereleases, which GitHub's `/releases/latest` skips (it returned the Python
+# `cua-agent` package with zero binary assets and made every non-arm64 host
+# skip the install), and re-implementing upstream's tag resolution
+# (`CUA_DRIVER_RS_BAKED_VERSION`) here would drift. Trust the installer: fresh
+# installs run install.sh directly (it errors clean on a missing-arch asset);
+# upgrades ask the binary via `cua_driver_update_check()`.
def _cua_install_target_writable() -> bool:
"""Return whether the upstream installer can write its app bundle target."""
if sys.platform != "darwin":
return True
- applications_dir = "/Applications"
try:
- if not os.path.isdir(applications_dir):
- return True
- return os.access(applications_dir, os.W_OK)
+ return not os.path.isdir("/Applications") or os.access("/Applications", os.W_OK)
except Exception:
return True
+def _cua_driver_version(binary: str) -> Optional[str]:
+ """``<binary> --version`` stdout (possibly ""), or None when the probe itself fails."""
+ try:
+ return subprocess.run(
+ [binary, "--version"],
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5, env=_cua_driver_env(),
+ creationflags=_post_setup_no_window_flags(),
+ ).stdout.strip()
+ except Exception:
+ return None
+
+
def install_cua_driver(
upgrade: bool = False,
require_confirmed_update: bool = False,
@@ -980,50 +781,15 @@ def install_cua_driver(
) -> bool:
"""Install or refresh the cua-driver binary used by Computer Use.
- The upstream installer always pulls the latest release tag, so re-running
- it is the canonical way to upgrade. We expose two modes:
-
- * ``upgrade=False`` — keep a compatible Cua Driver 0.20 installation,
- repair an old or incomplete installation, and install when missing.
- Used by the toolset enable flow.
- * ``upgrade=True`` — always re-run the installer (or call ``cua-driver
- update`` if the binary supports it). Used by ``hermes update`` and
- by ``hermes computer-use install --upgrade``.
-
- ``require_confirmed_update`` (only meaningful with ``upgrade=True`` and
- an installed binary): when the driver's native ``check-update`` verb
- can't positively confirm that a newer release exists — the driver is
- too old for the verb, the GitHub check failed, we're offline, or the
- probe timed out — keep the installed version and return instead of
- falling through to the full upstream installer. ``hermes update`` sets
- this so a broken update check costs seconds, not a multi-minute silent
- reinstall on every update (the upstream installer runs up to
- ``_CUA_INSTALLER_TIMEOUT`` and install.ps1's concurrency lock can add
- a further ~600s wait on Windows). ``hermes computer-use install
- --upgrade`` leaves it False — an explicit upgrade request should still
- reinstall when the check is indeterminate. On Windows this flag also
- defers contract REPAIRS and fresh INSTALLS to the explicit command
- (those paths can legitimately need a human: first-time autostart
- elevation, SmartScreen). Routine confirmed upgrades DO run, in
- unattended-safe mode: stdin closed, version pinned, lock/network
- preflights, and the shorter background ceiling below.
-
- ``show_installer_progress`` controls the installer's own progress line.
- ``hermes update`` already prints a contextual line before its update
- check, so it disables this to avoid printing the refresh twice.
-
- The confirmed-update path is also bounded by
- ``_CUA_BACKGROUND_UPDATE_TIMEOUT``. It runs as an optional, quiet part of
- ``hermes update`` and must not inherit the explicit install command's
- 11-minute ceiling when an upstream prompt or UAC dialog is unattended.
-
- Returns True iff cua-driver is installed (or successfully refreshed)
- when the function returns. Supported on macOS, Windows, and Linux
- (Linux is alpha). Silently returns False on unsupported platforms.
+ The upstream installer always pulls the latest release tag, so re-running it is the canonical
+ way to upgrade. We expose two modes:
+
+ * ``upgrade=False`` — keep a compatible Cua Driver 0.20 installation, repair an old or
+ incomplete installation, and install when missing. Used by the toolset enable flow. *
+ ``upgrade=True`` — always re-run the installer (or call ``cua-driver update`` if the binary
+ supports it).
"""
import platform as _plat
- import shutil
- import subprocess
system = _plat.system()
if system not in ("Darwin", "Windows", "Linux"):
@@ -1072,9 +838,6 @@ def install_cua_driver(
_print_warning(f" {fetch_tool} not found — install manually:")
_print_info(" https://github.com/trycua/cua/blob/main/libs/cua-driver/README.md")
return False
- # Pre-install asset probe deleted — see comment near the top of
- # tools_config.py for why. install.sh has CUA_DRIVER_RS_BAKED_VERSION
- # baked in by CD and errors cleanly on missing-arch assets.
return _run_cua_driver_installer(label="Installing")
# An installed driver that fails Hermes' runtime contract (version floor,
@@ -1091,29 +854,17 @@ def install_cua_driver(
# A compatible existing installation needs no download. Finish the small
# host-specific setup that the upstream installer normally owns.
if binary and not upgrade and not repair_existing:
- try:
- version = subprocess.run(
- [binary, "--version"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5, env=_cua_driver_env(),
- creationflags=_post_setup_no_window_flags(),
- ).stdout.strip()
- _print_success(f" {driver_cmd} already installed: {version or 'unknown version'}")
- except Exception:
+ version = _cua_driver_version(binary)
+ if version is None:
_print_success(f" {driver_cmd} already installed.")
- if is_windows:
- if not _repair_cua_driver_autostart_windows(binary, verbose=False):
- _print_warning(
- " cua-driver is compatible, but Windows autostart repair failed."
- )
- return False
- _print_info(" cua-driver may spawn a UIAccess worker (cua-driver-uia.exe);")
- _print_info(" Windows/SmartScreen may prompt the first time it runs.")
- elif is_linux:
- _print_warning(" Linux support is alpha.")
else:
- _print_info(" Grant macOS permissions if not done yet:")
- _print_info(" System Settings > Privacy & Security > Accessibility")
- _print_info(" System Settings > Privacy & Security > Screen Recording")
+ _print_success(f" {driver_cmd} already installed: {version or 'unknown version'}")
+ if is_windows and not _repair_cua_driver_autostart_windows(binary, verbose=False):
+ _print_warning(
+ " cua-driver is compatible, but Windows autostart repair failed."
+ )
+ return False
+ _print_cua_platform_notes(is_windows, is_linux, fresh_install=False)
return True
if repair_existing:
@@ -1155,11 +906,6 @@ def install_cua_driver(
_print_warning(f" {fetch_tool} not found — cannot refresh cua-driver.")
return bool(binary)
- # Pre-install asset probe deleted (see top-of-file comment). The
- # `cua_driver_update_check()` call further down asks the installed
- # cua-driver binary itself whether an update exists — same
- # tag-resolution as the installer, no duplication.
-
# Skip the (network) re-install when the driver itself reports it's already
# on the latest release. Best-effort: an older driver (no check-update
# verb) or an offline check returns None. What happens then depends on the
@@ -1231,18 +977,8 @@ def install_cua_driver(
)
return False
- if binary:
- # Show before/after version when we have a baseline. Best-effort.
- try:
- before = subprocess.run(
- [binary, "--version"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5, env=_cua_driver_env(),
- creationflags=_post_setup_no_window_flags(),
- ).stdout.strip()
- except Exception:
- before = ""
- else:
- before = ""
+ # Show before/after version when we have a baseline. Best-effort.
+ before = (_cua_driver_version(binary) or "") if binary else ""
ok = _run_cua_driver_installer(
label="Repairing" if repair_existing else "Refreshing",
@@ -1265,18 +1001,11 @@ def install_cua_driver(
_print_info(" Run: hermes computer-use doctor")
return False
if ok and before:
- try:
- after = subprocess.run(
- [binary, "--version"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=5, env=_cua_driver_env(),
- creationflags=_post_setup_no_window_flags(),
- ).stdout.strip()
- if after and after != before:
- _print_success(f" {driver_cmd} upgraded: {before} → {after}")
- elif after:
- _print_info(f" {driver_cmd} up to date: {after}")
- except Exception:
- pass
+ after = _cua_driver_version(binary)
+ if after and after != before:
+ _print_success(f" {driver_cmd} upgraded: {before} → {after}")
+ elif after:
+ _print_info(f" {driver_cmd} up to date: {after}")
return ok
@@ -1333,11 +1062,9 @@ def _cua_windows_install_lock_file() -> "Path":
def _clear_stale_windows_cua_install_lock() -> None:
"""Delete install.ps1's lock file only when no process still holds it.
- ``install.ps1`` serializes installs with a ``FileStream`` opened using
- ``FileShare::None``. Mirror that primitive with a zero-share
- ``CreateFileW`` probe. ``FILE_FLAG_DELETE_ON_CLOSE`` removes an unlocked
- leftover atomically when the probe handle closes, avoiding a gap where a
- new installer could acquire the file between our probe and deletion.
+ install.ps1 locks with ``FileShare::None``; mirror it with a zero-share ``CreateFileW`` probe
+ and ``FILE_FLAG_DELETE_ON_CLOSE`` so an unlocked leftover is removed atomically, with no window
+ in which a new installer could acquire the file between probe and delete.
"""
lock_file = _cua_windows_install_lock_file()
try:
@@ -1414,11 +1141,10 @@ def _clear_stale_windows_cua_install_lock() -> None:
def _clear_stale_cua_install_lock() -> None:
"""Best-effort: remove a stale installer lock left by a dead holder.
- The POSIX installer stamps its holder pid into
- ``~/.cua-driver/packages/.install.lock.d/info``. The Windows installer
- instead holds ``~/.cua-driver/install.lock`` open with
- ``FileShare::None``. Clear either artifact up front only when its
- platform-specific liveness check proves that no install still holds it.
+ The POSIX installer stamps its holder pid into ``~/.cua-driver/packages/.install.lock.d/info``.
+ The Windows installer instead holds ``~/.cua-driver/install.lock`` open with
+ ``FileShare::None``. Clear either artifact up front only when its platform-specific liveness
+ check proves that no install still holds it.
"""
if sys.platform == "win32":
_clear_stale_windows_cua_install_lock()
@@ -1458,8 +1184,7 @@ def _clear_stale_cua_install_lock() -> None:
if age < _CUA_LOCK_STALE_AFTER:
return
- import shutil as _shutil
- _shutil.rmtree(lock_dir, ignore_errors=True)
+ shutil.rmtree(lock_dir, ignore_errors=True)
logger.info("Cleared stale cua-driver install lock at %s", lock_dir)
_print_info(f" Cleared stale cua-driver install lock ({lock_dir}).")
except Exception as e:
@@ -1469,13 +1194,8 @@ def _clear_stale_cua_install_lock() -> None:
def _cua_install_lock_held() -> bool:
"""True when the upstream installer's lock is held by a LIVE process.
- Called after ``_clear_stale_cua_install_lock()``: anything provably
- stale is already gone, so a surviving lock artifact means a concurrent
- (or orphaned-but-alive) install owns it. Upstream waits up to
- ``LOCK_STALE_AFTER_SECONDS=600`` on a held lock before probing —
- unattended refreshes must not eat that wait (the 11-minute hang class,
- #87703): they skip instead. Best-effort: unreadable state reports
- not-held so a probe failure can never block an install.
+ Called after ``_clear_stale_cua_install_lock()``: anything provably stale is already gone, so a
+ surviving lock artifact means a concurrent (or orphaned-but-alive) install owns it.
"""
try:
if sys.platform == "win32":
@@ -1489,9 +1209,7 @@ def _cua_install_lock_held() -> bool:
try:
with open(lock_file, "r+b"):
return False # opened fine → not held (racy leftover)
- except PermissionError:
- return True
- except OSError:
+ except OSError: # sharing violation surfaces as PermissionError
return True
lock_dir = _cua_install_lock_dir()
return lock_dir.is_dir()
@@ -1503,13 +1221,9 @@ def _cua_install_lock_held() -> bool:
def _cua_release_endpoint_reachable(timeout: float = 5.0) -> bool:
"""Fast probe: can we reach GitHub's release download host at all?
- The upstream installers (install.ps1 / _install-rust.sh) download from
- ``github.com/<repo>/releases/download/...``. When that host is
- unreachable (outage, DNS, firewall), the installer dies slowly inside
- its own retries while the unattended refresh eats the whole ceiling.
- A 5s HEAD tells us in seconds. Only a *connection-level* failure counts
- as unreachable — any HTTP response (including 4xx/5xx) proves the path
- works and lets the installer make its own decisions.
+ When github.com is down the installer dies slowly inside its own retries and eats the whole
+ unattended ceiling; a 5s HEAD decides in seconds. Only a connection-level failure counts as
+ unreachable — any HTTP response (even 4xx/5xx) proves the path works.
"""
import urllib.error
import urllib.request
@@ -1536,8 +1250,6 @@ def _cua_driver_autostart_registered_windows() -> bool:
"""Return whether the Windows cua-driver scheduled task is registered."""
if sys.platform != "win32":
return False
- import subprocess
-
try:
result = subprocess.run(
["schtasks.exe", "/Query", "/TN", "cua-driver-serve"],
@@ -1553,21 +1265,15 @@ def _cua_driver_autostart_registered_windows() -> bool:
def _repair_cua_driver_autostart_windows(driver_cmd: str, *, verbose: bool) -> bool:
"""Best-effort repair for Windows installer autostart quoting failures.
- Older install.ps1 builds invoked
- ``& C:\\Users\\Name With Spaces\\...\\cua-driver`` from an elevated
- PowerShell command string, which PowerShell split at the first space. If
- the installer left the scheduled task missing, retry by
- launching the resolved binary through Start-Process's structured
- ``-FilePath`` / ``-ArgumentList`` parameters instead of interpolating a
- path into a command string.
+ Older install.ps1 builds interpolated the binary path into a PowerShell command string, which
+ split at the first space. If the scheduled task is missing, retry via Start-Process's structured
+ ``-FilePath`` / ``-ArgumentList`` parameters instead.
"""
if sys.platform != "win32":
return True
if _cua_driver_autostart_registered_windows():
return True
- import subprocess
-
binary = shutil.which(driver_cmd)
if not binary:
return False
@@ -1614,6 +1320,31 @@ def _repair_cua_driver_autostart_windows(driver_cmd: str, *, verbose: bool) -> b
return False
+def _remove_quietly(path: str) -> None:
+ try:
+ os.remove(path)
+ except OSError:
+ pass
+
+
+def _print_cua_platform_notes(is_windows: bool, is_linux: bool, *, fresh_install: bool) -> None:
+ """Host-specific follow-up notes after an install or a compatible-install check."""
+ if is_windows:
+ _print_info(" cua-driver may spawn a UIAccess worker (cua-driver-uia.exe);")
+ _print_info(" Windows/SmartScreen may prompt the first time it runs.")
+ elif is_linux:
+ _print_warning(" Linux support is alpha.")
+ elif fresh_install:
+ _print_info(" IMPORTANT — grant macOS permissions now:")
+ _print_info(" System Settings > Privacy & Security > Accessibility")
+ _print_info(" System Settings > Privacy & Security > Screen Recording")
+ _print_info(" Both must allow the terminal / Hermes process.")
+ else:
+ _print_info(" Grant macOS permissions if not done yet:")
+ _print_info(" System Settings > Privacy & Security > Accessibility")
+ _print_info(" System Settings > Privacy & Security > Screen Recording")
+
+
def _run_cua_driver_installer(
label: str = "Installing",
verbose: bool = True,
@@ -1623,26 +1354,13 @@ def _run_cua_driver_installer(
) -> bool:
"""Run the upstream cua-driver installer for this platform.
- The scripts are idempotent: they always download the latest release, so
- re-running on an already-installed system performs an upgrade.
-
- * macOS / Linux → ``curl -fsSL …/install.sh | /bin/bash``.
- * Windows → ``powershell -NoProfile -ExecutionPolicy Bypass -Command
- "irm …/install.ps1 | iex"``.
+ The scripts are idempotent: they always download the latest release, so re-running on an
+ already-installed system performs an upgrade.
- ``pin_version`` (e.g. ``"0.13.1"``) is exported as
- ``CUA_DRIVER_RS_VERSION`` so the installer downloads that exact release
- instead of its baked-in default. The baked version on upstream ``main``
- is bumped by Release Please *before* the release assets are published,
- so an unpinned run inside that window fails with a 404; pinning to the
- version ``check-update`` confirmed sidesteps the race entirely.
-
- ``installer_timeout`` lets quiet callers use a shorter ceiling without
- weakening the explicit install path's stale-lock recovery window.
+ ``installer_timeout`` lets quiet callers use a shorter ceiling without weakening the explicit
+ install path's stale-lock recovery window.
"""
import platform as _plat
- import shutil
- import subprocess
system = _plat.system()
is_windows = system == "Windows"
@@ -1684,25 +1402,14 @@ def _run_cua_driver_installer(
["curl", "-fsSL", "-o", script_path, install_url],
capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=120,
)
+ failure = None if dl.returncode == 0 else (dl.stderr or "").strip()[:200]
except (subprocess.TimeoutExpired, OSError) as e:
- _print_warning(f" cua-driver installer download failed: {e}")
- try:
- os.remove(script_path)
- except OSError:
- pass
- return False
- if dl.returncode != 0:
- _print_warning(
- " cua-driver installer download failed: "
- f"{(dl.stderr or '').strip()[:200]}"
- )
- try:
- os.remove(script_path)
- except OSError:
- pass
+ failure = str(e)
+ if failure is not None:
+ _print_warning(f" cua-driver installer download failed: {failure}")
+ _remove_quietly(script_path)
return False
install_cmd = ["/bin/bash", script_path]
- use_shell = False
if show_progress:
if verbose:
@@ -1833,23 +1540,9 @@ def _run_cua_driver_installer(
def _reap_after_timeout(proc):
"""Kill the installer tree, then drain its pipes under a deadline.
- ``_kill_installer_tree`` is best-effort by construction: every
- ``psutil.Error`` it can raise is logged at debug level and stepped
- over, on the reasoning that a partly-killed tree beats none. The case
- that matters is an ``install.ps1`` which self-elevated through
- ``Start-Process -Verb RunAs``: that descendant runs at High integrity,
- a medium-integrity kill gets ``AccessDenied``, and the survivor is
- still holding the ``stdout=PIPE`` write handle it inherited.
-
- Draining with no deadline then blocks on an EOF that only arrives when
- someone kills that process by hand, so the ``_CUA_INSTALLER_TIMEOUT``
- ceiling stops bounding anything and ``hermes update`` hangs past its
- own timeout warning (#87703). Bound the drain instead: a kill that
- landed closes the pipe at once, and one that did not costs
- ``_CUA_INSTALLER_DRAIN_GRACE`` rather than forever. The caller
- re-raises the original ``TimeoutExpired`` either way, so the manual
- re-run hint still prints and the update unwinds. Losing the tail of a
- timed-out installer's log is the cheaper half of that trade.
+ Draining with no deadline then blocks on an EOF that only arrives when someone kills that
+ process by hand, so the ``_CUA_INSTALLER_TIMEOUT`` ceiling stops bounding anything and
+ ``hermes update`` hangs past its own timeout warning (#87703).
"""
_kill_installer_tree(proc)
try:
@@ -1886,7 +1579,7 @@ def _run_cua_driver_installer(
# keep streaming live.
if verbose:
proc = subprocess.Popen(
- install_cmd, shell=use_shell, env=installer_env,
+ install_cmd, shell=False, env=installer_env,
creationflags=_post_setup_no_window_flags(streams_to_console=True),
**popen_kwargs
)
@@ -1900,7 +1593,7 @@ def _run_cua_driver_installer(
)
else:
proc = subprocess.Popen(
- install_cmd, shell=use_shell, env=installer_env,
+ install_cmd, shell=False, env=installer_env,
stdin=subprocess.DEVNULL,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding="utf-8", errors="replace",
@@ -1944,16 +1637,7 @@ def _run_cua_driver_installer(
)
if verbose:
_print_success(f" {driver_cmd} installed.")
- if is_windows:
- _print_info(" cua-driver may spawn a UIAccess worker (cua-driver-uia.exe);")
- _print_info(" Windows/SmartScreen may prompt the first time it runs.")
- elif is_linux:
- _print_warning(" Linux support is alpha.")
- else:
- _print_info(" IMPORTANT — grant macOS permissions now:")
- _print_info(" System Settings > Privacy & Security > Accessibility")
- _print_info(" System Settings > Privacy & Security > Screen Recording")
- _print_info(" Both must allow the terminal / Hermes process.")
+ _print_cua_platform_notes(is_windows, is_linux, fresh_install=True)
return True
_print_warning(f" cua-driver {label.lower()} did not complete. Re-run manually:")
_print_info(f" {manual_hint}")
@@ -1975,30 +1659,18 @@ def _run_cua_driver_installer(
return False
finally:
if script_path:
- try:
- os.remove(script_path)
- except OSError:
- pass
+ _remove_quietly(script_path)
def _ensure_browser_use_cli(*, verbose_hints: bool = False) -> None:
"""Install the Browser Use CLI if it isn't already runnable.
- The Browser Use CLI 3.0 is the primary driver engine for EVERY browser
- backend except Camofox (which is Firefox-based with no CDP surface, so
- the CDP-only browser-use harness cannot drive it). Local, Browserbase,
- Firecrawl, and the Nous-managed cloud rows all execute through
- ``browser_exec`` when the CLI is runnable — so every one of those
- picker selections must attempt this install, not just the explicit
- "Browser Use" row. Failure is non-fatal: ``browser_exec`` can still run
- zero-install via ``uvx browser-use``, and the built-in browser tools
- remain the final fallback.
-
- MANAGED-FIRST: a browser-use on the user's PATH does NOT satisfy this
- check — only the Hermes-managed ``$HERMES_HOME/bin`` copy does.
- ``install_cli()`` short-circuits on the managed copy and otherwise
- provisions it, so resolution always lands on a binary Hermes installs
- and updates rather than a user-level side install.
+ The Browser Use CLI 3.0 is the primary driver engine for EVERY browser backend except Camofox
+ (which is Firefox-based with no CDP surface, so the CDP-only browser-use harness cannot drive
+ it).
+
+ MANAGED-FIRST: a browser-use on the user's PATH does NOT satisfy this check — only the Hermes-
+ managed ``$HERMES_HOME/bin`` copy does.
"""
_print_info(" Ensuring browser-use CLI (managed install)...")
try:
@@ -2021,405 +1693,415 @@ def _ensure_browser_use_cli(*, verbose_hints: bool = False) -> None:
_print_info(" Cloud browsers: browser-use auth login (or set BROWSER_USE_API_KEY)")
-def _run_post_setup(post_setup_key: str):
- """Run post-setup hooks for tools that need extra installation steps."""
- from hermes_constants import find_node_executable
+def _post_setup_lightpanda() -> None:
+ # Browser Use mode drives Lightpanda directly (Hermes spawns
+ # ``lightpanda serve``); the built-in tools go through agent-browser.
+ # Neither needs a Chromium build.
+ _ensure_browser_use_cli()
+ from tools.browser_lightpanda import (
+ LIGHTPANDA_INSTALL_HINT,
+ find_lightpanda_binary,
+ )
- if post_setup_key == "lightpanda":
- # Browser Use mode drives Lightpanda directly (Hermes spawns
- # ``lightpanda serve``); the built-in tools go through agent-browser.
- # Neither needs a Chromium build.
- _ensure_browser_use_cli()
- from tools.browser_lightpanda import (
- LIGHTPANDA_INSTALL_HINT,
- find_lightpanda_binary,
+ lightpanda_bin = find_lightpanda_binary()
+ if lightpanda_bin:
+ _print_success(f" Lightpanda found: {lightpanda_bin}")
+ else:
+ _print_warning(
+ " lightpanda binary not found on PATH, ~/.lightpanda or ~/.local/bin"
)
+ _print_info(f" {LIGHTPANDA_INSTALL_HINT}")
+ if os.name == "nt":
+ _print_info(" Lightpanda has no native Windows build; run Hermes under WSL2.")
- lightpanda_bin = find_lightpanda_binary()
- if lightpanda_bin:
- _print_success(f" Lightpanda found: {lightpanda_bin}")
- else:
- _print_warning(
- " lightpanda binary not found on PATH, ~/.lightpanda or ~/.local/bin"
- )
- _print_info(f" {LIGHTPANDA_INSTALL_HINT}")
- if os.name == "nt":
- _print_info(" Lightpanda has no native Windows build; run Hermes under WSL2.")
+
+def _post_setup_agent_browser(post_setup_key: str) -> None:
+ """``agent_browser`` (local Chromium) and ``browserbase`` (cloud rows) hooks.
+
+ agent-browser is no longer a root package.json dependency (#43564) — it resolves lazily via npx
+ (or a global/Hermes-managed install), so there is no ``npm install`` step here.
+ """
+ # Every non-Camofox browser backend drives through the Browser Use
+ # CLI when it's runnable — install it here too, not only on the
+ # explicit "Browser Use" picker row.
+ _ensure_browser_use_cli()
+ try:
+ # Import lazily so the tools_config UI doesn't pull in the full
+ # browser_tool module at import time.
+ from tools.browser_tool import (
+ _chromium_installed,
+ _running_in_docker,
+ _find_agent_browser,
+ _resolve_npx_bin,
+ _is_npx_agent_browser_sentinel,
+ AGENT_BROWSER_NPX_SPEC,
+ )
+ except Exception as exc: # pragma: no cover — defensive
+ _print_warning(f" Could not check Chromium status: {exc}")
return
- if post_setup_key in {"agent_browser", "browserbase"}:
- # Every non-Camofox browser backend drives through the Browser Use
- # CLI when it's runnable — install it here too, not only on the
- # explicit "Browser Use" picker row.
- _ensure_browser_use_cli()
- # agent-browser is no longer a root package.json dependency (#43564)
- # — it resolves lazily via npx (or a global/Hermes-managed install)
- # instead of a local `npm install`, so there's no node_modules/
- # population step here anymore.
- try:
- # Import lazily so the tools_config UI doesn't pull in the full
- # browser_tool module at import time.
- from tools.browser_tool import (
- _chromium_installed,
- _running_in_docker,
- _find_agent_browser,
- _resolve_npx_bin,
- _is_npx_agent_browser_sentinel,
- AGENT_BROWSER_NPX_SPEC,
- )
- except Exception as exc: # pragma: no cover — defensive
- _print_warning(f" Could not check Chromium status: {exc}")
- return
+ # Reuse the same resolution cascade browser tools use at runtime
+ # (PATH -> Homebrew/Hermes-managed node -> npx) rather than a bare
+ # shutil.which — Hermes-managed-Node-only setups resolve agent-browser
+ # / npx only through the extended fallback path.
+ try:
+ browser_cmd = _find_agent_browser(validate=False)
+ except FileNotFoundError:
+ _print_warning(
+ " npx not found - browser tools require Node.js: https://nodejs.org"
+ )
+ return
- # Reuse the same resolution cascade browser tools use at runtime
- # (PATH -> Homebrew/Hermes-managed node -> npx) rather than a bare
- # shutil.which — Hermes-managed-Node-only setups resolve agent-browser
- # / npx only through the extended fallback path, which a bare
- # shutil.which("npx") lookup misses.
- try:
- browser_cmd = _find_agent_browser(validate=False)
- except FileNotFoundError:
- _print_warning(
- " npx not found - browser tools require Node.js: https://nodejs.org"
- )
- return
+ # Only the local browser provider actually needs Chromium on disk. Cloud
+ # providers (Browserbase, Browser Use, Firecrawl) host their own Chromium.
+ if post_setup_key != "agent_browser":
+ return
- # Step 1: only the local browser provider actually needs Chromium on
- # disk. Cloud providers (Browserbase, Browser Use, Firecrawl) host
- # their own Chromium and don't need the local install.
- if post_setup_key != "agent_browser":
- return
+ # Ensure the Chromium / headless-shell build agent-browser drives is
+ # installed. Without it the CLI hangs on first use until the command
+ # timeout fires. Skip inside Docker — the image bakes Chromium in at
+ # build time, and runtime users usually can't write to
+ # PLAYWRIGHT_BROWSERS_PATH anyway.
+ if _chromium_installed():
+ _print_success(" Chromium browser already installed, nothing to do")
+ return
- # Step 2: ensure the Chromium / headless-shell build agent-browser
- # drives is actually installed. Without it the CLI hangs on first
- # use until the command timeout fires. Skip inside Docker — the
- # image bakes Chromium in at build time, and runtime users usually
- # can't write to PLAYWRIGHT_BROWSERS_PATH anyway.
- if _chromium_installed():
- _print_success(" Chromium browser already installed, nothing to do")
- return
+ if _running_in_docker():
+ _print_warning(
+ " Chromium is missing but you're running in Docker."
+ )
+ _print_info(
+ " Pull the latest image to get the bundled Chromium:"
+ )
+ _print_info(
+ " docker pull ghcr.io/nousresearch/hermes-agent:latest"
+ )
+ return
- if _running_in_docker():
+ if _is_npx_agent_browser_sentinel(browser_cmd):
+ # Re-resolve via the same PATH + extended-PATH cascade
+ # _find_agent_browser used — a bare shutil.which("npx") would
+ # silently diverge and hand subprocess.run a None argument.
+ npx_bin = _resolve_npx_bin()
+ if not npx_bin:
_print_warning(
- " Chromium is missing but you're running in Docker."
- )
- _print_info(
- " Pull the latest image to get the bundled Chromium:"
- )
- _print_info(
- " docker pull ghcr.io/nousresearch/hermes-agent:latest"
+ " npx not found - install Chromium manually: npx agent-browser install --with-deps"
)
return
+ install_cmd = [npx_bin, "--ignore-scripts", "-y", AGENT_BROWSER_NPX_SPEC, "install", "--with-deps"]
+ else:
+ install_cmd = [browser_cmd, "install", "--with-deps"]
- # browser_cmd was already resolved above (same PATH -> Homebrew ->
- # Hermes-managed-node -> npx cascade _find_agent_browser uses at
- # runtime), so this can't diverge from what actually gets invoked.
- if _is_npx_agent_browser_sentinel(browser_cmd):
- # Re-resolve via the same PATH + extended-PATH cascade
- # _find_agent_browser used, rather than a bare shutil.which("npx")
- # — Hermes-managed-Node-only setups resolve npx only through the
- # extended fallback path, and a bare lookup here would silently
- # diverge and hand subprocess.run a None argument.
- npx_bin = _resolve_npx_bin()
- if not npx_bin:
- _print_warning(
- " npx not found - install Chromium manually: npx agent-browser install --with-deps"
- )
- return
- install_cmd = [npx_bin, "--ignore-scripts", "-y", AGENT_BROWSER_NPX_SPEC, "install", "--with-deps"]
+ _print_info(" Installing Chromium (~170MB one-time download)...")
+ try:
+ result = subprocess.run(
+ install_cmd,
+ capture_output=True, text=True, encoding="utf-8", errors="replace", cwd=str(PROJECT_ROOT), timeout=600,
+ creationflags=_post_setup_no_window_flags(),
+ )
+ if result.returncode == 0:
+ _print_success(" Chromium installed")
+ # Invalidate the cached "missing" result so subsequent
+ # check_browser_requirements() calls see the new install.
+ import tools.browser_tool as _bt
+ _bt._cached_chromium_installed = None
else:
- install_cmd = [browser_cmd, "install", "--with-deps"]
-
- _print_info(" Installing Chromium (~170MB one-time download)...")
- import subprocess
- try:
- result = subprocess.run(
- install_cmd,
- capture_output=True, text=True, encoding="utf-8", errors="replace", cwd=str(PROJECT_ROOT), timeout=600,
- creationflags=_post_setup_no_window_flags(),
- )
- if result.returncode == 0:
- _print_success(" Chromium installed")
- # Invalidate the cached "missing" result so subsequent
- # check_browser_requirements() calls see the new install.
- import tools.browser_tool as _bt
- _bt._cached_chromium_installed = None
- else:
- _print_warning(" Chromium install failed:")
- tail = (result.stderr or result.stdout or "").strip().splitlines()[-3:]
- for line in tail:
- _print_info(f" {line[:200]}")
- _print_info(" Run manually: npx agent-browser install --with-deps")
- except subprocess.TimeoutExpired:
- _print_warning(" Chromium install timed out (>10min)")
- _print_info(" Run manually: npx agent-browser install --with-deps")
- except Exception as exc:
- _print_warning(f" Chromium install failed: {exc}")
+ _print_warning(" Chromium install failed:")
+ tail = (result.stderr or result.stdout or "").strip().splitlines()[-3:]
+ for line in tail:
+ _print_info(f" {line[:200]}")
_print_info(" Run manually: npx agent-browser install --with-deps")
+ except subprocess.TimeoutExpired:
+ _print_warning(" Chromium install timed out (>10min)")
+ _print_info(" Run manually: npx agent-browser install --with-deps")
+ except Exception as exc:
+ _print_warning(f" Chromium install failed: {exc}")
+ _print_info(" Run manually: npx agent-browser install --with-deps")
- elif post_setup_key == "browser_use_cli":
- _ensure_browser_use_cli(verbose_hints=True)
-
- elif post_setup_key == "camofox":
- camofox_dir = PROJECT_ROOT / "node_modules" / "@askjo" / "camofox-browser"
- _npm_bin = find_node_executable("npm")
- if camofox_dir.exists():
- _print_success(" Camofox already installed, nothing to do")
- elif _npm_bin:
- _print_info(" Installing Camofox browser server...")
- import subprocess
- # Absolute npm path so .cmd shim executes on Windows.
- result = subprocess.run(
- # --workspaces=false avoids resolving apps/desktop. See #38772.
- [_npm_bin, "install", "--silent", "--workspaces=false"],
- capture_output=True, text=True, encoding="utf-8", errors="replace", cwd=str(PROJECT_ROOT),
- creationflags=_post_setup_no_window_flags(),
- )
- if result.returncode == 0:
- _print_success(" Camofox installed")
- else:
- _print_warning(" npm install failed - run manually: npm install --workspaces=false")
- if camofox_dir.exists():
- _print_info(" Start the Camofox server:")
- _print_info(" npx @askjo/camofox-browser")
- _print_info(" First run downloads the Camoufox engine (~300MB)")
- _print_info(" Or use Docker: docker run -p 9377:9377 -e CAMOFOX_PORT=9377 jo-inc/camofox-browser")
- elif not _npm_bin:
- _print_warning(" Node.js not found. Install Camofox via Docker:")
- _print_info(" docker run -p 9377:9377 -e CAMOFOX_PORT=9377 jo-inc/camofox-browser")
-
- elif post_setup_key == "cua_driver":
- install_cua_driver(upgrade=False)
-
- elif post_setup_key == "faster_whisper":
- import subprocess
- try:
- __import__("faster_whisper")
- _print_success(" faster-whisper is already installed")
- return
- except ImportError:
- pass
- _print_info(" Installing faster-whisper (model ~150MB downloads on first use)...")
- try:
- result = _pip_install(["-U", "faster-whisper", "--quiet"], timeout=300)
- if result.returncode == 0:
- _print_success(" faster-whisper installed")
- _print_info(" Model sizes: tiny, base (default), small, medium, large-v3")
- _print_info(" Change via stt.local.model in ~/.hermes/config.yaml")
- else:
- _print_warning(" faster-whisper install failed:")
- _print_info(f" {(result.stderr or '').strip()[:300]}")
- _print_info(" Run manually: uv pip install -U faster-whisper")
- except subprocess.TimeoutExpired:
- _print_warning(" faster-whisper install timed out (>5min)")
- _print_info(" Run manually: uv pip install -U faster-whisper")
- elif post_setup_key == "kittentts":
- try:
- __import__("kittentts")
- _print_success(" kittentts is already installed")
- return
- except ImportError:
- pass
- _print_info(" Installing kittentts (~25-80MB model, CPU-only)...")
- wheel_url = (
- "https://github.com/KittenML/KittenTTS/releases/download/"
- "0.8.1/kittentts-0.8.1-py3-none-any.whl"
+def _post_setup_camofox() -> None:
+ from hermes_constants import find_node_executable
+
+ camofox_dir = PROJECT_ROOT / "node_modules" / "@askjo" / "camofox-browser"
+ _npm_bin = find_node_executable("npm")
+ if camofox_dir.exists():
+ _print_success(" Camofox already installed, nothing to do")
+ elif _npm_bin:
+ _print_info(" Installing Camofox browser server...")
+ # Absolute npm path so .cmd shim executes on Windows.
+ result = subprocess.run(
+ # --workspaces=false avoids resolving apps/desktop. See #38772.
+ [_npm_bin, "install", "--silent", "--workspaces=false"],
+ capture_output=True, text=True, encoding="utf-8", errors="replace", cwd=str(PROJECT_ROOT),
+ creationflags=_post_setup_no_window_flags(),
)
+ if result.returncode == 0:
+ _print_success(" Camofox installed")
+ else:
+ _print_warning(" npm install failed - run manually: npm install --workspaces=false")
+ if camofox_dir.exists():
+ _print_info(" Start the Camofox server:")
+ _print_info(" npx @askjo/camofox-browser")
+ _print_info(" First run downloads the Camoufox engine (~300MB)")
+ _print_info(" Or use Docker: docker run -p 9377:9377 -e CAMOFOX_PORT=9377 jo-inc/camofox-browser")
+ elif not _npm_bin:
+ _print_warning(" Node.js not found. Install Camofox via Docker:")
+ _print_info(" docker run -p 9377:9377 -e CAMOFOX_PORT=9377 jo-inc/camofox-browser")
+
+
+_KITTENTTS_WHEEL_URL = (
+ "https://github.com/KittenML/KittenTTS/releases/download/"
+ "0.8.1/kittentts-0.8.1-py3-none-any.whl"
+)
+
+# Post-setup hooks that only pip-install a Python package. Fields:
+# module import probe (already installed → skip the install)
+# label package name used in status lines
+# installing progress line printed before the install
+# args _pip_install arguments (keep in sync with
+# _RESTORABLE_PYTHON_TOOL_DEPENDENCIES)
+# manual the "Run manually:" command shown on failure/timeout
+# on_install info lines printed only after a fresh successful install
+# always info lines printed whenever the package ends up present
+_PIP_POST_SETUP_HOOKS: dict = {
+ "faster_whisper": {
+ "module": "faster_whisper",
+ "label": "faster-whisper",
+ "installing": "Installing faster-whisper (model ~150MB downloads on first use)...",
+ "args": ["-U", "faster-whisper", "--quiet"],
+ "manual": "uv pip install -U faster-whisper",
+ "on_install": (
+ "Model sizes: tiny, base (default), small, medium, large-v3",
+ "Change via stt.local.model in ~/.hermes/config.yaml",
+ ),
+ "always": (),
+ },
+ "kittentts": {
+ "module": "kittentts",
+ "label": "kittentts",
+ "installing": "Installing kittentts (~25-80MB model, CPU-only)...",
+ "args": ["-U", _KITTENTTS_WHEEL_URL, "soundfile", "--quiet"],
+ "manual": f"uv pip install -U '{_KITTENTTS_WHEEL_URL}' soundfile",
+ "on_install": (
+ "Voices: Jasper, Bella, Luna, Bruno, Rosie, Hugo, Kiki, Leo",
+ "Models: KittenML/kitten-tts-nano-0.8-int8 (25MB), micro (41MB), mini (80MB)",
+ ),
+ "always": (),
+ },
+ "piper": {
+ "module": "piper",
+ "label": "piper-tts",
+ "installing": "Installing piper-tts (~14MB wheel, voices downloaded on first use)...",
+ "args": ["-U", "piper-tts", "--quiet"],
+ "manual": "uv pip install -U piper-tts",
+ "on_install": (),
+ "always": (
+ "Default voice: en_US-lessac-medium (downloaded on first TTS call)",
+ "Full voice list: https://github.com/OHF-Voice/piper1-gpl/blob/main/docs/VOICES.md",
+ "Switch voices by setting tts.piper.voice in ~/.hermes/config.yaml",
+ ),
+ },
+ "ddgs": {
+ "module": "ddgs",
+ "label": "ddgs",
+ "installing": "Installing ddgs (DuckDuckGo search package)...",
+ "args": ["-U", "ddgs", "--quiet"],
+ "manual": "uv pip install -U ddgs",
+ "on_install": (),
+ "always": (
+ "No API key required. DuckDuckGo enforces server-side rate limits.",
+ "Pair with an extract provider if you also need web_extract.",
+ ),
+ },
+}
+
+
+def _post_setup_pip(spec: dict) -> None:
+ """Run one ``_PIP_POST_SETUP_HOOKS`` entry."""
+ label = spec["label"]
+ freshly_installed = False
+ try:
+ __import__(spec["module"])
+ _print_success(f" {label} is already installed")
+ except ImportError:
+ _print_info(f" {spec['installing']}")
try:
- result = _pip_install(["-U", wheel_url, "soundfile", "--quiet"], timeout=300)
+ result = _pip_install(spec["args"], timeout=300)
if result.returncode == 0:
- _print_success(" kittentts installed")
- _print_info(" Voices: Jasper, Bella, Luna, Bruno, Rosie, Hugo, Kiki, Leo")
- _print_info(" Models: KittenML/kitten-tts-nano-0.8-int8 (25MB), micro (41MB), mini (80MB)")
+ _print_success(f" {label} installed")
+ freshly_installed = True
else:
- _print_warning(" kittentts install failed:")
+ _print_warning(f" {label} install failed:")
_print_info(f" {(result.stderr or '').strip()[:300]}")
- _print_info(f" Run manually: uv pip install -U '{wheel_url}' soundfile")
+ _print_info(f" Run manually: {spec['manual']}")
+ return
except subprocess.TimeoutExpired:
- _print_warning(" kittentts install timed out (>5min)")
- _print_info(f" Run manually: uv pip install -U '{wheel_url}' soundfile")
+ _print_warning(f" {label} install timed out (>5min)")
+ _print_info(f" Run manually: {spec['manual']}")
+ return
+ if freshly_installed:
+ for line in spec["on_install"]:
+ _print_info(f" {line}")
+ for line in spec["always"]:
+ _print_info(f" {line}")
+
+
+def _post_setup_spotify() -> None:
+ # Run the full `hermes auth spotify` flow — if the user has no
+ # client_id yet, this drops them into the interactive wizard
+ # (opens the Spotify dashboard, prompts for client_id, persists
+ # to ~/.hermes/.env), then continues straight into PKCE. If they
+ # already have an app, it skips the wizard and just does OAuth.
+ from types import SimpleNamespace
+ try:
+ from hermes_cli.auth import login_spotify_command
+ except Exception as exc:
+ _print_warning(f" Could not load Spotify auth: {exc}")
+ _print_info(" Run manually: hermes auth spotify")
+ return
+ _print_info(" Starting Spotify login...")
+ try:
+ login_spotify_command(SimpleNamespace(
+ client_id=None, redirect_uri=None, scope=None,
+ no_browser=False, timeout=None,
+ ))
+ _print_success(" Spotify authenticated")
+ except SystemExit as exc:
+ # User aborted the wizard, or OAuth failed — don't fail the
+ # toolset enable; they can retry with `hermes auth spotify`.
+ _print_warning(f" Spotify login did not complete: {exc}")
+ _print_info(" Run later: hermes auth spotify")
+ except Exception as exc:
+ _print_warning(f" Spotify login failed: {exc}")
+ _print_info(" Run manually: hermes auth spotify")
- elif post_setup_key == "piper":
- try:
- __import__("piper")
- _print_success(" piper-tts is already installed")
- except ImportError:
- _print_info(" Installing piper-tts (~14MB wheel, voices downloaded on first use)...")
- try:
- result = _pip_install(["-U", "piper-tts", "--quiet"], timeout=300)
- if result.returncode == 0:
- _print_success(" piper-tts installed")
- else:
- _print_warning(" piper-tts install failed:")
- _print_info(f" {(result.stderr or '').strip()[:300]}")
- _print_info(" Run manually: uv pip install -U piper-tts")
- return
- except subprocess.TimeoutExpired:
- _print_warning(" piper-tts install timed out (>5min)")
- _print_info(" Run manually: uv pip install -U piper-tts")
- return
- _print_info(" Default voice: en_US-lessac-medium (downloaded on first TTS call)")
- _print_info(" Full voice list: https://github.com/OHF-Voice/piper1-gpl/blob/main/docs/VOICES.md")
- _print_info(" Switch voices by setting tts.piper.voice in ~/.hermes/config.yaml")
- elif post_setup_key == "ddgs":
- try:
- __import__("ddgs")
- _print_success(" ddgs is already installed")
- except ImportError:
- _print_info(" Installing ddgs (DuckDuckGo search package)...")
- try:
- result = _pip_install(["-U", "ddgs", "--quiet"], timeout=300)
- if result.returncode == 0:
- _print_success(" ddgs installed")
- else:
- _print_warning(" ddgs install failed:")
- _print_info(f" {(result.stderr or '').strip()[:300]}")
- _print_info(" Run manually: uv pip install -U ddgs")
- return
- except subprocess.TimeoutExpired:
- _print_warning(" ddgs install timed out (>5min)")
- _print_info(" Run manually: uv pip install -U ddgs")
- return
- _print_info(" No API key required. DuckDuckGo enforces server-side rate limits.")
- _print_info(" Pair with an extract provider if you also need web_extract.")
-
- elif post_setup_key == "spotify":
- # Run the full `hermes auth spotify` flow — if the user has no
- # client_id yet, this drops them into the interactive wizard
- # (opens the Spotify dashboard, prompts for client_id, persists
- # to ~/.hermes/.env), then continues straight into PKCE. If they
- # already have an app, it skips the wizard and just does OAuth.
- from types import SimpleNamespace
- try:
- from hermes_cli.auth import login_spotify_command
- except Exception as exc:
- _print_warning(f" Could not load Spotify auth: {exc}")
- _print_info(" Run manually: hermes auth spotify")
- return
- _print_info(" Starting Spotify login...")
- try:
- login_spotify_command(SimpleNamespace(
- client_id=None, redirect_uri=None, scope=None,
- no_browser=False, timeout=None,
- ))
- _print_success(" Spotify authenticated")
- except SystemExit as exc:
- # User aborted the wizard, or OAuth failed — don't fail the
- # toolset enable; they can retry with `hermes auth spotify`.
- _print_warning(f" Spotify login did not complete: {exc}")
- _print_info(" Run later: hermes auth spotify")
- except Exception as exc:
- _print_warning(f" Spotify login failed: {exc}")
- _print_info(" Run manually: hermes auth spotify")
-
- elif post_setup_key == "langfuse":
- # Install the langfuse SDK.
- try:
- __import__("langfuse")
- _print_success(" langfuse SDK already installed")
- except ImportError:
- _print_info(" Installing langfuse SDK...")
- result = _pip_install(["langfuse", "--quiet"], timeout=120)
- if result.returncode == 0:
- _print_success(" langfuse SDK installed")
- else:
- _print_warning(" langfuse SDK install failed — run manually: uv pip install langfuse")
- # Opt the bundled observability/langfuse plugin into plugins.enabled.
- # The plugin ships in the repo but doesn't load until the user enables
- # it (standalone plugins are opt-in).
- try:
- from hermes_cli.plugins_cmd import _get_enabled_set, _save_enabled_set
- enabled = _get_enabled_set()
- if "observability/langfuse" in enabled or "langfuse" in enabled:
- _print_success(" Plugin observability/langfuse already enabled")
- else:
- enabled.add("observability/langfuse")
- _save_enabled_set(enabled)
- _print_success(" Plugin observability/langfuse enabled")
- except Exception as exc:
- _print_warning(f" Could not enable plugin automatically: {exc}")
- _print_info(" Run manually: hermes plugins enable observability/langfuse")
- _print_info(" Restart Hermes for tracing to take effect.")
- _print_info(" Verify: hermes plugins list")
-
- elif post_setup_key == "xai_grok":
- # Shared credential bootstrap for any picker entry that talks to xAI
- # (TTS, Video Gen, future Image Gen, etc.). Accepts either a
- # SuperGrok-tier OAuth bearer token (preferred — billed against the
- # user's existing subscription) or a raw XAI_API_KEY from
- # console.x.ai. The picker entries declare empty env_vars so we
- # drive the full auth UX here.
- try:
- from hermes_cli.auth import get_xai_oauth_auth_status
- oauth_logged_in = bool(get_xai_oauth_auth_status().get("logged_in"))
- except Exception:
- oauth_logged_in = False
- existing_api_key = get_env_value("XAI_API_KEY")
+def _post_setup_langfuse() -> None:
+ # Install the langfuse SDK.
+ try:
+ __import__("langfuse")
+ _print_success(" langfuse SDK already installed")
+ except ImportError:
+ _print_info(" Installing langfuse SDK...")
+ result = _pip_install(["langfuse", "--quiet"], timeout=120)
+ if result.returncode == 0:
+ _print_success(" langfuse SDK installed")
+ else:
+ _print_warning(" langfuse SDK install failed — run manually: uv pip install langfuse")
+ # Opt the bundled observability/langfuse plugin into plugins.enabled.
+ # The plugin ships in the repo but doesn't load until the user enables
+ # it (standalone plugins are opt-in).
+ try:
+ from hermes_cli.plugins_cmd import _get_enabled_set, _save_enabled_set
+ enabled = _get_enabled_set()
+ if "observability/langfuse" in enabled or "langfuse" in enabled:
+ _print_success(" Plugin observability/langfuse already enabled")
+ else:
+ enabled.add("observability/langfuse")
+ _save_enabled_set(enabled)
+ _print_success(" Plugin observability/langfuse enabled")
+ except Exception as exc:
+ _print_warning(f" Could not enable plugin automatically: {exc}")
+ _print_info(" Run manually: hermes plugins enable observability/langfuse")
+ _print_info(" Restart Hermes for tracing to take effect.")
+ _print_info(" Verify: hermes plugins list")
- if oauth_logged_in:
- _print_success(
- " xAI will use your xAI Grok OAuth (SuperGrok / Premium+) credentials"
- )
- return
- if existing_api_key:
- _print_success(" xAI will use your existing XAI_API_KEY")
- return
- _print_info(" xAI needs credentials. Choose one:")
- try:
- from hermes_cli.setup import (
- _run_xai_oauth_login_from_setup,
- prompt_choice,
- prompt as _setup_prompt,
- )
- from hermes_cli.config import save_env_value
- except Exception as exc:
- _print_warning(f" Could not load setup helpers: {exc}")
- _print_info(" Run later: hermes auth add xai-oauth (or set XAI_API_KEY)")
- return
+def _post_setup_xai_grok() -> None:
+ """Shared xAI credential bootstrap for any picker row that talks to xAI (TTS, STT, Video Gen,
+ x_search …). Accepts a SuperGrok-tier OAuth token (preferred — billed to the existing
+ subscription) or a raw XAI_API_KEY; the rows declare empty env_vars so the auth UX lives here.
+ """
+ try:
+ from hermes_cli.auth import get_xai_oauth_auth_status
+ oauth_logged_in = bool(get_xai_oauth_auth_status().get("logged_in"))
+ except Exception:
+ oauth_logged_in = False
+ existing_api_key = get_env_value("XAI_API_KEY")
- idx = prompt_choice(
- " How do you want xAI to authenticate?",
- choices=[
- "Sign in with xAI Grok OAuth (SuperGrok / Premium+) — browser login",
- "Paste an xAI API key (console.x.ai)",
- "Skip — configure later via `hermes auth add xai-oauth`",
- ],
- default=0,
+ if oauth_logged_in:
+ _print_success(
+ " xAI will use your xAI Grok OAuth (SuperGrok / Premium+) credentials"
)
- if idx == 0:
- if _run_xai_oauth_login_from_setup():
- _print_success(
- " Logged in — xAI will use these OAuth credentials"
- )
- else:
- _print_warning(
- " xAI Grok OAuth login did not complete. "
- "Run later: hermes auth add xai-oauth"
- )
- elif idx == 1:
- api_key = _setup_prompt(" xAI API key", password=True)
- if api_key:
- save_env_value("XAI_API_KEY", api_key)
- _print_success(" XAI_API_KEY saved")
- else:
- _print_warning(
- " No API key provided. Run later: hermes auth add xai-oauth"
- )
+ return
+ if existing_api_key:
+ _print_success(" xAI will use your existing XAI_API_KEY")
+ return
+
+ _print_info(" xAI needs credentials. Choose one:")
+ try:
+ from hermes_cli.setup import (
+ _run_xai_oauth_login_from_setup,
+ prompt_choice,
+ prompt as _setup_prompt,
+ )
+ from hermes_cli.config import save_env_value
+ except Exception as exc:
+ _print_warning(f" Could not load setup helpers: {exc}")
+ _print_info(" Run later: hermes auth add xai-oauth (or set XAI_API_KEY)")
+ return
+
+ idx = prompt_choice(
+ " How do you want xAI to authenticate?",
+ choices=[
+ "Sign in with xAI Grok OAuth (SuperGrok / Premium+) — browser login",
+ "Paste an xAI API key (console.x.ai)",
+ "Skip — configure later via `hermes auth add xai-oauth`",
+ ],
+ default=0,
+ )
+ if idx == 0:
+ if _run_xai_oauth_login_from_setup():
+ _print_success(
+ " Logged in — xAI will use these OAuth credentials"
+ )
+ else:
+ _print_warning(
+ " xAI Grok OAuth login did not complete. "
+ "Run later: hermes auth add xai-oauth"
+ )
+ elif idx == 1:
+ api_key = _setup_prompt(" xAI API key", password=True)
+ if api_key:
+ save_env_value("XAI_API_KEY", api_key)
+ _print_success(" XAI_API_KEY saved")
else:
- _print_info(" xAI will remain inactive until credentials are configured.")
+ _print_warning(
+ " No API key provided. Run later: hermes auth add xai-oauth"
+ )
+ else:
+ _print_info(" xAI will remain inactive until credentials are configured.")
+
+
+# post_setup key -> hook. Unknown keys are a silent no-op (callers validate
+# against valid_post_setup_keys()).
+_POST_SETUP_HOOKS: dict = {
+ "lightpanda": _post_setup_lightpanda,
+ "agent_browser": lambda: _post_setup_agent_browser("agent_browser"),
+ "browserbase": lambda: _post_setup_agent_browser("browserbase"),
+ "browser_use_cli": lambda: _ensure_browser_use_cli(verbose_hints=True),
+ "camofox": _post_setup_camofox,
+ "cua_driver": lambda: install_cua_driver(upgrade=False),
+ "spotify": _post_setup_spotify,
+ "langfuse": _post_setup_langfuse,
+ "xai_grok": _post_setup_xai_grok,
+ **{key: (lambda spec=spec: _post_setup_pip(spec)) for key, spec in _PIP_POST_SETUP_HOOKS.items()},
+}
+
+
+def _run_post_setup(post_setup_key: str):
+ """Run post-setup hooks for tools that need extra installation steps."""
+ hook = _POST_SETUP_HOOKS.get(post_setup_key)
+ if hook is not None:
+ hook()
def valid_post_setup_keys() -> Set[str]:
"""Return the set of post-setup keys declared by any visible provider.
- Collected from ``TOOL_CATEGORIES`` plus the plugin-registered web /
- image-gen / video-gen / browser providers (which can also carry a
- ``post_setup``). This is the allowlist the ``hermes tools post-setup``
- command and the dashboard post-setup endpoint validate against, so a
- caller can't drive ``_run_post_setup`` with an arbitrary key.
+ Collected from ``TOOL_CATEGORIES`` plus plugin-registered web/image/video/browser providers.
+ This is the allowlist the ``post-setup`` command and dashboard endpoint validate against, so a
+ caller cannot drive ``_run_post_setup`` with an arbitrary key.
"""
keys: Set[str] = set()
for cat in TOOL_CATEGORIES.values():
@@ -2447,11 +2129,8 @@ def valid_post_setup_keys() -> Set[str]:
def run_post_setup_command(args) -> int:
"""``hermes tools post-setup <key>`` — non-interactive post-setup runner.
- Runs the install/bootstrap hook a provider declares (npm install for
- browser/Camofox, pip install for kittentts/piper/ddgs, cua-driver fetch,
- etc.). This is the stable, scriptable target the dashboard spawns so the
- GUI can drive backend setup without re-implementing the install logic.
- Returns a process exit code (0 ok, 2 unknown key).
+ Stable, scriptable target the dashboard spawns so the GUI can drive backend setup without
+ re-implementing install logic. Returns a process exit code (0 ok, 2 unknown key).
"""
key = getattr(args, "post_setup_key", None)
if not key:
@@ -2476,28 +2155,29 @@ def run_post_setup_command(args) -> int:
# ─── Platform / Toolset Helpers ───────────────────────────────────────────────
+_PLATFORM_ENABLE_ENV_VARS = (
+ ("telegram", "TELEGRAM_BOT_TOKEN"),
+ ("discord", "DISCORD_BOT_TOKEN"),
+ ("slack", "SLACK_BOT_TOKEN"),
+ ("whatsapp", "WHATSAPP_ENABLED"),
+ ("qqbot", "QQ_APP_ID"),
+)
+
+
def _get_enabled_platforms() -> List[str]:
"""Return platform keys that are configured (have tokens or are CLI)."""
- enabled = ["cli"]
- if get_env_value("TELEGRAM_BOT_TOKEN"):
- enabled.append("telegram")
- if get_env_value("DISCORD_BOT_TOKEN"):
- enabled.append("discord")
- if get_env_value("SLACK_BOT_TOKEN"):
- enabled.append("slack")
- if get_env_value("WHATSAPP_ENABLED"):
- enabled.append("whatsapp")
- if get_env_value("QQ_APP_ID"):
- enabled.append("qqbot")
- return enabled
+ return ["cli"] + [
+ platform
+ for platform, env_var in _PLATFORM_ENABLE_ENV_VARS
+ if get_env_value(env_var)
+ ]
def _platform_toolset_summary(config: dict, platforms: Optional[List[str]] = None) -> Dict[str, Set[str]]:
"""Return a summary of enabled toolsets per platform.
- When ``platforms`` is None, this uses ``_get_enabled_platforms`` to
- auto-detect platforms. Tests can pass an explicit list to avoid relying
- on environment variables.
+ When ``platforms`` is None, this uses ``_get_enabled_platforms`` to auto-detect platforms. Tests
+ can pass an explicit list to avoid relying on environment variables.
"""
if platforms is None:
platforms = _get_enabled_platforms()
@@ -2528,18 +2208,10 @@ def _parse_enabled_flag(value, default: bool = True) -> bool:
def enabled_mcp_server_names(config: dict) -> Set[str]:
"""Names of MCP servers globally enabled in config.yaml or by a plugin.
- Shared by the gateway/CLI platform resolver (``_get_platform_tools``) and
- the cron per-job toolset resolver (``cron.scheduler``) so every path agrees
- on MCP membership. A server is enabled unless its config sets an explicitly
- falsey ``enabled`` (per ``_parse_enabled_flag``: false/0/no/off) — a missing
- flag or an unrecognized value is treated as enabled.
-
- Portable Agent Plugins contribute MCP servers in-memory rather than via
- ``config.yaml`` (see ``PluginManager.get_portable_mcp_servers``). Those are
- included here so their tools fold into platform toolsets like native
- servers do — the user's opt-in is enabling the plugin itself. Without this,
- a portable server registers with the MCP runtime but its tools never reach
- the model's schema.
+ Shared by the platform resolver and the cron toolset resolver so every path agrees on MCP
+ membership. A server is enabled unless ``enabled`` is explicitly falsey; missing/unknown values
+ count as enabled. Portable-plugin servers (in-memory, not in config.yaml) are included so their
+ tools reach the model's schema — enabling the plugin is the user's opt-in.
"""
mcp_servers = (config or {}).get("mcp_servers") or {}
names = {
@@ -2550,7 +2222,6 @@ def enabled_mcp_server_names(config: dict) -> Set[str]:
}
try:
from hermes_cli.plugins import (
- get_plugin_manager,
get_portable_mcp_server_names_nowait,
)
@@ -2567,14 +2238,10 @@ def _exempt_explicit_platform_native(
) -> None:
"""Let platform-native default-off toolsets through on explicit config.
- Toolsets that are both in ``_DEFAULT_OFF_TOOLSETS`` and restricted to
- ``platform`` via ``_TOOLSET_PLATFORM_RESTRICTIONS`` (currently
- ``discord``/``discord_admin`` on the discord platform) are the platform's
- own native tools. They are kept off for *unconfigured* platforms (security
- opt-in), but once a user explicitly saves a toolset list for the platform
- the composite they chose (e.g. ``hermes-discord``, which contains those
- tools) is an opt-in — stripping them silently defeats the explicit
- configuration (#35527). Mutates ``default_off`` in place.
+ Default-off toolsets restricted to a platform (e.g. ``discord`` on discord) are that platform's
+ native tools: kept off for unconfigured platforms as a security opt-in, but once the user
+ explicitly saves a toolset list, stripping them silently would defeat that configuration.
+ Mutates ``default_off`` in place.
"""
if not explicitly_configured:
return
@@ -2613,18 +2280,17 @@ def _enable_recently_shipped_toolsets(
) -> None:
"""Turn on toolsets that shipped after this platform's saved list.
- Either way of saying no outlives this: unchecking in ``hermes tools``
- records the toolset in ``known_builtin_toolsets`` so it reads as declined
- from then on, and ``agent.disabled_toolsets`` is subtracted after every
- rule in :func:`_get_platform_tools`. Mutates ``enabled_toolsets`` in place.
+ Either way of saying no outlives this: unchecking in ``hermes tools`` records the toolset in
+ ``known_builtin_toolsets`` so it reads as declined from then on, and ``agent.disabled_toolsets``
+ is subtracted after every rule in :func:`_get_platform_tools`. Mutates ``enabled_toolsets`` in
+ place.
"""
from toolsets import resolve_toolset
offered = (config.get("known_builtin_toolsets") or {}).get(platform)
declined = {str(ts) for ts in offered} if isinstance(offered, list) else set()
- plat_info = PLATFORMS.get(platform)
- default_ts = plat_info["default_toolset"] if plat_info else f"hermes-{platform}"
+ default_ts = _platform_default_toolset(platform)
composite_tools = None
for ts_key in sorted(_RECENTLY_SHIPPED_TOOLSETS):
@@ -2643,6 +2309,46 @@ def _enable_recently_shipped_toolsets(
enabled_toolsets.add(ts_key)
+def _configurable_subset_of(tool_names: Set[str], platform: str) -> Set[str]:
+ """Configurable toolsets whose STATIC membership is contained in ``tool_names``.
+
+ Compares ``resolve_toolset(ts, include_registry=False)``: a tool registered into a toolset at
+ runtime (e.g. delegate_cli -> delegation, desktop-only read_terminal -> terminal) that the
+ composite never listed must not drop the whole toolset (issue #49622).
+ """
+ from toolsets import resolve_toolset
+
+ enabled = set()
+ for ts_key, _, _ in CONFIGURABLE_TOOLSETS:
+ if not _toolset_allowed_for_platform(ts_key, platform):
+ continue
+ ts_tools = set(resolve_toolset(ts_key, include_registry=False))
+ if ts_tools and ts_tools.issubset(tool_names):
+ enabled.add(ts_key)
+ return enabled
+
+
+def _default_off_toolsets(platform: str, explicitly_configured: bool) -> Set[str]:
+ """Toolsets to strip from an implicit (composite-derived) enable set for ``platform``.
+
+ Legacy safety: a platform whose own name matches a default-off toolset (``homeassistant``)
+ keeps that toolset on first install — except platform-restricted toolsets, which stay opt-in
+ even on their own platform (``discord`` + ``discord`` stays OFF). Home Assistant is runtime-
+ gated by its check_fn (needs HASS_TOKEN), so a configured token is an explicit opt-in and must
+ not be stripped here — otherwise HA silently vanished from platforms like cron that resolve
+ without a saved toolset list (regression after #14798).
+ """
+ default_off = set(_DEFAULT_OFF_TOOLSETS)
+ if platform in default_off and platform not in _TOOLSET_PLATFORM_RESTRICTIONS:
+ default_off.remove(platform)
+ if "homeassistant" in default_off and _homeassistant_credentials_present():
+ default_off.remove("homeassistant")
+ _exempt_explicit_platform_native(
+ default_off, platform, explicitly_configured=explicitly_configured
+ )
+ return default_off
+
+
def _get_platform_tools(
config: dict,
platform: str,
@@ -2660,14 +2366,8 @@ def _get_platform_tools(
# toolsets — see _exempt_explicit_platform_native (#35527).
explicitly_configured = isinstance(toolset_names, list)
- if toolset_names is None or not isinstance(toolset_names, list):
- plat_info = PLATFORMS.get(platform)
- if plat_info:
- default_ts = plat_info["default_toolset"]
- else:
- # Plugin platform — derive toolset name from platform key
- default_ts = f"hermes-{platform}"
- toolset_names = [default_ts]
+ if not explicitly_configured:
+ toolset_names = [_platform_default_toolset(platform)]
# YAML may parse bare numeric names (e.g. ``12306:``) as int.
# Normalise to str so downstream sorted() never mixes types.
@@ -2702,36 +2402,13 @@ def _get_platform_tools(
# user explicitly listed (e.g. ``spotify``) must survive.
composite_tools = set()
for ts_name in toolset_names:
- if ts_name in configurable_keys or ts_name in plugin_ts_keys:
- continue
- if ts_name not in TOOLSETS:
- continue
- composite_tools.update(resolve_toolset(ts_name))
+ if ts_name not in explicit_known_keys and ts_name in TOOLSETS:
+ composite_tools.update(resolve_toolset(ts_name))
if composite_tools:
- expanded = set()
- for ts_key, _, _ in CONFIGURABLE_TOOLSETS:
- if not _toolset_allowed_for_platform(ts_key, platform):
- continue
- # Compare the toolset's STATIC membership: a tool registered
- # into a toolset (e.g. delegate_cli -> delegation, desktop-only
- # read_terminal -> terminal) that the composite never listed must
- # not drop the whole toolset. See issue #49622.
- ts_tools = set(resolve_toolset(ts_key, include_registry=False))
- if ts_tools and ts_tools.issubset(composite_tools):
- expanded.add(ts_key)
-
- default_off = set(_DEFAULT_OFF_TOOLSETS)
- if platform in default_off and platform not in _TOOLSET_PLATFORM_RESTRICTIONS:
- default_off.remove(platform)
- if "homeassistant" in default_off and _homeassistant_credentials_present():
- default_off.remove("homeassistant")
- _exempt_explicit_platform_native(
- default_off, platform, explicitly_configured=explicitly_configured
+ enabled_toolsets |= _configurable_subset_of(composite_tools, platform) - _default_off_toolsets(
+ platform, explicitly_configured
)
- expanded -= default_off
-
- enabled_toolsets |= expanded
_enable_recently_shipped_toolsets(enabled_toolsets, config, platform)
else:
@@ -2740,19 +2417,7 @@ def _get_platform_tools(
all_tool_names = set()
for ts_name in toolset_names:
all_tool_names.update(resolve_toolset(ts_name))
-
- enabled_toolsets = set()
- for ts_key, _, _ in CONFIGURABLE_TOOLSETS:
- if not _toolset_allowed_for_platform(ts_key, platform):
- continue
- # Compare the toolset's STATIC membership against the composite (see
- # issue #49622): get_toolset() merges registry-registered tools into
- # a toolset, but platform composites enumerate static tool names, so
- # an all-tools subset test against the merged set drops the whole
- # toolset the moment a plugin/overlay/desktop tool joins it.
- ts_tools = set(resolve_toolset(ts_key, include_registry=False))
- if ts_tools and ts_tools.issubset(all_tool_names):
- enabled_toolsets.add(ts_key)
+ enabled_toolsets = _configurable_subset_of(all_tool_names, platform)
# Auto-enable ``x_search`` when xAI credentials are configured.
# Unlike ``homeassistant`` (whose ``ha_*`` tools live inside the
@@ -2771,71 +2436,15 @@ def _get_platform_tools(
if x_search_auto_enabled:
enabled_toolsets.add("x_search")
- default_off = set(_DEFAULT_OFF_TOOLSETS)
- # Legacy safety: if the platform's own name matches a default-off
- # toolset (e.g. `homeassistant` platform + `homeassistant` toolset),
- # keep that toolset enabled on first install. Skip this dodge for
- # platform-restricted toolsets — those are always opt-in even on
- # their own platform (e.g. `discord` + `discord` should stay OFF).
- if platform in default_off and platform not in _TOOLSET_PLATFORM_RESTRICTIONS:
- default_off.remove(platform)
- # Home Assistant is already runtime-gated by its check_fn (requires
- # HASS_TOKEN to register any tools). When a user has configured
- # HASS_TOKEN, they've explicitly opted in — don't also strip it via
- # _DEFAULT_OFF_TOOLSETS, which would silently drop HA from platforms
- # (e.g. cron) that run through _get_platform_tools without an
- # explicit saved toolset list. Without this, Norbert's HA cron jobs
- # regressed after #14798 made cron honor per-platform tool config.
- if "homeassistant" in default_off and _homeassistant_credentials_present():
- default_off.remove("homeassistant")
+ default_off = _default_off_toolsets(platform, explicitly_configured)
# Symmetric carve-out for x_search auto-enable (see the inject
# block above). Without this, the default_off subtraction would
# strip the entry we just added.
- if x_search_auto_enabled and "x_search" in default_off:
- default_off.remove("x_search")
- _exempt_explicit_platform_native(
- default_off, platform, explicitly_configured=explicitly_configured
- )
+ if x_search_auto_enabled:
+ default_off.discard("x_search")
enabled_toolsets -= default_off
- # Recover non-configurable platform toolsets (e.g. discord, feishu_doc,
- # feishu_drive). These are part of the platform's default composite but
- # absent from CONFIGURABLE_TOOLSETS, so they can't appear in the TUI
- # checklist or in a user-saved config. Must run in BOTH branches —
- # otherwise saving via `hermes tools` (which flips has_explicit_config
- # to True) silently drops them.
- _plat_info = PLATFORMS.get(platform)
- _default_ts = _plat_info["default_toolset"] if _plat_info else f"hermes-{platform}"
- platform_tool_universe = set(resolve_toolset(_default_ts))
- configurable_tool_universe = set()
- for ck in configurable_keys:
- configurable_tool_universe.update(resolve_toolset(ck))
- claimed = set()
- for ts_key in enabled_toolsets:
- claimed.update(resolve_toolset(ts_key))
- skip = configurable_keys | plugin_ts_keys | platform_default_keys
- skip |= {k for k in TOOLSETS if k.startswith("hermes-")}
- skip |= set(_DEFAULT_OFF_TOOLSETS) - {platform}
- for ts_key, ts_def in TOOLSETS.items():
- if ts_key in skip:
- continue
- if ts_def.get("includes"):
- continue
- # Posture toolsets (e.g. ``coding``) are session-level selections made
- # by agent/coding_context.py — not per-platform capabilities to recover.
- if ts_def.get("posture"):
- continue
- # Static membership (see #49622): a registry-added tool absent from the
- # platform composite must not block recovery of a non-configurable
- # toolset whose authored tools the composite does list.
- ts_tools = set(resolve_toolset(ts_key, include_registry=False))
- if not ts_tools or not ts_tools.issubset(platform_tool_universe):
- continue
- if ts_tools.issubset(configurable_tool_universe):
- continue
- if not ts_tools.issubset(claimed):
- enabled_toolsets.add(ts_key)
- claimed.update(ts_tools)
+ _recover_platform_native_toolsets(enabled_toolsets, platform, skip=configurable_keys | plugin_ts_keys | platform_default_keys)
# Plugin toolsets: enabled by default unless explicitly disabled, or
# unless the toolset is in _DEFAULT_OFF_TOOLSETS (e.g. spotify —
@@ -2848,16 +2457,10 @@ def _get_platform_tools(
known_map = config.get("known_plugin_toolsets", {}) or {}
known_for_platform = set(known_map.get(platform, []) or [])
for pts in plugin_ts_keys:
- if pts in toolset_names:
- # Explicitly listed in config — enabled
- enabled_toolsets.add(pts)
- elif pts in _DEFAULT_OFF_TOOLSETS:
- # Opt-in plugin toolset — stay off until user picks it
- continue
- elif pts not in known_for_platform:
- # New plugin not yet seen by hermes tools — default enabled
+ if pts in toolset_names or (
+ pts not in _DEFAULT_OFF_TOOLSETS and pts not in known_for_platform
+ ):
enabled_toolsets.add(pts)
- # else: known but not in config = user disabled it
# Context-engine tools are runtime-provided by the active engine, so they
# are not part of any static platform composite. When a non-default engine
@@ -2869,43 +2472,20 @@ def _get_platform_tools(
if not isinstance(context_cfg, dict):
context_cfg = {}
context_engine_name = str(context_cfg.get("engine") or "compressor").strip().lower()
- explicit_empty_selection = (
- platform in platform_toolsets
- and isinstance(platform_toolsets.get(platform), list)
- and not toolset_names
- )
- if context_engine_name and context_engine_name != "compressor" and not explicit_empty_selection:
+ if context_engine_name and context_engine_name != "compressor" and not (
+ explicitly_configured and not toolset_names
+ ):
enabled_toolsets.add("context_engine")
# Preserve any explicit non-configurable toolset entries (for example,
# custom toolsets or MCP server names saved in platform_toolsets).
explicit_passthrough = {
- ts
- for ts in toolset_names
- if ts not in configurable_keys
- and ts not in plugin_ts_keys
- and ts not in platform_default_keys
+ ts for ts in toolset_names
+ if ts not in explicit_known_keys and ts not in platform_default_keys
}
-
- # MCP servers are expected to be available on all platforms by default.
- # If the platform explicitly lists one or more MCP server names, treat that
- # as an allowlist. Otherwise include every globally enabled MCP server.
- # Special sentinel: "no_mcp" in the toolset list disables all MCP servers.
- enabled_mcp_servers = enabled_mcp_server_names(config)
- # Allow "no_mcp" sentinel to opt out of all MCP servers for this platform
- if "no_mcp" in toolset_names:
- explicit_mcp_servers = set()
- enabled_toolsets.update(explicit_passthrough - enabled_mcp_servers - {"no_mcp"})
- else:
- explicit_mcp_servers = explicit_passthrough & enabled_mcp_servers
- enabled_toolsets.update(explicit_passthrough - enabled_mcp_servers)
- if include_default_mcp_servers:
- if explicit_mcp_servers or "no_mcp" in toolset_names:
- enabled_toolsets.update(explicit_mcp_servers)
- else:
- enabled_toolsets.update(enabled_mcp_servers)
- else:
- enabled_toolsets.update(explicit_mcp_servers)
+ enabled_toolsets |= _merge_mcp_servers(
+ config, toolset_names, explicit_passthrough, include_default_mcp_servers
+ )
# Honor agent.disabled_toolsets from config.yaml — allows users to
# globally suppress specific toolsets (e.g. "memory") across all
@@ -2918,45 +2498,102 @@ def _get_platform_tools(
if disabled_toolsets:
from agent.skill_utils import parse_config_string_list
- disabled_set = {
+ enabled_toolsets -= {
name.strip() for name in parse_config_string_list(disabled_toolsets) if name.strip()
}
- enabled_toolsets -= disabled_set
-
- # #38798: if this platform was explicitly configured but every toolset name
- # is invalid (e.g. a migration or hand-edit left `hermes` instead of
- # `hermes-cli`), resolve_toolset() returns [] for each and the platform ends
- # up with no native tools — silently, with no error. Surface it at the point
- # tools are resolved for a session so an already-corrupted config is caught
- # at runtime, not only during the next `hermes update`/`hermes doctor`.
- _explicit = platform_toolsets.get(platform)
- if isinstance(_explicit, list) and _explicit:
- from toolsets import validate_toolset
-
- _named = [str(t) for t in _explicit if isinstance(t, str) and t]
- if (
- _named
- and not any(validate_toolset(t) for t in _named)
- and platform not in _warned_invalid_platform_toolsets
- ):
- _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),
- )
+
+ if explicitly_configured and toolset_names:
+ _warn_all_invalid_platform_toolsets(platform, platform_toolsets[platform])
return enabled_toolsets
-def _save_platform_tools(config: dict, platform: str, enabled_toolset_keys: Set[str]):
- """Save the selected toolset keys for a platform to config.
+def _recover_platform_native_toolsets(enabled_toolsets: Set[str], platform: str, *, skip: Set[str]) -> None:
+ """Add non-configurable platform toolsets (e.g. discord, feishu_doc, feishu_drive) in place.
+
+ These are part of the platform's default composite but absent from CONFIGURABLE_TOOLSETS, so
+ they can't appear in the TUI checklist or in a user-saved config. Must run for BOTH the explicit
+ and the composite branch of ``_get_platform_tools`` — otherwise saving via ``hermes tools``
+ silently drops them.
+ """
+ from toolsets import resolve_toolset, TOOLSETS
+
+ platform_tool_universe = set(resolve_toolset(_platform_default_toolset(platform)))
+ configurable_tool_universe = set()
+ for ts_key, _, _ in CONFIGURABLE_TOOLSETS:
+ configurable_tool_universe.update(resolve_toolset(ts_key))
+ claimed = set()
+ for ts_key in enabled_toolsets:
+ claimed.update(resolve_toolset(ts_key))
+ skip = skip | {k for k in TOOLSETS if k.startswith("hermes-")}
+ skip |= set(_DEFAULT_OFF_TOOLSETS) - {platform}
+ for ts_key, ts_def in TOOLSETS.items():
+ # Posture toolsets (e.g. ``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 (see #49622): a registry-added tool absent from the
+ # platform composite must not block recovery of a non-configurable
+ # toolset whose authored tools the composite does list.
+ ts_tools = set(resolve_toolset(ts_key, include_registry=False))
+ if not ts_tools or not ts_tools.issubset(platform_tool_universe):
+ continue
+ if ts_tools.issubset(configurable_tool_universe):
+ continue
+ if not ts_tools.issubset(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 the MCP servers enabled for this platform.
- Preserves any non-configurable toolset entries (like MCP server names)
- that were already in the config for this platform.
+ MCP servers are available on all platforms by default. If the platform explicitly lists one or
+ more MCP server names, that is an allowlist; otherwise every globally enabled server is included
+ (when ``include_default_mcp_servers``). The ``no_mcp`` sentinel disables all MCP servers.
"""
+ enabled_mcp_servers = enabled_mcp_server_names(config)
+ no_mcp = "no_mcp" in toolset_names
+ if no_mcp:
+ explicit_mcp_servers = set()
+ result = explicit_passthrough - enabled_mcp_servers - {"no_mcp"}
+ else:
+ explicit_mcp_servers = explicit_passthrough & enabled_mcp_servers
+ result = explicit_passthrough - enabled_mcp_servers
+ if include_default_mcp_servers and not explicit_mcp_servers and not no_mcp:
+ return result | enabled_mcp_servers
+ return result | explicit_mcp_servers
+
+
+def _warn_all_invalid_platform_toolsets(platform: str, explicit: list) -> None:
+ """#38798: warn once when an explicitly configured platform has only invalid toolset names.
+
+ A migration or hand-edit that left ``hermes`` instead of ``hermes-cli`` makes resolve_toolset()
+ return [] for every entry and the platform silently ends up with no native tools. Surface it
+ where tools are resolved for a session, not only during ``hermes update``/``hermes doctor``.
+ """
+ from toolsets import validate_toolset
+
+ named = [str(t) for t in explicit if isinstance(t, str) and t]
+ if (
+ named
+ and not any(validate_toolset(t) for t in named)
+ and platform not in _warned_invalid_platform_toolsets
+ ):
+ _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),
+ )
+
+
+def _save_platform_tools(config: dict, platform: str, enabled_toolset_keys: Set[str]):
+ """Save the selected toolset keys for a platform to config."""
config.setdefault("platform_toolsets", {})
# Drop platform-scoped toolsets that don't apply here. Prevents the
@@ -3000,21 +2637,17 @@ def _save_platform_tools(config: dict, platform: str, enabled_toolset_keys: Set[
# Track which plugin toolsets are "known" for this platform so we can
# distinguish "new plugin, default enabled" from "user disabled it".
+ # _cfg_section normalizes a present-but-null key ("known_plugin_toolsets:"
+ # in config.yaml parses to None) that setdefault alone would not replace.
if plugin_keys:
- # setdefault does NOT replace a present-but-null key ("known_plugin_toolsets:"
- # in config.yaml parses to None) — normalize before indexing into it.
- if not isinstance(config.get("known_plugin_toolsets"), dict):
- config["known_plugin_toolsets"] = {}
- config["known_plugin_toolsets"][platform] = sorted(plugin_keys)
+ _cfg_section(config, "known_plugin_toolsets")[platform] = sorted(plugin_keys)
# Same record for builtin toolsets: which ones this platform's checklist
# has actually put in front of the user. Without it, a toolset the user
# unchecks here is indistinguishable from one that shipped after they
# saved, and _enable_recently_shipped_toolsets would turn it straight back
# on. Recorded from the full catalog, since that is what the picker showed.
- if not isinstance(config.get("known_builtin_toolsets"), dict):
- config["known_builtin_toolsets"] = {}
- config["known_builtin_toolsets"][platform] = sorted(
+ _cfg_section(config, "known_builtin_toolsets")[platform] = sorted(
ts_key for ts_key, _, _ in CONFIGURABLE_TOOLSETS
)
@@ -3032,23 +2665,23 @@ def _save_platform_tools(config: dict, platform: str, enabled_toolset_keys: Set[
# are left alone, so agent.disabled_toolsets keeps working as a
# cross-platform suppression list for anything not actively re-enabled.
agent_cfg = config.get("agent")
- if isinstance(agent_cfg, dict):
- disabled_toolsets = agent_cfg.get("disabled_toolsets")
- if disabled_toolsets:
- from agent.skill_utils import parse_config_string_list
-
- parsed_disabled = parse_config_string_list(disabled_toolsets)
- newly_enabled = enabled_toolset_keys - preserved_entries
- if newly_enabled:
- remaining = [
- ts for ts in parsed_disabled if ts not in newly_enabled
- ]
- if remaining != parsed_disabled:
- agent_cfg["disabled_toolsets"] = remaining
+ newly_enabled = enabled_toolset_keys - preserved_entries
+ if isinstance(agent_cfg, dict) and agent_cfg.get("disabled_toolsets") and newly_enabled:
+ from agent.skill_utils import parse_config_string_list
+
+ parsed_disabled = parse_config_string_list(agent_cfg["disabled_toolsets"])
+ remaining = [ts for ts in parsed_disabled if ts not in newly_enabled]
+ if remaining != parsed_disabled:
+ agent_cfg["disabled_toolsets"] = remaining
save_config(config)
+def _provider_env_ready(provider: dict) -> bool:
+ """True when every env var a provider row declares is set (trivially true for no-key rows)."""
+ return all(get_env_value(e["key"]) for e in provider.get("env_vars", []))
+
+
def _toolset_has_keys(
ts_key: str,
config: dict = None,
@@ -3078,21 +2711,14 @@ def _toolset_has_keys(
if feature and (feature.available or feature.managed_by_nous):
return True
- # Check TOOL_CATEGORIES first (provider-aware)
+ # Check TOOL_CATEGORIES first (provider-aware). A no-key provider
+ # (Local Browser, Edge TTS) counts as configured.
cat = TOOL_CATEGORIES.get(ts_key)
if cat:
- for provider in _visible_providers(
- cat,
- config,
- force_fresh=force_fresh,
- features=features,
- ):
- env_vars = provider.get("env_vars", [])
- if not env_vars:
- return True # No-key provider (e.g. Local Browser, Edge TTS)
- if all(get_env_value(e["key"]) for e in env_vars):
- return True
- return False
+ return any(
+ _provider_env_ready(provider)
+ for provider in _visible_providers(cat, config, force_fresh=force_fresh, features=features)
+ )
# Fallback to simple requirements
requirements = TOOLSET_ENV_REQUIREMENTS.get(ts_key, [])
@@ -3118,16 +2744,14 @@ _tool_token_cache: Optional[Dict[tuple[str, int], Dict[str, int]]] = None
def _estimate_tool_tokens() -> Dict[str, int]:
"""Return estimated token counts per individual tool name.
- Uses tiktoken (cl100k_base) to count tokens in the JSON-serialised
- OpenAI-format tool schema. Triggers tool discovery on first call,
- then caches the result for the rest of the process.
-
- Returns an empty dict when tiktoken or the registry is unavailable.
+ Counts tiktoken (cl100k_base) tokens of the JSON-serialised OpenAI tool schema. Triggers tool
+ discovery on first call and caches for the process. Empty dict if tiktoken/registry unavailable.
"""
global _tool_token_cache
from hermes_constants import hermes_home_key
scope = hermes_home_key()
+ _tool_token_cache = _tool_token_cache or {}
try:
# Trigger full tool discovery (imports all tool modules).
@@ -3136,12 +2760,9 @@ def _estimate_tool_tokens() -> Dict[str, int]:
cache_key = (scope, registry._generation)
except Exception:
logger.debug("Tool registry unavailable; skipping token estimation")
- cache_key = (scope, -1)
- _tool_token_cache = _tool_token_cache or {}
- _tool_token_cache[cache_key] = {}
- return _tool_token_cache[cache_key]
+ return _tool_token_cache.setdefault((scope, -1), {})
- if _tool_token_cache is not None and cache_key in _tool_token_cache:
+ if cache_key in _tool_token_cache:
return _tool_token_cache[cache_key]
try:
@@ -3149,9 +2770,7 @@ def _estimate_tool_tokens() -> Dict[str, int]:
enc = tiktoken.get_encoding("cl100k_base")
except Exception:
logger.debug("tiktoken unavailable; skipping tool token estimation")
- _tool_token_cache = _tool_token_cache or {}
- _tool_token_cache[cache_key] = {}
- return _tool_token_cache[cache_key]
+ return _tool_token_cache.setdefault(cache_key, {})
counts: Dict[str, int] = {}
for name in registry.get_all_tool_names():
@@ -3161,7 +2780,6 @@ def _estimate_tool_tokens() -> Dict[str, int]:
# {"type": "function", "function": <schema>}
text = _json.dumps({"type": "function", "function": schema})
counts[name] = len(enc.encode(text))
- _tool_token_cache = _tool_token_cache or {}
_tool_token_cache[cache_key] = counts
return counts
@@ -3194,7 +2812,7 @@ def _prompt_toolset_checklist(
suffix = ""
if (
not _toolset_has_keys(ts_key, force_fresh=force_fresh)
- and (TOOL_CATEGORIES.get(ts_key) or TOOLSET_ENV_REQUIREMENTS.get(ts_key))
+ and _is_configurable(ts_key)
):
suffix = " [no API key]"
labels.append(f"{ts_label} ({ts_desc}){suffix}")
@@ -3238,9 +2856,9 @@ def _configure_toolset(
force_fresh: bool = True,
):
"""Configure a toolset - provider selection + API keys.
-
- Uses TOOL_CATEGORIES for provider-aware config, falls back to simple
- env var prompts for toolsets not in TOOL_CATEGORIES.
+
+ Uses TOOL_CATEGORIES for provider-aware config, falls back to simple env var prompts for
+ toolsets not in TOOL_CATEGORIES.
"""
cat = TOOL_CATEGORIES.get(ts_key)
@@ -3251,163 +2869,123 @@ def _configure_toolset(
_configure_simple_requirements(ts_key)
-def _plugin_image_gen_providers() -> list[dict]:
- """Build picker-row dicts from plugin-registered image gen providers.
-
- Each returned dict looks like a regular ``TOOL_CATEGORIES`` provider
- row but carries an ``image_gen_plugin_name`` marker so downstream
- code (config writing, model picker) knows to route through the
- plugin registry. Every image-gen backend is a plugin now — there
- are no hardcoded rows left in ``TOOL_CATEGORIES["image_gen"]`` for
- this function to dedupe against (see issue #26241).
+def _plugin_provider_rows(
+ registry_module: str,
+ marker_keys: tuple[str, ...],
+ *,
+ require_name: bool = True,
+ skip_builtin: bool = False,
+ flatten_variants: bool = False,
+) -> list[dict]:
+ """Build picker-row dicts from a plugin registry's providers.
+
+ Each row looks like a hardcoded ``TOOL_CATEGORIES`` provider row plus the ``marker_keys``
+ (all set to the provider's registry name) that tell downstream config-writing / model-picker
+ code to route through the plugin registry. ``skip_builtin`` drops providers whose name shadows
+ the registry's ``_BUILTIN_NAMES`` (defence in depth — the registry already rejects them).
+ ``flatten_variants`` expands a schema's tier ``variants`` (e.g. Exa/Parallel free keyless vs
+ paid SDK) into separate rows sharing one backend name, distinguished by ``web_tier``.
"""
try:
- from agent.image_gen_registry import list_providers
+ import importlib
+
+ registry = importlib.import_module(registry_module)
from hermes_cli.plugins import _ensure_plugins_discovered
_ensure_plugins_discovered()
- providers = list_providers()
+ providers = registry.list_providers()
+ builtin = registry._BUILTIN_NAMES if skip_builtin else frozenset()
except Exception:
return []
rows: list[dict] = []
for provider in providers:
+ if require_name:
+ name = getattr(provider, "name", None)
+ if not name:
+ continue
+ if skip_builtin and name.lower().strip() in builtin:
+ continue
try:
schema = provider.get_setup_schema()
except Exception:
continue
if not isinstance(schema, dict):
continue
- row = {
- "name": schema.get("name", provider.display_name),
- "badge": schema.get("badge", ""),
- "tag": schema.get("tag", ""),
- "env_vars": schema.get("env_vars", []),
- "image_gen_plugin_name": provider.name,
- }
- if schema.get("post_setup"):
- row["post_setup"] = schema["post_setup"]
- rows.append(row)
+ if not require_name:
+ name = provider.name
+ entries = [schema]
+ if flatten_variants:
+ entries += [v for v in (schema.get("variants") or []) if isinstance(v, dict)]
+ for entry in entries:
+ row = {
+ "name": entry.get("name", provider.display_name),
+ "badge": entry.get("badge", ""),
+ "tag": entry.get("tag", ""),
+ "env_vars": entry.get("env_vars", []),
+ }
+ for key in marker_keys:
+ row[key] = name
+ if flatten_variants and entry.get("web_tier"):
+ row["web_tier"] = entry["web_tier"]
+ if entry.get("post_setup"):
+ row["post_setup"] = entry["post_setup"]
+ rows.append(row)
return rows
-def _plugin_video_gen_providers() -> list[dict]:
- """Build picker-row dicts from plugin-registered video gen providers.
-
- Mirrors ``_plugin_image_gen_providers`` exactly — every video backend
- is a plugin, so this function is the *only* source of provider rows
- for the Video Generation category. The hardcoded ``TOOL_CATEGORIES``
- entry for ``video_gen`` keeps an empty providers list.
- """
- try:
- from agent.video_gen_registry import list_providers
- from hermes_cli.plugins import _ensure_plugins_discovered
+def _plugin_image_gen_providers() -> list[dict]:
+ """Picker rows for plugin-registered image gen providers (``image_gen_plugin_name`` marker)."""
+ return _plugin_provider_rows(
+ "agent.image_gen_registry", ("image_gen_plugin_name",), require_name=False
+ )
- _ensure_plugins_discovered()
- providers = list_providers()
- except Exception:
- return []
- rows: list[dict] = []
- for provider in providers:
- try:
- schema = provider.get_setup_schema()
- except Exception:
- continue
- if not isinstance(schema, dict):
- continue
- row = {
- "name": schema.get("name", provider.display_name),
- "badge": schema.get("badge", ""),
- "tag": schema.get("tag", ""),
- "env_vars": schema.get("env_vars", []),
- "video_gen_plugin_name": provider.name,
- }
- if schema.get("post_setup"):
- row["post_setup"] = schema["post_setup"]
- rows.append(row)
- return rows
+def _plugin_video_gen_providers() -> list[dict]:
+ """Picker rows for plugin-registered video gen providers — the *only* source of rows for the
+ Video Generation category (every video backend is a plugin)."""
+ return _plugin_provider_rows(
+ "agent.video_gen_registry", ("video_gen_plugin_name",), require_name=False
+ )
-# Mirror of _plugin_image_gen_providers for web search backends. Surfaces
-# every plugin-registered web provider so it appears in the
-# "Web Search & Extract" picker. All bundled providers (brave-free, ddgs,
-# searxng, exa, parallel, tavily, firecrawl, keenable) live as plugins after
-# PR #25182 — this helper is the sole source of truth for the category's
-# provider rows. The hardcoded entries that used to drive the category
-# were deleted in the same PR; only the two non-provider UX rows
-# ("Nous Subscription" managed-gateway entry, "Firecrawl Self-Hosted")
-# remain in TOOL_CATEGORIES because they describe alternative *setup
-# flows* for the firecrawl backend rather than distinct providers.
def _plugin_web_search_providers() -> list[dict]:
- """Build picker-row dicts from plugin-registered web search providers.
+ """Picker rows for plugin-registered web search providers.
- Each returned dict is a regular ``TOOL_CATEGORIES`` provider row. It
- populates both ``web_backend`` (legacy field consumed by setup +
- selection helpers) and ``web_search_plugin_name`` (informational
- marker) so the picker behaves identically whether a provider is
- hardcoded or plugin-registered.
-
- After PR #25182, all bundled web providers (brave-free, ddgs, searxng,
- exa, parallel, tavily, firecrawl, keenable) are plugins; this helper is the sole
- source of provider rows for the Web Search & Extract category.
+ After PR #25182 all bundled web providers (brave-free, ddgs, searxng, exa, parallel, tavily,
+ firecrawl, keenable) are plugins, so this is the sole source of provider rows for Web Search &
+ Extract; only the two non-provider firecrawl setup-flow rows stay in ``TOOL_CATEGORIES``.
"""
- try:
- from agent.web_search_registry import list_providers as _list_web_providers
- from hermes_cli.plugins import _ensure_plugins_discovered
+ return _plugin_provider_rows(
+ "agent.web_search_registry",
+ ("web_backend", "web_search_plugin_name"),
+ flatten_variants=True,
+ )
- _ensure_plugins_discovered()
- providers = _list_web_providers()
- except Exception:
- return []
- rows: list[dict] = []
- for provider in providers:
- name = getattr(provider, "name", None)
- if not name:
- continue
- try:
- schema = provider.get_setup_schema()
- except Exception:
- continue
- if not isinstance(schema, dict):
- continue
- # A schema may expose tier ``variants`` (e.g. Exa/Parallel free
- # keyless endpoint vs paid SDK) — flatten the base row plus each
- # variant into separate picker rows sharing the same backend name,
- # distinguished by ``web_tier`` (persisted to
- # ``web.provider_tier.<name>`` on selection).
- schemas = [schema] + [
- v for v in (schema.get("variants") or []) if isinstance(v, dict)
- ]
- for entry in schemas:
- row = {
- "name": entry.get("name", provider.display_name),
- "badge": entry.get("badge", ""),
- "tag": entry.get("tag", ""),
- "env_vars": entry.get("env_vars", []),
- "web_backend": name,
- "web_search_plugin_name": name,
- }
- if entry.get("web_tier"):
- row["web_tier"] = entry["web_tier"]
- # Optional pass-through fields the schema can opt into.
- if entry.get("post_setup"):
- row["post_setup"] = entry["post_setup"]
- rows.append(row)
- return rows
+def _plugin_browser_providers() -> list[dict]:
+ """Picker rows for plugin-registered cloud browser providers (Browserbase / Browser Use /
+ Firecrawl, PR #25214). ``browser_provider`` is the legacy key written to
+ ``browser.cloud_provider``; ``browser_plugin_name`` marks the row as plugin-backed."""
+ return _plugin_provider_rows(
+ "agent.browser_registry", ("browser_provider", "browser_plugin_name")
+ )
+
+
+def _plugin_tts_providers() -> list[dict]:
+ """Picker rows for plugin-registered TTS providers, rendered below the hardcoded built-in rows.
+ Selecting one writes ``tts.provider: <name>`` like the built-in rows do."""
+ return _plugin_provider_rows(
+ "agent.tts_registry", ("tts_provider", "tts_plugin_name"), skip_builtin=True
+ )
def web_provider_capabilities(backend: str) -> list:
"""Return the capabilities (``search`` / ``extract``) a web backend supports.
- Consults the plugin registry's provider instance (``supports_search`` /
- ``supports_extract``) so the Capabilities GUI can offer per-capability
- selection (``web.search_backend`` / ``web.extract_backend``) only where it
- makes sense — e.g. ddgs and brave-free are search-only. Falls back to both
- capabilities when the backend isn't registered (hardcoded setup-flow rows
- like the managed Firecrawl entries resolve before plugin discovery in some
- test contexts, and firecrawl itself supports both).
+ Consults the plugin registry's provider instance (``supports_search`` / ``supports_extract``) so
+ the Capabilities GUI can offer per-capability selection (``web.search_backend`` /
+ ``web.extract_backend``) only where it makes sense — e.g. ddgs and brave-free are search-only.
"""
try:
from agent.web_search_registry import get_provider
@@ -3425,115 +3003,14 @@ def web_provider_capabilities(backend: str) -> list:
return ["search", "extract"]
-# Mirror of _plugin_web_search_providers for cloud browser backends. After
-# PR #25214, Browserbase / Browser Use / Firecrawl live as plugins under
-# plugins/browser/<vendor>/; this helper is the sole source of provider rows
-# for those three in the "Browser Automation" picker. The hardcoded
-# ``TOOL_CATEGORIES["browser"]`` entries that drove the category before
-# were deleted in the same PR; only non-provider UX setup-flow rows remain
-# ("Nous Subscription", "Local Browser", "Camofox") — see the comment block
-# in ``TOOL_CATEGORIES["browser"]`` for why each one stays hardcoded.
-def _plugin_browser_providers() -> list[dict]:
- """Build picker-row dicts from plugin-registered cloud browser providers.
-
- Each returned dict mirrors the legacy ``TOOL_CATEGORIES["browser"]``
- schema (``name`` / ``badge`` / ``tag`` / ``env_vars`` /
- ``browser_provider`` / ``post_setup``) so the picker behaves identically
- whether a provider was hardcoded or plugin-registered.
-
- Populates ``browser_provider`` (the legacy config key written to
- ``browser.cloud_provider``) and a ``browser_plugin_name`` marker so
- setup / write paths can route through the registry when they want to.
- """
- try:
- from agent.browser_registry import list_providers as _list_browser_providers
- from hermes_cli.plugins import _ensure_plugins_discovered
-
- _ensure_plugins_discovered()
- providers = _list_browser_providers()
- except Exception:
- return []
-
- rows: list[dict] = []
- for provider in providers:
- name = getattr(provider, "name", None)
- if not name:
- continue
- try:
- schema = provider.get_setup_schema()
- except Exception:
- continue
- if not isinstance(schema, dict):
- continue
- row = {
- "name": schema.get("name", provider.display_name),
- "badge": schema.get("badge", ""),
- "tag": schema.get("tag", ""),
- "env_vars": schema.get("env_vars", []),
- "browser_provider": name,
- "browser_plugin_name": name,
- }
- # Pass-through optional fields the schema can opt into.
- if schema.get("post_setup"):
- row["post_setup"] = schema["post_setup"]
- rows.append(row)
- return rows
-
-
-def _plugin_tts_providers() -> list[dict]:
- """Build picker-row dicts from plugin-registered TTS providers.
-
- Issue #30398 — the ``register_tts_provider()`` plugin hook
- coexists alongside the 10 built-in TTS providers
- (``edge``/``openai``/``elevenlabs``/…) and the
- ``tts.providers.<name>: type: command`` registry from PR #17843.
- Built-in rows stay hardcoded in ``TOOL_CATEGORIES["tts"]``; this
- function only injects PLUGIN-registered providers.
-
- Defensive: plugins whose name collides with a built-in TTS provider
- are filtered out — even though the registry already rejects them
- at registration time, a future code path that registers directly
- via :func:`agent.tts_registry.register_provider` could slip
- through. Filtering here keeps the picker invariant.
- """
- try:
- from agent.tts_registry import _BUILTIN_NAMES, list_providers
- from hermes_cli.plugins import _ensure_plugins_discovered
-
- _ensure_plugins_discovered()
- providers = list_providers()
- except Exception:
- return []
-
- rows: list[dict] = []
- for provider in providers:
- name = getattr(provider, "name", None)
- if not name:
- continue
- # Defensive: reject built-in shadowing at the picker layer too.
- if name.lower().strip() in _BUILTIN_NAMES:
- continue
- try:
- schema = provider.get_setup_schema()
- except Exception:
- continue
- if not isinstance(schema, dict):
- continue
- row = {
- "name": schema.get("name", provider.display_name),
- "badge": schema.get("badge", ""),
- "tag": schema.get("tag", ""),
- "env_vars": schema.get("env_vars", []),
- # Selecting this row writes ``tts.provider: <name>`` — the
- # same write-path used by hardcoded rows. The plugin
- # dispatcher picks it up automatically from there.
- "tts_provider": name,
- "tts_plugin_name": name,
- }
- if schema.get("post_setup"):
- row["post_setup"] = schema["post_setup"]
- rows.append(row)
- return rows
+# TOOL_CATEGORIES[<key>]["name"] -> builder of plugin-registered picker rows.
+_PLUGIN_ROW_BUILDERS = {
+ "Image Generation": _plugin_image_gen_providers,
+ "Video Generation": _plugin_video_gen_providers,
+ "Web Search & Extract": _plugin_web_search_providers,
+ "Browser Automation": _plugin_browser_providers,
+ "Text-to-Speech": _plugin_tts_providers,
+}
def _visible_providers(
@@ -3545,11 +3022,8 @@ def _visible_providers(
) -> list[dict]:
"""Return provider entries visible for the current auth/config state.
- Nous-managed Tool Gateway rows (``managed_nous_feature``) are always
- shown — even to logged-out / unentitled users — so the picker advertises
- that the capability exists. Selecting one drives an inline Nous Portal
- login + entitlement check (see ``_configure_provider``); the row only
- *activates* the gateway once paid access is confirmed.
+ Nous-managed Tool Gateway rows (``managed_nous_feature``) are always shown — even to logged-out
+ / unentitled users — so the picker advertises that the capability exists.
"""
if features is None:
features = get_nous_subscription_features(config, force_fresh=force_fresh)
@@ -3587,60 +3061,17 @@ def _visible_providers(
continue
visible.append(provider)
- # Inject plugin-registered image_gen backends (OpenAI today, more
- # later) so the picker lists them alongside FAL / Nous Subscription.
- if cat.get("name") == "Image Generation":
- visible.extend(_plugin_image_gen_providers())
-
- # Inject plugin-registered video_gen backends. Unlike image_gen,
- # video_gen has NO hardcoded providers — every backend is a plugin.
- if cat.get("name") == "Video Generation":
- visible.extend(_plugin_video_gen_providers())
-
- # Inject plugin-registered web search backends. After PR #25182, this
- # is the SOLE source of provider rows for the Web Search & Extract
- # category — the per-provider hardcoded entries were deleted. The two
- # remaining hardcoded rows ("Nous Subscription", "Firecrawl
- # Self-Hosted") are non-provider UX setup-flow rows for firecrawl.
- if cat.get("name") == "Web Search & Extract":
- visible.extend(_plugin_web_search_providers())
-
- # Inject plugin-registered cloud browser backends. After PR #25214,
- # Browserbase / Browser Use / Firecrawl are the plugin-supplied rows;
- # the hardcoded "Nous Subscription" / "Local Browser" / "Camofox" rows
- # stay because they're non-provider UX setup flows (subscription auth,
- # local fallback, and the REST-API anti-detection backend respectively).
- if cat.get("name") == "Browser Automation":
- visible.extend(_plugin_browser_providers())
-
- # Inject plugin-registered TTS backends (issue #30398). Plugin rows
- # render BELOW the 10 hardcoded built-in rows. Built-in shadowing
- # is filtered out by ``_plugin_tts_providers`` defensively.
- if cat.get("name") == "Text-to-Speech":
- visible.extend(_plugin_tts_providers())
+ # Plugin-registered rows render BELOW the hardcoded rows. For web
+ # (PR #25182) and browser (PR #25214) they are the only real provider
+ # rows — the hardcoded entries left are non-provider UX setup flows
+ # (Nous Subscription, Firecrawl Self-Hosted, Local Browser, Camofox).
+ builder = _PLUGIN_ROW_BUILDERS.get(cat.get("name"))
+ if builder is not None:
+ visible.extend(builder())
return visible
-def _hidden_nous_gateway_message(
- cat: dict,
- config: dict,
- capability: str,
- *,
- force_fresh: bool = False,
-) -> str:
- """Deprecated: Nous Tool Gateway rows are no longer hidden.
-
- Previously this returned a "log in / upgrade" banner shown above a
- category when its Nous-managed rows were filtered out for unentitled
- users. Those rows are now always listed (see ``_visible_providers``), and
- the login + entitlement guidance happens inline when the user selects one
- (``ensure_nous_portal_access``). Kept as a no-op so call sites stay simple;
- always returns an empty string.
- """
- return ""
-
-
_POST_SETUP_INSTALLED: dict = {
# post_setup_key -> predicate(): True when the install side-effect
# is already satisfied. Used by `_toolset_needs_configuration_prompt`
@@ -3689,15 +3120,7 @@ def _module_installed(module_name: str) -> bool:
# arguments in sync with the corresponding ``_run_post_setup`` branches.
_RESTORABLE_PYTHON_TOOL_DEPENDENCIES: dict[str, tuple[str, tuple[str, ...]]] = {
"faster_whisper": ("faster_whisper", ("-U", "faster-whisper")),
- "kittentts": (
- "kittentts",
- (
- "-U",
- "https://github.com/KittenML/KittenTTS/releases/download/"
- "0.8.1/kittentts-0.8.1-py3-none-any.whl",
- "soundfile",
- ),
- ),
+ "kittentts": ("kittentts", ("-U", _KITTENTTS_WHEEL_URL, "soundfile")),
"piper": ("piper", ("-U", "piper-tts")),
"ddgs": ("ddgs", ("-U", "ddgs")),
"langfuse": ("langfuse", ("langfuse",)),
@@ -3723,13 +3146,11 @@ def restorable_python_tool_dependency(
def _agent_browser_installed() -> bool:
- """True when everything ``_run_post_setup("agent_browser")`` installs is
- present: the agent-browser CLI *and* the Chromium build it drives (or the
- Lightpanda engine, which needs no Chromium). Mirrors the hook so "Run
- setup" flips to an installed state only when re-running it would be a
- no-op."""
- import sys
-
+ """True when everything ``_run_post_setup("agent_browser")`` installs is present: the agent-browser
+ CLI *and* the Chromium build it drives (or the Lightpanda engine, which needs no Chromium).
+ Mirrors the hook so "Run setup" flips to an installed state only when re-running it would be a
+ no-op.
+ """
from hermes_cli.nous_subscription import _local_browser_runnable
# The install hook runs in a spawned ``hermes tools post-setup`` process,
@@ -3756,20 +3177,6 @@ def _camofox_installed() -> bool:
# still "needs_setup". Mirrors the installed-checks ``_run_post_setup`` itself
# performs before installing. ``xai_grok`` is intentionally absent — it is a
# credential bootstrap, not an install, and is handled as an auth check.
-_POST_SETUP_READY: dict = {
- "kittentts": lambda: _module_installed("kittentts"),
- "piper": lambda: _module_installed("piper"),
- "faster_whisper": lambda: _module_installed("faster_whisper"),
- "ddgs": lambda: _module_installed("ddgs"),
- "langfuse": lambda: _module_installed("langfuse"),
- "agent_browser": lambda: _agent_browser_installed(),
- "browserbase": lambda: _cloud_agent_browser_installed(),
- "camofox": lambda: _camofox_installed(),
- "lightpanda": lambda: _lightpanda_installed(),
- "cua_driver": lambda: _cua_driver_install_ready(),
-}
-
-
def _lightpanda_installed() -> bool:
"""True when a lightpanda binary is on PATH or in a known install dir."""
try:
@@ -3783,13 +3190,25 @@ def _lightpanda_installed() -> bool:
def _cloud_agent_browser_installed() -> bool:
"""Installed-check for the ``browserbase`` hook (cloud provider rows).
- Cloud providers host their own Chromium, so their hook only installs the
- agent-browser npm package — presence of the CLI is the whole contract."""
+ Cloud providers host their own Chromium, so their hook only installs the agent-browser npm
+ package — presence of the CLI is the whole contract.
+ """
from hermes_cli.nous_subscription import _has_agent_browser
return _has_agent_browser()
+# Late-bound lambdas so tests can monkeypatch the underlying predicates.
+_POST_SETUP_READY: dict = {
+ **{key: (lambda m=module: _module_installed(m)) for key, (module, _args) in _RESTORABLE_PYTHON_TOOL_DEPENDENCIES.items()},
+ "agent_browser": lambda: _agent_browser_installed(),
+ "browserbase": lambda: _cloud_agent_browser_installed(),
+ "camofox": lambda: _camofox_installed(),
+ "lightpanda": lambda: _lightpanda_installed(),
+ "cua_driver": lambda: _cua_driver_install_ready(),
+}
+
+
def provider_readiness_status(
provider: dict,
config: dict,
@@ -3799,30 +3218,12 @@ def provider_readiness_status(
) -> str:
"""Compute an honest readiness state for a provider picker row.
- Returns one of:
-
- - ``"ready"`` — usable as-is (keys set / entitled / installed).
- - ``"needs_keys"`` — declares env vars and at least one is unset.
- - ``"needs_auth"`` — needs a sign-in: Nous Portal login/entitlement for
- managed Tool Gateway rows, or xAI Grok OAuth / XAI_API_KEY for
- ``post_setup: "xai_grok"`` rows.
- - ``"needs_setup"`` — keyless row whose ``post_setup`` install hook has
- verifiably not run yet (see ``_POST_SETUP_READY``).
-
- Keyless ≠ usable: this is the server-side truth the GUI "Ready" pill
- renders from (the old client-side heuristic showed Ready for every
- zero-env-var row, including logged-out Nous Subscription rows).
-
- ``features`` (a ``NousSubscriptionFeatures``) can be passed to avoid
- re-fetching portal state per row. ``is_active`` is the completed-setup
- fallback signal for post_setup hooks with no registered installed-check
- (selecting a row runs its hook, so the active row has been set up).
+ ``features`` (a ``NousSubscriptionFeatures``) can be passed to avoid re-fetching portal state
+ per row. ``is_active`` is the completed-setup fallback signal for post_setup hooks with no
+ registered installed-check (selecting a row runs its hook, so the active row has been set up).
"""
- env_vars = provider.get("env_vars", [])
- if env_vars:
- if all(get_env_value(e["key"]) for e in env_vars):
- return "ready"
- return "needs_keys"
+ if provider.get("env_vars", []):
+ return "ready" if _provider_env_ready(provider) else "needs_keys"
managed_feature = provider.get("managed_nous_feature")
if provider.get("requires_nous_auth") or managed_feature:
@@ -3890,113 +3291,89 @@ def _toolset_needs_configuration_prompt(
if post_setup and not _post_setup_already_installed(post_setup):
return True
- if ts_key == "tts":
- tts_cfg = config.get("tts", {})
- return not isinstance(tts_cfg, dict) or "provider" not in tts_cfg
- if ts_key == "web":
- web_cfg = config.get("web", {})
- return not isinstance(web_cfg, dict) or "backend" not in web_cfg
- if ts_key == "browser":
- browser_cfg = config.get("browser", {})
- return not isinstance(browser_cfg, dict) or "cloud_provider" not in browser_cfg
+ # Categories whose "configured" signal is a selected provider key.
+ selection_key = {"tts": "provider", "web": "backend", "browser": "cloud_provider"}.get(ts_key)
+ if selection_key:
+ section = config.get(ts_key, {})
+ return not isinstance(section, dict) or selection_key not in section
if ts_key == "image_gen":
# Satisfied when the in-tree FAL backend is configured OR any
# plugin-registered image gen provider is available.
- if fal_key_is_configured():
- return False
- try:
- from agent.image_gen_registry import list_providers
- from hermes_cli.plugins import _ensure_plugins_discovered
-
- _ensure_plugins_discovered()
- for provider in list_providers():
- try:
- if provider.is_available():
- return False
- except Exception:
- continue
- except Exception:
- pass
- return True
+ return not fal_key_is_configured() and not _any_plugin_provider_available(
+ "agent.image_gen_registry"
+ )
if ts_key == "video_gen":
- # Satisfied when any plugin-registered video gen provider reports
- # available — no in-tree fallback (every backend is a plugin).
- try:
- from agent.video_gen_registry import list_providers
- from hermes_cli.plugins import _ensure_plugins_discovered
-
- _ensure_plugins_discovered()
- for provider in list_providers():
- try:
- if provider.is_available():
- return False
- except Exception:
- continue
- except Exception:
- pass
- return True
+ # No in-tree fallback — every video backend is a plugin.
+ return not _any_plugin_provider_available("agent.video_gen_registry")
return not _toolset_has_keys(ts_key, config, force_fresh=force_fresh)
+def _any_plugin_provider_available(registry_module: str) -> bool:
+ """True when any provider in the plugin registry reports ``is_available()``."""
+ try:
+ import importlib
+
+ registry = importlib.import_module(registry_module)
+ from hermes_cli.plugins import _ensure_plugins_discovered
+
+ _ensure_plugins_discovered()
+ for provider in registry.list_providers():
+ try:
+ if provider.is_available():
+ return True
+ except Exception:
+ continue
+ except Exception:
+ pass
+ return False
+
+
def _configure_tool_category(
ts_key: str,
cat: dict,
config: dict,
*,
force_fresh: bool = True,
+ reconfigure: bool = False,
):
- """Configure a tool category with provider selection."""
+ """Provider selection for a tool category, then API-key setup for the chosen row.
+
+ ``reconfigure`` is the "Reconfigure an existing tool" flow: no setup note / skip row / Nous
+ marker, and the chosen provider goes through the key-update prompts instead of the new-enable
+ prompts.
+ """
icon = cat.get("icon", "")
name = cat["name"]
providers = _visible_providers(cat, config, force_fresh=force_fresh)
- hidden_nous_message = _hidden_nous_gateway_message(
- cat,
- config,
- f"the Nous Subscription provider for {name}",
- force_fresh=force_fresh,
- )
-
- # Check Python version requirement
- if cat.get("requires_python"):
- req = cat["requires_python"]
- if sys.version_info < req:
- print()
- _print_error(f" {name} requires Python {req[0]}.{req[1]}+ (current: {sys.version_info.major}.{sys.version_info.minor})")
- _print_info(" Upgrade Python and reinstall to enable this tool.")
- return
if len(providers) == 1:
# Single provider - configure directly
provider = providers[0]
print()
print(color(f" --- {icon} {name} ({provider['name']}) ---", Colors.CYAN))
- if provider.get("tag"):
- _print_info(f" {provider['tag']}")
- # For single-provider tools, show a note if available
- if cat.get("setup_note"):
- _print_info(f" {cat['setup_note']}")
- if hidden_nous_message:
- for line in hidden_nous_message.splitlines():
- _print_warning(f" {line}")
- _configure_provider(provider, config, force_fresh=force_fresh)
- else:
- # Multiple providers - let user choose
- print()
- # Use custom title if provided (e.g. "Select Search Provider")
- title = cat.get("setup_title", "Choose a provider")
- print(color(f" --- {icon} {name} - {title} ---", Colors.CYAN))
- if cat.get("setup_note"):
- _print_info(f" {cat['setup_note']}")
- if hidden_nous_message:
- for line in hidden_nous_message.splitlines():
- _print_warning(f" {line}")
- print()
+ if not reconfigure:
+ if provider.get("tag"):
+ _print_info(f" {provider['tag']}")
+ if cat.get("setup_note"):
+ _print_info(f" {cat['setup_note']}")
+ _configure_provider(provider, config, force_fresh=force_fresh, reconfigure=reconfigure)
+ return
+
+ # Multiple providers - let user choose
+ print()
+ # Use custom title if provided (e.g. "Select Search Provider")
+ title = "Choose a provider" if reconfigure else cat.get("setup_title", "Choose a provider")
+ print(color(f" --- {icon} {name} - {title} ---", Colors.CYAN))
+ if not reconfigure and cat.get("setup_note"):
+ _print_info(f" {cat['setup_note']}")
+ print()
- # Plain text labels only (no ANSI codes in menu items)
- # When the user is logged into Nous, surface a marker on providers
- # whose access is included in their subscription so it's visually
- # obvious which options cost extra vs. cost nothing on top of Nous.
+ # When the user is logged into Nous, surface a marker on providers whose
+ # access is included in their subscription so it's visually obvious
+ # which options cost extra vs. cost nothing on top of Nous.
+ _nous_logged_in = False
+ if not reconfigure:
try:
_nous_logged_in = bool(
get_nous_subscription_features(
@@ -4007,64 +3384,61 @@ def _configure_tool_category(
except Exception:
_nous_logged_in = False
- provider_choices = []
- for p in providers:
- badge = f" [{p['badge']}]" if p.get("badge") else ""
- tag = f" — {p['tag']}" if p.get("tag") else ""
- configured = ""
- env_vars = p.get("env_vars", [])
- if not env_vars or all(get_env_value(v["key"]) for v in env_vars):
- if _is_provider_active(p, config, force_fresh=force_fresh):
- configured = " [active]"
- elif not env_vars:
- configured = ""
- else:
- configured = " [configured]"
- # Mark Nous-managed entries. Logged-in paid subscribers get the
- # "included" star; everyone else gets a "via Nous Portal" hint so
- # it's clear selecting the row triggers a Portal login. The rows
- # are always shown now (see _visible_providers) — selecting one
- # drives an inline login + entitlement check.
- sub_marker = ""
- if p.get("managed_nous_feature"):
- if _nous_logged_in:
- sub_marker = " ★ Included with your Nous subscription"
- else:
- sub_marker = " ★ via Nous Portal (login on select)"
- provider_choices.append(f"{p['name']}{badge}{tag}{configured}{sub_marker}")
-
- # Add skip option
+ # Plain text labels only (no ANSI codes in menu items)
+ provider_choices = []
+ for p in providers:
+ badge = f" [{p['badge']}]" if p.get("badge") else ""
+ tag = f" — {p['tag']}" if p.get("tag") else ""
+ configured = ""
+ if _provider_env_ready(p):
+ if _is_provider_active(p, config, force_fresh=force_fresh):
+ configured = " [active]"
+ elif p.get("env_vars", []):
+ configured = " [configured]"
+ # Mark Nous-managed entries. Logged-in paid subscribers get the
+ # "included" star; everyone else gets a "via Nous Portal" hint so
+ # it's clear selecting the row triggers a Portal login.
+ sub_marker = ""
+ if not reconfigure and p.get("managed_nous_feature"):
+ if _nous_logged_in:
+ sub_marker = " ★ Included with your Nous subscription"
+ else:
+ sub_marker = " ★ via Nous Portal (login on select)"
+ provider_choices.append(f"{p['name']}{badge}{tag}{configured}{sub_marker}")
+
+ if not reconfigure:
provider_choices.append("Skip — keep defaults / configure later")
- # Detect current provider as default
- default_idx = _detect_active_provider_index(
- providers,
- config,
- force_fresh=force_fresh,
- )
+ # Detect current provider as default
+ default_idx = _detect_active_provider_index(
+ providers,
+ config,
+ force_fresh=force_fresh,
+ )
- provider_idx = _prompt_choice(f" {title}:", provider_choices, default_idx)
+ question = " Select provider:" if reconfigure else f" {title}:"
+ provider_idx = _prompt_choice(question, provider_choices, default_idx)
- # Skip selected
- if provider_idx >= len(providers):
- _print_info(f" Skipped {name}")
- return
+ if provider_idx >= len(providers):
+ _print_info(f" Skipped {name}")
+ return
- _configure_provider(providers[provider_idx], config, force_fresh=force_fresh)
+ _configure_provider(
+ providers[provider_idx], config, force_fresh=force_fresh, reconfigure=reconfigure
+ )
def _web_tier_matches(provider: dict, config: dict) -> bool:
"""Return True when a web picker row's tier matches the configured tier.
- Tiered rows (Exa/Parallel Free vs Paid) share one ``web_backend`` name
- and differ only in ``web_tier``. The configured tier lives at
- ``web.provider_tier.<backend>`` (set on selection). Matching rules:
+ Tiered rows (Exa/Parallel Free vs Paid) share one ``web_backend`` name and differ only in
+ ``web_tier``. The configured tier lives at ``web.provider_tier.<backend>`` (set on selection).
+ Matching rules:
- - row has no ``web_tier`` → tier-agnostic row, matches (legacy rows)
- - configured tier set → must equal the row's tier
- - configured tier unset → "auto": the effective tier is paid when the
- row's env vars are all present, free otherwise — highlight the row
- the runtime would actually use
+ - row has no ``web_tier`` → tier-agnostic row, matches (legacy rows) - configured tier set →
+ must equal the row's tier - configured tier unset → "auto": the effective tier is paid when the
+ row's env vars are all present, free otherwise — highlight the row the runtime would actually
+ use
"""
row_tier = provider.get("web_tier")
if not row_tier:
@@ -4122,53 +3496,31 @@ def _is_provider_active(
feature = features.features.get(managed_feature)
if feature is None:
return False
- if managed_feature == "image_gen":
- image_cfg = config.get("image_gen", {})
- if isinstance(image_cfg, dict):
- configured_provider = image_cfg.get("provider")
- if configured_provider not in {None, "", "fal", NOUS_MANAGED_PROVIDER}:
- return False
- if (
- configured_provider != NOUS_MANAGED_PROVIDER
- and image_cfg.get("use_gateway") is not None
- and not is_truthy_value(image_cfg.get("use_gateway"), default=False)
- ):
- return False
- return feature.managed_by_nous
- if managed_feature == "video_gen":
- video_cfg = config.get("video_gen", {})
- if isinstance(video_cfg, dict):
- configured_provider = video_cfg.get("provider")
+ if managed_feature in ("image_gen", "video_gen"):
+ gen_cfg = config.get(managed_feature, {})
+ if isinstance(gen_cfg, dict):
+ configured_provider = gen_cfg.get("provider")
if configured_provider not in {None, "", "fal", NOUS_MANAGED_PROVIDER}:
return False
if (
configured_provider != NOUS_MANAGED_PROVIDER
- and video_cfg.get("use_gateway") is not None
- and not is_truthy_value(video_cfg.get("use_gateway"), default=False)
+ and gen_cfg.get("use_gateway") is not None
+ and not is_truthy_value(gen_cfg.get("use_gateway"), default=False)
):
return False
return feature.managed_by_nous
if provider.get("tts_provider"):
- return (
- feature.managed_by_nous
- and cfg_get(config, "tts", "provider")
- in {provider["tts_provider"], NOUS_MANAGED_PROVIDER}
- )
+ current = cfg_get(config, "tts", "provider")
+ return feature.managed_by_nous and current in {provider["tts_provider"], NOUS_MANAGED_PROVIDER}
if provider.get("stt_provider"):
- return (
- feature.managed_by_nous
- and cfg_get(config, "stt", "provider")
- in {provider["stt_provider"], NOUS_MANAGED_PROVIDER}
- )
+ current = cfg_get(config, "stt", "provider")
+ return feature.managed_by_nous and current in {provider["stt_provider"], NOUS_MANAGED_PROVIDER}
if "browser_provider" in provider:
# Browser Use mode is a driver on top of the provider (it attaches
# to the provider's CDP endpoint), so the provider row stays
# active alongside the Browser Use row.
current = cfg_get(config, "browser", "cloud_provider")
- return feature.managed_by_nous and current in {
- provider["browser_provider"],
- NOUS_MANAGED_PROVIDER,
- }
+ return feature.managed_by_nous and current in {provider["browser_provider"], NOUS_MANAGED_PROVIDER}
if provider.get("web_backend"):
current = cfg_get(config, "web", "backend")
return (
@@ -4261,8 +3613,7 @@ def _detect_active_provider_index(
if _is_provider_active(p, config, force_fresh=force_fresh):
return i
# Fallback: env vars present → likely configured
- env_vars = p.get("env_vars", [])
- if env_vars and all(get_env_value(v["key"]) for v in env_vars):
+ if p.get("env_vars", []) and _provider_env_ready(p):
return i
return 0
@@ -4295,48 +3646,69 @@ IMAGEGEN_BACKENDS = {
}
-def _format_imagegen_model_row(model_id: str, meta: dict, widths: dict) -> str:
- """Format a single picker row with column-aligned speed / strengths / price."""
- return (
- f"{model_id:<{widths['model']}} "
- f"{meta.get('speed', ''):<{widths['speed']}} "
- f"{meta.get('strengths', ''):<{widths['strengths']}} "
- f"{meta.get('price', '')}"
- )
+def _plugin_model_catalog(registry_module: str, plugin_name: str):
+ """Return ``(catalog_dict, default_model_id)`` for a plugin provider.
+ ``catalog_dict`` is shaped like the legacy ``FAL_MODELS`` table so the picker code path is
+ shared. Returns ``({}, None)`` if the provider is unregistered or has no models.
+ """
+ try:
+ import importlib
-def _configure_imagegen_model(backend_name: str, config: dict) -> None:
- """Prompt the user to pick a model for the given imagegen backend.
+ registry = importlib.import_module(registry_module)
+ from hermes_cli.plugins import _ensure_plugins_discovered
- Writes selection to ``config[backend_config_key]["model"]``. Safe to
- call even when stdin is not a TTY — curses_radiolist falls back to
- keeping the current selection.
- """
- backend = IMAGEGEN_BACKENDS.get(backend_name)
- if not backend:
- return
+ _ensure_plugins_discovered()
+ provider = registry.get_provider(plugin_name)
+ except Exception:
+ return {}, None
+ if provider is None:
+ return {}, None
+ try:
+ models = provider.list_models() or []
+ default = provider.default_model()
+ except Exception:
+ return {}, None
+ catalog = {m["id"]: m for m in models if isinstance(m, dict) and "id" in m}
+ return catalog, default
- catalog, default_model = backend["catalog_fn"]()
+
+def _plugin_image_gen_catalog(plugin_name: str):
+ """``(catalog, default_model)`` for a plugin-registered image gen provider."""
+ return _plugin_model_catalog("agent.image_gen_registry", plugin_name)
+
+
+def _plugin_video_gen_catalog(plugin_name: str):
+ """``(catalog, default_model)`` for a plugin-registered video gen provider."""
+ return _plugin_model_catalog("agent.video_gen_registry", plugin_name)
+
+
+def _pick_model_from_catalog(
+ catalog: dict,
+ default_model,
+ cfg_key: str,
+ display: str,
+ config: dict,
+ *,
+ row_indent: str = "",
+) -> None:
+ """Column-aligned model picker shared by the FAL, plugin image gen and video gen flows.
+
+ Writes the choice to ``config[cfg_key]["model"]``. The current model is listed first so the
+ cursor lands on it; a saved model that belongs to another provider (shared config key) or a
+ drifted catalog default never indexes the catalog. Safe when stdin is not a TTY —
+ curses_radiolist keeps the current selection.
+ """
if not catalog:
return
-
- cfg_key = backend["config_key"]
- cur_cfg = config.setdefault(cfg_key, {})
- if not isinstance(cur_cfg, dict):
- cur_cfg = {}
- config[cfg_key] = cur_cfg
+ cur_cfg = _cfg_section(config, cfg_key)
current_model = cur_cfg.get("model") or default_model
if current_model not in catalog:
- # The saved model may belong to another provider (shared config key)
- # and the catalog default itself may have drifted — never index the
- # catalog with a key it doesn't contain.
current_model = default_model if default_model in catalog else next(iter(catalog))
model_ids = list(catalog.keys())
- # Put current model at the top so the cursor lands on it by default.
ordered = [current_model] + [m for m in model_ids if m != current_model]
- # Column widths
widths = {
"model": max(len(m) for m in model_ids),
"speed": max((len(catalog[m].get("speed", "")) for m in model_ids), default=6),
@@ -4354,118 +3726,53 @@ def _configure_imagegen_model(backend_name: str, config: dict) -> None:
rows = []
for mid in ordered:
- row = _format_imagegen_model_row(mid, catalog[mid], widths)
+ meta = catalog[mid]
+ row = (
+ f"{row_indent}{mid:<{widths['model']}} "
+ f"{meta.get('speed', ''):<{widths['speed']}} "
+ f"{meta.get('strengths', ''):<{widths['strengths']}} "
+ f"{meta.get('price', '')}"
+ )
if mid == current_model:
row += " ← currently in use"
rows.append(row)
- idx = _prompt_choice(
- f" Choose {backend['display']} model:",
- rows,
- default=0,
- )
+ idx = _prompt_choice(f" Choose {display} model:", rows, default=0)
chosen = ordered[idx]
cur_cfg["model"] = chosen
_print_success(f" Model set to: {chosen}")
-def _plugin_image_gen_catalog(plugin_name: str):
- """Return ``(catalog_dict, default_model_id)`` for a plugin provider.
-
- ``catalog_dict`` is shaped like the legacy ``FAL_MODELS`` table —
- ``{model_id: {"display", "speed", "strengths", "price", ...}}`` —
- so the existing picker code paths work without change. Returns
- ``({}, None)`` if the provider isn't registered or has no models.
- """
- try:
- from agent.image_gen_registry import get_provider
- from hermes_cli.plugins import _ensure_plugins_discovered
-
- _ensure_plugins_discovered()
- provider = get_provider(plugin_name)
- except Exception:
- return {}, None
- if provider is None:
- return {}, None
- try:
- models = provider.list_models() or []
- default = provider.default_model()
- except Exception:
- return {}, None
- catalog = {m["id"]: m for m in models if isinstance(m, dict) and "id" in m}
- return catalog, default
+def _configure_imagegen_model(backend_name: str, config: dict) -> None:
+ """Prompt for a model of an in-tree imagegen backend (``IMAGEGEN_BACKENDS``)."""
+ backend = IMAGEGEN_BACKENDS.get(backend_name)
+ if not backend:
+ return
+ catalog, default_model = backend["catalog_fn"]()
+ _pick_model_from_catalog(catalog, default_model, backend["config_key"], backend["display"], config)
def _configure_imagegen_model_for_plugin(plugin_name: str, config: dict) -> None:
- """Prompt the user to pick a model for a plugin-registered backend.
-
- Writes selection to ``image_gen.model``. Mirrors
- :func:`_configure_imagegen_model` but sources its catalog from the
- plugin registry instead of :data:`IMAGEGEN_BACKENDS`.
- """
+ """Prompt for a model from a plugin-registered image gen backend's catalog."""
catalog, default_model = _plugin_image_gen_catalog(plugin_name)
- if not catalog:
- return
-
- cur_cfg = config.setdefault("image_gen", {})
- if not isinstance(cur_cfg, dict):
- cur_cfg = {}
- config["image_gen"] = cur_cfg
- current_model = cur_cfg.get("model") or default_model
- if current_model not in catalog:
- current_model = default_model if default_model in catalog else next(iter(catalog))
-
- model_ids = list(catalog.keys())
- ordered = [current_model] + [m for m in model_ids if m != current_model]
-
- widths = {
- "model": max(len(m) for m in model_ids),
- "speed": max((len(catalog[m].get("speed", "")) for m in model_ids), default=6),
- "strengths": max((len(catalog[m].get("strengths", "")) for m in model_ids), default=0),
- }
-
- print()
- header = (
- f" {'Model':<{widths['model']}} "
- f"{'Speed':<{widths['speed']}} "
- f"{'Strengths':<{widths['strengths']}} "
- f"Price"
- )
- print(color(header, Colors.CYAN))
+ _pick_model_from_catalog(catalog, default_model, "image_gen", plugin_name, config)
- rows = []
- for mid in ordered:
- row = _format_imagegen_model_row(mid, catalog[mid], widths)
- if mid == current_model:
- row += " ← currently in use"
- rows.append(row)
- idx = _prompt_choice(
- f" Choose {plugin_name} model:",
- rows,
- default=0,
+def _configure_videogen_model_for_plugin(plugin_name: str, config: dict) -> None:
+ """Prompt for a video gen model from a plugin's catalog."""
+ catalog, default_model = _plugin_video_gen_catalog(plugin_name)
+ # Video rows historically carry a two-space indent; kept for output parity.
+ _pick_model_from_catalog(
+ catalog, default_model, "video_gen", plugin_name, config, row_indent=" "
)
- chosen = ordered[idx]
- cur_cfg["model"] = chosen
- _print_success(f" Model set to: {chosen}")
-
def _configure_xai_imagine_storage(section_name: str, config: dict) -> None:
"""Prompt for xAI Imagine stored public URL behavior."""
- section = config.setdefault(section_name, {})
- if not isinstance(section, dict):
- section = {}
- config[section_name] = section
- xai_cfg = section.setdefault("xai", {})
- if not isinstance(xai_cfg, dict):
- xai_cfg = {}
- section["xai"] = xai_cfg
- storage_cfg = xai_cfg.setdefault("storage", {})
- if not isinstance(storage_cfg, dict):
- storage_cfg = {}
- xai_cfg["storage"] = storage_cfg
+ section = _cfg_section(config, section_name)
+ xai_cfg = _cfg_section(section, "xai")
+ storage_cfg = _cfg_section(xai_cfg, "storage")
_print_warning(
" xAI Imagine can store generated media and create reusable public URLs. "
@@ -4495,115 +3802,31 @@ def _configure_xai_imagine_storage(section_name: str, config: dict) -> None:
_print_success(" xAI stored public URLs enabled without automatic expiry")
-def _select_plugin_image_gen_provider(plugin_name: str, config: dict, *, use_gateway: bool = False) -> None:
- """Persist a plugin-backed image generation provider selection.
+def _select_plugin_gen_provider(section: str, plugin_name: str, config: dict, *, use_gateway: bool) -> None:
+ """Persist a plugin-backed image/video generation provider selection and run its model picker.
- ``use_gateway=True`` marks a provider picked through the Nous-managed
- flow: the stored selection becomes ``image_gen.provider: nous`` (the
- single provider string the runtime switches on). BYOK picks store the
- plugin name. Any legacy ``use_gateway`` key is removed so old-config
- read-time shims cannot override the fresh selection.
+ ``use_gateway=True`` (Nous-managed pick) stores ``<section>.provider: nous``; BYOK picks store
+ the plugin name. Any legacy ``use_gateway`` key is removed so old read-time shims cannot
+ override the fresh selection.
"""
- img_cfg = config.setdefault("image_gen", {})
- if not isinstance(img_cfg, dict):
- img_cfg = {}
- config["image_gen"] = img_cfg
- img_cfg["provider"] = NOUS_MANAGED_PROVIDER if use_gateway else plugin_name
- img_cfg.pop("use_gateway", None)
- _print_success(f" image_gen.provider set to: {img_cfg['provider']}")
- _configure_imagegen_model_for_plugin(plugin_name, config)
+ cfg = _cfg_section(config, section)
+ cfg["provider"] = NOUS_MANAGED_PROVIDER if use_gateway else plugin_name
+ cfg.pop("use_gateway", None)
+ _print_success(f" {section}.provider set to: {cfg['provider']}")
+ if section == "image_gen":
+ _configure_imagegen_model_for_plugin(plugin_name, config)
+ else:
+ _configure_videogen_model_for_plugin(plugin_name, config)
if plugin_name == "xai":
- _configure_xai_imagine_storage("image_gen", config)
-
-
-# ─── Video Generation Model Pickers ───────────────────────────────────────────
-
+ _configure_xai_imagine_storage(section, config)
-def _plugin_video_gen_catalog(plugin_name: str):
- """Return ``(catalog_dict, default_model_id)`` for a video gen plugin.
-
- Mirrors :func:`_plugin_image_gen_catalog`. Returns ``({}, None)`` when
- the plugin isn't registered or has no models.
- """
- try:
- from agent.video_gen_registry import get_provider
- from hermes_cli.plugins import _ensure_plugins_discovered
-
- _ensure_plugins_discovered()
- provider = get_provider(plugin_name)
- except Exception:
- return {}, None
- if provider is None:
- return {}, None
- try:
- models = provider.list_models() or []
- default = provider.default_model()
- except Exception:
- return {}, None
- catalog = {m["id"]: m for m in models if isinstance(m, dict) and "id" in m}
- return catalog, default
-
-
-def _configure_videogen_model_for_plugin(plugin_name: str, config: dict) -> None:
- """Prompt for a video gen model from a plugin's catalog.
-
- Mirrors :func:`_configure_imagegen_model_for_plugin`. Writes the
- selection to ``video_gen.model``.
- """
- catalog, default_model = _plugin_video_gen_catalog(plugin_name)
- if not catalog:
- return
-
- cur_cfg = config.setdefault("video_gen", {})
- if not isinstance(cur_cfg, dict):
- cur_cfg = {}
- config["video_gen"] = cur_cfg
- current_model = cur_cfg.get("model") or default_model
- if current_model not in catalog:
- # Same guard as the image pickers: a stale cross-provider model or a
- # drifted default must not become an unindexable catalog key.
- current_model = default_model if default_model in catalog else next(iter(catalog))
-
- model_ids = list(catalog.keys())
- ordered = [current_model] + [m for m in model_ids if m != current_model]
-
- widths = {
- "model": max(len(m) for m in model_ids),
- "speed": max((len(catalog[m].get("speed", "")) for m in model_ids), default=6),
- "strengths": max((len(catalog[m].get("strengths", "")) for m in model_ids), default=0),
- }
-
- print()
- header = (
- f" {'Model':<{widths['model']}} "
- f"{'Speed':<{widths['speed']}} "
- f"{'Strengths':<{widths['strengths']}} "
- f"Price"
- )
- print(color(header, Colors.CYAN))
- rows = []
- for mid in ordered:
- meta = catalog[mid]
- row = (
- f" {mid:<{widths['model']}} "
- f"{meta.get('speed', ''):<{widths['speed']}} "
- f"{meta.get('strengths', ''):<{widths['strengths']}} "
- f"{meta.get('price', '')}"
- )
- if mid == current_model:
- row += " ← currently in use"
- rows.append(row)
+def _select_plugin_image_gen_provider(plugin_name: str, config: dict, *, use_gateway: bool = False) -> None:
+ _select_plugin_gen_provider("image_gen", plugin_name, config, use_gateway=use_gateway)
- idx = _prompt_choice(
- f" Choose {plugin_name} model:",
- rows,
- default=0,
- )
- chosen = ordered[idx]
- cur_cfg["model"] = chosen
- _print_success(f" Model set to: {chosen}")
+def _select_plugin_video_gen_provider(plugin_name: str, config: dict, *, use_gateway: bool = False) -> None:
+ _select_plugin_gen_provider("video_gen", plugin_name, config, use_gateway=use_gateway)
# Per-provider STT model catalogs for the interactive picker. Keys are
@@ -4623,22 +3846,12 @@ _STT_MODEL_CONFIG_KEY = {"elevenlabs": "model_id"}
def _configure_stt_model(stt_provider: str, config: dict) -> None:
- """Prompt for the STT model after a provider pick (when a catalog exists).
-
- Providers without a static catalog (xai, deepinfra) skip the prompt —
- xAI has a single model and DeepInfra resolves from its live catalog.
- """
+ """Prompt for the STT model after a provider pick (when a catalog exists)."""
catalog = STT_MODEL_CATALOG.get(stt_provider)
if not catalog:
return
- stt_cfg = config.setdefault("stt", {})
- if not isinstance(stt_cfg, dict):
- stt_cfg = {}
- config["stt"] = stt_cfg
- prov_cfg = stt_cfg.setdefault(stt_provider, {})
- if not isinstance(prov_cfg, dict):
- prov_cfg = {}
- stt_cfg[stt_provider] = prov_cfg
+ stt_cfg = _cfg_section(config, "stt")
+ prov_cfg = _cfg_section(stt_cfg, stt_provider)
model_key = _STT_MODEL_CONFIG_KEY.get(stt_provider, "model")
current = str(prov_cfg.get(model_key) or "").strip()
ordered = list(catalog)
@@ -4649,46 +3862,29 @@ def _configure_stt_model(stt_provider: str, config: dict) -> None:
_print_success(f" STT model set to: {chosen}")
-def _select_plugin_video_gen_provider(plugin_name: str, config: dict, *, use_gateway: bool = False) -> None:
- """Persist a plugin-backed video generation provider selection.
-
- Mirrors :func:`_select_plugin_image_gen_provider`: managed picks store
- ``video_gen.provider: nous``; BYOK picks store the plugin name; any
- legacy ``use_gateway`` key is removed.
- """
- vid_cfg = config.setdefault("video_gen", {})
- if not isinstance(vid_cfg, dict):
- vid_cfg = {}
- config["video_gen"] = vid_cfg
- vid_cfg["provider"] = NOUS_MANAGED_PROVIDER if use_gateway else plugin_name
- vid_cfg.pop("use_gateway", None)
- _print_success(f" video_gen.provider set to: {vid_cfg['provider']}")
- _configure_videogen_model_for_plugin(plugin_name, config)
- if plugin_name == "xai":
- _configure_xai_imagine_storage("video_gen", config)
+# Provider-row marker key -> config section it selects into.
+_PROVIDER_MARKER_SECTIONS = {
+ "tts_provider": "tts",
+ "stt_provider": "stt",
+ "browser_provider": "browser",
+ "web_backend": "web",
+ "image_gen_plugin_name": "image_gen",
+ "imagegen_backend": "image_gen",
+ "video_gen_plugin_name": "video_gen",
+}
def _write_provider_config(provider: dict, config: dict, *, managed_feature) -> None:
"""Persist the provider/backend config keys for a selected provider.
- This is the pure, non-interactive core of :func:`_configure_provider` —
- it writes ``tts.provider`` / ``browser.cloud_provider`` / ``web.backend``
- based on the provider's markers, but does NOT prompt for env vars, run
- post-setup hooks, gate on Nous auth, or run interactive model pickers.
- Both the CLI configurator and the desktop GUI ``PUT .../provider``
- endpoint call through here so there is one code path.
-
- Selection model: every row writes exactly ONE provider string per
- category. Managed "Nous Subscription" rows write ``nous``; BYOK rows
- write the vendor name. ``use_gateway`` is no longer written — a fresh
- pick removes any legacy key from the touched section so the read-time
- legacy shim (use_gateway: true ⇒ nous) cannot override the new choice.
+ Pure, non-interactive core of :func:`_configure_provider`: no env prompts, post-setup hooks,
+ Nous auth gating or model pickers. Both the CLI and the GUI ``PUT .../provider`` endpoint call
+ through here so there is one code path. Each pick writes exactly ONE provider string per
+ category (``nous`` for managed rows) and removes any legacy ``use_gateway`` key so the read-time
+ shim cannot override the new choice.
"""
def _set_selection(section_key: str, name_key: str, vendor_value) -> None:
- section = config.setdefault(section_key, {})
- if not isinstance(section, dict):
- section = {}
- config[section_key] = section
+ section = _cfg_section(config, section_key)
section[name_key] = (
NOUS_MANAGED_PROVIDER if managed_feature else vendor_value
)
@@ -4757,44 +3953,27 @@ def _write_provider_config(provider: dict, config: dict, *, managed_feature) ->
# provider's own markers first (plugin-injected rows are NOT in
# TOOL_CATEGORIES' hardcoded provider lists and previously skipped
# this clear), then fall back to the category-membership walk.
- marker_sections = {
- "tts_provider": "tts",
- "stt_provider": "stt",
- "browser_provider": "browser",
- "web_backend": "web",
- "image_gen_plugin_name": "image_gen",
- "imagegen_backend": "image_gen",
- "video_gen_plugin_name": "video_gen",
- }
- cleared = False
- for marker, section_key in marker_sections.items():
- if provider.get(marker) or marker in provider:
- section = config.get(section_key)
- if isinstance(section, dict):
- section.pop("use_gateway", None)
- cleared = True
- if not cleared:
- for cat_key, cat in TOOL_CATEGORIES.items():
- if provider in cat.get("providers", []):
- section = config.get(cat_key)
- if isinstance(section, dict):
- section.pop("use_gateway", None)
- break
+ sections = [
+ section_key for marker, section_key in _PROVIDER_MARKER_SECTIONS.items()
+ if marker in provider
+ ]
+ if not sections:
+ sections = [
+ cat_key for cat_key, cat in TOOL_CATEGORIES.items()
+ if provider in cat.get("providers", [])
+ ][:1]
+ for section_key in sections:
+ section = config.get(section_key)
+ if isinstance(section, dict):
+ section.pop("use_gateway", None)
def apply_provider_selection(ts_key: str, provider_name: str, config: dict) -> None:
"""Non-interactively persist a provider selection for a toolset.
- Resolves ``provider_name`` within ``ts_key``'s category (matching the
- rows the GUI/CLI picker shows via :func:`_visible_providers`) and writes
- the corresponding backend/provider config keys. Unlike
- :func:`_configure_provider`, this does NOT prompt for API keys, run
- post-setup hooks, gate on Nous Portal auth, or run interactive model
- pickers — those are handled separately (env endpoints, post-setup
- endpoints, the model picker) in the desktop GUI.
-
- Raises ``KeyError`` if the toolset has no category or the provider name
- is not found among the visible providers.
+ Resolves ``provider_name`` among the rows the picker shows (:func:`_visible_providers`) and
+ writes the config keys only — API keys, post-setup hooks, auth gating and model pickers are
+ handled by separate GUI endpoints. Raises ``KeyError`` for an unknown toolset or provider.
"""
cat = TOOL_CATEGORIES.get(ts_key)
if cat is None:
@@ -4809,59 +3988,32 @@ def apply_provider_selection(ts_key: str, provider_name: str, config: dict) -> N
_write_provider_config(provider, config, managed_feature=managed_feature)
# Plugin-registered image/video gen backends record the provider name in
- # their own config section. Write that here (without the interactive
- # model picker the CLI runs afterwards — model choice is a separate GUI
- # flow). Managed picks store the "nous" selection.
- plugin_name = provider.get("image_gen_plugin_name")
- if plugin_name:
- img_cfg = config.setdefault("image_gen", {})
- if not isinstance(img_cfg, dict):
- img_cfg = {}
- config["image_gen"] = img_cfg
- img_cfg["provider"] = (
- NOUS_MANAGED_PROVIDER if managed_feature else plugin_name
- )
- img_cfg.pop("use_gateway", None)
-
- video_plugin = provider.get("video_gen_plugin_name")
- if video_plugin:
- vid_cfg = config.setdefault("video_gen", {})
- if not isinstance(vid_cfg, dict):
- vid_cfg = {}
- config["video_gen"] = vid_cfg
- vid_cfg["provider"] = (
- NOUS_MANAGED_PROVIDER if managed_feature else video_plugin
- )
- vid_cfg.pop("use_gateway", None)
-
- # In-tree FAL imagegen backend (BYOK): always persist the explicit
- # ``image_gen.provider: fal`` selection — historically this row could
- # leave the provider key unset, making a deliberate BYOK pick
- # indistinguishable from a never-configured install.
- if provider.get("imagegen_backend") and not managed_feature:
- img_cfg = config.setdefault("image_gen", {})
- if not isinstance(img_cfg, dict):
- img_cfg = {}
- config["image_gen"] = img_cfg
- img_cfg["provider"] = "fal"
- img_cfg.pop("use_gateway", None)
+ # their own config section (without the interactive model picker the CLI
+ # runs afterwards — model choice is a separate GUI flow). Managed picks
+ # store the "nous" selection. The in-tree FAL BYOK row always persists an
+ # explicit ``image_gen.provider: fal`` — historically it could leave the
+ # key unset, making a deliberate pick indistinguishable from a
+ # never-configured install.
+ selections = [
+ ("image_gen", provider.get("image_gen_plugin_name")),
+ ("video_gen", provider.get("video_gen_plugin_name")),
+ ("image_gen", "fal" if provider.get("imagegen_backend") and not managed_feature else None),
+ ]
+ for section_key, vendor in selections:
+ if vendor:
+ section = _cfg_section(config, section_key)
+ section["provider"] = NOUS_MANAGED_PROVIDER if managed_feature else vendor
+ section.pop("use_gateway", None)
-def _configure_provider(
- provider: dict,
- config: dict,
- *,
- force_fresh: bool = True,
-):
- """Configure a single provider - prompt for API keys and set config."""
- env_vars = provider.get("env_vars", [])
- managed_feature = provider.get("managed_nous_feature")
+def _nous_provider_gate(provider: dict, config: dict, managed_feature, *, force_fresh: bool) -> bool:
+ """Return False (after printing why) when a Nous-gated row cannot be selected.
- # Nous-managed Tool Gateway backends are always listed (see
- # _visible_providers), but only *activate* once the user has paid Nous
- # Portal access. Selecting one runs an inline Portal login when needed —
- # auth + entitlement only, no inference-provider switch and no bulk
- # "enable all tools" prompt (that lives in `hermes model`).
+ Managed Tool Gateway rows are always listed (see ``_visible_providers``) but only *activate*
+ with paid Nous Portal access — selecting one runs an inline Portal login (auth + entitlement
+ only, no inference-provider switch). Pure pre-auth UX rows (``requires_nous_auth`` without a
+ managed feature) keep the older logged-in + entitled gate.
+ """
if managed_feature:
from hermes_cli.nous_subscription import (
MANAGED_FEATURE_COVERAGE_CATEGORY,
@@ -4875,12 +4027,10 @@ def _configure_provider(
_print_warning(
" Not enabled — Nous Portal access is required for this backend."
)
- return
+ return False
+ return True
- # Pure pre-auth UX rows (requires_nous_auth without a managed gateway
- # feature) keep the old gate. Managed rows are handled by the inline
- # login above, so don't double-check them here.
- if provider.get("requires_nous_auth") and not managed_feature:
+ if provider.get("requires_nous_auth"):
features = get_nous_subscription_features(config, force_fresh=force_fresh)
entitled = bool(
features.account_info and features.account_info.paid_service_access is True
@@ -4893,37 +4043,86 @@ def _configure_provider(
_print_warning(
f" {message or 'Nous Subscription is only available after logging into Nous Portal.'}"
)
- return
+ return False
+ return True
- # Set TTS provider in config if applicable
- if provider.get("tts_provider"):
- tts_cfg = config.setdefault("tts", {})
- tts_cfg["provider"] = (
- NOUS_MANAGED_PROVIDER if managed_feature else provider["tts_provider"]
- )
- tts_cfg.pop("use_gateway", None)
- # Set STT provider in config if applicable
+def _finish_provider_selection(provider: dict, config: dict, managed_feature) -> None:
+ """Model pickers that follow a provider pick: plugin image/video gen, in-tree FAL, STT."""
+ plugin_name = provider.get("image_gen_plugin_name")
+ if plugin_name:
+ _select_plugin_image_gen_provider(plugin_name, config, use_gateway=bool(managed_feature))
+ return
+ video_plugin = provider.get("video_gen_plugin_name")
+ if video_plugin:
+ _select_plugin_video_gen_provider(video_plugin, config, use_gateway=bool(managed_feature))
+ return
+ backend = provider.get("imagegen_backend")
+ if backend:
+ _configure_imagegen_model(backend, config)
+ # In-tree FAL is the only non-plugin backend today. Persist the
+ # explicit selection: "nous" for a managed row, "fal" for BYOK, and
+ # drop any legacy use_gateway key — never clobber a Nous-managed pick
+ # back onto direct keys.
+ img_cfg = _cfg_section(config, "image_gen")
+ img_cfg["provider"] = NOUS_MANAGED_PROVIDER if managed_feature else "fal"
+ img_cfg.pop("use_gateway", None)
+ # STT providers prompt for model selection after the backend pick
+ # (skipped for managed rows — the gateway pins the model).
+ if provider.get("stt_provider") and not managed_feature:
+ _configure_stt_model(provider["stt_provider"], config)
+
+
+def _print_provider_selection(provider: dict, managed_feature, *, reconfigure: bool) -> None:
+ """Status lines announcing which backend/provider keys a pick writes."""
+ if reconfigure and provider.get("tts_provider"):
+ _print_success(f" TTS provider set to: {provider['tts_provider']}")
if provider.get("stt_provider"):
_print_success(f" STT provider set to: {provider['stt_provider']}")
-
- # Set browser cloud provider in config if applicable
if "browser_provider" in provider:
bp = provider["browser_provider"]
- if bp == "local":
+ if reconfigure and managed_feature:
+ _print_success(f" Browser cloud provider set to: {bp or 'nous'}")
+ elif bp == "local":
_print_success(" Browser set to local mode")
elif bp:
_print_success(f" Browser cloud provider set to: {bp}")
-
if provider.get("browser_backend"):
_print_success(" Browser set to Browser Use (browser_exec via CLI 3.0)")
-
if provider.get("browser_engine") and provider["browser_engine"] != "auto":
_print_success(f" Browser engine set to: {provider['browser_engine']}")
-
- # Set web search backend in config if applicable
if provider.get("web_backend"):
- _print_success(f" Web backend set to: {provider['web_backend']}")
+ if reconfigure and provider.get("web_tier"):
+ _print_success(
+ f" Web backend set to: {provider['web_backend']} "
+ f"({provider['web_tier']} tier)"
+ )
+ else:
+ _print_success(f" Web backend set to: {provider['web_backend']}")
+ if reconfigure and provider.get("computer_use_backend"):
+ _print_success(f" Computer Use backend set to: {provider['computer_use_backend']}")
+
+
+def _configure_provider(
+ provider: dict,
+ config: dict,
+ *,
+ force_fresh: bool = True,
+ reconfigure: bool = False,
+):
+ """Configure a single provider - prompt for API keys and set config.
+
+ ``reconfigure=False`` is the new-enable flow: already-set keys are kept without asking, and
+ the post-setup hook only runs when every key was provided. ``reconfigure=True`` re-prompts
+ every key ("Enter to keep current") and always runs the post-setup hook.
+ """
+ env_vars = provider.get("env_vars", [])
+ managed_feature = provider.get("managed_nous_feature")
+
+ if not _nous_provider_gate(provider, config, managed_feature, force_fresh=force_fresh):
+ return
+
+ _print_provider_selection(provider, managed_feature, reconfigure=reconfigure)
# Persist the provider/backend config keys + use_gateway flags. Shared
# with the GUI provider-select endpoint via apply_provider_selection so
@@ -4936,44 +4135,36 @@ def _configure_provider(
_print_success(f" {provider['name']} - no configuration needed!")
if managed_feature:
_print_info(" Requests for this tool will be billed to your Nous subscription.")
- # Plugin-registered image_gen provider: write image_gen.provider
- # and route model selection to the plugin's own catalog.
- plugin_name = provider.get("image_gen_plugin_name")
- if plugin_name:
- _select_plugin_image_gen_provider(plugin_name, config, use_gateway=bool(managed_feature))
- return
- # Plugin-registered video_gen provider — same flow, different
- # registry.
- video_plugin = provider.get("video_gen_plugin_name")
- if video_plugin:
- _select_plugin_video_gen_provider(video_plugin, config, use_gateway=bool(managed_feature))
- return
- # Imagegen backends prompt for model selection after backend pick.
- backend = provider.get("imagegen_backend")
- if backend:
- _configure_imagegen_model(backend, config)
- # In-tree FAL is the only non-plugin backend today. Persist the
- # explicit selection: "nous" for a managed row, "fal" for BYOK.
- img_cfg = config.setdefault("image_gen", {})
- if isinstance(img_cfg, dict):
- img_cfg["provider"] = (
- NOUS_MANAGED_PROVIDER if managed_feature else "fal"
- )
- img_cfg.pop("use_gateway", None)
- # STT providers prompt for model selection after backend pick
- # (skipped for managed rows — the gateway pins the model).
- if provider.get("stt_provider") and not managed_feature:
- _configure_stt_model(provider["stt_provider"], config)
+ _finish_provider_selection(provider, config, managed_feature)
+ return
+
+ if reconfigure:
+ for var in env_vars:
+ existing = get_env_value(var["key"])
+ if existing:
+ _print_info(f" {var['key']}: configured ({existing[:8]}...)")
+ url = var.get("url", "")
+ if url:
+ _print_info(f" Get yours at: {url}")
+ default_val = var.get("default", "")
+ value = _prompt(f" {var.get('prompt', var['key'])} (Enter to keep current)", password=not default_val)
+ if value and value.strip():
+ save_env_value(var["key"], value.strip())
+ _print_success(" Updated")
+ else:
+ _print_info(" Kept current")
+
+ if provider.get("post_setup"):
+ _run_post_setup(provider["post_setup"])
+ _finish_provider_selection(provider, config, managed_feature)
return
- # Prompt for each required env var
- all_configured = True
# If this BYOK provider lives in a category that ALSO has a
# Nous-managed sibling, show a single dim hint so users know
# they can avoid the key entirely via a Portal subscription.
# Suppressed when the user is already authed to Nous.
_show_portal_hint = False
- if env_vars and not managed_feature and not provider.get("requires_nous_auth"):
+ if not managed_feature and not provider.get("requires_nous_auth"):
try:
_has_managed_sibling = False
for _cat_key, _cat in TOOL_CATEGORIES.items():
@@ -4995,12 +4186,13 @@ def _configure_provider(
if _show_portal_hint:
_print_info(" Available through Nous Portal subscription.")
+ # Prompt for each required env var
+ all_configured = True
for var in env_vars:
existing = get_env_value(var["key"])
if existing:
- _print_success(f" {var['key']}: already configured")
# Don't ask to update - this is a new enable flow.
- # Reconfigure is handled separately.
+ _print_success(f" {var['key']}: already configured")
else:
url = var.get("url", "")
if url:
@@ -5025,39 +4217,21 @@ def _configure_provider(
if all_configured:
_print_success(f" {provider['name']} configured!")
- plugin_name = provider.get("image_gen_plugin_name")
- if plugin_name:
- _select_plugin_image_gen_provider(plugin_name, config, use_gateway=bool(managed_feature))
- return
- video_plugin = provider.get("video_gen_plugin_name")
- if video_plugin:
- _select_plugin_video_gen_provider(video_plugin, config, use_gateway=bool(managed_feature))
- return
- # Imagegen backends prompt for model selection after env vars are in.
- backend = provider.get("imagegen_backend")
- if backend:
- _configure_imagegen_model(backend, config)
- img_cfg = config.setdefault("image_gen", {})
- if isinstance(img_cfg, dict):
- img_cfg["provider"] = (
- NOUS_MANAGED_PROVIDER if managed_feature else "fal"
- )
- img_cfg.pop("use_gateway", None)
- # STT providers prompt for model selection after env vars are in.
- if provider.get("stt_provider") and not managed_feature:
- _configure_stt_model(provider["stt_provider"], config)
+ _finish_provider_selection(provider, config, managed_feature)
+
+
+def _reconfigure_provider(provider: dict, config: dict, *, force_fresh: bool = True):
+ """Reconfigure a provider - update API keys."""
+ _configure_provider(provider, config, force_fresh=force_fresh, reconfigure=True)
def _configure_vision_backend() -> None:
"""Interactive vision-backend configuration.
- Vision is an auxiliary task whose provider/model are resolved from
- ``auxiliary.vision.{provider,model,base_url}`` in config.yaml (see
- ``agent/auxiliary_client.resolve_vision_provider_client``). Rather than
- forcing the user onto OpenRouter, let them pick any authenticated
- provider + model — the same surface as ``hermes model`` — or point at a
- custom OpenAI-compatible endpoint. "Auto" leaves the config keys empty so
- the resolver uses the main model / aggregator fallback chain.
+ Vision resolves from ``auxiliary.vision.{provider,model,base_url}``. Rather than forcing
+ OpenRouter, offer any authenticated provider + model (same surface as ``hermes model``) or a
+ custom endpoint. "Auto" leaves the keys empty so the resolver uses the main-model fallback
+ chain.
"""
print()
print(color(" Vision / Image Analysis needs a multimodal model.", Colors.YELLOW))
@@ -5075,14 +4249,7 @@ def _configure_vision_backend() -> None:
idx = _prompt_choice(" Configure vision backend", choices, 0)
config = load_config()
- aux = config.setdefault("auxiliary", {})
- if not isinstance(aux, dict):
- aux = {}
- config["auxiliary"] = aux
- vision_cfg = aux.setdefault("vision", {})
- if not isinstance(vision_cfg, dict):
- vision_cfg = {}
- aux["vision"] = vision_cfg
+ vision_cfg = _cfg_section(_cfg_section(config, "auxiliary"), "vision")
if idx == 0:
# Auto: clear any pinned override so the resolver auto-detects.
@@ -5131,12 +4298,9 @@ def _configure_vision_backend() -> None:
def _configure_vision_provider_model(config: dict, vision_cfg: dict) -> None:
"""Provider + model picker for vision, mirroring the ``/model`` surface.
- Provider rows come from ``build_aux_picker_rows()`` — the shared aux-picker
- substrate — so this picker lists exactly what the ``hermes model`` aux-task
- picker lists, including the user's own ``providers:`` / ``custom_providers:``
- endpoints. Lets the user pick a provider and then a model from its curated
- list (or type a custom id), and persists ``auxiliary.vision.provider`` +
- ``.model``.
+ Rows come from ``build_aux_picker_rows()`` so this lists exactly what the ``hermes model``
+ aux-task picker lists, including user-defined ``providers:`` / ``custom_providers:`` endpoints.
+ Persists ``auxiliary.vision.provider`` + ``.model``.
"""
try:
from hermes_cli.inventory import (
@@ -5211,35 +4375,48 @@ def _configure_vision_provider_model(config: dict, vision_cfg: dict) -> None:
_print_success(f" Vision set to {slug} / {model}")
-def _configure_simple_requirements(ts_key: str):
- """Simple fallback for toolsets that just need env vars (no provider selection)."""
+def _configure_simple_requirements(ts_key: str, *, reconfigure: bool = False):
+ """Fallback for toolsets that just need env vars (no provider selection).
+
+ Vision has its own provider/model picker (any provider, like ``hermes model``) — run it
+ directly so neither flow falls back to the generic single-key prompt (which would re-ask for
+ OPENROUTER_API_KEY).
+ """
if ts_key == "vision":
- if _toolset_has_keys("vision"):
- return
- _configure_vision_backend()
+ if reconfigure or not _toolset_has_keys("vision"):
+ _configure_vision_backend()
return
requirements = TOOLSET_ENV_REQUIREMENTS.get(ts_key, [])
+ if not reconfigure:
+ requirements = [(var, url) for var, url in requirements if not get_env_value(var)]
if not requirements:
return
- missing = [(var, url) for var, url in requirements if not get_env_value(var)]
- if not missing:
- return
-
- ts_label = next((l for k, l, _ in _get_effective_configurable_toolsets() if k == ts_key), ts_key)
+ ts_label = _toolset_label(ts_key)
print()
- print(color(f" {ts_label} requires configuration:", Colors.YELLOW))
+ if reconfigure:
+ print(color(f" {ts_label}:", Colors.CYAN))
+ else:
+ print(color(f" {ts_label} requires configuration:", Colors.YELLOW))
- for var, url in missing:
+ for var, url in requirements:
+ if reconfigure:
+ existing = get_env_value(var)
+ if existing:
+ _print_info(f" {var}: configured ({existing[:8]}...)")
if url:
_print_info(f" Get key at: {url}")
- value = _prompt(f" {var}", password=True)
+ suffix = " (Enter to keep current)" if reconfigure else ""
+ value = _prompt(f" {var}{suffix}", password=True)
if value and value.strip():
save_env_value(var, value.strip())
- _print_success(" Saved")
+ _print_success(" Updated" if reconfigure else " Saved")
else:
- _print_warning(" Skipped")
+ if reconfigure:
+ _print_info(" Kept current")
+ else:
+ _print_warning(" Skipped")
def _reconfigure_tool(
@@ -5251,14 +4428,11 @@ def _reconfigure_tool(
# Build list of configurable tools that are currently set up
configurable = []
for ts_key, ts_label, _ in _get_effective_configurable_toolsets():
- cat = TOOL_CATEGORIES.get(ts_key)
- reqs = TOOLSET_ENV_REQUIREMENTS.get(ts_key)
- if cat or reqs:
- if (
- _toolset_has_keys(ts_key, config, force_fresh=force_fresh)
- or _toolset_enabled_for_reconfigure(ts_key, config)
- ):
- configurable.append((ts_key, ts_label))
+ if _is_configurable(ts_key) and (
+ _toolset_has_keys(ts_key, config, force_fresh=force_fresh)
+ or _toolset_enabled_for_reconfigure(ts_key, config)
+ ):
+ configurable.append((ts_key, ts_label))
if not configurable:
_print_info("No configured tools to reconfigure.")
@@ -5276,14 +4450,9 @@ def _reconfigure_tool(
cat = TOOL_CATEGORIES.get(ts_key)
if cat:
- _configure_tool_category_for_reconfig(
- ts_key,
- cat,
- config,
- force_fresh=force_fresh,
- )
+ _configure_tool_category(ts_key, cat, config, force_fresh=force_fresh, reconfigure=True)
else:
- _reconfigure_simple_requirements(ts_key)
+ _configure_simple_requirements(ts_key, reconfigure=True)
save_config(config)
@@ -5291,8 +4460,8 @@ def _reconfigure_tool(
def _toolset_enabled_for_reconfigure(ts_key: str, config: dict) -> bool:
"""Return True if a configurable toolset is enabled anywhere.
- Reconfigure must include enabled-but-unconfigured categories so users can
- finish provider/API-key setup without disabling and re-enabling the toolset.
+ Reconfigure must include enabled-but-unconfigured categories so users can finish provider/API-
+ key setup without disabling and re-enabling the toolset.
"""
for platform in PLATFORMS:
if not _toolset_allowed_for_platform(ts_key, platform):
@@ -5310,316 +4479,6 @@ def _toolset_enabled_for_reconfigure(ts_key: str, config: dict) -> bool:
return False
-def _configure_tool_category_for_reconfig(
- ts_key: str,
- cat: dict,
- config: dict,
- *,
- force_fresh: bool = True,
-):
- """Reconfigure a tool category - provider selection + API key update."""
- icon = cat.get("icon", "")
- name = cat["name"]
- providers = _visible_providers(cat, config, force_fresh=force_fresh)
- hidden_nous_message = _hidden_nous_gateway_message(
- cat,
- config,
- f"the Nous Subscription provider for {name}",
- force_fresh=force_fresh,
- )
-
- if len(providers) == 1:
- provider = providers[0]
- print()
- print(color(f" --- {icon} {name} ({provider['name']}) ---", Colors.CYAN))
- if hidden_nous_message:
- for line in hidden_nous_message.splitlines():
- _print_warning(f" {line}")
- _reconfigure_provider(provider, config, force_fresh=force_fresh)
- else:
- print()
- print(color(f" --- {icon} {name} - Choose a provider ---", Colors.CYAN))
- if hidden_nous_message:
- for line in hidden_nous_message.splitlines():
- _print_warning(f" {line}")
- print()
-
- provider_choices = []
- for p in providers:
- badge = f" [{p['badge']}]" if p.get("badge") else ""
- tag = f" — {p['tag']}" if p.get("tag") else ""
- configured = ""
- env_vars = p.get("env_vars", [])
- if not env_vars or all(get_env_value(v["key"]) for v in env_vars):
- if _is_provider_active(p, config, force_fresh=force_fresh):
- configured = " [active]"
- elif not env_vars:
- configured = ""
- else:
- configured = " [configured]"
- provider_choices.append(f"{p['name']}{badge}{tag}{configured}")
-
- default_idx = _detect_active_provider_index(
- providers,
- config,
- force_fresh=force_fresh,
- )
-
- provider_idx = _prompt_choice(" Select provider:", provider_choices, default_idx)
- _reconfigure_provider(
- providers[provider_idx],
- config,
- force_fresh=force_fresh,
- )
-
-
-def _reconfigure_provider(
- provider: dict,
- config: dict,
- *,
- force_fresh: bool = True,
-):
- """Reconfigure a provider - update API keys."""
- env_vars = provider.get("env_vars", [])
- managed_feature = provider.get("managed_nous_feature")
-
- # Same inline Nous Portal login + entitlement gate as _configure_provider:
- # managed Tool Gateway backends only activate with paid Portal access.
- if managed_feature:
- from hermes_cli.nous_subscription import (
- MANAGED_FEATURE_COVERAGE_CATEGORY,
- ensure_nous_portal_access,
- )
-
- if not ensure_nous_portal_access(
- capability=f"{provider.get('name', 'the Nous Tool Gateway')}",
- coverage_category=MANAGED_FEATURE_COVERAGE_CATEGORY.get(managed_feature),
- ):
- _print_warning(
- " Not enabled — Nous Portal access is required for this backend."
- )
- return
-
- # Pure pre-auth UX rows keep the old gate; managed rows already handled
- # by the inline login above.
- if provider.get("requires_nous_auth") and not managed_feature:
- features = get_nous_subscription_features(config, force_fresh=force_fresh)
- entitled = bool(
- features.account_info and features.account_info.paid_service_access is True
- )
- if not features.nous_auth_present or not entitled:
- message = format_nous_portal_entitlement_message(
- features.account_info,
- capability=f"{provider.get('name', 'Nous Subscription')}",
- )
- _print_warning(
- f" {message or 'Nous Subscription is only available after logging into Nous Portal.'}"
- )
- return
-
- # Selection model (mirrors _write_provider_config): every row writes ONE
- # provider string per category — "nous" for managed rows, the vendor name
- # for BYOK rows — and drops any legacy use_gateway key so the read-time
- # shim (use_gateway: true ⇒ nous) cannot override the fresh pick.
- if provider.get("tts_provider"):
- tts_cfg = config.setdefault("tts", {})
- tts_cfg["provider"] = (
- NOUS_MANAGED_PROVIDER if managed_feature else provider["tts_provider"]
- )
- tts_cfg.pop("use_gateway", None)
- _print_success(f" TTS provider set to: {provider['tts_provider']}")
-
- if provider.get("stt_provider"):
- stt_cfg = config.setdefault("stt", {})
- stt_cfg["provider"] = (
- NOUS_MANAGED_PROVIDER if managed_feature else provider["stt_provider"]
- )
- stt_cfg.pop("use_gateway", None)
- _print_success(f" STT provider set to: {provider['stt_provider']}")
-
- if "browser_provider" in provider:
- bp = provider["browser_provider"]
- browser_cfg = config.setdefault("browser", {})
- if managed_feature:
- browser_cfg["cloud_provider"] = NOUS_MANAGED_PROVIDER
- _print_success(f" Browser cloud provider set to: {bp or 'nous'}")
- elif bp == "local":
- browser_cfg["cloud_provider"] = "local"
- _print_success(" Browser set to local mode")
- elif bp:
- browser_cfg["cloud_provider"] = bp
- _print_success(f" Browser cloud provider set to: {bp}")
- # Browser Use mode (browser.backend) composes with the provider —
- # switching providers keeps the driver choice intact.
- browser_cfg.pop("use_gateway", None)
-
- if provider.get("browser_backend"):
- browser_cfg = config.setdefault("browser", {})
- browser_cfg["backend"] = provider["browser_backend"]
- _print_success(" Browser set to Browser Use (browser_exec via CLI 3.0)")
-
- if provider.get("browser_engine"):
- browser_cfg = config.setdefault("browser", {})
- browser_cfg["engine"] = provider["browser_engine"]
- if provider["browser_engine"] != "auto":
- _print_success(f" Browser engine set to: {provider['browser_engine']}")
-
- # Set web search backend in config if applicable
- if provider.get("web_backend"):
- web_cfg = config.setdefault("web", {})
- web_cfg["backend"] = (
- NOUS_MANAGED_PROVIDER if managed_feature else provider["web_backend"]
- )
- web_cfg.pop("use_gateway", None)
- if provider.get("web_tier"):
- tiers = web_cfg.setdefault("provider_tier", {})
- if isinstance(tiers, dict):
- tiers[provider["web_backend"]] = provider["web_tier"]
- _print_success(
- f" Web backend set to: {provider['web_backend']} "
- f"({provider['web_tier']} tier)"
- )
- else:
- stale_tiers = web_cfg.get("provider_tier")
- if isinstance(stale_tiers, dict):
- stale_tiers.pop(provider["web_backend"], None)
- _print_success(f" Web backend set to: {provider['web_backend']}")
-
- # Set computer_use backend in config if applicable
- if provider.get("computer_use_backend"):
- cu_cfg = config.setdefault("computer_use", {})
- cu_cfg["backend"] = provider["computer_use_backend"]
- _print_success(f" Computer Use backend set to: {provider['computer_use_backend']}")
-
- if managed_feature and managed_feature not in {"web", "tts", "stt", "browser"}:
- section = config.setdefault(managed_feature, {})
- if not isinstance(section, dict):
- section = {}
- config[managed_feature] = section
- section["provider"] = NOUS_MANAGED_PROVIDER
- section.pop("use_gateway", None)
- elif not managed_feature:
- for cat_key, cat in TOOL_CATEGORIES.items():
- if provider in cat.get("providers", []):
- section = config.get(cat_key)
- if isinstance(section, dict):
- section.pop("use_gateway", None)
- break
-
- if not env_vars:
- if provider.get("post_setup"):
- _run_post_setup(provider["post_setup"])
- _print_success(f" {provider['name']} - no configuration needed!")
- if managed_feature:
- _print_info(" Requests for this tool will be billed to your Nous subscription.")
- plugin_name = provider.get("image_gen_plugin_name")
- if plugin_name:
- _select_plugin_image_gen_provider(plugin_name, config, use_gateway=bool(managed_feature))
- return
- # Plugin-registered video_gen provider — same flow, different registry.
- video_plugin = provider.get("video_gen_plugin_name")
- if video_plugin:
- _select_plugin_video_gen_provider(video_plugin, config, use_gateway=bool(managed_feature))
- return
- # Imagegen backends prompt for model selection on reconfig too.
- backend = provider.get("imagegen_backend")
- if backend:
- _configure_imagegen_model(backend, config)
- if backend == "fal":
- img_cfg = config.setdefault("image_gen", {})
- if isinstance(img_cfg, dict):
- # A managed (Nous Subscription) row also carries
- # imagegen_backend="fal" — store the "nous" selection
- # for it, "fal" for BYOK, and drop any legacy
- # use_gateway key.
- img_cfg["provider"] = (
- NOUS_MANAGED_PROVIDER if managed_feature else "fal"
- )
- img_cfg.pop("use_gateway", None)
- # STT providers prompt for model selection on reconfig too.
- if provider.get("stt_provider") and not managed_feature:
- _configure_stt_model(provider["stt_provider"], config)
- return
-
- for var in env_vars:
- existing = get_env_value(var["key"])
- if existing:
- _print_info(f" {var['key']}: configured ({existing[:8]}...)")
- url = var.get("url", "")
- if url:
- _print_info(f" Get yours at: {url}")
- default_val = var.get("default", "")
- value = _prompt(f" {var.get('prompt', var['key'])} (Enter to keep current)", password=not default_val)
- if value and value.strip():
- save_env_value(var["key"], value.strip())
- _print_success(" Updated")
- else:
- _print_info(" Kept current")
-
- if provider.get("post_setup"):
- _run_post_setup(provider["post_setup"])
-
- # Imagegen backends prompt for model selection on reconfig too.
- plugin_name = provider.get("image_gen_plugin_name")
- if plugin_name:
- _select_plugin_image_gen_provider(plugin_name, config, use_gateway=bool(managed_feature))
- return
-
- # Plugin-registered video_gen provider — same flow, different registry.
- video_plugin = provider.get("video_gen_plugin_name")
- if video_plugin:
- _select_plugin_video_gen_provider(video_plugin, config, use_gateway=bool(managed_feature))
- return
-
- backend = provider.get("imagegen_backend")
- if backend:
- _configure_imagegen_model(backend, config)
- if backend == "fal":
- img_cfg = config.setdefault("image_gen", {})
- if isinstance(img_cfg, dict):
- # Same managed-row guard as the no-env-vars branch above:
- # never clobber a Nous-managed pick back onto direct keys.
- img_cfg["provider"] = (
- NOUS_MANAGED_PROVIDER if managed_feature else "fal"
- )
- img_cfg.pop("use_gateway", None)
-
- # STT providers prompt for model selection on reconfig too.
- if provider.get("stt_provider") and not managed_feature:
- _configure_stt_model(provider["stt_provider"], config)
-
-
-def _reconfigure_simple_requirements(ts_key: str):
- """Reconfigure simple env var requirements."""
- if ts_key == "vision":
- # Vision has its own provider/model picker (any provider, like
- # `hermes model`). Run it directly so reconfigure doesn't fall back to
- # the generic single-key prompt (which would re-ask for OPENROUTER_API_KEY).
- _configure_vision_backend()
- return
-
- requirements = TOOLSET_ENV_REQUIREMENTS.get(ts_key, [])
- if not requirements:
- return
-
- ts_label = next((l for k, l, _ in _get_effective_configurable_toolsets() if k == ts_key), ts_key)
- print()
- print(color(f" {ts_label}:", Colors.CYAN))
-
- for var, url in requirements:
- existing = get_env_value(var)
- if existing:
- _print_info(f" {var}: configured ({existing[:8]}...)")
- if url:
- _print_info(f" Get key at: {url}")
- value = _prompt(f" {var} (Enter to keep current)", password=True)
- if value and value.strip():
- save_env_value(var, value.strip())
- _print_success(" Updated")
- else:
- _print_info(" Kept current")
-
-
# ─── Main Entry Point ─────────────────────────────────────────────────────────
def _shared_metrics_state(config: dict) -> tuple[bool, bool]:
@@ -5646,9 +4505,8 @@ def _shared_metrics_menu_label(config: dict) -> str:
def _configure_shared_metrics_interactive(config: dict) -> None:
"""Toggle shared-metrics collection and sending from `hermes tools`.
- Delegates to the setup wizard's prompt so the consent rules live in one
- place: sending requires collection, and turning collection off also turns
- sending off.
+ Delegates to the setup wizard's prompt so the consent rules live in one place: sending requires
+ collection, and disabling collection also disables sending.
"""
from hermes_cli.setup import setup_telemetry
@@ -5659,16 +4517,48 @@ def _configure_shared_metrics_interactive(config: dict) -> None:
save_config(config)
+def _print_toolset_diff(added: Set[str], removed: Set[str], *, indent: str = " ") -> None:
+ """Print ``+ label`` / ``- label`` lines for a checklist change."""
+ for ts in sorted(added):
+ print(color(f"{indent}+ {_toolset_label(ts)}", Colors.GREEN))
+ for ts in sorted(removed):
+ print(color(f"{indent}- {_toolset_label(ts)}", Colors.RED))
+
+
+def _toolsets_needing_setup(new_enabled: Set[str], config: dict) -> List[str]:
+ """Selected toolsets still missing provider/API-key setup, in sorted order.
+
+ These must open configuration even when the checklist selection itself didn't change (e.g. Web
+ Search already enabled but ``web.backend`` missing).
+ """
+ return [
+ ts_key for ts_key in sorted(new_enabled)
+ if _is_configurable(ts_key)
+ and _toolset_needs_configuration_prompt(ts_key, config, force_fresh=True)
+ ]
+
+
+def _configure_newly_added(added: Set[str], already: Set[str], config: dict) -> None:
+ """Configure newly enabled toolsets that need keys, skipping those already handled."""
+ for ts_key in sorted(added - already):
+ if _is_configurable(ts_key) and _toolset_needs_configuration_prompt(
+ ts_key, config, force_fresh=True,
+ ):
+ _configure_toolset(ts_key, config)
+
+
+def _platform_menu_label(config: dict, pkey: str) -> str:
+ count = len(_get_platform_tools(config, pkey, include_default_mcp_servers=False))
+ total = len(_get_effective_configurable_toolsets())
+ return f"Configure {PLATFORMS[pkey]['label']} ({count}/{total} enabled)"
+
+
def tools_command(args=None, first_install: bool = False, config: dict = None):
"""Entry point for `hermes tools` and `hermes setup tools`.
- Args:
- first_install: When True (set by the setup wizard on fresh installs),
- skip the platform menu, go straight to the CLI checklist, and
- prompt for API keys on all enabled tools that need them.
- config: Optional config dict to use. When called from the setup
- wizard, the wizard passes its own dict so that platform_toolsets
- are written into it and survive the wizard's final save_config().
+ ``first_install`` (fresh installs) skips the platform menu, goes straight to the CLI checklist
+ and prompts for API keys on enabled tools. When the wizard passes its own ``config`` dict,
+ platform_toolsets are written into it so they survive the wizard's final save_config().
"""
if config is None:
config = load_config()
@@ -5689,8 +4579,7 @@ def tools_command(args=None, first_install: bool = False, config: dict = None):
print(color(f" {pinfo['label']}", Colors.BOLD) + color(f" ({count}/{total})", Colors.DIM))
if enabled:
for ts_key in sorted(enabled):
- label = next((l for k, l, _ in _get_effective_configurable_toolsets() if k == ts_key), ts_key)
- print(color(f" ✓ {label}", Colors.GREEN))
+ print(color(f" ✓ {_toolset_label(ts_key)}", Colors.GREEN))
else:
print(color(" (none enabled)", Colors.DIM))
print()
@@ -5701,6 +4590,19 @@ def tools_command(args=None, first_install: bool = False, config: dict = None):
print(color(" Guide: https://hermes-agent.nousresearch.com/docs/user-guide/features/tools", Colors.DIM))
print()
+ def _configure_list(to_configure, *, selected=True):
+ if not to_configure:
+ return
+ print()
+ what = "selected tool(s)" if selected else "tool(s)"
+ print(color(f" Configuring {len(to_configure)} {what}:", Colors.YELLOW))
+ for ts_key in to_configure:
+ print(color(f" • {_toolset_label(ts_key)}", Colors.DIM))
+ print(color(" You can skip any tool you don't need right now.", Colors.DIM))
+ print()
+ for ts_key in to_configure:
+ _configure_toolset(ts_key, config)
+
# ── First-time install: linear flow, no platform menu ──
if first_install:
for pkey in enabled_platforms:
@@ -5720,16 +4622,10 @@ def tools_command(args=None, first_install: bool = False, config: dict = None):
# print spurious ``- kanban`` removals even though the config keeps
# them. See _checklist_toolset_keys.
_diff_universe = _checklist_toolset_keys(pkey)
- added = (new_enabled - current_enabled) & _diff_universe
- removed = (current_enabled - new_enabled) & _diff_universe
- if added:
- for ts in sorted(added):
- label = next((l for k, l, _ in _get_effective_configurable_toolsets() if k == ts), ts)
- print(color(f" + {label}", Colors.GREEN))
- if removed:
- for ts in sorted(removed):
- label = next((l for k, l, _ in _get_effective_configurable_toolsets() if k == ts), ts)
- print(color(f" - {label}", Colors.RED))
+ _print_toolset_diff(
+ (new_enabled - current_enabled) & _diff_universe,
+ (current_enabled - new_enabled) & _diff_universe,
+ )
auto_configured = apply_nous_managed_defaults(
config,
@@ -5744,22 +4640,13 @@ def tools_command(args=None, first_install: bool = False, config: dict = None):
# need API keys. This ensures browser (Local vs Browserbase),
# TTS (Edge vs OpenAI vs ElevenLabs), etc. are shown even when
# a free provider exists.
- to_configure = [
- ts_key for ts_key in sorted(new_enabled)
- if (TOOL_CATEGORIES.get(ts_key) or TOOLSET_ENV_REQUIREMENTS.get(ts_key))
- and ts_key not in auto_configured
- ]
-
- if to_configure:
- print()
- print(color(f" Configuring {len(to_configure)} tool(s):", Colors.YELLOW))
- for ts_key in to_configure:
- label = next((l for k, l, _ in _get_effective_configurable_toolsets() if k == ts_key), ts_key)
- print(color(f" • {label}", Colors.DIM))
- print(color(" You can skip any tool you don't need right now.", Colors.DIM))
- print()
- for ts_key in to_configure:
- _configure_toolset(ts_key, config)
+ _configure_list(
+ [
+ ts_key for ts_key in sorted(new_enabled)
+ if _is_configurable(ts_key) and ts_key not in auto_configured
+ ],
+ selected=False,
+ )
_save_platform_tools(config, pkey, new_enabled)
save_config(config)
@@ -5769,16 +4656,8 @@ def tools_command(args=None, first_install: bool = False, config: dict = None):
return
# ── Returning user: platform menu loop ──
- # Build platform choices
- platform_choices = []
- platform_keys = []
- for pkey in enabled_platforms:
- pinfo = PLATFORMS[pkey]
- current = _get_platform_tools(config, pkey, include_default_mcp_servers=False)
- count = len(current)
- total = len(_get_effective_configurable_toolsets())
- platform_choices.append(f"Configure {pinfo['label']} ({count}/{total} enabled)")
- platform_keys.append(pkey)
+ platform_keys = list(enabled_platforms)
+ platform_choices = [_platform_menu_label(config, pkey) for pkey in platform_keys]
if len(platform_keys) > 1:
platform_choices.append("Configure all platforms (global)")
@@ -5802,30 +4681,25 @@ def tools_command(args=None, first_install: bool = False, config: dict = None):
while True:
idx = _prompt_choice("Select an option:", platform_choices, default=0)
- # "Done" selected
if idx == _done_idx:
break
- # "Reconfigure" selected
if idx == _reconfig_idx:
_reconfigure_tool(config, force_fresh=True)
print()
continue
- # "Shared metrics" selected
if idx == _metrics_idx:
_configure_shared_metrics_interactive(config)
platform_choices[_metrics_idx] = _shared_metrics_menu_label(config)
print()
continue
- # "Configure MCP tools" selected
if idx == _mcp_idx:
_configure_mcp_tools_interactive(config)
print()
continue
- # "Configure all platforms (global)" selected
if idx == _global_idx:
# Use the union of all platforms' current tools as the starting state
all_current = set()
@@ -5836,28 +4710,8 @@ def tools_command(args=None, first_install: bool = False, config: dict = None):
all_current,
force_fresh=True,
)
- selected_to_configure = [
- ts_key for ts_key in sorted(new_enabled)
- if (TOOL_CATEGORIES.get(ts_key) or TOOLSET_ENV_REQUIREMENTS.get(ts_key))
- and _toolset_needs_configuration_prompt(
- ts_key,
- config,
- force_fresh=True,
- )
- ]
-
- selected_to_configure_set = set(selected_to_configure)
-
- if selected_to_configure:
- print()
- print(color(f" Configuring {len(selected_to_configure)} selected tool(s):", Colors.YELLOW))
- for ts_key in selected_to_configure:
- label = next((l for k, l, _ in _get_effective_configurable_toolsets() if k == ts_key), ts_key)
- print(color(f" • {label}", Colors.DIM))
- print(color(" You can skip any tool you don't need right now.", Colors.DIM))
- print()
- for ts_key in selected_to_configure:
- _configure_toolset(ts_key, config)
+ selected_to_configure = _toolsets_needing_setup(new_enabled, config)
+ _configure_list(selected_to_configure)
if new_enabled != all_current or selected_to_configure:
for pk in platform_keys:
@@ -5868,37 +4722,20 @@ def tools_command(args=None, first_install: bool = False, config: dict = None):
_diff_universe = _checklist_toolset_keys(pk)
added = (new_enabled - prev) & _diff_universe
removed = (prev - new_enabled) & _diff_universe
- pinfo_inner = PLATFORMS[pk]
if added or removed:
- print(color(f" {pinfo_inner['label']}:", Colors.DIM))
- for ts in sorted(added):
- label = next((l for k, l, _ in _get_effective_configurable_toolsets() if k == ts), ts)
- print(color(f" + {label}", Colors.GREEN))
- for ts in sorted(removed):
- label = next((l for k, l, _ in _get_effective_configurable_toolsets() if k == ts), ts)
- print(color(f" - {label}", Colors.RED))
+ print(color(f" {PLATFORMS[pk]['label']}:", Colors.DIM))
+ _print_toolset_diff(added, removed, indent=" ")
# Configure API keys for newly enabled tools not already
- # handled by the global selected-tool pass above. This
- # preserves the old per-platform enable flow but avoids
- # dropping users back to the main menu when a selected tool
- # was already enabled globally and only lacked provider
- # configuration.
- for ts_key in sorted(added - selected_to_configure_set):
- if (TOOL_CATEGORIES.get(ts_key) or TOOLSET_ENV_REQUIREMENTS.get(ts_key)):
- if _toolset_needs_configuration_prompt(
- ts_key,
- config,
- force_fresh=True,
- ):
- _configure_toolset(ts_key, config)
+ # handled by the global selected-tool pass above, so a
+ # tool that was already enabled globally but lacked
+ # provider configuration doesn't drop the user back to the
+ # main menu.
+ _configure_newly_added(added, set(selected_to_configure), config)
_save_platform_tools(config, pk, new_enabled)
save_config(config)
print(color(" ✓ Saved configuration for all platforms", Colors.GREEN))
- # Update choice labels
for ci, pk in enumerate(platform_keys):
- new_count = len(_get_platform_tools(config, pk, include_default_mcp_servers=False))
- total = len(_get_effective_configurable_toolsets())
- platform_choices[ci] = f"Configure {PLATFORMS[pk]['label']} ({new_count}/{total} enabled)"
+ platform_choices[ci] = _platform_menu_label(config, pk)
else:
print(color(" No changes", Colors.DIM))
print()
@@ -5907,70 +4744,22 @@ def tools_command(args=None, first_install: bool = False, config: dict = None):
pkey = platform_keys[idx]
pinfo = PLATFORMS[pkey]
- # Get current enabled toolsets for this platform
current_enabled = _get_platform_tools(config, pkey, include_default_mcp_servers=False)
-
- # Show checklist
new_enabled = _prompt_toolset_checklist(
pinfo["label"],
current_enabled,
force_fresh=True,
)
- # Selected toolsets still missing provider/API-key setup must open
- # configuration even when the checklist selection itself didn't
- # change (e.g. Web Search already enabled but web.backend missing).
- # Mirrors the "Configure all platforms (global)" flow above.
- selected_to_configure = [
- ts_key for ts_key in sorted(new_enabled)
- if (TOOL_CATEGORIES.get(ts_key) or TOOLSET_ENV_REQUIREMENTS.get(ts_key))
- and _toolset_needs_configuration_prompt(
- ts_key,
- config,
- force_fresh=True,
- )
- ]
-
- selected_to_configure_set = set(selected_to_configure)
-
- if selected_to_configure:
- print()
- print(color(f" Configuring {len(selected_to_configure)} selected tool(s):", Colors.YELLOW))
- for ts_key in selected_to_configure:
- label = next((l for k, l, _ in _get_effective_configurable_toolsets() if k == ts_key), ts_key)
- print(color(f" • {label}", Colors.DIM))
- print(color(" You can skip any tool you don't need right now.", Colors.DIM))
- print()
- for ts_key in selected_to_configure:
- _configure_toolset(ts_key, config)
+ selected_to_configure = _toolsets_needing_setup(new_enabled, config)
+ _configure_list(selected_to_configure)
if new_enabled != current_enabled or selected_to_configure:
- # Scope the printed diff to the checklist's universe (see
- # _checklist_toolset_keys) so non-configurable toolsets like
- # ``kanban`` aren't reported as added/removed.
_diff_universe = _checklist_toolset_keys(pkey)
added = (new_enabled - current_enabled) & _diff_universe
removed = (current_enabled - new_enabled) & _diff_universe
-
- if added:
- for ts in sorted(added):
- label = next((l for k, l, _ in _get_effective_configurable_toolsets() if k == ts), ts)
- print(color(f" + {label}", Colors.GREEN))
- if removed:
- for ts in sorted(removed):
- label = next((l for k, l, _ in _get_effective_configurable_toolsets() if k == ts), ts)
- print(color(f" - {label}", Colors.RED))
-
- # Configure newly enabled toolsets that need API keys, skipping
- # any already handled by the selected-tool pass above.
- for ts_key in sorted(added - selected_to_configure_set):
- if (TOOL_CATEGORIES.get(ts_key) or TOOLSET_ENV_REQUIREMENTS.get(ts_key)):
- if _toolset_needs_configuration_prompt(
- ts_key,
- config,
- force_fresh=True,
- ):
- _configure_toolset(ts_key, config)
+ _print_toolset_diff(added, removed)
+ _configure_newly_added(added, set(selected_to_configure), config)
_save_platform_tools(config, pkey, new_enabled)
save_config(config)
@@ -5979,11 +4768,7 @@ def tools_command(args=None, first_install: bool = False, config: dict = None):
print(color(f" No changes to {pinfo['label']}", Colors.DIM))
print()
-
- # Update the choice label with new count
- new_count = len(_get_platform_tools(config, pkey, include_default_mcp_servers=False))
- total = len(_get_effective_configurable_toolsets())
- platform_choices[idx] = f"Configure {pinfo['label']} ({new_count}/{total} enabled)"
+ platform_choices[idx] = _platform_menu_label(config, pkey)
print()
from hermes_constants import display_hermes_home
@@ -5995,12 +4780,84 @@ def tools_command(args=None, first_install: bool = False, config: dict = None):
# ─── MCP Tools Interactive Configuration ─────────────────────────────────────
+def _mcp_match_filter():
+ """Runtime name-filter matcher (exact names or fnmatch globs), with a literal fallback.
+
+ Must use the SAME semantics as tools/mcp_tool.py registration — a literal ``in`` check renders
+ glob excludes (e.g. ``*team_member*`` from catalog default_excluded manifests) as if nothing
+ were excluded.
+ """
+ try:
+ from tools.mcp_tool import matches_name_filter
+
+ return matches_name_filter
+ except ImportError: # pragma: no cover — defensive fallback
+ return lambda tool_name, patterns: tool_name in patterns
+
+
+def _mcp_preselected(tool_names: List[str], include_set, exclude_set, match) -> Set[int]:
+ """Indices of tools currently enabled: include mode, exclude mode, or all when unfiltered."""
+ if include_set:
+ return {i for i, tn in enumerate(tool_names) if match(tn, include_set)}
+ if exclude_set:
+ return {i for i, tn in enumerate(tool_names) if not match(tn, exclude_set)}
+ return set(range(len(tool_names)))
+
+
+def _apply_mcp_checklist(server_name: str, tools_cfg: dict, tool_names: List[str], chosen: Set[int],
+ include_set, exclude_set, match) -> None:
+ """Write a checklist result back as ``tools.include`` / ``tools.exclude``."""
+ exclude_mode = bool(exclude_set) and not include_set
+
+ if len(chosen) == len(tool_names) and not exclude_mode:
+ # All tools enabled — clear filters (cleanest config shape; the
+ # server's native tool set is the active set, and any tools the
+ # server adds later are auto-enabled).
+ tools_cfg.pop("exclude", None)
+ tools_cfg.pop("include", None)
+ elif exclude_mode:
+ # Exclude-mode server (catalog default_excluded / hand-written
+ # tools.exclude): stay in exclude mode — do NOT demote the
+ # dynamic filter to a frozen include list. Unchecked tools are
+ # added as literal excludes; re-checked literals are dropped;
+ # glob patterns are preserved (they intentionally keep matching
+ # tools the vendor ships later).
+ old_exclude = sorted(exclude_set or set())
+ glob_entries = [p for p in old_exclude if "*" in p or "?" in p or "[" in p]
+ literal_entries = {p for p in old_exclude if p not in glob_entries}
+ unchecked = {tn for i, tn in enumerate(tool_names) if i not in chosen}
+ checked = {tool_names[i] for i in chosen}
+ new_literals = (literal_entries - checked) | {
+ tn for tn in unchecked if not match(tn, set(old_exclude))
+ }
+ new_exclude = glob_entries + sorted(new_literals)
+ glob_shadowed = sorted(
+ tn for tn in checked if glob_entries and match(tn, set(glob_entries))
+ )
+ if glob_shadowed:
+ _print_warning(
+ f" {server_name}: {len(glob_shadowed)} re-enabled "
+ f"tool(s) still match glob exclude pattern(s) "
+ f"{glob_entries} and stay excluded — edit "
+ f"mcp_servers.{server_name}.tools.exclude in config.yaml "
+ "to enable them."
+ )
+ if new_exclude:
+ tools_cfg["exclude"] = new_exclude
+ else:
+ tools_cfg.pop("exclude", None)
+ tools_cfg.pop("include", None)
+ else:
+ tools_cfg["include"] = [tool_names[i] for i in sorted(chosen)]
+ # Drop any legacy exclude block — we're include-mode now.
+ tools_cfg.pop("exclude", None)
+
+
def _configure_mcp_tools_interactive(config: dict):
"""Probe MCP servers for available tools and let user toggle them on/off.
- Connects to each configured MCP server, discovers tools, then shows
- a per-server curses checklist. Writes changes back as ``tools.exclude``
- entries in config.yaml.
+ Connects to each server, discovers tools, shows a per-server curses checklist, and writes the
+ result back as ``tools.exclude`` entries in config.yaml.
"""
from hermes_cli.curses_ui import curses_checklist
@@ -6009,7 +4866,6 @@ def _configure_mcp_tools_interactive(config: dict):
_print_info("No MCP servers configured.")
return
- # Count enabled servers
enabled_names = [
k for k, v in mcp_servers.items()
if v.get("enabled", True) not in {False, "false", "0", "no", "off"}
@@ -6034,10 +4890,8 @@ def _configure_mcp_tools_interactive(config: dict):
_print_info("Check that server commands/URLs are correct and dependencies are installed.")
return
- # Report discovery results
- failed = [n for n in enabled_names if n not in server_tools]
- if failed:
- for name in failed:
+ for name in enabled_names:
+ if name not in server_tools:
_print_warning(f" Could not connect to '{name}'")
total_tools = sum(len(tools) for tools in server_tools.values())
@@ -6045,53 +4899,25 @@ def _configure_mcp_tools_interactive(config: dict):
print()
any_changes = False
-
for server_name, tools in server_tools.items():
if not tools:
_print_info(f" {server_name}: no tools found")
continue
- srv_cfg = mcp_servers.get(server_name, {})
- tools_cfg = srv_cfg.get("tools") or {}
+ tools_cfg = mcp_servers.get(server_name, {}).get("tools") or {}
include_list = tools_cfg.get("include") or []
exclude_list = tools_cfg.get("exclude") or []
- # Build checklist labels
labels = []
for tool_name, description in tools:
desc_short = description[:70] + "..." if len(description) > 70 else description
- if desc_short:
- labels.append(f"{tool_name} ({desc_short})")
- else:
- labels.append(tool_name)
-
- # Determine which tools are currently enabled. Use the SAME matching
- # semantics as runtime registration (tools/mcp_tool.py): exact names
- # or fnmatch globs — a literal `in` check renders glob excludes
- # (e.g. "*team_member*" from catalog default_excluded manifests) as
- # if nothing were excluded.
- try:
- from tools.mcp_tool import matches_name_filter as _match_filter
- except ImportError: # pragma: no cover — defensive fallback
- def _match_filter(tool_name, patterns):
- return tool_name in patterns
+ labels.append(f"{tool_name} ({desc_short})" if desc_short else tool_name)
- pre_selected: Set[int] = set()
+ match = _mcp_match_filter()
tool_names = [t[0] for t in tools]
include_set = {str(p) for p in include_list} if include_list else None
exclude_set = {str(p) for p in exclude_list} if exclude_list else None
- for i, tool_name in enumerate(tool_names):
- if include_set:
- # Include mode: only included tools are selected
- if _match_filter(tool_name, include_set):
- pre_selected.add(i)
- elif exclude_set:
- # Exclude mode: everything except excluded
- if not _match_filter(tool_name, exclude_set):
- pre_selected.add(i)
- else:
- # No filter: all enabled
- pre_selected.add(i)
+ pre_selected = _mcp_preselected(tool_names, include_set, exclude_set, match)
chosen = curses_checklist(
f"MCP Server: {server_name} ({len(tools)} tools)",
@@ -6104,65 +4930,11 @@ def _configure_mcp_tools_interactive(config: dict):
_print_info(f" {server_name}: no changes")
continue
- # Update config
- srv_cfg = mcp_servers.setdefault(server_name, {})
- tools_cfg = srv_cfg.setdefault("tools", {})
-
- exclude_mode = bool(exclude_set) and not include_set
-
- if len(chosen) == len(tools) and not exclude_mode:
- # All tools enabled — clear filters (cleanest config shape; the
- # server\'s native tool set is the active set, and any tools the
- # server adds later are auto-enabled).
- tools_cfg.pop("exclude", None)
- tools_cfg.pop("include", None)
- elif exclude_mode:
- # Exclude-mode server (catalog default_excluded / hand-written
- # tools.exclude): stay in exclude mode — do NOT demote the
- # dynamic filter to a frozen include list. Unchecked tools are
- # added as literal excludes; re-checked literals are dropped;
- # glob patterns are preserved (they intentionally keep matching
- # tools the vendor ships later).
- old_exclude = sorted(exclude_set or set())
- glob_entries = [p for p in old_exclude
- if "*" in p or "?" in p or "[" in p]
- literal_entries = {p for p in old_exclude if p not in glob_entries}
- unchecked = {tool_names[i] for i in range(len(tools))
- if i not in chosen}
- checked = {tool_names[i] for i in chosen}
- new_literals = (literal_entries - checked) | {
- tn for tn in unchecked
- if not _match_filter(tn, set(old_exclude))
- }
- new_exclude = glob_entries + sorted(new_literals)
- glob_shadowed = sorted(
- tn for tn in checked
- if glob_entries and _match_filter(tn, set(glob_entries))
- )
- if glob_shadowed:
- _print_warning(
- f" {server_name}: {len(glob_shadowed)} re-enabled "
- f"tool(s) still match glob exclude pattern(s) "
- f"{glob_entries} and stay excluded — edit "
- f"mcp_servers.{server_name}.tools.exclude in config.yaml "
- "to enable them."
- )
- if not new_exclude:
- tools_cfg.pop("exclude", None)
- tools_cfg.pop("include", None)
- else:
- tools_cfg["exclude"] = new_exclude
- tools_cfg.pop("include", None)
- else:
- chosen_names = [tool_names[i] for i in sorted(chosen)]
- tools_cfg["include"] = chosen_names
- # Drop any legacy exclude block — we\'re include-mode now.
- tools_cfg.pop("exclude", None)
+ tools_cfg = mcp_servers.setdefault(server_name, {}).setdefault("tools", {})
+ _apply_mcp_checklist(server_name, tools_cfg, tool_names, chosen, include_set, exclude_set, match)
- enabled_count = len(chosen)
- disabled_count = len(tools) - enabled_count
_print_success(
- f" {server_name}: {enabled_count} enabled, {disabled_count} disabled"
+ f" {server_name}: {len(chosen)} enabled, {len(tools) - len(chosen)} disabled"
)
any_changes = True
@@ -6188,10 +4960,7 @@ def _apply_toolset_change(config: dict, platform: str, toolset_names: List[str],
def _apply_mcp_change(config: dict, targets: List[str], action: str) -> Set[str]:
- """Add or remove specific MCP tools from a server's exclude list.
-
- Returns the set of server names that were not found in config.
- """
+ """Add or remove specific MCP tools from a server's exclude list."""
failed_servers: Set[str] = set()
mcp_servers = config.get("mcp_servers") or {}
@@ -6221,23 +4990,20 @@ def _print_tools_list(enabled_toolsets: set, mcp_servers: dict, platform: str =
]
builtin_keys = {ts_key for ts_key, _, _ in CONFIGURABLE_TOOLSETS}
+ def _print_rows(entries):
+ for ts_key, label in entries:
+ status = (color("✓ enabled", Colors.GREEN) if ts_key in enabled_toolsets
+ else color("✗ disabled", Colors.RED))
+ print(f" {status} {ts_key} {color(label, Colors.DIM)}")
+
print(f"Built-in toolsets ({platform}):")
- for ts_key, label, _ in effective:
- if ts_key not in builtin_keys:
- continue
- status = (color("✓ enabled", Colors.GREEN) if ts_key in enabled_toolsets
- else color("✗ disabled", Colors.RED))
- print(f" {status} {ts_key} {color(label, Colors.DIM)}")
+ _print_rows((k, l) for k, l, _ in effective if k in builtin_keys)
- # Plugin toolsets
plugin_entries = [(k, l) for k, l, _ in effective if k not in builtin_keys]
if plugin_entries:
print()
print(f"Plugin toolsets ({platform}):")
- for ts_key, label in plugin_entries:
- status = (color("✓ enabled", Colors.GREEN) if ts_key in enabled_toolsets
- else color("✗ disabled", Colors.RED))
- print(f" {status} {ts_key} {color(label, Colors.DIM)}")
+ _print_rows(plugin_entries)
if mcp_servers:
print()
@@ -6257,9 +5023,9 @@ def _print_tools_list(enabled_toolsets: set, mcp_servers: dict, platform: str =
def _known_tool_platforms() -> set[str]:
"""Return built-in plus discovered plugin platform names.
- Plugin platforms are registered at runtime rather than in the static CLI
- display registry. Tool introspection/configuration must recognize those
- names too, otherwise an active plugin platform cannot audit its authority.
+ Plugin platforms are registered at runtime rather than in the static CLI display registry. Tool
+ introspection/configuration must recognize those names too, otherwise an active plugin platform
+ cannot audit its authority.
"""
known = set(PLATFORMS)
try:
@@ -6276,11 +5042,7 @@ def _known_tool_platforms() -> set[str]:
def tools_disable_enable_command(args):
- """Enable, disable, or list tools for a platform.
-
- Built-in toolsets use plain names (e.g. ``web``, ``memory``).
- MCP tools use ``server:tool`` notation (e.g. ``github:create_issue``).
- """
+ """Enable, disable, or list tools for a platform."""
action = args.tools_action
platform = getattr(args, "platform", "cli")
config = load_config()
diff --git a/hermes_cli/toolset_scope.py b/hermes_cli/toolset_scope.py
index 1085f3fcd4b..4bb107fba32 100644
--- a/hermes_cli/toolset_scope.py
+++ b/hermes_cli/toolset_scope.py
@@ -1,8 +1,4 @@
-"""Platform scope rules for configured toolsets.
-
-This module is intentionally independent of tool resolution and CLI setup so
-configuration validation and runtime resolution apply the same platform policy.
-"""
+"""Platform scope rules for configured toolsets."""
from typing import Set
diff --git a/hermes_cli/toolset_validation.py b/hermes_cli/toolset_validation.py
index e7a2b7cedde..ad34f3bacb2 100644
--- a/hermes_cli/toolset_validation.py
+++ b/hermes_cli/toolset_validation.py
@@ -1,22 +1,12 @@
-"""Validation for the ``platform_toolsets`` config section.
-
-Pure, side-effect-free helpers so the logic is unit-testable without importing
-the tool registry or launching Hermes (mirrors the decoupled-helper pattern used
-elsewhere in the CLI).
-
-Motivated by #38798: a config migration silently rewrote the valid toolset name
-``hermes-cli`` to the non-existent ``hermes``. ``resolve_toolset('hermes')``
-returns an empty list, so every tool silently disappeared with no error, warning,
-or log entry — the agent degraded to text-only replies and the cause took
-significant debugging to find. Surfacing invalid toolset names (and the
-zero-tools end state) loudly turns that silent failure into an actionable one.
-"""
+"""Validation for the ``platform_toolsets`` config section."""
from typing import Callable, List
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 _platform_default_toolset(platform: object) -> str:
info = PLATFORMS.get(platform)
@@ -29,9 +19,8 @@ def _platform_default_is_valid(
is_valid_toolset: Callable[[str], bool],
is_allowed_for_platform: Callable[[str, str], bool],
) -> bool:
- platform_name = str(platform)
if is_valid_toolset(default_toolset) and is_allowed_for_platform(
- default_toolset, platform_name
+ default_toolset, str(platform)
):
return True
# Dynamic plugin platforms are resolved by toolsets.resolve_toolset() even
@@ -51,34 +40,12 @@ def validate_platform_toolsets(
) -> List[str]:
"""Return human-readable warnings for a ``platform_toolsets`` mapping.
- The following failure modes are reported:
-
- 1. A toolset name that ``is_valid_toolset`` rejects — usually a corrupted or
- renamed entry. When ``hermes-<platform>`` would have been valid (the exact
- #38798 shape, where ``cli`` held ``hermes`` instead of ``hermes-cli``),
- the warning includes that as a suggestion.
- 2. The mapping is non-empty but resolves to *zero* valid toolsets, so the
- agent would start with no tools at all.
- 3. A platform is configured with no valid toolsets. Checked per-platform
- because the global zero-valid-toolsets net in (2) is suppressed as soon
- as any other platform carries a valid toolset. This includes empty
- lists and lists containing only invalid entries. Null values are also
- reported, but match the resolver's platform-default fallback.
- 4. A non-list platform value is malformed but matches the resolver's
- platform-default fallback rather than selecting a toolset by itself.
-
- ``is_valid_toolset`` is injected (normally :func:`toolsets.validate_toolset`)
- so this function performs no tool-registry imports or I/O and is testable in
- isolation. Platform default metadata comes from the shared platform registry.
-
- Args:
- platform_toolsets: The raw ``platform_toolsets`` value from config. Only
- ``dict`` values carry toolset entries; anything else yields no
- warnings (nothing to validate).
- is_valid_toolset: Predicate returning ``True`` for a known toolset name.
-
- Returns:
- A list of warning strings (empty when everything is valid).
+ 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:
@@ -86,17 +53,18 @@ def validate_platform_toolsets(
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
if not isinstance(raw, list):
- fallback = _platform_default_toolset(platform)
- if _platform_default_is_valid(
- platform, fallback, is_valid_toolset, is_allowed_for_platform
- ):
+ if default_valid:
valid_count += 1
platform_valid_count += 1
- fallback_detail = f"falling back to '{fallback}'"
+ fallback_detail = f"falling back to '{default}'"
else:
- fallback_detail = f"falling back to unknown default '{fallback}'"
+ fallback_detail = f"falling back to unknown default '{default}'"
if raw is None:
value_detail = "a null toolset value"
elif isinstance(raw, str):
@@ -108,53 +76,31 @@ def validate_platform_toolsets(
f"{fallback_detail}. Run `hermes tools` to configure explicitly."
)
if platform_valid_count == 0:
- warnings.append(
- f"platform '{platform}' has no valid toolsets configured — "
- f"the agent will have no tools on this platform. "
- f"Run `hermes tools` to reconfigure."
- )
+ warnings.append(f"platform '{platform}' has no valid toolsets configured — {_NO_TOOLS}")
continue
- names = raw
- for name in names:
+
+ for name in raw:
if not isinstance(name, str) or not name:
continue
- if is_valid_toolset(name) and is_allowed_for_platform(
- name, str(platform)
- ):
- valid_count += 1
- platform_valid_count += 1
- continue
if is_valid_toolset(name):
- warnings.append(
- f"platform '{platform}' references toolset '{name}' "
- "which is not available on this platform"
- )
+ if 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"
+ )
continue
- suggestion = _platform_default_toolset(platform)
- hint = (
- f" — did you mean '{suggestion}'?"
- if _platform_default_is_valid(
- platform,
- suggestion,
- is_valid_toolset,
- is_allowed_for_platform,
- )
- else ""
- )
+ hint = f" — did you mean '{default}'?" if default_valid else ""
warnings.append(
f"platform '{platform}' references unknown toolset "
f"'{name}'{hint}"
)
if platform_valid_count == 0:
- if isinstance(raw, list) and not raw:
- reason = "is configured with an empty toolset list"
- else:
- reason = "has no valid toolsets configured"
- warnings.append(
- f"platform '{platform}' {reason} — the agent will have no "
- f"tools on this platform. Run `hermes tools` to reconfigure."
- )
+ reason = "is configured with an empty toolset list" if not raw else "has no valid toolsets configured"
+ warnings.append(f"platform '{platform}' {reason} — {_NO_TOOLS}")
if valid_count == 0:
warnings.append(