diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index d46a19e49..752311cbc 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -12,7 +12,7 @@ "name": "mem0", "source": "./integrations/claude-code-plugin", "description": "Cross-session memory and token savings for coding agents.", - "version": "0.3.1" + "version": "0.3.3" } ] } diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.json index 409b7d8fc..4d083a06b 100644 --- a/.cursor-plugin/marketplace.json +++ b/.cursor-plugin/marketplace.json @@ -12,7 +12,7 @@ "name": "mem0", "source": "./integrations/cursor-plugin", "description": "Cross-session memory and token savings for coding agents.", - "version": "0.3.1" + "version": "0.3.3" } ] } diff --git a/.github/workflows/opencode-plugin-checks.yml b/.github/workflows/opencode-plugin-checks.yml index 4fb95fc6c..a93d741eb 100644 --- a/.github/workflows/opencode-plugin-checks.yml +++ b/.github/workflows/opencode-plugin-checks.yml @@ -32,6 +32,9 @@ jobs: - name: Type check run: bun run type-check + - name: Test + run: bun test + - name: Build run: bun run build diff --git a/.kimi-plugin/marketplace.json b/.kimi-plugin/marketplace.json index 8ff2134b4..47c986c6c 100644 --- a/.kimi-plugin/marketplace.json +++ b/.kimi-plugin/marketplace.json @@ -5,7 +5,7 @@ { "id": "mem0", "displayName": "Mem0", - "version": "0.3.1", + "version": "0.3.3", "description": "Cross-session memory and token savings for coding agents.", "homepage": "https://mem0.ai", "keywords": ["memory", "personalization", "mcp", "semantic-search"], diff --git a/README.md b/README.md index 9a81e74ef..c9ed6dbfb 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,17 @@ Mem0 - The Memory Layer for Personalized AI

+ +

+ + Mem0 OSS Halloween Happy Hour: The People Who Read the Source. Tuesday, Oct 27, 5:00 PM, San Francisco. Costumes encouraged. + +
+ ๐ŸŽƒ Register here โ†’ ยท Contributors get priority +

+ + +

mem0ai%2Fmem0 | Trendshift diff --git a/cli/CLI_SPECIFICATION.md b/cli/CLI_SPECIFICATION.md deleted file mode 100644 index a243e833c..000000000 --- a/cli/CLI_SPECIFICATION.md +++ /dev/null @@ -1,1613 +0,0 @@ -# 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 d078066e2..62797eca5 100644 --- a/cli/node/package.json +++ b/cli/node/package.json @@ -1,6 +1,6 @@ { "name": "@mem0/cli", - "version": "0.2.13", + "version": "0.2.14", "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.0.0", + "vite": "^6.4.4", "vitest": "^4.1.11", "@biomejs/biome": "^1.7.0", "@types/node": "^20.0.0" @@ -52,7 +52,8 @@ "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" + "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/pnpm-lock.yaml b/cli/node/pnpm-lock.yaml index 968075cc7..50ad5a518 100644 --- a/cli/node/pnpm-lock.yaml +++ b/cli/node/pnpm-lock.yaml @@ -11,6 +11,7 @@ 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: @@ -48,11 +49,11 @@ importers: specifier: ^5.4.0 version: 5.9.3 vite: - specifier: ^6.0.0 - version: 6.4.3(@types/node@20.19.37)(tsx@4.21.0) + specifier: ^6.4.4 + version: 6.4.5(@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.3(@types/node@20.19.37)(tsx@4.21.0)) + version: 4.1.11(@types/node@20.19.37)(vite@6.4.5(@types/node@20.19.37)(tsx@4.21.0)) packages: @@ -756,8 +757,8 @@ packages: resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} engines: {node: '>=14'} - source-map-js@1.2.1: - resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} engines: {node: '>=0.10.0'} source-map@0.7.6: @@ -870,8 +871,8 @@ packages: undici-types@6.21.0: resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} - vite@6.4.3: - resolution: {integrity: sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==} + vite@6.4.5: + resolution: {integrity: sha512-4enwjFfi4IwtEh0w+jPzpLVOFQiPHmmzPxcHXQOyEur47o6u0jE573DmGpjA+7irXoMLYRZD5ZaFUEneS3abPg==} engines: {node: ^18.0.0 || ^20.0.0 || >=22.0.0} hasBin: true peerDependencies: @@ -1195,13 +1196,13 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.11(vite@6.4.3(@types/node@20.19.37)(tsx@4.21.0))': + '@vitest/mocker@4.1.11(vite@6.4.5(@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.3(@types/node@20.19.37)(tsx@4.21.0) + vite: 6.4.5(@types/node@20.19.37)(tsx@4.21.0) '@vitest/pretty-format@4.1.11': dependencies: @@ -1452,7 +1453,7 @@ snapshots: dependencies: nanoid: 3.3.16 picocolors: 1.1.1 - source-map-js: 1.2.1 + source-map-js: 1.2.2 readdirp@4.1.2: {} @@ -1500,7 +1501,7 @@ snapshots: signal-exit@4.1.0: {} - source-map-js@1.2.1: {} + source-map-js@1.2.2: {} source-map@0.7.6: {} @@ -1614,7 +1615,7 @@ snapshots: undici-types@6.21.0: {} - vite@6.4.3(@types/node@20.19.37)(tsx@4.21.0): + vite@6.4.5(@types/node@20.19.37)(tsx@4.21.0): dependencies: esbuild: 0.28.1 fdir: 6.5.0(picomatch@4.0.4) @@ -1627,10 +1628,10 @@ snapshots: fsevents: 2.3.3 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)): + vitest@4.1.11(@types/node@20.19.37)(vite@6.4.5(@types/node@20.19.37)(tsx@4.21.0)): dependencies: '@vitest/expect': 4.1.11 - '@vitest/mocker': 4.1.11(vite@6.4.3(@types/node@20.19.37)(tsx@4.21.0)) + '@vitest/mocker': 4.1.11(vite@6.4.5(@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 @@ -1647,7 +1648,7 @@ snapshots: tinyexec: 1.2.4 tinyglobby: 0.2.15 tinyrainbow: 3.1.0 - vite: 6.4.3(@types/node@20.19.37)(tsx@4.21.0) + vite: 6.4.5(@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 daadb240e..bc1c71b28 100644 --- a/cli/node/pnpm-workspace.yaml +++ b/cli/node/pnpm-workspace.yaml @@ -12,3 +12,4 @@ 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 705a3d470..65a4b6228 100644 --- a/cli/node/src/backend/platform.ts +++ b/cli/node/src/backend/platform.ts @@ -31,7 +31,8 @@ export class PlatformBackend implements Backend { this.headers = { Authorization: `Token ${config.apiKey}`, "Content-Type": "application/json", - "X-Mem0-Source": "cli", + "X-Mem0-Source": "CLI", + "X-Mem0-Client": `mem0-cli-node/${CLI_VERSION}`, "X-Mem0-Client-Language": "node", "X-Mem0-Client-Version": CLI_VERSION, }; diff --git a/cli/python/pyproject.toml b/cli/python/pyproject.toml index be7e72709..961d2b78d 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.12" +version = "0.2.13" 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 6d686291e..0aeb58270 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.12" +__version__ = "0.2.13" diff --git a/cli/python/src/mem0_cli/backend/platform.py b/cli/python/src/mem0_cli/backend/platform.py index 1d153da9c..a9ce60df1 100644 --- a/cli/python/src/mem0_cli/backend/platform.py +++ b/cli/python/src/mem0_cli/backend/platform.py @@ -27,7 +27,8 @@ class PlatformBackend(Backend): headers={ "Authorization": f"Token {config.api_key}", "Content-Type": "application/json", - "X-Mem0-Source": "cli", + "X-Mem0-Source": "CLI", + "X-Mem0-Client": f"mem0-cli-python/{__version__}", "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 new file mode 100644 index 000000000..e5de5a12d --- /dev/null +++ b/docs/api-reference/profiles/generate-profiles.mdx @@ -0,0 +1,5 @@ +--- +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 new file mode 100644 index 000000000..c24e86794 --- /dev/null +++ b/docs/api-reference/profiles/get-profile-job.mdx @@ -0,0 +1,5 @@ +--- +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 new file mode 100644 index 000000000..82eb1b37b --- /dev/null +++ b/docs/api-reference/profiles/get-profile-settings.mdx @@ -0,0 +1,5 @@ +--- +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 new file mode 100644 index 000000000..604535a3c --- /dev/null +++ b/docs/api-reference/profiles/get-profile.mdx @@ -0,0 +1,5 @@ +--- +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 new file mode 100644 index 000000000..e33dc9198 --- /dev/null +++ b/docs/api-reference/profiles/update-profile-settings.mdx @@ -0,0 +1,5 @@ +--- +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 71fb7e1d8..14c9c014d 100644 --- a/docs/changelog/sdk.mdx +++ b/docs/changelog/sdk.mdx @@ -7,6 +7,36 @@ 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:** @@ -174,7 +204,7 @@ mode: "wide" **New Features:** -- **Embeddings:** Add native `embed_batch` to five embedders: LM Studio, Together, HuggingFace, Vertex AI, and Google GenAI: for batched embedding requests ([#5609](https://github.com/mem0ai/mem0/pull/5609)) +- **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)) **Bug Fixes:** - **Core:** Guard against malformed `image_url` entries in `parse_vision_messages` to prevent crashes ([#5631](https://github.com/mem0ai/mem0/pull/5631)) @@ -964,7 +994,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 Opsearch Serverless +- **AWS:** Added support for OpenSearch Serverless - **Examples:** Added ElizaOS Example **Improvements:** @@ -1227,6 +1257,31 @@ 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:** @@ -1864,6 +1919,13 @@ 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:** @@ -2076,7 +2138,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, 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. +- 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. - 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) @@ -2371,9 +2433,25 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex - + -Sidekick is now available only in Claude Code, with Sonnet, worktree isolation, and parent memories. +**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. @@ -2396,9 +2474,24 @@ Sidekick is now available only in Claude Code, with Sonnet, worktree isolation, - + -Removes Sidekick and its start/stop hooks. Memory capture, search, and six skills remain available. +**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. @@ -2421,9 +2514,24 @@ Removes Sidekick and its start/stop hooks. Memory capture, search, and six skill - + -Renames shared tracking to use subagent terminology. Native subagent memory support remains available. +**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. @@ -2443,32 +2551,25 @@ Renames shared tracking to use subagent terminology. Native subagent memory supp - - - - -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:** @@ -2567,9 +2668,24 @@ Sidekick is available only in Claude Code, not in the portable package. - + -Removes Sidekick. Memory capture, search, and six skills remain available. +**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. @@ -2665,9 +2781,24 @@ Existing memories written by the previous versions are not rewritten. If your me - + -Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skills remain available. +**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. @@ -2705,6 +2836,21 @@ Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skill + + +**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:** @@ -2993,6 +3139,22 @@ Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skill + + +**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:** @@ -3106,6 +3268,21 @@ Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skill + + +**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:** @@ -3150,6 +3327,13 @@ Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skill + + +**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 75f44227e..a71c1764a 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 93a0bf4ad..8577b50cc 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 is provided, it will be used for authentication over an Azure Identity + If an API key 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 f322a0a95..ddd36c416 100644 --- a/docs/components/vectordbs/dbs/pgvector.mdx +++ b/docs/components/vectordbs/dbs/pgvector.mdx @@ -5,6 +5,12 @@ 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 31662ed29..1cd06b592 100644 --- a/docs/components/vectordbs/dbs/pinecone.mdx +++ b/docs/components/vectordbs/dbs/pinecone.mdx @@ -94,6 +94,7 @@ 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 0696f45e5..9c9571a66 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 new file mode 100644 index 000000000..60b102324 --- /dev/null +++ b/docs/cookbooks/integrations/supabase.mdx @@ -0,0 +1,388 @@ +--- +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 5998b4f3c..1be360c79 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 - - Choose the right scope for user, agent, run, and session memory. + + Organize Platform memories by user, agent, app, and run. 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 eb8f4c8c9..ddd86a8e3 100644 --- a/docs/core-concepts/memory-operations/delete.mdx +++ b/docs/core-concepts/memory-operations/delete.mdx @@ -137,6 +137,10 @@ 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 deleted file mode 100644 index a2a18e077..000000000 --- a/docs/core-concepts/memory-types.mdx +++ /dev/null @@ -1,118 +0,0 @@ ---- -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 4ca51fa24..b694e288a 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -54,7 +54,6 @@ "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", @@ -72,6 +71,7 @@ "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,7 +87,8 @@ "platform/advanced-memory-operations", "platform/features/custom-instructions", "platform/features/memory-decay", - "platform/features/dream" + "platform/features/dream", + "platform/features/byok" ] }, { @@ -115,7 +116,8 @@ "group": "Support", "icon": "life-buoy", "pages": [ - "platform/faqs" + "platform/faqs", + "platform/pricing" ] }, { @@ -444,7 +446,8 @@ "cookbooks/integrations/mastra-agent", "cookbooks/integrations/healthcare-google-adk", "cookbooks/integrations/aws-bedrock", - "cookbooks/integrations/tavily-search" + "cookbooks/integrations/tavily-search", + "cookbooks/integrations/supabase" ] }, { @@ -512,6 +515,17 @@ "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", @@ -1020,7 +1034,11 @@ }, { "source": "/concepts/memory-scoring", - "destination": "/core-concepts/memory-types" + "destination": "/core-concepts/how-it-works" + }, + { + "source": "/core-concepts/memory-types", + "destination": "/core-concepts/how-it-works" }, { "source": "/cookbooks/research-copilot", diff --git a/docs/images/halloween-happy-hour.png b/docs/images/halloween-happy-hour.png new file mode 100644 index 000000000..8b5ab3874 Binary files /dev/null and b/docs/images/halloween-happy-hour.png differ diff --git a/docs/images/platform/byok-accuracy-vs-cost.png b/docs/images/platform/byok-accuracy-vs-cost.png new file mode 100644 index 000000000..020c40fc0 Binary files /dev/null and b/docs/images/platform/byok-accuracy-vs-cost.png differ diff --git a/docs/images/platform/byok-picks.png b/docs/images/platform/byok-picks.png new file mode 100644 index 000000000..f09b9b2af Binary files /dev/null and b/docs/images/platform/byok-picks.png differ diff --git a/docs/integrations/camel-ai.mdx b/docs/integrations/camel-ai.mdx index 1eb715b20..342291819 100644 --- a/docs/integrations/camel-ai.mdx +++ b/docs/integrations/camel-ai.mdx @@ -130,10 +130,10 @@ print(response.msgs[0].content) + 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. + ## Agent Tools @@ -29,21 +33,33 @@ 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` (default `false`, Platform mode only) | +| `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_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: +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: ```bash -curl -fsSL https://raw.githubusercontent.com/NousResearch/hermes-agent/main/scripts/install.sh | bash -source ~/.bashrc +hermes plugins install mem0ai/mem0/integrations/hermes-plugin-mem0 +hermes plugins enable mem0 +hermes memory setup +hermes memory status ``` -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. +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. + ## Platform Setup @@ -52,10 +68,10 @@ Platform mode uses managed Mem0 Cloud and is the fastest way to start. ### Option 1: Interactive wizard (recommended) ```bash -hermes memory setup +hermes memory setup mem0 ``` -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`. +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. Get your API key from app.mem0.ai. @@ -63,17 +79,25 @@ Select **mem0**, choose **Platform**, and paste your API key when prompted. The ```bash hermes config set memory.provider mem0 -echo "MEM0_API_KEY=your-api-key" >> ~/.hermes/.env ``` -Then in your `config.yaml`: +Add your key to the active Hermes profile's `.env`: -```yaml -memory: - provider: mem0 +```dotenv +MEM0_API_KEY=your-api-key ``` -That's it. Mem0 runs automatically from here. +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`. ## Self-Hosted Server Setup @@ -82,48 +106,47 @@ Run the [Mem0 server](https://github.com/mem0ai/mem0/tree/main/server) (FastAPI ### Interactive ```bash -hermes memory setup -# Select "mem0", then "Self-hosted server", and enter the server URL +hermes memory setup mem0 +# Choose "Self-hosted server", then enter the server URL and API key ``` -### With flags +### Manual configuration -```bash -hermes memory setup mem0 --mode selfhosted \ - --host http://localhost:8888 \ - --api-key your-admin-api-key +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" +} ``` -### With environment variables +Add the server key to that profile's `.env`: -```bash -echo "MEM0_HOST=http://localhost:8888" >> ~/.hermes/.env -echo "MEM0_API_KEY=your-admin-api-key" >> ~/.hermes/.env +```dotenv +MEM0_API_KEY=your-admin-api-key ``` +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 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. +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. ### Interactive ```bash -hermes memory setup -# Select "mem0", then "Open Source (self-hosted)" +hermes memory setup mem0 +# Choose "Open Source" # Follow the prompts for LLM, embedder, and vector store ``` -### With flags - -```bash -hermes memory setup mem0 --mode oss \ - --oss-llm openai --oss-llm-key sk-... \ - --oss-vector qdrant -``` +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. ### Supported providers @@ -133,52 +156,24 @@ hermes memory setup mem0 --mode oss \ | Embedder | `openai` (default `text-embedding-3-small`), `ollama` (local, default `nomic-embed-text`) | | Vector store | `qdrant` (local path or server), `pgvector` | -### Flag reference - -| Flag | Description | -|------|-------------| -| `--mode` | `platform`, `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. +### Manual configuration ```bash -# Platform to OSS -hermes memory setup mem0 --mode oss --oss-llm-key sk-... - -# OSS to Platform -hermes memory setup mem0 --mode platform --api-key sk-... - -# 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 +hermes config set memory.provider mem0 ``` -A self-hosted `~/.hermes/mem0.json` looks like this: +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. ```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"}}, @@ -187,33 +182,65 @@ A self-hosted `~/.hermes/mem0.json` looks like this: } ``` +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 -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`. +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. | 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` | `hermes-user` | Identifier that scopes memories. See cross-channel behavior below | +| `user_id` | gateway user ID, then `hermes-user` | Identifier that scopes memories. See cross-channel behavior below | | `agent_id` | `hermes` | Agent identifier attached to writes | -| `rerank` | `false` | Rerank search results for relevance (Platform mode only) | +| `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 | ### Cross-channel memories Hermes can run from the CLI and from gateways like Telegram, Slack, and Discord. The `user_id` setting controls how memories are scoped across them: -- **Set a `user_id`** and it applies to every gateway, so one person gets a single merged memory store no matter where they talk to the agent. -- **Leave it unset** (or at the default `hermes-user`) and each gateway uses its own native id, keeping per-platform memories separate. +- **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`. -Either way, every write is tagged with `metadata.channel` (for example `telegram` or `cli`), so per-channel views are still possible at query time. +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. ## Reliability -- **Circuit breaker**: if Mem0 fails five times in a row, Hermes pauses calls for two minutes, then retries. The agent keeps working without memory during that window. Expected client errors, like a 404 on a missing memory id, do not count toward tripping the breaker. -- **Non-blocking**: 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. +- **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. ## Troubleshooting @@ -248,15 +275,12 @@ 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/mem0.json`). +- 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. -## Key Features +### OSS: embedding dimension mismatch -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`). +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. diff --git a/docs/integrations/llama-index.mdx b/docs/integrations/llama-index.mdx index f2bc02491..d529937f6 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 the 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 at least one of the fields in the `Mem0Memory` constructor. It can be any of the following: ```python context = { diff --git a/docs/llms.txt b/docs/llms.txt index 686835a0e..f13e2fc07 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -186,7 +186,6 @@ 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. @@ -198,6 +197,7 @@ 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,6 +209,7 @@ 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 @@ -224,6 +225,7 @@ 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. @@ -256,7 +258,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 the user is on Hermes. +- [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. - [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. @@ -326,6 +328,7 @@ 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. @@ -363,6 +366,11 @@ 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 8cc9690da..8a16dde57 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: none | Default: `0.1` | Pass `0.0` to disable | -| `rerank` | Default: `true` | Default: `false` | Pass `true` to enable (adds latency) | +| `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) | | 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` (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. + 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. - 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. + 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. 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 af215596f..f27449514 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -8070,6 +8070,480 @@ } } } + }, + "/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": { @@ -8988,4 +9462,4 @@ } }, "x-original-swagger-version": "2.0" -} \ No newline at end of file +} diff --git a/docs/platform/features/async-client.mdx b/docs/platform/features/async-client.mdx index 6effd9995..964fb1ce5 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. + 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. ### History diff --git a/docs/platform/features/byok.mdx b/docs/platform/features/byok.mdx new file mode 100644 index 000000000..6a57c6cd8 --- /dev/null +++ b/docs/platform/features/byok.mdx @@ -0,0 +1,126 @@ +--- +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 three picks. Best value: DeepSeek V4.1 Flash, open weights, on OpenRouter: 92.9% accuracy, $5.34 per 1,000 add requests, 18.5 s latency at p95. Best under $1: Amazon Nova Micro, closed, on OpenRouter: 88.0% accuracy, $0.86 per 1,000 add requests, 10.2 s latency at p95. Best quality: Claude Opus 5.5, closed, on Anthropic, OpenRouter: 93.5% accuracy, $158.55 per 1,000 add requests, 18.1 s latency at p95. + + + +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%. + + + Scatter chart of accuracy against cost per 1,000 add requests on a log scale, one ring per model, each labelled with its accuracy. Mistral Nemo sits at the far left at $0.68 and 84.1%; Claude Opus 5.5 at the far right at $158.55 and 93.5%. A dashed gray line marks Mem0's default model (free tier) at 92.5%. A green shaded region holds the models above it for under $10 per 1,000 add requests, a gold one the models under $2 per 1,000 add requests, and a dashed green line marks the best accuracy available at each price. Tags mark our picks: best value, DeepSeek V4.1 Flash; best under $1, Amazon Nova Micro; best quality, Claude Opus 5.5. + diff --git a/docs/platform/features/custom-instructions.mdx b/docs/platform/features/custom-instructions.mdx index 8b5b1f35e..9acd741f2 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, - filters={"agent_id": "support-agent"}, + 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 new file mode 100644 index 000000000..1e99f59ea --- /dev/null +++ b/docs/platform/features/user-profiles.mdx @@ -0,0 +1,359 @@ +--- +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 ddb5ff405..9bc34aea9 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. - - How user, agent, app, and run memory differ. + + Organize memories by user, agent, app, and run. The core memory operations, end to end. diff --git a/docs/platform/platform-vs-oss.mdx b/docs/platform/platform-vs-oss.mdx index 92bcc27b4..8a79ab351 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**, **procedural memory** (Python), and **custom extraction instructions** (`custom_instructions`) +- **Multimodal input**, **memory expiration** (`expiration_date`), **reranking**, 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 new file mode 100644 index 000000000..5d27d8252 --- /dev/null +++ b/docs/platform/pricing.mdx @@ -0,0 +1,96 @@ +--- +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 d04412863..67a83d556 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 fc502f88b..7582f3a47 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 f86cb7745..b31d1b442 100644 --- a/docs/templates/parameters_reference_template.mdx +++ b/docs/templates/parameters_reference_template.mdx @@ -38,7 +38,6 @@ client.memories.add( user_id: str, memory: str, metadata: Optional[dict] = None, - memory_type: Literal["session", "long_term"] = "session", ) ``` @@ -47,13 +46,13 @@ await mem0.memories.add({ userId: string; memory: string; metadata?: Record; - memoryType?: "session" | "long_term"; }); ``` - Defaults to session memories. Override `memory_type` for long-term storage. + [Describe defaults supported by this operation and SDK. Do not infer a + memory type or retention policy from a scoping identifier.] @@ -67,7 +66,6 @@ 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 50eb08e04..a5bf80016 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 -- Memory types: factual (preferences, facts), episodic (past interactions), - semantic (concept relationships), working (session state) +- Store preferences, facts, and past interactions; use run_id to scope a + session. Platform does not expose a memory_type selector. - 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 ef1f8d20a..32366bb8b 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.24", + "next": "15.5.28", "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 bb4edbc42..abd383a47 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", user_id=user_id) + past_memories = memory.search("movie preferences", filters={"user_id": user_id}) prompt = user_query - if past_memories: - prompt += f"\nPreviously, the user mentioned: {past_memories}" + if past_memories["results"]: + prompt += f"\nPreviously, the user mentioned: {[m['memory'] for m in past_memories['results']]}" # 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 01fde8614..37f1a2fb8 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, user_id=user_id) + results = m.search(query, filters={"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, user_id=user_id) + results = m.search(graph_query, filters={"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(user_id=user_id) + all_memories = m.get_all(filters={"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 635cb550e..610edd2b7 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, user_id="user_123") + memories = memory.search(query=query, filters={"user_id": "user_123"}) - for memory_item in memories: + for memory_item in memories["results"]: print(f" - {memory_item['memory']}") print("\n--> Getting all memories for user...") - all_memories = memory.get_all(user_id="user_123") - print(f"Total memories stored: {len(all_memories)}") + all_memories = memory.get_all(filters={"user_id": "user_123"}) + print(f"Total memories stored: {len(all_memories['results'])}") - for memory_item in all_memories: + for memory_item in all_memories["results"]: 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 new file mode 100644 index 000000000..72ef7580d --- /dev/null +++ b/examples/notebooks/user-profiles.ipynb @@ -0,0 +1,764 @@ +{ + "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 c129dd48b..e7814523f 100644 --- a/integrations/AGENTS.md +++ b/integrations/AGENTS.md @@ -6,6 +6,7 @@ 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 | @@ -49,6 +50,48 @@ 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/`. @@ -59,3 +102,4 @@ Run the type check after every TypeScript change: `pnpm run typecheck` or `tsc - 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 f11026319..dab9a88b7 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, formatting, identity, scoping, and telemetry +โ”‚ โ”œโ”€โ”€ typescript/ # Shared lifecycle, search prompts, 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 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. +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. 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 e675efb02..3059b9b1f 100644 --- a/integrations/agent-plugin-core/build/build.py +++ b/integrations/agent-plugin-core/build/build.py @@ -81,15 +81,23 @@ def replace_output(staged: Path, output: Path) -> Path: return output -def _render_harness_id(host: str) -> str: +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" @@ -98,8 +106,10 @@ def _render_harness_id(host: str) -> str: "\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 = "{host}"\n' + f'PLATFORM_APPLICATION = "{application}"\n' ) @@ -122,7 +132,7 @@ def _bundle_python( # 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), encoding="utf-8") + (core / "_harness_id.py").write_text(_render_harness_id(host, portable=portable), encoding="utf-8") values = { "PLUGIN_ROOT": plugin_root, diff --git a/integrations/agent-plugin-core/python/mcp_server.py b/integrations/agent-plugin-core/python/mcp_server.py index 036fbbdc9..a0b73cb79 100644 --- a/integrations/agent-plugin-core/python/mcp_server.py +++ b/integrations/agent-plugin-core/python/mcp_server.py @@ -21,16 +21,9 @@ from memory_core import ( PROTOCOL_VERSION = "2024-11-05" TOOL_NAME = "search_memories" TOOL_DESCRIPTION = ( - "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." + "Search memories from earlier work in this repository. Use it before " + "repeating investigation or when earlier decisions, fixes, commands, or " + "results may help." ) 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 77d7a2b80..9b420a063 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.1" +PLUGIN_VERSION = "0.3.3" _harness_name: str = "generic" _harness_env_prefix: str = "MEM0_PLUGIN" @@ -71,15 +71,13 @@ MAX_FLUSH_ATTEMPTS = 5 FORGET_PAGE_SIZE = 100 FORGET_MAX_PAGES = 50 -PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository. +PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work. 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. -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. +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. -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. +Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state. If nothing useful was established, return no memories.""" @@ -1800,6 +1798,34 @@ 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]: @@ -1807,7 +1833,7 @@ def _request_json( request = urllib.request.Request( url, data=raw, - headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="POST", ) with urllib.request.urlopen(request, timeout=timeout) as response: @@ -1834,7 +1860,7 @@ def _get_json( ) -> tuple[dict[str, Any] | list[Any], int]: request = urllib.request.Request( url, - headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="GET", ) with urllib.request.urlopen(request, timeout=timeout) as response: @@ -1980,6 +2006,13 @@ 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, @@ -2523,7 +2556,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={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="DELETE", ) try: diff --git a/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl index 3a255b1ad..6c4fdd03c 100644 --- a/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl +++ b/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl @@ -12,11 +12,9 @@ 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; 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. +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 54b5e5c6a..23295cc38 100644 --- a/integrations/agent-plugin-core/tests/test_build.py +++ b/integrations/agent-plugin-core/tests/test_build.py @@ -70,6 +70,38 @@ 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_uninitialised_identity.py b/integrations/agent-plugin-core/tests/test_uninitialised_identity.py index 7d48dbcc3..74a31fa5c 100644 --- a/integrations/agent-plugin-core/tests/test_uninitialised_identity.py +++ b/integrations/agent-plugin-core/tests/test_uninitialised_identity.py @@ -179,6 +179,33 @@ def test_source_tag_defaults_agree_between_the_two_modules(): 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( diff --git a/integrations/agent-plugin-core/typescript/src/lifecycle.ts b/integrations/agent-plugin-core/typescript/src/lifecycle.ts index 42c522b54..738ccc1c7 100644 --- a/integrations/agent-plugin-core/typescript/src/lifecycle.ts +++ b/integrations/agent-plugin-core/typescript/src/lifecycle.ts @@ -1,5 +1,6 @@ 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; @@ -70,12 +71,14 @@ export function extractConversation( } interface RecallOptions { + heading?: string; maxChars?: number; seenIds?: Set; timeoutMs?: number; } interface MemoryLifecycleOptions { + recallHeading?: string; maxContextChars?: number; recallTimeoutMs?: number; } @@ -109,6 +112,7 @@ 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, @@ -148,8 +152,7 @@ export async function buildRecallContext( const unseen = memories.filter((memory) => !options.seenIds?.has(memory.id)); if (!unseen.length) return ""; - 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 prefix = `\n${options.heading ?? RECALL_HEADING}\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 new file mode 100644 index 000000000..cb4d4e07b --- /dev/null +++ b/integrations/agent-plugin-core/typescript/src/prompts.ts @@ -0,0 +1,10 @@ +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 c6a7544ce..2b6c5286e 100644 --- a/integrations/agent-plugin-core/typescript/src/telemetry.ts +++ b/integrations/agent-plugin-core/typescript/src/telemetry.ts @@ -1,3 +1,5 @@ +import { randomUUID } from "node:crypto"; + import { redactSecrets } from "./lifecycle.ts"; const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"; @@ -74,34 +76,108 @@ 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[]) => { - await fetch(POSTHOG_BATCH_URL, { + const response = 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(): Promise { + 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; 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 { - // Telemetry must never affect plugin behavior. + // 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; } } function beforeExit(): void { - void flush(); + // 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); } function build(event: string, properties: Record = {}): Record | null { @@ -112,6 +188,15 @@ 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 ?? {}), @@ -134,8 +219,10 @@ 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?.(); @@ -149,6 +236,8 @@ 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 new file mode 100644 index 000000000..3090c1d51 --- /dev/null +++ b/integrations/agent-plugin-core/typescript/tests/prompts.test.ts @@ -0,0 +1,31 @@ +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 e04794614..cf9671682 100644 --- a/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts +++ b/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts @@ -122,3 +122,250 @@ 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 index 2c8a515f4..18b7f68ec 100644 --- a/integrations/antigravity-plugin/core/_harness_id.py +++ b/integrations/antigravity-plugin/core/_harness_id.py @@ -5,5 +5,7 @@ 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/mcp_server.py b/integrations/antigravity-plugin/core/mcp_server.py index 036fbbdc9..a0b73cb79 100644 --- a/integrations/antigravity-plugin/core/mcp_server.py +++ b/integrations/antigravity-plugin/core/mcp_server.py @@ -21,16 +21,9 @@ from memory_core import ( PROTOCOL_VERSION = "2024-11-05" TOOL_NAME = "search_memories" TOOL_DESCRIPTION = ( - "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." + "Search memories from earlier work in this repository. Use it before " + "repeating investigation or when earlier decisions, fixes, commands, or " + "results may help." ) TOOL_SCHEMA = { "type": "object", diff --git a/integrations/antigravity-plugin/core/memory_core.py b/integrations/antigravity-plugin/core/memory_core.py index 77d7a2b80..9b420a063 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.1" +PLUGIN_VERSION = "0.3.3" _harness_name: str = "generic" _harness_env_prefix: str = "MEM0_PLUGIN" @@ -71,15 +71,13 @@ MAX_FLUSH_ATTEMPTS = 5 FORGET_PAGE_SIZE = 100 FORGET_MAX_PAGES = 50 -PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository. +PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work. 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. -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. +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. -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. +Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state. If nothing useful was established, return no memories.""" @@ -1800,6 +1798,34 @@ 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]: @@ -1807,7 +1833,7 @@ def _request_json( request = urllib.request.Request( url, data=raw, - headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="POST", ) with urllib.request.urlopen(request, timeout=timeout) as response: @@ -1834,7 +1860,7 @@ def _get_json( ) -> tuple[dict[str, Any] | list[Any], int]: request = urllib.request.Request( url, - headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="GET", ) with urllib.request.urlopen(request, timeout=timeout) as response: @@ -1980,6 +2006,13 @@ 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, @@ -2523,7 +2556,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={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="DELETE", ) try: diff --git a/integrations/antigravity-plugin/plugin-build.json b/integrations/antigravity-plugin/plugin-build.json index ac65c4bea..5a9112025 100644 --- a/integrations/antigravity-plugin/plugin-build.json +++ b/integrations/antigravity-plugin/plugin-build.json @@ -1,6 +1,6 @@ { "id": "mem0", - "version": "0.3.1", + "version": "0.3.3", "homepage": "https://docs.mem0.ai/integrations/antigravity", "native": { "pluginRoot": "${ANTIGRAVITY_PLUGIN_ROOT}", diff --git a/integrations/antigravity-plugin/skills/search/SKILL.md b/integrations/antigravity-plugin/skills/search/SKILL.md index 7a6af05fa..530a70a86 100644 --- a/integrations/antigravity-plugin/skills/search/SKILL.md +++ b/integrations/antigravity-plugin/skills/search/SKILL.md @@ -12,11 +12,9 @@ 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; 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. +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 6f214cc14..8182b49dc 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.1", + "version": "0.3.3", "description": "Cross-session memory and token savings for coding agents.", "author": { "name": "Mem0" diff --git a/integrations/claude-code-plugin/agents/sidekick.md b/integrations/claude-code-plugin/agents/sidekick.md index d0552c0c3..8f719327a 100644 --- a/integrations/claude-code-plugin/agents/sidekick.md +++ b/integrations/claude-code-plugin/agents/sidekick.md @@ -12,11 +12,8 @@ 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. -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. +When memories from earlier sessions could help, call `search_memories` with a +focused question before searching the repository again. 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 index 6c3e1ce15..9c4949408 100644 --- a/integrations/claude-code-plugin/core/_harness_id.py +++ b/integrations/claude-code-plugin/core/_harness_id.py @@ -5,5 +5,7 @@ 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/mcp_server.py b/integrations/claude-code-plugin/core/mcp_server.py index 036fbbdc9..a0b73cb79 100644 --- a/integrations/claude-code-plugin/core/mcp_server.py +++ b/integrations/claude-code-plugin/core/mcp_server.py @@ -21,16 +21,9 @@ from memory_core import ( PROTOCOL_VERSION = "2024-11-05" TOOL_NAME = "search_memories" TOOL_DESCRIPTION = ( - "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." + "Search memories from earlier work in this repository. Use it before " + "repeating investigation or when earlier decisions, fixes, commands, or " + "results may help." ) 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 77d7a2b80..9b420a063 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.1" +PLUGIN_VERSION = "0.3.3" _harness_name: str = "generic" _harness_env_prefix: str = "MEM0_PLUGIN" @@ -71,15 +71,13 @@ MAX_FLUSH_ATTEMPTS = 5 FORGET_PAGE_SIZE = 100 FORGET_MAX_PAGES = 50 -PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository. +PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work. 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. -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. +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. -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. +Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state. If nothing useful was established, return no memories.""" @@ -1800,6 +1798,34 @@ 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]: @@ -1807,7 +1833,7 @@ def _request_json( request = urllib.request.Request( url, data=raw, - headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="POST", ) with urllib.request.urlopen(request, timeout=timeout) as response: @@ -1834,7 +1860,7 @@ def _get_json( ) -> tuple[dict[str, Any] | list[Any], int]: request = urllib.request.Request( url, - headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="GET", ) with urllib.request.urlopen(request, timeout=timeout) as response: @@ -1980,6 +2006,13 @@ 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, @@ -2523,7 +2556,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={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="DELETE", ) try: diff --git a/integrations/claude-code-plugin/plugin-build.json b/integrations/claude-code-plugin/plugin-build.json index 68d306fd6..d62d653c3 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.1", + "version": "0.3.3", "homepage": "https://docs.mem0.ai/integrations/claude-code", "native": { "pluginRoot": "${CLAUDE_PLUGIN_ROOT}", diff --git a/integrations/claude-code-plugin/skills/search/SKILL.md b/integrations/claude-code-plugin/skills/search/SKILL.md index 198a1f023..f7289b91d 100644 --- a/integrations/claude-code-plugin/skills/search/SKILL.md +++ b/integrations/claude-code-plugin/skills/search/SKILL.md @@ -12,11 +12,9 @@ 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; 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. +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 8c7017913..b6b1c28f9 100644 --- a/integrations/claude-code-plugin/tests/test_memory_core.py +++ b/integrations/claude-code-plugin/tests/test_memory_core.py @@ -2,6 +2,7 @@ from __future__ import annotations import json import os +import re import sqlite3 import subprocess import sys @@ -2306,8 +2307,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 "ALWAYS call `search_memories` before answering anything" in normalized - assert "Do not rely on the chat window" in normalized + assert "call `search_memories` with a" in normalized + assert "focused question before searching the repository again" 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 @@ -3460,7 +3461,12 @@ 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" - assert manifest["version"] == memory_core.PLUGIN_VERSION == "0.3.1" + # 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 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") @@ -4327,7 +4333,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 "invocation that succeeded" in sent_body["agent_custom_instructions"] + assert "Write about the repository, not the user" 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/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json index 916b72e66..e91eca25a 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.1", + "version": "0.3.3", "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 index 152313a21..47938ee08 100644 --- a/integrations/codex-plugin/core/_harness_id.py +++ b/integrations/codex-plugin/core/_harness_id.py @@ -5,5 +5,7 @@ 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/mcp_server.py b/integrations/codex-plugin/core/mcp_server.py index 036fbbdc9..a0b73cb79 100644 --- a/integrations/codex-plugin/core/mcp_server.py +++ b/integrations/codex-plugin/core/mcp_server.py @@ -21,16 +21,9 @@ from memory_core import ( PROTOCOL_VERSION = "2024-11-05" TOOL_NAME = "search_memories" TOOL_DESCRIPTION = ( - "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." + "Search memories from earlier work in this repository. Use it before " + "repeating investigation or when earlier decisions, fixes, commands, or " + "results may help." ) TOOL_SCHEMA = { "type": "object", diff --git a/integrations/codex-plugin/core/memory_core.py b/integrations/codex-plugin/core/memory_core.py index 77d7a2b80..9b420a063 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.1" +PLUGIN_VERSION = "0.3.3" _harness_name: str = "generic" _harness_env_prefix: str = "MEM0_PLUGIN" @@ -71,15 +71,13 @@ MAX_FLUSH_ATTEMPTS = 5 FORGET_PAGE_SIZE = 100 FORGET_MAX_PAGES = 50 -PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository. +PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work. 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. -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. +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. -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. +Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state. If nothing useful was established, return no memories.""" @@ -1800,6 +1798,34 @@ 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]: @@ -1807,7 +1833,7 @@ def _request_json( request = urllib.request.Request( url, data=raw, - headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="POST", ) with urllib.request.urlopen(request, timeout=timeout) as response: @@ -1834,7 +1860,7 @@ def _get_json( ) -> tuple[dict[str, Any] | list[Any], int]: request = urllib.request.Request( url, - headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="GET", ) with urllib.request.urlopen(request, timeout=timeout) as response: @@ -1980,6 +2006,13 @@ 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, @@ -2523,7 +2556,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={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="DELETE", ) try: diff --git a/integrations/codex-plugin/plugin-build.json b/integrations/codex-plugin/plugin-build.json index 8d4c51c07..a354c31f5 100644 --- a/integrations/codex-plugin/plugin-build.json +++ b/integrations/codex-plugin/plugin-build.json @@ -1,6 +1,6 @@ { "id": "mem0", - "version": "0.3.1", + "version": "0.3.3", "homepage": "https://docs.mem0.ai/integrations/codex", "native": { "pluginRoot": "${PLUGIN_ROOT}", diff --git a/integrations/codex-plugin/skills/search/SKILL.md b/integrations/codex-plugin/skills/search/SKILL.md index f6c27b19c..90f435008 100644 --- a/integrations/codex-plugin/skills/search/SKILL.md +++ b/integrations/codex-plugin/skills/search/SKILL.md @@ -12,11 +12,9 @@ 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; 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. +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 e33de76a2..7c2304f29 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.1", + "version": "0.3.3", "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 index 40241a7f4..0e20bf1ff 100644 --- a/integrations/cursor-plugin/core/_harness_id.py +++ b/integrations/cursor-plugin/core/_harness_id.py @@ -5,5 +5,7 @@ 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/mcp_server.py b/integrations/cursor-plugin/core/mcp_server.py index 036fbbdc9..a0b73cb79 100644 --- a/integrations/cursor-plugin/core/mcp_server.py +++ b/integrations/cursor-plugin/core/mcp_server.py @@ -21,16 +21,9 @@ from memory_core import ( PROTOCOL_VERSION = "2024-11-05" TOOL_NAME = "search_memories" TOOL_DESCRIPTION = ( - "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." + "Search memories from earlier work in this repository. Use it before " + "repeating investigation or when earlier decisions, fixes, commands, or " + "results may help." ) TOOL_SCHEMA = { "type": "object", diff --git a/integrations/cursor-plugin/core/memory_core.py b/integrations/cursor-plugin/core/memory_core.py index 77d7a2b80..9b420a063 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.1" +PLUGIN_VERSION = "0.3.3" _harness_name: str = "generic" _harness_env_prefix: str = "MEM0_PLUGIN" @@ -71,15 +71,13 @@ MAX_FLUSH_ATTEMPTS = 5 FORGET_PAGE_SIZE = 100 FORGET_MAX_PAGES = 50 -PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository. +PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work. 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. -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. +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. -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. +Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state. If nothing useful was established, return no memories.""" @@ -1800,6 +1798,34 @@ 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]: @@ -1807,7 +1833,7 @@ def _request_json( request = urllib.request.Request( url, data=raw, - headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="POST", ) with urllib.request.urlopen(request, timeout=timeout) as response: @@ -1834,7 +1860,7 @@ def _get_json( ) -> tuple[dict[str, Any] | list[Any], int]: request = urllib.request.Request( url, - headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="GET", ) with urllib.request.urlopen(request, timeout=timeout) as response: @@ -1980,6 +2006,13 @@ 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, @@ -2523,7 +2556,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={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="DELETE", ) try: diff --git a/integrations/cursor-plugin/plugin-build.json b/integrations/cursor-plugin/plugin-build.json index 279b3178c..5320fb7f9 100644 --- a/integrations/cursor-plugin/plugin-build.json +++ b/integrations/cursor-plugin/plugin-build.json @@ -1,6 +1,6 @@ { "id": "mem0", - "version": "0.3.1", + "version": "0.3.3", "homepage": "https://docs.mem0.ai/integrations/cursor", "native": { "pluginRoot": "${CURSOR_PLUGIN_ROOT}", diff --git a/integrations/cursor-plugin/skills/search/SKILL.md b/integrations/cursor-plugin/skills/search/SKILL.md index 7a7ddfa90..2e3bde6a7 100644 --- a/integrations/cursor-plugin/skills/search/SKILL.md +++ b/integrations/cursor-plugin/skills/search/SKILL.md @@ -12,11 +12,9 @@ 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; 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. +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/package.json b/integrations/deepseek-plugin/package.json index ea00bb9c5..3de2d4f13 100644 --- a/integrations/deepseek-plugin/package.json +++ b/integrations/deepseek-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@mem0/deepseek-plugin", - "version": "0.3.0", + "version": "0.3.2", "description": "Mem0 long-term memory as a native DeepSeek Harness (Cordis) plugin.", "type": "module", "license": "Apache-2.0", @@ -60,5 +60,12 @@ "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 1444b53d4..e56466e4a 100644 --- a/integrations/deepseek-plugin/pnpm-lock.yaml +++ b/integrations/deepseek-plugin/pnpm-lock.yaml @@ -4,6 +4,11 @@ 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: .: @@ -32,7 +37,7 @@ importers: version: 22.20.1 tsup: specifier: ^8.5.0 - version: 8.5.1(postcss@8.5.26)(typescript@5.9.3) + version: 8.5.1(postcss@8.5.32)(typescript@5.9.3) typescript: specifier: ^5.6.0 version: 5.9.3 @@ -277,95 +282,95 @@ packages: cpu: [x64] os: [linux] - '@oxc-project/types@0.146.0': - resolution: {integrity: sha512-XC0QsnnhVe7sLIWmYmdPw7x5P0h4W8vUU3Nv1ySgWXtvCz8NizoAEpGXA0sOYoJQV2Rl13LgURAHQ5cI5ILCSA==} + '@oxc-project/types@0.156.0': + resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} - '@rolldown/binding-android-arm-eabi@1.2.5': - resolution: {integrity: sha512-DLe/i+l8ynIBY7XEQ191TeZvCoowIGa18R+dIV30GW7DiOtp74i/xX8hs8GUjW5ARV7VZuie3d6AumSmCwbeRA==} + '@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.5': - resolution: {integrity: sha512-zXcwKlQApYAOELHd8PwKDFkagYF9Wy4e0RJ+0qnzl9Pjnpj75TEG8ufv40p2J7kCEfwZAsNiuzRIyNNMWT38ig==} + '@rolldown/binding-android-arm64@1.2.16': + resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] - '@rolldown/binding-darwin-arm64@1.2.5': - resolution: {integrity: sha512-dK4QakI42nzWgJT5sm4y4y/O//D4OxM75/cH28RLV+nzIN9AY+YsbuUVrUTjlLjXR6vpyxFbSsbmNuJ6BP9sww==} + '@rolldown/binding-darwin-arm64@1.2.16': + resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@rolldown/binding-darwin-x64@1.2.5': - resolution: {integrity: sha512-fqSALaUu1Wjd1nK2uW2kJDWdLCc8lx1IcY+MTY26Aurfdx19anlzhqXOgCFbBFQnlFDTn4TC1/7Nz4Bl2mLP3A==} + '@rolldown/binding-darwin-x64@1.2.16': + resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@rolldown/binding-freebsd-x64@1.2.5': - resolution: {integrity: sha512-/vCnNxlkxs9tKxNDcyWUePpJ/PgTzxIaVhoM5SmG8UV+GR/IcPam4VYxi7GIMo7PSDuNqlJqvprqii9NqqVCMw==} + '@rolldown/binding-freebsd-x64@1.2.16': + resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] - '@rolldown/binding-linux-arm-gnueabihf@1.2.5': - resolution: {integrity: sha512-abk0NLA519LxRCszmbE0jYKuQ9YPocOXTiOXOo6Yr+YAT95VH+PtqYAjOJvGKt3viEd/x4qzabAlwd5bHOOARg==} + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@rolldown/binding-linux-arm64-gnu@1.2.5': - resolution: {integrity: sha512-Y7eALiJ8lr0M2HH103Js+g7V34wf6snlpZLAsHI90uLhr3PVlNsbFVAXJC9d/V6BnPyKtpSwI+NcB/RLxsQxuA==} + '@rolldown/binding-linux-arm64-gnu@1.2.16': + resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] - '@rolldown/binding-linux-arm64-musl@1.2.5': - resolution: {integrity: sha512-xMvZgnbZg4YVnR/AX2b3oOPDTFYJvUVaJg5FedA/LuvexAtXibZQej4cnTkw3rjsJ/ggUROB64TdtETiim+FYA==} + '@rolldown/binding-linux-arm64-musl@1.2.16': + resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] - '@rolldown/binding-linux-ppc64-gnu@1.2.5': - resolution: {integrity: sha512-GRjeqTUDHTo5GwntsLaAMcBahG3nlpjftXWZLN73HiYQlhwEowvarFgQnRnQZtIp4keXX7quXFbG38uPZBa2EA==} + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] - '@rolldown/binding-linux-s390x-gnu@1.2.5': - resolution: {integrity: sha512-vLNTR45F2Uwc8AufkNXPmB4VliaXs+FvcheEogIzOXzO4l+LzieXF5A/TWxLy5HtqpsRCHUfd0lPVrrdgXdLHQ==} + '@rolldown/binding-linux-s390x-gnu@1.2.16': + resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] - '@rolldown/binding-linux-x64-gnu@1.2.5': - resolution: {integrity: sha512-Mgj59/HTuYeK9Gz2MA+mBWKnHsAgkBSec15ZMb1st3oIfFbX7gCjOae7GydHhzcyQi9Z/7M1QuN9bR3oFqF0jQ==} + '@rolldown/binding-linux-x64-gnu@1.2.16': + resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] - '@rolldown/binding-linux-x64-musl@1.2.5': - resolution: {integrity: sha512-mY8AP0/ichsbhAxGnLa3d3+MwV0EfgrPND2bplI3Ym8T6R2pJ0N87bvrKVwNXmdy3jnr6eQBecdqx/HMknBmpA==} + '@rolldown/binding-linux-x64-musl@1.2.16': + resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] - '@rolldown/binding-openharmony-arm64@1.2.5': - resolution: {integrity: sha512-8SLssA2oweAxyRgDp789ACfRb/3P+zNRJpzZxSizxF9m8NUDQ4+3xjo8ttjhVGGw6Qxb70oZiEtIjaKikCO7Yw==} + '@rolldown/binding-openharmony-arm64@1.2.16': + resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] - '@rolldown/binding-win32-arm64-msvc@1.2.5': - resolution: {integrity: sha512-vGbruD5zquhoc8D9SViXgN2FBJtNdTyQ4DtG+SWiEGlJiAzoKcZ2xp+xuXCffhubVdt0NJlTZqkeRuERy7g8Cw==} + '@rolldown/binding-win32-arm64-msvc@1.2.16': + resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] - '@rolldown/binding-win32-x64-msvc@1.2.5': - resolution: {integrity: sha512-e/SXpgISz+IoqVcSSI0rx/d/he8zqLex+/rCWpnHpmVfmPIUjag9H6P7zotf0gJHwPUhQxZ/mF8tr6acebT9yw==} + '@rolldown/binding-win32-x64-msvc@1.2.16': + resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] @@ -526,7 +531,7 @@ packages: resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==} peerDependencies: msw: ^2.4.9 - vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + vite: '>=8.2.4 <9.0.0' peerDependenciesMeta: msw: optional: true @@ -575,8 +580,8 @@ packages: asynckit@0.4.0: resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} - axios@1.19.0: - resolution: {integrity: sha512-ht/iuYZXEjFxLH/Hkezgd7m6JKlHHXEUSneaDz8uZe1Gj5QZtCnpyDsckvAiEnT89OEbCLmnte4R4sn7P0EKFw==} + axios@1.20.0: + resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==} bundle-require@5.1.0: resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==} @@ -686,8 +691,8 @@ packages: fix-dts-default-cjs-exports@1.0.1: resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==} - follow-redirects@1.16.0: - resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==} + follow-redirects@1.16.2: + resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==} engines: {node: '>=4.0'} peerDependencies: debug: '*' @@ -972,8 +977,8 @@ packages: mz@2.7.0: resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==} - nanoid@3.3.18: - resolution: {integrity: sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==} + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true @@ -1021,6 +1026,10 @@ 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'} @@ -1046,8 +1055,8 @@ packages: yaml: optional: true - postcss@8.5.26: - resolution: {integrity: sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==} + postcss@8.5.32: + resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} engines: {node: ^10 || ^12 || >=14} proxy-from-env@2.1.0: @@ -1062,8 +1071,8 @@ packages: resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==} engines: {node: '>=8'} - rolldown@1.2.5: - resolution: {integrity: sha512-VD2IE5PUG4Oj8zz2VGykiYd5wbnjdIiSsNQb8Qu5B+noEp+A78mu2iVvpp27g8es14Tk9rofNs5Tku9iQCS4fA==} + rolldown@1.2.16: + resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true @@ -1075,8 +1084,8 @@ packages: siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} - source-map-js@1.2.1: - resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} engines: {node: '>=0.10.0'} source-map@0.7.6: @@ -1166,13 +1175,13 @@ packages: resolution: {integrity: sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==} hasBin: true - vite@8.2.2: - resolution: {integrity: sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q==} + vite@8.3.6: + resolution: {integrity: sha512-UI7dK29NnS54Fk+mmo7o+jI6U8Fp7hDl+X5Q1k45WH+d4dSlbLVUETGQ+hfkNgvLQGyoElPj837nZyv4MBc0VA==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true peerDependencies: '@types/node': ^20.19.0 || >=22.12.0 - '@vitejs/devtools': ^0.4.0 || ^0.5.0 + '@vitejs/devtools': ^0.7.1 || ^0.8.0 esbuild: ^0.27.0 || ^0.28.0 jiti: '>=1.21.0' less: ^4.0.0 @@ -1399,51 +1408,51 @@ snapshots: '@napi-rs/lzma-linux-x64-gnu@1.5.1': optional: true - '@oxc-project/types@0.146.0': {} + '@oxc-project/types@0.156.0': {} - '@rolldown/binding-android-arm-eabi@1.2.5': + '@rolldown/binding-android-arm-eabi@1.2.16': optional: true - '@rolldown/binding-android-arm64@1.2.5': + '@rolldown/binding-android-arm64@1.2.16': optional: true - '@rolldown/binding-darwin-arm64@1.2.5': + '@rolldown/binding-darwin-arm64@1.2.16': optional: true - '@rolldown/binding-darwin-x64@1.2.5': + '@rolldown/binding-darwin-x64@1.2.16': optional: true - '@rolldown/binding-freebsd-x64@1.2.5': + '@rolldown/binding-freebsd-x64@1.2.16': optional: true - '@rolldown/binding-linux-arm-gnueabihf@1.2.5': + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': optional: true - '@rolldown/binding-linux-arm64-gnu@1.2.5': + '@rolldown/binding-linux-arm64-gnu@1.2.16': optional: true - '@rolldown/binding-linux-arm64-musl@1.2.5': + '@rolldown/binding-linux-arm64-musl@1.2.16': optional: true - '@rolldown/binding-linux-ppc64-gnu@1.2.5': + '@rolldown/binding-linux-ppc64-gnu@1.2.16': optional: true - '@rolldown/binding-linux-s390x-gnu@1.2.5': + '@rolldown/binding-linux-s390x-gnu@1.2.16': optional: true - '@rolldown/binding-linux-x64-gnu@1.2.5': + '@rolldown/binding-linux-x64-gnu@1.2.16': optional: true - '@rolldown/binding-linux-x64-musl@1.2.5': + '@rolldown/binding-linux-x64-musl@1.2.16': optional: true - '@rolldown/binding-openharmony-arm64@1.2.5': + '@rolldown/binding-openharmony-arm64@1.2.16': optional: true - '@rolldown/binding-win32-arm64-msvc@1.2.5': + '@rolldown/binding-win32-arm64-msvc@1.2.16': optional: true - '@rolldown/binding-win32-x64-msvc@1.2.5': + '@rolldown/binding-win32-x64-msvc@1.2.16': optional: true '@rolldown/pluginutils@1.0.1': {} @@ -1556,13 +1565,13 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.1 - '@vitest/mocker@4.1.11(vite@8.2.2(@types/node@22.20.1)(esbuild@0.27.7))': + '@vitest/mocker@4.1.11(vite@8.3.6(@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.2.2(@types/node@22.20.1)(esbuild@0.27.7) + vite: 8.3.6(@types/node@22.20.1)(esbuild@0.27.7) '@vitest/pretty-format@4.1.11': dependencies: @@ -1610,9 +1619,9 @@ snapshots: asynckit@0.4.0: {} - axios@1.19.0: + axios@1.20.0: dependencies: - follow-redirects: 1.16.0 + follow-redirects: 1.16.2 form-data: 4.0.6 https-proxy-agent: 5.0.1 proxy-from-env: 2.1.0 @@ -1728,7 +1737,7 @@ snapshots: mlly: 1.8.2 rollup: 4.62.5 - follow-redirects@1.16.0: {} + follow-redirects@1.16.2: {} form-data-encoder@1.7.2: {} @@ -1856,7 +1865,7 @@ snapshots: mem0ai@3.1.6: dependencies: - axios: 1.19.0 + axios: 1.20.0 openai: 4.104.0(zod@3.25.76) uuid: 11.1.1 zod: 3.25.76 @@ -1887,7 +1896,7 @@ snapshots: object-assign: 4.1.1 thenify-all: 1.6.0 - nanoid@3.3.18: {} + nanoid@3.3.20: {} node-domexception@1.0.0: {} @@ -1919,6 +1928,8 @@ snapshots: picomatch@4.0.5: {} + picomatch@4.0.7: {} + pirates@4.0.7: {} pkg-types@1.3.1: @@ -1927,17 +1938,17 @@ snapshots: mlly: 1.8.2 pathe: 2.0.3 - postcss-load-config@6.0.1(postcss@8.5.26): + postcss-load-config@6.0.1(postcss@8.5.32): dependencies: lilconfig: 3.1.3 optionalDependencies: - postcss: 8.5.26 + postcss: 8.5.32 - postcss@8.5.26: + postcss@8.5.32: dependencies: - nanoid: 3.3.18 + nanoid: 3.3.20 picocolors: 1.1.1 - source-map-js: 1.2.1 + source-map-js: 1.2.2 proxy-from-env@2.1.0: {} @@ -1945,26 +1956,26 @@ snapshots: resolve-from@5.0.0: {} - rolldown@1.2.5: + rolldown@1.2.16: dependencies: - '@oxc-project/types': 0.146.0 + '@oxc-project/types': 0.156.0 '@rolldown/pluginutils': 1.0.1 optionalDependencies: - '@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 + '@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 rollup@4.62.5: dependencies: @@ -2000,7 +2011,7 @@ snapshots: siginfo@2.0.0: {} - source-map-js@1.2.1: {} + source-map-js@1.2.2: {} source-map@0.7.6: {} @@ -2045,7 +2056,7 @@ snapshots: ts-interface-checker@0.1.13: {} - tsup@8.5.1(postcss@8.5.26)(typescript@5.9.3): + tsup@8.5.1(postcss@8.5.32)(typescript@5.9.3): dependencies: bundle-require: 5.1.0(esbuild@0.27.7) cac: 6.7.14 @@ -2056,7 +2067,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.26) + postcss-load-config: 6.0.1(postcss@8.5.32) resolve-from: 5.0.0 rollup: 4.62.5 source-map: 0.7.6 @@ -2065,7 +2076,7 @@ snapshots: tinyglobby: 0.2.17 tree-kill: 1.2.2 optionalDependencies: - postcss: 8.5.26 + postcss: 8.5.32 typescript: 5.9.3 transitivePeerDependencies: - jiti @@ -2083,12 +2094,12 @@ snapshots: uuid@11.1.1: {} - vite@8.2.2(@types/node@22.20.1)(esbuild@0.27.7): + vite@8.3.6(@types/node@22.20.1)(esbuild@0.27.7): dependencies: lightningcss: 1.33.0 - picomatch: 4.0.5 - postcss: 8.5.26 - rolldown: 1.2.5 + picomatch: 4.0.7 + postcss: 8.5.32 + rolldown: 1.2.16 tinyglobby: 0.2.17 optionalDependencies: '@types/node': 22.20.1 @@ -2098,7 +2109,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.2.2(@types/node@22.20.1)(esbuild@0.27.7)) + '@vitest/mocker': 4.1.11(vite@8.3.6(@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 @@ -2115,7 +2126,7 @@ snapshots: tinyexec: 1.3.0 tinyglobby: 0.2.17 tinyrainbow: 3.1.1 - vite: 8.2.2(@types/node@22.20.1)(esbuild@0.27.7) + vite: 8.3.6(@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 2d24b498a..c5eb64390 100644 --- a/integrations/deepseek-plugin/src/index.ts +++ b/integrations/deepseek-plugin/src/index.ts @@ -21,13 +21,19 @@ 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. The backend's KNOWN_EVENT_SOURCES allowlist recognizes this value; -// anything outside it buckets into "OTHERS". +// 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. const SOURCE = "DEEPSEEK_HARNESS"; const DEFAULT_SEARCH_LIMIT = 10; @@ -106,7 +112,7 @@ export function apply(ctx: Context, config: Config): void { const stateFor = (session: object): SessionState => { let state = sessionStates.get(session); if (!state) { - const lifecycle = createMemoryLifecycle(); + const lifecycle = createMemoryLifecycle({ recallHeading: USER_RECALL_HEADING }); lifecycle.beginSession(); state = { lifecycle, messages: [] }; sessionStates.set(session, state); @@ -196,10 +202,9 @@ export function apply(ctx: Context, config: Config): void { ctx.tools.register( defineTool({ name: "search_memory", - 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.", + description: USER_SEARCH_TOOL_DESCRIPTION, parameters: { - query: { type: "string", description: "What to recall.", required: true }, + query: { type: "string", description: USER_SEARCH_QUERY_DESCRIPTION, 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 new file mode 100644 index 000000000..00f2d38d8 --- /dev/null +++ b/integrations/hermes-plugin-mem0/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.pyc +.venv/ diff --git a/integrations/hermes-plugin-mem0/LICENSE b/integrations/hermes-plugin-mem0/LICENSE new file mode 100644 index 000000000..5ee05954c --- /dev/null +++ b/integrations/hermes-plugin-mem0/LICENSE @@ -0,0 +1,236 @@ + 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 new file mode 100644 index 000000000..ad4d2f87e --- /dev/null +++ b/integrations/hermes-plugin-mem0/README.md @@ -0,0 +1,131 @@ +# 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 new file mode 100644 index 000000000..1ab504753 --- /dev/null +++ b/integrations/hermes-plugin-mem0/__init__.py @@ -0,0 +1,504 @@ +"""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 new file mode 100644 index 000000000..455750207 --- /dev/null +++ b/integrations/hermes-plugin-mem0/_backend.py @@ -0,0 +1,336 @@ +"""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 new file mode 100644 index 000000000..ed1296364 --- /dev/null +++ b/integrations/hermes-plugin-mem0/_openai_llm.py @@ -0,0 +1,66 @@ +"""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 new file mode 100644 index 000000000..c6ced627f --- /dev/null +++ b/integrations/hermes-plugin-mem0/_oss_providers.py @@ -0,0 +1,53 @@ +"""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 new file mode 100644 index 000000000..302129c18 --- /dev/null +++ b/integrations/hermes-plugin-mem0/_setup.py @@ -0,0 +1,567 @@ +"""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 new file mode 100644 index 000000000..c6ae10acc --- /dev/null +++ b/integrations/hermes-plugin-mem0/plugin.yaml @@ -0,0 +1,5 @@ +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 new file mode 100644 index 000000000..962237b28 --- /dev/null +++ b/integrations/hermes-plugin-mem0/pyproject.toml @@ -0,0 +1,17 @@ +[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 new file mode 100644 index 000000000..14fdcc0ac --- /dev/null +++ b/integrations/hermes-plugin-mem0/tests/smoke_hermes.py @@ -0,0 +1,178 @@ +"""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 new file mode 100644 index 000000000..6993948b7 --- /dev/null +++ b/integrations/hermes-plugin-mem0/tests/test_plugin.py @@ -0,0 +1,286 @@ +"""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 index aa17750b1..83ab061ef 100644 --- a/integrations/kimi-plugin/core/_harness_id.py +++ b/integrations/kimi-plugin/core/_harness_id.py @@ -5,5 +5,7 @@ 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/mcp_server.py b/integrations/kimi-plugin/core/mcp_server.py index 036fbbdc9..a0b73cb79 100644 --- a/integrations/kimi-plugin/core/mcp_server.py +++ b/integrations/kimi-plugin/core/mcp_server.py @@ -21,16 +21,9 @@ from memory_core import ( PROTOCOL_VERSION = "2024-11-05" TOOL_NAME = "search_memories" TOOL_DESCRIPTION = ( - "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." + "Search memories from earlier work in this repository. Use it before " + "repeating investigation or when earlier decisions, fixes, commands, or " + "results may help." ) TOOL_SCHEMA = { "type": "object", diff --git a/integrations/kimi-plugin/core/memory_core.py b/integrations/kimi-plugin/core/memory_core.py index 77d7a2b80..9b420a063 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.1" +PLUGIN_VERSION = "0.3.3" _harness_name: str = "generic" _harness_env_prefix: str = "MEM0_PLUGIN" @@ -71,15 +71,13 @@ MAX_FLUSH_ATTEMPTS = 5 FORGET_PAGE_SIZE = 100 FORGET_MAX_PAGES = 50 -PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository. +PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work. 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. -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. +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. -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. +Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state. If nothing useful was established, return no memories.""" @@ -1800,6 +1798,34 @@ 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]: @@ -1807,7 +1833,7 @@ def _request_json( request = urllib.request.Request( url, data=raw, - headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="POST", ) with urllib.request.urlopen(request, timeout=timeout) as response: @@ -1834,7 +1860,7 @@ def _get_json( ) -> tuple[dict[str, Any] | list[Any], int]: request = urllib.request.Request( url, - headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="GET", ) with urllib.request.urlopen(request, timeout=timeout) as response: @@ -1980,6 +2006,13 @@ 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, @@ -2523,7 +2556,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={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="DELETE", ) try: diff --git a/integrations/kimi-plugin/kimi.plugin.json b/integrations/kimi-plugin/kimi.plugin.json index 0d63501fe..6b28575d3 100644 --- a/integrations/kimi-plugin/kimi.plugin.json +++ b/integrations/kimi-plugin/kimi.plugin.json @@ -1,6 +1,6 @@ { "name": "mem0", - "version": "0.3.1", + "version": "0.3.3", "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 3926a57df..35e38ecf5 100644 --- a/integrations/kimi-plugin/plugin-build.json +++ b/integrations/kimi-plugin/plugin-build.json @@ -1,6 +1,6 @@ { "id": "mem0", - "version": "0.3.1", + "version": "0.3.3", "homepage": "https://docs.mem0.ai/integrations/kimi", "native": { "pluginRoot": "${KIMI_PLUGIN_ROOT}", diff --git a/integrations/kimi-plugin/skills/search/SKILL.md b/integrations/kimi-plugin/skills/search/SKILL.md index eb92a6ca8..316b78e53 100644 --- a/integrations/kimi-plugin/skills/search/SKILL.md +++ b/integrations/kimi-plugin/skills/search/SKILL.md @@ -12,11 +12,9 @@ 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; 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. +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 index b0836d6de..3efd000f8 100644 --- a/integrations/mem0-agent-plugin/core/_harness_id.py +++ b/integrations/mem0-agent-plugin/core/_harness_id.py @@ -5,5 +5,7 @@ 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 = "coding-agent" +PLATFORM_APPLICATION = "" diff --git a/integrations/mem0-agent-plugin/core/mcp_server.py b/integrations/mem0-agent-plugin/core/mcp_server.py index 036fbbdc9..a0b73cb79 100644 --- a/integrations/mem0-agent-plugin/core/mcp_server.py +++ b/integrations/mem0-agent-plugin/core/mcp_server.py @@ -21,16 +21,9 @@ from memory_core import ( PROTOCOL_VERSION = "2024-11-05" TOOL_NAME = "search_memories" TOOL_DESCRIPTION = ( - "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." + "Search memories from earlier work in this repository. Use it before " + "repeating investigation or when earlier decisions, fixes, commands, or " + "results may help." ) 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 77d7a2b80..9b420a063 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.1" +PLUGIN_VERSION = "0.3.3" _harness_name: str = "generic" _harness_env_prefix: str = "MEM0_PLUGIN" @@ -71,15 +71,13 @@ MAX_FLUSH_ATTEMPTS = 5 FORGET_PAGE_SIZE = 100 FORGET_MAX_PAGES = 50 -PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help anyone with future coding work in this repository. +PROJECT_MEMORY_INSTRUCTIONS = """Save concise repository facts that will help with future coding work. 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. -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. +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. -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. +Write about the repository, not the user, assistant, session, or task. Do not include test results, documentation updates, release notes, or temporary state. If nothing useful was established, return no memories.""" @@ -1800,6 +1798,34 @@ 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]: @@ -1807,7 +1833,7 @@ def _request_json( request = urllib.request.Request( url, data=raw, - headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="POST", ) with urllib.request.urlopen(request, timeout=timeout) as response: @@ -1834,7 +1860,7 @@ def _get_json( ) -> tuple[dict[str, Any] | list[Any], int]: request = urllib.request.Request( url, - headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="GET", ) with urllib.request.urlopen(request, timeout=timeout) as response: @@ -1980,6 +2006,13 @@ 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, @@ -2523,7 +2556,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={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + headers=platform_headers(key), method="DELETE", ) try: diff --git a/integrations/mem0-agent-plugin/plugin.json b/integrations/mem0-agent-plugin/plugin.json index 2cbaa99de..95ff54651 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.1", + "version": "0.3.3", "description": "Cross-session memory and token savings for coding agents.", "author": { "name": "Mem0", diff --git a/integrations/mem0-agent-plugin/skills/search/SKILL.md b/integrations/mem0-agent-plugin/skills/search/SKILL.md index d52c4ff34..bbd4eb535 100644 --- a/integrations/mem0-agent-plugin/skills/search/SKILL.md +++ b/integrations/mem0-agent-plugin/skills/search/SKILL.md @@ -10,11 +10,9 @@ 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; 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. +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/n8n-nodes-mem0/package.json b/integrations/n8n-nodes-mem0/package.json index 207dbbc7c..08fd754ae 100644 --- a/integrations/n8n-nodes-mem0/package.json +++ b/integrations/n8n-nodes-mem0/package.json @@ -74,8 +74,9 @@ "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.1": ">=3.15.1 <4.0.0", - "js-yaml@>=4.0.0 <4.3.1": ">=4.3.1 <5.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", + "handlebars@<4.7.10": ">=4.7.10 <5.0.0" } } } diff --git a/integrations/n8n-nodes-mem0/pnpm-lock.yaml b/integrations/n8n-nodes-mem0/pnpm-lock.yaml index 41440b3ca..b802536a2 100644 --- a/integrations/n8n-nodes-mem0/pnpm-lock.yaml +++ b/integrations/n8n-nodes-mem0/pnpm-lock.yaml @@ -11,8 +11,9 @@ 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.1: '>=3.15.1 <4.0.0' - js-yaml@>=4.0.0 <4.3.1: '>=4.3.1 <5.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' + handlebars@<4.7.10: '>=4.7.10 <5.0.0' importers: @@ -1146,8 +1147,8 @@ packages: resolution: {integrity: sha512-V2FaKiOhpR3DRXZuYdRLn/qiY0yI5XmqbTKrYbdemJ+xOh2d2MOweI/XFgMzd/9+1twdvMwllnZbWZNJ+BOm4A==} engines: {node: '>= 10.13.0'} - handlebars@4.7.9: - resolution: {integrity: sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==} + handlebars@4.7.10: + resolution: {integrity: sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==} engines: {node: '>=0.4.7'} hasBin: true @@ -1494,12 +1495,12 @@ packages: js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} - js-yaml@3.15.1: - resolution: {integrity: sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==} + js-yaml@3.15.2: + resolution: {integrity: sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==} hasBin: true - js-yaml@4.3.1: - resolution: {integrity: sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==} + js-yaml@4.3.2: + resolution: {integrity: sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA==} hasBin: true jsesc@3.1.0: @@ -2506,7 +2507,7 @@ snapshots: globals: 13.24.0 ignore: 5.3.2 import-fresh: 3.3.1 - js-yaml: 4.3.1 + js-yaml: 4.3.2 minimatch: 3.1.5 strip-json-comments: 3.1.1 transitivePeerDependencies: @@ -2546,7 +2547,7 @@ snapshots: camelcase: 5.3.1 find-up: 4.1.0 get-package-type: 0.1.0 - js-yaml: 3.15.1 + js-yaml: 3.15.2 resolve-from: 5.0.0 '@istanbuljs/schema@0.1.6': {} @@ -3353,7 +3354,7 @@ snapshots: imurmurhash: 0.1.4 is-glob: 4.0.3 is-path-inside: 3.0.3 - js-yaml: 4.3.1 + js-yaml: 4.3.2 json-stable-stringify-without-jsonify: 1.0.1 levn: 0.4.1 lodash.merge: 4.6.2 @@ -3658,7 +3659,7 @@ snapshots: dependencies: glogg: 2.2.0 - handlebars@4.7.9: + handlebars@4.7.10: dependencies: minimist: 1.2.8 neo-async: 2.6.2 @@ -4173,12 +4174,12 @@ snapshots: js-tokens@4.0.0: {} - js-yaml@3.15.1: + js-yaml@3.15.2: dependencies: argparse: 1.0.10 esprima: 4.0.1 - js-yaml@4.3.1: + js-yaml@4.3.2: dependencies: argparse: 2.0.1 @@ -4758,7 +4759,7 @@ snapshots: dependencies: bs-logger: 0.2.6 fast-json-stable-stringify: 2.1.0 - handlebars: 4.7.9 + handlebars: 4.7.10 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 99453cb1b..a34d6c08b 100644 --- a/integrations/openclaw/cli/config-file.ts +++ b/integrations/openclaw/cli/config-file.ts @@ -35,6 +35,8 @@ export interface PluginAuthConfig { autoCapture?: boolean; topK?: number; anonymousTelemetryId?: string; + /** SHA-256 prefix of the API key userEmail was resolved for. */ + keyFingerprint?: string; } // ============================================================================ @@ -135,6 +137,9 @@ 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, }; } @@ -236,6 +241,21 @@ 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 4e43c8c44..09dcbc837 100644 --- a/integrations/openclaw/config.ts +++ b/integrations/openclaw/config.ts @@ -148,6 +148,7 @@ 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 2d9f46518..e3b299112 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.1.0", + "version": "1.2.1", "kind": "memory", "skills": ["skills"], "commandAliases": [ @@ -209,6 +209,10 @@ "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 03938e4da..33e315314 100644 --- a/integrations/openclaw/package.json +++ b/integrations/openclaw/package.json @@ -1,6 +1,6 @@ { "name": "@mem0/openclaw-mem0", - "version": "1.1.0", + "version": "1.2.1", "type": "module", "description": "Mem0 memory backend for OpenClaw โ€” platform or self-hosted open-source", "license": "Apache-2.0", @@ -59,23 +59,26 @@ "@vitest/coverage-v8": "^4.1.11", "tsup": "^8.5.0", "typescript": "^5.8.3", - "vite": "^8.0.5", + "vite": "^8.1.6", "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.0.5", + "vite": "^8.1.6", "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.29.0": ">=7.29.0 <8.0.0", - "axios@<1.18.0": ">=1.18.0 <2.0.0", + "undici@<7.30.1": ">=7.30.1 <8.0.0", + "axios@<1.20.0": ">=1.20.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" + "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/pnpm-lock.yaml b/integrations/openclaw/pnpm-lock.yaml index 79dd0d10a..cce1cf61c 100644 --- a/integrations/openclaw/pnpm-lock.yaml +++ b/integrations/openclaw/pnpm-lock.yaml @@ -5,18 +5,21 @@ 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.0.5 + vite: ^8.1.6 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.29.0: '>=7.29.0 <8.0.0' - axios@<1.18.0: '>=1.18.0 <2.0.0' + undici@<7.30.1: '>=7.30.1 <8.0.0' + axios@<1.20.0: '>=1.20.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: @@ -27,7 +30,7 @@ importers: version: 0.34.47 mem0ai: specifier: 3.0.7 - 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) + 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) devDependencies: '@qdrant/js-client-rest': specifier: ^1.18.0 @@ -40,16 +43,16 @@ importers: version: 4.1.11(vitest@4.1.11) tsup: specifier: ^8.5.0 - version: 8.5.1(postcss@8.5.23)(typescript@5.9.3) + version: 8.5.1(postcss@8.5.32)(typescript@5.9.3) typescript: specifier: ^5.8.3 version: 5.9.3 vite: - specifier: ^8.0.5 - version: 8.0.16(@types/node@22.19.20)(esbuild@0.28.1) + specifier: ^8.1.6 + version: 8.3.6(@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.0.16(@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.3.6(@types/node@22.19.20)(esbuild@0.28.1)) packages: @@ -79,6 +82,10 @@ 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'} @@ -91,9 +98,9 @@ packages: resolution: {integrity: sha512-XPArKLzsvl0Hf0CaGyKHUyVgF7oDnhKoP85Xv6M4StF/1AhfORhZudHtOyf2s+FcbuQ9dPRAjB8J2KvRRMUK2A==} engines: {node: '>=20.0.0'} - '@azure/identity@4.13.1': - resolution: {integrity: sha512-5C/2WD5Vb1lHnZS16dNQRPMjN6oV/Upba+C9nBIs15PmOi6A3ZGs4Lr2u60zw4S04gi+u3cEXiqTVP7M4Pz3kw==} - engines: {node: '>=20.0.0'} + '@azure/identity@4.14.1': + resolution: {integrity: sha512-HHuuFrmN1uuF9D5A6aAo5eHzNFNX4Q+P4SksZqDKse5YaJFFy/zDLG3wXHEV2FVGgetZ3QM8jGURNBtnQYf1NQ==} + engines: {node: '>=22.0.0'} '@azure/logger@1.3.0': resolution: {integrity: sha512-fCqPIfOcLE+CGqGPd66c8bZpwAji98tZ4JI9i/mlTNTlsIWslCfpg48s/ypyLxZTump5sypjrKn2/kY7q8oAbA==} @@ -103,12 +110,16 @@ 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@5.2.3': - resolution: {integrity: sha512-YYX4TchEVddVBiybKvKhV9QO/q22jgewP+BVxKG7Uh115voPcviGlypbKERDsqQdAiSTJrwi80gcWFjYKdo8+Q==} + '@azure/msal-node@7.2.0': + resolution: {integrity: sha512-Y87VJsMWF4jiqLqq8XYLb1o+rGc/HacwS3Zydi3bDtaVm5Sa8FlB7YrKrBFKRIYj27RJXAaDkErImMAqtM10Pg==} engines: {node: '>=20'} '@azure/search-documents@12.2.0': @@ -146,15 +157,6 @@ 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'} @@ -355,14 +357,8 @@ 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 - - '@oxc-project/types@0.133.0': - resolution: {integrity: sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==} + '@oxc-project/types@0.156.0': + resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} '@protobufjs/aspromise@1.1.2': resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==} @@ -437,97 +433,98 @@ packages: peerDependencies: '@redis/client': ^5.12.1 - '@rolldown/binding-android-arm64@1.0.3': - resolution: {integrity: sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==} + '@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==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] - '@rolldown/binding-darwin-arm64@1.0.3': - resolution: {integrity: sha512-PcAhP+ynjURNyy8SKGl5DQP94aGuB/7JrXJb/t7P+hanXvQVMWzUvRRhBAcg/lNRadBhoUPqSoP4xw5tR/KBEA==} + '@rolldown/binding-darwin-arm64@1.2.16': + resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@rolldown/binding-darwin-x64@1.0.3': - resolution: {integrity: sha512-9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg==} + '@rolldown/binding-darwin-x64@1.2.16': + resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@rolldown/binding-freebsd-x64@1.0.3': - resolution: {integrity: sha512-yB1IlAsSNHncV6SCTL27/MVGR5htvQsoGxIv5KMGXALp+Ll1wYsn+x98M9MW7qa+NdSbvrrY7ANI4wLJ0n1e6g==} + '@rolldown/binding-freebsd-x64@1.2.16': + resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] - '@rolldown/binding-linux-arm-gnueabihf@1.0.3': - resolution: {integrity: sha512-Yi30IVAAfLUCy2MseFjbB1jAMDl1VMCAas5StnYp8da9+CKvMd2H2cbEjWcw5NPaPqzvYkVIaF1nNUG+b7u/sw==} + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@rolldown/binding-linux-arm64-gnu@1.0.3': - resolution: {integrity: sha512-jsO7R8To+AdlYgUmN5sHSCZbfhtMBkO0WUx8iORQnPcMMdgr7qM2DQmMwgabs3GhNztdmoKkMKQFHD6DTMCIQw==} + '@rolldown/binding-linux-arm64-gnu@1.2.16': + resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-arm64-musl@1.0.3': - resolution: {integrity: sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==} + '@rolldown/binding-linux-arm64-musl@1.2.16': + resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [musl] - '@rolldown/binding-linux-ppc64-gnu@1.0.3': - resolution: {integrity: sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==} + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-s390x-gnu@1.0.3': - resolution: {integrity: sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==} + '@rolldown/binding-linux-s390x-gnu@1.2.16': + resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] libc: [glibc] - '@rolldown/binding-linux-x64-gnu@1.0.3': - resolution: {integrity: sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==} + '@rolldown/binding-linux-x64-gnu@1.2.16': + resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-x64-musl@1.0.3': - resolution: {integrity: sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==} + '@rolldown/binding-linux-x64-musl@1.2.16': + resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [musl] - '@rolldown/binding-openharmony-arm64@1.0.3': - resolution: {integrity: sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==} + '@rolldown/binding-openharmony-arm64@1.2.16': + resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] - '@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==} + '@rolldown/binding-win32-arm64-msvc@1.2.16': + resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] - '@rolldown/binding-win32-x64-msvc@1.0.3': - resolution: {integrity: sha512-eXB7CHuaQdqmJcc3koCNtNPmT/bj2gc999kUFgBxG8Ac0NdgXc4rkCHhqrgrhN3zddvvvrgzj1e90SuSfmyIXA==} + '@rolldown/binding-win32-x64-msvc@1.2.16': + resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] @@ -709,9 +706,6 @@ 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==} @@ -783,7 +777,7 @@ packages: resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==} peerDependencies: msw: ^2.4.9 - vite: ^8.0.5 + vite: ^8.1.6 peerDependenciesMeta: msw: optional: true @@ -857,8 +851,8 @@ packages: asynckit@0.4.0: resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} - axios@1.18.1: - resolution: {integrity: sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==} + axios@1.20.0: + resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==} base-64@0.1.0: resolution: {integrity: sha512-Y5gU45svrR5tI2Vt/X9GPd3L0HNIKzGu202EjxrXMpuc2V2CiKgemAbUUsqYmZJvPtCXoUKjNZwBJzsNScUbXA==} @@ -1001,8 +995,8 @@ packages: resolution: {integrity: sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==} engines: {node: '>=18'} - default-browser@5.5.0: - resolution: {integrity: sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw==} + default-browser@5.5.1: + resolution: {integrity: sha512-m1pAzaJgZ/gssEqlOhJkPJp8Xly7QyW6xcrkUa2KKcDeDSEMP7X8xipU3snUcfisTQx0w1AGae+9UtJSfVnXGw==} engines: {node: '>=18'} define-lazy-prop@3.0.0: @@ -1122,8 +1116,8 @@ packages: fix-dts-default-cjs-exports@1.0.1: resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==} - follow-redirects@1.16.0: - resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==} + follow-redirects@1.16.2: + resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==} engines: {node: '>=4.0'} peerDependencies: debug: '*' @@ -1253,6 +1247,10 @@ 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'} @@ -1348,78 +1346,78 @@ packages: ws: optional: true - lightningcss-android-arm64@1.32.0: - resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==} + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [android] - lightningcss-darwin-arm64@1.32.0: - resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==} + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [darwin] - lightningcss-darwin-x64@1.32.0: - resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==} + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [darwin] - lightningcss-freebsd-x64@1.32.0: - resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==} + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [freebsd] - lightningcss-linux-arm-gnueabihf@1.32.0: - resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==} + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} engines: {node: '>= 12.0.0'} cpu: [arm] os: [linux] - lightningcss-linux-arm64-gnu@1.32.0: - resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==} + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] libc: [glibc] - lightningcss-linux-arm64-musl@1.32.0: - resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==} + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] libc: [musl] - lightningcss-linux-x64-gnu@1.32.0: - resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==} + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] libc: [glibc] - lightningcss-linux-x64-musl@1.32.0: - resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==} + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] libc: [musl] - lightningcss-win32-arm64-msvc@1.32.0: - resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==} + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [win32] - lightningcss-win32-x64-msvc@1.32.0: - resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==} + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [win32] - lightningcss@1.32.0: - resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==} + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} engines: {node: '>= 12.0.0'} lilconfig@3.1.3: @@ -1479,7 +1477,7 @@ packages: engines: {node: '>=18'} peerDependencies: '@anthropic-ai/sdk': ^0.40.1 - '@azure/identity': ^4.0.0 + '@azure/identity': '>=4.14.1 <5.0.0' '@azure/search-documents': ^12.0.0 '@cloudflare/workers-types': ^4.20250504.0 '@google/genai': ^1.40.0 @@ -1583,8 +1581,8 @@ packages: mz@2.7.0: resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==} - nanoid@3.3.16: - resolution: {integrity: sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==} + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true @@ -1634,9 +1632,9 @@ packages: once@1.4.0: resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} - open@10.2.0: - resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==} - engines: {node: '>=18'} + open@11.0.4: + resolution: {integrity: sha512-++Zlftm0kVLPmzC06t6epuWmcRMDbI4z5P3NNX979WA/k23+NtSOynEGzsVfZwguKw2mi5umVgnBlJQMwRz4Pg==} + engines: {node: '>=20'} openai@4.104.0: resolution: {integrity: sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==} @@ -1734,6 +1732,10 @@ 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'} @@ -1759,8 +1761,8 @@ packages: yaml: optional: true - postcss@8.5.23: - resolution: {integrity: sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==} + postcss@8.5.32: + resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} engines: {node: ^10 || ^12 || >=14} postgres-array@2.0.0: @@ -1798,6 +1800,10 @@ 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'} @@ -1850,8 +1856,8 @@ packages: resolution: {integrity: sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==} engines: {node: '>= 4'} - rolldown@1.0.3: - resolution: {integrity: sha512-i00lAJ2ks1BYr7rjNjKC7BcqAS7nVfiT3QX1SI5aY+AFHblCmaUf9OE9dbdzDvW6dJxbi2ZCZiy9v3CcwOiX3g==} + rolldown@1.2.16: + resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true @@ -1892,8 +1898,8 @@ packages: resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==} engines: {node: '>=8'} - source-map-js@1.2.1: - resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} engines: {node: '>=0.10.0'} source-map@0.7.6: @@ -2036,8 +2042,8 @@ packages: undici-types@6.21.0: resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} - undici@7.29.0: - resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==} + undici@7.30.2: + resolution: {integrity: sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==} engines: {node: '>=20.18.1'} util-deprecate@1.0.2: @@ -2051,13 +2057,13 @@ packages: resolution: {integrity: sha512-Qo+uWgilfSmAhXCMav1uYFynlQO7fMFiMVZsQqZRMIXp0O7rR7qjkj+cPvBHLgBqi960QCoo/PH2/6ZtVqKvrg==} hasBin: true - vite@8.0.16: - resolution: {integrity: sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==} + vite@8.3.6: + resolution: {integrity: sha512-UI7dK29NnS54Fk+mmo7o+jI6U8Fp7hDl+X5Q1k45WH+d4dSlbLVUETGQ+hfkNgvLQGyoElPj837nZyv4MBc0VA==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true peerDependencies: '@types/node': ^20.19.0 || >=22.12.0 - '@vitejs/devtools': ^0.1.18 + '@vitejs/devtools': ^0.7.1 || ^0.8.0 esbuild: '>=0.28.1' jiti: '>=1.21.0' less: ^4.0.0 @@ -2110,7 +2116,7 @@ packages: '@vitest/ui': 4.1.11 happy-dom: '*' jsdom: '*' - vite: ^8.0.5 + vite: ^8.1.6 peerDependenciesMeta: '@edge-runtime/vm': optional: true @@ -2184,9 +2190,9 @@ packages: utf-8-validate: optional: true - wsl-utils@0.1.0: - resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==} - engines: {node: '>=18'} + wsl-utils@1.0.1: + resolution: {integrity: sha512-c16PKLIRxBYpR3jSWsdS7SFp0COm5SOQdiFjY818dYFHJbMGuLBszpF07LBWmOS1uzrHa9VGdynsEgoeKy0oOQ==} + engines: {node: '>=20'} xtend@4.0.2: resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} @@ -2251,6 +2257,8 @@ 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 @@ -2275,18 +2283,19 @@ snapshots: transitivePeerDependencies: - supports-color - '@azure/identity@4.13.1': + '@azure/identity@4.14.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': 5.2.3 - open: 10.2.0 + '@azure/msal-node': 7.2.0 + open: 11.0.4 tslib: 2.8.1 transitivePeerDependencies: - supports-color @@ -2302,11 +2311,13 @@ snapshots: dependencies: '@azure/msal-common': 16.7.0 + '@azure/msal-common@16.16.0': {} + '@azure/msal-common@16.7.0': {} - '@azure/msal-node@5.2.3': + '@azure/msal-node@7.2.0': dependencies: - '@azure/msal-common': 16.7.0 + '@azure/msal-common': 16.16.0 jsonwebtoken: 9.0.3 '@azure/search-documents@12.2.0': @@ -2349,22 +2360,6 @@ 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 @@ -2514,14 +2509,7 @@ 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 - - '@oxc-project/types@0.133.0': {} + '@oxc-project/types@0.156.0': {} '@protobufjs/aspromise@1.1.2': {} @@ -2547,7 +2535,7 @@ snapshots: dependencies: '@qdrant/openapi-typescript-fetch': 1.2.6 typescript: 5.9.3 - undici: 7.29.0 + undici: 7.30.2 '@qdrant/openapi-typescript-fetch@1.2.6': {} @@ -2571,53 +2559,49 @@ snapshots: dependencies: '@redis/client': 5.12.1 - '@rolldown/binding-android-arm64@1.0.3': + '@rolldown/binding-android-arm-eabi@1.2.16': optional: true - '@rolldown/binding-darwin-arm64@1.0.3': + '@rolldown/binding-android-arm64@1.2.16': optional: true - '@rolldown/binding-darwin-x64@1.0.3': + '@rolldown/binding-darwin-arm64@1.2.16': optional: true - '@rolldown/binding-freebsd-x64@1.0.3': + '@rolldown/binding-darwin-x64@1.2.16': optional: true - '@rolldown/binding-linux-arm-gnueabihf@1.0.3': + '@rolldown/binding-freebsd-x64@1.2.16': optional: true - '@rolldown/binding-linux-arm64-gnu@1.0.3': + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': optional: true - '@rolldown/binding-linux-arm64-musl@1.0.3': + '@rolldown/binding-linux-arm64-gnu@1.2.16': optional: true - '@rolldown/binding-linux-ppc64-gnu@1.0.3': + '@rolldown/binding-linux-arm64-musl@1.2.16': optional: true - '@rolldown/binding-linux-s390x-gnu@1.0.3': + '@rolldown/binding-linux-ppc64-gnu@1.2.16': optional: true - '@rolldown/binding-linux-x64-gnu@1.0.3': + '@rolldown/binding-linux-s390x-gnu@1.2.16': optional: true - '@rolldown/binding-linux-x64-musl@1.0.3': + '@rolldown/binding-linux-x64-gnu@1.2.16': optional: true - '@rolldown/binding-openharmony-arm64@1.0.3': + '@rolldown/binding-linux-x64-musl@1.2.16': optional: true - '@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) + '@rolldown/binding-openharmony-arm64@1.2.16': optional: true - '@rolldown/binding-win32-arm64-msvc@1.0.3': + '@rolldown/binding-win32-arm64-msvc@1.2.16': optional: true - '@rolldown/binding-win32-x64-msvc@1.0.3': + '@rolldown/binding-win32-x64-msvc@1.2.16': optional: true '@rolldown/pluginutils@1.0.1': {} @@ -2735,11 +2719,6 @@ 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 @@ -2819,7 +2798,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.0.16(@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.3.6(@types/node@22.19.20)(esbuild@0.28.1)) '@vitest/expect@4.1.11': dependencies: @@ -2830,13 +2809,13 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.11(vite@8.0.16(@types/node@22.19.20)(esbuild@0.28.1))': + '@vitest/mocker@4.1.11(vite@8.3.6(@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.0.16(@types/node@22.19.20)(esbuild@0.28.1) + vite: 8.3.6(@types/node@22.19.20)(esbuild@0.28.1) '@vitest/pretty-format@4.1.11': dependencies: @@ -2906,9 +2885,9 @@ snapshots: asynckit@0.4.0: {} - axios@1.18.1: + axios@1.20.0: dependencies: - follow-redirects: 1.16.0 + follow-redirects: 1.16.2 form-data: 4.0.6 https-proxy-agent: 5.0.1 proxy-from-env: 2.1.0 @@ -3039,7 +3018,7 @@ snapshots: default-browser-id@5.0.1: {} - default-browser@5.5.0: + default-browser@5.5.1: dependencies: bundle-name: 4.1.0 default-browser-id: 5.0.1 @@ -3168,7 +3147,7 @@ snapshots: mlly: 1.8.2 rollup: 4.61.1 - follow-redirects@1.16.0: {} + follow-redirects@1.16.2: {} form-data-encoder@1.7.2: {} @@ -3316,6 +3295,8 @@ snapshots: is-docker@3.0.0: {} + is-in-ssh@1.0.0: {} + is-inside-container@1.0.0: dependencies: is-docker: 3.0.0 @@ -3423,54 +3404,54 @@ snapshots: openai: 4.104.0(ws@8.21.0)(zod@3.25.76) ws: 8.21.0 - lightningcss-android-arm64@1.32.0: + lightningcss-android-arm64@1.33.0: optional: true - lightningcss-darwin-arm64@1.32.0: + lightningcss-darwin-arm64@1.33.0: optional: true - lightningcss-darwin-x64@1.32.0: + lightningcss-darwin-x64@1.33.0: optional: true - lightningcss-freebsd-x64@1.32.0: + lightningcss-freebsd-x64@1.33.0: optional: true - lightningcss-linux-arm-gnueabihf@1.32.0: + lightningcss-linux-arm-gnueabihf@1.33.0: optional: true - lightningcss-linux-arm64-gnu@1.32.0: + lightningcss-linux-arm64-gnu@1.33.0: optional: true - lightningcss-linux-arm64-musl@1.32.0: + lightningcss-linux-arm64-musl@1.33.0: optional: true - lightningcss-linux-x64-gnu@1.32.0: + lightningcss-linux-x64-gnu@1.33.0: optional: true - lightningcss-linux-x64-musl@1.32.0: + lightningcss-linux-x64-musl@1.33.0: optional: true - lightningcss-win32-arm64-msvc@1.32.0: + lightningcss-win32-arm64-msvc@1.33.0: optional: true - lightningcss-win32-x64-msvc@1.32.0: + lightningcss-win32-x64-msvc@1.33.0: optional: true - lightningcss@1.32.0: + lightningcss@1.33.0: dependencies: detect-libc: 2.1.2 optionalDependencies: - 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 + 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 lilconfig@3.1.3: {} @@ -3502,7 +3483,7 @@ snapshots: dependencies: '@babel/parser': 7.29.7 '@babel/types': 7.29.7 - source-map-js: 1.2.1 + source-map-js: 1.2.2 make-dir@4.0.0: dependencies: @@ -3516,10 +3497,10 @@ snapshots: crypt: 0.0.2 is-buffer: 1.1.6 - 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): + 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): dependencies: '@anthropic-ai/sdk': 0.40.1 - '@azure/identity': 4.13.1 + '@azure/identity': 4.14.1 '@azure/search-documents': 12.2.0 '@cloudflare/workers-types': 4.20260610.1 '@google/genai': 1.52.0 @@ -3529,7 +3510,7 @@ snapshots: '@supabase/supabase-js': 2.108.1 '@types/jest': 29.5.14 '@types/pg': 8.11.0 - axios: 1.18.1 + axios: 1.20.0 better-sqlite3: 12.10.0 cloudflare: 4.5.0 compromise: 14.15.1 @@ -3618,7 +3599,7 @@ snapshots: object-assign: 4.1.1 thenify-all: 1.6.0 - nanoid@3.3.16: {} + nanoid@3.3.20: {} napi-build-utils@2.0.0: {} @@ -3680,12 +3661,14 @@ snapshots: dependencies: wrappy: 1.0.2 - open@10.2.0: + open@11.0.4: dependencies: - default-browser: 5.5.0 + default-browser: 5.5.1 define-lazy-prop: 3.0.0 + is-in-ssh: 1.0.0 is-inside-container: 1.0.0 - wsl-utils: 0.1.0 + powershell-utils: 0.2.1 + wsl-utils: 1.0.1 openai@4.104.0(ws@8.21.0)(zod@3.25.76): dependencies: @@ -3791,6 +3774,8 @@ snapshots: picomatch@4.0.4: {} + picomatch@4.0.7: {} + pirates@4.0.7: {} pkg-types@1.3.1: @@ -3799,17 +3784,17 @@ snapshots: mlly: 1.8.2 pathe: 2.0.3 - postcss-load-config@6.0.1(postcss@8.5.23): + postcss-load-config@6.0.1(postcss@8.5.32): dependencies: lilconfig: 3.1.3 optionalDependencies: - postcss: 8.5.23 + postcss: 8.5.32 - postcss@8.5.23: + postcss@8.5.32: dependencies: - nanoid: 3.3.16 + nanoid: 3.3.20 picocolors: 1.1.1 - source-map-js: 1.2.1 + source-map-js: 1.2.2 postgres-array@2.0.0: {} @@ -3833,6 +3818,8 @@ snapshots: postgres-range@1.1.4: {} + powershell-utils@0.2.1: {} + prebuild-install@7.1.3: dependencies: detect-libc: 2.1.2 @@ -3909,26 +3896,26 @@ snapshots: retry@0.13.1: {} - rolldown@1.0.3: + rolldown@1.2.16: dependencies: - '@oxc-project/types': 0.133.0 + '@oxc-project/types': 0.156.0 '@rolldown/pluginutils': 1.0.1 optionalDependencies: - '@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 + '@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 rollup@4.61.1: dependencies: @@ -3983,7 +3970,7 @@ snapshots: slash@3.0.0: {} - source-map-js@1.2.1: {} + source-map-js@1.2.2: {} source-map@0.7.6: {} @@ -4079,7 +4066,7 @@ snapshots: tslib@2.8.1: {} - tsup@8.5.1(postcss@8.5.23)(typescript@5.9.3): + tsup@8.5.1(postcss@8.5.32)(typescript@5.9.3): dependencies: bundle-require: 5.1.0(esbuild@0.28.1) cac: 6.7.14 @@ -4090,7 +4077,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.23) + postcss-load-config: 6.0.1(postcss@8.5.32) resolve-from: 5.0.0 rollup: 4.61.1 source-map: 0.7.6 @@ -4099,7 +4086,7 @@ snapshots: tinyglobby: 0.2.17 tree-kill: 1.2.2 optionalDependencies: - postcss: 8.5.23 + postcss: 8.5.32 typescript: 5.9.3 transitivePeerDependencies: - jiti @@ -4121,7 +4108,7 @@ snapshots: undici-types@6.21.0: {} - undici@7.29.0: {} + undici@7.30.2: {} util-deprecate@1.0.2: {} @@ -4129,22 +4116,22 @@ snapshots: uuid@14.0.0: {} - vite@8.0.16(@types/node@22.19.20)(esbuild@0.28.1): + vite@8.3.6(@types/node@22.19.20)(esbuild@0.28.1): dependencies: - lightningcss: 1.32.0 - picomatch: 4.0.4 - postcss: 8.5.23 - rolldown: 1.0.3 + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.32 + rolldown: 1.2.16 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.0.16(@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.3.6(@types/node@22.19.20)(esbuild@0.28.1)): dependencies: '@vitest/expect': 4.1.11 - '@vitest/mocker': 4.1.11(vite@8.0.16(@types/node@22.19.20)(esbuild@0.28.1)) + '@vitest/mocker': 4.1.11(vite@8.3.6(@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 @@ -4161,7 +4148,7 @@ snapshots: tinyexec: 1.2.4 tinyglobby: 0.2.17 tinyrainbow: 3.1.0 - vite: 8.0.16(@types/node@22.19.20)(esbuild@0.28.1) + vite: 8.3.6(@types/node@22.19.20)(esbuild@0.28.1) why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 22.19.20 @@ -4200,9 +4187,10 @@ snapshots: ws@8.21.0: {} - wsl-utils@0.1.0: + wsl-utils@1.0.1: 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 0f9f833bc..5d33b5e7b 100644 --- a/integrations/openclaw/pnpm-workspace.yaml +++ b/integrations/openclaw/pnpm-workspace.yaml @@ -13,15 +13,18 @@ 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.0.5" + "vite": "^8.1.6" "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.29.0": ">=7.29.0 <8.0.0" - "axios@<1.18.0": ">=1.18.0 <2.0.0" + "undici@<7.30.1": ">=7.30.1 <8.0.0" + "axios@<1.20.0": ">=1.20.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 fc1c6b99d..bd77e1656 100644 --- a/integrations/openclaw/telemetry.ts +++ b/integrations/openclaw/telemetry.ts @@ -1,14 +1,20 @@ import { createHash, randomUUID } from "node:crypto"; import { createTelemetry } from "../agent-plugin-core/typescript/src/telemetry.ts"; -import { clearAnonymousTelemetryId, getBaseUrl, readPluginAuth, writePluginAuth } from "./cli/config-file.ts"; +import { + clearAnonymousTelemetryId, + clearResolvedAccount, + 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 emailResolutionAttempted = false; +let resolutionAttemptedFor = ""; let currentDistinctId = ""; function enabled(): boolean { @@ -33,10 +39,35 @@ 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 email = readPluginAuth().userEmail; - if (email) return createHash("sha256").update(email).digest("hex"); + 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(); + } } catch { // Fall through to the API key or anonymous identity. } @@ -66,8 +97,16 @@ function identifyAnonymous(id: string): void { } function resolveEmail(apiKey: string): void { - if (emailResolutionAttempted) return; - emailResolutionAttempted = true; + // 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 = ""; + }; fetch(`${getBaseUrl().replace(/\/+$/, "")}/v1/ping/`, { method: "GET", headers: { Authorization: `Token ${apiKey}`, "Content-Type": "application/json" }, @@ -76,7 +115,7 @@ function resolveEmail(apiKey: string): void { .then((response) => response.json()) .then((data: any) => { if (!data?.user_email) return; - writePluginAuth({ userEmail: data.user_email }); + writePluginAuth({ userEmail: data.user_email, keyFingerprint: fingerprint }); const oldId = createHash("sha256").update(apiKey).digest("hex"); const newId = createHash("sha256").update(data.user_email).digest("hex"); for (const event of telemetry.queueForTesting()) { @@ -84,7 +123,8 @@ function resolveEmail(apiKey: string): void { } }) .catch(() => { - // The API-key hash remains a stable fallback. + // The API-key hash remains a stable fallback, and the next capture retries. + releaseLatch(); }); } @@ -96,13 +136,15 @@ export function captureEvent( if (!enabled()) return; try { currentDistinctId = distinctId(context?.apiKey); - let hasEmail = false; + let resolvedForThisKey = false; try { - hasEmail = Boolean(readPluginAuth().userEmail); + const auth = readPluginAuth(); + resolvedForThisKey = + Boolean(auth.userEmail) && auth.keyFingerprint === keyFingerprint(context?.apiKey); } catch { // Resolve it below when possible. } - if (context?.apiKey && !hasEmail) resolveEmail(context.apiKey); + if (context?.apiKey && !resolvedForThisKey) 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 e059ddff3..ba63180cb 100644 --- a/integrations/openclaw/tests/config-file.test.ts +++ b/integrations/openclaw/tests/config-file.test.ts @@ -237,3 +237,43 @@ 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 2c6dbac2e..334c064fb 100644 --- a/integrations/openclaw/tests/config.test.ts +++ b/integrations/openclaw/tests/config.test.ts @@ -485,3 +485,18 @@ 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 9a7bee716..ad7a9bbe0 100644 --- a/integrations/openclaw/tests/telemetry.test.ts +++ b/integrations/openclaw/tests/telemetry.test.ts @@ -3,15 +3,30 @@ 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 { readPluginAuth } from "../cli/config-file.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); +} 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 }); @@ -40,11 +55,31 @@ describe("telemetry", () => { expect(() => captureEvent("test_event")).not.toThrow(); }); - it("uses userEmail as distinct ID when available", () => { - (readPluginAuth as ReturnType).mockReturnValueOnce({ + 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({ userEmail: "test@example.com", + keyFingerprint: await fingerprintOf("key-a"), }); - expect(() => captureEvent("test_event")).not.toThrow(); + + 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(); }); it("falls back to a generated anonymous id when no apiKey", () => { @@ -52,6 +87,43 @@ 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 58ce8183a..51d2ebcfd 100644 --- a/integrations/openclaw/tools/memory-search.ts +++ b/integrations/openclaw/tools/memory-search.ts @@ -1,4 +1,5 @@ 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"; @@ -8,9 +9,9 @@ export function createMemorySearchTool(deps: ToolDeps) { return { name: "memory_search", label: "Memory Search", - 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).", + description: USER_SEARCH_TOOL_DESCRIPTION, parameters: Type.Object({ - query: Type.String({ description: "Search query" }), + query: Type.String({ description: USER_SEARCH_QUERY_DESCRIPTION }), 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 8dcf6d535..a86eab3af 100644 --- a/integrations/opencode-plugin/opencode-mem0.ts +++ b/integrations/opencode-plugin/opencode-mem0.ts @@ -18,6 +18,7 @@ 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; @@ -424,9 +425,9 @@ Identity context (resolved at plugin startup): }), search_memories: tool({ - 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).", + description: SEARCH_TOOL_DESCRIPTION, args: { - query: tool.schema.string().describe("Search query"), + query: tool.schema.string().describe(SEARCH_QUERY_DESCRIPTION), 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"), @@ -636,9 +637,6 @@ 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", @@ -659,9 +657,6 @@ Identity context (resolved at plugin startup): } } - systemContext.push( - "Mem0 searches apply when user references past work, decision questions, errors, or non-trivial tasks. Queries use noun-phrases, 2-4 parallel calls with different metadata.type filters, and include user_id + app_id.", - ); systemContext.push(SCOPE_GUIDANCE); const activeScope = loadDefaultScope(); if (activeScope !== "project") { 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 803689076..b22f647dc 100644 --- a/integrations/opencode-plugin/opencode-skills/mem0-context-loader/SKILL.md +++ b/integrations/opencode-plugin/opencode-skills/mem0-context-loader/SKILL.md @@ -1,35 +1,19 @@ --- name: mem0-context-loader -description: Searches and injects relevant memories into context before starting work on a task. Use when beginning a new task, switching context, or when project history, past decisions, or coding conventions need to be loaded. +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. --- # 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. **Run 2-4 parallel `search_memories` calls** with different angles: +2. **Call `search_memories` once** with a focused question about the task: `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=10`. - | 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): +3. **Output compact context block** (max 10 memories): ``` context-loader: loaded memories for "" @@ -38,7 +22,7 @@ context-loader: loaded memories for "" - [anti_pattern] [mem0:] ``` -5. If **zero results**: output nothing. Don't announce empty context. +4. 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 ed3533991..e6b570d12 100644 --- a/integrations/opencode-plugin/opencode-skills/mem0-search/SKILL.md +++ b/integrations/opencode-plugin/opencode-skills/mem0-search/SKILL.md @@ -27,14 +27,11 @@ When an ID is detected: ### Step 2: Search -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` +Call `search_memories` once with the user's question: `query=`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=10`. ### Step 3: Display -Deduplicate by ID, then show compact results: +Show compact results: ``` ## mem0 search: "" ( results) diff --git a/integrations/opencode-plugin/package.json b/integrations/opencode-plugin/package.json index 79f68c4a8..36c3dce6b 100644 --- a/integrations/opencode-plugin/package.json +++ b/integrations/opencode-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@mem0/opencode-plugin", - "version": "0.3.0", + "version": "0.4.1", "type": "module", "description": "Mem0 persistent memory plugin for OpenCode โ€” add, search, and manage memories across sessions", "main": "dist/index.js", @@ -38,6 +38,7 @@ "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 393150977..79dc3ffdb 100644 --- a/integrations/opencode-plugin/telemetry.test.ts +++ b/integrations/opencode-plugin/telemetry.test.ts @@ -1,3 +1,5 @@ +import { createHash } from "node:crypto"; + import { afterEach, describe, expect, test } from "bun:test"; import { buildEvent, captureEvent, isTelemetryEnabled } from "./telemetry"; @@ -13,7 +15,10 @@ describe("opencode telemetry", () => { expect(payload).not.toBeNull(); const props = payload!.properties as Record; expect(payload!.event).toBe("plugin.session_start"); - expect(props.source).toBe("plugin"); + // 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.platform).toBe("opencode"); expect(props.memory_count).toBe(5); expect(props.$process_person_profile).toBe(false); @@ -30,7 +35,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("plugin"); + expect(props.source).toBe("OPENCODE_PLUGIN"); }); test("returns null without an API key (no anonymous events)", () => { @@ -56,9 +61,12 @@ describe("opencode telemetry", () => { expect(typeof props.os_version).toBe("string"); }); - test("project_hash is sha256(projectId) when a project id is supplied", async () => { + 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. const { createHash } = await import("node:crypto"); - const expected = createHash("sha256").update("acme-repo").digest("hex"); + const expected = createHash("sha256").update(`${KEY}:acme-repo`).digest("hex"); const props = buildEvent("session_start", {}, KEY, "acme-repo")! .properties as Record; expect(props.project_hash).toBe(expected); @@ -76,3 +84,38 @@ 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 8d0861d97..e2316dd88 100644 --- a/integrations/opencode-plugin/telemetry.ts +++ b/integrations/opencode-plugin/telemetry.ts @@ -25,7 +25,9 @@ const PLUGIN_VERSION = (() => { let currentDistinctId = ""; const telemetry = createTelemetry({ host: "opencode", - source: "plugin", + // 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", version: PLUGIN_VERSION, distinctId: () => currentDistinctId, eventName: (event) => `plugin.${event}`, @@ -40,8 +42,23 @@ function distinctId(apiKey: string): string { return createHash("sha256").update(apiKey).digest("hex").slice(0, 32); } -function projectHash(projectId?: string): Record { - return projectId ? { project_hash: createHash("sha256").update(projectId).digest("hex") } : {}; +/** + * 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") }; } export function buildEvent( @@ -51,7 +68,7 @@ export function buildEvent( projectId?: string, ): Record | null { currentDistinctId = apiKey ? distinctId(apiKey) : ""; - const event = telemetry.build(eventType, { ...properties, ...projectHash(projectId) }); + const event = telemetry.build(eventType, { ...properties, ...projectHash(projectId, apiKey) }); return event ? { api_key: POSTHOG_API_KEY, ...event } : null; } @@ -62,5 +79,5 @@ export function captureEvent( projectId?: string, ): void { currentDistinctId = apiKey ? distinctId(apiKey) : ""; - telemetry.capture(eventType, { ...properties, ...projectHash(projectId) }); + telemetry.capture(eventType, { ...properties, ...projectHash(projectId, apiKey) }); } diff --git a/integrations/pi-agent-plugin/README.md b/integrations/pi-agent-plugin/README.md index cb28d2314..3dc5b351b 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` | Pre-fetch relevant memories at session start | +| `context-loader` | Search memories when earlier work may already explain the task | | `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 d05673406..ed7b70b6c 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.0", + "version": "0.3.2", "type": "module", "description": "Mem0 memory extension for Pi Agent persistent, scoped, semantic memory across sessions and projects", "license": "Apache-2.0", @@ -69,16 +69,19 @@ }, "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.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", + "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", "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" + "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/pnpm-lock.yaml b/integrations/pi-agent-plugin/pnpm-lock.yaml index 177023505..dfb76912f 100644 --- a/integrations/pi-agent-plugin/pnpm-lock.yaml +++ b/integrations/pi-agent-plugin/pnpm-lock.yaml @@ -5,16 +5,19 @@ 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.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' + 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' 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: @@ -22,7 +25,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.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) + 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) devDependencies: '@earendil-works/pi-ai': specifier: ^0.79.0 @@ -35,7 +38,7 @@ importers: version: 25.9.2 tsup: specifier: ^8.5.0 - version: 8.5.1(jiti@2.7.0)(postcss@8.5.23)(typescript@6.0.3)(yaml@2.9.0) + version: 8.5.1(jiti@2.7.0)(postcss@8.5.32)(typescript@6.0.3)(yaml@2.9.0) typebox: specifier: ^1.2.3 version: 1.2.8 @@ -44,7 +47,7 @@ importers: version: 6.0.3 vitest: specifier: ^4.1.11 - 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)) + 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)) packages: @@ -181,6 +184,10 @@ 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'} @@ -193,9 +200,9 @@ packages: resolution: {integrity: sha512-XPArKLzsvl0Hf0CaGyKHUyVgF7oDnhKoP85Xv6M4StF/1AhfORhZudHtOyf2s+FcbuQ9dPRAjB8J2KvRRMUK2A==} engines: {node: '>=20.0.0'} - '@azure/identity@4.13.1': - resolution: {integrity: sha512-5C/2WD5Vb1lHnZS16dNQRPMjN6oV/Upba+C9nBIs15PmOi6A3ZGs4Lr2u60zw4S04gi+u3cEXiqTVP7M4Pz3kw==} - engines: {node: '>=20.0.0'} + '@azure/identity@4.14.1': + resolution: {integrity: sha512-HHuuFrmN1uuF9D5A6aAo5eHzNFNX4Q+P4SksZqDKse5YaJFFy/zDLG3wXHEV2FVGgetZ3QM8jGURNBtnQYf1NQ==} + engines: {node: '>=22.0.0'} '@azure/logger@1.3.0': resolution: {integrity: sha512-fCqPIfOcLE+CGqGPd66c8bZpwAji98tZ4JI9i/mlTNTlsIWslCfpg48s/ypyLxZTump5sypjrKn2/kY7q8oAbA==} @@ -205,12 +212,16 @@ 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@5.2.3': - resolution: {integrity: sha512-YYX4TchEVddVBiybKvKhV9QO/q22jgewP+BVxKG7Uh115voPcviGlypbKERDsqQdAiSTJrwi80gcWFjYKdo8+Q==} + '@azure/msal-node@7.2.0': + resolution: {integrity: sha512-Y87VJsMWF4jiqLqq8XYLb1o+rGc/HacwS3Zydi3bDtaVm5Sa8FlB7YrKrBFKRIYj27RJXAaDkErImMAqtM10Pg==} engines: {node: '>=20'} '@azure/search-documents@12.2.0': @@ -253,15 +264,6 @@ 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'} @@ -530,17 +532,11 @@ 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.133.0': - resolution: {integrity: sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==} + '@oxc-project/types@0.156.0': + resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} '@protobufjs/aspromise@1.1.2': resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==} @@ -615,97 +611,98 @@ packages: peerDependencies: '@redis/client': ^5.12.1 - '@rolldown/binding-android-arm64@1.0.3': - resolution: {integrity: sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==} + '@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==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [android] - '@rolldown/binding-darwin-arm64@1.0.3': - resolution: {integrity: sha512-PcAhP+ynjURNyy8SKGl5DQP94aGuB/7JrXJb/t7P+hanXvQVMWzUvRRhBAcg/lNRadBhoUPqSoP4xw5tR/KBEA==} + '@rolldown/binding-darwin-arm64@1.2.16': + resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@rolldown/binding-darwin-x64@1.0.3': - resolution: {integrity: sha512-9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg==} + '@rolldown/binding-darwin-x64@1.2.16': + resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@rolldown/binding-freebsd-x64@1.0.3': - resolution: {integrity: sha512-yB1IlAsSNHncV6SCTL27/MVGR5htvQsoGxIv5KMGXALp+Ll1wYsn+x98M9MW7qa+NdSbvrrY7ANI4wLJ0n1e6g==} + '@rolldown/binding-freebsd-x64@1.2.16': + resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [freebsd] - '@rolldown/binding-linux-arm-gnueabihf@1.0.3': - resolution: {integrity: sha512-Yi30IVAAfLUCy2MseFjbB1jAMDl1VMCAas5StnYp8da9+CKvMd2H2cbEjWcw5NPaPqzvYkVIaF1nNUG+b7u/sw==} + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - '@rolldown/binding-linux-arm64-gnu@1.0.3': - resolution: {integrity: sha512-jsO7R8To+AdlYgUmN5sHSCZbfhtMBkO0WUx8iORQnPcMMdgr7qM2DQmMwgabs3GhNztdmoKkMKQFHD6DTMCIQw==} + '@rolldown/binding-linux-arm64-gnu@1.2.16': + resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-arm64-musl@1.0.3': - resolution: {integrity: sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==} + '@rolldown/binding-linux-arm64-musl@1.2.16': + resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [linux] libc: [musl] - '@rolldown/binding-linux-ppc64-gnu@1.0.3': - resolution: {integrity: sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==} + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-s390x-gnu@1.0.3': - resolution: {integrity: sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==} + '@rolldown/binding-linux-s390x-gnu@1.2.16': + resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] libc: [glibc] - '@rolldown/binding-linux-x64-gnu@1.0.3': - resolution: {integrity: sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==} + '@rolldown/binding-linux-x64-gnu@1.2.16': + resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [glibc] - '@rolldown/binding-linux-x64-musl@1.0.3': - resolution: {integrity: sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==} + '@rolldown/binding-linux-x64-musl@1.2.16': + resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [musl] - '@rolldown/binding-openharmony-arm64@1.0.3': - resolution: {integrity: sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==} + '@rolldown/binding-openharmony-arm64@1.2.16': + resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [openharmony] - '@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==} + '@rolldown/binding-win32-arm64-msvc@1.2.16': + resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [win32] - '@rolldown/binding-win32-x64-msvc@1.0.3': - resolution: {integrity: sha512-eXB7CHuaQdqmJcc3koCNtNPmT/bj2gc999kUFgBxG8Ac0NdgXc4rkCHhqrgrhN3zddvvvrgzj1e90SuSfmyIXA==} + '@rolldown/binding-win32-x64-msvc@1.2.16': + resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==} engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [win32] @@ -927,9 +924,6 @@ 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==} @@ -992,7 +986,7 @@ packages: resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==} peerDependencies: msw: ^2.4.9 - vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + vite: ^8.1.6 peerDependenciesMeta: msw: optional: true @@ -1066,8 +1060,8 @@ packages: asynckit@0.4.0: resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} - axios@1.18.1: - resolution: {integrity: sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==} + axios@1.20.0: + resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==} balanced-match@4.0.4: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} @@ -1229,8 +1223,8 @@ packages: resolution: {integrity: sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==} engines: {node: '>=18'} - default-browser@5.5.0: - resolution: {integrity: sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw==} + default-browser@5.5.1: + resolution: {integrity: sha512-m1pAzaJgZ/gssEqlOhJkPJp8Xly7QyW6xcrkUa2KKcDeDSEMP7X8xipU3snUcfisTQx0w1AGae+9UtJSfVnXGw==} engines: {node: '>=18'} define-lazy-prop@3.0.0: @@ -1361,8 +1355,8 @@ packages: fix-dts-default-cjs-exports@1.0.1: resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==} - follow-redirects@1.16.0: - resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==} + follow-redirects@1.16.2: + resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==} engines: {node: '>=4.0'} peerDependencies: debug: '*' @@ -1508,6 +1502,10 @@ 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'} @@ -1599,78 +1597,78 @@ packages: ws: optional: true - lightningcss-android-arm64@1.32.0: - resolution: {integrity: sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==} + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [android] - lightningcss-darwin-arm64@1.32.0: - resolution: {integrity: sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==} + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [darwin] - lightningcss-darwin-x64@1.32.0: - resolution: {integrity: sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==} + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [darwin] - lightningcss-freebsd-x64@1.32.0: - resolution: {integrity: sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==} + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [freebsd] - lightningcss-linux-arm-gnueabihf@1.32.0: - resolution: {integrity: sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==} + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} engines: {node: '>= 12.0.0'} cpu: [arm] os: [linux] - lightningcss-linux-arm64-gnu@1.32.0: - resolution: {integrity: sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==} + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] libc: [glibc] - lightningcss-linux-arm64-musl@1.32.0: - resolution: {integrity: sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==} + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] libc: [musl] - lightningcss-linux-x64-gnu@1.32.0: - resolution: {integrity: sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==} + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] libc: [glibc] - lightningcss-linux-x64-musl@1.32.0: - resolution: {integrity: sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==} + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] libc: [musl] - lightningcss-win32-arm64-msvc@1.32.0: - resolution: {integrity: sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==} + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [win32] - lightningcss-win32-x64-msvc@1.32.0: - resolution: {integrity: sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==} + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [win32] - lightningcss@1.32.0: - resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==} + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} engines: {node: '>= 12.0.0'} lilconfig@3.1.3: @@ -1732,7 +1730,7 @@ packages: engines: {node: '>=18'} peerDependencies: '@anthropic-ai/sdk': ^0.40.1 - '@azure/identity': ^4.0.0 + '@azure/identity': '>=4.14.1 <5.0.0' '@azure/search-documents': ^12.0.0 '@cloudflare/workers-types': ^4.20250504.0 '@google/genai': ^1.40.0 @@ -1844,8 +1842,8 @@ packages: mz@2.7.0: resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==} - nanoid@3.3.16: - resolution: {integrity: sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q==} + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true @@ -1895,9 +1893,9 @@ packages: once@1.4.0: resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} - open@10.2.0: - resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==} - engines: {node: '>=18'} + open@11.0.4: + resolution: {integrity: sha512-++Zlftm0kVLPmzC06t6epuWmcRMDbI4z5P3NNX979WA/k23+NtSOynEGzsVfZwguKw2mi5umVgnBlJQMwRz4Pg==} + engines: {node: '>=20'} openai@4.104.0: resolution: {integrity: sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==} @@ -2022,6 +2020,10 @@ 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'} @@ -2047,8 +2049,8 @@ packages: yaml: optional: true - postcss@8.5.23: - resolution: {integrity: sha512-g50586zr4bZmwFiTlflMu8E0bDTb5I5gertgwAKmsdUlTQIhZtunzUlD1WSzwcVWPoAVpsrA6vlfCD7oXvRwgg==} + postcss@8.5.32: + resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} engines: {node: ^10 || ^12 || >=14} postgres-array@2.0.0: @@ -2086,6 +2088,10 @@ 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'} @@ -2145,8 +2151,8 @@ packages: resolution: {integrity: sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==} engines: {node: '>= 4'} - rolldown@1.0.3: - resolution: {integrity: sha512-i00lAJ2ks1BYr7rjNjKC7BcqAS7nVfiT3QX1SI5aY+AFHblCmaUf9OE9dbdzDvW6dJxbi2ZCZiy9v3CcwOiX3g==} + rolldown@1.2.16: + resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true @@ -2198,8 +2204,8 @@ packages: resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==} engines: {node: '>=8'} - source-map-js@1.2.1: - resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} engines: {node: '>=0.10.0'} source-map@0.7.6: @@ -2354,12 +2360,12 @@ packages: undici-types@7.24.6: resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} - undici@7.29.0: - resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==} + undici@7.30.2: + resolution: {integrity: sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==} engines: {node: '>=20.18.1'} - undici@8.10.0: - resolution: {integrity: sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ==} + undici@8.12.4: + resolution: {integrity: sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==} engines: {node: '>=22.19.0'} util-deprecate@1.0.2: @@ -2373,13 +2379,13 @@ packages: resolution: {integrity: sha512-Qo+uWgilfSmAhXCMav1uYFynlQO7fMFiMVZsQqZRMIXp0O7rR7qjkj+cPvBHLgBqi960QCoo/PH2/6ZtVqKvrg==} hasBin: true - vite@8.0.16: - resolution: {integrity: sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==} + vite@8.3.6: + resolution: {integrity: sha512-UI7dK29NnS54Fk+mmo7o+jI6U8Fp7hDl+X5Q1k45WH+d4dSlbLVUETGQ+hfkNgvLQGyoElPj837nZyv4MBc0VA==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true peerDependencies: '@types/node': ^20.19.0 || >=22.12.0 - '@vitejs/devtools': ^0.1.18 + '@vitejs/devtools': ^0.7.1 || ^0.8.0 esbuild: '>=0.28.1' jiti: '>=1.21.0' less: ^4.0.0 @@ -2432,7 +2438,7 @@ packages: '@vitest/ui': 4.1.11 happy-dom: '*' jsdom: '*' - vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + vite: ^8.1.6 peerDependenciesMeta: '@edge-runtime/vm': optional: true @@ -2511,9 +2517,9 @@ packages: utf-8-validate: optional: true - wsl-utils@0.1.0: - resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==} - engines: {node: '>=18'} + wsl-utils@1.0.1: + resolution: {integrity: sha512-c16PKLIRxBYpR3jSWsdS7SFp0COm5SOQdiFjY818dYFHJbMGuLBszpF07LBWmOS1uzrHa9VGdynsEgoeKy0oOQ==} + engines: {node: '>=20'} xml-naming@0.1.0: resolution: {integrity: sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==} @@ -2804,6 +2810,8 @@ 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 @@ -2828,18 +2836,19 @@ snapshots: transitivePeerDependencies: - supports-color - '@azure/identity@4.13.1': + '@azure/identity@4.14.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': 5.2.3 - open: 10.2.0 + '@azure/msal-node': 7.2.0 + open: 11.0.4 tslib: 2.8.1 transitivePeerDependencies: - supports-color @@ -2855,11 +2864,13 @@ snapshots: dependencies: '@azure/msal-common': 16.7.0 + '@azure/msal-common@16.16.0': {} + '@azure/msal-common@16.7.0': {} - '@azure/msal-node@5.2.3': + '@azure/msal-node@7.2.0': dependencies: - '@azure/msal-common': 16.7.0 + '@azure/msal-common': 16.16.0 jsonwebtoken: 9.0.3 '@azure/search-documents@12.2.0': @@ -2942,7 +2953,7 @@ snapshots: minimatch: 10.2.5 proper-lockfile: 4.1.2 typebox: 1.1.38 - undici: 8.10.0 + undici: 8.12.4 yaml: 2.9.0 optionalDependencies: '@mariozechner/clipboard': 0.3.9 @@ -2959,22 +2970,6 @@ 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 @@ -3168,16 +3163,9 @@ 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.133.0': {} + '@oxc-project/types@0.156.0': {} '@protobufjs/aspromise@1.1.2': {} @@ -3203,7 +3191,7 @@ snapshots: dependencies: '@qdrant/openapi-typescript-fetch': 1.2.6 typescript: 6.0.3 - undici: 7.29.0 + undici: 7.30.2 '@qdrant/openapi-typescript-fetch@1.2.6': {} @@ -3227,53 +3215,49 @@ snapshots: dependencies: '@redis/client': 5.12.1 - '@rolldown/binding-android-arm64@1.0.3': + '@rolldown/binding-android-arm-eabi@1.2.16': optional: true - '@rolldown/binding-darwin-arm64@1.0.3': + '@rolldown/binding-android-arm64@1.2.16': optional: true - '@rolldown/binding-darwin-x64@1.0.3': + '@rolldown/binding-darwin-arm64@1.2.16': optional: true - '@rolldown/binding-freebsd-x64@1.0.3': + '@rolldown/binding-darwin-x64@1.2.16': optional: true - '@rolldown/binding-linux-arm-gnueabihf@1.0.3': + '@rolldown/binding-freebsd-x64@1.2.16': optional: true - '@rolldown/binding-linux-arm64-gnu@1.0.3': + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': optional: true - '@rolldown/binding-linux-arm64-musl@1.0.3': + '@rolldown/binding-linux-arm64-gnu@1.2.16': optional: true - '@rolldown/binding-linux-ppc64-gnu@1.0.3': + '@rolldown/binding-linux-arm64-musl@1.2.16': optional: true - '@rolldown/binding-linux-s390x-gnu@1.0.3': + '@rolldown/binding-linux-ppc64-gnu@1.2.16': optional: true - '@rolldown/binding-linux-x64-gnu@1.0.3': + '@rolldown/binding-linux-s390x-gnu@1.2.16': optional: true - '@rolldown/binding-linux-x64-musl@1.0.3': + '@rolldown/binding-linux-x64-gnu@1.2.16': optional: true - '@rolldown/binding-openharmony-arm64@1.0.3': + '@rolldown/binding-linux-x64-musl@1.2.16': optional: true - '@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) + '@rolldown/binding-openharmony-arm64@1.2.16': optional: true - '@rolldown/binding-win32-arm64-msvc@1.0.3': + '@rolldown/binding-win32-arm64-msvc@1.2.16': optional: true - '@rolldown/binding-win32-x64-msvc@1.0.3': + '@rolldown/binding-win32-x64-msvc@1.2.16': optional: true '@rolldown/pluginutils@1.0.1': {} @@ -3445,11 +3429,6 @@ 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 @@ -3526,13 +3505,13 @@ snapshots: chai: 6.2.2 tinyrainbow: 3.1.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/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))': dependencies: '@vitest/spy': 4.1.11 estree-walker: 3.0.3 magic-string: 0.30.21 optionalDependencies: - vite: 8.0.16(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0) + vite: 8.3.6(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0) '@vitest/pretty-format@4.1.11': dependencies: @@ -3598,9 +3577,9 @@ snapshots: asynckit@0.4.0: {} - axios@1.18.1: + axios@1.20.0: dependencies: - follow-redirects: 1.16.0 + follow-redirects: 1.16.2 form-data: 4.0.6 https-proxy-agent: 5.0.1 proxy-from-env: 2.1.0 @@ -3747,7 +3726,7 @@ snapshots: default-browser-id@5.0.1: {} - default-browser@5.5.0: + default-browser@5.5.1: dependencies: bundle-name: 4.1.0 default-browser-id: 5.0.1 @@ -3890,7 +3869,7 @@ snapshots: mlly: 1.8.2 rollup: 4.61.1 - follow-redirects@1.16.0: {} + follow-redirects@1.16.2: {} form-data-encoder@1.7.2: {} @@ -4052,6 +4031,8 @@ snapshots: is-docker@3.0.0: {} + is-in-ssh@1.0.0: {} + is-inside-container@1.0.0: dependencies: is-docker: 3.0.0 @@ -4153,54 +4134,54 @@ snapshots: openai: 6.26.0(ws@8.21.0)(zod@3.25.76) ws: 8.21.0 - lightningcss-android-arm64@1.32.0: + lightningcss-android-arm64@1.33.0: optional: true - lightningcss-darwin-arm64@1.32.0: + lightningcss-darwin-arm64@1.33.0: optional: true - lightningcss-darwin-x64@1.32.0: + lightningcss-darwin-x64@1.33.0: optional: true - lightningcss-freebsd-x64@1.32.0: + lightningcss-freebsd-x64@1.33.0: optional: true - lightningcss-linux-arm-gnueabihf@1.32.0: + lightningcss-linux-arm-gnueabihf@1.33.0: optional: true - lightningcss-linux-arm64-gnu@1.32.0: + lightningcss-linux-arm64-gnu@1.33.0: optional: true - lightningcss-linux-arm64-musl@1.32.0: + lightningcss-linux-arm64-musl@1.33.0: optional: true - lightningcss-linux-x64-gnu@1.32.0: + lightningcss-linux-x64-gnu@1.33.0: optional: true - lightningcss-linux-x64-musl@1.32.0: + lightningcss-linux-x64-musl@1.33.0: optional: true - lightningcss-win32-arm64-msvc@1.32.0: + lightningcss-win32-arm64-msvc@1.33.0: optional: true - lightningcss-win32-x64-msvc@1.32.0: + lightningcss-win32-x64-msvc@1.33.0: optional: true - lightningcss@1.32.0: + lightningcss@1.33.0: dependencies: detect-libc: 2.1.2 optionalDependencies: - 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 + 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 lilconfig@3.1.3: {} @@ -4240,10 +4221,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.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): + 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): dependencies: '@anthropic-ai/sdk': 0.91.1(zod@3.25.76) - '@azure/identity': 4.13.1 + '@azure/identity': 4.14.1 '@azure/search-documents': 12.2.0 '@cloudflare/workers-types': 4.20260610.1 '@google/genai': 1.52.0 @@ -4253,7 +4234,7 @@ snapshots: '@supabase/supabase-js': 2.108.1 '@types/jest': 29.5.14 '@types/pg': 8.11.0 - axios: 1.18.1 + axios: 1.20.0 better-sqlite3: 12.10.0 cloudflare: 4.5.0 compromise: 14.15.1 @@ -4348,7 +4329,7 @@ snapshots: object-assign: 4.1.1 thenify-all: 1.6.0 - nanoid@3.3.16: {} + nanoid@3.3.20: {} napi-build-utils@2.0.0: {} @@ -4410,12 +4391,14 @@ snapshots: dependencies: wrappy: 1.0.2 - open@10.2.0: + open@11.0.4: dependencies: - default-browser: 5.5.0 + default-browser: 5.5.1 define-lazy-prop: 3.0.0 + is-in-ssh: 1.0.0 is-inside-container: 1.0.0 - wsl-utils: 0.1.0 + powershell-utils: 0.2.1 + wsl-utils: 1.0.1 openai@4.104.0(ws@8.21.0)(zod@3.25.76): dependencies: @@ -4537,6 +4520,8 @@ snapshots: picomatch@4.0.4: {} + picomatch@4.0.7: {} + pirates@4.0.7: {} pkg-types@1.3.1: @@ -4545,19 +4530,19 @@ snapshots: mlly: 1.8.2 pathe: 2.0.3 - postcss-load-config@6.0.1(jiti@2.7.0)(postcss@8.5.23)(yaml@2.9.0): + postcss-load-config@6.0.1(jiti@2.7.0)(postcss@8.5.32)(yaml@2.9.0): dependencies: lilconfig: 3.1.3 optionalDependencies: jiti: 2.7.0 - postcss: 8.5.23 + postcss: 8.5.32 yaml: 2.9.0 - postcss@8.5.23: + postcss@8.5.32: dependencies: - nanoid: 3.3.16 + nanoid: 3.3.20 picocolors: 1.1.1 - source-map-js: 1.2.1 + source-map-js: 1.2.2 postgres-array@2.0.0: {} @@ -4581,6 +4566,8 @@ snapshots: postgres-range@1.1.4: {} + powershell-utils@0.2.1: {} + prebuild-install@7.1.3: dependencies: detect-libc: 2.1.2 @@ -4665,26 +4652,26 @@ snapshots: retry@0.13.1: {} - rolldown@1.0.3: + rolldown@1.2.16: dependencies: - '@oxc-project/types': 0.133.0 + '@oxc-project/types': 0.156.0 '@rolldown/pluginutils': 1.0.1 optionalDependencies: - '@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 + '@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 rollup@4.61.1: dependencies: @@ -4747,7 +4734,7 @@ snapshots: slash@3.0.0: {} - source-map-js@1.2.1: {} + source-map-js@1.2.2: {} source-map@0.7.6: {} @@ -4849,7 +4836,7 @@ snapshots: tslib@2.8.1: {} - tsup@8.5.1(jiti@2.7.0)(postcss@8.5.23)(typescript@6.0.3)(yaml@2.9.0): + tsup@8.5.1(jiti@2.7.0)(postcss@8.5.32)(typescript@6.0.3)(yaml@2.9.0): dependencies: bundle-require: 5.1.0(esbuild@0.28.1) cac: 6.7.14 @@ -4860,7 +4847,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.23)(yaml@2.9.0) + postcss-load-config: 6.0.1(jiti@2.7.0)(postcss@8.5.32)(yaml@2.9.0) resolve-from: 5.0.0 rollup: 4.61.1 source-map: 0.7.6 @@ -4869,7 +4856,7 @@ snapshots: tinyglobby: 0.2.17 tree-kill: 1.2.2 optionalDependencies: - postcss: 8.5.23 + postcss: 8.5.32 typescript: 6.0.3 transitivePeerDependencies: - jiti @@ -4895,9 +4882,9 @@ snapshots: undici-types@7.24.6: {} - undici@7.29.0: {} + undici@7.30.2: {} - undici@8.10.0: {} + undici@8.12.4: {} util-deprecate@1.0.2: {} @@ -4905,12 +4892,12 @@ snapshots: uuid@14.0.0: {} - vite@8.0.16(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0): + vite@8.3.6(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0): dependencies: - lightningcss: 1.32.0 - picomatch: 4.0.4 - postcss: 8.5.23 - rolldown: 1.0.3 + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.32 + rolldown: 1.2.16 tinyglobby: 0.2.17 optionalDependencies: '@types/node': 25.9.2 @@ -4919,10 +4906,10 @@ snapshots: 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)): + 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)): dependencies: '@vitest/expect': 4.1.11 - '@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/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/pretty-format': 4.1.11 '@vitest/runner': 4.1.11 '@vitest/snapshot': 4.1.11 @@ -4939,7 +4926,7 @@ snapshots: tinyexec: 1.2.4 tinyglobby: 0.2.17 tinyrainbow: 3.1.0 - vite: 8.0.16(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0) + vite: 8.3.6(@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 @@ -4981,9 +4968,10 @@ snapshots: ws@8.21.0: {} - wsl-utils@0.1.0: + wsl-utils@1.0.1: 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 283b117cc..9e9b6e4ba 100644 --- a/integrations/pi-agent-plugin/pnpm-workspace.yaml +++ b/integrations/pi-agent-plugin/pnpm-workspace.yaml @@ -2,13 +2,16 @@ 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.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" + "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" "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 22c10b2c8..616de9d02 100644 --- a/integrations/pi-agent-plugin/skills/context-loader/SKILL.md +++ b/integrations/pi-agent-plugin/skills/context-loader/SKILL.md @@ -1,34 +1,19 @@ --- name: context-loader -description: Searches and injects relevant memories into context before starting work on a task or topic. Use when beginning a new task, switching context, or when past decisions, preferences, or knowledge need to be loaded. +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. --- # Context Loader Pre-fetches relevant memories to prime context before working on a task or topic. -## When to use - -- Session start (auto-triggered by the extension's `before_agent_start` event) -- User starts work on a specific topic or area -- User says "what do we know about X" or "context for X" - ## Steps 1. **Extract topics** from current message/task. Identify: subject areas, people mentioned, project names, goal references. -2. **Run 2-4 parallel searches** using `mem0_memory` tool with `action="search"` and different query angles: +2. **Call `mem0_memory` once** with `action="search"` and a focused question about the task. - | 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): +3. **Output compact context block** (max 10 memories): ``` context-loader: loaded memories for "" @@ -37,7 +22,7 @@ context-loader: loaded memories for "" - [lessons] [mem0:] ``` -5. If **zero results**: output nothing. Don't announce empty context. +4. 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 new file mode 100644 index 000000000..f90d28da3 --- /dev/null +++ b/integrations/pi-agent-plugin/src/attribution.test.ts @@ -0,0 +1,80 @@ +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 new file mode 100644 index 000000000..2cbc9a73e --- /dev/null +++ b/integrations/pi-agent-plugin/src/attribution.ts @@ -0,0 +1,65 @@ +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 9379bed9a..e969478a1 100644 --- a/integrations/pi-agent-plugin/src/commands.ts +++ b/integrations/pi-agent-plugin/src/commands.ts @@ -1,3 +1,4 @@ +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"; @@ -5,6 +6,12 @@ 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; @@ -29,7 +36,12 @@ 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 ?? []; }; @@ -45,7 +57,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 }, + { ...addParams, customCategories: DEFAULT_CUSTOM_CATEGORIES, infer: false, source: PLATFORM_SOURCE }, ); captureCommandEvent("mem0-remember", {}, telemetryCtx); diff --git a/integrations/pi-agent-plugin/src/entry.ts b/integrations/pi-agent-plugin/src/entry.ts index d49d78ad0..256c05aa4 100644 --- a/integrations/pi-agent-plugin/src/entry.ts +++ b/integrations/pi-agent-plugin/src/entry.ts @@ -10,6 +10,7 @@ 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"; @@ -29,6 +30,11 @@ 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 96d8e9b3e..f6110a73f 100644 --- a/integrations/pi-agent-plugin/src/memory/tools.ts +++ b/integrations/pi-agent-plugin/src/memory/tools.ts @@ -1,4 +1,5 @@ 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"; @@ -144,11 +145,10 @@ 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\" 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.", + `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.`, promptSnippet: "Semantic memory search and storage via Mem0", promptGuidelines: [ - '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 "search" ${SEARCH_WHEN}`, '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 -- 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).", + "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).", }, ), query: Type.Optional( Type.String({ description: - "Search text -- required for action \"search\". Use a focused noun-phrase; for multi-part questions run several searches with different phrasings.", + `Search text -- required for action "search". ${SEARCH_QUERY_DESCRIPTION}`, }), ), content: Type.Optional( diff --git a/integrations/pi-agent-plugin/src/prompt.ts b/integrations/pi-agent-plugin/src/prompt.ts index 83365239b..dd1137d35 100644 --- a/integrations/pi-agent-plugin/src/prompt.ts +++ b/integrations/pi-agent-plugin/src/prompt.ts @@ -1,10 +1,9 @@ -export const MEMORY_POLICY = ` -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. +import { SEARCH_WHEN } from "../../agent-plugin-core/typescript/src/prompts.ts"; -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). +export const MEMORY_POLICY = ` +You have persistent semantic memory via the mem0_memory tool, powered by Mem0. Relevant memories may be auto-injected under . + +Use mem0_memory with action "search" ${SEARCH_WHEN}. 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 7b417e460..959d69eb7 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.2", + "version": "3.0.3", "description": "Vercel AI Provider for providing memory to LLMs", "main": "./dist/index.js", "module": "./dist/index.mjs", @@ -88,9 +88,10 @@ "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.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" + "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" } } } diff --git a/integrations/vercel-ai-sdk/pnpm-lock.yaml b/integrations/vercel-ai-sdk/pnpm-lock.yaml index f8208a36a..dfdf09ab3 100644 --- a/integrations/vercel-ai-sdk/pnpm-lock.yaml +++ b/integrations/vercel-ai-sdk/pnpm-lock.yaml @@ -14,9 +14,10 @@ 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.1: '>=3.15.1 <4.0.0' - js-yaml@>=4.0.0 <4.3.1: '>=4.3.1 <5.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' importers: @@ -1115,8 +1116,8 @@ packages: graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} - handlebars@4.7.9: - resolution: {integrity: sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==} + handlebars@4.7.10: + resolution: {integrity: sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==} engines: {node: '>=0.4.7'} hasBin: true @@ -1356,8 +1357,8 @@ packages: js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} - js-yaml@3.15.1: - resolution: {integrity: sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==} + js-yaml@3.15.2: + resolution: {integrity: sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==} hasBin: true jsesc@3.1.0: @@ -2231,7 +2232,7 @@ snapshots: camelcase: 5.3.1 find-up: 4.1.0 get-package-type: 0.1.0 - js-yaml: 3.15.1 + js-yaml: 3.15.2 resolve-from: 5.0.0 '@istanbuljs/schema@0.1.6': {} @@ -2943,7 +2944,7 @@ snapshots: graceful-fs@4.2.11: {} - handlebars@4.7.9: + handlebars@4.7.10: dependencies: minimist: 1.2.8 neo-async: 2.6.2 @@ -3360,7 +3361,7 @@ snapshots: js-tokens@4.0.0: {} - js-yaml@3.15.1: + js-yaml@3.15.2: dependencies: argparse: 1.0.10 esprima: 4.0.1 @@ -3721,7 +3722,7 @@ snapshots: dependencies: bs-logger: 0.2.6 fast-json-stable-stringify: 2.1.0 - handlebars: 4.7.9 + handlebars: 4.7.10 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 93ff161d8..db4fa06a6 100644 --- a/integrations/vercel-ai-sdk/pnpm-workspace.yaml +++ b/integrations/vercel-ai-sdk/pnpm-workspace.yaml @@ -15,6 +15,7 @@ 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.1": ">=3.15.1 <4.0.0" - "js-yaml@>=4.0.0 <4.3.1": ">=4.3.1 <5.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" diff --git a/integrations/vercel-ai-sdk/src/mem0-utils.ts b/integrations/vercel-ai-sdk/src/mem0-utils.ts index 55d485cbc..b7a041939 100644 --- a/integrations/vercel-ai-sdk/src/mem0-utils.ts +++ b/integrations/vercel-ai-sdk/src/mem0-utils.ts @@ -1,3 +1,10 @@ +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'; @@ -277,7 +284,11 @@ const searchInternalMemories = async (query: string, config?: Mem0ConfigSettings method: 'POST', headers: { Authorization: `Token ${apiKey}`, - 'Content-Type': 'application/json' + '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}` }, body: JSON.stringify(body), }; @@ -331,7 +342,11 @@ const updateMemories = async (messages: Array, config?: Mem0ConfigSetti method: 'POST', headers: { Authorization: `Token ${apiKey}`, - 'Content-Type': 'application/json' + '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}` }, body: JSON.stringify(body), }; diff --git a/integrations/vercel-ai-sdk/tsconfig.json b/integrations/vercel-ai-sdk/tsconfig.json index b05d5db02..e40350730 100644 --- a/integrations/vercel-ai-sdk/tsconfig.json +++ b/integrations/vercel-ai-sdk/tsconfig.json @@ -12,6 +12,7 @@ "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 2c8f74a6d..ff2d298c0 100644 --- a/integrations/vercel-ai-sdk/tsup.config.ts +++ b/integrations/vercel-ai-sdk/tsup.config.ts @@ -1,4 +1,5 @@ import { defineConfig } from 'tsup' +import pkg from './package.json' export default defineConfig([ { @@ -6,5 +7,11 @@ 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/package.json b/integrations/zapier-mem0/package.json index b33e01b53..f2b245d35 100644 --- a/integrations/zapier-mem0/package.json +++ b/integrations/zapier-mem0/package.json @@ -72,7 +72,8 @@ "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.1": ">=3.15.1 <4.0.0" + "js-yaml@<3.15.2": ">=3.15.2 <4.0.0", + "handlebars@<4.7.10": ">=4.7.10 <5.0.0" } } } diff --git a/integrations/zapier-mem0/pnpm-lock.yaml b/integrations/zapier-mem0/pnpm-lock.yaml index 703de111d..04aed747c 100644 --- a/integrations/zapier-mem0/pnpm-lock.yaml +++ b/integrations/zapier-mem0/pnpm-lock.yaml @@ -11,7 +11,8 @@ 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.1: '>=3.15.1 <4.0.0' + js-yaml@<3.15.2: '>=3.15.2 <4.0.0' + handlebars@<4.7.10: '>=4.7.10 <5.0.0' importers: @@ -704,8 +705,8 @@ packages: graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} - handlebars@4.7.9: - resolution: {integrity: sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==} + handlebars@4.7.10: + resolution: {integrity: sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==} engines: {node: '>=0.4.7'} hasBin: true @@ -951,8 +952,8 @@ packages: js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} - js-yaml@3.15.1: - resolution: {integrity: sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==} + js-yaml@3.15.2: + resolution: {integrity: sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==} hasBin: true jsesc@3.1.0: @@ -1654,7 +1655,7 @@ snapshots: camelcase: 5.3.1 find-up: 4.1.0 get-package-type: 0.1.0 - js-yaml: 3.15.1 + js-yaml: 3.15.2 resolve-from: 5.0.0 '@istanbuljs/schema@0.1.6': {} @@ -2287,7 +2288,7 @@ snapshots: graceful-fs@4.2.11: {} - handlebars@4.7.9: + handlebars@4.7.10: dependencies: minimist: 1.2.8 neo-async: 2.6.2 @@ -2714,7 +2715,7 @@ snapshots: js-tokens@4.0.0: {} - js-yaml@3.15.1: + js-yaml@3.15.2: dependencies: argparse: 1.0.10 esprima: 4.0.1 @@ -3032,7 +3033,7 @@ snapshots: dependencies: bs-logger: 0.2.6 fast-json-stable-stringify: 2.1.0 - handlebars: 4.7.9 + handlebars: 4.7.10 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 e19a69b83..8b131a6c6 100644 --- a/integrations/zapier-mem0/pnpm-workspace.yaml +++ b/integrations/zapier-mem0/pnpm-workspace.yaml @@ -8,4 +8,5 @@ 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.1": ">=3.15.1 <4.0.0" + "js-yaml@<3.15.2": ">=3.15.2 <4.0.0" + "handlebars@<4.7.10": ">=4.7.10 <5.0.0" diff --git a/marketplace.json b/marketplace.json index eea48e2af..ded2d2ece 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.1" + "version": "0.3.3" } ] } diff --git a/mem0-ts/package.json b/mem0-ts/package.json index 7697b2384..8a20df517 100644 --- a/mem0-ts/package.json +++ b/mem0-ts/package.json @@ -1,6 +1,6 @@ { "name": "mem0ai", - "version": "3.1.8", + "version": "3.3.1", "description": "The Memory Layer For Your AI Apps", "main": "./dist/index.js", "module": "./dist/index.mjs", @@ -100,10 +100,11 @@ "tsup": "^8.3.0", "typescript": "5.5.4", "iovalkey": "^0.3.3", - "@mochow/mochow-sdk-node": "^2.1.5" + "@mochow/mochow-sdk-node": "^2.1.5", + "@types/jest": "^29.5.14" }, "dependencies": { - "axios": "^1.18.0", + "axios": "^1.20.0", "openai": "^4.93.0", "uuid": "^11.1.1", "zod": "^3.24.1" @@ -127,8 +128,7 @@ "@qdrant/js-client-rest": "^1.18.0", "@supabase/supabase-js": "^2.49.1", "@turbopuffer/turbopuffer": "^2.0.0", - "@types/jest": "29.5.14", - "@types/pg": "8.11.0", + "@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,6 +257,15 @@ }, "oracledb": { "optional": true + }, + "pg": { + "optional": true + }, + "@types/pg": { + "optional": true + }, + "natural": { + "optional": true } }, "engines": { @@ -272,14 +281,15 @@ "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.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", + "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", "langsmith@<0.6.0": "^0.6.0", "minimatch@<3.1.3": "^3.1.3", "minimatch@>=5.0.0 <5.1.8": "^5.1.8", @@ -294,21 +304,25 @@ "glob@>=10.2.0 <10.5.0": "^10.5.0", "@modelcontextprotocol/sdk": "^1.25.4", "esbuild": ">=0.28.1", - "undici@<7.29.0": ">=7.29.0 <8.0.0", + "undici@<7.30.1": ">=7.30.1 <8.0.0", "@aws-sdk/client-bedrock-runtime": "3.967.0", "@aws-sdk/client-neptune-graph": "3.966.0", - "axios@<1.18.0": ">=1.18.0 <2.0.0", + "axios@<1.20.0": ">=1.20.0 <2.0.0", "brace-expansion@<1.1.16": ">=1.1.16 <2.0.0", - "brace-expansion@>=2.0.0 <2.1.4": ">=2.1.4 <3.0.0", + "brace-expansion@>=2.0.0 <2.1.6": ">=2.1.6 <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.3.1": ">=10.3.1 <11.0.0", + "ip-address@<10.5.1": ">=10.5.1 <11.0.0", "browserslist@<4.28.7": ">=4.28.7 <5.0.0", - "mysql2@<3.23.1": ">=3.23.1 <4.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" } } } diff --git a/mem0-ts/pnpm-lock.yaml b/mem0-ts/pnpm-lock.yaml index 5deb30e7b..b4a57fa45 100644 --- a/mem0-ts/pnpm-lock.yaml +++ b/mem0-ts/pnpm-lock.yaml @@ -5,14 +5,15 @@ 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.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' + 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' langsmith@<0.6.0: ^0.6.0 minimatch@<3.1.3: ^3.1.3 minimatch@>=5.0.0 <5.1.8: ^5.1.8 @@ -27,21 +28,25 @@ overrides: glob@>=10.2.0 <10.5.0: ^10.5.0 '@modelcontextprotocol/sdk': ^1.25.4 esbuild: '>=0.28.1' - undici@<7.29.0: '>=7.29.0 <8.0.0' + undici@<7.30.1: '>=7.30.1 <8.0.0' '@aws-sdk/client-bedrock-runtime': 3.967.0 '@aws-sdk/client-neptune-graph': 3.966.0 - axios@<1.18.0: '>=1.18.0 <2.0.0' + axios@<1.20.0: '>=1.20.0 <2.0.0' brace-expansion@<1.1.16: '>=1.1.16 <2.0.0' - brace-expansion@>=2.0.0 <2.1.4: '>=2.1.4 <3.0.0' + brace-expansion@>=2.0.0 <2.1.6: '>=2.1.6 <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.3.1: '>=10.3.1 <11.0.0' + ip-address@<10.5.1: '>=10.5.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: @@ -65,8 +70,8 @@ importers: specifier: 3.967.0 version: 3.967.0 '@azure/identity': - specifier: ^4.0.0 - version: 4.13.1 + specifier: '>=4.14.1 <5.0.0' + version: 4.14.1 '@azure/search-documents': specifier: ^12.0.0 version: 12.2.0 @@ -109,11 +114,8 @@ 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 @@ -122,8 +124,8 @@ importers: specifier: ^2.4.0 || ^3.0.0 version: 3.0.3 axios: - specifier: ^1.18.0 - version: 1.18.1 + specifier: ^1.20.0 + version: 1.20.0 better-sqlite3: specifier: ^12.6.2 version: 12.10.0 @@ -167,8 +169,8 @@ importers: specifier: ^6.5.0 || ^7.0.0 version: 7.0.1 pg: - specifier: 8.11.3 - version: 8.11.3 + specifier: ^8.11.3 + version: 8.21.0 redis: specifier: ^4.6.13 version: 4.7.1 @@ -191,6 +193,9 @@ 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 @@ -575,6 +580,10 @@ 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'} @@ -587,9 +596,9 @@ packages: resolution: {integrity: sha512-XPArKLzsvl0Hf0CaGyKHUyVgF7oDnhKoP85Xv6M4StF/1AhfORhZudHtOyf2s+FcbuQ9dPRAjB8J2KvRRMUK2A==} engines: {node: '>=20.0.0'} - '@azure/identity@4.13.1': - resolution: {integrity: sha512-5C/2WD5Vb1lHnZS16dNQRPMjN6oV/Upba+C9nBIs15PmOi6A3ZGs4Lr2u60zw4S04gi+u3cEXiqTVP7M4Pz3kw==} - engines: {node: '>=20.0.0'} + '@azure/identity@4.14.1': + resolution: {integrity: sha512-HHuuFrmN1uuF9D5A6aAo5eHzNFNX4Q+P4SksZqDKse5YaJFFy/zDLG3wXHEV2FVGgetZ3QM8jGURNBtnQYf1NQ==} + engines: {node: '>=22.0.0'} '@azure/logger@1.3.0': resolution: {integrity: sha512-fCqPIfOcLE+CGqGPd66c8bZpwAji98tZ4JI9i/mlTNTlsIWslCfpg48s/ypyLxZTump5sypjrKn2/kY7q8oAbA==} @@ -599,12 +608,16 @@ 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@5.2.4': - resolution: {integrity: sha512-rpBUg9dA8UpC2WiFt3KeDKVQmmmVrfxdRnW+F1ebgou/jX/0tAvYuonaq5RUo8OaqzOrj4x/HaI8DmY56RXZ2Q==} + '@azure/msal-node@7.2.0': + resolution: {integrity: sha512-Y87VJsMWF4jiqLqq8XYLb1o+rGc/HacwS3Zydi3bDtaVm5Sa8FlB7YrKrBFKRIYj27RJXAaDkErImMAqtM10Pg==} engines: {node: '>=20'} '@azure/search-documents@12.2.0': @@ -861,8 +874,8 @@ packages: resolution: {integrity: sha512-L38Ax21uF2OPUmCRWycZ/dZdMYf7gMrtClcxvVrqJVFmn8ET2M++GYmFGJpLqOHS1beATxOXLWe7y2ijSQz/ng==} engines: {node: '>=20'} - '@emnapi/runtime@1.11.2': - resolution: {integrity: sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA==} + '@emnapi/runtime@1.11.3': + resolution: {integrity: sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA==} '@esbuild/aix-ppc64@0.28.1': resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==} @@ -1038,8 +1051,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.4': - resolution: {integrity: sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==} + '@grpc/grpc-js@1.14.5': + resolution: {integrity: sha512-7VZM+SVdEcUUqSQeNI3zM8Qs/BhQKZndPo2h5VkYkAM8Iz0wJIa8mKV5ekQGqG8UUsnkQ0NMxIxwkIHYvj0qOw==} engines: {node: '>=12.10.0'} '@grpc/proto-loader@0.8.1': @@ -1075,144 +1088,144 @@ packages: resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} engines: {node: '>=18'} - '@img/sharp-darwin-arm64@0.35.3': - resolution: {integrity: sha512-RMnFX7YQsMoh7lWfcM4NEHHymBX/rLuKNPVM84XE9ONPcaSCDgE7CHIHpSgPcO2xcRthgBy1HfNO319mwhIAkg==} + '@img/sharp-darwin-arm64@0.35.5': + resolution: {integrity: sha512-QRUlFQ0WxvdWyqqG/WtI3iupfD5rBzmCHXSdPsY91sAtVtTo7Q4cb6zOccZ3gqEqkr0f1As1ehLqmEpDsRf+lg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [darwin] - '@img/sharp-darwin-x64@0.35.3': - resolution: {integrity: sha512-Xo+5uFBtLN0BKqieTxiFzFPQAUlBbbH5iBKyRX/z1JrbnYsHTfKJnUfL8+p2TPXr1pXqao4eeL4Rl144uDpK9w==} + '@img/sharp-darwin-x64@0.35.5': + resolution: {integrity: sha512-+BR255RhDlpygUpOc/Jdt1nT6DQ3XG/ERo5wbcdOf5Q320dKtPCKPLR1LJs9VGXRaMa8l1uUa0tkCNOXiAxZUw==} engines: {node: '>=20.9.0'} cpu: [x64] os: [darwin] - '@img/sharp-freebsd-wasm32@0.35.3': - resolution: {integrity: sha512-lUxcqWIj2wMQ9BrwNjngcr1gWUr5xgaGThBRqPPalIC2n67Cqj1uPh8NnA/ZhAg8hUbKl+kVHKwgUIwe6ZYPrg==} + '@img/sharp-freebsd-wasm32@0.35.5': + resolution: {integrity: sha512-Y/z91nEZ4uIBX5X3nfTovjU9lHNKFYbL2lpHCLVNmXQK03VIZvXBBt0KxbPGp2SdGSF+2mQU4e+hQaWOt86iAw==} engines: {node: '>=20.9.0'} os: [freebsd] - '@img/sharp-libvips-darwin-arm64@1.3.2': - resolution: {integrity: sha512-9J6ypZFpQBj4YnePGoq/S38w6nz+vqg5WZLrLGY4YuSemdMq47GMLBPO42MzwdGwpg/agZ7xzZcFHa48xlywfg==} + '@img/sharp-libvips-darwin-arm64@1.3.4': + resolution: {integrity: sha512-5R89nBYiRdUlSWJxPhO+GVtaXzXSxKnRu/xqMn3KTA3L9EB9Oy/P+Nn2f2vlhPuUdy/Zusb2DarbyTpGCfEDuw==} cpu: [arm64] os: [darwin] - '@img/sharp-libvips-darwin-x64@1.3.2': - resolution: {integrity: sha512-m2pW1n6cns9VaubNwsZ+c3CRYjxNQWgJ5gPlnL1nbBcpkBvFm6SCFN5o0psFHI8w9n11NKhFkeEDns98tiqbEw==} + '@img/sharp-libvips-darwin-x64@1.3.4': + resolution: {integrity: sha512-iR2OKH80yi0U+dUplyh3/xdpFvps6YkCwsXenIJxqxR1v9o+xtKTGbS9H7cps+2Vxjc8B1j96p75NmTGjIhtpQ==} cpu: [x64] os: [darwin] - '@img/sharp-libvips-linux-arm64@1.3.2': - resolution: {integrity: sha512-dqVSFynCox4C/J8kT16V7SIFAns0IjgLwkvYT7p8LQVmJ5OS5b6tI9IGflxTeuBS//zXeFIUbwt5dwxyZ17cnA==} + '@img/sharp-libvips-linux-arm64@1.3.4': + resolution: {integrity: sha512-Y3dgX/6lE2QhQb+Gxy0WZxfg9MEm/JBjamZpS2IklP7xIQoKN4hzAm7KcMVGtaVDt3neE9OKBC7vAfonA/Lr1A==} cpu: [arm64] os: [linux] - '@img/sharp-libvips-linux-arm@1.3.2': - resolution: {integrity: sha512-1eMLzy92I4J6rmi4mAT8yC3HxOtniyGELlzGbNMLLeqe052ahFQ0h6LFq+lh5DsDIdYViIDst08abvSbcEdLXQ==} + '@img/sharp-libvips-linux-arm@1.3.4': + resolution: {integrity: sha512-LmRtTsOHuvM2+wlO2Db37dx5MiZhB0FvSunciw48YjdOkZz9KAiRbm8ujeMOA1INqmei5NapFxYEK1D1ZSidmw==} cpu: [arm] os: [linux] - '@img/sharp-libvips-linux-ppc64@1.3.2': - resolution: {integrity: sha512-3z0NHDxD6n5I9gc05U1eW1AyRm+Gznzq3naMrthPNqE6oYykcogW0l/jfpJdjYnuNl8R7yI9pNbE1XiUeyq0Aw==} + '@img/sharp-libvips-linux-ppc64@1.3.4': + resolution: {integrity: sha512-Le6boB8Tai0Nis+gIxIpKx68UDVVIqdR8Tin5Yf1z2LJJQLDJvCDRqRu+jC2qCoD+eIomonmOwB4smBRxfVpYQ==} cpu: [ppc64] os: [linux] - '@img/sharp-libvips-linux-riscv64@1.3.2': - resolution: {integrity: sha512-bsb4rI+NldGOsXuej2r8OdSS8+zXDVaCWxyWrcv6kneTOlgAHtZABRzBBCwdsPiD90J4myNJuHpg6kA20ImW/w==} + '@img/sharp-libvips-linux-riscv64@1.3.4': + resolution: {integrity: sha512-aHkkIEHPRdQEegJN20MLmGtxYD9R2wQr3Cwpddnu5+YKMt6Uzax7S9h5gpZTo8wyrGuZSlfQ63OevL5mTyOC7Q==} cpu: [riscv64] os: [linux] - '@img/sharp-libvips-linux-s390x@1.3.2': - resolution: {integrity: sha512-/ABshyj8gCpyIrNXnHn4LorDJ0HHm1VhXPBlxZ8zAtfVPAaSafXPGn+sUSIRiwaSBy0mmFjSjiXI5mkcwdChKQ==} + '@img/sharp-libvips-linux-s390x@1.3.4': + resolution: {integrity: sha512-ra/mB6MikESDUO7Yg+Mi95bFBb9GsObURuhnOv3OqknjGe9sZrG8tCe9q0xSIGrtLgvgw0gKnFWcK4blSgQOuQ==} cpu: [s390x] os: [linux] - '@img/sharp-libvips-linux-x64@1.3.2': - resolution: {integrity: sha512-ITPEtgffGJ0S6G9dRyw/366tJQqFRcHWPHhC+Stpg3Z8AEMrDrTr2lhdz4f/Y/HMbRh//7Z5mBzEpVdi62Oc3w==} + '@img/sharp-libvips-linux-x64@1.3.4': + resolution: {integrity: sha512-GJ//SSXbnwSDes02umB3nDJLFcQzw8a18V8fyhqr6tV515tOEMdImjjxj1AoafMRz56F3PHgftnj1QEKSU1zkw==} cpu: [x64] os: [linux] - '@img/sharp-libvips-linuxmusl-arm64@1.3.2': - resolution: {integrity: sha512-zE9EdiUzUmg5mDT5a1rk5fYJ6GWPloTwWBYDS14naqHsL+EaMpDj1AWnpLgh3u0YCORv2Tt50wrcrpYqkP97Kw==} + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': + resolution: {integrity: sha512-hvulFwtjUcagsis6BBxHwGFwWoNZjgYmULGVrZcyfNbjA8hKILbRxGg15/7w5HDyXHXUos/j6baAWqnCyQ2DWA==} cpu: [arm64] os: [linux] - '@img/sharp-libvips-linuxmusl-x64@1.3.2': - resolution: {integrity: sha512-m0lrLiUt+lBYnCFr8qV/65yMR4E/c7/wf78I5eKTdkEakFAlZ9QlzEM3QIhhAwVeUhLAHLcCq7a7Vszq/oFNZQ==} + '@img/sharp-libvips-linuxmusl-x64@1.3.4': + resolution: {integrity: sha512-6zXKeE/p39I1AmA3cJG35eyBGNqNddLnUXjhwBnsGjFPWqf5VKkDBEqaEkPDoTEtkxwi2vv8Tcr2mDyP4So7Fg==} cpu: [x64] os: [linux] - '@img/sharp-linux-arm64@0.35.3': - resolution: {integrity: sha512-QgKDspHPnrU+GQ55XPhGwyhC8acLVOOSyAvo1oVfFmrIXLkDNmGWzAfDZ4xK8oSA1qBQrALcHX0G5UZni/SuFQ==} + '@img/sharp-linux-arm64@0.35.5': + resolution: {integrity: sha512-LYVx5JTsOM2CBzmxreh+nl64/3H6Xb09iSLknqH47z2T2DFFxDeFLP5y4dJwe6H7uGQlHPyEEtIqyo3DYsRwdQ==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] - '@img/sharp-linux-arm@0.35.3': - resolution: {integrity: sha512-affVWCTLooy8TSxbDx2qkzuDeaWLNVBA+P//FNBirHsXpP2fuBhk5AuboYUnrDnzoXes8GFjpTx0SBFOCRg+FA==} + '@img/sharp-linux-arm@0.35.5': + resolution: {integrity: sha512-LEaXK2WdXVK5ykcw0buWyPMsmLLL2vpHLD6yrNSW+JGEL3BZPA4tpKN6iaMc4AxTTAoaX/sU1rOL51lcIz48ZQ==} engines: {node: '>=20.9.0'} cpu: [arm] os: [linux] - '@img/sharp-linux-ppc64@0.35.3': - resolution: {integrity: sha512-sMd8rDxmpLOwv/7N44klFjOD5DUO7FLdjiXDI0hoxYaf7Ar262dQIEkosE98bps+5HPLtp/EvNqeqQtOycP/IA==} + '@img/sharp-linux-ppc64@0.35.5': + resolution: {integrity: sha512-QVxAAq8evVRI9ia2vqgwrmWucn5Dfv+JdWzj75pD8omHLPSP7f8p20O8jxzjCcuCEQEOtYOZUmX1hkiZ0kdevA==} engines: {node: '>=20.9.0'} cpu: [ppc64] os: [linux] - '@img/sharp-linux-riscv64@0.35.3': - resolution: {integrity: sha512-0Eob78yjlYPfL5vMNWAW55l3R9Y6BQS/gOfe0ZcP9mEz9ohhKSt4im1hayiknXgf8AWrFqMvJcKIdmLmEe7yeQ==} + '@img/sharp-linux-riscv64@0.35.5': + resolution: {integrity: sha512-LtdreXguaavKODPIfzJ4kffx7UNt1omwtK0rch4EBbbSTXPnxWmYSayXdLJw0fJzQ97kHt1gL/yh4tvU+nCyRQ==} engines: {node: '>=20.9.0'} cpu: [riscv64] os: [linux] - '@img/sharp-linux-s390x@0.35.3': - resolution: {integrity: sha512-KgAxQ0DxpNOq1rG2t5cgTgShJFGSuU7XO45cqC+1NVOuZnP6tlgZRuSYOfNupGkHID0o3cJOsw4DVeJpMovcGw==} + '@img/sharp-linux-s390x@0.35.5': + resolution: {integrity: sha512-UZasTOFiYzotTsGOCu42BfUzP6Tu6Do/947iRm1RsLKvlllxwGcn4RN27LibGWceix4Y+Pmw3jsnTcCQIgWjqA==} engines: {node: '>=20.9.0'} cpu: [s390x] os: [linux] - '@img/sharp-linux-x64@0.35.3': - resolution: {integrity: sha512-8pqvxubL2PGdhlPy6GLqzDYMUjyRmKAwKHYKixpdJYBUK7PJ0C029XdsnpFIdgRZG68fZiGdHVWcKPvtiPB4cA==} + '@img/sharp-linux-x64@0.35.5': + resolution: {integrity: sha512-SxFtLTeJInhAA9Q836kux2vZNeOBQEx658qvbboZScr0wIARym3IcGmW7KpVD5sbVg0Ojy+udFQdayYIZyoNog==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] - '@img/sharp-linuxmusl-arm64@0.35.3': - resolution: {integrity: sha512-Vz0iQjzzcSX3HCbfwFfCSG/9SCIqyO0mH2sXyiHaAYfBk0cRsCWXRyQYX0ovCK/PAQBbTzQ0dsPQHh5MAFL59w==} + '@img/sharp-linuxmusl-arm64@0.35.5': + resolution: {integrity: sha512-9HbMclmI1zlNkFRs3z9/eBtDjfD0sGlrX1z6b1qwmiFY5ElDLh4BC0LPBdVp7z1DXFiKlIcznf+ZlsuZzLxQqg==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [linux] - '@img/sharp-linuxmusl-x64@0.35.3': - resolution: {integrity: sha512-6O1NPKcDVj9QEdg7Hx549EX8U0rp6yXQERqru6yRN7fGBn32UvIRJUlWnk+8xDCiG76hXVBbX82NZ/ZKr0euIg==} + '@img/sharp-linuxmusl-x64@0.35.5': + resolution: {integrity: sha512-4KOphqB035HrVdqLZfCgMzzERrQkkzOwRhl4OAkRO1YCldbaFjySXMaK534Mo0V+LndnlJk+sbUyLeU0ULyD1A==} engines: {node: '>=20.9.0'} cpu: [x64] os: [linux] - '@img/sharp-wasm32@0.35.3': - resolution: {integrity: sha512-cZ0XkcYGpHZkqW6iCkqTcmUC0CD9DhD5d/qeZlZkfRBn6GnHniZXLUo5+9xw8Iv76YE6LQFN9YNBlKREcCG76w==} + '@img/sharp-wasm32@0.35.5': + resolution: {integrity: sha512-Ptsga1su4tQx+LLF1ECS9U6nz5kmrXKo6XVbtR48Ke3ZRxxgaWBu7IDtEe1quo8hiupwm6WFqxVlXaSf7IINGQ==} engines: {node: '>=20.9.0'} - '@img/sharp-webcontainers-wasm32@0.35.3': - resolution: {integrity: sha512-2rnq7bX3NzeR2T4YWgz8qiG4h3TSdMe+vN1iQXpJleSJ3SM5zQ8Fy2SyyXAWlbxpEZ2Y+Z4u1BePgJEYbSy80Q==} + '@img/sharp-webcontainers-wasm32@0.35.5': + resolution: {integrity: sha512-hfhF/FmoQyTUkA0bIKFOtw536BQSeBMe6BF6QyWlrPxT754+TFLaZ7sKKTfvvM0yJgKgaYTwnFCIZ/GuDw5SUA==} engines: {node: '>=20.9.0'} cpu: [wasm32] - '@img/sharp-win32-arm64@0.35.3': - resolution: {integrity: sha512-4bPwFdMbeC4JQ8L8LOyWp6nsHcboP5fxkp6iPOXz2Vg49R42TuMs2whkJ5OAP4/Ul035qOzy0AecOF9VOscn4w==} + '@img/sharp-win32-arm64@0.35.5': + resolution: {integrity: sha512-X4t7g+7ZA5DKblCBEXGjUqqemj4vczING/5viFwAL8h4N3qYeyjwdCvRLHi4EdOUI+2Z7UFlp1VM+p/AuEtm6Q==} engines: {node: '>=20.9.0'} cpu: [arm64] os: [win32] - '@img/sharp-win32-ia32@0.35.3': - resolution: {integrity: sha512-r53mXsBN6lFUDiST764SvgwUdHAqM4rPAiDzAmf4fLoB6X/rkfyTrLCg6+g17wJJiCmB3JYgHuUldCWUIRFSXw==} + '@img/sharp-win32-ia32@0.35.5': + resolution: {integrity: sha512-5Zm82LoBc43nhwNybZlG7Y1KO//Zhsn306fQl29ZOuStHLGTo3BWL83q3cznX0poxSAMuYL1On/BHBxkBeKr6A==} engines: {node: ^20.9.0} cpu: [ia32] os: [win32] - '@img/sharp-win32-x64@0.35.3': - resolution: {integrity: sha512-D4y1vNeZrIIJCN+uHaWVtH86B+aCrdMYYjicy9pXHvbGZeGYLLSd3wdVuC37FxVXlU1ARsk84eKWfWMXGYEqvA==} + '@img/sharp-win32-x64@0.35.5': + resolution: {integrity: sha512-x76eH0vEiHlcMQu8Y8IenntaACtddpT6W0wmXtWrnKcnKI7ME5DdgqhAD6SEWOEl1v2zDvkZDhFA9KnURwpfqg==} engines: {node: '>=20.9.0'} cpu: [x64] os: [win32] @@ -2009,8 +2022,8 @@ packages: engines: {node: '>=0.4.0'} hasBin: true - adm-zip@0.6.0: - resolution: {integrity: sha512-XleryMhbuksdKtofnWZ9Sk+4CUTbms4Mb/EU32SZwToAyZ5RgVos/ki8n+yr0LWHOGKuakbXTuuYNHLQjhddgg==} + adm-zip@0.6.1: + resolution: {integrity: sha512-Xwrja8nx9e5o2N1my4DsKCeKpdrnACyr1wtbPxBDgGzKzKyE9kRtBFA8mWldI+RVlD7CBZNWY/wQ2+ydwOR6kQ==} engines: {node: '>=14.0'} afinn-165-financialmarketnews@3.0.0: @@ -2107,8 +2120,8 @@ packages: aws4@1.13.2: resolution: {integrity: sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==} - axios@1.18.1: - resolution: {integrity: sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==} + axios@1.20.0: + resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==} babel-jest@29.7.0: resolution: {integrity: sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg==} @@ -2153,8 +2166,8 @@ packages: engines: {node: '>=6.0.0'} hasBin: true - basic-ftp@5.3.1: - resolution: {integrity: sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw==} + basic-ftp@6.2.1: + resolution: {integrity: sha512-bK67isD+lKq46AU8vNtjvMaT2ZqAOAmNCbxUHlFBRD4k15NWxyEjmaKtZPlgce58So4BNTjITGQOVTjL9y0ECA==} engines: {node: '>=10.0.0'} better-sqlite3@12.10.0: @@ -2184,8 +2197,8 @@ packages: brace-expansion@1.1.16: resolution: {integrity: sha512-IDw48K2/2kRkg9LdJxurvq3lV3aBgq0REY89duEqFRthjlPdXHKMj7EnQOXVckxzgisinf3nHfrcE2FufFLXMw==} - brace-expansion@2.1.4: - resolution: {integrity: sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==} + brace-expansion@2.1.7: + resolution: {integrity: sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==} brace-expansion@5.0.8: resolution: {integrity: sha512-JZyDyq3D4AUifKTPOB7DELf6XsB3WdPuNxCtob1vFXPsSXhdAiHBWJ/tJ8HAc9aH84BK+5JFZLNkJKx3G9kzQg==} @@ -2228,10 +2241,6 @@ 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==} @@ -2516,8 +2525,8 @@ packages: resolution: {integrity: sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q==} engines: {node: '>=18'} - default-browser@5.5.0: - resolution: {integrity: sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw==} + default-browser@5.5.1: + resolution: {integrity: sha512-m1pAzaJgZ/gssEqlOhJkPJp8Xly7QyW6xcrkUa2KKcDeDSEMP7X8xipU3snUcfisTQx0w1AGae+9UtJSfVnXGw==} engines: {node: '>=18'} define-data-property@1.1.4: @@ -2774,8 +2783,8 @@ packages: fn.name@1.1.0: resolution: {integrity: sha512-GRnmB5gPyJpAhTQdSZTSp9uaPSvl09KoYcMQtsB9rQoOmzs9dH6ffeccH+Z+cv6P68Hu5bC6JjRh4Ah/mHSNRw==} - follow-redirects@1.16.0: - resolution: {integrity: sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==} + follow-redirects@1.16.2: + resolution: {integrity: sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==} engines: {node: '>=4.0'} peerDependencies: debug: '*' @@ -2940,8 +2949,8 @@ packages: guid-typescript@1.0.9: resolution: {integrity: sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ==} - handlebars@4.7.9: - resolution: {integrity: sha512-4E71E0rpOaQuJR2A3xDZ+GM1HyWYv1clR58tC8emQNeQe3RH7MAzSbat+V0wG78LQBo6m6bzSG/L4pBuCsgnUQ==} + handlebars@4.7.10: + resolution: {integrity: sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg==} engines: {node: '>=0.4.7'} hasBin: true @@ -3038,8 +3047,8 @@ packages: resolution: {integrity: sha512-4rTJX6Q5wTYEvxboXi8DsEiUo+OvqJGtLYOSGm37KpdRXsG5XJjbVtYKGJpPSWP+QT7rWscA4vsrdmzbEbenpw==} engines: {node: '>=18.12.0'} - ip-address@10.4.0: - resolution: {integrity: sha512-oSK96Grm3aP6OrS263xVxbNDGVL7rzBtYdpGqlDG8iQdoenDoTs/nkki+DflYbAEE8Xl6o5YxhxlrKvI3nqKXQ==} + ip-address@10.7.2: + resolution: {integrity: sha512-7H/2gFSIitxc0hG3nOI1glS8QLo/EHBFFLk8vEUjXY/xu0AdL8jZ9U1IzO2PUm0d2D/ofQcAifb0g6OBkt8U7w==} engines: {node: '>= 12'} is-arrayish@0.2.1: @@ -3082,6 +3091,10 @@ 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'} @@ -3286,8 +3299,8 @@ packages: js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} - js-yaml@3.15.1: - resolution: {integrity: sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==} + js-yaml@3.15.2: + resolution: {integrity: sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w==} hasBin: true jsesc@3.1.0: @@ -3776,9 +3789,9 @@ packages: onnxruntime-web@1.26.0-dev.20260416-b7804b056c: resolution: {integrity: sha512-MD6Ss4GSpQBo6zqoJzyT9LRbKYs7x/JVN23FT24EcEvlqF4VuzPOeH6X38orZPKHQDbprn7K+SBpu0/mj2CQiw==} - open@10.2.0: - resolution: {integrity: sha512-YgBpdJHPyQ2UE5x+hlSXcnejzAvD0b22U2OuAP+8OnlJT+PjWPxtgmGqKKc+RgTM63U9gN0YzrYc71R2WT/hTA==} - engines: {node: '>=18'} + open@11.0.4: + resolution: {integrity: sha512-++Zlftm0kVLPmzC06t6epuWmcRMDbI4z5P3NNX979WA/k23+NtSOynEGzsVfZwguKw2mi5umVgnBlJQMwRz4Pg==} + engines: {node: '>=20'} open@8.4.2: resolution: {integrity: sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ==} @@ -3846,9 +3859,6 @@ 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'} @@ -3920,15 +3930,6 @@ 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'} @@ -4019,6 +4020,10 @@ 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'} @@ -4225,8 +4230,8 @@ packages: resolution: {integrity: sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==} engines: {node: '>=10'} - sharp@0.35.3: - resolution: {integrity: sha512-ej0zVHuZGHCiABXcNxeYhpRnPNPAcvbG8RMdBAhDAxLKkCRVSpK3Iyu7qbqw3JMzoj0REeM6f3tJLtVwl0023Q==} + sharp@0.35.5: + resolution: {integrity: sha512-Ywn4OnzGukp7CDMrp08RQ50YKmuwG47brZgIVPTvBaaAfQlRlygrRqSrxdCiL9M+LlzLBiJ68IR1QqvzHyjC7g==} engines: {node: '>=20.9.0'} peerDependencies: '@types/node': '*' @@ -4625,8 +4630,8 @@ packages: undici-types@7.24.6: resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} - undici@7.29.0: - resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==} + undici@7.30.2: + resolution: {integrity: sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==} engines: {node: '>=20.18.1'} update-browserslist-db@1.3.2: @@ -4758,9 +4763,9 @@ packages: utf-8-validate: optional: true - wsl-utils@0.1.0: - resolution: {integrity: sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw==} - engines: {node: '>=18'} + wsl-utils@1.0.1: + resolution: {integrity: sha512-c16PKLIRxBYpR3jSWsdS7SFp0COm5SOQdiFjY818dYFHJbMGuLBszpF07LBWmOS1uzrHa9VGdynsEgoeKy0oOQ==} + engines: {node: '>=20'} xml-naming@0.1.0: resolution: {integrity: sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw==} @@ -5804,6 +5809,8 @@ 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 @@ -5828,18 +5835,19 @@ snapshots: transitivePeerDependencies: - supports-color - '@azure/identity@4.13.1': + '@azure/identity@4.14.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': 5.2.4 - open: 10.2.0 + '@azure/msal-node': 7.2.0 + open: 11.0.4 tslib: 2.8.1 transitivePeerDependencies: - supports-color @@ -5855,11 +5863,13 @@ snapshots: dependencies: '@azure/msal-common': 16.8.0 + '@azure/msal-common@16.16.0': {} + '@azure/msal-common@16.8.0': {} - '@azure/msal-node@5.2.4': + '@azure/msal-node@7.2.0': dependencies: - '@azure/msal-common': 16.8.0 + '@azure/msal-common': 16.16.0 jsonwebtoken: 9.0.3 '@azure/search-documents@12.2.0': @@ -6154,11 +6164,11 @@ snapshots: ms: 2.1.3 secure-json-parse: 4.1.0 tslib: 2.8.1 - undici: 7.29.0 + undici: 7.30.2 transitivePeerDependencies: - supports-color - '@emnapi/runtime@1.11.2': + '@emnapi/runtime@1.11.3': dependencies: tslib: 2.8.1 optional: true @@ -6262,7 +6272,7 @@ snapshots: dependencies: graphql: 16.14.2 - '@grpc/grpc-js@1.14.4': + '@grpc/grpc-js@1.14.5': dependencies: '@grpc/proto-loader': 0.8.1 '@js-sdsl/ordered-map': 4.4.2 @@ -6295,7 +6305,7 @@ snapshots: '@huggingface/tokenizers': 0.1.3 onnxruntime-node: 1.24.3 onnxruntime-web: 1.26.0-dev.20260416-b7804b056c - sharp: 0.35.3(@types/node@22.19.21) + sharp: 0.35.5(@types/node@22.19.21) transitivePeerDependencies: - '@types/node' @@ -6306,108 +6316,108 @@ snapshots: '@img/colour@1.1.0': {} - '@img/sharp-darwin-arm64@0.35.3': + '@img/sharp-darwin-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.3.2 + '@img/sharp-libvips-darwin-arm64': 1.3.4 optional: true - '@img/sharp-darwin-x64@0.35.3': + '@img/sharp-darwin-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.3.2 + '@img/sharp-libvips-darwin-x64': 1.3.4 optional: true - '@img/sharp-freebsd-wasm32@0.35.3': + '@img/sharp-freebsd-wasm32@0.35.5': dependencies: - '@img/sharp-wasm32': 0.35.3 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-libvips-darwin-arm64@1.3.2': + '@img/sharp-libvips-darwin-arm64@1.3.4': optional: true - '@img/sharp-libvips-darwin-x64@1.3.2': + '@img/sharp-libvips-darwin-x64@1.3.4': optional: true - '@img/sharp-libvips-linux-arm64@1.3.2': + '@img/sharp-libvips-linux-arm64@1.3.4': optional: true - '@img/sharp-libvips-linux-arm@1.3.2': + '@img/sharp-libvips-linux-arm@1.3.4': optional: true - '@img/sharp-libvips-linux-ppc64@1.3.2': + '@img/sharp-libvips-linux-ppc64@1.3.4': optional: true - '@img/sharp-libvips-linux-riscv64@1.3.2': + '@img/sharp-libvips-linux-riscv64@1.3.4': optional: true - '@img/sharp-libvips-linux-s390x@1.3.2': + '@img/sharp-libvips-linux-s390x@1.3.4': optional: true - '@img/sharp-libvips-linux-x64@1.3.2': + '@img/sharp-libvips-linux-x64@1.3.4': optional: true - '@img/sharp-libvips-linuxmusl-arm64@1.3.2': + '@img/sharp-libvips-linuxmusl-arm64@1.3.4': optional: true - '@img/sharp-libvips-linuxmusl-x64@1.3.2': + '@img/sharp-libvips-linuxmusl-x64@1.3.4': optional: true - '@img/sharp-linux-arm64@0.35.3': + '@img/sharp-linux-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-arm64': 1.3.2 + '@img/sharp-libvips-linux-arm64': 1.3.4 optional: true - '@img/sharp-linux-arm@0.35.3': + '@img/sharp-linux-arm@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-arm': 1.3.2 + '@img/sharp-libvips-linux-arm': 1.3.4 optional: true - '@img/sharp-linux-ppc64@0.35.3': + '@img/sharp-linux-ppc64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-ppc64': 1.3.2 + '@img/sharp-libvips-linux-ppc64': 1.3.4 optional: true - '@img/sharp-linux-riscv64@0.35.3': + '@img/sharp-linux-riscv64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-riscv64': 1.3.2 + '@img/sharp-libvips-linux-riscv64': 1.3.4 optional: true - '@img/sharp-linux-s390x@0.35.3': + '@img/sharp-linux-s390x@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-s390x': 1.3.2 + '@img/sharp-libvips-linux-s390x': 1.3.4 optional: true - '@img/sharp-linux-x64@0.35.3': + '@img/sharp-linux-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linux-x64': 1.3.2 + '@img/sharp-libvips-linux-x64': 1.3.4 optional: true - '@img/sharp-linuxmusl-arm64@0.35.3': + '@img/sharp-linuxmusl-arm64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linuxmusl-arm64': 1.3.2 + '@img/sharp-libvips-linuxmusl-arm64': 1.3.4 optional: true - '@img/sharp-linuxmusl-x64@0.35.3': + '@img/sharp-linuxmusl-x64@0.35.5': optionalDependencies: - '@img/sharp-libvips-linuxmusl-x64': 1.3.2 + '@img/sharp-libvips-linuxmusl-x64': 1.3.4 optional: true - '@img/sharp-wasm32@0.35.3': + '@img/sharp-wasm32@0.35.5': dependencies: - '@emnapi/runtime': 1.11.2 + '@emnapi/runtime': 1.11.3 optional: true - '@img/sharp-webcontainers-wasm32@0.35.3': + '@img/sharp-webcontainers-wasm32@0.35.5': dependencies: - '@img/sharp-wasm32': 0.35.3 + '@img/sharp-wasm32': 0.35.5 optional: true - '@img/sharp-win32-arm64@0.35.3': + '@img/sharp-win32-arm64@0.35.5': optional: true - '@img/sharp-win32-ia32@0.35.3': + '@img/sharp-win32-ia32@0.35.5': optional: true - '@img/sharp-win32-x64@0.35.3': + '@img/sharp-win32-x64@0.35.5': optional: true '@iovalkey/commands@0.1.0': {} @@ -6430,7 +6440,7 @@ snapshots: camelcase: 5.3.1 find-up: 4.1.0 get-package-type: 0.1.0 - js-yaml: 3.15.1 + js-yaml: 3.15.2 resolve-from: 5.0.0 '@istanbuljs/schema@0.1.6': {} @@ -6722,7 +6732,7 @@ snapshots: dependencies: '@qdrant/openapi-typescript-fetch': 1.2.6 typescript: 5.5.4 - undici: 7.29.0 + undici: 7.30.2 '@qdrant/openapi-typescript-fetch@1.2.6': {} @@ -7194,7 +7204,7 @@ snapshots: '@turbopuffer/turbopuffer@2.5.0': dependencies: pako: 2.2.0 - undici: 7.29.0 + undici: 7.30.2 '@types/babel__core@7.20.5': dependencies: @@ -7336,7 +7346,7 @@ snapshots: '@zilliz/milvus2-sdk-node@3.0.3': dependencies: - '@grpc/grpc-js': 1.14.4 + '@grpc/grpc-js': 1.14.5 '@grpc/proto-loader': 0.8.1 '@opentelemetry/api': 1.9.1 '@petamoriken/float16': 3.9.3 @@ -7362,7 +7372,7 @@ snapshots: acorn@8.16.0: {} - adm-zip@0.6.0: {} + adm-zip@0.6.1: {} afinn-165-financialmarketnews@3.0.0: {} @@ -7448,9 +7458,9 @@ snapshots: aws4@1.13.2: {} - axios@1.18.1: + axios@1.20.0: dependencies: - follow-redirects: 1.16.0 + follow-redirects: 1.16.2 form-data: 4.0.6 https-proxy-agent: 5.0.1 proxy-from-env: 2.1.0 @@ -7523,7 +7533,7 @@ snapshots: baseline-browser-mapping@2.11.21: {} - basic-ftp@5.3.1: {} + basic-ftp@6.2.1: {} better-sqlite3@12.10.0: dependencies: @@ -7553,7 +7563,7 @@ snapshots: balanced-match: 1.0.2 concat-map: 0.0.1 - brace-expansion@2.1.4: + brace-expansion@2.1.7: dependencies: balanced-match: 1.0.2 @@ -7593,8 +7603,6 @@ snapshots: buffer-from@1.1.2: {} - buffer-writer@2.0.0: {} - buffer@5.7.1: dependencies: base64-js: 1.5.1 @@ -7632,7 +7640,7 @@ snapshots: cassandra-driver@4.8.0: dependencies: '@types/node': 18.19.130 - adm-zip: 0.6.0 + adm-zip: 0.6.1 long: 5.2.5 chalk-template@0.4.0: @@ -7860,7 +7868,7 @@ snapshots: default-browser-id@5.0.1: {} - default-browser@5.5.0: + default-browser@5.5.1: dependencies: bundle-name: 4.1.0 default-browser-id: 5.0.1 @@ -8134,7 +8142,7 @@ snapshots: fn.name@1.1.0: {} - follow-redirects@1.16.0: {} + follow-redirects@1.16.2: {} foreground-child@3.3.1: dependencies: @@ -8225,7 +8233,7 @@ snapshots: get-uri@6.0.5: dependencies: - basic-ftp: 5.3.1 + basic-ftp: 6.2.1 data-uri-to-buffer: 6.0.2 debug: 4.4.3(supports-color@5.5.0) transitivePeerDependencies: @@ -8294,7 +8302,7 @@ snapshots: google-gax@5.0.7: dependencies: - '@grpc/grpc-js': 1.14.4 + '@grpc/grpc-js': 1.14.5 '@grpc/proto-loader': 0.8.1 duplexify: 4.1.3 google-auth-library: 10.5.0 @@ -8349,7 +8357,7 @@ snapshots: guid-typescript@1.0.9: {} - handlebars@4.7.9: + handlebars@4.7.10: dependencies: minimist: 1.2.8 neo-async: 2.6.2 @@ -8453,7 +8461,7 @@ snapshots: transitivePeerDependencies: - supports-color - ip-address@10.4.0: {} + ip-address@10.7.2: {} is-arrayish@0.2.1: {} @@ -8481,6 +8489,8 @@ 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 @@ -8525,7 +8535,7 @@ snapshots: '@babel/parser': 7.29.7 '@istanbuljs/schema': 0.1.6 istanbul-lib-coverage: 3.2.2 - semver: 7.8.4 + semver: 7.8.5 transitivePeerDependencies: - supports-color @@ -8873,7 +8883,7 @@ snapshots: js-tokens@4.0.0: {} - js-yaml@3.15.1: + js-yaml@3.15.2: dependencies: argparse: 1.0.10 esprima: 4.0.1 @@ -8907,7 +8917,7 @@ snapshots: lodash.isstring: 4.0.1 lodash.once: 4.1.1 ms: 2.1.3 - semver: 7.8.4 + semver: 7.8.5 jwa@2.0.1: dependencies: @@ -9023,7 +9033,7 @@ snapshots: make-dir@4.0.0: dependencies: - semver: 7.8.4 + semver: 7.8.5 make-error@1.3.6: {} @@ -9081,7 +9091,7 @@ snapshots: minimatch@9.0.9: dependencies: - brace-expansion: 2.1.4 + brace-expansion: 2.1.7 minimist@1.2.8: {} @@ -9218,7 +9228,7 @@ snapshots: nice-grpc@2.1.16: dependencies: - '@grpc/grpc-js': 1.14.4 + '@grpc/grpc-js': 1.14.5 abort-controller-x: 0.5.0 nice-grpc-common: 2.0.3 @@ -9309,7 +9319,7 @@ snapshots: onnxruntime-node@1.24.3: dependencies: - adm-zip: 0.6.0 + adm-zip: 0.6.1 global-agent: 3.0.0 onnxruntime-common: 1.24.3 @@ -9322,12 +9332,14 @@ snapshots: platform: 1.3.6 protobufjs: 7.6.5 - open@10.2.0: + open@11.0.4: dependencies: - default-browser: 5.5.0 + default-browser: 5.5.1 define-lazy-prop: 3.0.0 + is-in-ssh: 1.0.0 is-inside-container: 1.0.0 - wsl-utils: 0.1.0 + powershell-utils: 0.2.1 + wsl-utils: 1.0.1 open@8.4.2: dependencies: @@ -9409,8 +9421,6 @@ snapshots: package-json-from-dist@1.0.1: {} - packet-reader@1.0.0: {} - pad-left@2.1.0: dependencies: repeat-string: 1.6.1 @@ -9458,10 +9468,6 @@ 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 @@ -9486,18 +9492,6 @@ 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 @@ -9560,6 +9554,8 @@ snapshots: postgres-range@1.1.4: {} + powershell-utils@0.2.1: {} + prebuild-install@7.1.3: dependencies: detect-libc: 2.1.2 @@ -9806,37 +9802,37 @@ snapshots: dependencies: type-fest: 0.13.1 - sharp@0.35.3(@types/node@22.19.21): + sharp@0.35.5(@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.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 + '@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 '@types/node': 22.19.21 shebang-command@2.0.0: @@ -9881,7 +9877,7 @@ snapshots: socks@2.8.9: dependencies: - ip-address: 10.4.0 + ip-address: 10.7.2 smart-buffer: 4.2.0 source-map-support@0.5.13: @@ -10113,7 +10109,7 @@ snapshots: dependencies: bs-logger: 0.2.6 fast-json-stable-stringify: 2.1.0 - handlebars: 4.7.9 + handlebars: 4.7.10 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 @@ -10218,7 +10214,7 @@ snapshots: undici-types@7.24.6: {} - undici@7.29.0: {} + undici@7.30.2: {} update-browserslist-db@1.3.2(browserslist@4.28.9): dependencies: @@ -10346,9 +10342,10 @@ snapshots: ws@8.21.0: {} - wsl-utils@0.1.0: + wsl-utils@1.0.1: 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 4048a653c..4a75a2cdc 100644 --- a/mem0-ts/pnpm-workspace.yaml +++ b/mem0-ts/pnpm-workspace.yaml @@ -6,14 +6,15 @@ 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.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" + "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" "langsmith@<0.6.0": "^0.6.0" "minimatch@<3.1.3": "^3.1.3" "minimatch@>=5.0.0 <5.1.8": "^5.1.8" @@ -27,19 +28,23 @@ overrides: "glob@>=10.2.0 <10.5.0": "^10.5.0" "@modelcontextprotocol/sdk": "^1.25.4" "esbuild": ">=0.28.1" - "undici@<7.29.0": ">=7.29.0 <8.0.0" - "axios@<1.18.0": ">=1.18.0 <2.0.0" + "undici@<7.30.1": ">=7.30.1 <8.0.0" + "axios@<1.20.0": ">=1.20.0 <2.0.0" "brace-expansion@<1.1.16": ">=1.1.16 <2.0.0" - "brace-expansion@>=2.0.0 <2.1.4": ">=2.1.4 <3.0.0" + "brace-expansion@>=2.0.0 <2.1.6": ">=2.1.6 <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.3.1": ">=10.3.1 <11.0.0" + "ip-address@<10.5.1": ">=10.5.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 24ec5b8f4..138b29dc7 100644 --- a/mem0-ts/src/client/index.ts +++ b/mem0-ts/src/client/index.ts @@ -23,6 +23,14 @@ 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 ff259f2fe..c386be323 100644 --- a/mem0-ts/src/client/mem0.ts +++ b/mem0-ts/src/client/mem0.ts @@ -1,4 +1,5 @@ import axios from "axios"; +import { v7 as uuidv7 } from "uuid"; import { AllUsers, PaginatedMemories, @@ -20,6 +21,12 @@ import { FeedbackPayload, CreateMemoryExportPayload, GetMemoryExportPayload, + ProfileEntityType, + ProfileResponse, + ProfileJobResponse, + ProfileJobStatus, + ProfileSettings, + ProfileSettingsResponse, } from "./mem0.types"; import { captureClientEvent, @@ -67,6 +74,34 @@ 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)); } @@ -92,9 +127,72 @@ 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; @@ -129,6 +227,7 @@ export default class MemoryClient { this.headers = { Authorization: `Token ${this.apiKey}`, "Content-Type": "application/json", + ...surfaceHeaders(), }; this.client = axios.create({ @@ -244,7 +343,8 @@ export default class MemoryClient { }); } - async _fetchWithErrorHandling(url: string, options: any): Promise { + /** Fetch with no key conversion, for payloads carrying user-controlled property names. */ + async _fetchRawJson(url: string, options: any): Promise { const response = await fetch(url, { ...options, headers: { @@ -257,8 +357,11 @@ export default class MemoryClient { const errorData = await response.text(); throw createExceptionFromResponse(response.status, errorData); } - const jsonResponse = await response.json(); - return snakeToCamelKeys(jsonResponse); + return response.json(); + } + + async _fetchWithErrorHandling(url: string, options: any): Promise { + return snakeToCamelKeys(await this._fetchRawJson(url, options)); } _preparePayload( @@ -321,6 +424,7 @@ 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); @@ -465,6 +569,8 @@ 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)); @@ -536,6 +642,7 @@ 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; @@ -755,6 +862,192 @@ 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 c230441e0..a178f4529 100644 --- a/mem0-ts/src/client/mem0.types.ts +++ b/mem0-ts/src/client/mem0.types.ts @@ -30,6 +30,9 @@ 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 { @@ -122,6 +125,8 @@ 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; @@ -236,3 +241,98 @@ 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 new file mode 100644 index 000000000..463284852 --- /dev/null +++ b/mem0-ts/src/client/tests/memoryClient.entityGuards.test.ts @@ -0,0 +1,234 @@ +/** 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 new file mode 100644 index 000000000..27069a570 --- /dev/null +++ b/mem0-ts/src/client/tests/memoryClient.profiles.test.ts @@ -0,0 +1,341 @@ +/** + * 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 aca9ffbcd..8630ad470 100644 --- a/mem0-ts/src/client/utils.ts +++ b/mem0-ts/src/client/utils.ts @@ -34,6 +34,9 @@ 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 b2803d1b2..d2fa34b52 100644 --- a/mem0-ts/src/oss/src/config/manager.ts +++ b/mem0-ts/src/oss/src/config/manager.ts @@ -113,7 +113,18 @@ export class ConfigManager { const userConf = userConfig.llm?.config; const provider = userConfig.llm?.provider || DEFAULT_MEMORY_CONFIG.llm.provider; - let finalModel: string | any = defaultConf.model; + // 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; if (userConf?.model && typeof userConf.model === "object") { finalModel = userConf.model; @@ -131,9 +142,7 @@ export class ConfigManager { | string | undefined) ?? userConf?.url ?? - (provider.toLowerCase() === "vllm" - ? undefined - : defaultConf.baseURL); + (usesOpenAIDefaults ? defaultConf.baseURL : undefined); 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 1efbc3e45..00fdc7d97 100644 --- a/mem0-ts/src/oss/src/memory/index.ts +++ b/mem0-ts/src/oss/src/memory/index.ts @@ -768,7 +768,9 @@ export class Memory { has_filters: !!config.filters, infer: config.infer, }); - const { filters = {}, infer = true } = config; + // 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 metadata = stripIdentityKeys(config.metadata); // Validate and trim entity IDs @@ -1988,7 +1990,15 @@ export class Memory { updatedAt: new Date().toISOString(), }; - await this.vectorStore.update(memoryId, embedding, newMetadata); + 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.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 3b51e7eef..6efb2df2f 100644 --- a/mem0-ts/src/oss/src/tests/chroma.test.ts +++ b/mem0-ts/src/oss/src/tests/chroma.test.ts @@ -271,14 +271,47 @@ 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(); - await db.update("vec-1", [1, 2, 3], { text: "updated" }); + expect(await db.update("vec-1", [1, 2, 3], { text: "updated" })).toBe(true); 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 fe847b56c..d6600bf04 100644 --- a/mem0-ts/src/oss/src/tests/mongodb.test.ts +++ b/mem0-ts/src/oss/src/tests/mongodb.test.ts @@ -330,7 +330,9 @@ describe("MongoDB Vector Store", () => { it("should update document correctly", async () => { mockUpdateOne.mockResolvedValue({ matchedCount: 1 }); - await store.update("id1", [0.1, 0.2, 0.3, 0.4], { name: "new-alice" }); + expect( + await store.update("id1", [0.1, 0.2, 0.3, 0.4], { name: "new-alice" }), + ).toBe(true); expect(mockUpdateOne).toHaveBeenCalledWith( { _id: "id1" }, @@ -343,6 +345,32 @@ 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 3c008538e..5342d7a49 100644 --- a/mem0-ts/src/oss/src/tests/pinecone.test.ts +++ b/mem0-ts/src/oss/src/tests/pinecone.test.ts @@ -9,12 +9,13 @@ // 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, query, fetch, deleteOne, deleteAll }; +const nsHandle = { upsert, update, query, fetch, deleteOne, deleteAll }; const namespace = jest.fn().mockReturnValue(nsHandle); const describeIndexStats = jest @@ -26,6 +27,7 @@ const indexHandle = { describeIndexStats, // expose ops directly for the no-namespace path upsert, + update, query, fetch, deleteOne, @@ -45,6 +47,7 @@ const Pinecone = jest.fn().mockImplementation(() => ({ const __mocks__ = { upsert, + update, query, fetch, deleteOne, @@ -104,6 +107,7 @@ beforeEach(() => { const nsHandle = { upsert: __mocks__.upsert, + update: __mocks__.update, query: __mocks__.query, fetch: __mocks__.fetch, deleteOne: __mocks__.deleteOne, @@ -114,6 +118,7 @@ beforeEach(() => { namespace: __mocks__.namespace, describeIndexStats: __mocks__.describeIndexStats, upsert: __mocks__.upsert, + update: __mocks__.update, query: __mocks__.query, fetch: __mocks__.fetch, deleteOne: __mocks__.deleteOne, @@ -399,14 +404,27 @@ describe("get", () => { }); describe("update", () => { - it("upserts a single record", async () => { + it("updates by id and never upserts", async () => { const db = await initDb(); - 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" } }, - ], + 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" }, }); + 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 52576aca0..84117718b 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,15 +493,19 @@ export class AzureAISearch implements VectorStore { } } - const response = await this.searchClient.mergeOrUploadDocuments([document]); + const response = await this.searchClient.mergeDocuments([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 123767484..d525fcca7 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, RowDataPacket } from "mysql2/promise"; +import type { Pool, ResultSetHeader, RowDataPacket } from "mysql2/promise"; import { VectorStore } from "./base"; import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types"; import { loadPeer } from "../utils/load_peer"; @@ -275,16 +275,18 @@ export class AzureMySQLDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); const conn = await this.pool!.getConnection(); try { await conn.beginTransaction(); - await conn.execute( + // mysql2 sets CLIENT_FOUND_ROWS by default, so affectedRows counts matched rows. + const [result] = await conn.execute( `UPDATE ${this.col()} SET vector = ?, payload = ? WHERE id = ?`, [JSON.stringify(vector), JSON.stringify(payload), vectorId], ); await conn.commit(); + return result.affectedRows > 0; } catch (err) { await conn.rollback(); throw err; diff --git a/mem0-ts/src/oss/src/vector_stores/base.ts b/mem0-ts/src/oss/src/vector_stores/base.ts index 975541cf8..970981274 100644 --- a/mem0-ts/src/oss/src/vector_stores/base.ts +++ b/mem0-ts/src/oss/src/vector_stores/base.ts @@ -17,11 +17,12 @@ export interface VectorStore { filters?: SearchFilters, ): Promise; get(vectorId: string): Promise; + /** Must not create a record. true: record changed; false: id does not exist; void: the store cannot tell. */ update( vectorId: string, vector: number[], payload: Record, - ): Promise; + ): Promise; delete(vectorId: string): Promise; deleteCol(): Promise; list( diff --git a/mem0-ts/src/oss/src/vector_stores/chroma.ts b/mem0-ts/src/oss/src/vector_stores/chroma.ts index bec0e961a..994b0a596 100644 --- a/mem0-ts/src/oss/src/vector_stores/chroma.ts +++ b/mem0-ts/src/oss/src/vector_stores/chroma.ts @@ -186,13 +186,24 @@ export class ChromaDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { const collection = await this.getCollection(); await collection.update({ ids: [vectorId], embeddings: vector ? [vector] : undefined, metadatas: payload ? [payload] : undefined, } as any); + // Chroma skips unknown ids on update without an error, so check existence after the write. + try { + const existing = await collection.get({ ids: [vectorId], include: [] }); + return existing.ids.length > 0; + } catch (error) { + // The write already ran; failing here would surface an error for a landed update. + console.warn( + `Chroma update of '${vectorId}' could not be confirmed:`, + error, + ); + } } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/databricks.ts b/mem0-ts/src/oss/src/vector_stores/databricks.ts index 627e522ee..f09e8f2b5 100644 --- a/mem0-ts/src/oss/src/vector_stores/databricks.ts +++ b/mem0-ts/src/oss/src/vector_stores/databricks.ts @@ -665,7 +665,7 @@ export class DatabricksVectorStore implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); this.assertVectorDimension(vector, "Vector"); @@ -673,7 +673,8 @@ export class DatabricksVectorStore implements VectorStore { // are written once at insert(). Mirror Python's `excluded_keys`: update() must never rewrite // them from the payload -- a partial payload that omits these keys would otherwise SET them to // NULL and hide the row from every session-scoped search and list(). - await this.executeSql(` + // A Delta UPDATE returns one row with num_affected_rows; without it we cannot tell. + const rows = await this.executeSql(` UPDATE ${this.fullTableName} SET embedding = ${formatSqlValue(vector)}, payload = ${formatSqlValue(JSON.stringify(payload || {}))}, @@ -681,6 +682,10 @@ export class DatabricksVectorStore implements VectorStore { WHERE memory_id = ${formatSqlValue(vectorId)} `); this.requestIndexSync(); + const raw = extractRowValue(rows[0] ?? {}, ["num_affected_rows"]); + // Number(null) and Number("") are 0, which would read as "missing". + const affected = raw == null || raw === "" ? NaN : Number(raw); + if (Number.isFinite(affected)) return affected > 0; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/elasticsearch.ts b/mem0-ts/src/oss/src/vector_stores/elasticsearch.ts index 27ec5dde6..c8a5d0e5b 100644 --- a/mem0-ts/src/oss/src/vector_stores/elasticsearch.ts +++ b/mem0-ts/src/oss/src/vector_stores/elasticsearch.ts @@ -236,17 +236,24 @@ export class ElasticsearchDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); const doc: Record = {}; if (vector) doc.vector = vector; if (payload) doc.metadata = payload; - await this.client.update({ + const request = this.client.update({ index: this.collectionName, id: vectorId, doc, }); + try { + await request; + } catch (error: any) { + if (error?.meta?.statusCode === 404) return false; + throw error; + } + return true; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/memory.ts b/mem0-ts/src/oss/src/vector_stores/memory.ts index 7969194f0..bbbbabaf7 100644 --- a/mem0-ts/src/oss/src/vector_stores/memory.ts +++ b/mem0-ts/src/oss/src/vector_stores/memory.ts @@ -407,16 +407,17 @@ export class MemoryVectorStore implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { if (vector.length !== this.dimension) { throw new Error( `Vector dimension mismatch. Expected ${this.dimension}, got ${vector.length}`, ); } const vectorBuffer = Buffer.from(new Float32Array(vector).buffer); - this.db + const result = this.db .prepare(`UPDATE vectors SET vector = ?, payload = ? WHERE id = ?`) .run(vectorBuffer, JSON.stringify(payload), vectorId); + return result.changes > 0; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/mongodb.ts b/mem0-ts/src/oss/src/vector_stores/mongodb.ts index a3bcecf21..776bf7138 100644 --- a/mem0-ts/src/oss/src/vector_stores/mongodb.ts +++ b/mem0-ts/src/oss/src/vector_stores/mongodb.ts @@ -379,7 +379,7 @@ export class MongoDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); const updateFields: any = {}; if (vector) { @@ -397,9 +397,12 @@ export class MongoDB implements VectorStore { { _id: vectorId as any }, { $set: updateFields }, ); + // An unacknowledged write reports no real matchedCount. + if (result.acknowledged === false) return; if (result.matchedCount === 0) { console.warn(`No document found with ID '${vectorId}' to update.`); } + return result.matchedCount > 0; } catch (error) { console.error("Error updating document:", error); throw error; diff --git a/mem0-ts/src/oss/src/vector_stores/neptune_analytics.ts b/mem0-ts/src/oss/src/vector_stores/neptune_analytics.ts index 79f6e5c9a..f569ed24e 100644 --- a/mem0-ts/src/oss/src/vector_stores/neptune_analytics.ts +++ b/mem0-ts/src/oss/src/vector_stores/neptune_analytics.ts @@ -173,7 +173,7 @@ export class NeptuneAnalyticsVectorStore implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { if (vector.length > 0) { this.assertVectorDimension(vector, "Vector"); } @@ -195,7 +195,7 @@ export class NeptuneAnalyticsVectorStore implements VectorStore { if (hasPayload) { const properties = this.buildStoredPayload(payload); - await this.executeQuery( + const payloadResults = await this.executeQuery( ` MATCH (n:${this.collectionLabelExpr} {\`~id\`: $vectorId}) SET n = $properties @@ -206,6 +206,7 @@ export class NeptuneAnalyticsVectorStore implements VectorStore { properties, }, ); + if (payloadResults.length === 0) return false; } if (hasVector) { @@ -224,6 +225,7 @@ export class NeptuneAnalyticsVectorStore implements VectorStore { }, ); this.assertSuccessfulResults(updateResults, "Update"); + if (updateResults.length === 0) return false; } catch (error) { if (priorResult) { try { @@ -249,6 +251,7 @@ export class NeptuneAnalyticsVectorStore implements VectorStore { throw error; } } + if (hasPayload || hasVector) return true; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/opensearch.ts b/mem0-ts/src/oss/src/vector_stores/opensearch.ts index 10f42e46a..b16717c6f 100644 --- a/mem0-ts/src/oss/src/vector_stores/opensearch.ts +++ b/mem0-ts/src/oss/src/vector_stores/opensearch.ts @@ -367,13 +367,13 @@ export class OpenSearchDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); if (vector) { this.validateVector(vector, 0); } - await this.client.update({ + const request = this.client.update({ index: this.collectionName, id: vectorId, body: { @@ -385,6 +385,15 @@ export class OpenSearchDB implements VectorStore { }, refresh: this.autoRefresh, }); + try { + await request; + } catch (error: any) { + if (error?.statusCode === 404 || error?.meta?.statusCode === 404) { + return false; + } + throw error; + } + return true; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/oracledb.ts b/mem0-ts/src/oss/src/vector_stores/oracledb.ts index 46cf016b8..08c2d12a3 100644 --- a/mem0-ts/src/oss/src/vector_stores/oracledb.ts +++ b/mem0-ts/src/oss/src/vector_stores/oracledb.ts @@ -654,7 +654,7 @@ export class OracleAIVectorSearch implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); const assignments: string[] = []; @@ -670,7 +670,7 @@ export class OracleAIVectorSearch implements VectorStore { } if (assignments.length === 0) return; - await this.withConnection( + const result = await this.withConnection( (connection) => connection.execute( `UPDATE ${this.collectionName} SET ${assignments.join(", ")} WHERE id = :vector_id`, @@ -678,6 +678,8 @@ export class OracleAIVectorSearch implements VectorStore { ), true, ); + const affected = result.rowsAffected; + return typeof affected === "number" ? affected > 0 : undefined; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/pgvector.ts b/mem0-ts/src/oss/src/vector_stores/pgvector.ts index 450ffc9a5..1bd4d9a2c 100644 --- a/mem0-ts/src/oss/src/vector_stores/pgvector.ts +++ b/mem0-ts/src/oss/src/vector_stores/pgvector.ts @@ -1,8 +1,11 @@ import type { Client as ClientType, ClientConfig } from "pg"; -import pkg from "pg"; -const { Client, escapeIdentifier } = pkg; import { VectorStore } from "./base"; import { SearchFilters, VectorStoreConfig, VectorStoreResult } from "../types"; +import { loadPeer } from "../utils/load_peer"; + +function escapeIdentifier(name: string): string { + return `"${name.replace(/"/g, '""')}"`; +} const SAFE_IDENTIFIER_RE = /^[a-zA-Z_][a-zA-Z0-9_]{0,127}$/; @@ -212,7 +215,7 @@ function buildClientConfig( } export class PGVector implements VectorStore { - private client: ClientType; + private client!: ClientType; private collectionName: string; private useDiskann: boolean; private useHnsw: boolean; @@ -234,13 +237,6 @@ export class PGVector implements VectorStore { ? "" : validateIdentifier(config.dbname || "vector_store", "dbname"); this.config = config; - - this.client = new Client( - buildClientConfig( - config, - this.useDirectConnection ? undefined : "postgres", - ), - ); this.initialize().catch(console.error); } @@ -257,6 +253,18 @@ export class PGVector implements VectorStore { private async _doInitialize(): Promise { try { + const pg = await loadPeer( + "pg", + "PGVector vector store", + () => import("pg"), + ); + const { Client } = pg.default ?? pg; + this.client = new Client( + buildClientConfig( + this.config, + this.useDirectConnection ? undefined : "postgres", + ), + ); await this.client.connect(); if (!this.useDirectConnection) { @@ -345,6 +353,7 @@ export class PGVector implements VectorStore { ids: string[], payloads: Record[], ): Promise { + await this.initialize(); const values = vectors.map((vector, i) => ({ id: ids[i], vector: `[${vector.join(",")}]`, @@ -368,6 +377,7 @@ export class PGVector implements VectorStore { topK: number = 5, filters?: SearchFilters, ): Promise { + await this.initialize(); try { const { conditions, @@ -406,6 +416,7 @@ export class PGVector implements VectorStore { topK: number = 5, filters?: SearchFilters, ): Promise { + await this.initialize(); const queryVector = `[${query.join(",")}]`; const { conditions, @@ -435,6 +446,7 @@ export class PGVector implements VectorStore { } async get(vectorId: string): Promise { + await this.initialize(); const result = await this.client.query( `SELECT id, payload FROM ${this.col()} WHERE id = $1`, [vectorId], @@ -452,9 +464,10 @@ export class PGVector implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { + await this.initialize(); const vectorStr = `[${vector.join(",")}]`; - await this.client.query( + const result = await this.client.query( ` UPDATE ${this.col()} SET vector = $1::vector, payload = $2::jsonb @@ -462,15 +475,18 @@ export class PGVector implements VectorStore { `, [vectorStr, payload, vectorId], ); + return (result.rowCount ?? 0) > 0; } async delete(vectorId: string): Promise { + await this.initialize(); await this.client.query(`DELETE FROM ${this.col()} WHERE id = $1`, [ vectorId, ]); } async deleteCol(): Promise { + await this.initialize(); await this.client.query(`DROP TABLE IF EXISTS ${this.col()}`); } @@ -487,6 +503,7 @@ export class PGVector implements VectorStore { filters?: SearchFilters, topK: number = 100, ): Promise<[VectorStoreResult[], number]> { + await this.initialize(); const { conditions, values: filterValues, @@ -525,10 +542,11 @@ export class PGVector implements VectorStore { } async close(): Promise { - await this.client.end(); + await this.client?.end(); } async getUserId(): Promise { + await this.initialize(); const result = await this.client.query( "SELECT user_id FROM memory_migrations LIMIT 1", ); @@ -549,6 +567,7 @@ export class PGVector implements VectorStore { } async setUserId(userId: string): Promise { + await this.initialize(); await this.client.query("DELETE FROM memory_migrations"); await this.client.query( "INSERT INTO memory_migrations (user_id) VALUES ($1)", diff --git a/mem0-ts/src/oss/src/vector_stores/pinecone.ts b/mem0-ts/src/oss/src/vector_stores/pinecone.ts index 3d8f4e851..ed6f9eb96 100644 --- a/mem0-ts/src/oss/src/vector_stores/pinecone.ts +++ b/mem0-ts/src/oss/src/vector_stores/pinecone.ts @@ -305,8 +305,11 @@ export class PineconeDB implements VectorStore { payload: Record, ): Promise { await this.initialize(); - await this.namespacedIndex().upsert({ - records: [{ id: vectorId, values: vector, metadata: payload }], + // update() never creates a missing id but does not report whether it existed. + await this.namespacedIndex().update({ + id: vectorId, + ...(vector ? { values: vector } : {}), + metadata: payload, }); } diff --git a/mem0-ts/src/oss/src/vector_stores/qdrant.ts b/mem0-ts/src/oss/src/vector_stores/qdrant.ts index e84a138f1..99f72b20c 100644 --- a/mem0-ts/src/oss/src/vector_stores/qdrant.ts +++ b/mem0-ts/src/oss/src/vector_stores/qdrant.ts @@ -319,9 +319,13 @@ export class Qdrant implements VectorStore { // named-vector and BM25-inference shapes are not typed. private async upsertPoints( points: { id: string | number; vector: any; payload?: any }[], + options: { update_mode?: "update_only" } = {}, ): Promise { try { - await this.client.upsert(this.collectionName, { points: points as any }); + await this.client.upsert(this.collectionName, { + points: points as any, + ...options, + }); } catch (error) { if (!this._hasBm25Slot) { throw error; @@ -338,6 +342,7 @@ export class Qdrant implements VectorStore { })); await this.client.upsert(this.collectionName, { points: denseOnly as any, + ...options, }); } } @@ -430,7 +435,7 @@ export class Qdrant implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); const point = { id: vectorId, @@ -439,7 +444,15 @@ export class Qdrant implements VectorStore { payload, }; - await this.upsertPoints([point]); + // One write keeps the vector and payload of concurrent updates together. + // update_only (Qdrant 1.17+) never creates a point; older servers upsert as before. + await this.upsertPoints([point], { update_mode: "update_only" }); + const found = await this.client.retrieve(this.collectionName, { + ids: [vectorId], + with_payload: false, + with_vector: false, + }); + return found.length > 0; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/redis.ts b/mem0-ts/src/oss/src/vector_stores/redis.ts index ecb326ac2..be016bada 100644 --- a/mem0-ts/src/oss/src/vector_stores/redis.ts +++ b/mem0-ts/src/oss/src/vector_stores/redis.ts @@ -122,6 +122,11 @@ const EXCLUDED_KEYS = new Set([ "updated_at", ]); +// HSET alone creates a missing hash; the script checks and writes atomically. +const HSET_IF_EXISTS = + "if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end " + + "redis.call('HSET', KEYS[1], unpack(ARGV)) return 1"; + // Utility function to convert object keys to snake_case function toSnakeCase(obj: Record): Record { if (typeof obj !== "object" || obj === null) return obj; @@ -574,7 +579,7 @@ export class RedisDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); const snakePayload = toSnakeCase(payload); const createdAt = snakePayload.created_at @@ -589,8 +594,8 @@ export class RedisDB implements VectorStore { memory: snakePayload.data ?? "", created_at: createdAt, updated_at: updatedAt, - embedding: Buffer.from(new Float32Array(vector).buffer), }; + if (vector) entry.embedding = Buffer.from(new Float32Array(vector).buffer); // Add optional fields ["agent_id", "run_id", "user_id"].forEach((field) => { @@ -606,8 +611,40 @@ export class RedisDB implements VectorStore { ), ); + const key = `${this.indexPrefix}:${vectorId}`; try { - await this.client.hSet(`${this.indexPrefix}:${vectorId}`, entry); + const updated = await this.client + .sendCommand([ + "EVAL", + HSET_IF_EXISTS, + "1", + key, + ...Object.entries(entry).flatMap(([field, value]) => [ + field, + typeof value === "number" ? String(value) : value, + ]), + ]) + .catch(async (error: Error) => { + // ACL users without +@scripting: WATCH/MULTI is also atomic, but needs its own connection. + if (!String(error?.message).includes("NOPERM")) throw error; + const { WatchError } = await import("redis"); + return this.client.executeIsolated(async (conn) => { + for (;;) { + await conn.watch(key); + if (!(await conn.exists(key))) { + await conn.unwatch(); + return 0; + } + try { + await conn.multi().hSet(key, entry).exec(); + return 1; + } catch (e) { + if (!(e instanceof WatchError)) throw e; + } + } + }); + }); + return updated === 1; } catch (error) { console.error("Error during vector update:", error); throw error; diff --git a/mem0-ts/src/oss/src/vector_stores/turbopuffer.ts b/mem0-ts/src/oss/src/vector_stores/turbopuffer.ts index 5134aa80a..30e032630 100644 --- a/mem0-ts/src/oss/src/vector_stores/turbopuffer.ts +++ b/mem0-ts/src/oss/src/vector_stores/turbopuffer.ts @@ -247,23 +247,54 @@ export class TurbopufferDB implements VectorStore { } } + // Maps mem0's universal filter operators to Turbopuffer's filter tokens. + private static readonly OPERATOR_MAP: Record = { + eq: "Eq", + ne: "NotEq", + gt: "Gt", + gte: "Gte", + lt: "Lt", + lte: "Lte", + in: "In", + nin: "NotIn", + }; + private convertFilters(filters?: SearchFilters): any { if (!filters || Object.keys(filters).length === 0) return null; const conditions: any[] = []; for (const [key, value] of Object.entries(filters)) { - if ( - typeof value === "object" && - value !== null && - !Array.isArray(value) - ) { - if ("gte" in value) conditions.push([key, "Gte", value.gte]); - if ("lte" in value) conditions.push([key, "Lte", value.lte]); - if ("gt" in value) conditions.push([key, "Gt", value.gt]); - if ("lt" in value) conditions.push([key, "Lt", value.lt]); - } else { - conditions.push([key, "Eq", value]); + // "*" is a match-any wildcard: it must not constrain the query. The old + // code turned it into `[key, "Eq", "*"]`, matching nothing. + if (value === "*") { + continue; } + + // Array shorthand: { key: [a, b] } means "in". + if (Array.isArray(value)) { + conditions.push([key, "In", value]); + continue; + } + + if (typeof value === "object" && value !== null) { + // Operator dict: every operator present must hold. Previously only + // `gte` and `lte` were read, so `gt`/`lt`/`ne`/`eq`/`in`/`nin` were + // silently dropped and the filter returned unfiltered results. + for (const [op, operand] of Object.entries(value)) { + const token = TurbopufferDB.OPERATOR_MAP[op]; + if (!token) { + throw new Error( + `Unsupported Turbopuffer filter operator '${op}' for field '${key}'. ` + + `Supported operators: ${Object.keys(TurbopufferDB.OPERATOR_MAP).join(", ")}.`, + ); + } + conditions.push([key, token, operand]); + } + continue; + } + + // Scalar shorthand: equality. + conditions.push([key, "Eq", value]); } if (conditions.length === 0) return null; @@ -274,7 +305,18 @@ export class TurbopufferDB implements VectorStore { private parseRows(rows: any[]): VectorStoreResult[] { return rows.map((row) => { const { id, $dist, vector, ...rest } = row; - const score = $dist != null ? 1 - $dist : undefined; + let score: number | undefined; + if ($dist == null) { + score = undefined; + } else if (this.distanceMetric === "euclidean_squared") { + // euclidean_squared $dist is an unbounded squared distance, so 1 - $dist + // goes negative for any $dist > 1 and inverts ranking. Convert it to a + // bounded higher-is-better score, mirroring the milvus/baidu stores. + score = 1 / (1 + $dist); + } else { + // Cosine distance is in [0, 2]; 1 - $dist stays a meaningful similarity. + score = 1 - $dist; + } return { id: String(id), payload: rest, score }; }); } diff --git a/mem0-ts/src/oss/src/vector_stores/upstash_vector.ts b/mem0-ts/src/oss/src/vector_stores/upstash_vector.ts index 2fa539dd6..bd627f409 100644 --- a/mem0-ts/src/oss/src/vector_stores/upstash_vector.ts +++ b/mem0-ts/src/oss/src/vector_stores/upstash_vector.ts @@ -141,19 +141,19 @@ export class UpstashVector implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); - // Upstash's `update` can't set the vector and metadata in one call (its - // payload is a discriminated union of vector | data | metadata), so a - // single `upsert` replaces both atomically, the same way insert() writes. - await this.client.upsert( + const { updated } = await this.client.update( { id: vectorId, - vector, + ...(vector ? { vector } : {}), metadata: payload, + metadataUpdateMode: "OVERWRITE", }, { namespace: this.collectionName }, ); + // 0 is not documented as "missing" and can come back for an existing id. + return typeof updated === "number" && updated > 0 ? true : undefined; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/valkey.ts b/mem0-ts/src/oss/src/vector_stores/valkey.ts index cd4f85920..61c557551 100644 --- a/mem0-ts/src/oss/src/vector_stores/valkey.ts +++ b/mem0-ts/src/oss/src/vector_stores/valkey.ts @@ -14,6 +14,16 @@ interface ValkeyClient { set: (key: string, value: string) => Promise<"OK">; quit: () => Promise<"OK">; on: (event: string, listener: (...args: any[]) => void) => void; + duplicate: () => ValkeyClient; + watch: (key: string) => Promise<"OK">; + unwatch: () => Promise<"OK">; + multi: () => { + hset: ( + key: string, + data: Record, + ) => { exec: () => Promise<[Error | null, unknown][] | null> }; + }; + disconnect: () => void; } /** @@ -36,6 +46,11 @@ const EXCLUDED_KEYS = new Set([ "updated_at", ]); +// HSET alone creates a missing hash; the script checks and writes atomically. +const HSET_IF_EXISTS = + "if redis.call('EXISTS', KEYS[1]) == 0 then return 0 end " + + "redis.call('HSET', KEYS[1], unpack(ARGV)) return 1"; + function toSnakeCase(obj: Record): Record { if (typeof obj !== "object" || obj === null) return obj; return Object.fromEntries( @@ -503,7 +518,7 @@ export class ValkeyDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { const snakePayload = toSnakeCase(payload); const key = `${this.indexPrefix}:${vectorId}`; @@ -518,13 +533,15 @@ export class ValkeyDB implements VectorStore { created_at: String( Math.floor(new Date(snakePayload.created_at).getTime() / 1000), ), - embedding: Buffer.from(new Float32Array(vector).buffer), metadata: JSON.stringify( Object.fromEntries( Object.entries(snakePayload).filter(([k]) => !EXCLUDED_KEYS.has(k)), ), ), }; + if (vector) { + hashData.embedding = Buffer.from(new Float32Array(vector).buffer); + } if (snakePayload.updated_at) { hashData.updated_at = String( @@ -538,7 +555,31 @@ export class ValkeyDB implements VectorStore { } } - await this.client.hset(key, hashData); + const updated = await this.client + .call("EVAL", HSET_IF_EXISTS, 1, key, ...Object.entries(hashData).flat()) + .catch(async (error: Error) => { + // ACL users without +@scripting: WATCH/MULTI is also atomic, but needs its own connection. + if (!String(error?.message).includes("NOPERM")) throw error; + const conn = this.client.duplicate(); + try { + for (;;) { + await conn.watch(key); + if (!(await conn.exists(key))) { + await conn.unwatch(); + return 0; + } + // exec() resolves to null when a watched key changed: retry. + const replies = await conn.multi().hset(key, hashData).exec(); + if (!replies) continue; + const failed = replies.find(([err]) => err); + if (failed) throw failed[0]; + return 1; + } + } finally { + conn.disconnect(); + } + }); + return updated === 1; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/src/vector_stores/weaviate.ts b/mem0-ts/src/oss/src/vector_stores/weaviate.ts index 3c7d51246..ff0a6f95c 100644 --- a/mem0-ts/src/oss/src/vector_stores/weaviate.ts +++ b/mem0-ts/src/oss/src/vector_stores/weaviate.ts @@ -189,13 +189,20 @@ export class WeaviateDB implements VectorStore { vectorId: string, vector: number[], payload: Record, - ): Promise { + ): Promise { await this.initialize(); - await this._col.data.update({ + const request = this._col.data.update({ id: vectorId, properties: payload, vectors: vector, }); + try { + await request; + } catch (error: any) { + if (error?.code === 404) return false; + throw error; + } + return true; } async delete(vectorId: string): Promise { diff --git a/mem0-ts/src/oss/tests/config-manager.test.ts b/mem0-ts/src/oss/tests/config-manager.test.ts index 7c1856ad8..b3304509a 100644 --- a/mem0-ts/src/oss/tests/config-manager.test.ts +++ b/mem0-ts/src/oss/tests/config-manager.test.ts @@ -1,5 +1,6 @@ /// import { ConfigManager } from "../src/config/manager"; +import { LLMFactory } from "../src/utils/factory"; describe("ConfigManager", () => { describe("mergeConfig - dimension handling", () => { @@ -141,7 +142,7 @@ describe("ConfigManager", () => { expect(config.llm.config.url).toBe("http://my-ollama-host:11434"); }); - it("should use default baseURL when no url or baseURL provided", () => { + it("should not fall back to the OpenAI default baseURL for a non-OpenAI provider", () => { const config = ConfigManager.mergeConfig({ embedder: baseEmbedder, vectorStore: baseVectorStore, @@ -152,7 +153,9 @@ describe("ConfigManager", () => { }); expect(config.llm.config.url).toBeUndefined(); - expect(config.llm.config.baseURL).toBe("https://api.openai.com/v1"); + // OllamaLLM defaults to http://localhost:11434. The OpenAI default used to be + // injected here, which pointed OllamaLLM at OpenAI instead. + expect(config.llm.config.baseURL).toBeUndefined(); }); it("normalizes vllm_base_url to baseURL for vLLM", () => { @@ -367,14 +370,63 @@ describe("ConfigManager", () => { expect(cfg.llm.config.baseURL).toBe("http://camel:1234/v1"); }); - it("falls back to default baseURL when neither is provided for LLM", () => { + it("does not inject the OpenAI baseURL default for a non-OpenAI provider", () => { const cfg = ConfigManager.mergeConfig({ embedder: baseEmbedder, vectorStore: { provider: "memory", config: {} }, llm: { provider: "lmstudio", config: { model: "test-model" } }, }); - expect(cfg.llm.config.baseURL).toBe("https://api.openai.com/v1"); + // The provider supplies its own baseURL (http://localhost:1234/v1) when none is + // given. Injecting OpenAI's here shadowed it and sent lmstudio traffic to OpenAI. + expect(cfg.llm.config.baseURL).toBeUndefined(); + }); + + it("does not inject the OpenAI model default for a non-OpenAI provider", () => { + const cfg = ConfigManager.mergeConfig({ + embedder: baseEmbedder, + vectorStore: { provider: "memory", config: {} }, + llm: { provider: "deepseek", config: { apiKey: "k" } }, + }); + + // DeepSeekLLM falls back to "deepseek-chat" when model is unset. Injecting + // "gpt-5-mini" here made that fallback unreachable. + expect(cfg.llm.config.model).toBeUndefined(); + }); + + it("still applies the OpenAI defaults for the OpenAI providers", () => { + for (const provider of ["openai", "openai_structured"]) { + const cfg = ConfigManager.mergeConfig({ + embedder: baseEmbedder, + vectorStore: { provider: "memory", config: {} }, + llm: { provider, config: { apiKey: "k" } }, + }); + + expect(cfg.llm.config.baseURL).toBe("https://api.openai.com/v1"); + expect(cfg.llm.config.model).toBe("gpt-5-mini"); + } + }); + + it("lets each non-OpenAI provider resolve its own endpoint", () => { + const cases: Array<[string, string]> = [ + ["deepseek", "https://api.deepseek.com"], + ["xai", "https://api.x.ai/v1"], + ["lmstudio", "http://localhost:1234/v1"], + ]; + + for (const [provider, expected] of cases) { + const cfg = ConfigManager.mergeConfig({ + embedder: baseEmbedder, + vectorStore: { provider: "memory", config: {} }, + llm: { provider, config: { apiKey: "k" } }, + }); + + const built = LLMFactory.create(provider, cfg.llm.config); + // The client the provider actually built must not point at OpenAI. + const baseURL = + (built as any).openai?.baseURL ?? (built as any).baseURL; + expect(String(baseURL)).toBe(expected); + } }); }); diff --git a/mem0-ts/src/oss/tests/elasticsearch.unit.test.ts b/mem0-ts/src/oss/tests/elasticsearch.unit.test.ts index 2793bf6a5..dbffc4c33 100644 --- a/mem0-ts/src/oss/tests/elasticsearch.unit.test.ts +++ b/mem0-ts/src/oss/tests/elasticsearch.unit.test.ts @@ -365,7 +365,9 @@ describe("ElasticsearchDB", () => { host: "localhost", }); - await store.update("id-1", [1, 2, 3, 4], { key: "val" }); + expect(await store.update("id-1", [1, 2, 3, 4], { key: "val" })).toBe( + true, + ); expect(mockUpdate).toHaveBeenCalledWith({ index: "mem0", @@ -373,6 +375,35 @@ describe("ElasticsearchDB", () => { doc: { vector: [1, 2, 3, 4], metadata: { key: "val" } }, }); }); + + it("returns false and inserts nothing when the document is missing", async () => { + mockUpdate.mockRejectedValue({ meta: { statusCode: 404 } }); + const store = new ElasticsearchDB({ + collectionName: "mem0", + embeddingModelDims: 4, + host: "localhost", + }); + + expect(await store.update("missing", [1, 2, 3, 4], { k: "v" })).toBe( + false, + ); + expect(mockUpdate.mock.calls[0][0]).not.toHaveProperty("doc_as_upsert"); + expect(mockUpdate.mock.calls[0][0]).not.toHaveProperty("upsert"); + expect(mockIndex_).not.toHaveBeenCalled(); + }); + + it("sends only metadata on a payload-only update", async () => { + const store = new ElasticsearchDB({ + collectionName: "mem0", + embeddingModelDims: 4, + host: "localhost", + }); + + expect(await store.update("id-1", null, { key: "new" })).toBe(true); + expect(mockUpdate.mock.calls[0][0].doc).toEqual({ + metadata: { key: "new" }, + }); + }); }); describe("delete", () => { diff --git a/mem0-ts/src/oss/tests/memory.add-filters-isolation.test.ts b/mem0-ts/src/oss/tests/memory.add-filters-isolation.test.ts new file mode 100644 index 000000000..a23926e41 --- /dev/null +++ b/mem0-ts/src/oss/tests/memory.add-filters-isolation.test.ts @@ -0,0 +1,115 @@ +/// +/** + * add() writes the resolved scope (user_id / agent_id / run_id) into its + * filters object. If that object is the caller's, the scope survives the call + * and leaks into the next add() that reuses it, which also defeats the + * "one of userId, agentId or runId is required" guard. + * + * search() and getAll() already build a fresh object from config.filters. + */ +jest.mock("../src/utils/telemetry", () => ({ + captureClientEvent: jest.fn().mockResolvedValue(undefined), + isTelemetryEnabled: jest.fn(() => false), +})); + +import { Memory } from "../src/memory"; + +const DIM = 1536; +let seq = 0; + +function createMemory(): Memory { + const m = new Memory({ + disableHistory: true, + vectorStore: { + provider: "memory", + config: { + collectionName: `test-add-filters-${seq++}`, + dimension: DIM, + dbPath: ":memory:", + }, + }, + historyDbPath: ":memory:", + embedder: { provider: "openai", config: { apiKey: "test-key" } }, + llm: { provider: "openai", config: { apiKey: "test-key" } }, + } as any); + + // infer:false is enough to exercise the scope handling, so the LLM is never + // called; the embedder just has to return a well-formed vector. + (m as any).embedder = { + embed: async () => new Array(DIM).fill(0.1), + embedBatch: async (texts: string[]) => + texts.map(() => new Array(DIM).fill(0.1)), + }; + return m; +} + +describe("add() does not mutate the caller's filters object", () => { + it("leaves the caller's object untouched", async () => { + const memory = createMemory(); + const filters: Record = {}; + + await memory.add([{ role: "user", content: "alice note" }], { + userId: "alice", + infer: false, + filters, + }); + + expect(filters).toEqual({}); + }); + + it("still throws when a reused object is the only source of scope", async () => { + const memory = createMemory(); + const filters: Record = {}; + + await memory.add([{ role: "user", content: "alice note" }], { + userId: "alice", + infer: false, + filters, + }); + + // No userId/agentId/runId on this call, so the required-scope guard must + // fire rather than reading a value left behind by the previous call. + await expect( + memory.add([{ role: "user", content: "bob note" }], { + infer: false, + filters, + }), + ).rejects.toThrow( + "One of the filters: userId, agentId or runId is required!", + ); + }); + + it("does not store one user's memory under another user's scope", async () => { + const memory = createMemory(); + const filters: Record = {}; + + await memory.add([{ role: "user", content: "alice note" }], { + userId: "alice", + infer: false, + filters, + }); + // A second caller reuses the object and supplies no scope of its own. This + // must not be silently attributed to alice. + await memory + .add([{ role: "user", content: "bob note" }], { + infer: false, + filters, + }) + .catch(() => undefined); + + const alice = await memory.getAll({ filters: { user_id: "alice" } }); + expect(alice.results.map((r) => r.memory)).toEqual(["alice note"]); + }); + + it("keeps scope keys the caller passed in", async () => { + const memory = createMemory(); + + await memory.add([{ role: "user", content: "scoped note" }], { + infer: false, + filters: { user_id: "carol" }, + }); + + const carol = await memory.getAll({ filters: { user_id: "carol" } }); + expect(carol.results.map((r) => r.memory)).toEqual(["scoped note"]); + }); +}); diff --git a/mem0-ts/src/oss/tests/memory.crud.test.ts b/mem0-ts/src/oss/tests/memory.crud.test.ts index 6e45eaa01..35f3a54f2 100644 --- a/mem0-ts/src/oss/tests/memory.crud.test.ts +++ b/mem0-ts/src/oss/tests/memory.crud.test.ts @@ -165,6 +165,30 @@ describe("Memory - update()", () => { expect(result.message).toBe("Memory updated successfully!"); }); + test("a delete that lands between get and update is not undone", async () => { + const addResult: SearchResult = await memory.add("Race me", { + userId, + infer: false, + }); + const id = addResult.results[0].id; + const store = (memory as any).vectorStore; + const realUpdate = store.update.bind(store); + const updateSpy = jest + .spyOn(store, "update") + .mockImplementationOnce(async (...args: any[]) => { + await memory.delete(id); + return realUpdate(...args); + }); + + await expect(memory.update(id, { text: "Resurrected" })).rejects.toThrow( + `Memory with ID ${id} not found`, + ); + updateSpy.mockRestore(); + expect(await memory.get(id)).toBeNull(); + const actions = (await memory.history(id)).map((h) => h.action); + expect(actions).toEqual(["DELETE", "ADD"]); + }); + test("persists the updated text", async () => { const addResult: SearchResult = await memory.add("Before update", { userId, diff --git a/mem0-ts/src/oss/tests/missing-optional-peers.test.ts b/mem0-ts/src/oss/tests/missing-optional-peers.test.ts new file mode 100644 index 000000000..910849c55 --- /dev/null +++ b/mem0-ts/src/oss/tests/missing-optional-peers.test.ts @@ -0,0 +1,39 @@ +jest.mock("pg", () => { + throw new Error("Cannot find module 'pg'"); +}); + +jest.mock("natural", () => { + throw new Error("Cannot find module 'natural'"); +}); + +describe("mem0ai/oss without pg or natural installed", () => { + beforeEach(() => { + jest.spyOn(console, "error").mockImplementation(() => {}); + }); + + afterEach(() => { + jest.restoreAllMocks(); + }); + + test("mem0ai/oss loads", async () => { + await expect(import("../src")).resolves.toHaveProperty("Memory"); + }); + + test("PGVector explains how to install pg", async () => { + const { PGVector } = await import("../src/vector_stores/pgvector"); + const store = new PGVector({ + connectionString: "postgresql://localhost:5432/db", + embeddingModelDims: 3, + } as any); + + await expect(store.initialize()).rejects.toThrow( + "The 'pg' package is required to use the PGVector vector store. Install it with: npm install pg", + ); + }); + + test("BM25 lemmatization falls back to the built-in stemmer", async () => { + const { lemmatizeForBm25 } = await import("../src/utils/lemmatization"); + + expect(lemmatizeForBm25("The dogs were running")).toBe("dog runn running"); + }); +}); diff --git a/mem0-ts/src/oss/tests/opensearch.unit.test.ts b/mem0-ts/src/oss/tests/opensearch.unit.test.ts index e53a1dbc0..145f5cc8b 100644 --- a/mem0-ts/src/oss/tests/opensearch.unit.test.ts +++ b/mem0-ts/src/oss/tests/opensearch.unit.test.ts @@ -154,6 +154,46 @@ describe("OpenSearchDB", () => { await expect(store.get("missing")).resolves.toBeNull(); }); + it("update returns false and inserts nothing when the document is missing (404)", async () => { + const client = createClient({ + update: jest.fn().mockRejectedValue({ meta: { statusCode: 404 } }), + }); + const store = await createStore(client); + + await expect( + store.update("missing", [0.1, 0.2, 0.3], { data: "x" }), + ).resolves.toBe(false); + expect(client.update.mock.calls[0][0].body).not.toHaveProperty( + "doc_as_upsert", + ); + expect(client.index).not.toHaveBeenCalled(); + expect(client.bulk).not.toHaveBeenCalled(); + }); + + it("update returns true and sends the same partial doc for an existing document", async () => { + const client = createClient(); + const store = await createStore(client); + + await expect( + store.update("mem-1", [0.1, 0.2, 0.3], { data: "new" }), + ).resolves.toBe(true); + expect(client.update.mock.calls[0][0].body).toEqual({ + doc: { + vector_field: [0.1, 0.2, 0.3], + payload: { data: "new" }, + id: "mem-1", + }, + }); + + await expect( + store.update("mem-1", null as any, { data: "only" }), + ).resolves.toBe(true); + expect(client.update.mock.calls[1][0].body.doc).toEqual({ + payload: { data: "only" }, + id: "mem-1", + }); + }); + it("keywordSearch queries lemmatized payload fields", async () => { const client = createClient(); const store = await createStore(client); diff --git a/mem0-ts/src/oss/tests/oracledb.unit.test.ts b/mem0-ts/src/oss/tests/oracledb.unit.test.ts index 3afdbac6e..90e8fee5b 100644 --- a/mem0-ts/src/oss/tests/oracledb.unit.test.ts +++ b/mem0-ts/src/oss/tests/oracledb.unit.test.ts @@ -411,6 +411,44 @@ describe("OracleAIVectorSearch SQL", () => { expect(results).toEqual([]); expect(count).toBe(0); }); + + function storeWithRowsAffected(calls: Call[], rowsAffected: number) { + const connection: any = fakeConnection(calls, []); + const execute = connection.execute; + connection.execute = async (sql: string, binds: any = {}) => ({ + ...(await execute(sql, binds)), + rowsAffected, + }); + return makeStore(calls, [], { client: connection }); + } + + it("returns false from update and inserts nothing when the id is missing", async () => { + const calls: Call[] = []; + const store = storeWithRowsAffected(calls, 0); + expect(await store.update("missing", [1, 2, 3], { a: 1 })).toBe(false); + expect(calls.some((c) => /^(INSERT|MERGE)/.test(c.sql))).toBe(false); + }); + + it("returns undefined from update when the driver gives no rowsAffected", async () => { + const store = storeWithRowsAffected([], undefined as any); + expect(await store.update("id-1", [1, 2, 3], { a: 1 })).toBeUndefined(); + }); + + it("returns true from update and binds the same values for an existing id", async () => { + const calls: Call[] = []; + const store = storeWithRowsAffected(calls, 1); + expect(await store.update("id-1", [1, 2, 3], { a: 1 })).toBe(true); + expect(await store.update("id-1", null as any, { b: 2 })).toBe(true); + const updates = calls.filter((c) => c.sql.startsWith("UPDATE")); + expect(updates[0].sql).toBe( + 'UPDATE "mem0" SET vector = :vector, payload = :payload WHERE id = :vector_id', + ); + expect(updates[0].binds.vector.val).toEqual(new Float32Array([1, 2, 3])); + expect(updates[0].binds.payload.val).toEqual({ a: 1 }); + expect(updates[1].sql).toBe( + 'UPDATE "mem0" SET payload = :payload WHERE id = :vector_id', + ); + }); }); describe("OracleAIVectorSearch initialization failure", () => { diff --git a/mem0-ts/src/oss/tests/pgvector.unit.test.ts b/mem0-ts/src/oss/tests/pgvector.unit.test.ts index f6f75701f..eb3035aee 100644 --- a/mem0-ts/src/oss/tests/pgvector.unit.test.ts +++ b/mem0-ts/src/oss/tests/pgvector.unit.test.ts @@ -241,4 +241,29 @@ describe("PGVector", () => { ["[1,0,0]", 4], ); }); + + test("update returns rowCount > 0 and only ever issues an UPDATE", async () => { + const store = new PGVector({ + collectionName: "memories", + connectionString: "postgresql://postgres:postgres@localhost:5432/db", + embeddingModelDims: 3, + dimension: 3, + } as any); + await store.initialize(); + const client = require("pg").__mock.clients[0]; + client.query.mockClear(); + + client.query.mockResolvedValueOnce({ rows: [], rowCount: 0 }); + expect(await store.update("missing", [1, 0, 0], { data: "x" })).toBe(false); + client.query.mockResolvedValueOnce({ rows: [], rowCount: 1 }); + expect(await store.update("a", [0, 1, 0], { data: "y" })).toBe(true); + + const queries = getClientQueries(client); + expect(queries).toHaveLength(2); + expect(queries.every((sql) => sql.trim().startsWith("UPDATE"))).toBe(true); + expect(client.query).toHaveBeenLastCalledWith( + expect.stringContaining("SET vector = $1::vector, payload = $2::jsonb"), + ["[0,1,0]", { data: "y" }, "a"], + ); + }); }); diff --git a/mem0-ts/src/oss/tests/qdrant-keyword-search.test.ts b/mem0-ts/src/oss/tests/qdrant-keyword-search.test.ts index 2746238cc..a8d1ccd31 100644 --- a/mem0-ts/src/oss/tests/qdrant-keyword-search.test.ts +++ b/mem0-ts/src/oss/tests/qdrant-keyword-search.test.ts @@ -283,6 +283,27 @@ describe("Qdrant BM25 keyword search โ€” insert / update", () => { expect(point.vector.bm25).toBeUndefined(); }); + it("update writes vector and payload in one update_only upsert", async () => { + const { store, client } = await freshStore(); + client.retrieve.mockResolvedValueOnce([{ id: "mem-1" }]); + const payload = { data: "new", user_id: "u" }; + + await expect(store.update("mem-1", [0.4], payload)).resolves.toBe(true); + expect(client.upsert).toHaveBeenCalledTimes(1); + const body = client.upsert.mock.calls[0][1]; + expect(body.update_mode).toBe("update_only"); + expect(body.points[0]).toMatchObject({ id: "mem-1", payload }); + }); + + it("update returns false when the point is gone after the write", async () => { + const { store, client } = await freshStore(); + client.retrieve.mockResolvedValueOnce([]); + + await expect(store.update("gone", [0.1], { data: "x" })).resolves.toBe( + false, + ); + }); + it("inserts a plain dense vector (no named/sparse) on legacy collections", async () => { const client = buildMockClient( { createCollection: jest.fn().mockRejectedValue({ status: 409 }) }, @@ -485,6 +506,7 @@ describe("Qdrant BM25 keyword search โ€” reactive downgrade on upsert failure", expect(upsert).toHaveBeenCalledTimes(2); const retryPoint = upsert.mock.calls[1][1].points[0]; expect(retryPoint.vector).toEqual([0.4, 0.5]); + expect(upsert.mock.calls[1][1].update_mode).toBe("update_only"); expect(warnSpy).toHaveBeenCalledTimes(1); expect(await store.keywordSearch("updat")).toBeNull(); }); diff --git a/mem0-ts/src/oss/tests/redis.unit.test.ts b/mem0-ts/src/oss/tests/redis.unit.test.ts index 03343b501..c3a458860 100644 --- a/mem0-ts/src/oss/tests/redis.unit.test.ts +++ b/mem0-ts/src/oss/tests/redis.unit.test.ts @@ -1,6 +1,7 @@ import { RedisDB } from "../src/vector_stores/redis"; jest.mock("redis", () => ({ + WatchError: class WatchError extends Error {}, createClient: jest.fn(() => ({ connect: jest.fn(), on: jest.fn(), @@ -12,6 +13,8 @@ jest.mock("redis", () => ({ _list: jest.fn().mockResolvedValue([]), }, hSet: jest.fn(), + sendCommand: jest.fn().mockResolvedValue(1), + executeIsolated: jest.fn(), hGetAll: jest.fn(), del: jest.fn(), exists: jest.fn(), @@ -19,6 +22,13 @@ jest.mock("redis", () => ({ })), })); +// update() sends EVAL