diff --git a/cli/CLI_SPECIFICATION.md b/cli/CLI_SPECIFICATION.md
new file mode 100644
index 000000000..a243e833c
--- /dev/null
+++ b/cli/CLI_SPECIFICATION.md
@@ -0,0 +1,1613 @@
+# mem0 CLI SDK Specification
+
+Complete reference for the mem0 CLI. This document is the authoritative guide for any developer or AI agent working on this SDK.
+
+---
+
+## Table of Contents
+
+1. [Project Overview](#1-project-overview)
+2. [Architecture](#2-architecture)
+3. [Complete Command Reference](#3-complete-command-reference)
+4. [API Endpoints](#4-api-endpoints)
+5. [Configuration](#5-configuration)
+6. [Key Behavioral Patterns](#6-key-behavioral-patterns)
+7. [Output Modes](#7-output-modes)
+8. [Agent-Friendly Design Decisions](#8-agent-friendly-design-decisions)
+9. [Adding a New Command](#9-adding-a-new-command)
+10. [Adding a New Language Implementation](#10-adding-a-new-language-implementation)
+
+---
+
+## 1. Project Overview
+
+### What is mem0 CLI?
+
+mem0 CLI is the official command-line interface for [mem0](https://mem0.ai) -- the memory layer for AI agents. It lets developers and AI agents add, search, list, update, and delete memories via the mem0 Platform API from the terminal.
+
+### Who is it for?
+
+- Developers integrating mem0 into their workflows
+- AI agents that need persistent memory (the CLI is designed with `--json`/`--agent` global flags and `help --json` specifically for machine consumption)
+- DevOps/CI pipelines that need to manage memories programmatically
+
+### Project Structure
+
+The `cli/` directory provides the mem0 CLI in two languages with a shared specification for behavioral consistency.
+
+| Language | Directory | Package Name | Install Command |
+|------------|------------|---------------|----------------------------|
+| TypeScript | `node/` | `@mem0/cli` | `npm install -g @mem0/cli` |
+| Python | `python/` | `mem0-cli` | `pip install mem0-cli` |
+
+Both implementations produce a binary named `mem0` and provide **identical CLI behavior** -- same commands, same options, same output formats, same error messages.
+
+### Version
+
+Current version: `0.1.0` (defined in `cli-spec.json`, `node/package.json`, and `python/pyproject.toml`).
+
+### License
+
+Apache-2.0
+
+---
+
+## 2. Architecture
+
+### Directory Layout
+
+```
+.
+โโโ cli-spec.json # Shared CLI specification (source of truth)
+โโโ README.md # CLI README
+โโโ SDK_SPECIFICATION.md # This file
+โโโ python/
+โ โโโ pyproject.toml # Python package config (hatchling build)
+โ โโโ README.md
+โ โโโ src/mem0_cli/
+โ โโโ __init__.py # __version__
+โ โโโ app.py # Main Typer app, command registration, helpers
+โ โโโ config.py # Config loading/saving, env var overrides
+โ โโโ branding.py # Colors, icons, banner, timed_status, print helpers
+โ โโโ output.py # Output formatting (text, json, table, quiet)
+โ โโโ backend/
+โ โ โโโ __init__.py # Re-exports get_backend
+โ โ โโโ base.py # Abstract Backend ABC, get_backend factory
+โ โ โโโ platform.py # PlatformBackend (httpx), error classes
+โ โโโ commands/
+โ โโโ memory.py # cmd_add, cmd_search, cmd_get, cmd_list, cmd_update, cmd_delete, cmd_delete_all
+โ โโโ init_cmd.py # run_init (interactive wizard)
+โ โโโ config_cmd.py # cmd_config_show, cmd_config_get, cmd_config_set
+โ โโโ entities.py # cmd_entities_list, cmd_entities_delete
+โ โโโ events_cmd.py # cmd_event_list, cmd_event_status
+โ โโโ utils.py # cmd_status, cmd_version, cmd_import
+โโโ node/
+ โโโ package.json # Node package config (tsup build)
+ โโโ README.md
+ โโโ src/
+ โโโ index.ts # Main Commander.js app, command registration, helpers
+ โโโ config.ts # Config loading/saving, env var overrides
+ โโโ branding.ts # Colors, icons, banner, timedStatus, print helpers
+ โโโ output.ts # Output formatting (text, json, table, quiet)
+ โโโ state.ts # Agent mode flag (setAgentMode, isAgentMode)
+ โโโ help.ts # Rich-style help formatter (panels, command ordering)
+ โโโ backend/
+ โ โโโ index.ts # Re-exports
+ โ โโโ base.ts # Backend interface, error classes, getBackend factory
+ โ โโโ platform.ts # PlatformBackend (native fetch), _buildFilters
+ โโโ commands/
+ โโโ memory.ts # cmdAdd, cmdSearch, cmdGet, cmdList, cmdUpdate, cmdDelete, cmdDeleteAll
+ โโโ init.ts # runInit (interactive wizard)
+ โโโ config.ts # cmdConfigShow, cmdConfigGet, cmdConfigSet
+ โโโ entities.ts # cmdEntitiesList, cmdEntitiesDelete
+ โโโ events.ts # cmdEventList, cmdEventStatus
+ โโโ utils.ts # cmdStatus, cmdVersion, cmdImport
+```
+
+### How Both CLIs Mirror Each Other
+
+Every command, option, argument, and behavioral pattern is implemented identically in both CLIs. The shared `cli-spec.json` is the source of truth for:
+
+- All command names, descriptions, and usage strings
+- All arguments and options (names, types, defaults, help text, panel grouping)
+- API endpoint paths and methods
+- Branding constants (colors, icons, logo)
+- Config schema (sections, fields, env var mappings)
+- Error messages and templates
+- Option grouping (Scope, Search, Pagination, Filters, Output, Connection)
+
+### Tech Stacks
+
+| Concern | Python | Node |
+|------------------|-------------------------------------|-----------------------------------------|
+| CLI framework | Typer >= 0.9.0 | Commander.js ^12.0.0 |
+| Rich output | Rich >= 13.0.0 | chalk ^5.3.0 + cli-table3 ^0.6.4 |
+| Spinners | Rich Status | ora ^8.0.0 |
+| Boxed panels | Rich Panel | boxen ^7.1.0 |
+| HTTP client | httpx >= 0.24.0 | Native fetch (Node >= 18) |
+| Build system | Hatchling | tsup ^8.0.0 |
+| Test framework | pytest >= 7.0 | vitest ^1.5.0 |
+| Linter | ruff >= 0.1.0 | Biome ^1.7.0 |
+| Type checking | (ruff type checks) | TypeScript ^5.4.0 |
+| Min runtime | Python >= 3.10 | Node >= 18.0.0 |
+| Module format | Standard Python package | ESM (`"type": "module"`) |
+| Entrypoint | `mem0 = "mem0_cli.app:main"` | `"bin": { "mem0": "./dist/index.js" }` |
+
+---
+
+## 3. Complete Command Reference
+
+### 3.1 `init`
+
+Interactive setup wizard for mem0 CLI.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 init [OPTIONS]` |
+| needsBackend | No |
+| needsConfig | No |
+| resolveIds | No |
+| resolveGraph | No |
+| confirmDangerous | No |
+
+**Options:**
+
+| Flag | Type | Required | Default | Help |
+|-----------------|--------|----------|---------|------|
+| `--api-key` | string | No | - | API key (skip prompt). |
+| `-u, --user-id` | string | No | - | Default user ID (skip prompt). |
+| `--email` | string | No | - | Login via email verification code. |
+| `--code` | string | No | - | Verification code (use with --email for non-interactive login). |
+| `--force` | bool | No | false | Overwrite existing config without confirmation. |
+
+**Behavior:**
+
+*Existing config protection:*
+- If `~/.mem0/config.json` exists with an API key, the CLI warns and asks for confirmation before overwriting.
+- In non-TTY mode, this is a hard error unless `--force` is passed.
+- `--force` skips the confirmation in both TTY and non-TTY modes.
+
+*Email login flow (when `--email` is provided):*
+- Sends a 6-digit verification code to the email via `POST /api/v1/auth/email_code/`.
+- If `--code` is also provided, verifies immediately (fully non-interactive).
+- If `--code` is not provided, prompts for the code interactively.
+- On success: receives API key, org_id, project_id. Saves to config. Creates account if email is new.
+- Cannot be combined with `--api-key`.
+
+*API key flow (existing behavior):*
+- If both `--api-key` and `--user-id` are provided, runs non-interactively (no prompts).
+- If running in a non-TTY without both flags, prints an error with usage hint and exits.
+- Interactive mode: prints banner, prompts for API key (masked with `*`), prompts for default user ID (default: `mem0-cli`), validates connection, saves config.
+- API key input uses raw terminal mode to echo `*` for each character typed. Supports backspace and Ctrl+U (clear line).
+
+**Examples:**
+```bash
+mem0 init
+mem0 init --api-key m0-xxx --user-id alice
+mem0 init --api-key m0-xxx --user-id alice --force
+mem0 init --email alice@company.com
+mem0 init --email alice@company.com --code 482901
+```
+
+---
+
+### 3.2 `add`
+
+Add a memory from text, messages, file, or stdin.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 add [OPTIONS]` |
+| needsBackend | Yes |
+| needsConfig | Yes |
+| resolveIds | Yes |
+| resolveGraph | Yes |
+| confirmDangerous | No |
+| Output formats | text, json, quiet |
+| Default output | text |
+| API endpoint | `POST /v1/memories/` |
+
+**Arguments:**
+
+| Name | Type | Required | Help |
+|--------|--------|----------|------|
+| `text` | string | No | Text content to add as a memory. |
+
+**Options:**
+
+| Flag | Type | Default | Panel | Help |
+|------------------|---------|---------|------------|------|
+| `-u, --user-id` | string | - | Scope | Scope to user. |
+| `--agent-id` | string | - | Scope | Scope to agent. |
+| `--app-id` | string | - | Scope | Scope to app. |
+| `--run-id` | string | - | Scope | Scope to run. |
+| `--messages` | string | - | - | Conversation messages as JSON. |
+| `-f, --file` | path | - | - | Read messages from JSON file. |
+| `-m, --metadata` | string | - | - | Custom metadata as JSON. |
+| `--immutable` | boolean | false | - | Prevent future updates. |
+| `--no-infer` | boolean | false | - | Skip inference, store raw. |
+| `--expires` | string | - | - | Expiration date (YYYY-MM-DD). |
+| `--categories` | string | - | - | Categories (JSON array or comma-separated). |
+| `--graph` | boolean | false | Scope | Enable graph memory extraction. |
+| `--no-graph` | boolean | false | Scope | Disable graph memory extraction. |
+| `-o, --output` | string | "text" | Output | Output format: text, json, quiet. |
+| `--api-key` | string | - | Connection | Override API key. |
+| `--base-url` | string | - | Connection | Override API base URL. |
+
+**Input priority:** `--file` > `--messages` > text argument > stdin (if piped and no text).
+
+**Content wrapping:** Text content is wrapped as `[{"role": "user", "content": ""}]` before sending to the API. Messages from `--messages` or `--file` are sent as-is.
+
+**Examples:**
+```bash
+mem0 add "I prefer dark mode" --user-id alice
+echo "text" | mem0 add -u alice
+mem0 add --file msgs.json -u alice -o json
+```
+
+---
+
+### 3.3 `search`
+
+Search memories by semantic query.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 search [OPTIONS]` |
+| needsBackend | Yes |
+| needsConfig | Yes |
+| resolveIds | Yes |
+| resolveGraph | Yes |
+| confirmDangerous | No |
+| Output formats | text, json, table |
+| Default output | text |
+| API endpoint | `POST /v2/memories/search/` |
+
+**Arguments:**
+
+| Name | Type | Required | Help |
+|---------|--------|----------|------|
+| `query` | string | Yes | Search query. |
+
+**Options:**
+
+| Flag | Type | Default | Panel | Help |
+|-------------------------|---------|---------|------------|------|
+| `-u, --user-id` | string | - | Scope | Filter by user. |
+| `--agent-id` | string | - | Scope | Filter by agent. |
+| `--app-id` | string | - | Scope | Filter by app. |
+| `--run-id` | string | - | Scope | Filter by run. |
+| `-k, --top-k, --limit` | integer | 10 | Search | Number of results. |
+| `--threshold` | float | 0.3 | Search | Minimum similarity score. |
+| `--rerank` | boolean | false | Search | Enable reranking (Platform only). |
+| `--keyword` | boolean | false | Search | Use keyword search. |
+| `--filter` | string | - | Search | Advanced filter expression (JSON). |
+| `--fields` | string | - | Search | Specific fields to return (comma-separated). |
+| `--graph` | boolean | false | Search | Enable graph in search. |
+| `--no-graph` | boolean | false | Search | Disable graph in search. |
+| `-o, --output` | string | "text" | Output | Output: text, json, table. |
+| `--api-key` | string | - | Connection | Override API key. |
+| `--base-url` | string | - | Connection | Override API base URL. |
+
+**Stdin fallback:** If no query argument is provided and stdin is piped, reads query from stdin.
+
+**Examples:**
+```bash
+mem0 search "preferences" --user-id alice
+mem0 search "tools" -u alice -o json -k 5
+echo "preferences" | mem0 search -u alice
+```
+
+---
+
+### 3.4 `get`
+
+Get a specific memory by ID.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 get [OPTIONS]` |
+| needsBackend | Yes |
+| needsConfig | No |
+| resolveIds | No |
+| resolveGraph | No |
+| confirmDangerous | No |
+| Output formats | text, json |
+| Default output | text |
+| API endpoint | `GET /v1/memories/{memory_id}/` |
+
+**Arguments:**
+
+| Name | Type | Required | Help |
+|-------------|--------|----------|------|
+| `memory_id` | string | Yes | Memory ID to retrieve. |
+
+**Options:**
+
+| Flag | Type | Default | Panel | Help |
+|----------------|--------|---------|------------|------|
+| `-o, --output` | string | "text" | Output | Output: text, json. |
+| `--api-key` | string | - | Connection | Override API key. |
+| `--base-url` | string | - | Connection | Override API base URL. |
+
+**Examples:**
+```bash
+mem0 get abc-123-def-456
+mem0 get abc-123-def-456 -o json
+```
+
+---
+
+### 3.5 `list`
+
+List memories with optional filters.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 list [OPTIONS]` |
+| needsBackend | Yes |
+| needsConfig | Yes |
+| resolveIds | Yes |
+| resolveGraph | Yes |
+| confirmDangerous | No |
+| Output formats | text, json, table |
+| Default output | table |
+| API endpoint | `POST /v2/memories/` |
+
+**Arguments:** None.
+
+**Options:**
+
+| Flag | Type | Default | Panel | Help |
+|------------------|---------|---------|------------|------|
+| `-u, --user-id` | string | - | Scope | Filter by user. |
+| `--agent-id` | string | - | Scope | Filter by agent. |
+| `--app-id` | string | - | Scope | Filter by app. |
+| `--run-id` | string | - | Scope | Filter by run. |
+| `--page` | integer | 1 | Pagination | Page number. |
+| `--page-size` | integer | 100 | Pagination | Results per page. |
+| `--category` | string | - | Filters | Filter by category. |
+| `--after` | string | - | Filters | Created after (YYYY-MM-DD). |
+| `--before` | string | - | Filters | Created before (YYYY-MM-DD). |
+| `--graph` | boolean | false | Filters | Enable graph in listing. |
+| `--no-graph` | boolean | false | Filters | Disable graph in listing. |
+| `-o, --output` | string | "table" | Output | Output: text, json, table. |
+| `--api-key` | string | - | Connection | Override API key. |
+| `--base-url` | string | - | Connection | Override API base URL. |
+
+**Examples:**
+```bash
+mem0 list -u alice
+mem0 list --category prefs --after 2024-01-01 -o json
+```
+
+---
+
+### 3.6 `update`
+
+Update a memory's text or metadata.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 update [text] [OPTIONS]` |
+| needsBackend | Yes |
+| needsConfig | No |
+| resolveIds | No |
+| resolveGraph | No |
+| confirmDangerous | No |
+| Output formats | text, json, quiet |
+| Default output | text |
+| API endpoint | `PUT /v1/memories/{memory_id}/` |
+
+**Arguments:**
+
+| Name | Type | Required | Help |
+|-------------|--------|----------|------|
+| `memory_id` | string | Yes | Memory ID to update. |
+| `text` | string | No | New memory text. |
+
+**Options:**
+
+| Flag | Type | Default | Panel | Help |
+|------------------|--------|---------|------------|------|
+| `-m, --metadata` | string | - | - | Update metadata (JSON). |
+| `-o, --output` | string | "text" | Output | Output: text, json, quiet. |
+| `--api-key` | string | - | Connection | Override API key. |
+| `--base-url` | string | - | Connection | Override API base URL. |
+
+**Stdin fallback:** If no text argument is provided and no `--metadata` flag is set and stdin is piped, reads text from stdin.
+
+**Examples:**
+```bash
+mem0 update abc-123 "new text"
+mem0 update abc-123 --metadata '{"key":"val"}'
+echo "new text" | mem0 update abc-123
+```
+
+---
+
+### 3.7 `delete`
+
+Delete a memory, all memories matching a scope, or an entity. This is a consolidated command with three mutually exclusive modes.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 delete [memory_id] [OPTIONS]` |
+| needsBackend | Yes |
+| needsConfig | Yes |
+| resolveIds | Yes |
+| resolveGraph | No |
+| confirmDangerous | Yes |
+| Output formats | text, json, quiet |
+| Default output | text |
+| API endpoint | `DELETE /v1/memories/{memory_id}/` (single), `DELETE /v1/memories/` (--all), `DELETE /v1/entities/` (--entity) |
+
+**Arguments:**
+
+| Name | Type | Required | Help |
+|-------------|--------|----------|------|
+| `memory_id` | string | No | Memory ID to delete (omit when using --all or --entity). |
+
+**Options:**
+
+| Flag | Type | Default | Panel | Help |
+|-----------------|---------|---------|------------|------|
+| `--all` | boolean | false | - | Delete all memories matching scope filters. |
+| `--entity` | boolean | false | - | Delete the entity itself and all its memories (cascade). |
+| `--project` | boolean | false | - | With --all: delete ALL memories project-wide. |
+| `--dry-run` | boolean | false | - | Show what would be deleted without deleting. |
+| `--force` | boolean | false | - | Skip confirmation. |
+| `-u, --user-id` | string | - | Scope | Scope to user. |
+| `--agent-id` | string | - | Scope | Scope to agent. |
+| `--app-id` | string | - | Scope | Scope to app. |
+| `--run-id` | string | - | Scope | Scope to run. |
+| `-o, --output` | string | "text" | Output | Output: text, json, quiet. |
+| `--api-key` | string | - | Connection | Override API key. |
+| `--base-url` | string | - | Connection | Override API base URL. |
+
+**Three modes (mutually exclusive):**
+
+1. **Single memory:** `mem0 delete ` -- deletes one memory by ID. Cannot combine with `--all` or `--entity`.
+2. **Bulk delete:** `mem0 delete --all [scope]` -- deletes all memories matching scope filters. Use `--project` with `--all` to wipe all memories project-wide (sends wildcard `*` entity IDs). Cannot combine with `` or `--entity`.
+3. **Entity cascade:** `mem0 delete --entity [scope]` -- deletes the entity itself and all its memories. Cannot combine with `` or `--all`.
+
+If none of ``, `--all`, or `--entity` is provided, the command prints a usage hint and exits with an error.
+
+**Dry-run behavior:**
+- Single: fetches the memory via `GET`, displays it, then prints "No changes made."
+- `--all`: lists matching memories and displays the count, then prints "No changes made."
+- `--entity`: shows the scope that would be affected without deleting.
+
+**Confirmation:** Without `--force`, prompts the user with "[y/N]" confirmation. With `--all --project`, the prompt warns about entire project wipe.
+
+**`--all --project` wildcard behavior:** Sends `DELETE /v1/memories/` with query params `user_id=*&agent_id=*&app_id=*&run_id=*`. The API typically returns an async response with a `message` field (deletion happens in background). The CLI detects this and prints "Deletion started. Memories will be removed in the background."
+
+**Examples:**
+```bash
+mem0 delete abc-123-def-456 # single memory
+mem0 delete --all -u alice --force # all memories for user
+mem0 delete --all --project --force # project-wide wipe
+mem0 delete --entity -u alice --force # entity + all its memories
+mem0 delete abc-123 --dry-run # preview single delete
+```
+
+---
+
+### 3.8 `import`
+
+Import memories from a JSON file.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 import [OPTIONS]` |
+| needsBackend | Yes |
+| needsConfig | Yes |
+| resolveIds | Yes |
+| resolveGraph | No |
+| confirmDangerous | No |
+| Output formats | text, json |
+| Default output | text |
+| API endpoint | `POST /v1/memories/` (per item) |
+
+**Arguments:**
+
+| Name | Type | Required | Help |
+|-------------|--------|----------|------|
+| `file_path` | string | Yes | JSON file to import. |
+
+**Options:**
+
+| Flag | Type | Default | Panel | Help |
+|-----------------|--------|---------|------------|------|
+| `-u, --user-id` | string | - | Scope | Override user ID. |
+| `--agent-id` | string | - | Scope | Override agent ID. |
+| `-o, --output` | string | "text" | Output | Output: text, json. |
+| `--api-key` | string | - | Connection | Override API key. |
+| `--base-url` | string | - | Connection | Override API base URL. |
+
+**File format:** JSON array (or single object) where each item has `memory`, `text`, or `content` field for the text, plus optional `user_id`, `agent_id`, and `metadata` fields.
+
+**Behavior:** Iterates through items, calling `backend.add()` for each. CLI-provided `--user-id` and `--agent-id` override per-item values. Displays progress indicator (every 10 items in Node, Rich progress bar in Python). Reports `added` and `failed` counts.
+
+**JSON output envelope:**
+```json
+{
+ "status": "success",
+ "command": "import",
+ "data": { "added": 42, "failed": 0, "duration_s": 3.14 },
+ "duration_ms": 3140
+}
+```
+
+**Examples:**
+```bash
+mem0 import data.json --user-id alice
+mem0 import data.json -u alice -o json
+```
+
+---
+
+### 3.9 `config show`
+
+Display current configuration (secrets redacted).
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 config show [OPTIONS]` |
+| needsBackend | No |
+| needsConfig | No |
+
+**Options:**
+
+| Flag | Type | Default | Help |
+|----------------|--------|---------|------|
+| `-o, --output` | string | "text" | Output: text, json. |
+
+**Behavior:** Loads config (file + env vars), displays as table (text) or JSON envelope. API keys are always redacted using `redact_key()`.
+
+**Examples:**
+```bash
+mem0 config show
+mem0 config show -o json
+```
+
+---
+
+### 3.10 `config get`
+
+Get a configuration value.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 config get ` |
+| needsBackend | No |
+| needsConfig | No |
+
+**Arguments:**
+
+| Name | Type | Required | Help |
+|-------|--------|----------|------|
+| `key` | string | Yes | Config key (e.g. `platform.api_key`). |
+
+**Valid keys:** `platform.api_key`, `platform.base_url`, `defaults.user_id`, `defaults.agent_id`, `defaults.app_id`, `defaults.run_id`, `defaults.enable_graph`.
+
+**Behavior:** Prints the value to stdout. API keys are redacted. Unknown keys print an error.
+
+**Examples:**
+```bash
+mem0 config get platform.api_key
+mem0 config get defaults.user_id
+```
+
+---
+
+### 3.11 `config set`
+
+Set a configuration value.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 config set ` |
+| needsBackend | No |
+| needsConfig | No |
+
+**Arguments:**
+
+| Name | Type | Required | Help |
+|---------|--------|----------|------|
+| `key` | string | Yes | Config key (e.g. `platform.api_key`). |
+| `value` | string | Yes | Value to set. |
+
+**Type coercion:** Boolean fields accept `true/1/yes` (case-insensitive) as true, anything else as false. Integer fields are parsed via `parseInt`. String fields are stored as-is.
+
+**Examples:**
+```bash
+mem0 config set defaults.user_id alice
+mem0 config set platform.base_url https://api.mem0.ai
+```
+
+---
+
+### 3.12 `entity list`
+
+List all entities of a given type.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 entity list ` |
+| needsBackend | Yes |
+| needsConfig | No |
+| resolveIds | No |
+| resolveGraph | No |
+| confirmDangerous | No |
+| Output formats | table, json |
+| Default output | table |
+| API endpoint | `GET /v1/entities/` |
+
+**Arguments:**
+
+| Name | Type | Required | Choices | Help |
+|---------------|--------|----------|--------------------------------|------|
+| `entity_type` | string | Yes | `users`, `agents`, `apps`, `runs` | Entity type to list. |
+
+**Behavior:** Calls `GET /v1/entities/` which returns ALL entity types, then filters client-side using the type map: `users` -> `user`, `agents` -> `agent`, `apps` -> `app`, `runs` -> `run`. Displays a table with "Name / ID" and "Created" columns.
+
+**Options:**
+
+| Flag | Type | Default | Panel | Help |
+|----------------|--------|---------|------------|------|
+| `-o, --output` | string | "table" | Output | Output: table, json. |
+| `--api-key` | string | - | Connection | Override API key. |
+| `--base-url` | string | - | Connection | Override API base URL. |
+
+**Examples:**
+```bash
+mem0 entity list users
+mem0 entity list agents -o json
+```
+
+---
+
+### 3.13 `entity delete`
+
+Delete an entity and ALL its memories (cascade). Also accessible via `mem0 delete --entity`.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 entity delete [OPTIONS]` |
+| needsBackend | Yes |
+| needsConfig | No |
+| resolveIds | No |
+| resolveGraph | No |
+| confirmDangerous | Yes |
+| Output formats | text, json, quiet |
+| Default output | text |
+| API endpoint | `DELETE /v1/entities/` |
+
+**Arguments:** None.
+
+**Options:**
+
+| Flag | Type | Default | Panel | Help |
+|-----------------|---------|---------|------------|------|
+| `-u, --user-id` | string | - | Scope | User ID. |
+| `--agent-id` | string | - | Scope | Agent ID. |
+| `--app-id` | string | - | Scope | App ID. |
+| `--run-id` | string | - | Scope | Run ID. |
+| `--dry-run` | boolean | false | - | Show what would be deleted without deleting. |
+| `--force` | boolean | false | - | Skip confirmation. |
+| `-o, --output` | string | "text" | Output | Output: text, json, quiet. |
+| `--api-key` | string | - | Connection | Override API key. |
+| `--base-url` | string | - | Connection | Override API base URL. |
+
+**Validation:** At least one entity ID is required. Errors if none provided.
+
+**Examples:**
+```bash
+mem0 entity delete --user-id alice --force
+mem0 entity delete --user-id alice --dry-run
+```
+
+---
+
+### 3.14 `event list`
+
+List recent background processing events.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 event list [OPTIONS]` |
+| needsBackend | Yes |
+| needsConfig | Yes |
+| resolveIds | No |
+| resolveGraph | No |
+| confirmDangerous | No |
+| Output formats | text (table), json |
+| Default output | table |
+| API endpoint | `GET /v1/events/` |
+
+**Options:**
+
+| Flag | Type | Default | Panel | Help |
+|----------------|--------|---------|------------|------|
+| `-o, --output` | string | "table" | Output | Output: text, json. |
+| `--api-key` | string | - | Connection | Override API key. |
+| `--base-url` | string | - | Connection | Override API base URL. |
+
+**Behavior:** Fetches all background events for the project. Displays as a table with columns: Event ID (first 8 chars), Type, Status (color-coded), Latency, Created. Status values: `PENDING` (accent), `SUCCEEDED` (green), `FAILED` (red), `PROCESSING` (yellow).
+
+**JSON output envelope:**
+```json
+{
+ "status": "success",
+ "command": "event list",
+ "count": 3,
+ "duration_ms": 87,
+ "data": [
+ { "id": "evt-abc", "event_type": "ADD", "status": "SUCCEEDED", "latency": 412.0, "created_at": "2026-01-01T10:00:00Z" }
+ ]
+}
+```
+
+**Examples:**
+```bash
+mem0 event list
+mem0 event list --output json
+```
+
+---
+
+### 3.15 `event status`
+
+Get the status and results of a specific background event.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 event status [OPTIONS]` |
+| needsBackend | Yes |
+| needsConfig | Yes |
+| resolveIds | No |
+| resolveGraph | No |
+| confirmDangerous | No |
+| Output formats | text, json |
+| Default output | text |
+| API endpoint | `GET /v1/events/{event_id}/` |
+
+**Arguments:**
+
+| Name | Type | Required | Help |
+|------------|--------|----------|------|
+| `event_id` | string | Yes | Event ID to inspect. |
+
+**Options:**
+
+| Flag | Type | Default | Panel | Help |
+|----------------|--------|---------|------------|------|
+| `-o, --output` | string | "text" | Output | Output: text, json. |
+| `--api-key` | string | - | Connection | Override API key. |
+| `--base-url` | string | - | Connection | Override API base URL. |
+
+**Behavior:** Fetches the event by ID and displays: Event ID, Type, Status (color-coded), Latency, Created, Updated, and a numbered list of result memories (event type, memory text, user_id, truncated memory ID). Displayed in a boxed panel (text) or JSON envelope.
+
+**JSON output envelope:**
+```json
+{
+ "status": "success",
+ "command": "event status",
+ "duration_ms": 65,
+ "data": {
+ "id": "evt-abc",
+ "event_type": "ADD",
+ "status": "SUCCEEDED",
+ "latency": 412.0,
+ "created_at": "2026-01-01T10:00:00Z",
+ "updated_at": "2026-01-01T10:00:01Z",
+ "results": [
+ { "id": "mem-xyz", "event": "ADD", "user_id": "alice", "memory": "User prefers dark mode" }
+ ]
+ }
+}
+```
+
+**Examples:**
+```bash
+mem0 event status evt-abc-123
+mem0 event status evt-abc-123 --output json
+```
+
+---
+
+### 3.16 `status`
+
+Check connectivity and authentication.
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 status [OPTIONS]` |
+| needsBackend | Yes |
+| needsConfig | Yes |
+| resolveIds | No |
+| resolveGraph | No |
+| confirmDangerous | No |
+
+**Options:**
+
+| Flag | Type | Default | Panel | Help |
+|----------------|--------|---------|------------|------|
+| `-o, --output` | string | "text" | Output | Output: text, json. |
+| `--api-key` | string | - | Connection | Override API key. |
+| `--base-url` | string | - | Connection | Override API base URL. |
+
+**Behavior:** Validates connectivity by calling `GET /v1/ping/`. Displays connection status in a boxed panel (text) or JSON envelope. The ping endpoint is lightweight and does not require any entity scope.
+
+**JSON output:**
+```json
+{
+ "status": "success",
+ "command": "status",
+ "duration_ms": 112,
+ "data": {
+ "connected": true,
+ "backend": "platform",
+ "base_url": "https://api.mem0.ai"
+ }
+}
+```
+
+**Examples:**
+```bash
+mem0 status
+mem0 status -o json
+```
+
+---
+
+### 3.17 `help`
+
+Show help. Use `--json` for machine-readable output (for LLM agents).
+
+| Property | Value |
+|------------------|-------|
+| Usage | `mem0 help [OPTIONS]` |
+| needsBackend | No |
+| needsConfig | No |
+
+**Options:**
+
+| Flag | Type | Default | Help |
+|----------|---------|---------|------|
+| `--json` | boolean | false | Output machine-readable JSON for LLM agents. |
+
+**Behavior:**
+- Without `--json`: prints a human-readable summary of all commands.
+- With `--json`: Node outputs the entire `cli-spec.json` file. Python outputs a hand-built JSON object describing all commands, arguments, options, and global options.
+
+**Examples:**
+```bash
+mem0 help
+mem0 help --json
+```
+
+---
+
+## 4. API Endpoints
+
+### Base URL
+
+Default: `https://api.mem0.ai` (configurable via `--base-url`, `MEM0_BASE_URL`, or `platform.base_url` in config).
+
+### Authentication
+
+All requests include the header:
+```
+Authorization: Token
+```
+
+The auth header name is `Authorization` and the scheme is `Token` (not Bearer).
+
+### Timeout
+
+30 seconds for all requests (Python: `httpx.Client(timeout=30.0)`, Node: `AbortSignal.timeout(30_000)`).
+
+### Endpoint Reference
+
+| Operation | Method | Path | Request Body | Query Params |
+|-----------------|----------|-------------------------------|------------------|-------------------------|
+| Add memory | `POST` | `/v1/memories/` | JSON payload | - |
+| Search | `POST` | `/v2/memories/search/` | JSON payload | - |
+| Get memory | `GET` | `/v1/memories/{memory_id}/` | - | - |
+| List memories | `POST` | `/v2/memories/` | JSON payload | `page`, `page_size` |
+| Update memory | `PUT` | `/v1/memories/{memory_id}/` | JSON payload | - |
+| Delete memory | `DELETE` | `/v1/memories/{memory_id}/` | - | - |
+| Delete all | `DELETE` | `/v1/memories/` | - | entity ID params |
+| List entities | `GET` | `/v1/entities/` | - | - |
+| Delete entities | `DELETE` | `/v1/entities/` | - | entity ID params |
+| List events | `GET` | `/v1/events/` | - | - |
+| Get event | `GET` | `/v1/events/{event_id}/` | - | - |
+| Ping (status) | `GET` | `/v1/ping/` | - | - |
+
+### How Filters Are Built (`_buildFilters` / `_build_filters`)
+
+Both CLIs use an identical filter-building algorithm:
+
+1. If the caller passed a pre-built filter structure containing `AND` or `OR` keys (e.g. from `--filter`), use it directly.
+2. Otherwise, build an array of AND conditions:
+ - Each entity ID becomes `{"user_id": "..."}`, `{"agent_id": "..."}`, etc.
+ - Extra filters (category, date ranges) are appended as additional conditions.
+3. If exactly 1 condition: return it directly (no wrapping).
+4. If 2+ conditions: return `{"AND": [condition1, condition2, ...]}`.
+5. If 0 conditions: return `undefined`/`None`.
+
+**Category filter format:** `{"categories": {"contains": ""}}`
+
+**Date filter format:** `{"created_at": {"gte": "YYYY-MM-DD"}}` and/or `{"created_at": {"lte": "YYYY-MM-DD"}}`. If both `after` and `before` are set, they merge into one `created_at` object: `{"created_at": {"gte": "...", "lte": "..."}}`.
+
+### How Pagination Works
+
+For the `list` command (and `search` internally):
+- `page` and `page_size` are sent as **query parameters** (not in the POST body).
+- Filters and `enable_graph` are sent in the **POST body**.
+- Default: `page=1`, `page_size=100`.
+
+### Response Normalization
+
+Both CLIs handle inconsistent API response formats:
+```
+# For search and list, the API may return:
+result = [...] # Direct array
+result = {"results": [...]} # Wrapped in results key
+result = {"memories": [...]} # Wrapped in memories key
+
+# Normalization logic (identical in both CLIs):
+if isinstance(result, list):
+ return result
+else:
+ return result.get("results", result.get("memories", []))
+```
+
+### Error Handling
+
+HTTP errors are mapped to typed exceptions:
+
+| HTTP Status | Error Class | Message Template |
+|-------------|----------------|-----------------|
+| 401 | `AuthError` | "Authentication failed. Your API key may be invalid or expired." |
+| 404 | `NotFoundError`| "Resource not found: {path}" |
+| 400 | `APIError` | "Bad request to {path}: {detail}" (detail extracted from response JSON `.detail` field) |
+| 204 | (success) | Returns `{}` (empty object) |
+| Other | Generic Error | "HTTP {status}: {statusText}" |
+
+---
+
+## 5. Configuration
+
+### Config File Location
+
+- Directory: `~/.mem0/` (created with permissions `0700`)
+- File: `~/.mem0/config.json` (written with permissions `0600`)
+
+### Config Precedence (highest to lowest)
+
+1. **CLI flags** (`--api-key`, `--base-url`, `--user-id`, etc.)
+2. **Environment variables** (`MEM0_API_KEY`, etc.)
+3. **Config file** (`~/.mem0/config.json`)
+4. **Defaults** (hardcoded)
+
+### Environment Variables
+
+| Variable | Config Path | Type | Default |
+|--------------------|--------------------------|---------|-----------------------|
+| `MEM0_API_KEY` | `platform.api_key` | string | `""` |
+| `MEM0_BASE_URL` | `platform.base_url` | string | `"https://api.mem0.ai"` |
+| `MEM0_USER_ID` | `defaults.user_id` | string | `""` |
+| `MEM0_AGENT_ID` | `defaults.agent_id` | string | `""` |
+| `MEM0_APP_ID` | `defaults.app_id` | string | `""` |
+| `MEM0_RUN_ID` | `defaults.run_id` | string | `""` |
+| `MEM0_ENABLE_GRAPH`| `defaults.enable_graph` | boolean | `false` |
+
+**Boolean parsing for `MEM0_ENABLE_GRAPH`:** Accepted truthy values are `"true"`, `"1"`, `"yes"` (case-insensitive). Everything else is `false`.
+
+### Config File JSON Schema
+
+```json
+{
+ "version": 1,
+ "defaults": {
+ "user_id": "",
+ "agent_id": "",
+ "app_id": "",
+ "run_id": "",
+ "enable_graph": false
+ },
+ "platform": {
+ "api_key": "",
+ "base_url": "https://api.mem0.ai"
+ }
+}
+```
+
+| Field | Type | Default | Description |
+|--------------------------|---------|--------------------------|-------------|
+| `version` | integer | `1` | Config schema version. |
+| `defaults.user_id` | string | `""` | Default user ID for scoping. |
+| `defaults.agent_id` | string | `""` | Default agent ID for scoping. |
+| `defaults.app_id` | string | `""` | Default app ID for scoping. |
+| `defaults.run_id` | string | `""` | Default run ID for scoping. |
+| `defaults.enable_graph` | boolean | `false` | Default graph memory extraction. |
+| `platform.api_key` | string | `""` | API key for mem0 Platform. |
+| `platform.base_url` | string | `"https://api.mem0.ai"` | Base URL for API requests. |
+
+### Config Key Map (for `config get`/`config set`)
+
+The dotted key paths map to internal config objects as follows:
+
+| Dotted Key | Section | Field |
+|-------------------------|------------|--------------|
+| `platform.api_key` | platform | apiKey / api_key |
+| `platform.base_url` | platform | baseUrl / base_url |
+| `defaults.user_id` | defaults | userId / user_id |
+| `defaults.agent_id` | defaults | agentId / agent_id |
+| `defaults.app_id` | defaults | appId / app_id |
+| `defaults.run_id` | defaults | runId / run_id |
+| `defaults.enable_graph` | defaults | enableGraph / enable_graph |
+
+### API Key Redaction
+
+The `redact_key`/`redactKey` function:
+- Empty string: returns `"(not set)"`
+- Length <= 8: returns first 2 chars + `"***"`
+- Length > 8: returns first 4 chars + `"..."` + last 4 chars
+
+---
+
+## 6. Key Behavioral Patterns
+
+These patterns are the **contract** both CLIs must follow. Any new implementation must replicate them exactly.
+
+### 6.1 Entity ID Resolution
+
+**Function:** `_resolve_ids` (Python) / `resolveIds` (Node)
+
+**Rule:** If **any** explicit entity ID is provided via CLI flags, only use the explicitly provided IDs. Do NOT mix in defaults for other entity types (which would over-filter). If **no** explicit IDs are provided, fall back to **all** configured defaults.
+
+```
+if any(user_id, agent_id, app_id, run_id):
+ # Only use what was explicitly passed; others become None
+ return {user_id or None, agent_id or None, app_id or None, run_id or None}
+else:
+ # Fall back to all configured defaults
+ return {config.user_id or None, config.agent_id or None, ...}
+```
+
+**Rationale:** If a user passes `--user-id alice` and the config also has `agent_id=bot1`, they probably want only Alice's memories, not the intersection of Alice AND bot1.
+
+### 6.2 Graph Tri-State Resolution
+
+**Rule:** `--no-graph` > `--graph` > config default.
+
+```
+if opts.no_graph: return false
+if opts.graph: return true
+return config.defaults.enable_graph
+```
+
+This is resolved in the main app file (not in the command handlers) before calling the command function.
+
+### 6.3 Category Parsing
+
+**Rule:** Try JSON parse first, fallback to comma-split.
+
+```
+if categories:
+ try:
+ cats = JSON.parse(categories) # e.g. '["a","b"]'
+ except:
+ cats = categories.split(",").map(s => s.trim()) # e.g. "a, b"
+```
+
+### 6.4 Stdin Detection
+
+**Rule:** Read from stdin if no text argument is provided AND stdin is piped (not a TTY).
+
+- `add`: If no `text`, no `--messages`, no `--file`, and stdin is piped -> read content from stdin.
+- `search`: If no `query` argument and stdin is piped -> read query from stdin.
+- `update`: If no `text` argument and no `--metadata` and stdin is piped -> read text from stdin.
+
+Detection method:
+- Python: `not sys.stdin.isatty()`
+- Node: `!process.stdin.isTTY`
+
+Reading method:
+- Python: `sys.stdin.read().strip()`
+- Node: `fs.readFileSync(0, "utf-8").trim()`
+
+### 6.5 Filter Building (`_buildFilters`)
+
+Detailed algorithm (see Section 4 for full description):
+
+1. If `extraFilters` has `AND` or `OR` key -> return it as-is (pre-built filter).
+2. Collect AND conditions from entity IDs.
+3. Append extra filters (category, date ranges).
+4. 0 conditions -> `undefined`/`None`.
+5. 1 condition -> return that single object.
+6. 2+ conditions -> `{"AND": [...]}`.
+
+### 6.6 API Response Normalization
+
+All `search` and `listMemories`/`list_memories` calls normalize the response:
+
+```
+if Array.isArray(result): return result
+return result.results ?? result.memories ?? []
+```
+
+This handles both direct array responses and wrapped `{results: [...]}` or `{memories: [...]}` formats.
+
+### 6.7 Config File Permissions
+
+- Config directory (`~/.mem0/`): created with mode `0o700` (owner read+write+execute only).
+- Config file (`~/.mem0/config.json`): written with mode `0o600` (owner read+write only).
+- Python uses `os.chmod()` with `stat.S_IRWXU` (dir) and `stat.S_IRUSR | stat.S_IWUSR` (file).
+- Node uses `fs.mkdirSync(..., { mode: 0o700 })` and `fs.chmodSync(file, 0o600)`.
+
+### 6.8 Timed Status Pattern
+
+Every API call is wrapped in a spinner + timing pattern:
+
+**Python:**
+```python
+with timed_status(err_console, "Adding memory...") as ts:
+ result = backend.add(...)
+```
+Uses Rich `Status` context manager on stderr. On success, prints `ts.success_msg` with elapsed time. On error, prints `ts.error_msg` with elapsed time.
+
+**Node:**
+```typescript
+result = await timedStatus("Adding memory...", async (ctx) => {
+ return backend.add(...);
+});
+```
+Uses `ora` spinner on stderr. On success, prints `ctx.successMsg` with elapsed time. On error, prints `ctx.errorMsg` with elapsed time.
+
+Both use `performance.now()` / `time.perf_counter()` for timing. Elapsed time is formatted as `{seconds:.2f}s`.
+
+**Key:** Spinners and timing messages always go to **stderr** so they never contaminate machine-readable stdout.
+
+### 6.9 Error Hierarchy
+
+```
+AuthError (HTTP 401) -> "Authentication failed. Your API key may be invalid or expired."
+NotFoundError (HTTP 404) -> "Resource not found: {path}"
+APIError (HTTP 400) -> "Bad request to {path}: {detail}"
+```
+
+For HTTP 400, the CLI attempts to extract a `detail` field from the JSON response body. If parsing fails, falls back to `resp.statusText`/`resp.text`.
+
+HTTP 204 is treated as success with empty body (`{}`).
+
+Any other non-OK response throws a generic error with `"HTTP {status}: {statusText}"`.
+
+### 6.10 `delete --all --project` Wildcard Behavior
+
+When `delete --all --project` is used, the CLI sends wildcard entity IDs (`user_id=*`, `agent_id=*`, `app_id=*`, `run_id=*`) to `DELETE /v1/memories/`. The API typically returns an **asynchronous response** with a `message` field (the deletion happens in the background). The CLI detects the `message` key in the response and prints "Deletion started. Memories will be removed in the background." instead of a success count.
+
+### 6.11 Non-Interactive Init
+
+When both `--api-key` and `--user-id` are provided to `mem0 init`:
+1. Sets config values directly (no prompts).
+2. Validates the platform connection.
+3. Saves config to disk.
+4. Prints success message.
+
+When running in a non-TTY (piped input) without both flags, prints an error with usage hint:
+```
+"Non-interactive terminal detected and missing required flags."
+"Usage: mem0 init --api-key --user-id "
+```
+
+### 6.12 Add Result Event Display
+
+The `format_add_result` function handles the API response from `POST /v1/memories/`:
+
+The response is either a direct array or `{results: [...]}`. Each result item has an `event` field:
+
+| Event | Icon | Label |
+|----------|------|------------|
+| `ADD` | `+` | Added |
+| `UPDATE` | `~` | Updated |
+| `DELETE` | `-` | Deleted |
+| `NOOP` | `.` | No change |
+| `PENDING`| hourglass | Queued (async) |
+
+For `PENDING` events, displays "Processing in background" with the event ID.
+
+---
+
+## 7. Output Modes
+
+### 7.1 Supported Modes Per Command
+
+All commands also support `agent` mode via the global `--json`/`--agent` flag, which wraps output in a structured JSON envelope with sanitized fields.
+
+| Command | text | json | table | quiet |
+|----------------|------|------|-------|-------|
+| add | Y | Y | - | Y |
+| search | Y | Y | Y | - |
+| get | Y | Y | - | - |
+| list | Y | Y | Y (default) | - |
+| update | Y | Y | - | Y |
+| delete | Y | Y | - | Y |
+| import | Y | Y | - | - |
+| config show | Y | Y | - | - |
+| config get | (raw value) | - | - | - |
+| config set | (success msg) | - | - | - |
+| entity list | - | Y | Y (default) | - |
+| entity delete | Y | Y | - | Y |
+| event list | Y (table) | Y | - | - |
+| event status | Y | Y | - | - |
+| status | Y | Y | - | - |
+| help | Y | Y (--json) | - | - |
+
+### 7.2 JSON Envelope Format
+
+There are two related envelope formats:
+
+**`formatJsonEnvelope`** โ used by `config show`, `status`, and `import` for `--output json`:
+
+```json
+{
+ "status": "success",
+ "command": "",
+ "duration_ms": 245,
+ "scope": {"user_id": "alice", "agent_id": null},
+ "count": 10,
+ "error": null,
+ "data": { ... }
+}
+```
+
+**`formatAgentEnvelope`** โ used by all commands in agent mode (`--json`/`--agent`). Same structure, but `data` is passed through `sanitizeAgentData(command, data)` to project only the most relevant fields:
+
+| Command | Fields in `data` |
+|---------------|-----------------|
+| add | `[{id, memory, event}]` or `[{status, event_id}]` for PENDING |
+| search | `[{id, memory, score, created_at, categories}]` |
+| list | `[{id, memory, created_at, categories}]` |
+| get | `{id, memory, created_at, updated_at, categories, metadata}` |
+| update | `{id, memory}` |
+| delete | (raw API response) |
+| entity list | `[{name, type, count}]` |
+| event list | `[{id, event_type, status, latency, created_at}]` |
+| event status | `{id, event_type, status, latency, created_at, updated_at, results: [{id, event, user_id, memory}]}` |
+| status/config/import | (pass-through) |
+
+Error envelopes (on non-zero exit):
+```json
+{
+ "status": "error",
+ "command": "",
+ "error": "Authentication failed. Your API key may be invalid or expired.",
+ "data": null
+}
+```
+
+Fields:
+- `status`: `"success"` or `"error"`.
+- `command`: The command name.
+- `duration_ms`: Optional, elapsed time in milliseconds.
+- `scope`: Optional, active entity scope (omitted if empty).
+- `count`: Optional, result count.
+- `error`: Only present when `status` is `"error"`.
+- `data`: The primary payload (sanitized in agent mode).
+
+### 7.3 Text Output
+
+- `formatMemoriesText`: Numbered list with memory text, score, ID (first 8 chars), created date, and category, separated by ` . ` in dim color.
+- `formatSingleMemory`: Boxed panel (boxen/Rich Panel) showing memory text, ID, created date, updated date, metadata, and categories.
+- `formatAddResult`: Event-based output with icons (+, ~, -, .) and labels.
+
+### 7.4 Table Output
+
+Uses `cli-table3` (Node) or `rich.table.Table` (Python) with columns:
+- ID (first 8 chars, dim)
+- Memory (truncated to 60 chars with "...")
+- Category (first category from array)
+- Created (YYYY-MM-DD)
+
+### 7.5 Quiet Mode
+
+Commands that support `--output quiet` (`add`, `update`, `delete`, `entity delete`) produce **no stdout output** in quiet mode. The operation still executes. Exit code indicates success/failure.
+
+### 7.6 Error Output
+
+- **Errors always go to stderr.** Both CLIs use a separate stderr console:
+ - Python: `Console(stderr=True)` for `print_error` calls.
+ - Node: `console.error()` in `printError`, spinner on `process.stderr` stream.
+- **Data always goes to stdout.** JSON output, table output, and text output all go to stdout.
+
+### 7.7 Unicode Symbol Degradation
+
+The `_sym`/`sym` function selects symbols based on terminal capability:
+
+| Condition | Fancy Symbol | Plain Fallback |
+|----------------------------------------|-------------|----------------|
+| `!stdout.isTTY` or `NO_COLOR` env set | - | Used |
+| Interactive TTY with color | Used | - |
+
+| Symbol | Fancy | Plain |
+|----------|-------|-----------|
+| Success | `checkmark` | `[ok]` |
+| Error | `X` | `[error]` |
+| Warning | `warning triangle` | `[warn]` |
+| Info | `diamond` | `*` |
+
+### 7.8 Result Summary Footer
+
+After list/search results, a summary line is printed in dim:
+```
+ 10 results . page 1 . user id=alice . 0.45s
+```
+
+Format: `{count} result(s) . page {n} . {scope} . {elapsed}s`
+
+### 7.9 Date Formatting
+
+All dates are normalized to `YYYY-MM-DD` format for display. The formatting handles ISO 8601 strings with `Z` timezone suffix by replacing it with `+00:00` before parsing.
+
+---
+
+## 8. Agent-Friendly Design Decisions
+
+### Why `--dry-run` exists on destructive commands
+
+The `delete` command (all modes) and `entity delete` support `--dry-run`. This lets AI agents preview the effect of a destructive operation before committing. For `delete `, it fetches the memory and displays it. For `delete --all`, it lists matching memories and shows the count. For `delete --entity` / `entity delete`, it shows the scope that would be affected.
+
+### Why `--force` exists
+
+Destructive commands (`delete --all`, `delete --entity`, `entity delete`) require interactive confirmation by default. The `--force` flag skips this confirmation, which is essential for:
+- AI agents (non-interactive)
+- CI/CD pipelines
+- Scripting
+
+### Why `--json`/`--agent` global flags exist
+
+The `--json` and `--agent` flags (aliases of each other) activate agent mode globally. When set:
+1. All output becomes a structured JSON envelope (`{status, command, duration_ms, scope, count, data}`).
+2. The `data` field is sanitized via `sanitizeAgentData` โ only the most relevant fields are included per command, reducing noise for agents parsing the output.
+3. All human-readable output (spinners, colors, banners, timing lines) is suppressed.
+4. Errors are emitted as JSON to stdout with a non-zero exit code, not to stderr as text.
+
+This is distinct from `--output json`, which returns the raw API response without sanitization.
+
+### Why `--output json` is on every command
+
+Every data-returning command supports `--output json` (or `--json` for `help`). This enables machine consumption by AI agents and scripts. JSON output goes to stdout while human-readable spinners/timing go to stderr, so piping `mem0 list -o json | jq .` works cleanly.
+
+### Why stdin is supported
+
+Commands `add`, `search`, and `update` can read from stdin when piped. This enables composability:
+```bash
+echo "I prefer dark mode" | mem0 add -u alice
+cat query.txt | mem0 search -u alice
+echo "updated text" | mem0 update abc-123
+```
+
+### Why `help --json` exists
+
+The `help --json` command outputs the complete CLI specification in machine-readable JSON. AI agents can call this once to discover all available commands, their arguments, options, and valid values -- enabling self-documenting tool use.
+
+### Why errors go to stderr
+
+All error messages, warnings, spinners, and timing information go to stderr. This means `--output json` produces **only** valid JSON on stdout, with no interleaved human-readable messages. An AI agent can safely parse stdout as JSON.
+
+---
+
+## 9. Adding a New Command
+
+Step-by-step guide for adding a new command to both CLIs.
+
+### Step 1: Add to `cli-spec.json`
+
+Add a new entry to the `commands` array with all required fields:
+
+```json
+{
+ "name": "my-command",
+ "description": "What this command does.",
+ "usage": "mem0 my-command [OPTIONS]",
+ "needsBackend": true,
+ "needsConfig": true,
+ "resolveIds": true,
+ "resolveGraph": false,
+ "confirmDangerous": false,
+ "outputFormats": ["text", "json"],
+ "defaultOutput": "text",
+ "arguments": [
+ {
+ "name": "arg",
+ "type": "string",
+ "required": true,
+ "help": "Argument description."
+ }
+ ],
+ "options": [
+ {
+ "name": "user_id",
+ "flags": ["--user-id", "-u"],
+ "type": "string",
+ "help": "Scope to user.",
+ "panel": "Scope"
+ },
+ {
+ "name": "output",
+ "flags": ["--output", "-o"],
+ "type": "string",
+ "default": "text",
+ "help": "Output format.",
+ "panel": "Output"
+ }
+ ],
+ "apiEndpoint": "myEndpoint"
+}
+```
+
+If the command calls a new API endpoint, also add it to `api.endpoints`.
+
+### Step 2: Add Backend Method (if new API endpoint)
+
+**Python** (`python/src/mem0_cli/backend/base.py` and `platform.py`):
+1. Add abstract method to `Backend` ABC in `base.py`.
+2. Implement in `PlatformBackend` in `platform.py`.
+
+**Node** (`node/src/backend/base.ts` and `platform.ts`):
+1. Add method signature to `Backend` interface in `base.ts`.
+2. Implement in `PlatformBackend` class in `platform.ts`.
+
+### Step 3: Add Command Handler
+
+**Python** (`python/src/mem0_cli/commands/`):
+Create a function `cmd_my_command(backend, ...)` in the appropriate commands file. Follow the patterns:
+- Use `timed_status(err_console, "...")` for API calls.
+- Use `print_error(err_console, ...)` for errors.
+- Use `format_json(console, ...)` for JSON output.
+- Raise `typer.Exit(1)` on errors.
+
+**Node** (`node/src/commands/`):
+Create an async function `cmdMyCommand(backend, ...)`. Follow the patterns:
+- Use `await timedStatus("...", async () => { ... })` for API calls.
+- Use `printError(...)` for errors.
+- Use `formatJson(...)` for JSON output.
+- Call `process.exit(1)` on errors.
+
+### Step 4: Register in App Entrypoint
+
+**Python** (`python/src/mem0_cli/app.py`):
+```python
+@app.command(name="my-command")
+def my_command(
+ arg: str = typer.Argument(..., help="..."),
+ output: str = typer.Option("text", "--output", "-o", help="...", rich_help_panel="Output"),
+ api_key: str | None = typer.Option(None, "--api-key", help="...", rich_help_panel="Connection"),
+ base_url: str | None = typer.Option(None, "--base-url", help="...", rich_help_panel="Connection"),
+) -> None:
+ """Command description."""
+ from mem0_cli.commands.my_module import cmd_my_command
+ backend, config = _get_backend_and_config(api_key, base_url)
+ ids = _resolve_ids(config, ...)
+ cmd_my_command(backend, arg, **ids, output=output)
+```
+
+**Node** (`node/src/index.ts`):
+```typescript
+program
+ .command("my-command ")
+ .description("Command description.")
+ .option("-o, --output ", "Output format.", "text")
+ .option("--api-key ", "Override API key.")
+ .option("--base-url ", "Override API base URL.")
+ .action(async (arg, opts) => {
+ const { cmdMyCommand } = await import("./commands/my-module.js");
+ const { backend, config } = getBackendAndConfig(opts.apiKey, opts.baseUrl);
+ const ids = resolveIds(config, opts);
+ await cmdMyCommand(backend, arg, { ...ids, output: opts.output });
+ });
+```
+
+### Step 5: Add Help Examples
+
+Both CLIs include examples in the help text:
+- Python: In the docstring of the Typer command function.
+- Node: Via `.addHelpText("after", "\nExamples:\n $ mem0 ...")`.
+
+### Step 6: Add to Help Display and Command Order
+
+**Node** (`node/src/help.ts`):
+1. Add `"my-command"` to `COMMAND_ORDER` array (determines display order in `--help`).
+2. Add option-to-panel mappings in `OPTION_PANELS["my-command"]`.
+
+**Python**: Options are assigned to panels via `rich_help_panel="..."` on each `typer.Option()`. The `help` command's `_build_help_json()` function needs a new entry.
+
+### Step 7: Add to `help` Command Output
+
+**Python** (`python/src/mem0_cli/app.py`):
+1. Add entry in `_build_help_json()` dict.
+2. Add line in the `help` command's human-readable output.
+
+**Node** (`node/src/index.ts`):
+Add line in the `help` command's human-readable output listing.
+
+### Step 8: Add Tests
+
+- Python: Add tests in `python/tests/`.
+- Node: Add tests in `node/src/__tests__/` or similar.
+
+### Step 9: Update This Specification
+
+Add the command to the Complete Command Reference (Section 3) with all arguments, options, behavior notes, and examples.
+
+---
+
+## 10. Adding a New Language Implementation
+
+To add a new language implementation (e.g., Go, Rust, Ruby), you need to replicate the exact behavioral contract defined in `cli-spec.json` and this document. Here is what is required:
+
+### 10.1 Core Modules to Implement
+
+| Module | Purpose |
+|---------------|---------|
+| **config** | Load `~/.mem0/config.json`, apply env var overrides, enforce precedence. Implement `load_config`, `save_config`, `ensure_config_dir`, `redact_key`, `get_nested_value`, `set_nested_value`. |
+| **backend/base** | Define the `Backend` interface/trait with all 8 methods: `add`, `search`, `get`, `list_memories`, `update`, `delete`, `delete_entities`, `status`, `entities`. Define error types: `AuthError`, `NotFoundError`, `APIError`. |
+| **backend/platform** | Implement `PlatformBackend` with HTTP client. Must implement `_build_filters` logic exactly. Must handle response normalization. Must set `Authorization: Token ` header. 30s timeout. |
+| **branding** | Implement print helpers (`print_success`, `print_error`, `print_warning`, `print_info`, `print_scope`), `print_banner`, `timed_status` pattern, `sym` function for Unicode degradation. Colors must match the hex values in `cli-spec.json`. |
+| **output** | Implement `format_memories_text`, `format_memories_table`, `format_single_memory`, `format_add_result`, `format_json`, `format_json_envelope`, `print_result_summary`. Date formatting to YYYY-MM-DD. ID truncation to 8 chars. Memory text truncation to 60 chars in tables. |
+| **commands/** | Implement all command handlers matching the exact behavior described in Section 3. |
+| **app/main** | CLI entrypoint with all commands registered. Implement `resolve_ids`, `resolve_graph`, stdin detection, and the `getBackendAndConfig` helper. |
+| **help** | Implement help formatter with grouped option panels (Scope, Search, Pagination, Filters, Output, Connection). Implement `help --json` output. |
+
+### 10.2 Behavioral Checklist
+
+Every new implementation MUST:
+
+- [ ] Read and respect `cli-spec.json` for all command names, descriptions, argument names, option flags, and defaults
+- [ ] Implement config precedence: CLI flags > env vars > config file > defaults
+- [ ] Implement entity ID resolution (explicit IDs only vs. all defaults)
+- [ ] Implement graph tri-state (`--no-graph` > `--graph` > config default)
+- [ ] Implement category parsing (JSON first, comma-split fallback)
+- [ ] Implement stdin detection and reading for `add`, `search`, `update`
+- [ ] Implement `_build_filters` with AND/OR structure
+- [ ] Implement response normalization (array vs `{results}` vs `{memories}`)
+- [ ] Set config directory permissions to 0700 and file to 0600
+- [ ] Implement timed status with spinner on stderr + elapsed time
+- [ ] Implement error hierarchy (AuthError 401, NotFoundError 404, APIError 400)
+- [ ] Implement `delete --all --project` with wildcard `*` entity IDs and async response handling
+- [ ] Implement non-interactive `init` when both `--api-key` and `--user-id` provided
+- [ ] Implement `--dry-run` on delete (all modes) and entity delete
+- [ ] Implement `--force` on delete --all, delete --entity, and entity delete
+- [ ] Send errors to stderr, data to stdout
+- [ ] Implement Unicode symbol degradation for non-TTY/NO_COLOR
+- [ ] Implement JSON envelope format for status, config show, import
+- [ ] Support `--output` on all data-returning commands
+- [ ] Implement `help --json` for machine-readable command discovery
+- [ ] Implement masked API key input during `init` (echo `*` per character)
+- [ ] Implement confirmation prompts for dangerous commands (unless `--force`)
+- [ ] Binary must be named `mem0`
+
+### 10.3 Package Metadata
+
+Follow the naming conventions:
+- Package description: "The official CLI for mem0 -- the memory layer for AI agents"
+- Author: `mem0.ai `
+- License: Apache-2.0
+- Keywords: `mem0`, `memory`, `ai`, `agents`, `cli`
+
+### 10.4 Testing
+
+Conformance tests should verify:
+- All commands from `cli-spec.json` are registered
+- All options from `cli-spec.json` are accepted
+- Config precedence is correct
+- Entity ID resolution matches the spec
+- Filter building produces correct structures
+- Output modes produce expected formats
+- Error codes are mapped correctly
+- Stdin reading works for supported commands
diff --git a/cli/node/package.json b/cli/node/package.json
index 62797eca5..d078066e2 100644
--- a/cli/node/package.json
+++ b/cli/node/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/cli",
- "version": "0.2.14",
+ "version": "0.2.13",
"description": "The official CLI for mem0 โ the memory layer for AI agents",
"type": "module",
"bin": {
@@ -40,7 +40,7 @@
"typescript": "^5.4.0",
"tsup": "^8.0.0",
"tsx": "^4.7.0",
- "vite": "^6.4.4",
+ "vite": "^6.0.0",
"vitest": "^4.1.11",
"@biomejs/biome": "^1.7.0",
"@types/node": "^20.0.0"
@@ -52,8 +52,7 @@
"tar-fs@>=2.0.0 <2.1.4": "^2.1.4",
"picomatch@<2.3.2": "^2.3.2",
"esbuild": ">=0.28.1",
- "postcss@<8.5.18": ">=8.5.18 <9.0.0",
- "source-map-js@<1.2.2": ">=1.2.2 <2.0.0"
+ "postcss@<8.5.18": ">=8.5.18 <9.0.0"
}
}
}
diff --git a/cli/node/pnpm-lock.yaml b/cli/node/pnpm-lock.yaml
index 50ad5a518..968075cc7 100644
--- a/cli/node/pnpm-lock.yaml
+++ b/cli/node/pnpm-lock.yaml
@@ -11,7 +11,6 @@ overrides:
picomatch@<2.3.2: ^2.3.2
esbuild: '>=0.28.1'
postcss@<8.5.18: '>=8.5.18 <9.0.0'
- source-map-js@<1.2.2: '>=1.2.2 <2.0.0'
importers:
@@ -49,11 +48,11 @@ importers:
specifier: ^5.4.0
version: 5.9.3
vite:
- specifier: ^6.4.4
- version: 6.4.5(@types/node@20.19.37)(tsx@4.21.0)
+ specifier: ^6.0.0
+ version: 6.4.3(@types/node@20.19.37)(tsx@4.21.0)
vitest:
specifier: ^4.1.11
- version: 4.1.11(@types/node@20.19.37)(vite@6.4.5(@types/node@20.19.37)(tsx@4.21.0))
+ version: 4.1.11(@types/node@20.19.37)(vite@6.4.3(@types/node@20.19.37)(tsx@4.21.0))
packages:
@@ -757,8 +756,8 @@ packages:
resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==}
engines: {node: '>=14'}
- source-map-js@1.2.2:
- resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
+ source-map-js@1.2.1:
+ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'}
source-map@0.7.6:
@@ -871,8 +870,8 @@ packages:
undici-types@6.21.0:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
- vite@6.4.5:
- resolution: {integrity: sha512-4enwjFfi4IwtEh0w+jPzpLVOFQiPHmmzPxcHXQOyEur47o6u0jE573DmGpjA+7irXoMLYRZD5ZaFUEneS3abPg==}
+ vite@6.4.3:
+ resolution: {integrity: sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==}
engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0}
hasBin: true
peerDependencies:
@@ -1196,13 +1195,13 @@ snapshots:
chai: 6.2.2
tinyrainbow: 3.1.0
- '@vitest/mocker@4.1.11(vite@6.4.5(@types/node@20.19.37)(tsx@4.21.0))':
+ '@vitest/mocker@4.1.11(vite@6.4.3(@types/node@20.19.37)(tsx@4.21.0))':
dependencies:
'@vitest/spy': 4.1.11
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
- vite: 6.4.5(@types/node@20.19.37)(tsx@4.21.0)
+ vite: 6.4.3(@types/node@20.19.37)(tsx@4.21.0)
'@vitest/pretty-format@4.1.11':
dependencies:
@@ -1453,7 +1452,7 @@ snapshots:
dependencies:
nanoid: 3.3.16
picocolors: 1.1.1
- source-map-js: 1.2.2
+ source-map-js: 1.2.1
readdirp@4.1.2: {}
@@ -1501,7 +1500,7 @@ snapshots:
signal-exit@4.1.0: {}
- source-map-js@1.2.2: {}
+ source-map-js@1.2.1: {}
source-map@0.7.6: {}
@@ -1615,7 +1614,7 @@ snapshots:
undici-types@6.21.0: {}
- vite@6.4.5(@types/node@20.19.37)(tsx@4.21.0):
+ vite@6.4.3(@types/node@20.19.37)(tsx@4.21.0):
dependencies:
esbuild: 0.28.1
fdir: 6.5.0(picomatch@4.0.4)
@@ -1628,10 +1627,10 @@ snapshots:
fsevents: 2.3.3
tsx: 4.21.0
- vitest@4.1.11(@types/node@20.19.37)(vite@6.4.5(@types/node@20.19.37)(tsx@4.21.0)):
+ vitest@4.1.11(@types/node@20.19.37)(vite@6.4.3(@types/node@20.19.37)(tsx@4.21.0)):
dependencies:
'@vitest/expect': 4.1.11
- '@vitest/mocker': 4.1.11(vite@6.4.5(@types/node@20.19.37)(tsx@4.21.0))
+ '@vitest/mocker': 4.1.11(vite@6.4.3(@types/node@20.19.37)(tsx@4.21.0))
'@vitest/pretty-format': 4.1.11
'@vitest/runner': 4.1.11
'@vitest/snapshot': 4.1.11
@@ -1648,7 +1647,7 @@ snapshots:
tinyexec: 1.2.4
tinyglobby: 0.2.15
tinyrainbow: 3.1.0
- vite: 6.4.5(@types/node@20.19.37)(tsx@4.21.0)
+ vite: 6.4.3(@types/node@20.19.37)(tsx@4.21.0)
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 20.19.37
diff --git a/cli/node/pnpm-workspace.yaml b/cli/node/pnpm-workspace.yaml
index bc1c71b28..daadb240e 100644
--- a/cli/node/pnpm-workspace.yaml
+++ b/cli/node/pnpm-workspace.yaml
@@ -12,4 +12,3 @@ overrides:
picomatch@<2.3.2: ^2.3.2
"esbuild": ">=0.28.1"
"postcss@<8.5.18": ">=8.5.18 <9.0.0"
- "source-map-js@<1.2.2": ">=1.2.2 <2.0.0"
diff --git a/cli/node/src/backend/platform.ts b/cli/node/src/backend/platform.ts
index 65a4b6228..705a3d470 100644
--- a/cli/node/src/backend/platform.ts
+++ b/cli/node/src/backend/platform.ts
@@ -31,8 +31,7 @@ export class PlatformBackend implements Backend {
this.headers = {
Authorization: `Token ${config.apiKey}`,
"Content-Type": "application/json",
- "X-Mem0-Source": "CLI",
- "X-Mem0-Client": `mem0-cli-node/${CLI_VERSION}`,
+ "X-Mem0-Source": "cli",
"X-Mem0-Client-Language": "node",
"X-Mem0-Client-Version": CLI_VERSION,
};
diff --git a/cli/python/pyproject.toml b/cli/python/pyproject.toml
index 961d2b78d..be7e72709 100644
--- a/cli/python/pyproject.toml
+++ b/cli/python/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "mem0-cli"
-version = "0.2.13"
+version = "0.2.12"
description = "The official CLI for mem0 โ the memory layer for AI agents"
readme = "README.md"
license = "Apache-2.0"
diff --git a/cli/python/src/mem0_cli/__init__.py b/cli/python/src/mem0_cli/__init__.py
index 0aeb58270..6d686291e 100644
--- a/cli/python/src/mem0_cli/__init__.py
+++ b/cli/python/src/mem0_cli/__init__.py
@@ -1,3 +1,3 @@
"""mem0 CLI โ the command-line interface for the mem0 memory layer."""
-__version__ = "0.2.13"
+__version__ = "0.2.12"
diff --git a/cli/python/src/mem0_cli/backend/platform.py b/cli/python/src/mem0_cli/backend/platform.py
index a9ce60df1..1d153da9c 100644
--- a/cli/python/src/mem0_cli/backend/platform.py
+++ b/cli/python/src/mem0_cli/backend/platform.py
@@ -27,8 +27,7 @@ class PlatformBackend(Backend):
headers={
"Authorization": f"Token {config.api_key}",
"Content-Type": "application/json",
- "X-Mem0-Source": "CLI",
- "X-Mem0-Client": f"mem0-cli-python/{__version__}",
+ "X-Mem0-Source": "cli",
"X-Mem0-Client-Language": "python",
"X-Mem0-Client-Version": __version__,
},
diff --git a/docs/api-reference/profiles/generate-profiles.mdx b/docs/api-reference/profiles/generate-profiles.mdx
deleted file mode 100644
index e5de5a12d..000000000
--- a/docs/api-reference/profiles/generate-profiles.mdx
+++ /dev/null
@@ -1,5 +0,0 @@
----
-title: 'Generate Profiles'
-description: "Start one generation: sample a few entities, or build one for a single entity."
-openapi: post /v2/profiles/jobs/
----
diff --git a/docs/api-reference/profiles/get-profile-job.mdx b/docs/api-reference/profiles/get-profile-job.mdx
deleted file mode 100644
index c24e86794..000000000
--- a/docs/api-reference/profiles/get-profile-job.mdx
+++ /dev/null
@@ -1,5 +0,0 @@
----
-title: 'Get Generation Job'
-description: "Read the progress of a generation, and whether it finished."
-openapi: get /v2/profiles/jobs/{job_id}/
----
diff --git a/docs/api-reference/profiles/get-profile-settings.mdx b/docs/api-reference/profiles/get-profile-settings.mdx
deleted file mode 100644
index 82eb1b37b..000000000
--- a/docs/api-reference/profiles/get-profile-settings.mdx
+++ /dev/null
@@ -1,5 +0,0 @@
----
-title: 'Get Profile Settings'
-description: "Retrieve the profile schema, custom instructions, and enabled flag for the current project."
-openapi: get /v2/profiles/settings/
----
diff --git a/docs/api-reference/profiles/get-profile.mdx b/docs/api-reference/profiles/get-profile.mdx
deleted file mode 100644
index 604535a3c..000000000
--- a/docs/api-reference/profiles/get-profile.mdx
+++ /dev/null
@@ -1,5 +0,0 @@
----
-title: 'Get Profile'
-description: "Retrieve the structured profile for a user, with a status describing whether generation has completed."
-openapi: get /v2/entities/{entity_type}/{entity_id}/profile/
----
diff --git a/docs/api-reference/profiles/update-profile-settings.mdx b/docs/api-reference/profiles/update-profile-settings.mdx
deleted file mode 100644
index e33dc9198..000000000
--- a/docs/api-reference/profiles/update-profile-settings.mdx
+++ /dev/null
@@ -1,5 +0,0 @@
----
-title: 'Update Profile Settings'
-description: "Set the JSON Schema, custom instructions, or enabled flag that control profile generation for the project."
-openapi: post /v2/profiles/settings/
----
diff --git a/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdx
index 14c9c014d..71fb7e1d8 100644
--- a/docs/changelog/sdk.mdx
+++ b/docs/changelog/sdk.mdx
@@ -7,36 +7,6 @@ mode: "wide"
-
-
-**Bug Fixes:**
-- **Core:** `add()` (`Memory` and `AsyncMemory`) no longer reports records the vector store rejected as successful `ADD` events. Only records that were actually inserted are written to history, entity-linked, and returned. If none of the extracted memories could be inserted, `add()` now raises `VectorStoreError` instead of returning memories that were never stored ([#7066](https://github.com/mem0ai/mem0/pull/7066))
-- **Core:** Restore the context-manager protocol on `Memory` (`with Memory() as m:`) and `AsyncMemory` (`async with AsyncMemory() as m:`), which closes the instance on exit ([#7354](https://github.com/mem0ai/mem0/pull/7354))
-- **LLMs:** The AWS Bedrock Anthropic path now returns the first Converse content block that carries text instead of always reading `content[0]`. Claude reasoning models can emit a `reasoningContent` block before the text block, which previously made the call fail with a `KeyError` ([#6369](https://github.com/mem0ai/mem0/pull/6369))
-- **Vector Stores:** Turbopuffer filters now apply every operator (`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`). Only `gte` and `lte` were read before, so any other operator was silently dropped and the query returned unfiltered results. An unsupported operator now raises `ValueError` ([#6564](https://github.com/mem0ai/mem0/pull/6564))
-- **Vector Stores:** Turbopuffer `search()` scores now respect `distance_metric`. With `euclidean_squared`, the unbounded squared distance maps to `1 / (1 + distance)` instead of `1 - distance`, which went negative and inverted ranking for any distance above 1 ([#6559](https://github.com/mem0ai/mem0/pull/6559))
-- **Vector Stores:** S3 Vectors `search()` scores are now metric-aware. With `euclidean`, the distance maps to `1 / (1 + distance)` instead of `max(0, 1 - distance)`, which collapsed most scores to 0 ([#6547](https://github.com/mem0ai/mem0/pull/6547))
-
-
-
-
-
-**New Features:**
-- **Client:** Add User Profiles to `MemoryClient` and `AsyncMemoryClient`: `get_profile()`, `generate_profile()`, `get_profile_settings()`, `update_profile_settings()`, `sample_profiles()`, and `get_profile_job()`. A profile is a structured, always-current JSON summary of one user, shaped by a JSON Schema you configure per project and filled by an LLM from that user's memories. Generation is asynchronous. Every job POST carries an `Idempotency-Key`; to retry a lost request without starting a second job, pass the same `idempotency_key` on each attempt ([#7340](https://github.com/mem0ai/mem0/pull/7340))
-
-**Bug Fixes:**
-- **Vector Stores:** Guard against `None` timestamps in the Valkey vector store's `insert()` and `update()` paths. `created_at` and `updated_at` fields that were present in the payload but set to `None` previously passed the `"created_at" not in payload` / `"updated_at" in payload` checks and raised `TypeError` when `datetime.fromisoformat()` received `None`. Both paths now use `.get()` with a truthiness check so `None` values fall through to the default, matching the Redis provider's behavior ([#6993](https://github.com/mem0ai/mem0/pull/6993))
-
-
-
-
-
-**Improvements:**
-- **Client:** Requests now carry three surface-identity headers so the platform can tell which product made a call. `X-Mem0-Source` names the surface and `X-Application` the host app it runs inside, both set-once so a wrapper that already declared its identity keeps it. `X-Mem0-Client` is append-only and carries `name/version` per layer, outermost first, so a plugin calling this SDK reports the whole chain rather than only the last speaker. `MEM0_SOURCE`, `MEM0_APPLICATION` and `MEM0_CLIENT_STACK` set them from the environment for wrappers that cannot pass options ([#7326](https://github.com/mem0ai/mem0/pull/7326))
-- **Client:** The client stack is bounded by dropping whole entries rather than slicing characters, and this SDK's own entry is the reserved one. Truncating the joined string could sever an identifier mid-name and the platform parsed the fragment as a real client ([#7326](https://github.com/mem0ai/mem0/pull/7326))
-
-
-
**Improvements:**
@@ -204,7 +174,7 @@ mode: "wide"
**New Features:**
-- **Embeddings:** Add native `embed_batch` to five embedders for batched embedding requests: LM Studio, Together, HuggingFace, Vertex AI, and Google GenAI ([#5609](https://github.com/mem0ai/mem0/pull/5609))
+- **Embeddings:** Add native `embed_batch` to five embedders: LM Studio, Together, HuggingFace, Vertex AI, and Google GenAI: for batched embedding requests ([#5609](https://github.com/mem0ai/mem0/pull/5609))
**Bug Fixes:**
- **Core:** Guard against malformed `image_url` entries in `parse_vision_messages` to prevent crashes ([#5631](https://github.com/mem0ai/mem0/pull/5631))
@@ -994,7 +964,7 @@ See the [OSS v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-
**New Features:**
- **OpenMemory:** Added OpenMemory support
- **Neo4j:** Added weights to Neo4j model
-- **AWS:** Added support for OpenSearch Serverless
+- **AWS:** Added support for Opsearch Serverless
- **Examples:** Added ElizaOS Example
**Improvements:**
@@ -1257,31 +1227,6 @@ See the [OSS v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-
-
-
-**Bug Fixes:**
-- **Config (OSS):** `ConfigManager` no longer injects OpenAI's default `baseURL` and `model` into non-OpenAI LLM providers. The defaults now apply only to `openai` and `openai_structured`, so a DeepSeek, xAI, or other provider config without an explicit `baseURL` or `model` falls back to that provider's own defaults and env vars (`DEEPSEEK_API_BASE`, `XAI_API_BASE`, ...) instead of pointing at OpenAI with an OpenAI model name ([#7350](https://github.com/mem0ai/mem0/pull/7350))
-- **Vector Stores:** Turbopuffer filters now apply every operator (`eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`). Only the range operators were read before, so `eq`, `ne`, `in`, and `nin` were silently dropped. A `"*"` value now matches anything instead of nothing, an array value is treated as `in`, and an unsupported operator throws ([#6578](https://github.com/mem0ai/mem0/pull/6578))
-- **Vector Stores:** Turbopuffer `search()` with `euclidean_squared` now maps the unbounded squared distance to `1 / (1 + distance)` instead of `1 - distance`, which went negative and inverted ranking for any distance above 1 ([#6580](https://github.com/mem0ai/mem0/pull/6580))
-- **Packaging:** `pg`, `@types/pg`, and `natural` are now optional peer dependencies, and `pg` / `@types/pg` accept caret ranges instead of the exact `8.11.3` / `8.11.0` pins, so installing `mem0ai` no longer pulls in `pg` or conflicts with an app's own `pg` version. The PGVector store now imports `pg` only when it is used, so install it alongside `mem0ai` (`npm install pg`) if you use that store. `@types/jest` moved from peer dependencies to dev dependencies ([#7450](https://github.com/mem0ai/mem0/pull/7450))
-
-
-
-
-
-**New Features:**
-- **Client:** Add User Profiles to `MemoryClient`: `getProfile()`, `generateProfile()`, `getProfileSettings()`, `updateProfileSettings()`, `sampleProfiles()`, and `getProfileJob()`. A profile is a structured, always-current JSON summary of one user, shaped by a JSON Schema you configure per project and filled by an LLM from that user's memories. Generation is asynchronous. Every job POST carries an `Idempotency-Key`; to retry a lost request without starting a second job, pass the same `idempotencyKey` on each attempt ([#7340](https://github.com/mem0ai/mem0/pull/7340))
-
-
-
-
-
-**Improvements:**
-- **Client:** Requests now carry `X-Mem0-Source`, `X-Application` and `X-Mem0-Client`, matching the Python SDK. The first two are set-once so an outer wrapper keeps its identity; the third is append-only and reports the whole layer chain. Read from `MEM0_SOURCE`, `MEM0_APPLICATION` and `MEM0_CLIENT_STACK` when set ([#7326](https://github.com/mem0ai/mem0/pull/7326))
-- **Client:** The SDK version in `X-Mem0-Client` is injected at build time rather than hardcoded, so it cannot go stale at the next release ([#7326](https://github.com/mem0ai/mem0/pull/7326))
-
-
-
**Improvements:**
@@ -1919,13 +1864,6 @@ See the [OSS v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-
-
-
-**Improvements:**
-- **Client:** Requests now carry the three surface-identity headers (`X-Mem0-Source`, `X-Application`, `X-Mem0-Client`) introduced in the Python and TypeScript SDKs, so the platform can attribute calls made through the CLI to the correct surface and version ([#7326](https://github.com/mem0ai/mem0/pull/7326))
-
-
-
**New Features:**
@@ -2138,7 +2076,7 @@ A full-featured command-line interface for Mem0, available in both Python and No
- New Git repository writes use a hash of the remote identity in `agent_id`. Search and explicit shared-memory deletion include both current and legacy repository IDs within the repository's `app_id`. Existing memories are not rewritten. Legacy IDs retain their original ambiguity for matching owner/repository names on different Git hosts.
**Packaging:**
-- Claude Code, Cursor, Codex, Kimi, Antigravity, and the portable Python bundle are versioned at `0.3.1`. OpenCode and DeepSeek Harness are `0.3.0`; Pi Agent is `0.3.0`; OpenClaw is `1.1.0`. Each host's changes and upgrade considerations are listed in its tab.
+- Claude Code, Cursor, Codex, Kimi, Antigravity, and the portable Python bundle are versioned at `0.3.1`. OpenCode, Pi Agent, and DeepSeek Harness are `0.3.0`; OpenClaw is `1.1.0`. Each host's changes and upgrade considerations are listed in its tab.
- Python and TypeScript CI run their respective runtime suites. Package checks build the installable artifacts, check generated-file consistency, and reject TypeScript output that still imports monorepo source.
[#7203](https://github.com/mem0ai/mem0/pull/7203)
@@ -2433,25 +2371,9 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex
-
+
-**Improvements:**
-- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Sidekick:** Sidekick searches memories when earlier sessions could help, instead of before every answer ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-
-
-
-
-
-**Improvements:**
-- **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373))
-- **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
-
-**Changes:**
-- **Sidekick:** Sidekick is now available only in Claude Code, with Sonnet, worktree isolation, and parent memories.
+Sidekick is now available only in Claude Code, with Sonnet, worktree isolation, and parent memories.
@@ -2474,24 +2396,9 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex
-
+
-**Improvements:**
-- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-
-
-
-
-
-**Improvements:**
-- **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373))
-- **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
-
-**Changes:**
-- **Sidekick:** Removes Sidekick and its start/stop hooks. Memory capture, search, and six skills remain available.
+Removes Sidekick and its start/stop hooks. Memory capture, search, and six skills remain available.
@@ -2514,24 +2421,9 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex
-
+
-**Improvements:**
-- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-
-
-
-
-
-**Improvements:**
-- **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373))
-- **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
-
-**Changes:**
-- **Sidekick:** Renames shared tracking to use subagent terminology. Native subagent memory support remains available.
+Renames shared tracking to use subagent terminology. Native subagent memory support remains available.
@@ -2551,25 +2443,32 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex
+
+
+
+
+Sidekick is available only in Claude Code, not in the portable package.
+
+
+
+
+
+**Added:**
+- One portable package at `integrations/mem0-agent-plugin/`, using the Agent Plugins 1.0.0 root `plugin.json`, `mcp.json`, and fixed `skills/` locations.
+- Ships a local, read-only `search_memories` server and the six shared memory skills. Uses `PLUGIN_ROOT` for bundled files and `PLUGIN_DATA` for persistent plugin state; all package files remain inside the installable directory.
+
+**Packaging:**
+- Generated from the shared Python runtime and skill templates. Builds validate the manifest, MCP configuration, skills, and generated-file consistency.
+- Host lifecycle hooks and native Sidekick declarations remain in the native plugin packages; the portable package does not provide automatic lifecycle capture or host-specific subagent isolation. Its bundled remember skill cannot persist a new memory on its own because the portable package has no capture hooks or write tool.
+
+[#7203](https://github.com/mem0ai/mem0/pull/7203)
+
+
+
+
+
-
-
-**Improvements:**
-- **Search:** The `search_memories` tool description no longer asks the agent to search proactively or to run several searches for multi-part questions. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, the same wording as the other coding-agent plugins ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Session context:** Removed two system-context lines that told the agent to run 2 parallel searches before responding and 2-4 parallel searches for non-trivial tasks ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Skills:** `/mem0-search` and `/mem0-context-loader` make one `search_memories` call instead of 2 and 2-4 parallel calls. `/mem0-context-loader` now uses the search skill description from the other coding-agent plugins instead of asking to load at every new task or context switch ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-
-
-
-
-
-**Changes:**
-- **Telemetry:** The PostHog `source` tag changed from the literal `"plugin"` to `OPENCODE_PLUGIN`, and `project_hash` is now salted. Saved PostHog insights filtering on `source = "plugin"` will stop matching new events; historical data is unaffected ([#7322](https://github.com/mem0ai/mem0/pull/7322))
-- **Config:** A new `keyFingerprint` key appears in the install-count deduplication logic; installs are now counted once per key rather than on every activation ([#7325](https://github.com/mem0ai/mem0/pull/7325))
-
-
-
**Changed:**
@@ -2668,24 +2567,9 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex
-
+
-**Improvements:**
-- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-
-
-
-
-
-**Improvements:**
-- **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373))
-- **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
-
-**Changes:**
-- **Sidekick:** Removes Sidekick. Memory capture, search, and six skills remain available.
+Removes Sidekick. Memory capture, search, and six skills remain available.
@@ -2781,24 +2665,9 @@ Existing memories written by the previous versions are not rewritten. If your me
-
+
-**Improvements:**
-- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-
-
-
-
-
-**Improvements:**
-- **Telemetry:** `PLUGIN_VERSION` bumped to `0.3.2`. The `mem0-plugin/` wire header and `plugin_version` telemetry field now reflect the fixes from #7322 through #7358 ([#7373](https://github.com/mem0ai/mem0/pull/7373))
-- **Telemetry:** Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
-
-**Changes:**
-- **Sidekick:** Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skills remain available.
+Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skills remain available.
@@ -2836,21 +2705,6 @@ Existing memories written by the previous versions are not rewritten. If your me
-
-
-**Improvements:**
-- **Search:** The `memory_search` tool description no longer asks the agent to search proactively or to run several searches for multi-part questions. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help. Recall strategies (`smart`, `always`, `manual`) are unchanged ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-
-
-
-
-
-**Changes:**
-- **Config:** Added `keyFingerprint` to the config schema for install-count deduplication; installs are now counted once per key rather than on every activation ([#7325](https://github.com/mem0ai/mem0/pull/7325))
-- **Telemetry:** Events are no longer delivered twice, and the `plugin_version` field now reflects the plugin that produced the event ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
-
-
-
**Changed:**
@@ -3139,22 +2993,6 @@ Existing memories written by the previous versions are not rewritten. If your me
-
-
-**Improvements:**
-- **Search:** The memory policy, `mem0_memory` tool description, and prompt guidelines no longer ask the agent to search before answering anything that may depend on earlier context or to run several searches per question. They now ask for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Skills:** `context-loader` makes one search instead of 2-4 parallel searches, and uses the search skill description from the other coding-agent plugins ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Automatic recall:** Injected memories are introduced as "Mem0 found these relevant memories from earlier work in this repository:", the same heading as the Python plugins. The old heading called them a shallow first pass and told the agent to search again ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-
-
-
-
-
-**Improvements:**
-- **Telemetry:** Events are no longer delivered twice, no longer lose parked events, and now attribute each event to the plugin that produced it. The `plugin_version` wire field reflects the fixed release ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
-
-
-
**Changed:**
@@ -3268,21 +3106,6 @@ Existing memories written by the previous versions are not rewritten. If your me
-
-
-**Improvements:**
-- **Search:** The `search_memory` tool description no longer asks the agent to search proactively before answering anything that may depend on earlier context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-- **Automatic recall:** Injected memories are introduced as "Mem0 found these relevant memories from earlier work:". The old heading called them a shallow first pass and told the agent to search again with `mem0_memory`, a tool DeepSeek does not have ([#7420](https://github.com/mem0ai/mem0/pull/7420))
-
-
-
-
-
-**Improvements:**
-- **Telemetry:** Rebuild with the fixed shared telemetry core from `agent-plugin-core`. Events are no longer delivered twice, no longer lose parked events on flush, and now attribute each event to the plugin that produced it ([#7323](https://github.com/mem0ai/mem0/pull/7323), [#7324](https://github.com/mem0ai/mem0/pull/7324), [#7358](https://github.com/mem0ai/mem0/pull/7358))
-
-
-
**Added:**
@@ -3327,13 +3150,6 @@ Existing memories written by the previous versions are not rewritten. If your me
-
-
-**Improvements:**
-- **Client:** Inherits the three surface-identity headers (`X-Mem0-Source`, `X-Application`, `X-Mem0-Client`) from the TypeScript SDK bump, so platform calls made through the Vercel AI SDK provider are now correctly attributed ([#7326](https://github.com/mem0ai/mem0/pull/7326))
-
-
-
**Security:**
diff --git a/docs/components/embedders/models/together.mdx b/docs/components/embedders/models/together.mdx
index a71c1764a..75f44227e 100644
--- a/docs/components/embedders/models/together.mdx
+++ b/docs/components/embedders/models/together.mdx
@@ -11,7 +11,7 @@ To use Together embedding models, set the `TOGETHER_API_KEY` environment variabl
The `embedding_model_dims` parameter for `vector_store` should be set to `1024` for Together embedder.
-**Breaking default change.** The default Together embedding model is now `intfloat/multilingual-e5-large-instruct` (**1024-dim**), replacing the previous default `togethercomputer/m2-bert-80M-8k-retrieval` (**768-dim**). If you created a self-hosted vector store with the old default, its collection is 768-dim and will reject the new 1024-dim vectors โ **recreate/reindex the collection at 1024 dimensions** after upgrading. To defer the change, pin the previous values explicitly (`model="togethercomputer/m2-bert-80M-8k-retrieval"`, `embedding_dims=768`) โ note Together no longer lists this model among its recommended embeddings, so reindexing at 1024 is the durable path.
+**Breaking default change.** The default Together embedding model is now `intfloat/multilingual-e5-large-instruct` (**1024-dim**), replacing the previous default `togethercomputer/m2-bert-80M-8k-retrieval` (**768-dim**). If you created a self-hosted vector store with the old default, its collection is 768-dim and will reject the new 1024-dim vectors **recreate/reindex the collection at 1024 dimensions** after upgrading. To defer the change, pin the previous values explicitly (`model="togethercomputer/m2-bert-80M-8k-retrieval"`, `embedding_dims=768`) note Together no longer lists this model among its recommended embeddings, so reindexing at 1024 is the durable path.
diff --git a/docs/components/vectordbs/dbs/azure.mdx b/docs/components/vectordbs/dbs/azure.mdx
index 8577b50cc..93a0bf4ad 100644
--- a/docs/components/vectordbs/dbs/azure.mdx
+++ b/docs/components/vectordbs/dbs/azure.mdx
@@ -95,7 +95,7 @@ Uses the identity from Azure PowerShell (`Connect-AzAccount`).
7. **Azure Developer CLI Credential:**
Uses the session from Azure Developer CLI (`azd auth login`).
- If an API key is provided, it will be used for authentication over an Azure Identity
+ If an API is provided, it will be used for authentication over an Azure Identity
To enable Role-Based Access Control (RBAC) for Azure AI Search, follow these steps:
1. In the Azure Portal, navigate to your **Azure AI Search** service.
diff --git a/docs/components/vectordbs/dbs/pgvector.mdx b/docs/components/vectordbs/dbs/pgvector.mdx
index ddd36c416..f322a0a95 100644
--- a/docs/components/vectordbs/dbs/pgvector.mdx
+++ b/docs/components/vectordbs/dbs/pgvector.mdx
@@ -5,12 +5,6 @@ description: "Use pgvector as a vector store in Mem0 for PostgreSQL-based vector
[pgvector](https://github.com/pgvector/pgvector) is an open-source vector similarity search extension for Postgres. After connecting to Postgres, run `CREATE EXTENSION IF NOT EXISTS vector;` to create the vector extension.
-The TypeScript SDK loads the `pg` driver only when you use this store, so install it alongside `mem0ai`:
-
-```bash
-npm install pg
-```
-
### Usage
diff --git a/docs/components/vectordbs/dbs/pinecone.mdx b/docs/components/vectordbs/dbs/pinecone.mdx
index 1cd06b592..31662ed29 100644
--- a/docs/components/vectordbs/dbs/pinecone.mdx
+++ b/docs/components/vectordbs/dbs/pinecone.mdx
@@ -94,7 +94,6 @@ Here are the parameters available for configuring Pinecone:
| `hybrid_search` | Whether to enable hybrid search | `False` |
| `metric` | Distance metric for vector similarity | `"cosine"` |
| `batch_size` | Batch size for operations | `100` |
-| `extra_params` | Additional keyword arguments passed to the `Pinecone` client constructor. Ignored when `client` is supplied. | `None` |
| `namespace` | Namespace for the collection, useful for multi-tenancy. | `None` |
diff --git a/docs/cookbooks/integrations/healthcare-google-adk.mdx b/docs/cookbooks/integrations/healthcare-google-adk.mdx
index 9c9571a66..0696f45e5 100644
--- a/docs/cookbooks/integrations/healthcare-google-adk.mdx
+++ b/docs/cookbooks/integrations/healthcare-google-adk.mdx
@@ -30,7 +30,7 @@ pip install google-adk mem0ai python-dotenv
## Code Breakdown
-Let's get started and understand the different components required in building a healthcare assistant powered by memory.
+Let's get started and understand the different components required in building a healthcare assistant powered by memory
```python
# Import dependencies
diff --git a/docs/cookbooks/integrations/supabase.mdx b/docs/cookbooks/integrations/supabase.mdx
deleted file mode 100644
index 60b102324..000000000
--- a/docs/cookbooks/integrations/supabase.mdx
+++ /dev/null
@@ -1,388 +0,0 @@
----
-title: Build a Company Brain with Mem0 Platform and Supabase
-description: "Build a shared company brain using Mem0 Platform as the managed memory layer, Supabase as your system of record, and the Mem0 MCP server."
----
-
-
-**Uses:** Mem0 **Platform** (`MemoryClient`) ยท **System of record:** Supabase (Postgres + Auth) ยท **Access layer:** the hosted Mem0 MCP server. **You'll build:** a company brain your whole org (and every agent) writes to and queries, ending with a new-hire onboarding demo.
-
-
-Companies lose knowledge constantly: why you picked Postgres over Mongo, who owns billing, the deploy rule only one engineer remembers. A **company brain** captures this and answers questions about it, for every employee and every agent, and keeps it after people leave.
-
-We'll build one on **Mem0 Platform** (the managed memory layer, so there's no vector DB to run) with **Supabase as the system of record** (where your employees, teams, and source documents actually live) and the **Mem0 MCP server** as the wire that lets Claude Code, Cursor, or a Slack bot all reach the same brain.
-
-
-**How Platform and Supabase divide the work.** Mem0 Platform manages storage and extraction server-side, you do **not** point it at your own database. Supabase is your app's source of truth and identity provider; we *ingest* knowledge from Supabase into the brain and use Supabase Auth to decide who's asking. (If you want to self-host the vector store instead, that's the OSS path, see the [Supabase vector store reference](/components/vectordbs/dbs/supabase).)
-
-
-## Architecture
-
-```mermaid
-flowchart LR
- subgraph SB["Supabase: system of record"]
- K[(knowledge / employees / teams)]
- AU[Auth ยท who is asking]
- end
- subgraph M0["Mem0 Platform: the brain"]
- B[(managed memory)]
- end
- K -->|ingest| B
- AU -->|maps to scope| B
- CC[Claude Code] --> MCP[Mem0 MCP server]
- CU[Cursor] --> MCP
- SL[Slack bot] --> MCP
- MCP --> B
-```
-
-Memory splits by entity. An individual is a **`user_id`** (their Supabase Auth id). Shared knowledge lives on an **`agent_id`**: the company-wide brain is `org:acme`, and each team is its own agent, e.g. `team:payments`. A person's own facts route to their `user_id`; company and team facts route to the agent. This split is what lets one search return "my" context alongside the shared org knowledge.
-
-## Prerequisites
-
-- **Python 3.9+**
-- A **Mem0 Platform API key**, [app.mem0.ai/dashboard/api-keys](https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=cookbook-company-brain). (Platform runs extraction and embeddings for you, so there's no OpenAI key to manage.)
-- A **Supabase** project, [supabase.com](https://supabase.com)
-
-About 20 minutes.
-
----
-
-## Step 1: Get your Mem0 Platform API key
-
-Sign in at [app.mem0.ai](https://app.mem0.ai) and copy a key from **Dashboard โ API Keys**. The key is scoped to your org and project; Mem0 resolves both server-side, so you never pass IDs by hand.
-
-## Step 2: Create the Supabase system of record
-
-In the Supabase **SQL editor**, create the tables your company already thinks in: people, teams, and a `knowledge` table the brain will ingest from. Identity reuses Supabase Auth's built-in `auth.users`.
-
-```sql
--- Employees extend Supabase Auth's users; identity is auth.users.id (uuid)
-create table public.employees (
- id uuid primary key references auth.users (id) on delete cascade,
- name text not null,
- team text not null
-);
-
--- The company knowledge the brain ingests. `scope` decides who can recall it.
-create table public.knowledge (
- id bigint generated always as identity primary key,
- scope text not null, -- the shared agent this belongs to: 'org:acme' | 'team:payments'
- content text not null,
- author uuid references auth.users (id), -- who recorded it (their user_id); null for org seed data
- created_at timestamptz default now(),
- mem0_synced_at timestamptz -- null until ingested into the brain
-);
-create index on public.knowledge (mem0_synced_at, created_at);
-
--- Seed a little company knowledge to ingest.
-insert into public.knowledge (scope, content) values
- ('org:acme', 'We chose Postgres over MongoDB for the core product for strong transactional guarantees and relational joins.'),
- ('org:acme', 'All production deploys go out Tuesday and Thursday; never on Fridays.'),
- ('org:acme', 'Customer data must stay in the EU region for GDPR compliance.'),
- ('org:acme', 'Billing is owned by the Payments team, and Alice is the Payments tech lead.'),
- ('team:payments', 'Stripe is our processor; webhooks are verified with PAYMENTS_WEBHOOK_SECRET.');
-```
-
-Grab your project URL and **service-role** key from **Settings โ API** (the ingestion job runs server-side and needs to read every scope).
-
-## Step 3: Project setup
-
-```bash
-mkdir company-brain && cd company-brain
-pip install "mem0ai>=2.0.17" supabase requests # 2.0.17+ for agent_custom_instructions
-```
-
-```bash
-export MEM0_API_KEY="m0-..."
-export SUPABASE_URL="https://.supabase.co"
-export SUPABASE_SERVICE_KEY=""
-```
-
-## Step 4: Configure the brain
-
-Create **`brain.py`**. This constructs the Platform client and teaches it what to remember. The key is the **two** instruction sets: `custom_instructions` governs a person's own (`user_id`) memories, and `agent_custom_instructions` governs shared (`agent_id`) memories, phrased in the third person so company facts read "The companyโฆ", not "The user's organizationโฆ". `custom_categories` files each memory under a useful label.
-
-```python
-# brain.py
-import os
-from mem0 import MemoryClient
-
-client = MemoryClient(api_key=os.environ["MEM0_API_KEY"])
-
-# Steer extraction (project-wide). Runs server-side; no LLM key needed here.
-client.project.update(
- # Governs a person's OWN memories (user_id).
- custom_instructions=(
- "Extract the individual's own durable preferences, context, and how they work. "
- "Ignore greetings and one-off chatter."
- ),
- # Governs SHARED memories (agent_id); write them in the third person.
- agent_custom_instructions=(
- "Extract durable company/team knowledge in the third person "
- "(\"The company...\", \"The team...\"): decisions and their rationale, ownership "
- "(who owns what), processes, policies, tooling choices, and gotchas. "
- "Ignore greetings, scheduling, and one-off chatter."
- ),
- custom_categories=[
- {"decision": "Architectural or product decisions and why they were made"},
- {"ownership": "Who owns a system, service, or process"},
- {"policy": "Compliance, security, and process rules"},
- {"tooling": "Tools, services, and how they're configured"},
- ],
-)
-
-# Scopes. A person is a user_id; shared brains are agent_ids.
-COMPANY = "org:acme" # agent_id: company-wide shared brain
-def team(name): return f"team:{name}" # agent_id: a team's shared brain
-def person(uid): return uid # user_id: an individual (Supabase auth id)
-```
-
-Run it once to apply the project settings:
-
-```bash
-python -c "import brain; print('brain configured')"
-```
-
-
-## Step 5: Ingest company knowledge from Supabase
-
-This is where Supabase and the brain connect. Create **`ingest.py`**: read un-synced rows from `knowledge`, add each to the Platform brain under its scope, then mark it synced. Platform `add()` is **asynchronous**, it returns an `event_id` you can poll, so we include a small `wait_for` helper.
-
-```python
-# ingest.py
-import os, time, requests
-from supabase import create_client
-from brain import client, person
-
-sb = create_client(os.environ["SUPABASE_URL"], os.environ["SUPABASE_SERVICE_KEY"])
-MEM0_HEADERS = {"Authorization": f"Token {os.environ['MEM0_API_KEY']}"}
-
-def wait_for(event_id, timeout=30):
- """Platform extraction is async; poll the event until it settles."""
- for _ in range(timeout):
- r = requests.get(f"https://api.mem0.ai/v1/event/{event_id}/", headers=MEM0_HEADERS).json()
- if r.get("status") in ("SUCCEEDED", "FAILED"):
- return r["status"]
- time.sleep(1)
- return "TIMEOUT"
-
-# 1. Read knowledge that hasn't been ingested yet
-rows = sb.table("knowledge").select("*").is_("mem0_synced_at", "null").execute().data
-
-for row in rows:
- # 2. Add it. agent_id = the shared scope (org/team); user_id = who recorded it.
- # Mem0 routes shared facts to the agent and personal facts to the individual,
- # so pass both when there's an author.
- add_kwargs = {
- "agent_id": row["scope"],
- "metadata": {"source": "supabase", "knowledge_id": row["id"]},
- }
- if row["author"]:
- add_kwargs["user_id"] = person(row["author"])
- res = client.add([{"role": "user", "content": row["content"]}], **add_kwargs)
- # 3. Platform returns an event_id; wait for extraction to finish
- event_id = res.get("event_id") if isinstance(res, dict) else None
- if event_id:
- wait_for(event_id)
- # 4. Mark the row synced so we never double-ingest
- sb.table("knowledge").update({"mem0_synced_at": "now()"}).eq("id", row["id"]).execute()
-
-print(f"Ingested {len(rows)} knowledge items into the company brain.")
-```
-
-```bash
-python ingest.py
-```
-
-```text
-Ingested 5 knowledge items into the company brain.
-```
-
-Re-running is safe, `mem0_synced_at` gates it, so a nightly cron can keep the brain in step with Supabase.
-
-## Step 6: Ask the brain
-
-Create **`ask.py`**. It searches everything relevant to the asker: their own (`user_id`) memories **plus** the shared company and team (`agent_id`) memories. This has to be an **`OR`**, each memory row belongs to exactly one entity, so a flat filter or an `AND` of a `user_id` and an `agent_id` matches nothing.
-
-```python
-# ask.py
-import sys
-from brain import client, COMPANY, team, person
-
-def ask(question: str, uid: str | None = None, user_team: str | None = None) -> str:
- scopes = [{"agent_id": COMPANY}] # company-wide brain
- if user_team:
- scopes.append({"agent_id": team(user_team)}) # the asker's team
- if uid:
- scopes.append({"user_id": person(uid)}) # the asker's own memories
- hits = client.search(
- query=question,
- filters={"OR": scopes}, # OR, never AND (one FK per memory row)
- top_k=5,
- rerank=True,
- )
- return "\n".join(f"- {h['memory']}" for h in hits.get("results", hits))
-
-if __name__ == "__main__":
- print(ask(" ".join(sys.argv[1:]) or "When can we deploy?"))
-```
-
-```bash
-python ask.py "Why did we pick Postgres, and can I deploy on Friday?"
-```
-
-```text
-- The company chose Postgres over MongoDB for strong transactional guarantees and relational joins
-- The company's production deploys go out Tuesday and Thursday, never on Fridays
-```
-
-Search returns every relevant memory, so a question resolves across separate facts, here it pulls both the owning team and the person:
-
-```bash
-python ask.py "Who should I talk to about billing?"
-```
-
-```text
-- Billing is owned by the Payments team
-- Alice is the Payments tech lead
-```
-
-## Step 7: Sharper retrieval
-
-Platform search is hybrid (semantic + keyword) and filterable. Combine a keyword pass with a category filter to answer precise questions:
-
-```python
-client.search(
- query="webhook signing secret",
- filters={"agent_id": "team:payments", "categories": {"in": ["tooling"]}},
- keyword_search=True, # hybrid keyword + semantic
- rerank=True,
- threshold=0.3,
-)
-```
-
-Filters use keyword operators (`in`, `gte`, `contains`, โฆ) and AND/OR/NOT, so you can scope by date, category, or metadata, for example the company's policies added this quarter:
-
-```python
-client.search(
- query="compliance rules",
- filters={"AND": [
- {"agent_id": "org:acme"},
- {"categories": {"in": ["policy"]}},
- {"created_at": {"gte": "2026-01-01"}},
- ]},
-)
-```
-
-## Step 8: Expose the brain to every agent (MCP)
-
-A brain only your script can reach isn't a company brain. Mem0's **hosted MCP server** lets any agent (Claude Code, Cursor, a Slack bot) query and contribute to the *same* brain. The endpoint is `https://mcp.mem0.ai/mcp`, and the supported way to connect is the `mcp-add` helper, which registers the server and runs Mem0's OAuth login so no key ever lands in a config file.
-
-
-
-```bash
-npx mcp-add --url "https://mcp.mem0.ai/mcp" --clients "claude code,cursor"
-```
-Complete the browser login on first connect. Now the agent has the brain's memory tools (`add_memory`, `search_memories`, and more) available in-editor.
-
-
-```json
-{
- "mcpServers": {
- "mem0": { "url": "https://mcp.mem0.ai/mcp" }
- }
-}
-```
-Auth happens via Mem0's OAuth flow on first use, don't paste a static token into the file (the hosted gateway may reject a raw `Token` header).
-
-
-```python
-# A Slack bot is just another MCP client. Point its MCP layer at the same URL,
-# authenticate via Mem0's OAuth flow, and pass the company scope on each call.
-await mcp.call_tool("search_memories", {
- "query": user_message,
- "agent_id": "org:acme",
-})
-```
-
-
-
-With this, an engineer asks the brain from their editor and a teammate asks it from Slack, one shared memory behind both.
-
-## Step 9: Onboard a new hire (the payoff)
-
-This is what a company brain is *for*. Dana joins, and her identity comes from **Supabase Auth**, which maps straight to her Mem0 `user_id`. She asks the questions every new hire asks and gets real answers on day one, drawn from the shared company (and her team's) brain, plus anything she's told it herself.
-
-```python
-# onboarding.py
-from brain import client, person
-from ask import ask
-
-# In a real app these come from sb.auth.get_user(jwt) and the employees table.
-dana_uid, dana_team = "8f3c...-dana", "payments"
-
-# Dana also tells the brain how *she* works. This is personal, so it goes to her
-# user_id, not the shared agent, and stays scoped to her.
-client.add(
- [{"role": "user", "content": "I prefer early returns over nested ifs, and I review PRs in the morning."}],
- user_id=person(dana_uid),
-)
-
-for q in [
- "Who owns billing and who do I talk to?", # company (agent) knowledge
- "When are deploys, and are there hard rules?",
- "How do I like to write code?", # Dana's own (user) knowledge
-]:
- print(f"Q: {q}\nA: {ask(q, uid=dana_uid, user_team=dana_team)}\n")
-```
-
-```text
-Q: Who owns billing and who do I talk to?
-A: - Billing is owned by the Payments team; Alice is the Payments tech lead
-
-Q: When are deploys, and are there hard rules?
-A: - The company's production deploys go out Tuesday and Thursday, never on Fridays
-
-Q: How do I like to write code?
-A: - User prefers early returns over nested ifs
-```
-
-The same `ask()` blends the shared company facts with Dana's own preference, because the `OR` filter spans both her `user_id` and the org and team `agent_id`s.
-
-Dana onboarded herself by asking, drawing on the shared brain the rest of the team had been filling.
-
-## Production notes
-
-
-**`user_id` vs `agent_id`.** An individual is a `user_id`; shared brains (company, team) are `agent_id`s. Keeping them separate is what gives you the third-person "The companyโฆ" framing and lets a person's own context sit alongside org knowledge. Put a secret like a webhook key on a **team** agent, never the company agent, or everyone can recall it, and mirror the boundary in Supabase with a Row Level Security policy on `knowledge`.
-
-
-
-**Search must `OR` the scopes.** A memory row belongs to exactly one entity, so `filters={"OR": [{"user_id": ...}, {"agent_id": "org:acme"}, {"agent_id": "team:..."}]}`. A flat filter, or an `AND` of a `user_id` and an `agent_id`, returns nothing.
-
-
-
-**`add()` is asynchronous.** It returns `{event_id, status: "PENDING"}` and extraction finishes a moment later, poll `GET /v1/event/{event_id}/` (as in Step 5) when you need to know a write has landed before searching for it.
-
-
-
-**Where the entity ID goes differs by call.** `search()` and `get_all()` take the scope inside `filters={...}` (a top-level `user_id=`/`agent_id=` is rejected). `add()` and `delete_all()` are the opposite, they take it as a top-level keyword: `client.delete_all(agent_id="team:payments")`. Deletes are asynchronous too, so a `get_all` right after a `delete_all` can still show rows for a few seconds.
-
-
-## Where to take it next
-
-- **Auto-feed the brain** from PR descriptions, RFCs, and incident write-ups so it grows without anyone thinking about it, just insert into Supabase `knowledge` and let the cron ingest.
-- **Scope by real identity** end to end: verify the Supabase JWT, read `sb.auth.get_user(jwt).user.id` for the `user_id`, look up the person's team, and `OR` their `user_id` with the company and team `agent_id`s on every recall.
-- **Give teams a private view** with Supabase RLS so `team:` knowledge is only readable by that team.
-
----
-
-
-
- Connect any agent or editor to the brain over MCP.
-
-
- Steer exactly what the brain extracts and how it's filed.
-
-
-
-
diff --git a/docs/core-concepts/how-it-works.mdx b/docs/core-concepts/how-it-works.mdx
index 1be360c79..5998b4f3c 100644
--- a/docs/core-concepts/how-it-works.mdx
+++ b/docs/core-concepts/how-it-works.mdx
@@ -89,8 +89,8 @@ On Mem0 Platform, these stores are managed for you. In OSS, you choose and opera
## Next steps
-
- Organize Platform memories by user, agent, app, and run.
+
+ Choose the right scope for user, agent, run, and session memory.
Add, search, update, and delete memories from your app.
diff --git a/docs/core-concepts/memory-operations/delete.mdx b/docs/core-concepts/memory-operations/delete.mdx
index ddd86a8e3..eb8f4c8c9 100644
--- a/docs/core-concepts/memory-operations/delete.mdx
+++ b/docs/core-concepts/memory-operations/delete.mdx
@@ -137,10 +137,6 @@ You can also filter by other parameters such as:
**Breaking change:** `delete_all` previously wiped all project memories when called with no filters. It now **raises an error** if no filters are provided. Use `"*"` wildcards for intentional bulk deletion (see below).
-
- Pass entity IDs as top-level arguments (`user_id="alice"` or `userId: "alice"`). `delete_all` does not accept `filters`. An empty or whitespace-only ID such as `user_id=""` matches every memory in the project, so the SDKs raise an error before sending the request. `delete_users` and `deleteUsers` apply the same check.
-
-
### Wildcard deletes
Setting a filter to `"*"` deletes **all memories** for that entity type across the entire project. This is an intentionally explicit opt-in to bulk deletion.
diff --git a/docs/core-concepts/memory-types.mdx b/docs/core-concepts/memory-types.mdx
new file mode 100644
index 000000000..a2a18e077
--- /dev/null
+++ b/docs/core-concepts/memory-types.mdx
@@ -0,0 +1,118 @@
+---
+title: Memory Types
+description: "What memory_type actually does in Mem0: procedural memory is implemented, semantic and episodic are not."
+icon: "tag"
+iconType: "solid"
+---
+
+# Memory Types
+
+Mem0's Python SDK exposes a `memory_type` parameter on `add()`. The underlying `MemoryType` enum defines three values, but only one of them is wired up. This page states plainly which is which so you don't build against a type that doesn't exist yet.
+
+## Status
+
+| Type | Enum value | Status | Notes |
+| --- | --- | --- | --- |
+| Procedural memory | `procedural_memory` | **Implemented** | Python OSS only (`Memory`/`AsyncMemory`). Pass `memory_type="procedural_memory"` and `agent_id` to `add()`. Not available on the Platform `MemoryClient`, and not available in the TypeScript SDK (OSS or Platform). |
+| Semantic memory | `semantic_memory` | **Not implemented** | Defined in the `MemoryType` enum but never read anywhere else in the codebase. Passing it to `add()` raises a validation error. There is no evidence in this repo of a roadmap date for this. |
+| Episodic memory | `episodic_memory` | **Not implemented** | Same as above: defined, never wired into the extraction pipeline, rejected by validation, no documented roadmap. |
+
+
+ Only `procedural_memory` is a real, working value. Calling `memory.add(messages, memory_type="semantic_memory")` (or `episodic_memory`) is rejected and tells you to pass `procedural_memory` instead. Sync `Memory.add()` raises `Mem0ValidationError`; `AsyncMemory.add()` raises a plain `ValueError`.
+
+
+## Procedural memory
+
+Procedural memory stores step-by-step task knowledge (how an agent performs a workflow) rather than facts about a user. It requires `agent_id`:
+
+```python
+from mem0 import Memory
+
+memory = Memory()
+
+memory.add(
+ [
+ {"role": "user", "content": "Book a flight from SFO to NYC"},
+ {"role": "assistant", "content": "1. Search flights. 2. Filter by price. 3. Confirm booking."},
+ ],
+ agent_id="travel-agent",
+ memory_type="procedural_memory",
+)
+```
+
+Omit `memory_type` entirely and Mem0 stores the messages as an ordinary memory: there is no semantic/episodic pathway for it to fall into. Any other explicit value is rejected by validation rather than quietly falling back to an ordinary memory.
+
+## How every other memory is scoped
+
+Outside of the `procedural_memory` special case, Mem0 does not sort memories into named types. Every memory is scoped by the identifiers you pass in, and the same identifiers are used to retrieve it later:
+
+- **`user_id`**: ties a memory to a specific person or account.
+- **`agent_id`**: ties a memory to a specific agent or assistant persona.
+- **`run_id`**: ties a memory to a specific session, task, or conversation thread.
+- **`app_id`** (Platform only): ties a memory to a specific application or tenant, in addition to the three above. See Entity-Scoped Memory.
+
+At least one identifier is required on `add()`. Passing more than one narrows the scope further (for example, `user_id` + `run_id` together).
+
+```python
+from mem0 import Memory
+
+memory = Memory()
+
+memory.add(
+ "I'm Alex and I prefer boutique hotels.",
+ user_id="alex",
+ run_id="trip-planning-2025",
+)
+
+results = memory.search(
+ "Any hotel preferences?",
+ filters={"user_id": "alex", "run_id": "trip-planning-2025"},
+)
+```
+
+
+ Use `run_id` when you want a set of memories to stay tied to one session or task; use `user_id` alone for anything that should persist across every session for that person.
+
+
+## How memories are extracted and updated
+
+When `infer=True` (the default) on `add()`, Mem0 runs a single pipeline rather than routing through separate type-specific paths:
+
+1. **Context gathering**: pulls the most recent messages already stored for the same `user_id`/`agent_id`/`run_id` scope.
+2. **Existing memory retrieval**: embeds the new messages and runs a vector search against memories already in that same scope, to find candidates that might need to change.
+3. **Extraction**: a single LLM call compares the new messages against the retrieved candidates and decides, per fact, whether to `ADD`, `UPDATE`, `DELETE`, or leave a memory alone.
+
+Alongside this, both OSS and Platform extract named entities (people, places, organizations) from memory text and use shared entities between memories to boost related results at search time. On Platform, that entity graph is also queryable directly; see Graph Memory. In OSS, entities only affect ranking, there is no separate graph to query.
+
+
+ Avoid storing secrets or unredacted PII in memories: they are retrievable by design. Encrypt or hash sensitive values before calling `add()`.
+
+
+## Put it into practice
+
+
+
+
+
+
+
diff --git a/docs/docs.json b/docs/docs.json
index b694e288a..c1c4887d2 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -41,7 +41,6 @@
"pages": [
"platform/quickstart",
"platform/overview",
- "platform/copilot",
"platform/agent-signup",
"vibecoding",
"platform/cli",
@@ -54,6 +53,7 @@
"icon": "brain",
"pages": [
"core-concepts/how-it-works",
+ "core-concepts/memory-types",
"core-concepts/memory-operations/add",
"core-concepts/memory-operations/search",
"core-concepts/memory-operations/update",
@@ -71,7 +71,6 @@
"pages": [
"platform/features/v2-memory-filters",
"platform/features/entity-scoped-memory",
- "platform/features/user-profiles",
"platform/features/graph-memory",
"platform/features/async-client",
"platform/features/multimodal-support",
@@ -87,8 +86,7 @@
"platform/advanced-memory-operations",
"platform/features/custom-instructions",
"platform/features/memory-decay",
- "platform/features/dream",
- "platform/features/byok"
+ "platform/features/dream"
]
},
{
@@ -116,8 +114,7 @@
"group": "Support",
"icon": "life-buoy",
"pages": [
- "platform/faqs",
- "platform/pricing"
+ "platform/faqs"
]
},
{
@@ -446,8 +443,7 @@
"cookbooks/integrations/mastra-agent",
"cookbooks/integrations/healthcare-google-adk",
"cookbooks/integrations/aws-bedrock",
- "cookbooks/integrations/tavily-search",
- "cookbooks/integrations/supabase"
+ "cookbooks/integrations/tavily-search"
]
},
{
@@ -515,17 +511,6 @@
"api-reference/entities/delete-user"
]
},
- {
- "group": "Profiles",
- "icon": "id-card",
- "pages": [
- "api-reference/profiles/get-profile",
- "api-reference/profiles/get-profile-settings",
- "api-reference/profiles/update-profile-settings",
- "api-reference/profiles/generate-profiles",
- "api-reference/profiles/get-profile-job"
- ]
- },
{
"group": "Organizations",
"icon": "building",
@@ -1034,11 +1019,7 @@
},
{
"source": "/concepts/memory-scoring",
- "destination": "/core-concepts/how-it-works"
- },
- {
- "source": "/core-concepts/memory-types",
- "destination": "/core-concepts/how-it-works"
+ "destination": "/core-concepts/memory-types"
},
{
"source": "/cookbooks/research-copilot",
diff --git a/docs/images/halloween-happy-hour.png b/docs/images/halloween-happy-hour.png
deleted file mode 100644
index 8b5ab3874..000000000
Binary files a/docs/images/halloween-happy-hour.png and /dev/null differ
diff --git a/docs/images/platform/byok-accuracy-vs-cost.png b/docs/images/platform/byok-accuracy-vs-cost.png
deleted file mode 100644
index 020c40fc0..000000000
Binary files a/docs/images/platform/byok-accuracy-vs-cost.png and /dev/null differ
diff --git a/docs/images/platform/byok-picks.png b/docs/images/platform/byok-picks.png
deleted file mode 100644
index f09b9b2af..000000000
Binary files a/docs/images/platform/byok-picks.png and /dev/null differ
diff --git a/docs/integrations/camel-ai.mdx b/docs/integrations/camel-ai.mdx
index 342291819..1eb715b20 100644
--- a/docs/integrations/camel-ai.mdx
+++ b/docs/integrations/camel-ai.mdx
@@ -130,10 +130,10 @@ print(response.msgs[0].content)
Detailed MCP configuration for all clients
diff --git a/docs/integrations/deepseek-plugin.mdx b/docs/integrations/deepseek-plugin.mdx
index 0242496e1..16b8badaf 100644
--- a/docs/integrations/deepseek-plugin.mdx
+++ b/docs/integrations/deepseek-plugin.mdx
@@ -114,7 +114,7 @@ Both tools also accept optional per-call `userId`, `agentId`, and `runId` params
## Telemetry
-Writes are tagged `source="DEEPSEEK_HARNESS"` so Mem0 can attribute usage to this integration. Usage events include operation names, durations, result counts, and coarse failure kinds. They are **not anonymous**: when an API key is configured they are sent under your Mem0 account email, the same way the SDK attributes its own. Queries, memory text, entity IDs, and API keys are never included. Set `MEM0_TELEMETRY=false` to opt out.
+Writes are tagged `source="DEEPSEEK_HARNESS"` so Mem0 can attribute usage to this integration. Anonymous usage events include operation names, durations, result counts, and coarse failure kinds. Queries, memory text, entity IDs, and API keys are never included. Set `MEM0_TELEMETRY=false` to opt out.
This plugin is a developer preview and tracks the evolving DeepSeek Harness plugin API.
diff --git a/docs/integrations/hermes.mdx b/docs/integrations/hermes.mdx
index f1d385144..0f3ba0958 100644
--- a/docs/integrations/hermes.mdx
+++ b/docs/integrations/hermes.mdx
@@ -1,9 +1,9 @@
---
title: Hermes Agent
-description: "Add persistent memory to Hermes Agent with Mem0 Cloud, a self-hosted server, or the in-process OSS SDK."
+description: "Add long-term memory to Hermes agents with Mem0 via managed Platform, self-hosted server, or fully local OSS, with turn recall and fact extraction."
---
-Add long-term memory to [Hermes Agent](https://github.com/NousResearch/hermes-agent), a self-improving AI agent CLI by Nous Research. The [standalone Mem0 plugin](https://github.com/mem0ai/mem0/tree/main/integrations/hermes-plugin-mem0) learns facts from conversations and recalls relevant memories for the current question.
+Add long-term memory to [Hermes Agent](https://github.com/NousResearch/hermes-agent), a self-improving AI agent CLI by Nous Research. Hermes has a pluggable memory system, and Mem0 is one of the supported providers. Once enabled, Mem0 learns facts from your conversations and surfaces relevant ones for the current question, without slowing down the chat.
You can run Mem0 in three ways:
@@ -17,15 +17,11 @@ Hermes runs a built-in memory system (file-based `MEMORY.md` and `USER.md`) alon
### 1. Current-turn recall (bounded wait)
-When you send a message, Hermes searches your stored memories for the current question and waits up to 3 seconds for results. If they arrive in time, they are injected into the system prompt so the model can see them. If the backend is slower, Hermes skips the injection and the model can still call `mem0_search` itself after the bounded recall wait.
+When you send a message, Hermes searches your stored memories for the current question and waits up to 3 seconds for results. If they arrive in time, they are injected into the system prompt so the model can see them. If the backend is slower, Hermes skips the injection and the model can still call `mem0_search` itself โ so a slow backend never blocks a turn.
### 2. Background fact extraction (sync)
-Once the model finishes, the plugin sends the user message and assistant response to Mem0 in a background thread for fact extraction. Each write includes the agent identifier and gateway channel.
-
-
- Automatic capture truncates each message to **450 characters by default in every mode**, preferring a sentence boundary. Adjust `sync_max_chars` for your model's context limit. Capture is best effort: if the previous sync is still running after a five-second wait, the next turn is skipped. Use `mem0_add` to store specific text verbatim.
-
+Once the model finishes, Hermes sends the `(user message, assistant response)` pair to Mem0 in a background thread. Mem0 extracts facts automatically (for example, "user prefers Python" or "user works at Acme Corp"), so you never have to tell it what to remember. Each write is tagged with the gateway channel it came from.
## Agent Tools
@@ -33,33 +29,21 @@ When Mem0 is active, the model gets four tools it can call during a conversation
| Tool | Description | Parameters |
|------|-------------|------------|
-| `mem0_search` | Semantic search by meaning, ranked by relevance | `query` (required), `top_k` (default 10, max 50), `rerank` (uses the configured default, Platform mode only) |
+| `mem0_search` | Semantic search by meaning, ranked by relevance | `query` (required), `top_k` (default 10, max 50), `rerank` (default `false`, Platform mode only) |
| `mem0_add` | Store a fact verbatim, with no LLM extraction | `content` (required) |
| `mem0_update` | Update a memory's text by ID | `memory_id`, `text` (both required) |
| `mem0_delete` | Delete a memory by ID | `memory_id` (required) |
## Installation
-Install [Hermes Agent](https://github.com/NousResearch/hermes-agent) with memory-provider plugin support and Python 3.11 or later. Once the plugin directory is available on Mem0's main branch, install it from the repository subdirectory:
+Install Hermes Agent:
```bash
-hermes plugins install mem0ai/mem0/integrations/hermes-plugin-mem0
-hermes plugins enable mem0
-hermes memory setup
-hermes memory status
+curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash
+source ~/.bashrc
```
-Select **mem0** in setup and choose one of the modes below. Start a fresh Hermes conversation after setup.
-
-Hermes installers with plugin dependency support install `mem0ai>=2.0.10,<3` and `httpx>=0.27,<1` from the plugin's `pyproject.toml`. Older hosts such as Hermes v0.21.3 require those packages to be installed explicitly into the Hermes Python environment. The OSS setup flow installs additional provider packages as needed.
-
-
- Hermes versions that still bundle Mem0 prefer the bundled provider. Use a Hermes release that has completed the standalone-provider migration; installing this plugin alone does not replace the bundled implementation. Existing users should keep their current configuration; see [Migration for existing users](#migration-for-existing-users).
-
-
-
- Run the setup wizard in an interactive terminal. On Hermes hosts whose `hermes memory setup --help` lists only a provider argument, options such as `--mode`, `--host`, and `--oss-llm` are rejected by Hermes before the plugin runs. Use `hermes memory setup mem0` or the manual configuration below. Redirected input cannot select the mode picker and falls back to Platform.
-
+The `mem0ai` package is installed automatically when you enable the Mem0 provider, so there is no manual pip step. OSS providers may need extra packages (for example `qdrant-client`, `psycopg2-binary`, or `ollama`), which the setup flow installs for you when you pick them.
## Platform Setup
@@ -68,10 +52,10 @@ Platform mode uses managed Mem0 Cloud and is the fastest way to start.
### Option 1: Interactive wizard (recommended)
```bash
-hermes memory setup mem0
+hermes memory setup
```
-Choose **Platform** and paste your API key when prompted. The wizard writes settings to `$HERMES_HOME/mem0.json` and keeps the key in that profile's `.env`. The default Hermes home is `~/.hermes`; named profiles use their own home directory.
+Select **mem0**, choose **Platform**, and paste your API key when prompted. The wizard writes the non-secret settings to `~/.hermes/mem0.json` and keeps the key in `~/.hermes/.env`.
Get your API key from app.mem0.ai.
@@ -79,25 +63,17 @@ Choose **Platform** and paste your API key when prompted. The wizard writes sett
```bash
hermes config set memory.provider mem0
+echo "MEM0_API_KEY=your-api-key" >> ~/.hermes/.env
```
-Add your key to the active Hermes profile's `.env`:
+Then in your `config.yaml`:
-```dotenv
-MEM0_API_KEY=your-api-key
+```yaml
+memory:
+ provider: mem0
```
-Set these values in the active profile's `mem0.json`, choosing a stable user identity:
-
-```json
-{
- "mode": "platform",
- "host": "",
- "user_id": "my-hermes-user"
-}
-```
-
-Remove any stale `MEM0_HOST` from the environment and profile `.env`, and remove an old inline `api_key` from `mem0.json` so the new `.env` key is used. The config command sets `memory.provider: mem0` in that profile's `config.yaml`. Restart Hermes and check `hermes memory status`.
+That's it. Mem0 runs automatically from here.
## Self-Hosted Server Setup
@@ -106,47 +82,48 @@ Run the [Mem0 server](https://github.com/mem0ai/mem0/tree/main/server) (FastAPI
### Interactive
```bash
-hermes memory setup mem0
-# Choose "Self-hosted server", then enter the server URL and API key
+hermes memory setup
+# Select "mem0", then "Self-hosted server", and enter the server URL
```
-### Manual configuration
+### With flags
-Select `mem0` with `hermes config set memory.provider mem0`. Set these values in the active profile's `mem0.json`:
-
-```json
-{
- "mode": "platform",
- "host": "http://localhost:8888",
- "user_id": "my-hermes-user"
-}
+```bash
+hermes memory setup mem0 --mode selfhosted \
+ --host http://localhost:8888 \
+ --api-key your-admin-api-key
```
-Add the server key to that profile's `.env`:
+### With environment variables
-```dotenv
-MEM0_API_KEY=your-admin-api-key
+```bash
+echo "MEM0_HOST=http://localhost:8888" >> ~/.hermes/.env
+echo "MEM0_API_KEY=your-admin-api-key" >> ~/.hermes/.env
```
-Remove an old inline `api_key` from `mem0.json` so the `.env` key is used. `MEM0_HOST` can also supply the server URL, but a non-empty `host` in `mem0.json` overrides it. Keep `mode` set to `platform` for the HTTP server backend.
-
Then start a fresh Hermes session and call `mem0_search` โ it connects to your server. The plugin authenticates with `X-API-Key` and uses the server's `/search` and `/memories` routes. The API key is optional only for servers running with `AUTH_DISABLED`.
Setting `host` routes to the self-hosted server automatically. Don't combine it with `mode: oss` โ OSS takes precedence and ignores `host`.
## OSS (Self-Hosted) Setup
-OSS mode runs the Mem0 SDK in the Hermes process with your chosen LLM, embedder, and vector store. It does not use Mem0 Cloud or require a Mem0 API key. Data goes to the model services you configure; use local Ollama models and local storage for a fully local setup.
+OSS mode runs Mem0 entirely on your own infrastructure: your LLM, your embedder, and your vector store. No data is sent to Mem0 Cloud, and no Mem0 API key is required.
### Interactive
```bash
-hermes memory setup mem0
-# Choose "Open Source"
+hermes memory setup
+# Select "mem0", then "Open Source (self-hosted)"
# Follow the prompts for LLM, embedder, and vector store
```
-The wizard uses the listed default OpenAI models and local Qdrant storage. For custom OpenAI-compatible endpoints, deployment names, or a Qdrant server, use manual configuration below.
+### With flags
+
+```bash
+hermes memory setup mem0 --mode oss \
+ --oss-llm openai --oss-llm-key sk-... \
+ --oss-vector qdrant
+```
### Supported providers
@@ -156,24 +133,52 @@ The wizard uses the listed default OpenAI models and local Qdrant storage. For c
| Embedder | `openai` (default `text-embedding-3-small`), `ollama` (local, default `nomic-embed-text`) |
| Vector store | `qdrant` (local path or server), `pgvector` |
-### Manual configuration
+### Flag reference
+
+| Flag | Description |
+|------|-------------|
+| `--mode` | `platform`, `selfhosted`, or `oss` |
+| `--api-key` | Platform API key, or the admin key of a self-hosted server |
+| `--host` | Self-hosted server URL (with `--mode selfhosted`) |
+| `--oss-llm` | LLM provider (`openai` or `ollama`, default `openai`) |
+| `--oss-llm-key` | LLM API key (for `openai`) |
+| `--oss-llm-model` | Override the LLM model |
+| `--oss-llm-url` | LLM base URL (for `ollama` or a custom endpoint) |
+| `--oss-embedder` | Embedder provider (default `openai`) |
+| `--oss-embedder-key` | Embedder API key |
+| `--oss-embedder-model` | Override the embedder model |
+| `--oss-embedder-url` | Embedder base URL (for `ollama` or a custom endpoint) |
+| `--oss-vector` | Vector store (`qdrant` or `pgvector`, default `qdrant`) |
+| `--oss-vector-path` | Local Qdrant storage path |
+| `--oss-vector-url` | Qdrant server URL |
+| `--oss-vector-host`, `--oss-vector-port` | PGVector or remote Qdrant host and port |
+| `--oss-vector-user`, `--oss-vector-password`, `--oss-vector-dbname` | PGVector connection details |
+| `--user-id` | Canonical user identifier |
+| `--dry-run` | Preview the resolved config without writing it |
+
+## Switching Modes
+
+You can move between the three modes at any time. Run the setup command again, or edit `~/.hermes/mem0.json` directly.
```bash
-hermes config set memory.provider mem0
+# Platform to OSS
+hermes memory setup mem0 --mode oss --oss-llm-key sk-...
+
+# OSS to Platform
+hermes memory setup mem0 --mode platform --api-key sk-...
+
+# Platform to a self-hosted server
+hermes memory setup mem0 --mode selfhosted --host http://localhost:8888
+
+# Preview without writing anything
+hermes memory setup mem0 --mode oss --oss-llm-key sk-... --dry-run
```
-Add the model key to the active profile's `.env`:
-
-```dotenv
-OPENAI_API_KEY=your-model-api-key
-```
-
-Set the following in that profile's `mem0.json`. Use your existing storage path when migrating; for a new named profile, choose a path inside that profile's home.
+A self-hosted `~/.hermes/mem0.json` looks like this:
```json
{
"mode": "oss",
- "user_id": "my-hermes-user",
"oss": {
"llm": {"provider": "openai", "config": {"model": "gpt-5-mini", "is_reasoning_model": true}},
"embedder": {"provider": "openai", "config": {"model": "text-embedding-3-small"}},
@@ -182,65 +187,33 @@ Set the following in that profile's `mem0.json`. Use your existing storage path
}
```
-For an OpenAI-compatible service such as Azure's `/openai/v1` endpoint, add `OPENAI_BASE_URL` to the profile's `.env` and set each `model` to its deployed name. Both the LLM and embedder use this endpoint unless their `config.openai_base_url` overrides it. The main Hermes chat model is configured separately; this JSON configures Mem0's extraction and embedding models.
-
-For a Qdrant server, replace `vector_store.config.path` with `url`, for example `"url": "http://localhost:6333"`. Manual setup does not install optional provider dependencies: install `qdrant-client`, `psycopg2-binary`, or `ollama` in the **Hermes Python environment** as needed for your selected providers. Start a fresh session and verify a memory write and search; `hermes memory status` reports configuration availability, not a full backend health check.
-
-Desktop sessions in the same process and profile share local Qdrant storage when their OSS settings match. Operations are serialized, and storage closes after the last session releases it. Conflicting settings are rejected without changing existing memories; close active sessions before changing models or credentials. For concurrent CLI and Desktop processes, use a Qdrant server or the self-hosted Mem0 HTTP API instead of sharing a local directory.
-
-## Switching Modes
-
-Run `hermes memory setup mem0` in an interactive terminal and choose the new mode, or edit the active profile's `mem0.json` using the examples above. Switching backends does not transfer memories between them. Preserve existing OSS storage paths when editing configuration. When returning to Platform, set `mode` to `platform`, clear `host`, and remove any stale `MEM0_HOST` setting from your environment and profile `.env`.
-
## Configuration
-Settings live in `$HERMES_HOME/mem0.json` and are written by `hermes memory setup`. API keys normally live in that profile's `.env`; distinct OpenAI LLM/embedder keys and database credentials are stored in the OSS configuration. Setup writes these files atomically with owner-only permissions.
-
-When editing these files manually, restrict both `.env` and `mem0.json` to their owner (`chmod 600` on Unix). Keep configuration and secrets in the same active Hermes profile.
-
-`MEM0_MODE`, `MEM0_HOST`, `MEM0_USER_ID`, and `MEM0_AGENT_ID` supply environment defaults. Non-empty values in `mem0.json` take precedence. `MEM0_API_KEY` supplies the Cloud or server key unless `api_key` is set in the file.
+Behavioral settings live in `~/.hermes/mem0.json` and are written for you by `hermes memory setup`. Only the secret `MEM0_API_KEY` belongs in `~/.hermes/.env`.
| Key | Default | Description |
|-----|---------|-------------|
| `mode` | `platform` | `platform` (Mem0 Cloud) or `oss` (self-managed, in-process). Self-hosted server routing is set via `host` |
| `host` | none | Self-hosted Mem0 server URL. When set, the plugin talks HTTP to your server instead of the cloud |
| `api_key` | none | Mem0 Platform API key, or the admin key of a self-hosted server. Stored in `.env` as `MEM0_API_KEY` |
-| `user_id` | gateway user ID, then `hermes-user` | Identifier that scopes memories. See cross-channel behavior below |
+| `user_id` | `hermes-user` | Identifier that scopes memories. See cross-channel behavior below |
| `agent_id` | `hermes` | Agent identifier attached to writes |
-| `rerank` | `false` | Platform reranking for recall and tool searches that omit `rerank` |
-| `sync_max_chars` | `450` | Per-message character cap for automatic fact extraction in every mode |
-| `oss` | `{}` | OSS LLM, embedder, and vector-store configuration |
+| `rerank` | `false` | Rerank search results for relevance (Platform mode only) |
### Cross-channel memories
Hermes can run from the CLI and from gateways like Telegram, Slack, and Discord. The `user_id` setting controls how memories are scoped across them:
-- **Set a `user_id` other than `hermes-user`** and it applies to every gateway, so one person gets a single merged memory store no matter where they talk to the agent.
-- **Leave it unset** (or at the default `hermes-user`) and each gateway uses its own native ID when available, falling back to `hermes-user`.
+- **Set a `user_id`** and it applies to every gateway, so one person gets a single merged memory store no matter where they talk to the agent.
+- **Leave it unset** (or at the default `hermes-user`) and each gateway uses its own native id, keeping per-platform memories separate.
-Every write is tagged with `metadata.channel` (for example `telegram` or `cli`). Plugin searches filter by user identity across sessions; they do not restrict recall to the current channel or session.
-
-## Migration for Existing Users
-
-Keep `memory.provider: mem0`, `mem0.json`, `MEM0_*` settings, user identity, and OSS database paths unchanged. Moving from the bundled provider to this standalone plugin does not require rerunning setup or moving stored memories.
-
-Automatic migration depends on Hermes rollout as well as this repository:
-
-1. Users need a Hermes build containing [PR #114569](https://github.com/NousResearch/hermes-agent/pull/114569).
-2. Hermes maintainers must approve a catalog entry named `mem0` with `repo: https://github.com/mem0ai/mem0`, `subdir: integrations/hermes-plugin-mem0`, and a reviewed full commit SHA.
-3. The bundled Mem0 provider must be removed so the standalone provider can load.
-
-With these in place, Hermes installs a missing configured provider during `hermes update` across profiles or at agent startup. Startup installation respects `security.allow_lazy_installs`. Offline or disabled installation needs manual action; merging the plugin directory alone does not complete automatic migration.
-
-CLI setup and status are supported. This plugin does not ship a Desktop configuration panel or provider-specific CLI commands.
+Either way, every write is tagged with `metadata.channel` (for example `telegram` or `cli`), so per-channel views are still possible at query time.
## Reliability
-- **Circuit breaker**: five consecutive backend failures pause calls for two minutes. The agent can continue without memory during that window. Expected update/delete errors such as a missing memory do not trip the breaker.
-- **Bounded waits**: recall waits up to three seconds. Capture runs in the background, but an overlapping turn may wait up to five seconds for the previous sync before being skipped.
-- **Graceful shutdown**: shutdown and Python process exit wait for active recall and capture workers before closing the backend. Backend network timeouts still apply. Self-hosted HTTP capture uses a 120-second read timeout and a 30-second connection timeout; other self-hosted HTTP operations use 30 seconds.
-- **Best-effort capture**: there is no durable queue. Forced termination, including Hermes' 30-second exit watchdog, can interrupt pending writes even while graceful shutdown is waiting.
-- **OSS data protection**: an embedding dimension mismatch fails initialization without deleting the existing collection or table.
+- **Circuit breaker**: if Mem0 fails five times in a row, Hermes pauses calls for two minutes, then retries. The agent keeps working without memory during that window. Expected client errors, like a 404 on a missing memory id, do not count toward tripping the breaker.
+- **Non-blocking**: fact extraction runs in a background daemon thread, and current-turn recall waits at most 3 seconds, so a slow or failed call never blocks your conversation.
+- **Thread-safe**: the client uses lazy initialization with locking, and the background sync and recall threads are guarded so concurrent gateway messages cannot produce duplicate memories.
## Troubleshooting
@@ -275,12 +248,15 @@ curl http://localhost:11434/api/tags
- `mem0_add` stores text verbatim with no extraction. Ordinary conversation turns are extracted automatically by the background sync.
- Search is semantic, so try a broader query.
-- Confirm `user_id` is the same across sessions (check `$HERMES_HOME/mem0.json`).
-- Check `sync_max_chars`: facts beyond the per-message limit are not sent for extraction.
+- Confirm `user_id` is the same across sessions (check `~/.hermes/mem0.json`).
-### OSS: embedding dimension mismatch
+## Key Features
-Restore the embedding model and dimensions that created the existing collection, or choose a new collection and migrate data explicitly. The plugin leaves the original collection intact when dimensions differ.
+1. **Three ways to run**: managed Platform, a self-hosted server, or fully local OSS, switchable at any time.
+2. **Current-turn recall**: memories for the current question are injected within a 3-second window, with `mem0_search` as the model's own backstop.
+3. **Automatic extraction**: Mem0 extracts and deduplicates facts from each exchange for you.
+4. **Non-blocking and fault tolerant**: background threads plus a circuit breaker keep the agent responsive even when Mem0 is unreachable.
+5. **Additive memory**: works alongside Hermes' built-in file memory (`MEMORY.md`, `USER.md`).
diff --git a/docs/integrations/llama-index.mdx b/docs/integrations/llama-index.mdx
index d529937f6..f2bc02491 100644
--- a/docs/integrations/llama-index.mdx
+++ b/docs/integrations/llama-index.mdx
@@ -45,7 +45,7 @@ memory_from_client = Mem0Memory.from_client(
)
```
-Context is used to identify the user, agent or the conversation in the Mem0. It is required to be passed in at least one of the fields in the `Mem0Memory` constructor. It can be any of the following:
+Context is used to identify the user, agent or the conversation in the Mem0. It is required to be passed in the at least one of the fields in the `Mem0Memory` constructor. It can be any of the following:
```python
context = {
diff --git a/docs/integrations/openclaw.mdx b/docs/integrations/openclaw.mdx
index fd7d449d9..a9642d444 100644
--- a/docs/integrations/openclaw.mdx
+++ b/docs/integrations/openclaw.mdx
@@ -481,9 +481,7 @@ Plugin config is stored in `~/.openclaw/openclaw.json` with file permissions `0o
### Telemetry
-Usage telemetry (PostHog) is enabled by default to help improve the plugin. No conversation content or memory values are included, only event counts (recall, capture, tool usage, CLI commands).
-
-These events are **not anonymous**. OpenClaw does not send your account email the way the SDK does, but it does send an unsalted SHA-256 hash of it, falling back to a hash of the API key and then to a random per-machine id. Mem0 holds the email the hash is derived from, so the hash identifies your account rather than concealing it. The first run that resolves an account also emits a PostHog `$identify`, which permanently merges any earlier random id into that identity.
+Anonymous usage telemetry (PostHog) is enabled by default to help improve the plugin. No conversation content or memory values are included, only event counts (recall, capture, tool usage, CLI commands).
To opt out, set the environment variable:
diff --git a/docs/llms.txt b/docs/llms.txt
index f13e2fc07..65e13de8f 100644
--- a/docs/llms.txt
+++ b/docs/llms.txt
@@ -171,7 +171,6 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
- [Introduction](https://docs.mem0.ai/introduction) [Both]: Use when the user wants a one-page overview of how memory fits between the LLM and the app.
- [Vibe Code with Mem0](https://docs.mem0.ai/vibecoding) [Both]: Use when the user is in Claude Code, Cursor, or Windsurf and wants memory wired into their editor.
- [Platform Overview](https://docs.mem0.ai/platform/overview) [Platform]: Use when the user picks the managed product - 4-line integration, hosted API, dashboard.
-- [Mem0 Copilot](https://docs.mem0.ai/platform/copilot) [Platform]: Use when inspecting project memories, reviewing configuration changes, or testing extraction in the dashboard.
- [Sign up as an agent](https://docs.mem0.ai/platform/agent-signup) [Platform]: Use when an AI agent needs to mint a Mem0 API key autonomously - four commands, no email or dashboard, human claims ownership later.
- [Platform vs Open Source](https://docs.mem0.ai/platform/platform-vs-oss) [Both]: Use when the user is deciding between managed and self-hosted.
- [Platform Quickstart](https://docs.mem0.ai/platform/quickstart) [Platform]: Use for the first Platform integration - API key plus `MemoryClient.add/search`.
@@ -186,6 +185,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
## Core Concepts
- [How Mem0 Works](https://docs.mem0.ai/core-concepts/how-it-works) [Both]: Use when explaining the end-to-end pipeline: extraction (ADD-only distillation), storage across vector/entity/history stores, and multi-signal retrieval.
+- [Memory Types](https://docs.mem0.ai/core-concepts/memory-types) [Both]: Use when checking which `memory_type` values actually work: `procedural_memory` is implemented, `semantic_memory` and `episodic_memory` are defined in the enum but rejected by validation.
- [Memory Operations - Add](https://docs.mem0.ai/core-concepts/memory-operations/add) [Both]: Use when explaining how `add()` extracts facts, resolves conflicts, and writes to both stores.
- [Memory Operations - Search](https://docs.mem0.ai/core-concepts/memory-operations/search) [Both]: Use when explaining how queries are processed and ranked.
- [Memory Operations - Update](https://docs.mem0.ai/core-concepts/memory-operations/update) [Both]: Use when memories need to be edited in place or reconciled against new info.
@@ -197,7 +197,6 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
### Features - Essential
- [V2 Memory Filters](https://docs.mem0.ai/platform/features/v2-memory-filters) [Platform]: Use when compound filters (AND/OR on metadata, entity, time) are needed at search.
- [Entity-Scoped Memory](https://docs.mem0.ai/platform/features/entity-scoped-memory) [Platform]: Use when partitioning memories by user, agent, app, or run.
-- [Profiles](https://docs.mem0.ai/platform/features/user-profiles) [Platform]: Use when a structured always-current summary of a user is needed in one read, instead of searching their memories.
- [Graph Memory](https://docs.mem0.ai/platform/features/graph-memory) [Platform]: Use when connecting facts across memories through shared entities for entity-centric or multi-hop questions.
- [Async Client](https://docs.mem0.ai/platform/features/async-client) [Platform]: Use when the app issues many concurrent Mem0 calls and needs non-blocking I/O.
- [Multimodal Support](https://docs.mem0.ai/platform/features/multimodal-support) [Platform]: Use when storing images or PDFs as memory input.
@@ -209,7 +208,6 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
- [Custom Instructions](https://docs.mem0.ai/platform/features/custom-instructions) [Platform]: Use when tailoring what Mem0 extracts and stores on Platform.
- [Memory Decay](https://docs.mem0.ai/platform/features/memory-decay) [Platform]: Use when search results should boost recently-reinforced memories and dampen stale ones. Opt in per project; applies at search time and never filters candidates out.
- [Dream](https://docs.mem0.ai/platform/features/dream) [Platform]: Use when long-lived user memory should stay coherent on its own - synthesizing recurring patterns, superseding outdated facts, and merging duplicates in the background. Synthesis is opt-in (Pro+); Supersede and Merge are always on.
-- [Bring Your Own Key (BYOK)](https://docs.mem0.ai/platform/features/byok) [Platform]: Use when connecting your own OpenAI, Anthropic, OpenRouter or Azure OpenAI key so memories are created on your model - setup, key-check errors, failed adds, rate limits and choosing a model.
- [Advanced Memory Operations](https://docs.mem0.ai/platform/advanced-memory-operations) [Platform]: Use when basic CRUD is not enough - batch ops, complex filters, workflows.
### Features - Data Management
@@ -225,7 +223,6 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
### Support & Migration
- [FAQs](https://docs.mem0.ai/platform/faqs) [Platform]: Use when answering common Platform questions.
-- [Pricing FAQ](https://docs.mem0.ai/platform/pricing) [Platform]: Use when a user asks how the October 26, 2026 pricing change affects their plan - existing Starter, Growth and Pro plans, free plan limits and the 30-day period, connecting their own LLM key, Vercel accounts and usage-based billing.
- [Contribute to Platform](https://docs.mem0.ai/platform/contribute) [Platform]: Use when a user wants to contribute to Platform docs or code.
- [OSS to Platform Migration](https://docs.mem0.ai/migration/oss-to-platform) [Both]: Use when moving from self-hosted to managed.
- [OSS v2 to v3 Migration](https://docs.mem0.ai/migration/oss-v2-to-v3) [OSS]: Use when upgrading a self-hosted deployment across major versions.
@@ -258,7 +255,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
- [Agno](https://docs.mem0.ai/integrations/agno) [Platform]: Use when the user is on Agno.
- [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) [Platform]: Use when the user is on ChatDev.
-- [Hermes](https://docs.mem0.ai/integrations/hermes) [Both]: Use when installing or configuring the standalone Hermes memory plugin, or migrating from the bundled Mem0 provider.
+- [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 automatic capture, prompt recall, scoped memory, and six memory commands to Pi Agent.
- [DeepSeek Harness](https://docs.mem0.ai/integrations/deepseek-plugin) [Platform]: Use when adding automatic recall, completed-turn capture, and native search/add tools to DeepSeek Harness.
- [OpenAI Agents SDK](https://docs.mem0.ai/integrations/openai-agents-sdk) [Platform]: Use when the user is on the OpenAI Agents SDK.
@@ -328,7 +325,6 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st
- [Healthcare Google ADK](https://docs.mem0.ai/cookbooks/integrations/healthcare-google-adk) [Platform]: Use when the domain is medical and the framework is Google ADK.
- [AWS Bedrock](https://docs.mem0.ai/cookbooks/integrations/aws-bedrock) [OSS]: Use when deploying with AWS managed model services.
- [Tavily Search](https://docs.mem0.ai/cookbooks/integrations/tavily-search) [Platform]: Use when the agent layers web search on memory.
-- [Company Brain (Mem0 Platform + Supabase)](https://docs.mem0.ai/cookbooks/integrations/supabase) [Platform]: Use to build a shared org brain on Mem0 Platform with Supabase as system of record and the MCP server as the access layer (with a new-hire onboarding demo).
### Framework Examples
- [LlamaIndex React](https://docs.mem0.ai/cookbooks/frameworks/llamaindex-react) [Both]: Use when building a React UI with LlamaIndex and memory.
@@ -366,11 +362,6 @@ All API Reference docs describe Mem0 Platform REST endpoints (requires API key).
### Entities
- [Get Users](https://docs.mem0.ai/api-reference/entities/get-users) [Platform]: Use when listing users, agents, or apps known to a project.
- [Delete User](https://docs.mem0.ai/api-reference/entities/delete-user) [Platform]: Use when removing an entity and all its memories.
-- [Get Profile](https://docs.mem0.ai/api-reference/profiles/get-profile) [Platform]: Use when reading a user's structured profile and branching on its generation status.
-- [Get Profile Settings](https://docs.mem0.ai/api-reference/profiles/get-profile-settings) [Platform]: Use when checking the project's profile schema, instructions, or enabled flag.
-- [Update Profile Settings](https://docs.mem0.ai/api-reference/profiles/update-profile-settings) [Platform]: Use when defining or changing the JSON Schema that shapes profiles for a project.
-- [Generate Profiles](https://docs.mem0.ai/api-reference/profiles/generate-profiles) [Platform]: Use when building profiles now: a sample of ten, or one entity.
-- [Get Generation Job](https://docs.mem0.ai/api-reference/profiles/get-profile-job) [Platform]: Use when checking how far a generation has got, and whether it finished.
### Organizations
- [Create Organization](https://docs.mem0.ai/api-reference/organization/create-org) [Platform]: Use when setting up a new org.
diff --git a/docs/migration/platform-v2-to-v3.mdx b/docs/migration/platform-v2-to-v3.mdx
index 8a16dde57..8cc9690da 100644
--- a/docs/migration/platform-v2-to-v3.mdx
+++ b/docs/migration/platform-v2-to-v3.mdx
@@ -136,8 +136,8 @@ curl -X POST 'https://api.mem0.ai/v3/memories/?page=1&page_size=50' \
| Parameter | V1/V2 | V3 | Notes |
|---|---|---|---|
| `top_k` | Supported | Supported (1-1000, default 10) | No change |
-| `threshold` | Default: `0.3` (v2) | Default: `0.1` | Pass `0.3` to keep the v2 cutoff, or `0.0` to disable |
-| `rerank` | Default: `false` | Default: `false` | No change. Pass `true` to enable (adds latency) |
+| `threshold` | Default: none | Default: `0.1` | Pass `0.0` to disable |
+| `rerank` | Default: `true` | Default: `false` | Pass `true` to enable (adds latency) |
| Entity IDs in `search` / `get_all` | Top-level | Inside `filters` dict | Top-level raises 400 |
### Response Format
@@ -265,10 +265,10 @@ If your application previously read graph relations from the API response (`rela
- The default `threshold` is now `0.1` (it was `0.3` on v2), so lower-scoring matches that v2 hid can now appear. Scores are computed differently in v3, so retune against representative queries. To keep a stricter cutoff, pass an explicit `threshold` in your search calls, or pass `threshold=0.0` to disable filtering.
+ The default `threshold` is now `0.1` (previously no threshold). If your application was relying on unfiltered results, explicitly pass `threshold=0.0` in your search calls to preserve the old behavior. In most cases, the new default is better: it filters out low-relevance noise.
- Reranking is `false` by default, the same as on v2. If your application depends on reranked results, pass `rerank=True` to your search calls. Note that reranking adds latency (~200-400ms) but can improve ordering quality for complex queries.
+ Reranking is now `false` by default. If your application depended on reranked results, add `rerank=True` to your search calls. Note that reranking adds latency (~200-400ms) but can improve ordering quality for complex queries.
The top-level `score` field continues to work as before. It is now a combined multi-signal score (semantic + keyword + entity) rather than pure cosine similarity, so the absolute numbers will differ. Relative ranking remains comparable: if you have threshold-based filtering in your app, retune on a representative query set.
diff --git a/docs/openapi.json b/docs/openapi.json
index f27449514..af215596f 100644
--- a/docs/openapi.json
+++ b/docs/openapi.json
@@ -8070,480 +8070,6 @@
}
}
}
- },
- "/v2/entities/{entity_type}/{entity_id}/profile/": {
- "get": {
- "tags": [
- "profiles"
- ],
- "operationId": "profiles_read",
- "summary": "Get an entity's profile",
- "description": "Return the memory profile for one user.\n\nGeneration is asynchronous, so a known entity that has no profile yet is a normal 200 carrying a `status`. A 404 means only that no such entity exists.",
- "parameters": [
- {
- "name": "entity_type",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string",
- "enum": [
- "user"
- ]
- },
- "description": "The kind of entity that carries the profile."
- },
- {
- "name": "entity_id",
- "in": "path",
- "required": true,
- "schema": {
- "type": "string"
- },
- "description": "The entity's id, as supplied when the memory was added."
- }
- ],
- "responses": {
- "200": {
- "description": "The profile envelope.",
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "properties": {
- "profile": {
- "type": "object",
- "additionalProperties": true,
- "description": "The generated profile, shaped by the project's schema. Empty unless status is succeeded."
- },
- "status": {
- "type": "string",
- "enum": [
- "succeeded",
- "pending",
- "failed",
- "not_enabled",
- "insufficient_data"
- ],
- "description": "Generation state. Branch on this rather than on an empty profile."
- },
- "entity_type": {
- "type": "string",
- "enum": [
- "user"
- ]
- },
- "entity_id": {
- "type": "string"
- },
- "updated_at": {
- "type": "string",
- "format": "date-time",
- "nullable": true
- },
- "generation_count": {
- "type": "integer"
- }
- }
- }
- }
- }
- },
- "400": {
- "description": "Unsupported entity type."
- },
- "404": {
- "description": "No such entity in this project."
- }
- }
- }
- },
- "/v2/profiles/settings/": {
- "get": {
- "tags": [
- "profiles"
- ],
- "operationId": "profiles_settings_read",
- "summary": "Get profile settings",
- "description": "Return the profile settings for the project the API key is scoped to.",
- "responses": {
- "200": {
- "description": "Current settings.",
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "properties": {
- "enabled": {
- "type": "boolean",
- "description": "Whether profile generation runs for this project. Project-wide."
- },
- "entities": {
- "type": "object",
- "description": "Settings for user profiles, under `user`.",
- "properties": {
- "user": {
- "type": "object",
- "properties": {
- "schema": {
- "type": "object",
- "additionalProperties": true,
- "nullable": true,
- "description": "JSON Schema describing the profile. Every property needs a description."
- },
- "custom_instructions": {
- "type": "string",
- "nullable": true,
- "description": "Extra guidance for the extraction step."
- }
- }
- }
- }
- },
- "capabilities": {
- "type": "object",
- "properties": {
- "jobs": {
- "type": "boolean"
- },
- "estimates": {
- "type": "boolean"
- },
- "samples": {
- "type": "boolean"
- },
- "full_rebuild": {
- "type": "boolean",
- "description": "Whether a project-wide rebuild (regenerate/backfill) is available. Currently false."
- }
- }
- }
- }
- }
- }
- }
- }
- }
- },
- "post": {
- "tags": [
- "profiles"
- ],
- "operationId": "profiles_settings_update",
- "summary": "Update profile settings",
- "description": "Update the project's profile settings. Only the fields present in the body are written, so one setting can change without re-sending the others.",
- "requestBody": {
- "required": true,
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "description": "Only the fields present are written. `schema` and `custom_instructions` nest under `entities.user`; a flat body is rejected.",
- "properties": {
- "enabled": {
- "type": "boolean",
- "description": "Whether profile generation runs for this project. Project-wide."
- },
- "entities": {
- "type": "object",
- "description": "Settings for user profiles, under `user`.",
- "properties": {
- "user": {
- "type": "object",
- "properties": {
- "schema": {
- "type": "object",
- "additionalProperties": true,
- "nullable": true,
- "description": "JSON Schema describing the profile. Every property needs a description. Send null to clear it."
- },
- "custom_instructions": {
- "type": "string",
- "nullable": true,
- "description": "Extra guidance for the extraction step. Send null to clear it."
- }
- }
- }
- }
- }
- }
- }
- }
- }
- },
- "responses": {
- "200": {
- "description": "Settings as stored after the update.",
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "properties": {
- "enabled": {
- "type": "boolean",
- "description": "Whether profile generation runs for this project. Project-wide."
- },
- "entities": {
- "type": "object",
- "description": "Settings for user profiles, under `user`.",
- "properties": {
- "user": {
- "type": "object",
- "properties": {
- "schema": {
- "type": "object",
- "additionalProperties": true,
- "nullable": true,
- "description": "JSON Schema describing the profile. Every property needs a description."
- },
- "custom_instructions": {
- "type": "string",
- "nullable": true,
- "description": "Extra guidance for the extraction step."
- }
- }
- }
- }
- },
- "capabilities": {
- "type": "object",
- "properties": {
- "jobs": {
- "type": "boolean"
- },
- "estimates": {
- "type": "boolean"
- },
- "samples": {
- "type": "boolean"
- },
- "full_rebuild": {
- "type": "boolean",
- "description": "Whether a project-wide rebuild (regenerate/backfill) is available. Currently false."
- }
- }
- }
- }
- }
- }
- }
- },
- "400": {
- "description": "The schema is not a valid profile schema."
- }
- }
- }
- },
- "/v2/profiles/jobs/": {
- "post": {
- "tags": [
- "profiles"
- ],
- "operationId": "profiles_create_job",
- "summary": "Generate profiles",
- "description": "Start one generation. `operation` says what to build:\n\n- `sample` โ up to 10 real entities, so a schema can be judged before it is used widely. These are real profiles: they are saved to those entities and count toward usage.\n- `trigger` โ one entity, named by `entity_id`.\n\nSend an `Idempotency-Key` header. Replaying the same key returns the same job instead of charging twice. Poll `status_url` from the response until the status is terminal.",
- "parameters": [
- {
- "in": "header",
- "name": "Idempotency-Key",
- "required": true,
- "schema": {
- "type": "string",
- "minLength": 8,
- "maxLength": 128
- },
- "description": "Makes a retry safe: the same key returns the same job."
- }
- ],
- "requestBody": {
- "required": true,
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "required": [
- "operation",
- "entity_type"
- ],
- "properties": {
- "operation": {
- "type": "string",
- "enum": [
- "sample",
- "trigger"
- ],
- "description": "What to generate. Optional only when `entity_id` is set, which means `trigger`."
- },
- "entity_type": {
- "type": "string",
- "enum": [
- "user"
- ]
- },
- "entity_id": {
- "type": "string",
- "description": "One entity, for `trigger`."
- },
- "limit": {
- "type": "integer",
- "minimum": 1,
- "maximum": 10,
- "description": "How many entities to sample."
- }
- }
- }
- }
- }
- },
- "responses": {
- "202": {
- "description": "Job accepted.",
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "properties": {
- "job_id": {
- "type": "string"
- },
- "status": {
- "type": "string"
- },
- "status_url": {
- "type": "string",
- "description": "Poll this. Building the path yourself breaks on a route change."
- },
- "operation": {
- "type": "string"
- },
- "entity_type": {
- "type": "string"
- },
- "entity_count_reserved": {
- "type": "integer",
- "description": "Entities reserved against usage for this job."
- },
- "event_id": {
- "type": "string",
- "nullable": true
- },
- "replayed": {
- "type": "boolean",
- "description": "True when an Idempotency-Key returned an existing job."
- },
- "sampled": {
- "type": "integer",
- "description": "`sample` only."
- },
- "entity_ids": {
- "type": "array",
- "items": {
- "type": "string"
- },
- "description": "`sample` only: the entity ids picked. Read each with `GET /v2/entities/user/{entity_id}/profile/`."
- }
- }
- }
- }
- }
- },
- "400": {
- "description": "Unknown or missing `operation`, or profiles are not configured."
- },
- "402": {
- "description": "Payment required."
- },
- "409": {
- "description": "A job is already running, or the Idempotency-Key was used for a different request. Branch on `error.code`."
- },
- "429": {
- "description": "Cooldown. `retry_after_seconds` sits inside `error`."
- },
- "503": {
- "description": "`jobs_unavailable` โ generation is switched off for this project."
- }
- }
- }
- },
- "/v2/profiles/jobs/{job_id}/": {
- "get": {
- "tags": [
- "profiles"
- ],
- "operationId": "profiles_get_job",
- "summary": "Read a generation job",
- "description": "The job nests under `job`. `total` is null until `enumeration_complete`, and `completed` is `succeeded + failed + skipped`.",
- "parameters": [
- {
- "in": "path",
- "name": "job_id",
- "required": true,
- "schema": {
- "type": "string"
- }
- }
- ],
- "responses": {
- "200": {
- "description": "The job.",
- "content": {
- "application/json": {
- "schema": {
- "type": "object",
- "properties": {
- "job": {
- "type": "object",
- "properties": {
- "id": {
- "type": "string"
- },
- "operation": {
- "type": "string"
- },
- "entity_type": {
- "type": "string"
- },
- "status": {
- "type": "string",
- "enum": [
- "QUEUED",
- "RUNNING",
- "SUCCEEDED",
- "PARTIALLY_SUCCEEDED",
- "FAILED",
- "CANCELLED"
- ]
- },
- "total": {
- "type": "integer",
- "nullable": true
- },
- "enumeration_complete": {
- "type": "boolean"
- },
- "completed": {
- "type": "integer"
- },
- "succeeded": {
- "type": "integer"
- },
- "failed": {
- "type": "integer"
- },
- "skipped": {
- "type": "integer"
- }
- }
- }
- }
- }
- }
- }
- },
- "404": {
- "description": "No such job in this project."
- }
- }
- }
}
},
"components": {
@@ -9462,4 +8988,4 @@
}
},
"x-original-swagger-version": "2.0"
-}
+}
\ No newline at end of file
diff --git a/docs/platform/copilot.mdx b/docs/platform/copilot.mdx
deleted file mode 100644
index 3d218ff84..000000000
--- a/docs/platform/copilot.mdx
+++ /dev/null
@@ -1,194 +0,0 @@
----
-title: "Mem0 Copilot"
-description: "Inspect project memories, review configuration changes, and test extraction from the Mem0 dashboard."
-icon: "message"
----
-
-Copilot is an AI assistant in the [Mem0 dashboard](https://app.mem0.ai/dashboard/copilot). Ask it to inspect stored memories, suggest extraction rules and categories, change project settings, or explain the platform SDKs and APIs.
-
-You describe the task in chat. Copilot uses tools to read project data or propose changes. In **Review changes** mode, you approve each change before it runs.
-
-## Start with your project
-
-1. Sign in to the dashboard and select the organization and project you want to work on.
-2. Open **Copilot** in the sidebar.
-3. Select **Review changes** below the message box.
-4. Ask: โShow my current project settings and explain what each one does.โ
-5. Expand an activity card, such as **Read project config**, to see its **Input** and **Result**. Check these results when reviewing an answer or confirming a change.
-
-You can ask about settings or SDK usage with an empty project. Suggestions based on stored data need enough project history to analyze.
-
-## Inspect stored memories
-
-Start with a project overview, then narrow the question:
-
-| Prompt | What to inspect |
-| --- | --- |
-| โSummarize what this project has stored and how it is categorized.โ | The memories and category patterns Copilot reads. Check which records support its summary. |
-| โAnalyze the memories for user alice.โ | Facts stored for `alice`, their categories, and unwanted information. To investigate a missing fact, also provide the original input. |
-| โSearch alice's memories for dietary preferences.โ | Memories relevant to the query within that user's scope. |
-
-Copilot can list memories across the project. Searching by meaning needs a specific User, Agent, App, or Run ID. Select one in **Scope** or name it in your prompt.
-
-Memory lists are paginated, and suggestions use samples. Check the activity results to see which records were read. Ask for more pages when you need to inspect the rest.
-
-### Choose the memory scope
-
-Open **Scope** below the message box. Select an existing ID or type one and choose it.
-
-| Control | Identifies |
-| --- | --- |
-| **User** | The end user whose memories you want to inspect, such as `alice`. |
-| **Agent** | An AI agent associated with the memories. |
-| **App** | An application associated with the memories. |
-| **Run** | A particular execution or session associated with the memories. |
-
-A field set to **any** adds no filter for that entity type. **Clear scope** removes the selections. Scope gives Copilot default IDs to use; you can request a different entity in a message. Check the activity's **Input** to confirm which IDs it used. Adding a test memory requires a **User** ID, even when another entity is selected.
-
-
- Scope selects memories, not separate settings. Categories, extraction instructions, memory depth, and multilingual settings apply to the selected project. Category and extraction suggestions also analyze project data, regardless of the selected entity.
-
-
-See [Entity-scoped memory](/platform/features/entity-scoped-memory) for how these IDs organize memories in your application.
-
-## Review and apply changes
-
-The mode control below the message box determines when changes run:
-
-- **Review changes**: Copilot pauses before changing project configuration or adding a test memory. Read the proposal and choose whether to apply it.
-- **Auto-apply**: Copilot can change settings and add test memories without asking for approval. Check the selected project and scope before using it.
-
-Ask Copilot to show the current settings before requesting an update. In the approval card, review every listed field. Approving the card applies the whole proposal, including fields you did not edit.
-
-| Action | Effect |
-| --- | --- |
-| **Apply change** | Approve the proposed write. Inspect the subsequent result to confirm it succeeded. |
-| **Edit** | When offered, edit extraction instructions or category names and descriptions. Choose **Apply with edits** to submit your revision. |
-| **Discard edits** | Return to the original proposal without applying it. |
-| **Decline** | Reject this proposal without applying it. |
-| **Ask for something else** | Enter feedback and choose **Send**. This declines the current proposal and sends your feedback as a new message. Review the next proposal before applying it. |
-
-Not every field has an inline editor. If a proposal includes both extraction instructions and categories, only the instructions get an editor. The editor cannot apply blank instructions or an empty category list. Use **Ask for something else** to change other fields or request separate proposals.
-
-
- A generated prompt profile contains separate prompts for extraction and summaries. If your project uses one, saving extraction instructions through Copilot deactivates it. Review the replacement rules and test the affected behavior before using them in production.
-
-
-## What Copilot cannot do
-
-Copilot cannot perform these actions, even in **Auto-apply** mode:
-
-- Create or delete API keys.
-- Directly edit or delete existing memories.
-- Export project data.
-- Invite or remove organization or project members, or change their roles and permissions.
-- Create or delete organizations or projects.
-- Change billing details or subscription plans.
-
-Use the dashboard or the relevant platform API for these tasks. Copilot can explain the steps or point you to documentation, but it cannot carry out the actions.
-
-Copilot supports the managed Mem0 platform. It does not help configure or use the [self-hosted open-source library](/open-source/overview).
-
-## Example 1: Stop storing small talk, then test extraction
-
-This walkthrough uses a project where you have noticed greetings or small talk in stored memories. Use a development project when trying configuration changes, since a test user does not isolate project settings.
-
-
-
- Select the project, set **User** to `alice`, and ask:
-
- > Analyze the memories for user alice.
-
- Inspect the returned memories. Identify examples of small talk you want to exclude and useful facts you still want to keep.
-
-
- With **Review changes** selected, ask:
-
- > Update my extraction instructions to ignore greetings and small talk. Keep the existing rules for durable user preferences.
-
- Check for a **Read project config** activity before reviewing the update. If it is missing, ask Copilot to read the current instructions first. If analysis reports insufficient data, ask it to use the rule you provided. You can also set the rule directly through [Custom instructions](/platform/features/custom-instructions).
-
-
- Review the full replacement text. Keep existing rules your application needs. For this test, the relevant rules could look like:
-
- ```text
- Remember the following:
-
- * The user's dietary preferences and food restrictions.
-
- Don't remember the following:
-
- * Greetings and small talk.
- ```
-
- Use **Edit** to adjust the wording, or **Ask for something else** to request a revision.
-
- Choose **Apply change** or **Apply with edits**, then inspect the result to confirm the instructions were saved.
-
-
- Choose a new **User** ID for this test, such as `copilot-extraction-test-01`, and clear any other entity selections. Ask:
-
- > Add this as a user message for copilot-extraction-test-01: โHi! How's your day? I prefer vegetarian meals and avoid peanuts.โ
-
- Review the test-memory proposal and choose **Apply change**.
-
-
- Adding a test memory writes to the selected project. It is not a dry run. Use a dedicated test user so you can find and remove the test data afterward.
-
-
-
- Expand **Add test memory** and inspect **Result**. A `PENDING` status means extraction is still running. Use the returned `event_id` with the [Get Event API](/api-reference/events/get-event) to check progress. Wait for `SUCCEEDED` before evaluating the output. If the event is `FAILED`, inspect its details before retrying.
-
- Then ask:
-
- > List all memories for user copilot-extraction-test-01. Then search that user's memories for dietary preferences.
-
- Check that the memories retain the vegetarian preference and peanut restriction, and exclude the greeting. Inspect the full list as well as search results: a relevant search can hide unwanted small-talk records.
-
- If the output is wrong, describe the mismatch and review another instruction change. Use a new test user for the next attempt so earlier memories do not affect the result. Remove test data afterward through the dashboard or [memory deletion API](/api-reference/memory/delete-memories).
-
-
-
-Test with new inputs after changing settings. Updating configuration is not a cleanup operation for existing memories. See [Custom instructions](/platform/features/custom-instructions) for guidance on writing extraction rules.
-
-## Example 2: Suggest categories and extraction instructions
-
-These workflows sample the selected project's data. Generating a suggestion does not update settings by itself. Copilot can then propose applying it, which follows the selected review mode. Use **Review changes** to inspect suggestions before they are saved.
-
-| Workflow | Data used | Example prompt |
-| --- | --- | --- |
-| Custom categories | Stored memories, excluding deleted memories. | โSuggest custom categories from this project's memories.โ |
-| Extraction instructions | Successful requests to add conversation data, including requests that produced no memories. | โCompare recent add requests with the extracted memories and suggest better extraction instructions.โ |
-
-Category suggestions identify recurring themes. Review the names, descriptions, and examples. Applying a category list replaces the project's previous list; it does not add to it or re-tag existing memories. See [Custom categories](/platform/features/custom-categories) for project and per-call behavior.
-
-Extraction suggestions compare conversation inputs with what was extracted. One add request can produce several memories or none, so the number of add requests is different from the number of stored memories. Keep your application's existing requirements when reviewing the proposal.
-
-Both workflows require enough project data. If a suggestion fails because there is too little data, check the activity's **Result** for the current and required counts. You can still inspect memories, ask SDK/API questions, or provide your own rules instead of requesting a data-based suggestion.
-
-## Example 3: Adjust detail and language
-
-Ask Copilot to read the current settings, then request the change you need:
-
-- **Memory depth** controls the level of detail: **Less**, **Medium**, or **More detailed**. Try โShow my current memory depth, then propose More detailed memories.โ For deciding *which facts* to retain, use extraction instructions.
-- **Multilingual** behavior preserves the user's original language. Try โEnable multilingual behavior so memories preserve the language of the input.โ Test it with a new conversation in the language your application uses.
-
-Both are project settings. Review the proposed values and test a fresh input after applying them. See [Organization and project settings](/api-reference/organizations-projects) for configuration through the API.
-
-## Example 4: Ask SDK and API questions
-
-Include your language and the task, for example:
-
-> Show me how to search memories for user alice with the managed Mem0 Python SDK. Link the documentation you used.
-
-Copilot can look up the official platform documentation. Check the **Browse mem0 docs** and **Read docs page** activities and open the cited pages. If an answer has no sources, ask for them before using the example. The [Platform quickstart](/platform/quickstart) covers adding and searching memories in code.
-
-## Resume a conversation and check message limits
-
-Use **History** to reopen your 50 most recently active chats for the selected project. Chats belong to the person who created them; other project members cannot open them. Use **New chat** to start a separate conversation, or **Delete chat** in history to remove one. Deleting a chat does not undo settings changes or remove test memories.
-
-Message allowances depend on the organization's plan and are shared across its projects and members. They reset at the start of each calendar month in UTC.
-
-For plans with a limit, a usage notice appears once 80% of the allowance is used. Below that point, no counter is shown. At the limit, new messages are disabled until the allowance resets or the plan is upgraded. Follow the notice's upgrade link to review plan options.
-
-Sending feedback through **Ask for something else** counts as a new message. Approving or declining a saved proposal without feedback does not use another message. Test additions and searches also use the platform APIs and remain subject to their normal quotas.
diff --git a/docs/platform/features/async-client.mdx b/docs/platform/features/async-client.mdx
index 964fb1ce5..6effd9995 100644
--- a/docs/platform/features/async-client.mdx
+++ b/docs/platform/features/async-client.mdx
@@ -124,7 +124,7 @@ await client.deleteAll({ userId: "alice" });
- At least one filter (`user_id`, `agent_id`, `app_id`, or `run_id`) is required: calling `delete_all` with no filters raises an error to prevent accidental data loss. You can pass `"*"` as a value to delete all memories for a given entity type (e.g., `user_id="*"` removes memories for every user). A full project wipe requires all four filters set to `"*"`. When multiple entity filters are combined on a single `delete_all` call, only one is currently guaranteed to be honored; scope each call to a single entity id to be safe. Entity IDs are top-level arguments, not `filters`, and an empty or whitespace-only ID raises an error instead of matching every memory.
+ At least one filter (`user_id`, `agent_id`, `app_id`, or `run_id`) is required: calling `delete_all` with no filters raises an error to prevent accidental data loss. You can pass `"*"` as a value to delete all memories for a given entity type (e.g., `user_id="*"` removes memories for every user). A full project wipe requires all four filters set to `"*"`. When multiple entity filters are combined on a single `delete_all` call, only one is currently guaranteed to be honored; scope each call to a single entity id to be safe.
### History
diff --git a/docs/platform/features/byok.mdx b/docs/platform/features/byok.mdx
deleted file mode 100644
index 6a57c6cd8..000000000
--- a/docs/platform/features/byok.mdx
+++ /dev/null
@@ -1,126 +0,0 @@
----
-title: "Bring Your Own Key (BYOK)"
-sidebarTitle: "BYOK"
-description: "Run memory creation on your own LLM provider and model, billed to your own API key."
----
-
-## Overview
-
-With Bring Your Own Key (BYOK), Mem0 runs the LLM calls that turn your messages into memories on a model you choose, using your own API key. Mem0 sends your message text to that provider under your account, and your provider bills you directly. If your key stops working, Mem0 doesn't switch to its own key. The add fails and shows why. Embeddings, search and reranking still run on Mem0.
-
-## Where to find it
-
-BYOK is set per organization, in **Settings โ BYOK** in the [Mem0 dashboard](https://app.mem0.ai/dashboard/settings?tab=org-llm). Only organization owners see this tab. One key covers every project in the organization.
-
-
- Organizations created through the Vercel Marketplace are managed from Vercel and can't use BYOK.
-
-
-## Supported providers
-
-| Provider | What you need | Model |
-|---|---|---|
-| OpenAI | An OpenAI API key | Pick from the list or enter any OpenAI model ID. GPT-6 Luna is recommended for best value. |
-| Anthropic | An Anthropic API key | Pick from the list or enter any Claude model ID. Claude Haiku 5.5 is recommended for best value. |
-| OpenRouter | An OpenRouter API key | Pick from the list or enter any OpenRouter model ID, such as `deepseek/deepseek-v4.1-flash`. DeepSeek V4.1 Flash is recommended for best value. |
-| Azure OpenAI | An API key and your endpoint URL | Your deployment name |
-
-For Azure OpenAI, use your resource's endpoint from the Azure portal, such as `https://your-resource.openai.azure.com/`.
-
-## Set up BYOK
-
-
-
-Go to **Settings โ BYOK** in the dashboard.
-
-
-Pick OpenAI, Anthropic, OpenRouter or Azure OpenAI from the **Provider** list.
-
-
-The **Model** list shows the models we tested, with a **Recommended** tag on our pick for that provider. Under the model, the tab shows its estimated cost per 1,000 adds on your provider account.
-
-To use a model that isn't in the list, choose **Other model ID** and type the model ID exactly as your provider names it. For Azure OpenAI, type your deployment name in **Deployment / Model**.
-
-
-Paste your key into **API key**. For Azure OpenAI, also fill in **Endpoint URL**.
-
-
-Click **Save key**. Mem0 sends a short test request to your provider with your key and model, then saves them. When the test passes, the top of the tab shows your provider and model, such as **Running on OpenAI ยท gpt-6-luna**.
-
-
-
-Mem0 encrypts your key and never shows it again. To change only the model, pick the new model and leave **API key** empty to keep the saved key. To stop using BYOK, click **Remove key**. New adds then run on Mem0's default model, within your plan's limits.
-
-## Errors and rate limits
-
-### When you save a key
-
-If the test request finds one of these problems, Mem0 doesn't save the key:
-
-| Message | What to check |
-|---|---|
-| The provider rejected the API key. Double-check the key and try again. | The key is wrong, revoked, or from a different provider. |
-| The provider couldn't find that model or deployment. Double-check the Model name and try again. | The model ID is misspelled, your account can't use that model, or the Azure deployment doesn't exist on that resource. |
-| Could not reach the endpoint. Double-check the Endpoint URL and try again. | The Azure OpenAI **Endpoint URL** is misspelled, doesn't exist, or isn't reachable. |
-| The Endpoint URL responded unexpectedly (HTTP โฆ). Double-check the Endpoint URL and try again. | The Azure OpenAI **Endpoint URL** doesn't point to an Azure OpenAI resource. |
-| Could not reach the provider. Try again in a moment. | Mem0 couldn't connect to your provider. This is usually brief. |
-| The provider responded unexpectedly (HTTP โฆ). Try again in a moment. | Your provider returned an error Mem0 didn't expect. |
-
-Some problems don't stop the save, because they can be fixed on your provider's side without changing anything in Mem0. In that case Mem0 saves the key and shows a warning at the top of the tab that names your provider. For example, with an OpenAI key:
-
-- **No credit:** "Key saved, but OpenAI says this account has no credit. Adds will fail until you add credit with OpenAI."
-- **Rate limited:** "Key saved, but OpenAI is rate limiting requests right now. Adds may fail until the limit resets."
-
-After you add credit or the limit resets, click **Check again** to run the test again on the saved key.
-
-### When an add fails
-
-Adds run in the background. Each add returns an `event_id`, and you can follow it with [Get Event](/api-reference/events/get-event). When an add fails for one of the reasons below, the event ends as `FAILED` and its `error` field says why:
-
-```json
-{
- "id": "6f1d3a2e-8c4b-4f6a-9d2e-1b7c5a9e0f42",
- "event_type": "ADD",
- "status": "FAILED",
- "error": "The configured LLM provider account is out of quota or credits."
-}
-```
-
-| `error` | What to do |
-|---|---|
-| The configured LLM provider rejected the API credentials. | Save a valid key in **Settings โ BYOK**. |
-| The configured LLM provider account is out of quota or credits. | Add credit with your provider. |
-| The configured LLM model or deployment was not found. | Pick a model your account can use, or fix the Azure deployment name. |
-| The configured LLM provider returned a response that could not be parsed. | Switch to a model from the **Model** list. This model replied in a format Mem0 couldn't read. |
-| The configured LLM credentials could not be read. Please re-save your provider settings. | Save your key again in **Settings โ BYOK**. |
-| Input exceeds the model's context window. | Send shorter messages, or pick a model with a larger context window. |
-
-In the dashboard, open the failed add on the **Requests** page to see the same reason. Mem0 doesn't retry these adds, so send them again after you fix the cause.
-
-### Rate limits and temporary errors
-
-When your provider rate limits a request, times out or returns a server error, Mem0 retries it automatically, so the add can take longer to finish. If this happens often, raise the rate limits on your provider account.
-
-## Choose a model
-
-Three things decide which model fits:
-
-- **Accuracy:** how well the memories a model writes answer questions later.
-- **Cost:** what your provider charges for the calls behind one add.
-- **Latency:** how long it takes from sending an add until its memories show up in search.
-
-We measured these on [LoCoMo](https://github.com/snap-research/locomo), a public benchmark of long conversations, for a limited set of popular models. Your own data can give different results. Based on what we measured, these are our picks: **Best value** balances accuracy and price, **Best under \$1** is the most accurate model under \$1 per 1,000 add requests, and **Best quality** has the highest accuracy.
-
-
-
-
-
-
-The latency above is for adds, which run asynchronously: the add call returns an event ID right away, and the memories become searchable once processing finishes. Search doesn't use your model, and its server-side latency is about 270 ms at p50 and 640 ms at p95.
-
-
-Accuracy against cost for every model we tested. The green line marks the best accuracy available at each price, the gold area holds the models under $2 per 1,000 add requests, and the gray dashed line is Mem0's default model, at 92.5%.
-
-
-
-
diff --git a/docs/platform/features/custom-instructions.mdx b/docs/platform/features/custom-instructions.mdx
index 9acd741f2..8b5b1f35e 100644
--- a/docs/platform/features/custom-instructions.mdx
+++ b/docs/platform/features/custom-instructions.mdx
@@ -153,7 +153,7 @@ Both fields are also accepted per request, overriding the project setting for th
```python Python
client.add(
messages,
- agent_id="support-agent",
+ filters={"agent_id": "support-agent"},
agent_custom_instructions="Only remember which tools errored and why.",
)
```
diff --git a/docs/platform/features/user-profiles.mdx b/docs/platform/features/user-profiles.mdx
deleted file mode 100644
index 1e99f59ea..000000000
--- a/docs/platform/features/user-profiles.mdx
+++ /dev/null
@@ -1,359 +0,0 @@
----
-title: Profiles
-description: "Build a structured, always-current summary of each user from their memories, shaped by a JSON Schema you define."
----
-
-# Profiles
-
-Memories are individual facts. A profile is the summary of all of them for one entity: a single structured object, shaped by a JSON Schema you define, that Mem0 keeps current as new memories arrive.
-
-Search answers "what did this user say about X". A profile answers "who is this user", in one read, with no query to write.
-
-
- **Use profiles whenโฆ**
- - You want to personalize a first response, before the user says anything in this session.
- - You need a compact object to drop into a prompt instead of a list of memories.
- - You want the same fields for every user, so your code can rely on their shape.
-
-
-
- User Profiles are in **beta** and available on request. To enable them for your
- organization, contact [support@mem0.ai](mailto:support@mem0.ai).
-
-
-## How it works
-
-1. You define a **schema**: the fields a profile should contain, each with a description.
-2. Mem0 builds each entity's profile from their memories, and rebuilds it as new memories arrive.
-3. You read the profile whenever you need it.
-
-Generation is **asynchronous**. A profile is not ready the instant an entity's first memory lands, so a read tells you where it is with a `status` rather than failing.
-
-## Define the schema
-
-The schema is JSON Schema. Every property needs a `description` โ that is what tells the model how to fill the field, so a vague description gives a vague profile.
-
-
-```python Python
-from mem0 import MemoryClient
-
-client = MemoryClient()
-
-client.update_profile_settings(
- enabled=True,
- schema={
- "type": "object",
- "properties": {
- "communication_style": {
- "type": "string",
- "description": "How the user prefers to be addressed: terse, detailed, formal, casual",
- },
- "expertise_areas": {
- "type": "array",
- "items": {"type": "string"},
- "description": "Subjects the user demonstrates working knowledge of",
- },
- "current_goals": {
- "type": "array",
- "items": {"type": "string"},
- "description": "What the user is actively trying to accomplish",
- },
- },
- },
- custom_instructions="Prefer durable traits over one-off remarks.",
-)
-```
-
-```typescript TypeScript
-import MemoryClient from "mem0ai";
-
-const client = new MemoryClient({ apiKey: "your-api-key" });
-
-await client.updateProfileSettings({
- enabled: true,
- schema: {
- type: "object",
- properties: {
- communication_style: {
- type: "string",
- description:
- "How the user prefers to be addressed: terse, detailed, formal, casual",
- },
- expertise_areas: {
- type: "array",
- items: { type: "string" },
- description: "Subjects the user demonstrates working knowledge of",
- },
- current_goals: {
- type: "array",
- items: { type: "string" },
- description: "What the user is actively trying to accomplish",
- },
- },
- },
- customInstructions: "Prefer durable traits over one-off remarks.",
-});
-```
-
-
-
- Your schema's property names reach the API exactly as you write them. The SDKs do not rewrite them, so a profile always comes back with the field names you chose.
-
-
-Only the fields you pass are written. To turn the feature off without touching your schema, send `enabled` alone.
-
-## Read a profile
-
-
-```python Python
-result = client.get_profile("alice")
-
-if result["status"] == "succeeded":
- print(result["profile"])
-else:
- print("not ready:", result["status"])
-```
-
-```typescript TypeScript
-const result = await client.getProfile({ entityId: "alice" });
-
-if (result.status === "succeeded") {
- console.log(result.profile);
-} else {
- console.log("not ready:", result.status);
-}
-```
-
-
-A response looks like this:
-
-```json
-{
- "profile": {
- "communication_style": "terse",
- "expertise_areas": ["distributed systems", "postgres"],
- "current_goals": ["cut p99 latency", "migrate off the legacy queue"]
- },
- "status": "succeeded",
- "entity_type": "user",
- "entity_id": "alice",
- "updated_at": "2026-02-08T10:30:00Z",
- "generation_count": 3
-}
-```
-
-`generation_count` is how many times this profile has been (re)generated โ `0` before the first generation completes.
-
-### Always branch on `status`
-
-`profile` is empty unless `status` is `succeeded`. Check the status rather than the emptiness of the object, so a profile that is merely still building is not mistaken for a user you know nothing about.
-
-| `status` | Meaning | What to do |
-|---|---|---|
-| `succeeded` | Profile is built and current | Use it |
-| `pending` | Generation is queued or running | Read again shortly |
-| `insufficient_data` | Not enough memories to say anything yet | Fall back to defaults |
-| `not_enabled` | Profiles are off for this project | Enable them in settings |
-| `failed` | The last generation did not complete | Retry, or trigger a new one |
-
-A `404` means only that no such entity exists in your project.
-
-## Generate a profile on demand
-
-Profiles are built once an entity has accumulated enough messages, so a brand-new user has none during their first few interactions. Trigger one directly to close that gap:
-
-
-```python Python
-client.generate_profile("alice")
-```
-
-```typescript TypeScript
-await client.generateProfile({ entityId: "alice" });
-```
-
-
-The call returns as soon as the work is queued. Poll the read endpoint and branch on `status`.
-
-## Test a schema before applying it
-
-A schema that reads well can still produce disappointing profiles. Sample a few real entities and inspect the output before committing to it.
-
-Sampling is asynchronous: the call returns a job as soon as it is queued. Poll `status_url` until the job is terminal, then read each sampled entity's profile:
-
-
-```python Python
-import time
-
-job = client.sample_profiles(limit=5)
-
-# Poll until the sample job reaches a terminal state (job status is UPPERCASE).
-TERMINAL = {"SUCCEEDED", "PARTIALLY_SUCCEEDED", "FAILED", "CANCELLED"}
-deadline = time.time() + 120
-while True:
- status = client.get_profile_job(job["status_url"])["job"]
- if status["status"] in TERMINAL:
- break
- if time.time() > deadline:
- raise TimeoutError("Sample job did not finish in time")
- time.sleep(3)
-
-print(status["status"], status["succeeded"], "of", status["total"])
-
-# The create response lists the sampled entities; read each one's saved profile.
-for entity_id in job.get("entity_ids", []):
- print(client.get_profile(entity_id))
-```
-
-```typescript TypeScript
-const job = await client.sampleProfiles({ limit: 5 });
-
-// Poll until the sample job reaches a terminal state (job status is UPPERCASE).
-const TERMINAL = ["SUCCEEDED", "PARTIALLY_SUCCEEDED", "FAILED", "CANCELLED"];
-const deadline = Date.now() + 120_000;
-let status;
-while (true) {
- status = (await client.getProfileJob(job.statusUrl)).job;
- if (TERMINAL.includes(status.status)) break;
- if (Date.now() > deadline)
- throw new Error("Sample job did not finish in time");
- await new Promise((resolve) => setTimeout(resolve, 3000));
-}
-
-console.log(status.status, status.succeeded, "of", status.total);
-
-// The create response lists the sampled entities; read each one's saved profile.
-for (const entityId of job.entityIds ?? []) {
- console.log(await client.getProfile({ entityId }));
-}
-```
-
-
-These are real generations. The profiles are saved to those entities and count toward your usage, so sampling is not wasted work and not a free dry run. A sample covers up to 10 entities and cannot be repeated immediately.
-
-## Apply a new schema to existing entities
-
-A new schema shapes the next generation. Profiles that already exist keep their values until their entity is generated again.
-
-Each entity picks the new schema up as it sends more memories, and you can generate one now with `generate_profile`.
-
-
-Rebuilding every profile in a project at once is not available yet. Refresh profiles one entity at a time with `generate_profile`, or let each one update on its own as its entity sends more memories.
-
-
-## When profiles update
-
-You never call an "update profile" endpoint โ Mem0 keeps each profile current for you. Two things drive it:
-
-- **Automatically, as memories accumulate.** Mem0 refreshes an entity's profile after roughly every **10 messages** it receives, folding the new memories into the existing profile. There is no schedule to wait for and no extra call to make: the same `add` you already do keeps the profile moving.
-- **On demand.** Call `generate_profile` to build or refresh a profile immediately โ useful for a brand-new entity that has not yet crossed the automatic threshold.
-
-Generation is **asynchronous and incremental**. A refresh runs in the background a short while after its trigger, so a read taken immediately after an `add` may still show the previous profile (or `pending`). Branch on `status` rather than assuming the latest memory is already reflected.
-
-
- Updates are **incremental**, not a full rebuild each time โ Mem0 merges what it newly learns into the stored profile and keeps the fields your schema still defines. After a schema change, existing profiles pick it up as their entities send more memories, or when you call `generate_profile` โ see [Apply a new schema to existing entities](#apply-a-new-schema-to-existing-entities).
-
-
-## Use a profile in a prompt
-
-The point of the structure is that it drops straight into a prompt:
-
-```python
-result = client.get_profile(user_id)
-
-if result["status"] == "succeeded":
- profile = result["profile"]
- system_prompt = f"""You are helping {user_id}.
-Communication style: {profile.get("communication_style", "unknown")}
-Areas of expertise: {", ".join(profile.get("expertise_areas", []))}
-Current goals: {", ".join(profile.get("current_goals", []))}
-
-Match their style and do not explain what they already know."""
-else:
- system_prompt = "You are a helpful assistant."
-```
-
-## Writing a schema that works
-
-- **Describe every field.** The description is the instruction; without it the model guesses.
-- **Prefer durable traits.** "Prefers dark mode" ages well; "is annoyed today" does not.
-- **Keep it small.** Ten focused fields beat forty speculative ones, and cost less to generate.
-- **Say what the field is not.** A description that rules out the near-miss interpretation is worth more than one that only states the obvious.
-- **Sample before you commit.** It is the only way to see what your descriptions actually produce.
-
-
- A schema has a size budget of roughly **10,000 tokens** of serialized JSON โ the whole schema is sent to the model on every generation, so a handful of verbose fields can cost more than many terse ones. Oversized schemas are rejected on save.
-
-
-## Availability
-
-The feature is in beta and enabled per organization on request โ see the note at the top of this page.
-
-Once it is on, an entity gets a profile when two more things hold:
-
-- profiles are **enabled** with a schema for the project (see [Define the schema](#define-the-schema)), and
-- the memory is scoped to an entity โ a `user_id`.
-
-On a project where profiles are turned off, a read returns `status: not_enabled` rather than an error, so you can call it unconditionally and branch on the status.
-
-## Settings reference
-
-| Argument | Type | Description |
-|---|---|---|
-| `enabled` | boolean | Whether profile generation runs for the project |
-| `schema` | object | JSON Schema describing the profile. Every property needs a `description` |
-| `custom_instructions` | string | Extra guidance applied during extraction |
-
-`enabled` is project-wide. `schema` and `custom_instructions` apply to user
-profiles, so the stored settings nest them under `entities`:
-
-```json
-{
- "enabled": true,
- "entities": {
- "user": {
- "schema": { "type": "object", "properties": { "...": {} } },
- "custom_instructions": "Prefer durable traits over one-off remarks."
- }
- },
- "capabilities": { "full_rebuild": false }
-}
-```
-
-That is what a read returns and what a write accepts. The SDKs take the fields
-flat and nest them for you, so a schema you write with
-`update_profile_settings` comes back unchanged from `get_profile_settings`.
-
-
- Profile settings are per project. An API key is scoped to one project, so profiles never cross a project boundary.
-
-
-## FAQ
-
-**Do I need to change my `add` or `search` calls to use profiles?**
-No. Profiles are built from the memories you already add. You define a schema once and read the profile when you need it โ your ingestion and retrieval code is unchanged.
-
-**Why is `profile` empty even though the entity has memories?**
-Generation is asynchronous and needs enough to work with. Branch on `status`: `pending` means it is still building, and `insufficient_data` means there are not yet enough memories to fill the schema. Read again shortly, or call `generate_profile` to build one now.
-
-**Is sampling free?**
-No. `sample_profiles` runs real generations against real memories and **keeps** the profiles it produces, so it counts toward your usage like any other generation. It exists to check a schema on a few entities before you commit to it โ not as a zero-cost dry run.
-
-**Does changing the schema rewrite existing profiles?**
-No. A schema change applies to the next generation. An existing profile keeps its values until its entity is generated again, which happens as that entity sends more memories, or when you call `generate_profile` for it.
-
-**What happens to a field I remove from the schema?**
-It stops being maintained. On an entity's next generation, fields your schema no longer defines are pruned from the stored profile โ so keep a field in the schema for as long as you want its value kept.
-
-**How current is a profile?**
-It refreshes automatically as memories accumulate (about every 10 messages for an entity), plus any on-demand `generate_profile` calls. Because refreshes run in the background, expect a short delay after the triggering `add` rather than an instant update.
-
-## Related
-
-
-
- How users, agents, apps and runs partition memories.
-
-
- Steer what Mem0 extracts in the first place.
-
-
diff --git a/docs/platform/overview.mdx b/docs/platform/overview.mdx
index 9bc34aea9..ddb5ff405 100644
--- a/docs/platform/overview.mdx
+++ b/docs/platform/overview.mdx
@@ -50,8 +50,8 @@ For the full pipeline, see [How Mem0 works](/core-concepts/how-it-works).
Get an API key and save your first memory.
-
- Organize memories by user, agent, app, and run.
+
+ How user, agent, app, and run memory differ.
The core memory operations, end to end.
diff --git a/docs/platform/platform-vs-oss.mdx b/docs/platform/platform-vs-oss.mdx
index 8a79ab351..92bcc27b4 100644
--- a/docs/platform/platform-vs-oss.mdx
+++ b/docs/platform/platform-vs-oss.mdx
@@ -39,7 +39,7 @@ The core memory loop is identical on both: `add`, `search`, `get`, `get_all`, `u
- **Entity scoping** by `user_id`, `agent_id`, and `run_id`
- **Filter grouping**: both accept `AND`/`OR`/`NOT` wrappers, both implicitly AND a flat multi-key filter like `{"user_id": "alice", "agent_id": "a1"}`, and both accept `*` as a wildcard value. Which fields you may filter on, and which operators each field accepts, differ (see below)
- **Entity-aware ranking**: both extract entities from memory text and use shared entities to boost related results at search time
-- **Multimodal input**, **memory expiration** (`expiration_date`), **reranking**, and **custom extraction instructions** (`custom_instructions`)
+- **Multimodal input**, **memory expiration** (`expiration_date`), **reranking**, **procedural memory** (Python), and **custom extraction instructions** (`custom_instructions`)
- Python and JavaScript SDKs, plus a REST API (self-hosted via `server/`, or hosted)
## What's actually different
diff --git a/docs/platform/pricing.mdx b/docs/platform/pricing.mdx
deleted file mode 100644
index 5d27d8252..000000000
--- a/docs/platform/pricing.mdx
+++ /dev/null
@@ -1,96 +0,0 @@
----
-title: "Pricing FAQ"
-sidebarTitle: "Pricing"
-description: "Frequently asked questions about Mem0's plans, limits and using your own LLM key."
-icon: "credit-card"
----
-
-## Existing paid plans
-
-
-
- Nothing. Your price, limits, extra usage and billing date stay the same, and you can still turn extra usage on or off from your dashboard. These plans are no longer sold to new accounts.
-
-
- Plan changes now go through our team. If you need higher limits or more features, [talk to us](https://app.mem0.ai/enterprise?ref=docs) and we'll set up a custom plan. If you cancel, your account moves to the free plan, any extra usage up to then is billed on your last invoice, and the old plan can't be restarted.
-
-
-
-## Free plan
-
-
-
- For your first 30 days, Mem0 pays for the model calls, with limits of 10,000 adds and 1,000 retrievals a month. After that, connect your own LLM key to keep adding memories, and your limits go up to 50,000 adds and 10,000 retrievals a month at no charge from Mem0. You can connect a key at any time, including during your first 30 days.
-
-
- If you signed up before October 26, 2026, you have until November 25, 2026. Otherwise, your 30 days start on the day you sign up.
-
-
- Your memories stay, and searches keep working up to 1,000 a month. New adds return an error until you connect a key.
-
-
- Calls past the limit return an error until your limits reset next month.
-
-
- Yes. We email the organization owner at 50%, 80% and 100% of each monthly limit, and of your usage-based billing cap.
-
-
-
-## Your own LLM key
-
-
-
- Adding a memory runs language model calls that extract and organize it. With your key, those calls bill to your provider account. That is how we keep the free plan free at higher limits.
-
-
- It depends on the model. Our recommended models cost about \$3.55 to \$5.34 per 1,000 adds: GPT-6 Luna on OpenAI, Claude Haiku 5.5 on Anthropic and DeepSeek V4.1 Flash on OpenRouter. The [BYOK guide](/platform/features/byok#choose-a-model) compares accuracy and cost across every model we tested.
-
-
- OpenAI, Anthropic, Azure OpenAI and OpenRouter.
-
-
- Yes. The text you add is sent to your provider under your account and its terms. Mem0 stores your key encrypted, never shows it again after you save it, and you can remove it at any time.
-
-
- Organization owners, in **Settings โ BYOK**. One key covers every project in the organization.
-
-
- Adds fail with a reason you can see in the dashboard, and we email the organization owner, at most once a day. Mem0 doesn't switch to its own key, so send the failed adds again once the key works. Searches keep working.
-
-
- Your limits go back to the ones without a key, and usage-based billing stops until you connect a key again. Anything you used before removing it is still billed on your next invoice.
-
-
-
-## Vercel
-
-
-
- Nothing changes. Your plan is billed through Vercel. Organizations created through the Vercel Marketplace are managed from Vercel and can't use BYOK.
-
-
-
-## Need more
-
-
-
- Once you've connected your own key, you can turn on usage-based billing from your dashboard and set a monthly spending cap. For SSO, an SLA or a contract, [talk to us](https://app.mem0.ai/enterprise?ref=docs).
-
-
- You pay only for adds and retrievals above your free limits, billed once a month. The rate is shown when you turn it on, and those extra calls stop when you reach your monthly cap.
-
-
- Yes, at any time from your dashboard. If you turn it off, you're still billed for what you used before.
-
-
-
-## Learn more
-
-
-
- Connect your provider key, pick a model and fix failed adds.
-
-
- Accuracy, cost and latency for every model we tested.
-
-
diff --git a/docs/templates/api_reference_template.mdx b/docs/templates/api_reference_template.mdx
index 67a83d556..d04412863 100644
--- a/docs/templates/api_reference_template.mdx
+++ b/docs/templates/api_reference_template.mdx
@@ -4,7 +4,7 @@ description: "Standard layout for documenting Mem0 API endpoints."
icon: "code"
---
-# API Reference Template
+# Api Reference Template
API reference pages document a single endpoint contract. Present metadata, request/response examples, and recovery guidance without narrative detours.
diff --git a/docs/templates/feature_guide_template.mdx b/docs/templates/feature_guide_template.mdx
index 7582f3a47..fc502f88b 100644
--- a/docs/templates/feature_guide_template.mdx
+++ b/docs/templates/feature_guide_template.mdx
@@ -124,7 +124,7 @@ Walk through a real request/response. Include sample payloads and highlight nota
{/* DEBUG: verify CTA targets */}
-
+
Understand how Mem0 ranks memories under the hood.
diff --git a/docs/templates/parameters_reference_template.mdx b/docs/templates/parameters_reference_template.mdx
index b31d1b442..f86cb7745 100644
--- a/docs/templates/parameters_reference_template.mdx
+++ b/docs/templates/parameters_reference_template.mdx
@@ -38,6 +38,7 @@ client.memories.add(
user_id: str,
memory: str,
metadata: Optional[dict] = None,
+ memory_type: Literal["session", "long_term"] = "session",
)
```
@@ -46,13 +47,13 @@ await mem0.memories.add({
userId: string;
memory: string;
metadata?: Record;
+ memoryType?: "session" | "long_term";
});
```
- [Describe defaults supported by this operation and SDK. Do not infer a
- memory type or retention policy from a scoping identifier.]
+ Defaults to session memories. Override `memory_type` for long-term storage.
@@ -66,6 +67,7 @@ await mem0.memories.add({
| `user_id` | string | Yes | Unique identifier for the end user. | Must match follow-up operations. |
| `memory` | string | Yes | Content to persist. | Managed & OSS. Markdown allowed. |
| `metadata` | object | No | Key-value pairs for filters. | OSS stores as JSONB; limit to 2KB. |
+| `memory_type` | string | No | Retention bucket | Platform supports `shared`. |
Set `ttl_seconds` when you need memories to expire automatically (OSS only).
diff --git a/docs/vibecoding.mdx b/docs/vibecoding.mdx
index a5bf80016..50eb08e04 100644
--- a/docs/vibecoding.mdx
+++ b/docs/vibecoding.mdx
@@ -96,8 +96,8 @@ time. Storage: vector embeddings.
**Architecture Overview:**
- Memory is scoped by user_id, agent_id, or run_id
- Core operations: add, search, update, delete
-- Store preferences, facts, and past interactions; use run_id to scope a
- session. Platform does not expose a memory_type selector.
+- Memory types: factual (preferences, facts), episodic (past interactions),
+ semantic (concept relationships), working (session state)
- Integration pattern: retrieve relevant memories โ generate response โ store
new memories
diff --git a/examples/mem0-demo/package.json b/examples/mem0-demo/package.json
index 32366bb8b..ec5b7c61c 100644
--- a/examples/mem0-demo/package.json
+++ b/examples/mem0-demo/package.json
@@ -28,7 +28,7 @@
"clsx": "^2.1.1",
"js-cookie": "^3.0.6",
"lucide-react": "^0.477.0",
- "next": "15.5.28",
+ "next": "15.5.21",
"react": "^19.0.0",
"react-dom": "^19.0.0",
"react-markdown": "^10.0.1",
diff --git a/examples/misc/movie_recommendation_grok3.py b/examples/misc/movie_recommendation_grok3.py
index abd383a47..bb4edbc42 100644
--- a/examples/misc/movie_recommendation_grok3.py
+++ b/examples/misc/movie_recommendation_grok3.py
@@ -45,11 +45,11 @@ grok_client = OpenAI(
def recommend_movie_with_memory(user_id: str, user_query: str):
# Retrieve prior memory about movies
- past_memories = memory.search("movie preferences", filters={"user_id": user_id})
+ past_memories = memory.search("movie preferences", user_id=user_id)
prompt = user_query
- if past_memories["results"]:
- prompt += f"\nPreviously, the user mentioned: {[m['memory'] for m in past_memories['results']]}"
+ if past_memories:
+ prompt += f"\nPreviously, the user mentioned: {past_memories}"
# Generate movie recommendation using Grok 3
response = grok_client.chat.completions.create(model="grok-3-beta", messages=[{"role": "user", "content": prompt}])
diff --git a/examples/misc/strands_agent_aws_elasticache_neptune.py b/examples/misc/strands_agent_aws_elasticache_neptune.py
index 37f1a2fb8..01fde8614 100644
--- a/examples/misc/strands_agent_aws_elasticache_neptune.py
+++ b/examples/misc/strands_agent_aws_elasticache_neptune.py
@@ -198,7 +198,7 @@ def search_memory_tool(query: str, user_id: str = "user") -> str:
Relevant vector memories found or message if none found
"""
try:
- results = m.search(query, filters={"user_id": user_id})
+ results = m.search(query, user_id=user_id)
if isinstance(results, dict) and 'results' in results:
memory_list = results['results']
@@ -245,7 +245,7 @@ def search_graph_memory_tool(query: str, user_id: str = "user") -> str:
"""
try:
graph_query = f"relationships connections {query}"
- results = m.search(graph_query, filters={"user_id": user_id})
+ results = m.search(graph_query, user_id=user_id)
if isinstance(results, dict) and 'results' in results:
memory_list = results['results']
@@ -290,7 +290,7 @@ def get_all_memories_tool(user_id: str = "user") -> str:
All memories for the user or message if none found
"""
try:
- all_memories = m.get_all(filters={"user_id": user_id})
+ all_memories = m.get_all(user_id=user_id)
if isinstance(all_memories, dict) and 'results' in all_memories:
memory_list = all_memories['results']
diff --git a/examples/misc/vllm_example.py b/examples/misc/vllm_example.py
index 610edd2b7..635cb550e 100644
--- a/examples/misc/vllm_example.py
+++ b/examples/misc/vllm_example.py
@@ -107,16 +107,16 @@ def main():
for query in search_queries:
print(f"\nQuery: {query}")
- memories = memory.search(query=query, filters={"user_id": "user_123"})
+ memories = memory.search(query=query, user_id="user_123")
- for memory_item in memories["results"]:
+ for memory_item in memories:
print(f" - {memory_item['memory']}")
print("\n--> Getting all memories for user...")
- all_memories = memory.get_all(filters={"user_id": "user_123"})
- print(f"Total memories stored: {len(all_memories['results'])}")
+ all_memories = memory.get_all(user_id="user_123")
+ print(f"Total memories stored: {len(all_memories)}")
- for memory_item in all_memories["results"]:
+ for memory_item in all_memories:
print(f" - {memory_item['memory']}")
print("\n--> vLLM integration demo completed successfully!")
diff --git a/examples/notebooks/user-profiles.ipynb b/examples/notebooks/user-profiles.ipynb
deleted file mode 100644
index 72ef7580d..000000000
--- a/examples/notebooks/user-profiles.ipynb
+++ /dev/null
@@ -1,764 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# User Profiles โ live demo\n",
- "\n",
- "A **profile** is a structured JSON document about ONE user, filled by an LLM from that\n",
- "user's memories, shaped by a JSON Schema you supply.\n",
- "\n",
- "Search answers *\"what did this user say about X\"*. A profile answers *\"who is this\n",
- "user\"*, in one read, with no query to write โ and it is available on the first turn of a\n",
- "session, before the user has said anything.\n",
- "\n",
- "**What this notebook does:** feed a user 12 conversation turns, watch a profile get\n",
- "generated from them, add 6 more turns that contradict the first set, and watch the\n",
- "profile rewrite itself. Then it shows every way the API says no.\n",
- "\n",
- "**You need:** an API key, and a project on the **Pro plan or higher**. Never commit one.\n",
- "\n",
- "> Set `MEM0_API_KEY`, and `MEM0_API_HOST` if you are pointing at a sandbox rather than\n",
- "> production. The cells below read both from the environment.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "> **Use a disposable project.** This notebook overwrites the project's profile settings\n",
- "> (enabled, schema, custom instructions). The last cell restores the values saved at the\n",
- "> start, but only if you reach it: if a cell fails midway, the project keeps the demo\n",
- "> schema until you run the cleanup cell or reset it yourself. Do not point it at a\n",
- "> project other people or production traffic depend on.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# This notebook drives the SDK from this worktree, not the published mem0ai:\n",
- "# the profile fixes below are not released yet.\n",
- "%pip install -q -e ../..\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": "import json\nimport os\nimport time\nimport uuid\n\nimport mem0\nfrom mem0 import MemoryClient\n\nAPI_KEY = os.environ.get(\"MEM0_API_KEY\")\nif not API_KEY:\n import getpass\n\n API_KEY = getpass.getpass(\"API key: \")\n\nclient = MemoryClient(api_key=API_KEY, host=os.environ.get(\"MEM0_API_HOST\") or None)\n\n# Fresh id each run, so nothing below is stale from a previous pass.\nUSER_ID = f\"demo_{uuid.uuid4().hex[:8]}\"\n\n# Snapshot the project's profile settings up front. This notebook overwrites the\n# shared project schema/instructions/enabled below; the cleanup cell restores this.\nORIGINAL_SETTINGS = client.get_profile_settings()\n\nprint(\"sdk :\", mem0.__file__) # must be this worktree\nprint(\"host :\", client.host)\nprint(\"demo user:\", USER_ID)"
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 1. Define the schema\n",
- "\n",
- "The schema is handed to the model as a **tool definition**, and each field's\n",
- "`description` is the only instruction the model gets about what belongs there. An\n",
- "undescribed field is a field the model guesses at.\n",
- "\n",
- "Rules worth knowing:\n",
- "\n",
- "- root `type: object` with a **non-empty** `properties` โ an empty one is refused, because\n",
- " it would bill you to extract nothing\n",
- "- the root keys `_profile_config_version` and `entities` are **reserved** and rejected:\n",
- " they name the storage envelope, so a schema using them could not be read back\n",
- " unambiguously\n",
- "- keep it small. The whole schema is sent to the model on every generation\n",
- "\n",
- "Descriptions are **not** enforced on write in this build โ a property without one is\n",
- "accepted and then quietly underfilled at generation time. Section F1 demonstrates it.\n",
- "Treat descriptions as your job, not the validator's.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "SCHEMA = {\n",
- " \"type\": \"object\",\n",
- " \"properties\": {\n",
- " \"occupation\": {\n",
- " \"type\": \"string\",\n",
- " \"description\": \"The person's current job title, in one short phrase.\",\n",
- " },\n",
- " \"location\": {\n",
- " \"type\": \"string\",\n",
- " \"description\": \"The city or region the person currently lives in.\",\n",
- " },\n",
- " \"interests\": {\n",
- " \"type\": \"array\",\n",
- " \"items\": {\"type\": \"string\"},\n",
- " \"description\": \"Hobbies and topics they return to, as short lowercase tags.\",\n",
- " },\n",
- " \"dietary_restrictions\": {\n",
- " \"type\": \"array\",\n",
- " \"items\": {\"type\": \"string\"},\n",
- " \"description\": \"Foods the person avoids, and why, if they said.\",\n",
- " },\n",
- " \"communication_style\": {\n",
- " \"type\": \"string\",\n",
- " \"enum\": [\"concise\", \"detailed\", \"casual\", \"formal\"],\n",
- " \"description\": \"How this person prefers to be answered.\",\n",
- " },\n",
- " \"expertise_level\": {\n",
- " \"type\": \"string\",\n",
- " \"enum\": [\"beginner\", \"intermediate\", \"advanced\"],\n",
- " \"description\": \"Their technical depth, judged from how they discuss their work.\",\n",
- " },\n",
- " },\n",
- "}\n",
- "\n",
- "settings = client.update_profile_settings(\n",
- " enabled=True,\n",
- " schema=SCHEMA,\n",
- " custom_instructions=(\n",
- " \"Prefer facts the person stated outright over anything inferred. \"\n",
- " \"Leave a field empty rather than guessing.\"\n",
- " ),\n",
- ")\n",
- "\n",
- "# Sorted, because JSONB storage does not preserve the key order you sent.\n",
- "# Compare a stored schema by SET, never by string or by key order.\n",
- "stored = settings[\"entities\"][\"user\"][\"schema\"]\n",
- "print(\"schema fields:\", sorted(stored[\"properties\"]))\n",
- "print(\"enabled :\", settings[\"enabled\"])\n",
- "print(\"capabilities :\", settings[\"capabilities\"])\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "`enabled` is project-wide; `schema` and `custom_instructions` apply to user profiles\n",
- "and are stored under `entities`. The SDK takes them flat and nests them for you, so what\n",
- "you write comes back unchanged from `get_profile_settings()`.\n",
- "\n",
- "Only the arguments you pass are written. To turn the feature off without touching your\n",
- "schema, send `enabled` alone.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 2. The turns\n",
- "\n",
- "Twelve conversation turns for one user. Nothing about `add()` changes โ profiles are a\n",
- "side effect of the normal pipeline.\n",
- "\n",
- "Twelve, not five, because generation fires when an entity crosses a **10-message\n",
- "boundary**. Below that it waits for a flush window measured in hours, and this notebook\n",
- "would sit there.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "TURNS = [\n",
- " (\"user\", \"Hey โ I just moved to Berlin for a new job.\"),\n",
- " (\"assistant\", \"Congratulations! What's the new role?\"),\n",
- " (\"user\", \"Senior data engineer at a logistics company. Mostly Spark and Airflow.\"),\n",
- " (\"assistant\", \"Nice stack. How are you finding the pipelines there?\"),\n",
- " (\"user\", \"Honestly the DAGs are a mess. I've been rewriting the partitioning to cut shuffle.\"),\n",
- " (\"assistant\", \"That usually pays off fast. Anything blocking you?\"),\n",
- " (\"user\", \"Just time. Keep it short when you answer me, I skim everything.\"),\n",
- " (\"assistant\", \"Understood โ short answers from here.\"),\n",
- " (\"user\", \"Outside work I climb most weekends, and I'm learning German.\"),\n",
- " (\"assistant\", \"Bouldering or ropes?\"),\n",
- " (\"user\", \"Bouldering. Also โ I'm vegetarian, so skip meat in any recipe suggestions.\"),\n",
- " (\"assistant\", \"Noted, vegetarian only.\"),\n",
- "]\n",
- "\n",
- "response = client.add(\n",
- " [{\"role\": r, \"content\": c} for r, c in TURNS],\n",
- " user_id=USER_ID,\n",
- ")\n",
- "print(json.dumps(response, indent=2)[:300])\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "The add is **async** โ it returns an `event_id` and the memories do not exist yet. Poll\n",
- "`GET /v1/event/{event_id}/` until it is `SUCCEEDED` or `FAILED`; that, not a sleep, is how\n",
- "you know the add finished. Then let the extracted memories settle.\n",
- "\n",
- "Under load this can take a minute or more, so the cell says plainly whether it ran out of\n",
- "time rather than printing `0 memories` as though that were the answer.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "event_id = response[\"event_id\"]\n",
- "deadline = time.time() + 300\n",
- "\n",
- "# 1. The add itself. Terminal status, not a sleep.\n",
- "event_status = None\n",
- "while time.time() < deadline:\n",
- " event_status = client.client.get(f\"/v1/event/{event_id}/\").json().get(\"status\")\n",
- " if event_status in (\"SUCCEEDED\", \"FAILED\"):\n",
- " break\n",
- " print(f\" add {event_status}\")\n",
- " time.sleep(5)\n",
- "print(f\"add finished: {event_status}\")\n",
- "# Stop here unless the add SUCCEEDED. A failed or unfinished add would otherwise let the\n",
- "# generation below bill for a profile built without these memories.\n",
- "if event_status != \"SUCCEEDED\":\n",
- " raise RuntimeError(f\"add did not succeed (status={event_status}); not generating a profile\")\n",
- "\n",
- "# 2. Extraction lands in batches, so the FIRST non-empty page is not the whole set.\n",
- "# Wait for the count to stop growing instead of breaking on the first result.\n",
- "memories, stable = [], 0\n",
- "while time.time() < deadline:\n",
- " page = client.get_all(filters={\"user_id\": USER_ID}, page_size=50)\n",
- " found = page.get(\"results\", []) if isinstance(page, dict) else page\n",
- " stable = stable + 1 if found and len(found) == len(memories) else 0\n",
- " memories = found\n",
- " if stable >= 2: # two identical polls in a row\n",
- " break\n",
- " print(f\" ... {len(memories)} so far\")\n",
- " time.sleep(5)\n",
- "\n",
- "if memories:\n",
- " print(f\"\\n{len(memories)} memories extracted:\\n\")\n",
- " for m in memories:\n",
- " print(\" \\u2022\", m.get(\"memory\"))\n",
- "else:\n",
- " # Say so. Reporting '0 memories' as a result hides a busy or broken environment\n",
- " # and makes the profile below look like it came from nothing.\n",
- " print(\"\\nNO memories yet โ extraction is still catching up, or the ingestion\")\n",
- " print(\"worker is down. Everything below will report insufficient_data.\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 3. Read the profile\n",
- "\n",
- "Crossing the 10-message boundary should already have queued a generation. Read first โ\n",
- "and note that a known user with no profile yet is a **200 with a status**, not a 404. That\n",
- "distinction is the whole point of the envelope.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "envelope = client.get_profile(USER_ID)\n",
- "print(json.dumps(envelope, indent=2))\n",
- "\n",
- "print(\"\\nstatus vocabulary:\")\n",
- "print(\" succeeded terminal โ a generation ran AND the profile has content\")\n",
- "print(\" pending queued or running\")\n",
- "print(\" failed terminal โ the last generation did not complete\")\n",
- "print(\" not_enabled feature off, or plan below Pro\")\n",
- "print(\" insufficient_data no content to show: no row yet, queued, or a\")\n",
- "print(\" generation that legitimately found nothing\")\n",
- "print()\n",
- "print(\"`succeeded` is decided by the profile BODY, not by generation_count: an\")\n",
- "print(\"empty extraction still increments the counter, so counting generations\")\n",
- "print(\"reports 'done' for a profile with nothing in it.\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "### Force it, rather than waiting\n",
- "\n",
- "`generate_profile()` closes the bootstrapping gap: without it a new user has no profile\n",
- "until their tenth message. One entity, a few seconds.\n",
- "\n",
- "Each call sends a new `Idempotency-Key` unless you pass one, and a new key starts a new job.\n",
- "To retry a dropped request safely, generate the key yourself and pass the same\n",
- "`idempotency_key` on every attempt: the server then returns the original job instead of\n",
- "billing a second one.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "TERMINAL = {\"succeeded\", \"failed\", \"not_enabled\"}\n",
- "\n",
- "\n",
- "def wait_for_profile(entity_id, timeout=300, interval=5, since=None):\n",
- " \"\"\"Poll until terminal.\n",
- "\n",
- " `since` waits for a generation_count ABOVE that value, which is how you wait\n",
- " for an UPDATE rather than accepting the profile you already had.\n",
- "\n",
- " `insufficient_data` is NOT terminal by itself โ it also covers 'queued', so\n",
- " poll through it and give up on the timeout instead.\n",
- " \"\"\"\n",
- " deadline = time.time() + timeout\n",
- " body = None\n",
- " while time.time() < deadline:\n",
- " body = client.get_profile(entity_id)\n",
- " status = (body.get(\"status\") or \"\").lower()\n",
- " count = body.get(\"generation_count\") or 0\n",
- " fresh = count > since if since is not None else True\n",
- " if status == \"succeeded\" and fresh:\n",
- " return body\n",
- " if status in (\"failed\", \"not_enabled\"):\n",
- " raise RuntimeError(f\"generation stopped: {status}\")\n",
- " print(f\" ... {status} (generation_count={count})\")\n",
- " time.sleep(interval)\n",
- " raise TimeoutError(f\"not ready in {timeout}s: {body}\")\n",
- "\n",
- "\n",
- "print(json.dumps(client.generate_profile(USER_ID), indent=2))\n",
- "print(\"\\npolling...\")\n",
- "\n",
- "try:\n",
- " body = wait_for_profile(USER_ID)\n",
- " print(\"\\n=== PROFILE ===\")\n",
- " print(json.dumps(body[\"profile\"], indent=2))\n",
- " print(f\"\\nstatus={body['status']} generations={body['generation_count']} updated={body['updated_at']}\")\n",
- "except TimeoutError as e:\n",
- " # Say so plainly and let the rest of the notebook skip, rather than raising\n",
- " # a NameError in every cell below and burying the real cause.\n",
- " body = None\n",
- " print(f\"\\nNO PROFILE: {e}\")\n",
- " print(\"Generation never finished. Usually the ingestion worker is down, or\")\n",
- " print(\"this project has no memories for the user yet.\")\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# The model must not invent fields outside your schema โ the forced tool call is\n",
- "# what makes that structural rather than a request.\n",
- "if body is None:\n",
- " print(\"skipped โ no profile was generated above\")\n",
- "else:\n",
- " extra = set(body[\"profile\"]) - set(SCHEMA[\"properties\"])\n",
- " print(\"fields outside the schema:\", extra or \"none\")\n",
- "\n",
- " # A forced JSON-Schema response makes the model emit SOMETHING for every property,\n",
- " # so 'I found nothing' arrives as a type default: 0, \"\", [].\n",
- " filled = {k: v for k, v in body[\"profile\"].items() if v not in (None, \"\", [], {}, 0)}\n",
- " print(f\"genuinely populated: {len(filled)}/{len(SCHEMA['properties'])} -> {list(filled)}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 4. Now watch it update\n",
- "\n",
- "Six more turns that contradict and extend what we already know: a promotion, a move, a\n",
- "dropped hobby. A profile is a living document, not an append-only log โ the model gets the\n",
- "memories and rewrites the whole thing.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "if body is None:\n",
- " print(\"skipped โ no profile was generated above\")\n",
- "else:\n",
- " before = body[\"generation_count\"]\n",
- "\n",
- " MORE_TURNS = [\n",
- " (\"user\", \"Update โ I got promoted to staff engineer last week.\"),\n",
- " (\"assistant\", \"Congratulations. Same team?\"),\n",
- " (\"user\", \"Same company, but I'm relocating to Munich for it.\"),\n",
- " (\"assistant\", \"Big move. How do you feel about it?\"),\n",
- " (\"user\", \"Good. I've stopped climbing though โ knee injury. Picked up cycling instead.\"),\n",
- " (\"assistant\", \"Sorry about the knee. Cycling's kinder on it.\"),\n",
- " ]\n",
- "\n",
- " followup = client.add(\n",
- " [{\"role\": r, \"content\": c} for r, c in MORE_TURNS],\n",
- " user_id=USER_ID,\n",
- " )\n",
- "\n",
- " # Wait for the add to land before triggering: a generation queued before the new\n",
- " # memories exist rewrites the profile from the OLD ones and looks like a no-op.\n",
- " deadline = time.time() + 300\n",
- " status = None\n",
- " while time.time() < deadline:\n",
- " status = client.client.get(f\"/v1/event/{followup['event_id']}/\").json().get(\"status\")\n",
- " if status in (\"SUCCEEDED\", \"FAILED\"):\n",
- " break\n",
- " time.sleep(5)\n",
- " print(\"follow-up add:\", status)\n",
- " # Generating after a FAILED or unfinished add bills for a profile built from the OLD\n",
- " # memories only, so stop instead.\n",
- " if status != \"SUCCEEDED\":\n",
- " raise RuntimeError(f\"follow-up add did not succeed (status={status}); not regenerating\")\n",
- " time.sleep(15) # let extraction settle\n",
- "\n",
- " print(json.dumps(client.generate_profile(USER_ID), indent=2))\n",
- " print(f\"\\npolling for a NEW generation (count must exceed {before})...\")\n",
- " updated = wait_for_profile(USER_ID, since=before)\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "if body is None:\n",
- " print(\"skipped โ no profile was generated above\")\n",
- "else:\n",
- " print(f\"{'field':<22} {'before':<34} after\")\n",
- " print(\"-\" * 92)\n",
- " for field in SCHEMA[\"properties\"]:\n",
- " b = json.dumps(body[\"profile\"].get(field))\n",
- " a = json.dumps(updated[\"profile\"].get(field))\n",
- " mark = \" \" if a == b else \"->\"\n",
- " print(f\"{mark} {field:<20} {b[:32]:<34} {a[:32]}\")\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 5. Use it in a prompt\n",
- "\n",
- "The point of the structure is that it drops straight into a prompt โ no list of memories\n",
- "to summarize, no query to write.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "def build_system_prompt(entity_id):\n",
- " result = client.get_profile(entity_id)\n",
- " if result[\"status\"] != \"succeeded\":\n",
- " # Branch on status, never on an empty profile: a user whose profile is\n",
- " # still building is not a user you know nothing about.\n",
- " return \"You are a helpful assistant.\"\n",
- "\n",
- " p = result[\"profile\"]\n",
- " return f\"\"\"You are helping {entity_id}.\n",
- "Occupation: {p.get(\"occupation\", \"unknown\")}\n",
- "Location: {p.get(\"location\", \"unknown\")}\n",
- "Interests: {\", \".join(p.get(\"interests\", [])) or \"unknown\"}\n",
- "Dietary restrictions: {\", \".join(p.get(\"dietary_restrictions\", [])) or \"none stated\"}\n",
- "Preferred style: {p.get(\"communication_style\", \"unknown\")}\n",
- "\n",
- "Match their style and do not explain what they already know.\"\"\"\n",
- "\n",
- "\n",
- "print(build_system_prompt(USER_ID))\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 6. Judge a schema before committing to it\n",
- "\n",
- "`sample_profiles()` runs your schema against up to 10 **real** users that have memories.\n",
- "\n",
- "These are real generations and the results are **kept** โ a dry run would cost exactly the\n",
- "same and leave those users no better off. It is not a free preview.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "# 202, not 200: the sample generations are queued, not finished.\n",
- "#\n",
- "# A 409 `already_running` means a sample from an earlier run is still going.\n",
- "# That is the cooldown working, not an error โ reuse that job rather than\n",
- "# failing the notebook.\n",
- "try:\n",
- " job = client.sample_profiles(limit=3)\n",
- " print(json.dumps(job, indent=2)[:400])\n",
- " print(\"\\nsampled\", job.get(\"sampled\"), \"entities:\", job.get(\"entity_ids\"))\n",
- "except Exception as e:\n",
- " detail = str(e)\n",
- " print(\"sample refused:\", detail[:200])\n",
- " running = json.loads(detail).get(\"error\", {}).get(\"job_id\") if detail.startswith(\"{\") else None\n",
- " job = {\"job_id\": running, \"status_url\": f\"/v2/profiles/jobs/{running}/\"} if running else None\n",
- " print(\"reusing the running job:\", running)\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Poll `status_url` to see how the job went. `total` is `null` until enumeration finishes,\n",
- "so format it defensively rather than assuming a number.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": "JOB_TERMINAL = {\"SUCCEEDED\", \"PARTIALLY_SUCCEEDED\", \"FAILED\", \"CANCELLED\"}\n\n\ndef wait_for_job(job_response, timeout=300, interval=5):\n \"\"\"Poll a generation job. Prefer status_url over a bare job id, so a route\n change needs no client update. Raise on timeout so an unfinished job is never\n mistaken for a finished one.\"\"\"\n handle = job_response.get(\"status_url\") or job_response[\"job_id\"]\n deadline = time.time() + timeout\n status = None\n while time.time() < deadline:\n status = client.get_profile_job(handle)[\"job\"]\n total = status.get(\"total\")\n print(\n f\" {status['status']} \"\n f\"completed={status.get('completed', 0)}/{total if total is not None else '?'} \"\n f\"succeeded={status.get('succeeded', 0)} \"\n f\"failed={status.get('failed', 0)} \"\n f\"skipped={status.get('skipped', 0)}\"\n )\n if str(status.get(\"status\", \"\")).upper() in JOB_TERMINAL:\n return status\n time.sleep(interval)\n raise TimeoutError(\n f\"job not terminal in {timeout}s (last status: {status.get('status') if status else 'none'})\"\n )\n\n\nif job is None:\n print(\"no sample job to poll\")\nelse:\n final = wait_for_job(job)\n\n print(\"\\n--- what the sample produced ---\")\n for entity_id in job.get(\"entity_ids\", []):\n got = client.get_profile(entity_id)\n print(f\"\\n{entity_id} [{got['status']}]\")\n print(\" \", json.dumps(got[\"profile\"])[:220])"
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 7. Apply a new schema to existing users\n",
- "\n",
- "A new schema shapes the **next** generation. Profiles that already exist keep their values\n",
- "until their user is generated again โ which happens as that user sends more memories, or\n",
- "when you call `generate_profile()` for them.\n",
- "\n",
- "A field you **remove** stops being maintained: on the next generation, fields your schema\n",
- "no longer defines are pruned. Keep a field for as long as you want its value kept."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "# Failure scenarios\n",
- "\n",
- "Everything above is the path that works. These are the ways it says no, and what each one\n",
- "means. Run this section last: F3 deliberately leaves the project switched off for a moment.\n",
- "\n",
- "> **About the `HTTP error occurred:` lines below.** The SDK logs every 4xx at\n",
- "> ERROR level before raising, so they appear even for the failures these cells\n",
- "> deliberately catch. Read the line printed *after* each one โ that is the cell's\n",
- "> own verdict. Nothing here is unhandled.\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## F1. Schemas that get rejected\n",
- "\n",
- "Rejections happen on **write**, where you can see and fix them โ not silently at\n",
- "generation time, where you would only notice as an empty profile weeks later.\n",
- "\n",
- "The last case matters for storage: the user schema lives in one JSONB column alongside\n",
- "the envelope that separates it, so a schema using the envelope's own reserved keys could\n",
- "not be read back unambiguously. It is refused rather than stored.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "BAD_SCHEMAS = [\n",
- " ({\"type\": \"object\", \"properties\": {}}, \"empty โ bills you to extract nothing\"),\n",
- " ({\"type\": \"array\", \"items\": {\"type\": \"string\"}}, \"root must be an object\"),\n",
- " (\n",
- " {\n",
- " \"type\": \"object\",\n",
- " \"properties\": {\"tone\": {\"type\": \"string\", \"description\": \"Preferred tone.\"}},\n",
- " # At the schema ROOT, which is where the envelope's own keys live.\n",
- " \"_profile_config_version\": 1,\n",
- " \"entities\": {\"user\": {}},\n",
- " },\n",
- " \"reserved settings keys at the schema root\",\n",
- " ),\n",
- "]\n",
- "\n",
- "for bad, why in BAD_SCHEMAS:\n",
- " try:\n",
- " client.update_profile_settings(schema=bad)\n",
- " print(f\"ACCEPTED (unexpected): {why}\")\n",
- " except Exception as e:\n",
- " print(f\"rejected [{why}]:\\n {str(e)[:160]}\\n\")\n",
- "\n",
- "# NOT rejected: a property with no description. The validator allows it and the\n",
- "# model then has nothing to go on, so the field comes back empty. Descriptions are\n",
- "# your job, not the validator's.\n",
- "try:\n",
- " client.update_profile_settings(schema={\"type\": \"object\", \"properties\": {\"x\": {\"type\": \"string\"}}})\n",
- " print(\"accepted [no description on 'x'] <- the trap: valid to store, useless to generate\")\n",
- "finally:\n",
- " client.update_profile_settings(schema=SCHEMA) # put the good one back\n",
- "\n",
- "restored = client.get_profile_settings()[\"entities\"][\"user\"][\"schema\"]\n",
- "assert set(restored[\"properties\"]) == set(SCHEMA[\"properties\"])\n",
- "print(\"\\nschema restored:\", sorted(restored[\"properties\"]))\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## F2. A user that does not exist\n",
- "\n",
- "404 means only \"no such user\". A known user with no profile yet is a 200 carrying\n",
- "`insufficient_data`, so an ordinary empty state never looks like an error.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "from mem0.exceptions import MemoryNotFoundError\n",
- "\n",
- "try:\n",
- " client.get_profile(\"user_who_never_existed\")\n",
- " print(\"ACCEPTED (unexpected)\")\n",
- "except MemoryNotFoundError as e:\n",
- " print(\"404 as intended:\", str(e)[:120])\n",
- "\n",
- "# ...versus a real user who simply has no profile row yet.\n",
- "fresh = f\"demo_never_profiled_{uuid.uuid4().hex[:6]}\"\n",
- "client.add([{\"role\": \"user\", \"content\": \"One passing remark.\"}], user_id=fresh)\n",
- "time.sleep(5)\n",
- "print(\"known but unprofiled:\", client.get_profile(fresh)[\"status\"])\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## F3. Profiles turned off\n",
- "\n",
- "`enabled` is the one project-wide switch. Every generation path then refuses.\n",
- "\n",
- "Nothing is deleted. Your schema and every profile you already built are kept, so turning\n",
- "it back on resumes rather than restarts.\n",
- "\n",
- "Note what a read does **not** do โ a profile that already exists keeps reporting\n",
- "`succeeded` and keeps returning its content. `not_enabled` is only what you get for a user\n",
- "with no profile yet. Turning the feature off stops new work; it does not hide what has\n",
- "already been built.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "client.update_profile_settings(enabled=False)\n",
- "\n",
- "print(\"read (demo user) :\", client.get_profile(USER_ID)[\"status\"])\n",
- "print(\"read (never profiled) :\", client.get_profile(fresh)[\"status\"])\n",
- "try:\n",
- " client.generate_profile(USER_ID)\n",
- " print(\"trigger: ACCEPTED (unexpected)\")\n",
- "except Exception as e:\n",
- " print(\"trigger:\", str(e)[:160])\n",
- "\n",
- "back = client.update_profile_settings(enabled=True) # put it back\n",
- "print(\"\\nrestored:\", back[\"enabled\"])\n",
- "print(\"schema survived:\", bool(back[\"entities\"][\"user\"][\"schema\"]))\n"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 7. Cleanup\n",
- "\n",
- "Removes the demo users. The profile row cascades with the entity.\n"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": "# Restore the project's profile settings to the start-of-run snapshot in `finally`, so a\n# failed delete still leaves a shared project as we found it. Passing the original values\n# (including None) clears anything this notebook set: the SDK treats an explicit None as\n# \"clear\" and an omitted argument as \"unchanged\".\ntry:\n # `fresh` only exists if the error-handling section ran.\n for entity_id in (USER_ID, globals().get(\"fresh\")):\n if entity_id is None:\n continue\n r = client.client.delete(f\"/v2/entities/user/{entity_id}/\")\n print(entity_id, \"->\", r.status_code)\nfinally:\n _user = ORIGINAL_SETTINGS.get(\"entities\", {}).get(\"user\", {})\n client.update_profile_settings(\n enabled=ORIGINAL_SETTINGS.get(\"enabled\", False),\n schema=_user.get(\"schema\"),\n custom_instructions=_user.get(\"custom_instructions\"),\n )\n print(\"profile settings restored to the pre-notebook snapshot\")"
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "---\n",
- "\n",
- "## Cheat sheet\n",
- "\n",
- "| Want | Call | Cost |\n",
- "| --- | --- | --- |\n",
- "| configure | `update_profile_settings(...)` | free |\n",
- "| read | `get_profile(user_id)` | free |\n",
- "| one user now | `generate_profile(user_id)` | 1 LLM call |\n",
- "| try a schema | `sample_profiles(limit=n)` | โค10 real generations, kept |\n",
- "| poll a job | `get_profile_job(status_url)` | free |\n",
- "\n",
- "**Settings apply to user profiles.** The stored shape is:\n",
- "\n",
- "```json\n",
- "{\"enabled\": true,\n",
- " \"entities\": {\"user\": {\"schema\": {...}, \"custom_instructions\": \"...\"}},\n",
- " \"capabilities\": {\"full_rebuild\": false}}\n",
- "```\n",
- "\n",
- "The SDK takes these flat and nests them for you. Only the fields you pass are written;\n",
- "`enabled` is the one project-wide switch.\n",
- "\n",
- "**Left alone, generation fires** on a 10-message boundary, or after a flush window\n",
- "measured in hours. `generate_profile()` is how you skip the wait for one user.\n",
- "\n",
- "**Three traps:**\n",
- "\n",
- "1. `insufficient_data` is not a terminal verdict โ it also covers \"queued\", so poll\n",
- " through it and give up on a timeout instead.\n",
- "2. `succeeded` is decided by the profile **body**, not `generation_count`. An empty\n",
- " extraction still increments the counter.\n",
- "3. A forced JSON-Schema response emits something for every property, so \"nothing found\"\n",
- " arrives as a type default โ `\"\"`, `[]`, `0` โ not as a missing key.\n"
- ]
- }
- ],
- "metadata": {
- "kernelspec": {
- "display_name": "Python 3 (ipykernel)",
- "language": "python",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 3
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython3",
- "version": "3.12.4"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 4
-}
\ No newline at end of file
diff --git a/integrations/AGENTS.md b/integrations/AGENTS.md
index e7814523f..c129dd48b 100644
--- a/integrations/AGENTS.md
+++ b/integrations/AGENTS.md
@@ -6,7 +6,6 @@ Agent and editor integrations. Most packages are self-contained; coding-agent pl
|-----------|---------|-------|------|------|
| `vercel-ai-sdk/` | `@mem0/vercel-ai-provider` | tsup (CJS+ESM) | ESLint + Prettier | jest + vitest (edge/node) |
| `openclaw/` | `@mem0/openclaw-mem0` | tsup (ESM) | none | vitest |
-| `hermes-plugin-mem0/` | Standalone Hermes memory provider | none | ruff + isort | pytest (host-stubbed offline); live CLI/Desktop validation |
| `agent-plugin-core/` | Shared Python/TypeScript behavior, skill templates, builds, and conformance | Python build script | ruff + tsc | pytest + node:test |
| `mem0-agent-plugin/` | One portable Agent Plugins v1 package | Python | ruff | shared conformance |
| `claude-code-plugin/`, `cursor-plugin/`, `codex-plugin/`, `kimi-plugin/`, `antigravity-plugin/` | Self-contained native plugins generated from the shared Python core | Python | ruff | pytest |
@@ -50,48 +49,6 @@ Run the type check after every TypeScript change: `pnpm run typecheck` or `tsc -
- **`zapier-mem0/`** is a Zapier Platform CLI app: add, search, get, delete. It deploys to Zapier, not npm, so it is **not** in the release router. Deploy it with `gh workflow run zapier-mem0-cd.yml --ref main` (needs the `ZAPIER_DEPLOY_KEY` secret).
- **`mem0-strands/`** is a native Strands `MemoryStore` (Python, published to PyPI as `mem0-strands`). It plugs into the Strands `MemoryManager` for automatic recall and server-side extraction, over the hosted Mem0 platform or self-hosted Mem0 OSS. The package lives under `mem0-strands/python/`.
-## Surface attribution
-
-Every integration tells the Mem0 platform which surface it is. Three headers,
-and the rules on them are what keep one layer from erasing another:
-
-| Header | Carries | Rule |
-|--------|---------|------|
-| `X-Mem0-Source` | one canonical source value | **set-once** โ write only if absent |
-| `X-Application` | the host app it runs inside | **set-once** โ write only if absent |
-| `X-Mem0-Client` | `name/version`, outermost first | **append-only** โ add yourself, never replace |
-
-Set-once means check-then-set, never assignment. An integration that wraps the
-SDK is the outermost layer and sets the source; the SDK underneath defers to it.
-Assignment is exactly how every agent plugin came to be indistinguishable from
-every other one at the platform.
-
-How to declare it from an integration, in order of preference:
-
-1. Send the headers yourself, if you make the HTTP call directly.
-2. Pass `source` in the call options, if you go through an SDK.
-3. Set `MEM0_SOURCE` / `MEM0_APPLICATION` / `MEM0_CLIENT_STACK` in the
- environment before constructing the client. The SDKs read these and defer to
- anything already present.
-
-Append-only applies where a stack can actually form: an SDK handed a client that
-already carries `X-Mem0-Client` appends itself rather than replacing. An SDK
-constructed with no outer context simply reports itself, which is correct โ it
-is the outermost layer in that process.
-
-The backend recognizes a fixed list of source values and buckets everything else
-into `OTHERS`. A new value has to land in the platform's `EventSource` enum, so
-do not invent one without that change going in too.
-
-`X-Application` is allowlisted the same way, and this one has a rule of its own:
-**omit the header when you do not know the host.** A value outside the allowlist
-is discarded server-side, so guessing produces an event that claims an
-attribution we do not actually have. The portable bundle is the case that
-matters. It runs in whatever editor a user drops it into, so its build leaves
-`PLATFORM_APPLICATION` empty and `memory_core` sends no header at all, while the
-native bundles each name the host they were generated for. If you add a build
-target, decide which of those two it is.
-
## Adding an integration
1. For a native coding-agent host, add `integrations/-plugin/` with `plugin-build.json`, its manifest, and a thin adapter, then generate its shared runtime. Portable clients use the single `mem0-agent-plugin/` package. Independent TypeScript integrations stay self-contained and import shared lifecycle behavior from `agent-plugin-core/typescript/`.
@@ -102,4 +59,3 @@ target, decide which of those two it is.
5. If it is a Claude Code or editor marketplace plugin, register the generated native bundle path in the applicable marketplace files. Preserve the existing public plugin name.
6. Document it under `docs/integrations/` and add the page to `docs/docs.json` and `docs/llms.txt`.
7. Add rows to the table above and to the CI/CD tables in [`../.github/AGENTS.md`](../.github/AGENTS.md).
-8. Send the three headers in [Surface attribution](#surface-attribution), and land the matching `EventSource` value on the platform in the same week. Until it exists, your traffic reports as `OTHERS`.
diff --git a/integrations/agent-plugin-core/README.md b/integrations/agent-plugin-core/README.md
index dab9a88b7..f11026319 100644
--- a/integrations/agent-plugin-core/README.md
+++ b/integrations/agent-plugin-core/README.md
@@ -8,7 +8,7 @@ This directory is the single source of shared memory behavior for Mem0 coding-ag
integrations/
โโโ agent-plugin-core/ # Shared source; never installed as a plugin
โ โโโ python/ # Claude-derived capture, recall, MCP, scoping, and telemetry
-โ โโโ typescript/ # Shared lifecycle, search prompts, formatting, identity, scoping, and telemetry
+โ โโโ typescript/ # Shared lifecycle, formatting, identity, scoping, and telemetry
โ โโโ skills/ # The only source for the six generated memory skills
โ โโโ build/ # Bundle builder, schemas, and validation
โ โโโ conformance/ # One offline/live verification entry point
@@ -45,7 +45,7 @@ New Git repository writes use a hashed remote identity for shared `agent_id`. Se
Captured prompts and responses preserve their full text after secret redaction. Python extraction splits oversized input across requests without dropping message text. The session-end worker flushes the conversation already collected by hooks without adding the final answer again. Search queries, retrieved context, and tool evidence have separate limits.
-TypeScript hosts reuse redaction, lifecycle utilities, and the search prompts in `typescript/src/prompts.ts`, which a test keeps identical to the Python core. They retain their own tools, scopes, and capture events. They do not inherit the Python `repo`/`dir`/`mine` contract or its background batching. OpenCode captures selected user prompts; Pi and DeepSeek capture completed conversation turns; OpenClaw selects recent messages and earlier summaries, then filters noise. Removing message-length truncation does not turn these integrations into complete transcript archives.
+TypeScript hosts reuse redaction and lifecycle utilities but retain their own tools, scopes, and capture events. They do not inherit the Python `repo`/`dir`/`mine` contract or its background batching. OpenCode captures selected user prompts; Pi and DeepSeek capture completed conversation turns; OpenClaw selects recent messages and earlier summaries, then filters noise. Removing message-length truncation does not turn these integrations into complete transcript archives.
For installation, follow the host guides: [Claude Code](../../docs/integrations/claude-code.mdx), [Cursor](../../docs/integrations/cursor.mdx), [Codex](../../docs/integrations/codex.mdx), [Kimi](../../docs/integrations/kimi.mdx), and [Antigravity](../../docs/integrations/antigravity.mdx).
diff --git a/integrations/agent-plugin-core/build/build.py b/integrations/agent-plugin-core/build/build.py
index 3059b9b1f..7a72e5c51 100644
--- a/integrations/agent-plugin-core/build/build.py
+++ b/integrations/agent-plugin-core/build/build.py
@@ -81,38 +81,6 @@ def replace_output(staged: Path, output: Path) -> Path:
return output
-def _render_harness_id(host: str, *, portable: bool = False) -> str:
- """Emit core/_harness_id.py for one host.
-
- Carries both vocabularies from a single definition: the PostHog `source` tag
- and the platform's X-Mem0-Source / X-Application pair. Keeping them together
- is what stops the two from drifting into separate vocabularies for the same
- thing.
-
- The portable bundle runs in whatever editor a user drops it into, so it does
- not know its host and must not guess one. HARNESS_ID stays "coding-agent",
- which is true and useful for grouping in PostHog, but PLATFORM_APPLICATION is
- left empty: X-Application names a real host app, is checked against an
- allowlist server-side, and a value that is always discarded is worse than no
- value -- it reads like an attribution we have and do not.
- """
- tag = host.upper().replace("-", "_") + "_PLUGIN"
- application = "" if portable else host
- return (
- '"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""\n'
- "\n"
- f'HARNESS_ID = "{host}"\n'
- f'SOURCE_TAG = "{tag}"\n'
- "\n"
- "# Platform-side vocabulary (mem0_event.source + X-Application). The whole\n"
- "# plugin family is one source; which editor it runs in is the application.\n"
- "# An empty application means the host is unknown, and memory_core omits\n"
- "# the header entirely rather than sending a placeholder.\n"
- 'PLATFORM_SOURCE = "MEM0_PLUGIN"\n'
- f'PLATFORM_APPLICATION = "{application}"\n'
- )
-
-
def _bundle_python(
staged: Path,
host: str,
@@ -128,12 +96,6 @@ def _bundle_python(
continue
shutil.copy2(source, core / source.name)
- # Generated per host so identity does not depend on an entrypoint remembering
- # to call telemetry.init(). mcp_server.py and the detached telemetry.py sender
- # never did, which is how MCP searches reported harness=generic and every
- # batch they drained was labelled MEM0_PLUGIN regardless of the real host.
- (core / "_harness_id.py").write_text(_render_harness_id(host, portable=portable), encoding="utf-8")
-
values = {
"PLUGIN_ROOT": plugin_root,
"PLUGIN_DATA": "${PLUGIN_DATA}",
diff --git a/integrations/agent-plugin-core/python/hook_runner.py b/integrations/agent-plugin-core/python/hook_runner.py
index b3d8a3210..2a2adb557 100644
--- a/integrations/agent-plugin-core/python/hook_runner.py
+++ b/integrations/agent-plugin-core/python/hook_runner.py
@@ -290,11 +290,6 @@ def run(
if args.plugin_data_dir:
os.environ[data_dir_env] = args.plugin_data_dir
- # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key
- # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking
- # after them always saw content and every fresh install reported an upgrade.
- data_dir_was_empty = telemetry.data_dir_was_empty()
-
cache_plugin_api_key()
if args.action == "session-start":
clear_stale_api_key_cache()
@@ -310,19 +305,8 @@ def run(
return 0
if args.action == "session-start":
- # Claims the marker atomically and says which event to record, so a
- # second session starting alongside this one cannot record it too.
- first_event = telemetry.claim_install(was_empty=data_dir_was_empty)
- if first_event == "install":
+ if telemetry.is_first_run():
telemetry.record("install")
- elif first_event == "upgrade":
- # First run after a build that never wrote the marker; the
- # predecessor version was never recorded anywhere.
- telemetry.record("upgrade", from_version="pre-0.3")
- else:
- previous = telemetry.claim_version_change()
- if previous:
- telemetry.record("upgrade", from_version=previous)
recovered = recover_pending_handoffs()
record_session_start(store, hook_input)
if recovered:
diff --git a/integrations/agent-plugin-core/python/mcp_server.py b/integrations/agent-plugin-core/python/mcp_server.py
index a0b73cb79..036fbbdc9 100644
--- a/integrations/agent-plugin-core/python/mcp_server.py
+++ b/integrations/agent-plugin-core/python/mcp_server.py
@@ -21,9 +21,16 @@ from memory_core import (
PROTOCOL_VERSION = "2024-11-05"
TOOL_NAME = "search_memories"
TOOL_DESCRIPTION = (
- "Search memories from earlier work in this repository. Use it before "
- "repeating investigation or when earlier decisions, fixes, commands, or "
- "results may help."
+ "Search memories from earlier work in this repository. ALWAYS call this "
+ "tool before answering anything that could depend on prior context: the "
+ "user's preferences, facts about this codebase, history, people, projects, "
+ "or earlier decisions. Do not rely on the chat window alone. The "
+ "repository's memory is shared by everyone who works in it and includes "
+ "what it took to run, test, or build here, so search before assuming an "
+ "invocation works. The scope argument changes what is searched: 'repo' "
+ "(default) is the whole repository's shared memory plus your own "
+ "preferences, 'dir' narrows the shared part to the directory you are "
+ "working in, and 'mine' is your preferences alone."
)
TOOL_SCHEMA = {
"type": "object",
diff --git a/integrations/agent-plugin-core/python/memory_core.py b/integrations/agent-plugin-core/python/memory_core.py
index 9b420a063..77d7a2b80 100644
--- a/integrations/agent-plugin-core/python/memory_core.py
+++ b/integrations/agent-plugin-core/python/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.3"
+PLUGIN_VERSION = "0.3.1"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
@@ -71,13 +71,15 @@ MAX_FLUSH_ATTEMPTS = 5
FORGET_PAGE_SIZE = 100
FORGET_MAX_PAGES = 50
-PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work.
+PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository.
A completed change should produce one memory explaining the resulting behavior, where it is implemented when useful, and any important constraints or reasoning. Exploration or accepted decisions may produce separate memories only when they are independently useful.
-Use the coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+A command that failed and was then made to work should produce one memory naming the failing invocation, the error it returned, and the invocation that succeeded. Do not save one-off errors caused by an edit still in progress, transient network failures, or anything a rerun would fix on its own.
-Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state.
+Use the current coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+
+Write about the repository, not the user, assistant, session, or task. Do not save personal preferences. Do not save a memory that only states which repository, branch, or directory the session worked in. Do not include test results, documentation updates, release notes, or temporary state.
If nothing useful was established, return no memories."""
@@ -1798,34 +1800,6 @@ def extraction_message_batches(
return batches
-# Platform surface attribution. Read from the generated per-host module so a new
-# entrypoint is correct without remembering to configure anything.
-try: # pragma: no cover - absent only in the un-built shared source tree
- from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
- from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
-except ImportError:
- _PLATFORM_SOURCE = "MEM0_PLUGIN"
- _PLATFORM_APPLICATION = ""
-
-
-def platform_headers(key: str) -> dict[str, str]:
- """Auth plus the three surface-identity headers.
-
- X-Mem0-Source and X-Application are set-once by contract: this is the
- outermost layer, so it sets them, and nothing below may overwrite them.
- X-Mem0-Client is append-only โ anything downstream adds itself to the tail.
- """
- headers = {
- "Authorization": f"Token {key}",
- "Content-Type": "application/json",
- "X-Mem0-Source": _PLATFORM_SOURCE,
- "X-Mem0-Client": f"mem0-plugin/{PLUGIN_VERSION}",
- }
- if _PLATFORM_APPLICATION:
- headers["X-Application"] = _PLATFORM_APPLICATION
- return headers
-
-
def _request_json(
url: str, key: str, payload: dict[str, Any], timeout: float
) -> tuple[dict[str, Any] | list[Any], int, int]:
@@ -1833,7 +1807,7 @@ def _request_json(
request = urllib.request.Request(
url,
data=raw,
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -1860,7 +1834,7 @@ def _get_json(
) -> tuple[dict[str, Any] | list[Any], int]:
request = urllib.request.Request(
url,
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="GET",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -2006,13 +1980,6 @@ def flush_session(
"user_id": write_user,
"app_id": repo.app_id,
"run_id": session_id,
- # Top level, not metadata: the backend reads `source` from the body or
- # the query string, never from metadata, which is where this used to
- # sit. The X-Mem0-Source header is also read, but only from the
- # platform release that ships alongside this change, so the body value
- # is what makes attribution work on both. The harness tag stays in
- # metadata as hook provenance.
- "source": _PLATFORM_SOURCE,
"metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)},
"agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS,
"custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS,
@@ -2556,7 +2523,7 @@ def _collect_memory_ids(
def _delete_memory(api_url: str, key: str, memory_id: str) -> bool:
request = urllib.request.Request(
f"{api_url}/v1/memories/{urllib.parse.quote(memory_id)}/",
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="DELETE",
)
try:
diff --git a/integrations/agent-plugin-core/python/telemetry.py b/integrations/agent-plugin-core/python/telemetry.py
index c1fc0084c..249595475 100644
--- a/integrations/agent-plugin-core/python/telemetry.py
+++ b/integrations/agent-plugin-core/python/telemetry.py
@@ -1,9 +1,5 @@
#!/usr/bin/env python3
-"""Usage telemetry for Mem0 agent plugins.
-
-Events are linked to your Mem0 account email when an API key is configured, and
-to a random per-machine id otherwise. Not anonymous โ the Python SDK and CLI
-attribute the same way.
+"""Anonymous usage telemetry for Mem0 agent plugins.
Hooks run on a 3-6 second budget and fire on every tool call, so recording never
touches the network: `record` appends one JSON line to a local spool and returns.
@@ -13,8 +9,7 @@ started once per session and again from the flush worker that is already detache
Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false.
Never sends prompts, memory text, queries, file paths, repository names, or API
-keys: only event names, durations, counts, coarse outcomes, and repo/session
-identifiers hashed with a random per-install salt.
+keys: only event names, durations, counts, coarse outcomes, and salted hashes.
"""
from __future__ import annotations
@@ -34,24 +29,8 @@ from typing import Any
import memory_core
-# Seeded from the per-host module the build generates into core/. Two processes
-# in this pipeline never call init() โ mcp_server.py, and the detached
-# `python3 telemetry.py` sender that spawn_flush() starts โ so a module default
-# was what every one of their events got labelled with.
-try: # pragma: no cover - absent only in the un-built shared source tree
- from _harness_id import HARNESS_ID as _DEFAULT_HARNESS
- from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
- from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
- from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG
-except ImportError:
- _DEFAULT_HARNESS = "generic"
- _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN"
- _PLATFORM_SOURCE = "MEM0_PLUGIN"
- _PLATFORM_APPLICATION = ""
-
-_salt_cache: str = ""
-_harness: str = _DEFAULT_HARNESS
-_source_tag: str = _DEFAULT_SOURCE_TAG
+_harness: str = "generic"
+_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
"apikey",
"authorization",
@@ -77,19 +56,10 @@ _PRIVATE_KEYS = {
}
-def init(harness: str = "", source_tag: str = "") -> None:
- """Override the generated identity. Optional โ core/_harness_id.py is the default.
-
- The fallback shape matches memory_core.configure_harness's (``_PLUGIN``).
- It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which
- meant one plugin could emit three different source values depending on which
- process happened to send the batch.
- """
+def init(harness: str = "generic", source_tag: str = "") -> None:
global _harness, _source_tag
- _harness = harness or _DEFAULT_HARNESS
- _source_tag = source_tag or (
- f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG
- )
+ _harness = harness
+ _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/"
@@ -100,16 +70,6 @@ BATCH_SIZE = 100
SEND_TIMEOUT = 5
CLAIM_STALE_SECONDS = 120
CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60
-# A batch is only discarded once it has genuinely been retried this many times.
-MAX_CLAIM_ATTEMPTS = 3
-# Parked claims drained per run, after the live spool. Bounded so a long backlog
-# cannot turn one flush into an unbounded send loop.
-MAX_PARKED_PER_RUN = 3
-# Added to the wait before a released claim becomes reclaimable, per attempt
-# already spent. Releasing straight to "reclaimable now" let two senders burn the
-# whole budget within seconds of one another on a single momentary failure, and
-# discard a batch a retry a minute later would have delivered.
-RETRY_COOLDOWN_SECONDS = 60
def is_enabled() -> bool:
@@ -123,126 +83,9 @@ def is_enabled() -> bool:
def _digest(value: str, length: int = 16) -> str:
- """Unsalted digest. Only for values that are already secrets (API keys)."""
return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length]
-def _salt_path() -> Path:
- return memory_core.data_dir() / "telemetry-salt"
-
-
-def _install_salt() -> str:
- """Random per-install salt, created once and memoized for the process.
-
- Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in
- the identity file. Three reasons, all of which produced wrong data when this
- lived in the identity dict:
-
- - Hooks are short-lived separate processes firing on every tool call, and
- people run more than one agent window. A read-modify-write would let each
- process mint its own salt, so one repository would hash several ways in the
- window before a writer won.
- - resolve_distinct_id holds a copy of the identity dict across a network call
- to /v1/ping/, so whichever write landed second erased the other's key โ
- losing either the salt (repo_hash changes mid-stream) or the email (a
- second $identify, splitting the person).
- - Touching the identity file from record() would create it, and is_first_run
- keys off that file, so recording an event would silently suppress the
- install event.
-
- Published atomically, and there is deliberately no derived fallback. Creating
- the file with O_CREAT|O_EXCL and then writing into it leaves a window where
- the file exists and is empty, and a concurrent hook that reads it in that
- window gets nothing. Falling back to a digest of the path would hand that
- process a salt an attacker can compute, memoized for its whole run, which is
- the privacy control this function exists to provide silently turning itself
- off under load. The salt is written to a private temp file first and linked
- into place, so the name either does not exist or already has the full value.
-
- Returns "" when it genuinely cannot persist. Callers omit the hash entirely
- rather than emit an unsalted one.
- """
- global _salt_cache
- if _salt_cache:
- return _salt_cache
-
- path = _salt_path()
- # Read before writing. Hooks are separate processes firing on every tool
- # call, so all but the first find the salt already published; going straight
- # to create-fsync-link-unlink meant every one of them paid an fsync to
- # discover that, on a path whose whole promise is appending a line and
- # returning.
- try:
- _salt_cache = path.read_text(encoding="utf-8").strip()
- if _salt_cache:
- return _salt_cache
- except OSError:
- pass
-
- temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(handle, "w", encoding="utf-8") as stream:
- stream.write(uuid.uuid4().hex)
- stream.flush()
- os.fsync(stream.fileno())
- try:
- # Atomic claim: fails if another process already published one.
- # os.link rather than replace, which would clobber theirs.
- os.link(temporary, path)
- except FileExistsError:
- pass
- except OSError:
- # No hardlinks here (some network mounts, some container volumes).
- # Claim the name directly instead. That reopens the empty-file
- # window, but the window is now benign: a reader that lands in it
- # gets "" and omits the hash for that process rather than caching a
- # guessable one. Losing the hashes on every run of an entire
- # filesystem is the worse failure.
- try:
- fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(fallback, "w", encoding="utf-8") as stream:
- stream.write(temporary.read_text(encoding="utf-8"))
- except OSError:
- pass
- except OSError:
- pass
- finally:
- try:
- temporary.unlink()
- except OSError:
- pass
-
- try:
- _salt_cache = path.read_text(encoding="utf-8").strip()
- except OSError:
- _salt_cache = ""
- return _salt_cache
-
-
-def _scoped_digest(value: str, length: int = 16) -> str:
- """Salted digest for values drawn from a guessable space.
-
- repo.identity is a git remote URL, or ``local:`` when there is
- no remote โ which normally contains the account username. Sixteen unsalted
- hex characters over that input space is enumerable, so this is not a
- privacy control without the salt. Salting per install keeps every
- within-account join the analytics actually use and gives up only
- cross-machine joins on the same repository, which nothing computes.
-
- Returns "" when there is no salt, so record() omits the property. An
- unsalted digest over this input space is close to plaintext, and emitting one
- under a name that implies it is hashed is worse than sending nothing.
- """
- if not value:
- return ""
- salt = _install_salt()
- if not salt:
- return ""
- return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length]
-
-
def _safe_value(value: Any) -> Any:
if isinstance(value, str):
return memory_core.redact(value)
@@ -302,176 +145,9 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str:
return created
-def _rotate_anonymous_id(identity: dict[str, str]) -> str:
- """Mint a fresh anonymous id because the account context is gone.
-
- The previous id may already have been merged into a person profile by an
- $identify, and that merge is permanent. Reusing it after a logout or a key
- change attributes everything that follows to the account that just went
- away, which is the same misattribution the key fingerprint exists to stop,
- only arriving through the anonymous path instead.
-
- `aliased` is cleared with it: the new id has never been merged, so it is
- eligible to be aliased into whatever account comes next.
- """
- created = f"code-anon-{uuid.uuid4().hex}"
- identity["anonymous_id"] = created
- identity.pop("aliased", None)
- _write_identity(identity)
- return created
-
-
-def _install_state_path() -> Path:
- return memory_core.data_dir() / "install-state.json"
-
-
def is_first_run() -> bool:
- """Whether install has never been recorded on this machine.
-
- Deliberately NOT the identity file. That file is only written by a
- successful flush, so an offline or firewalled user recorded code.install on
- every single session, forever โ and every 0.2.x user recorded one on their
- first 0.3.x session because 0.2.x never wrote it at all.
- """
- return not _install_state_path().exists()
-
-
-def data_dir_was_empty() -> bool:
- """Whether the data directory is untouched. Call BEFORE anything writes to it.
-
- hook_runner reaches claim_install() only after cache_plugin_api_key() has
- written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so
- asking at claim time always saw content and every fresh install reported an
- upgrade. The caller snapshots this at the top of the run instead.
- """
- return not _data_dir_has_content()
-
-
-def claim_install(was_empty: bool | None = None) -> str | None:
- """Claim the one install/upgrade record for this machine, atomically.
-
- Returns the event to record ("install" or "upgrade"), or None if another
- session already claimed it. O_CREAT|O_EXCL so two sessions starting together
- cannot both win.
-
- `was_empty` must come from data_dir_was_empty() called before this process
- wrote anything. Omitting it falls back to checking now, which is only
- correct for a caller that has touched nothing.
- """
- if not is_enabled():
- # Never consume the one-shot claim while the user is opted out, or they
- # would silently lose their install event if they later opt in.
- return None
-
- path = _install_state_path()
- upgrading = not (data_dir_was_empty() if was_empty is None else was_empty)
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- except FileExistsError:
- return None
- except OSError:
- return None
- try:
- with os.fdopen(handle, "w", encoding="utf-8") as stream:
- json.dump(
- {
- "plugin_version": memory_core.PLUGIN_VERSION,
- "installed_at": memory_core.utc_now(),
- "upgraded": upgrading,
- },
- stream,
- )
- # Durable before this returns. The O_EXCL open is what makes the
- # claim exclusive, so it cannot be replaced by a temp-and-rename
- # without losing that, which leaves the content as the thing to make
- # safe. A kill between the open and this fsync used to leave a marker
- # that exists but parses to nothing: is_first_run reads it as claimed
- # and claim_version_change cannot read a version out of it.
- stream.flush()
- os.fsync(stream.fileno())
- except OSError:
- pass
- return "upgrade" if upgrading else "install"
-
-
-def _data_dir_has_content() -> bool:
- """Whether anything predates this session in the plugin data directory."""
- try:
- for entry in memory_core.data_dir().iterdir():
- if entry.name != "install-state.json":
- return True
- except OSError:
- pass
- return False
-
-
-def _repair_install_state(path: Path) -> None:
- """Rewrite an unparseable marker so version tracking can resume."""
- try:
- temporary = path.with_suffix(f".{os.getpid()}.tmp")
- temporary.write_text(
- json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}),
- encoding="utf-8",
- )
- temporary.replace(path)
- except OSError:
- pass
-
-
-def claim_version_change() -> str | None:
- """Return the previously recorded version if it differs, updating the marker.
-
- Only meaningful once the marker exists โ the first transition into 0.3.x has
- no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting
- the marker means the next session sees no change and records nothing.
- """
- path = _install_state_path()
- try:
- state = json.loads(path.read_text(encoding="utf-8"))
- except OSError:
- return None
- except json.JSONDecodeError:
- # A crash between O_EXCL and the write leaves an empty marker. Left
- # alone it disables every future upgrade event on this machine, because
- # claim_install sees the file and this function cannot parse it.
- state = None
- if not isinstance(state, dict):
- _repair_install_state(path)
- return None
- previous = str(state.get("plugin_version") or "")
- if not previous or previous == memory_core.PLUGIN_VERSION:
- return None
- # Claim the transition with an exclusive sentinel before rewriting the
- # marker. A plain read-modify-write let every concurrently starting session
- # observe the old version and each record its own upgrade โ and the first
- # session after a version bump is exactly when several agent windows restart
- # together.
- sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}")
- try:
- os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
- except FileExistsError:
- return None
- except OSError:
- return None
-
- state["plugin_version"] = memory_core.PLUGIN_VERSION
- state["upgraded_at"] = memory_core.utc_now()
- temporary = path.with_suffix(f".{os.getpid()}.tmp")
- try:
- temporary.write_text(json.dumps(state), encoding="utf-8")
- temporary.replace(path)
- except OSError:
- # Release the claim. The marker still records the old version, so
- # without this the sentinel makes claim_version_change return early on
- # every later run and this version's upgrade is never recorded again.
- for leftover in (sentinel, temporary):
- try:
- leftover.unlink()
- except OSError:
- pass
- return None
- return previous
+ """Whether this machine has never recorded a plugin event before."""
+ return not _identity_path().exists()
def record(
@@ -492,32 +168,19 @@ def record(
except OSError:
pass
properties = _safe_value(properties)
- # Stamped in the RECORDING process, beside harness. `source` used to be
- # read in the sending process from a module global, so whichever process
- # drained the spool named every event in it. flush() spreads per-event
- # properties last, so this now wins over any sender's default.
properties.update(
harness=_harness,
- source=_source_tag,
plugin_version=memory_core.PLUGIN_VERSION,
os=sys.platform,
python_version=platform.python_version(),
)
- # Assigned only when the digest is real. _scoped_digest returns "" when
- # the salt could not be persisted, and an empty property is worse than an
- # absent one: it survives the None filter below and reads as a value.
if repo is not None:
- repo_hash = _scoped_digest(getattr(repo, "identity", ""))
- if repo_hash:
- properties["repo_hash"] = repo_hash
+ properties["repo_hash"] = _digest(getattr(repo, "identity", ""))
if session_id:
- session_hash = _scoped_digest(session_id)
- if session_hash:
- properties["session_hash"] = session_hash
+ properties["session_hash"] = _digest(session_id)
line = json.dumps(
{
"event": f"{EVENT_PREFIX}.{event}",
- "uuid": str(uuid.uuid4()),
"timestamp": memory_core.utc_now(),
"properties": {
key: value for key, value in properties.items() if value is not None
@@ -576,201 +239,38 @@ def spawn_flush() -> bool:
return False
-def _claim_name(attempt: int = 0) -> str:
- """Claim filename. The attempt count rides in the name so the 7-day expiry
- only ever discards a batch that was actually retried and failed."""
- return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending"
-
-
-def _claim_attempt(claim: Path) -> int:
- """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape.
-
- Anchored on field position, not on a leading "a": the legacy shape is
- ``telemetry--.sending`` and a hex id such as ``a1234567`` would
- otherwise parse as attempt 1234567 and be discarded unsent on the first
- flush after an upgrade.
- """
- stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name
- parts = stem.split("-")
- if len(parts) != 4:
- return 0
- tail = parts[3]
- if tail.startswith("a") and tail[1:].isdigit():
- return int(tail[1:])
- return 0
-
-
-def _touch(path: Path) -> None:
- """Refresh mtime so a claim's age measures time since it was claimed.
-
- ``Path.replace`` is ``os.rename``, which preserves mtime โ so a claim created
- after a quiet minute inherited the spool's last-write time and looked
- abandoned the instant it was made. A second sender would then take it over
- while the first was still posting, and both would deliver the batch.
- """
- try:
- os.utime(path, None)
- except OSError:
- pass
-
-
def _claim_spool() -> Path | None:
"""Rename the spool aside so exactly one sender owns each batch."""
directory = memory_core.data_dir()
- claim = directory / _claim_name()
+ claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending"
spool = _spool_path()
try:
spool.replace(claim)
- _touch(claim)
return claim
except OSError:
pass
- return _claim_parked(directory)
-
-
-def _sweep_debris(directory: Path) -> None:
- """Remove files nothing else will ever pick up again.
-
- *.partial is a temp file orphaned by a crash between write and rename.
- *.corrupt is a batch quarantined for undecodable content. No glob in this
- module matches either, so without this they accumulate on disk for the life
- of the install.
-
- Quarantined batches are kept far longer than debris: they are the only
- evidence left of events that could not be delivered, and someone diagnosing
- a report of missing telemetry has to be able to find one.
- """
now = time.time()
- for debris in directory.glob("telemetry-*.partial"):
- try:
- if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS:
- debris.unlink()
- except OSError:
- continue
- for quarantined in directory.glob("telemetry-*.corrupt"):
- try:
- if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS:
- quarantined.unlink()
- except OSError:
- continue
- # The same reasoning covers *.tmp. _write_identity and _install_salt both
- # create one and unlink it in a finally, which a SIGKILL skips, and no glob
- # in this module matches the leftovers either.
- for temporary in directory.glob("telemetry-*.tmp"):
- try:
- if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS:
- temporary.unlink()
- except OSError:
- continue
-
-
-def _claim_parked(directory: Path) -> Path | None:
- """Take the oldest abandoned claim, if any lease has actually expired.
-
- Kept separate from the live spool so flush() can drain both in one run.
- Previously parked batches were only reachable when no spool existed at all,
- and because sessions keep recording there usually was one โ so a batch
- parked by a failed send waited until the 7-day expiry deleted it unsent,
- even though its own presence is what started the sender.
- """
- now = time.time()
- for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime):
+ for orphan in sorted(directory.glob("telemetry-*.sending")):
try:
age = now - orphan.stat().st_mtime
except OSError:
continue
- if age < CLAIM_STALE_SECONDS:
- # Someone else holds a live lease on it. This check has to come
- # first. Claiming a file bumps its attempt count and refreshes its
- # mtime, so a sender that has just taken the final attempt looks
- # exhausted to everyone else while it is actively draining. Judging
- # exhaustion before liveness let a second sender unlink a batch out
- # from under its owner, losing every event in it.
- continue
- # Attempts, not age. Every re-claim touches the mtime and every release
- # backdates it by a fixed amount, so age is pinned near the stale
- # threshold and never reaches the expiry. Age stays only as a backstop
- # for files that never carried an attempt marker.
- if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS:
+ if age > CLAIM_EXPIRY_SECONDS:
try:
orphan.unlink()
except OSError:
pass
continue
- claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1)
+ if age < CLAIM_STALE_SECONDS:
+ continue
try:
orphan.replace(claim)
- _touch(claim)
return claim
except OSError:
continue
return None
-def _safe_mtime(path: Path) -> float:
- try:
- return path.stat().st_mtime
- except OSError:
- return 0.0
-
-
-def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool:
- """Persist the unsent remainder, atomically, and refresh the lease.
-
- Called after every successful batch. Two jobs: a retry resumes where the
- send stopped instead of re-posting from the top, and the rewrite doubles as
- the lease heartbeat, so a slow sender does not have its claim stolen
- mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS.
- """
- if not remaining:
- try:
- claim.unlink()
- except OSError:
- pass
- return True
- temporary = claim.with_suffix(f".{os.getpid()}.partial")
- try:
- payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining)
- # fsync before the rename: without it the rename can land while the
- # bytes have not, and the claim comes back empty or truncated after a
- # crash. _drain then reads zero events and unlinks it.
- with open(temporary, "w", encoding="utf-8") as handle:
- handle.write(payload)
- handle.flush()
- os.fsync(handle.fileno())
- temporary.replace(claim)
- _touch(claim)
- return True
- except OSError:
- try:
- temporary.unlink()
- except OSError:
- pass
- return False
-
-
-def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None:
- """Persist the remainder and drop the lease, because this sender has given up.
-
- Distinct from the per-batch heartbeat: heartbeating on the way out would
- make an abandoned batch look actively owned for a further
- CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the
- threshold lets the next flush pick it up immediately, while the attempt
- count in the filename still bounds how many times that can happen.
- """
- if not _rewrite_claim(claim, remaining):
- return
- try:
- # Backdate past the stale threshold so the next flush can pick it up,
- # minus a cooldown that grows with the attempts already spent. Clamped so
- # the mtime never lands in the future, which would read as a live lease.
- cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS)
- released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown
- os.utime(claim, (released, released))
- except OSError:
- pass
-
-
def _resolve_email(key: str) -> str:
"""Trade the API key for the account email so events join other Mem0 surfaces."""
url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/"
@@ -800,130 +300,34 @@ def _post(payload: dict[str, Any], url: str) -> bool:
def resolve_distinct_id() -> tuple[str, str]:
- """Return the PostHog distinct id and the anonymous id it replaced, if any.
-
- The second value becomes a PostHog $identify alias. It is ONLY ever an
- anonymous id: aliasing one account email to another merges two real person
- profiles and cannot be undone, so a key that now belongs to a different
- account re-resolves with no alias.
- """
+ """Return the PostHog distinct id and the anonymous id it replaced, if any."""
identity = _read_identity()
- key = memory_core.api_key()
- fingerprint = _digest(key) if key else ""
email = identity.get("email", "")
-
- if email and fingerprint:
- recorded = identity.get("key_fingerprint", "")
- if recorded == fingerprint:
- return email, ""
- if not recorded:
- # Rows written before fingerprints existed. Verify rather than
- # adopt: a key changed before the upgrade would otherwise bind the
- # new key to the previous account's email, permanently, and the
- # fingerprint would then agree with itself forever after.
- verified = _resolve_email(key)
- if not verified:
- # Offline, firewalled, or the API is down. Keep the previous
- # behaviour and retry on the next flush rather than dropping a
- # real account attribution. Safe because the same network that
- # failed /v1/ping/ is about to fail the PostHog POST, so nothing
- # is delivered under the unverified identity in the meantime.
- return email, ""
- identity["email"] = verified
- identity["key_fingerprint"] = fingerprint
- _write_identity(identity)
- return verified, ""
-
+ if email:
+ return email, ""
+ key = memory_core.api_key()
if not key:
- # No key to verify the account with; do not keep attributing to it.
- if email:
- identity.pop("email", None)
- identity.pop("key_fingerprint", None)
- return _rotate_anonymous_id(identity), ""
return anonymous_id(identity), ""
-
- resolved = _resolve_email(key)
- if not resolved:
- # The key changed and will not resolve (revoked, offline, API down).
- # Reaching here with an email means the recorded fingerprint disagreed,
- # so the key really did change. Drop the account and rotate: the stored
- # anonymous id may already be merged into that account's person, and
- # reusing it would keep the events on the profile we are trying to
- # leave.
- if email:
- identity.pop("email", None)
- identity.pop("key_fingerprint", None)
- return _rotate_anonymous_id(identity), ""
+ email = _resolve_email(key)
+ if not email:
return anonymous_id(identity), ""
-
- # Alias only when going anonymous -> email for the first time. Once an anon
- # id has been merged into an account it must never be offered again: an
- # alias naming an already-identified id is what could link two real people.
- previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "")
- if previous:
- identity["aliased"] = True
- identity["email"] = resolved
- identity["key_fingerprint"] = fingerprint
+ previous = identity.get("anonymous_id", "")
+ identity["email"] = email
_write_identity(identity)
- return resolved, previous
+ return email, previous
def flush() -> int:
- """Drain the live spool, then any parked claims, and return events sent."""
+ """Drain claimed spools to PostHog and return the number of events sent."""
if not is_enabled():
return 0
- sent, delivered = _drain(_claim_spool())
- if not delivered:
- # The network is failing. Retrying other batches now would only burn
- # their attempt budget against the same broken connection.
- return sent
-
- # Parked batches used to starve behind the live spool indefinitely. Bounded
- # per run so a long backlog cannot turn one flush into an unbounded loop.
- directory = memory_core.data_dir()
- _sweep_debris(directory)
- for _ in range(MAX_PARKED_PER_RUN):
- parked = _claim_parked(directory)
- if parked is None:
- break
- count, delivered = _drain(parked)
- sent += count
- if not delivered:
- break
- return sent
-
-
-def _drain(claim: Path | None) -> tuple[int, bool]:
- """Post one claimed batch file, recording progress after every batch.
-
- Returns (events sent, whether everything was delivered).
- """
+ claim = _claim_spool()
if claim is None:
- return 0, True
+ return 0
try:
lines = claim.read_text(encoding="utf-8").splitlines()
- except ValueError:
- # UnicodeDecodeError from a torn write: the content is unrecoverable, so
- # quarantine rather than retry. flush() runs from a bare `finally:` in
- # flush_worker, so raising here also skips the handoff cleanup, and an
- # undecodable file would otherwise be re-read on every flush forever.
- # Reported as delivered because there is nothing left to deliver and the
- # rest of the run should continue.
- try:
- claim.replace(claim.with_suffix(".corrupt"))
- except OSError:
- try:
- claim.unlink()
- except OSError:
- pass
- return 0, True
except OSError:
- # Could not read it, which is not the same as having nothing to send.
- # The file is left exactly where it is: a vanished or briefly unreadable
- # claim is retryable, and quarantining it here would discard events over
- # a transient filesystem error. Reported as undelivered so the run stops
- # instead of counting a batch nothing was posted from as delivered.
- return 0, False
+ return 0
events = []
for line in lines:
try:
@@ -933,18 +337,11 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
if isinstance(value, dict) and value.get("event"):
events.append(value)
if not events:
- # Only delete when the file really is empty. A non-empty file that
- # parses to nothing is a torn write, and its contents are the unsent
- # remainder โ deleting it is the data loss this PR exists to prevent.
try:
- empty = claim.stat().st_size == 0
- except OSError:
- empty = True
- try:
- claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink()
+ claim.unlink()
except OSError:
pass
- return 0, True
+ return 0
distinct_id, aliased_anonymous_id = resolve_distinct_id()
if aliased_anonymous_id:
@@ -963,17 +360,12 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
sent = 0
for start in range(0, len(events), BATCH_SIZE):
- chunk = events[start : start + BATCH_SIZE]
batch = [
{
"event": event["event"],
"distinct_id": distinct_id,
- # Carried through from record() so a resend can be collapsed.
- "uuid": event.get("uuid"),
"timestamp": event.get("timestamp"),
"properties": {
- # Fallback only: events recorded by a build before source
- # moved into record() have none of their own.
"source": _source_tag,
"language": "python",
"$process_person_profile": False,
@@ -981,24 +373,16 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
**(event.get("properties") or {}),
},
}
- for event in chunk
+ for event in events[start : start + BATCH_SIZE]
]
if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL):
- # Keep only what has not been delivered, and release the lease.
- # Previously the whole file was kept and the retry re-posted every
- # batch, including the ones that had already arrived.
- _release_claim(claim, events[start:])
- return sent, False
- sent += len(chunk)
- # Record progress and refresh the lease after each successful batch, so
- # a crash repeats at most one batch instead of the entire file. If the
- # rewrite fails the claim still holds delivered events, so stop rather
- # than carry on as though progress were recorded โ continuing is how the
- # duplicate delivery this PR fixes would come back.
- if not _rewrite_claim(claim, events[start + len(chunk) :]):
- _release_claim(claim, events[start + len(chunk) :])
- return sent, False
- return sent, True
+ return sent
+ sent += len(batch)
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return sent
def main() -> int:
diff --git a/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl
index 569305ec7..9cc720c7a 100644
--- a/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl
+++ b/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl
@@ -7,8 +7,8 @@ disable-model-invocation: true
# Pause memory capture
To pause (hooks stop capturing and sending session content; a minimal
-telemetry ping still fires at session start, under your Mem0 account email,
-unless `MEM0_TELEMETRY=false`):
+anonymous telemetry ping still fires at session start unless
+`MEM0_TELEMETRY=false`):
```bash
python3 "{{PLUGIN_ROOT}}/core/memory_cli.py" --harness "{{HARNESS_ID}}" {{PLUGIN_DATA_ARG}} pause
diff --git a/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl
index 6c4fdd03c..3a255b1ad 100644
--- a/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl
+++ b/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl
@@ -12,9 +12,11 @@ Call `search_memories` with the user's question. Treat `--top-k`, `--category`,
query.
Omit `top_k` to use Mem0's configured default. Omit `category` to search every
-category. Omit `scope` to use the configured default, normally `repo`: this
-repository's shared memory, which everyone who works in it contributes to,
-plus your own preferences.
+category; a category is a best-effort label Mem0 assigned when it saved the
+memory, so if a category search misses, repeat it without the category. Omit
+`scope` to use the configured default, normally `repo`: this repository's
+shared memory, which everyone who works in it contributes to, plus your own
+preferences.
Pass `scope` when the question needs something else: `dir` to narrow the
shared memory to the directory you are working in (a package inside a
diff --git a/integrations/agent-plugin-core/tests/test_build.py b/integrations/agent-plugin-core/tests/test_build.py
index 23295cc38..54b5e5c6a 100644
--- a/integrations/agent-plugin-core/tests/test_build.py
+++ b/integrations/agent-plugin-core/tests/test_build.py
@@ -70,38 +70,6 @@ def test_portable_bundle_is_conformant_and_self_contained(tmp_path: Path) -> Non
assert not any(path.is_symlink() for path in root.rglob("*"))
-def _harness_identity(root: Path) -> dict[str, str]:
- """Read the generated core/_harness_id.py without importing it."""
- values: dict[str, str] = {}
- for line in (root / "core" / "_harness_id.py").read_text(encoding="utf-8").splitlines():
- if "=" in line and not line.lstrip().startswith("#"):
- name, _, raw = line.partition("=")
- values[name.strip()] = raw.strip().strip('"')
- return values
-
-
-def test_the_portable_bundle_declares_no_host_application(tmp_path: Path) -> None:
- """It runs in whatever editor a user drops it into, so it cannot know the host.
-
- X-Application is allowlisted server-side. A guessed value is silently dropped
- there, which is the worst outcome: the wire says we know the host and the
- stored event says we do not.
- """
- identity = _harness_identity(build("mem0-agent-plugin", "portable", tmp_path / "portable"))
-
- assert identity["PLATFORM_APPLICATION"] == ""
- # The PostHog-side label is still useful for grouping and stays populated.
- assert identity["HARNESS_ID"] == "coding-agent"
- assert identity["PLATFORM_SOURCE"] == "MEM0_PLUGIN"
-
-
-@pytest.mark.parametrize("host", ["claude-code", "cursor", "codex", "kimi", "antigravity"])
-def test_a_native_bundle_names_the_host_it_was_built_for(host: str, tmp_path: Path) -> None:
- identity = _harness_identity(build(host, "native", tmp_path / host))
-
- assert identity["PLATFORM_APPLICATION"] == host
-
-
@pytest.mark.parametrize("host", ["claude-code", "cursor", "codex", "kimi", "antigravity"])
def test_native_bundle_is_self_contained(host: str, tmp_path: Path) -> None:
root = build(host, "native", tmp_path / host)
diff --git a/integrations/agent-plugin-core/tests/test_spool_delivery.py b/integrations/agent-plugin-core/tests/test_spool_delivery.py
deleted file mode 100644
index accd631a6..000000000
--- a/integrations/agent-plugin-core/tests/test_spool_delivery.py
+++ /dev/null
@@ -1,446 +0,0 @@
-"""Delivery semantics of the telemetry spool: no duplicates, no starvation.
-
-These run against a built host's core in-process (not a subprocess) because they
-need to inject failures into ``_post``. The identity tests next door cover the
-uninitialised-process case that needs a real interpreter.
-"""
-
-from __future__ import annotations
-
-import importlib
-import json
-import os
-import sys
-import time
-from pathlib import Path
-
-import pytest
-
-CORE_ROOT = Path(__file__).resolve().parents[1]
-REPOSITORY_ROOT = CORE_ROOT.parents[1]
-HOST_CORE = REPOSITORY_ROOT / "integrations" / "claude-code-plugin" / "core"
-
-pytestmark = pytest.mark.skipif(not HOST_CORE.exists(), reason="claude-code-plugin is not built")
-
-
-@pytest.fixture()
-def telemetry(tmp_path, monkeypatch):
- # CI runs this directory and claude-code-plugin/tests in ONE pytest process,
- # and that suite's conftest sets MEM0_TELEMETRY=false at import, process-wide.
- # Without this the whole file silently no-ops: record() returns early and
- # every assertion sees an empty spool. Do not rely on ambient env.
- monkeypatch.setenv("MEM0_TELEMETRY", "true")
- monkeypatch.setenv("MEM0_CODE_DATA_DIR", str(tmp_path / "data"))
- monkeypatch.syspath_prepend(str(HOST_CORE))
-
- # Save and RESTORE rather than delete. claude-code-plugin/tests/conftest.py
- # imports memory_core once at collection and calls configure_harness() on it;
- # dropping the module left a later re-import with default harness config, so
- # tests in that suite failed depending on collection order.
- names = ("telemetry", "memory_core", "_harness_id")
- saved = {name: sys.modules.get(name) for name in names}
- for name in names:
- sys.modules.pop(name, None)
-
- module = importlib.import_module("telemetry")
- monkeypatch.setattr(module, "resolve_distinct_id", lambda: ("tester@example.com", ""))
- try:
- yield module
- finally:
- for name in names:
- sys.modules.pop(name, None)
- if saved[name] is not None:
- sys.modules[name] = saved[name]
-
-
-def _delivered(payloads):
- return [event for payload in payloads if "batch" in payload for event in payload["batch"]]
-
-
-def test_a_partial_failure_does_not_redeliver_what_already_arrived(telemetry):
- """Defect 2a: flush kept the whole claim on failure and retried from the top.
-
- 150 events across two batches, the second failing, previously delivered 250.
- """
- for index in range(150):
- telemetry.record("search", index=index)
-
- sent: list[dict] = []
- calls = {"n": 0}
-
- def flaky(payload, url):
- calls["n"] += 1
- if calls["n"] == 2: # second batch fails
- return False
- sent.append(payload)
- return True
-
- telemetry._post = flaky
- telemetry.flush()
-
- telemetry._post = lambda payload, url: sent.append(payload) or True
- telemetry.flush()
-
- events = _delivered(sent)
- assert len(events) == 150
- assert len({event["uuid"] for event in events}) == 150
-
-
-def test_a_fresh_claim_is_not_immediately_stealable(telemetry):
- """Defect 2b: rename preserves mtime, so a claim inherited the spool's age.
-
- With the last write older than the stale threshold, a claim made now looked
- abandoned the instant it existed and a second sender took it over.
- """
- telemetry.record("search")
- spool = telemetry._spool_path()
- old = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
- os.utime(spool, (old, old))
-
- first = telemetry._claim_spool()
- assert first is not None
-
- # A second sender starting right now must find nothing to take.
- assert telemetry._claim_parked(first.parent) is None
-
-
-def test_a_live_final_attempt_is_not_deleted_by_another_sender(telemetry):
- """Review finding: exhaustion was judged before liveness, so owners lost batches.
-
- Claiming a parked file bumps its attempt count and refreshes its mtime. Once
- the count reaches the budget, the owner draining it looked exhausted to every
- other sender, which unlinked the file out from under it. Everything in that
- batch was gone, which is precisely the loss this PR exists to stop.
- """
- telemetry.record("search", reason="owned-by-the-first-sender")
- spool = telemetry._spool_path()
- stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
- os.utime(spool, (stale, stale))
-
- claim = telemetry._claim_spool()
- assert claim is not None
-
- # Walk it to the final attempt, ageing it each round so it can be re-claimed.
- # _claim_spool hands back a0 and _release_claim keeps the name, so it takes
- # one full round per attempt to reach the budget.
- for _ in range(telemetry.MAX_CLAIM_ATTEMPTS):
- # Carry the marker through each rewrite so the final assertion proves the
- # events survived, not merely that some file with the right name did.
- telemetry._release_claim(claim, [{"event": "code.search", "uuid": "owned-by-the-first-sender"}])
- parked = sorted(claim.parent.glob("telemetry-*.sending"))
- assert parked, "the batch was dropped while still inside its budget"
- os.utime(parked[0], (stale, stale))
- claim = telemetry._claim_parked(claim.parent)
- assert claim is not None
-
- assert telemetry._claim_attempt(claim) >= telemetry.MAX_CLAIM_ATTEMPTS
- assert claim.exists()
-
- # The owner is draining it right now: fresh mtime, live lease.
- second_sender = telemetry._claim_parked(claim.parent)
-
- assert second_sender is None, "a second sender took a batch under a live lease"
- assert claim.exists(), "a second sender deleted a batch its owner was draining"
- assert "owned-by-the-first-sender" in claim.read_text(encoding="utf-8")
-
-
-def test_an_exhausted_batch_is_still_discarded_once_its_lease_lapses(telemetry):
- """The liveness check must defer the cleanup, not cancel it.
-
- Guards the obvious over-correction: skipping live claims is only safe if an
- abandoned one at the same attempt count is still reaped on a later run.
- """
- telemetry.record("search")
- spool = telemetry._spool_path()
- stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
- os.utime(spool, (stale, stale))
-
- claim = telemetry._claim_spool()
- assert claim is not None
- exhausted = claim.parent / telemetry._claim_name(telemetry.MAX_CLAIM_ATTEMPTS)
- claim.replace(exhausted)
- os.utime(exhausted, (stale, stale))
-
- assert telemetry._claim_parked(exhausted.parent) is None
- assert not exhausted.exists(), "an abandoned exhausted batch was left behind forever"
-
-
-def test_a_parked_batch_is_drained_behind_the_live_spool(telemetry):
- """Defect 6: parked claims were only reachable when no spool existed.
-
- Because sessions keep recording there usually was one, so a batch parked by
- a failed send waited until the 7-day expiry deleted it unsent โ even though
- its own presence is what starts the sender.
- """
- telemetry.record("parked")
- telemetry._post = lambda payload, url: False
- telemetry.flush()
-
- parked = list(telemetry.memory_core.data_dir().glob("telemetry-*.sending"))
- assert len(parked) == 1
- old = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
- os.utime(parked[0], (old, old))
-
- telemetry.record("fresh")
- sent: list[dict] = []
- telemetry._post = lambda payload, url: sent.append(payload) or True
- telemetry.flush()
-
- names = {event["event"] for event in _delivered(sent)}
- assert names == {"code.parked", "code.fresh"}
-
-
-def test_a_batch_is_retried_until_the_budget_is_spent_not_discarded(telemetry):
- """Expiry discards what failed repeatedly, not what merely sat for a while.
-
- The budget is the attempt count, because age cannot be one: every re-claim
- touches the mtime and every release backdates it, so age never accumulates.
- """
- telemetry.record("parked")
- telemetry._post = lambda payload, url: False
- telemetry.flush()
-
- parked = list(telemetry.memory_core.data_dir().glob("telemetry-*.sending"))
- assert len(parked) == 1
- assert telemetry._claim_attempt(parked[0]) < telemetry.MAX_CLAIM_ATTEMPTS
-
- sent: list[dict] = []
- telemetry._post = lambda payload, url: sent.append(payload) or True
- telemetry.flush()
-
- assert [event["event"] for event in _delivered(sent)] == ["code.parked"]
-
-
-def test_progress_is_recorded_after_every_batch(telemetry):
- """A crash repeats at most one batch, not the whole file."""
- for index in range(250):
- telemetry.record("search", index=index)
-
- calls = {"n": 0}
-
- def die_after_two(payload, url):
- calls["n"] += 1
- if calls["n"] > 2:
- return False
- return True
-
- telemetry._post = die_after_two
- telemetry.flush()
-
- parked = list(telemetry.memory_core.data_dir().glob("telemetry-*.sending"))
- assert len(parked) == 1
- remaining = parked[0].read_text(encoding="utf-8").strip().splitlines()
- # Two batches of 100 landed; only the last 50 should still be pending.
- assert len(remaining) == 50
- assert json.loads(remaining[0])["properties"]["index"] == 200
-
-
-def test_the_heartbeat_actually_refreshes_the_lease(telemetry):
- """The claim rewrite doubles as the lease heartbeat.
-
- Previously asserted `SEND_TIMEOUT * 4 < CLAIM_STALE_SECONDS`, which compares
- two constants and executes none of the code under test. Drive the real
- rewrite and watch the mtime move instead.
- """
- for index in range(150):
- telemetry.record("search", index=index)
- claim = telemetry._claim_spool()
- assert claim is not None
-
- stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
- os.utime(claim, (stale, stale))
- assert time.time() - claim.stat().st_mtime > telemetry.CLAIM_STALE_SECONDS
-
- telemetry._rewrite_claim(claim, [{"event": "code.x", "properties": {}}])
- assert time.time() - claim.stat().st_mtime < telemetry.CLAIM_STALE_SECONDS
-
-
-def test_an_undeliverable_batch_is_eventually_given_up_on(telemetry):
- """Expiry has to be reachable from a state the state machine can produce.
-
- It was not: every re-claim touched the mtime and every release backdated it
- by a fixed amount, so age hovered near the stale threshold and the 7-day
- expiry never fired. An undeliverable batch lived on disk forever, and
- spawn_flush saw it and started a sender on every hook.
- """
- telemetry.record("doomed")
- telemetry._post = lambda payload, url: False
-
- directory = telemetry.memory_core.data_dir()
- for _ in range(telemetry.MAX_CLAIM_ATTEMPTS + 3):
- telemetry.flush()
- # Attempts now carry a cooldown, so a released claim is not instantly
- # reclaimable. Age it to stand in for the wall time a real retry waits;
- # without this the loop spins inside one cooldown and proves nothing.
- for parked in directory.glob("telemetry-*.sending"):
- stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
- os.utime(parked, (stale, stale))
-
- leftover = list(directory.glob("telemetry-*.sending"))
- assert leftover == [], f"batch never given up on: {[p.name for p in leftover]}"
-
-
-def test_a_batch_that_cannot_be_read_is_not_counted_as_delivered(telemetry):
- """Review finding: a read failure reported 'everything delivered'.
-
- Nothing was posted, so calling it delivered lets flush() carry on to other
- claims as though this batch had arrived, and hides the failure from the one
- signal that says the run went badly. It also must not quarantine: a briefly
- unreadable file is retryable, and moving it to .corrupt discards the events
- over a transient filesystem error, because nothing ever re-globs .corrupt.
- """
- telemetry.record("search")
- spool = telemetry._spool_path()
- stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
- os.utime(spool, (stale, stale))
- claim = telemetry._claim_spool()
- assert claim is not None
-
- original = Path.read_text
-
- def unreadable(self, *args, **kwargs):
- if self == claim:
- raise OSError(5, "I/O error")
- return original(self, *args, **kwargs)
-
- Path.read_text = unreadable
- try:
- sent, delivered = telemetry._drain(claim)
- finally:
- Path.read_text = original
-
- assert sent == 0
- assert delivered is False, "an unread batch was reported as delivered"
- assert claim.exists(), "a transient read error discarded the batch"
- assert not list(claim.parent.glob("*.corrupt")), "quarantined over a transient error"
-
-
-def test_undecodable_content_is_still_quarantined_and_the_run_continues(telemetry):
- """The other half: genuinely unrecoverable content must not block the run.
-
- Guards the over-correction. If every read problem returned undelivered, one
- torn file would stop every later claim on every flush, forever.
- """
- telemetry.record("search")
- spool = telemetry._spool_path()
- stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
- os.utime(spool, (stale, stale))
- claim = telemetry._claim_spool()
- assert claim is not None
- claim.write_bytes(b"\xff\xfe torn \x00 write")
-
- sent, delivered = telemetry._drain(claim)
-
- assert (sent, delivered) == (0, True)
- assert not claim.exists()
- assert list(claim.parent.glob("*.corrupt")), "unrecoverable content was not quarantined"
-
-
-def test_retries_are_spread_over_real_time_not_burned_at_once(telemetry):
- """Review finding: releasing straight to reclaimable spent the budget instantly.
-
- Two senders hitting one momentary failure could walk a batch from attempt 0
- to the limit within seconds and discard it, when a retry a minute later would
- have delivered. Each release now has to age past a cooldown that grows with
- the attempts already spent.
- """
- telemetry.record("doomed")
- telemetry._post = lambda payload, url: False
-
- directory = telemetry.memory_core.data_dir()
- telemetry.flush()
-
- parked = list(directory.glob("telemetry-*.sending"))
- assert parked, "the batch was discarded on its first failure"
- assert telemetry._claim_attempt(parked[0]) == 0
-
- # Second sender, immediately: the cooldown has not elapsed, so it must not
- # be able to spend another attempt.
- telemetry.flush()
- still = list(directory.glob("telemetry-*.sending"))
- assert len(still) == 1
- assert telemetry._claim_attempt(still[0]) <= 1, "burned attempts without waiting"
-
-
-def test_a_legacy_claim_filename_is_not_mistaken_for_a_huge_attempt_count(telemetry):
- """The old shape is telemetry--.sending, and hex can start with 'a'."""
- assert telemetry._claim_attempt(Path("telemetry-999-deadbeef.sending")) == 0
- assert telemetry._claim_attempt(Path("telemetry-999-a1234567.sending")) == 0
- assert telemetry._claim_attempt(Path("telemetry-999-deadbeef-a2.sending")) == 2
-
-
-def test_a_torn_claim_is_quarantined_not_deleted(telemetry):
- """A non-empty file that parses to nothing is the remainder, not garbage."""
- telemetry.record("search")
- claim = telemetry._claim_spool()
- claim.write_bytes(b"\xff\xfe not utf-8 at all")
- stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
- os.utime(claim, (stale, stale))
-
- sent = telemetry.flush()
-
- assert sent == 0
- assert not claim.exists()
- quarantined = list(telemetry.memory_core.data_dir().glob("*.corrupt"))
- assert len(quarantined) == 1, "torn claim was destroyed instead of kept"
-
-
-def test_a_failed_rewrite_stops_instead_of_redelivering(telemetry):
- """Ignoring the rewrite result reintroduced the duplicates this PR fixes."""
- for index in range(250):
- telemetry.record("search", index=index)
-
- telemetry._rewrite_claim = lambda claim, remaining: False
- delivered = []
- telemetry._post = lambda payload, url: delivered.extend(payload.get("batch", [])) or True
-
- telemetry.flush()
- assert len(delivered) == 100, f"kept going after a failed rewrite: {len(delivered)}"
-
-
-def test_partial_files_are_swept(telemetry):
- """Nothing else globs *.partial, so a crash mid-rename orphans one forever."""
- data_dir = telemetry.memory_core.data_dir()
- data_dir.mkdir(parents=True, exist_ok=True)
- debris = data_dir / "telemetry-1-abc-a0.1.partial"
- debris.write_text("x", encoding="utf-8")
- old = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
- os.utime(debris, (old, old))
-
- telemetry.flush()
- assert not debris.exists()
-
-
-def test_quarantined_batches_are_eventually_collected(telemetry):
- """Nothing re-globs .corrupt, so without a sweep they live on disk forever.
-
- Kept much longer than .partial debris on purpose: a quarantined batch is the
- only remaining evidence of events that could not be delivered.
- """
- directory = telemetry.memory_core.data_dir()
- directory.mkdir(parents=True, exist_ok=True)
- fresh = directory / "telemetry-1-aaaaaaaa-a0.corrupt"
- old = directory / "telemetry-2-bbbbbbbb-a0.corrupt"
- for path in (fresh, old):
- path.write_text("torn", encoding="utf-8")
- expired = time.time() - (telemetry.CLAIM_EXPIRY_SECONDS + 60)
- os.utime(old, (expired, expired))
-
- telemetry._sweep_debris(directory)
-
- assert fresh.exists(), "a recent quarantine was discarded before anyone could look at it"
- assert not old.exists(), "an expired quarantine was left on disk forever"
-
-
-def test_temp_files_orphaned_by_a_kill_are_collected(telemetry):
- """_write_identity and _install_salt unlink in a finally, which SIGKILL skips."""
- directory = telemetry.memory_core.data_dir()
- directory.mkdir(parents=True, exist_ok=True)
- orphan = directory / "telemetry-salt.999.tmp"
- orphan.write_text("abandoned", encoding="utf-8")
- stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60)
- os.utime(orphan, (stale, stale))
-
- telemetry._sweep_debris(directory)
-
- assert not orphan.exists(), "a killed process left a temp file on disk forever"
diff --git a/integrations/agent-plugin-core/tests/test_uninitialised_identity.py b/integrations/agent-plugin-core/tests/test_uninitialised_identity.py
deleted file mode 100644
index 74a31fa5c..000000000
--- a/integrations/agent-plugin-core/tests/test_uninitialised_identity.py
+++ /dev/null
@@ -1,274 +0,0 @@
-"""Core telemetry behaviour with NO telemetry.init(), in a real subprocess.
-
-Why this file exists
---------------------
-``telemetry.py`` lives in ``agent-plugin-core/python/`` but its only tests lived
-under ``claude-code-plugin/tests/``, behind a ``conftest.py`` that calls
-``configure_harness()`` and ``telemetry.init()`` at import. Core behaviour was
-therefore only ever exercised inside an already-configured module.
-
-Two processes in the real pipeline never call ``init()``:
-
-- ``mcp_server.py``, which records every manual search;
-- the detached ``python3 telemetry.py`` sender that ``spawn_flush()`` starts at
- session start, after every skill command, and when the MCP server exits.
-
-Both fell back to module defaults, so MCP searches reported ``harness=generic``
-and everything that sender delivered was labelled ``MEM0_PLUGIN`` regardless of
-which of the six plugins produced it. The suite stayed green throughout.
-
-These tests run in a fresh interpreter with no conftest, against a built host
-bundle, which is the only arrangement that can catch that class of bug.
-"""
-
-from __future__ import annotations
-
-import json
-import subprocess
-import sys
-import tempfile
-from pathlib import Path
-
-import pytest
-
-CORE_ROOT = Path(__file__).resolve().parents[1]
-REPOSITORY_ROOT = CORE_ROOT.parents[1]
-HOSTS = {
- "claude-code": ("claude-code-plugin", "CLAUDE_CODE_PLUGIN"),
- "cursor": ("cursor-plugin", "CURSOR_PLUGIN"),
- "codex": ("codex-plugin", "CODEX_PLUGIN"),
- "kimi": ("kimi-plugin", "KIMI_PLUGIN"),
- "antigravity": ("antigravity-plugin", "ANTIGRAVITY_PLUGIN"),
- # Portable: no flush_worker and no hook_runner, so its ONLY sender is the
- # uninitialised telemetry.py. A native-only test passes here vacuously.
- "coding-agent": ("mem0-agent-plugin", "CODING_AGENT_PLUGIN"),
-}
-
-
-def _core_dir(directory: str) -> Path:
- return REPOSITORY_ROOT / "integrations" / directory / "core"
-
-
-def _run(core: Path, data_dir: Path, body: str) -> str:
- """Execute `body` in a fresh interpreter with only the host's core on sys.path."""
- script = f"import sys; sys.path.insert(0, {str(core)!r})\n{body}"
- result = subprocess.run(
- [sys.executable, "-c", script],
- capture_output=True,
- text=True,
- env={
- "MEM0_CODE_DATA_DIR": str(data_dir),
- "PATH": "/usr/bin:/bin",
- "HOME": str(data_dir),
- },
- )
- assert result.returncode == 0, result.stderr
- return result.stdout.strip()
-
-
-@pytest.mark.parametrize("harness,spec", sorted(HOSTS.items()))
-def test_identity_resolves_without_init(harness, spec):
- """Every built host knows what it is with no configuration call at all."""
- directory, source_tag = spec
- core = _core_dir(directory)
- if not core.exists():
- pytest.skip(f"{directory} is not built in this tree")
-
- with tempfile.TemporaryDirectory() as tmp:
- out = _run(
- core,
- Path(tmp),
- "import telemetry; print(telemetry._harness, telemetry._source_tag)",
- )
- assert out == f"{harness} {source_tag}"
-
-
-def test_mcp_server_records_the_real_harness():
- """mcp_server imports telemetry and never initialises it (server.py has no init).
-
- Its recorded events used to carry harness=generic for every plugin.
- """
- core = _core_dir("claude-code-plugin")
- if not core.exists():
- pytest.skip("claude-code-plugin is not built in this tree")
-
- with tempfile.TemporaryDirectory() as tmp:
- data_dir = Path(tmp)
- _run(
- core,
- data_dir,
- "import mcp_server, telemetry; telemetry.record('search', trigger='mcp-search')",
- )
- spooled = (data_dir / "telemetry.jsonl").read_text(encoding="utf-8").strip()
-
- event = json.loads(spooled)
- assert event["properties"]["harness"] == "claude-code"
- assert event["properties"]["source"] == "CLAUDE_CODE_PLUGIN"
-
-
-def test_the_detached_sender_does_not_relabel_events():
- """`python3 telemetry.py` is the sender spawn_flush() starts, and never inits.
-
- source is stamped at record time now, so which process sends is irrelevant.
- """
- core = _core_dir("claude-code-plugin")
- if not core.exists():
- pytest.skip("claude-code-plugin is not built in this tree")
-
- with tempfile.TemporaryDirectory() as tmp:
- data_dir = Path(tmp)
- _run(core, data_dir, "import telemetry; telemetry.record('search')")
-
- captured = data_dir / "captured.json"
- # Drain with a fresh, unconfigured interpreter, capturing the payload
- # instead of posting it.
- _run(
- core,
- data_dir,
- "import json, telemetry\n"
- "sent = []\n"
- "telemetry._post = lambda payload, url: sent.append(payload) or True\n"
- "telemetry.flush()\n"
- f"open({str(captured)!r}, 'w').write(json.dumps(sent))",
- )
- payloads = json.loads(captured.read_text(encoding="utf-8"))
-
- batches = [p for p in payloads if "batch" in p]
- assert batches, "nothing was sent"
- properties = batches[0]["batch"][0]["properties"]
- assert properties["source"] == "CLAUDE_CODE_PLUGIN"
- assert properties["harness"] == "claude-code"
-
-
-def test_every_event_carries_a_uuid_for_dedupe():
- core = _core_dir("claude-code-plugin")
- if not core.exists():
- pytest.skip("claude-code-plugin is not built in this tree")
-
- with tempfile.TemporaryDirectory() as tmp:
- data_dir = Path(tmp)
- _run(core, data_dir, "import telemetry; telemetry.record('search'); telemetry.record('flush')")
- lines = (data_dir / "telemetry.jsonl").read_text(encoding="utf-8").strip().splitlines()
-
- ids = [json.loads(line)["uuid"] for line in lines]
- assert len(ids) == 2
- assert len(set(ids)) == 2
-
-
-def test_source_tag_defaults_agree_between_the_two_modules():
- """configure_harness and telemetry.init must derive the same tag.
-
- They disagreed: `_plugin` in one and `MEM0__PLUGIN` in the other,
- so one plugin could emit three different source values depending on which
- process sent the batch.
- """
- core = _core_dir("claude-code-plugin")
- if not core.exists():
- pytest.skip("claude-code-plugin is not built in this tree")
-
- with tempfile.TemporaryDirectory() as tmp:
- out = _run(
- core,
- Path(tmp),
- "import memory_core, telemetry\n"
- "memory_core.configure_harness('kimi')\n"
- "telemetry.init(harness='kimi')\n"
- "print(memory_core.harness_config()['source_tag'].upper(), telemetry._source_tag)",
- )
- left, right = out.split()
- assert left == right == "KIMI_PLUGIN"
-
-
-def test_the_plugin_declares_its_surface_in_the_body_and_the_headers():
- """Body and headers both, because only the body works on every backend."""
- core = _core_dir("claude-code-plugin")
- if not core.exists():
- pytest.skip("claude-code-plugin is not built in this tree")
-
- with tempfile.TemporaryDirectory() as tmp:
- out = _run(
- core,
- Path(tmp),
- "import json, memory_core\n"
- "h = memory_core.platform_headers('k')\n"
- "print(json.dumps({'source': h.get('X-Mem0-Source'),"
- " 'app': h.get('X-Application'),"
- " 'client': h.get('X-Mem0-Client'),"
- " 'auth': h.get('Authorization'),"
- " 'ctype': h.get('Content-Type')}))",
- )
- headers = json.loads(out)
- assert headers["source"] == "MEM0_PLUGIN"
- assert headers["app"] == "claude-code"
- assert headers["client"].startswith("mem0-plugin/")
- # The transport headers the three call sites relied on must survive.
- assert headers["auth"] == "Token k"
- assert headers["ctype"] == "application/json"
-
-
-def _session_start(core: Path, data_dir: Path) -> list[str]:
- """Drive the real hook_runner session-start path and return lifecycle events."""
- recorded = "\n".join(
- [
- "import io, json, sys",
- f"sys.path.insert(0, {str(core)!r})",
- "import telemetry, hook_runner",
- "seen = []",
- "telemetry.record = lambda event, **kw: seen.append(event) or None",
- "telemetry.spawn_flush = lambda: False",
- # run() reads sys.argv through argparse; it takes no positional args.
- "sys.argv = ['hook_runner', 'session-start']",
- "sys.stdin = io.StringIO('{}')",
- "hook_runner.run()",
- "print(json.dumps([e for e in seen if e in ('install', 'upgrade')]))",
- ]
- )
- import json as _json
-
- return _json.loads(_run(core, data_dir, recorded) or "[]")
-
-
-def test_a_fresh_install_reports_install_not_upgrade():
- """The decision must survive the writes hook_runner does before asking.
-
- claim_install() is reached only after cache_plugin_api_key() has written
- `api-key` and EvidenceStore() has created `evidence.sqlite3`. Asking "is the
- data dir empty" at that point always saw content, so code.install could
- never fire and every new user was counted as an upgrade.
- """
- core = _core_dir("claude-code-plugin")
- if not core.exists():
- pytest.skip("claude-code-plugin is not built in this tree")
-
- with tempfile.TemporaryDirectory() as tmp:
- data_dir = Path(tmp) / "data"
- assert _session_start(core, data_dir) == ["install"]
-
-
-def test_the_lifecycle_event_fires_exactly_once():
- core = _core_dir("claude-code-plugin")
- if not core.exists():
- pytest.skip("claude-code-plugin is not built in this tree")
-
- with tempfile.TemporaryDirectory() as tmp:
- data_dir = Path(tmp) / "data"
- first = _session_start(core, data_dir)
- second = _session_start(core, data_dir)
- third = _session_start(core, data_dir)
-
- assert first == ["install"]
- assert second == []
- assert third == []
-
-
-def test_an_existing_data_dir_reports_upgrade():
- core = _core_dir("claude-code-plugin")
- if not core.exists():
- pytest.skip("claude-code-plugin is not built in this tree")
-
- with tempfile.TemporaryDirectory() as tmp:
- data_dir = Path(tmp) / "data"
- data_dir.mkdir(parents=True)
- # A 0.2.x leftover: the data dir survives the upgrade.
- (data_dir / "requirements.txt").write_text("mem0ai\n", encoding="utf-8")
- assert _session_start(core, data_dir) == ["upgrade"]
diff --git a/integrations/agent-plugin-core/typescript/src/lifecycle.ts b/integrations/agent-plugin-core/typescript/src/lifecycle.ts
index 738ccc1c7..42c522b54 100644
--- a/integrations/agent-plugin-core/typescript/src/lifecycle.ts
+++ b/integrations/agent-plugin-core/typescript/src/lifecycle.ts
@@ -1,6 +1,5 @@
import type { MemoryLike } from "./formatting.ts";
import { formatMemoryCompact } from "./formatting.ts";
-import { RECALL_HEADING } from "./prompts.ts";
const MAX_RECALL_QUERY_CHARS = 6_000;
export const DEFAULT_MAX_CONTEXT_CHARS = 4_000;
@@ -71,14 +70,12 @@ export function extractConversation(
}
interface RecallOptions {
- heading?: string;
maxChars?: number;
seenIds?: Set;
timeoutMs?: number;
}
interface MemoryLifecycleOptions {
- recallHeading?: string;
maxContextChars?: number;
recallTimeoutMs?: number;
}
@@ -112,7 +109,6 @@ class MemoryLifecycle {
search: (query: string) => Promise<{ results?: unknown[] }>,
): Promise {
return buildRecallContext(prompt, enabled, search, {
- heading: this.#options.recallHeading,
maxChars: this.#options.maxContextChars,
seenIds: this.#seenMemoryIds,
timeoutMs: this.#options.recallTimeoutMs,
@@ -152,7 +148,8 @@ export async function buildRecallContext(
const unseen = memories.filter((memory) => !options.seenIds?.has(memory.id));
if (!unseen.length) return "";
- const prefix = `\n${options.heading ?? RECALL_HEADING}\n`;
+ const prefix =
+ "\nRetrieved automatically for the current request. This is a shallow first pass โ search mem0_memory for more if you need it.\n";
const suffix = "\n";
const maxChars = options.maxChars ?? DEFAULT_MAX_CONTEXT_CHARS;
const lines: string[] = [];
diff --git a/integrations/agent-plugin-core/typescript/src/prompts.ts b/integrations/agent-plugin-core/typescript/src/prompts.ts
deleted file mode 100644
index cb4d4e07b..000000000
--- a/integrations/agent-plugin-core/typescript/src/prompts.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-export const SEARCH_WHEN =
- "before repeating investigation or when earlier decisions, fixes, commands, or results may help";
-
-export const SEARCH_TOOL_DESCRIPTION = `Search memories from earlier work in this repository. Use it ${SEARCH_WHEN}.`;
-export const SEARCH_QUERY_DESCRIPTION = "A direct question about earlier work in this repository.";
-export const RECALL_HEADING = "Mem0 found these relevant memories from earlier work in this repository:";
-
-export const USER_SEARCH_TOOL_DESCRIPTION = `Search memories from earlier work. Use it ${SEARCH_WHEN}.`;
-export const USER_SEARCH_QUERY_DESCRIPTION = "A direct question about earlier work.";
-export const USER_RECALL_HEADING = "Mem0 found these relevant memories from earlier work:";
diff --git a/integrations/agent-plugin-core/typescript/src/telemetry.ts b/integrations/agent-plugin-core/typescript/src/telemetry.ts
index 2b6c5286e..c6a7544ce 100644
--- a/integrations/agent-plugin-core/typescript/src/telemetry.ts
+++ b/integrations/agent-plugin-core/typescript/src/telemetry.ts
@@ -1,5 +1,3 @@
-import { randomUUID } from "node:crypto";
-
import { redactSecrets } from "./lifecycle.ts";
const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX";
@@ -76,108 +74,34 @@ export function errorKind(error: unknown): string {
return error instanceof Error ? error.constructor.name : "other";
}
-// Delivery is retried in memory, not spooled to disk, and that is a decision
-// rather than an omission. The Python core spools because its hooks are separate
-// processes that fire per tool call and exit immediately, so nothing survives
-// without a file. These plugins are loaded into a host that lives for a whole
-// session, so re-queueing covers the same transient failures without the claim
-// and lease machinery a correct cross-process spool needs. What that leaves
-// uncovered is narrow: a session that both starts and ends with no connectivity.
-const RETRY_BACKOFF_CEILING_MS = 60_000;
-// Consecutive failed flushes before the queue is dropped. Deliberately NOT the
-// same thing as Python's budget, which rides in the claim filename and so
-// follows one batch: this counter lives in the closure and counts the outage,
-// not the payload. Events captured between attempts join the same queue and go
-// with it. Per-batch accounting would need an attempt count on every event, and
-// the queue is already bounded, so the simpler rule is the one in force here.
-// Without any bound a payload the server will never accept is retried for the
-// whole session and, now that the backlog is preferred over new events, holds
-// the queue against everything behind it.
-const MAX_DELIVERY_ATTEMPTS = 5;
-
export function createTelemetry(config: TelemetryConfig) {
let queue: Record[] = [];
let timer: ReturnType | undefined;
- let consecutiveFailures = 0;
- let retryNotBefore = 0;
- let exitFlushAttempted = false;
- let flushing = false;
const flushThreshold = config.flushThreshold ?? 10;
const maxQueueSize = config.maxQueueSize ?? 100;
const deliver = config.delivery ?? (async (batch: Record[]) => {
- const response = await fetch(POSTHOG_BATCH_URL, {
+ await fetch(POSTHOG_BATCH_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ api_key: POSTHOG_API_KEY, batch }),
signal: AbortSignal.timeout(3_000),
});
- // fetch only rejects on a network-level failure. Without this check a 500,
- // a 503 or a 429 resolved normally and the batch was counted as delivered
- // and dropped, which is the likelier outage than a refused connection.
- // Any non-2xx is retried, matching the Python core: the backoff and the
- // queue bound contain a payload that will never be accepted, because the
- // re-queued batch sits at the front and is the first thing evicted.
- if (!response.ok) throw new Error(`posthog responded ${response.status}`);
});
- async function flush(force = false): Promise {
- // One at a time. Two overlapping flushes each detach the queue and each
- // prepend their own batch back on failure, so the later batch lands in front
- // of the earlier one and the truncation then drops the OLDER events first,
- // inverting the priority the failure path exists to establish. A second
- // caller returns immediately; the queue waits for the next flush.
- if (flushing) return;
+ async function flush(): Promise {
if (!queue.length) return;
- // `force` skips the cooldown. beforeExit is the last chance this process
- // gets, and gating it on the same backoff meant that after any failure the
- // exit flush did nothing and the queue died with the process, which is the
- // loss this whole mechanism exists to prevent.
- if (!force && Date.now() < retryNotBefore) return;
const batch = queue;
queue = [];
- flushing = true;
try {
await deliver(batch);
- consecutiveFailures = 0;
- retryNotBefore = 0;
} catch {
- // Put it back. Detaching the batch and swallowing the error deleted the
- // events outright, so any blip silently dropped telemetry with nothing
- // recording that it had happened. Every event carries a uuid, so a retry
- // that duplicates one PostHog already accepted is collapsed there.
- //
- consecutiveFailures += 1;
- if (consecutiveFailures >= MAX_DELIVERY_ATTEMPTS) {
- // Give up on the queue so a failing outage cannot hold it for the
- // session. This drops whatever is queued now, which includes events
- // captured during the outage, not only the batch that kept failing.
- consecutiveFailures = 0;
- retryNotBefore = 0;
- return;
- }
- // Keep the FRONT on overflow, so the batch being retried survives and a
- // new event is what gets dropped. Matches the Python core, where record()
- // refuses new events once the spool is full rather than evicting the
- // backlog. Keeping the newest would throw away exactly the events this
- // retry exists to save.
- queue = [...batch, ...queue].slice(0, maxQueueSize);
- retryNotBefore = Date.now() + Math.min(2 ** consecutiveFailures * 1_000, RETRY_BACKOFF_CEILING_MS);
- } finally {
- flushing = false;
+ // Telemetry must never affect plugin behavior.
}
}
function beforeExit(): void {
- // Once, and only once. Node re-emits beforeExit whenever the handler
- // schedules more async work, so an unconditional forced flush looped until
- // the attempt budget was spent: five attempts against a 3s delivery timeout
- // is fifteen seconds added to the shutdown of whatever editor or CLI is
- // hosting this. The backoff used to end that loop after one attempt, and
- // removing it for the forced path removed the only thing bounding it.
- if (exitFlushAttempted) return;
- exitFlushAttempted = true;
- void flush(true);
+ void flush();
}
function build(event: string, properties: Record = {}): Record | null {
@@ -188,15 +112,6 @@ export function createTelemetry(config: TelemetryConfig) {
return {
event: config.eventName?.(event) ?? event,
distinct_id: distinctId,
- // Stamped once, at capture. This is what makes retrying safe: a batch
- // re-sent after a failure carries the same ids, so PostHog collapses
- // anything it already accepted instead of counting it twice.
- uuid: randomUUID(),
- // Capture time, not ingestion time. Events now sit through backoff and
- // across a whole outage, so without this PostHog records them whenever
- // delivery happened to succeed. It also matters for the uuid dedupe
- // above, whose key includes the event date.
- timestamp: new Date().toISOString(),
properties: {
...safeProperties(properties),
...safeProperties(config.commonProperties ?? {}),
@@ -219,10 +134,8 @@ export function createTelemetry(config: TelemetryConfig) {
try {
const payload = build(event, properties);
if (!payload) return;
- // Full means drop this event, not evict the backlog. Same rule as the
- // failure path above and as Python's record().
- if (queue.length >= maxQueueSize) return;
queue.push(payload);
+ if (queue.length > maxQueueSize) queue = queue.slice(-maxQueueSize);
if (!timer) {
timer = setInterval(() => void flush(), config.flushIntervalMs ?? 5_000);
timer.unref?.();
@@ -236,8 +149,6 @@ export function createTelemetry(config: TelemetryConfig) {
function resetForTesting(): void {
queue = [];
- consecutiveFailures = 0;
- retryNotBefore = 0;
if (timer) clearInterval(timer);
timer = undefined;
process.off("beforeExit", beforeExit);
diff --git a/integrations/agent-plugin-core/typescript/tests/prompts.test.ts b/integrations/agent-plugin-core/typescript/tests/prompts.test.ts
deleted file mode 100644
index 3090c1d51..000000000
--- a/integrations/agent-plugin-core/typescript/tests/prompts.test.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import assert from "node:assert/strict";
-import { readFileSync } from "node:fs";
-import test from "node:test";
-
-import { buildRecallContext } from "../src/lifecycle.ts";
-import {
- RECALL_HEADING,
- SEARCH_QUERY_DESCRIPTION,
- SEARCH_TOOL_DESCRIPTION,
- USER_RECALL_HEADING,
-} from "../src/prompts.ts";
-
-const pythonSource = (name: string) =>
- readFileSync(new URL(`../../python/${name}`, import.meta.url), "utf8").replace(/"\s*\n\s*"/g, "");
-
-test("search prompts match the Python core", () => {
- assert.ok(pythonSource("mcp_server.py").includes(SEARCH_TOOL_DESCRIPTION));
- assert.ok(pythonSource("mcp_server.py").includes(SEARCH_QUERY_DESCRIPTION));
- assert.ok(pythonSource("hook_runner.py").includes(RECALL_HEADING));
-});
-
-test("recall context uses the repository heading unless the host overrides it", async () => {
- const search = async () => ({ results: [{ id: "m1", memory: "Use pnpm" }] });
-
- assert.ok((await buildRecallContext("package manager", true, search)).includes(RECALL_HEADING));
- assert.ok(
- (await buildRecallContext("package manager", true, search, { heading: USER_RECALL_HEADING })).includes(
- USER_RECALL_HEADING,
- ),
- );
-});
diff --git a/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts b/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts
index cf9671682..e04794614 100644
--- a/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts
+++ b/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts
@@ -122,250 +122,3 @@ test("error classification does not expose messages", () => {
assert.equal(errorKind(new Error("request timeout")), "timeout");
assert.equal(errorKind(new Error("fetch failed")), "network");
});
-
-test("a failed delivery keeps the batch instead of deleting it", async () => {
- // The defect: the queue was detached before the await and the error swallowed,
- // so one blip destroyed the events with nothing recording that it happened.
- const attempts: Record[][] = [];
- let failNext = true;
- const telemetry = createTelemetry({
- host: "h", source: "S", version: "1", distinctId: "d",
- flushThreshold: 1000,
- delivery: async (batch) => {
- attempts.push(batch);
- if (failNext) throw new Error("network down");
- },
- });
-
- telemetry.capture("one");
- telemetry.capture("two");
- await telemetry.flush();
-
- assert.equal(attempts.length, 1);
- assert.equal(telemetry.queueForTesting().length, 2, "events were dropped on failure");
-
- failNext = false;
- // Backoff is in force, so wait it out the way wall time would.
- await new Promise((resolve) => setTimeout(resolve, 2_100));
- await telemetry.flush();
-
- assert.equal(attempts.length, 2, "never retried");
- assert.equal(telemetry.queueForTesting().length, 0);
- telemetry.resetForTesting();
-});
-
-test("a retried event carries the same uuid so PostHog can collapse it", async () => {
- const attempts: Record[][] = [];
- let failNext = true;
- const telemetry = createTelemetry({
- host: "h", source: "S", version: "1", distinctId: "d",
- flushThreshold: 1000,
- delivery: async (batch) => {
- attempts.push(batch);
- if (failNext) throw new Error("network down");
- },
- });
-
- telemetry.capture("once");
- await telemetry.flush();
- failNext = false;
- await new Promise((resolve) => setTimeout(resolve, 2_100));
- await telemetry.flush();
-
- assert.equal(attempts.length, 2);
- const first = attempts[0][0].uuid;
- assert.ok(first, "events carry no uuid, so a retry would double count");
- assert.equal(attempts[1][0].uuid, first, "retry minted a new uuid");
- telemetry.resetForTesting();
-});
-
-test("repeated failures back off instead of retrying every flush", async () => {
- let calls = 0;
- const telemetry = createTelemetry({
- host: "h", source: "S", version: "1", distinctId: "d",
- flushThreshold: 1000,
- delivery: async () => { calls += 1; throw new Error("blocked"); },
- });
-
- telemetry.capture("one");
- await telemetry.flush();
- await telemetry.flush();
- await telemetry.flush();
-
- assert.equal(calls, 1, "a blocked host was hammered on every flush");
- assert.equal(telemetry.queueForTesting().length, 1, "the event was lost while backing off");
- telemetry.resetForTesting();
-});
-
-test("a full queue drops the new event and keeps the batch being retried", async () => {
- // Python's record() refuses new events once the spool is full rather than
- // evicting the backlog. Keeping the newest here would throw away exactly the
- // events the retry exists to save.
- const telemetry = createTelemetry({
- host: "h", source: "S", version: "1", distinctId: "d",
- flushThreshold: 1000, maxQueueSize: 3,
- delivery: async () => { throw new Error("down"); },
- });
-
- // Fill past the cap BEFORE the flush, so the re-queue actually has to truncate.
- // Capturing only two left the queue empty at re-queue time and the slice on the
- // failure path never ran, which is the half that decides the direction.
- telemetry.capture("a");
- telemetry.capture("b");
- telemetry.capture("c");
- await telemetry.flush();
- telemetry.capture("d");
- telemetry.capture("e");
-
- const events = telemetry.queueForTesting().map((e) => (e as any).event);
- assert.equal(events.length, 3, "queue grew past maxQueueSize");
- assert.deepEqual(events, ["a", "b", "c"], "the retried batch was evicted instead of the new events");
- telemetry.resetForTesting();
-});
-
-test("the exit-time flush ignores the backoff", async () => {
- // beforeExit is the last chance the process gets. Gating it on the same
- // cooldown meant that after any failure it did nothing and the queue died.
- let attempts = 0;
- let failing = true;
- const telemetry = createTelemetry({
- host: "h", source: "S", version: "1", distinctId: "d", flushThreshold: 1000,
- delivery: async () => { attempts += 1; if (failing) throw new Error("down"); },
- });
-
- telemetry.capture("a");
- await telemetry.flush();
- assert.equal(attempts, 1);
-
- failing = false;
- await telemetry.flush();
- assert.equal(attempts, 1, "the backoff should still hold for an ordinary flush");
-
- await telemetry.flush(true);
- assert.equal(attempts, 2, "the exit flush was suppressed by the backoff");
- assert.equal(telemetry.queueForTesting().length, 0);
- telemetry.resetForTesting();
-});
-
-test("every event carries a capture-time timestamp", async () => {
- const sent: Record[][] = [];
- const telemetry = createTelemetry({
- host: "h", source: "S", version: "1", distinctId: "d", flushThreshold: 1000,
- delivery: async (batch) => { sent.push(batch); },
- });
-
- telemetry.capture("a");
- const capturedAt = Date.now();
- await new Promise((resolve) => setTimeout(resolve, 50));
- await telemetry.flush();
-
- const stamped = sent[0][0].timestamp as string;
- assert.ok(stamped, "no timestamp, so PostHog would record delivery time");
- assert.ok(Math.abs(Date.parse(stamped) - capturedAt) < 1_000, "not capture time");
- telemetry.resetForTesting();
-});
-
-test("a batch the server will never accept is eventually given up on", async () => {
- let attempts = 0;
- const telemetry = createTelemetry({
- host: "h", source: "S", version: "1", distinctId: "d", flushThreshold: 1000,
- delivery: async () => { attempts += 1; throw new Error("permanently bad"); },
- });
-
- telemetry.capture("doomed");
- for (let i = 0; i < 8; i += 1) await telemetry.flush(true);
-
- assert.ok(attempts <= 6, `retried ${attempts} times with no cap`);
- assert.equal(telemetry.queueForTesting().length, 0, "a doomed batch held the queue forever");
- telemetry.resetForTesting();
-});
-
-test("an HTTP error response is a failure, not a delivery", async () => {
- // fetch only rejects on a network-level failure, so a 500 used to resolve
- // normally and the batch was dropped as delivered. Exercises the real default
- // delivery path rather than an injected one, which is where this hid.
- const realFetch = globalThis.fetch;
- let calls = 0;
- globalThis.fetch = (async () => {
- calls += 1;
- return new Response("upstream is unwell", { status: 503 });
- }) as typeof fetch;
-
- const telemetry = createTelemetry({
- host: "h", source: "S", version: "1", distinctId: "d", flushThreshold: 1000,
- });
- try {
- telemetry.capture("during.outage");
- await telemetry.flush();
-
- assert.equal(calls, 1, "never reached the network");
- assert.equal(telemetry.queueForTesting().length, 1, "a 503 was counted as delivered");
- } finally {
- globalThis.fetch = realFetch;
- telemetry.resetForTesting();
- }
-});
-
-test("a 2xx is a delivery", async () => {
- const realFetch = globalThis.fetch;
- globalThis.fetch = (async () => new Response("ok", { status: 200 })) as typeof fetch;
-
- const telemetry = createTelemetry({
- host: "h", source: "S", version: "1", distinctId: "d", flushThreshold: 1000,
- });
- try {
- telemetry.capture("fine");
- await telemetry.flush();
- assert.equal(telemetry.queueForTesting().length, 0, "a good response did not clear the queue");
- } finally {
- globalThis.fetch = realFetch;
- telemetry.resetForTesting();
- }
-});
-
-test("the exit flush is attempted once, not until the budget is spent", async () => {
- // Node re-emits beforeExit whenever the handler schedules async work, so an
- // unconditional forced flush looped until MAX_DELIVERY_ATTEMPTS. Against the
- // real 3s delivery timeout that is fifteen seconds added to a host's shutdown.
- let attempts = 0;
- const telemetry = createTelemetry({
- host: "h", source: "S", version: "1", distinctId: "d", flushThreshold: 1000,
- delivery: async () => { attempts += 1; throw new Error("down"); },
- });
-
- telemetry.capture("a");
- const handlers = process.listeners("beforeExit");
- const ours = handlers[handlers.length - 1] as () => void;
- ours();
- ours();
- ours();
- await new Promise((resolve) => setTimeout(resolve, 20));
-
- assert.equal(attempts, 1, `exit flush ran ${attempts} times`);
- telemetry.resetForTesting();
-});
-
-test("overlapping flushes do not reorder the backlog behind newer events", async () => {
- // Each flush detaches the queue and prepends its own batch back on failure, so
- // two in flight at once put the LATER batch in front of the earlier one. The
- // truncation then drops the older events first, inverting the priority the
- // failure path exists to establish.
- let release: (() => void)[] = [];
- const telemetry = createTelemetry({
- host: "h", source: "S", version: "1", distinctId: "d", flushThreshold: 1000,
- delivery: () => new Promise((_resolve, reject) => { release.push(() => reject(new Error("down"))); }),
- });
-
- telemetry.capture("first");
- const a = telemetry.flush();
- telemetry.capture("second");
- const b = telemetry.flush();
-
- release.forEach((fn) => fn());
- await Promise.all([a, b]);
-
- const events = telemetry.queueForTesting().map((e) => (e as any).event);
- assert.equal(release.length, 1, "a second delivery started while one was in flight");
- assert.deepEqual(events, ["first", "second"], `backlog reordered: ${events.join(",")}`);
- telemetry.resetForTesting();
-});
diff --git a/integrations/antigravity-plugin/core/_harness_id.py b/integrations/antigravity-plugin/core/_harness_id.py
deleted file mode 100644
index 18b7f68ec..000000000
--- a/integrations/antigravity-plugin/core/_harness_id.py
+++ /dev/null
@@ -1,11 +0,0 @@
-"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""
-
-HARNESS_ID = "antigravity"
-SOURCE_TAG = "ANTIGRAVITY_PLUGIN"
-
-# Platform-side vocabulary (mem0_event.source + X-Application). The whole
-# plugin family is one source; which editor it runs in is the application.
-# An empty application means the host is unknown, and memory_core omits
-# the header entirely rather than sending a placeholder.
-PLATFORM_SOURCE = "MEM0_PLUGIN"
-PLATFORM_APPLICATION = "antigravity"
diff --git a/integrations/antigravity-plugin/core/hook_runner.py b/integrations/antigravity-plugin/core/hook_runner.py
index b3d8a3210..2a2adb557 100644
--- a/integrations/antigravity-plugin/core/hook_runner.py
+++ b/integrations/antigravity-plugin/core/hook_runner.py
@@ -290,11 +290,6 @@ def run(
if args.plugin_data_dir:
os.environ[data_dir_env] = args.plugin_data_dir
- # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key
- # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking
- # after them always saw content and every fresh install reported an upgrade.
- data_dir_was_empty = telemetry.data_dir_was_empty()
-
cache_plugin_api_key()
if args.action == "session-start":
clear_stale_api_key_cache()
@@ -310,19 +305,8 @@ def run(
return 0
if args.action == "session-start":
- # Claims the marker atomically and says which event to record, so a
- # second session starting alongside this one cannot record it too.
- first_event = telemetry.claim_install(was_empty=data_dir_was_empty)
- if first_event == "install":
+ if telemetry.is_first_run():
telemetry.record("install")
- elif first_event == "upgrade":
- # First run after a build that never wrote the marker; the
- # predecessor version was never recorded anywhere.
- telemetry.record("upgrade", from_version="pre-0.3")
- else:
- previous = telemetry.claim_version_change()
- if previous:
- telemetry.record("upgrade", from_version=previous)
recovered = recover_pending_handoffs()
record_session_start(store, hook_input)
if recovered:
diff --git a/integrations/antigravity-plugin/core/mcp_server.py b/integrations/antigravity-plugin/core/mcp_server.py
index a0b73cb79..036fbbdc9 100644
--- a/integrations/antigravity-plugin/core/mcp_server.py
+++ b/integrations/antigravity-plugin/core/mcp_server.py
@@ -21,9 +21,16 @@ from memory_core import (
PROTOCOL_VERSION = "2024-11-05"
TOOL_NAME = "search_memories"
TOOL_DESCRIPTION = (
- "Search memories from earlier work in this repository. Use it before "
- "repeating investigation or when earlier decisions, fixes, commands, or "
- "results may help."
+ "Search memories from earlier work in this repository. ALWAYS call this "
+ "tool before answering anything that could depend on prior context: the "
+ "user's preferences, facts about this codebase, history, people, projects, "
+ "or earlier decisions. Do not rely on the chat window alone. The "
+ "repository's memory is shared by everyone who works in it and includes "
+ "what it took to run, test, or build here, so search before assuming an "
+ "invocation works. The scope argument changes what is searched: 'repo' "
+ "(default) is the whole repository's shared memory plus your own "
+ "preferences, 'dir' narrows the shared part to the directory you are "
+ "working in, and 'mine' is your preferences alone."
)
TOOL_SCHEMA = {
"type": "object",
diff --git a/integrations/antigravity-plugin/core/memory_core.py b/integrations/antigravity-plugin/core/memory_core.py
index 9b420a063..77d7a2b80 100644
--- a/integrations/antigravity-plugin/core/memory_core.py
+++ b/integrations/antigravity-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.3"
+PLUGIN_VERSION = "0.3.1"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
@@ -71,13 +71,15 @@ MAX_FLUSH_ATTEMPTS = 5
FORGET_PAGE_SIZE = 100
FORGET_MAX_PAGES = 50
-PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work.
+PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository.
A completed change should produce one memory explaining the resulting behavior, where it is implemented when useful, and any important constraints or reasoning. Exploration or accepted decisions may produce separate memories only when they are independently useful.
-Use the coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+A command that failed and was then made to work should produce one memory naming the failing invocation, the error it returned, and the invocation that succeeded. Do not save one-off errors caused by an edit still in progress, transient network failures, or anything a rerun would fix on its own.
-Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state.
+Use the current coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+
+Write about the repository, not the user, assistant, session, or task. Do not save personal preferences. Do not save a memory that only states which repository, branch, or directory the session worked in. Do not include test results, documentation updates, release notes, or temporary state.
If nothing useful was established, return no memories."""
@@ -1798,34 +1800,6 @@ def extraction_message_batches(
return batches
-# Platform surface attribution. Read from the generated per-host module so a new
-# entrypoint is correct without remembering to configure anything.
-try: # pragma: no cover - absent only in the un-built shared source tree
- from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
- from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
-except ImportError:
- _PLATFORM_SOURCE = "MEM0_PLUGIN"
- _PLATFORM_APPLICATION = ""
-
-
-def platform_headers(key: str) -> dict[str, str]:
- """Auth plus the three surface-identity headers.
-
- X-Mem0-Source and X-Application are set-once by contract: this is the
- outermost layer, so it sets them, and nothing below may overwrite them.
- X-Mem0-Client is append-only โ anything downstream adds itself to the tail.
- """
- headers = {
- "Authorization": f"Token {key}",
- "Content-Type": "application/json",
- "X-Mem0-Source": _PLATFORM_SOURCE,
- "X-Mem0-Client": f"mem0-plugin/{PLUGIN_VERSION}",
- }
- if _PLATFORM_APPLICATION:
- headers["X-Application"] = _PLATFORM_APPLICATION
- return headers
-
-
def _request_json(
url: str, key: str, payload: dict[str, Any], timeout: float
) -> tuple[dict[str, Any] | list[Any], int, int]:
@@ -1833,7 +1807,7 @@ def _request_json(
request = urllib.request.Request(
url,
data=raw,
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -1860,7 +1834,7 @@ def _get_json(
) -> tuple[dict[str, Any] | list[Any], int]:
request = urllib.request.Request(
url,
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="GET",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -2006,13 +1980,6 @@ def flush_session(
"user_id": write_user,
"app_id": repo.app_id,
"run_id": session_id,
- # Top level, not metadata: the backend reads `source` from the body or
- # the query string, never from metadata, which is where this used to
- # sit. The X-Mem0-Source header is also read, but only from the
- # platform release that ships alongside this change, so the body value
- # is what makes attribution work on both. The harness tag stays in
- # metadata as hook provenance.
- "source": _PLATFORM_SOURCE,
"metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)},
"agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS,
"custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS,
@@ -2556,7 +2523,7 @@ def _collect_memory_ids(
def _delete_memory(api_url: str, key: str, memory_id: str) -> bool:
request = urllib.request.Request(
f"{api_url}/v1/memories/{urllib.parse.quote(memory_id)}/",
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="DELETE",
)
try:
diff --git a/integrations/antigravity-plugin/core/telemetry.py b/integrations/antigravity-plugin/core/telemetry.py
index c1fc0084c..249595475 100644
--- a/integrations/antigravity-plugin/core/telemetry.py
+++ b/integrations/antigravity-plugin/core/telemetry.py
@@ -1,9 +1,5 @@
#!/usr/bin/env python3
-"""Usage telemetry for Mem0 agent plugins.
-
-Events are linked to your Mem0 account email when an API key is configured, and
-to a random per-machine id otherwise. Not anonymous โ the Python SDK and CLI
-attribute the same way.
+"""Anonymous usage telemetry for Mem0 agent plugins.
Hooks run on a 3-6 second budget and fire on every tool call, so recording never
touches the network: `record` appends one JSON line to a local spool and returns.
@@ -13,8 +9,7 @@ started once per session and again from the flush worker that is already detache
Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false.
Never sends prompts, memory text, queries, file paths, repository names, or API
-keys: only event names, durations, counts, coarse outcomes, and repo/session
-identifiers hashed with a random per-install salt.
+keys: only event names, durations, counts, coarse outcomes, and salted hashes.
"""
from __future__ import annotations
@@ -34,24 +29,8 @@ from typing import Any
import memory_core
-# Seeded from the per-host module the build generates into core/. Two processes
-# in this pipeline never call init() โ mcp_server.py, and the detached
-# `python3 telemetry.py` sender that spawn_flush() starts โ so a module default
-# was what every one of their events got labelled with.
-try: # pragma: no cover - absent only in the un-built shared source tree
- from _harness_id import HARNESS_ID as _DEFAULT_HARNESS
- from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
- from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
- from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG
-except ImportError:
- _DEFAULT_HARNESS = "generic"
- _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN"
- _PLATFORM_SOURCE = "MEM0_PLUGIN"
- _PLATFORM_APPLICATION = ""
-
-_salt_cache: str = ""
-_harness: str = _DEFAULT_HARNESS
-_source_tag: str = _DEFAULT_SOURCE_TAG
+_harness: str = "generic"
+_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
"apikey",
"authorization",
@@ -77,19 +56,10 @@ _PRIVATE_KEYS = {
}
-def init(harness: str = "", source_tag: str = "") -> None:
- """Override the generated identity. Optional โ core/_harness_id.py is the default.
-
- The fallback shape matches memory_core.configure_harness's (``_PLUGIN``).
- It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which
- meant one plugin could emit three different source values depending on which
- process happened to send the batch.
- """
+def init(harness: str = "generic", source_tag: str = "") -> None:
global _harness, _source_tag
- _harness = harness or _DEFAULT_HARNESS
- _source_tag = source_tag or (
- f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG
- )
+ _harness = harness
+ _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/"
@@ -100,16 +70,6 @@ BATCH_SIZE = 100
SEND_TIMEOUT = 5
CLAIM_STALE_SECONDS = 120
CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60
-# A batch is only discarded once it has genuinely been retried this many times.
-MAX_CLAIM_ATTEMPTS = 3
-# Parked claims drained per run, after the live spool. Bounded so a long backlog
-# cannot turn one flush into an unbounded send loop.
-MAX_PARKED_PER_RUN = 3
-# Added to the wait before a released claim becomes reclaimable, per attempt
-# already spent. Releasing straight to "reclaimable now" let two senders burn the
-# whole budget within seconds of one another on a single momentary failure, and
-# discard a batch a retry a minute later would have delivered.
-RETRY_COOLDOWN_SECONDS = 60
def is_enabled() -> bool:
@@ -123,126 +83,9 @@ def is_enabled() -> bool:
def _digest(value: str, length: int = 16) -> str:
- """Unsalted digest. Only for values that are already secrets (API keys)."""
return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length]
-def _salt_path() -> Path:
- return memory_core.data_dir() / "telemetry-salt"
-
-
-def _install_salt() -> str:
- """Random per-install salt, created once and memoized for the process.
-
- Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in
- the identity file. Three reasons, all of which produced wrong data when this
- lived in the identity dict:
-
- - Hooks are short-lived separate processes firing on every tool call, and
- people run more than one agent window. A read-modify-write would let each
- process mint its own salt, so one repository would hash several ways in the
- window before a writer won.
- - resolve_distinct_id holds a copy of the identity dict across a network call
- to /v1/ping/, so whichever write landed second erased the other's key โ
- losing either the salt (repo_hash changes mid-stream) or the email (a
- second $identify, splitting the person).
- - Touching the identity file from record() would create it, and is_first_run
- keys off that file, so recording an event would silently suppress the
- install event.
-
- Published atomically, and there is deliberately no derived fallback. Creating
- the file with O_CREAT|O_EXCL and then writing into it leaves a window where
- the file exists and is empty, and a concurrent hook that reads it in that
- window gets nothing. Falling back to a digest of the path would hand that
- process a salt an attacker can compute, memoized for its whole run, which is
- the privacy control this function exists to provide silently turning itself
- off under load. The salt is written to a private temp file first and linked
- into place, so the name either does not exist or already has the full value.
-
- Returns "" when it genuinely cannot persist. Callers omit the hash entirely
- rather than emit an unsalted one.
- """
- global _salt_cache
- if _salt_cache:
- return _salt_cache
-
- path = _salt_path()
- # Read before writing. Hooks are separate processes firing on every tool
- # call, so all but the first find the salt already published; going straight
- # to create-fsync-link-unlink meant every one of them paid an fsync to
- # discover that, on a path whose whole promise is appending a line and
- # returning.
- try:
- _salt_cache = path.read_text(encoding="utf-8").strip()
- if _salt_cache:
- return _salt_cache
- except OSError:
- pass
-
- temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(handle, "w", encoding="utf-8") as stream:
- stream.write(uuid.uuid4().hex)
- stream.flush()
- os.fsync(stream.fileno())
- try:
- # Atomic claim: fails if another process already published one.
- # os.link rather than replace, which would clobber theirs.
- os.link(temporary, path)
- except FileExistsError:
- pass
- except OSError:
- # No hardlinks here (some network mounts, some container volumes).
- # Claim the name directly instead. That reopens the empty-file
- # window, but the window is now benign: a reader that lands in it
- # gets "" and omits the hash for that process rather than caching a
- # guessable one. Losing the hashes on every run of an entire
- # filesystem is the worse failure.
- try:
- fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(fallback, "w", encoding="utf-8") as stream:
- stream.write(temporary.read_text(encoding="utf-8"))
- except OSError:
- pass
- except OSError:
- pass
- finally:
- try:
- temporary.unlink()
- except OSError:
- pass
-
- try:
- _salt_cache = path.read_text(encoding="utf-8").strip()
- except OSError:
- _salt_cache = ""
- return _salt_cache
-
-
-def _scoped_digest(value: str, length: int = 16) -> str:
- """Salted digest for values drawn from a guessable space.
-
- repo.identity is a git remote URL, or ``local:`` when there is
- no remote โ which normally contains the account username. Sixteen unsalted
- hex characters over that input space is enumerable, so this is not a
- privacy control without the salt. Salting per install keeps every
- within-account join the analytics actually use and gives up only
- cross-machine joins on the same repository, which nothing computes.
-
- Returns "" when there is no salt, so record() omits the property. An
- unsalted digest over this input space is close to plaintext, and emitting one
- under a name that implies it is hashed is worse than sending nothing.
- """
- if not value:
- return ""
- salt = _install_salt()
- if not salt:
- return ""
- return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length]
-
-
def _safe_value(value: Any) -> Any:
if isinstance(value, str):
return memory_core.redact(value)
@@ -302,176 +145,9 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str:
return created
-def _rotate_anonymous_id(identity: dict[str, str]) -> str:
- """Mint a fresh anonymous id because the account context is gone.
-
- The previous id may already have been merged into a person profile by an
- $identify, and that merge is permanent. Reusing it after a logout or a key
- change attributes everything that follows to the account that just went
- away, which is the same misattribution the key fingerprint exists to stop,
- only arriving through the anonymous path instead.
-
- `aliased` is cleared with it: the new id has never been merged, so it is
- eligible to be aliased into whatever account comes next.
- """
- created = f"code-anon-{uuid.uuid4().hex}"
- identity["anonymous_id"] = created
- identity.pop("aliased", None)
- _write_identity(identity)
- return created
-
-
-def _install_state_path() -> Path:
- return memory_core.data_dir() / "install-state.json"
-
-
def is_first_run() -> bool:
- """Whether install has never been recorded on this machine.
-
- Deliberately NOT the identity file. That file is only written by a
- successful flush, so an offline or firewalled user recorded code.install on
- every single session, forever โ and every 0.2.x user recorded one on their
- first 0.3.x session because 0.2.x never wrote it at all.
- """
- return not _install_state_path().exists()
-
-
-def data_dir_was_empty() -> bool:
- """Whether the data directory is untouched. Call BEFORE anything writes to it.
-
- hook_runner reaches claim_install() only after cache_plugin_api_key() has
- written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so
- asking at claim time always saw content and every fresh install reported an
- upgrade. The caller snapshots this at the top of the run instead.
- """
- return not _data_dir_has_content()
-
-
-def claim_install(was_empty: bool | None = None) -> str | None:
- """Claim the one install/upgrade record for this machine, atomically.
-
- Returns the event to record ("install" or "upgrade"), or None if another
- session already claimed it. O_CREAT|O_EXCL so two sessions starting together
- cannot both win.
-
- `was_empty` must come from data_dir_was_empty() called before this process
- wrote anything. Omitting it falls back to checking now, which is only
- correct for a caller that has touched nothing.
- """
- if not is_enabled():
- # Never consume the one-shot claim while the user is opted out, or they
- # would silently lose their install event if they later opt in.
- return None
-
- path = _install_state_path()
- upgrading = not (data_dir_was_empty() if was_empty is None else was_empty)
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- except FileExistsError:
- return None
- except OSError:
- return None
- try:
- with os.fdopen(handle, "w", encoding="utf-8") as stream:
- json.dump(
- {
- "plugin_version": memory_core.PLUGIN_VERSION,
- "installed_at": memory_core.utc_now(),
- "upgraded": upgrading,
- },
- stream,
- )
- # Durable before this returns. The O_EXCL open is what makes the
- # claim exclusive, so it cannot be replaced by a temp-and-rename
- # without losing that, which leaves the content as the thing to make
- # safe. A kill between the open and this fsync used to leave a marker
- # that exists but parses to nothing: is_first_run reads it as claimed
- # and claim_version_change cannot read a version out of it.
- stream.flush()
- os.fsync(stream.fileno())
- except OSError:
- pass
- return "upgrade" if upgrading else "install"
-
-
-def _data_dir_has_content() -> bool:
- """Whether anything predates this session in the plugin data directory."""
- try:
- for entry in memory_core.data_dir().iterdir():
- if entry.name != "install-state.json":
- return True
- except OSError:
- pass
- return False
-
-
-def _repair_install_state(path: Path) -> None:
- """Rewrite an unparseable marker so version tracking can resume."""
- try:
- temporary = path.with_suffix(f".{os.getpid()}.tmp")
- temporary.write_text(
- json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}),
- encoding="utf-8",
- )
- temporary.replace(path)
- except OSError:
- pass
-
-
-def claim_version_change() -> str | None:
- """Return the previously recorded version if it differs, updating the marker.
-
- Only meaningful once the marker exists โ the first transition into 0.3.x has
- no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting
- the marker means the next session sees no change and records nothing.
- """
- path = _install_state_path()
- try:
- state = json.loads(path.read_text(encoding="utf-8"))
- except OSError:
- return None
- except json.JSONDecodeError:
- # A crash between O_EXCL and the write leaves an empty marker. Left
- # alone it disables every future upgrade event on this machine, because
- # claim_install sees the file and this function cannot parse it.
- state = None
- if not isinstance(state, dict):
- _repair_install_state(path)
- return None
- previous = str(state.get("plugin_version") or "")
- if not previous or previous == memory_core.PLUGIN_VERSION:
- return None
- # Claim the transition with an exclusive sentinel before rewriting the
- # marker. A plain read-modify-write let every concurrently starting session
- # observe the old version and each record its own upgrade โ and the first
- # session after a version bump is exactly when several agent windows restart
- # together.
- sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}")
- try:
- os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
- except FileExistsError:
- return None
- except OSError:
- return None
-
- state["plugin_version"] = memory_core.PLUGIN_VERSION
- state["upgraded_at"] = memory_core.utc_now()
- temporary = path.with_suffix(f".{os.getpid()}.tmp")
- try:
- temporary.write_text(json.dumps(state), encoding="utf-8")
- temporary.replace(path)
- except OSError:
- # Release the claim. The marker still records the old version, so
- # without this the sentinel makes claim_version_change return early on
- # every later run and this version's upgrade is never recorded again.
- for leftover in (sentinel, temporary):
- try:
- leftover.unlink()
- except OSError:
- pass
- return None
- return previous
+ """Whether this machine has never recorded a plugin event before."""
+ return not _identity_path().exists()
def record(
@@ -492,32 +168,19 @@ def record(
except OSError:
pass
properties = _safe_value(properties)
- # Stamped in the RECORDING process, beside harness. `source` used to be
- # read in the sending process from a module global, so whichever process
- # drained the spool named every event in it. flush() spreads per-event
- # properties last, so this now wins over any sender's default.
properties.update(
harness=_harness,
- source=_source_tag,
plugin_version=memory_core.PLUGIN_VERSION,
os=sys.platform,
python_version=platform.python_version(),
)
- # Assigned only when the digest is real. _scoped_digest returns "" when
- # the salt could not be persisted, and an empty property is worse than an
- # absent one: it survives the None filter below and reads as a value.
if repo is not None:
- repo_hash = _scoped_digest(getattr(repo, "identity", ""))
- if repo_hash:
- properties["repo_hash"] = repo_hash
+ properties["repo_hash"] = _digest(getattr(repo, "identity", ""))
if session_id:
- session_hash = _scoped_digest(session_id)
- if session_hash:
- properties["session_hash"] = session_hash
+ properties["session_hash"] = _digest(session_id)
line = json.dumps(
{
"event": f"{EVENT_PREFIX}.{event}",
- "uuid": str(uuid.uuid4()),
"timestamp": memory_core.utc_now(),
"properties": {
key: value for key, value in properties.items() if value is not None
@@ -576,201 +239,38 @@ def spawn_flush() -> bool:
return False
-def _claim_name(attempt: int = 0) -> str:
- """Claim filename. The attempt count rides in the name so the 7-day expiry
- only ever discards a batch that was actually retried and failed."""
- return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending"
-
-
-def _claim_attempt(claim: Path) -> int:
- """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape.
-
- Anchored on field position, not on a leading "a": the legacy shape is
- ``telemetry--.sending`` and a hex id such as ``a1234567`` would
- otherwise parse as attempt 1234567 and be discarded unsent on the first
- flush after an upgrade.
- """
- stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name
- parts = stem.split("-")
- if len(parts) != 4:
- return 0
- tail = parts[3]
- if tail.startswith("a") and tail[1:].isdigit():
- return int(tail[1:])
- return 0
-
-
-def _touch(path: Path) -> None:
- """Refresh mtime so a claim's age measures time since it was claimed.
-
- ``Path.replace`` is ``os.rename``, which preserves mtime โ so a claim created
- after a quiet minute inherited the spool's last-write time and looked
- abandoned the instant it was made. A second sender would then take it over
- while the first was still posting, and both would deliver the batch.
- """
- try:
- os.utime(path, None)
- except OSError:
- pass
-
-
def _claim_spool() -> Path | None:
"""Rename the spool aside so exactly one sender owns each batch."""
directory = memory_core.data_dir()
- claim = directory / _claim_name()
+ claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending"
spool = _spool_path()
try:
spool.replace(claim)
- _touch(claim)
return claim
except OSError:
pass
- return _claim_parked(directory)
-
-
-def _sweep_debris(directory: Path) -> None:
- """Remove files nothing else will ever pick up again.
-
- *.partial is a temp file orphaned by a crash between write and rename.
- *.corrupt is a batch quarantined for undecodable content. No glob in this
- module matches either, so without this they accumulate on disk for the life
- of the install.
-
- Quarantined batches are kept far longer than debris: they are the only
- evidence left of events that could not be delivered, and someone diagnosing
- a report of missing telemetry has to be able to find one.
- """
now = time.time()
- for debris in directory.glob("telemetry-*.partial"):
- try:
- if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS:
- debris.unlink()
- except OSError:
- continue
- for quarantined in directory.glob("telemetry-*.corrupt"):
- try:
- if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS:
- quarantined.unlink()
- except OSError:
- continue
- # The same reasoning covers *.tmp. _write_identity and _install_salt both
- # create one and unlink it in a finally, which a SIGKILL skips, and no glob
- # in this module matches the leftovers either.
- for temporary in directory.glob("telemetry-*.tmp"):
- try:
- if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS:
- temporary.unlink()
- except OSError:
- continue
-
-
-def _claim_parked(directory: Path) -> Path | None:
- """Take the oldest abandoned claim, if any lease has actually expired.
-
- Kept separate from the live spool so flush() can drain both in one run.
- Previously parked batches were only reachable when no spool existed at all,
- and because sessions keep recording there usually was one โ so a batch
- parked by a failed send waited until the 7-day expiry deleted it unsent,
- even though its own presence is what started the sender.
- """
- now = time.time()
- for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime):
+ for orphan in sorted(directory.glob("telemetry-*.sending")):
try:
age = now - orphan.stat().st_mtime
except OSError:
continue
- if age < CLAIM_STALE_SECONDS:
- # Someone else holds a live lease on it. This check has to come
- # first. Claiming a file bumps its attempt count and refreshes its
- # mtime, so a sender that has just taken the final attempt looks
- # exhausted to everyone else while it is actively draining. Judging
- # exhaustion before liveness let a second sender unlink a batch out
- # from under its owner, losing every event in it.
- continue
- # Attempts, not age. Every re-claim touches the mtime and every release
- # backdates it by a fixed amount, so age is pinned near the stale
- # threshold and never reaches the expiry. Age stays only as a backstop
- # for files that never carried an attempt marker.
- if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS:
+ if age > CLAIM_EXPIRY_SECONDS:
try:
orphan.unlink()
except OSError:
pass
continue
- claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1)
+ if age < CLAIM_STALE_SECONDS:
+ continue
try:
orphan.replace(claim)
- _touch(claim)
return claim
except OSError:
continue
return None
-def _safe_mtime(path: Path) -> float:
- try:
- return path.stat().st_mtime
- except OSError:
- return 0.0
-
-
-def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool:
- """Persist the unsent remainder, atomically, and refresh the lease.
-
- Called after every successful batch. Two jobs: a retry resumes where the
- send stopped instead of re-posting from the top, and the rewrite doubles as
- the lease heartbeat, so a slow sender does not have its claim stolen
- mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS.
- """
- if not remaining:
- try:
- claim.unlink()
- except OSError:
- pass
- return True
- temporary = claim.with_suffix(f".{os.getpid()}.partial")
- try:
- payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining)
- # fsync before the rename: without it the rename can land while the
- # bytes have not, and the claim comes back empty or truncated after a
- # crash. _drain then reads zero events and unlinks it.
- with open(temporary, "w", encoding="utf-8") as handle:
- handle.write(payload)
- handle.flush()
- os.fsync(handle.fileno())
- temporary.replace(claim)
- _touch(claim)
- return True
- except OSError:
- try:
- temporary.unlink()
- except OSError:
- pass
- return False
-
-
-def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None:
- """Persist the remainder and drop the lease, because this sender has given up.
-
- Distinct from the per-batch heartbeat: heartbeating on the way out would
- make an abandoned batch look actively owned for a further
- CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the
- threshold lets the next flush pick it up immediately, while the attempt
- count in the filename still bounds how many times that can happen.
- """
- if not _rewrite_claim(claim, remaining):
- return
- try:
- # Backdate past the stale threshold so the next flush can pick it up,
- # minus a cooldown that grows with the attempts already spent. Clamped so
- # the mtime never lands in the future, which would read as a live lease.
- cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS)
- released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown
- os.utime(claim, (released, released))
- except OSError:
- pass
-
-
def _resolve_email(key: str) -> str:
"""Trade the API key for the account email so events join other Mem0 surfaces."""
url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/"
@@ -800,130 +300,34 @@ def _post(payload: dict[str, Any], url: str) -> bool:
def resolve_distinct_id() -> tuple[str, str]:
- """Return the PostHog distinct id and the anonymous id it replaced, if any.
-
- The second value becomes a PostHog $identify alias. It is ONLY ever an
- anonymous id: aliasing one account email to another merges two real person
- profiles and cannot be undone, so a key that now belongs to a different
- account re-resolves with no alias.
- """
+ """Return the PostHog distinct id and the anonymous id it replaced, if any."""
identity = _read_identity()
- key = memory_core.api_key()
- fingerprint = _digest(key) if key else ""
email = identity.get("email", "")
-
- if email and fingerprint:
- recorded = identity.get("key_fingerprint", "")
- if recorded == fingerprint:
- return email, ""
- if not recorded:
- # Rows written before fingerprints existed. Verify rather than
- # adopt: a key changed before the upgrade would otherwise bind the
- # new key to the previous account's email, permanently, and the
- # fingerprint would then agree with itself forever after.
- verified = _resolve_email(key)
- if not verified:
- # Offline, firewalled, or the API is down. Keep the previous
- # behaviour and retry on the next flush rather than dropping a
- # real account attribution. Safe because the same network that
- # failed /v1/ping/ is about to fail the PostHog POST, so nothing
- # is delivered under the unverified identity in the meantime.
- return email, ""
- identity["email"] = verified
- identity["key_fingerprint"] = fingerprint
- _write_identity(identity)
- return verified, ""
-
+ if email:
+ return email, ""
+ key = memory_core.api_key()
if not key:
- # No key to verify the account with; do not keep attributing to it.
- if email:
- identity.pop("email", None)
- identity.pop("key_fingerprint", None)
- return _rotate_anonymous_id(identity), ""
return anonymous_id(identity), ""
-
- resolved = _resolve_email(key)
- if not resolved:
- # The key changed and will not resolve (revoked, offline, API down).
- # Reaching here with an email means the recorded fingerprint disagreed,
- # so the key really did change. Drop the account and rotate: the stored
- # anonymous id may already be merged into that account's person, and
- # reusing it would keep the events on the profile we are trying to
- # leave.
- if email:
- identity.pop("email", None)
- identity.pop("key_fingerprint", None)
- return _rotate_anonymous_id(identity), ""
+ email = _resolve_email(key)
+ if not email:
return anonymous_id(identity), ""
-
- # Alias only when going anonymous -> email for the first time. Once an anon
- # id has been merged into an account it must never be offered again: an
- # alias naming an already-identified id is what could link two real people.
- previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "")
- if previous:
- identity["aliased"] = True
- identity["email"] = resolved
- identity["key_fingerprint"] = fingerprint
+ previous = identity.get("anonymous_id", "")
+ identity["email"] = email
_write_identity(identity)
- return resolved, previous
+ return email, previous
def flush() -> int:
- """Drain the live spool, then any parked claims, and return events sent."""
+ """Drain claimed spools to PostHog and return the number of events sent."""
if not is_enabled():
return 0
- sent, delivered = _drain(_claim_spool())
- if not delivered:
- # The network is failing. Retrying other batches now would only burn
- # their attempt budget against the same broken connection.
- return sent
-
- # Parked batches used to starve behind the live spool indefinitely. Bounded
- # per run so a long backlog cannot turn one flush into an unbounded loop.
- directory = memory_core.data_dir()
- _sweep_debris(directory)
- for _ in range(MAX_PARKED_PER_RUN):
- parked = _claim_parked(directory)
- if parked is None:
- break
- count, delivered = _drain(parked)
- sent += count
- if not delivered:
- break
- return sent
-
-
-def _drain(claim: Path | None) -> tuple[int, bool]:
- """Post one claimed batch file, recording progress after every batch.
-
- Returns (events sent, whether everything was delivered).
- """
+ claim = _claim_spool()
if claim is None:
- return 0, True
+ return 0
try:
lines = claim.read_text(encoding="utf-8").splitlines()
- except ValueError:
- # UnicodeDecodeError from a torn write: the content is unrecoverable, so
- # quarantine rather than retry. flush() runs from a bare `finally:` in
- # flush_worker, so raising here also skips the handoff cleanup, and an
- # undecodable file would otherwise be re-read on every flush forever.
- # Reported as delivered because there is nothing left to deliver and the
- # rest of the run should continue.
- try:
- claim.replace(claim.with_suffix(".corrupt"))
- except OSError:
- try:
- claim.unlink()
- except OSError:
- pass
- return 0, True
except OSError:
- # Could not read it, which is not the same as having nothing to send.
- # The file is left exactly where it is: a vanished or briefly unreadable
- # claim is retryable, and quarantining it here would discard events over
- # a transient filesystem error. Reported as undelivered so the run stops
- # instead of counting a batch nothing was posted from as delivered.
- return 0, False
+ return 0
events = []
for line in lines:
try:
@@ -933,18 +337,11 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
if isinstance(value, dict) and value.get("event"):
events.append(value)
if not events:
- # Only delete when the file really is empty. A non-empty file that
- # parses to nothing is a torn write, and its contents are the unsent
- # remainder โ deleting it is the data loss this PR exists to prevent.
try:
- empty = claim.stat().st_size == 0
- except OSError:
- empty = True
- try:
- claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink()
+ claim.unlink()
except OSError:
pass
- return 0, True
+ return 0
distinct_id, aliased_anonymous_id = resolve_distinct_id()
if aliased_anonymous_id:
@@ -963,17 +360,12 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
sent = 0
for start in range(0, len(events), BATCH_SIZE):
- chunk = events[start : start + BATCH_SIZE]
batch = [
{
"event": event["event"],
"distinct_id": distinct_id,
- # Carried through from record() so a resend can be collapsed.
- "uuid": event.get("uuid"),
"timestamp": event.get("timestamp"),
"properties": {
- # Fallback only: events recorded by a build before source
- # moved into record() have none of their own.
"source": _source_tag,
"language": "python",
"$process_person_profile": False,
@@ -981,24 +373,16 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
**(event.get("properties") or {}),
},
}
- for event in chunk
+ for event in events[start : start + BATCH_SIZE]
]
if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL):
- # Keep only what has not been delivered, and release the lease.
- # Previously the whole file was kept and the retry re-posted every
- # batch, including the ones that had already arrived.
- _release_claim(claim, events[start:])
- return sent, False
- sent += len(chunk)
- # Record progress and refresh the lease after each successful batch, so
- # a crash repeats at most one batch instead of the entire file. If the
- # rewrite fails the claim still holds delivered events, so stop rather
- # than carry on as though progress were recorded โ continuing is how the
- # duplicate delivery this PR fixes would come back.
- if not _rewrite_claim(claim, events[start + len(chunk) :]):
- _release_claim(claim, events[start + len(chunk) :])
- return sent, False
- return sent, True
+ return sent
+ sent += len(batch)
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return sent
def main() -> int:
diff --git a/integrations/antigravity-plugin/plugin-build.json b/integrations/antigravity-plugin/plugin-build.json
index 5a9112025..ac65c4bea 100644
--- a/integrations/antigravity-plugin/plugin-build.json
+++ b/integrations/antigravity-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.3",
+ "version": "0.3.1",
"homepage": "https://docs.mem0.ai/integrations/antigravity",
"native": {
"pluginRoot": "${ANTIGRAVITY_PLUGIN_ROOT}",
diff --git a/integrations/antigravity-plugin/skills/pause/SKILL.md b/integrations/antigravity-plugin/skills/pause/SKILL.md
index 77b4146b6..e88f7d315 100644
--- a/integrations/antigravity-plugin/skills/pause/SKILL.md
+++ b/integrations/antigravity-plugin/skills/pause/SKILL.md
@@ -7,8 +7,8 @@ disable-model-invocation: true
# Pause memory capture
To pause (hooks stop capturing and sending session content; a minimal
-telemetry ping still fires at session start, under your Mem0 account email,
-unless `MEM0_TELEMETRY=false`):
+anonymous telemetry ping still fires at session start unless
+`MEM0_TELEMETRY=false`):
```bash
python3 "${ANTIGRAVITY_PLUGIN_ROOT}/core/memory_cli.py" --harness "antigravity" pause
diff --git a/integrations/antigravity-plugin/skills/search/SKILL.md b/integrations/antigravity-plugin/skills/search/SKILL.md
index 530a70a86..7a6af05fa 100644
--- a/integrations/antigravity-plugin/skills/search/SKILL.md
+++ b/integrations/antigravity-plugin/skills/search/SKILL.md
@@ -12,9 +12,11 @@ Call `search_memories` with the user's question. Treat `--top-k`, `--category`,
query.
Omit `top_k` to use Mem0's configured default. Omit `category` to search every
-category. Omit `scope` to use the configured default, normally `repo`: this
-repository's shared memory, which everyone who works in it contributes to,
-plus your own preferences.
+category; a category is a best-effort label Mem0 assigned when it saved the
+memory, so if a category search misses, repeat it without the category. Omit
+`scope` to use the configured default, normally `repo`: this repository's
+shared memory, which everyone who works in it contributes to, plus your own
+preferences.
Pass `scope` when the question needs something else: `dir` to narrow the
shared memory to the directory you are working in (a package inside a
diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json
index 8182b49dc..6f214cc14 100644
--- a/integrations/claude-code-plugin/.claude-plugin/plugin.json
+++ b/integrations/claude-code-plugin/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mem0",
- "version": "0.3.3",
+ "version": "0.3.1",
"description": "Cross-session memory and token savings for coding agents.",
"author": {
"name": "Mem0"
diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md
index b58f54c79..130460b17 100644
--- a/integrations/claude-code-plugin/README.md
+++ b/integrations/claude-code-plugin/README.md
@@ -136,23 +136,13 @@ Local data lives in `${CLAUDE_PLUGIN_DATA}`:
- `pending/`: sessions waiting to be sent to Mem0 (retried after interruption)
- `flush-worker.log`: whether memory creation succeeded
- `plugin-errors.log`: hook errors (no credentials)
-- `telemetry.jsonl` / `telemetry-identity.json`: usage events and the id they are sent under
-- `telemetry-salt`: random per-install salt for the repo and session hashes
-- `install-state.json`: records that install has been counted once on this machine
+- `telemetry.jsonl` / `telemetry-identity.json`: anonymous usage events
Mem0 receives captured user messages, Claude's answers, sidekick assignments and completed responses, and changed file paths. When a failed command is recorded, extraction can also include bounded command details and results. Complete files and general tool output stay on your machine. Values that look like credentials are redacted before anything is sent.
## Telemetry
-Usage events (which hook ran, timing, result counts, failure types) so Mem0 can identify what's used and what's breaking.
-
-**These events are not anonymous.** When an API key is configured โ which installing the plugin requires โ events are sent under your Mem0 account email, the same way the Python SDK and the CLI attribute theirs. Without a key they are sent under a random per-machine id.
-
-What each event carries: the event name, the plugin version, the harness it ran in, your OS and Python version, and per-event properties describing what happened โ timings, counts, coarse outcome and failure labels, and which model was configured. Repository and session identifiers are hashed with a random salt generated on your machine, so they cannot be linked back to a repository name or path.
-
-Rather than restate a list that drifts, the exact set is enforced in code: `telemetry.record` filters every property through a denylist of sensitive keys and redacts credential-shaped values. See `_PRIVATE_KEYS` in `core/telemetry.py`.
-
-Prompts, memory text, queries, file paths, repository names, and API keys are never sent.
+Anonymous usage events (which hook ran, timing, result counts, failure types) so Mem0 can identify what's used and what's breaking. Repo and session IDs are hashed before leaving your machine. Prompts, memory text, file paths, tool output, and API keys are never sent.
Turn it off:
diff --git a/integrations/claude-code-plugin/agents/sidekick.md b/integrations/claude-code-plugin/agents/sidekick.md
index 8f719327a..d0552c0c3 100644
--- a/integrations/claude-code-plugin/agents/sidekick.md
+++ b/integrations/claude-code-plugin/agents/sidekick.md
@@ -12,8 +12,11 @@ You are Mem0's Sonnet coding agent. Complete the work the main agent gives you.
Work in the separate Git worktree Claude Code created for you. Return a tested
result that the main agent can review without doing the same work again.
-When memories from earlier sessions could help, call `search_memories` with a
-focused question before searching the repository again.
+ALWAYS call `search_memories` before answering anything that could depend on
+prior context (the user's preferences, facts about this codebase, history,
+people, projects, or earlier decisions). Do not rely on the chat window or
+assume you know enough from the current conversation. Search with a focused
+question before investigating the repository.
Inspect the relevant code and repository rules. Reproduce the problem when that
helps. Decide the implementation details, edit files when asked, and test the
diff --git a/integrations/claude-code-plugin/core/_harness_id.py b/integrations/claude-code-plugin/core/_harness_id.py
deleted file mode 100644
index 9c4949408..000000000
--- a/integrations/claude-code-plugin/core/_harness_id.py
+++ /dev/null
@@ -1,11 +0,0 @@
-"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""
-
-HARNESS_ID = "claude-code"
-SOURCE_TAG = "CLAUDE_CODE_PLUGIN"
-
-# Platform-side vocabulary (mem0_event.source + X-Application). The whole
-# plugin family is one source; which editor it runs in is the application.
-# An empty application means the host is unknown, and memory_core omits
-# the header entirely rather than sending a placeholder.
-PLATFORM_SOURCE = "MEM0_PLUGIN"
-PLATFORM_APPLICATION = "claude-code"
diff --git a/integrations/claude-code-plugin/core/hook_runner.py b/integrations/claude-code-plugin/core/hook_runner.py
index b3d8a3210..2a2adb557 100644
--- a/integrations/claude-code-plugin/core/hook_runner.py
+++ b/integrations/claude-code-plugin/core/hook_runner.py
@@ -290,11 +290,6 @@ def run(
if args.plugin_data_dir:
os.environ[data_dir_env] = args.plugin_data_dir
- # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key
- # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking
- # after them always saw content and every fresh install reported an upgrade.
- data_dir_was_empty = telemetry.data_dir_was_empty()
-
cache_plugin_api_key()
if args.action == "session-start":
clear_stale_api_key_cache()
@@ -310,19 +305,8 @@ def run(
return 0
if args.action == "session-start":
- # Claims the marker atomically and says which event to record, so a
- # second session starting alongside this one cannot record it too.
- first_event = telemetry.claim_install(was_empty=data_dir_was_empty)
- if first_event == "install":
+ if telemetry.is_first_run():
telemetry.record("install")
- elif first_event == "upgrade":
- # First run after a build that never wrote the marker; the
- # predecessor version was never recorded anywhere.
- telemetry.record("upgrade", from_version="pre-0.3")
- else:
- previous = telemetry.claim_version_change()
- if previous:
- telemetry.record("upgrade", from_version=previous)
recovered = recover_pending_handoffs()
record_session_start(store, hook_input)
if recovered:
diff --git a/integrations/claude-code-plugin/core/mcp_server.py b/integrations/claude-code-plugin/core/mcp_server.py
index a0b73cb79..036fbbdc9 100644
--- a/integrations/claude-code-plugin/core/mcp_server.py
+++ b/integrations/claude-code-plugin/core/mcp_server.py
@@ -21,9 +21,16 @@ from memory_core import (
PROTOCOL_VERSION = "2024-11-05"
TOOL_NAME = "search_memories"
TOOL_DESCRIPTION = (
- "Search memories from earlier work in this repository. Use it before "
- "repeating investigation or when earlier decisions, fixes, commands, or "
- "results may help."
+ "Search memories from earlier work in this repository. ALWAYS call this "
+ "tool before answering anything that could depend on prior context: the "
+ "user's preferences, facts about this codebase, history, people, projects, "
+ "or earlier decisions. Do not rely on the chat window alone. The "
+ "repository's memory is shared by everyone who works in it and includes "
+ "what it took to run, test, or build here, so search before assuming an "
+ "invocation works. The scope argument changes what is searched: 'repo' "
+ "(default) is the whole repository's shared memory plus your own "
+ "preferences, 'dir' narrows the shared part to the directory you are "
+ "working in, and 'mine' is your preferences alone."
)
TOOL_SCHEMA = {
"type": "object",
diff --git a/integrations/claude-code-plugin/core/memory_core.py b/integrations/claude-code-plugin/core/memory_core.py
index 9b420a063..77d7a2b80 100644
--- a/integrations/claude-code-plugin/core/memory_core.py
+++ b/integrations/claude-code-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.3"
+PLUGIN_VERSION = "0.3.1"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
@@ -71,13 +71,15 @@ MAX_FLUSH_ATTEMPTS = 5
FORGET_PAGE_SIZE = 100
FORGET_MAX_PAGES = 50
-PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work.
+PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository.
A completed change should produce one memory explaining the resulting behavior, where it is implemented when useful, and any important constraints or reasoning. Exploration or accepted decisions may produce separate memories only when they are independently useful.
-Use the coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+A command that failed and was then made to work should produce one memory naming the failing invocation, the error it returned, and the invocation that succeeded. Do not save one-off errors caused by an edit still in progress, transient network failures, or anything a rerun would fix on its own.
-Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state.
+Use the current coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+
+Write about the repository, not the user, assistant, session, or task. Do not save personal preferences. Do not save a memory that only states which repository, branch, or directory the session worked in. Do not include test results, documentation updates, release notes, or temporary state.
If nothing useful was established, return no memories."""
@@ -1798,34 +1800,6 @@ def extraction_message_batches(
return batches
-# Platform surface attribution. Read from the generated per-host module so a new
-# entrypoint is correct without remembering to configure anything.
-try: # pragma: no cover - absent only in the un-built shared source tree
- from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
- from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
-except ImportError:
- _PLATFORM_SOURCE = "MEM0_PLUGIN"
- _PLATFORM_APPLICATION = ""
-
-
-def platform_headers(key: str) -> dict[str, str]:
- """Auth plus the three surface-identity headers.
-
- X-Mem0-Source and X-Application are set-once by contract: this is the
- outermost layer, so it sets them, and nothing below may overwrite them.
- X-Mem0-Client is append-only โ anything downstream adds itself to the tail.
- """
- headers = {
- "Authorization": f"Token {key}",
- "Content-Type": "application/json",
- "X-Mem0-Source": _PLATFORM_SOURCE,
- "X-Mem0-Client": f"mem0-plugin/{PLUGIN_VERSION}",
- }
- if _PLATFORM_APPLICATION:
- headers["X-Application"] = _PLATFORM_APPLICATION
- return headers
-
-
def _request_json(
url: str, key: str, payload: dict[str, Any], timeout: float
) -> tuple[dict[str, Any] | list[Any], int, int]:
@@ -1833,7 +1807,7 @@ def _request_json(
request = urllib.request.Request(
url,
data=raw,
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -1860,7 +1834,7 @@ def _get_json(
) -> tuple[dict[str, Any] | list[Any], int]:
request = urllib.request.Request(
url,
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="GET",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -2006,13 +1980,6 @@ def flush_session(
"user_id": write_user,
"app_id": repo.app_id,
"run_id": session_id,
- # Top level, not metadata: the backend reads `source` from the body or
- # the query string, never from metadata, which is where this used to
- # sit. The X-Mem0-Source header is also read, but only from the
- # platform release that ships alongside this change, so the body value
- # is what makes attribution work on both. The harness tag stays in
- # metadata as hook provenance.
- "source": _PLATFORM_SOURCE,
"metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)},
"agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS,
"custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS,
@@ -2556,7 +2523,7 @@ def _collect_memory_ids(
def _delete_memory(api_url: str, key: str, memory_id: str) -> bool:
request = urllib.request.Request(
f"{api_url}/v1/memories/{urllib.parse.quote(memory_id)}/",
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="DELETE",
)
try:
diff --git a/integrations/claude-code-plugin/core/telemetry.py b/integrations/claude-code-plugin/core/telemetry.py
index c1fc0084c..249595475 100644
--- a/integrations/claude-code-plugin/core/telemetry.py
+++ b/integrations/claude-code-plugin/core/telemetry.py
@@ -1,9 +1,5 @@
#!/usr/bin/env python3
-"""Usage telemetry for Mem0 agent plugins.
-
-Events are linked to your Mem0 account email when an API key is configured, and
-to a random per-machine id otherwise. Not anonymous โ the Python SDK and CLI
-attribute the same way.
+"""Anonymous usage telemetry for Mem0 agent plugins.
Hooks run on a 3-6 second budget and fire on every tool call, so recording never
touches the network: `record` appends one JSON line to a local spool and returns.
@@ -13,8 +9,7 @@ started once per session and again from the flush worker that is already detache
Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false.
Never sends prompts, memory text, queries, file paths, repository names, or API
-keys: only event names, durations, counts, coarse outcomes, and repo/session
-identifiers hashed with a random per-install salt.
+keys: only event names, durations, counts, coarse outcomes, and salted hashes.
"""
from __future__ import annotations
@@ -34,24 +29,8 @@ from typing import Any
import memory_core
-# Seeded from the per-host module the build generates into core/. Two processes
-# in this pipeline never call init() โ mcp_server.py, and the detached
-# `python3 telemetry.py` sender that spawn_flush() starts โ so a module default
-# was what every one of their events got labelled with.
-try: # pragma: no cover - absent only in the un-built shared source tree
- from _harness_id import HARNESS_ID as _DEFAULT_HARNESS
- from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
- from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
- from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG
-except ImportError:
- _DEFAULT_HARNESS = "generic"
- _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN"
- _PLATFORM_SOURCE = "MEM0_PLUGIN"
- _PLATFORM_APPLICATION = ""
-
-_salt_cache: str = ""
-_harness: str = _DEFAULT_HARNESS
-_source_tag: str = _DEFAULT_SOURCE_TAG
+_harness: str = "generic"
+_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
"apikey",
"authorization",
@@ -77,19 +56,10 @@ _PRIVATE_KEYS = {
}
-def init(harness: str = "", source_tag: str = "") -> None:
- """Override the generated identity. Optional โ core/_harness_id.py is the default.
-
- The fallback shape matches memory_core.configure_harness's (``_PLUGIN``).
- It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which
- meant one plugin could emit three different source values depending on which
- process happened to send the batch.
- """
+def init(harness: str = "generic", source_tag: str = "") -> None:
global _harness, _source_tag
- _harness = harness or _DEFAULT_HARNESS
- _source_tag = source_tag or (
- f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG
- )
+ _harness = harness
+ _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/"
@@ -100,16 +70,6 @@ BATCH_SIZE = 100
SEND_TIMEOUT = 5
CLAIM_STALE_SECONDS = 120
CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60
-# A batch is only discarded once it has genuinely been retried this many times.
-MAX_CLAIM_ATTEMPTS = 3
-# Parked claims drained per run, after the live spool. Bounded so a long backlog
-# cannot turn one flush into an unbounded send loop.
-MAX_PARKED_PER_RUN = 3
-# Added to the wait before a released claim becomes reclaimable, per attempt
-# already spent. Releasing straight to "reclaimable now" let two senders burn the
-# whole budget within seconds of one another on a single momentary failure, and
-# discard a batch a retry a minute later would have delivered.
-RETRY_COOLDOWN_SECONDS = 60
def is_enabled() -> bool:
@@ -123,126 +83,9 @@ def is_enabled() -> bool:
def _digest(value: str, length: int = 16) -> str:
- """Unsalted digest. Only for values that are already secrets (API keys)."""
return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length]
-def _salt_path() -> Path:
- return memory_core.data_dir() / "telemetry-salt"
-
-
-def _install_salt() -> str:
- """Random per-install salt, created once and memoized for the process.
-
- Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in
- the identity file. Three reasons, all of which produced wrong data when this
- lived in the identity dict:
-
- - Hooks are short-lived separate processes firing on every tool call, and
- people run more than one agent window. A read-modify-write would let each
- process mint its own salt, so one repository would hash several ways in the
- window before a writer won.
- - resolve_distinct_id holds a copy of the identity dict across a network call
- to /v1/ping/, so whichever write landed second erased the other's key โ
- losing either the salt (repo_hash changes mid-stream) or the email (a
- second $identify, splitting the person).
- - Touching the identity file from record() would create it, and is_first_run
- keys off that file, so recording an event would silently suppress the
- install event.
-
- Published atomically, and there is deliberately no derived fallback. Creating
- the file with O_CREAT|O_EXCL and then writing into it leaves a window where
- the file exists and is empty, and a concurrent hook that reads it in that
- window gets nothing. Falling back to a digest of the path would hand that
- process a salt an attacker can compute, memoized for its whole run, which is
- the privacy control this function exists to provide silently turning itself
- off under load. The salt is written to a private temp file first and linked
- into place, so the name either does not exist or already has the full value.
-
- Returns "" when it genuinely cannot persist. Callers omit the hash entirely
- rather than emit an unsalted one.
- """
- global _salt_cache
- if _salt_cache:
- return _salt_cache
-
- path = _salt_path()
- # Read before writing. Hooks are separate processes firing on every tool
- # call, so all but the first find the salt already published; going straight
- # to create-fsync-link-unlink meant every one of them paid an fsync to
- # discover that, on a path whose whole promise is appending a line and
- # returning.
- try:
- _salt_cache = path.read_text(encoding="utf-8").strip()
- if _salt_cache:
- return _salt_cache
- except OSError:
- pass
-
- temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(handle, "w", encoding="utf-8") as stream:
- stream.write(uuid.uuid4().hex)
- stream.flush()
- os.fsync(stream.fileno())
- try:
- # Atomic claim: fails if another process already published one.
- # os.link rather than replace, which would clobber theirs.
- os.link(temporary, path)
- except FileExistsError:
- pass
- except OSError:
- # No hardlinks here (some network mounts, some container volumes).
- # Claim the name directly instead. That reopens the empty-file
- # window, but the window is now benign: a reader that lands in it
- # gets "" and omits the hash for that process rather than caching a
- # guessable one. Losing the hashes on every run of an entire
- # filesystem is the worse failure.
- try:
- fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(fallback, "w", encoding="utf-8") as stream:
- stream.write(temporary.read_text(encoding="utf-8"))
- except OSError:
- pass
- except OSError:
- pass
- finally:
- try:
- temporary.unlink()
- except OSError:
- pass
-
- try:
- _salt_cache = path.read_text(encoding="utf-8").strip()
- except OSError:
- _salt_cache = ""
- return _salt_cache
-
-
-def _scoped_digest(value: str, length: int = 16) -> str:
- """Salted digest for values drawn from a guessable space.
-
- repo.identity is a git remote URL, or ``local:`` when there is
- no remote โ which normally contains the account username. Sixteen unsalted
- hex characters over that input space is enumerable, so this is not a
- privacy control without the salt. Salting per install keeps every
- within-account join the analytics actually use and gives up only
- cross-machine joins on the same repository, which nothing computes.
-
- Returns "" when there is no salt, so record() omits the property. An
- unsalted digest over this input space is close to plaintext, and emitting one
- under a name that implies it is hashed is worse than sending nothing.
- """
- if not value:
- return ""
- salt = _install_salt()
- if not salt:
- return ""
- return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length]
-
-
def _safe_value(value: Any) -> Any:
if isinstance(value, str):
return memory_core.redact(value)
@@ -302,176 +145,9 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str:
return created
-def _rotate_anonymous_id(identity: dict[str, str]) -> str:
- """Mint a fresh anonymous id because the account context is gone.
-
- The previous id may already have been merged into a person profile by an
- $identify, and that merge is permanent. Reusing it after a logout or a key
- change attributes everything that follows to the account that just went
- away, which is the same misattribution the key fingerprint exists to stop,
- only arriving through the anonymous path instead.
-
- `aliased` is cleared with it: the new id has never been merged, so it is
- eligible to be aliased into whatever account comes next.
- """
- created = f"code-anon-{uuid.uuid4().hex}"
- identity["anonymous_id"] = created
- identity.pop("aliased", None)
- _write_identity(identity)
- return created
-
-
-def _install_state_path() -> Path:
- return memory_core.data_dir() / "install-state.json"
-
-
def is_first_run() -> bool:
- """Whether install has never been recorded on this machine.
-
- Deliberately NOT the identity file. That file is only written by a
- successful flush, so an offline or firewalled user recorded code.install on
- every single session, forever โ and every 0.2.x user recorded one on their
- first 0.3.x session because 0.2.x never wrote it at all.
- """
- return not _install_state_path().exists()
-
-
-def data_dir_was_empty() -> bool:
- """Whether the data directory is untouched. Call BEFORE anything writes to it.
-
- hook_runner reaches claim_install() only after cache_plugin_api_key() has
- written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so
- asking at claim time always saw content and every fresh install reported an
- upgrade. The caller snapshots this at the top of the run instead.
- """
- return not _data_dir_has_content()
-
-
-def claim_install(was_empty: bool | None = None) -> str | None:
- """Claim the one install/upgrade record for this machine, atomically.
-
- Returns the event to record ("install" or "upgrade"), or None if another
- session already claimed it. O_CREAT|O_EXCL so two sessions starting together
- cannot both win.
-
- `was_empty` must come from data_dir_was_empty() called before this process
- wrote anything. Omitting it falls back to checking now, which is only
- correct for a caller that has touched nothing.
- """
- if not is_enabled():
- # Never consume the one-shot claim while the user is opted out, or they
- # would silently lose their install event if they later opt in.
- return None
-
- path = _install_state_path()
- upgrading = not (data_dir_was_empty() if was_empty is None else was_empty)
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- except FileExistsError:
- return None
- except OSError:
- return None
- try:
- with os.fdopen(handle, "w", encoding="utf-8") as stream:
- json.dump(
- {
- "plugin_version": memory_core.PLUGIN_VERSION,
- "installed_at": memory_core.utc_now(),
- "upgraded": upgrading,
- },
- stream,
- )
- # Durable before this returns. The O_EXCL open is what makes the
- # claim exclusive, so it cannot be replaced by a temp-and-rename
- # without losing that, which leaves the content as the thing to make
- # safe. A kill between the open and this fsync used to leave a marker
- # that exists but parses to nothing: is_first_run reads it as claimed
- # and claim_version_change cannot read a version out of it.
- stream.flush()
- os.fsync(stream.fileno())
- except OSError:
- pass
- return "upgrade" if upgrading else "install"
-
-
-def _data_dir_has_content() -> bool:
- """Whether anything predates this session in the plugin data directory."""
- try:
- for entry in memory_core.data_dir().iterdir():
- if entry.name != "install-state.json":
- return True
- except OSError:
- pass
- return False
-
-
-def _repair_install_state(path: Path) -> None:
- """Rewrite an unparseable marker so version tracking can resume."""
- try:
- temporary = path.with_suffix(f".{os.getpid()}.tmp")
- temporary.write_text(
- json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}),
- encoding="utf-8",
- )
- temporary.replace(path)
- except OSError:
- pass
-
-
-def claim_version_change() -> str | None:
- """Return the previously recorded version if it differs, updating the marker.
-
- Only meaningful once the marker exists โ the first transition into 0.3.x has
- no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting
- the marker means the next session sees no change and records nothing.
- """
- path = _install_state_path()
- try:
- state = json.loads(path.read_text(encoding="utf-8"))
- except OSError:
- return None
- except json.JSONDecodeError:
- # A crash between O_EXCL and the write leaves an empty marker. Left
- # alone it disables every future upgrade event on this machine, because
- # claim_install sees the file and this function cannot parse it.
- state = None
- if not isinstance(state, dict):
- _repair_install_state(path)
- return None
- previous = str(state.get("plugin_version") or "")
- if not previous or previous == memory_core.PLUGIN_VERSION:
- return None
- # Claim the transition with an exclusive sentinel before rewriting the
- # marker. A plain read-modify-write let every concurrently starting session
- # observe the old version and each record its own upgrade โ and the first
- # session after a version bump is exactly when several agent windows restart
- # together.
- sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}")
- try:
- os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
- except FileExistsError:
- return None
- except OSError:
- return None
-
- state["plugin_version"] = memory_core.PLUGIN_VERSION
- state["upgraded_at"] = memory_core.utc_now()
- temporary = path.with_suffix(f".{os.getpid()}.tmp")
- try:
- temporary.write_text(json.dumps(state), encoding="utf-8")
- temporary.replace(path)
- except OSError:
- # Release the claim. The marker still records the old version, so
- # without this the sentinel makes claim_version_change return early on
- # every later run and this version's upgrade is never recorded again.
- for leftover in (sentinel, temporary):
- try:
- leftover.unlink()
- except OSError:
- pass
- return None
- return previous
+ """Whether this machine has never recorded a plugin event before."""
+ return not _identity_path().exists()
def record(
@@ -492,32 +168,19 @@ def record(
except OSError:
pass
properties = _safe_value(properties)
- # Stamped in the RECORDING process, beside harness. `source` used to be
- # read in the sending process from a module global, so whichever process
- # drained the spool named every event in it. flush() spreads per-event
- # properties last, so this now wins over any sender's default.
properties.update(
harness=_harness,
- source=_source_tag,
plugin_version=memory_core.PLUGIN_VERSION,
os=sys.platform,
python_version=platform.python_version(),
)
- # Assigned only when the digest is real. _scoped_digest returns "" when
- # the salt could not be persisted, and an empty property is worse than an
- # absent one: it survives the None filter below and reads as a value.
if repo is not None:
- repo_hash = _scoped_digest(getattr(repo, "identity", ""))
- if repo_hash:
- properties["repo_hash"] = repo_hash
+ properties["repo_hash"] = _digest(getattr(repo, "identity", ""))
if session_id:
- session_hash = _scoped_digest(session_id)
- if session_hash:
- properties["session_hash"] = session_hash
+ properties["session_hash"] = _digest(session_id)
line = json.dumps(
{
"event": f"{EVENT_PREFIX}.{event}",
- "uuid": str(uuid.uuid4()),
"timestamp": memory_core.utc_now(),
"properties": {
key: value for key, value in properties.items() if value is not None
@@ -576,201 +239,38 @@ def spawn_flush() -> bool:
return False
-def _claim_name(attempt: int = 0) -> str:
- """Claim filename. The attempt count rides in the name so the 7-day expiry
- only ever discards a batch that was actually retried and failed."""
- return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending"
-
-
-def _claim_attempt(claim: Path) -> int:
- """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape.
-
- Anchored on field position, not on a leading "a": the legacy shape is
- ``telemetry--.sending`` and a hex id such as ``a1234567`` would
- otherwise parse as attempt 1234567 and be discarded unsent on the first
- flush after an upgrade.
- """
- stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name
- parts = stem.split("-")
- if len(parts) != 4:
- return 0
- tail = parts[3]
- if tail.startswith("a") and tail[1:].isdigit():
- return int(tail[1:])
- return 0
-
-
-def _touch(path: Path) -> None:
- """Refresh mtime so a claim's age measures time since it was claimed.
-
- ``Path.replace`` is ``os.rename``, which preserves mtime โ so a claim created
- after a quiet minute inherited the spool's last-write time and looked
- abandoned the instant it was made. A second sender would then take it over
- while the first was still posting, and both would deliver the batch.
- """
- try:
- os.utime(path, None)
- except OSError:
- pass
-
-
def _claim_spool() -> Path | None:
"""Rename the spool aside so exactly one sender owns each batch."""
directory = memory_core.data_dir()
- claim = directory / _claim_name()
+ claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending"
spool = _spool_path()
try:
spool.replace(claim)
- _touch(claim)
return claim
except OSError:
pass
- return _claim_parked(directory)
-
-
-def _sweep_debris(directory: Path) -> None:
- """Remove files nothing else will ever pick up again.
-
- *.partial is a temp file orphaned by a crash between write and rename.
- *.corrupt is a batch quarantined for undecodable content. No glob in this
- module matches either, so without this they accumulate on disk for the life
- of the install.
-
- Quarantined batches are kept far longer than debris: they are the only
- evidence left of events that could not be delivered, and someone diagnosing
- a report of missing telemetry has to be able to find one.
- """
now = time.time()
- for debris in directory.glob("telemetry-*.partial"):
- try:
- if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS:
- debris.unlink()
- except OSError:
- continue
- for quarantined in directory.glob("telemetry-*.corrupt"):
- try:
- if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS:
- quarantined.unlink()
- except OSError:
- continue
- # The same reasoning covers *.tmp. _write_identity and _install_salt both
- # create one and unlink it in a finally, which a SIGKILL skips, and no glob
- # in this module matches the leftovers either.
- for temporary in directory.glob("telemetry-*.tmp"):
- try:
- if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS:
- temporary.unlink()
- except OSError:
- continue
-
-
-def _claim_parked(directory: Path) -> Path | None:
- """Take the oldest abandoned claim, if any lease has actually expired.
-
- Kept separate from the live spool so flush() can drain both in one run.
- Previously parked batches were only reachable when no spool existed at all,
- and because sessions keep recording there usually was one โ so a batch
- parked by a failed send waited until the 7-day expiry deleted it unsent,
- even though its own presence is what started the sender.
- """
- now = time.time()
- for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime):
+ for orphan in sorted(directory.glob("telemetry-*.sending")):
try:
age = now - orphan.stat().st_mtime
except OSError:
continue
- if age < CLAIM_STALE_SECONDS:
- # Someone else holds a live lease on it. This check has to come
- # first. Claiming a file bumps its attempt count and refreshes its
- # mtime, so a sender that has just taken the final attempt looks
- # exhausted to everyone else while it is actively draining. Judging
- # exhaustion before liveness let a second sender unlink a batch out
- # from under its owner, losing every event in it.
- continue
- # Attempts, not age. Every re-claim touches the mtime and every release
- # backdates it by a fixed amount, so age is pinned near the stale
- # threshold and never reaches the expiry. Age stays only as a backstop
- # for files that never carried an attempt marker.
- if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS:
+ if age > CLAIM_EXPIRY_SECONDS:
try:
orphan.unlink()
except OSError:
pass
continue
- claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1)
+ if age < CLAIM_STALE_SECONDS:
+ continue
try:
orphan.replace(claim)
- _touch(claim)
return claim
except OSError:
continue
return None
-def _safe_mtime(path: Path) -> float:
- try:
- return path.stat().st_mtime
- except OSError:
- return 0.0
-
-
-def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool:
- """Persist the unsent remainder, atomically, and refresh the lease.
-
- Called after every successful batch. Two jobs: a retry resumes where the
- send stopped instead of re-posting from the top, and the rewrite doubles as
- the lease heartbeat, so a slow sender does not have its claim stolen
- mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS.
- """
- if not remaining:
- try:
- claim.unlink()
- except OSError:
- pass
- return True
- temporary = claim.with_suffix(f".{os.getpid()}.partial")
- try:
- payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining)
- # fsync before the rename: without it the rename can land while the
- # bytes have not, and the claim comes back empty or truncated after a
- # crash. _drain then reads zero events and unlinks it.
- with open(temporary, "w", encoding="utf-8") as handle:
- handle.write(payload)
- handle.flush()
- os.fsync(handle.fileno())
- temporary.replace(claim)
- _touch(claim)
- return True
- except OSError:
- try:
- temporary.unlink()
- except OSError:
- pass
- return False
-
-
-def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None:
- """Persist the remainder and drop the lease, because this sender has given up.
-
- Distinct from the per-batch heartbeat: heartbeating on the way out would
- make an abandoned batch look actively owned for a further
- CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the
- threshold lets the next flush pick it up immediately, while the attempt
- count in the filename still bounds how many times that can happen.
- """
- if not _rewrite_claim(claim, remaining):
- return
- try:
- # Backdate past the stale threshold so the next flush can pick it up,
- # minus a cooldown that grows with the attempts already spent. Clamped so
- # the mtime never lands in the future, which would read as a live lease.
- cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS)
- released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown
- os.utime(claim, (released, released))
- except OSError:
- pass
-
-
def _resolve_email(key: str) -> str:
"""Trade the API key for the account email so events join other Mem0 surfaces."""
url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/"
@@ -800,130 +300,34 @@ def _post(payload: dict[str, Any], url: str) -> bool:
def resolve_distinct_id() -> tuple[str, str]:
- """Return the PostHog distinct id and the anonymous id it replaced, if any.
-
- The second value becomes a PostHog $identify alias. It is ONLY ever an
- anonymous id: aliasing one account email to another merges two real person
- profiles and cannot be undone, so a key that now belongs to a different
- account re-resolves with no alias.
- """
+ """Return the PostHog distinct id and the anonymous id it replaced, if any."""
identity = _read_identity()
- key = memory_core.api_key()
- fingerprint = _digest(key) if key else ""
email = identity.get("email", "")
-
- if email and fingerprint:
- recorded = identity.get("key_fingerprint", "")
- if recorded == fingerprint:
- return email, ""
- if not recorded:
- # Rows written before fingerprints existed. Verify rather than
- # adopt: a key changed before the upgrade would otherwise bind the
- # new key to the previous account's email, permanently, and the
- # fingerprint would then agree with itself forever after.
- verified = _resolve_email(key)
- if not verified:
- # Offline, firewalled, or the API is down. Keep the previous
- # behaviour and retry on the next flush rather than dropping a
- # real account attribution. Safe because the same network that
- # failed /v1/ping/ is about to fail the PostHog POST, so nothing
- # is delivered under the unverified identity in the meantime.
- return email, ""
- identity["email"] = verified
- identity["key_fingerprint"] = fingerprint
- _write_identity(identity)
- return verified, ""
-
+ if email:
+ return email, ""
+ key = memory_core.api_key()
if not key:
- # No key to verify the account with; do not keep attributing to it.
- if email:
- identity.pop("email", None)
- identity.pop("key_fingerprint", None)
- return _rotate_anonymous_id(identity), ""
return anonymous_id(identity), ""
-
- resolved = _resolve_email(key)
- if not resolved:
- # The key changed and will not resolve (revoked, offline, API down).
- # Reaching here with an email means the recorded fingerprint disagreed,
- # so the key really did change. Drop the account and rotate: the stored
- # anonymous id may already be merged into that account's person, and
- # reusing it would keep the events on the profile we are trying to
- # leave.
- if email:
- identity.pop("email", None)
- identity.pop("key_fingerprint", None)
- return _rotate_anonymous_id(identity), ""
+ email = _resolve_email(key)
+ if not email:
return anonymous_id(identity), ""
-
- # Alias only when going anonymous -> email for the first time. Once an anon
- # id has been merged into an account it must never be offered again: an
- # alias naming an already-identified id is what could link two real people.
- previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "")
- if previous:
- identity["aliased"] = True
- identity["email"] = resolved
- identity["key_fingerprint"] = fingerprint
+ previous = identity.get("anonymous_id", "")
+ identity["email"] = email
_write_identity(identity)
- return resolved, previous
+ return email, previous
def flush() -> int:
- """Drain the live spool, then any parked claims, and return events sent."""
+ """Drain claimed spools to PostHog and return the number of events sent."""
if not is_enabled():
return 0
- sent, delivered = _drain(_claim_spool())
- if not delivered:
- # The network is failing. Retrying other batches now would only burn
- # their attempt budget against the same broken connection.
- return sent
-
- # Parked batches used to starve behind the live spool indefinitely. Bounded
- # per run so a long backlog cannot turn one flush into an unbounded loop.
- directory = memory_core.data_dir()
- _sweep_debris(directory)
- for _ in range(MAX_PARKED_PER_RUN):
- parked = _claim_parked(directory)
- if parked is None:
- break
- count, delivered = _drain(parked)
- sent += count
- if not delivered:
- break
- return sent
-
-
-def _drain(claim: Path | None) -> tuple[int, bool]:
- """Post one claimed batch file, recording progress after every batch.
-
- Returns (events sent, whether everything was delivered).
- """
+ claim = _claim_spool()
if claim is None:
- return 0, True
+ return 0
try:
lines = claim.read_text(encoding="utf-8").splitlines()
- except ValueError:
- # UnicodeDecodeError from a torn write: the content is unrecoverable, so
- # quarantine rather than retry. flush() runs from a bare `finally:` in
- # flush_worker, so raising here also skips the handoff cleanup, and an
- # undecodable file would otherwise be re-read on every flush forever.
- # Reported as delivered because there is nothing left to deliver and the
- # rest of the run should continue.
- try:
- claim.replace(claim.with_suffix(".corrupt"))
- except OSError:
- try:
- claim.unlink()
- except OSError:
- pass
- return 0, True
except OSError:
- # Could not read it, which is not the same as having nothing to send.
- # The file is left exactly where it is: a vanished or briefly unreadable
- # claim is retryable, and quarantining it here would discard events over
- # a transient filesystem error. Reported as undelivered so the run stops
- # instead of counting a batch nothing was posted from as delivered.
- return 0, False
+ return 0
events = []
for line in lines:
try:
@@ -933,18 +337,11 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
if isinstance(value, dict) and value.get("event"):
events.append(value)
if not events:
- # Only delete when the file really is empty. A non-empty file that
- # parses to nothing is a torn write, and its contents are the unsent
- # remainder โ deleting it is the data loss this PR exists to prevent.
try:
- empty = claim.stat().st_size == 0
- except OSError:
- empty = True
- try:
- claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink()
+ claim.unlink()
except OSError:
pass
- return 0, True
+ return 0
distinct_id, aliased_anonymous_id = resolve_distinct_id()
if aliased_anonymous_id:
@@ -963,17 +360,12 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
sent = 0
for start in range(0, len(events), BATCH_SIZE):
- chunk = events[start : start + BATCH_SIZE]
batch = [
{
"event": event["event"],
"distinct_id": distinct_id,
- # Carried through from record() so a resend can be collapsed.
- "uuid": event.get("uuid"),
"timestamp": event.get("timestamp"),
"properties": {
- # Fallback only: events recorded by a build before source
- # moved into record() have none of their own.
"source": _source_tag,
"language": "python",
"$process_person_profile": False,
@@ -981,24 +373,16 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
**(event.get("properties") or {}),
},
}
- for event in chunk
+ for event in events[start : start + BATCH_SIZE]
]
if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL):
- # Keep only what has not been delivered, and release the lease.
- # Previously the whole file was kept and the retry re-posted every
- # batch, including the ones that had already arrived.
- _release_claim(claim, events[start:])
- return sent, False
- sent += len(chunk)
- # Record progress and refresh the lease after each successful batch, so
- # a crash repeats at most one batch instead of the entire file. If the
- # rewrite fails the claim still holds delivered events, so stop rather
- # than carry on as though progress were recorded โ continuing is how the
- # duplicate delivery this PR fixes would come back.
- if not _rewrite_claim(claim, events[start + len(chunk) :]):
- _release_claim(claim, events[start + len(chunk) :])
- return sent, False
- return sent, True
+ return sent
+ sent += len(batch)
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return sent
def main() -> int:
diff --git a/integrations/claude-code-plugin/plugin-build.json b/integrations/claude-code-plugin/plugin-build.json
index d62d653c3..68d306fd6 100644
--- a/integrations/claude-code-plugin/plugin-build.json
+++ b/integrations/claude-code-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.3",
+ "version": "0.3.1",
"homepage": "https://docs.mem0.ai/integrations/claude-code",
"native": {
"pluginRoot": "${CLAUDE_PLUGIN_ROOT}",
diff --git a/integrations/claude-code-plugin/skills/pause/SKILL.md b/integrations/claude-code-plugin/skills/pause/SKILL.md
index ce69d13d2..5aef04f39 100644
--- a/integrations/claude-code-plugin/skills/pause/SKILL.md
+++ b/integrations/claude-code-plugin/skills/pause/SKILL.md
@@ -7,8 +7,8 @@ disable-model-invocation: true
# Pause memory capture
To pause (hooks stop capturing and sending session content; a minimal
-telemetry ping still fires at session start, under your Mem0 account email,
-unless `MEM0_TELEMETRY=false`):
+anonymous telemetry ping still fires at session start unless
+`MEM0_TELEMETRY=false`):
```bash
python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" --harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" pause
diff --git a/integrations/claude-code-plugin/skills/search/SKILL.md b/integrations/claude-code-plugin/skills/search/SKILL.md
index f7289b91d..198a1f023 100644
--- a/integrations/claude-code-plugin/skills/search/SKILL.md
+++ b/integrations/claude-code-plugin/skills/search/SKILL.md
@@ -12,9 +12,11 @@ Call `search_memories` with the user's question. Treat `--top-k`, `--category`,
query.
Omit `top_k` to use Mem0's configured default. Omit `category` to search every
-category. Omit `scope` to use the configured default, normally `repo`: this
-repository's shared memory, which everyone who works in it contributes to,
-plus your own preferences.
+category; a category is a best-effort label Mem0 assigned when it saved the
+memory, so if a category search misses, repeat it without the category. Omit
+`scope` to use the configured default, normally `repo`: this repository's
+shared memory, which everyone who works in it contributes to, plus your own
+preferences.
Pass `scope` when the question needs something else: `dir` to narrow the
shared memory to the directory you are working in (a package inside a
diff --git a/integrations/claude-code-plugin/tests/test_memory_core.py b/integrations/claude-code-plugin/tests/test_memory_core.py
index b6b1c28f9..8c7017913 100644
--- a/integrations/claude-code-plugin/tests/test_memory_core.py
+++ b/integrations/claude-code-plugin/tests/test_memory_core.py
@@ -2,7 +2,6 @@ from __future__ import annotations
import json
import os
-import re
import sqlite3
import subprocess
import sys
@@ -2307,8 +2306,8 @@ def test_sidekick_instructions_reject_unrequested_related_changes():
prompt = (PLUGIN_ROOT / "agents" / "sidekick.md").read_text()
normalized = " ".join(prompt.split())
assert "Skill" in prompt.split("---", 2)[1]
- assert "call `search_memories` with a" in normalized
- assert "focused question before searching the repository again" in normalized
+ assert "ALWAYS call `search_memories` before answering anything" in normalized
+ assert "Do not rely on the chat window" in normalized
assert "Complete only the work the main agent assigned" in normalized
assert "Do not make related improvements" in normalized
assert "report them separately" in normalized
@@ -3461,12 +3460,7 @@ def test_automatic_flush_can_be_disabled_for_external_harnesses(isolated_env):
def test_version_is_single_sourced():
manifest = json.loads((PLUGIN_ROOT / ".claude-plugin" / "plugin.json").read_text())
assert manifest["name"] == "mem0"
- # Compared against PLUGIN_VERSION, never a literal. A hardcoded version here
- # was one more place to edit on every release, inside the test asserting the
- # version is single-sourced, and it caught nothing that the agreement checks
- # below do not: fifteen places set to the same wrong value would still pass.
- assert re.fullmatch(r"\d+\.\d+\.\d+", memory_core.PLUGIN_VERSION), memory_core.PLUGIN_VERSION
- assert manifest["version"] == memory_core.PLUGIN_VERSION
+ assert manifest["version"] == memory_core.PLUGIN_VERSION == "0.3.1"
root = REPOSITORY_ROOT
for mp in (root / "marketplace.json", root / ".claude-plugin" / "marketplace.json"):
entry = next(p for p in json.loads(mp.read_text())["plugins"] if p["name"] == "mem0")
@@ -4333,7 +4327,7 @@ def test_flush_sends_unified_body_with_both_agent_and_user_id(isolated_env, monk
assert sent_body["run_id"] == "s1"
assert "lane" not in sent_body["metadata"]
assert "Save concise repository facts" in sent_body["agent_custom_instructions"]
- assert "Write about the repository, not the user" in sent_body["agent_custom_instructions"]
+ assert "invocation that succeeded" in sent_body["agent_custom_instructions"]
assert "Do not save repository facts" in sent_body["custom_instructions"]
assert sent_body["custom_categories"] == memory_core.CODING_MEMORY_CATEGORIES
store.close()
diff --git a/integrations/claude-code-plugin/tests/test_telemetry.py b/integrations/claude-code-plugin/tests/test_telemetry.py
index 73bf8f121..0ae280b19 100644
--- a/integrations/claude-code-plugin/tests/test_telemetry.py
+++ b/integrations/claude-code-plugin/tests/test_telemetry.py
@@ -1,7 +1,6 @@
from __future__ import annotations
import json
-import os
import sys
from pathlib import Path
from unittest.mock import patch
@@ -199,11 +198,9 @@ def test_a_stale_claim_is_reclaimed(isolated_env, monkeypatch):
telemetry.record("search")
orphan = telemetry._claim_spool()
assert orphan is not None
- # Frozen rather than re-stat'd per call: flush() drains the live spool and
- # then looks for parked claims in the same run, so by the second look this
- # file no longer exists.
- stale_now = orphan.stat().st_mtime + telemetry.CLAIM_STALE_SECONDS + 1
- monkeypatch.setattr(telemetry.time, "time", lambda: stale_now)
+ monkeypatch.setattr(
+ telemetry.time, "time", lambda: orphan.stat().st_mtime + telemetry.CLAIM_STALE_SECONDS + 1
+ )
with patch.object(telemetry, "_post", lambda payload, url: True):
assert telemetry.flush() == 1
@@ -213,13 +210,9 @@ def test_an_expired_claim_is_dropped(isolated_env, monkeypatch):
telemetry.record("search")
orphan = telemetry._claim_spool()
assert orphan is not None
- expired_now = orphan.stat().st_mtime + telemetry.CLAIM_EXPIRY_SECONDS + 1
- monkeypatch.setattr(telemetry.time, "time", lambda: expired_now)
- # Expiry now only discards a batch that was genuinely retried and failed,
- # so age alone is not enough โ age it past the attempt budget too.
- retried = orphan.parent / orphan.name.replace("-a0.", f"-a{telemetry.MAX_CLAIM_ATTEMPTS}.")
- orphan.replace(retried)
- os.utime(retried, (expired_now, expired_now - telemetry.CLAIM_EXPIRY_SECONDS - 1))
+ monkeypatch.setattr(
+ telemetry.time, "time", lambda: orphan.stat().st_mtime + telemetry.CLAIM_EXPIRY_SECONDS + 1
+ )
assert telemetry._claim_spool() is None
assert not list(memory_core.data_dir().glob("telemetry-*.sending"))
@@ -265,150 +258,12 @@ def test_an_unresolvable_key_falls_back_to_the_anonymous_id(isolated_env, monkey
assert telemetry.resolve_distinct_id()[0].startswith("code-anon-")
-def test_logging_out_does_not_leave_events_on_the_previous_account(isolated_env, monkeypatch):
- """Review finding: clearing the email kept an id already merged into a person.
-
- The anonymous id is offered to PostHog as $anon_distinct_id on first sign-in,
- and that merge is permanent. Keeping it after the key goes away means every
- later anonymous event lands on the account that just left.
- """
- # Run anonymously first, which is the only way an id exists to be merged.
- merged = telemetry.anonymous_id()
-
- monkeypatch.setenv("MEM0_API_KEY", "key-for-account-a")
- with patch.object(telemetry, "_resolve_email", lambda key: "a@example.com"):
- identified, alias = telemetry.resolve_distinct_id()
- assert identified == "a@example.com"
- assert alias == merged, "the anonymous id was merged into this account"
-
- monkeypatch.delenv("MEM0_API_KEY", raising=False)
- after_logout, logout_alias = telemetry.resolve_distinct_id()
-
- assert after_logout.startswith("code-anon-")
- assert after_logout != merged, "reused an id already merged into the previous account"
- assert logout_alias == ""
- assert "aliased" not in telemetry._read_identity(), "rotated id must be aliasable again"
-
-
-def test_a_changed_key_that_will_not_resolve_rotates_the_anonymous_id(isolated_env, monkeypatch):
- """Same leak by the other route: fingerprint disagrees and the lookup fails."""
- merged = telemetry.anonymous_id()
- monkeypatch.setenv("MEM0_API_KEY", "key-for-account-a")
- with patch.object(telemetry, "_resolve_email", lambda key: "a@example.com"):
- telemetry.resolve_distinct_id()
-
- monkeypatch.setenv("MEM0_API_KEY", "key-for-account-b")
- with patch.object(telemetry, "_resolve_email", lambda key: ""):
- after, alias = telemetry.resolve_distinct_id()
-
- assert after.startswith("code-anon-")
- assert after != merged
- assert alias == ""
- assert "email" not in telemetry._read_identity()
-
-
-def test_a_legacy_cached_email_is_verified_before_the_key_is_bound(isolated_env, monkeypatch):
- """Review finding: a key changed before upgrading bound the wrong account.
-
- Rows written before fingerprints existed carry an email and no fingerprint.
- Adopting the current key without checking pinned that key to the previous
- account's email, and every run after that agreed with itself.
- """
- telemetry._write_identity({"email": "old@example.com", "anonymous_id": "code-anon-seed"})
- monkeypatch.setenv("MEM0_API_KEY", "key-for-account-b")
-
- with patch.object(telemetry, "_resolve_email", lambda key: "new@example.com"):
- resolved, alias = telemetry.resolve_distinct_id()
-
- assert resolved == "new@example.com"
- assert alias == "", "email to email must never alias; it merges two real people"
- stored = telemetry._read_identity()
- assert stored["email"] == "new@example.com"
- assert stored["key_fingerprint"] == telemetry._digest("key-for-account-b")
-
-
-def test_a_legacy_row_keeps_working_when_the_account_cannot_be_checked(isolated_env, monkeypatch):
- """Firewalled users must not lose attribution, and must not bind unverified.
-
- The same network that fails /v1/ping/ fails the PostHog POST, so nothing is
- delivered under the unverified identity while this holds.
- """
- telemetry._write_identity({"email": "old@example.com"})
- monkeypatch.setenv("MEM0_API_KEY", "key-for-account-b")
-
- with patch.object(telemetry, "_resolve_email", lambda key: ""):
- resolved, _ = telemetry.resolve_distinct_id()
-
- assert resolved == "old@example.com"
- assert "key_fingerprint" not in telemetry._read_identity(), "bound an unverified key"
-
-
-def test_a_failed_upgrade_claim_can_be_retried(isolated_env, monkeypatch):
- """Review finding: a failed rewrite left the sentinel and suppressed forever.
-
- claim_version_change returns early on FileExistsError, and the marker still
- holds the old version, so the upgrade for that version was never recorded
- again on that machine.
- """
- telemetry.claim_install()
- state_path = memory_core.data_dir() / "install-state.json"
- state = json.loads(state_path.read_text())
- state["plugin_version"] = "0.0.1-old"
- state_path.write_text(json.dumps(state), encoding="utf-8")
-
- real_replace = Path.replace
-
- def failing_replace(self, target):
- raise OSError("disk full")
-
- monkeypatch.setattr(Path, "replace", failing_replace)
- assert telemetry.claim_version_change() is None
-
- monkeypatch.setattr(Path, "replace", real_replace)
- assert telemetry.claim_version_change() == "0.0.1-old", "sentinel suppressed the retry"
-
-
-def test_first_run_is_not_flipped_by_writing_the_identity_file(isolated_env):
- """The identity file is written by a successful flush, not by recording.
-
- Keying first-run off it meant an offline user recorded code.install on every
- session forever, and every 0.2.x user recorded one on their first 0.3.x run.
- """
+def test_is_first_run_flips_after_the_first_identity_write(isolated_env):
assert telemetry.is_first_run()
telemetry.anonymous_id()
- assert telemetry.is_first_run()
-
-
-def test_claiming_install_ends_first_run(isolated_env):
- assert telemetry.claim_install() == "install"
assert not telemetry.is_first_run()
-def test_install_can_only_be_claimed_once(isolated_env):
- """Two sessions starting together must not both record an install."""
- assert telemetry.claim_install() == "install"
- assert telemetry.claim_install() is None
-
-
-def test_a_populated_data_dir_reads_as_an_upgrade(isolated_env):
- """A fresh install has an empty data directory; anything else predates it."""
- data_dir = memory_core.data_dir()
- data_dir.mkdir(parents=True, exist_ok=True)
- (data_dir / "requirements.txt").write_text("mem0ai\n", encoding="utf-8")
- assert telemetry.claim_install() == "upgrade"
-
-
-def test_a_version_change_is_claimed_once(isolated_env):
- telemetry.claim_install()
- state_path = memory_core.data_dir() / "install-state.json"
- state = json.loads(state_path.read_text())
- state["plugin_version"] = "0.0.1-old"
- state_path.write_text(json.dumps(state), encoding="utf-8")
-
- assert telemetry.claim_version_change() == "0.0.1-old"
- assert telemetry.claim_version_change() is None
-
-
def test_spawn_flush_does_nothing_without_a_spool(isolated_env):
with patch.object(telemetry.subprocess, "Popen") as popen:
assert telemetry.spawn_flush() is False
@@ -418,114 +273,3 @@ def test_spawn_flush_does_nothing_without_a_spool(isolated_env):
with patch.object(telemetry.subprocess, "Popen") as popen:
assert telemetry.spawn_flush() is True
popen.assert_called_once()
-
-
-def test_salt_is_stable_across_processes(isolated_env):
- """Hooks are separate short-lived processes; one repo must hash one way.
-
- An unlocked read-modify-write let each process mint its own salt, so a
- repository hashed several ways in the window before one writer won.
- """
- import subprocess as sp
-
- core = str(Path(__file__).resolve().parents[1] / "core")
- script = (
- f"import sys; sys.path.insert(0, {core!r})\n"
- "import telemetry\n"
- "print(telemetry._install_salt())"
- )
- env = {**os.environ, "MEM0_CODE_DATA_DIR": str(memory_core.data_dir())}
- salts = {
- sp.run([sys.executable, "-c", script], capture_output=True, text=True, env=env).stdout.strip()
- for _ in range(4)
- }
- assert len(salts) == 1, f"one repo hashed {len(salts)} ways: {salts}"
-
-
-def test_salt_does_not_touch_the_identity_file(isolated_env):
- """The identity file is is_first_run's marker and the sender's email store.
-
- Writing the salt into it would create it from record(), suppressing the
- install event, and would race resolve_distinct_id, which holds a stale copy
- of that dict across a network call.
- """
- telemetry._install_salt()
- assert not telemetry._identity_path().exists()
-
-
-def test_no_salt_means_no_hash_rather_than_an_unsalted_one(isolated_env, monkeypatch):
- """A read-only data dir drops the property; it must not emit a weak digest.
-
- The previous fallback was a digest of the salt file's own path, which an
- attacker can compute, memoized for the whole process. A property named
- repo_hash carrying an effectively unsalted digest is worse than no property:
- it reads as protected and is not.
- """
- telemetry._salt_cache = ""
- monkeypatch.setattr(telemetry.os, "open", lambda *a, **k: (_ for _ in ()).throw(OSError("read-only")))
-
- assert telemetry._install_salt() == ""
- assert telemetry._scoped_digest("git@github.com:acme/secret.git") == ""
-
-
-def test_a_half_written_salt_is_never_visible_to_another_process(isolated_env, monkeypatch):
- """The window this closes: file created, value not yet written.
-
- O_CREAT|O_EXCL then write leaves the name present and empty in between. A
- hook reading it there used to get "", fall back to the path digest and cache
- that for its whole run, so the same repo hashed two ways depending on timing.
- Publishing by link means the name either does not exist or is complete.
- """
- telemetry._salt_cache = ""
- salt_path = telemetry._salt_path()
- observed = []
-
- real_link = telemetry.os.link
-
- def observing_link(source, target):
- # Stand where the racing reader stands: after the temp file is written,
- # before the real name exists.
- observed.append(salt_path.exists())
- return real_link(source, target)
-
- monkeypatch.setattr(telemetry.os, "link", observing_link)
- salt = telemetry._install_salt()
-
- assert observed == [False], "the salt name existed before it held a value"
- assert len(salt) == 32
- assert salt_path.read_text(encoding="utf-8").strip() == salt
-
-
-def test_a_filesystem_without_hardlinks_still_gets_a_salt(isolated_env, monkeypatch):
- """Publishing by link must not become a silent loss of the hashes.
-
- Some network mounts and container volumes reject os.link. Returning ""
- there would drop repo_hash and session_hash on every run for that whole
- cohort, which is a bigger loss than the narrow race the link closes.
- """
- telemetry._salt_cache = ""
- monkeypatch.setattr(
- telemetry.os, "link", lambda src, dst: (_ for _ in ()).throw(OSError(38, "not implemented"))
- )
-
- salt = telemetry._install_salt()
-
- assert len(salt) == 32, "no salt on a filesystem without hardlinks"
- assert telemetry._salt_path().read_text(encoding="utf-8").strip() == salt
- assert telemetry._scoped_digest("git@github.com:acme/x.git") != ""
- assert not list(telemetry._salt_path().parent.glob("telemetry-salt.*.tmp"))
-
-
-def test_a_concurrent_writer_does_not_clobber_the_published_salt(isolated_env):
- """Second process to finish must adopt the first one's salt, not replace it.
-
- os.link rather than os.replace is what makes losing the race harmless.
- """
- telemetry._salt_cache = ""
- first = telemetry._install_salt()
-
- telemetry._salt_cache = ""
- second = telemetry._install_salt()
-
- assert second == first
- assert not list(telemetry._salt_path().parent.glob("telemetry-salt.*.tmp")), "temp file left behind"
diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json
index e91eca25a..916b72e66 100644
--- a/integrations/codex-plugin/.codex-plugin/plugin.json
+++ b/integrations/codex-plugin/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mem0",
- "version": "0.3.3",
+ "version": "0.3.1",
"description": "Cross-session memory and token savings for coding agents.",
"author": { "name": "Mem0", "email": "support@mem0.ai" },
"homepage": "https://docs.mem0.ai/integrations/codex",
diff --git a/integrations/codex-plugin/core/_harness_id.py b/integrations/codex-plugin/core/_harness_id.py
deleted file mode 100644
index 47938ee08..000000000
--- a/integrations/codex-plugin/core/_harness_id.py
+++ /dev/null
@@ -1,11 +0,0 @@
-"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""
-
-HARNESS_ID = "codex"
-SOURCE_TAG = "CODEX_PLUGIN"
-
-# Platform-side vocabulary (mem0_event.source + X-Application). The whole
-# plugin family is one source; which editor it runs in is the application.
-# An empty application means the host is unknown, and memory_core omits
-# the header entirely rather than sending a placeholder.
-PLATFORM_SOURCE = "MEM0_PLUGIN"
-PLATFORM_APPLICATION = "codex"
diff --git a/integrations/codex-plugin/core/hook_runner.py b/integrations/codex-plugin/core/hook_runner.py
index b3d8a3210..2a2adb557 100644
--- a/integrations/codex-plugin/core/hook_runner.py
+++ b/integrations/codex-plugin/core/hook_runner.py
@@ -290,11 +290,6 @@ def run(
if args.plugin_data_dir:
os.environ[data_dir_env] = args.plugin_data_dir
- # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key
- # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking
- # after them always saw content and every fresh install reported an upgrade.
- data_dir_was_empty = telemetry.data_dir_was_empty()
-
cache_plugin_api_key()
if args.action == "session-start":
clear_stale_api_key_cache()
@@ -310,19 +305,8 @@ def run(
return 0
if args.action == "session-start":
- # Claims the marker atomically and says which event to record, so a
- # second session starting alongside this one cannot record it too.
- first_event = telemetry.claim_install(was_empty=data_dir_was_empty)
- if first_event == "install":
+ if telemetry.is_first_run():
telemetry.record("install")
- elif first_event == "upgrade":
- # First run after a build that never wrote the marker; the
- # predecessor version was never recorded anywhere.
- telemetry.record("upgrade", from_version="pre-0.3")
- else:
- previous = telemetry.claim_version_change()
- if previous:
- telemetry.record("upgrade", from_version=previous)
recovered = recover_pending_handoffs()
record_session_start(store, hook_input)
if recovered:
diff --git a/integrations/codex-plugin/core/mcp_server.py b/integrations/codex-plugin/core/mcp_server.py
index a0b73cb79..036fbbdc9 100644
--- a/integrations/codex-plugin/core/mcp_server.py
+++ b/integrations/codex-plugin/core/mcp_server.py
@@ -21,9 +21,16 @@ from memory_core import (
PROTOCOL_VERSION = "2024-11-05"
TOOL_NAME = "search_memories"
TOOL_DESCRIPTION = (
- "Search memories from earlier work in this repository. Use it before "
- "repeating investigation or when earlier decisions, fixes, commands, or "
- "results may help."
+ "Search memories from earlier work in this repository. ALWAYS call this "
+ "tool before answering anything that could depend on prior context: the "
+ "user's preferences, facts about this codebase, history, people, projects, "
+ "or earlier decisions. Do not rely on the chat window alone. The "
+ "repository's memory is shared by everyone who works in it and includes "
+ "what it took to run, test, or build here, so search before assuming an "
+ "invocation works. The scope argument changes what is searched: 'repo' "
+ "(default) is the whole repository's shared memory plus your own "
+ "preferences, 'dir' narrows the shared part to the directory you are "
+ "working in, and 'mine' is your preferences alone."
)
TOOL_SCHEMA = {
"type": "object",
diff --git a/integrations/codex-plugin/core/memory_core.py b/integrations/codex-plugin/core/memory_core.py
index 9b420a063..77d7a2b80 100644
--- a/integrations/codex-plugin/core/memory_core.py
+++ b/integrations/codex-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.3"
+PLUGIN_VERSION = "0.3.1"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
@@ -71,13 +71,15 @@ MAX_FLUSH_ATTEMPTS = 5
FORGET_PAGE_SIZE = 100
FORGET_MAX_PAGES = 50
-PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work.
+PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository.
A completed change should produce one memory explaining the resulting behavior, where it is implemented when useful, and any important constraints or reasoning. Exploration or accepted decisions may produce separate memories only when they are independently useful.
-Use the coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+A command that failed and was then made to work should produce one memory naming the failing invocation, the error it returned, and the invocation that succeeded. Do not save one-off errors caused by an edit still in progress, transient network failures, or anything a rerun would fix on its own.
-Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state.
+Use the current coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+
+Write about the repository, not the user, assistant, session, or task. Do not save personal preferences. Do not save a memory that only states which repository, branch, or directory the session worked in. Do not include test results, documentation updates, release notes, or temporary state.
If nothing useful was established, return no memories."""
@@ -1798,34 +1800,6 @@ def extraction_message_batches(
return batches
-# Platform surface attribution. Read from the generated per-host module so a new
-# entrypoint is correct without remembering to configure anything.
-try: # pragma: no cover - absent only in the un-built shared source tree
- from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
- from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
-except ImportError:
- _PLATFORM_SOURCE = "MEM0_PLUGIN"
- _PLATFORM_APPLICATION = ""
-
-
-def platform_headers(key: str) -> dict[str, str]:
- """Auth plus the three surface-identity headers.
-
- X-Mem0-Source and X-Application are set-once by contract: this is the
- outermost layer, so it sets them, and nothing below may overwrite them.
- X-Mem0-Client is append-only โ anything downstream adds itself to the tail.
- """
- headers = {
- "Authorization": f"Token {key}",
- "Content-Type": "application/json",
- "X-Mem0-Source": _PLATFORM_SOURCE,
- "X-Mem0-Client": f"mem0-plugin/{PLUGIN_VERSION}",
- }
- if _PLATFORM_APPLICATION:
- headers["X-Application"] = _PLATFORM_APPLICATION
- return headers
-
-
def _request_json(
url: str, key: str, payload: dict[str, Any], timeout: float
) -> tuple[dict[str, Any] | list[Any], int, int]:
@@ -1833,7 +1807,7 @@ def _request_json(
request = urllib.request.Request(
url,
data=raw,
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -1860,7 +1834,7 @@ def _get_json(
) -> tuple[dict[str, Any] | list[Any], int]:
request = urllib.request.Request(
url,
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="GET",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -2006,13 +1980,6 @@ def flush_session(
"user_id": write_user,
"app_id": repo.app_id,
"run_id": session_id,
- # Top level, not metadata: the backend reads `source` from the body or
- # the query string, never from metadata, which is where this used to
- # sit. The X-Mem0-Source header is also read, but only from the
- # platform release that ships alongside this change, so the body value
- # is what makes attribution work on both. The harness tag stays in
- # metadata as hook provenance.
- "source": _PLATFORM_SOURCE,
"metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)},
"agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS,
"custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS,
@@ -2556,7 +2523,7 @@ def _collect_memory_ids(
def _delete_memory(api_url: str, key: str, memory_id: str) -> bool:
request = urllib.request.Request(
f"{api_url}/v1/memories/{urllib.parse.quote(memory_id)}/",
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="DELETE",
)
try:
diff --git a/integrations/codex-plugin/core/telemetry.py b/integrations/codex-plugin/core/telemetry.py
index c1fc0084c..249595475 100644
--- a/integrations/codex-plugin/core/telemetry.py
+++ b/integrations/codex-plugin/core/telemetry.py
@@ -1,9 +1,5 @@
#!/usr/bin/env python3
-"""Usage telemetry for Mem0 agent plugins.
-
-Events are linked to your Mem0 account email when an API key is configured, and
-to a random per-machine id otherwise. Not anonymous โ the Python SDK and CLI
-attribute the same way.
+"""Anonymous usage telemetry for Mem0 agent plugins.
Hooks run on a 3-6 second budget and fire on every tool call, so recording never
touches the network: `record` appends one JSON line to a local spool and returns.
@@ -13,8 +9,7 @@ started once per session and again from the flush worker that is already detache
Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false.
Never sends prompts, memory text, queries, file paths, repository names, or API
-keys: only event names, durations, counts, coarse outcomes, and repo/session
-identifiers hashed with a random per-install salt.
+keys: only event names, durations, counts, coarse outcomes, and salted hashes.
"""
from __future__ import annotations
@@ -34,24 +29,8 @@ from typing import Any
import memory_core
-# Seeded from the per-host module the build generates into core/. Two processes
-# in this pipeline never call init() โ mcp_server.py, and the detached
-# `python3 telemetry.py` sender that spawn_flush() starts โ so a module default
-# was what every one of their events got labelled with.
-try: # pragma: no cover - absent only in the un-built shared source tree
- from _harness_id import HARNESS_ID as _DEFAULT_HARNESS
- from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
- from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
- from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG
-except ImportError:
- _DEFAULT_HARNESS = "generic"
- _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN"
- _PLATFORM_SOURCE = "MEM0_PLUGIN"
- _PLATFORM_APPLICATION = ""
-
-_salt_cache: str = ""
-_harness: str = _DEFAULT_HARNESS
-_source_tag: str = _DEFAULT_SOURCE_TAG
+_harness: str = "generic"
+_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
"apikey",
"authorization",
@@ -77,19 +56,10 @@ _PRIVATE_KEYS = {
}
-def init(harness: str = "", source_tag: str = "") -> None:
- """Override the generated identity. Optional โ core/_harness_id.py is the default.
-
- The fallback shape matches memory_core.configure_harness's (``_PLUGIN``).
- It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which
- meant one plugin could emit three different source values depending on which
- process happened to send the batch.
- """
+def init(harness: str = "generic", source_tag: str = "") -> None:
global _harness, _source_tag
- _harness = harness or _DEFAULT_HARNESS
- _source_tag = source_tag or (
- f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG
- )
+ _harness = harness
+ _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/"
@@ -100,16 +70,6 @@ BATCH_SIZE = 100
SEND_TIMEOUT = 5
CLAIM_STALE_SECONDS = 120
CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60
-# A batch is only discarded once it has genuinely been retried this many times.
-MAX_CLAIM_ATTEMPTS = 3
-# Parked claims drained per run, after the live spool. Bounded so a long backlog
-# cannot turn one flush into an unbounded send loop.
-MAX_PARKED_PER_RUN = 3
-# Added to the wait before a released claim becomes reclaimable, per attempt
-# already spent. Releasing straight to "reclaimable now" let two senders burn the
-# whole budget within seconds of one another on a single momentary failure, and
-# discard a batch a retry a minute later would have delivered.
-RETRY_COOLDOWN_SECONDS = 60
def is_enabled() -> bool:
@@ -123,126 +83,9 @@ def is_enabled() -> bool:
def _digest(value: str, length: int = 16) -> str:
- """Unsalted digest. Only for values that are already secrets (API keys)."""
return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length]
-def _salt_path() -> Path:
- return memory_core.data_dir() / "telemetry-salt"
-
-
-def _install_salt() -> str:
- """Random per-install salt, created once and memoized for the process.
-
- Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in
- the identity file. Three reasons, all of which produced wrong data when this
- lived in the identity dict:
-
- - Hooks are short-lived separate processes firing on every tool call, and
- people run more than one agent window. A read-modify-write would let each
- process mint its own salt, so one repository would hash several ways in the
- window before a writer won.
- - resolve_distinct_id holds a copy of the identity dict across a network call
- to /v1/ping/, so whichever write landed second erased the other's key โ
- losing either the salt (repo_hash changes mid-stream) or the email (a
- second $identify, splitting the person).
- - Touching the identity file from record() would create it, and is_first_run
- keys off that file, so recording an event would silently suppress the
- install event.
-
- Published atomically, and there is deliberately no derived fallback. Creating
- the file with O_CREAT|O_EXCL and then writing into it leaves a window where
- the file exists and is empty, and a concurrent hook that reads it in that
- window gets nothing. Falling back to a digest of the path would hand that
- process a salt an attacker can compute, memoized for its whole run, which is
- the privacy control this function exists to provide silently turning itself
- off under load. The salt is written to a private temp file first and linked
- into place, so the name either does not exist or already has the full value.
-
- Returns "" when it genuinely cannot persist. Callers omit the hash entirely
- rather than emit an unsalted one.
- """
- global _salt_cache
- if _salt_cache:
- return _salt_cache
-
- path = _salt_path()
- # Read before writing. Hooks are separate processes firing on every tool
- # call, so all but the first find the salt already published; going straight
- # to create-fsync-link-unlink meant every one of them paid an fsync to
- # discover that, on a path whose whole promise is appending a line and
- # returning.
- try:
- _salt_cache = path.read_text(encoding="utf-8").strip()
- if _salt_cache:
- return _salt_cache
- except OSError:
- pass
-
- temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(handle, "w", encoding="utf-8") as stream:
- stream.write(uuid.uuid4().hex)
- stream.flush()
- os.fsync(stream.fileno())
- try:
- # Atomic claim: fails if another process already published one.
- # os.link rather than replace, which would clobber theirs.
- os.link(temporary, path)
- except FileExistsError:
- pass
- except OSError:
- # No hardlinks here (some network mounts, some container volumes).
- # Claim the name directly instead. That reopens the empty-file
- # window, but the window is now benign: a reader that lands in it
- # gets "" and omits the hash for that process rather than caching a
- # guessable one. Losing the hashes on every run of an entire
- # filesystem is the worse failure.
- try:
- fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(fallback, "w", encoding="utf-8") as stream:
- stream.write(temporary.read_text(encoding="utf-8"))
- except OSError:
- pass
- except OSError:
- pass
- finally:
- try:
- temporary.unlink()
- except OSError:
- pass
-
- try:
- _salt_cache = path.read_text(encoding="utf-8").strip()
- except OSError:
- _salt_cache = ""
- return _salt_cache
-
-
-def _scoped_digest(value: str, length: int = 16) -> str:
- """Salted digest for values drawn from a guessable space.
-
- repo.identity is a git remote URL, or ``local:`` when there is
- no remote โ which normally contains the account username. Sixteen unsalted
- hex characters over that input space is enumerable, so this is not a
- privacy control without the salt. Salting per install keeps every
- within-account join the analytics actually use and gives up only
- cross-machine joins on the same repository, which nothing computes.
-
- Returns "" when there is no salt, so record() omits the property. An
- unsalted digest over this input space is close to plaintext, and emitting one
- under a name that implies it is hashed is worse than sending nothing.
- """
- if not value:
- return ""
- salt = _install_salt()
- if not salt:
- return ""
- return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length]
-
-
def _safe_value(value: Any) -> Any:
if isinstance(value, str):
return memory_core.redact(value)
@@ -302,176 +145,9 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str:
return created
-def _rotate_anonymous_id(identity: dict[str, str]) -> str:
- """Mint a fresh anonymous id because the account context is gone.
-
- The previous id may already have been merged into a person profile by an
- $identify, and that merge is permanent. Reusing it after a logout or a key
- change attributes everything that follows to the account that just went
- away, which is the same misattribution the key fingerprint exists to stop,
- only arriving through the anonymous path instead.
-
- `aliased` is cleared with it: the new id has never been merged, so it is
- eligible to be aliased into whatever account comes next.
- """
- created = f"code-anon-{uuid.uuid4().hex}"
- identity["anonymous_id"] = created
- identity.pop("aliased", None)
- _write_identity(identity)
- return created
-
-
-def _install_state_path() -> Path:
- return memory_core.data_dir() / "install-state.json"
-
-
def is_first_run() -> bool:
- """Whether install has never been recorded on this machine.
-
- Deliberately NOT the identity file. That file is only written by a
- successful flush, so an offline or firewalled user recorded code.install on
- every single session, forever โ and every 0.2.x user recorded one on their
- first 0.3.x session because 0.2.x never wrote it at all.
- """
- return not _install_state_path().exists()
-
-
-def data_dir_was_empty() -> bool:
- """Whether the data directory is untouched. Call BEFORE anything writes to it.
-
- hook_runner reaches claim_install() only after cache_plugin_api_key() has
- written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so
- asking at claim time always saw content and every fresh install reported an
- upgrade. The caller snapshots this at the top of the run instead.
- """
- return not _data_dir_has_content()
-
-
-def claim_install(was_empty: bool | None = None) -> str | None:
- """Claim the one install/upgrade record for this machine, atomically.
-
- Returns the event to record ("install" or "upgrade"), or None if another
- session already claimed it. O_CREAT|O_EXCL so two sessions starting together
- cannot both win.
-
- `was_empty` must come from data_dir_was_empty() called before this process
- wrote anything. Omitting it falls back to checking now, which is only
- correct for a caller that has touched nothing.
- """
- if not is_enabled():
- # Never consume the one-shot claim while the user is opted out, or they
- # would silently lose their install event if they later opt in.
- return None
-
- path = _install_state_path()
- upgrading = not (data_dir_was_empty() if was_empty is None else was_empty)
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- except FileExistsError:
- return None
- except OSError:
- return None
- try:
- with os.fdopen(handle, "w", encoding="utf-8") as stream:
- json.dump(
- {
- "plugin_version": memory_core.PLUGIN_VERSION,
- "installed_at": memory_core.utc_now(),
- "upgraded": upgrading,
- },
- stream,
- )
- # Durable before this returns. The O_EXCL open is what makes the
- # claim exclusive, so it cannot be replaced by a temp-and-rename
- # without losing that, which leaves the content as the thing to make
- # safe. A kill between the open and this fsync used to leave a marker
- # that exists but parses to nothing: is_first_run reads it as claimed
- # and claim_version_change cannot read a version out of it.
- stream.flush()
- os.fsync(stream.fileno())
- except OSError:
- pass
- return "upgrade" if upgrading else "install"
-
-
-def _data_dir_has_content() -> bool:
- """Whether anything predates this session in the plugin data directory."""
- try:
- for entry in memory_core.data_dir().iterdir():
- if entry.name != "install-state.json":
- return True
- except OSError:
- pass
- return False
-
-
-def _repair_install_state(path: Path) -> None:
- """Rewrite an unparseable marker so version tracking can resume."""
- try:
- temporary = path.with_suffix(f".{os.getpid()}.tmp")
- temporary.write_text(
- json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}),
- encoding="utf-8",
- )
- temporary.replace(path)
- except OSError:
- pass
-
-
-def claim_version_change() -> str | None:
- """Return the previously recorded version if it differs, updating the marker.
-
- Only meaningful once the marker exists โ the first transition into 0.3.x has
- no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting
- the marker means the next session sees no change and records nothing.
- """
- path = _install_state_path()
- try:
- state = json.loads(path.read_text(encoding="utf-8"))
- except OSError:
- return None
- except json.JSONDecodeError:
- # A crash between O_EXCL and the write leaves an empty marker. Left
- # alone it disables every future upgrade event on this machine, because
- # claim_install sees the file and this function cannot parse it.
- state = None
- if not isinstance(state, dict):
- _repair_install_state(path)
- return None
- previous = str(state.get("plugin_version") or "")
- if not previous or previous == memory_core.PLUGIN_VERSION:
- return None
- # Claim the transition with an exclusive sentinel before rewriting the
- # marker. A plain read-modify-write let every concurrently starting session
- # observe the old version and each record its own upgrade โ and the first
- # session after a version bump is exactly when several agent windows restart
- # together.
- sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}")
- try:
- os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
- except FileExistsError:
- return None
- except OSError:
- return None
-
- state["plugin_version"] = memory_core.PLUGIN_VERSION
- state["upgraded_at"] = memory_core.utc_now()
- temporary = path.with_suffix(f".{os.getpid()}.tmp")
- try:
- temporary.write_text(json.dumps(state), encoding="utf-8")
- temporary.replace(path)
- except OSError:
- # Release the claim. The marker still records the old version, so
- # without this the sentinel makes claim_version_change return early on
- # every later run and this version's upgrade is never recorded again.
- for leftover in (sentinel, temporary):
- try:
- leftover.unlink()
- except OSError:
- pass
- return None
- return previous
+ """Whether this machine has never recorded a plugin event before."""
+ return not _identity_path().exists()
def record(
@@ -492,32 +168,19 @@ def record(
except OSError:
pass
properties = _safe_value(properties)
- # Stamped in the RECORDING process, beside harness. `source` used to be
- # read in the sending process from a module global, so whichever process
- # drained the spool named every event in it. flush() spreads per-event
- # properties last, so this now wins over any sender's default.
properties.update(
harness=_harness,
- source=_source_tag,
plugin_version=memory_core.PLUGIN_VERSION,
os=sys.platform,
python_version=platform.python_version(),
)
- # Assigned only when the digest is real. _scoped_digest returns "" when
- # the salt could not be persisted, and an empty property is worse than an
- # absent one: it survives the None filter below and reads as a value.
if repo is not None:
- repo_hash = _scoped_digest(getattr(repo, "identity", ""))
- if repo_hash:
- properties["repo_hash"] = repo_hash
+ properties["repo_hash"] = _digest(getattr(repo, "identity", ""))
if session_id:
- session_hash = _scoped_digest(session_id)
- if session_hash:
- properties["session_hash"] = session_hash
+ properties["session_hash"] = _digest(session_id)
line = json.dumps(
{
"event": f"{EVENT_PREFIX}.{event}",
- "uuid": str(uuid.uuid4()),
"timestamp": memory_core.utc_now(),
"properties": {
key: value for key, value in properties.items() if value is not None
@@ -576,201 +239,38 @@ def spawn_flush() -> bool:
return False
-def _claim_name(attempt: int = 0) -> str:
- """Claim filename. The attempt count rides in the name so the 7-day expiry
- only ever discards a batch that was actually retried and failed."""
- return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending"
-
-
-def _claim_attempt(claim: Path) -> int:
- """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape.
-
- Anchored on field position, not on a leading "a": the legacy shape is
- ``telemetry--.sending`` and a hex id such as ``a1234567`` would
- otherwise parse as attempt 1234567 and be discarded unsent on the first
- flush after an upgrade.
- """
- stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name
- parts = stem.split("-")
- if len(parts) != 4:
- return 0
- tail = parts[3]
- if tail.startswith("a") and tail[1:].isdigit():
- return int(tail[1:])
- return 0
-
-
-def _touch(path: Path) -> None:
- """Refresh mtime so a claim's age measures time since it was claimed.
-
- ``Path.replace`` is ``os.rename``, which preserves mtime โ so a claim created
- after a quiet minute inherited the spool's last-write time and looked
- abandoned the instant it was made. A second sender would then take it over
- while the first was still posting, and both would deliver the batch.
- """
- try:
- os.utime(path, None)
- except OSError:
- pass
-
-
def _claim_spool() -> Path | None:
"""Rename the spool aside so exactly one sender owns each batch."""
directory = memory_core.data_dir()
- claim = directory / _claim_name()
+ claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending"
spool = _spool_path()
try:
spool.replace(claim)
- _touch(claim)
return claim
except OSError:
pass
- return _claim_parked(directory)
-
-
-def _sweep_debris(directory: Path) -> None:
- """Remove files nothing else will ever pick up again.
-
- *.partial is a temp file orphaned by a crash between write and rename.
- *.corrupt is a batch quarantined for undecodable content. No glob in this
- module matches either, so without this they accumulate on disk for the life
- of the install.
-
- Quarantined batches are kept far longer than debris: they are the only
- evidence left of events that could not be delivered, and someone diagnosing
- a report of missing telemetry has to be able to find one.
- """
now = time.time()
- for debris in directory.glob("telemetry-*.partial"):
- try:
- if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS:
- debris.unlink()
- except OSError:
- continue
- for quarantined in directory.glob("telemetry-*.corrupt"):
- try:
- if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS:
- quarantined.unlink()
- except OSError:
- continue
- # The same reasoning covers *.tmp. _write_identity and _install_salt both
- # create one and unlink it in a finally, which a SIGKILL skips, and no glob
- # in this module matches the leftovers either.
- for temporary in directory.glob("telemetry-*.tmp"):
- try:
- if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS:
- temporary.unlink()
- except OSError:
- continue
-
-
-def _claim_parked(directory: Path) -> Path | None:
- """Take the oldest abandoned claim, if any lease has actually expired.
-
- Kept separate from the live spool so flush() can drain both in one run.
- Previously parked batches were only reachable when no spool existed at all,
- and because sessions keep recording there usually was one โ so a batch
- parked by a failed send waited until the 7-day expiry deleted it unsent,
- even though its own presence is what started the sender.
- """
- now = time.time()
- for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime):
+ for orphan in sorted(directory.glob("telemetry-*.sending")):
try:
age = now - orphan.stat().st_mtime
except OSError:
continue
- if age < CLAIM_STALE_SECONDS:
- # Someone else holds a live lease on it. This check has to come
- # first. Claiming a file bumps its attempt count and refreshes its
- # mtime, so a sender that has just taken the final attempt looks
- # exhausted to everyone else while it is actively draining. Judging
- # exhaustion before liveness let a second sender unlink a batch out
- # from under its owner, losing every event in it.
- continue
- # Attempts, not age. Every re-claim touches the mtime and every release
- # backdates it by a fixed amount, so age is pinned near the stale
- # threshold and never reaches the expiry. Age stays only as a backstop
- # for files that never carried an attempt marker.
- if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS:
+ if age > CLAIM_EXPIRY_SECONDS:
try:
orphan.unlink()
except OSError:
pass
continue
- claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1)
+ if age < CLAIM_STALE_SECONDS:
+ continue
try:
orphan.replace(claim)
- _touch(claim)
return claim
except OSError:
continue
return None
-def _safe_mtime(path: Path) -> float:
- try:
- return path.stat().st_mtime
- except OSError:
- return 0.0
-
-
-def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool:
- """Persist the unsent remainder, atomically, and refresh the lease.
-
- Called after every successful batch. Two jobs: a retry resumes where the
- send stopped instead of re-posting from the top, and the rewrite doubles as
- the lease heartbeat, so a slow sender does not have its claim stolen
- mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS.
- """
- if not remaining:
- try:
- claim.unlink()
- except OSError:
- pass
- return True
- temporary = claim.with_suffix(f".{os.getpid()}.partial")
- try:
- payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining)
- # fsync before the rename: without it the rename can land while the
- # bytes have not, and the claim comes back empty or truncated after a
- # crash. _drain then reads zero events and unlinks it.
- with open(temporary, "w", encoding="utf-8") as handle:
- handle.write(payload)
- handle.flush()
- os.fsync(handle.fileno())
- temporary.replace(claim)
- _touch(claim)
- return True
- except OSError:
- try:
- temporary.unlink()
- except OSError:
- pass
- return False
-
-
-def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None:
- """Persist the remainder and drop the lease, because this sender has given up.
-
- Distinct from the per-batch heartbeat: heartbeating on the way out would
- make an abandoned batch look actively owned for a further
- CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the
- threshold lets the next flush pick it up immediately, while the attempt
- count in the filename still bounds how many times that can happen.
- """
- if not _rewrite_claim(claim, remaining):
- return
- try:
- # Backdate past the stale threshold so the next flush can pick it up,
- # minus a cooldown that grows with the attempts already spent. Clamped so
- # the mtime never lands in the future, which would read as a live lease.
- cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS)
- released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown
- os.utime(claim, (released, released))
- except OSError:
- pass
-
-
def _resolve_email(key: str) -> str:
"""Trade the API key for the account email so events join other Mem0 surfaces."""
url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/"
@@ -800,130 +300,34 @@ def _post(payload: dict[str, Any], url: str) -> bool:
def resolve_distinct_id() -> tuple[str, str]:
- """Return the PostHog distinct id and the anonymous id it replaced, if any.
-
- The second value becomes a PostHog $identify alias. It is ONLY ever an
- anonymous id: aliasing one account email to another merges two real person
- profiles and cannot be undone, so a key that now belongs to a different
- account re-resolves with no alias.
- """
+ """Return the PostHog distinct id and the anonymous id it replaced, if any."""
identity = _read_identity()
- key = memory_core.api_key()
- fingerprint = _digest(key) if key else ""
email = identity.get("email", "")
-
- if email and fingerprint:
- recorded = identity.get("key_fingerprint", "")
- if recorded == fingerprint:
- return email, ""
- if not recorded:
- # Rows written before fingerprints existed. Verify rather than
- # adopt: a key changed before the upgrade would otherwise bind the
- # new key to the previous account's email, permanently, and the
- # fingerprint would then agree with itself forever after.
- verified = _resolve_email(key)
- if not verified:
- # Offline, firewalled, or the API is down. Keep the previous
- # behaviour and retry on the next flush rather than dropping a
- # real account attribution. Safe because the same network that
- # failed /v1/ping/ is about to fail the PostHog POST, so nothing
- # is delivered under the unverified identity in the meantime.
- return email, ""
- identity["email"] = verified
- identity["key_fingerprint"] = fingerprint
- _write_identity(identity)
- return verified, ""
-
+ if email:
+ return email, ""
+ key = memory_core.api_key()
if not key:
- # No key to verify the account with; do not keep attributing to it.
- if email:
- identity.pop("email", None)
- identity.pop("key_fingerprint", None)
- return _rotate_anonymous_id(identity), ""
return anonymous_id(identity), ""
-
- resolved = _resolve_email(key)
- if not resolved:
- # The key changed and will not resolve (revoked, offline, API down).
- # Reaching here with an email means the recorded fingerprint disagreed,
- # so the key really did change. Drop the account and rotate: the stored
- # anonymous id may already be merged into that account's person, and
- # reusing it would keep the events on the profile we are trying to
- # leave.
- if email:
- identity.pop("email", None)
- identity.pop("key_fingerprint", None)
- return _rotate_anonymous_id(identity), ""
+ email = _resolve_email(key)
+ if not email:
return anonymous_id(identity), ""
-
- # Alias only when going anonymous -> email for the first time. Once an anon
- # id has been merged into an account it must never be offered again: an
- # alias naming an already-identified id is what could link two real people.
- previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "")
- if previous:
- identity["aliased"] = True
- identity["email"] = resolved
- identity["key_fingerprint"] = fingerprint
+ previous = identity.get("anonymous_id", "")
+ identity["email"] = email
_write_identity(identity)
- return resolved, previous
+ return email, previous
def flush() -> int:
- """Drain the live spool, then any parked claims, and return events sent."""
+ """Drain claimed spools to PostHog and return the number of events sent."""
if not is_enabled():
return 0
- sent, delivered = _drain(_claim_spool())
- if not delivered:
- # The network is failing. Retrying other batches now would only burn
- # their attempt budget against the same broken connection.
- return sent
-
- # Parked batches used to starve behind the live spool indefinitely. Bounded
- # per run so a long backlog cannot turn one flush into an unbounded loop.
- directory = memory_core.data_dir()
- _sweep_debris(directory)
- for _ in range(MAX_PARKED_PER_RUN):
- parked = _claim_parked(directory)
- if parked is None:
- break
- count, delivered = _drain(parked)
- sent += count
- if not delivered:
- break
- return sent
-
-
-def _drain(claim: Path | None) -> tuple[int, bool]:
- """Post one claimed batch file, recording progress after every batch.
-
- Returns (events sent, whether everything was delivered).
- """
+ claim = _claim_spool()
if claim is None:
- return 0, True
+ return 0
try:
lines = claim.read_text(encoding="utf-8").splitlines()
- except ValueError:
- # UnicodeDecodeError from a torn write: the content is unrecoverable, so
- # quarantine rather than retry. flush() runs from a bare `finally:` in
- # flush_worker, so raising here also skips the handoff cleanup, and an
- # undecodable file would otherwise be re-read on every flush forever.
- # Reported as delivered because there is nothing left to deliver and the
- # rest of the run should continue.
- try:
- claim.replace(claim.with_suffix(".corrupt"))
- except OSError:
- try:
- claim.unlink()
- except OSError:
- pass
- return 0, True
except OSError:
- # Could not read it, which is not the same as having nothing to send.
- # The file is left exactly where it is: a vanished or briefly unreadable
- # claim is retryable, and quarantining it here would discard events over
- # a transient filesystem error. Reported as undelivered so the run stops
- # instead of counting a batch nothing was posted from as delivered.
- return 0, False
+ return 0
events = []
for line in lines:
try:
@@ -933,18 +337,11 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
if isinstance(value, dict) and value.get("event"):
events.append(value)
if not events:
- # Only delete when the file really is empty. A non-empty file that
- # parses to nothing is a torn write, and its contents are the unsent
- # remainder โ deleting it is the data loss this PR exists to prevent.
try:
- empty = claim.stat().st_size == 0
- except OSError:
- empty = True
- try:
- claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink()
+ claim.unlink()
except OSError:
pass
- return 0, True
+ return 0
distinct_id, aliased_anonymous_id = resolve_distinct_id()
if aliased_anonymous_id:
@@ -963,17 +360,12 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
sent = 0
for start in range(0, len(events), BATCH_SIZE):
- chunk = events[start : start + BATCH_SIZE]
batch = [
{
"event": event["event"],
"distinct_id": distinct_id,
- # Carried through from record() so a resend can be collapsed.
- "uuid": event.get("uuid"),
"timestamp": event.get("timestamp"),
"properties": {
- # Fallback only: events recorded by a build before source
- # moved into record() have none of their own.
"source": _source_tag,
"language": "python",
"$process_person_profile": False,
@@ -981,24 +373,16 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
**(event.get("properties") or {}),
},
}
- for event in chunk
+ for event in events[start : start + BATCH_SIZE]
]
if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL):
- # Keep only what has not been delivered, and release the lease.
- # Previously the whole file was kept and the retry re-posted every
- # batch, including the ones that had already arrived.
- _release_claim(claim, events[start:])
- return sent, False
- sent += len(chunk)
- # Record progress and refresh the lease after each successful batch, so
- # a crash repeats at most one batch instead of the entire file. If the
- # rewrite fails the claim still holds delivered events, so stop rather
- # than carry on as though progress were recorded โ continuing is how the
- # duplicate delivery this PR fixes would come back.
- if not _rewrite_claim(claim, events[start + len(chunk) :]):
- _release_claim(claim, events[start + len(chunk) :])
- return sent, False
- return sent, True
+ return sent
+ sent += len(batch)
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return sent
def main() -> int:
diff --git a/integrations/codex-plugin/plugin-build.json b/integrations/codex-plugin/plugin-build.json
index a354c31f5..8d4c51c07 100644
--- a/integrations/codex-plugin/plugin-build.json
+++ b/integrations/codex-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.3",
+ "version": "0.3.1",
"homepage": "https://docs.mem0.ai/integrations/codex",
"native": {
"pluginRoot": "${PLUGIN_ROOT}",
diff --git a/integrations/codex-plugin/skills/pause/SKILL.md b/integrations/codex-plugin/skills/pause/SKILL.md
index c8f8ddd5f..d8a52f47b 100644
--- a/integrations/codex-plugin/skills/pause/SKILL.md
+++ b/integrations/codex-plugin/skills/pause/SKILL.md
@@ -7,8 +7,8 @@ disable-model-invocation: true
# Pause memory capture
To pause (hooks stop capturing and sending session content; a minimal
-telemetry ping still fires at session start, under your Mem0 account email,
-unless `MEM0_TELEMETRY=false`):
+anonymous telemetry ping still fires at session start unless
+`MEM0_TELEMETRY=false`):
```bash
python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "codex" --plugin-data-dir "${PLUGIN_DATA}" pause
diff --git a/integrations/codex-plugin/skills/search/SKILL.md b/integrations/codex-plugin/skills/search/SKILL.md
index 90f435008..f6c27b19c 100644
--- a/integrations/codex-plugin/skills/search/SKILL.md
+++ b/integrations/codex-plugin/skills/search/SKILL.md
@@ -12,9 +12,11 @@ Call `search_memories` with the user's question. Treat `--top-k`, `--category`,
query.
Omit `top_k` to use Mem0's configured default. Omit `category` to search every
-category. Omit `scope` to use the configured default, normally `repo`: this
-repository's shared memory, which everyone who works in it contributes to,
-plus your own preferences.
+category; a category is a best-effort label Mem0 assigned when it saved the
+memory, so if a category search misses, repeat it without the category. Omit
+`scope` to use the configured default, normally `repo`: this repository's
+shared memory, which everyone who works in it contributes to, plus your own
+preferences.
Pass `scope` when the question needs something else: `dir` to narrow the
shared memory to the directory you are working in (a package inside a
diff --git a/integrations/cursor-plugin/.cursor-plugin/plugin.json b/integrations/cursor-plugin/.cursor-plugin/plugin.json
index 7c2304f29..e33de76a2 100644
--- a/integrations/cursor-plugin/.cursor-plugin/plugin.json
+++ b/integrations/cursor-plugin/.cursor-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "mem0",
- "version": "0.3.3",
+ "version": "0.3.1",
"description": "Cross-session memory and token savings for coding agents.",
"author": { "name": "Mem0", "email": "support@mem0.ai" },
"homepage": "https://docs.mem0.ai/integrations/cursor",
diff --git a/integrations/cursor-plugin/core/_harness_id.py b/integrations/cursor-plugin/core/_harness_id.py
deleted file mode 100644
index 0e20bf1ff..000000000
--- a/integrations/cursor-plugin/core/_harness_id.py
+++ /dev/null
@@ -1,11 +0,0 @@
-"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""
-
-HARNESS_ID = "cursor"
-SOURCE_TAG = "CURSOR_PLUGIN"
-
-# Platform-side vocabulary (mem0_event.source + X-Application). The whole
-# plugin family is one source; which editor it runs in is the application.
-# An empty application means the host is unknown, and memory_core omits
-# the header entirely rather than sending a placeholder.
-PLATFORM_SOURCE = "MEM0_PLUGIN"
-PLATFORM_APPLICATION = "cursor"
diff --git a/integrations/cursor-plugin/core/hook_runner.py b/integrations/cursor-plugin/core/hook_runner.py
index b3d8a3210..2a2adb557 100644
--- a/integrations/cursor-plugin/core/hook_runner.py
+++ b/integrations/cursor-plugin/core/hook_runner.py
@@ -290,11 +290,6 @@ def run(
if args.plugin_data_dir:
os.environ[data_dir_env] = args.plugin_data_dir
- # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key
- # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking
- # after them always saw content and every fresh install reported an upgrade.
- data_dir_was_empty = telemetry.data_dir_was_empty()
-
cache_plugin_api_key()
if args.action == "session-start":
clear_stale_api_key_cache()
@@ -310,19 +305,8 @@ def run(
return 0
if args.action == "session-start":
- # Claims the marker atomically and says which event to record, so a
- # second session starting alongside this one cannot record it too.
- first_event = telemetry.claim_install(was_empty=data_dir_was_empty)
- if first_event == "install":
+ if telemetry.is_first_run():
telemetry.record("install")
- elif first_event == "upgrade":
- # First run after a build that never wrote the marker; the
- # predecessor version was never recorded anywhere.
- telemetry.record("upgrade", from_version="pre-0.3")
- else:
- previous = telemetry.claim_version_change()
- if previous:
- telemetry.record("upgrade", from_version=previous)
recovered = recover_pending_handoffs()
record_session_start(store, hook_input)
if recovered:
diff --git a/integrations/cursor-plugin/core/mcp_server.py b/integrations/cursor-plugin/core/mcp_server.py
index a0b73cb79..036fbbdc9 100644
--- a/integrations/cursor-plugin/core/mcp_server.py
+++ b/integrations/cursor-plugin/core/mcp_server.py
@@ -21,9 +21,16 @@ from memory_core import (
PROTOCOL_VERSION = "2024-11-05"
TOOL_NAME = "search_memories"
TOOL_DESCRIPTION = (
- "Search memories from earlier work in this repository. Use it before "
- "repeating investigation or when earlier decisions, fixes, commands, or "
- "results may help."
+ "Search memories from earlier work in this repository. ALWAYS call this "
+ "tool before answering anything that could depend on prior context: the "
+ "user's preferences, facts about this codebase, history, people, projects, "
+ "or earlier decisions. Do not rely on the chat window alone. The "
+ "repository's memory is shared by everyone who works in it and includes "
+ "what it took to run, test, or build here, so search before assuming an "
+ "invocation works. The scope argument changes what is searched: 'repo' "
+ "(default) is the whole repository's shared memory plus your own "
+ "preferences, 'dir' narrows the shared part to the directory you are "
+ "working in, and 'mine' is your preferences alone."
)
TOOL_SCHEMA = {
"type": "object",
diff --git a/integrations/cursor-plugin/core/memory_core.py b/integrations/cursor-plugin/core/memory_core.py
index 9b420a063..77d7a2b80 100644
--- a/integrations/cursor-plugin/core/memory_core.py
+++ b/integrations/cursor-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.3"
+PLUGIN_VERSION = "0.3.1"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
@@ -71,13 +71,15 @@ MAX_FLUSH_ATTEMPTS = 5
FORGET_PAGE_SIZE = 100
FORGET_MAX_PAGES = 50
-PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work.
+PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository.
A completed change should produce one memory explaining the resulting behavior, where it is implemented when useful, and any important constraints or reasoning. Exploration or accepted decisions may produce separate memories only when they are independently useful.
-Use the coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+A command that failed and was then made to work should produce one memory naming the failing invocation, the error it returned, and the invocation that succeeded. Do not save one-off errors caused by an edit still in progress, transient network failures, or anything a rerun would fix on its own.
-Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state.
+Use the current coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+
+Write about the repository, not the user, assistant, session, or task. Do not save personal preferences. Do not save a memory that only states which repository, branch, or directory the session worked in. Do not include test results, documentation updates, release notes, or temporary state.
If nothing useful was established, return no memories."""
@@ -1798,34 +1800,6 @@ def extraction_message_batches(
return batches
-# Platform surface attribution. Read from the generated per-host module so a new
-# entrypoint is correct without remembering to configure anything.
-try: # pragma: no cover - absent only in the un-built shared source tree
- from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
- from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
-except ImportError:
- _PLATFORM_SOURCE = "MEM0_PLUGIN"
- _PLATFORM_APPLICATION = ""
-
-
-def platform_headers(key: str) -> dict[str, str]:
- """Auth plus the three surface-identity headers.
-
- X-Mem0-Source and X-Application are set-once by contract: this is the
- outermost layer, so it sets them, and nothing below may overwrite them.
- X-Mem0-Client is append-only โ anything downstream adds itself to the tail.
- """
- headers = {
- "Authorization": f"Token {key}",
- "Content-Type": "application/json",
- "X-Mem0-Source": _PLATFORM_SOURCE,
- "X-Mem0-Client": f"mem0-plugin/{PLUGIN_VERSION}",
- }
- if _PLATFORM_APPLICATION:
- headers["X-Application"] = _PLATFORM_APPLICATION
- return headers
-
-
def _request_json(
url: str, key: str, payload: dict[str, Any], timeout: float
) -> tuple[dict[str, Any] | list[Any], int, int]:
@@ -1833,7 +1807,7 @@ def _request_json(
request = urllib.request.Request(
url,
data=raw,
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -1860,7 +1834,7 @@ def _get_json(
) -> tuple[dict[str, Any] | list[Any], int]:
request = urllib.request.Request(
url,
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="GET",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -2006,13 +1980,6 @@ def flush_session(
"user_id": write_user,
"app_id": repo.app_id,
"run_id": session_id,
- # Top level, not metadata: the backend reads `source` from the body or
- # the query string, never from metadata, which is where this used to
- # sit. The X-Mem0-Source header is also read, but only from the
- # platform release that ships alongside this change, so the body value
- # is what makes attribution work on both. The harness tag stays in
- # metadata as hook provenance.
- "source": _PLATFORM_SOURCE,
"metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)},
"agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS,
"custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS,
@@ -2556,7 +2523,7 @@ def _collect_memory_ids(
def _delete_memory(api_url: str, key: str, memory_id: str) -> bool:
request = urllib.request.Request(
f"{api_url}/v1/memories/{urllib.parse.quote(memory_id)}/",
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="DELETE",
)
try:
diff --git a/integrations/cursor-plugin/core/telemetry.py b/integrations/cursor-plugin/core/telemetry.py
index c1fc0084c..249595475 100644
--- a/integrations/cursor-plugin/core/telemetry.py
+++ b/integrations/cursor-plugin/core/telemetry.py
@@ -1,9 +1,5 @@
#!/usr/bin/env python3
-"""Usage telemetry for Mem0 agent plugins.
-
-Events are linked to your Mem0 account email when an API key is configured, and
-to a random per-machine id otherwise. Not anonymous โ the Python SDK and CLI
-attribute the same way.
+"""Anonymous usage telemetry for Mem0 agent plugins.
Hooks run on a 3-6 second budget and fire on every tool call, so recording never
touches the network: `record` appends one JSON line to a local spool and returns.
@@ -13,8 +9,7 @@ started once per session and again from the flush worker that is already detache
Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false.
Never sends prompts, memory text, queries, file paths, repository names, or API
-keys: only event names, durations, counts, coarse outcomes, and repo/session
-identifiers hashed with a random per-install salt.
+keys: only event names, durations, counts, coarse outcomes, and salted hashes.
"""
from __future__ import annotations
@@ -34,24 +29,8 @@ from typing import Any
import memory_core
-# Seeded from the per-host module the build generates into core/. Two processes
-# in this pipeline never call init() โ mcp_server.py, and the detached
-# `python3 telemetry.py` sender that spawn_flush() starts โ so a module default
-# was what every one of their events got labelled with.
-try: # pragma: no cover - absent only in the un-built shared source tree
- from _harness_id import HARNESS_ID as _DEFAULT_HARNESS
- from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
- from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
- from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG
-except ImportError:
- _DEFAULT_HARNESS = "generic"
- _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN"
- _PLATFORM_SOURCE = "MEM0_PLUGIN"
- _PLATFORM_APPLICATION = ""
-
-_salt_cache: str = ""
-_harness: str = _DEFAULT_HARNESS
-_source_tag: str = _DEFAULT_SOURCE_TAG
+_harness: str = "generic"
+_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
"apikey",
"authorization",
@@ -77,19 +56,10 @@ _PRIVATE_KEYS = {
}
-def init(harness: str = "", source_tag: str = "") -> None:
- """Override the generated identity. Optional โ core/_harness_id.py is the default.
-
- The fallback shape matches memory_core.configure_harness's (``_PLUGIN``).
- It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which
- meant one plugin could emit three different source values depending on which
- process happened to send the batch.
- """
+def init(harness: str = "generic", source_tag: str = "") -> None:
global _harness, _source_tag
- _harness = harness or _DEFAULT_HARNESS
- _source_tag = source_tag or (
- f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG
- )
+ _harness = harness
+ _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/"
@@ -100,16 +70,6 @@ BATCH_SIZE = 100
SEND_TIMEOUT = 5
CLAIM_STALE_SECONDS = 120
CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60
-# A batch is only discarded once it has genuinely been retried this many times.
-MAX_CLAIM_ATTEMPTS = 3
-# Parked claims drained per run, after the live spool. Bounded so a long backlog
-# cannot turn one flush into an unbounded send loop.
-MAX_PARKED_PER_RUN = 3
-# Added to the wait before a released claim becomes reclaimable, per attempt
-# already spent. Releasing straight to "reclaimable now" let two senders burn the
-# whole budget within seconds of one another on a single momentary failure, and
-# discard a batch a retry a minute later would have delivered.
-RETRY_COOLDOWN_SECONDS = 60
def is_enabled() -> bool:
@@ -123,126 +83,9 @@ def is_enabled() -> bool:
def _digest(value: str, length: int = 16) -> str:
- """Unsalted digest. Only for values that are already secrets (API keys)."""
return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length]
-def _salt_path() -> Path:
- return memory_core.data_dir() / "telemetry-salt"
-
-
-def _install_salt() -> str:
- """Random per-install salt, created once and memoized for the process.
-
- Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in
- the identity file. Three reasons, all of which produced wrong data when this
- lived in the identity dict:
-
- - Hooks are short-lived separate processes firing on every tool call, and
- people run more than one agent window. A read-modify-write would let each
- process mint its own salt, so one repository would hash several ways in the
- window before a writer won.
- - resolve_distinct_id holds a copy of the identity dict across a network call
- to /v1/ping/, so whichever write landed second erased the other's key โ
- losing either the salt (repo_hash changes mid-stream) or the email (a
- second $identify, splitting the person).
- - Touching the identity file from record() would create it, and is_first_run
- keys off that file, so recording an event would silently suppress the
- install event.
-
- Published atomically, and there is deliberately no derived fallback. Creating
- the file with O_CREAT|O_EXCL and then writing into it leaves a window where
- the file exists and is empty, and a concurrent hook that reads it in that
- window gets nothing. Falling back to a digest of the path would hand that
- process a salt an attacker can compute, memoized for its whole run, which is
- the privacy control this function exists to provide silently turning itself
- off under load. The salt is written to a private temp file first and linked
- into place, so the name either does not exist or already has the full value.
-
- Returns "" when it genuinely cannot persist. Callers omit the hash entirely
- rather than emit an unsalted one.
- """
- global _salt_cache
- if _salt_cache:
- return _salt_cache
-
- path = _salt_path()
- # Read before writing. Hooks are separate processes firing on every tool
- # call, so all but the first find the salt already published; going straight
- # to create-fsync-link-unlink meant every one of them paid an fsync to
- # discover that, on a path whose whole promise is appending a line and
- # returning.
- try:
- _salt_cache = path.read_text(encoding="utf-8").strip()
- if _salt_cache:
- return _salt_cache
- except OSError:
- pass
-
- temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(handle, "w", encoding="utf-8") as stream:
- stream.write(uuid.uuid4().hex)
- stream.flush()
- os.fsync(stream.fileno())
- try:
- # Atomic claim: fails if another process already published one.
- # os.link rather than replace, which would clobber theirs.
- os.link(temporary, path)
- except FileExistsError:
- pass
- except OSError:
- # No hardlinks here (some network mounts, some container volumes).
- # Claim the name directly instead. That reopens the empty-file
- # window, but the window is now benign: a reader that lands in it
- # gets "" and omits the hash for that process rather than caching a
- # guessable one. Losing the hashes on every run of an entire
- # filesystem is the worse failure.
- try:
- fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(fallback, "w", encoding="utf-8") as stream:
- stream.write(temporary.read_text(encoding="utf-8"))
- except OSError:
- pass
- except OSError:
- pass
- finally:
- try:
- temporary.unlink()
- except OSError:
- pass
-
- try:
- _salt_cache = path.read_text(encoding="utf-8").strip()
- except OSError:
- _salt_cache = ""
- return _salt_cache
-
-
-def _scoped_digest(value: str, length: int = 16) -> str:
- """Salted digest for values drawn from a guessable space.
-
- repo.identity is a git remote URL, or ``local:`` when there is
- no remote โ which normally contains the account username. Sixteen unsalted
- hex characters over that input space is enumerable, so this is not a
- privacy control without the salt. Salting per install keeps every
- within-account join the analytics actually use and gives up only
- cross-machine joins on the same repository, which nothing computes.
-
- Returns "" when there is no salt, so record() omits the property. An
- unsalted digest over this input space is close to plaintext, and emitting one
- under a name that implies it is hashed is worse than sending nothing.
- """
- if not value:
- return ""
- salt = _install_salt()
- if not salt:
- return ""
- return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length]
-
-
def _safe_value(value: Any) -> Any:
if isinstance(value, str):
return memory_core.redact(value)
@@ -302,176 +145,9 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str:
return created
-def _rotate_anonymous_id(identity: dict[str, str]) -> str:
- """Mint a fresh anonymous id because the account context is gone.
-
- The previous id may already have been merged into a person profile by an
- $identify, and that merge is permanent. Reusing it after a logout or a key
- change attributes everything that follows to the account that just went
- away, which is the same misattribution the key fingerprint exists to stop,
- only arriving through the anonymous path instead.
-
- `aliased` is cleared with it: the new id has never been merged, so it is
- eligible to be aliased into whatever account comes next.
- """
- created = f"code-anon-{uuid.uuid4().hex}"
- identity["anonymous_id"] = created
- identity.pop("aliased", None)
- _write_identity(identity)
- return created
-
-
-def _install_state_path() -> Path:
- return memory_core.data_dir() / "install-state.json"
-
-
def is_first_run() -> bool:
- """Whether install has never been recorded on this machine.
-
- Deliberately NOT the identity file. That file is only written by a
- successful flush, so an offline or firewalled user recorded code.install on
- every single session, forever โ and every 0.2.x user recorded one on their
- first 0.3.x session because 0.2.x never wrote it at all.
- """
- return not _install_state_path().exists()
-
-
-def data_dir_was_empty() -> bool:
- """Whether the data directory is untouched. Call BEFORE anything writes to it.
-
- hook_runner reaches claim_install() only after cache_plugin_api_key() has
- written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so
- asking at claim time always saw content and every fresh install reported an
- upgrade. The caller snapshots this at the top of the run instead.
- """
- return not _data_dir_has_content()
-
-
-def claim_install(was_empty: bool | None = None) -> str | None:
- """Claim the one install/upgrade record for this machine, atomically.
-
- Returns the event to record ("install" or "upgrade"), or None if another
- session already claimed it. O_CREAT|O_EXCL so two sessions starting together
- cannot both win.
-
- `was_empty` must come from data_dir_was_empty() called before this process
- wrote anything. Omitting it falls back to checking now, which is only
- correct for a caller that has touched nothing.
- """
- if not is_enabled():
- # Never consume the one-shot claim while the user is opted out, or they
- # would silently lose their install event if they later opt in.
- return None
-
- path = _install_state_path()
- upgrading = not (data_dir_was_empty() if was_empty is None else was_empty)
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- except FileExistsError:
- return None
- except OSError:
- return None
- try:
- with os.fdopen(handle, "w", encoding="utf-8") as stream:
- json.dump(
- {
- "plugin_version": memory_core.PLUGIN_VERSION,
- "installed_at": memory_core.utc_now(),
- "upgraded": upgrading,
- },
- stream,
- )
- # Durable before this returns. The O_EXCL open is what makes the
- # claim exclusive, so it cannot be replaced by a temp-and-rename
- # without losing that, which leaves the content as the thing to make
- # safe. A kill between the open and this fsync used to leave a marker
- # that exists but parses to nothing: is_first_run reads it as claimed
- # and claim_version_change cannot read a version out of it.
- stream.flush()
- os.fsync(stream.fileno())
- except OSError:
- pass
- return "upgrade" if upgrading else "install"
-
-
-def _data_dir_has_content() -> bool:
- """Whether anything predates this session in the plugin data directory."""
- try:
- for entry in memory_core.data_dir().iterdir():
- if entry.name != "install-state.json":
- return True
- except OSError:
- pass
- return False
-
-
-def _repair_install_state(path: Path) -> None:
- """Rewrite an unparseable marker so version tracking can resume."""
- try:
- temporary = path.with_suffix(f".{os.getpid()}.tmp")
- temporary.write_text(
- json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}),
- encoding="utf-8",
- )
- temporary.replace(path)
- except OSError:
- pass
-
-
-def claim_version_change() -> str | None:
- """Return the previously recorded version if it differs, updating the marker.
-
- Only meaningful once the marker exists โ the first transition into 0.3.x has
- no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting
- the marker means the next session sees no change and records nothing.
- """
- path = _install_state_path()
- try:
- state = json.loads(path.read_text(encoding="utf-8"))
- except OSError:
- return None
- except json.JSONDecodeError:
- # A crash between O_EXCL and the write leaves an empty marker. Left
- # alone it disables every future upgrade event on this machine, because
- # claim_install sees the file and this function cannot parse it.
- state = None
- if not isinstance(state, dict):
- _repair_install_state(path)
- return None
- previous = str(state.get("plugin_version") or "")
- if not previous or previous == memory_core.PLUGIN_VERSION:
- return None
- # Claim the transition with an exclusive sentinel before rewriting the
- # marker. A plain read-modify-write let every concurrently starting session
- # observe the old version and each record its own upgrade โ and the first
- # session after a version bump is exactly when several agent windows restart
- # together.
- sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}")
- try:
- os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
- except FileExistsError:
- return None
- except OSError:
- return None
-
- state["plugin_version"] = memory_core.PLUGIN_VERSION
- state["upgraded_at"] = memory_core.utc_now()
- temporary = path.with_suffix(f".{os.getpid()}.tmp")
- try:
- temporary.write_text(json.dumps(state), encoding="utf-8")
- temporary.replace(path)
- except OSError:
- # Release the claim. The marker still records the old version, so
- # without this the sentinel makes claim_version_change return early on
- # every later run and this version's upgrade is never recorded again.
- for leftover in (sentinel, temporary):
- try:
- leftover.unlink()
- except OSError:
- pass
- return None
- return previous
+ """Whether this machine has never recorded a plugin event before."""
+ return not _identity_path().exists()
def record(
@@ -492,32 +168,19 @@ def record(
except OSError:
pass
properties = _safe_value(properties)
- # Stamped in the RECORDING process, beside harness. `source` used to be
- # read in the sending process from a module global, so whichever process
- # drained the spool named every event in it. flush() spreads per-event
- # properties last, so this now wins over any sender's default.
properties.update(
harness=_harness,
- source=_source_tag,
plugin_version=memory_core.PLUGIN_VERSION,
os=sys.platform,
python_version=platform.python_version(),
)
- # Assigned only when the digest is real. _scoped_digest returns "" when
- # the salt could not be persisted, and an empty property is worse than an
- # absent one: it survives the None filter below and reads as a value.
if repo is not None:
- repo_hash = _scoped_digest(getattr(repo, "identity", ""))
- if repo_hash:
- properties["repo_hash"] = repo_hash
+ properties["repo_hash"] = _digest(getattr(repo, "identity", ""))
if session_id:
- session_hash = _scoped_digest(session_id)
- if session_hash:
- properties["session_hash"] = session_hash
+ properties["session_hash"] = _digest(session_id)
line = json.dumps(
{
"event": f"{EVENT_PREFIX}.{event}",
- "uuid": str(uuid.uuid4()),
"timestamp": memory_core.utc_now(),
"properties": {
key: value for key, value in properties.items() if value is not None
@@ -576,201 +239,38 @@ def spawn_flush() -> bool:
return False
-def _claim_name(attempt: int = 0) -> str:
- """Claim filename. The attempt count rides in the name so the 7-day expiry
- only ever discards a batch that was actually retried and failed."""
- return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending"
-
-
-def _claim_attempt(claim: Path) -> int:
- """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape.
-
- Anchored on field position, not on a leading "a": the legacy shape is
- ``telemetry--.sending`` and a hex id such as ``a1234567`` would
- otherwise parse as attempt 1234567 and be discarded unsent on the first
- flush after an upgrade.
- """
- stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name
- parts = stem.split("-")
- if len(parts) != 4:
- return 0
- tail = parts[3]
- if tail.startswith("a") and tail[1:].isdigit():
- return int(tail[1:])
- return 0
-
-
-def _touch(path: Path) -> None:
- """Refresh mtime so a claim's age measures time since it was claimed.
-
- ``Path.replace`` is ``os.rename``, which preserves mtime โ so a claim created
- after a quiet minute inherited the spool's last-write time and looked
- abandoned the instant it was made. A second sender would then take it over
- while the first was still posting, and both would deliver the batch.
- """
- try:
- os.utime(path, None)
- except OSError:
- pass
-
-
def _claim_spool() -> Path | None:
"""Rename the spool aside so exactly one sender owns each batch."""
directory = memory_core.data_dir()
- claim = directory / _claim_name()
+ claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending"
spool = _spool_path()
try:
spool.replace(claim)
- _touch(claim)
return claim
except OSError:
pass
- return _claim_parked(directory)
-
-
-def _sweep_debris(directory: Path) -> None:
- """Remove files nothing else will ever pick up again.
-
- *.partial is a temp file orphaned by a crash between write and rename.
- *.corrupt is a batch quarantined for undecodable content. No glob in this
- module matches either, so without this they accumulate on disk for the life
- of the install.
-
- Quarantined batches are kept far longer than debris: they are the only
- evidence left of events that could not be delivered, and someone diagnosing
- a report of missing telemetry has to be able to find one.
- """
now = time.time()
- for debris in directory.glob("telemetry-*.partial"):
- try:
- if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS:
- debris.unlink()
- except OSError:
- continue
- for quarantined in directory.glob("telemetry-*.corrupt"):
- try:
- if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS:
- quarantined.unlink()
- except OSError:
- continue
- # The same reasoning covers *.tmp. _write_identity and _install_salt both
- # create one and unlink it in a finally, which a SIGKILL skips, and no glob
- # in this module matches the leftovers either.
- for temporary in directory.glob("telemetry-*.tmp"):
- try:
- if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS:
- temporary.unlink()
- except OSError:
- continue
-
-
-def _claim_parked(directory: Path) -> Path | None:
- """Take the oldest abandoned claim, if any lease has actually expired.
-
- Kept separate from the live spool so flush() can drain both in one run.
- Previously parked batches were only reachable when no spool existed at all,
- and because sessions keep recording there usually was one โ so a batch
- parked by a failed send waited until the 7-day expiry deleted it unsent,
- even though its own presence is what started the sender.
- """
- now = time.time()
- for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime):
+ for orphan in sorted(directory.glob("telemetry-*.sending")):
try:
age = now - orphan.stat().st_mtime
except OSError:
continue
- if age < CLAIM_STALE_SECONDS:
- # Someone else holds a live lease on it. This check has to come
- # first. Claiming a file bumps its attempt count and refreshes its
- # mtime, so a sender that has just taken the final attempt looks
- # exhausted to everyone else while it is actively draining. Judging
- # exhaustion before liveness let a second sender unlink a batch out
- # from under its owner, losing every event in it.
- continue
- # Attempts, not age. Every re-claim touches the mtime and every release
- # backdates it by a fixed amount, so age is pinned near the stale
- # threshold and never reaches the expiry. Age stays only as a backstop
- # for files that never carried an attempt marker.
- if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS:
+ if age > CLAIM_EXPIRY_SECONDS:
try:
orphan.unlink()
except OSError:
pass
continue
- claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1)
+ if age < CLAIM_STALE_SECONDS:
+ continue
try:
orphan.replace(claim)
- _touch(claim)
return claim
except OSError:
continue
return None
-def _safe_mtime(path: Path) -> float:
- try:
- return path.stat().st_mtime
- except OSError:
- return 0.0
-
-
-def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool:
- """Persist the unsent remainder, atomically, and refresh the lease.
-
- Called after every successful batch. Two jobs: a retry resumes where the
- send stopped instead of re-posting from the top, and the rewrite doubles as
- the lease heartbeat, so a slow sender does not have its claim stolen
- mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS.
- """
- if not remaining:
- try:
- claim.unlink()
- except OSError:
- pass
- return True
- temporary = claim.with_suffix(f".{os.getpid()}.partial")
- try:
- payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining)
- # fsync before the rename: without it the rename can land while the
- # bytes have not, and the claim comes back empty or truncated after a
- # crash. _drain then reads zero events and unlinks it.
- with open(temporary, "w", encoding="utf-8") as handle:
- handle.write(payload)
- handle.flush()
- os.fsync(handle.fileno())
- temporary.replace(claim)
- _touch(claim)
- return True
- except OSError:
- try:
- temporary.unlink()
- except OSError:
- pass
- return False
-
-
-def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None:
- """Persist the remainder and drop the lease, because this sender has given up.
-
- Distinct from the per-batch heartbeat: heartbeating on the way out would
- make an abandoned batch look actively owned for a further
- CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the
- threshold lets the next flush pick it up immediately, while the attempt
- count in the filename still bounds how many times that can happen.
- """
- if not _rewrite_claim(claim, remaining):
- return
- try:
- # Backdate past the stale threshold so the next flush can pick it up,
- # minus a cooldown that grows with the attempts already spent. Clamped so
- # the mtime never lands in the future, which would read as a live lease.
- cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS)
- released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown
- os.utime(claim, (released, released))
- except OSError:
- pass
-
-
def _resolve_email(key: str) -> str:
"""Trade the API key for the account email so events join other Mem0 surfaces."""
url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/"
@@ -800,130 +300,34 @@ def _post(payload: dict[str, Any], url: str) -> bool:
def resolve_distinct_id() -> tuple[str, str]:
- """Return the PostHog distinct id and the anonymous id it replaced, if any.
-
- The second value becomes a PostHog $identify alias. It is ONLY ever an
- anonymous id: aliasing one account email to another merges two real person
- profiles and cannot be undone, so a key that now belongs to a different
- account re-resolves with no alias.
- """
+ """Return the PostHog distinct id and the anonymous id it replaced, if any."""
identity = _read_identity()
- key = memory_core.api_key()
- fingerprint = _digest(key) if key else ""
email = identity.get("email", "")
-
- if email and fingerprint:
- recorded = identity.get("key_fingerprint", "")
- if recorded == fingerprint:
- return email, ""
- if not recorded:
- # Rows written before fingerprints existed. Verify rather than
- # adopt: a key changed before the upgrade would otherwise bind the
- # new key to the previous account's email, permanently, and the
- # fingerprint would then agree with itself forever after.
- verified = _resolve_email(key)
- if not verified:
- # Offline, firewalled, or the API is down. Keep the previous
- # behaviour and retry on the next flush rather than dropping a
- # real account attribution. Safe because the same network that
- # failed /v1/ping/ is about to fail the PostHog POST, so nothing
- # is delivered under the unverified identity in the meantime.
- return email, ""
- identity["email"] = verified
- identity["key_fingerprint"] = fingerprint
- _write_identity(identity)
- return verified, ""
-
+ if email:
+ return email, ""
+ key = memory_core.api_key()
if not key:
- # No key to verify the account with; do not keep attributing to it.
- if email:
- identity.pop("email", None)
- identity.pop("key_fingerprint", None)
- return _rotate_anonymous_id(identity), ""
return anonymous_id(identity), ""
-
- resolved = _resolve_email(key)
- if not resolved:
- # The key changed and will not resolve (revoked, offline, API down).
- # Reaching here with an email means the recorded fingerprint disagreed,
- # so the key really did change. Drop the account and rotate: the stored
- # anonymous id may already be merged into that account's person, and
- # reusing it would keep the events on the profile we are trying to
- # leave.
- if email:
- identity.pop("email", None)
- identity.pop("key_fingerprint", None)
- return _rotate_anonymous_id(identity), ""
+ email = _resolve_email(key)
+ if not email:
return anonymous_id(identity), ""
-
- # Alias only when going anonymous -> email for the first time. Once an anon
- # id has been merged into an account it must never be offered again: an
- # alias naming an already-identified id is what could link two real people.
- previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "")
- if previous:
- identity["aliased"] = True
- identity["email"] = resolved
- identity["key_fingerprint"] = fingerprint
+ previous = identity.get("anonymous_id", "")
+ identity["email"] = email
_write_identity(identity)
- return resolved, previous
+ return email, previous
def flush() -> int:
- """Drain the live spool, then any parked claims, and return events sent."""
+ """Drain claimed spools to PostHog and return the number of events sent."""
if not is_enabled():
return 0
- sent, delivered = _drain(_claim_spool())
- if not delivered:
- # The network is failing. Retrying other batches now would only burn
- # their attempt budget against the same broken connection.
- return sent
-
- # Parked batches used to starve behind the live spool indefinitely. Bounded
- # per run so a long backlog cannot turn one flush into an unbounded loop.
- directory = memory_core.data_dir()
- _sweep_debris(directory)
- for _ in range(MAX_PARKED_PER_RUN):
- parked = _claim_parked(directory)
- if parked is None:
- break
- count, delivered = _drain(parked)
- sent += count
- if not delivered:
- break
- return sent
-
-
-def _drain(claim: Path | None) -> tuple[int, bool]:
- """Post one claimed batch file, recording progress after every batch.
-
- Returns (events sent, whether everything was delivered).
- """
+ claim = _claim_spool()
if claim is None:
- return 0, True
+ return 0
try:
lines = claim.read_text(encoding="utf-8").splitlines()
- except ValueError:
- # UnicodeDecodeError from a torn write: the content is unrecoverable, so
- # quarantine rather than retry. flush() runs from a bare `finally:` in
- # flush_worker, so raising here also skips the handoff cleanup, and an
- # undecodable file would otherwise be re-read on every flush forever.
- # Reported as delivered because there is nothing left to deliver and the
- # rest of the run should continue.
- try:
- claim.replace(claim.with_suffix(".corrupt"))
- except OSError:
- try:
- claim.unlink()
- except OSError:
- pass
- return 0, True
except OSError:
- # Could not read it, which is not the same as having nothing to send.
- # The file is left exactly where it is: a vanished or briefly unreadable
- # claim is retryable, and quarantining it here would discard events over
- # a transient filesystem error. Reported as undelivered so the run stops
- # instead of counting a batch nothing was posted from as delivered.
- return 0, False
+ return 0
events = []
for line in lines:
try:
@@ -933,18 +337,11 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
if isinstance(value, dict) and value.get("event"):
events.append(value)
if not events:
- # Only delete when the file really is empty. A non-empty file that
- # parses to nothing is a torn write, and its contents are the unsent
- # remainder โ deleting it is the data loss this PR exists to prevent.
try:
- empty = claim.stat().st_size == 0
- except OSError:
- empty = True
- try:
- claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink()
+ claim.unlink()
except OSError:
pass
- return 0, True
+ return 0
distinct_id, aliased_anonymous_id = resolve_distinct_id()
if aliased_anonymous_id:
@@ -963,17 +360,12 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
sent = 0
for start in range(0, len(events), BATCH_SIZE):
- chunk = events[start : start + BATCH_SIZE]
batch = [
{
"event": event["event"],
"distinct_id": distinct_id,
- # Carried through from record() so a resend can be collapsed.
- "uuid": event.get("uuid"),
"timestamp": event.get("timestamp"),
"properties": {
- # Fallback only: events recorded by a build before source
- # moved into record() have none of their own.
"source": _source_tag,
"language": "python",
"$process_person_profile": False,
@@ -981,24 +373,16 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
**(event.get("properties") or {}),
},
}
- for event in chunk
+ for event in events[start : start + BATCH_SIZE]
]
if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL):
- # Keep only what has not been delivered, and release the lease.
- # Previously the whole file was kept and the retry re-posted every
- # batch, including the ones that had already arrived.
- _release_claim(claim, events[start:])
- return sent, False
- sent += len(chunk)
- # Record progress and refresh the lease after each successful batch, so
- # a crash repeats at most one batch instead of the entire file. If the
- # rewrite fails the claim still holds delivered events, so stop rather
- # than carry on as though progress were recorded โ continuing is how the
- # duplicate delivery this PR fixes would come back.
- if not _rewrite_claim(claim, events[start + len(chunk) :]):
- _release_claim(claim, events[start + len(chunk) :])
- return sent, False
- return sent, True
+ return sent
+ sent += len(batch)
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return sent
def main() -> int:
diff --git a/integrations/cursor-plugin/plugin-build.json b/integrations/cursor-plugin/plugin-build.json
index 5320fb7f9..279b3178c 100644
--- a/integrations/cursor-plugin/plugin-build.json
+++ b/integrations/cursor-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.3",
+ "version": "0.3.1",
"homepage": "https://docs.mem0.ai/integrations/cursor",
"native": {
"pluginRoot": "${CURSOR_PLUGIN_ROOT}",
diff --git a/integrations/cursor-plugin/skills/pause/SKILL.md b/integrations/cursor-plugin/skills/pause/SKILL.md
index 17384c368..634385145 100644
--- a/integrations/cursor-plugin/skills/pause/SKILL.md
+++ b/integrations/cursor-plugin/skills/pause/SKILL.md
@@ -7,8 +7,8 @@ disable-model-invocation: true
# Pause memory capture
To pause (hooks stop capturing and sending session content; a minimal
-telemetry ping still fires at session start, under your Mem0 account email,
-unless `MEM0_TELEMETRY=false`):
+anonymous telemetry ping still fires at session start unless
+`MEM0_TELEMETRY=false`):
```bash
python3 "${CURSOR_PLUGIN_ROOT}/core/memory_cli.py" --harness "cursor" pause
diff --git a/integrations/cursor-plugin/skills/search/SKILL.md b/integrations/cursor-plugin/skills/search/SKILL.md
index 2e3bde6a7..7a7ddfa90 100644
--- a/integrations/cursor-plugin/skills/search/SKILL.md
+++ b/integrations/cursor-plugin/skills/search/SKILL.md
@@ -12,9 +12,11 @@ Call `search_memories` with the user's question. Treat `--top-k`, `--category`,
query.
Omit `top_k` to use Mem0's configured default. Omit `category` to search every
-category. Omit `scope` to use the configured default, normally `repo`: this
-repository's shared memory, which everyone who works in it contributes to,
-plus your own preferences.
+category; a category is a best-effort label Mem0 assigned when it saved the
+memory, so if a category search misses, repeat it without the category. Omit
+`scope` to use the configured default, normally `repo`: this repository's
+shared memory, which everyone who works in it contributes to, plus your own
+preferences.
Pass `scope` when the question needs something else: `dir` to narrow the
shared memory to the directory you are working in (a package inside a
diff --git a/integrations/deepseek-plugin/README.md b/integrations/deepseek-plugin/README.md
index d5cb3345a..93e5f563f 100644
--- a/integrations/deepseek-plugin/README.md
+++ b/integrations/deepseek-plugin/README.md
@@ -86,9 +86,9 @@ Per-call `userId` overrides are rejected unless the operator enables `allowUserO
## Telemetry
-Writes are tagged `source="DEEPSEEK_HARNESS"`. That value has to exist in the backend's `EventSource` enum for usage to surface by name; until it does, these writes read as `OTHERS`. It is added by [mem0ai/platform#3602](https://github.com/mem0ai/platform/pull/3602), which has to ship before this claim is true.
+Writes are tagged `source="DEEPSEEK_HARNESS"` so Mem0's backend can attribute usage to this integration. For it to surface by name (rather than bucketing into `OTHERS`), `DEEPSEEK_HARNESS` must be present in the backend's `KNOWN_EVENT_SOURCES` allowlist, a one-line platform change matching the existing `ZAPIER` / `STRANDS` sources.
-The plugin also sends usage events (which tool ran, duration, result counts, coarse failure kind) so Mem0 can tell how the plugin is used and where it breaks. These are **not anonymous**: when an API key is configured they are sent under your Mem0 account email, the same way the SDK attributes its own. Queries, memory text, and entity ids are never sent. Turn it off with `MEM0_TELEMETRY=false`.
+The plugin also sends anonymous usage events (which tool ran, duration, result counts, coarse failure kind) so Mem0 can tell how the plugin is used and where it breaks. Queries, memory text, and entity ids are never sent. Turn it off with `MEM0_TELEMETRY=false`.
## Status
diff --git a/integrations/deepseek-plugin/package.json b/integrations/deepseek-plugin/package.json
index 3de2d4f13..ea00bb9c5 100644
--- a/integrations/deepseek-plugin/package.json
+++ b/integrations/deepseek-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/deepseek-plugin",
- "version": "0.3.2",
+ "version": "0.3.0",
"description": "Mem0 long-term memory as a native DeepSeek Harness (Cordis) plugin.",
"type": "module",
"license": "Apache-2.0",
@@ -60,12 +60,5 @@
"tsup": "^8.5.0",
"typescript": "^5.6.0",
"vitest": "^4.1.7"
- },
- "pnpm": {
- "overrides": {
- "axios@<1.20.0": ">=1.20.0 <2.0.0",
- "follow-redirects@<1.16.2": ">=1.16.2 <2.0.0",
- "vite@>=8.2.0 <8.2.4": ">=8.2.4 <9.0.0"
- }
}
}
diff --git a/integrations/deepseek-plugin/pnpm-lock.yaml b/integrations/deepseek-plugin/pnpm-lock.yaml
index e56466e4a..1444b53d4 100644
--- a/integrations/deepseek-plugin/pnpm-lock.yaml
+++ b/integrations/deepseek-plugin/pnpm-lock.yaml
@@ -4,11 +4,6 @@ settings:
autoInstallPeers: false
excludeLinksFromLockfile: false
-overrides:
- axios@<1.20.0: '>=1.20.0 <2.0.0'
- follow-redirects@<1.16.2: '>=1.16.2 <2.0.0'
- vite@>=8.2.0 <8.2.4: '>=8.2.4 <9.0.0'
-
importers:
.:
@@ -37,7 +32,7 @@ importers:
version: 22.20.1
tsup:
specifier: ^8.5.0
- version: 8.5.1(postcss@8.5.32)(typescript@5.9.3)
+ version: 8.5.1(postcss@8.5.26)(typescript@5.9.3)
typescript:
specifier: ^5.6.0
version: 5.9.3
@@ -282,95 +277,95 @@ packages:
cpu: [x64]
os: [linux]
- '@oxc-project/types@0.156.0':
- resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==}
+ '@oxc-project/types@0.146.0':
+ resolution: {integrity: sha512-XC0QsnnhVe7sLIWmYmdPw7x5P0h4W8vUU3Nv1ySgWXtvCz8NizoAEpGXA0sOYoJQV2Rl13LgURAHQ5cI5ILCSA==}
- '@rolldown/binding-android-arm-eabi@1.2.16':
- resolution: {integrity: sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==}
+ '@rolldown/binding-android-arm-eabi@1.2.5':
+ resolution: {integrity: sha512-DLe/i+l8ynIBY7XEQ191TeZvCoowIGa18R+dIV30GW7DiOtp74i/xX8hs8GUjW5ARV7VZuie3d6AumSmCwbeRA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [android]
- '@rolldown/binding-android-arm64@1.2.16':
- resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==}
+ '@rolldown/binding-android-arm64@1.2.5':
+ resolution: {integrity: sha512-zXcwKlQApYAOELHd8PwKDFkagYF9Wy4e0RJ+0qnzl9Pjnpj75TEG8ufv40p2J7kCEfwZAsNiuzRIyNNMWT38ig==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [android]
- '@rolldown/binding-darwin-arm64@1.2.16':
- resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==}
+ '@rolldown/binding-darwin-arm64@1.2.5':
+ resolution: {integrity: sha512-dK4QakI42nzWgJT5sm4y4y/O//D4OxM75/cH28RLV+nzIN9AY+YsbuUVrUTjlLjXR6vpyxFbSsbmNuJ6BP9sww==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [darwin]
- '@rolldown/binding-darwin-x64@1.2.16':
- resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==}
+ '@rolldown/binding-darwin-x64@1.2.5':
+ resolution: {integrity: sha512-fqSALaUu1Wjd1nK2uW2kJDWdLCc8lx1IcY+MTY26Aurfdx19anlzhqXOgCFbBFQnlFDTn4TC1/7Nz4Bl2mLP3A==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [darwin]
- '@rolldown/binding-freebsd-x64@1.2.16':
- resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==}
+ '@rolldown/binding-freebsd-x64@1.2.5':
+ resolution: {integrity: sha512-/vCnNxlkxs9tKxNDcyWUePpJ/PgTzxIaVhoM5SmG8UV+GR/IcPam4VYxi7GIMo7PSDuNqlJqvprqii9NqqVCMw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [freebsd]
- '@rolldown/binding-linux-arm-gnueabihf@1.2.16':
- resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==}
+ '@rolldown/binding-linux-arm-gnueabihf@1.2.5':
+ resolution: {integrity: sha512-abk0NLA519LxRCszmbE0jYKuQ9YPocOXTiOXOo6Yr+YAT95VH+PtqYAjOJvGKt3viEd/x4qzabAlwd5bHOOARg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
- '@rolldown/binding-linux-arm64-gnu@1.2.16':
- resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==}
+ '@rolldown/binding-linux-arm64-gnu@1.2.5':
+ resolution: {integrity: sha512-Y7eALiJ8lr0M2HH103Js+g7V34wf6snlpZLAsHI90uLhr3PVlNsbFVAXJC9d/V6BnPyKtpSwI+NcB/RLxsQxuA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- '@rolldown/binding-linux-arm64-musl@1.2.16':
- resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==}
+ '@rolldown/binding-linux-arm64-musl@1.2.5':
+ resolution: {integrity: sha512-xMvZgnbZg4YVnR/AX2b3oOPDTFYJvUVaJg5FedA/LuvexAtXibZQej4cnTkw3rjsJ/ggUROB64TdtETiim+FYA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
- '@rolldown/binding-linux-ppc64-gnu@1.2.16':
- resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==}
+ '@rolldown/binding-linux-ppc64-gnu@1.2.5':
+ resolution: {integrity: sha512-GRjeqTUDHTo5GwntsLaAMcBahG3nlpjftXWZLN73HiYQlhwEowvarFgQnRnQZtIp4keXX7quXFbG38uPZBa2EA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
- '@rolldown/binding-linux-s390x-gnu@1.2.16':
- resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==}
+ '@rolldown/binding-linux-s390x-gnu@1.2.5':
+ resolution: {integrity: sha512-vLNTR45F2Uwc8AufkNXPmB4VliaXs+FvcheEogIzOXzO4l+LzieXF5A/TWxLy5HtqpsRCHUfd0lPVrrdgXdLHQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
- '@rolldown/binding-linux-x64-gnu@1.2.16':
- resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==}
+ '@rolldown/binding-linux-x64-gnu@1.2.5':
+ resolution: {integrity: sha512-Mgj59/HTuYeK9Gz2MA+mBWKnHsAgkBSec15ZMb1st3oIfFbX7gCjOae7GydHhzcyQi9Z/7M1QuN9bR3oFqF0jQ==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- '@rolldown/binding-linux-x64-musl@1.2.16':
- resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==}
+ '@rolldown/binding-linux-x64-musl@1.2.5':
+ resolution: {integrity: sha512-mY8AP0/ichsbhAxGnLa3d3+MwV0EfgrPND2bplI3Ym8T6R2pJ0N87bvrKVwNXmdy3jnr6eQBecdqx/HMknBmpA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
- '@rolldown/binding-openharmony-arm64@1.2.16':
- resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==}
+ '@rolldown/binding-openharmony-arm64@1.2.5':
+ resolution: {integrity: sha512-8SLssA2oweAxyRgDp789ACfRb/3P+zNRJpzZxSizxF9m8NUDQ4+3xjo8ttjhVGGw6Qxb70oZiEtIjaKikCO7Yw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [openharmony]
- '@rolldown/binding-win32-arm64-msvc@1.2.16':
- resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==}
+ '@rolldown/binding-win32-arm64-msvc@1.2.5':
+ resolution: {integrity: sha512-vGbruD5zquhoc8D9SViXgN2FBJtNdTyQ4DtG+SWiEGlJiAzoKcZ2xp+xuXCffhubVdt0NJlTZqkeRuERy7g8Cw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [win32]
- '@rolldown/binding-win32-x64-msvc@1.2.16':
- resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==}
+ '@rolldown/binding-win32-x64-msvc@1.2.5':
+ resolution: {integrity: sha512-e/SXpgISz+IoqVcSSI0rx/d/he8zqLex+/rCWpnHpmVfmPIUjag9H6P7zotf0gJHwPUhQxZ/mF8tr6acebT9yw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [win32]
@@ -531,7 +526,7 @@ packages:
resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==}
peerDependencies:
msw: ^2.4.9
- vite: '>=8.2.4 <9.0.0'
+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0
peerDependenciesMeta:
msw:
optional: true
@@ -580,8 +575,8 @@ packages:
asynckit@0.4.0:
resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}
- axios@1.20.0:
- resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==}
+ axios@1.19.0:
+ resolution: {integrity: sha512-ht/iuYZXEjFxLH/Hkezgd7m6JKlHHXEUSneaDz8uZe1Gj5QZtCnpyDsckvAiEnT89OEbCLmnte4R4sn7P0EKFw==}
bundle-require@5.1.0:
resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==}
@@ -691,8 +686,8 @@ packages:
fix-dts-default-cjs-exports@1.0.1:
resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==}
- follow-redirects@1.16.2:
- resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==}
+ follow-redirects@1.16.0:
+ resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==}
engines: {node: '>=4.0'}
peerDependencies:
debug: '*'
@@ -977,8 +972,8 @@ packages:
mz@2.7.0:
resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==}
- nanoid@3.3.20:
- resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}
+ nanoid@3.3.18:
+ resolution: {integrity: sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
@@ -1026,10 +1021,6 @@ packages:
resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==}
engines: {node: '>=12'}
- picomatch@4.0.7:
- resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
- engines: {node: '>=12'}
-
pirates@4.0.7:
resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==}
engines: {node: '>= 6'}
@@ -1055,8 +1046,8 @@ packages:
yaml:
optional: true
- postcss@8.5.32:
- resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==}
+ postcss@8.5.26:
+ resolution: {integrity: sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==}
engines: {node: ^10 || ^12 || >=14}
proxy-from-env@2.1.0:
@@ -1071,8 +1062,8 @@ packages:
resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==}
engines: {node: '>=8'}
- rolldown@1.2.16:
- resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==}
+ rolldown@1.2.5:
+ resolution: {integrity: sha512-VD2IE5PUG4Oj8zz2VGykiYd5wbnjdIiSsNQb8Qu5B+noEp+A78mu2iVvpp27g8es14Tk9rofNs5Tku9iQCS4fA==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
@@ -1084,8 +1075,8 @@ packages:
siginfo@2.0.0:
resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==}
- source-map-js@1.2.2:
- resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
+ source-map-js@1.2.1:
+ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'}
source-map@0.7.6:
@@ -1175,13 +1166,13 @@ packages:
resolution: {integrity: sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==}
hasBin: true
- vite@8.3.6:
- resolution: {integrity: sha512-UI7dK29NnS54Fk+mmo7o+jI6U8Fp7hDl+X5Q1k45WH+d4dSlbLVUETGQ+hfkNgvLQGyoElPj837nZyv4MBc0VA==}
+ vite@8.2.2:
+ resolution: {integrity: sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
peerDependencies:
'@types/node': ^20.19.0 || >=22.12.0
- '@vitejs/devtools': ^0.7.1 || ^0.8.0
+ '@vitejs/devtools': ^0.4.0 || ^0.5.0
esbuild: ^0.27.0 || ^0.28.0
jiti: '>=1.21.0'
less: ^4.0.0
@@ -1408,51 +1399,51 @@ snapshots:
'@napi-rs/lzma-linux-x64-gnu@1.5.1':
optional: true
- '@oxc-project/types@0.156.0': {}
+ '@oxc-project/types@0.146.0': {}
- '@rolldown/binding-android-arm-eabi@1.2.16':
+ '@rolldown/binding-android-arm-eabi@1.2.5':
optional: true
- '@rolldown/binding-android-arm64@1.2.16':
+ '@rolldown/binding-android-arm64@1.2.5':
optional: true
- '@rolldown/binding-darwin-arm64@1.2.16':
+ '@rolldown/binding-darwin-arm64@1.2.5':
optional: true
- '@rolldown/binding-darwin-x64@1.2.16':
+ '@rolldown/binding-darwin-x64@1.2.5':
optional: true
- '@rolldown/binding-freebsd-x64@1.2.16':
+ '@rolldown/binding-freebsd-x64@1.2.5':
optional: true
- '@rolldown/binding-linux-arm-gnueabihf@1.2.16':
+ '@rolldown/binding-linux-arm-gnueabihf@1.2.5':
optional: true
- '@rolldown/binding-linux-arm64-gnu@1.2.16':
+ '@rolldown/binding-linux-arm64-gnu@1.2.5':
optional: true
- '@rolldown/binding-linux-arm64-musl@1.2.16':
+ '@rolldown/binding-linux-arm64-musl@1.2.5':
optional: true
- '@rolldown/binding-linux-ppc64-gnu@1.2.16':
+ '@rolldown/binding-linux-ppc64-gnu@1.2.5':
optional: true
- '@rolldown/binding-linux-s390x-gnu@1.2.16':
+ '@rolldown/binding-linux-s390x-gnu@1.2.5':
optional: true
- '@rolldown/binding-linux-x64-gnu@1.2.16':
+ '@rolldown/binding-linux-x64-gnu@1.2.5':
optional: true
- '@rolldown/binding-linux-x64-musl@1.2.16':
+ '@rolldown/binding-linux-x64-musl@1.2.5':
optional: true
- '@rolldown/binding-openharmony-arm64@1.2.16':
+ '@rolldown/binding-openharmony-arm64@1.2.5':
optional: true
- '@rolldown/binding-win32-arm64-msvc@1.2.16':
+ '@rolldown/binding-win32-arm64-msvc@1.2.5':
optional: true
- '@rolldown/binding-win32-x64-msvc@1.2.16':
+ '@rolldown/binding-win32-x64-msvc@1.2.5':
optional: true
'@rolldown/pluginutils@1.0.1': {}
@@ -1565,13 +1556,13 @@ snapshots:
chai: 6.2.2
tinyrainbow: 3.1.1
- '@vitest/mocker@4.1.11(vite@8.3.6(@types/node@22.20.1)(esbuild@0.27.7))':
+ '@vitest/mocker@4.1.11(vite@8.2.2(@types/node@22.20.1)(esbuild@0.27.7))':
dependencies:
'@vitest/spy': 4.1.11
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
- vite: 8.3.6(@types/node@22.20.1)(esbuild@0.27.7)
+ vite: 8.2.2(@types/node@22.20.1)(esbuild@0.27.7)
'@vitest/pretty-format@4.1.11':
dependencies:
@@ -1619,9 +1610,9 @@ snapshots:
asynckit@0.4.0: {}
- axios@1.20.0:
+ axios@1.19.0:
dependencies:
- follow-redirects: 1.16.2
+ follow-redirects: 1.16.0
form-data: 4.0.6
https-proxy-agent: 5.0.1
proxy-from-env: 2.1.0
@@ -1737,7 +1728,7 @@ snapshots:
mlly: 1.8.2
rollup: 4.62.5
- follow-redirects@1.16.2: {}
+ follow-redirects@1.16.0: {}
form-data-encoder@1.7.2: {}
@@ -1865,7 +1856,7 @@ snapshots:
mem0ai@3.1.6:
dependencies:
- axios: 1.20.0
+ axios: 1.19.0
openai: 4.104.0(zod@3.25.76)
uuid: 11.1.1
zod: 3.25.76
@@ -1896,7 +1887,7 @@ snapshots:
object-assign: 4.1.1
thenify-all: 1.6.0
- nanoid@3.3.20: {}
+ nanoid@3.3.18: {}
node-domexception@1.0.0: {}
@@ -1928,8 +1919,6 @@ snapshots:
picomatch@4.0.5: {}
- picomatch@4.0.7: {}
-
pirates@4.0.7: {}
pkg-types@1.3.1:
@@ -1938,17 +1927,17 @@ snapshots:
mlly: 1.8.2
pathe: 2.0.3
- postcss-load-config@6.0.1(postcss@8.5.32):
+ postcss-load-config@6.0.1(postcss@8.5.26):
dependencies:
lilconfig: 3.1.3
optionalDependencies:
- postcss: 8.5.32
+ postcss: 8.5.26
- postcss@8.5.32:
+ postcss@8.5.26:
dependencies:
- nanoid: 3.3.20
+ nanoid: 3.3.18
picocolors: 1.1.1
- source-map-js: 1.2.2
+ source-map-js: 1.2.1
proxy-from-env@2.1.0: {}
@@ -1956,26 +1945,26 @@ snapshots:
resolve-from@5.0.0: {}
- rolldown@1.2.16:
+ rolldown@1.2.5:
dependencies:
- '@oxc-project/types': 0.156.0
+ '@oxc-project/types': 0.146.0
'@rolldown/pluginutils': 1.0.1
optionalDependencies:
- '@rolldown/binding-android-arm-eabi': 1.2.16
- '@rolldown/binding-android-arm64': 1.2.16
- '@rolldown/binding-darwin-arm64': 1.2.16
- '@rolldown/binding-darwin-x64': 1.2.16
- '@rolldown/binding-freebsd-x64': 1.2.16
- '@rolldown/binding-linux-arm-gnueabihf': 1.2.16
- '@rolldown/binding-linux-arm64-gnu': 1.2.16
- '@rolldown/binding-linux-arm64-musl': 1.2.16
- '@rolldown/binding-linux-ppc64-gnu': 1.2.16
- '@rolldown/binding-linux-s390x-gnu': 1.2.16
- '@rolldown/binding-linux-x64-gnu': 1.2.16
- '@rolldown/binding-linux-x64-musl': 1.2.16
- '@rolldown/binding-openharmony-arm64': 1.2.16
- '@rolldown/binding-win32-arm64-msvc': 1.2.16
- '@rolldown/binding-win32-x64-msvc': 1.2.16
+ '@rolldown/binding-android-arm-eabi': 1.2.5
+ '@rolldown/binding-android-arm64': 1.2.5
+ '@rolldown/binding-darwin-arm64': 1.2.5
+ '@rolldown/binding-darwin-x64': 1.2.5
+ '@rolldown/binding-freebsd-x64': 1.2.5
+ '@rolldown/binding-linux-arm-gnueabihf': 1.2.5
+ '@rolldown/binding-linux-arm64-gnu': 1.2.5
+ '@rolldown/binding-linux-arm64-musl': 1.2.5
+ '@rolldown/binding-linux-ppc64-gnu': 1.2.5
+ '@rolldown/binding-linux-s390x-gnu': 1.2.5
+ '@rolldown/binding-linux-x64-gnu': 1.2.5
+ '@rolldown/binding-linux-x64-musl': 1.2.5
+ '@rolldown/binding-openharmony-arm64': 1.2.5
+ '@rolldown/binding-win32-arm64-msvc': 1.2.5
+ '@rolldown/binding-win32-x64-msvc': 1.2.5
rollup@4.62.5:
dependencies:
@@ -2011,7 +2000,7 @@ snapshots:
siginfo@2.0.0: {}
- source-map-js@1.2.2: {}
+ source-map-js@1.2.1: {}
source-map@0.7.6: {}
@@ -2056,7 +2045,7 @@ snapshots:
ts-interface-checker@0.1.13: {}
- tsup@8.5.1(postcss@8.5.32)(typescript@5.9.3):
+ tsup@8.5.1(postcss@8.5.26)(typescript@5.9.3):
dependencies:
bundle-require: 5.1.0(esbuild@0.27.7)
cac: 6.7.14
@@ -2067,7 +2056,7 @@ snapshots:
fix-dts-default-cjs-exports: 1.0.1
joycon: 3.1.1
picocolors: 1.1.1
- postcss-load-config: 6.0.1(postcss@8.5.32)
+ postcss-load-config: 6.0.1(postcss@8.5.26)
resolve-from: 5.0.0
rollup: 4.62.5
source-map: 0.7.6
@@ -2076,7 +2065,7 @@ snapshots:
tinyglobby: 0.2.17
tree-kill: 1.2.2
optionalDependencies:
- postcss: 8.5.32
+ postcss: 8.5.26
typescript: 5.9.3
transitivePeerDependencies:
- jiti
@@ -2094,12 +2083,12 @@ snapshots:
uuid@11.1.1: {}
- vite@8.3.6(@types/node@22.20.1)(esbuild@0.27.7):
+ vite@8.2.2(@types/node@22.20.1)(esbuild@0.27.7):
dependencies:
lightningcss: 1.33.0
- picomatch: 4.0.7
- postcss: 8.5.32
- rolldown: 1.2.16
+ picomatch: 4.0.5
+ postcss: 8.5.26
+ rolldown: 1.2.5
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 22.20.1
@@ -2109,7 +2098,7 @@ snapshots:
vitest@4.1.11(@types/node@22.20.1)(esbuild@0.27.7):
dependencies:
'@vitest/expect': 4.1.11
- '@vitest/mocker': 4.1.11(vite@8.3.6(@types/node@22.20.1)(esbuild@0.27.7))
+ '@vitest/mocker': 4.1.11(vite@8.2.2(@types/node@22.20.1)(esbuild@0.27.7))
'@vitest/pretty-format': 4.1.11
'@vitest/runner': 4.1.11
'@vitest/snapshot': 4.1.11
@@ -2126,7 +2115,7 @@ snapshots:
tinyexec: 1.3.0
tinyglobby: 0.2.17
tinyrainbow: 3.1.1
- vite: 8.3.6(@types/node@22.20.1)(esbuild@0.27.7)
+ vite: 8.2.2(@types/node@22.20.1)(esbuild@0.27.7)
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 22.20.1
diff --git a/integrations/deepseek-plugin/src/index.ts b/integrations/deepseek-plugin/src/index.ts
index c5eb64390..bea70c02c 100644
--- a/integrations/deepseek-plugin/src/index.ts
+++ b/integrations/deepseek-plugin/src/index.ts
@@ -21,19 +21,15 @@ import { truncateOutput } from "./output.ts";
import { resolveSearchFilters, resolveAddParams } from "./scoping.ts";
import { captureEvent, errorKind } from "./telemetry.ts";
import { createMemoryLifecycle } from "../../agent-plugin-core/typescript/src/lifecycle.ts";
-import {
- USER_RECALL_HEADING,
- USER_SEARCH_QUERY_DESCRIPTION,
- USER_SEARCH_TOOL_DESCRIPTION,
-} from "../../agent-plugin-core/typescript/src/prompts.ts";
export const name = "mem0";
export const inject = ["tools", "systemPrompt"];
// Tags writes so Mem0's backend attributes them to this integration in
-// telemetry. Values outside the backend's KNOWN_EVENT_SOURCES allowlist bucket
-// into "OTHERS"; this one is added by mem0ai/platform#3602 and reads as OTHERS
-// until that ships.
+// telemetry. The backend keeps recognized values via its KNOWN_EVENT_SOURCES
+// allowlist; unknown values bucket into "OTHERS", so "DEEPSEEK_HARNESS" must be
+// added to that allowlist for usage to surface by name (a one-line backend PR,
+// same pattern as the ZAPIER / STRANDS sources).
const SOURCE = "DEEPSEEK_HARNESS";
const DEFAULT_SEARCH_LIMIT = 10;
@@ -112,7 +108,7 @@ export function apply(ctx: Context, config: Config): void {
const stateFor = (session: object): SessionState => {
let state = sessionStates.get(session);
if (!state) {
- const lifecycle = createMemoryLifecycle({ recallHeading: USER_RECALL_HEADING });
+ const lifecycle = createMemoryLifecycle();
lifecycle.beginSession();
state = { lifecycle, messages: [] };
sessionStates.set(session, state);
@@ -202,9 +198,10 @@ export function apply(ctx: Context, config: Config): void {
ctx.tools.register(
defineTool({
name: "search_memory",
- description: USER_SEARCH_TOOL_DESCRIPTION,
+ description:
+ "Search the user's long-term Mem0 memory for facts relevant to a query. Use proactively before answering anything that may depend on what the user told you earlier.",
parameters: {
- query: { type: "string", description: USER_SEARCH_QUERY_DESCRIPTION, required: true },
+ query: { type: "string", description: "What to recall.", required: true },
limit: {
type: "integer",
description: `Max results to return (default ${DEFAULT_SEARCH_LIMIT}).`,
diff --git a/integrations/hermes-plugin-mem0/.gitignore b/integrations/hermes-plugin-mem0/.gitignore
deleted file mode 100644
index 00f2d38d8..000000000
--- a/integrations/hermes-plugin-mem0/.gitignore
+++ /dev/null
@@ -1,3 +0,0 @@
-__pycache__/
-*.pyc
-.venv/
diff --git a/integrations/hermes-plugin-mem0/LICENSE b/integrations/hermes-plugin-mem0/LICENSE
deleted file mode 100644
index 5ee05954c..000000000
--- a/integrations/hermes-plugin-mem0/LICENSE
+++ /dev/null
@@ -1,236 +0,0 @@
- 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 [2023] [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.
-
-Third-party software
---------------------
-
-hermes-plugin-mem0
-
-Mem0 contributions are licensed under the Apache License, Version 2.0.
-
-This plugin includes code from Nous Research's hermes-plugin-mem0:
-https://github.com/NousResearch/hermes-plugin-mem0
-Source commit: 3fc36950b2b7c19cdd81c6de99f10d2cbed850af
-
-The imported code retains the following MIT license and copyright notice:
-
-MIT License
-
-Copyright (c) 2025 Nous Research
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/integrations/hermes-plugin-mem0/README.md b/integrations/hermes-plugin-mem0/README.md
deleted file mode 100644
index ad4d2f87e..000000000
--- a/integrations/hermes-plugin-mem0/README.md
+++ /dev/null
@@ -1,131 +0,0 @@
-# Mem0 for Hermes Agent
-
-Persistent memory for [Hermes Agent](https://github.com/NousResearch/hermes-agent), powered by [Mem0](https://mem0.ai).
-
-This standalone plugin recalls relevant memories before a response and extracts facts from conversations afterward. It works alongside Hermes' file-based memory and supports Mem0 Cloud, a self-hosted Mem0 server, or the in-process OSS SDK.
-
-## Features
-
-- **Automatic recall and capture** across conversations.
-- **Four agent tools** to search, add, update, and delete memories.
-- **Three backend modes** with interactive setup through `hermes memory setup`.
-- **User-scoped memories** with agent and channel metadata on writes.
-
-## Setup
-
-### 1. Install
-
-Requires [Hermes Agent](https://github.com/NousResearch/hermes-agent) with memory-provider plugin support and Python 3.11 or later. After this directory is merged to Mem0's main branch:
-
-```bash
-hermes plugins install mem0ai/mem0/integrations/hermes-plugin-mem0
-hermes plugins enable mem0
-```
-
-Hermes installers with plugin dependency support install `mem0ai>=2.0.10,<3` and `httpx>=0.27,<1` from this directory's `pyproject.toml`. On older hosts such as Hermes v0.21.3, install those requirements into the **Hermes Python environment** explicitly. The OSS setup wizard installs additional provider packages as needed.
-
-> Hermes versions that still bundle Mem0 prefer the bundled provider. Use a Hermes release that has completed the standalone-provider migration; installing this plugin alone does not replace the bundled implementation. See [Existing users and migration](#existing-users-and-migration).
-
-### 2. Configure
-
-```bash
-hermes memory setup mem0
-```
-
-Run this in an interactive terminal and choose a backend:
-
-| Mode | What you need |
-|------|----------------|
-| **Platform** (default) | A Mem0 API key from [app.mem0.ai](https://app.mem0.ai/dashboard/api-keys) |
-| **Self-hosted server** | A running [Mem0 server](../../server), its URL, and its API key unless authentication is disabled |
-| **OSS** | An LLM, embedder, and vector store; no Mem0 API key needed |
-
-For a self-hosted server, choose **Self-hosted server** and enter its URL and API key. Requests use `X-API-Key` and the server's `/search` and `/memories` routes. Setting `host` selects this backend unless `mode` is `oss`.
-
-For the in-process SDK, choose **Open Source**. The wizard offers OpenAI or Ollama and local Qdrant or PGVector. Use manual configuration for custom OpenAI-compatible endpoints, deployment names, or a Qdrant server. OSS does not use Mem0 Cloud; data still goes to whichever model services you configure. Run setup again to switch modes. When switching to Platform, remove any stale `MEM0_HOST` setting from the environment and profile `.env`.
-
-Desktop sessions in the same process and profile share local Qdrant storage when their OSS settings match. Operations are serialized, and storage closes after the last session releases it. Conflicting settings are rejected without changing existing memories; close the active sessions before changing models or credentials. Use a Qdrant server or the self-hosted Mem0 HTTP API when separate processes (for example, CLI and Desktop together) need the same store.
-
-Hermes hosts whose `hermes memory setup --help` lists only a provider argument reject options such as `--mode`, `--host`, and `--oss-llm` before the plugin runs. Use the interactive command above, or the [manual profile configuration](https://docs.mem0.ai/integrations/hermes) for unattended setup. Redirected input cannot select the mode picker; it falls back to Platform.
-
-### 3. Verify
-
-```bash
-hermes memory status
-```
-
-Start a fresh Hermes conversation and ask it to remember a fact, then search for that fact in a later session using the same user identity.
-
-## Tools
-
-| Tool | Description | Parameters |
-|------|-------------|------------|
-| `mem0_search` | Search memories by meaning | `query`, optional `top_k` (default 10, max 50) and `rerank` (Platform only) |
-| `mem0_add` | Store text verbatim, without fact extraction | `content` |
-| `mem0_update` | Update a memory's text | `memory_id`, `text` |
-| `mem0_delete` | Delete a memory | `memory_id` |
-
-## Configuration
-
-Settings live in `$HERMES_HOME/mem0.json`; the default Hermes home is `~/.hermes`. Setup normally stores API keys in that profile's `.env`. Distinct OpenAI LLM/embedder keys and database credentials are stored in the OSS configuration. Setup writes both files atomically with owner-only permissions.
-
-| Key | Default | Description |
-|-----|---------|-------------|
-| `mode` | `platform` | `platform` for Cloud/server routing, or `oss` for the in-process SDK |
-| `host` | unset | Self-hosted server URL; ignored in OSS mode |
-| `user_id` | gateway user ID, then `hermes-user` | Set a stable ID to share memories across gateways |
-| `agent_id` | `hermes` | Agent identifier attached to writes |
-| `rerank` | `false` | Platform reranking for automatic recall and tool searches that omit `rerank` |
-| `sync_max_chars` | `450` | Maximum characters per user/assistant message sent for automatic extraction |
-| `oss` | `{}` | OSS LLM, embedder, and vector-store configuration written by setup |
-
-`MEM0_MODE`, `MEM0_HOST`, `MEM0_USER_ID`, and `MEM0_AGENT_ID` provide environment defaults; non-empty file settings override them. `MEM0_API_KEY` supplies the Cloud or server key when `api_key` is not set in the file.
-
-An explicit `user_id` other than `hermes-user` takes precedence over a gateway's native user ID. Searches use that user identity across sessions; writes attach `agent_id` and `metadata.channel`.
-
-## Automatic recall and capture
-
-Recall waits up to three seconds for memories relevant to the current message. If results are late, the model can still call `mem0_search`.
-
-After a turn, a background worker sends the user message and assistant response for extraction. Each message is truncated to **450 characters by default in every mode**, preferring a sentence boundary. Increase `sync_max_chars` to suit your model's context limit. Explicit `mem0_add` calls store their supplied text verbatim.
-
-Capture is best effort: if the previous sync remains busy after a five-second wait, the new turn is skipped. There is no durable queue. Five consecutive backend failures pause calls for two minutes before retrying.
-
-Graceful shutdown waits for active recall and capture workers before closing the backend, including at Python process exit. Backend network timeouts still apply: self-hosted HTTP capture has a 120-second read timeout and a 30-second connection timeout; other self-hosted HTTP operations use 30 seconds. Forced termination, including Hermes' 30-second exit watchdog, can still interrupt pending writes.
-
-## Existing users and migration
-
-Keep `memory.provider: mem0`, your existing `mem0.json`, `MEM0_*` settings, user identity, and OSS storage paths. Moving the plugin does not require moving memories or rerunning setup.
-
-Automatic migration also requires coordination in Hermes:
-
-1. A Hermes build containing [migration support from PR #114569](https://github.com/NousResearch/hermes-agent/pull/114569).
-2. An approved catalog entry named `mem0`, pointing to `https://github.com/mem0ai/mem0`, with `subdir: integrations/hermes-plugin-mem0` and a reviewed full commit SHA.
-3. Removal of Hermes' bundled Mem0 provider, which otherwise takes precedence.
-
-With those in place, Hermes can install a missing configured provider during `hermes update` or at agent startup. Startup installation respects `security.allow_lazy_installs`; disabled or offline installation requires manual action. Merging this directory alone does not register the catalog entry or complete rollout.
-
-The plugin supports CLI setup/status. It does not include a Desktop configuration panel or provider-specific CLI commands.
-
-## Troubleshooting
-
-- **Mem0 unavailable:** run `hermes memory status`. Check the API key and backend connectivity; after five consecutive failures the circuit breaker waits two minutes.
-- **Memories missing:** confirm the same user identity across sessions and check `sync_max_chars`. Automatic extraction may omit facts; use `mem0_add` to store exact text.
-- **OSS connection refused:** check the configured model/vector service, or filesystem permissions for local Qdrant.
-- **Embedding dimension mismatch:** initialization fails without deleting existing data. Restore the previous embedding model/dimensions, or use a new collection and migrate data explicitly.
-
-## Development
-
-From the Mem0 repository root, with `ruff` and `isort` installed:
-
-```bash
-ruff check integrations/hermes-plugin-mem0
-isort --check-only --profile black integrations/hermes-plugin-mem0
-```
-
-Validate changes in an isolated Hermes profile using live CLI and Desktop sessions. Check memory
-add/search/update/delete, automatic capture and recall, overlapping Desktop sessions, and persistence after restart.
-
-## License
-
-[Apache-2.0](LICENSE) for Mem0 contributions. Includes code from [Nous Research's standalone Mem0 provider](https://github.com/NousResearch/hermes-plugin-mem0/tree/3fc36950b2b7c19cdd81c6de99f10d2cbed850af) under MIT; its original license and copyright notice are preserved in the third-party section of [LICENSE](LICENSE).
diff --git a/integrations/hermes-plugin-mem0/__init__.py b/integrations/hermes-plugin-mem0/__init__.py
deleted file mode 100644
index 1ab504753..000000000
--- a/integrations/hermes-plugin-mem0/__init__.py
+++ /dev/null
@@ -1,504 +0,0 @@
-"""Mem0 memory plugin โ MemoryProvider interface.
-
-Server-side fact extraction and semantic search via the Mem0 Platform API (cloud), a
-self-hosted Mem0 server (MEM0_HOST, HTTP), or OSS Memory. Secrets live in $HERMES_HOME/.env
-(MEM0_API_KEY, MEM0_HOST); settings in $HERMES_HOME/mem0.json via `hermes memory setup`:
-mode ("platform"|"oss"), host, user_id (canonical id across gateways; unset โ gateway-native
-id), agent_id. MEM0_* env vars remain a fallback.
-"""
-
-from __future__ import annotations
-
-import atexit
-import json
-import logging
-import threading
-import time
-from contextlib import suppress
-from pathlib import Path
-from typing import Any, Dict, List
-
-from agent.memory_provider import MemoryProvider, spawn_context_thread
-from agent.secret_scope import get_secret
-from tools.registry import tool_error
-from utils import atomic_json_write, read_json_or_empty
-
-logger = logging.getLogger(__name__)
-
-# Circuit breaker: after _BREAKER_THRESHOLD consecutive failures, pause API
-# calls for _BREAKER_COOLDOWN_SECS to avoid hammering a down server.
-_BREAKER_THRESHOLD, _BREAKER_COOLDOWN_SECS, _PREFETCH_WAIT_SECS = 5, 120, 3
-_CLIENT_ERROR_TYPES = ("MemoryNotFoundError", "ValidationError")
-# Placeholder user_id. initialize() treats it as "no operator-configured user_id"
-# so legacy mem0.json files written by the wizard don't override gateway-native ids.
-_DEFAULT_USER_ID = "hermes-user"
-
-# sync_turn sends the whole turn to the backend for fact extraction. OSS embedding
-# models often have small context windows (bge-small-zh-v1.5: 512 tokens โ 500 chars;
-# jina-embeddings-v3: 8192), and oversized turns make backend.add() raise โ Ollama
-# answers HTTP 500, hosted APIs return INPUT_TOKEN_LIMIT_EXCEEDED โ which _try only
-# logs, silently dropping the turn's memory extraction. Cap each message up front.
-# The default fits a 512-token embedder (measured: 450 OK, 600 -> HTTP 500 on
-# bge-small-zh-v1.5:f16); ``sync_max_chars`` in mem0.json raises it for larger windows.
-_SYNC_MSG_MAX_CHARS = 450
-
-
-# Sentence ends recognized when trimming a synced message. Deliberately unordered:
-# the LAST boundary of ANY kind wins, so one CJK stop early in a mixed-script turn
-# cannot outrank a Latin stop near the end of the window. ``".\n"`` is not listed โ
-# its index can never exceed the bare ``"."`` it starts with.
-_SYNC_SENTENCE_ENDS = ("ใ", "๏ผ", "๏ผ", ".", "!", "?")
-
-
-def _truncate_for_sync(text: str, max_len: int = _SYNC_MSG_MAX_CHARS) -> str:
- """Cap a synced message at its last sentence boundary within ``max_len``.
-
- Short messages pass through unchanged; long ones keep the last complete
- sentence inside the window so fact extraction still sees coherent statements,
- with a hard cut as fallback when no boundary exists (or one only appears in
- the first third of the window, which usually means unsegmented input).
- """
- if len(text) <= max_len:
- return text
- window = text[:max_len]
- cut = max(window.rfind(sep) for sep in _SYNC_SENTENCE_ENDS)
- if cut > max_len // 3:
- return text[:cut + 1]
- return text[:max_len]
-
-
-def _is_client_error(exc: Exception) -> bool:
- """True for user-caused errors (bad ID, not found) that should NOT trip circuit breaker."""
- err_str = str(exc).lower()
- return type(exc).__name__ in _CLIENT_ERROR_TYPES or any(s in err_str for s in ("404", "not found", "valid uuid"))
-
-
-def _load_config() -> dict:
- """Env vars provide defaults; $HERMES_HOME/mem0.json overrides individual keys.
- Layering avoids a silent failure when the JSON file exists but lacks fields
- like ``api_key`` that the user set in ``.env``."""
- from hermes_constants import get_hermes_home
-
- # Identity (user/agent id), host and mode are .env values like the key: read them through the
- # profile scope too, or a secondary profile's memories land in the default profile's account.
- # A scope-less multiplex caller raises here on purpose โ that is a spawn-site bug, and
- # swallowing it would silently route the turn's memories to the default profile.
- config = {"mode": get_secret("MEM0_MODE", "") or "platform", "host": get_secret("MEM0_HOST", "") or "",
- "agent_id": get_secret("MEM0_AGENT_ID", "") or "hermes", "oss": {}}
- if user_id := get_secret("MEM0_USER_ID", ""): # only when explicitly configured, so initialize() can fall back to the gateway-native id
- config["user_id"] = user_id
- file_cfg = read_json_or_empty(get_hermes_home() / "mem0.json")
- config.update({k: v for k, v in file_cfg.items() if v is not None and v != ""})
- # MEM0_API_KEY authenticates the Platform and self-hosted HTTP backends; pure OSS mode builds its
- # backend from the local ``oss`` config and has no platform credential to resolve, so a profile
- # scope WITHOUT the key must still load an OSS config (#99121 as it stands today: the caller is
- # scoped, the scope is just empty). Decided after mem0.json overrode the env defaults because
- # the file may be what selects ``oss``. Scope-less callers already raised above.
- if config.get("mode", "platform") == "oss":
- config.setdefault("api_key", "")
- elif not config.get("api_key"):
- config["api_key"] = get_secret("MEM0_API_KEY", "")
- return config
-
-
-def _schema(name: str, description: str, properties: dict[str, tuple[str, str]], required: list[str]) -> dict:
- props = {k: {"type": t, "description": d} for k, (t, d) in properties.items()}
- return {"name": name, "description": description, "parameters": {"type": "object", "properties": props, "required": required}}
-
-
-TOOL_SCHEMAS = [
- _schema("mem0_search", "Search the user's memories by meaning; returns facts ranked by relevance. Use this before answering any question that may depend on what you know about the user (preferences, facts, history, people, projects, past decisions). For multi-part or multi-hop questions, call it several times โ vary the wording and run follow-up searches on what earlier results reveal; one search is rarely enough.",
- {"query": ("string", "What to search for."), "top_k": ("integer", "Max results (default: 10, max: 50)."), "rerank": ("boolean", "Rerank results for relevance (default: false, platform mode only).")}, ["query"]),
- _schema("mem0_add", "Store a durable fact about the user, verbatim (no LLM extraction). Call this the moment the user states a lasting preference, correction, decision, or personal detail worth recalling on future turns โ don't wait to be asked to remember. Skip transient chit-chat and facts you've already stored.",
- {"content": ("string", "The fact to store.")}, ["content"]),
- _schema("mem0_update", "Replace the text of an existing memory by its ID (take the ID from a mem0_search result). Use when a stored fact has changed or was wrong โ correct it in place instead of adding a duplicate.",
- {"memory_id": ("string", "Memory UUID to update."), "text": ("string", "New text content.")}, ["memory_id", "text"]),
- _schema("mem0_delete", "Delete a memory by its ID (take the ID from a mem0_search result). Use when a stored fact is obsolete or the user asks you to forget it; prefer mem0_update if the fact merely changed.",
- {"memory_id": ("string", "Memory UUID to delete.")}, ["memory_id"]),
-]
-
-_PROMPT_BODY = (
- "You have persistent memory of this user from past conversations. You should call mem0_search before answering anything that could depend on prior context (the user's preferences, facts, history, people, projects, or earlier decisions) โ do not rely on the chat window alone, and do not assume you have no memory.\n"
- "For multi-part or multi-hop questions, run several searches with different wording/angles and follow-up searches on what the first results surface; one search is rarely enough. Keep searching until you have every fact the question needs before you answer.\n"
- "Tools: mem0_search to find memories, mem0_add to store facts, mem0_update and mem0_delete to manage by ID."
-)
-
-
-class Mem0MemoryProvider(MemoryProvider):
- """Mem0 memory with server-side extraction and semantic search (platform, self-hosted or OSS)."""
-
- def __init__(self):
- self._config = self._backend = self._sync_thread = self._prefetch_thread = None
- self._mode, self._api_key, self._host, self._user_id, self._agent_id = "platform", "", "", _DEFAULT_USER_ID, "hermes"
- self._rerank_default, self._channel = False, "cli" # channel = gateway name (cli/telegram/discord/...)
- self._sync_max_chars = _SYNC_MSG_MAX_CHARS
- self._prefetch_query = self._prefetch_result = ""
- self._prefetch_done = self._atexit_registered = False
- self._consecutive_failures, self._breaker_open_until = 0, 0.0 # circuit breaker state
- self._breaker_lock, self._sync_lock, self._prefetch_lock = threading.Lock(), threading.Lock(), threading.Lock()
-
- @property
- def name(self) -> str:
- return "mem0"
-
- def is_available(self) -> bool:
- cfg = _load_config()
- if cfg.get("mode", "platform") == "oss":
- return bool(cfg.get("oss", {}).get("vector_store"))
- return bool(cfg.get("api_key") or cfg.get("host")) # platform needs a key; self-hosted a host (key optional with AUTH_DISABLED)
-
- def save_config(self, values, hermes_home):
- """Merge-write config to $HERMES_HOME/mem0.json."""
- config_path = Path(hermes_home) / "mem0.json"
- atomic_json_write(config_path, {**read_json_or_empty(config_path), **values}, mode=0o600)
-
- def get_config_schema(self):
- cfg = _load_config()
- api_key_required = cfg.get("mode", "platform") != "oss" and not cfg.get("host")
- return [
- {"key": "api_key", "description": "Mem0 Platform API key", "secret": True, "required": api_key_required, "env_var": "MEM0_API_KEY", "url": "https://app.mem0.ai"},
- {"key": "host", "description": "Self-hosted Mem0 server URL (leave blank for cloud)", "required": False, "env_var": "MEM0_HOST"},
- {"key": "user_id", "description": "User identifier", "default": "hermes-user"},
- {"key": "agent_id", "description": "Agent identifier", "default": "hermes"},
- {"key": "rerank", "description": "Enable reranking for recall", "default": "false", "choices": ["true", "false"]},
- ]
-
- def post_setup(self, hermes_home: str, config: dict) -> None:
- from ._setup import post_setup
- post_setup(hermes_home, config)
-
- def _oss_hint(self, template: str, default: str = "vector store") -> str:
- """OSS-only hint; ``{vs}`` is the configured vector-store provider. "" in other modes."""
- return template.format(vs=self._config.get("oss", {}).get("vector_store", {}).get("provider", default)) if self._mode == "oss" else ""
-
- def _create_backend(self):
- # Lazy-install the mem0 SDK before the backend imports it (honors security.allow_lazy_installs);
- # on failure the backend import raises the canonical error, captured below.
- with suppress(Exception):
- pass # dependencies come from pyproject.toml (installed by Hermes on install/enable/update)
- try:
- from . import _backend
- if self._mode == "oss":
- return _backend.OSSBackend(self._config.get("oss", {}))
- return _backend.SelfHostedBackend(self._api_key, self._host) if self._host else _backend.PlatformBackend(self._api_key)
- except Exception as e:
- logger.error("Mem0 backend failed to initialize (%s mode): %s", self._mode, e)
- self._init_error = str(e)
- return None
-
- def _is_breaker_open(self) -> bool:
- """True while the breaker is tripped; an expired cooldown resets the failure count."""
- with self._breaker_lock:
- if self._consecutive_failures >= _BREAKER_THRESHOLD and time.monotonic() < self._breaker_open_until:
- return True
- if self._consecutive_failures >= _BREAKER_THRESHOLD:
- self._consecutive_failures = 0
- return False
-
- def _format_error(self, prefix: str, exc: Exception) -> str:
- msg = f"{prefix}: {exc}"
- if any(s in str(exc).lower() for s in ("connection", "refused", "timeout")):
- msg += self._oss_hint(" (check that {vs} is running)")
- return msg
-
- def _record_success(self):
- with self._breaker_lock:
- self._consecutive_failures = 0
-
- def _record_failure(self):
- with self._breaker_lock:
- self._consecutive_failures = count = self._consecutive_failures + 1
- if count >= _BREAKER_THRESHOLD:
- self._breaker_open_until = time.monotonic() + _BREAKER_COOLDOWN_SECS
- if count >= _BREAKER_THRESHOLD:
- hint = self._oss_hint(" Check that your {vs} vector store is running and reachable.", "unknown")
- logger.warning("Mem0 circuit breaker tripped after %d consecutive failures. Pausing API calls for %ds.%s", count, _BREAKER_COOLDOWN_SECS, hint)
-
- def _try(self, call, log, msg: str):
- """Background-path wrapper: run ``call`` under the breaker; on error log ``msg`` and return None."""
- try:
- result = call()
- except Exception as e:
- self._record_failure()
- log(msg, e)
- return None
- self._record_success()
- return result
-
- def initialize(self, session_id: str, **kwargs) -> None:
- self._config = cfg = _load_config()
- self._mode, self._api_key, self._host, self._agent_id = cfg.get("mode", "platform"), cfg.get("api_key", ""), cfg.get("host", ""), cfg.get("agent_id", "hermes")
- # user_id precedence: operator-configured (env/mem0.json) > gateway-native id (kwargs) > _DEFAULT_USER_ID.
- # The literal placeholder counts as unset so wizard users still get gateway-native ids.
- configured = cfg.get("user_id")
- self._user_id = (None if configured == _DEFAULT_USER_ID else configured) or kwargs.get("user_id") or _DEFAULT_USER_ID
- # Persisted rerank preference: default for mem0_search when the model omits ``rerank``. Platform-only.
- _rr = cfg.get("rerank", False)
- self._rerank_default = _rr.lower() in ("true", "1", "yes") if isinstance(_rr, str) else bool(_rr)
- self._channel = kwargs.get("platform") or "cli"
- try:
- self._sync_max_chars = int(cfg.get("sync_max_chars") or _SYNC_MSG_MAX_CHARS)
- except (ValueError, TypeError):
- self._sync_max_chars = _SYNC_MSG_MAX_CHARS
- self._backend = self._create_backend()
- if self._backend and not self._atexit_registered:
- atexit.register(self.shutdown)
- self._atexit_registered = True
-
- def _search(self, query: str, top_k: int = 10, rerank: bool = False, backend=None) -> list:
- # Scoped to user_id only โ by design โ so recall surfaces memories from any gateway/agent under this
- # principal; writes attach agent_id and metadata.channel so narrower views remain possible at query time.
- return (backend or self._backend).search(query, filters={"user_id": self._user_id}, top_k=top_k, rerank=rerank)
-
- def _add(self, messages: list, infer: bool):
- metadata = {"channel": self._channel} if self._channel else {}
- return self._backend.add(messages, user_id=self._user_id, agent_id=self._agent_id, infer=infer, metadata=metadata)
-
- def system_prompt_block(self) -> str:
- # Mirror _create_backend precedence (oss > host > platform). Rerank is a Mem0 Platform feature only.
- mode_label = "OSS (self-hosted)" if self._mode == "oss" else "self-hosted (HTTP API)" if self._host else "platform (cloud API)"
- rerank_note = " Rerank is available on search." if (self._mode == "platform" and not self._host) else ""
- return f"# Mem0 Memory\nActive. Mode: {mode_label}. User: {self._user_id}.\n{_PROMPT_BODY}{rerank_note}"
-
- def on_turn_start(self, turn_number: int, message: str, **kwargs) -> None:
- self._start_prefetch(message)
-
- def _consume_prefetch_result(self, query: str) -> str | None:
- """Pop the finished prefetch body for ``query`` (None if absent or still running)."""
- with self._prefetch_lock:
- if self._prefetch_query != query or not self._prefetch_done:
- return None
- result, self._prefetch_result, self._prefetch_done = self._prefetch_result, "", False
- return result
-
- def _start_prefetch(self, query: str) -> None:
- backend = self._backend
- if not query or backend is None or self._is_breaker_open():
- return
-
- def _run():
- results = self._try(lambda: self._search(query, rerank=self._rerank_default, backend=backend), logger.debug, "Mem0 prefetch failed: %s")
- lines = [r.get("memory", "") for r in (results or []) if r.get("memory")]
- body = "## Mem0 Memory\n" + "\n".join(f"- {line}" for line in lines) if lines else ""
- with self._prefetch_lock:
- if self._prefetch_query == query:
- self._prefetch_result, self._prefetch_done = body, True
-
- with self._prefetch_lock:
- if self._prefetch_query == query and (self._prefetch_done or (self._prefetch_thread and self._prefetch_thread.is_alive())):
- return
- self._prefetch_query, self._prefetch_result, self._prefetch_done = query, "", False
- self._prefetch_thread = spawn_context_thread(_run, name="mem0-prefetch")
- self._prefetch_thread.start()
-
- def prefetch(self, query: str, *, session_id: str = "") -> str:
- """Recall memories for the CURRENT question with a short hot-path wait."""
- if (cached := self._consume_prefetch_result(query)) is not None:
- return cached
- self._start_prefetch(query)
- with self._prefetch_lock:
- thread = self._prefetch_thread if self._prefetch_query == query else None
- if thread:
- thread.join(timeout=_PREFETCH_WAIT_SECS)
- return self._consume_prefetch_result(query) or "" # slow backend: skip injection; mem0_search remains the backstop
-
- def sync_turn(self, user_content: str, assistant_content: str, *, session_id: str = "") -> None:
- """Send the turn to Mem0 for server-side fact extraction (non-blocking)."""
- if self._backend is None or self._is_breaker_open():
- return
-
- def _sync():
- if self._backend is not None:
- messages = [
- {"role": "user", "content": _truncate_for_sync(user_content, self._sync_max_chars)},
- {"role": "assistant", "content": _truncate_for_sync(assistant_content, self._sync_max_chars)},
- ]
- self._try(lambda: self._add(messages, infer=True), logger.warning, "Mem0 sync failed: %s")
-
- with self._sync_lock:
- prev = self._sync_thread
- if prev and prev.is_alive():
- prev.join(timeout=5.0)
- if prev.is_alive():
- return
- with self._sync_lock:
- self._sync_thread = spawn_context_thread(_sync, name="mem0-sync")
- self._sync_thread.start()
-
- def get_tool_schemas(self) -> List[Dict[str, Any]]:
- return list(TOOL_SCHEMAS)
-
- # -- tool handlers: (required params, error label, body, client-error policy) ---
- # Client errors (bad ID / not found) never trip the breaker, except for mem0_add
- # where they count as failures; update/delete answer them with "Memory not found".
-
- def _tool_search(self, args: dict) -> str:
- top_k = max(1, min(int(args.get("top_k", 10)), 50))
- rerank_raw = args.get("rerank", self._rerank_default)
- rerank = rerank_raw.lower() not in ("false", "0", "no") if isinstance(rerank_raw, str) else bool(rerank_raw)
- results = self._search(args["query"], top_k, rerank)
- if not results:
- return json.dumps({"result": "No relevant memories found."})
- items = [{"id": r.get("id"), "memory": r.get("memory", ""), "score": r.get("score", 0)} for r in results]
- return json.dumps({"results": items, "count": len(items)})
-
- def _tool_add(self, args: dict) -> str:
- result = self._add([{"role": "user", "content": args["content"]}], infer=False)
- event_id = result.get("event_id") if isinstance(result, dict) else None
- # Cloud add is async (server-side extraction); OSS and self-hosted store synchronously.
- msg = "Fact stored." if (self._mode == "oss" or self._host) else "Fact queued for storage."
- return json.dumps({"result": msg, "event_id": event_id})
-
- def _ensure_owns_memory(self, memory_id: str) -> None:
- """Reject a mutation on a memory that doesn't belong to the caller's user_id."""
- memory = self._backend.get(memory_id)
- if not memory:
- raise ValueError(f"Memory not found: {memory_id}")
- owner = memory.get("user_id") if isinstance(memory, dict) else None
- if owner and owner != self._user_id:
- raise PermissionError(f"Memory {memory_id} does not belong to this user.")
-
- def _tool_update(self, args: dict) -> str:
- self._ensure_owns_memory(args["memory_id"])
- return json.dumps(self._backend.update(args["memory_id"], args["text"]))
-
- def _tool_delete(self, args: dict) -> str:
- self._ensure_owns_memory(args["memory_id"])
- return json.dumps(self._backend.delete(args["memory_id"]))
-
- _TOOL_HANDLERS = {
- "mem0_search": (("query",), "Search failed", _tool_search, "skip"),
- "mem0_add": (("content",), "Failed to store", _tool_add, "count"),
- "mem0_update": (("memory_id", "text"), "Update failed", _tool_update, "not_found"),
- "mem0_delete": (("memory_id",), "Delete failed", _tool_delete, "not_found"),
- }
-
- def handle_tool_call(self, tool_name: str, args: dict, **kwargs) -> str:
- if self._backend is None:
- err = getattr(self, "_init_error", "unknown error")
- return json.dumps({"error": f"Mem0 backend not initialized: {err}.{self._oss_hint(' Check that {vs} is running and reachable.')}"})
- if self._is_breaker_open():
- return json.dumps({"error": f"Mem0 temporarily unavailable (multiple consecutive failures). Will retry automatically.{self._oss_hint(' Check that your {vs} is running.')}"})
- if tool_name not in self._TOOL_HANDLERS:
- return tool_error(f"Unknown tool: {tool_name}")
- required, label, body, on_client_error = self._TOOL_HANDLERS[tool_name]
- if not isinstance(args, dict):
- return tool_error("Tool arguments must be an object")
- if missing := next((k for k in required if not isinstance(args.get(k), str) or not args[k].strip()), None):
- return tool_error(f"Missing or invalid required parameter: {missing}")
- if tool_name == "mem0_search":
- try:
- int(args.get("top_k", 10))
- except (TypeError, ValueError, OverflowError):
- return tool_error("top_k must be an integer")
- try:
- result = body(self, args)
- except PermissionError as e:
- return tool_error(str(e))
- except Exception as e:
- client = _is_client_error(e)
- if client and on_client_error == "not_found":
- return tool_error(f"Memory not found: {args['memory_id']}")
- if not client or on_client_error == "count":
- self._record_failure()
- return tool_error(self._format_error(label, e))
- self._record_success()
- return result
-
- def _shutdown_backend(self):
- with suppress(Exception):
- if self._backend:
- self._backend.close()
- self._backend = None
-
- def shutdown(self) -> None:
- for t in (self._prefetch_thread, self._sync_thread):
- if t and t.is_alive():
- # Extraction can outlast five seconds. Closing storage underneath it
- # loses the turn; let the backend's network timeouts bound the drain.
- t.join()
- self._shutdown_backend()
-
-
-def register(ctx) -> None:
- """Register Mem0 as a memory provider plugin."""
- ctx.register_memory_provider(Mem0MemoryProvider())
-
-
-# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
-# Names external plugins imported from this module before the Sep 2026 decomposition.
-# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
-# The whole block is removed by reverting the commit that added it.
-
-ADD_SCHEMA = {
- "name": "mem0_add",
- "description": (
- "Store a durable fact about the user, verbatim (no LLM extraction). "
- "Call this the moment the user states a lasting preference, correction, "
- "decision, or personal detail worth recalling on future turns โ don't "
- "wait to be asked to remember. Skip transient chit-chat and facts you've "
- "already stored."
- ),
- "parameters": {
- "type": "object",
- "properties": {
- "content": {"type": "string", "description": "The fact to store."},
- },
- "required": ["content"],
- },
-}
-
-DELETE_SCHEMA = {
- "name": "mem0_delete",
- "description": (
- "Delete a memory by its ID (take the ID from a mem0_search "
- "result). Use when a stored fact is obsolete or the user asks you to "
- "forget it; prefer mem0_update if the fact merely changed."
- ),
- "parameters": {
- "type": "object",
- "properties": {
- "memory_id": {"type": "string", "description": "Memory UUID to delete."},
- },
- "required": ["memory_id"],
- },
-}
-
-SEARCH_SCHEMA = {
- "name": "mem0_search",
- "description": (
- "Search the user's memories by meaning; returns facts ranked by "
- "relevance. Use this before answering any question that may depend on "
- "what you know about the user (preferences, facts, history, people, "
- "projects, past decisions). For multi-part or multi-hop questions, "
- "call it several times โ vary the wording and run follow-up searches "
- "on what earlier results reveal; one search is rarely enough."
- ),
- "parameters": {
- "type": "object",
- "properties": {
- "query": {"type": "string", "description": "What to search for."},
- "top_k": {"type": "integer", "description": "Max results (default: 10, max: 50)."},
- "rerank": {"type": "boolean", "description": "Rerank results for relevance (default: false, platform mode only)."},
- },
- "required": ["query"],
- },
-}
-
-UPDATE_SCHEMA = {
- "name": "mem0_update",
- "description": (
- "Replace the text of an existing memory by its ID (take the ID from a "
- "mem0_search result). Use when a stored fact has changed "
- "or was wrong โ correct it in place instead of adding a duplicate."
- ),
- "parameters": {
- "type": "object",
- "properties": {
- "memory_id": {"type": "string", "description": "Memory UUID to update."},
- "text": {"type": "string", "description": "New text content."},
- },
- "required": ["memory_id", "text"],
- },
-}
-# ---- END PLUGIN-COMPAT ----
diff --git a/integrations/hermes-plugin-mem0/_backend.py b/integrations/hermes-plugin-mem0/_backend.py
deleted file mode 100644
index 455750207..000000000
--- a/integrations/hermes-plugin-mem0/_backend.py
+++ /dev/null
@@ -1,336 +0,0 @@
-"""Backend abstraction for Mem0 Platform and OSS modes."""
-
-from __future__ import annotations
-
-import logging
-import os
-from abc import ABC, abstractmethod
-from contextlib import closing, nullcontext, suppress
-from copy import deepcopy
-from dataclasses import dataclass, field
-from threading import RLock
-from typing import Any
-
-logger = logging.getLogger(__name__)
-
-
-def _add_kwargs(user_id: str, agent_id: str, infer: bool, metadata: dict | None) -> dict[str, Any]:
- return {"user_id": user_id, "agent_id": agent_id, "infer": infer, **({"metadata": metadata} if metadata else {})}
-
-
-def _unwrap_results(response: Any) -> list:
- """Normalize API response โ extract results list from dict or pass through."""
- return response.get("results", []) if isinstance(response, dict) else response if isinstance(response, list) else []
-
-
-class Mem0Backend(ABC):
- """Unified interface over Platform (MemoryClient), self-hosted (HTTP) and OSS (Memory) backends.
- update()/delete() are template methods: subclasses implement raw ``_update``/``_delete``."""
-
- @abstractmethod
- def search(self, query: str, *, filters: dict, top_k: int = 10, rerank: bool = False) -> list[dict]: ...
- @abstractmethod
- def add(self, messages: list, *, user_id: str, agent_id: str, infer: bool = False, metadata: dict | None = None) -> dict: ...
- @abstractmethod
- def get(self, memory_id: str) -> dict | None: ...
- @abstractmethod
- def _update(self, memory_id: str, text: str) -> None: ...
- @abstractmethod
- def _delete(self, memory_id: str) -> None: ...
-
- def update(self, memory_id: str, text: str) -> dict:
- self._update(memory_id, text)
- return {"result": "Memory updated.", "memory_id": memory_id}
-
- def delete(self, memory_id: str) -> dict:
- self._delete(memory_id)
- return {"result": "Memory deleted.", "memory_id": memory_id}
-
- def close(self) -> None:
- pass
-
-
-class PlatformBackend(Mem0Backend):
- """Wraps mem0.MemoryClient for Mem0 Platform (cloud API)."""
-
- def __init__(self, api_key: str):
- from mem0 import MemoryClient
- self._client = MemoryClient(api_key=api_key)
-
- def search(self, query: str, *, filters: dict, top_k: int = 10, rerank: bool = False) -> list[dict]:
- return _unwrap_results(self._client.search(query, filters=filters, top_k=top_k, rerank=rerank))
-
- def add(self, messages: list, *, user_id: str, agent_id: str, infer: bool = False, metadata: dict | None = None) -> dict:
- return self._client.add(messages, **_add_kwargs(user_id, agent_id, infer, metadata))
-
- def get(self, memory_id: str) -> dict | None:
- return self._client.get(memory_id)
-
- def _update(self, memory_id: str, text: str) -> None:
- self._client.update(memory_id=memory_id, text=text)
-
- def _delete(self, memory_id: str) -> None:
- self._client.delete(memory_id=memory_id)
-
-
-class SelfHostedBackend(Mem0Backend):
- """Direct HTTP backend for a self-hosted Mem0 server (the FastAPI ``server/``).
- mem0.MemoryClient is hardwired to the cloud API (``Authorization: Token``, ``GET /v1/ping/`` in ``__init__``),
- so this speaks the server's real contract: ``X-API-Key`` auth and the ``/memories`` / ``/search`` routes."""
-
- def __init__(self, api_key: str, host: str, transport=None):
- import httpx
- headers = {"Content-Type": "application/json", **({"X-API-Key": api_key} if api_key else {})} # key omitted only for AUTH_DISABLED servers
- # Connect-level retries keep one dropped SYN from counting toward the breaker. ``transport`` is injectable for tests.
- self._client = httpx.Client(base_url=host.rstrip("/"), headers=headers, timeout=30.0, transport=transport or httpx.HTTPTransport(retries=2))
- self._capture_timeout = httpx.Timeout(120.0, connect=30.0)
-
- def _json(self, method: str, path: str, **kwargs) -> Any:
- resp = self._client.request(method, path, **kwargs)
- resp.raise_for_status()
- return resp.json() if resp.content else {}
-
- def search(self, query: str, *, filters: dict, top_k: int = 10, rerank: bool = False) -> list[dict]:
- # rerank is platform-only; the self-hosted /search ignores it. user_id belongs in filters (top-level is deprecated).
- return _unwrap_results(self._json("POST", "/search", json={"query": query, "top_k": top_k, **({"filters": filters} if filters else {})}))
-
- def add(self, messages: list, *, user_id: str, agent_id: str, infer: bool = False, metadata: dict | None = None) -> dict:
- # Server-side extraction takes longer than a search or verbatim write.
- return self._json("POST", "/memories", json={"messages": messages, **_add_kwargs(user_id, agent_id, infer, metadata)},
- timeout=self._capture_timeout if infer else self._client.timeout)
-
- def get(self, memory_id: str) -> dict | None:
- return self._json("GET", f"/memories/{memory_id}")
-
- def _update(self, memory_id: str, text: str) -> None:
- self._json("PUT", f"/memories/{memory_id}", json={"text": text})
-
- def _delete(self, memory_id: str) -> None:
- self._json("DELETE", f"/memories/{memory_id}")
-
- def close(self) -> None:
- with suppress(Exception):
- self._client.close()
-
-
-_DIRECT_OPENAI_PROVIDER = "hermes_openai"
-_DIRECT_OPENAI_CLASS_PATH = f"{__package__}._openai_llm.DirectOpenAILLM"
-
-
-@dataclass
-class _LocalQdrantMemory:
- memory: Any
- config: dict
- profile: str
- lock: Any = field(default_factory=RLock)
- users: int = 1
-
-
-_LOCAL_QDRANT_MEMORIES: dict[str, _LocalQdrantMemory] = {}
-_LOCAL_QDRANT_LOCK = RLock()
-
-
-def _register_direct_openai_provider() -> None:
- """Register Hermes' OpenAI-only Mem0 LLM provider once per factory."""
- from mem0.configs.llms.openai import OpenAIConfig
- from mem0.utils.factory import LlmFactory
- provider_map = getattr(LlmFactory, "provider_to_class", None)
- register_provider = getattr(LlmFactory, "register_provider", None)
- if not isinstance(provider_map, dict) or not callable(register_provider):
- raise RuntimeError("mem0 LlmFactory does not support the provider registration required for the Hermes OpenAI OSS backend")
- if provider_map.get(_DIRECT_OPENAI_PROVIDER) != (_DIRECT_OPENAI_CLASS_PATH, OpenAIConfig):
- register_provider(_DIRECT_OPENAI_PROVIDER, _DIRECT_OPENAI_CLASS_PATH, OpenAIConfig)
-
-
-class OSSBackend(Mem0Backend):
- """Wraps mem0.Memory for self-hosted (OSS) mode."""
-
- def __init__(self, oss_config: dict):
- from ._oss_providers import EMBEDDER_PROVIDERS, KNOWN_DIMS, LLM_PROVIDERS
-
- self._local_path = None
- self._owner = None
- self._lock = nullcontext()
- self._closed = False
-
- def _provider_block(name: str, registry: dict) -> dict:
- """Copy of oss_config[name] with the legacy ``api_base`` key mapped to the provider's canonical base-URL key."""
- block = dict(oss_config[name])
- provider_config = dict(block.get("config", {}))
- legacy_base = provider_config.pop("api_base", None)
- canonical_key = registry.get(str(block.get("provider") or "").strip().lower(), {}).get("base_url_key")
- if legacy_base and canonical_key:
- provider_config.setdefault(canonical_key, legacy_base)
- if str(block.get("provider") or "").strip().lower() == "openai":
- from agent.secret_scope import get_secret
-
- # Resolve profile secrets before comparing configurations for sharing.
- provider_config["api_key"] = provider_config.get("api_key") or get_secret("OPENAI_API_KEY", "")
- if not provider_config["api_key"]:
- raise ValueError(f"OpenAI API key is required for the Hermes Mem0 OSS {name}")
- provider_config["openai_base_url"] = (
- provider_config.get("openai_base_url") or get_secret("OPENAI_API_BASE", "")
- or get_secret("OPENAI_BASE_URL", "") or "https://api.openai.com/v1"
- )
- block["config"] = provider_config
- return block
-
- vector_store = dict(oss_config["vector_store"])
- vs_config = dict(vector_store.get("config", {}))
- if vs_config.get("path"):
- vs_config["path"] = os.path.expanduser(vs_config["path"])
- embedder_config = oss_config.get("embedder", {}).get("config", {})
- dims = embedder_config.get("embedding_dims") or KNOWN_DIMS.get(embedder_config.get("model", ""))
- if dims:
- vs_config["embedding_model_dims"] = dims
- remote = (vs_config.get("host") and vs_config.get("port")) or vs_config.get("url") or vs_config.get("api_key")
- if (vector_store.get("provider", "qdrant") == "qdrant" and not vs_config.get("client")
- and not remote and vs_config.get("https") is None):
- from mem0.configs.vector_stores.qdrant import QdrantConfig
- path = vs_config.get("path", QdrantConfig.model_fields["path"].default)
- if path:
- self._local_path = vs_config["path"] = os.path.realpath(os.path.expanduser(path))
- vector_store["config"] = vs_config
- config = {"vector_store": vector_store, "llm": _provider_block("llm", LLM_PROVIDERS), "embedder": _provider_block("embedder", EMBEDDER_PROVIDERS), "version": "v1.1"}
- if self._local_path:
- from hermes_constants import get_hermes_home
- profile = os.path.realpath(get_hermes_home())
- with _LOCAL_QDRANT_LOCK:
- owner = _LOCAL_QDRANT_MEMORIES.get(self._local_path)
- if owner is None:
- owner = _LocalQdrantMemory(self._create_memory(config, dims), deepcopy(config), profile)
- _LOCAL_QDRANT_MEMORIES[self._local_path] = owner
- else:
- if owner.profile != profile or owner.config != config:
- raise ValueError("Local Qdrant storage is already open with a different profile or configuration. "
- "Existing memories were preserved. Close its active sessions before changing settings, "
- "or use a separate storage path.")
- owner.users += 1
- self._owner, self._lock, self._memory = owner, owner.lock, owner.memory
- else:
- self._memory = self._create_memory(config, dims)
-
- @staticmethod
- def _create_memory(config: dict, dims: int | None):
- from mem0 import Memory
- vector_store = config["vector_store"]
- vs_config = vector_store["config"]
- if dims:
- OSSBackend._reject_dimension_mismatch(vector_store.get("provider", "qdrant"), vs_config, dims)
- else:
- logger.warning("Unknown embedding dimensions; skipping dimension-change guard for collection %r.",
- vs_config.get("collection_name", "mem0"))
- if str(config["llm"].get("provider") or "").strip().lower() == "openai":
- # mem0 validates LlmConfig.provider before its factory lookup: build the supported OpenAI config, then swap the provider.
- _register_direct_openai_provider()
- from mem0.configs.base import MemoryConfig
- memory_config = MemoryConfig(**config)
- try:
- memory_config.llm.provider = _DIRECT_OPENAI_PROVIDER
- except (AttributeError, TypeError) as exc:
- raise RuntimeError("mem0 MemoryConfig does not expose a mutable llm.provider for the Hermes OpenAI OSS backend") from exc
- return Memory(memory_config)
- return Memory.from_config(config)
-
- @staticmethod
- def _detect_current_dims(provider: str, vs_config: dict, collection_name: str) -> int | None:
- """Current embedding dimension of ``collection_name``, or None if it doesn't exist yet.
- Raises on any failure to connect/inspect so the caller can decide whether to skip the guard."""
- if provider == "qdrant":
- from qdrant_client import QdrantClient
- path, url, host = vs_config.get("path"), vs_config.get("url"), vs_config.get("host")
- if path:
- client = QdrantClient(path=path)
- elif url:
- client = QdrantClient(url=url, api_key=vs_config.get("api_key"))
- elif host:
- client = QdrantClient(host=host, port=vs_config.get("port") or 6333, api_key=vs_config.get("api_key"))
- else:
- return None
- with closing(client):
- if not client.collection_exists(collection_name):
- return None
- vectors = client.get_collection(collection_name).config.params.vectors
- # Named-vector collections expose a dict; unnamed expose an object with .size.
- if isinstance(vectors, dict):
- vectors = next(iter(vectors.values()), None)
- return getattr(vectors, "size", None)
- elif provider == "pgvector":
- import psycopg2
- conn_params = {k: vs_config[k] for k in ("host", "port", "user", "password", "dbname", "sslmode") if vs_config.get(k)}
- with closing(psycopg2.connect(**conn_params)) as conn:
- conn.autocommit = True
- with closing(conn.cursor()) as cur:
- cur.execute("SELECT atttypmod FROM pg_attribute WHERE attrelid = %s::regclass AND attname = 'vector'", (collection_name,))
- row = cur.fetchone()
- return row[0] if row and row[0] > 0 else None
- return None
-
- @staticmethod
- def _reject_dimension_mismatch(provider: str, vs_config: dict, expected_dims: int) -> None:
- """Reject embedding dimension changes without deleting existing memories."""
- collection_name = vs_config.get("collection_name", "mem0")
- try:
- current_dims = OSSBackend._detect_current_dims(provider, vs_config, collection_name)
- except Exception as dimension_detection_error:
- logger.warning(
- "Could not determine embedding dimensions for collection %r (%s): %s. Skipping dimension-change guard.",
- collection_name, provider, dimension_detection_error,
- )
- return
- if current_dims is not None and current_dims != expected_dims:
- raise ValueError(
- f"Collection {collection_name!r} has {current_dims} embedding dimensions, but {expected_dims} are configured. "
- "Existing memories were preserved. Restore the previous embedder or use a new collection_name."
- )
-
- def search(self, query: str, *, filters: dict, top_k: int = 10, rerank: bool = False) -> list[dict]:
- return _unwrap_results(self._call("search", query, filters=filters, top_k=top_k))
-
- def add(self, messages: list, *, user_id: str, agent_id: str, infer: bool = False, metadata: dict | None = None) -> dict:
- return self._call("add", messages, **_add_kwargs(user_id, agent_id, infer, metadata))
-
- def get(self, memory_id: str) -> dict | None:
- return self._call("get", memory_id)
-
- def _update(self, memory_id: str, text: str) -> None:
- self._call("update", memory_id, data=text)
-
- def _delete(self, memory_id: str) -> None:
- self._call("delete", memory_id)
-
- def _call(self, method, *args, **kwargs):
- # ponytail: serialize whole local SDK operations, including extraction's read/modify/write.
- # Use a Qdrant server for parallel throughput or access from multiple processes.
- with self._lock:
- if self._closed:
- raise RuntimeError("Mem0 backend is closed")
- return getattr(self._memory, method)(*args, **kwargs)
-
- def close(self):
- with self._lock:
- if self._closed:
- return
- self._closed = True
- if self._owner:
- with _LOCAL_QDRANT_LOCK:
- self._owner.users -= 1
- if self._owner.users == 0:
- self._close_memory()
- del _LOCAL_QDRANT_MEMORIES[self._local_path]
- else:
- self._close_memory()
-
- def _close_memory(self):
- with suppress(Exception):
- telemetry = getattr(self._memory, "telemetry", None)
- if telemetry and hasattr(telemetry, "posthog"):
- with suppress(Exception):
- telemetry.posthog.shutdown()
- vs = getattr(self._memory, "vector_store", None)
- telemetry_vs = getattr(self._memory, "_telemetry_vector_store", None)
- resources = (self._memory, vs, getattr(vs, "client", None), getattr(telemetry_vs, "client", None))
- for obj in {id(obj): obj for obj in resources if obj is not None}.values():
- if hasattr(obj, "close"):
- with suppress(Exception):
- obj.close()
diff --git a/integrations/hermes-plugin-mem0/_openai_llm.py b/integrations/hermes-plugin-mem0/_openai_llm.py
deleted file mode 100644
index ed1296364..000000000
--- a/integrations/hermes-plugin-mem0/_openai_llm.py
+++ /dev/null
@@ -1,66 +0,0 @@
-"""OpenAI-only LLM adapter for Mem0 OSS mode."""
-
-from __future__ import annotations
-
-import logging
-from typing import Dict, List, Optional, Union
-
-from mem0.configs.llms.base import BaseLlmConfig
-from mem0.configs.llms.openai import OpenAIConfig
-from mem0.llms.base import LLMBase
-from mem0.llms.openai import OpenAILLM
-
-# BaseLlmConfig fields copied into OpenAIConfig; the last two may be absent on older mem0.
-_COPIED_FIELDS = ("model", "temperature", "api_key", "max_tokens", "top_p", "top_k", "enable_vision", "vision_details", "http_client_proxies")
-_OPTIONAL_FIELDS = ("reasoning_effort", "is_reasoning_model")
-
-
-class DirectOpenAILLM(OpenAILLM):
- """Use OpenAI credentials and requests regardless of router environment."""
-
- def __init__(self, config: Optional[Union[BaseLlmConfig, OpenAIConfig, Dict]] = None):
- if config is None:
- config = OpenAIConfig()
- elif isinstance(config, dict):
- config = OpenAIConfig(**config)
- elif isinstance(config, BaseLlmConfig) and not isinstance(config, OpenAIConfig):
- fields = {k: getattr(config, k) for k in _COPIED_FIELDS}
- fields.update({k: getattr(config, k, None) for k in _OPTIONAL_FIELDS})
- config = OpenAIConfig(**fields)
- if not config.model:
- config.model = "gpt-5-mini"
- # Configs predating the setup marker: keep the default model reasoning-safe
- # without overriding an explicit user choice.
- if config.model == "gpt-5-mini" and config.is_reasoning_model is None:
- config.is_reasoning_model = True
- # Bypass OpenAILLM.__init__ (it picks OpenRouter when OPENROUTER_API_KEY is
- # set); LLMBase still owns validation and supported-parameter filtering.
- LLMBase.__init__(self, config)
- # OPENAI_API_KEY / OPENAI_BASE_URL are profile credentials: read them through the secret
- # scope, never raw os.environ, or a multiplexed secondary's memory extraction runs on the
- # default profile's OpenAI account (and its proxy).
- from agent.secret_scope import get_secret
- api_key = self.config.api_key or get_secret("OPENAI_API_KEY", "")
- if not api_key:
- raise ValueError("OpenAI API key is required for the Hermes Mem0 OSS provider")
- from openai import OpenAI
- self.client = OpenAI(api_key=api_key, base_url=self.config.openai_base_url or get_secret("OPENAI_API_BASE", "") or get_secret("OPENAI_BASE_URL", "") or "https://api.openai.com/v1", timeout=120.0)
-
- def generate_response(self, messages: List[Dict[str, str]], response_format=None, tools: Optional[List[Dict]] = None, tool_choice: str = "auto", **kwargs):
- params = self._get_supported_params(messages=messages, **kwargs)
- params.update({"model": self.config.model, "messages": messages})
- # No OpenRouter-only fields; ``store`` is opt-in so OpenAI-compatible endpoints never receive unknown fields.
- if self.config.store is not None:
- params["store"] = self.config.store
- if response_format:
- params["response_format"] = response_format
- if tools:
- params["tools"], params["tool_choice"] = tools, tool_choice
- response = self.client.chat.completions.create(**params)
- parsed_response = self._parse_response(response, tools)
- if self.config.response_callback:
- try:
- self.config.response_callback(self, response, params)
- except Exception:
- logging.error("Error running Mem0 OpenAI response callback")
- return parsed_response
diff --git a/integrations/hermes-plugin-mem0/_oss_providers.py b/integrations/hermes-plugin-mem0/_oss_providers.py
deleted file mode 100644
index c6ced627f..000000000
--- a/integrations/hermes-plugin-mem0/_oss_providers.py
+++ /dev/null
@@ -1,53 +0,0 @@
-"""OSS provider definitions for LLM, embedder, and vector store."""
-
-from __future__ import annotations
-
-import os
-from typing import Any
-
-from hermes_constants import get_hermes_home
-
-LLM_PROVIDERS: dict[str, dict[str, Any]] = {
- "openai": {"label": "OpenAI", "needs_key": True, "env_var": "OPENAI_API_KEY", "default_model": "gpt-5-mini", "base_url_key": "openai_base_url"},
- "ollama": {"label": "Ollama (local)", "needs_key": False, "default_model": "llama3.1:8b", "default_url": "http://localhost:11434", "base_url_key": "ollama_base_url", "pip_dep": "ollama"},
-}
-
-EMBEDDER_PROVIDERS: dict[str, dict[str, Any]] = {
- "openai": {"label": "OpenAI", "needs_key": True, "env_var": "OPENAI_API_KEY", "default_model": "text-embedding-3-small", "base_url_key": "openai_base_url", "dims": 1536},
- "ollama": {"label": "Ollama (local)", "needs_key": False, "default_model": "nomic-embed-text", "default_url": "http://localhost:11434", "base_url_key": "ollama_base_url", "dims": 768, "pip_dep": "ollama"},
-}
-
-VECTOR_PROVIDERS: dict[str, dict[str, Any]] = {
- # Resolved lazily (see ``vector_default_config``): the profile home is a ContextVar at call time,
- # not an import-time constant, and ``~/.hermes`` is wrong on Windows and under profiles.
- "qdrant": {"label": "Qdrant", "default_config": {"path": lambda: str(get_hermes_home() / "mem0_qdrant")}, "pip_dep": "qdrant-client"},
- "pgvector": {
- "label": "PGVector",
- "default_config": {"host": "localhost", "port": 5432, "user": os.getenv("USER", "postgres"), "dbname": "postgres"},
- "pip_dep": "psycopg2-binary",
- },
-}
-
-KNOWN_DIMS: dict[str, int] = {"text-embedding-3-small": 1536, "text-embedding-3-large": 3072, "text-embedding-ada-002": 1536, "nomic-embed-text": 768}
-
-def vector_default_config(provider_id: str) -> dict[str, Any]:
- """A vector store's ``default_config`` with callable defaults resolved for the active profile."""
- return {k: (v() if callable(v) else v) for k, v in VECTOR_PROVIDERS[provider_id]["default_config"].items()}
-
-
-SECTION_REGISTRIES = (("llm", LLM_PROVIDERS), ("embedder", EMBEDDER_PROVIDERS), ("vector_store", VECTOR_PROVIDERS))
-
-
-def validate_oss_config(oss_config: dict) -> list[str]:
- """Validate an OSS config dict. Returns list of error strings (empty = valid)."""
- errors: list[str] = []
- for section, registry in SECTION_REGISTRIES:
- block = oss_config.get(section)
- if not block or not isinstance(block, dict):
- errors.append(f"Missing required section: {section}")
- elif block.get("provider", "") not in registry:
- errors.append(f"Unknown {section} provider '{block.get('provider', '')}'. Valid: {', '.join(registry.keys())}")
- vs = oss_config.get("vector_store", {})
- if vs.get("provider") == "pgvector" and not vs.get("config", {}).get("user"):
- errors.append("PGVector requires 'user' in vector_store.config")
- return errors
diff --git a/integrations/hermes-plugin-mem0/_setup.py b/integrations/hermes-plugin-mem0/_setup.py
deleted file mode 100644
index 302129c18..000000000
--- a/integrations/hermes-plugin-mem0/_setup.py
+++ /dev/null
@@ -1,567 +0,0 @@
-"""Setup wizard for Mem0 plugin โ interactive and flag-based modes."""
-
-from __future__ import annotations
-
-import getpass
-import json
-import os
-import re
-import secrets
-import shutil
-import socket
-import subprocess
-import sys
-import time
-import urllib.error
-import urllib.request
-from contextlib import suppress
-from pathlib import Path
-from typing import Any
-
-from hermes_constants import get_hermes_home # noqa: F401 โ patched by tests
-
-from ._oss_providers import (
- EMBEDDER_PROVIDERS,
- KNOWN_DIMS,
- LLM_PROVIDERS,
- SECTION_REGISTRIES,
- VECTOR_PROVIDERS,
- validate_oss_config,
- vector_default_config,
-)
-
-_OLLAMA_URL = "http://localhost:11434"
-_PGVECTOR_CONTAINER, _PGVECTOR_IMAGE = "hermes-pgvector", "pgvector/pgvector:pg17"
-
-
-def _version_tuple(version: str) -> tuple[int, ...]:
- """Best-effort (major, minor, patch) from a version string, tolerating pre-release suffixes like '2.1.0rc1'."""
- parts = version.split(".")[:3]
- return tuple(int(m.group()) if (m := re.match(r"\d+", p)) else 0 for p in parts)
-
-
-def _scrub(text: str, *secrets_to_hide: str) -> str:
- """Replace any occurrence of the given secrets in ``text`` (e.g. before printing a subprocess error)."""
- for secret in secrets_to_hide:
- if secret:
- text = text.replace(secret, "***")
- return text
-
-
-def _curses_select(title: str, items: list[tuple[str, str]], default: int = 0) -> int:
- from hermes_cli.curses_ui import curses_radiolist
- return curses_radiolist(title, [f"{label} {desc}" if desc else label for label, desc in items], selected=default, cancel_returns=default)
-
-
-def _prompt(label: str, default: str | None = None, secret: bool = False) -> str:
- """Prompt for a value with optional default and secret masking."""
- sys.stdout.write(f" {label}{f' [{default}]' if default else ''}: ")
- sys.stdout.flush()
- val = getpass.getpass(prompt="") if secret and sys.stdin.isatty() else sys.stdin.readline().strip()
- return val or (default or "")
-
-
-def _input(label: str, default: str) -> str:
- return input(f" {label} [{default}]: ").strip() or default
-
-
-def _masked(secret: str) -> str:
- return f"...{secret[-4:]}" if len(secret) > 4 else "set"
-
-
-def _http_get(url: str, path: str, timeout: int):
- return urllib.request.urlopen(urllib.request.Request(f"{url.rstrip('/')}{path}", method="GET"), timeout=timeout)
-
-
-def _prompt_api_key(label: str, env_var: str, hermes_home: str) -> str:
- """Prompt for API key, showing masked existing value if found."""
- existing = os.environ.get(env_var, "")
- if not existing:
- from agent.secret_scope import load_env_file
-
- existing = load_env_file(Path(hermes_home) / ".env").get(env_var, "")
- hint = f" (current: {_masked(existing)}, blank to keep)" if existing else ""
- return getpass.getpass(f" {label} API key{hint}: ").strip()
-
-
-def _api_key_writes(flags: dict, label: str, *, url: str | None = None, fresh_label: str | None = None) -> dict[str, str]:
- """MEM0_API_KEY for .env: from --api-key, else prompt (masking any key already in the environment)."""
- if flags.get("api_key"):
- return {"MEM0_API_KEY": flags["api_key"]}
- existing = os.environ.get("MEM0_API_KEY", "")
- if url and not existing:
- print(f" Get yours at {url}")
- val = _prompt(f"{label} (current: {_masked(existing)}, blank to keep)" if existing else fresh_label or label, secret=True)
- return {"MEM0_API_KEY": val} if val else {}
-
-
-def _print_dry_run(summary: str, env_writes: dict, check=None) -> None:
- print(f"\n [dry-run] Would save config: {summary}")
- if env_writes:
- print(" [dry-run] Would write API key to .env")
- if check:
- check()
- print(" [dry-run] No files written.\n")
-
-
-# --oss-vector- flags accepted per vector store (also the pgvector key order).
-_VECTOR_FLAG_KEYS = {"qdrant": ("path", "url"), "pgvector": ("host", "port", "user", "password", "dbname")}
-_FLAG_KEYS = ("mode", "api_key", "host", *(f"oss_{s}{k}" for s in ("llm", "embedder") for k in ("", "_key", "_model", "_url")),
- "oss_vector", *(f"oss_vector_{k}" for ks in _VECTOR_FLAG_KEYS.values() for k in ks), "user_id")
-_FLAG_DEFAULTS = {"oss_llm": "openai", "oss_embedder": "openai", "oss_vector": "qdrant"}
-
-
-def parse_flags(argv: list[str] | None = None) -> dict[str, str]:
- args = argv if argv is not None else sys.argv[1:]
- flags: dict[str, Any] = {**{k: _FLAG_DEFAULTS.get(k, "") for k in _FLAG_KEYS}, "dry_run": False}
- flag_map = {"--" + k.replace("_", "-"): k for k in _FLAG_KEYS}
- i = 0
- while i < len(args):
- if args[i] == "--dry-run":
- flags["dry_run"] = True
- elif args[i] in flag_map and i + 1 < len(args):
- flags[flag_map[args[i]]] = args[i + 1]
- i += 1
- i += 1
- return flags
-
-
-def _model_block(flags: dict, registry: dict, prefix: str) -> tuple[str, dict, dict[str, Any]]:
- """Resolve (provider_id, provider_def, config) for an LLM/embedder section from flags."""
- pid = flags.get(prefix, "openai")
- pdef = registry[pid]
- cfg: dict[str, Any] = {"model": flags.get(f"{prefix}_model") or pdef["default_model"]}
- url = flags.get(f"{prefix}_url") or pdef.get("default_url")
- if url and pdef.get("base_url_key"):
- cfg[pdef["base_url_key"]] = url
- return pid, pdef, cfg
-
-
-def build_oss_config(flags: dict[str, str]) -> tuple[dict, dict[str, str]]:
- """Build (oss_config for mem0.json, env_writes of secrets for .env) from parsed flags."""
- llm_id, llm_def, llm_config = _model_block(flags, LLM_PROVIDERS, "oss_llm")
- if llm_id == "openai" and llm_config["model"] == "gpt-5-mini":
- llm_config["is_reasoning_model"] = True
- embedder_id, embedder_def, embedder_config = _model_block(flags, EMBEDDER_PROVIDERS, "oss_embedder")
- dims = KNOWN_DIMS.get(embedder_config["model"])
- if dims:
- embedder_config["embedding_dims"] = dims
- vector_id = flags.get("oss_vector", "qdrant")
- vector_config = vector_default_config(vector_id)
- for key in _VECTOR_FLAG_KEYS.get(vector_id, ()):
- if val := flags.get(f"oss_vector_{key}"):
- if key == "port" and not val.isdigit():
- raise ValueError(f"--oss-vector-port must be a number, got {val!r}")
- vector_config[key] = int(val) if key == "port" else val
- if "url" in vector_config:
- vector_config.pop("path", None) # a remote Qdrant URL replaces local storage
- oss_config = {"llm": {"provider": llm_id, "config": llm_config}, "embedder": {"provider": embedder_id, "config": embedder_config}, "vector_store": {"provider": vector_id, "config": vector_config}}
- # An embedder sharing the LLM's provider reuses the LLM key when no embedder key was given.
- llm_key = flags.get("oss_llm_key") if llm_def.get("needs_key") else ""
- emb_key = (flags.get("oss_embedder_key") or (flags.get("oss_llm_key") if embedder_id == llm_id else "")) if embedder_def.get("needs_key") else ""
- env_writes = {d["env_var"]: k for d, k in ((llm_def, llm_key), (embedder_def, emb_key)) if k}
- if llm_key and emb_key and llm_key != emb_key and llm_def["env_var"] == embedder_def["env_var"]:
- # One environment variable cannot hold two accounts; save explicit keys in the private config.
- llm_config["api_key"], embedder_config["api_key"] = llm_key, emb_key
- env_writes.pop(llm_def["env_var"])
- return oss_config, env_writes
-
-
-def _write_env(env_path: Path, env_writes: dict[str, str]) -> None:
- env_path.parent.mkdir(parents=True, exist_ok=True)
- # utf-8-sig like the canonical .env readers: a BOM'd first line would miss the key match and get duplicated.
- existing_lines = env_path.read_text(encoding="utf-8-sig").splitlines() if env_path.exists() else []
- keys = [line.split("=", 1)[0].strip() if "=" in line and not line.startswith("#") else None for line in existing_lines]
- new_lines = [f"{k}={env_writes[k]}" if k in env_writes else line for k, line in zip(keys, existing_lines)]
- new_lines += [f"{k}={v}" for k, v in env_writes.items() if k not in keys]
- from utils import atomic_write_text
-
- atomic_write_text(env_path, "\n".join(new_lines) + "\n", mode=0o600)
-
-
-def _activate_provider(config: dict) -> None:
- """Point config.yaml's memory.provider at mem0."""
- from hermes_cli.config import save_config
- config["memory"]["provider"] = "mem0"
- save_config(config)
-
-
-def _persist_provider_config(hermes_home: str, config: dict, provider_config: dict, env_writes: dict[str, str], label: str, key_line: str, server: str | None = None) -> None:
- """Shared platform/self-hosted tail: activate, write mem0.json (0600), then .env, then a saved summary."""
- _activate_provider(config)
- from . import Mem0MemoryProvider
- if "MEM0_API_KEY" in env_writes:
- provider_config["api_key"] = "" # Let the newly saved .env key replace legacy inline credentials.
- Mem0MemoryProvider().save_config(provider_config, hermes_home)
- if env_writes:
- _write_env(Path(hermes_home) / ".env", env_writes)
- if server:
- _check_selfhosted_server(server)
- print("\n".join(["", f" Memory provider: {label}", *([f" Server: {server}"] if server else []), " Activation saved to config.yaml", " Provider config saved",
- *([f" {key_line}"] if env_writes else []), "", " Start a new session to activate.", ""]))
-
-
-def _setup_platform(hermes_home: str, config: dict, flags: dict[str, str]) -> None:
- """Platform mode setup โ prompts for API key (secret -> .env), user/agent ids and rerank (-> mem0.json)."""
- from utils import read_json_or_empty
- provider_config = read_json_or_empty(Path(hermes_home) / "mem0.json")
- print("\n Configuring mem0:\n")
- env_writes = _api_key_writes(flags, "Mem0 Platform API key", url="https://app.mem0.ai")
- for key, desc, default in (("user_id", "User identifier", "hermes-user"), ("agent_id", "Agent identifier", "hermes")):
- if val := flags.get(key) or _prompt(desc, default=str(provider_config.get(key) or default)):
- provider_config[key] = val
- choices = ["true", "false"]
- current = str(provider_config.get("rerank", "false") or "").lower()
- provider_config["rerank"] = choices[_curses_select(" Enable reranking for recall", [(c, "") for c in choices], default=choices.index(current) if current in choices else 0)]
- if flags.get("dry_run"):
- _print_dry_run(str({k: provider_config.get(k) for k in ("user_id", "agent_id", "rerank")}), env_writes)
- return
- # Routing checks ``host`` before platform, so clear a stale self-hosted host. "" rather than
- # pop(): save_config merges into the existing mem0.json, so a popped key would survive.
- provider_config.update(mode="platform", host="")
- # _load_config() also seeds ``host`` from MEM0_HOST (.env); the file clear can't help there, so warn.
- if os.environ.get("MEM0_HOST", "").strip():
- print(f"\n โ MEM0_HOST is set in your environment ({os.environ['MEM0_HOST']}). It overrides platform mode โ remove it from ~/.hermes/.env (or unset it) or Hermes will keep routing to the self-hosted server.")
- _persist_provider_config(hermes_home, config, provider_config, env_writes, "mem0", "API keys saved to .env")
-
-
-def _check_selfhosted_server(host: str) -> None:
- """Best-effort reachability check for a self-hosted Mem0 server (non-fatal)."""
- try:
- _http_get(host, "/docs", 5)
- print(f" โ Mem0 server reachable at {host}")
- except urllib.error.HTTPError:
- # Any HTTP response (401/403/404) still means something is listening.
- print(f" โ Mem0 server responding at {host}")
- except Exception:
- print(f" โ Could not reach {host} โ check the URL and that the server is running.")
-
-
-def _setup_selfhosted(hermes_home: str, config: dict, flags: dict[str, str]) -> None:
- """Self-hosted mode โ point at an existing Mem0 server: URL -> mem0.json, key -> .env (MEM0_API_KEY)."""
- from utils import read_json_or_empty
- provider_config = read_json_or_empty(Path(hermes_home) / "mem0.json")
- print("\n Configuring mem0 (self-hosted server):\n")
- host = flags.get("host") or _prompt("Mem0 server URL (e.g. http://localhost:8888)", default=provider_config.get("host") or None)
- if not host:
- print(" Error: a server URL is required for self-hosted mode.", file=sys.stderr)
- return
- host = host.rstrip("/")
- env_writes = _api_key_writes(flags, "Server API key", fresh_label="Server API key (blank if AUTH_DISABLED)")
- user_id = flags.get("user_id") or _prompt("User identifier", default=provider_config.get("user_id") or "hermes-user")
- agent_id = _prompt("Agent identifier", default=provider_config.get("agent_id") or "hermes")
- if flags.get("dry_run"):
- _print_dry_run(f"host={host}, user_id={user_id}, agent_id={agent_id}", env_writes, lambda: _check_selfhosted_server(host))
- return
- provider_config.update(mode="platform", host=host, user_id=user_id, agent_id=agent_id) # routing: oss > host > platform
- _persist_provider_config(hermes_home, config, provider_config, env_writes, "mem0 (self-hosted)", "API key saved to .env", server=host)
-
-
-def _print_oss_summary(oss_config: dict, env_writes: dict, dry_run: bool = False) -> None:
- llm, emb = oss_config["llm"], oss_config["embedder"]
- w = 0 if dry_run else 9 # final summary column-aligns the labels
- lines = ["", " [dry-run] OSS config would be:" if dry_run else " โ Mem0 configured (OSS mode)",
- f" {'LLM:':<{w}} {llm['provider']} ({llm['config'].get('model', '')})", f" {'Embedder:':<{w}} {emb['provider']} ({emb['config'].get('model', '')})",
- f" {'Vector:':<{w}} {oss_config['vector_store']['provider']}"]
- if dry_run:
- lines += [f" Env vars: {', '.join(env_writes.keys())}"] if env_writes else []
- else:
- lines += [*([" API keys saved to .env"] if env_writes else []), " Config saved to mem0.json", " Provider set in config.yaml", "", " Start a new session to activate.", ""]
- print("\n".join(lines))
-
-
-def _finish_oss(hermes_home: str, config: dict, oss_config: dict, env_writes: dict[str, str], user_id: str, agent_id: str, pgvector_config: dict | None = None) -> None:
- """Shared OSS tail: write secrets + mem0.json, install deps, activate, check, summarize."""
- from . import Mem0MemoryProvider
- if env_writes:
- _write_env(Path(hermes_home) / ".env", env_writes)
- Mem0MemoryProvider().save_config(
- {"mode": "oss", "user_id": user_id, "agent_id": agent_id, "oss": oss_config}, hermes_home
- )
- _install_provider_deps(oss_config["llm"]["provider"], oss_config["embedder"]["provider"], oss_config["vector_store"]["provider"])
- if pgvector_config:
- _ensure_pgvector_extension(pgvector_config)
- _activate_provider(config)
- _run_connectivity_checks(oss_config)
- _print_oss_summary(oss_config, env_writes)
-
-
-def _setup_oss(hermes_home: str, config: dict, flags: dict[str, str]) -> None:
- """OSS mode โ non-interactive when --mode was given, otherwise curses pickers."""
- if not flags.get("_mode_from_flag"):
- _setup_oss_interactive(hermes_home, config)
- return
- try:
- oss_config, env_writes = build_oss_config(flags)
- except ValueError as e:
- print(f" Error: {e}", file=sys.stderr)
- sys.exit(1)
- if errors := validate_oss_config(oss_config):
- print("".join(f" Error: {e}\n" for e in errors), end="", file=sys.stderr)
- sys.exit(1)
- if flags.get("dry_run"):
- _print_oss_summary(oss_config, env_writes, dry_run=True)
- _run_connectivity_checks(oss_config)
- print(" [dry-run] No files written.\n")
- return
- _finish_oss(hermes_home, config, oss_config, env_writes, flags.get("user_id") or os.getenv("USER", "hermes-user"), "hermes")
-
-
-def _docker(*args: str, timeout: int, **kwargs) -> subprocess.CompletedProcess:
- return subprocess.run(["docker", *args], capture_output=True, timeout=timeout, stdin=subprocess.DEVNULL, **kwargs)
-
-
-def _pg_ready(host: str, port: int, wait: int) -> bool:
- """Wait up to ``wait`` seconds for the port, then report whether PostgreSQL answers."""
- _wait_for_port(host, port, timeout=wait)
- return _check_pgvector(host, port)[0]
-
-
-def _ensure_pgvector(host: str = "localhost", port: int = 5432) -> dict | None:
- """Ensure pgvector is reachable, offering Docker if not; returns the started container's vector_config, else None."""
- if _check_pgvector(host, port)[0]:
- print(f" โ PostgreSQL reachable at {host}:{port}")
- return None
- print(f" PostgreSQL not reachable at {host}:{port}")
- if not shutil.which("docker"):
- print(" Docker not found. Install Docker to auto-start pgvector,\n or run PostgreSQL with pgvector manually.")
- return None
- with suppress(Exception): # restart our own container if it exists but is stopped
- result = _docker("inspect", _PGVECTOR_CONTAINER, "--format", "{{.State.Status}}", timeout=10, text=True, encoding='utf-8', errors='replace')
- if result.returncode == 0 and "exited" in result.stdout:
- print(f" Found stopped container '{_PGVECTOR_CONTAINER}', restarting...")
- _docker("start", _PGVECTOR_CONTAINER, timeout=15)
- if _pg_ready(host, port, 15):
- print(" โ PostgreSQL container restarted")
- return None
- if input(" Start pgvector via Docker? [Y/n]: ").strip().lower() not in ("", "y", "yes"):
- print(" Skipping Docker setup. Make sure PostgreSQL with pgvector is running.")
- return None
- password = secrets.token_urlsafe(24)
- try:
- print(f" Pulling {_PGVECTOR_IMAGE}...")
- _docker("pull", _PGVECTOR_IMAGE, timeout=120)
- print(f" Starting container '{_PGVECTOR_CONTAINER}' on port {port}...")
- _docker("run", "-d", "--name", _PGVECTOR_CONTAINER, "-e", f"POSTGRES_PASSWORD={password}", "-p", f"127.0.0.1:{port}:5432", _PGVECTOR_IMAGE, timeout=30, check=True)
- if _pg_ready(host, port, 20):
- print(f" โ pgvector running on {host}:{port}")
- else:
- print(" Warning: Container started but PostgreSQL not yet accepting connections.\n It may need a few more seconds. Config will be saved; retry later.")
- return {"host": host, "port": port, "user": "postgres", "password": password, "dbname": "postgres"}
- except subprocess.CalledProcessError as e:
- print(f" Failed to start Docker container: {_scrub(str(e), password)}")
- except Exception as e:
- print(f" Docker error: {_scrub(str(e), password)}")
- return None
-
-
-def _ensure_ollama(models: list[str]) -> bool:
- """Ensure Ollama is running and ``models`` are pulled; False when the user must handle it manually."""
- ollama_bin = shutil.which("ollama")
- if not (ok := _check_ollama(_OLLAMA_URL)[0]):
- if not ollama_bin:
- print(" Ollama not found. Install it:\n curl -fsSL https://ollama.com/install.sh | sh\n Or on macOS: brew install ollama")
- return False
- print(" Ollama installed but not running. Starting...")
- try:
- subprocess.Popen([ollama_bin, "serve"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
- _wait_for_port("localhost", 11434, timeout=10)
- if ok := _check_ollama(_OLLAMA_URL)[0]:
- print(" โ Ollama started")
- except Exception as e:
- print(f" Could not start Ollama: {e}")
- if not ok:
- print(" Warning: Ollama not reachable. Models cannot be pulled.")
- return False
- for model in models:
- try:
- names = [m.get("name", "") for m in json.loads(_http_get(_OLLAMA_URL, "/api/tags", 5).read()).get("models", [])]
- except Exception:
- names = []
- if any(model in n or model.split(":")[0] in n for n in names):
- print(f" โ Model '{model}' available")
- continue
- print(f" Pulling '{model}'... (this may take a few minutes)")
- try:
- subprocess.run([ollama_bin or "ollama", "pull", model], timeout=600, stdin=subprocess.DEVNULL)
- print(f" โ Model '{model}' pulled")
- except Exception as e:
- print(f" Warning: Could not pull '{model}': {e}\n Run manually: ollama pull {model}")
- return True
-
-
-def _ensure_pgvector_extension(pg_config: dict) -> None:
- try:
- import psycopg2
- except ImportError:
- return
- defaults = {"host": "localhost", "port": 5432, "user": "postgres", "dbname": "postgres"}
- try:
- conn = psycopg2.connect(**(defaults | {k: v for k, v in pg_config.items() if k in defaults or (k == "password" and v)}))
- conn.autocommit = True
- conn.cursor().execute("CREATE EXTENSION IF NOT EXISTS vector")
- conn.close()
- print(" โ pgvector extension enabled")
- except Exception as e:
- print(f" Warning: Could not enable pgvector extension: {e}")
-
-
-def _wait_for_port(host: str, port: int, timeout: int = 15) -> None:
- deadline = time.monotonic() + timeout
- while time.monotonic() < deadline:
- try:
- socket.create_connection((host, port), timeout=1).close()
- return
- except OSError:
- time.sleep(0.5)
-
-
-# Picker descriptions: LLM/embedder show model (+ URL); vector stores by provider id (default: the id itself).
-_VECTOR_DESCRIPTIONS = {"qdrant": lambda cfg: cfg.get("path", "local storage"), "pgvector": lambda cfg: f"{cfg.get('host', 'localhost')}:{cfg.get('port', 5432)}"}
-
-
-def _configure_model_provider(kind: str, registry: dict, hermes_home: str, env_writes: dict[str, str], llm: tuple[str, dict] | None = None) -> tuple[str, dict, str, str | None]:
- """Pick an LLM/embedder provider, collect its key, and (for Ollama) model + URL -> (id, definition, model, url).
- For the embedder (``llm`` given), a provider shared with the LLM reuses the LLM key instead of prompting again."""
- items = [(v["label"], f"{v.get('default_model', '')} ({v['default_url']})" if v.get("default_url") else v.get("default_model", "")) for v in registry.values()]
- pid = list(registry)[_curses_select(f"{kind} Provider", items, 0)]
- pdef = registry[pid]
- model, url = pdef["default_model"], pdef.get("default_url")
- if pdef["needs_key"]:
- if llm is None or pid != llm[0]:
- if key := _prompt_api_key(pdef["label"] if llm is None else f"{pdef['label']} embedder", pdef["env_var"], hermes_home):
- env_writes[pdef["env_var"]] = key
- elif llm[1].get("env_var") in env_writes:
- env_writes[pdef["env_var"]] = env_writes[llm[1]["env_var"]]
- if pid == "ollama":
- model = _input(f"{kind} model", pdef["default_model"])
- url = _input("Ollama URL", pdef["default_url"])
- return pid, pdef, model, url
-
-
-def _setup_oss_interactive(hermes_home: str, config: dict) -> None:
- env_writes: dict[str, str] = {}
- llm_id, llm_def, llm_model, llm_url = _configure_model_provider("LLM", LLM_PROVIDERS, hermes_home, env_writes)
- embedder_id, _, embedder_model, embedder_url = _configure_model_provider("Embedder", EMBEDDER_PROVIDERS, hermes_home, env_writes, llm=(llm_id, llm_def))
- vector_items = [(v["label"], _VECTOR_DESCRIPTIONS.get(pid, lambda cfg: pid)(vector_default_config(pid))) for pid, v in VECTOR_PROVIDERS.items()]
- vector_id = list(VECTOR_PROVIDERS)[_curses_select("Vector Store", vector_items, 0)]
- # Auto-setup: ensure Ollama is running and models are pulled; ensure pgvector is reachable (offer Docker if not).
- ollama_models = [m for pid, m in ((llm_id, llm_model), (embedder_id, embedder_model)) if pid == "ollama"]
- if ollama_models:
- _ensure_ollama(ollama_models)
- pgvector_config = _ensure_pgvector() if vector_id == "pgvector" else None
- if vector_id == "pgvector" and not pgvector_config: # native PostgreSQL: prompt for connection details (user first, historical order)
- pg = {k: _input(f"PostgreSQL {label}", d) for k, label, d in (("user", "user", os.getenv("USER", "postgres")), ("host", "host", "localhost"), ("port", "port", "5432"), ("dbname", "database", "postgres"))}
- pg_password = getpass.getpass(" PostgreSQL password (blank if none): ").strip()
- pgvector_config = {**pg, "port": int(pg["port"]), **({"password": pg_password} if pg_password else {})}
- user_id = _input("User ID", os.getenv("USER", "hermes-user"))
- agent_id = _input("Agent ID", "hermes")
- flags = {
- "oss_llm": llm_id, "oss_llm_model": llm_model, "oss_llm_url": llm_url or "",
- "oss_llm_key": env_writes.get(llm_def["env_var"], "") if llm_def.get("env_var") else "",
- "oss_embedder": embedder_id, "oss_embedder_model": embedder_model, "oss_embedder_url": embedder_url or "",
- "oss_vector": vector_id, "user_id": user_id,
- }
- flags.update({f"oss_vector_{key}": str(val) for key, val in (pgvector_config or {}).items() if val})
- oss_config, _ = build_oss_config(flags)
- _finish_oss(hermes_home, config, oss_config, env_writes, user_id, agent_id, pgvector_config)
-
-
-def _install_provider_deps(llm_id: str, embedder_id: str, vector_id: str) -> None:
- deps = {registry[pid]["pip_dep"] for (_, registry), pid in zip(SECTION_REGISTRIES, (llm_id, embedder_id, vector_id)) if registry.get(pid, {}).get("pip_dep")}
- for dep in sorted(deps):
- print(f" Installing {dep}...")
- try:
- # Environment-aware install: sealed hosted venvs redirect to the durable data-volume target instead of /opt/hermes.
- from tools.lazy_deps import install_specs
- outcome = install_specs([dep], timeout=60)
- except Exception:
- outcome = None
- print(f" โ Installed {dep}" if outcome is not None and outcome.ok else f" Warning: cannot install {dep}: {outcome.reason}" if outcome is not None and outcome.blocked
- else f" Warning: Could not install {dep}. Install manually: uv pip install {dep}")
- if deps:
- import importlib
- importlib.invalidate_caches()
-
-
-def _probe(fn, ok: str, fail: str, exc=Exception) -> tuple[bool, str]:
- """Run ``fn``; (True, ok) on success, (False, "fail: ") on ``exc``."""
- try:
- fn()
- return True, ok
- except exc as e:
- return False, f"{fail}: {e}"
-
-
-def _check_qdrant_path(path: str) -> tuple[bool, str]:
- """Check that qdrant local storage parent dir is writable."""
- parent = Path(path).expanduser().parent
- return _probe(lambda: parent.mkdir(parents=True, exist_ok=True), f"Directory writable: {parent}", f"Cannot write to {parent}", OSError)
-
-
-def _check_ollama(url: str) -> tuple[bool, str]:
- return _probe(lambda: _http_get(url, "/api/tags", 3), "Ollama reachable", f"Ollama not reachable at {url}")
-
-
-def _check_pgvector(host: str, port: int) -> tuple[bool, str]:
- return _probe(lambda: socket.create_connection((host, port), timeout=3).close(), f"PGVector reachable at {host}:{port}", f"PGVector not reachable at {host}:{port}")
-
-
-def _warn_unless(check: tuple[bool, str]) -> None:
- ok, msg = check
- if not ok:
- print(f" Warning: {msg}")
-
-
-def _run_connectivity_checks(oss_config: dict) -> None:
- vs = oss_config.get("vector_store", {})
- cfg = vs.get("config", {})
- if vs.get("provider") == "qdrant":
- path, url = cfg.get("path"), cfg.get("url")
- if path:
- _warn_unless(_check_qdrant_path(path))
- elif url:
- _warn_unless(_probe(lambda: _http_get(url, "/healthz", 3), "Qdrant reachable", f"Qdrant not reachable at {url}"))
- elif vs.get("provider") == "pgvector":
- _warn_unless(_check_pgvector(cfg.get("host", "localhost"), cfg.get("port", 5432)))
- llm = oss_config.get("llm", {})
- if llm.get("provider") == "ollama":
- _warn_unless(_check_ollama(llm.get("config", {}).get("ollama_base_url", _OLLAMA_URL)))
-
-
-_MODE_HANDLERS = {"oss": _setup_oss, "selfhosted": _setup_selfhosted, "self-hosted": _setup_selfhosted, "platform": _setup_platform}
-# Interactive picker order: Platform, Self-hosted server, Open Source.
-_MODE_ITEMS = [("Platform", "Mem0 Cloud API (lightweight, just needs an API key)"), ("Self-hosted server", "Connect to an existing self-hosted Mem0 server (Docker/FastAPI)"), ("Open Source", "Run Mem0 locally (self-hosted LLM + vector store)")]
-_MODE_PICKER = (_setup_platform, _setup_selfhosted, _setup_oss)
-
-
-def post_setup(hermes_home: str, config: dict) -> None:
- """Entry point for `hermes memory setup`: routes on --mode (platform / selfhosted / oss), else shows a picker.
- OSS is non-interactive only when the mode came from the flag."""
- with suppress(ImportError): # mem0ai must meet the minimum version from plugin.yaml
- import mem0
- installed_ver = getattr(mem0, "__version__", None)
- if installed_ver and _version_tuple(installed_ver) < (2, 0, 10):
- print(f"\n โ mem0ai {installed_ver} installed but >=2.0.10 required.\n Run: uv pip install --python {sys.executable} 'mem0ai>=2.0.10'")
- flags = parse_flags(sys.argv[1:])
- handler = _MODE_HANDLERS.get(flags["mode"])
- flags["_mode_from_flag"] = handler is not None
- if handler is None:
- handler = _MODE_PICKER[_curses_select(" Select mode", _MODE_ITEMS, 0)]
- handler(hermes_home, config, flags)
-
-
-# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----
-# Names external plugins imported from this module before the Sep 2026 decomposition.
-# Internal code MUST NOT use these (scripts/check_compat_pointers.py fails CI if it does).
-# The whole block is removed by reverting the commit that added it.
-
-def has_oss_flags() -> bool:
- """Check if OSS-related flags are present in sys.argv."""
- flags = parse_flags(sys.argv[1:])
- if flags["mode"] == "oss":
- return True
- if any(flags.get(k) for k in ("oss_llm_key", "oss_vector_path", "oss_vector_url")):
- return True
- return False
-# ---- END PLUGIN-COMPAT ----
diff --git a/integrations/hermes-plugin-mem0/plugin.yaml b/integrations/hermes-plugin-mem0/plugin.yaml
deleted file mode 100644
index c6ae10acc..000000000
--- a/integrations/hermes-plugin-mem0/plugin.yaml
+++ /dev/null
@@ -1,5 +0,0 @@
-name: mem0
-version: 1.3.0
-description: "Mem0 โ server-side LLM fact extraction with semantic search, automatic deduplication, and opt-in reranking (platform mode)."
-pip_dependencies:
- - mem0ai>=2.0.10,<3
diff --git a/integrations/hermes-plugin-mem0/pyproject.toml b/integrations/hermes-plugin-mem0/pyproject.toml
deleted file mode 100644
index 962237b28..000000000
--- a/integrations/hermes-plugin-mem0/pyproject.toml
+++ /dev/null
@@ -1,17 +0,0 @@
-[project]
-name = "hermes-plugin-mem0"
-version = "1.3.0"
-description = "Hermes Agent memory provider plugin: mem0"
-requires-python = ">=3.11"
-license = { text = "Apache-2.0 AND MIT" }
-# Installed into the Hermes venv by `hermes plugins install` / `enable` and re-applied after
-# every `hermes update` (hermes-agent#113851). Keep upper bounds: Hermes pins its own deps exactly
-# and refuses a plugin whose requirements cannot resolve against them.
-dependencies = [
- "mem0ai>=2.0.10,<3",
- "httpx>=0.27,<1",
-]
-
-[project.optional-dependencies]
-postgres = ['psycopg2-binary>=2.9,<3']
-qdrant = ['qdrant-client>=1.9,<2']
diff --git a/integrations/hermes-plugin-mem0/tests/smoke_hermes.py b/integrations/hermes-plugin-mem0/tests/smoke_hermes.py
deleted file mode 100644
index 14fdcc0ac..000000000
--- a/integrations/hermes-plugin-mem0/tests/smoke_hermes.py
+++ /dev/null
@@ -1,178 +0,0 @@
-"""Real Hermes + Mem0 SDK + local Qdrant; only the model API is simulated.
-
-HERMES_SOURCE=/path/to/hermes-agent python tests/smoke_hermes.py
-Requires the Hermes dependencies, mem0ai, and qdrant-client in the active environment.
-All configuration, credentials, and database files are temporary.
-"""
-
-import importlib
-import io
-import json
-import os
-import shutil
-import sys
-import tempfile
-import threading
-from contextlib import redirect_stdout
-from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
-from pathlib import Path
-from unittest.mock import patch
-
-
-class ModelAPI(BaseHTTPRequestHandler):
- calls = []
-
- def log_message(self, *args):
- pass
-
- def do_POST(self):
- if self.headers.get("Authorization") != "Bearer local-test":
- self.send_error(401)
- return
- body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
- self.calls.append(self.path)
- if self.path == "/v1/embeddings":
- result = {
- "object": "list",
- "data": [{"object": "embedding", "index": i, "embedding": [1.0, 0.0, 0.0]}
- for i, _ in enumerate(body["input"])],
- "model": "test-embedding",
- "usage": {"prompt_tokens": 1, "total_tokens": 1},
- }
- elif self.path == "/v1/chat/completions":
- result = {
- "id": "test-completion", "object": "chat.completion", "created": 0, "model": "gpt-4.1-mini",
- "choices": [{"index": 0, "finish_reason": "stop", "message": {"role": "assistant", "content":
- json.dumps({"facts": ["Prefers green tea."], "memory": [
- {"id": "0", "text": "Prefers green tea.", "event": "ADD"}]})}}],
- }
- else:
- self.send_error(404)
- return
- encoded = json.dumps(result).encode()
- self.send_response(200)
- self.send_header("Content-Type", "application/json")
- self.send_header("Content-Length", str(len(encoded)))
- self.end_headers()
- self.wfile.write(encoded)
-
-
-def main():
- hermes_source = Path(os.environ["HERMES_SOURCE"]).resolve()
- sys.path.insert(0, str(hermes_source))
- with tempfile.TemporaryDirectory() as temporary:
- home = Path(temporary)
- os.environ.update(HERMES_HOME=temporary, MEM0_DIR=str(home / "mem0-data"), MEM0_TELEMETRY="false")
- (home / "mem0-data").mkdir()
- server = ThreadingHTTPServer(("127.0.0.1", 0), ModelAPI)
- worker = threading.Thread(target=server.serve_forever, daemon=True)
- worker.start()
- try:
- url = f"http://127.0.0.1:{server.server_port}/v1"
- config = {
- "mode": "oss", "user_id": "existing-user", "agent_id": "hermes",
- "oss": {
- "llm": {"provider": "openai", "config": {
- "model": "gpt-4.1-mini", "api_key": "local-test", "openai_base_url": url}},
- "embedder": {"provider": "openai", "config": {
- "model": "test-embedding", "embedding_dims": 3,
- "api_key": "local-test", "openai_base_url": url}},
- "vector_store": {"provider": "qdrant", "config": {"path": str(home / "qdrant")}},
- },
- }
- (home / "mem0.json").write_text(json.dumps(config))
- destination = home / "plugins" / "mem0"
- shutil.copytree(Path(__file__).resolve().parents[1], destination)
- import plugins.memory as memory_plugins
- from agent.memory_manager import MemoryManager
-
- # Simulate bundled-provider removal only inside this test process.
- memory_plugins._MEMORY_PLUGINS_DIR = home / "empty-bundled"
- memory_plugins._MEMORY_PLUGINS_DIR.mkdir()
- assert memory_plugins.find_provider_dir("mem0") == destination
- provider = memory_plugins.load_memory_provider("mem0", register_skills=False)
- assert provider is not None and provider.__class__.__module__.startswith("_hermes_user_memory.")
- setup = importlib.import_module(f"{provider.__class__.__module__}._setup")
- from hermes_cli.memory_setup import cmd_setup_provider, cmd_status
-
- output = io.StringIO()
- arguments = ["hermes", "memory", "setup", "mem0", "--mode", "platform", "--api-key", "local-test"]
- with patch.object(sys, "argv", arguments), patch.object(sys, "stdin", io.StringIO("\n\n")):
- with patch.object(setup, "_curses_select", return_value=0), redirect_stdout(output):
- cmd_setup_provider("mem0")
- assert json.loads((home / "mem0.json").read_text())["user_id"] == "existing-user"
- provider.save_config(config, home)
- assert (home / "mem0.json").stat().st_mode & 0o777 == 0o600
- with redirect_stdout(output):
- cmd_status(None)
- assert "installed โ" in output.getvalue() and "available โ" in output.getvalue()
- assert (home / ".env").stat().st_mode & 0o777 == 0o600
- manager = MemoryManager()
- manager.add_provider(provider)
- manager.initialize_all("smoke-session", platform="cli", user_id="gateway-user")
- assert provider._backend is not None, getattr(provider, "_init_error", "initialization failed")
-
- def tool(name, **arguments):
- result = json.loads(manager.handle_tool_call(name, arguments))
- assert "error" not in result, result
- return result
-
- try:
- assert tool("mem0_add", content="Prefers Python.")["result"] == "Fact stored."
- memories = tool("mem0_search", query="language")["results"]
- assert len(memories) == 1 and memories[0]["memory"] == "Prefers Python."
- memory_id = memories[0]["id"]
- tool("mem0_update", memory_id=memory_id, text="Prefers Rust.")
- assert "Prefers Rust." in provider.prefetch("language preference")
- assert tool("mem0_search", query="language")["results"][0]["memory"] == "Prefers Rust."
- tool("mem0_delete", memory_id=memory_id)
- assert tool("mem0_search", query="language")["result"] == "No relevant memories found."
- manager.sync_all("I prefer green tea.", "Noted.", session_id="smoke-session")
- assert provider._user_id == "existing-user"
- finally:
- manager.shutdown_all()
- assert provider._backend is None
- # A changed embedder must fail without destroying the existing collection.
- config["oss"]["embedder"]["config"]["embedding_dims"] = 4
- provider.save_config(config, home)
- mismatched = type(provider)()
- mismatched.initialize("mismatched-session")
- assert mismatched._backend is None and "Existing memories were preserved" in mismatched._init_error
- config["oss"]["embedder"]["config"]["embedding_dims"] = 3
- # Resolve embedder credentials from the active profile, not another profile's process env.
- del config["oss"]["embedder"]["config"]["api_key"]
- del config["oss"]["embedder"]["config"]["openai_base_url"]
- provider.save_config(config, home)
- from agent.secret_scope import (
- reset_secret_scope,
- set_multiplex_active,
- set_secret_scope,
- )
-
- resumed = type(provider)()
- with patch.dict(os.environ, {"OPENAI_API_KEY": "wrong-profile", "OPENAI_API_BASE": "http://127.0.0.1:1/v1"}):
- set_multiplex_active(True)
- token = set_secret_scope({"OPENAI_API_KEY": "local-test", "OPENAI_BASE_URL": url})
- try:
- resumed.initialize("resumed-session", user_id="different-gateway-user")
- finally:
- reset_secret_scope(token)
- set_multiplex_active(False)
- try:
- assert resumed._backend is not None
- found = json.loads(resumed.handle_tool_call("mem0_search", {"query": "drink"}))
- assert "results" in found, found
- assert found["results"][0]["memory"] == "Prefers green tea."
- finally:
- resumed.shutdown()
- assert "/v1/chat/completions" in ModelAPI.calls
- print("PASS: external Hermes loader, CLI setup/status, real Mem0/Qdrant CRUD, recall, background extraction,")
- print(" existing identity, profile credentials, private files, shutdown, dimension safety and persistence across restart. Model responses simulated locally.")
- finally:
- server.shutdown()
- server.server_close()
- worker.join(timeout=5)
-
-
-if __name__ == "__main__":
- main()
diff --git a/integrations/hermes-plugin-mem0/tests/test_plugin.py b/integrations/hermes-plugin-mem0/tests/test_plugin.py
deleted file mode 100644
index 6993948b7..000000000
--- a/integrations/hermes-plugin-mem0/tests/test_plugin.py
+++ /dev/null
@@ -1,286 +0,0 @@
-"""Offline regressions for the standalone Hermes plugin."""
-
-import contextvars
-import importlib
-import importlib.util
-import json
-import sys
-import threading
-import types
-from pathlib import Path
-from unittest.mock import Mock
-
-import pytest
-
-ROOT = Path(__file__).resolve().parents[1]
-
-
-@pytest.fixture
-def plugin(monkeypatch, tmp_path):
- def spawn(target, *, name):
- return threading.Thread(target=contextvars.copy_context().run, args=(target,), name=name)
-
- def atomic_write_text(path, value, *, mode):
- path.write_text(value)
- path.chmod(mode)
-
- modules = {
- "agent.memory_provider": {"MemoryProvider": object, "spawn_context_thread": spawn},
- "agent.secret_scope": {"get_secret": lambda key, default="": default},
- "tools.registry": {"tool_error": lambda message: json.dumps({"error": message})},
- "utils": {
- "read_json_or_empty": lambda path: json.loads(path.read_text()) if path.exists() else {},
- "atomic_json_write": lambda path, value, **kwargs: atomic_write_text(path, json.dumps(value), **kwargs),
- "atomic_write_text": atomic_write_text,
- },
- "hermes_constants": {"get_hermes_home": lambda: tmp_path},
- }
- for name, values in modules.items():
- module = types.ModuleType(name)
- module.__dict__.update(values)
- monkeypatch.setitem(sys.modules, name, module)
- spec = importlib.util.spec_from_file_location("standalone_mem0", ROOT / "__init__.py")
- module = importlib.util.module_from_spec(spec)
- monkeypatch.setitem(sys.modules, spec.name, module)
- spec.loader.exec_module(module)
- monkeypatch.setattr(module.atexit, "register", lambda *args: None)
- yield module
- for name in list(sys.modules):
- if name.startswith("standalone_mem0."):
- monkeypatch.delitem(sys.modules, name)
-
-
-def test_dimension_mismatch_preserves_qdrant_collection(plugin, monkeypatch):
- backend = importlib.import_module(f"{plugin.__name__}._backend")
- client = Mock()
- client.collection_exists.return_value = True
- client.get_collection.return_value.config.params.vectors = types.SimpleNamespace(size=1536)
- monkeypatch.setitem(sys.modules, "qdrant_client", types.SimpleNamespace(QdrantClient=Mock(return_value=client)))
- with pytest.raises(ValueError, match="1536.*768"):
- backend.OSSBackend._reject_dimension_mismatch("qdrant", {"path": "/unused"}, 768)
- client.delete_collection.assert_not_called()
- client.close.assert_called_once()
-
-
-def test_dimension_mismatch_preserves_pgvector_table(plugin, monkeypatch):
- backend = importlib.import_module(f"{plugin.__name__}._backend")
- cursor, connection = Mock(), Mock()
- cursor.fetchone.return_value = (1536,)
- connection.cursor.return_value = cursor
- driver = types.SimpleNamespace(connect=Mock(return_value=connection), sql=Mock())
- monkeypatch.setitem(sys.modules, "psycopg2", driver)
- with pytest.raises(ValueError, match="1536.*768"):
- backend.OSSBackend._reject_dimension_mismatch("pgvector", {"user": "test"}, 768)
- assert cursor.execute.call_count == 1
- assert cursor.execute.call_args.args[0].startswith("SELECT")
- connection.close.assert_called_once()
-
-
-def test_setup_keeps_credentials_private_and_preserves_existing_values(plugin, tmp_path):
- setup = importlib.import_module(f"{plugin.__name__}._setup")
- path = tmp_path / ".env"
- path.write_text("EXISTING=value\nMEM0_API_KEY=old\n")
- path.chmod(0o644)
- setup._write_env(path, {"MEM0_API_KEY": "new"})
- assert path.read_text() == "EXISTING=value\nMEM0_API_KEY=new\n"
- assert path.stat().st_mode & 0o777 == 0o600
-
-
-def test_oss_setup_keeps_database_password_private(plugin, tmp_path, monkeypatch):
- setup = importlib.import_module(f"{plugin.__name__}._setup")
- for name in ("_install_provider_deps", "_activate_provider", "_run_connectivity_checks"):
- monkeypatch.setattr(setup, name, Mock())
- config = {"llm": {"provider": "openai", "config": {}}, "embedder": {"provider": "openai", "config": {}},
- "vector_store": {"provider": "pgvector", "config": {"password": "test-password"}}}
- setup._finish_oss(str(tmp_path), {}, config, {}, "existing-user", "hermes")
- path = tmp_path / "mem0.json"
- assert json.loads(path.read_text())["user_id"] == "existing-user"
- assert path.stat().st_mode & 0o777 == 0o600
-
-
-def test_optional_server_key_and_prefetch_rerank(plugin, monkeypatch):
- monkeypatch.setattr(plugin, "_load_config", lambda: {"host": "http://localhost:8888", "rerank": True})
- provider = plugin.Mem0MemoryProvider()
- assert not next(field for field in provider.get_config_schema() if field["key"] == "api_key")["required"]
- backend = Mock()
- backend.search.return_value = [{"memory": "Prefers Python"}]
- monkeypatch.setattr(provider, "_create_backend", lambda: backend)
- provider.initialize("test-session")
- try:
- assert "Prefers Python" in provider.prefetch("language")
- assert backend.search.call_args.kwargs["rerank"] is True
- finally:
- provider.shutdown()
-
-
-def test_invalid_tool_arguments_never_reach_backend(plugin, monkeypatch):
- provider = plugin.Mem0MemoryProvider()
- provider._backend = Mock()
- for args in (None, {"query": []}, {"query": " "}, {"query": "fact", "top_k": "invalid"}):
- assert "error" in json.loads(provider.handle_tool_call("mem0_search", args))
- provider._backend.search.assert_not_called()
- assert provider._consecutive_failures == 0
-
-
-def test_selfhosted_http_auth_and_tool_routes(plugin):
- import httpx
-
- backend = importlib.import_module(f"{plugin.__name__}._backend")
- requests = []
-
- def respond(request):
- requests.append(request)
- return httpx.Response(200, json={"results": [{"id": "existing", "memory": "Prefers Python"}]})
-
- client = backend.SelfHostedBackend("test-key", "http://localhost:8888", transport=httpx.MockTransport(respond))
- try:
- client.add([], user_id="existing-user", agent_id="hermes", infer=True)
- assert requests[-1].headers["X-API-Key"] == "test-key"
- assert json.loads(requests[-1].content)["user_id"] == "existing-user"
- assert client.search("language", filters={"user_id": "existing-user"})[0]["id"] == "existing"
- assert json.loads(requests[-1].content)["filters"] == {"user_id": "existing-user"}
- client.update("existing", "Prefers Rust")
- assert json.loads(requests[-1].content) == {"text": "Prefers Rust"}
- client.delete("existing")
- assert [(r.method, r.url.path) for r in requests] == [
- ("POST", "/memories"), ("POST", "/search"), ("PUT", "/memories/existing"), ("DELETE", "/memories/existing")
- ]
- finally:
- client.close()
-
-
-@pytest.mark.parametrize("mode", ["platform", "selfhosted"])
-def test_setup_rotates_legacy_file_key(plugin, monkeypatch, tmp_path, mode):
- setup = importlib.import_module(f"{plugin.__name__}._setup")
- (tmp_path / "mem0.json").write_text(json.dumps({"api_key": "old-key", "user_id": "existing-user"}))
- monkeypatch.setattr(setup, "_activate_provider", Mock())
- monkeypatch.setattr(setup, "_check_selfhosted_server", Mock())
- monkeypatch.setattr(setup, "_prompt", lambda label, default=None, **kwargs: default or "")
- monkeypatch.setattr(setup, "_curses_select", lambda *args, **kwargs: 0)
- setup._MODE_HANDLERS[mode](str(tmp_path), {}, {"api_key": "new-key", "host": "http://localhost:8888"})
- monkeypatch.setattr(plugin, "get_secret", lambda key, default="": "new-key" if key == "MEM0_API_KEY" else default)
- assert plugin._load_config()["api_key"] == "new-key"
- assert "old-key" not in (tmp_path / "mem0.json").read_text()
- assert "MEM0_API_KEY=new-key" in (tmp_path / ".env").read_text()
-
-
-def test_platform_setup_honors_user_id_flag(plugin, monkeypatch, tmp_path):
- setup = importlib.import_module(f"{plugin.__name__}._setup")
- monkeypatch.setattr(setup, "_activate_provider", Mock())
- monkeypatch.setattr(setup, "_prompt", lambda label, default=None, **kwargs: default or "")
- monkeypatch.setattr(setup, "_curses_select", lambda *args, **kwargs: 0)
- setup._setup_platform(str(tmp_path), {}, {"api_key": "new-key", "user_id": "chosen-user"})
- assert plugin._load_config()["user_id"] == "chosen-user"
-
-
-@pytest.mark.parametrize("scoped_key", ["profile-key", ""])
-def test_oss_embedder_never_uses_another_profiles_credentials(plugin, monkeypatch, scoped_key):
- backend = importlib.import_module(f"{plugin.__name__}._backend")
- memory = Mock()
- monkeypatch.setitem(sys.modules, "mem0", types.SimpleNamespace(Memory=memory))
- qdrant_config = types.SimpleNamespace(model_fields={"path": types.SimpleNamespace(default=None)})
- monkeypatch.setitem(
- sys.modules, "mem0.configs.vector_stores.qdrant", types.SimpleNamespace(QdrantConfig=qdrant_config)
- )
- monkeypatch.setenv("OPENAI_API_KEY", "other-profile-key")
- monkeypatch.setenv("OPENAI_API_BASE", "https://other-profile.invalid/v1")
- secrets = {"OPENAI_API_KEY": scoped_key, "OPENAI_BASE_URL": "https://profile.invalid/v1"}
- monkeypatch.setattr(sys.modules["agent.secret_scope"], "get_secret", lambda key, default="": secrets.get(key, default))
- config = {
- "llm": {"provider": "ollama", "config": {}},
- "embedder": {"provider": "openai", "config": {}},
- "vector_store": {"provider": "qdrant", "config": {}},
- }
- if not scoped_key:
- with pytest.raises(ValueError, match="OpenAI API key"):
- backend.OSSBackend(config)
- memory.from_config.assert_not_called()
- else:
- backend.OSSBackend(config)
- resolved = memory.from_config.call_args.args[0]["embedder"]["config"]
- assert resolved["api_key"] == scoped_key
- assert resolved["openai_base_url"] == "https://profile.invalid/v1"
- assert config["embedder"]["config"] == {}
-
-
-def test_pgvector_setup_never_removes_existing_container(plugin, monkeypatch):
- setup = importlib.import_module(f"{plugin.__name__}._setup")
- monkeypatch.setattr(setup, "_check_pgvector", lambda *args: (False, "unreachable"))
- monkeypatch.setattr(setup.shutil, "which", lambda name: "/test/docker")
- monkeypatch.setattr("builtins.input", lambda prompt: "y")
- calls = []
-
- def docker(*args, **kwargs):
- calls.append(args)
- if args[0] == "run":
- raise setup.subprocess.CalledProcessError(1, "docker run: container name already exists")
- return types.SimpleNamespace(returncode=0, stdout="paused")
-
- monkeypatch.setattr(setup, "_docker", docker)
- assert setup._ensure_pgvector() is None
- assert not any(args[0] == "rm" for args in calls)
-
-
-def test_platform_dry_run_does_not_print_stored_secrets(plugin, monkeypatch, tmp_path, capsys):
- setup = importlib.import_module(f"{plugin.__name__}._setup")
- config = {"api_key": "old-secret", "oss": {"vector_store": {"config": {"password": "db-secret"}}}}
- path = tmp_path / "mem0.json"
- path.write_text(json.dumps(config))
- monkeypatch.setattr(setup, "_prompt", lambda label, default=None, **kwargs: default or "")
- monkeypatch.setattr(setup, "_curses_select", lambda *args, **kwargs: 0)
- setup._setup_platform(str(tmp_path), {}, {"api_key": "new-secret", "dry_run": True})
- output = capsys.readouterr().out
- assert all(secret not in output for secret in ("old-secret", "db-secret", "new-secret"))
- assert json.loads(path.read_text()) == config
- assert not (tmp_path / ".env").exists()
-
-
-def test_oss_setup_preserves_distinct_llm_and_embedder_keys(plugin):
- setup = importlib.import_module(f"{plugin.__name__}._setup")
- config, env = setup.build_oss_config({"oss_llm_key": "llm-key", "oss_embedder_key": "embedder-key"})
- assert config["llm"]["config"].get("api_key", env.get("OPENAI_API_KEY")) == "llm-key"
- assert config["embedder"]["config"].get("api_key", env.get("OPENAI_API_KEY")) == "embedder-key"
-
-
-def test_direct_openai_llm_uses_scoped_credentials(plugin, monkeypatch):
- llm_mod = importlib.import_module(f"{plugin.__name__}._openai_llm")
- openai_mock = types.SimpleNamespace(OpenAI=Mock(return_value=Mock()))
- monkeypatch.setitem(sys.modules, "openai", openai_mock)
- monkeypatch.setenv("OPENROUTER_API_KEY", "should-be-ignored")
- monkeypatch.setenv("OPENAI_API_KEY", "env-key-should-be-ignored")
- secrets = {"OPENAI_API_KEY": "scoped-key", "OPENAI_API_BASE": "", "OPENAI_BASE_URL": ""}
- monkeypatch.setattr(sys.modules["agent.secret_scope"], "get_secret", lambda key, default="": secrets.get(key, default))
- llm_mod.DirectOpenAILLM({"api_key": "", "model": "gpt-5-mini"})
- call_kwargs = openai_mock.OpenAI.call_args.kwargs
- assert call_kwargs["api_key"] == "scoped-key"
- assert "openrouter" not in call_kwargs.get("base_url", "").lower()
-
-
-def test_direct_openai_llm_rejects_missing_key(plugin, monkeypatch):
- llm_mod = importlib.import_module(f"{plugin.__name__}._openai_llm")
- monkeypatch.setattr(sys.modules["agent.secret_scope"], "get_secret", lambda key, default="": "")
- with pytest.raises(ValueError, match="API key"):
- llm_mod.DirectOpenAILLM({"api_key": "", "model": "gpt-5-mini"})
-
-
-def test_selfhosted_keyless_omits_auth_header(plugin):
- import httpx
-
- backend = importlib.import_module(f"{plugin.__name__}._backend")
- requests = []
-
- def respond(request):
- requests.append(request)
- return httpx.Response(200, json={"results": []})
-
- client = backend.SelfHostedBackend("", "http://localhost:8888", transport=httpx.MockTransport(respond))
- client.search("test", filters={"user_id": "u"})
- assert "X-API-Key" not in requests[0].headers
- client.close()
-
-
-def test_initialize_tolerates_non_numeric_sync_max_chars(plugin, monkeypatch):
- monkeypatch.setattr(plugin, "_load_config", lambda: {"sync_max_chars": "not-a-number"})
- provider = plugin.Mem0MemoryProvider()
- provider.initialize("test-session")
- assert provider._sync_max_chars == plugin._SYNC_MSG_MAX_CHARS
diff --git a/integrations/kimi-plugin/core/_harness_id.py b/integrations/kimi-plugin/core/_harness_id.py
deleted file mode 100644
index 83ab061ef..000000000
--- a/integrations/kimi-plugin/core/_harness_id.py
+++ /dev/null
@@ -1,11 +0,0 @@
-"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""
-
-HARNESS_ID = "kimi"
-SOURCE_TAG = "KIMI_PLUGIN"
-
-# Platform-side vocabulary (mem0_event.source + X-Application). The whole
-# plugin family is one source; which editor it runs in is the application.
-# An empty application means the host is unknown, and memory_core omits
-# the header entirely rather than sending a placeholder.
-PLATFORM_SOURCE = "MEM0_PLUGIN"
-PLATFORM_APPLICATION = "kimi"
diff --git a/integrations/kimi-plugin/core/hook_runner.py b/integrations/kimi-plugin/core/hook_runner.py
index b3d8a3210..2a2adb557 100644
--- a/integrations/kimi-plugin/core/hook_runner.py
+++ b/integrations/kimi-plugin/core/hook_runner.py
@@ -290,11 +290,6 @@ def run(
if args.plugin_data_dir:
os.environ[data_dir_env] = args.plugin_data_dir
- # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key
- # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking
- # after them always saw content and every fresh install reported an upgrade.
- data_dir_was_empty = telemetry.data_dir_was_empty()
-
cache_plugin_api_key()
if args.action == "session-start":
clear_stale_api_key_cache()
@@ -310,19 +305,8 @@ def run(
return 0
if args.action == "session-start":
- # Claims the marker atomically and says which event to record, so a
- # second session starting alongside this one cannot record it too.
- first_event = telemetry.claim_install(was_empty=data_dir_was_empty)
- if first_event == "install":
+ if telemetry.is_first_run():
telemetry.record("install")
- elif first_event == "upgrade":
- # First run after a build that never wrote the marker; the
- # predecessor version was never recorded anywhere.
- telemetry.record("upgrade", from_version="pre-0.3")
- else:
- previous = telemetry.claim_version_change()
- if previous:
- telemetry.record("upgrade", from_version=previous)
recovered = recover_pending_handoffs()
record_session_start(store, hook_input)
if recovered:
diff --git a/integrations/kimi-plugin/core/mcp_server.py b/integrations/kimi-plugin/core/mcp_server.py
index a0b73cb79..036fbbdc9 100644
--- a/integrations/kimi-plugin/core/mcp_server.py
+++ b/integrations/kimi-plugin/core/mcp_server.py
@@ -21,9 +21,16 @@ from memory_core import (
PROTOCOL_VERSION = "2024-11-05"
TOOL_NAME = "search_memories"
TOOL_DESCRIPTION = (
- "Search memories from earlier work in this repository. Use it before "
- "repeating investigation or when earlier decisions, fixes, commands, or "
- "results may help."
+ "Search memories from earlier work in this repository. ALWAYS call this "
+ "tool before answering anything that could depend on prior context: the "
+ "user's preferences, facts about this codebase, history, people, projects, "
+ "or earlier decisions. Do not rely on the chat window alone. The "
+ "repository's memory is shared by everyone who works in it and includes "
+ "what it took to run, test, or build here, so search before assuming an "
+ "invocation works. The scope argument changes what is searched: 'repo' "
+ "(default) is the whole repository's shared memory plus your own "
+ "preferences, 'dir' narrows the shared part to the directory you are "
+ "working in, and 'mine' is your preferences alone."
)
TOOL_SCHEMA = {
"type": "object",
diff --git a/integrations/kimi-plugin/core/memory_core.py b/integrations/kimi-plugin/core/memory_core.py
index 9b420a063..77d7a2b80 100644
--- a/integrations/kimi-plugin/core/memory_core.py
+++ b/integrations/kimi-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.3"
+PLUGIN_VERSION = "0.3.1"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
@@ -71,13 +71,15 @@ MAX_FLUSH_ATTEMPTS = 5
FORGET_PAGE_SIZE = 100
FORGET_MAX_PAGES = 50
-PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work.
+PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository.
A completed change should produce one memory explaining the resulting behavior, where it is implemented when useful, and any important constraints or reasoning. Exploration or accepted decisions may produce separate memories only when they are independently useful.
-Use the coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+A command that failed and was then made to work should produce one memory naming the failing invocation, the error it returned, and the invocation that succeeded. Do not save one-off errors caused by an edit still in progress, transient network failures, or anything a rerun would fix on its own.
-Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state.
+Use the current coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+
+Write about the repository, not the user, assistant, session, or task. Do not save personal preferences. Do not save a memory that only states which repository, branch, or directory the session worked in. Do not include test results, documentation updates, release notes, or temporary state.
If nothing useful was established, return no memories."""
@@ -1798,34 +1800,6 @@ def extraction_message_batches(
return batches
-# Platform surface attribution. Read from the generated per-host module so a new
-# entrypoint is correct without remembering to configure anything.
-try: # pragma: no cover - absent only in the un-built shared source tree
- from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
- from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
-except ImportError:
- _PLATFORM_SOURCE = "MEM0_PLUGIN"
- _PLATFORM_APPLICATION = ""
-
-
-def platform_headers(key: str) -> dict[str, str]:
- """Auth plus the three surface-identity headers.
-
- X-Mem0-Source and X-Application are set-once by contract: this is the
- outermost layer, so it sets them, and nothing below may overwrite them.
- X-Mem0-Client is append-only โ anything downstream adds itself to the tail.
- """
- headers = {
- "Authorization": f"Token {key}",
- "Content-Type": "application/json",
- "X-Mem0-Source": _PLATFORM_SOURCE,
- "X-Mem0-Client": f"mem0-plugin/{PLUGIN_VERSION}",
- }
- if _PLATFORM_APPLICATION:
- headers["X-Application"] = _PLATFORM_APPLICATION
- return headers
-
-
def _request_json(
url: str, key: str, payload: dict[str, Any], timeout: float
) -> tuple[dict[str, Any] | list[Any], int, int]:
@@ -1833,7 +1807,7 @@ def _request_json(
request = urllib.request.Request(
url,
data=raw,
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -1860,7 +1834,7 @@ def _get_json(
) -> tuple[dict[str, Any] | list[Any], int]:
request = urllib.request.Request(
url,
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="GET",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -2006,13 +1980,6 @@ def flush_session(
"user_id": write_user,
"app_id": repo.app_id,
"run_id": session_id,
- # Top level, not metadata: the backend reads `source` from the body or
- # the query string, never from metadata, which is where this used to
- # sit. The X-Mem0-Source header is also read, but only from the
- # platform release that ships alongside this change, so the body value
- # is what makes attribution work on both. The harness tag stays in
- # metadata as hook provenance.
- "source": _PLATFORM_SOURCE,
"metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)},
"agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS,
"custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS,
@@ -2556,7 +2523,7 @@ def _collect_memory_ids(
def _delete_memory(api_url: str, key: str, memory_id: str) -> bool:
request = urllib.request.Request(
f"{api_url}/v1/memories/{urllib.parse.quote(memory_id)}/",
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="DELETE",
)
try:
diff --git a/integrations/kimi-plugin/core/telemetry.py b/integrations/kimi-plugin/core/telemetry.py
index c1fc0084c..249595475 100644
--- a/integrations/kimi-plugin/core/telemetry.py
+++ b/integrations/kimi-plugin/core/telemetry.py
@@ -1,9 +1,5 @@
#!/usr/bin/env python3
-"""Usage telemetry for Mem0 agent plugins.
-
-Events are linked to your Mem0 account email when an API key is configured, and
-to a random per-machine id otherwise. Not anonymous โ the Python SDK and CLI
-attribute the same way.
+"""Anonymous usage telemetry for Mem0 agent plugins.
Hooks run on a 3-6 second budget and fire on every tool call, so recording never
touches the network: `record` appends one JSON line to a local spool and returns.
@@ -13,8 +9,7 @@ started once per session and again from the flush worker that is already detache
Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false.
Never sends prompts, memory text, queries, file paths, repository names, or API
-keys: only event names, durations, counts, coarse outcomes, and repo/session
-identifiers hashed with a random per-install salt.
+keys: only event names, durations, counts, coarse outcomes, and salted hashes.
"""
from __future__ import annotations
@@ -34,24 +29,8 @@ from typing import Any
import memory_core
-# Seeded from the per-host module the build generates into core/. Two processes
-# in this pipeline never call init() โ mcp_server.py, and the detached
-# `python3 telemetry.py` sender that spawn_flush() starts โ so a module default
-# was what every one of their events got labelled with.
-try: # pragma: no cover - absent only in the un-built shared source tree
- from _harness_id import HARNESS_ID as _DEFAULT_HARNESS
- from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
- from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
- from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG
-except ImportError:
- _DEFAULT_HARNESS = "generic"
- _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN"
- _PLATFORM_SOURCE = "MEM0_PLUGIN"
- _PLATFORM_APPLICATION = ""
-
-_salt_cache: str = ""
-_harness: str = _DEFAULT_HARNESS
-_source_tag: str = _DEFAULT_SOURCE_TAG
+_harness: str = "generic"
+_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
"apikey",
"authorization",
@@ -77,19 +56,10 @@ _PRIVATE_KEYS = {
}
-def init(harness: str = "", source_tag: str = "") -> None:
- """Override the generated identity. Optional โ core/_harness_id.py is the default.
-
- The fallback shape matches memory_core.configure_harness's (``_PLUGIN``).
- It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which
- meant one plugin could emit three different source values depending on which
- process happened to send the batch.
- """
+def init(harness: str = "generic", source_tag: str = "") -> None:
global _harness, _source_tag
- _harness = harness or _DEFAULT_HARNESS
- _source_tag = source_tag or (
- f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG
- )
+ _harness = harness
+ _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/"
@@ -100,16 +70,6 @@ BATCH_SIZE = 100
SEND_TIMEOUT = 5
CLAIM_STALE_SECONDS = 120
CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60
-# A batch is only discarded once it has genuinely been retried this many times.
-MAX_CLAIM_ATTEMPTS = 3
-# Parked claims drained per run, after the live spool. Bounded so a long backlog
-# cannot turn one flush into an unbounded send loop.
-MAX_PARKED_PER_RUN = 3
-# Added to the wait before a released claim becomes reclaimable, per attempt
-# already spent. Releasing straight to "reclaimable now" let two senders burn the
-# whole budget within seconds of one another on a single momentary failure, and
-# discard a batch a retry a minute later would have delivered.
-RETRY_COOLDOWN_SECONDS = 60
def is_enabled() -> bool:
@@ -123,126 +83,9 @@ def is_enabled() -> bool:
def _digest(value: str, length: int = 16) -> str:
- """Unsalted digest. Only for values that are already secrets (API keys)."""
return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length]
-def _salt_path() -> Path:
- return memory_core.data_dir() / "telemetry-salt"
-
-
-def _install_salt() -> str:
- """Random per-install salt, created once and memoized for the process.
-
- Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in
- the identity file. Three reasons, all of which produced wrong data when this
- lived in the identity dict:
-
- - Hooks are short-lived separate processes firing on every tool call, and
- people run more than one agent window. A read-modify-write would let each
- process mint its own salt, so one repository would hash several ways in the
- window before a writer won.
- - resolve_distinct_id holds a copy of the identity dict across a network call
- to /v1/ping/, so whichever write landed second erased the other's key โ
- losing either the salt (repo_hash changes mid-stream) or the email (a
- second $identify, splitting the person).
- - Touching the identity file from record() would create it, and is_first_run
- keys off that file, so recording an event would silently suppress the
- install event.
-
- Published atomically, and there is deliberately no derived fallback. Creating
- the file with O_CREAT|O_EXCL and then writing into it leaves a window where
- the file exists and is empty, and a concurrent hook that reads it in that
- window gets nothing. Falling back to a digest of the path would hand that
- process a salt an attacker can compute, memoized for its whole run, which is
- the privacy control this function exists to provide silently turning itself
- off under load. The salt is written to a private temp file first and linked
- into place, so the name either does not exist or already has the full value.
-
- Returns "" when it genuinely cannot persist. Callers omit the hash entirely
- rather than emit an unsalted one.
- """
- global _salt_cache
- if _salt_cache:
- return _salt_cache
-
- path = _salt_path()
- # Read before writing. Hooks are separate processes firing on every tool
- # call, so all but the first find the salt already published; going straight
- # to create-fsync-link-unlink meant every one of them paid an fsync to
- # discover that, on a path whose whole promise is appending a line and
- # returning.
- try:
- _salt_cache = path.read_text(encoding="utf-8").strip()
- if _salt_cache:
- return _salt_cache
- except OSError:
- pass
-
- temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(handle, "w", encoding="utf-8") as stream:
- stream.write(uuid.uuid4().hex)
- stream.flush()
- os.fsync(stream.fileno())
- try:
- # Atomic claim: fails if another process already published one.
- # os.link rather than replace, which would clobber theirs.
- os.link(temporary, path)
- except FileExistsError:
- pass
- except OSError:
- # No hardlinks here (some network mounts, some container volumes).
- # Claim the name directly instead. That reopens the empty-file
- # window, but the window is now benign: a reader that lands in it
- # gets "" and omits the hash for that process rather than caching a
- # guessable one. Losing the hashes on every run of an entire
- # filesystem is the worse failure.
- try:
- fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(fallback, "w", encoding="utf-8") as stream:
- stream.write(temporary.read_text(encoding="utf-8"))
- except OSError:
- pass
- except OSError:
- pass
- finally:
- try:
- temporary.unlink()
- except OSError:
- pass
-
- try:
- _salt_cache = path.read_text(encoding="utf-8").strip()
- except OSError:
- _salt_cache = ""
- return _salt_cache
-
-
-def _scoped_digest(value: str, length: int = 16) -> str:
- """Salted digest for values drawn from a guessable space.
-
- repo.identity is a git remote URL, or ``local:`` when there is
- no remote โ which normally contains the account username. Sixteen unsalted
- hex characters over that input space is enumerable, so this is not a
- privacy control without the salt. Salting per install keeps every
- within-account join the analytics actually use and gives up only
- cross-machine joins on the same repository, which nothing computes.
-
- Returns "" when there is no salt, so record() omits the property. An
- unsalted digest over this input space is close to plaintext, and emitting one
- under a name that implies it is hashed is worse than sending nothing.
- """
- if not value:
- return ""
- salt = _install_salt()
- if not salt:
- return ""
- return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length]
-
-
def _safe_value(value: Any) -> Any:
if isinstance(value, str):
return memory_core.redact(value)
@@ -302,176 +145,9 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str:
return created
-def _rotate_anonymous_id(identity: dict[str, str]) -> str:
- """Mint a fresh anonymous id because the account context is gone.
-
- The previous id may already have been merged into a person profile by an
- $identify, and that merge is permanent. Reusing it after a logout or a key
- change attributes everything that follows to the account that just went
- away, which is the same misattribution the key fingerprint exists to stop,
- only arriving through the anonymous path instead.
-
- `aliased` is cleared with it: the new id has never been merged, so it is
- eligible to be aliased into whatever account comes next.
- """
- created = f"code-anon-{uuid.uuid4().hex}"
- identity["anonymous_id"] = created
- identity.pop("aliased", None)
- _write_identity(identity)
- return created
-
-
-def _install_state_path() -> Path:
- return memory_core.data_dir() / "install-state.json"
-
-
def is_first_run() -> bool:
- """Whether install has never been recorded on this machine.
-
- Deliberately NOT the identity file. That file is only written by a
- successful flush, so an offline or firewalled user recorded code.install on
- every single session, forever โ and every 0.2.x user recorded one on their
- first 0.3.x session because 0.2.x never wrote it at all.
- """
- return not _install_state_path().exists()
-
-
-def data_dir_was_empty() -> bool:
- """Whether the data directory is untouched. Call BEFORE anything writes to it.
-
- hook_runner reaches claim_install() only after cache_plugin_api_key() has
- written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so
- asking at claim time always saw content and every fresh install reported an
- upgrade. The caller snapshots this at the top of the run instead.
- """
- return not _data_dir_has_content()
-
-
-def claim_install(was_empty: bool | None = None) -> str | None:
- """Claim the one install/upgrade record for this machine, atomically.
-
- Returns the event to record ("install" or "upgrade"), or None if another
- session already claimed it. O_CREAT|O_EXCL so two sessions starting together
- cannot both win.
-
- `was_empty` must come from data_dir_was_empty() called before this process
- wrote anything. Omitting it falls back to checking now, which is only
- correct for a caller that has touched nothing.
- """
- if not is_enabled():
- # Never consume the one-shot claim while the user is opted out, or they
- # would silently lose their install event if they later opt in.
- return None
-
- path = _install_state_path()
- upgrading = not (data_dir_was_empty() if was_empty is None else was_empty)
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- except FileExistsError:
- return None
- except OSError:
- return None
- try:
- with os.fdopen(handle, "w", encoding="utf-8") as stream:
- json.dump(
- {
- "plugin_version": memory_core.PLUGIN_VERSION,
- "installed_at": memory_core.utc_now(),
- "upgraded": upgrading,
- },
- stream,
- )
- # Durable before this returns. The O_EXCL open is what makes the
- # claim exclusive, so it cannot be replaced by a temp-and-rename
- # without losing that, which leaves the content as the thing to make
- # safe. A kill between the open and this fsync used to leave a marker
- # that exists but parses to nothing: is_first_run reads it as claimed
- # and claim_version_change cannot read a version out of it.
- stream.flush()
- os.fsync(stream.fileno())
- except OSError:
- pass
- return "upgrade" if upgrading else "install"
-
-
-def _data_dir_has_content() -> bool:
- """Whether anything predates this session in the plugin data directory."""
- try:
- for entry in memory_core.data_dir().iterdir():
- if entry.name != "install-state.json":
- return True
- except OSError:
- pass
- return False
-
-
-def _repair_install_state(path: Path) -> None:
- """Rewrite an unparseable marker so version tracking can resume."""
- try:
- temporary = path.with_suffix(f".{os.getpid()}.tmp")
- temporary.write_text(
- json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}),
- encoding="utf-8",
- )
- temporary.replace(path)
- except OSError:
- pass
-
-
-def claim_version_change() -> str | None:
- """Return the previously recorded version if it differs, updating the marker.
-
- Only meaningful once the marker exists โ the first transition into 0.3.x has
- no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting
- the marker means the next session sees no change and records nothing.
- """
- path = _install_state_path()
- try:
- state = json.loads(path.read_text(encoding="utf-8"))
- except OSError:
- return None
- except json.JSONDecodeError:
- # A crash between O_EXCL and the write leaves an empty marker. Left
- # alone it disables every future upgrade event on this machine, because
- # claim_install sees the file and this function cannot parse it.
- state = None
- if not isinstance(state, dict):
- _repair_install_state(path)
- return None
- previous = str(state.get("plugin_version") or "")
- if not previous or previous == memory_core.PLUGIN_VERSION:
- return None
- # Claim the transition with an exclusive sentinel before rewriting the
- # marker. A plain read-modify-write let every concurrently starting session
- # observe the old version and each record its own upgrade โ and the first
- # session after a version bump is exactly when several agent windows restart
- # together.
- sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}")
- try:
- os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
- except FileExistsError:
- return None
- except OSError:
- return None
-
- state["plugin_version"] = memory_core.PLUGIN_VERSION
- state["upgraded_at"] = memory_core.utc_now()
- temporary = path.with_suffix(f".{os.getpid()}.tmp")
- try:
- temporary.write_text(json.dumps(state), encoding="utf-8")
- temporary.replace(path)
- except OSError:
- # Release the claim. The marker still records the old version, so
- # without this the sentinel makes claim_version_change return early on
- # every later run and this version's upgrade is never recorded again.
- for leftover in (sentinel, temporary):
- try:
- leftover.unlink()
- except OSError:
- pass
- return None
- return previous
+ """Whether this machine has never recorded a plugin event before."""
+ return not _identity_path().exists()
def record(
@@ -492,32 +168,19 @@ def record(
except OSError:
pass
properties = _safe_value(properties)
- # Stamped in the RECORDING process, beside harness. `source` used to be
- # read in the sending process from a module global, so whichever process
- # drained the spool named every event in it. flush() spreads per-event
- # properties last, so this now wins over any sender's default.
properties.update(
harness=_harness,
- source=_source_tag,
plugin_version=memory_core.PLUGIN_VERSION,
os=sys.platform,
python_version=platform.python_version(),
)
- # Assigned only when the digest is real. _scoped_digest returns "" when
- # the salt could not be persisted, and an empty property is worse than an
- # absent one: it survives the None filter below and reads as a value.
if repo is not None:
- repo_hash = _scoped_digest(getattr(repo, "identity", ""))
- if repo_hash:
- properties["repo_hash"] = repo_hash
+ properties["repo_hash"] = _digest(getattr(repo, "identity", ""))
if session_id:
- session_hash = _scoped_digest(session_id)
- if session_hash:
- properties["session_hash"] = session_hash
+ properties["session_hash"] = _digest(session_id)
line = json.dumps(
{
"event": f"{EVENT_PREFIX}.{event}",
- "uuid": str(uuid.uuid4()),
"timestamp": memory_core.utc_now(),
"properties": {
key: value for key, value in properties.items() if value is not None
@@ -576,201 +239,38 @@ def spawn_flush() -> bool:
return False
-def _claim_name(attempt: int = 0) -> str:
- """Claim filename. The attempt count rides in the name so the 7-day expiry
- only ever discards a batch that was actually retried and failed."""
- return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending"
-
-
-def _claim_attempt(claim: Path) -> int:
- """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape.
-
- Anchored on field position, not on a leading "a": the legacy shape is
- ``telemetry--.sending`` and a hex id such as ``a1234567`` would
- otherwise parse as attempt 1234567 and be discarded unsent on the first
- flush after an upgrade.
- """
- stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name
- parts = stem.split("-")
- if len(parts) != 4:
- return 0
- tail = parts[3]
- if tail.startswith("a") and tail[1:].isdigit():
- return int(tail[1:])
- return 0
-
-
-def _touch(path: Path) -> None:
- """Refresh mtime so a claim's age measures time since it was claimed.
-
- ``Path.replace`` is ``os.rename``, which preserves mtime โ so a claim created
- after a quiet minute inherited the spool's last-write time and looked
- abandoned the instant it was made. A second sender would then take it over
- while the first was still posting, and both would deliver the batch.
- """
- try:
- os.utime(path, None)
- except OSError:
- pass
-
-
def _claim_spool() -> Path | None:
"""Rename the spool aside so exactly one sender owns each batch."""
directory = memory_core.data_dir()
- claim = directory / _claim_name()
+ claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending"
spool = _spool_path()
try:
spool.replace(claim)
- _touch(claim)
return claim
except OSError:
pass
- return _claim_parked(directory)
-
-
-def _sweep_debris(directory: Path) -> None:
- """Remove files nothing else will ever pick up again.
-
- *.partial is a temp file orphaned by a crash between write and rename.
- *.corrupt is a batch quarantined for undecodable content. No glob in this
- module matches either, so without this they accumulate on disk for the life
- of the install.
-
- Quarantined batches are kept far longer than debris: they are the only
- evidence left of events that could not be delivered, and someone diagnosing
- a report of missing telemetry has to be able to find one.
- """
now = time.time()
- for debris in directory.glob("telemetry-*.partial"):
- try:
- if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS:
- debris.unlink()
- except OSError:
- continue
- for quarantined in directory.glob("telemetry-*.corrupt"):
- try:
- if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS:
- quarantined.unlink()
- except OSError:
- continue
- # The same reasoning covers *.tmp. _write_identity and _install_salt both
- # create one and unlink it in a finally, which a SIGKILL skips, and no glob
- # in this module matches the leftovers either.
- for temporary in directory.glob("telemetry-*.tmp"):
- try:
- if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS:
- temporary.unlink()
- except OSError:
- continue
-
-
-def _claim_parked(directory: Path) -> Path | None:
- """Take the oldest abandoned claim, if any lease has actually expired.
-
- Kept separate from the live spool so flush() can drain both in one run.
- Previously parked batches were only reachable when no spool existed at all,
- and because sessions keep recording there usually was one โ so a batch
- parked by a failed send waited until the 7-day expiry deleted it unsent,
- even though its own presence is what started the sender.
- """
- now = time.time()
- for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime):
+ for orphan in sorted(directory.glob("telemetry-*.sending")):
try:
age = now - orphan.stat().st_mtime
except OSError:
continue
- if age < CLAIM_STALE_SECONDS:
- # Someone else holds a live lease on it. This check has to come
- # first. Claiming a file bumps its attempt count and refreshes its
- # mtime, so a sender that has just taken the final attempt looks
- # exhausted to everyone else while it is actively draining. Judging
- # exhaustion before liveness let a second sender unlink a batch out
- # from under its owner, losing every event in it.
- continue
- # Attempts, not age. Every re-claim touches the mtime and every release
- # backdates it by a fixed amount, so age is pinned near the stale
- # threshold and never reaches the expiry. Age stays only as a backstop
- # for files that never carried an attempt marker.
- if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS:
+ if age > CLAIM_EXPIRY_SECONDS:
try:
orphan.unlink()
except OSError:
pass
continue
- claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1)
+ if age < CLAIM_STALE_SECONDS:
+ continue
try:
orphan.replace(claim)
- _touch(claim)
return claim
except OSError:
continue
return None
-def _safe_mtime(path: Path) -> float:
- try:
- return path.stat().st_mtime
- except OSError:
- return 0.0
-
-
-def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool:
- """Persist the unsent remainder, atomically, and refresh the lease.
-
- Called after every successful batch. Two jobs: a retry resumes where the
- send stopped instead of re-posting from the top, and the rewrite doubles as
- the lease heartbeat, so a slow sender does not have its claim stolen
- mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS.
- """
- if not remaining:
- try:
- claim.unlink()
- except OSError:
- pass
- return True
- temporary = claim.with_suffix(f".{os.getpid()}.partial")
- try:
- payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining)
- # fsync before the rename: without it the rename can land while the
- # bytes have not, and the claim comes back empty or truncated after a
- # crash. _drain then reads zero events and unlinks it.
- with open(temporary, "w", encoding="utf-8") as handle:
- handle.write(payload)
- handle.flush()
- os.fsync(handle.fileno())
- temporary.replace(claim)
- _touch(claim)
- return True
- except OSError:
- try:
- temporary.unlink()
- except OSError:
- pass
- return False
-
-
-def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None:
- """Persist the remainder and drop the lease, because this sender has given up.
-
- Distinct from the per-batch heartbeat: heartbeating on the way out would
- make an abandoned batch look actively owned for a further
- CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the
- threshold lets the next flush pick it up immediately, while the attempt
- count in the filename still bounds how many times that can happen.
- """
- if not _rewrite_claim(claim, remaining):
- return
- try:
- # Backdate past the stale threshold so the next flush can pick it up,
- # minus a cooldown that grows with the attempts already spent. Clamped so
- # the mtime never lands in the future, which would read as a live lease.
- cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS)
- released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown
- os.utime(claim, (released, released))
- except OSError:
- pass
-
-
def _resolve_email(key: str) -> str:
"""Trade the API key for the account email so events join other Mem0 surfaces."""
url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/"
@@ -800,130 +300,34 @@ def _post(payload: dict[str, Any], url: str) -> bool:
def resolve_distinct_id() -> tuple[str, str]:
- """Return the PostHog distinct id and the anonymous id it replaced, if any.
-
- The second value becomes a PostHog $identify alias. It is ONLY ever an
- anonymous id: aliasing one account email to another merges two real person
- profiles and cannot be undone, so a key that now belongs to a different
- account re-resolves with no alias.
- """
+ """Return the PostHog distinct id and the anonymous id it replaced, if any."""
identity = _read_identity()
- key = memory_core.api_key()
- fingerprint = _digest(key) if key else ""
email = identity.get("email", "")
-
- if email and fingerprint:
- recorded = identity.get("key_fingerprint", "")
- if recorded == fingerprint:
- return email, ""
- if not recorded:
- # Rows written before fingerprints existed. Verify rather than
- # adopt: a key changed before the upgrade would otherwise bind the
- # new key to the previous account's email, permanently, and the
- # fingerprint would then agree with itself forever after.
- verified = _resolve_email(key)
- if not verified:
- # Offline, firewalled, or the API is down. Keep the previous
- # behaviour and retry on the next flush rather than dropping a
- # real account attribution. Safe because the same network that
- # failed /v1/ping/ is about to fail the PostHog POST, so nothing
- # is delivered under the unverified identity in the meantime.
- return email, ""
- identity["email"] = verified
- identity["key_fingerprint"] = fingerprint
- _write_identity(identity)
- return verified, ""
-
+ if email:
+ return email, ""
+ key = memory_core.api_key()
if not key:
- # No key to verify the account with; do not keep attributing to it.
- if email:
- identity.pop("email", None)
- identity.pop("key_fingerprint", None)
- return _rotate_anonymous_id(identity), ""
return anonymous_id(identity), ""
-
- resolved = _resolve_email(key)
- if not resolved:
- # The key changed and will not resolve (revoked, offline, API down).
- # Reaching here with an email means the recorded fingerprint disagreed,
- # so the key really did change. Drop the account and rotate: the stored
- # anonymous id may already be merged into that account's person, and
- # reusing it would keep the events on the profile we are trying to
- # leave.
- if email:
- identity.pop("email", None)
- identity.pop("key_fingerprint", None)
- return _rotate_anonymous_id(identity), ""
+ email = _resolve_email(key)
+ if not email:
return anonymous_id(identity), ""
-
- # Alias only when going anonymous -> email for the first time. Once an anon
- # id has been merged into an account it must never be offered again: an
- # alias naming an already-identified id is what could link two real people.
- previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "")
- if previous:
- identity["aliased"] = True
- identity["email"] = resolved
- identity["key_fingerprint"] = fingerprint
+ previous = identity.get("anonymous_id", "")
+ identity["email"] = email
_write_identity(identity)
- return resolved, previous
+ return email, previous
def flush() -> int:
- """Drain the live spool, then any parked claims, and return events sent."""
+ """Drain claimed spools to PostHog and return the number of events sent."""
if not is_enabled():
return 0
- sent, delivered = _drain(_claim_spool())
- if not delivered:
- # The network is failing. Retrying other batches now would only burn
- # their attempt budget against the same broken connection.
- return sent
-
- # Parked batches used to starve behind the live spool indefinitely. Bounded
- # per run so a long backlog cannot turn one flush into an unbounded loop.
- directory = memory_core.data_dir()
- _sweep_debris(directory)
- for _ in range(MAX_PARKED_PER_RUN):
- parked = _claim_parked(directory)
- if parked is None:
- break
- count, delivered = _drain(parked)
- sent += count
- if not delivered:
- break
- return sent
-
-
-def _drain(claim: Path | None) -> tuple[int, bool]:
- """Post one claimed batch file, recording progress after every batch.
-
- Returns (events sent, whether everything was delivered).
- """
+ claim = _claim_spool()
if claim is None:
- return 0, True
+ return 0
try:
lines = claim.read_text(encoding="utf-8").splitlines()
- except ValueError:
- # UnicodeDecodeError from a torn write: the content is unrecoverable, so
- # quarantine rather than retry. flush() runs from a bare `finally:` in
- # flush_worker, so raising here also skips the handoff cleanup, and an
- # undecodable file would otherwise be re-read on every flush forever.
- # Reported as delivered because there is nothing left to deliver and the
- # rest of the run should continue.
- try:
- claim.replace(claim.with_suffix(".corrupt"))
- except OSError:
- try:
- claim.unlink()
- except OSError:
- pass
- return 0, True
except OSError:
- # Could not read it, which is not the same as having nothing to send.
- # The file is left exactly where it is: a vanished or briefly unreadable
- # claim is retryable, and quarantining it here would discard events over
- # a transient filesystem error. Reported as undelivered so the run stops
- # instead of counting a batch nothing was posted from as delivered.
- return 0, False
+ return 0
events = []
for line in lines:
try:
@@ -933,18 +337,11 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
if isinstance(value, dict) and value.get("event"):
events.append(value)
if not events:
- # Only delete when the file really is empty. A non-empty file that
- # parses to nothing is a torn write, and its contents are the unsent
- # remainder โ deleting it is the data loss this PR exists to prevent.
try:
- empty = claim.stat().st_size == 0
- except OSError:
- empty = True
- try:
- claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink()
+ claim.unlink()
except OSError:
pass
- return 0, True
+ return 0
distinct_id, aliased_anonymous_id = resolve_distinct_id()
if aliased_anonymous_id:
@@ -963,17 +360,12 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
sent = 0
for start in range(0, len(events), BATCH_SIZE):
- chunk = events[start : start + BATCH_SIZE]
batch = [
{
"event": event["event"],
"distinct_id": distinct_id,
- # Carried through from record() so a resend can be collapsed.
- "uuid": event.get("uuid"),
"timestamp": event.get("timestamp"),
"properties": {
- # Fallback only: events recorded by a build before source
- # moved into record() have none of their own.
"source": _source_tag,
"language": "python",
"$process_person_profile": False,
@@ -981,24 +373,16 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
**(event.get("properties") or {}),
},
}
- for event in chunk
+ for event in events[start : start + BATCH_SIZE]
]
if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL):
- # Keep only what has not been delivered, and release the lease.
- # Previously the whole file was kept and the retry re-posted every
- # batch, including the ones that had already arrived.
- _release_claim(claim, events[start:])
- return sent, False
- sent += len(chunk)
- # Record progress and refresh the lease after each successful batch, so
- # a crash repeats at most one batch instead of the entire file. If the
- # rewrite fails the claim still holds delivered events, so stop rather
- # than carry on as though progress were recorded โ continuing is how the
- # duplicate delivery this PR fixes would come back.
- if not _rewrite_claim(claim, events[start + len(chunk) :]):
- _release_claim(claim, events[start + len(chunk) :])
- return sent, False
- return sent, True
+ return sent
+ sent += len(batch)
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return sent
def main() -> int:
diff --git a/integrations/kimi-plugin/kimi.plugin.json b/integrations/kimi-plugin/kimi.plugin.json
index 6b28575d3..0d63501fe 100644
--- a/integrations/kimi-plugin/kimi.plugin.json
+++ b/integrations/kimi-plugin/kimi.plugin.json
@@ -1,6 +1,6 @@
{
"name": "mem0",
- "version": "0.3.3",
+ "version": "0.3.1",
"description": "Cross-session memory and token savings for coding agents.",
"keywords": ["memory", "coding-agents", "continual-learning", "token-efficiency"],
"author": { "name": "Mem0", "email": "support@mem0.ai" },
diff --git a/integrations/kimi-plugin/plugin-build.json b/integrations/kimi-plugin/plugin-build.json
index 35e38ecf5..3926a57df 100644
--- a/integrations/kimi-plugin/plugin-build.json
+++ b/integrations/kimi-plugin/plugin-build.json
@@ -1,6 +1,6 @@
{
"id": "mem0",
- "version": "0.3.3",
+ "version": "0.3.1",
"homepage": "https://docs.mem0.ai/integrations/kimi",
"native": {
"pluginRoot": "${KIMI_PLUGIN_ROOT}",
diff --git a/integrations/kimi-plugin/skills/pause/SKILL.md b/integrations/kimi-plugin/skills/pause/SKILL.md
index 8f93e3bf7..9f217a468 100644
--- a/integrations/kimi-plugin/skills/pause/SKILL.md
+++ b/integrations/kimi-plugin/skills/pause/SKILL.md
@@ -7,8 +7,8 @@ disable-model-invocation: true
# Pause memory capture
To pause (hooks stop capturing and sending session content; a minimal
-telemetry ping still fires at session start, under your Mem0 account email,
-unless `MEM0_TELEMETRY=false`):
+anonymous telemetry ping still fires at session start unless
+`MEM0_TELEMETRY=false`):
```bash
python3 "${KIMI_PLUGIN_ROOT}/core/memory_cli.py" --harness "kimi" pause
diff --git a/integrations/kimi-plugin/skills/search/SKILL.md b/integrations/kimi-plugin/skills/search/SKILL.md
index 316b78e53..eb92a6ca8 100644
--- a/integrations/kimi-plugin/skills/search/SKILL.md
+++ b/integrations/kimi-plugin/skills/search/SKILL.md
@@ -12,9 +12,11 @@ Call `search_memories` with the user's question. Treat `--top-k`, `--category`,
query.
Omit `top_k` to use Mem0's configured default. Omit `category` to search every
-category. Omit `scope` to use the configured default, normally `repo`: this
-repository's shared memory, which everyone who works in it contributes to,
-plus your own preferences.
+category; a category is a best-effort label Mem0 assigned when it saved the
+memory, so if a category search misses, repeat it without the category. Omit
+`scope` to use the configured default, normally `repo`: this repository's
+shared memory, which everyone who works in it contributes to, plus your own
+preferences.
Pass `scope` when the question needs something else: `dir` to narrow the
shared memory to the directory you are working in (a package inside a
diff --git a/integrations/mem0-agent-plugin/core/_harness_id.py b/integrations/mem0-agent-plugin/core/_harness_id.py
deleted file mode 100644
index 3efd000f8..000000000
--- a/integrations/mem0-agent-plugin/core/_harness_id.py
+++ /dev/null
@@ -1,11 +0,0 @@
-"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""
-
-HARNESS_ID = "coding-agent"
-SOURCE_TAG = "CODING_AGENT_PLUGIN"
-
-# Platform-side vocabulary (mem0_event.source + X-Application). The whole
-# plugin family is one source; which editor it runs in is the application.
-# An empty application means the host is unknown, and memory_core omits
-# the header entirely rather than sending a placeholder.
-PLATFORM_SOURCE = "MEM0_PLUGIN"
-PLATFORM_APPLICATION = ""
diff --git a/integrations/mem0-agent-plugin/core/mcp_server.py b/integrations/mem0-agent-plugin/core/mcp_server.py
index a0b73cb79..036fbbdc9 100644
--- a/integrations/mem0-agent-plugin/core/mcp_server.py
+++ b/integrations/mem0-agent-plugin/core/mcp_server.py
@@ -21,9 +21,16 @@ from memory_core import (
PROTOCOL_VERSION = "2024-11-05"
TOOL_NAME = "search_memories"
TOOL_DESCRIPTION = (
- "Search memories from earlier work in this repository. Use it before "
- "repeating investigation or when earlier decisions, fixes, commands, or "
- "results may help."
+ "Search memories from earlier work in this repository. ALWAYS call this "
+ "tool before answering anything that could depend on prior context: the "
+ "user's preferences, facts about this codebase, history, people, projects, "
+ "or earlier decisions. Do not rely on the chat window alone. The "
+ "repository's memory is shared by everyone who works in it and includes "
+ "what it took to run, test, or build here, so search before assuming an "
+ "invocation works. The scope argument changes what is searched: 'repo' "
+ "(default) is the whole repository's shared memory plus your own "
+ "preferences, 'dir' narrows the shared part to the directory you are "
+ "working in, and 'mine' is your preferences alone."
)
TOOL_SCHEMA = {
"type": "object",
diff --git a/integrations/mem0-agent-plugin/core/memory_core.py b/integrations/mem0-agent-plugin/core/memory_core.py
index 9b420a063..77d7a2b80 100644
--- a/integrations/mem0-agent-plugin/core/memory_core.py
+++ b/integrations/mem0-agent-plugin/core/memory_core.py
@@ -29,7 +29,7 @@ from typing import Any, Iterable
import telemetry
DEFAULT_API_URL = "https://api.mem0.ai"
-PLUGIN_VERSION = "0.3.3"
+PLUGIN_VERSION = "0.3.1"
_harness_name: str = "generic"
_harness_env_prefix: str = "MEM0_PLUGIN"
@@ -71,13 +71,15 @@ MAX_FLUSH_ATTEMPTS = 5
FORGET_PAGE_SIZE = 100
FORGET_MAX_PAGES = 50
-PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work.
+PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository.
A completed change should produce one memory explaining the resulting behavior, where it is implemented when useful, and any important constraints or reasoning. Exploration or accepted decisions may produce separate memories only when they are independently useful.
-Use the coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+A command that failed and was then made to work should produce one memory naming the failing invocation, the error it returned, and the invocation that succeeded. Do not save one-off errors caused by an edit still in progress, transient network failures, or anything a rerun would fix on its own.
-Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state.
+Use the current coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions.
+
+Write about the repository, not the user, assistant, session, or task. Do not save personal preferences. Do not save a memory that only states which repository, branch, or directory the session worked in. Do not include test results, documentation updates, release notes, or temporary state.
If nothing useful was established, return no memories."""
@@ -1798,34 +1800,6 @@ def extraction_message_batches(
return batches
-# Platform surface attribution. Read from the generated per-host module so a new
-# entrypoint is correct without remembering to configure anything.
-try: # pragma: no cover - absent only in the un-built shared source tree
- from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
- from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
-except ImportError:
- _PLATFORM_SOURCE = "MEM0_PLUGIN"
- _PLATFORM_APPLICATION = ""
-
-
-def platform_headers(key: str) -> dict[str, str]:
- """Auth plus the three surface-identity headers.
-
- X-Mem0-Source and X-Application are set-once by contract: this is the
- outermost layer, so it sets them, and nothing below may overwrite them.
- X-Mem0-Client is append-only โ anything downstream adds itself to the tail.
- """
- headers = {
- "Authorization": f"Token {key}",
- "Content-Type": "application/json",
- "X-Mem0-Source": _PLATFORM_SOURCE,
- "X-Mem0-Client": f"mem0-plugin/{PLUGIN_VERSION}",
- }
- if _PLATFORM_APPLICATION:
- headers["X-Application"] = _PLATFORM_APPLICATION
- return headers
-
-
def _request_json(
url: str, key: str, payload: dict[str, Any], timeout: float
) -> tuple[dict[str, Any] | list[Any], int, int]:
@@ -1833,7 +1807,7 @@ def _request_json(
request = urllib.request.Request(
url,
data=raw,
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -1860,7 +1834,7 @@ def _get_json(
) -> tuple[dict[str, Any] | list[Any], int]:
request = urllib.request.Request(
url,
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="GET",
)
with urllib.request.urlopen(request, timeout=timeout) as response:
@@ -2006,13 +1980,6 @@ def flush_session(
"user_id": write_user,
"app_id": repo.app_id,
"run_id": session_id,
- # Top level, not metadata: the backend reads `source` from the body or
- # the query string, never from metadata, which is where this used to
- # sit. The X-Mem0-Source header is also read, but only from the
- # platform release that ships alongside this change, so the body value
- # is what makes attribution work on both. The harness tag stays in
- # metadata as hook provenance.
- "source": _PLATFORM_SOURCE,
"metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)},
"agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS,
"custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS,
@@ -2556,7 +2523,7 @@ def _collect_memory_ids(
def _delete_memory(api_url: str, key: str, memory_id: str) -> bool:
request = urllib.request.Request(
f"{api_url}/v1/memories/{urllib.parse.quote(memory_id)}/",
- headers=platform_headers(key),
+ headers={"Authorization": f"Token {key}", "Content-Type": "application/json"},
method="DELETE",
)
try:
diff --git a/integrations/mem0-agent-plugin/core/telemetry.py b/integrations/mem0-agent-plugin/core/telemetry.py
index c1fc0084c..249595475 100644
--- a/integrations/mem0-agent-plugin/core/telemetry.py
+++ b/integrations/mem0-agent-plugin/core/telemetry.py
@@ -1,9 +1,5 @@
#!/usr/bin/env python3
-"""Usage telemetry for Mem0 agent plugins.
-
-Events are linked to your Mem0 account email when an API key is configured, and
-to a random per-machine id otherwise. Not anonymous โ the Python SDK and CLI
-attribute the same way.
+"""Anonymous usage telemetry for Mem0 agent plugins.
Hooks run on a 3-6 second budget and fire on every tool call, so recording never
touches the network: `record` appends one JSON line to a local spool and returns.
@@ -13,8 +9,7 @@ started once per session and again from the flush worker that is already detache
Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false.
Never sends prompts, memory text, queries, file paths, repository names, or API
-keys: only event names, durations, counts, coarse outcomes, and repo/session
-identifiers hashed with a random per-install salt.
+keys: only event names, durations, counts, coarse outcomes, and salted hashes.
"""
from __future__ import annotations
@@ -34,24 +29,8 @@ from typing import Any
import memory_core
-# Seeded from the per-host module the build generates into core/. Two processes
-# in this pipeline never call init() โ mcp_server.py, and the detached
-# `python3 telemetry.py` sender that spawn_flush() starts โ so a module default
-# was what every one of their events got labelled with.
-try: # pragma: no cover - absent only in the un-built shared source tree
- from _harness_id import HARNESS_ID as _DEFAULT_HARNESS
- from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION
- from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE
- from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG
-except ImportError:
- _DEFAULT_HARNESS = "generic"
- _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN"
- _PLATFORM_SOURCE = "MEM0_PLUGIN"
- _PLATFORM_APPLICATION = ""
-
-_salt_cache: str = ""
-_harness: str = _DEFAULT_HARNESS
-_source_tag: str = _DEFAULT_SOURCE_TAG
+_harness: str = "generic"
+_source_tag: str = "MEM0_PLUGIN"
_PRIVATE_KEYS = {
"apikey",
"authorization",
@@ -77,19 +56,10 @@ _PRIVATE_KEYS = {
}
-def init(harness: str = "", source_tag: str = "") -> None:
- """Override the generated identity. Optional โ core/_harness_id.py is the default.
-
- The fallback shape matches memory_core.configure_harness's (``_PLUGIN``).
- It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which
- meant one plugin could emit three different source values depending on which
- process happened to send the batch.
- """
+def init(harness: str = "generic", source_tag: str = "") -> None:
global _harness, _source_tag
- _harness = harness or _DEFAULT_HARNESS
- _source_tag = source_tag or (
- f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG
- )
+ _harness = harness
+ _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN"
POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"
POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/"
@@ -100,16 +70,6 @@ BATCH_SIZE = 100
SEND_TIMEOUT = 5
CLAIM_STALE_SECONDS = 120
CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60
-# A batch is only discarded once it has genuinely been retried this many times.
-MAX_CLAIM_ATTEMPTS = 3
-# Parked claims drained per run, after the live spool. Bounded so a long backlog
-# cannot turn one flush into an unbounded send loop.
-MAX_PARKED_PER_RUN = 3
-# Added to the wait before a released claim becomes reclaimable, per attempt
-# already spent. Releasing straight to "reclaimable now" let two senders burn the
-# whole budget within seconds of one another on a single momentary failure, and
-# discard a batch a retry a minute later would have delivered.
-RETRY_COOLDOWN_SECONDS = 60
def is_enabled() -> bool:
@@ -123,126 +83,9 @@ def is_enabled() -> bool:
def _digest(value: str, length: int = 16) -> str:
- """Unsalted digest. Only for values that are already secrets (API keys)."""
return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length]
-def _salt_path() -> Path:
- return memory_core.data_dir() / "telemetry-salt"
-
-
-def _install_salt() -> str:
- """Random per-install salt, created once and memoized for the process.
-
- Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in
- the identity file. Three reasons, all of which produced wrong data when this
- lived in the identity dict:
-
- - Hooks are short-lived separate processes firing on every tool call, and
- people run more than one agent window. A read-modify-write would let each
- process mint its own salt, so one repository would hash several ways in the
- window before a writer won.
- - resolve_distinct_id holds a copy of the identity dict across a network call
- to /v1/ping/, so whichever write landed second erased the other's key โ
- losing either the salt (repo_hash changes mid-stream) or the email (a
- second $identify, splitting the person).
- - Touching the identity file from record() would create it, and is_first_run
- keys off that file, so recording an event would silently suppress the
- install event.
-
- Published atomically, and there is deliberately no derived fallback. Creating
- the file with O_CREAT|O_EXCL and then writing into it leaves a window where
- the file exists and is empty, and a concurrent hook that reads it in that
- window gets nothing. Falling back to a digest of the path would hand that
- process a salt an attacker can compute, memoized for its whole run, which is
- the privacy control this function exists to provide silently turning itself
- off under load. The salt is written to a private temp file first and linked
- into place, so the name either does not exist or already has the full value.
-
- Returns "" when it genuinely cannot persist. Callers omit the hash entirely
- rather than emit an unsalted one.
- """
- global _salt_cache
- if _salt_cache:
- return _salt_cache
-
- path = _salt_path()
- # Read before writing. Hooks are separate processes firing on every tool
- # call, so all but the first find the salt already published; going straight
- # to create-fsync-link-unlink meant every one of them paid an fsync to
- # discover that, on a path whose whole promise is appending a line and
- # returning.
- try:
- _salt_cache = path.read_text(encoding="utf-8").strip()
- if _salt_cache:
- return _salt_cache
- except OSError:
- pass
-
- temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp")
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(handle, "w", encoding="utf-8") as stream:
- stream.write(uuid.uuid4().hex)
- stream.flush()
- os.fsync(stream.fileno())
- try:
- # Atomic claim: fails if another process already published one.
- # os.link rather than replace, which would clobber theirs.
- os.link(temporary, path)
- except FileExistsError:
- pass
- except OSError:
- # No hardlinks here (some network mounts, some container volumes).
- # Claim the name directly instead. That reopens the empty-file
- # window, but the window is now benign: a reader that lands in it
- # gets "" and omits the hash for that process rather than caching a
- # guessable one. Losing the hashes on every run of an entire
- # filesystem is the worse failure.
- try:
- fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- with os.fdopen(fallback, "w", encoding="utf-8") as stream:
- stream.write(temporary.read_text(encoding="utf-8"))
- except OSError:
- pass
- except OSError:
- pass
- finally:
- try:
- temporary.unlink()
- except OSError:
- pass
-
- try:
- _salt_cache = path.read_text(encoding="utf-8").strip()
- except OSError:
- _salt_cache = ""
- return _salt_cache
-
-
-def _scoped_digest(value: str, length: int = 16) -> str:
- """Salted digest for values drawn from a guessable space.
-
- repo.identity is a git remote URL, or ``local:`` when there is
- no remote โ which normally contains the account username. Sixteen unsalted
- hex characters over that input space is enumerable, so this is not a
- privacy control without the salt. Salting per install keeps every
- within-account join the analytics actually use and gives up only
- cross-machine joins on the same repository, which nothing computes.
-
- Returns "" when there is no salt, so record() omits the property. An
- unsalted digest over this input space is close to plaintext, and emitting one
- under a name that implies it is hashed is worse than sending nothing.
- """
- if not value:
- return ""
- salt = _install_salt()
- if not salt:
- return ""
- return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length]
-
-
def _safe_value(value: Any) -> Any:
if isinstance(value, str):
return memory_core.redact(value)
@@ -302,176 +145,9 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str:
return created
-def _rotate_anonymous_id(identity: dict[str, str]) -> str:
- """Mint a fresh anonymous id because the account context is gone.
-
- The previous id may already have been merged into a person profile by an
- $identify, and that merge is permanent. Reusing it after a logout or a key
- change attributes everything that follows to the account that just went
- away, which is the same misattribution the key fingerprint exists to stop,
- only arriving through the anonymous path instead.
-
- `aliased` is cleared with it: the new id has never been merged, so it is
- eligible to be aliased into whatever account comes next.
- """
- created = f"code-anon-{uuid.uuid4().hex}"
- identity["anonymous_id"] = created
- identity.pop("aliased", None)
- _write_identity(identity)
- return created
-
-
-def _install_state_path() -> Path:
- return memory_core.data_dir() / "install-state.json"
-
-
def is_first_run() -> bool:
- """Whether install has never been recorded on this machine.
-
- Deliberately NOT the identity file. That file is only written by a
- successful flush, so an offline or firewalled user recorded code.install on
- every single session, forever โ and every 0.2.x user recorded one on their
- first 0.3.x session because 0.2.x never wrote it at all.
- """
- return not _install_state_path().exists()
-
-
-def data_dir_was_empty() -> bool:
- """Whether the data directory is untouched. Call BEFORE anything writes to it.
-
- hook_runner reaches claim_install() only after cache_plugin_api_key() has
- written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so
- asking at claim time always saw content and every fresh install reported an
- upgrade. The caller snapshots this at the top of the run instead.
- """
- return not _data_dir_has_content()
-
-
-def claim_install(was_empty: bool | None = None) -> str | None:
- """Claim the one install/upgrade record for this machine, atomically.
-
- Returns the event to record ("install" or "upgrade"), or None if another
- session already claimed it. O_CREAT|O_EXCL so two sessions starting together
- cannot both win.
-
- `was_empty` must come from data_dir_was_empty() called before this process
- wrote anything. Omitting it falls back to checking now, which is only
- correct for a caller that has touched nothing.
- """
- if not is_enabled():
- # Never consume the one-shot claim while the user is opted out, or they
- # would silently lose their install event if they later opt in.
- return None
-
- path = _install_state_path()
- upgrading = not (data_dir_was_empty() if was_empty is None else was_empty)
- try:
- path.parent.mkdir(parents=True, exist_ok=True)
- handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
- except FileExistsError:
- return None
- except OSError:
- return None
- try:
- with os.fdopen(handle, "w", encoding="utf-8") as stream:
- json.dump(
- {
- "plugin_version": memory_core.PLUGIN_VERSION,
- "installed_at": memory_core.utc_now(),
- "upgraded": upgrading,
- },
- stream,
- )
- # Durable before this returns. The O_EXCL open is what makes the
- # claim exclusive, so it cannot be replaced by a temp-and-rename
- # without losing that, which leaves the content as the thing to make
- # safe. A kill between the open and this fsync used to leave a marker
- # that exists but parses to nothing: is_first_run reads it as claimed
- # and claim_version_change cannot read a version out of it.
- stream.flush()
- os.fsync(stream.fileno())
- except OSError:
- pass
- return "upgrade" if upgrading else "install"
-
-
-def _data_dir_has_content() -> bool:
- """Whether anything predates this session in the plugin data directory."""
- try:
- for entry in memory_core.data_dir().iterdir():
- if entry.name != "install-state.json":
- return True
- except OSError:
- pass
- return False
-
-
-def _repair_install_state(path: Path) -> None:
- """Rewrite an unparseable marker so version tracking can resume."""
- try:
- temporary = path.with_suffix(f".{os.getpid()}.tmp")
- temporary.write_text(
- json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}),
- encoding="utf-8",
- )
- temporary.replace(path)
- except OSError:
- pass
-
-
-def claim_version_change() -> str | None:
- """Return the previously recorded version if it differs, updating the marker.
-
- Only meaningful once the marker exists โ the first transition into 0.3.x has
- no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting
- the marker means the next session sees no change and records nothing.
- """
- path = _install_state_path()
- try:
- state = json.loads(path.read_text(encoding="utf-8"))
- except OSError:
- return None
- except json.JSONDecodeError:
- # A crash between O_EXCL and the write leaves an empty marker. Left
- # alone it disables every future upgrade event on this machine, because
- # claim_install sees the file and this function cannot parse it.
- state = None
- if not isinstance(state, dict):
- _repair_install_state(path)
- return None
- previous = str(state.get("plugin_version") or "")
- if not previous or previous == memory_core.PLUGIN_VERSION:
- return None
- # Claim the transition with an exclusive sentinel before rewriting the
- # marker. A plain read-modify-write let every concurrently starting session
- # observe the old version and each record its own upgrade โ and the first
- # session after a version bump is exactly when several agent windows restart
- # together.
- sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}")
- try:
- os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
- except FileExistsError:
- return None
- except OSError:
- return None
-
- state["plugin_version"] = memory_core.PLUGIN_VERSION
- state["upgraded_at"] = memory_core.utc_now()
- temporary = path.with_suffix(f".{os.getpid()}.tmp")
- try:
- temporary.write_text(json.dumps(state), encoding="utf-8")
- temporary.replace(path)
- except OSError:
- # Release the claim. The marker still records the old version, so
- # without this the sentinel makes claim_version_change return early on
- # every later run and this version's upgrade is never recorded again.
- for leftover in (sentinel, temporary):
- try:
- leftover.unlink()
- except OSError:
- pass
- return None
- return previous
+ """Whether this machine has never recorded a plugin event before."""
+ return not _identity_path().exists()
def record(
@@ -492,32 +168,19 @@ def record(
except OSError:
pass
properties = _safe_value(properties)
- # Stamped in the RECORDING process, beside harness. `source` used to be
- # read in the sending process from a module global, so whichever process
- # drained the spool named every event in it. flush() spreads per-event
- # properties last, so this now wins over any sender's default.
properties.update(
harness=_harness,
- source=_source_tag,
plugin_version=memory_core.PLUGIN_VERSION,
os=sys.platform,
python_version=platform.python_version(),
)
- # Assigned only when the digest is real. _scoped_digest returns "" when
- # the salt could not be persisted, and an empty property is worse than an
- # absent one: it survives the None filter below and reads as a value.
if repo is not None:
- repo_hash = _scoped_digest(getattr(repo, "identity", ""))
- if repo_hash:
- properties["repo_hash"] = repo_hash
+ properties["repo_hash"] = _digest(getattr(repo, "identity", ""))
if session_id:
- session_hash = _scoped_digest(session_id)
- if session_hash:
- properties["session_hash"] = session_hash
+ properties["session_hash"] = _digest(session_id)
line = json.dumps(
{
"event": f"{EVENT_PREFIX}.{event}",
- "uuid": str(uuid.uuid4()),
"timestamp": memory_core.utc_now(),
"properties": {
key: value for key, value in properties.items() if value is not None
@@ -576,201 +239,38 @@ def spawn_flush() -> bool:
return False
-def _claim_name(attempt: int = 0) -> str:
- """Claim filename. The attempt count rides in the name so the 7-day expiry
- only ever discards a batch that was actually retried and failed."""
- return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending"
-
-
-def _claim_attempt(claim: Path) -> int:
- """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape.
-
- Anchored on field position, not on a leading "a": the legacy shape is
- ``telemetry--.sending`` and a hex id such as ``a1234567`` would
- otherwise parse as attempt 1234567 and be discarded unsent on the first
- flush after an upgrade.
- """
- stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name
- parts = stem.split("-")
- if len(parts) != 4:
- return 0
- tail = parts[3]
- if tail.startswith("a") and tail[1:].isdigit():
- return int(tail[1:])
- return 0
-
-
-def _touch(path: Path) -> None:
- """Refresh mtime so a claim's age measures time since it was claimed.
-
- ``Path.replace`` is ``os.rename``, which preserves mtime โ so a claim created
- after a quiet minute inherited the spool's last-write time and looked
- abandoned the instant it was made. A second sender would then take it over
- while the first was still posting, and both would deliver the batch.
- """
- try:
- os.utime(path, None)
- except OSError:
- pass
-
-
def _claim_spool() -> Path | None:
"""Rename the spool aside so exactly one sender owns each batch."""
directory = memory_core.data_dir()
- claim = directory / _claim_name()
+ claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending"
spool = _spool_path()
try:
spool.replace(claim)
- _touch(claim)
return claim
except OSError:
pass
- return _claim_parked(directory)
-
-
-def _sweep_debris(directory: Path) -> None:
- """Remove files nothing else will ever pick up again.
-
- *.partial is a temp file orphaned by a crash between write and rename.
- *.corrupt is a batch quarantined for undecodable content. No glob in this
- module matches either, so without this they accumulate on disk for the life
- of the install.
-
- Quarantined batches are kept far longer than debris: they are the only
- evidence left of events that could not be delivered, and someone diagnosing
- a report of missing telemetry has to be able to find one.
- """
now = time.time()
- for debris in directory.glob("telemetry-*.partial"):
- try:
- if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS:
- debris.unlink()
- except OSError:
- continue
- for quarantined in directory.glob("telemetry-*.corrupt"):
- try:
- if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS:
- quarantined.unlink()
- except OSError:
- continue
- # The same reasoning covers *.tmp. _write_identity and _install_salt both
- # create one and unlink it in a finally, which a SIGKILL skips, and no glob
- # in this module matches the leftovers either.
- for temporary in directory.glob("telemetry-*.tmp"):
- try:
- if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS:
- temporary.unlink()
- except OSError:
- continue
-
-
-def _claim_parked(directory: Path) -> Path | None:
- """Take the oldest abandoned claim, if any lease has actually expired.
-
- Kept separate from the live spool so flush() can drain both in one run.
- Previously parked batches were only reachable when no spool existed at all,
- and because sessions keep recording there usually was one โ so a batch
- parked by a failed send waited until the 7-day expiry deleted it unsent,
- even though its own presence is what started the sender.
- """
- now = time.time()
- for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime):
+ for orphan in sorted(directory.glob("telemetry-*.sending")):
try:
age = now - orphan.stat().st_mtime
except OSError:
continue
- if age < CLAIM_STALE_SECONDS:
- # Someone else holds a live lease on it. This check has to come
- # first. Claiming a file bumps its attempt count and refreshes its
- # mtime, so a sender that has just taken the final attempt looks
- # exhausted to everyone else while it is actively draining. Judging
- # exhaustion before liveness let a second sender unlink a batch out
- # from under its owner, losing every event in it.
- continue
- # Attempts, not age. Every re-claim touches the mtime and every release
- # backdates it by a fixed amount, so age is pinned near the stale
- # threshold and never reaches the expiry. Age stays only as a backstop
- # for files that never carried an attempt marker.
- if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS:
+ if age > CLAIM_EXPIRY_SECONDS:
try:
orphan.unlink()
except OSError:
pass
continue
- claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1)
+ if age < CLAIM_STALE_SECONDS:
+ continue
try:
orphan.replace(claim)
- _touch(claim)
return claim
except OSError:
continue
return None
-def _safe_mtime(path: Path) -> float:
- try:
- return path.stat().st_mtime
- except OSError:
- return 0.0
-
-
-def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool:
- """Persist the unsent remainder, atomically, and refresh the lease.
-
- Called after every successful batch. Two jobs: a retry resumes where the
- send stopped instead of re-posting from the top, and the rewrite doubles as
- the lease heartbeat, so a slow sender does not have its claim stolen
- mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS.
- """
- if not remaining:
- try:
- claim.unlink()
- except OSError:
- pass
- return True
- temporary = claim.with_suffix(f".{os.getpid()}.partial")
- try:
- payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining)
- # fsync before the rename: without it the rename can land while the
- # bytes have not, and the claim comes back empty or truncated after a
- # crash. _drain then reads zero events and unlinks it.
- with open(temporary, "w", encoding="utf-8") as handle:
- handle.write(payload)
- handle.flush()
- os.fsync(handle.fileno())
- temporary.replace(claim)
- _touch(claim)
- return True
- except OSError:
- try:
- temporary.unlink()
- except OSError:
- pass
- return False
-
-
-def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None:
- """Persist the remainder and drop the lease, because this sender has given up.
-
- Distinct from the per-batch heartbeat: heartbeating on the way out would
- make an abandoned batch look actively owned for a further
- CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the
- threshold lets the next flush pick it up immediately, while the attempt
- count in the filename still bounds how many times that can happen.
- """
- if not _rewrite_claim(claim, remaining):
- return
- try:
- # Backdate past the stale threshold so the next flush can pick it up,
- # minus a cooldown that grows with the attempts already spent. Clamped so
- # the mtime never lands in the future, which would read as a live lease.
- cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS)
- released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown
- os.utime(claim, (released, released))
- except OSError:
- pass
-
-
def _resolve_email(key: str) -> str:
"""Trade the API key for the account email so events join other Mem0 surfaces."""
url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/"
@@ -800,130 +300,34 @@ def _post(payload: dict[str, Any], url: str) -> bool:
def resolve_distinct_id() -> tuple[str, str]:
- """Return the PostHog distinct id and the anonymous id it replaced, if any.
-
- The second value becomes a PostHog $identify alias. It is ONLY ever an
- anonymous id: aliasing one account email to another merges two real person
- profiles and cannot be undone, so a key that now belongs to a different
- account re-resolves with no alias.
- """
+ """Return the PostHog distinct id and the anonymous id it replaced, if any."""
identity = _read_identity()
- key = memory_core.api_key()
- fingerprint = _digest(key) if key else ""
email = identity.get("email", "")
-
- if email and fingerprint:
- recorded = identity.get("key_fingerprint", "")
- if recorded == fingerprint:
- return email, ""
- if not recorded:
- # Rows written before fingerprints existed. Verify rather than
- # adopt: a key changed before the upgrade would otherwise bind the
- # new key to the previous account's email, permanently, and the
- # fingerprint would then agree with itself forever after.
- verified = _resolve_email(key)
- if not verified:
- # Offline, firewalled, or the API is down. Keep the previous
- # behaviour and retry on the next flush rather than dropping a
- # real account attribution. Safe because the same network that
- # failed /v1/ping/ is about to fail the PostHog POST, so nothing
- # is delivered under the unverified identity in the meantime.
- return email, ""
- identity["email"] = verified
- identity["key_fingerprint"] = fingerprint
- _write_identity(identity)
- return verified, ""
-
+ if email:
+ return email, ""
+ key = memory_core.api_key()
if not key:
- # No key to verify the account with; do not keep attributing to it.
- if email:
- identity.pop("email", None)
- identity.pop("key_fingerprint", None)
- return _rotate_anonymous_id(identity), ""
return anonymous_id(identity), ""
-
- resolved = _resolve_email(key)
- if not resolved:
- # The key changed and will not resolve (revoked, offline, API down).
- # Reaching here with an email means the recorded fingerprint disagreed,
- # so the key really did change. Drop the account and rotate: the stored
- # anonymous id may already be merged into that account's person, and
- # reusing it would keep the events on the profile we are trying to
- # leave.
- if email:
- identity.pop("email", None)
- identity.pop("key_fingerprint", None)
- return _rotate_anonymous_id(identity), ""
+ email = _resolve_email(key)
+ if not email:
return anonymous_id(identity), ""
-
- # Alias only when going anonymous -> email for the first time. Once an anon
- # id has been merged into an account it must never be offered again: an
- # alias naming an already-identified id is what could link two real people.
- previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "")
- if previous:
- identity["aliased"] = True
- identity["email"] = resolved
- identity["key_fingerprint"] = fingerprint
+ previous = identity.get("anonymous_id", "")
+ identity["email"] = email
_write_identity(identity)
- return resolved, previous
+ return email, previous
def flush() -> int:
- """Drain the live spool, then any parked claims, and return events sent."""
+ """Drain claimed spools to PostHog and return the number of events sent."""
if not is_enabled():
return 0
- sent, delivered = _drain(_claim_spool())
- if not delivered:
- # The network is failing. Retrying other batches now would only burn
- # their attempt budget against the same broken connection.
- return sent
-
- # Parked batches used to starve behind the live spool indefinitely. Bounded
- # per run so a long backlog cannot turn one flush into an unbounded loop.
- directory = memory_core.data_dir()
- _sweep_debris(directory)
- for _ in range(MAX_PARKED_PER_RUN):
- parked = _claim_parked(directory)
- if parked is None:
- break
- count, delivered = _drain(parked)
- sent += count
- if not delivered:
- break
- return sent
-
-
-def _drain(claim: Path | None) -> tuple[int, bool]:
- """Post one claimed batch file, recording progress after every batch.
-
- Returns (events sent, whether everything was delivered).
- """
+ claim = _claim_spool()
if claim is None:
- return 0, True
+ return 0
try:
lines = claim.read_text(encoding="utf-8").splitlines()
- except ValueError:
- # UnicodeDecodeError from a torn write: the content is unrecoverable, so
- # quarantine rather than retry. flush() runs from a bare `finally:` in
- # flush_worker, so raising here also skips the handoff cleanup, and an
- # undecodable file would otherwise be re-read on every flush forever.
- # Reported as delivered because there is nothing left to deliver and the
- # rest of the run should continue.
- try:
- claim.replace(claim.with_suffix(".corrupt"))
- except OSError:
- try:
- claim.unlink()
- except OSError:
- pass
- return 0, True
except OSError:
- # Could not read it, which is not the same as having nothing to send.
- # The file is left exactly where it is: a vanished or briefly unreadable
- # claim is retryable, and quarantining it here would discard events over
- # a transient filesystem error. Reported as undelivered so the run stops
- # instead of counting a batch nothing was posted from as delivered.
- return 0, False
+ return 0
events = []
for line in lines:
try:
@@ -933,18 +337,11 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
if isinstance(value, dict) and value.get("event"):
events.append(value)
if not events:
- # Only delete when the file really is empty. A non-empty file that
- # parses to nothing is a torn write, and its contents are the unsent
- # remainder โ deleting it is the data loss this PR exists to prevent.
try:
- empty = claim.stat().st_size == 0
- except OSError:
- empty = True
- try:
- claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink()
+ claim.unlink()
except OSError:
pass
- return 0, True
+ return 0
distinct_id, aliased_anonymous_id = resolve_distinct_id()
if aliased_anonymous_id:
@@ -963,17 +360,12 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
sent = 0
for start in range(0, len(events), BATCH_SIZE):
- chunk = events[start : start + BATCH_SIZE]
batch = [
{
"event": event["event"],
"distinct_id": distinct_id,
- # Carried through from record() so a resend can be collapsed.
- "uuid": event.get("uuid"),
"timestamp": event.get("timestamp"),
"properties": {
- # Fallback only: events recorded by a build before source
- # moved into record() have none of their own.
"source": _source_tag,
"language": "python",
"$process_person_profile": False,
@@ -981,24 +373,16 @@ def _drain(claim: Path | None) -> tuple[int, bool]:
**(event.get("properties") or {}),
},
}
- for event in chunk
+ for event in events[start : start + BATCH_SIZE]
]
if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL):
- # Keep only what has not been delivered, and release the lease.
- # Previously the whole file was kept and the retry re-posted every
- # batch, including the ones that had already arrived.
- _release_claim(claim, events[start:])
- return sent, False
- sent += len(chunk)
- # Record progress and refresh the lease after each successful batch, so
- # a crash repeats at most one batch instead of the entire file. If the
- # rewrite fails the claim still holds delivered events, so stop rather
- # than carry on as though progress were recorded โ continuing is how the
- # duplicate delivery this PR fixes would come back.
- if not _rewrite_claim(claim, events[start + len(chunk) :]):
- _release_claim(claim, events[start + len(chunk) :])
- return sent, False
- return sent, True
+ return sent
+ sent += len(batch)
+ try:
+ claim.unlink()
+ except OSError:
+ pass
+ return sent
def main() -> int:
diff --git a/integrations/mem0-agent-plugin/plugin.json b/integrations/mem0-agent-plugin/plugin.json
index 95ff54651..2cbaa99de 100644
--- a/integrations/mem0-agent-plugin/plugin.json
+++ b/integrations/mem0-agent-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
"name": "mem0",
- "version": "0.3.3",
+ "version": "0.3.1",
"description": "Cross-session memory and token savings for coding agents.",
"author": {
"name": "Mem0",
diff --git a/integrations/mem0-agent-plugin/skills/pause/SKILL.md b/integrations/mem0-agent-plugin/skills/pause/SKILL.md
index a87d6c3ee..c6316dd0b 100644
--- a/integrations/mem0-agent-plugin/skills/pause/SKILL.md
+++ b/integrations/mem0-agent-plugin/skills/pause/SKILL.md
@@ -6,8 +6,8 @@ description: Pause Mem0 memory capture on this machine. Use when the user wants
# Pause memory capture
To pause (hooks stop capturing and sending session content; a minimal
-telemetry ping still fires at session start, under your Mem0 account email,
-unless `MEM0_TELEMETRY=false`):
+anonymous telemetry ping still fires at session start unless
+`MEM0_TELEMETRY=false`):
```bash
python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "coding-agent" pause
diff --git a/integrations/mem0-agent-plugin/skills/search/SKILL.md b/integrations/mem0-agent-plugin/skills/search/SKILL.md
index bbd4eb535..d52c4ff34 100644
--- a/integrations/mem0-agent-plugin/skills/search/SKILL.md
+++ b/integrations/mem0-agent-plugin/skills/search/SKILL.md
@@ -10,9 +10,11 @@ Call `search_memories` with the user's question. Treat `--top-k`, `--category`,
query.
Omit `top_k` to use Mem0's configured default. Omit `category` to search every
-category. Omit `scope` to use the configured default, normally `repo`: this
-repository's shared memory, which everyone who works in it contributes to,
-plus your own preferences.
+category; a category is a best-effort label Mem0 assigned when it saved the
+memory, so if a category search misses, repeat it without the category. Omit
+`scope` to use the configured default, normally `repo`: this repository's
+shared memory, which everyone who works in it contributes to, plus your own
+preferences.
Pass `scope` when the question needs something else: `dir` to narrow the
shared memory to the directory you are working in (a package inside a
diff --git a/integrations/mem0-strands/README.md b/integrations/mem0-strands/README.md
index 8ea4ecacc..f45d98e44 100644
--- a/integrations/mem0-strands/README.md
+++ b/integrations/mem0-strands/README.md
@@ -79,11 +79,9 @@ the tool share one Mem0 backend and namespace.
## Telemetry
-The store sends usage events (store configuration, operation, duration, result
-counts, coarse failure kind) over the Mem0 SDK's existing telemetry client,
-tagged `source="STRANDS"`. These are **not anonymous**: when an API key is
-configured they are sent under your Mem0 account email, the same way the SDK
-attributes its own. Queries, memory text, message content, entity ids, and
+The store sends anonymous usage events (store configuration, operation, duration,
+result counts, coarse failure kind) over the Mem0 SDK's existing telemetry client,
+tagged `source="STRANDS"`. Queries, memory text, message content, entity ids, and
metadata are never sent. Turn it off with `MEM0_TELEMETRY=false`.
## Development
diff --git a/integrations/n8n-nodes-mem0/package.json b/integrations/n8n-nodes-mem0/package.json
index 08fd754ae..207dbbc7c 100644
--- a/integrations/n8n-nodes-mem0/package.json
+++ b/integrations/n8n-nodes-mem0/package.json
@@ -74,9 +74,8 @@
"brace-expansion@<1.1.16": ">=1.1.16 <2.0.0",
"brace-expansion@>=2.0.0 <2.1.2": ">=2.1.2 <3.0.0",
"brace-expansion@>=5.0.0 <5.0.8": ">=5.0.8",
- "js-yaml@<3.15.2": ">=3.15.2 <4.0.0",
- "js-yaml@>=4.0.0 <4.3.2": ">=4.3.2 <5.0.0",
- "handlebars@<4.7.10": ">=4.7.10 <5.0.0"
+ "js-yaml@<3.15.1": ">=3.15.1 <4.0.0",
+ "js-yaml@>=4.0.0 <4.3.1": ">=4.3.1 <5.0.0"
}
}
}
diff --git a/integrations/n8n-nodes-mem0/pnpm-lock.yaml b/integrations/n8n-nodes-mem0/pnpm-lock.yaml
index b802536a2..41440b3ca 100644
--- a/integrations/n8n-nodes-mem0/pnpm-lock.yaml
+++ b/integrations/n8n-nodes-mem0/pnpm-lock.yaml
@@ -11,9 +11,8 @@ overrides:
brace-expansion@<1.1.16: '>=1.1.16 <2.0.0'
brace-expansion@>=2.0.0 <2.1.2: '>=2.1.2 <3.0.0'
brace-expansion@>=5.0.0 <5.0.8: '>=5.0.8'
- js-yaml@<3.15.2: '>=3.15.2 <4.0.0'
- js-yaml@>=4.0.0 <4.3.2: '>=4.3.2 <5.0.0'
- handlebars@<4.7.10: '>=4.7.10 <5.0.0'
+ js-yaml@<3.15.1: '>=3.15.1 <4.0.0'
+ js-yaml@>=4.0.0 <4.3.1: '>=4.3.1 <5.0.0'
importers:
@@ -1147,8 +1146,8 @@ packages:
resolution: {integrity: sha512-V2FaKiOhpR3DRXZuYdRLn/qiY0yI5XmqbTKrYbdemJ+xOh2d2MOweI/XFgMzd/9+1twdvMwllnZbWZNJ+BOm4A==}
engines: {node: '>= 10.13.0'}
- handlebars@4.7.10:
- resolution: {integrity: sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==}
+ handlebars@4.7.9:
+ resolution: {integrity: sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==}
engines: {node: '>=0.4.7'}
hasBin: true
@@ -1495,12 +1494,12 @@ packages:
js-tokens@4.0.0:
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
- js-yaml@3.15.2:
- resolution: {integrity: sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==}
+ js-yaml@3.15.1:
+ resolution: {integrity: sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==}
hasBin: true
- js-yaml@4.3.2:
- resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==}
+ js-yaml@4.3.1:
+ resolution: {integrity: sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==}
hasBin: true
jsesc@3.1.0:
@@ -2507,7 +2506,7 @@ snapshots:
globals: 13.24.0
ignore: 5.3.2
import-fresh: 3.3.1
- js-yaml: 4.3.2
+ js-yaml: 4.3.1
minimatch: 3.1.5
strip-json-comments: 3.1.1
transitivePeerDependencies:
@@ -2547,7 +2546,7 @@ snapshots:
camelcase: 5.3.1
find-up: 4.1.0
get-package-type: 0.1.0
- js-yaml: 3.15.2
+ js-yaml: 3.15.1
resolve-from: 5.0.0
'@istanbuljs/schema@0.1.6': {}
@@ -3354,7 +3353,7 @@ snapshots:
imurmurhash: 0.1.4
is-glob: 4.0.3
is-path-inside: 3.0.3
- js-yaml: 4.3.2
+ js-yaml: 4.3.1
json-stable-stringify-without-jsonify: 1.0.1
levn: 0.4.1
lodash.merge: 4.6.2
@@ -3659,7 +3658,7 @@ snapshots:
dependencies:
glogg: 2.2.0
- handlebars@4.7.10:
+ handlebars@4.7.9:
dependencies:
minimist: 1.2.8
neo-async: 2.6.2
@@ -4174,12 +4173,12 @@ snapshots:
js-tokens@4.0.0: {}
- js-yaml@3.15.2:
+ js-yaml@3.15.1:
dependencies:
argparse: 1.0.10
esprima: 4.0.1
- js-yaml@4.3.2:
+ js-yaml@4.3.1:
dependencies:
argparse: 2.0.1
@@ -4759,7 +4758,7 @@ snapshots:
dependencies:
bs-logger: 0.2.6
fast-json-stable-stringify: 2.1.0
- handlebars: 4.7.10
+ handlebars: 4.7.9
jest: 29.7.0(@types/node@20.19.43)
json5: 2.2.3
lodash.memoize: 4.1.2
diff --git a/integrations/openclaw/cli/config-file.ts b/integrations/openclaw/cli/config-file.ts
index a34d6c08b..99453cb1b 100644
--- a/integrations/openclaw/cli/config-file.ts
+++ b/integrations/openclaw/cli/config-file.ts
@@ -35,8 +35,6 @@ export interface PluginAuthConfig {
autoCapture?: boolean;
topK?: number;
anonymousTelemetryId?: string;
- /** SHA-256 prefix of the API key userEmail was resolved for. */
- keyFingerprint?: string;
}
// ============================================================================
@@ -137,9 +135,6 @@ export function readPluginAuth(): PluginAuthConfig {
autoCapture: cfg.autoCapture as boolean | undefined,
topK: cfg.topK as number | undefined,
anonymousTelemetryId: cfg.anonymousTelemetryId as string | undefined,
- // Without this the reader silently drops it, every fingerprint comparison
- // fails against undefined, and the resolved email is never used again.
- keyFingerprint: cfg.keyFingerprint as string | undefined,
};
}
@@ -241,21 +236,6 @@ export function getBaseUrl(): string {
return auth.baseUrl || DEFAULT_BASE_URL;
}
-/** Forget the resolved account, so the next capture re-resolves for the current key. */
-export function clearResolvedAccount(): void {
- const full = readFullConfig() as any;
- const cfg = full?.plugins?.entries?.[PLUGIN_ID]?.config;
- if (!cfg) return;
- let changed = false;
- for (const key of ["userEmail", "keyFingerprint"]) {
- if (key in cfg) {
- delete cfg[key];
- changed = true;
- }
- }
- if (changed) writeFullConfig(full);
-}
-
/** Remove anonymousTelemetryId from config (after PostHog aliasing) */
export function clearAnonymousTelemetryId(): void {
const full = readFullConfig() as any;
diff --git a/integrations/openclaw/config.ts b/integrations/openclaw/config.ts
index 09dcbc837..4e43c8c44 100644
--- a/integrations/openclaw/config.ts
+++ b/integrations/openclaw/config.ts
@@ -148,7 +148,6 @@ const ALLOWED_KEYS = [
"mode",
"apiKey",
"anonymousTelemetryId",
- "keyFingerprint",
"baseUrl",
"userId",
"userEmail",
diff --git a/integrations/openclaw/openclaw.plugin.json b/integrations/openclaw/openclaw.plugin.json
index e3b299112..2d9f46518 100644
--- a/integrations/openclaw/openclaw.plugin.json
+++ b/integrations/openclaw/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "openclaw-mem0",
"name": "Memory (Mem0)",
"description": "Mem0 memory backend for OpenClaw โ platform (mem0.ai cloud) or self-hosted open-source. Auto-recall and auto-capture are opt-in (disabled by default). Supports OpenAI, Anthropic, Ollama (fully local), Qdrant, and PGVector providers.",
- "version": "1.2.1",
+ "version": "1.1.0",
"kind": "memory",
"skills": ["skills"],
"commandAliases": [
@@ -209,10 +209,6 @@
"type": "string",
"description": "Persistent anonymous telemetry identifier"
},
- "keyFingerprint": {
- "type": "string",
- "description": "Digest of the API key userEmail was resolved for. Set automatically; a mismatch re-resolves the account."
- },
"oss": {
"type": "object",
"properties": {
diff --git a/integrations/openclaw/package.json b/integrations/openclaw/package.json
index 33e315314..03938e4da 100644
--- a/integrations/openclaw/package.json
+++ b/integrations/openclaw/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/openclaw-mem0",
- "version": "1.2.1",
+ "version": "1.1.0",
"type": "module",
"description": "Mem0 memory backend for OpenClaw โ platform or self-hosted open-source",
"license": "Apache-2.0",
@@ -59,26 +59,23 @@
"@vitest/coverage-v8": "^4.1.11",
"tsup": "^8.5.0",
"typescript": "^5.8.3",
- "vite": "^8.1.6",
+ "vite": "^8.0.5",
"vitest": "^4.1.11"
},
"pnpm": {
"overrides": {
- "@azure/identity@<4.14.1": ">=4.14.1 <5.0.0",
"form-data@<4.0.6": ">=4.0.6",
"protobufjs@<7.6.5": ">=7.6.5 <8.0.0",
- "vite": "^8.1.6",
+ "vite": "^8.0.5",
"langsmith@<0.6.0": "^0.6.0",
"picomatch@<2.3.2": "^2.3.2",
"@qdrant/js-client-rest": "^1.18.0",
"uuid@<11.1.1": ">=11.1.1",
"esbuild": ">=0.28.1",
- "undici@<7.30.1": ">=7.30.1 <8.0.0",
- "axios@<1.20.0": ">=1.20.0 <2.0.0",
+ "undici@<7.29.0": ">=7.29.0 <8.0.0",
+ "axios@<1.18.0": ">=1.18.0 <2.0.0",
"postcss@<8.5.18": ">=8.5.18 <9.0.0",
- "mongoose@>=9.0.0 <9.7.2": ">=9.7.2 <10.0.0",
- "follow-redirects@<1.16.2": ">=1.16.2 <2.0.0",
- "source-map-js@<1.2.2": ">=1.2.2 <2.0.0"
+ "mongoose@>=9.0.0 <9.7.2": ">=9.7.2 <10.0.0"
}
}
}
diff --git a/integrations/openclaw/pnpm-lock.yaml b/integrations/openclaw/pnpm-lock.yaml
index cce1cf61c..79dd0d10a 100644
--- a/integrations/openclaw/pnpm-lock.yaml
+++ b/integrations/openclaw/pnpm-lock.yaml
@@ -5,21 +5,18 @@ settings:
excludeLinksFromLockfile: false
overrides:
- '@azure/identity@<4.14.1': '>=4.14.1 <5.0.0'
form-data@<4.0.6: '>=4.0.6'
protobufjs@<7.6.5: '>=7.6.5 <8.0.0'
- vite: ^8.1.6
+ vite: ^8.0.5
langsmith@<0.6.0: ^0.6.0
picomatch@<2.3.2: ^2.3.2
'@qdrant/js-client-rest': ^1.18.0
uuid@<11.1.1: '>=11.1.1'
esbuild: '>=0.28.1'
- undici@<7.30.1: '>=7.30.1 <8.0.0'
- axios@<1.20.0: '>=1.20.0 <2.0.0'
+ undici@<7.29.0: '>=7.29.0 <8.0.0'
+ axios@<1.18.0: '>=1.18.0 <2.0.0'
postcss@<8.5.18: '>=8.5.18 <9.0.0'
mongoose@>=9.0.0 <9.7.2: '>=9.7.2 <10.0.0'
- follow-redirects@<1.16.2: '>=1.16.2 <2.0.0'
- source-map-js@<1.2.2: '>=1.2.2 <2.0.0'
importers:
@@ -30,7 +27,7 @@ importers:
version: 0.34.47
mem0ai:
specifier: 3.0.7
- version: 3.0.7(@anthropic-ai/sdk@0.40.1)(@azure/identity@4.14.1)(@azure/search-documents@12.2.0)(@cloudflare/workers-types@4.20260610.1)(@google/genai@1.52.0)(@langchain/core@1.1.48(openai@4.104.0(ws@8.21.0)(zod@3.25.76))(ws@8.21.0))(@mistralai/mistralai@1.15.1)(@qdrant/js-client-rest@1.18.0(typescript@5.9.3))(@supabase/supabase-js@2.108.1)(@types/jest@29.5.14)(@types/pg@8.11.0)(better-sqlite3@12.10.0)(cloudflare@4.5.0)(compromise@14.15.1)(groq-sdk@0.3.0)(natural@8.1.1)(ollama@0.5.18)(pg@8.11.3)(redis@5.12.1)(ws@8.21.0)
+ version: 3.0.7(@anthropic-ai/sdk@0.40.1)(@azure/identity@4.13.1)(@azure/search-documents@12.2.0)(@cloudflare/workers-types@4.20260610.1)(@google/genai@1.52.0)(@langchain/core@1.1.48(openai@4.104.0(ws@8.21.0)(zod@3.25.76))(ws@8.21.0))(@mistralai/mistralai@1.15.1)(@qdrant/js-client-rest@1.18.0(typescript@5.9.3))(@supabase/supabase-js@2.108.1)(@types/jest@29.5.14)(@types/pg@8.11.0)(better-sqlite3@12.10.0)(cloudflare@4.5.0)(compromise@14.15.1)(groq-sdk@0.3.0)(natural@8.1.1)(ollama@0.5.18)(pg@8.11.3)(redis@5.12.1)(ws@8.21.0)
devDependencies:
'@qdrant/js-client-rest':
specifier: ^1.18.0
@@ -43,16 +40,16 @@ importers:
version: 4.1.11(vitest@4.1.11)
tsup:
specifier: ^8.5.0
- version: 8.5.1(postcss@8.5.32)(typescript@5.9.3)
+ version: 8.5.1(postcss@8.5.23)(typescript@5.9.3)
typescript:
specifier: ^5.8.3
version: 5.9.3
vite:
- specifier: ^8.1.6
- version: 8.3.6(@types/node@22.19.20)(esbuild@0.28.1)
+ specifier: ^8.0.5
+ version: 8.0.16(@types/node@22.19.20)(esbuild@0.28.1)
vitest:
specifier: ^4.1.11
- version: 4.1.11(@types/node@22.19.20)(@vitest/coverage-v8@4.1.11)(vite@8.3.6(@types/node@22.19.20)(esbuild@0.28.1))
+ version: 4.1.11(@types/node@22.19.20)(@vitest/coverage-v8@4.1.11)(vite@8.0.16(@types/node@22.19.20)(esbuild@0.28.1))
packages:
@@ -82,10 +79,6 @@ packages:
resolution: {integrity: sha512-YKWi9YuCU04B55h25cnOYZHxXYtEvQEbKST5vqRga7hWY9ydd3FZHdeQF8pyh+acWZvppw13M/LMGx0LABUVMA==}
engines: {node: '>=18.0.0'}
- '@azure/core-process@1.0.0':
- resolution: {integrity: sha512-/shnJ+ooO8WPxDhPEeI/2oRQuubn16gZ6CvlbpWbEswZfzwI9tI/sMAHmF3x1LuQ9yZYXfLW3TjzGMLEC5blKg==}
- engines: {node: '>=22.0.0'}
-
'@azure/core-rest-pipeline@1.24.0':
resolution: {integrity: sha512-PpLsoDQ3AMmKZ0VU+0GrmqMxgp/sExjlVm4R+nLWngeoEGAzOIPVifaxKGU5gMv+nWELUoHfvrolWD+ZS/nFJg==}
engines: {node: '>=20.0.0'}
@@ -98,9 +91,9 @@ packages:
resolution: {integrity: sha512-XPArKLzsvl0Hf0CaGyKHUyVgF7oDnhKoP85Xv6M4StF/1AhfORhZudHtOyf2s+FcbuQ9dPRAjB8J2KvRRMUK2A==}
engines: {node: '>=20.0.0'}
- '@azure/identity@4.14.1':
- resolution: {integrity: sha512-HHuuFrmN1uuF9D5A6aAo5eHzNFNX4Q+P4SksZqDKse5YaJFFy/zDLG3wXHEV2FVGgetZ3QM8jGURNBtnQYf1NQ==}
- engines: {node: '>=22.0.0'}
+ '@azure/identity@4.13.1':
+ resolution: {integrity: sha512-5C/2WD5Vb1lHnZS16dNQRPMjN6oV/Upba+C9nBIs15PmOi6A3ZGs4Lr2u60zw4S04gi+u3cEXiqTVP7M4Pz3kw==}
+ engines: {node: '>=20.0.0'}
'@azure/logger@1.3.0':
resolution: {integrity: sha512-fCqPIfOcLE+CGqGPd66c8bZpwAji98tZ4JI9i/mlTNTlsIWslCfpg48s/ypyLxZTump5sypjrKn2/kY7q8oAbA==}
@@ -110,16 +103,12 @@ packages:
resolution: {integrity: sha512-eNf2aqx1C6I0yT1GEu5ukblFrmaBXGfe1bivpmlfqvK7giPZvoXLa404C8EfeHVsy6EIryfQuPRzuW1fPxWlHg==}
engines: {node: '>=0.8.0'}
- '@azure/msal-common@16.16.0':
- resolution: {integrity: sha512-EZgd8h5nczsdRAQAgXA0A0pC5L/zj43n1jePXvUMgdwXMbH2zhb7b7Hp+Oe7ZOODK/sch2x+soD6FOrtgUbx/w==}
- engines: {node: '>=0.8.0'}
-
'@azure/msal-common@16.7.0':
resolution: {integrity: sha512-Jb8Y7pX6KM42SIT7KWP6YbY3+vLbwB5b5m+tpiiOzMU1QeyelQzs9lO8jv1e7/Uj9r7tg7VjPvW4T0KB1jF3UQ==}
engines: {node: '>=0.8.0'}
- '@azure/msal-node@7.2.0':
- resolution: {integrity: sha512-Y87VJsMWF4jiqLqq8XYLb1o+rGc/HacwS3Zydi3bDtaVm5Sa8FlB7YrKrBFKRIYj27RJXAaDkErImMAqtM10Pg==}
+ '@azure/msal-node@5.2.3':
+ resolution: {integrity: sha512-YYX4TchEVddVBiybKvKhV9QO/q22jgewP+BVxKG7Uh115voPcviGlypbKERDsqQdAiSTJrwi80gcWFjYKdo8+Q==}
engines: {node: '>=20'}
'@azure/search-documents@12.2.0':
@@ -157,6 +146,15 @@ packages:
'@cloudflare/workers-types@4.20260610.1':
resolution: {integrity: sha512-Mk/f3lUygeIHzQ4HnJjU/JvGg/kllgp9gISty9nylHE/2M2MFeKO+hgAKSgiPpmwUbuhewdYGgqFGgT/ADK0/g==}
+ '@emnapi/core@1.10.0':
+ resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==}
+
+ '@emnapi/runtime@1.10.0':
+ resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==}
+
+ '@emnapi/wasi-threads@1.2.1':
+ resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==}
+
'@esbuild/aix-ppc64@0.28.1':
resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==}
engines: {node: '>=18'}
@@ -357,8 +355,14 @@ packages:
'@mongodb-js/saslprep@1.4.11':
resolution: {integrity: sha512-o9rAHc0IpIjuPSxRutWpE1F62x7n+4mVS4rCNHkzhIUMQcc18bb6xEq5wd2NdN0WjepIyXIppRshYI2kQDOZVA==}
- '@oxc-project/types@0.156.0':
- resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==}
+ '@napi-rs/wasm-runtime@1.1.5':
+ resolution: {integrity: sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==}
+ peerDependencies:
+ '@emnapi/core': ^1.7.1
+ '@emnapi/runtime': ^1.7.1
+
+ '@oxc-project/types@0.133.0':
+ resolution: {integrity: sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==}
'@protobufjs/aspromise@1.1.2':
resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==}
@@ -433,98 +437,97 @@ packages:
peerDependencies:
'@redis/client': ^5.12.1
- '@rolldown/binding-android-arm-eabi@1.2.16':
- resolution: {integrity: sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm]
- os: [android]
-
- '@rolldown/binding-android-arm64@1.2.16':
- resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==}
+ '@rolldown/binding-android-arm64@1.0.3':
+ resolution: {integrity: sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [android]
- '@rolldown/binding-darwin-arm64@1.2.16':
- resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==}
+ '@rolldown/binding-darwin-arm64@1.0.3':
+ resolution: {integrity: sha512-PcAhP+ynjURNyy8SKGl5DQP94aGuB/7JrXJb/t7P+hanXvQVMWzUvRRhBAcg/lNRadBhoUPqSoP4xw5tR/KBEA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [darwin]
- '@rolldown/binding-darwin-x64@1.2.16':
- resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==}
+ '@rolldown/binding-darwin-x64@1.0.3':
+ resolution: {integrity: sha512-9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [darwin]
- '@rolldown/binding-freebsd-x64@1.2.16':
- resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==}
+ '@rolldown/binding-freebsd-x64@1.0.3':
+ resolution: {integrity: sha512-yB1IlAsSNHncV6SCTL27/MVGR5htvQsoGxIv5KMGXALp+Ll1wYsn+x98M9MW7qa+NdSbvrrY7ANI4wLJ0n1e6g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [freebsd]
- '@rolldown/binding-linux-arm-gnueabihf@1.2.16':
- resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==}
+ '@rolldown/binding-linux-arm-gnueabihf@1.0.3':
+ resolution: {integrity: sha512-Yi30IVAAfLUCy2MseFjbB1jAMDl1VMCAas5StnYp8da9+CKvMd2H2cbEjWcw5NPaPqzvYkVIaF1nNUG+b7u/sw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
- '@rolldown/binding-linux-arm64-gnu@1.2.16':
- resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==}
+ '@rolldown/binding-linux-arm64-gnu@1.0.3':
+ resolution: {integrity: sha512-jsO7R8To+AdlYgUmN5sHSCZbfhtMBkO0WUx8iORQnPcMMdgr7qM2DQmMwgabs3GhNztdmoKkMKQFHD6DTMCIQw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
- '@rolldown/binding-linux-arm64-musl@1.2.16':
- resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==}
+ '@rolldown/binding-linux-arm64-musl@1.0.3':
+ resolution: {integrity: sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
- '@rolldown/binding-linux-ppc64-gnu@1.2.16':
- resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==}
+ '@rolldown/binding-linux-ppc64-gnu@1.0.3':
+ resolution: {integrity: sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
- '@rolldown/binding-linux-s390x-gnu@1.2.16':
- resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==}
+ '@rolldown/binding-linux-s390x-gnu@1.0.3':
+ resolution: {integrity: sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
- '@rolldown/binding-linux-x64-gnu@1.2.16':
- resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==}
+ '@rolldown/binding-linux-x64-gnu@1.0.3':
+ resolution: {integrity: sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
- '@rolldown/binding-linux-x64-musl@1.2.16':
- resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==}
+ '@rolldown/binding-linux-x64-musl@1.0.3':
+ resolution: {integrity: sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
- '@rolldown/binding-openharmony-arm64@1.2.16':
- resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==}
+ '@rolldown/binding-openharmony-arm64@1.0.3':
+ resolution: {integrity: sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [openharmony]
- '@rolldown/binding-win32-arm64-msvc@1.2.16':
- resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==}
+ '@rolldown/binding-wasm32-wasi@1.0.3':
+ resolution: {integrity: sha512-JTtb8BWFynicNSoPrehsCzBtOKjZ6jhMiPFEmOiuXg1Fl8dn2KHQob+GuPSGR0dryQa1PQJbzjF3dqO/whhjLg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [wasm32]
+
+ '@rolldown/binding-win32-arm64-msvc@1.0.3':
+ resolution: {integrity: sha512-gEdFFEN70A/jxb2svrWsN3aDL7OUtmvlOy+6fa2jxG8K0wQ1ZbdeLGnidov6Yu5/733dI5ySfzFlQ/cb0bSz1g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [win32]
- '@rolldown/binding-win32-x64-msvc@1.2.16':
- resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==}
+ '@rolldown/binding-win32-x64-msvc@1.0.3':
+ resolution: {integrity: sha512-eXB7CHuaQdqmJcc3koCNtNPmT/bj2gc999kUFgBxG8Ac0NdgXc4rkCHhqrgrhN3zddvvvrgzj1e90SuSfmyIXA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [win32]
@@ -706,6 +709,9 @@ packages:
resolution: {integrity: sha512-V/1hRKLSCJ0zEL+9QFRBUtivvePfOsaAYQmC0HhFNSHC2F3xFs4jSF3YhkLmzex6E4V4FGvmBDOP72D/53NnZA==}
engines: {node: '>=20.0.0'}
+ '@tybys/wasm-util@0.10.2':
+ resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==}
+
'@types/chai@5.2.3':
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
@@ -777,7 +783,7 @@ packages:
resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==}
peerDependencies:
msw: ^2.4.9
- vite: ^8.1.6
+ vite: ^8.0.5
peerDependenciesMeta:
msw:
optional: true
@@ -851,8 +857,8 @@ packages:
asynckit@0.4.0:
resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}
- axios@1.20.0:
- resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==}
+ axios@1.18.1:
+ resolution: {integrity: sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==}
base-64@0.1.0:
resolution: {integrity: sha512-Y5gU45svrR5tI2Vt/X9GPd3L0HNIKzGu202EjxrXMpuc2V2CiKgemAbUUsqYmZJvPtCXoUKjNZwBJzsNScUbXA==}
@@ -995,8 +1001,8 @@ packages:
resolution: {integrity: sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==}
engines: {node: '>=18'}
- default-browser@5.5.1:
- resolution: {integrity: sha512-m1pAzaJgZ/gssEqlOhJkPJp8Xly7QyW6xcrkUa2KKcDeDSEMP7X8xipU3snUcfisTQx0w1AGae+9UtJSfVnXGw==}
+ default-browser@5.5.0:
+ resolution: {integrity: sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw==}
engines: {node: '>=18'}
define-lazy-prop@3.0.0:
@@ -1116,8 +1122,8 @@ packages:
fix-dts-default-cjs-exports@1.0.1:
resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==}
- follow-redirects@1.16.2:
- resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==}
+ follow-redirects@1.16.0:
+ resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==}
engines: {node: '>=4.0'}
peerDependencies:
debug: '*'
@@ -1247,10 +1253,6 @@ packages:
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
hasBin: true
- is-in-ssh@1.0.0:
- resolution: {integrity: sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw==}
- engines: {node: '>=20'}
-
is-inside-container@1.0.0:
resolution: {integrity: sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==}
engines: {node: '>=14.16'}
@@ -1346,78 +1348,78 @@ packages:
ws:
optional: true
- lightningcss-android-arm64@1.33.0:
- resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==}
+ lightningcss-android-arm64@1.32.0:
+ resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [android]
- lightningcss-darwin-arm64@1.33.0:
- resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==}
+ lightningcss-darwin-arm64@1.32.0:
+ resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [darwin]
- lightningcss-darwin-x64@1.33.0:
- resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==}
+ lightningcss-darwin-x64@1.32.0:
+ resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [darwin]
- lightningcss-freebsd-x64@1.33.0:
- resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==}
+ lightningcss-freebsd-x64@1.32.0:
+ resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [freebsd]
- lightningcss-linux-arm-gnueabihf@1.33.0:
- resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==}
+ lightningcss-linux-arm-gnueabihf@1.32.0:
+ resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==}
engines: {node: '>= 12.0.0'}
cpu: [arm]
os: [linux]
- lightningcss-linux-arm64-gnu@1.33.0:
- resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==}
+ lightningcss-linux-arm64-gnu@1.32.0:
+ resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
- lightningcss-linux-arm64-musl@1.33.0:
- resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==}
+ lightningcss-linux-arm64-musl@1.32.0:
+ resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [musl]
- lightningcss-linux-x64-gnu@1.33.0:
- resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==}
+ lightningcss-linux-x64-gnu@1.32.0:
+ resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
- lightningcss-linux-x64-musl@1.33.0:
- resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==}
+ lightningcss-linux-x64-musl@1.32.0:
+ resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [musl]
- lightningcss-win32-arm64-msvc@1.33.0:
- resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==}
+ lightningcss-win32-arm64-msvc@1.32.0:
+ resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [win32]
- lightningcss-win32-x64-msvc@1.33.0:
- resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==}
+ lightningcss-win32-x64-msvc@1.32.0:
+ resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [win32]
- lightningcss@1.33.0:
- resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==}
+ lightningcss@1.32.0:
+ resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==}
engines: {node: '>= 12.0.0'}
lilconfig@3.1.3:
@@ -1477,7 +1479,7 @@ packages:
engines: {node: '>=18'}
peerDependencies:
'@anthropic-ai/sdk': ^0.40.1
- '@azure/identity': '>=4.14.1 <5.0.0'
+ '@azure/identity': ^4.0.0
'@azure/search-documents': ^12.0.0
'@cloudflare/workers-types': ^4.20250504.0
'@google/genai': ^1.40.0
@@ -1581,8 +1583,8 @@ packages:
mz@2.7.0:
resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==}
- nanoid@3.3.20:
- resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}
+ nanoid@3.3.16:
+ resolution: {integrity: sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
@@ -1632,9 +1634,9 @@ packages:
once@1.4.0:
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
- open@11.0.4:
- resolution: {integrity: sha512-++Zlftm0kVLPmzC06t6epuWmcRMDbI4z5P3NNX979WA/k23+NtSOynEGzsVfZwguKw2mi5umVgnBlJQMwRz4Pg==}
- engines: {node: '>=20'}
+ open@10.2.0:
+ resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==}
+ engines: {node: '>=18'}
openai@4.104.0:
resolution: {integrity: sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==}
@@ -1732,10 +1734,6 @@ packages:
resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==}
engines: {node: '>=12'}
- picomatch@4.0.7:
- resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
- engines: {node: '>=12'}
-
pirates@4.0.7:
resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==}
engines: {node: '>= 6'}
@@ -1761,8 +1759,8 @@ packages:
yaml:
optional: true
- postcss@8.5.32:
- resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==}
+ postcss@8.5.23:
+ resolution: {integrity: sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==}
engines: {node: ^10 || ^12 || >=14}
postgres-array@2.0.0:
@@ -1800,10 +1798,6 @@ packages:
postgres-range@1.1.4:
resolution: {integrity: sha512-i/hbxIE9803Alj/6ytL7UHQxRvZkI9O4Sy+J3HGc4F4oo/2eQAjTSNJ0bfxyse3bH0nuVesCk+3IRLaMtG3H6w==}
- powershell-utils@0.2.1:
- resolution: {integrity: sha512-C+y9x90UElAddDZmV4qOx9W53B61PO7cIqWz2dQsWlwswuq4mr8NEwytdGKboYbQlGZ3awrkTeNvcZiZNHnQ8A==}
- engines: {node: '>=20'}
-
prebuild-install@7.1.3:
resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==}
engines: {node: '>=10'}
@@ -1856,8 +1850,8 @@ packages:
resolution: {integrity: sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==}
engines: {node: '>= 4'}
- rolldown@1.2.16:
- resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==}
+ rolldown@1.0.3:
+ resolution: {integrity: sha512-i00lAJ2ks1BYr7rjNjKC7BcqAS7nVfiT3QX1SI5aY+AFHblCmaUf9OE9dbdzDvW6dJxbi2ZCZiy9v3CcwOiX3g==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
@@ -1898,8 +1892,8 @@ packages:
resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==}
engines: {node: '>=8'}
- source-map-js@1.2.2:
- resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
+ source-map-js@1.2.1:
+ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'}
source-map@0.7.6:
@@ -2042,8 +2036,8 @@ packages:
undici-types@6.21.0:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
- undici@7.30.2:
- resolution: {integrity: sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==}
+ undici@7.29.0:
+ resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==}
engines: {node: '>=20.18.1'}
util-deprecate@1.0.2:
@@ -2057,13 +2051,13 @@ packages:
resolution: {integrity: sha512-Qo+uWgilfSmAhXCMav1uYFynlQO7fMFiMVZsQqZRMIXp0O7rR7qjkj+cPvBHLgBqi960QCoo/PH2/6ZtVqKvrg==}
hasBin: true
- vite@8.3.6:
- resolution: {integrity: sha512-UI7dK29NnS54Fk+mmo7o+jI6U8Fp7hDl+X5Q1k45WH+d4dSlbLVUETGQ+hfkNgvLQGyoElPj837nZyv4MBc0VA==}
+ vite@8.0.16:
+ resolution: {integrity: sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
peerDependencies:
'@types/node': ^20.19.0 || >=22.12.0
- '@vitejs/devtools': ^0.7.1 || ^0.8.0
+ '@vitejs/devtools': ^0.1.18
esbuild: '>=0.28.1'
jiti: '>=1.21.0'
less: ^4.0.0
@@ -2116,7 +2110,7 @@ packages:
'@vitest/ui': 4.1.11
happy-dom: '*'
jsdom: '*'
- vite: ^8.1.6
+ vite: ^8.0.5
peerDependenciesMeta:
'@edge-runtime/vm':
optional: true
@@ -2190,9 +2184,9 @@ packages:
utf-8-validate:
optional: true
- wsl-utils@1.0.1:
- resolution: {integrity: sha512-c16PKLIRxBYpR3jSWsdS7SFp0COm5SOQdiFjY818dYFHJbMGuLBszpF07LBWmOS1uzrHa9VGdynsEgoeKy0oOQ==}
- engines: {node: '>=20'}
+ wsl-utils@0.1.0:
+ resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==}
+ engines: {node: '>=18'}
xtend@4.0.2:
resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==}
@@ -2257,8 +2251,6 @@ snapshots:
dependencies:
tslib: 2.8.1
- '@azure/core-process@1.0.0': {}
-
'@azure/core-rest-pipeline@1.24.0':
dependencies:
'@azure/abort-controller': 2.1.2
@@ -2283,19 +2275,18 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@azure/identity@4.14.1':
+ '@azure/identity@4.13.1':
dependencies:
'@azure/abort-controller': 2.1.2
'@azure/core-auth': 1.10.1
'@azure/core-client': 1.10.2
- '@azure/core-process': 1.0.0
'@azure/core-rest-pipeline': 1.24.0
'@azure/core-tracing': 1.3.1
'@azure/core-util': 1.13.1
'@azure/logger': 1.3.0
'@azure/msal-browser': 5.12.0
- '@azure/msal-node': 7.2.0
- open: 11.0.4
+ '@azure/msal-node': 5.2.3
+ open: 10.2.0
tslib: 2.8.1
transitivePeerDependencies:
- supports-color
@@ -2311,13 +2302,11 @@ snapshots:
dependencies:
'@azure/msal-common': 16.7.0
- '@azure/msal-common@16.16.0': {}
-
'@azure/msal-common@16.7.0': {}
- '@azure/msal-node@7.2.0':
+ '@azure/msal-node@5.2.3':
dependencies:
- '@azure/msal-common': 16.16.0
+ '@azure/msal-common': 16.7.0
jsonwebtoken: 9.0.3
'@azure/search-documents@12.2.0':
@@ -2360,6 +2349,22 @@ snapshots:
'@cloudflare/workers-types@4.20260610.1': {}
+ '@emnapi/core@1.10.0':
+ dependencies:
+ '@emnapi/wasi-threads': 1.2.1
+ tslib: 2.8.1
+ optional: true
+
+ '@emnapi/runtime@1.10.0':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
+ '@emnapi/wasi-threads@1.2.1':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
'@esbuild/aix-ppc64@0.28.1':
optional: true
@@ -2509,7 +2514,14 @@ snapshots:
dependencies:
sparse-bitfield: 3.0.3
- '@oxc-project/types@0.156.0': {}
+ '@napi-rs/wasm-runtime@1.1.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)':
+ dependencies:
+ '@emnapi/core': 1.10.0
+ '@emnapi/runtime': 1.10.0
+ '@tybys/wasm-util': 0.10.2
+ optional: true
+
+ '@oxc-project/types@0.133.0': {}
'@protobufjs/aspromise@1.1.2': {}
@@ -2535,7 +2547,7 @@ snapshots:
dependencies:
'@qdrant/openapi-typescript-fetch': 1.2.6
typescript: 5.9.3
- undici: 7.30.2
+ undici: 7.29.0
'@qdrant/openapi-typescript-fetch@1.2.6': {}
@@ -2559,49 +2571,53 @@ snapshots:
dependencies:
'@redis/client': 5.12.1
- '@rolldown/binding-android-arm-eabi@1.2.16':
+ '@rolldown/binding-android-arm64@1.0.3':
optional: true
- '@rolldown/binding-android-arm64@1.2.16':
+ '@rolldown/binding-darwin-arm64@1.0.3':
optional: true
- '@rolldown/binding-darwin-arm64@1.2.16':
+ '@rolldown/binding-darwin-x64@1.0.3':
optional: true
- '@rolldown/binding-darwin-x64@1.2.16':
+ '@rolldown/binding-freebsd-x64@1.0.3':
optional: true
- '@rolldown/binding-freebsd-x64@1.2.16':
+ '@rolldown/binding-linux-arm-gnueabihf@1.0.3':
optional: true
- '@rolldown/binding-linux-arm-gnueabihf@1.2.16':
+ '@rolldown/binding-linux-arm64-gnu@1.0.3':
optional: true
- '@rolldown/binding-linux-arm64-gnu@1.2.16':
+ '@rolldown/binding-linux-arm64-musl@1.0.3':
optional: true
- '@rolldown/binding-linux-arm64-musl@1.2.16':
+ '@rolldown/binding-linux-ppc64-gnu@1.0.3':
optional: true
- '@rolldown/binding-linux-ppc64-gnu@1.2.16':
+ '@rolldown/binding-linux-s390x-gnu@1.0.3':
optional: true
- '@rolldown/binding-linux-s390x-gnu@1.2.16':
+ '@rolldown/binding-linux-x64-gnu@1.0.3':
optional: true
- '@rolldown/binding-linux-x64-gnu@1.2.16':
+ '@rolldown/binding-linux-x64-musl@1.0.3':
optional: true
- '@rolldown/binding-linux-x64-musl@1.2.16':
+ '@rolldown/binding-openharmony-arm64@1.0.3':
optional: true
- '@rolldown/binding-openharmony-arm64@1.2.16':
+ '@rolldown/binding-wasm32-wasi@1.0.3':
+ dependencies:
+ '@emnapi/core': 1.10.0
+ '@emnapi/runtime': 1.10.0
+ '@napi-rs/wasm-runtime': 1.1.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)
optional: true
- '@rolldown/binding-win32-arm64-msvc@1.2.16':
+ '@rolldown/binding-win32-arm64-msvc@1.0.3':
optional: true
- '@rolldown/binding-win32-x64-msvc@1.2.16':
+ '@rolldown/binding-win32-x64-msvc@1.0.3':
optional: true
'@rolldown/pluginutils@1.0.1': {}
@@ -2719,6 +2735,11 @@ snapshots:
'@supabase/realtime-js': 2.108.1
'@supabase/storage-js': 2.108.1
+ '@tybys/wasm-util@0.10.2':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
'@types/chai@5.2.3':
dependencies:
'@types/deep-eql': 4.0.2
@@ -2798,7 +2819,7 @@ snapshots:
obug: 2.1.2
std-env: 4.1.0
tinyrainbow: 3.1.0
- vitest: 4.1.11(@types/node@22.19.20)(@vitest/coverage-v8@4.1.11)(vite@8.3.6(@types/node@22.19.20)(esbuild@0.28.1))
+ vitest: 4.1.11(@types/node@22.19.20)(@vitest/coverage-v8@4.1.11)(vite@8.0.16(@types/node@22.19.20)(esbuild@0.28.1))
'@vitest/expect@4.1.11':
dependencies:
@@ -2809,13 +2830,13 @@ snapshots:
chai: 6.2.2
tinyrainbow: 3.1.0
- '@vitest/mocker@4.1.11(vite@8.3.6(@types/node@22.19.20)(esbuild@0.28.1))':
+ '@vitest/mocker@4.1.11(vite@8.0.16(@types/node@22.19.20)(esbuild@0.28.1))':
dependencies:
'@vitest/spy': 4.1.11
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
- vite: 8.3.6(@types/node@22.19.20)(esbuild@0.28.1)
+ vite: 8.0.16(@types/node@22.19.20)(esbuild@0.28.1)
'@vitest/pretty-format@4.1.11':
dependencies:
@@ -2885,9 +2906,9 @@ snapshots:
asynckit@0.4.0: {}
- axios@1.20.0:
+ axios@1.18.1:
dependencies:
- follow-redirects: 1.16.2
+ follow-redirects: 1.16.0
form-data: 4.0.6
https-proxy-agent: 5.0.1
proxy-from-env: 2.1.0
@@ -3018,7 +3039,7 @@ snapshots:
default-browser-id@5.0.1: {}
- default-browser@5.5.1:
+ default-browser@5.5.0:
dependencies:
bundle-name: 4.1.0
default-browser-id: 5.0.1
@@ -3147,7 +3168,7 @@ snapshots:
mlly: 1.8.2
rollup: 4.61.1
- follow-redirects@1.16.2: {}
+ follow-redirects@1.16.0: {}
form-data-encoder@1.7.2: {}
@@ -3295,8 +3316,6 @@ snapshots:
is-docker@3.0.0: {}
- is-in-ssh@1.0.0: {}
-
is-inside-container@1.0.0:
dependencies:
is-docker: 3.0.0
@@ -3404,54 +3423,54 @@ snapshots:
openai: 4.104.0(ws@8.21.0)(zod@3.25.76)
ws: 8.21.0
- lightningcss-android-arm64@1.33.0:
+ lightningcss-android-arm64@1.32.0:
optional: true
- lightningcss-darwin-arm64@1.33.0:
+ lightningcss-darwin-arm64@1.32.0:
optional: true
- lightningcss-darwin-x64@1.33.0:
+ lightningcss-darwin-x64@1.32.0:
optional: true
- lightningcss-freebsd-x64@1.33.0:
+ lightningcss-freebsd-x64@1.32.0:
optional: true
- lightningcss-linux-arm-gnueabihf@1.33.0:
+ lightningcss-linux-arm-gnueabihf@1.32.0:
optional: true
- lightningcss-linux-arm64-gnu@1.33.0:
+ lightningcss-linux-arm64-gnu@1.32.0:
optional: true
- lightningcss-linux-arm64-musl@1.33.0:
+ lightningcss-linux-arm64-musl@1.32.0:
optional: true
- lightningcss-linux-x64-gnu@1.33.0:
+ lightningcss-linux-x64-gnu@1.32.0:
optional: true
- lightningcss-linux-x64-musl@1.33.0:
+ lightningcss-linux-x64-musl@1.32.0:
optional: true
- lightningcss-win32-arm64-msvc@1.33.0:
+ lightningcss-win32-arm64-msvc@1.32.0:
optional: true
- lightningcss-win32-x64-msvc@1.33.0:
+ lightningcss-win32-x64-msvc@1.32.0:
optional: true
- lightningcss@1.33.0:
+ lightningcss@1.32.0:
dependencies:
detect-libc: 2.1.2
optionalDependencies:
- lightningcss-android-arm64: 1.33.0
- lightningcss-darwin-arm64: 1.33.0
- lightningcss-darwin-x64: 1.33.0
- lightningcss-freebsd-x64: 1.33.0
- lightningcss-linux-arm-gnueabihf: 1.33.0
- lightningcss-linux-arm64-gnu: 1.33.0
- lightningcss-linux-arm64-musl: 1.33.0
- lightningcss-linux-x64-gnu: 1.33.0
- lightningcss-linux-x64-musl: 1.33.0
- lightningcss-win32-arm64-msvc: 1.33.0
- lightningcss-win32-x64-msvc: 1.33.0
+ lightningcss-android-arm64: 1.32.0
+ lightningcss-darwin-arm64: 1.32.0
+ lightningcss-darwin-x64: 1.32.0
+ lightningcss-freebsd-x64: 1.32.0
+ lightningcss-linux-arm-gnueabihf: 1.32.0
+ lightningcss-linux-arm64-gnu: 1.32.0
+ lightningcss-linux-arm64-musl: 1.32.0
+ lightningcss-linux-x64-gnu: 1.32.0
+ lightningcss-linux-x64-musl: 1.32.0
+ lightningcss-win32-arm64-msvc: 1.32.0
+ lightningcss-win32-x64-msvc: 1.32.0
lilconfig@3.1.3: {}
@@ -3483,7 +3502,7 @@ snapshots:
dependencies:
'@babel/parser': 7.29.7
'@babel/types': 7.29.7
- source-map-js: 1.2.2
+ source-map-js: 1.2.1
make-dir@4.0.0:
dependencies:
@@ -3497,10 +3516,10 @@ snapshots:
crypt: 0.0.2
is-buffer: 1.1.6
- mem0ai@3.0.7(@anthropic-ai/sdk@0.40.1)(@azure/identity@4.14.1)(@azure/search-documents@12.2.0)(@cloudflare/workers-types@4.20260610.1)(@google/genai@1.52.0)(@langchain/core@1.1.48(openai@4.104.0(ws@8.21.0)(zod@3.25.76))(ws@8.21.0))(@mistralai/mistralai@1.15.1)(@qdrant/js-client-rest@1.18.0(typescript@5.9.3))(@supabase/supabase-js@2.108.1)(@types/jest@29.5.14)(@types/pg@8.11.0)(better-sqlite3@12.10.0)(cloudflare@4.5.0)(compromise@14.15.1)(groq-sdk@0.3.0)(natural@8.1.1)(ollama@0.5.18)(pg@8.11.3)(redis@5.12.1)(ws@8.21.0):
+ mem0ai@3.0.7(@anthropic-ai/sdk@0.40.1)(@azure/identity@4.13.1)(@azure/search-documents@12.2.0)(@cloudflare/workers-types@4.20260610.1)(@google/genai@1.52.0)(@langchain/core@1.1.48(openai@4.104.0(ws@8.21.0)(zod@3.25.76))(ws@8.21.0))(@mistralai/mistralai@1.15.1)(@qdrant/js-client-rest@1.18.0(typescript@5.9.3))(@supabase/supabase-js@2.108.1)(@types/jest@29.5.14)(@types/pg@8.11.0)(better-sqlite3@12.10.0)(cloudflare@4.5.0)(compromise@14.15.1)(groq-sdk@0.3.0)(natural@8.1.1)(ollama@0.5.18)(pg@8.11.3)(redis@5.12.1)(ws@8.21.0):
dependencies:
'@anthropic-ai/sdk': 0.40.1
- '@azure/identity': 4.14.1
+ '@azure/identity': 4.13.1
'@azure/search-documents': 12.2.0
'@cloudflare/workers-types': 4.20260610.1
'@google/genai': 1.52.0
@@ -3510,7 +3529,7 @@ snapshots:
'@supabase/supabase-js': 2.108.1
'@types/jest': 29.5.14
'@types/pg': 8.11.0
- axios: 1.20.0
+ axios: 1.18.1
better-sqlite3: 12.10.0
cloudflare: 4.5.0
compromise: 14.15.1
@@ -3599,7 +3618,7 @@ snapshots:
object-assign: 4.1.1
thenify-all: 1.6.0
- nanoid@3.3.20: {}
+ nanoid@3.3.16: {}
napi-build-utils@2.0.0: {}
@@ -3661,14 +3680,12 @@ snapshots:
dependencies:
wrappy: 1.0.2
- open@11.0.4:
+ open@10.2.0:
dependencies:
- default-browser: 5.5.1
+ default-browser: 5.5.0
define-lazy-prop: 3.0.0
- is-in-ssh: 1.0.0
is-inside-container: 1.0.0
- powershell-utils: 0.2.1
- wsl-utils: 1.0.1
+ wsl-utils: 0.1.0
openai@4.104.0(ws@8.21.0)(zod@3.25.76):
dependencies:
@@ -3774,8 +3791,6 @@ snapshots:
picomatch@4.0.4: {}
- picomatch@4.0.7: {}
-
pirates@4.0.7: {}
pkg-types@1.3.1:
@@ -3784,17 +3799,17 @@ snapshots:
mlly: 1.8.2
pathe: 2.0.3
- postcss-load-config@6.0.1(postcss@8.5.32):
+ postcss-load-config@6.0.1(postcss@8.5.23):
dependencies:
lilconfig: 3.1.3
optionalDependencies:
- postcss: 8.5.32
+ postcss: 8.5.23
- postcss@8.5.32:
+ postcss@8.5.23:
dependencies:
- nanoid: 3.3.20
+ nanoid: 3.3.16
picocolors: 1.1.1
- source-map-js: 1.2.2
+ source-map-js: 1.2.1
postgres-array@2.0.0: {}
@@ -3818,8 +3833,6 @@ snapshots:
postgres-range@1.1.4: {}
- powershell-utils@0.2.1: {}
-
prebuild-install@7.1.3:
dependencies:
detect-libc: 2.1.2
@@ -3896,26 +3909,26 @@ snapshots:
retry@0.13.1: {}
- rolldown@1.2.16:
+ rolldown@1.0.3:
dependencies:
- '@oxc-project/types': 0.156.0
+ '@oxc-project/types': 0.133.0
'@rolldown/pluginutils': 1.0.1
optionalDependencies:
- '@rolldown/binding-android-arm-eabi': 1.2.16
- '@rolldown/binding-android-arm64': 1.2.16
- '@rolldown/binding-darwin-arm64': 1.2.16
- '@rolldown/binding-darwin-x64': 1.2.16
- '@rolldown/binding-freebsd-x64': 1.2.16
- '@rolldown/binding-linux-arm-gnueabihf': 1.2.16
- '@rolldown/binding-linux-arm64-gnu': 1.2.16
- '@rolldown/binding-linux-arm64-musl': 1.2.16
- '@rolldown/binding-linux-ppc64-gnu': 1.2.16
- '@rolldown/binding-linux-s390x-gnu': 1.2.16
- '@rolldown/binding-linux-x64-gnu': 1.2.16
- '@rolldown/binding-linux-x64-musl': 1.2.16
- '@rolldown/binding-openharmony-arm64': 1.2.16
- '@rolldown/binding-win32-arm64-msvc': 1.2.16
- '@rolldown/binding-win32-x64-msvc': 1.2.16
+ '@rolldown/binding-android-arm64': 1.0.3
+ '@rolldown/binding-darwin-arm64': 1.0.3
+ '@rolldown/binding-darwin-x64': 1.0.3
+ '@rolldown/binding-freebsd-x64': 1.0.3
+ '@rolldown/binding-linux-arm-gnueabihf': 1.0.3
+ '@rolldown/binding-linux-arm64-gnu': 1.0.3
+ '@rolldown/binding-linux-arm64-musl': 1.0.3
+ '@rolldown/binding-linux-ppc64-gnu': 1.0.3
+ '@rolldown/binding-linux-s390x-gnu': 1.0.3
+ '@rolldown/binding-linux-x64-gnu': 1.0.3
+ '@rolldown/binding-linux-x64-musl': 1.0.3
+ '@rolldown/binding-openharmony-arm64': 1.0.3
+ '@rolldown/binding-wasm32-wasi': 1.0.3
+ '@rolldown/binding-win32-arm64-msvc': 1.0.3
+ '@rolldown/binding-win32-x64-msvc': 1.0.3
rollup@4.61.1:
dependencies:
@@ -3970,7 +3983,7 @@ snapshots:
slash@3.0.0: {}
- source-map-js@1.2.2: {}
+ source-map-js@1.2.1: {}
source-map@0.7.6: {}
@@ -4066,7 +4079,7 @@ snapshots:
tslib@2.8.1: {}
- tsup@8.5.1(postcss@8.5.32)(typescript@5.9.3):
+ tsup@8.5.1(postcss@8.5.23)(typescript@5.9.3):
dependencies:
bundle-require: 5.1.0(esbuild@0.28.1)
cac: 6.7.14
@@ -4077,7 +4090,7 @@ snapshots:
fix-dts-default-cjs-exports: 1.0.1
joycon: 3.1.1
picocolors: 1.1.1
- postcss-load-config: 6.0.1(postcss@8.5.32)
+ postcss-load-config: 6.0.1(postcss@8.5.23)
resolve-from: 5.0.0
rollup: 4.61.1
source-map: 0.7.6
@@ -4086,7 +4099,7 @@ snapshots:
tinyglobby: 0.2.17
tree-kill: 1.2.2
optionalDependencies:
- postcss: 8.5.32
+ postcss: 8.5.23
typescript: 5.9.3
transitivePeerDependencies:
- jiti
@@ -4108,7 +4121,7 @@ snapshots:
undici-types@6.21.0: {}
- undici@7.30.2: {}
+ undici@7.29.0: {}
util-deprecate@1.0.2: {}
@@ -4116,22 +4129,22 @@ snapshots:
uuid@14.0.0: {}
- vite@8.3.6(@types/node@22.19.20)(esbuild@0.28.1):
+ vite@8.0.16(@types/node@22.19.20)(esbuild@0.28.1):
dependencies:
- lightningcss: 1.33.0
- picomatch: 4.0.7
- postcss: 8.5.32
- rolldown: 1.2.16
+ lightningcss: 1.32.0
+ picomatch: 4.0.4
+ postcss: 8.5.23
+ rolldown: 1.0.3
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 22.19.20
esbuild: 0.28.1
fsevents: 2.3.3
- vitest@4.1.11(@types/node@22.19.20)(@vitest/coverage-v8@4.1.11)(vite@8.3.6(@types/node@22.19.20)(esbuild@0.28.1)):
+ vitest@4.1.11(@types/node@22.19.20)(@vitest/coverage-v8@4.1.11)(vite@8.0.16(@types/node@22.19.20)(esbuild@0.28.1)):
dependencies:
'@vitest/expect': 4.1.11
- '@vitest/mocker': 4.1.11(vite@8.3.6(@types/node@22.19.20)(esbuild@0.28.1))
+ '@vitest/mocker': 4.1.11(vite@8.0.16(@types/node@22.19.20)(esbuild@0.28.1))
'@vitest/pretty-format': 4.1.11
'@vitest/runner': 4.1.11
'@vitest/snapshot': 4.1.11
@@ -4148,7 +4161,7 @@ snapshots:
tinyexec: 1.2.4
tinyglobby: 0.2.17
tinyrainbow: 3.1.0
- vite: 8.3.6(@types/node@22.19.20)(esbuild@0.28.1)
+ vite: 8.0.16(@types/node@22.19.20)(esbuild@0.28.1)
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 22.19.20
@@ -4187,10 +4200,9 @@ snapshots:
ws@8.21.0: {}
- wsl-utils@1.0.1:
+ wsl-utils@0.1.0:
dependencies:
is-wsl: 3.1.1
- powershell-utils: 0.2.1
xtend@4.0.2: {}
diff --git a/integrations/openclaw/pnpm-workspace.yaml b/integrations/openclaw/pnpm-workspace.yaml
index 5d33b5e7b..0f9f833bc 100644
--- a/integrations/openclaw/pnpm-workspace.yaml
+++ b/integrations/openclaw/pnpm-workspace.yaml
@@ -13,18 +13,15 @@ onlyBuiltDependencies:
- protobufjs
overrides:
- "@azure/identity@<4.14.1": ">=4.14.1 <5.0.0"
"form-data@<4.0.6": ">=4.0.6"
"protobufjs@<7.6.5": ">=7.6.5 <8.0.0"
- "vite": "^8.1.6"
+ "vite": "^8.0.5"
"langsmith@<0.6.0": "^0.6.0"
"picomatch@<2.3.2": "^2.3.2"
"@qdrant/js-client-rest": "^1.18.0"
"uuid@<11.1.1": ">=11.1.1"
"esbuild": ">=0.28.1"
- "undici@<7.30.1": ">=7.30.1 <8.0.0"
- "axios@<1.20.0": ">=1.20.0 <2.0.0"
+ "undici@<7.29.0": ">=7.29.0 <8.0.0"
+ "axios@<1.18.0": ">=1.18.0 <2.0.0"
"postcss@<8.5.18": ">=8.5.18 <9.0.0"
"mongoose@>=9.0.0 <9.7.2": ">=9.7.2 <10.0.0"
- "follow-redirects@<1.16.2": ">=1.16.2 <2.0.0"
- "source-map-js@<1.2.2": ">=1.2.2 <2.0.0"
diff --git a/integrations/openclaw/telemetry.ts b/integrations/openclaw/telemetry.ts
index bd77e1656..fc1c6b99d 100644
--- a/integrations/openclaw/telemetry.ts
+++ b/integrations/openclaw/telemetry.ts
@@ -1,20 +1,14 @@
import { createHash, randomUUID } from "node:crypto";
import { createTelemetry } from "../agent-plugin-core/typescript/src/telemetry.ts";
-import {
- clearAnonymousTelemetryId,
- clearResolvedAccount,
- getBaseUrl,
- readPluginAuth,
- writePluginAuth,
-} from "./cli/config-file.ts";
+import { clearAnonymousTelemetryId, getBaseUrl, readPluginAuth, writePluginAuth } from "./cli/config-file.ts";
declare const __OPENCLAW_PLUGIN_VERSION__: string;
export const PLUGIN_VERSION: string = __OPENCLAW_PLUGIN_VERSION__;
let cachedAnonymousId: string | undefined;
let aliasCheckDone = false;
-let resolutionAttemptedFor = "";
+let emailResolutionAttempted = false;
let currentDistinctId = "";
function enabled(): boolean {
@@ -39,35 +33,10 @@ function anonymousId(): string {
return (cachedAnonymousId = created);
}
-/** SHA-256 prefix of the key an account was resolved for. */
-function keyFingerprint(apiKey?: string): string {
- return apiKey ? createHash("sha256").update(apiKey).digest("hex").slice(0, 16) : "";
-}
-
function distinctId(apiKey?: string): string {
try {
- const auth = readPluginAuth();
- if (auth.userEmail) {
- // Only when it belongs to the key in hand. Without this check a cached
- // email was used forever: switch to a different account and every event
- // kept reporting under the previous one, with nothing to notice it by.
- if (auth.keyFingerprint === keyFingerprint(apiKey)) {
- return createHash("sha256").update(auth.userEmail).digest("hex");
- }
- // Only a REAL key that disagrees means the account changed. Without the
- // apiKey guard the comparison is `undefined === ""` for any call that
- // simply omits the key, so a capture with no context wiped a perfectly
- // good account out of openclaw.json.
- //
- // A row with an email and NO fingerprint is the legacy shape, from an
- // install predating this field. Clearing it here deleted a real account
- // before anything had replaced it, and if the re-resolve then failed
- // because the user was offline the email was gone from disk for good. The
- // Python core refuses the same trade: verify, and keep what you have until
- // the verification succeeds. resolveEmail below overwrites both fields
- // when it does, so there is nothing to clear first.
- if (apiKey && auth.keyFingerprint) clearResolvedAccount();
- }
+ const email = readPluginAuth().userEmail;
+ if (email) return createHash("sha256").update(email).digest("hex");
} catch {
// Fall through to the API key or anonymous identity.
}
@@ -97,16 +66,8 @@ function identifyAnonymous(id: string): void {
}
function resolveEmail(apiKey: string): void {
- // Latched per key, not once per process. A single boolean meant a key changed
- // mid-session was never looked up, so the fallback identity stuck until restart.
- const fingerprint = keyFingerprint(apiKey);
- if (resolutionAttemptedFor === fingerprint) return;
- resolutionAttemptedFor = fingerprint;
- const releaseLatch = () => {
- // A failed lookup must not pin the fallback identity for the rest of the
- // process. Released so the next capture tries again.
- if (resolutionAttemptedFor === fingerprint) resolutionAttemptedFor = "";
- };
+ if (emailResolutionAttempted) return;
+ emailResolutionAttempted = true;
fetch(`${getBaseUrl().replace(/\/+$/, "")}/v1/ping/`, {
method: "GET",
headers: { Authorization: `Token ${apiKey}`, "Content-Type": "application/json" },
@@ -115,7 +76,7 @@ function resolveEmail(apiKey: string): void {
.then((response) => response.json())
.then((data: any) => {
if (!data?.user_email) return;
- writePluginAuth({ userEmail: data.user_email, keyFingerprint: fingerprint });
+ writePluginAuth({ userEmail: data.user_email });
const oldId = createHash("sha256").update(apiKey).digest("hex");
const newId = createHash("sha256").update(data.user_email).digest("hex");
for (const event of telemetry.queueForTesting()) {
@@ -123,8 +84,7 @@ function resolveEmail(apiKey: string): void {
}
})
.catch(() => {
- // The API-key hash remains a stable fallback, and the next capture retries.
- releaseLatch();
+ // The API-key hash remains a stable fallback.
});
}
@@ -136,15 +96,13 @@ export function captureEvent(
if (!enabled()) return;
try {
currentDistinctId = distinctId(context?.apiKey);
- let resolvedForThisKey = false;
+ let hasEmail = false;
try {
- const auth = readPluginAuth();
- resolvedForThisKey =
- Boolean(auth.userEmail) && auth.keyFingerprint === keyFingerprint(context?.apiKey);
+ hasEmail = Boolean(readPluginAuth().userEmail);
} catch {
// Resolve it below when possible.
}
- if (context?.apiKey && !resolvedForThisKey) resolveEmail(context.apiKey);
+ if (context?.apiKey && !hasEmail) resolveEmail(context.apiKey);
identifyAnonymous(currentDistinctId);
telemetry.capture(eventName, {
mode: context?.mode,
diff --git a/integrations/openclaw/tests/config-file.test.ts b/integrations/openclaw/tests/config-file.test.ts
index ba63180cb..e059ddff3 100644
--- a/integrations/openclaw/tests/config-file.test.ts
+++ b/integrations/openclaw/tests/config-file.test.ts
@@ -237,43 +237,3 @@ describe("getBaseUrl", () => {
expect(getBaseUrl()).toBe(DEFAULT_BASE_URL);
});
});
-
-// ---------------------------------------------------------------------------
-// keyFingerprint round trip
-// ---------------------------------------------------------------------------
-
-describe("keyFingerprint survives a write and read", () => {
- it("readPluginAuth returns a persisted keyFingerprint", () => {
- // It did not. readPluginAuth builds its result field by field, and this one
- // was missing, so every fingerprint comparison ran against undefined, the
- // resolved email was never used again, and telemetry silently fell back to
- // the API key hash. The telemetry tests could not see it because they mock
- // this module and their mock returned the field the real reader dropped.
- setConfigFile({
- plugins: {
- entries: {
- "openclaw-mem0": {
- config: {
- apiKey: "m0-test",
- userEmail: "person@example.com",
- keyFingerprint: "0123456789abcdef",
- },
- },
- },
- },
- });
-
- expect(readPluginAuth().keyFingerprint).toBe("0123456789abcdef");
- });
-
- it("writePluginAuth persists it where readPluginAuth looks", () => {
- setConfigFile({ plugins: { entries: { "openclaw-mem0": { config: {} } } } });
-
- writePluginAuth({ userEmail: "person@example.com", keyFingerprint: "abc123" });
-
- const written = JSON.parse(mockWriteText.mock.calls.at(-1)![1] as string);
- const cfg = written.plugins.entries["openclaw-mem0"].config;
- expect(cfg.keyFingerprint).toBe("abc123");
- expect(cfg.userEmail).toBe("person@example.com");
- });
-});
diff --git a/integrations/openclaw/tests/config.test.ts b/integrations/openclaw/tests/config.test.ts
index 334c064fb..2c6dbac2e 100644
--- a/integrations/openclaw/tests/config.test.ts
+++ b/integrations/openclaw/tests/config.test.ts
@@ -485,18 +485,3 @@ describe("mem0ConfigSchema.parse() โ apiKey edge cases", () => {
expect(cfg.needsSetup).toBe(false);
});
});
-
-describe("telemetry fingerprint round trip", () => {
- it("a config carrying keyFingerprint is accepted by the real schema", () => {
- // What writePluginAuth persists after a successful lookup. It was not in
- // ALLOWED_KEYS, and assertAllowedKeys throws, so the first successful
- // resolve wrote a config that broke every subsequent load of the plugin.
- const persisted = {
- apiKey: "m0-test",
- userEmail: "person@example.com",
- keyFingerprint: "0123456789abcdef",
- };
-
- expect(() => mem0ConfigSchema.parse(persisted)).not.toThrow();
- });
-});
diff --git a/integrations/openclaw/tests/telemetry.test.ts b/integrations/openclaw/tests/telemetry.test.ts
index ad7a9bbe0..9a7bee716 100644
--- a/integrations/openclaw/tests/telemetry.test.ts
+++ b/integrations/openclaw/tests/telemetry.test.ts
@@ -3,30 +3,15 @@ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
// Mock config-file before importing telemetry
vi.mock("../cli/config-file.ts", () => ({
readPluginAuth: vi.fn().mockReturnValue({}),
- writePluginAuth: vi.fn(),
- clearAnonymousTelemetryId: vi.fn(),
- clearResolvedAccount: vi.fn(),
- getBaseUrl: vi.fn().mockReturnValue("https://api.mem0.ai"),
}));
import { captureEvent } from "../telemetry.ts";
-import { clearResolvedAccount, readPluginAuth } from "../cli/config-file.ts";
-
-/** sha256(key).slice(0, 16), the shape telemetry.ts stores. */
-async function fingerprintOf(apiKey: string): Promise {
- const { createHash } = await import("node:crypto");
- return createHash("sha256").update(apiKey).digest("hex").slice(0, 16);
-}
+import { readPluginAuth } from "../cli/config-file.ts";
describe("telemetry", () => {
let fetchSpy: ReturnType;
beforeEach(() => {
- // Call history has to be cleared per test, not just restored: the mocks are
- // module-level vi.fn()s, so without this one test's calls are visible to the
- // next and assertions on "was not called" pass or fail by ordering.
- vi.clearAllMocks();
- (readPluginAuth as ReturnType).mockReturnValue({});
// Reset telemetry enabled state
(globalThis as any).__mem0_telemetry_override = undefined;
fetchSpy = vi.fn().mockResolvedValue({ ok: true });
@@ -55,31 +40,11 @@ describe("telemetry", () => {
expect(() => captureEvent("test_event")).not.toThrow();
});
- it("uses userEmail as distinct ID when it belongs to the current key", async () => {
- // Previously asserted only not.toThrow(), which passed whatever the identity
- // turned out to be, and under the fingerprint gate the no-context path does
- // not use the email at all. Pin the real condition instead.
- (readPluginAuth as ReturnType).mockReturnValue({
+ it("uses userEmail as distinct ID when available", () => {
+ (readPluginAuth as ReturnType).mockReturnValueOnce({
userEmail: "test@example.com",
- keyFingerprint: await fingerprintOf("key-a"),
});
-
- captureEvent("test_event", {}, { apiKey: "key-a" });
-
- expect(clearResolvedAccount).not.toHaveBeenCalled();
- });
-
- it("a capture with no apiKey leaves a resolved account alone", async () => {
- // `undefined === ""` made every keyless capture look like a key change, so
- // one context-free call wiped a good account out of openclaw.json.
- (readPluginAuth as ReturnType).mockReturnValue({
- userEmail: "test@example.com",
- keyFingerprint: await fingerprintOf("key-a"),
- });
-
- captureEvent("test_event");
-
- expect(clearResolvedAccount).not.toHaveBeenCalled();
+ expect(() => captureEvent("test_event")).not.toThrow();
});
it("falls back to a generated anonymous id when no apiKey", () => {
@@ -87,43 +52,6 @@ describe("telemetry", () => {
expect(() => captureEvent("test_event", {}, {})).not.toThrow();
});
- it("keeps using a cached email only while it belongs to the current key", async () => {
- (readPluginAuth as ReturnType).mockReturnValue({
- userEmail: "person@example.com",
- keyFingerprint: await fingerprintOf("key-a"),
- });
-
- captureEvent("test_event", {}, { apiKey: "key-a" });
-
- expect(clearResolvedAccount).not.toHaveBeenCalled();
- });
-
- it("forgets the account when the API key changes", async () => {
- // The defect: the cached email was used forever, so events after an account
- // switch kept reporting under the previous account.
- (readPluginAuth as ReturnType).mockReturnValue({
- userEmail: "person@example.com",
- keyFingerprint: await fingerprintOf("key-a"),
- });
-
- captureEvent("test_event", {}, { apiKey: "key-b" });
-
- expect(clearResolvedAccount).toHaveBeenCalled();
- });
-
- it("re-resolves for a key it has not looked up before", async () => {
- (readPluginAuth as ReturnType).mockReturnValue({
- userEmail: "person@example.com",
- keyFingerprint: await fingerprintOf("key-a"),
- });
-
- captureEvent("test_event", {}, { apiKey: "key-c" });
-
- // The resolution latch is per key, not once per process, so a key changed
- // mid-session is actually looked up instead of sticking to the fallback.
- expect(fetchSpy).toHaveBeenCalled();
- });
-
it("handles readPluginAuth errors gracefully", () => {
(readPluginAuth as ReturnType).mockImplementationOnce(() => {
throw new Error("config read failed");
diff --git a/integrations/openclaw/tools/memory-search.ts b/integrations/openclaw/tools/memory-search.ts
index 51d2ebcfd..58ce8183a 100644
--- a/integrations/openclaw/tools/memory-search.ts
+++ b/integrations/openclaw/tools/memory-search.ts
@@ -1,5 +1,4 @@
import { Type } from "@sinclair/typebox";
-import { USER_SEARCH_QUERY_DESCRIPTION, USER_SEARCH_TOOL_DESCRIPTION } from "../../agent-plugin-core/typescript/src/prompts.ts";
import type { MemoryItem, SearchOptions } from "../types.ts";
import type { ToolDeps } from "./index.ts";
@@ -9,9 +8,9 @@ export function createMemorySearchTool(deps: ToolDeps) {
return {
name: "memory_search",
label: "Memory Search",
- description: USER_SEARCH_TOOL_DESCRIPTION,
+ description: "Search long-term memories stored in Mem0 by semantic meaning. Use this proactively before answering when the request may depend on the user's past work, preferences, or decisions -- relevant memories are not always already in context. For multi-part or comparative questions, run several searches with different phrasings and combine the results rather than stopping after one (multi-hop).",
parameters: Type.Object({
- query: Type.String({ description: USER_SEARCH_QUERY_DESCRIPTION }),
+ query: Type.String({ description: "Search query" }),
limit: Type.Optional(Type.Number({ description: `Max results (default: ${cfg.topK})` })),
userId: Type.Optional(Type.String({ description: "User ID to scope search" })),
agentId: Type.Optional(Type.String({ description: "Agent ID to search a specific agent's memories" })),
diff --git a/integrations/opencode-plugin/opencode-mem0.ts b/integrations/opencode-plugin/opencode-mem0.ts
index a86eab3af..8dcf6d535 100644
--- a/integrations/opencode-plugin/opencode-mem0.ts
+++ b/integrations/opencode-plugin/opencode-mem0.ts
@@ -18,7 +18,6 @@ import {asScope, scopeSearchFilters, scopeWriteParams, resolveDefaultScope, SCOP
import {parseProjectFromRemote} from "./project";
import {resolveApiKey} from "./api-key";
import {createMemoryLifecycle} from "../agent-plugin-core/typescript/src/lifecycle.ts";
-import {SEARCH_QUERY_DESCRIPTION, SEARCH_TOOL_DESCRIPTION} from "../agent-plugin-core/typescript/src/prompts.ts";
async function getUserId(): Promise {
if (process.env.MEM0_USER_ID) return process.env.MEM0_USER_ID;
@@ -425,9 +424,9 @@ Identity context (resolved at plugin startup):
}),
search_memories: tool({
- description: SEARCH_TOOL_DESCRIPTION,
+ description: "Search stored memories by semantic meaning. Use this proactively before answering when the request may depend on the user's past work, preferences, decisions, or environment -- relevant memories are not always auto-injected. For multi-part or comparative questions, run several searches with different phrasings and combine the results rather than stopping after one (multi-hop).",
args: {
- query: tool.schema.string().describe(SEARCH_QUERY_DESCRIPTION),
+ query: tool.schema.string().describe("Search query"),
user_id: tool.schema.string().optional().describe("User ID"),
app_id: tool.schema.string().optional().describe("App/Project ID"),
agent_id: tool.schema.string().optional().describe("Agent ID"),
@@ -637,6 +636,9 @@ Identity context (resolved at plugin startup):
}
if (memoryCount > 0) {
+ systemContext.push(
+ "Search mem0 for recent decisions and task learnings before responding. Run 2 parallel searches: one for decision type, one for task_learning type.",
+ );
try {
const res = await mem0.search(
"recent session state decisions and learnings",
@@ -657,6 +659,9 @@ Identity context (resolved at plugin startup):
}
}
+ systemContext.push(
+ "Mem0 searches apply when user references past work, decision questions, errors, or non-trivial tasks. Queries use noun-phrases, 2-4 parallel calls with different metadata.type filters, and include user_id + app_id.",
+ );
systemContext.push(SCOPE_GUIDANCE);
const activeScope = loadDefaultScope();
if (activeScope !== "project") {
diff --git a/integrations/opencode-plugin/opencode-skills/mem0-context-loader/SKILL.md b/integrations/opencode-plugin/opencode-skills/mem0-context-loader/SKILL.md
index b22f647dc..803689076 100644
--- a/integrations/opencode-plugin/opencode-skills/mem0-context-loader/SKILL.md
+++ b/integrations/opencode-plugin/opencode-skills/mem0-context-loader/SKILL.md
@@ -1,19 +1,35 @@
---
name: mem0-context-loader
-description: Search memories from earlier OpenCode sessions in this repository. Use it when earlier work may already explain the code, error, decision, or command you need, so you can avoid repeating file reads, searches, or experiments.
+description: Searches and injects relevant memories into context before starting work on a task. Use when beginning a new task, switching context, or when project history, past decisions, or coding conventions need to be loaded.
---
# Context Loader
Pre-fetches relevant memories to prime context before working on a task.
+## When to use
+
+- Session start (invoke manually or auto-triggered by skill description matching)
+- User starts work on a specific feature or file set
+- Complex multi-step task begins
+- User says "what do we know about X" or "context for X"
+
## Steps
1. **Extract topics** from current message/task. Identify: file paths, module names, feature areas, error patterns.
-2. **Call `search_memories` once** with a focused question about the task: `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=10`.
+2. **Run 2-4 parallel `search_memories` calls** with different angles:
-3. **Output compact context block** (max 10 memories):
+ | Query angle | Filter | Purpose |
+ |---|---|---|
+ | Feature/module name | `{"AND": [{"user_id": ""}, {"app_id": ""}, {"metadata": {"type": "decision"}}]}` | Architecture decisions |
+ | File paths mentioned | `{"AND": [{"user_id": ""}, {"app_id": ""}, {"metadata": {"type": "convention"}}]}` | Coding patterns |
+ | Error keywords (if any) | `{"AND": [{"user_id": ""}, {"app_id": ""}, {"metadata": {"type": "anti_pattern"}}]}` | Known pitfalls |
+ | Broad project context | `{"AND": [{"user_id": ""}, {"app_id": ""}]}` | Catch-all |
+
+3. **Deduplicate** results by memory ID across all search responses.
+
+4. **Output compact context block** (max 10 memories):
```
context-loader: loaded memories for ""
@@ -22,7 +38,7 @@ context-loader: loaded memories for ""
- [anti_pattern] [mem0:]
```
-4. If **zero results**: output nothing. Don't announce empty context.
+5. If **zero results**: output nothing. Don't announce empty context.
## Constraints
diff --git a/integrations/opencode-plugin/opencode-skills/mem0-search/SKILL.md b/integrations/opencode-plugin/opencode-skills/mem0-search/SKILL.md
index e6b570d12..ed3533991 100644
--- a/integrations/opencode-plugin/opencode-skills/mem0-search/SKILL.md
+++ b/integrations/opencode-plugin/opencode-skills/mem0-search/SKILL.md
@@ -27,11 +27,14 @@ When an ID is detected:
### Step 2: Search
-Call `search_memories` once with the user's question: `query=`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=10`.
+Run 2 parallel `search_memories` calls:
+
+1. Broad: `query=`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=10`, `rerank=true`
+2. Targeted: `query=`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}, {"metadata": {"type": "decision"}}]}`, `top_k=5`, `rerank=true`
### Step 3: Display
-Show compact results:
+Deduplicate by ID, then show compact results:
```
## mem0 search: "" ( results)
diff --git a/integrations/opencode-plugin/package.json b/integrations/opencode-plugin/package.json
index 36c3dce6b..79f68c4a8 100644
--- a/integrations/opencode-plugin/package.json
+++ b/integrations/opencode-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/opencode-plugin",
- "version": "0.4.1",
+ "version": "0.3.0",
"type": "module",
"description": "Mem0 persistent memory plugin for OpenCode โ add, search, and manage memories across sessions",
"main": "dist/index.js",
@@ -38,7 +38,6 @@
"build": "bun build opencode-mem0.ts --outdir dist --target bun --format esm --entry-naming index.[ext]",
"dev": "bun build opencode-mem0.ts --outdir dist --target bun --format esm --entry-naming index.[ext] --watch",
"type-check": "tsc --noEmit",
- "test": "bun test",
"prepack": "bun run build",
"postpack": ""
},
diff --git a/integrations/opencode-plugin/telemetry.test.ts b/integrations/opencode-plugin/telemetry.test.ts
index 79dc3ffdb..393150977 100644
--- a/integrations/opencode-plugin/telemetry.test.ts
+++ b/integrations/opencode-plugin/telemetry.test.ts
@@ -1,5 +1,3 @@
-import { createHash } from "node:crypto";
-
import { afterEach, describe, expect, test } from "bun:test";
import { buildEvent, captureEvent, isTelemetryEnabled } from "./telemetry";
@@ -15,10 +13,7 @@ describe("opencode telemetry", () => {
expect(payload).not.toBeNull();
const props = payload!.properties as Record;
expect(payload!.event).toBe("plugin.session_start");
- // Was "plugin", which named no particular plugin and matched no vocabulary.
- // Now shaped like every other surface. Any saved PostHog insight filtering
- // source = "plugin" needs repointing; historical data is untouched.
- expect(props.source).toBe("OPENCODE_PLUGIN");
+ expect(props.source).toBe("plugin");
expect(props.platform).toBe("opencode");
expect(props.memory_count).toBe(5);
expect(props.$process_person_profile).toBe(false);
@@ -35,7 +30,7 @@ describe("opencode telemetry", () => {
const props = buildEvent("x", { platform: "HACK", source: "HACK" }, KEY)!
.properties as Record;
expect(props.platform).toBe("opencode");
- expect(props.source).toBe("OPENCODE_PLUGIN");
+ expect(props.source).toBe("plugin");
});
test("returns null without an API key (no anonymous events)", () => {
@@ -61,12 +56,9 @@ describe("opencode telemetry", () => {
expect(typeof props.os_version).toBe("string");
});
- test("project_hash is a salted digest of the project id", async () => {
- // Previously asserted the bare sha256(projectId), which is the defect: that
- // digest is reversible by anyone who can guess a project id. Salted with the
- // API key, which is already in play here and is high entropy.
+ test("project_hash is sha256(projectId) when a project id is supplied", async () => {
const { createHash } = await import("node:crypto");
- const expected = createHash("sha256").update(`${KEY}:acme-repo`).digest("hex");
+ const expected = createHash("sha256").update("acme-repo").digest("hex");
const props = buildEvent("session_start", {}, KEY, "acme-repo")!
.properties as Record;
expect(props.project_hash).toBe(expected);
@@ -84,38 +76,3 @@ describe("opencode telemetry", () => {
}
});
});
-
-describe("project_hash salting", () => {
- const PROJECT = "my-project";
-
- test("is not a bare digest of the project id", () => {
- // The defect: an unsalted SHA-256 over a guessable identifier is reversible
- // by anyone who can enumerate project ids.
- const unsalted = createHash("sha256").update(PROJECT).digest("hex");
- const payload = buildEvent("session_start", {}, KEY, PROJECT) as Record;
-
- expect(payload.properties.project_hash).toBeDefined();
- expect(payload.properties.project_hash).not.toBe(unsalted);
- });
-
- test("differs per account for the same project", () => {
- const a = buildEvent("session_start", {}, "m0-account-a", PROJECT) as Record;
- const b = buildEvent("session_start", {}, "m0-account-b", PROJECT) as Record;
-
- expect(a.properties.project_hash).not.toBe(b.properties.project_hash);
- });
-
- test("is stable for one account, so joins still work", () => {
- const first = buildEvent("session_start", {}, KEY, PROJECT) as Record;
- const second = buildEvent("session_end", {}, KEY, PROJECT) as Record;
-
- expect(first.properties.project_hash).toBe(second.properties.project_hash);
- });
-
- test("is omitted rather than unsalted when there is no key", () => {
- const payload = buildEvent("session_start", {}, undefined, PROJECT);
-
- // No key means no event at all, so there is no unsalted hash to leak.
- expect(payload).toBeNull();
- });
-});
diff --git a/integrations/opencode-plugin/telemetry.ts b/integrations/opencode-plugin/telemetry.ts
index e2316dd88..8d0861d97 100644
--- a/integrations/opencode-plugin/telemetry.ts
+++ b/integrations/opencode-plugin/telemetry.ts
@@ -25,9 +25,7 @@ const PLUGIN_VERSION = (() => {
let currentDistinctId = "";
const telemetry = createTelemetry({
host: "opencode",
- // Shaped like the platform's EventSource values, as every other surface is.
- // "plugin" said nothing about which plugin and matched no vocabulary.
- source: "OPENCODE_PLUGIN",
+ source: "plugin",
version: PLUGIN_VERSION,
distinctId: () => currentDistinctId,
eventName: (event) => `plugin.${event}`,
@@ -42,23 +40,8 @@ function distinctId(apiKey: string): string {
return createHash("sha256").update(apiKey).digest("hex").slice(0, 32);
}
-/**
- * Salted so the hash is not enumerable.
- *
- * An unsalted SHA-256 of a project id is reversible by anyone who can guess the
- * id, which for a project identifier is a small space. The API key is the salt:
- * it is already in play here (distinctId is a digest of it), it is high entropy,
- * and using it needs no per-install file and so no write race to get wrong. The
- * hash is therefore per account rather than per machine, which also keeps joins
- * working for one user across machines. It resets when the key rotates, which is
- * consistent, because distinctId resets with it.
- *
- * Both are omitted without a key. An event cannot be built without a distinctId
- * anyway, so this costs nothing.
- */
-function projectHash(projectId?: string, apiKey?: string): Record {
- if (!projectId || !apiKey) return {};
- return { project_hash: createHash("sha256").update(`${apiKey}:${projectId}`).digest("hex") };
+function projectHash(projectId?: string): Record {
+ return projectId ? { project_hash: createHash("sha256").update(projectId).digest("hex") } : {};
}
export function buildEvent(
@@ -68,7 +51,7 @@ export function buildEvent(
projectId?: string,
): Record | null {
currentDistinctId = apiKey ? distinctId(apiKey) : "";
- const event = telemetry.build(eventType, { ...properties, ...projectHash(projectId, apiKey) });
+ const event = telemetry.build(eventType, { ...properties, ...projectHash(projectId) });
return event ? { api_key: POSTHOG_API_KEY, ...event } : null;
}
@@ -79,5 +62,5 @@ export function captureEvent(
projectId?: string,
): void {
currentDistinctId = apiKey ? distinctId(apiKey) : "";
- telemetry.capture(eventType, { ...properties, ...projectHash(projectId, apiKey) });
+ telemetry.capture(eventType, { ...properties, ...projectHash(projectId) });
}
diff --git a/integrations/pi-agent-plugin/README.md b/integrations/pi-agent-plugin/README.md
index 3dc5b351b..cb28d2314 100644
--- a/integrations/pi-agent-plugin/README.md
+++ b/integrations/pi-agent-plugin/README.md
@@ -71,7 +71,7 @@ The plugin includes 6 skills that guide the agent on how to use each capability:
| Skill | Purpose |
|-------|---------|
-| `context-loader` | Search memories when earlier work may already explain the task |
+| `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 |
diff --git a/integrations/pi-agent-plugin/package.json b/integrations/pi-agent-plugin/package.json
index ed7b70b6c..d05673406 100644
--- a/integrations/pi-agent-plugin/package.json
+++ b/integrations/pi-agent-plugin/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/pi-agent-plugin",
- "version": "0.3.2",
+ "version": "0.3.0",
"type": "module",
"description": "Mem0 memory extension for Pi Agent persistent, scoped, semantic memory across sessions and projects",
"license": "Apache-2.0",
@@ -69,19 +69,16 @@
},
"pnpm": {
"overrides": {
- "@azure/identity@<4.14.1": ">=4.14.1 <5.0.0",
"form-data@<4.0.6": ">=4.0.6",
"uuid@<11.1.1": ">=11.1.1",
"esbuild": ">=0.28.1",
- "undici@<7.30.1": ">=7.30.1 <8.0.0",
- "undici@>=8.0.0 <8.12.2": ">=8.12.2 <9.0.0",
- "axios@<1.20.0": ">=1.20.0 <2.0.0",
+ "undici@<7.29.0": ">=7.29.0 <8.0.0",
+ "undici@>=8.0.0 <8.9.0": ">=8.9.0 <9.0.0",
+ "axios@<1.18.0": ">=1.18.0 <2.0.0",
"brace-expansion@>=3.0.0 <5.0.8": ">=5.0.8 <6.0.0",
"postcss@<8.5.18": ">=8.5.18 <9.0.0",
"mongoose@>=9.0.0 <9.7.2": ">=9.7.2 <10.0.0",
- "protobufjs@<7.6.5": ">=7.6.5 <8.0.0",
- "follow-redirects@<1.16.2": ">=1.16.2 <2.0.0",
- "vite": "^8.1.6"
+ "protobufjs@<7.6.5": ">=7.6.5 <8.0.0"
}
}
}
diff --git a/integrations/pi-agent-plugin/pnpm-lock.yaml b/integrations/pi-agent-plugin/pnpm-lock.yaml
index dfb76912f..177023505 100644
--- a/integrations/pi-agent-plugin/pnpm-lock.yaml
+++ b/integrations/pi-agent-plugin/pnpm-lock.yaml
@@ -5,19 +5,16 @@ settings:
excludeLinksFromLockfile: false
overrides:
- '@azure/identity@<4.14.1': '>=4.14.1 <5.0.0'
form-data@<4.0.6: '>=4.0.6'
uuid@<11.1.1: '>=11.1.1'
esbuild: '>=0.28.1'
- undici@<7.30.1: '>=7.30.1 <8.0.0'
- undici@>=8.0.0 <8.12.2: '>=8.12.2 <9.0.0'
- axios@<1.20.0: '>=1.20.0 <2.0.0'
+ undici@<7.29.0: '>=7.29.0 <8.0.0'
+ undici@>=8.0.0 <8.9.0: '>=8.9.0 <9.0.0'
+ axios@<1.18.0: '>=1.18.0 <2.0.0'
brace-expansion@>=3.0.0 <5.0.8: '>=5.0.8 <6.0.0'
postcss@<8.5.18: '>=8.5.18 <9.0.0'
mongoose@>=9.0.0 <9.7.2: '>=9.7.2 <10.0.0'
protobufjs@<7.6.5: '>=7.6.5 <8.0.0'
- follow-redirects@<1.16.2: '>=1.16.2 <2.0.0'
- vite: ^8.1.6
importers:
@@ -25,7 +22,7 @@ importers:
dependencies:
mem0ai:
specifier: ^3.0.7
- version: 3.0.7(@anthropic-ai/sdk@0.91.1(zod@3.25.76))(@azure/identity@4.14.1)(@azure/search-documents@12.2.0)(@cloudflare/workers-types@4.20260610.1)(@google/genai@1.52.0)(@langchain/core@1.1.48(openai@6.26.0(ws@8.21.0)(zod@3.25.76))(ws@8.21.0))(@mistralai/mistralai@2.2.1)(@qdrant/js-client-rest@1.18.0(typescript@6.0.3))(@supabase/supabase-js@2.108.1)(@types/jest@29.5.14)(@types/pg@8.11.0)(better-sqlite3@12.10.0)(cloudflare@4.5.0)(compromise@14.15.1)(groq-sdk@0.3.0)(natural@8.1.1)(ollama@0.5.18)(pg@8.11.3)(redis@5.12.1)(ws@8.21.0)
+ version: 3.0.7(@anthropic-ai/sdk@0.91.1(zod@3.25.76))(@azure/identity@4.13.1)(@azure/search-documents@12.2.0)(@cloudflare/workers-types@4.20260610.1)(@google/genai@1.52.0)(@langchain/core@1.1.48(openai@6.26.0(ws@8.21.0)(zod@3.25.76))(ws@8.21.0))(@mistralai/mistralai@2.2.1)(@qdrant/js-client-rest@1.18.0(typescript@6.0.3))(@supabase/supabase-js@2.108.1)(@types/jest@29.5.14)(@types/pg@8.11.0)(better-sqlite3@12.10.0)(cloudflare@4.5.0)(compromise@14.15.1)(groq-sdk@0.3.0)(natural@8.1.1)(ollama@0.5.18)(pg@8.11.3)(redis@5.12.1)(ws@8.21.0)
devDependencies:
'@earendil-works/pi-ai':
specifier: ^0.79.0
@@ -38,7 +35,7 @@ importers:
version: 25.9.2
tsup:
specifier: ^8.5.0
- version: 8.5.1(jiti@2.7.0)(postcss@8.5.32)(typescript@6.0.3)(yaml@2.9.0)
+ version: 8.5.1(jiti@2.7.0)(postcss@8.5.23)(typescript@6.0.3)(yaml@2.9.0)
typebox:
specifier: ^1.2.3
version: 1.2.8
@@ -47,7 +44,7 @@ importers:
version: 6.0.3
vitest:
specifier: ^4.1.11
- version: 4.1.11(@types/node@25.9.2)(vite@8.3.6(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0))
+ version: 4.1.11(@types/node@25.9.2)(vite@8.0.16(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0))
packages:
@@ -184,10 +181,6 @@ packages:
resolution: {integrity: sha512-YKWi9YuCU04B55h25cnOYZHxXYtEvQEbKST5vqRga7hWY9ydd3FZHdeQF8pyh+acWZvppw13M/LMGx0LABUVMA==}
engines: {node: '>=18.0.0'}
- '@azure/core-process@1.0.0':
- resolution: {integrity: sha512-/shnJ+ooO8WPxDhPEeI/2oRQuubn16gZ6CvlbpWbEswZfzwI9tI/sMAHmF3x1LuQ9yZYXfLW3TjzGMLEC5blKg==}
- engines: {node: '>=22.0.0'}
-
'@azure/core-rest-pipeline@1.24.0':
resolution: {integrity: sha512-PpLsoDQ3AMmKZ0VU+0GrmqMxgp/sExjlVm4R+nLWngeoEGAzOIPVifaxKGU5gMv+nWELUoHfvrolWD+ZS/nFJg==}
engines: {node: '>=20.0.0'}
@@ -200,9 +193,9 @@ packages:
resolution: {integrity: sha512-XPArKLzsvl0Hf0CaGyKHUyVgF7oDnhKoP85Xv6M4StF/1AhfORhZudHtOyf2s+FcbuQ9dPRAjB8J2KvRRMUK2A==}
engines: {node: '>=20.0.0'}
- '@azure/identity@4.14.1':
- resolution: {integrity: sha512-HHuuFrmN1uuF9D5A6aAo5eHzNFNX4Q+P4SksZqDKse5YaJFFy/zDLG3wXHEV2FVGgetZ3QM8jGURNBtnQYf1NQ==}
- engines: {node: '>=22.0.0'}
+ '@azure/identity@4.13.1':
+ resolution: {integrity: sha512-5C/2WD5Vb1lHnZS16dNQRPMjN6oV/Upba+C9nBIs15PmOi6A3ZGs4Lr2u60zw4S04gi+u3cEXiqTVP7M4Pz3kw==}
+ engines: {node: '>=20.0.0'}
'@azure/logger@1.3.0':
resolution: {integrity: sha512-fCqPIfOcLE+CGqGPd66c8bZpwAji98tZ4JI9i/mlTNTlsIWslCfpg48s/ypyLxZTump5sypjrKn2/kY7q8oAbA==}
@@ -212,16 +205,12 @@ packages:
resolution: {integrity: sha512-eNf2aqx1C6I0yT1GEu5ukblFrmaBXGfe1bivpmlfqvK7giPZvoXLa404C8EfeHVsy6EIryfQuPRzuW1fPxWlHg==}
engines: {node: '>=0.8.0'}
- '@azure/msal-common@16.16.0':
- resolution: {integrity: sha512-EZgd8h5nczsdRAQAgXA0A0pC5L/zj43n1jePXvUMgdwXMbH2zhb7b7Hp+Oe7ZOODK/sch2x+soD6FOrtgUbx/w==}
- engines: {node: '>=0.8.0'}
-
'@azure/msal-common@16.7.0':
resolution: {integrity: sha512-Jb8Y7pX6KM42SIT7KWP6YbY3+vLbwB5b5m+tpiiOzMU1QeyelQzs9lO8jv1e7/Uj9r7tg7VjPvW4T0KB1jF3UQ==}
engines: {node: '>=0.8.0'}
- '@azure/msal-node@7.2.0':
- resolution: {integrity: sha512-Y87VJsMWF4jiqLqq8XYLb1o+rGc/HacwS3Zydi3bDtaVm5Sa8FlB7YrKrBFKRIYj27RJXAaDkErImMAqtM10Pg==}
+ '@azure/msal-node@5.2.3':
+ resolution: {integrity: sha512-YYX4TchEVddVBiybKvKhV9QO/q22jgewP+BVxKG7Uh115voPcviGlypbKERDsqQdAiSTJrwi80gcWFjYKdo8+Q==}
engines: {node: '>=20'}
'@azure/search-documents@12.2.0':
@@ -264,6 +253,15 @@ packages:
resolution: {integrity: sha512-YvZCMfSE0YDSLNklAwMY6LC6SyEgnP0zMOoioTLNnXFNdexrCexMJdee7iDJsNcFlKt7+DVLccomuURtZS1C6g==}
engines: {node: '>=22.19.0'}
+ '@emnapi/core@1.10.0':
+ resolution: {integrity: sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==}
+
+ '@emnapi/runtime@1.10.0':
+ resolution: {integrity: sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==}
+
+ '@emnapi/wasi-threads@1.2.1':
+ resolution: {integrity: sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==}
+
'@esbuild/aix-ppc64@0.28.1':
resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==}
engines: {node: '>=18'}
@@ -532,11 +530,17 @@ packages:
'@mongodb-js/saslprep@1.4.11':
resolution: {integrity: sha512-o9rAHc0IpIjuPSxRutWpE1F62x7n+4mVS4rCNHkzhIUMQcc18bb6xEq5wd2NdN0WjepIyXIppRshYI2kQDOZVA==}
+ '@napi-rs/wasm-runtime@1.1.5':
+ resolution: {integrity: sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==}
+ peerDependencies:
+ '@emnapi/core': ^1.7.1
+ '@emnapi/runtime': ^1.7.1
+
'@nodable/entities@2.1.1':
resolution: {integrity: sha512-Pig3HxDIoMgjdEH8OCf/dkcTmLFjJRjWuq8jSnklu284/TKOPibSRERmOykiwmyXTtv61mP+44f3GMx0tLAyjg==}
- '@oxc-project/types@0.156.0':
- resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==}
+ '@oxc-project/types@0.133.0':
+ resolution: {integrity: sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==}
'@protobufjs/aspromise@1.1.2':
resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==}
@@ -611,98 +615,97 @@ packages:
peerDependencies:
'@redis/client': ^5.12.1
- '@rolldown/binding-android-arm-eabi@1.2.16':
- resolution: {integrity: sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==}
- engines: {node: ^20.19.0 || >=22.12.0}
- cpu: [arm]
- os: [android]
-
- '@rolldown/binding-android-arm64@1.2.16':
- resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==}
+ '@rolldown/binding-android-arm64@1.0.3':
+ resolution: {integrity: sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [android]
- '@rolldown/binding-darwin-arm64@1.2.16':
- resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==}
+ '@rolldown/binding-darwin-arm64@1.0.3':
+ resolution: {integrity: sha512-PcAhP+ynjURNyy8SKGl5DQP94aGuB/7JrXJb/t7P+hanXvQVMWzUvRRhBAcg/lNRadBhoUPqSoP4xw5tR/KBEA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [darwin]
- '@rolldown/binding-darwin-x64@1.2.16':
- resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==}
+ '@rolldown/binding-darwin-x64@1.0.3':
+ resolution: {integrity: sha512-9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [darwin]
- '@rolldown/binding-freebsd-x64@1.2.16':
- resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==}
+ '@rolldown/binding-freebsd-x64@1.0.3':
+ resolution: {integrity: sha512-yB1IlAsSNHncV6SCTL27/MVGR5htvQsoGxIv5KMGXALp+Ll1wYsn+x98M9MW7qa+NdSbvrrY7ANI4wLJ0n1e6g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [freebsd]
- '@rolldown/binding-linux-arm-gnueabihf@1.2.16':
- resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==}
+ '@rolldown/binding-linux-arm-gnueabihf@1.0.3':
+ resolution: {integrity: sha512-Yi30IVAAfLUCy2MseFjbB1jAMDl1VMCAas5StnYp8da9+CKvMd2H2cbEjWcw5NPaPqzvYkVIaF1nNUG+b7u/sw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm]
os: [linux]
- '@rolldown/binding-linux-arm64-gnu@1.2.16':
- resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==}
+ '@rolldown/binding-linux-arm64-gnu@1.0.3':
+ resolution: {integrity: sha512-jsO7R8To+AdlYgUmN5sHSCZbfhtMBkO0WUx8iORQnPcMMdgr7qM2DQmMwgabs3GhNztdmoKkMKQFHD6DTMCIQw==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [glibc]
- '@rolldown/binding-linux-arm64-musl@1.2.16':
- resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==}
+ '@rolldown/binding-linux-arm64-musl@1.0.3':
+ resolution: {integrity: sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [linux]
libc: [musl]
- '@rolldown/binding-linux-ppc64-gnu@1.2.16':
- resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==}
+ '@rolldown/binding-linux-ppc64-gnu@1.0.3':
+ resolution: {integrity: sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [ppc64]
os: [linux]
libc: [glibc]
- '@rolldown/binding-linux-s390x-gnu@1.2.16':
- resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==}
+ '@rolldown/binding-linux-s390x-gnu@1.0.3':
+ resolution: {integrity: sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [s390x]
os: [linux]
libc: [glibc]
- '@rolldown/binding-linux-x64-gnu@1.2.16':
- resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==}
+ '@rolldown/binding-linux-x64-gnu@1.0.3':
+ resolution: {integrity: sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [glibc]
- '@rolldown/binding-linux-x64-musl@1.2.16':
- resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==}
+ '@rolldown/binding-linux-x64-musl@1.0.3':
+ resolution: {integrity: sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [linux]
libc: [musl]
- '@rolldown/binding-openharmony-arm64@1.2.16':
- resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==}
+ '@rolldown/binding-openharmony-arm64@1.0.3':
+ resolution: {integrity: sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [openharmony]
- '@rolldown/binding-win32-arm64-msvc@1.2.16':
- resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==}
+ '@rolldown/binding-wasm32-wasi@1.0.3':
+ resolution: {integrity: sha512-JTtb8BWFynicNSoPrehsCzBtOKjZ6jhMiPFEmOiuXg1Fl8dn2KHQob+GuPSGR0dryQa1PQJbzjF3dqO/whhjLg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [wasm32]
+
+ '@rolldown/binding-win32-arm64-msvc@1.0.3':
+ resolution: {integrity: sha512-gEdFFEN70A/jxb2svrWsN3aDL7OUtmvlOy+6fa2jxG8K0wQ1ZbdeLGnidov6Yu5/733dI5ySfzFlQ/cb0bSz1g==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [arm64]
os: [win32]
- '@rolldown/binding-win32-x64-msvc@1.2.16':
- resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==}
+ '@rolldown/binding-win32-x64-msvc@1.0.3':
+ resolution: {integrity: sha512-eXB7CHuaQdqmJcc3koCNtNPmT/bj2gc999kUFgBxG8Ac0NdgXc4rkCHhqrgrhN3zddvvvrgzj1e90SuSfmyIXA==}
engines: {node: ^20.19.0 || >=22.12.0}
cpu: [x64]
os: [win32]
@@ -924,6 +927,9 @@ packages:
resolution: {integrity: sha512-V/1hRKLSCJ0zEL+9QFRBUtivvePfOsaAYQmC0HhFNSHC2F3xFs4jSF3YhkLmzex6E4V4FGvmBDOP72D/53NnZA==}
engines: {node: '>=20.0.0'}
+ '@tybys/wasm-util@0.10.2':
+ resolution: {integrity: sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==}
+
'@types/chai@5.2.3':
resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==}
@@ -986,7 +992,7 @@ packages:
resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==}
peerDependencies:
msw: ^2.4.9
- vite: ^8.1.6
+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0
peerDependenciesMeta:
msw:
optional: true
@@ -1060,8 +1066,8 @@ packages:
asynckit@0.4.0:
resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}
- axios@1.20.0:
- resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==}
+ axios@1.18.1:
+ resolution: {integrity: sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==}
balanced-match@4.0.4:
resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
@@ -1223,8 +1229,8 @@ packages:
resolution: {integrity: sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==}
engines: {node: '>=18'}
- default-browser@5.5.1:
- resolution: {integrity: sha512-m1pAzaJgZ/gssEqlOhJkPJp8Xly7QyW6xcrkUa2KKcDeDSEMP7X8xipU3snUcfisTQx0w1AGae+9UtJSfVnXGw==}
+ default-browser@5.5.0:
+ resolution: {integrity: sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw==}
engines: {node: '>=18'}
define-lazy-prop@3.0.0:
@@ -1355,8 +1361,8 @@ packages:
fix-dts-default-cjs-exports@1.0.1:
resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==}
- follow-redirects@1.16.2:
- resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==}
+ follow-redirects@1.16.0:
+ resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==}
engines: {node: '>=4.0'}
peerDependencies:
debug: '*'
@@ -1502,10 +1508,6 @@ packages:
engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0}
hasBin: true
- is-in-ssh@1.0.0:
- resolution: {integrity: sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw==}
- engines: {node: '>=20'}
-
is-inside-container@1.0.0:
resolution: {integrity: sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==}
engines: {node: '>=14.16'}
@@ -1597,78 +1599,78 @@ packages:
ws:
optional: true
- lightningcss-android-arm64@1.33.0:
- resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==}
+ lightningcss-android-arm64@1.32.0:
+ resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [android]
- lightningcss-darwin-arm64@1.33.0:
- resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==}
+ lightningcss-darwin-arm64@1.32.0:
+ resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [darwin]
- lightningcss-darwin-x64@1.33.0:
- resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==}
+ lightningcss-darwin-x64@1.32.0:
+ resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [darwin]
- lightningcss-freebsd-x64@1.33.0:
- resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==}
+ lightningcss-freebsd-x64@1.32.0:
+ resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [freebsd]
- lightningcss-linux-arm-gnueabihf@1.33.0:
- resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==}
+ lightningcss-linux-arm-gnueabihf@1.32.0:
+ resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==}
engines: {node: '>= 12.0.0'}
cpu: [arm]
os: [linux]
- lightningcss-linux-arm64-gnu@1.33.0:
- resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==}
+ lightningcss-linux-arm64-gnu@1.32.0:
+ resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [glibc]
- lightningcss-linux-arm64-musl@1.33.0:
- resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==}
+ lightningcss-linux-arm64-musl@1.32.0:
+ resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [linux]
libc: [musl]
- lightningcss-linux-x64-gnu@1.33.0:
- resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==}
+ lightningcss-linux-x64-gnu@1.32.0:
+ resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [glibc]
- lightningcss-linux-x64-musl@1.33.0:
- resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==}
+ lightningcss-linux-x64-musl@1.32.0:
+ resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [linux]
libc: [musl]
- lightningcss-win32-arm64-msvc@1.33.0:
- resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==}
+ lightningcss-win32-arm64-msvc@1.32.0:
+ resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==}
engines: {node: '>= 12.0.0'}
cpu: [arm64]
os: [win32]
- lightningcss-win32-x64-msvc@1.33.0:
- resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==}
+ lightningcss-win32-x64-msvc@1.32.0:
+ resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==}
engines: {node: '>= 12.0.0'}
cpu: [x64]
os: [win32]
- lightningcss@1.33.0:
- resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==}
+ lightningcss@1.32.0:
+ resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==}
engines: {node: '>= 12.0.0'}
lilconfig@3.1.3:
@@ -1730,7 +1732,7 @@ packages:
engines: {node: '>=18'}
peerDependencies:
'@anthropic-ai/sdk': ^0.40.1
- '@azure/identity': '>=4.14.1 <5.0.0'
+ '@azure/identity': ^4.0.0
'@azure/search-documents': ^12.0.0
'@cloudflare/workers-types': ^4.20250504.0
'@google/genai': ^1.40.0
@@ -1842,8 +1844,8 @@ packages:
mz@2.7.0:
resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==}
- nanoid@3.3.20:
- resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}
+ nanoid@3.3.16:
+ resolution: {integrity: sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
@@ -1893,9 +1895,9 @@ packages:
once@1.4.0:
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
- open@11.0.4:
- resolution: {integrity: sha512-++Zlftm0kVLPmzC06t6epuWmcRMDbI4z5P3NNX979WA/k23+NtSOynEGzsVfZwguKw2mi5umVgnBlJQMwRz4Pg==}
- engines: {node: '>=20'}
+ open@10.2.0:
+ resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==}
+ engines: {node: '>=18'}
openai@4.104.0:
resolution: {integrity: sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==}
@@ -2020,10 +2022,6 @@ packages:
resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==}
engines: {node: '>=12'}
- picomatch@4.0.7:
- resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}
- engines: {node: '>=12'}
-
pirates@4.0.7:
resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==}
engines: {node: '>= 6'}
@@ -2049,8 +2047,8 @@ packages:
yaml:
optional: true
- postcss@8.5.32:
- resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==}
+ postcss@8.5.23:
+ resolution: {integrity: sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==}
engines: {node: ^10 || ^12 || >=14}
postgres-array@2.0.0:
@@ -2088,10 +2086,6 @@ packages:
postgres-range@1.1.4:
resolution: {integrity: sha512-i/hbxIE9803Alj/6ytL7UHQxRvZkI9O4Sy+J3HGc4F4oo/2eQAjTSNJ0bfxyse3bH0nuVesCk+3IRLaMtG3H6w==}
- powershell-utils@0.2.1:
- resolution: {integrity: sha512-C+y9x90UElAddDZmV4qOx9W53B61PO7cIqWz2dQsWlwswuq4mr8NEwytdGKboYbQlGZ3awrkTeNvcZiZNHnQ8A==}
- engines: {node: '>=20'}
-
prebuild-install@7.1.3:
resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==}
engines: {node: '>=10'}
@@ -2151,8 +2145,8 @@ packages:
resolution: {integrity: sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==}
engines: {node: '>= 4'}
- rolldown@1.2.16:
- resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==}
+ rolldown@1.0.3:
+ resolution: {integrity: sha512-i00lAJ2ks1BYr7rjNjKC7BcqAS7nVfiT3QX1SI5aY+AFHblCmaUf9OE9dbdzDvW6dJxbi2ZCZiy9v3CcwOiX3g==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
@@ -2204,8 +2198,8 @@ packages:
resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==}
engines: {node: '>=8'}
- source-map-js@1.2.2:
- resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}
+ source-map-js@1.2.1:
+ resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==}
engines: {node: '>=0.10.0'}
source-map@0.7.6:
@@ -2360,12 +2354,12 @@ packages:
undici-types@7.24.6:
resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}
- undici@7.30.2:
- resolution: {integrity: sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==}
+ undici@7.29.0:
+ resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==}
engines: {node: '>=20.18.1'}
- undici@8.12.4:
- resolution: {integrity: sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==}
+ undici@8.10.0:
+ resolution: {integrity: sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ==}
engines: {node: '>=22.19.0'}
util-deprecate@1.0.2:
@@ -2379,13 +2373,13 @@ packages:
resolution: {integrity: sha512-Qo+uWgilfSmAhXCMav1uYFynlQO7fMFiMVZsQqZRMIXp0O7rR7qjkj+cPvBHLgBqi960QCoo/PH2/6ZtVqKvrg==}
hasBin: true
- vite@8.3.6:
- resolution: {integrity: sha512-UI7dK29NnS54Fk+mmo7o+jI6U8Fp7hDl+X5Q1k45WH+d4dSlbLVUETGQ+hfkNgvLQGyoElPj837nZyv4MBc0VA==}
+ vite@8.0.16:
+ resolution: {integrity: sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==}
engines: {node: ^20.19.0 || >=22.12.0}
hasBin: true
peerDependencies:
'@types/node': ^20.19.0 || >=22.12.0
- '@vitejs/devtools': ^0.7.1 || ^0.8.0
+ '@vitejs/devtools': ^0.1.18
esbuild: '>=0.28.1'
jiti: '>=1.21.0'
less: ^4.0.0
@@ -2438,7 +2432,7 @@ packages:
'@vitest/ui': 4.1.11
happy-dom: '*'
jsdom: '*'
- vite: ^8.1.6
+ vite: ^6.0.0 || ^7.0.0 || ^8.0.0
peerDependenciesMeta:
'@edge-runtime/vm':
optional: true
@@ -2517,9 +2511,9 @@ packages:
utf-8-validate:
optional: true
- wsl-utils@1.0.1:
- resolution: {integrity: sha512-c16PKLIRxBYpR3jSWsdS7SFp0COm5SOQdiFjY818dYFHJbMGuLBszpF07LBWmOS1uzrHa9VGdynsEgoeKy0oOQ==}
- engines: {node: '>=20'}
+ wsl-utils@0.1.0:
+ resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==}
+ engines: {node: '>=18'}
xml-naming@0.1.0:
resolution: {integrity: sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==}
@@ -2810,8 +2804,6 @@ snapshots:
dependencies:
tslib: 2.8.1
- '@azure/core-process@1.0.0': {}
-
'@azure/core-rest-pipeline@1.24.0':
dependencies:
'@azure/abort-controller': 2.1.2
@@ -2836,19 +2828,18 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@azure/identity@4.14.1':
+ '@azure/identity@4.13.1':
dependencies:
'@azure/abort-controller': 2.1.2
'@azure/core-auth': 1.10.1
'@azure/core-client': 1.10.2
- '@azure/core-process': 1.0.0
'@azure/core-rest-pipeline': 1.24.0
'@azure/core-tracing': 1.3.1
'@azure/core-util': 1.13.1
'@azure/logger': 1.3.0
'@azure/msal-browser': 5.12.0
- '@azure/msal-node': 7.2.0
- open: 11.0.4
+ '@azure/msal-node': 5.2.3
+ open: 10.2.0
tslib: 2.8.1
transitivePeerDependencies:
- supports-color
@@ -2864,13 +2855,11 @@ snapshots:
dependencies:
'@azure/msal-common': 16.7.0
- '@azure/msal-common@16.16.0': {}
-
'@azure/msal-common@16.7.0': {}
- '@azure/msal-node@7.2.0':
+ '@azure/msal-node@5.2.3':
dependencies:
- '@azure/msal-common': 16.16.0
+ '@azure/msal-common': 16.7.0
jsonwebtoken: 9.0.3
'@azure/search-documents@12.2.0':
@@ -2953,7 +2942,7 @@ snapshots:
minimatch: 10.2.5
proper-lockfile: 4.1.2
typebox: 1.1.38
- undici: 8.12.4
+ undici: 8.10.0
yaml: 2.9.0
optionalDependencies:
'@mariozechner/clipboard': 0.3.9
@@ -2970,6 +2959,22 @@ snapshots:
get-east-asian-width: 1.6.0
marked: 15.0.12
+ '@emnapi/core@1.10.0':
+ dependencies:
+ '@emnapi/wasi-threads': 1.2.1
+ tslib: 2.8.1
+ optional: true
+
+ '@emnapi/runtime@1.10.0':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
+ '@emnapi/wasi-threads@1.2.1':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
'@esbuild/aix-ppc64@0.28.1':
optional: true
@@ -3163,9 +3168,16 @@ snapshots:
dependencies:
sparse-bitfield: 3.0.3
+ '@napi-rs/wasm-runtime@1.1.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)':
+ dependencies:
+ '@emnapi/core': 1.10.0
+ '@emnapi/runtime': 1.10.0
+ '@tybys/wasm-util': 0.10.2
+ optional: true
+
'@nodable/entities@2.1.1': {}
- '@oxc-project/types@0.156.0': {}
+ '@oxc-project/types@0.133.0': {}
'@protobufjs/aspromise@1.1.2': {}
@@ -3191,7 +3203,7 @@ snapshots:
dependencies:
'@qdrant/openapi-typescript-fetch': 1.2.6
typescript: 6.0.3
- undici: 7.30.2
+ undici: 7.29.0
'@qdrant/openapi-typescript-fetch@1.2.6': {}
@@ -3215,49 +3227,53 @@ snapshots:
dependencies:
'@redis/client': 5.12.1
- '@rolldown/binding-android-arm-eabi@1.2.16':
+ '@rolldown/binding-android-arm64@1.0.3':
optional: true
- '@rolldown/binding-android-arm64@1.2.16':
+ '@rolldown/binding-darwin-arm64@1.0.3':
optional: true
- '@rolldown/binding-darwin-arm64@1.2.16':
+ '@rolldown/binding-darwin-x64@1.0.3':
optional: true
- '@rolldown/binding-darwin-x64@1.2.16':
+ '@rolldown/binding-freebsd-x64@1.0.3':
optional: true
- '@rolldown/binding-freebsd-x64@1.2.16':
+ '@rolldown/binding-linux-arm-gnueabihf@1.0.3':
optional: true
- '@rolldown/binding-linux-arm-gnueabihf@1.2.16':
+ '@rolldown/binding-linux-arm64-gnu@1.0.3':
optional: true
- '@rolldown/binding-linux-arm64-gnu@1.2.16':
+ '@rolldown/binding-linux-arm64-musl@1.0.3':
optional: true
- '@rolldown/binding-linux-arm64-musl@1.2.16':
+ '@rolldown/binding-linux-ppc64-gnu@1.0.3':
optional: true
- '@rolldown/binding-linux-ppc64-gnu@1.2.16':
+ '@rolldown/binding-linux-s390x-gnu@1.0.3':
optional: true
- '@rolldown/binding-linux-s390x-gnu@1.2.16':
+ '@rolldown/binding-linux-x64-gnu@1.0.3':
optional: true
- '@rolldown/binding-linux-x64-gnu@1.2.16':
+ '@rolldown/binding-linux-x64-musl@1.0.3':
optional: true
- '@rolldown/binding-linux-x64-musl@1.2.16':
+ '@rolldown/binding-openharmony-arm64@1.0.3':
optional: true
- '@rolldown/binding-openharmony-arm64@1.2.16':
+ '@rolldown/binding-wasm32-wasi@1.0.3':
+ dependencies:
+ '@emnapi/core': 1.10.0
+ '@emnapi/runtime': 1.10.0
+ '@napi-rs/wasm-runtime': 1.1.5(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)
optional: true
- '@rolldown/binding-win32-arm64-msvc@1.2.16':
+ '@rolldown/binding-win32-arm64-msvc@1.0.3':
optional: true
- '@rolldown/binding-win32-x64-msvc@1.2.16':
+ '@rolldown/binding-win32-x64-msvc@1.0.3':
optional: true
'@rolldown/pluginutils@1.0.1': {}
@@ -3429,6 +3445,11 @@ snapshots:
'@supabase/realtime-js': 2.108.1
'@supabase/storage-js': 2.108.1
+ '@tybys/wasm-util@0.10.2':
+ dependencies:
+ tslib: 2.8.1
+ optional: true
+
'@types/chai@5.2.3':
dependencies:
'@types/deep-eql': 4.0.2
@@ -3505,13 +3526,13 @@ snapshots:
chai: 6.2.2
tinyrainbow: 3.1.0
- '@vitest/mocker@4.1.11(vite@8.3.6(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0))':
+ '@vitest/mocker@4.1.11(vite@8.0.16(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0))':
dependencies:
'@vitest/spy': 4.1.11
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
- vite: 8.3.6(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0)
+ vite: 8.0.16(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0)
'@vitest/pretty-format@4.1.11':
dependencies:
@@ -3577,9 +3598,9 @@ snapshots:
asynckit@0.4.0: {}
- axios@1.20.0:
+ axios@1.18.1:
dependencies:
- follow-redirects: 1.16.2
+ follow-redirects: 1.16.0
form-data: 4.0.6
https-proxy-agent: 5.0.1
proxy-from-env: 2.1.0
@@ -3726,7 +3747,7 @@ snapshots:
default-browser-id@5.0.1: {}
- default-browser@5.5.1:
+ default-browser@5.5.0:
dependencies:
bundle-name: 4.1.0
default-browser-id: 5.0.1
@@ -3869,7 +3890,7 @@ snapshots:
mlly: 1.8.2
rollup: 4.61.1
- follow-redirects@1.16.2: {}
+ follow-redirects@1.16.0: {}
form-data-encoder@1.7.2: {}
@@ -4031,8 +4052,6 @@ snapshots:
is-docker@3.0.0: {}
- is-in-ssh@1.0.0: {}
-
is-inside-container@1.0.0:
dependencies:
is-docker: 3.0.0
@@ -4134,54 +4153,54 @@ snapshots:
openai: 6.26.0(ws@8.21.0)(zod@3.25.76)
ws: 8.21.0
- lightningcss-android-arm64@1.33.0:
+ lightningcss-android-arm64@1.32.0:
optional: true
- lightningcss-darwin-arm64@1.33.0:
+ lightningcss-darwin-arm64@1.32.0:
optional: true
- lightningcss-darwin-x64@1.33.0:
+ lightningcss-darwin-x64@1.32.0:
optional: true
- lightningcss-freebsd-x64@1.33.0:
+ lightningcss-freebsd-x64@1.32.0:
optional: true
- lightningcss-linux-arm-gnueabihf@1.33.0:
+ lightningcss-linux-arm-gnueabihf@1.32.0:
optional: true
- lightningcss-linux-arm64-gnu@1.33.0:
+ lightningcss-linux-arm64-gnu@1.32.0:
optional: true
- lightningcss-linux-arm64-musl@1.33.0:
+ lightningcss-linux-arm64-musl@1.32.0:
optional: true
- lightningcss-linux-x64-gnu@1.33.0:
+ lightningcss-linux-x64-gnu@1.32.0:
optional: true
- lightningcss-linux-x64-musl@1.33.0:
+ lightningcss-linux-x64-musl@1.32.0:
optional: true
- lightningcss-win32-arm64-msvc@1.33.0:
+ lightningcss-win32-arm64-msvc@1.32.0:
optional: true
- lightningcss-win32-x64-msvc@1.33.0:
+ lightningcss-win32-x64-msvc@1.32.0:
optional: true
- lightningcss@1.33.0:
+ lightningcss@1.32.0:
dependencies:
detect-libc: 2.1.2
optionalDependencies:
- lightningcss-android-arm64: 1.33.0
- lightningcss-darwin-arm64: 1.33.0
- lightningcss-darwin-x64: 1.33.0
- lightningcss-freebsd-x64: 1.33.0
- lightningcss-linux-arm-gnueabihf: 1.33.0
- lightningcss-linux-arm64-gnu: 1.33.0
- lightningcss-linux-arm64-musl: 1.33.0
- lightningcss-linux-x64-gnu: 1.33.0
- lightningcss-linux-x64-musl: 1.33.0
- lightningcss-win32-arm64-msvc: 1.33.0
- lightningcss-win32-x64-msvc: 1.33.0
+ lightningcss-android-arm64: 1.32.0
+ lightningcss-darwin-arm64: 1.32.0
+ lightningcss-darwin-x64: 1.32.0
+ lightningcss-freebsd-x64: 1.32.0
+ lightningcss-linux-arm-gnueabihf: 1.32.0
+ lightningcss-linux-arm64-gnu: 1.32.0
+ lightningcss-linux-arm64-musl: 1.32.0
+ lightningcss-linux-x64-gnu: 1.32.0
+ lightningcss-linux-x64-musl: 1.32.0
+ lightningcss-win32-arm64-msvc: 1.32.0
+ lightningcss-win32-x64-msvc: 1.32.0
lilconfig@3.1.3: {}
@@ -4221,10 +4240,10 @@ snapshots:
crypt: 0.0.2
is-buffer: 1.1.6
- mem0ai@3.0.7(@anthropic-ai/sdk@0.91.1(zod@3.25.76))(@azure/identity@4.14.1)(@azure/search-documents@12.2.0)(@cloudflare/workers-types@4.20260610.1)(@google/genai@1.52.0)(@langchain/core@1.1.48(openai@6.26.0(ws@8.21.0)(zod@3.25.76))(ws@8.21.0))(@mistralai/mistralai@2.2.1)(@qdrant/js-client-rest@1.18.0(typescript@6.0.3))(@supabase/supabase-js@2.108.1)(@types/jest@29.5.14)(@types/pg@8.11.0)(better-sqlite3@12.10.0)(cloudflare@4.5.0)(compromise@14.15.1)(groq-sdk@0.3.0)(natural@8.1.1)(ollama@0.5.18)(pg@8.11.3)(redis@5.12.1)(ws@8.21.0):
+ mem0ai@3.0.7(@anthropic-ai/sdk@0.91.1(zod@3.25.76))(@azure/identity@4.13.1)(@azure/search-documents@12.2.0)(@cloudflare/workers-types@4.20260610.1)(@google/genai@1.52.0)(@langchain/core@1.1.48(openai@6.26.0(ws@8.21.0)(zod@3.25.76))(ws@8.21.0))(@mistralai/mistralai@2.2.1)(@qdrant/js-client-rest@1.18.0(typescript@6.0.3))(@supabase/supabase-js@2.108.1)(@types/jest@29.5.14)(@types/pg@8.11.0)(better-sqlite3@12.10.0)(cloudflare@4.5.0)(compromise@14.15.1)(groq-sdk@0.3.0)(natural@8.1.1)(ollama@0.5.18)(pg@8.11.3)(redis@5.12.1)(ws@8.21.0):
dependencies:
'@anthropic-ai/sdk': 0.91.1(zod@3.25.76)
- '@azure/identity': 4.14.1
+ '@azure/identity': 4.13.1
'@azure/search-documents': 12.2.0
'@cloudflare/workers-types': 4.20260610.1
'@google/genai': 1.52.0
@@ -4234,7 +4253,7 @@ snapshots:
'@supabase/supabase-js': 2.108.1
'@types/jest': 29.5.14
'@types/pg': 8.11.0
- axios: 1.20.0
+ axios: 1.18.1
better-sqlite3: 12.10.0
cloudflare: 4.5.0
compromise: 14.15.1
@@ -4329,7 +4348,7 @@ snapshots:
object-assign: 4.1.1
thenify-all: 1.6.0
- nanoid@3.3.20: {}
+ nanoid@3.3.16: {}
napi-build-utils@2.0.0: {}
@@ -4391,14 +4410,12 @@ snapshots:
dependencies:
wrappy: 1.0.2
- open@11.0.4:
+ open@10.2.0:
dependencies:
- default-browser: 5.5.1
+ default-browser: 5.5.0
define-lazy-prop: 3.0.0
- is-in-ssh: 1.0.0
is-inside-container: 1.0.0
- powershell-utils: 0.2.1
- wsl-utils: 1.0.1
+ wsl-utils: 0.1.0
openai@4.104.0(ws@8.21.0)(zod@3.25.76):
dependencies:
@@ -4520,8 +4537,6 @@ snapshots:
picomatch@4.0.4: {}
- picomatch@4.0.7: {}
-
pirates@4.0.7: {}
pkg-types@1.3.1:
@@ -4530,19 +4545,19 @@ snapshots:
mlly: 1.8.2
pathe: 2.0.3
- postcss-load-config@6.0.1(jiti@2.7.0)(postcss@8.5.32)(yaml@2.9.0):
+ postcss-load-config@6.0.1(jiti@2.7.0)(postcss@8.5.23)(yaml@2.9.0):
dependencies:
lilconfig: 3.1.3
optionalDependencies:
jiti: 2.7.0
- postcss: 8.5.32
+ postcss: 8.5.23
yaml: 2.9.0
- postcss@8.5.32:
+ postcss@8.5.23:
dependencies:
- nanoid: 3.3.20
+ nanoid: 3.3.16
picocolors: 1.1.1
- source-map-js: 1.2.2
+ source-map-js: 1.2.1
postgres-array@2.0.0: {}
@@ -4566,8 +4581,6 @@ snapshots:
postgres-range@1.1.4: {}
- powershell-utils@0.2.1: {}
-
prebuild-install@7.1.3:
dependencies:
detect-libc: 2.1.2
@@ -4652,26 +4665,26 @@ snapshots:
retry@0.13.1: {}
- rolldown@1.2.16:
+ rolldown@1.0.3:
dependencies:
- '@oxc-project/types': 0.156.0
+ '@oxc-project/types': 0.133.0
'@rolldown/pluginutils': 1.0.1
optionalDependencies:
- '@rolldown/binding-android-arm-eabi': 1.2.16
- '@rolldown/binding-android-arm64': 1.2.16
- '@rolldown/binding-darwin-arm64': 1.2.16
- '@rolldown/binding-darwin-x64': 1.2.16
- '@rolldown/binding-freebsd-x64': 1.2.16
- '@rolldown/binding-linux-arm-gnueabihf': 1.2.16
- '@rolldown/binding-linux-arm64-gnu': 1.2.16
- '@rolldown/binding-linux-arm64-musl': 1.2.16
- '@rolldown/binding-linux-ppc64-gnu': 1.2.16
- '@rolldown/binding-linux-s390x-gnu': 1.2.16
- '@rolldown/binding-linux-x64-gnu': 1.2.16
- '@rolldown/binding-linux-x64-musl': 1.2.16
- '@rolldown/binding-openharmony-arm64': 1.2.16
- '@rolldown/binding-win32-arm64-msvc': 1.2.16
- '@rolldown/binding-win32-x64-msvc': 1.2.16
+ '@rolldown/binding-android-arm64': 1.0.3
+ '@rolldown/binding-darwin-arm64': 1.0.3
+ '@rolldown/binding-darwin-x64': 1.0.3
+ '@rolldown/binding-freebsd-x64': 1.0.3
+ '@rolldown/binding-linux-arm-gnueabihf': 1.0.3
+ '@rolldown/binding-linux-arm64-gnu': 1.0.3
+ '@rolldown/binding-linux-arm64-musl': 1.0.3
+ '@rolldown/binding-linux-ppc64-gnu': 1.0.3
+ '@rolldown/binding-linux-s390x-gnu': 1.0.3
+ '@rolldown/binding-linux-x64-gnu': 1.0.3
+ '@rolldown/binding-linux-x64-musl': 1.0.3
+ '@rolldown/binding-openharmony-arm64': 1.0.3
+ '@rolldown/binding-wasm32-wasi': 1.0.3
+ '@rolldown/binding-win32-arm64-msvc': 1.0.3
+ '@rolldown/binding-win32-x64-msvc': 1.0.3
rollup@4.61.1:
dependencies:
@@ -4734,7 +4747,7 @@ snapshots:
slash@3.0.0: {}
- source-map-js@1.2.2: {}
+ source-map-js@1.2.1: {}
source-map@0.7.6: {}
@@ -4836,7 +4849,7 @@ snapshots:
tslib@2.8.1: {}
- tsup@8.5.1(jiti@2.7.0)(postcss@8.5.32)(typescript@6.0.3)(yaml@2.9.0):
+ tsup@8.5.1(jiti@2.7.0)(postcss@8.5.23)(typescript@6.0.3)(yaml@2.9.0):
dependencies:
bundle-require: 5.1.0(esbuild@0.28.1)
cac: 6.7.14
@@ -4847,7 +4860,7 @@ snapshots:
fix-dts-default-cjs-exports: 1.0.1
joycon: 3.1.1
picocolors: 1.1.1
- postcss-load-config: 6.0.1(jiti@2.7.0)(postcss@8.5.32)(yaml@2.9.0)
+ postcss-load-config: 6.0.1(jiti@2.7.0)(postcss@8.5.23)(yaml@2.9.0)
resolve-from: 5.0.0
rollup: 4.61.1
source-map: 0.7.6
@@ -4856,7 +4869,7 @@ snapshots:
tinyglobby: 0.2.17
tree-kill: 1.2.2
optionalDependencies:
- postcss: 8.5.32
+ postcss: 8.5.23
typescript: 6.0.3
transitivePeerDependencies:
- jiti
@@ -4882,9 +4895,9 @@ snapshots:
undici-types@7.24.6: {}
- undici@7.30.2: {}
+ undici@7.29.0: {}
- undici@8.12.4: {}
+ undici@8.10.0: {}
util-deprecate@1.0.2: {}
@@ -4892,12 +4905,12 @@ snapshots:
uuid@14.0.0: {}
- vite@8.3.6(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0):
+ vite@8.0.16(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0):
dependencies:
- lightningcss: 1.33.0
- picomatch: 4.0.7
- postcss: 8.5.32
- rolldown: 1.2.16
+ lightningcss: 1.32.0
+ picomatch: 4.0.4
+ postcss: 8.5.23
+ rolldown: 1.0.3
tinyglobby: 0.2.17
optionalDependencies:
'@types/node': 25.9.2
@@ -4906,10 +4919,10 @@ snapshots:
jiti: 2.7.0
yaml: 2.9.0
- vitest@4.1.11(@types/node@25.9.2)(vite@8.3.6(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0)):
+ vitest@4.1.11(@types/node@25.9.2)(vite@8.0.16(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0)):
dependencies:
'@vitest/expect': 4.1.11
- '@vitest/mocker': 4.1.11(vite@8.3.6(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0))
+ '@vitest/mocker': 4.1.11(vite@8.0.16(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0))
'@vitest/pretty-format': 4.1.11
'@vitest/runner': 4.1.11
'@vitest/snapshot': 4.1.11
@@ -4926,7 +4939,7 @@ snapshots:
tinyexec: 1.2.4
tinyglobby: 0.2.17
tinyrainbow: 3.1.0
- vite: 8.3.6(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0)
+ vite: 8.0.16(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0)
why-is-node-running: 2.3.0
optionalDependencies:
'@types/node': 25.9.2
@@ -4968,10 +4981,9 @@ snapshots:
ws@8.21.0: {}
- wsl-utils@1.0.1:
+ wsl-utils@0.1.0:
dependencies:
is-wsl: 3.1.1
- powershell-utils: 0.2.1
xml-naming@0.1.0: {}
diff --git a/integrations/pi-agent-plugin/pnpm-workspace.yaml b/integrations/pi-agent-plugin/pnpm-workspace.yaml
index 9e9b6e4ba..283b117cc 100644
--- a/integrations/pi-agent-plugin/pnpm-workspace.yaml
+++ b/integrations/pi-agent-plugin/pnpm-workspace.yaml
@@ -2,16 +2,13 @@ packages:
- '.'
overrides:
- "@azure/identity@<4.14.1": ">=4.14.1 <5.0.0"
"form-data@<4.0.6": ">=4.0.6"
"uuid@<11.1.1": ">=11.1.1"
"esbuild": ">=0.28.1"
- "undici@<7.30.1": ">=7.30.1 <8.0.0"
- "undici@>=8.0.0 <8.12.2": ">=8.12.2 <9.0.0"
- "axios@<1.20.0": ">=1.20.0 <2.0.0"
+ "undici@<7.29.0": ">=7.29.0 <8.0.0"
+ "undici@>=8.0.0 <8.9.0": ">=8.9.0 <9.0.0"
+ "axios@<1.18.0": ">=1.18.0 <2.0.0"
"brace-expansion@>=3.0.0 <5.0.8": ">=5.0.8 <6.0.0"
"postcss@<8.5.18": ">=8.5.18 <9.0.0"
"mongoose@>=9.0.0 <9.7.2": ">=9.7.2 <10.0.0"
"protobufjs@<7.6.5": ">=7.6.5 <8.0.0"
- "follow-redirects@<1.16.2": ">=1.16.2 <2.0.0"
- "vite": "^8.1.6"
diff --git a/integrations/pi-agent-plugin/skills/context-loader/SKILL.md b/integrations/pi-agent-plugin/skills/context-loader/SKILL.md
index 616de9d02..22c10b2c8 100644
--- a/integrations/pi-agent-plugin/skills/context-loader/SKILL.md
+++ b/integrations/pi-agent-plugin/skills/context-loader/SKILL.md
@@ -1,19 +1,34 @@
---
name: context-loader
-description: Search memories from earlier Pi sessions in this repository. Use it when earlier work may already explain the code, error, decision, or command you need, so you can avoid repeating file reads, searches, or experiments.
+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. **Call `mem0_memory` once** with `action="search"` and a focused question about the task.
+2. **Run 2-4 parallel searches** using `mem0_memory` tool with `action="search"` and different query angles:
-3. **Output compact context block** (max 10 memories):
+ | 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 memories for ""
@@ -22,7 +37,7 @@ context-loader: loaded memories for ""
- [lessons] [mem0:]
```
-4. If **zero results**: output nothing. Don't announce empty context.
+5. If **zero results**: output nothing. Don't announce empty context.
## Constraints
diff --git a/integrations/pi-agent-plugin/src/attribution.test.ts b/integrations/pi-agent-plugin/src/attribution.test.ts
deleted file mode 100644
index f90d28da3..000000000
--- a/integrations/pi-agent-plugin/src/attribution.test.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { applySurfaceHeaders, PLATFORM_APPLICATION, PLATFORM_SOURCE } from "./attribution.ts";
-
-function client(headers: Record = {}) {
- return { headers: { Authorization: "Token k", ...headers } } as never;
-}
-
-describe("applySurfaceHeaders", () => {
- it("stamps the shared client so every path is attributed, not just commands", () => {
- const mem0 = client();
- applySurfaceHeaders(mem0);
- const headers = (mem0 as unknown as { headers: Record }).headers;
-
- expect(headers["X-Mem0-Source"]).toBe(PLATFORM_SOURCE);
- expect(headers["X-Application"]).toBe(PLATFORM_APPLICATION);
- expect(headers["X-Mem0-Client"]).toMatch(/^mem0-pi-agent\//);
- expect(headers.Authorization).toBe("Token k");
- });
-
- it("defers to a surface an outer wrapper already declared", () => {
- const mem0 = client({ "X-Mem0-Source": "OPENCLAW", "X-Application": "vscode" });
- applySurfaceHeaders(mem0);
- const headers = (mem0 as unknown as { headers: Record }).headers;
-
- expect(headers["X-Mem0-Source"]).toBe("OPENCLAW");
- expect(headers["X-Application"]).toBe("vscode");
- });
-
- it("appends to the client stack rather than replacing it", () => {
- const mem0 = client({ "X-Mem0-Client": "openclaw/2.1.0" });
- applySurfaceHeaders(mem0);
- const headers = (mem0 as unknown as { headers: Record }).headers;
-
- expect(headers["X-Mem0-Client"]).toMatch(/^openclaw\/2\.1\.0, mem0-pi-agent\//);
- });
-
- it("treats a blank header as absent", () => {
- const mem0 = client({ "X-Mem0-Source": " " });
- applySurfaceHeaders(mem0);
- const headers = (mem0 as unknown as { headers: Record }).headers;
-
- expect(headers["X-Mem0-Source"]).toBe(PLATFORM_SOURCE);
- });
-
- it("bounds the stack so a long chain cannot grow the header without limit", () => {
- const mem0 = client({ "X-Mem0-Client": "a/1, b/1, c/1, d/1, e/1" });
- applySurfaceHeaders(mem0);
- const headers = (mem0 as unknown as { headers: Record }).headers;
-
- expect(headers["X-Mem0-Client"].split(",").length).toBeLessThanOrEqual(4);
- expect(headers["X-Mem0-Client"].length).toBeLessThanOrEqual(200);
- });
-});
-
-describe("client stack bounding", () => {
- it("keeps our own entry when the caller already filled the stack", () => {
- // The defect: pushing then trimming to four dropped exactly the entry this
- // function exists to add, so we vanished from our own stack.
- const mem0 = client({ "X-Mem0-Client": "a/1, b/2, c/3, d/4" });
- applySurfaceHeaders(mem0);
- const stack = (mem0 as unknown as { headers: Record }).headers["X-Mem0-Client"];
-
- expect(stack).toMatch(/mem0-pi-agent\//);
- expect(stack.split(",").length).toBeLessThanOrEqual(4);
- });
-
- it("drops whole entries at the character cap, never a fragment", () => {
- const long = `${"n".repeat(90)}/1.0, ${"m".repeat(90)}/1.0, ${"o".repeat(90)}/1.0`;
- const mem0 = client({ "X-Mem0-Client": long });
- applySurfaceHeaders(mem0);
- const stack = (mem0 as unknown as { headers: Record }).headers["X-Mem0-Client"];
-
- expect(stack.length).toBeLessThanOrEqual(200);
- expect(stack.endsWith("/0.0.0") || /mem0-pi-agent\/[\w.\-]+$/.test(stack)).toBe(true);
- // Every surviving entry is whole: name/version, no severed tail.
- for (const entry of stack.split(",")) {
- expect(entry.trim()).toMatch(/^[^/]+\/[^/]+$/);
- }
- });
-});
diff --git a/integrations/pi-agent-plugin/src/attribution.ts b/integrations/pi-agent-plugin/src/attribution.ts
deleted file mode 100644
index 2cbc9a73e..000000000
--- a/integrations/pi-agent-plugin/src/attribution.ts
+++ /dev/null
@@ -1,65 +0,0 @@
-import type MemoryClient from "mem0ai";
-import * as fs from "node:fs";
-
-/** Surface identity for this plugin, as the platform's EventSource knows it. */
-export const PLATFORM_SOURCE = "PI_AGENT";
-
-/** Host app the plugin runs inside. Allowlisted server-side. */
-export const PLATFORM_APPLICATION = "pi";
-
-const PLUGIN_VERSION = (() => {
- try {
- return JSON.parse(
- fs.readFileSync(new URL("../package.json", import.meta.url), "utf-8"),
- ).version as string;
- } catch {
- return "unknown";
- }
-})();
-
-const MAX_STACK_ENTRIES = 4;
-const MAX_STACK_CHARS = 200;
-
-/**
- * Append our own entry and bound the result, dropping WHOLE entries.
- *
- * Neither cap cuts characters: slicing the joined string severs an identifier
- * and leaves a fragment the platform parses as a real client name. And the
- * reserved slot is ours, since it is the only entry this layer can vouch for.
- */
-function boundedStack(callerEntries: string[], own: string): string {
- const kept: string[] = [];
- let budget = MAX_STACK_CHARS - own.length;
- for (const entry of callerEntries.slice(0, MAX_STACK_ENTRIES - 1)) {
- const cost = entry.length + ", ".length;
- if (cost > budget) break;
- budget -= cost;
- kept.push(entry);
- }
- return [...kept, own].join(", ");
-}
-
-/**
- * Stamp surface identity onto the shared client, once, at construction.
- *
- * Tagging individual call sites was not enough: automatic recall, capture, the
- * memory tools and deletion all go through this same client, so everything
- * except the explicit slash commands reached the platform as generic SDK
- * traffic. Every request method in the SDK sends `this.headers`, so setting
- * them here covers all of them.
- *
- * X-Mem0-Source and X-Application are set-once, so a wrapper that already named
- * a surface keeps it. X-Mem0-Client is append-only, so the platform sees the
- * whole chain rather than only the last speaker.
- */
-export function applySurfaceHeaders(client: MemoryClient): void {
- const headers = client.headers as Record;
- if (!headers["X-Mem0-Source"]?.trim()) headers["X-Mem0-Source"] = PLATFORM_SOURCE;
- if (!headers["X-Application"]?.trim()) headers["X-Application"] = PLATFORM_APPLICATION;
-
- const existing = (headers["X-Mem0-Client"] ?? "")
- .split(",")
- .map((part) => part.trim())
- .filter(Boolean);
- headers["X-Mem0-Client"] = boundedStack(existing, `mem0-pi-agent/${PLUGIN_VERSION}`);
-}
diff --git a/integrations/pi-agent-plugin/src/commands.ts b/integrations/pi-agent-plugin/src/commands.ts
index e969478a1..9379bed9a 100644
--- a/integrations/pi-agent-plugin/src/commands.ts
+++ b/integrations/pi-agent-plugin/src/commands.ts
@@ -1,4 +1,3 @@
-import type { SearchMemoryOptions } from "mem0ai";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import type MemoryClient from "mem0ai";
import type { Mem0Config, ScopeContext, Scope } from "./types.ts";
@@ -6,12 +5,6 @@ import { DEFAULT_CUSTOM_CATEGORIES } from "./types.ts";
import { resolveSearchFilters, resolveAddParams } from "./memory/scoping.ts";
import { formatMemoryList, formatMemoryCompact, groupByCategory } from "./memory/formatting.ts";
import { captureCommandEvent } from "./telemetry.ts";
-import { PLATFORM_SOURCE } from "./attribution.ts";
-
-// Wire identity is set once on the shared client in entry.ts, which covers
-// every path including recall, capture, tools and deletion. It stays in the
-// body of the two calls below as well: body `source` is what the backend reads
-// when the header is absent.
const SEARCH_TOP_K = 10;
@@ -36,12 +29,7 @@ export function registerCommands(
threshold: config.searchThreshold,
topK: SEARCH_TOP_K,
rerank: true,
- source: PLATFORM_SOURCE,
- // Widened by exactly this one property. `source` reaches the wire via the
- // SDK's camelToSnakeKeys spread, but it is absent from SearchMemoryOptions
- // in the published mem0ai types. A blanket `as never` would also disable
- // checking of filters, threshold, topK and rerank above.
- } as SearchMemoryOptions & { source: string });
+ });
return result.results ?? [];
};
@@ -57,7 +45,7 @@ export function registerCommands(
const addParams = resolveAddParams(config.defaultScope, getScopeCtx());
const result = await mem0.add(
[{ role: "user", content: text }],
- { ...addParams, customCategories: DEFAULT_CUSTOM_CATEGORIES, infer: false, source: PLATFORM_SOURCE },
+ { ...addParams, customCategories: DEFAULT_CUSTOM_CATEGORIES, infer: false },
);
captureCommandEvent("mem0-remember", {}, telemetryCtx);
diff --git a/integrations/pi-agent-plugin/src/entry.ts b/integrations/pi-agent-plugin/src/entry.ts
index 256c05aa4..d49d78ad0 100644
--- a/integrations/pi-agent-plugin/src/entry.ts
+++ b/integrations/pi-agent-plugin/src/entry.ts
@@ -10,7 +10,6 @@ import { captureEvent } from "./telemetry.ts";
import * as os from "node:os";
import type { ScopeContext } from "./types.ts";
import { createMemoryLifecycle } from "../../agent-plugin-core/typescript/src/lifecycle.ts";
-import { applySurfaceHeaders } from "./attribution.ts";
export { buildRecallContext } from "../../agent-plugin-core/typescript/src/lifecycle.ts";
@@ -30,11 +29,6 @@ export default function mem0Extension(pi: ExtensionAPI): void {
}
const mem0 = new MemoryClient({ apiKey: config.apiKey });
- // Every path below shares this client: automatic recall, capture, the memory
- // tools and deletion as well as the slash commands. Attribution belongs here
- // rather than on individual calls, or everything except the commands reports
- // as generic SDK traffic.
- applySurfaceHeaders(mem0);
const scopeCtx: ScopeContext = {
userId: resolveUserId(config.userId),
diff --git a/integrations/pi-agent-plugin/src/memory/tools.ts b/integrations/pi-agent-plugin/src/memory/tools.ts
index f6110a73f..96d8e9b3e 100644
--- a/integrations/pi-agent-plugin/src/memory/tools.ts
+++ b/integrations/pi-agent-plugin/src/memory/tools.ts
@@ -1,5 +1,4 @@
import { resolveToolScope } from "../../../agent-plugin-core/typescript/src/scoping.ts";
-import { SEARCH_QUERY_DESCRIPTION, SEARCH_WHEN } from "../../../agent-plugin-core/typescript/src/prompts.ts";
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
import { Type } from "typebox";
import { StringEnum } from "@earendil-works/pi-ai";
@@ -145,10 +144,11 @@ export function registerMemoryTool(
name: "mem0_memory",
label: "Mem0 Memory",
description:
- `Search, add, update, and manage persistent semantic memories powered by Mem0. Memories persist across sessions and devices. Use action "search" ${SEARCH_WHEN}. Output is truncated to 200 lines / 50KB.`,
+ "Search, add, update, and manage persistent semantic memories powered by Mem0. Memories persist across sessions and devices. Use action \"search\" proactively -- before answering anything that may depend on what the user told you earlier -- and run multiple searches with different phrasings for multi-part questions. Output is truncated to 200 lines / 50KB.",
promptSnippet: "Semantic memory search and storage via Mem0",
promptGuidelines: [
- `Use mem0_memory with action "search" ${SEARCH_WHEN}`,
+ 'Use mem0_memory with action "search" proactively whenever the request may depend on the user\'s past work, preferences, decisions, or environment -- not only when they explicitly mention the past',
+ 'For multi-part or comparative questions, run several searches with different phrasings and combine the results before answering -- one search is rarely enough',
'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 after the user selects /mem0-scope global use scope \"global\"",
@@ -166,13 +166,13 @@ export function registerMemoryTool(
] as const,
{
description:
- "Memory operation to run: \"search\" (semantic recall of earlier work in this repository), \"add\" (save a new fact/preference/decision), \"get_all\" (list everything in scope, no query needed), \"update\" (replace an existing memory's text by id), \"delete\" (remove one memory by id), \"delete_all\" (wipe every memory in the scope -- destructive, only on explicit request).",
+ "Memory operation to run: \"search\" (semantic recall -- use proactively before answering; run several with different phrasings for multi-part questions), \"add\" (save a new fact/preference/decision), \"get_all\" (list everything in scope, no query needed), \"update\" (replace an existing memory's text by id), \"delete\" (remove one memory by id), \"delete_all\" (wipe every memory in the scope -- destructive, only on explicit request).",
},
),
query: Type.Optional(
Type.String({
description:
- `Search text -- required for action "search". ${SEARCH_QUERY_DESCRIPTION}`,
+ "Search text -- required for action \"search\". Use a focused noun-phrase; for multi-part questions run several searches with different phrasings.",
}),
),
content: Type.Optional(
diff --git a/integrations/pi-agent-plugin/src/prompt.ts b/integrations/pi-agent-plugin/src/prompt.ts
index dd1137d35..83365239b 100644
--- a/integrations/pi-agent-plugin/src/prompt.ts
+++ b/integrations/pi-agent-plugin/src/prompt.ts
@@ -1,9 +1,10 @@
-import { SEARCH_WHEN } from "../../agent-plugin-core/typescript/src/prompts.ts";
-
export const MEMORY_POLICY = `
-You have persistent semantic memory via the mem0_memory tool, powered by Mem0. Relevant memories may be auto-injected under .
+You have persistent semantic memory via the mem0_memory tool, powered by Mem0. Relevant memories may be auto-injected under , but that retrieval is shallow โ treat it as a starting point, not the full picture.
-Use mem0_memory with action "search" ${SEARCH_WHEN}.
+Be proactive about retrieval:
+- Search memory BEFORE answering whenever the request could depend on the user's past work, preferences, decisions, environment, or anything they told you earlier โ don't wait to be asked.
+- Check memory before asking the user something they may have already told you.
+- For multi-part, comparative, or "how did weโฆ" questions, run SEVERAL searches with different phrasings and combine the results. One search is rarely enough โ keep going until you have what you need (multi-hop).
Be proactive about saving:
- Save important facts, preferences, goals, decisions, lessons learned, identity, relationships, and routines the user shares.
diff --git a/integrations/vercel-ai-sdk/package.json b/integrations/vercel-ai-sdk/package.json
index 959d69eb7..7b417e460 100644
--- a/integrations/vercel-ai-sdk/package.json
+++ b/integrations/vercel-ai-sdk/package.json
@@ -1,6 +1,6 @@
{
"name": "@mem0/vercel-ai-provider",
- "version": "3.0.3",
+ "version": "3.0.2",
"description": "Vercel AI Provider for providing memory to LLMs",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
@@ -88,10 +88,9 @@
"esbuild": ">=0.28.1",
"brace-expansion@<1.1.16": ">=1.1.16 <2.0.0",
"brace-expansion@>=3.0.0 <5.0.8": ">=5.0.8 <6.0.0",
- "js-yaml@<3.15.2": ">=3.15.2 <4.0.0",
- "js-yaml@>=4.0.0 <4.3.2": ">=4.3.2 <5.0.0",
- "browserslist@<4.28.7": ">=4.28.7 <5.0.0",
- "handlebars@<4.7.10": ">=4.7.10 <5.0.0"
+ "js-yaml@<3.15.1": ">=3.15.1 <4.0.0",
+ "js-yaml@>=4.0.0 <4.3.1": ">=4.3.1 <5.0.0",
+ "browserslist@<4.28.7": ">=4.28.7 <5.0.0"
}
}
}
diff --git a/integrations/vercel-ai-sdk/pnpm-lock.yaml b/integrations/vercel-ai-sdk/pnpm-lock.yaml
index dfdf09ab3..f8208a36a 100644
--- a/integrations/vercel-ai-sdk/pnpm-lock.yaml
+++ b/integrations/vercel-ai-sdk/pnpm-lock.yaml
@@ -14,10 +14,9 @@ overrides:
esbuild: '>=0.28.1'
brace-expansion@<1.1.16: '>=1.1.16 <2.0.0'
brace-expansion@>=3.0.0 <5.0.8: '>=5.0.8 <6.0.0'
- js-yaml@<3.15.2: '>=3.15.2 <4.0.0'
- js-yaml@>=4.0.0 <4.3.2: '>=4.3.2 <5.0.0'
+ js-yaml@<3.15.1: '>=3.15.1 <4.0.0'
+ js-yaml@>=4.0.0 <4.3.1: '>=4.3.1 <5.0.0'
browserslist@<4.28.7: '>=4.28.7 <5.0.0'
- handlebars@<4.7.10: '>=4.7.10 <5.0.0'
importers:
@@ -1116,8 +1115,8 @@ packages:
graceful-fs@4.2.11:
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
- handlebars@4.7.10:
- resolution: {integrity: sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==}
+ handlebars@4.7.9:
+ resolution: {integrity: sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==}
engines: {node: '>=0.4.7'}
hasBin: true
@@ -1357,8 +1356,8 @@ packages:
js-tokens@4.0.0:
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
- js-yaml@3.15.2:
- resolution: {integrity: sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==}
+ js-yaml@3.15.1:
+ resolution: {integrity: sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==}
hasBin: true
jsesc@3.1.0:
@@ -2232,7 +2231,7 @@ snapshots:
camelcase: 5.3.1
find-up: 4.1.0
get-package-type: 0.1.0
- js-yaml: 3.15.2
+ js-yaml: 3.15.1
resolve-from: 5.0.0
'@istanbuljs/schema@0.1.6': {}
@@ -2944,7 +2943,7 @@ snapshots:
graceful-fs@4.2.11: {}
- handlebars@4.7.10:
+ handlebars@4.7.9:
dependencies:
minimist: 1.2.8
neo-async: 2.6.2
@@ -3361,7 +3360,7 @@ snapshots:
js-tokens@4.0.0: {}
- js-yaml@3.15.2:
+ js-yaml@3.15.1:
dependencies:
argparse: 1.0.10
esprima: 4.0.1
@@ -3722,7 +3721,7 @@ snapshots:
dependencies:
bs-logger: 0.2.6
fast-json-stable-stringify: 2.1.0
- handlebars: 4.7.10
+ handlebars: 4.7.9
jest: 29.7.0(@types/node@18.19.130)(ts-node@10.9.2(@types/node@18.19.130)(typescript@5.9.3))
json5: 2.2.3
lodash.memoize: 4.1.2
diff --git a/integrations/vercel-ai-sdk/pnpm-workspace.yaml b/integrations/vercel-ai-sdk/pnpm-workspace.yaml
index db4fa06a6..93ff161d8 100644
--- a/integrations/vercel-ai-sdk/pnpm-workspace.yaml
+++ b/integrations/vercel-ai-sdk/pnpm-workspace.yaml
@@ -15,7 +15,6 @@ overrides:
"esbuild": ">=0.28.1"
"brace-expansion@<1.1.16": ">=1.1.16 <2.0.0"
"brace-expansion@>=3.0.0 <5.0.8": ">=5.0.8 <6.0.0"
- "js-yaml@<3.15.2": ">=3.15.2 <4.0.0"
- "js-yaml@>=4.0.0 <4.3.2": ">=4.3.2 <5.0.0"
+ "js-yaml@<3.15.1": ">=3.15.1 <4.0.0"
+ "js-yaml@>=4.0.0 <4.3.1": ">=4.3.1 <5.0.0"
"browserslist@<4.28.7": ">=4.28.7 <5.0.0"
- "handlebars@<4.7.10": ">=4.7.10 <5.0.0"
diff --git a/integrations/vercel-ai-sdk/src/mem0-utils.ts b/integrations/vercel-ai-sdk/src/mem0-utils.ts
index b7a041939..55d485cbc 100644
--- a/integrations/vercel-ai-sdk/src/mem0-utils.ts
+++ b/integrations/vercel-ai-sdk/src/mem0-utils.ts
@@ -1,10 +1,3 @@
-declare const __MEM0_PROVIDER_VERSION__: string | undefined;
-
-// Replaced at build time by tsup `define`. The fallback only applies when the
-// source is run unbundled, such as in tests.
-const PROVIDER_VERSION =
- typeof __MEM0_PROVIDER_VERSION__ !== "undefined" ? __MEM0_PROVIDER_VERSION__ : "dev";
-
import { LanguageModelV3Prompt } from '@ai-sdk/provider';
import { Mem0ConfigSettings } from './mem0-types';
import { loadApiKey } from '@ai-sdk/provider-utils';
@@ -284,11 +277,7 @@ const searchInternalMemories = async (query: string, config?: Mem0ConfigSettings
method: 'POST',
headers: {
Authorization: `Token ${apiKey}`,
- 'Content-Type': 'application/json',
- // Surface attribution. Set-once by contract: this wrapper is the
- // outermost layer on these raw fetch calls.
- 'X-Mem0-Source': 'VERCEL_AI_SDK',
- 'X-Mem0-Client': `mem0-vercel-ai-provider/${PROVIDER_VERSION}`
+ 'Content-Type': 'application/json'
},
body: JSON.stringify(body),
};
@@ -342,11 +331,7 @@ const updateMemories = async (messages: Array, config?: Mem0ConfigSetti
method: 'POST',
headers: {
Authorization: `Token ${apiKey}`,
- 'Content-Type': 'application/json',
- // Surface attribution. Set-once by contract: this wrapper is the
- // outermost layer on these raw fetch calls.
- 'X-Mem0-Source': 'VERCEL_AI_SDK',
- 'X-Mem0-Client': `mem0-vercel-ai-provider/${PROVIDER_VERSION}`
+ 'Content-Type': 'application/json'
},
body: JSON.stringify(body),
};
diff --git a/integrations/vercel-ai-sdk/tsconfig.json b/integrations/vercel-ai-sdk/tsconfig.json
index e40350730..b05d5db02 100644
--- a/integrations/vercel-ai-sdk/tsconfig.json
+++ b/integrations/vercel-ai-sdk/tsconfig.json
@@ -12,7 +12,6 @@
"noUnusedLocals": false,
"noUnusedParameters": false,
"preserveWatchOutput": true,
- "resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"types": ["@types/node", "jest"],
diff --git a/integrations/vercel-ai-sdk/tsup.config.ts b/integrations/vercel-ai-sdk/tsup.config.ts
index ff2d298c0..2c8f74a6d 100644
--- a/integrations/vercel-ai-sdk/tsup.config.ts
+++ b/integrations/vercel-ai-sdk/tsup.config.ts
@@ -1,5 +1,4 @@
import { defineConfig } from 'tsup'
-import pkg from './package.json'
export default defineConfig([
{
@@ -7,11 +6,5 @@ export default defineConfig([
entry: ['src/index.ts'],
format: ['cjs', 'esm'],
sourcemap: true,
- // Injected rather than written in the source. A hardcoded literal matches
- // package.json on the day it is written and misreports the client version
- // from the next release bump onwards. Same mechanism as mem0-ts.
- define: {
- __MEM0_PROVIDER_VERSION__: JSON.stringify(pkg.version),
- },
},
])
\ No newline at end of file
diff --git a/integrations/zapier-mem0/README.md b/integrations/zapier-mem0/README.md
index dab21d3f3..7b3f5ed0f 100644
--- a/integrations/zapier-mem0/README.md
+++ b/integrations/zapier-mem0/README.md
@@ -32,7 +32,7 @@ pnpm test:unit # offline unit tests (mocked, no network)
MEM0_API_KEY=m0-... pnpm test # unit + live E2E against api.mem0.ai
```
-This app sends no telemetry of its own. Its API requests carry `source: "ZAPIER"` so Mem0 can see aggregate usage of the integration.
+Anonymous usage telemetry is sent to Mem0; opt out with `MEM0_TELEMETRY=false`.
To deploy (maintainers): `pnpm build && zapier push`.
diff --git a/integrations/zapier-mem0/package.json b/integrations/zapier-mem0/package.json
index f2b245d35..b33e01b53 100644
--- a/integrations/zapier-mem0/package.json
+++ b/integrations/zapier-mem0/package.json
@@ -72,8 +72,7 @@
"undici@<7.29.0": ">=7.29.0 <8.0.0",
"undici@>=8.0.0 <8.9.0": ">=8.9.0 <9.0.0",
"brace-expansion@<1.1.16": ">=1.1.16 <2.0.0",
- "js-yaml@<3.15.2": ">=3.15.2 <4.0.0",
- "handlebars@<4.7.10": ">=4.7.10 <5.0.0"
+ "js-yaml@<3.15.1": ">=3.15.1 <4.0.0"
}
}
}
diff --git a/integrations/zapier-mem0/pnpm-lock.yaml b/integrations/zapier-mem0/pnpm-lock.yaml
index 04aed747c..703de111d 100644
--- a/integrations/zapier-mem0/pnpm-lock.yaml
+++ b/integrations/zapier-mem0/pnpm-lock.yaml
@@ -11,8 +11,7 @@ overrides:
undici@<7.29.0: '>=7.29.0 <8.0.0'
undici@>=8.0.0 <8.9.0: '>=8.9.0 <9.0.0'
brace-expansion@<1.1.16: '>=1.1.16 <2.0.0'
- js-yaml@<3.15.2: '>=3.15.2 <4.0.0'
- handlebars@<4.7.10: '>=4.7.10 <5.0.0'
+ js-yaml@<3.15.1: '>=3.15.1 <4.0.0'
importers:
@@ -705,8 +704,8 @@ packages:
graceful-fs@4.2.11:
resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==}
- handlebars@4.7.10:
- resolution: {integrity: sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==}
+ handlebars@4.7.9:
+ resolution: {integrity: sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==}
engines: {node: '>=0.4.7'}
hasBin: true
@@ -952,8 +951,8 @@ packages:
js-tokens@4.0.0:
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
- js-yaml@3.15.2:
- resolution: {integrity: sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==}
+ js-yaml@3.15.1:
+ resolution: {integrity: sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==}
hasBin: true
jsesc@3.1.0:
@@ -1655,7 +1654,7 @@ snapshots:
camelcase: 5.3.1
find-up: 4.1.0
get-package-type: 0.1.0
- js-yaml: 3.15.2
+ js-yaml: 3.15.1
resolve-from: 5.0.0
'@istanbuljs/schema@0.1.6': {}
@@ -2288,7 +2287,7 @@ snapshots:
graceful-fs@4.2.11: {}
- handlebars@4.7.10:
+ handlebars@4.7.9:
dependencies:
minimist: 1.2.8
neo-async: 2.6.2
@@ -2715,7 +2714,7 @@ snapshots:
js-tokens@4.0.0: {}
- js-yaml@3.15.2:
+ js-yaml@3.15.1:
dependencies:
argparse: 1.0.10
esprima: 4.0.1
@@ -3033,7 +3032,7 @@ snapshots:
dependencies:
bs-logger: 0.2.6
fast-json-stable-stringify: 2.1.0
- handlebars: 4.7.10
+ handlebars: 4.7.9
jest: 29.7.0(@types/node@22.20.1)
json5: 2.2.3
lodash.memoize: 4.1.2
diff --git a/integrations/zapier-mem0/pnpm-workspace.yaml b/integrations/zapier-mem0/pnpm-workspace.yaml
index 8b131a6c6..e19a69b83 100644
--- a/integrations/zapier-mem0/pnpm-workspace.yaml
+++ b/integrations/zapier-mem0/pnpm-workspace.yaml
@@ -8,5 +8,4 @@ overrides:
"undici@<7.29.0": ">=7.29.0 <8.0.0"
"undici@>=8.0.0 <8.9.0": ">=8.9.0 <9.0.0"
"brace-expansion@<1.1.16": ">=1.1.16 <2.0.0"
- "js-yaml@<3.15.2": ">=3.15.2 <4.0.0"
- "handlebars@<4.7.10": ">=4.7.10 <5.0.0"
+ "js-yaml@<3.15.1": ">=3.15.1 <4.0.0"
diff --git a/marketplace.json b/marketplace.json
index ded2d2ece..eea48e2af 100644
--- a/marketplace.json
+++ b/marketplace.json
@@ -13,7 +13,7 @@
},
"category": "Productivity",
"description": "Cross-session memory and token savings for coding agents.",
- "version": "0.3.3"
+ "version": "0.3.1"
}
]
}
diff --git a/mem0-ts/package.json b/mem0-ts/package.json
index 8a20df517..7697b2384 100644
--- a/mem0-ts/package.json
+++ b/mem0-ts/package.json
@@ -1,6 +1,6 @@
{
"name": "mem0ai",
- "version": "3.3.1",
+ "version": "3.1.8",
"description": "The Memory Layer For Your AI Apps",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
@@ -100,11 +100,10 @@
"tsup": "^8.3.0",
"typescript": "5.5.4",
"iovalkey": "^0.3.3",
- "@mochow/mochow-sdk-node": "^2.1.5",
- "@types/jest": "^29.5.14"
+ "@mochow/mochow-sdk-node": "^2.1.5"
},
"dependencies": {
- "axios": "^1.20.0",
+ "axios": "^1.18.0",
"openai": "^4.93.0",
"uuid": "^11.1.1",
"zod": "^3.24.1"
@@ -128,7 +127,8 @@
"@qdrant/js-client-rest": "^1.18.0",
"@supabase/supabase-js": "^2.49.1",
"@turbopuffer/turbopuffer": "^2.0.0",
- "@types/pg": "^8.11.0",
+ "@types/jest": "29.5.14",
+ "@types/pg": "8.11.0",
"@upstash/vector": "^1.2.3",
"better-sqlite3": "^12.6.2",
"cassandra-driver": "4.8.0",
@@ -141,7 +141,7 @@
"weaviate-client": "^3.0.0",
"ollama": "^0.5.14",
"oracledb": "^6.5.0 || ^7.0.0",
- "pg": "^8.11.3",
+ "pg": "8.11.3",
"redis": "^4.6.13",
"@elastic/elasticsearch": "^9.0.0",
"iovalkey": "^0.3.3",
@@ -257,15 +257,6 @@
},
"oracledb": {
"optional": true
- },
- "pg": {
- "optional": true
- },
- "@types/pg": {
- "optional": true
- },
- "natural": {
- "optional": true
}
},
"engines": {
@@ -281,15 +272,14 @@
"better-sqlite3"
],
"overrides": {
- "@azure/identity@<4.14.1": ">=4.14.1 <5.0.0",
"form-data@<4.0.6": ">=4.0.6",
"picomatch@<2.3.2": "^2.3.2",
"picomatch@>=4.0.0 <4.0.4": "^4.0.4",
"jws@4.0.0": "4.0.1",
- "js-yaml@<3.15.2": ">=3.15.2 <4.0.0",
- "js-yaml@>=4.0.0 <4.3.2": ">=4.3.2 <5.0.0",
- "sharp@<0.35.4": ">=0.35.4 <0.36.0",
- "adm-zip@<0.6.1": ">=0.6.1 <0.7.0",
+ "js-yaml@<3.15.1": ">=3.15.1 <4.0.0",
+ "js-yaml@>=4.0.0 <4.3.1": ">=4.3.1 <5.0.0",
+ "sharp@<0.35.0": ">=0.35.0 <0.36.0",
+ "adm-zip@<0.6.0": ">=0.6.0 <0.7.0",
"langsmith@<0.6.0": "^0.6.0",
"minimatch@<3.1.3": "^3.1.3",
"minimatch@>=5.0.0 <5.1.8": "^5.1.8",
@@ -304,25 +294,21 @@
"glob@>=10.2.0 <10.5.0": "^10.5.0",
"@modelcontextprotocol/sdk": "^1.25.4",
"esbuild": ">=0.28.1",
- "undici@<7.30.1": ">=7.30.1 <8.0.0",
+ "undici@<7.29.0": ">=7.29.0 <8.0.0",
"@aws-sdk/client-bedrock-runtime": "3.967.0",
"@aws-sdk/client-neptune-graph": "3.966.0",
- "axios@<1.20.0": ">=1.20.0 <2.0.0",
+ "axios@<1.18.0": ">=1.18.0 <2.0.0",
"brace-expansion@<1.1.16": ">=1.1.16 <2.0.0",
- "brace-expansion@>=2.0.0 <2.1.6": ">=2.1.6 <3.0.0",
+ "brace-expansion@>=2.0.0 <2.1.4": ">=2.1.4 <3.0.0",
"brace-expansion@>=3.0.0 <5.0.8": ">=5.0.8 <6.0.0",
"fast-xml-parser@>=5.0.0 <5.10.1": ">=5.10.1 <6.0.0",
"tar@<7.5.21": ">=7.5.21 <8.0.0",
"thrift@<0.23.0": "^0.23.0",
"mongoose@>=9.0.0 <9.7.2": ">=9.7.2 <10.0.0",
"protobufjs@<7.6.5": ">=7.6.5 <8.0.0",
- "ip-address@<10.5.1": ">=10.5.1 <11.0.0",
+ "ip-address@<10.3.1": ">=10.3.1 <11.0.0",
"browserslist@<4.28.7": ">=4.28.7 <5.0.0",
- "mysql2@<3.23.1": ">=3.23.1 <4.0.0",
- "basic-ftp@<6.2.1": ">=6.2.1 <7.0.0",
- "@grpc/grpc-js@>=1.14.0 <1.14.5": ">=1.14.5 <2.0.0",
- "handlebars@<4.7.10": ">=4.7.10 <5.0.0",
- "follow-redirects@<1.16.2": ">=1.16.2 <2.0.0"
+ "mysql2@<3.23.1": ">=3.23.1 <4.0.0"
}
}
}
diff --git a/mem0-ts/pnpm-lock.yaml b/mem0-ts/pnpm-lock.yaml
index b4a57fa45..5deb30e7b 100644
--- a/mem0-ts/pnpm-lock.yaml
+++ b/mem0-ts/pnpm-lock.yaml
@@ -5,15 +5,14 @@ settings:
excludeLinksFromLockfile: false
overrides:
- '@azure/identity@<4.14.1': '>=4.14.1 <5.0.0'
form-data@<4.0.6: '>=4.0.6'
picomatch@<2.3.2: ^2.3.2
picomatch@>=4.0.0 <4.0.4: ^4.0.4
jws@4.0.0: 4.0.1
- js-yaml@<3.15.2: '>=3.15.2 <4.0.0'
- js-yaml@>=4.0.0 <4.3.2: '>=4.3.2 <5.0.0'
- sharp@<0.35.4: '>=0.35.4 <0.36.0'
- adm-zip@<0.6.1: '>=0.6.1 <0.7.0'
+ js-yaml@<3.15.1: '>=3.15.1 <4.0.0'
+ js-yaml@>=4.0.0 <4.3.1: '>=4.3.1 <5.0.0'
+ sharp@<0.35.0: '>=0.35.0 <0.36.0'
+ adm-zip@<0.6.0: '>=0.6.0 <0.7.0'
langsmith@<0.6.0: ^0.6.0
minimatch@<3.1.3: ^3.1.3
minimatch@>=5.0.0 <5.1.8: ^5.1.8
@@ -28,25 +27,21 @@ overrides:
glob@>=10.2.0 <10.5.0: ^10.5.0
'@modelcontextprotocol/sdk': ^1.25.4
esbuild: '>=0.28.1'
- undici@<7.30.1: '>=7.30.1 <8.0.0'
+ undici@<7.29.0: '>=7.29.0 <8.0.0'
'@aws-sdk/client-bedrock-runtime': 3.967.0
'@aws-sdk/client-neptune-graph': 3.966.0
- axios@<1.20.0: '>=1.20.0 <2.0.0'
+ axios@<1.18.0: '>=1.18.0 <2.0.0'
brace-expansion@<1.1.16: '>=1.1.16 <2.0.0'
- brace-expansion@>=2.0.0 <2.1.6: '>=2.1.6 <3.0.0'
+ brace-expansion@>=2.0.0 <2.1.4: '>=2.1.4 <3.0.0'
brace-expansion@>=3.0.0 <5.0.8: '>=5.0.8 <6.0.0'
fast-xml-parser@>=5.0.0 <5.10.1: '>=5.10.1 <6.0.0'
tar@<7.5.21: '>=7.5.21 <8.0.0'
thrift@<0.23.0: ^0.23.0
mongoose@>=9.0.0 <9.7.2: '>=9.7.2 <10.0.0'
protobufjs@<7.6.5: '>=7.6.5 <8.0.0'
- ip-address@<10.5.1: '>=10.5.1 <11.0.0'
+ ip-address@<10.3.1: '>=10.3.1 <11.0.0'
browserslist@<4.28.7: '>=4.28.7 <5.0.0'
mysql2@<3.23.1: '>=3.23.1 <4.0.0'
- basic-ftp@<6.2.1: '>=6.2.1 <7.0.0'
- '@grpc/grpc-js@>=1.14.0 <1.14.5': '>=1.14.5 <2.0.0'
- handlebars@<4.7.10: '>=4.7.10 <5.0.0'
- follow-redirects@<1.16.2: '>=1.16.2 <2.0.0'
patchedDependencies:
tar@7.5.22:
@@ -70,8 +65,8 @@ importers:
specifier: 3.967.0
version: 3.967.0
'@azure/identity':
- specifier: '>=4.14.1 <5.0.0'
- version: 4.14.1
+ specifier: ^4.0.0
+ version: 4.13.1
'@azure/search-documents':
specifier: ^12.0.0
version: 12.2.0
@@ -114,8 +109,11 @@ importers:
'@turbopuffer/turbopuffer':
specifier: ^2.0.0
version: 2.5.0
+ '@types/jest':
+ specifier: 29.5.14
+ version: 29.5.14
'@types/pg':
- specifier: ^8.11.0
+ specifier: 8.11.0
version: 8.11.0
'@upstash/vector':
specifier: ^1.2.3
@@ -124,8 +122,8 @@ importers:
specifier: ^2.4.0 || ^3.0.0
version: 3.0.3
axios:
- specifier: ^1.20.0
- version: 1.20.0
+ specifier: ^1.18.0
+ version: 1.18.1
better-sqlite3:
specifier: ^12.6.2
version: 12.10.0
@@ -169,8 +167,8 @@ importers:
specifier: ^6.5.0 || ^7.0.0
version: 7.0.1
pg:
- specifier: ^8.11.3
- version: 8.21.0
+ specifier: 8.11.3
+ version: 8.11.3
redis:
specifier: ^4.6.13
version: 4.7.1
@@ -193,9 +191,6 @@ importers:
'@types/better-sqlite3':
specifier: ^7.6.13
version: 7.6.13
- '@types/jest':
- specifier: ^29.5.14
- version: 29.5.14
'@types/node':
specifier: ^22.7.6
version: 22.19.21
@@ -580,10 +575,6 @@ packages:
resolution: {integrity: sha512-YKWi9YuCU04B55h25cnOYZHxXYtEvQEbKST5vqRga7hWY9ydd3FZHdeQF8pyh+acWZvppw13M/LMGx0LABUVMA==}
engines: {node: '>=18.0.0'}
- '@azure/core-process@1.0.0':
- resolution: {integrity: sha512-/shnJ+ooO8WPxDhPEeI/2oRQuubn16gZ6CvlbpWbEswZfzwI9tI/sMAHmF3x1LuQ9yZYXfLW3TjzGMLEC5blKg==}
- engines: {node: '>=22.0.0'}
-
'@azure/core-rest-pipeline@1.24.0':
resolution: {integrity: sha512-PpLsoDQ3AMmKZ0VU+0GrmqMxgp/sExjlVm4R+nLWngeoEGAzOIPVifaxKGU5gMv+nWELUoHfvrolWD+ZS/nFJg==}
engines: {node: '>=20.0.0'}
@@ -596,9 +587,9 @@ packages:
resolution: {integrity: sha512-XPArKLzsvl0Hf0CaGyKHUyVgF7oDnhKoP85Xv6M4StF/1AhfORhZudHtOyf2s+FcbuQ9dPRAjB8J2KvRRMUK2A==}
engines: {node: '>=20.0.0'}
- '@azure/identity@4.14.1':
- resolution: {integrity: sha512-HHuuFrmN1uuF9D5A6aAo5eHzNFNX4Q+P4SksZqDKse5YaJFFy/zDLG3wXHEV2FVGgetZ3QM8jGURNBtnQYf1NQ==}
- engines: {node: '>=22.0.0'}
+ '@azure/identity@4.13.1':
+ resolution: {integrity: sha512-5C/2WD5Vb1lHnZS16dNQRPMjN6oV/Upba+C9nBIs15PmOi6A3ZGs4Lr2u60zw4S04gi+u3cEXiqTVP7M4Pz3kw==}
+ engines: {node: '>=20.0.0'}
'@azure/logger@1.3.0':
resolution: {integrity: sha512-fCqPIfOcLE+CGqGPd66c8bZpwAji98tZ4JI9i/mlTNTlsIWslCfpg48s/ypyLxZTump5sypjrKn2/kY7q8oAbA==}
@@ -608,16 +599,12 @@ packages:
resolution: {integrity: sha512-Ea23x0U8XNFY+qJ9T44zO2BbY+AHdb+WdjmYnx36OhJ/KO+PGU5pmsNHf1DCElYX+6wyVRJz1HFeCPC/cHbRug==}
engines: {node: '>=0.8.0'}
- '@azure/msal-common@16.16.0':
- resolution: {integrity: sha512-EZgd8h5nczsdRAQAgXA0A0pC5L/zj43n1jePXvUMgdwXMbH2zhb7b7Hp+Oe7ZOODK/sch2x+soD6FOrtgUbx/w==}
- engines: {node: '>=0.8.0'}
-
'@azure/msal-common@16.8.0':
resolution: {integrity: sha512-5S4RHOcInL2Nu2U217tDZbWGI6StMfcWCrA7TWvWdJmXQ+cYrrIqr84AsN62fGh2MDBysiBJPt6CfWceJfloEA==}
engines: {node: '>=0.8.0'}
- '@azure/msal-node@7.2.0':
- resolution: {integrity: sha512-Y87VJsMWF4jiqLqq8XYLb1o+rGc/HacwS3Zydi3bDtaVm5Sa8FlB7YrKrBFKRIYj27RJXAaDkErImMAqtM10Pg==}
+ '@azure/msal-node@5.2.4':
+ resolution: {integrity: sha512-rpBUg9dA8UpC2WiFt3KeDKVQmmmVrfxdRnW+F1ebgou/jX/0tAvYuonaq5RUo8OaqzOrj4x/HaI8DmY56RXZ2Q==}
engines: {node: '>=20'}
'@azure/search-documents@12.2.0':
@@ -874,8 +861,8 @@ packages:
resolution: {integrity: sha512-L38Ax21uF2OPUmCRWycZ/dZdMYf7gMrtClcxvVrqJVFmn8ET2M++GYmFGJpLqOHS1beATxOXLWe7y2ijSQz/ng==}
engines: {node: '>=20'}
- '@emnapi/runtime@1.11.3':
- resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==}
+ '@emnapi/runtime@1.11.2':
+ resolution: {integrity: sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==}
'@esbuild/aix-ppc64@0.28.1':
resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==}
@@ -1051,8 +1038,8 @@ packages:
peerDependencies:
graphql: ^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0
- '@grpc/grpc-js@1.14.5':
- resolution: {integrity: sha512-7VZM+SVdEcUUqSQeNI3zM8Qs/BhQKZndPo2h5VkYkAM8Iz0wJIa8mKV5ekQGqG8UUsnkQ0NMxIxwkIHYvj0qOw==}
+ '@grpc/grpc-js@1.14.4':
+ resolution: {integrity: sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==}
engines: {node: '>=12.10.0'}
'@grpc/proto-loader@0.8.1':
@@ -1088,144 +1075,144 @@ packages:
resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==}
engines: {node: '>=18'}
- '@img/sharp-darwin-arm64@0.35.5':
- resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==}
+ '@img/sharp-darwin-arm64@0.35.3':
+ resolution: {integrity: sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg==}
engines: {node: '>=20.9.0'}
cpu: [arm64]
os: [darwin]
- '@img/sharp-darwin-x64@0.35.5':
- resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==}
+ '@img/sharp-darwin-x64@0.35.3':
+ resolution: {integrity: sha512-Xo+5uFBtLN0BKqieTxiFzFPQAUlBbbH5iBKyRX/z1JrbnYsHTfKJnUfL8+p2TPXr1pXqao4eeL4Rl144uDpK9w==}
engines: {node: '>=20.9.0'}
cpu: [x64]
os: [darwin]
- '@img/sharp-freebsd-wasm32@0.35.5':
- resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==}
+ '@img/sharp-freebsd-wasm32@0.35.3':
+ resolution: {integrity: sha512-lUxcqWIj2wMQ9BrwNjngcr1gWUr5xgaGThBRqPPalIC2n67Cqj1uPh8NnA/ZhAg8hUbKl+kVHKwgUIwe6ZYPrg==}
engines: {node: '>=20.9.0'}
os: [freebsd]
- '@img/sharp-libvips-darwin-arm64@1.3.4':
- resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==}
+ '@img/sharp-libvips-darwin-arm64@1.3.2':
+ resolution: {integrity: sha512-9J6ypZFpQBj4YnePGoq/S38w6nz+vqg5WZLrLGY4YuSemdMq47GMLBPO42MzwdGwpg/agZ7xzZcFHa48xlywfg==}
cpu: [arm64]
os: [darwin]
- '@img/sharp-libvips-darwin-x64@1.3.4':
- resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==}
+ '@img/sharp-libvips-darwin-x64@1.3.2':
+ resolution: {integrity: sha512-m2pW1n6cns9VaubNwsZ+c3CRYjxNQWgJ5gPlnL1nbBcpkBvFm6SCFN5o0psFHI8w9n11NKhFkeEDns98tiqbEw==}
cpu: [x64]
os: [darwin]
- '@img/sharp-libvips-linux-arm64@1.3.4':
- resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==}
+ '@img/sharp-libvips-linux-arm64@1.3.2':
+ resolution: {integrity: sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA==}
cpu: [arm64]
os: [linux]
- '@img/sharp-libvips-linux-arm@1.3.4':
- resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==}
+ '@img/sharp-libvips-linux-arm@1.3.2':
+ resolution: {integrity: sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ==}
cpu: [arm]
os: [linux]
- '@img/sharp-libvips-linux-ppc64@1.3.4':
- resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==}
+ '@img/sharp-libvips-linux-ppc64@1.3.2':
+ resolution: {integrity: sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw==}
cpu: [ppc64]
os: [linux]
- '@img/sharp-libvips-linux-riscv64@1.3.4':
- resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==}
+ '@img/sharp-libvips-linux-riscv64@1.3.2':
+ resolution: {integrity: sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w==}
cpu: [riscv64]
os: [linux]
- '@img/sharp-libvips-linux-s390x@1.3.4':
- resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==}
+ '@img/sharp-libvips-linux-s390x@1.3.2':
+ resolution: {integrity: sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ==}
cpu: [s390x]
os: [linux]
- '@img/sharp-libvips-linux-x64@1.3.4':
- resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==}
+ '@img/sharp-libvips-linux-x64@1.3.2':
+ resolution: {integrity: sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w==}
cpu: [x64]
os: [linux]
- '@img/sharp-libvips-linuxmusl-arm64@1.3.4':
- resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==}
+ '@img/sharp-libvips-linuxmusl-arm64@1.3.2':
+ resolution: {integrity: sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw==}
cpu: [arm64]
os: [linux]
- '@img/sharp-libvips-linuxmusl-x64@1.3.4':
- resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==}
+ '@img/sharp-libvips-linuxmusl-x64@1.3.2':
+ resolution: {integrity: sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ==}
cpu: [x64]
os: [linux]
- '@img/sharp-linux-arm64@0.35.5':
- resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==}
+ '@img/sharp-linux-arm64@0.35.3':
+ resolution: {integrity: sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ==}
engines: {node: '>=20.9.0'}
cpu: [arm64]
os: [linux]
- '@img/sharp-linux-arm@0.35.5':
- resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==}
+ '@img/sharp-linux-arm@0.35.3':
+ resolution: {integrity: sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA==}
engines: {node: '>=20.9.0'}
cpu: [arm]
os: [linux]
- '@img/sharp-linux-ppc64@0.35.5':
- resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==}
+ '@img/sharp-linux-ppc64@0.35.3':
+ resolution: {integrity: sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA==}
engines: {node: '>=20.9.0'}
cpu: [ppc64]
os: [linux]
- '@img/sharp-linux-riscv64@0.35.5':
- resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==}
+ '@img/sharp-linux-riscv64@0.35.3':
+ resolution: {integrity: sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ==}
engines: {node: '>=20.9.0'}
cpu: [riscv64]
os: [linux]
- '@img/sharp-linux-s390x@0.35.5':
- resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==}
+ '@img/sharp-linux-s390x@0.35.3':
+ resolution: {integrity: sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw==}
engines: {node: '>=20.9.0'}
cpu: [s390x]
os: [linux]
- '@img/sharp-linux-x64@0.35.5':
- resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==}
+ '@img/sharp-linux-x64@0.35.3':
+ resolution: {integrity: sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA==}
engines: {node: '>=20.9.0'}
cpu: [x64]
os: [linux]
- '@img/sharp-linuxmusl-arm64@0.35.5':
- resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==}
+ '@img/sharp-linuxmusl-arm64@0.35.3':
+ resolution: {integrity: sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w==}
engines: {node: '>=20.9.0'}
cpu: [arm64]
os: [linux]
- '@img/sharp-linuxmusl-x64@0.35.5':
- resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==}
+ '@img/sharp-linuxmusl-x64@0.35.3':
+ resolution: {integrity: sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg==}
engines: {node: '>=20.9.0'}
cpu: [x64]
os: [linux]
- '@img/sharp-wasm32@0.35.5':
- resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==}
+ '@img/sharp-wasm32@0.35.3':
+ resolution: {integrity: sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w==}
engines: {node: '>=20.9.0'}
- '@img/sharp-webcontainers-wasm32@0.35.5':
- resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==}
+ '@img/sharp-webcontainers-wasm32@0.35.3':
+ resolution: {integrity: sha512-2rnq7bX3NzeR2T4YWgz8qiG4h3TSdMe+vN1iQXpJleSJ3SM5zQ8Fy2SyyXAWlbxpEZ2Y+Z4u1BePgJEYbSy80Q==}
engines: {node: '>=20.9.0'}
cpu: [wasm32]
- '@img/sharp-win32-arm64@0.35.5':
- resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==}
+ '@img/sharp-win32-arm64@0.35.3':
+ resolution: {integrity: sha512-4bPwFdMbeC4JQ8L8LOyWp6nsHcboP5fxkp6iPOXz2Vg49R42TuMs2whkJ5OAP4/Ul035qOzy0AecOF9VOscn4w==}
engines: {node: '>=20.9.0'}
cpu: [arm64]
os: [win32]
- '@img/sharp-win32-ia32@0.35.5':
- resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==}
+ '@img/sharp-win32-ia32@0.35.3':
+ resolution: {integrity: sha512-r53mXsBN6lFUDiST764SvgwUdHAqM4rPAiDzAmf4fLoB6X/rkfyTrLCg6+g17wJJiCmB3JYgHuUldCWUIRFSXw==}
engines: {node: ^20.9.0}
cpu: [ia32]
os: [win32]
- '@img/sharp-win32-x64@0.35.5':
- resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==}
+ '@img/sharp-win32-x64@0.35.3':
+ resolution: {integrity: sha512-D4y1vNeZrIIJCN+uHaWVtH86B+aCrdMYYjicy9pXHvbGZeGYLLSd3wdVuC37FxVXlU1ARsk84eKWfWMXGYEqvA==}
engines: {node: '>=20.9.0'}
cpu: [x64]
os: [win32]
@@ -2022,8 +2009,8 @@ packages:
engines: {node: '>=0.4.0'}
hasBin: true
- adm-zip@0.6.1:
- resolution: {integrity: sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==}
+ adm-zip@0.6.0:
+ resolution: {integrity: sha512-XleryMhbuksdKtofnWZ9Sk+4CUTbms4Mb/EU32SZwToAyZ5RgVos/ki8n+yr0LWHOGKuakbXTuuYNHLQjhddgg==}
engines: {node: '>=14.0'}
afinn-165-financialmarketnews@3.0.0:
@@ -2120,8 +2107,8 @@ packages:
aws4@1.13.2:
resolution: {integrity: sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==}
- axios@1.20.0:
- resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==}
+ axios@1.18.1:
+ resolution: {integrity: sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==}
babel-jest@29.7.0:
resolution: {integrity: sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==}
@@ -2166,8 +2153,8 @@ packages:
engines: {node: '>=6.0.0'}
hasBin: true
- basic-ftp@6.2.1:
- resolution: {integrity: sha512-bK67isD+lKq46AU8vNtjvMaT2ZqAOAmNCbxUHlFBRD4k15NWxyEjmaKtZPlgce58So4BNTjITGQOVTjL9y0ECA==}
+ basic-ftp@5.3.1:
+ resolution: {integrity: sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw==}
engines: {node: '>=10.0.0'}
better-sqlite3@12.10.0:
@@ -2197,8 +2184,8 @@ packages:
brace-expansion@1.1.16:
resolution: {integrity: sha512-IDw48K2/2kRkg9LdJxurvq3lV3aBgq0REY89duEqFRthjlPdXHKMj7EnQOXVckxzgisinf3nHfrcE2FufFLXMw==}
- brace-expansion@2.1.7:
- resolution: {integrity: sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==}
+ brace-expansion@2.1.4:
+ resolution: {integrity: sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==}
brace-expansion@5.0.8:
resolution: {integrity: sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==}
@@ -2241,6 +2228,10 @@ packages:
buffer-from@1.1.2:
resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==}
+ buffer-writer@2.0.0:
+ resolution: {integrity: sha512-a7ZpuTZU1TRtnwyCNW3I5dc0wWNC3VR9S++Ewyk2HHZdrO3CQJqSpd+95Us590V6AL7JqUAH2IwZ/398PmNFgw==}
+ engines: {node: '>=4'}
+
buffer@5.7.1:
resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==}
@@ -2525,8 +2516,8 @@ packages:
resolution: {integrity: sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==}
engines: {node: '>=18'}
- default-browser@5.5.1:
- resolution: {integrity: sha512-m1pAzaJgZ/gssEqlOhJkPJp8Xly7QyW6xcrkUa2KKcDeDSEMP7X8xipU3snUcfisTQx0w1AGae+9UtJSfVnXGw==}
+ default-browser@5.5.0:
+ resolution: {integrity: sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw==}
engines: {node: '>=18'}
define-data-property@1.1.4:
@@ -2783,8 +2774,8 @@ packages:
fn.name@1.1.0:
resolution: {integrity: sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==}
- follow-redirects@1.16.2:
- resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==}
+ follow-redirects@1.16.0:
+ resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==}
engines: {node: '>=4.0'}
peerDependencies:
debug: '*'
@@ -2949,8 +2940,8 @@ packages:
guid-typescript@1.0.9:
resolution: {integrity: sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==}
- handlebars@4.7.10:
- resolution: {integrity: sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==}
+ handlebars@4.7.9:
+ resolution: {integrity: sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==}
engines: {node: '>=0.4.7'}
hasBin: true
@@ -3047,8 +3038,8 @@ packages:
resolution: {integrity: sha512-4rTJX6Q5wTYEvxboXi8DsEiUo+OvqJGtLYOSGm37KpdRXsG5XJjbVtYKGJpPSWP+QT7rWscA4vsrdmzbEbenpw==}
engines: {node: '>=18.12.0'}
- ip-address@10.7.2:
- resolution: {integrity: sha512-7H/2gFSIitxc0hG3nOI1glS8QLo/EHBFFLk8vEUjXY/xu0AdL8jZ9U1IzO2PUm0d2D/ofQcAifb0g6OBkt8U7w==}
+ ip-address@10.4.0:
+ resolution: {integrity: sha512-oSK96Grm3aP6OrS263xVxbNDGVL7rzBtYdpGqlDG8iQdoenDoTs/nkki+DflYbAEE8Xl6o5YxhxlrKvI3nqKXQ==}
engines: {node: '>= 12'}
is-arrayish@0.2.1:
@@ -3091,10 +3082,6 @@ packages:
resolution: {integrity: sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==}
engines: {node: '>=0.10.0'}
- is-in-ssh@1.0.0:
- resolution: {integrity: sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw==}
- engines: {node: '>=20'}
-
is-inside-container@1.0.0:
resolution: {integrity: sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA==}
engines: {node: '>=14.16'}
@@ -3299,8 +3286,8 @@ packages:
js-tokens@4.0.0:
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
- js-yaml@3.15.2:
- resolution: {integrity: sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==}
+ js-yaml@3.15.1:
+ resolution: {integrity: sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==}
hasBin: true
jsesc@3.1.0:
@@ -3789,9 +3776,9 @@ packages:
onnxruntime-web@1.26.0-dev.20260416-b7804b056c:
resolution: {integrity: sha512-MD6Ss4GSpQBo6zqoJzyT9LRbKYs7x/JVN23FT24EcEvlqF4VuzPOeH6X38orZPKHQDbprn7K+SBpu0/mj2CQiw==}
- open@11.0.4:
- resolution: {integrity: sha512-++Zlftm0kVLPmzC06t6epuWmcRMDbI4z5P3NNX979WA/k23+NtSOynEGzsVfZwguKw2mi5umVgnBlJQMwRz4Pg==}
- engines: {node: '>=20'}
+ open@10.2.0:
+ resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==}
+ engines: {node: '>=18'}
open@8.4.2:
resolution: {integrity: sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==}
@@ -3859,6 +3846,9 @@ packages:
package-json-from-dist@1.0.1:
resolution: {integrity: sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==}
+ packet-reader@1.0.0:
+ resolution: {integrity: sha512-HAKu/fG3HpHFO0AA8WE8q2g+gBJaZ9MG7fcKk+IJPLTGAD6Psw4443l+9DGRbOIh3/aXr7Phy0TjilYivJo5XQ==}
+
pad-left@2.1.0:
resolution: {integrity: sha512-HJxs9K9AztdIQIAIa/OIazRAUW/L6B9hbQDxO4X07roW3eo9XqZc2ur9bn1StH9CnbbI9EgvejHQX7CBpCF1QA==}
engines: {node: '>=0.10.0'}
@@ -3930,6 +3920,15 @@ packages:
resolution: {integrity: sha512-o2XFanIMy/3+mThw69O8d4n1E5zsLhdO+OPqswezu7Z5ekP4hYDqlDjlmOpYMbzY2Br0ufCwJLdDIXeNVwcWFg==}
engines: {node: '>=10'}
+ pg@8.11.3:
+ resolution: {integrity: sha512-+9iuvG8QfaaUrrph+kpF24cXkH1YOOUeArRNYIxq1viYHZagBxrTno7cecY1Fa44tJeZvaoG+Djpkc3JwehN5g==}
+ engines: {node: '>= 8.0.0'}
+ peerDependencies:
+ pg-native: '>=3.0.1'
+ peerDependenciesMeta:
+ pg-native:
+ optional: true
+
pg@8.21.0:
resolution: {integrity: sha512-AUP1EYJuHraQGsVoCQVIcM7TEJVGtDzxWtGFZd8rds9d+CCXlU5Js1rYgfLNvxy9iJrpHjGrRjoi/3BT9fRyiA==}
engines: {node: '>= 16.0.0'}
@@ -4020,10 +4019,6 @@ packages:
postgres-range@1.1.4:
resolution: {integrity: sha512-i/hbxIE9803Alj/6ytL7UHQxRvZkI9O4Sy+J3HGc4F4oo/2eQAjTSNJ0bfxyse3bH0nuVesCk+3IRLaMtG3H6w==}
- powershell-utils@0.2.1:
- resolution: {integrity: sha512-C+y9x90UElAddDZmV4qOx9W53B61PO7cIqWz2dQsWlwswuq4mr8NEwytdGKboYbQlGZ3awrkTeNvcZiZNHnQ8A==}
- engines: {node: '>=20'}
-
prebuild-install@7.1.3:
resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==}
engines: {node: '>=10'}
@@ -4230,8 +4225,8 @@ packages:
resolution: {integrity: sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==}
engines: {node: '>=10'}
- sharp@0.35.5:
- resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==}
+ sharp@0.35.3:
+ resolution: {integrity: sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q==}
engines: {node: '>=20.9.0'}
peerDependencies:
'@types/node': '*'
@@ -4630,8 +4625,8 @@ packages:
undici-types@7.24.6:
resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==}
- undici@7.30.2:
- resolution: {integrity: sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==}
+ undici@7.29.0:
+ resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==}
engines: {node: '>=20.18.1'}
update-browserslist-db@1.3.2:
@@ -4763,9 +4758,9 @@ packages:
utf-8-validate:
optional: true
- wsl-utils@1.0.1:
- resolution: {integrity: sha512-c16PKLIRxBYpR3jSWsdS7SFp0COm5SOQdiFjY818dYFHJbMGuLBszpF07LBWmOS1uzrHa9VGdynsEgoeKy0oOQ==}
- engines: {node: '>=20'}
+ wsl-utils@0.1.0:
+ resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==}
+ engines: {node: '>=18'}
xml-naming@0.1.0:
resolution: {integrity: sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==}
@@ -5809,8 +5804,6 @@ snapshots:
dependencies:
tslib: 2.8.1
- '@azure/core-process@1.0.0': {}
-
'@azure/core-rest-pipeline@1.24.0':
dependencies:
'@azure/abort-controller': 2.1.2
@@ -5835,19 +5828,18 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@azure/identity@4.14.1':
+ '@azure/identity@4.13.1':
dependencies:
'@azure/abort-controller': 2.1.2
'@azure/core-auth': 1.10.1
'@azure/core-client': 1.10.2
- '@azure/core-process': 1.0.0
'@azure/core-rest-pipeline': 1.24.0
'@azure/core-tracing': 1.3.1
'@azure/core-util': 1.13.1
'@azure/logger': 1.3.0
'@azure/msal-browser': 5.13.0
- '@azure/msal-node': 7.2.0
- open: 11.0.4
+ '@azure/msal-node': 5.2.4
+ open: 10.2.0
tslib: 2.8.1
transitivePeerDependencies:
- supports-color
@@ -5863,13 +5855,11 @@ snapshots:
dependencies:
'@azure/msal-common': 16.8.0
- '@azure/msal-common@16.16.0': {}
-
'@azure/msal-common@16.8.0': {}
- '@azure/msal-node@7.2.0':
+ '@azure/msal-node@5.2.4':
dependencies:
- '@azure/msal-common': 16.16.0
+ '@azure/msal-common': 16.8.0
jsonwebtoken: 9.0.3
'@azure/search-documents@12.2.0':
@@ -6164,11 +6154,11 @@ snapshots:
ms: 2.1.3
secure-json-parse: 4.1.0
tslib: 2.8.1
- undici: 7.30.2
+ undici: 7.29.0
transitivePeerDependencies:
- supports-color
- '@emnapi/runtime@1.11.3':
+ '@emnapi/runtime@1.11.2':
dependencies:
tslib: 2.8.1
optional: true
@@ -6272,7 +6262,7 @@ snapshots:
dependencies:
graphql: 16.14.2
- '@grpc/grpc-js@1.14.5':
+ '@grpc/grpc-js@1.14.4':
dependencies:
'@grpc/proto-loader': 0.8.1
'@js-sdsl/ordered-map': 4.4.2
@@ -6305,7 +6295,7 @@ snapshots:
'@huggingface/tokenizers': 0.1.3
onnxruntime-node: 1.24.3
onnxruntime-web: 1.26.0-dev.20260416-b7804b056c
- sharp: 0.35.5(@types/node@22.19.21)
+ sharp: 0.35.3(@types/node@22.19.21)
transitivePeerDependencies:
- '@types/node'
@@ -6316,108 +6306,108 @@ snapshots:
'@img/colour@1.1.0': {}
- '@img/sharp-darwin-arm64@0.35.5':
+ '@img/sharp-darwin-arm64@0.35.3':
optionalDependencies:
- '@img/sharp-libvips-darwin-arm64': 1.3.4
+ '@img/sharp-libvips-darwin-arm64': 1.3.2
optional: true
- '@img/sharp-darwin-x64@0.35.5':
+ '@img/sharp-darwin-x64@0.35.3':
optionalDependencies:
- '@img/sharp-libvips-darwin-x64': 1.3.4
+ '@img/sharp-libvips-darwin-x64': 1.3.2
optional: true
- '@img/sharp-freebsd-wasm32@0.35.5':
+ '@img/sharp-freebsd-wasm32@0.35.3':
dependencies:
- '@img/sharp-wasm32': 0.35.5
+ '@img/sharp-wasm32': 0.35.3
optional: true
- '@img/sharp-libvips-darwin-arm64@1.3.4':
+ '@img/sharp-libvips-darwin-arm64@1.3.2':
optional: true
- '@img/sharp-libvips-darwin-x64@1.3.4':
+ '@img/sharp-libvips-darwin-x64@1.3.2':
optional: true
- '@img/sharp-libvips-linux-arm64@1.3.4':
+ '@img/sharp-libvips-linux-arm64@1.3.2':
optional: true
- '@img/sharp-libvips-linux-arm@1.3.4':
+ '@img/sharp-libvips-linux-arm@1.3.2':
optional: true
- '@img/sharp-libvips-linux-ppc64@1.3.4':
+ '@img/sharp-libvips-linux-ppc64@1.3.2':
optional: true
- '@img/sharp-libvips-linux-riscv64@1.3.4':
+ '@img/sharp-libvips-linux-riscv64@1.3.2':
optional: true
- '@img/sharp-libvips-linux-s390x@1.3.4':
+ '@img/sharp-libvips-linux-s390x@1.3.2':
optional: true
- '@img/sharp-libvips-linux-x64@1.3.4':
+ '@img/sharp-libvips-linux-x64@1.3.2':
optional: true
- '@img/sharp-libvips-linuxmusl-arm64@1.3.4':
+ '@img/sharp-libvips-linuxmusl-arm64@1.3.2':
optional: true
- '@img/sharp-libvips-linuxmusl-x64@1.3.4':
+ '@img/sharp-libvips-linuxmusl-x64@1.3.2':
optional: true
- '@img/sharp-linux-arm64@0.35.5':
+ '@img/sharp-linux-arm64@0.35.3':
optionalDependencies:
- '@img/sharp-libvips-linux-arm64': 1.3.4
+ '@img/sharp-libvips-linux-arm64': 1.3.2
optional: true
- '@img/sharp-linux-arm@0.35.5':
+ '@img/sharp-linux-arm@0.35.3':
optionalDependencies:
- '@img/sharp-libvips-linux-arm': 1.3.4
+ '@img/sharp-libvips-linux-arm': 1.3.2
optional: true
- '@img/sharp-linux-ppc64@0.35.5':
+ '@img/sharp-linux-ppc64@0.35.3':
optionalDependencies:
- '@img/sharp-libvips-linux-ppc64': 1.3.4
+ '@img/sharp-libvips-linux-ppc64': 1.3.2
optional: true
- '@img/sharp-linux-riscv64@0.35.5':
+ '@img/sharp-linux-riscv64@0.35.3':
optionalDependencies:
- '@img/sharp-libvips-linux-riscv64': 1.3.4
+ '@img/sharp-libvips-linux-riscv64': 1.3.2
optional: true
- '@img/sharp-linux-s390x@0.35.5':
+ '@img/sharp-linux-s390x@0.35.3':
optionalDependencies:
- '@img/sharp-libvips-linux-s390x': 1.3.4
+ '@img/sharp-libvips-linux-s390x': 1.3.2
optional: true
- '@img/sharp-linux-x64@0.35.5':
+ '@img/sharp-linux-x64@0.35.3':
optionalDependencies:
- '@img/sharp-libvips-linux-x64': 1.3.4
+ '@img/sharp-libvips-linux-x64': 1.3.2
optional: true
- '@img/sharp-linuxmusl-arm64@0.35.5':
+ '@img/sharp-linuxmusl-arm64@0.35.3':
optionalDependencies:
- '@img/sharp-libvips-linuxmusl-arm64': 1.3.4
+ '@img/sharp-libvips-linuxmusl-arm64': 1.3.2
optional: true
- '@img/sharp-linuxmusl-x64@0.35.5':
+ '@img/sharp-linuxmusl-x64@0.35.3':
optionalDependencies:
- '@img/sharp-libvips-linuxmusl-x64': 1.3.4
+ '@img/sharp-libvips-linuxmusl-x64': 1.3.2
optional: true
- '@img/sharp-wasm32@0.35.5':
+ '@img/sharp-wasm32@0.35.3':
dependencies:
- '@emnapi/runtime': 1.11.3
+ '@emnapi/runtime': 1.11.2
optional: true
- '@img/sharp-webcontainers-wasm32@0.35.5':
+ '@img/sharp-webcontainers-wasm32@0.35.3':
dependencies:
- '@img/sharp-wasm32': 0.35.5
+ '@img/sharp-wasm32': 0.35.3
optional: true
- '@img/sharp-win32-arm64@0.35.5':
+ '@img/sharp-win32-arm64@0.35.3':
optional: true
- '@img/sharp-win32-ia32@0.35.5':
+ '@img/sharp-win32-ia32@0.35.3':
optional: true
- '@img/sharp-win32-x64@0.35.5':
+ '@img/sharp-win32-x64@0.35.3':
optional: true
'@iovalkey/commands@0.1.0': {}
@@ -6440,7 +6430,7 @@ snapshots:
camelcase: 5.3.1
find-up: 4.1.0
get-package-type: 0.1.0
- js-yaml: 3.15.2
+ js-yaml: 3.15.1
resolve-from: 5.0.0
'@istanbuljs/schema@0.1.6': {}
@@ -6732,7 +6722,7 @@ snapshots:
dependencies:
'@qdrant/openapi-typescript-fetch': 1.2.6
typescript: 5.5.4
- undici: 7.30.2
+ undici: 7.29.0
'@qdrant/openapi-typescript-fetch@1.2.6': {}
@@ -7204,7 +7194,7 @@ snapshots:
'@turbopuffer/turbopuffer@2.5.0':
dependencies:
pako: 2.2.0
- undici: 7.30.2
+ undici: 7.29.0
'@types/babel__core@7.20.5':
dependencies:
@@ -7346,7 +7336,7 @@ snapshots:
'@zilliz/milvus2-sdk-node@3.0.3':
dependencies:
- '@grpc/grpc-js': 1.14.5
+ '@grpc/grpc-js': 1.14.4
'@grpc/proto-loader': 0.8.1
'@opentelemetry/api': 1.9.1
'@petamoriken/float16': 3.9.3
@@ -7372,7 +7362,7 @@ snapshots:
acorn@8.16.0: {}
- adm-zip@0.6.1: {}
+ adm-zip@0.6.0: {}
afinn-165-financialmarketnews@3.0.0: {}
@@ -7458,9 +7448,9 @@ snapshots:
aws4@1.13.2: {}
- axios@1.20.0:
+ axios@1.18.1:
dependencies:
- follow-redirects: 1.16.2
+ follow-redirects: 1.16.0
form-data: 4.0.6
https-proxy-agent: 5.0.1
proxy-from-env: 2.1.0
@@ -7533,7 +7523,7 @@ snapshots:
baseline-browser-mapping@2.11.21: {}
- basic-ftp@6.2.1: {}
+ basic-ftp@5.3.1: {}
better-sqlite3@12.10.0:
dependencies:
@@ -7563,7 +7553,7 @@ snapshots:
balanced-match: 1.0.2
concat-map: 0.0.1
- brace-expansion@2.1.7:
+ brace-expansion@2.1.4:
dependencies:
balanced-match: 1.0.2
@@ -7603,6 +7593,8 @@ snapshots:
buffer-from@1.1.2: {}
+ buffer-writer@2.0.0: {}
+
buffer@5.7.1:
dependencies:
base64-js: 1.5.1
@@ -7640,7 +7632,7 @@ snapshots:
cassandra-driver@4.8.0:
dependencies:
'@types/node': 18.19.130
- adm-zip: 0.6.1
+ adm-zip: 0.6.0
long: 5.2.5
chalk-template@0.4.0:
@@ -7868,7 +7860,7 @@ snapshots:
default-browser-id@5.0.1: {}
- default-browser@5.5.1:
+ default-browser@5.5.0:
dependencies:
bundle-name: 4.1.0
default-browser-id: 5.0.1
@@ -8142,7 +8134,7 @@ snapshots:
fn.name@1.1.0: {}
- follow-redirects@1.16.2: {}
+ follow-redirects@1.16.0: {}
foreground-child@3.3.1:
dependencies:
@@ -8233,7 +8225,7 @@ snapshots:
get-uri@6.0.5:
dependencies:
- basic-ftp: 6.2.1
+ basic-ftp: 5.3.1
data-uri-to-buffer: 6.0.2
debug: 4.4.3(supports-color@5.5.0)
transitivePeerDependencies:
@@ -8302,7 +8294,7 @@ snapshots:
google-gax@5.0.7:
dependencies:
- '@grpc/grpc-js': 1.14.5
+ '@grpc/grpc-js': 1.14.4
'@grpc/proto-loader': 0.8.1
duplexify: 4.1.3
google-auth-library: 10.5.0
@@ -8357,7 +8349,7 @@ snapshots:
guid-typescript@1.0.9: {}
- handlebars@4.7.10:
+ handlebars@4.7.9:
dependencies:
minimist: 1.2.8
neo-async: 2.6.2
@@ -8461,7 +8453,7 @@ snapshots:
transitivePeerDependencies:
- supports-color
- ip-address@10.7.2: {}
+ ip-address@10.4.0: {}
is-arrayish@0.2.1: {}
@@ -8489,8 +8481,6 @@ snapshots:
dependencies:
is-extglob: 2.1.1
- is-in-ssh@1.0.0: {}
-
is-inside-container@1.0.0:
dependencies:
is-docker: 3.0.0
@@ -8535,7 +8525,7 @@ snapshots:
'@babel/parser': 7.29.7
'@istanbuljs/schema': 0.1.6
istanbul-lib-coverage: 3.2.2
- semver: 7.8.5
+ semver: 7.8.4
transitivePeerDependencies:
- supports-color
@@ -8883,7 +8873,7 @@ snapshots:
js-tokens@4.0.0: {}
- js-yaml@3.15.2:
+ js-yaml@3.15.1:
dependencies:
argparse: 1.0.10
esprima: 4.0.1
@@ -8917,7 +8907,7 @@ snapshots:
lodash.isstring: 4.0.1
lodash.once: 4.1.1
ms: 2.1.3
- semver: 7.8.5
+ semver: 7.8.4
jwa@2.0.1:
dependencies:
@@ -9033,7 +9023,7 @@ snapshots:
make-dir@4.0.0:
dependencies:
- semver: 7.8.5
+ semver: 7.8.4
make-error@1.3.6: {}
@@ -9091,7 +9081,7 @@ snapshots:
minimatch@9.0.9:
dependencies:
- brace-expansion: 2.1.7
+ brace-expansion: 2.1.4
minimist@1.2.8: {}
@@ -9228,7 +9218,7 @@ snapshots:
nice-grpc@2.1.16:
dependencies:
- '@grpc/grpc-js': 1.14.5
+ '@grpc/grpc-js': 1.14.4
abort-controller-x: 0.5.0
nice-grpc-common: 2.0.3
@@ -9319,7 +9309,7 @@ snapshots:
onnxruntime-node@1.24.3:
dependencies:
- adm-zip: 0.6.1
+ adm-zip: 0.6.0
global-agent: 3.0.0
onnxruntime-common: 1.24.3
@@ -9332,14 +9322,12 @@ snapshots:
platform: 1.3.6
protobufjs: 7.6.5
- open@11.0.4:
+ open@10.2.0:
dependencies:
- default-browser: 5.5.1
+ default-browser: 5.5.0
define-lazy-prop: 3.0.0
- is-in-ssh: 1.0.0
is-inside-container: 1.0.0
- powershell-utils: 0.2.1
- wsl-utils: 1.0.1
+ wsl-utils: 0.1.0
open@8.4.2:
dependencies:
@@ -9421,6 +9409,8 @@ snapshots:
package-json-from-dist@1.0.1: {}
+ packet-reader@1.0.0: {}
+
pad-left@2.1.0:
dependencies:
repeat-string: 1.6.1
@@ -9468,6 +9458,10 @@ snapshots:
pg-numeric@1.0.2: {}
+ pg-pool@3.14.0(pg@8.11.3):
+ dependencies:
+ pg: 8.11.3
+
pg-pool@3.14.0(pg@8.21.0):
dependencies:
pg: 8.21.0
@@ -9492,6 +9486,18 @@ snapshots:
postgres-interval: 3.0.0
postgres-range: 1.1.4
+ pg@8.11.3:
+ dependencies:
+ buffer-writer: 2.0.0
+ packet-reader: 1.0.0
+ pg-connection-string: 2.13.0
+ pg-pool: 3.14.0(pg@8.11.3)
+ pg-protocol: 1.14.0
+ pg-types: 2.2.0
+ pgpass: 1.0.5
+ optionalDependencies:
+ pg-cloudflare: 1.4.0
+
pg@8.21.0:
dependencies:
pg-connection-string: 2.13.0
@@ -9554,8 +9560,6 @@ snapshots:
postgres-range@1.1.4: {}
- powershell-utils@0.2.1: {}
-
prebuild-install@7.1.3:
dependencies:
detect-libc: 2.1.2
@@ -9802,37 +9806,37 @@ snapshots:
dependencies:
type-fest: 0.13.1
- sharp@0.35.5(@types/node@22.19.21):
+ sharp@0.35.3(@types/node@22.19.21):
dependencies:
'@img/colour': 1.1.0
detect-libc: 2.1.2
semver: 7.8.5
optionalDependencies:
- '@img/sharp-darwin-arm64': 0.35.5
- '@img/sharp-darwin-x64': 0.35.5
- '@img/sharp-freebsd-wasm32': 0.35.5
- '@img/sharp-libvips-darwin-arm64': 1.3.4
- '@img/sharp-libvips-darwin-x64': 1.3.4
- '@img/sharp-libvips-linux-arm': 1.3.4
- '@img/sharp-libvips-linux-arm64': 1.3.4
- '@img/sharp-libvips-linux-ppc64': 1.3.4
- '@img/sharp-libvips-linux-riscv64': 1.3.4
- '@img/sharp-libvips-linux-s390x': 1.3.4
- '@img/sharp-libvips-linux-x64': 1.3.4
- '@img/sharp-libvips-linuxmusl-arm64': 1.3.4
- '@img/sharp-libvips-linuxmusl-x64': 1.3.4
- '@img/sharp-linux-arm': 0.35.5
- '@img/sharp-linux-arm64': 0.35.5
- '@img/sharp-linux-ppc64': 0.35.5
- '@img/sharp-linux-riscv64': 0.35.5
- '@img/sharp-linux-s390x': 0.35.5
- '@img/sharp-linux-x64': 0.35.5
- '@img/sharp-linuxmusl-arm64': 0.35.5
- '@img/sharp-linuxmusl-x64': 0.35.5
- '@img/sharp-webcontainers-wasm32': 0.35.5
- '@img/sharp-win32-arm64': 0.35.5
- '@img/sharp-win32-ia32': 0.35.5
- '@img/sharp-win32-x64': 0.35.5
+ '@img/sharp-darwin-arm64': 0.35.3
+ '@img/sharp-darwin-x64': 0.35.3
+ '@img/sharp-freebsd-wasm32': 0.35.3
+ '@img/sharp-libvips-darwin-arm64': 1.3.2
+ '@img/sharp-libvips-darwin-x64': 1.3.2
+ '@img/sharp-libvips-linux-arm': 1.3.2
+ '@img/sharp-libvips-linux-arm64': 1.3.2
+ '@img/sharp-libvips-linux-ppc64': 1.3.2
+ '@img/sharp-libvips-linux-riscv64': 1.3.2
+ '@img/sharp-libvips-linux-s390x': 1.3.2
+ '@img/sharp-libvips-linux-x64': 1.3.2
+ '@img/sharp-libvips-linuxmusl-arm64': 1.3.2
+ '@img/sharp-libvips-linuxmusl-x64': 1.3.2
+ '@img/sharp-linux-arm': 0.35.3
+ '@img/sharp-linux-arm64': 0.35.3
+ '@img/sharp-linux-ppc64': 0.35.3
+ '@img/sharp-linux-riscv64': 0.35.3
+ '@img/sharp-linux-s390x': 0.35.3
+ '@img/sharp-linux-x64': 0.35.3
+ '@img/sharp-linuxmusl-arm64': 0.35.3
+ '@img/sharp-linuxmusl-x64': 0.35.3
+ '@img/sharp-webcontainers-wasm32': 0.35.3
+ '@img/sharp-win32-arm64': 0.35.3
+ '@img/sharp-win32-ia32': 0.35.3
+ '@img/sharp-win32-x64': 0.35.3
'@types/node': 22.19.21
shebang-command@2.0.0:
@@ -9877,7 +9881,7 @@ snapshots:
socks@2.8.9:
dependencies:
- ip-address: 10.7.2
+ ip-address: 10.4.0
smart-buffer: 4.2.0
source-map-support@0.5.13:
@@ -10109,7 +10113,7 @@ snapshots:
dependencies:
bs-logger: 0.2.6
fast-json-stable-stringify: 2.1.0
- handlebars: 4.7.10
+ handlebars: 4.7.9
jest: 29.7.0(@types/node@22.19.21)(ts-node@10.9.2(@types/node@22.19.21)(typescript@5.5.4))
json5: 2.2.3
lodash.memoize: 4.1.2
@@ -10214,7 +10218,7 @@ snapshots:
undici-types@7.24.6: {}
- undici@7.30.2: {}
+ undici@7.29.0: {}
update-browserslist-db@1.3.2(browserslist@4.28.9):
dependencies:
@@ -10342,10 +10346,9 @@ snapshots:
ws@8.21.0: {}
- wsl-utils@1.0.1:
+ wsl-utils@0.1.0:
dependencies:
is-wsl: 3.1.1
- powershell-utils: 0.2.1
xml-naming@0.1.0: {}
diff --git a/mem0-ts/pnpm-workspace.yaml b/mem0-ts/pnpm-workspace.yaml
index 4a75a2cdc..4048a653c 100644
--- a/mem0-ts/pnpm-workspace.yaml
+++ b/mem0-ts/pnpm-workspace.yaml
@@ -6,15 +6,14 @@ onlyBuiltDependencies:
- better-sqlite3
overrides:
- "@azure/identity@<4.14.1": ">=4.14.1 <5.0.0"
"form-data@<4.0.6": ">=4.0.6"
"picomatch@<2.3.2": "^2.3.2"
"picomatch@>=4.0.0 <4.0.4": "^4.0.4"
"jws@4.0.0": "4.0.1"
- "js-yaml@<3.15.2": ">=3.15.2 <4.0.0"
- "js-yaml@>=4.0.0 <4.3.2": ">=4.3.2 <5.0.0"
- "sharp@<0.35.4": ">=0.35.4 <0.36.0"
- "adm-zip@<0.6.1": ">=0.6.1 <0.7.0"
+ "js-yaml@<3.15.1": ">=3.15.1 <4.0.0"
+ "js-yaml@>=4.0.0 <4.3.1": ">=4.3.1 <5.0.0"
+ "sharp@<0.35.0": ">=0.35.0 <0.36.0"
+ "adm-zip@<0.6.0": ">=0.6.0 <0.7.0"
"langsmith@<0.6.0": "^0.6.0"
"minimatch@<3.1.3": "^3.1.3"
"minimatch@>=5.0.0 <5.1.8": "^5.1.8"
@@ -28,23 +27,19 @@ overrides:
"glob@>=10.2.0 <10.5.0": "^10.5.0"
"@modelcontextprotocol/sdk": "^1.25.4"
"esbuild": ">=0.28.1"
- "undici@<7.30.1": ">=7.30.1 <8.0.0"
- "axios@<1.20.0": ">=1.20.0 <2.0.0"
+ "undici@<7.29.0": ">=7.29.0 <8.0.0"
+ "axios@<1.18.0": ">=1.18.0 <2.0.0"
"brace-expansion@<1.1.16": ">=1.1.16 <2.0.0"
- "brace-expansion@>=2.0.0 <2.1.6": ">=2.1.6 <3.0.0"
+ "brace-expansion@>=2.0.0 <2.1.4": ">=2.1.4 <3.0.0"
"brace-expansion@>=3.0.0 <5.0.8": ">=5.0.8 <6.0.0"
"fast-xml-parser@>=5.0.0 <5.10.1": ">=5.10.1 <6.0.0"
"tar@<7.5.21": ">=7.5.21 <8.0.0"
"thrift@<0.23.0": "^0.23.0"
"mongoose@>=9.0.0 <9.7.2": ">=9.7.2 <10.0.0"
"protobufjs@<7.6.5": ">=7.6.5 <8.0.0"
- "ip-address@<10.5.1": ">=10.5.1 <11.0.0"
+ "ip-address@<10.3.1": ">=10.3.1 <11.0.0"
"browserslist@<4.28.7": ">=4.28.7 <5.0.0"
"mysql2@<3.23.1": ">=3.23.1 <4.0.0"
- "basic-ftp@<6.2.1": ">=6.2.1 <7.0.0"
- "@grpc/grpc-js@>=1.14.0 <1.14.5": ">=1.14.5 <2.0.0"
- "handlebars@<4.7.10": ">=4.7.10 <5.0.0"
- "follow-redirects@<1.16.2": ">=1.16.2 <2.0.0"
patchedDependencies:
"tar@7.5.22": "patches/tar@7.5.22.patch"
diff --git a/mem0-ts/src/client/index.ts b/mem0-ts/src/client/index.ts
index 138b29dc7..24ec5b8f4 100644
--- a/mem0-ts/src/client/index.ts
+++ b/mem0-ts/src/client/index.ts
@@ -23,14 +23,6 @@ export type {
FeedbackPayload,
CreateMemoryExportPayload,
GetMemoryExportPayload,
- ProfileEntityType,
- ProfileStatus,
- ProfileResponse,
- ProfileJobResponse,
- ProfileJobStatus,
- ProfileSettings,
- ProfileSettingsResponse,
- EntityProfileSettings,
} from "./mem0.types";
// Re-export enums as values (not type-only)
diff --git a/mem0-ts/src/client/mem0.ts b/mem0-ts/src/client/mem0.ts
index c386be323..ff259f2fe 100644
--- a/mem0-ts/src/client/mem0.ts
+++ b/mem0-ts/src/client/mem0.ts
@@ -1,5 +1,4 @@
import axios from "axios";
-import { v7 as uuidv7 } from "uuid";
import {
AllUsers,
PaginatedMemories,
@@ -21,12 +20,6 @@ import {
FeedbackPayload,
CreateMemoryExportPayload,
GetMemoryExportPayload,
- ProfileEntityType,
- ProfileResponse,
- ProfileJobResponse,
- ProfileJobStatus,
- ProfileSettings,
- ProfileSettingsResponse,
} from "./mem0.types";
import {
captureClientEvent,
@@ -74,34 +67,6 @@ function rejectTopLevelEntityParams(
}
}
-function rejectFilters(
- options: Record | undefined,
- methodName: string,
-): void {
- if (options?.filters != null) {
- throw new Error(
- `filters is not supported in ${methodName}(). ` +
- `Pass entity IDs at the top level, e.g. userId: "...".`,
- );
- }
-}
-
-/** Throws on an empty entity ID, which the API treats as matching every memory. */
-function rejectBlankEntityIds(options: Record | undefined): void {
- for (const [key, value] of Object.entries(options ?? {})) {
- if (
- ENTITY_PARAMS.includes(key) &&
- typeof value === "string" &&
- value.trim() === ""
- ) {
- throw new Error(
- `${key} cannot be empty or whitespace-only: an empty ID would match every memory in the project. ` +
- `To delete everything on purpose, call deleteAll() with "*" explicitly.`,
- );
- }
- }
-}
-
function encodePathSegment(value: unknown): string {
return encodeURIComponent(String(value));
}
@@ -127,72 +92,9 @@ interface ClientIdentity {
}
// Shares one ping per (host, api key) across clients; FIFO-capped.
-// One collection for every generation; the operation is a body field.
-const PROFILE_JOBS_PATH = "/v2/profiles/jobs/";
-
const IDENTITY_CACHE_MAX_DEFAULT = 50;
const identityByCredentials = new Map>();
-declare const __MEM0_SDK_VERSION__: string | undefined;
-
-// Injected by tsup (see mem0-ts/tsup.config.ts `define`), the same mechanism
-// telemetry.ts already uses. A hardcoded literal goes stale at the next release
-// bump and then misreports the client version forever.
-const SDK_VERSION =
- typeof __MEM0_SDK_VERSION__ !== "undefined" ? __MEM0_SDK_VERSION__ : "dev";
-
-const MAX_STACK_ENTRIES = 4;
-const MAX_STACK_CHARS = 200;
-
-/**
- * Append our own entry and bound the result, dropping WHOLE entries.
- *
- * Neither cap cuts characters: slicing the joined string severs an identifier
- * and leaves a fragment the platform parses as a real client name. And the
- * reserved slot is ours. Pushing first and then trimming to four dropped exactly
- * the entry this exists to add whenever a caller already sent four, so we
- * vanished from our own stack while every caller claim survived.
- */
-function boundedStack(callerEntries: string[], own: string): string {
- const kept: string[] = [];
- let budget = MAX_STACK_CHARS - own.length;
- for (const entry of callerEntries.slice(0, MAX_STACK_ENTRIES - 1)) {
- const cost = entry.length + ", ".length;
- if (cost > budget) break;
- budget -= cost;
- kept.push(entry);
- }
- return [...kept, own].join(", ");
-}
-
-/**
- * Surface-identity headers.
- *
- * X-Mem0-Source and X-Application are SET-ONCE by contract: whichever layer is
- * outermost sets them and nothing below overwrites, so a plugin wrapping this
- * SDK keeps its own identity. X-Mem0-Client is APPEND-ONLY - every layer adds
- * itself, so the platform sees the whole stack and not just the last speaker.
- */
-function surfaceHeaders(): Record {
- const env: Record =
- typeof process !== "undefined" && process.env ? process.env : {};
- const existing = (env.MEM0_CLIENT_STACK ?? "").trim();
- const entries = existing
- ? existing
- .split(",")
- .map((part) => part.trim())
- .filter(Boolean)
- : [];
- const headers: Record = {
- "X-Mem0-Client": boundedStack(entries, `mem0-js/${SDK_VERSION}`),
- };
- const source = (env.MEM0_SOURCE ?? "").trim();
- if (source) headers["X-Mem0-Source"] = source;
- const application = (env.MEM0_APPLICATION ?? "").trim();
- if (application) headers["X-Application"] = application;
- return headers;
-}
-
export default class MemoryClient {
apiKey: string;
host: string;
@@ -227,7 +129,6 @@ export default class MemoryClient {
this.headers = {
Authorization: `Token ${this.apiKey}`,
"Content-Type": "application/json",
- ...surfaceHeaders(),
};
this.client = axios.create({
@@ -343,8 +244,7 @@ export default class MemoryClient {
});
}
- /** Fetch with no key conversion, for payloads carrying user-controlled property names. */
- async _fetchRawJson(url: string, options: any): Promise {
+ async _fetchWithErrorHandling(url: string, options: any): Promise {
const response = await fetch(url, {
...options,
headers: {
@@ -357,11 +257,8 @@ export default class MemoryClient {
const errorData = await response.text();
throw createExceptionFromResponse(response.status, errorData);
}
- return response.json();
- }
-
- async _fetchWithErrorHandling(url: string, options: any): Promise {
- return snakeToCamelKeys(await this._fetchRawJson(url, options));
+ const jsonResponse = await response.json();
+ return snakeToCamelKeys(jsonResponse);
}
_preparePayload(
@@ -424,7 +321,6 @@ export default class MemoryClient {
if (!messages || (Array.isArray(messages) && messages.length === 0)) {
throw new Error("Cannot process an empty messages payload.");
}
- rejectFilters(options, "add");
const payload = this._preparePayload(messages, options);
const payloadKeys = Object.keys(payload);
@@ -569,8 +465,6 @@ export default class MemoryClient {
async deleteAll(
options: DeleteAllMemoryOptions = {},
): Promise<{ message: string }> {
- rejectFilters(options, "deleteAll");
- rejectBlankEntityIds(options);
const payloadKeys = Object.keys(options || {});
this._captureEvent("delete_all", [payloadKeys]);
const snakeOptions = camelToSnakeKeys(this._prepareParams(options));
@@ -642,7 +536,6 @@ export default class MemoryClient {
runId?: string;
} = {},
): Promise<{ message: string }> {
- rejectBlankEntityIds(params);
let to_delete: Array<{ type: string; name: string }> = [];
const { userId, agentId, appId, runId } = params;
@@ -862,192 +755,6 @@ export default class MemoryClient {
return response;
}
- /**
- * Get the memory profile for a single user.
- *
- * Branch on `status`, not on an empty `profile`: generation is asynchronous,
- * so a known user without a profile yet is a normal response.
- */
- async getProfile(data: { entityId: string }): Promise {
- this._captureEvent("get_profile", []);
- await this._awaitIdentity();
-
- const response = await this._fetchWithErrorHandling(
- `${this.host}/v2/entities/user/${encodeURIComponent(data.entityId)}/profile/`,
- {
- headers: this.headers,
- },
- );
- return response;
- }
-
- /**
- * Generate or refresh the profile for one user, now.
- *
- * Profiles are otherwise built once a user crosses an internal message
- * threshold, so a new user has none for its first few memories. Returns as
- * soon as the work is queued: poll {@link getProfile} and branch on `status`.
- *
- * Pass `idempotencyKey` and reuse it to retry a lost request without starting
- * (and being billed for) a second job.
- */
- async generateProfile(data: {
- entityId: string;
- idempotencyKey?: string;
- }): Promise {
- this._captureEvent("generate_profile", []);
- await this._awaitIdentity();
-
- const response = await this._fetchWithErrorHandling(
- `${this.host}${PROFILE_JOBS_PATH}`,
- {
- method: "POST",
- headers: {
- ...this.headers,
- "Idempotency-Key": data.idempotencyKey ?? uuidv7(),
- },
- body: JSON.stringify({
- operation: "trigger",
- entity_type: "user",
- entity_id: data.entityId,
- }),
- },
- );
- return response;
- }
-
- /** Get the profile settings for the current project. */
- async getProfileSettings(): Promise {
- this._captureEvent("get_profile_settings", []);
- await this._awaitIdentity();
-
- const raw = await this._fetchRawJson(`${this.host}/v2/profiles/settings/`, {
- headers: this.headers,
- });
- return this._settingsWithVerbatimSchema(raw);
- }
-
- /**
- * The envelope keys are ours; the schema's property names are the customer's.
- *
- * Each entity type carries its own schema, so every one has to be restored
- * from the raw body โ otherwise camel-casing rewrites the customer's field
- * names and a profile comes back under keys they never chose.
- */
- private _settingsWithVerbatimSchema(raw: any): ProfileSettingsResponse {
- const settings = snakeToCamelKeys(raw) as ProfileSettingsResponse;
- if (!raw || typeof raw !== "object") {
- return settings;
- }
-
- const rawEntities = raw.entities;
- if (rawEntities && typeof rawEntities === "object") {
- for (const [entityType, entitySettings] of Object.entries(rawEntities)) {
- if (
- entitySettings &&
- typeof entitySettings === "object" &&
- "schema" in entitySettings &&
- settings.entities?.[entityType as ProfileEntityType]
- ) {
- settings.entities[entityType as ProfileEntityType]!.schema = (
- entitySettings as Record
- ).schema;
- }
- }
- }
-
- return settings;
- }
-
- /**
- * Update profile settings. Only the fields you pass are written.
- *
- * `schema` and `customInstructions` are per user and are nested under
- * `entities` for the API; only `enabled` is project-wide. Sending them flat
- * is rejected with `Unsupported settings`.
- */
- async updateProfileSettings(
- settings: ProfileSettings,
- ): Promise {
- const payloadKeys = Object.keys(settings || {});
- this._captureEvent("update_profile_settings", [payloadKeys]);
- await this._awaitIdentity();
-
- const { schema, customInstructions, enabled } = settings || {};
-
- const body: Record = {};
- if (enabled !== undefined) {
- body.enabled = enabled;
- }
-
- const entitySettings: Record = {};
- // The schema's property names are the customer's and must reach the API verbatim.
- if (schema !== undefined) {
- entitySettings.schema = schema;
- }
- if (customInstructions !== undefined) {
- entitySettings.custom_instructions = customInstructions;
- }
- if (Object.keys(entitySettings).length > 0) {
- body.entities = { user: entitySettings };
- }
-
- const raw = await this._fetchRawJson(`${this.host}/v2/profiles/settings/`, {
- method: "POST",
- headers: this.headers,
- body: JSON.stringify(body),
- });
- return this._settingsWithVerbatimSchema(raw);
- }
-
- /**
- * Generate profiles for a few real users, to check a schema.
- *
- * Real generations against real memories, and the results are kept: the
- * profiles are written to those users and count toward usage.
- */
- async sampleProfiles(data?: {
- limit?: number;
- idempotencyKey?: string;
- }): Promise {
- this._captureEvent("sample_profiles", []);
- await this._awaitIdentity();
-
- const response = await this._fetchWithErrorHandling(
- `${this.host}${PROFILE_JOBS_PATH}`,
- {
- method: "POST",
- headers: {
- ...this.headers,
- "Idempotency-Key": data?.idempotencyKey ?? uuidv7(),
- },
- body: JSON.stringify({
- operation: "sample",
- // Required: the API refuses a job that does not name an entity kind.
- entity_type: "user",
- ...this._prepareParams({ limit: data?.limit }),
- }),
- },
- );
- return response;
- }
-
- /**
- * Read one generation job. Accepts the `statusUrl` from a create call, or a
- * bare job id. Prefer `statusUrl` so a route change needs no client update.
- */
- async getProfileJob(jobIdOrStatusUrl: string): Promise {
- await this._awaitIdentity();
-
- const path = jobIdOrStatusUrl.startsWith("/")
- ? jobIdOrStatusUrl
- : `${PROFILE_JOBS_PATH}${jobIdOrStatusUrl}/`;
- return this._fetchWithErrorHandling(`${this.host}${path}`, {
- method: "GET",
- headers: this.headers,
- });
- }
-
async createMemoryExport(
data: CreateMemoryExportPayload,
): Promise<{ message: string; id: string }> {
diff --git a/mem0-ts/src/client/mem0.types.ts b/mem0-ts/src/client/mem0.types.ts
index a178f4529..c230441e0 100644
--- a/mem0-ts/src/client/mem0.types.ts
+++ b/mem0-ts/src/client/mem0.types.ts
@@ -30,9 +30,6 @@ export interface SearchMemoryOptions {
showExpired?: boolean;
referenceDate?: string | number;
keywordSearch?: boolean;
- /** Surface that produced the call, e.g. "OPENCLAW". Must be a value the
- * backend's EventSource enum knows, or it buckets into OTHERS. */
- source?: string;
}
export interface GetAllMemoryOptions {
@@ -125,8 +122,6 @@ export interface Memory {
categories?: Array;
createdAt?: Date;
updatedAt?: Date;
- // TODO: Review this response field for removal in a future breaking release.
- // It is not a selectable memory type; TypeScript has no procedural-memory path.
memoryType?: string;
score?: number;
metadata?: any | null;
@@ -241,98 +236,3 @@ export interface GetMemoryExportPayload {
filters?: Record;
memoryExportId?: string;
}
-
-// โโโ Profile Types โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
-
-/** The entity kind that carries a profile. */
-export type ProfileEntityType = "user";
-
-/**
- * `succeeded` is the only state in which `profile` is guaranteed to hold content.
- *
- * These are values, not keys, so the client does not camel-case them: the wire
- * spelling is what a comparison has to match.
- */
-export type ProfileStatus =
- | "succeeded"
- | "pending"
- | "failed"
- | "not_enabled"
- | "insufficient_data";
-
-export interface ProfileResponse {
- /** Shaped by the project's schema; keys are not camel-cased. */
- profile: Record;
- status: ProfileStatus;
- entityType: ProfileEntityType;
- entityId: string;
- updatedAt: string | null;
- generationCount: number;
- /** The last generation's failure reason, when `status` is `failed`. */
- error?: string | null;
-}
-
-/** Every accepted generation. `statusUrl` is the server's own poll path. */
-export interface ProfileJobResponse {
- jobId: string;
- status: string;
- statusUrl: string;
- operation: string;
- entityType: ProfileEntityType;
- /** Entities reserved against usage for this job. */
- entityCountReserved?: number;
- /** Null when the job has no associated event. */
- eventId?: string | null;
- replayed?: boolean;
- /** Sample runs only: how many entities were picked. */
- sampled?: number;
- /** Sample runs only: the entity ids picked. Read each one with `getProfile`. */
- entityIds?: string[];
-}
-
-/** The settings to write. `schema` and `customInstructions` apply to user profiles. */
-export interface ProfileSettings {
- /** Turn profile generation on or off. Project-wide. */
- enabled?: boolean;
- /** JSON Schema for the profile. Every property needs a `description`. */
- schema?: Record | null;
- customInstructions?: string | null;
-}
-
-/** One entity type's stored configuration. */
-export interface EntityProfileSettings {
- /** The customer's JSON Schema, with its property names verbatim. */
- schema?: Record | null;
- customInstructions?: string | null;
- [key: string]: any;
-}
-
-/**
- * The settings as stored. `schema` and `customInstructions` are per entity
- * type and nest under `entities`; only `enabled` is project-wide.
- */
-export interface ProfileSettingsResponse {
- enabled?: boolean;
- entities?: Partial>;
- capabilities?: Record;
- [key: string]: any;
-}
-
-/** `GET /v2/profiles/jobs/{id}/`. The job nests under `job`. */
-export interface ProfileJobStatus {
- job: {
- id: string;
- operation: string;
- entityType: ProfileEntityType;
- status: string;
- /** Null until `enumerationComplete`. */
- total: number | null;
- enumerationComplete: boolean;
- /** succeeded + failed + skipped. */
- completed: number;
- succeeded: number;
- failed: number;
- skipped: number;
- [key: string]: any;
- };
-}
diff --git a/mem0-ts/src/client/tests/memoryClient.entityGuards.test.ts b/mem0-ts/src/client/tests/memoryClient.entityGuards.test.ts
deleted file mode 100644
index 463284852..000000000
--- a/mem0-ts/src/client/tests/memoryClient.entityGuards.test.ts
+++ /dev/null
@@ -1,234 +0,0 @@
-/** MemoryClient unit tests for entity ID handling in add, deleteAll, and deleteUsers. */
-import { MemoryClient } from "../mem0";
-import { createMockAllUsers, createMockUser, TEST_API_KEY } from "./helpers";
-import {
- setupMockFetch,
- findFetchCall,
- getFetchBody,
- installConsoleSuppression,
-} from "./setup";
-
-installConsoleSuppression();
-
-const BLANK_IDS = ["", " ", "\t\n"];
-const ENTITY_KEYS = [
- "userId",
- "agentId",
- "appId",
- "runId",
- "user_id",
- "agent_id",
- "app_id",
- "run_id",
-];
-
-function mockDeleteAll() {
- const extra = new Map();
- extra.set("/v1/memories/", { status: 200, body: { message: "Deleted" } });
- return setupMockFetch(extra);
-}
-
-describe("MemoryClient - deleteAll() blank entity IDs", () => {
- test.each(
- ENTITY_KEYS.flatMap((key) => BLANK_IDS.map((blank) => [key, blank])),
- )("rejects %s=%j without sending a request", async (key, blank) => {
- const mock = mockDeleteAll();
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
-
- await expect(client.deleteAll({ [key]: blank } as never)).rejects.toThrow(
- key,
- );
-
- expect(findFetchCall(mock, "/v1/memories/", "DELETE")).toBeUndefined();
- });
-
- test("rejects a blank ID next to a valid ID", async () => {
- const mock = mockDeleteAll();
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
-
- await expect(
- client.deleteAll({ userId: "u1", agentId: "" }),
- ).rejects.toThrow("agentId");
-
- expect(findFetchCall(mock, "/v1/memories/", "DELETE")).toBeUndefined();
- });
-
- test("error explains the risk and the wildcard", async () => {
- mockDeleteAll();
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
-
- await expect(client.deleteAll({ userId: "" })).rejects.toThrow(
- /every memory in the project.*"\*"/,
- );
- });
-});
-
-describe("MemoryClient - deleteAll() valid inputs", () => {
- test("sends the entity ID as a query param", async () => {
- const mock = mockDeleteAll();
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
-
- await client.deleteAll({ userId: "u1" });
-
- const call = findFetchCall(mock, "/v1/memories/?", "DELETE");
- expect(call![0]).toContain("user_id=u1");
- });
-
- test("still allows the explicit wildcard", async () => {
- const mock = mockDeleteAll();
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
-
- await client.deleteAll({ userId: "*" });
-
- const call = findFetchCall(mock, "/v1/memories/?", "DELETE");
- expect(call![0]).toContain("user_id=*");
- });
-
- test("ignores undefined entity IDs", async () => {
- const mock = mockDeleteAll();
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
-
- await client.deleteAll({ userId: "u1", agentId: undefined });
-
- const call = findFetchCall(mock, "/v1/memories/?", "DELETE");
- expect(call![0]).not.toContain("agent_id");
- });
-});
-
-describe("MemoryClient - deleteAll() rejects filters", () => {
- test("throws and sends no request", async () => {
- const mock = mockDeleteAll();
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
-
- await expect(
- client.deleteAll({ filters: { user_id: "u1" } } as never),
- ).rejects.toThrow(/filters.*userId/);
-
- expect(findFetchCall(mock, "/v1/memories/", "DELETE")).toBeUndefined();
- });
-});
-
-describe("MemoryClient - deleteUsers() blank entity IDs", () => {
- test.each(
- ["userId", "agentId", "appId", "runId"].flatMap((key) =>
- BLANK_IDS.map((blank) => [key, blank]),
- ),
- )("rejects %s=%j before any request", async (key, blank) => {
- const extra = new Map();
- extra.set("/v1/entities/", {
- status: 200,
- body: createMockAllUsers([createMockUser()]),
- });
- const mock = setupMockFetch(extra);
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
-
- await expect(client.deleteUsers({ [key]: blank })).rejects.toThrow(key);
-
- expect(findFetchCall(mock, "/v1/entities/")).toBeUndefined();
- expect(findFetchCall(mock, "/v2/entities/", "DELETE")).toBeUndefined();
- });
-});
-
-describe("MemoryClient - deleteUsers() valid inputs", () => {
- test("deletes the named entity", async () => {
- const extra = new Map();
- extra.set("/v2/entities/user/u1/", {
- status: 200,
- body: { message: "ok" },
- });
- const mock = setupMockFetch(extra);
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
-
- await client.deleteUsers({ userId: "u1" });
-
- expect(
- findFetchCall(mock, "/v2/entities/user/u1/", "DELETE"),
- ).toBeDefined();
- });
-
- test("with no IDs still deletes every listed entity", async () => {
- const extra = new Map();
- extra.set("/v1/entities/", {
- status: 200,
- body: createMockAllUsers([
- createMockUser({ name: "u1", type: "user" }),
- createMockUser({ name: "a1", type: "agent" }),
- ]),
- });
- extra.set("/v2/entities/user/u1/", {
- status: 200,
- body: { message: "ok" },
- });
- extra.set("/v2/entities/agent/a1/", {
- status: 200,
- body: { message: "ok" },
- });
- const mock = setupMockFetch(extra);
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
-
- await client.deleteUsers();
-
- expect(
- findFetchCall(mock, "/v2/entities/user/u1/", "DELETE"),
- ).toBeDefined();
- expect(
- findFetchCall(mock, "/v2/entities/agent/a1/", "DELETE"),
- ).toBeDefined();
- });
-});
-
-describe("MemoryClient - add() entity IDs", () => {
- function mockAdd() {
- const extra = new Map();
- extra.set("/v3/memories/add/", { status: 200, body: [] });
- return setupMockFetch(extra);
- }
-
- test("rejects filters and sends no request", async () => {
- const mock = mockAdd();
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
-
- await expect(
- client.add([{ role: "user", content: "hi" }], {
- filters: { user_id: "u1" },
- }),
- ).rejects.toThrow(/filters.*userId/);
-
- expect(findFetchCall(mock, "/v3/memories/add/", "POST")).toBeUndefined();
- });
-
- test("treats filters: undefined as not provided", async () => {
- const mock = mockAdd();
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
-
- await client.add([{ role: "user", content: "hi" }], {
- userId: "u1",
- filters: undefined,
- });
-
- const call = findFetchCall(mock, "/v3/memories/add/", "POST");
- expect(getFetchBody(call!).user_id).toBe("u1");
- });
-
- test("sends top-level entity IDs in the body", async () => {
- const mock = mockAdd();
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
-
- await client.add([{ role: "user", content: "hi" }], {
- userId: "u1",
- agentId: "a1",
- appId: "p1",
- runId: "r1",
- });
-
- const body = getFetchBody(
- findFetchCall(mock, "/v3/memories/add/", "POST")!,
- );
- expect(body).toMatchObject({
- user_id: "u1",
- agent_id: "a1",
- app_id: "p1",
- run_id: "r1",
- });
- });
-});
diff --git a/mem0-ts/src/client/tests/memoryClient.profiles.test.ts b/mem0-ts/src/client/tests/memoryClient.profiles.test.ts
deleted file mode 100644
index 27069a570..000000000
--- a/mem0-ts/src/client/tests/memoryClient.profiles.test.ts
+++ /dev/null
@@ -1,341 +0,0 @@
-/**
- * MemoryClient unit tests โ profiles.
- * Verifies request construction and the verbatim round-trip of user-controlled
- * profile/schema keys, not mock response echo.
- */
-import { MemoryClient } from "../mem0";
-import type { ProfileStatus } from "../mem0.types";
-import { TEST_API_KEY } from "./helpers";
-import {
- setupMockFetch,
- findFetchCall,
- getFetchBody,
- installConsoleSuppression,
-} from "./setup";
-
-installConsoleSuppression();
-
-describe("MemoryClient - getProfile()", () => {
- test("reads the v2 entity route and keeps profile keys verbatim", async () => {
- const extra = new Map();
- extra.set("/v2/entities/user/alice/profile/", {
- status: 200,
- body: {
- // Customer schema keys: camel-casing these would break the schema they wrote.
- profile: {
- favorite_topics: ["hiking"],
- work_style: { preferred_hours: "mornings" },
- },
- status: "succeeded",
- entity_type: "user",
- entity_id: "alice",
- updated_at: "2026-02-08T00:00:00Z",
- generation_count: 3,
- },
- });
- const mock = setupMockFetch(extra);
-
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
- const result = await client.getProfile({ entityId: "alice" });
-
- const call = findFetchCall(mock, "/v2/entities/user/alice/profile/");
- expect(call).toBeDefined();
-
- expect(result.profile).toEqual({
- favorite_topics: ["hiking"],
- work_style: { preferred_hours: "mornings" },
- });
- expect(result.entityType).toBe("user");
- expect(result.entityId).toBe("alice");
- expect(result.generationCount).toBe(3);
- expect(result.status).toBe("succeeded");
- });
-
- test("status keeps its wire spelling", async () => {
- // A status is a VALUE, not a key, so the client does not camel-case it.
- // Declaring the union as `insufficientData` made tsc reject the comparison
- // that works and accept one that can never be true.
- const extra = new Map();
- extra.set("/v2/entities/user/bob/profile/", {
- status: 200,
- body: {
- profile: {},
- status: "insufficient_data",
- entity_type: "user",
- entity_id: "bob",
- },
- });
- setupMockFetch(extra);
-
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
- const result = await client.getProfile({ entityId: "bob" });
-
- expect(result.status).toBe("insufficient_data");
- // Assignable without a cast: the declared union must contain the wire value.
- const status: ProfileStatus = result.status;
- expect(status).not.toBe("insufficientData");
- });
-
- test("scopes to user and encodes the entity id", async () => {
- const extra = new Map();
- extra.set("/v2/entities/user/", {
- status: 200,
- body: { profile: {}, status: "pending", entity_type: "user" },
- });
- const mock = setupMockFetch(extra);
-
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
- await client.getProfile({ entityId: "a/b" });
-
- const call = findFetchCall(mock, "/v2/entities/user/a%2Fb/profile/");
- expect(call).toBeDefined();
- });
-});
-
-describe("MemoryClient - generateProfile()", () => {
- test("sends operation trigger with the entity to the jobs collection", async () => {
- const extra = new Map();
- extra.set("/v2/profiles/jobs/", {
- status: 202,
- body: {
- job_id: "00000000-0000-7000-8000-000000000001",
- status: "QUEUED",
- status_url: "/v2/profiles/jobs/00000000-0000-7000-8000-000000000001/",
- operation: "trigger",
- entity_type: "user",
- entity_count_reserved: 1,
- event_id: "00000000-0000-7000-8000-000000000002",
- replayed: false,
- },
- });
- const mock = setupMockFetch(extra);
-
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
- const result = await client.generateProfile({ entityId: "alice" });
-
- const call = findFetchCall(mock, "/v2/profiles/jobs/", "POST");
- expect(call).toBeDefined();
- const body = getFetchBody(call!);
- expect(body.operation).toBe("trigger");
- expect(body.entity_type).toBe("user");
- expect(body.entity_id).toBe("alice");
- // A generated Idempotency-Key is always sent so the create can be retried safely.
- const headers = call![1].headers as Record;
- expect(headers["Idempotency-Key"]).toBeTruthy();
- expect(result.jobId).toBe("00000000-0000-7000-8000-000000000001");
- expect(result.statusUrl).toBe(
- "/v2/profiles/jobs/00000000-0000-7000-8000-000000000001/",
- );
- expect(result.replayed).toBe(false);
- });
-
- test("reuses a caller-supplied idempotency key", async () => {
- const extra = new Map();
- extra.set("/v2/profiles/jobs/", {
- status: 202,
- body: {
- job_id: "j1",
- status: "QUEUED",
- status_url: "/v2/profiles/jobs/j1/",
- operation: "trigger",
- entity_type: "user",
- },
- });
- const mock = setupMockFetch(extra);
-
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
- await client.generateProfile({
- entityId: "alice",
- idempotencyKey: "retry-key-123",
- });
-
- const call = findFetchCall(mock, "/v2/profiles/jobs/", "POST");
- const headers = call![1].headers as Record;
- expect(headers["Idempotency-Key"]).toBe("retry-key-123");
- });
-});
-
-describe("MemoryClient - profile settings", () => {
- test("sends schema property names verbatim and returns them unchanged", async () => {
- const schema = {
- type: "object",
- properties: {
- favorite_topics: {
- type: "array",
- description: "Topics the user returns to",
- items: { type: "string" },
- },
- workStyle: {
- type: "string",
- description: "How the user prefers to work",
- },
- },
- };
-
- const extra = new Map();
- extra.set("/v2/profiles/settings/", {
- status: 200,
- body: {
- enabled: true,
- entities: {
- user: {
- schema,
- custom_instructions: "Focus on durable preferences",
- },
- },
- },
- });
- const mock = setupMockFetch(extra);
-
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
- const result = await client.updateProfileSettings({
- enabled: true,
- schema,
- customInstructions: "Focus on durable preferences",
- });
-
- const call = findFetchCall(mock, "/v2/profiles/settings/", "POST");
- expect(call).toBeDefined();
- const body = getFetchBody(call!);
-
- // Mixed casing goes out exactly as written, nested under the entity type.
- // Exact, not a subset match: the customer's keys must go out unchanged.
- expect(body.entities).toEqual({
- user: { schema, custom_instructions: "Focus on durable preferences" },
- });
- expect(body.enabled).toBe(true);
- // A flat schema is rejected by the API with "Unsupported settings".
- expect("schema" in body).toBe(false);
-
- // And the customer's property names survive the round trip.
- expect(result.entities?.user?.schema).toEqual(schema);
- expect(result.entities?.user?.customInstructions).toBe(
- "Focus on durable preferences",
- );
- });
-
- test("scopes entity-level settings under user", async () => {
- const extra = new Map();
- extra.set("/v2/profiles/settings/", {
- status: 200,
- body: { enabled: true },
- });
- const mock = setupMockFetch(extra);
-
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
- await client.updateProfileSettings({
- schema: { type: "object", properties: {} },
- });
-
- const body = getFetchBody(
- findFetchCall(mock, "/v2/profiles/settings/", "POST")!,
- );
- expect(Object.keys(body.entities as object)).toEqual(["user"]);
- });
-
- test("omits fields the caller did not set", async () => {
- const extra = new Map();
- extra.set("/v2/profiles/settings/", {
- status: 200,
- body: {
- enabled: false,
- entities: { user: { schema: null, custom_instructions: null } },
- },
- });
- const mock = setupMockFetch(extra);
-
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
- await client.updateProfileSettings({ enabled: false });
-
- const call = findFetchCall(mock, "/v2/profiles/settings/", "POST");
- const body = getFetchBody(call!);
- expect(body.enabled).toBe(false);
- // Nothing entity-scoped was passed, so no entities key is sent at all.
- expect("entities" in body).toBe(false);
- expect("schema" in body).toBe(false);
- expect("custom_instructions" in body).toBe(false);
- });
-
- test("getProfileSettings reads the v2 route", async () => {
- const extra = new Map();
- extra.set("/v2/profiles/settings/", {
- status: 200,
- body: {
- enabled: true,
- entities: {
- user: {
- schema: { properties: { favorite_topics: { type: "array" } } },
- custom_instructions: null,
- },
- },
- capabilities: { full_rebuild: false },
- },
- });
- const mock = setupMockFetch(extra);
-
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
- const result = await client.getProfileSettings();
-
- expect(findFetchCall(mock, "/v2/profiles/settings/")).toBeDefined();
- expect(result.enabled).toBe(true);
- expect(result.entities?.user?.schema).toEqual({
- properties: { favorite_topics: { type: "array" } },
- });
- expect(result.capabilities?.fullRebuild).toBe(false);
- });
-});
-
-describe("MemoryClient - sampleProfiles()", () => {
- test("sampleProfiles omits limit when unset", async () => {
- const extra = new Map();
- extra.set("/v2/profiles/jobs/", {
- status: 202,
- body: {
- job_id: "job_1",
- status: "QUEUED",
- status_url: "/v2/profiles/jobs/job_1/",
- operation: "sample",
- entity_type: "user",
- sampled: 5,
- results: [],
- },
- });
- const mock = setupMockFetch(extra);
-
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
- await client.sampleProfiles();
-
- const call = findFetchCall(mock, "/v2/profiles/jobs/", "POST");
- // Every job names an entity kind: the API refuses one that does not.
- expect(getFetchBody(call!)).toEqual({
- operation: "sample",
- entity_type: "user",
- });
- });
-
- test("sampleProfiles passes an explicit limit", async () => {
- const extra = new Map();
- extra.set("/v2/profiles/jobs/", {
- status: 202,
- body: {
- job_id: "job_2",
- status: "QUEUED",
- status_url: "/v2/profiles/jobs/job_2/",
- operation: "sample",
- entity_type: "user",
- sampled: 3,
- results: [],
- },
- });
- const mock = setupMockFetch(extra);
-
- const client = new MemoryClient({ apiKey: TEST_API_KEY });
- const result = await client.sampleProfiles({ limit: 3 });
-
- const call = findFetchCall(mock, "/v2/profiles/jobs/", "POST");
- expect(getFetchBody(call!).operation).toBe("sample");
- expect(getFetchBody(call!).limit).toBe(3);
- expect(getFetchBody(call!).entity_type).toBe("user");
- expect(result.sampled).toBe(3);
- });
-});
diff --git a/mem0-ts/src/client/utils.ts b/mem0-ts/src/client/utils.ts
index 8630ad470..aca9ffbcd 100644
--- a/mem0-ts/src/client/utils.ts
+++ b/mem0-ts/src/client/utils.ts
@@ -34,9 +34,6 @@ const OPAQUE_VALUE_KEYS = new Set([
// (see issue #5738; same class as `metadata`/`structuredDataSchema`).
"customCategories",
"custom_categories",
- // A profile's keys come from the customer's own JSON Schema. The schema itself
- // is handled in `updateProfileSettings`, so that `schema` is not opaque globally.
- "profile",
]);
/**
diff --git a/mem0-ts/src/oss/src/config/manager.ts b/mem0-ts/src/oss/src/config/manager.ts
index d2fa34b52..b2803d1b2 100644
--- a/mem0-ts/src/oss/src/config/manager.ts
+++ b/mem0-ts/src/oss/src/config/manager.ts
@@ -113,18 +113,7 @@ export class ConfigManager {
const userConf = userConfig.llm?.config;
const provider =
userConfig.llm?.provider || DEFAULT_MEMORY_CONFIG.llm.provider;
- // DEFAULT_MEMORY_CONFIG.llm.config holds OpenAI's own defaults (baseURL and
- // model). Handing those to any other provider shadows that provider's default
- // *and* its env fallback (DEEPSEEK_API_BASE, XAI_API_BASE, ...), so a config
- // copied from the docs for another provider ends up pointed at OpenAI with an
- // OpenAI model name. vLLM already needed a carve-out here for exactly this
- // reason; every non-OpenAI provider needs it.
- const usesOpenAIDefaults =
- provider.toLowerCase() === "openai" ||
- provider.toLowerCase() === "openai_structured";
- let finalModel: string | any = usesOpenAIDefaults
- ? defaultConf.model
- : undefined;
+ let finalModel: string | any = defaultConf.model;
if (userConf?.model && typeof userConf.model === "object") {
finalModel = userConf.model;
@@ -142,7 +131,9 @@ export class ConfigManager {
| string
| undefined) ??
userConf?.url ??
- (usesOpenAIDefaults ? defaultConf.baseURL : undefined);
+ (provider.toLowerCase() === "vllm"
+ ? undefined
+ : defaultConf.baseURL);
const temperature =
userConf?.temperature ??
(llmRaw?.temperature as number | undefined);
diff --git a/mem0-ts/src/oss/src/memory/index.ts b/mem0-ts/src/oss/src/memory/index.ts
index 00fdc7d97..1efbc3e45 100644
--- a/mem0-ts/src/oss/src/memory/index.ts
+++ b/mem0-ts/src/oss/src/memory/index.ts
@@ -768,9 +768,7 @@ export class Memory {
has_filters: !!config.filters,
infer: config.infer,
});
- // Copy: scope keys are written into this object below, and the caller's next add() must not inherit them (#6796).
- const filters: SearchFilters = { ...(config.filters ?? {}) };
- const { infer = true } = config;
+ const { filters = {}, infer = true } = config;
const metadata = stripIdentityKeys(config.metadata);
// Validate and trim entity IDs
@@ -1990,15 +1988,7 @@ export class Memory {
updatedAt: new Date().toISOString(),
};
- const updated = await this.vectorStore.update(
- memoryId,
- embedding,
- newMetadata,
- );
- // The memory was deleted between the get above and this write.
- if (updated === false) {
- throw new Error(`Memory with ID ${memoryId} not found`);
- }
+ await this.vectorStore.update(memoryId, embedding, newMetadata);
await this.db.addHistory(
memoryId,
prevValue,
diff --git a/mem0-ts/src/oss/src/tests/chroma.test.ts b/mem0-ts/src/oss/src/tests/chroma.test.ts
index 6efb2df2f..3b51e7eef 100644
--- a/mem0-ts/src/oss/src/tests/chroma.test.ts
+++ b/mem0-ts/src/oss/src/tests/chroma.test.ts
@@ -271,47 +271,14 @@ describe("get", () => {
describe("update", () => {
it("updates a single record with embedding and metadata", async () => {
- __mocks__.get.mockResolvedValue({ ids: ["vec-1"], metadatas: [{}] });
const db = await initDb();
- expect(await db.update("vec-1", [1, 2, 3], { text: "updated" })).toBe(true);
+ await db.update("vec-1", [1, 2, 3], { text: "updated" });
expect(__mocks__.update).toHaveBeenCalledWith({
ids: ["vec-1"],
embeddings: [[1, 2, 3]],
metadatas: [{ text: "updated" }],
});
});
-
- it("returns false and inserts nothing when the id does not exist", async () => {
- const db = await initDb();
- expect(await db.update("missing", [1, 2, 3], { text: "x" })).toBe(false);
- expect(__mocks__.get).toHaveBeenCalledWith({
- ids: ["missing"],
- include: [],
- });
- expect(__mocks__.add).not.toHaveBeenCalled();
- expect(__mocks__.upsert).not.toHaveBeenCalled();
- });
-
- it("returns undefined, not an error, when the read-back after a landed update fails", async () => {
- const warn = jest.spyOn(console, "warn").mockImplementation(() => {});
- const db = await initDb();
- __mocks__.get.mockRejectedValueOnce(new Error("chroma unavailable"));
- expect(await db.update("vec-1", [1, 2, 3], { text: "x" })).toBeUndefined();
- expect(__mocks__.update).toHaveBeenCalledTimes(1);
- expect(warn).toHaveBeenCalled();
- warn.mockRestore();
- });
-
- it("supports a payload-only update", async () => {
- __mocks__.get.mockResolvedValue({ ids: ["vec-1"], metadatas: [{}] });
- const db = await initDb();
- expect(await db.update("vec-1", null as any, { text: "only" })).toBe(true);
- expect(__mocks__.update).toHaveBeenCalledWith({
- ids: ["vec-1"],
- embeddings: undefined,
- metadatas: [{ text: "only" }],
- });
- });
});
describe("delete", () => {
diff --git a/mem0-ts/src/oss/src/tests/mongodb.test.ts b/mem0-ts/src/oss/src/tests/mongodb.test.ts
index d6600bf04..fe847b56c 100644
--- a/mem0-ts/src/oss/src/tests/mongodb.test.ts
+++ b/mem0-ts/src/oss/src/tests/mongodb.test.ts
@@ -330,9 +330,7 @@ describe("MongoDB Vector Store", () => {
it("should update document correctly", async () => {
mockUpdateOne.mockResolvedValue({ matchedCount: 1 });
- expect(
- await store.update("id1", [0.1, 0.2, 0.3, 0.4], { name: "new-alice" }),
- ).toBe(true);
+ await store.update("id1", [0.1, 0.2, 0.3, 0.4], { name: "new-alice" });
expect(mockUpdateOne).toHaveBeenCalledWith(
{ _id: "id1" },
@@ -345,32 +343,6 @@ describe("MongoDB Vector Store", () => {
);
});
- it("should return false and not insert when updating a missing id", async () => {
- mockUpdateOne.mockResolvedValue({ matchedCount: 0, modifiedCount: 0 });
- await store.initialize();
- mockInsertOne.mockClear();
-
- expect(await store.update("missing", [0.1, 0.2, 0.3, 0.4], {})).toBe(false);
- expect(mockUpdateOne.mock.calls[0][2]?.upsert).toBeFalsy();
- expect(mockInsertOne).not.toHaveBeenCalled();
- expect(mockInsertMany).not.toHaveBeenCalled();
- });
-
- it("should return undefined when the write is unacknowledged", async () => {
- mockUpdateOne.mockResolvedValue({ acknowledged: false, matchedCount: 0 });
- expect(await store.update("id1", [0.1, 0.2, 0.3, 0.4], {})).toBeUndefined();
- });
-
- it("should merge a payload-only update without touching the embedding", async () => {
- mockUpdateOne.mockResolvedValue({ matchedCount: 1 });
-
- expect(await store.update("id1", null as any, { name: "bob" })).toBe(true);
- expect(mockUpdateOne).toHaveBeenCalledWith(
- { _id: "id1" },
- { $set: { "payload.name": "bob" } },
- );
- });
-
it("should delete document correctly", async () => {
mockDeleteOne.mockResolvedValue({ deletedCount: 1 });
diff --git a/mem0-ts/src/oss/src/tests/pinecone.test.ts b/mem0-ts/src/oss/src/tests/pinecone.test.ts
index 5342d7a49..3c008538e 100644
--- a/mem0-ts/src/oss/src/tests/pinecone.test.ts
+++ b/mem0-ts/src/oss/src/tests/pinecone.test.ts
@@ -9,13 +9,12 @@
// so `beforeEach` can reach them before the lazy import has fired; the factory,
// which runs on first use, just returns a reference to the Pinecone class mock.
const upsert = jest.fn().mockResolvedValue(undefined);
-const update = jest.fn().mockResolvedValue(undefined);
const query = jest.fn().mockResolvedValue({ matches: [] });
const fetch = jest.fn().mockResolvedValue({ records: {} });
const deleteOne = jest.fn().mockResolvedValue(undefined);
const deleteAll = jest.fn().mockResolvedValue(undefined);
-const nsHandle = { upsert, update, query, fetch, deleteOne, deleteAll };
+const nsHandle = { upsert, query, fetch, deleteOne, deleteAll };
const namespace = jest.fn().mockReturnValue(nsHandle);
const describeIndexStats = jest
@@ -27,7 +26,6 @@ const indexHandle = {
describeIndexStats,
// expose ops directly for the no-namespace path
upsert,
- update,
query,
fetch,
deleteOne,
@@ -47,7 +45,6 @@ const Pinecone = jest.fn().mockImplementation(() => ({
const __mocks__ = {
upsert,
- update,
query,
fetch,
deleteOne,
@@ -107,7 +104,6 @@ beforeEach(() => {
const nsHandle = {
upsert: __mocks__.upsert,
- update: __mocks__.update,
query: __mocks__.query,
fetch: __mocks__.fetch,
deleteOne: __mocks__.deleteOne,
@@ -118,7 +114,6 @@ beforeEach(() => {
namespace: __mocks__.namespace,
describeIndexStats: __mocks__.describeIndexStats,
upsert: __mocks__.upsert,
- update: __mocks__.update,
query: __mocks__.query,
fetch: __mocks__.fetch,
deleteOne: __mocks__.deleteOne,
@@ -404,27 +399,14 @@ describe("get", () => {
});
describe("update", () => {
- it("updates by id and never upserts", async () => {
+ it("upserts a single record", async () => {
const db = await initDb();
- await expect(
- db.update("vec-1", [1, 2, 3, 4], { text: "updated" }),
- ).resolves.toBeUndefined();
- expect(__mocks__.update).toHaveBeenCalledWith({
- id: "vec-1",
- values: [1, 2, 3, 4],
- metadata: { text: "updated" },
+ await db.update("vec-1", [1, 2, 3, 4], { text: "updated" });
+ expect(__mocks__.upsert).toHaveBeenCalledWith({
+ records: [
+ { id: "vec-1", values: [1, 2, 3, 4], metadata: { text: "updated" } },
+ ],
});
- expect(__mocks__.upsert).not.toHaveBeenCalled();
- });
-
- it("payload-only update leaves the vector values alone", async () => {
- const db = await initDb();
- await db.update("vec-1", null as any, { text: "renamed" });
- expect(__mocks__.update).toHaveBeenCalledWith({
- id: "vec-1",
- metadata: { text: "renamed" },
- });
- expect(__mocks__.upsert).not.toHaveBeenCalled();
});
});
diff --git a/mem0-ts/src/oss/src/vector_stores/azure_ai_search.ts b/mem0-ts/src/oss/src/vector_stores/azure_ai_search.ts
index 84117718b..52576aca0 100644
--- a/mem0-ts/src/oss/src/vector_stores/azure_ai_search.ts
+++ b/mem0-ts/src/oss/src/vector_stores/azure_ai_search.ts
@@ -474,7 +474,7 @@ export class AzureAISearch implements VectorStore {
vectorId: string,
vector: number[],
payload: Record,
- ): Promise {
+ ): Promise {
await this.initialize();
const document: Record = { id: vectorId };
@@ -493,19 +493,15 @@ export class AzureAISearch implements VectorStore {
}
}
- const response = await this.searchClient.mergeDocuments([document]);
+ const response = await this.searchClient.mergeOrUploadDocuments([document]);
for (const result of response.results) {
- if (result.statusCode === 404) {
- return false;
- }
if (!result.succeeded) {
throw new Error(
`Update failed for document ${vectorId}: ${result.errorMessage}`,
);
}
}
- return true;
}
/**
diff --git a/mem0-ts/src/oss/src/vector_stores/azure_mysql.ts b/mem0-ts/src/oss/src/vector_stores/azure_mysql.ts
index d525fcca7..123767484 100644
--- a/mem0-ts/src/oss/src/vector_stores/azure_mysql.ts
+++ b/mem0-ts/src/oss/src/vector_stores/azure_mysql.ts
@@ -1,4 +1,4 @@
-import type { Pool, ResultSetHeader, RowDataPacket } from "mysql2/promise";
+import type { Pool, RowDataPacket } from "mysql2/promise";
import { VectorStore } from "./base";
import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types";
import { loadPeer } from "../utils/load_peer";
@@ -275,18 +275,16 @@ export class AzureMySQLDB implements VectorStore {
vectorId: string,
vector: number[],
payload: Record,
- ): Promise