The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(supermemory): write turns via documents API instead of session-end conversations ingest
Mahesh Sanikommu03627dbf9588
diff --git a/plugins/memory/supermemory/README.md b/plugins/memory/supermemory/README.mdindex 3636905d2ed..4f09389cf07 100644--- a/plugins/memory/supermemory/README.md+++ b/plugins/memory/supermemory/README.md@@ -1,6 +1,6 @@# Supermemory Memory Provider-Semantic long-term memory with profile recall, semantic search, explicit memory tools, and full-session conversation ingest (one ingest per session) for richer profiles.+Semantic long-term memory with profile recall, semantic search, explicit memory tools, and per-turn conversation capture into one document per session per 4-hour window for richer profiles.## Requirements@@ -55,7 +55,7 @@ Config file: `$HERMES_HOME/supermemory.json`| `capture_mode` | `all` | Skip tiny or trivial turns by default || `search_mode` | `hybrid` | Search mode: `hybrid` (profile + memories), `memories` (memories only), `documents` (documents only) || `entity_context` | built-in default | Extraction guidance passed to Supermemory |-| `api_timeout` | `5.0` | Timeout for SDK and ingest requests |+| `api_timeout` | `5.0` | Timeout for SDK requests |### Environment Variables@@ -67,7 +67,7 @@ Config file: `$HERMES_HOME/supermemory.json`Base URL precedence is `supermemory.json` → `SUPERMEMORY_BASE_URL` →`https://api.supermemory.ai`. Hermes resolves it once and uses the same endpoint-for SDK operations, setup/status probes, and full-session conversation ingest.+for SDK operations and setup/status probes.## Tools@@ -93,9 +93,9 @@ Supermemory app, so you can filter, browse, and bulk-manage them per source agenWhen enabled, Hermes can:- prefetch relevant memory context before each turn-- buffer the full conversation and ingest it as **one session** at session end (or on `/reset`, branch, compression, or shutdown)-- ingest the full session to the conversations endpoint for richer profile/graph updates-- route every SDK, probe, and conversation-ingest request through the configured hosted or self-hosted endpoint+- write each completed user/assistant turn to **one document per session per 4-hour window** (`customId` = `<session>_<date>_b<0-5>`, so the API appends deltas), like the Codex and OpenClaw plugins+- retry failed turn writes on the next turn, session end, `/reset`, or shutdown+- route every SDK and probe request through the configured hosted or self-hosted endpoint- expose explicit tools for search, store, forget, and profile accessThe session is written once via the conversations endpoint, which drives Supermemory's entity extraction and profile building while keeping a clean, retrievable full transcript.@@ -128,7 +128,7 @@ For advanced setups (e.g. OpenClaw-style multi-workspace), you can enable customWhen enabled:- `supermemory-search`, `supermemory-save`, `supermemory-forget`, and `supermemory-profile` accept an optional `container_tag` parameter- The tag must be in the whitelist: primary container + `custom_containers`-- Automatic operations (turn sync, prefetch, memory write mirroring, session ingest) always use the **primary** container only+- Automatic operations (turn capture, prefetch, memory write mirroring) always use the **primary** container only- Custom container instructions are injected into the system prompt## Supportdiff --git a/plugins/memory/supermemory/__init__.py b/plugins/memory/supermemory/__init__.pyindex 8b4ac247ccd..ac168a6846d 100644--- a/plugins/memory/supermemory/__init__.py+++ b/plugins/memory/supermemory/__init__.py@@ -1,4 +1,4 @@-"""Supermemory memory plugin (MemoryProvider): profile recall, semantic search, memory tools, turn capture, session ingest."""+"""Supermemory memory plugin (MemoryProvider): profile recall, semantic search, memory tools, per-turn capture."""from __future__ import annotations@@ -8,7 +8,6 @@ import loggingimport osimport reimport threading-import urllib.requestfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any, Callable, Dict, List, Optional@@ -25,6 +24,8 @@ _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)+_DATA_URI_RE = re.compile(r"data:[^;,\s]+;base64,[A-Za-z0-9+/=]+") # pasted inline images are useless as memory text+_CAPTURE_BUCKET_HOURS = 4 # one capture document per session per 4h window (matches codex/openclaw plugins)_DEFAULT_ENTITY_CONTEXT = ("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"@@ -161,7 +162,7 @@ def _format_prefetch_context(static_facts: list, dynamic_facts: list, search_resdef _clean_text_for_capture(text: str) -> str:- return _INJECTED_BLOCK_RE.sub("", text or "").strip()+ return _DATA_URI_RE.sub("[image]", _INJECTED_BLOCK_RE.sub("", text or "")).strip()def _memory_fields(item: Any, *keys: str) -> dict:@@ -231,14 +232,16 @@ class _SupermemoryClient: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],- **({"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 _format_turn(user: str, assistant: str) -> str:+ """Render one turn in the [role: x]...[x:end] layout the entity context describes."""+ return "\n".join(f"[role: {role}]\n{text}\n[{role}:end]" for role, text in (("user", user), ("assistant", assistant)) if text)+++def _capture_custom_id(session_id: str, now: Optional[datetime] = None) -> str:+ """<session>_<YYYY-MM-DD>_b<0..5>: same id within a 4h window, so the API appends turns to one document."""+ now = now or datetime.now(timezone.utc)+ return f"{_sanitize_tag(session_id) or 'hermes'}_{now:%Y-%m-%d}_b{now.hour // _CAPTURE_BUCKET_HOURS}"def _build_client(api_key: str, config: dict, container_tag: str) -> _SupermemoryClient:@@ -312,7 +315,7 @@ class SupermemoryMemoryProvider(MemoryProvider):self._client: Optional[_SupermemoryClient] = Noneself._container_tag, self._turn_count, self._write_enabled, self._active = _DEFAULT_CONTAINER_TAG, 0, True, Falseself._prefetch_thread = self._sync_thread = self._write_thread = None # only _write_thread is ever started- self._session_turns: List[Dict[str, str]] = []+ self._pending_turns: List[Dict[str, str]] = [] # turns whose write failed; retried on next write/end/shutdownself._apply_config(_load_supermemory_config())self._base_url, self._allowed_containers = _DEFAULT_BASE_URL, [] # env var is only consulted in initialize()@@ -373,7 +376,7 @@ class SupermemoryMemoryProvider(MemoryProvider):def initialize(self, session_id: str, **kwargs) -> None:from hermes_constants import get_hermes_homeself._hermes_home = kwargs.get("hermes_home") or str(get_hermes_home())- self._session_id, self._turn_count, self._session_turns = session_id, 0, []+ self._session_id, self._turn_count, self._pending_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"))@@ -408,41 +411,43 @@ class SupermemoryMemoryProvider(MemoryProvider):profile["search_results"], self._max_recall_results)return _quietly(_recall, "Supermemory prefetch failed", default="")+ def _write_turns(self, turns: List[Dict[str, str]], session_id: str, mode: str) -> None:+ """Append turns to the session's current 4h document (shared custom_id, API merges deltas). Failures stay pending."""+ now = datetime.now(timezone.utc)+ content = "\n\n".join(_format_turn(t["user"], t["assistant"]) for t in turns)+ metadata = {"type": "conversation", "session_id": session_id, "timestamp": now.isoformat()} # no sm_capture_mode: Hermes policy+ try:+ self._client.add_memory(content, metadata=metadata, entity_context=self._entity_context,+ custom_id=_capture_custom_id(session_id, now))+ self._pending_turns = []+ except Exception:+ logger.log(logging.WARNING if mode != "turn" else logging.DEBUG, "Supermemory capture failed (%s, %d turns pending)",+ mode, len(turns), exc_info=True)+ self._pending_turns = turns+def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:+ # Host runs this on a worker thread, so the blocking write is fine here.if not self._can_write() or not self._auto_capture:returnturn = {"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(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)+ if any(turn.values()):+ self._write_turns(self._pending_turns + [turn], session_id or self._session_id, "turn")- 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 _flush_pending(self, session_id: str, mode: str) -> None:+ if self._can_write() and self._pending_turns:+ self._write_turns(list(self._pending_turns), session_id, mode)def on_session_end(self, messages: List[Dict[str, Any]]) -> None:- if not self._can_write() or not self._session_id:- return- 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(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+ # Turns were already written as they completed; only retry what failed.+ self._flush_pending(self._session_id, "session_end")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."""old_session_id = self._session_id+ self._flush_pending(old_session_id, "session_switch")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 = 0self._session_id = str(new_session_id or "").strip() or old_session_id- self._session_turns = []+ self._pending_turns = []def on_memory_write(self, action: str, target: str, content: str) -> None:if not self._can_write() or action != "add" or not (content or "").strip():@@ -456,10 +461,7 @@ class SupermemoryMemoryProvider(MemoryProvider):self._write_thread.start()def shutdown(self) -> None:- # Emergency fallback (crashes only). Buffer is cleared on normal on_session_end().- 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._flush_turns(self._session_id, partial=True, fail_msg="Supermemory shutdown ingest failed")+ self._flush_pending(self._session_id, "shutdown")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 = Nonediff --git a/plugins/memory/supermemory/plugin.yaml b/plugins/memory/supermemory/plugin.yamlindex 8100b321364..afb2cf0f483 100644--- a/plugins/memory/supermemory/plugin.yaml+++ b/plugins/memory/supermemory/plugin.yaml@@ -1,5 +1,5 @@name: supermemoryversion: 1.0.1-description: "Supermemory semantic long-term memory with profile recall, semantic search, explicit memory tools, and session ingest."+description: "Supermemory semantic long-term memory with profile recall, semantic search, explicit memory tools, and per-turn conversation capture."pip_dependencies:- supermemorydiff --git a/tests/plugins/memory/test_supermemory_provider.py b/tests/plugins/memory/test_supermemory_provider.pyindex 0aea3b9fc24..5993d5fbd2f 100644--- a/tests/plugins/memory/test_supermemory_provider.py+++ b/tests/plugins/memory/test_supermemory_provider.py@@ -7,6 +7,7 @@ import pytestfrom plugins.memory.supermemory import (SupermemoryMemoryProvider,+ _capture_custom_id,_clean_text_for_capture,_format_connection_summary,_format_prefetch_context,@@ -27,12 +28,14 @@ class FakeClient:self.add_calls = []self.search_results = []self.profile_response = {"static": [], "dynamic": [], "search_results": []}- self.ingest_calls = []+ self.fail_add = Falseself.forgotten_ids = []self.forget_by_query_response = {"success": True, "message": "Forgot"}def add_memory(self, content, metadata=None, *, entity_context="",container_tag=None, custom_id=None):+ if self.fail_add:+ raise RuntimeError("boom")self.add_calls.append({"content": content,"metadata": metadata,@@ -54,9 +57,6 @@ class FakeClient:def forget_by_query(self, query, *, container_tag=None):return self.forget_by_query_response- def ingest_conversation(self, session_id, messages, metadata=None):- self.ingest_calls.append({"session_id": session_id, "messages": messages, "metadata": metadata})-@pytest.fixturedef provider(monkeypatch, tmp_path):@@ -87,6 +87,11 @@ def test_clean_text_for_capture_strips_injected_context():assert _clean_text_for_capture(text) == "hello\nworld"+def test_clean_text_for_capture_strips_inline_data_uri():+ text = "look: data:image/png;base64,iVBORw0KGgoAAAANSUhEUg== ok"+ assert _clean_text_for_capture(text) == "look: [image] ok"++def test_format_prefetch_context_deduplicates_overlap():result = _format_prefetch_context(static_facts=["Jordan prefers short answers"],@@ -112,33 +117,74 @@ def test_prefetch_includes_profile_on_first_turn(provider):assert "Relevant Memories" in result-def test_sync_turn_buffers_short_messages(provider):- # Trivial filtering is no longer applied at sync time — every non-empty turn- # is buffered and only the full session is written at session boundaries.- provider.sync_turn("ok", "sure", session_id="session-1")- assert provider._session_turns == [{"user": "ok", "assistant": "sure"}]+def test_capture_custom_id_buckets_by_four_hours():+ from datetime import datetime, timezone+ a = _capture_custom_id("session-1", datetime(2026, 9, 12, 3, 59, tzinfo=timezone.utc))+ b = _capture_custom_id("session-1", datetime(2026, 9, 12, 4, 0, tzinfo=timezone.utc))+ assert a == "session_1_2026-09-12_b0"+ assert b == "session_1_2026-09-12_b1"+ assert _capture_custom_id("", datetime(2026, 9, 12, 23, 0, tzinfo=timezone.utc)) == "hermes_2026-09-12_b5"+++def test_sync_turn_writes_turn_to_session_document(provider):+ # Every completed turn is appended to one document per session per 4h window.+ provider.sync_turn("hello", "hi there", session_id="session-1")+ assert len(provider._client.add_calls) == 1+ call = provider._client.add_calls[0]+ assert call["custom_id"] == _capture_custom_id("session-1")+ assert call["content"] == "[role: user]\nhello\n[user:end]\n[role: assistant]\nhi there\n[assistant:end]"+ assert call["metadata"]["type"] == "conversation"+ assert call["metadata"]["session_id"] == "session-1"+ assert call["entity_context"]+ assert provider._pending_turns == []+++def test_sync_turn_skips_empty_turn(provider):+ provider.sync_turn("", "<supermemory-context>x</supermemory-context>", session_id="session-1")assert provider._client.add_calls == []-def test_on_session_end_ingests_clean_messages(provider):- messages = [- {"role": "system", "content": "skip"},- {"role": "user", "content": "hello"},- {"role": "assistant", "content": "hi there"},- ]- provider.on_session_end(messages)- assert len(provider._client.ingest_calls) == 1- payload = provider._client.ingest_calls[0]- assert payload["session_id"] == "session-1"- assert payload["messages"] == [- {"role": "user", "content": "hello"},- {"role": "assistant", "content": "hi there"},- ]- assert payload["metadata"]["type"] == "full_session"- assert payload["metadata"]["session_id"] == "session-1"- assert payload["metadata"]["message_count"] == 2- # Buffer is cleared after a normal session-end ingest.- assert provider._session_turns == []+def test_failed_turn_write_is_retried_at_session_end(provider):+ provider._client.fail_add = True+ provider.sync_turn("hello", "hi there", session_id="session-1")+ assert provider._client.add_calls == []+ assert provider._pending_turns == [{"user": "hello", "assistant": "hi there"}]++ provider._client.fail_add = False+ provider.on_session_end([])+ assert len(provider._client.add_calls) == 1+ call = provider._client.add_calls[0]+ assert call["custom_id"] == _capture_custom_id("session-1")+ assert "hello" in call["content"]+ assert provider._pending_turns == []+++def test_pending_turns_are_batched_with_next_turn(provider):+ provider._client.fail_add = True+ provider.sync_turn("one", "uno", session_id="session-1")+ provider._client.fail_add = False+ provider.sync_turn("two", "dos", session_id="session-1")+ assert len(provider._client.add_calls) == 1+ assert provider._client.add_calls[0]["content"].index("one") < provider._client.add_calls[0]["content"].index("two")+ assert provider._pending_turns == []+++def test_session_switch_flushes_pending_to_old_session(provider):+ provider._client.fail_add = True+ provider.sync_turn("hello", "hi", session_id="session-1")+ provider._client.fail_add = False+ provider.on_session_switch("session-2", reset=True)+ assert provider._client.add_calls[0]["custom_id"] == _capture_custom_id("session-1")+ assert provider._session_id == "session-2"+ assert provider._pending_turns == []+++def test_sync_turn_drops_inline_image_payloads(provider):+ blob = "A" * 4096+ provider.sync_turn(f"describe this data:image/png;base64,{blob}", "a screenshot", session_id="session-1")+ call = provider._client.add_calls[0]+ assert "describe this [image]" in call["content"]+ assert blob not in json.dumps(call)def test_merge_metadata_stamps_sm_source():@@ -164,25 +210,30 @@ def test_shutdown_joins_threads_and_flushes_buffer(provider, monkeypatch):def slow_add_memory(content, metadata=None, *, entity_context="",container_tag=None, custom_id=None):+ if provider._client.fail_add:+ raise RuntimeError("boom")started.set()release.wait(timeout=1)provider._client.add_calls.append({"content": content,"metadata": metadata,"entity_context": entity_context,+ "custom_id": custom_id,})return {"id": "mem_slow"}monkeypatch.setattr(provider._client, "add_memory", slow_add_memory)- # sync_turn now only buffers — no thread is spawned.+ # A failed turn write stays pending; shutdown retries it.+ provider._client.fail_add = Trueprovider.sync_turn("Please remember this request in long-term memory","Absolutely, I will keep that in long-term memory.",session_id="session-1",)+ provider._client.fail_add = Falseassert provider._sync_thread is None- assert len(provider._session_turns) == 1+ assert len(provider._pending_turns) == 1# on_memory_write still runs on a background thread.provider.on_memory_write("add", "memory", "Jordan likes concise docs")@@ -196,14 +247,10 @@ def test_shutdown_joins_threads_and_flushes_buffer(provider, monkeypatch):assert provider._sync_thread is Noneassert provider._write_thread is Noneassert provider._prefetch_thread is None- # Explicit memory write went through.- assert len(provider._client.add_calls) == 1- # Buffered turn was flushed as a partial full-session ingest.- assert len(provider._client.ingest_calls) == 1- payload = provider._client.ingest_calls[0]- assert payload["session_id"] == "session-1"- assert payload["metadata"]["partial"] is True- assert payload["metadata"]["type"] == "full_session"+ # Explicit memory write and the retried turn both went through.+ assert len(provider._client.add_calls) == 2+ flushed = next(c for c in provider._client.add_calls if c.get("custom_id") == _capture_custom_id("session-1"))+ assert provider._pending_turns == []def test_store_tool_returns_saved_payload(provider):@@ -297,7 +344,7 @@ def test_base_url_defaults_to_cloud(monkeypatch, tmp_path):def test_client_passes_custom_base_url_to_sdk(monkeypatch):- """SDK operations and raw conversation ingest share one normalized base URL."""+ """SDK client receives the normalized base URL."""import sysimport types@@ -325,41 +372,6 @@ def test_client_passes_custom_base_url_to_sdk(monkeypatch):assert captured["base_url"] == "http://localhost:6767"- ("base_url", "expected_url"),- [- ("https://api.supermemory.ai", "https://api.supermemory.ai/v4/conversations"),- ("http://localhost:6767", "http://localhost:6767/v4/conversations"),- ],-)-def test_ingest_conversation_uses_client_base_url(monkeypatch, base_url, expected_url):- """Raw conversation ingest follows the same endpoint as SDK operations."""- from plugins.memory.supermemory import _SupermemoryClient-- client = _SupermemoryClient.__new__(_SupermemoryClient)- client._api_key = "test-key"- client._container_tag = "hermes"- client._timeout = 1.0- client._base_url = base_url-- captured = {}-- class _FakeResponse:- def __enter__(self):- return self-- def __exit__(self, *args):- return False-- def fake_urlopen(req, timeout=None):- captured["url"] = req.full_url- return _FakeResponse()-- monkeypatch.setattr("urllib.request.urlopen", fake_urlopen)- client.ingest_conversation("s1", [{"role": "user", "content": "hello there"}])- assert captured["url"] == expected_url--# -- Multi-container tests ----------------------------------------------------diff --git a/website/docs/user-guide/features/memory-providers.md b/website/docs/user-guide/features/memory-providers.mdindex bbd5451519a..807d4c4334b 100644--- a/website/docs/user-guide/features/memory-providers.md+++ b/website/docs/user-guide/features/memory-providers.md@@ -567,7 +567,7 @@ hermes config set memory.provider byterover### Supermemory-Semantic long-term memory with profile recall, semantic search, explicit memory tools, and session-end conversation ingest via the Supermemory graph API.+Semantic long-term memory with profile recall, semantic search, explicit memory tools, and per-turn conversation capture (one document per session per 4-hour window).| | ||---|---|diff --git a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/memory-providers.md b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/memory-providers.mdindex 2d7f762ff5c..638781cdf01 100644--- a/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/memory-providers.md+++ b/website/i18n/zh-Hans/docusaurus-plugin-content-docs/current/user-guide/features/memory-providers.md@@ -462,7 +462,7 @@ hermes config set memory.provider byterover### Supermemory-语义长期记忆,具备 profile 召回、语义搜索、显式记忆工具,以及通过 Supermemory graph API 进行会话结束时的对话导入。+语义长期记忆,具备 profile 召回、语义搜索、显式记忆工具,以及逐轮对话捕获(每个会话每 4 小时一个文档)。| | ||---|---|