feat: add @mem0/pi-agent-plugin for Pi Agent memory (#5459)

This commit is contained in:
Kartik
2026-06-10 01:04:09 +05:30
committed by GitHub
parent 9b0705c345
commit 2274b5acad
42 changed files with 8364 additions and 2 deletions
+4 -2
View File
@@ -143,7 +143,8 @@
"icon": "robot",
"pages": [
"integrations/openclaw",
"integrations/hermes"
"integrations/hermes",
"integrations/pi-agent"
]
}
]
@@ -464,7 +465,8 @@
"icon": "robot",
"pages": [
"integrations/openclaw",
"integrations/hermes"
"integrations/hermes",
"integrations/pi-agent"
]
}
]
+181
View File
@@ -0,0 +1,181 @@
---
title: Pi Agent
description: "Add persistent memory to Pi Agent with the Mem0 plugin semantic search, auto-capture, and dream consolidation."
---
Add persistent memory to [**Pi Agent**](https://pi.dev) with `@mem0/pi-agent-plugin`. Your agent forgets everything between sessions — this plugin fixes that by automatically capturing knowledge from conversations, storing it in Mem0's cloud memory layer, and retrieving relevant context before every response.
## Overview
The plugin provides:
1. **Auto-capture** — Extracts durable facts from both user and assistant messages automatically
2. **Semantic recall** — Retrieves relevant memories via the `mem0_memory` tool before each response
3. **Dream consolidation** — Periodic maintenance: merges duplicates, resolves contradictions, prunes stale entries
4. **Monorepo-aware scoping** — Uses git root for project detection, consistent across subdirectories
5. **Confirmation dialogs** — Destructive commands ask before acting via Pi's built-in UI
6. **8 skills + 8 commands** — Essential memory management from slash commands and agent-guided workflows
## Prerequisites
1. A Mem0 Platform account and API key:
- <a href="https://app.mem0.ai?utm_source=oss&utm_medium=integration-pi-agent" rel="nofollow">Sign up at app.mem0.ai</a>
- <a href="https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=integration-pi-agent" rel="nofollow">Get your API key</a> (starts with `m0-`)
2. Pi Agent installed ([pi.dev](https://pi.dev))
3. Your API key added to your shell profile:
<CodeGroup>
```bash zsh
echo 'export MEM0_API_KEY="m0-your-api-key"' >> ~/.zshrc
source ~/.zshrc
```
```bash bash
echo 'export MEM0_API_KEY="m0-your-api-key"' >> ~/.bashrc
source ~/.bashrc
```
</CodeGroup>
## Installation
```bash
pi install npm:@mem0/pi-agent-plugin
```
That's it. The extension loads automatically on every Pi session. No config files needed — `MEM0_API_KEY` from your environment is picked up automatically.
<Info>
Start a new Pi session and run `/mem0-status` to verify the connection. You should see your user ID, detected project, and memory count.
</Info>
### Optional Configuration
For advanced settings, create `~/.pi/agent/mem0-config.json`:
```json
{
"apiKey": "m0-your-key-here",
"userId": "your-username",
"autoCapture": true,
"defaultScope": "project",
"dream": {
"enabled": true,
"auto": true,
"minHours": 24,
"minSessions": 5,
"minMemories": 20
}
}
```
| Key | Type | Default | Description |
|-----|------|---------|-------------|
| `apiKey` | `string` | `$MEM0_API_KEY` | Mem0 API key. Environment variable takes precedence. |
| `userId` | `string` | `$MEM0_USER_ID` or `"default"` | User identity for memory scoping |
| `autoCapture` | `boolean` | `true` | Store facts from conversations automatically |
| `defaultScope` | `string` | `"project"` | Default memory scope: `project`, `session`, or `global` |
| `dream.enabled` | `boolean` | `true` | Enable dream consolidation |
| `dream.auto` | `boolean` | `true` | Auto-trigger dreams when thresholds are met |
| `dream.minHours` | `number` | `24` | Minimum hours between auto-dreams |
| `dream.minSessions` | `number` | `5` | Minimum sessions before first auto-dream |
| `dream.minMemories` | `number` | `20` | Minimum memories before auto-dream triggers |
## What's Included
| Component | Description |
|-----------|-------------|
| `mem0_memory` tool | Agent-callable tool for search, add, get_all, delete, delete_all |
| 8 slash commands | Essential memory management from the command line |
| 8 skills | Guide the agent on how to use each capability |
| Auto-capture | Extracts and stores facts on every `agent_end` event |
| System prompt | Appends memory policy to every agent turn |
| Dream consolidation | Automated memory maintenance with session/time/count gates |
## Agent Tool
The `mem0_memory` tool is registered with Pi and callable by the agent during conversations:
| Action | Required Params | Description |
|--------|----------------|-------------|
| `search` | `query` | Semantic search across memories |
| `add` | `content` | Store a new memory |
| `get_all` | — | List all memories in scope |
| `delete` | `memory_id` | Delete a specific memory |
| `delete_all` | — | Delete all memories in scope |
All actions accept an optional `scope` parameter: `project` (default), `session`, or `global`.
Tool output is truncated to 200 lines / 50KB to prevent context overflow.
## Commands
| Command | Description |
|---------|-------------|
| `/mem0-remember <text>` | Store a memory verbatim (no inference) |
| `/mem0-forget <query>` | Search and delete memories (with confirmation dialog) |
| `/mem0-search <query>` | Semantic search across memories |
| `/mem0-tour [scope]` | Browse all memories grouped by category |
| `/mem0-dream` | Consolidate — merge duplicates, prune stale, resolve contradictions |
| `/mem0-pin <query>` | Pin a memory to protect from dream pruning (preserves memory ID) |
| `/mem0-scope <scope>` | Change default scope for this session (project, session, global) |
| `/mem0-status` | Connection health, identity, and memory count |
## Memory Scopes
Memories are scoped using Mem0's `user_id`, `app_id`, and `run_id` parameters:
| Scope | Filters | Use Case |
|-------|---------|----------|
| `project` | user_id + app_id (git root) | **Default.** Project-specific knowledge — decisions, architecture, config |
| `session` | user_id + app_id + run_id | Ephemeral context for the current session only |
| `global` | user_id only | All memories across all your projects |
The `app_id` is auto-detected from the git repository root (`git rev-parse --show-toplevel`), so all subdirectories within a monorepo share the same memory pool. Falls back to the working directory name for non-git directories. The `run_id` is derived from Pi's session file path.
## Dream Consolidation
### Confirmation Dialogs
Destructive and mutating commands use Pi's built-in `ctx.ui.confirm()` dialog before acting:
- `/mem0-forget` asks "Delete this memory?" before deleting a single match
- `/mem0-pin` asks "Pin this memory?" before modifying it
- Cancelling either operation is always safe — no changes are made
### Pin
`/mem0-pin` uses Mem0's `update()` API to prepend `[PINNED]` to the memory text. This preserves the original memory ID — no add+delete cycle that would lose history or change the UUID.
### Dream Consolidation
The plugin includes automated memory maintenance ("dream") that merges duplicates, resolves contradictions, and prunes stale entries. When enabled, dreams auto-trigger after enough sessions, time, and memories accumulate (configurable via `dream.*` settings). Run `/mem0-dream` to trigger consolidation manually at any time. Pinned memories (via `/mem0-pin`) are protected from pruning.
## Example Workflow
```text
# Session 1
You: I prefer dark mode and concise answers.
# Mem0 auto-captures preferences
# Session 2 (days later)
You: What do you know about my preferences?
# Pi retrieves stored memories — no re-explaining needed
```
## Troubleshooting
- **"No API key found"** — Verify `MEM0_API_KEY` is set: `echo $MEM0_API_KEY`. If empty, add it to your shell profile (see Prerequisites)
- **Extension not loading** — Check Pi startup output for errors. Run `pi -e ./src/entry.ts` from the plugin directory for verbose output
- **Memories not capturing** — Verify `autoCapture` is `true` (default). Check `/mem0-status` for connection health
- **Wrong project detected** — The plugin uses the git repository root as `app_id`. If not in a git repo, it falls back to the working directory name. Run `/mem0-status` to see the detected project
- **Dream not triggering** — All three gates must pass (time, sessions, memories). Use `/mem0-dream` to force it manually
<CardGroup cols={2}>
<Card title="Claude Code Integration" icon="terminal" href="/integrations/claude-code">
Add Mem0 memory to Claude Code
</Card>
<Card title="OpenClaw Integration" icon="plug" href="/integrations/openclaw">
Add Mem0 memory to OpenClaw agents
</Card>
</CardGroup>
+1
View File
@@ -259,6 +259,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or Platform `output_f
- [Camel AI](https://docs.mem0.ai/integrations/camel-ai) [Both]: Use when the user is on Camel AI.
- [ChatDev](https://docs.mem0.ai/integrations/chatdev) [Both]: Use when the user is on ChatDev.
- [Hermes](https://docs.mem0.ai/integrations/hermes) [Both]: Use when the user is on Hermes.
- [Pi Agent](https://docs.mem0.ai/integrations/pi-agent) [Platform]: Use when adding persistent memory to Pi Agent with the Mem0 plugin.
- [OpenAI Agents SDK](https://docs.mem0.ai/integrations/openai-agents-sdk) [Both]: Use when the user is on the OpenAI Agents SDK.
- [Google AI ADK](https://docs.mem0.ai/integrations/google-ai-adk) [Both]: Use when the user is on Google's Agent Development Kit.
- [Mastra](https://docs.mem0.ai/integrations/mastra) [Both]: Use when the user is on Mastra (TypeScript).
+47
View File
@@ -0,0 +1,47 @@
# Changelog
## 0.1.0 (2026-06-09)
Initial release of `@mem0/pi-agent-plugin` — persistent semantic memory for Pi Agent.
### Features
- **Extension entry point** — registers `mem0_memory` tool, 8 slash commands, and auto-capture hooks
- **Agent tool** (`mem0_memory`) — search, add, get_all, delete, delete_all with scoped filters
- **Auto-capture** — extracts and stores memories from both user and assistant messages on `agent_end`
- **Dream consolidation** — automated memory maintenance: merge duplicates, resolve contradictions, prune stale entries. Gated by session count, time elapsed, and memory count thresholds
- **System prompt injection** — appends `MEMORY_POLICY` to every agent turn via `before_agent_start`
- **Monorepo-aware project scoping** — uses `git rev-parse --show-toplevel` for consistent app_id across subdirectories
- **3 memory scopes** — project (default), session, global
- **10 memory categories** — identity, preferences, goals, projects, decisions, technical, relationships, routines, lessons, work
- **8 skills** — context-loader, remember, search, forget, dream, tour, pin, status
- **Confirmation dialogs** — `/mem0-forget` and `/mem0-pin` ask for confirmation before destructive or mutating actions via `ctx.ui.confirm()`
- **Pin preserves memory ID** — `/mem0-pin` uses `mem0.update()` instead of add+delete, keeping the original UUID
- **Full memory IDs** — all displayed memory references show the complete UUID, not truncated short IDs
- **Dream gate optimization** — `dreamChecked` flag prevents repeated `getAll` API calls when the memory gate fails
- **Output truncation** — tool results capped at 200 lines / 50KB per Pi docs
- **Signal cancellation** — all tool actions respect `AbortSignal`
- **Session shutdown cleanup** — releases dream lock on `session_shutdown`
- **PostHog telemetry** — batched event queue with PII-safe error payloads
### Commands
| Command | Description |
|---------|-------------|
| `/mem0-remember` | Store a memory verbatim (no inference) |
| `/mem0-forget` | Search and delete memories (with confirmation) |
| `/mem0-search` | Semantic search across memories |
| `/mem0-tour` | Browse all memories by category |
| `/mem0-dream` | Trigger memory consolidation |
| `/mem0-pin` | Pin a memory to protect from pruning (preserves ID) |
| `/mem0-scope` | Change default scope for this session |
| `/mem0-status` | Connection health and diagnostics |
### Hooks
| Hook | Purpose |
|------|---------|
| `session_start` | Detect project (git root), resolve session ID, increment dream counter |
| `before_agent_start` | Inject memory policy into system prompt, auto-trigger dream if gates pass |
| `agent_end` | Auto-capture conversation memories, check dream completion |
| `session_shutdown` | Release dream lock, flush telemetry |
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [2026] [Taranjeet Singh]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+144
View File
@@ -0,0 +1,144 @@
# @mem0/pi-agent-plugin
Persistent semantic memory for [Pi Agent](https://pi.dev), powered by [Mem0](https://mem0.ai).
This extension gives Pi Agent long-term memory that persists across sessions, projects, and devices. Memories are automatically captured from conversations and can be searched, managed, and consolidated through slash commands and an agent-accessible tool.
## Features
- **Automatic memory capture** — learns from every conversation (both user and assistant messages)
- **Semantic search** — find memories by meaning, not just keywords
- **Scoped memory** — project, session, or global scope
- **Monorepo-aware** — uses git root for project detection, consistent app_id across subdirectories
- **Dream consolidation** — merges duplicates, resolves contradictions, prunes stale entries
- **Confirmation dialogs** — destructive commands ask before acting
- **8 slash commands** — essential memory management from the command line
- **Agent tool** — `mem0_memory` tool lets the agent search and store memories autonomously
## Setup
### 1. Get an API key
Sign up at [app.mem0.ai](https://app.mem0.ai/dashboard/api-keys) and copy your API key.
### 2. Install
```bash
pi install npm:@mem0/pi-agent-plugin
```
### 3. Configure
Set the API key as an environment variable:
```bash
export MEM0_API_KEY="m0-your-key-here"
```
Or create a config file at `~/.pi/agent/mem0-config.json`:
```json
{
"apiKey": "m0-your-key-here",
"userId": "your-username",
"autoCapture": true,
"defaultScope": "project",
"dream": {
"enabled": true,
"auto": true,
"minHours": 24,
"minSessions": 5,
"minMemories": 20
}
}
```
Environment variables (`MEM0_API_KEY`, `MEM0_USER_ID`) override the config file.
## Commands
| Command | Description |
|---------|-------------|
| `/mem0-remember <text>` | Store a memory verbatim (no inference) |
| `/mem0-forget <query>` | Search and delete memories (with confirmation) |
| `/mem0-search <query>` | Semantic search across memories |
| `/mem0-tour [scope]` | Browse all memories grouped by category |
| `/mem0-dream` | Consolidate — merge duplicates, prune stale, resolve contradictions |
| `/mem0-pin <query>` | Pin a memory to protect from dream pruning (preserves ID) |
| `/mem0-scope <scope>` | Change default scope for this session |
| `/mem0-status` | Connection health, identity, and memory count |
## Skills
The plugin includes 8 skills that guide the agent on how to use each capability:
| Skill | Purpose |
|-------|---------|
| `context-loader` | Pre-fetch relevant memories at session start |
| `remember` | Store facts with category classification |
| `search` | Quick semantic search with compact results |
| `forget` | Delete memories with confirmation |
| `dream` | Memory consolidation workflow |
| `tour` | Full memory walkthrough by category |
| `pin` | Protect critical memories from pruning |
| `status` | Health check and diagnostics |
## Memory Scopes
| Scope | Filters | Use case |
|-------|---------|----------|
| `project` | user + app_id (git root) | Default. Project-specific knowledge |
| `session` | user + app_id + run_id | Ephemeral, session-only context |
| `global` | user only | All memories across all your projects |
Project scoping uses `git rev-parse --show-toplevel` to detect the repository root, so all subdirectories within a monorepo share the same memory pool.
## Memory Categories
Memories are automatically classified into 10 general-purpose categories:
| Category | Description |
|----------|-------------|
| `identity` | Personal details, background, self-descriptions |
| `preferences` | Likes, dislikes, habits, preferred approaches |
| `goals` | Objectives, aspirations, targets |
| `projects` | Ongoing work, initiatives, areas of focus |
| `decisions` | Choices made, rationale, trade-offs |
| `technical` | Technical knowledge, tools, configurations |
| `relationships` | People, teams, organizations |
| `routines` | Recurring patterns, workflows, schedules |
| `lessons` | Insights learned, mistakes to avoid |
| `work` | Professional context, role, responsibilities |
## Architecture
```
pi-agent-plugin/
├── src/
│ ├── entry.ts # Extension entry point
│ ├── index.ts # Barrel exports
│ ├── commands.ts # 8 slash commands
│ ├── prompt.ts # System prompt injection (MEMORY_POLICY)
│ ├── types.ts # Shared interfaces and categories
│ ├── telemetry.ts # PostHog telemetry (batched, PII-safe)
│ ├── config/ # Config loading (~/.pi/agent/mem0-config.json)
│ ├── memory/ # Tool registration, scoping (git root), formatting
│ ├── capture/ # Auto-capture from conversations (user + assistant)
│ └── dream/ # Consolidation state, gating, locking, prompts
├── skills/ # 8 SKILL.md files for Pi Agent
├── tests/ # Vitest unit tests
└── dist/ # Built output (ESM + DTS)
```
## Development
```bash
pnpm install # Install dependencies
pnpm run typecheck # Type check
pnpm run test # Run tests
pnpm run build # Build (ESM + declarations)
```
## License
[Apache-2.0](LICENSE)
+68
View File
@@ -0,0 +1,68 @@
{
"name": "@mem0/pi-agent-plugin",
"version": "0.1.0",
"type": "module",
"description": "Mem0 memory extension for Pi Agent persistent, scoped, semantic memory across sessions and projects",
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "https://github.com/mem0ai/mem0/pi-agent-plugin",
"directory": "pi-agent-plugin"
},
"keywords": [
"pi-package",
"pi-extension",
"skills",
"memory",
"mem0",
"semantic-memory",
"persistent-memory",
"agent-memory"
],
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"publishConfig": {
"access": "public"
},
"files": [
"dist",
"src",
"skills",
"CHANGELOG.md",
"README.md",
"LICENSE"
],
"pi": {
"extensions": ["./src/entry.ts"],
"skills": ["./skills"]
},
"scripts": {
"build": "tsup",
"test": "vitest run",
"test:watch": "vitest",
"typecheck": "tsc --noEmit"
},
"peerDependencies": {
"@earendil-works/pi-coding-agent": "*",
"@earendil-works/pi-ai": "*",
"typebox": "*"
},
"devDependencies": {
"@earendil-works/pi-ai": "^0.79.0",
"@earendil-works/pi-coding-agent": "^0.79.0",
"@types/node": "^25.9.2",
"tsup": "^8.5.0",
"typebox": "^1.2.3",
"typescript": "^6.0.3",
"vitest": "^4.1.7"
},
"dependencies": {
"mem0ai": "^3.0.6"
}
}
+4923
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,47 @@
---
name: context-loader
description: Searches and injects relevant memories into context before starting work on a task or topic. Use when beginning a new task, switching context, or when past decisions, preferences, or knowledge need to be loaded.
---
# Context Loader
Pre-fetches relevant memories to prime context before working on a task or topic.
## When to use
- Session start (auto-triggered by the extension's `before_agent_start` event)
- User starts work on a specific topic or area
- User says "what do we know about X" or "context for X"
## Steps
1. **Extract topics** from current message/task. Identify: subject areas, people mentioned, project names, goal references.
2. **Run 2-4 parallel searches** using `mem0_memory` tool with `action="search"` and different query angles:
| Query angle | Purpose |
|---|---|
| Topic/subject name | Relevant decisions and preferences |
| People mentioned | Relationship context |
| Project/goal references | Progress and background |
| Broad context | Catch-all for anything relevant |
3. **Deduplicate** results by memory ID across all search responses.
4. **Output compact context block** (max 10 memories):
```
context-loader: loaded <N> memories for "<task summary>"
- [decisions] <content> [mem0:<short_id>]
- [preferences] <content> [mem0:<short_id>]
- [lessons] <content> [mem0:<short_id>]
```
5. If **zero results**: output nothing. Don't announce empty context.
## Constraints
- **Read-only** — never modify or delete memories
- **Max 10 memories** returned (most relevant only)
- **Silent on empty** — only surfaces findings if relevant context exists
- Skip memories already visible in current session context
+125
View File
@@ -0,0 +1,125 @@
---
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.
---
# Dream — Memory Consolidation
This skill performs a memory consolidation pass: it fetches all memories, identifies near-duplicates, flags contradictions, and prunes stale entries. All proposed changes are shown as a diff for user approval before anything is modified.
**IMPORTANT: Execute steps strictly in order (1 -> 2 -> 3 -> 4 -> 5). Each step depends on the previous one. Do NOT run steps in parallel or skip ahead.**
## Step 1: Fetch ALL Memories
Use `mem0_memory` tool with `action="get_all"` to retrieve every memory.
If zero memories are found, print:
```
No memories found. Nothing to consolidate.
```
...and stop.
## Step 2: Analyze — Find Issues
Work entirely in-memory; do not modify anything yet.
Group memories by category. For each group, identify the following:
### 2a. Near-duplicate pairs (merge candidates)
Two memories are near-duplicates when they express the same fact but phrased differently (e.g., "Prefers morning meetings" and "Likes scheduling meetings early").
Heuristics — two memories are near-duplicates if **all** of these hold:
- If >60% of significant nouns/keywords overlap, treat as near-duplicate.
- Same category.
- Neither memory is pinned (content does not start with `[PINNED]`).
For each qualifying pair, draft a merged version that is more complete than either original.
### 2b. Contradictions
Two memories contradict when they assert opposing facts about the same topic (e.g., "Prefers cats" vs. "Allergic to cats, prefers dogs").
Identify the likely winner: the more recent memory wins. Store both IDs and their content for user review.
### 2c. Prune candidates
A memory is a prune candidate when **any** of the following is true:
1. It is older than 180 days AND has not been accessed recently.
2. Its content is extremely vague (fewer than 5 meaningful words).
**Always skip memories where content starts with `[PINNED]`**, regardless of age.
## Step 3: Print Diff Report
Print a structured diff before making any changes:
```
## dream — consolidation report
Merges (<N>):
[mem0:<id1>] + [mem0:<id2>] -> "<merged content, 100 chars>"
Conflicts (<N>):
[mem0:<idA>] vs [mem0:<idB>] — "<topic>" [A/B/skip]
Prune (<N>):
[mem0:<id>] — <category>, <age>d old
Proposed: <N> merges, <N> prunes, <N> conflicts. Apply? [Y/n]
```
If there are zero total proposals, print:
```
Dream complete. No duplicate, contradictory, or stale memories found.
```
...and stop.
## Step 4: Wait for User Input and Apply
### 4a. Contradictions
For each conflict pair, wait for the user to choose A, B, or skip.
### 4b. Final confirmation
After all conflict resolutions are collected, prompt: `Apply? [Y/n]`
If the user declines, print `Cancelled. No changes made.` and stop.
If confirmed, apply all changes:
**Merges:** Delete both originals, add the merged version using `mem0_memory` with `action="add"`.
**Contradictions (resolved):** Delete the loser using `mem0_memory` with `action="delete"`.
**Prunes:** Delete each using `mem0_memory` with `action="delete"`.
## Step 5: Print Summary
```
Dream complete — merged: <N>, pruned: <N>, conflicts resolved: <N>, skipped: <N>
```
## Auto mode
When invoked with `--auto` (e.g., `/mem0-dream --auto`), run non-interactively:
- **Merges**: applied automatically.
- **Prunes**: applied automatically.
- **Contradictions**: skipped — they require human judgment.
Print a compact summary:
```
[mem0-dream --auto] merged=<N> pruned=<N> conflicts_skipped=<N>
```
## See also
- `/mem0-forget` — targeted deletion of specific memories
- `/mem0-status` — quick health check
+53
View File
@@ -0,0 +1,53 @@
---
name: forget
description: Deletes memories by search query or memory ID with confirmation before removal. Use when removing outdated information, incorrect memories, sensitive data, or cleaning up after experiments.
---
# Forget
Delete specific memories from Mem0.
## Execution
### Step 1: Parse input
The user provides either:
- A search query: `/mem0-forget travel plans`
- A memory ID: `/mem0-forget <memory_id>`
If no argument, ask: "What should I forget? Provide a search query or memory ID."
### Step 2: Find memories
**If memory ID provided** (looks like a UUID or hex string):
- Use `mem0_memory` tool with `action="search"` and the ID as query, or look it up directly.
- Show: `Found: "<memory content first 120 chars>" (created <date>)`
**If search query provided:**
- Use `mem0_memory` tool with `action="search"`, `query=<user's query>`.
- Show numbered list:
```
Found <N> memories matching "<query>":
1. <content, 120 chars> [<category>] [ID: <short_id>]
2. ...
```
### Step 3: Confirm
Ask: "Delete which memories? Enter numbers (e.g., 1,3,5), 'all', or 'cancel'."
For a single memory ID, ask: "Delete this memory? [y/N]"
**Never delete without confirmation.** This is destructive.
### Step 4: Delete
For each confirmed memory, use `mem0_memory` tool with `action="delete"` and the memory ID.
### Step 5: Report
```
Deleted <N> memories.
```
If any deletions failed, report which ones and why.
+48
View File
@@ -0,0 +1,48 @@
---
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 core preferences, important decisions, or immutable personal facts.
---
# Pin
Pin a memory to mark it as high-priority and protect from dream pruning.
## Execution
### Step 1: Find the memory
The user provides either a search query or memory ID.
**If memory ID:** Look it up directly.
**If search query:**
- Use `mem0_memory` tool with `action="search"`, `query=<query>`.
- Show numbered list with content previews.
- Ask: "Which memory to pin? Enter a number."
### Step 2: Pin it
Pinning works by prepending `[PINNED]` to the memory text. This marker tells the dream consolidation to skip it during pruning.
Use `mem0_memory` tool with `action="add"`, `content="[PINNED] <original memory text>"`.
Then delete the original using `mem0_memory` with `action="delete"` and the original memory ID.
**For new memories** (user wants to pin text that isn't stored yet):
- Use `mem0_memory` tool with `action="add"`, `content="[PINNED] <the user's text>"`.
### Step 3: Confirm
```
Pinned: "<memory content, first 80 chars>"
```
Append `...` only if content exceeds 80 characters.
### Unpin
If the user says "unpin":
1. Find the memory (search or by ID).
2. Create a new memory without the `[PINNED]` prefix.
3. Delete the pinned version.
4. Print: `Unpinned: "<content>..."`
+50
View File
@@ -0,0 +1,50 @@
---
name: remember
description: Stores a memory verbatim from user input with appropriate category classification. Use when the user says remember this, save this, store this, note that, or explicitly asks to record a preference, decision, goal, or lesson.
---
# Remember
Store a fact, preference, or learning directly into Mem0.
## Execution
### Step 1: Extract the content
The user provides the content as an argument: `/mem0-remember <text>`
If no text was provided, ask: "What should I remember?"
### Step 2: Classify the memory
Based on the content, pick the best category:
| Content signal | Category |
|---|---|
| "I prefer...", "I like...", "use X instead of Y" | `preferences` |
| "we decided...", "always use...", "never..." | `decisions` |
| "I learned...", "figured out...", "don't try..." | `lessons` |
| "my goal is...", "I want to...", "working toward..." | `goals` |
| "I work at...", "my role is...", "my team..." | `work` |
| "every day I...", "my workflow is..." | `routines` |
| "I'm working on...", "the project involves..." | `projects` |
| "John is...", "my manager...", "the team..." | `relationships` |
| "my name is...", "I'm from...", "I studied..." | `identity` |
| setup, tools, config, environment | `technical` |
| anything else | `lessons` |
### Step 3: Store
Use the `mem0_memory` tool with:
- `action="add"`
- `content="<the user's text>"`
The `/mem0-remember` command stores verbatim — no inference. This is already handled by the command.
### Step 4: Confirm
```
Remembered as <category>: "<content, first 80 chars>"
```
Append `...` only if content was truncated (longer than 80 chars).
+41
View File
@@ -0,0 +1,41 @@
---
name: search
description: Searches memories and displays compact one-liner results, or looks up a specific memory by ID. Use for quick memory lookups, checking if something was recorded, resolving [mem0:id] citations, or browsing memories without full category detail.
---
# Search / Peek
Quick semantic search with compact output. Lighter than `/mem0-tour`.
## Execution
### Step 1: Parse query
The user provides a search query: `/mem0-search favorite restaurants`
If no query provided, ask: "What should I search for?"
**Memory ID detection:** If the query matches a UUID pattern (`^[a-f0-9-]{20,}$`), treat it as a direct memory lookup instead of a search.
### Step 2: Search
Use `mem0_memory` tool with `action="search"`, `query=<user's query>`.
### Step 3: Display
Show compact results:
```
## mem0 search: "<query>" (<N> results)
1. [preferences] Prefers window seats on flights (2026-05-15) [mem0:a3f8b2c1]
2. [goals] Wants to visit Japan in 2027 (2026-05-10) [mem0:7e2d9f4a]
3. [identity] Lives in San Francisco (2026-05-08) [mem0:c4d5e6f7]
```
Format: `<number>. [<category>] <content, 80 chars> (<date>) [mem0:<short_id>]`
If no results:
```
No memories matching "<query>".
```
+89
View File
@@ -0,0 +1,89 @@
---
name: status
description: Diagnoses Mem0 connectivity, API key validity, and memory read/write functionality. Use when memory operations fail, searches return empty, or to verify the plugin is working correctly.
---
# Health Check / Status
Run a diagnostic check on the Mem0 plugin. Useful for troubleshooting.
## Execution
Run ALL checks, then display a single summary. Do not stop on the first failure.
### Check 1: API key
Verify the API key is configured. The plugin loads it from `MEM0_API_KEY` env var or `~/.pi/agent/mem0-config.json`.
- If not set: FAIL — "No API key configured"
- If set: PASS — show first 6 chars followed by `...`
### Check 2: Identity resolution
Report the resolved identity:
- `user_id`: from config, env, or system user
- `project_id`: auto-detected from current directory
- `session_id`: current session identifier
PASS if user_id and project_id are non-empty. WARN if any falls back to defaults.
### Check 3: Connectivity
Use `mem0_memory` tool with `action="search"`, `query="health check"`.
- If returns successfully (even empty): PASS
- If errors: FAIL — show the error message
### Check 4: Memory write capability
Use `mem0_memory` tool with `action="add"`, `content="Health check probe — safe to delete."`.
- If succeeds: PASS — then clean up by deleting the probe memory.
- If errors: FAIL — show the error.
### Display
```
## mem0 health
PASS API Key m0-dVe...
PASS Identity user=kartik, project=my-app, session=abc123
PASS Connectivity 142ms
PASS Write/Read write + delete OK
All checks passed.
```
If any check fails, add a `## Troubleshooting` section with specific fix steps.
## Extended mode: Memory Quality Analysis
When invoked with `--deep` (e.g., `/mem0-status --deep`), run the standard checks above **plus** a memory quality scan.
### Quality Check 1: Duplicates
Fetch all memories with `mem0_memory` `action="get_all"`. Compare pairs within the same category for high textual overlap (shared nouns > 60%). Report:
```
Potential duplicates: <N> pairs
[mem0:<id1>] ~ [mem0:<id2>] — both about "<shared topic>"
```
### Quality Check 2: Stale memories
Flag memories older than 180 days that haven't been accessed recently.
### Quality Check 3: Contradictions
Within each category, flag pairs that assert opposing facts.
### Quality summary
```
## Memory Quality
Duplicates: <N> · Stale: <N> · Contradictions: <N>
```
If all counts are 0: `Memory quality: clean.`
If any non-zero: append `Run /mem0-dream to fix.`
+88
View File
@@ -0,0 +1,88 @@
---
name: tour
description: Browses all stored memories grouped by category with full content display. Use when reviewing all memories, exploring stored knowledge, onboarding to a new session, or getting an overview of what the agent remembers.
---
# Memory Tour
Show the user what Mem0 has stored — a full walkthrough of all memories grouped by category.
## Cross-project mode
When invoked with `--all-projects` (e.g., `/mem0-tour --all-projects`), search across ALL projects:
1. Use `mem0_memory` tool with `action="get_all"`, `scope="global"` — no project filter.
2. Group results by project first, then by category within each project.
3. Display:
```
## <project_1> (<N> memories) <- current
**Goals** — <memory content>
...
## <project_2> (<N> memories)
...
<N> memories across <M> projects
```
4. Mark the current project with `<- current` in the heading.
If `--all-projects` is NOT present, use the standard single-project flow below.
## Search mode
When `/mem0-tour` receives a search query argument (e.g., `/mem0-tour cooking recipes`), run in **search mode** — compact one-liner results:
1. Use `mem0_memory` tool with `action="search"`, `query=<query>`.
2. Display compact results (same format as the search skill).
3. If no results: `No memories matching "<query>".`
If no query argument and no `--all-projects` flag, use the full tour flow below.
## Execution
### Step 1: Fetch ALL memories
Use `mem0_memory` tool with `action="get_all"`.
### Step 2: Group by category
Group memories using their `categories` field. Map to display names:
| Category | Display name |
|---|---|
| `identity` | Identity & Background |
| `preferences` | Preferences |
| `goals` | Goals & Aspirations |
| `projects` | Projects & Initiatives |
| `decisions` | Decisions |
| `technical` | Technical Knowledge |
| `relationships` | People & Relationships |
| `routines` | Routines & Workflows |
| `lessons` | Lessons Learned |
| `work` | Work & Professional |
| anything else | Other |
### Step 3: Display results
Sort groups by descending memory count. For each group:
```
## <display_name> (<count> memories)
- <full_memory_content> (<date>)
- ...
```
Show the **full memory text** for each entry — do NOT truncate. If a group has more than 10 entries, show top 10 by recency and note `... and <N> more`.
### Step 4: Print totals
```
<N> memories across <M> categories
```
### Step 5: Empty state
If zero memories found:
```
No memories stored yet. Start a conversation — Mem0 captures learnings automatically, or use /mem0-remember to store something manually.
```
+70
View File
@@ -0,0 +1,70 @@
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import type MemoryClient from "mem0ai";
import type { Mem0Config, ScopeContext } from "../types.ts";
import { DEFAULT_CUSTOM_CATEGORIES } from "../types.ts";
import { resolveAddParams } from "../memory/scoping.ts";
import { captureEvent } from "../telemetry.ts";
interface MessageLike {
role: string;
content?: unknown;
}
function extractText(content: unknown): string | null {
if (typeof content === "string") return content;
if (Array.isArray(content)) {
const texts = content
.filter((b: any) => b.type === "text" && typeof b.text === "string")
.map((b: any) => b.text);
return texts.length > 0 ? texts.join("\n") : null;
}
return null;
}
export function extractConversation(
messages: MessageLike[],
): Array<{ role: "user" | "assistant"; content: string }> {
const result: Array<{ role: "user" | "assistant"; content: string }> = [];
for (const msg of messages) {
if (msg.role !== "user" && msg.role !== "assistant") continue;
const text = extractText(msg.content);
if (!text) continue;
result.push({ role: msg.role as "user" | "assistant", content: text });
}
return result;
}
export function setupAutoCapture(
pi: ExtensionAPI,
mem0: MemoryClient,
config: Mem0Config,
getScopeCtx: () => ScopeContext,
telemetryCtx?: { apiKey?: string },
): void {
if (!config.autoCapture) return;
pi.on("agent_end", async (event) => {
const messages = event.messages ?? [];
const conversation = extractConversation(messages);
if (conversation.length === 0) return;
const scopeCtx = getScopeCtx();
const addParams = resolveAddParams("project", scopeCtx);
try {
await mem0.add(conversation, {
...addParams,
customCategories: DEFAULT_CUSTOM_CATEGORIES,
});
captureEvent("pi.capture.auto", { success: true, message_count: conversation.length }, telemetryCtx);
} catch (err: unknown) {
captureEvent("pi.capture.auto", {
success: false,
error_type: err instanceof Error ? err.name : "unknown",
}, telemetryCtx);
console.error("[mem0] auto-capture failed:", err);
}
});
}
+297
View File
@@ -0,0 +1,297 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { registerCommands } from "./commands.ts";
import type { Mem0Config, ScopeContext } from "./types.ts";
vi.mock("./telemetry.ts", () => ({
captureCommandEvent: vi.fn(),
}));
vi.mock("./dream/index.ts", () => ({
acquireDreamLock: vi.fn(() => true),
}));
vi.mock("./dream/prompt.ts", () => ({
DREAM_PROTOCOL: "dream protocol text",
}));
function makeMem0() {
return {
search: vi.fn(),
delete: vi.fn(),
add: vi.fn(),
get: vi.fn(),
getAll: vi.fn(),
update: vi.fn(),
} as any;
}
function makePi() {
const commands = new Map<string, { handler: (args: string, ctx: any) => Promise<void> }>();
return {
registerCommand: vi.fn((name: string, opts: any) => {
commands.set(name, opts);
}),
sendMessage: vi.fn(),
_commands: commands,
_invoke: (name: string, args: string, ctx: any) => commands.get(name)!.handler(args, ctx),
};
}
function makeCtx(confirmResult = true) {
return {
hasUI: true,
ui: {
notify: vi.fn(),
confirm: vi.fn(async () => confirmResult),
select: vi.fn(),
input: vi.fn(),
},
};
}
const defaultConfig: Mem0Config = {
apiKey: "test-key",
userId: "test-user",
autoCapture: false,
defaultScope: "project",
contextInjection: false,
dream: { enabled: false, auto: false, minHours: 24, minSessions: 5, minMemories: 20 },
};
const scopeCtx: ScopeContext = { userId: "test-user", appId: "test-app", runId: "test-run" };
describe("registerCommands", () => {
let pi: ReturnType<typeof makePi>;
let mem0: ReturnType<typeof makeMem0>;
beforeEach(() => {
pi = makePi();
mem0 = makeMem0();
registerCommands(pi as any, mem0, defaultConfig, () => scopeCtx);
});
it("registers all expected commands", () => {
const names = [...pi._commands.keys()];
expect(names).toContain("mem0-remember");
expect(names).toContain("mem0-forget");
expect(names).toContain("mem0-search");
expect(names).toContain("mem0-tour");
expect(names).toContain("mem0-dream");
expect(names).toContain("mem0-pin");
expect(names).toContain("mem0-scope");
expect(names).toContain("mem0-status");
});
describe("/mem0-forget", () => {
it("shows warning when no query provided", async () => {
const ctx = makeCtx();
await pi._invoke("mem0-forget", "", ctx);
expect(ctx.ui.notify).toHaveBeenCalledWith("Usage: /mem0-forget <query>", "warning");
expect(mem0.search).not.toHaveBeenCalled();
});
it("notifies when no memories match", async () => {
const ctx = makeCtx();
mem0.search.mockResolvedValue({ results: [] });
await pi._invoke("mem0-forget", "old preference", ctx);
expect(ctx.ui.notify).toHaveBeenCalledWith("No matching memories found.", "info");
});
it("asks for confirmation before deleting a single match", async () => {
const ctx = makeCtx(true);
mem0.search.mockResolvedValue({ results: [{ id: "abc-123", memory: "test mem" }] });
mem0.delete.mockResolvedValue({ message: "Deleted" });
await pi._invoke("mem0-forget", "test", ctx);
expect(ctx.ui.confirm).toHaveBeenCalledWith(
"Delete this memory?",
expect.stringContaining("test mem"),
);
expect(mem0.delete).toHaveBeenCalledWith("abc-123");
});
it("does not delete when user cancels confirmation", async () => {
const ctx = makeCtx(false);
mem0.search.mockResolvedValue({ results: [{ id: "abc-123", memory: "test mem" }] });
await pi._invoke("mem0-forget", "test", ctx);
expect(ctx.ui.confirm).toHaveBeenCalled();
expect(mem0.delete).not.toHaveBeenCalled();
expect(ctx.ui.notify).toHaveBeenCalledWith("Cancelled.", "info");
});
it("uses select UI for multiple matches and deletes chosen memory", async () => {
const ctx = makeCtx();
mem0.search.mockResolvedValue({
results: [
{ id: "id-1", memory: "mem one" },
{ id: "id-2", memory: "mem two" },
],
});
mem0.delete.mockResolvedValue({ message: "Deleted" });
ctx.ui.select = vi.fn(async (_title: string, options: string[]) => options[1]);
await pi._invoke("mem0-forget", "test", ctx);
expect(ctx.ui.select).toHaveBeenCalledWith(
"Which memory should I delete?",
expect.arrayContaining([
expect.stringContaining("mem one"),
expect.stringContaining("mem two"),
]),
);
expect(mem0.delete).toHaveBeenCalledWith("id-2");
});
it("does not delete when user cancels select", async () => {
const ctx = makeCtx();
ctx.ui.select = vi.fn(async () => undefined);
mem0.search.mockResolvedValue({
results: [
{ id: "id-1", memory: "mem one" },
{ id: "id-2", memory: "mem two" },
],
});
await pi._invoke("mem0-forget", "test", ctx);
expect(mem0.delete).not.toHaveBeenCalled();
expect(ctx.ui.notify).toHaveBeenCalledWith("Cancelled.", "info");
});
});
describe("/mem0-pin", () => {
it("uses update to pin in-place, preserving memory ID", async () => {
const ctx = makeCtx(true);
mem0.search.mockResolvedValue({ results: [{ id: "abc-123", memory: "important fact" }] });
mem0.update.mockResolvedValue([]);
await pi._invoke("mem0-pin", "important", ctx);
expect(ctx.ui.confirm).toHaveBeenCalledWith(
"Pin this memory?",
expect.stringContaining("important fact"),
);
expect(mem0.update).toHaveBeenCalledWith("abc-123", { text: "[PINNED] important fact" });
expect(mem0.add).not.toHaveBeenCalled();
expect(mem0.delete).not.toHaveBeenCalled();
});
it("does not pin when user cancels", async () => {
const ctx = makeCtx(false);
mem0.search.mockResolvedValue({ results: [{ id: "abc-123", memory: "fact" }] });
await pi._invoke("mem0-pin", "fact", ctx);
expect(mem0.update).not.toHaveBeenCalled();
});
it("skips already-pinned memories", async () => {
const ctx = makeCtx();
mem0.search.mockResolvedValue({ results: [{ id: "abc-123", memory: "[PINNED] fact" }] });
await pi._invoke("mem0-pin", "fact", ctx);
expect(ctx.ui.confirm).not.toHaveBeenCalled();
expect(mem0.add).not.toHaveBeenCalled();
expect(ctx.ui.notify).toHaveBeenCalledWith("Already pinned.", "info");
});
it("uses select UI for multiple matches and pins chosen memory", async () => {
const ctx = makeCtx();
mem0.search.mockResolvedValue({
results: [
{ id: "id-1", memory: "fact one" },
{ id: "id-2", memory: "fact two" },
],
});
mem0.update.mockResolvedValue([]);
ctx.ui.select = vi.fn(async (_title: string, options: string[]) => options[1]);
await pi._invoke("mem0-pin", "fact", ctx);
expect(ctx.ui.select).toHaveBeenCalledWith(
"Which memory should I pin?",
expect.arrayContaining([
expect.stringContaining("fact one"),
expect.stringContaining("fact two"),
]),
);
expect(mem0.update).toHaveBeenCalledWith("id-2", { text: "[PINNED] fact two" });
});
it("does not pin when user cancels select", async () => {
const ctx = makeCtx();
ctx.ui.select = vi.fn(async () => undefined);
mem0.search.mockResolvedValue({
results: [
{ id: "id-1", memory: "fact one" },
{ id: "id-2", memory: "fact two" },
],
});
await pi._invoke("mem0-pin", "fact", ctx);
expect(mem0.update).not.toHaveBeenCalled();
expect(ctx.ui.notify).toHaveBeenCalledWith("Cancelled.", "info");
});
});
describe("/mem0-search", () => {
it("always performs semantic search", async () => {
const ctx = makeCtx();
mem0.search.mockResolvedValue({ results: [{ id: "id-1", memory: "result" }] });
await pi._invoke("mem0-search", "my preferences", ctx);
expect(mem0.search).toHaveBeenCalledWith("my preferences", expect.any(Object));
expect(pi.sendMessage).toHaveBeenCalledWith(
expect.objectContaining({ customType: "mem0-search" }),
);
});
it("uses semantic search even for hex-looking strings", async () => {
const ctx = makeCtx();
mem0.search.mockResolvedValue({ results: [] });
await pi._invoke("mem0-search", "abcd1234", ctx);
expect(mem0.search).toHaveBeenCalledWith("abcd1234", expect.any(Object));
expect(mem0.getAll).not.toHaveBeenCalled();
expect(mem0.get).not.toHaveBeenCalled();
});
it("shows empty results message", async () => {
const ctx = makeCtx();
mem0.search.mockResolvedValue({ results: [] });
await pi._invoke("mem0-search", "nonexistent", ctx);
expect(pi.sendMessage).toHaveBeenCalledWith(
expect.objectContaining({ content: "No memories found." }),
);
});
});
describe("/mem0-remember", () => {
it("stores a memory verbatim", async () => {
const ctx = makeCtx();
mem0.add.mockResolvedValue({ message: "Memory stored." });
await pi._invoke("mem0-remember", "I prefer dark mode", ctx);
expect(mem0.add).toHaveBeenCalledWith(
[{ role: "user", content: "I prefer dark mode" }],
expect.objectContaining({ infer: false }),
);
});
it("shows warning when no text provided", async () => {
const ctx = makeCtx();
await pi._invoke("mem0-remember", " ", ctx);
expect(ctx.ui.notify).toHaveBeenCalledWith("Usage: /mem0-remember <text>", "warning");
});
});
});
+291
View File
@@ -0,0 +1,291 @@
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import type MemoryClient from "mem0ai";
import type { Mem0Config, ScopeContext, Scope } from "./types.ts";
import { DEFAULT_CUSTOM_CATEGORIES } from "./types.ts";
import { resolveSearchFilters, resolveAddParams } from "./memory/scoping.ts";
import { formatMemoryList, formatMemoryCompact, groupByCategory } from "./memory/formatting.ts";
import { DREAM_PROTOCOL } from "./dream/prompt.ts";
import { acquireDreamLock } from "./dream/index.ts";
import { CONFIG_DIR } from "./config/index.ts";
import { captureCommandEvent } from "./telemetry.ts";
export function registerCommands(
pi: ExtensionAPI,
mem0: MemoryClient,
config: Mem0Config,
getScopeCtx: () => ScopeContext,
telemetryCtx?: { apiKey?: string },
): void {
// ── /mem0-remember ──────────────────────────────────────────────────
pi.registerCommand("mem0-remember", {
description: "Store a memory verbatim (no inference)",
handler: async (args, ctx) => {
const text = args?.trim();
if (!text) {
ctx.ui.notify("Usage: /mem0-remember <text>", "warning");
return;
}
const scopeCtx = getScopeCtx();
const addParams = resolveAddParams(config.defaultScope, scopeCtx);
const result = await mem0.add(
[{ role: "user", content: text }],
{ ...addParams, customCategories: DEFAULT_CUSTOM_CATEGORIES, infer: false },
);
const msg = (result as { message?: string }).message ?? "Memory stored.";
captureCommandEvent("mem0-remember", {}, telemetryCtx);
ctx.ui.notify(msg, "info");
},
});
// ── /mem0-forget ────────────────────────────────────────────────────
pi.registerCommand("mem0-forget", {
description: "Delete memories matching a natural language query",
handler: async (args, ctx) => {
const query = args?.trim();
if (!query) {
ctx.ui.notify("Usage: /mem0-forget <query>", "warning");
return;
}
const scopeCtx = getScopeCtx();
const filters = resolveSearchFilters(config.defaultScope, scopeCtx);
const result = await mem0.search(query, { filters });
const memories = result.results ?? [];
if (memories.length === 0) {
captureCommandEvent("mem0-forget", { result_count: 0 }, telemetryCtx);
ctx.ui.notify("No matching memories found.", "info");
return;
}
if (memories.length === 1) {
const target = memories[0];
const confirmed = await ctx.ui.confirm(
"Delete this memory?",
formatMemoryCompact(target),
);
if (!confirmed) {
ctx.ui.notify("Cancelled.", "info");
return;
}
await mem0.delete(target.id);
captureCommandEvent("mem0-forget", { deleted_count: 1 }, telemetryCtx);
ctx.ui.notify(`Deleted: ${formatMemoryCompact(target)}`, "info");
return;
}
const labels = memories.map((m) => formatMemoryCompact(m));
const selected = await ctx.ui.select("Which memory should I delete?", labels);
if (!selected) {
ctx.ui.notify("Cancelled.", "info");
return;
}
const idx = labels.indexOf(selected);
if (idx < 0) return;
const target = memories[idx];
await mem0.delete(target.id);
captureCommandEvent("mem0-forget", { deleted_count: 1 }, telemetryCtx);
ctx.ui.notify(`Deleted: ${formatMemoryCompact(target)}`, "info");
},
});
// ── /mem0-search ────────────────────────────────────────────────────
pi.registerCommand("mem0-search", {
description: "Semantic search across memories",
handler: async (args, ctx) => {
const query = args?.trim();
if (!query) {
ctx.ui.notify("Usage: /mem0-search <query>", "warning");
return;
}
const scopeCtx = getScopeCtx();
const filters = resolveSearchFilters(config.defaultScope, scopeCtx);
const result = await mem0.search(query, { filters });
const memories = result.results ?? [];
captureCommandEvent("mem0-search", { result_count: memories.length }, telemetryCtx);
pi.sendMessage({
customType: "mem0-search",
content: formatMemoryList(memories),
display: true,
});
},
});
// ── /mem0-tour ──────────────────────────────────────────────────────
pi.registerCommand("mem0-tour", {
description: "Browse all memories grouped by category",
handler: async (args, ctx) => {
const raw = args?.trim().toLowerCase();
const validScopes: Scope[] = ["project", "session", "global"];
if (raw && !validScopes.includes(raw as Scope)) {
ctx.ui.notify(`Invalid scope "${raw}". Must be one of: ${validScopes.join(", ")}`, "warning");
return;
}
const scope: Scope = (raw as Scope) || config.defaultScope;
const scopeCtx = getScopeCtx();
const filters = resolveSearchFilters(scope, scopeCtx);
const result = await mem0.getAll({ filters });
const memories = result.results ?? [];
if (memories.length === 0) {
captureCommandEvent("mem0-tour", { memory_count: 0, scope }, telemetryCtx);
pi.sendMessage({ customType: "mem0-tour", content: "No memories found.", display: true });
return;
}
const groups = groupByCategory(memories);
const lines: string[] = [`**Memory Tour** (${memories.length} total, scope: ${scope})`, ""];
for (const [category, items] of groups) {
lines.push(`### ${category} (${items.length})`);
for (const m of items) {
lines.push(`- ${formatMemoryCompact(m)}`);
}
lines.push("");
}
captureCommandEvent("mem0-tour", { memory_count: memories.length, scope }, telemetryCtx);
pi.sendMessage({ customType: "mem0-tour", content: lines.join("\n"), display: true });
},
});
// ── /mem0-dream ─────────────────────────────────────────────────────
pi.registerCommand("mem0-dream", {
description: "Consolidate memories — merge duplicates, prune stale entries, resolve contradictions",
handler: async (_args, ctx) => {
if (!acquireDreamLock(CONFIG_DIR)) {
ctx.ui.notify("A dream consolidation is already in progress.", "warning");
return;
}
captureCommandEvent("mem0-dream", {}, telemetryCtx);
pi.sendMessage({ customType: "mem0-dream", content: DREAM_PROTOCOL, display: true }, { triggerTurn: true });
ctx.ui.notify("Dream consolidation started.", "info");
},
});
// ── /mem0-pin ───────────────────────────────────────────────────────
pi.registerCommand("mem0-pin", {
description: "Pin a memory to protect it from dream pruning",
handler: async (args, ctx) => {
const query = args?.trim();
if (!query) {
ctx.ui.notify("Usage: /mem0-pin <query>", "warning");
return;
}
const scopeCtx = getScopeCtx();
const filters = resolveSearchFilters(config.defaultScope, scopeCtx);
const result = await mem0.search(query, { filters });
const memories = result.results ?? [];
if (memories.length === 0) {
captureCommandEvent("mem0-pin", { result_count: 0 }, telemetryCtx);
ctx.ui.notify("No matching memories found to pin.", "info");
return;
}
if (memories.length === 1) {
const target = memories[0];
const text = target.memory ?? "";
if (text.startsWith("[PINNED]")) {
ctx.ui.notify("Already pinned.", "info");
return;
}
const confirmed = await ctx.ui.confirm(
"Pin this memory?",
formatMemoryCompact(target),
);
if (!confirmed) {
ctx.ui.notify("Cancelled.", "info");
return;
}
await mem0.update(target.id, { text: `[PINNED] ${text}` });
captureCommandEvent("mem0-pin", { pinned: true }, telemetryCtx);
ctx.ui.notify(`Pinned: ${formatMemoryCompact(target)}`, "info");
return;
}
const labels = memories.map((m) => formatMemoryCompact(m));
const selected = await ctx.ui.select("Which memory should I pin?", labels);
if (!selected) {
ctx.ui.notify("Cancelled.", "info");
return;
}
const idx = labels.indexOf(selected);
if (idx < 0) return;
const target = memories[idx];
const selectedText = target.memory ?? "";
if (selectedText.startsWith("[PINNED]")) {
ctx.ui.notify("Already pinned.", "info");
return;
}
await mem0.update(target.id, { text: `[PINNED] ${selectedText}` });
captureCommandEvent("mem0-pin", { pinned: true }, telemetryCtx);
ctx.ui.notify(`Pinned: ${formatMemoryCompact(target)}`, "info");
},
});
// ── /mem0-scope ─────────────────────────────────────────────────────
pi.registerCommand("mem0-scope", {
description: "Change default memory scope for this session (project, session, global)",
handler: async (args, ctx) => {
const scope = args?.trim().toLowerCase();
const valid: Scope[] = ["project", "session", "global"];
if (!scope) {
ctx.ui.notify(`Current scope: ${config.defaultScope}. Usage: /mem0-scope <${valid.join("|")}>`, "info");
return;
}
if (!valid.includes(scope as Scope)) {
ctx.ui.notify(`Invalid scope "${scope}". Must be one of: ${valid.join(", ")}`, "warning");
return;
}
config.defaultScope = scope as Scope;
captureCommandEvent("mem0-scope", { scope }, telemetryCtx);
ctx.ui.notify(`Default scope changed to "${scope}" for this session.`, "info");
},
});
// ── /mem0-status ────────────────────────────────────────────────────
pi.registerCommand("mem0-status", {
description: "Show connection health, identity, project, and memory count",
handler: async (_args, _ctx) => {
const scopeCtx = getScopeCtx();
const filters = resolveSearchFilters("project", scopeCtx);
let count = 0;
let connected = false;
try {
const result = await mem0.getAll({ filters });
count = result.count ?? (result.results ?? []).length;
connected = true;
} catch {
connected = false;
}
const lines = [
"**Mem0 Status**",
"",
`- Connection: ${connected ? "connected" : "disconnected"}`,
`- User: ${scopeCtx.userId}`,
`- Project: ${scopeCtx.appId}`,
`- Session: ${scopeCtx.runId}`,
`- Default scope: ${config.defaultScope}`,
`- Project memories: ${count}`,
`- Auto-capture: ${config.autoCapture ? "on" : "off"}`,
`- Dream: ${config.dream.enabled ? "enabled" : "disabled"}`,
];
captureCommandEvent("mem0-status", { connected, memory_count: count }, telemetryCtx);
pi.sendMessage({ customType: "mem0-status", content: lines.join("\n"), display: true });
},
});
}
+58
View File
@@ -0,0 +1,58 @@
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import type { Mem0Config, DreamConfig } from "../types.ts";
const AGENT_ROOT = path.join(os.homedir(), ".pi", "agent");
export const CONFIG_DIR = AGENT_ROOT;
const CONFIG_PATH = path.join(AGENT_ROOT, "mem0-config.json");
const DEFAULT_DREAM: DreamConfig = {
enabled: true,
auto: true,
minHours: 24,
minSessions: 5,
minMemories: 20,
};
const DEFAULT_CONFIG: Mem0Config = {
apiKey: "",
userId: "",
autoCapture: true,
defaultScope: "project",
contextInjection: false,
dream: DEFAULT_DREAM,
};
export function loadConfig(): Mem0Config {
let fileConfig: Partial<Mem0Config> = {};
if (fs.existsSync(CONFIG_PATH)) {
try {
const raw = fs.readFileSync(CONFIG_PATH, "utf-8");
fileConfig = JSON.parse(raw);
} catch {
// Corrupted config — use defaults
}
}
const dream: DreamConfig = {
...DEFAULT_DREAM,
...(fileConfig.dream ?? {}),
};
const config: Mem0Config = {
...DEFAULT_CONFIG,
...fileConfig,
dream,
};
if (process.env.MEM0_API_KEY) {
config.apiKey = process.env.MEM0_API_KEY;
}
if (process.env.MEM0_USER_ID) {
config.userId = process.env.MEM0_USER_ID;
}
return config;
}
+115
View File
@@ -0,0 +1,115 @@
import * as fs from "node:fs";
import * as path from "node:path";
import type { DreamState, DreamLock, DreamConfig } from "../types.ts";
const LOCK_STALE_MS = 60 * 60 * 1000;
const DEFAULTS: DreamConfig = {
enabled: true,
auto: true,
minHours: 24,
minSessions: 5,
minMemories: 20,
};
function statePath(stateDir: string): string {
return path.join(stateDir, "mem0-dream-state.json");
}
function lockPath(stateDir: string): string {
return path.join(stateDir, "mem0-dream.lock");
}
function ensureDir(dir: string): void {
try {
fs.mkdirSync(dir, { recursive: true });
} catch { /* exists */ }
}
function readState(stateDir: string): DreamState {
try {
const raw = fs.readFileSync(statePath(stateDir), "utf-8");
return JSON.parse(raw) as DreamState;
} catch {
return { lastConsolidatedAt: 0, sessionsSince: 0, lastSessionId: null };
}
}
function writeState(stateDir: string, state: DreamState): void {
ensureDir(stateDir);
fs.writeFileSync(statePath(stateDir), JSON.stringify(state, null, 2));
}
export function incrementSessionCount(stateDir: string, sessionId: string): void {
const state = readState(stateDir);
if (state.lastSessionId !== sessionId) {
state.sessionsSince++;
state.lastSessionId = sessionId;
writeState(stateDir, state);
}
}
export function checkCheapGates(
stateDir: string,
config: Partial<DreamConfig>,
): { proceed: boolean; reason?: string } {
const minHours = config.minHours ?? DEFAULTS.minHours;
const minSessions = config.minSessions ?? 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 };
}
export function checkMemoryGate(
memoryCount: number,
config: Partial<DreamConfig>,
): { pass: boolean; reason?: string } {
const minMemories = config.minMemories ?? DEFAULTS.minMemories;
if (memoryCount < minMemories) {
return { pass: false, reason: `memories: ${memoryCount} < ${minMemories}` };
}
return { pass: true };
}
export function acquireDreamLock(stateDir: string): boolean {
ensureDir(stateDir);
const lp = lockPath(stateDir);
try {
const raw = fs.readFileSync(lp, "utf-8");
const lock = JSON.parse(raw) as DreamLock;
if (Date.now() - lock.startedAt < LOCK_STALE_MS) {
return false;
}
try { fs.unlinkSync(lp); } catch { /* race ok */ }
} catch { /* no lock file */ }
const lock: DreamLock = { pid: process.pid, startedAt: Date.now() };
try {
fs.writeFileSync(lp, JSON.stringify(lock), { flag: "wx" });
return true;
} catch {
return false;
}
}
export function releaseDreamLock(stateDir: string): void {
try { fs.unlinkSync(lockPath(stateDir)); } catch { /* already gone */ }
}
export function recordDreamCompletion(stateDir: string): void {
const state = readState(stateDir);
state.lastConsolidatedAt = Date.now();
state.sessionsSince = 0;
state.lastSessionId = null;
writeState(stateDir, state);
}
+22
View File
@@ -0,0 +1,22 @@
export const DREAM_PROTOCOL = `<mem0-dream>
You are running memory consolidation. Complete these steps using the mem0_memory tool:
1. ORIENT — Call mem0_memory with action "get_all" 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. Use mem0_memory "add" with improved text, then "delete" the old one.
- KEEP: everything else.
Skip any memory starting with "[PINNED]".
3. CONSOLIDATE — Execute the changes:
- Delete stale/duplicate entries
- For merges: add the merged text, delete both originals
- For rewrites: add improved version, delete 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>`;
+34
View File
@@ -0,0 +1,34 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { resolveUserId } from "./entry.ts";
describe("resolveUserId", () => {
const originalEnv = { ...process.env };
afterEach(() => {
process.env = { ...originalEnv };
});
it("returns config userId when set", () => {
expect(resolveUserId("config-user")).toBe("config-user");
});
it("falls back to USER env var", () => {
process.env.USER = "env-user";
delete process.env.USERNAME;
expect(resolveUserId("")).toBe("env-user");
});
it("falls back to USERNAME env var on Windows", () => {
delete process.env.USER;
process.env.USERNAME = "win-user";
expect(resolveUserId("")).toBe("win-user");
});
it("falls back to os.userInfo() when env vars are missing", () => {
delete process.env.USER;
delete process.env.USERNAME;
const result = resolveUserId("");
expect(typeof result).toBe("string");
expect(result.length).toBeGreaterThan(0);
});
});
+146
View File
@@ -0,0 +1,146 @@
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import MemoryClient from "mem0ai";
import { loadConfig, CONFIG_DIR } from "./config/index.ts";
import { detectAppId, detectRunId, resolveSearchFilters } from "./memory/scoping.ts";
import { registerMemoryTool } from "./memory/tools.ts";
import { registerCommands } from "./commands.ts";
import { setupAutoCapture } from "./capture/index.ts";
import { MEMORY_POLICY } from "./prompt.ts";
import { DREAM_PROTOCOL } from "./dream/prompt.ts";
import {
incrementSessionCount,
checkCheapGates,
checkMemoryGate,
acquireDreamLock,
releaseDreamLock,
recordDreamCompletion,
} from "./dream/index.ts";
import { captureEvent } from "./telemetry.ts";
import * as os from "node:os";
import type { ScopeContext } from "./types.ts";
export function resolveUserId(configUserId: string): string {
if (configUserId) return configUserId;
if (process.env.USER) return process.env.USER;
if (process.env.USERNAME) return process.env.USERNAME;
try { return os.userInfo().username; } catch { return "default"; }
}
export default function mem0Extension(pi: ExtensionAPI): void {
const config = loadConfig();
if (!config.apiKey) {
console.warn("[mem0] No API key found. Set MEM0_API_KEY or add apiKey to ~/.pi/agent/mem0-config.json. Extension disabled.");
return;
}
const mem0 = new MemoryClient({ apiKey: config.apiKey });
const scopeCtx: ScopeContext = {
userId: resolveUserId(config.userId),
appId: "",
runId: "unknown",
};
function getScopeCtx(): ScopeContext {
return scopeCtx;
}
const telemetryCtx = { apiKey: config.apiKey };
// ── Register tool + commands + auto-capture ─────────────────────────
registerMemoryTool(pi, mem0, config, getScopeCtx, telemetryCtx);
registerCommands(pi, mem0, config, getScopeCtx, telemetryCtx);
setupAutoCapture(pi, mem0, config, getScopeCtx, telemetryCtx);
captureEvent("pi.plugin.registered", {
auto_capture: config.autoCapture,
dream_enabled: config.dream.enabled,
default_scope: config.defaultScope,
}, telemetryCtx);
// ── session_start: detect project + session, reconstruct scope ──────
pi.on("session_start", async (_event, ctx) => {
scopeCtx.appId = detectAppId(ctx.cwd);
const sessionFile = ctx.sessionManager?.getSessionFile?.();
scopeCtx.runId = detectRunId(sessionFile);
if (config.userId) {
scopeCtx.userId = config.userId;
}
if (config.dream.enabled) {
incrementSessionCount(CONFIG_DIR, scopeCtx.runId);
}
captureEvent("pi.session.start", {}, telemetryCtx);
});
// ── before_agent_start: append memory policy + auto-dream trigger ───
let dreamTriggered = false;
let dreamChecked = false;
pi.on("before_agent_start", async (event, _ctx) => {
let extra = MEMORY_POLICY;
if (config.dream.enabled && config.dream.auto && !dreamTriggered && !dreamChecked) {
const gates = checkCheapGates(CONFIG_DIR, config.dream);
if (gates.proceed) {
try {
const filters = resolveSearchFilters("project", scopeCtx);
const result = await mem0.getAll({ filters });
const count = result.count ?? (result.results ?? []).length;
dreamChecked = true;
const memGate = checkMemoryGate(count, config.dream);
if (memGate.pass && acquireDreamLock(CONFIG_DIR)) {
dreamTriggered = true;
extra += "\n\n" + DREAM_PROTOCOL;
captureEvent("pi.dream.triggered", { memory_count: count }, telemetryCtx);
}
} catch {
// Transient error — retry next turn
}
}
}
return {
systemPrompt: (event.systemPrompt ?? "") + "\n\n" + extra,
};
});
// ── agent_end: dream completion check ───────────────────────────────
pi.on("agent_end", async (event) => {
if (!dreamTriggered) return;
const messages = event.messages ?? [];
const hadWriteAction = messages.some((m) => {
if (m.role !== "assistant") return false;
const content = Array.isArray(m.content) ? m.content : [];
return content.some(
(block: any) =>
block.type === "tool_use" &&
block.name === "mem0_memory" &&
["add", "delete", "delete_all"].includes(block.input?.action),
);
});
if (hadWriteAction) {
recordDreamCompletion(CONFIG_DIR);
captureEvent("pi.dream.completed", {}, telemetryCtx);
}
releaseDreamLock(CONFIG_DIR);
dreamTriggered = false;
});
// ── session_shutdown: release dream lock if still held ──────────────
pi.on("session_shutdown", async () => {
captureEvent("pi.session.stop", {}, telemetryCtx);
if (dreamTriggered) {
releaseDreamLock(CONFIG_DIR);
dreamTriggered = false;
}
});
}
+34
View File
@@ -0,0 +1,34 @@
export type {
Scope,
Mem0Config,
DreamConfig,
ScopeContext,
CustomCategory,
} from "./types.ts";
export { DEFAULT_CUSTOM_CATEGORIES } from "./types.ts";
export { loadConfig, CONFIG_DIR } from "./config/index.ts";
export { registerMemoryTool, buildToolExecute } from "./memory/tools.ts";
export { detectAppId, detectRunId, resolveSearchFilters, resolveAddParams } from "./memory/scoping.ts";
export { formatAge, formatMemoryCompact, formatMemoryList, groupByCategory } from "./memory/formatting.ts";
export { setupAutoCapture, extractConversation } from "./capture/index.ts";
export {
incrementSessionCount,
checkCheapGates,
checkMemoryGate,
acquireDreamLock,
releaseDreamLock,
recordDreamCompletion,
} from "./dream/index.ts";
export { DREAM_PROTOCOL } from "./dream/prompt.ts";
export { MEMORY_POLICY } from "./prompt.ts";
export { registerCommands } from "./commands.ts";
export { captureEvent, captureToolEvent, captureCommandEvent, _getEventQueue, _resetForTesting } from "./telemetry.ts";
export { default as mem0Extension } from "./entry.ts";
+43
View File
@@ -0,0 +1,43 @@
interface MemoryLike {
id: string;
memory?: string;
categories?: string[];
createdAt?: Date | string;
}
export function formatAge(date: Date | string): string {
const d = typeof date === "string" ? new Date(date) : date;
const ms = Date.now() - d.getTime();
const minutes = Math.floor(ms / 60_000);
if (minutes < 60) return `${minutes}m ago`;
const hours = Math.floor(minutes / 60);
if (hours < 24) return `${hours}h ago`;
const days = Math.floor(hours / 24);
return `${days}d ago`;
}
export function formatMemoryCompact(mem: MemoryLike): string {
const cat = mem.categories?.[0] ?? "uncategorized";
const age = mem.createdAt ? ` (${formatAge(mem.createdAt)})` : "";
return `[${cat}] ${mem.memory ?? "(empty)"}${age} [mem0:${mem.id}]`;
}
export function formatMemoryList(memories: MemoryLike[]): string {
if (memories.length === 0) return "No memories found.";
return memories
.map((m, i) => `${i + 1}. ${formatMemoryCompact(m)}`)
.join("\n");
}
export function groupByCategory(
memories: MemoryLike[],
): Map<string, MemoryLike[]> {
const groups = new Map<string, MemoryLike[]>();
for (const m of memories) {
const cat = m.categories?.[0] ?? "uncategorized";
const list = groups.get(cat) ?? [];
list.push(m);
groups.set(cat, list);
}
return groups;
}
@@ -0,0 +1,85 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { detectRunId, resolveSearchFilters, resolveAddParams } from "./scoping.ts";
const mockExecFileSync = vi.fn();
vi.mock("node:child_process", () => ({
execFileSync: (...args: any[]) => mockExecFileSync(...args),
}));
const { detectAppId } = await import("./scoping.ts");
describe("detectAppId", () => {
beforeEach(() => {
mockExecFileSync.mockReset();
});
it("uses git root basename for a git repo", () => {
mockExecFileSync.mockReturnValue("/home/user/projects/my-app\n");
expect(detectAppId("/home/user/projects/my-app")).toBe("my-app");
});
it("returns same app_id from any subdirectory in a monorepo", () => {
mockExecFileSync.mockReturnValue("/home/user/projects/monorepo\n");
const root = detectAppId("/home/user/projects/monorepo");
const sub = detectAppId("/home/user/projects/monorepo/packages/core");
expect(root).toBe("monorepo");
expect(sub).toBe("monorepo");
});
it("falls back to basename when not in a git repo", () => {
mockExecFileSync.mockImplementation(() => {
throw new Error("fatal: not a git repository");
});
expect(detectAppId("/home/user/scratch")).toBe("scratch");
});
});
describe("detectRunId", () => {
it("returns 'unknown' when no session file", () => {
expect(detectRunId(undefined)).toBe("unknown");
});
it("returns a 12-char hex hash for a session file", () => {
const id = detectRunId("/tmp/session-abc.json");
expect(id).toMatch(/^[0-9a-f]{12}$/);
});
it("produces different IDs for different session files", () => {
const a = detectRunId("/tmp/session-a.json");
const b = detectRunId("/tmp/session-b.json");
expect(a).not.toBe(b);
});
});
describe("resolveSearchFilters", () => {
const ctx = { userId: "u1", appId: "a1", runId: "r1" };
it("includes user_id and app_id for project scope", () => {
expect(resolveSearchFilters("project", ctx)).toEqual({ user_id: "u1", app_id: "a1" });
});
it("includes run_id for session scope", () => {
expect(resolveSearchFilters("session", ctx)).toEqual({ user_id: "u1", app_id: "a1", run_id: "r1" });
});
it("uses wildcard app_id for global scope", () => {
expect(resolveSearchFilters("global", ctx)).toEqual({ user_id: "u1", app_id: "*" });
});
});
describe("resolveAddParams", () => {
const ctx = { userId: "u1", appId: "a1", runId: "r1" };
it("includes userId and appId for project scope", () => {
expect(resolveAddParams("project", ctx)).toEqual({ userId: "u1", appId: "a1" });
});
it("includes runId for session scope", () => {
expect(resolveAddParams("session", ctx)).toEqual({ userId: "u1", appId: "a1", runId: "r1" });
});
it("only includes userId for global scope", () => {
expect(resolveAddParams("global", ctx)).toEqual({ userId: "u1" });
});
});
+51
View File
@@ -0,0 +1,51 @@
import * as path from "node:path";
import * as crypto from "node:crypto";
import { execFileSync } from "node:child_process";
import type { Scope, ScopeContext } from "../types.ts";
export function detectAppId(cwd: string): string {
try {
const root = execFileSync("git", ["rev-parse", "--show-toplevel"], {
cwd,
encoding: "utf-8",
timeout: 3000,
stdio: ["ignore", "pipe", "ignore"],
}).trim();
return path.basename(root);
} catch {
return path.basename(cwd);
}
}
export function detectRunId(sessionFile: string | undefined): string {
if (!sessionFile) return "unknown";
return crypto.createHash("sha256").update(sessionFile).digest("hex").slice(0, 12);
}
export function resolveSearchFilters(
scope: Scope,
ctx: ScopeContext,
): Record<string, string> {
switch (scope) {
case "project":
return { user_id: ctx.userId, app_id: ctx.appId };
case "session":
return { user_id: ctx.userId, app_id: ctx.appId, run_id: ctx.runId };
case "global":
return { user_id: ctx.userId, app_id: "*" };
}
}
export function resolveAddParams(
scope: Scope,
ctx: ScopeContext,
): Record<string, string> {
switch (scope) {
case "project":
return { userId: ctx.userId, appId: ctx.appId };
case "session":
return { userId: ctx.userId, appId: ctx.appId, runId: ctx.runId };
case "global":
return { userId: ctx.userId };
}
}
+195
View File
@@ -0,0 +1,195 @@
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";
import { StringEnum } from "@earendil-works/pi-ai";
import type MemoryClient from "mem0ai";
import type { Scope, ScopeContext, Mem0Config } from "../types.ts";
import { DEFAULT_CUSTOM_CATEGORIES } from "../types.ts";
import { resolveSearchFilters, resolveAddParams } from "./scoping.ts";
import { formatMemoryList } from "./formatting.ts";
import { captureToolEvent } from "../telemetry.ts";
interface MemoryResult {
message?: string;
eventId?: string;
status?: string;
}
const MAX_OUTPUT_LINES = 200;
const MAX_OUTPUT_BYTES = 50_000;
function truncateOutput(text: string): string {
const lines = text.split("\n");
if (lines.length <= MAX_OUTPUT_LINES && text.length <= MAX_OUTPUT_BYTES) {
return text;
}
const kept = lines.slice(0, MAX_OUTPUT_LINES);
let result = kept.join("\n");
if (result.length > MAX_OUTPUT_BYTES) {
result = result.slice(0, MAX_OUTPUT_BYTES);
}
const dropped = lines.length - kept.length;
if (dropped > 0 || text.length > MAX_OUTPUT_BYTES) {
result += `\n\n[Output truncated: showing ${kept.length} of ${lines.length} lines]`;
}
return result;
}
interface ToolParams {
action: "search" | "add" | "get_all" | "update" | "delete" | "delete_all";
query?: string;
content?: string;
memory_id?: string;
scope?: Scope;
}
export function buildToolExecute(
mem0: MemoryClient,
scopeCtx: ScopeContext,
defaultScope: Scope,
) {
return async (params: ToolParams, signal?: AbortSignal) => {
const scope = params.scope ?? defaultScope;
switch (params.action) {
case "search": {
if (signal?.aborted) throw new Error("Cancelled");
if (!params.query) throw new Error("query is required for search");
const filters = resolveSearchFilters(scope, scopeCtx);
const result = await mem0.search(params.query, { filters });
const memories = result.results ?? [];
return {
content: [{ type: "text" as const, text: truncateOutput(formatMemoryList(memories)) }],
details: { matchCount: memories.length },
};
}
case "add": {
if (signal?.aborted) throw new Error("Cancelled");
if (!params.content) throw new Error("content is required for add");
const addParams = resolveAddParams(scope, scopeCtx);
const result = await mem0.add(
[{ role: "user", content: params.content }],
{ ...addParams, customCategories: DEFAULT_CUSTOM_CATEGORIES },
);
const res = result as MemoryResult;
const msg = res.message ?? "Memory stored.";
return {
content: [{ type: "text" as const, text: msg }],
details: { eventId: res.eventId ?? null, status: res.status ?? null },
};
}
case "get_all": {
if (signal?.aborted) throw new Error("Cancelled");
const filters = resolveSearchFilters(scope, scopeCtx);
const result = await mem0.getAll({ filters });
const memories = result.results ?? [];
return {
content: [{ type: "text" as const, text: truncateOutput(formatMemoryList(memories)) }],
details: { totalCount: result.count ?? memories.length },
};
}
case "update": {
if (signal?.aborted) throw new Error("Cancelled");
if (!params.memory_id) throw new Error("memory_id is required for update");
if (!params.content) throw new Error("content is required for update");
const updateResult = await mem0.update(params.memory_id, { text: params.content });
const res = updateResult as MemoryResult;
return {
content: [{ type: "text" as const, text: res.status ?? "Memory updated." }],
details: { memoryId: params.memory_id },
};
}
case "delete": {
if (signal?.aborted) throw new Error("Cancelled");
if (!params.memory_id) throw new Error("memory_id is required for delete");
const result = await mem0.delete(params.memory_id);
return {
content: [{ type: "text" as const, text: result.message ?? "Memory deleted." }],
details: {},
};
}
case "delete_all": {
if (signal?.aborted) throw new Error("Cancelled");
const delParams = resolveAddParams(scope, scopeCtx);
const result = await mem0.deleteAll(delParams);
return {
content: [{ type: "text" as const, text: result.message ?? "All memories deleted." }],
details: {},
};
}
}
};
}
export function registerMemoryTool(
pi: ExtensionAPI,
mem0: MemoryClient,
config: Mem0Config,
getScopeCtx: () => ScopeContext,
telemetryCtx?: { apiKey?: string },
): void {
pi.registerTool({
name: "mem0_memory",
label: "Mem0 Memory",
description:
"Search, add, update, and manage persistent semantic memories powered by Mem0. Memories persist across sessions and devices. Output is truncated to 200 lines / 50KB.",
promptSnippet: "Semantic memory search and storage via Mem0",
promptGuidelines: [
'Use mem0_memory with action "search" when the user asks about past conversations, preferences, or decisions',
'Use mem0_memory with action "add" to save important facts, preferences, goals, decisions, or lessons the user shares',
'Use mem0_memory with action "update" to modify an existing memory — requires memory_id and content. Preserves the memory ID',
"Always use the default project scope unless the user EXPLICITLY asks to search across all projects — only then use scope \"global\"",
"Do NOT pass scope at all for normal queries — omitting it uses the project default automatically",
],
parameters: Type.Object({
action: StringEnum([
"search",
"add",
"get_all",
"update",
"delete",
"delete_all",
] as const),
query: Type.Optional(
Type.String({ description: "Search query or memory text" }),
),
content: Type.Optional(
Type.String({ description: "Memory content to store or updated text" }),
),
memory_id: Type.Optional(
Type.String({ description: "Memory ID for update or delete" }),
),
scope: Type.Optional(
StringEnum(["project", "session", "global"] as const),
),
}),
async execute(toolCallId, params, signal, onUpdate, ctx) {
const scopeCtx = getScopeCtx();
const exec = buildToolExecute(mem0, scopeCtx, config.defaultScope);
const start = Date.now();
try {
const result = await exec(params as ToolParams, signal);
const details = (result as any).details ?? {};
captureToolEvent((params as ToolParams).action, {
success: true,
latency_ms: Date.now() - start,
result_count: details.matchCount ?? details.totalCount ?? undefined,
}, telemetryCtx);
return result;
} catch (err) {
captureToolEvent((params as ToolParams).action, {
success: false,
latency_ms: Date.now() - start,
error_type: err instanceof Error ? err.name : "unknown",
}, telemetryCtx);
throw err;
}
},
});
}
+16
View File
@@ -0,0 +1,16 @@
export const MEMORY_POLICY = `<mem0-memory-policy>
You have persistent semantic memory via the mem0_memory tool, powered by Mem0.
Memory is scoped to the current project by default. Do not change the scope unless explicitly asked.
- "project" (default): memories for this project — use this for all normal queries
- "session": memories from this session only
- "global": all memories across projects — ONLY use when the user explicitly asks for cross-project search
When to use memory:
- Search when the user references past conversations, preferences, or decisions
- Save important facts, user preferences, key decisions, and lessons learned
- Check memory before asking the user something they may have already told you
- Save identity information, goals, relationships, and routines the user shares
Memory persists across sessions and devices via Mem0's cloud.
</mem0-memory-policy>`;
+240
View File
@@ -0,0 +1,240 @@
/**
* Plugin telemetry — anonymous usage tracking via PostHog.
*
* Sends fire-and-forget events to PostHog using native fetch().
* Events are batched and flushed every 5 seconds or when the queue
* reaches 10 events, whichever comes first.
*
* Disable with: MEM0_TELEMETRY=false
*/
import { createHash, randomUUID } from "node:crypto";
import * as fs from "node:fs";
import * as path from "node:path";
import { CONFIG_DIR } from "./config/index.ts";
const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
const POSTHOG_HOST = "https://us.i.posthog.com/i/v0/e/";
const FLUSH_INTERVAL_MS = 5_000;
const FLUSH_THRESHOLD = 10;
let eventQueue: Record<string, unknown>[] = [];
let flushTimer: ReturnType<typeof setInterval> | undefined;
function _loadPluginVersion(): string {
try {
const pkgUrl = new URL("../package.json", import.meta.url);
const pkg = JSON.parse(fs.readFileSync(pkgUrl, "utf-8"));
return pkg.version ?? "unknown";
} catch {
return "unknown";
}
}
const PLUGIN_VERSION = _loadPluginVersion();
// ── Opt-out ──────────────────────────────────────────────────────────────
function isTelemetryEnabled(): boolean {
try {
const val = process.env.MEM0_TELEMETRY;
if (val !== undefined) {
const s = val.toLowerCase();
return s !== "false" && s !== "0" && s !== "no" && s !== "off";
}
return true;
} catch {
return true;
}
}
// ── Identity ─────────────────────────────────────────────────────────────
const TELEMETRY_ID_PATH = path.join(CONFIG_DIR, "mem0-telemetry-id.json");
let _cachedAnonymousId: string | undefined;
function getOrCreateAnonymousId(): string {
if (_cachedAnonymousId) return _cachedAnonymousId;
try {
if (fs.existsSync(TELEMETRY_ID_PATH)) {
const data = JSON.parse(fs.readFileSync(TELEMETRY_ID_PATH, "utf-8"));
if (data.anonymousId) {
_cachedAnonymousId = data.anonymousId;
return _cachedAnonymousId!;
}
}
} catch { /* ignore */ }
const newId = `pi-mem0-anon-${randomUUID().replace(/-/g, "")}`;
try {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
fs.writeFileSync(TELEMETRY_ID_PATH, JSON.stringify({ anonymousId: newId }), "utf-8");
} catch { /* ignore */ }
_cachedAnonymousId = newId;
return newId;
}
function getDistinctId(apiKey?: string): string {
if (apiKey) {
return createHash("sha256").update(apiKey).digest("hex");
}
return getOrCreateAnonymousId();
}
let _identifyDone = false;
function maybeBuildIdentifyEvent(distinctId: string): Record<string, unknown> | null {
if (_identifyDone) return null;
if (!distinctId || distinctId.startsWith("pi-mem0-anon-")) return null;
try {
if (!fs.existsSync(TELEMETRY_ID_PATH)) {
_identifyDone = true;
return null;
}
const data = JSON.parse(fs.readFileSync(TELEMETRY_ID_PATH, "utf-8"));
const storedAnon = data.anonymousId;
if (!storedAnon) {
_identifyDone = true;
return null;
}
const identifyEvent = {
event: "$identify",
distinct_id: distinctId,
properties: { $anon_distinct_id: storedAnon, $lib: "posthog-node" },
};
try {
fs.unlinkSync(TELEMETRY_ID_PATH);
} catch { /* ignore */ }
_identifyDone = true;
_cachedAnonymousId = undefined;
return identifyEvent;
} catch {
return null;
}
}
// ── Flush machinery ──────────────────────────────────────────────────────
function ensureFlushTimer(): void {
if (flushTimer) return;
flushTimer = setInterval(flushEvents, FLUSH_INTERVAL_MS);
if (typeof flushTimer === "object" && "unref" in flushTimer) {
flushTimer.unref();
}
}
let _exitHandlerInstalled = false;
function ensureExitHandler(): void {
if (_exitHandlerInstalled) return;
_exitHandlerInstalled = true;
process.on("beforeExit", async () => {
if (eventQueue.length === 0) return;
const batch = eventQueue;
eventQueue = [];
const body = JSON.stringify({ api_key: POSTHOG_API_KEY, batch });
try {
await fetch(POSTHOG_HOST, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": String(Buffer.byteLength(body)),
},
body,
signal: AbortSignal.timeout(3_000),
});
} catch { /* silently swallow */ }
});
}
function flushEvents(): void {
if (eventQueue.length === 0) return;
const batch = eventQueue;
eventQueue = [];
const body = JSON.stringify({ api_key: POSTHOG_API_KEY, batch });
fetch(POSTHOG_HOST, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": String(Buffer.byteLength(body)),
},
body,
signal: AbortSignal.timeout(3_000),
}).catch(() => { /* silently swallow */ });
}
// ── Public API ───────────────────────────────────────────────────────────
export function captureEvent(
eventName: string,
properties: Record<string, unknown> = {},
ctx?: { apiKey?: string },
): void {
if (!isTelemetryEnabled()) return;
try {
const distinctId = getDistinctId(ctx?.apiKey);
const identifyEvent = maybeBuildIdentifyEvent(distinctId);
if (identifyEvent) {
eventQueue.push(identifyEvent);
}
eventQueue.push({
event: eventName,
distinct_id: distinctId,
properties: {
source: "PI_AGENT_PLUGIN",
language: "node",
plugin_version: PLUGIN_VERSION,
node_version: process.version,
os: process.platform,
$process_person_profile: false,
$lib: "posthog-node",
...properties,
},
});
ensureFlushTimer();
ensureExitHandler();
if (eventQueue.length >= FLUSH_THRESHOLD) {
flushEvents();
}
} catch { /* silently swallow */ }
}
export function captureToolEvent(
action: string,
properties: Record<string, unknown> = {},
ctx?: { apiKey?: string },
): void {
captureEvent("pi.tool.mem0_memory", { action, ...properties }, ctx);
}
export function captureCommandEvent(
command: string,
properties: Record<string, unknown> = {},
ctx?: { apiKey?: string },
): void {
captureEvent(`pi.command.${command}`, properties, ctx);
}
// ── Test helpers ─────────────────────────────────────────────────────────
export function _getEventQueue(): Record<string, unknown>[] {
return eventQueue;
}
export function _resetForTesting(): void {
eventQueue = [];
if (flushTimer) {
clearInterval(flushTimer);
flushTimer = undefined;
}
_cachedAnonymousId = undefined;
_identifyDone = false;
}
+52
View File
@@ -0,0 +1,52 @@
export type Scope = "project" | "session" | "global";
export interface DreamConfig {
enabled: boolean;
auto: boolean;
minHours: number;
minSessions: number;
minMemories: number;
}
export interface Mem0Config {
apiKey: string;
userId: string;
autoCapture: boolean;
defaultScope: Scope;
contextInjection: boolean;
dream: DreamConfig;
}
export interface DreamState {
lastConsolidatedAt: number;
sessionsSince: number;
lastSessionId: string | null;
}
export interface DreamLock {
pid: number;
startedAt: number;
}
export interface ScopeContext {
userId: string;
appId: string;
runId: string;
}
export interface CustomCategory {
[key: string]: string;
}
export const DEFAULT_CUSTOM_CATEGORIES: CustomCategory[] = [
{ identity: "Personal details, background, and self-descriptions" },
{ preferences: "Likes, dislikes, habits, and preferred ways of doing things" },
{ goals: "Objectives, aspirations, and targets the user is working toward" },
{ projects: "Ongoing work, initiatives, and areas of focus" },
{ decisions: "Choices made, rationale, and trade-offs considered" },
{ technical: "Technical knowledge, tools, configurations, and environment details" },
{ relationships: "People, teams, organizations, and their roles" },
{ routines: "Recurring patterns, workflows, schedules, and processes" },
{ lessons: "Insights learned, mistakes to avoid, and best practices discovered" },
{ work: "Professional context, role, responsibilities, and work environment" },
];
+62
View File
@@ -0,0 +1,62 @@
import { describe, it, expect } from "vitest";
import { extractConversation } from "../src/capture/index.ts";
describe("extractConversation", () => {
it("extracts user and assistant text messages", () => {
const messages = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there!" },
];
const result = extractConversation(messages);
expect(result).toHaveLength(2);
expect(result[0]).toEqual({ role: "user", content: "Hello" });
expect(result[1]).toEqual({ role: "assistant", content: "Hi there!" });
});
it("skips assistant tool_use blocks, keeps text blocks", () => {
const messages = [
{ role: "user", content: "Search" },
{ role: "assistant", content: [{ type: "tool_use", id: "x", name: "mem0" }] },
{ role: "tool", content: "results" },
{ role: "assistant", content: "Here are the results" },
];
const result = extractConversation(messages);
expect(result).toHaveLength(2);
expect(result[0]).toEqual({ role: "user", content: "Search" });
expect(result[1]).toEqual({ role: "assistant", content: "Here are the results" });
});
it("extracts text from content arrays for both roles", () => {
const messages = [
{ role: "user", content: [{ type: "text", text: "Hello world" }] },
{ role: "assistant", content: [{ type: "text", text: "Response" }, { type: "tool_use", id: "x" }] },
];
const result = extractConversation(messages);
expect(result).toHaveLength(2);
expect(result[0].content).toBe("Hello world");
expect(result[1].content).toBe("Response");
});
it("skips tool and system messages", () => {
const messages = [
{ role: "system", content: "You are helpful" },
{ role: "user", content: "Hi" },
{ role: "tool", content: "tool output" },
];
const result = extractConversation(messages);
expect(result).toHaveLength(1);
expect(result[0]).toEqual({ role: "user", content: "Hi" });
});
it("skips assistant messages with only tool_use (no text)", () => {
const messages = [
{ role: "assistant", content: [{ type: "tool_use", id: "x", name: "bash" }] },
];
const result = extractConversation(messages);
expect(result).toHaveLength(0);
});
it("returns empty array for empty input", () => {
expect(extractConversation([])).toEqual([]);
});
});
+59
View File
@@ -0,0 +1,59 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import * as fs from "node:fs";
import { loadConfig } from "../src/config/index.ts";
vi.mock("node:fs");
describe("loadConfig", () => {
const originalEnv = process.env;
beforeEach(() => {
process.env = { ...originalEnv, HOME: "/home/testuser" };
vi.mocked(fs.existsSync).mockReturnValue(false);
});
afterEach(() => {
process.env = originalEnv;
vi.restoreAllMocks();
});
it("reads config from env vars when no config file exists", () => {
process.env.MEM0_API_KEY = "m0-test-key";
process.env.MEM0_USER_ID = "env-user";
const config = loadConfig();
expect(config.apiKey).toBe("m0-test-key");
expect(config.userId).toBe("env-user");
expect(config.autoCapture).toBe(true);
expect(config.defaultScope).toBe("project");
});
it("returns empty apiKey when no key found anywhere", () => {
delete process.env.MEM0_API_KEY;
const config = loadConfig();
expect(config.apiKey).toBe("");
});
it("reads config file and merges with defaults", () => {
delete process.env.MEM0_API_KEY;
delete process.env.MEM0_USER_ID;
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readFileSync).mockReturnValue(
JSON.stringify({ apiKey: "m0-file-key", userId: "file-user" })
);
const config = loadConfig();
expect(config.apiKey).toBe("m0-file-key");
expect(config.userId).toBe("file-user");
expect(config.dream.enabled).toBe(true);
expect(config.dream.minHours).toBe(24);
});
it("env vars override config file", () => {
process.env.MEM0_API_KEY = "m0-env-key";
vi.mocked(fs.existsSync).mockReturnValue(true);
vi.mocked(fs.readFileSync).mockReturnValue(
JSON.stringify({ apiKey: "m0-file-key" })
);
const config = loadConfig();
expect(config.apiKey).toBe("m0-env-key");
});
});
+59
View File
@@ -0,0 +1,59 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import * as fs from "node:fs";
import { checkCheapGates, checkMemoryGate } from "../src/dream/index.ts";
vi.mock("node:fs");
const STATE_DIR = "/tmp/test-mem0-dream";
describe("checkCheapGates", () => {
beforeEach(() => {
vi.mocked(fs.mkdirSync).mockReturnValue(undefined);
});
afterEach(() => {
vi.restoreAllMocks();
});
it("blocks when no state file exists (zero sessions)", () => {
vi.mocked(fs.readFileSync).mockImplementation(() => { throw new Error("ENOENT"); });
const result = checkCheapGates(STATE_DIR, {});
expect(result.proceed).toBe(false);
expect(result.reason).toContain("sessions");
});
it("blocks when consolidated recently", () => {
vi.mocked(fs.readFileSync).mockReturnValue(
JSON.stringify({ lastConsolidatedAt: Date.now() - 3_600_000, sessionsSince: 10, lastSessionId: null })
);
const result = checkCheapGates(STATE_DIR, {});
expect(result.proceed).toBe(false);
expect(result.reason).toContain("time");
});
it("blocks when not enough sessions", () => {
vi.mocked(fs.readFileSync).mockReturnValue(
JSON.stringify({ lastConsolidatedAt: Date.now() - 48 * 3_600_000, sessionsSince: 2, lastSessionId: null })
);
const result = checkCheapGates(STATE_DIR, {});
expect(result.proceed).toBe(false);
expect(result.reason).toContain("sessions");
});
it("proceeds when both gates pass", () => {
vi.mocked(fs.readFileSync).mockReturnValue(
JSON.stringify({ lastConsolidatedAt: Date.now() - 48 * 3_600_000, sessionsSince: 10, lastSessionId: null })
);
expect(checkCheapGates(STATE_DIR, {}).proceed).toBe(true);
});
});
describe("checkMemoryGate", () => {
it("blocks when too few memories", () => {
expect(checkMemoryGate(5, {}).pass).toBe(false);
});
it("passes when enough memories", () => {
expect(checkMemoryGate(25, {}).pass).toBe(true);
});
});
+47
View File
@@ -0,0 +1,47 @@
import { describe, it, expect } from "vitest";
import { formatAge, formatMemoryCompact, formatMemoryList } from "../src/memory/formatting.ts";
describe("formatAge", () => {
it("formats minutes", () => {
expect(formatAge(new Date(Date.now() - 30 * 60_000))).toBe("30m ago");
});
it("formats hours", () => {
expect(formatAge(new Date(Date.now() - 3 * 3_600_000))).toBe("3h ago");
});
it("formats days", () => {
expect(formatAge(new Date(Date.now() - 5 * 86_400_000))).toBe("5d ago");
});
});
describe("formatMemoryCompact", () => {
it("formats a memory as a single line", () => {
const mem = {
id: "abc-123-def-456",
memory: "User prefers dark mode",
categories: ["preference"],
createdAt: new Date(),
};
const line = formatMemoryCompact(mem);
expect(line).toContain("[preference]");
expect(line).toContain("User prefers dark mode");
expect(line).toContain("[mem0:abc-123-def-456]");
});
});
describe("formatMemoryList", () => {
it("formats multiple memories with numbering", () => {
const memories = [
{ id: "id-1", memory: "Fact one", categories: ["insight"], createdAt: new Date() },
{ id: "id-2", memory: "Fact two", categories: ["convention"], createdAt: new Date() },
];
const output = formatMemoryList(memories);
expect(output).toContain("1.");
expect(output).toContain("2.");
});
it("returns empty message for no memories", () => {
expect(formatMemoryList([])).toBe("No memories found.");
});
});
+47
View File
@@ -0,0 +1,47 @@
import { describe, it, expect } from "vitest";
import { resolveAddParams, resolveSearchFilters } from "../src/memory/scoping.ts";
import type { ScopeContext } from "../src/types.ts";
const ctx: ScopeContext = {
userId: "kartik",
appId: "my-project",
runId: "session-abc123",
};
describe("resolveSearchFilters", () => {
it("project scope returns user_id + app_id", () => {
expect(resolveSearchFilters("project", ctx)).toEqual({
user_id: "kartik", app_id: "my-project",
});
});
it("session scope returns user_id + app_id + run_id", () => {
expect(resolveSearchFilters("session", ctx)).toEqual({
user_id: "kartik", app_id: "my-project", run_id: "session-abc123",
});
});
it("global scope returns user_id with app_id wildcard", () => {
expect(resolveSearchFilters("global", ctx)).toEqual({
user_id: "kartik", app_id: "*",
});
});
});
describe("resolveAddParams", () => {
it("project scope returns userId + appId (camelCase)", () => {
expect(resolveAddParams("project", ctx)).toEqual({
userId: "kartik", appId: "my-project",
});
});
it("session scope includes runId", () => {
expect(resolveAddParams("session", ctx)).toEqual({
userId: "kartik", appId: "my-project", runId: "session-abc123",
});
});
it("global scope returns userId only", () => {
expect(resolveAddParams("global", ctx)).toEqual({ userId: "kartik" });
});
});
+122
View File
@@ -0,0 +1,122 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
vi.mock("node:fs", () => ({
existsSync: vi.fn().mockReturnValue(false),
readFileSync: vi.fn().mockReturnValue("{}"),
writeFileSync: vi.fn(),
mkdirSync: vi.fn(),
unlinkSync: vi.fn(),
}));
import {
captureEvent,
captureToolEvent,
captureCommandEvent,
_getEventQueue,
_resetForTesting,
} from "../src/telemetry.ts";
describe("telemetry", () => {
let fetchSpy: ReturnType<typeof vi.fn>;
beforeEach(() => {
delete process.env.MEM0_TELEMETRY;
_resetForTesting();
fetchSpy = vi.fn().mockResolvedValue({ ok: true });
vi.stubGlobal("fetch", fetchSpy);
});
afterEach(() => {
vi.restoreAllMocks();
delete process.env.MEM0_TELEMETRY;
});
it("queues an event with correct name and standard properties", () => {
captureEvent("pi.test.event", { custom: 42 });
const queue = _getEventQueue();
expect(queue).toHaveLength(1);
expect(queue[0].event).toBe("pi.test.event");
const props = queue[0].properties as Record<string, unknown>;
expect(props.source).toBe("PI_AGENT_PLUGIN");
expect(props.language).toBe("node");
expect(props.custom).toBe(42);
expect(props.$process_person_profile).toBe(false);
});
it("uses SHA-256 of apiKey as distinct_id when provided", () => {
captureEvent("test", {}, { apiKey: "m0-testkey" });
const queue = _getEventQueue();
expect(queue[0].distinct_id).toMatch(/^[a-f0-9]{64}$/);
expect(queue[0].distinct_id).not.toBe("m0-testkey");
});
it("generates a persistent anonymous id when no apiKey", () => {
captureEvent("test", {}, {});
const queue = _getEventQueue();
expect(queue[0].distinct_id).toMatch(/^pi-mem0-anon-/);
});
it("does not queue events when MEM0_TELEMETRY=false", () => {
process.env.MEM0_TELEMETRY = "false";
captureEvent("should.not.appear");
expect(_getEventQueue()).toHaveLength(0);
});
it("does not queue events when MEM0_TELEMETRY=0", () => {
process.env.MEM0_TELEMETRY = "0";
captureEvent("should.not.appear");
expect(_getEventQueue()).toHaveLength(0);
});
it("does not queue events when MEM0_TELEMETRY=off", () => {
process.env.MEM0_TELEMETRY = "off";
captureEvent("should.not.appear");
expect(_getEventQueue()).toHaveLength(0);
});
it("re-enables telemetry when env var is cleared between calls", () => {
process.env.MEM0_TELEMETRY = "false";
captureEvent("blocked");
expect(_getEventQueue()).toHaveLength(0);
delete process.env.MEM0_TELEMETRY;
captureEvent("allowed");
expect(_getEventQueue()).toHaveLength(1);
expect(_getEventQueue()[0].event).toBe("allowed");
});
it("flushes via fetch when queue reaches threshold", () => {
for (let i = 0; i < 10; i++) {
captureEvent(`event_${i}`);
}
expect(fetchSpy).toHaveBeenCalledTimes(1);
expect(_getEventQueue()).toHaveLength(0);
});
it("captureToolEvent uses pi.tool.mem0_memory event name with action property", () => {
captureToolEvent("search", { success: true, latency_ms: 42 });
const queue = _getEventQueue();
expect(queue).toHaveLength(1);
expect(queue[0].event).toBe("pi.tool.mem0_memory");
const props = queue[0].properties as Record<string, unknown>;
expect(props.action).toBe("search");
expect(props.success).toBe(true);
expect(props.latency_ms).toBe(42);
});
it("captureCommandEvent uses pi.command.<name> event name", () => {
captureCommandEvent("mem0-search", { result_count: 5 });
const queue = _getEventQueue();
expect(queue).toHaveLength(1);
expect(queue[0].event).toBe("pi.command.mem0-search");
const props = queue[0].properties as Record<string, unknown>;
expect(props.result_count).toBe(5);
});
it("never throws even if fetch throws", () => {
fetchSpy.mockRejectedValueOnce(new Error("network down"));
expect(() => {
for (let i = 0; i < 10; i++) captureEvent(`event_${i}`);
}).not.toThrow();
});
});
+61
View File
@@ -0,0 +1,61 @@
import { describe, it, expect, vi } from "vitest";
import { buildToolExecute } from "../src/memory/tools.ts";
import type { ScopeContext } from "../src/types.ts";
const mockMem0 = {
search: vi.fn(),
add: vi.fn(),
getAll: vi.fn(),
delete: vi.fn(),
deleteAll: vi.fn(),
};
const scopeCtx: ScopeContext = {
userId: "testuser",
appId: "testproject",
runId: "session123",
};
describe("buildToolExecute", () => {
const execute = buildToolExecute(mockMem0 as any, scopeCtx, "project");
it("search calls mem0.search with correct filters", async () => {
mockMem0.search.mockResolvedValue({ results: [] });
await execute({ action: "search", query: "dark mode" });
expect(mockMem0.search).toHaveBeenCalledWith("dark mode", {
filters: { user_id: "testuser", app_id: "testproject" },
});
});
it("add calls mem0.add with customCategories and entity params", async () => {
mockMem0.add.mockResolvedValue([{ id: "new-id", memory: "test" }]);
await execute({ action: "add", content: "User likes tabs" });
const call = mockMem0.add.mock.calls[0];
expect(call[0]).toEqual([{ role: "user", content: "User likes tabs" }]);
expect(call[1].userId).toBe("testuser");
expect(call[1].appId).toBe("testproject");
expect(call[1].customCategories).toBeDefined();
expect(call[1].customCategories.length).toBe(10);
});
it("search with scope=global filters by user_id with app_id wildcard", async () => {
mockMem0.search.mockResolvedValue({ results: [] });
await execute({ action: "search", query: "preferences", scope: "global" });
expect(mockMem0.search).toHaveBeenCalledWith("preferences", {
filters: { user_id: "testuser", app_id: "*" },
});
});
it("delete calls mem0.delete with full memory_id", async () => {
mockMem0.delete.mockResolvedValue({ message: "deleted" });
await execute({ action: "delete", memory_id: "abc12345-6789-0abc-def0-123456789abc" });
expect(mockMem0.delete).toHaveBeenCalledWith("abc12345-6789-0abc-def0-123456789abc");
});
it("delete passes memory_id directly to mem0.delete", async () => {
const fullId = "956e3d68-b420-4e07-a4e3-3019e7cebe6f";
mockMem0.delete.mockResolvedValue({ message: "deleted" });
await execute({ action: "delete", memory_id: fullId });
expect(mockMem0.delete).toHaveBeenCalledWith(fullId);
});
});
+24
View File
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"ignoreDeprecations": "6.0",
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"outDir": "dist",
"rootDir": "src",
"strict": true,
"types": ["node"],
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"isolatedModules": true,
"verbatimModuleSyntax": true,
"allowImportingTsExtensions": true,
"noEmit": true
},
"include": ["src"],
"exclude": ["node_modules", "dist", "**/*.test.ts"]
}
+17
View File
@@ -0,0 +1,17 @@
import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/index.ts", "src/entry.ts"],
format: ["esm"],
splitting: true,
dts: true,
sourcemap: true,
clean: true,
external: [
/^node:/,
/^@earendil-works\//,
"typebox",
"mem0ai",
/^mem0ai\//,
],
});
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
globals: true,
},
});