mirror of
https://github.com/rohitg00/agentmemory.git
synced 2026-09-14 20:16:33 +08:00
9c82d2aa7d
* chore(release): v0.9.29 with project-scope parity across surfaces Version trio + plugin manifests + supportedVersions + ExportData union bumped to 0.9.29; CHANGELOG entry covering everything since v0.9.28 with upgrade notes for the four visible behavior changes. Fixes the endpoint-count drift on main (130 registered routes vs docs saying 129 after #1132 landed in parallel with #1136). Project-scope parity: OpenCode plugin, Hermes plugin, Pi extension, and JSONL replay now resolve project the same way the hooks do (env override, git toplevel basename, cwd basename) instead of sending raw filesystem paths, closing #903 and #1135 and pre-empting the same bug in pi. The filesystem watcher accepts AGENTMEMORY_PROJECT_NAME with the old AGENTMEMORY_PROJECT kept as a deprecated alias, replay handles Windows-recorded paths, and OpenCode file enrichment matches the agent's lowercase tool names (the capitalized set never matched). Tests: opencode fallback expectations updated to basenames per the canonicalization, git-toplevel resolution covered with a fixture repo, new project-scope-parity suite for replay and fs-watcher. * fix(release): review findings, git-toplevel parity, doc counts - skills generator dedupes routes on method plus path, so the REST reference lists all 130 registered routes instead of hiding the second method on ten dual-method paths (header said 119) - fs-watcher trims AGENTMEMORY_PROJECT_NAME and the deprecated alias, treating whitespace as unset, and derives the git toplevel basename when watching a subdirectory - replay resolves the git toplevel basename when the recorded cwd still exists locally (memoized per cwd), keeping the basename fallback for historical or cross-platform paths; no env override here since a bulk import spans many projects - parity tests for replay git-root resolution, watcher git-root and trim behavior - stat-tests badge updated from 1428+ to 1550+ passing * fix(cli): refuse second-instance boot over a live daemon Closes the class behind issue 1140: agentmemory consolidate (or any unrecognized word) fell through the command table into the full server boot, registering a duplicate worker on the running engine; on iii 0.11.2 the second instance's shutdown tears down the daemon's HTTP trigger routing until a full engine restart. Unknown subcommands now error with the supported list, and main() probes livez on the resolved port and refuses to boot over a live daemon, so multi-instance setups on other ports are unaffected. Verified behaviorally against the built CLI: both paths refuse with exit 1. Also from review: the watcher stamps each event with its own root's project via a per-root map (an explicit config.project still overrides for every root), and replay only accepts a non-empty string cwd from parsed JSONL so malformed entries cannot reach the filesystem probe. * test(watcher): two-repository flush events scope to their own project * chore(release): bump packages/mcp, guard it, refresh CONTRIBUTING packages/mcp was still 0.9.28 after the release bump because nothing guarded it; a consistency test now pins it to package.json. CONTRIBUTING release list corrected to the files a bump actually touches (no tracked lockfile, the two extra plugin manifests, the export test derives from VERSION now), and the subsystems table gains src/cli, integrations/pi, and the generated-manifest note. * fix(export): refuse over-frame export instead of dropping the worker Closes the availability bug in issue 1142: GET /agentmemory/export assembles the full store and returns it through sdk.trigger, so a store whose serialized export passes the engine's 16 MiB WebSocket frame (tungstenite max_frame_size, not raisable under the 0.11.2 pin) dies on the worker->engine hop, drops the worker, and 404s every endpoint for ~1s. The session collections page on maxSessions/offset but ~18 others do not, so a large store hits this at any parameter combination. A shared frame-guard measures the serialized size before returning: mem::export returns a small oversized error instead of the giant object, and api::mesh-export returns 413 (same dead-end as #890). Either way the over-frame payload never crosses the boundary, so the daemon stays up and the failure is one clean request with a hint to narrow the range. Full pagination of the non-session collections is a follow-up. Layer 1 of the fix; verified with a synthetic oversized export returning the error object (tiny) rather than the payload. * ci: collapse to a single npm install to fix Node 24/26 CI The two-step install (npm install --package-lock-only then npm ci) failed only on the Node 24/26 matrix rows: their stricter npm rejects rolldown's optional platform bindings (@rolldown/binding-android-arm64) that a --package-lock-only pass does not fully enumerate. Lockfiles are gitignored, so npm ci re-validation buys no reproducibility here. A single lenient npm install resolves and installs in one pass. * fix(mesh): scope exported memories by project like actions api::mesh-export filtered actions by ?project but returned every project's memories. On a mesh instance federating one project to a peer, the peer pulled other projects' memories (cross-project leak), and those extras could push the payload past the 16 MiB transport frame into a 413 even when the requested project's own slice fit. Memories carry the same optional project field as actions, so filter both before the frame-size guard runs. Adds a regression test asserting a project-scoped export excludes other projects' memories and that an oversized memory in another project no longer 413s the scoped request. * chore(release): credit the Antigravity native hooks adapter in 0.9.29 notes * chore(release): sweep stale 0.9.28 refs for 0.9.29 Deploy Dockerfiles/compose/render pins, AGENTS.md stats header, opencode plugin manifest, website meta snapshot, test-count claims (1,428 -> 1,596) in README/AGENTS/stat SVGs, and the missing 0.9.29 CHANGELOG compare link. * chore(release): sync stat-tests badge to 1596+ and commit bridge exec bit * refactor: trim frame-guard comments and drop issue refs from code
414 lines
15 KiB
Python
414 lines
15 KiB
Python
"""
|
|
agentmemory memory provider for Hermes Agent.
|
|
|
|
Drop this folder into ~/.hermes/plugins/agentmemory/
|
|
or install via: hermes plugin install agentmemory
|
|
|
|
Requires agentmemory server running: npx @agentmemory/agentmemory
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import sys
|
|
import threading
|
|
import subprocess
|
|
from pathlib import PurePath
|
|
|
|
|
|
def _resolve_project(cwd: str) -> str:
|
|
"""Canonical project scope, matching the hooks' resolveProject order:
|
|
AGENTMEMORY_PROJECT_NAME env override, git toplevel basename, cwd basename.
|
|
Keeps Hermes sessions in the same project bucket as every other agent."""
|
|
explicit = os.environ.get("AGENTMEMORY_PROJECT_NAME", "").strip()
|
|
if explicit:
|
|
return explicit
|
|
try:
|
|
top = subprocess.run(
|
|
["git", "rev-parse", "--show-toplevel"],
|
|
cwd=cwd,
|
|
capture_output=True,
|
|
text=True,
|
|
timeout=5,
|
|
).stdout.strip()
|
|
if top:
|
|
return PurePath(top).name
|
|
except Exception:
|
|
pass
|
|
return PurePath(cwd).name or cwd
|
|
import time
|
|
from pathlib import Path
|
|
from typing import Any, Callable
|
|
from urllib.parse import urlparse
|
|
from urllib.request import Request, urlopen
|
|
from urllib.error import URLError
|
|
|
|
try:
|
|
from agent.memory_provider import MemoryProvider
|
|
except ImportError:
|
|
from abc import ABC, abstractmethod
|
|
|
|
class MemoryProvider(ABC):
|
|
@property
|
|
@abstractmethod
|
|
def name(self) -> str: ...
|
|
@abstractmethod
|
|
def is_available(self) -> bool: ...
|
|
@abstractmethod
|
|
def initialize(self, session_id: str, **kwargs: Any) -> None: ...
|
|
@abstractmethod
|
|
def get_tool_schemas(self) -> list[dict]: ...
|
|
@abstractmethod
|
|
def handle_tool_call(self, name: str, args: dict) -> str: ...
|
|
def get_config_schema(self) -> list[dict]: return []
|
|
def save_config(self, values: dict, hermes_home: str) -> None: pass
|
|
def system_prompt_block(self) -> str: return ""
|
|
def prefetch(self, query: str, **kwargs: Any) -> str: return ""
|
|
def queue_prefetch(self, query: str, **kwargs: Any) -> None: pass
|
|
def sync_turn(self, user: str, assistant: str, **kwargs: Any) -> None: pass
|
|
def on_session_end(self, messages: list, **kwargs: Any) -> None: pass
|
|
def on_pre_compress(self, messages: list, **kwargs: Any) -> None: pass
|
|
def on_memory_write(self, action: str, target: str, content: str, **kwargs: Any) -> None: pass
|
|
def shutdown(self, **kwargs: Any) -> None: pass
|
|
|
|
|
|
DEFAULT_BASE_URL = "http://localhost:3111"
|
|
TIMEOUT = 5
|
|
LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
|
|
_plaintext_bearer_warned = False
|
|
|
|
# agentmemory's documented runtime config lives at ~/.agentmemory/.env.
|
|
# When agentmemory is launched as a systemd user service (or any other
|
|
# process manager that loads that file directly), those values never
|
|
# reach an interactive shell. `hermes memory status` then reads
|
|
# os.environ in the Hermes CLI process, finds AGENTMEMORY_URL /
|
|
# AGENTMEMORY_SECRET unset, and reports the plugin as "Missing" even
|
|
# though the service is healthy and live sessions can use it (#250).
|
|
#
|
|
# Preload the file at plugin-import time using os.environ.setdefault so
|
|
# we never override anything the user explicitly set in the shell. The
|
|
# preload is best-effort and silent on any failure (file absent,
|
|
# unreadable, malformed) — the plugin falls back to its existing default
|
|
# (http://localhost:3111) and Hermes status reflects that.
|
|
def _preload_agentmemory_dotenv() -> None:
|
|
candidates: list[Path] = []
|
|
home = os.environ.get("HOME")
|
|
if home:
|
|
candidates.append(Path(home) / ".agentmemory" / ".env")
|
|
xdg_config = os.environ.get("XDG_CONFIG_HOME")
|
|
if xdg_config:
|
|
candidates.append(Path(xdg_config) / "agentmemory" / ".env")
|
|
for path in candidates:
|
|
try:
|
|
if not path.is_file():
|
|
continue
|
|
for raw in path.read_text(encoding="utf-8").splitlines():
|
|
line = raw.strip()
|
|
if not line or line.startswith("#") or "=" not in line:
|
|
continue
|
|
key, _, value = line.partition("=")
|
|
key = key.strip()
|
|
value = value.strip().strip('"').strip("'")
|
|
if key:
|
|
os.environ.setdefault(key, value)
|
|
except (OSError, UnicodeDecodeError):
|
|
continue
|
|
# Guarantee AGENTMEMORY_URL is set so `hermes memory status` never
|
|
# reports it as Missing when a user runs agentmemory at the default
|
|
# localhost:3111 (or via systemd with the URL line commented out in
|
|
# ~/.agentmemory/.env because it matches the default). #520.
|
|
os.environ.setdefault("AGENTMEMORY_URL", DEFAULT_BASE_URL)
|
|
|
|
|
|
_preload_agentmemory_dotenv()
|
|
|
|
|
|
def _validate_url(base: str) -> bool:
|
|
if not base:
|
|
return False
|
|
try:
|
|
parsed = urlparse(base)
|
|
# .port raises ValueError on a non-numeric or out-of-range port
|
|
_ = parsed.port
|
|
except ValueError:
|
|
return False
|
|
if parsed.scheme not in ("http", "https"):
|
|
return False
|
|
return bool(parsed.hostname)
|
|
|
|
|
|
def _uses_plaintext_bearer_auth(base: str, secret: str = "") -> bool:
|
|
if not secret:
|
|
return False
|
|
parsed = urlparse(base)
|
|
return parsed.scheme == "http" and (parsed.hostname or "").lower() not in LOOPBACK_HOSTS
|
|
|
|
|
|
def _plaintext_bearer_auth_message(base: str) -> str:
|
|
return f"agentmemory: AGENTMEMORY_SECRET is configured for plaintext HTTP to {base}. Bearer tokens and memory payloads can be observed on the network; use HTTPS or an SSH tunnel."
|
|
|
|
|
|
def _warn_plaintext_bearer_auth(message: str) -> None:
|
|
print(message, file=sys.stderr)
|
|
|
|
|
|
def _check_plaintext_bearer_guard(
|
|
base: str,
|
|
secret: str = "",
|
|
warn: Callable[[str], None] | None = None,
|
|
) -> None:
|
|
global _plaintext_bearer_warned
|
|
if not _uses_plaintext_bearer_auth(base, secret):
|
|
return
|
|
message = _plaintext_bearer_auth_message(base)
|
|
if os.environ.get("AGENTMEMORY_REQUIRE_HTTPS") == "1":
|
|
raise RuntimeError(message)
|
|
if not _plaintext_bearer_warned:
|
|
_plaintext_bearer_warned = True
|
|
(warn or _warn_plaintext_bearer_auth)(message)
|
|
|
|
|
|
def _reset_plaintext_bearer_guard_for_tests() -> None:
|
|
global _plaintext_bearer_warned
|
|
_plaintext_bearer_warned = False
|
|
|
|
|
|
def _api(base: str, path: str, body: dict | None = None, method: str = "POST", secret: str = "") -> dict | None:
|
|
if not _validate_url(base):
|
|
return None
|
|
url = f"{base}/agentmemory/{path}"
|
|
headers = {"Content-Type": "application/json"}
|
|
auth = secret or os.environ.get("AGENTMEMORY_SECRET", "")
|
|
_check_plaintext_bearer_guard(base, auth)
|
|
if auth:
|
|
headers["Authorization"] = f"Bearer {auth}"
|
|
|
|
data = json.dumps(body).encode() if body else None
|
|
req = Request(url, data=data, headers=headers, method=method)
|
|
try:
|
|
with urlopen(req, timeout=TIMEOUT) as resp:
|
|
return json.loads(resp.read().decode())
|
|
except (URLError, TimeoutError, json.JSONDecodeError):
|
|
return None
|
|
|
|
|
|
def _api_bg(base: str, path: str, body: dict | None = None) -> None:
|
|
t = threading.Thread(target=_api, args=(base, path, body), daemon=True)
|
|
t.start()
|
|
|
|
|
|
class AgentMemoryProvider(MemoryProvider):
|
|
|
|
@property
|
|
def name(self) -> str:
|
|
return "agentmemory"
|
|
|
|
def is_available(self) -> bool:
|
|
# Hermes contract: no network calls in is_available.
|
|
base = os.environ.get("AGENTMEMORY_URL", DEFAULT_BASE_URL)
|
|
return _validate_url(base)
|
|
|
|
def initialize(self, session_id: str, **kwargs: Any) -> None:
|
|
self._base = os.environ.get("AGENTMEMORY_URL", DEFAULT_BASE_URL)
|
|
self._session_id = session_id
|
|
self._cwd = kwargs.get("cwd", os.getcwd())
|
|
self._project = _resolve_project(self._cwd)
|
|
if os.environ.get("AGENTMEMORY_REQUIRE_HTTPS") == "1":
|
|
_check_plaintext_bearer_guard(self._base, os.environ.get("AGENTMEMORY_SECRET", ""))
|
|
|
|
_api(self._base, "session/start", {
|
|
"sessionId": session_id,
|
|
"project": self._project,
|
|
"cwd": self._cwd,
|
|
})
|
|
|
|
def get_config_schema(self) -> list[dict]:
|
|
return [
|
|
{
|
|
"key": "url",
|
|
"description": "agentmemory server URL",
|
|
"default": DEFAULT_BASE_URL,
|
|
"env_var": "AGENTMEMORY_URL",
|
|
},
|
|
{
|
|
"key": "secret",
|
|
"description": "agentmemory auth secret (optional)",
|
|
"secret": True,
|
|
"required": False,
|
|
"env_var": "AGENTMEMORY_SECRET",
|
|
},
|
|
]
|
|
|
|
def save_config(self, values: dict, hermes_home: str) -> None:
|
|
config_path = Path(hermes_home) / "agentmemory.json"
|
|
config_path.write_text(json.dumps(values, indent=2))
|
|
|
|
def system_prompt_block(self) -> str:
|
|
result = _api(self._base, "context", {
|
|
"sessionId": self._session_id,
|
|
"project": self._project,
|
|
})
|
|
if result and result.get("context"):
|
|
return result["context"]
|
|
return ""
|
|
|
|
def prefetch(self, query: str, **kwargs: Any) -> str:
|
|
result = _api(self._base, "smart-search", {
|
|
"query": query,
|
|
"limit": 5,
|
|
})
|
|
if not result or not result.get("results"):
|
|
return ""
|
|
|
|
lines = []
|
|
for r in result["results"][:5]:
|
|
obs = r.get("observation", r)
|
|
title = obs.get("title", "")
|
|
narrative = obs.get("narrative", "")
|
|
if title:
|
|
lines.append(f"- {title}: {narrative[:200]}")
|
|
return "\n".join(lines) if lines else ""
|
|
|
|
def queue_prefetch(self, query: str, **kwargs: Any) -> None:
|
|
_api_bg(self._base, "smart-search", {"query": query, "limit": 3})
|
|
|
|
def get_tool_schemas(self) -> list[dict]:
|
|
return [
|
|
{
|
|
"name": "memory_recall",
|
|
"description": "Search agentmemory for past observations by keyword",
|
|
"parameters": {
|
|
"type": "object",
|
|
"properties": {
|
|
"query": {"type": "string", "description": "Search query"},
|
|
"limit": {"type": "integer", "description": "Max results", "default": 10},
|
|
},
|
|
"required": ["query"],
|
|
},
|
|
},
|
|
{
|
|
"name": "memory_save",
|
|
"description": "Save an insight, decision, or pattern to long-term memory",
|
|
"parameters": {
|
|
"type": "object",
|
|
"properties": {
|
|
"content": {"type": "string", "description": "What to remember"},
|
|
"type": {
|
|
"type": "string",
|
|
"enum": ["pattern", "preference", "architecture", "bug", "workflow", "fact"],
|
|
"description": "Memory type",
|
|
},
|
|
},
|
|
"required": ["content"],
|
|
},
|
|
},
|
|
{
|
|
"name": "memory_search",
|
|
"description": "Hybrid semantic + keyword search across all memories",
|
|
"parameters": {
|
|
"type": "object",
|
|
"properties": {
|
|
"query": {"type": "string"},
|
|
"limit": {"type": "integer", "default": 5},
|
|
},
|
|
"required": ["query"],
|
|
},
|
|
},
|
|
]
|
|
|
|
def handle_tool_call(self, name: str, args: dict) -> str:
|
|
# Hermes stores the return value as the tool result `content` in the
|
|
# session history. Anthropic-protocol providers reject non-string
|
|
# content with a 400 on the next request, so always serialize to a
|
|
# JSON string here — matches what agentmemory's main MCP server does
|
|
# in src/mcp/standalone.ts (`{ type: "text", text: JSON.stringify(...) }`).
|
|
if name == "memory_recall":
|
|
result = _api(self._base, "search", {
|
|
"query": args["query"],
|
|
"limit": args.get("limit", 10),
|
|
})
|
|
if not result:
|
|
return json.dumps({"results": []})
|
|
items = []
|
|
for r in result.get("results", []):
|
|
obs = r.get("observation", r)
|
|
items.append({
|
|
"title": obs.get("title", ""),
|
|
"type": obs.get("type", ""),
|
|
"narrative": obs.get("narrative", ""),
|
|
"importance": obs.get("importance", 0),
|
|
"timestamp": obs.get("timestamp", ""),
|
|
})
|
|
return json.dumps({"results": items})
|
|
|
|
if name == "memory_save":
|
|
result = _api(self._base, "remember", {
|
|
"content": args["content"],
|
|
"type": args.get("type", "fact"),
|
|
})
|
|
return json.dumps(result or {"success": False})
|
|
|
|
if name == "memory_search":
|
|
result = _api(self._base, "smart-search", {
|
|
"query": args["query"],
|
|
"limit": args.get("limit", 5),
|
|
})
|
|
if not result:
|
|
return json.dumps({"results": []})
|
|
items = []
|
|
for r in result.get("results", []):
|
|
obs = r.get("observation", r)
|
|
items.append({
|
|
"title": obs.get("title", ""),
|
|
"narrative": obs.get("narrative", "")[:300],
|
|
"score": r.get("combinedScore", r.get("score", 0)),
|
|
})
|
|
return json.dumps({"results": items})
|
|
|
|
return json.dumps({"error": f"Unknown tool: {name}"})
|
|
|
|
def sync_turn(self, user: str, assistant: str, **kwargs: Any) -> None:
|
|
_api_bg(self._base, "observe", {
|
|
"hookType": "post_tool_use",
|
|
"sessionId": kwargs.get("session_id", self._session_id),
|
|
"project": self._project,
|
|
"cwd": self._cwd,
|
|
"timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
|
"data": {
|
|
"tool_name": "conversation",
|
|
"tool_input": user[:500],
|
|
"tool_output": assistant[:2000],
|
|
},
|
|
})
|
|
|
|
def on_session_end(self, messages: list, **kwargs: Any) -> None:
|
|
_api(self._base, "session/end", {
|
|
"sessionId": kwargs.get("session_id", self._session_id),
|
|
})
|
|
|
|
def on_pre_compress(self, messages: list, **kwargs: Any) -> None:
|
|
result = _api(self._base, "context", {
|
|
"sessionId": kwargs.get("session_id", self._session_id),
|
|
"project": self._project,
|
|
})
|
|
if result and result.get("context"):
|
|
messages.insert(0, {
|
|
"role": "user",
|
|
"content": f"[agentmemory context before compaction]\n{result['context']}",
|
|
})
|
|
|
|
def on_memory_write(self, action: str, target: str, content: str, **kwargs: Any) -> None:
|
|
if action in ("add", "update") and content:
|
|
_api_bg(self._base, "remember", {
|
|
"content": content,
|
|
"type": "fact",
|
|
})
|
|
|
|
def shutdown(self, **kwargs: Any) -> None:
|
|
pass
|
|
|
|
|
|
def register(ctx: Any) -> None:
|
|
ctx.register_memory_provider(AgentMemoryProvider())
|