Skip to content

The agent that grows with you

refactor(hermes_cli): memory_setup — extract schema-field prompt loop, post_setup hook, provider lookup; hoist import-name table

Teknium890029b5d466
diff --git a/hermes_cli/memory_setup.py b/hermes_cli/memory_setup.py
index e2fc9ea831e..0a6783879d8 100644
--- a/hermes_cli/memory_setup.py
+++ b/hermes_cli/memory_setup.py
@@ -12,12 +12,20 @@ from hermes_cli.secret_prompt import masked_secret_prompt
_CANCELLED = -1
+# pip name → import name mapping for packages where they differ
+_IMPORT_NAMES = {
+ "honcho-ai": "honcho",
+ "mem0ai": "mem0",
+ "hindsight-client": "hindsight_client",
+ "hindsight-all": "hindsight",
+}
+
def _provider_pip_dependencies(provider_name: str, declared: list) -> list:
"""Return the pip deps a provider actually needs on THIS install.
- ``plugin.yaml`` declares the provider's baseline bridge packages, but some providers install
- mode-dependent extras at setup time that the manifest can't express.
+ ``plugin.yaml`` declares the baseline bridge packages; some providers add mode-dependent extras
+ at setup time that the manifest can't express.
"""
deps = list(declared or [])
if provider_name == "hindsight":
@@ -25,9 +33,8 @@ def _provider_pip_dependencies(provider_name: str, declared: list) -> list:
import json
cfg_path = get_hermes_home() / "hindsight" / "config.json"
cfg = json.loads(cfg_path.read_text(encoding="utf-8")) if cfg_path.exists() else {}
- mode = cfg.get("mode", "")
# "local" is a legacy alias for "local_embedded"
- if mode in {"local", "local_embedded"}:
+ if cfg.get("mode", "") in {"local", "local_embedded"}:
deps.append("hindsight-all")
except Exception:
pass
@@ -50,12 +57,7 @@ def _curses_select(
if cancel_returns is None:
cancel_returns = default
-
- # Format (label, desc) tuples into display strings
- display_items = [
- f"{label} - {desc}" if desc else label
- for label, desc in items
- ]
+ display_items = [f"{label} - {desc}" if desc else label for label, desc in items]
result = curses_radiolist(title, display_items, selected=default, cancel_returns=cancel_returns)
_clear_interactive_transition()
return result
@@ -92,9 +94,8 @@ def _prompt(label: str, default: str | None = None, secret: bool = False) -> str
def _install_dependencies(provider_name: str, *, force: bool = False) -> None:
"""Install pip dependencies declared in ``plugin.yaml``.
- With ``force`` every declared dependency goes to the installer even if it imports; the resolver
- reinstalls anything missing or version-drifted and no-ops otherwise. This is how ``hermes
- update`` heals the active memory provider after a venv rebuild removed its bridge packages.
+ With ``force`` every declared dependency goes to the installer even if it imports (the resolver
+ no-ops when nothing drifted) — how ``hermes update`` heals a provider after a venv rebuild.
"""
import subprocess
from plugins.memory import find_provider_dir
@@ -105,7 +106,6 @@ def _install_dependencies(provider_name: str, *, force: bool = False) -> None:
yaml_path = plugin_dir / "plugin.yaml"
if not yaml_path.exists():
return
-
try:
import yaml
with open(yaml_path, encoding="utf-8") as f:
@@ -117,15 +117,6 @@ def _install_dependencies(provider_name: str, *, force: bool = False) -> None:
if not pip_deps:
return
- # pip name → import name mapping for packages where they differ
- _IMPORT_NAMES = {
- "honcho-ai": "honcho",
- "mem0ai": "mem0",
- "hindsight-client": "hindsight_client",
- "hindsight-all": "hindsight",
- }
-
- # Check which packages need installation.
missing = []
for dep in pip_deps:
if force:
@@ -138,16 +129,13 @@ def _install_dependencies(provider_name: str, *, force: bool = False) -> None:
__import__(import_name)
except ImportError:
missing.append(dep)
-
if not missing:
return
print(f"\n Installing dependencies: {', '.join(missing)}")
- # Environment-aware install: on immutable hosted images the agent venv
- # is sealed read-only and installs must go to the durable target on the
- # data volume (HERMES_LAZY_INSTALL_TARGET). install_specs handles the
- # routing/gating; on normal installs it is venv-scoped as before (NS-605).
+ # install_specs routes to the durable target on sealed hosted images (HERMES_LAZY_INSTALL_TARGET)
+ # and is venv-scoped on normal installs.
from tools.lazy_deps import install_specs
manual_cmd = f"uv pip install {' '.join(missing)}"
@@ -167,25 +155,25 @@ def _install_dependencies(provider_name: str, *, force: bool = False) -> None:
print(f" ⚠ Install failed: {e}")
print(f" Run manually: {manual_cmd}")
- # Also show external dependencies (non-pip) if any
- ext_deps = meta.get("external_dependencies", [])
- for dep in ext_deps:
- dep_name = dep.get("name", "")
+ # Also show external (non-pip) dependencies that are missing.
+ for dep in meta.get("external_dependencies", []):
check_cmd = dep.get("check", "")
install_cmd = dep.get("install", "")
if check_cmd:
try:
- subprocess.run(
- shlex.split(check_cmd), check=True, capture_output=True, timeout=5
- )
+ subprocess.run(shlex.split(check_cmd), check=True, capture_output=True, timeout=5)
except Exception:
if install_cmd:
- print(f"\n ⚠ '{dep_name}' not found. Install with:")
+ print(f"\n ⚠ '{dep.get('name', '')}' not found. Install with:")
print(f" {install_cmd}")
+def _schema_of(provider) -> list:
+ return provider.get_config_schema() if hasattr(provider, "get_config_schema") else []
+
+
def _get_available_providers() -> list:
- """Discover memory providers from plugins/memory/."""
+ """Discover memory providers from plugins/memory/ as ``(name, setup_hint, provider)`` tuples."""
try:
from plugins.memory import discover_memory_providers, load_memory_provider
raw = discover_memory_providers()
@@ -200,8 +188,7 @@ def _get_available_providers() -> list:
continue
except Exception:
continue
-
- schema = provider.get_config_schema() if hasattr(provider, "get_config_schema") else []
+ schema = _schema_of(provider)
has_secrets = any(f.get("secret") for f in schema)
has_non_secrets = any(not f.get("secret") for f in schema)
if has_secrets and has_non_secrets:
@@ -212,46 +199,45 @@ def _get_available_providers() -> list:
setup_hint = "no setup needed"
else:
setup_hint = "local"
-
results.append((name, setup_hint, provider))
return results
+def _find_provider(providers: list, provider_name: str):
+ return next((p for p in providers if p[0] == provider_name), None)
+
+
# ---------------------------------------------------------------------------
# Setup wizard
# ---------------------------------------------------------------------------
+def _post_setup_hook(provider, config: dict) -> bool:
+ """Normalize the ``memory`` block; True when the provider's ``post_setup`` took over (it owns
+ config, connection test and activation), so the caller must stop."""
+ if not isinstance(config.get("memory"), dict):
+ config["memory"] = {}
+ if hasattr(provider, "post_setup"):
+ provider.post_setup(str(get_hermes_home()), config)
+ return True
+ return False
+
+
def cmd_setup_provider(provider_name: str) -> None:
"""Run memory setup for a specific provider, skipping the picker."""
from hermes_cli.config import load_config, save_config
- providers = _get_available_providers()
- match = None
- for name, desc, provider in providers:
- if name == provider_name:
- match = (name, desc, provider)
- break
-
+ match = _find_provider(_get_available_providers(), provider_name)
if not match:
print(f"\n Memory provider '{provider_name}' not found.")
print(" Run 'hermes memory setup' to see available providers.\n")
return
-
name, _, provider = match
_clear_interactive_transition()
-
_install_dependencies(name)
-
config = load_config()
- if not isinstance(config.get("memory"), dict):
- config["memory"] = {}
-
- if hasattr(provider, "post_setup"):
- hermes_home = str(get_hermes_home())
- provider.post_setup(hermes_home, config)
+ if _post_setup_hook(provider, config):
return
-
# Fallback: generic schema-based setup (same as cmd_setup)
config["memory"]["provider"] = name
save_config(config)
@@ -259,23 +245,70 @@ def cmd_setup_provider(provider_name: str) -> None:
print(" Activation saved to config.yaml\n")
+def _prompt_schema_fields(name: str, schema: list, provider_config: dict, env_writes: dict) -> bool:
+ """Walk a provider's config schema, prompting per field. False when the user cancelled."""
+ print(f"\n Configuring {name}:\n")
+ for field in schema:
+ key = field["key"]
+ desc = field.get("description", key)
+ default = field.get("default")
+ # Dynamic default: look up default from another field's value
+ default_from = field.get("default_from")
+ if default_from and isinstance(default_from, dict):
+ ref_value = provider_config.get(default_from.get("field", ""), "")
+ ref_map = default_from.get("map", {})
+ if ref_value and ref_value in ref_map:
+ default = ref_map[ref_value]
+ is_secret = field.get("secret", False)
+ choices = field.get("choices")
+ env_var = field.get("env_var")
+ url = field.get("url")
+
+ when = field.get("when")
+ if when and isinstance(when, dict) and not all(provider_config.get(k) == v for k, v in when.items()):
+ continue
+
+ if choices and not is_secret:
+ current = provider_config.get(key, default)
+ current_idx = choices.index(current) if current and current in choices else 0
+ sel = _curses_select(f" {desc}", [(c, "") for c in choices], default=current_idx, cancel_returns=_CANCELLED)
+ if sel == _CANCELLED:
+ _print_cancelled_setup()
+ return False
+ provider_config[key] = choices[sel]
+ elif is_secret:
+ existing = os.environ.get(env_var, "") if env_var else ""
+ if existing:
+ masked = f"...{existing[-4:]}" if len(existing) > 4 else "set"
+ val = _prompt(f"{desc} (current: {masked}, blank to keep)", secret=True)
+ else:
+ if url:
+ print(f" Get yours at {url}")
+ val = _prompt(desc, secret=True)
+ if val and env_var:
+ env_writes[env_var] = val
+ else:
+ effective_default = provider_config.get(key) or default
+ val = _prompt(desc, default=str(effective_default) if effective_default else None)
+ if val:
+ provider_config[key] = val
+ if env_var and env_var not in env_writes:
+ env_writes[env_var] = val
+ return True
+
+
def cmd_setup(args) -> None:
"""Interactive memory provider setup wizard."""
from hermes_cli.config import load_config, save_config
providers = _get_available_providers()
-
if not providers:
print("\n No memory provider plugins detected.")
print(" Install a plugin to ~/.hermes/plugins/ and try again.\n")
return
- # Build picker items
- items = []
- for name, desc, _ in providers:
- items.append((name, f"— {desc}"))
+ items = [(name, f"— {desc}") for name, desc, _ in providers]
items.append(("Built-in only", "— MEMORY.md / USER.md (default)"))
-
builtin_idx = len(items) - 1
selected = _curses_select("Memory provider setup", items, default=builtin_idx, cancel_returns=_CANCELLED)
if selected == _CANCELLED:
@@ -285,8 +318,6 @@ def cmd_setup(args) -> None:
config = load_config()
if not isinstance(config.get("memory"), dict):
config["memory"] = {}
-
- # Built-in only
if selected >= len(providers):
config["memory"]["provider"] = ""
save_config(config)
@@ -295,102 +326,27 @@ def cmd_setup(args) -> None:
return
name, _, provider = providers[selected]
-
_clear_interactive_transition()
-
- # Install pip dependencies if declared in plugin.yaml
_install_dependencies(name)
-
- # If the provider has a post_setup hook, delegate entirely to it.
- # The hook handles its own config, connection test, and activation.
- if hasattr(provider, "post_setup"):
- hermes_home = str(get_hermes_home())
- provider.post_setup(hermes_home, config)
+ if _post_setup_hook(provider, config):
return
- schema = provider.get_config_schema() if hasattr(provider, "get_config_schema") else []
-
provider_config = config["memory"].get(name, {})
if not isinstance(provider_config, dict):
provider_config = {}
+ env_writes: dict = {}
+ schema = _schema_of(provider)
+ if schema and not _prompt_schema_fields(name, schema, provider_config, env_writes):
+ return
- env_writes = {}
-
- if schema:
- print(f"\n Configuring {name}:\n")
-
- for field in schema:
- key = field["key"]
- desc = field.get("description", key)
- default = field.get("default")
- # Dynamic default: look up default from another field's value
- default_from = field.get("default_from")
- if default_from and isinstance(default_from, dict):
- ref_field = default_from.get("field", "")
- ref_map = default_from.get("map", {})
- ref_value = provider_config.get(ref_field, "")
- if ref_value and ref_value in ref_map:
- default = ref_map[ref_value]
- is_secret = field.get("secret", False)
- choices = field.get("choices")
- env_var = field.get("env_var")
- url = field.get("url")
-
- # Skip fields whose "when" condition doesn't match
- when = field.get("when")
- if when and isinstance(when, dict):
- if not all(provider_config.get(k) == v for k, v in when.items()):
- continue
-
- if choices and not is_secret:
- # Use curses picker for choice fields
- choice_items = [(c, "") for c in choices]
- current = provider_config.get(key, default)
- current_idx = 0
- if current and current in choices:
- current_idx = choices.index(current)
- sel = _curses_select(f" {desc}", choice_items, default=current_idx, cancel_returns=_CANCELLED)
- if sel == _CANCELLED:
- _print_cancelled_setup()
- return
- provider_config[key] = choices[sel]
- elif is_secret:
- # Prompt for secret
- existing = os.environ.get(env_var, "") if env_var else ""
- if existing:
- masked = f"...{existing[-4:]}" if len(existing) > 4 else "set"
- val = _prompt(f"{desc} (current: {masked}, blank to keep)", secret=True)
- else:
- hint = f" Get yours at {url}" if url else ""
- if hint:
- print(hint)
- val = _prompt(desc, secret=True)
- if val and env_var:
- env_writes[env_var] = val
- else:
- # Regular text prompt
- current = provider_config.get(key)
- effective_default = current or default
- val = _prompt(desc, default=str(effective_default) if effective_default else None)
- if val:
- provider_config[key] = val
- # Also write to .env if this field has an env_var
- if env_var and env_var not in env_writes:
- env_writes[env_var] = val
-
- # Write activation key to config.yaml
config["memory"]["provider"] = name
save_config(config)
- # Write non-secret config to provider's native location
- hermes_home = str(get_hermes_home())
if provider_config and hasattr(provider, "save_config"):
try:
- provider.save_config(provider_config, hermes_home)
+ provider.save_config(provider_config, str(get_hermes_home()))
except Exception as e:
print(f" Failed to write provider config: {e}")
-
- # Write secrets to .env
if env_writes:
_write_env_vars(env_writes)
@@ -409,12 +365,10 @@ def _write_env_vars(
) -> None:
"""Persist memory-provider env vars through the canonical ``.env`` writer.
- Delegates to ``save_env_value`` so keys pass the same gate as every other ``.env`` writer: name
- regex, denylist (``LD_PRELOAD``/``PYTHONPATH``/``HERMES_HOME``…), CR/LF stripping and atomic
- 0o600 writes. A direct write previously let a plugin schema inject ``LD_PRELOAD`` into ``.env``.
- ``ValueError`` from validation is reported and skipped so one bad key doesn't sink the batch;
- filesystem errors propagate since later keys can't be persisted safely either. ``hermes_home``
- is applied via the context-local home override, not by mutating ``os.environ``.
+ ``save_env_value`` applies the shared gate (name regex, ``LD_PRELOAD``/``PYTHONPATH``/``HERMES_HOME``
+ denylist, CR/LF stripping, atomic 0o600 writes). ``ValueError`` is reported and skipped so one
+ bad key doesn't sink the batch; filesystem errors propagate. ``hermes_home`` is applied via the
+ context-local override, not ``os.environ``.
"""
from hermes_cli.config import save_env_value
from hermes_constants import reset_hermes_home_override, set_hermes_home_override
@@ -435,6 +389,10 @@ def _write_env_vars(
# Status
# ---------------------------------------------------------------------------
+def _mark(enabled) -> str:
+ return "enabled ✓" if enabled else "disabled ✗"
+
+
def cmd_status(args) -> None:
"""Show current memory provider config."""
from hermes_cli.config import load_config
@@ -443,33 +401,23 @@ def cmd_status(args) -> None:
mem_config = config.get("memory", {})
provider_name = mem_config.get("provider", "")
- memory_enabled = mem_config.get("memory_enabled", True)
- user_profile_enabled = mem_config.get("user_profile_enabled", True)
-
- mem_mark = "enabled ✓" if memory_enabled else "disabled ✗"
- user_mark = "enabled ✓" if user_profile_enabled else "disabled ✗"
-
- # Check if the memory tool is enabled for the CLI platform via the
- # canonical resolver and respects the check_fn gate when both stores are disabled.
+ # Memory tool enablement for the CLI platform via the canonical resolver, respecting the
+ # check_fn gate when both stores are disabled.
from hermes_cli.tools_config import _get_platform_tools
from tools.memory_tool import check_memory_requirements
cli_tools = _get_platform_tools(config, "cli", include_default_mcp_servers=False)
memory_tool_enabled = ("memory" in cli_tools) and check_memory_requirements()
- tool_mark = "enabled ✓" if memory_tool_enabled else "disabled ✗"
print("\nMemory status\n" + "─" * 40)
print(" Built-in (MEMORY.md / USER.md):")
- print(f" Memory injection: {mem_mark}")
- print(f" User profile: {user_mark}")
- print(f" Memory tool: {tool_mark}")
+ print(f" Memory injection: {_mark(mem_config.get('memory_enabled', True))}")
+ print(f" User profile: {_mark(mem_config.get('user_profile_enabled', True))}")
+ print(f" Memory tool: {_mark(memory_tool_enabled)}")
print(f" Provider: {provider_name or '(none — built-in only)'}")
providers = _get_available_providers()
- provider = None
- for pname, _, candidate in providers:
- if pname == provider_name:
- provider = candidate
- break
+ match = _find_provider(providers, provider_name)
+ provider = match[2] if match else None
if provider_name:
provider_config = mem_config.get(provider_name, {})
@@ -481,7 +429,6 @@ def cmd_status(args) -> None:
display_config = dict(provider_config) if isinstance(provider_config, dict) else provider_config
if isinstance(display_config, dict):
display_config["status_config_error"] = str(e)
-
if display_config:
print(f"\n {provider_name} config:")
for key, val in display_config.items():
@@ -493,26 +440,20 @@ def cmd_status(args) -> None:
print(" Status: available ✓")
else:
print(" Status: not available ✗")
- schema = provider.get_config_schema() if hasattr(provider, "get_config_schema") else []
- # Check all fields that have env_var (both secret and non-secret)
- required_fields = [f for f in schema if f.get("env_var")]
+ # All fields with env_var (secret and non-secret)
+ required_fields = [f for f in _schema_of(provider) if f.get("env_var")]
if required_fields:
print(" Missing:")
for f in required_fields:
env_var = f.get("env_var", "")
url = f.get("url", "")
is_set = bool(os.environ.get(env_var))
- mark = "✓" if is_set else "✗"
- line = f" {mark} {env_var}"
+ line = f" {'✓' if is_set else '✗'} {env_var}"
if url and not is_set:
line += f" → {url}"
print(line)
- print(
- " Note: systemd/gateway services do not inherit ~/.hermes/.env —"
- )
- print(
- " set any variables above in the service environment."
- )
+ print(" Note: systemd/gateway services do not inherit ~/.hermes/.env —")
+ print(" set any variables above in the service environment.")
else:
print("\n Plugin: NOT installed ✗")
print(f" Install the '{provider_name}' memory plugin to ~/.hermes/plugins/")
@@ -522,7 +463,6 @@ def cmd_status(args) -> None:
for pname, desc, _ in providers:
active = " ← active" if pname == provider_name else ""
print(f" • {pname} ({desc}){active}")
-
print()
@@ -532,14 +472,11 @@ def cmd_status(args) -> None:
def memory_command(args) -> None:
"""Route memory subcommands."""
- sub = getattr(args, "memory_command", None)
- if sub == "setup":
+ if getattr(args, "memory_command", None) == "setup":
provider = getattr(args, "provider", None)
if provider:
cmd_setup_provider(provider)
else:
cmd_setup(args)
- elif sub == "status":
- cmd_status(args)
else:
cmd_status(args)