Files
hermes-agent/hermes_cli/dump.py
Teknium 1cf261a8cd refactor(wecom): WeCom leaves core for the wecom Hermes Labs plugin
Both WeCom platforms (AI Bot `wecom`, self-built-app `wecom_callback`) move to
NousResearch/hermes-labs-plugins `wecom/`. Two LEFT_CORE rows (one per
platform, one shared plugin, installed once) whose platform_in_use predicates
replicate core's enable gates per mode. Stacked on the DingTalk removal
(#159638): the platform lists both PRs edit are resolved once here.

Folded from the earlier branch (one commit per step, in order):

  331094ca15a3 Teknium test(gateway): a named profile's port-binder is served only on a default listener, live reconcile too
  The live reconcile builds a named profile's platforms through the same prepare step as startup, so the
  "not served" refusal holds there as well: a LINE secondary with neither api_server nor webhook on the
  default stays unstarted and names the remedy instead of reading as connected. The two LINE named-profile
  reconcile tests now give the default a webhook listener, so their LINE is served at /p/b/ as in a real
  setup; their assertions are unchanged.

  bedc93176b93 Teknium fix(left-core): off-platforms derive from the LEFT_CORE rows; left-core routes name the install
  Same hunk as the QQ Bot (#159640) and Feishu (#159651) PRs, so merge order cannot leave a stale entry.

  - A row whose tools lived in its own hermes-<platform> bundle only (Yuanbao) sets own_platform_only;
    _derive_off_platforms fills off_platforms with every platform core knows plus every platform a
    LEFT_CORE row moved out. The hand list _YUANBAO_OFF_PLATFORMS (which this PR had extended with
    wecom/wecom_callback) is gone. The WeCom rows carry no toolsets (hermes-wecom and
    hermes-wecom-callback bundled core tools only), so they need no off-platforms.
  - Webhook routes: is_known_platform accepts any platform a LEFT_CORE row moved out, so a saved wecom or
    wecom_callback route stays loaded before a secondary profile's plugin registers; without the plugin
    the send fails naming the install.
  - Cron: a deliver route naming a left-core platform whose plugin is not loaded reports the install
    command (delivery error and preflight). tests/cron/test_cron_left_core_platform_route.py runs for
    wecom and wecom_callback.

  05d04a49ccc3 Teknium refactor(wecom): drop the one-install-per-home copy; the installer-race PR carries it generically

  296e4a152f99 Teknium fix(gateway): a secondary port-binder with no default listener is not served, not "connected"
  Under multiplex a secondary profile's port-binding adapter (WeCom callback, LINE, SMS, Teams, ...)
  binds nothing: its app is published for /p/<profile>/ on the default profile's api_server or
  webhook listener. With neither running on the default, connect() still returned True and the
  runner logged "✓ wecom_callback connected (profile: b)" while nothing listened anywhere.

  - Runner: such an adapter is not started; it is stamped `<profile>:<platform>` disabled with
    error_code multiplex_no_shared_listener and a WARNING naming the remedy.
  - Migration preflight: a secondary whose own gateway serves a port-binder today is refused when
    the default enables neither listener (it would be served nowhere after the fold); a secondary
    with no gateway gets the same text as a notice.
  - bind_listener publishes the port it actually bound (`listener_base`); the dashboard topology
    reads that instead of resolving a plugin platform's listen_port in the profile's plugin
    registry, so a parked or cold profile's callback port is reported and no deferred loader runs.

  26cde0b03cdc Teknium refactor(wecom): WeCom moves to the Hermes Labs wecom plugin, opt-in
  WeCom is now a Hermes Labs plugin (NousResearch/hermes-labs-plugins), not an
  official default one. Only homes that used WeCom get it installed, once; a new
  home installs nothing.

  - Both LEFT_CORE rows (bot and callback) carry the labs notice, like Yuanbao
    and DingTalk, merged with the plugins.disabled 'wecom' sentence.
  - Docs pages say "moved to the wecom Hermes Labs plugin" with the labs
    warning (en + zh-Hans); no default-install wording is left.
  - The one-automatic-install-per-plugin seam between default_plugins and the
    left-core migration stays: it is general (any plugin that is both a catalog
    default and a LEFT_CORE row) and now has its tests in test_default_plugins
    with a stand-in plugin instead of the wecom-named ones.

  9c82896ffee9 Teknium fix(wecom): migration preflight and dashboard read plugin capabilities in the owning profile
  - platform_serves_profile_prefix(value, home) reads the adapter class in the
    owning profile's plugin scope, like platform_binds_port: a port-binding
    plugin only a secondary installed is a URL-change notice, not a blocker.
  - A parked profile's plugins are never discovered for either check, nor for the
    dashboard's port readout (read-only probe).

  deb0661c69ea Teknium fix(wecom): review findings on the core removal
  - One automatic install per plugin across both installers: left-core
    `_pending` skips a plugin `_default_plugins_installed` records, and
    default_plugins skips one `_left_core_installed` records, so a removed
    WeCom stays removed whichever ran first.
  - `listen_port` is read in the owning profile's plugin scope: a multiplexed
    secondary (shared-listener routing), migration preflight (per profile home)
    and the dashboard topology (discovers that home's plugins; preflight never
    does, a parked profile's plugins must not run here).
  - `hermes-wecom-callback` keeps resolving: a `hermes-<a-b>` bundle falls back
    to platform `a_b`, and toolset validation accepts it.
  - StandaloneSendPolicy.media_via_adapter moves after reply_file_over so
    positional callers keep their meaning.
  - cron home-target priority keeps wecom (the plugin platform keeps it).
  - `_BUNDLED_ENV_SIBLINGS` removed with its readers' prefix branch.

  c3ec8edb3cc4 Teknium refactor(wecom): WeCom leaves core for the official wecom plugin
  Both WeCom platforms (AI Bot `wecom`, self-built-app `wecom_callback`) move to
  NousResearch/hermes-official-plugins `wecom/`, installed by default on every
  home (catalog `default: true`). Existing users get it automatically: two
  LEFT_CORE rows (one per platform, one shared plugin, installed once) whose
  platform_in_use predicates replicate core's enable gates per mode.

  Generic seams added for the plugin, never a name check left in core:
  - PlatformEntry.listen_port: a plugin platform that binds a host port
    (platform_binds_port, multiplex shared listener, migration blockers,
    dashboard topology). Replaces the wecom_callback rows.
  - StandaloneSendPolicy.media_via_adapter: send_message media through the live
    adapter route. Replaces the _CHUNKED_ROUTES["wecom"] row.
  - cron: a registered plugin platform without a cron env var (home channel from
    config.yaml only) is a valid delivery target. Replaces the wecom_callback row.

  Child-env strip set unchanged: _ADAPTER_SECRET_ENV also carries the
  left-core platform rows' secret_env.
2026-11-28 07:35:40 -08:00

348 lines
15 KiB
Python

"""Dump command for hermes CLI."""
import json
import os
import platform
import subprocess
import sys
from pathlib import Path
from hermes_cli.config import get_hermes_home, get_env_path, get_project_root, load_config
from hermes_cli.env_loader import load_hermes_dotenv
from hermes_constants import display_hermes_home
from hermes_platform.resolver.git import inspect_git
from agent.skill_utils import is_excluded_skill_path
from datetime import UTC
def _dotenv_key_names() -> set[str]:
"""Env-var names assigned a non-empty value in ~/.hermes/.env — what the managed backends (launchd /
systemd / desktop ``serve``) load, as opposed to the shell exports ``os.getenv`` reflects here.
``hermes debug share`` runs in a terminal, so ``os.getenv`` reflects the shell's environment, which can
include exported keys the managed backend never sees. Comparing against this set lets the dump flag that
mismatch (the exact trap behind #48504-style "no web_search" reports: key exported in the shell, absent
from .env, invisible to the launchd backend).
"""
try:
env_path = get_env_path()
text = env_path.read_text(encoding="utf-8-sig", errors="ignore")
except (OSError, UnicodeError):
return set()
names: set[str] = set()
for raw in text.splitlines():
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
if line.lower().startswith("export "):
line = line[len("export "):].lstrip()
name, _, value = line.partition("=")
if name.strip() and value.strip().strip("'\""): # a bare `KEY=` is effectively unset for the backend
names.add(name.strip())
return names
def _git_output(project_root: Path, *args: str) -> str:
"""Stripped stdout of ``git <args>`` run in *project_root*, or '' on any failure."""
if not inspect_git(cwd=project_root).usable:
return ""
try:
result = subprocess.run(["git", *args], capture_output=True, text=True, encoding='utf-8', errors='replace',
timeout=5, cwd=str(project_root), check=False)
return result.stdout.strip() if result.returncode == 0 else ""
except Exception:
return ""
def _get_git_commit(project_root: Path) -> str:
"""Short git commit hash, or '(unknown)'.
The requested *project_root* is authoritative: when it has no git,
the install-stamp fallback is only valid for the RUNNING install
(``hermes_cli.version_info`` has no per-root API — it reads
HERMES_INSTALL_ROOT / the running code root, never an arbitrary
directory). For any other root the provenance is unknown.
"""
value = _git_output(project_root, "rev-parse", "--short=8", "HEAD")
if value:
return value
if project_root.resolve() != get_project_root():
return "(unknown)"
try:
from hermes_cli.version_info import get_code_identity # deferred: keeps dump cheap on non-dump paths
return get_code_identity().get("short_sha") or "(unknown)"
except Exception:
return "(unknown)"
def _get_git_commit_date(project_root: Path) -> str:
"""Return the date the HEAD commit was authored (YYYY-MM-DD), or ''.
Same authority rule as :func:`_get_git_commit`: the stamp fallback
describes the running install only.
"""
value = _git_output(project_root, "log", "-1", "--format=%cd", "--date=short", "HEAD")
if value:
return value
if project_root.resolve() != get_project_root():
return ""
try:
from datetime import datetime, timezone
from hermes_cli.version_info import get_version_info # deferred: keeps dump cheap on non-dump paths
commit_date = get_version_info().commit_date
return datetime.fromtimestamp(commit_date, tz=UTC).strftime("%Y-%m-%d") if commit_date else ""
except Exception:
return ""
def _redact(value: str) -> str:
"""Redact all but first 4 and last 4 chars; ``""`` for an empty value (dump formats empties as blank)."""
from agent.redact import mask_secret
return mask_secret(value)
def _gateway_status() -> str:
"""Return a short gateway status string."""
try:
from hermes_cli.gateway import get_gateway_runtime_snapshot
snapshot = get_gateway_runtime_snapshot()
if snapshot.running:
mode = "manual" if snapshot.has_process_service_mismatch else snapshot.manager
# A supervised gateway may have no scannable PID (s6 `python -c` launcher, #125390).
pid = f", pid {snapshot.gateway_pids[0]}" if snapshot.gateway_pids else ""
return f"running ({mode}{pid})"
return f"stopped ({snapshot.manager})"
except Exception:
return "unknown" if sys.platform.startswith(("linux", "darwin")) else "N/A"
def _count_skills(hermes_home: Path) -> int:
"""Count installed skills."""
skills_dir = hermes_home / "skills"
return sum(1 for item in skills_dir.rglob("SKILL.md") if not is_excluded_skill_path(item)) if skills_dir.is_dir() else 0
def _cron_summary(hermes_home: Path) -> str:
"""Return cron jobs summary."""
jobs_file = hermes_home / "cron" / "jobs.json"
if not jobs_file.exists():
return "0"
try:
# utf-8-sig: same dialect as cron/jobs.load_jobs — Windows editors may leave a UTF-8 BOM.
with open(jobs_file, encoding="utf-8-sig") as f:
jobs = json.load(f).get("jobs", [])
active = sum(1 for j in jobs if j.get("enabled", True))
return f"{active} active / {len(jobs)} total"
except Exception:
return "(error reading)"
_PLATFORM_ENV_VARS = {
"telegram": "TELEGRAM_BOT_TOKEN", "discord": "DISCORD_BOT_TOKEN", "slack": "SLACK_BOT_TOKEN",
"whatsapp": "WHATSAPP_ENABLED", "signal": "SIGNAL_HTTP_URL", "email": "EMAIL_ADDRESS",
"sms": "TWILIO_ACCOUNT_SID", "matrix": "MATRIX_HOMESERVER_URL", "mattermost": "MATTERMOST_URL",
"feishu": "FEISHU_APP_ID",
"weixin": "WEIXIN_ACCOUNT_ID",
"qqbot": "QQ_APP_ID",
}
def _get_model_and_provider(config: dict) -> tuple[str, str]:
"""Extract model and provider from config."""
model_cfg = config.get("model", "")
if isinstance(model_cfg, dict):
return (model_cfg.get("default") or model_cfg.get("model") or model_cfg.get("name") or "(not set)", model_cfg.get("provider") or "(auto)")
return (model_cfg if isinstance(model_cfg, str) else "") or "(not set)", "(auto)"
# Sections with interesting user-facing overrides
_INTERESTING_PATHS = (
("agent", "max_turns"), ("agent", "gateway_timeout"), ("agent", "session_stall_timeout"),
("agent", "sanitizer_heal_escalation_threshold"), ("agent", "tool_use_enforcement"),
("agent", "execution_guidance"), ("terminal", "backend"), ("terminal", "docker_image"),
("terminal", "persistent_shell"), ("browser", "allow_private_urls"), ("compression", "enabled"),
("compression", "threshold"), ("compression", "in_place"), ("display", "streaming"),
("display", "skin"), ("display", "show_reasoning"), ("privacy", "redact_pii"), ("tts", "provider"),
)
def _config_overrides(config: dict) -> dict[str, str]:
"""Find non-default config values worth reporting."""
from hermes_cli.config import DEFAULT_CONFIG
overrides = {}
for section, key in _INTERESTING_PATHS:
default_section = DEFAULT_CONFIG.get(section, {})
user_section = config.get(section, {})
if not isinstance(default_section, dict) or not isinstance(user_section, dict):
continue
user_val = user_section.get(key)
if user_val is not None and user_val != default_section.get(key):
overrides[f"{section}.{key}"] = str(user_val)
user_toolsets = config.get("toolsets", [])
if user_toolsets != DEFAULT_CONFIG.get("toolsets", []):
overrides["toolsets"] = str(user_toolsets)
fallbacks = config.get("fallback_providers", [])
if fallbacks:
from hermes_cli.debug_redaction import redact_debug_support_text
overrides["fallback_providers"] = redact_debug_support_text(
str(_fallback_debug_projection(fallbacks))
)
return overrides
_FALLBACK_DEBUG_FIELDS = (
"provider",
"model",
"base_url",
"api_mode",
"key_env",
"api_key_env",
"max_tokens",
)
def _fallback_debug_projection(value) -> list[dict]:
"""Render only route metadata useful to support; omit arbitrary containers.
Fallback entries are open mappings consumed by provider-specific code, so a
denylist cannot make their ``headers``, ``env``, command/argv, or future
fields safe to serialize. Credential pointer names remain useful and carry
no values; an inline key is represented only as a source status.
"""
entries = [value] if isinstance(value, dict) else value if isinstance(value, list) else []
projected: list[dict] = []
for entry in entries:
if not isinstance(entry, dict):
continue
item: dict = {}
for key in _FALLBACK_DEBUG_FIELDS:
child = entry.get(key)
if key == "max_tokens":
if isinstance(child, (int, float)) and not isinstance(child, bool):
item[key] = child
elif isinstance(child, str):
item[key] = child
if entry.get("api_key"):
item["credential_source"] = "inline"
projected.append(item)
return projected
# (env var, dump label) in display order.
_API_KEYS = [
("OPENROUTER_API_KEY", "openrouter"), ("OPENAI_API_KEY", "openai"),
("ANTHROPIC_API_KEY", "anthropic"), ("ANTHROPIC_TOKEN", "anthropic_token"),
("NOUS_API_KEY", "nous"), ("GOOGLE_API_KEY", "google/gemini"), ("GEMINI_API_KEY", "gemini"),
("GLM_API_KEY", "glm/zai"), ("ZAI_API_KEY", "zai"), ("KIMI_API_KEY", "kimi"),
("MINIMAX_API_KEY", "minimax"), ("DEEPSEEK_API_KEY", "deepseek"),
("DASHSCOPE_API_KEY", "dashscope"), ("HF_TOKEN", "huggingface"), ("NVIDIA_API_KEY", "nvidia"),
("AI_GATEWAY_API_KEY", "ai_gateway"), ("OPENCODE_ZEN_API_KEY", "opencode_zen"),
("OPENCODE_GO_API_KEY", "opencode_go"), ("COMMANDCODE_API_KEY", "commandcode"),
("KILOCODE_API_KEY", "kilocode"), ("FIRECRAWL_API_KEY", "firecrawl"), ("TAVILY_API_KEY", "tavily"), ("PERPLEXITY_API_KEY", "perplexity"),
("KEENABLE_API_KEY", "keenable"), ("BROWSERBASE_API_KEY", "browserbase"), ("FAL_KEY", "fal"),
("ELEVENLABS_API_KEY", "elevenlabs"), ("GITHUB_TOKEN", "github"),
]
def _version_line(project_root: Path) -> str:
"""``<version> [<commit>] (<commit date>)`` using the running code identity."""
try:
from hermes_cli.version_info import get_version_info
version = get_version_info().derived_version
except Exception:
version = "(unknown)"
ver_str = f"{version} [{_get_git_commit(project_root)}]"
commit_date = _get_git_commit_date(project_root)
return f"{ver_str} ({commit_date})" if commit_date else ver_str
def _effective_terminal_backend(config: dict) -> str:
"""The EFFECTIVE backend: a TERMINAL_ENV set directly in .env / the shell overrides ``terminal.backend`` and
is what terminal_tool uses. run_dump() has already loaded .env, so os.environ reflects the override."""
config_backend = config.get("terminal", {}).get("backend", "local")
env_backend = (os.environ.get("TERMINAL_ENV") or "").strip().lower()
if env_backend and env_backend != str(config_backend).strip().lower():
return f"{env_backend} (TERMINAL_ENV overrides config.yaml terminal.backend={config_backend})"
return config_backend
def _api_key_lines(show_keys: bool) -> list[str]:
dotenv_keys = _dotenv_key_names()
lines = []
for env_var, label in _API_KEYS:
val = os.getenv(env_var, "")
display = _redact(val) if show_keys and val else ("set" if val else "not set")
# Set in this shell but absent from ~/.hermes/.env: a managed backend loads .env, not the login
# shell, so it likely can't see this key — flag it so support doesn't chase a phantom "configured".
if val and env_var not in dotenv_keys:
display += " (shell only — not in .env; managed/desktop backend may not see it)"
# `hermes auth add openrouter` credentials live in the pool, not env — don't read "not set".
# A credential added via `hermes auth add openrouter` lives in the credential pool, not as an env
# var — surface it so the dump doesn't misleadingly read "not set" while `hermes auth list` shows it
# (#42130).
if not val and label == "openrouter":
try:
from agent.credential_pool import load_pool as _load_pool
if _load_pool("openrouter").has_credentials():
display = "set (auth pool)"
except Exception:
pass
lines.append(f" {label:<20} {display}")
return lines
def _openai_version() -> str:
try:
import openai
return openai.__version__
except ImportError:
return "not installed"
def run_dump(args):
"""Output a compact, copy-pasteable setup summary."""
show_keys = getattr(args, "show_keys", False)
# Load env from .env file so key checks work
load_hermes_dotenv(hermes_home=get_env_path().parent, project_env=get_project_root() / ".env")
project_root, hermes_home = get_project_root(), get_hermes_home()
try:
config = load_config()
except Exception:
config = {}
model, provider = _get_model_and_provider(config)
try:
from hermes_cli.profiles import get_active_profile_name
profile = get_active_profile_name() or "(default)"
except Exception:
profile = "(default)"
toolsets = config.get("toolsets", ["hermes-cli"])
platforms = [name for name, env in _PLATFORM_ENV_VARS.items() if os.getenv(env)]
lines = [
"--- hermes dump ---",
f"version: {_version_line(project_root)}",
f"os: {platform.system()} {platform.release()} {platform.machine()}",
f"python: {sys.version.split()[0]}",
f"openai_sdk: {_openai_version()}",
f"profile: {profile}",
f"hermes_home: {display_hermes_home()}",
f"model: {model}",
f"provider: {provider}",
f"terminal: {_effective_terminal_backend(config)}",
"", "api_keys:", *_api_key_lines(show_keys),
"", "features:",
f" toolsets: {', '.join(toolsets) if toolsets else '(default)'}",
f" mcp_servers: {len(config.get('mcp', {}).get('servers', {}))}",
f" memory_provider: {config.get('memory', {}).get('provider', '') or 'built-in'}",
f" gateway: {_gateway_status()}",
f" platforms: {', '.join(platforms) if platforms else 'none'}",
f" cron_jobs: {_cron_summary(hermes_home)}",
f" skills: {_count_skills(hermes_home)}",
]
overrides = _config_overrides(config)
if overrides:
lines += ["", "config_overrides:"] + [f" {key}: {val}" for key, val in overrides.items()]
print("\n".join(lines + ["--- end dump ---"]))