The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
chore(memory): remove the bundled hindsight provider (moved to the plugin catalog)
teknium14cbf862abe44
diff --git a/COMPAT_MANIFEST.md b/COMPAT_MANIFEST.mdindex 79ef74f59d0..1dc2d189a42 100644--- a/COMPAT_MANIFEST.md+++ b/COMPAT_MANIFEST.md@@ -2425,13 +2425,6 @@ to the public equivalent or the new module. Test monkeypatch seams are likewise| `save_b64_image` | moved-lazy | `agent.image_gen_provider` || `save_url_image` | moved-lazy | `agent.image_gen_provider` |-### `plugins.memory.hindsight`--| name | kind | new location |-|---|---|---|-| `dataclass` | import | `dataclasses` |-| `importlib` | import | `importlib` |-### `plugins.memory.honcho`| name | kind | new location |diff --git a/CONTRIBUTING.es.md b/CONTRIBUTING.es.mdindex 0c8915ecf81..052e916f08b 100644--- a/CONTRIBUTING.es.md+++ b/CONTRIBUTING.es.md@@ -51,7 +51,7 @@ Si tu habilidad es especializada, contribuida por la comunidad o de nicho, es me## Proveedores de Memoria: Publicar como Plugin Independiente-**Ya no aceptamos nuevos proveedores de memoria en este repositorio.** El conjunto de proveedores integrados en `plugins/memory/` (honcho, mem0, supermemory, byterover, hindsight, holographic, openviking, retaindb) está cerrado. Si quieres añadir un nuevo backend de memoria, publícalo como un **repositorio de plugin independiente** que los usuarios instalen en `~/.hermes/plugins/` (o a través de un entry point de pip).+**Ya no aceptamos nuevos proveedores de memoria en este repositorio.** El conjunto de proveedores integrados en `plugins/memory/` (honcho, mem0, supermemory, byterover, holographic, openviking, retaindb) está cerrado. Si quieres añadir un nuevo backend de memoria, publícalo como un **repositorio de plugin independiente** que los usuarios instalen en `~/.hermes/plugins/` (o a través de un entry point de pip).Los plugins de memoria independientes:diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 176faa054b7..675969214aa 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -69,7 +69,7 @@ If your skill is specialized, community-contributed, or niche, it's better suite## Memory Providers: Ship as a Standalone Plugin-**We are no longer accepting new memory providers into this repo.** The set of built-in providers under `plugins/memory/` (honcho, mem0, supermemory, byterover, hindsight, holographic, openviking, retaindb) is closed. If you want to add a new memory backend, publish it as a **standalone plugin repo** that users install into `~/.hermes/plugins/` (or via a pip entry point).+**We are no longer accepting new memory providers into this repo.** The set of built-in providers under `plugins/memory/` (honcho, mem0, supermemory, byterover, holographic, openviking, retaindb) is closed. If you want to add a new memory backend, publish it as a **standalone plugin repo** that users install into `~/.hermes/plugins/` (or via a pip entry point).Standalone memory plugins:diff --git a/compat_manifest.json b/compat_manifest.jsonindex 292ee175eea..c93354e4a00 100644--- a/compat_manifest.json+++ b/compat_manifest.json@@ -7910,18 +7910,6 @@"kind": "moved-lazy","target": "agent.image_gen_provider"},- {- "facade": "plugins.memory.hindsight",- "name": "dataclass",- "kind": "import",- "target": "dataclasses"- },- {- "facade": "plugins.memory.hindsight",- "name": "importlib",- "kind": "import",- "target": "importlib"- },{"facade": "plugins.memory.honcho","name": "CONCLUDE_SCHEMA",diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 41a60d06d6a..ef6b1939769 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1294,7 +1294,7 @@ DEFAULT_CONFIG = {# Periodic built-in memory review; 0 when an external provider auto-extracts."nudge_interval": 10,# External memory provider plugin (empty = built-in only); only ONE at a time: "openviking",- # "mem0", "hindsight", "holographic", "retaindb", "byterover".+ # "mem0", "holographic", "retaindb", "byterover", or a catalog-installed one ("hindsight")."provider": "",},# Subagent delegation — override the provider:model used by delegate_task so children run on adiff --git a/hermes_cli/memory_setup.py b/hermes_cli/memory_setup.pyindex a7aab868c48..bc40df3aa82 100644--- a/hermes_cli/memory_setup.py+++ b/hermes_cli/memory_setup.py@@ -12,33 +12,13 @@ from hermes_cli.secret_prompt import masked_secret_prompt_CANCELLED = -1-# pip name → import name mapping for packages where they differ+# pip name → import name mapping for packages where they differ. Catalog-installed providers keep+# declaring pip_dependencies in their plugin.yaml, so their bridge packages stay here too._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 baseline bridge packages; some providers add mode-dependent extras- at setup time that the manifest can't express.-- Hindsight's ``local_embedded`` mode installs ``hindsight-all`` (daemon + embedder + client) during- ``hermes memory setup`` — if the update-time refresh only reinstalled the declared ``hindsight-client``,- the embedded daemon would stay broken after a venv rebuild stripped ``hindsight-embed`` (#70636).- """- deps = list(declared or [])- if provider_name == "hindsight":- from utils import read_json_or_empty # BOM-tolerant; {} on missing/corrupt-- cfg = read_json_or_empty(get_hermes_home() / "hindsight" / "config.json")- # "local" is a legacy alias for "local_embedded"- if cfg.get("mode", "") in {"local", "local_embedded"}:- deps.append("hindsight-all")- return deps+}def _curses_select(@@ -106,7 +86,7 @@ def _install_dependencies(provider_name: str, *, force: bool = False) -> None:except Exception:return- pip_deps = _provider_pip_dependencies(provider_name, meta.get("pip_dependencies", []))+ pip_deps = list(meta.get("pip_dependencies", []) or [])if not pip_deps:returndiff --git a/hermes_cli/subcommands/memory.py b/hermes_cli/subcommands/memory.pyindex d11565f3cfa..70992b14d22 100644--- a/hermes_cli/subcommands/memory.py+++ b/hermes_cli/subcommands/memory.py@@ -12,8 +12,9 @@ def build_memory_parser(subparsers, *, cmd_memory: Callable) -> None:memory_parser = subparsers.add_parser("memory", help="Configure external memory provider",description="Set up and manage external memory provider plugins.\n\n"- "Available providers: honcho, openviking, mem0, hindsight,\n"- "holographic, retaindb, byterover.\n\n"+ "Bundled providers: honcho, openviking, mem0, holographic,\n"+ "retaindb, byterover. Catalog providers (e.g. hindsight):\n"+ "hermes plugins install <name>.\n\n""Only one external provider can be active at a time.\n""Built-in memory (MEMORY.md/USER.md) is always active.")memory_sub = memory_parser.add_subparsers(dest="memory_command")diff --git a/hermes_cli/tips.py b/hermes_cli/tips.pyindex 0fb8b5f2483..b3a7c365e64 100644--- a/hermes_cli/tips.py+++ b/hermes_cli/tips.py@@ -224,7 +224,7 @@ TIPS = [# --- Plugins ---"Three plugin types: general (tools/hooks), memory providers, and context engines.","hermes plugins install owner/repo installs plugins directly from GitHub.",- "8 external memory providers available: Honcho, OpenViking, Mem0, Hindsight, and more.",+ "External memory providers: Honcho, OpenViking, Mem0 bundled; Hindsight and more via hermes plugins install.","Plugin hooks include pre/post_tool_call, pre/post_llm_call, and transform_terminal_output for output canonicalization.",# --- Miscellaneous ---"Prompt caching (Anthropic) reduces costs by reusing cached system prompt prefixes.",diff --git a/hermes_cli/update_cmd.py b/hermes_cli/update_cmd.pyindex be34f5bf207..6a1f42ddc61 100644--- a/hermes_cli/update_cmd.py+++ b/hermes_cli/update_cmd.py@@ -652,7 +652,7 @@ def _repair_venv_on_current_checkout(_m()._refresh_active_lazy_features(repair_prefix, env=repair_env, features=active_lazy_features)_m()._restore_active_tool_dependencies(active_tool_dependencies, repair_prefix, env=repair_env)# Same order as the pull and ZIP paths: the ``[all]`` reinstall above may have stripped the- # active memory provider's bridge packages (hindsight-embed, torch, ...).+ # active memory provider's bridge packages (torch, embedding stacks, ...)._m()._refresh_active_memory_provider_dependencies()_m()._reapply_plugin_python_dependencies()# Core ``.[all]`` install finished. Clear the generic core breadcrumb before the lazy-refresh phase —diff --git a/hermes_cli/web_server_memory.py b/hermes_cli/web_server_memory.pyindex 6902a93579c..da4687f139d 100644--- a/hermes_cli/web_server_memory.py+++ b/hermes_cli/web_server_memory.py@@ -19,7 +19,6 @@ _MEMORY_PROVIDER_IMPORT_NAMES = {"honcho-ai": "honcho","mem0ai": "mem0","hindsight-client": "hindsight_client",- "hindsight-all": "hindsight",}diff --git a/plugins/AGENTS.md b/plugins/AGENTS.mdindex ec6b44a5c4d..93548f6472a 100644--- a/plugins/AGENTS.md+++ b/plugins/AGENTS.md@@ -17,7 +17,9 @@ command. A hook with no concrete consumer is speculative infrastructure and is r## What may live in this tree (policy)- **No new in-tree memory providers (May 2026).** `plugins/memory/` is closed (honcho, mem0,- supermemory, byterover, hindsight, holographic, openviking, retaindb stay; bug fixes welcome). New+ supermemory, byterover, holographic, openviking, retaindb stay; bug fixes welcome; hindsight moved+ to the plugin catalog in Sep 2026 — `plugin-catalog/hindsight.yaml`, auto-installed by+ `hermes_cli/memory_provider_migration.py` for homes still configured for it). Newbackends ship as standalone repos implementing the same `MemoryProvider` ABC, discovered throughthe same path, integrated via `hermes memory setup` / `post_setup()`.- **No new third-party-product plugins (June 2026).** Observability/metrics backends, vendor SaaS@@ -119,4 +121,4 @@ External-plugin compat is handled ONCE here — never add per-PR re-export shims`tests/plugins/`. Load through real discovery with a temp `HERMES_HOME`; assert behaviour (toolregistered, hook fired with expected kwargs), not counts. Opt-in telemetry rule applies to plugins-too: no attribution tag ships by default (`tests/plugins/memory/test_hindsight_provider.py`).+too: no attribution tag ships by default.diff --git a/plugins/memory/__init__.py b/plugins/memory/__init__.pyindex 08780102b62..6ecdec8e622 100644--- a/plugins/memory/__init__.py+++ b/plugins/memory/__init__.py@@ -238,9 +238,9 @@ def import_memory_provider_module(name: Optional[str] = None) -> bool:except Exception:logger.debug("memory provider '%s' warm-up import failed", name, exc_info=True)if imported:- # The deadlock is numpy's lazy ``_core`` init; hindsight defers that import to- # ``is_available()`` (sentence_transformers), so the provider module alone leaves- # it unwarmed. Every reporter's workaround was a plain ``import numpy`` up front.+ # The deadlock is numpy's lazy ``_core`` init; embedding-backed providers (e.g. the+ # hindsight plugin) defer that import to ``is_available()`` (sentence_transformers), so+ # the provider module alone leaves it unwarmed. Every reporter's workaround was a plain ``import numpy`` up front.for module in _NATIVE_WARM_IMPORTS:try:importlib.import_module(module)diff --git a/plugins/memory/hindsight/README.md b/plugins/memory/hindsight/README.mddeleted file mode 100644index 06382a43215..00000000000--- a/plugins/memory/hindsight/README.md+++ /dev/null@@ -1,157 +0,0 @@-# Hindsight Memory Provider--Long-term memory with knowledge graph, entity resolution, and multi-strategy retrieval. Supports cloud, local embedded, and local external modes.--## Requirements--- **Cloud:** API key from [ui.hindsight.vectorize.io](https://ui.hindsight.vectorize.io)-- **Local Embedded:** API key for a supported LLM provider (OpenAI, Anthropic, Gemini, Groq, OpenRouter, MiniMax, Ollama, or any OpenAI-compatible endpoint). Embeddings and reranking run locally — no additional API keys needed.-- **Local External:** A running Hindsight instance (Docker or self-hosted) reachable over HTTP.--## Setup--```bash-hermes memory setup # select "hindsight"-```--The setup wizard installs dependencies automatically via `uv`, walks you through configuration, and offers to seed the bank with a **starter memory template** (a curated set of dispositions/instructions for common agent roles) — you can skip it, and it warns before overwriting an already-configured bank.--Or manually (cloud mode with defaults):-```bash-hermes config set memory.provider hindsight-echo "HINDSIGHT_API_KEY=your-key" >> ~/.hermes/.env-```--### Cloud--Connects to the Hindsight Cloud API. Requires an API key from [ui.hindsight.vectorize.io](https://ui.hindsight.vectorize.io).--### Local Embedded--Hermes spins up a local Hindsight daemon with built-in PostgreSQL. Requires an LLM API key for memory extraction and synthesis. The daemon starts automatically in the background on first use and stops after 5 minutes of inactivity.--Supports any OpenAI-compatible LLM endpoint (llama.cpp, vLLM, LM Studio, etc.) — pick `openai_compatible` as the provider and enter the base URL.--Daemon startup logs: `~/.hermes/logs/hindsight-embed.log`-Daemon runtime logs: `~/.hindsight/profiles/<profile>.log`--To open the Hindsight web UI (local embedded mode only):-```bash-hindsight-embed -p hermes ui start-```--### Local External--Points the plugin at an existing Hindsight instance you're already running (Docker, self-hosted, etc.). No daemon management — just a URL and an optional API key.--## Config--Config file: `~/.hermes/hindsight/config.json`--### Connection--| Key | Default | Description |-|-----|---------|-------------|-| `mode` | `cloud` | `cloud`, `local_embedded`, or `local_external` |-| `api_url` | `https://api.hindsight.vectorize.io` | API URL (cloud and local_external modes) |--### Memory Bank--| Key | Default | Description |-|-----|---------|-------------|-| `bank_id` | `hermes` | Memory bank name (static fallback used when `bank_id_template` is unset or resolves empty) |-| `bank_id_template` | — | Optional template to derive the bank name dynamically. Placeholders: `{profile}`, `{workspace}`, `{platform}`, `{user}`, `{session}`. Example: `hermes-{profile}` isolates memory per active Hermes profile. Empty placeholders collapse cleanly (e.g. `hermes-{user}` with no user becomes `hermes`). |-| `bank_mission` | — | Reflect mission (identity/framing for reflect reasoning). Applied via Banks API. |-| `bank_retain_mission` | — | Retain mission (steers what gets extracted). Applied via Banks API. |--### Recall--| Key | Default | Description |-|-----|---------|-------------|-| `recall_budget` | `mid` | Recall thoroughness: `low` / `mid` / `high` |-| `recall_prefetch_method` | `recall` | Auto-recall method: `recall` (raw facts) or `reflect` (LLM synthesis) |-| `recall_max_tokens` | `4096` | Maximum tokens for recall results |-| `recall_max_input_chars` | `800` | Maximum input query length for auto-recall |-| `recall_prompt_preamble` | — | Custom preamble for recalled memories in context |-| `recall_tags` | — | Tags to filter when searching memories |-| `recall_tags_match` | `any` | Tag matching mode: `any` / `all` / `any_strict` / `all_strict` |-| `recall_types` | `observation` | Fact types surfaced by recall (both auto-recall and the `hindsight_recall` tool). Comma-separated string or JSON list. **Default narrowed to `observation` only** (see "Behavior change" below). Set to `observation,world,experience` to also include raw facts. |-| `auto_recall` | `true` | Automatically recall memories before each turn |-| `recall_sync` | `false` | Recall synchronously against the *current* message each turn (higher relevance, adds recall latency). Default off: recall runs in the background and is injected on the next turn. |-| `recall_indicator` | `true` | Show a `👁️ Hindsight — recalled N memories` status line when auto-recall injects memory. Turn off for customer-facing agents. |--> **Behavior change — `recall_types` defaults to `observation` only.**->-> Previously recall returned all three fact types. It now returns only observations.->-> Per [Hindsight's docs](https://hindsight.vectorize.io/developer/observations), observations are the **consolidated** knowledge layer Hindsight builds on top of raw facts: deduplicated beliefs grounded in evidence, refined as new facts arrive, with proof counts and freshness signals. Raw `world` / `experience` facts are the individual supporting evidence that feeds them. For per-turn context injection, observations are denser per token and avoid feeding the model multiple raw facts that one observation already summarizes.->-> Restore the broad recall with `"recall_types": "observation,world,experience"` (string or JSON list) in `~/.hermes/hindsight/config.json`. This applies to **both** auto-recall and the `hindsight_recall` tool — both read the same `recall_types` setting (the tool schema has no per-call `types` argument), so narrowing the default narrows both paths.--### Retain--| Key | Default | Description |-|-----|---------|-------------|-| `auto_retain` | `true` | Automatically retain conversation turns |-| `retain_async` | `true` | Process retain asynchronously on the Hindsight server |-| `retain_every_n_turns` | `1` | Retain every N turns (1 = every turn) |-| `retain_context` | `conversation between Hermes Agent and the User` | Context label for retained memories |-| `retain_tags` | — | Default tags applied to retained memories; merged with per-call tool tags |-| `retain_source` | — | Opt-in `metadata.source` attached to retained memories (identifies the storing client, e.g. `hermes`). Empty by default — no attribution tag ships unless you set it. |-| `retain_indicator` | `true` | Show a `👁️ Hindsight — saving to memory…` status line when a turn is saved. Turn off for customer-facing agents. |-| `retain_user_prefix` | `User` | Label used before user turns in auto-retained transcripts |-| `retain_assistant_prefix` | `Assistant` | Label used before assistant turns in auto-retained transcripts |--### Integration--| Key | Default | Description |-|-----|---------|-------------|-| `memory_mode` | `hybrid` | How memories are integrated into the agent |--**memory_mode:**-- `hybrid` — automatic context injection + tools available to the LLM-- `context` — automatic injection only, no tools exposed-- `tools` — tools only, no automatic injection--### Local Embedded LLM--| Key | Default | Description |-|-----|---------|-------------|-| `llm_provider` | `openai` | `openai`, `anthropic`, `gemini`, `groq`, `openrouter`, `minimax`, `ollama`, `lmstudio`, `openai_compatible` |-| `llm_model` | per-provider | Model name (e.g. `gpt-4o-mini`, `qwen/qwen3.5-9b`) |-| `llm_base_url` | — | Endpoint URL for `openai_compatible` (e.g. `http://192.168.1.10:8080/v1`) |--The LLM API key is stored in `~/.hermes/.env` as `HINDSIGHT_LLM_API_KEY`.--The embedded daemon is a subprocess that cannot see the per-turn secret-scope, so it reads the key from `~/.hindsight/profiles/<profile>.env`-(materialized owner-only at setup and on config change). Key resolution-order is explicit config → secret scope → the on-disk profile env, and the-rewrite path is fail-closed: a build with no key never clobbers a profile-file that already holds one.--## Tools--Available in `hybrid` and `tools` memory modes:--| Tool | Description |-|------|-------------|-| `hindsight_retain` | Store information with auto entity extraction; supports optional per-call `tags` |-| `hindsight_recall` | Multi-strategy search (semantic + entity graph) |-| `hindsight_reflect` | Cross-memory synthesis (LLM-powered) |--## Environment Variables--| Variable | Description |-|----------|-------------|-| `HINDSIGHT_API_KEY` | API key for Hindsight Cloud |-| `HINDSIGHT_LLM_API_KEY` | LLM API key for local mode |-| `HINDSIGHT_API_LLM_BASE_URL` | LLM Base URL for local mode (e.g. OpenRouter) |-| `HINDSIGHT_API_URL` | Override API endpoint |-| `HINDSIGHT_BANK_ID` | Override bank name |-| `HINDSIGHT_BUDGET` | Override recall budget |-| `HINDSIGHT_MODE` | Override mode (`cloud`, `local_embedded`, `local_external`) |--## Client Version--Requires `hindsight-client >= 0.6.1`. The plugin auto-upgrades on session start if an older version is detected.diff --git a/plugins/memory/hindsight/__init__.py b/plugins/memory/hindsight/__init__.pydeleted file mode 100644index 20236b0a4e6..00000000000--- a/plugins/memory/hindsight/__init__.py+++ /dev/null@@ -1,1263 +0,0 @@-"""Hindsight memory plugin — MemoryProvider with knowledge graph, entity resolution-and multi-strategy retrieval; cloud (API key), local_external, or local_embedded.--Config: $HERMES_HOME/hindsight/config.json (profile-scoped), else ~/.hindsight/-config.json (legacy, shared), else env: HINDSIGHT_API_KEY / BANK_ID / BUDGET /-API_URL / MODE / TIMEOUT / IDLE_TIMEOUT / RETAIN_TAGS / RETAIN_OBSERVATION_SCOPES /-RETAIN_SOURCE / RETAIN_USER_PREFIX / RETAIN_ASSISTANT_PREFIX, and-HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT (config.json port_health_grace_timeout).-"""--from __future__ import annotations--import asyncio-import atexit-import contextlib-import json-import logging-import os-import queue-import sys-import threading-import time-from datetime import datetime, timezone-from pathlib import Path-from typing import Any, Callable, Dict, List, Optional--from agent.memory_provider import MemoryProvider, RecallStatus, spawn_context_thread-from agent.secret_scope import UnscopedSecretError, get_secret-from hermes_cli.config import cfg_get-from hermes_constants import get_hermes_home-from hermes_time import now as _hermes_now-from tools.registry import tool_error-from utils import read_json_or_empty--from .embedded import (- _RETRIABLE_CONNECTION_MARKERS, _build_embedded_profile_env,- _check_local_runtime, _embedded_llm_api_key, _embedded_profile_env_path,- _export_port_health_grace_timeout, _load_simple_env, _local_runtime_hint, _materialize_embedded_profile_env,- _may_rewrite_profile_env,-)-from .settings import (- _DEFAULT_API_URL, _DEFAULT_IDLE_TIMEOUT, _DEFAULT_LOCAL_URL, _DEFAULT_RETAIN_SOURCE,- _DEFAULT_TIMEOUT, _HINDSIGHT_GLYPH, _MIN_CLIENT_VERSION, _MIN_VERSION_FOR_UPDATE_MODE_APPEND,- _PROVIDER_DEFAULT_MODELS, _VALID_BUDGETS, _daemon_llm_provider,- _normalize_observation_scopes, _normalize_retain_tags, _parse_int_setting,- _resolve_bank_id_template,-)--logger = logging.getLogger(__name__)--_LOCAL_MODES = {"local", "local_embedded"}-_RETAIN_CONTEXT_DEFAULT = "conversation between Hermes Agent and the User"---def _ensure_client_dependency() -> None:- """Lazily install the Hindsight client (``tools.lazy_deps``) before importing it."""- try:- from tools.lazy_deps import ensure as _lazy_ensure- _lazy_ensure("memory.hindsight", prompt=False)- except ImportError:- pass- except Exception as exc:- raise ImportError(str(exc)) from exc---def _scoped_setting(name: str, default: str = "") -> str:- """Profile-scoped read of a retain SHAPING value, with the provider's own default on a miss.-- Under ``gateway.multiplex_profiles`` ``os.environ`` holds the DEFAULT profile's ``.env``, so a miss- is a miss — never ``os.environ`` (same rule as the daemon's key and base URL in ``embedded.py``).- Single-profile deployments are unchanged: with no scope installed ``get_secret`` still reads the- process env, where the value IS this profile's own.-- Deliberately narrower than a bare ``get_secret``: this helper is only for presentation shaping- (retain source label, speaker prefixes, tags). The isolation-critical values — ``mode``,- ``apiKey`` and the ``bankId`` data partition — read through bare ``get_secret`` above and so- still fail loud on a scopeless multiplexed read, matching the other scoped credential readers.- In ``_load_config`` that read happens FIRST, so a missing scope raises on ``HINDSIGHT_MODE``- before this helper is ever reached; swallowing here therefore cannot mask an isolation failure.- What it does avoid is losing the whole memory provider (``initialize`` failing, and the manager- logging + dropping it) because a speaker prefix could not be resolved.- """- try:- value = get_secret(name, default)- except UnscopedSecretError:- return default- return default if value is None else value---def _cloud_api_key(config: dict) -> str:- return config.get("apiKey") or config.get("api_key") or get_secret("HINDSIGHT_API_KEY", "")---def _maybe_upgrade_client() -> None:- """Auto-upgrade an outdated hindsight-client via the environment-aware lazy_deps- installer (sealed hosted venvs redirect to the durable target)."""- try:- from importlib.metadata import version as pkg_version- from packaging.version import Version- installed = pkg_version("hindsight-client")- if Version(installed) < Version(_MIN_CLIENT_VERSION):- logger.warning("hindsight-client %s is outdated (need >=%s), attempting upgrade...",- installed, _MIN_CLIENT_VERSION)- from tools.lazy_deps import install_specs- outcome = install_specs([f"hindsight-client>={_MIN_CLIENT_VERSION}"], timeout=120)- if outcome.ok:- logger.info("hindsight-client upgraded to >=%s", _MIN_CLIENT_VERSION)- elif outcome.blocked:- logger.warning("Auto-upgrade unavailable: %s. Run: uv pip install 'hindsight-client>=%s'",- outcome.reason, _MIN_CLIENT_VERSION)- else:- logger.warning("Auto-upgrade failed: %s. Run: uv pip install 'hindsight-client>=%s'",- (outcome.stderr or "").strip() or "install error", _MIN_CLIENT_VERSION)- except Exception:- pass # packaging not available or other issue — proceed anyway---# update_mode='append' capability (Hindsight >= 0.5.0), cached per (API URL, key fingerprint)-# per process so every provider on the same API+key shares one /version round trip. A failed probe-# caches False, so the key must include the credential or one profile's 401 would silently downgrade-# a sibling profile that shares the URL with a valid key.-_append_capability_cache: Dict[tuple[str, str | None], bool] = {}-_append_capability_lock = threading.Lock()---def _fetch_hindsight_api_version(api_url: str, api_key: str | None = None,- timeout: float = 5.0) -> str | None:- """GET ``<api_url>/version`` -> version string, or None on any failure (= legacy API)."""- import urllib.request- if not api_url:- return None- url = api_url.rstrip("/") + "/version"- req = urllib.request.Request(url, headers={"Authorization": f"Bearer {api_key}"} if api_key else {})- try:- with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310- data = json.loads(resp.read().decode("utf-8", errors="replace"))- except Exception as exc:- logger.debug("Hindsight /version probe failed for %s: %s", url, exc)- return None- version = (data.get("version") or data.get("api_version")) if isinstance(data, dict) else None- return str(version) if version else None---def _check_api_supports_update_mode_append(api_url: str, api_key: str | None = None) -> bool:- """Cached ``update_mode='append'`` check for *api_url*. False on any probe failure- (safe default: per-process document_id, no update_mode = resume-overwrite fix intact).-- Probes once per URL per process. See #6654.- """- if not api_url:- return False- from agent.credential_persistence import fingerprint_secret_value-- cache_key = (api_url, fingerprint_secret_value(api_key))- with _append_capability_lock:- if cache_key in _append_capability_cache:- return _append_capability_cache[cache_key]- version = _fetch_hindsight_api_version(api_url, api_key)- try: # missing/invalid version -> unsupported- from packaging.version import Version- supported = bool(version) and Version(version) >= Version(_MIN_VERSION_FOR_UPDATE_MODE_APPEND)- except Exception:- supported = False- with _append_capability_lock:- # A concurrent probe may have filled the cache meanwhile; its answer wins.- supported = _append_capability_cache.setdefault(cache_key, supported)- if supported:- logger.debug("Hindsight API %s version %s supports update_mode='append'", api_url, version)- else:- logger.warning("Hindsight API at %s reports version %r, older than %s. "- "Falling back to per-process document_id — retains across "- "processes/sessions create separate documents instead of "- "appending to a session-scoped one. Upgrade Hindsight to "- "%s+ to enable update_mode='append' deduplication.",- api_url, version, _MIN_VERSION_FOR_UPDATE_MODE_APPEND, _MIN_VERSION_FOR_UPDATE_MODE_APPEND)- return supported---# One long-lived event loop per process for Hindsight async calls; ephemeral-# loops would leak aiohttp sessions.-_loop: asyncio.AbstractEventLoop | None = None-_loop_thread: threading.Thread | None = None-_loop_lock = threading.Lock()--# Pushed to the per-provider retain queue to wake the writer for a clean exit.-_WRITER_SENTINEL = object()---def _get_loop() -> asyncio.AbstractEventLoop:- """Return a long-lived event loop running on a background thread."""- global _loop, _loop_thread- with _loop_lock:- if _loop is not None and _loop.is_running():- return _loop- loop = _loop = asyncio.new_event_loop()- _loop_thread = threading.Thread(- target=lambda: (asyncio.set_event_loop(loop), loop.run_forever()), daemon=True, name="hindsight-loop",- )- _loop_thread.start()- return _loop---def _run_sync(coro, timeout: float = _DEFAULT_TIMEOUT):- """Schedule *coro* on the shared loop and block until done."""- from agent.async_utils import safe_schedule_threadsafe- future = safe_schedule_threadsafe(coro, _get_loop())- if future is None:- raise RuntimeError("Hindsight loop unavailable")- return future.result(timeout=timeout)---RETAIN_SCHEMA = {- "name": "hindsight_retain",- "description": (- "Store information to long-term memory. Hindsight automatically "- "extracts structured facts, resolves entities, and indexes for retrieval."- ),- "parameters": {- "type": "object",- "properties": {- "content": {"type": "string", "description": "The information to store."},- "context": {"type": "string", "description": "Short label (e.g. 'user preference', 'project decision')."},- "tags": {"type": "array", "items": {"type": "string"},- "description": "Optional per-call tags to merge with configured default retain tags."},- "occurred_at": {"type": "string", "description": (- "When the remembered event actually happened, as an ISO-8601 date "- "or datetime (e.g. '2026-08-20' or '2026-08-20T14:30:00+02:00'). "- "Pass this whenever the memory references a specific event time "- "('yesterday', 'last Tuesday', 'on March 3rd') so Hindsight can "- "anchor it on the timeline. Omit for timeless facts/preferences."- )},- },- "required": ["content"],- },-}--RECALL_SCHEMA = {- "name": "hindsight_recall",- "description": (- "Search long-term memory. Returns memories ranked by relevance using "- "semantic search, keyword matching, entity graph traversal, and reranking."- ),- "parameters": {"type": "object", "required": ["query"],- "properties": {"query": {"type": "string", "description": "What to search for."}}},-}--REFLECT_SCHEMA = {- "name": "hindsight_reflect",- "description": (- "Synthesize a reasoned answer from long-term memories. Unlike recall, "- "this reasons across all stored memories to produce a coherent response."- ),- "parameters": {"type": "object", "required": ["query"],- "properties": {"query": {"type": "string", "description": "The question to reflect on."}}},-}---def _load_config() -> dict:- """$HERMES_HOME/hindsight/config.json (profile-scoped), else ~/.hindsight/config.json- (legacy, shared), else environment variables."""- for path in (get_hermes_home() / "hindsight" / "config.json", Path.home() / ".hindsight" / "config.json"):- # A corrupt (or empty) file falls through to the next source, as before the dedup.- if path.exists() and (data := read_json_or_empty(path)):- return data- # Mode, bank (the data partition), endpoint and retain shaping are per-profile .env values like- # the key beside them: read through the secret scope so a multiplexed secondary never inherits- # the default profile's bank/mode. Tuning knobs (timeouts, budget) stay process-global.- return {- "mode": get_secret("HINDSIGHT_MODE", "") or "cloud",- "apiKey": get_secret("HINDSIGHT_API_KEY", ""),- "timeout": _parse_int_setting(os.environ.get("HINDSIGHT_TIMEOUT"), _DEFAULT_TIMEOUT),- "idle_timeout": _parse_int_setting(os.environ.get("HINDSIGHT_IDLE_TIMEOUT"), _DEFAULT_IDLE_TIMEOUT),- "retain_tags": get_secret("HINDSIGHT_RETAIN_TAGS", "") or "",- "observation_scopes": get_secret("HINDSIGHT_RETAIN_OBSERVATION_SCOPES", "") or "",- "retain_source": _scoped_setting("HINDSIGHT_RETAIN_SOURCE", _DEFAULT_RETAIN_SOURCE),- "retain_user_prefix": _scoped_setting("HINDSIGHT_RETAIN_USER_PREFIX", "User"),- "retain_assistant_prefix": _scoped_setting("HINDSIGHT_RETAIN_ASSISTANT_PREFIX", "Assistant"),- "banks": {"hermes": {"bankId": get_secret("HINDSIGHT_BANK_ID", "") or "hermes",- "budget": os.environ.get("HINDSIGHT_BUDGET", "mid"), "enabled": True}},- }---def _event_timestamp() -> str:- """Configured Hermes event time with an explicit UTC offset."""- event_time = _hermes_now()- # hermes_time.now() is aware; guard a replacement clock emitting offset-less dates.- if event_time.tzinfo is None or event_time.utcoffset() is None:- event_time = event_time.astimezone()- return event_time.isoformat(timespec="seconds")---def _mint_document_id(session_id: str) -> str:- """Per-process document id: reusing session_id alone overwrote the document on- /resume (the reloaded session's first retain replaced the stored content)."""- return f"{session_id}-{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}"---# initialize() kwargs copied verbatim (str, stripped) onto ``self._<name>``.-_SESSION_KWARGS = (- "platform", "user_id", "user_name", "chat_id", "chat_name", "chat_type",- "thread_id", "agent_identity", "agent_workspace",-)-# Retain metadata keys, each stamped from the attribute of the same name when set.-_METADATA_ATTRS = (- "session_id", "platform", "user_id", "user_name", "chat_id", "chat_name",- "chat_type", "thread_id", "agent_identity",-)-_SYSTEM_PROMPT_TAILS = {- "context": "Relevant memories are automatically injected into context.",- "tools": ("Use hindsight_recall to search, hindsight_reflect for synthesis, "- "hindsight_retain to store facts."),- "hybrid": ("Relevant memories are automatically injected into context. "- "Use hindsight_recall to search, hindsight_reflect for synthesis, "- "hindsight_retain to store facts."),-}---class HindsightMemoryProvider(MemoryProvider):- """Hindsight long-term memory with knowledge graph and multi-strategy retrieval."""-- # Each server-side op status poll is a round trip — coarser than the 0.05s queue poll.- _RETAIN_OP_POLL_INTERVAL_S = 0.5-- def backup_paths(self) -> List[str]:- """Legacy shared config + embedded-mode profile env files live under ~/.hindsight."""- with contextlib.suppress(Exception):- return [str(Path.home() / ".hindsight")]- return []-- def __init__(self):- self._config = self._api_key = self._client = None- self._api_url, self._llm_base_url, self._mode = _DEFAULT_API_URL, "", "cloud"- self._timeout, self._idle_timeout = _DEFAULT_TIMEOUT, _DEFAULT_IDLE_TIMEOUT- self._bank_id, self._budget, self._bank_id_template = "hermes", "mid", ""- self._bank_mission, self._bank_retain_mission = "", None- self._memory_mode = "hybrid" # "context", "tools", or "hybrid"- self._prefetch_method = "recall" # "recall" or "reflect"- for name in _SESSION_KWARGS:- setattr(self, f"_{name}", "")- self._session_id = self._parent_session_id = self._document_id = ""- self._status_callback: Optional[Callable[[str], None]] = None-- # Retain: single-writer model — sync_turn() enqueues, one writer thread- # drains sequentially (ad-hoc threads raced interpreter shutdown:- # "cannot schedule new futures" / "Unclosed client session").- self._retain_queue: queue.Queue = queue.Queue()- self._writer_thread: threading.Thread | None = None- self._sync_thread = None # legacy alias external callers may join; points at the writer- self._shutting_down = threading.Event()- self._atexit_registered = False- self._retain_tags: List[str] = []- self._tags: list[str] | None = None- self._retain_source = _DEFAULT_RETAIN_SOURCE- self._retain_user_prefix, self._retain_assistant_prefix = "User", "Assistant"- self._turn_counter = self._turn_index = 0- self._session_turns: list[str] = [] # ALL turns for the session- self._last_retained_turn_count = 0 # append-mode delta watermark- # Server-side async retain ops still in flight: aretain_batch returns on- # *acceptance*, not durability, so the prefetch gates on these via- # get_operation_status (a drained local queue is not a read-after-write signal).- self._pending_retain_ops: set[str] = set()- self._pending_retain_ops_lock = threading.Lock()- self._retain_ops_bank_id = ""- self._apply_retain_policy({})-- # Recall: pending prefetch block + count, and the indicator state (recall_status()).- self._prefetch_result, self._prefetch_count = "", 0- self._prefetch_lock = threading.Lock()- self._prefetch_thread = None- self._last_recall_returned, self._last_recall_count = False, 0- self._apply_recall_settings({})-- @property- def name(self) -> str:- return "hindsight"-- def is_available(self) -> bool:- try:- cfg = _load_config()- mode = cfg.get("mode", "cloud")- if mode in _LOCAL_MODES:- return _check_local_runtime()[0]- return mode == "local_external" or bool(- _cloud_api_key(cfg) or cfg.get("api_url") or get_secret("HINDSIGHT_API_URL", ""))- except Exception:- return False-- def unavailable_reason(self) -> str:- """Install hint for an unavailable local_embedded runtime (is_available() gates- initialize() out, so the hint it would log never fires; agent_init shows this).-- ``is_available()`` returns False for local modes when the embedded runtime can't be imported, so- ``initialize()`` — and the hint it would log — is never reached (#7718). Surface the install- guidance here, where agent_init warns about an unavailable provider.- """- try:- if _load_config().get("mode", "cloud") not in _LOCAL_MODES:- return ""- except Exception:- return ""- available, reason = _check_local_runtime()- return "" if available else _local_runtime_hint(reason).strip()-- def save_config(self, values, hermes_home):- """Merge *values* into $HERMES_HOME/hindsight/config.json."""- from utils import atomic_json_write- config_path = Path(hermes_home) / "hindsight" / "config.json"- atomic_json_write(config_path, {**read_json_or_empty(config_path), **values}, mode=0o600)-- def post_setup(self, hermes_home: str, config: dict) -> None:- """Custom setup wizard — installs only the deps needed for the selected mode."""- from .setup import run_setup- run_setup(self, hermes_home, config)-- def get_config_schema(self):- return [- {"key": "mode", "description": "Connection mode", "default": "cloud", "choices": ["cloud", "local_embedded", "local_external"]},- # Cloud mode- {"key": "api_url", "description": "Hindsight Cloud API URL", "default": _DEFAULT_API_URL, "when": {"mode": "cloud"}},- {"key": "api_key", "description": "Hindsight Cloud API key", "secret": True, "env_var": "HINDSIGHT_API_KEY", "url": "https://ui.hindsight.vectorize.io", "when": {"mode": "cloud"}},- # Local external mode- {"key": "api_url", "description": "Hindsight API URL", "default": _DEFAULT_LOCAL_URL, "when": {"mode": "local_external"}},- {"key": "api_key", "description": "API key (optional)", "secret": True, "env_var": "HINDSIGHT_API_KEY", "when": {"mode": "local_external"}},- # Local embedded mode- {"key": "llm_provider", "description": "LLM provider", "default": "openai", "choices": ["openai", "anthropic", "gemini", "groq", "openrouter", "minimax", "ollama", "lmstudio", "openai_compatible"], "when": {"mode": "local_embedded"}},- {"key": "llm_base_url", "description": "Endpoint URL (e.g. http://192.168.1.10:8080/v1)", "default": "", "when": {"mode": "local_embedded", "llm_provider": "openai_compatible"}},- {"key": "llm_api_key", "description": "LLM API key (optional for openai_compatible)", "secret": True, "env_var": "HINDSIGHT_LLM_API_KEY", "when": {"mode": "local_embedded"}},- {"key": "llm_model", "description": "LLM model", "default": "gpt-4o-mini", "default_from": {"field": "llm_provider", "map": _PROVIDER_DEFAULT_MODELS}, "when": {"mode": "local_embedded"}},- {"key": "bank_id", "description": "Memory bank name (static fallback when bank_id_template is unset)", "default": "hermes"},- {"key": "bank_id_template", "description": "Optional template to derive bank_id dynamically. Placeholders: {profile}, {workspace}, {platform}, {user}, {session}. Example: hermes-{profile}", "default": ""},- {"key": "bank_mission", "description": "Mission/purpose description for the memory bank"},- {"key": "bank_retain_mission", "description": "Custom extraction prompt for memory retention"},- {"key": "recall_budget", "description": "Recall thoroughness", "default": "mid", "choices": ["low", "mid", "high"]},- {"key": "memory_mode", "description": "Memory integration mode", "default": "hybrid", "choices": ["hybrid", "context", "tools"]},- {"key": "recall_prefetch_method", "description": "Auto-recall method", "default": "recall", "choices": ["recall", "reflect"]},- {"key": "retain_tags", "description": "Default tags applied to retained memories (comma-separated)", "default": ""},- {"key": "observation_scopes", "description": "How observations are scoped during consolidation: 'combined' (default — one pass over all tags), 'per_tag' (one isolated observation per tag), 'all_combinations' (every tag subset — expensive), or a JSON list of tag-lists for explicit custom scopes. Empty uses Hindsight's 'combined' default.", "default": ""},- {"key": "retain_source", "description": "Metadata source value attached to retained memories (identifies the client that stored them)", "default": _DEFAULT_RETAIN_SOURCE},- {"key": "retain_user_prefix", "description": "Label used before user turns in retained transcripts", "default": "User"},- {"key": "retain_assistant_prefix", "description": "Label used before assistant turns in retained transcripts", "default": "Assistant"},- {"key": "recall_tags", "description": "Tags to filter when searching memories (comma-separated)", "default": ""},- {"key": "recall_tags_match", "description": "Tag matching mode for recall", "default": "any", "choices": ["any", "all", "any_strict", "all_strict"]},- {"key": "recall_types", "description": "Fact types to surface on recall — applies to both auto-recall and the hindsight_recall tool (comma-separated or list). Defaults to observation-only — observations are Hindsight's consolidated, deduplicated, evidence-grounded knowledge layer; raw world/experience facts are the supporting evidence observations already summarize. Set to e.g. 'observation,world,experience' to also include raw facts.", "default": "observation"},- {"key": "auto_recall", "description": "Automatically recall memories before each turn", "default": True},- {"key": "recall_sync", "description": "Recall synchronously against the current message before each turn (higher relevance, adds recall latency to the turn). Default off: recall runs in the background and is injected on the next turn.", "default": False},- {"key": "recall_indicator", "description": "Show a '👁️ Hindsight — recalled N memories' status line when auto-recall injects memory (turn off for customer-facing agents)", "default": True},- {"key": "retain_indicator", "description": "Show a '👁️ Hindsight — saving to memory…' status line when a turn is saved to memory (turn off for customer-facing agents)", "default": True},- {"key": "auto_retain", "description": "Automatically retain conversation turns", "default": True},- {"key": "retain_every_n_turns", "description": "Retain every N turns (1 = every turn)", "default": 1},- {"key": "retain_async","description": "Process retain asynchronously on the Hindsight server", "default": True},- {"key": "prefetch_waits_for_retain", "description": "Have the background next-turn prefetch wait for the just-completed retain to become recall-visible on the server (local queue drain + async operation completion) before recalling, so recall includes the just-completed turn (runs off the reply path, adds no response latency)", "default": True},- {"key": "prefetch_retain_drain_timeout", "description": "Max seconds the background prefetch waits for the retain to become recall-visible (queue drain + server-side completion) before recalling anyway", "default": 10.0},- {"key": "retain_context", "description": "Context label for retained memories", "default": "conversation between Hermes Agent and the User"},- {"key": "recall_max_tokens", "description": "Maximum tokens for recall results", "default": 4096},- {"key": "recall_max_input_chars", "description": "Maximum input query length for auto-recall", "default": 800},- {"key": "recall_prompt_preamble", "description": "Custom preamble for recalled memories in context"},- {"key": "timeout", "description": "API request timeout in seconds", "default": _DEFAULT_TIMEOUT},- {"key": "idle_timeout", "description": "Embedded daemon idle timeout in seconds (0 disables auto-shutdown)", "default": _DEFAULT_IDLE_TIMEOUT, "when": {"mode": "local_embedded"}},- {"key": "port_health_grace_timeout", "description": "Seconds to wait for a slow daemon /health before treating it as stale (raise on busy/low-resource hosts; blank uses the 30s default)", "default": "", "when": {"mode": "local_embedded"}},- ]-- # -- client --------------------------------------------------------------- def _int_setting(self, key: str, env_var: str, default: int, env_default=None) -> int:- """Config value if set (explicit 0 preserved), else env var, else default."""- value = self._config.get(key)- return _parse_int_setting(os.environ.get(env_var, env_default) if value is None else value, default)-- def _new_embedded_client(self):- available, reason = _check_local_runtime()- if not available:- raise RuntimeError("Hindsight local runtime is unavailable" + (f": {reason}" if reason else ""))- _ensure_client_dependency()- from hindsight import HindsightEmbedded- HindsightEmbedded.__del__ = lambda self: None- cfg = self._config- llm_provider = _daemon_llm_provider(cfg.get("llm_provider", ""))- logger.debug("Creating HindsightEmbedded client (profile=%s, provider=%s)",- cfg.get("profile", "hermes"), llm_provider)- self._idle_timeout = self._int_setting(- "idle_timeout", "HINDSIGHT_IDLE_TIMEOUT", _DEFAULT_IDLE_TIMEOUT, env_default=self._idle_timeout,- )- kwargs = dict(profile=cfg.get("profile", "hermes"), llm_provider=llm_provider,- llm_api_key=_embedded_llm_api_key(cfg), llm_model=cfg.get("llm_model", ""),- idle_timeout=self._idle_timeout)- if self._llm_base_url:- kwargs["llm_base_url"] = self._llm_base_url- return HindsightEmbedded(**kwargs)-- def _new_cloud_client(self):- _ensure_client_dependency()- from hindsight_client import Hindsight- kwargs = {"base_url": self._api_url, "timeout": float(self._timeout or _DEFAULT_TIMEOUT)}- if self._api_key:- kwargs["api_key"] = self._api_key- logger.debug("Creating Hindsight cloud client (url=%s, has_key=%s, timeout=%s)",- self._api_url, bool(self._api_key), kwargs["timeout"])- return Hindsight(**kwargs)-- def _get_client(self):- """Return the cached Hindsight client (created once, reused)."""- if self._client is None:- self._client = self._new_embedded_client() if self._mode == "local_embedded" else self._new_cloud_client()- return self._client-- def _run_sync(self, coro):- """Schedule *coro* on the shared loop using the configured timeout."""- return _run_sync(coro, timeout=self._timeout)-- def _run_hindsight_operation(self, operation):- """Run an async client operation; for local_embedded, a stale-daemon- connection failure recreates the client and retries once."""- try:- return self._run_sync(operation(self._get_client()))- except Exception as exc:- text = f"{type(exc).__name__}: {exc}".lower()- if self._mode != "local_embedded" or not any(m in text for m in _RETRIABLE_CONNECTION_MARKERS):- raise- logger.info("Hindsight embedded daemon appears unreachable; recreating client and retrying once: %s", exc)- self._client = None- self._client = client = self._get_client()- return self._run_sync(operation(client))-- # -- retain writer thread + server-side visibility --------------------------- def _ensure_writer(self) -> None:- """Lazy-start the single retain-writer thread (tools-only providers never pay for it)."""- if (thread := self._writer_thread) is not None and thread.is_alive():- return- # A previous writer may have exited after shutdown(); allow the fresh one to drain.- self._shutting_down.clear()- thread = spawn_context_thread(self._writer_loop, name="hindsight-writer")- self._writer_thread = self._sync_thread = thread- thread.start()-- def _register_atexit(self) -> None:- """Idempotent atexit drain: a CLI exit that skips MemoryManager.shutdown_all()- must not race interpreter teardown."""- if not self._atexit_registered:- self._atexit_registered = True- atexit.register(self._atexit_shutdown)-- def _writer_loop(self) -> None:- """Drain the retain queue serially until the sentinel. A failing job can't- kill the writer; task_done() always fires so queue.join() works."""- while True:- try:- job = self._retain_queue.get(timeout=1.0)- except queue.Empty:- if self._shutting_down.is_set():- return- continue- try:- if job is _WRITER_SENTINEL:- return- job()- except Exception as exc:- logger.warning("Hindsight retain failed: %s", exc, exc_info=True)- finally:- self._retain_queue.task_done()-- def _atexit_shutdown(self) -> None:- try:- if not self._shutting_down.is_set():- self.shutdown()- except Exception as exc:- logger.debug("Hindsight atexit shutdown failed: %s", exc)-- def _track_retain_ops(self, retain_response, bank_id: str) -> None:- """Record the async ``operation_id``/``operation_ids`` of an aretain_batch reply- (pending until recall-visible). No id (older API / sync completion) leaves- only the local queue drain as a signal."""- raw_ids = [getattr(retain_response, "operation_id", None), *(getattr(retain_response, "operation_ids", None) or [])]- if ids := [str(op) for op in raw_ids if op]:- self._retain_ops_bank_id = bank_id- with self._pending_retain_ops_lock:- self._pending_retain_ops.update(ids)-- def _is_retain_op_complete(self, bank_id: str, op_id: str) -> bool:- """True when a server-side retain op is done or gone (completed ops are evicted,- so 404 = no longer pending). Transient errors -> False, caller keeps waiting."""- from hindsight_client_api.exceptions import NotFoundException-- try:- resp = self._run_hindsight_operation(- lambda client: client.operations.get_operation_status(bank_id=bank_id, operation_id=op_id)- )- except NotFoundException:- return True- except Exception as exc:- logger.debug("Prefetch: operation status check failed for %s: %s", op_id, exc)- return False- return str(getattr(resp, "status", "") or "").lower() in {"completed", "failed"}-- def _wait_for_retains_drained(self, timeout: float) -> bool:- """Block up to *timeout* s for the last retain to become recall-visible- (prefetch thread only, never the reply path). Two barriers on one budget:- (1) the writer queue drains — polls ``unfinished_tasks`` rather than- ``queue.join()`` so a wedged write can't hang the prefetch; (2) the- server-side async ops complete (async retain returns on acceptance, not- durability). False on timeout/shutdown."""- deadline = None if timeout <= 0 else time.monotonic() + timeout- expired = lambda: deadline is not None and time.monotonic() >= deadline # noqa: E731- while self._retain_queue.unfinished_tasks > 0:- if self._shutting_down.is_set():- return False- if expired():- logger.debug("Prefetch: retain drain timed out after %.1fs (%d pending)",- timeout, self._retain_queue.unfinished_tasks)- return False- time.sleep(0.05)- return self._wait_for_server_retain_ops(expired, timeout)-- def _wait_for_server_retain_ops(self, _expired: Callable[[], bool], timeout: float) -> bool:- """Poll tracked async retain ops until complete or *_expired()* (deadline- predicate). Ops still pending at the deadline are DROPPED: keeping them- would let a permanently failing status endpoint burn the full timeout on- EVERY later prefetch (a per-turn latency penalty via prefetch()'s bounded- join). Trades a possibly-stale recall for liveness; WARNING once per prefetch."""- while True:- with self._pending_retain_ops_lock:- bank_id = self._retain_ops_bank_id or self._bank_id- pending = list(self._pending_retain_ops)- if not pending:- return True- if self._shutting_down.is_set():- return False- done: set[str] = set()- for op_id in pending:- if self._shutting_down.is_set():- return False- if _expired():- break- if self._is_retain_op_complete(bank_id, op_id):- done.add(op_id)- with self._pending_retain_ops_lock:- self._pending_retain_ops.difference_update(done)- if not self._pending_retain_ops:- return True- dropped = len(self._pending_retain_ops) if _expired() else 0- if dropped:- self._pending_retain_ops.clear()- if dropped:- logger.warning("Prefetch: server retain visibility timed out after %.1fs; "- "dropping %d unresolved op(s) so later prefetches stay "- "bounded (recall may miss the just-completed turn)", timeout, dropped)- return False- time.sleep(self._RETAIN_OP_POLL_INTERVAL_S)-- # -- retain target ------------------------------------------------------------- def _resolve_retain_target(self, fallback_document_id: str) -> tuple[str, str | None]:- """(document_id, update_mode) from live API capability: >= 0.5.0 reuses the- stable session-scoped id with ``update_mode='append'``; older APIs get- *fallback_document_id* (per-process unique) and no update_mode — the only- way the resume-overwrite fix works there. The /version probe targets the- embedded client's dynamic per-profile port when running, else api_url.-- On Hindsight ≥ 0.5.0 the API supports ``update_mode='append'``, which lets us reuse a stable- session-scoped ``document_id`` across process lifecycles without overwriting prior turns. On older- APIs we fall back to *fallback_document_id* (the per-process unique ``f"{session_id}-{start_ts}"``- minted at initialize / switch time) and don't pass ``update_mode`` at all — that's the only way the- resume-overwrite fix (#6654) keeps working on legacy servers.- """- url = getattr(self._client, "url", None) if self._mode == "local_embedded" else None- probe_url = str(url) if url else (self._api_url or "")- if self._session_id and _check_api_supports_update_mode_append(probe_url, self._api_key):- return self._session_id, "append"- return fallback_document_id, None-- # -- lifecycle ----------------------------------------------------------------- def initialize(self, session_id: str, **kwargs) -> None:- self._session_id = str(session_id or "").strip()- self._parent_session_id = str(kwargs.get("parent_session_id", "") or "").strip()- # Status channel for the retain indicator (recall reports via recall_status()).- if callable(kwargs.get("status_callback")):- self._status_callback = kwargs["status_callback"]- # Gated presentation for automatic startup warnings (agent._emit_warning on CLI).- self._warning_callback = kwargs.get("warning_callback") if callable(kwargs.get("warning_callback")) else None- self._platform = str(kwargs.get("platform") or "cli")- # session_id stays in tags so processes for one session remain filterable together.- self._document_id = _mint_document_id(self._session_id)- _maybe_upgrade_client()-- self._config = cfg = _load_config()- for name in _SESSION_KWARGS:- setattr(self, f"_{name}", str(kwargs.get(name) or "").strip())- self._turn_index = self._last_retained_turn_count = 0- self._session_turns = []- self._mode = cfg.get("mode", "cloud")- self._timeout = self._int_setting("timeout", "HINDSIGHT_TIMEOUT", _DEFAULT_TIMEOUT)- self._idle_timeout = self._int_setting("idle_timeout", "HINDSIGHT_IDLE_TIMEOUT", _DEFAULT_IDLE_TIMEOUT)- if self._mode == "local": # legacy alias- self._mode = "local_embedded"- if self._mode == "local_embedded":- # Must precede the daemon_embed_manager import, which reads it at import time.- _export_port_health_grace_timeout(cfg)- available, reason = _check_local_runtime()- if not available:- logger.warning("Hindsight local mode disabled because its runtime could not be imported: %s.%s",- reason, _local_runtime_hint(reason))- self._mode = "disabled"- return- self._apply_connection_settings(cfg)- self._apply_retain_settings(cfg)- self._apply_recall_settings(cfg)-- client_version = "unknown"- with contextlib.suppress(Exception):- from importlib.metadata import version as pkg_version- client_version = pkg_version("hindsight-client")- logger.info("Hindsight initialized: mode=%s, api_url=%s, bank=%s, budget=%s, memory_mode=%s, prefetch_method=%s, client=%s",- self._mode, self._api_url, self._bank_id, self._budget, self._memory_mode, self._prefetch_method, client_version)- if self._bank_id_template:- logger.debug("Hindsight bank resolved from template %r: profile=%s workspace=%s platform=%s user=%s -> bank=%s",- self._bank_id_template, self._agent_identity, self._agent_workspace,- self._platform, self._user_id, self._bank_id)- logger.debug("Hindsight config: auto_retain=%s, auto_recall=%s, retain_every_n=%d, "- "retain_async=%s, retain_context=%s, recall_max_tokens=%d, recall_max_input_chars=%d, tags=%s, recall_tags=%s",- self._auto_retain, self._auto_recall, self._retain_every_n_turns,- self._retain_async, self._retain_context, self._recall_max_tokens, self._recall_max_input_chars,- self._tags, self._recall_tags)-- if self._mode == "local_embedded":- self._start_embedded_daemon()-- def _apply_connection_settings(self, cfg: dict) -> None:- """Endpoint, bank and mode selectors from *cfg* (env fallbacks where documented)."""- self._api_key = _cloud_api_key(cfg)- default_url = _DEFAULT_LOCAL_URL if self._mode in {"local_embedded", "local_external"} else _DEFAULT_API_URL- self._api_url = cfg.get("api_url") or get_secret("HINDSIGHT_API_URL", "") or default_url- self._llm_base_url = cfg.get("llm_base_url", "")-- banks = cfg_get(cfg, "banks", "hermes", default={})- self._bank_id_template = cfg.get("bank_id_template", "") or ""- self._bank_id = _resolve_bank_id_template(- self._bank_id_template,- fallback=cfg.get("bank_id") or banks.get("bankId", "hermes"),- profile=self._agent_identity, workspace=self._agent_workspace,- platform=self._platform, user=self._user_id, session=self._session_id,- )- budget = cfg.get("recall_budget") or cfg.get("budget") or banks.get("budget", "mid")- self._budget = budget if budget in _VALID_BUDGETS else "mid"- memory_mode = cfg.get("memory_mode", "hybrid")- self._memory_mode = memory_mode if memory_mode in _SYSTEM_PROMPT_TAILS else "hybrid"- prefetch_method = cfg.get("recall_prefetch_method") or cfg.get("prefetch_method", "recall")- self._prefetch_method = prefetch_method if prefetch_method in {"recall", "reflect"} else "recall"- self._bank_mission = cfg.get("bank_mission", "")- self._bank_retain_mission = cfg.get("bank_retain_mission") or None-- def _apply_retain_settings(self, cfg: dict) -> None:- def _cfg_or_env(key: str, env_var: str, default: str = "") -> Any:- # The env half is the same per-profile value ``_load_config`` resolves through the scope;- # a raw read here handed a multiplexed secondary the DEFAULT profile's retain shaping back.- return cfg.get(key) or _scoped_setting(env_var, default)-- self._retain_tags = _normalize_retain_tags(_cfg_or_env("retain_tags", "HINDSIGHT_RETAIN_TAGS"))- self._tags = self._retain_tags or None- self._observation_scopes = _normalize_observation_scopes(- _cfg_or_env("observation_scopes", "HINDSIGHT_RETAIN_OBSERVATION_SCOPES"))- self._retain_source = str(_cfg_or_env("retain_source", "HINDSIGHT_RETAIN_SOURCE", _DEFAULT_RETAIN_SOURCE)).strip()- self._retain_user_prefix = str(_cfg_or_env("retain_user_prefix", "HINDSIGHT_RETAIN_USER_PREFIX", "User")).strip() or "User"- self._retain_assistant_prefix = (- str(_cfg_or_env("retain_assistant_prefix", "HINDSIGHT_RETAIN_ASSISTANT_PREFIX", "Assistant")).strip()- or "Assistant"- )- self._apply_retain_policy(cfg)-- def _apply_retain_policy(self, cfg: dict) -> None:- """Pure-config retain knobs (no env/secret reads; ``{}`` yields the defaults)."""- self._auto_retain = cfg.get("auto_retain", True)- self._retain_every_n_turns = max(1, int(cfg.get("retain_every_n_turns", 1)))- self._retain_context = cfg.get("retain_context", _RETAIN_CONTEXT_DEFAULT)- self._retain_async = cfg.get("retain_async", True)- # On by default so the user SEES memory working whether or not the model- # mentions it; off switch for customer-facing agents (recall_indicator too).- self._retain_indicator = bool(cfg.get("retain_indicator", True))- # The next turn's warm prefetch could read BEFORE an async retain is- # recall-visible; when True it first waits (bounded, off the reply path)- # for the queue to drain AND the server-side op(s) to complete.- self._prefetch_waits_for_retain = cfg.get("prefetch_waits_for_retain", True)- self._prefetch_retain_drain_timeout = float(cfg.get("prefetch_retain_drain_timeout", 10.0))-- def _apply_recall_settings(self, cfg: dict) -> None:- """Recall knobs are pure config too (``{}`` yields the defaults)."""- self._recall_tags = cfg.get("recall_tags") or None- self._recall_tags_match = cfg.get("recall_tags_match", "any")- self._auto_recall = cfg.get("auto_recall", True)- self._recall_sync = bool(cfg.get("recall_sync", False))- self._recall_max_tokens = int(cfg.get("recall_max_tokens", 4096))- self._recall_max_input_chars = int(cfg.get("recall_max_input_chars", 800))- # None -> observation-only (Hindsight's consolidated, deduplicated layer; raw- # world/experience facts re-ship the evidence they summarize and burn the- # recall_max_tokens budget); a comma-separated string is accepted for parity- # with recall_tags; an explicit list broadens or disables the filter.- configured_types = cfg.get("recall_types")- if isinstance(configured_types, str):- self._recall_types = [t.strip() for t in configured_types.split(",") if t.strip()]- else:- self._recall_types = list([] if configured_types is None else configured_types) or ["observation"]- self._recall_prompt_preamble = cfg.get("recall_prompt_preamble", "")- self._recall_indicator = bool(cfg.get("recall_indicator", True))-- def _start_embedded_daemon(self) -> None:- """Start the embedded daemon on a background thread (Rich output -> log file)."""- # PostgreSQL's initdb refuses root; without this guard the start thread- # retries forever, reloading embedding models (~958MB RAM, ~33% CPU)- # with no user-visible error.- if hasattr(os, "geteuid") and os.geteuid() == 0:- msg = ("Hindsight local_embedded mode cannot run as root "- "(PostgreSQL initdb refuses root). Skipping the embedded "- "memory daemon. Run Hermes as a non-root user, or switch "- "to cloud / local_external mode via 'hermes memory setup'.")- logger.warning(msg)- # Surface to the terminal too — a daemon that never starts would otherwise fail silently and- # the user would only see Hermes get sluggish (issue #13125). This is an automatic- # startup diagnostic: it goes through the agent's gated warning sink when wired,- # otherwise through the shared render boundary; the log line above never does.- with contextlib.suppress(Exception):- cb = getattr(self, "_warning_callback", None)- if cb is not None:- cb(msg)- else:- from gateway.warning_notifications import render_notification- render_notification(lambda: print(f" ⚠ {msg}", file=sys.stderr, flush=True),- platform=getattr(self, "_platform", "cli"))- self._mode = "disabled"- return- spawn_context_thread(self._daemon_start_worker, name="hindsight-daemon-start").start()-- def _daemon_start_worker(self) -> None:- import traceback- log_path = get_hermes_home() / "logs" / "hindsight-embed.log"- log_path.parent.mkdir(parents=True, exist_ok=True)-- def _log(text: str) -> None:- with open(log_path, "a", encoding="utf-8") as f:- f.write(text)-- try:- # Rich console -> our log file (redirecting global fds would capture other threads).- import hindsight_embed.daemon_embed_manager as dem- from rich.console import Console- dem.console = Console(file=open(log_path, "a", encoding="utf-8"), force_terminal=False)-- client = self._get_client()- profile = self._config.get("profile", "hermes")- # Profile .env out of sync with config -> rewrite and restart a running daemon.- # Fail-closed on key material: when this process holds no key (no secret- # scope on this thread) but the file does, a rewrite would destroy the- # only key copy the daemon subprocess can read. Skip the write AND the- # stop: restarting the daemon now would boot it keyless, which is the- # exact outage this guards against. _get_client() above already passed- # whatever key WAS available into the in-process client kwargs.- if _load_simple_env(_embedded_profile_env_path(self._config)) != _build_embedded_profile_env(self._config):- if _may_rewrite_profile_env(self._config):- _materialize_embedded_profile_env(self._config)- if client._manager.is_running(profile):- _log("\n=== Config changed, restarting daemon ===\n")- client._manager.stop(profile)- else:- logger.warning(- "Hindsight profile env for %r holds an LLM API key this process cannot see "- "(no secret scope); leaving the file untouched so the daemon keeps its key.",- profile)- _log("\n=== Profile env has a key this process cannot see; left untouched ===\n")- client._ensure_started()- _log("\n=== Daemon started successfully ===\n")- except Exception as e:- _log(f"\n=== Daemon startup failed: {e} ===\n" + traceback.format_exc())-- def system_prompt_block(self) -> str:- mode = self._memory_mode if self._memory_mode in _SYSTEM_PROMPT_TAILS else "hybrid"- label = "" if mode == "hybrid" else f" ({mode} mode)"- return f"# Hindsight Memory\nActive{label}. Bank: {self._bank_id}, budget: {self._budget}.\n{_SYSTEM_PROMPT_TAILS[mode]}"-- # -- recall -------------------------------------------------------------------- def _recall_disabled(self) -> bool:- """Guards shared by the async and synchronous recall paths."""- why = ("tools-only mode" if self._memory_mode == "tools" else "auto_recall disabled" if not self._auto_recall- else "shutting down" if self._shutting_down.is_set() else None)- if why:- logger.debug("Prefetch: skipped (%s)", why)- return why is not None-- def _recall(self, query: str) -> list:- kwargs: dict = {"bank_id": self._bank_id, "query": query, "budget": self._budget, "max_tokens": self._recall_max_tokens}- if self._recall_tags:- kwargs.update(tags=self._recall_tags, tags_match=self._recall_tags_match)- if self._recall_types:- kwargs["types"] = self._recall_types- resp = self._run_hindsight_operation(lambda client: client.arecall(**kwargs))- return resp.results or []-- def _reflect(self, query: str) -> str | None:- resp = self._run_hindsight_operation(- lambda client: client.areflect(bank_id=self._bank_id, query=query, budget=self._budget)- )- return resp.text-- def _do_recall(self, query: str) -> tuple[str, int]:- """One recall/reflect for *query* (background prefetch and ``recall_sync`` paths)- -> (text, memory count); the count is 0 for reflect (synthesis) and on error."""- if self._recall_max_input_chars:- query = query[:self._recall_max_input_chars]- try:- if self._prefetch_method == "reflect":- logger.debug("Recall: calling reflect (bank=%s, query_len=%d)", self._bank_id, len(query))- return self._reflect(query) or "", 0- logger.debug("Recall: calling recall (bank=%s, query_len=%d, budget=%s)",- self._bank_id, len(query), self._budget)- results = self._recall(query)- logger.debug("Recall: returned %d results", len(results))- return "\n".join(f"- {r.text}" for r in results if r.text), len(results)- except Exception as e:- logger.debug("Hindsight recall failed: %s", e, exc_info=True)- return "", 0-- def _finish_prefetch(self, result: str, count: int) -> str:- """Record indicator state (cleared on empty turns, never a stale count); format the block."""- self._last_recall_returned, self._last_recall_count = bool(result), count if result else 0- if not result:- logger.debug("Prefetch: no results available")- return ""- logger.debug("Prefetch: returning %d chars of context", len(result))- header = self._recall_prompt_preamble or (- "# Hindsight Memory (persistent cross-session context)\n"- "Use this to answer questions about the user and prior sessions. "- "Do not call tools to look up information that is already present here."- )- return f"{header}\n\n{result}"-- def _join_prefetch(self, timeout: float, *, log: bool = False) -> None:- if not (self._prefetch_thread and self._prefetch_thread.is_alive()):- return- if log:- logger.debug("Prefetch: waiting for background thread to complete")- self._prefetch_thread.join(timeout=timeout)-- def prefetch(self, query: str, *, session_id: str = "") -> str:- # Opt-in: recall synchronously against the *current* message so the- # injected memories match this turn's query, not the previous turn's.- # See NousResearch/hermes-agent#5820.- if self._recall_sync:- return self._finish_prefetch(*(("", 0) if self._recall_disabled() else self._do_recall(query)))- # Default: the background worker's result for the previous turn (capped join).- self._join_prefetch(3.0, log=True)- with self._prefetch_lock:- result, count = self._prefetch_result, self._prefetch_count- self._prefetch_result, self._prefetch_count = "", 0- return self._finish_prefetch(result, count)-- def recall_status(self) -> Optional[RecallStatus]:- """Count injected by the last prefetch; None if nothing injected or ``recall_indicator=false``."""- if not self._recall_indicator or not self._last_recall_returned:- return None- return RecallStatus(provider_label="Hindsight", count=self._last_recall_count, glyph=_HINDSIGHT_GLYPH)-- def queue_prefetch(self, query: str, *, session_id: str = "") -> None:- # Sync mode recalls live each turn — nothing to prime in the background.- if self._recall_sync or self._recall_disabled():- return-- def _run():- # Wait (bounded, off the reply path) for the just-completed turn's- # retain to be recall-visible so the warmed context includes it.- if self._prefetch_waits_for_retain:- self._wait_for_retains_drained(self._prefetch_retain_drain_timeout)- text, count = self._do_recall(query)- if text:- with self._prefetch_lock:- self._prefetch_result, self._prefetch_count = text, count-- self._prefetch_thread = spawn_context_thread(_run, name="hindsight-prefetch")- self._prefetch_thread.start()-- # -- retain -------------------------------------------------------------------- def _build_turn_messages(self, user_content: str, assistant_content: str) -> List[Dict[str, str]]:- now = _event_timestamp() # one turn -> both messages share the event timestamp- return [{"role": role, "content": f"{prefix}: {content}", "timestamp": now} for role, prefix, content in- (("user", self._retain_user_prefix, user_content), ("assistant", self._retain_assistant_prefix, assistant_content))]-- def _build_metadata(self, *, message_count: int, turn_index: int) -> Dict[str, str]:- metadata: Dict[str, str] = {- # UTC write/audit time (event time lives on the item timestamp).- "retained_at": datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z"),- "message_count": str(message_count),- "turn_index": str(turn_index),- }- if self._retain_source:- metadata["source"] = self._retain_source- metadata.update({name: value for name in _METADATA_ATTRS if (value := getattr(self, f"_{name}"))})- return metadata-- def _build_retain_kwargs(self, content: str, *, context: str | None = None,- metadata: Dict[str, str] | None = None, tags: List[str] | None = None,- occurred_at: str | None = None, update_mode: str | None = None) -> Dict[str, Any]:- """Build one aretain_batch item. The server resolves occurred_start/end (incl.- relative phrases in content) from the item timestamp: explicit occurred_at- wins, else the configured event clock."""- item: Dict[str, Any] = {- # See #93568.- "content": content,- "metadata": metadata or self._build_metadata(message_count=1, turn_index=self._turn_index),- "timestamp": (occurred_at or "").strip() or _event_timestamp(),- }- merged_tags = _normalize_retain_tags(list(self._retain_tags) + _normalize_retain_tags(tags))- item.update({k: v for k, v in (("context", context), ("update_mode", update_mode)) if v is not None})- item.update({k: v for k, v in (("tags", merged_tags), ("observation_scopes", self._observation_scopes)) if v})- return item-- def _retain_batch(self, item: dict, *, bank_id: str, document_id: str | None = None,- retain_async: bool | None = None):- """Dispatch one item via aretain_batch (bank_id/document_id/retain_async are- call-level args, never item keys)."""- kwargs: Dict[str, Any] = {"bank_id": bank_id, "items": [item], "document_id": document_id, "retain_async": retain_async}- kwargs = {k: v for k, v in kwargs.items() if v is not None}- return self._run_hindsight_operation(lambda client: client.aretain_batch(**kwargs))-- def _make_turn_retain_job(self, turns: list[str], *, document_id: str, update_mode: str | None,- label: str, track_ops: bool = True) -> Callable[[], None]:- """Writer job shipping *turns* as one document. Inputs are snapshotted NOW: the- writer runs after later sync_turn() calls mutate _session_turns/_turn_index/_session_id."""- content = "[" + ",".join(turns) + "]"- metadata = self._build_metadata(message_count=len(turns) * 2, turn_index=self._turn_index)- lineage = (("session", self._session_id), ("parent", self._parent_session_id))- tags = [f"{kind}:{sid}" for kind, sid in lineage if sid] or None- bank_id, retain_async, retain_context = self._bank_id, self._retain_async, self._retain_context-- def _job() -> None:- item = self._build_retain_kwargs(content, context=retain_context, metadata=metadata,- tags=tags, update_mode=update_mode)- logger.debug("Hindsight %s: bank=%s, doc=%s, mode=%s, async=%s, content_len=%d, num_turns=%d",- label, bank_id, document_id, update_mode, retain_async, len(content), len(turns))- resp = self._retain_batch(item, bank_id=bank_id, document_id=document_id, retain_async=retain_async)- # Async retains are only *accepted* here; track the op id(s) so the- # next-turn prefetch can wait for true server-side completion.- if retain_async and track_ops:- self._track_retain_ops(resp, bank_id)- logger.debug("Hindsight %s succeeded", label)-- return _job-- def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:- """Enqueue a retain for the current turn (non-blocking; writer thread). Dropped- once shutdown() fired so post-exit retains never reach aiohttp during teardown."""- why = "auto_retain disabled" if not self._auto_retain else "shutting down" if self._shutting_down.is_set() else None- if why:- logger.debug("sync_turn: skipped (%s)", why)- return- if session_id:- self._session_id = str(session_id).strip()-- self._session_turns.append(json.dumps(self._build_turn_messages(user_content, assistant_content), ensure_ascii=False))- self._turn_counter = self._turn_index = self._turn_counter + 1- if remainder := self._turn_counter % self._retain_every_n_turns:- logger.debug("sync_turn: buffered turn %d (will retain at turn %d)",- self._turn_counter, self._turn_counter + (self._retain_every_n_turns - remainder))- return-- document_id, update_mode = self._resolve_retain_target(self._document_id)- # Append-capable APIs get only the delta since the last retain; legacy /- # overwrite APIs need the whole session because each retain replaces the document.- start = self._last_retained_turn_count if update_mode == "append" else 0- turns_to_retain = self._session_turns[start:]- if not turns_to_retain:- logger.debug("sync_turn: skipped append retain; no new turns since last retain")- return- logger.debug("sync_turn: retaining %d/%d turns, payload %d chars",- len(turns_to_retain), len(self._session_turns), sum(len(t) for t in turns_to_retain))-- job = self._make_turn_retain_job(turns_to_retain, document_id=document_id,- update_mode=update_mode, label="retain")- # Indicator fires only past every skip/buffer gate: solely on turns that persist.- # Model-independent status line; no-op without retain_indicator/status channel.- if self._retain_indicator and self._status_callback is not None:- try:- self._status_callback(f"{_HINDSIGHT_GLYPH} Hindsight — saving to memory…")- except Exception:- logger.debug("Retain indicator emit failed (non-fatal)", exc_info=True)- self._enqueue_retain(job)- # Advance the watermark only after the delta is queued so a later retain- # doesn't re-ship turns already handed to the writer.- if update_mode == "append":- # The job above holds its own copy, and append retains (here and flush-on-switch) only- # ever read the un-retained tail — so drop shipped turns instead of pinning every turn- # of a never-ending session (#62950). Overwrite mode resends the whole session and- # must keep them all.- self._session_turns.clear()- self._last_retained_turn_count = 0-- def _enqueue_retain(self, job: Callable[[], None]) -> None:- """Hand *job* to the (lazily started) writer and arm the atexit drain."""- self._ensure_writer()- self._register_atexit()- self._retain_queue.put(job)-- # -- tools --------------------------------------------------------------------- def get_tool_schemas(self) -> List[Dict[str, Any]]:- return [] if self._memory_mode == "context" else [RETAIN_SCHEMA, RECALL_SCHEMA, REFLECT_SCHEMA]-- def _tool_retain(self, args: dict) -> str:- content, context = args["content"], args.get("context")- item = self._build_retain_kwargs(content, context=context, tags=args.get("tags"),- occurred_at=args.get("occurred_at"))- logger.debug("Tool hindsight_retain: bank=%s, content_len=%d, context=%s",- self._bank_id, len(content), context)- self._retain_batch(item, bank_id=self._bank_id)- logger.debug("Tool hindsight_retain: success")- return "Memory stored successfully."-- def _tool_recall(self, args: dict) -> str:- query = args["query"]- logger.debug("Tool hindsight_recall: bank=%s, query_len=%d, budget=%s",- self._bank_id, len(query), self._budget)- results = self._recall(query)- logger.debug("Tool hindsight_recall: %d results", len(results))- return "\n".join(f"{i}. {r.text}" for i, r in enumerate(results, 1)) or "No relevant memories found."-- def _tool_reflect(self, args: dict) -> str:- query = args["query"]- logger.debug("Tool hindsight_reflect: bank=%s, query_len=%d, budget=%s",- self._bank_id, len(query), self._budget)- text = self._reflect(query) or ""- logger.debug("Tool hindsight_reflect: response_len=%d", len(text))- return text or "No relevant memories found."-- # tool name -> (required arg, handler, user-facing failure prefix)- _TOOL_HANDLERS = {- "hindsight_retain": ("content", _tool_retain, "Failed to store memory"),- "hindsight_recall": ("query", _tool_recall, "Failed to search memory"),- "hindsight_reflect": ("query", _tool_reflect, "Failed to reflect"),- }-- def handle_tool_call(self, tool_name: str, args: dict, **kwargs) -> str:- if tool_name not in self._TOOL_HANDLERS:- return tool_error(f"Unknown tool: {tool_name}")- required, handler, failure = self._TOOL_HANDLERS[tool_name]- if not args.get(required, ""):- return tool_error(f"Missing required parameter: {required}")- try:- return json.dumps({"result": handler(self, args)})- except Exception as e:- logger.warning("%s failed: %s", tool_name, e, exc_info=True)- return tool_error(f"{failure}: {e}")-- # -- session lifecycle --------------------------------------------------------- def on_session_switch(self, new_session_id: str, *, parent_session_id: str = "",- reset: bool = False, **kwargs) -> None:- """Rotate per-session state (/resume, /branch, /reset, /new, compression) so- writes don't land in the previous session's document. Always: flush buffered- turns under the OLD ids first (``retain_every_n_turns > 1`` would silently- lose them), join the in-flight prefetch and drop its result (no stale recall- for the new session), then set ``_session_id``, mint a fresh ``_document_id``- and clear the batch buffers. ``reset`` is accepted but unneeded: buffer- clearing is correct for every switch.-- Without this hook, initialize()-cached state (``_session_id``, ``_document_id``, ``_session_turns``,- ``_turn_counter``) would keep pointing at the previous session and writes would land in the wrong- document. See hermes-agent#6672.- Always update ``_session_id`` so metadata and tags on subsequent retains reflect the active session.- Always clear the accumulated batch buffers (``_session_turns``, ``_turn_counter``, ``_turn_index``)- — even for /resume and /branch, the new session's batching must start from zero so an in-flight- retain doesn't flush under the wrong ``_document_id``. See #1303.- """- new_id = str(new_session_id or "").strip()- if not new_id:- return-- # 1. Flush buffered turns under the OLD identifiers, resolved BEFORE the- # rotation (legacy: per-process unique; >=0.5.0: session-scoped + append).- if self._session_turns:- old_document_id, old_update_mode = self._resolve_retain_target(self._document_id)- job = self._make_turn_retain_job(list(self._session_turns), document_id=old_document_id,- update_mode=old_update_mode, label="flush-on-switch",- track_ops=False)-- def _flush():- try:- job()- except Exception as e:- logger.warning("Hindsight flush-on-switch failed: %s", e, exc_info=True)- # Same writer queue as sync_turn: FIFO behind queued old-session retains,- # no two threads racing aretain_batch on one document, shutdown drain intact.- if not self._shutting_down.is_set():- self._enqueue_retain(_flush)-- # 2. Drain the old session's in-flight prefetch and drop its result.- self._join_prefetch(3.0)- with self._prefetch_lock:- self._prefetch_result = ""-- # 3. Rotate to the new session.- if parent_session_id:- self._parent_session_id = str(parent_session_id).strip()- self._session_id, self._document_id = new_id, _mint_document_id(new_id)- self._session_turns = []- self._turn_counter = self._turn_index = self._last_retained_turn_count = 0- logger.debug("Hindsight on_session_switch: new_session=%s parent=%s reset=%s doc=%s",- self._session_id, self._parent_session_id, reset, self._document_id)-- def _close_client(self) -> None:- if self._mode != "local_embedded":- self._run_sync(self._client.aclose())- return- # HindsightEmbedded.close() closes its sync client from this thread ("attached- # to a different loop" before aiohttp releases the session): aclose the inner- # client on the shared loop first, then let the wrapper clean up bookkeeping.- inner_client = getattr(self._client, "_client", None)- if inner_client is not None and hasattr(inner_client, "aclose"):- _run_sync(inner_client.aclose())- with contextlib.suppress(Exception):- self._client._client = None- with contextlib.suppress(RuntimeError):- self._client.close()-- def shutdown(self) -> None:- logger.debug("Hindsight shutdown: stopping writer + waiting for background threads")- # Stop accepting retain jobs first so late sync_turn() calls are dropped.- self._shutting_down.set()- # The writer finishes in-flight work then exits on the sentinel; the- # bounded join keeps shutdown predictable even if the daemon is wedged.- if (writer := self._writer_thread) is not None and writer.is_alive():- self._retain_queue.put(_WRITER_SENTINEL)- writer.join(timeout=10.0)- if writer.is_alive():- logger.warning("Hindsight writer did not stop within 10s; abandoning %d pending retain(s)",- self._retain_queue.qsize())- self._join_prefetch(5.0)- if self._client is not None:- with contextlib.suppress(Exception):- self._close_client()- self._client = None- # The module-global loop is intentionally NOT stopped: it's shared by every- # provider in the process (one per gateway chat session); stopping it would- # strand siblings' aiohttp sessions ("Unclosed client session"). Daemon- # thread, reclaimed at process exit.---# The module-global background event loop (_loop / _loop_thread) is intentionally NOT stopped here. It is-# shared across every HindsightMemoryProvider instance in the process — the plugin loader creates a new-# provider per AIAgent, and the gateway creates one AIAgent per concurrent chat session. Stopping the loop-# from one provider's shutdown() strands the aiohttp ClientSession + TCPConnector owned by every sibling-# provider on a dead loop, which surfaces as the "Unclosed client session" / "Unclosed connector" warnings-# reported in #11923. The loop runs on a daemon thread and is reclaimed on process exit; per-session cleanup-# happens via self._client.aclose() above.-def register(ctx) -> None:- """Register Hindsight as a memory provider plugin."""- ctx.register_memory_provider(HindsightMemoryProvider())---# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) -----# Names external plugins imported from this module before the Sep 2026 decomposition.-# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).-# The whole block is removed by reverting the commit that added it.-from dataclasses import dataclass # noqa: F401,E402-import importlib # noqa: F401,E402-# ---- END PLUGIN-COMPAT ----diff --git a/plugins/memory/hindsight/config_schema.py b/plugins/memory/hindsight/config_schema.pydeleted file mode 100644index 4a2f1dbf242..00000000000--- a/plugins/memory/hindsight/config_schema.py+++ /dev/null@@ -1,36 +0,0 @@-"""Hindsight's declared config surface — rendered by the generic desktop panel."""--from plugins.memory.config_schema import (- KIND_SECRET, KIND_SELECT, KIND_TEXT, ProviderConfigSchema, ProviderField, ProviderFieldOption,-)--CONFIG_SCHEMA = ProviderConfigSchema(- name="hindsight",- label="Hindsight",- fields=(- ProviderField(- key="mode", label="Mode", kind=KIND_SELECT, default="cloud",- description="How Hermes connects to Hindsight.",- options=(- ProviderFieldOption("cloud", "Cloud", "Hindsight Cloud API (lightweight, just needs an API key)"),- ProviderFieldOption("local_external", "Local External", "Connect to an existing Hindsight instance"),- ),- inline=True,- ),- ProviderField(- key="api_key", label="API key", kind=KIND_SECRET, env_key="HINDSIGHT_API_KEY",- description="Used to authenticate with the Hindsight API.",- placeholder="Enter Hindsight API key", inline=True,- ),- ProviderField(- key="api_url", label="API URL", kind=KIND_TEXT, default="https://api.hindsight.vectorize.io",- aliases=("apiUrl",), env_fallbacks=("HINDSIGHT_API_URL",), inline=True,- ),- ProviderField(key="bank_id", label="Bank ID", kind=KIND_TEXT, default="hermes", aliases=("bankId",), inline=True),- ProviderField(- key="recall_budget", label="Recall budget", kind=KIND_SELECT, default="mid", aliases=("budget",),- options=tuple(ProviderFieldOption(b, b) for b in ("low", "mid", "high")),- inline=True,- ),- ),-)diff --git a/plugins/memory/hindsight/embedded.py b/plugins/memory/hindsight/embedded.pydeleted file mode 100644index 27bf2de2e9b..00000000000--- a/plugins/memory/hindsight/embedded.py+++ /dev/null@@ -1,230 +0,0 @@-"""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--import contextlib-import importlib-import logging-import os-import sys-from pathlib import Path-from typing import Any--from agent.secret_scope import UnscopedSecretError, get_secret--from .settings import _DEFAULT_IDLE_TIMEOUT, _daemon_llm_provider, _parse_int_setting--logger = logging.getLogger(__name__.rpartition(".")[0])--# 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.-# Env var the embedded daemon manager reads (at import time, as a module-level constant) to size the grace-# window it waits for a slow /health before declaring a daemon stale and killing it. We surface it as plugin-# config so users can raise it without hand-setting an env var, consistent with "config.json, not raw env-# vars". See #13125.-_PORT_HEALTH_GRACE_ENV = "HINDSIGHT_EMBED_PORT_HEALTH_GRACE_TIMEOUT"--# Stale embedded-daemon connection markers (client recreated, operation retried once).-_RETRIABLE_CONNECTION_MARKERS = (- "cannot connect to host",- # Connection-establishment / DNS failure message patterns. These surface when the exception TYPE is- # generic (RuntimeError/Exception from a local shim, MCP bridge, subprocess wrapper, or an SDK that- # re-raises without chaining) so the _TRANSPORT_ERROR_TYPES check never fires, and the error carries no- # HTTP status. Without message-level matching they fall through to FailoverReason.unknown, which misses- # the transport eager-fallback path in the retry loop (unknown retries the same dead endpoint for the- # full budget before fallback). Ported from anomalyco/opencode#40707, which hit the same bug shape:- # serialized midstream errors matched by type only. Deliberately EXCLUDES mid-stream disconnect strings- # ("connection reset by peer", "peer closed connection", "unexpected eof", "socket hang up") — those- # belong to _SERVER_DISCONNECT_PATTERNS, whose classification step runs later and routes large sessions- # to context-overflow compression. A connection that was never established cannot be a server-side- # overflow rejection, so these are safe to classify as plain retryable transport.- "connection refused",- "connect call failed",- "clientconnectorerror",-)---def _export_port_health_grace_timeout(config: dict[str, Any]) -> None:- """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 == "":- return- try:- seconds = float(raw)- except (TypeError, ValueError):- return logger.warning("Invalid Hindsight port_health_grace_timeout %r; ignoring.", raw)- if seconds < 0:- return logger.warning("Negative Hindsight port_health_grace_timeout %r; ignoring.", raw)- os.environ.setdefault(_PORT_HEALTH_GRACE_ENV, repr(seconds))---def _check_local_runtime() -> tuple[bool, str | None]:- """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:- for module in ("hindsight", "hindsight_embed.daemon_embed_manager", "sentence_transformers"):- importlib.import_module(module)- return True, None- except Exception as exc:- return False, str(exc)---def _local_runtime_hint(reason: str | None) -> str:- """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'``.-- ``local_embedded`` imports ``from hindsight import HindsightEmbedded``, which is provided only by the- ``hindsight-all`` package (its wheel ships the top-level ``hindsight`` module).- NousResearch/hermes-agent#7718.- """- text = (reason or "").lower()- if "no module named" in text and any(m in text for m in ("hindsight'", 'hindsight"', "hindsight_embed")):- return (- f" Install the embedded runtime with: uv pip install --python "- f"{sys.executable} hindsight-all — or run 'hermes memory setup'. "- "(local_embedded needs the 'hindsight-all' package, which provides the "- "top-level 'hindsight' module; 'hindsight-client' alone only covers "- "cloud / local_external.)"- )- return ""---def _load_simple_env(path) -> dict[str, str]:- """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 {}- pairs = (line.split("=", 1) for line in path.read_text(encoding="utf-8-sig", errors="replace").splitlines()- if line and not line.startswith("#") and "=" in line)- return {key.strip(): value.strip() for key, value in pairs}---def _embedded_profile_env_path(config: dict[str, Any]) -> Path:- profile = str(config.get("profile", "hermes") or "hermes")- return Path.home() / ".hindsight" / "profiles" / f"{profile}.env"---def _on_disk_llm_api_key(config: dict[str, Any]) -> str:- """The key currently persisted in the profile env file ("" when absent)."""- with contextlib.suppress(Exception):- return _load_simple_env(_embedded_profile_env_path(config)).get("HINDSIGHT_API_LLM_API_KEY", "") or ""- return ""---def _embedded_llm_api_key(config: dict[str, Any]) -> str:- """Resolve the LLM API key: explicit config first, then the profile secret- scope, then the on-disk profile env as a last resort.-- The disk fallback is the durability core: the background daemon-start- worker usually runs with no secret scope, and without it the client would- be built keyless — its ``ensure_running(config)`` merge would then- overwrite the file's good key with emptiness inside the upstream manager- (``_register_profile`` → ``create_profile`` rewrite). Falling back to the- persisted key keeps the in-process client, the file compare, and the- daemon subprocess all keyed from the same surviving copy.- """- if config.get("llmApiKey") or config.get("llm_api_key"):- return config.get("llmApiKey") or config.get("llm_api_key")- # NOTE: the vault item is named HINDSIGHT_API_LLM_API_KEY (matching the- # daemon's env var), not HINDSIGHT_LLM_API_KEY (the setup-wizard name).- # Accept both so vault-fed scopes resolve regardless of which name the- # secret source carries.- try:- scoped = get_secret("HINDSIGHT_API_LLM_API_KEY", "") or get_secret("HINDSIGHT_LLM_API_KEY", "")- except UnscopedSecretError:- # Multiplexed gateway with no profile scope on this thread: never let- # a missing scope read os.environ (another profile's key may live- # there). Fall through to the on-disk copy below.- scoped = ""- if scoped:- return scoped- return _on_disk_llm_api_key(config)---def _may_rewrite_profile_env(config: dict[str, Any]) -> bool:- """Whether rewriting the profile env file is safe right now.-- False exactly when the build has no key (no scope, no config key) but the- file holds one: a rewrite would clobber live credentials with emptiness.- All other mismatches (model/provider/base-url/idle-timeout drift, missing- file, key rotation to a new non-empty value) remain writable.- """- if _build_embedded_profile_env(config).get("HINDSIGHT_API_LLM_API_KEY"):- return True- return not _on_disk_llm_api_key(config)---def _build_embedded_profile_env(config: dict[str, Any], *, llm_api_key: str | None = None) -> dict[str, str]:- """Build the profile-scoped env that standalone hindsight-embed consumes."""- if llm_api_key is None:- llm_api_key = _embedded_llm_api_key(config)- env_values = {- "HINDSIGHT_API_LLM_PROVIDER": str(_daemon_llm_provider(config.get("llm_provider", ""))),- "HINDSIGHT_API_LLM_API_KEY": str(llm_api_key or ""),- "HINDSIGHT_API_LLM_MODEL": str(config.get("llm_model", "")),- "HINDSIGHT_API_LOG_LEVEL": "info",- }- # Base URL is per-profile like the key beside it (the scoped key must not go to the default's host);- # on the scopeless daemon worker a miss is a miss, never os.environ (same rule as the key above).- base_url = config.get("llm_base_url")- if not base_url:- try:- base_url = get_secret("HINDSIGHT_API_LLM_BASE_URL", "") or ""- except UnscopedSecretError:- base_url = ""- if base_url:- env_values["HINDSIGHT_API_LLM_BASE_URL"] = str(base_url)- if (idle_timeout := config.get("idle_timeout")) is None:- idle_timeout = os.environ.get("HINDSIGHT_IDLE_TIMEOUT")- if idle_timeout is not None and idle_timeout != "":- env_values["HINDSIGHT_EMBED_DAEMON_IDLE_TIMEOUT"] = str(_parse_int_setting(idle_timeout, _DEFAULT_IDLE_TIMEOUT))- return env_values---def _secure_write_profile_env(profile_env: Path, content: str) -> None:- """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():- with contextlib.suppress(OSError):- os.chmod(profile_env, 0o600)- fd = os.open(str(profile_env), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)- with os.fdopen(fd, "w", encoding="utf-8") as fh:- fh.write(content)---def _validate_profile_env_permissions(profile_env: Path) -> None:- """Post-write check: owner-only on POSIX (Windows ACLs aren't mode bits; skipped)."""- if os.name != "posix":- return- import stat-- if stat.S_IMODE(profile_env.stat().st_mode) != 0o600:- with contextlib.suppress(OSError):- os.chmod(profile_env, 0o600)- if stat.S_IMODE(profile_env.stat().st_mode) != 0o600:- raise PermissionError(- f"Embedded Hindsight profile environment is not owner-only: {profile_env}"- )---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 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)- content = "".join(f"{key}={value}\n" for key, value in env_values.items())- try:- _secure_write_profile_env(profile_env, content)- _validate_profile_env_permissions(profile_env)- except BaseException:- with contextlib.suppress(OSError):- profile_env.unlink()- raise- return profile_envdiff --git a/plugins/memory/hindsight/plugin.yaml b/plugins/memory/hindsight/plugin.yamldeleted file mode 100644index 3495aa63cc9..00000000000--- a/plugins/memory/hindsight/plugin.yaml+++ /dev/null@@ -1,6 +0,0 @@-name: hindsight-version: 1.0.0-description: "Hindsight — long-term memory with knowledge graph, entity resolution, and multi-strategy retrieval."-pip_dependencies:- - "hindsight-client>=0.6.1"-requires_env: []diff --git a/plugins/memory/hindsight/settings.py b/plugins/memory/hindsight/settings.pydeleted file mode 100644index 6655b2a5d39..00000000000--- a/plugins/memory/hindsight/settings.py+++ /dev/null@@ -1,128 +0,0 @@-"""Hindsight plugin constants and pure config normalizers (no I/O, no origin imports)."""--from __future__ import annotations--import contextlib-import json-import logging-import re-from typing import Any, List--# Log under the plugin package's own logger name (loader-path independent).-logger = logging.getLogger(__name__.rpartition(".")[0])--_DEFAULT_API_URL = "https://api.hindsight.vectorize.io"-_DEFAULT_LOCAL_URL = "http://localhost:8888"-# Keep in sync with tools/lazy_deps.py ("memory.hindsight") and plugin.yaml.-_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`` 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'``; older APIs would silently-# overwrite prior turns under a stable document_id, so they keep the per-process id.-# Mirrors hindsight-integrations/openclaw — Hindsight 0.5.0 added `update_mode='append'` semantics on retain-# (vectorize-io/hindsight#932).-_MIN_VERSION_FOR_UPDATE_MODE_APPEND = "0.5.0"-_VALID_BUDGETS = {"low", "mid", "high"}-_PROVIDER_DEFAULT_MODELS = {- "openai": "gpt-4o-mini",- "anthropic": "claude-haiku-4-5",- "gemini": "gemini-3.6-flash",- "groq": "openai/gpt-oss-120b",- "openrouter": "qwen/qwen3.5-9b",- "minimax": "MiniMax-M2.7",- "ollama": "gemma3:12b",- "lmstudio": "local-model",- "openai_compatible": "your-model-name",-}-# The embedded daemon speaks OpenAI wire format for these providers.-_OPENAI_WIRE_PROVIDERS = {"openai_compatible", "openrouter"}-_OBSERVATION_SCOPE_KEYWORDS = {"per_tag", "combined", "all_combinations"}---def _parse_int_setting(value: Any, default: int) -> int:- """Parse an integer config/env value, falling back on invalid input."""- if value is None or value == "":- return default- try:- return int(value)- except (TypeError, ValueError):- logger.warning("Invalid integer Hindsight setting %r; using default %s", value, default)- return default---def _daemon_llm_provider(provider: str) -> str:- return "openai" if provider in _OPENAI_WIRE_PROVIDERS else provider---def _normalize_retain_tags(value: Any) -> List[str]:- """Normalize tag config/tool values to a deduplicated list of strings."""- if value is None:- return []- raw_items = value if isinstance(value, list) else [value]- if isinstance(value, str):- text = value.strip()- parsed = None- if text.startswith("["):- with contextlib.suppress(Exception):- parsed = json.loads(text)- raw_items = parsed if isinstance(parsed, list) else text.split(",")- normalized: list[str] = []- for item in raw_items:- tag = str(item).strip()- if tag and tag not in normalized:- normalized.append(tag)- return normalized---def _normalize_observation_scopes(value: Any) -> Any:- """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:- return text- if text.startswith("["):- try:- return _normalize_observation_scopes(json.loads(text))- except Exception:- return None- return None- if not isinstance(value, (list, tuple)):- return None- if all(isinstance(entry, str) for entry in value): # flat tag list -> one scope- value = [value]- scopes = [- [str(tag).strip() for tag in entry if str(tag).strip()] if isinstance(entry, (list, tuple))- else [entry.strip()] if isinstance(entry, str) and entry.strip() else []- for entry in value- ]- return [s for s in scopes if s] or None---def _sanitize_bank_segment(value: str) -> str:- """URL/filesystem-safe bank_id placeholder: runs outside ``[A-Za-z0-9_-]`` (per- ``str.isalnum``) become one dash; leading/trailing ``-``/``_`` are stripped."""- # \w == str.isalnum() + "_" for str patterns, so this matches the per-char rule.- return re.sub(r"[^\w-]+", "-", str(value)).strip("-_") if value else ""---def _resolve_bank_id_template(template: str, fallback: str, **placeholders: str) -> str:- """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 fallback- try:- rendered = template.format(**{k: _sanitize_bank_segment(v) for k, v in placeholders.items()})- except (KeyError, IndexError) as exc:- logger.warning("Invalid bank_id_template %r: %s — using fallback %r",- template, exc, fallback)- return fallback- return re.sub(r"([-_])\1+", r"\1", rendered).strip("-_") or fallbackdiff --git a/plugins/memory/hindsight/setup.py b/plugins/memory/hindsight/setup.pydeleted file mode 100644index e6fdbac3515..00000000000--- a/plugins/memory/hindsight/setup.py+++ /dev/null@@ -1,183 +0,0 @@-"""`hermes memory setup` wizard for the Hindsight provider (``post_setup``)."""--from __future__ import annotations--import contextlib-import json-import os-import sys-from pathlib import Path--from agent.secret_scope import get_secret-from hermes_cli.secret_prompt import masked_secret_prompt--from . import templates as _hs_templates-from .embedded import _embedded_profile_env_path, _load_simple_env, _materialize_embedded_profile_env-from .settings import (- _DEFAULT_API_URL, _DEFAULT_IDLE_TIMEOUT, _DEFAULT_LOCAL_URL, _DEFAULT_TIMEOUT, _MIN_CLIENT_VERSION,- _PROVIDER_DEFAULT_MODELS,-)--_MODE_VALUES = ["cloud", "local_embedded", "local_external"]-_MODE_ITEMS = [- ("Cloud", "Hindsight Cloud API (lightweight, just needs an API key)"),- ("Local Embedded", "Run Hindsight locally (downloads ~200MB, needs LLM key)"),- ("Local External", "Connect to an existing Hindsight instance"),-]---def _secret_prompt(label: str) -> str:- """Masked prompt on a TTY; plain readline when stdin is piped."""- sys.stdout.write(label)- sys.stdout.flush()- return masked_secret_prompt("") if sys.stdin.isatty() else sys.stdin.readline().strip()---def _select(title: str, items: list, values: list, current) -> str | None:- """Curses pick from *values*, defaulting to *current*; None when cancelled."""- from hermes_cli.memory_setup import _CANCELLED, _curses_select, _print_cancelled_setup-- default = values.index(current) if current in values else 0- idx = _curses_select(title, items, default=default, cancel_returns=_CANCELLED)- if idx == _CANCELLED:- _print_cancelled_setup()- return None- return values[idx]---def _write_env(env_path: Path, env_writes: dict) -> None:- """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()- new_lines = []- for line in existing:- key = line.split("=", 1)[0].strip() if "=" in line and not line.startswith("#") else None- new_lines.append(f"{key}={env_writes[key]}" if key in env_writes else line)- updated.add(key)- new_lines.extend(f"{k}={v}" for k, v in env_writes.items() if k not in updated)- env_path.write_text("\n".join(new_lines) + "\n", encoding="utf-8")---def _prompt_embedded_llm(llm_provider: str, provider_config: dict, env_writes: dict, hermes_env: Path) -> None:- """local_embedded wizard step: endpoint (openai_compatible only), model, LLM key."""- if llm_provider == "openai_compatible":- existing_base_url = provider_config.get("llm_base_url", "")- prompt = " LLM endpoint URL (e.g. http://192.168.1.10:8080/v1)" + (f" [{existing_base_url}]" if existing_base_url else "")- if val := input(prompt + ": ").strip():- provider_config["llm_base_url"] = val- elif llm_provider == "openrouter":- provider_config["llm_base_url"] = "https://openrouter.ai/api/v1"- current_model = provider_config.get("llm_model") or _PROVIDER_DEFAULT_MODELS.get(llm_provider, "gpt-4o-mini")- val = input(f" LLM model [{current_model}]: ").strip()- provider_config["llm_model"] = val or current_model- llm_key = _secret_prompt(" LLM API key: ")- env_writes["HINDSIGHT_LLM_API_KEY"] = llm_key or _load_simple_env(hermes_env).get("HINDSIGHT_LLM_API_KEY", "")---def run_setup(provider, hermes_home: str, config: dict) -> None:- """Interactive wizard — installs only the deps the selected mode needs."""- from hermes_cli.config import save_config-- from . import _load_config-- print("\n Configuring Hindsight memory:\n")-- existing_config = provider._config if isinstance(provider._config, dict) else _load_config()- if not isinstance(existing_config, dict):- existing_config = {}-- mode = _select(" Select mode", _MODE_ITEMS, _MODE_VALUES, existing_config.get("mode"))- if mode is None:- return- provider_config: dict = dict(existing_config, mode=mode)- env_writes: dict = {}- hermes_env = Path(hermes_home) / ".env"-- llm_provider = ""- if mode == "local_embedded":- llm_items = [(p, f"default model: {m}") for p, m in _PROVIDER_DEFAULT_MODELS.items()]- llm_provider = _select(" Select LLM provider", llm_items, list(_PROVIDER_DEFAULT_MODELS),- provider_config.get("llm_provider"))- if llm_provider is None:- return- provider_config["llm_provider"] = llm_provider-- print("\n Checking dependencies...")- # Environment-aware install: sealed hosted venvs redirect to the durable data volume.- from tools.lazy_deps import install_specs-- deps = ["hindsight-all"] if mode == "local_embedded" else [f"hindsight-client>={_MIN_CLIENT_VERSION}"]- outcome = install_specs(deps, timeout=120)- if outcome.ok:- print(" ✓ Dependencies up to date")- elif outcome.blocked:- print(f" ⚠ Cannot install dependencies: {outcome.reason}")- else:- print(f" ⚠ Install failed:\n{(outcome.stderr or '').strip()}")- print(f" Run manually: uv pip install --python {sys.executable} {' '.join(deps)}")-- if mode == "cloud":- print("\n Get your API key at https://ui.hindsight.vectorize.io\n")- existing_key = get_secret("HINDSIGHT_API_KEY", "") or ""- masked = f"...{existing_key[-4:]}" if len(existing_key) > 4 else "set"- api_key = _secret_prompt(f" API key (current: {masked}, blank to keep): " if existing_key else " API key: ")- if api_key:- env_writes["HINDSIGHT_API_KEY"] = api_key- if val := input(f" API URL [{_DEFAULT_API_URL}]: ").strip():- provider_config["api_url"] = val- elif mode == "local_external":- val = input(f" Hindsight API URL [{_DEFAULT_LOCAL_URL}]: ").strip()- provider_config["api_url"] = val or _DEFAULT_LOCAL_URL- if api_key := _secret_prompt(" API key (optional, blank to skip): "):- env_writes["HINDSIGHT_API_KEY"] = api_key- else:- _prompt_embedded_llm(llm_provider, provider_config, env_writes, hermes_env)-- provider_config.setdefault("bank_id", "hermes")- provider_config.setdefault("recall_budget", "mid")- # Preserve explicit 0 timeouts instead of treating them as blank.- timeouts = [("timeout", "HINDSIGHT_TIMEOUT", _DEFAULT_TIMEOUT)]- if mode == "local_embedded":- 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(hermes_env, env_writes)-- # Starter template (best-effort) only where the API is reachable now- # (local_embedded's daemon isn't up).- if _hs_templates.supported_for_mode(mode):- from hermes_cli.memory_setup import _CANCELLED, _curses_select-- default_url = _DEFAULT_LOCAL_URL if mode == "local_external" else _DEFAULT_API_URL- _hs_templates.run_template_step(- api_url=provider_config.get("api_url") or default_url,- bank_id=provider_config.get("bank_id", "hermes"),- api_key=env_writes.get("HINDSIGHT_API_KEY") or os.environ.get("HINDSIGHT_API_KEY", "") or None,- select=_curses_select, cancelled=_CANCELLED,- )-- if mode == "local_embedded":- materialized_config = dict(provider_config)- with contextlib.suppress(Exception):- materialized_config = json.loads(- (Path(hermes_home) / "hindsight" / "config.json").read_text(encoding="utf-8-sig")- )- llm_api_key = (- env_writes.get("HINDSIGHT_LLM_API_KEY", "")- or _load_simple_env(hermes_env).get("HINDSIGHT_LLM_API_KEY", "")- or _load_simple_env(_embedded_profile_env_path(materialized_config)).get("HINDSIGHT_API_LLM_API_KEY", "")- )- _materialize_embedded_profile_env(materialized_config, llm_api_key=llm_api_key or None)-- print(f"\n ✓ Hindsight memory configured ({mode} mode)")- if env_writes:- print(" API keys saved to .env")- print("\n Start a new session to activate.\n")diff --git a/plugins/memory/hindsight/templates.py b/plugins/memory/hindsight/templates.pydeleted file mode 100644index bf71258714b..00000000000--- a/plugins/memory/hindsight/templates.py+++ /dev/null@@ -1,128 +0,0 @@-"""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--import json-import logging-import os-import urllib.request-from urllib.parse import urljoin--from hermes_cli.urllib_security import open_credentialed_url--logger = logging.getLogger(__name__)--# 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 API must be reachable during setup; a local_embedded daemon isn't up yet.-SUPPORTED_MODES = ("cloud", "local_external")---def supported_for_mode(mode: str) -> bool:- return mode in SUPPORTED_MODES---def catalog_url() -> str:- return os.environ.get("HINDSIGHT_TEMPLATES_URL", _DEFAULT_CATALOG_URL)---def _get_json(url: str) -> dict:- req = urllib.request.Request(url, headers={"Accept": "application/json"})- with urllib.request.urlopen(req, timeout=_HTTP_TIMEOUT) as resp: # noqa: S310 - fixed https catalog- return json.loads(resp.read().decode("utf-8"))---def fetch_hermes_templates(url: str | None = None) -> list[dict]:- """Return catalog entries tagged for the ``hermes`` integration."""- catalog = _get_json(url or catalog_url())- entries = catalog.get("templates", []) if isinstance(catalog, dict) else []- return [e for e in entries if "hermes" in (e.get("integrations") or [])]---def fetch_manifest(entry: dict, url: str | None = None) -> dict:- """Fetch the BankTemplateManifest JSON for a catalog entry (``manifest_file`` is- relative to the catalog, e.g. "templates/foo.json")."""- return _get_json(urljoin(url or catalog_url(), entry["manifest_file"]))---def _bank_request(api_url: str, bank_id: str, api_key: str | None, action: str, *, headers: dict, **kwargs):- if api_key:- headers = {**headers, "Authorization": f"Bearer {api_key}"}- 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-2xx---def 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 (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"))- except Exception as e: # missing bank / network — treat as not customized- logger.debug("Hindsight: bank customization probe skipped: %s", e)- return False- return bool(data.get("bank") or data.get("mental_models") or data.get("directives"))---def run_template_step(*, api_url: str, bank_id: str, api_key: str | None, select, cancelled, log=print) -> str | None:- """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- logger.debug("Hindsight: could not fetch templates: %s", e)- return None- if not entries:- return None-- items = [(e.get("name", e["id"]), (e.get("description") or "")[:72]) for e in entries]- items.append(("Blank", "Start with an empty memory bank"))- idx = select(" Starter memory template", items, default=0, cancel_returns=cancelled)- if idx == cancelled or idx >= len(entries):- return None # blank or cancelled-- entry = entries[idx]-- # 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?",- [("Apply", "Overwrite config; add/update mental models & directives"),- ("Keep existing", "Leave the bank as-is")],- default=1,- cancel_returns=cancelled,- )- if confirm != 0:- log(f" Kept existing settings for bank '{bank_id}'.")- return None-- try:- manifest = fetch_manifest(entry)- apply_template(api_url, bank_id, api_key, manifest)- log(f" ✓ Applied '{entry.get('name', entry['id'])}' template to bank '{bank_id}'")- return entry["id"]- except Exception as e:- log(f" ⚠ Could not apply template ({e}). You can apply one later from "- f"hindsight.vectorize.io/templates.")- return Nonediff --git a/tools/lazy_deps.py b/tools/lazy_deps.pyindex 7e33d431aca..d6b309e1a06 100644--- a/tools/lazy_deps.py+++ b/tools/lazy_deps.py@@ -107,14 +107,12 @@ LAZY_DEPS: dict[str, tuple[str, ...]] = {# ─── Memory providers ──────────────────────────────────────────────────"memory.honcho": ("honcho-ai==2.2.0",),- # Plugin-owned SDKs mirror the range their plugin.yaml declares instead of an exact pin: an exact pin- # made _is_satisfied() reject every newer compatible release, so `hermes update` (and the hindsight- # plugin's own >=_MIN_CLIENT_VERSION auto-upgrade) kept downgrading a working 0.9.x client to 0.6.1- # and broke embedded daemons whose DB a newer client had migrated (#86992, #39424, #98407).- "memory.hindsight": ("hindsight-client>=0.6.1,<1",),# Cloud memory SDKs MUST be allowlisted + ensure()'d at the import site, or they never# install on the sealed Docker image (durable-target only)."memory.supermemory": ("supermemory==3.50.0",),+ # Plugin-owned SDKs mirror the range their plugin.yaml declares instead of an exact pin: an exact pin+ # made _is_satisfied() reject every newer compatible release, so `hermes update` kept downgrading a+ # working newer client and broke daemons whose DB it had migrated (#86992, #39424, #98407)."memory.mem0": ("mem0ai>=2.0.10,<3",),# ─── Messaging platforms (lazy-installable on demand) ──────────────────@@ -206,15 +204,13 @@ LAZY_DEPS: dict[str, tuple[str, ...]] = {"httpx2==2.7.0", # mcp 2.x HTTP stack — sync with pyproject [computer-use]"starlette==1.3.1",),- # huggingface-hub is SHARED with transformers (>=1.5.0,<2 via Hindsight) and marked active- # on mere presence, so `hermes update` re-asserts this pin everywhere hub exists. MUST stay- # inside transformers' window and match uv.lock (tests/test_project_metadata.py enforces).# HF Agent Trace Viewer upload (hermes trace upload / /upload-trace). huggingface-hub is a SHARED- # dependency: transformers (pulled by sentence-transformers for local Hindsight embeddings) requires- # >=1.5.0,<2, and faster-whisper/tokenizers depend on it transitively. Because active_features() marks a- # feature active from mere package presence, the `hermes update` lazy-refresh pass re-asserts THIS pin- # on every install where hub is present — so an exact pin below 1.5.0 force-downgrades the shared- # package and breaks Hindsight startup (#60783). Policy: keep the exact pin (no ranges — security+ # dependency: transformers (pulled by sentence-transformers when a memory plugin runs local embeddings,+ # e.g. the catalog hindsight plugin's local_embedded mode) requires >=1.5.0,<2, and+ # faster-whisper/tokenizers depend on it transitively. Because active_features() marks a feature active+ # from mere package presence, the `hermes update` lazy-refresh pass re-asserts THIS pin on every install+ # where hub is present — so an exact pin below 1.5.0 force-downgrades the shared package and breaks+ # those embedding daemons on startup (#60783). Policy: keep the exact pin (no ranges — security# posture), but it MUST stay inside transformers' accepted window and MUST match uv.lock so the whole# tree converges on ONE hub version (tests/test_project_metadata.py enforces both). When bumping: update# here AND `uv lock --upgrade-package huggingface-hub` in lockstep.