Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

Add tested Pi/OpenClaw/Hermes integration fixes (#230)

Mandeep Singh2daeb5afda16
diff --git a/README.md b/README.md
index b2602507..eff3339b 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
<p align="center">
<strong>Your coding agent remembers everything. No more re-explaining.</strong><br/>
- Persistent memory for Claude Code, Cursor, Gemini CLI, OpenCode, and any MCP client.
+ Persistent memory for Claude Code, Cursor, Gemini CLI, Codex CLI, pi, OpenCode, and any MCP client.
</p>
<p align="center">
@@ -341,7 +341,7 @@ Install agentmemory: run `npx @agentmemory/agentmemory` in a separate terminal t
<summary><b>OpenClaw (paste this prompt)</b></summary>
```
-Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to my OpenClaw MCP config so agentmemory is available with all 50 memory tools:
+Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to my OpenClaw MCP config so agentmemory is available with all 43 memory tools:
{
"mcpServers": {
@@ -352,7 +352,7 @@ Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separa
}
}
-Restart OpenClaw. Verify with `curl http://localhost:3111/agentmemory/health`. Open http://localhost:3113 for the real-time viewer. For deeper 4-hook gateway integration, see integrations/openclaw in the agentmemory repo.
+Restart OpenClaw. Verify with `curl http://localhost:3111/agentmemory/health`. Open http://localhost:3113 for the real-time viewer. For deeper memory-slot integration, copy `integrations/openclaw` to `~/.openclaw/extensions/agentmemory` and enable `plugins.slots.memory = "agentmemory"` in `~/.openclaw/openclaw.json`.
```
Full guide: [`integrations/openclaw/`](integrations/openclaw/)
@@ -363,13 +363,16 @@ Full guide: [`integrations/openclaw/`](integrations/openclaw/)
<summary><b>Hermes Agent (paste this prompt)</b></summary>
```
-Install agentmemory for Hermes. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to ~/.hermes/config.yaml so Hermes can use agentmemory as an MCP server with all 50 memory tools:
+Install agentmemory for Hermes. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111. Then add this to ~/.hermes/config.yaml so Hermes can use agentmemory as an MCP server with all 43 memory tools:
mcp_servers:
agentmemory:
command: npx
args: ["-y", "@agentmemory/mcp"]
+memory:
+ provider: agentmemory
+
Verify with `curl http://localhost:3111/agentmemory/health`. Open http://localhost:3113 for the real-time viewer. For deeper 6-hook memory provider integration (pre-LLM context injection, turn capture, MEMORY.md mirroring, system prompt block), copy integrations/hermes from the agentmemory repo to ~/.hermes/plugins/agentmemory.
```
@@ -386,11 +389,12 @@ Then add the MCP config for your agent:
| Agent | Setup |
|---|---|
| **Cursor** | Add to `~/.cursor/mcp.json`: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["-y", "@agentmemory/mcp"]}}}` |
-| **OpenClaw** | Add to MCP config: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["-y", "@agentmemory/mcp"]}}}` or use the [gateway plugin](integrations/openclaw/) |
-| **Gemini CLI** | `gemini mcp add agentmemory -- npx -y @agentmemory/mcp` |
-| **Codex CLI** | Add to `.codex/config.yaml`: `mcp_servers: {agentmemory: {command: npx, args: ["-y", "@agentmemory/mcp"]}}` |
+| **OpenClaw** | Add to MCP config: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["-y", "@agentmemory/mcp"]}}}` or use the [memory plugin](integrations/openclaw/) |
+| **Gemini CLI** | `gemini mcp add agentmemory npx -y @agentmemory/mcp --scope user` |
+| **Codex CLI** | `codex mcp add agentmemory -- npx -y @agentmemory/mcp` or add `[mcp_servers.agentmemory]` to `.codex/config.toml` |
+| **pi** | Copy [`integrations/pi`](integrations/pi/) to `~/.pi/agent/extensions/agentmemory` and restart pi |
| **OpenCode** | Add to `opencode.json`: `{"mcp": {"agentmemory": {"type": "local", "command": ["npx", "-y", "@agentmemory/mcp"], "enabled": true}}}` |
-| **Hermes Agent** | Add to `~/.hermes/config.yaml` or use the [memory provider plugin](integrations/hermes/) |
+| **Hermes Agent** | Add to `~/.hermes/config.yaml` with `memory.provider: agentmemory` or use the [memory provider plugin](integrations/hermes/) |
| **Cline / Goose / Kilo Code** | Add MCP server in settings |
| **Claude Desktop** | Add to `claude_desktop_config.json`: `{"mcpServers": {"agentmemory": {"command": "npx", "args": ["-y", "@agentmemory/mcp"]}}}` |
| **Aider** | REST API: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'` |
diff --git a/integrations/hermes/README.md b/integrations/hermes/README.md
index ee648105..ffb6c8c4 100644
--- a/integrations/hermes/README.md
+++ b/integrations/hermes/README.md
@@ -37,6 +37,9 @@ mcp_servers:
command: npx
args: ["-y", "@agentmemory/mcp"]
+memory:
+ provider: agentmemory
+
Verify it's working with
`curl http://localhost:3111/agentmemory/health` — it should return
{"status":"healthy"}. Open the real-time viewer at
@@ -62,9 +65,12 @@ mcp_servers:
agentmemory:
command: npx
args: ["-y", "@agentmemory/mcp"]
+
+memory:
+ provider: agentmemory
```
-This gives Hermes access to all 43 MCP tools. Start the server separately:
+This gives Hermes access to all 43 MCP tools and enables the agentmemory memory provider. Start the server separately:
```bash
npx @agentmemory/agentmemory
@@ -84,7 +90,7 @@ Start the agentmemory server:
npx @agentmemory/agentmemory
```
-The plugin auto-detects the running server and hooks into the Hermes agent loop:
+The plugin auto-detects the running server and hooks into the Hermes agent loop. Make sure `memory.provider` is set to `agentmemory` in `~/.hermes/config.yaml`:
- `prefetch()` injects relevant memories before each LLM call
- `sync_turn()` captures every conversation turn in the background
diff --git a/integrations/hermes/__init__.py b/integrations/hermes/__init__.py
index 2677820c..7fe74229 100644
--- a/integrations/hermes/__init__.py
+++ b/integrations/hermes/__init__.py
@@ -1,7 +1,7 @@
"""
agentmemory memory provider for Hermes Agent.
-Drop this folder into ~/.hermes/plugins/memory/agentmemory/
+Drop this folder into ~/.hermes/plugins/agentmemory/
or install via: hermes plugin install agentmemory
Requires agentmemory server running: npx @agentmemory/agentmemory
@@ -91,7 +91,7 @@ class AgentMemoryProvider(MemoryProvider):
if not _validate_url(base):
return False
try:
- req = Request(f"{base}/", method="GET")
+ req = Request(f"{base}/agentmemory/health", method="GET")
with urlopen(req, timeout=2):
return True
except Exception:
diff --git a/integrations/openclaw/README.md b/integrations/openclaw/README.md
index b3a632a7..8dc0258d 100644
--- a/integrations/openclaw/README.md
+++ b/integrations/openclaw/README.md
@@ -14,7 +14,7 @@
<p align="center">
<img src="https://img.shields.io/badge/MCP-43_tools-1f6feb?style=flat-square" alt="43 MCP tools" />
- <img src="https://img.shields.io/badge/Hooks-4_lifecycle-1f6feb?style=flat-square" alt="4 lifecycle hooks" />
+ <img src="https://img.shields.io/badge/Plugin-memory_slot-1f6feb?style=flat-square" alt="OpenClaw memory plugin" />
<img src="https://img.shields.io/badge/[email protected]%25-00875f?style=flat-square" alt="95.2% R@5" />
<img src="https://img.shields.io/badge/Self--hosted-yes-00875f?style=flat-square" alt="Self-hosted" />
<img src="https://img.shields.io/badge/License-Apache_2.0-blue?style=flat-square" alt="Apache 2.0" />
@@ -27,11 +27,9 @@
**Paste this prompt into OpenClaw** and it does the whole setup for you:
```text
-Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a
-separate terminal to start the memory server on localhost:3111. Then add
-this to my OpenClaw MCP config so agentmemory is available as an MCP
-server with all 43 memory tools (memory_recall, memory_save,
-memory_smart_search, memory_timeline, memory_profile, etc.):
+Install agentmemory for OpenClaw. Run `npx @agentmemory/agentmemory` in a separate terminal to start the memory server on localhost:3111.
+
+For zero-code setup, add this MCP server so OpenClaw gets all 43 memory tools:
{
"mcpServers": {
@@ -42,31 +40,34 @@ memory_smart_search, memory_timeline, memory_profile, etc.):
}
}
-Restart OpenClaw. Verify it's working with
-`curl http://localhost:3111/agentmemory/health` — it should return
-{"status":"healthy"}. Open the real-time viewer at
-http://localhost:3113 to watch memories being captured live.
+For deeper memory integration, copy `integrations/openclaw` from the agentmemory repo to `~/.openclaw/extensions/agentmemory`, then enable it in `~/.openclaw/openclaw.json`:
-If I want deeper integration with pre-LLM context injection and
-automatic tool-use capture, copy `integrations/openclaw` from the
-agentmemory repo to `~/.openclaw/plugins/memory/agentmemory` — that
-gives me the 4-hook gateway plugin instead of just the MCP server.
+{
+ "plugins": {
+ "slots": {
+ "memory": "agentmemory"
+ },
+ "entries": {
+ "agentmemory": {
+ "enabled": true,
+ "config": {
+ "base_url": "http://localhost:3111",
+ "token_budget": 2000,
+ "min_confidence": 0.5,
+ "fallback_on_error": true,
+ "timeout_ms": 5000
+ }
+ }
+ }
+ }
+}
+
+Restart OpenClaw. Verify with `curl http://localhost:3111/agentmemory/health`. Open http://localhost:3113 for the real-time viewer.
```
That's it. OpenClaw handles the rest.
-## Why you want this
-
-OpenClaw agents restart fresh every session. You waste tokens re-explaining architecture, re-discovering bugs, re-teaching preferences. agentmemory captures every tool use automatically and injects relevant context when the next session starts.
-
-- **92% fewer tokens** per session vs full-context pasting
-- **12 auto-capture hooks** — zero manual `memory.add()` calls
-- **MCP-native** — same server works for Claude Code, Cursor, Gemini CLI, Hermes, and OpenClaw at the same time
-- **Self-hosted** — no external database, no cloud, no API key needed for embeddings
-
-## Quick setup
-
-### Option 1: MCP server (zero code)
+## Option 1: MCP server (zero code)
Start the agentmemory server in a separate terminal:
@@ -89,86 +90,58 @@ Then add to your OpenClaw MCP config:
OpenClaw now has access to all 43 MCP tools including `memory_recall`, `memory_save`, `memory_smart_search`, `memory_timeline`, `memory_profile`, and more.
-### Option 2: Gateway plugin (deeper integration)
-
-If you're running an OpenClaw gateway, drop this folder into your gateway's plugins directory:
-
-```bash
-cp -r integrations/openclaw ~/.openclaw/plugins/memory/agentmemory
-```
+## Option 2: OpenClaw memory plugin (deeper integration)
-Start the agentmemory server:
+Copy this folder into OpenClaw's extension directory:
```bash
-npx @agentmemory/agentmemory
-```
-
-The plugin auto-detects the running server and hooks into the OpenClaw agent loop:
-
-- `onSessionStart` starts a new session on the agentmemory server and injects any returned context
-- `onPreLlmCall` injects token-budgeted memories before each LLM call (BM25 + vector + graph fusion)
-- `onPostToolUse` records every tool use, error, and decision after execution
-- `onSessionEnd` marks the session complete so raw observations can be compressed into structured memory
-
-Configure via `~/.openclaw/plugins/memory/agentmemory/config.yaml`:
-
-```yaml
-enabled: true
-base_url: http://localhost:3111
-token_budget: 2000
-min_confidence: 0.5
+mkdir -p ~/.openclaw/extensions
+cp -r integrations/openclaw ~/.openclaw/extensions/agentmemory
```
-## What your agent gets
-
-### Automatic context injection
-
-When a session starts, agentmemory injects ~1,900 tokens of the most relevant past context:
+Then enable it in `~/.openclaw/openclaw.json`:
-```text
-Project profile:
- - Auth uses JWT middleware in src/middleware/auth.ts (jose, not jsonwebtoken)
- - Tests in test/auth.test.ts cover token validation
- - Database uses Prisma with include{} to avoid N+1 queries
- - Rate limiting: 100 req/min default, Redis for prod
-
-Recent decisions:
- - Chose jose over jsonwebtoken for Edge compatibility (2026-03-15)
- - N+1 fix dropped query time 450ms → 28ms (2026-03-20)
+```json
+{
+ "plugins": {
+ "slots": {
+ "memory": "agentmemory"
+ },
+ "entries": {
+ "agentmemory": {
+ "enabled": true,
+ "config": {
+ "base_url": "http://localhost:3111",
+ "token_budget": 2000,
+ "min_confidence": 0.5,
+ "fallback_on_error": true,
+ "timeout_ms": 5000
+ }
+ }
+ }
+ }
+}
```
-### Semantic search across sessions
-
-Ask "what was that fix for slow user queries?" and the agent finds the Prisma include{} decision from three weeks ago. BM25 + vector + knowledge graph fusion.
-
-### Privacy filtering
+What the plugin does:
-Every captured observation is scanned for API keys, secrets, bearer tokens, and `<private>` tags. These are stripped before storage. Modern token formats supported: `sk-`, `sk-proj-`, `ghp_/ghs_/ghu_`, AWS keys, and more.
-
-### Multi-agent coordination
-
-If you're running multiple OpenClaw agents on the same codebase:
-
-- **Leases** give one agent exclusive claim on an action so they don't stomp each other
-- **Signals** let agents send threaded messages to each other with read receipts
-- **Mesh sync** shares memory between agentmemory instances (requires `AGENTMEMORY_SECRET`)
+- recalls relevant long-term memory before the agent starts
+- captures completed conversation turns after the agent finishes
+- shares the same backend with Claude Code, Codex CLI, Gemini CLI, Hermes, pi, and other agents
## Troubleshooting
-**"Connection refused on port 3111"** — The agentmemory server isn't running. Start it with `npx @agentmemory/agentmemory` in a separate terminal.
-
-**"No memories returned"** — Check `http://localhost:3113` (the real-time viewer). If there are no observations, the hooks aren't firing. Make sure your OpenClaw plugin is loaded and enabled.
+**Plugin validates but does not load** — make sure the folder contains `package.json`, `openclaw.plugin.json`, and `plugin.mjs`, and that `plugins.slots.memory` is set to `agentmemory`.
-**"Search returns irrelevant results"** — Install local embeddings: `npm install @xenova/transformers`. This enables vector search for +8pp recall over BM25-only.
+**Connection refused on port 3111** — the agentmemory server is not running. Start it with `npx @agentmemory/agentmemory`.
-**"I want to see what agentmemory is learning"** — Open `http://localhost:3113` in a browser. Live observation stream, session explorer, memory graph, and health dashboard.
+**No memories returned** — open `http://localhost:3113` and verify observations are being captured.
## See also
- [agentmemory main README](../../README.md)
-- [Benchmark results](../../benchmark/LONGMEMEVAL.md) — 95.2% R@5 on LongMemEval-S
-- [Competitor comparison](../../benchmark/COMPARISON.md) — vs mem0, Letta, Khoj, claude-mem, Hippo
-- [Hermes integration](../hermes/README.md) — same server also works with Hermes Agent
+- [Hermes integration](../hermes/README.md)
+- [pi integration](../pi/README.md)
## License
diff --git a/integrations/openclaw/openclaw.plugin.json b/integrations/openclaw/openclaw.plugin.json
new file mode 100644
index 00000000..9f154384
--- /dev/null
+++ b/integrations/openclaw/openclaw.plugin.json
@@ -0,0 +1,27 @@
+{
+ "id": "agentmemory",
+ "kind": "memory",
+ "name": "agentmemory",
+ "description": "Persistent cross-session memory for OpenClaw via agentmemory.",
+ "version": "0.9.4",
+ "configSchema": {
+ "type": "object",
+ "additionalProperties": false,
+ "properties": {
+ "enabled": { "type": "boolean" },
+ "base_url": { "type": "string" },
+ "token_budget": { "type": "number" },
+ "min_confidence": { "type": "number" },
+ "fallback_on_error": { "type": "boolean" },
+ "timeout_ms": { "type": "number" }
+ }
+ },
+ "uiHints": {
+ "enabled": { "label": "Enabled" },
+ "base_url": { "label": "Base URL", "help": "agentmemory REST server base URL" },
+ "token_budget": { "label": "Token Budget", "help": "Approximate context budget to inject before the agent starts" },
+ "min_confidence": { "label": "Min Confidence" },
+ "fallback_on_error": { "label": "Fallback On Error" },
+ "timeout_ms": { "label": "Timeout (ms)" }
+ }
+}
diff --git a/integrations/openclaw/package.json b/integrations/openclaw/package.json
new file mode 100644
index 00000000..c671f5d5
--- /dev/null
+++ b/integrations/openclaw/package.json
@@ -0,0 +1,10 @@
+{
+ "name": "agentmemory",
+ "version": "0.9.4",
+ "type": "module",
+ "openclaw": {
+ "extensions": [
+ "./plugin.mjs"
+ ]
+ }
+}
diff --git a/integrations/openclaw/plugin.mjs b/integrations/openclaw/plugin.mjs
index 7850f3fc..1ed9a3b5 100644
--- a/integrations/openclaw/plugin.mjs
+++ b/integrations/openclaw/plugin.mjs
@@ -1,97 +1,162 @@
/**
- * agentmemory plugin for OpenClaw gateway
+ * agentmemory plugin for OpenClaw
*
- * Hooks into the OpenClaw agent loop:
- * - onSessionStart: starts a session on the memory server and injects any returned context
- * - onPreLlmCall: injects token-budgeted memories before each LLM call
- * - onPostToolUse: records every tool use, error, and decision after execution
- * - onSessionEnd: marks the session complete for downstream compression
+ * Deeper integration than raw MCP:
+ * - recalls relevant memories before the agent starts
+ * - captures completed conversation turns after the agent finishes
*
- * Requires the agentmemory server running on localhost:3111.
+ * Requires the agentmemory server on localhost:3111.
* Start it with: npx @agentmemory/agentmemory
*/
const DEFAULT_BASE_URL = "http://localhost:3111";
const DEFAULT_TIMEOUT_MS = 5000;
-export class AgentmemoryPlugin {
- constructor(config = {}) {
- this.enabled = config.enabled !== false;
- this.baseUrl = config.base_url ?? DEFAULT_BASE_URL;
- this.tokenBudget = config.token_budget ?? 2000;
- this.minConfidence = config.min_confidence ?? 0.5;
- this.fallbackOnError = config.fallback_on_error !== false;
- this.timeoutMs = config.timeout_ms ?? DEFAULT_TIMEOUT_MS;
- this.secret = process.env.AGENTMEMORY_SECRET;
+const configSchema = {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ enabled: { type: "boolean" },
+ base_url: { type: "string" },
+ token_budget: { type: "number" },
+ min_confidence: { type: "number" },
+ fallback_on_error: { type: "boolean" },
+ timeout_ms: { type: "number" },
+ },
+};
+
+function extractText(content) {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return "";
+ return content
+ .flatMap((block) => {
+ if (!block || typeof block !== "object") return [];
+ if (block.type === "text" && typeof block.text === "string") return [block.text];
+ return [];
+ })
+ .join("\n")
+ .trim();
+}
+
+function lastAssistantText(messages) {
+ for (const message of [...messages].reverse()) {
+ if (!message || typeof message !== "object") continue;
+ if (message.role !== "assistant") continue;
+ const text = extractText(message.content);
+ if (text) return text;
}
+ return "";
+}
- get name() {
- return "agentmemory";
+function latestUserText(messages) {
+ for (const message of [...messages].reverse()) {
+ if (!message || typeof message !== "object") continue;
+ if (message.role !== "user") continue;
+ const text = extractText(message.content);
+ if (text) return text;
}
+ return "";
+}
- async postJson(path, payload) {
- const headers = { "Content-Type": "application/json" };
- if (this.secret) headers["Authorization"] = `Bearer ${this.secret}`;
+function formatResults(results) {
+ if (!Array.isArray(results) || results.length === 0) return "";
+ return results
+ .slice(0, 5)
+ .map((result, index) => {
+ const obs = result?.observation ?? result ?? {};
+ const title = (obs.title || `Memory ${index + 1}`).trim();
+ const narrative = (obs.narrative || "").trim();
+ const type = (obs.type || "memory").trim();
+ return `- ${title} (${type})${narrative ? `: ${narrative}` : ""}`;
+ })
+ .join("\n");
+}
+
+function createClient(cfg, api) {
+ const baseUrl = String(cfg.base_url || DEFAULT_BASE_URL).replace(/\/+$/, "");
+ const timeoutMs = Number(cfg.timeout_ms || DEFAULT_TIMEOUT_MS);
+ const fallbackOnError = cfg.fallback_on_error !== false;
+ const secret = process.env.AGENTMEMORY_SECRET;
+ async function postJson(path, payload) {
+ const headers = { "Content-Type": "application/json" };
+ if (secret) headers.Authorization = `Bearer ${secret}`;
try {
- const res = await fetch(`${this.baseUrl}${path}`, {
+ const res = await fetch(`${baseUrl}${path}`, {
method: "POST",
headers,
body: JSON.stringify(payload),
- signal: AbortSignal.timeout(this.timeoutMs),
+ signal: AbortSignal.timeout(timeoutMs),
});
if (!res.ok) {
- if (this.fallbackOnError) return null;
+ if (fallbackOnError) return null;
const body = await res.text().catch(() => "");
- throw new Error(
- `agentmemory POST ${path} failed: ${res.status} ${res.statusText}${body ? ` — ${body.slice(0, 200)}` : ""}`,
- );
+ throw new Error(`agentmemory ${path} failed: ${res.status} ${body}`);
}
return await res.json();
- } catch (err) {
- if (!this.fallbackOnError) throw err;
+ } catch (error) {
+ if (!fallbackOnError) throw error;
+ api.logger.warn?.(`agentmemory: ${String(error)}`);
return null;
}
}
- async onSessionStart(ctx) {
- if (!this.enabled) return;
- const result = await this.postJson("/agentmemory/session/start", {
- sessionId: ctx.sessionId,
- project: ctx.project || ctx.cwd,
- cwd: ctx.cwd,
- });
- if (result?.context) ctx.injectContext(result.context);
- }
+ return { postJson, baseUrl };
+}
- async onPreLlmCall(ctx) {
- if (!this.enabled) return;
- const result = await this.postJson("/agentmemory/context", {
- sessionId: ctx.sessionId,
- project: ctx.project || ctx.cwd,
- budget: this.tokenBudget,
- });
- if (result?.context) ctx.injectContext(result.context);
- }
+const plugin = {
+ id: "agentmemory",
+ name: "agentmemory",
+ description: "Shared cross-session memory via the local agentmemory server.",
+ configSchema,
+ register(api) {
+ const cfg = {
+ enabled: api.pluginConfig?.enabled !== false,
+ base_url: api.pluginConfig?.base_url || DEFAULT_BASE_URL,
+ token_budget: api.pluginConfig?.token_budget || 2000,
+ min_confidence: api.pluginConfig?.min_confidence || 0.5,
+ fallback_on_error: api.pluginConfig?.fallback_on_error !== false,
+ timeout_ms: api.pluginConfig?.timeout_ms || DEFAULT_TIMEOUT_MS,
+ };
+ const client = createClient(cfg, api);
- async onPostToolUse(ctx) {
- if (!this.enabled) return;
- await this.postJson("/agentmemory/observe", {
- hookType: "post_tool_use",
- sessionId: ctx.sessionId,
- timestamp: new Date().toISOString(),
- data: {
- tool_name: ctx.toolName,
- tool_input: ctx.toolInput,
- tool_output: ctx.toolOutput,
- },
+ api.on("before_agent_start", async (event) => {
+ if (!cfg.enabled) return;
+ const prompt = typeof event?.prompt === "string" ? event.prompt.trim() : "";
+ if (!prompt) return;
+ const result = await client.postJson("/agentmemory/smart-search", {
+ query: prompt,
+ limit: 5,
+ });
+ const block = formatResults(result?.results || []);
+ if (!block) return;
+ return {
+ prependContext: `Relevant long-term memory from agentmemory:\n${block}`,
+ };
});
- }
- async onSessionEnd(ctx) {
- if (!this.enabled) return;
- await this.postJson("/agentmemory/session/end", { sessionId: ctx.sessionId });
- }
-}
+ api.on("agent_end", async (event) => {
+ if (!cfg.enabled || !event?.success || !Array.isArray(event.messages)) return;
+ const userText = latestUserText(event.messages);
+ const assistantText = lastAssistantText(event.messages);
+ if (!userText || !assistantText) return;
+ const sessionId =
+ event.sessionId ||
+ event.sessionKey ||
+ event.runId ||
+ `openclaw-${Date.now()}`;
+ await client.postJson("/agentmemory/observe", {
+ hookType: "post_tool_use",
+ sessionId,
+ timestamp: new Date().toISOString(),
+ data: {
+ tool_name: "conversation",
+ tool_input: userText.slice(0, 1000),
+ tool_output: assistantText.slice(0, 4000),
+ },
+ });
+ });
+ },
+};
-export default AgentmemoryPlugin;
+export default plugin;
diff --git a/integrations/pi/README.md b/integrations/pi/README.md
new file mode 100644
index 00000000..cdc613cc
--- /dev/null
+++ b/integrations/pi/README.md
@@ -0,0 +1,76 @@
+<p align="center">
+ <img src="../../assets/banner.png" alt="agentmemory" width="640" />
+</p>
+
+<h1 align="center">
+ &nbsp;agentmemory for pi
+</h1>
+
+<p align="center">
+ <strong>Your pi sessions remember everything. No more re-explaining.</strong><br/>
+ <sub>Persistent cross-session memory via <a href="https://github.com/rohitg00/agentmemory">agentmemory</a> — shared with Claude Code, Codex CLI, Gemini CLI, Hermes, OpenClaw, and more.</sub>
+</p>
+
+---
+
+## Quick setup
+
+Start the agentmemory server in a separate terminal:
+
+```bash
+npx @agentmemory/agentmemory
+```
+
+Copy this folder into pi's global extensions directory:
+
+```bash
+mkdir -p ~/.pi/agent/extensions/agentmemory
+cp integrations/pi/index.ts ~/.pi/agent/extensions/agentmemory/index.ts
+```
+
+Then enable it in `~/.pi/agent/settings.json` if you prefer explicit loading:
+
+```json
+{
+ "extensions": ["~/.pi/agent/extensions/agentmemory"]
+}
+```
+
+If you place it under `~/.pi/agent/extensions/agentmemory/`, pi will also auto-discover it and `/reload` can hot-reload it.
+
+## What it adds
+
+- `memory_health` — confirm the shared memory server is reachable
+- `memory_search` — search prior decisions, bugs, workflows, and preferences
+- `memory_save` — write durable facts back to long-term memory
+- `/agentmemory-status` — check health from inside pi
+- `before_agent_start` recall — injects relevant memories into the prompt
+- `agent_end` capture — saves completed conversation turns back to agentmemory
+
+## Environment variables
+
+| Variable | Default | Description |
+|---|---|---|
+| `AGENTMEMORY_URL` | `http://localhost:3111` | agentmemory server URL |
+| `AGENTMEMORY_SECRET` | (none) | Bearer token for protected instances |
+
+## Smoke test
+
+Run pi and ask it to use the `memory_health` tool, or call the command directly:
+
+```text
+/agentmemory-status
+```
+
+You should see `agentmemory healthy` and a footer status like `🧠 agentmemory`.
+
+## Notes
+
+- This extension uses pi's extension API, not MCP, so it can hook directly into the agent lifecycle.
+- One local agentmemory server can be shared across pi, pi2, Hermes, OpenClaw, Claude Code, Codex CLI, and Gemini CLI.
+
+## See also
+
+- [agentmemory main README](../../README.md)
+- [Hermes integration](../hermes/README.md)
+- [OpenClaw integration](../openclaw/README.md)
diff --git a/integrations/pi/index.ts b/integrations/pi/index.ts
new file mode 100644
index 00000000..f2bafc0a
--- /dev/null
+++ b/integrations/pi/index.ts
@@ -0,0 +1,265 @@
+import type { ExtensionAPI } from "@mariozechner/pi-coding-agent";
+import { Type } from "typebox";
+import path from "node:path";
+import crypto from "node:crypto";
+
+type TextBlock = { type?: string; text?: string };
+type AssistantMessage = { role?: string; content?: unknown };
+type SmartSearchResult = {
+ title?: string;
+ narrative?: string;
+ type?: string;
+ combinedScore?: number;
+ score?: number;
+ observation?: {
+ title?: string;
+ narrative?: string;
+ type?: string;
+ };
+};
+
+type HealthResponse = {
+ status?: string;
+ service?: string;
+ version?: string;
+ health?: {
+ status?: string;
+ notes?: string[];
+ };
+};
+
+const DEFAULT_URL = process.env.AGENTMEMORY_URL || "http://localhost:3111";
+const TOOL_GUIDANCE = [
+ "agentmemory is available for cross-session memory.",
+ "Use memory_search to recall prior decisions, preferences, bugs, and workflows.",
+ "Use memory_save when you discover durable facts worth remembering beyond this session.",
+].join(" ");
+
+function normalizeBaseUrl(url: string): string {
+ return url.replace(/\/+$/, "");
+}
+
+function getText(content: unknown): string {
+ if (typeof content === "string") return content;
+ if (!Array.isArray(content)) return "";
+ return content
+ .flatMap((part) => {
+ if (!part || typeof part !== "object") return [] as string[];
+ const block = part as TextBlock;
+ if (block.type === "text" && typeof block.text === "string") return [block.text];
+ return [] as string[];
+ })
+ .join("\n")
+ .trim();
+}
+
+function getLastAssistantText(messages: unknown[]): string {
+ for (const msg of [...messages].reverse()) {
+ if (!msg || typeof msg !== "object") continue;
+ const assistant = msg as AssistantMessage;
+ if (assistant.role !== "assistant") continue;
+ const text = getText(assistant.content);
+ if (text) return text;
+ }
+ return "";
+}
+
+function formatSearchResults(results: SmartSearchResult[]): string {
+ if (!results.length) return "No relevant memories found.";
+ return results
+ .slice(0, 5)
+ .map((result, index) => {
+ const obs = result.observation ?? result;
+ const title = obs.title?.trim() || `Memory ${index + 1}`;
+ const narrative = obs.narrative?.trim() || "";
+ const type = obs.type?.trim() || "memory";
+ const score = result.combinedScore ?? result.score;
+ const scoreText = typeof score === "number" ? ` [score=${score.toFixed(3)}]` : "";
+ return `- ${title} (${type})${scoreText}${narrative ? `: ${narrative}` : ""}`;
+ })
+ .join("\n");
+}
+
+async function callAgentMemory<T>(
+ pathname: string,
+ options?: {
+ method?: "GET" | "POST";
+ body?: unknown;
+ baseUrl?: string;
+ },
+): Promise<T | null> {
+ const baseUrl = normalizeBaseUrl(options?.baseUrl || process.env.AGENTMEMORY_URL || DEFAULT_URL);
+ const method = options?.method || "POST";
+ const url = `${baseUrl}/agentmemory/${pathname.replace(/^\/+/, "")}`;
+ const headers: Record<string, string> = {};
+ if (options?.body !== undefined) headers["Content-Type"] = "application/json";
+ if (process.env.AGENTMEMORY_SECRET) headers.Authorization = `Bearer ${process.env.AGENTMEMORY_SECRET}`;
+
+ try {
+ const response = await fetch(url, {
+ method,
+ headers,
+ body: options?.body !== undefined ? JSON.stringify(options.body) : undefined,
+ });
+ if (!response.ok) return null;
+ return (await response.json()) as T;
+ } catch {
+ return null;
+ }
+}
+
+export default function agentmemoryExtension(pi: ExtensionAPI) {
+ let sessionId = `ephemeral-${crypto.randomUUID().slice(0, 8)}`;
+ let currentProject = process.cwd();
+ let lastPrompt = "";
+ let lastHealthOk = false;
+
+ async function getHealth() {
+ return await callAgentMemory<HealthResponse>("health", { method: "GET" });
+ }
+
+ async function refreshStatus(ctx: { ui: { setStatus: (key: string, text: string) => void } }) {
+ const health = await getHealth();
+ lastHealthOk = !!health && (health.status === "healthy" || health.health?.status === "healthy");
+ ctx.ui.setStatus("agentmemory", lastHealthOk ? "🧠 agentmemory" : "🧠 agentmemory off");
+ }
+
+ pi.registerCommand("agentmemory-status", {
+ description: "Check local agentmemory server health",
+ handler: async (_args, ctx) => {
+ const health = await getHealth();
+ if (!health) {
+ ctx.ui.notify("agentmemory is unreachable at http://localhost:3111", "warning");
+ return;
+ }
+ ctx.ui.notify(
+ `agentmemory ${health.status || health.health?.status || "unknown"}${health.version ? ` v${health.version}` : ""}`,
+ "info",
+ );
+ },
+ });
+
+ pi.registerTool({
+ name: "memory_health",
+ label: "Memory Health",
+ description: "Check whether the local agentmemory server is reachable and healthy",
+ parameters: Type.Object({}),
+ async execute() {
+ const health = await getHealth();
+ if (!health) {
+ return {
+ content: [{ type: "text", text: "agentmemory is unreachable at http://localhost:3111" }],
+ details: { ok: false },
+ };
+ }
+ return {
+ content: [
+ {
+ type: "text",
+ text: `agentmemory status: ${health.status || health.health?.status || "unknown"}${health.version ? ` (v${health.version})` : ""}`,
+ },
+ ],
+ details: health,
+ };
+ },
+ });
+
+ pi.registerTool({
+ name: "memory_search",
+ label: "Memory Search",
+ description: "Search agentmemory for cross-session project memory, prior decisions, bugs, and user preferences",
+ parameters: Type.Object({
+ query: Type.String({ description: "What to search for in memory" }),
+ limit: Type.Optional(Type.Integer({ minimum: 1, maximum: 10, default: 5, description: "Maximum results" })),
+ }),
+ async execute(_toolCallId, params) {
+ const result = await callAgentMemory<{ results?: SmartSearchResult[] }>("smart-search", {
+ body: { query: params.query, limit: params.limit ?? 5 },
+ });
+ const results = result?.results || [];
+ return {
+ content: [{ type: "text", text: formatSearchResults(results) }],
+ details: { query: params.query, results },
+ };
+ },
+ });
+
+ pi.registerTool({
+ name: "memory_save",
+ label: "Memory Save",
+ description: "Save a durable fact, convention, workflow, preference, or bug fix into agentmemory",
+ parameters: Type.Object({
+ content: Type.String({ description: "What should be remembered" }),
+ type: Type.Optional(
+ Type.String({
+ description: "Memory type",
+ default: "fact",
+ }),
+ ),
+ }),
+ async execute(_toolCallId, params) {
+ const result = await callAgentMemory<Record<string, unknown>>("remember", {
+ body: { content: params.content, type: params.type || "fact" },
+ });
+ if (!result) {
+ return {
+ content: [{ type: "text", text: "Failed to save memory to agentmemory." }],
+ details: { ok: false },
+ };
+ }
+ return {
+ content: [{ type: "text", text: `Saved memory (${params.type || "fact"}): ${params.content}` }],
+ details: result,
+ };
+ },
+ });
+
+ pi.on("session_start", async (_event, ctx) => {
+ const sessionFile = ctx.sessionManager.getSessionFile();
+ sessionId = sessionFile ? path.basename(sessionFile).replace(/\.[^.]+$/, "") : `ephemeral-${crypto.randomUUID().slice(0, 8)}`;
+ currentProject = process.cwd();
+ await refreshStatus(ctx);
+ });
+
+ pi.on("before_agent_start", async (event, ctx) => {
+ currentProject = event.systemPromptOptions.cwd || process.cwd();
+ lastPrompt = event.prompt?.trim() || "";
+ if (!lastPrompt) return;
+
+ const result = await callAgentMemory<{ results?: SmartSearchResult[] }>("smart-search", {
+ body: { query: lastPrompt, limit: 5 },
+ });
+ const results = result?.results || [];
+ const recallBlock = results.length
+ ? [
+ "Relevant long-term memory from agentmemory:",
+ formatSearchResults(results),
+ ].join("\n")
+ : "";
+
+ await refreshStatus(ctx);
+ return {
+ systemPrompt: [event.systemPrompt, TOOL_GUIDANCE, recallBlock].filter(Boolean).join("\n\n"),
+ };
+ });
+
+ pi.on("agent_end", async (event) => {
+ if (!lastHealthOk || !lastPrompt) return;
+ const assistantText = getLastAssistantText(event.messages as unknown[]);
+ if (!assistantText) return;
+ void callAgentMemory("observe", {
+ body: {
+ hookType: "post_tool_use",
+ sessionId,
+ project: currentProject,
+ cwd: currentProject,
+ timestamp: new Date().toISOString(),
+ data: {
+ tool_name: "conversation",
+ input: lastPrompt.slice(0, 500),
+ output: assistantText.slice(0, 4000),
+ },
+ },
+ });
+ });
+}
diff --git a/integrations/pi/package.json b/integrations/pi/package.json
new file mode 100644
index 00000000..eec302de
--- /dev/null
+++ b/integrations/pi/package.json
@@ -0,0 +1,5 @@
+{
+ "name": "agentmemory-pi-extension",
+ "private": true,
+ "type": "module"
+}