From e7d9e07dbc408063a40f701f7c2a57642edba5ef Mon Sep 17 00:00:00 2001 From: teknium1 <127238744+teknium1@users.noreply.github.com> Date: Sat, 12 Sep 2026 20:32:54 -0700 Subject: [PATCH] refactor(plugins): HERMES_HOME resolves through hermes_constants.get_hermes_home everywhere; no ~/.hermes fallbacks Four bundled plugins wrapped get_hermes_home() in a try/except that fell back to ~/.hermes on ImportError (a2a/protocol._hermes_home, photon/auth ._auth_json_path, google_chat adapter inline, openviking done in the previous commit). A bundled plugin cannot lose hermes_constants -- each already imports gateway.* / agent.* from the same tree -- so the fallback was dead code that was also wrong on Windows (%LOCALAPPDATA%/hermes) and under a profile override. telegram's gmail-triage verb path used Path.home()/".hermes" outright, ignoring profiles. mem0/_oss_providers baked os.path.expanduser("~/.hermes/mem0_qdrant") into VECTOR_PROVIDERS at import time, so the Qdrant default landed in the user's ~/.hermes for every profile; the default is now a lazy callable resolved by vector_default_config(provider_id) at setup time. a2a/security.py only changes its import (it borrowed protocol._hermes_home). Behavior change: on Windows and under profiles these paths now follow the active HERMES_HOME (they were previously anchored to ~/.hermes in the impossible fallback / at import time); the default-profile POSIX layout is unchanged. Test: tests/plugins/test_plugin_paths_follow_profile.py asserts each resolver (a2a conversations, photon auth.json, mem0 qdrant default, openviking log) lands inside a HERMES_HOME ContextVar override; sabotage red for the mem0 import-time constant and the photon ~/.hermes fallback. --- plugins/memory/mem0/_oss_providers.py | 11 ++++- plugins/memory/mem0/_setup.py | 6 +-- plugins/platforms/a2a/protocol.py | 13 ++--- plugins/platforms/a2a/security.py | 6 +-- plugins/platforms/google_chat/adapter.py | 8 +-- plugins/platforms/photon/auth.py | 9 ++-- plugins/platforms/telegram/adapter.py | 3 +- .../test_plugin_paths_follow_profile.py | 49 +++++++++++++++++++ 8 files changed, 75 insertions(+), 30 deletions(-) create mode 100644 tests/plugins/test_plugin_paths_follow_profile.py diff --git a/plugins/memory/mem0/_oss_providers.py b/plugins/memory/mem0/_oss_providers.py index 7fb87d998a..c6ced627fc 100644 --- a/plugins/memory/mem0/_oss_providers.py +++ b/plugins/memory/mem0/_oss_providers.py @@ -5,6 +5,8 @@ from __future__ import annotations import os from typing import Any +from hermes_constants import get_hermes_home + LLM_PROVIDERS: dict[str, dict[str, Any]] = { "openai": {"label": "OpenAI", "needs_key": True, "env_var": "OPENAI_API_KEY", "default_model": "gpt-5-mini", "base_url_key": "openai_base_url"}, "ollama": {"label": "Ollama (local)", "needs_key": False, "default_model": "llama3.1:8b", "default_url": "http://localhost:11434", "base_url_key": "ollama_base_url", "pip_dep": "ollama"}, @@ -16,7 +18,9 @@ EMBEDDER_PROVIDERS: dict[str, dict[str, Any]] = { } VECTOR_PROVIDERS: dict[str, dict[str, Any]] = { - "qdrant": {"label": "Qdrant", "default_config": {"path": os.path.expanduser("~/.hermes/mem0_qdrant")}, "pip_dep": "qdrant-client"}, + # Resolved lazily (see ``vector_default_config``): the profile home is a ContextVar at call time, + # not an import-time constant, and ``~/.hermes`` is wrong on Windows and under profiles. + "qdrant": {"label": "Qdrant", "default_config": {"path": lambda: str(get_hermes_home() / "mem0_qdrant")}, "pip_dep": "qdrant-client"}, "pgvector": { "label": "PGVector", "default_config": {"host": "localhost", "port": 5432, "user": os.getenv("USER", "postgres"), "dbname": "postgres"}, @@ -26,6 +30,11 @@ VECTOR_PROVIDERS: dict[str, dict[str, Any]] = { KNOWN_DIMS: dict[str, int] = {"text-embedding-3-small": 1536, "text-embedding-3-large": 3072, "text-embedding-ada-002": 1536, "nomic-embed-text": 768} +def vector_default_config(provider_id: str) -> dict[str, Any]: + """A vector store's ``default_config`` with callable defaults resolved for the active profile.""" + return {k: (v() if callable(v) else v) for k, v in VECTOR_PROVIDERS[provider_id]["default_config"].items()} + + SECTION_REGISTRIES = (("llm", LLM_PROVIDERS), ("embedder", EMBEDDER_PROVIDERS), ("vector_store", VECTOR_PROVIDERS)) diff --git a/plugins/memory/mem0/_setup.py b/plugins/memory/mem0/_setup.py index 9db123667c..c081c9fd94 100644 --- a/plugins/memory/mem0/_setup.py +++ b/plugins/memory/mem0/_setup.py @@ -18,7 +18,7 @@ from typing import Any from hermes_constants import get_hermes_home # noqa: F401 — patched by tests -from ._oss_providers import EMBEDDER_PROVIDERS, KNOWN_DIMS, LLM_PROVIDERS, SECTION_REGISTRIES, VECTOR_PROVIDERS, validate_oss_config +from ._oss_providers import EMBEDDER_PROVIDERS, KNOWN_DIMS, LLM_PROVIDERS, SECTION_REGISTRIES, VECTOR_PROVIDERS, validate_oss_config, vector_default_config _OLLAMA_URL = "http://localhost:11434" _PGVECTOR_CONTAINER, _PGVECTOR_IMAGE, _PGVECTOR_PASSWORD = "hermes-pgvector", "pgvector/pgvector:pg17", "hermes" @@ -123,7 +123,7 @@ def build_oss_config(flags: dict[str, str]) -> tuple[dict, dict[str, str]]: if dims: embedder_config["embedding_dims"] = dims vector_id = flags.get("oss_vector", "qdrant") - vector_config = dict(VECTOR_PROVIDERS[vector_id]["default_config"]) + vector_config = vector_default_config(vector_id) for key in _VECTOR_FLAG_KEYS.get(vector_id, ()): if val := flags.get(f"oss_vector_{key}"): vector_config[key] = int(val) if key == "port" else val @@ -404,7 +404,7 @@ def _setup_oss_interactive(hermes_home: str, config: dict) -> None: env_writes: dict[str, str] = {} llm_id, llm_def, llm_model, llm_url = _configure_model_provider("LLM", LLM_PROVIDERS, hermes_home, env_writes) embedder_id, _, embedder_model, embedder_url = _configure_model_provider("Embedder", EMBEDDER_PROVIDERS, hermes_home, env_writes, llm=(llm_id, llm_def)) - vector_items = [(v["label"], _VECTOR_DESCRIPTIONS.get(pid, lambda cfg: pid)(v.get("default_config", {}))) for pid, v in VECTOR_PROVIDERS.items()] + vector_items = [(v["label"], _VECTOR_DESCRIPTIONS.get(pid, lambda cfg: pid)(vector_default_config(pid))) for pid, v in VECTOR_PROVIDERS.items()] vector_id = list(VECTOR_PROVIDERS)[_curses_select("Vector Store", vector_items, 0)] # Auto-setup: ensure Ollama is running and models are pulled; ensure pgvector is reachable (offer Docker if not). ollama_models = [m for pid, m in ((llm_id, llm_model), (embedder_id, embedder_model)) if pid == "ollama"] diff --git a/plugins/platforms/a2a/protocol.py b/plugins/platforms/a2a/protocol.py index 1b3c2c5f35..707527a9a8 100644 --- a/plugins/platforms/a2a/protocol.py +++ b/plugins/platforms/a2a/protocol.py @@ -17,6 +17,7 @@ from pathlib import Path from typing import Any, Optional from gateway.platforms._shared import coerce_port as _coerce_int +from hermes_constants import get_hermes_home PROTOCOL_VERSION = "1.0" @@ -55,14 +56,6 @@ def now_iso() -> str: return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" -def _hermes_home() -> Path: - try: - from hermes_constants import get_hermes_home - return Path(get_hermes_home()) - except Exception: - return Path(os.path.expanduser("~/.hermes")) - - def build_agent_card(*, name: str, url: str, description: str, skills: Optional[list[dict]] = None, streaming: bool = False, push_notifications: bool = False, auth_required: bool = False, tenant: str = "") -> dict: @@ -437,7 +430,7 @@ class TaskStore: def _conv_path(context_id: str) -> Path: safe = "".join(c for c in (context_id or "default") if c.isalnum() or c in "-_") or "default" - return _hermes_home() / "a2a_conversations" / f"{safe}.jsonl" + return get_hermes_home() / "a2a_conversations" / f"{safe}.jsonl" def persist_message(context_id: str, role: str, text: str, task_id: str = "") -> None: @@ -469,7 +462,7 @@ def load_conversation(context_id: str, limit: int = 50) -> list[dict]: def list_conversations() -> list[str]: """Context-ids that have persisted conversations.""" - return sorted(p.stem for p in (_hermes_home() / "a2a_conversations").glob("*.jsonl")) + return sorted(p.stem for p in (get_hermes_home() / "a2a_conversations").glob("*.jsonl")) # ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ---- diff --git a/plugins/platforms/a2a/security.py b/plugins/platforms/a2a/security.py index cc3cf2dcf1..bb3affeb5f 100644 --- a/plugins/platforms/a2a/security.py +++ b/plugins/platforms/a2a/security.py @@ -201,10 +201,10 @@ def is_safe_callback_url(url: str, *, localhost_mode: Optional[bool] = None) -> def audit(direction: str, peer: str, task_id: str, summary: str) -> None: """Append an audit record (direction: inbound | outbound | push). Never raises.""" try: - from .protocol import _hermes_home + from hermes_constants import get_hermes_home rec = {"ts": time.time(), "direction": direction, "peer": peer, "task_id": task_id, "summary": (summary or "")[:500]} - _hermes_home().mkdir(parents=True, exist_ok=True) - with (_hermes_home() / "a2a_audit.jsonl").open("a", encoding="utf-8") as fh: + get_hermes_home().mkdir(parents=True, exist_ok=True) + with (get_hermes_home() / "a2a_audit.jsonl").open("a", encoding="utf-8") as fh: fh.write(json.dumps(rec, ensure_ascii=False) + "\n") except Exception: logger.debug("A2A: audit write failed", exc_info=True) diff --git a/plugins/platforms/google_chat/adapter.py b/plugins/platforms/google_chat/adapter.py index 8b89b29c24..4b2ee48e91 100644 --- a/plugins/platforms/google_chat/adapter.py +++ b/plugins/platforms/google_chat/adapter.py @@ -378,12 +378,8 @@ class GoogleChatAdapter(BasePlatformAdapter): # Last inbound thread per space: DMs get a NEW thread per top-level message but users # see one conversation, so thread_id leaves the source (stable session key) and is cached here. self._last_inbound_thread: Dict[str, str] = {} - try: - from hermes_constants import get_hermes_home as _get_hermes_home - _hermes_home = _get_hermes_home() - except (ModuleNotFoundError, ImportError): - _hermes_home = _Path.home() / ".hermes" - self._thread_count_store = _ThreadCountStore(_hermes_home / "google_chat_thread_counts.json") + from hermes_constants import get_hermes_home as _get_hermes_home + self._thread_count_store = _ThreadCountStore(_get_hermes_home() / "google_chat_thread_counts.json") # In-flight typing-card creates per chat_id: reserved BEFORE the API call so # concurrent _keep_typing calls wait instead of duplicating cards. self._typing_card_inflight: Dict[str, asyncio.Event] = {} diff --git a/plugins/platforms/photon/auth.py b/plugins/platforms/photon/auth.py index 198bfa5b43..86d8281d02 100644 --- a/plugins/platforms/photon/auth.py +++ b/plugins/platforms/photon/auth.py @@ -27,6 +27,7 @@ except ImportError: # pragma: no cover - httpx is a hermes dependency httpx = None # type: ignore[assignment] from gateway.platforms._shared import get_scoped_secret as _get_scoped_secret +from hermes_constants import get_hermes_home import contextlib logger = logging.getLogger(__name__) @@ -51,12 +52,8 @@ E164_RE = re.compile(r"^\+[1-9]\d{6,14}$") # -- auth.json helpers (shares the file with the rest of hermes-agent) ------------ def _auth_json_path() -> Path: - """``~/.hermes/auth.json`` honouring the active Hermes profile.""" - try: - from hermes_constants import get_hermes_home - return Path(get_hermes_home()) / "auth.json" - except Exception: - return Path(os.path.expanduser("~/.hermes")) / "auth.json" + """The active profile's ``auth.json`` (shared with the rest of hermes-agent).""" + return get_hermes_home() / "auth.json" def _load_auth() -> Dict[str, Any]: diff --git a/plugins/platforms/telegram/adapter.py b/plugins/platforms/telegram/adapter.py index c4c644c182..659dadaa96 100644 --- a/plugins/platforms/telegram/adapter.py +++ b/plugins/platforms/telegram/adapter.py @@ -4479,7 +4479,8 @@ class TelegramAdapter(BasePlatformAdapter): await query.answer(text=f"Unknown verb: {verb}") return script_name, extra_args, success_label, is_state_verb = entry - script_path = _Path.home() / ".hermes" / "scripts" / "gmail-triage" / script_name + from hermes_constants import get_hermes_home + script_path = get_hermes_home() / "scripts" / "gmail-triage" / script_name if not script_path.exists(): await query.answer(text=f"❌ {script_name} missing") logger.error("[%s] gmail-triage script missing: %s", self.name, script_path) diff --git a/tests/plugins/test_plugin_paths_follow_profile.py b/tests/plugins/test_plugin_paths_follow_profile.py new file mode 100644 index 0000000000..b51c6c5dca --- /dev/null +++ b/tests/plugins/test_plugin_paths_follow_profile.py @@ -0,0 +1,49 @@ +"""Plugin data paths follow the active profile's HERMES_HOME, including the ContextVar override. + +Several plugins carried a ``~/.hermes`` fallback (guarding an ImportError of ``hermes_constants`` +that cannot happen for a bundled plugin) or resolved the home at import time. Both are wrong on +Windows and under multiplex profile overrides. Every resolver below must land inside the override. +""" +from __future__ import annotations + +import pytest + +from hermes_constants import reset_hermes_home_override, set_hermes_home_override + + +def _a2a_conversation(home): + from plugins.platforms.a2a import protocol + return protocol._conv_path("peer-x") + + +def _photon_auth(home): + from plugins.platforms.photon import auth + return auth._auth_json_path() + + +def _mem0_qdrant(home): + from plugins.memory.mem0._oss_providers import vector_default_config + return vector_default_config("qdrant")["path"] + + +def _openviking_log(home): + import plugins.memory.openviking as ov + return ov.get_hermes_home() / ov._OPENVIKING_SERVER_LOG_RELATIVE_PATH + + +_RESOLVERS = {"a2a": _a2a_conversation, "photon": _photon_auth, "mem0-qdrant": _mem0_qdrant, + "openviking": _openviking_log} + + +@pytest.mark.parametrize("name", sorted(_RESOLVERS)) +def test_plugin_path_follows_profile_override(name, tmp_path, monkeypatch): + monkeypatch.setenv("HERMES_HOME", str(tmp_path / "default")) + monkeypatch.setenv("HOME", str(tmp_path / "user-home")) + profile = tmp_path / "profiles" / "b" + profile.mkdir(parents=True) + token = set_hermes_home_override(profile) + try: + resolved = str(_RESOLVERS[name](profile)) + finally: + reset_hermes_home_override(token) + assert resolved.startswith(str(profile)), f"{name} resolved {resolved!r} outside the active profile"