The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(memory): compact discovery/config-schema docs, fold CLI scan early-returns, dedupe hindsight setup/template request building
Tekniumb5721f7cc4a2
diff --git a/plugins/memory/__init__.py b/plugins/memory/__init__.pyindex 7b6b31c46ef..6496b77cf2c 100644--- a/plugins/memory/__init__.py+++ b/plugins/memory/__init__.py@@ -1,32 +1,10 @@-"""Memory provider plugin discovery.--Scans four sources for memory provider plugins:--1. Bundled providers: ``plugins/memory/<name>/`` (shipped with hermes-agent)-2. User-installed providers: ``$HERMES_HOME/plugins/<name>/``-3. Project-local providers: ``./.hermes/plugins/<name>/``, opt-in via- ``HERMES_ENABLE_PROJECT_PLUGINS``-4. Pip-installed providers: ``hermes_agent.memory_providers`` entry points--Directory providers must contain ``__init__.py`` with a class implementing-the MemoryProvider ABC. Pip packages expose a provider or ``register(ctx)``-callback through the entry-point group.--These are the same four sources the general ``PluginManager`` scans, but the-precedence is deliberately the reverse of its later-source-wins order: here-**bundled wins**, then user, then project, then entry point. A memory provider-is activated by name, so letting a directory dropped into the working tree-shadow a shipped provider would silently redirect the agent's memory. Changing-this order is a breaking change, not a cleanup.--Only ONE provider can be active at a time, selected via-``memory.provider`` in config.yaml.--Usage:- from plugins.memory import discover_memory_providers, load_memory_provider-- available = discover_memory_providers() # [(name, desc, available), ...]- provider = load_memory_provider("mnemosyne") # MemoryProvider instance+"""Memory provider plugin discovery: bundled ``plugins/memory/<name>/``, user+``$HERMES_HOME/plugins/<name>/``, project ``./.hermes/plugins/<name>/`` (opt-in via+HERMES_ENABLE_PROJECT_PLUGINS), then ``hermes_agent.memory_providers`` entry points.+Precedence is deliberately the REVERSE of PluginManager's later-source-wins:+bundled wins, then user, project, entry point — a provider is activated by name+(``memory.provider``, one at a time), so a directory dropped into the working tree+must never shadow a shipped provider. Changing this order is a breaking change."""from __future__ import annotations@@ -50,25 +28,16 @@ _MEMORY_PLUGINS_DIR = Path(__file__).parentENTRY_POINTS_GROUP = "hermes_agent.memory_providers"_REGISTERED_MEMORY_PROVIDER_SKILLS: dict[str, Path] = {}-# Synthetic parent package for user-installed providers, so they don't-# collide with bundled providers in sys.modules.+# Synthetic parent package so user-installed providers don't collide with bundled ones._USER_NAMESPACE = "_hermes_user_memory"_register_synthetic_package = _loader.register_synthetic_package_get_user_plugins_dir = _loader.user_plugins_dir-# ----------------------------------------------------------------------------# Directory helpers-# ----------------------------------------------------------------------------def _get_project_plugins_dir() -> Optional[Path]:- """Return ``./.hermes/plugins/`` or None if unavailable or not opted in.-- Gated on ``HERMES_ENABLE_PROJECT_PLUGINS`` exactly as the general- ``PluginManager`` gates its own project scan — a repository you merely- ``cd`` into must not be able to offer the agent a memory backend.- """+ """``./.hermes/plugins/`` or None. Gated on HERMES_ENABLE_PROJECT_PLUGINS like the+ PluginManager scan: a repo you merely ``cd`` into must not offer a memory backend."""try:from hermes_cli.plugins import _env_enabled@@ -135,16 +104,10 @@ def _iter_entry_points():def find_provider_dir(name: str) -> Optional[Path]:- """Resolve a provider name to its directory: bundled, user, project, then the- package directory of a pip entry-point provider.-- The entry-point case matters because two of a provider's files are read from- disk rather than imported: ``config_schema.py`` (loaded by path so the web- server never pulls in the agent runtime) and ``cli.py`` (loaded by- ``discover_plugin_cli_commands`` at argparse time). Without a directory a- pip-installed provider silently loses its dashboard config panel and its- ``hermes <provider>`` subcommands.- """+ """Provider name -> directory: bundled, user, project, then a pip entry point's+ package dir. The entry-point case matters because ``config_schema.py`` and+ ``cli.py`` are read from disk, not imported; without a directory a pip-installed+ provider silently loses its dashboard panel and ``hermes <provider>`` commands."""bundled = _MEMORY_PLUGINS_DIR / nameif bundled.is_dir() and (bundled / "__init__.py").exists():return bundled@@ -158,16 +121,10 @@ def find_provider_dir(name: str) -> Optional[Path]:def _entry_point_package_dir(entry_point) -> Optional[Path]:- """The directory of an entry point's module, resolved WITHOUT importing it.-- Discovery must stay free of third-party imports: ``find_provider_dir`` runs- from the dashboard and argparse setup, long before the operator has selected- a provider, so importing every installed candidate would run arbitrary code- on the strength of a package merely being present.-- Only package entry points (``pkg/__init__.py``) yield a directory — a bare- ``module.py`` has nowhere to put a sibling ``config_schema.py``.- """+ """Directory of an entry point's module, resolved WITHOUT importing it (discovery+ runs from the dashboard/argparse before a provider is selected; importing every+ candidate would run arbitrary code). Only package entry points yield a+ directory — a bare ``module.py`` has nowhere for a sibling ``config_schema.py``."""if entry_point is None:return Nonetry:@@ -190,40 +147,29 @@ def find_provider_entry_point(name: str):return next((ep for ep in _iter_entry_points() if ep.name == name), None)-# ----------------------------------------------------------------------------# Public API-# ----------------------------------------------------------------------------def list_memory_provider_names() -> List[str]:- """Cheap name-only listing: directory scan plus entry-point *enumeration*- (distribution metadata only — no provider import, no availability check),- so it is safe at module-import time (dashboard ``memory.provider`` dropdown).- """+ """Cheap name-only listing (directory scan + entry-point enumeration, no import or+ availability check) — safe at module-import time (dashboard dropdown)."""names = {name for name, _ in _iter_provider_dirs()}names.update(ep.name for ep in _iter_entry_points())return sorted(names)def discover_memory_providers() -> List[Tuple[str, str, bool]]:- """``[(name, description, is_available), ...]`` for directory then entry-point- providers; bundled wins on name collisions, then user directories, then pip."""- results = []- for name, child in _iter_provider_dirs():- results.append((- name,- _loader.read_plugin_description(child),- _loader.probe_availability(lambda c=child: _load_provider_from_dir(c, register_skills=False)),- ))+ """``[(name, description, is_available), ...]``; bundled wins on name collisions,+ then user directories, then pip."""+ results = [+ (name, _loader.read_plugin_description(child),+ _loader.probe_availability(lambda c=child: _load_provider_from_dir(c, register_skills=False)))+ for name, child in _iter_provider_dirs()+ ]seen = {name for name, _, _ in results}for entry_point in _iter_entry_points():if entry_point.name not in seen:seen.add(entry_point.name)- results.append((- entry_point.name, "",- _loader.probe_availability(- lambda ep=entry_point: _load_provider_from_entry_point(ep, register_skills=False)- ),- ))+ results.append((entry_point.name, "", _loader.probe_availability(+ lambda ep=entry_point: _load_provider_from_entry_point(ep, register_skills=False)+ )))return results@@ -232,24 +178,17 @@ def load_memory_provider(*,register_skills: Optional[bool] = None,) -> Optional["MemoryProvider"]:- """Load a MemoryProvider by name (bundled, user, project, then pip entry point).-- Skills register only when *name* is the configured active provider unless- ``register_skills`` is passed explicitly, so status/setup inspection of- inactive providers leaves no registry side effects.-- Returns None if the provider is not found or fails to load.- """+ """Load a MemoryProvider by name (bundled, user, project, then pip entry point);+ None if not found or failing to load. Skills register only for the configured+ active provider unless ``register_skills`` is explicit, so inspecting inactive+ providers leaves no registry side effects."""if register_skills is None:register_skills = name == _get_active_memory_provider()provider_dir = find_provider_dir(name)entry_point = None if provider_dir else find_provider_entry_point(name)if not provider_dir and entry_point is None:- logger.debug(- "Memory provider '%s' not found in bundled, user plugins, or entry points",- name,- )+ logger.debug("Memory provider '%s' not found in bundled, user plugins, or entry points", name)return Nonedef _load(_dir):@@ -325,8 +264,7 @@ def _load_provider_from_dir(*,register_skills: bool = True,) -> Optional["MemoryProvider"]:- """Import a provider module and extract its MemoryProvider: ``register(ctx)``- first (how our plugins are written), else instantiate a top-level subclass."""+ """Import a provider module; ``register(ctx)`` first, else a top-level subclass."""name = provider_dir.namemod = _loader.load_plugin_module(_module_name(provider_dir, name), provider_dir,@@ -342,10 +280,9 @@ def _load_provider_from_dir(try:mod.register(collector)except Exception as e:- # A raise AFTER register_memory_provider() must not cost us the- # provider. Falling through to the subclass scan below would- # discard the instance the plugin configured and hand back a bare- # second one — a silent downgrade that looks like success.+ # A raise AFTER register_memory_provider() must not cost us the provider:+ # falling through to the subclass scan would hand back a bare second+ # instance — a silent downgrade that looks like success.if collector.provider is None:logger.debug("register() failed for %s: %s", name, e)else:@@ -361,13 +298,9 @@ def _load_provider_from_dir(class _ProviderCollector:- """Plugin context for memory providers.-- Captures ``register_memory_provider`` directly — that is the one call the- exclusive activation path owns — and delegates everything else to a real- ``PluginContext`` (see ``__getattr__``), so a memory provider has the same- registration surface as any other plugin.- """+ """Plugin context for memory providers: captures ``register_memory_provider``+ (the one call the activation path owns) and delegates other ``register_*``+ calls to a real ``PluginContext`` so providers have the full plugin surface."""def __init__(self, name: str, *, register_skills: bool = True):self.name = name@@ -379,17 +312,9 @@ class _ProviderCollector:self.provider = providerdef register_skill(self, *args, **kwargs):- """Forward plugin-provided skills to the general plugin registry.-- Handled explicitly rather than through ``__getattr__`` because skills- are tracked for pruning: switching the active provider has to retract- the skills the previous one registered, which needs the qualified name- and resolved path recorded here.-- Gated on ``register_skills`` so merely *inspecting* an inactive- provider — ``hermes memory status``, the setup picker — leaves no- registry side effects behind.- """+ """Forward skills to the plugin registry, tracking qualified name + path so+ switching the active provider can retract the previous one's skills. Gated+ on ``register_skills`` so inspecting an inactive provider has no side effects."""if not self._register_skills:returntry:@@ -410,17 +335,9 @@ class _ProviderCollector:pass # CLI registration happens via discover_plugin_cli_commands()def __getattr__(self, attr: str):- """Delegate any other ``register_*`` call to a real ``PluginContext``.-- A hand-maintained stub used to silently drop calls it knew- (``register_tool``, ``register_hook``) and raise ``AttributeError`` on- ones it didn't (``register_auxiliary_task``), which surfaced as- "register() failed" and cost the provider. Delegating means this can- never drift behind ``PluginContext`` again.-- Only ``register_*`` is forwarded. Everything else raises normally, so a- typo still fails loudly rather than being absorbed.- """+ """Delegate any other ``register_*`` call to a real ``PluginContext`` (a+ hand-maintained stub drifted: unknown calls raised and cost the provider).+ Non-``register_*`` attributes raise normally so a typo still fails loudly."""if not attr.startswith("register_"):raise AttributeError(attr)@@ -428,23 +345,15 @@ class _ProviderCollector:try:return self._plugin_context().__getattribute__(attr)(*args, **kwargs)except Exception as exc:- # A secondary registration must not cost the provider itself —- # by the time these run, register_memory_provider has usually- # already handed us the instance the agent needs.- logger.warning(- "Memory provider '%s' failed to %s: %s", self.name, attr, exc- )+ # A secondary registration must not cost the provider itself.+ logger.warning("Memory provider '%s' failed to %s: %s", self.name, attr, exc)return Nonereturn _forwarddef _plugin_context(self):- """A real ``PluginContext`` for this provider, built once on demand.-- Lazy because the common case — a provider that only calls- ``register_memory_provider`` — must not pay for importing the general- plugin manager, which discovery touches on every hermes startup.- """+ """A real ``PluginContext``, built once on demand: the common provider that only+ calls ``register_memory_provider`` must not pay for importing the plugin manager."""if self._context is None:from hermes_cli.plugins import PluginContext, PluginManifest, get_plugin_manager@@ -473,11 +382,8 @@ def _prune_inactive_memory_provider_skills(from hermes_cli.plugins import get_plugin_managermanager = get_plugin_manager()- for qualified_name, registered_path in list(- _REGISTERED_MEMORY_PROVIDER_SKILLS.items()- ):- namespace, _, _ = qualified_name.partition(":")- if namespace == active_provider:+ for qualified_name, registered_path in list(_REGISTERED_MEMORY_PROVIDER_SKILLS.items()):+ if qualified_name.partition(":")[0] == active_provider:continueif manager.find_plugin_skill(qualified_name) == registered_path:manager.remove_plugin_skill(qualified_name)@@ -485,68 +391,44 @@ def _prune_inactive_memory_provider_skills(def discover_plugin_cli_commands() -> List[dict]:- """CLI commands for the **active** memory plugin only (``memory.provider``).-- Lightweight: imports only the active plugin's ``cli.py`` (looking for- ``register_cli(subparser)``), never the provider module, so it is safe during- argparse setup. Returns at most one dict with keys ``name``, ``help``,- ``description``, ``setup_fn``, ``handler_fn``, ``plugin``.- """- results: List[dict] = []- if not _MEMORY_PLUGINS_DIR.is_dir():- return results-- active_provider = _get_active_memory_provider()- if not active_provider:- return results-- plugin_dir = find_provider_dir(active_provider)- if not plugin_dir:- return results-- cli_file = plugin_dir / "cli.py"- if not cli_file.exists():- return results+ """CLI commands for the **active** memory plugin only. Imports just its ``cli.py``+ (``register_cli(subparser)``), never the provider module, so it is safe during+ argparse setup. At most one dict: name/help/description/setup_fn/handler_fn/plugin."""+ active_provider = _get_active_memory_provider() if _MEMORY_PLUGINS_DIR.is_dir() else None+ plugin_dir = find_provider_dir(active_provider) if active_provider else None+ if not plugin_dir or not (plugin_dir / "cli.py").exists():+ return []module_name = _module_name(plugin_dir, active_provider) + ".cli"try:- if module_name in sys.modules:- cli_mod = sys.modules[module_name]- else:+ cli_mod = sys.modules.get(module_name)+ if cli_mod is None:if not _is_bundled(plugin_dir):- # cli.py imports as _hermes_user_memory.<name>.cli, usually before- # the provider itself is loaded. Register its parent packages so- # relative imports inside cli.py resolve without executing the- # plugin's __init__.py. The shell has no __file__, so- # _load_provider_from_dir() still loads the real module later.+ # cli.py imports as _hermes_user_memory.<name>.cli, usually before the+ # provider is loaded: register parent packages so its relative imports+ # resolve without executing the plugin's __init__.py (the shell has no+ # __file__, so _load_provider_from_dir() still loads the real module)._register_synthetic_package(_USER_NAMESPACE, [])- _register_synthetic_package(- f"{_USER_NAMESPACE}.{active_provider}", [str(plugin_dir)]- )- spec = importlib.util.spec_from_file_location(module_name, str(cli_file))+ _register_synthetic_package(f"{_USER_NAMESPACE}.{active_provider}", [str(plugin_dir)])+ spec = importlib.util.spec_from_file_location(module_name, str(plugin_dir / "cli.py"))if not spec or not spec.loader:- return results+ return []cli_mod = importlib.util.module_from_spec(spec)sys.modules[module_name] = cli_modspec.loader.exec_module(cli_mod)register_cli = getattr(cli_mod, "register_cli", None)if not callable(register_cli):- return results-+ return []desc = _loader.read_plugin_description(plugin_dir)- handler_fn = getattr(cli_mod, f"{active_provider}_command", None) or \- getattr(cli_mod, "honcho_command", None)-- results.append({+ return [{"name": active_provider,"help": desc or f"Manage {active_provider} memory plugin","description": desc or "","setup_fn": register_cli,- "handler_fn": handler_fn,+ "handler_fn": getattr(cli_mod, f"{active_provider}_command", None) or getattr(cli_mod, "honcho_command", None),"plugin": active_provider,- })+ }]except Exception as e:logger.debug("Failed to scan CLI for memory plugin '%s': %s", active_provider, e)-- return results+ return []diff --git a/plugins/memory/config_schema.py b/plugins/memory/config_schema.pyindex 1af9844eff3..d558ab7630c 100644--- a/plugins/memory/config_schema.py+++ b/plugins/memory/config_schema.py@@ -1,15 +1,9 @@-"""Declarative configuration schema for memory provider plugins.--Each provider *declares* its configurable surface in a ``config_schema.py`` next-to its ``__init__.py`` (fields, kinds, secrets, select options); one generic-renderer in the desktop UI and one generic ``GET/PUT-/api/memory/providers/{name}/config`` endpoint pair drive the whole experience.--Schema files are loaded by path, never via package import: plugin ``__init__.py``-files pull in the agent runtime, which must not load into the web server. A-``config_schema.py`` may only import from this module, and this module is pure-data (nothing from the config/env layer). ``web_server`` owns the read/write-logic, dispatching on ``ProviderConfigSchema.storage``.+"""Declarative config schema for memory provider plugins: each declares its fields in+a ``config_schema.py`` beside ``__init__.py``; one generic renderer and one+``GET/PUT /api/memory/providers/{name}/config`` pair drive the UI. Schema files are+loaded by path, never imported as a package (plugin ``__init__`` pulls in the agent+runtime, which must not load into the web server); they may import only this+pure-data module. ``web_server`` owns read/write, dispatching on ``storage``."""from __future__ import annotations@@ -44,15 +38,10 @@ class ProviderFieldOption:@dataclass(frozen=True)class ProviderField:- """One configurable field on a memory provider.-- Stored in exactly one place by ``kind``: non-secret kinds go to the provider's- storage backend under ``key``; ``secret`` goes to the env store under- ``env_key`` and is never read back over the API (only an ``is_set`` flag).- ``aliases``/``env_fallbacks`` read legacy values from earlier CLI/env setup.- ``inline`` marks the compact-panel subset; the rest appear only in the- full-config modal, bucketed by ``group``.- """+ """One configurable field. Stored in exactly one place by ``kind``: non-secret+ kinds under ``key`` in the provider's storage; ``secret`` in the env store under+ ``env_key``, never read back (only ``is_set``). ``aliases``/``env_fallbacks`` read+ legacy values; ``inline`` marks the compact-panel subset (rest: modal, by ``group``)."""key: strlabel: str@@ -98,11 +87,8 @@ _SCHEMA_CACHE: dict[str, ProviderConfigSchema] = {}def get_provider_config_schema(name: str) -> ProviderConfigSchema | None:- """``CONFIG_SCHEMA`` declared by provider ``name``; None (no panel) without a ``config_schema.py``.-- The cache keys on the resolved schema file, not the name: user-installed- plugins are per-profile, so one profile's lookup must never answer for another's.- """+ """``CONFIG_SCHEMA`` of provider ``name``; None (no panel) without a ``config_schema.py``.+ Cached by resolved file path, not name: user plugins are per-profile."""from plugins.memory import find_provider_dirprovider_dir = find_provider_dir(name)diff --git a/plugins/memory/hindsight/embedded.py b/plugins/memory/hindsight/embedded.pyindex 3283dad9be8..f97a3210aae 100644--- a/plugins/memory/hindsight/embedded.py+++ b/plugins/memory/hindsight/embedded.py@@ -1,6 +1,5 @@-"""Local-embedded Hindsight runtime helpers: import probe, install hint, the-per-profile env file the standalone ``hindsight-embed`` daemon consumes, and the-daemon health-grace env export."""+"""Local-embedded Hindsight runtime: import probe, install hint, the per-profile env+file the standalone ``hindsight-embed`` daemon consumes, and the health-grace export."""from __future__ import annotations@@ -17,14 +16,12 @@ from .settings import _DEFAULT_IDLE_TIMEOUT, _daemon_llm_provider, _parse_int_selogger = logging.getLogger(__name__.rpartition(".")[0])-# Read by hindsight_embed.daemon_embed_manager AT IMPORT TIME (module-level-# constant): how long to wait for a slow /health before declaring the daemon-# stale and killing it. On resource-contended hosts a busy daemon can exceed-# the upstream 2s check and get needlessly restarted, so it's plugin config.+# Read by hindsight_embed.daemon_embed_manager AT IMPORT TIME: how long to wait+# for a slow /health before killing the daemon as stale. Busy hosts exceed the+# upstream 2s check and get needlessly restarted, so it's plugin config._PORT_HEALTH_GRACE_ENV = "HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT"-# Markers of a stale embedded-daemon connection (the client is recreated and-# the operation retried once).+# Stale embedded-daemon connection markers (client recreated, operation retried once)._RETRIABLE_CONNECTION_MARKERS = ("cannot connect to host","connection refused",@@ -34,53 +31,39 @@ _RETRIABLE_CONNECTION_MARKERS = (def _export_port_health_grace_timeout(config: dict[str, Any]) -> None:- """Export the daemon health grace timeout to the process env.-- Must run BEFORE ``hindsight_embed.daemon_embed_manager`` is imported. Only- set when the user configured a value; ``setdefault`` so an explicit env- override always wins.- """+ """Export the daemon health grace timeout BEFORE ``daemon_embed_manager`` is+ imported. Only when configured; ``setdefault`` so an explicit env override wins."""raw = config.get("port_health_grace_timeout")if raw is None or raw == "":returntry:seconds = float(raw)except (TypeError, ValueError):- logger.warning("Invalid Hindsight port_health_grace_timeout %r; ignoring.", raw)- return- if seconds < 0:- logger.warning("Negative Hindsight port_health_grace_timeout %r; ignoring.", raw)+ seconds = None+ if seconds is None or seconds < 0:+ logger.warning("%s Hindsight port_health_grace_timeout %r; ignoring.",+ "Invalid" if seconds is None else "Negative", raw)returnos.environ.setdefault(_PORT_HEALTH_GRACE_ENV, repr(seconds))def _check_local_runtime() -> tuple[bool, str | None]:- """Return whether the local embedded Hindsight stack imports cleanly.-- On older CPUs NumPy can raise at import before the daemon starts; report- "unavailable" so Hermes degrades instead of retrying a broken backend.- ``sentence_transformers`` is imported too: ``hindsight``/``hindsight_embed``- import fine even when the embedding stack is broken, and without this the- probe (and ``hermes memory status``) would stay green while the daemon- aborts on every retain/recall.- """+ """Whether the local embedded stack imports cleanly (older CPUs: NumPy can raise+ at import, so Hermes degrades instead of retrying a broken backend).+ ``sentence_transformers`` is probed too: ``hindsight`` imports fine with a broken+ embedding stack, and the daemon would then abort on every retain/recall."""try:- importlib.import_module("hindsight")- importlib.import_module("hindsight_embed.daemon_embed_manager")- importlib.import_module("sentence_transformers")+ for module in ("hindsight", "hindsight_embed.daemon_embed_manager", "sentence_transformers"):+ importlib.import_module(module)return True, Noneexcept Exception as exc:return False, str(exc)def _local_runtime_hint(reason: str | None) -> str:- """Install guidance when the local_embedded runtime is missing.-- The top-level ``hindsight`` module ships only with ``hindsight-all``;- ``plugin.yaml`` declares just ``hindsight-client`` (cloud/local_external),- so a hand-written config, the legacy ``"mode": "local"`` alias, or a- restored backup hits ``ModuleNotFoundError: No module named 'hindsight'``.- """+ """Install guidance when the local_embedded runtime is missing: ``plugin.yaml``+ declares only ``hindsight-client``, so a hand-written config, the legacy+ ``"mode": "local"`` alias or a restored backup hits ``No module named 'hindsight'``."""text = (reason or "").lower()if "no module named" in text and ("hindsight'" in text or 'hindsight"' in textor "hindsight_embed" in text):@@ -95,11 +78,8 @@ def _local_runtime_hint(reason: str | None) -> str:def _load_simple_env(path) -> dict[str, str]:- """Parse a KEY=VALUE env file, ignoring comments and blank lines.-- utf-8-sig, not utf-8: also used on the Hermes .env during post_setup, where- a Notepad BOM would otherwise stick to the first key.- """+ """Parse a KEY=VALUE env file (comments/blank lines ignored). utf-8-sig: also used+ on the Hermes .env during post_setup, where a Notepad BOM would stick to the first key."""if not path.exists():return {}values: dict[str, str] = {}@@ -144,9 +124,8 @@ def _build_embedded_profile_env(config: dict[str, Any], *, llm_api_key: str | Nodef _secure_write_profile_env(profile_env: Path, content: str) -> None:- """Create/overwrite *profile_env* owner-only (0600). The file carries the- daemon's plaintext LLM API key, so a pre-existing file is tightened BEFORE- the new secret bytes are written."""+ """Create/overwrite *profile_env* owner-only (0600); a pre-existing file is+ tightened BEFORE the plaintext LLM API key is written."""if profile_env.exists():try:os.chmod(profile_env, 0o600)@@ -158,8 +137,7 @@ def _secure_write_profile_env(profile_env: Path, content: str) -> None:def _validate_profile_env_permissions(profile_env: Path) -> None:- """Post-write check: the secret file must be owner-only on POSIX (Windows- ACLs aren't modelled by mode bits, so skipped there)."""+ """Post-write check: owner-only on POSIX (Windows ACLs aren't mode bits; skipped)."""if os.name != "posix":returnimport stat@@ -177,8 +155,8 @@ def _validate_profile_env_permissions(profile_env: Path) -> None:def _materialize_embedded_profile_env(config: dict[str, Any], *, llm_api_key: str | None = None) -> Path:- """Write the profile env file; never leave a plaintext key behind in a file- whose permissions could not be verified."""+ """Write the profile env file; never leave a plaintext key in a file whose+ permissions could not be verified."""profile_env = _embedded_profile_env_path(config)profile_env.parent.mkdir(parents=True, exist_ok=True)env_values = _build_embedded_profile_env(config, llm_api_key=llm_api_key)diff --git a/plugins/memory/hindsight/settings.py b/plugins/memory/hindsight/settings.pyindex 7c436d692d0..a23f1f9ea0f 100644--- a/plugins/memory/hindsight/settings.py+++ b/plugins/memory/hindsight/settings.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport jsonimport logging+import refrom typing import Any, List# Log under the plugin package's own logger name (loader-path independent).@@ -15,15 +16,13 @@ _DEFAULT_LOCAL_URL = "http://localhost:8888"_MIN_CLIENT_VERSION = "0.6.1"_DEFAULT_TIMEOUT = 120 # seconds — cloud API can take 30-40s per request_DEFAULT_IDLE_TIMEOUT = 300 # seconds — Hindsight embedded daemon default-# ``metadata.source`` stamped on retained memories — OPT-IN, empty by default:-# AGENTS.md forbids on-by-default third-party attribution tags. Set via the-# ``retain_source`` config key or HINDSIGHT_RETAIN_SOURCE.+# ``metadata.source`` on retained memories is OPT-IN (AGENTS.md forbids+# on-by-default attribution tags): ``retain_source`` / HINDSIGHT_RETAIN_SOURCE._DEFAULT_RETAIN_SOURCE = ""# Hindsight brand mark (eye ringed by graph nodes) for the recall/retain indicators._HINDSIGHT_GLYPH = "👁️"-# Hindsight 0.5.0 added ``update_mode='append'`` on retain. Without it, reusing a-# stable session-scoped document_id silently overwrites prior turns server-side,-# so older APIs keep the per-process unique document_id fallback.+# Hindsight 0.5.0 added ``update_mode='append'``; older APIs would silently+# overwrite prior turns under a stable document_id, so they keep the per-process id._MIN_VERSION_FOR_UPDATE_MODE_APPEND = "0.5.0"_VALID_BUDGETS = {"low", "mid", "high"}_PROVIDER_DEFAULT_MODELS = {@@ -72,7 +71,7 @@ def _normalize_retain_tags(value: Any) -> List[str]:try:parsed = json.loads(text)except Exception:- parsed = None+ passraw_items = parsed if isinstance(parsed, list) else text.split(",")else:raw_items = [value]@@ -85,14 +84,10 @@ def _normalize_retain_tags(value: Any) -> List[str]:def _normalize_observation_scopes(value: Any) -> Any:- """Normalize an observation_scopes value to a Hindsight-accepted form.-- Returns ``None`` (nothing configured; Hindsight applies its ``combined``- default), a keyword string, or ``list[list[str]]`` (one inner list per- consolidation pass). Accepts a keyword, a JSON-encoded list, a flat list of- tags (one scope), or a list of tag-lists. Anything unrecognized yields- ``None`` so we never send an invalid payload.- """+ """Normalize observation_scopes to a keyword string, ``list[list[str]]`` (one inner+ list per consolidation pass), or ``None`` (Hindsight's ``combined`` default).+ Accepts a keyword, a JSON-encoded list, a flat tag list (one scope) or a list of+ tag-lists; anything unrecognized -> ``None`` so we never send an invalid payload."""if isinstance(value, str):text = value.strip()if text in _OBSERVATION_SCOPE_KEYWORDS:@@ -120,8 +115,8 @@ def _normalize_observation_scopes(value: Any) -> Any:def _sanitize_bank_segment(value: str) -> str:- """Make a bank_id placeholder URL/filesystem safe: non ``[A-Za-z0-9_-]``- runs become a single dash; leading/trailing dashes and underscores are stripped."""+ """URL/filesystem-safe bank_id placeholder: runs outside ``[A-Za-z0-9_-]`` (per+ ``str.isalnum``) become one dash; leading/trailing ``-``/``_`` are stripped."""if not value:return ""out = []@@ -137,11 +132,9 @@ def _sanitize_bank_segment(value: str) -> str:def _resolve_bank_id_template(template: str, fallback: str, **placeholders: str) -> str:- """Render a bank_id template ({profile}, {workspace}, {platform}, {user},- {session}); each placeholder is sanitized first. Empty placeholders render- as "" and the dash/underscore runs they leave are collapsed, e.g.- ``hermes-{user}`` with no user becomes ``hermes``. Empty template or an- invalid placeholder falls back to *fallback*."""+ """Render a bank_id template ({profile}, {workspace}, {platform}, {user}, {session}),+ sanitizing each placeholder; the ``-``/``_`` runs empty placeholders leave are+ collapsed (``hermes-{user}`` -> ``hermes``). Empty/invalid template -> *fallback*."""if not template:return fallbacksanitized = {k: _sanitize_bank_segment(v) for k, v in placeholders.items()}@@ -151,8 +144,6 @@ def _resolve_bank_id_template(template: str, fallback: str, **placeholders: str)logger.warning("Invalid bank_id_template %r: %s — using fallback %r",template, exc, fallback)return fallback- while "--" in rendered:- rendered = rendered.replace("--", "-")- while "__" in rendered:- rendered = rendered.replace("__", "_")+ rendered = re.sub(r"-{2,}", "-", rendered)+ rendered = re.sub(r"_{2,}", "_", rendered)return rendered.strip("-_") or fallbackdiff --git a/plugins/memory/hindsight/setup.py b/plugins/memory/hindsight/setup.pyindex f5e0bddc6a2..1442c00f50c 100644--- a/plugins/memory/hindsight/setup.py+++ b/plugins/memory/hindsight/setup.py@@ -52,8 +52,8 @@ def _select(title: str, items: list, values: list, current) -> str | None:def _write_env(env_path: Path, env_writes: dict) -> None:- """Update keys in place (BOM-tolerant read so a Notepad BOM can't glue- U+FEFF onto the first key and cause a duplicate line), append the rest."""+ """Update keys in place (BOM-tolerant read: a Notepad BOM would glue U+FEFF onto+ the first key and duplicate the line), append the rest."""env_path.parent.mkdir(parents=True, exist_ok=True)existing = env_path.read_text(encoding="utf-8-sig").splitlines() if env_path.exists() else []updated = set()@@ -113,8 +113,7 @@ def run_setup(provider, hermes_home: str, config: dict) -> None:provider_config["llm_provider"] = llm_providerprint("\n Checking dependencies...")- # Environment-aware install: sealed hosted venvs redirect to the durable- # data-volume target instead of writing to /opt/hermes.+ # Environment-aware install: sealed hosted venvs redirect to the durable data volume.from tools.lazy_deps import install_specsdeps = ["hindsight-all"] if mode == "local_embedded" else [f"hindsight-client>={_MIN_CLIENT_VERSION}"]@@ -172,25 +171,20 @@ def run_setup(provider, hermes_home: str, config: dict) -> None:provider_config.setdefault("bank_id", "hermes")provider_config.setdefault("recall_budget", "mid")# Preserve explicit 0 timeouts instead of treating them as blank.- timeout_val = provider_config.get("timeout")- if timeout_val is None:- timeout_val = _DEFAULT_TIMEOUT- provider_config["timeout"] = timeout_val- env_writes["HINDSIGHT_TIMEOUT"] = str(timeout_val)+ timeouts = [("timeout", "HINDSIGHT_TIMEOUT", _DEFAULT_TIMEOUT)]if mode == "local_embedded":- idle_timeout_val = provider_config.get("idle_timeout")- if idle_timeout_val is None:- idle_timeout_val = _DEFAULT_IDLE_TIMEOUT- provider_config["idle_timeout"] = idle_timeout_val- env_writes["HINDSIGHT_IDLE_TIMEOUT"] = str(idle_timeout_val)+ timeouts.append(("idle_timeout", "HINDSIGHT_IDLE_TIMEOUT", _DEFAULT_IDLE_TIMEOUT))+ for key, env_key, default in timeouts:+ value = provider_config.get(key)+ provider_config[key] = value = default if value is None else value+ env_writes[env_key] = str(value)config["memory"]["provider"] = "hindsight"save_config(config)provider.save_config(provider_config, hermes_home)if env_writes:_write_env(Path(hermes_home) / ".env", env_writes)- # Starter template only for cloud / local_external — the API is reachable- # now; local_embedded's daemon isn't up during setup.+ # Starter template only where the API is reachable now (local_embedded's daemon isn't up).if _hs_templates.supported_for_mode(mode):_offer_starter_template(mode, provider_config, env_writes)diff --git a/plugins/memory/hindsight/templates.py b/plugins/memory/hindsight/templates.pyindex f053b34c314..594a5503418 100644--- a/plugins/memory/hindsight/templates.py+++ b/plugins/memory/hindsight/templates.py@@ -1,13 +1,7 @@-"""Starter bank templates for the Hindsight memory-provider setup wizard.--Fetches the Hindsight Bank Templates catalog, filters to templates tagged for-the ``hermes`` integration, and applies a chosen manifest to the user's bank-via the import API (``POST /v1/default/banks/{bank}/import``, which creates the-bank if it doesn't exist).--Kept out of ``__init__`` so the wizard logic stays small and testable. The-catalog source is overridable with ``HINDSIGHT_TEMPLATES_URL`` (e.g. to pin a-version or point at a mirror).+"""Starter bank templates for the Hindsight setup wizard: fetch the Bank Templates+catalog, filter to the ``hermes`` integration, apply a manifest via+``POST /v1/default/banks/{bank}/import`` (creates the bank if missing).+Catalog source overridable with ``HINDSIGHT_TEMPLATES_URL`` (pin/mirror)."""from __future__ import annotations@@ -22,16 +16,14 @@ from hermes_cli.urllib_security import open_credentialed_urllogger = logging.getLogger(__name__)-# The Bank Templates catalog lives in the Hindsight docs repo and is the same-# file that powers hindsight.vectorize.io/templates.+# Same file that powers hindsight.vectorize.io/templates._DEFAULT_CATALOG_URL = ("https://raw.githubusercontent.com/vectorize-io/hindsight/main/""hindsight-docs/src/data/templates.json")_HTTP_TIMEOUT = 15-# The starter-template step needs the API reachable during setup. A-# local_embedded daemon isn't running yet at that point, so it's skipped there.+# The API must be reachable during setup; a local_embedded daemon isn't up yet.SUPPORTED_MODES = ("cloud", "local_external")@@ -63,30 +55,27 @@ def fetch_manifest(entry: dict, url: str | None = None) -> dict:return _get_json(manifest_url)-def apply_template(api_url: str, bank_id: str, api_key: str | None, manifest: dict) -> None:- """Apply a manifest to a bank via the import endpoint. Raises on failure."""- endpoint = f"{api_url.rstrip('/')}/v1/default/banks/{bank_id}/import"- data = json.dumps(manifest).encode("utf-8")- headers = {"Content-Type": "application/json"}+def _bank_request(api_url: str, bank_id: str, api_key: str | None, action: str, **kwargs) -> urllib.request.Request:+ headers = dict(kwargs.pop("headers"))if api_key:headers["Authorization"] = f"Bearer {api_key}"- req = urllib.request.Request(endpoint, data=data, headers=headers, method="POST") # noqa: S310+ endpoint = f"{api_url.rstrip('/')}/v1/default/banks/{bank_id}/{action}"+ return urllib.request.Request(endpoint, headers=headers, **kwargs) # noqa: S310+++def apply_template(api_url: str, bank_id: str, api_key: str | None, manifest: dict) -> None:+ """Apply a manifest to a bank via the import endpoint. Raises on failure."""+ req = _bank_request(api_url, bank_id, api_key, "import", data=json.dumps(manifest).encode("utf-8"),+ headers={"Content-Type": "application/json"}, method="POST")with open_credentialed_url(req, timeout=_HTTP_TIMEOUT) as resp:resp.read() # drain; open_credentialed_url raises HTTPError on non-2xxdef probe_existing_customization(api_url: str, bank_id: str, api_key: str | None) -> bool:- """Best-effort: True if the bank already has template-level config, mental- models, or directives — i.e. applying a template would overwrite settings.-- A missing bank, or any error, is treated as "not customized": the step must- never block on this probe.- """- endpoint = f"{api_url.rstrip('/')}/v1/default/banks/{bank_id}/export"- headers = {"Accept": "application/json"}- if api_key:- headers["Authorization"] = f"Bearer {api_key}"- req = urllib.request.Request(endpoint, headers=headers) # noqa: S310+ """Best-effort: True if the bank already has template-level config, mental models+ or directives (a template would overwrite them). A missing bank or any error+ counts as "not customized": the step must never block on this probe."""+ req = _bank_request(api_url, bank_id, api_key, "export", headers={"Accept": "application/json"})try:with open_credentialed_url(req, timeout=_HTTP_TIMEOUT) as resp:data = json.loads(resp.read().decode("utf-8"))@@ -105,12 +94,9 @@ def run_template_step(cancelled,log=print,) -> str | None:- """Drive the wizard's starter-template step.-- ``select(title, items, default, cancel_returns)`` is the picker (injected so- this is testable without curses). Returns the applied template id, or None- if skipped/blank/failed. Never raises — the template is a nice-to-have.- """+ """Wizard starter-template step. ``select(title, items, default, cancel_returns)``+ is the picker (injected: testable without curses). Returns the applied template+ id, or None if skipped/blank/failed. Never raises — a template is a nice-to-have."""try:entries = fetch_hermes_templates()except Exception as e: # network/parse — non-fatal@@ -127,9 +113,8 @@ def run_template_step(entry = entries[idx]- # If the bank is already configured (re-running setup on an existing bank),- # applying a template overwrites its config and upserts its models/directives.- # Confirm before clobbering.+ # Re-running setup on a configured bank: a template overwrites its config and+ # upserts models/directives — confirm before clobbering.if probe_existing_customization(api_url, bank_id, api_key):confirm = select(f" Bank '{bank_id}' already has memory settings — apply this template on top?",diff --git a/plugins/memory/query_rewrite.py b/plugins/memory/query_rewrite.pyindex 03707ef26b5..8789239012a 100644--- a/plugins/memory/query_rewrite.py+++ b/plugins/memory/query_rewrite.py@@ -62,10 +62,10 @@ def _extract_response_text(response: Any) -> str:return ""if isinstance(content, str):return content- if isinstance(content, list):- texts = (part.get("text") if isinstance(part, dict) else getattr(part, "text", None) for part in content)- return "".join(t for t in texts if isinstance(t, str))- return ""+ if not isinstance(content, list):+ return ""+ texts = (part.get("text") if isinstance(part, dict) else getattr(part, "text", None) for part in content)+ return "".join(t for t in texts if isinstance(t, str))def _normalize_rewrite(text: str) -> str: