diff --git a/plugins/memory/byterover/__init__.py b/plugins/memory/byterover/__init__.py index 55bc1e75f6..6d81225bf5 100644 --- a/plugins/memory/byterover/__init__.py +++ b/plugins/memory/byterover/__init__.py @@ -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: diff --git a/plugins/memory/retaindb/__init__.py b/plugins/memory/retaindb/__init__.py index ed21555795..fe8f2972c9 100644 --- a/plugins/memory/retaindb/__init__.py +++ b/plugins/memory/retaindb/__init__.py @@ -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