Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 013718c817 |
@@ -12,7 +12,7 @@
|
||||
"name": "mem0",
|
||||
"source": "./integrations/mem0-plugin",
|
||||
"description": "Mem0 memory layer for AI applications. Add persistent memory, personalization, and semantic search to Claude workflows.",
|
||||
"version": "0.2.11"
|
||||
"version": "0.2.10"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
"name": "mem0",
|
||||
"source": "./integrations/mem0-plugin",
|
||||
"description": "Mem0 memory layer for AI applications. Add persistent memory, personalization, and semantic search.",
|
||||
"version": "0.2.11"
|
||||
"version": "0.2.10"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -189,5 +189,3 @@ eval/
|
||||
qdrant_storage/
|
||||
.crossnote
|
||||
testing.ipynb
|
||||
.weave/
|
||||
|
||||
|
||||
@@ -5,15 +5,6 @@ All notable changes to `@mem0/cli` are documented here.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.2.9] — 2026-06-19
|
||||
|
||||
### Security
|
||||
|
||||
- Telemetry no longer passes the Mem0 API key to its child process via
|
||||
command-line arguments. The context is now sent over stdin, so the key is no
|
||||
longer visible in the process list (`ps`, `/proc/<pid>/cmdline`, Activity
|
||||
Monitor). Fixes #4862.
|
||||
|
||||
## [0.2.8] — 2026-06-01
|
||||
|
||||
### Security
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@mem0/cli",
|
||||
"version": "0.2.9",
|
||||
"version": "0.2.8",
|
||||
"description": "The official CLI for mem0 — the memory layer for AI agents",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
|
||||
@@ -145,11 +145,11 @@ export function captureEvent(
|
||||
anonDistinctIdToAlias: anonIdToAlias,
|
||||
};
|
||||
|
||||
const child = spawn(process.execPath, [SENDER_SCRIPT], {
|
||||
detached: true,
|
||||
stdio: ["pipe", "ignore", "ignore"],
|
||||
});
|
||||
child.stdin?.end(JSON.stringify(context));
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[SENDER_SCRIPT, JSON.stringify(context)],
|
||||
{ detached: true, stdio: "ignore" },
|
||||
);
|
||||
child.unref();
|
||||
} catch {
|
||||
/* silently swallow */
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
/**
|
||||
* Standalone telemetry sender — runs as a detached child process.
|
||||
*
|
||||
* Usage: node telemetry-sender.cjs (JSON context is read from stdin; a single
|
||||
* argv argument is still accepted as a legacy fallback)
|
||||
* Usage: node telemetry-sender.cjs '<json context>'
|
||||
*
|
||||
* This script is spawned by telemetry.captureEvent() and runs independently
|
||||
* of the parent CLI process. It:
|
||||
@@ -20,31 +19,6 @@
|
||||
const https = require("https");
|
||||
const fs = require("fs");
|
||||
|
||||
function loadContext() {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (process.argv[2]) {
|
||||
try {
|
||||
resolve(JSON.parse(process.argv[2]));
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
let data = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => (data += chunk));
|
||||
process.stdin.on("end", () => {
|
||||
try {
|
||||
resolve(JSON.parse(data));
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
});
|
||||
process.stdin.on("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
function httpsRequest(url, method, headers, body) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const u = new URL(url);
|
||||
@@ -134,7 +108,7 @@ async function sendIdentifyEvent(ctx, payload, anonId) {
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const ctx = await loadContext();
|
||||
const ctx = JSON.parse(process.argv[2]);
|
||||
const payload = ctx.payload;
|
||||
|
||||
if (ctx.needsEmail && ctx.mem0ApiKey) {
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mockLoadConfig = vi.fn();
|
||||
const mockSaveConfig = vi.fn();
|
||||
const mockSpawn = vi.fn();
|
||||
|
||||
vi.mock("../src/config.js", () => ({
|
||||
CONFIG_FILE: "/tmp/mem0-config.json",
|
||||
loadConfig: mockLoadConfig,
|
||||
saveConfig: mockSaveConfig,
|
||||
}));
|
||||
|
||||
vi.mock("node:child_process", () => ({
|
||||
spawn: mockSpawn,
|
||||
}));
|
||||
|
||||
describe("captureEvent", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
mockLoadConfig.mockReset();
|
||||
mockSaveConfig.mockReset();
|
||||
mockSpawn.mockReset();
|
||||
delete process.env.MEM0_TELEMETRY;
|
||||
});
|
||||
|
||||
it("pipes the telemetry context through stdin instead of argv", async () => {
|
||||
mockLoadConfig.mockReturnValue({
|
||||
platform: {
|
||||
apiKey: "m0-node-secret",
|
||||
baseUrl: "https://api.mem0.ai",
|
||||
userEmail: "",
|
||||
},
|
||||
telemetry: {
|
||||
anonymousId: "cli-anon-node",
|
||||
},
|
||||
});
|
||||
|
||||
const stdin = { end: vi.fn() };
|
||||
const child = { stdin, unref: vi.fn() };
|
||||
mockSpawn.mockReturnValue(child);
|
||||
|
||||
const { captureEvent } = await import("../src/telemetry.js");
|
||||
captureEvent("node_test_event", { case: "stdin-secret" });
|
||||
|
||||
expect(mockSpawn).toHaveBeenCalledTimes(1);
|
||||
const [execPath, args, options] = mockSpawn.mock.calls[0];
|
||||
expect(execPath).toBe(process.execPath);
|
||||
expect(args).toHaveLength(1);
|
||||
expect(String(args[0])).toContain("telemetry-sender.cjs");
|
||||
expect(JSON.stringify(args)).not.toContain("m0-node-secret");
|
||||
expect(options).toMatchObject({ detached: true, stdio: ["pipe", "ignore", "ignore"] });
|
||||
|
||||
expect(stdin.end).toHaveBeenCalledTimes(1);
|
||||
const payload = JSON.parse(stdin.end.mock.calls[0][0]);
|
||||
expect(payload.mem0ApiKey).toBe("m0-node-secret");
|
||||
expect(payload.payload.event).toBe("node_test_event");
|
||||
expect(child.unref).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -5,19 +5,6 @@ All notable changes to `mem0-cli` (Python) are documented here.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.2.8] — 2026-06-19
|
||||
|
||||
### Security
|
||||
|
||||
- Telemetry no longer passes the Mem0 API key to its child process via
|
||||
command-line arguments. The context is now sent over stdin, so the key is no
|
||||
longer visible in the process list (`ps`, `/proc/<pid>/cmdline`, Activity
|
||||
Monitor). Fixes #4862.
|
||||
|
||||
### Fixed
|
||||
|
||||
- `__version__` now matches the packaged version (was stale at 0.2.4).
|
||||
|
||||
## [0.2.7] — 2026-05-20
|
||||
|
||||
### Added
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "mem0-cli"
|
||||
version = "0.2.8"
|
||||
version = "0.2.7"
|
||||
description = "The official CLI for mem0 — the memory layer for AI agents"
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0"
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
"""mem0 CLI — the command-line interface for the mem0 memory layer."""
|
||||
|
||||
__version__ = "0.2.8"
|
||||
__version__ = "0.2.4"
|
||||
|
||||
@@ -137,19 +137,12 @@ def capture_event(
|
||||
"anon_distinct_id_to_alias": anon_id_to_alias,
|
||||
}
|
||||
|
||||
child = subprocess.Popen(
|
||||
[sys.executable, "-m", "mem0_cli.telemetry_sender"],
|
||||
stdin=subprocess.PIPE,
|
||||
subprocess.Popen(
|
||||
[sys.executable, "-m", "mem0_cli.telemetry_sender", json.dumps(context)],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
start_new_session=True,
|
||||
close_fds=True,
|
||||
text=True,
|
||||
)
|
||||
if child.stdin:
|
||||
with contextlib.suppress(Exception):
|
||||
child.stdin.write(json.dumps(context))
|
||||
with contextlib.suppress(Exception):
|
||||
child.stdin.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
"""Standalone telemetry sender — runs as a detached subprocess.
|
||||
|
||||
Usage: python -m mem0_cli.telemetry_sender (JSON context is read from stdin;
|
||||
a single argv argument is still accepted as a legacy fallback)
|
||||
Usage: python -m mem0_cli.telemetry_sender '<json context>'
|
||||
|
||||
This module is spawned by telemetry.capture_event() and runs independently
|
||||
of the parent CLI process. It:
|
||||
@@ -21,18 +20,8 @@ import sys
|
||||
import urllib.request
|
||||
|
||||
|
||||
def _load_context() -> dict:
|
||||
"""Load telemetry context from stdin, falling back to argv for compatibility."""
|
||||
raw = ""
|
||||
if not sys.stdin.isatty():
|
||||
raw = sys.stdin.read().strip()
|
||||
if not raw and len(sys.argv) > 1:
|
||||
raw = sys.argv[1]
|
||||
return json.loads(raw)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ctx = _load_context()
|
||||
ctx = json.loads(sys.argv[1])
|
||||
payload = ctx["payload"]
|
||||
|
||||
if ctx.get("needs_email") and ctx.get("mem0_api_key"):
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
"""Tests for telemetry subprocess secret handling."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from mem0_cli.config import Mem0Config, save_config
|
||||
from mem0_cli.telemetry import capture_event
|
||||
from mem0_cli.telemetry_sender import _load_context
|
||||
|
||||
|
||||
class _CaptureStdin:
|
||||
def __init__(self):
|
||||
self.buffer = ""
|
||||
self.closed = False
|
||||
|
||||
def write(self, value: str) -> None:
|
||||
self.buffer += value
|
||||
|
||||
def close(self) -> None:
|
||||
self.closed = True
|
||||
|
||||
|
||||
class _DummyProcess:
|
||||
def __init__(self):
|
||||
self.stdin = _CaptureStdin()
|
||||
|
||||
|
||||
def test_capture_event_writes_context_to_stdin_not_argv(isolate_config, monkeypatch):
|
||||
config = Mem0Config()
|
||||
config.platform.api_key = "m0-test-secret"
|
||||
config.telemetry.anonymous_id = "cli-anon-test"
|
||||
save_config(config)
|
||||
|
||||
captured: dict[str, object] = {}
|
||||
proc = _DummyProcess()
|
||||
|
||||
def fake_popen(args, **kwargs):
|
||||
captured["args"] = args
|
||||
captured["kwargs"] = kwargs
|
||||
return proc
|
||||
|
||||
monkeypatch.setattr("mem0_cli.telemetry.subprocess.Popen", fake_popen)
|
||||
|
||||
capture_event("unit_test_event", {"case": "stdin-secret"})
|
||||
|
||||
argv = captured["args"]
|
||||
assert argv == [sys.executable, "-m", "mem0_cli.telemetry_sender"]
|
||||
assert all("m0-test-secret" not in arg for arg in argv)
|
||||
|
||||
kwargs = captured["kwargs"]
|
||||
assert kwargs["stdin"] == subprocess.PIPE
|
||||
assert kwargs["text"] is True
|
||||
|
||||
ctx = json.loads(proc.stdin.buffer)
|
||||
assert ctx["mem0_api_key"] == "m0-test-secret"
|
||||
assert ctx["payload"]["event"] == "unit_test_event"
|
||||
|
||||
assert proc.stdin.closed
|
||||
|
||||
|
||||
def test_load_context_reads_from_stdin(monkeypatch):
|
||||
monkeypatch.setattr("sys.argv", ["telemetry_sender"])
|
||||
monkeypatch.setattr("sys.stdin", io.StringIO('{"payload": {"event": "stdin"}}'))
|
||||
|
||||
ctx = _load_context()
|
||||
|
||||
assert ctx["payload"]["event"] == "stdin"
|
||||
|
||||
|
||||
def test_load_context_falls_back_to_argv(monkeypatch):
|
||||
monkeypatch.setattr("sys.argv", ["telemetry_sender", '{"payload": {"event": "argv"}}'])
|
||||
monkeypatch.setattr("sys.stdin", io.StringIO(""))
|
||||
|
||||
ctx = _load_context()
|
||||
|
||||
assert ctx["payload"]["event"] == "argv"
|
||||
@@ -4,4 +4,4 @@ description: "Submit an export job to create a structured memory export using a
|
||||
openapi: post /v1/exports/
|
||||
---
|
||||
|
||||
Submit a job to create a structured export of memories using a customizable Pydantic schema. This process may take some time to complete, especially if you're exporting a large number of memories. You can tailor the export by applying various filters (e.g., `user_id`, `agent_id`, `app_id`, or `run_id`) and by modifying the Pydantic schema to ensure the final data matches your exact needs.
|
||||
Submit a job to create a structured export of memories using a customizable Pydantic schema. This process may take some time to complete, especially if you're exporting a large number of memories. You can tailor the export by applying various filters (e.g., `user_id`, `agent_id`, `run_id`, or `session_id`) and by modifying the Pydantic schema to ensure the final data matches your exact needs.
|
||||
|
||||
@@ -4,4 +4,4 @@ description: "Retrieve the latest structured memory export after submitting an e
|
||||
openapi: post /v1/exports/get
|
||||
---
|
||||
|
||||
Retrieve the latest structured memory export after submitting an export job. You can filter the export by `user_id`, `agent_id`, `app_id`, `run_id`, `created_at`, or `updated_at` to get the most recent export matching your filters.
|
||||
Retrieve the latest structured memory export after submitting an export job. You can filter the export by `user_id`, `run_id`, `session_id`, or `app_id` to get the most recent export matching your filters.
|
||||
@@ -20,11 +20,11 @@ The `filters` object supports complex logical operations (AND, OR, NOT) and comp
|
||||
|
||||
### Search parameter defaults
|
||||
|
||||
| Parameter | Default |
|
||||
| --- | --- |
|
||||
| `top_k` | `10` (range 1–1000) |
|
||||
| `threshold` | `0.1` (pass `0.0` to disable) |
|
||||
| `rerank` | `false` (pass `true` to enable) |
|
||||
| Parameter | V1/V2 | V3 |
|
||||
| --- | --- | --- |
|
||||
| `top_k` | Supported (default 10) | Supported (1-1000, default 10) |
|
||||
| `threshold` | No default | Default `0.1` (pass `0.0` to disable) |
|
||||
| `rerank` | Default `true` | Default `false` (pass `true` to enable) |
|
||||
|
||||
<CodeGroup>
|
||||
```python Platform API Example
|
||||
|
||||
@@ -14,7 +14,7 @@ Organizations and projects are **optional** features. You can use Mem0 without t
|
||||
|
||||
## Key Capabilities
|
||||
|
||||
- **Multi-org/project Support**: Organization and project are resolved automatically from your API key via `/v1/ping/` — no org or project params are accepted by `MemoryClient.__init__`. Use a project-specific API key to target a particular project.
|
||||
- **Multi-org/project Support**: Specify organization and project when initializing the Mem0 client to attribute API usage appropriately
|
||||
- **Member Management**: Control access to data through organization and project membership
|
||||
- **Access Control**: Only members can access memories and data within their organization/project scope
|
||||
- **Team Isolation**: Maintain data separation between different teams and projects for secure collaboration
|
||||
@@ -79,7 +79,7 @@ new_project = client.project.create(
|
||||
|
||||
### Update Project Settings
|
||||
|
||||
Modify project configuration including custom instructions, categories, language preferences, retrieval criteria, and memory decay:
|
||||
Modify project configuration including custom instructions, categories, and language preferences:
|
||||
|
||||
```python
|
||||
# Update project with custom categories
|
||||
@@ -98,17 +98,6 @@ client.project.update(
|
||||
# Use the input language for memory storage and retrieval
|
||||
client.project.update(multilingual=True)
|
||||
|
||||
# Set retrieval criteria to control which memories are surfaced in search
|
||||
client.project.update(
|
||||
retrieval_criteria=[
|
||||
{"name": "relevance", "description": "How directly relevant this memory is to the current topic or user query", "weight": 3},
|
||||
{"name": "access_frequency", "description": "How often this memory has been accessed or surfaced recently", "weight": 1}
|
||||
]
|
||||
)
|
||||
|
||||
# Enable Memory Decay (boosts recently-accessed memories at search time)
|
||||
client.project.update(decay=True)
|
||||
|
||||
# Update multiple settings at once
|
||||
client.project.update(
|
||||
custom_instructions="...",
|
||||
@@ -120,34 +109,6 @@ client.project.update(
|
||||
)
|
||||
```
|
||||
|
||||
#### Set Retrieval Criteria
|
||||
|
||||
`retrieval_criteria` is a per-project list of dictionaries (`List[Dict]`) that shapes how memories are ranked and filtered during search. Each dictionary has three fields: `name` (identifier), `description` (interpreted by the LLM to score each memory), and `weight` (relative influence on the final score). Use this to focus retrieval on intent-aligned or signal-specific memories:
|
||||
|
||||
```python
|
||||
client.project.update(
|
||||
retrieval_criteria=[
|
||||
{
|
||||
"name": "joy",
|
||||
"description": "Measure the intensity of positive emotions such as happiness, excitement, or amusement expressed in the memory. A higher score reflects greater joy.",
|
||||
"weight": 3
|
||||
},
|
||||
{
|
||||
"name": "curiosity",
|
||||
"description": "Assess the extent to which the memory reflects inquisitiveness or interest in exploring new information. A higher score reflects stronger curiosity.",
|
||||
"weight": 2
|
||||
},
|
||||
{
|
||||
"name": "access_frequency",
|
||||
"description": "How often this memory has been accessed or surfaced recently.",
|
||||
"weight": 1
|
||||
}
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
Pass an empty list to clear all criteria and restore default retrieval behaviour.
|
||||
|
||||
#### Toggle Memory Decay
|
||||
|
||||
`decay` is a per-project boolean that turns on [Memory Decay](/platform/features/memory-decay) — a search-time ranking bias that reinforces recently-accessed memories and gently dampens stale ones. The flag is `false` by default; set it via the same project-update endpoint:
|
||||
|
||||
@@ -46,9 +46,9 @@ Ground-up rewrite of the memory pipeline with 20+ point benchmark improvements:
|
||||
- **~3-4x fewer tokens** — Under 7K tokens per retrieval vs 25K+ for full-context approaches
|
||||
- **ADD-only extraction** — Memories accumulate; nothing is overwritten or deleted
|
||||
- **Hybrid retrieval** — Semantic + BM25 keyword + entity boost, scored in parallel
|
||||
- **Graph memory (built-in)**: entities extracted, embedded, and linked across memories, with no external graph store required
|
||||
- **Entity linking** — Entities extracted, embedded, and linked across memories
|
||||
|
||||
Breaking changes: external graph stores removed from OSS (replaced by built-in graph memory), `search()` defaults changed, deprecated params removed. See [migration guide](/migration/oss-v2-to-v3).
|
||||
Breaking changes: Graph memory removed from OSS, `search()` defaults changed, deprecated params removed. See [migration guide](/migration/oss-v2-to-v3).
|
||||
|
||||
</Update>
|
||||
|
||||
|
||||
@@ -25,7 +25,7 @@ mode: "wide"
|
||||
<Update label="2026-04-16" description="">
|
||||
|
||||
**Improvements:**
|
||||
- **UI:** Removed the legacy external-graph-store visualization tab, page, and its references from dashboard, sidebar, project settings, playground, and billing
|
||||
- **UI:** Removed Graph Memory tab, page, and all references from dashboard, sidebar, project settings, playground, and billing
|
||||
|
||||
</Update>
|
||||
|
||||
|
||||
+3
-134
@@ -7,100 +7,6 @@ mode: "wide"
|
||||
<Tabs>
|
||||
<Tab title="Python">
|
||||
|
||||
<Update label="2026-06-24" description="v2.0.9">
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Memory (OSS):** Improve entity extraction precision by avoiding sentence-start common noun noise, preserving useful topic phrases, and exact-deduplicating entity links before semantic matching ([#5829](https://github.com/mem0ai/mem0/pull/5829))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-06-24" description="v2.0.8">
|
||||
|
||||
**New Features:**
|
||||
- **Embeddings:** Add native `embed_batch` to five embedders — LM Studio, Together, HuggingFace, Vertex AI, and Google GenAI — for batched embedding requests ([#5609](https://github.com/mem0ai/mem0/pull/5609))
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Core:** Guard against malformed `image_url` entries in `parse_vision_messages` to prevent crashes ([#5631](https://github.com/mem0ai/mem0/pull/5631))
|
||||
- **Core:** Return `attributed_to` from `get()`, `get_all()`, and `search()` ([#5629](https://github.com/mem0ai/mem0/pull/5629))
|
||||
- **Core:** Fix `reset()` only dropping the history table and leaving stale messages behind ([#5541](https://github.com/mem0ai/mem0/pull/5541))
|
||||
- **Core:** Guard against an entity `embed_batch` count mismatch in the v3 add pipeline ([#5604](https://github.com/mem0ai/mem0/pull/5604))
|
||||
- **Core:** Fix an async `delete_all` race condition that corrupted the entity store's `linked_memory_ids` ([#5553](https://github.com/mem0ai/mem0/pull/5553))
|
||||
- **LLMs:** Skip the JSON `response_format` for Groq compound models that reject it ([#5513](https://github.com/mem0ai/mem0/pull/5513))
|
||||
- **LLMs:** Preserve reasoning fields during base-to-provider config conversion ([#5638](https://github.com/mem0ai/mem0/pull/5638))
|
||||
- **LLMs:** Pass the configured `anthropic_base_url` to the Anthropic client ([#5626](https://github.com/mem0ai/mem0/pull/5626))
|
||||
- **LLMs:** Stop the Azure provider from mutating and corrupting caller messages during content rewrite ([#5731](https://github.com/mem0ai/mem0/pull/5731))
|
||||
- **LLMs & Embeddings:** Repair HTTP proxy support for `httpx>=0.28` and preserve `proxies` in `LlmFactory` ([#5447](https://github.com/mem0ai/mem0/pull/5447))
|
||||
- **Embeddings:** Forward `embedding_dims` to Titan V2 in the AWS Bedrock embedder ([#5671](https://github.com/mem0ai/mem0/pull/5671))
|
||||
- **Rerankers:** Log reranking failures instead of swallowing them silently ([#5717](https://github.com/mem0ai/mem0/pull/5717))
|
||||
- **Rerankers:** Clamp out-of-range LLM scores instead of mis-parsing them ([#5635](https://github.com/mem0ai/mem0/pull/5635))
|
||||
- **Rerankers:** Export all five rerankers from the package root ([#5636](https://github.com/mem0ai/mem0/pull/5636))
|
||||
- **Vector Stores:** Point the FastEmbed-missing warning at `mem0ai[extras]` ([#5622](https://github.com/mem0ai/mem0/pull/5622))
|
||||
- **Vector Stores:** Preserve empty Azure AI Search update values ([#5524](https://github.com/mem0ai/mem0/pull/5524))
|
||||
- **Vector Stores:** Add an `auto_refresh` option for OpenSearch Serverless compatibility ([#3893](https://github.com/mem0ai/mem0/pull/3893))
|
||||
- **Vector Stores:** Wrap a scalar `vector_id` in a list for Chroma `delete()` ([#5703](https://github.com/mem0ai/mem0/pull/5703))
|
||||
- **Vector Stores:** Wrap Chroma `update()` ids, embeddings, and metadatas in lists ([#5757](https://github.com/mem0ai/mem0/pull/5757))
|
||||
- **Vector Stores:** Wrap a scalar `vector_id` in a list for Milvus `delete()` ([#5704](https://github.com/mem0ai/mem0/pull/5704))
|
||||
- **Vector Stores:** Map all comparison operators in the Pinecone `_create_filter()` ([#5707](https://github.com/mem0ai/mem0/pull/5707))
|
||||
- **Vector Stores:** Return `None` instead of `{}` from Chroma `_generate_where_clause` for empty filters ([#5713](https://github.com/mem0ai/mem0/pull/5713))
|
||||
- **Vector Stores:** Return `[[]]` from the OpenSearch `list()` error path to honor the `list()` contract ([#5727](https://github.com/mem0ai/mem0/pull/5727))
|
||||
- **Vector Stores:** Return `[[]]` from the Pinecone `list()` error path instead of a dict ([#5706](https://github.com/mem0ai/mem0/pull/5706))
|
||||
- **Vector Stores:** Return `[[]]` for an uninitialized FAISS index to honor the `list()` contract ([#5725](https://github.com/mem0ai/mem0/pull/5725))
|
||||
- **Vector Stores:** Wrap the MongoDB `list()` return in an outer list to match the interface contract ([#5729](https://github.com/mem0ai/mem0/pull/5729))
|
||||
- **Vector Stores:** Deep-copy Redis `DEFAULT_FIELDS` so instances keep distinct dims ([#5633](https://github.com/mem0ai/mem0/pull/5633))
|
||||
- **Vector Stores:** Pass the required `vectors` arg in Vertex AI `list()` and similarity search ([#5627](https://github.com/mem0ai/mem0/pull/5627))
|
||||
- **Vector Stores:** Return `None` from Redis `get()` for missing IDs ([#5625](https://github.com/mem0ai/mem0/pull/5625))
|
||||
- **Vector Stores:** Drop a stray `print` in Weaviate `list_cols` ([#5637](https://github.com/mem0ai/mem0/pull/5637))
|
||||
- **Graph:** Keep distinct entities that share a substring prefix ([#5630](https://github.com/mem0ai/mem0/pull/5630))
|
||||
- **Client:** Check the HTTP status before parsing the ping response in `_validate_api_key` ([#5639](https://github.com/mem0ai/mem0/pull/5639))
|
||||
- **Server:** Fetch filtered dashboard memories beyond the default page ([#5753](https://github.com/mem0ai/mem0/pull/5753))
|
||||
- **Server:** Return 404/400 instead of 502 for not-found and invalid input ([#5634](https://github.com/mem0ai/mem0/pull/5634))
|
||||
- **Server:** Return 404 instead of 500 for a malformed API key id on revoke ([#5640](https://github.com/mem0ai/mem0/pull/5640))
|
||||
- **Server:** Use `127.0.0.1` in the dashboard healthcheck to avoid IPv6 localhost resolution ([#5612](https://github.com/mem0ai/mem0/pull/5612))
|
||||
|
||||
**Improvements:**
|
||||
- **Vector Stores:** Batch BM25 sparse encoding in Qdrant insert ([#5592](https://github.com/mem0ai/mem0/pull/5592))
|
||||
|
||||
**Security:**
|
||||
- **Vector Stores:** Sanitize Milvus and Baidu filter values to prevent expression injection ([#5746](https://github.com/mem0ai/mem0/pull/5746))
|
||||
- **Vector Stores:** Reject dict filter values in MongoDB to prevent NoSQL operator injection ([#5748](https://github.com/mem0ai/mem0/pull/5748))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-06-17" description="v2.0.7">
|
||||
|
||||
**New Features:**
|
||||
- **LLMs:** Add Gemini via Vertex AI as LLM provider ([#4030](https://github.com/mem0ai/mem0/pull/4030))
|
||||
- **Embeddings:** Add native `embed_batch` to `OllamaEmbedding` for batched embedding requests ([#5415](https://github.com/mem0ai/mem0/pull/5415))
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Core:** Fix `api_error_handler` silently dropping return values from async methods ([#5540](https://github.com/mem0ai/mem0/pull/5540))
|
||||
- **Core:** Fix `AsyncMemory.reset()` not resetting the entity store ([#5535](https://github.com/mem0ai/mem0/pull/5535))
|
||||
- **Core:** Fix `async delete_all` aborting on first error, leaving partial deletion ([#5529](https://github.com/mem0ai/mem0/pull/5529))
|
||||
- **Core:** Skip messages without a `content` key in message parsers to prevent `KeyError` crashes ([#5575](https://github.com/mem0ai/mem0/pull/5575))
|
||||
- **Core:** Preserve custom metadata fields during memory update ([#5480](https://github.com/mem0ai/mem0/pull/5480))
|
||||
- **LLMs:** Fix Anthropic `tool_choice` format and tool response parsing ([#5537](https://github.com/mem0ai/mem0/pull/5537))
|
||||
- **LLMs:** Fix Ollama `json` format mutating the caller's messages list in-place ([#5539](https://github.com/mem0ai/mem0/pull/5539))
|
||||
- **LLMs:** Omit `None` config values from Gemini `GenerateContentConfig` to prevent validation errors ([#5528](https://github.com/mem0ai/mem0/pull/5528))
|
||||
- **LLMs:** Honor reasoning-model params in `AzureOpenAIStructuredLLM` ([#5548](https://github.com/mem0ai/mem0/pull/5548))
|
||||
- **LLMs:** Honor reasoning-model params in `OpenAIStructuredLLM` ([#5458](https://github.com/mem0ai/mem0/pull/5458))
|
||||
- **LLMs:** Send `max_completion_tokens` for the GPT-5 family across all providers ([#5547](https://github.com/mem0ai/mem0/pull/5547))
|
||||
- **LLMs:** Accept and forward `**kwargs` in Together, LangChain, and Sarvam providers ([#5556](https://github.com/mem0ai/mem0/pull/5556))
|
||||
- **LLMs:** Fix Bedrock AI21 response parse default using `dict` literal instead of `set` ([#5527](https://github.com/mem0ai/mem0/pull/5527))
|
||||
- **LLMs:** Fix LiteLLM function-calling check blocking all calls on non-tool models ([#5536](https://github.com/mem0ai/mem0/pull/5536))
|
||||
- **LLMs:** Fix HuggingFace provider using `self.config` instead of raw `config` parameter ([#5538](https://github.com/mem0ai/mem0/pull/5538))
|
||||
- **Embeddings:** Honor `aws_session_token` in AWS Bedrock embeddings ([#5566](https://github.com/mem0ai/mem0/pull/5566))
|
||||
- **Rerankers:** Respect `config.top_k` in Cohere and ZeroEntropy fallback paths ([#5560](https://github.com/mem0ai/mem0/pull/5560))
|
||||
- **Vector Stores:** Fix FAISS filtered search dropping over-fetched candidates before filtering ([#5453](https://github.com/mem0ai/mem0/pull/5453))
|
||||
- **Vector Stores:** Fix Weaviate `reset()` crashing with missing `vector_size` argument ([#5531](https://github.com/mem0ai/mem0/pull/5531))
|
||||
- **Vector Stores:** Pass embedding dims in Weaviate `reset()` to avoid re-init crash ([#5570](https://github.com/mem0ai/mem0/pull/5570))
|
||||
- **Vector Stores:** Fix MongoDB `reset()` passing wrong argument to `create_col()` ([#5532](https://github.com/mem0ai/mem0/pull/5532))
|
||||
- **Vector Stores:** Fix Pinecone hybrid search crashing when `filters` is `None` ([#5533](https://github.com/mem0ai/mem0/pull/5533))
|
||||
- **Vector Stores:** Fix Redis crashing on empty or `None` filters in `search()` and `list()` ([#5446](https://github.com/mem0ai/mem0/pull/5446))
|
||||
- **Vector Stores:** Return `None` from `get()` for missing IDs in Milvus, Weaviate, and Supabase ([#5562](https://github.com/mem0ai/mem0/pull/5562))
|
||||
- **Vector Stores:** Return `None` from ChromaDB `get()` for missing IDs ([#5561](https://github.com/mem0ai/mem0/pull/5561))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-06-13" description="v2.0.6">
|
||||
|
||||
**New Features:**
|
||||
@@ -208,8 +114,8 @@ mode: "wide"
|
||||
- **`messages` in `Memory.add()` rejects invalid types:** Passing `None` or non-`(str | dict | list)` values raises `Mem0ValidationError` (`error_code="VALIDATION_003"`) ([#4843](https://github.com/mem0ai/mem0/pull/4843))
|
||||
- **`qdrant-client>=1.12.0` required** — Upgrade from `>=1.9.1` ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **`org_id` and `project_id` removed** — Removed from `MemoryClient` constructor and all method signatures ([#4740](https://github.com/mem0ai/mem0/pull/4740))
|
||||
- **External Graph Store Removed (OSS):** `mem0/memory/graph_memory.py`, `memgraph_memory.py`, `kuzu_memory.py`, `apache_age_memory.py`, and `mem0/graphs/` (Neo4j / Memgraph / Kuzu / Apache AGE / Neptune drivers) deleted, about 4,000 lines. The external graph store integration is no longer part of the OSS SDK; graph drivers (neo4j, memgraph, kuzu, etc.) can be uninstalled. Graph memory now runs natively as built-in entity linking. Remove `enable_graph` and `graph_store` from your config ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **`enable_graph` removed from Client SDK:** Graph memory now runs automatically and no longer needs a flag. Remove `enable_graph` from `MemoryClient.add()` / `search()` / `get_all()` / `update_project()` calls ([#4776](https://github.com/mem0ai/mem0/pull/4776))
|
||||
- **Graph Memory Removed (OSS):** `mem0/memory/graph_memory.py`, `memgraph_memory.py`, `kuzu_memory.py`, `apache_age_memory.py`, and `mem0/graphs/` (Neo4j / Memgraph / Kuzu / Apache AGE / Neptune drivers) deleted — ~4,000 lines. Graph memory is no longer supported in the OSS SDK; graph drivers (neo4j, memgraph, kuzu, etc.) can be uninstalled. Use the Platform API for graph features. Remove `enable_graph` and `graph_store` from your config ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **`enable_graph` removed from Client SDK** — Graph memory is now a project-level setting on the Platform. Remove `enable_graph` from `MemoryClient.add()` / `search()` / `get_all()` / `update_project()` calls ([#4776](https://github.com/mem0ai/mem0/pull/4776))
|
||||
- **`custom_fact_extraction_prompt` renamed to `custom_instructions`** — Update config and memory module references ([#4740](https://github.com/mem0ai/mem0/pull/4740))
|
||||
- **Typed option classes** — Added Pydantic v2 typed classes: `AddMemoryOptions`, `SearchMemoryOptions`, `GetAllMemoryOptions`, `DeleteAllMemoryOptions`, `UpdateMemoryOptions`, `ProjectUpdateOptions` ([#4740](https://github.com/mem0ai/mem0/pull/4740))
|
||||
|
||||
@@ -1070,43 +976,6 @@ See the [OSS v1 to v2 migration guide](https://docs.mem0.ai/migration/oss-v1-to-
|
||||
|
||||
<Tab title="TypeScript">
|
||||
|
||||
<Update label="2026-06-24" description="v3.0.11">
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Memory (OSS):** Align entity extraction with Python by reducing generic entity noise, preserving useful topic phrases, and exact-deduplicating entity links before semantic matching ([#5829](https://github.com/mem0ai/mem0/pull/5829))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-06-24" description="v3.0.10">
|
||||
|
||||
**Bug Fixes:**
|
||||
- **Memory (OSS):** Guard against malformed `image_url` entries in `parseVisionMessages` to prevent crashes ([#5631](https://github.com/mem0ai/mem0/pull/5631))
|
||||
- **Memory (OSS):** Return `attributedTo` from `get()`, `search()`, and `getAll()` ([#5675](https://github.com/mem0ai/mem0/pull/5675))
|
||||
- **Memory (OSS):** Preserve message roles in the extraction input so assistant facts aren't attributed to the user ([#5643](https://github.com/mem0ai/mem0/pull/5643))
|
||||
- **Memory (OSS):** Reject empty or blank messages in `Memory.add()` to prevent hallucinated memories ([#5545](https://github.com/mem0ai/mem0/pull/5545))
|
||||
- **Memory (OSS):** Check `message.role` instead of `content` when detecting system messages ([#3921](https://github.com/mem0ai/mem0/pull/3921))
|
||||
- **LLMs:** Honor the configured `baseURL` in `AnthropicLLM` ([#5740](https://github.com/mem0ai/mem0/pull/5740))
|
||||
- **Client:** Preserve `customCategories` names through key conversion ([#5741](https://github.com/mem0ai/mem0/pull/5741))
|
||||
- **Client:** Prevent hallucinated memories on an empty messages payload ([#5613](https://github.com/mem0ai/mem0/pull/5613))
|
||||
- **Client:** Preserve user metadata keys across the case-conversion round-trip ([#5515](https://github.com/mem0ai/mem0/pull/5515))
|
||||
|
||||
**Security:**
|
||||
- **Dependencies:** Upgrade `form-data` to `>=4.0.6` across pnpm workspaces to remediate CVE-2026-12143 ([#5618](https://github.com/mem0ai/mem0/pull/5618))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-06-17" description="v3.0.9">
|
||||
|
||||
**Bug Fixes:**
|
||||
- **LLMs:** Fix Anthropic `tool_choice` format — was incorrectly sent as a bare string `"auto"` (rejected by the API); now correctly sent as `{ type: "auto" }`. Also fixes tool response parsing: `tool_use` blocks are now parsed into `toolCalls` objects instead of throwing. Updated default model to `claude-sonnet-4-6` and default `max_tokens` to `2000` to match the Python provider. Added `temperature`, `topP`, and `maxTokens` to `LLMConfig` so Anthropic params can be configured ([#5537](https://github.com/mem0ai/mem0/pull/5537))
|
||||
- **Memory (OSS):** Preserve custom metadata fields during `update()` — fields such as `category`, `priority`, and other user-defined keys were previously dropped on update; the existing payload is now spread before applying the new data ([#5480](https://github.com/mem0ai/mem0/pull/5480))
|
||||
- **Client:** Preserve user-defined schema keys in `createMemoryExport` ([#5594](https://github.com/mem0ai/mem0/pull/5594))
|
||||
|
||||
**Security:**
|
||||
- **Dependencies:** Bump `esbuild` to `>=0.28.1` across all npm packages via pnpm overrides to remediate upstream vulnerability ([#5563](https://github.com/mem0ai/mem0/pull/5563))
|
||||
|
||||
</Update>
|
||||
|
||||
<Update label="2026-06-13" description="v3.0.8">
|
||||
|
||||
**New Features:**
|
||||
@@ -1197,7 +1066,7 @@ See the [OSS v1 to v2 migration guide](https://docs.mem0.ai/migration/oss-v1-to-
|
||||
- **Default model:** `gpt-5-mini` is now the default in `OpenAI`, `OpenAIStructured`, and `Azure` LLM providers ([#4829](https://github.com/mem0ai/mem0/pull/4829))
|
||||
|
||||
**Breaking Changes:**
|
||||
- **External Graph Store Removed (OSS):** `graph_memory.ts` (675 lines), `graphs/tools.ts` (267 lines), `graphs/utils.ts` (116 lines), `graphs/configs.ts` (30 lines) deleted. The external graph store integration is no longer part of the OSS SDK; graph memory now runs natively as built-in entity linking ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **Graph Memory Removed (OSS):** `graph_memory.ts` (675 lines), `graphs/tools.ts` (267 lines), `graphs/utils.ts` (116 lines), `graphs/configs.ts` (30 lines) deleted. Graph memory is no longer supported in the OSS SDK — use Platform API for graph features ([#4805](https://github.com/mem0ai/mem0/pull/4805))
|
||||
- **camelCase Parameters (Client SDK):** All user-facing parameters converted from snake_case to camelCase. Mapping is transparent at API boundary via `camelToSnakeKeys()` / `snakeToCamelKeys()` ([#4776](https://github.com/mem0ai/mem0/pull/4776))
|
||||
```typescript
|
||||
// Before
|
||||
|
||||
@@ -7,8 +7,7 @@ To use DeepSeek LLM models, you have to set the `DEEPSEEK_API_KEY` environment v
|
||||
|
||||
## Usage
|
||||
|
||||
<CodeGroup>
|
||||
```python Python
|
||||
```python
|
||||
import os
|
||||
from mem0 import Memory
|
||||
|
||||
@@ -37,32 +36,6 @@ messages = [
|
||||
m.add(messages, user_id="alice", metadata={"category": "movies"})
|
||||
```
|
||||
|
||||
```typescript TypeScript
|
||||
import { Memory } from 'mem0ai/oss';
|
||||
|
||||
const config = {
|
||||
llm: {
|
||||
provider: 'deepseek',
|
||||
config: {
|
||||
apiKey: process.env.DEEPSEEK_API_KEY || '',
|
||||
model: 'deepseek-chat',
|
||||
temperature: 0.2,
|
||||
maxTokens: 2000,
|
||||
top_p: 1.0,
|
||||
},
|
||||
},
|
||||
};
|
||||
const memory = new Memory(config);
|
||||
const messages = [
|
||||
{"role": "user", "content": "I'm planning to watch a movie tonight. Any recommendations?"},
|
||||
{"role": "assistant", "content": "How about thriller movies? They can be quite engaging."},
|
||||
{"role": "user", "content": "I’m not a big fan of thriller movies but I love sci-fi movies."},
|
||||
{"role": "assistant", "content": "Got it! I'll avoid thriller recommendations and suggest sci-fi movies in the future."}
|
||||
];
|
||||
await memory.add(messages, { userId: 'alice', metadata: { category: 'movies' } });
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
You can also configure the API base URL in the config:
|
||||
|
||||
```python
|
||||
|
||||
@@ -56,30 +56,6 @@ config = {
|
||||
}
|
||||
```
|
||||
|
||||
### Configuration Options
|
||||
|
||||
| Parameter | Type | Default | Description |
|
||||
|-----------|------|---------|-------------|
|
||||
| `collection_name` | string | required | Name of the OpenSearch index |
|
||||
| `host` | string | required | OpenSearch endpoint URL |
|
||||
| `port` | int | 9200 | Port number |
|
||||
| `http_auth` | object | None | Authentication credentials (e.g., AWSV4SignerAuth) |
|
||||
| `embedding_model_dims` | int | 1536 | Dimension of embedding vectors |
|
||||
| `use_ssl` | bool | False | Enable SSL/TLS connection |
|
||||
| `verify_certs` | bool | False | Verify SSL certificates |
|
||||
| `auto_refresh` | bool | False | Automatically refresh index after insert. OpenSearch refreshes every ~1 second by default, so this is rarely needed. |
|
||||
|
||||
<Note>
|
||||
The defaults above match a local OpenSearch instance. The AWS OpenSearch Serverless
|
||||
example earlier on this page intentionally overrides them with `port=443`, `use_ssl=True`,
|
||||
and `verify_certs=True`, which are required when connecting to a Serverless collection.
|
||||
</Note>
|
||||
|
||||
<Note>
|
||||
For **AWS OpenSearch Serverless**, keep `auto_refresh=False` (the default).
|
||||
The `indices.refresh()` API is not supported on Serverless collections.
|
||||
</Note>
|
||||
|
||||
### Add Memories
|
||||
|
||||
```python
|
||||
|
||||
@@ -17,7 +17,7 @@ Some benchmarks today — particularly smaller ones like LoCoMo and LongMemEval
|
||||
|
||||
## Architecture Overview
|
||||
|
||||
Mem0's memory system operates across two phases, **extraction** (writing) and **retrieval** (reading), with a graph memory layer (entity linking) connecting them.
|
||||
Mem0's memory system operates across two phases — **extraction** (writing) and **retrieval** (reading) — with an entity linking layer connecting them.
|
||||
|
||||
### Memory Extraction (Distillation)
|
||||
|
||||
@@ -27,14 +27,14 @@ When new conversations arrive, the extraction pipeline processes them through fi
|
||||
2. **Context Lookup** — Find related existing memories to avoid duplicates
|
||||
3. **Distill Memories** — Single-pass LLM extraction produces ADD-only facts from input + context
|
||||
4. **Deduplicate + Embed** — Hash-based deduplication, then vectorize new memories
|
||||
5. **Graph Memory (Entity Linking)**: Identify entities (proper nouns, quoted text, compound noun phrases) and link them across memories into a graph
|
||||
5. **Entity Linking** — Identify entities (proper nouns, quoted text, compound noun phrases) and link them across memories
|
||||
|
||||
Memories are distributed across three storage layers, each tuned for a specific retrieval pattern:
|
||||
|
||||
| Store | Contents | Purpose |
|
||||
|---|---|---|
|
||||
| **Vector Database** | Memory text, embeddings, metadata (timestamps, hash, categories, attributed_to) | Primary fact storage + semantic retrieval |
|
||||
| **Graph / Entity Store** | Entities + embeddings + linked memory IDs | Graph connections across memories + entity-based retrieval boost |
|
||||
| **Entity Store** | Entities + embeddings + linked memory IDs | Entity-based retrieval boost |
|
||||
| **SQL Database** | History log (ADD events) + rolling message window | Audit trail + extraction dedup context |
|
||||
|
||||
<Info>
|
||||
@@ -76,7 +76,7 @@ The combined score outperformed every individual signal across every category te
|
||||
|
||||
*Mean tokens: 6,956*
|
||||
|
||||
The two largest gains are **temporal queries (+29.6)** and **multi-hop reasoning (+23.1)**. Both categories directly test the ADD-only architecture (preserving temporal context) and graph memory / entity linking (connecting facts across memories).
|
||||
The two largest gains are **temporal queries (+29.6)** and **multi-hop reasoning (+23.1)**. Both categories directly test the ADD-only architecture (preserving temporal context) and entity linking (connecting facts across memories).
|
||||
|
||||
### LongMemEval
|
||||
|
||||
@@ -345,7 +345,7 @@ When evaluating memory systems, keep these considerations in mind:
|
||||
<Card title="Research" icon="flask" href="https://mem0.ai/research">
|
||||
Published research papers and technical reports
|
||||
</Card>
|
||||
<Card title="Blog Post" icon="newspaper" href="https://mem0.ai/blog/the-token-efficient-memory-algorithm-now-has-temporal-reasoning">
|
||||
<Card title="Blog Post" icon="newspaper" href="https://mem0.ai/blog/new-algorithm">
|
||||
Detailed writeup of the new algorithm design and results
|
||||
</Card>
|
||||
<Card title="Platform Migration" icon="arrow-right" href="/migration/platform-v2-to-v3">
|
||||
|
||||
@@ -21,7 +21,7 @@ Adding memory is how Mem0 captures useful details from a conversation so your ag
|
||||
- **Messages** – The ordered list of user/assistant turns you send to `add`.
|
||||
- **Infer** – Controls whether Mem0 extracts structured memories (`infer=True`, default) or stores raw messages.
|
||||
- **Metadata** – Optional filters (e.g., `{"category": "movie_recommendations"}`) that improve retrieval later.
|
||||
- **User / Session identifiers** – `user_id`, `agent_id`, `app_id`, or `run_id` that scope the memory for future searches.
|
||||
- **User / Session identifiers** – `user_id`, `agent_id`, or `run_id` that scope the memory for future searches.
|
||||
|
||||
## How does it work?
|
||||
|
||||
@@ -30,22 +30,22 @@ Mem0 offers two flows:
|
||||
- **Mem0 Platform** – Fully managed API with dashboard and scaling.
|
||||
- **Mem0 Open Source** – Local SDK that you run in your own environment.
|
||||
|
||||
Both flows take the same payload and add memories through an additive pipeline.
|
||||
Both flows take the same payload and pass it through the same pipeline.
|
||||
|
||||
<Steps>
|
||||
<Step title="Information extraction">
|
||||
Mem0 sends the messages through an LLM that pulls out key facts, decisions, or preferences to remember.
|
||||
</Step>
|
||||
<Step title="Additive storage">
|
||||
New memories are added without overwriting or deleting existing memories.
|
||||
<Step title="Conflict resolution">
|
||||
Existing memories are checked for duplicates or contradictions so the latest truth wins.
|
||||
</Step>
|
||||
<Step title="Retrieval">
|
||||
Future searches rank the most relevant memories for the query.
|
||||
<Step title="Storage">
|
||||
The resulting memories land in managed vector storage so future searches return them quickly.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Warning>
|
||||
When you switch to `infer=False`, Mem0 stores your payload exactly as provided, so duplicates can land. Mixing both modes for the same fact can save it twice.
|
||||
Duplicate protection only runs during that conflict-resolution step when you let Mem0 infer memories (`infer=True`, the default). If you switch to `infer=False`, Mem0 stores your payload exactly as provided, so duplicates will land. Mixing both modes for the same fact will save it twice.
|
||||
</Warning>
|
||||
|
||||
You trigger this pipeline with a single `add` call—no manual orchestration needed.
|
||||
@@ -80,13 +80,13 @@ const messages = [
|
||||
];
|
||||
|
||||
await client.add(messages, {
|
||||
userId: "alice",
|
||||
user_id: "alice",
|
||||
});
|
||||
```
|
||||
</CodeGroup>
|
||||
|
||||
<Info icon="check">
|
||||
Expect a `status: "PENDING"` response with an `event_id`. Poll `GET /v1/event/{event_id}/` to confirm completion.
|
||||
Expect a `memory_id` (or list of IDs) in the response. Check the Mem0 dashboard to confirm the new entry under the correct user.
|
||||
</Info>
|
||||
|
||||
## Add with Mem0 Open Source
|
||||
@@ -138,7 +138,7 @@ const result = memory.add(messages, {
|
||||
</Tip>
|
||||
|
||||
<Warning>
|
||||
If you do choose `infer=False`, keep it consistent. Raw inserts skip inference, so a later `infer=True` call with the same content can create a second memory.
|
||||
If you do choose `infer=False`, keep it consistent. Raw inserts skip conflict resolution, so a later `infer=True` call with the same content will create a second memory instead of updating the first.
|
||||
</Warning>
|
||||
|
||||
## When Should You Add Memory?
|
||||
@@ -167,7 +167,7 @@ For full list of supported fields, required formats, and advanced options, see t
|
||||
|
||||
| Capability | Mem0 Platform | Mem0 OSS |
|
||||
| --- | --- | --- |
|
||||
| Add behavior | ADD-only; memories accumulate | ADD-only; you control storage |
|
||||
| Conflict resolution | Automatic with dashboard visibility | SDK handles merges locally; you control storage |
|
||||
| Rate limits | Managed quotas per workspace | Limited by your hardware and provider APIs |
|
||||
| Dashboard visibility | Yes — inspect memories visually | Inspect via CLI, logs, or custom UI |
|
||||
|
||||
|
||||
+6
-3
@@ -71,7 +71,6 @@
|
||||
"pages": [
|
||||
"platform/features/v2-memory-filters",
|
||||
"platform/features/entity-scoped-memory",
|
||||
"platform/features/graph-memory",
|
||||
"platform/features/async-client",
|
||||
"platform/features/multimodal-support",
|
||||
"platform/features/custom-categories",
|
||||
@@ -441,7 +440,7 @@
|
||||
"integrations/flowise",
|
||||
"integrations/langchain-tools",
|
||||
"integrations/agentops",
|
||||
"integrations/respan",
|
||||
"integrations/keywords",
|
||||
"integrations/raycast"
|
||||
]
|
||||
}
|
||||
@@ -648,6 +647,10 @@
|
||||
"source": "/open-source/features/custom-fact-extraction-prompt",
|
||||
"destination": "/open-source/features/custom-instructions"
|
||||
},
|
||||
{
|
||||
"source": "/platform/features/graph-memory",
|
||||
"destination": "/migration/oss-v2-to-v3"
|
||||
},
|
||||
{
|
||||
"source": "/cookbooks/essentials/choosing-memory-architecture-vector-vs-graph",
|
||||
"destination": "/migration/oss-v2-to-v3"
|
||||
@@ -1022,7 +1025,7 @@
|
||||
},
|
||||
{
|
||||
"source": "/features/graph-memory",
|
||||
"destination": "/platform/features/graph-memory"
|
||||
"destination": "/migration/oss-v2-to-v3"
|
||||
},
|
||||
{
|
||||
"source": "/features/:slug",
|
||||
|
||||
@@ -309,21 +309,19 @@ Here are the available integrations for Mem0:
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="Respan"
|
||||
title="Keywords AI"
|
||||
icon={
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 200 200"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
>
|
||||
<path d="M2.00635 190.234V9.76584H53.3558V29.5101H26.7223V170.562H53.3558V190.234H2.00635Z" fill="currentColor"></path>
|
||||
<path d="M120.692 160.902C116.383 160.902 112.691 159.387 109.612 156.357C106.535 153.327 105.02 149.633 105.067 145.277C105.02 141.016 106.535 137.37 109.612 134.34C112.691 131.309 116.383 129.794 120.692 129.794C124.859 129.794 128.481 131.309 131.559 134.34C134.684 137.37 136.27 141.016 136.317 145.277C136.27 148.166 135.512 150.793 134.045 153.161C132.624 155.528 130.73 157.422 128.362 158.842C126.042 160.216 123.486 160.902 120.692 160.902Z" fill="currentColor"></path>
|
||||
<path d="M197.993 9.76584V190.234H146.643V170.562H173.278V29.5101H146.643V9.76584H197.993Z" fill="currentColor"></path>
|
||||
<path fill-rule="evenodd" clip-rule="evenodd" d="M9.07513 1.1863C9.21663 1.07722 9.39144 1.01009 9.56624 1.01009C9.83261 1.01009 10.0823 1.12756 10.2405 1.33734L15.0101 7.4964V12.4136L16.4335 13.8401C16.7582 14.1673 16.7582 14.7043 16.4335 15.0316C16.1089 15.3588 15.5762 15.3588 15.2515 15.0316L13.3453 13.1016V8.07538L8.92529 2.36944V2.36105C8.64228 2.00024 8.70887 1.4716 9.07513 1.1863ZM18.976 14.4133C18.8344 14.3778 18.7003 14.3042 18.5894 14.1925L16.9163 12.5059C16.7249 12.3129 16.6416 12.0528 16.6749 11.8094V6.88385H16.6499L11.8553 0.691225C11.7282 0.529117 11.6716 0.333133 11.6803 0.140562C11.134 0.0481292 10.5726 0 10 0C4.47715 0 0 4.47715 0 10C0 15.5228 4.47715 20 10 20C13.9387 20 17.3456 17.7229 18.976 14.4133Z" fill="currentColor"></path>
|
||||
</svg>
|
||||
}
|
||||
href="/integrations/respan"
|
||||
href="/integrations/keywords"
|
||||
>
|
||||
Build AI applications with persistent memory and comprehensive LLM observability.
|
||||
</Card>
|
||||
|
||||
@@ -65,7 +65,6 @@ The plugin uses the same shell scripts as Claude Code, Cursor, and Codex — hoo
|
||||
| **User prompt** | `UserPromptSubmit` | Searches relevant memories before each message |
|
||||
| **Pre-tool** | `PreToolUse` | Blocks MEMORY.md writes, enforces `user_id`/`app_id` on mem0 tools |
|
||||
| **Post-tool** | `PostToolUse` | Tracks stats, scans bash errors for related memories |
|
||||
| **Stop** | `Stop` | Stores a session summary when the session ends |
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ Add the Mem0 MCP server directly with a single command:
|
||||
npx mcp-add \
|
||||
--name mem0-mcp \
|
||||
--type http \
|
||||
--url "https://mcp.mem0.ai/mcp/" \
|
||||
--url "https://mcp.mem0.ai/mcp" \
|
||||
--clients "claude code"
|
||||
```
|
||||
|
||||
@@ -142,8 +142,7 @@ When installed via the plugin marketplace, Mem0 hooks into Claude Code's lifecyc
|
||||
| **User prompt** | `UserPromptSubmit` | Searches relevant memories before each message; skips short prompts |
|
||||
| **Pre-tool** | `PreToolUse` | Blocks MEMORY.md writes, enforces `user_id`/`app_id` on mem0 tool calls |
|
||||
| **Post-tool** | `PostToolUse` | Tracks stats, scans bash errors for related memories |
|
||||
| **Stop** | `Stop` | Stores a session summary when the session ends |
|
||||
| **Pre-compact** | `PreCompact` | Stores a summary before the context is compacted |
|
||||
| **Pre-compact** | `PreCompact` | Stores a session summary before context compaction |
|
||||
|
||||
## Example Workflow
|
||||
|
||||
|
||||
@@ -41,17 +41,7 @@ Install the full plugin including MCP server, lifecycle hooks, and SDK skill.
|
||||
codex plugin marketplace add mem0ai/mem0
|
||||
```
|
||||
|
||||
2. Install the plugin:
|
||||
|
||||
```bash
|
||||
codex plugin add mem0@mem0-plugins
|
||||
```
|
||||
|
||||
Or, in the app: restart Codex, open the Plugin Directory, browse the **Mem0 Plugins** marketplace, and install **Mem0**.
|
||||
|
||||
<Note>
|
||||
Step 1 is required for the app UI. Mem0 isn't in OpenAI's curated directory yet, so **without `codex plugin marketplace add`, Mem0 won't appear in the Codex app's Plugin Directory** — searching for it returns nothing. Adding the marketplace surfaces it (under **Created by you**) and makes it installable.
|
||||
</Note>
|
||||
2. Restart Codex, open the Plugin Directory, browse the **Mem0 Plugins** marketplace, and install **Mem0**.
|
||||
|
||||
<Info>
|
||||
Do not combine with Option B. The plugin manifest auto-registers the `mem0` MCP server, so adding both will create a duplicate registration.
|
||||
@@ -59,30 +49,27 @@ Install the full plugin including MCP server, lifecycle hooks, and SDK skill.
|
||||
|
||||
### Option B — Direct MCP
|
||||
|
||||
The fastest way to connect Codex to Mem0 — no plugin, no marketplace. Add the MCP server with a single command:
|
||||
|
||||
```bash
|
||||
codex mcp add mem0 --url https://mcp.mem0.ai/mcp/ --bearer-token-env-var MEM0_API_KEY
|
||||
```
|
||||
|
||||
Or add it manually to `~/.codex/config.toml`:
|
||||
The fastest way to connect Codex to Mem0 — no plugin, no marketplace. Add to `~/.codex/config.toml`:
|
||||
|
||||
```toml
|
||||
[mcp_servers.mem0]
|
||||
url = "https://mcp.mem0.ai/mcp/"
|
||||
url = "https://mcp.mem0.ai/mcp"
|
||||
bearer_token_env_var = "MEM0_API_KEY"
|
||||
```
|
||||
|
||||
Make sure `MEM0_API_KEY` is exported in the shell you launch Codex from, then restart Codex.
|
||||
|
||||
<Info>
|
||||
Codex's `codex mcp add` CLI only supports stdio MCP servers. Because Mem0's MCP is HTTP/streamable, you configure it by editing `config.toml` directly (or via the **Plugins → Connect to a custom MCP → Streamable HTTP** UI in the Codex app).
|
||||
</Info>
|
||||
|
||||
This gives you the MCP tools but not the lifecycle hooks or SDK skill.
|
||||
|
||||
### Managing the Plugin
|
||||
|
||||
```bash
|
||||
codex plugin marketplace upgrade # pull latest plugin versions
|
||||
codex plugin remove mem0@mem0-plugins # uninstall the plugin (keeps the marketplace)
|
||||
codex plugin marketplace remove mem0-plugins # unregister the marketplace entirely
|
||||
codex plugin marketplace remove mem0-plugins # unregister the marketplace
|
||||
```
|
||||
|
||||
To update, run `codex plugin marketplace upgrade` to pull the latest from the Mem0 repo.
|
||||
@@ -125,8 +112,7 @@ When installed via the plugin marketplace, Mem0 hooks into Codex's lifecycle to
|
||||
| **User prompt** | `UserPromptSubmit` | Searches relevant memories before each message |
|
||||
| **Pre-tool** | `PreToolUse` | Blocks MEMORY.md writes, enforces `user_id`/`app_id` on mem0 tool calls |
|
||||
| **Post-tool** | `PostToolUse` | Tracks stats, scans bash errors for related memories |
|
||||
| **Stop** | `Stop` | Stores a session summary when the session ends |
|
||||
| **Pre-compact** | `PreCompact` | Stores a summary before the context is compacted |
|
||||
| **Pre-compact** | `PreCompact` | Stores a session summary before context compaction |
|
||||
|
||||
## Example Workflow
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ The fastest way to get started. Click the link below to install the Mem0 MCP ser
|
||||
npx mcp-add \
|
||||
--name mem0-mcp \
|
||||
--type http \
|
||||
--url "https://mcp.mem0.ai/mcp/" \
|
||||
--url "https://mcp.mem0.ai/mcp" \
|
||||
--clients "cursor"
|
||||
```
|
||||
|
||||
@@ -110,8 +110,7 @@ When installed via the Cursor Marketplace, Mem0 hooks into Cursor's lifecycle:
|
||||
| **User prompt** | `beforeSubmitPrompt` | Searches relevant memories before each message; skips short prompts |
|
||||
| **Pre-tool (2 handlers)** | `preToolUse` | Blocks MEMORY.md writes, enforces `user_id`/`app_id` on mem0 tool calls |
|
||||
| **Post-tool (2 handlers)** | `postToolUse` | Tracks stats, scans bash errors for related memories |
|
||||
| **Stop** | `stop` | Stores a session summary when the session ends |
|
||||
| **Pre-compact** | `preCompact` | Stores a summary before the context is compacted |
|
||||
| **Pre-compact** | `preCompact` | Stores a session summary before context compaction |
|
||||
|
||||
## Example Workflow
|
||||
|
||||
|
||||
@@ -100,12 +100,12 @@ This section:
|
||||
Initialize both the ElevenLabs and Mem0 clients:
|
||||
|
||||
```python
|
||||
# Initialize ElevenLabs client
|
||||
client = ElevenLabs(api_key=API_KEY)
|
||||
# Initialize ElevenLabs client
|
||||
client = ElevenLabs(api_key=API_KEY)
|
||||
|
||||
# Initialize memory client and tools
|
||||
client_tools = ClientTools()
|
||||
mem0_client = AsyncMemoryClient()
|
||||
# Initialize memory client and tools
|
||||
client_tools = ClientTools()
|
||||
mem0_client = AsyncMemoryClient()
|
||||
```
|
||||
|
||||
Here we:
|
||||
@@ -118,36 +118,36 @@ Here we:
|
||||
Define the two key memory functions that will be registered as tools:
|
||||
|
||||
```python
|
||||
# Define memory-related functions for the agent
|
||||
async def add_memories(parameters):
|
||||
"""Add a message to the memory store"""
|
||||
message = parameters.get("message")
|
||||
await mem0_client.add(
|
||||
messages=message,
|
||||
user_id=USER_ID
|
||||
)
|
||||
return "Memory added successfully"
|
||||
# Define memory-related functions for the agent
|
||||
async def add_memories(parameters):
|
||||
"""Add a message to the memory store"""
|
||||
message = parameters.get("message")
|
||||
await mem0_client.add(
|
||||
messages=message,
|
||||
user_id=USER_ID
|
||||
)
|
||||
return "Memory added successfully"
|
||||
|
||||
async def retrieve_memories(parameters):
|
||||
"""Retrieve relevant memories based on the input message"""
|
||||
message = parameters.get("message")
|
||||
async def retrieve_memories(parameters):
|
||||
"""Retrieve relevant memories based on the input message"""
|
||||
message = parameters.get("message")
|
||||
|
||||
# For Platform API, user_id goes in filters
|
||||
filters = {"user_id": USER_ID}
|
||||
# For Platform API, user_id goes in filters
|
||||
filters = {"user_id": USER_ID}
|
||||
|
||||
# Search for relevant memories using the message as a query
|
||||
results = await mem0_client.search(
|
||||
query=message,
|
||||
filters=filters
|
||||
)
|
||||
# Search for relevant memories using the message as a query
|
||||
results = await mem0_client.search(
|
||||
query=message,
|
||||
filters=filters
|
||||
)
|
||||
|
||||
# Extract and join the memory texts
|
||||
memories = ' '.join([result["memory"] for result in results.get('results', [])])
|
||||
print("[ Memories ]", memories)
|
||||
# Extract and join the memory texts
|
||||
memories = ' '.join([result["memory"] for result in results.get('results', [])])
|
||||
print("[ Memories ]", memories)
|
||||
|
||||
if memories:
|
||||
return memories
|
||||
return "No memories found"
|
||||
if memories:
|
||||
return memories
|
||||
return "No memories found"
|
||||
```
|
||||
|
||||
These functions:
|
||||
@@ -171,9 +171,9 @@ These functions:
|
||||
Register the memory functions with the ElevenLabs ClientTools system:
|
||||
|
||||
```python
|
||||
# Register the memory functions as tools for the agent
|
||||
client_tools.register("addMemories", add_memories, is_async=True)
|
||||
client_tools.register("retrieveMemories", retrieve_memories, is_async=True)
|
||||
# Register the memory functions as tools for the agent
|
||||
client_tools.register("addMemories", add_memories, is_async=True)
|
||||
client_tools.register("retrieveMemories", retrieve_memories, is_async=True)
|
||||
```
|
||||
|
||||
This allows the ElevenLabs agent to:
|
||||
@@ -186,19 +186,19 @@ This allows the ElevenLabs agent to:
|
||||
Configure the conversation with ElevenLabs:
|
||||
|
||||
```python
|
||||
# Initialize the conversation
|
||||
conversation = Conversation(
|
||||
client,
|
||||
AGENT_ID,
|
||||
# Assume auth is required when API_KEY is set
|
||||
requires_auth=bool(API_KEY),
|
||||
audio_interface=DefaultAudioInterface(),
|
||||
client_tools=client_tools,
|
||||
callback_agent_response=lambda response: print(f"Agent: {response}"),
|
||||
callback_agent_response_correction=lambda original, corrected: print(f"Agent: {original} -> {corrected}"),
|
||||
callback_user_transcript=lambda transcript: print(f"User: {transcript}"),
|
||||
# callback_latency_measurement=lambda latency: print(f"Latency: {latency}ms"),
|
||||
)
|
||||
# Initialize the conversation
|
||||
conversation = Conversation(
|
||||
client,
|
||||
AGENT_ID,
|
||||
# Assume auth is required when API_KEY is set
|
||||
requires_auth=bool(API_KEY),
|
||||
audio_interface=DefaultAudioInterface(),
|
||||
client_tools=client_tools,
|
||||
callback_agent_response=lambda response: print(f"Agent: {response}"),
|
||||
callback_agent_response_correction=lambda original, corrected: print(f"Agent: {original} -> {corrected}"),
|
||||
callback_user_transcript=lambda transcript: print(f"User: {transcript}"),
|
||||
# callback_latency_measurement=lambda latency: print(f"Latency: {latency}ms"),
|
||||
)
|
||||
```
|
||||
|
||||
This sets up the conversation with:
|
||||
@@ -217,16 +217,16 @@ This sets up the conversation with:
|
||||
Start and manage the conversation:
|
||||
|
||||
```python
|
||||
# Start the conversation
|
||||
print(f"Starting conversation with user_id: {USER_ID}")
|
||||
conversation.start_session()
|
||||
# Start the conversation
|
||||
print(f"Starting conversation with user_id: {USER_ID}")
|
||||
conversation.start_session()
|
||||
|
||||
# Handle Ctrl+C to gracefully end the session
|
||||
signal.signal(signal.SIGINT, lambda sig, frame: conversation.end_session())
|
||||
# Handle Ctrl+C to gracefully end the session
|
||||
signal.signal(signal.SIGINT, lambda sig, frame: conversation.end_session())
|
||||
|
||||
# Wait for the conversation to end and get the conversation ID
|
||||
conversation_id = conversation.wait_for_session_end()
|
||||
print(f"Conversation ID: {conversation_id}")
|
||||
# Wait for the conversation to end and get the conversation ID
|
||||
conversation_id = conversation.wait_for_session_end()
|
||||
print(f"Conversation ID: {conversation_id}")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
@@ -445,3 +445,4 @@ By integrating ElevenLabs Conversational AI with Mem0, you can create voice agen
|
||||
Create voice-first AI applications
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
|
||||
+37
-164
@@ -1,42 +1,35 @@
|
||||
---
|
||||
title: Hermes Agent
|
||||
description: "Add long-term memory to Hermes agents with Mem0, on managed Mem0 Cloud or fully self-hosted (OSS), with automatic background sync and zero-latency prefetch."
|
||||
description: "Add long-term memory to Hermes agents using Mem0 as a pluggable memory provider with automatic background sync and zero-latency prefetch."
|
||||
---
|
||||
|
||||
Add long-term memory to [Hermes Agent](https://github.com/NousResearch/hermes-agent), a self-improving AI agent CLI by Nous Research. Hermes has a pluggable memory system, and Mem0 is one of the supported providers. Once enabled, Mem0 learns facts from your conversations and surfaces relevant ones before each turn, without slowing down the chat.
|
||||
Add long-term memory to [Hermes Agent](https://github.com/NousResearch/hermes-agent) — a self-improving AI agent CLI by Nous Research. Hermes has a pluggable memory system, and Mem0 is one of the supported providers. Once enabled, Mem0 automatically learns facts from your conversations and surfaces relevant ones before each turn — all without slowing down the chat.
|
||||
|
||||
You can run Mem0 in two ways:
|
||||
## Overview
|
||||
|
||||
- **Platform mode** (default): managed Mem0 Cloud. Add your API key and you are ready.
|
||||
- **OSS mode**: fully self-hosted with your own LLM, embedder, and vector store. No data leaves your machine.
|
||||
Hermes runs a built-in memory system (file-based `MEMORY.md` and `USER.md`) alongside one external provider. When Mem0 is active, it works additively with the built-in system at three key moments in every conversation turn:
|
||||
|
||||
## How It Works
|
||||
### 1. Before the Agent Responds (Prefetch)
|
||||
|
||||
Hermes runs a built-in memory system (file-based `MEMORY.md` and `USER.md`) alongside one external provider. When Mem0 is active, it works additively with the built-in system at three points in every conversation turn.
|
||||
When you send a message, Hermes checks if it already has cached Mem0 search results from the previous turn. If so, those memories are injected into the system prompt so the LLM can see them. This is **zero-latency** — no waiting for an API call.
|
||||
|
||||
### 1. Before the agent responds (prefetch)
|
||||
### 2. After the Agent Responds (Sync)
|
||||
|
||||
When you send a message, Hermes checks for cached Mem0 search results from the previous turn. If they exist, those memories are injected into the system prompt so the model can see them. This is zero-latency, with no waiting on an API call.
|
||||
Once the LLM finishes responding, Hermes sends the `(user message, assistant response)` pair to Mem0's API in a **background thread**. Mem0's server-side LLM automatically extracts facts (e.g., "user prefers Python", "user works at Acme Corp") — you don't have to tell it what to remember.
|
||||
|
||||
### 2. After the agent responds (sync)
|
||||
### 3. Background Prefetch for Next Turn
|
||||
|
||||
Once the model finishes, Hermes sends the `(user message, assistant response)` pair to Mem0 in a background thread. Mem0 extracts facts automatically (for example, "user prefers Python" or "user works at Acme Corp"), so you never have to tell it what to remember. Each write is tagged with the gateway channel it came from.
|
||||
|
||||
### 3. Background prefetch for the next turn
|
||||
|
||||
At the same time, Hermes runs a background search to pre-load relevant memories for your next message. By the time you type, the results are already cached.
|
||||
At the same time as sync, Hermes kicks off a background search on Mem0 to pre-load relevant memories for the next turn. By the time you type your next message, the memories are already cached.
|
||||
|
||||
## Agent Tools
|
||||
|
||||
When Mem0 is active, the model gets five tools it can call during a conversation:
|
||||
When Mem0 is active, the LLM gets three extra tools it can call during conversations:
|
||||
|
||||
| Tool | Description | Parameters |
|
||||
|------|-------------|------------|
|
||||
| `mem0_list` | List all stored memories, for a full overview | `page`, `page_size` (default 100, max 200) |
|
||||
| `mem0_search` | Semantic search by meaning, ranked by relevance | `query` (required), `top_k` (default 10, max 50), `rerank` (default `true`, Platform mode only) |
|
||||
| `mem0_add` | Store a fact verbatim, with no LLM extraction | `content` (required) |
|
||||
| `mem0_update` | Update a memory's text by ID | `memory_id`, `text` (both required) |
|
||||
| `mem0_delete` | Delete a memory by ID | `memory_id` (required) |
|
||||
| Tool | Description |
|
||||
|------|-------------|
|
||||
| `mem0_profile` | Fetch all stored memories about the user |
|
||||
| `mem0_search` | Semantic search through memories (supports optional reranking via `rerank` and `top_k` parameters) |
|
||||
| `mem0_conclude` | Store a specific fact verbatim — uses `infer=False` so no server-side LLM extraction happens |
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -47,19 +40,17 @@ curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scri
|
||||
source ~/.bashrc
|
||||
```
|
||||
|
||||
The `mem0ai` package is installed automatically when you enable the Mem0 provider, so there is no manual pip step. OSS providers may need extra packages (for example `qdrant-client`, `psycopg2-binary`, or `ollama`), which the setup flow installs for you when you pick them.
|
||||
The `mem0ai` Python package is automatically installed when you enable the Mem0 provider — no manual pip install needed.
|
||||
|
||||
## Platform Setup
|
||||
## Setup
|
||||
|
||||
Platform mode uses managed Mem0 Cloud and is the fastest way to start.
|
||||
|
||||
### Option 1: Interactive wizard (recommended)
|
||||
### Option 1: Interactive Setup Wizard (Recommended)
|
||||
|
||||
```bash
|
||||
hermes memory setup
|
||||
```
|
||||
|
||||
Select **mem0**, choose **Platform**, and paste your API key when prompted. The wizard writes the non-secret settings to `~/.hermes/mem0.json` and keeps the key in `~/.hermes/.env`.
|
||||
Select **mem0** as the provider and enter your Mem0 API key when prompted. The wizard writes your config to `~/.hermes/mem0.json`.
|
||||
|
||||
<Note>Get your API key from <a href="https://app.mem0.ai?utm_source=oss&utm_medium=integration-hermes" rel="nofollow">app.mem0.ai</a>.</Note>
|
||||
|
||||
@@ -77,151 +68,33 @@ memory:
|
||||
provider: mem0
|
||||
```
|
||||
|
||||
That's it. Mem0 runs automatically from here.
|
||||
That's it — Mem0 runs automatically from this point.
|
||||
|
||||
## OSS (Self-Hosted) Setup
|
||||
## Configuration Options
|
||||
|
||||
OSS mode runs Mem0 entirely on your own infrastructure: your LLM, your embedder, and your vector store. No data is sent to Mem0 Cloud, and no Mem0 API key is required.
|
||||
Configuration is stored in `~/.hermes/mem0.json`. Values can also be set via environment variables.
|
||||
|
||||
### Interactive
|
||||
|
||||
```bash
|
||||
hermes memory setup
|
||||
# Select "mem0", then "Open Source (self-hosted)"
|
||||
# Follow the prompts for LLM, embedder, and vector store
|
||||
```
|
||||
|
||||
### With flags
|
||||
|
||||
```bash
|
||||
hermes memory setup mem0 --mode oss \
|
||||
--oss-llm openai --oss-llm-key sk-... \
|
||||
--oss-vector qdrant
|
||||
```
|
||||
|
||||
### Supported providers
|
||||
|
||||
| Component | Providers |
|
||||
|-----------|-----------|
|
||||
| LLM | `openai` (default model `gpt-5-mini`), `ollama` (local, default `llama3.1:8b`) |
|
||||
| Embedder | `openai` (default `text-embedding-3-small`), `ollama` (local, default `nomic-embed-text`) |
|
||||
| Vector store | `qdrant` (local path or server), `pgvector` |
|
||||
|
||||
### Flag reference
|
||||
|
||||
| Flag | Description |
|
||||
|------|-------------|
|
||||
| `--mode` | `platform` or `oss` |
|
||||
| `--oss-llm` | LLM provider (`openai` or `ollama`, default `openai`) |
|
||||
| `--oss-llm-key` | LLM API key (for `openai`) |
|
||||
| `--oss-llm-model` | Override the LLM model |
|
||||
| `--oss-llm-url` | LLM base URL (for `ollama` or a custom endpoint) |
|
||||
| `--oss-embedder` | Embedder provider (default `openai`) |
|
||||
| `--oss-embedder-key` | Embedder API key |
|
||||
| `--oss-vector` | Vector store (`qdrant` or `pgvector`, default `qdrant`) |
|
||||
| `--oss-vector-path` | Local Qdrant storage path |
|
||||
| `--oss-vector-host`, `--oss-vector-port` | PGVector or remote Qdrant host and port |
|
||||
| `--oss-vector-user`, `--oss-vector-password`, `--oss-vector-dbname` | PGVector connection details |
|
||||
| `--user-id` | Canonical user identifier |
|
||||
| `--dry-run` | Preview the resolved config without writing it |
|
||||
|
||||
## Switching Modes
|
||||
|
||||
You can move between Platform and OSS at any time. Run the setup command again, or edit `~/.hermes/mem0.json` directly.
|
||||
|
||||
```bash
|
||||
# Platform to OSS
|
||||
hermes memory setup mem0 --mode oss --oss-llm-key sk-...
|
||||
|
||||
# OSS to Platform
|
||||
hermes memory setup mem0 --mode platform --api-key sk-...
|
||||
|
||||
# Preview without writing anything
|
||||
hermes memory setup mem0 --mode oss --oss-llm-key sk-... --dry-run
|
||||
```
|
||||
|
||||
A self-hosted `~/.hermes/mem0.json` looks like this:
|
||||
|
||||
```json
|
||||
{
|
||||
"mode": "oss",
|
||||
"oss": {
|
||||
"llm": {"provider": "openai", "config": {"model": "gpt-5-mini"}},
|
||||
"embedder": {"provider": "openai", "config": {"model": "text-embedding-3-small"}},
|
||||
"vector_store": {"provider": "qdrant", "config": {"path": "~/.hermes/mem0_qdrant"}}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
Behavioral settings live in `~/.hermes/mem0.json` and are written for you by `hermes memory setup`. Only the secret `MEM0_API_KEY` belongs in `~/.hermes/.env`.
|
||||
|
||||
| Key | Default | Description |
|
||||
|-----|---------|-------------|
|
||||
| `mode` | `platform` | `platform` (Mem0 Cloud) or `oss` (self-hosted) |
|
||||
| `api_key` | none | Mem0 Platform API key, required in Platform mode. Stored in `.env` as `MEM0_API_KEY` |
|
||||
| `user_id` | `hermes-user` | Identifier that scopes memories. See cross-channel behavior below |
|
||||
| `agent_id` | `hermes` | Agent identifier attached to writes |
|
||||
| `rerank` | `true` | Rerank search results for relevance (Platform mode only) |
|
||||
|
||||
### Cross-channel memories
|
||||
|
||||
Hermes can run from the CLI and from gateways like Telegram, Slack, and Discord. The `user_id` setting controls how memories are scoped across them:
|
||||
|
||||
- **Set a `user_id`** and it applies to every gateway, so one person gets a single merged memory store no matter where they talk to the agent.
|
||||
- **Leave it unset** (or at the default `hermes-user`) and each gateway uses its own native id, keeping per-platform memories separate.
|
||||
|
||||
Either way, every write is tagged with `metadata.channel` (for example `telegram` or `cli`), so per-channel views are still possible at query time.
|
||||
| Key | Env Variable | Default | Description |
|
||||
|-----|-------------|---------|-------------|
|
||||
| `api_key` | `MEM0_API_KEY` | — | **Required.** Mem0 Platform API key |
|
||||
| `user_id` | `MEM0_USER_ID` | `hermes-user` | User identifier for scoping memories |
|
||||
| `agent_id` | `MEM0_AGENT_ID` | `hermes` | Agent identifier |
|
||||
| `rerank` | — | `true` | Enable reranking for memory recall |
|
||||
|
||||
|
||||
## Reliability
|
||||
|
||||
- **Circuit breaker**: if Mem0 fails five times in a row, Hermes pauses calls for two minutes, then retries. The agent keeps working without memory during that window. Expected client errors, like a 404 on a missing memory id, do not count toward tripping the breaker.
|
||||
- **Non-blocking**: every Mem0 call runs in a background daemon thread, so a slow or failed call never blocks your conversation.
|
||||
- **Thread-safe**: the client uses lazy initialization with locking, and the background sync and prefetch threads are guarded so concurrent gateway messages cannot produce duplicate memories.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### "Mem0 temporarily unavailable"
|
||||
|
||||
The circuit breaker tripped after five consecutive failures and resets after two minutes.
|
||||
|
||||
- **Platform mode**: check your API key and internet connection.
|
||||
- **OSS mode**: make sure your vector store (Qdrant or PGVector) is running and reachable.
|
||||
|
||||
### OSS: vector store connection refused
|
||||
|
||||
```bash
|
||||
# Local Qdrant: confirm the storage path is writable
|
||||
ls -la ~/.hermes/mem0_qdrant
|
||||
|
||||
# Qdrant server: confirm it is reachable
|
||||
curl http://localhost:6333/healthz
|
||||
|
||||
# PGVector: confirm PostgreSQL is accepting connections
|
||||
pg_isready -h localhost -p 5432
|
||||
```
|
||||
|
||||
### OSS: Ollama not reachable
|
||||
|
||||
```bash
|
||||
curl http://localhost:11434/api/tags
|
||||
```
|
||||
|
||||
### Memories not appearing
|
||||
|
||||
- `mem0_add` stores text verbatim with no extraction. Ordinary conversation turns are extracted automatically by the background sync.
|
||||
- Search is semantic, so try a broader query.
|
||||
- Confirm `user_id` is the same across sessions (check `~/.hermes/mem0.json`).
|
||||
- **Circuit Breaker** — If Mem0's API fails 5 times in a row, Hermes stops calling it for 2 minutes, then retries. The agent keeps working fine without memory during that time.
|
||||
- **Non-blocking** — All Mem0 API calls happen in background daemon threads. A slow or failed API call never blocks your conversation.
|
||||
- **Thread-safe** — The Mem0 client uses lazy initialization with locking, safe for concurrent access.
|
||||
|
||||
## Key Features
|
||||
|
||||
1. **Two ways to run**: managed Platform or fully self-hosted OSS, switchable at any time.
|
||||
2. **Zero-latency recall**: memories are prefetched in the background and cached before you type.
|
||||
3. **Automatic extraction**: Mem0 extracts and deduplicates facts from each exchange for you.
|
||||
4. **Non-blocking and fault tolerant**: background threads plus a circuit breaker keep the agent responsive even when Mem0 is unreachable.
|
||||
5. **Additive memory**: works alongside Hermes' built-in file memory (`MEMORY.md`, `USER.md`).
|
||||
1. **Zero-Latency Recall** — Memories are prefetched in the background and cached, ready before you type
|
||||
2. **Server-side Extraction** — Mem0's API automatically extracts and deduplicates facts from each exchange
|
||||
3. **Non-blocking** — All API calls run in background daemon threads
|
||||
4. **Fault Tolerant** — Circuit breaker ensures the agent works even if Mem0 is temporarily unreachable
|
||||
5. **Additive Memory** — Works alongside Hermes' built-in file-based memory system (MEMORY.md, USER.md)
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="OpenClaw Integration" icon={<svg width="24" height="24" viewBox="0 0 500 500" fill="none" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="m153.5 173.5q24.62 1.46 46 13.5 12.11 8.1 17.5 21.5 0.74 2.45 0.5 5 0.09 0.81 1 1 1.48-4.9 1-10 5.04 10.48 1.5 22-9.81 27.86-35.5 42.5-26.17 14.97-56 19.5-2.77-0.4-2 1 2.86 1.27 6 1 25.64 1.53 48.5-10 0.34 10.08 2 20 1.08 5.76 5 10 1 1.5 0 3-31.11 20.84-68.5 17.5-23.7-5.7-32.5-28.5-4.39-9.18-3.5-19 15.41 6.23 32 4.5-20.68-6.39-39-18-34.81-27.22-12.5-65.5 11.84-14.83 29-23 4.21 7.66 11.5 12.5 3 1 6 0-26.04-34.62-29-78-0.13-8.46 2-16.5 1 6.5 2 13 3.43 39.53 24.5 73 2.03 2.28 4.5 4 0.5-1.25 1-2.5-1.27-6.54-5-12 0.5-0.75 1-1.5 9.72-3.43 20-4 0.55 10.34 8 17.5 1.94 0.74 4 0.5-17.8-64.6 16.5-122 0.98-1.79 1.5 0-28.21 56.64-13.5 118 1.08 1.43 2.5 0.5 2.21-4.98 2-10.5z" fill="currentColor"/><path fill-rule="evenodd" d="m454.5 97.5q-1.33 11.18-8.5 20-21.81 26.28-55.5 32-1.11-0.2-2 0.5 2.31 2.82 5.5 4.5 1 2 0 4-9.56 11.3-19.5 20 19.71-8.72 31-27 2.68-0.43 5 1-14.24 30.97-48 36.5-9.93 1.71-20 1.5-6.8-0.48-13 1 5.81 6.92 14 11-10.78 16.03-27 26.5 27.16-7.4 38-33.5 4.34 1.35 9 1-9.08 23.84-33 33.5-18.45 6.41-38 7 22.59 8.92 45-1 12.05-5.52 24-11 9.01-1.79 17 2.5 5.28-4.38 11-8 12.8-6.07 27-5 0 0.5 0 1-19.34 2.69-34 15.5 0.5 0.25 1 0.5 17.79-8.09 36-15 2.71-0.79 5-2 2.5-1 5-2 5.53-4.04 11-8 11.7-4.18 24-6.5 7.78-1.36 15 1.5-2.97 18.45-13.5 34-34.92 49.37-94.5 62.5-59.27 12.45-108-23-15.53-12.52-21.5-31.5-2.47-14.26 4-27-3.15 24.41 14 42-4.92-10.28-7-22-1.97-17.63 7-33 47.28-69.5 125.5-100 15.86-3.42 32-5.5 18.63-1.47 37 1.5z" fill="currentColor"/><path fill-rule="evenodd" d="m231.5 238.5q1.31-0.2 2 1-3.13 28.62 15 51-16.25 6.75-27-7.5-1-1-2 0 14.73 29.34 46 18.5 1.79 0.52 0 1.5-37.63 16.82-50.5-22.5-5.1-26.48 16.5-42z" fill="currentColor"/><path fill-rule="evenodd" d="m203.5 266.5q1.31-0.2 2 1-2.48 22.08 12 39-6.99 1.35-14 0.5 4.59 4.08 10 7-8.71 0.28-14.5-6.5-16.98-22.76 4.5-41z" fill="currentColor"/><path fill-rule="evenodd" d="m58.5 284.5q9.6-2.17 14.5 6 5.15 14.18-1 28-11.05-13.14-27.5-17.5 5.15-9.9 14-16.5z" fill="currentColor"/><path fill-rule="evenodd" d="m56.5 313.5q3.43 5.43 8 10-4.88 0.44-8 4-1.11-0.2-2 0.5 28.91 1.65 38 28.5 0.45 3.16-1 6-11.02-7.01-23-12.5-4.75-3.75-9.5-7.5 1.47 7.42 7 13 8.34 27.18 32 43 0.99 2.41-1.5 3.5-40.25 5.58-66.5-25.5-15.67-22.01-8-48 10.46-23.87 34.5-15z" fill="currentColor"/><path fill-rule="evenodd" d="m198.5 319.5q1.44 0.68 2.5 2 2.41 8.23 6 16 1.2 2.64-0.5 5-30.65 21.41-68 18.5-25.16-6.17-32.5-30.5 6.96 4.99 15.5 6.5 8.99 0.75 18 0.5 16.25 2.38 32-2.5 15.9-3.94 27-15.5z" fill="currentColor"/><path fill-rule="evenodd" d="m239.5 342.5q7.02-0.25 14 0.5 4.46 1.06 8 3.5-5.2 2.35-10 5.5-3.88 4.65-9 7.5-9.89-3.09-9.5-13 2.36-3.63 6.5-4z" fill="currentColor"/><path fill-rule="evenodd" d="m214.5 349.5q5.96 7.2 13.5 13 1 1 0 2-28.58 23.34-65.5 20.5-18.15-4.24-27.5-19.5 1.13 0.94 2.5 1.5 14.7 1.42 29-1.5 26.57-0.52 48-16z" fill="currentColor"/><path fill-rule="evenodd" d="m302.5 373.5q0.21 2.44-2 3.5-28.69 7.6-50.5-12.5-0.06-6.71 6.5-9 4.45-0.75 9-1 22.26 2.27 37 19z" fill="currentColor"/><path fill-rule="evenodd" d="m232.5 365.5q17.6 6.19 10.5 23-10.6 10.42-25.5 11.5-25.94 3.21-49-9 36.75-1.65 64-25.5z" fill="currentColor"/><path fill-rule="evenodd" d="m113.5 367.5q7.7-0.01 9.5 7-9.69 7.19-18.5 15.5-7.23 5.76-5.5-3.5 3.12-12.84 14.5-19z" fill="currentColor"/><path fill-rule="evenodd" d="m126.5 380.5q7.88-0.4 12 6.5-8.5 7.25-17 14.5-5.62-12.55 5-21z" fill="currentColor"/><path fill-rule="evenodd" d="m283.5 385.5q3.22 2.95 7 5.5 2.8 4.03 6 7.5 0.42 2.77-2 4-15.5-9.75-31-19.5-1.79-0.98 0-1.5 9.96 2.49 20 4z" fill="currentColor"/></svg>} href="/integrations/openclaw">
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
---
|
||||
title: Respan
|
||||
description: "Combine Mem0 persistent memory with Respan observability for tracked, cost-optimized AI applications."
|
||||
title: Keywords AI
|
||||
description: "Combine Mem0 persistent memory with Keywords AI observability for tracked, cost-optimized AI applications."
|
||||
---
|
||||
|
||||
Build AI applications with persistent memory and comprehensive LLM observability by integrating Mem0 with Respan.
|
||||
Build AI applications with persistent memory and comprehensive LLM observability by integrating Mem0 with Keywords AI.
|
||||
|
||||
## Overview
|
||||
|
||||
Mem0 is a self-improving memory layer for LLM applications, enabling personalized AI experiences that save costs and delight users. Respan (formerly Keywords AI) provides complete LLM observability.
|
||||
Mem0 is a self-improving memory layer for LLM applications, enabling personalized AI experiences that save costs and delight users. Keywords AI provides complete LLM observability.
|
||||
|
||||
Combining Mem0 with Respan allows you to:
|
||||
Combining Mem0 with Keywords AI allows you to:
|
||||
1. Add persistent memory to your AI applications
|
||||
2. Track interactions across sessions
|
||||
3. Monitor memory usage and retrieval with Respan observability
|
||||
3. Monitor memory usage and retrieval with Keywords AI observability
|
||||
4. Optimize token usage and reduce costs
|
||||
|
||||
<Note>
|
||||
You can get your Mem0 API key from the <a href="https://app.mem0.ai/?utm_source=oss&utm_medium=integration-respan" rel="nofollow">Mem0 dashboard</a>.
|
||||
You can get your Mem0 API key from the <a href="https://app.mem0.ai/?utm_source=oss&utm_medium=integration-keywords" rel="nofollow">Mem0 dashboard</a>.
|
||||
</Note>
|
||||
|
||||
## Setup and Configuration
|
||||
@@ -24,7 +24,7 @@ You can get your Mem0 API key from the <a href="https://app.mem0.ai/?utm_source=
|
||||
Install the necessary libraries:
|
||||
|
||||
```bash
|
||||
pip install mem0ai openai
|
||||
pip install mem0ai keywordsai-sdk
|
||||
```
|
||||
|
||||
Set up your environment variables:
|
||||
@@ -34,13 +34,13 @@ import os
|
||||
|
||||
# Set your API keys
|
||||
os.environ["MEM0_API_KEY"] = "your-mem0-api-key"
|
||||
os.environ["RESPAN_API_KEY"] = "your-respan-api-key"
|
||||
os.environ["RESPAN_BASE_URL"] = "https://api.respan.ai/api/"
|
||||
os.environ["KEYWORDSAI_API_KEY"] = "your-keywords-api-key"
|
||||
os.environ["KEYWORDSAI_BASE_URL"] = "https://api.keywordsai.co/api/"
|
||||
```
|
||||
|
||||
## Basic Integration Example
|
||||
|
||||
Here's a simple example of using Mem0 with Respan:
|
||||
Here's a simple example of using Mem0 with Keywords AI:
|
||||
|
||||
```python
|
||||
from mem0 import Memory
|
||||
@@ -48,17 +48,17 @@ import os
|
||||
|
||||
# Configuration
|
||||
api_key = os.getenv("MEM0_API_KEY")
|
||||
respan_api_key = os.getenv("RESPAN_API_KEY")
|
||||
base_url = os.getenv("RESPAN_BASE_URL") # "https://api.respan.ai/api/"
|
||||
keywordsai_api_key = os.getenv("KEYWORDSAI_API_KEY")
|
||||
base_url = os.getenv("KEYWORDSAI_BASE_URL") # "https://api.keywordsai.co/api/"
|
||||
|
||||
# Set up Mem0 with Respan as the LLM provider
|
||||
# Set up Mem0 with Keywords AI as the LLM provider
|
||||
config = {
|
||||
"llm": {
|
||||
"provider": "openai",
|
||||
"config": {
|
||||
"model": "gpt-5-mini",
|
||||
"temperature": 0.0,
|
||||
"api_key": respan_api_key,
|
||||
"api_key": keywordsai_api_key,
|
||||
"openai_base_url": base_url,
|
||||
},
|
||||
}
|
||||
@@ -79,7 +79,7 @@ print(result)
|
||||
|
||||
## Advanced Integration with OpenAI SDK
|
||||
|
||||
For more advanced use cases, you can integrate Respan with Mem0 through the OpenAI SDK:
|
||||
For more advanced use cases, you can integrate Keywords AI with Mem0 through the OpenAI SDK:
|
||||
|
||||
```python
|
||||
from openai import OpenAI
|
||||
@@ -88,8 +88,8 @@ import json
|
||||
|
||||
# Initialize client
|
||||
client = OpenAI(
|
||||
api_key=os.environ.get("RESPAN_API_KEY"),
|
||||
base_url=os.environ.get("RESPAN_BASE_URL"),
|
||||
api_key=os.environ.get("KEYWORDSAI_API_KEY"),
|
||||
base_url=os.environ.get("KEYWORDSAI_BASE_URL"),
|
||||
)
|
||||
|
||||
# Sample conversation messages
|
||||
@@ -118,18 +118,18 @@ response = client.chat.completions.create(
|
||||
print(json.dumps(response.model_dump(), indent=4))
|
||||
```
|
||||
|
||||
For detailed information on this integration, refer to the official [Respan Mem0 integration documentation](https://www.respan.ai/docs/integrations/mem0).
|
||||
For detailed information on this integration, refer to the official [Keywords AI Mem0 integration documentation](https://docs.keywordsai.co/integration/development-frameworks/mem0).
|
||||
|
||||
## Key Features
|
||||
|
||||
1. **Memory Integration**: Store and retrieve relevant information from past interactions
|
||||
2. **LLM Observability**: Track memory usage and retrieval patterns with Respan
|
||||
2. **LLM Observability**: Track memory usage and retrieval patterns with Keywords AI
|
||||
3. **Session Persistence**: Maintain context across multiple user sessions
|
||||
4. **Cost Optimization**: Reduce token usage through efficient memory retrieval
|
||||
|
||||
## Conclusion
|
||||
|
||||
Integrating Mem0 with Respan provides a powerful combination for building AI applications with persistent memory and comprehensive observability. This integration enables more personalized user experiences while providing insights into your application's memory usage.
|
||||
Integrating Mem0 with Keywords AI provides a powerful combination for building AI applications with persistent memory and comprehensive observability. This integration enables more personalized user experiences while providing insights into your application's memory usage.
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="OpenAI Agents SDK" icon="cube" href="/integrations/openai-agents-sdk">
|
||||
@@ -139,3 +139,4 @@ Integrating Mem0 with Respan provides a powerful combination for building AI app
|
||||
Monitor agent performance with AgentOps
|
||||
</Card>
|
||||
</CardGroup>
|
||||
|
||||
@@ -36,7 +36,7 @@ opencode plugin @mem0/opencode-plugin
|
||||
Install @mem0/opencode-plugin by following https://raw.githubusercontent.com/mem0ai/mem0/main/integrations/mem0-plugin/.opencode-plugin/README.md
|
||||
```
|
||||
|
||||
This adds the plugin to your `~/.config/opencode/opencode.json`. Restart OpenCode — you get the native memory tools, lifecycle hooks, and all `/mem0-*` slash commands. The memory tools are registered by the plugin itself via the `mem0ai` SDK — no MCP server to configure.
|
||||
This adds the plugin to your `~/.config/opencode/opencode.json`. Restart OpenCode — you get the native memory tools, lifecycle hooks, and all `/mem0:` slash commands. The memory tools are registered by the plugin itself via the `mem0ai` SDK — no MCP server to configure.
|
||||
|
||||
### Option B — Standalone MCP Server
|
||||
|
||||
@@ -63,7 +63,7 @@ If you only need the memory tools without the plugin's hooks or skills, point Op
|
||||
|-----------|:----------:|:------------------:|
|
||||
| 9 memory tools | Native (SDK) | Remote MCP server |
|
||||
| Lifecycle Hooks | Yes | No |
|
||||
| 9 Skills | Yes | No |
|
||||
| 8 Skills | Yes | No |
|
||||
|
||||
## Available Memory Tools
|
||||
|
||||
@@ -79,37 +79,13 @@ If you only need the memory tools without the plugin's hooks or skills, point Op
|
||||
| `delete_entities` | Delete a user/agent/app/run entity and its memories |
|
||||
| `list_entities` | List users/agents/apps/runs stored in Mem0 |
|
||||
|
||||
## Memory scope
|
||||
|
||||
`search_memories`, `get_memories`, `add_memory`, and `delete_all_memories` accept an optional **`scope`** that controls how widely they read or write:
|
||||
|
||||
| Scope | Reads | Writes |
|
||||
|-------|-------|--------|
|
||||
| `project` *(default)* | this repo (`user_id` + `app_id`) | this repo |
|
||||
| `session` | this run only (`+ run_id`) | this run |
|
||||
| `global` | **all your projects in the workspace** (`app_id: "*"`) | user-wide |
|
||||
|
||||
Just ask naturally — e.g. *"search my memories across all my projects"* — and the agent passes `scope: "global"`. For normal questions it stays scoped to the current project automatically.
|
||||
|
||||
To change the **default** scope (used when no scope is passed), run the `/mem0-scope` skill:
|
||||
|
||||
```
|
||||
/mem0-scope # show the current default scope + identity
|
||||
/mem0-scope global # save & search across all your projects by default
|
||||
/mem0-scope project # back to repo-only (the default)
|
||||
```
|
||||
|
||||
The default persists in `~/.mem0/settings.json` (`default_scope`) and is read fresh on each memory operation, so a change applies immediately — no restart. `delete_all_memories` always requires an explicit `scope: "global"` to delete user-wide, so changing the default can't trigger a cross-project wipe.
|
||||
|
||||
The project id (`app_id`) is derived from your git remote (`owner-repo`), falling back to the git repo's root directory name, then the current directory. Launch OpenCode from inside your repo so memories scope to the project rather than your home directory.
|
||||
|
||||
## Lifecycle Hooks
|
||||
|
||||
The plugin uses the [mem0ai](https://www.npmjs.com/package/mem0ai) TypeScript SDK directly — pure TypeScript, no Python, no shell scripts.
|
||||
|
||||
| OpenCode Event | Hook | What happens |
|
||||
|----------------|------|-------------|
|
||||
| `config` | **Config** | Registers the `/mem0-*` slash commands (`config.command`) and adds the plugin's own `opencode-skills/` dir to OpenCode's `skills.paths` for in-place skill discovery (no copying) |
|
||||
| `config` | **Config** | Registers the bundled skills (`skills.paths`) and `/mem0:*` slash commands at startup |
|
||||
| `chat.message` | **Chat message** | Searches prior memories on session start, searches relevant memories before each prompt, auto-captures learnings periodically |
|
||||
| `tool.execute.before` | **Pre-tool** | Blocks MEMORY.md writes, steering them to the `add_memory` tool |
|
||||
| `tool.execute.after` | **Post-tool** | Scans Bash errors and pre-fetches related error memories |
|
||||
@@ -117,32 +93,12 @@ The plugin uses the [mem0ai](https://www.npmjs.com/package/mem0ai) TypeScript SD
|
||||
| `experimental.session.compacting` | **Compaction** | Stores session state memory, then injects prior memories into compaction context so nothing is lost |
|
||||
| `shell.env` | **Shell env** | Exports `MEM0_USER_ID`, `MEM0_APP_ID`, `MEM0_SESSION_ID`, and `MEM0_BRANCH` to all shell executions |
|
||||
|
||||
## Auto-dream (memory consolidation)
|
||||
|
||||
The plugin can automatically consolidate stored memories — merging duplicates, dropping stale/sensitive entries, and rewriting vague ones — so your memory set stays clean over time. It runs at most once per session, and only when **all** gates pass:
|
||||
|
||||
- **Time** — at least `minHours` (default 24) since the last consolidation
|
||||
- **Sessions** — at least `minSessions` (default 5) sessions since then
|
||||
- **Memories** — at least `minMemories` (default 20) stored for the project
|
||||
|
||||
A filesystem lock (`~/.mem0/mem0-dream.lock`) keeps two sessions from consolidating at once. Tune the thresholds with a `dream` block in `~/.mem0/settings.json`, or disable entirely with `MEM0_DREAM=false`:
|
||||
|
||||
```json
|
||||
{
|
||||
"dream": { "enabled": true, "auto": true, "minHours": 24, "minSessions": 5, "minMemories": 20 }
|
||||
}
|
||||
```
|
||||
|
||||
If auto-dream hasn't run yet, it's almost always because a gate hasn't been met (most often too few memories). Run `/mem0-status` to see the exact gate progress (e.g. `sessions 2/5, memories 3/20`), `/mem0-dream` to consolidate **now** regardless of the gates, or lower the thresholds above.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **No tools appearing** — Restart OpenCode after installing
|
||||
- **"Connection failed"** — Verify your key is set: `echo $MEM0_API_KEY`
|
||||
- **Plugin not loading** — Run `opencode plugin @mem0/opencode-plugin` again, then restart
|
||||
- **Hooks not firing** — Hooks require the plugin install (Option A). MCP-only installs don't include hooks.
|
||||
- **Auto-dream never runs** — It's gated (time + sessions + memories). Run `/mem0-status` to see which gate is blocking, or `/mem0-dream` to consolidate now.
|
||||
- **Wrong project name / memories not found** — The project id comes from your git remote; launch OpenCode from inside the repo (not your home directory). Check the resolved id with `/mem0-status`.
|
||||
|
||||
<CardGroup cols={2}>
|
||||
<Card title="Mem0 MCP Setup" icon="puzzle-piece" href="/platform/mem0-mcp">
|
||||
|
||||
+1
-2
@@ -197,7 +197,6 @@ If the user is on a pre-current major (Python < 2, TS < 3, or Platform `output_f
|
||||
- [Platform Features Overview](https://docs.mem0.ai/platform/features/platform-overview) [Platform]: Use when surveying what managed offers beyond CRUD.
|
||||
- [V2 Memory Filters](https://docs.mem0.ai/platform/features/v2-memory-filters) [Platform]: Use when compound filters (AND/OR on metadata, entity, time) are needed at search.
|
||||
- [Entity-Scoped Memory](https://docs.mem0.ai/platform/features/entity-scoped-memory) [Platform]: Use when partitioning memories by user, agent, app, or run.
|
||||
- [Graph Memory](https://docs.mem0.ai/platform/features/graph-memory) [Platform]: Use when connecting facts across memories through shared entities for entity-centric or multi-hop questions.
|
||||
- [Async Client](https://docs.mem0.ai/platform/features/async-client) [Platform]: Use when the app issues many concurrent Mem0 calls and needs non-blocking I/O.
|
||||
- [Multimodal Support](https://docs.mem0.ai/platform/features/multimodal-support) [Platform]: Use when storing images or PDFs as memory input.
|
||||
- [Custom Categories](https://docs.mem0.ai/platform/features/custom-categories) [Platform]: Use when the default categories do not match the domain.
|
||||
@@ -286,7 +285,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or Platform `output_f
|
||||
- [Dify](https://docs.mem0.ai/integrations/dify) [Both]: Use when the user is on Dify LLMOps.
|
||||
- [Flowise](https://docs.mem0.ai/integrations/flowise) [Both]: Use when the user is on Flowise no-code.
|
||||
- [AgentOps](https://docs.mem0.ai/integrations/agentops) [Both]: Use when tracking agent observability with memory metadata.
|
||||
- [Respan](https://docs.mem0.ai/integrations/respan) [Both]: Use when monitoring Mem0 with Respan (formerly Keywords AI) LLM observability.
|
||||
- [Keywords AI](https://docs.mem0.ai/integrations/keywords) [Both]: Use when monitoring with Keywords AI.
|
||||
- [Raycast](https://docs.mem0.ai/integrations/raycast) [Both]: Use when the user wants quick memory access via Raycast.
|
||||
|
||||
## Cookbooks
|
||||
|
||||
@@ -62,8 +62,7 @@ def add(
|
||||
filters: dict = None,
|
||||
output_format: str = None, # ❌ REMOVED
|
||||
version: str = None # ❌ REMOVED
|
||||
) -> Union[List[dict], dict]:
|
||||
...
|
||||
) -> Union[List[dict], dict]
|
||||
```
|
||||
|
||||
#### v1.0.0 Signature
|
||||
@@ -77,8 +76,7 @@ def add(
|
||||
metadata: dict = None,
|
||||
filters: dict = None,
|
||||
infer: bool = True # ✅ NEW: Control memory inference
|
||||
) -> dict: # Always returns dict with "results" key
|
||||
...
|
||||
) -> dict # Always returns dict with "results" key
|
||||
```
|
||||
|
||||
#### Changes Summary
|
||||
@@ -149,8 +147,7 @@ def search(
|
||||
filters: dict = None, # Basic key-value only
|
||||
output_format: str = None, # ❌ REMOVED
|
||||
version: str = None # ❌ REMOVED
|
||||
) -> Union[List[dict], dict]:
|
||||
...
|
||||
) -> Union[List[dict], dict]
|
||||
```
|
||||
|
||||
#### v1.0.0 Signature
|
||||
@@ -164,8 +161,7 @@ def search(
|
||||
limit: int = 100,
|
||||
filters: dict = None, # ✅ ENHANCED: Advanced operators
|
||||
rerank: bool = True # ✅ NEW: Reranking support
|
||||
) -> dict: # Always returns dict with "results" key
|
||||
...
|
||||
) -> dict # Always returns dict with "results" key
|
||||
```
|
||||
|
||||
#### Enhanced Filtering
|
||||
@@ -220,8 +216,7 @@ def get_all(
|
||||
filters: dict = None,
|
||||
output_format: str = None, # ❌ REMOVED
|
||||
version: str = None # ❌ REMOVED
|
||||
) -> Union[List[dict], dict]:
|
||||
...
|
||||
) -> Union[List[dict], dict]
|
||||
```
|
||||
|
||||
#### v1.0.0 Signature
|
||||
@@ -232,8 +227,7 @@ def get_all(
|
||||
agent_id: str = None,
|
||||
run_id: str = None,
|
||||
filters: dict = None # ✅ ENHANCED: Advanced operators
|
||||
) -> dict: # Always returns dict with "results" key
|
||||
...
|
||||
) -> dict # Always returns dict with "results" key
|
||||
```
|
||||
|
||||
### update() Method
|
||||
@@ -245,8 +239,7 @@ def update(
|
||||
self,
|
||||
memory_id: str,
|
||||
data: str
|
||||
) -> dict:
|
||||
...
|
||||
) -> dict
|
||||
```
|
||||
|
||||
### delete() Method
|
||||
@@ -257,8 +250,7 @@ def update(
|
||||
def delete(
|
||||
self,
|
||||
memory_id: str
|
||||
) -> dict:
|
||||
...
|
||||
) -> dict
|
||||
```
|
||||
|
||||
### delete_all() Method
|
||||
@@ -352,7 +344,7 @@ config = {
|
||||
### New Configuration Options
|
||||
|
||||
#### Reranker Configuration
|
||||
```text
|
||||
```python
|
||||
# Cohere reranker
|
||||
"reranker": {
|
||||
"provider": "cohere",
|
||||
@@ -571,4 +563,4 @@ results = m.search(
|
||||
|
||||
<Info>
|
||||
Use this reference to systematically update your codebase. Test each change thoroughly before deploying to production.
|
||||
</Info>
|
||||
</Info>
|
||||
@@ -328,27 +328,27 @@ The new algorithm automatically creates a parallel entity store collection named
|
||||
Make sure your vector store user/credentials have permission to create new collections. If you're using a managed vector database with restricted permissions, pre-create the `{collection_name}_entities` collection with the same embedding dimensions as your main collection.
|
||||
</Warning>
|
||||
|
||||
## Graph Memory: Now Built-In
|
||||
## Graph Memory → Entity Linking
|
||||
|
||||
External graph **store** support has been removed from the open-source SDK and replaced by **built-in graph memory** (entity linking), which runs natively with no external dependencies.
|
||||
Graph store support has been removed from the open-source SDK. It is replaced by **built-in entity linking**, which runs natively with no external dependencies.
|
||||
|
||||
**What was removed:**
|
||||
- `enable_graph` / `enableGraph` config flag
|
||||
- `graph_store` / `graphStore` configuration block (Neo4j, Memgraph, Kuzu, Apache AGE, Neptune)
|
||||
- All external graph store code paths (~4000 lines)
|
||||
- All graph memory code paths (~4000 lines)
|
||||
|
||||
**What replaces it:**
|
||||
|
||||
Mem0 now builds the graph itself. It extracts entities (proper nouns, quoted text, compound noun phrases) from every memory during the add pipeline and stores them in a parallel collection (`{collection}_entities`) inside your existing vector store. Memories that share an entity are linked, and at search time entities from the query are matched against this collection to boost connected memories. The boost is folded into the combined `score` on each result.
|
||||
Entity linking extracts entities (proper nouns, quoted text, compound noun phrases) from every memory during the add pipeline and stores them in a parallel collection (`{collection}_entities`) inside your existing vector store. At search time, entities from the query are matched against this collection and used to boost relevant memories. The boost is folded into the combined `score` on each result.
|
||||
|
||||
**Migration:**
|
||||
- Remove `enable_graph` / `enableGraph` from your config
|
||||
- Remove the `graph_store` / `graphStore` block — it is no longer read
|
||||
- Uninstall external graph drivers (neo4j, memgraph, etc.) if you were using them only for Mem0
|
||||
- No data migration is required. Built-in graph memory activates automatically on the next `add()` call.
|
||||
- Uninstall graph drivers (neo4j, memgraph, etc.) if you were using them only for Mem0
|
||||
- No data migration is required. Entity linking activates automatically on the next `add()` call.
|
||||
|
||||
<Warning>
|
||||
The old `relations` field on search results (populated by the external graph store) is no longer returned. Entity connections are now applied through retrieval ranking rather than exposed as a separate, directly traversable structure. If your application read or traversed the `relations` array, you will need to redesign that part against the new API.
|
||||
Graph relationships exposed via the old `relations` field on search results are no longer populated. Entity relationships are consumed indirectly through retrieval ranking, not exposed as a queryable graph structure. If your application depended on traversing graph relationships directly, you will need to redesign that part against the new API.
|
||||
</Warning>
|
||||
|
||||
## How the New Algorithm Works
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: "Platform: Migrating to the New Memory Algorithm"
|
||||
description: "Guide for Mem0 Platform users to adopt the new memory algorithm with single-pass extraction, built-in graph memory, and multi-signal retrieval."
|
||||
description: "Guide for Mem0 Platform users to adopt the new memory algorithm with single-pass extraction, entity linking, and multi-signal retrieval."
|
||||
icon: "arrow-right"
|
||||
iconType: "solid"
|
||||
---
|
||||
@@ -18,7 +18,8 @@ The new Mem0 memory algorithm is a ground-up redesign of how memories are extrac
|
||||
| **Extraction** | Two LLM passes (extract + merge) | Single-pass ADD-only (one LLM call) |
|
||||
| **Memory mutations** | ADD, UPDATE, DELETE | ADD only — nothing is overwritten or deleted |
|
||||
| **Agent-generated facts** | Often ignored | First-class, stored with equal weight |
|
||||
| **Graph memory** | External graph store (Neo4j, etc.) + manual setup | Built-in and automatic; entities extracted and linked across memories natively, no external store |
|
||||
| **Entity linking** | Not available | Entities extracted and linked across memories |
|
||||
| **Graph memory** | Separate graph store + dashboard visualization | Replaced by built-in entity linking, no graph visuals on platform dashboard |
|
||||
| **Retrieval** | Semantic (vector) only | Hybrid retrieval combining multiple signals |
|
||||
|
||||
## What This Means for Your Application
|
||||
@@ -248,18 +249,19 @@ await client.search("query", {
|
||||
For the full list of parameter changes across all SDKs, see the [OSS migration guide](/migration/oss-v2-to-v3#removed-parameters-reference).
|
||||
</Info>
|
||||
|
||||
## Graph Memory Is Now Built-In
|
||||
## Graph Memory → Entity Linking
|
||||
|
||||
Graph memory no longer requires an external graph database. It is now **native to the platform** and automatic. The changes:
|
||||
Graph memory has been replaced by **built-in entity linking**. The changes:
|
||||
|
||||
- **No external graph store to configure.** Previously, graph memory required a separate Neo4j (or similar) deployment. Mem0 now builds the graph itself from your memories, so there is nothing to provision and no connection strings to manage.
|
||||
- **Always on, no flag.** The `enable_graph` project setting is no longer needed; graph memory activates automatically. (The API parameter is now ignored if sent.)
|
||||
- **Connections power retrieval directly.** Entities (proper nouns, quoted text, compound noun phrases) are automatically extracted from every memory and linked across memories belonging to the same user. At search time, entities from the query are matched against the graph and used to boost ranking. The boost is folded into the combined `score` returned on each result.
|
||||
- **Graph visualizations removed from the platform dashboard.** The graph view in your project dashboard is no longer available.
|
||||
- **`enable_graph` project setting removed.** The toggle is gone from the dashboard; the API parameter is ignored.
|
||||
- **No external graph store to configure.** Previously graph memory required a separate Neo4j (or similar) deployment. Entity linking runs natively inside the platform — nothing to provision, no connection strings to manage.
|
||||
- **Entity linking is the native replacement.** Entities (proper nouns, quoted text, compound noun phrases) are automatically extracted from every memory and linked across memories belonging to the same user. At search time, entities from the query are matched against this index and used to boost ranking. The boost is folded into the combined `score` returned on each result.
|
||||
|
||||
**No migration work is required.** Graph memory activates automatically for all projects on the new algorithm. Existing memories are not re-processed, but any new memories you add are added to the graph going forward. See [Graph Memory](/platform/features/graph-memory) for how the built-in graph works.
|
||||
**No migration work is required.** Entity linking activates automatically for all projects on the new algorithm. Existing memories are not re-processed, but any new memories you add will be indexed for entity-based retrieval going forward.
|
||||
|
||||
<Note>
|
||||
If your application previously read graph relations from the API response (`relations` field on search results), note that this field is no longer populated. Entity connections are now applied through retrieval ranking rather than returned as a separate `relations` array.
|
||||
If your application previously read graph relations from the API response (`relations` field on search results), note that this field is no longer populated. Entity relationships are now consumed indirectly through retrieval ranking, not exposed as a separate graph structure.
|
||||
</Note>
|
||||
|
||||
## Migration Checklist
|
||||
|
||||
+8
-21
@@ -4861,7 +4861,8 @@
|
||||
"items": {
|
||||
"type": "object",
|
||||
"required": [
|
||||
"memory_id"
|
||||
"memory_id",
|
||||
"text"
|
||||
],
|
||||
"properties": {
|
||||
"memory_id": {
|
||||
@@ -4872,11 +4873,6 @@
|
||||
"text": {
|
||||
"type": "string",
|
||||
"description": "The new text content for the memory"
|
||||
},
|
||||
"metadata": {
|
||||
"type": "object",
|
||||
"additionalProperties": true,
|
||||
"description": "Updated metadata to associate with the memory."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -4952,27 +4948,18 @@
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"memories": {
|
||||
"memory_ids": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"memory_id": {
|
||||
"type": "string",
|
||||
"format": "uuid",
|
||||
"description": "The unique identifier of the memory to delete."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"memory_id"
|
||||
]
|
||||
"type": "string",
|
||||
"format": "uuid"
|
||||
},
|
||||
"maxItems": 1000,
|
||||
"description": "Array of memory objects to delete."
|
||||
"description": "Array of memory IDs to delete."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"memories"
|
||||
"memory_ids"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -6269,4 +6256,4 @@
|
||||
}
|
||||
},
|
||||
"x-original-swagger-version": "2.0"
|
||||
}
|
||||
}
|
||||
@@ -117,7 +117,7 @@ results_without_criteria = client.search(
|
||||
### Compare Results
|
||||
|
||||
### Search Results (with Criteria)
|
||||
```text
|
||||
```python
|
||||
[
|
||||
{"memory": "User feels refreshed and ready to take on anything on a beautiful sunny day", "score": 0.666, ...},
|
||||
{"memory": "User finally has time to draw something after a long time", "score": 0.616, ...},
|
||||
@@ -128,7 +128,7 @@ results_without_criteria = client.search(
|
||||
```
|
||||
|
||||
### Search Results (without Criteria)
|
||||
```text
|
||||
```python
|
||||
[
|
||||
{"memory": "User is happy today", "score": 0.607, ...},
|
||||
{"memory": "User feels refreshed and ready to take on anything on a beautiful sunny day", "score": 0.512, ...},
|
||||
|
||||
@@ -190,7 +190,7 @@ messages = [
|
||||
client.add(messages, user_id='alice')
|
||||
```
|
||||
|
||||
```text Memories with categories
|
||||
```python Memories with categories
|
||||
# Following categories will be created for the memories added
|
||||
Sometimes draws and sketches in free time (hobbies)
|
||||
Is quite athletic (sports)
|
||||
|
||||
@@ -5,10 +5,6 @@ description: Scope conversations by user, agent, app, and session so memories la
|
||||
|
||||
Mem0's Platform API lets you separate memories for different users, agents, and apps. By tagging each write and query with the right identifiers, you can prevent data from mixing between them, maintain clear audit trails, and control data retention.
|
||||
|
||||
<Note>
|
||||
**Entity IDs vs. graph entities.** This page covers the `user_id` / `agent_id` / `app_id` / `run_id` identifiers used to *scope* memories. These are different from the **graph entities** (the people, places, and concepts surfaced in [Graph Memory](/platform/features/graph-memory)).
|
||||
</Note>
|
||||
|
||||
<Tip icon="layers">
|
||||
Want the long-form tutorial? The <Link href="/cookbooks/essentials/entity-partitioning-playbook">Partition Memories by Entity</Link> cookbook walks through multi-agent storage, debugging, and cleanup step by step.
|
||||
</Tip>
|
||||
|
||||
@@ -1,93 +0,0 @@
|
||||
---
|
||||
title: "Graph Memory"
|
||||
description: "Mem0 Platform builds a native graph linking people, places, and concepts across your memories, with no external graph database to provision."
|
||||
icon: "circle-nodes"
|
||||
iconType: "solid"
|
||||
---
|
||||
|
||||
Mem0 Platform automatically organizes your memories into a **graph**: the **graph entities** mentioned across your memories (the people, places, organizations, and concepts they refer to) become nodes, and memories that share an entity are connected. This is how Mem0 reasons across separate facts, for example linking everything it knows about a person, a company, or a project, without you defining any schema.
|
||||
|
||||
Graph Memory is **built in**. There is no Neo4j, Memgraph, or other graph store to deploy, no connection strings to manage, and nothing to enable. It runs natively inside the platform and is always on.
|
||||
|
||||
<Info>
|
||||
**Graph Memory matters when…**
|
||||
- You ask entity-centric questions like "what do we know about Alice?" and expect facts pulled from many different conversations
|
||||
- Your app needs multi-hop recall, connecting a fact in one memory to a related fact in another
|
||||
- You previously used an external graph store and want the same cross-memory connections with zero infrastructure
|
||||
</Info>
|
||||
|
||||
<Note>
|
||||
**Graph entities vs. entity IDs.** The entities in your graph (people, places, and concepts extracted from memory text) are different from the *entity IDs* (`user_id`, `agent_id`, `app_id`, `run_id`) used to scope memories. Those are covered in [Entity-Scoped Memory](/platform/features/entity-scoped-memory).
|
||||
</Note>
|
||||
|
||||
<Note>
|
||||
Graph Memory is the native successor to Mem0's earlier graph store integration. Earlier versions connected an external graph database (Neo4j and others) and exposed a `relations` field. Mem0 now builds the graph itself from your memories. See [What changed from the external graph store](#what-changed-from-the-external-graph-store) below.
|
||||
</Note>
|
||||
|
||||
## How it works
|
||||
|
||||
Graph Memory is built and used across the two phases of the memory pipeline: **extraction** (when you add memories) and **retrieval** (when you search).
|
||||
|
||||
### 1. Entities become nodes
|
||||
|
||||
Every time you add a memory, Mem0 extracts the **entities** it contains: the proper nouns, names, and key phrases that identify a specific person, place, organization, product, or concept (for example *Alice*, *San Francisco*, *Acme Corp*, *the Q1 roadmap*). Each distinct entity is stored once and embedded, so entities that refer to the same thing can be matched even when they are phrased differently.
|
||||
|
||||
### 2. Shared entities become connections
|
||||
|
||||
When the same entity appears in more than one memory, those memories are **linked** through that entity. Over time this forms a graph: a web of entities, each connecting all the memories that mention it. The connections are derived directly from your data. There is no relationship schema to define and nothing to label by hand.
|
||||
|
||||
### 3. The graph powers retrieval
|
||||
|
||||
At search time, Mem0 extracts the entities from your query and matches them against the graph. Memories connected to those entities receive a ranking boost, which is combined with semantic (vector) and keyword (BM25) scores into the single `score` returned on each result.
|
||||
|
||||
This is what lets Mem0 answer entity-centric and multi-hop questions: a query about *Alice* surfaces facts about Alice that live in completely different memories, because the graph connects them. The connecting-facts-across-memories behavior contributes to Mem0's gains on multi-hop and temporal benchmarks. See [Memory Evaluation](/core-concepts/memory-evaluation).
|
||||
|
||||
<Info>
|
||||
Graph Memory affects **ranking**, not the response shape. Search results come back in the normal format with a combined `score`; there is no separate graph payload to parse.
|
||||
</Info>
|
||||
|
||||
## What's in the graph
|
||||
|
||||
| Element | What it is |
|
||||
| --- | --- |
|
||||
| **Graph entity** (node) | A distinct person, place, organization, product, or concept extracted from your memories (e.g. *Alice*, *Acme Corp*). Distinct from the user/agent/app/run *entity IDs* used to scope memories. |
|
||||
| **Memory node** | An individual memory (fact) stored for a user, agent, or session. |
|
||||
| **Connection** | A link between an entity and every memory that mentions it. Two entities are related when they co-occur in one or more memories. |
|
||||
|
||||
Graph Memory captures **which entities your memories are about and how they connect through shared context**. It does not assign typed, labeled relationships between entities (it won't, for example, record a "manages" edge from one person to another); connections are inferred from co-occurrence rather than declared. This is what makes it schema-free and zero-configuration.
|
||||
|
||||
## Availability
|
||||
|
||||
Graph Memory is **automatic and included on all plans**. It activates on the new memory algorithm with no flag, no configuration, and no external dependencies. You don't need to do anything to benefit from it.
|
||||
|
||||
```python
|
||||
from mem0 import MemoryClient
|
||||
|
||||
client = MemoryClient(api_key="your-api-key")
|
||||
|
||||
# Entities are extracted and linked into the graph automatically on add
|
||||
client.add(
|
||||
messages=[
|
||||
{"role": "user", "content": "I work at Acme Corp with Alice on the Q1 roadmap"}
|
||||
],
|
||||
user_id="jordan",
|
||||
)
|
||||
|
||||
# Entity matches from the query are used to connect and boost related memories
|
||||
results = client.search(
|
||||
query="who does jordan work with?",
|
||||
filters={"user_id": "jordan"},
|
||||
)
|
||||
```
|
||||
|
||||
## What changed from the external graph store
|
||||
|
||||
Earlier versions of Mem0 offered graph memory by connecting an **external graph database** (Neo4j, Memgraph, Kuzu, Apache AGE, or Neptune) through an `enable_graph` flag and a `graph_store` configuration block. That integration has been replaced by **native, built-in Graph Memory**:
|
||||
|
||||
- **No external graph store.** The graph is built inside Mem0 from your memories. There is nothing to provision or connect.
|
||||
- **Always on, all plans.** The `enable_graph` flag is no longer needed; Graph Memory is automatic. (If you still send the parameter, it is ignored.)
|
||||
- **Connections power retrieval directly.** Entity connections are folded into the combined `score` on each result. The standalone `relations` field that the external graph store returned is no longer populated. If your application read that field, see the migration guide below.
|
||||
|
||||
<Card title="Platform Migration Guide" icon="arrow-right" href="/migration/platform-v2-to-v3">
|
||||
Full details on the move to the new algorithm, including the `relations` field change.
|
||||
</Card>
|
||||
@@ -108,10 +108,10 @@ print(response)
|
||||
|
||||
```javascript JavaScript
|
||||
// Basic Export request
|
||||
const basicFilters = {"user_id": "alice"};
|
||||
const filters = {"user_id": "alice"};
|
||||
const response = await client.createMemoryExport({
|
||||
schema: json_schema,
|
||||
filters: basicFilters
|
||||
filters: filters
|
||||
});
|
||||
|
||||
// Export with custom instructions and additional filters
|
||||
@@ -124,16 +124,16 @@ const export_instructions = `
|
||||
`;
|
||||
|
||||
// For create operation, using only user_id filter as requested
|
||||
const exportFilters = {
|
||||
const filters = {
|
||||
"AND": [
|
||||
{"user_id": "alex"},
|
||||
{"created_at": {"gte": "2024-01-01"}}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
const responseWithInstructions = await client.createMemoryExport({
|
||||
schema: json_schema,
|
||||
filters: exportFilters,
|
||||
filters: filters,
|
||||
exportInstructions: export_instructions
|
||||
});
|
||||
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/react-syntax-highlighter": "^15.5.13",
|
||||
"@types/uuid": "^10.0.0",
|
||||
"ai": "^5.0.52",
|
||||
"ai": "^4.1.46",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"js-cookie": "^3.0.6",
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
"@radix-ui/react-scroll-area": "^1.2.0",
|
||||
"@radix-ui/react-select": "^2.1.2",
|
||||
"@radix-ui/react-slot": "^1.1.0",
|
||||
"ai": "^5.0.52",
|
||||
"ai": "4.1.42",
|
||||
"buffer": "^6.0.3",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"clsx": "^2.1.1",
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
"@radix-ui/react-scroll-area": "^1.2.0",
|
||||
"@radix-ui/react-select": "^2.1.2",
|
||||
"@radix-ui/react-slot": "^1.1.0",
|
||||
"ai": "^5.0.52",
|
||||
"ai": "4.1.42",
|
||||
"buffer": "^6.0.3",
|
||||
"class-variance-authority": "^0.7.0",
|
||||
"clsx": "^2.1.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mem0",
|
||||
"version": "0.2.11",
|
||||
"version": "0.2.10",
|
||||
"description": "Persistent memory for Claude Code. Remembers decisions, patterns, and preferences across sessions.",
|
||||
"author": {
|
||||
"name": "Mem0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mem0",
|
||||
"version": "0.2.11",
|
||||
"version": "0.2.10",
|
||||
"description": "Persistent memory for Codex. Remembers decisions, patterns, and preferences across sessions.",
|
||||
"author": {
|
||||
"name": "Mem0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mem0",
|
||||
"version": "0.2.11",
|
||||
"version": "0.2.10",
|
||||
"description": "Mem0 memory layer for AI applications. Add persistent memory, personalization, and semantic search using the Mem0 Platform MCP server.",
|
||||
"author": {
|
||||
"name": "Mem0",
|
||||
|
||||
@@ -8,30 +8,17 @@ All notable changes to the `@mem0/opencode-plugin` will be documented in this fi
|
||||
|
||||
- **Memory tools are now native OpenCode tools** registered via the `@opencode-ai/plugin` `tool()` helper and backed by the `mem0ai` SDK directly. The plugin no longer registers or depends on the remote MCP server (`mcp.mem0.ai`); the bundled `opencode.json` and the regex-based MCP call interception have been removed. Tools: `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`, plus a `get_event_status` helper for async-write status.
|
||||
- **Skills load via the `config` hook (`skills.paths`)** instead of being copied into the project's `.opencode/` directory on startup. The `installSkills()` filesystem copy and the `cli.ts` installer (`mem0-opencode` bin) have been removed — install with `opencode plugin @mem0/opencode-plugin`.
|
||||
- **Trimmed to 9 focused skills** (`context-loader`, `dream`, `forget`, `status`, `search`, `scope`, `pin`, `remember`, `tour`). Removed `import`, `export`, `memory-reviewer`, `mem0` (SDK reference), `list-projects`, `stats`, and `onboard`. The old stateful `switch-project` skill is superseded by the project/session/global scope model and the new `/mem0-scope` skill.
|
||||
- **Trimmed to 8 focused skills** (`context-loader`, `dream`, `forget`, `health`, `peek`, `pin`, `remember`, `tour`). Removed `import`, `export`, `memory-reviewer`, `mem0` (SDK reference), `list-projects`, `switch-project`, `stats`, and `onboard`.
|
||||
|
||||
### Added
|
||||
|
||||
- **Expanded telemetry to the full shared `plugin.*` schema.** In addition to `plugin.session_start` and `plugin.tool_use`, the plugin now emits `plugin.user_prompt`, `plugin.bash_error`, `plugin.pre_compact`, and `plugin.session_stop`. `tool_use` now fires from inside each native tool. Every event also carries `project_hash` (anonymized `sha256(app_id)`) and `os_version`, matching the editor plugin's `telemetry.py`.
|
||||
- **Auto-dream — gated automatic memory consolidation** (ported from the pi-agent plugin). When the time (`minHours`, default 24), session-count (`minSessions`, default 5), and memory-count (`minMemories`, default 20) gates all pass, the plugin injects a consolidation protocol so the agent merges duplicates, drops stale/sensitive entries, and rewrites vague ones before answering. A filesystem lock (`~/.mem0/mem0-dream.lock`) prevents concurrent sessions from dreaming at once, and completion resets the gates. Tune via the `dream` block in `~/.mem0/settings.json`; disable with `MEM0_DREAM=false`. Emits `plugin.dream_triggered` / `plugin.dream_completed`.
|
||||
- **Memory `scope` — per-call parameter and a persistent default.** `search_memories`, `get_memories`, `add_memory`, and `delete_all_memories` accept an optional `scope`: `"project"` (this repo, default), `"session"` (this run, adds `run_id`), or `"global"` (across all the user's projects — `app_id: "*"` for reads, user-wide for writes). The new **`/mem0-scope` skill** views and changes the *default* scope (used when no scope is passed), persisted to `~/.mem0/settings.json` (`default_scope`) and read **fresh on each memory operation** so changes apply immediately — no restart. `add_memory` / `search_memories` / `get_memories` honor the default (an explicit `scope`, `filters`, or `agent_id` still wins; a `project` default preserves prior behavior, including `global_search`).
|
||||
|
||||
### Changed
|
||||
|
||||
- **`/mem0-status` now reports the active default scope and auto-dream readiness.** It reads `default_scope` from `~/.mem0/settings.json` (falling back to `project`) and shows the auto-dream gate progress (sessions / memories / time vs. thresholds) so it's clear *why* a consolidation hasn't run yet.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Skills load in place via `skills.paths` — no copying.** The `config` hook adds the plugin's own `opencode-skills/` directory to OpenCode's `skills.paths`, so OpenCode discovers the skills directly from the linked/installed plugin package (recursive `**/SKILL.md` scan). The `installSkills()` step that copied skills into `~/.config/opencode/skills/` (and the legacy `~/.opencode/skills/`) and its version-marker gating are removed — the plugin no longer writes into those directories or creates `~/.opencode`. The `config` hook still registers the `/mem0-*` slash commands via `config.command`: OpenCode's TUI slash menu is built from `config.command`, and skills on `skills.paths` are available to the agent's skill tool but do not appear as slash commands on their own. Skill dir names are `mem0-<skill>` (matching `^[a-z0-9]+(-[a-z0-9]+)*$`); commands are `/mem0-<skill>`.
|
||||
- **Robust project-id (`app_id`) detection.** Parsed from the git remote's `owner/repo` — handling https, scp-style ssh, and **custom ssh host aliases** like `git@github.com-work:owner/repo.git` — falling back to the git repo's **root directory name** (not the cwd, which may be a sub-directory or your home dir), then the cwd. Fixes the project showing as your username/home when OpenCode was launched outside the repo root.
|
||||
- **Auto-dream visibility + robustness.** When auto-dream doesn't fire, the plugin logs the blocking gate (e.g. `auto-dream waiting — memories: 3 < 20`), and `/mem0-status` surfaces the same gate progress. The session-start memory count is parsed defensively (handles both paginated `{count}` and bare-array SDK responses) so the memory gate evaluates correctly.
|
||||
- **Error-pattern lookup** in `tool.execute.after` no longer issues two identical `mem0.search()` calls; it now performs a single `topK: 6` search.
|
||||
- Corrected the documented system-prompt hook name from `experimental.chat.system.transform` to the actual `experimental.chat.messages.transform`.
|
||||
|
||||
### Safety
|
||||
|
||||
- **`delete_all_memories` deliberately ignores the default scope.** Deleting user-wide always requires an explicit `scope="global"`, so raising the default to `global` can never turn a routine cleanup into a cross-project wipe.
|
||||
|
||||
## 0.1.3 — File-context injection, session summaries & activity timeline, anonymous telemetry
|
||||
|
||||
### Added
|
||||
|
||||
@@ -30,7 +30,7 @@ Restart OpenCode.
|
||||
|-----------|-------------|
|
||||
| **9 Native Memory Tools** | `add_memory`, `search_memories`, `get_memories`, `update_memory`, `delete_memory`, and more — registered as OpenCode tools, backed by the `mem0ai` SDK (no MCP server required) |
|
||||
| **Lifecycle Hooks** | Auto-search on session start and every prompt, error memory lookup, compaction context, secret redaction |
|
||||
| **9 Skills** | `/mem0-remember`, `/mem0-tour`, `/mem0-search`, `/mem0-status`, `/mem0-scope`, `/mem0-dream`, `/mem0-forget`, `/mem0-pin`, `/mem0-context-loader` — discovered in place from the plugin via OpenCode's `skills.paths` |
|
||||
| **8 Skills** | `/mem0:remember`, `/mem0:tour`, `/mem0:peek`, `/mem0:health`, `/mem0:dream`, `/mem0:forget`, `/mem0:pin`, `/mem0:context-loader` |
|
||||
|
||||
## Hooks
|
||||
|
||||
@@ -38,7 +38,7 @@ Pure TypeScript — no Python, no shell scripts. Memory operations are native Op
|
||||
|
||||
| Hook | Event | What it does |
|
||||
|------|-------|-------------|
|
||||
| **Config** | `config` | Registers the `/mem0-*` slash commands (via `config.command`) and adds the plugin's own `opencode-skills/` dir to OpenCode's `skills.paths` for in-place skill discovery — no copying into `~/.config/opencode/skills` |
|
||||
| **Config** | `config` | Registers the bundled skills (`skills.paths`) and `/mem0:*` slash commands at startup |
|
||||
| **Chat message** | `chat.message` | Loads prior memories on session start, searches relevant memories before each prompt, auto-captures learnings periodically |
|
||||
| **Pre-tool** | `tool.execute.before` | Blocks MEMORY.md writes, steering them to the `add_memory` tool |
|
||||
| **Post-tool** | `tool.execute.after` | Scans bash errors and pre-fetches related memories |
|
||||
@@ -60,28 +60,6 @@ Pure TypeScript — no Python, no shell scripts. Memory operations are native Op
|
||||
| `delete_entities` | Delete an entity and its memories |
|
||||
| `list_entities` | List users/agents/apps stored in Mem0 |
|
||||
|
||||
## Memory scope
|
||||
|
||||
Every memory tool accepts an optional `scope`, and you can set the **default**
|
||||
scope (used when none is passed) with the `/mem0-scope` skill:
|
||||
|
||||
| Scope | Reads | Writes |
|
||||
|-------|-------|--------|
|
||||
| `project` (default) | this repo (`user_id` + `app_id`) | this repo |
|
||||
| `session` | this run (adds `run_id`) | this run |
|
||||
| `global` | all your projects (`app_id="*"`) | user-wide (drops `app_id`) |
|
||||
|
||||
```
|
||||
/mem0-scope # show the current default scope
|
||||
/mem0-scope global # save & search across all your projects by default
|
||||
/mem0-scope project # back to repo-only (default)
|
||||
```
|
||||
|
||||
The default persists in `~/.mem0/settings.json` (`default_scope`) and is read
|
||||
fresh on each memory operation, so a change applies immediately — no restart.
|
||||
`delete_all_memories` always requires an explicit `scope="global"` to delete
|
||||
user-wide, so changing the default can't trigger a cross-project wipe.
|
||||
|
||||
## Verify
|
||||
|
||||
Start OpenCode and ask: *"Search my memories for recent decisions"*
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"name": "@mem0/opencode-plugin",
|
||||
"dependencies": {
|
||||
"@opencode-ai/plugin": "^1.0.162",
|
||||
"mem0ai": "^3.0.8",
|
||||
"mem0ai": "^3.0.7",
|
||||
},
|
||||
"devDependencies": {
|
||||
"bun-types": ">=1.3.14",
|
||||
@@ -462,7 +462,7 @@
|
||||
|
||||
"md5": ["md5@2.3.0", "", { "dependencies": { "charenc": "0.0.2", "crypt": "0.0.2", "is-buffer": "~1.1.6" } }, "sha512-T1GITYmFaKuO91vxyoQMFETst+O71VUPEU3ze5GNzDm0OWdP8v1ziTaAEPUr/3kLsY3Sftgz242A1SetQiDL7g=="],
|
||||
|
||||
"mem0ai": ["mem0ai@3.0.8", "", { "dependencies": { "axios": "^1.16.0", "openai": "^4.93.0", "uuid": "^11.1.1", "zod": "^3.24.1" }, "peerDependencies": { "@anthropic-ai/sdk": "^0.40.1", "@azure/identity": "^4.0.0", "@azure/search-documents": "^12.0.0", "@cloudflare/workers-types": "^4.20250504.0", "@google/genai": "^1.40.0", "@langchain/core": "^1.1.47", "@mistralai/mistralai": "^1.5.2", "@qdrant/js-client-rest": "^1.18.0", "@supabase/supabase-js": "^2.49.1", "@types/jest": "29.5.14", "@types/pg": "8.11.0", "better-sqlite3": "^12.6.2", "cloudflare": "^4.2.0", "compromise": "^14.0.0", "groq-sdk": "0.3.0", "natural": "^8.0.1", "ollama": "^0.5.14", "pg": "8.11.3", "redis": "^4.6.13" } }, "sha512-6lvHGOYc/Z2r0JEulS559MVPOOiOtfAqG02VESDY7b0WAZwsmgLWAjQkbmWnD9fbXQQ3QvSpSaVx1q6Ex01eLQ=="],
|
||||
"mem0ai": ["mem0ai@3.0.7", "", { "dependencies": { "axios": "^1.16.0", "openai": "^4.93.0", "uuid": "9.0.1", "zod": "^3.24.1" }, "peerDependencies": { "@anthropic-ai/sdk": "^0.40.1", "@azure/identity": "^4.0.0", "@azure/search-documents": "^12.0.0", "@cloudflare/workers-types": "^4.20250504.0", "@google/genai": "^1.40.0", "@langchain/core": "^1.1.47", "@mistralai/mistralai": "^1.5.2", "@qdrant/js-client-rest": "^1.18.0", "@supabase/supabase-js": "^2.49.1", "@types/jest": "29.5.14", "@types/pg": "8.11.0", "better-sqlite3": "^12.6.2", "cloudflare": "^4.2.0", "compromise": "^14.0.0", "groq-sdk": "0.3.0", "natural": "^8.0.1", "ollama": "^0.5.14", "pg": "8.11.3", "redis": "^4.6.13" } }, "sha512-CUHzX7DyeKTHcI3aDsSqY9LXTD7GcFxf988796TuOa4yJgGuF2Xd2NROcBhVFRo3r9y8fVmbo3c5TF9jv1KlKw=="],
|
||||
|
||||
"memjs": ["memjs@1.3.2", "", {}, "sha512-qUEg2g8vxPe+zPn09KidjIStHPtoBO8Cttm8bgJFWWabbsjQ9Av9Ky+6UcvKx6ue0LLb/LEhtcyQpRyKfzeXcg=="],
|
||||
|
||||
@@ -652,7 +652,7 @@
|
||||
|
||||
"util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
|
||||
|
||||
"uuid": ["uuid@11.1.1", "", { "bin": { "uuid": "dist/esm/bin/uuid" } }, "sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ=="],
|
||||
"uuid": ["uuid@9.0.1", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="],
|
||||
|
||||
"web-streams-polyfill": ["web-streams-polyfill@3.3.3", "", {}, "sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw=="],
|
||||
|
||||
|
||||
@@ -1,100 +0,0 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
|
||||
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import {
|
||||
loadDreamConfig,
|
||||
incrementSessionCount,
|
||||
checkCheapGates,
|
||||
checkMemoryGate,
|
||||
acquireDreamLock,
|
||||
releaseDreamLock,
|
||||
recordDreamCompletion,
|
||||
DREAM_DEFAULTS,
|
||||
DREAM_PROTOCOL,
|
||||
} from "./dream";
|
||||
|
||||
let dir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
dir = mkdtempSync(join(tmpdir(), "mem0-dream-"));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
try {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
delete process.env.MEM0_DREAM;
|
||||
});
|
||||
|
||||
describe("auto-dream gates", () => {
|
||||
test("memory gate passes at >= minMemories, fails below", () => {
|
||||
expect(checkMemoryGate(DREAM_DEFAULTS.minMemories, {}).pass).toBe(true);
|
||||
expect(checkMemoryGate(DREAM_DEFAULTS.minMemories - 1, {}).pass).toBe(false);
|
||||
});
|
||||
|
||||
test("cheap gates: fresh state blocks on session count, passes after enough sessions", () => {
|
||||
// Fresh state: time gate passes (lastConsolidatedAt=0), but 0 sessions blocks.
|
||||
expect(checkCheapGates(dir, {}).proceed).toBe(false);
|
||||
for (let i = 0; i < DREAM_DEFAULTS.minSessions; i++) {
|
||||
incrementSessionCount(dir, `ses_${i}`);
|
||||
}
|
||||
expect(checkCheapGates(dir, {}).proceed).toBe(true);
|
||||
});
|
||||
|
||||
test("incrementSessionCount only counts distinct session ids", () => {
|
||||
incrementSessionCount(dir, "ses_a");
|
||||
incrementSessionCount(dir, "ses_a");
|
||||
incrementSessionCount(dir, "ses_a");
|
||||
expect(checkCheapGates(dir, { minHours: 0 }).reason).toContain("sessions: 1");
|
||||
});
|
||||
|
||||
test("recordDreamCompletion resets gates (recent time blocks again)", () => {
|
||||
for (let i = 0; i < 6; i++) incrementSessionCount(dir, `ses_${i}`);
|
||||
expect(checkCheapGates(dir, {}).proceed).toBe(true);
|
||||
recordDreamCompletion(dir);
|
||||
const r = checkCheapGates(dir, {});
|
||||
expect(r.proceed).toBe(false);
|
||||
expect(r.reason).toContain("time");
|
||||
});
|
||||
|
||||
test("dream lock is exclusive and reclaimable after release", () => {
|
||||
expect(acquireDreamLock(dir)).toBe(true);
|
||||
expect(acquireDreamLock(dir)).toBe(false);
|
||||
releaseDreamLock(dir);
|
||||
expect(acquireDreamLock(dir)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("dream config", () => {
|
||||
test("defaults when no settings file", () => {
|
||||
const cfg = loadDreamConfig(dir);
|
||||
expect(cfg.enabled).toBe(true);
|
||||
expect(cfg.auto).toBe(true);
|
||||
expect(cfg.minMemories).toBe(DREAM_DEFAULTS.minMemories);
|
||||
});
|
||||
|
||||
test("MEM0_DREAM=false force-disables", () => {
|
||||
process.env.MEM0_DREAM = "false";
|
||||
expect(loadDreamConfig(dir).enabled).toBe(false);
|
||||
});
|
||||
|
||||
test("settings.json dream block overrides defaults", () => {
|
||||
writeFileSync(
|
||||
join(dir, "settings.json"),
|
||||
JSON.stringify({ dream: { minMemories: 99, auto: false } }),
|
||||
);
|
||||
const cfg = loadDreamConfig(dir);
|
||||
expect(cfg.minMemories).toBe(99);
|
||||
expect(cfg.auto).toBe(false);
|
||||
expect(cfg.enabled).toBe(true);
|
||||
});
|
||||
|
||||
test("protocol uses native tools, not the MCP tool", () => {
|
||||
expect(DREAM_PROTOCOL).toContain("get_memories");
|
||||
expect(DREAM_PROTOCOL).toContain("add_memory");
|
||||
expect(DREAM_PROTOCOL).not.toContain("mem0_memory");
|
||||
});
|
||||
});
|
||||
@@ -1,225 +0,0 @@
|
||||
/**
|
||||
* Auto-dream: gated automatic memory consolidation for the Mem0 OpenCode plugin.
|
||||
*
|
||||
* Ported from the (stable) pi-agent plugin's dream module and adapted to
|
||||
* OpenCode's hook model. When the cheap gates (time since last consolidation +
|
||||
* sessions since) and the memory-count gate all pass, the plugin injects the
|
||||
* DREAM_PROTOCOL into the agent's context so it consolidates memories (merge
|
||||
* duplicates, drop stale/sensitive entries, rewrite vague ones) before
|
||||
* answering. A filesystem lock prevents concurrent sessions from dreaming at
|
||||
* once, and completion is recorded so it won't re-trigger until the next cycle.
|
||||
*
|
||||
* State + lock live in ~/.mem0/ alongside settings.json. Opt out with
|
||||
* MEM0_DREAM=false, or tune via the `dream` block in ~/.mem0/settings.json.
|
||||
*/
|
||||
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
export interface DreamConfig {
|
||||
enabled: boolean;
|
||||
auto: boolean;
|
||||
minHours: number;
|
||||
minSessions: number;
|
||||
minMemories: number;
|
||||
}
|
||||
|
||||
interface DreamState {
|
||||
lastConsolidatedAt: number;
|
||||
sessionsSince: number;
|
||||
lastSessionId: string | null;
|
||||
}
|
||||
|
||||
interface DreamLock {
|
||||
pid: number;
|
||||
startedAt: number;
|
||||
}
|
||||
|
||||
const LOCK_STALE_MS = 60 * 60 * 1000;
|
||||
|
||||
export const DREAM_DEFAULTS: DreamConfig = {
|
||||
enabled: true,
|
||||
auto: true,
|
||||
minHours: 24,
|
||||
minSessions: 5,
|
||||
minMemories: 20,
|
||||
};
|
||||
|
||||
function statePath(stateDir: string): string {
|
||||
return join(stateDir, "mem0-dream-state.json");
|
||||
}
|
||||
|
||||
function lockPath(stateDir: string): string {
|
||||
return join(stateDir, "mem0-dream.lock");
|
||||
}
|
||||
|
||||
function ensureDir(dir: string): void {
|
||||
try {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
} catch {
|
||||
/* exists */
|
||||
}
|
||||
}
|
||||
|
||||
function readState(stateDir: string): DreamState {
|
||||
try {
|
||||
return JSON.parse(readFileSync(statePath(stateDir), "utf-8")) as DreamState;
|
||||
} catch {
|
||||
return { lastConsolidatedAt: 0, sessionsSince: 0, lastSessionId: null };
|
||||
}
|
||||
}
|
||||
|
||||
function writeState(stateDir: string, state: DreamState): void {
|
||||
ensureDir(stateDir);
|
||||
writeFileSync(statePath(stateDir), JSON.stringify(state, null, 2));
|
||||
}
|
||||
|
||||
/**
|
||||
* Load dream config from ~/.mem0/settings.json (`dream` block), applying
|
||||
* defaults. MEM0_DREAM=false (or 0/no/off) force-disables regardless.
|
||||
*/
|
||||
export function loadDreamConfig(settingsDir: string): DreamConfig {
|
||||
let envEnabled: boolean | undefined;
|
||||
const env = process.env.MEM0_DREAM;
|
||||
if (env !== undefined) {
|
||||
const s = env.toLowerCase();
|
||||
envEnabled = s !== "false" && s !== "0" && s !== "no" && s !== "off";
|
||||
}
|
||||
|
||||
let cfg: DreamConfig = { ...DREAM_DEFAULTS };
|
||||
try {
|
||||
const sp = join(settingsDir, "settings.json");
|
||||
if (existsSync(sp)) {
|
||||
const settings = JSON.parse(readFileSync(sp, "utf-8"));
|
||||
const d = settings?.dream;
|
||||
if (d && typeof d === "object") {
|
||||
cfg = {
|
||||
enabled: typeof d.enabled === "boolean" ? d.enabled : cfg.enabled,
|
||||
auto: typeof d.auto === "boolean" ? d.auto : cfg.auto,
|
||||
minHours: typeof d.minHours === "number" ? d.minHours : cfg.minHours,
|
||||
minSessions: typeof d.minSessions === "number" ? d.minSessions : cfg.minSessions,
|
||||
minMemories: typeof d.minMemories === "number" ? d.minMemories : cfg.minMemories,
|
||||
};
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* defaults */
|
||||
}
|
||||
|
||||
if (envEnabled !== undefined) cfg.enabled = envEnabled;
|
||||
return cfg;
|
||||
}
|
||||
|
||||
/** Count a new session toward the dream gate (once per distinct sessionId). */
|
||||
export function incrementSessionCount(stateDir: string, sessionId: string): void {
|
||||
const state = readState(stateDir);
|
||||
if (state.lastSessionId !== sessionId) {
|
||||
state.sessionsSince++;
|
||||
state.lastSessionId = sessionId;
|
||||
writeState(stateDir, state);
|
||||
}
|
||||
}
|
||||
|
||||
/** Cheap gates that don't need an API call: time since last + sessions since. */
|
||||
export function checkCheapGates(
|
||||
stateDir: string,
|
||||
config: Partial<DreamConfig>,
|
||||
): { proceed: boolean; reason?: string } {
|
||||
const minHours = config.minHours ?? DREAM_DEFAULTS.minHours;
|
||||
const minSessions = config.minSessions ?? DREAM_DEFAULTS.minSessions;
|
||||
const state = readState(stateDir);
|
||||
|
||||
const hoursSince = (Date.now() - state.lastConsolidatedAt) / 3_600_000;
|
||||
if (hoursSince < minHours) {
|
||||
return { proceed: false, reason: `time: ${hoursSince.toFixed(1)}h < ${minHours}h` };
|
||||
}
|
||||
if (state.sessionsSince < minSessions) {
|
||||
return { proceed: false, reason: `sessions: ${state.sessionsSince} < ${minSessions}` };
|
||||
}
|
||||
return { proceed: true };
|
||||
}
|
||||
|
||||
/** Memory-count gate (uses the count already fetched at session init). */
|
||||
export function checkMemoryGate(
|
||||
memoryCount: number,
|
||||
config: Partial<DreamConfig>,
|
||||
): { pass: boolean; reason?: string } {
|
||||
const minMemories = config.minMemories ?? DREAM_DEFAULTS.minMemories;
|
||||
if (memoryCount < minMemories) {
|
||||
return { pass: false, reason: `memories: ${memoryCount} < ${minMemories}` };
|
||||
}
|
||||
return { pass: true };
|
||||
}
|
||||
|
||||
/** Acquire an exclusive dream lock (stale locks > 1h are reclaimed). */
|
||||
export function acquireDreamLock(stateDir: string): boolean {
|
||||
ensureDir(stateDir);
|
||||
const lp = lockPath(stateDir);
|
||||
|
||||
try {
|
||||
const lock = JSON.parse(readFileSync(lp, "utf-8")) as DreamLock;
|
||||
if (Date.now() - lock.startedAt < LOCK_STALE_MS) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
unlinkSync(lp);
|
||||
} catch {
|
||||
/* race ok */
|
||||
}
|
||||
} catch {
|
||||
/* no lock file */
|
||||
}
|
||||
|
||||
const lock: DreamLock = { pid: process.pid, startedAt: Date.now() };
|
||||
try {
|
||||
writeFileSync(lp, JSON.stringify(lock), { flag: "wx" });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function releaseDreamLock(stateDir: string): void {
|
||||
try {
|
||||
unlinkSync(lockPath(stateDir));
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
}
|
||||
|
||||
/** Reset the gates after a successful consolidation. */
|
||||
export function recordDreamCompletion(stateDir: string): void {
|
||||
const state = readState(stateDir);
|
||||
state.lastConsolidatedAt = Date.now();
|
||||
state.sessionsSince = 0;
|
||||
state.lastSessionId = null;
|
||||
writeState(stateDir, state);
|
||||
}
|
||||
|
||||
/**
|
||||
* Consolidation protocol injected into the agent context when a dream is
|
||||
* triggered. Uses the plugin's native OpenCode memory tools (get_memories /
|
||||
* add_memory / delete_memory) rather than an MCP tool.
|
||||
*/
|
||||
export const DREAM_PROTOCOL = `<mem0-dream>
|
||||
You are running memory consolidation. Complete these steps using the mem0 memory tools (get_memories, add_memory, delete_memory):
|
||||
|
||||
1. ORIENT — Call get_memories to list all memories. Count by category. Note oldest/newest.
|
||||
|
||||
2. GATHER TARGETS — Review each memory. Classify as:
|
||||
- DELETE: sensitive information (API keys, passwords, tokens), expired/stale entries, noise, redundant operational details
|
||||
- MERGE: near-duplicates (same fact stated differently). Keep the better-worded one, delete the other.
|
||||
- REWRITE: vague, first-person, or poorly-categorized entries. add_memory with improved text, then delete_memory the old one.
|
||||
- KEEP: everything else.
|
||||
Skip any memory starting with "[PINNED]".
|
||||
|
||||
3. CONSOLIDATE — Execute the changes:
|
||||
- Delete stale/duplicate entries with delete_memory
|
||||
- For merges: add_memory the merged text, delete_memory both originals
|
||||
- For rewrites: add_memory the improved version, delete_memory the original
|
||||
|
||||
4. REPORT — Summarize: how many reviewed, deleted, merged, rewritten, final count.
|
||||
|
||||
Quality targets: zero sensitive data stored, zero duplicates, all entries are atomic (one fact each), 15-50 words each.
|
||||
After consolidation, respond to the user's message normally.
|
||||
</mem0-dream>`;
|
||||
@@ -8,23 +8,12 @@ import {MemoryClient} from "mem0ai";
|
||||
import {userInfo} from "os";
|
||||
import {basename, resolve, dirname} from "path";
|
||||
import {randomBytes} from "crypto";
|
||||
import {existsSync, mkdirSync, readFileSync, writeFileSync, readdirSync} from "fs";
|
||||
import {existsSync, mkdirSync, readFileSync, writeFileSync} from "fs";
|
||||
import {homedir} from "os";
|
||||
import {join} from "path";
|
||||
import {createHash} from "crypto";
|
||||
import {readdirSync} from "node:fs";
|
||||
import {captureEvent} from "./telemetry";
|
||||
import {
|
||||
loadDreamConfig,
|
||||
incrementSessionCount,
|
||||
checkCheapGates,
|
||||
checkMemoryGate,
|
||||
acquireDreamLock,
|
||||
releaseDreamLock,
|
||||
recordDreamCompletion,
|
||||
DREAM_PROTOCOL,
|
||||
} from "./dream";
|
||||
import {asScope, scopeSearchFilters, scopeWriteParams, resolveDefaultScope, SCOPE_GUIDANCE, type Scope} from "./scope";
|
||||
import {parseProjectFromRemote} from "./project";
|
||||
|
||||
async function getUserId(): Promise<string> {
|
||||
if (process.env.MEM0_USER_ID) return process.env.MEM0_USER_ID;
|
||||
@@ -37,20 +26,11 @@ async function getUserId(): Promise<string> {
|
||||
|
||||
async function getProjectId($: any): Promise<string> {
|
||||
if (process.env.MEM0_APP_ID) return process.env.MEM0_APP_ID;
|
||||
// Prefer the git remote's owner/repo — stable across clones, worktrees, and
|
||||
// sub-directories (handles https + ssh, incl. custom host aliases).
|
||||
try {
|
||||
const r = await $`git remote get-url origin`.quiet();
|
||||
const project = parseProjectFromRemote(r.stdout.toString());
|
||||
if (project) return project;
|
||||
} catch {
|
||||
}
|
||||
// No usable remote: use the git repo ROOT dir name, not cwd (which may be a
|
||||
// sub-directory, or your home dir if OpenCode was launched outside a repo).
|
||||
try {
|
||||
const r = await $`git rev-parse --show-toplevel`.quiet();
|
||||
const top = r.stdout.toString().trim();
|
||||
if (top) return basename(top);
|
||||
const remote = r.stdout.toString().trim();
|
||||
const m = remote.match(/[:/]([^/]+\/[^/]+?)(?:\.git)?$/);
|
||||
if (m) return m[1].replace("/", "-");
|
||||
} catch {
|
||||
}
|
||||
return basename(process.cwd());
|
||||
@@ -94,28 +74,15 @@ function redact(text: string): string {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Read & parse `~/.mem0/settings.json`, returning {} when missing/invalid. */
|
||||
function loadSettings(): Record<string, unknown> {
|
||||
function loadGlobalSearch(): boolean {
|
||||
try {
|
||||
const settingsPath = join(homedir(), ".mem0", "settings.json");
|
||||
if (!existsSync(settingsPath)) return {};
|
||||
return JSON.parse(readFileSync(settingsPath, "utf8"));
|
||||
if (!existsSync(settingsPath)) return false;
|
||||
const settings = JSON.parse(readFileSync(settingsPath, "utf8"));
|
||||
return settings.global_search === true;
|
||||
} catch {
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
function loadGlobalSearch(): boolean {
|
||||
return loadSettings().global_search === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The user's persisted default memory scope (set via the `mem0-scope` skill).
|
||||
* Read fresh so a scope change takes effect on the next memory operation without
|
||||
* restarting OpenCode. Defaults to "project".
|
||||
*/
|
||||
function loadDefaultScope(): Scope {
|
||||
return resolveDefaultScope(loadSettings());
|
||||
return false;
|
||||
}
|
||||
|
||||
const CODING_CATEGORIES = [
|
||||
@@ -289,12 +256,6 @@ const Mem0Plugin: Plugin = async (ctx) => {
|
||||
|
||||
const systemContext: string[] = [];
|
||||
|
||||
// Auto-dream: gated memory-consolidation state (ported from the pi-agent plugin).
|
||||
const mem0StateDir = join(homedir(), ".mem0");
|
||||
const dreamConfig = loadDreamConfig(mem0StateDir);
|
||||
let dreamTriggered = false;
|
||||
let dreamWriteSeen = false;
|
||||
|
||||
// Emit a session_stop telemetry event once when the process winds down.
|
||||
let sessionStopSent = false;
|
||||
const emitSessionStop = () => {
|
||||
@@ -306,16 +267,6 @@ const Mem0Plugin: Plugin = async (ctx) => {
|
||||
apiKey,
|
||||
appId,
|
||||
);
|
||||
// Finish an in-flight auto-dream: record completion if the agent consolidated,
|
||||
// and always release the lock so the next eligible session can dream.
|
||||
if (dreamTriggered) {
|
||||
if (dreamWriteSeen) {
|
||||
recordDreamCompletion(mem0StateDir);
|
||||
captureEvent("dream_completed", {}, apiKey, appId);
|
||||
}
|
||||
releaseDreamLock(mem0StateDir);
|
||||
dreamTriggered = false;
|
||||
}
|
||||
};
|
||||
try {
|
||||
process.on("beforeExit", emitSessionStop);
|
||||
@@ -326,12 +277,9 @@ const Mem0Plugin: Plugin = async (ctx) => {
|
||||
Promise.resolve().then(() => autoSetupCategories(mem0, apiKey)).catch(() => {
|
||||
});
|
||||
|
||||
// Register a `/mem0-<skill>` slash command per bundled skill. OpenCode's TUI
|
||||
// slash menu is populated from `config.command` entries (skills discovered via
|
||||
// `skills.paths` are available to the agent's skill tool but do NOT appear as
|
||||
// slash commands), so this is what makes `/mem0-scope` etc. typeable.
|
||||
function registerCommands(skillsDir: string, opencodeConfig: any) {
|
||||
for (const entry of readdirSync(skillsDir, {withFileTypes: true})) {
|
||||
const skillEntries = readdirSync(skillsDir, {withFileTypes: true});
|
||||
for (const entry of skillEntries) {
|
||||
if (!entry.isDirectory()) continue;
|
||||
const skillMd = resolve(skillsDir, entry.name, "SKILL.md");
|
||||
if (!existsSync(skillMd)) continue;
|
||||
@@ -345,8 +293,8 @@ const Mem0Plugin: Plugin = async (ctx) => {
|
||||
}
|
||||
|
||||
opencodeConfig.command ??= {};
|
||||
opencodeConfig.command[entry.name] = {
|
||||
template: `Load and execute the \`${entry.name}\` skill.
|
||||
opencodeConfig.command[`mem0:${entry.name}`] = {
|
||||
template: `Load and execute the \`mem0:${entry.name}\` skill.
|
||||
|
||||
Use the mem0 memory tools (add_memory, search_memories, get_memories, get_memory, update_memory, delete_memory, delete_all_memories, delete_entities, list_entities, get_event_status) as instructed by the skill.
|
||||
|
||||
@@ -360,19 +308,6 @@ Identity context (resolved at plugin startup):
|
||||
}
|
||||
}
|
||||
|
||||
// Resolve read filters for the memory tools. Precedence: an explicit `scope`
|
||||
// arg wins; then explicit `filters`/`agent_id`; otherwise fall back to the
|
||||
// user's persisted default scope (read fresh so /mem0-scope applies at once).
|
||||
// A "project" default preserves the existing behavior, including global_search.
|
||||
function readScopeFilters(args: any): any {
|
||||
if (args.scope) return scopeSearchFilters(asScope(args.scope), userId, appId, sessionId);
|
||||
if (args.filters || args.agent_id) return resolveFilters(args, globalSearch, userId, appId);
|
||||
const ds = loadDefaultScope();
|
||||
return ds === "project"
|
||||
? resolveFilters(args, globalSearch, userId, appId)
|
||||
: scopeSearchFilters(ds, userId, appId, sessionId);
|
||||
}
|
||||
|
||||
return {
|
||||
"chat.message": chatMessageHook,
|
||||
"experimental.chat.messages.transform": chatMessagesTransformHook,
|
||||
@@ -394,22 +329,17 @@ Identity context (resolved at plugin startup):
|
||||
},
|
||||
|
||||
config: async (opencodeConfig: any) => {
|
||||
// Point OpenCode at the plugin's OWN skills directory via `skills.paths`
|
||||
const here = import.meta.filename;
|
||||
const skillsDir = [
|
||||
resolve(dirname(dirname(here)), "opencode-skills"),
|
||||
resolve(dirname(here), "opencode-skills"),
|
||||
].find(existsSync);
|
||||
if (!skillsDir) return;
|
||||
const pluginDir = dirname(dirname(import.meta.filename));
|
||||
const skillsDir = resolve(pluginDir, "opencode-skills");
|
||||
|
||||
opencodeConfig.skills ??= {};
|
||||
opencodeConfig.skills.paths ??= [];
|
||||
if (!opencodeConfig.skills.paths.includes(skillsDir)) {
|
||||
opencodeConfig.skills.paths.push(skillsDir);
|
||||
if (existsSync(skillsDir)) {
|
||||
opencodeConfig.skills ??= {};
|
||||
opencodeConfig.skills.paths ??= [];
|
||||
if (!opencodeConfig.skills.paths.includes(skillsDir)) {
|
||||
opencodeConfig.skills.paths.push(skillsDir);
|
||||
}
|
||||
}
|
||||
|
||||
// Register the /mem0-* slash commands (the TUI slash menu reads these from
|
||||
// config.command; skills.paths alone does not create slash commands).
|
||||
registerCommands(skillsDir, opencodeConfig);
|
||||
},
|
||||
|
||||
@@ -422,17 +352,13 @@ Identity context (resolved at plugin startup):
|
||||
app_id: tool.schema.string().optional().describe("App/Project ID"),
|
||||
agent_id: tool.schema.string().optional().describe("Agent ID"),
|
||||
metadata: tool.schema.record(tool.schema.string(), tool.schema.any()).optional().describe("Metadata key-value pairs"),
|
||||
infer: tool.schema.boolean().optional().describe("Set to false to store memory verbatim without LLM fact extraction"),
|
||||
scope: tool.schema.string().optional().describe('Write scope: "project" (this repo, default), "session" (this run), or "global" (user-wide, all projects). Use "global" only when explicitly asked.')
|
||||
infer: tool.schema.boolean().optional().describe("Set to false to store memory verbatim without LLM fact extraction")
|
||||
},
|
||||
async execute(args) {
|
||||
stats.adds++;
|
||||
if (dreamTriggered) dreamWriteSeen = true;
|
||||
captureEvent("tool_use", {tool: "add_memory"}, apiKey, appId);
|
||||
const effScope: Scope = args.scope ? asScope(args.scope) : loadDefaultScope();
|
||||
const sp = scopeWriteParams(effScope, userId, appId, sessionId);
|
||||
const finalUserId = args.agent_id ? args.user_id : (args.user_id ?? sp.user_id);
|
||||
const finalAppId = args.app_id ?? sp.app_id;
|
||||
const finalUserId = args.agent_id ? args.user_id : (args.user_id ?? userId);
|
||||
const finalAppId = args.app_id ?? appId;
|
||||
|
||||
const meta = args.metadata ?? {};
|
||||
if (meta.confidence === undefined) meta.confidence = 0.7;
|
||||
@@ -452,7 +378,6 @@ Identity context (resolved at plugin startup):
|
||||
{
|
||||
user_id: finalUserId,
|
||||
app_id: finalAppId,
|
||||
run_id: sp.run_id,
|
||||
agent_id: args.agent_id,
|
||||
metadata: meta,
|
||||
infer
|
||||
@@ -472,13 +397,12 @@ Identity context (resolved at plugin startup):
|
||||
filters: tool.schema.record(tool.schema.string(), tool.schema.any()).optional().describe("Key-value filters (e.g. metadata or user/app filters)"),
|
||||
limit: tool.schema.number().optional().describe("Maximum number of results to return (top_k)"),
|
||||
top_k: tool.schema.number().optional().describe("Maximum number of results to return (alternative parameter)"),
|
||||
scope: tool.schema.string().optional().describe('Search scope: "project" (this repo, default), "session" (this run only), or "global" (across ALL your projects). Only use "global" when the user explicitly asks to search across projects.'),
|
||||
},
|
||||
async execute(args) {
|
||||
stats.searches++;
|
||||
captureEvent("tool_use", {tool: "search_memories"}, apiKey, appId);
|
||||
const topK = args.limit ?? args.top_k ?? 10;
|
||||
const filters = readScopeFilters(args);
|
||||
const filters = resolveFilters(args, globalSearch, userId, appId);
|
||||
|
||||
const res = await mem0.search(args.query, {
|
||||
filters,
|
||||
@@ -497,11 +421,10 @@ Identity context (resolved at plugin startup):
|
||||
filters: tool.schema.record(tool.schema.string(), tool.schema.any()).optional().describe("Metadata/identity filters"),
|
||||
page: tool.schema.number().optional().describe("Page number"),
|
||||
page_size: tool.schema.number().optional().describe("Page size"),
|
||||
scope: tool.schema.string().optional().describe('Scope: "project" (default), "session", or "global" (across ALL your projects). Use "global" only when explicitly asked.'),
|
||||
},
|
||||
async execute(args) {
|
||||
captureEvent("tool_use", {tool: "get_memories"}, apiKey, appId);
|
||||
const filters = readScopeFilters(args);
|
||||
const filters = resolveFilters(args, globalSearch, userId, appId);
|
||||
|
||||
const res = await mem0.getAll({
|
||||
page: args.page,
|
||||
@@ -547,7 +470,6 @@ Identity context (resolved at plugin startup):
|
||||
id: tool.schema.string().describe("The ID of the memory to delete"),
|
||||
},
|
||||
async execute(args) {
|
||||
if (dreamTriggered) dreamWriteSeen = true;
|
||||
captureEvent("tool_use", {tool: "delete_memory"}, apiKey, appId);
|
||||
const res = await mem0.delete(args.id);
|
||||
return JSON.stringify(res);
|
||||
@@ -560,16 +482,12 @@ Identity context (resolved at plugin startup):
|
||||
user_id: tool.schema.string().optional().describe("User ID whose memories to delete"),
|
||||
app_id: tool.schema.string().optional().describe("App ID whose memories to delete"),
|
||||
agent_id: tool.schema.string().optional().describe("Agent ID whose memories to delete"),
|
||||
scope: tool.schema.string().optional().describe('Scope to delete: "project" (default), "session", or "global" (user-wide). Use "global" only when explicitly asked.'),
|
||||
},
|
||||
async execute(args) {
|
||||
if (dreamTriggered) dreamWriteSeen = true;
|
||||
captureEvent("tool_use", {tool: "delete_all_memories"}, apiKey, appId);
|
||||
const sp = args.scope ? scopeWriteParams(asScope(args.scope), userId, appId, sessionId) : null;
|
||||
const res = await mem0.deleteAll({
|
||||
user_id: sp ? sp.user_id : (args.agent_id ? args.user_id : (args.user_id ?? userId)),
|
||||
app_id: sp ? sp.app_id : (args.app_id ?? appId),
|
||||
run_id: sp?.run_id,
|
||||
user_id: args.agent_id ? args.user_id : (args.user_id ?? userId),
|
||||
app_id: args.app_id ?? appId,
|
||||
agent_id: args.agent_id,
|
||||
} as any);
|
||||
return JSON.stringify(res);
|
||||
@@ -637,10 +555,6 @@ Identity context (resolved at plugin startup):
|
||||
if (!initialized) {
|
||||
initialized = true;
|
||||
|
||||
if (dreamConfig.enabled) {
|
||||
incrementSessionCount(mem0StateDir, sessionId);
|
||||
}
|
||||
|
||||
const searchFilters = globalSearch
|
||||
? {OR: [{user_id: "*"}]}
|
||||
: {AND: [{user_id: userId}, {app_id: appId}]};
|
||||
@@ -651,15 +565,10 @@ Identity context (resolved at plugin startup):
|
||||
page: 1,
|
||||
pageSize: 1,
|
||||
});
|
||||
const a: any = all;
|
||||
memoryCount =
|
||||
typeof a?.count === "number"
|
||||
? a.count
|
||||
: Array.isArray(a)
|
||||
? a.length
|
||||
: Array.isArray(a?.results)
|
||||
? a.results.length
|
||||
: 0;
|
||||
(all as any)?.count ??
|
||||
(all as any)?.results?.length ??
|
||||
0;
|
||||
|
||||
if (globalSearch) {
|
||||
systemContext.push(
|
||||
@@ -704,13 +613,6 @@ Identity context (resolved at plugin startup):
|
||||
systemContext.push(
|
||||
"Mem0 searches apply when user references past work, decision questions, errors, or non-trivial tasks. Queries use noun-phrases, 2-4 parallel calls with different metadata.type filters, and include user_id + app_id.",
|
||||
);
|
||||
systemContext.push(SCOPE_GUIDANCE);
|
||||
const activeScope = loadDefaultScope();
|
||||
if (activeScope !== "project") {
|
||||
systemContext.push(
|
||||
`Active default memory scope is "${activeScope}" (set via /mem0-scope). Memory tools use this when no explicit scope is given: "session" limits to this run (run_id="${sessionId}"); "global" spans all your projects (app_id="*"). Pass an explicit scope to override per call. delete_all_memories still requires an explicit scope="global" to delete user-wide.`,
|
||||
);
|
||||
}
|
||||
} catch (err: any) {
|
||||
try {
|
||||
await client.app.log({
|
||||
@@ -725,29 +627,6 @@ Identity context (resolved at plugin startup):
|
||||
}
|
||||
|
||||
captureEvent("session_start", {memory_count: memoryCount}, apiKey, appId);
|
||||
|
||||
// Auto-dream: when the time/session/memory gates pass, inject the
|
||||
// consolidation protocol so the agent tidies memories before answering.
|
||||
if (dreamConfig.enabled && dreamConfig.auto && !dreamTriggered) {
|
||||
const gates = checkCheapGates(mem0StateDir, dreamConfig);
|
||||
const memGate = checkMemoryGate(memoryCount, dreamConfig);
|
||||
if (gates.proceed && memGate.pass && acquireDreamLock(mem0StateDir)) {
|
||||
dreamTriggered = true;
|
||||
systemContext.push(DREAM_PROTOCOL);
|
||||
captureEvent("dream_triggered", {memory_count: memoryCount}, apiKey, appId);
|
||||
} else {
|
||||
// Make "why didn't auto-dream run?" answerable from the logs.
|
||||
const waiting = [gates.reason, memGate.reason].filter(Boolean).join("; ");
|
||||
if (waiting) {
|
||||
try {
|
||||
await client.app.log({
|
||||
body: {service: "mem0", level: "info", message: `auto-dream waiting — ${waiting}`},
|
||||
});
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const hasRemember = NUDGE_RE.test(safeText);
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: mem0-context-loader
|
||||
name: context-loader
|
||||
description: Searches and injects relevant memories into context before starting work on a task. Use when beginning a new task, switching context, or when project history, past decisions, or coding conventions need to be loaded.
|
||||
---
|
||||
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: mem0-dream
|
||||
name: dream
|
||||
description: Consolidates stored memories by merging duplicates, resolving contradictions, and pruning stale entries. Use when memory count is high, search results feel noisy or repetitive, or periodic cleanup is needed to maintain memory quality.
|
||||
---
|
||||
|
||||
@@ -192,7 +192,7 @@ Dream complete — merged: <N>, pruned: <N>, conflicts resolved: <N>, skipped: <
|
||||
|
||||
## Auto mode
|
||||
|
||||
When invoked with `--auto` (e.g., `/mem0-dream --auto`), run non-interactively:
|
||||
When invoked with `--auto` (e.g., `/mem0:dream --auto`), run non-interactively:
|
||||
|
||||
- **Merges**: applied automatically (no contradiction, both are compatible).
|
||||
- **Prunes**: applied automatically (age/confidence-based, no ambiguity).
|
||||
@@ -219,7 +219,7 @@ In auto mode:
|
||||
- If no match, store the reminder:
|
||||
```python
|
||||
add_memory(
|
||||
text="mem0-dream detected <N> contradiction(s) requiring manual review. Run /mem0-dream to resolve them interactively.",
|
||||
text="mem0-dream detected <N> contradiction(s) requiring manual review. Run /mem0:dream to resolve them interactively.",
|
||||
user_id="<active_user_id>",
|
||||
app_id="<active_project_id>",
|
||||
metadata={"type": "task_learning", "source": "mem0-dream-auto", "branch": "<active_branch>"},
|
||||
@@ -229,8 +229,8 @@ In auto mode:
|
||||
|
||||
## See also
|
||||
|
||||
- `/mem0-forget` — targeted deletion of specific memories (search + confirm + delete)
|
||||
- `/mem0-status --deep` — quick quality scan without applying changes
|
||||
- `/mem0:forget` — targeted deletion of specific memories (search + confirm + delete)
|
||||
- `/mem0:health --deep` — quick quality scan without applying changes
|
||||
|
||||
## Output formatting
|
||||
|
||||
+4
-4
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: mem0-forget
|
||||
name: forget
|
||||
description: Deletes memories by search query or memory ID with confirmation before removal. Use when removing outdated decisions, incorrect memories, sensitive data, or cleaning up after experiments. Also handles undo of recent additions.
|
||||
---
|
||||
|
||||
@@ -12,8 +12,8 @@ Delete specific memories from mem0.
|
||||
### Step 1: Parse input
|
||||
|
||||
The user provides either:
|
||||
- A search query: `/mem0-forget auth module decisions`
|
||||
- A memory ID: `/mem0-forget <memory_id>`
|
||||
- A search query: `/mem0:forget auth module decisions`
|
||||
- A memory ID: `/mem0:forget <memory_id>`
|
||||
|
||||
If no argument, ask: "What should I forget? Provide a search query or memory ID."
|
||||
|
||||
@@ -67,7 +67,7 @@ If the user says "undo last N memories" or "undo last write":
|
||||
3. Sort results by creation time descending and show the last N entries (default 1). Ask for confirmation.
|
||||
4. Delete confirmed entries via `delete_memory`.
|
||||
|
||||
If `MEM0_SESSION_ID` is not set or the search returns no results, tell the user: "No recent memory IDs tracked this session. Try `/mem0-tour` to browse recent memories, or `/mem0-forget <search query>` to find specific ones."
|
||||
If `MEM0_SESSION_ID` is not set or the search returns no results, tell the user: "No recent memory IDs tracked this session. Try `/mem0:tour` to browse recent memories, or `/mem0:forget <search query>` to find specific ones."
|
||||
|
||||
## Output formatting
|
||||
|
||||
+11
-49
@@ -1,9 +1,9 @@
|
||||
---
|
||||
name: mem0-status
|
||||
name: health
|
||||
description: Diagnoses mem0 connectivity, API key validity, and memory read/write functionality. Use when memory operations fail, searches return empty, add_memory errors occur, or to verify the plugin is working correctly.
|
||||
---
|
||||
|
||||
# Mem0 Status
|
||||
# Mem0 Health Check
|
||||
|
||||
Run a diagnostic check on the mem0 plugin. Useful for troubleshooting.
|
||||
|
||||
@@ -23,23 +23,19 @@ _KEY="${MEM0_API_KEY:-}"
|
||||
|
||||
### Check 2: Identity resolution
|
||||
|
||||
Resolve identity from the `MEM0_*` environment variables set by the plugin's `shell.env` hook. These are the exact values the plugin uses to scope memories, so report them directly. Do NOT re-run `git` here: the plugin already resolved branch and project from git at session start, and re-shelling git can disagree with it — e.g. it prints an empty branch that renders as `(not a git repo)` while the Session check below shows `branch=main`. One source of truth keeps the two lines consistent.
|
||||
Resolve identity from environment variables set by the plugin's `shell.env` hook:
|
||||
|
||||
```bash
|
||||
echo "user_id=${MEM0_USER_ID:-${USER:-default}}"
|
||||
echo "user_id=${MEM0_USER_ID:-${USER:-}}"
|
||||
echo "project_id=${MEM0_APP_ID:-}"
|
||||
echo "branch=${MEM0_BRANCH:-main}"
|
||||
_S="$HOME/.mem0/settings.json"
|
||||
_SCOPE="$(grep -o '"default_scope"[[:space:]]*:[[:space:]]*"[a-z]*"' "$_S" 2>/dev/null | grep -o '[a-z]*"$' | tr -d '"')"
|
||||
echo "default_scope=${_SCOPE:-project}"
|
||||
echo "branch=$(git branch --show-current 2>/dev/null || echo '')"
|
||||
```
|
||||
|
||||
- `user_id`: from `MEM0_USER_ID`, falling back to `$USER`
|
||||
- `project_id`: from `MEM0_APP_ID`
|
||||
- `branch`: from `MEM0_BRANCH` (the plugin's resolved value; falls back to `main` outside a git repo)
|
||||
- `default_scope`: from `~/.mem0/settings.json` (`default_scope`), falling back to `project`. This is the scope memory tools use when none is given; change it with `/mem0-scope`.
|
||||
- `branch`: from `git branch --show-current`
|
||||
|
||||
PASS if `user_id` and `project_id` are non-empty. WARN if `project_id` is empty — the `shell.env` hook may not have fired (restart OpenCode). Report the branch verbatim from `MEM0_BRANCH`; never invent a string like `(not a git repo)`.
|
||||
PASS if all three are non-empty. WARN if any falls back to defaults.
|
||||
|
||||
### Check 3: Memory tool connectivity
|
||||
|
||||
@@ -79,59 +75,25 @@ echo "branch=${MEM0_BRANCH:-}"
|
||||
- If all three are non-empty: PASS — "Session active"
|
||||
- If any are missing: WARN — "Plugin env vars not set; shell.env hook may not have fired"
|
||||
|
||||
### Check 6: Auto-dream readiness
|
||||
|
||||
Explain whether auto-dream (memory consolidation) is eligible to run, and if not, exactly which gate is blocking. Auto-dream runs at most once per session and only when **all** gates pass: time since last consolidation ≥ `minHours`, sessions since ≥ `minSessions`, and project memory count ≥ `minMemories`.
|
||||
|
||||
Read the gate state and thresholds:
|
||||
|
||||
```bash
|
||||
_ST="$HOME/.mem0/mem0-dream-state.json"
|
||||
_SET="$HOME/.mem0/settings.json"
|
||||
echo "sessions_since=$(grep -o '"sessionsSince"[[:space:]]*:[[:space:]]*[0-9]*' "$_ST" 2>/dev/null | grep -o '[0-9]*$' || echo 0)"
|
||||
echo "last_consolidated_ms=$(grep -o '"lastConsolidatedAt"[[:space:]]*:[[:space:]]*[0-9]*' "$_ST" 2>/dev/null | grep -o '[0-9]*$' || echo 0)"
|
||||
echo "min_hours=$(grep -o '"minHours"[[:space:]]*:[[:space:]]*[0-9]*' "$_SET" 2>/dev/null | grep -o '[0-9]*$' || echo 24)"
|
||||
echo "min_sessions=$(grep -o '"minSessions"[[:space:]]*:[[:space:]]*[0-9]*' "$_SET" 2>/dev/null | grep -o '[0-9]*$' || echo 5)"
|
||||
echo "min_memories=$(grep -o '"minMemories"[[:space:]]*:[[:space:]]*[0-9]*' "$_SET" 2>/dev/null | grep -o '[0-9]*$' || echo 20)"
|
||||
echo "now_s=$(date +%s)"
|
||||
echo "dream_env=${MEM0_DREAM:-unset}"
|
||||
```
|
||||
|
||||
For the memory count, reuse the project memory count from Check 3/4 (or call `get_memories` with the project filter, `page_size=1`, and read `count`).
|
||||
|
||||
Compute each gate:
|
||||
- **time**: `hours_since = (now_s - last_consolidated_ms/1000) / 3600`. Passes when `≥ min_hours`. If `last_consolidated_ms` is 0 it has never run → time gate passes.
|
||||
- **sessions**: passes when `sessions_since ≥ min_sessions`.
|
||||
- **memories**: passes when project memory count `≥ min_memories`.
|
||||
|
||||
Report:
|
||||
- If `dream_env` is `false`/`0`/`no`/`off`, or `dream.enabled` is false in settings: WARN — "Auto-dream disabled".
|
||||
- If all three gates pass: PASS — "eligible (runs at next session start)".
|
||||
- Otherwise: WARN — list the blocking gate(s), e.g. `sessions 2/5, memories 3/20`. This is expected, not an error — auto-dream is just waiting. Note the user can run `/mem0-dream` to consolidate now, or lower the thresholds via the `dream` block in `~/.mem0/settings.json`.
|
||||
|
||||
### Display
|
||||
|
||||
```
|
||||
## mem0 status
|
||||
## mem0 health
|
||||
|
||||
PASS API Key m0-dVe...
|
||||
PASS Identity user=kartik, project=mem0, branch=main
|
||||
PASS Default scope project
|
||||
PASS Memory Tools 142ms
|
||||
PASS Write/Read write + delete OK
|
||||
PASS Session session_id=abc123, app_id=mem0, branch=main
|
||||
WARN Auto-dream waiting — sessions 2/5, memories 3/20 (/mem0-dream to run now)
|
||||
|
||||
All checks passed.
|
||||
```
|
||||
|
||||
The Auto-dream line is informational: WARN here means "waiting on gates", not a failure. Show PASS when eligible, or "disabled" when turned off.
|
||||
|
||||
If any check fails, add a `## Troubleshooting` section with specific fix steps for each failure.
|
||||
|
||||
## Extended mode: Memory Quality Analysis
|
||||
|
||||
When invoked with `--deep` (e.g., `/mem0-status --deep`), run the standard 6 checks above **plus** a memory quality scan.
|
||||
When invoked with `--deep` (e.g., `/mem0:health --deep`), run the standard 5 checks above **plus** a memory quality scan.
|
||||
|
||||
### Quality Check 1: Duplicates
|
||||
|
||||
@@ -188,9 +150,9 @@ Duplicates: <N> · Stale: <N> · Contradictions: <N> · Orphans: <N>
|
||||
```
|
||||
|
||||
If all counts are 0: `Memory quality: clean.`
|
||||
If any non-zero: append `Run /mem0-dream to fix.`
|
||||
If any non-zero: append `Run /mem0:dream to fix.`
|
||||
|
||||
To fix issues found by `--deep`, run `/mem0-dream` for automated consolidation (merges, prunes, conflict resolution).
|
||||
To fix issues found by `--deep`, run `/mem0:dream` for automated consolidation (merges, prunes, conflict resolution).
|
||||
|
||||
## Output formatting
|
||||
|
||||
@@ -1,119 +0,0 @@
|
||||
---
|
||||
name: mem0-scope
|
||||
description: Views or changes the default memory scope (project, session, or global) used when saving and searching memories. Use when the user wants to control whether memories are scoped to this repo, this run, or shared across all their projects.
|
||||
---
|
||||
|
||||
# Mem0 Scope
|
||||
|
||||
View or change the **default memory scope** — the scope the memory tools use when
|
||||
no explicit `scope` is given. The setting persists in `~/.mem0/settings.json`
|
||||
(`default_scope`) and the plugin reads it fresh on each memory operation, so a
|
||||
change takes effect immediately in the current session.
|
||||
|
||||
The three scopes:
|
||||
|
||||
- `project` (default) — this repo only. Filters by `user_id` + `app_id`.
|
||||
- `session` — this run only. Adds `run_id` (the current session) so memories are
|
||||
isolated to this conversation.
|
||||
- `global` — across ALL your projects. Reads use `app_id="*"`; writes drop
|
||||
`app_id` so the memory is user-wide.
|
||||
|
||||
## Execution
|
||||
|
||||
### Step 1: Determine intent
|
||||
|
||||
Look at the user's message for a target scope word: `project`, `session`, or
|
||||
`global` (also accept "repo"→project, "run"→session, "all"/"everywhere"→global).
|
||||
|
||||
- No target word present → **View mode** (Step 2).
|
||||
- A target word present → **Change mode** (Step 3).
|
||||
|
||||
### Step 2: View mode — show the current scope
|
||||
|
||||
1. Read the current default scope from settings:
|
||||
|
||||
```bash
|
||||
_S="$HOME/.mem0/settings.json"
|
||||
[ -f "$_S" ] && grep -o '"default_scope"[[:space:]]*:[[:space:]]*"[a-z]*"' "$_S" | grep -o '[a-z]*"$' | tr -d '"' || echo "project"
|
||||
```
|
||||
|
||||
If the command prints nothing, the scope is `project` (the default).
|
||||
|
||||
2. (Optional) Show how many memories live in the current scope by calling
|
||||
`get_memories` with `scope="<current>"`, `page_size=1`, and reading the
|
||||
`count` (or result length) from the response.
|
||||
|
||||
3. Display using the identity the plugin exported (do NOT re-shell git):
|
||||
|
||||
```
|
||||
Mem0 memory scope
|
||||
|
||||
Current default scope: <current>
|
||||
|
||||
project - this repo only (user + app_id) <marker if active>
|
||||
session - this run only (adds run_id) <marker if active>
|
||||
global - all your projects (app_id = *) <marker if active>
|
||||
|
||||
User: ${MEM0_USER_ID}
|
||||
Project: ${MEM0_APP_ID}
|
||||
Session: ${MEM0_SESSION_ID}
|
||||
|
||||
To change: /mem0-scope session (or project / global)
|
||||
```
|
||||
|
||||
Put `[active]` next to the current scope. If you fetched a count in step 2,
|
||||
add a `Memories in scope: <N>` line.
|
||||
|
||||
### Step 3: Change mode — set a new scope
|
||||
|
||||
1. Validate the target is one of `project`, `session`, `global`. If not, show the
|
||||
three options and stop.
|
||||
|
||||
2. Read the existing settings so you preserve every other key. Use the Read tool
|
||||
on `~/.mem0/settings.json` (it may not exist yet — treat a missing file as
|
||||
`{}`).
|
||||
|
||||
3. Write the file back with the Write tool, keeping ALL existing keys and only
|
||||
setting `"default_scope"` to the target. Pretty-print with 2-space indent and
|
||||
a trailing newline. Do not drop `global_search`, `dream`, `auto_save`, or any
|
||||
other field that was present.
|
||||
|
||||
Example resulting file (when other keys already existed):
|
||||
|
||||
```json
|
||||
{
|
||||
"auto_save": true,
|
||||
"search_limit": 10,
|
||||
"default_scope": "global"
|
||||
}
|
||||
```
|
||||
|
||||
4. Confirm:
|
||||
|
||||
```
|
||||
Default memory scope changed: <old> -> <new>
|
||||
|
||||
<one line describing the effect — see below>
|
||||
Applies immediately to memory tools in this session.
|
||||
|
||||
To revert: /mem0-scope <old>
|
||||
```
|
||||
|
||||
Effect lines:
|
||||
- project → "New memories and searches are limited to this repo."
|
||||
- session → "New memories and searches are limited to this run (this conversation)."
|
||||
- global → "New memories and searches span all your projects. delete_all_memories still needs an explicit scope=global to delete user-wide."
|
||||
|
||||
### Notes
|
||||
|
||||
- This only changes the **default**. Any memory tool call can still pass an
|
||||
explicit `scope` to override it for that one call.
|
||||
- `delete_all_memories` deliberately ignores the default scope: deleting
|
||||
user-wide always requires an explicit `scope="global"`, so changing the
|
||||
default can never turn a routine cleanup into a cross-project wipe.
|
||||
- `global` scope (this user, all their projects) is distinct from the separate
|
||||
`global_search` setting (all users). Leave `global_search` untouched here.
|
||||
|
||||
## Output formatting
|
||||
|
||||
IMPORTANT: Do NOT use markdown in your output. OpenCode TUI renders text verbatim — markdown like **bold**, ## headers, and | table | syntax appears as raw characters. Use plain text with indentation for structure. Use dashes for lists. Use spaces to align columns instead of markdown tables.
|
||||
+5
-5
@@ -1,17 +1,17 @@
|
||||
---
|
||||
name: mem0-search
|
||||
name: peek
|
||||
description: Searches memories and displays compact one-liner results, or looks up a specific memory by ID. Use for quick memory lookups, checking if a decision was recorded, resolving [mem0:id] citations, or browsing memories without full category detail.
|
||||
---
|
||||
|
||||
# Mem0 Search
|
||||
# Mem0 Peek
|
||||
|
||||
Quick search with compact output. Lighter than `/mem0-tour`.
|
||||
Quick search with compact output. Lighter than `/mem0:tour`.
|
||||
|
||||
## Execution
|
||||
|
||||
### Step 1: Parse query
|
||||
|
||||
The user provides a search query: `/mem0-search auth middleware`
|
||||
The user provides a search query: `/mem0:peek auth middleware`
|
||||
|
||||
If no query provided, ask: "What should I search for?"
|
||||
|
||||
@@ -37,7 +37,7 @@ Run 2 parallel `search_memories` calls:
|
||||
Deduplicate by ID, then show compact results:
|
||||
|
||||
```
|
||||
## mem0 search: "<query>" (<N> results)
|
||||
## mem0 peek: "<query>" (<N> results)
|
||||
|
||||
1. [decision] Auth module uses JWT with RS256 keys (2025-05-15) [mem0:a3f8b2c1]
|
||||
2. [anti_pattern] Don't use symmetric HS256 — leaked in env (2025-05-10) [mem0:7e2d9f4a]
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: mem0-pin
|
||||
name: pin
|
||||
description: Pins or unpins a memory to protect it from pruning during dream consolidation. Use when a memory is critical and must never be removed, such as architecture decisions, security constraints, or immutable team conventions.
|
||||
---
|
||||
|
||||
+2
-2
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: mem0-remember
|
||||
name: remember
|
||||
description: Stores a memory verbatim from user input with appropriate type classification and metadata. Use when the user says remember this, save this, store this, note that, or explicitly asks to record a decision, preference, convention, or learning.
|
||||
---
|
||||
|
||||
@@ -11,7 +11,7 @@ Store a fact or learning directly into mem0.
|
||||
|
||||
### Step 1: Extract the content
|
||||
|
||||
The user provides the content as an argument: `/mem0-remember <text>`
|
||||
The user provides the content as an argument: `/mem0:remember <text>`
|
||||
|
||||
If no text was provided, ask: "What should I remember?"
|
||||
|
||||
+5
-5
@@ -1,5 +1,5 @@
|
||||
---
|
||||
name: mem0-tour
|
||||
name: tour
|
||||
description: Browses all stored memories grouped by category with full content display. Use when reviewing all project memories, exploring stored knowledge, onboarding to a project, or getting an overview of captured decisions, conventions, and learnings.
|
||||
---
|
||||
|
||||
@@ -9,8 +9,8 @@ Show the user what mem0 has stored for the current project.
|
||||
|
||||
## Cross-project mode
|
||||
|
||||
When invoked with `--all-projects` (e.g., `/mem0-tour --all-projects` or
|
||||
`/mem0-tour --all-projects auth middleware`), search across ALL projects:
|
||||
When invoked with `--all-projects` (e.g., `/mem0:tour --all-projects` or
|
||||
`/mem0:tour --all-projects auth middleware`), search across ALL projects:
|
||||
|
||||
1. Call `get_memories` with `filters={"AND": [{"user_id": "<active_user_id>"}]}`, `page_size=200` — **no `app_id` filter**.
|
||||
2. If a search query was also provided, run `search_memories` with `query=<query>`,
|
||||
@@ -33,7 +33,7 @@ If `--all-projects` is NOT present, use the standard single-project flow below.
|
||||
|
||||
## Peek mode (compact search)
|
||||
|
||||
When `/mem0-tour` receives a search query argument (e.g., `/mem0-tour auth middleware`)
|
||||
When `/mem0:tour` receives a search query argument (e.g., `/mem0:tour auth middleware`)
|
||||
WITHOUT `--all-projects`, run in **peek mode** — compact one-liner results:
|
||||
|
||||
1. Run 2 parallel `search_memories` calls:
|
||||
@@ -148,7 +148,7 @@ Identity - user: <user_id> project: <project_id> branch: <branch>
|
||||
If zero memories found for this project, print:
|
||||
```
|
||||
No memories stored yet for project <project_id>.
|
||||
Start working - mem0 captures learnings automatically, or use /mem0-remember to save something now.
|
||||
Start working - mem0 captures learnings automatically, or use /mem0:remember to save something now.
|
||||
```
|
||||
|
||||
## Output formatting
|
||||
@@ -54,7 +54,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@opencode-ai/plugin": "^1.0.162",
|
||||
"mem0ai": "^3.0.8"
|
||||
"mem0ai": "^3.0.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"bun-types": ">=1.3.14",
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { parseProjectFromRemote } from "./project";
|
||||
|
||||
describe("parseProjectFromRemote", () => {
|
||||
test("ssh remote with a custom host alias (github.com-work)", () => {
|
||||
expect(parseProjectFromRemote("git@github.com-mem0:mem0ai/mem0.git")).toBe("mem0ai-mem0");
|
||||
});
|
||||
|
||||
test("standard scp-style ssh remote", () => {
|
||||
expect(parseProjectFromRemote("git@github.com:openai/gym.git")).toBe("openai-gym");
|
||||
});
|
||||
|
||||
test("https remote", () => {
|
||||
expect(parseProjectFromRemote("https://github.com/mem0ai/mem0.git")).toBe("mem0ai-mem0");
|
||||
});
|
||||
|
||||
test("https remote without a .git suffix", () => {
|
||||
expect(parseProjectFromRemote("https://gitlab.com/acme/widgets")).toBe("acme-widgets");
|
||||
});
|
||||
|
||||
test("trailing slash is ignored", () => {
|
||||
expect(parseProjectFromRemote("https://github.com/acme/widgets/")).toBe("acme-widgets");
|
||||
});
|
||||
|
||||
test("returns null when no owner/repo can be parsed", () => {
|
||||
expect(parseProjectFromRemote("not-a-remote")).toBeNull();
|
||||
expect(parseProjectFromRemote("")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
/**
|
||||
* Project identity resolution for the Mem0 OpenCode plugin.
|
||||
*
|
||||
* The project id (`app_id`) scopes memories to a repo. We derive it from the
|
||||
* git remote so it is stable across clones, worktrees, and sub-directories —
|
||||
* falling back (in opencode-mem0.ts) to the git repo root dir name, then the
|
||||
* cwd. Keeping the parser pure makes the tricky remote formats testable.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Parse `owner/repo` out of a git remote URL and return it as `owner-repo`.
|
||||
* Handles https, scp-style ssh, custom ssh host aliases (e.g.
|
||||
* `git@github.com-work:owner/repo.git`), an optional `.git` suffix, and a
|
||||
* trailing slash. Returns null when no owner/repo can be found.
|
||||
*/
|
||||
export function parseProjectFromRemote(remote: string): string | null {
|
||||
const m = remote.trim().match(/[:/]([^/:]+)\/([^/:]+?)(?:\.git)?\/?$/);
|
||||
if (!m) return null;
|
||||
return `${m[1]}-${m[2]}`;
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { scopeSearchFilters, scopeWriteParams, asScope, resolveDefaultScope } from "./scope";
|
||||
|
||||
describe("memory scope (pi-agent parity)", () => {
|
||||
test("project scope = this repo", () => {
|
||||
expect(scopeSearchFilters("project", "u", "app", "run")).toEqual({
|
||||
user_id: "u",
|
||||
app_id: "app",
|
||||
});
|
||||
expect(scopeWriteParams("project", "u", "app", "run")).toEqual({
|
||||
user_id: "u",
|
||||
app_id: "app",
|
||||
});
|
||||
});
|
||||
|
||||
test("session scope adds run_id", () => {
|
||||
expect(scopeSearchFilters("session", "u", "app", "run")).toEqual({
|
||||
user_id: "u",
|
||||
app_id: "app",
|
||||
run_id: "run",
|
||||
});
|
||||
expect(scopeWriteParams("session", "u", "app", "run")).toEqual({
|
||||
user_id: "u",
|
||||
app_id: "app",
|
||||
run_id: "run",
|
||||
});
|
||||
});
|
||||
|
||||
test("global scope spans all the user's projects (matches pi-agent)", () => {
|
||||
expect(scopeSearchFilters("global", "u", "app", "run")).toEqual({
|
||||
user_id: "u",
|
||||
app_id: "*",
|
||||
});
|
||||
// global writes drop app_id so the memory is user-wide, not project-bound
|
||||
expect(scopeWriteParams("global", "u", "app", "run")).toEqual({ user_id: "u" });
|
||||
});
|
||||
|
||||
test("default scope is project when settings are absent", () => {
|
||||
expect(resolveDefaultScope(null)).toBe("project");
|
||||
expect(resolveDefaultScope(undefined)).toBe("project");
|
||||
expect(resolveDefaultScope({})).toBe("project");
|
||||
});
|
||||
|
||||
test("default scope reads default_scope from settings", () => {
|
||||
expect(resolveDefaultScope({ default_scope: "session" })).toBe("session");
|
||||
expect(resolveDefaultScope({ default_scope: "global" })).toBe("global");
|
||||
expect(resolveDefaultScope({ default_scope: "project" })).toBe("project");
|
||||
});
|
||||
|
||||
test("default scope normalizes an invalid default_scope to project", () => {
|
||||
expect(resolveDefaultScope({ default_scope: "nonsense" })).toBe("project");
|
||||
expect(resolveDefaultScope({ default_scope: 42 })).toBe("project");
|
||||
});
|
||||
|
||||
test("asScope normalizes unknown values to project", () => {
|
||||
expect(asScope("global")).toBe("global");
|
||||
expect(asScope("session")).toBe("session");
|
||||
expect(asScope("project")).toBe("project");
|
||||
expect(asScope("nonsense")).toBe("project");
|
||||
expect(asScope(undefined)).toBe("project");
|
||||
});
|
||||
});
|
||||
@@ -1,71 +0,0 @@
|
||||
/**
|
||||
* Memory scope resolution — ported from the pi-agent plugin's scoping model.
|
||||
*
|
||||
* Lets the agent choose, per memory operation, how wide to read/write:
|
||||
* - "project" (default): this repo only -> { user_id, app_id }
|
||||
* - "session": this run only -> { user_id, app_id, run_id }
|
||||
* - "global": across ALL of the user's projects -> { user_id, app_id: "*" }
|
||||
*
|
||||
* Mirrors pi-agent/src/memory/scoping.ts (resolveSearchFilters / resolveAddParams)
|
||||
* so the OpenCode plugin exposes scope the same way: as a per-call tool parameter,
|
||||
* not a stateful "switch project" command.
|
||||
*/
|
||||
|
||||
export type Scope = "project" | "session" | "global";
|
||||
|
||||
/** Filters for `search` / `get_memories` at the given scope. */
|
||||
export function scopeSearchFilters(
|
||||
scope: Scope,
|
||||
userId: string,
|
||||
appId: string,
|
||||
runId: string,
|
||||
): Record<string, string> {
|
||||
switch (scope) {
|
||||
case "session":
|
||||
return { user_id: userId, app_id: appId, run_id: runId };
|
||||
case "global":
|
||||
return { user_id: userId, app_id: "*" };
|
||||
case "project":
|
||||
default:
|
||||
return { user_id: userId, app_id: appId };
|
||||
}
|
||||
}
|
||||
|
||||
/** Identity params for `add` / `delete_all` at the given scope. */
|
||||
export function scopeWriteParams(
|
||||
scope: Scope,
|
||||
userId: string,
|
||||
appId: string,
|
||||
runId: string,
|
||||
): { user_id: string; app_id?: string; run_id?: string } {
|
||||
switch (scope) {
|
||||
case "session":
|
||||
return { user_id: userId, app_id: appId, run_id: runId };
|
||||
case "global":
|
||||
return { user_id: userId };
|
||||
case "project":
|
||||
default:
|
||||
return { user_id: userId, app_id: appId };
|
||||
}
|
||||
}
|
||||
|
||||
/** Normalize an arbitrary value to a valid Scope (defaults to "project"). */
|
||||
export function asScope(value: unknown): Scope {
|
||||
return value === "session" || value === "global" ? value : "project";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the persisted default scope from a parsed `~/.mem0/settings.json`
|
||||
* object. This is the user-changeable default applied to memory operations when
|
||||
* no explicit `scope` is passed (set via the `mem0-scope` skill). Falls back to
|
||||
* "project" when unset or invalid.
|
||||
*/
|
||||
export function resolveDefaultScope(
|
||||
settings: Record<string, unknown> | null | undefined,
|
||||
): Scope {
|
||||
return asScope(settings?.default_scope);
|
||||
}
|
||||
|
||||
/** Guidance injected so the agent uses `global` only when explicitly asked. */
|
||||
export const SCOPE_GUIDANCE =
|
||||
'Memory tools accept an optional `scope`: omit it (or "project") for normal queries; use "session" to limit to the current run; use "global" ONLY when the user explicitly asks to search across all their projects in this workspace.';
|
||||
@@ -2,18 +2,6 @@
|
||||
|
||||
All notable changes to the Mem0 plugin will be documented in this file.
|
||||
|
||||
## 0.2.11 — Session-summary metadata fix + rerank auto-injected context by default
|
||||
|
||||
> Versions: Claude Code / Cursor / Codex `0.2.11`; Antigravity `0.1.3`. All four editors share `scripts/`, so the fix below applies to every editor.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **`files_touched` was double-JSON-encoded in session summaries (`scripts/capture_session_summary.py`):** the Stop-hook summary set `metadata["files_touched"] = json.dumps(files[:20])` — a pre-serialized JSON string — and then serialized the whole request body again with `json.dumps(body)`. The stored memory therefore carried an escaped string blob (`"[\"mem0/memory/main.py\", \"src/client/index.ts\"]"`) instead of a real array, so file paths surfaced as backslash- and slash-heavy escaped text when those memories were returned by `search_memories`/`get_memories` and shown in Claude Code, Cursor, Codex, and Antigravity. The fix stores the list directly (`metadata["files_touched"] = files[:20]`) so the body is encoded exactly once. New `tests/test_capture_session_summary.py` asserts the posted body contains a JSON array and no escaped-string artifact.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Auto-injected memory context is now reranked by default (`scripts/_search.py`, `scripts/file_context.py`, `scripts/on_bash_output.sh`, `scripts/on_user_prompt.sh`):** the REST search endpoint does not rerank when `rerank` is omitted, so hook-injected context (file-context, bash-error lookup, session-resume prefetch) was ordered by raw vector similarity and the single most relevant memory could fall outside the injected `top_k` window. A new `should_rerank()` helper turns reranking on for every auto-injection path; the extra ~150–200 ms stays within the hook's curl budget. Opt out with `MEM0_RERANK=0` (also accepts `false`/`no`/`off`). (#5690)
|
||||
|
||||
## 0.2.10 — Accurate per-editor telemetry attribution
|
||||
|
||||
### Fixed
|
||||
|
||||
@@ -158,10 +158,29 @@ Install from the [Cursor Marketplace](https://cursor.com/marketplace) for the co
|
||||
### OpenCode
|
||||
|
||||
```bash
|
||||
opencode plugin @mem0/opencode-plugin
|
||||
bunx @mem0/opencode-plugin@latest install
|
||||
```
|
||||
|
||||
Add `--global` to install for all projects. The plugin auto-registers its native memory tools, hooks, and skills via its `config` hook — no MCP server to configure. Restart OpenCode after installing.
|
||||
Or via OpenCode's built-in CLI: `opencode plugin @mem0/opencode-plugin`
|
||||
|
||||
Then add the MCP server to your `opencode.json` (project or global at `~/.config/opencode/opencode.json`):
|
||||
|
||||
```json
|
||||
{
|
||||
"mcp": {
|
||||
"mem0": {
|
||||
"type": "remote",
|
||||
"url": "https://mcp.mem0.ai/mcp/",
|
||||
"headers": {
|
||||
"Authorization": "Token {env:MEM0_API_KEY}"
|
||||
},
|
||||
"oauth": false
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Restart OpenCode. The plugin installs hooks and skills automatically. Drop the `plugin` install if you only want MCP.
|
||||
|
||||
See [OpenCode integration docs](https://docs.mem0.ai/integrations/opencode) for full details.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "mem0",
|
||||
"name": "mem0",
|
||||
"version": "0.1.3",
|
||||
"version": "0.1.2",
|
||||
"description": "Persistent semantic memory for Antigravity agents. Cross-session, user-level recall via the Mem0 Platform MCP server. 16 slash commands, lifecycle hooks for auto-capture and metadata enforcement.",
|
||||
"author": { "name": "Mem0", "email": "support@mem0.ai" },
|
||||
"publisher": "mem0ai",
|
||||
|
||||
@@ -7,31 +7,12 @@ All pre-fetch hooks use this instead of duplicating urllib boilerplate.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import urllib.request
|
||||
|
||||
SEARCH_URL = "https://api.mem0.ai/v3/memories/search/"
|
||||
SEARCH_TIMEOUT = 5
|
||||
|
||||
|
||||
def should_rerank() -> bool:
|
||||
"""Whether auto-injection searches should request Platform reranking.
|
||||
|
||||
The REST search endpoint does not rerank when ``rerank`` is omitted, so
|
||||
auto-injected context is ordered by raw vector similarity and the single
|
||||
most relevant memory can fall outside the injected top_k window. We default
|
||||
reranking ON for the hook-driven injection path (the extra ~150-200ms is
|
||||
well within the hook's curl budget) and let users opt out via MEM0_RERANK.
|
||||
|
||||
MEM0_RERANK is read case-insensitively; ``0``, ``false``, ``no``, and
|
||||
``off`` disable reranking. Anything else (including unset) enables it.
|
||||
"""
|
||||
raw = os.environ.get("MEM0_RERANK")
|
||||
if raw is None:
|
||||
return True
|
||||
return raw.strip().lower() not in ("0", "false", "no", "off", "")
|
||||
|
||||
|
||||
def _do_search(api_key: str, payload: dict) -> list[dict]:
|
||||
body = json.dumps(payload).encode()
|
||||
req = urllib.request.Request(
|
||||
|
||||
@@ -173,7 +173,7 @@ def store_summary(
|
||||
if branch:
|
||||
metadata["branch"] = branch
|
||||
if files:
|
||||
metadata["files_touched"] = files[:20]
|
||||
metadata["files_touched"] = json.dumps(files[:20])
|
||||
|
||||
body = {
|
||||
"messages": [{"role": "user", "content": summary_prompt}],
|
||||
|
||||
@@ -23,7 +23,7 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from _formatting import TYPE_ICONS, format_age
|
||||
from _identity import resolve_api_key, resolve_user_id
|
||||
from _project import resolve_project_id
|
||||
from _search import search_memories, should_rerank
|
||||
from _search import search_memories
|
||||
|
||||
FILE_READ_GATE_MIN_BYTES = 1500
|
||||
MAX_RESULTS = 5
|
||||
@@ -93,7 +93,6 @@ def search_file_context(
|
||||
api_key, user_id, project_id, query,
|
||||
top_k=MAX_RESULTS, threshold=0.3,
|
||||
global_search=global_search,
|
||||
rerank=should_rerank(),
|
||||
)
|
||||
|
||||
results = results[:MAX_RESULTS]
|
||||
|
||||
@@ -77,16 +77,15 @@ RESULTS=$(PYTHONPATH="$SCRIPT_DIR" MEM0_SEARCH_QUERY="$ERROR_QUERY" MEM0_SEARCH_
|
||||
python3 -c "
|
||||
import os, sys
|
||||
sys.path.insert(0, os.environ.get('PYTHONPATH', '.'))
|
||||
from _search import search_memories, format_results_for_context, should_rerank
|
||||
from _search import search_memories, format_results_for_context
|
||||
|
||||
api_key = os.environ.get('MEM0_API_KEY', '')
|
||||
user_id = os.environ.get('MEM0_SEARCH_USER', 'default')
|
||||
project_id = os.environ.get('MEM0_PROJECT_ID', 'unknown')
|
||||
query = os.environ.get('MEM0_SEARCH_QUERY', '')
|
||||
rerank = should_rerank()
|
||||
|
||||
r1 = search_memories(api_key, user_id, project_id, query, metadata_type='anti_pattern', top_k=3, rerank=rerank)
|
||||
r2 = search_memories(api_key, user_id, project_id, query, metadata_type='bug_fix', top_k=3, rerank=rerank)
|
||||
r1 = search_memories(api_key, user_id, project_id, query, metadata_type='anti_pattern', top_k=3)
|
||||
r2 = search_memories(api_key, user_id, project_id, query, metadata_type='bug_fix', top_k=3)
|
||||
|
||||
seen = set()
|
||||
combined = []
|
||||
|
||||
@@ -120,15 +120,14 @@ if [ -n "$HAS_RESUME" ]; then
|
||||
RESUME_RESULTS=$(PYTHONPATH="$SCRIPT_DIR" MEM0_SEARCH_USER="$USER_ID" python3 -c "
|
||||
import os, sys
|
||||
sys.path.insert(0, os.environ.get('PYTHONPATH', '.'))
|
||||
from _search import search_memories, format_results_for_context, should_rerank
|
||||
from _search import search_memories, format_results_for_context
|
||||
|
||||
api_key = os.environ.get('MEM0_API_KEY', '')
|
||||
user_id = os.environ.get('MEM0_SEARCH_USER', 'default')
|
||||
project_id = os.environ.get('MEM0_PROJECT_ID', 'unknown')
|
||||
rerank = should_rerank()
|
||||
|
||||
state = search_memories(api_key, user_id, project_id, 'session state current task', metadata_type='session_state', top_k=3, rerank=rerank)
|
||||
decisions = search_memories(api_key, user_id, project_id, 'recent decisions and learnings', metadata_type='decision', top_k=3, rerank=rerank)
|
||||
state = search_memories(api_key, user_id, project_id, 'session state current task', metadata_type='session_state', top_k=3)
|
||||
decisions = search_memories(api_key, user_id, project_id, 'recent decisions and learnings', metadata_type='decision', top_k=3)
|
||||
|
||||
all_r = state + decisions
|
||||
seen = set()
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
"""Regression tests for capture_session_summary.py request body construction.
|
||||
|
||||
Guards against the double-JSON-encoding bug where ``files_touched`` was stored
|
||||
as a pre-serialized JSON string and then encoded a second time with the rest of
|
||||
the request body — surfacing as escaped, slash-heavy blobs in the memories shown
|
||||
inside Claude Code / Cursor / Codex / Antigravity (all four editors share this
|
||||
script).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
|
||||
class _FakeResp:
|
||||
status = 200
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *_):
|
||||
return False
|
||||
|
||||
|
||||
def _capture_request_body(monkeypatch):
|
||||
"""Patch urlopen so store_summary posts nowhere; capture the request body."""
|
||||
import capture_session_summary as css
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
def fake_urlopen(req, timeout=0):
|
||||
captured["raw"] = req.data.decode("utf-8")
|
||||
captured["body"] = json.loads(captured["raw"])
|
||||
return _FakeResp()
|
||||
|
||||
monkeypatch.setattr(css.urllib.request, "urlopen", fake_urlopen)
|
||||
return captured, css
|
||||
|
||||
|
||||
def test_files_touched_is_json_array_not_double_encoded(monkeypatch):
|
||||
"""files_touched must be a real JSON array, encoded exactly once."""
|
||||
captured, css = _capture_request_body(monkeypatch)
|
||||
files = ["mem0/memory/main.py", "src/client/index.ts"]
|
||||
|
||||
css.store_summary(
|
||||
api_key="test-key",
|
||||
summary_prompt="did some work",
|
||||
user_id="u1",
|
||||
session_id="s1",
|
||||
project_id="p1",
|
||||
branch="main",
|
||||
files=files,
|
||||
)
|
||||
|
||||
files_touched = captured["body"]["metadata"]["files_touched"]
|
||||
assert isinstance(files_touched, list), (
|
||||
"files_touched must be a JSON array, not a double-encoded string; "
|
||||
f"got {type(files_touched).__name__}: {files_touched!r}"
|
||||
)
|
||||
assert files_touched == files
|
||||
# The file paths must not appear as an escaped JSON string inside the body.
|
||||
assert '\\"' not in captured["raw"]
|
||||
|
||||
|
||||
def test_files_touched_omitted_when_no_files(monkeypatch):
|
||||
"""No files touched -> no files_touched key (unchanged behaviour)."""
|
||||
captured, css = _capture_request_body(monkeypatch)
|
||||
|
||||
css.store_summary(
|
||||
api_key="test-key",
|
||||
summary_prompt="did some work",
|
||||
user_id="u1",
|
||||
session_id="s1",
|
||||
project_id="p1",
|
||||
branch="main",
|
||||
files=[],
|
||||
)
|
||||
|
||||
assert "files_touched" not in captured["body"]["metadata"]
|
||||
@@ -101,67 +101,6 @@ def test_search_memories_no_api_key_returns_empty():
|
||||
assert results == []
|
||||
|
||||
|
||||
def test_search_memories_omits_rerank_by_default():
|
||||
"""Regression for #5684: rerank must not be sent unless requested."""
|
||||
from _search import search_memories
|
||||
|
||||
captured_body = {}
|
||||
|
||||
def mock_urlopen(req, timeout=None):
|
||||
captured_body.update(json.loads(req.data.decode()))
|
||||
resp = MagicMock()
|
||||
resp.read.return_value = json.dumps({"results": []}).encode()
|
||||
resp.__enter__ = lambda s: s
|
||||
resp.__exit__ = MagicMock(return_value=False)
|
||||
return resp
|
||||
|
||||
with patch("urllib.request.urlopen", side_effect=mock_urlopen):
|
||||
search_memories("key", "user", "proj", "query")
|
||||
|
||||
assert "rerank" not in captured_body
|
||||
|
||||
|
||||
def test_search_memories_forwards_rerank_true():
|
||||
"""Regression for #5684: rerank=True must reach the request body so the
|
||||
REST endpoint actually reranks (it does not rerank when omitted)."""
|
||||
from _search import search_memories
|
||||
|
||||
captured_body = {}
|
||||
|
||||
def mock_urlopen(req, timeout=None):
|
||||
captured_body.update(json.loads(req.data.decode()))
|
||||
resp = MagicMock()
|
||||
resp.read.return_value = json.dumps({"results": []}).encode()
|
||||
resp.__enter__ = lambda s: s
|
||||
resp.__exit__ = MagicMock(return_value=False)
|
||||
return resp
|
||||
|
||||
with patch("urllib.request.urlopen", side_effect=mock_urlopen):
|
||||
search_memories("key", "user", "proj", "query", rerank=True)
|
||||
|
||||
assert captured_body.get("rerank") is True
|
||||
|
||||
|
||||
def test_should_rerank_defaults_true(monkeypatch):
|
||||
"""Regression for #5684: auto-injection reranks by default."""
|
||||
from _search import should_rerank
|
||||
|
||||
monkeypatch.delenv("MEM0_RERANK", raising=False)
|
||||
assert should_rerank() is True
|
||||
|
||||
|
||||
def test_should_rerank_opt_out_values(monkeypatch):
|
||||
from _search import should_rerank
|
||||
|
||||
for falsey in ("0", "false", "False", "NO", "off", ""):
|
||||
monkeypatch.setenv("MEM0_RERANK", falsey)
|
||||
assert should_rerank() is False, falsey
|
||||
|
||||
for truthy in ("1", "true", "yes", "on"):
|
||||
monkeypatch.setenv("MEM0_RERANK", truthy)
|
||||
assert should_rerank() is True, truthy
|
||||
|
||||
|
||||
def test_format_results_for_context():
|
||||
from _search import format_results_for_context
|
||||
|
||||
|
||||
@@ -64,7 +64,6 @@
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"form-data@<4.0.6": ">=4.0.6",
|
||||
"protobufjs@<7.5.5": "^7.5.5",
|
||||
"vite": "^8.0.5",
|
||||
"langsmith@<0.6.0": "^0.6.0",
|
||||
|
||||
Generated
+5
-6
@@ -5,7 +5,6 @@ settings:
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
overrides:
|
||||
form-data@<4.0.6: '>=4.0.6'
|
||||
protobufjs@<7.5.5: ^7.5.5
|
||||
vite: ^8.0.5
|
||||
langsmith@<0.6.0: ^0.6.0
|
||||
@@ -1110,8 +1109,8 @@ packages:
|
||||
form-data-encoder@1.7.2:
|
||||
resolution: {integrity: sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==}
|
||||
|
||||
form-data@4.0.6:
|
||||
resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==}
|
||||
form-data@4.0.5:
|
||||
resolution: {integrity: sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==}
|
||||
engines: {node: '>= 6'}
|
||||
|
||||
formdata-node@4.4.1:
|
||||
@@ -2729,7 +2728,7 @@ snapshots:
|
||||
'@types/node-fetch@2.6.13':
|
||||
dependencies:
|
||||
'@types/node': 22.19.20
|
||||
form-data: 4.0.6
|
||||
form-data: 4.0.5
|
||||
|
||||
'@types/node@18.19.130':
|
||||
dependencies:
|
||||
@@ -2871,7 +2870,7 @@ snapshots:
|
||||
axios@1.17.0:
|
||||
dependencies:
|
||||
follow-redirects: 1.16.0
|
||||
form-data: 4.0.6
|
||||
form-data: 4.0.5
|
||||
https-proxy-agent: 5.0.1
|
||||
proxy-from-env: 2.1.0
|
||||
transitivePeerDependencies:
|
||||
@@ -3132,7 +3131,7 @@ snapshots:
|
||||
|
||||
form-data-encoder@1.7.2: {}
|
||||
|
||||
form-data@4.0.6:
|
||||
form-data@4.0.5:
|
||||
dependencies:
|
||||
asynckit: 0.4.0
|
||||
combined-stream: 1.0.8
|
||||
|
||||
@@ -13,7 +13,6 @@ onlyBuiltDependencies:
|
||||
- protobufjs
|
||||
|
||||
overrides:
|
||||
"form-data@<4.0.6": ">=4.0.6"
|
||||
"protobufjs@<7.5.5": "^7.5.5"
|
||||
"vite": "^8.0.5"
|
||||
"langsmith@<0.6.0": "^0.6.0"
|
||||
|
||||
@@ -71,10 +71,8 @@
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {
|
||||
"form-data@<4.0.6": ">=4.0.6",
|
||||
"uuid@<11.1.1": ">=11.1.1",
|
||||
"esbuild": ">=0.28.1",
|
||||
"undici@>=8.0.0 <8.5.0": ">=8.5.0"
|
||||
"esbuild": ">=0.28.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-11
@@ -5,10 +5,8 @@ settings:
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
overrides:
|
||||
form-data@<4.0.6: '>=4.0.6'
|
||||
uuid@<11.1.1: '>=11.1.1'
|
||||
esbuild: '>=0.28.1'
|
||||
undici@>=8.0.0 <8.5.0: '>=8.5.0'
|
||||
|
||||
importers:
|
||||
|
||||
@@ -1370,8 +1368,8 @@ packages:
|
||||
form-data-encoder@1.7.2:
|
||||
resolution: {integrity: sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==}
|
||||
|
||||
form-data@4.0.6:
|
||||
resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==}
|
||||
form-data@4.0.5:
|
||||
resolution: {integrity: sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==}
|
||||
engines: {node: '>= 6'}
|
||||
|
||||
formdata-node@4.4.1:
|
||||
@@ -2355,8 +2353,8 @@ packages:
|
||||
resolution: {integrity: sha512-4yqz8a3n5HmGTlsbADNtr/dJlhkh/55Rq798G6ibiULcXbDtaLpTl1pvdqcbFfeoj3iSi52lePFM7h9H21cw/A==}
|
||||
engines: {node: '>=18.17'}
|
||||
|
||||
undici@8.5.0:
|
||||
resolution: {integrity: sha512-xamtWoB1EshgjpmlXd7GGm2VfdDtw1+rD8uhry8pSNW3If6S8E0m2T2+orSKeZXEn/aPJMviCpDBA65WJt8zhg==}
|
||||
undici@8.3.0:
|
||||
resolution: {integrity: sha512-TkUDgb6tl7KOGZ+7e8E3d2FYgUQgF6z5YypqjWmixVQSQERFcVrVg0ySADm2LVLRh5ljAaHTCR5Fmz3Q34rB7Q==}
|
||||
engines: {node: '>=22.19.0'}
|
||||
|
||||
util-deprecate@1.0.2:
|
||||
@@ -2939,7 +2937,7 @@ snapshots:
|
||||
minimatch: 10.2.5
|
||||
proper-lockfile: 4.1.2
|
||||
typebox: 1.1.38
|
||||
undici: 8.5.0
|
||||
undici: 8.3.0
|
||||
yaml: 2.9.0
|
||||
optionalDependencies:
|
||||
'@mariozechner/clipboard': 0.3.9
|
||||
@@ -3476,7 +3474,7 @@ snapshots:
|
||||
'@types/node-fetch@2.6.13':
|
||||
dependencies:
|
||||
'@types/node': 25.9.2
|
||||
form-data: 4.0.6
|
||||
form-data: 4.0.5
|
||||
|
||||
'@types/node@18.19.130':
|
||||
dependencies:
|
||||
@@ -3600,7 +3598,7 @@ snapshots:
|
||||
axios@1.17.0:
|
||||
dependencies:
|
||||
follow-redirects: 1.16.0
|
||||
form-data: 4.0.6
|
||||
form-data: 4.0.5
|
||||
https-proxy-agent: 5.0.1
|
||||
proxy-from-env: 2.1.0
|
||||
transitivePeerDependencies:
|
||||
@@ -3893,7 +3891,7 @@ snapshots:
|
||||
|
||||
form-data-encoder@1.7.2: {}
|
||||
|
||||
form-data@4.0.6:
|
||||
form-data@4.0.5:
|
||||
dependencies:
|
||||
asynckit: 0.4.0
|
||||
combined-stream: 1.0.8
|
||||
@@ -4896,7 +4894,7 @@ snapshots:
|
||||
|
||||
undici@6.26.0: {}
|
||||
|
||||
undici@8.5.0: {}
|
||||
undici@8.3.0: {}
|
||||
|
||||
util-deprecate@1.0.2: {}
|
||||
|
||||
|
||||
@@ -2,7 +2,5 @@ packages:
|
||||
- '.'
|
||||
|
||||
overrides:
|
||||
"form-data@<4.0.6": ">=4.0.6"
|
||||
"uuid@<11.1.1": ">=11.1.1"
|
||||
"esbuild": ">=0.28.1"
|
||||
"undici@>=8.0.0 <8.5.0": ">=8.5.0"
|
||||
|
||||
@@ -80,7 +80,6 @@
|
||||
],
|
||||
"overrides": {
|
||||
"glob@>=10.2.0 <10.5.0": "^10.5.0",
|
||||
"js-yaml@<=4.1.1": ">=4.2.0",
|
||||
"minimatch@<3.1.3": "^3.1.3",
|
||||
"minimatch@>=5.0.0 <5.1.8": "^5.1.8",
|
||||
"minimatch@>=9.0.0 <9.0.7": "^9.0.7",
|
||||
|
||||
+23
-9
@@ -6,7 +6,6 @@ settings:
|
||||
|
||||
overrides:
|
||||
glob@>=10.2.0 <10.5.0: ^10.5.0
|
||||
js-yaml@<=4.1.1: '>=4.2.0'
|
||||
minimatch@<3.1.3: ^3.1.3
|
||||
minimatch@>=5.0.0 <5.1.8: ^5.1.8
|
||||
minimatch@>=9.0.0 <9.0.7: ^9.0.7
|
||||
@@ -794,8 +793,8 @@ packages:
|
||||
arg@4.1.3:
|
||||
resolution: {integrity: sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==}
|
||||
|
||||
argparse@2.0.1:
|
||||
resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==}
|
||||
argparse@1.0.10:
|
||||
resolution: {integrity: sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg==}
|
||||
|
||||
babel-jest@29.7.0:
|
||||
resolution: {integrity: sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==}
|
||||
@@ -1026,6 +1025,11 @@ packages:
|
||||
resolution: {integrity: sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==}
|
||||
engines: {node: '>=8'}
|
||||
|
||||
esprima@4.0.1:
|
||||
resolution: {integrity: sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==}
|
||||
engines: {node: '>=4'}
|
||||
hasBin: true
|
||||
|
||||
eventsource-parser@3.1.0:
|
||||
resolution: {integrity: sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg==}
|
||||
engines: {node: '>=18.0.0'}
|
||||
@@ -1347,8 +1351,8 @@ packages:
|
||||
js-tokens@4.0.0:
|
||||
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
|
||||
|
||||
js-yaml@4.2.0:
|
||||
resolution: {integrity: sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==}
|
||||
js-yaml@3.14.2:
|
||||
resolution: {integrity: sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==}
|
||||
hasBin: true
|
||||
|
||||
jsesc@3.1.0:
|
||||
@@ -1650,6 +1654,9 @@ packages:
|
||||
resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==}
|
||||
engines: {node: '>= 12'}
|
||||
|
||||
sprintf-js@1.0.3:
|
||||
resolution: {integrity: sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g==}
|
||||
|
||||
stack-utils@2.0.6:
|
||||
resolution: {integrity: sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==}
|
||||
engines: {node: '>=10'}
|
||||
@@ -2219,7 +2226,7 @@ snapshots:
|
||||
camelcase: 5.3.1
|
||||
find-up: 4.1.0
|
||||
get-package-type: 0.1.0
|
||||
js-yaml: 4.2.0
|
||||
js-yaml: 3.14.2
|
||||
resolve-from: 5.0.0
|
||||
|
||||
'@istanbuljs/schema@0.1.6': {}
|
||||
@@ -2598,7 +2605,9 @@ snapshots:
|
||||
|
||||
arg@4.1.3: {}
|
||||
|
||||
argparse@2.0.1: {}
|
||||
argparse@1.0.10:
|
||||
dependencies:
|
||||
sprintf-js: 1.0.3
|
||||
|
||||
babel-jest@29.7.0(@babel/core@7.29.7):
|
||||
dependencies:
|
||||
@@ -2848,6 +2857,8 @@ snapshots:
|
||||
|
||||
escape-string-regexp@2.0.0: {}
|
||||
|
||||
esprima@4.0.1: {}
|
||||
|
||||
eventsource-parser@3.1.0: {}
|
||||
|
||||
execa@5.1.1:
|
||||
@@ -3344,9 +3355,10 @@ snapshots:
|
||||
|
||||
js-tokens@4.0.0: {}
|
||||
|
||||
js-yaml@4.2.0:
|
||||
js-yaml@3.14.2:
|
||||
dependencies:
|
||||
argparse: 2.0.1
|
||||
argparse: 1.0.10
|
||||
esprima: 4.0.1
|
||||
|
||||
jsesc@3.1.0: {}
|
||||
|
||||
@@ -3616,6 +3628,8 @@ snapshots:
|
||||
|
||||
source-map@0.7.6: {}
|
||||
|
||||
sprintf-js@1.0.3: {}
|
||||
|
||||
stack-utils@2.0.6:
|
||||
dependencies:
|
||||
escape-string-regexp: 2.0.0
|
||||
|
||||
@@ -7,7 +7,6 @@ onlyBuiltDependencies:
|
||||
|
||||
overrides:
|
||||
"glob@>=10.2.0 <10.5.0": "^10.5.0"
|
||||
"js-yaml@<=4.1.1": ">=4.2.0"
|
||||
"minimatch@<3.1.3": "^3.1.3"
|
||||
"minimatch@>=5.0.0 <5.1.8": "^5.1.8"
|
||||
"minimatch@>=9.0.0 <9.0.7": "^9.0.7"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mem0ai",
|
||||
"version": "3.0.11",
|
||||
"version": "3.0.8",
|
||||
"description": "The Memory Layer For Your AI Apps",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
@@ -139,7 +139,6 @@
|
||||
"better-sqlite3"
|
||||
],
|
||||
"overrides": {
|
||||
"form-data@<4.0.6": ">=4.0.6",
|
||||
"picomatch@<2.3.2": "^2.3.2",
|
||||
"picomatch@>=4.0.0 <4.0.4": "^4.0.4",
|
||||
"jws@4.0.0": "4.0.1",
|
||||
|
||||
Generated
+5
-6
@@ -5,7 +5,6 @@ settings:
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
overrides:
|
||||
form-data@<4.0.6: '>=4.0.6'
|
||||
picomatch@<2.3.2: ^2.3.2
|
||||
picomatch@>=4.0.0 <4.0.4: ^4.0.4
|
||||
jws@4.0.0: 4.0.1
|
||||
@@ -1555,8 +1554,8 @@ packages:
|
||||
form-data-encoder@1.7.2:
|
||||
resolution: {integrity: sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==}
|
||||
|
||||
form-data@4.0.6:
|
||||
resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==}
|
||||
form-data@4.0.5:
|
||||
resolution: {integrity: sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==}
|
||||
engines: {node: '>= 6'}
|
||||
|
||||
formdata-node@4.4.1:
|
||||
@@ -3973,7 +3972,7 @@ snapshots:
|
||||
'@types/node-fetch@2.6.13':
|
||||
dependencies:
|
||||
'@types/node': 22.19.21
|
||||
form-data: 4.0.6
|
||||
form-data: 4.0.5
|
||||
|
||||
'@types/node@18.19.130':
|
||||
dependencies:
|
||||
@@ -4079,7 +4078,7 @@ snapshots:
|
||||
axios@1.17.0:
|
||||
dependencies:
|
||||
follow-redirects: 1.16.0
|
||||
form-data: 4.0.6
|
||||
form-data: 4.0.5
|
||||
https-proxy-agent: 5.0.1
|
||||
proxy-from-env: 2.1.0
|
||||
transitivePeerDependencies:
|
||||
@@ -4562,7 +4561,7 @@ snapshots:
|
||||
|
||||
form-data-encoder@1.7.2: {}
|
||||
|
||||
form-data@4.0.6:
|
||||
form-data@4.0.5:
|
||||
dependencies:
|
||||
asynckit: 0.4.0
|
||||
combined-stream: 1.0.8
|
||||
|
||||
@@ -6,7 +6,6 @@ onlyBuiltDependencies:
|
||||
- better-sqlite3
|
||||
|
||||
overrides:
|
||||
"form-data@<4.0.6": ">=4.0.6"
|
||||
"picomatch@<2.3.2": "^2.3.2"
|
||||
"picomatch@>=4.0.0 <4.0.4": "^4.0.4"
|
||||
"jws@4.0.0": "4.0.1"
|
||||
|
||||
@@ -253,11 +253,6 @@ export default class MemoryClient {
|
||||
messages: Array<Message>,
|
||||
options: AddMemoryOptions & Record<string, any> = {},
|
||||
): Promise<Array<Memory>> {
|
||||
// Tightly scoped validation guard to resolve #5465
|
||||
if (!messages || (Array.isArray(messages) && messages.length === 0)) {
|
||||
throw new Error("Cannot process an empty messages payload.");
|
||||
}
|
||||
|
||||
if (this.telemetryId === "") await this.ping();
|
||||
|
||||
const payload = this._preparePayload(messages, options);
|
||||
@@ -701,10 +696,7 @@ export default class MemoryClient {
|
||||
throw new Error("Missing filters or schema");
|
||||
}
|
||||
|
||||
// filters and schema are user-controlled blobs whose keys must reach the
|
||||
// API verbatim; only the remaining SDK params (e.g. exportInstructions)
|
||||
// get camel->snake conversion. See issue #5593.
|
||||
const { filters, schema, ...rest } = data;
|
||||
const { filters, ...rest } = data;
|
||||
const response = await this._fetchWithErrorHandling(
|
||||
`${this.host}/v1/exports/`,
|
||||
{
|
||||
@@ -713,7 +705,6 @@ export default class MemoryClient {
|
||||
body: JSON.stringify({
|
||||
...camelToSnakeKeys(rest),
|
||||
filters,
|
||||
schema,
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
@@ -169,9 +169,7 @@ export interface PaginatedMemories {
|
||||
|
||||
export interface ProjectResponse {
|
||||
customInstructions?: string;
|
||||
// The API returns category objects (`[{ "<name>": "<description>" }]`),
|
||||
// not bare strings (see issue #5738).
|
||||
customCategories?: custom_categories[];
|
||||
customCategories?: string[];
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
|
||||
@@ -59,15 +59,16 @@ describe("MemoryClient - add()", () => {
|
||||
expect(getFetchBody(call!).user_id).toBe("user_1");
|
||||
});
|
||||
|
||||
test("throws an error when given an empty messages array", async () => {
|
||||
setupMockFetch();
|
||||
test("sends empty messages array without crashing", async () => {
|
||||
const extra = new Map<string, { status: number; body: unknown }>();
|
||||
extra.set("/v3/memories/add/", { status: 200, body: [] });
|
||||
const mock = setupMockFetch(extra);
|
||||
|
||||
const client = new MemoryClient({ apiKey: TEST_API_KEY });
|
||||
await client.add([], { userId: "u1" });
|
||||
|
||||
//Asserts that the validation guard catches the empty input early
|
||||
await expect(client.add([], { userId: "u1" })).rejects.toThrow(
|
||||
"Cannot process an empty messages payload.",
|
||||
);
|
||||
const call = findFetchCall(mock, "/v3/memories/add/", "POST");
|
||||
expect(getFetchBody(call!).messages).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
/**
|
||||
* MemoryClient unit tests — createMemoryExport.
|
||||
* Verifies request construction, not mock response echo.
|
||||
*/
|
||||
import { MemoryClient } from "../mem0";
|
||||
import { TEST_API_KEY } from "./helpers";
|
||||
import {
|
||||
setupMockFetch,
|
||||
findFetchCall,
|
||||
getFetchBody,
|
||||
installConsoleSuppression,
|
||||
} from "./setup";
|
||||
|
||||
installConsoleSuppression();
|
||||
|
||||
describe("MemoryClient - createMemoryExport()", () => {
|
||||
test("sends user-defined schema keys verbatim, converts SDK params", async () => {
|
||||
const extra = new Map<string, { status: number; body: unknown }>();
|
||||
extra.set("/v1/exports/", {
|
||||
status: 200,
|
||||
body: { message: "ok", id: "exp_1" },
|
||||
});
|
||||
const mock = setupMockFetch(extra);
|
||||
|
||||
const client = new MemoryClient({ apiKey: TEST_API_KEY });
|
||||
await client.createMemoryExport({
|
||||
// camelCase keys here are user-defined export field names — they must
|
||||
// not be snake_cased on the way out.
|
||||
schema: { messageId: "string", customField: { nestedKey: "number" } },
|
||||
filters: { user_id: "u1" },
|
||||
exportInstructions: "export it",
|
||||
});
|
||||
|
||||
const call = findFetchCall(mock, "/v1/exports/", "POST");
|
||||
expect(call).toBeDefined();
|
||||
const body = getFetchBody(call!);
|
||||
|
||||
// User blobs round-trip verbatim (no camel->snake on their keys).
|
||||
expect(body.schema).toEqual({
|
||||
messageId: "string",
|
||||
customField: { nestedKey: "number" },
|
||||
});
|
||||
expect(body.filters).toEqual({ user_id: "u1" });
|
||||
// SDK param is still snake_cased.
|
||||
expect(body.export_instructions).toBe("export it");
|
||||
});
|
||||
});
|
||||
@@ -1,148 +0,0 @@
|
||||
import { camelToSnakeKeys, snakeToCamelKeys } from "../utils";
|
||||
|
||||
describe("camelToSnakeKeys / snakeToCamelKeys", () => {
|
||||
it("converts SDK-defined keys between camelCase and snake_case", () => {
|
||||
expect(camelToSnakeKeys({ userId: "u1", agentId: "a1" })).toEqual({
|
||||
user_id: "u1",
|
||||
agent_id: "a1",
|
||||
});
|
||||
expect(snakeToCamelKeys({ user_id: "u1", agent_id: "a1" })).toEqual({
|
||||
userId: "u1",
|
||||
agentId: "a1",
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves logical operator keys (OR/AND/NOT)", () => {
|
||||
expect(camelToSnakeKeys({ OR: [{ userId: "u1" }] })).toEqual({
|
||||
OR: [{ user_id: "u1" }],
|
||||
});
|
||||
});
|
||||
|
||||
describe("user-controlled metadata blob (issue #5055)", () => {
|
||||
it("does not camelize snake_case keys inside metadata on read", () => {
|
||||
const apiResponse = {
|
||||
id: "mem-1",
|
||||
user_id: "u1",
|
||||
metadata: { message_id: "x", some_custom_key: "y" },
|
||||
};
|
||||
|
||||
expect(snakeToCamelKeys(apiResponse)).toEqual({
|
||||
id: "mem-1",
|
||||
userId: "u1",
|
||||
metadata: { message_id: "x", some_custom_key: "y" },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not snake_case camelCase keys inside metadata on write", () => {
|
||||
const payload = {
|
||||
userId: "u1",
|
||||
metadata: { messageId: "x", someCustomKey: "y" },
|
||||
};
|
||||
|
||||
expect(camelToSnakeKeys(payload)).toEqual({
|
||||
user_id: "u1",
|
||||
metadata: { messageId: "x", someCustomKey: "y" },
|
||||
});
|
||||
});
|
||||
|
||||
it("round-trips arbitrary metadata keys losslessly", () => {
|
||||
const metadata = {
|
||||
message_id: "abc",
|
||||
camelKey: 1,
|
||||
nested: { deep_snake: true, deepCamel: false },
|
||||
arr: [{ inner_key: 1 }],
|
||||
};
|
||||
|
||||
const roundTripped = snakeToCamelKeys(
|
||||
camelToSnakeKeys({ userId: "u1", metadata }),
|
||||
);
|
||||
|
||||
expect(roundTripped.metadata).toEqual(metadata);
|
||||
});
|
||||
|
||||
it("preserves metadata nested inside an array of results", () => {
|
||||
const apiResponse = {
|
||||
results: [
|
||||
{ id: "1", metadata: { message_id: "x" } },
|
||||
{ id: "2", metadata: { another_key: "z" } },
|
||||
],
|
||||
};
|
||||
|
||||
expect(snakeToCamelKeys(apiResponse)).toEqual({
|
||||
results: [
|
||||
{ id: "1", metadata: { message_id: "x" } },
|
||||
{ id: "2", metadata: { another_key: "z" } },
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("user-controlled structuredDataSchema blob (issue #5055)", () => {
|
||||
it("converts the outer key but leaves user field names on write", () => {
|
||||
expect(
|
||||
camelToSnakeKeys({
|
||||
structuredDataSchema: { firstName: "string", lastName: "string" },
|
||||
}),
|
||||
).toEqual({
|
||||
// outer SDK key is snake_cased, user-defined field names are not
|
||||
structured_data_schema: { firstName: "string", lastName: "string" },
|
||||
});
|
||||
});
|
||||
|
||||
it("converts the outer key but leaves user field names on read", () => {
|
||||
expect(
|
||||
snakeToCamelKeys({
|
||||
structured_data_schema: { first_name: "string", last_name: "string" },
|
||||
}),
|
||||
).toEqual({
|
||||
structuredDataSchema: { first_name: "string", last_name: "string" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("user-controlled customCategories names (issue #5738)", () => {
|
||||
it("converts the outer key but leaves multi-word category names on write", () => {
|
||||
expect(
|
||||
camelToSnakeKeys({
|
||||
customCategories: [
|
||||
{ work_life_balance: "desc" },
|
||||
{ AIResearch: "desc" },
|
||||
],
|
||||
}),
|
||||
).toEqual({
|
||||
// outer SDK key is snake_cased, user-defined category names are not
|
||||
custom_categories: [
|
||||
{ work_life_balance: "desc" },
|
||||
{ AIResearch: "desc" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("converts the outer key but leaves category names verbatim on read", () => {
|
||||
expect(
|
||||
snakeToCamelKeys({
|
||||
custom_categories: [
|
||||
{ work_life_balance: "desc" },
|
||||
{ AIResearch: "desc" },
|
||||
],
|
||||
}),
|
||||
).toEqual({
|
||||
customCategories: [
|
||||
{ work_life_balance: "desc" },
|
||||
{ AIResearch: "desc" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("round-trips category names losslessly (write then read)", () => {
|
||||
const customCategories = [
|
||||
{ work_life_balance: "balance between work and life" },
|
||||
{ AIResearch: "artificial intelligence research" },
|
||||
];
|
||||
const roundTripped = snakeToCamelKeys(
|
||||
camelToSnakeKeys({ customCategories }),
|
||||
);
|
||||
expect(roundTripped.customCategories).toEqual(customCategories);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -14,32 +14,9 @@ function snakeToCamel(str: string): string {
|
||||
return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Keys whose values are user-controlled, opaque blobs. Their nested keys must
|
||||
* be passed through verbatim — converting them would silently rewrite the
|
||||
* user's own keys and break round-trips (see issue #5055).
|
||||
*
|
||||
* The check runs against the source key, so a multi-word key must be listed in
|
||||
* both casings to be covered in both directions: the camelCase form for the
|
||||
* outbound `camelToSnakeKeys` path and the snake_case form for the inbound
|
||||
* `snakeToCamelKeys` path. `metadata` is spelled identically in both, so one
|
||||
* entry suffices; `structuredDataSchema` needs both.
|
||||
*/
|
||||
const OPAQUE_VALUE_KEYS = new Set([
|
||||
"metadata",
|
||||
"structuredDataSchema",
|
||||
"structured_data_schema",
|
||||
// Custom-category names are user-controlled keys (`[{ "<name>": "<desc>" }]`).
|
||||
// Listed in both casings so they round-trip verbatim in both directions
|
||||
// (see issue #5738; same class as `metadata`/`structuredDataSchema`).
|
||||
"customCategories",
|
||||
"custom_categories",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Recursively converts all keys of an object from camelCase to snake_case.
|
||||
* Used for converting user-facing camelCase params to API snake_case payloads.
|
||||
* Values under {@link OPAQUE_VALUE_KEYS} (e.g. `metadata`) are left untouched.
|
||||
*/
|
||||
export function camelToSnakeKeys(obj: any): any {
|
||||
if (obj === null || obj === undefined || typeof obj !== "object") return obj;
|
||||
@@ -49,7 +26,7 @@ export function camelToSnakeKeys(obj: any): any {
|
||||
return Object.fromEntries(
|
||||
Object.entries(obj).map(([key, value]) => [
|
||||
camelToSnake(key),
|
||||
OPAQUE_VALUE_KEYS.has(key) ? value : camelToSnakeKeys(value),
|
||||
camelToSnakeKeys(value),
|
||||
]),
|
||||
);
|
||||
}
|
||||
@@ -57,7 +34,6 @@ export function camelToSnakeKeys(obj: any): any {
|
||||
/**
|
||||
* Recursively converts all keys of an object from snake_case to camelCase.
|
||||
* Used for converting API snake_case responses to user-facing camelCase.
|
||||
* Values under {@link OPAQUE_VALUE_KEYS} (e.g. `metadata`) are left untouched.
|
||||
*/
|
||||
export function snakeToCamelKeys(obj: any): any {
|
||||
if (obj === null || obj === undefined || typeof obj !== "object") return obj;
|
||||
@@ -67,7 +43,7 @@ export function snakeToCamelKeys(obj: any): any {
|
||||
return Object.fromEntries(
|
||||
Object.entries(obj).map(([key, value]) => [
|
||||
snakeToCamel(key),
|
||||
OPAQUE_VALUE_KEYS.has(key) ? value : snakeToCamelKeys(value),
|
||||
snakeToCamelKeys(value),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,13 +14,7 @@ export class AnthropicLLM implements LLM {
|
||||
if (!apiKey) {
|
||||
throw new Error("Anthropic API key is required");
|
||||
}
|
||||
// Forward baseURL to the client when set so proxy/gateway users are
|
||||
// honored (parity with the OpenAI provider and the Python fix in #5626).
|
||||
const clientArgs: { apiKey: string; baseURL?: string } = { apiKey };
|
||||
if (config.baseURL) {
|
||||
clientArgs.baseURL = config.baseURL;
|
||||
}
|
||||
this.client = new Anthropic(clientArgs);
|
||||
this.client = new Anthropic({ apiKey });
|
||||
this.model = config.model || "claude-sonnet-4-6";
|
||||
// Defaults mirror the Python provider's AnthropicConfig
|
||||
// (max_tokens=2000, temperature=0.1, top_p omitted).
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user