Skip to content

The agent that grows with you

fix(memory): user-dir memory providers keep Desktop config + OAuth

teknium19318b7a74d44
diff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.py
index f287511e655..fe3bbba5c4b 100644
--- a/hermes_cli/doctor_state.py
+++ b/hermes_cli/doctor_state.py
@@ -18,8 +18,8 @@ from hermes_state_holders import read_only_db_uri
def _honcho_is_configured_for_doctor() -> bool:
"""Return True when Honcho is configured, even if this process has no active session."""
try:
- from plugins.memory.honcho.client import HonchoClientConfig
- cfg = HonchoClientConfig.from_global_config()
+ from plugins.memory import import_provider_module
+ cfg = import_provider_module("honcho", "client").HonchoClientConfig.from_global_config()
return bool(cfg.enabled and (cfg.api_key or cfg.base_url))
except Exception:
return False
@@ -473,9 +473,10 @@ def _check_skills_hub(should_fix: bool, f: Finding) -> None:
def _memory_provider_honcho(issues: list) -> None:
- from plugins.memory.honcho.client import HonchoClientConfig, resolve_config_path
- hcfg = HonchoClientConfig.from_global_config()
- cfg_path = resolve_config_path()
+ from plugins.memory import import_provider_module
+ client = import_provider_module("honcho", "client")
+ hcfg = client.HonchoClientConfig.from_global_config()
+ cfg_path = client.resolve_config_path()
if not cfg_path.exists():
# Config file missing — env-var fallback may still have resolved it.
check_bool(hcfg.api_key or hcfg.base_url,
@@ -487,18 +488,17 @@ def _memory_provider_honcho(issues: list) -> None:
_fail_and_issue("Honcho API key or base URL not set", "run: hermes memory setup",
"No Honcho API key — run 'hermes memory setup'", issues)
else:
- from plugins.memory.honcho.client import get_honcho_client, reset_honcho_client
- reset_honcho_client()
+ client.reset_honcho_client()
try:
- get_honcho_client(hcfg)
+ client.get_honcho_client(hcfg)
check_ok("Honcho connected", f"workspace={hcfg.workspace_id} mode={hcfg.recall_mode} freq={hcfg.write_frequency}")
except Exception as _e:
_fail_and_issue("Honcho connection failed", str(_e), f"Honcho unreachable: {_e}", issues)
def _memory_provider_mem0(issues: list) -> None:
- from plugins.memory.mem0 import _load_config as _load_mem0_config
- mem0_cfg = _load_mem0_config()
+ from plugins.memory import import_provider_module
+ mem0_cfg = import_provider_module("mem0")._load_config()
if mem0_cfg.get("api_key", ""):
check_ok("Mem0 API key configured")
check_info(f"user_id={mem0_cfg.get('user_id', '?')} agent_id={mem0_cfg.get('agent_id', '?')}")
diff --git a/hermes_cli/memory_oauth.py b/hermes_cli/memory_oauth.py
index a8ad018e4b8..b4fc095a26b 100644
--- a/hermes_cli/memory_oauth.py
+++ b/hermes_cli/memory_oauth.py
@@ -2,7 +2,6 @@
from __future__ import annotations
-import importlib
from contextlib import contextmanager
from typing import Optional
@@ -12,11 +11,13 @@ router = APIRouter(prefix="/api/memory/providers")
def _resolve_flow(provider: str):
- """Return a provider's OAuth flow module by convention, or raise 404."""
+ """Return a provider's ``oauth_flow`` module (bundled or user-dir copy), or raise 404."""
if not provider.isidentifier():
raise HTTPException(status_code=404, detail=f"unknown memory provider {provider!r}")
+ from plugins.memory import import_provider_module
+
try:
- return importlib.import_module(f"plugins.memory.{provider}.oauth_flow")
+ return import_provider_module(provider, "oauth_flow")
except ImportError:
raise HTTPException(status_code=404, detail=f"{provider} does not support OAuth connect")
diff --git a/hermes_cli/profile_cmd.py b/hermes_cli/profile_cmd.py
index 6e6058031e6..0eccafdde6e 100644
--- a/hermes_cli/profile_cmd.py
+++ b/hermes_cli/profile_cmd.py
@@ -221,14 +221,15 @@ def _profile_create(args):
_print_channel_clone_notice(name, source_label, clone_channels, "--clone-all" if clone_all else "--clone")
# Auto-clone Honcho config for the new profile (only with clone operations)
try:
- from plugins.memory.honcho.cli import ConfigWriteRefused, clone_honcho_for_profile
+ from plugins.memory import import_provider_module
+ honcho_cli = import_provider_module("honcho", "cli")
except Exception:
- clone_honcho_for_profile = None # Honcho plugin not installed
- if clone_honcho_for_profile is not None:
+ honcho_cli = None # Honcho plugin not installed
+ if honcho_cli is not None:
try:
- if clone_honcho_for_profile(name):
+ if honcho_cli.clone_honcho_for_profile(name):
print(f"Honcho config cloned (peer: {name})")
- except ConfigWriteRefused as e:
+ except honcho_cli.ConfigWriteRefused as e:
print(f"Honcho config not cloned: {e}")
except Exception:
pass # Honcho not configured
diff --git a/hermes_cli/profiles.py b/hermes_cli/profiles.py
index 806aa7f52d1..0c7fe8c95a2 100644
--- a/hermes_cli/profiles.py
+++ b/hermes_cli/profiles.py
@@ -1664,8 +1664,8 @@ def delete_profile(name: str, yes: bool = False) -> Path:
# Inside serve (DELETE /api/profiles/<name>) the handles live here; from the CLI no-op.
with contextlib.suppress(Exception): # best-effort: never block the delete on the release path
# 2c. See #88347.
- from plugins.memory.holographic.store import MemoryStore as _MemoryStore
- _released = _MemoryStore.release_all_under(profile_dir)
+ from plugins.memory import import_provider_module
+ _released = import_provider_module("holographic", "store").MemoryStore.release_all_under(profile_dir)
if _released:
print(f"✓ Released {_released} memory-store connection(s) held by this process")
with contextlib.suppress(Exception):
diff --git a/hermes_cli/update_cmd_maint.py b/hermes_cli/update_cmd_maint.py
index 048942af38a..69468fad580 100644
--- a/hermes_cli/update_cmd_maint.py
+++ b/hermes_cli/update_cmd_maint.py
@@ -858,8 +858,8 @@ def _sync_profiles_after_update() -> None:
print(f"→ Seeded .env for {len(backfilled)} profile(s) (copied from default): {', '.join(backfilled)}")
with suppress(Exception):
- from plugins.memory.honcho.cli import sync_honcho_profiles_quiet
- synced = sync_honcho_profiles_quiet()
+ from plugins.memory import import_provider_module
+ synced = import_provider_module("honcho", "cli").sync_honcho_profiles_quiet()
if synced:
print(f"\n-> Honcho: synced {synced} profile(s)")
diff --git a/hermes_cli/web_routers/memory_providers.py b/hermes_cli/web_routers/memory_providers.py
index 30ad3201bc5..c9dc1f8b440 100644
--- a/hermes_cli/web_routers/memory_providers.py
+++ b/hermes_cli/web_routers/memory_providers.py
@@ -123,10 +123,13 @@ def _read_flat_json(provider: ProviderConfigSchema) -> Dict[str, Any]:
return _read_json_dict(_flat_json_path(provider), "memory provider config")
-def _honcho_resolvers():
- """Lazily import the Honcho plugin's resolvers (optional plugin)."""
- from plugins.memory.honcho.client import _host_block, resolve_active_host, resolve_config_path
- return resolve_active_host, resolve_config_path, _host_block
+def _honcho_resolvers(name: str):
+ """Host-block resolvers of provider *name*'s own ``client`` module, wherever the provider is
+ installed (bundled or ``$HERMES_HOME/plugins/``)."""
+ from plugins.memory import import_provider_module
+
+ client = import_provider_module(name, "client")
+ return client.resolve_active_host, client.resolve_config_path, client._host_block
def _save_submitted_secrets(provider: ProviderConfigSchema, values: Dict[str, str]) -> list:
@@ -179,17 +182,18 @@ def _write_provider_flat(provider: ProviderConfigSchema, values: Dict[str, str])
def _write_provider_honcho(provider: ProviderConfigSchema, values: Dict[str, str]) -> None:
"""Persist submitted fields to Honcho's real config for the active host (partial
saves touch only submitted keys; blank text clears a key — see ``_apply_field_values``)."""
- from plugins.memory.honcho.oauth import ACCESS_TOKEN_PREFIX, _config_refresh_lock, _read_config_strict, _refresh_lock
+ from plugins.memory import import_provider_module
- resolve_active_host, resolve_config_path, host_block_of = _honcho_resolvers()
+ oauth = import_provider_module(provider.name, "oauth")
+ resolve_active_host, resolve_config_path, host_block_of = _honcho_resolvers(provider.name)
host = resolve_active_host()
# Write the file reads resolve, or a save shadows it with a sparse copy.
path = resolve_config_path()
# OAuth rotation is single-use; an unlocked RMW here can revoke the grant.
- with _refresh_lock, _config_refresh_lock(path):
+ with oauth._refresh_lock, oauth._config_refresh_lock(path):
# Strict: a file that exists but does not parse must not be replaced by this host's block alone.
- cfg = _read_config_strict(path)
+ cfg = oauth._read_config_strict(path)
hosts = cfg.get("hosts")
cfg["hosts"] = hosts = hosts if isinstance(hosts, dict) else {}
# Update the block reads resolve (legacy dot-form included), never shadow it.
@@ -200,7 +204,7 @@ def _write_provider_honcho(provider: ProviderConfigSchema, values: Dict[str, str
for field, submitted in _save_submitted_secrets(provider, values):
# Persist where the client reads first; an OAuth token owns that slot.
stored = host_block.get(field.key)
- if not (isinstance(stored, str) and stored.startswith(ACCESS_TOKEN_PREFIX)):
+ if not (isinstance(stored, str) and stored.startswith(oauth.ACCESS_TOKEN_PREFIX)):
host_block[field.key] = submitted
_apply_field_values(provider, values, lambda field: host_block if field.scope == "host" else cfg)
@@ -246,7 +250,7 @@ def _declared_provider_payload(provider: ProviderConfigSchema) -> Dict[str, Any]
env = load_env()
is_honcho = provider.storage == STORAGE_HONCHO_HOST_BLOCK
if is_honcho:
- resolve_active_host, resolve_config_path, host_block_of = _honcho_resolvers()
+ resolve_active_host, resolve_config_path, host_block_of = _honcho_resolvers(provider.name)
host = resolve_active_host()
raw = _read_json_dict(resolve_config_path(), "Honcho config")
host_block = host_block_of(raw, host)
diff --git a/plugins/memory/__init__.py b/plugins/memory/__init__.py
index 22ef4b6404e..08780102b62 100644
--- a/plugins/memory/__init__.py
+++ b/plugins/memory/__init__.py
@@ -231,10 +231,7 @@ def import_memory_provider_module(name: Optional[str] = None) -> bool:
imported = False
try:
if provider_dir := find_provider_dir(name):
- imported = _loader.load_plugin_module(
- _module_name(provider_dir, name), provider_dir, parents=("plugins", "plugins.memory"),
- logger=logger, synthetic_namespace=None if _is_bundled(provider_dir) else _USER_NAMESPACE,
- ) is not None
+ imported = _load_package(provider_dir, name) is not None
elif (entry_point := find_provider_entry_point(name)) is not None:
entry_point.load()
imported = True
@@ -252,6 +249,36 @@ def import_memory_provider_module(name: Optional[str] = None) -> bool:
return imported
+def _load_package(provider_dir: Path, name: str):
+ """Import the provider package at *provider_dir* under the module name the loader owns
+ (``plugins.memory.<name>`` bundled, synthetic user namespace otherwise); None on failure."""
+ return _loader.load_plugin_module(
+ _module_name(provider_dir, name), provider_dir,
+ parents=("plugins", "plugins.memory"),
+ logger=logger,
+ synthetic_namespace=None if _is_bundled(provider_dir) else _USER_NAMESPACE,
+ )
+
+
+def import_provider_module(name: str, submodule: Optional[str] = None):
+ """The package (or ``<package>.<submodule>``) of whichever copy of provider *name* is installed.
+
+ Host-side code (dashboard host-block storage, OAuth routes, doctor, profile clone) used to
+ ``import plugins.memory.<name>.<submodule>``, which only exists for the bundled copy; a
+ catalog install under ``$HERMES_HOME/plugins/`` loads under the synthetic user namespace,
+ so those surfaces 500'd/404'd the moment the bundled copy left core. Resolving through
+ ``find_provider_dir`` makes bundled and user-dir copies behave identically. Raises
+ ``ImportError`` when the provider is not installed or lacks the submodule.
+ """
+ provider_dir = find_provider_dir(name)
+ if provider_dir is None:
+ raise ImportError(f"memory provider {name!r} is not installed")
+ package = _load_package(provider_dir, name)
+ if package is None:
+ raise ImportError(f"memory provider {name!r} failed to import")
+ return importlib.import_module(f"{package.__name__}.{submodule}") if submodule else package
+
+
def _instantiate_subclass(namespace) -> Optional["MemoryProvider"]:
"""First instantiable ``MemoryProvider`` subclass found among *namespace*'s attributes."""
from agent.memory_provider import MemoryProvider
@@ -305,12 +332,7 @@ def _load_provider_from_entry_point(entry_point, *, register_skills: bool = True
def _load_provider_from_dir(provider_dir: Path, *, register_skills: bool = True) -> Optional["MemoryProvider"]:
"""Import a provider module; ``register(ctx)`` first, else a top-level subclass."""
name = provider_dir.name
- mod = _loader.load_plugin_module(
- _module_name(provider_dir, name), provider_dir,
- parents=("plugins", "plugins.memory"),
- logger=logger,
- synthetic_namespace=None if _is_bundled(provider_dir) else _USER_NAMESPACE,
- )
+ mod = _load_package(provider_dir, name)
if mod is None:
return None
diff --git a/tests/hermes_cli/test_web_memory_providers_honcho_write.py b/tests/hermes_cli/test_web_memory_providers_honcho_write.py
index dd04ec29929..7c082d6c923 100644
--- a/tests/hermes_cli/test_web_memory_providers_honcho_write.py
+++ b/tests/hermes_cli/test_web_memory_providers_honcho_write.py
@@ -11,7 +11,7 @@ from plugins.memory.honcho.config_schema import CONFIG_SCHEMA
def _point_at(monkeypatch, path):
from plugins.memory.honcho.client import _host_block
- monkeypatch.setattr(mp, "_honcho_resolvers", lambda: (lambda: "hermes", lambda: path, _host_block))
+ monkeypatch.setattr(mp, "_honcho_resolvers", lambda name: (lambda: "hermes", lambda: path, _host_block))
@pytest.mark.parametrize("corrupt", [True, False], ids=["unparseable-file-is-left-alone", "parseable-file-is-merged"])
diff --git a/tests/hermes_cli/test_web_memory_user_dir_provider.py b/tests/hermes_cli/test_web_memory_user_dir_provider.py
new file mode 100644
index 00000000000..9fb83150987
--- /dev/null
+++ b/tests/hermes_cli/test_web_memory_user_dir_provider.py
@@ -0,0 +1,89 @@
+"""A memory provider installed under ``$HERMES_HOME/plugins/`` (catalog install) keeps the
+Desktop surfaces a bundled copy has: host-block config storage and the OAuth connect routes
+resolve the provider's own ``client`` / ``oauth_flow`` modules through ``find_provider_dir``,
+not a hard-coded ``plugins.memory.<name>`` import that only the bundled copy satisfies."""
+
+import json
+import sys
+import textwrap
+
+import pytest
+
+_CLIENT = '''
+import json, os
+from pathlib import Path
+
+def resolve_active_host():
+ return "hermes"
+
+def resolve_config_path():
+ return Path(os.environ["HERMES_HOME"]) / "honcho.json"
+
+def _host_block(cfg, host):
+ return (cfg.get("hosts") or {}).get(host) or {}
+'''
+
+_OAUTH_FLOW = '''
+from . import client # relative import: only a real package load resolves it
+
+def start_loopback_flow_background():
+ return {"state": "pending", "config": str(client.resolve_config_path())}
+
+def get_flow_status():
+ return {"state": "idle"}
+'''
+
+_CONFIG_SCHEMA = '''
+from plugins.memory.config_schema import STORAGE_HONCHO_HOST_BLOCK, ProviderConfigSchema, ProviderField
+
+CONFIG_SCHEMA = ProviderConfigSchema(
+ name="honcho", label="Honcho (user dir)", storage=STORAGE_HONCHO_HOST_BLOCK,
+ fields=(ProviderField(key="workspace", label="Workspace", inline=True),),
+)
+'''
+
+
+def user_dir_honcho(monkeypatch, tmp_path, _isolate_hermes_home):
+ """A user-dir ``honcho`` with the bundled copy gone: empty bundled root and the bundled
+ module path blocked, the way a post-removal core + a catalog install look."""
+ import plugins.memory as memory_pkg
+ from hermes_constants import get_hermes_home
+
+ plugin_dir = get_hermes_home() / "plugins" / "honcho"
+ plugin_dir.mkdir(parents=True)
+ (plugin_dir / "__init__.py").write_text(
+ '"""fake provider: register_memory_provider"""\nfrom .client import resolve_active_host\n', encoding="utf-8"
+ )
+ for stem, source in (("client", _CLIENT), ("oauth_flow", _OAUTH_FLOW), ("config_schema", _CONFIG_SCHEMA)):
+ (plugin_dir / f"{stem}.py").write_text(textwrap.dedent(source), encoding="utf-8")
+ (get_hermes_home() / "honcho.json").write_text(
+ json.dumps({"hosts": {"hermes": {"workspace": "from-user-dir"}}}), encoding="utf-8"
+ )
+
+ monkeypatch.setattr(memory_pkg, "_MEMORY_PLUGINS_DIR", tmp_path / "no-bundled")
+ for name in ("plugins.memory.honcho", "plugins.memory.honcho.client", "plugins.memory.honcho.oauth_flow"):
+ monkeypatch.setitem(sys.modules, name, None)
+ return plugin_dir
+
+
+def test_user_dir_host_block_provider_serves_its_declared_config(user_dir_honcho):
+ from starlette.testclient import TestClient
+
+ from hermes_cli.web_server import _SESSION_HEADER_NAME, _SESSION_TOKEN, app
+
+ client = TestClient(app, headers={_SESSION_HEADER_NAME: _SESSION_TOKEN})
+ resp = client.get("/api/memory/providers/honcho/config", params={"surface": "declared"})
+
+ assert resp.status_code == 200, resp.text
+ (field,) = resp.json()["fields"]
+ assert (field["key"], field["value"]) == ("workspace", "from-user-dir")
+
+
+def test_user_dir_provider_oauth_flow_resolves_from_its_directory(user_dir_honcho):
+ from hermes_cli.memory_oauth import _resolve_flow
+
+ flow = _resolve_flow("honcho")
+
+ assert flow.__file__ == str(user_dir_honcho / "oauth_flow.py")
+ assert flow.start_loopback_flow_background()["state"] == "pending"