Merge branch 'simp/r3-27-D' into simp/integration3
This commit is contained in:
@@ -1,14 +1,9 @@
|
||||
"""ByteRover memory plugin — MemoryProvider interface.
|
||||
|
||||
Persistent memory via the ByteRover CLI (``brv``): hierarchical context tree with
|
||||
tiered retrieval (fuzzy text → LLM-driven search), local-first with optional cloud sync.
|
||||
Original PR #3499 by hieuntg81, adapted to the MemoryProvider ABC.
|
||||
|
||||
Requires the ``brv`` CLI (npm install -g byterover-cli, or byterover.dev/install.sh).
|
||||
|
||||
Config: BRV_API_KEY env var (cloud features; optional for local), and in config.yaml
|
||||
``memory.byterover.auto_extract: false`` to disable automatic brv curate hooks.
|
||||
Working directory: $HERMES_HOME/byterover/ (profile-scoped context tree).
|
||||
Persistent memory via the ByteRover CLI (``brv``): hierarchical context tree with tiered retrieval
|
||||
(fuzzy text → LLM-driven search), local-first with optional cloud sync (BRV_API_KEY). Requires the
|
||||
``brv`` CLI (npm install -g byterover-cli, or byterover.dev/install.sh). Working directory is
|
||||
$HERMES_HOME/byterover/ (profile-scoped); ``memory.byterover.auto_extract: false`` disables curate hooks.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,7 +15,7 @@ import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from agent.memory_provider import MemoryProvider
|
||||
from tools.registry import tool_error
|
||||
@@ -46,22 +41,25 @@ def _load_plugin_config() -> Dict[str, Any]:
|
||||
"""Read ``memory.byterover``; fall back to legacy ``memory.provider_config`` (early docs used it)."""
|
||||
try:
|
||||
from hermes_cli.config import load_config
|
||||
|
||||
memory_config = load_config().get("memory", {})
|
||||
if isinstance(memory_config, dict):
|
||||
for key in ("byterover", "provider_config"):
|
||||
block = memory_config.get(key, {})
|
||||
if isinstance(block, dict) and (block or key == "provider_config"):
|
||||
return dict(block)
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
for key in ("byterover", "provider_config") if isinstance(memory_config, dict) else ():
|
||||
block = memory_config.get(key, {})
|
||||
if isinstance(block, dict) and (block or key == "provider_config"):
|
||||
return dict(block)
|
||||
return {}
|
||||
|
||||
|
||||
# ── brv binary resolution (cached, thread-safe) ─────────────────────────────
|
||||
def _get_brv_cwd() -> Path:
|
||||
"""Profile-scoped working directory for the brv context tree."""
|
||||
from hermes_constants import get_hermes_home
|
||||
return get_hermes_home() / "byterover"
|
||||
|
||||
|
||||
# brv binary resolution (cached, thread-safe): None = unresolved, "" = resolved-missing
|
||||
_brv_path_lock = threading.Lock()
|
||||
_cached_brv_path: Optional[str] = None # None = unresolved, "" = resolved-missing
|
||||
_cached_brv_path: Optional[str] = None
|
||||
|
||||
|
||||
def _resolve_brv_path() -> Optional[str]:
|
||||
@@ -84,7 +82,6 @@ def _run_brv(args: List[str], timeout: int = _QUERY_TIMEOUT, cwd: str = None) ->
|
||||
brv_path = _resolve_brv_path()
|
||||
if not brv_path:
|
||||
return {"success": False, "error": "brv CLI not found. Install: npm install -g byterover-cli"}
|
||||
|
||||
effective_cwd = cwd or str(_get_brv_cwd())
|
||||
Path(effective_cwd).mkdir(parents=True, exist_ok=True)
|
||||
env = {**os.environ, "PATH": str(Path(brv_path).parent) + os.pathsep + os.environ.get("PATH", "")}
|
||||
@@ -93,10 +90,6 @@ def _run_brv(args: List[str], timeout: int = _QUERY_TIMEOUT, cwd: str = None) ->
|
||||
[brv_path] + args, capture_output=True, text=True, encoding='utf-8', errors='replace',
|
||||
timeout=timeout, cwd=effective_cwd, env=env, stdin=subprocess.DEVNULL,
|
||||
)
|
||||
stdout, stderr = result.stdout.strip(), result.stderr.strip()
|
||||
if result.returncode == 0:
|
||||
return {"success": True, "output": stdout}
|
||||
return {"success": False, "error": stderr or stdout or f"brv exited {result.returncode}"}
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"success": False, "error": f"brv timed out after {timeout}s"}
|
||||
except FileNotFoundError:
|
||||
@@ -105,48 +98,35 @@ def _run_brv(args: List[str], timeout: int = _QUERY_TIMEOUT, cwd: str = None) ->
|
||||
return {"success": False, "error": "brv CLI not found"}
|
||||
except Exception as e:
|
||||
return {"success": False, "error": str(e)}
|
||||
stdout, stderr = result.stdout.strip(), result.stderr.strip()
|
||||
if result.returncode == 0:
|
||||
return {"success": True, "output": stdout}
|
||||
return {"success": False, "error": stderr or stdout or f"brv exited {result.returncode}"}
|
||||
|
||||
|
||||
def _get_brv_cwd() -> Path:
|
||||
"""Profile-scoped working directory for the brv context tree."""
|
||||
from hermes_constants import get_hermes_home
|
||||
return get_hermes_home() / "byterover"
|
||||
|
||||
|
||||
# ── Tool schemas ─────────────────────────────────────────────────────────────
|
||||
|
||||
def _schema(name: str, description: str, arg: str = "", arg_desc: str = "") -> dict:
|
||||
props = {arg: {"type": "string", "description": arg_desc}} if arg else {}
|
||||
return {"name": name, "description": description, "parameters": {"type": "object", "properties": props, "required": [arg] if arg else []}}
|
||||
|
||||
|
||||
QUERY_SCHEMA = _schema(
|
||||
"brv_query",
|
||||
"Search ByteRover's persistent knowledge tree for relevant context. Returns memories, project knowledge, "
|
||||
"brv_query", "Search ByteRover's persistent knowledge tree for relevant context. Returns memories, project knowledge, "
|
||||
"architectural decisions, and patterns from previous sessions. Use for any question where past context would help.",
|
||||
"query", "What to search for.",
|
||||
)
|
||||
"query", "What to search for.")
|
||||
CURATE_SCHEMA = _schema(
|
||||
"brv_curate",
|
||||
"Store important information in ByteRover's persistent knowledge tree. Use for architectural decisions, bug fixes, "
|
||||
"brv_curate", "Store important information in ByteRover's persistent knowledge tree. Use for architectural decisions, bug fixes, "
|
||||
"user preferences, project patterns — anything worth remembering across sessions. ByteRover's LLM automatically "
|
||||
"categorizes and organizes the memory.",
|
||||
"content", "The information to remember.",
|
||||
)
|
||||
"categorizes and organizes the memory.", "content", "The information to remember.")
|
||||
STATUS_SCHEMA = _schema("brv_status", "Check ByteRover status — CLI version, context tree stats, cloud sync state.")
|
||||
|
||||
|
||||
# ── MemoryProvider implementation ────────────────────────────────────────────
|
||||
|
||||
class ByteRoverMemoryProvider(MemoryProvider):
|
||||
"""ByteRover persistent memory via the brv CLI."""
|
||||
|
||||
def __init__(self, config: Optional[Dict[str, Any]] = None):
|
||||
self._config = dict(config) if config is not None else _load_plugin_config()
|
||||
self._auto_extract = _coerce_bool(self._config.get("auto_extract"), True)
|
||||
self._cwd = ""
|
||||
self._session_id = ""
|
||||
self._turn_count = 0
|
||||
self._cwd, self._session_id, self._turn_count = "", "", 0
|
||||
self._sync_thread: Optional[threading.Thread] = None
|
||||
|
||||
@property
|
||||
@@ -166,20 +146,14 @@ class ByteRoverMemoryProvider(MemoryProvider):
|
||||
]
|
||||
|
||||
def initialize(self, session_id: str, **kwargs) -> None:
|
||||
self._cwd = str(_get_brv_cwd())
|
||||
self._session_id = session_id
|
||||
self._turn_count = 0
|
||||
self._cwd, self._session_id, self._turn_count = str(_get_brv_cwd()), session_id, 0
|
||||
Path(self._cwd).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
def system_prompt_block(self) -> str:
|
||||
if not _resolve_brv_path():
|
||||
return ""
|
||||
return (
|
||||
"# ByteRover Memory\n"
|
||||
"Active. Persistent knowledge tree with hierarchical context.\n"
|
||||
"Use brv_query to search past knowledge, brv_curate to store "
|
||||
"important facts, brv_status to check state."
|
||||
)
|
||||
return ("# ByteRover Memory\nActive. Persistent knowledge tree with hierarchical context.\n"
|
||||
"Use brv_query to search past knowledge, brv_curate to store important facts, brv_status to check state.")
|
||||
|
||||
def _query(self, query: str) -> dict:
|
||||
return _run_brv(["query", "--", query.strip()[:5000]], timeout=_QUERY_TIMEOUT, cwd=self._cwd)
|
||||
@@ -222,78 +196,59 @@ class ByteRoverMemoryProvider(MemoryProvider):
|
||||
self._turn_count += 1
|
||||
if not self._auto_extract_enabled("sync_turn") or len(user_content.strip()) < _MIN_QUERY_LEN:
|
||||
return
|
||||
# Wait for the previous sync so curates don't pile up.
|
||||
if self._sync_thread and self._sync_thread.is_alive():
|
||||
if self._sync_thread and self._sync_thread.is_alive(): # wait for the previous sync so curates don't pile up
|
||||
self._sync_thread.join(timeout=5.0)
|
||||
combined = f"User: {user_content[:2000]}\nAssistant: {assistant_content[:2000]}"
|
||||
self._sync_thread = self._curate_in_background(combined, name="brv-sync", what="sync")
|
||||
self._sync_thread = self._curate_in_background(f"User: {user_content[:2000]}\nAssistant: {assistant_content[:2000]}",
|
||||
name="brv-sync", what="sync")
|
||||
|
||||
def on_memory_write(self, action: str, target: str, content: str) -> None:
|
||||
"""Mirror built-in memory writes to ByteRover."""
|
||||
if not self._auto_extract_enabled("memory mirror") or action not in {"add", "replace"} or not content:
|
||||
return
|
||||
label = "User profile" if target == "user" else "Agent memory"
|
||||
self._curate_in_background(f"[{label}] {content}", name="brv-memwrite", what="memory mirror")
|
||||
if self._auto_extract_enabled("memory mirror") and action in {"add", "replace"} and content:
|
||||
label = "User profile" if target == "user" else "Agent memory"
|
||||
self._curate_in_background(f"[{label}] {content}", name="brv-memwrite", what="memory mirror")
|
||||
|
||||
def on_pre_compress(self, messages: List[Dict[str, Any]]) -> str:
|
||||
"""Extract insights from the last 10 user/assistant messages before compression discards them."""
|
||||
if not self._auto_extract_enabled("pre-compression flush") or not messages:
|
||||
return ""
|
||||
parts = []
|
||||
for msg in messages[-10:]:
|
||||
role, content = msg.get("role", ""), msg.get("content", "")
|
||||
if isinstance(content, str) and content.strip() and role in {"user", "assistant"}:
|
||||
parts.append(f"{role}: {content[:500]}")
|
||||
parts = [f"{msg.get('role', '')}: {msg.get('content', '')[:500]}" for msg in messages[-10:]
|
||||
if msg.get("role", "") in {"user", "assistant"} and isinstance(msg.get("content", ""), str) and msg.get("content", "").strip()]
|
||||
if parts:
|
||||
self._curate_in_background(
|
||||
"[Pre-compression context]\n" + "\n".join(parts), name="brv-flush", what="pre-compression flush",
|
||||
on_done=f"ByteRover pre-compression flush: {len(parts)} messages",
|
||||
)
|
||||
self._curate_in_background("[Pre-compression context]\n" + "\n".join(parts), name="brv-flush", what="pre-compression flush",
|
||||
on_done=f"ByteRover pre-compression flush: {len(parts)} messages")
|
||||
return ""
|
||||
|
||||
def get_tool_schemas(self) -> List[Dict[str, Any]]:
|
||||
return [QUERY_SCHEMA, CURATE_SCHEMA, STATUS_SCHEMA]
|
||||
|
||||
def handle_tool_call(self, tool_name: str, args: dict, **kwargs) -> str:
|
||||
handler = self._TOOLS.get(tool_name)
|
||||
if handler is None:
|
||||
if tool_name not in _TOOLS:
|
||||
return tool_error(f"Unknown tool: {tool_name}")
|
||||
return handler(self, args)
|
||||
arg, fail_msg, run, on_ok = _TOOLS[tool_name]
|
||||
value = args.get(arg, "") if arg else None
|
||||
if arg and not value:
|
||||
return tool_error(f"{arg} is required")
|
||||
result = run(self, value)
|
||||
return json.dumps(on_ok(result.get("output", ""))) if result["success"] else tool_error(result.get("error", fail_msg))
|
||||
|
||||
def shutdown(self) -> None:
|
||||
if self._sync_thread and self._sync_thread.is_alive():
|
||||
self._sync_thread.join(timeout=10.0)
|
||||
|
||||
# Tool implementations
|
||||
|
||||
@staticmethod
|
||||
def _tool_result(result: dict, fail_msg: str, on_ok: Callable[[str], dict]) -> str:
|
||||
if not result["success"]:
|
||||
return tool_error(result.get("error", fail_msg))
|
||||
return json.dumps(on_ok(result.get("output", "")))
|
||||
def _format_query_output(output: str) -> dict:
|
||||
output = output.strip()
|
||||
if len(output) < _MIN_OUTPUT_LEN:
|
||||
return {"result": "No relevant memories found."}
|
||||
return {"result": output[:8000] + "\n\n[... truncated]" if len(output) > 8000 else output}
|
||||
|
||||
def _tool_query(self, args: dict) -> str:
|
||||
query = args.get("query", "")
|
||||
if not query:
|
||||
return tool_error("query is required")
|
||||
|
||||
def fmt(output: str) -> dict:
|
||||
output = output.strip()
|
||||
if len(output) < _MIN_OUTPUT_LEN:
|
||||
return {"result": "No relevant memories found."}
|
||||
return {"result": output[:8000] + "\n\n[... truncated]" if len(output) > 8000 else output}
|
||||
return self._tool_result(self._query(query), "Query failed", fmt)
|
||||
|
||||
def _tool_curate(self, args: dict) -> str:
|
||||
content = args.get("content", "")
|
||||
if not content:
|
||||
return tool_error("content is required")
|
||||
return self._tool_result(self._curate(content), "Curate failed", lambda _: {"result": "Memory curated successfully."})
|
||||
|
||||
def _tool_status(self, args: dict) -> str:
|
||||
return self._tool_result(_run_brv(["status"], timeout=15, cwd=self._cwd), "Status check failed", lambda out: {"status": out})
|
||||
|
||||
_TOOLS = {"brv_query": _tool_query, "brv_curate": _tool_curate, "brv_status": _tool_status}
|
||||
# tool name -> (required arg or None, failure message, run(provider, arg_value) -> brv result, on_ok(output) -> JSON payload)
|
||||
_TOOLS = {
|
||||
"brv_query": ("query", "Query failed", lambda p, q: p._query(q), _format_query_output),
|
||||
"brv_curate": ("content", "Curate failed", lambda p, c: p._curate(c), lambda _: {"result": "Memory curated successfully."}),
|
||||
"brv_status": (None, "Status check failed", lambda p, _: _run_brv(["status"], timeout=15, cwd=p._cwd), lambda out: {"status": out}),
|
||||
}
|
||||
|
||||
|
||||
def register(ctx) -> None:
|
||||
|
||||
+147
-259
@@ -2,9 +2,8 @@
|
||||
|
||||
Cross-session memory via the RetainDB cloud API: durable SQLite write-behind queue, semantic
|
||||
search + profile, context overlay, dialectic/agent self-model prefetch, shared file store tools.
|
||||
|
||||
Config (env vars, or config.yaml ``memory.retaindb`` for the non-secret ones): RETAINDB_API_KEY (required),
|
||||
RETAINDB_BASE_URL (default https://api.retaindb.com), RETAINDB_PROJECT (optional; defaults to "default").
|
||||
Config: RETAINDB_API_KEY (required, scoped secret), RETAINDB_BASE_URL (default https://api.retaindb.com),
|
||||
RETAINDB_PROJECT (optional; defaults to "default"); the non-secret two also read config.yaml ``memory.retaindb``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,7 +19,7 @@ import time
|
||||
from contextlib import suppress
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import quote
|
||||
|
||||
from agent.memory_provider import MemoryProvider
|
||||
@@ -35,103 +34,83 @@ _ASYNC_SHUTDOWN = object()
|
||||
_TEXT_EXTS = (".txt", ".md", ".json", ".csv", ".yaml", ".yml", ".xml", ".html")
|
||||
|
||||
|
||||
def _load_retaindb_config() -> Dict[str, Any]:
|
||||
def _load_retaindb_config() -> dict[str, Any]:
|
||||
"""``memory.retaindb`` block from config.yaml (empty on error): Dashboard-persisted base_url/project; api_key stays in scoped secrets."""
|
||||
try:
|
||||
from hermes_cli.config import load_config_readonly
|
||||
|
||||
provider_config = load_config_readonly().get("memory", {}).get("retaindb", {})
|
||||
return dict(provider_config) if isinstance(provider_config, dict) else {}
|
||||
block = load_config_readonly().get("memory", {}).get("retaindb", {})
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def _config_str(value: Any) -> str:
|
||||
"""Stripped string for a config value, else ``""``."""
|
||||
return value.strip() if isinstance(value, str) else ""
|
||||
block = None
|
||||
return dict(block) if isinstance(block, dict) else {}
|
||||
|
||||
|
||||
def _q(s: str) -> str:
|
||||
return quote(s, safe="")
|
||||
|
||||
|
||||
# ── Tool schemas ─────────────────────────────────────────────────────────────
|
||||
def _quiet(label: str, fn: Callable[[], Any]) -> Any:
|
||||
"""Run *fn*; on any exception log "RetainDB <label> failed" at debug and return None."""
|
||||
try:
|
||||
return fn()
|
||||
except Exception as exc:
|
||||
logger.debug("RetainDB %s failed: %s", label, exc)
|
||||
return None
|
||||
|
||||
|
||||
def _schema(name: str, description: str, properties: dict | None = None, required: tuple = ()) -> dict:
|
||||
return {
|
||||
"name": name,
|
||||
"description": description,
|
||||
"parameters": {"type": "object", "properties": properties or {}, "required": list(required)},
|
||||
}
|
||||
return {"name": name, "description": description,
|
||||
"parameters": {"type": "object", "properties": properties or {}, "required": list(required)}}
|
||||
|
||||
|
||||
def _prop(type_: str, description: str, **extra) -> dict:
|
||||
def _p(description: str, type_: str = "string", **extra) -> dict:
|
||||
return {"type": type_, **extra, "description": description}
|
||||
|
||||
|
||||
def _s(description: str, **extra) -> dict:
|
||||
return _prop("string", description, **extra)
|
||||
|
||||
|
||||
PROFILE_SCHEMA = _schema(
|
||||
"retaindb_profile", "Get the user's stable profile — preferences, facts, and patterns recalled from long-term memory.")
|
||||
SEARCH_SCHEMA = _schema(
|
||||
"retaindb_search", "Semantic search across stored memories. Returns ranked results with relevance scores.",
|
||||
{"query": _s("What to search for."), "top_k": _prop("integer", "Max results (default: 8, max: 20).")}, ("query",))
|
||||
CONTEXT_SCHEMA = _schema(
|
||||
"retaindb_context", "Synthesized context block — what matters most for the current task, pulled from long-term memory.",
|
||||
{"query": _s("Current task or question.")}, ("query",))
|
||||
REMEMBER_SCHEMA = _schema(
|
||||
"retaindb_remember", "Persist an explicit fact, preference, or decision to long-term memory.",
|
||||
{"content": _s("The fact to remember."),
|
||||
"memory_type": _s("Category (default: factual).", enum=["factual", "preference", "goal", "instruction", "event", "opinion"]),
|
||||
"importance": _prop("number", "Importance 0-1 (default: 0.7).")}, ("content",))
|
||||
FORGET_SCHEMA = _schema("retaindb_forget", "Delete a specific memory by ID.", {"memory_id": _s("Memory ID to delete.")}, ("memory_id",))
|
||||
FILE_UPLOAD_SCHEMA = _schema(
|
||||
"retaindb_upload_file", "Upload a file to the shared RetainDB file store. Returns an rdb:// URI any agent can reference.",
|
||||
{"local_path": _s("Local file path to upload."), "remote_path": _s("Destination path, e.g. /reports/q1.pdf"),
|
||||
"scope": _s("Access scope (default: PROJECT).", enum=["USER", "PROJECT", "ORG"]),
|
||||
"ingest": _prop("boolean", "Also extract memories from file after upload (default: false).")}, ("local_path",))
|
||||
FILE_LIST_SCHEMA = _schema(
|
||||
"retaindb_list_files", "List files in the shared file store.",
|
||||
{"prefix": _s("Path prefix to filter by, e.g. /reports/"), "limit": _prop("integer", "Max results (default: 50).")})
|
||||
FILE_READ_SCHEMA = _schema(
|
||||
"retaindb_read_file", "Read the text content of a stored file by its file ID.",
|
||||
{"file_id": _s("File ID returned from upload or list.")}, ("file_id",))
|
||||
FILE_INGEST_SCHEMA = _schema(
|
||||
"retaindb_ingest_file", "Chunk, embed, and extract memories from a stored file. Makes its contents searchable.",
|
||||
{"file_id": _s("File ID to ingest.")}, ("file_id",))
|
||||
FILE_DELETE_SCHEMA = _schema("retaindb_delete_file", "Delete a stored file.", {"file_id": _s("File ID to delete.")}, ("file_id",))
|
||||
_SCHEMAS = (
|
||||
PROFILE_SCHEMA, SEARCH_SCHEMA, CONTEXT_SCHEMA, REMEMBER_SCHEMA, FORGET_SCHEMA,
|
||||
FILE_UPLOAD_SCHEMA, FILE_LIST_SCHEMA, FILE_READ_SCHEMA, FILE_INGEST_SCHEMA, FILE_DELETE_SCHEMA,
|
||||
_schema("retaindb_profile", "Get the user's stable profile — preferences, facts, and patterns recalled from long-term memory."),
|
||||
_schema("retaindb_search", "Semantic search across stored memories. Returns ranked results with relevance scores.",
|
||||
{"query": _p("What to search for."), "top_k": _p("Max results (default: 8, max: 20).", "integer")}, ("query",)),
|
||||
_schema("retaindb_context", "Synthesized context block — what matters most for the current task, pulled from long-term memory.",
|
||||
{"query": _p("Current task or question.")}, ("query",)),
|
||||
_schema("retaindb_remember", "Persist an explicit fact, preference, or decision to long-term memory.",
|
||||
{"content": _p("The fact to remember."),
|
||||
"memory_type": _p("Category (default: factual).", enum=["factual", "preference", "goal", "instruction", "event", "opinion"]),
|
||||
"importance": _p("Importance 0-1 (default: 0.7).", "number")}, ("content",)),
|
||||
_schema("retaindb_forget", "Delete a specific memory by ID.", {"memory_id": _p("Memory ID to delete.")}, ("memory_id",)),
|
||||
_schema("retaindb_upload_file", "Upload a file to the shared RetainDB file store. Returns an rdb:// URI any agent can reference.",
|
||||
{"local_path": _p("Local file path to upload."), "remote_path": _p("Destination path, e.g. /reports/q1.pdf"),
|
||||
"scope": _p("Access scope (default: PROJECT).", enum=["USER", "PROJECT", "ORG"]),
|
||||
"ingest": _p("Also extract memories from file after upload (default: false).", "boolean")}, ("local_path",)),
|
||||
_schema("retaindb_list_files", "List files in the shared file store.",
|
||||
{"prefix": _p("Path prefix to filter by, e.g. /reports/"), "limit": _p("Max results (default: 50).", "integer")}),
|
||||
_schema("retaindb_read_file", "Read the text content of a stored file by its file ID.",
|
||||
{"file_id": _p("File ID returned from upload or list.")}, ("file_id",)),
|
||||
_schema("retaindb_ingest_file", "Chunk, embed, and extract memories from a stored file. Makes its contents searchable.",
|
||||
{"file_id": _p("File ID to ingest.")}, ("file_id",)),
|
||||
_schema("retaindb_delete_file", "Delete a stored file.", {"file_id": _p("File ID to delete.")}, ("file_id",)),
|
||||
)
|
||||
|
||||
|
||||
# ── HTTP client ──────────────────────────────────────────────────────────────
|
||||
|
||||
class _Client:
|
||||
"""Thin HTTP client over the RetainDB REST API (lazy ``requests`` import)."""
|
||||
|
||||
def __init__(self, api_key: str, base_url: str, project: str):
|
||||
self.api_key = api_key
|
||||
self.base_url = re.sub(r"/+$", "", base_url)
|
||||
self.project = project
|
||||
self.api_key, self.base_url, self.project = api_key, re.sub(r"/+$", "", base_url), project
|
||||
|
||||
def _headers(self, path: str, json_body: bool = True) -> dict:
|
||||
token = self.api_key.replace("Bearer ", "").strip()
|
||||
return {
|
||||
"Authorization": f"Bearer {token}", "x-sdk-runtime": "hermes-plugin",
|
||||
**({"Content-Type": "application/json"} if json_body else {}),
|
||||
# memory/context routes also accept the key as X-API-Key
|
||||
**({"X-API-Key": token} if path.startswith(("/v1/memory", "/v1/context")) else {}),
|
||||
}
|
||||
return {"Authorization": f"Bearer {token}", "x-sdk-runtime": "hermes-plugin",
|
||||
**({"Content-Type": "application/json"} if json_body else {}),
|
||||
**({"X-API-Key": token} if path.startswith(("/v1/memory", "/v1/context")) else {})} # memory/context also accept X-API-Key
|
||||
|
||||
def _http(self, method: str, path: str, *, json_body: bool = True, timeout: float = 30, **kwargs):
|
||||
import requests
|
||||
return requests.request(method, f"{self.base_url}{path}", headers=self._headers(path, json_body), timeout=timeout, **kwargs)
|
||||
|
||||
def request(self, method: str, path: str, *, params=None, json_body=None, timeout: float = 8.0) -> Any:
|
||||
import requests
|
||||
"""JSON request; raises RuntimeError carrying the server message on a non-2xx response."""
|
||||
method = method.upper()
|
||||
resp = requests.request(
|
||||
method, f"{self.base_url}{path}", params=params, json=json_body if method not in {"GET", "DELETE"} else None,
|
||||
headers=self._headers(path), timeout=timeout,
|
||||
)
|
||||
resp = self._http(method, path, params=params, json=json_body if method not in {"GET", "DELETE"} else None, timeout=timeout)
|
||||
try:
|
||||
payload = resp.json()
|
||||
except Exception:
|
||||
@@ -141,6 +120,11 @@ class _Client:
|
||||
raise RuntimeError(f"RetainDB {method} {path} failed ({resp.status_code}): {msg or payload}")
|
||||
return payload
|
||||
|
||||
def _raw(self, method: str, path: str, **kwargs) -> Any:
|
||||
"""Non-JSON request (multipart upload / binary download); raises on HTTP error."""
|
||||
resp = self._http(method, path, json_body=False, **kwargs)
|
||||
return resp.raise_for_status() or resp
|
||||
|
||||
@staticmethod
|
||||
def _with_fallback(primary: Callable[[], dict], fallback: Callable[[], dict]) -> dict:
|
||||
"""Try the current API route; on any error retry via the legacy route."""
|
||||
@@ -152,144 +136,100 @@ class _Client:
|
||||
def _scoped(self, user_id: str, session_id: str, **extra) -> dict:
|
||||
return {"project": self.project, "user_id": user_id, "session_id": session_id, **extra}
|
||||
|
||||
# Memory
|
||||
|
||||
# Memory routes (one endpoint per method; bodies are the wire payloads)
|
||||
def query_context(self, user_id: str, session_id: str, query: str, max_tokens: int = 1200) -> dict:
|
||||
body = self._scoped(user_id, session_id, query=query, include_memories=True, max_tokens=max_tokens)
|
||||
return self.request("POST", "/v1/context/query", json_body=body)
|
||||
|
||||
return self.request("POST", "/v1/context/query", json_body=self._scoped(user_id, session_id, query=query, include_memories=True, max_tokens=max_tokens))
|
||||
def search(self, user_id: str, session_id: str, query: str, top_k: int = 8) -> dict:
|
||||
body = self._scoped(user_id, session_id, query=query, top_k=top_k, include_pending=True)
|
||||
return self.request("POST", "/v1/memory/search", json_body=body)
|
||||
|
||||
return self.request("POST", "/v1/memory/search", json_body=self._scoped(user_id, session_id, query=query, top_k=top_k, include_pending=True))
|
||||
def get_profile(self, user_id: str) -> dict:
|
||||
return self._with_fallback(
|
||||
lambda: self.request("GET", f"/v1/memory/profile/{_q(user_id)}", params={"project": self.project, "include_pending": "true"}),
|
||||
lambda: self.request("GET", "/v1/memories", params={"project": self.project, "user_id": user_id, "limit": "200"}),
|
||||
)
|
||||
|
||||
lambda: self.request("GET", "/v1/memories", params={"project": self.project, "user_id": user_id, "limit": "200"}))
|
||||
def add_memory(self, user_id: str, session_id: str, content: str, memory_type: str = "factual", importance: float = 0.7) -> dict:
|
||||
body = self._scoped(user_id, session_id, content=content, memory_type=memory_type, importance=importance)
|
||||
return self._with_fallback(
|
||||
lambda: self.request("POST", "/v1/memory", json_body={**body, "write_mode": "sync"}, timeout=5.0),
|
||||
lambda: self.request("POST", "/v1/memories", json_body=body, timeout=5.0),
|
||||
)
|
||||
|
||||
lambda: self.request("POST", "/v1/memories", json_body=body, timeout=5.0))
|
||||
def delete_memory(self, memory_id: str) -> dict:
|
||||
return self._with_fallback(
|
||||
lambda: self.request("DELETE", f"/v1/memory/{_q(memory_id)}", timeout=5.0),
|
||||
lambda: self.request("DELETE", f"/v1/memories/{_q(memory_id)}", timeout=5.0),
|
||||
)
|
||||
|
||||
lambda: self.request("DELETE", f"/v1/memories/{_q(memory_id)}", timeout=5.0))
|
||||
def ingest_session(self, user_id: str, session_id: str, messages: list, timeout: float = 15.0) -> dict:
|
||||
body = self._scoped(user_id, session_id, messages=messages, write_mode="sync")
|
||||
return self.request("POST", "/v1/memory/ingest/session", json_body=body, timeout=timeout)
|
||||
|
||||
return self.request("POST", "/v1/memory/ingest/session", json_body=self._scoped(user_id, session_id, messages=messages, write_mode="sync"), timeout=timeout)
|
||||
def ask_user(self, user_id: str, query: str, reasoning_level: str = "low") -> dict:
|
||||
body = {"project": self.project, "query": query, "reasoning_level": reasoning_level}
|
||||
return self.request("POST", f"/v1/memory/profile/{_q(user_id)}/ask", json_body=body, timeout=8.0)
|
||||
|
||||
return self.request("POST", f"/v1/memory/profile/{_q(user_id)}/ask", json_body={"project": self.project, "query": query, "reasoning_level": reasoning_level}, timeout=8.0)
|
||||
def get_agent_model(self, agent_id: str) -> dict:
|
||||
return self.request("GET", f"/v1/memory/agent/{_q(agent_id)}/model", params={"project": self.project}, timeout=4.0)
|
||||
|
||||
def seed_agent_identity(self, agent_id: str, content: str, source: str = "soul_md") -> dict:
|
||||
body = {"project": self.project, "content": content, "source": source}
|
||||
return self.request("POST", f"/v1/memory/agent/{_q(agent_id)}/seed", json_body=body, timeout=20.0)
|
||||
|
||||
# Files
|
||||
|
||||
def _raw(self, method: str, path: str, **kwargs) -> Any:
|
||||
"""Non-JSON request (multipart upload / binary download); raises on HTTP error."""
|
||||
import requests
|
||||
resp = requests.request(method, f"{self.base_url}{path}", headers=self._headers(path, json_body=False), timeout=30, **kwargs)
|
||||
resp.raise_for_status()
|
||||
return resp
|
||||
return self.request("POST", f"/v1/memory/agent/{_q(agent_id)}/seed", json_body={"project": self.project, "content": content, "source": source}, timeout=20.0)
|
||||
|
||||
# File routes
|
||||
def upload_file(self, data: bytes, filename: str, remote_path: str, mime_type: str, scope: str, project_id: str | None) -> dict:
|
||||
import io
|
||||
fields = {"path": remote_path, "scope": scope.upper(), **({"project_id": project_id} if project_id else {})}
|
||||
return self._raw("POST", "/v1/files", files={"file": (filename, io.BytesIO(data), mime_type)}, data=fields).json()
|
||||
|
||||
def list_files(self, prefix: str | None = None, limit: int = 50) -> dict:
|
||||
return self.request("GET", "/v1/files", params={"limit": limit, **({"prefix": prefix} if prefix else {})})
|
||||
|
||||
def get_file(self, file_id: str) -> dict:
|
||||
return self.request("GET", f"/v1/files/{_q(file_id)}")
|
||||
|
||||
def read_file_content(self, file_id: str) -> bytes:
|
||||
return self._raw("GET", f"/v1/files/{_q(file_id)}/content", allow_redirects=True).content
|
||||
|
||||
def ingest_file(self, file_id: str, user_id: str | None = None, agent_id: str | None = None) -> dict:
|
||||
body = {k: v for k, v in (("user_id", user_id), ("agent_id", agent_id)) if v}
|
||||
return self.request("POST", f"/v1/files/{_q(file_id)}/ingest", json_body=body, timeout=60.0)
|
||||
|
||||
def delete_file(self, file_id: str) -> dict:
|
||||
return self.request("DELETE", f"/v1/files/{_q(file_id)}", timeout=5.0)
|
||||
|
||||
|
||||
# ── Durable write-behind queue ───────────────────────────────────────────────
|
||||
|
||||
class _WriteQueue:
|
||||
"""SQLite-backed async write queue. Survives crashes — pending rows replay on startup."""
|
||||
|
||||
def __init__(self, client: _Client, db_path: Path):
|
||||
self._client = client
|
||||
self._db_path = db_path
|
||||
self._q: queue.Queue = queue.Queue()
|
||||
self._client, self._db_path, self._q = client, db_path, queue.Queue()
|
||||
self._thread = threading.Thread(target=self._loop, name="retaindb-writer", daemon=True)
|
||||
self._db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._local = threading.local() # one cached connection per thread
|
||||
db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._local = threading.local() # one cached connection per thread, all tracked in _connections
|
||||
self._connections: set[sqlite3.Connection] = set()
|
||||
self._connections_lock = threading.Lock()
|
||||
self._shutdown_lock = threading.Lock()
|
||||
self._shutdown = False
|
||||
conn = self._execute(
|
||||
"CREATE TABLE IF NOT EXISTS pending (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id TEXT, "
|
||||
"session_id TEXT, messages_json TEXT, created_at TEXT, last_error TEXT)"
|
||||
).connection
|
||||
self._connections_lock, self._shutdown_lock, self._shutdown = threading.Lock(), threading.Lock(), False
|
||||
conn = self._execute("CREATE TABLE IF NOT EXISTS pending (id INTEGER PRIMARY KEY AUTOINCREMENT, user_id TEXT, "
|
||||
"session_id TEXT, messages_json TEXT, created_at TEXT, last_error TEXT)").connection
|
||||
self._thread.start()
|
||||
# Replay any rows left from a previous crash
|
||||
for row_id, user_id, session_id, msgs_json in conn.execute(
|
||||
"SELECT id, user_id, session_id, messages_json FROM pending ORDER BY id ASC LIMIT 200"
|
||||
).fetchall():
|
||||
replay = conn.execute("SELECT id, user_id, session_id, messages_json FROM pending ORDER BY id ASC LIMIT 200").fetchall()
|
||||
for row_id, user_id, session_id, msgs_json in replay: # rows left from a previous crash
|
||||
self._q.put((row_id, user_id, session_id, json.loads(msgs_json)))
|
||||
|
||||
def _get_conn(self) -> sqlite3.Connection:
|
||||
"""Return a cached connection for the current thread."""
|
||||
conn = getattr(self._local, "conn", None)
|
||||
if conn is None:
|
||||
conn = sqlite3.connect(str(self._db_path), timeout=30, check_same_thread=False)
|
||||
conn = self._local.conn = sqlite3.connect(str(self._db_path), timeout=30, check_same_thread=False)
|
||||
conn.row_factory = sqlite3.Row
|
||||
self._local.conn = conn
|
||||
with self._connections_lock:
|
||||
self._connections.add(conn)
|
||||
return conn
|
||||
|
||||
def _execute(self, sql: str, params: tuple = ()) -> sqlite3.Cursor:
|
||||
"""Execute + commit on this thread's connection."""
|
||||
cur = self._get_conn().execute(sql, params)
|
||||
cur.connection.commit()
|
||||
return cur
|
||||
|
||||
def _close(self, *conns: sqlite3.Connection) -> None:
|
||||
for conn in conns:
|
||||
with self._connections_lock:
|
||||
self._connections.discard(conn)
|
||||
with suppress(Exception):
|
||||
conn.close()
|
||||
|
||||
def _close_thread_conn(self) -> None:
|
||||
conn = getattr(self._local, "conn", None)
|
||||
if conn is None:
|
||||
return
|
||||
self._local.conn = None
|
||||
with self._connections_lock:
|
||||
self._connections.discard(conn)
|
||||
with suppress(Exception):
|
||||
conn.close()
|
||||
conn, self._local.conn = getattr(self._local, "conn", None), None
|
||||
self._close(*([conn] if conn is not None else []))
|
||||
|
||||
def enqueue(self, user_id: str, session_id: str, messages: list) -> None:
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
with self._shutdown_lock:
|
||||
if self._shutdown:
|
||||
return
|
||||
cur = self._execute(
|
||||
"INSERT INTO pending (user_id, session_id, messages_json, created_at) VALUES (?,?,?,?)",
|
||||
(user_id, session_id, json.dumps(messages, ensure_ascii=False), now),
|
||||
)
|
||||
cur = self._execute("INSERT INTO pending (user_id, session_id, messages_json, created_at) VALUES (?,?,?,?)",
|
||||
(user_id, session_id, json.dumps(messages, ensure_ascii=False), now))
|
||||
self._q.put((cur.lastrowid, user_id, session_id, messages))
|
||||
|
||||
def _flush_row(self, row_id: int, user_id: str, session_id: str, messages: list) -> None:
|
||||
@@ -319,18 +259,12 @@ class _WriteQueue:
|
||||
self._q.put(_ASYNC_SHUTDOWN)
|
||||
self._close_thread_conn() # caller thread owns the connection opened in __init__
|
||||
self._thread.join(timeout=10)
|
||||
if not self._thread.is_alive():
|
||||
# Executor workers that already exited may have left tracked handles;
|
||||
# check_same_thread=False lets shutdown close them deterministically.
|
||||
if not self._thread.is_alive(): # exited executor workers may have left tracked handles (check_same_thread=False)
|
||||
with self._connections_lock:
|
||||
connections, self._connections = list(self._connections), set()
|
||||
for conn in connections:
|
||||
with suppress(Exception):
|
||||
conn.close()
|
||||
stragglers = list(self._connections)
|
||||
self._close(*stragglers)
|
||||
|
||||
|
||||
# ── Overlay formatter ────────────────────────────────────────────────────────
|
||||
|
||||
def _compact(s: str) -> str:
|
||||
return re.sub(r"\s+", " ", str(s or "")).strip()[:320]
|
||||
|
||||
@@ -352,18 +286,13 @@ def _build_overlay(profile: dict, query_result: dict, local_entries: list[str] |
|
||||
out.append(c)
|
||||
return out
|
||||
|
||||
profile_items = _dedupe((profile or {}).get("memories"))
|
||||
query_items = _dedupe((query_result or {}).get("results"))
|
||||
profile_items, query_items = _dedupe((profile or {}).get("memories")), _dedupe((query_result or {}).get("results"))
|
||||
if not profile_items and not query_items:
|
||||
return ""
|
||||
return "\n".join(
|
||||
["[RetainDB Context]", "Profile:"] + ([f"- {i}" for i in profile_items] or ["- None"])
|
||||
+ ["Relevant memories:"] + ([f"- {i}" for i in query_items] or ["- None"])
|
||||
)
|
||||
return "\n".join(["[RetainDB Context]", "Profile:"] + ([f"- {i}" for i in profile_items] or ["- None"])
|
||||
+ ["Relevant memories:"] + ([f"- {i}" for i in query_items] or ["- None"]))
|
||||
|
||||
|
||||
# ── Provider ─────────────────────────────────────────────────────────────────
|
||||
|
||||
# Agent self-model keys -> prefetch line formatter, in display order.
|
||||
_AGENT_MODEL_FIELDS = (
|
||||
("persona", lambda v: f"Persona: {v}"),
|
||||
@@ -379,11 +308,9 @@ class RetainDBMemoryProvider(MemoryProvider):
|
||||
self._client: _Client | None = None
|
||||
self._queue: _WriteQueue | None = None
|
||||
self._user_id, self._session_id, self._agent_id = "default", "", "hermes"
|
||||
self._lock = threading.Lock()
|
||||
# Prefetch caches + thread tracking (prevents accumulation on rapid calls)
|
||||
self._context_result = self._dialectic_result = ""
|
||||
self._agent_model: dict = {}
|
||||
self._prefetch_threads: list[threading.Thread] = []
|
||||
self._lock = threading.Lock() # guards the prefetch caches below
|
||||
self._context_result, self._dialectic_result, self._agent_model = "", "", {}
|
||||
self._prefetch_threads: list[threading.Thread] = [] # tracked so rapid turns don't pile up threads
|
||||
|
||||
@property
|
||||
def name(self) -> str:
|
||||
@@ -392,7 +319,7 @@ class RetainDBMemoryProvider(MemoryProvider):
|
||||
def is_available(self) -> bool:
|
||||
return bool(get_secret("RETAINDB_API_KEY"))
|
||||
|
||||
def get_config_schema(self) -> List[Dict[str, Any]]:
|
||||
def get_config_schema(self) -> list[dict[str, Any]]:
|
||||
return [
|
||||
{"key": "api_key", "description": "RetainDB API key", "secret": True, "required": True, "env_var": "RETAINDB_API_KEY", "url": "https://retaindb.com"},
|
||||
{"key": "base_url", "description": "API endpoint", "default": _DEFAULT_BASE_URL},
|
||||
@@ -401,118 +328,88 @@ class RetainDBMemoryProvider(MemoryProvider):
|
||||
|
||||
def initialize(self, session_id: str, **kwargs) -> None:
|
||||
# Non-secret fields resolve env -> config.yaml (written by the Dashboard) -> default.
|
||||
provider_config = _load_retaindb_config()
|
||||
base_url = re.sub(r"/+$", "", os.environ.get("RETAINDB_BASE_URL") or _config_str(provider_config.get("base_url")) or _DEFAULT_BASE_URL)
|
||||
cfg = {k: v.strip() for k, v in _load_retaindb_config().items() if isinstance(v, str)}
|
||||
base_url = re.sub(r"/+$", "", os.environ.get("RETAINDB_BASE_URL") or cfg.get("base_url") or _DEFAULT_BASE_URL)
|
||||
# Project: RETAINDB_PROJECT > config.yaml > hermes-<profile> > "default" (API auto-creates "default").
|
||||
project = os.environ.get("RETAINDB_PROJECT") or _config_str(provider_config.get("project"))
|
||||
project = os.environ.get("RETAINDB_PROJECT") or cfg.get("project")
|
||||
if not project:
|
||||
profile_name = os.path.basename(str(kwargs.get("hermes_home", "")))
|
||||
project = f"hermes-{profile_name}" if profile_name not in {"", ".hermes"} else "default"
|
||||
|
||||
self._client = _Client(get_secret("RETAINDB_API_KEY", "") or "", base_url, project)
|
||||
self._session_id = session_id
|
||||
self._user_id = kwargs.get("user_id", "default") or "default"
|
||||
self._session_id, self._user_id = session_id, kwargs.get("user_id", "default") or "default"
|
||||
self._agent_id = kwargs.get("agent_id", "hermes") or "hermes"
|
||||
|
||||
from hermes_constants import get_hermes_home
|
||||
hermes_home_path = get_hermes_home()
|
||||
self._queue = _WriteQueue(self._client, hermes_home_path / "retaindb_queue.db")
|
||||
# Seed agent identity from SOUL.md in background
|
||||
soul_path = hermes_home_path / "SOUL.md"
|
||||
soul_content = soul_path.read_text(encoding="utf-8", errors="replace").strip() if soul_path.exists() else ""
|
||||
if soul_content:
|
||||
threading.Thread(target=self._seed_soul, args=(soul_content,), name="retaindb-soul-seed", daemon=True).start()
|
||||
|
||||
def _seed_soul(self, content: str) -> None:
|
||||
try:
|
||||
self._client.seed_agent_identity(self._agent_id, content, source="soul_md")
|
||||
except Exception as exc:
|
||||
logger.debug("RetainDB soul seed failed: %s", exc)
|
||||
home = get_hermes_home()
|
||||
self._queue = _WriteQueue(self._client, home / "retaindb_queue.db")
|
||||
soul = (home / "SOUL.md").read_text(encoding="utf-8", errors="replace").strip() if (home / "SOUL.md").exists() else ""
|
||||
if soul: # seed agent identity from SOUL.md in background
|
||||
seed = lambda: self._client.seed_agent_identity(self._agent_id, soul, source="soul_md") # noqa: E731
|
||||
threading.Thread(target=_quiet, args=("soul seed", seed), name="retaindb-soul-seed", daemon=True).start()
|
||||
|
||||
def system_prompt_block(self) -> str:
|
||||
project = self._client.project if self._client else "retaindb"
|
||||
return (
|
||||
f"# RetainDB Memory\nActive. Project: {project}.\n"
|
||||
"Use retaindb_search to find memories, retaindb_remember to store facts, "
|
||||
"retaindb_profile for a user overview, retaindb_context for current-task context."
|
||||
)
|
||||
|
||||
# Background prefetch (fires at turn-end, consumed next turn-start)
|
||||
return (f"# RetainDB Memory\nActive. Project: {project}.\nUse retaindb_search to find memories, retaindb_remember to store facts, "
|
||||
"retaindb_profile for a user overview, retaindb_context for current-task context.")
|
||||
|
||||
def queue_prefetch(self, query: str, *, session_id: str = "") -> None:
|
||||
"""Fire context + dialectic + agent model prefetches in background."""
|
||||
"""Fire context + dialectic + agent model prefetches in background (turn-end); prefetch() consumes them next turn."""
|
||||
if not self._client:
|
||||
return
|
||||
# Wait for the previous batch so threads don't accumulate on rapid turns.
|
||||
for t in self._prefetch_threads:
|
||||
for t in self._prefetch_threads: # wait for the previous batch so threads don't accumulate on rapid turns
|
||||
t.join(timeout=2.0)
|
||||
if any(t.is_alive() for t in self._prefetch_threads):
|
||||
logger.debug("RetainDB prefetch still running; skipping new batch")
|
||||
return
|
||||
jobs = (
|
||||
("retaindb-ctx", "context", lambda: ("_context_result", self._context_overlay(query)["context"])),
|
||||
("retaindb-dialectic", "dialectic", lambda: self._fetch_dialectic(query)),
|
||||
("retaindb-agent-model", "agent model", self._fetch_agent_model),
|
||||
jobs = ( # (thread name, log label, cache attr, fetch) — fetch returns None to leave the cache untouched
|
||||
("retaindb-ctx", "context", "_context_result", lambda: self._context_overlay(query)["context"]),
|
||||
("retaindb-dialectic", "dialectic", "_dialectic_result", lambda: str(
|
||||
self._client.ask_user(self._user_id, query, reasoning_level=self._reasoning_level(query)).get("answer") or "") or None),
|
||||
("retaindb-agent-model", "agent model", "_agent_model", lambda: self._agent_model_or_none(self._client.get_agent_model(self._agent_id))),
|
||||
)
|
||||
threads = [threading.Thread(target=self._store, args=(label, fetch), name=name, daemon=True) for name, label, fetch in jobs]
|
||||
self._prefetch_threads = threads
|
||||
for t in threads:
|
||||
self._prefetch_threads = [threading.Thread(target=self._store, args=(label, attr, fetch), name=name, daemon=True)
|
||||
for name, label, attr, fetch in jobs]
|
||||
for t in self._prefetch_threads:
|
||||
t.start()
|
||||
|
||||
def _context_overlay(self, query: str) -> dict:
|
||||
query_result = self._client.query_context(self._user_id, self._session_id, query)
|
||||
profile = self._client.get_profile(self._user_id)
|
||||
return {"context": _build_overlay(profile, query_result), "raw": query_result}
|
||||
return {"context": _build_overlay(self._client.get_profile(self._user_id), query_result), "raw": query_result}
|
||||
|
||||
def _fetch_dialectic(self, query: str) -> tuple[str, str | None]:
|
||||
result = self._client.ask_user(self._user_id, query, reasoning_level=self._reasoning_level(query))
|
||||
return "_dialectic_result", str(result.get("answer") or "") or None
|
||||
@staticmethod
|
||||
def _agent_model_or_none(model: dict) -> dict | None:
|
||||
return model if model.get("memory_count", 0) > 0 else None
|
||||
|
||||
def _fetch_agent_model(self) -> tuple[str, dict | None]:
|
||||
model = self._client.get_agent_model(self._agent_id)
|
||||
return "_agent_model", model if model.get("memory_count", 0) > 0 else None
|
||||
|
||||
def _store(self, label: str, fetch: Callable[[], tuple[str, Any]]) -> None:
|
||||
"""Run one prefetch job; store (attr, value) under the lock unless value is None; log failures at debug."""
|
||||
try:
|
||||
attr, value = fetch()
|
||||
if value is not None:
|
||||
with self._lock:
|
||||
setattr(self, attr, value)
|
||||
except Exception as exc:
|
||||
logger.debug("RetainDB %s prefetch failed: %s", label, exc)
|
||||
def _store(self, label: str, attr: str, fetch: Callable[[], Any]) -> None:
|
||||
"""Run one prefetch job; cache its value under the lock unless None (failures log at debug)."""
|
||||
value = _quiet(f"{label} prefetch", fetch)
|
||||
if value is not None:
|
||||
with self._lock:
|
||||
setattr(self, attr, value)
|
||||
|
||||
@staticmethod
|
||||
def _reasoning_level(query: str) -> str:
|
||||
n = len(query)
|
||||
return "low" if n < 120 else "medium" if n < 400 else "high"
|
||||
return "low" if len(query) < 120 else "medium" if len(query) < 400 else "high"
|
||||
|
||||
def prefetch(self, query: str, *, session_id: str = "") -> str:
|
||||
"""Consume prefetched results and return them as a context block."""
|
||||
with self._lock:
|
||||
context, dialectic, agent_model = self._context_result, self._dialectic_result, self._agent_model
|
||||
self._context_result = self._dialectic_result = ""
|
||||
self._agent_model = {}
|
||||
parts = [context] if context else []
|
||||
if dialectic:
|
||||
parts.append(f"[RetainDB User Synthesis]\n{dialectic}")
|
||||
if agent_model.get("memory_count", 0) > 0:
|
||||
model_lines = [fmt(agent_model[k]) for k, fmt in _AGENT_MODEL_FIELDS if agent_model.get(k)]
|
||||
if model_lines:
|
||||
parts.append("[RetainDB Agent Self-Model]\n" + "\n".join(model_lines))
|
||||
return "\n\n".join(parts)
|
||||
self._context_result, self._dialectic_result, self._agent_model = "", "", {}
|
||||
model_lines = [fmt(agent_model[k]) for k, fmt in _AGENT_MODEL_FIELDS if agent_model.get(k)] if agent_model.get("memory_count", 0) > 0 else []
|
||||
parts = [context, dialectic and f"[RetainDB User Synthesis]\n{dialectic}",
|
||||
model_lines and "[RetainDB Agent Self-Model]\n" + "\n".join(model_lines)]
|
||||
return "\n\n".join(p for p in parts if p)
|
||||
|
||||
def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:
|
||||
"""Queue turn for async ingest. Returns immediately."""
|
||||
if not self._queue or not user_content:
|
||||
return
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
self._queue.enqueue(self._user_id, session_id or self._session_id, [
|
||||
{"role": "user", "content": user_content, "timestamp": now},
|
||||
{"role": "assistant", "content": assistant_content, "timestamp": now},
|
||||
])
|
||||
self._queue.enqueue(self._user_id, session_id or self._session_id,
|
||||
[{"role": "user", "content": user_content, "timestamp": now},
|
||||
{"role": "assistant", "content": assistant_content, "timestamp": now}])
|
||||
|
||||
def get_tool_schemas(self) -> List[Dict[str, Any]]:
|
||||
def get_tool_schemas(self) -> list[dict[str, Any]]:
|
||||
return list(_SCHEMAS)
|
||||
|
||||
def handle_tool_call(self, tool_name: str, args: dict, **kwargs) -> str:
|
||||
@@ -524,14 +421,11 @@ class RetainDBMemoryProvider(MemoryProvider):
|
||||
return tool_error(str(exc))
|
||||
|
||||
def _dispatch(self, tool_name: str, args: dict) -> Any:
|
||||
entry = _TOOLS.get(tool_name)
|
||||
if entry is None:
|
||||
required, handler = _TOOLS.get(tool_name, (None, None))
|
||||
if handler is None:
|
||||
return {"error": f"Unknown tool: {tool_name}"}
|
||||
required, handler = entry
|
||||
value = args.get(required, "") if required else None
|
||||
if required and not value:
|
||||
return {"error": f"{required} is required"}
|
||||
return handler(self, args, value)
|
||||
return {"error": f"{required} is required"} if required and not value else handler(self, args, value)
|
||||
|
||||
def _tool_upload_file(self, args: dict, local_path: str) -> Any:
|
||||
path_obj = Path(local_path)
|
||||
@@ -542,19 +436,17 @@ class RetainDBMemoryProvider(MemoryProvider):
|
||||
except ValueError as exc:
|
||||
return {"error": str(exc)}
|
||||
import mimetypes
|
||||
mime = mimetypes.guess_type(path_obj.name)[0] or "application/octet-stream"
|
||||
result = self._client.upload_file(path_obj.read_bytes(), path_obj.name, args.get("remote_path") or f"/{path_obj.name}",
|
||||
mime, args.get("scope", "PROJECT"), None)
|
||||
mimetypes.guess_type(path_obj.name)[0] or "application/octet-stream", args.get("scope", "PROJECT"), None)
|
||||
if args.get("ingest") and result.get("file", {}).get("id"):
|
||||
result["ingest"] = self._ingest(result["file"]["id"])
|
||||
return result
|
||||
|
||||
def _tool_read_file(self, args: dict, file_id: str) -> Any:
|
||||
file_info = self._client.get_file(file_id).get("file") or {}
|
||||
mime = (file_info.get("mime_type") or "").lower()
|
||||
raw = self._client.read_file_content(file_id)
|
||||
out = {"file_id": file_id, "rdb_uri": file_info.get("rdb_uri"), "name": file_info.get("name")}
|
||||
if not (mime.startswith("text/") or file_info.get("name", "").endswith(_TEXT_EXTS)):
|
||||
if not ((file_info.get("mime_type") or "").lower().startswith("text/") or file_info.get("name", "").endswith(_TEXT_EXTS)):
|
||||
return {**out, "content": None, "note": "Binary file — use retaindb_ingest_file to extract text into memory."}
|
||||
text = raw.decode("utf-8", errors="replace")
|
||||
return {**out, "content": text[:32000], "truncated": len(text) > 32000}
|
||||
@@ -566,23 +458,19 @@ class RetainDBMemoryProvider(MemoryProvider):
|
||||
"""Mirror built-in memory writes to RetainDB."""
|
||||
if action != "add" or not content or not self._client:
|
||||
return
|
||||
try:
|
||||
memory_type = "preference" if target == "user" else "factual"
|
||||
self._client.add_memory(self._user_id, self._session_id, content, memory_type=memory_type)
|
||||
except Exception as exc:
|
||||
logger.debug("RetainDB memory mirror failed: %s", exc)
|
||||
_quiet("memory mirror", lambda: self._client.add_memory(
|
||||
self._user_id, self._session_id, content, memory_type="preference" if target == "user" else "factual"))
|
||||
|
||||
def shutdown(self) -> None:
|
||||
for t in self._prefetch_threads:
|
||||
t.join(timeout=3.0)
|
||||
self._prefetch_threads = []
|
||||
queue_obj, self._queue, self._client = self._queue, None, None
|
||||
queue_obj, self._prefetch_threads, self._queue, self._client = self._queue, [], None, None
|
||||
if queue_obj:
|
||||
queue_obj.shutdown()
|
||||
|
||||
|
||||
# tool name -> (required arg or None, handler(provider, args, required_value)); missing arg -> "<arg> is required"
|
||||
_TOOLS: Dict[str, tuple[str | None, Callable[..., Any]]] = {
|
||||
_TOOLS: dict[str, tuple[str | None, Callable[..., Any]]] = {
|
||||
"retaindb_profile": (None, lambda p, a, _: p._client.get_profile(p._user_id)),
|
||||
"retaindb_search": ("query", lambda p, a, q: p._client.search(p._user_id, p._session_id, q, top_k=min(int(a.get("top_k", 8)), 20))),
|
||||
"retaindb_context": ("query", lambda p, a, q: p._context_overlay(q)),
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
"""Supermemory memory plugin (MemoryProvider): profile recall, semantic search, explicit memory tools,
|
||||
cleaned turn capture, and session-end conversation ingest."""
|
||||
"""Supermemory memory plugin (MemoryProvider): profile recall, semantic search, memory tools, turn capture, session ingest."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -20,22 +20,13 @@ from tools.registry import tool_error
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_DEFAULT_CONTAINER_TAG = "hermes"
|
||||
_DEFAULT_MAX_RECALL_RESULTS = 10
|
||||
_DEFAULT_PROFILE_FREQUENCY = 50
|
||||
_DEFAULT_CAPTURE_MODE = "all"
|
||||
_DEFAULT_SEARCH_MODE = "hybrid"
|
||||
_VALID_SEARCH_MODES = ("hybrid", "memories", "documents")
|
||||
_DEFAULT_API_TIMEOUT = 5.0
|
||||
_MAX_ENTITY_CONTEXT_LENGTH = 1500
|
||||
_DEFAULT_BASE_URL = "https://api.supermemory.ai"
|
||||
_API_KEY_URL = "http://app.supermemory.ai/integrations?connect=hermes"
|
||||
# Strips injected <supermemory-context> / <supermemory-containers> blocks before capture.
|
||||
_INJECTED_BLOCK_RE = re.compile(
|
||||
r"<supermemory-(context|containers)>[\s\S]*?</supermemory-\1>\s*", re.DOTALL
|
||||
)
|
||||
_INJECTED_BLOCK_RE = re.compile(r"<supermemory-(context|containers)>[\s\S]*?</supermemory-\1>\s*", re.DOTALL)
|
||||
_DEFAULT_ENTITY_CONTEXT = (
|
||||
"User-assistant conversation. Format: [role: user]...[user:end] and "
|
||||
"[role: assistant]...[assistant:end].\n\n"
|
||||
"User-assistant conversation. Format: [role: user]...[user:end] and [role: assistant]...[assistant:end].\n\n"
|
||||
"Only extract things useful in future conversations. Most messages are not worth remembering.\n\n"
|
||||
"Remember lasting personal facts, preferences, routines, tools, ongoing projects, working context, "
|
||||
"and explicit requests to remember something.\n\n"
|
||||
@@ -43,18 +34,20 @@ _DEFAULT_ENTITY_CONTEXT = (
|
||||
"When in doubt, store less."
|
||||
)
|
||||
# snake_case tool name -> kebab-case alias exposed alongside it.
|
||||
_KEBAB_ALIASES = {
|
||||
"supermemory_store": "supermemory-save",
|
||||
"supermemory_search": "supermemory-search",
|
||||
"supermemory_forget": "supermemory-forget",
|
||||
"supermemory_profile": "supermemory-profile",
|
||||
}
|
||||
_KEBAB_ALIASES = {"supermemory_store": "supermemory-save", "supermemory_search": "supermemory-search",
|
||||
"supermemory_forget": "supermemory-forget", "supermemory_profile": "supermemory-profile"}
|
||||
_ALIAS_TO_TOOL = {kebab: snake for snake, kebab in _KEBAB_ALIASES.items()}
|
||||
_BOOL_WORDS = {**dict.fromkeys(("true", "1", "yes", "y", "on"), True), **dict.fromkeys(("false", "0", "no", "n", "off"), False)}
|
||||
|
||||
|
||||
def _default_config() -> dict:
|
||||
"""Fresh copy of every config default (lists are copied so callers can mutate safely)."""
|
||||
return {k: (list(d) if isinstance(d, list) else d) for k, (d, _) in _CONFIG_SPEC.items()}
|
||||
def _quietly(fn: Callable[[], Any], fail_msg: str = "", *args: Any, level: int = logging.DEBUG, default: Any = None) -> Any:
|
||||
"""Run ``fn()``; on any exception log ``fail_msg`` (if given) with traceback and return ``default``."""
|
||||
try:
|
||||
return fn()
|
||||
except Exception:
|
||||
if fail_msg:
|
||||
logger.log(level, fail_msg, *args, exc_info=True)
|
||||
return default
|
||||
|
||||
|
||||
def _sanitize_tag(raw: str) -> str:
|
||||
@@ -62,35 +55,23 @@ def _sanitize_tag(raw: str) -> str:
|
||||
|
||||
|
||||
def _resolve_base_url(config_value: Any = "") -> str:
|
||||
"""Resolve the API base URL: config > SUPERMEMORY_BASE_URL env var > default (self-hosted support)."""
|
||||
"""config > SUPERMEMORY_BASE_URL env var > default (self-hosted support)."""
|
||||
raw = str(config_value or "").strip() or os.environ.get("SUPERMEMORY_BASE_URL", "").strip()
|
||||
return (raw or _DEFAULT_BASE_URL).rstrip("/") or _DEFAULT_BASE_URL
|
||||
|
||||
|
||||
def _clamp_entity_context(text: str) -> str:
|
||||
return text.strip()[:_MAX_ENTITY_CONTEXT_LENGTH] if text else _DEFAULT_ENTITY_CONTEXT
|
||||
|
||||
|
||||
_BOOL_WORDS = {**dict.fromkeys(("true", "1", "yes", "y", "on"), True), **dict.fromkeys(("false", "0", "no", "n", "off"), False)}
|
||||
return text.strip()[:1500] if text else _DEFAULT_ENTITY_CONTEXT
|
||||
|
||||
|
||||
def _as_bool(value: Any, default: bool) -> bool:
|
||||
"""bool passthrough; common true/false words parsed; anything else (incl. ints) -> default."""
|
||||
if isinstance(value, bool):
|
||||
return value
|
||||
return _BOOL_WORDS.get(value.strip().lower(), default) if isinstance(value, str) else default
|
||||
|
||||
|
||||
def _valid_search_mode(mode: str) -> str:
|
||||
return mode if mode in _VALID_SEARCH_MODES else _DEFAULT_SEARCH_MODE
|
||||
return value if isinstance(value, bool) else _BOOL_WORDS.get(value.strip().lower(), default) if isinstance(value, str) else default
|
||||
|
||||
|
||||
def _clamp_number(value: Any, default, lo, hi, cast):
|
||||
"""Cast ``value`` and clamp it to [lo, hi]; fall back to ``default`` on any conversion error."""
|
||||
try:
|
||||
return max(lo, min(hi, cast(value)))
|
||||
except Exception:
|
||||
return default
|
||||
return _quietly(lambda: max(lo, min(hi, cast(value))), default=default)
|
||||
|
||||
|
||||
# config key -> (default, normalizer applied to the raw/merged value). Order = supermemory.json layout.
|
||||
@@ -100,14 +81,13 @@ _CONFIG_SPEC: Dict[str, tuple] = {
|
||||
"container_tag": (_DEFAULT_CONTAINER_TAG, lambda v: str(v).strip() or _DEFAULT_CONTAINER_TAG),
|
||||
"auto_recall": (True, lambda v: _as_bool(v, True)),
|
||||
"auto_capture": (True, lambda v: _as_bool(v, True)),
|
||||
"max_recall_results": (_DEFAULT_MAX_RECALL_RESULTS, lambda v: _clamp_number(v, _DEFAULT_MAX_RECALL_RESULTS, 1, 20, int)),
|
||||
"profile_frequency": (_DEFAULT_PROFILE_FREQUENCY, lambda v: _clamp_number(v, _DEFAULT_PROFILE_FREQUENCY, 1, 500, int)),
|
||||
"capture_mode": (_DEFAULT_CAPTURE_MODE, lambda v: "everything" if v == "everything" else "all"),
|
||||
"search_mode": (_DEFAULT_SEARCH_MODE, lambda v: _valid_search_mode(str(v).strip().lower())),
|
||||
"max_recall_results": (10, lambda v: _clamp_number(v, 10, 1, 20, int)),
|
||||
"profile_frequency": (50, lambda v: _clamp_number(v, 50, 1, 500, int)),
|
||||
"capture_mode": ("all", lambda v: "everything" if v == "everything" else "all"),
|
||||
"search_mode": ("hybrid", lambda v: v if (v := str(v).strip().lower()) in _VALID_SEARCH_MODES else "hybrid"),
|
||||
"entity_context": (_DEFAULT_ENTITY_CONTEXT, lambda v: _clamp_entity_context(str(v))),
|
||||
"api_timeout": (_DEFAULT_API_TIMEOUT, lambda v: _clamp_number(v, _DEFAULT_API_TIMEOUT, 0.5, 15.0, float)),
|
||||
"api_timeout": (5.0, lambda v: _clamp_number(v, 5.0, 0.5, 15.0, float)),
|
||||
"base_url": ("", lambda v: str(v or "").strip()),
|
||||
# Multi-container support
|
||||
"enable_custom_container_tags": (False, lambda v: _as_bool(v, False)),
|
||||
"custom_containers": ([], lambda v: [_sanitize_tag(str(t)) for t in v if t] if isinstance(v, list) else []),
|
||||
"custom_container_instructions": ("", lambda v: str(v).strip()),
|
||||
@@ -115,202 +95,129 @@ _CONFIG_SPEC: Dict[str, tuple] = {
|
||||
|
||||
|
||||
def _read_json_dict(path: Path) -> dict:
|
||||
"""Return the JSON object stored at ``path`` or {} if missing/invalid."""
|
||||
if path.exists():
|
||||
try:
|
||||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||||
if isinstance(raw, dict):
|
||||
return raw
|
||||
except Exception:
|
||||
logger.debug("Failed to parse %s", path, exc_info=True)
|
||||
return {}
|
||||
raw = _quietly(lambda: json.loads(path.read_text(encoding="utf-8")), "Failed to parse %s", path) if path.exists() else None
|
||||
return raw if isinstance(raw, dict) else {}
|
||||
|
||||
|
||||
def _load_supermemory_config(hermes_home: str) -> dict:
|
||||
config = _default_config()
|
||||
config.update({k: v for k, v in _read_json_dict(Path(hermes_home) / "supermemory.json").items() if v is not None})
|
||||
def _load_supermemory_config(hermes_home: Optional[str] = None) -> dict:
|
||||
"""Defaults overlaid with $hermes_home/supermemory.json (None = defaults only), every key normalized."""
|
||||
config = {k: (list(d) if isinstance(d, list) else d) for k, (d, _) in _CONFIG_SPEC.items()}
|
||||
if hermes_home is not None:
|
||||
config.update({k: v for k, v in _read_json_dict(Path(hermes_home) / "supermemory.json").items() if v is not None})
|
||||
for key, (_, normalize) in _CONFIG_SPEC.items():
|
||||
config[key] = normalize(config[key])
|
||||
return config
|
||||
|
||||
|
||||
def _save_supermemory_config(values: dict, hermes_home: str) -> None:
|
||||
config_path = Path(hermes_home) / "supermemory.json"
|
||||
existing = _read_json_dict(config_path)
|
||||
existing.update(values)
|
||||
from utils import atomic_json_write
|
||||
atomic_json_write(config_path, existing, mode=0o600, sort_keys=True)
|
||||
|
||||
|
||||
# Ordered: first matching pattern wins.
|
||||
_CATEGORY_PATTERNS = (
|
||||
("preference", r"prefer|like|love|hate|want"),
|
||||
("decision", r"decided|will use|going with"),
|
||||
("fact", r"\bis\b|\bare\b|\bhas\b|\bhave\b"),
|
||||
)
|
||||
config_path = Path(hermes_home) / "supermemory.json"
|
||||
atomic_json_write(config_path, {**_read_json_dict(config_path), **values}, mode=0o600, sort_keys=True)
|
||||
|
||||
|
||||
def _detect_category(text: str) -> str:
|
||||
lowered = text.lower()
|
||||
return next((cat for cat, pat in _CATEGORY_PATTERNS if re.search(pat, lowered)), "other")
|
||||
lowered = text.lower() # first matching pattern wins
|
||||
return next((cat for cat, pat in (("preference", r"prefer|like|love|hate|want"), ("decision", r"decided|will use|going with"),
|
||||
("fact", r"\bis\b|\bare\b|\bhas\b|\bhave\b")) if re.search(pat, lowered)), "other")
|
||||
|
||||
|
||||
def _format_relative_time(iso_timestamp: str) -> str:
|
||||
try:
|
||||
dt = datetime.fromisoformat(iso_timestamp.replace("Z", "+00:00"))
|
||||
now = datetime.now(timezone.utc)
|
||||
"""'just now' / '5m ago' / '3h ago' / '2d ago' / '%d %b[ %Y]'; '' when unparseable."""
|
||||
def _fmt():
|
||||
dt, now = datetime.fromisoformat(iso_timestamp.replace("Z", "+00:00")), datetime.now(timezone.utc)
|
||||
seconds = (now - dt).total_seconds()
|
||||
if seconds < 1800:
|
||||
return "just now"
|
||||
for limit, unit, label in ((3600, 60, "m"), (86400, 3600, "h"), (604800, 86400, "d")):
|
||||
for limit, unit, label in ((1800, 0, "just now"), (3600, 60, "m ago"), (86400, 3600, "h ago"), (604800, 86400, "d ago")):
|
||||
if seconds < limit:
|
||||
return f"{int(seconds / unit)}{label} ago"
|
||||
return f"{int(seconds / unit)}{label}" if unit else label
|
||||
return dt.strftime("%d %b" if dt.year == now.year else "%d %b %Y")
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def _deduplicate_recall(static_facts: list, dynamic_facts: list, search_results: list) -> tuple[list, list, list]:
|
||||
"""Drop empties and repeats across the three lists; earlier lists win (profile facts beat search hits)."""
|
||||
seen: set = set()
|
||||
|
||||
def _unique(items, key=lambda x: x):
|
||||
out = []
|
||||
for item in items or []:
|
||||
k = key(item)
|
||||
if k and k not in seen:
|
||||
seen.add(k)
|
||||
out.append(item)
|
||||
return out
|
||||
|
||||
return _unique(static_facts), _unique(dynamic_facts), _unique(search_results, key=lambda i: i.get("memory", ""))
|
||||
|
||||
|
||||
def _bullets(title: str, items: list) -> str:
|
||||
return f"## {title}\n" + "\n".join(f"- {item}" for item in items)
|
||||
return _quietly(_fmt, default="")
|
||||
|
||||
|
||||
def _similarity_pct(value: Any) -> Optional[int]:
|
||||
"""0..1 similarity -> whole percent; None when absent or unparseable."""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
return round(float(value) * 100)
|
||||
except Exception:
|
||||
return None
|
||||
return _quietly(lambda: None if value is None else round(float(value) * 100))
|
||||
|
||||
|
||||
def _profile_sections(static_facts: list, dynamic_facts: list) -> list[str]:
|
||||
return ([_bullets("User Profile (Persistent)", static_facts)] if static_facts else []) + \
|
||||
([_bullets("Recent Context", dynamic_facts)] if dynamic_facts else [])
|
||||
return [f"## {title}\n" + "\n".join(f"- {item}" for item in items)
|
||||
for title, items in (("User Profile (Persistent)", static_facts), ("Recent Context", dynamic_facts)) if items]
|
||||
|
||||
|
||||
def _format_prefetch_context(static_facts: list, dynamic_facts: list, search_results: list, max_results: int) -> str:
|
||||
statics, dynamics, search = (lst[:max_results] for lst in _deduplicate_recall(static_facts, dynamic_facts, search_results))
|
||||
sections = _profile_sections(statics, dynamics)
|
||||
"""Dedupe across the three lists (earlier lists win: profile facts beat search hits), cap each, render."""
|
||||
seen: set = set()
|
||||
|
||||
def _unique(items, key=lambda x: x): # set.add() returns None, so `not seen.add(k)` records k and keeps the item
|
||||
return [i for i in items or [] if (k := key(i)) and k not in seen and not seen.add(k)][:max_results]
|
||||
sections = _profile_sections(_unique(static_facts), _unique(dynamic_facts))
|
||||
lines = []
|
||||
for item in search: # dedupe already dropped items without a memory string
|
||||
for item in _unique(search_results, key=lambda i: i.get("memory", "")):
|
||||
rel = _format_relative_time(item.get("updated_at") or item.get("updatedAt") or "")
|
||||
pct = _similarity_pct(item.get("similarity"))
|
||||
prefix_bits = ([f"[{rel}]"] if rel else []) + ([f"[{pct}%]"] if pct is not None else [])
|
||||
lines.append(f"- {' '.join(prefix_bits)} {item['memory']}".strip())
|
||||
if lines:
|
||||
sections.append("## Relevant Memories\n" + "\n".join(lines))
|
||||
if not sections:
|
||||
return ""
|
||||
intro = ("The following is background context from long-term memory. Use it silently when relevant. "
|
||||
"Do not force memories into the conversation.")
|
||||
return f"<supermemory-context>\n{intro}\n\n" + "\n\n".join(sections) + "\n</supermemory-context>"
|
||||
lines.append(f"- {' '.join(([f'[{rel}]'] if rel else []) + ([f'[{pct}%]'] if pct is not None else []))} {item['memory']}".strip())
|
||||
sections += ["## Relevant Memories\n" + "\n".join(lines)] if lines else []
|
||||
intro = "The following is background context from long-term memory. Use it silently when relevant. Do not force memories into the conversation."
|
||||
return f"<supermemory-context>\n{intro}\n\n" + "\n\n".join(sections) + "\n</supermemory-context>" if sections else ""
|
||||
|
||||
|
||||
def _clean_text_for_capture(text: str) -> str:
|
||||
return _INJECTED_BLOCK_RE.sub("", text or "").strip()
|
||||
|
||||
|
||||
def _updated_at(item: Any) -> Any:
|
||||
return getattr(item, "updated_at", None) or getattr(item, "updatedAt", None)
|
||||
def _memory_fields(item: Any, *keys: str) -> dict:
|
||||
"""Pick SDK result attrs into a plain dict; ``updated_at`` also accepts camelCase ``updatedAt``."""
|
||||
defaults = {"id": "", "memory": "", "similarity": None, "metadata": None}
|
||||
return {k: getattr(item, "updated_at", None) or getattr(item, "updatedAt", None) if k == "updated_at" else getattr(item, k, defaults[k])
|
||||
for k in keys}
|
||||
|
||||
|
||||
class _SupermemoryClient:
|
||||
def __init__(self, api_key: str, timeout: float, container_tag: str,
|
||||
search_mode: str = "hybrid", base_url: str = ""):
|
||||
# Lazy-install the SDK on demand (honors security.allow_lazy_installs and
|
||||
# sealed Docker venvs). On failure fall through so the raw import below
|
||||
# produces the canonical ImportError message.
|
||||
try:
|
||||
from tools.lazy_deps import ensure as _lazy_ensure
|
||||
_lazy_ensure("memory.supermemory", prompt=False)
|
||||
except Exception:
|
||||
pass
|
||||
# Lazy-install the SDK on demand (honors security.allow_lazy_installs and sealed Docker
|
||||
# venvs). On failure fall through so the raw import produces the canonical ImportError.
|
||||
_quietly(lambda: importlib.import_module("tools.lazy_deps").ensure("memory.supermemory", prompt=False))
|
||||
from supermemory import Supermemory
|
||||
|
||||
self._api_key = api_key
|
||||
self._container_tag = container_tag
|
||||
self._search_mode = _valid_search_mode(search_mode)
|
||||
self._timeout = timeout
|
||||
self._api_key, self._container_tag, self._timeout = api_key, container_tag, timeout
|
||||
self._search_mode = search_mode if search_mode in _VALID_SEARCH_MODES else "hybrid"
|
||||
self._base_url = _resolve_base_url(base_url)
|
||||
self._client = Supermemory(api_key=api_key, base_url=self._base_url, timeout=timeout, max_retries=0,
|
||||
default_headers={"x-sm-source": "hermes"})
|
||||
|
||||
def _merge_metadata(self, metadata: Optional[dict]) -> dict:
|
||||
# sm_source routes Hermes writes into the "Hermes" Space in the Supermemory
|
||||
# app so the user can filter / bulk-manage them per source agent (a
|
||||
# functional routing key for the user, not vendor telemetry).
|
||||
# sm_source routes Hermes writes into the "Hermes" Space in the Supermemory app so the user
|
||||
# can filter / bulk-manage them per source agent (a routing key for the user, not telemetry).
|
||||
merged = {"sm_source": "hermes", **(metadata or {})}
|
||||
legacy_source = merged.pop("source", None)
|
||||
if legacy_source and "type" not in merged:
|
||||
if (legacy_source := merged.pop("source", None)) and "type" not in merged:
|
||||
merged["type"] = str(legacy_source)
|
||||
return merged
|
||||
|
||||
def add_memory(self, content: str, metadata: Optional[dict] = None, *, entity_context: str = "",
|
||||
container_tag: Optional[str] = None, custom_id: Optional[str] = None) -> dict:
|
||||
kwargs: dict[str, Any] = {"content": content.strip(), "container_tags": [container_tag or self._container_tag]}
|
||||
if metadata:
|
||||
kwargs["metadata"] = self._merge_metadata(metadata)
|
||||
if entity_context:
|
||||
kwargs["entity_context"] = _clamp_entity_context(entity_context)
|
||||
if custom_id:
|
||||
kwargs["custom_id"] = custom_id
|
||||
result = self._client.documents.add(**kwargs)
|
||||
return {"id": getattr(result, "id", "")}
|
||||
kwargs: dict[str, Any] = {"content": content.strip(), "container_tags": [container_tag or self._container_tag],
|
||||
**({"metadata": self._merge_metadata(metadata)} if metadata else {}),
|
||||
**({"entity_context": _clamp_entity_context(entity_context)} if entity_context else {}),
|
||||
**({"custom_id": custom_id} if custom_id else {})}
|
||||
return {"id": getattr(self._client.documents.add(**kwargs), "id", "")}
|
||||
|
||||
def search_memories(self, query: str, *, limit: int = 5, container_tag: Optional[str] = None,
|
||||
search_mode: Optional[str] = None) -> list[dict]:
|
||||
mode = search_mode or self._search_mode
|
||||
kwargs: dict[str, Any] = {"q": query, "container_tag": container_tag or self._container_tag, "limit": limit}
|
||||
if mode in _VALID_SEARCH_MODES:
|
||||
kwargs["search_mode"] = mode
|
||||
kwargs: dict[str, Any] = {"q": query, "container_tag": container_tag or self._container_tag, "limit": limit,
|
||||
**({"search_mode": mode} if mode in _VALID_SEARCH_MODES else {})}
|
||||
response = self._client.search.memories(**kwargs)
|
||||
return [
|
||||
{
|
||||
"id": getattr(item, "id", ""),
|
||||
"memory": getattr(item, "memory", "") or "",
|
||||
"similarity": getattr(item, "similarity", None),
|
||||
"updated_at": _updated_at(item),
|
||||
"metadata": getattr(item, "metadata", None),
|
||||
}
|
||||
for item in (getattr(response, "results", None) or [])
|
||||
]
|
||||
return [{**_memory_fields(item, "id", "memory", "similarity", "updated_at", "metadata"), "memory": getattr(item, "memory", "") or ""}
|
||||
for item in (getattr(response, "results", None) or [])]
|
||||
|
||||
def get_profile(self, query: Optional[str] = None, *, container_tag: Optional[str] = None) -> dict:
|
||||
kwargs: dict[str, Any] = {"container_tag": container_tag or self._container_tag}
|
||||
if query:
|
||||
kwargs["q"] = query
|
||||
response = self._client.profile(**kwargs)
|
||||
response = self._client.profile(container_tag=container_tag or self._container_tag, **({"q": query} if query else {}))
|
||||
profile_data = getattr(response, "profile", None)
|
||||
search_data = getattr(response, "search_results", None) or getattr(response, "searchResults", None)
|
||||
raw_results = getattr(search_data, "results", None) or search_data or []
|
||||
return {
|
||||
"static": (getattr(profile_data, "static", []) or []) if profile_data else [],
|
||||
"dynamic": (getattr(profile_data, "dynamic", []) or []) if profile_data else [],
|
||||
"search_results": [
|
||||
item if isinstance(item, dict) else {
|
||||
"memory": getattr(item, "memory", ""),
|
||||
"updated_at": _updated_at(item),
|
||||
"similarity": getattr(item, "similarity", None),
|
||||
}
|
||||
for item in raw_results
|
||||
] if isinstance(raw_results, list) else [],
|
||||
**{k: (getattr(profile_data, k, []) or []) if profile_data else [] for k in ("static", "dynamic")},
|
||||
"search_results": [item if isinstance(item, dict) else _memory_fields(item, "memory", "updated_at", "similarity")
|
||||
for item in raw_results] if isinstance(raw_results, list) else [],
|
||||
}
|
||||
|
||||
def forget_memory(self, memory_id: str, *, container_tag: Optional[str] = None) -> None:
|
||||
@@ -318,30 +225,27 @@ class _SupermemoryClient:
|
||||
|
||||
def forget_by_query(self, query: str, *, container_tag: Optional[str] = None) -> dict:
|
||||
results = self.search_memories(query, limit=5, container_tag=container_tag)
|
||||
if not results:
|
||||
return {"success": False, "message": "No matching memory found to forget."}
|
||||
memory_id = results[0].get("id", "")
|
||||
memory_id = results[0].get("id", "") if results else ""
|
||||
if not memory_id:
|
||||
return {"success": False, "message": "Best matching memory has no id."}
|
||||
return {"success": False, "message": "Best matching memory has no id." if results else "No matching memory found to forget."}
|
||||
self.forget_memory(memory_id, container_tag=container_tag)
|
||||
return {"success": True, "message": f'Forgot: "{(results[0].get("memory") or "")[:100]}"', "id": memory_id}
|
||||
|
||||
def ingest_conversation(self, session_id: str, messages: list[dict], metadata: dict | None = None) -> None:
|
||||
payload: dict = {"conversationId": session_id, "messages": messages, "containerTags": [self._container_tag]}
|
||||
if metadata:
|
||||
payload["metadata"] = self._merge_metadata(metadata)
|
||||
|
||||
req = urllib.request.Request(
|
||||
f"{self._base_url}/v4/conversations",
|
||||
data=json.dumps(payload).encode("utf-8"),
|
||||
headers={"Authorization": f"Bearer {self._api_key}", "Content-Type": "application/json",
|
||||
"x-sm-source": "hermes"},
|
||||
method="POST",
|
||||
)
|
||||
payload: dict = {"conversationId": session_id, "messages": messages, "containerTags": [self._container_tag],
|
||||
**({"metadata": self._merge_metadata(metadata)} if metadata else {})}
|
||||
req = urllib.request.Request(f"{self._base_url}/v4/conversations", data=json.dumps(payload).encode("utf-8"), method="POST",
|
||||
headers={"Authorization": f"Bearer {self._api_key}", "Content-Type": "application/json",
|
||||
"x-sm-source": "hermes"})
|
||||
with urllib.request.urlopen(req, timeout=self._timeout + 3):
|
||||
return
|
||||
|
||||
|
||||
def _build_client(api_key: str, config: dict, container_tag: str) -> _SupermemoryClient:
|
||||
return _SupermemoryClient(api_key=api_key, timeout=config["api_timeout"], container_tag=container_tag,
|
||||
search_mode=config["search_mode"], base_url=_resolve_base_url(config["base_url"]))
|
||||
|
||||
|
||||
def _resolve_container_tag(config_tag: str, identity: str) -> str:
|
||||
"""SUPERMEMORY_CONTAINER_TAG env > config > default; {identity} expands to the agent identity, then sanitize."""
|
||||
raw_tag = os.environ.get("SUPERMEMORY_CONTAINER_TAG", "").strip() or config_tag
|
||||
@@ -350,105 +254,71 @@ def _resolve_container_tag(config_tag: str, identity: str) -> str:
|
||||
|
||||
def _probe_supermemory_connection(api_key: str, hermes_home: str, *, identity: str = "default") -> dict:
|
||||
config = _load_supermemory_config(hermes_home)
|
||||
status = {
|
||||
"ok": False, "error": "", "profile_facts": 0,
|
||||
"container_tag": _resolve_container_tag(config["container_tag"], identity),
|
||||
"auto_recall": bool(config["auto_recall"]), "auto_capture": bool(config["auto_capture"]),
|
||||
}
|
||||
status = {"ok": False, "error": "", "profile_facts": 0, "container_tag": _resolve_container_tag(config["container_tag"], identity),
|
||||
"auto_recall": bool(config["auto_recall"]), "auto_capture": bool(config["auto_capture"])}
|
||||
if not (api_key or "").strip():
|
||||
status["error"] = "SUPERMEMORY_API_KEY not set"
|
||||
return status
|
||||
return {**status, "error": "SUPERMEMORY_API_KEY not set"}
|
||||
try:
|
||||
__import__("supermemory")
|
||||
except ImportError:
|
||||
status["error"] = "supermemory package not installed"
|
||||
return status
|
||||
return {**status, "error": "supermemory package not installed"}
|
||||
try:
|
||||
client = _SupermemoryClient(api_key=api_key.strip(), timeout=config["api_timeout"],
|
||||
container_tag=status["container_tag"], search_mode=config["search_mode"],
|
||||
base_url=_resolve_base_url(config["base_url"]))
|
||||
profile = client.get_profile()
|
||||
status["profile_facts"] = sum(
|
||||
1 for f in (profile.get("static") or []) + (profile.get("dynamic") or []) if f and str(f).strip()
|
||||
)
|
||||
status["ok"] = True
|
||||
profile = _build_client(api_key.strip(), config, status["container_tag"]).get_profile()
|
||||
except Exception as exc:
|
||||
status["error"] = str(exc).strip()[:160] or "connection failed"
|
||||
return status
|
||||
return {**status, "error": str(exc).strip()[:160] or "connection failed"}
|
||||
facts = sum(1 for f in (profile.get("static") or []) + (profile.get("dynamic") or []) if f and str(f).strip())
|
||||
return {**status, "ok": True, "profile_facts": facts}
|
||||
|
||||
|
||||
def _format_connection_summary(status: dict) -> str:
|
||||
container = status.get("container_tag") or _DEFAULT_CONTAINER_TAG
|
||||
flags = (f"auto_recall {'on' if status.get('auto_recall') else 'off'} · "
|
||||
f"auto_capture {'on' if status.get('auto_capture') else 'off'}")
|
||||
flags = f"auto_recall {'on' if status.get('auto_recall') else 'off'} · auto_capture {'on' if status.get('auto_capture') else 'off'}"
|
||||
if status.get("ok"):
|
||||
facts = int(status.get("profile_facts") or 0)
|
||||
return f"✓ Connected · container: {container} · {facts} profile {'fact' if facts == 1 else 'facts'} · {flags}"
|
||||
return f"✗ {status.get('error') or 'connection failed'} · container: {container} · {flags}"
|
||||
|
||||
|
||||
def _schema(name: str, description: str, properties: dict, required: Optional[list] = None) -> dict:
|
||||
parameters: dict[str, Any] = {"type": "object", "properties": properties}
|
||||
if required:
|
||||
parameters["required"] = required
|
||||
return {"name": name, "description": description, "parameters": parameters}
|
||||
|
||||
|
||||
def _str_prop(description: str) -> dict:
|
||||
return {"type": "string", "description": description}
|
||||
|
||||
|
||||
STORE_SCHEMA, SEARCH_SCHEMA, FORGET_SCHEMA, PROFILE_SCHEMA = _BASE_SCHEMAS = [
|
||||
_schema("supermemory_store", "Store an explicit memory for future recall.", {
|
||||
"content": _str_prop("The memory content to store."),
|
||||
"metadata": {"type": "object", "description": "Optional metadata attached to the memory."},
|
||||
}, required=["content"]),
|
||||
_schema("supermemory_search", "Search long-term memory by semantic similarity.", {
|
||||
"query": _str_prop("What to search for."),
|
||||
"limit": {"type": "integer", "description": "Maximum results to return, 1 to 20."},
|
||||
}, required=["query"]),
|
||||
_schema("supermemory_forget", "Forget a memory by exact id or by best-match query.", {
|
||||
"id": _str_prop("Exact memory id to delete."),
|
||||
"query": _str_prop("Query used to find the memory to forget."),
|
||||
}),
|
||||
_schema("supermemory_profile", "Retrieve persistent profile facts and recent memory context.", {
|
||||
"query": _str_prop("Optional query to focus the profile response."),
|
||||
}),
|
||||
# (name, description, ((prop, type, description), ...), required) -> tool schema; kebab aliases are added in get_tool_schemas().
|
||||
_BASE_SCHEMAS = [
|
||||
{"name": name, "description": description,
|
||||
"parameters": {"type": "object", "properties": {p: {"type": t, "description": d} for p, t, d in props}, **({"required": req} if req else {})}}
|
||||
for name, description, props, req in (
|
||||
("supermemory_store", "Store an explicit memory for future recall.",
|
||||
(("content", "string", "The memory content to store."), ("metadata", "object", "Optional metadata attached to the memory.")), ["content"]),
|
||||
("supermemory_search", "Search long-term memory by semantic similarity.",
|
||||
(("query", "string", "What to search for."), ("limit", "integer", "Maximum results to return, 1 to 20.")), ["query"]),
|
||||
("supermemory_forget", "Forget a memory by exact id or by best-match query.",
|
||||
(("id", "string", "Exact memory id to delete."), ("query", "string", "Query used to find the memory to forget.")), None),
|
||||
("supermemory_profile", "Retrieve persistent profile facts and recent memory context.",
|
||||
(("query", "string", "Optional query to focus the profile response."),), None),
|
||||
)
|
||||
]
|
||||
|
||||
|
||||
def _turns_to_messages(turns: List[Dict[str, str]]) -> list[dict]:
|
||||
return [{"role": role, "content": turn[role]} for turn in turns for role in ("user", "assistant") if turn.get(role)]
|
||||
class _TagError(Exception):
|
||||
"""Tool call named a container_tag outside the whitelist."""
|
||||
|
||||
|
||||
def _tagged(resp: dict, tag: Optional[str]) -> dict:
|
||||
return {**resp, "container_tag": tag} if tag else resp
|
||||
|
||||
|
||||
class SupermemoryMemoryProvider(MemoryProvider):
|
||||
def __init__(self):
|
||||
self._api_key = self._session_id = self._hermes_home = self._prefetch_result = ""
|
||||
self._api_key = self._session_id = self._hermes_home = ""
|
||||
self._client: Optional[_SupermemoryClient] = None
|
||||
self._container_tag = _DEFAULT_CONTAINER_TAG
|
||||
self._turn_count = 0
|
||||
self._prefetch_lock = threading.Lock()
|
||||
self._prefetch_thread: Optional[threading.Thread] = None
|
||||
self._sync_thread: Optional[threading.Thread] = None
|
||||
self._write_thread: Optional[threading.Thread] = None
|
||||
self._write_enabled = True
|
||||
self._active = False
|
||||
self._container_tag, self._turn_count, self._write_enabled, self._active = _DEFAULT_CONTAINER_TAG, 0, True, False
|
||||
self._prefetch_thread = self._sync_thread = self._write_thread = None # only _write_thread is ever started
|
||||
self._session_turns: List[Dict[str, str]] = []
|
||||
self._apply_config(_default_config())
|
||||
self._base_url = _DEFAULT_BASE_URL # env var is only consulted in initialize()
|
||||
self._allowed_containers = []
|
||||
self._apply_config(_load_supermemory_config())
|
||||
self._base_url, self._allowed_containers = _DEFAULT_BASE_URL, [] # env var is only consulted in initialize()
|
||||
|
||||
def _apply_config(self, config: dict) -> None:
|
||||
self._config = config
|
||||
for key in ("auto_recall", "auto_capture", "max_recall_results", "profile_frequency", "capture_mode",
|
||||
"search_mode", "entity_context", "api_timeout"):
|
||||
"search_mode", "entity_context", "api_timeout", "custom_containers", "custom_container_instructions"):
|
||||
setattr(self, f"_{key}", config[key])
|
||||
# Base URL: config > SUPERMEMORY_BASE_URL env var > api.supermemory.ai (self-hosted support).
|
||||
self._base_url = _resolve_base_url(config["base_url"])
|
||||
# Multi-container support
|
||||
self._enable_custom_containers = config["enable_custom_container_tags"]
|
||||
self._custom_containers: List[str] = config["custom_containers"]
|
||||
self._custom_container_instructions = config["custom_container_instructions"]
|
||||
self._base_url, self._enable_custom_containers = _resolve_base_url(config["base_url"]), config["enable_custom_container_tags"]
|
||||
self._allowed_containers: List[str] = [self._container_tag] + list(self._custom_containers)
|
||||
|
||||
@property
|
||||
@@ -456,314 +326,212 @@ class SupermemoryMemoryProvider(MemoryProvider):
|
||||
return "supermemory"
|
||||
|
||||
def is_available(self) -> bool:
|
||||
# Key presence only, no SDK import check: the SDK is lazy-installed when the
|
||||
# client is first constructed in initialize(), so gating on importability here
|
||||
# would be a chicken-and-egg trap on sealed venvs. Mirrors honcho/mem0.
|
||||
# Key presence only, no SDK import check: the SDK is lazy-installed in initialize(), so gating on
|
||||
# importability here is a chicken-and-egg trap on sealed venvs. Mirrors honcho/mem0.
|
||||
return bool(get_secret("SUPERMEMORY_API_KEY", ""))
|
||||
|
||||
def get_config_schema(self):
|
||||
# Only prompt for the API key during `hermes memory setup`; other options
|
||||
# live in $HERMES_HOME/supermemory.json or SUPERMEMORY_CONTAINER_TAG.
|
||||
return [
|
||||
{"key": "api_key", "description": "Supermemory API key", "secret": True, "required": True, "env_var": "SUPERMEMORY_API_KEY", "url": _API_KEY_URL},
|
||||
]
|
||||
# Only the API key is prompted during `hermes memory setup`; other options live in supermemory.json / env.
|
||||
return [{"key": "api_key", "description": "Supermemory API key", "secret": True, "required": True, "env_var": "SUPERMEMORY_API_KEY", "url": _API_KEY_URL}]
|
||||
|
||||
def save_config(self, values, hermes_home):
|
||||
sanitized = dict(values or {})
|
||||
if "container_tag" in sanitized:
|
||||
sanitized["container_tag"] = _sanitize_tag(str(sanitized["container_tag"]))
|
||||
if "entity_context" in sanitized:
|
||||
sanitized["entity_context"] = _clamp_entity_context(str(sanitized["entity_context"]))
|
||||
for key, fix in (("container_tag", _sanitize_tag), ("entity_context", _clamp_entity_context)):
|
||||
if key in sanitized:
|
||||
sanitized[key] = fix(str(sanitized[key]))
|
||||
_save_supermemory_config(sanitized, hermes_home)
|
||||
|
||||
def get_status_config(self, provider_config: dict) -> dict:
|
||||
from hermes_constants import get_hermes_home
|
||||
|
||||
del provider_config
|
||||
api_key = get_secret("SUPERMEMORY_API_KEY", "") or ""
|
||||
status = _probe_supermemory_connection(api_key, str(get_hermes_home()))
|
||||
return {"summary": _format_connection_summary(status)}
|
||||
return {"summary": _format_connection_summary(_probe_supermemory_connection(get_secret("SUPERMEMORY_API_KEY", "") or "", str(get_hermes_home())))}
|
||||
|
||||
def post_setup(self, hermes_home: str, config: dict) -> None:
|
||||
from hermes_cli.config import save_config
|
||||
from hermes_cli.memory_setup import _prompt, _write_env_vars
|
||||
|
||||
print(f"\n Configuring supermemory:\n\n Get your API key at {_API_KEY_URL}\n")
|
||||
|
||||
existing = os.environ.get("SUPERMEMORY_API_KEY", "")
|
||||
masked = f"...{existing[-4:]}" if len(existing) > 4 else "set"
|
||||
val = _prompt(f"Supermemory API key (current: {masked}, blank to keep)" if existing else "Supermemory API key",
|
||||
secret=True)
|
||||
env_writes = {"SUPERMEMORY_API_KEY": val} if val else {}
|
||||
|
||||
if not isinstance(config.get("memory"), dict):
|
||||
config["memory"] = {}
|
||||
config["memory"]["provider"] = self.name
|
||||
val = _prompt(f"Supermemory API key (current: {masked}, blank to keep)" if existing else "Supermemory API key", secret=True)
|
||||
memory = config["memory"] = config["memory"] if isinstance(config.get("memory"), dict) else {}
|
||||
memory["provider"] = self.name
|
||||
save_config(config)
|
||||
|
||||
if env_writes:
|
||||
_write_env_vars(env_writes, hermes_home=hermes_home)
|
||||
|
||||
if val:
|
||||
_write_env_vars({"SUPERMEMORY_API_KEY": val}, hermes_home=hermes_home)
|
||||
api_key = val or existing
|
||||
# Make the freshly-entered key visible to the probe below. Single-profile
|
||||
# only: under a multiplexed gateway, writing to the process-global environ
|
||||
# would leak the key to sibling profiles and their subprocesses.
|
||||
# Make the freshly-entered key visible to the probe below. Single-profile only: under a multiplexed
|
||||
# gateway, writing to the process-global environ would leak the key to sibling profiles and their subprocesses.
|
||||
if api_key and not is_multiplex_active() and os.environ.get("SUPERMEMORY_API_KEY") != api_key:
|
||||
os.environ["SUPERMEMORY_API_KEY"] = api_key
|
||||
|
||||
status = _probe_supermemory_connection(api_key, hermes_home)
|
||||
print(f"\n {_format_connection_summary(status)}\n\n Memory provider: supermemory\n Activation saved to config.yaml")
|
||||
if env_writes:
|
||||
if val:
|
||||
print(" API keys saved to .env")
|
||||
print("\n Start a new session to activate.\n")
|
||||
|
||||
def initialize(self, session_id: str, **kwargs) -> None:
|
||||
from hermes_constants import get_hermes_home
|
||||
self._hermes_home = kwargs.get("hermes_home") or str(get_hermes_home())
|
||||
self._session_id = session_id
|
||||
self._turn_count = 0
|
||||
self._session_id, self._turn_count, self._session_turns = session_id, 0, []
|
||||
config = _load_supermemory_config(self._hermes_home)
|
||||
self._api_key = get_secret("SUPERMEMORY_API_KEY", "") or ""
|
||||
|
||||
self._container_tag = _resolve_container_tag(config["container_tag"], kwargs.get("agent_identity", "default"))
|
||||
self._apply_config(config)
|
||||
self._session_turns = []
|
||||
|
||||
self._write_enabled = kwargs.get("agent_context", "") not in {"cron", "flush", "subagent"}
|
||||
self._active = bool(self._api_key)
|
||||
self._client = None
|
||||
if self._active:
|
||||
try:
|
||||
self._client = _SupermemoryClient(api_key=self._api_key, timeout=self._api_timeout,
|
||||
container_tag=self._container_tag, search_mode=self._search_mode,
|
||||
base_url=self._base_url)
|
||||
except Exception:
|
||||
logger.warning("Supermemory initialization failed", exc_info=True)
|
||||
self._active = False
|
||||
self._client = None
|
||||
self._client = _quietly(lambda: _build_client(self._api_key, config, self._container_tag),
|
||||
"Supermemory initialization failed", level=logging.WARNING) if self._api_key else None
|
||||
self._active = self._client is not None
|
||||
|
||||
def on_turn_start(self, turn_number: int, message: str, **kwargs) -> None:
|
||||
self._turn_count = max(turn_number, 0)
|
||||
|
||||
def system_prompt_block(self) -> str:
|
||||
if not self._active:
|
||||
return ""
|
||||
lines = [
|
||||
"# Supermemory",
|
||||
f"Active. Container: {self._container_tag}.",
|
||||
"Use supermemory-search, supermemory-save, supermemory-forget, and supermemory-profile (aliases: supermemory_search, supermemory_store, supermemory_forget, supermemory_profile).",
|
||||
]
|
||||
lines = ["# Supermemory", f"Active. Container: {self._container_tag}.",
|
||||
"Use supermemory-search, supermemory-save, supermemory-forget, and supermemory-profile (aliases: supermemory_search, supermemory_store, supermemory_forget, supermemory_profile)."]
|
||||
if self._enable_custom_containers and self._custom_containers:
|
||||
lines.append(f"\nMulti-container mode enabled. Available containers: {', '.join(self._allowed_containers)}.")
|
||||
lines.append("Pass an optional container_tag to supermemory_search, supermemory_store, supermemory_forget, and supermemory_profile to target a specific container.")
|
||||
if self._custom_container_instructions:
|
||||
lines.append(f"\n{self._custom_container_instructions}")
|
||||
return "\n".join(lines)
|
||||
lines += [f"\nMulti-container mode enabled. Available containers: {', '.join(self._allowed_containers)}.",
|
||||
"Pass an optional container_tag to supermemory_search, supermemory_store, supermemory_forget, and supermemory_profile to target a specific container."]
|
||||
lines += [f"\n{self._custom_container_instructions}"] if self._custom_container_instructions else []
|
||||
return "\n".join(lines) if self._active else ""
|
||||
|
||||
def _can_write(self) -> bool:
|
||||
return bool(self._active and self._write_enabled and self._client)
|
||||
|
||||
def prefetch(self, query: str, *, session_id: str = "") -> str:
|
||||
if not self._active or not self._auto_recall or not self._client or not query.strip():
|
||||
return ""
|
||||
try:
|
||||
def _recall():
|
||||
profile = self._client.get_profile(query=query[:200])
|
||||
include_profile = self._turn_count <= 1 or (self._turn_count % self._profile_frequency == 0)
|
||||
return _format_prefetch_context(
|
||||
static_facts=profile["static"] if include_profile else [],
|
||||
dynamic_facts=profile["dynamic"] if include_profile else [],
|
||||
search_results=profile["search_results"],
|
||||
max_results=self._max_recall_results,
|
||||
)
|
||||
except Exception:
|
||||
logger.debug("Supermemory prefetch failed", exc_info=True)
|
||||
return ""
|
||||
return _format_prefetch_context(profile["static"] if include_profile else [], profile["dynamic"] if include_profile else [],
|
||||
profile["search_results"], self._max_recall_results)
|
||||
return _quietly(_recall, "Supermemory prefetch failed", default="")
|
||||
|
||||
def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:
|
||||
if not self._active or not self._auto_capture or not self._write_enabled or not self._client:
|
||||
if not self._can_write() or not self._auto_capture:
|
||||
return
|
||||
clean_user = _clean_text_for_capture(user_content)
|
||||
clean_assistant = _clean_text_for_capture(assistant_content)
|
||||
if clean_user or clean_assistant:
|
||||
# Buffer every turn for the single full-session document written at end/switch/shutdown
|
||||
self._session_turns.append({"user": clean_user, "assistant": clean_assistant})
|
||||
turn = {"user": _clean_text_for_capture(user_content), "assistant": _clean_text_for_capture(assistant_content)}
|
||||
if any(turn.values()): # buffered for the single full-session document written at end/switch/shutdown
|
||||
self._session_turns.append(turn)
|
||||
|
||||
def _ingest_session(self, session_id: str, messages: list[dict], metadata: dict,
|
||||
fail_msg: str, level: int = logging.DEBUG) -> None:
|
||||
try:
|
||||
self._client.ingest_conversation(
|
||||
session_id, messages, metadata={"type": "full_session", "session_id": session_id, **metadata}
|
||||
)
|
||||
except Exception:
|
||||
logger.log(level, fail_msg, exc_info=True)
|
||||
def _ingest(self, session_id: str, messages: list[dict], metadata: dict, fail_msg: str, level: int = logging.DEBUG) -> None:
|
||||
metadata = {"type": "full_session", "session_id": session_id, **metadata}
|
||||
_quietly(lambda: self._client.ingest_conversation(session_id, messages, metadata=metadata), fail_msg, level=level)
|
||||
|
||||
def _ingest_buffered_turns(self, session_id: str, *, partial: bool, fail_msg: str) -> None:
|
||||
# message_count reports 2 per buffered turn regardless of empty sides.
|
||||
self._ingest_session(session_id, _turns_to_messages(self._session_turns),
|
||||
{"message_count": len(self._session_turns) * 2, "partial": partial}, fail_msg)
|
||||
def _flush_turns(self, session_id: str, *, partial: bool, fail_msg: str) -> None:
|
||||
turns = self._session_turns # message_count reports 2 per buffered turn regardless of empty sides
|
||||
messages = [{"role": role, "content": t[role]} for t in turns for role in ("user", "assistant") if t.get(role)]
|
||||
self._ingest(session_id, messages, {"message_count": len(turns) * 2, "partial": partial}, fail_msg)
|
||||
|
||||
def on_session_end(self, messages: List[Dict[str, Any]]) -> None:
|
||||
if not self._active or not self._write_enabled or not self._client or not self._session_id:
|
||||
if not self._can_write() or not self._session_id:
|
||||
return
|
||||
cleaned = [
|
||||
{"role": m.get("role"), "content": _clean_text_for_capture(str(m.get("content", "")))}
|
||||
for m in messages or [] if m.get("role") in {"user", "assistant"}
|
||||
]
|
||||
cleaned = [m for m in cleaned if m["content"]]
|
||||
cleaned = [{"role": m.get("role"), "content": content} for m in messages or []
|
||||
if m.get("role") in {"user", "assistant"} and (content := _clean_text_for_capture(str(m.get("content", ""))))]
|
||||
if not cleaned or (len(cleaned) == 1 and len(cleaned[0]["content"]) < 20):
|
||||
return
|
||||
self._ingest_session(self._session_id, cleaned, {"message_count": len(cleaned)},
|
||||
"Supermemory session ingest failed", level=logging.WARNING)
|
||||
# Clear buffer so shutdown() doesn't duplicate on normal exit
|
||||
self._session_turns = []
|
||||
self._ingest(self._session_id, cleaned, {"message_count": len(cleaned)}, "Supermemory session ingest failed", level=logging.WARNING)
|
||||
self._session_turns = [] # so shutdown() doesn't duplicate on normal exit
|
||||
|
||||
def on_session_switch(self, new_session_id: str, *, parent_session_id: str = "", reset: bool = False,
|
||||
**kwargs) -> None:
|
||||
def on_session_switch(self, new_session_id: str, *, parent_session_id: str = "", reset: bool = False, **kwargs) -> None:
|
||||
"""Flush any buffered turns from the old session as one document, then reset for the new session."""
|
||||
if not self._active or not self._write_enabled or not self._client:
|
||||
self._session_id = str(new_session_id or "").strip() or self._session_id
|
||||
self._session_turns = []
|
||||
return
|
||||
|
||||
old_session_id = self._session_id
|
||||
if self._session_turns and old_session_id:
|
||||
self._ingest_buffered_turns(old_session_id, partial=not reset,
|
||||
fail_msg="Supermemory session-switch ingest failed")
|
||||
|
||||
if self._can_write():
|
||||
if self._session_turns and old_session_id:
|
||||
self._flush_turns(old_session_id, partial=not reset, fail_msg="Supermemory session-switch ingest failed")
|
||||
self._turn_count = 0
|
||||
self._session_id = str(new_session_id or "").strip() or old_session_id
|
||||
self._session_turns = []
|
||||
self._turn_count = 0
|
||||
|
||||
def on_memory_write(self, action: str, target: str, content: str) -> None:
|
||||
if not self._active or not self._write_enabled or not self._client:
|
||||
if not self._can_write() or action != "add" or not (content or "").strip():
|
||||
return
|
||||
if action != "add" or not (content or "").strip():
|
||||
return
|
||||
|
||||
def _run():
|
||||
try:
|
||||
self._client.add_memory(content.strip(), metadata={"target": target, "type": "explicit_memory"},
|
||||
entity_context=self._entity_context)
|
||||
except Exception:
|
||||
logger.debug("Supermemory on_memory_write failed", exc_info=True)
|
||||
|
||||
if self._write_thread and self._write_thread.is_alive():
|
||||
self._write_thread.join(timeout=2.0)
|
||||
self._write_thread = threading.Thread(target=_run, daemon=False, name="supermemory-memory-write")
|
||||
self._write_thread = threading.Thread(
|
||||
target=_quietly, daemon=False, name="supermemory-memory-write",
|
||||
args=(lambda: self._client.add_memory(content.strip(), metadata={"target": target, "type": "explicit_memory"},
|
||||
entity_context=self._entity_context), "Supermemory on_memory_write failed"))
|
||||
self._write_thread.start()
|
||||
|
||||
def shutdown(self) -> None:
|
||||
# Emergency fallback (crashes only). Buffer is cleared on normal on_session_end().
|
||||
if self._active and self._write_enabled and self._client and self._session_turns and self._session_id:
|
||||
if self._can_write() and self._session_turns and self._session_id:
|
||||
logger.warning("Supermemory: Saving session via shutdown (session=%s, turns=%d)", self._session_id, len(self._session_turns))
|
||||
self._ingest_buffered_turns(self._session_id, partial=True, fail_msg="Supermemory shutdown ingest failed")
|
||||
|
||||
for attr_name in ("_prefetch_thread", "_sync_thread", "_write_thread"):
|
||||
thread = getattr(self, attr_name, None)
|
||||
if thread and thread.is_alive():
|
||||
thread.join(timeout=5.0)
|
||||
setattr(self, attr_name, None)
|
||||
|
||||
def _resolve_tool_container_tag(self, args: dict) -> Optional[str]:
|
||||
"""Return the validated container_tag from args, None for primary; raise ValueError if not whitelisted."""
|
||||
tag = str(args.get("container_tag") or "").strip() if self._enable_custom_containers else ""
|
||||
if not tag:
|
||||
return None
|
||||
sanitized = _sanitize_tag(tag)
|
||||
if sanitized not in self._allowed_containers:
|
||||
raise ValueError(f"Container tag '{sanitized}' is not allowed. Allowed: {', '.join(self._allowed_containers)}")
|
||||
return sanitized
|
||||
self._flush_turns(self._session_id, partial=True, fail_msg="Supermemory shutdown ingest failed")
|
||||
if self._write_thread and self._write_thread.is_alive():
|
||||
self._write_thread.join(timeout=5.0)
|
||||
self._prefetch_thread = self._sync_thread = self._write_thread = None
|
||||
|
||||
def get_tool_schemas(self) -> List[Dict[str, Any]]:
|
||||
schemas = [json.loads(json.dumps(base)) for base in _BASE_SCHEMAS] # deep copies
|
||||
if self._enable_custom_containers:
|
||||
for schema in schemas: # multi-container mode: every tool takes an optional container_tag
|
||||
schema["parameters"]["properties"]["container_tag"] = {
|
||||
"type": "string",
|
||||
"description": f"Optional container tag. Allowed: {', '.join(self._allowed_containers)}. Defaults to primary ({self._container_tag}).",
|
||||
}
|
||||
for schema in schemas if self._enable_custom_containers else (): # multi-container mode: every tool takes container_tag
|
||||
schema["parameters"]["properties"]["container_tag"] = {
|
||||
"type": "string", "description": f"Optional container tag. Allowed: {', '.join(self._allowed_containers)}. Defaults to primary ({self._container_tag})."}
|
||||
# Kebab-case aliases are appended after all snake_case schemas (deep-copied, name swapped).
|
||||
return schemas + [{**json.loads(json.dumps(s)), "name": _KEBAB_ALIASES[s["name"]]} for s in schemas]
|
||||
|
||||
def _run_tool(self, args: dict, fail_prefix: str, fn: Callable[[Optional[str]], Any], *,
|
||||
tag_in_response: bool = True) -> str:
|
||||
"""Resolve container_tag, run ``fn(tag)``, and JSON-encode its result; errors become tool_error()."""
|
||||
try:
|
||||
tag = self._resolve_tool_container_tag(args)
|
||||
except ValueError as exc:
|
||||
return tool_error(str(exc))
|
||||
try:
|
||||
resp = fn(tag)
|
||||
if tag and tag_in_response:
|
||||
resp["container_tag"] = tag
|
||||
return json.dumps(resp)
|
||||
except Exception as exc:
|
||||
return tool_error(f"{fail_prefix}: {exc}")
|
||||
def _tool_container_tag(self, args: dict) -> Optional[str]:
|
||||
"""Validated container_tag from args; None = primary. Raises _TagError when not whitelisted."""
|
||||
raw = str(args.get("container_tag") or "").strip() if self._enable_custom_containers else ""
|
||||
tag = _sanitize_tag(raw) if raw else None
|
||||
if tag and tag not in self._allowed_containers:
|
||||
raise _TagError(f"Container tag '{tag}' is not allowed. Allowed: {', '.join(self._allowed_containers)}")
|
||||
return tag
|
||||
|
||||
def _tool_store(self, args: dict) -> str:
|
||||
def _tool_store(self, args: dict) -> dict | str:
|
||||
content = str(args.get("content") or "").strip()
|
||||
if not content:
|
||||
return tool_error("content is required")
|
||||
metadata = args.get("metadata") or {}
|
||||
if not isinstance(metadata, dict):
|
||||
metadata = {}
|
||||
metadata = args.get("metadata") if isinstance(args.get("metadata"), dict) else {}
|
||||
metadata.setdefault("type", _detect_category(content))
|
||||
metadata.pop("source", None)
|
||||
tag = self._tool_container_tag(args)
|
||||
result = self._client.add_memory(content, metadata=metadata, entity_context=self._entity_context, container_tag=tag)
|
||||
return _tagged({"saved": True, "id": result.get("id", ""), "preview": content[:80] + ("..." if len(content) > 80 else "")}, tag)
|
||||
|
||||
def _store(tag):
|
||||
result = self._client.add_memory(content, metadata=metadata, entity_context=self._entity_context, container_tag=tag)
|
||||
preview = content[:80] + ("..." if len(content) > 80 else "")
|
||||
return {"saved": True, "id": result.get("id", ""), "preview": preview}
|
||||
|
||||
return self._run_tool(args, "Failed to store memory", _store)
|
||||
|
||||
def _tool_search(self, args: dict) -> str:
|
||||
def _tool_search(self, args: dict) -> dict | str:
|
||||
query = str(args.get("query") or "").strip()
|
||||
if not query:
|
||||
return tool_error("query is required")
|
||||
limit = _clamp_number(args.get("limit", 5) or 5, 5, 1, 20, int)
|
||||
tag = self._tool_container_tag(args)
|
||||
results = [{"id": i.get("id", ""), "content": i.get("memory", ""), **({"similarity": pct} if (pct := _similarity_pct(i.get("similarity"))) is not None else {})}
|
||||
for i in self._client.search_memories(query, limit=limit, container_tag=tag)]
|
||||
return _tagged({"results": results, "count": len(results)}, tag)
|
||||
|
||||
def _search(tag):
|
||||
formatted = []
|
||||
for item in self._client.search_memories(query, limit=limit, container_tag=tag):
|
||||
pct = _similarity_pct(item.get("similarity"))
|
||||
formatted.append({"id": item.get("id", ""), "content": item.get("memory", ""),
|
||||
**({"similarity": pct} if pct is not None else {})})
|
||||
return {"results": formatted, "count": len(formatted)}
|
||||
|
||||
return self._run_tool(args, "Search failed", _search)
|
||||
|
||||
def _tool_forget(self, args: dict) -> str:
|
||||
memory_id = str(args.get("id") or "").strip()
|
||||
query = str(args.get("query") or "").strip()
|
||||
def _tool_forget(self, args: dict) -> dict | str:
|
||||
memory_id, query = str(args.get("id") or "").strip(), str(args.get("query") or "").strip()
|
||||
if not memory_id and not query:
|
||||
return tool_error("Provide either id or query")
|
||||
|
||||
def _forget(tag):
|
||||
if memory_id:
|
||||
self._client.forget_memory(memory_id, container_tag=tag)
|
||||
return {"forgotten": True, "id": memory_id}
|
||||
tag = self._tool_container_tag(args) # not echoed in the response
|
||||
if not memory_id:
|
||||
return self._client.forget_by_query(query, container_tag=tag)
|
||||
self._client.forget_memory(memory_id, container_tag=tag)
|
||||
return {"forgotten": True, "id": memory_id}
|
||||
|
||||
return self._run_tool(args, "Forget failed", _forget, tag_in_response=False)
|
||||
|
||||
def _tool_profile(self, args: dict) -> str:
|
||||
query = str(args.get("query") or "").strip() or None
|
||||
|
||||
def _profile(tag):
|
||||
profile = self._client.get_profile(query=query, container_tag=tag)
|
||||
return {"profile": "\n\n".join(_profile_sections(profile["static"], profile["dynamic"])),
|
||||
"static_count": len(profile["static"]), "dynamic_count": len(profile["dynamic"])}
|
||||
|
||||
return self._run_tool(args, "Profile failed", _profile)
|
||||
def _tool_profile(self, args: dict) -> dict:
|
||||
tag = self._tool_container_tag(args)
|
||||
profile = self._client.get_profile(query=str(args.get("query") or "").strip() or None, container_tag=tag)
|
||||
return _tagged({"profile": "\n\n".join(_profile_sections(profile["static"], profile["dynamic"])),
|
||||
"static_count": len(profile["static"]), "dynamic_count": len(profile["dynamic"])}, tag)
|
||||
|
||||
def handle_tool_call(self, tool_name: str, args: Dict[str, Any], **kwargs) -> str:
|
||||
"""Handlers return a tool_error() string for bad args or a dict to JSON-encode; client failures get ``fail_prefix``."""
|
||||
if not self._active or not self._client:
|
||||
return tool_error("Supermemory is not configured")
|
||||
tool_name = _ALIAS_TO_TOOL.get(tool_name, tool_name)
|
||||
handler = self._TOOL_HANDLERS.get(tool_name)
|
||||
return handler(self, args) if handler else tool_error(f"Unknown tool: {tool_name}")
|
||||
if tool_name not in self._TOOL_HANDLERS:
|
||||
return tool_error(f"Unknown tool: {tool_name}")
|
||||
handler, fail_prefix = self._TOOL_HANDLERS[tool_name]
|
||||
try:
|
||||
resp = handler(self, args)
|
||||
except Exception as exc:
|
||||
return tool_error(str(exc) if isinstance(exc, _TagError) else f"{fail_prefix}: {exc}")
|
||||
return resp if isinstance(resp, str) else json.dumps(resp)
|
||||
|
||||
# snake_case tool name -> handler; kebab aliases are folded in via _ALIAS_TO_TOOL first.
|
||||
_TOOL_HANDLERS = {"supermemory_store": _tool_store, "supermemory_search": _tool_search,
|
||||
"supermemory_forget": _tool_forget, "supermemory_profile": _tool_profile}
|
||||
# snake_case tool name -> (handler, error prefix); kebab aliases are folded in via _ALIAS_TO_TOOL first.
|
||||
_TOOL_HANDLERS = {"supermemory_store": (_tool_store, "Failed to store memory"), "supermemory_search": (_tool_search, "Search failed"),
|
||||
"supermemory_forget": (_tool_forget, "Forget failed"), "supermemory_profile": (_tool_profile, "Profile failed")}
|
||||
|
||||
|
||||
def register(ctx):
|
||||
|
||||
Reference in New Issue
Block a user