From 73e7b8763a81f3fa43c6b79312ad049f3106498d Mon Sep 17 00:00:00 2001 From: Kartik Date: Tue, 8 Sep 2026 23:32:25 +0530 Subject: [PATCH 01/61] refactor(integrations): shared agent plugin runtimes and native adapters (#7203) --- .agents/plugins/marketplace.json | 2 +- .claude-plugin/marketplace.json | 2 +- .codex-plugin/marketplace.json | 2 +- .cursor-plugin/marketplace.json | 6 +- .github/AGENTS.md | 6 +- .../workflows/agent-plugins-python-checks.yml | 97 + .../agent-plugins-typescript-checks.yml | 42 + .github/workflows/ci-gate.yml | 57 +- .../workflows/claude-code-plugin-checks.yml | 46 - .github/workflows/deepseek-plugin-checks.yml | 7 +- .github/workflows/mem0-plugin-checks.yml | 58 - .github/workflows/openclaw-checks.yml | 7 +- .github/workflows/opencode-plugin-cd.yml | 2 +- .github/workflows/opencode-plugin-checks.yml | 11 +- .github/workflows/pi-agent-plugin-checks.yml | 9 +- .gitignore | 4 + .kimi-plugin/marketplace.json | 6 +- AGENTS.md | 2 +- docs/changelog/sdk.mdx | 201 ++ docs/docs.json | 1 + docs/integrations/antigravity.mdx | 72 +- docs/integrations/claude-code.mdx | 16 +- docs/integrations/codex.mdx | 58 +- docs/integrations/cursor.mdx | 64 +- docs/integrations/deepseek-plugin.mdx | 62 +- docs/integrations/kimi.mdx | 109 + docs/integrations/openclaw.mdx | 21 +- docs/integrations/opencode.mdx | 32 +- docs/integrations/pi-agent.mdx | 52 +- docs/introduction.mdx | 2 +- docs/llms.txt | 26 +- integrations/AGENTS.md | 19 +- integrations/agent-plugin-core/README.md | 102 + .../agent-plugin-core/build/__init__.py | 1 + integrations/agent-plugin-core/build/build.py | 252 ++ .../build/schemas/mcp.schema.json | 89 + .../build/schemas/plugin.schema.json | 45 + .../agent-plugin-core/build/validate.py | 76 + .../conformance/artifacts.py | 58 + .../agent-plugin-core/conformance/run.py | 320 ++ .../agent-plugin-core/python/flush_worker.py | 100 + .../agent-plugin-core/python/hook_runner.py | 372 +++ .../agent-plugin-core/python/mcp_server.py | 247 ++ .../agent-plugin-core/python/memory_cli.py | 154 + .../agent-plugin-core/python/memory_core.py | 2645 +++++++++++++++++ .../agent-plugin-core/python/telemetry.py | 397 +++ .../agent-plugin-core/requirements-dev.txt | 3 + .../skills/forget/SKILL.md.tmpl | 26 + .../skills/pause/SKILL.md.tmpl | 20 + .../skills/remember/SKILL.md.tmpl | 21 + .../skills/resume/SKILL.md.tmpl | 19 + .../skills/search/SKILL.md.tmpl | 28 + .../skills/status/SKILL.md.tmpl | 23 + .../agent-plugin-core/tests/test_build.py | 116 + .../tests/test_conformance.py | 190 ++ .../agent-plugin-core/tests/test_sidekick.py | 83 + .../agent-plugin-core/tests/test_validate.py | 115 + .../agent-plugin-core/typescript/package.json | 14 + .../typescript/pnpm-lock.yaml | 39 + .../typescript/src/formatting.ts | 70 + .../typescript/src/identity.ts | 33 + .../typescript/src/lifecycle.ts | 177 ++ .../typescript/src/scoping.ts | 50 + .../typescript/src/telemetry.ts | 158 + .../typescript/tests/formatting.test.ts | 39 + .../typescript/tests/identity.test.ts | 18 + .../typescript/tests/lifecycle.test.ts | 120 + .../typescript/tests/scoping.test.ts | 44 + .../typescript/tests/telemetry.test.ts | 124 + .../typescript/tsconfig.json | 12 + .../agents/sidekick/agent.md | 17 + .../antigravity-plugin/core/flush_worker.py | 100 + .../antigravity-plugin/core/hook_runner.py | 372 +++ .../antigravity-plugin/core/mcp_server.py | 247 ++ .../antigravity-plugin/core/memory_cli.py | 154 + .../antigravity-plugin/core/memory_core.py | 2645 +++++++++++++++++ .../antigravity-plugin/core/telemetry.py | 397 +++ integrations/antigravity-plugin/hooks.json | 18 + .../antigravity-plugin/hooks/adapter.py | 163 + .../antigravity-plugin/mcp_config.json | 8 + .../antigravity-plugin/plugin-build.json | 15 + integrations/antigravity-plugin/plugin.json | 5 + .../antigravity-plugin/skills/forget/SKILL.md | 26 + .../antigravity-plugin/skills/pause/SKILL.md | 20 + .../skills/remember/SKILL.md | 21 + .../antigravity-plugin/skills/resume/SKILL.md | 19 + .../antigravity-plugin/skills/search/SKILL.md | 28 + .../antigravity-plugin/skills/status/SKILL.md | 23 + .../tests/test_antigravity.py | 140 + .../.claude-plugin/plugin.json | 2 +- integrations/claude-code-plugin/.gitignore | 11 - integrations/claude-code-plugin/README.md | 19 +- .../adapters/claude/hook.py | 383 +-- .../adapters/claude/transcript.py | 362 +++ .../claude-code-plugin/core/flush_worker.py | 24 +- .../claude-code-plugin/core/hook_runner.py | 372 +++ .../claude-code-plugin/core/mcp_server.py | 47 +- .../claude-code-plugin/core/memory_cli.py | 6 + .../claude-code-plugin/core/memory_core.py | 694 ++--- .../claude-code-plugin/core/telemetry.py | 56 +- .../claude-code-plugin/plugin-build.json | 17 + .../claude-code-plugin/skills/forget/SKILL.md | 2 +- .../claude-code-plugin/skills/pause/SKILL.md | 2 +- .../claude-code-plugin/skills/resume/SKILL.md | 2 +- .../claude-code-plugin/skills/search/SKILL.md | 10 +- .../claude-code-plugin/skills/status/SKILL.md | 4 +- .../claude-code-plugin/tests/conftest.py | 15 +- .../tests/integration/test_live_scoping.py | 17 +- .../tests/test_claude_build.py | 35 + .../tests/test_memory_core.py | 649 +++- .../tests/test_telemetry.py | 45 +- .../codex-plugin/.codex-plugin/plugin.json | 13 + integrations/codex-plugin/.mcp.json | 19 + .../codex-plugin/core/flush_worker.py | 100 + integrations/codex-plugin/core/hook_runner.py | 372 +++ integrations/codex-plugin/core/mcp_server.py | 247 ++ integrations/codex-plugin/core/memory_cli.py | 154 + integrations/codex-plugin/core/memory_core.py | 2645 +++++++++++++++++ integrations/codex-plugin/core/telemetry.py | 397 +++ integrations/codex-plugin/hooks/adapter.py | 64 + integrations/codex-plugin/hooks/hooks.json | 63 + integrations/codex-plugin/plugin-build.json | 15 + .../codex-plugin/skills/forget/SKILL.md | 26 + .../codex-plugin/skills/pause/SKILL.md | 20 + .../codex-plugin/skills/remember/SKILL.md | 21 + .../codex-plugin/skills/resume/SKILL.md | 19 + .../codex-plugin/skills/search/SKILL.md | 28 + .../codex-plugin/skills/status/SKILL.md | 23 + integrations/codex-plugin/tests/test_codex.py | 107 + .../cursor-plugin/.cursor-plugin/plugin.json | 25 + integrations/cursor-plugin/agents/sidekick.md | 16 + .../cursor-plugin/core/flush_worker.py | 100 + .../cursor-plugin/core/hook_runner.py | 372 +++ integrations/cursor-plugin/core/mcp_server.py | 247 ++ integrations/cursor-plugin/core/memory_cli.py | 154 + .../cursor-plugin/core/memory_core.py | 2645 +++++++++++++++++ integrations/cursor-plugin/core/telemetry.py | 397 +++ integrations/cursor-plugin/hooks/adapter.py | 132 + integrations/cursor-plugin/hooks/hooks.json | 15 + integrations/cursor-plugin/mcp.json | 18 + integrations/cursor-plugin/plugin-build.json | 15 + .../cursor-plugin/skills/forget/SKILL.md | 26 + .../cursor-plugin/skills/pause/SKILL.md | 20 + .../cursor-plugin/skills/remember/SKILL.md | 21 + .../cursor-plugin/skills/resume/SKILL.md | 19 + .../cursor-plugin/skills/search/SKILL.md | 28 + .../cursor-plugin/skills/status/SKILL.md | 23 + .../cursor-plugin/tests/test_adapter.py | 112 + integrations/deepseek-plugin/README.md | 41 +- .../deepseek-plugin/cordis.example.yml | 16 +- integrations/deepseek-plugin/package.json | 11 +- integrations/deepseek-plugin/pnpm-lock.yaml | 84 +- .../deepseek-plugin/src/formatting.ts | 76 +- integrations/deepseek-plugin/src/index.ts | 141 +- integrations/deepseek-plugin/src/output.ts | 38 +- integrations/deepseek-plugin/src/scoping.ts | 58 +- integrations/deepseek-plugin/src/telemetry.ts | 149 +- .../deepseek-plugin/tests/apply.test.ts | 128 +- .../deepseek-plugin/tests/telemetry.test.ts | 7 +- integrations/deepseek-plugin/tsconfig.json | 1 - integrations/kimi-plugin/agents/sidekick.md | 18 + integrations/kimi-plugin/core/flush_worker.py | 100 + integrations/kimi-plugin/core/hook_runner.py | 372 +++ integrations/kimi-plugin/core/mcp_server.py | 247 ++ integrations/kimi-plugin/core/memory_cli.py | 154 + integrations/kimi-plugin/core/memory_core.py | 2645 +++++++++++++++++ integrations/kimi-plugin/core/telemetry.py | 397 +++ integrations/kimi-plugin/hooks/adapter.py | 154 + integrations/kimi-plugin/kimi.plugin.json | 32 + integrations/kimi-plugin/plugin-build.json | 13 + .../kimi-plugin/skills/forget/SKILL.md | 26 + .../kimi-plugin/skills/pause/SKILL.md | 20 + .../kimi-plugin/skills/remember/SKILL.md | 21 + .../kimi-plugin/skills/resume/SKILL.md | 19 + .../kimi-plugin/skills/search/SKILL.md | 28 + .../kimi-plugin/skills/status/SKILL.md | 23 + integrations/kimi-plugin/tests/test_kimi.py | 190 ++ .../mem0-agent-plugin/core/mcp_server.py | 247 ++ .../mem0-agent-plugin/core/memory_cli.py | 154 + .../mem0-agent-plugin/core/memory_core.py | 2645 +++++++++++++++++ .../mem0-agent-plugin/core/telemetry.py | 397 +++ integrations/mem0-agent-plugin/mcp.json | 12 + integrations/mem0-agent-plugin/plugin.json | 19 + .../mem0-agent-plugin/skills/forget/SKILL.md | 25 + .../mem0-agent-plugin/skills/pause/SKILL.md | 19 + .../skills/remember/SKILL.md | 20 + .../mem0-agent-plugin/skills/resume/SKILL.md | 18 + .../mem0-agent-plugin/skills/search/SKILL.md | 26 + .../mem0-agent-plugin/skills/status/SKILL.md | 22 + integrations/mem0-plugin/.codex-mcp.json | 8 - .../mem0-plugin/.codex-plugin/plugin.json | 35 - integrations/mem0-plugin/.cursor-mcp.json | 10 - .../mem0-plugin/.cursor-plugin/plugin.json | 17 - .../mem0-plugin/.kimi-plugin/plugin.json | 86 - .../.opencode-plugin/dream.test.ts | 100 - .../mem0-plugin/.opencode-plugin/dream.ts | 225 -- .../opencode-skills/mem0-dream/SKILL.md | 237 -- .../opencode-skills/mem0-pin/SKILL.md | 71 - .../mem0-plugin/.opencode-plugin/project.ts | 20 - .../mem0-plugin/.opencode-plugin/scope.ts | 71 - .../mem0-plugin/.opencode-plugin/telemetry.ts | 113 - integrations/mem0-plugin/README.md | 278 -- integrations/mem0-plugin/hooks.json | 104 - .../mem0-plugin/hooks/codex-hooks.json | 104 - .../mem0-plugin/hooks/cursor-hooks.json | 56 - integrations/mem0-plugin/logo.svg | 19 - integrations/mem0-plugin/mcp_config.json | 10 - integrations/mem0-plugin/plugin.json | 13 - integrations/mem0-plugin/requirements.txt | 1 - integrations/mem0-plugin/scripts/_chunking.py | 75 - .../mem0-plugin/scripts/_formatting.py | 51 - integrations/mem0-plugin/scripts/_identity.py | 104 - integrations/mem0-plugin/scripts/_identity.sh | 87 - .../mem0-plugin/scripts/_instructions.py | 51 - integrations/mem0-plugin/scripts/_project.py | 175 -- integrations/mem0-plugin/scripts/_project.sh | 77 - integrations/mem0-plugin/scripts/_search.py | 105 - .../mem0-plugin/scripts/auto_capture.py | 213 -- .../mem0-plugin/scripts/auto_import.py | 374 --- .../scripts/auto_setup_categories.py | 236 -- .../mem0-plugin/scripts/block_memory_write.sh | 36 - .../scripts/block_memory_write_cursor.sh | 33 - .../scripts/capture_compact_summary.py | 203 -- .../scripts/capture_session_summary.py | 272 -- .../scripts/enforce_metadata_defaults.sh | 218 -- .../mem0-plugin/scripts/ensure_deps.sh | 50 - .../mem0-plugin/scripts/file_context.py | 134 - .../scripts/import_competing_tools.py | 299 -- .../scripts/install_codex_hooks.py | 162 - .../mem0-plugin/scripts/kimi_hook_shim.sh | 120 - .../mem0-plugin/scripts/load_settings.py | 71 - .../mem0-plugin/scripts/on_bash_output.sh | 123 - .../mem0-plugin/scripts/on_file_read.sh | 51 - .../scripts/on_file_read_cursor.sh | 41 - .../mem0-plugin/scripts/on_post_tool_use.sh | 36 - .../scripts/on_post_tool_use_cursor.sh | 18 - .../mem0-plugin/scripts/on_pre_compact.py | 314 -- .../mem0-plugin/scripts/on_pre_compact.sh | 23 - .../scripts/on_pre_compact_cursor.sh | 22 - .../mem0-plugin/scripts/on_session_start.sh | 207 -- .../scripts/on_session_start_cursor.sh | 22 - integrations/mem0-plugin/scripts/on_stop.sh | 55 - .../mem0-plugin/scripts/on_stop_cursor.sh | 38 - .../mem0-plugin/scripts/on_user_prompt.sh | 228 -- .../scripts/on_user_prompt_cursor.sh | 22 - .../mem0-plugin/scripts/parse_export_file.py | 150 - .../mem0-plugin/scripts/parse_mem0_config.py | 316 -- .../mem0-plugin/scripts/session_stats.py | 138 - .../mem0-plugin/scripts/session_timeline.py | 106 - .../scripts/setup_coding_categories.py | 236 -- integrations/mem0-plugin/scripts/telemetry.py | 174 -- .../skills/context-loader/SKILL.md | 48 - .../mem0-plugin/skills/dream/SKILL.md | 232 -- .../mem0-plugin/skills/export/SKILL.md | 76 - .../mem0-plugin/skills/forget/SKILL.md | 71 - .../mem0-plugin/skills/health/SKILL.md | 160 - .../mem0-plugin/skills/import/SKILL.md | 177 -- .../mem0-plugin/skills/list-projects/SKILL.md | 60 - integrations/mem0-plugin/skills/mem0/LICENSE | 189 -- .../mem0-plugin/skills/mem0/README.md | 73 - integrations/mem0-plugin/skills/mem0/SKILL.md | 187 -- .../skills/mem0/client/differences.md | 129 - .../mem0-plugin/skills/mem0/client/node.md | 418 --- .../mem0-plugin/skills/mem0/client/python.md | 487 --- .../skills/mem0/references/api-reference.md | 150 - .../skills/mem0/references/architecture.md | 330 -- .../skills/mem0/references/features.md | 406 --- .../mem0/references/integration-patterns.md | 395 --- .../skills/mem0/references/quickstart.md | 119 - .../skills/mem0/references/sdk-guide.md | 353 --- .../skills/mem0/references/use-cases.md | 720 ----- .../skills/mem0/scripts/mem0_doc_search.py | 220 -- .../skills/memory-reviewer/SKILL.md | 59 - .../mem0-plugin/skills/onboard/SKILL.md | 184 -- integrations/mem0-plugin/skills/peek/SKILL.md | 52 - integrations/mem0-plugin/skills/pin/SKILL.md | 67 - .../mem0-plugin/skills/policy/SKILL.md | 71 - .../mem0-plugin/skills/remember/SKILL.md | 57 - .../mem0-plugin/skills/stats/SKILL.md | 130 - .../skills/switch-project/SKILL.md | 103 - integrations/mem0-plugin/skills/tour/SKILL.md | 123 - integrations/mem0-plugin/tests/conftest.py | 65 - .../mem0-plugin/tests/test_auto_capture.py | 142 - .../tests/test_auto_setup_categories.py | 153 - .../tests/test_capture_session_summary.py | 79 - .../tests/test_coding_categories.py | 88 - .../tests/test_import_competing_tools.py | 355 --- .../mem0-plugin/tests/test_instructions.py | 126 - .../mem0-plugin/tests/test_kimi_manifests.py | 80 - .../mem0-plugin/tests/test_load_settings.py | 86 - .../mem0-plugin/tests/test_message_roles.py | 144 - .../tests/test_parse_export_file.py | 298 -- .../tests/test_parse_mem0_config.py | 439 --- .../mem0-plugin/tests/test_project.py | 171 -- .../mem0-plugin/tests/test_rubric_dedup.py | 61 - integrations/mem0-plugin/tests/test_search.py | 211 -- .../mem0-plugin/tests/test_session_stats.py | 248 -- .../mem0-plugin/tests/test_telemetry.py | 268 -- .../mem0-plugin/tests/test_write_path.py | 207 -- .../mem0-strands/python/pyproject.toml | 2 +- integrations/openclaw/README.md | 14 +- integrations/openclaw/cli/commands.ts | 119 +- integrations/openclaw/cli/config-file.ts | 3 +- integrations/openclaw/dream-gate.ts | 214 -- integrations/openclaw/filtering.ts | 18 +- integrations/openclaw/index.test.ts | 16 +- integrations/openclaw/index.ts | 158 +- .../openclaw/openclaw-plugin-sdk.d.ts | 2 +- integrations/openclaw/openclaw.plugin.json | 16 +- integrations/openclaw/package.json | 2 +- integrations/openclaw/public-artifacts.ts | 50 +- integrations/openclaw/scripts/configure.py | 1 - integrations/openclaw/skill-loader.ts | 13 +- .../openclaw/skills/memory-dream/SKILL.md | 150 - integrations/openclaw/telemetry.ts | 348 +-- .../openclaw/tests/cli-commands.test.ts | 122 +- integrations/openclaw/tests/config.test.ts | 17 +- .../openclaw/tests/dream-gate.test.ts | 376 --- integrations/openclaw/tsconfig.json | 4 +- integrations/openclaw/types.ts | 11 - .../LICENSE | 0 .../README.md | 9 +- .../api-key.test.ts | 0 .../api-key.ts | 0 .../bun.lock | 37 - integrations/opencode-plugin/index.d.ts | 4 + .../opencode-mem0.ts | 95 +- .../mem0-context-loader/SKILL.md | 0 .../opencode-skills/mem0-forget/SKILL.md | 0 .../opencode-skills/mem0-remember/SKILL.md | 0 .../opencode-skills/mem0-scope/SKILL.md | 2 +- .../opencode-skills/mem0-search/SKILL.md | 0 .../opencode-skills/mem0-status/SKILL.md | 39 +- .../opencode-skills/mem0-tour/SKILL.md | 0 .../package.json | 14 +- .../project.test.ts | 0 integrations/opencode-plugin/project.ts | 1 + .../scope.test.ts | 1 - integrations/opencode-plugin/scope.ts | 42 + .../telemetry.test.ts | 0 integrations/opencode-plugin/telemetry.ts | 66 + .../tsconfig.json | 3 +- integrations/pi-agent-plugin/README.md | 31 +- integrations/pi-agent-plugin/package.json | 5 +- .../pi-agent-plugin/skills/dream/SKILL.md | 125 - .../pi-agent-plugin/skills/pin/SKILL.md | 48 - .../pi-agent-plugin/skills/status/SKILL.md | 2 +- .../pi-agent-plugin/src/capture/index.ts | 35 +- .../pi-agent-plugin/src/commands.test.ts | 141 +- integrations/pi-agent-plugin/src/commands.ts | 88 - .../pi-agent-plugin/src/config/index.ts | 17 +- .../pi-agent-plugin/src/dream/index.ts | 115 - .../pi-agent-plugin/src/dream/prompt.ts | 22 - integrations/pi-agent-plugin/src/entry.ts | 108 +- integrations/pi-agent-plugin/src/index.ts | 11 - .../pi-agent-plugin/src/memory/formatting.ts | 50 +- .../src/memory/scoping.test.ts | 4 +- .../pi-agent-plugin/src/memory/scoping.ts | 22 +- .../pi-agent-plugin/src/memory/tools.ts | 16 +- integrations/pi-agent-plugin/src/telemetry.ts | 253 +- integrations/pi-agent-plugin/src/types.ts | 20 - .../pi-agent-plugin/tests/capture.test.ts | 6 + .../pi-agent-plugin/tests/config.test.ts | 2 - .../pi-agent-plugin/tests/dream.test.ts | 59 - .../pi-agent-plugin/tests/scoping.test.ts | 4 +- .../pi-agent-plugin/tests/tools.test.ts | 24 +- integrations/pi-agent-plugin/tsconfig.json | 2 +- marketplace.json | 2 +- skills/mem0-integrate/SKILL.md | 4 +- 369 files changed, 31056 insertions(+), 20464 deletions(-) create mode 100644 .github/workflows/agent-plugins-python-checks.yml create mode 100644 .github/workflows/agent-plugins-typescript-checks.yml delete mode 100644 .github/workflows/claude-code-plugin-checks.yml delete mode 100644 .github/workflows/mem0-plugin-checks.yml create mode 100644 docs/integrations/kimi.mdx create mode 100644 integrations/agent-plugin-core/README.md create mode 100644 integrations/agent-plugin-core/build/__init__.py create mode 100644 integrations/agent-plugin-core/build/build.py create mode 100644 integrations/agent-plugin-core/build/schemas/mcp.schema.json create mode 100644 integrations/agent-plugin-core/build/schemas/plugin.schema.json create mode 100644 integrations/agent-plugin-core/build/validate.py create mode 100644 integrations/agent-plugin-core/conformance/artifacts.py create mode 100644 integrations/agent-plugin-core/conformance/run.py create mode 100644 integrations/agent-plugin-core/python/flush_worker.py create mode 100644 integrations/agent-plugin-core/python/hook_runner.py create mode 100644 integrations/agent-plugin-core/python/mcp_server.py create mode 100644 integrations/agent-plugin-core/python/memory_cli.py create mode 100644 integrations/agent-plugin-core/python/memory_core.py create mode 100644 integrations/agent-plugin-core/python/telemetry.py create mode 100644 integrations/agent-plugin-core/requirements-dev.txt create mode 100644 integrations/agent-plugin-core/skills/forget/SKILL.md.tmpl create mode 100644 integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl create mode 100644 integrations/agent-plugin-core/skills/remember/SKILL.md.tmpl create mode 100644 integrations/agent-plugin-core/skills/resume/SKILL.md.tmpl create mode 100644 integrations/agent-plugin-core/skills/search/SKILL.md.tmpl create mode 100644 integrations/agent-plugin-core/skills/status/SKILL.md.tmpl create mode 100644 integrations/agent-plugin-core/tests/test_build.py create mode 100644 integrations/agent-plugin-core/tests/test_conformance.py create mode 100644 integrations/agent-plugin-core/tests/test_sidekick.py create mode 100644 integrations/agent-plugin-core/tests/test_validate.py create mode 100644 integrations/agent-plugin-core/typescript/package.json create mode 100644 integrations/agent-plugin-core/typescript/pnpm-lock.yaml create mode 100644 integrations/agent-plugin-core/typescript/src/formatting.ts create mode 100644 integrations/agent-plugin-core/typescript/src/identity.ts create mode 100644 integrations/agent-plugin-core/typescript/src/lifecycle.ts create mode 100644 integrations/agent-plugin-core/typescript/src/scoping.ts create mode 100644 integrations/agent-plugin-core/typescript/src/telemetry.ts create mode 100644 integrations/agent-plugin-core/typescript/tests/formatting.test.ts create mode 100644 integrations/agent-plugin-core/typescript/tests/identity.test.ts create mode 100644 integrations/agent-plugin-core/typescript/tests/lifecycle.test.ts create mode 100644 integrations/agent-plugin-core/typescript/tests/scoping.test.ts create mode 100644 integrations/agent-plugin-core/typescript/tests/telemetry.test.ts create mode 100644 integrations/agent-plugin-core/typescript/tsconfig.json create mode 100644 integrations/antigravity-plugin/agents/sidekick/agent.md create mode 100644 integrations/antigravity-plugin/core/flush_worker.py create mode 100644 integrations/antigravity-plugin/core/hook_runner.py create mode 100644 integrations/antigravity-plugin/core/mcp_server.py create mode 100644 integrations/antigravity-plugin/core/memory_cli.py create mode 100644 integrations/antigravity-plugin/core/memory_core.py create mode 100644 integrations/antigravity-plugin/core/telemetry.py create mode 100644 integrations/antigravity-plugin/hooks.json create mode 100644 integrations/antigravity-plugin/hooks/adapter.py create mode 100644 integrations/antigravity-plugin/mcp_config.json create mode 100644 integrations/antigravity-plugin/plugin-build.json create mode 100644 integrations/antigravity-plugin/plugin.json create mode 100644 integrations/antigravity-plugin/skills/forget/SKILL.md create mode 100644 integrations/antigravity-plugin/skills/pause/SKILL.md create mode 100644 integrations/antigravity-plugin/skills/remember/SKILL.md create mode 100644 integrations/antigravity-plugin/skills/resume/SKILL.md create mode 100644 integrations/antigravity-plugin/skills/search/SKILL.md create mode 100644 integrations/antigravity-plugin/skills/status/SKILL.md create mode 100644 integrations/antigravity-plugin/tests/test_antigravity.py delete mode 100644 integrations/claude-code-plugin/.gitignore create mode 100644 integrations/claude-code-plugin/adapters/claude/transcript.py create mode 100644 integrations/claude-code-plugin/core/hook_runner.py create mode 100644 integrations/claude-code-plugin/plugin-build.json create mode 100644 integrations/claude-code-plugin/tests/test_claude_build.py create mode 100644 integrations/codex-plugin/.codex-plugin/plugin.json create mode 100644 integrations/codex-plugin/.mcp.json create mode 100644 integrations/codex-plugin/core/flush_worker.py create mode 100644 integrations/codex-plugin/core/hook_runner.py create mode 100644 integrations/codex-plugin/core/mcp_server.py create mode 100644 integrations/codex-plugin/core/memory_cli.py create mode 100644 integrations/codex-plugin/core/memory_core.py create mode 100644 integrations/codex-plugin/core/telemetry.py create mode 100644 integrations/codex-plugin/hooks/adapter.py create mode 100644 integrations/codex-plugin/hooks/hooks.json create mode 100644 integrations/codex-plugin/plugin-build.json create mode 100644 integrations/codex-plugin/skills/forget/SKILL.md create mode 100644 integrations/codex-plugin/skills/pause/SKILL.md create mode 100644 integrations/codex-plugin/skills/remember/SKILL.md create mode 100644 integrations/codex-plugin/skills/resume/SKILL.md create mode 100644 integrations/codex-plugin/skills/search/SKILL.md create mode 100644 integrations/codex-plugin/skills/status/SKILL.md create mode 100644 integrations/codex-plugin/tests/test_codex.py create mode 100644 integrations/cursor-plugin/.cursor-plugin/plugin.json create mode 100644 integrations/cursor-plugin/agents/sidekick.md create mode 100644 integrations/cursor-plugin/core/flush_worker.py create mode 100644 integrations/cursor-plugin/core/hook_runner.py create mode 100644 integrations/cursor-plugin/core/mcp_server.py create mode 100644 integrations/cursor-plugin/core/memory_cli.py create mode 100644 integrations/cursor-plugin/core/memory_core.py create mode 100644 integrations/cursor-plugin/core/telemetry.py create mode 100644 integrations/cursor-plugin/hooks/adapter.py create mode 100644 integrations/cursor-plugin/hooks/hooks.json create mode 100644 integrations/cursor-plugin/mcp.json create mode 100644 integrations/cursor-plugin/plugin-build.json create mode 100644 integrations/cursor-plugin/skills/forget/SKILL.md create mode 100644 integrations/cursor-plugin/skills/pause/SKILL.md create mode 100644 integrations/cursor-plugin/skills/remember/SKILL.md create mode 100644 integrations/cursor-plugin/skills/resume/SKILL.md create mode 100644 integrations/cursor-plugin/skills/search/SKILL.md create mode 100644 integrations/cursor-plugin/skills/status/SKILL.md create mode 100644 integrations/cursor-plugin/tests/test_adapter.py create mode 100644 integrations/kimi-plugin/agents/sidekick.md create mode 100644 integrations/kimi-plugin/core/flush_worker.py create mode 100644 integrations/kimi-plugin/core/hook_runner.py create mode 100644 integrations/kimi-plugin/core/mcp_server.py create mode 100644 integrations/kimi-plugin/core/memory_cli.py create mode 100644 integrations/kimi-plugin/core/memory_core.py create mode 100644 integrations/kimi-plugin/core/telemetry.py create mode 100644 integrations/kimi-plugin/hooks/adapter.py create mode 100644 integrations/kimi-plugin/kimi.plugin.json create mode 100644 integrations/kimi-plugin/plugin-build.json create mode 100644 integrations/kimi-plugin/skills/forget/SKILL.md create mode 100644 integrations/kimi-plugin/skills/pause/SKILL.md create mode 100644 integrations/kimi-plugin/skills/remember/SKILL.md create mode 100644 integrations/kimi-plugin/skills/resume/SKILL.md create mode 100644 integrations/kimi-plugin/skills/search/SKILL.md create mode 100644 integrations/kimi-plugin/skills/status/SKILL.md create mode 100644 integrations/kimi-plugin/tests/test_kimi.py create mode 100644 integrations/mem0-agent-plugin/core/mcp_server.py create mode 100644 integrations/mem0-agent-plugin/core/memory_cli.py create mode 100644 integrations/mem0-agent-plugin/core/memory_core.py create mode 100644 integrations/mem0-agent-plugin/core/telemetry.py create mode 100644 integrations/mem0-agent-plugin/mcp.json create mode 100644 integrations/mem0-agent-plugin/plugin.json create mode 100644 integrations/mem0-agent-plugin/skills/forget/SKILL.md create mode 100644 integrations/mem0-agent-plugin/skills/pause/SKILL.md create mode 100644 integrations/mem0-agent-plugin/skills/remember/SKILL.md create mode 100644 integrations/mem0-agent-plugin/skills/resume/SKILL.md create mode 100644 integrations/mem0-agent-plugin/skills/search/SKILL.md create mode 100644 integrations/mem0-agent-plugin/skills/status/SKILL.md delete mode 100644 integrations/mem0-plugin/.codex-mcp.json delete mode 100644 integrations/mem0-plugin/.codex-plugin/plugin.json delete mode 100644 integrations/mem0-plugin/.cursor-mcp.json delete mode 100644 integrations/mem0-plugin/.cursor-plugin/plugin.json delete mode 100644 integrations/mem0-plugin/.kimi-plugin/plugin.json delete mode 100644 integrations/mem0-plugin/.opencode-plugin/dream.test.ts delete mode 100644 integrations/mem0-plugin/.opencode-plugin/dream.ts delete mode 100644 integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-dream/SKILL.md delete mode 100644 integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-pin/SKILL.md delete mode 100644 integrations/mem0-plugin/.opencode-plugin/project.ts delete mode 100644 integrations/mem0-plugin/.opencode-plugin/scope.ts delete mode 100644 integrations/mem0-plugin/.opencode-plugin/telemetry.ts delete mode 100644 integrations/mem0-plugin/README.md delete mode 100644 integrations/mem0-plugin/hooks.json delete mode 100644 integrations/mem0-plugin/hooks/codex-hooks.json delete mode 100644 integrations/mem0-plugin/hooks/cursor-hooks.json delete mode 100644 integrations/mem0-plugin/logo.svg delete mode 100644 integrations/mem0-plugin/mcp_config.json delete mode 100644 integrations/mem0-plugin/plugin.json delete mode 100644 integrations/mem0-plugin/requirements.txt delete mode 100644 integrations/mem0-plugin/scripts/_chunking.py delete mode 100644 integrations/mem0-plugin/scripts/_formatting.py delete mode 100644 integrations/mem0-plugin/scripts/_identity.py delete mode 100644 integrations/mem0-plugin/scripts/_identity.sh delete mode 100644 integrations/mem0-plugin/scripts/_instructions.py delete mode 100644 integrations/mem0-plugin/scripts/_project.py delete mode 100755 integrations/mem0-plugin/scripts/_project.sh delete mode 100644 integrations/mem0-plugin/scripts/_search.py delete mode 100755 integrations/mem0-plugin/scripts/auto_capture.py delete mode 100644 integrations/mem0-plugin/scripts/auto_import.py delete mode 100644 integrations/mem0-plugin/scripts/auto_setup_categories.py delete mode 100755 integrations/mem0-plugin/scripts/block_memory_write.sh delete mode 100755 integrations/mem0-plugin/scripts/block_memory_write_cursor.sh delete mode 100644 integrations/mem0-plugin/scripts/capture_compact_summary.py delete mode 100644 integrations/mem0-plugin/scripts/capture_session_summary.py delete mode 100755 integrations/mem0-plugin/scripts/enforce_metadata_defaults.sh delete mode 100755 integrations/mem0-plugin/scripts/ensure_deps.sh delete mode 100644 integrations/mem0-plugin/scripts/file_context.py delete mode 100644 integrations/mem0-plugin/scripts/import_competing_tools.py delete mode 100755 integrations/mem0-plugin/scripts/install_codex_hooks.py delete mode 100755 integrations/mem0-plugin/scripts/kimi_hook_shim.sh delete mode 100644 integrations/mem0-plugin/scripts/load_settings.py delete mode 100755 integrations/mem0-plugin/scripts/on_bash_output.sh delete mode 100755 integrations/mem0-plugin/scripts/on_file_read.sh delete mode 100755 integrations/mem0-plugin/scripts/on_file_read_cursor.sh delete mode 100755 integrations/mem0-plugin/scripts/on_post_tool_use.sh delete mode 100755 integrations/mem0-plugin/scripts/on_post_tool_use_cursor.sh delete mode 100755 integrations/mem0-plugin/scripts/on_pre_compact.py delete mode 100755 integrations/mem0-plugin/scripts/on_pre_compact.sh delete mode 100755 integrations/mem0-plugin/scripts/on_pre_compact_cursor.sh delete mode 100755 integrations/mem0-plugin/scripts/on_session_start.sh delete mode 100755 integrations/mem0-plugin/scripts/on_session_start_cursor.sh delete mode 100755 integrations/mem0-plugin/scripts/on_stop.sh delete mode 100755 integrations/mem0-plugin/scripts/on_stop_cursor.sh delete mode 100755 integrations/mem0-plugin/scripts/on_user_prompt.sh delete mode 100755 integrations/mem0-plugin/scripts/on_user_prompt_cursor.sh delete mode 100644 integrations/mem0-plugin/scripts/parse_export_file.py delete mode 100644 integrations/mem0-plugin/scripts/parse_mem0_config.py delete mode 100644 integrations/mem0-plugin/scripts/session_stats.py delete mode 100644 integrations/mem0-plugin/scripts/session_timeline.py delete mode 100644 integrations/mem0-plugin/scripts/setup_coding_categories.py delete mode 100644 integrations/mem0-plugin/scripts/telemetry.py delete mode 100644 integrations/mem0-plugin/skills/context-loader/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/dream/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/export/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/forget/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/health/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/import/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/list-projects/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/mem0/LICENSE delete mode 100644 integrations/mem0-plugin/skills/mem0/README.md delete mode 100644 integrations/mem0-plugin/skills/mem0/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/mem0/client/differences.md delete mode 100644 integrations/mem0-plugin/skills/mem0/client/node.md delete mode 100644 integrations/mem0-plugin/skills/mem0/client/python.md delete mode 100644 integrations/mem0-plugin/skills/mem0/references/api-reference.md delete mode 100644 integrations/mem0-plugin/skills/mem0/references/architecture.md delete mode 100644 integrations/mem0-plugin/skills/mem0/references/features.md delete mode 100644 integrations/mem0-plugin/skills/mem0/references/integration-patterns.md delete mode 100644 integrations/mem0-plugin/skills/mem0/references/quickstart.md delete mode 100644 integrations/mem0-plugin/skills/mem0/references/sdk-guide.md delete mode 100644 integrations/mem0-plugin/skills/mem0/references/use-cases.md delete mode 100755 integrations/mem0-plugin/skills/mem0/scripts/mem0_doc_search.py delete mode 100644 integrations/mem0-plugin/skills/memory-reviewer/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/onboard/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/peek/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/pin/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/policy/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/remember/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/stats/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/switch-project/SKILL.md delete mode 100644 integrations/mem0-plugin/skills/tour/SKILL.md delete mode 100644 integrations/mem0-plugin/tests/conftest.py delete mode 100644 integrations/mem0-plugin/tests/test_auto_capture.py delete mode 100644 integrations/mem0-plugin/tests/test_auto_setup_categories.py delete mode 100644 integrations/mem0-plugin/tests/test_capture_session_summary.py delete mode 100644 integrations/mem0-plugin/tests/test_coding_categories.py delete mode 100644 integrations/mem0-plugin/tests/test_import_competing_tools.py delete mode 100644 integrations/mem0-plugin/tests/test_instructions.py delete mode 100644 integrations/mem0-plugin/tests/test_kimi_manifests.py delete mode 100644 integrations/mem0-plugin/tests/test_load_settings.py delete mode 100644 integrations/mem0-plugin/tests/test_message_roles.py delete mode 100644 integrations/mem0-plugin/tests/test_parse_export_file.py delete mode 100644 integrations/mem0-plugin/tests/test_parse_mem0_config.py delete mode 100644 integrations/mem0-plugin/tests/test_project.py delete mode 100644 integrations/mem0-plugin/tests/test_rubric_dedup.py delete mode 100644 integrations/mem0-plugin/tests/test_search.py delete mode 100644 integrations/mem0-plugin/tests/test_session_stats.py delete mode 100644 integrations/mem0-plugin/tests/test_telemetry.py delete mode 100644 integrations/mem0-plugin/tests/test_write_path.py delete mode 100644 integrations/openclaw/dream-gate.ts delete mode 100644 integrations/openclaw/skills/memory-dream/SKILL.md delete mode 100644 integrations/openclaw/tests/dream-gate.test.ts rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/LICENSE (100%) rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/README.md (88%) rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/api-key.test.ts (100%) rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/api-key.ts (100%) rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/bun.lock (94%) create mode 100644 integrations/opencode-plugin/index.d.ts rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/opencode-mem0.ts (92%) rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/opencode-skills/mem0-context-loader/SKILL.md (100%) rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/opencode-skills/mem0-forget/SKILL.md (100%) rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/opencode-skills/mem0-remember/SKILL.md (100%) rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/opencode-skills/mem0-scope/SKILL.md (98%) rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/opencode-skills/mem0-search/SKILL.md (100%) rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/opencode-skills/mem0-status/SKILL.md (69%) rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/opencode-skills/mem0-tour/SKILL.md (100%) rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/package.json (81%) rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/project.test.ts (100%) create mode 100644 integrations/opencode-plugin/project.ts rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/scope.test.ts (99%) create mode 100644 integrations/opencode-plugin/scope.ts rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/telemetry.test.ts (100%) create mode 100644 integrations/opencode-plugin/telemetry.ts rename integrations/{mem0-plugin/.opencode-plugin => opencode-plugin}/tsconfig.json (88%) delete mode 100644 integrations/pi-agent-plugin/skills/dream/SKILL.md delete mode 100644 integrations/pi-agent-plugin/skills/pin/SKILL.md delete mode 100644 integrations/pi-agent-plugin/src/dream/index.ts delete mode 100644 integrations/pi-agent-plugin/src/dream/prompt.ts delete mode 100644 integrations/pi-agent-plugin/tests/dream.test.ts diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json index b09335c80..cc00a131a 100644 --- a/.agents/plugins/marketplace.json +++ b/.agents/plugins/marketplace.json @@ -8,7 +8,7 @@ "name": "mem0", "source": { "source": "local", - "path": "./integrations/mem0-plugin" + "path": "./integrations/codex-plugin" }, "policy": { "installation": "AVAILABLE", diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 392e9c6f5..d46a19e49 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.0" + "version": "0.3.1" } ] } diff --git a/.codex-plugin/marketplace.json b/.codex-plugin/marketplace.json index b09335c80..cc00a131a 100644 --- a/.codex-plugin/marketplace.json +++ b/.codex-plugin/marketplace.json @@ -8,7 +8,7 @@ "name": "mem0", "source": { "source": "local", - "path": "./integrations/mem0-plugin" + "path": "./integrations/codex-plugin" }, "policy": { "installation": "AVAILABLE", diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.json index f931f04ff..409b7d8fc 100644 --- a/.cursor-plugin/marketplace.json +++ b/.cursor-plugin/marketplace.json @@ -10,9 +10,9 @@ "plugins": [ { "name": "mem0", - "source": "./integrations/mem0-plugin", - "description": "Mem0 memory layer for AI applications. Add persistent memory, personalization, and semantic search.", - "version": "0.2.15" + "source": "./integrations/cursor-plugin", + "description": "Cross-session memory and token savings for coding agents.", + "version": "0.3.1" } ] } diff --git a/.github/AGENTS.md b/.github/AGENTS.md index e207cb9fd..573480da5 100644 --- a/.github/AGENTS.md +++ b/.github/AGENTS.md @@ -18,9 +18,9 @@ Package workflows keep their own push-to-main and manual triggers. Their `pull_r | Python CLI | `cli-python-ci.yml` | Push to main (`cli/python/`), manual | Ruff + pytest + hatch build on Python 3.10, 3.11, 3.12 | | Node CLI | `cli-node-ci.yml` | Push to main (`cli/node/`), manual | Biome + tsc + vitest + tsup on Node 20, 22 | | OpenClaw | `openclaw-checks.yml` | Push to main (`integrations/openclaw/`), manual | tsc + vitest (Codecov) + tsup on Node 20, 22 | -| Mem0 Plugin (legacy) | `mem0-plugin-checks.yml` | Push to main (`integrations/mem0-plugin/`, excluding `.opencode-plugin/`), manual | pytest + hook exec bits + JSON manifest validation on Python 3.10, 3.11, 3.12 | -| Claude Code Plugin | `claude-code-plugin-checks.yml` | Push to main (`integrations/claude-code-plugin/`), manual | pytest + ruff + JSON manifest validation on Python 3.10, 3.11, 3.12 | -| OpenCode Plugin | `opencode-plugin-checks.yml` | Push to main (`.opencode-plugin/`), manual | Bun: tsc + build + dist artifact check | +| Agent Plugins Python | `agent-plugins-python-checks.yml` | Push to main (shared Python core and native/portable plugin directories), manual | Runtime tests on Python 3.10; full pytest on 3.11, 3.12; ruff + generated-package drift on 3.12 | +| Agent Plugins TypeScript | `agent-plugins-typescript-checks.yml` | Push to main (`integrations/agent-plugin-core/typescript/`), manual | tsc + node:test on Node 22 | +| OpenCode Plugin | `opencode-plugin-checks.yml` | Push to main (`integrations/opencode-plugin/`), manual | Bun: tsc + build + dist artifact check | | Pi Agent Plugin | `pi-agent-plugin-checks.yml` | Push to main (`integrations/pi-agent-plugin/`), manual | tsc + vitest + tsup on Node 20, 22 | | DeepSeek Harness Plugin | `deepseek-plugin-checks.yml` | Push to main (`integrations/deepseek-plugin/`), manual | tsc + vitest + tsup on Node 20, 22 | | n8n Node | `n8n-nodes-mem0-checks.yml` | Push to main (`integrations/n8n-nodes-mem0/`), manual | ESLint + tsc build on Node 20 | diff --git a/.github/workflows/agent-plugins-python-checks.yml b/.github/workflows/agent-plugins-python-checks.yml new file mode 100644 index 000000000..dde6598ab --- /dev/null +++ b/.github/workflows/agent-plugins-python-checks.yml @@ -0,0 +1,97 @@ +name: Agent Plugins Python Checks + +# Python runtime, adapters, generated bundles, and portable plugin validation. +# On PRs this is invoked by ci-gate.yml (the single required check); +# push-to-main and manual runs remain standalone. +on: + workflow_dispatch: + push: + branches: [main] + paths: + - 'integrations/agent-plugin-core/**' + - '!integrations/agent-plugin-core/typescript/**' + - 'integrations/mem0-agent-plugin/**' + - 'integrations/claude-code-plugin/**' + - 'integrations/cursor-plugin/**' + - 'integrations/codex-plugin/**' + - 'integrations/kimi-plugin/**' + - 'integrations/antigravity-plugin/**' + - 'marketplace.json' + - '.agents/plugins/marketplace.json' + - '.claude-plugin/marketplace.json' + - '.codex-plugin/marketplace.json' + - '.cursor-plugin/marketplace.json' + - '.kimi-plugin/marketplace.json' + - '.github/workflows/agent-plugins-python-checks.yml' + workflow_call: + +jobs: + test: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + python-version: ["3.10", "3.11", "3.12"] + steps: + - uses: actions/checkout@v4 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + + - name: Install runtime test tooling + if: matrix.python-version == '3.10' + run: pip install pytest + + - name: Install build and test tooling + if: matrix.python-version != '3.10' + run: pip install pytest ruff -r integrations/agent-plugin-core/requirements-dev.txt + + - name: Check Python runtime compatibility + run: >- + python3 -m compileall -q + integrations/agent-plugin-core/python + integrations/claude-code-plugin/adapters + integrations/cursor-plugin/hooks + integrations/codex-plugin/hooks + integrations/kimi-plugin/hooks + integrations/antigravity-plugin/hooks + + - name: Lint + if: matrix.python-version == '3.12' + run: >- + python3 -m ruff check + integrations/agent-plugin-core + integrations/claude-code-plugin + integrations/cursor-plugin + integrations/codex-plugin + integrations/kimi-plugin + integrations/antigravity-plugin + + - name: Verify installable plugins are current + if: matrix.python-version == '3.12' + run: | + for host in claude-code cursor codex kimi antigravity; do + python3 integrations/agent-plugin-core/build/build.py "$host" --kind native --check + done + python3 integrations/agent-plugin-core/build/build.py mem0-agent-plugin --kind portable --check + + - name: Run Python 3.10 runtime tests + if: matrix.python-version == '3.10' + run: >- + python3 -m pytest -q + integrations/claude-code-plugin/tests/test_memory_core.py + integrations/claude-code-plugin/tests/test_telemetry.py + + - name: Run full tests + if: matrix.python-version != '3.10' + run: >- + python3 -m pytest -q + integrations/agent-plugin-core/tests + integrations/claude-code-plugin/tests + integrations/cursor-plugin/tests + integrations/codex-plugin/tests + integrations/kimi-plugin/tests + integrations/antigravity-plugin/tests + --ignore=integrations/claude-code-plugin/tests/integration diff --git a/.github/workflows/agent-plugins-typescript-checks.yml b/.github/workflows/agent-plugins-typescript-checks.yml new file mode 100644 index 000000000..1b480edbd --- /dev/null +++ b/.github/workflows/agent-plugins-typescript-checks.yml @@ -0,0 +1,42 @@ +name: Agent Plugins TypeScript Checks + +# Shared TypeScript runtime checks. Each consuming integration keeps its own +# build workflow, which is also triggered when this shared core changes. +on: + workflow_dispatch: + push: + branches: [main] + paths: + - 'integrations/agent-plugin-core/typescript/**' + - '.github/workflows/agent-plugins-typescript-checks.yml' + workflow_call: + +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 10 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: 22 + cache: 'pnpm' + cache-dependency-path: integrations/agent-plugin-core/typescript/pnpm-lock.yaml + + - name: Install dependencies + working-directory: integrations/agent-plugin-core/typescript + run: pnpm install --frozen-lockfile + + - name: Type check + working-directory: integrations/agent-plugin-core/typescript + run: pnpm typecheck + + - name: Run tests + working-directory: integrations/agent-plugin-core/typescript + run: pnpm test diff --git a/.github/workflows/ci-gate.yml b/.github/workflows/ci-gate.yml index 2359de80b..b4fd6dc81 100644 --- a/.github/workflows/ci-gate.yml +++ b/.github/workflows/ci-gate.yml @@ -38,8 +38,8 @@ jobs: cli_python: ${{ steps.filter.outputs.cli_python }} cli_node: ${{ steps.filter.outputs.cli_node }} openclaw: ${{ steps.filter.outputs.openclaw }} - mem0_plugin: ${{ steps.filter.outputs.mem0_plugin }} - claude_code_plugin: ${{ steps.filter.outputs.claude_code_plugin }} + agent_plugins_python: ${{ steps.filter.outputs.agent_plugins_python }} + agent_plugins_typescript: ${{ steps.filter.outputs.agent_plugins_typescript }} opencode_plugin: ${{ steps.filter.outputs.opencode_plugin }} pi_agent_plugin: ${{ steps.filter.outputs.pi_agent_plugin }} deepseek_plugin: ${{ steps.filter.outputs.deepseek_plugin }} @@ -76,27 +76,43 @@ jobs: - '.github/workflows/ci-gate.yml' openclaw: - 'integrations/openclaw/**' + - 'integrations/agent-plugin-core/typescript/**' - '.github/workflows/openclaw-checks.yml' - '.github/workflows/ci-gate.yml' - mem0_plugin: - - 'integrations/mem0-plugin/**' - - '!integrations/mem0-plugin/.opencode-plugin/**' - - '.github/workflows/mem0-plugin-checks.yml' - - '.github/workflows/ci-gate.yml' - claude_code_plugin: + agent_plugins_python: + - 'integrations/agent-plugin-core/**' + - '!integrations/agent-plugin-core/typescript/**' + - 'integrations/mem0-agent-plugin/**' - 'integrations/claude-code-plugin/**' - - '.github/workflows/claude-code-plugin-checks.yml' + - 'integrations/cursor-plugin/**' + - 'integrations/codex-plugin/**' + - 'integrations/kimi-plugin/**' + - 'integrations/antigravity-plugin/**' + - 'marketplace.json' + - '.agents/plugins/marketplace.json' + - '.claude-plugin/marketplace.json' + - '.codex-plugin/marketplace.json' + - '.cursor-plugin/marketplace.json' + - '.kimi-plugin/marketplace.json' + - '.github/workflows/agent-plugins-python-checks.yml' + - '.github/workflows/ci-gate.yml' + agent_plugins_typescript: + - 'integrations/agent-plugin-core/typescript/**' + - '.github/workflows/agent-plugins-typescript-checks.yml' - '.github/workflows/ci-gate.yml' opencode_plugin: - - 'integrations/mem0-plugin/.opencode-plugin/**' + - 'integrations/opencode-plugin/**' + - 'integrations/agent-plugin-core/typescript/**' - '.github/workflows/opencode-plugin-checks.yml' - '.github/workflows/ci-gate.yml' pi_agent_plugin: - 'integrations/pi-agent-plugin/**' + - 'integrations/agent-plugin-core/typescript/**' - '.github/workflows/pi-agent-plugin-checks.yml' - '.github/workflows/ci-gate.yml' deepseek_plugin: - 'integrations/deepseek-plugin/**' + - 'integrations/agent-plugin-core/typescript/**' - '.github/workflows/deepseek-plugin-checks.yml' - '.github/workflows/ci-gate.yml' n8n_nodes_mem0: @@ -160,18 +176,17 @@ jobs: uses: ./.github/workflows/openclaw-checks.yml secrets: inherit - mem0-plugin: - name: Mem0 Plugin + agent-plugins-python: + name: Agent Plugins Python needs: changes - if: needs.changes.outputs.mem0_plugin == 'true' - uses: ./.github/workflows/mem0-plugin-checks.yml - secrets: inherit + if: needs.changes.outputs.agent_plugins_python == 'true' + uses: ./.github/workflows/agent-plugins-python-checks.yml - claude-code-plugin: - name: Claude Code Plugin + agent-plugins-typescript: + name: Agent Plugins TypeScript needs: changes - if: needs.changes.outputs.claude_code_plugin == 'true' - uses: ./.github/workflows/claude-code-plugin-checks.yml + if: needs.changes.outputs.agent_plugins_typescript == 'true' + uses: ./.github/workflows/agent-plugins-typescript-checks.yml secrets: inherit opencode-plugin: @@ -248,8 +263,8 @@ jobs: - cli-python - cli-node - openclaw - - mem0-plugin - - claude-code-plugin + - agent-plugins-python + - agent-plugins-typescript - opencode-plugin - pi-agent-plugin - deepseek-plugin diff --git a/.github/workflows/claude-code-plugin-checks.yml b/.github/workflows/claude-code-plugin-checks.yml deleted file mode 100644 index 01d0dde8e..000000000 --- a/.github/workflows/claude-code-plugin-checks.yml +++ /dev/null @@ -1,46 +0,0 @@ -name: Claude Code Plugin Checks - -# On PRs this is invoked by ci-gate.yml (the single required check); -# push-to-main and manual runs remain standalone. -on: - workflow_dispatch: - push: - branches: [main] - paths: - - 'integrations/claude-code-plugin/**' - - '.github/workflows/claude-code-plugin-checks.yml' - workflow_call: - -jobs: - test: - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - python-version: ["3.10", "3.11", "3.12"] - steps: - - uses: actions/checkout@v4 - - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - - - name: Install test tooling - run: pip install pytest ruff - # The plugin itself has zero runtime dependencies — nothing else to install. - - - name: Check manifests are valid JSON - working-directory: integrations/claude-code-plugin - run: | - for f in .claude-plugin/plugin.json .mcp.json hooks/hooks.json; do - jq empty "$f" || (echo "Invalid JSON: $f" && exit 1) - done - - - name: Lint - working-directory: integrations/claude-code-plugin - run: python3 -m ruff check . - - - name: Run tests - working-directory: integrations/claude-code-plugin - run: python3 -m pytest tests -q diff --git a/.github/workflows/deepseek-plugin-checks.yml b/.github/workflows/deepseek-plugin-checks.yml index ecaeb6da6..6054f4832 100644 --- a/.github/workflows/deepseek-plugin-checks.yml +++ b/.github/workflows/deepseek-plugin-checks.yml @@ -8,6 +8,7 @@ on: branches: [main] paths: - 'integrations/deepseek-plugin/**' + - 'integrations/agent-plugin-core/typescript/**' - '.github/workflows/deepseek-plugin-checks.yml' workflow_call: @@ -84,7 +85,5 @@ jobs: - name: Build run: cd integrations/deepseek-plugin && pnpm build - - name: Verify dist output exists - run: | - test -f integrations/deepseek-plugin/dist/index.js || (echo "Build output missing: dist/index.js" && exit 1) - test -f integrations/deepseek-plugin/dist/index.d.ts || (echo "Build output missing: dist/index.d.ts" && exit 1) + - name: Verify package artifact + run: python3 integrations/agent-plugin-core/conformance/artifacts.py deepseek diff --git a/.github/workflows/mem0-plugin-checks.yml b/.github/workflows/mem0-plugin-checks.yml deleted file mode 100644 index 87eda7ada..000000000 --- a/.github/workflows/mem0-plugin-checks.yml +++ /dev/null @@ -1,58 +0,0 @@ -name: Mem0 Plugin Checks - -# On PRs this is invoked by ci-gate.yml (the single required check); -# push-to-main and manual runs remain standalone. -# -# Covers the Python plugin (scripts/ + tests/). The nested .opencode-plugin/ -# is a separate package with its own workflow (opencode-plugin-checks.yml). -on: - workflow_dispatch: - push: - branches: [main] - paths: - - 'integrations/mem0-plugin/**' - - '!integrations/mem0-plugin/.opencode-plugin/**' - - '.github/workflows/mem0-plugin-checks.yml' - workflow_call: - -jobs: - test: - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - python-version: ["3.10", "3.11", "3.12"] - steps: - - uses: actions/checkout@v4 - - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - - - name: Install dependencies - working-directory: integrations/mem0-plugin - run: | - pip install -r requirements.txt - pip install pytest - - - name: Verify hook entry points are executable - working-directory: integrations/mem0-plugin - run: | - missing=$(find scripts -name '*.sh' ! -name '_*' ! -perm -u+x -print) - if [ -n "$missing" ]; then - echo "Hook entry points must be executable:" - echo "$missing" - exit 1 - fi - - - name: Check hook manifests are valid JSON - working-directory: integrations/mem0-plugin - run: | - for f in plugin.json mcp_config.json hooks.json hooks/*.json; do - jq empty "$f" || (echo "Invalid JSON: $f" && exit 1) - done - - - name: Run tests - working-directory: integrations/mem0-plugin - run: pytest -q diff --git a/.github/workflows/openclaw-checks.yml b/.github/workflows/openclaw-checks.yml index ec3bfee54..be6651f60 100644 --- a/.github/workflows/openclaw-checks.yml +++ b/.github/workflows/openclaw-checks.yml @@ -8,6 +8,7 @@ on: branches: [main] paths: - 'integrations/openclaw/**' + - 'integrations/agent-plugin-core/typescript/**' - '.github/workflows/openclaw-checks.yml' workflow_call: @@ -93,7 +94,5 @@ jobs: - name: Build run: cd integrations/openclaw && pnpm build - - name: Verify dist output exists - run: | - test -f integrations/openclaw/dist/index.js || (echo "Build output missing: dist/index.js" && exit 1) - test -f integrations/openclaw/dist/index.d.ts || (echo "Build output missing: dist/index.d.ts" && exit 1) + - name: Verify package artifact + run: python3 integrations/agent-plugin-core/conformance/artifacts.py openclaw diff --git a/.github/workflows/opencode-plugin-cd.yml b/.github/workflows/opencode-plugin-cd.yml index bf37f739f..6c2e11564 100644 --- a/.github/workflows/opencode-plugin-cd.yml +++ b/.github/workflows/opencode-plugin-cd.yml @@ -25,7 +25,7 @@ jobs: id-token: write defaults: run: - working-directory: integrations/mem0-plugin/.opencode-plugin + working-directory: integrations/opencode-plugin steps: - uses: actions/checkout@v4 with: diff --git a/.github/workflows/opencode-plugin-checks.yml b/.github/workflows/opencode-plugin-checks.yml index f1d9585f1..4fb95fc6c 100644 --- a/.github/workflows/opencode-plugin-checks.yml +++ b/.github/workflows/opencode-plugin-checks.yml @@ -7,7 +7,8 @@ on: push: branches: [main] paths: - - 'integrations/mem0-plugin/.opencode-plugin/**' + - 'integrations/opencode-plugin/**' + - 'integrations/agent-plugin-core/typescript/**' - '.github/workflows/opencode-plugin-checks.yml' workflow_call: @@ -16,7 +17,7 @@ jobs: runs-on: ubuntu-latest defaults: run: - working-directory: integrations/mem0-plugin/.opencode-plugin + working-directory: integrations/opencode-plugin steps: - uses: actions/checkout@v4 @@ -34,6 +35,6 @@ jobs: - name: Build run: bun run build - - name: Verify dist output exists - run: | - test -f dist/index.js || (echo "Build output missing: dist/index.js" && exit 1) + - name: Verify package artifact + working-directory: . + run: python3 integrations/agent-plugin-core/conformance/artifacts.py opencode diff --git a/.github/workflows/pi-agent-plugin-checks.yml b/.github/workflows/pi-agent-plugin-checks.yml index 258863f9e..7e4dc5a0c 100644 --- a/.github/workflows/pi-agent-plugin-checks.yml +++ b/.github/workflows/pi-agent-plugin-checks.yml @@ -8,6 +8,7 @@ on: branches: [main] paths: - 'integrations/pi-agent-plugin/**' + - 'integrations/agent-plugin-core/typescript/**' - '.github/workflows/pi-agent-plugin-checks.yml' workflow_call: @@ -84,9 +85,5 @@ jobs: - name: Build run: cd integrations/pi-agent-plugin && pnpm build - - name: Verify dist output exists - run: | - test -f integrations/pi-agent-plugin/dist/index.js || (echo "Build output missing: dist/index.js" && exit 1) - test -f integrations/pi-agent-plugin/dist/index.d.ts || (echo "Build output missing: dist/index.d.ts" && exit 1) - test -f integrations/pi-agent-plugin/dist/entry.js || (echo "Build output missing: dist/entry.js" && exit 1) - test -f integrations/pi-agent-plugin/dist/entry.d.ts || (echo "Build output missing: dist/entry.d.ts" && exit 1) + - name: Verify package artifact + run: python3 integrations/agent-plugin-core/conformance/artifacts.py pi-agent diff --git a/.gitignore b/.gitignore index 01ee55a0c..c950ac598 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,10 @@ server/.env # Distribution / packaging .Python build/ +!integrations/agent-plugin-core/build/ +!integrations/agent-plugin-core/build/*.py +!integrations/agent-plugin-core/build/schemas/ +!integrations/agent-plugin-core/build/schemas/*.json develop-eggs/ dist/ downloads/ diff --git a/.kimi-plugin/marketplace.json b/.kimi-plugin/marketplace.json index faaed4998..8ff2134b4 100644 --- a/.kimi-plugin/marketplace.json +++ b/.kimi-plugin/marketplace.json @@ -5,11 +5,11 @@ { "id": "mem0", "displayName": "Mem0", - "version": "0.1.0", - "description": "Persistent memory for Kimi Code. Remembers decisions, patterns, and preferences across sessions.", + "version": "0.3.1", + "description": "Cross-session memory and token savings for coding agents.", "homepage": "https://mem0.ai", "keywords": ["memory", "personalization", "mcp", "semantic-search"], - "source": "https://github.com/mem0ai/mem0/tree/main/integrations/mem0-plugin" + "source": "https://github.com/mem0ai/mem0/tree/main/integrations/kimi-plugin" } ] } diff --git a/AGENTS.md b/AGENTS.md index d91b8ee7b..ba1b72f47 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,7 +14,7 @@ This is a polyglot monorepo and **every package sets its own rules**. Read the ` - Modify anything in `.github/workflows/` without explicit maintainer approval. Publishing credentials are pinned to workflow filenames. - Commit `.env` files, API keys, or credentials. - Skip pre-commit hooks. -- Use npm or yarn in TypeScript packages. This repo is pnpm-only (Bun in `.opencode-plugin/`). +- Use npm or yarn in TypeScript packages. This repo is pnpm-only (Bun in `integrations/opencode-plugin/`). - Use `require()` in TypeScript. ES module `import` syntax only. - Mix up linter configs. Root Python is ruff at line length **120**, `cli/python/` is ruff at **100**, `cli/node/` is Biome, `mem0-ts/` is Prettier, `integrations/vercel-ai-sdk/` is ESLint. - Add Python dependencies to the core `dependencies` list in `pyproject.toml`. Use an optional group. diff --git a/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdx index db9d06396..454f86964 100644 --- a/docs/changelog/sdk.mdx +++ b/docs/changelog/sdk.mdx @@ -2060,6 +2060,29 @@ A full-featured command-line interface for Mem0, available in both Python and No + + +**Changed:** +- Consolidated the coding-agent integrations into `integrations/agent-plugin-core/`: one Python runtime, one TypeScript utility library, and six canonical Python-plugin skill templates. Native adapters retain each host's event contracts and capabilities. +- Python plugins ship generated, self-contained `core/` and `skills/` directories. Builds validate portable schemas and skills, parse native JSON, and reject generated-file drift, missing files, stale generated files, and symlinks. TypeScript packages bundle the shared source into their distributable JavaScript and verify their entry points. +- Replaced the old `integrations/mem0-plugin/` layout with native host directories and one portable `integrations/mem0-agent-plugin/` package. Updated marketplace paths, installation guides, and integration-skill links. OpenCode now lives in `integrations/opencode-plugin/`. +- Native Python plugins expose one local, read-only `search_memories` MCP tool and six skills: search, remember, forget, status, pause, and resume. The shared search tool no longer accepts `run_id`; session IDs remain internal metadata. This local tool is separate from the hosted Mem0 MCP server's tool set. + +**Fixes:** +- Hooks, controls, MCP servers, and detached workers use the same host-specific data directory. Detached workers retain the host identity and telemetry source; `--plugin-data-dir` reaches the shared resolver. +- Session-end workers flush the conversation already captured by hooks. Repeated and concurrent response hooks no longer duplicate an answer, while identical answers after separate prompts are preserved. +- Shared prompts and responses are redacted without the previous 6,000-character cutoff. Python extraction splits oversized messages without dropping text to enforce each request's input budget. Flush event selection and claims share one write transaction, delayed handoffs are replaced atomically, and permanent HTTP polling errors fail promptly. +- Extraction instructions refer to the current coding agent. Python redaction covers JSON-shaped credentials; both telemetry runtimes recursively remove sensitive keys, including keys inside nested lists. +- 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. +- 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) + + + **Fixes:** @@ -2346,8 +2369,100 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex + + + + +**Changed:** +- Extracted hook orchestration and memory behavior into the shared Python core; Claude transcript parsing remains in its native adapter. The installed package contains the generated runtime rather than importing files outside its plugin directory. +- Preserves the public `mem0` name, hook declarations, MCP launch configuration, user configuration, and `mem0:sidekick` worktree behavior. The manifest and marketplace version advance from `0.3.0` to `0.3.1` so installations can identify the update. + +**Fixes:** +- Session-end extraction no longer appends a final answer already captured from the transcript while an earlier extraction was running. +- Existing repository memories remain searchable after the shared-ID change; explicit shared-memory deletion also covers the legacy ID. Background workers and control skills consistently use Claude's data directory. +- Receives the shared JSON-secret redaction and nested telemetry filtering fixes. The local search tool exposes query, result count, category, and scope without asking the agent for a session ID. + +[#7203](https://github.com/mem0ai/mem0/pull/7203) + + + + + + + + + +**Changed:** +- Moves from the legacy shared editor-plugin directory to a native `integrations/cursor-plugin/` package with generated Python core and skills, Cursor variables, local MCP configuration, and a native Sidekick. +- Translates Cursor conversation/workspace fields, response and summary fields, tool outcomes, and subagent lifecycle events into the shared runtime. The Sidekick searches memory itself because Cursor's subagent-start response cannot inject parent context. + +**Fixes:** +- Adapter errors are logged and exit successfully so a memory failure does not terminate the host hook. Sidekick telemetry reports zero parent-injected context because this host uses self-search. +- Repeated response events and Stop/session-end capture do not duplicate the same answer. +- Receives shared data-directory handling, background-worker identity, redaction, and legacy-memory retrieval fixes. + +[#7203](https://github.com/mem0ai/mem0/pull/7203) + + + + + + + + + +**Changed:** +- Moves from the legacy shared editor-plugin directory to a native `integrations/codex-plugin/` package, with generated Python core and six skills, a local search MCP server, and native lifecycle hooks. +- Resolves MCP repository searches from Codex workspace metadata when supplied. Control skills, hooks, and workers use the same plugin data directory. +- Native subagent start/stop hooks supply parent-retrieved memory context and record completions for every native subagent. Named custom agents remain project/user configuration; the plugin does not distribute a named Codex Sidekick. + +**Fixes:** +- Receives shared credential redaction, legacy-memory retrieval, background-worker identity, and duplicate-response fixes. Codex tool outcomes use available structured failure indicators; missing outcome information is recorded as unknown. + +[#7203](https://github.com/mem0ai/mem0/pull/7203) + + + + + + + + + +**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 claim automatic lifecycle capture or host-specific subagent isolation. + +[#7203](https://github.com/mem0ai/mem0/pull/7203) + + + + + + + +**Changed:** +- Moved the source from `integrations/mem0-plugin/.opencode-plugin/` to `integrations/opencode-plugin/`, retaining the `@mem0/opencode-plugin` package name and native OpenCode hooks. +- Reuses shared conversation preparation, redaction, scoping, and telemetry. Builds a self-contained Bun/ESM `dist/index.js` and publishes its TypeScript entry declaration. +- Global memory tool scope requires the user to enable it in plugin settings first; empty and wildcard identities are rejected. +- Retains the seven commands for context loading, search, remember, forget, scope, status, and tour; bundled skills continue loading through OpenCode's native configuration. + +**Removed:** +- Removed auto-Dream consolidation, its gates and state handling, and the Dream and pin skills/commands. Existing configurations and workflows that use these features must be updated. + +**Builds:** +- Updated build and publish paths for the relocated source directory; the existing release tag prefix and publishing workflow filename are unchanged. + +[#7203](https://github.com/mem0ai/mem0/pull/7203) + + + **Fixes:** @@ -2428,6 +2543,22 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex + + +**Changed:** +- Ships a native package with generated Python core and six skills, a local search MCP server, a Sidekick declaration, and an adapter for `PreInvocation`, `PostToolUse`, and `Stop`. +- Normalizes conversation IDs, transcript paths, workspace paths, tool calls, and errors. The adapter captures all completed user/assistant transcript messages incrementally, including later-turn intent, without replaying earlier messages. +- Sidekick searches Mem0 itself; this plugin does not provide Claude Code's worktree isolation. + +**Fixes and host limitations:** +- Accepts `MEM0_CWD` as an explicit workspace fallback when the host omits `workspacePaths`. Skips capture when neither is available, rather than writing under an unrelated directory. +- Documents global MCP registration with `agy mcp add` when the host does not register the plugin-scoped server. Recall on the initial invocation depends on the host providing a prompt or readable transcript. +- Receives the shared data-directory, redaction, legacy-memory retrieval, and duplicate-response fixes. + +[#7203](https://github.com/mem0ai/mem0/pull/7203) + + + **Fixes:** @@ -2504,6 +2635,24 @@ Existing memories written by the previous versions are not rewritten. If your me + + +**Changed:** +- Ships a self-contained native package with six skills, nine lifecycle hooks, a local search MCP server, and a native Sidekick declaration. Added a dedicated installation and troubleshooting guide. +- Translates Kimi's session, prompt, tool, compaction, shutdown, and subagent events into the shared Python runtime. Sidekicks receive parent memory context through Kimi's native lifecycle. + +**Fixes:** +- Recovers completed assistant output from Kimi's indexed v2 wire transcript when Stop events omit the response text. Repeated Sidekick invocations receive distinct run identifiers. Stops without a host ID are left uncorrelated when multiple matching runs are active, preserving their responses without assigning them to the wrong run. +- Keeps controls, hooks, MCP, and detached workers on the same Kimi data directory and preserves host identity in background workers. +- Receives the shared redaction, legacy-memory retrieval, and duplicate-response fixes. + +**Host compatibility:** +- Documents `CHOKIDAR_USEPOLLING=1` for the observed macOS watcher issue. Filesystem isolation remains Kimi's responsibility. + +[#7203](https://github.com/mem0ai/mem0/pull/7203) + + + **Initial release** of the Mem0 plugin for Kimi Code, sharing its scripts, skills, and marketplace listing with the Claude Code / Cursor / Codex / Antigravity plugin family ([#6919](https://github.com/mem0ai/mem0/pull/6919)) @@ -2520,6 +2669,23 @@ Existing memories written by the previous versions are not rewritten. If your me + + +**Changed:** +- Reuses shared conversation preparation, redaction, and telemetry while retaining OpenClaw's native memory backend, tools, CLI, and Platform/OSS modes. +- Continues to publish a self-contained ESM package under `@mem0/openclaw-mem0`; the plugin manifest and package version now agree. + +**Removed:** +- Removed Dream consolidation: automatic scheduling and locking, `openclaw mem0 dream`, Dream configuration, the memory-dream skill, and Dream-state public artifacts. Triage, recall, and memory/entity artifacts remain available. Update configurations or integrations that use the removed Dream surface. + +**Fixes:** +- `openclaw mem0 status` handles an unconfigured installation without crashing and directs users to setup. +- Telemetry removes sensitive properties recursively and uses the shared failure-safe delivery implementation. + +[#7203](https://github.com/mem0ai/mem0/pull/7203) + + + **Security:** @@ -2790,6 +2956,24 @@ Existing memories written by the previous versions are not rewritten. If your me + + +**Changed:** +- Reuses shared conversation preparation, memory formatting, project/session/global scope utilities, and telemetry while preserving Pi's native extension API and `@mem0/pi-agent-plugin` package name. +- Pi loads the built `dist/entry.js` extension instead of executing source TypeScript from an installed package. Builds also publish the library entry point and declarations. + +**Removed:** +- Removed Dream consolidation and pin commands, skills, configuration, types, and exports. The remaining commands are remember, search, forget, tour, scope, and status. Update integrations that import removed APIs or invoke removed commands. + +**Fixes:** +- Global memory tool scope requires the user to select `/mem0-scope global` or configure a global default first. Empty and wildcard identities are rejected. +- Memory update and delete accept the `mem0:` and `[mem0:]` citations displayed in tool results, as well as raw IDs. +- Shared capture preparation filters conversation roles and redacts content; telemetry removes sensitive keys inside nested structures. + +[#7203](https://github.com/mem0ai/mem0/pull/7203) + + + **Security:** @@ -2885,6 +3069,23 @@ Existing memories written by the previous versions are not rewritten. If your me + + +**Added:** +- Automatic recall during `system-prompt/assemble`, using the latest human prompt and avoiding repeated context injection within a session. +- Automatic capture from the durable `session/event` stream after a completed turn. Interrupted or incomplete turns are not sent through this automatic capture path. `autoRecall` and `autoCapture` default to `true` and can be disabled. + +**Changed:** +- Reuses shared lifecycle, redaction, identity, and telemetry utilities while retaining the explicit `search_memory` and `add_memory` tools and their per-call agent/session scope. Cross-user `userId` overrides now require operator opt-in with `allowUserOverride: true`. +- Publishes a self-contained ESM artifact under `@mem0/deepseek-plugin`; native Harness services and the Mem0 SDK remain external dependencies. Plugin cleanup remains tied to the native Cordis lifecycle. + +**Host compatibility:** +- Supports the declared Harness runtime dependencies and documents the macOS watcher workaround. The plugin does not bundle a named Sidekick or provide child filesystem isolation. + +[#7203](https://github.com/mem0ai/mem0/pull/7203) + + + **New Features:** diff --git a/docs/docs.json b/docs/docs.json index 269cf9426..c1c4887d2 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -373,6 +373,7 @@ "integrations/claude-ai", "integrations/cursor", "integrations/codex", + "integrations/kimi", "integrations/opencode", "integrations/antigravity" ] diff --git a/docs/integrations/antigravity.mdx b/docs/integrations/antigravity.mdx index a3017d2ef..d9229bf2f 100644 --- a/docs/integrations/antigravity.mdx +++ b/docs/integrations/antigravity.mdx @@ -1,16 +1,20 @@ --- title: Antigravity -description: "Add persistent memory to Google Antigravity with the Mem0 plugin: MCP server, lifecycle hooks, and slash commands." +description: "Add persistent memory to Google Antigravity with the Mem0 plugin: a search tool, lifecycle hooks, and memory skills." --- -Add persistent memory to [**Google Antigravity**](https://antigravity.google) (`agy` CLI and Desktop IDE) with the Mem0 plugin. Your agent forgets everything between sessions. Mem0 fixes that by storing decisions, preferences, and learnings so they carry over automatically. +Add persistent memory to [**Google Antigravity**](https://antigravity.google) (`agy` CLI and Desktop IDE) with the Mem0 plugin. The plugin captures completed work, and Antigravity can search those memories in later sessions. + +Current plugin version: `0.3.1`. ## Prerequisites 1. A Mem0 API key (starts with `m0-`): - Get your API key (free sign-up at app.mem0.ai) -2. Add it to your shell profile so it persists across sessions: +2. Python 3.10 or newer available as `python3` + +3. Add the key to your shell profile so it persists across sessions: ```bash zsh @@ -26,22 +30,33 @@ echo 'export MEM0_API_KEY="m0-your-api-key"' >> ~/.bashrc && source ~/.bashrc **Option A: degit** (recommended): + + When upgrading an existing installation, move `~/.gemini/config/plugins/mem0` aside first. Installing over that directory can leave obsolete files from older plugin versions. + + ```bash # Install the plugin (MCP server, hooks, scripts) -npx degit mem0ai/mem0/integrations/mem0-plugin ~/.gemini/config/plugins/mem0 +npx degit mem0ai/mem0/integrations/antigravity-plugin ~/.gemini/config/plugins/mem0 ``` -This installs the MCP server, lifecycle hooks, and shared scripts. +This installs the generated Antigravity bundle with the Mem0 server, lifecycle hooks, and six memory skills. ## What's Included | Component | Included | |-----------|:--------:| -| MCP Server (9 memory tools) | Yes | +| Local MCP Server (`search_memories`) | Yes | | Lifecycle Hooks | Yes | -| 16 Slash Commands | Yes | +| 6 Memory Skills | Yes | +| Sidekick Agent | Yes | -## Available MCP Tools +## Memory tools and skills + +The full plugin exposes a focused `search_memories` tool and captures completed work through lifecycle hooks. Six skills provide search, status, remember, forget, pause, and resume workflows. A native sidekick can handle a bounded task in the workspace assigned by Antigravity; it does not claim Claude Code worktree isolation. + +If you need the full set of direct CRUD tools, connect the [hosted Mem0 MCP server](/platform/mem0-mcp) separately instead of installing both configurations under the same server name. + +## Hosted MCP tools | Tool | Description | |------|-------------| @@ -57,23 +72,46 @@ This installs the MCP server, lifecycle hooks, and shared scripts. ## Lifecycle Hooks -The plugin uses the same shell scripts as Claude Code, Cursor, and Codex: hooks bridge environment variables using `${extensionPath}` (Antigravity's plugin-root token). +The plugin translates Antigravity events into the shared Mem0 capture lifecycle. | Hook | Event | What it does | |------|-------|-------------| -| **Session start** | `SessionStart` | Loads prior memories and displays status banner | -| **User prompt** | `UserPromptSubmit` | Searches relevant memories before each message | -| **Pre-tool** | `PreToolUse` | Blocks MEMORY.md writes, enforces `user_id`/`app_id` on mem0 tools | -| **Post-tool** | `PostToolUse` | Tracks stats, scans bash errors for related memories | -| **Stop** | `Stop` | Stores a session summary at the end of every assistant turn (not just at session end) | +| **Invocation** | `PreInvocation` | Initializes the first invocation and recovers pending capture | +| **Post-tool** | `PostToolUse` | Records useful tool results and failures | +| **Stop** | `Stop` | Captures the completed exchange for a later session | -What you type is stored as yours. What the agent produces (session summaries and compaction summaries) is stored as the assistant's, so its suggestions never become your stated preferences. +Recall is explicit through `search_memories` and the search skill. The current Antigravity adapter does not inject query-specific memory during `PreInvocation` because that event does not include the user's prompt. + +What you type is stored as yours. Captured agent summaries are stored as the assistant's, so its suggestions never become your stated preferences. + +## Antigravity 1.1.25 workarounds + +Antigravity 1.1.25 can validate a plugin's `mcp_config.json` without loading the server. Check whether Mem0 is registered: + +```bash +agy mcp list +``` + +If `mem0` is absent, register the plugin's bundled server with Antigravity's supported global MCP command, then start a new session: + +```bash +agy mcp add mem0 python3 ~/.gemini/config/plugins/mem0/core/mcp_server.py +``` + +The same release can send hooks with an empty `workspacePaths` array. For the `agy` CLI, pass the current repository explicitly: + +```bash +MEM0_CWD="$PWD" agy +``` + +The adapter uses `MEM0_CWD` only when Antigravity omits the workspace. If neither value is available, it skips recall and capture instead of writing memories under an incorrect repository scope. ## Troubleshooting - **No tools appearing**: Restart your Antigravity session after installation -- **"Connection failed"**: Verify your key is set: `echo $MEM0_API_KEY` -- **MCP 401 Unauthorized**: If `${MEM0_API_KEY}` interpolation doesn't work in your `agy` version, replace with your literal key in `mcp_config.json` +- **No `mem0` entry in `agy mcp list`**: Use the Antigravity 1.1.25 global MCP registration command above +- **Hooks do not capture in the CLI**: Launch `agy` with `MEM0_CWD="$PWD"` +- **"Connection failed"**: Verify your key is set without printing it: `test -n "$MEM0_API_KEY" && echo configured` diff --git a/docs/integrations/claude-code.mdx b/docs/integrations/claude-code.mdx index 0dd0b153f..e185758dc 100644 --- a/docs/integrations/claude-code.mdx +++ b/docs/integrations/claude-code.mdx @@ -5,6 +5,8 @@ description: "Persistent cross-session memory for Claude Code. Install once, mem Claude Code forgets everything between sessions. This plugin fixes that. Install it, work normally, and Claude remembers what happened across sessions. +Current plugin version: `0.3.1`. + ## Prerequisites 1. A Mem0 Platform account and API key (starts with `m0-`): @@ -71,6 +73,8 @@ Review its result and send any corrections back to the same sidekick. Changes stay in the sidekick's worktree until the main agent reviews and copies them over. By default the worktree branches from the repo's default branch. Set `worktree.baseRef` to `"head"` in your Claude settings to branch from the current commit instead. Uncommitted changes are not copied into the sidekick's worktree. +At startup, Sidekick receives the memories already recalled for its parent session. It can also call the Mem0 search tool for its assigned task. Start and completion hooks track its work locally; completing a Sidekick task does not independently send a memory-extraction request. Sidekick returns its result, validation, and a local commit when it changes files, so the main agent can review the work before incorporating it. + ## How it works The plugin follows a simple cycle: capture during a session, extract memories in the background, recall in the next session. @@ -81,11 +85,11 @@ The plugin follows a simple cycle: capture during a session, extract memories in **Step by step:** -1. **Capture.** Hooks save the main agent's activity locally: user messages, Claude's answers, changed files, and short test/build results. Subagent (sidekick) output is excluded. No model calls, no blocking. +1. **Capture.** Hooks save the main agent's activity locally: user messages, Claude's answers, changed files, and short test/build results. Direct Sidekick lifecycle records stay local. Subagent results included in the main transcript can provide supporting evidence for extraction; the main agent's final response establishes the outcome. Capture does not call a model. 2. **Flush.** After every five completed exchanges, a detached background worker sends that batch to Mem0. Large exchanges flush sooner. Ending or compacting the session flushes anything remaining. If the session sits idle, an auto-flush runs after five minutes (configurable with `MEM0_CODE_IDLE_FLUSH_SECONDS`). The timer resets on each new exchange. The worker survives Claude Code exiting. -3. **Extract.** Each flush sends a single `add` call with `agent_id` (the project identity), `user_id` (you), `app_id` (the repository), and `run_id` (the session). Mem0 classifies each extracted memory as shared project knowledge or a personal preference. +3. **Extract.** Each flush sends `add` calls with `agent_id` (the project identity), `user_id` (you), `app_id` (the repository), and `run_id` (the session). Prompts and responses are redacted without a character cutoff. Large conversations are split across requests without dropping message text. Mem0 classifies each extracted memory as shared project knowledge or a personal preference. 4. **Recall.** On the next session's first prompt, the plugin searches automatically and supplies up to five relevant memories. No model is called to write the query. @@ -110,10 +114,14 @@ Every memory carries identifiers showing where it came from: | Identifier | What it is | Example | | --- | --- | --- | | `user_id` | You (personal memory only) | Your Mem0 user ID | -| `agent_id` | The project identity (shared memory only) | `acme-payments-api` | +| `agent_id` | The project identity (shared memory only) | `acme-payments-api-` | | `app_id` | The repository (scopes both lanes) | `acme-payments-api` | | `run_id` | The Claude Code session | The session ID | +New Git repository memories use an `agent_id` with a hash of the Git remote identity so matching owner/repository names on different hosts stay separate. Searches also include the previous unhashed `agent_id`, scoped by the repository's `app_id`, so existing shared memories remain available after upgrading. Those older memories retain their original namespace, which did not distinguish Git hosts. Local folders continue using a hash of their path. + +Explicitly forgetting shared project memory with `--include-project-memory` covers both repository IDs. Without that option, shared memories are preserved. + A search returns the union of shared project memory and your personal preferences. The scope narrows the project part: | Scope | What you get | @@ -124,7 +132,7 @@ A search returns the union of shared project memory and your personal preference The `dir` scope is hierarchical: a parent directory sees everything in its children, but a child never sees the parent's memories. -Pass `--run-id ` to see only what one specific session recorded. Set the default scope with the `search_scope` setting or `MEM0_CODE_SEARCH_SCOPE` env var. +The search tool accepts an optional `run_id` with every scope (`repo`, `dir`, and `mine`); `/mem0:search` exposes it as `--run-id session-id`. It restricts both shared and personal results to memories saved in that coding-agent session. Omit it to search across sessions. This is a memory filter, not a label for the session making the request; automatically filtering by the current session would hide earlier-session memories. Each memory update still records the session's `run_id`. Set the default scope with the `search_scope` setting or `MEM0_CODE_SEARCH_SCOPE` env var. ## Settings diff --git a/docs/integrations/codex.mdx b/docs/integrations/codex.mdx index 7b2be4b55..33f09b16c 100644 --- a/docs/integrations/codex.mdx +++ b/docs/integrations/codex.mdx @@ -1,9 +1,11 @@ --- title: Codex -description: "Add persistent memory to OpenAI Codex with the Mem0 plugin: MCP server, lifecycle hooks, and SDK skill." +description: "Add persistent memory to OpenAI Codex with automatic capture, automatic recall, a search tool, and six memory skills." --- -Add persistent memory to [**OpenAI Codex**](https://openai.com/codex/) with the Mem0 plugin. Codex forgets everything between tasks. This plugin fixes that by connecting to Mem0's cloud memory layer via MCP, automatically capturing learnings at key lifecycle points, and retrieving relevant context before every response. +Add persistent memory to [**OpenAI Codex**](https://openai.com/index/codex/) with the Mem0 plugin. Codex forgets everything between tasks. This plugin fixes that by connecting to Mem0's cloud memory layer via MCP, automatically capturing learnings at key lifecycle points, and retrieving relevant context before every response. + +Current plugin version: `0.3.1`. ## Prerequisites @@ -15,7 +17,9 @@ Before setting up Mem0 with Codex, ensure you have: 2. OpenAI Codex access -3. Your API key added to your shell profile (persists across sessions): +3. Python 3.10 or newer available as `python3` + +4. Your API key added to your shell profile (persists across sessions): ```bash zsh @@ -33,7 +37,7 @@ source ~/.bashrc ### Option A: Plugin Marketplace (Recommended) -Install the full plugin including MCP server, lifecycle hooks, and SDK skill. +Install the full plugin, including automatic capture and recall, the `search_memories` tool, and six memory skills. 1. Add the Mem0 marketplace: @@ -88,7 +92,7 @@ codex plugin marketplace remove mem0-plugins # unregister the marketplace enti To update, run `codex plugin marketplace upgrade` to pull the latest from the Mem0 repo. - After either option, start a new Codex task and ask: *"List my mem0 entities"* or *"Search my memories for hello"*. If the `mem0` tools appear and respond, you're all set. + After Option A, ask Codex to search memory for a recent project decision. After Option B, ask it to list your Mem0 entities. If the matching tool responds, the connection is ready. ## Codex Cloud @@ -106,13 +110,16 @@ Lifecycle hooks that shell out to local scripts (Option A) are not applicable in | Component | Plugin Install | MCP Only | |-----------|:--------------:|:--------:| -| MCP Server (9 memory tools) | Yes | Yes | -| Lifecycle Hooks | Opt-in (see below) | No | -| Mem0 SDK Skill | Yes | No | +| Memory tools | `search_memories` | 9 CRUD tools | +| Lifecycle hooks | Yes | No | +| Native subagent memory lifecycle | Yes | No | +| Memory skills | 6 | No | -## Available MCP Tools +Codex plugins cannot currently bundle a named custom agent. If you define project or user agents under `.codex/agents/` or `~/.codex/agents/`, the full Mem0 plugin gives every native subagent the parent turn's retrieved memory context and records its completed result. -Once installed, the following tools are available in every Codex session: +## Direct MCP tools + +Option B exposes the following hosted tools. The full plugin in Option A uses the focused `search_memories` tool and captures writes through lifecycle hooks. | Tool | Description | |------|-------------| @@ -126,33 +133,20 @@ Once installed, the following tools are available in every Codex session: | `delete_entities` | Delete a user/agent/app/run entity and its memories | | `list_entities` | List users/agents/apps/runs stored in Mem0 | -## Lifecycle Hooks +## Lifecycle hooks -Unlike Claude Code, Codex has no plugin-host mechanism for auto-wiring hooks from an installed plugin: it only reads hooks from `~/.codex/hooks.json` (or `/.codex/hooks.json`). Installing the plugin (Option A) does **not** turn hooks on by itself. To enable them, run the bundled installer once against your local clone: - -```bash -python3 /integrations/mem0-plugin/scripts/install_codex_hooks.py -``` - -This merges Mem0's entries into `~/.codex/hooks.json` and is idempotent (safe to re-run after upgrading). It also requires the `codex_hooks` feature flag in `~/.codex/config.toml`: - -```toml -[features] -codex_hooks = true -``` - -The installer prints a reminder if the flag isn't set. Restart Codex after installing hooks or editing the config. To remove: `python3 .../install_codex_hooks.py --uninstall`. - -Once enabled, Mem0 hooks into Codex's lifecycle to automatically manage memory: +Option A registers the hooks with the plugin. No separate hook installer or global `hooks.json` edit is required. | Hook | Event | What it does | |------|-------|-------------| | **Session start** | `SessionStart` | Loads prior memories and displays status banner | | **User prompt** | `UserPromptSubmit` | Searches relevant memories before each message | -| **Pre-tool (3 handlers)** | `PreToolUse` | Blocks MEMORY.md writes; enforces `user_id`/`app_id` on mem0 tool calls; scans files being read for relevant memory context | -| **Post-tool** | `PostToolUse` | Tracks stats, scans bash errors for related memories | -| **Stop** | `Stop` | Stores a session summary at the end of every assistant turn (not just at session end) | -| **Pre-compact** | `PreCompact` | Stores a summary before the context is compacted | +| **Post-tool** | `PostToolUse` | Records useful tool outcomes for the completed exchange | +| **Subagent start** | `SubagentStart` | Reuses the parent turn's retrieved memory context in the child | +| **Subagent stop** | `SubagentStop` | Records the child transcript path and completed result | +| **Stop** | `Stop` | Captures completed work and starts a background flush when needed | +| **Pre-compact** | `PreCompact` | Flushes pending capture before context compaction | +| **Session end** | `SessionEnd` | Flushes any remaining capture in the background | What you type is stored as yours. What Codex produces (session summaries and compaction summaries) is stored as the assistant's, so its suggestions never become your stated preferences. @@ -181,7 +175,7 @@ You: Add WebSocket support for real-time notification delivery. - **"Connection failed"**: Verify `MEM0_API_KEY` is set: `echo $MEM0_API_KEY` - **No tools appearing**: Restart your Codex session after installation - **Duplicate `mem0` MCP / "tool collision" errors**: You combined Option A with Option B. Remove the `[mcp_servers.mem0]` block from `~/.codex/config.toml`; the plugin registers it automatically -- **Hooks not firing**: Hooks are opt-in and are not installed by the marketplace install itself. Run `scripts/install_codex_hooks.py` (see [Lifecycle Hooks](#lifecycle-hooks)), confirm `codex_hooks = true` is set under `[features]` in `~/.codex/config.toml`, and restart Codex. MCP-only installs (Option B) never include hooks +- **Hooks not firing**: Confirm you installed Option A and restart Codex. MCP-only installs (Option B) do not include hooks. diff --git a/docs/integrations/cursor.mdx b/docs/integrations/cursor.mdx index 03486853b..df54d27dc 100644 --- a/docs/integrations/cursor.mdx +++ b/docs/integrations/cursor.mdx @@ -1,9 +1,11 @@ --- title: Cursor -description: "Add persistent memory to Cursor with the Mem0 MCP server for context-aware coding." +description: "Add persistent memory to Cursor with automatic capture, explicit recall, a search tool, and six memory skills." --- -Add persistent memory to [**Cursor**](https://cursor.com) with the Mem0 MCP server. Your AI assistant forgets everything between sessions. Mem0 fixes that by connecting Cursor to Mem0's cloud memory layer via MCP so you can save and retrieve relevant context during coding sessions. +Add persistent memory to [**Cursor**](https://cursor.com) with the Mem0 plugin. Cursor captures completed work in the background, and its agent can search relevant project context in later sessions. You can also connect only the hosted MCP server when you do not need lifecycle capture. + +Current plugin version: `0.3.1`. ## Prerequisites @@ -15,7 +17,9 @@ Before setting up Mem0 with Cursor, ensure you have: 2. Cursor installed ([cursor.com](https://cursor.com)) -3. Your API key added to your shell profile (persists across sessions): +3. Python 3.10 or newer available as `python3` + +4. Your API key added to your shell profile (persists across sessions): ```bash zsh @@ -35,13 +39,25 @@ source ~/.bashrc ## Installation -### Option A: One-Click Deeplink (MCP Only) +### Option A: Full Plugin (Recommended) + +Add the Mem0 marketplace: + +```bash +cursor-agent plugin marketplace add https://github.com/mem0ai/mem0 +``` + +Open Cursor's **Customize** page or run `/plugins`, select the **Mem0 Plugins** marketplace, and install **Mem0** at user or project scope. Enter your Mem0 API key when Cursor asks for the plugin configuration, then restart Cursor. + +The full plugin includes automatic capture, the `search_memories` recall tool, lifecycle hooks, a sidekick agent, and six memory skills. + +### Option B: One-Click Deeplink (MCP Only) The fastest way to get started. Click the link below to install the Mem0 MCP server directly in Cursor: [Install Mem0 MCP in Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=mem0&config=eyJtY3BTZXJ2ZXJzIjp7Im1lbTAiOnsidXJsIjoiaHR0cHM6Ly9tY3AubWVtMC5haS9tY3AvIiwiaGVhZGVycyI6eyJBdXRob3JpemF0aW9uIjoiVG9rZW4gJHtlbnY6TUVNMF9BUElfS0VZfSJ9fX19) -### Option B: npx (MCP Only) +### Option C: npx (MCP Only) ```bash npx mcp-add \ @@ -51,7 +67,7 @@ npx mcp-add \ --clients "cursor" ``` -### Option C: Manual Configuration (MCP Only) +### Option D: Manual Configuration (MCP Only) Add the following to your `.cursor/mcp.json`: @@ -73,9 +89,20 @@ Add the following to your `.cursor/mcp.json`: -## Available MCP Tools +## What's included -Once installed, the following tools are available in every Cursor session: +| Component | Full plugin | MCP only | +| --- | :---: | :---: | +| Memory tools | `search_memories` | 9 CRUD tools | +| Automatic capture | Yes | No | +| Recall | `search_memories` | MCP search tools | +| Lifecycle hooks | Yes | No | +| Memory skills | 6 | No | +| Sidekick agent | Yes | No | + +## MCP-only tools + +Options B, C, and D expose the following hosted tools. The full plugin uses the focused `search_memories` tool and captures writes through lifecycle hooks. | Tool | Description | |------|-------------| @@ -89,6 +116,25 @@ Once installed, the following tools are available in every Cursor session: | `delete_entities` | Delete a user/agent/app/run entity and its memories | | `list_entities` | List users/agents/apps/runs stored in Mem0 | +## Lifecycle hooks + +The full plugin translates Cursor's native events into the shared Mem0 memory lifecycle: + +| Cursor event | What Mem0 does | +| --- | --- | +| `sessionStart` | Initializes the project session and recovers pending capture | +| `beforeSubmitPrompt` | Observes the submitted prompt; recall stays tool-driven because this event cannot inject context | +| `postToolUse` / `postToolUseFailure` | Records useful tool results and failures | +| `subagentStart` / `subagentStop` | Records the Mem0 Sidekick lifecycle and completed result | +| `afterAgentResponse` / `stop` | Captures the completed exchange | +| `preCompact` / `sessionEnd` | Flushes pending capture in the background | + + + Cursor's `beforeSubmitPrompt` hook can allow or block a prompt, but it cannot add context to that prompt. The plugin therefore gives the agent `search_memories` and a memory-aware sidekick for recall instead of claiming automatic per-prompt injection. + + +Cursor's `subagentStart` hook also cannot inject parent context. The bundled Sidekick searches Mem0 itself, while the lifecycle hooks correlate its start and completion for later capture. + ## Example Workflow ```text @@ -112,7 +158,7 @@ You: The /orders endpoint is also slow, same pattern as before. ## Troubleshooting - **"Connection failed"**: Verify `MEM0_API_KEY` is set: `echo $MEM0_API_KEY` -- **Duplicate tools**: If you had a previous MCP config for `mem0`, remove it before installing the plugin +- **Duplicate tools**: Do not combine the full plugin with an MCP-only option. Remove the standalone `mem0` MCP entry before installing the plugin. - **No tools appearing**: Go to Cursor Settings > MCP and verify the `mem0` server shows as connected diff --git a/docs/integrations/deepseek-plugin.mdx b/docs/integrations/deepseek-plugin.mdx index f26b08b23..1a9f98a6d 100644 --- a/docs/integrations/deepseek-plugin.mdx +++ b/docs/integrations/deepseek-plugin.mdx @@ -1,16 +1,20 @@ --- title: DeepSeek Harness -description: "Add persistent Mem0 memory to the DeepSeek Harness (Cordis) agent with two native tools: search and add." +description: "Add persistent memory to DeepSeek Harness with automatic recall, automatic capture, and two native Mem0 tools." --- -Add persistent memory to the [**DeepSeek Harness**](https://github.com/deepseek-ai/deepseek-harness) with `@mem0/deepseek-plugin`. The Harness agent forgets everything between sessions. This plugin gives it two Mem0-backed tools so recall and writes persist across runs, sharing the same memory bank you already use from Claude Code, Codex, and other agents. +Add persistent memory to the [**DeepSeek Harness**](https://github.com/deepseek-ai/deepseek-harness) with `@mem0/deepseek-plugin`. The plugin recalls relevant context before a model request, captures completed turns, and provides explicit Mem0 tools when the agent needs them. + +Current package version: `0.3.0`. ## Overview -The plugin registers two agent-callable tools: +The plugin provides automatic memory plus two agent-callable tools: -| Tool | Does | +| Capability | What it does | |---|---| +| Automatic recall | Searches with the latest human prompt and adds unseen results to the model context | +| Automatic capture | Stores the human and assistant messages from each completed turn | | `search_memory` | Recall facts from Mem0 relevant to a query | | `add_memory` | Store a fact in Mem0 for future sessions | @@ -18,7 +22,15 @@ Unlike file-based memory plugins, Mem0 is a managed backend: server-side extract ## How it works -A Cordis plugin is a module exporting `apply(ctx, config)`. This one declares `inject = ['tools']` so it waits for the harness tool registry, then registers the two tools via `ctx.tools.register(...)`. When the plugin unmounts, the tools are removed automatically (Cordis revertible effects). +A Cordis plugin is a module exporting `apply(ctx, config)`. This plugin waits for the Harness tool and system-prompt services, then uses their native extension points: + +- `system-prompt/assemble` recalls memory before a model request. +- `session/event` captures only completed turns from the durable event stream. +- `ctx.tools.register(...)` exposes explicit search and add tools. + +Cordis removes the listeners and tools when the plugin unmounts. Memory failures are fail-open, so a Mem0 outage does not stop the agent from completing its normal work. + +DeepSeek Harness provides subagents through separate host-composition packages. This Mem0 package does not register a named Sidekick or claim child filesystem isolation. A Harness child uses Mem0 only when its own agent preset includes the Mem0 plugin. ## Prerequisites @@ -44,19 +56,28 @@ source ~/.bashrc ## Try it locally -1. Build the plugin: +1. Build and pack the plugin: ```sh cd integrations/deepseek-plugin - pnpm install + pnpm install --frozen-lockfile pnpm build + mkdir -p /tmp/mem0-deepseek-plugin + pnpm pack --pack-destination /tmp/mem0-deepseek-plugin ``` -2. Point the Harness at it. Copy `cordis.example.yml`, set the absolute path to `dist/index.js` and your `userId`, then load it: +2. Install it into a disposable Harness profile so Harness supplies its peer dependencies: ```sh - pnpm dsh web --patch ./integrations/deepseek-plugin/cordis.example.yml + DSH_HOME=/tmp/mem0-dsh-dev pnpm dlx @deepseek-ai/dsh@0.1.1-rc.2 \ + plugin --profile headless add /tmp/mem0-deepseek-plugin/mem0-deepseek-plugin-0.3.0.tgz ``` -3. Open the web UI and ask the agent to remember something, then recall it in a later turn. +3. Copy `cordis.example.yml`, set its installed package path and your `userId`, then load it with the same profile: + ```sh + DSH_HOME=/tmp/mem0-dsh-dev pnpm dlx @deepseek-ai/dsh@0.1.1-rc.2 \ + web --patch ./integrations/deepseek-plugin/cordis.example.yml + ``` + +4. Open the web UI and ask the agent to remember something, then recall it in a later turn. The `cordis.yml` entry looks like this: @@ -65,10 +86,12 @@ The `cordis.yml` entry looks like this: - name: "@deepseek-ai/dsh-tools" - insert: - id: mem0 - name: "/absolute/path/to/integrations/deepseek-plugin/dist/index.js" + name: "/tmp/mem0-dsh-dev/profiles/headless/node_modules/@mem0/deepseek-plugin/dist/index.js" config: # apiKey is read from MEM0_API_KEY when omitted here. userId: "your-user-id" + autoRecall: true + autoCapture: true # host: "https://your-onprem.mem0.ai" # optional: Platform on-prem / dedicated base URL ``` @@ -80,10 +103,25 @@ For a Mem0 Platform on-prem or dedicated deployment, point `config.host` at that |---|---|---|---| | `apiKey` | no | `$MEM0_API_KEY` | Mem0 platform API key | | `userId` | yes | | Default entity that owns the memories | +| `allowUserOverride` | no | `false` | Permit model-selected access to a different user only in a trusted multi-user deployment | | `host` | no | `api.mem0.ai` | Platform base URL (on-prem / dedicated) | +| `autoRecall` | no | `true` | Recall relevant memory before model requests | +| `autoCapture` | no | `true` | Store completed human and assistant turns | Both tools also accept optional per-call `userId`, `agentId`, and `runId` params so a single install can partition memory by entity, agent, or session; when omitted they fall back to the configured `userId`. ## Telemetry -Writes are tagged `source="DEEPSEEK_HARNESS"` so Mem0's backend can attribute usage to this integration. +Writes are tagged `source="DEEPSEEK_HARNESS"` so Mem0 can attribute usage to this integration. Anonymous usage events include operation names, durations, result counts, and coarse failure kinds. Queries, memory text, entity IDs, and API keys are never included. Set `MEM0_TELEMETRY=false` to opt out. + + + This plugin is a developer preview and tracks the evolving DeepSeek Harness plugin API. + + +## Troubleshooting + +- **`MISSING_CREDENTIAL` for `deepseek-official`**: Configure `DEEPSEEK_API_KEY` through Harness's Models page or export it in the shell that launches Harness. +- **`EMFILE: too many open files, watch` on macOS**: Launch Harness with `CHOKIDAR_USEPOLLING=1`. +- **Mem0 tools do not appear**: Run Harness with `--dump-config` and confirm the final composition contains the `mem0` row and the installed `dist/index.js` path. + +Per-call `userId` overrides are rejected unless the operator enables `allowUserOverride: true`. Automatic recall and capture always use the configured user. diff --git a/docs/integrations/kimi.mdx b/docs/integrations/kimi.mdx new file mode 100644 index 000000000..9b66d7603 --- /dev/null +++ b/docs/integrations/kimi.mdx @@ -0,0 +1,109 @@ +--- +title: Kimi Code +description: "Add persistent project memory to Kimi Code with automatic capture, automatic recall, Mem0 skills, and tools." +--- + +Kimi Code forgets project decisions between sessions. The Mem0 plugin captures completed work, recalls relevant context before a response, and gives Kimi explicit memory tools and skills. + +Current plugin version: `0.3.1`. + +## Prerequisites + +1. A Mem0 Platform account and API key: + - [Sign up at app.mem0.ai](https://app.mem0.ai?utm_source=oss&utm_medium=integration-kimi) + - [Get your API key](https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=integration-kimi) (starts with `m0-`) + +2. [Kimi Code](https://www.kimi.com/code) with plugin support. + +3. Python 3.10+ and Git on your machine. + +## Quick start + +Export the key in the shell where you start Kimi Code: + +```bash +export MEM0_API_KEY='your-mem0-api-key' +kimi +``` + +Inside Kimi Code, install the native plugin bundle and reload the session: + +```text +/plugins install https://github.com/mem0ai/mem0/tree/main/integrations/kimi-plugin +/reload +``` + +Run `/plugins info mem0` to confirm that the plugin, MCP server, skills, hooks, and sidekick agent loaded. + +## What you get + +- **Automatic capture:** Kimi records completed exchanges locally and flushes durable project knowledge to Mem0 in the background. +- **Automatic recall:** Relevant memories are added before Kimi answers the first prompt in a session. +- **Explicit search:** Kimi can call `search_memories` when it needs a more specific answer. +- **Six memory skills:** Search, status, remember, forget, pause, and resume use the same memory behavior as the other Mem0 coding-agent plugins. +- **Project scoping:** Memories stay attached to the repository, with separate personal and shared project lanes. +- **Kimi sidekick:** A focused subagent can investigate or implement a bounded task in a separate context. Filesystem isolation depends on the environment Kimi provides. + +Credentials are redacted before memory capture. If Mem0 is unavailable, hooks fail open so Kimi can continue its normal work. + +## How it works + +Kimi's native lifecycle events are translated into the shared Mem0 memory lifecycle: + +| Kimi event | What Mem0 does | +| --- | --- | +| `SessionStart` | Loads recent project context | +| `UserPromptSubmit` | Searches for relevant memories before the response | +| `PostToolUse` / `PostToolUseFailure` | Records useful tool results and failures | +| `Stop` | Captures the completed exchange | +| `PreCompact` / `SessionEnd` | Flushes pending capture in the background | +| `SubagentStart` / `SubagentStop` | Passes parent context to the Mem0 sidekick and records its lifecycle | + +## Verify the plugin + +In one session, say: + +```text +Remember exactly: the release codename for this repository is ORCHID-9274. +``` + +Start a new Kimi session in the same repository and ask: + +```text +What is the release codename for this repository? Do not infer it from repository files. +``` + +Kimi should return `ORCHID-9274` from memory. + +## Managing the plugin + +```text +/plugins list +/plugins info mem0 +/plugins disable mem0 +/plugins enable mem0 +/plugins remove mem0 +``` + +Run `/reload` or start a new session after enabling, disabling, or reinstalling the plugin. + +## Troubleshooting + +| Problem | Fix | +| --- | --- | +| Missing API key | Start Kimi from a shell where `MEM0_API_KEY` is exported. | +| Plugin changes do not appear | Run `/plugins reload`, then `/reload` or `/new`. | +| MCP server is disabled | Run `/plugins mcp enable mem0 mem0`, then `/reload`. | +| No memory in a later session | Wait a moment for the background flush, then ask Kimi to search memory explicitly. | +| Remove the plugin | Run `/plugins remove mem0`. | + + + + Add the same persistent project memory to Cursor + + + Use Mem0 with Claude Code and its isolated sidekick + + + + diff --git a/docs/integrations/openclaw.mdx b/docs/integrations/openclaw.mdx index f2fb49b1c..501900de6 100644 --- a/docs/integrations/openclaw.mdx +++ b/docs/integrations/openclaw.mdx @@ -5,6 +5,8 @@ description: "Add long-term memory to OpenClaw agents using the Mem0 plugin with Add long-term memory to [OpenClaw](https://github.com/openclaw/openclaw) agents with the `@mem0/openclaw-mem0` plugin. Your agent forgets everything between sessions. This plugin fixes that by automatically watching conversations, extracting what matters, and bringing it back when relevant. +Current package version: `1.1.0`. + ## Overview @@ -14,11 +16,12 @@ Add long-term memory to [OpenClaw](https://github.com/openclaw/openclaw) agents The plugin provides: 1. **Triage**: The agent extracts durable facts from conversations using a structured protocol with importance gates and domain overlays 2. **Recall**: Before each turn, relevant memories are retrieved with reranking and injected into context -3. **Dream**: Periodic memory consolidation merges duplicates, resolves conflicts, prunes stale entries -4. **Agent Tools**: Eight tools for explicit memory operations during conversations +3. **Agent Tools**: Eight tools for explicit memory operations during conversations Skills mode, `autoRecall`, and `autoCapture` are all enabled by default during `openclaw mem0 init`. +Automatic capture preserves the full text of selected user and assistant messages after noise filtering and secret redaction, without a per-message character cutoff. It selects recent messages and earlier work summaries; it does not capture every message in the conversation. + ## Requirements Check your OpenClaw version: @@ -101,7 +104,7 @@ You no longer need manual config editing to get started. Everything happens insi -That's it. No API key, no config file editing, no environment variables. The plugin is now active with skills-based memory (triage, recall, and dream) running automatically. +That's it. No API key, no config file editing, no environment variables. The plugin is now active with skills-based memory (triage and recall) running automatically. The chat flow uses the same underlying config as manual setup: it writes `apiKey`, `userId`, and `skills` config into `openclaw.json` for you. You can still open the file to inspect or override values afterward. @@ -142,7 +145,6 @@ That's it. No API key, no config file editing, no environment variables. The plu "keywordSearch": true, "identityAlwaysInclude": true }, - "dream": { "enabled": true }, "domain": "companion" } } @@ -441,7 +443,7 @@ If `openclaw plugins update` fails: ### Auto-Capture and Auto-Recall -Auto-capture and auto-recall are **enabled by default**. When skills mode is configured (the default after `openclaw mem0 init`), these are ignored in favor of the skills-based triage/recall/dream protocol. +Auto-capture and auto-recall are **enabled by default**. When skills mode is configured (the default after `openclaw mem0 init`), these are ignored in favor of the skills-based triage and recall protocol. To disable either: @@ -464,13 +466,12 @@ The agent can always use memory tools (`memory_add`, `memory_search`, etc.) expl ### Credential Protection -The plugin never stores API keys, tokens, or secrets as memories. Five independent layers enforce this: +The plugin never stores API keys, tokens, or secrets as memories. Four independent layers enforce this: 1. **Triage gate**: The extraction prompt rejects values matching known credential patterns (`sk-`, `m0-`, `ghp_`, `AKIA`, `Bearer`, `password=`, `token=`, `secret=`) -2. **Dream cleanup**: Periodic memory consolidation deletes any memories that slipped through containing credential patterns -3. **Extraction instructions**: Default extraction rules explicitly instruct the model to store only that a credential was configured, never the value -4. **Configurable patterns**: Add custom credential patterns via `skills.triage.credentialPatterns` -5. **CLI redaction**: `openclaw mem0 config show` redacts sensitive fields (`apiKey`, `oss.*.config.apiKey`) +2. **Extraction instructions**: Default extraction rules explicitly instruct the model to store only that a credential was configured, never the value +3. **Configurable patterns**: Add custom credential patterns via `skills.triage.credentialPatterns` +4. **CLI redaction**: `openclaw mem0 config show` redacts sensitive fields (`apiKey`, `oss.*.config.apiKey`) ### API Key Storage diff --git a/docs/integrations/opencode.mdx b/docs/integrations/opencode.mdx index 8593232fb..6c6ff5470 100644 --- a/docs/integrations/opencode.mdx +++ b/docs/integrations/opencode.mdx @@ -5,6 +5,8 @@ description: "Add persistent memory to OpenCode with the Mem0 plugin: native SDK Add persistent memory to [**OpenCode**](https://opencode.ai) with the Mem0 plugin. Your agent forgets everything between sessions. Mem0 fixes that by storing decisions, preferences, and learnings so they carry over automatically. +Current package version: `0.3.0`. + ## Prerequisites 1. A Mem0 API key (starts with `m0-`): @@ -33,7 +35,7 @@ opencode plugin @mem0/opencode-plugin **Or let your agent do it**: paste this into OpenCode: ``` -Install @mem0/opencode-plugin by following https://raw.githubusercontent.com/mem0ai/mem0/main/integrations/mem0-plugin/.opencode-plugin/README.md +Install @mem0/opencode-plugin by following https://raw.githubusercontent.com/mem0ai/mem0/main/integrations/opencode-plugin/README.md ``` This adds the plugin to your `~/.config/opencode/opencode.json`. Restart OpenCode. You get the native memory tools, lifecycle hooks, and all `/mem0-*` slash commands. The memory tools are registered by the plugin itself via the `mem0ai` SDK. No MCP server to configure. @@ -61,9 +63,9 @@ If you only need the memory tools without the plugin's hooks or skills, point Op | Component | Plugin (A) | Standalone MCP (B) | |-----------|:----------:|:------------------:| -| 9 memory tools | Native (SDK) | Remote MCP server | +| 10 memory tools | Native (SDK) | 9 remote MCP tools | | Lifecycle Hooks | Yes | No | -| 9 Skills | Yes | No | +| 7 Skills | Yes | No | ## Available Memory Tools @@ -78,6 +80,7 @@ If you only need the memory tools without the plugin's hooks or skills, point Op | `delete_all_memories` | Bulk delete all memories in scope | | `delete_entities` | Delete a user/agent/app/run entity and its memories | | `list_entities` | List users/agents/apps/runs stored in Mem0 | +| `get_event_status` | Check the processing status of an asynchronous memory event | ## Memory scope @@ -87,9 +90,9 @@ If you only need the memory tools without the plugin's hooks or skills, point Op |-------|-------|--------| | `project` *(default)* | this repo (`user_id` + `app_id`) | this repo | | `session` | this run only (`+ run_id`) | this run | -| `global` | **all your projects in the workspace** (`app_id: "*"`) | user-wide | +| `global` | **all your projects in the workspace** (filtered by your user ID) | user-wide | -Ask naturally, for example, *"search my memories across all my projects"*. The agent passes `scope: "global"`. For normal questions it stays scoped to the current project automatically. +Select `/mem0-scope global` before requesting a cross-project tool operation. A tool cannot enable global scope by supplying an argument alone. Switch back with `/mem0-scope project` when finished. To change the **default** scope (used when no scope is passed), run the `/mem0-scope` skill: @@ -117,31 +120,12 @@ The plugin uses the [mem0ai](https://www.npmjs.com/package/mem0ai) TypeScript SD | `experimental.session.compacting` | **Compaction** | Stores session state memory, then injects prior memories into compaction context so nothing is lost | | `shell.env` | **Shell env** | Exports `MEM0_USER_ID`, `MEM0_APP_ID`, `MEM0_SESSION_ID`, and `MEM0_BRANCH` to all shell executions | -## Auto-dream (memory consolidation) - -The plugin can automatically consolidate stored memories by merging duplicates, dropping stale/sensitive entries, and rewriting vague ones. This keeps your memory set clean over time. It runs at most once per session, and only when **all** gates pass: - -- **Time**: at least `minHours` (default 24) since the last consolidation -- **Sessions**: at least `minSessions` (default 5) sessions since then -- **Memories**: at least `minMemories` (default 20) stored for the project - -A filesystem lock (`~/.mem0/mem0-dream.lock`) keeps two sessions from consolidating at once. Tune the thresholds with a `dream` block in `~/.mem0/settings.json`, or disable entirely with `MEM0_DREAM=false`: - -```json -{ - "dream": { "enabled": true, "auto": true, "minHours": 24, "minSessions": 5, "minMemories": 20 } -} -``` - -If auto-dream hasn't run yet, it's almost always because a gate hasn't been met (most often too few memories). Run `/mem0-status` to see the exact gate progress (e.g. `sessions 2/5, memories 3/20`), `/mem0-dream` to consolidate **now** regardless of the gates, or lower the thresholds above. - ## Troubleshooting - **No tools appearing**: Restart OpenCode after installing - **"Connection failed"**: Verify your key is set: `echo $MEM0_API_KEY` - **Plugin not loading**: Run `opencode plugin @mem0/opencode-plugin` again, then restart - **Hooks not firing**: Hooks require the plugin install (Option A). MCP-only installs don't include hooks. -- **Auto-dream never runs**: It's gated (time + sessions + memories). Run `/mem0-status` to see which gate is blocking, or `/mem0-dream` to consolidate now. - **Wrong project name / memories not found**: The project id comes from your git remote; launch OpenCode from inside the repo (not your home directory). Check the resolved id with `/mem0-status`. diff --git a/docs/integrations/pi-agent.mdx b/docs/integrations/pi-agent.mdx index e377131da..e743bc7a9 100644 --- a/docs/integrations/pi-agent.mdx +++ b/docs/integrations/pi-agent.mdx @@ -1,19 +1,20 @@ --- title: Pi Agent -description: "Add persistent memory to Pi Agent with the Mem0 plugin semantic search, auto-capture, and dream consolidation." +description: "Add persistent memory to Pi Agent with the Mem0 plugin, semantic search, and automatic capture." --- Add persistent memory to [**Pi Agent**](https://pi.dev) with `@mem0/pi-agent-plugin`. Your agent forgets everything between sessions. This plugin fixes that by automatically capturing knowledge from conversations, storing it in Mem0's cloud memory layer, and retrieving relevant context before every response. +Current package version: `0.3.0`. + ## Overview The plugin provides: 1. **Auto-capture**: Extracts durable facts from both user and assistant messages automatically 2. **Semantic recall**: Retrieves relevant memories via the `mem0_memory` tool before each response -3. **Dream consolidation**: Periodic maintenance: merges duplicates, resolves contradictions, prunes stale entries -4. **Monorepo-aware scoping**: Uses git root for project detection, consistent across subdirectories -5. **Confirmation dialogs**: Destructive commands ask before acting via Pi's built-in UI -6. **8 skills + 8 commands**: Essential memory management from slash commands and agent-guided workflows +3. **Monorepo-aware scoping**: Uses git root for project detection, consistent across subdirectories +4. **Confirmation dialogs**: Destructive commands ask before acting via Pi's built-in UI +5. **6 skills + 6 commands**: Essential memory management from slash commands and agent-guided workflows ## Prerequisites @@ -59,14 +60,7 @@ For advanced settings, create `~/.pi/agent/mem0-config.json`: "userId": "your-username", "autoCapture": true, "defaultScope": "project", - "searchThreshold": 0.3, - "dream": { - "enabled": true, - "auto": true, - "minHours": 24, - "minSessions": 5, - "minMemories": 20 - } + "searchThreshold": 0.3 } ``` @@ -76,12 +70,7 @@ For advanced settings, create `~/.pi/agent/mem0-config.json`: | `userId` | `string` | `$MEM0_USER_ID` or `"default"` | User identity for memory scoping | | `autoCapture` | `boolean` | `true` | Store facts from conversations automatically | | `defaultScope` | `string` | `"project"` | Default memory scope: `project`, `session`, or `global` | -| `searchThreshold` | `number` | `0.3` | Minimum similarity score (0–1) a memory must reach to count as a match for `/mem0-search`, `/mem0-forget`, and `/mem0-pin`, enforced on each result's relevance score. Raise it to be stricter; lower it if relevant results are missed. | -| `dream.enabled` | `boolean` | `true` | Enable dream consolidation | -| `dream.auto` | `boolean` | `true` | Auto-trigger dreams when thresholds are met | -| `dream.minHours` | `number` | `24` | Minimum hours between auto-dreams | -| `dream.minSessions` | `number` | `5` | Minimum sessions before first auto-dream | -| `dream.minMemories` | `number` | `20` | Minimum memories before auto-dream triggers | +| `searchThreshold` | `number` | `0.3` | Minimum similarity score (0–1) a memory must reach to count as a match for `/mem0-search` and `/mem0-forget`, enforced on each result's relevance score. Raise it to be stricter; lower it if relevant results are missed. | ## What's Included @@ -89,11 +78,10 @@ For advanced settings, create `~/.pi/agent/mem0-config.json`: | Component | Description | |-----------|-------------| | `mem0_memory` tool | Agent-callable tool for search, add, get_all, delete, delete_all | -| 8 slash commands | Essential memory management from the command line | -| 8 skills | Guide the agent on how to use each capability | +| 6 slash commands | Essential memory management from the command line | +| 6 skills | Guide the agent on how to use each capability | | Auto-capture | Extracts and stores facts on every `agent_end` event | | System prompt | Appends memory policy to every agent turn | -| Dream consolidation | Automated memory maintenance with session/time/count gates | ## Agent Tool @@ -119,8 +107,6 @@ Tool output is truncated to 200 lines / 50KB to prevent context overflow. | `/mem0-forget ` | Search and delete memories (with confirmation dialog) | | `/mem0-search ` | Semantic search across memories | | `/mem0-tour [scope]` | Browse all memories grouped by category | -| `/mem0-dream` | Consolidate: merge duplicates, prune stale, resolve contradictions | -| `/mem0-pin ` | Pin a memory to protect from dream pruning (preserves memory ID) | | `/mem0-scope ` | Change default scope for this session (project, session, global) | | `/mem0-status` | Connection health, identity, and memory count | @@ -136,23 +122,12 @@ Memories are scoped using Mem0's `user_id`, `app_id`, and `run_id` parameters: The `app_id` is auto-detected from the git repository root (`git rev-parse --show-toplevel`), so all subdirectories within a monorepo share the same memory pool. Falls back to the working directory name for non-git directories. The `run_id` is derived from Pi's session file path. -## Dream Consolidation - -### Confirmation Dialogs +## Confirmation Dialogs Destructive and mutating commands use Pi's built-in `ctx.ui.confirm()` dialog before acting: - `/mem0-forget` asks "Delete this memory?" before deleting a single match -- `/mem0-pin` asks "Pin this memory?" before modifying it -- Cancelling either operation is always safe. No changes are made - -### Pin - -`/mem0-pin` uses Mem0's `update()` API to prepend `[PINNED]` to the memory text. This preserves the original memory ID. There is no add+delete cycle that would lose history or change the UUID. - -### Dream Consolidation - -The plugin includes automated memory maintenance ("dream") that merges duplicates, resolves contradictions, and prunes stale entries. When enabled, dreams auto-trigger after enough sessions, time, and memories accumulate (configurable via `dream.*` settings). Run `/mem0-dream` to trigger consolidation manually at any time. Pinned memories (via `/mem0-pin`) are protected from pruning. +- Cancelling the operation is always safe. No changes are made. ## Example Workflow @@ -172,7 +147,6 @@ You: What do you know about my preferences? - **Extension not loading**: Check Pi startup output for errors. Run `pi -e ./src/entry.ts` from the plugin directory for verbose output - **Memories not capturing**: Verify `autoCapture` is `true` (default). Check `/mem0-status` for connection health - **Wrong project detected**: The plugin uses the git repository root as `app_id`. If not in a git repo, it falls back to the working directory name. Run `/mem0-status` to see the detected project -- **Dream not triggering**: All three gates must pass (time, sessions, memories). Use `/mem0-dream` to force it manually @@ -184,3 +158,5 @@ You: What do you know about my preferences? + +Global tool operations require `/mem0-scope global` or `defaultScope: "global"` in plugin configuration. A model-supplied `scope` argument cannot enable cross-project access on its own. Empty or wildcard user, project, and session identities are rejected. diff --git a/docs/introduction.mdx b/docs/introduction.mdx index 53d424630..094855ad3 100644 --- a/docs/introduction.mdx +++ b/docs/introduction.mdx @@ -63,7 +63,7 @@ mode: "custom" Add memory to your coding agent

- Plugins that let Claude Code, Cursor, Codex, and other harnesses remember your project. Opens the Claude Code guide. + Start with Claude Code, then choose the individual guide for Cursor, Codex, Kimi Code, OpenCode, OpenClaw, Pi Agent, DeepSeek Harness, or Antigravity.

diff --git a/docs/llms.txt b/docs/llms.txt index ae45ad462..0523c6ab9 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -256,12 +256,12 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st - [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. -- [Pi Agent](https://docs.mem0.ai/integrations/pi-agent) [Platform]: Use when adding persistent memory to Pi Agent with the Mem0 plugin. -- [DeepSeek Harness](https://docs.mem0.ai/integrations/deepseek-plugin) [Platform]: Use when adding persistent memory to the DeepSeek Harness (Cordis) agent via the Mem0 plugin. +- [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. - [Google AI ADK](https://docs.mem0.ai/integrations/google-ai-adk) [Platform]: Use when the user is on Google's Agent Development Kit. - [Mastra](https://docs.mem0.ai/integrations/mastra) [Platform]: Use when the user is on Mastra (TypeScript). -- [OpenClaw](https://docs.mem0.ai/integrations/openclaw) [Both]: Use when wiring Mem0 into Claude Code or editors via OpenClaw. +- [OpenClaw](https://docs.mem0.ai/integrations/openclaw) [Both]: Use when adding persistent memory to OpenClaw agents with Mem0 Platform or a self-hosted backend. - [Vercel AI SDK](https://docs.mem0.ai/integrations/vercel-ai-sdk) [Both]: Use when the user is on the Vercel AI SDK. - [Vercel](https://docs.mem0.ai/integrations/vercel) [Platform]: Use when deploying on Vercel and installing Mem0 from the Vercel Marketplace. - [Strands Agents](https://docs.mem0.ai/integrations/strands) [Both]: Use when the user is on AWS Strands and wants a native MemoryStore. @@ -269,10 +269,11 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st ### AI Coding Tools - [Claude Code](https://docs.mem0.ai/integrations/claude-code) [Both]: Use when wiring memory into Claude Code. - [Claude.ai](https://docs.mem0.ai/integrations/claude-ai) [Platform]: Use when connecting Mem0 to Claude.ai (the hosted web app) via a custom remote MCP connector, or when Claude's native memory seems to be crowding out mem0 tool calls. -- [Cursor](https://docs.mem0.ai/integrations/cursor) [Platform]: Use when wiring memory into Cursor. -- [Codex](https://docs.mem0.ai/integrations/codex) [Platform]: Use when wiring memory into Codex / other editor assistants. -- [OpenCode](https://docs.mem0.ai/integrations/opencode) [Platform]: Use when wiring memory into OpenCode. -- [Antigravity](https://docs.mem0.ai/integrations/antigravity) [Platform]: Use when wiring memory into Google Antigravity. +- [Cursor](https://docs.mem0.ai/integrations/cursor) [Platform]: Use when adding lifecycle capture, explicit memory recall, six skills, and a sidekick to Cursor. +- [Codex](https://docs.mem0.ai/integrations/codex) [Platform]: Use when adding automatic capture and recall, six memory skills, and a search tool to OpenAI Codex. +- [Kimi Code](https://docs.mem0.ai/integrations/kimi) [Platform]: Use when adding persistent project memory to Kimi Code through its native plugin lifecycle. +- [OpenCode](https://docs.mem0.ai/integrations/opencode) [Platform]: Use when adding ten native SDK memory tools, automatic context, seven skills, and project scoping to OpenCode. +- [Antigravity](https://docs.mem0.ai/integrations/antigravity) [Platform]: Use when adding lifecycle capture, explicit recall, six memory skills, and a native sidekick to Google Antigravity. ### Voice & Real-time - [LiveKit](https://docs.mem0.ai/integrations/livekit) [Platform]: Use when building real-time voice/video with memory. @@ -417,22 +418,25 @@ Each subdirectory is a Claude Code Skill (`SKILL.md` + supporting assets). Load Source: https://github.com/mem0ai/mem0/tree/main/integrations/claude-code-plugin -The `integrations/claude-code-plugin/` directory is the Claude Code plugin (v0.3.0, installs as `mem0@mem0-plugins`). It captures evidence locally through lifecycle hooks, extracts memories in a detached background worker, and exposes a single local MCP tool, `search_memories`, plus six `/mem0:*` skills and the `mem0:sidekick` agent. Pure-stdlib Python, nothing to install. +The self-contained Claude Code plugin lives in `integrations/claude-code-plugin/` (v0.3.0, installs as `mem0@mem0-plugins`). It captures evidence locally through lifecycle hooks, extracts memories in a detached background worker, and exposes a single local MCP tool, `search_memories`, plus six `/mem0:*` skills and the unchanged `mem0:sidekick` agent. Pure-stdlib Python, nothing to install. -### Editor Plugin (shared glue) +### Coding-Agent Plugin Sources -Source: https://github.com/mem0ai/mem0/tree/main/integrations/mem0-plugin +Source: https://github.com/mem0ai/mem0/tree/main/integrations/agent-plugin-core -The `integrations/mem0-plugin/` directory provides MCP server connection, lifecycle hooks, and skill bundling for Cursor, Codex, Kimi, Antigravity, and OpenCode. It exposes 9 MCP tools: `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`. Claude Code moved to `integrations/claude-code-plugin/` in v0.3.0; do not run both at the same time. +The `integrations/agent-plugin-core/` directory is the single source for shared Python and TypeScript memory behavior. Native plugins live in their own sibling directories, while `integrations/mem0-agent-plugin/` is the single portable Agent Plugins v1 package. TypeScript integrations reuse the core's lifecycle, formatting, identity, scoping, and telemetry utilities while keeping their public packages and native host APIs unchanged. Editor-specific setup docs (already listed above under `## Integrations > AI Coding Tools`): - `integrations/claude-code` [Both] - `integrations/cursor` [Platform] - `integrations/codex` [Platform] +- `integrations/kimi` [Platform] - `integrations/opencode` [Platform] - `integrations/antigravity` [Platform] - `integrations/openclaw` [Both] +- `integrations/pi-agent` [Platform] +- `integrations/deepseek-plugin` [Platform] ### MCP Endpoints diff --git a/integrations/AGENTS.md b/integrations/AGENTS.md index 6083dcf6a..c129dd48b 100644 --- a/integrations/AGENTS.md +++ b/integrations/AGENTS.md @@ -1,21 +1,22 @@ # Integrations (`integrations/`) -Agent and editor integrations. Each subdirectory is self-contained: its own `package.json`, lockfile, build, and tests. **There is no shared toolchain.** Check the table before running anything. +Agent and editor integrations. Most packages are self-contained; coding-agent plugins share the code in `agent-plugin-core/`. Check the table before running anything. | Directory | Package | Build | Lint | Test | |-----------|---------|-------|------|------| | `vercel-ai-sdk/` | `@mem0/vercel-ai-provider` | tsup (CJS+ESM) | ESLint + Prettier | jest + vitest (edge/node) | | `openclaw/` | `@mem0/openclaw-mem0` | tsup (ESM) | none | vitest | -| `claude-code-plugin/` | Claude Code plugin, installs as `mem0@mem0-plugins` (v0.3.0) | none | ruff | pytest | -| `mem0-plugin/` | Cursor / Codex / Kimi / Antigravity / OpenCode plugin (legacy — Claude Code moved to `claude-code-plugin/`) | none | none | pytest | -| `mem0-plugin/.opencode-plugin/` | `@mem0/opencode-plugin` | Bun | none | tsc type-check | +| `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 | +| `opencode-plugin/` | `@mem0/opencode-plugin` (Bun/TypeScript) | tsup (via Bun) | tsc | bun test | | `pi-agent-plugin/` | `@mem0/pi-agent-plugin` | tsup | none | vitest | | `deepseek-plugin/` | `@mem0/deepseek-plugin` | tsup (ESM) | none | vitest | | `n8n-nodes-mem0/` | `@mem0/n8n-nodes-mem0` | tsc | ESLint (n8n-nodes-base) | none | | `zapier-mem0/` | `@mem0/zapier` | tsc | none | offline unit tests + `zapier validate` | | `mem0-strands/` | `mem0-strands` (PyPI) | hatch | Ruff + mypy | pytest | -pnpm everywhere except `.opencode-plugin/` (Bun) and `mem0-strands/` (Python: pip / hatch). Never npm, never yarn. +pnpm for TypeScript packages except `opencode-plugin/` (Bun). `mem0-strands/` uses Python/pip/hatch. Never npm or yarn. ## Commands @@ -41,8 +42,8 @@ Run the type check after every TypeScript change: `pnpm run typecheck` or `tsc - ## What each one is - **`vercel-ai-sdk/`** wraps the Vercel AI SDK through a `createMem0` provider. Integrations for AI-SDK repos go through this wrapper, not raw `MemoryClient`. -- **`claude-code-plugin/`** is the Claude Code plugin (v0.3.0, installs as `mem0@mem0-plugins`): local evidence capture via lifecycle hooks, background memory extraction to the Mem0 Platform, a local `search_memories` MCP tool, six `/mem0:*` skills, and the `mem0:sidekick` agent. Pure-stdlib Python — no dependencies to install. Its `core/` + `adapters/claude/` split marks engine vs. harness glue; future per-harness plugins start by copying `core/` and keeping the contract tests verbatim (see its `docs/CONTRACT.md`). -- **`mem0-plugin/`** connects Cursor, Codex, Kimi, Antigravity, and OpenCode to the MCP server at `mcp.mem0.ai` and installs lifecycle hooks for automatic memory capture. Exposes 9 MCP tools: `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`. The Claude Code plugin moved to [`claude-code-plugin/`](claude-code-plugin/) in v0.3.0 (installs as `mem0@mem0-plugins`); do not run both at the same time. +- **`agent-plugin-core/`** owns the shared Python memory runtime, TypeScript lifecycle utilities, skill templates, builds, and conformance runner. Claude Code is the behavioral source of truth. Native manifests and adapters live in sibling plugin directories; do not hand-edit their generated `core/` or `skills/` trees. Build and validation details are in [`agent-plugin-core/README.md`](agent-plugin-core/README.md). +- **`opencode-plugin/`** is a Bun/TypeScript plugin for OpenCode (`@mem0/opencode-plugin` on npm). It registers Mem0 memory tools as an OpenCode plugin with its own skills and telemetry. - **`openclaw/`**, **`pi-agent-plugin/`**, **`deepseek-plugin/`** are editor and agent plugins with the same shape. `deepseek-plugin/` registers Mem0 search/add tools as a native DeepSeek Harness (Cordis) plugin. - **`n8n-nodes-mem0/`** is an n8n community node: add, search, get, update, delete. - **`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). @@ -50,11 +51,11 @@ Run the type check after every TypeScript change: `pnpm run typecheck` or `tsc - ## Adding an integration -1. Create `integrations//` and build it there, self-contained. +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/`. 2. If it publishes to a registry, set `repository.directory: "integrations/"` in `package.json` so npm provenance links to the right subdirectory. 3. Add `.github/workflows/-checks.yml` and `-cd.yml`. Use `integrations/` in the `paths:` trigger, `working-directory`, and `cache-dependency-path`. Register the release tag prefix in the `case` block in `release.yml`, keeping the bare `v*` arm last. **Workflow filenames are load-bearing:** npm OIDC trusted publishing is pinned to repository plus workflow filename. Renaming one breaks publishing. 4. Register the CI workflow in `ci-gate.yml`: a path filter under the `changes` job, a call job, and an entry in the gate job's `needs` list. -5. If it is a Claude Code or editor marketplace plugin, register its path in all five `marketplace.json` files: root, `.claude-plugin/`, `.cursor-plugin/`, `.codex-plugin/`, and `.agents/plugins/`. +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). diff --git a/integrations/agent-plugin-core/README.md b/integrations/agent-plugin-core/README.md new file mode 100644 index 000000000..b2bc6e5cc --- /dev/null +++ b/integrations/agent-plugin-core/README.md @@ -0,0 +1,102 @@ +# Mem0 agent plugin core + +This directory is the single source of shared memory behavior for Mem0 coding-agent plugins. Installable plugins remain ordinary sibling directories under `integrations/`. + +## Architecture + +```text +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 +│ ├── skills/ # The only source for the six generated memory skills +│ ├── build/ # Bundle builder, schemas, and validation +│ ├── conformance/ # One offline/live verification entry point +│ └── tests/ +├── mem0-agent-plugin/ # One portable Agent Plugins v1 package +├── claude-code-plugin/ # Native Claude package and adapter +├── cursor-plugin/ # Native Cursor package and adapter +├── codex-plugin/ # Native Codex package and adapter +├── kimi-plugin/ # Native Kimi package and adapter +└── antigravity-plugin/ # Native Antigravity package and adapter +``` + +Each native directory owns only its manifest, native hooks or adapter, tests, and `plugin-build.json`. Its `core/` and `skills/` directories are generated from this module. They are committed because clients install a self-contained plugin directory and the Agent Plugins specification forbids package files from resolving outside the plugin root. + +Claude Code remains the behavioral source of truth. Its sidekick stays at `claude-code-plugin/agents/sidekick.md` and is not generated or copied to hosts without a compatible native subagent interface. + +TypeScript integrations (`openclaw`, `opencode-plugin`, `pi-agent-plugin`, and `deepseek-plugin`) import `typescript/src/` at build time. Their package builders include the shared implementation in their normal output; they do not carry checked-in copies. + +## Build and verify + +From the repository root: + +```bash +python3.11 -m venv /tmp/mem0-agent-plugins +/tmp/mem0-agent-plugins/bin/pip install \ + -r integrations/agent-plugin-core/requirements-dev.txt + +for host in claude-code cursor codex kimi antigravity; do + /tmp/mem0-agent-plugins/bin/python \ + integrations/agent-plugin-core/build/build.py "$host" \ + --kind native --check +done + +/tmp/mem0-agent-plugins/bin/python \ + integrations/agent-plugin-core/build/build.py mem0-agent-plugin \ + --kind portable --check +``` + +Use `--sync` instead of `--check` after changing `python/` or `skills/`. This only replaces generated `core/` and `skills/` content; it does not change manifests, adapters, tests, or the Claude sidekick. + +Run every offline Python and TypeScript check and write one machine-readable report: + +```bash +/tmp/mem0-agent-plugins/bin/python \ + integrations/agent-plugin-core/conformance/run.py \ + --install \ + --report /tmp/mem0-plugin-conformance.json +``` + +For every TypeScript integration, this also builds the publishable package, verifies its required entry files, and rejects compiled artifacts that still import monorepo source. This keeps published plugins self-contained without committing their `dist/` directories. + +The offline suite does not contact Mem0 Platform. An explicit disposable key enables the inherited live scoping suite: + +```bash +export MEM0_API_KEY="m0-disposable-test-key" +/tmp/mem0-agent-plugins/bin/python \ + integrations/agent-plugin-core/conformance/run.py \ + --group live-platform --live \ + --report /tmp/mem0-plugin-live-conformance.json +``` + +Do not put a real key in source files, command history shared with others, or pull-request configuration. + +## Add a plugin + +For another native Python host: + +1. Add `integrations/-plugin/` with its native manifest and the smallest adapter that translates host events. +2. Add `plugin-build.json` declaring the plugin-root variable and runtime files. +3. Add one adapter contract test. +4. Register the host in `build/build.py` and `conformance/run.py`. +5. Run `--sync`, `--check`, and the conformance command above. + +Keep capture, recall, memory scoping, redaction, skill text, and telemetry in this shared module. Host directories should contain only behavior required by their native SDK. + +For a TypeScript host, import the shared lifecycle modules directly and keep only native SDK registration in the integration. Do not advertise capture, compaction, or sidekick behavior unless the host exposes the necessary lifecycle seam. + +## Host capture capabilities + +| Host | Conversation capture | Tool outcomes | Subagent context and correlation | +| --- | --- | --- | --- | +| Claude Code | Incremental active transcript branch | Native success/failure hooks | Parent context; native agent ID | +| Cursor | Prompt and response hooks; duplicate responses suppressed | Native success/failure hooks | Sidekick searches itself; no parent-injection claim | +| Codex | Native prompt and final-response fields | Structured failure indicators when present; otherwise unknown | Parent context; native agent ID | +| Kimi | Prompt hooks and completed v2 wire output | Native success/failure hooks | Parent context; without an ID, a stop matches only one unambiguous active run | +| Antigravity | Incremental completed transcript messages, including later prompts | Native tool errors | Sidekick searches itself; no worktree-isolation claim | +| Portable v1 | Explicit memory skills | No native lifecycle hooks | No native subagent declaration | + +An uncorrelated subagent completion is kept as its own record; the plugin never guesses which overlapping run completed. Codex's documented hook fields already match the shared input contract, so no speculative field aliases or unsupported failure event are registered. + +Offline conformance exercises the adapters and MCP servers with native-shaped payloads and builds each distributable package. It does not establish that every installed editor or Harness version loads the plugin correctly; those checks require smoke tests in the actual hosts. diff --git a/integrations/agent-plugin-core/build/__init__.py b/integrations/agent-plugin-core/build/__init__.py new file mode 100644 index 000000000..81c68c34c --- /dev/null +++ b/integrations/agent-plugin-core/build/__init__.py @@ -0,0 +1 @@ +"""Build and validate self-contained Mem0 agent plugins.""" diff --git a/integrations/agent-plugin-core/build/build.py b/integrations/agent-plugin-core/build/build.py new file mode 100644 index 000000000..7a72e5c51 --- /dev/null +++ b/integrations/agent-plugin-core/build/build.py @@ -0,0 +1,252 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import re +import shutil +import tempfile +from collections.abc import Mapping +from pathlib import Path + +try: + from .validate import validate_bundle +except ImportError: + from validate import validate_bundle + +CORE_ROOT = Path(__file__).resolve().parents[1] +REPOSITORY_ROOT = CORE_ROOT.parents[1] +INTEGRATIONS_ROOT = REPOSITORY_ROOT / "integrations" +SHARED_SKILLS = CORE_ROOT / "skills" +PORTABLE_PLUGIN = "mem0-agent-plugin" +NATIVE_PLUGINS = { + "claude-code": INTEGRATIONS_ROOT / "claude-code-plugin", + "cursor": INTEGRATIONS_ROOT / "cursor-plugin", + "codex": INTEGRATIONS_ROOT / "codex-plugin", + "kimi": INTEGRATIONS_ROOT / "kimi-plugin", + "antigravity": INTEGRATIONS_ROOT / "antigravity-plugin", +} +PROTECTED_OUTPUTS = { + REPOSITORY_ROOT, + INTEGRATIONS_ROOT, + CORE_ROOT, + INTEGRATIONS_ROOT / PORTABLE_PLUGIN, + *NATIVE_PLUGINS.values(), +} +TEMPLATE_TOKEN = re.compile(r"{{([A-Z_]+)}}") +TEMPLATE_TOKENS = { + "PLUGIN_ROOT", + "PLUGIN_DATA", + "PLUGIN_DATA_ARG", + "COMMAND_PREFIX", + "HARNESS_ID", + "HARNESS_NAME", +} + + +def render_template(source: str, values: Mapping[str, str]) -> str: + def replace(match: re.Match[str]) -> str: + token = match.group(1) + if token not in TEMPLATE_TOKENS or token not in values: + raise ValueError(f"unknown or unresolved template token: {token}") + return values[token] + + rendered = TEMPLATE_TOKEN.sub(replace, source) + if "{{" in rendered or "}}" in rendered: + raise ValueError("unresolved template token") + return rendered + + +def replace_output(staged: Path, output: Path) -> Path: + """Replace one explicit build output without touching its siblings.""" + if not staged.is_dir(): + raise ValueError(f"staged directory does not exist: {staged}") + + resolved_output = output.resolve() + if resolved_output in {path.resolve() for path in PROTECTED_OUTPUTS}: + raise ValueError(f"refusing protected output path: {output}") + if output.exists() and not output.is_dir(): + raise ValueError(f"output path is not a directory: {output}") + + output.parent.mkdir(parents=True, exist_ok=True) + temporary = Path(tempfile.mkdtemp(prefix=f".{output.name}-", dir=output.parent)) + try: + shutil.copytree(staged, temporary, dirs_exist_ok=True) + if output.exists(): + shutil.rmtree(output) + temporary.replace(output) + finally: + if temporary.exists(): + shutil.rmtree(temporary) + return output + + +def _bundle_python( + staged: Path, + host: str, + plugin_root: str, + *, + plugin_data: str = "", + portable: bool = False, +) -> None: + core = staged / "core" + core.mkdir() + for source in sorted((CORE_ROOT / "python").glob("*.py")): + if portable and source.name in {"flush_worker.py", "hook_runner.py"}: + continue + shutil.copy2(source, core / source.name) + + values = { + "PLUGIN_ROOT": plugin_root, + "PLUGIN_DATA": "${PLUGIN_DATA}", + "PLUGIN_DATA_ARG": f'--plugin-data-dir "{plugin_data}"' if plugin_data else "", + "COMMAND_PREFIX": "mem0", + "HARNESS_ID": host, + "HARNESS_NAME": host.replace("-", " ").title(), + } + for source in sorted(SHARED_SKILLS.glob("*/SKILL.md.tmpl")): + target = staged / "skills" / source.parent.name / "SKILL.md" + target.parent.mkdir(parents=True) + rendered = render_template(source.read_text(encoding="utf-8"), values) + if portable: + rendered = "\n".join( + line + for line in rendered.splitlines() + if not line.startswith(("argument-hint:", "disable-model-invocation:")) + ) + "\n" + target.write_text(rendered, encoding="utf-8") + + +def _build_portable(staged: Path) -> None: + source = INTEGRATIONS_ROOT / PORTABLE_PLUGIN + _copy_declared_files(staged, source, {"plugin.json": "plugin.json", "mcp.json": "mcp.json"}) + _bundle_python(staged, "coding-agent", "${PLUGIN_ROOT}", portable=True) + + +def _copy_declared_files(staged: Path, source_root: Path, files: object) -> None: + if not isinstance(files, dict): + raise ValueError("native files must be an object") + source_root = source_root.resolve() + staged_root = staged.resolve() + for source_name, target_name in files.items(): + if not isinstance(source_name, str) or not isinstance(target_name, str): + raise ValueError("native file paths must be strings") + source = (source_root / source_name).resolve() + target = (staged / target_name).resolve() + if not source.is_relative_to(source_root) or not target.is_relative_to(staged_root): + raise ValueError("native file paths must stay inside their roots") + if not source.is_file(): + raise ValueError(f"native source file does not exist: {source_name}") + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(source, target) + + +def _build_native(host: str, source_root: Path, staged: Path, descriptor: dict) -> None: + native = descriptor.get("native") + if not isinstance(native, dict) or not isinstance(native.get("pluginRoot"), str): + raise ValueError(f"native build is not declared for {host}") + _bundle_python( + staged, + host, + native["pluginRoot"], + plugin_data=str(native.get("pluginData") or ""), + ) + _copy_declared_files(staged, source_root, native.get("files", {})) + + +def build(host: str, kind: str, output: Path) -> Path: + if kind not in {"portable", "native"}: + raise ValueError(f"unknown bundle kind: {kind}") + if kind == "portable": + if host != PORTABLE_PLUGIN: + raise ValueError(f"the portable bundle is {PORTABLE_PLUGIN}") + source_root = INTEGRATIONS_ROOT / PORTABLE_PLUGIN + descriptor = None + else: + source_root = NATIVE_PLUGINS.get(host) + if source_root is None: + raise ValueError(f"unknown host: {host}") + descriptor_path = source_root / "plugin-build.json" + descriptor = json.loads(descriptor_path.read_text(encoding="utf-8")) + with tempfile.TemporaryDirectory(prefix=f"mem0-{host}-{kind}-") as temporary: + staged = Path(temporary) / "bundle" + staged.mkdir() + if kind == "portable": + _build_portable(staged) + else: + assert descriptor is not None + _build_native(host, source_root, staged, descriptor) + errors = validate_bundle(staged, kind) + if errors: + raise ValueError("invalid bundle:\n" + "\n".join(errors)) + return replace_output(staged, output) + + +def installable_root(host: str, kind: str) -> Path: + if kind == "portable" and host == PORTABLE_PLUGIN: + return INTEGRATIONS_ROOT / PORTABLE_PLUGIN + if kind == "native" and host in NATIVE_PLUGINS: + return NATIVE_PLUGINS[host] + raise ValueError(f"unknown {kind} plugin: {host}") + + +def bundle_drift(host: str, kind: str) -> list[str]: + target = installable_root(host, kind) + with tempfile.TemporaryDirectory(prefix=f"mem0-check-{host}-") as temporary: + generated = build(host, kind, Path(temporary) / "bundle") + errors: list[str] = [] + for directory in ("core", "skills"): + expected = { + path.relative_to(generated) + for path in (generated / directory).rglob("*") + if path.is_file() + } + actual = { + path.relative_to(target) + for path in (target / directory).rglob("*") + if path.is_file() and "__pycache__" not in path.parts and path.suffix != ".pyc" + } + errors.extend(f"missing generated file: {path}" for path in sorted(expected - actual)) + errors.extend(f"stale generated file: {path}" for path in sorted(actual - expected)) + for source in sorted(path for path in generated.rglob("*") if path.is_file()): + relative = source.relative_to(generated) + installed = target / relative + if not installed.is_file() or source.read_bytes() != installed.read_bytes(): + errors.append(f"generated file differs: {relative}") + return errors + + +def sync_generated(host: str, kind: str) -> Path: + target = installable_root(host, kind) + with tempfile.TemporaryDirectory(prefix=f"mem0-sync-{host}-") as temporary: + generated = build(host, kind, Path(temporary) / "bundle") + for directory in ("core", "skills"): + replace_output(generated / directory, target / directory) + return target + + +def main() -> int: + parser = argparse.ArgumentParser(description="Build a self-contained Mem0 agent plugin") + parser.add_argument("host") + parser.add_argument("--kind", choices=("portable", "native"), required=True) + action = parser.add_mutually_exclusive_group(required=True) + action.add_argument("--output", type=Path) + action.add_argument("--check", action="store_true") + action.add_argument("--sync", action="store_true") + args = parser.parse_args() + if args.check: + errors = bundle_drift(args.host, args.kind) + if errors: + print("\n".join(errors)) + return 1 + print(f"Current {args.kind} bundle: {installable_root(args.host, args.kind)}") + elif args.sync: + print(sync_generated(args.host, args.kind)) + else: + assert args.output is not None + print(build(args.host, args.kind, args.output)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/agent-plugin-core/build/schemas/mcp.schema.json b/integrations/agent-plugin-core/build/schemas/mcp.schema.json new file mode 100644 index 000000000..1c0626056 --- /dev/null +++ b/integrations/agent-plugin-core/build/schemas/mcp.schema.json @@ -0,0 +1,89 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json", + "title": "Agent Plugins MCP Configuration", + "description": "Machine-readable schema for mcp.json in Agent Plugins 1.0.0. The Agent Plugins specification defines additional semantic and operational requirements.", + "type": "object", + "properties": { + "$schema": { + "const": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json", + "description": "Canonical identifier of the MCP configuration schema for the Agent Plugins version targeted by this document." + }, + "mcpServers": { + "type": "object", + "additionalProperties": { "$ref": "#/$defs/server" } + } + }, + "required": ["$schema", "mcpServers"], + "additionalProperties": false, + "$defs": { + "server": { + "title": "MCP server", + "oneOf": [ + { "$ref": "#/$defs/stdioServer" }, + { "$ref": "#/$defs/streamableHttpServer" }, + { "$ref": "#/$defs/sseServer" } + ] + }, + "stdioServer": { + "title": "stdio MCP server", + "type": "object", + "properties": { + "type": { "const": "stdio" }, + "command": { + "type": "string", + "minLength": 1, + "description": "Executable token. Resolution rules are defined by the Agent Plugins specification." + }, + "args": { "type": "array", "items": { "type": "string" } }, + "env": { + "type": "object", + "propertyNames": { "not": { "enum": ["PLUGIN_ROOT", "PLUGIN_DATA"] } }, + "additionalProperties": { "type": "string" } + }, + "cwd": { + "type": "string", + "pattern": "^(?:\\./|\\$\\{PLUGIN_ROOT\\}(?:/|$)|\\$\\{PLUGIN_DATA\\}(?:/|$))", + "description": "Plugin-relative, PLUGIN_ROOT-rooted, or PLUGIN_DATA-rooted working directory. Filesystem containment is validated separately." + } + }, + "required": ["type", "command"], + "additionalProperties": false + }, + "streamableHttpServer": { + "title": "Streamable HTTP MCP server", + "type": "object", + "properties": { + "type": { "const": "streamable-http" }, + "url": { + "type": "string", + "minLength": 1, + "description": "MCP endpoint URL. URL semantics are defined by the Agent Plugins specification." + }, + "headers": { "$ref": "#/$defs/headers" } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + "sseServer": { + "title": "Legacy HTTP+SSE MCP server", + "type": "object", + "properties": { + "type": { "const": "sse" }, + "url": { + "type": "string", + "minLength": 1, + "description": "MCP endpoint URL. URL semantics are defined by the Agent Plugins specification." + }, + "headers": { "$ref": "#/$defs/headers" } + }, + "required": ["type", "url"], + "additionalProperties": false + }, + "headers": { + "title": "HTTP headers", + "type": "object", + "additionalProperties": { "type": "string" } + } + } +} diff --git a/integrations/agent-plugin-core/build/schemas/plugin.schema.json b/integrations/agent-plugin-core/build/schemas/plugin.schema.json new file mode 100644 index 000000000..fc3155c35 --- /dev/null +++ b/integrations/agent-plugin-core/build/schemas/plugin.schema.json @@ -0,0 +1,45 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", + "title": "Agent Plugins Manifest", + "description": "Machine-readable schema for plugin.json in Agent Plugins 1.0.0. The Agent Plugins specification defines additional semantic and operational requirements.", + "type": "object", + "properties": { + "$schema": { + "const": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", + "description": "Canonical identifier of the plugin manifest schema for the Agent Plugins version targeted by this document." + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 64, + "pattern": "^(?!.*(?:--|\\.\\.))[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?$", + "description": "Human-readable plugin name." + }, + "version": { "type": "string" }, + "description": { "type": "string" }, + "author": { + "type": "object", + "properties": { + "name": { "type": "string" }, + "email": { "type": "string" }, + "url": { "type": "string" } + }, + "additionalProperties": false + }, + "homepage": { "type": "string" }, + "repository": { "type": "string" }, + "license": { "type": "string" }, + "keywords": { + "type": "array", + "items": { "type": "string" } + }, + "extensions": { + "type": "object", + "description": "Client-specific manifest data keyed by reverse-domain extension namespace. Agent Plugins assigns no semantics to namespace object contents.", + "additionalProperties": { "type": "object" } + } + }, + "required": ["$schema", "name"], + "additionalProperties": false +} diff --git a/integrations/agent-plugin-core/build/validate.py b/integrations/agent-plugin-core/build/validate.py new file mode 100644 index 000000000..fea164e16 --- /dev/null +++ b/integrations/agent-plugin-core/build/validate.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path + +from jsonschema import Draft202012Validator +from skills_ref import validate as validate_skill + +SCHEMAS = Path(__file__).resolve().parent / "schemas" + + +def _schema_errors(path: Path, schema_name: str) -> list[str]: + if not path.is_file(): + return [f"{path.name}: file is required"] + + try: + value = json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as error: + return [f"{path.name}: {error}"] + + schema = json.loads((SCHEMAS / schema_name).read_text(encoding="utf-8")) + errors = Draft202012Validator(schema).iter_errors(value) + return [ + f"{path.name}{''.join(f'.{part}' for part in error.absolute_path)}: {error.message}" + for error in sorted(errors, key=lambda item: tuple(str(part) for part in item.absolute_path)) + ] + + +def validate_bundle(root: Path, kind: str) -> list[str]: + errors: list[str] = [] + if not root.is_dir(): + return [f"{root}: directory is required"] + + for path in sorted(root.rglob("*")): + if path.is_symlink(): + errors.append(f"{path.relative_to(root)}: symlinks are not allowed in release bundles") + + if kind == "portable": + errors.extend(_schema_errors(root / "plugin.json", "plugin.schema.json")) + if (root / "mcp.json").exists(): + errors.extend(_schema_errors(root / "mcp.json", "mcp.schema.json")) + skills = root / "skills" + if skills.is_dir(): + for skill in sorted(path for path in skills.iterdir() if path.is_dir()): + errors.extend(f"skills/{skill.name}: {error}" for error in validate_skill(skill)) + elif kind == "native": + for path in sorted(root.rglob("*.json")): + relative = path.relative_to(root) + try: + json.loads(path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError) as error: + errors.append(f"{relative}: {error}") + return sorted(errors) + + +def main() -> int: + parser = argparse.ArgumentParser(description="Validate a generated Mem0 plugin bundle") + parser.add_argument("root", type=Path) + parser.add_argument("--kind", choices=("portable", "native"), required=True) + args = parser.parse_args() + + errors = validate_bundle(args.root, args.kind) + if errors: + for error in errors: + print(error, file=sys.stderr) + return 1 + + print(f"Validated {args.kind} bundle: {args.root}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/agent-plugin-core/conformance/artifacts.py b/integrations/agent-plugin-core/conformance/artifacts.py new file mode 100644 index 000000000..a7aa6efa7 --- /dev/null +++ b/integrations/agent-plugin-core/conformance/artifacts.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Verify that a built TypeScript plugin is self-contained and publishable.""" + +from __future__ import annotations + +import argparse +import re +import time +from pathlib import Path +from typing import Any + + +CORE_ROOT = Path(__file__).resolve().parents[1] +INTEGRATIONS_ROOT = CORE_ROOT.parent +TYPESCRIPT_ARTIFACTS = { + "openclaw": (INTEGRATIONS_ROOT / "openclaw", ("dist/index.js", "dist/index.d.ts")), + "opencode": (INTEGRATIONS_ROOT / "opencode-plugin", ("dist/index.js", "index.d.ts")), + "pi-agent": ( + INTEGRATIONS_ROOT / "pi-agent-plugin", + ("dist/index.js", "dist/index.d.ts", "dist/entry.js", "dist/entry.d.ts"), + ), + "deepseek": (INTEGRATIONS_ROOT / "deepseek-plugin", ("dist/index.js", "dist/index.d.ts")), +} +MONOREPO_IMPORT = re.compile( + r"(?:from\s+|import\s*\(|require\s*\()\s*['\"][^'\"]*agent-plugin-core" +) + + +def verify_artifact(group: str, package: Path, required: tuple[str, ...]) -> dict[str, Any]: + started = time.monotonic() + errors = [f"missing package artifact: {name}" for name in required if not (package / name).is_file()] + dist = package / "dist" + for pattern in ("*.js", "*.mjs", "*.cjs", "*.d.ts"): + for artifact in dist.rglob(pattern) if dist.is_dir() else (): + if MONOREPO_IMPORT.search(artifact.read_text(encoding="utf-8")): + errors.append(f"monorepo source import in package artifact: {artifact.relative_to(package)}") + return { + "name": f"{group}-artifact", + "group": group, + "status": "failed" if errors else "passed", + "duration_seconds": round(time.monotonic() - started, 3), + **({"output": "\n".join(errors)} if errors else {}), + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("group", choices=tuple(TYPESCRIPT_ARTIFACTS)) + args = parser.parse_args() + package, required = TYPESCRIPT_ARTIFACTS[args.group] + result = verify_artifact(args.group, package, required) + if result.get("output"): + print(result["output"]) + return 0 if result["status"] == "passed" else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/agent-plugin-core/conformance/run.py b/integrations/agent-plugin-core/conformance/run.py new file mode 100644 index 000000000..86f7de10f --- /dev/null +++ b/integrations/agent-plugin-core/conformance/run.py @@ -0,0 +1,320 @@ +#!/usr/bin/env python3 +"""Run every coding-agent plugin check and emit one conformance report.""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import tempfile +import time +from pathlib import Path +from typing import Any + + +CORE_ROOT = Path(__file__).resolve().parents[1] +REPOSITORY_ROOT = CORE_ROOT.parents[1] +PYTHON_HOSTS = ("claude-code", "cursor", "codex", "kimi", "antigravity") +GROUPS = ( + "python-bundles", + "python-tests", + "typescript-core", + "openclaw", + "opencode", + "pi-agent", + "deepseek", +) +LIVE_GROUP = "live-platform" + +sys.path.insert(0, str(CORE_ROOT)) +sys.path.insert(0, str(CORE_ROOT / "python")) +from memory_core import redact # noqa: E402 +from build.build import build # noqa: E402 +from conformance.artifacts import TYPESCRIPT_ARTIFACTS, verify_artifact as _typescript_artifact_check # noqa: E402 + + +def _package_directories() -> dict[str, Path]: + return { + "typescript-core": CORE_ROOT / "typescript", + "openclaw": REPOSITORY_ROOT / "integrations" / "openclaw", + "opencode": REPOSITORY_ROOT / "integrations" / "opencode-plugin", + "pi-agent": REPOSITORY_ROOT / "integrations" / "pi-agent-plugin", + "deepseek": REPOSITORY_ROOT / "integrations" / "deepseek-plugin", + } + + +def _runtime_commands() -> dict[str, list[list[str]]]: + return { + "python-tests": [ + [ + sys.executable, + "-m", + "pytest", + "integrations/agent-plugin-core/tests", + "integrations/claude-code-plugin/tests", + "integrations/cursor-plugin/tests", + "integrations/codex-plugin/tests", + "integrations/kimi-plugin/tests", + "integrations/antigravity-plugin/tests", + "-q", + "--ignore=integrations/agent-plugin-core/tests/test_conformance.py", + "--ignore=integrations/claude-code-plugin/tests/integration", + ] + ], + "typescript-core": [["pnpm", "test"], ["pnpm", "typecheck"]], + "openclaw": [ + ["pnpm", "test"], + ["pnpm", "exec", "tsc", "--noEmit"], + ["pnpm", "build"], + ], + "opencode": [ + ["bun", "test"], + ["bun", "run", "type-check"], + ["bun", "run", "build"], + ], + "pi-agent": [ + ["pnpm", "test"], + ["pnpm", "typecheck"], + ["pnpm", "build"], + ], + "deepseek": [ + ["pnpm", "test"], + ["pnpm", "typecheck"], + ["pnpm", "build"], + ], + LIVE_GROUP: [ + [ + sys.executable, + "-m", + "pytest", + "integrations/claude-code-plugin/tests/integration", + "-q", + ] + ], + } + + +def _planned_checks(groups: set[str]) -> list[dict[str, Any]]: + checks: list[dict[str, Any]] = [] + if "python-bundles" in groups: + checks.append( + { + "name": "python-bundles", + "group": "python-bundles", + "status": "planned", + "hosts": list(PYTHON_HOSTS), + "kinds": {"native": list(PYTHON_HOSTS), "portable": ["mem0-agent-plugin"]}, + } + ) + for group, commands in _runtime_commands().items(): + if group not in groups: + continue + for index, command in enumerate(commands, start=1): + checks.append( + { + "name": f"{group}-{index}", + "group": group, + "status": "planned", + "command": command, + } + ) + if group in TYPESCRIPT_ARTIFACTS: + _, required = TYPESCRIPT_ARTIFACTS[group] + checks.append( + { + "name": f"{group}-artifact", + "group": group, + "status": "planned", + "required": list(required), + } + ) + return checks + + +def _command_check( + name: str, + group: str, + command: list[str], + *, + cwd: Path, + environment_overrides: dict[str, str] | None = None, +) -> dict[str, Any]: + started = time.monotonic() + environment = dict(os.environ) + environment.update(environment_overrides or {}) + safe_command = [redact(part) for part in command] + try: + result = subprocess.run( + command, + cwd=cwd, + env=environment, + text=True, + capture_output=True, + check=False, + ) + output = redact((result.stdout + result.stderr).strip()) + return { + "name": name, + "group": group, + "status": "passed" if result.returncode == 0 else "failed", + "duration_seconds": round(time.monotonic() - started, 3), + "command": safe_command, + "exit_code": result.returncode, + **({"output": output[-8_000:]} if output else {}), + } + except OSError as exc: + return { + "name": name, + "group": group, + "status": "failed", + "duration_seconds": round(time.monotonic() - started, 3), + "command": safe_command, + "exit_code": None, + "output": redact(str(exc)), + } + + +def _bundle_checks(artifacts_dir: Path) -> list[dict[str, Any]]: + checks: list[dict[str, Any]] = [] + plugins = [(host, "native") for host in PYTHON_HOSTS] + [("mem0-agent-plugin", "portable")] + for host, kind in plugins: + started = time.monotonic() + try: + output = artifacts_dir / host + build(host, kind, output) + status, error = "passed", "" + except Exception as exc: + status, error = "failed", f"{type(exc).__name__}: {exc}" + checks.append( + { + "name": f"{host}-{kind}", + "group": "python-bundles", + "host": host, + "kind": kind, + "status": status, + "duration_seconds": round(time.monotonic() - started, 3), + **({"output": error} if error else {}), + } + ) + return checks + + +def _install_checks(groups: set[str]) -> list[dict[str, Any]]: + checks: list[dict[str, Any]] = [] + for group, package in _package_directories().items(): + if group not in groups: + continue + command = ( + ["bun", "install", "--frozen-lockfile"] + if group == "opencode" + else ["pnpm", "install", "--frozen-lockfile"] + ) + checks.append( + _command_check( + f"{group}-install", + group, + command, + cwd=package, + environment_overrides={"CI": "true"}, + ) + ) + return checks + + +def _runtime_checks(groups: set[str]) -> list[dict[str, Any]]: + checks: list[dict[str, Any]] = [] + directories = { + **_package_directories(), + "python-tests": REPOSITORY_ROOT, + LIVE_GROUP: REPOSITORY_ROOT, + } + for group, commands in _runtime_commands().items(): + if group not in groups: + continue + for index, command in enumerate(commands, start=1): + checks.append( + _command_check( + f"{group}-{index}", + group, + command, + cwd=directories[group], + ) + ) + if group in TYPESCRIPT_ARTIFACTS: + _, required = TYPESCRIPT_ARTIFACTS[group] + checks.append( + _typescript_artifact_check( + group, + directories[group], + required, + ) + ) + return checks + + +def _print_report(report: dict[str, Any]) -> None: + for check in report["checks"]: + marker = {"passed": "PASS", "failed": "FAIL", "planned": "PLAN"}[check["status"]] + duration = f" ({check['duration_seconds']:.3f}s)" if "duration_seconds" in check else "" + print(f"{marker:4} {check['name']}{duration}") + if check["status"] == "failed" and check.get("output"): + print(check["output"]) + print(f"\nConformance: {report['status']} ({len(report['checks'])} checks)") + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--group", action="append", choices=("all", *GROUPS, LIVE_GROUP), default=[]) + parser.add_argument("--list", action="store_true", help="Print the checks without running them") + parser.add_argument("--install", action="store_true", help="Install TypeScript dependencies first") + parser.add_argument("--live", action="store_true", help="Run the opt-in tests against Mem0 Platform") + parser.add_argument("--artifacts-dir", type=Path) + parser.add_argument("--report", type=Path) + args = parser.parse_args() + + selected = set(GROUPS if not args.group or "all" in args.group else args.group) + if args.live: + selected.add(LIVE_GROUP) + if args.list: + report = {"status": "planned", "checks": _planned_checks(selected)} + if args.report: + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + _print_report(report) + return 0 + if LIVE_GROUP in selected and not os.environ.get("MEM0_API_KEY"): + parser.error("MEM0_API_KEY is required for --live") + + temporary = None + if args.artifacts_dir: + artifacts_dir = args.artifacts_dir.resolve() + artifacts_dir.mkdir(parents=True, exist_ok=True) + else: + temporary = tempfile.TemporaryDirectory(prefix="mem0-plugin-conformance-") + artifacts_dir = Path(temporary.name) + + checks: list[dict[str, Any]] = [] + try: + if args.install: + checks.extend(_install_checks(selected)) + if "python-bundles" in selected: + checks.extend(_bundle_checks(artifacts_dir)) + checks.extend(_runtime_checks(selected)) + report = { + "status": "passed" if all(check["status"] == "passed" for check in checks) else "failed", + "checks": checks, + } + if args.report: + args.report.parent.mkdir(parents=True, exist_ok=True) + args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8") + _print_report(report) + return 0 if report["status"] == "passed" else 1 + finally: + if temporary is not None: + temporary.cleanup() + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/agent-plugin-core/python/flush_worker.py b/integrations/agent-plugin-core/python/flush_worker.py new file mode 100644 index 000000000..6f7b9ecb2 --- /dev/null +++ b/integrations/agent-plugin-core/python/flush_worker.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Detached remote checkpoint worker. + +Claude Code may cancel SessionEnd hooks as a print-mode process exits. The hook +therefore persists its input first and launches this process in a new session. +""" + +from __future__ import annotations + +import json +import os +import sys +import time +from pathlib import Path + +import telemetry +from memory_core import ( + EvidenceStore, + checkpoint_session, + configure_harness, + touch_handoff_heartbeat, +) + + +def main() -> int: + if len(sys.argv) != 2: + return 2 + handoff_path = Path(sys.argv[1]) + os.environ["MEM0_CODE_HANDOFF_PATH"] = str(handoff_path) + harness = os.environ.get("MEM0_PLUGIN_HARNESS") + if harness: + source_tag = os.environ.get("MEM0_PLUGIN_SOURCE_TAG", "") + configure_harness( + harness, + env_prefix=os.environ.get("MEM0_PLUGIN_ENV_PREFIX", ""), + data_dir_name=os.environ.get("MEM0_PLUGIN_DATA_DIR_NAME", ""), + source_tag=source_tag, + ) + telemetry.init(harness=harness, source_tag=source_tag.upper()) + completed = False + try: + payload = json.loads(handoff_path.read_text(encoding="utf-8")) + delay = float(payload.get("delay_seconds") or 0) + if delay > 0: + payload.pop("delay_seconds", None) + temporary = handoff_path.with_suffix(f".{os.getpid()}.tmp") + try: + temporary.write_text(json.dumps(payload), encoding="utf-8") + temporary.replace(handoff_path) + finally: + temporary.unlink(missing_ok=True) + time.sleep(delay) + if not handoff_path.exists(): + return 0 + hook_input = payload.get("hook_input") or {} + reason = str(payload.get("reason") or "checkpoint") + wait_for_inflight = bool(payload.get("wait_for_inflight")) + store = EvidenceStore() + try: + if wait_for_inflight: + session_id = str( + hook_input.get("session_id") or "unknown-session" + ) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + deadline = time.monotonic() + float( + os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120") + ) + while ( + store.has_inflight_flush(repo.identity, session_id) + and time.monotonic() < deadline + ): + touch_handoff_heartbeat() + time.sleep(0.25) + # Hooks capture the conversation before handoff; the worker only flushes it. + result = checkpoint_session(store, hook_input, reason) + print(json.dumps(result, sort_keys=True), flush=True) + completed = result.get("status") in { + "semantic-succeeded", + "explicitly-stored", + "nothing-to-flush", + } + finally: + store.close() + return 0 + finally: + telemetry.flush() + if completed: + try: + handoff_path.unlink() + except OSError: + pass + elif handoff_path.suffix == ".running": + try: + handoff_path.replace(handoff_path.with_suffix(".json")) + except OSError: + pass + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/agent-plugin-core/python/hook_runner.py b/integrations/agent-plugin-core/python/hook_runner.py new file mode 100644 index 000000000..2a2adb557 --- /dev/null +++ b/integrations/agent-plugin-core/python/hook_runner.py @@ -0,0 +1,372 @@ +"""Shared hook orchestration for all Mem0 agent plugins.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +import uuid +from pathlib import Path + +import telemetry +from memory_core import ( + EvidenceStore, + _session_id, + api_key, + bounded, + cache_plugin_api_key, + checkpoint_session, + clear_stale_api_key_cache, + configure_harness, + data_dir, + detached_process_kwargs, + format_context, + harness_config, + record_session_start, + record_tool, + record_user_prompt, + redact, + search_memories, +) + +STALE_RUNNING_SECONDS = 300 +PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60 +PENDING_LAUNCH_LIMIT = 5 +DEFAULT_IDLE_FLUSH_SECONDS = 300 + +_core_dir: Path = Path(__file__).resolve().parent + + +def read_hook_input() -> dict: + try: + value = json.load(sys.stdin) + return value if isinstance(value, dict) else {} + except (json.JSONDecodeError, OSError): + return {} + + +def default_record_stop(store: EvidenceStore, hook_input: dict): + """Record the assistant's response without transcript parsing.""" + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + message = redact(hook_input.get("last_assistant_message", "")).strip() + if message: + store.record_assistant_response(repo, session_id, message) + return repo, session_id + + +def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict: + """Search once before the agent handles the first prompt in a session.""" + repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input) + if not is_first_prompt: + return {} + try: + minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20")) + except ValueError: + minimum_query_chars = 20 + if len(prompt.strip()) < max(minimum_query_chars, 1): + return {} + result = search_memories( + store, repo, session_id, bounded(prompt, 6000), + top_k=5, operation="first-prompt-search", timeout=2, + ) + if not result.memories: + return {} + context = format_context( + result.memories, + "Mem0 found these relevant memories from earlier work in this repository:", + ) + telemetry.record( + "context_injected", + repo=repo, session_id=session_id, trigger="first-prompt", + memory_count=len(result.memories), context_chars=len(context), + prompt_chars=len(prompt), + ) + return { + "hookSpecificOutput": { + "hookEventName": "UserPromptSubmit", + "additionalContext": context, + }, + } + + +def _launch_handoff(handoff_path: Path) -> bool: + running_path = handoff_path.with_suffix(".running") + try: + handoff_path.replace(running_path) + except OSError: + return False + worker = _core_dir / "flush_worker.py" + log_path = data_dir() / "flush-worker.log" + log_handle = open(log_path, "a", encoding="utf-8") + harness = harness_config() + child_env = os.environ.copy() + child_env.update( + { + "MEM0_CODE_DATA_DIR": str(data_dir()), + "MEM0_PLUGIN_HARNESS": harness["name"], + "MEM0_PLUGIN_ENV_PREFIX": harness["env_prefix"], + "MEM0_PLUGIN_DATA_DIR_NAME": harness["data_dir_name"], + "MEM0_PLUGIN_SOURCE_TAG": harness["source_tag"], + } + ) + try: + subprocess.Popen( + [sys.executable, str(worker), str(running_path)], + stdin=subprocess.DEVNULL, + stdout=log_handle, stderr=log_handle, + close_fds=True, + env=child_env, + **detached_process_kwargs(), + ) + finally: + log_handle.close() + return True + + +def recover_pending_handoffs() -> int: + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + now = time.time() + for running in pending_dir.glob("*.running"): + try: + if now - running.stat().st_mtime > STALE_RUNNING_SECONDS: + running.replace(running.with_suffix(".json")) + except OSError: + continue + recoverable = [] + for handoff in pending_dir.glob("*.json"): + try: + age = now - handoff.stat().st_mtime + except OSError: + continue + if age > PENDING_EXPIRY_SECONDS: + handoff.unlink(missing_ok=True) + continue + recoverable.append((age, handoff)) + recoverable.sort(key=lambda item: item[0], reverse=True) + launched = 0 + for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]: + launched += int(_launch_handoff(handoff)) + return launched + + +def refresh_pending_handoffs() -> None: + pending_dir = data_dir() / "pending" + if not pending_dir.is_dir(): + return + for pattern in ("*.json", "*.running"): + for handoff in pending_dir.glob(pattern): + try: + os.utime(handoff) + except OSError: + continue + + +def hand_off_flush( + hook_input: dict, reason: str, *, wait_for_inflight: bool = False, +) -> None: + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + material = ( + f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}" + ) + digest = hashlib.sha256(material.encode()).hexdigest()[:24] + handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json" + temporary_path = handoff_path.with_suffix(".tmp") + temporary_path.write_text( + json.dumps({ + "hook_input": hook_input, + "reason": reason, + "wait_for_inflight": wait_for_inflight, + }), + encoding="utf-8", + ) + temporary_path.replace(handoff_path) + _launch_handoff(handoff_path) + + +def automatic_flush_enabled() -> bool: + return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in { + "1", "true", "yes", "on", + } + + +def schedule_periodic_checkpoint( + store: EvidenceStore, hook_input: dict, repo, session_id: str, +) -> bool: + if ( + not automatic_flush_enabled() + or not api_key() + or not store.checkpoint_due(repo.identity, session_id) + ): + return False + if store.prepare_flush(repo, session_id, "periodic") is None: + return False + hand_off_flush(hook_input, "periodic") + return True + + +def _idle_flush_seconds() -> int: + try: + return max( + int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))), + 0, + ) + except ValueError: + return DEFAULT_IDLE_FLUSH_SECONDS + + +def schedule_idle_flush( + store: EvidenceStore, hook_input: dict, repo, session_id: str, +) -> bool: + delay = _idle_flush_seconds() + if delay <= 0 or not automatic_flush_enabled() or not api_key(): + return False + if store.has_inflight_flush(repo.identity, session_id): + return False + if not store.has_unflushed_events(repo.identity, session_id): + return False + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}" + digest = hashlib.sha256(material.encode()).hexdigest()[:24] + for old in pending_dir.glob(f"idle-{digest}*"): + old.unlink(missing_ok=True) + handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json" + temporary_path = handoff_path.with_suffix(".tmp") + temporary_path.write_text( + json.dumps({ + "hook_input": hook_input, + "reason": "idle", + "delay_seconds": delay, + }), + encoding="utf-8", + ) + temporary_path.replace(handoff_path) + _launch_handoff(handoff_path) + return True + + +def log_failure(exc: Exception) -> None: + try: + log_path = data_dir() / "plugin-errors.log" + with log_path.open("a", encoding="utf-8") as handle: + handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n") + except OSError: + pass + + +def run( + *, + record_stop_fn=None, + extra_actions: dict | None = None, + data_dir_env: str = "MEM0_PLUGIN_DATA_DIR", + automatic_flush_reasons: set | None = None, +) -> int: + if record_stop_fn is None: + record_stop_fn = default_record_stop + if automatic_flush_reasons is None: + automatic_flush_reasons = {"session-end"} + + base_actions = ["session-start", "user-prompt", "post-tool", "stop", "flush"] + all_actions = base_actions + list((extra_actions or {}).keys()) + + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=all_actions) + parser.add_argument("--reason", default="manual") + parser.add_argument("--plugin-data-dir", default="") + parser.add_argument("--harness", default="") + args = parser.parse_args() + + if args.harness: + configure_harness(args.harness) + telemetry.init(harness=args.harness) + + if args.plugin_data_dir: + os.environ[data_dir_env] = args.plugin_data_dir + + cache_plugin_api_key() + if args.action == "session-start": + clear_stale_api_key_cache() + + hook_input = read_hook_input() + store = EvidenceStore() + try: + if store.is_paused(): + if args.action == "session-start": + refresh_pending_handoffs() + telemetry.record("session_start", paused=True) + telemetry.spawn_flush() + return 0 + + if args.action == "session-start": + if telemetry.is_first_run(): + telemetry.record("install") + recovered = recover_pending_handoffs() + record_session_start(store, hook_input) + if recovered: + telemetry.record("handoff_recovered", count=recovered) + telemetry.spawn_flush() + elif args.action == "user-prompt": + output = first_prompt_memory_output(store, hook_input) + if output: + print(json.dumps(output)) + elif args.action == "post-tool": + record_tool(store, hook_input) + elif args.action == "stop": + repo, session_id = record_stop_fn(store, hook_input) + if not schedule_periodic_checkpoint(store, hook_input, repo, session_id): + schedule_idle_flush(store, hook_input, repo, session_id) + elif args.action == "flush": + automatic = args.reason in automatic_flush_reasons + if automatic and not automatic_flush_enabled(): + return 0 + if args.reason == "session-end": + record_stop_fn(store, hook_input) + if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1": + print(json.dumps(checkpoint_session(store, hook_input, args.reason))) + else: + session_id = str(hook_input.get("session_id") or "unknown-session") + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + already_running = store.has_inflight_flush(repo.identity, session_id) + if already_running and args.reason == "session-end": + hand_off_flush(hook_input, args.reason, wait_for_inflight=True) + elif not already_running and store.prepare_flush( + repo, session_id, args.reason, + ) is not None: + hand_off_flush(hook_input, args.reason) + elif extra_actions and args.action in extra_actions: + result = extra_actions[args.action](store, hook_input) + if result: + print(json.dumps(result)) + finally: + store.close() + return 0 + + +def entry_point( + *, + record_stop_fn=None, + extra_actions: dict | None = None, + data_dir_env: str = "MEM0_PLUGIN_DATA_DIR", + automatic_flush_reasons: set | None = None, +) -> None: + try: + raise SystemExit(run( + record_stop_fn=record_stop_fn, + extra_actions=extra_actions, + data_dir_env=data_dir_env, + automatic_flush_reasons=automatic_flush_reasons, + )) + except Exception as exc: + log_failure(exc) + raise SystemExit(0) + + +if __name__ == "__main__": + entry_point() diff --git a/integrations/agent-plugin-core/python/mcp_server.py b/integrations/agent-plugin-core/python/mcp_server.py new file mode 100644 index 000000000..036fbbdc9 --- /dev/null +++ b/integrations/agent-plugin-core/python/mcp_server.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Expose Mem0's memory search as one local coding-agent tool.""" + +from __future__ import annotations + +import json +import os +import sys +from typing import Any + +import telemetry +from memory_core import ( + CODING_MEMORY_CATEGORY_NAMES, + PLUGIN_VERSION, + SEARCH_SCOPES, + format_search_result, + resolve_repo, + search_memories, +) + +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." +) +TOOL_SCHEMA = { + "type": "object", + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 2000, + "description": "A direct question about earlier work in this repository.", + }, + "top_k": { + "type": "integer", + "minimum": 1, + "maximum": 20, + "description": "Maximum memories to return. Uses Mem0's configured default when omitted.", + }, + "category": { + "type": "string", + "enum": list(CODING_MEMORY_CATEGORY_NAMES), + "description": "Optional memory category. Omit to search every category.", + }, + "scope": { + "type": "string", + "enum": list(SEARCH_SCOPES), + "description": ( + "Which memories to search. 'repo' (default) is the whole repository's " + "shared memory plus your own preferences, 'dir' narrows the shared " + "part to the current directory, 'mine' is your preferences alone." + ), + }, + "run_id": { + "type": "string", + "minLength": 1, + "description": ( + "Optional coding-agent session ID. With any scope, restricts results to memories " + "saved in that session. Omit to recall memories across sessions." + ), + }, + }, + "required": ["query"], + "additionalProperties": False, +} + + +class ToolInputError(ValueError): + pass + + +def _validate_arguments( + arguments: Any, +) -> tuple[str, int | None, str | None, str | None, str | None]: + if not isinstance(arguments, dict): + raise ToolInputError("Search arguments must be an object.") + + unknown = set(arguments) - {"query", "top_k", "category", "scope", "run_id"} + if unknown: + raise ToolInputError(f"Unknown search argument: {sorted(unknown)[0]}") + + query = arguments.get("query") + if not isinstance(query, str) or not query.strip(): + raise ToolInputError("query must be a non-empty string.") + query = query.strip() + if len(query) > 2000: + raise ToolInputError("query must be at most 2,000 characters.") + + top_k = arguments.get("top_k") + if top_k is not None and ( + isinstance(top_k, bool) or not isinstance(top_k, int) or not 1 <= top_k <= 20 + ): + raise ToolInputError("top_k must be an integer from 1 to 20.") + + category = arguments.get("category") + if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES: + raise ToolInputError("category must be one of Mem0's supported categories.") + + scope = arguments.get("scope") + if scope is not None and scope not in SEARCH_SCOPES: + raise ToolInputError(f"scope must be one of {list(SEARCH_SCOPES)}.") + + run_id = arguments.get("run_id") + if run_id is not None: + if not isinstance(run_id, str) or not run_id.strip(): + raise ToolInputError("run_id must be a non-empty string.") + run_id = run_id.strip() + + return query, top_k, category, scope, run_id + + +def call_search_memories(arguments: Any, cwd: str | None = None) -> str: + query, top_k, category, scope, run_id = _validate_arguments(arguments) + repo = resolve_repo(cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()) + result = search_memories( + None, + repo, + None, + query, + top_k=top_k, + category=category, + scope=scope, + run_id=run_id, + operation="mcp-search", + ) + return format_search_result(result) + + +def _workspace_cwd(params: dict[str, Any]) -> str | None: + meta = params.get("_meta") + if not isinstance(meta, dict): + return None + metadata = meta.get("x-codex-turn-metadata") + if not isinstance(metadata, dict): + return None + workspaces = metadata.get("workspaces") or {} + if isinstance(workspaces, dict): + return next((path for path in workspaces if isinstance(path, str) and path), None) + return None + + +def _tool_response(text: str, *, is_error: bool = False) -> dict[str, Any]: + return { + "content": [{"type": "text", "text": text}], + "isError": is_error, + } + + +def handle_request(message: Any) -> dict[str, Any] | None: + if not isinstance(message, dict): + return None + request_id = message.get("id") + method = message.get("method") + + if method == "notifications/initialized": + return None + if method == "initialize": + requested = (message.get("params") or {}).get("protocolVersion") + return { + "jsonrpc": "2.0", + "id": request_id, + "result": { + "protocolVersion": requested or PROTOCOL_VERSION, + "capabilities": {"tools": {"listChanged": False}}, + "serverInfo": {"name": "mem0", "version": PLUGIN_VERSION}, + }, + } + if method == "ping": + return {"jsonrpc": "2.0", "id": request_id, "result": {}} + if method == "tools/list": + return { + "jsonrpc": "2.0", + "id": request_id, + "result": { + "tools": [ + { + "name": TOOL_NAME, + "description": TOOL_DESCRIPTION, + "inputSchema": TOOL_SCHEMA, + "annotations": { + "readOnlyHint": True, + "idempotentHint": True, + "openWorldHint": True, + }, + } + ] + }, + } + if method == "tools/call": + params = message.get("params") or {} + if params.get("name") != TOOL_NAME: + result = _tool_response("Unknown Mem0 tool.", is_error=True) + else: + try: + result = _tool_response( + call_search_memories(params.get("arguments"), _workspace_cwd(params)) + ) + except ToolInputError as exc: + result = _tool_response(str(exc), is_error=True) + except Exception: + result = _tool_response("Memory search failed.", is_error=True) + return {"jsonrpc": "2.0", "id": request_id, "result": result} + if request_id is None: + return None + return { + "jsonrpc": "2.0", + "id": request_id, + "error": {"code": -32601, "message": "Method not found"}, + } + + +def main() -> int: + for raw_line in sys.stdin: + try: + message = json.loads(raw_line) + response = handle_request(message) + except json.JSONDecodeError: + response = { + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32700, "message": "Parse error"}, + } + except Exception: + response = { + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32603, "message": "Internal error"}, + } + if response is not None: + sys.stdout.write(json.dumps(response, separators=(",", ":")) + "\n") + sys.stdout.flush() + telemetry.spawn_flush() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/agent-plugin-core/python/memory_cli.py b/integrations/agent-plugin-core/python/memory_cli.py new file mode 100644 index 000000000..595729feb --- /dev/null +++ b/integrations/agent-plugin-core/python/memory_cli.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Mem0 diagnostics and user controls.""" + +from __future__ import annotations + +import argparse +import json +import os + +import telemetry +from memory_core import ( + EvidenceStore, + api_key, + data_dir, + doctor, + forget_remote_repo, + configure_harness, + resolve_repo, + user_id, +) + + +def _print_status(value: dict) -> None: + last = value.get("last_operation") or {} + print(f"Mem0: {'paused' if value['paused'] else 'active'}") + print(f"Repository: {value['repo_id']}") + print(f"Local data: {value['data_dir']}") + print(f"API key: {'configured' if value['api_key_configured'] else 'missing'}") + print( + "Saved on this computer: " + f"{value['events']} session details, {value['flushes']} memory updates" + ) + print( + f"Used in this repository: {value['retrievals']} memories returned, " + f"{value['sidekick_runs']} sidekick runs" + ) + if last: + item_label = "" + if last["operation"] in {"flush", "flush-retry"}: + item_label = f", {last['item_count']} memories" + operation = ( + "memory update" + if last["operation"] in {"flush", "flush-retry"} + else last["operation"].replace("-", " ") + ) + print( + f"Last {operation}: " + f"{'succeeded' if last['success'] else 'failed'} " + f"({last['duration_ms']:.1f} ms{item_label})" + ) + sidekick = value.get("last_sidekick") or {} + if sidekick: + state = "finished" if sidekick.get("stopped_at") else "started" + print( + "Last sidekick: " + f"{state}, received {sidekick['context_chars']} characters of memory, " + f"agent {sidekick['agent_id']}" + ) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--plugin-data-dir", default="") + parser.add_argument("--harness", default="") + subparsers = parser.add_subparsers(dest="command", required=True) + + status = subparsers.add_parser("status") + status.add_argument("--json", action="store_true") + + doctor_parser = subparsers.add_parser("doctor") + doctor_parser.add_argument("--json", action="store_true") + + subparsers.add_parser("pause") + subparsers.add_parser("resume") + + forget = subparsers.add_parser("forget") + forget.add_argument("--remote", action="store_true") + forget.add_argument("--yes", action="store_true") + forget.add_argument("--include-project-memory", action="store_true") + + args = parser.parse_args() + if args.harness: + source_tag = f"{args.harness.replace('-', '_')}_plugin" + configure_harness(args.harness, source_tag=source_tag) + telemetry.init(harness=args.harness, source_tag=source_tag.upper()) + if args.plugin_data_dir: + os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir + store = EvidenceStore() + try: + repo = resolve_repo(os.getcwd()) + telemetry.record("control", repo=repo, action=args.command) + if args.command == "status": + result = { + **store.status(repo.identity), + "repo_id": repo.identity, + "app_id": repo.app_id, + "project_id": repo.project_id, + "directory": repo.directory, + "user_id": user_id(), + "data_dir": str(data_dir()), + "api_key_configured": bool(api_key()), + } + if args.json: + print(json.dumps(result, indent=2, default=str)) + else: + _print_status(result) + elif args.command == "doctor": + result = doctor(os.getcwd()) + if args.json: + print(json.dumps(result, indent=2, default=str)) + else: + for name, check in result["checks"].items(): + print( + f"{'PASS' if check['ok'] else 'FAIL'} {name}: {check['detail']}" + ) + return 0 if result["ok"] else 1 + elif args.command == "pause": + store.set_setting("paused", "true") + print("Mem0 stopped saving and searching memories.") + elif args.command == "resume": + store.set_setting("paused", "false") + print("Mem0 resumed saving and searching memories.") + elif args.command == "forget": + if not args.yes: + print( + "Refusing to delete data without --yes. Add --remote to also " + "delete this user/repository scope from Mem0." + ) + return 2 + remote_result = ( + forget_remote_repo( + repo, include_project_memory=args.include_project_memory + ) + if args.remote + else None + ) + local_result = store.forget_local_repo(repo.identity) + print( + json.dumps( + {"local": local_result, "remote": remote_result}, + indent=2, + default=str, + ) + ) + if remote_result and remote_result.get("status") == "error": + return 1 + finally: + store.close() + telemetry.spawn_flush() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/agent-plugin-core/python/memory_core.py b/integrations/agent-plugin-core/python/memory_core.py new file mode 100644 index 000000000..cf71196b8 --- /dev/null +++ b/integrations/agent-plugin-core/python/memory_core.py @@ -0,0 +1,2645 @@ +#!/usr/bin/env python3 +"""Shared core for Mem0 agent plugins. + +Hooks record small session details locally. When the agent compacts or ends the +session, Mem0 sends the useful parts to the platform so it can create memories. +The agent can search those memories during later work in the repository. +""" + +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import sqlite3 +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Iterable + +import telemetry + +DEFAULT_API_URL = "https://api.mem0.ai" +PLUGIN_VERSION = "0.3.1" + +_harness_name: str = "generic" +_harness_env_prefix: str = "MEM0_PLUGIN" +_harness_data_dir_name: str = "mem0-plugin" +_harness_source_tag: str = "mem0_plugin" + + +def configure_harness( + name: str, + env_prefix: str = "", + data_dir_name: str = "", + source_tag: str = "", +) -> None: + global _harness_name, _harness_env_prefix, _harness_data_dir_name, _harness_source_tag + _harness_name = name + _harness_env_prefix = env_prefix or f"MEM0_{name.upper().replace('-', '_')}" + _harness_data_dir_name = data_dir_name or f"{name}-plugin" + _harness_source_tag = source_tag or f"{name.replace('-', '_')}_plugin" + + +def harness_config() -> dict[str, str]: + return { + "name": _harness_name, + "env_prefix": _harness_env_prefix, + "data_dir_name": _harness_data_dir_name, + "source_tag": _harness_source_tag, + } + + +MAX_COMMAND_CHARS = 2000 +MAX_RESULT_CHARS = 2500 +MAX_EPISODE_CHARS = 12000 +CHECKPOINT_EXCHANGES = 5 +CHECKPOINT_MESSAGES = 10 +CHECKPOINT_SOURCE_CHARS = 40000 +DEFAULT_MAX_CONTEXT_CHARS = 4000 +MAX_EXTRACTION_INPUT_TOKENS = 24000 +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. + +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 current coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions. + +Write about the repository, not the user, assistant, session, or task. Do not save personal preferences. Do not save a memory that only states which repository, branch, or directory the session worked in. Do not include test results, documentation updates, release notes, or temporary state. + +If nothing useful was established, return no memories.""" + +PERSONAL_MEMORY_INSTRUCTIONS = """Save concise facts about the user that will help in any repository: preferred tools, package managers, languages, coding style, review and communication preferences, and anything the user explicitly asked to be remembered about themselves. + +Write in the third person about the user, not about the repository, the assistant, the session, or the task. Do not save repository facts, project decisions, commands, or what was built. + +Never save that the user has no preferences or that nothing was learned. If nothing was learned about the user, return no memories.""" + +CODING_MEMORY_CATEGORIES = [ + { + "project_knowledge": ( + "What the project is and how its code, APIs, data, files, and " + "components work." + ) + }, + { + "decisions_and_constraints": ( + "Why an approach was chosen, what must remain true, and rules future " + "work must follow." + ) + }, + { + "workflows": ( + "How to run, test, debug, deploy, configure, or otherwise work on the " + "project." + ) + }, + { + "problems_and_fixes": ( + "Bugs, failures, known pitfalls, their causes, and how to fix or avoid " + "them." + ) + }, + { + "results": ( + "Outcomes and measurements from tests, benchmarks, experiments, or " + "investigations." + ) + }, +] +CODING_MEMORY_CATEGORY_NAMES = tuple( + category_name + for category in CODING_MEMORY_CATEGORIES + for category_name in category +) + +TEST_COMMAND_RE = re.compile( + r"(?:^|\s)(?:pytest|py\.test|jest|vitest|go\s+test|cargo\s+test|" + r"npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|" + r"mvn\s+test|gradle\s+test|make\s+test)(?:\s|$)", + re.IGNORECASE, +) +BUILD_COMMAND_RE = re.compile( + r"(?:^|\s)(?:npm|pnpm|yarn)\s+(?:run\s+)?build(?:\s|$)|" + r"(?:^|\s)(?:cargo|go|mvn|gradle|make)\s+build(?:\s|$)", + re.IGNORECASE, +) + +SECRET_PATTERNS = [ + re.compile(r"(?i)(authorization\s*[:=]\s*(?:bearer|token)\s+)[^\s\"']+"), + re.compile( + r"(?i)((?:api[_-]?key|secret[_-]?access[_-]?key|session[_-]?token)\s*[:=]\s*)[^\s\"']+" + ), + re.compile( + r"(?i)((?:access[_-]?token|refresh[_-]?token|password|credential)" + r"\s*[:=]\s*)[^\s&\"']+" + ), + re.compile(r"\b(?:sk|m0|mem0_sk|psk)-[A-Za-z0-9_\-]{12,}\b"), + re.compile(r"\b(?:ASIA|AKIA)[A-Z0-9]{12,}\b"), + re.compile(r"\b(?:ghp_|github_pat_|xox[baprs]-)[A-Za-z0-9_\-]{12,}\b"), + re.compile( + r"-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----", + re.DOTALL, + ), + re.compile( + r'(?i)("(?:api[_-]?key|password|secret(?:[_-]?access[_-]?key)?' + r'|(?:access|refresh|session)[_-]?token|token|authorization|credential' + r')"\s*:\s*")(?:\\.|[^"\\])*' + ), +] + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def redact(value: Any) -> str: + text = ( + value + if isinstance(value, str) + else json.dumps(value, ensure_ascii=False, default=str) + ) + for pattern in SECRET_PATTERNS: + if pattern.groups: + text = pattern.sub(r"\1[REDACTED]", text) + else: + text = pattern.sub("[REDACTED]", text) + return text + + +def bounded(value: Any, limit: int) -> str: + text = redact(value).strip() + if len(text) <= limit: + return text + return text[:limit] + f"\n...[truncated {len(text) - limit} chars]" + + +def _git(cwd: str, *args: str) -> str: + try: + result = subprocess.run( + ["git", "-C", cwd, *args], + check=False, + capture_output=True, + text=True, + timeout=0.5, + ) + except (OSError, subprocess.TimeoutExpired): + return "" + return result.stdout.strip() if result.returncode == 0 else "" + + +def _normalize_remote(remote: str) -> str: + remote = remote.strip() + if remote.startswith("git@") and ":" in remote: + host_path = remote[4:].replace(":", "/", 1) + remote = f"https://{host_path}" + if remote.endswith(".git"): + remote = remote[:-4] + if "://" in remote: + parsed = urllib.parse.urlsplit(remote) + hostname = parsed.hostname or "" + if parsed.port: + hostname = f"{hostname}:{parsed.port}" + remote = urllib.parse.urlunsplit( + (parsed.scheme, hostname, parsed.path, parsed.query, parsed.fragment) + ) + return remote.rstrip("/") + + +_WILDCARD_SCOPE = re.compile(r"^\*+$") + + +def _scope_value(raw: str | None) -> str: + """Reject wildcards as identities: they are filter syntax and would widen the scope.""" + value = (raw or "").strip() + return "" if _WILDCARD_SCOPE.match(value) else value + + +SEARCH_SCOPES = ("repo", "dir", "mine") +DEFAULT_SEARCH_SCOPE = "repo" + +def directory_app_id(repo: RepoContext) -> str: + """The app_id of the directory this session runs in: the repository at the root, repository/path below it.""" + return f"{repo.app_id}/{repo.directory}" if repo.directory else repo.app_id + + +def directory_chain(repo: RepoContext) -> list[str]: + """Every directory a memory belongs to, from the top-level folder down to the one it was written in.""" + parts = repo.directory.split("/") if repo.directory else [] + return ["/".join(parts[: index + 1]) for index in range(len(parts))] + + +def _shared_project_ids(repo: RepoContext) -> list[str]: + """Current and pre-upgrade namespaces, shared by recall and explicit deletion.""" + if not repo.identity.startswith("local:") and repo.project_id != repo.app_id: + return [repo.project_id, repo.app_id] + return [repo.project_id] + + +def _search_filters(user: str, repo: RepoContext, scope: str) -> dict[str, Any]: + """Build the scope filter: app_id scopes to the repo, then union shared and personal lanes.""" + app_scope = {"app_id": repo.app_id} + mine = {"AND": [{"user_id": user}, app_scope]} + if scope == "mine": + return mine + projects = [{"AND": [{"agent_id": project_id}, app_scope]} for project_id in _shared_project_ids(repo)] + shared: dict[str, Any] = projects[0] if len(projects) == 1 else {"OR": projects} + if scope == "dir" and repo.directory: + shared = {"AND": [shared, {"metadata": {"dirs": {"contains": repo.directory}}}]} + return {"OR": [shared, mine]} + + +def search_scope() -> str: + configured = ( + _plugin_option("search_scope", "MEM0_CODE_SEARCH_SCOPE") or "" + ).strip().lower() + return configured if configured in SEARCH_SCOPES else DEFAULT_SEARCH_SCOPE + + +def resolve_search_scope(scope: str | None) -> str: + value = (scope or search_scope()).strip().lower() + if value not in SEARCH_SCOPES: + raise ValueError(f"Unknown search scope: {value}") + return value + + +def _legacy_project_map(cwd: str, root: str, raw_remote: str) -> str: + """Return the project name used by the previous Claude Code plugin.""" + try: + data = json.loads((Path.home() / ".mem0" / "project_map.json").read_text()) + except (OSError, json.JSONDecodeError): + return "" + if not isinstance(data, dict): + return "" + + keys = list(dict.fromkeys([cwd, root, os.path.realpath(cwd), os.path.realpath(root)])) + if raw_remote: + keys.append(f"remote:{hashlib.sha256(raw_remote.encode()).hexdigest()[:16]}") + for key in keys: + value = data.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + return "" + + +def _legacy_project_id(cwd: str, root: str, raw_remote: str, identity: str) -> str: + """Use the repository namespace created by the previous Mem0 plugin.""" + configured = _scope_value(os.environ.get("MEM0_PROJECT_ID")) + if configured: + return configured + + mapped = _scope_value(_legacy_project_map(cwd, root, raw_remote)) + if mapped: + return mapped + + remote = raw_remote or ("" if identity.startswith("local:") else identity) + remote = remote.strip().removesuffix(".git") + for prefix in ("https://", "http://", "ssh://", "git://"): + if remote.startswith(prefix): + remote = remote[len(prefix) :] + break + else: + remote = re.sub(r"^git@", "", remote) + parts = [part for part in remote.replace(":", "/", 1).split("/") if part] + if len(parts) >= 2: + return f"{parts[-2]}-{parts[-1]}".replace("/", "-").replace(":", "-") + if parts: + return parts[-1].replace("/", "-").replace(":", "-") + return os.path.basename(root or cwd) or "unknown" + + +@dataclass(frozen=True) +class RepoContext: + cwd: str + root: str + identity: str + app_id: str + branch: str + head_sha: str + project_id: str = "" + directory: str = "" + + +def _project_id(root: str, identity: str, app_id: str) -> str: + """The shared namespace: includes a host hash so repos with the same owner/name on different hosts stay apart.""" + if not identity.startswith("local:"): + return f"{app_id}-{hashlib.sha256(identity.encode()).hexdigest()[:10]}" + return f"local-{app_id}-{hashlib.sha256(root.encode()).hexdigest()[:10]}" + + +def _relative_directory(cwd: str, root: str) -> str: + relative = os.path.relpath(cwd, root) + return "" if relative == "." or relative.startswith("..") else relative.replace(os.sep, "/") + + +@dataclass(frozen=True) +class MemorySearchResult: + succeeded: bool + matched_count: int + already_shown_count: int + memories: list[dict[str, Any]] + + +@functools.lru_cache(maxsize=64) +def _resolve_repo_cached(cwd: str) -> RepoContext: + given_cwd = cwd + cwd = os.path.realpath(cwd) + given_root = _git(cwd, "rev-parse", "--show-toplevel") or given_cwd + root = os.path.realpath(given_root) + raw_remote = _git(root, "config", "--get", "remote.origin.url") + remote = _normalize_remote(raw_remote) + identity = remote or f"local:{root}" + app_id = _legacy_project_id(given_cwd, given_root, raw_remote, identity) + return RepoContext( + cwd=cwd, + root=root, + identity=identity, + app_id=app_id, + branch=_git(root, "branch", "--show-current") or "detached", + head_sha=_git(root, "rev-parse", "HEAD"), + project_id=_project_id(root, identity, app_id), + directory=_relative_directory(cwd, root), + ) + + +def resolve_repo(cwd: str | None) -> RepoContext: + return _resolve_repo_cached(os.path.abspath(cwd or os.getcwd())) + + +def api_key() -> str: + configured = ( + os.environ.get("MEM0_API_KEY") + or os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if configured: + return configured + try: + return (data_dir() / "api-key").read_text(encoding="utf-8").strip() + except OSError: + return "" + + +def cache_plugin_api_key() -> bool: + """Bridge host's hook-only sensitive config into plugin-owned storage.""" + configured = ( + os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if not configured: + return False + + directory = data_dir() + directory.mkdir(parents=True, exist_ok=True) + path = directory / "api-key" + temporary = directory / f"api-key.{os.getpid()}.tmp" + descriptor = os.open( + temporary, + os.O_WRONLY | os.O_CREAT | os.O_TRUNC, + 0o600, + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + handle.write(configured) + os.replace(temporary, path) + os.chmod(path, 0o600) + finally: + try: + temporary.unlink() + except FileNotFoundError: + pass + return True + + +def clear_stale_api_key_cache() -> bool: + """Drop the cached key file once every configured key source is gone.""" + configured = ( + os.environ.get("MEM0_API_KEY") + or os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if configured: + return False + path = data_dir() / "api-key" + if not path.exists(): + return False + try: + path.unlink() + except OSError: + return False + return True + + +def detached_process_kwargs(platform: str | None = None) -> dict: + """Keep a spawned worker alive after the coding agent exits, on POSIX and Windows.""" + if (platform or sys.platform) == "win32": + return { + "creationflags": subprocess.DETACHED_PROCESS + | subprocess.CREATE_NEW_PROCESS_GROUP + } + return {"start_new_session": True} + + +def _plugin_option(name: str, fallback: str = "") -> str: + return ( + os.environ.get(f"PLUGIN_OPTION_{name.upper()}") + or os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name.upper()}") + or os.environ.get(fallback) + or "" + ).strip() + + +def user_id() -> str: + return ( + _scope_value(_plugin_option("user_id", "MEM0_CODE_USER_ID")) + or _scope_value(os.environ.get("MEM0_USER_ID")) + or _scope_value(os.environ.get("MEM0_RESOLVED_USER_ID")) + or _scope_value(os.environ.get("USER")) + or _scope_value(os.environ.get("USERNAME")) + or "default" + ) + + +def data_dir() -> Path: + configured = ( + os.environ.get("MEM0_CODE_DATA_DIR") + or os.environ.get("MEM0_PLUGIN_DATA_DIR") + or os.environ.get("PLUGIN_DATA") + or os.environ.get("CLAUDE_PLUGIN_DATA") + ) + return ( + Path(configured).expanduser() if configured else Path.home() / ".mem0" / _harness_data_dir_name + ) + + +def _bool_option(name: str, fallback: str, default: bool = False) -> bool: + value = _plugin_option(name, fallback) + if not value: + return default + return value.lower() in {"1", "true", "yes", "on"} + + +def _int_option(name: str, fallback: str, default: int) -> int: + value = _plugin_option(name, fallback) + try: + return int(value) if value else default + except ValueError: + return default + + + +def _checkpoint_message(event: dict[str, Any]) -> str: + kind = event.get("kind") + payload = event.get("payload") or {} + if kind == "user_prompt": + return redact(payload.get("text", "")).strip() + if kind == "assistant_stop": + transcript_messages = payload.get("transcript_messages") or [] + if isinstance(transcript_messages, list): + text = "\n".join( + str(message.get("content") or "") + for message in transcript_messages + if isinstance(message, dict) and message.get("content") + ) + if text: + return text + return redact(payload.get("text", "")).strip() + if kind == "sidekick_stop": + return redact(payload.get("final_message", "")).strip() + return "" + + +def checkpoint_stats(events: list[dict[str, Any]]) -> tuple[int, int, int]: + """Return completed exchanges, messages, and source characters.""" + completed = sum(event.get("kind") == "assistant_stop" for event in events) + contents = [content for event in events if (content := _checkpoint_message(event))] + return completed, len(contents), sum(len(content) for content in contents) + + +def select_checkpoint_events( + events: list[dict[str, Any]], *, force: bool +) -> list[dict[str, Any]]: + """Select one ordered extraction block without splitting an exchange.""" + for index, event in enumerate(events): + if event.get("kind") != "assistant_stop": + continue + candidate = events[: index + 1] + completed, messages, source_chars = checkpoint_stats(candidate) + if ( + completed >= CHECKPOINT_EXCHANGES + or messages >= CHECKPOINT_MESSAGES + or source_chars >= CHECKPOINT_SOURCE_CHARS + ): + return candidate + return events if force else [] + + +class EvidenceStore: + def __init__(self, path: Path | None = None): + directory = data_dir() if path is None else path.parent + directory.mkdir(parents=True, exist_ok=True) + self.path = path or directory / "evidence.sqlite3" + try: + self._open() + except sqlite3.DatabaseError: + self._quarantine() + self._open() + + def _open(self) -> None: + self.conn = sqlite3.connect(self.path, timeout=10) + self.conn.row_factory = sqlite3.Row + try: + self.conn.execute("PRAGMA journal_mode=WAL") + self.conn.execute("PRAGMA busy_timeout=10000") + self._migrate() + except sqlite3.DatabaseError: + self.conn.close() + raise + + def _quarantine(self) -> None: + """Move an unreadable database aside so capture restarts cleanly.""" + stamp = int(time.time()) + for suffix in ("", "-wal", "-shm"): + source = Path(f"{self.path}{suffix}") + try: + source.replace(f"{self.path}.corrupt-{stamp}{suffix}") + except FileNotFoundError: + continue + except OSError: + try: + source.unlink() + except OSError: + pass + telemetry.record("db_quarantined") + + def close(self) -> None: + self.conn.close() + + def _migrate(self) -> None: + self.conn.executescript( + """ + CREATE TABLE IF NOT EXISTS events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + session_id TEXT NOT NULL, + created_at TEXT NOT NULL, + kind TEXT NOT NULL, + payload_json TEXT NOT NULL, + flush_id TEXT + ); + CREATE INDEX IF NOT EXISTS events_session_idx + ON events(repo_id, session_id, flush_id, id); + + CREATE TABLE IF NOT EXISTS session_scopes ( + session_id TEXT PRIMARY KEY, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + root TEXT NOT NULL, + branch TEXT NOT NULL, + head_sha TEXT NOT NULL, + created_at TEXT NOT NULL, + directory TEXT NOT NULL DEFAULT '' + ); + + CREATE TABLE IF NOT EXISTS flushes ( + packet_id TEXT PRIMARY KEY, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + session_id TEXT NOT NULL, + reason TEXT NOT NULL, + event_start INTEGER NOT NULL, + event_end INTEGER NOT NULL, + status TEXT NOT NULL, + episode_event_id TEXT, + semantic_event_id TEXT, + error TEXT, + attempts INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS retrievals ( + session_id TEXT NOT NULL, + repo_id TEXT NOT NULL, + memory_id TEXT NOT NULL, + injected_at TEXT NOT NULL, + rank INTEGER, + score REAL, + memory_text TEXT, + context_chars INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY(session_id, repo_id, memory_id) + ); + + CREATE TABLE IF NOT EXISTS operations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created_at TEXT NOT NULL, + repo_id TEXT NOT NULL, + session_id TEXT NOT NULL, + operation TEXT NOT NULL, + duration_ms REAL NOT NULL, + success INTEGER NOT NULL, + item_count INTEGER NOT NULL DEFAULT 0, + request_chars INTEGER NOT NULL DEFAULT 0, + response_chars INTEGER NOT NULL DEFAULT 0, + error TEXT + ); + + CREATE TABLE IF NOT EXISTS sidekick_runs ( + repo_id TEXT NOT NULL, + session_id TEXT NOT NULL, + agent_id TEXT NOT NULL, + agent_type TEXT NOT NULL, + started_at TEXT NOT NULL, + stopped_at TEXT, + transcript_path TEXT, + context_chars INTEGER NOT NULL DEFAULT 0, + final_message TEXT, + PRIMARY KEY(repo_id, session_id, agent_id) + ); + CREATE INDEX IF NOT EXISTS sidekick_runs_repo_idx + ON sidekick_runs(repo_id, started_at); + + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + """ + ) + # Remove the pre-0.1.1 no-tools snapshot implementation. The real coding + # sidekick is a native Claude Code agent and stores no state in this DB. + self.conn.executescript( + """ + DROP TABLE IF EXISTS sidekick_calls; + DROP TABLE IF EXISTS sidekick_snapshots; + DROP TABLE IF EXISTS sidekick_state; + DROP TABLE IF EXISTS sidekick_packets; + """ + ) + self._ensure_column("retrievals", "rank", "INTEGER") + self._ensure_column("retrievals", "score", "REAL") + self._ensure_column("retrievals", "memory_text", "TEXT") + self._ensure_column("retrievals", "context_chars", "INTEGER NOT NULL DEFAULT 0") + self._ensure_column("flushes", "attempts", "INTEGER NOT NULL DEFAULT 0") + self._ensure_column("session_scopes", "directory", "TEXT NOT NULL DEFAULT ''") + self.conn.commit() + + def _ensure_column(self, table: str, column: str, declaration: str) -> None: + columns = { + str(row["name"]) + for row in self.conn.execute(f"PRAGMA table_info({table})").fetchall() + } + if column not in columns: + self.conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {declaration}") + + def record_event( + self, + repo: RepoContext, + session_id: str, + kind: str, + payload: dict[str, Any], + ) -> int: + cursor = self.conn.execute( + """INSERT INTO events + (repo_id, app_id, session_id, created_at, kind, payload_json) + VALUES (?, ?, ?, ?, ?, ?)""", + ( + repo.identity, + repo.app_id, + session_id, + utc_now(), + kind, + json.dumps(payload, ensure_ascii=False, sort_keys=True), + ), + ) + self.conn.commit() + return int(cursor.lastrowid) + + def record_assistant_response(self, repo: RepoContext, session_id: str, message: str) -> None: + """Ignore repeated response hooks until another prompt or a different answer arrives.""" + with self.conn: + # Serialize the check and insert across concurrent Stop and SessionEnd hooks. + self.conn.execute("BEGIN IMMEDIATE") + previous = self.conn.execute( + """SELECT kind, payload_json FROM events + WHERE repo_id = ? AND session_id = ? AND kind IN ('user_prompt', 'assistant_stop') + ORDER BY id DESC LIMIT 1""", + (repo.identity, session_id), + ).fetchone() + if ( + previous is not None + and previous["kind"] == "assistant_stop" + and json.loads(previous["payload_json"]).get("text") == message + ): + return + self.record_event(repo, session_id, "assistant_stop", {"text": message}) + + def repo_for_session(self, session_id: str, cwd: str | None) -> RepoContext: + """Keep one project scope for every hook in a coding-agent session.""" + current = resolve_repo(cwd) + if session_id == "unknown-session": + return current + + with self.conn: + self.conn.execute( + """INSERT OR IGNORE INTO session_scopes + (session_id, repo_id, app_id, root, branch, head_sha, created_at, directory) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", + ( + session_id, + current.identity, + current.app_id, + current.root, + current.branch, + current.head_sha, + utc_now(), + current.directory, + ), + ) + scope = self.conn.execute( + "SELECT * FROM session_scopes WHERE session_id = ?", (session_id,) + ).fetchone() + same_git_repo = ( + current.identity == scope["repo_id"] and bool(current.head_sha) + ) + pinned = current if same_git_repo else resolve_repo(str(scope["root"])) + return RepoContext( + cwd=current.cwd, + root=pinned.root, + identity=str(scope["repo_id"]), + app_id=str(scope["app_id"]), + branch=pinned.branch, + head_sha=pinned.head_sha, + project_id=pinned.project_id, + directory=str(scope["directory"] or ""), + ) + + def prepare_flush( + self, repo: RepoContext, session_id: str, reason: str + ) -> tuple[str, list[dict[str, Any]]] | None: + with self.conn: + self.conn.execute("BEGIN IMMEDIATE") + existing = self.conn.execute( + """SELECT * FROM flushes + WHERE repo_id = ? AND session_id = ? + AND status NOT IN ('semantic-succeeded', 'explicitly-stored', 'gave-up') + ORDER BY created_at LIMIT 1""", + (repo.identity, session_id), + ).fetchone() + if existing and int(existing["attempts"] or 0) >= MAX_FLUSH_ATTEMPTS: + self.conn.execute( + "UPDATE flushes SET status = 'gave-up', updated_at = ? WHERE packet_id = ?", + (utc_now(), existing["packet_id"]), + ) + telemetry.record( + "flush", + repo=repo, + session_id=session_id, + reason=reason, + status="gave-up", + success=False, + attempts=int(existing["attempts"] or 0), + ) + existing = None + if existing: + if reason != "periodic" and existing["reason"] == "periodic": + self.conn.execute( + "UPDATE flushes SET reason = ?, updated_at = ? WHERE packet_id = ?", + (reason, utc_now(), existing["packet_id"]), + ) + existing_rows = self.conn.execute( + "SELECT * FROM events WHERE flush_id = ? ORDER BY id", + (existing["packet_id"],), + ).fetchall() + if existing_rows: + return str(existing["packet_id"]), [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in existing_rows + ] + + rows = self.conn.execute( + """SELECT * FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id""", + (repo.identity, session_id), + ).fetchall() + if not rows: + return None + + events = [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in rows + ] + events = select_checkpoint_events(events, force=reason != "periodic") + if not events: + return None + event_start, event_end = events[0]["id"], events[-1]["id"] + packet_material = f"{repo.identity}\0{session_id}\0{event_start}\0{event_end}" + packet_id = hashlib.sha256(packet_material.encode()).hexdigest()[:32] + now = utc_now() + + self.conn.execute( + """INSERT OR IGNORE INTO flushes + (packet_id, repo_id, app_id, session_id, reason, event_start, + event_end, status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, 'prepared', ?, ?)""", + ( + packet_id, + repo.identity, + repo.app_id, + session_id, + reason, + event_start, + event_end, + now, + now, + ), + ) + event_ids = [event["id"] for event in events] + placeholders = ", ".join("?" for _ in event_ids) + self.conn.execute( + f"UPDATE events SET flush_id = ? " + f"WHERE id IN ({placeholders}) AND flush_id IS NULL", + (packet_id, *event_ids), + ) + return packet_id, events + + def checkpoint_due(self, repo_id: str, session_id: str) -> bool: + if self.has_inflight_flush(repo_id, session_id): + return False + rows = self.conn.execute( + """SELECT * FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id""", + (repo_id, session_id), + ).fetchall() + events = [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in rows + ] + return bool(select_checkpoint_events(events, force=False)) + + def has_inflight_flush(self, repo_id: str, session_id: str) -> bool: + return ( + self.conn.execute( + """SELECT 1 FROM flushes + WHERE repo_id = ? AND session_id = ? + AND status IN ('prepared', 'semantic-queued') + LIMIT 1""", + (repo_id, session_id), + ).fetchone() + is not None + ) + + def flush_record(self, packet_id: str) -> dict[str, Any] | None: + row = self.conn.execute( + "SELECT * FROM flushes WHERE packet_id = ?", (packet_id,) + ).fetchone() + return dict(row) if row else None + + def has_unflushed_events(self, repo_id: str, session_id: str) -> bool: + return ( + self.conn.execute( + """SELECT 1 FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + LIMIT 1""", + (repo_id, session_id), + ).fetchone() + is not None + ) + + def unflushed_starts_with_session_start( + self, repo_id: str, session_id: str + ) -> bool: + row = self.conn.execute( + """SELECT kind FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id LIMIT 1""", + (repo_id, session_id), + ).fetchone() + return bool(row and row["kind"] == "session_start") + + def update_flush(self, packet_id: str, **fields: Any) -> None: + allowed = {"status", "episode_event_id", "semantic_event_id", "error"} + updates = {key: value for key, value in fields.items() if key in allowed} + updates["updated_at"] = utc_now() + clause = ", ".join(f"{key} = ?" for key in updates) + failed = str(fields.get("status", "")) in { + "error", + "semantic-failed", + "semantic-timeout", + "semantic-missing", + } + if failed: + clause += ", attempts = attempts + 1" + with self.conn: + self.conn.execute( + f"UPDATE flushes SET {clause} WHERE packet_id = ?", + [*updates.values(), packet_id], + ) + + def unseen( + self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]] + ) -> list[dict[str, Any]]: + seen = { + row["memory_id"] + for row in self.conn.execute( + "SELECT memory_id FROM retrievals WHERE session_id = ? AND repo_id = ?", + (session_id, repo_id), + ) + } + return [memory for memory in memories if str(memory.get("id", "")) not in seen] + + def mark_injected( + self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]] + ) -> None: + now = utc_now() + with self.conn: + for rank, memory in enumerate(memories, start=1): + memory_id = str(memory.get("id", "")) + if memory_id: + memory_text = bounded( + memory.get("memory") or memory.get("text") or "", + 4000, + ) + try: + score = float(memory["score"]) + except (KeyError, TypeError, ValueError): + score = None + self.conn.execute( + """INSERT OR IGNORE INTO retrievals + (session_id, repo_id, memory_id, injected_at, rank, + score, memory_text, context_chars) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", + ( + session_id, + repo_id, + memory_id, + now, + rank, + score, + memory_text, + len(memory_text), + ), + ) + + def injected_memories( + self, session_id: str, repo_id: str + ) -> list[dict[str, Any]]: + """Return the exact memories already supplied to the main conversation.""" + rows = self.conn.execute( + """SELECT memory_id, rank, score, memory_text + FROM retrievals + WHERE session_id = ? AND repo_id = ? + ORDER BY COALESCE(rank, 2147483647), injected_at, memory_id""", + (session_id, repo_id), + ).fetchall() + return [ + { + "id": row["memory_id"], + "memory": row["memory_text"], + "score": row["score"], + } + for row in rows + if row["memory_text"] + ] + + def start_sidekick( + self, + repo: RepoContext, + session_id: str, + agent_id: str, + agent_type: str, + context_chars: int, + ) -> bool: + """Record one native sidekick instance and whether context was first sent.""" + with self.conn: + cursor = self.conn.execute( + """INSERT OR IGNORE INTO sidekick_runs + (repo_id, session_id, agent_id, agent_type, started_at, + context_chars) + VALUES (?, ?, ?, ?, ?, ?)""", + ( + repo.identity, + session_id, + agent_id, + agent_type, + utc_now(), + context_chars, + ), + ) + return int(cursor.rowcount) > 0 + + def stop_sidekick( + self, + repo: RepoContext, + session_id: str, + agent_id: str, + agent_type: str, + transcript_path: str, + final_message: str, + ) -> str: + now = utc_now() + self.conn.execute("BEGIN IMMEDIATE") + try: + if not agent_id: + rows = self.conn.execute( + """SELECT agent_id FROM sidekick_runs + WHERE repo_id = ? AND session_id = ? AND agent_type = ? AND stopped_at IS NULL + LIMIT 2""", + (repo.identity, session_id, agent_type), + ).fetchall() + # Without a host ID, overlapping runs cannot be correlated reliably. + agent_id = rows[0]["agent_id"] if len(rows) == 1 else f"unknown-agent-{time.time_ns()}" + self.conn.execute( + """INSERT INTO sidekick_runs + (repo_id, session_id, agent_id, agent_type, started_at, + stopped_at, transcript_path, final_message) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(repo_id, session_id, agent_id) DO UPDATE SET + stopped_at = excluded.stopped_at, + transcript_path = excluded.transcript_path, + final_message = excluded.final_message""", + ( + repo.identity, + session_id, + agent_id, + agent_type, + now, + now, + bounded(transcript_path, 2000), + redact(final_message).strip(), + ), + ) + self.conn.commit() + except Exception: + self.conn.rollback() + raise + return agent_id + + def operation( + self, + repo: RepoContext, + session_id: str, + operation: str, + duration_ms: float, + success: bool, + *, + item_count: int = 0, + request_chars: int = 0, + response_chars: int = 0, + error: str = "", + ) -> None: + with self.conn: + self.conn.execute( + """INSERT INTO operations + (created_at, repo_id, session_id, operation, duration_ms, + success, item_count, request_chars, response_chars, error) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", + ( + utc_now(), + repo.identity, + session_id, + operation, + duration_ms, + int(success), + item_count, + request_chars, + response_chars, + bounded(error, 1000), + ), + ) + + def has_operation(self, repo_id: str, session_id: str, operation: str) -> bool: + row = self.conn.execute( + """SELECT 1 FROM operations + WHERE repo_id = ? AND session_id = ? AND operation = ? + LIMIT 1""", + (repo_id, session_id, operation), + ).fetchone() + return row is not None + + def has_event(self, repo_id: str, session_id: str, kind: str) -> bool: + row = self.conn.execute( + """SELECT 1 FROM events + WHERE repo_id = ? AND session_id = ? AND kind = ? + LIMIT 1""", + (repo_id, session_id, kind), + ).fetchone() + return row is not None + + def latest_event_payload( + self, repo_id: str, session_id: str, kind: str + ) -> dict[str, Any]: + row = self.conn.execute( + """SELECT payload_json FROM events + WHERE repo_id = ? AND session_id = ? AND kind = ? + ORDER BY id DESC LIMIT 1""", + (repo_id, session_id, kind), + ).fetchone() + if not row: + return {} + try: + payload = json.loads(row["payload_json"]) + except json.JSONDecodeError: + return {} + return payload if isinstance(payload, dict) else {} + + def setting(self, key: str, default: str = "") -> str: + row = self.conn.execute( + "SELECT value FROM settings WHERE key = ?", (key,) + ).fetchone() + return str(row["value"]) if row else default + + def set_setting(self, key: str, value: str) -> None: + with self.conn: + self.conn.execute( + """INSERT INTO settings(key, value, updated_at) + VALUES (?, ?, ?) + ON CONFLICT(key) DO UPDATE SET + value = excluded.value, + updated_at = excluded.updated_at""", + (key, value, utc_now()), + ) + + def is_paused(self) -> bool: + return self.setting("paused", "false").lower() in { + "1", + "true", + "yes", + "on", + } + + def forget_local_repo(self, repo_id: str) -> dict[str, int]: + tables = { + "events": "repo_id", + "session_scopes": "repo_id", + "flushes": "repo_id", + "retrievals": "repo_id", + "operations": "repo_id", + "sidekick_runs": "repo_id", + } + removed: dict[str, int] = {} + with self.conn: + for table, column in tables.items(): + cursor = self.conn.execute( + f"DELETE FROM {table} WHERE {column} = ?", (repo_id,) + ) + removed[table] = max(int(cursor.rowcount), 0) + return removed + + def status(self, repo_id: str) -> dict[str, Any]: + def count(table: str) -> int: + return int( + self.conn.execute( + f"SELECT COUNT(*) FROM {table} WHERE repo_id = ?", (repo_id,) + ).fetchone()[0] + ) + + last_operation = self.conn.execute( + """SELECT created_at, operation, duration_ms, success, item_count, error + FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""", + (repo_id,), + ).fetchone() + last_sidekick = self.conn.execute( + """SELECT session_id, agent_id, agent_type, started_at, stopped_at, + context_chars + FROM sidekick_runs WHERE repo_id = ? + ORDER BY started_at DESC LIMIT 1""", + (repo_id,), + ).fetchone() + return { + "paused": self.is_paused(), + "events": count("events"), + "flushes": count("flushes"), + "retrievals": count("retrievals"), + "sidekick_runs": count("sidekick_runs"), + "last_operation": dict(last_operation) if last_operation else None, + "last_sidekick": dict(last_sidekick) if last_sidekick else None, + } + + +def _session_id(hook_input: dict[str, Any]) -> str: + return str(hook_input.get("session_id") or "unknown-session") + + +def record_session_start(store: EvidenceStore, hook_input: dict[str, Any]) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + store.record_event( + repo, + session_id, + "session_start", + { + "source": hook_input.get("source", "startup"), + "model": bounded(hook_input.get("model", ""), 200), + "branch": repo.branch, + "head_sha": repo.head_sha, + }, + ) + telemetry.record( + "session_start", + repo=repo, + session_id=session_id, + trigger=bounded(str(hook_input.get("source", "startup")), 60), + model=bounded(hook_input.get("model", ""), 200), + api_key_configured=bool(api_key()), + is_git_repo=not repo.identity.startswith("local:"), + ) + + +def record_user_prompt( + store: EvidenceStore, hook_input: dict[str, Any] +) -> tuple[RepoContext, str, str, bool]: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + prompt = redact(hook_input.get("prompt", "")).strip() + is_first_prompt = not store.has_event(repo.identity, session_id, "user_prompt") + store.record_event(repo, session_id, "user_prompt", {"text": prompt}) + return repo, session_id, prompt, is_first_prompt + + +def _tool_result_preview(response: Any) -> str: + if isinstance(response, dict): + selected = {} + for key in ( + "stdout", + "stderr", + "output", + "content", + "error", + "filePath", + "success", + "interrupted", + ): + if key in response: + selected[key] = response[key] + response = selected or {"keys": sorted(response.keys())[:20]} + return bounded(response, MAX_RESULT_CHARS) + + +def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> dict[str, Any]: + name = str(hook_input.get("tool_name") or "unknown") + tool_input = hook_input.get("tool_input") or {} + if not isinstance(tool_input, dict): + tool_input = {} + payload: dict[str, Any] = { + "tool": name, + "failed": failed, + "duration_ms": hook_input.get("duration_ms"), + "agent_role": "sidekick" if hook_input.get("agent_id") else "main", + } + if hook_input.get("agent_id"): + payload["agent_id"] = bounded(hook_input["agent_id"], 200) + if hook_input.get("agent_type"): + payload["agent_type"] = bounded(hook_input["agent_type"], 200) + + if name in {"Read", "Write", "Edit", "MultiEdit", "NotebookEdit"}: + path = tool_input.get("file_path") or tool_input.get("notebook_path") + if path: + payload["path"] = bounded(path, 1000) + if name in {"Write", "Edit", "MultiEdit", "NotebookEdit"}: + payload["mutation_chars"] = sum( + len(str(tool_input.get(key, ""))) + for key in ("content", "new_string", "new_source", "edits") + ) + elif name == "Bash" or "command" in tool_input: + command = bounded(tool_input.get("command", ""), MAX_COMMAND_CHARS) + payload["command"] = command + payload["command_kind"] = ( + "test" + if TEST_COMMAND_RE.search(command) + else "build" + if BUILD_COMMAND_RE.search(command) + else "shell" + ) + response = ( + hook_input.get("error") if failed else hook_input.get("tool_response") + ) + payload["result_preview"] = _tool_result_preview(response) + elif name in {"Grep", "Glob", "WebSearch", "WebFetch"}: + for key in ("pattern", "path", "query", "url"): + if tool_input.get(key): + payload[key] = bounded(tool_input[key], 1000) + else: + payload["input_keys"] = sorted(tool_input.keys())[:20] + if failed: + payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS) + + if failed and "error" not in payload: + payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS) + return payload + + +def record_tool( + store: EvidenceStore, hook_input: dict[str, Any], *, failed: bool | None = False +) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + payload = tool_payload(hook_input, failed=failed) + if payload.get("path"): + payload["repo_path"] = _repo_relative_path(repo, str(payload["path"])) + store.record_event( + repo, + session_id, + "tool_failure" if failed else "tool_result", + payload, + ) + + +def record_sidekick_start( + store: EvidenceStore, hook_input: dict[str, Any], *, inject_context: bool = True +) -> str: + """Record a native sidekick and reuse the main turn's retrieved memories.""" + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200) + agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + context = combine_context( + format_context(store.injected_memories(session_id, repo.identity)) + ) + if not inject_context: + context = "" + first_start = store.start_sidekick( + repo, session_id, agent_id, agent_type, len(context) + ) + store.record_event( + repo, + session_id, + "sidekick_start", + { + "agent_id": agent_id, + "agent_type": agent_type, + "context_chars": len(context) if first_start else 0, + "worktree_root": bounded(repo.root, 2000), + }, + ) + telemetry.record( + "sidekick", + repo=repo, + session_id=session_id, + phase="start", + first_start=first_start, + context_chars=len(context) if first_start else 0, + ) + return context if first_start else "" + + +def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_id = bounded(hook_input.get("agent_id", ""), 200) + final_message = redact(hook_input.get("last_assistant_message", "")).strip() + transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000) + agent_id = store.stop_sidekick( + repo, + session_id, + agent_id, + agent_type, + transcript_path, + final_message, + ) + store.record_event( + repo, + session_id, + "sidekick_stop", + { + "agent_id": agent_id, + "agent_type": agent_type, + "transcript_path": transcript_path, + "final_message": final_message, + }, + ) + telemetry.record( + "sidekick", + repo=repo, + session_id=session_id, + phase="stop", + has_transcript=bool(transcript_path), + message_chars=len(final_message), + ) + + +def _ordered_unique(values: Iterable[str]) -> list[str]: + seen: set[str] = set() + result = [] + for value in values: + if value and value not in seen: + seen.add(value) + result.append(value) + return result + + +def _repo_relative_path(repo: RepoContext, value: str) -> str: + value = str(value or "").strip() + if not value: + return "" + try: + path = Path(value) + if path.is_absolute(): + try: + return path.resolve().relative_to(Path(repo.root).resolve()).as_posix() + except ValueError: + return "" + except (OSError, ValueError): + pass + return bounded(value, 1000) + + +def _render_command_lines(commands: list[dict[str, str]]) -> list[str]: + lines = [] + for command in commands: + line = f"- [{command['status']}/{command['kind']}] {command['command']}" + if command["result"]: + line += f" — {bounded(command['result'], 500).replace(chr(10), ' ')}" + lines.append(line) + return lines + + +def build_episode( + repo: RepoContext, + session_id: str, + packet_id: str, + events: list[dict[str, Any]], + *, + canonical_task: str = "", + task_outcome: str = "", +) -> tuple[str, dict[str, Any]]: + prompts = [ + redact(e["payload"].get("text", "")).strip() + for e in events + if e["kind"] == "user_prompt" and e["payload"].get("text") + ] + assistant_conclusions = [ + redact(e["payload"].get("text", "")).strip() + for e in events + if e["kind"] == "assistant_stop" and e["payload"].get("text") + ] + sidekick_outcomes = [ + redact(e["payload"].get("final_message", "")).strip() + for e in events + if e["kind"] == "sidekick_stop" and e["payload"].get("final_message") + ] + tools = [ + e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"} + and e["payload"].get("agent_role", "main") == "main" + ] + read_paths = _ordered_unique( + _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", ""))) + for t in tools + if t.get("tool") == "Read" + ) + modified_paths = _ordered_unique( + _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", ""))) + for t in tools + if t.get("tool") in {"Write", "Edit", "MultiEdit", "NotebookEdit"} + ) + searches = [ + {key: t[key] for key in ("tool", "pattern", "path", "query", "url") if key in t} + for t in tools + if t.get("tool") in {"Grep", "Glob", "WebSearch", "WebFetch"} + ] + commands = [ + { + "command": t.get("command", ""), + "kind": t.get("command_kind", "shell"), + "status": "unknown" if t.get("failed", False) is None else "failed" if t.get("failed") else "succeeded", + "result": t.get("result_preview", ""), + } + for t in tools + if t.get("command") + ] + + task = bounded(canonical_task or (prompts[0] if prompts else ""), 4000) + conclusion = redact(assistant_conclusions[-1] if assistant_conclusions else "").strip() + outcome = bounded(task_outcome, 2000) + + extraction_messages: list[dict[str, str]] = [] + pending_user_messages: list[dict[str, str]] = [] + if task and not prompts: + pending_user_messages.append({"role": "user", "content": task}) + for event in events: + if event["kind"] == "user_prompt" and event["payload"].get("text"): + pending_user_messages.append( + { + "role": "user", + "content": redact(event["payload"].get("text", "")).strip(), + } + ) + elif event["kind"] == "assistant_stop": + transcript_messages = event["payload"].get("transcript_messages") or [] + if isinstance(transcript_messages, list) and transcript_messages: + transcript_users = { + redact(message.get("content") or "").strip() + for message in transcript_messages + if isinstance(message, dict) and message.get("role") == "user" + } + extraction_messages.extend( + message + for message in pending_user_messages + if message["content"].strip() not in transcript_users + ) + extraction_messages.extend( + { + "role": str(message.get("role") or ""), + "content": redact(message.get("content") or "").strip(), + } + for message in transcript_messages + if isinstance(message, dict) + and message.get("role") in {"user", "assistant"} + and message.get("content") + ) + else: + extraction_messages.extend(pending_user_messages) + if event["payload"].get("text"): + extraction_messages.append( + { + "role": "assistant", + "content": redact(event["payload"].get("text", "")).strip(), + } + ) + pending_user_messages = [] + elif event["kind"] == "sidekick_stop": + pass + extraction_messages.extend(pending_user_messages) + + structured = { + "packet_id": packet_id, + "repo": repo.identity, + "app_id": repo.app_id, + "session_id": session_id, + "branch": repo.branch, + "head_sha": repo.head_sha, + "task": task, + "task_outcome": outcome, + "assistant_conclusion": conclusion, + "user_messages": prompts, + "assistant_outcomes": assistant_conclusions, + "sidekick_outcomes": sidekick_outcomes, + "extraction_messages": extraction_messages, + "files_read": read_paths[:50], + "files_modified": modified_paths[:50], + "searches": searches[-30:], + "commands": commands[-30:], + } + lines = ["Coding-session episode"] + if task: + lines.extend(["", "Task:", task]) + if modified_paths: + lines.extend( + ["", "Files modified:", *[f"- {path}" for path in modified_paths[:50]]] + ) + if read_paths: + lines.extend(["", "Files read:", *[f"- {path}" for path in read_paths[:50]]]) + if commands: + lines.append("") + lines.append("Observed commands:") + lines.extend(_render_command_lines(commands[-30:])) + if searches: + lines.extend( + [ + "", + "Observed searches:", + *[ + f"- {json.dumps(item, ensure_ascii=False, sort_keys=True)}" + for item in searches[-20:] + ], + ] + ) + if conclusion: + lines.extend(["", "Agent conclusion:", conclusion]) + if outcome: + lines.extend(["", "Task outcome:", outcome]) + lines.extend( + [ + "", + f"Provenance: repo={repo.identity}; branch={repo.branch}; head={repo.head_sha}; packet={packet_id}", + ] + ) + content = "\n".join(lines) + return bounded(content, MAX_EPISODE_CHARS), structured + + +def build_semantic_evidence(structured: dict[str, Any]) -> str: + """Format changed paths for memory extraction. + + Test and build results remain in the local evidence store for diagnostics, + but are not useful repository knowledge by default and should not steer + memory extraction toward transient verification details. + """ + modified_paths = [ + bounded(path, 500) for path in structured.get("files_modified", [])[:20] + ] + commands = structured.get("commands") or [] + if not any(command.get("status") == "failed" for command in commands): + commands = [] + + if not modified_paths and not commands: + return "" + + lines = ["Additional repository details from this session"] + if modified_paths: + lines.extend( + [ + "", + "Changed paths:", + *[f"- {path}" for path in modified_paths], + ] + ) + if commands: + lines.extend(["", "Commands run in this session:", *_render_command_lines(commands)]) + return bounded("\n".join(lines), 8000) + + +def build_extraction_messages(structured: dict[str, Any]) -> list[dict[str, str]]: + """Build the session messages sent to Mem0 for memory extraction.""" + evidence = build_semantic_evidence(structured) + messages = [ + {"role": message["role"], "content": redact(message["content"]).strip()} + for message in structured.get("extraction_messages", []) + if message.get("role") in {"user", "assistant"} and message.get("content") + ] + if evidence: + for message in reversed(messages): + if message["role"] == "assistant": + message["content"] = f"{message['content']}\n\n{evidence}" + break + else: + messages.append({"role": "assistant", "content": evidence}) + + return messages + + +def _estimated_tokens(value: str) -> int: + """Conservatively estimate tokens without adding a tokenizer dependency.""" + ascii_chars = sum(ord(char) < 128 for char in value) + return math.ceil((ascii_chars * 0.4) + (len(value) - ascii_chars)) + + +def _message_tokens(messages: list[dict[str, str]]) -> int: + return _estimated_tokens(json.dumps(messages, ensure_ascii=False)) + + +def _is_agent_assignment(message: dict[str, str]) -> bool: + return message.get("role") == "assistant" and message.get( + "content", "" + ).startswith("Subagent assignment (") + + +def _is_agent_response(message: dict[str, str]) -> bool: + return message.get("role") == "assistant" and message.get( + "content", "" + ).startswith("Subagent response (") + + +def extraction_message_batches( + messages: list[dict[str, str]], + *, + max_tokens: int = MAX_EXTRACTION_INPUT_TOKENS, +) -> list[list[dict[str, str]]]: + """Keep exchanges together when possible; split oversized messages to enforce the request budget.""" + if not messages or _message_tokens(messages) <= max_tokens: + return [messages] + + exchanges: list[list[dict[str, str]]] = [] + exchange: list[dict[str, str]] = [] + for message in messages: + if message.get("role") == "user" and exchange: + exchanges.append(exchange) + exchange = [] + exchange.append(message) + if exchange: + exchanges.append(exchange) + + units: list[list[dict[str, str]]] = [] + for exchange in exchanges: + if _message_tokens(exchange) <= max_tokens: + units.append(exchange) + continue + index = 0 + while index < len(exchange): + message = exchange[index] + if ( + _is_agent_assignment(message) + and index + 1 < len(exchange) + and _is_agent_response(exchange[index + 1]) + ): + units.append(exchange[index : index + 2]) + index += 2 + else: + units.append([message]) + index += 1 + + bounded_units: list[list[dict[str, str]]] = [] + for unit in units: + if _message_tokens(unit) <= max_tokens: + bounded_units.append(unit) + continue + for message in unit: + remaining = message["content"] + while remaining: + low, high = 0, len(remaining) + while low < high: + middle = (low + high + 1) // 2 + if _message_tokens([{**message, "content": remaining[:middle]}]) <= max_tokens: + low = middle + else: + high = middle - 1 + if low == 0: + raise ValueError("Extraction token budget cannot fit a message") + bounded_units.append([{**message, "content": remaining[:low]}]) + remaining = remaining[low:] + + batches: list[list[dict[str, str]]] = [] + batch: list[dict[str, str]] = [] + for unit in bounded_units: + candidate = [*batch, *unit] + if batch and _message_tokens(candidate) > max_tokens: + batches.append(batch) + batch = list(unit) + else: + batch = candidate + if batch: + batches.append(batch) + return batches + + +def _request_json( + url: str, key: str, payload: dict[str, Any], timeout: float +) -> tuple[dict[str, Any] | list[Any], int, int]: + raw = json.dumps(payload, ensure_ascii=False).encode() + request = urllib.request.Request( + url, + data=raw, + headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + response_raw = response.read() + parsed = json.loads(response_raw or b"{}") + return parsed, len(raw), len(response_raw) + + +def _request_json_with_network_retry( + url: str, key: str, payload: dict[str, Any], timeout: float +) -> tuple[dict[str, Any] | list[Any], int, int]: + """Retry one transient connection failure without retrying API responses.""" + try: + return _request_json(url, key, payload, timeout) + except urllib.error.HTTPError: + raise + except (urllib.error.URLError, TimeoutError, OSError): + time.sleep(0.25) + return _request_json(url, key, payload, timeout) + + +def _get_json( + url: str, key: str, timeout: float +) -> tuple[dict[str, Any] | list[Any], int]: + request = urllib.request.Request( + url, + headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + method="GET", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + response_raw = response.read() + return json.loads(response_raw or b"{}"), len(response_raw) + + +def _event_id(response: dict[str, Any] | list[Any]) -> str: + return str(response.get("event_id", "")) if isinstance(response, dict) else "" + + +def _stored_event_ids(value: Any) -> list[str]: + raw = str(value or "") + if not raw.startswith("["): + return [] + try: + parsed = json.loads(raw) + except json.JSONDecodeError: + return [] + return [str(item or "") for item in parsed] if isinstance(parsed, list) else [] + + +def _result_count(response: dict[str, Any] | list[Any]) -> int: + if isinstance(response, dict): + results = response.get("results") + return len(results) if isinstance(results, list) else 0 + return len(response) if isinstance(response, list) else 0 + + +def touch_handoff_heartbeat() -> None: + """Mark the worker's handoff file alive so recovery does not relaunch it.""" + path = os.environ.get("MEM0_CODE_HANDOFF_PATH", "") + if not path: + return + try: + os.utime(path) + except OSError: + pass + + +def _wait_for_event(api_url: str, key: str, event_id: str) -> tuple[str, int, int]: + """Wait for extraction to finish before a later task can search the store.""" + if not event_id: + return "MISSING", 0, 0 + wait_seconds = float(os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120")) + poll_seconds = max(float(os.environ.get("MEM0_CODE_EVENT_POLL_SECONDS", "1")), 0.1) + deadline = time.monotonic() + wait_seconds + response_chars = 0 + while time.monotonic() < deadline: + touch_handoff_heartbeat() + try: + response, size = _get_json( + f"{api_url}/v1/event/{event_id}/", + key, + min(10, poll_seconds + 5), + ) + except urllib.error.HTTPError as exc: + if exc.code not in {408, 429} and exc.code < 500: + raise + time.sleep(poll_seconds) + continue + except (urllib.error.URLError, TimeoutError, OSError): + # The extraction job is durable server-side. A transient polling + # failure must not discard a job that may still complete normally. + time.sleep(poll_seconds) + continue + response_chars += size + status = ( + str(response.get("status", "UNKNOWN")) + if isinstance(response, dict) + else "UNKNOWN" + ) + if status in {"SUCCEEDED", "FAILED"}: + return status, response_chars, _result_count(response) + time.sleep(poll_seconds) + return "TIMEOUT", response_chars, 0 + + +def _record_flush( + repo: RepoContext, + session_id: str, + reason: str, + status: str, + elapsed: float, + **extra: Any, +) -> None: + telemetry.record( + "flush", + repo=repo, + session_id=session_id, + reason=reason, + status=status, + success=status in {"semantic-succeeded", "nothing-to-flush"}, + duration_ms=round(elapsed, 2), + **extra, + ) + + +def flush_session( + store: EvidenceStore, hook_input: dict[str, Any], reason: str +) -> dict[str, Any]: + key = api_key() + if not key: + telemetry.record("flush", reason=reason, status="local-only", success=False) + return {"status": "local-only", "reason": "no-api-key"} + + session_id = _session_id(hook_input) + if session_id == "unknown-session": + telemetry.record("flush", reason=reason, status="no-session-id", success=False) + return {"status": "error", "reason": "no-session-id"} + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + prepared = store.prepare_flush(repo, session_id, reason) + if prepared is None: + return {"status": "nothing-to-flush"} + packet_id, events = prepared + existing_flush = store.flush_record(packet_id) or {} + + _, structured = build_episode( + repo, + session_id, + packet_id, + events, + canonical_task=bounded(hook_input.get("task", ""), 4000), + task_outcome=bounded(hook_input.get("task_outcome", ""), 2000), + ) + + metadata = {"source": _harness_source_tag} + if repo.branch and repo.branch not in {"detached", "unknown"}: + metadata["branch"] = repo.branch + if repo.head_sha: + metadata["git_sha"] = repo.head_sha + api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + add_url = f"{api_url}/v3/memories/add/" + + write_user = _scope_value(user_id()) + write_project = _scope_value(repo.project_id) + if not write_user or not _scope_value(repo.app_id) or not write_project: + telemetry.record("flush", reason=reason, status="unscoped", success=False) + return {"status": "error", "reason": "wildcard-scope"} + + body = { + "agent_id": write_project, + "user_id": write_user, + "app_id": repo.app_id, + "run_id": session_id, + "metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)}, + "agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS, + "custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS, + "custom_categories": CODING_MEMORY_CATEGORIES, + "infer": True, + } + + started = time.perf_counter() + try: + stored_events = _stored_event_ids(existing_flush.get("semantic_event_id")) + existing_event = ( + "" if stored_events else str(existing_flush.get("semantic_event_id") or "") + ) + if existing_event: + existing_status, existing_resp, existing_items = _wait_for_event( + api_url, key, existing_event + ) + if existing_status == "SUCCEEDED": + elapsed = (time.perf_counter() - started) * 1000 + store.update_flush( + packet_id, + status="semantic-succeeded", + semantic_event_id=existing_event, + error="", + ) + store.operation( + repo, + session_id, + "flush-retry", + elapsed, + True, + item_count=existing_items, + response_chars=existing_resp, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-succeeded", + elapsed, + memory_count=existing_items, + resumed=True, + ) + effective_reason = str( + (store.flush_record(packet_id) or {}).get("reason") or reason + ) + if ( + store.has_unflushed_events(repo.identity, session_id) + and not store.unflushed_starts_with_session_start( + repo.identity, session_id + ) + and ( + effective_reason != "periodic" + or store.checkpoint_due(repo.identity, session_id) + ) + ): + return flush_session(store, hook_input, effective_reason) + return { + "status": "semantic-succeeded", + "packet_id": packet_id, + "semantic_event_id": existing_event, + "semantic_status": existing_status, + "memory_count": existing_items, + "duration_ms": round(elapsed, 2), + "resumed": True, + } + if existing_status == "TIMEOUT": + elapsed = (time.perf_counter() - started) * 1000 + error = "semantic extraction event timed out" + store.update_flush(packet_id, status="semantic-timeout", error=error) + store.operation( + repo, + session_id, + "flush-retry", + elapsed, + False, + response_chars=existing_resp, + error=error, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-timeout", + elapsed, + resumed=True, + error_kind="timeout", + ) + return { + "status": "semantic-timeout", + "packet_id": packet_id, + "semantic_event_id": existing_event, + "duration_ms": round(elapsed, 2), + "resumed": True, + } + + message_batches = [ + batch + for batch in extraction_message_batches( + build_extraction_messages(structured) + ) + if batch + ] + batches = [(body, messages) for messages in message_batches] + if not batches: + store.update_flush(packet_id, status="semantic-succeeded", error="") + return {"status": "nothing-to-flush", "packet_id": packet_id} + operation_name = "flush-retry" if stored_events else "flush" + semantic_events = stored_events[: len(batches)] + semantic_events += [""] * (len(batches) - len(semantic_events)) + semantic_req = 0 + semantic_resp = 0 + for index, (body, messages) in enumerate(batches): + if semantic_events[index]: + continue + semantic_response, request_chars, response_chars = _request_json( + add_url, + key, + {**body, "messages": messages}, + 15, + ) + semantic_events[index] = _event_id(semantic_response) + semantic_req += request_chars + semantic_resp += response_chars + store.update_flush( + packet_id, + status="semantic-queued", + semantic_event_id=json.dumps(semantic_events), + ) + + semantic_event = semantic_events[-1] + semantic_status = "SUCCEEDED" + event_resp = 0 + semantic_items = 0 + failed_event = semantic_event + for index, queued_event in enumerate(semantic_events): + status, response_chars, item_count = _wait_for_event( + api_url, key, queued_event + ) + event_resp += response_chars + semantic_items += item_count + if status != "SUCCEEDED": + semantic_status = status + failed_event = queued_event + if status in {"FAILED", "MISSING"}: + semantic_events[index] = "" + store.update_flush( + packet_id, semantic_event_id=json.dumps(semantic_events) + ) + break + if semantic_status != "SUCCEEDED": + elapsed = (time.perf_counter() - started) * 1000 + error = f"semantic extraction event {semantic_status.lower()}" + store.update_flush( + packet_id, status=f"semantic-{semantic_status.lower()}", error=error + ) + store.operation( + repo, + session_id, + operation_name, + elapsed, + False, + item_count=semantic_items, + request_chars=semantic_req, + response_chars=semantic_resp + event_resp, + error=error, + ) + _record_flush( + repo, + session_id, + reason, + f"semantic-{semantic_status.lower()}", + elapsed, + memory_count=semantic_items, + batch_count=len(batches), + error_kind=telemetry.error_kind(error), + ) + return { + "status": f"semantic-{semantic_status.lower()}", + "packet_id": packet_id, + "semantic_event_id": failed_event, + "memory_count": semantic_items, + "duration_ms": round(elapsed, 2), + } + + elapsed = (time.perf_counter() - started) * 1000 + store.update_flush( + packet_id, + status="semantic-succeeded", + semantic_event_id=json.dumps(semantic_events), + error="", + ) + store.operation( + repo, + session_id, + operation_name, + elapsed, + True, + item_count=semantic_items, + request_chars=semantic_req, + response_chars=semantic_resp + event_resp, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-succeeded", + elapsed, + memory_count=semantic_items, + batch_count=len(batches), + request_chars=semantic_req, + ) + effective_reason = str( + (store.flush_record(packet_id) or {}).get("reason") or reason + ) + if ( + store.has_unflushed_events(repo.identity, session_id) + and not store.unflushed_starts_with_session_start( + repo.identity, session_id + ) + and ( + effective_reason != "periodic" + or store.checkpoint_due(repo.identity, session_id) + ) + ): + return flush_session(store, hook_input, effective_reason) + return { + "status": "semantic-succeeded", + "packet_id": packet_id, + "semantic_event_id": semantic_event, + "semantic_status": semantic_status, + "memory_count": semantic_items, + "duration_ms": round(elapsed, 2), + } + except Exception as exc: # hooks must fail open + elapsed = (time.perf_counter() - started) * 1000 + error = bounded(str(exc), 1000) + store.update_flush(packet_id, status="error", error=error) + store.operation(repo, session_id, "flush", elapsed, False, error=error) + _record_flush( + repo, + session_id, + reason, + "error", + elapsed, + error_kind=telemetry.error_kind(exc), + ) + return {"status": "error", "packet_id": packet_id, "error": error} + + +def checkpoint_session( + store: EvidenceStore, hook_input: dict[str, Any], reason: str +) -> dict[str, Any]: + """Run remote extraction at a durable boundary.""" + return flush_session(store, hook_input, reason) + + + +def search_memories( + store: EvidenceStore | None, + repo: RepoContext, + session_id: str | None, + query: str, + *, + top_k: int | None = None, + category: str | None = None, + scope: str | None = None, + run_id: str | None = None, + operation: str = "search", + timeout: float = 5, +) -> MemorySearchResult: + key = api_key() + if not key or not query.strip(): + return MemorySearchResult(False, 0, 0, []) + search_once = os.environ.get( + "MEM0_CODE_SEARCH_ONCE_PER_SESSION", "false" + ).lower() in { + "1", + "true", + "yes", + "on", + } + track_session = store is not None and bool(session_id) + if ( + search_once + and track_session + and store.has_operation(repo.identity, session_id, "search") + ): + return MemorySearchResult(False, 0, 0, []) + + result_limit = min( + max( + top_k + if top_k is not None + else _int_option("top_k", "MEM0_CODE_TOP_K", 3), + 1, + ), + 20, + ) + if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES: + raise ValueError(f"Unknown memory category: {category}") + user, project = _scope_value(user_id()), _scope_value(repo.project_id) + if not user or not project or not _scope_value(repo.app_id): + return MemorySearchResult(False, 0, 0, []) + filters = _search_filters(user, repo, resolve_search_scope(scope)) + if category: + filters = {"AND": [filters, {"categories": {"contains": category}}]} + if run_id: + filters = {"AND": [filters, {"run_id": run_id}]} + payload = { + "query": query, + "app_id": repo.app_id, + "filters": filters, + "top_k": result_limit, + "rerank": False, + "latest_only": True, + } + url = ( + os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + + "/v3/memories/search/" + ) + started = time.perf_counter() + try: + response, request_chars, response_chars = _request_json_with_network_retry( + url, key, payload, timeout + ) + memories = ( + response if isinstance(response, list) else response.get("results", []) + ) + memories = [ + memory + for memory in memories + if isinstance(memory, dict) + and (memory.get("metadata") or {}).get("record_kind") != "task_episode" + ][:result_limit] + if track_session: + returned_memories = store.unseen(session_id, repo.identity, memories) + store.mark_injected(session_id, repo.identity, returned_memories) + already_shown_count = len(memories) - len(returned_memories) + else: + returned_memories = memories + already_shown_count = 0 + elapsed = (time.perf_counter() - started) * 1000 + if track_session: + store.operation( + repo, + session_id, + operation, + elapsed, + True, + item_count=len(returned_memories), + request_chars=request_chars, + response_chars=response_chars, + ) + telemetry.record( + "search", + repo=repo, + session_id=session_id, + trigger=operation, + success=True, + duration_ms=round(elapsed, 2), + matched_count=len(memories), + returned_count=len(returned_memories), + already_shown_count=already_shown_count, + top_k=result_limit, + has_category=bool(category), + ) + return MemorySearchResult( + succeeded=True, + matched_count=len(memories), + already_shown_count=already_shown_count, + memories=returned_memories, + ) + except Exception as exc: + elapsed = (time.perf_counter() - started) * 1000 + if track_session: + store.operation(repo, session_id, operation, elapsed, False, error=str(exc)) + telemetry.record( + "search", + repo=repo, + session_id=session_id, + trigger=operation, + success=False, + duration_ms=round(elapsed, 2), + top_k=result_limit, + has_category=bool(category), + error_kind=telemetry.error_kind(exc), + ) + return MemorySearchResult(False, 0, 0, []) + + +def format_context( + memories: list[dict[str, Any]], + heading: str = "Relevant repository memories:", +) -> str: + if not memories: + return "" + limit = min( + max( + _int_option( + "max_context_chars", + "MEM0_CODE_MAX_CONTEXT_CHARS", + DEFAULT_MAX_CONTEXT_CHARS, + ), + 1000, + ), + 10000, + ) + lines = [heading] if heading else [] + for memory in memories: + text = re.sub( + r"\s+", + " ", + redact(memory.get("memory") or memory.get("text") or ""), + ) + text = text.strip() + if not text: + continue + branch = str((memory.get("metadata") or {}).get("branch") or "").strip() + branch_label = ( + f" [learnt on branch {branch}]" + if branch.casefold() not in {"", "main", "master", "unknown", "detached"} + else "" + ) + number = len(lines) if heading else len(lines) + 1 + entry = f"{number}. {text}{branch_label}" + candidate = "\n".join([*lines, entry]) + if len(candidate) <= limit: + lines.append(entry) + continue + if not lines or (heading and len(lines) == 1): + prefix = f"{number}. " + suffix = f"…{branch_label}" + available = ( + limit + - len("\n".join(lines)) + - (1 if lines else 0) + - len(prefix) + - len(suffix) + ) + if available > 0: + lines.append(prefix + text[:available].rstrip() + suffix) + break + minimum_lines = 2 if heading else 1 + return "\n".join(lines) if len(lines) >= minimum_lines else "" + + +def format_search_result(result: MemorySearchResult) -> str: + """Return only the text the coding agent needs from an explicit memory search.""" + if not result.succeeded: + return "Memory search failed." + if result.memories: + rendered = format_context(result.memories, heading="") + if rendered: + return rendered + return "No matching memories found." + + +def combine_context(*contexts: str) -> str: + """Combine memory sources under one hard budget without repeated lines.""" + seen: set[str] = set() + lines: list[str] = [] + for context in contexts: + for line in str(context or "").splitlines(): + normalized = re.sub(r"\s+", " ", line).strip().casefold() + if not normalized or normalized in seen: + continue + seen.add(normalized) + lines.append(line.rstrip()) + limit = min( + max( + _int_option( + "max_context_chars", + "MEM0_CODE_MAX_CONTEXT_CHARS", + DEFAULT_MAX_CONTEXT_CHARS, + ), + 1000, + ), + 10000, + ) + return bounded("\n".join(lines), limit) if lines else "" + + +def _scoped_memory_ids( + api_url: str, key: str, user: str, repo: RepoContext, include_project: bool +) -> list[str]: + """List this user's memory ids for this repository, plus the shared project memory when asked.""" + ids: list[str] = [] + seen: set[str] = set() + prefix = repo.app_id + _collect_memory_ids( + api_url, key, {"user_id": user}, ids, seen, + app_id_prefix=prefix, + ) + if include_project: + for project_id in _shared_project_ids(repo): + _collect_memory_ids( + api_url, key, {"agent_id": project_id}, ids, seen, + app_id_prefix=prefix, + ) + return ids + + +def _collect_memory_ids( + api_url: str, + key: str, + filters: dict[str, Any], + ids: list[str], + seen: set[str], + *, + app_id_prefix: str = "", +) -> None: + """Page through one list filter; the list endpoint returns nothing for an OR whose user branch has no memories.""" + payload = {"filters": filters} + for page in range(1, FORGET_MAX_PAGES + 1): + parsed, _, _ = _request_json( + f"{api_url}/v2/memories/?page={page}&page_size={FORGET_PAGE_SIZE}", + key, + payload, + 15, + ) + items = parsed.get("results") if isinstance(parsed, dict) else parsed + if not isinstance(items, list) or not items: + break + for item in items: + if not isinstance(item, dict): + continue + memory_id = str(item.get("id", "")) + if not memory_id or memory_id in seen: + continue + if app_id_prefix: + item_app_id = str(item.get("app_id") or "") + if item_app_id != app_id_prefix and not item_app_id.startswith(app_id_prefix + "/"): + continue + seen.add(memory_id) + ids.append(memory_id) + if len(items) < FORGET_PAGE_SIZE: + break + + +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"}, + method="DELETE", + ) + try: + with urllib.request.urlopen(request, timeout=15): + return True + except Exception: + return False + + +def forget_remote_repo( + repo: RepoContext, *, include_project_memory: bool = False +) -> dict[str, Any]: + """Delete this user's memories for this repository; project memory is shared, so only on request.""" + key = api_key() + if not key: + telemetry.record("forget", repo=repo, success=False, error_kind="no-api-key") + return {"status": "error", "error": "Mem0 API key is not configured"} + user = _scope_value(user_id()) + if not user or not _scope_value(repo.app_id) or not _scope_value(repo.project_id): + telemetry.record("forget", repo=repo, success=False, error_kind="unscoped") + return { + "status": "error", + "error": "Refusing to forget: the user or repository scope is a wildcard", + } + api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + try: + memory_ids = _scoped_memory_ids(api_url, key, user, repo, include_project_memory) + except Exception as exc: + telemetry.record( + "forget", repo=repo, success=False, error_kind=telemetry.error_kind(exc) + ) + return {"status": "error", "error": bounded(str(exc), 1000)} + deleted = sum(_delete_memory(api_url, key, memory_id) for memory_id in memory_ids) + failed = len(memory_ids) - deleted + telemetry.record("forget", repo=repo, success=not failed, item_count=deleted) + if failed: + return { + "status": "partial", + "deleted": deleted, + "failed": failed, + "error": f"{failed} of {len(memory_ids)} memories could not be deleted", + } + return {"status": "deleted", "deleted": deleted} + + +def _doctor_mem0_authentication(repo: RepoContext) -> dict[str, Any]: + """Verify the configured key with one read-only, repository-scoped search.""" + key = api_key() + if not key: + return {"ok": False, "detail": "API key missing"} + payload = { + "query": "Mem0 authentication check", + "filters": { + "AND": [ + {"user_id": user_id()}, + {"app_id": repo.app_id}, + ] + }, + "top_k": 1, + "threshold": 1.0, + "rerank": False, + } + url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + started = time.perf_counter() + try: + _request_json(f"{url}/v3/memories/search/", key, payload, 5) + except Exception as exc: + return {"ok": False, "detail": bounded(str(exc), 300)} + elapsed = (time.perf_counter() - started) * 1000 + return {"ok": True, "detail": f"connected ({elapsed:.0f} ms)"} + + +def _doctor_user_id() -> dict[str, Any]: + """Flag a configured user ID the plugin refuses, since the silent fallback surprises people.""" + configured = _plugin_option("user_id", "MEM0_CODE_USER_ID") or os.environ.get( + "MEM0_USER_ID", "" + ) + if configured and not _scope_value(configured): + return { + "ok": False, + "detail": f"configured user_id {configured!r} is a wildcard; using {user_id()!r}", + } + return {"ok": True, "detail": user_id()} + + +def doctor(cwd: str | None = None) -> dict[str, Any]: + repo = resolve_repo(cwd) + directory = data_dir() + directory.mkdir(parents=True, exist_ok=True) + checks: dict[str, dict[str, Any]] = { + "python": { + "ok": tuple(sys.version_info[:2]) >= (3, 10), + "detail": f"{sys.version_info.major}.{sys.version_info.minor}", + }, + "data_directory": { + "ok": os.access(directory, os.W_OK), + "detail": str(directory), + }, + "mem0_api_key": { + "ok": bool(api_key()), + "detail": "configured" if api_key() else "missing", + }, + "repository": { + "ok": bool(repo.identity), + "detail": repo.identity, + }, + "user_id": _doctor_user_id(), + "mem0_authentication": _doctor_mem0_authentication(repo), + } + return { + "ok": all(bool(value["ok"]) for value in checks.values()), + "plugin_version": PLUGIN_VERSION, + "repo_id": repo.identity, + "app_id": repo.app_id, + "user_id": user_id(), + "checks": checks, + } diff --git a/integrations/agent-plugin-core/python/telemetry.py b/integrations/agent-plugin-core/python/telemetry.py new file mode 100644 index 000000000..249595475 --- /dev/null +++ b/integrations/agent-plugin-core/python/telemetry.py @@ -0,0 +1,397 @@ +#!/usr/bin/env python3 +"""Anonymous usage telemetry for Mem0 agent plugins. + +Hooks run on a 3-6 second budget and fire on every tool call, so recording never +touches the network: `record` appends one JSON line to a local spool and returns. +A detached `python3 telemetry.py` drains the spool in one batched PostHog request, +started once per session and again from the flush worker that is already detached. + +Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false. + +Never sends prompts, memory text, queries, file paths, repository names, or API +keys: only event names, durations, counts, coarse outcomes, and salted hashes. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import platform +import subprocess +import sys +import time +import urllib.error +import urllib.request +import uuid +from pathlib import Path +from typing import Any + +import memory_core + +_harness: str = "generic" +_source_tag: str = "MEM0_PLUGIN" +_PRIVATE_KEYS = { + "apikey", + "authorization", + "password", + "query", + "secret", + "prompt", + "token", + "text", + "memory", + "message", + "error", + "path", + "cwd", + "userid", + "agentid", + "runid", + "repoid", + "repositoryid", + "projectid", + "appid", + "filters", +} + + +def init(harness: str = "generic", source_tag: str = "") -> None: + global _harness, _source_tag + _harness = harness + _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN" + +POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" +POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/" +POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/" +EVENT_PREFIX = "code" +SPOOL_LIMIT_BYTES = 256 * 1024 +BATCH_SIZE = 100 +SEND_TIMEOUT = 5 +CLAIM_STALE_SECONDS = 120 +CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60 + + +def is_enabled() -> bool: + """Whether telemetry is switched on for this process.""" + return os.environ.get("MEM0_TELEMETRY", "true").strip().lower() not in { + "false", + "0", + "no", + "off", + } + + +def _digest(value: str, length: int = 16) -> str: + return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length] + + +def _safe_value(value: Any) -> Any: + if isinstance(value, str): + return memory_core.redact(value) + if isinstance(value, dict): + return { + key: _safe_value(item) + for key, item in value.items() + if "".join(character for character in str(key).lower() if character.isalnum()) + not in _PRIVATE_KEYS + } + if isinstance(value, (list, tuple)): + return [_safe_value(item) for item in value] + if value is None or isinstance(value, (bool, int, float)): + return value + return memory_core.redact(value) + + +def _spool_path() -> Path: + return memory_core.data_dir() / "telemetry.jsonl" + + +def _identity_path() -> Path: + return memory_core.data_dir() / "telemetry-identity.json" + + +def _read_identity() -> dict[str, str]: + try: + value = json.loads(_identity_path().read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {} + return value if isinstance(value, dict) else {} + + +def _write_identity(identity: dict[str, str]) -> None: + path = _identity_path() + temporary = path.with_suffix(f".{os.getpid()}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + temporary.write_text(json.dumps(identity), encoding="utf-8") + temporary.replace(path) + except OSError: + try: + temporary.unlink() + except OSError: + pass + + +def anonymous_id(identity: dict[str, str] | None = None) -> str: + """Per-machine anonymous identifier, created and persisted on first use.""" + identity = _read_identity() if identity is None else identity + existing = identity.get("anonymous_id") + if existing: + return existing + created = f"code-anon-{uuid.uuid4().hex}" + identity["anonymous_id"] = created + _write_identity(identity) + return created + + +def is_first_run() -> bool: + """Whether this machine has never recorded a plugin event before.""" + return not _identity_path().exists() + + +def record( + event: str, + *, + repo: Any = None, + session_id: str | None = None, + **properties: Any, +) -> None: + """Append one event to the local spool. Never blocks and never raises.""" + if not is_enabled(): + return + try: + spool = _spool_path() + try: + if spool.stat().st_size > SPOOL_LIMIT_BYTES: + return + except OSError: + pass + properties = _safe_value(properties) + properties.update( + harness=_harness, + plugin_version=memory_core.PLUGIN_VERSION, + os=sys.platform, + python_version=platform.python_version(), + ) + if repo is not None: + properties["repo_hash"] = _digest(getattr(repo, "identity", "")) + if session_id: + properties["session_hash"] = _digest(session_id) + line = json.dumps( + { + "event": f"{EVENT_PREFIX}.{event}", + "timestamp": memory_core.utc_now(), + "properties": { + key: value for key, value in properties.items() if value is not None + }, + }, + separators=(",", ":"), + default=str, + ) + spool.parent.mkdir(parents=True, exist_ok=True) + with spool.open("a", encoding="utf-8") as handle: + handle.write(line + "\n") + except Exception: + pass + + +def error_kind(exc: BaseException | str) -> str: + """Coarse, content-free label for a failure, safe to send.""" + text = exc if isinstance(exc, str) else f"{type(exc).__name__}: {exc}" + lowered = text.lower() + if "timed out" in lowered or "timeout" in lowered: + return "timeout" + if "401" in lowered or "403" in lowered or "unauthor" in lowered or "forbidden" in lowered: + return "auth" + if "429" in lowered or "rate limit" in lowered: + return "rate-limited" + if any(code in lowered for code in ("500", "502", "503", "504")): + return "server-error" + if "400" in lowered or "422" in lowered: + return "bad-request" + if isinstance(exc, str): + return "other" + if isinstance(exc, urllib.error.URLError): + return "network" + return type(exc).__name__ + + +def spawn_flush() -> bool: + """Start the detached sender that drains the spool.""" + if not is_enabled(): + return False + try: + if not _spool_path().exists() and not any( + memory_core.data_dir().glob("telemetry-*.sending") + ): + return False + subprocess.Popen( + [sys.executable, str(Path(__file__).resolve())], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + close_fds=True, + **memory_core.detached_process_kwargs(), + ) + return True + except Exception: + return False + + +def _claim_spool() -> Path | None: + """Rename the spool aside so exactly one sender owns each batch.""" + directory = memory_core.data_dir() + claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending" + spool = _spool_path() + try: + spool.replace(claim) + return claim + except OSError: + pass + now = time.time() + for orphan in sorted(directory.glob("telemetry-*.sending")): + try: + age = now - orphan.stat().st_mtime + except OSError: + continue + if age > CLAIM_EXPIRY_SECONDS: + try: + orphan.unlink() + except OSError: + pass + continue + if age < CLAIM_STALE_SECONDS: + continue + try: + orphan.replace(claim) + return claim + except OSError: + continue + return None + + +def _resolve_email(key: str) -> str: + """Trade the API key for the account email so events join other Mem0 surfaces.""" + url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/" + request = urllib.request.Request( + url, headers={"Authorization": f"Token {key}", "Content-Type": "application/json"} + ) + try: + with urllib.request.urlopen(request, timeout=SEND_TIMEOUT) as response: + payload = json.loads(response.read().decode("utf-8")) + except Exception: + return "" + email = payload.get("user_email") if isinstance(payload, dict) else "" + return email if isinstance(email, str) else "" + + +def _post(payload: dict[str, Any], url: str) -> bool: + request = urllib.request.Request( + url, + data=json.dumps(payload, default=str).encode("utf-8"), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=SEND_TIMEOUT): + return True + except Exception: + return False + + +def resolve_distinct_id() -> tuple[str, str]: + """Return the PostHog distinct id and the anonymous id it replaced, if any.""" + identity = _read_identity() + email = identity.get("email", "") + if email: + return email, "" + key = memory_core.api_key() + if not key: + return anonymous_id(identity), "" + email = _resolve_email(key) + if not email: + return anonymous_id(identity), "" + previous = identity.get("anonymous_id", "") + identity["email"] = email + _write_identity(identity) + return email, previous + + +def flush() -> int: + """Drain claimed spools to PostHog and return the number of events sent.""" + if not is_enabled(): + return 0 + claim = _claim_spool() + if claim is None: + return 0 + try: + lines = claim.read_text(encoding="utf-8").splitlines() + except OSError: + return 0 + events = [] + for line in lines: + try: + value = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(value, dict) and value.get("event"): + events.append(value) + if not events: + try: + claim.unlink() + except OSError: + pass + return 0 + + distinct_id, aliased_anonymous_id = resolve_distinct_id() + if aliased_anonymous_id: + _post( + { + "api_key": POSTHOG_API_KEY, + "event": "$identify", + "distinct_id": distinct_id, + "properties": { + "$anon_distinct_id": aliased_anonymous_id, + "$lib": "posthog-python", + }, + }, + POSTHOG_CAPTURE_URL, + ) + + sent = 0 + for start in range(0, len(events), BATCH_SIZE): + batch = [ + { + "event": event["event"], + "distinct_id": distinct_id, + "timestamp": event.get("timestamp"), + "properties": { + "source": _source_tag, + "language": "python", + "$process_person_profile": False, + "$lib": "posthog-python", + **(event.get("properties") or {}), + }, + } + for event in events[start : start + BATCH_SIZE] + ] + if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL): + return sent + sent += len(batch) + try: + claim.unlink() + except OSError: + pass + return sent + + +def main() -> int: + flush() + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except Exception: + raise SystemExit(0) diff --git a/integrations/agent-plugin-core/requirements-dev.txt b/integrations/agent-plugin-core/requirements-dev.txt new file mode 100644 index 000000000..1fbe37b8d --- /dev/null +++ b/integrations/agent-plugin-core/requirements-dev.txt @@ -0,0 +1,3 @@ +jsonschema>=4.23,<5 +pytest>=8,<10 +skills-ref==0.1.1 diff --git a/integrations/agent-plugin-core/skills/forget/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/forget/SKILL.md.tmpl new file mode 100644 index 000000000..1b16a6c79 --- /dev/null +++ b/integrations/agent-plugin-core/skills/forget/SKILL.md.tmpl @@ -0,0 +1,26 @@ +--- +name: forget +description: Delete the Mem0 memories stored for this repository and this user. Use when the user asks to forget, clear, wipe, or delete memories. +disable-model-invocation: true +--- + +# Forget this repository's memories + +This permanently deletes remote memories. Before running anything, tell the +user exactly what will be deleted: their own memories for this repository +only. The repository's project memory is shared by everyone who works in it, +so it stays unless the user explicitly asks to delete that too. + +After the user confirms, run: + +```bash +python3 "{{PLUGIN_ROOT}}/core/memory_cli.py" --harness "{{HARNESS_ID}}" {{PLUGIN_DATA_ARG}} forget --remote --yes +``` + +If the user also asked to delete the repository's shared project memory, add +`--include-project-memory` and say that this removes it for every teammate. + +Report what the command output says was deleted. If the user only wants local +data cleared (evidence log, pending queue), run the same command without +`--remote`. Never pass `--yes` before the user has confirmed in this +conversation. diff --git a/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl new file mode 100644 index 000000000..9cc720c7a --- /dev/null +++ b/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl @@ -0,0 +1,20 @@ +--- +name: pause +description: Pause Mem0 memory capture on this machine. Use when the user wants to stop memories being recorded, for example for private work or experiments. +disable-model-invocation: true +--- + +# Pause memory capture + +To pause (hooks stop capturing and sending session content; a minimal +anonymous telemetry ping still fires at session start unless +`MEM0_TELEMETRY=false`): + +```bash +python3 "{{PLUGIN_ROOT}}/core/memory_cli.py" --harness "{{HARNESS_ID}}" {{PLUGIN_DATA_ARG}} pause +``` + +Confirm the new state back to the user, and remind them that already-created +memories still exist and remain searchable. Pending unsent packets are held +while paused, not expired, and are delivered after resuming. To turn capture +back on, use `/mem0:resume`. diff --git a/integrations/agent-plugin-core/skills/remember/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/remember/SKILL.md.tmpl new file mode 100644 index 000000000..7be5fc9be --- /dev/null +++ b/integrations/agent-plugin-core/skills/remember/SKILL.md.tmpl @@ -0,0 +1,21 @@ +--- +name: remember +description: Acknowledge a "remember this" request and make sure it is captured well. Use when the user explicitly asks to remember, note, or save something for future sessions. +disable-model-invocation: true +--- + +# Remember something for future sessions + +Mem0 creates memories from the session automatically — there is no separate +write command. When the user asks to remember something: + +1. Restate the fact clearly and completely in your reply, in one or two + sentences, including any names, values, or paths it depends on. Your visible + reply is what memory extraction reads, so a precise restatement is what gets + remembered. +2. Tell the user it will be saved with this session's memories when the session + ends or compacts, and that it will surface in future sessions in this + repository (they can check later with /mem0:search). + +Do not invent a storage confirmation or a memory ID — creation happens in the +background after the session. diff --git a/integrations/agent-plugin-core/skills/resume/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/resume/SKILL.md.tmpl new file mode 100644 index 000000000..b8a4d5f01 --- /dev/null +++ b/integrations/agent-plugin-core/skills/resume/SKILL.md.tmpl @@ -0,0 +1,19 @@ +--- +name: resume +description: Resume Mem0 memory capture after it was paused with /mem0:pause. +disable-model-invocation: true +--- + +# Resume memory capture + +Resume memory capture for this machine. + +Run: + +```bash +python3 "{{PLUGIN_ROOT}}/core/memory_cli.py" --harness "{{HARNESS_ID}}" {{PLUGIN_DATA_ARG}} resume +``` + +Confirm to the user that capture is active again. New sessions record evidence and +create memories as normal; nothing that happened while paused is retroactively +captured. diff --git a/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl new file mode 100644 index 000000000..3a255b1ad --- /dev/null +++ b/integrations/agent-plugin-core/skills/search/SKILL.md.tmpl @@ -0,0 +1,28 @@ +--- +name: search +description: Search memories from earlier {{HARNESS_NAME}} 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. +argument-hint: "[question] [--top-k number] [--category category-name] [--scope repo|dir|mine] [--run-id session-id]" +disable-model-invocation: true +--- + +# Search memories + +Call `search_memories` with the user's question. Treat `--top-k`, `--category`, +`--scope`, and `--run-id` as tool arguments instead of including them in the +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. + +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 +monorepo), `mine` for your own preferences alone. + +Pass `run_id` with any scope to retrieve memories saved in a specific coding-agent +session. Omit `run_id` to search across sessions. It filters the memories returned; +it does not identify the session making the search request. Use a known session ID, +never invent one. Return the tool's result directly. diff --git a/integrations/agent-plugin-core/skills/status/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/status/SKILL.md.tmpl new file mode 100644 index 000000000..c1ac9e8f9 --- /dev/null +++ b/integrations/agent-plugin-core/skills/status/SKILL.md.tmpl @@ -0,0 +1,23 @@ +--- +name: status +description: Show whether Mem0 memory is working in this repository, covering configuration, capture state, pending flushes, and whether the Mem0 API key is valid. Use when the user asks whether memory is on, why a memory is missing, or anything looks broken. +disable-model-invocation: false +--- + +# Memory status + +Run both commands and report the combined result in plain language: + +```bash +python3 "{{PLUGIN_ROOT}}/core/memory_cli.py" --harness "{{HARNESS_ID}}" {{PLUGIN_DATA_ARG}} status --json +python3 "{{PLUGIN_ROOT}}/core/memory_cli.py" --harness "{{HARNESS_ID}}" {{PLUGIN_DATA_ARG}} doctor +``` + +Summarize, using only fields the JSON actually reports: whether capture is +active or paused, the user ID and repository scope (`repo_id`), whether an +API key is configured, the event/flush/retrieval counts (`flushes` is the +number of completed flushes, not a pending count), and the doctor check +results. If doctor reports an authentication failure (401 / invalid key), say +clearly that the Mem0 API key is invalid or expired and that memories are NOT +being created. Never report an auth failure as "no memories found". Suggest +reinstalling with `--config api_key=...` in that case. diff --git a/integrations/agent-plugin-core/tests/test_build.py b/integrations/agent-plugin-core/tests/test_build.py new file mode 100644 index 000000000..dfa154f3d --- /dev/null +++ b/integrations/agent-plugin-core/tests/test_build.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +import sys +import json +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +REPOSITORY_ROOT = ROOT.parents[1] +sys.path.insert(0, str(ROOT)) + +from build.build import build, bundle_drift, render_template, replace_output # noqa: E402 +from build.validate import validate_bundle # noqa: E402 + + +def test_render_rejects_unknown_or_unresolved_tokens() -> None: + with pytest.raises(ValueError, match="UNKNOWN"): + render_template("run {{UNKNOWN}}", {}) + + +def test_build_replaces_only_the_requested_output(tmp_path: Path) -> None: + staged = tmp_path / "staged" + staged.mkdir() + (staged / "plugin.json").write_text("{}", encoding="utf-8") + output = tmp_path / "output" + output.mkdir() + (output / "stale.py").write_text("stale", encoding="utf-8") + sibling = tmp_path / "keep.txt" + sibling.write_text("keep", encoding="utf-8") + + replace_output(staged, output) + + assert not (output / "stale.py").exists() + assert (output / "plugin.json").exists() + assert sibling.read_text(encoding="utf-8") == "keep" + + +def test_build_cannot_replace_an_installable_source_directory(tmp_path: Path) -> None: + staged = tmp_path / "staged" + staged.mkdir() + + with pytest.raises(ValueError, match="protected output path"): + replace_output(staged, REPOSITORY_ROOT / "integrations" / "claude-code-plugin") + + +def test_portable_bundle_is_conformant_and_self_contained(tmp_path: Path) -> None: + root = build("mem0-agent-plugin", "portable", tmp_path / "mem0-agent-plugin") + + assert validate_bundle(root, "portable") == [] + assert json.loads((root / "plugin.json").read_text(encoding="utf-8"))["$schema"] == ( + "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json" + ) + server = json.loads((root / "mcp.json").read_text(encoding="utf-8"))["mcpServers"]["mem0"] + assert server["type"] == "stdio" + assert server["args"] == ["${PLUGIN_ROOT}/core/mcp_server.py"] + assert "env" not in server + assert not (root / "core" / "hook_runner.py").exists() + assert not (root / "core" / "flush_worker.py").exists() + for skill in (root / "skills").glob("*/SKILL.md"): + frontmatter = skill.read_text(encoding="utf-8").split("---", 2)[1] + keys = {line.split(":", 1)[0] for line in frontmatter.splitlines() if ":" in line} + assert keys <= {"name", "description", "license", "compatibility", "metadata", "allowed-tools"} + assert not any(path.is_symlink() for path in root.rglob("*")) + + +@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) + + assert (root / "core" / "memory_core.py").is_file() + assert (root / "skills" / "remember" / "SKILL.md").is_file() + assert not any(path.is_symlink() for path in root.rglob("*")) + + +@pytest.mark.parametrize("host", ["claude-code", "cursor", "codex", "kimi", "antigravity"]) +def test_native_control_skills_select_the_host_store(host: str, tmp_path: Path) -> None: + root = build(host, "native", tmp_path / host) + status = (root / "skills" / "status" / "SKILL.md").read_text(encoding="utf-8") + + assert f'--harness "{host}"' in status + if host == "claude-code": + assert '--plugin-data-dir "${CLAUDE_PLUGIN_DATA}"' in status + elif host == "codex": + assert '--plugin-data-dir "${PLUGIN_DATA}"' in status + + +@pytest.mark.parametrize( + ("host", "kind"), + [ + ("mem0-agent-plugin", "portable"), + ("claude-code", "native"), + ("cursor", "native"), + ("codex", "native"), + ("kimi", "native"), + ("antigravity", "native"), + ], +) +def test_installable_plugin_directories_are_current(host: str, kind: str) -> None: + assert bundle_drift(host, kind) == [] + + +def test_marketplaces_keep_public_names_and_reference_real_plugins() -> None: + marketplace = json.loads((REPOSITORY_ROOT / "marketplace.json").read_text(encoding="utf-8")) + sources = {plugin["name"]: plugin["source"] for plugin in marketplace["plugins"]} + + assert sources == {"mem0": "./integrations/claude-code-plugin"} + for source in sources.values(): + assert (REPOSITORY_ROOT / source).exists() + + codex_marketplace = json.loads( + (REPOSITORY_ROOT / ".agents" / "plugins" / "marketplace.json").read_text(encoding="utf-8") + ) + assert [plugin["name"] for plugin in codex_marketplace["plugins"]] == ["mem0"] + codex = codex_marketplace["plugins"][0] + assert codex["source"]["path"] == "./integrations/codex-plugin" diff --git a/integrations/agent-plugin-core/tests/test_conformance.py b/integrations/agent-plugin-core/tests/test_conformance.py new file mode 100644 index 000000000..53c7fb826 --- /dev/null +++ b/integrations/agent-plugin-core/tests/test_conformance.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import json +import os +import subprocess +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) +from conformance import run as conformance_run # noqa: E402 +from conformance.run import _command_check # noqa: E402 + + +PLUGIN_ROOT = Path(__file__).resolve().parents[1] +RUNNER = PLUGIN_ROOT / "conformance" / "run.py" +PYTHON_HOSTS = {"claude-code", "cursor", "codex", "kimi", "antigravity"} + + +def test_python_bundle_conformance_builds_every_host(tmp_path: Path) -> None: + report = tmp_path / "report.json" + artifacts = tmp_path / "artifacts" + + result = subprocess.run( + [ + sys.executable, + str(RUNNER), + "--group", + "python-bundles", + "--artifacts-dir", + str(artifacts), + "--report", + str(report), + ], + cwd=PLUGIN_ROOT.parents[1], + text=True, + capture_output=True, + check=False, + ) + + assert result.returncode == 0, result.stdout + result.stderr + payload = json.loads(report.read_text(encoding="utf-8")) + assert payload["status"] == "passed" + assert { + entry["host"] + for entry in payload["checks"] + if entry["kind"] == "native" + } == PYTHON_HOSTS + assert { + entry["host"] + for entry in payload["checks"] + if entry["kind"] == "portable" + } == {"mem0-agent-plugin"} + for host in PYTHON_HOSTS: + assert (artifacts / host).is_dir() + assert (artifacts / "mem0-agent-plugin").is_dir() + + +def test_conformance_plan_covers_every_runtime(tmp_path: Path) -> None: + report = tmp_path / "plan.json" + + result = subprocess.run( + [sys.executable, str(RUNNER), "--list", "--report", str(report)], + cwd=PLUGIN_ROOT.parents[1], + text=True, + capture_output=True, + check=False, + ) + + assert result.returncode == 0, result.stdout + result.stderr + payload = json.loads(report.read_text(encoding="utf-8")) + assert {entry["group"] for entry in payload["checks"]} == { + "python-bundles", + "python-tests", + "typescript-core", + "openclaw", + "opencode", + "pi-agent", + "deepseek", + } + assert all(entry["status"] == "planned" for entry in payload["checks"]) + assert { + entry["group"] + for entry in payload["checks"] + if entry["name"].endswith("-artifact") + } == {"openclaw", "opencode", "pi-agent", "deepseek"} + + +def test_typescript_artifact_check_rejects_monorepo_imports(tmp_path: Path) -> None: + dist = tmp_path / "dist" + dist.mkdir() + (dist / "index.js").write_text( + 'import { createMemoryLifecycle } from "../../agent-plugin-core/typescript/src/lifecycle.ts";\n', + encoding="utf-8", + ) + + artifact_check = getattr(conformance_run, "_typescript_artifact_check", None) + assert artifact_check is not None, "TypeScript package artifacts are not checked" + result = artifact_check("example", tmp_path, ("dist/index.js",)) + + assert result["status"] == "failed" + assert "monorepo source import" in result["output"] + + +def test_live_conformance_requires_an_explicit_mem0_key(tmp_path: Path) -> None: + environment = dict(os.environ) + environment.pop("MEM0_API_KEY", None) + + result = subprocess.run( + [sys.executable, str(RUNNER), "--live", "--report", str(tmp_path / "report.json")], + cwd=PLUGIN_ROOT.parents[1], + env=environment, + text=True, + capture_output=True, + check=False, + ) + + assert result.returncode == 2 + assert "MEM0_API_KEY is required for --live" in result.stderr + + +def test_live_conformance_reports_platform_failure_without_crashing(tmp_path: Path) -> None: + report = tmp_path / "report.json" + environment = { + **os.environ, + "MEM0_API_KEY": "m0-intentionally-invalid", + "MEM0_API_URL": "http://127.0.0.1:1", + } + + result = subprocess.run( + [ + sys.executable, + str(RUNNER), + "--group", + "live-platform", + "--live", + "--report", + str(report), + ], + cwd=PLUGIN_ROOT.parents[1], + env=environment, + text=True, + capture_output=True, + check=False, + ) + + assert result.returncode == 1 + payload = json.loads(report.read_text(encoding="utf-8")) + assert payload["status"] == "failed" + assert payload["checks"][0]["group"] == "live-platform" + + +def test_runtime_checks_preserve_the_callers_telemetry_setting(tmp_path: Path, monkeypatch) -> None: + monkeypatch.delenv("MEM0_TELEMETRY", raising=False) + + result = _command_check( + "environment", + "test", + [sys.executable, "-c", "import os; print(os.environ.get('MEM0_TELEMETRY', 'unset'))"], + cwd=tmp_path, + ) + + assert result["status"] == "passed" + assert result["output"] == "unset" + + +def test_command_check_can_force_non_interactive_installs(tmp_path: Path) -> None: + result = _command_check( + "environment", + "test", + [sys.executable, "-c", "import os; print(os.environ['CI'])"], + cwd=tmp_path, + environment_overrides={"CI": "true"}, + ) + + assert result["status"] == "passed" + assert result["output"] == "true" + + +def test_conformance_report_redacts_command_output(tmp_path: Path) -> None: + secret = "sk-eval-12345678901234567890" + + result = _command_check( + "redaction", + "test", + [sys.executable, "-c", f"print('failure: {secret}')"], + cwd=tmp_path, + ) + + assert secret not in json.dumps(result) + assert "[REDACTED]" in result["output"] diff --git a/integrations/agent-plugin-core/tests/test_sidekick.py b/integrations/agent-plugin-core/tests/test_sidekick.py new file mode 100644 index 000000000..9503e946e --- /dev/null +++ b/integrations/agent-plugin-core/tests/test_sidekick.py @@ -0,0 +1,83 @@ +"""Exercise bundled subagent hooks as separate host processes, without Mem0 calls.""" + +import json +import os +import subprocess +import sys +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT / "python")) + +from memory_core import EvidenceStore # noqa: E402 + + +@pytest.mark.parametrize("host", ["claude-code", "codex", "kimi", "cursor"]) +def test_sidekick_hooks_preserve_parent_scope_and_correlate_completion(tmp_path, host): + parent = tmp_path / "parent" + child = tmp_path / "child-worktree" + parent.mkdir() + child.mkdir() + database = tmp_path / "data" / "evidence.sqlite3" + store = EvidenceStore(database) + repo = store.repo_for_session("parent-session", str(parent)) + store.mark_injected("parent-session", repo.identity, [{"id": "one", "memory": "Parent memory marker."}]) + store.mark_injected("other-session", repo.identity, [{"id": "two", "memory": "Foreign memory marker."}]) + store.close() + + plugin = ROOT.parent / f"{host}-plugin" + adapter = plugin / ("adapters/claude/hook.py" if host == "claude-code" else "hooks/adapter.py") + start, stop = "sidekick-start", "sidekick-stop" + payload = {"session_id": "parent-session", "cwd": str(child), "agent_id": "worker", "agent_type": "sidekick"} + response_key = "last_assistant_message" + if host == "kimi": + start, stop = "SubagentStart", "SubagentStop" + payload["agent_name"] = payload.pop("agent_type") + response_key = "response" + elif host == "cursor": + start, stop = "subagentStart", "subagentStop" + payload = { + "conversation_id": "parent-session", + "workspace_roots": [str(child)], + "subagent_id": "worker", + "subagent_type": "sidekick", + } + response_key = "summary" + + env = {key: value for key, value in os.environ.items() if not key.startswith(("MEM0_", "CLAUDE_PLUGIN_"))} + env.update(MEM0_CODE_DATA_DIR=str(database.parent), MEM0_TELEMETRY="false", MEM0_API_URL="http://127.0.0.1:1") + + def invoke(event, body): + result = subprocess.run( + [sys.executable, str(adapter), event], + input=json.dumps({**body, "hook_event_name": event}), + text=True, + capture_output=True, + env=env, + timeout=15, + check=True, + ) + return result.stdout + + output = invoke(start, payload) + if host == "cursor": + assert json.loads(output) == {"permission": "allow"} + else: + context = output if host == "kimi" else json.loads(output)["hookSpecificOutput"]["additionalContext"] + assert "Parent memory marker." in context + assert "Foreign memory marker." not in output + assert "Parent memory marker." not in invoke(start, payload) + invoke(stop, {**payload, response_key: "Finished the delegated task."}) + + store = EvidenceStore(database) + runs = store.conn.execute("SELECT * FROM sidekick_runs").fetchall() + store.close() + assert len(runs) == 1 + assert (runs[0]["repo_id"], runs[0]["session_id"], runs[0]["agent_id"]) == ( + repo.identity, "parent-session", "worker" + ) + assert runs[0]["stopped_at"] + assert runs[0]["final_message"] == "Finished the delegated task." + assert (runs[0]["context_chars"] > 0) == (host != "cursor") diff --git a/integrations/agent-plugin-core/tests/test_validate.py b/integrations/agent-plugin-core/tests/test_validate.py new file mode 100644 index 000000000..79df69f54 --- /dev/null +++ b/integrations/agent-plugin-core/tests/test_validate.py @@ -0,0 +1,115 @@ +from __future__ import annotations + +import json +import subprocess +import sys +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +VALIDATE = ROOT / "build" / "validate.py" +PLUGIN_SCHEMA = "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json" + + +def run_validator(bundle: Path) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, str(VALIDATE), str(bundle), "--kind", "portable"], + capture_output=True, + check=False, + text=True, + ) + + +def write_manifest(bundle: Path, schema: str = PLUGIN_SCHEMA) -> None: + bundle.mkdir(parents=True, exist_ok=True) + (bundle / "plugin.json").write_text( + json.dumps({"$schema": schema, "name": "mem0"}), + encoding="utf-8", + ) + + +def test_rejects_wrong_agent_plugin_schema(tmp_path: Path) -> None: + bundle = tmp_path / "plugin" + write_manifest(bundle, "https://agent-plugins.org/v1.0.0/plugin.schema.json") + + result = run_validator(bundle) + + assert result.returncode == 1 + assert result.stderr == ( + "plugin.json.$schema: " + "'https://agent-plugins.org/schemas/1.0.0/plugin.schema.json' was expected\n" + ) + + +def test_rejects_symlink_outside_bundle(tmp_path: Path) -> None: + bundle = tmp_path / "plugin" + write_manifest(bundle) + outside = tmp_path / "outside" + outside.mkdir() + (bundle / "skills").symlink_to(outside, target_is_directory=True) + + result = run_validator(bundle) + + assert result.returncode == 1 + assert result.stderr == "skills: symlinks are not allowed in release bundles\n" + + +def test_accepts_minimal_portable_bundle(tmp_path: Path) -> None: + bundle = tmp_path / "plugin" + write_manifest(bundle) + + result = run_validator(bundle) + + assert result.returncode == 0 + assert result.stdout == f"Validated portable bundle: {bundle}\n" + assert result.stderr == "" + + +def test_rejects_nonconformant_agent_skill(tmp_path: Path) -> None: + bundle = tmp_path / "plugin" + write_manifest(bundle) + skill = bundle / "skills" / "Bad_Name" + skill.mkdir(parents=True) + (skill / "SKILL.md").write_text( + "---\nname: Bad_Name\ndescription: invalid\nunknown: true\n---\n", + encoding="utf-8", + ) + + result = run_validator(bundle) + + assert result.returncode == 1 + assert "skills/Bad_Name" in result.stderr + + +def run_native_validator(bundle: Path) -> subprocess.CompletedProcess[str]: + return subprocess.run( + [sys.executable, str(VALIDATE), str(bundle), "--kind", "native"], + capture_output=True, + check=False, + text=True, + ) + + +def test_native_bundle_rejects_malformed_json(tmp_path: Path) -> None: + bundle = tmp_path / "plugin" + bundle.mkdir(parents=True) + (bundle / "plugin.json").write_text("{bad json", encoding="utf-8") + + result = run_native_validator(bundle) + + assert result.returncode == 1 + assert "plugin.json" in result.stderr + + +def test_native_bundle_accepts_valid_json(tmp_path: Path) -> None: + bundle = tmp_path / "plugin" + bundle.mkdir(parents=True) + (bundle / "plugin.json").write_text('{"name": "mem0"}', encoding="utf-8") + hooks = bundle / "hooks" + hooks.mkdir() + (hooks / "hooks.json").write_text('{"version": 1}', encoding="utf-8") + + result = run_native_validator(bundle) + + assert result.returncode == 0 + assert "native" in result.stdout diff --git a/integrations/agent-plugin-core/typescript/package.json b/integrations/agent-plugin-core/typescript/package.json new file mode 100644 index 000000000..b9794e88a --- /dev/null +++ b/integrations/agent-plugin-core/typescript/package.json @@ -0,0 +1,14 @@ +{ + "name": "@mem0/agent-plugin-core", + "version": "0.0.0", + "private": true, + "type": "module", + "scripts": { + "test": "node --test tests/*.test.ts", + "typecheck": "tsc --noEmit" + }, + "devDependencies": { + "@types/node": "^22.15.0", + "typescript": "^5.6.0" + } +} diff --git a/integrations/agent-plugin-core/typescript/pnpm-lock.yaml b/integrations/agent-plugin-core/typescript/pnpm-lock.yaml new file mode 100644 index 000000000..65e364ea3 --- /dev/null +++ b/integrations/agent-plugin-core/typescript/pnpm-lock.yaml @@ -0,0 +1,39 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + devDependencies: + '@types/node': + specifier: ^22.15.0 + version: 22.20.1 + typescript: + specifier: ^5.6.0 + version: 5.9.3 + +packages: + + '@types/node@22.20.1': + resolution: {integrity: sha512-EANqOCF9QFyra+4pfxUcX9STKJpCLjMbObVzljIJomAWSnuSIEAvyzEU53GaajbXJEgdh0iEcPL+DGvpUd4k1Q==} + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@6.21.0: + resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} + +snapshots: + + '@types/node@22.20.1': + dependencies: + undici-types: 6.21.0 + + typescript@5.9.3: {} + + undici-types@6.21.0: {} diff --git a/integrations/agent-plugin-core/typescript/src/formatting.ts b/integrations/agent-plugin-core/typescript/src/formatting.ts new file mode 100644 index 000000000..8f569cd94 --- /dev/null +++ b/integrations/agent-plugin-core/typescript/src/formatting.ts @@ -0,0 +1,70 @@ +export interface MemoryLike { + id: string; + memory?: string; + categories?: string[]; + createdAt?: Date | string; +} + +export const MAX_OUTPUT_LINES = 200; +export const MAX_OUTPUT_CHARS = 50_000; +export const MAX_OUTPUT_BYTES = MAX_OUTPUT_CHARS; + +export function formatAge(date: Date | string): string { + const minutes = Math.floor((Date.now() - new Date(date).getTime()) / 60_000); + if (minutes < 60) return `${minutes}m ago`; + const hours = Math.floor(minutes / 60); + return hours < 24 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago`; +} + +export function formatMemoryCompact(memory: MemoryLike): string { + const category = memory.categories?.[0] ?? "uncategorized"; + const age = memory.createdAt ? ` (${formatAge(memory.createdAt)})` : ""; + return `[${category}] ${memory.memory ?? "(empty)"}${age} [mem0:${memory.id}]`; +} + +export function formatMemoryList(memories: MemoryLike[]): string { + return memories.length + ? memories.map((memory, index) => `${index + 1}. ${formatMemoryCompact(memory)}`).join("\n") + : "No memories found."; +} + +export function formatAddResult(result: unknown): string { + const items: MemoryLike[] = Array.isArray(result) + ? result + : ((result as { results?: MemoryLike[] } | null)?.results ?? (result ? [result as MemoryLike] : [])); + const pending = items.find((item) => (item as { status?: string }).status === "PENDING") as + | { eventId?: string; event_id?: string } + | undefined; + if (pending) { + const id = pending.eventId ?? pending.event_id; + return `Memory queued for background extraction${id ? ` (event ${id})` : ""}; it will be searchable shortly.`; + } + if (!items.length) return "Memory stored."; + return `Stored ${items.length} ${items.length === 1 ? "memory" : "memories"}:\n${formatMemoryList(items)}`; +} + +export function groupByCategory(memories: MemoryLike[]): Map { + const groups = new Map(); + for (const memory of memories) { + const category = memory.categories?.[0] ?? "uncategorized"; + groups.set(category, [...(groups.get(category) ?? []), memory]); + } + return groups; +} + +export function truncateOutput( + text: string, + maxChars = MAX_OUTPUT_CHARS, + maxLines = MAX_OUTPUT_LINES, +): string { + const lines = text.split("\n"); + if (lines.length <= maxLines && text.length <= maxChars) return text; + const kept = lines.slice(0, maxLines); + let result = kept.join("\n"); + const charCapped = result.length > maxChars; + if (charCapped) result = result.slice(0, maxChars); + const reasons = []; + if (kept.length < lines.length) reasons.push(`showing ${kept.length} of ${lines.length} lines`); + if (charCapped) reasons.push(`cut at ${Math.floor(maxChars / 1000)}KB`); + return `${result}\n\n[Output truncated: ${reasons.join(", ")}]`; +} diff --git a/integrations/agent-plugin-core/typescript/src/identity.ts b/integrations/agent-plugin-core/typescript/src/identity.ts new file mode 100644 index 000000000..6fffdee93 --- /dev/null +++ b/integrations/agent-plugin-core/typescript/src/identity.ts @@ -0,0 +1,33 @@ +export interface EntityParams { + userId?: string; + agentId?: string; + runId?: string; +} + +const clean = (value: string | undefined): string | undefined => value?.trim() || undefined; + +export function entitySearchFilters( + params: EntityParams, + defaultUserId: string, +): Record { + const filters: Record = { user_id: clean(params.userId) ?? defaultUserId }; + const agentId = clean(params.agentId); + const runId = clean(params.runId); + if (agentId) filters.agent_id = agentId; + if (runId) filters.run_id = runId; + return filters; +} + +export function entityAddParams(params: EntityParams, defaultUserId: string): Record { + const values: Record = { userId: clean(params.userId) ?? defaultUserId }; + const agentId = clean(params.agentId); + const runId = clean(params.runId); + if (agentId) values.agentId = agentId; + if (runId) values.runId = runId; + return values; +} + +export function parseProjectFromRemote(remote: string): string | null { + const match = remote.trim().match(/[:/]([^/:]+)\/([^/:]+?)(?:\.git)?\/?$/); + return match ? `${match[1]}-${match[2]}` : null; +} diff --git a/integrations/agent-plugin-core/typescript/src/lifecycle.ts b/integrations/agent-plugin-core/typescript/src/lifecycle.ts new file mode 100644 index 000000000..42c522b54 --- /dev/null +++ b/integrations/agent-plugin-core/typescript/src/lifecycle.ts @@ -0,0 +1,177 @@ +import type { MemoryLike } from "./formatting.ts"; +import { formatMemoryCompact } from "./formatting.ts"; + +const MAX_RECALL_QUERY_CHARS = 6_000; +export const DEFAULT_MAX_CONTEXT_CHARS = 4_000; + +const SECRET_PATTERNS: Array<[RegExp, string]> = [ + [/(authorization\s*[:=]\s*(?:bearer|token)\s+)[^\s"']+/gi, "$1[REDACTED]"], + [ + /((?:api[_-]?key|secret[_-]?access[_-]?key|session[_-]?token)\s*[:=]\s*)[^\s"']+/gi, + "$1[REDACTED]", + ], + [ + /((?:access[_-]?token|refresh[_-]?token|password|credential)\s*[:=]\s*)[^\s&"']+/gi, + "$1[REDACTED]", + ], + [/\b(?:sk|m0|mem0_sk|psk)-[A-Za-z0-9_-]{12,}\b/g, "[REDACTED]"], + [/\b(?:ASIA|AKIA)[A-Z0-9]{12,}\b/g, "[REDACTED]"], + [/\b(?:ghp_|github_pat_|xox[baprs]-)[A-Za-z0-9_-]{12,}\b/g, "[REDACTED]"], + [/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g, "[REDACTED]"], +]; + +export function redactSecrets(value: unknown): string { + let text = + typeof value === "string" + ? value + : (JSON.stringify(value, null, 0) ?? String(value)); + for (const [pattern, replacement] of SECRET_PATTERNS) text = text.replace(pattern, replacement); + return text; +} + +export function boundedText(value: unknown, limit: number): string { + const text = redactSecrets(value).trim(); + return text.length <= limit ? text : `${text.slice(0, limit)}\n...[truncated ${text.length - limit} chars]`; +} + +interface MessageLike { + role: string; + content?: unknown; +} + +function extractText(content: unknown): string | null { + if (typeof content === "string") return content; + if (!Array.isArray(content)) return null; + const text = content + .filter( + (block): block is { type: "text"; text: string } => + typeof block === "object" && + block !== null && + (block as { type?: unknown }).type === "text" && + typeof (block as { text?: unknown }).text === "string", + ) + .map((block) => block.text) + .join("\n"); + return text || null; +} + +export function extractConversation( + messages: MessageLike[], +): Array<{ role: "user" | "assistant"; content: string }> { + const conversation: Array<{ role: "user" | "assistant"; content: string }> = []; + for (const message of messages) { + if (message.role !== "user" && message.role !== "assistant") continue; + const text = extractText(message.content); + if (!text) continue; + const content = redactSecrets(text).trim(); + if (content) conversation.push({ role: message.role, content }); + } + return conversation; +} + +interface RecallOptions { + maxChars?: number; + seenIds?: Set; + timeoutMs?: number; +} + +interface MemoryLifecycleOptions { + maxContextChars?: number; + recallTimeoutMs?: number; +} + +/** Shared lifecycle policy. Host adapters only translate native events into these operations. */ +class MemoryLifecycle { + readonly #seenMemoryIds = new Set(); + readonly #options: MemoryLifecycleOptions; + + constructor(options: MemoryLifecycleOptions = {}) { + this.#options = options; + } + + beginSession(): void { + this.#seenMemoryIds.clear(); + } + + prepareConversation( + messages: MessageLike[], + ): Array<{ role: "user" | "assistant"; content: string }> { + return extractConversation(messages); + } + + prepareUserText(value: unknown): string { + return redactSecrets(value).trim(); + } + + recall( + prompt: string, + enabled: boolean, + search: (query: string) => Promise<{ results?: unknown[] }>, + ): Promise { + return buildRecallContext(prompt, enabled, search, { + maxChars: this.#options.maxContextChars, + seenIds: this.#seenMemoryIds, + timeoutMs: this.#options.recallTimeoutMs, + }); + } +} + +export function createMemoryLifecycle( + options: MemoryLifecycleOptions = {}, +): MemoryLifecycle { + return new MemoryLifecycle(options); +} + +export async function buildRecallContext( + prompt: string, + enabled: boolean, + search: (query: string) => Promise<{ results?: unknown[] }>, + options: RecallOptions = {}, +): Promise { + if (!enabled) return ""; + const query = boundedText(prompt, MAX_RECALL_QUERY_CHARS); + if (!query) return ""; + + try { + let timer: ReturnType | undefined; + let response: { results?: unknown[] } | null; + try { + const timeout = new Promise((resolve) => { + timer = setTimeout(() => resolve(null), options.timeoutMs ?? 2_000); + }); + response = await Promise.race([search(query), timeout]); + } finally { + if (timer) clearTimeout(timer); + } + if (!response) return ""; + const memories = (response.results ?? []) as MemoryLike[]; + 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 suffix = "\n"; + const maxChars = options.maxChars ?? DEFAULT_MAX_CONTEXT_CHARS; + const lines: string[] = []; + for (const memory of unseen) { + const line = `${lines.length + 1}. ${redactSecrets(formatMemoryCompact(memory)) + .replace(/\s+/g, " ") + .trim()}`; + const candidate = prefix + [...lines, line].join("\n") + suffix; + if (candidate.length > maxChars) { + if (!lines.length) { + const available = maxChars - prefix.length - suffix.length; + if (available > 1) lines.push(`${line.slice(0, available - 1).trimEnd()}…`); + } + break; + } + lines.push(line); + options.seenIds?.add(memory.id); + } + if (!lines.length) return ""; + if (unseen[0] && !options.seenIds?.has(unseen[0].id)) options.seenIds?.add(unseen[0].id); + return prefix + lines.join("\n") + suffix; + } catch { + return ""; + } +} diff --git a/integrations/agent-plugin-core/typescript/src/scoping.ts b/integrations/agent-plugin-core/typescript/src/scoping.ts new file mode 100644 index 000000000..055ef2222 --- /dev/null +++ b/integrations/agent-plugin-core/typescript/src/scoping.ts @@ -0,0 +1,50 @@ +export type Scope = "project" | "session" | "global"; + +export interface ScopeContext { + userId: string; + appId: string; + runId: string; +} + +export function normalizeScope(value: unknown): Scope { + return value === "session" || value === "global" ? value : "project"; +} + +export function resolveToolScope(requested: Scope | undefined, configured: Scope): Scope { + const scope = requested ?? configured; + if (scope === "global" && configured !== "global") { + throw new Error("Select global scope in the plugin settings or /mem0-scope command first."); + } + return scope; +} + +function validateContext(scope: Scope, context: ScopeContext): void { + const keys: (keyof ScopeContext)[] = ["userId"]; + if (scope !== "global") keys.push("appId"); + if (scope === "session") keys.push("runId"); + for (const key of keys) { + if (!context[key]?.trim() || /^\*+$/.test(context[key].trim())) { + throw new Error(`Invalid memory scope ${key}`); + } + } +} + +export function scopeSearchFilters(scope: Scope, context: ScopeContext): Record { + validateContext(scope, context); + if (scope === "session") { + return { user_id: context.userId, app_id: context.appId, run_id: context.runId }; + } + return scope === "global" + ? { user_id: context.userId } + : { user_id: context.userId, app_id: context.appId }; +} + +export function scopeAddParams(scope: Scope, context: ScopeContext): Record { + validateContext(scope, context); + if (scope === "session") { + return { userId: context.userId, appId: context.appId, runId: context.runId }; + } + return scope === "global" + ? { userId: context.userId } + : { userId: context.userId, appId: context.appId }; +} diff --git a/integrations/agent-plugin-core/typescript/src/telemetry.ts b/integrations/agent-plugin-core/typescript/src/telemetry.ts new file mode 100644 index 000000000..c6a7544ce --- /dev/null +++ b/integrations/agent-plugin-core/typescript/src/telemetry.ts @@ -0,0 +1,158 @@ +import { redactSecrets } from "./lifecycle.ts"; + +const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"; +const POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/"; +const OFF_VALUES = new Set(["false", "0", "no", "off"]); +const PRIVATE_KEYS = new Set([ + "apikey", + "authorization", + "password", + "query", + "secret", + "prompt", + "token", + "text", + "memory", + "message", + "error", + "path", + "cwd", + "userid", + "agentid", + "runid", + "repoid", + "repositoryid", + "projectid", + "appid", + "filters", +]); + +export interface TelemetryConfig { + host: string; + source: string; + version: string; + distinctId: string | (() => string | undefined); + delivery?: (batch: Record[]) => void | Promise; + flushThreshold?: number; + flushIntervalMs?: number; + maxQueueSize?: number; + commonProperties?: Record; + eventName?: (event: string) => string; + enabled?: () => boolean; +} + +export function isTelemetryEnabled(): boolean { + const value = process.env.MEM0_TELEMETRY; + return value === undefined || !OFF_VALUES.has(value.toLowerCase()); +} + +function safeValue(value: unknown): unknown { + if (typeof value === "string") return redactSecrets(value); + if (Array.isArray(value)) return value.map(safeValue); + if (value && typeof value === "object") { + return Object.fromEntries( + Object.entries(value) + .filter(([key]) => !PRIVATE_KEYS.has(key.toLowerCase().replace(/[^a-z]/g, ""))) + .map(([key, nested]) => [key, safeValue(nested)]), + ); + } + return value; +} + +function safeProperties(properties: Record): Record { + return safeValue(properties) as Record; +} + +export function errorKind(error: unknown): string { + const text = (error instanceof Error ? error.message : String(error)).toLowerCase(); + if (text.includes("timeout") || text.includes("aborted")) return "timeout"; + if (text.includes("401") || text.includes("403") || text.includes("unauthor")) return "auth"; + if (text.includes("429") || text.includes("rate limit")) return "rate-limited"; + if (/50[0234]/.test(text)) return "server-error"; + if (text.includes("400") || text.includes("422")) return "bad-request"; + if (text.includes("fetch failed") || text.includes("enotfound")) return "network"; + return error instanceof Error ? error.constructor.name : "other"; +} + +export function createTelemetry(config: TelemetryConfig) { + let queue: Record[] = []; + let timer: ReturnType | undefined; + const flushThreshold = config.flushThreshold ?? 10; + const maxQueueSize = config.maxQueueSize ?? 100; + + const deliver = config.delivery ?? (async (batch: Record[]) => { + 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), + }); + }); + + async function flush(): Promise { + if (!queue.length) return; + const batch = queue; + queue = []; + try { + await deliver(batch); + } catch { + // Telemetry must never affect plugin behavior. + } + } + + function beforeExit(): void { + void flush(); + } + + function build(event: string, properties: Record = {}): Record | null { + if (!(config.enabled?.() ?? isTelemetryEnabled())) return null; + try { + const distinctId = typeof config.distinctId === "function" ? config.distinctId() : config.distinctId; + if (!distinctId) return null; + return { + event: config.eventName?.(event) ?? event, + distinct_id: distinctId, + properties: { + ...safeProperties(properties), + ...safeProperties(config.commonProperties ?? {}), + host: config.host, + source: config.source, + language: "node", + plugin_version: config.version, + node_version: process.version, + os: process.platform, + $process_person_profile: false, + $lib: "posthog-node", + }, + }; + } catch { + return null; + } + } + + function capture(event: string, properties: Record = {}): void { + try { + const payload = build(event, properties); + if (!payload) return; + queue.push(payload); + if (queue.length > maxQueueSize) queue = queue.slice(-maxQueueSize); + if (!timer) { + timer = setInterval(() => void flush(), config.flushIntervalMs ?? 5_000); + timer.unref?.(); + process.on("beforeExit", beforeExit); + } + if (queue.length >= flushThreshold) void flush(); + } catch { + // Telemetry must never affect plugin behavior. + } + } + + function resetForTesting(): void { + queue = []; + if (timer) clearInterval(timer); + timer = undefined; + process.off("beforeExit", beforeExit); + } + + return { build, capture, flush, resetForTesting, queueForTesting: () => queue }; +} diff --git a/integrations/agent-plugin-core/typescript/tests/formatting.test.ts b/integrations/agent-plugin-core/typescript/tests/formatting.test.ts new file mode 100644 index 000000000..d96a2cf2c --- /dev/null +++ b/integrations/agent-plugin-core/typescript/tests/formatting.test.ts @@ -0,0 +1,39 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + MAX_OUTPUT_CHARS, + MAX_OUTPUT_LINES, + formatAddResult, + formatAge, + formatMemoryCompact, + formatMemoryList, + truncateOutput, +} from "../src/formatting.ts"; + +test("memory formatting preserves the existing compact host output", () => { + const now = Date.now(); + assert.equal(formatAge(new Date(now - 30 * 60_000)), "30m ago"); + assert.match( + formatMemoryCompact({ id: "abc", memory: "Dark mode", categories: ["preference"] }), + /^\[preference\] Dark mode \[mem0:abc\]$/, + ); + assert.equal(formatMemoryList([]), "No memories found."); + assert.match(formatMemoryList([{ id: "1", memory: "A" }, { id: "2", memory: "B" }]), /^1\..*\n2\./); +}); + +test("write formatting handles pending, stored, and empty results", () => { + assert.equal( + formatAddResult({ eventId: "evt-9", status: "PENDING" }), + "Memory queued for background extraction (event evt-9); it will be searchable shortly.", + ); + assert.match(formatAddResult([{ id: "1" }, { id: "2" }]), /^Stored 2 memories:/); + assert.equal(formatAddResult([]), "Memory stored."); +}); + +test("output truncation preserves small output and bounds large output", () => { + assert.equal(truncateOutput("a\nb"), "a\nb"); + const many = Array.from({ length: MAX_OUTPUT_LINES + 1 }, (_, index) => `line ${index}`).join("\n"); + assert.match(truncateOutput(many), /showing 200 of 201 lines/); + assert.match(truncateOutput("x".repeat(MAX_OUTPUT_CHARS + 1)), /cut at 50KB/); +}); diff --git a/integrations/agent-plugin-core/typescript/tests/identity.test.ts b/integrations/agent-plugin-core/typescript/tests/identity.test.ts new file mode 100644 index 000000000..c789f766f --- /dev/null +++ b/integrations/agent-plugin-core/typescript/tests/identity.test.ts @@ -0,0 +1,18 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { entityAddParams, entitySearchFilters, parseProjectFromRemote } from "../src/identity.ts"; + +test("parses common git remote forms", () => { + assert.equal(parseProjectFromRemote("git@github.com-work:mem0ai/mem0.git"), "mem0ai-mem0"); + assert.equal(parseProjectFromRemote("https://github.com/mem0ai/mem0/"), "mem0ai-mem0"); + assert.equal(parseProjectFromRemote("not-a-remote"), null); + assert.equal(parseProjectFromRemote(""), null); +}); + +test("entity filters trim overrides and preserve API casing", () => { + const params = { userId: " alice ", agentId: " agent ", runId: " " }; + assert.deepEqual(entitySearchFilters(params, "default"), { user_id: "alice", agent_id: "agent" }); + assert.deepEqual(entityAddParams(params, "default"), { userId: "alice", agentId: "agent" }); + assert.deepEqual(entitySearchFilters({ userId: " " }, "default"), { user_id: "default" }); +}); diff --git a/integrations/agent-plugin-core/typescript/tests/lifecycle.test.ts b/integrations/agent-plugin-core/typescript/tests/lifecycle.test.ts new file mode 100644 index 000000000..7e1776eae --- /dev/null +++ b/integrations/agent-plugin-core/typescript/tests/lifecycle.test.ts @@ -0,0 +1,120 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { + boundedText, + buildRecallContext, + createMemoryLifecycle, + extractConversation, + redactSecrets, +} from "../src/lifecycle.ts"; + +test("one lifecycle owns recall state and resets it for a new session", async () => { + const lifecycle = createMemoryLifecycle({ recallTimeoutMs: 50 }); + const search = async () => ({ results: [{ id: "m1", memory: "Use pnpm" }] }); + + assert.match(await lifecycle.recall("package manager", true, search), /Use pnpm/); + assert.equal(await lifecycle.recall("package manager", true, search), ""); + + lifecycle.beginSession(); + assert.match(await lifecycle.recall("package manager", true, search), /Use pnpm/); +}); + +test("one lifecycle owns capture preparation", () => { + const lifecycle = createMemoryLifecycle(); + + assert.deepEqual( + lifecycle.prepareConversation([ + { role: "user", content: "password=secret-value" }, + { role: "assistant", content: "Configured it" }, + ]), + [ + { role: "user", content: "password=[REDACTED]" }, + { role: "assistant", content: "Configured it" }, + ], + ); +}); + +test("capture preserves long prompts and responses while redacting secrets", () => { + const lifecycle = createMemoryLifecycle(); + const prompt = "Repository question. ".repeat(2000) + "Final requirement. api_key=hidden-user-secret"; + const answer = "Repository answer. ".repeat(4000) + "Final detail. password=hidden-agent-secret"; + assert.deepEqual(lifecycle.prepareConversation([ + { role: "user", content: prompt }, + { role: "assistant", content: [{ type: "text", text: answer }] }, + ]), [ + { role: "user", content: redactSecrets(prompt) }, + { role: "assistant", content: redactSecrets(answer) }, + ]); + assert.equal(lifecycle.prepareUserText(prompt), redactSecrets(prompt)); +}); + +test("redacts Claude-equivalent credentials before content leaves the host", () => { + const privateKey = "-----BEGIN PRIVATE KEY-----\nsecret\n-----END PRIVATE KEY-----"; + const input = [ + "Authorization: Bearer top-secret-token", + "api_key=super-secret-value", + "password=hunter2", + "ghp_abcdefghijklmnopqrstuvwxyz123456", + privateKey, + ].join("\n"); + + const output = redactSecrets(input); + assert.equal(output.includes("top-secret-token"), false); + assert.equal(output.includes("super-secret-value"), false); + assert.equal(output.includes("hunter2"), false); + assert.equal(output.includes("ghp_"), false); + assert.equal(output.includes("secret\n-----END"), false); + assert.match(output, /\[REDACTED\]/); +}); + +test("bounds redacted content and reports the omitted character count", () => { + assert.equal(boundedText(" abc ", 10), "abc"); + assert.equal(boundedText("abcdefgh", 5), "abcde\n...[truncated 3 chars]"); +}); + +test("normalizes and sanitizes user/assistant conversation content", () => { + const messages = [ + { role: "system", content: "ignored" }, + { role: "user", content: [{ type: "text", text: "token=m0-abcdefghijklmnop" }] }, + { role: "assistant", content: [{ type: "tool_use" }, { type: "text", text: "done" }] }, + ]; + + assert.deepEqual(extractConversation(messages), [ + { role: "user", content: "token=[REDACTED]" }, + { role: "assistant", content: "done" }, + ]); +}); + +test("recall is bounded, fail-open, and de-duplicates already injected memories", async () => { + const seen = new Set(["old"]); + const search = async () => ({ + results: [ + { id: "old", memory: "already shown" }, + { id: "new", memory: `api_key=hidden ${"x".repeat(100)}` }, + ], + }); + + const output = await buildRecallContext("what changed?", true, search, { + maxChars: 240, + seenIds: seen, + }); + assert.equal(output.includes("already shown"), false); + assert.equal(output.includes("hidden"), false); + assert.ok(output.length <= 240); + assert.equal(seen.has("new"), true); + assert.equal( + await buildRecallContext("what changed?", true, async () => { + throw new Error("offline"); + }), + "", + ); +}); + +test("recall times out without blocking the host turn", async () => { + const never = () => new Promise<{ results?: unknown[] }>(() => {}); + const started = Date.now(); + + assert.equal(await buildRecallContext("hello", true, never, { timeoutMs: 5 }), ""); + assert.ok(Date.now() - started < 100); +}); diff --git a/integrations/agent-plugin-core/typescript/tests/scoping.test.ts b/integrations/agent-plugin-core/typescript/tests/scoping.test.ts new file mode 100644 index 000000000..266457649 --- /dev/null +++ b/integrations/agent-plugin-core/typescript/tests/scoping.test.ts @@ -0,0 +1,44 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { normalizeScope, resolveToolScope, scopeAddParams, scopeSearchFilters } from "../src/scoping.ts"; + +const context = { userId: "u", appId: "app", runId: "run" }; + +test("normalizes unknown scope to project", () => { + assert.equal(normalizeScope("session"), "session"); + assert.equal(normalizeScope("global"), "global"); + assert.equal(normalizeScope("invalid"), "project"); +}); + +test("resolves project, session, and global search filters", () => { + assert.deepEqual(scopeSearchFilters("project", context), { user_id: "u", app_id: "app" }); + assert.deepEqual(scopeSearchFilters("session", context), { user_id: "u", app_id: "app", run_id: "run" }); + assert.deepEqual(scopeSearchFilters("global", context), { user_id: "u" }); +}); + +test("resolves camel-case add params", () => { + assert.deepEqual(scopeAddParams("project", context), { userId: "u", appId: "app" }); + assert.deepEqual(scopeAddParams("session", context), { userId: "u", appId: "app", runId: "run" }); + assert.deepEqual(scopeAddParams("global", context), { userId: "u" }); +}); + +test("rejects empty and wildcard identities before building filters or writes", () => { + for (const invalid of ["", " ", "*", "***"]) { + for (const scope of ["project", "session"] as const) { + for (const resolve of [scopeSearchFilters, scopeAddParams]) { + assert.throws(() => resolve(scope, { ...context, appId: invalid }), /appId/); + assert.throws(() => resolve(scope, { ...context, userId: invalid }), /userId/); + } + } + assert.throws(() => scopeSearchFilters("session", { ...context, runId: invalid }), /runId/); + } +}); + + +test("tools cannot enable global scope without a user-configured global default", () => { + assert.throws(() => resolveToolScope("global", "project"), /Select global/); + assert.throws(() => resolveToolScope("global", "session"), /Select global/); + assert.equal(resolveToolScope("global", "global"), "global"); + assert.equal(resolveToolScope("session", "project"), "session"); +}); diff --git a/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts b/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts new file mode 100644 index 000000000..e04794614 --- /dev/null +++ b/integrations/agent-plugin-core/typescript/tests/telemetry.test.ts @@ -0,0 +1,124 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import { createTelemetry, errorKind } from "../src/telemetry.ts"; + +test("telemetry preserves host names and strips sensitive properties", async () => { + const delivered: Record[][] = []; + const telemetry = createTelemetry({ + host: "deepseek", + source: "DEEPSEEK_HARNESS", + version: "1.2.3", + distinctId: "person", + delivery: async (batch) => { + delivered.push(batch); + }, + }); + + telemetry.capture("deepseek.tool.search_memory", { + success: true, + query: "secret", + apiKey: "key", + cwd: "/private/repo", + repo_id: "raw-repo", + query_chars: 6, + }); + await telemetry.flush(); + telemetry.resetForTesting(); + + const event = delivered[0][0] as { event: string; properties: Record }; + assert.equal(event.event, "deepseek.tool.search_memory"); + assert.deepEqual(event.properties, { + success: true, + query_chars: 6, + host: "deepseek", + source: "DEEPSEEK_HARNESS", + language: "node", + plugin_version: "1.2.3", + node_version: process.version, + os: process.platform, + $process_person_profile: false, + $lib: "posthog-node", + }); +}); + +test("all false-like opt-out values suppress events", async () => { + const original = process.env.MEM0_TELEMETRY; + try { + for (const value of ["false", "0", "no", "OFF"]) { + process.env.MEM0_TELEMETRY = value; + let delivered = false; + const telemetry = createTelemetry({ + host: "pi", + source: "PI_AGENT_PLUGIN", + version: "1", + distinctId: "person", + delivery: async () => { + delivered = true; + }, + }); + telemetry.capture("pi.test"); + await telemetry.flush(); + telemetry.resetForTesting(); + assert.equal(delivered, false); + } + } finally { + if (original === undefined) delete process.env.MEM0_TELEMETRY; + else process.env.MEM0_TELEMETRY = original; + } +}); + +test("telemetry redacts secrets nested inside allowed properties", () => { + const secret = "sk-eval-12345678901234567890"; + const telemetry = createTelemetry({ + host: "pi", + source: "PI_AGENT_PLUGIN", + version: "1", + distinctId: "person", + }); + + const event = telemetry.build("pi.test", { + note: `failure contained ${secret}`, + details: { authorization: `Bearer ${secret}`, count: 2 }, + }); + telemetry.resetForTesting(); + + const serialized = JSON.stringify(event); + assert.equal(serialized.includes(secret), false); + assert.equal(serialized.includes("[REDACTED]"), true); + assert.equal((event?.properties as { details: { count: number } }).details.count, 2); +}); + +for (const key of ["password", "token", "secret", "authorization"]) { + test(`telemetry removes ${key} from nested list elements`, () => { + const secret = "sk-eval-12345678901234567890"; + const telemetry = createTelemetry({ + host: "pi", + source: "PI_AGENT_PLUGIN", + version: "1", + distinctId: "person", + }); + + const event = telemetry.build("pi.test", { + details: [ + { [key]: "plain-value", count: 2 }, + { nested: { [key.toUpperCase()]: "plain-value", ok: true } }, + [`failure contained ${secret}`], + ], + }); + telemetry.resetForTesting(); + + assert.deepEqual((event?.properties as { details: unknown[] }).details, [ + { count: 2 }, + { nested: { ok: true } }, + ["failure contained [REDACTED]"], + ]); + }); +} + +test("error classification does not expose messages", () => { + assert.equal(errorKind(new Error("429 secret query")), "rate-limited"); + assert.equal(errorKind(new Error("401 key")), "auth"); + assert.equal(errorKind(new Error("request timeout")), "timeout"); + assert.equal(errorKind(new Error("fetch failed")), "network"); +}); diff --git a/integrations/agent-plugin-core/typescript/tsconfig.json b/integrations/agent-plugin-core/typescript/tsconfig.json new file mode 100644 index 000000000..5abe9f948 --- /dev/null +++ b/integrations/agent-plugin-core/typescript/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "moduleResolution": "bundler", + "strict": true, + "types": ["node"], + "allowImportingTsExtensions": true, + "noEmit": true + }, + "include": ["src", "tests"] +} diff --git a/integrations/antigravity-plugin/agents/sidekick/agent.md b/integrations/antigravity-plugin/agents/sidekick/agent.md new file mode 100644 index 000000000..6a4d8f29a --- /dev/null +++ b/integrations/antigravity-plugin/agents/sidekick/agent.md @@ -0,0 +1,17 @@ +--- +name: sidekick +description: Coding subagent for focused implementation, investigation, testing, debugging, or review work. +subagent: true +--- + +You are Mem0's coding sidekick. Complete only the bounded task the main agent +delegates to you and return a concise, self-contained result. + +Search Mem0 before work that may depend on prior repository decisions or user +preferences. Inspect the relevant repository rules and code, make changes when +asked, and run the smallest decisive validation. Use only the workspace the +caller assigned; do not assume a separate Git worktree. + +Your final response must state the outcome, changed files, validation, and any +remaining risk. Do not commit, push, or open a pull request unless the caller +explicitly asks. diff --git a/integrations/antigravity-plugin/core/flush_worker.py b/integrations/antigravity-plugin/core/flush_worker.py new file mode 100644 index 000000000..6f7b9ecb2 --- /dev/null +++ b/integrations/antigravity-plugin/core/flush_worker.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Detached remote checkpoint worker. + +Claude Code may cancel SessionEnd hooks as a print-mode process exits. The hook +therefore persists its input first and launches this process in a new session. +""" + +from __future__ import annotations + +import json +import os +import sys +import time +from pathlib import Path + +import telemetry +from memory_core import ( + EvidenceStore, + checkpoint_session, + configure_harness, + touch_handoff_heartbeat, +) + + +def main() -> int: + if len(sys.argv) != 2: + return 2 + handoff_path = Path(sys.argv[1]) + os.environ["MEM0_CODE_HANDOFF_PATH"] = str(handoff_path) + harness = os.environ.get("MEM0_PLUGIN_HARNESS") + if harness: + source_tag = os.environ.get("MEM0_PLUGIN_SOURCE_TAG", "") + configure_harness( + harness, + env_prefix=os.environ.get("MEM0_PLUGIN_ENV_PREFIX", ""), + data_dir_name=os.environ.get("MEM0_PLUGIN_DATA_DIR_NAME", ""), + source_tag=source_tag, + ) + telemetry.init(harness=harness, source_tag=source_tag.upper()) + completed = False + try: + payload = json.loads(handoff_path.read_text(encoding="utf-8")) + delay = float(payload.get("delay_seconds") or 0) + if delay > 0: + payload.pop("delay_seconds", None) + temporary = handoff_path.with_suffix(f".{os.getpid()}.tmp") + try: + temporary.write_text(json.dumps(payload), encoding="utf-8") + temporary.replace(handoff_path) + finally: + temporary.unlink(missing_ok=True) + time.sleep(delay) + if not handoff_path.exists(): + return 0 + hook_input = payload.get("hook_input") or {} + reason = str(payload.get("reason") or "checkpoint") + wait_for_inflight = bool(payload.get("wait_for_inflight")) + store = EvidenceStore() + try: + if wait_for_inflight: + session_id = str( + hook_input.get("session_id") or "unknown-session" + ) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + deadline = time.monotonic() + float( + os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120") + ) + while ( + store.has_inflight_flush(repo.identity, session_id) + and time.monotonic() < deadline + ): + touch_handoff_heartbeat() + time.sleep(0.25) + # Hooks capture the conversation before handoff; the worker only flushes it. + result = checkpoint_session(store, hook_input, reason) + print(json.dumps(result, sort_keys=True), flush=True) + completed = result.get("status") in { + "semantic-succeeded", + "explicitly-stored", + "nothing-to-flush", + } + finally: + store.close() + return 0 + finally: + telemetry.flush() + if completed: + try: + handoff_path.unlink() + except OSError: + pass + elif handoff_path.suffix == ".running": + try: + handoff_path.replace(handoff_path.with_suffix(".json")) + except OSError: + pass + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/antigravity-plugin/core/hook_runner.py b/integrations/antigravity-plugin/core/hook_runner.py new file mode 100644 index 000000000..2a2adb557 --- /dev/null +++ b/integrations/antigravity-plugin/core/hook_runner.py @@ -0,0 +1,372 @@ +"""Shared hook orchestration for all Mem0 agent plugins.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +import uuid +from pathlib import Path + +import telemetry +from memory_core import ( + EvidenceStore, + _session_id, + api_key, + bounded, + cache_plugin_api_key, + checkpoint_session, + clear_stale_api_key_cache, + configure_harness, + data_dir, + detached_process_kwargs, + format_context, + harness_config, + record_session_start, + record_tool, + record_user_prompt, + redact, + search_memories, +) + +STALE_RUNNING_SECONDS = 300 +PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60 +PENDING_LAUNCH_LIMIT = 5 +DEFAULT_IDLE_FLUSH_SECONDS = 300 + +_core_dir: Path = Path(__file__).resolve().parent + + +def read_hook_input() -> dict: + try: + value = json.load(sys.stdin) + return value if isinstance(value, dict) else {} + except (json.JSONDecodeError, OSError): + return {} + + +def default_record_stop(store: EvidenceStore, hook_input: dict): + """Record the assistant's response without transcript parsing.""" + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + message = redact(hook_input.get("last_assistant_message", "")).strip() + if message: + store.record_assistant_response(repo, session_id, message) + return repo, session_id + + +def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict: + """Search once before the agent handles the first prompt in a session.""" + repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input) + if not is_first_prompt: + return {} + try: + minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20")) + except ValueError: + minimum_query_chars = 20 + if len(prompt.strip()) < max(minimum_query_chars, 1): + return {} + result = search_memories( + store, repo, session_id, bounded(prompt, 6000), + top_k=5, operation="first-prompt-search", timeout=2, + ) + if not result.memories: + return {} + context = format_context( + result.memories, + "Mem0 found these relevant memories from earlier work in this repository:", + ) + telemetry.record( + "context_injected", + repo=repo, session_id=session_id, trigger="first-prompt", + memory_count=len(result.memories), context_chars=len(context), + prompt_chars=len(prompt), + ) + return { + "hookSpecificOutput": { + "hookEventName": "UserPromptSubmit", + "additionalContext": context, + }, + } + + +def _launch_handoff(handoff_path: Path) -> bool: + running_path = handoff_path.with_suffix(".running") + try: + handoff_path.replace(running_path) + except OSError: + return False + worker = _core_dir / "flush_worker.py" + log_path = data_dir() / "flush-worker.log" + log_handle = open(log_path, "a", encoding="utf-8") + harness = harness_config() + child_env = os.environ.copy() + child_env.update( + { + "MEM0_CODE_DATA_DIR": str(data_dir()), + "MEM0_PLUGIN_HARNESS": harness["name"], + "MEM0_PLUGIN_ENV_PREFIX": harness["env_prefix"], + "MEM0_PLUGIN_DATA_DIR_NAME": harness["data_dir_name"], + "MEM0_PLUGIN_SOURCE_TAG": harness["source_tag"], + } + ) + try: + subprocess.Popen( + [sys.executable, str(worker), str(running_path)], + stdin=subprocess.DEVNULL, + stdout=log_handle, stderr=log_handle, + close_fds=True, + env=child_env, + **detached_process_kwargs(), + ) + finally: + log_handle.close() + return True + + +def recover_pending_handoffs() -> int: + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + now = time.time() + for running in pending_dir.glob("*.running"): + try: + if now - running.stat().st_mtime > STALE_RUNNING_SECONDS: + running.replace(running.with_suffix(".json")) + except OSError: + continue + recoverable = [] + for handoff in pending_dir.glob("*.json"): + try: + age = now - handoff.stat().st_mtime + except OSError: + continue + if age > PENDING_EXPIRY_SECONDS: + handoff.unlink(missing_ok=True) + continue + recoverable.append((age, handoff)) + recoverable.sort(key=lambda item: item[0], reverse=True) + launched = 0 + for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]: + launched += int(_launch_handoff(handoff)) + return launched + + +def refresh_pending_handoffs() -> None: + pending_dir = data_dir() / "pending" + if not pending_dir.is_dir(): + return + for pattern in ("*.json", "*.running"): + for handoff in pending_dir.glob(pattern): + try: + os.utime(handoff) + except OSError: + continue + + +def hand_off_flush( + hook_input: dict, reason: str, *, wait_for_inflight: bool = False, +) -> None: + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + material = ( + f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}" + ) + digest = hashlib.sha256(material.encode()).hexdigest()[:24] + handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json" + temporary_path = handoff_path.with_suffix(".tmp") + temporary_path.write_text( + json.dumps({ + "hook_input": hook_input, + "reason": reason, + "wait_for_inflight": wait_for_inflight, + }), + encoding="utf-8", + ) + temporary_path.replace(handoff_path) + _launch_handoff(handoff_path) + + +def automatic_flush_enabled() -> bool: + return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in { + "1", "true", "yes", "on", + } + + +def schedule_periodic_checkpoint( + store: EvidenceStore, hook_input: dict, repo, session_id: str, +) -> bool: + if ( + not automatic_flush_enabled() + or not api_key() + or not store.checkpoint_due(repo.identity, session_id) + ): + return False + if store.prepare_flush(repo, session_id, "periodic") is None: + return False + hand_off_flush(hook_input, "periodic") + return True + + +def _idle_flush_seconds() -> int: + try: + return max( + int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))), + 0, + ) + except ValueError: + return DEFAULT_IDLE_FLUSH_SECONDS + + +def schedule_idle_flush( + store: EvidenceStore, hook_input: dict, repo, session_id: str, +) -> bool: + delay = _idle_flush_seconds() + if delay <= 0 or not automatic_flush_enabled() or not api_key(): + return False + if store.has_inflight_flush(repo.identity, session_id): + return False + if not store.has_unflushed_events(repo.identity, session_id): + return False + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}" + digest = hashlib.sha256(material.encode()).hexdigest()[:24] + for old in pending_dir.glob(f"idle-{digest}*"): + old.unlink(missing_ok=True) + handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json" + temporary_path = handoff_path.with_suffix(".tmp") + temporary_path.write_text( + json.dumps({ + "hook_input": hook_input, + "reason": "idle", + "delay_seconds": delay, + }), + encoding="utf-8", + ) + temporary_path.replace(handoff_path) + _launch_handoff(handoff_path) + return True + + +def log_failure(exc: Exception) -> None: + try: + log_path = data_dir() / "plugin-errors.log" + with log_path.open("a", encoding="utf-8") as handle: + handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n") + except OSError: + pass + + +def run( + *, + record_stop_fn=None, + extra_actions: dict | None = None, + data_dir_env: str = "MEM0_PLUGIN_DATA_DIR", + automatic_flush_reasons: set | None = None, +) -> int: + if record_stop_fn is None: + record_stop_fn = default_record_stop + if automatic_flush_reasons is None: + automatic_flush_reasons = {"session-end"} + + base_actions = ["session-start", "user-prompt", "post-tool", "stop", "flush"] + all_actions = base_actions + list((extra_actions or {}).keys()) + + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=all_actions) + parser.add_argument("--reason", default="manual") + parser.add_argument("--plugin-data-dir", default="") + parser.add_argument("--harness", default="") + args = parser.parse_args() + + if args.harness: + configure_harness(args.harness) + telemetry.init(harness=args.harness) + + if args.plugin_data_dir: + os.environ[data_dir_env] = args.plugin_data_dir + + cache_plugin_api_key() + if args.action == "session-start": + clear_stale_api_key_cache() + + hook_input = read_hook_input() + store = EvidenceStore() + try: + if store.is_paused(): + if args.action == "session-start": + refresh_pending_handoffs() + telemetry.record("session_start", paused=True) + telemetry.spawn_flush() + return 0 + + if args.action == "session-start": + if telemetry.is_first_run(): + telemetry.record("install") + recovered = recover_pending_handoffs() + record_session_start(store, hook_input) + if recovered: + telemetry.record("handoff_recovered", count=recovered) + telemetry.spawn_flush() + elif args.action == "user-prompt": + output = first_prompt_memory_output(store, hook_input) + if output: + print(json.dumps(output)) + elif args.action == "post-tool": + record_tool(store, hook_input) + elif args.action == "stop": + repo, session_id = record_stop_fn(store, hook_input) + if not schedule_periodic_checkpoint(store, hook_input, repo, session_id): + schedule_idle_flush(store, hook_input, repo, session_id) + elif args.action == "flush": + automatic = args.reason in automatic_flush_reasons + if automatic and not automatic_flush_enabled(): + return 0 + if args.reason == "session-end": + record_stop_fn(store, hook_input) + if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1": + print(json.dumps(checkpoint_session(store, hook_input, args.reason))) + else: + session_id = str(hook_input.get("session_id") or "unknown-session") + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + already_running = store.has_inflight_flush(repo.identity, session_id) + if already_running and args.reason == "session-end": + hand_off_flush(hook_input, args.reason, wait_for_inflight=True) + elif not already_running and store.prepare_flush( + repo, session_id, args.reason, + ) is not None: + hand_off_flush(hook_input, args.reason) + elif extra_actions and args.action in extra_actions: + result = extra_actions[args.action](store, hook_input) + if result: + print(json.dumps(result)) + finally: + store.close() + return 0 + + +def entry_point( + *, + record_stop_fn=None, + extra_actions: dict | None = None, + data_dir_env: str = "MEM0_PLUGIN_DATA_DIR", + automatic_flush_reasons: set | None = None, +) -> None: + try: + raise SystemExit(run( + record_stop_fn=record_stop_fn, + extra_actions=extra_actions, + data_dir_env=data_dir_env, + automatic_flush_reasons=automatic_flush_reasons, + )) + except Exception as exc: + log_failure(exc) + raise SystemExit(0) + + +if __name__ == "__main__": + entry_point() diff --git a/integrations/antigravity-plugin/core/mcp_server.py b/integrations/antigravity-plugin/core/mcp_server.py new file mode 100644 index 000000000..036fbbdc9 --- /dev/null +++ b/integrations/antigravity-plugin/core/mcp_server.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Expose Mem0's memory search as one local coding-agent tool.""" + +from __future__ import annotations + +import json +import os +import sys +from typing import Any + +import telemetry +from memory_core import ( + CODING_MEMORY_CATEGORY_NAMES, + PLUGIN_VERSION, + SEARCH_SCOPES, + format_search_result, + resolve_repo, + search_memories, +) + +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." +) +TOOL_SCHEMA = { + "type": "object", + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 2000, + "description": "A direct question about earlier work in this repository.", + }, + "top_k": { + "type": "integer", + "minimum": 1, + "maximum": 20, + "description": "Maximum memories to return. Uses Mem0's configured default when omitted.", + }, + "category": { + "type": "string", + "enum": list(CODING_MEMORY_CATEGORY_NAMES), + "description": "Optional memory category. Omit to search every category.", + }, + "scope": { + "type": "string", + "enum": list(SEARCH_SCOPES), + "description": ( + "Which memories to search. 'repo' (default) is the whole repository's " + "shared memory plus your own preferences, 'dir' narrows the shared " + "part to the current directory, 'mine' is your preferences alone." + ), + }, + "run_id": { + "type": "string", + "minLength": 1, + "description": ( + "Optional coding-agent session ID. With any scope, restricts results to memories " + "saved in that session. Omit to recall memories across sessions." + ), + }, + }, + "required": ["query"], + "additionalProperties": False, +} + + +class ToolInputError(ValueError): + pass + + +def _validate_arguments( + arguments: Any, +) -> tuple[str, int | None, str | None, str | None, str | None]: + if not isinstance(arguments, dict): + raise ToolInputError("Search arguments must be an object.") + + unknown = set(arguments) - {"query", "top_k", "category", "scope", "run_id"} + if unknown: + raise ToolInputError(f"Unknown search argument: {sorted(unknown)[0]}") + + query = arguments.get("query") + if not isinstance(query, str) or not query.strip(): + raise ToolInputError("query must be a non-empty string.") + query = query.strip() + if len(query) > 2000: + raise ToolInputError("query must be at most 2,000 characters.") + + top_k = arguments.get("top_k") + if top_k is not None and ( + isinstance(top_k, bool) or not isinstance(top_k, int) or not 1 <= top_k <= 20 + ): + raise ToolInputError("top_k must be an integer from 1 to 20.") + + category = arguments.get("category") + if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES: + raise ToolInputError("category must be one of Mem0's supported categories.") + + scope = arguments.get("scope") + if scope is not None and scope not in SEARCH_SCOPES: + raise ToolInputError(f"scope must be one of {list(SEARCH_SCOPES)}.") + + run_id = arguments.get("run_id") + if run_id is not None: + if not isinstance(run_id, str) or not run_id.strip(): + raise ToolInputError("run_id must be a non-empty string.") + run_id = run_id.strip() + + return query, top_k, category, scope, run_id + + +def call_search_memories(arguments: Any, cwd: str | None = None) -> str: + query, top_k, category, scope, run_id = _validate_arguments(arguments) + repo = resolve_repo(cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()) + result = search_memories( + None, + repo, + None, + query, + top_k=top_k, + category=category, + scope=scope, + run_id=run_id, + operation="mcp-search", + ) + return format_search_result(result) + + +def _workspace_cwd(params: dict[str, Any]) -> str | None: + meta = params.get("_meta") + if not isinstance(meta, dict): + return None + metadata = meta.get("x-codex-turn-metadata") + if not isinstance(metadata, dict): + return None + workspaces = metadata.get("workspaces") or {} + if isinstance(workspaces, dict): + return next((path for path in workspaces if isinstance(path, str) and path), None) + return None + + +def _tool_response(text: str, *, is_error: bool = False) -> dict[str, Any]: + return { + "content": [{"type": "text", "text": text}], + "isError": is_error, + } + + +def handle_request(message: Any) -> dict[str, Any] | None: + if not isinstance(message, dict): + return None + request_id = message.get("id") + method = message.get("method") + + if method == "notifications/initialized": + return None + if method == "initialize": + requested = (message.get("params") or {}).get("protocolVersion") + return { + "jsonrpc": "2.0", + "id": request_id, + "result": { + "protocolVersion": requested or PROTOCOL_VERSION, + "capabilities": {"tools": {"listChanged": False}}, + "serverInfo": {"name": "mem0", "version": PLUGIN_VERSION}, + }, + } + if method == "ping": + return {"jsonrpc": "2.0", "id": request_id, "result": {}} + if method == "tools/list": + return { + "jsonrpc": "2.0", + "id": request_id, + "result": { + "tools": [ + { + "name": TOOL_NAME, + "description": TOOL_DESCRIPTION, + "inputSchema": TOOL_SCHEMA, + "annotations": { + "readOnlyHint": True, + "idempotentHint": True, + "openWorldHint": True, + }, + } + ] + }, + } + if method == "tools/call": + params = message.get("params") or {} + if params.get("name") != TOOL_NAME: + result = _tool_response("Unknown Mem0 tool.", is_error=True) + else: + try: + result = _tool_response( + call_search_memories(params.get("arguments"), _workspace_cwd(params)) + ) + except ToolInputError as exc: + result = _tool_response(str(exc), is_error=True) + except Exception: + result = _tool_response("Memory search failed.", is_error=True) + return {"jsonrpc": "2.0", "id": request_id, "result": result} + if request_id is None: + return None + return { + "jsonrpc": "2.0", + "id": request_id, + "error": {"code": -32601, "message": "Method not found"}, + } + + +def main() -> int: + for raw_line in sys.stdin: + try: + message = json.loads(raw_line) + response = handle_request(message) + except json.JSONDecodeError: + response = { + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32700, "message": "Parse error"}, + } + except Exception: + response = { + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32603, "message": "Internal error"}, + } + if response is not None: + sys.stdout.write(json.dumps(response, separators=(",", ":")) + "\n") + sys.stdout.flush() + telemetry.spawn_flush() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/antigravity-plugin/core/memory_cli.py b/integrations/antigravity-plugin/core/memory_cli.py new file mode 100644 index 000000000..595729feb --- /dev/null +++ b/integrations/antigravity-plugin/core/memory_cli.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Mem0 diagnostics and user controls.""" + +from __future__ import annotations + +import argparse +import json +import os + +import telemetry +from memory_core import ( + EvidenceStore, + api_key, + data_dir, + doctor, + forget_remote_repo, + configure_harness, + resolve_repo, + user_id, +) + + +def _print_status(value: dict) -> None: + last = value.get("last_operation") or {} + print(f"Mem0: {'paused' if value['paused'] else 'active'}") + print(f"Repository: {value['repo_id']}") + print(f"Local data: {value['data_dir']}") + print(f"API key: {'configured' if value['api_key_configured'] else 'missing'}") + print( + "Saved on this computer: " + f"{value['events']} session details, {value['flushes']} memory updates" + ) + print( + f"Used in this repository: {value['retrievals']} memories returned, " + f"{value['sidekick_runs']} sidekick runs" + ) + if last: + item_label = "" + if last["operation"] in {"flush", "flush-retry"}: + item_label = f", {last['item_count']} memories" + operation = ( + "memory update" + if last["operation"] in {"flush", "flush-retry"} + else last["operation"].replace("-", " ") + ) + print( + f"Last {operation}: " + f"{'succeeded' if last['success'] else 'failed'} " + f"({last['duration_ms']:.1f} ms{item_label})" + ) + sidekick = value.get("last_sidekick") or {} + if sidekick: + state = "finished" if sidekick.get("stopped_at") else "started" + print( + "Last sidekick: " + f"{state}, received {sidekick['context_chars']} characters of memory, " + f"agent {sidekick['agent_id']}" + ) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--plugin-data-dir", default="") + parser.add_argument("--harness", default="") + subparsers = parser.add_subparsers(dest="command", required=True) + + status = subparsers.add_parser("status") + status.add_argument("--json", action="store_true") + + doctor_parser = subparsers.add_parser("doctor") + doctor_parser.add_argument("--json", action="store_true") + + subparsers.add_parser("pause") + subparsers.add_parser("resume") + + forget = subparsers.add_parser("forget") + forget.add_argument("--remote", action="store_true") + forget.add_argument("--yes", action="store_true") + forget.add_argument("--include-project-memory", action="store_true") + + args = parser.parse_args() + if args.harness: + source_tag = f"{args.harness.replace('-', '_')}_plugin" + configure_harness(args.harness, source_tag=source_tag) + telemetry.init(harness=args.harness, source_tag=source_tag.upper()) + if args.plugin_data_dir: + os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir + store = EvidenceStore() + try: + repo = resolve_repo(os.getcwd()) + telemetry.record("control", repo=repo, action=args.command) + if args.command == "status": + result = { + **store.status(repo.identity), + "repo_id": repo.identity, + "app_id": repo.app_id, + "project_id": repo.project_id, + "directory": repo.directory, + "user_id": user_id(), + "data_dir": str(data_dir()), + "api_key_configured": bool(api_key()), + } + if args.json: + print(json.dumps(result, indent=2, default=str)) + else: + _print_status(result) + elif args.command == "doctor": + result = doctor(os.getcwd()) + if args.json: + print(json.dumps(result, indent=2, default=str)) + else: + for name, check in result["checks"].items(): + print( + f"{'PASS' if check['ok'] else 'FAIL'} {name}: {check['detail']}" + ) + return 0 if result["ok"] else 1 + elif args.command == "pause": + store.set_setting("paused", "true") + print("Mem0 stopped saving and searching memories.") + elif args.command == "resume": + store.set_setting("paused", "false") + print("Mem0 resumed saving and searching memories.") + elif args.command == "forget": + if not args.yes: + print( + "Refusing to delete data without --yes. Add --remote to also " + "delete this user/repository scope from Mem0." + ) + return 2 + remote_result = ( + forget_remote_repo( + repo, include_project_memory=args.include_project_memory + ) + if args.remote + else None + ) + local_result = store.forget_local_repo(repo.identity) + print( + json.dumps( + {"local": local_result, "remote": remote_result}, + indent=2, + default=str, + ) + ) + if remote_result and remote_result.get("status") == "error": + return 1 + finally: + store.close() + telemetry.spawn_flush() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/antigravity-plugin/core/memory_core.py b/integrations/antigravity-plugin/core/memory_core.py new file mode 100644 index 000000000..cf71196b8 --- /dev/null +++ b/integrations/antigravity-plugin/core/memory_core.py @@ -0,0 +1,2645 @@ +#!/usr/bin/env python3 +"""Shared core for Mem0 agent plugins. + +Hooks record small session details locally. When the agent compacts or ends the +session, Mem0 sends the useful parts to the platform so it can create memories. +The agent can search those memories during later work in the repository. +""" + +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import sqlite3 +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Iterable + +import telemetry + +DEFAULT_API_URL = "https://api.mem0.ai" +PLUGIN_VERSION = "0.3.1" + +_harness_name: str = "generic" +_harness_env_prefix: str = "MEM0_PLUGIN" +_harness_data_dir_name: str = "mem0-plugin" +_harness_source_tag: str = "mem0_plugin" + + +def configure_harness( + name: str, + env_prefix: str = "", + data_dir_name: str = "", + source_tag: str = "", +) -> None: + global _harness_name, _harness_env_prefix, _harness_data_dir_name, _harness_source_tag + _harness_name = name + _harness_env_prefix = env_prefix or f"MEM0_{name.upper().replace('-', '_')}" + _harness_data_dir_name = data_dir_name or f"{name}-plugin" + _harness_source_tag = source_tag or f"{name.replace('-', '_')}_plugin" + + +def harness_config() -> dict[str, str]: + return { + "name": _harness_name, + "env_prefix": _harness_env_prefix, + "data_dir_name": _harness_data_dir_name, + "source_tag": _harness_source_tag, + } + + +MAX_COMMAND_CHARS = 2000 +MAX_RESULT_CHARS = 2500 +MAX_EPISODE_CHARS = 12000 +CHECKPOINT_EXCHANGES = 5 +CHECKPOINT_MESSAGES = 10 +CHECKPOINT_SOURCE_CHARS = 40000 +DEFAULT_MAX_CONTEXT_CHARS = 4000 +MAX_EXTRACTION_INPUT_TOKENS = 24000 +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. + +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 current coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions. + +Write about the repository, not the user, assistant, session, or task. Do not save personal preferences. Do not save a memory that only states which repository, branch, or directory the session worked in. Do not include test results, documentation updates, release notes, or temporary state. + +If nothing useful was established, return no memories.""" + +PERSONAL_MEMORY_INSTRUCTIONS = """Save concise facts about the user that will help in any repository: preferred tools, package managers, languages, coding style, review and communication preferences, and anything the user explicitly asked to be remembered about themselves. + +Write in the third person about the user, not about the repository, the assistant, the session, or the task. Do not save repository facts, project decisions, commands, or what was built. + +Never save that the user has no preferences or that nothing was learned. If nothing was learned about the user, return no memories.""" + +CODING_MEMORY_CATEGORIES = [ + { + "project_knowledge": ( + "What the project is and how its code, APIs, data, files, and " + "components work." + ) + }, + { + "decisions_and_constraints": ( + "Why an approach was chosen, what must remain true, and rules future " + "work must follow." + ) + }, + { + "workflows": ( + "How to run, test, debug, deploy, configure, or otherwise work on the " + "project." + ) + }, + { + "problems_and_fixes": ( + "Bugs, failures, known pitfalls, their causes, and how to fix or avoid " + "them." + ) + }, + { + "results": ( + "Outcomes and measurements from tests, benchmarks, experiments, or " + "investigations." + ) + }, +] +CODING_MEMORY_CATEGORY_NAMES = tuple( + category_name + for category in CODING_MEMORY_CATEGORIES + for category_name in category +) + +TEST_COMMAND_RE = re.compile( + r"(?:^|\s)(?:pytest|py\.test|jest|vitest|go\s+test|cargo\s+test|" + r"npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|" + r"mvn\s+test|gradle\s+test|make\s+test)(?:\s|$)", + re.IGNORECASE, +) +BUILD_COMMAND_RE = re.compile( + r"(?:^|\s)(?:npm|pnpm|yarn)\s+(?:run\s+)?build(?:\s|$)|" + r"(?:^|\s)(?:cargo|go|mvn|gradle|make)\s+build(?:\s|$)", + re.IGNORECASE, +) + +SECRET_PATTERNS = [ + re.compile(r"(?i)(authorization\s*[:=]\s*(?:bearer|token)\s+)[^\s\"']+"), + re.compile( + r"(?i)((?:api[_-]?key|secret[_-]?access[_-]?key|session[_-]?token)\s*[:=]\s*)[^\s\"']+" + ), + re.compile( + r"(?i)((?:access[_-]?token|refresh[_-]?token|password|credential)" + r"\s*[:=]\s*)[^\s&\"']+" + ), + re.compile(r"\b(?:sk|m0|mem0_sk|psk)-[A-Za-z0-9_\-]{12,}\b"), + re.compile(r"\b(?:ASIA|AKIA)[A-Z0-9]{12,}\b"), + re.compile(r"\b(?:ghp_|github_pat_|xox[baprs]-)[A-Za-z0-9_\-]{12,}\b"), + re.compile( + r"-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----", + re.DOTALL, + ), + re.compile( + r'(?i)("(?:api[_-]?key|password|secret(?:[_-]?access[_-]?key)?' + r'|(?:access|refresh|session)[_-]?token|token|authorization|credential' + r')"\s*:\s*")(?:\\.|[^"\\])*' + ), +] + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def redact(value: Any) -> str: + text = ( + value + if isinstance(value, str) + else json.dumps(value, ensure_ascii=False, default=str) + ) + for pattern in SECRET_PATTERNS: + if pattern.groups: + text = pattern.sub(r"\1[REDACTED]", text) + else: + text = pattern.sub("[REDACTED]", text) + return text + + +def bounded(value: Any, limit: int) -> str: + text = redact(value).strip() + if len(text) <= limit: + return text + return text[:limit] + f"\n...[truncated {len(text) - limit} chars]" + + +def _git(cwd: str, *args: str) -> str: + try: + result = subprocess.run( + ["git", "-C", cwd, *args], + check=False, + capture_output=True, + text=True, + timeout=0.5, + ) + except (OSError, subprocess.TimeoutExpired): + return "" + return result.stdout.strip() if result.returncode == 0 else "" + + +def _normalize_remote(remote: str) -> str: + remote = remote.strip() + if remote.startswith("git@") and ":" in remote: + host_path = remote[4:].replace(":", "/", 1) + remote = f"https://{host_path}" + if remote.endswith(".git"): + remote = remote[:-4] + if "://" in remote: + parsed = urllib.parse.urlsplit(remote) + hostname = parsed.hostname or "" + if parsed.port: + hostname = f"{hostname}:{parsed.port}" + remote = urllib.parse.urlunsplit( + (parsed.scheme, hostname, parsed.path, parsed.query, parsed.fragment) + ) + return remote.rstrip("/") + + +_WILDCARD_SCOPE = re.compile(r"^\*+$") + + +def _scope_value(raw: str | None) -> str: + """Reject wildcards as identities: they are filter syntax and would widen the scope.""" + value = (raw or "").strip() + return "" if _WILDCARD_SCOPE.match(value) else value + + +SEARCH_SCOPES = ("repo", "dir", "mine") +DEFAULT_SEARCH_SCOPE = "repo" + +def directory_app_id(repo: RepoContext) -> str: + """The app_id of the directory this session runs in: the repository at the root, repository/path below it.""" + return f"{repo.app_id}/{repo.directory}" if repo.directory else repo.app_id + + +def directory_chain(repo: RepoContext) -> list[str]: + """Every directory a memory belongs to, from the top-level folder down to the one it was written in.""" + parts = repo.directory.split("/") if repo.directory else [] + return ["/".join(parts[: index + 1]) for index in range(len(parts))] + + +def _shared_project_ids(repo: RepoContext) -> list[str]: + """Current and pre-upgrade namespaces, shared by recall and explicit deletion.""" + if not repo.identity.startswith("local:") and repo.project_id != repo.app_id: + return [repo.project_id, repo.app_id] + return [repo.project_id] + + +def _search_filters(user: str, repo: RepoContext, scope: str) -> dict[str, Any]: + """Build the scope filter: app_id scopes to the repo, then union shared and personal lanes.""" + app_scope = {"app_id": repo.app_id} + mine = {"AND": [{"user_id": user}, app_scope]} + if scope == "mine": + return mine + projects = [{"AND": [{"agent_id": project_id}, app_scope]} for project_id in _shared_project_ids(repo)] + shared: dict[str, Any] = projects[0] if len(projects) == 1 else {"OR": projects} + if scope == "dir" and repo.directory: + shared = {"AND": [shared, {"metadata": {"dirs": {"contains": repo.directory}}}]} + return {"OR": [shared, mine]} + + +def search_scope() -> str: + configured = ( + _plugin_option("search_scope", "MEM0_CODE_SEARCH_SCOPE") or "" + ).strip().lower() + return configured if configured in SEARCH_SCOPES else DEFAULT_SEARCH_SCOPE + + +def resolve_search_scope(scope: str | None) -> str: + value = (scope or search_scope()).strip().lower() + if value not in SEARCH_SCOPES: + raise ValueError(f"Unknown search scope: {value}") + return value + + +def _legacy_project_map(cwd: str, root: str, raw_remote: str) -> str: + """Return the project name used by the previous Claude Code plugin.""" + try: + data = json.loads((Path.home() / ".mem0" / "project_map.json").read_text()) + except (OSError, json.JSONDecodeError): + return "" + if not isinstance(data, dict): + return "" + + keys = list(dict.fromkeys([cwd, root, os.path.realpath(cwd), os.path.realpath(root)])) + if raw_remote: + keys.append(f"remote:{hashlib.sha256(raw_remote.encode()).hexdigest()[:16]}") + for key in keys: + value = data.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + return "" + + +def _legacy_project_id(cwd: str, root: str, raw_remote: str, identity: str) -> str: + """Use the repository namespace created by the previous Mem0 plugin.""" + configured = _scope_value(os.environ.get("MEM0_PROJECT_ID")) + if configured: + return configured + + mapped = _scope_value(_legacy_project_map(cwd, root, raw_remote)) + if mapped: + return mapped + + remote = raw_remote or ("" if identity.startswith("local:") else identity) + remote = remote.strip().removesuffix(".git") + for prefix in ("https://", "http://", "ssh://", "git://"): + if remote.startswith(prefix): + remote = remote[len(prefix) :] + break + else: + remote = re.sub(r"^git@", "", remote) + parts = [part for part in remote.replace(":", "/", 1).split("/") if part] + if len(parts) >= 2: + return f"{parts[-2]}-{parts[-1]}".replace("/", "-").replace(":", "-") + if parts: + return parts[-1].replace("/", "-").replace(":", "-") + return os.path.basename(root or cwd) or "unknown" + + +@dataclass(frozen=True) +class RepoContext: + cwd: str + root: str + identity: str + app_id: str + branch: str + head_sha: str + project_id: str = "" + directory: str = "" + + +def _project_id(root: str, identity: str, app_id: str) -> str: + """The shared namespace: includes a host hash so repos with the same owner/name on different hosts stay apart.""" + if not identity.startswith("local:"): + return f"{app_id}-{hashlib.sha256(identity.encode()).hexdigest()[:10]}" + return f"local-{app_id}-{hashlib.sha256(root.encode()).hexdigest()[:10]}" + + +def _relative_directory(cwd: str, root: str) -> str: + relative = os.path.relpath(cwd, root) + return "" if relative == "." or relative.startswith("..") else relative.replace(os.sep, "/") + + +@dataclass(frozen=True) +class MemorySearchResult: + succeeded: bool + matched_count: int + already_shown_count: int + memories: list[dict[str, Any]] + + +@functools.lru_cache(maxsize=64) +def _resolve_repo_cached(cwd: str) -> RepoContext: + given_cwd = cwd + cwd = os.path.realpath(cwd) + given_root = _git(cwd, "rev-parse", "--show-toplevel") or given_cwd + root = os.path.realpath(given_root) + raw_remote = _git(root, "config", "--get", "remote.origin.url") + remote = _normalize_remote(raw_remote) + identity = remote or f"local:{root}" + app_id = _legacy_project_id(given_cwd, given_root, raw_remote, identity) + return RepoContext( + cwd=cwd, + root=root, + identity=identity, + app_id=app_id, + branch=_git(root, "branch", "--show-current") or "detached", + head_sha=_git(root, "rev-parse", "HEAD"), + project_id=_project_id(root, identity, app_id), + directory=_relative_directory(cwd, root), + ) + + +def resolve_repo(cwd: str | None) -> RepoContext: + return _resolve_repo_cached(os.path.abspath(cwd or os.getcwd())) + + +def api_key() -> str: + configured = ( + os.environ.get("MEM0_API_KEY") + or os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if configured: + return configured + try: + return (data_dir() / "api-key").read_text(encoding="utf-8").strip() + except OSError: + return "" + + +def cache_plugin_api_key() -> bool: + """Bridge host's hook-only sensitive config into plugin-owned storage.""" + configured = ( + os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if not configured: + return False + + directory = data_dir() + directory.mkdir(parents=True, exist_ok=True) + path = directory / "api-key" + temporary = directory / f"api-key.{os.getpid()}.tmp" + descriptor = os.open( + temporary, + os.O_WRONLY | os.O_CREAT | os.O_TRUNC, + 0o600, + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + handle.write(configured) + os.replace(temporary, path) + os.chmod(path, 0o600) + finally: + try: + temporary.unlink() + except FileNotFoundError: + pass + return True + + +def clear_stale_api_key_cache() -> bool: + """Drop the cached key file once every configured key source is gone.""" + configured = ( + os.environ.get("MEM0_API_KEY") + or os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if configured: + return False + path = data_dir() / "api-key" + if not path.exists(): + return False + try: + path.unlink() + except OSError: + return False + return True + + +def detached_process_kwargs(platform: str | None = None) -> dict: + """Keep a spawned worker alive after the coding agent exits, on POSIX and Windows.""" + if (platform or sys.platform) == "win32": + return { + "creationflags": subprocess.DETACHED_PROCESS + | subprocess.CREATE_NEW_PROCESS_GROUP + } + return {"start_new_session": True} + + +def _plugin_option(name: str, fallback: str = "") -> str: + return ( + os.environ.get(f"PLUGIN_OPTION_{name.upper()}") + or os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name.upper()}") + or os.environ.get(fallback) + or "" + ).strip() + + +def user_id() -> str: + return ( + _scope_value(_plugin_option("user_id", "MEM0_CODE_USER_ID")) + or _scope_value(os.environ.get("MEM0_USER_ID")) + or _scope_value(os.environ.get("MEM0_RESOLVED_USER_ID")) + or _scope_value(os.environ.get("USER")) + or _scope_value(os.environ.get("USERNAME")) + or "default" + ) + + +def data_dir() -> Path: + configured = ( + os.environ.get("MEM0_CODE_DATA_DIR") + or os.environ.get("MEM0_PLUGIN_DATA_DIR") + or os.environ.get("PLUGIN_DATA") + or os.environ.get("CLAUDE_PLUGIN_DATA") + ) + return ( + Path(configured).expanduser() if configured else Path.home() / ".mem0" / _harness_data_dir_name + ) + + +def _bool_option(name: str, fallback: str, default: bool = False) -> bool: + value = _plugin_option(name, fallback) + if not value: + return default + return value.lower() in {"1", "true", "yes", "on"} + + +def _int_option(name: str, fallback: str, default: int) -> int: + value = _plugin_option(name, fallback) + try: + return int(value) if value else default + except ValueError: + return default + + + +def _checkpoint_message(event: dict[str, Any]) -> str: + kind = event.get("kind") + payload = event.get("payload") or {} + if kind == "user_prompt": + return redact(payload.get("text", "")).strip() + if kind == "assistant_stop": + transcript_messages = payload.get("transcript_messages") or [] + if isinstance(transcript_messages, list): + text = "\n".join( + str(message.get("content") or "") + for message in transcript_messages + if isinstance(message, dict) and message.get("content") + ) + if text: + return text + return redact(payload.get("text", "")).strip() + if kind == "sidekick_stop": + return redact(payload.get("final_message", "")).strip() + return "" + + +def checkpoint_stats(events: list[dict[str, Any]]) -> tuple[int, int, int]: + """Return completed exchanges, messages, and source characters.""" + completed = sum(event.get("kind") == "assistant_stop" for event in events) + contents = [content for event in events if (content := _checkpoint_message(event))] + return completed, len(contents), sum(len(content) for content in contents) + + +def select_checkpoint_events( + events: list[dict[str, Any]], *, force: bool +) -> list[dict[str, Any]]: + """Select one ordered extraction block without splitting an exchange.""" + for index, event in enumerate(events): + if event.get("kind") != "assistant_stop": + continue + candidate = events[: index + 1] + completed, messages, source_chars = checkpoint_stats(candidate) + if ( + completed >= CHECKPOINT_EXCHANGES + or messages >= CHECKPOINT_MESSAGES + or source_chars >= CHECKPOINT_SOURCE_CHARS + ): + return candidate + return events if force else [] + + +class EvidenceStore: + def __init__(self, path: Path | None = None): + directory = data_dir() if path is None else path.parent + directory.mkdir(parents=True, exist_ok=True) + self.path = path or directory / "evidence.sqlite3" + try: + self._open() + except sqlite3.DatabaseError: + self._quarantine() + self._open() + + def _open(self) -> None: + self.conn = sqlite3.connect(self.path, timeout=10) + self.conn.row_factory = sqlite3.Row + try: + self.conn.execute("PRAGMA journal_mode=WAL") + self.conn.execute("PRAGMA busy_timeout=10000") + self._migrate() + except sqlite3.DatabaseError: + self.conn.close() + raise + + def _quarantine(self) -> None: + """Move an unreadable database aside so capture restarts cleanly.""" + stamp = int(time.time()) + for suffix in ("", "-wal", "-shm"): + source = Path(f"{self.path}{suffix}") + try: + source.replace(f"{self.path}.corrupt-{stamp}{suffix}") + except FileNotFoundError: + continue + except OSError: + try: + source.unlink() + except OSError: + pass + telemetry.record("db_quarantined") + + def close(self) -> None: + self.conn.close() + + def _migrate(self) -> None: + self.conn.executescript( + """ + CREATE TABLE IF NOT EXISTS events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + session_id TEXT NOT NULL, + created_at TEXT NOT NULL, + kind TEXT NOT NULL, + payload_json TEXT NOT NULL, + flush_id TEXT + ); + CREATE INDEX IF NOT EXISTS events_session_idx + ON events(repo_id, session_id, flush_id, id); + + CREATE TABLE IF NOT EXISTS session_scopes ( + session_id TEXT PRIMARY KEY, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + root TEXT NOT NULL, + branch TEXT NOT NULL, + head_sha TEXT NOT NULL, + created_at TEXT NOT NULL, + directory TEXT NOT NULL DEFAULT '' + ); + + CREATE TABLE IF NOT EXISTS flushes ( + packet_id TEXT PRIMARY KEY, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + session_id TEXT NOT NULL, + reason TEXT NOT NULL, + event_start INTEGER NOT NULL, + event_end INTEGER NOT NULL, + status TEXT NOT NULL, + episode_event_id TEXT, + semantic_event_id TEXT, + error TEXT, + attempts INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS retrievals ( + session_id TEXT NOT NULL, + repo_id TEXT NOT NULL, + memory_id TEXT NOT NULL, + injected_at TEXT NOT NULL, + rank INTEGER, + score REAL, + memory_text TEXT, + context_chars INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY(session_id, repo_id, memory_id) + ); + + CREATE TABLE IF NOT EXISTS operations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created_at TEXT NOT NULL, + repo_id TEXT NOT NULL, + session_id TEXT NOT NULL, + operation TEXT NOT NULL, + duration_ms REAL NOT NULL, + success INTEGER NOT NULL, + item_count INTEGER NOT NULL DEFAULT 0, + request_chars INTEGER NOT NULL DEFAULT 0, + response_chars INTEGER NOT NULL DEFAULT 0, + error TEXT + ); + + CREATE TABLE IF NOT EXISTS sidekick_runs ( + repo_id TEXT NOT NULL, + session_id TEXT NOT NULL, + agent_id TEXT NOT NULL, + agent_type TEXT NOT NULL, + started_at TEXT NOT NULL, + stopped_at TEXT, + transcript_path TEXT, + context_chars INTEGER NOT NULL DEFAULT 0, + final_message TEXT, + PRIMARY KEY(repo_id, session_id, agent_id) + ); + CREATE INDEX IF NOT EXISTS sidekick_runs_repo_idx + ON sidekick_runs(repo_id, started_at); + + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + """ + ) + # Remove the pre-0.1.1 no-tools snapshot implementation. The real coding + # sidekick is a native Claude Code agent and stores no state in this DB. + self.conn.executescript( + """ + DROP TABLE IF EXISTS sidekick_calls; + DROP TABLE IF EXISTS sidekick_snapshots; + DROP TABLE IF EXISTS sidekick_state; + DROP TABLE IF EXISTS sidekick_packets; + """ + ) + self._ensure_column("retrievals", "rank", "INTEGER") + self._ensure_column("retrievals", "score", "REAL") + self._ensure_column("retrievals", "memory_text", "TEXT") + self._ensure_column("retrievals", "context_chars", "INTEGER NOT NULL DEFAULT 0") + self._ensure_column("flushes", "attempts", "INTEGER NOT NULL DEFAULT 0") + self._ensure_column("session_scopes", "directory", "TEXT NOT NULL DEFAULT ''") + self.conn.commit() + + def _ensure_column(self, table: str, column: str, declaration: str) -> None: + columns = { + str(row["name"]) + for row in self.conn.execute(f"PRAGMA table_info({table})").fetchall() + } + if column not in columns: + self.conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {declaration}") + + def record_event( + self, + repo: RepoContext, + session_id: str, + kind: str, + payload: dict[str, Any], + ) -> int: + cursor = self.conn.execute( + """INSERT INTO events + (repo_id, app_id, session_id, created_at, kind, payload_json) + VALUES (?, ?, ?, ?, ?, ?)""", + ( + repo.identity, + repo.app_id, + session_id, + utc_now(), + kind, + json.dumps(payload, ensure_ascii=False, sort_keys=True), + ), + ) + self.conn.commit() + return int(cursor.lastrowid) + + def record_assistant_response(self, repo: RepoContext, session_id: str, message: str) -> None: + """Ignore repeated response hooks until another prompt or a different answer arrives.""" + with self.conn: + # Serialize the check and insert across concurrent Stop and SessionEnd hooks. + self.conn.execute("BEGIN IMMEDIATE") + previous = self.conn.execute( + """SELECT kind, payload_json FROM events + WHERE repo_id = ? AND session_id = ? AND kind IN ('user_prompt', 'assistant_stop') + ORDER BY id DESC LIMIT 1""", + (repo.identity, session_id), + ).fetchone() + if ( + previous is not None + and previous["kind"] == "assistant_stop" + and json.loads(previous["payload_json"]).get("text") == message + ): + return + self.record_event(repo, session_id, "assistant_stop", {"text": message}) + + def repo_for_session(self, session_id: str, cwd: str | None) -> RepoContext: + """Keep one project scope for every hook in a coding-agent session.""" + current = resolve_repo(cwd) + if session_id == "unknown-session": + return current + + with self.conn: + self.conn.execute( + """INSERT OR IGNORE INTO session_scopes + (session_id, repo_id, app_id, root, branch, head_sha, created_at, directory) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", + ( + session_id, + current.identity, + current.app_id, + current.root, + current.branch, + current.head_sha, + utc_now(), + current.directory, + ), + ) + scope = self.conn.execute( + "SELECT * FROM session_scopes WHERE session_id = ?", (session_id,) + ).fetchone() + same_git_repo = ( + current.identity == scope["repo_id"] and bool(current.head_sha) + ) + pinned = current if same_git_repo else resolve_repo(str(scope["root"])) + return RepoContext( + cwd=current.cwd, + root=pinned.root, + identity=str(scope["repo_id"]), + app_id=str(scope["app_id"]), + branch=pinned.branch, + head_sha=pinned.head_sha, + project_id=pinned.project_id, + directory=str(scope["directory"] or ""), + ) + + def prepare_flush( + self, repo: RepoContext, session_id: str, reason: str + ) -> tuple[str, list[dict[str, Any]]] | None: + with self.conn: + self.conn.execute("BEGIN IMMEDIATE") + existing = self.conn.execute( + """SELECT * FROM flushes + WHERE repo_id = ? AND session_id = ? + AND status NOT IN ('semantic-succeeded', 'explicitly-stored', 'gave-up') + ORDER BY created_at LIMIT 1""", + (repo.identity, session_id), + ).fetchone() + if existing and int(existing["attempts"] or 0) >= MAX_FLUSH_ATTEMPTS: + self.conn.execute( + "UPDATE flushes SET status = 'gave-up', updated_at = ? WHERE packet_id = ?", + (utc_now(), existing["packet_id"]), + ) + telemetry.record( + "flush", + repo=repo, + session_id=session_id, + reason=reason, + status="gave-up", + success=False, + attempts=int(existing["attempts"] or 0), + ) + existing = None + if existing: + if reason != "periodic" and existing["reason"] == "periodic": + self.conn.execute( + "UPDATE flushes SET reason = ?, updated_at = ? WHERE packet_id = ?", + (reason, utc_now(), existing["packet_id"]), + ) + existing_rows = self.conn.execute( + "SELECT * FROM events WHERE flush_id = ? ORDER BY id", + (existing["packet_id"],), + ).fetchall() + if existing_rows: + return str(existing["packet_id"]), [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in existing_rows + ] + + rows = self.conn.execute( + """SELECT * FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id""", + (repo.identity, session_id), + ).fetchall() + if not rows: + return None + + events = [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in rows + ] + events = select_checkpoint_events(events, force=reason != "periodic") + if not events: + return None + event_start, event_end = events[0]["id"], events[-1]["id"] + packet_material = f"{repo.identity}\0{session_id}\0{event_start}\0{event_end}" + packet_id = hashlib.sha256(packet_material.encode()).hexdigest()[:32] + now = utc_now() + + self.conn.execute( + """INSERT OR IGNORE INTO flushes + (packet_id, repo_id, app_id, session_id, reason, event_start, + event_end, status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, 'prepared', ?, ?)""", + ( + packet_id, + repo.identity, + repo.app_id, + session_id, + reason, + event_start, + event_end, + now, + now, + ), + ) + event_ids = [event["id"] for event in events] + placeholders = ", ".join("?" for _ in event_ids) + self.conn.execute( + f"UPDATE events SET flush_id = ? " + f"WHERE id IN ({placeholders}) AND flush_id IS NULL", + (packet_id, *event_ids), + ) + return packet_id, events + + def checkpoint_due(self, repo_id: str, session_id: str) -> bool: + if self.has_inflight_flush(repo_id, session_id): + return False + rows = self.conn.execute( + """SELECT * FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id""", + (repo_id, session_id), + ).fetchall() + events = [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in rows + ] + return bool(select_checkpoint_events(events, force=False)) + + def has_inflight_flush(self, repo_id: str, session_id: str) -> bool: + return ( + self.conn.execute( + """SELECT 1 FROM flushes + WHERE repo_id = ? AND session_id = ? + AND status IN ('prepared', 'semantic-queued') + LIMIT 1""", + (repo_id, session_id), + ).fetchone() + is not None + ) + + def flush_record(self, packet_id: str) -> dict[str, Any] | None: + row = self.conn.execute( + "SELECT * FROM flushes WHERE packet_id = ?", (packet_id,) + ).fetchone() + return dict(row) if row else None + + def has_unflushed_events(self, repo_id: str, session_id: str) -> bool: + return ( + self.conn.execute( + """SELECT 1 FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + LIMIT 1""", + (repo_id, session_id), + ).fetchone() + is not None + ) + + def unflushed_starts_with_session_start( + self, repo_id: str, session_id: str + ) -> bool: + row = self.conn.execute( + """SELECT kind FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id LIMIT 1""", + (repo_id, session_id), + ).fetchone() + return bool(row and row["kind"] == "session_start") + + def update_flush(self, packet_id: str, **fields: Any) -> None: + allowed = {"status", "episode_event_id", "semantic_event_id", "error"} + updates = {key: value for key, value in fields.items() if key in allowed} + updates["updated_at"] = utc_now() + clause = ", ".join(f"{key} = ?" for key in updates) + failed = str(fields.get("status", "")) in { + "error", + "semantic-failed", + "semantic-timeout", + "semantic-missing", + } + if failed: + clause += ", attempts = attempts + 1" + with self.conn: + self.conn.execute( + f"UPDATE flushes SET {clause} WHERE packet_id = ?", + [*updates.values(), packet_id], + ) + + def unseen( + self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]] + ) -> list[dict[str, Any]]: + seen = { + row["memory_id"] + for row in self.conn.execute( + "SELECT memory_id FROM retrievals WHERE session_id = ? AND repo_id = ?", + (session_id, repo_id), + ) + } + return [memory for memory in memories if str(memory.get("id", "")) not in seen] + + def mark_injected( + self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]] + ) -> None: + now = utc_now() + with self.conn: + for rank, memory in enumerate(memories, start=1): + memory_id = str(memory.get("id", "")) + if memory_id: + memory_text = bounded( + memory.get("memory") or memory.get("text") or "", + 4000, + ) + try: + score = float(memory["score"]) + except (KeyError, TypeError, ValueError): + score = None + self.conn.execute( + """INSERT OR IGNORE INTO retrievals + (session_id, repo_id, memory_id, injected_at, rank, + score, memory_text, context_chars) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", + ( + session_id, + repo_id, + memory_id, + now, + rank, + score, + memory_text, + len(memory_text), + ), + ) + + def injected_memories( + self, session_id: str, repo_id: str + ) -> list[dict[str, Any]]: + """Return the exact memories already supplied to the main conversation.""" + rows = self.conn.execute( + """SELECT memory_id, rank, score, memory_text + FROM retrievals + WHERE session_id = ? AND repo_id = ? + ORDER BY COALESCE(rank, 2147483647), injected_at, memory_id""", + (session_id, repo_id), + ).fetchall() + return [ + { + "id": row["memory_id"], + "memory": row["memory_text"], + "score": row["score"], + } + for row in rows + if row["memory_text"] + ] + + def start_sidekick( + self, + repo: RepoContext, + session_id: str, + agent_id: str, + agent_type: str, + context_chars: int, + ) -> bool: + """Record one native sidekick instance and whether context was first sent.""" + with self.conn: + cursor = self.conn.execute( + """INSERT OR IGNORE INTO sidekick_runs + (repo_id, session_id, agent_id, agent_type, started_at, + context_chars) + VALUES (?, ?, ?, ?, ?, ?)""", + ( + repo.identity, + session_id, + agent_id, + agent_type, + utc_now(), + context_chars, + ), + ) + return int(cursor.rowcount) > 0 + + def stop_sidekick( + self, + repo: RepoContext, + session_id: str, + agent_id: str, + agent_type: str, + transcript_path: str, + final_message: str, + ) -> str: + now = utc_now() + self.conn.execute("BEGIN IMMEDIATE") + try: + if not agent_id: + rows = self.conn.execute( + """SELECT agent_id FROM sidekick_runs + WHERE repo_id = ? AND session_id = ? AND agent_type = ? AND stopped_at IS NULL + LIMIT 2""", + (repo.identity, session_id, agent_type), + ).fetchall() + # Without a host ID, overlapping runs cannot be correlated reliably. + agent_id = rows[0]["agent_id"] if len(rows) == 1 else f"unknown-agent-{time.time_ns()}" + self.conn.execute( + """INSERT INTO sidekick_runs + (repo_id, session_id, agent_id, agent_type, started_at, + stopped_at, transcript_path, final_message) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(repo_id, session_id, agent_id) DO UPDATE SET + stopped_at = excluded.stopped_at, + transcript_path = excluded.transcript_path, + final_message = excluded.final_message""", + ( + repo.identity, + session_id, + agent_id, + agent_type, + now, + now, + bounded(transcript_path, 2000), + redact(final_message).strip(), + ), + ) + self.conn.commit() + except Exception: + self.conn.rollback() + raise + return agent_id + + def operation( + self, + repo: RepoContext, + session_id: str, + operation: str, + duration_ms: float, + success: bool, + *, + item_count: int = 0, + request_chars: int = 0, + response_chars: int = 0, + error: str = "", + ) -> None: + with self.conn: + self.conn.execute( + """INSERT INTO operations + (created_at, repo_id, session_id, operation, duration_ms, + success, item_count, request_chars, response_chars, error) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", + ( + utc_now(), + repo.identity, + session_id, + operation, + duration_ms, + int(success), + item_count, + request_chars, + response_chars, + bounded(error, 1000), + ), + ) + + def has_operation(self, repo_id: str, session_id: str, operation: str) -> bool: + row = self.conn.execute( + """SELECT 1 FROM operations + WHERE repo_id = ? AND session_id = ? AND operation = ? + LIMIT 1""", + (repo_id, session_id, operation), + ).fetchone() + return row is not None + + def has_event(self, repo_id: str, session_id: str, kind: str) -> bool: + row = self.conn.execute( + """SELECT 1 FROM events + WHERE repo_id = ? AND session_id = ? AND kind = ? + LIMIT 1""", + (repo_id, session_id, kind), + ).fetchone() + return row is not None + + def latest_event_payload( + self, repo_id: str, session_id: str, kind: str + ) -> dict[str, Any]: + row = self.conn.execute( + """SELECT payload_json FROM events + WHERE repo_id = ? AND session_id = ? AND kind = ? + ORDER BY id DESC LIMIT 1""", + (repo_id, session_id, kind), + ).fetchone() + if not row: + return {} + try: + payload = json.loads(row["payload_json"]) + except json.JSONDecodeError: + return {} + return payload if isinstance(payload, dict) else {} + + def setting(self, key: str, default: str = "") -> str: + row = self.conn.execute( + "SELECT value FROM settings WHERE key = ?", (key,) + ).fetchone() + return str(row["value"]) if row else default + + def set_setting(self, key: str, value: str) -> None: + with self.conn: + self.conn.execute( + """INSERT INTO settings(key, value, updated_at) + VALUES (?, ?, ?) + ON CONFLICT(key) DO UPDATE SET + value = excluded.value, + updated_at = excluded.updated_at""", + (key, value, utc_now()), + ) + + def is_paused(self) -> bool: + return self.setting("paused", "false").lower() in { + "1", + "true", + "yes", + "on", + } + + def forget_local_repo(self, repo_id: str) -> dict[str, int]: + tables = { + "events": "repo_id", + "session_scopes": "repo_id", + "flushes": "repo_id", + "retrievals": "repo_id", + "operations": "repo_id", + "sidekick_runs": "repo_id", + } + removed: dict[str, int] = {} + with self.conn: + for table, column in tables.items(): + cursor = self.conn.execute( + f"DELETE FROM {table} WHERE {column} = ?", (repo_id,) + ) + removed[table] = max(int(cursor.rowcount), 0) + return removed + + def status(self, repo_id: str) -> dict[str, Any]: + def count(table: str) -> int: + return int( + self.conn.execute( + f"SELECT COUNT(*) FROM {table} WHERE repo_id = ?", (repo_id,) + ).fetchone()[0] + ) + + last_operation = self.conn.execute( + """SELECT created_at, operation, duration_ms, success, item_count, error + FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""", + (repo_id,), + ).fetchone() + last_sidekick = self.conn.execute( + """SELECT session_id, agent_id, agent_type, started_at, stopped_at, + context_chars + FROM sidekick_runs WHERE repo_id = ? + ORDER BY started_at DESC LIMIT 1""", + (repo_id,), + ).fetchone() + return { + "paused": self.is_paused(), + "events": count("events"), + "flushes": count("flushes"), + "retrievals": count("retrievals"), + "sidekick_runs": count("sidekick_runs"), + "last_operation": dict(last_operation) if last_operation else None, + "last_sidekick": dict(last_sidekick) if last_sidekick else None, + } + + +def _session_id(hook_input: dict[str, Any]) -> str: + return str(hook_input.get("session_id") or "unknown-session") + + +def record_session_start(store: EvidenceStore, hook_input: dict[str, Any]) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + store.record_event( + repo, + session_id, + "session_start", + { + "source": hook_input.get("source", "startup"), + "model": bounded(hook_input.get("model", ""), 200), + "branch": repo.branch, + "head_sha": repo.head_sha, + }, + ) + telemetry.record( + "session_start", + repo=repo, + session_id=session_id, + trigger=bounded(str(hook_input.get("source", "startup")), 60), + model=bounded(hook_input.get("model", ""), 200), + api_key_configured=bool(api_key()), + is_git_repo=not repo.identity.startswith("local:"), + ) + + +def record_user_prompt( + store: EvidenceStore, hook_input: dict[str, Any] +) -> tuple[RepoContext, str, str, bool]: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + prompt = redact(hook_input.get("prompt", "")).strip() + is_first_prompt = not store.has_event(repo.identity, session_id, "user_prompt") + store.record_event(repo, session_id, "user_prompt", {"text": prompt}) + return repo, session_id, prompt, is_first_prompt + + +def _tool_result_preview(response: Any) -> str: + if isinstance(response, dict): + selected = {} + for key in ( + "stdout", + "stderr", + "output", + "content", + "error", + "filePath", + "success", + "interrupted", + ): + if key in response: + selected[key] = response[key] + response = selected or {"keys": sorted(response.keys())[:20]} + return bounded(response, MAX_RESULT_CHARS) + + +def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> dict[str, Any]: + name = str(hook_input.get("tool_name") or "unknown") + tool_input = hook_input.get("tool_input") or {} + if not isinstance(tool_input, dict): + tool_input = {} + payload: dict[str, Any] = { + "tool": name, + "failed": failed, + "duration_ms": hook_input.get("duration_ms"), + "agent_role": "sidekick" if hook_input.get("agent_id") else "main", + } + if hook_input.get("agent_id"): + payload["agent_id"] = bounded(hook_input["agent_id"], 200) + if hook_input.get("agent_type"): + payload["agent_type"] = bounded(hook_input["agent_type"], 200) + + if name in {"Read", "Write", "Edit", "MultiEdit", "NotebookEdit"}: + path = tool_input.get("file_path") or tool_input.get("notebook_path") + if path: + payload["path"] = bounded(path, 1000) + if name in {"Write", "Edit", "MultiEdit", "NotebookEdit"}: + payload["mutation_chars"] = sum( + len(str(tool_input.get(key, ""))) + for key in ("content", "new_string", "new_source", "edits") + ) + elif name == "Bash" or "command" in tool_input: + command = bounded(tool_input.get("command", ""), MAX_COMMAND_CHARS) + payload["command"] = command + payload["command_kind"] = ( + "test" + if TEST_COMMAND_RE.search(command) + else "build" + if BUILD_COMMAND_RE.search(command) + else "shell" + ) + response = ( + hook_input.get("error") if failed else hook_input.get("tool_response") + ) + payload["result_preview"] = _tool_result_preview(response) + elif name in {"Grep", "Glob", "WebSearch", "WebFetch"}: + for key in ("pattern", "path", "query", "url"): + if tool_input.get(key): + payload[key] = bounded(tool_input[key], 1000) + else: + payload["input_keys"] = sorted(tool_input.keys())[:20] + if failed: + payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS) + + if failed and "error" not in payload: + payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS) + return payload + + +def record_tool( + store: EvidenceStore, hook_input: dict[str, Any], *, failed: bool | None = False +) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + payload = tool_payload(hook_input, failed=failed) + if payload.get("path"): + payload["repo_path"] = _repo_relative_path(repo, str(payload["path"])) + store.record_event( + repo, + session_id, + "tool_failure" if failed else "tool_result", + payload, + ) + + +def record_sidekick_start( + store: EvidenceStore, hook_input: dict[str, Any], *, inject_context: bool = True +) -> str: + """Record a native sidekick and reuse the main turn's retrieved memories.""" + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200) + agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + context = combine_context( + format_context(store.injected_memories(session_id, repo.identity)) + ) + if not inject_context: + context = "" + first_start = store.start_sidekick( + repo, session_id, agent_id, agent_type, len(context) + ) + store.record_event( + repo, + session_id, + "sidekick_start", + { + "agent_id": agent_id, + "agent_type": agent_type, + "context_chars": len(context) if first_start else 0, + "worktree_root": bounded(repo.root, 2000), + }, + ) + telemetry.record( + "sidekick", + repo=repo, + session_id=session_id, + phase="start", + first_start=first_start, + context_chars=len(context) if first_start else 0, + ) + return context if first_start else "" + + +def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_id = bounded(hook_input.get("agent_id", ""), 200) + final_message = redact(hook_input.get("last_assistant_message", "")).strip() + transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000) + agent_id = store.stop_sidekick( + repo, + session_id, + agent_id, + agent_type, + transcript_path, + final_message, + ) + store.record_event( + repo, + session_id, + "sidekick_stop", + { + "agent_id": agent_id, + "agent_type": agent_type, + "transcript_path": transcript_path, + "final_message": final_message, + }, + ) + telemetry.record( + "sidekick", + repo=repo, + session_id=session_id, + phase="stop", + has_transcript=bool(transcript_path), + message_chars=len(final_message), + ) + + +def _ordered_unique(values: Iterable[str]) -> list[str]: + seen: set[str] = set() + result = [] + for value in values: + if value and value not in seen: + seen.add(value) + result.append(value) + return result + + +def _repo_relative_path(repo: RepoContext, value: str) -> str: + value = str(value or "").strip() + if not value: + return "" + try: + path = Path(value) + if path.is_absolute(): + try: + return path.resolve().relative_to(Path(repo.root).resolve()).as_posix() + except ValueError: + return "" + except (OSError, ValueError): + pass + return bounded(value, 1000) + + +def _render_command_lines(commands: list[dict[str, str]]) -> list[str]: + lines = [] + for command in commands: + line = f"- [{command['status']}/{command['kind']}] {command['command']}" + if command["result"]: + line += f" — {bounded(command['result'], 500).replace(chr(10), ' ')}" + lines.append(line) + return lines + + +def build_episode( + repo: RepoContext, + session_id: str, + packet_id: str, + events: list[dict[str, Any]], + *, + canonical_task: str = "", + task_outcome: str = "", +) -> tuple[str, dict[str, Any]]: + prompts = [ + redact(e["payload"].get("text", "")).strip() + for e in events + if e["kind"] == "user_prompt" and e["payload"].get("text") + ] + assistant_conclusions = [ + redact(e["payload"].get("text", "")).strip() + for e in events + if e["kind"] == "assistant_stop" and e["payload"].get("text") + ] + sidekick_outcomes = [ + redact(e["payload"].get("final_message", "")).strip() + for e in events + if e["kind"] == "sidekick_stop" and e["payload"].get("final_message") + ] + tools = [ + e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"} + and e["payload"].get("agent_role", "main") == "main" + ] + read_paths = _ordered_unique( + _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", ""))) + for t in tools + if t.get("tool") == "Read" + ) + modified_paths = _ordered_unique( + _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", ""))) + for t in tools + if t.get("tool") in {"Write", "Edit", "MultiEdit", "NotebookEdit"} + ) + searches = [ + {key: t[key] for key in ("tool", "pattern", "path", "query", "url") if key in t} + for t in tools + if t.get("tool") in {"Grep", "Glob", "WebSearch", "WebFetch"} + ] + commands = [ + { + "command": t.get("command", ""), + "kind": t.get("command_kind", "shell"), + "status": "unknown" if t.get("failed", False) is None else "failed" if t.get("failed") else "succeeded", + "result": t.get("result_preview", ""), + } + for t in tools + if t.get("command") + ] + + task = bounded(canonical_task or (prompts[0] if prompts else ""), 4000) + conclusion = redact(assistant_conclusions[-1] if assistant_conclusions else "").strip() + outcome = bounded(task_outcome, 2000) + + extraction_messages: list[dict[str, str]] = [] + pending_user_messages: list[dict[str, str]] = [] + if task and not prompts: + pending_user_messages.append({"role": "user", "content": task}) + for event in events: + if event["kind"] == "user_prompt" and event["payload"].get("text"): + pending_user_messages.append( + { + "role": "user", + "content": redact(event["payload"].get("text", "")).strip(), + } + ) + elif event["kind"] == "assistant_stop": + transcript_messages = event["payload"].get("transcript_messages") or [] + if isinstance(transcript_messages, list) and transcript_messages: + transcript_users = { + redact(message.get("content") or "").strip() + for message in transcript_messages + if isinstance(message, dict) and message.get("role") == "user" + } + extraction_messages.extend( + message + for message in pending_user_messages + if message["content"].strip() not in transcript_users + ) + extraction_messages.extend( + { + "role": str(message.get("role") or ""), + "content": redact(message.get("content") or "").strip(), + } + for message in transcript_messages + if isinstance(message, dict) + and message.get("role") in {"user", "assistant"} + and message.get("content") + ) + else: + extraction_messages.extend(pending_user_messages) + if event["payload"].get("text"): + extraction_messages.append( + { + "role": "assistant", + "content": redact(event["payload"].get("text", "")).strip(), + } + ) + pending_user_messages = [] + elif event["kind"] == "sidekick_stop": + pass + extraction_messages.extend(pending_user_messages) + + structured = { + "packet_id": packet_id, + "repo": repo.identity, + "app_id": repo.app_id, + "session_id": session_id, + "branch": repo.branch, + "head_sha": repo.head_sha, + "task": task, + "task_outcome": outcome, + "assistant_conclusion": conclusion, + "user_messages": prompts, + "assistant_outcomes": assistant_conclusions, + "sidekick_outcomes": sidekick_outcomes, + "extraction_messages": extraction_messages, + "files_read": read_paths[:50], + "files_modified": modified_paths[:50], + "searches": searches[-30:], + "commands": commands[-30:], + } + lines = ["Coding-session episode"] + if task: + lines.extend(["", "Task:", task]) + if modified_paths: + lines.extend( + ["", "Files modified:", *[f"- {path}" for path in modified_paths[:50]]] + ) + if read_paths: + lines.extend(["", "Files read:", *[f"- {path}" for path in read_paths[:50]]]) + if commands: + lines.append("") + lines.append("Observed commands:") + lines.extend(_render_command_lines(commands[-30:])) + if searches: + lines.extend( + [ + "", + "Observed searches:", + *[ + f"- {json.dumps(item, ensure_ascii=False, sort_keys=True)}" + for item in searches[-20:] + ], + ] + ) + if conclusion: + lines.extend(["", "Agent conclusion:", conclusion]) + if outcome: + lines.extend(["", "Task outcome:", outcome]) + lines.extend( + [ + "", + f"Provenance: repo={repo.identity}; branch={repo.branch}; head={repo.head_sha}; packet={packet_id}", + ] + ) + content = "\n".join(lines) + return bounded(content, MAX_EPISODE_CHARS), structured + + +def build_semantic_evidence(structured: dict[str, Any]) -> str: + """Format changed paths for memory extraction. + + Test and build results remain in the local evidence store for diagnostics, + but are not useful repository knowledge by default and should not steer + memory extraction toward transient verification details. + """ + modified_paths = [ + bounded(path, 500) for path in structured.get("files_modified", [])[:20] + ] + commands = structured.get("commands") or [] + if not any(command.get("status") == "failed" for command in commands): + commands = [] + + if not modified_paths and not commands: + return "" + + lines = ["Additional repository details from this session"] + if modified_paths: + lines.extend( + [ + "", + "Changed paths:", + *[f"- {path}" for path in modified_paths], + ] + ) + if commands: + lines.extend(["", "Commands run in this session:", *_render_command_lines(commands)]) + return bounded("\n".join(lines), 8000) + + +def build_extraction_messages(structured: dict[str, Any]) -> list[dict[str, str]]: + """Build the session messages sent to Mem0 for memory extraction.""" + evidence = build_semantic_evidence(structured) + messages = [ + {"role": message["role"], "content": redact(message["content"]).strip()} + for message in structured.get("extraction_messages", []) + if message.get("role") in {"user", "assistant"} and message.get("content") + ] + if evidence: + for message in reversed(messages): + if message["role"] == "assistant": + message["content"] = f"{message['content']}\n\n{evidence}" + break + else: + messages.append({"role": "assistant", "content": evidence}) + + return messages + + +def _estimated_tokens(value: str) -> int: + """Conservatively estimate tokens without adding a tokenizer dependency.""" + ascii_chars = sum(ord(char) < 128 for char in value) + return math.ceil((ascii_chars * 0.4) + (len(value) - ascii_chars)) + + +def _message_tokens(messages: list[dict[str, str]]) -> int: + return _estimated_tokens(json.dumps(messages, ensure_ascii=False)) + + +def _is_agent_assignment(message: dict[str, str]) -> bool: + return message.get("role") == "assistant" and message.get( + "content", "" + ).startswith("Subagent assignment (") + + +def _is_agent_response(message: dict[str, str]) -> bool: + return message.get("role") == "assistant" and message.get( + "content", "" + ).startswith("Subagent response (") + + +def extraction_message_batches( + messages: list[dict[str, str]], + *, + max_tokens: int = MAX_EXTRACTION_INPUT_TOKENS, +) -> list[list[dict[str, str]]]: + """Keep exchanges together when possible; split oversized messages to enforce the request budget.""" + if not messages or _message_tokens(messages) <= max_tokens: + return [messages] + + exchanges: list[list[dict[str, str]]] = [] + exchange: list[dict[str, str]] = [] + for message in messages: + if message.get("role") == "user" and exchange: + exchanges.append(exchange) + exchange = [] + exchange.append(message) + if exchange: + exchanges.append(exchange) + + units: list[list[dict[str, str]]] = [] + for exchange in exchanges: + if _message_tokens(exchange) <= max_tokens: + units.append(exchange) + continue + index = 0 + while index < len(exchange): + message = exchange[index] + if ( + _is_agent_assignment(message) + and index + 1 < len(exchange) + and _is_agent_response(exchange[index + 1]) + ): + units.append(exchange[index : index + 2]) + index += 2 + else: + units.append([message]) + index += 1 + + bounded_units: list[list[dict[str, str]]] = [] + for unit in units: + if _message_tokens(unit) <= max_tokens: + bounded_units.append(unit) + continue + for message in unit: + remaining = message["content"] + while remaining: + low, high = 0, len(remaining) + while low < high: + middle = (low + high + 1) // 2 + if _message_tokens([{**message, "content": remaining[:middle]}]) <= max_tokens: + low = middle + else: + high = middle - 1 + if low == 0: + raise ValueError("Extraction token budget cannot fit a message") + bounded_units.append([{**message, "content": remaining[:low]}]) + remaining = remaining[low:] + + batches: list[list[dict[str, str]]] = [] + batch: list[dict[str, str]] = [] + for unit in bounded_units: + candidate = [*batch, *unit] + if batch and _message_tokens(candidate) > max_tokens: + batches.append(batch) + batch = list(unit) + else: + batch = candidate + if batch: + batches.append(batch) + return batches + + +def _request_json( + url: str, key: str, payload: dict[str, Any], timeout: float +) -> tuple[dict[str, Any] | list[Any], int, int]: + raw = json.dumps(payload, ensure_ascii=False).encode() + request = urllib.request.Request( + url, + data=raw, + headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + response_raw = response.read() + parsed = json.loads(response_raw or b"{}") + return parsed, len(raw), len(response_raw) + + +def _request_json_with_network_retry( + url: str, key: str, payload: dict[str, Any], timeout: float +) -> tuple[dict[str, Any] | list[Any], int, int]: + """Retry one transient connection failure without retrying API responses.""" + try: + return _request_json(url, key, payload, timeout) + except urllib.error.HTTPError: + raise + except (urllib.error.URLError, TimeoutError, OSError): + time.sleep(0.25) + return _request_json(url, key, payload, timeout) + + +def _get_json( + url: str, key: str, timeout: float +) -> tuple[dict[str, Any] | list[Any], int]: + request = urllib.request.Request( + url, + headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + method="GET", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + response_raw = response.read() + return json.loads(response_raw or b"{}"), len(response_raw) + + +def _event_id(response: dict[str, Any] | list[Any]) -> str: + return str(response.get("event_id", "")) if isinstance(response, dict) else "" + + +def _stored_event_ids(value: Any) -> list[str]: + raw = str(value or "") + if not raw.startswith("["): + return [] + try: + parsed = json.loads(raw) + except json.JSONDecodeError: + return [] + return [str(item or "") for item in parsed] if isinstance(parsed, list) else [] + + +def _result_count(response: dict[str, Any] | list[Any]) -> int: + if isinstance(response, dict): + results = response.get("results") + return len(results) if isinstance(results, list) else 0 + return len(response) if isinstance(response, list) else 0 + + +def touch_handoff_heartbeat() -> None: + """Mark the worker's handoff file alive so recovery does not relaunch it.""" + path = os.environ.get("MEM0_CODE_HANDOFF_PATH", "") + if not path: + return + try: + os.utime(path) + except OSError: + pass + + +def _wait_for_event(api_url: str, key: str, event_id: str) -> tuple[str, int, int]: + """Wait for extraction to finish before a later task can search the store.""" + if not event_id: + return "MISSING", 0, 0 + wait_seconds = float(os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120")) + poll_seconds = max(float(os.environ.get("MEM0_CODE_EVENT_POLL_SECONDS", "1")), 0.1) + deadline = time.monotonic() + wait_seconds + response_chars = 0 + while time.monotonic() < deadline: + touch_handoff_heartbeat() + try: + response, size = _get_json( + f"{api_url}/v1/event/{event_id}/", + key, + min(10, poll_seconds + 5), + ) + except urllib.error.HTTPError as exc: + if exc.code not in {408, 429} and exc.code < 500: + raise + time.sleep(poll_seconds) + continue + except (urllib.error.URLError, TimeoutError, OSError): + # The extraction job is durable server-side. A transient polling + # failure must not discard a job that may still complete normally. + time.sleep(poll_seconds) + continue + response_chars += size + status = ( + str(response.get("status", "UNKNOWN")) + if isinstance(response, dict) + else "UNKNOWN" + ) + if status in {"SUCCEEDED", "FAILED"}: + return status, response_chars, _result_count(response) + time.sleep(poll_seconds) + return "TIMEOUT", response_chars, 0 + + +def _record_flush( + repo: RepoContext, + session_id: str, + reason: str, + status: str, + elapsed: float, + **extra: Any, +) -> None: + telemetry.record( + "flush", + repo=repo, + session_id=session_id, + reason=reason, + status=status, + success=status in {"semantic-succeeded", "nothing-to-flush"}, + duration_ms=round(elapsed, 2), + **extra, + ) + + +def flush_session( + store: EvidenceStore, hook_input: dict[str, Any], reason: str +) -> dict[str, Any]: + key = api_key() + if not key: + telemetry.record("flush", reason=reason, status="local-only", success=False) + return {"status": "local-only", "reason": "no-api-key"} + + session_id = _session_id(hook_input) + if session_id == "unknown-session": + telemetry.record("flush", reason=reason, status="no-session-id", success=False) + return {"status": "error", "reason": "no-session-id"} + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + prepared = store.prepare_flush(repo, session_id, reason) + if prepared is None: + return {"status": "nothing-to-flush"} + packet_id, events = prepared + existing_flush = store.flush_record(packet_id) or {} + + _, structured = build_episode( + repo, + session_id, + packet_id, + events, + canonical_task=bounded(hook_input.get("task", ""), 4000), + task_outcome=bounded(hook_input.get("task_outcome", ""), 2000), + ) + + metadata = {"source": _harness_source_tag} + if repo.branch and repo.branch not in {"detached", "unknown"}: + metadata["branch"] = repo.branch + if repo.head_sha: + metadata["git_sha"] = repo.head_sha + api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + add_url = f"{api_url}/v3/memories/add/" + + write_user = _scope_value(user_id()) + write_project = _scope_value(repo.project_id) + if not write_user or not _scope_value(repo.app_id) or not write_project: + telemetry.record("flush", reason=reason, status="unscoped", success=False) + return {"status": "error", "reason": "wildcard-scope"} + + body = { + "agent_id": write_project, + "user_id": write_user, + "app_id": repo.app_id, + "run_id": session_id, + "metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)}, + "agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS, + "custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS, + "custom_categories": CODING_MEMORY_CATEGORIES, + "infer": True, + } + + started = time.perf_counter() + try: + stored_events = _stored_event_ids(existing_flush.get("semantic_event_id")) + existing_event = ( + "" if stored_events else str(existing_flush.get("semantic_event_id") or "") + ) + if existing_event: + existing_status, existing_resp, existing_items = _wait_for_event( + api_url, key, existing_event + ) + if existing_status == "SUCCEEDED": + elapsed = (time.perf_counter() - started) * 1000 + store.update_flush( + packet_id, + status="semantic-succeeded", + semantic_event_id=existing_event, + error="", + ) + store.operation( + repo, + session_id, + "flush-retry", + elapsed, + True, + item_count=existing_items, + response_chars=existing_resp, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-succeeded", + elapsed, + memory_count=existing_items, + resumed=True, + ) + effective_reason = str( + (store.flush_record(packet_id) or {}).get("reason") or reason + ) + if ( + store.has_unflushed_events(repo.identity, session_id) + and not store.unflushed_starts_with_session_start( + repo.identity, session_id + ) + and ( + effective_reason != "periodic" + or store.checkpoint_due(repo.identity, session_id) + ) + ): + return flush_session(store, hook_input, effective_reason) + return { + "status": "semantic-succeeded", + "packet_id": packet_id, + "semantic_event_id": existing_event, + "semantic_status": existing_status, + "memory_count": existing_items, + "duration_ms": round(elapsed, 2), + "resumed": True, + } + if existing_status == "TIMEOUT": + elapsed = (time.perf_counter() - started) * 1000 + error = "semantic extraction event timed out" + store.update_flush(packet_id, status="semantic-timeout", error=error) + store.operation( + repo, + session_id, + "flush-retry", + elapsed, + False, + response_chars=existing_resp, + error=error, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-timeout", + elapsed, + resumed=True, + error_kind="timeout", + ) + return { + "status": "semantic-timeout", + "packet_id": packet_id, + "semantic_event_id": existing_event, + "duration_ms": round(elapsed, 2), + "resumed": True, + } + + message_batches = [ + batch + for batch in extraction_message_batches( + build_extraction_messages(structured) + ) + if batch + ] + batches = [(body, messages) for messages in message_batches] + if not batches: + store.update_flush(packet_id, status="semantic-succeeded", error="") + return {"status": "nothing-to-flush", "packet_id": packet_id} + operation_name = "flush-retry" if stored_events else "flush" + semantic_events = stored_events[: len(batches)] + semantic_events += [""] * (len(batches) - len(semantic_events)) + semantic_req = 0 + semantic_resp = 0 + for index, (body, messages) in enumerate(batches): + if semantic_events[index]: + continue + semantic_response, request_chars, response_chars = _request_json( + add_url, + key, + {**body, "messages": messages}, + 15, + ) + semantic_events[index] = _event_id(semantic_response) + semantic_req += request_chars + semantic_resp += response_chars + store.update_flush( + packet_id, + status="semantic-queued", + semantic_event_id=json.dumps(semantic_events), + ) + + semantic_event = semantic_events[-1] + semantic_status = "SUCCEEDED" + event_resp = 0 + semantic_items = 0 + failed_event = semantic_event + for index, queued_event in enumerate(semantic_events): + status, response_chars, item_count = _wait_for_event( + api_url, key, queued_event + ) + event_resp += response_chars + semantic_items += item_count + if status != "SUCCEEDED": + semantic_status = status + failed_event = queued_event + if status in {"FAILED", "MISSING"}: + semantic_events[index] = "" + store.update_flush( + packet_id, semantic_event_id=json.dumps(semantic_events) + ) + break + if semantic_status != "SUCCEEDED": + elapsed = (time.perf_counter() - started) * 1000 + error = f"semantic extraction event {semantic_status.lower()}" + store.update_flush( + packet_id, status=f"semantic-{semantic_status.lower()}", error=error + ) + store.operation( + repo, + session_id, + operation_name, + elapsed, + False, + item_count=semantic_items, + request_chars=semantic_req, + response_chars=semantic_resp + event_resp, + error=error, + ) + _record_flush( + repo, + session_id, + reason, + f"semantic-{semantic_status.lower()}", + elapsed, + memory_count=semantic_items, + batch_count=len(batches), + error_kind=telemetry.error_kind(error), + ) + return { + "status": f"semantic-{semantic_status.lower()}", + "packet_id": packet_id, + "semantic_event_id": failed_event, + "memory_count": semantic_items, + "duration_ms": round(elapsed, 2), + } + + elapsed = (time.perf_counter() - started) * 1000 + store.update_flush( + packet_id, + status="semantic-succeeded", + semantic_event_id=json.dumps(semantic_events), + error="", + ) + store.operation( + repo, + session_id, + operation_name, + elapsed, + True, + item_count=semantic_items, + request_chars=semantic_req, + response_chars=semantic_resp + event_resp, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-succeeded", + elapsed, + memory_count=semantic_items, + batch_count=len(batches), + request_chars=semantic_req, + ) + effective_reason = str( + (store.flush_record(packet_id) or {}).get("reason") or reason + ) + if ( + store.has_unflushed_events(repo.identity, session_id) + and not store.unflushed_starts_with_session_start( + repo.identity, session_id + ) + and ( + effective_reason != "periodic" + or store.checkpoint_due(repo.identity, session_id) + ) + ): + return flush_session(store, hook_input, effective_reason) + return { + "status": "semantic-succeeded", + "packet_id": packet_id, + "semantic_event_id": semantic_event, + "semantic_status": semantic_status, + "memory_count": semantic_items, + "duration_ms": round(elapsed, 2), + } + except Exception as exc: # hooks must fail open + elapsed = (time.perf_counter() - started) * 1000 + error = bounded(str(exc), 1000) + store.update_flush(packet_id, status="error", error=error) + store.operation(repo, session_id, "flush", elapsed, False, error=error) + _record_flush( + repo, + session_id, + reason, + "error", + elapsed, + error_kind=telemetry.error_kind(exc), + ) + return {"status": "error", "packet_id": packet_id, "error": error} + + +def checkpoint_session( + store: EvidenceStore, hook_input: dict[str, Any], reason: str +) -> dict[str, Any]: + """Run remote extraction at a durable boundary.""" + return flush_session(store, hook_input, reason) + + + +def search_memories( + store: EvidenceStore | None, + repo: RepoContext, + session_id: str | None, + query: str, + *, + top_k: int | None = None, + category: str | None = None, + scope: str | None = None, + run_id: str | None = None, + operation: str = "search", + timeout: float = 5, +) -> MemorySearchResult: + key = api_key() + if not key or not query.strip(): + return MemorySearchResult(False, 0, 0, []) + search_once = os.environ.get( + "MEM0_CODE_SEARCH_ONCE_PER_SESSION", "false" + ).lower() in { + "1", + "true", + "yes", + "on", + } + track_session = store is not None and bool(session_id) + if ( + search_once + and track_session + and store.has_operation(repo.identity, session_id, "search") + ): + return MemorySearchResult(False, 0, 0, []) + + result_limit = min( + max( + top_k + if top_k is not None + else _int_option("top_k", "MEM0_CODE_TOP_K", 3), + 1, + ), + 20, + ) + if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES: + raise ValueError(f"Unknown memory category: {category}") + user, project = _scope_value(user_id()), _scope_value(repo.project_id) + if not user or not project or not _scope_value(repo.app_id): + return MemorySearchResult(False, 0, 0, []) + filters = _search_filters(user, repo, resolve_search_scope(scope)) + if category: + filters = {"AND": [filters, {"categories": {"contains": category}}]} + if run_id: + filters = {"AND": [filters, {"run_id": run_id}]} + payload = { + "query": query, + "app_id": repo.app_id, + "filters": filters, + "top_k": result_limit, + "rerank": False, + "latest_only": True, + } + url = ( + os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + + "/v3/memories/search/" + ) + started = time.perf_counter() + try: + response, request_chars, response_chars = _request_json_with_network_retry( + url, key, payload, timeout + ) + memories = ( + response if isinstance(response, list) else response.get("results", []) + ) + memories = [ + memory + for memory in memories + if isinstance(memory, dict) + and (memory.get("metadata") or {}).get("record_kind") != "task_episode" + ][:result_limit] + if track_session: + returned_memories = store.unseen(session_id, repo.identity, memories) + store.mark_injected(session_id, repo.identity, returned_memories) + already_shown_count = len(memories) - len(returned_memories) + else: + returned_memories = memories + already_shown_count = 0 + elapsed = (time.perf_counter() - started) * 1000 + if track_session: + store.operation( + repo, + session_id, + operation, + elapsed, + True, + item_count=len(returned_memories), + request_chars=request_chars, + response_chars=response_chars, + ) + telemetry.record( + "search", + repo=repo, + session_id=session_id, + trigger=operation, + success=True, + duration_ms=round(elapsed, 2), + matched_count=len(memories), + returned_count=len(returned_memories), + already_shown_count=already_shown_count, + top_k=result_limit, + has_category=bool(category), + ) + return MemorySearchResult( + succeeded=True, + matched_count=len(memories), + already_shown_count=already_shown_count, + memories=returned_memories, + ) + except Exception as exc: + elapsed = (time.perf_counter() - started) * 1000 + if track_session: + store.operation(repo, session_id, operation, elapsed, False, error=str(exc)) + telemetry.record( + "search", + repo=repo, + session_id=session_id, + trigger=operation, + success=False, + duration_ms=round(elapsed, 2), + top_k=result_limit, + has_category=bool(category), + error_kind=telemetry.error_kind(exc), + ) + return MemorySearchResult(False, 0, 0, []) + + +def format_context( + memories: list[dict[str, Any]], + heading: str = "Relevant repository memories:", +) -> str: + if not memories: + return "" + limit = min( + max( + _int_option( + "max_context_chars", + "MEM0_CODE_MAX_CONTEXT_CHARS", + DEFAULT_MAX_CONTEXT_CHARS, + ), + 1000, + ), + 10000, + ) + lines = [heading] if heading else [] + for memory in memories: + text = re.sub( + r"\s+", + " ", + redact(memory.get("memory") or memory.get("text") or ""), + ) + text = text.strip() + if not text: + continue + branch = str((memory.get("metadata") or {}).get("branch") or "").strip() + branch_label = ( + f" [learnt on branch {branch}]" + if branch.casefold() not in {"", "main", "master", "unknown", "detached"} + else "" + ) + number = len(lines) if heading else len(lines) + 1 + entry = f"{number}. {text}{branch_label}" + candidate = "\n".join([*lines, entry]) + if len(candidate) <= limit: + lines.append(entry) + continue + if not lines or (heading and len(lines) == 1): + prefix = f"{number}. " + suffix = f"…{branch_label}" + available = ( + limit + - len("\n".join(lines)) + - (1 if lines else 0) + - len(prefix) + - len(suffix) + ) + if available > 0: + lines.append(prefix + text[:available].rstrip() + suffix) + break + minimum_lines = 2 if heading else 1 + return "\n".join(lines) if len(lines) >= minimum_lines else "" + + +def format_search_result(result: MemorySearchResult) -> str: + """Return only the text the coding agent needs from an explicit memory search.""" + if not result.succeeded: + return "Memory search failed." + if result.memories: + rendered = format_context(result.memories, heading="") + if rendered: + return rendered + return "No matching memories found." + + +def combine_context(*contexts: str) -> str: + """Combine memory sources under one hard budget without repeated lines.""" + seen: set[str] = set() + lines: list[str] = [] + for context in contexts: + for line in str(context or "").splitlines(): + normalized = re.sub(r"\s+", " ", line).strip().casefold() + if not normalized or normalized in seen: + continue + seen.add(normalized) + lines.append(line.rstrip()) + limit = min( + max( + _int_option( + "max_context_chars", + "MEM0_CODE_MAX_CONTEXT_CHARS", + DEFAULT_MAX_CONTEXT_CHARS, + ), + 1000, + ), + 10000, + ) + return bounded("\n".join(lines), limit) if lines else "" + + +def _scoped_memory_ids( + api_url: str, key: str, user: str, repo: RepoContext, include_project: bool +) -> list[str]: + """List this user's memory ids for this repository, plus the shared project memory when asked.""" + ids: list[str] = [] + seen: set[str] = set() + prefix = repo.app_id + _collect_memory_ids( + api_url, key, {"user_id": user}, ids, seen, + app_id_prefix=prefix, + ) + if include_project: + for project_id in _shared_project_ids(repo): + _collect_memory_ids( + api_url, key, {"agent_id": project_id}, ids, seen, + app_id_prefix=prefix, + ) + return ids + + +def _collect_memory_ids( + api_url: str, + key: str, + filters: dict[str, Any], + ids: list[str], + seen: set[str], + *, + app_id_prefix: str = "", +) -> None: + """Page through one list filter; the list endpoint returns nothing for an OR whose user branch has no memories.""" + payload = {"filters": filters} + for page in range(1, FORGET_MAX_PAGES + 1): + parsed, _, _ = _request_json( + f"{api_url}/v2/memories/?page={page}&page_size={FORGET_PAGE_SIZE}", + key, + payload, + 15, + ) + items = parsed.get("results") if isinstance(parsed, dict) else parsed + if not isinstance(items, list) or not items: + break + for item in items: + if not isinstance(item, dict): + continue + memory_id = str(item.get("id", "")) + if not memory_id or memory_id in seen: + continue + if app_id_prefix: + item_app_id = str(item.get("app_id") or "") + if item_app_id != app_id_prefix and not item_app_id.startswith(app_id_prefix + "/"): + continue + seen.add(memory_id) + ids.append(memory_id) + if len(items) < FORGET_PAGE_SIZE: + break + + +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"}, + method="DELETE", + ) + try: + with urllib.request.urlopen(request, timeout=15): + return True + except Exception: + return False + + +def forget_remote_repo( + repo: RepoContext, *, include_project_memory: bool = False +) -> dict[str, Any]: + """Delete this user's memories for this repository; project memory is shared, so only on request.""" + key = api_key() + if not key: + telemetry.record("forget", repo=repo, success=False, error_kind="no-api-key") + return {"status": "error", "error": "Mem0 API key is not configured"} + user = _scope_value(user_id()) + if not user or not _scope_value(repo.app_id) or not _scope_value(repo.project_id): + telemetry.record("forget", repo=repo, success=False, error_kind="unscoped") + return { + "status": "error", + "error": "Refusing to forget: the user or repository scope is a wildcard", + } + api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + try: + memory_ids = _scoped_memory_ids(api_url, key, user, repo, include_project_memory) + except Exception as exc: + telemetry.record( + "forget", repo=repo, success=False, error_kind=telemetry.error_kind(exc) + ) + return {"status": "error", "error": bounded(str(exc), 1000)} + deleted = sum(_delete_memory(api_url, key, memory_id) for memory_id in memory_ids) + failed = len(memory_ids) - deleted + telemetry.record("forget", repo=repo, success=not failed, item_count=deleted) + if failed: + return { + "status": "partial", + "deleted": deleted, + "failed": failed, + "error": f"{failed} of {len(memory_ids)} memories could not be deleted", + } + return {"status": "deleted", "deleted": deleted} + + +def _doctor_mem0_authentication(repo: RepoContext) -> dict[str, Any]: + """Verify the configured key with one read-only, repository-scoped search.""" + key = api_key() + if not key: + return {"ok": False, "detail": "API key missing"} + payload = { + "query": "Mem0 authentication check", + "filters": { + "AND": [ + {"user_id": user_id()}, + {"app_id": repo.app_id}, + ] + }, + "top_k": 1, + "threshold": 1.0, + "rerank": False, + } + url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + started = time.perf_counter() + try: + _request_json(f"{url}/v3/memories/search/", key, payload, 5) + except Exception as exc: + return {"ok": False, "detail": bounded(str(exc), 300)} + elapsed = (time.perf_counter() - started) * 1000 + return {"ok": True, "detail": f"connected ({elapsed:.0f} ms)"} + + +def _doctor_user_id() -> dict[str, Any]: + """Flag a configured user ID the plugin refuses, since the silent fallback surprises people.""" + configured = _plugin_option("user_id", "MEM0_CODE_USER_ID") or os.environ.get( + "MEM0_USER_ID", "" + ) + if configured and not _scope_value(configured): + return { + "ok": False, + "detail": f"configured user_id {configured!r} is a wildcard; using {user_id()!r}", + } + return {"ok": True, "detail": user_id()} + + +def doctor(cwd: str | None = None) -> dict[str, Any]: + repo = resolve_repo(cwd) + directory = data_dir() + directory.mkdir(parents=True, exist_ok=True) + checks: dict[str, dict[str, Any]] = { + "python": { + "ok": tuple(sys.version_info[:2]) >= (3, 10), + "detail": f"{sys.version_info.major}.{sys.version_info.minor}", + }, + "data_directory": { + "ok": os.access(directory, os.W_OK), + "detail": str(directory), + }, + "mem0_api_key": { + "ok": bool(api_key()), + "detail": "configured" if api_key() else "missing", + }, + "repository": { + "ok": bool(repo.identity), + "detail": repo.identity, + }, + "user_id": _doctor_user_id(), + "mem0_authentication": _doctor_mem0_authentication(repo), + } + return { + "ok": all(bool(value["ok"]) for value in checks.values()), + "plugin_version": PLUGIN_VERSION, + "repo_id": repo.identity, + "app_id": repo.app_id, + "user_id": user_id(), + "checks": checks, + } diff --git a/integrations/antigravity-plugin/core/telemetry.py b/integrations/antigravity-plugin/core/telemetry.py new file mode 100644 index 000000000..249595475 --- /dev/null +++ b/integrations/antigravity-plugin/core/telemetry.py @@ -0,0 +1,397 @@ +#!/usr/bin/env python3 +"""Anonymous usage telemetry for Mem0 agent plugins. + +Hooks run on a 3-6 second budget and fire on every tool call, so recording never +touches the network: `record` appends one JSON line to a local spool and returns. +A detached `python3 telemetry.py` drains the spool in one batched PostHog request, +started once per session and again from the flush worker that is already detached. + +Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false. + +Never sends prompts, memory text, queries, file paths, repository names, or API +keys: only event names, durations, counts, coarse outcomes, and salted hashes. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import platform +import subprocess +import sys +import time +import urllib.error +import urllib.request +import uuid +from pathlib import Path +from typing import Any + +import memory_core + +_harness: str = "generic" +_source_tag: str = "MEM0_PLUGIN" +_PRIVATE_KEYS = { + "apikey", + "authorization", + "password", + "query", + "secret", + "prompt", + "token", + "text", + "memory", + "message", + "error", + "path", + "cwd", + "userid", + "agentid", + "runid", + "repoid", + "repositoryid", + "projectid", + "appid", + "filters", +} + + +def init(harness: str = "generic", source_tag: str = "") -> None: + global _harness, _source_tag + _harness = harness + _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN" + +POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" +POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/" +POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/" +EVENT_PREFIX = "code" +SPOOL_LIMIT_BYTES = 256 * 1024 +BATCH_SIZE = 100 +SEND_TIMEOUT = 5 +CLAIM_STALE_SECONDS = 120 +CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60 + + +def is_enabled() -> bool: + """Whether telemetry is switched on for this process.""" + return os.environ.get("MEM0_TELEMETRY", "true").strip().lower() not in { + "false", + "0", + "no", + "off", + } + + +def _digest(value: str, length: int = 16) -> str: + return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length] + + +def _safe_value(value: Any) -> Any: + if isinstance(value, str): + return memory_core.redact(value) + if isinstance(value, dict): + return { + key: _safe_value(item) + for key, item in value.items() + if "".join(character for character in str(key).lower() if character.isalnum()) + not in _PRIVATE_KEYS + } + if isinstance(value, (list, tuple)): + return [_safe_value(item) for item in value] + if value is None or isinstance(value, (bool, int, float)): + return value + return memory_core.redact(value) + + +def _spool_path() -> Path: + return memory_core.data_dir() / "telemetry.jsonl" + + +def _identity_path() -> Path: + return memory_core.data_dir() / "telemetry-identity.json" + + +def _read_identity() -> dict[str, str]: + try: + value = json.loads(_identity_path().read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {} + return value if isinstance(value, dict) else {} + + +def _write_identity(identity: dict[str, str]) -> None: + path = _identity_path() + temporary = path.with_suffix(f".{os.getpid()}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + temporary.write_text(json.dumps(identity), encoding="utf-8") + temporary.replace(path) + except OSError: + try: + temporary.unlink() + except OSError: + pass + + +def anonymous_id(identity: dict[str, str] | None = None) -> str: + """Per-machine anonymous identifier, created and persisted on first use.""" + identity = _read_identity() if identity is None else identity + existing = identity.get("anonymous_id") + if existing: + return existing + created = f"code-anon-{uuid.uuid4().hex}" + identity["anonymous_id"] = created + _write_identity(identity) + return created + + +def is_first_run() -> bool: + """Whether this machine has never recorded a plugin event before.""" + return not _identity_path().exists() + + +def record( + event: str, + *, + repo: Any = None, + session_id: str | None = None, + **properties: Any, +) -> None: + """Append one event to the local spool. Never blocks and never raises.""" + if not is_enabled(): + return + try: + spool = _spool_path() + try: + if spool.stat().st_size > SPOOL_LIMIT_BYTES: + return + except OSError: + pass + properties = _safe_value(properties) + properties.update( + harness=_harness, + plugin_version=memory_core.PLUGIN_VERSION, + os=sys.platform, + python_version=platform.python_version(), + ) + if repo is not None: + properties["repo_hash"] = _digest(getattr(repo, "identity", "")) + if session_id: + properties["session_hash"] = _digest(session_id) + line = json.dumps( + { + "event": f"{EVENT_PREFIX}.{event}", + "timestamp": memory_core.utc_now(), + "properties": { + key: value for key, value in properties.items() if value is not None + }, + }, + separators=(",", ":"), + default=str, + ) + spool.parent.mkdir(parents=True, exist_ok=True) + with spool.open("a", encoding="utf-8") as handle: + handle.write(line + "\n") + except Exception: + pass + + +def error_kind(exc: BaseException | str) -> str: + """Coarse, content-free label for a failure, safe to send.""" + text = exc if isinstance(exc, str) else f"{type(exc).__name__}: {exc}" + lowered = text.lower() + if "timed out" in lowered or "timeout" in lowered: + return "timeout" + if "401" in lowered or "403" in lowered or "unauthor" in lowered or "forbidden" in lowered: + return "auth" + if "429" in lowered or "rate limit" in lowered: + return "rate-limited" + if any(code in lowered for code in ("500", "502", "503", "504")): + return "server-error" + if "400" in lowered or "422" in lowered: + return "bad-request" + if isinstance(exc, str): + return "other" + if isinstance(exc, urllib.error.URLError): + return "network" + return type(exc).__name__ + + +def spawn_flush() -> bool: + """Start the detached sender that drains the spool.""" + if not is_enabled(): + return False + try: + if not _spool_path().exists() and not any( + memory_core.data_dir().glob("telemetry-*.sending") + ): + return False + subprocess.Popen( + [sys.executable, str(Path(__file__).resolve())], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + close_fds=True, + **memory_core.detached_process_kwargs(), + ) + return True + except Exception: + return False + + +def _claim_spool() -> Path | None: + """Rename the spool aside so exactly one sender owns each batch.""" + directory = memory_core.data_dir() + claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending" + spool = _spool_path() + try: + spool.replace(claim) + return claim + except OSError: + pass + now = time.time() + for orphan in sorted(directory.glob("telemetry-*.sending")): + try: + age = now - orphan.stat().st_mtime + except OSError: + continue + if age > CLAIM_EXPIRY_SECONDS: + try: + orphan.unlink() + except OSError: + pass + continue + if age < CLAIM_STALE_SECONDS: + continue + try: + orphan.replace(claim) + return claim + except OSError: + continue + return None + + +def _resolve_email(key: str) -> str: + """Trade the API key for the account email so events join other Mem0 surfaces.""" + url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/" + request = urllib.request.Request( + url, headers={"Authorization": f"Token {key}", "Content-Type": "application/json"} + ) + try: + with urllib.request.urlopen(request, timeout=SEND_TIMEOUT) as response: + payload = json.loads(response.read().decode("utf-8")) + except Exception: + return "" + email = payload.get("user_email") if isinstance(payload, dict) else "" + return email if isinstance(email, str) else "" + + +def _post(payload: dict[str, Any], url: str) -> bool: + request = urllib.request.Request( + url, + data=json.dumps(payload, default=str).encode("utf-8"), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=SEND_TIMEOUT): + return True + except Exception: + return False + + +def resolve_distinct_id() -> tuple[str, str]: + """Return the PostHog distinct id and the anonymous id it replaced, if any.""" + identity = _read_identity() + email = identity.get("email", "") + if email: + return email, "" + key = memory_core.api_key() + if not key: + return anonymous_id(identity), "" + email = _resolve_email(key) + if not email: + return anonymous_id(identity), "" + previous = identity.get("anonymous_id", "") + identity["email"] = email + _write_identity(identity) + return email, previous + + +def flush() -> int: + """Drain claimed spools to PostHog and return the number of events sent.""" + if not is_enabled(): + return 0 + claim = _claim_spool() + if claim is None: + return 0 + try: + lines = claim.read_text(encoding="utf-8").splitlines() + except OSError: + return 0 + events = [] + for line in lines: + try: + value = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(value, dict) and value.get("event"): + events.append(value) + if not events: + try: + claim.unlink() + except OSError: + pass + return 0 + + distinct_id, aliased_anonymous_id = resolve_distinct_id() + if aliased_anonymous_id: + _post( + { + "api_key": POSTHOG_API_KEY, + "event": "$identify", + "distinct_id": distinct_id, + "properties": { + "$anon_distinct_id": aliased_anonymous_id, + "$lib": "posthog-python", + }, + }, + POSTHOG_CAPTURE_URL, + ) + + sent = 0 + for start in range(0, len(events), BATCH_SIZE): + batch = [ + { + "event": event["event"], + "distinct_id": distinct_id, + "timestamp": event.get("timestamp"), + "properties": { + "source": _source_tag, + "language": "python", + "$process_person_profile": False, + "$lib": "posthog-python", + **(event.get("properties") or {}), + }, + } + for event in events[start : start + BATCH_SIZE] + ] + if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL): + return sent + sent += len(batch) + try: + claim.unlink() + except OSError: + pass + return sent + + +def main() -> int: + flush() + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except Exception: + raise SystemExit(0) diff --git a/integrations/antigravity-plugin/hooks.json b/integrations/antigravity-plugin/hooks.json new file mode 100644 index 000000000..bc2b06f5f --- /dev/null +++ b/integrations/antigravity-plugin/hooks.json @@ -0,0 +1,18 @@ +{ + "mem0": { + "PreInvocation": [ + { "type": "command", "command": "python3 ./hooks/adapter.py PreInvocation", "timeout": 5 } + ], + "PostToolUse": [ + { + "matcher": "*", + "hooks": [ + { "type": "command", "command": "python3 ./hooks/adapter.py PostToolUse", "timeout": 3 } + ] + } + ], + "Stop": [ + { "type": "command", "command": "python3 ./hooks/adapter.py Stop", "timeout": 5 } + ] + } +} diff --git a/integrations/antigravity-plugin/hooks/adapter.py b/integrations/antigravity-plugin/hooks/adapter.py new file mode 100644 index 000000000..8c20e269b --- /dev/null +++ b/integrations/antigravity-plugin/hooks/adapter.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Translate Antigravity hooks into the shared Mem0 runtime.""" + +from __future__ import annotations + +import contextlib +import io +import json +import os +import re +import sys +from pathlib import Path + +HERE = Path(__file__).resolve() +BUNDLED_CORE = HERE.parent.parent / "core" +CORE = BUNDLED_CORE if BUNDLED_CORE.is_dir() else HERE.parents[2] / "core" / "python" +sys.path.insert(0, str(CORE)) + +import hook_runner # noqa: E402 +import telemetry # noqa: E402 +from memory_core import ( # noqa: E402 + configure_harness, + record_tool, + redact, +) + + +def _read_transcript(path: str) -> list[dict[str, str]]: + messages = [] + try: + with open(path, encoding="utf-8") as transcript: + for line in transcript: + try: + step = json.loads(line) + except json.JSONDecodeError: + continue + content = step.get("content") + if not isinstance(content, str) or step.get("status") != "DONE": + continue + if step.get("type") == "USER_INPUT": + match = re.search(r"\s*(.*?)\s*", content, re.DOTALL) + messages.append({"role": "user", "content": redact(match.group(1) if match else content).strip()}) + elif step.get("source") == "MODEL" and step.get("type") == "PLANNER_RESPONSE": + messages.append({"role": "assistant", "content": redact(content).strip()}) + except (OSError, TypeError): + pass + return messages + + +def _transcript_messages(path: str) -> tuple[str, str]: + messages = _read_transcript(path) + return tuple(next((m["content"] for m in reversed(messages) if m["role"] == role), "") + for role in ("user", "assistant")) + + +def _record_stop(store, payload): + session_id = str(payload.get("session_id") or "unknown-session") + repo = store.repo_for_session(session_id, payload.get("cwd")) + path = str(payload.get("transcript_path") or "") + messages = _read_transcript(path) + if not messages: + return hook_runner.default_record_stop(store, payload) + with store.conn: + store.conn.execute("BEGIN IMMEDIATE") + previous = store.latest_event_payload(repo.identity, session_id, "assistant_stop") + offset = previous.get("transcript_count", 0) if previous.get("transcript_path") == path else 0 + if not isinstance(offset, int) or not 0 <= offset <= len(messages): + offset = 0 + if messages[offset:]: + store.record_event(repo, session_id, "assistant_stop", { + "transcript_messages": messages[offset:], + "transcript_count": len(messages), + "transcript_path": path, + }) + return repo, session_id + + +def normalize(payload: dict) -> dict: + value = dict(payload) + value.setdefault("session_id", value.get("conversationId", "")) + workspaces = value.get("workspacePaths") or [] + cwd = workspaces[0] if workspaces else os.environ.get("MEM0_CWD", "").strip() + if cwd: + value.setdefault("cwd", cwd) + value.setdefault("transcript_path", value.get("transcriptPath", "")) + prompt, assistant = _transcript_messages(value["transcript_path"]) + if prompt: + value.setdefault("prompt", prompt) + if assistant: + value.setdefault("last_assistant_message", assistant) + tool_call = value.get("toolCall") or {} + if isinstance(tool_call, dict): + value.setdefault("tool_name", tool_call.get("name", "")) + value.setdefault("tool_input", tool_call.get("args", {})) + if value.get("error"): + value.setdefault("tool_response", value["error"]) + return value + + +def _record_failure(store, payload): + return record_tool(store, payload, failed=True) + + +def _run_shared(arguments: list[str], payload: dict) -> tuple[int, str]: + sys.argv = [sys.argv[0], *arguments] + sys.stdin = io.StringIO(json.dumps(payload)) + output = io.StringIO() + with contextlib.redirect_stdout(output): + result = hook_runner.run( + record_stop_fn=_record_stop, + extra_actions={"post-tool-failure": _record_failure}, + automatic_flush_reasons={"session-end"}, + ) + return result, output.getvalue() + + +def main() -> int: + if len(sys.argv) != 2 or sys.argv[1] not in {"PreInvocation", "PostToolUse", "Stop"}: + return 2 + event = sys.argv[1] + try: + raw = json.load(sys.stdin) + except (json.JSONDecodeError, OSError): + raw = {} + payload = normalize(raw if isinstance(raw, dict) else {}) + if not payload.get("cwd"): + output = {"injectSteps": []} if event == "PreInvocation" else {} + if event == "Stop": + output = {"decision": "allow"} + print(json.dumps(output)) + return 0 + configure_harness("antigravity", data_dir_name="antigravity-plugin", source_tag="antigravity_plugin") + telemetry.init(harness="antigravity", source_tag="ANTIGRAVITY_PLUGIN") + if event == "PreInvocation": + if payload.get("invocationNum") != 0: + print(json.dumps({"injectSteps": []})) + return 0 + _run_shared(["session-start"], payload) + result, output = _run_shared(["user-prompt"], payload) + context = "" + for line in output.splitlines(): + try: + context = json.loads(line)["hookSpecificOutput"]["additionalContext"] + except (json.JSONDecodeError, KeyError, TypeError): + continue + print(json.dumps({"injectSteps": [{"ephemeralMessage": context}] if context else []})) + return result + action = { + "PostToolUse": ["post-tool-failure" if payload.get("error") else "post-tool"], + "Stop": ["flush", "--reason", "session-end"], + }[event] + result, _ = _run_shared(action, payload) + print(json.dumps({"decision": "allow"} if event == "Stop" else {})) + return result + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except Exception as exc: + hook_runner.log_failure(exc) + print("{}") + raise SystemExit(0) from None diff --git a/integrations/antigravity-plugin/mcp_config.json b/integrations/antigravity-plugin/mcp_config.json new file mode 100644 index 000000000..cc9f44de1 --- /dev/null +++ b/integrations/antigravity-plugin/mcp_config.json @@ -0,0 +1,8 @@ +{ + "mcpServers": { + "mem0": { + "command": "python3", + "args": ["./core/mcp_server.py"] + } + } +} diff --git a/integrations/antigravity-plugin/plugin-build.json b/integrations/antigravity-plugin/plugin-build.json new file mode 100644 index 000000000..506bfeb51 --- /dev/null +++ b/integrations/antigravity-plugin/plugin-build.json @@ -0,0 +1,15 @@ +{ + "id": "mem0", + "version": "0.3.1", + "homepage": "https://docs.mem0.ai/integrations/antigravity", + "native": { + "pluginRoot": "${ANTIGRAVITY_PLUGIN_ROOT}", + "files": { + "plugin.json": "plugin.json", + "hooks.json": "hooks.json", + "mcp_config.json": "mcp_config.json", + "hooks/adapter.py": "hooks/adapter.py", + "agents/sidekick/agent.md": "agents/sidekick/agent.md" + } + } +} diff --git a/integrations/antigravity-plugin/plugin.json b/integrations/antigravity-plugin/plugin.json new file mode 100644 index 000000000..32490cc76 --- /dev/null +++ b/integrations/antigravity-plugin/plugin.json @@ -0,0 +1,5 @@ +{ + "$schema": "https://antigravity.google/schemas/v1/plugin.json", + "name": "mem0", + "description": "Cross-session memory and token savings for coding agents." +} diff --git a/integrations/antigravity-plugin/skills/forget/SKILL.md b/integrations/antigravity-plugin/skills/forget/SKILL.md new file mode 100644 index 000000000..a0c4cbe5c --- /dev/null +++ b/integrations/antigravity-plugin/skills/forget/SKILL.md @@ -0,0 +1,26 @@ +--- +name: forget +description: Delete the Mem0 memories stored for this repository and this user. Use when the user asks to forget, clear, wipe, or delete memories. +disable-model-invocation: true +--- + +# Forget this repository's memories + +This permanently deletes remote memories. Before running anything, tell the +user exactly what will be deleted: their own memories for this repository +only. The repository's project memory is shared by everyone who works in it, +so it stays unless the user explicitly asks to delete that too. + +After the user confirms, run: + +```bash +python3 "${ANTIGRAVITY_PLUGIN_ROOT}/core/memory_cli.py" --harness "antigravity" forget --remote --yes +``` + +If the user also asked to delete the repository's shared project memory, add +`--include-project-memory` and say that this removes it for every teammate. + +Report what the command output says was deleted. If the user only wants local +data cleared (evidence log, pending queue), run the same command without +`--remote`. Never pass `--yes` before the user has confirmed in this +conversation. diff --git a/integrations/antigravity-plugin/skills/pause/SKILL.md b/integrations/antigravity-plugin/skills/pause/SKILL.md new file mode 100644 index 000000000..e88f7d315 --- /dev/null +++ b/integrations/antigravity-plugin/skills/pause/SKILL.md @@ -0,0 +1,20 @@ +--- +name: pause +description: Pause Mem0 memory capture on this machine. Use when the user wants to stop memories being recorded, for example for private work or experiments. +disable-model-invocation: true +--- + +# Pause memory capture + +To pause (hooks stop capturing and sending session content; a minimal +anonymous telemetry ping still fires at session start unless +`MEM0_TELEMETRY=false`): + +```bash +python3 "${ANTIGRAVITY_PLUGIN_ROOT}/core/memory_cli.py" --harness "antigravity" pause +``` + +Confirm the new state back to the user, and remind them that already-created +memories still exist and remain searchable. Pending unsent packets are held +while paused, not expired, and are delivered after resuming. To turn capture +back on, use `/mem0:resume`. diff --git a/integrations/antigravity-plugin/skills/remember/SKILL.md b/integrations/antigravity-plugin/skills/remember/SKILL.md new file mode 100644 index 000000000..7be5fc9be --- /dev/null +++ b/integrations/antigravity-plugin/skills/remember/SKILL.md @@ -0,0 +1,21 @@ +--- +name: remember +description: Acknowledge a "remember this" request and make sure it is captured well. Use when the user explicitly asks to remember, note, or save something for future sessions. +disable-model-invocation: true +--- + +# Remember something for future sessions + +Mem0 creates memories from the session automatically — there is no separate +write command. When the user asks to remember something: + +1. Restate the fact clearly and completely in your reply, in one or two + sentences, including any names, values, or paths it depends on. Your visible + reply is what memory extraction reads, so a precise restatement is what gets + remembered. +2. Tell the user it will be saved with this session's memories when the session + ends or compacts, and that it will surface in future sessions in this + repository (they can check later with /mem0:search). + +Do not invent a storage confirmation or a memory ID — creation happens in the +background after the session. diff --git a/integrations/antigravity-plugin/skills/resume/SKILL.md b/integrations/antigravity-plugin/skills/resume/SKILL.md new file mode 100644 index 000000000..52a88a38d --- /dev/null +++ b/integrations/antigravity-plugin/skills/resume/SKILL.md @@ -0,0 +1,19 @@ +--- +name: resume +description: Resume Mem0 memory capture after it was paused with /mem0:pause. +disable-model-invocation: true +--- + +# Resume memory capture + +Resume memory capture for this machine. + +Run: + +```bash +python3 "${ANTIGRAVITY_PLUGIN_ROOT}/core/memory_cli.py" --harness "antigravity" resume +``` + +Confirm to the user that capture is active again. New sessions record evidence and +create memories as normal; nothing that happened while paused is retroactively +captured. diff --git a/integrations/antigravity-plugin/skills/search/SKILL.md b/integrations/antigravity-plugin/skills/search/SKILL.md new file mode 100644 index 000000000..7a6af05fa --- /dev/null +++ b/integrations/antigravity-plugin/skills/search/SKILL.md @@ -0,0 +1,28 @@ +--- +name: search +description: Search memories from earlier Antigravity 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. +argument-hint: "[question] [--top-k number] [--category category-name] [--scope repo|dir|mine] [--run-id session-id]" +disable-model-invocation: true +--- + +# Search memories + +Call `search_memories` with the user's question. Treat `--top-k`, `--category`, +`--scope`, and `--run-id` as tool arguments instead of including them in the +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. + +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 +monorepo), `mine` for your own preferences alone. + +Pass `run_id` with any scope to retrieve memories saved in a specific coding-agent +session. Omit `run_id` to search across sessions. It filters the memories returned; +it does not identify the session making the search request. Use a known session ID, +never invent one. Return the tool's result directly. diff --git a/integrations/antigravity-plugin/skills/status/SKILL.md b/integrations/antigravity-plugin/skills/status/SKILL.md new file mode 100644 index 000000000..d417e4a40 --- /dev/null +++ b/integrations/antigravity-plugin/skills/status/SKILL.md @@ -0,0 +1,23 @@ +--- +name: status +description: Show whether Mem0 memory is working in this repository, covering configuration, capture state, pending flushes, and whether the Mem0 API key is valid. Use when the user asks whether memory is on, why a memory is missing, or anything looks broken. +disable-model-invocation: false +--- + +# Memory status + +Run both commands and report the combined result in plain language: + +```bash +python3 "${ANTIGRAVITY_PLUGIN_ROOT}/core/memory_cli.py" --harness "antigravity" status --json +python3 "${ANTIGRAVITY_PLUGIN_ROOT}/core/memory_cli.py" --harness "antigravity" doctor +``` + +Summarize, using only fields the JSON actually reports: whether capture is +active or paused, the user ID and repository scope (`repo_id`), whether an +API key is configured, the event/flush/retrieval counts (`flushes` is the +number of completed flushes, not a pending count), and the doctor check +results. If doctor reports an authentication failure (401 / invalid key), say +clearly that the Mem0 API key is invalid or expired and that memories are NOT +being created. Never report an auth failure as "no memories found". Suggest +reinstalling with `--config api_key=...` in that case. diff --git a/integrations/antigravity-plugin/tests/test_antigravity.py b/integrations/antigravity-plugin/tests/test_antigravity.py new file mode 100644 index 000000000..531a7b181 --- /dev/null +++ b/integrations/antigravity-plugin/tests/test_antigravity.py @@ -0,0 +1,140 @@ +from __future__ import annotations + +import importlib.util +import io +import json +import sys +from pathlib import Path + +HOST = Path(__file__).resolve().parents[1] +CORE_ROOT = HOST.parent / "agent-plugin-core" +sys.path.insert(0, str(CORE_ROOT)) + +from build.build import build # noqa: E402 + +SPEC = importlib.util.spec_from_file_location("antigravity_adapter", HOST / "hooks" / "adapter.py") +assert SPEC and SPEC.loader +adapter = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(adapter) + + +def test_normalizes_antigravity_camel_case_payload(tmp_path: Path) -> None: + transcript = tmp_path / "transcript.jsonl" + transcript.write_text( + "\n".join( + [ + json.dumps( + { + "source": "USER_EXPLICIT", + "type": "USER_INPUT", + "status": "DONE", + "content": "\nremember the parser\n", + } + ), + json.dumps( + { + "source": "MODEL", + "type": "PLANNER_RESPONSE", + "status": "DONE", + "content": "The parser is fixed.", + } + ), + ] + ), + encoding="utf-8", + ) + value = adapter.normalize( + { + "conversationId": "conversation-1", + "workspacePaths": ["/repo"], + "transcriptPath": str(transcript), + "toolCall": {"name": "run_command", "args": {"CommandLine": "pytest"}}, + "error": "failed", + } + ) + + assert value["session_id"] == "conversation-1" + assert value["cwd"] == "/repo" + assert value["transcript_path"] == str(transcript) + assert value["prompt"] == "remember the parser" + assert value["last_assistant_message"] == "The parser is fixed." + assert value["tool_name"] == "run_command" + assert value["tool_input"] == {"CommandLine": "pytest"} + assert value["tool_response"] == "failed" + + +def test_uses_explicit_cwd_when_antigravity_omits_workspaces(monkeypatch) -> None: + monkeypatch.setenv("MEM0_CWD", "/repo") + + value = adapter.normalize({"workspacePaths": []}) + + assert value["cwd"] == "/repo" + + +def test_skips_capture_when_workspace_is_unknown(monkeypatch, capsys) -> None: + monkeypatch.delenv("MEM0_CWD", raising=False) + + def run_shared(*_): + raise AssertionError("shared runtime should not run") + + monkeypatch.setattr(adapter, "_run_shared", run_shared) + monkeypatch.setattr(sys, "argv", ["adapter.py", "PostToolUse"]) + monkeypatch.setattr(sys, "stdin", io.StringIO('{"workspacePaths": []}')) + + assert adapter.main() == 0 + assert json.loads(capsys.readouterr().out) == {} + + +def test_pre_invocation_translates_shared_recall_to_ephemeral_message(monkeypatch, capsys) -> None: + calls = [] + + def run_shared(arguments, payload): + calls.append(arguments) + if arguments == ["user-prompt"]: + return 0, json.dumps( + {"hookSpecificOutput": {"additionalContext": "Earlier repository context."}} + ) + return 0, "" + + monkeypatch.setattr(adapter, "_run_shared", run_shared) + monkeypatch.setattr(sys, "argv", ["adapter.py", "PreInvocation"]) + monkeypatch.setattr(sys, "stdin", io.StringIO('{"invocationNum": 0, "workspacePaths": ["/repo"]}')) + + assert adapter.main() == 0 + assert calls == [["session-start"], ["user-prompt"]] + assert json.loads(capsys.readouterr().out) == { + "injectSteps": [{"ephemeralMessage": "Earlier repository context."}] + } + + +def test_native_antigravity_bundle_uses_supported_events(tmp_path: Path) -> None: + root = build("antigravity", "native", tmp_path / "antigravity") + + manifest = json.loads((root / "plugin.json").read_text(encoding="utf-8")) + hooks = json.loads((root / "hooks.json").read_text(encoding="utf-8"))["mem0"] + assert manifest["$schema"] == "https://antigravity.google/schemas/v1/plugin.json" + assert set(hooks) == {"PreInvocation", "PostToolUse", "Stop"} + assert (root / "mcp_config.json").is_file() + assert (root / "agents" / "sidekick" / "agent.md").is_file() + assert not any(path.is_symlink() for path in root.rglob("*")) + + +def test_stop_captures_later_prompts_once(tmp_path): + transcript = tmp_path / "transcript.jsonl" + store = adapter.hook_runner.EvidenceStore(tmp_path / "evidence.sqlite3") + payload = {"session_id": "s1", "cwd": str(tmp_path), "transcript_path": str(transcript)} + turns = [] + try: + for prompt, answer in [("First question", "First answer"), ("Next question", "Next answer")]: + turns.extend([ + {"type": "USER_INPUT", "status": "DONE", "content": prompt}, + {"type": "PLANNER_RESPONSE", "source": "MODEL", "status": "DONE", "content": answer}, + ]) + transcript.write_text(''.join(json.dumps(row) + '\n' for row in turns)) + adapter._record_stop(store, payload) + adapter._record_stop(store, payload) + rows = store.conn.execute("SELECT payload_json FROM events WHERE kind = 'assistant_stop' ORDER BY id").fetchall() + messages = [message for row in rows for message in json.loads(row[0])["transcript_messages"]] + assert [m["content"] for m in messages] == ["First question", "First answer", "Next question", "Next answer"] + finally: + store.close() diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index 3fd2ceb02..6f214cc14 100644 --- a/integrations/claude-code-plugin/.claude-plugin/plugin.json +++ b/integrations/claude-code-plugin/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "mem0", - "version": "0.3.0", + "version": "0.3.1", "description": "Cross-session memory and token savings for coding agents.", "author": { "name": "Mem0" diff --git a/integrations/claude-code-plugin/.gitignore b/integrations/claude-code-plugin/.gitignore deleted file mode 100644 index 7f1a2fd19..000000000 --- a/integrations/claude-code-plugin/.gitignore +++ /dev/null @@ -1,11 +0,0 @@ -__pycache__/ -*.py[cod] -.pytest_cache/ -.ruff_cache/ -.venv/ -*.sqlite3 -*.sqlite3-shm -*.sqlite3-wal -flush-worker.log -plugin-errors.log -pending/ diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 87c535502..ae80910fc 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -34,10 +34,11 @@ To remove: claude plugin uninstall mem0@mem0-plugins ``` -For local development, load the current checkout directly: +For local development, verify and load the self-contained plugin directory: ```bash -claude --plugin-dir . +python3 integrations/agent-plugin-core/build/build.py claude-code --kind native --check +claude --plugin-dir integrations/claude-code-plugin ``` ## How it works @@ -104,7 +105,11 @@ Categories for `--category`: `project_knowledge`, `decisions_and_constraints`, ` | `dir` | Project memory from the current directory (and children), plus your preferences | | `mine` | Your personal preferences only | -Set the default with the `search_scope` setting or `MEM0_CODE_SEARCH_SCOPE`. Pass `--run-id ` to see only what one specific session recorded. +Set the default with the `search_scope` setting or `MEM0_CODE_SEARCH_SCOPE`. Search spans earlier sessions without a session ID; `run_id` remains internal metadata. + +New Git repository memories use a hash of the remote identity in `agent_id`. Searches also include the previous unhashed ID under the same repository `app_id`, so shared memories remain available after upgrading. Older IDs retain their original limitation: matching owner/repository names on different Git hosts share that legacy namespace. Local folders keep their path-based namespaces. + +Explicit shared-memory deletion with `--include-project-memory` covers both repository IDs. Default deletion preserves shared memories. ## Settings @@ -181,10 +186,10 @@ Breaking update. Memories carry over, most local config does not. ## Development checks -Run from `integrations/claude-code-plugin/`: +Run from the repository root: ```bash -python3 -m pytest tests -q -python3 -m ruff check . -claude plugin validate --strict . +python3 -m pytest integrations/claude-code-plugin/tests -q --ignore=integrations/claude-code-plugin/tests/integration +python3 -m ruff check integrations/agent-plugin-core/python integrations/claude-code-plugin +claude plugin validate --strict integrations/claude-code-plugin ``` diff --git a/integrations/claude-code-plugin/adapters/claude/hook.py b/integrations/claude-code-plugin/adapters/claude/hook.py index 1fcab1177..278cd190d 100644 --- a/integrations/claude-code-plugin/adapters/claude/hook.py +++ b/integrations/claude-code-plugin/adapters/claude/hook.py @@ -3,367 +3,52 @@ from __future__ import annotations -import argparse -import hashlib -import json -import os -import subprocess import sys -import time -import uuid from pathlib import Path -sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "core")) +_here = Path(__file__).resolve() +_bundled_core = _here.parents[2] / "core" +_core_dir = _bundled_core if (_bundled_core / "memory_core.py").is_file() else _bundled_core / "python" +sys.path.insert(0, str(_core_dir)) +sys.path.insert(0, str(_here.parent)) -import telemetry -from memory_core import ( - EvidenceStore, - api_key, - cache_plugin_api_key, - checkpoint_session, - clear_stale_api_key_cache, - data_dir, - detached_process_kwargs, - format_context, - record_session_start, +import telemetry # noqa: E402 +from memory_core import ( # noqa: E402 + configure_harness, record_sidekick_start, record_sidekick_stop, - record_stop, record_tool, - record_user_prompt, - search_memories, ) +from transcript import record_stop # noqa: E402 +import hook_runner # noqa: E402 + +configure_harness("claude-code", data_dir_name="claude-code-plugin", source_tag="claude_code_plugin") +telemetry.init(harness="claude-code", source_tag="CLAUDE_CODE_PLUGIN") -STALE_RUNNING_SECONDS = 300 -PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60 -PENDING_LAUNCH_LIMIT = 5 +def _sidekick_start(store, hook_input): + context = record_sidekick_start(store, hook_input) + if context: + return { + "hookSpecificOutput": { + "hookEventName": "SubagentStart", + "additionalContext": context, + }, + } -def read_hook_input() -> dict: - try: - value = json.load(sys.stdin) - return value if isinstance(value, dict) else {} - except (json.JSONDecodeError, OSError): - return {} - - -def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict: - """Search once before Claude handles the first prompt in a session.""" - repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input) - if not is_first_prompt: - return {} - try: - minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20")) - except ValueError: - minimum_query_chars = 20 - if len(prompt.strip()) < max(minimum_query_chars, 1): - return {} - result = search_memories( - store, - repo, - session_id, - prompt, - top_k=5, - operation="first-prompt-search", - timeout=2, - ) - if not result.memories: - return {} - context = format_context( - result.memories, - "Mem0 found these relevant memories from earlier work in this repository:", - ) - telemetry.record( - "context_injected", - repo=repo, - session_id=session_id, - trigger="first-prompt", - memory_count=len(result.memories), - context_chars=len(context), - prompt_chars=len(prompt), - ) - return { - "hookSpecificOutput": { - "hookEventName": "UserPromptSubmit", - "additionalContext": context, - }, - } - - -def _launch_handoff(handoff_path: Path) -> bool: - running_path = handoff_path.with_suffix(".running") - try: - handoff_path.replace(running_path) - except OSError: - return False - worker = Path(__file__).resolve().parents[2] / "core" / "flush_worker.py" - log_path = data_dir() / "flush-worker.log" - log_handle = open(log_path, "a", encoding="utf-8") - try: - subprocess.Popen( - [sys.executable, str(worker), str(running_path)], - stdin=subprocess.DEVNULL, - stdout=log_handle, - stderr=log_handle, - close_fds=True, - **detached_process_kwargs(), - ) - finally: - log_handle.close() - return True - - -def recover_pending_handoffs() -> int: - pending_dir = data_dir() / "pending" - pending_dir.mkdir(parents=True, exist_ok=True) - now = time.time() - for running in pending_dir.glob("*.running"): - try: - if now - running.stat().st_mtime > STALE_RUNNING_SECONDS: - running.replace(running.with_suffix(".json")) - except OSError: - continue - recoverable = [] - for handoff in pending_dir.glob("*.json"): - try: - age = now - handoff.stat().st_mtime - except OSError: - continue - if age > PENDING_EXPIRY_SECONDS: - handoff.unlink(missing_ok=True) - continue - recoverable.append((age, handoff)) - recoverable.sort(key=lambda item: item[0], reverse=True) - launched = 0 - for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]: - launched += int(_launch_handoff(handoff)) - return launched - - -def refresh_pending_handoffs() -> None: - """Hold unsent packets while paused instead of letting them expire.""" - pending_dir = data_dir() / "pending" - if not pending_dir.is_dir(): - return - for pattern in ("*.json", "*.running"): - for handoff in pending_dir.glob(pattern): - try: - os.utime(handoff) - except OSError: - continue - - -def hand_off_flush( - hook_input: dict, reason: str, *, wait_for_inflight: bool = False -) -> None: - """Persist hook input and detach delivery from Claude's shutdown lifecycle.""" - pending_dir = data_dir() / "pending" - pending_dir.mkdir(parents=True, exist_ok=True) - material = ( - f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}" - ) - digest = hashlib.sha256(material.encode()).hexdigest()[:24] - handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json" - temporary_path = handoff_path.with_suffix(".tmp") - temporary_path.write_text( - json.dumps( - { - "hook_input": hook_input, - "reason": reason, - "wait_for_inflight": wait_for_inflight, - } - ), - encoding="utf-8", - ) - temporary_path.replace(handoff_path) - _launch_handoff(handoff_path) - - -def automatic_flush_enabled() -> bool: - return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in { - "1", - "true", - "yes", - "on", - } - - -def schedule_periodic_checkpoint( - store: EvidenceStore, - hook_input: dict, - repo, - session_id: str, -) -> bool: - """Start one background extraction when a complete block is ready.""" - if ( - not automatic_flush_enabled() - or not api_key() - or not store.checkpoint_due(repo.identity, session_id) - ): - return False - if store.prepare_flush(repo, session_id, "periodic") is None: - return False - hand_off_flush(hook_input, "periodic") - return True - - -DEFAULT_IDLE_FLUSH_SECONDS = 300 - - -def _idle_flush_seconds() -> int: - try: - return max( - int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))), - 0, - ) - except ValueError: - return DEFAULT_IDLE_FLUSH_SECONDS - - -def schedule_idle_flush( - store: EvidenceStore, - hook_input: dict, - repo, - session_id: str, -) -> bool: - """Launch a delayed background flush for sessions that may never end.""" - delay = _idle_flush_seconds() - if delay <= 0 or not automatic_flush_enabled() or not api_key(): - return False - if store.has_inflight_flush(repo.identity, session_id): - return False - if not store.has_unflushed_events(repo.identity, session_id): - return False - pending_dir = data_dir() / "pending" - pending_dir.mkdir(parents=True, exist_ok=True) - material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}" - digest = hashlib.sha256(material.encode()).hexdigest()[:24] - for old in pending_dir.glob(f"idle-{digest}*"): - old.unlink(missing_ok=True) - handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json" - temporary_path = handoff_path.with_suffix(".tmp") - temporary_path.write_text( - json.dumps({ - "hook_input": hook_input, - "reason": "idle", - "delay_seconds": delay, - }), - encoding="utf-8", - ) - temporary_path.replace(handoff_path) - _launch_handoff(handoff_path) - return True - - -def log_failure(exc: Exception) -> None: - try: - log_path = data_dir() / "plugin-errors.log" - with log_path.open("a", encoding="utf-8") as handle: - handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n") - except OSError: - pass - - -def main() -> int: - parser = argparse.ArgumentParser() - parser.add_argument( - "action", - choices=[ - "session-start", - "user-prompt", - "post-tool", - "post-tool-failure", - "sidekick-start", - "sidekick-stop", - "stop", - "flush", - ], - ) - parser.add_argument("--reason", default="manual") - parser.add_argument("--plugin-data-dir", default="") - args = parser.parse_args() - if args.plugin_data_dir: - os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir - cache_plugin_api_key() - if args.action == "session-start": - clear_stale_api_key_cache() - hook_input = read_hook_input() - store = EvidenceStore() - try: - if store.is_paused(): - if args.action == "session-start": - refresh_pending_handoffs() - telemetry.record("session_start", paused=True) - telemetry.spawn_flush() - return 0 - if args.action == "session-start": - if telemetry.is_first_run(): - telemetry.record("install") - recovered = recover_pending_handoffs() - record_session_start(store, hook_input) - if recovered: - telemetry.record("handoff_recovered", count=recovered) - telemetry.spawn_flush() - elif args.action == "user-prompt": - output = first_prompt_memory_output(store, hook_input) - if output: - print(json.dumps(output)) - elif args.action == "post-tool": - record_tool(store, hook_input) - elif args.action == "post-tool-failure": - record_tool(store, hook_input, failed=True) - elif args.action == "sidekick-start": - context = record_sidekick_start(store, hook_input) - if context: - print( - json.dumps( - { - "hookSpecificOutput": { - "hookEventName": "SubagentStart", - "additionalContext": context, - } - } - ) - ) - elif args.action == "sidekick-stop": - record_sidekick_stop(store, hook_input) - elif args.action == "stop": - repo, session_id = record_stop(store, hook_input) - if not schedule_periodic_checkpoint(store, hook_input, repo, session_id): - schedule_idle_flush(store, hook_input, repo, session_id) - elif args.action == "flush": - automatic = args.reason in {"session-end", "pre-compact"} - if automatic and not automatic_flush_enabled(): - return 0 - if args.reason == "session-end": - # In print mode, SessionEnd can arrive before the Stop hook has - # recorded Claude's final response. Read any remaining visible - # transcript messages before preparing the final extraction. - record_stop(store, hook_input) - if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1": - print(json.dumps(checkpoint_session(store, hook_input, args.reason))) - else: - session_id = str(hook_input.get("session_id") or "unknown-session") - repo = store.repo_for_session(session_id, hook_input.get("cwd")) - already_running = store.has_inflight_flush(repo.identity, session_id) - if already_running and args.reason == "session-end": - hand_off_flush( - hook_input, args.reason, wait_for_inflight=True - ) - elif not already_running and store.prepare_flush( - repo, session_id, args.reason - ) is not None: - hand_off_flush(hook_input, args.reason) - finally: - store.close() - return 0 +def _sidekick_stop(store, hook_input): + record_sidekick_stop(store, hook_input) if __name__ == "__main__": - try: - raise SystemExit(main()) - except Exception as exc: - # Memory must never prevent the coding agent from continuing. - log_failure(exc) - raise SystemExit(0) + hook_runner.entry_point( + record_stop_fn=record_stop, + extra_actions={ + "post-tool-failure": lambda s, h: record_tool(s, h, failed=True), + "sidekick-start": _sidekick_start, + "sidekick-stop": _sidekick_stop, + }, + data_dir_env="MEM0_CODE_DATA_DIR", + automatic_flush_reasons={"session-end", "pre-compact"}, + ) diff --git a/integrations/claude-code-plugin/adapters/claude/transcript.py b/integrations/claude-code-plugin/adapters/claude/transcript.py new file mode 100644 index 000000000..1d55ccb96 --- /dev/null +++ b/integrations/claude-code-plugin/adapters/claude/transcript.py @@ -0,0 +1,362 @@ +"""Claude Code transcript parsing for Mem0 memory extraction.""" + +from __future__ import annotations + +import html +import json +import re +import sys +from pathlib import Path +from typing import Any + +_here = Path(__file__).resolve() +sys.path.insert(0, str(_here.parents[2] / "core" / "python")) + +from memory_core import ( # noqa: E402 + EvidenceStore, + RepoContext, + _session_id, + redact, +) + + +def _message_content_text(content: Any) -> str: + """Return visible text from one Claude transcript message.""" + if isinstance(content, str): + return redact(content).strip() + if not isinstance(content, list): + return "" + parts = [] + for block in content: + if not isinstance(block, dict) or block.get("type") != "text": + continue + text = redact(block.get("text", "")).strip() + if text: + parts.append(text) + return "\n\n".join(parts) + + +def _transcript_rows( + path: str, offset: int = 0 +) -> tuple[list[dict[str, Any]], int, bool]: + """Parse transcript rows from a byte offset, returning rows, end offset, and whether the offset was honored.""" + if not path: + return [], 0, False + rows = [] + try: + resolved = Path(path).expanduser() + if not 0 <= offset <= resolved.stat().st_size: + offset = 0 + end = offset + with resolved.open("rb") as handle: + handle.seek(offset) + for line in handle: + if not line.endswith(b"\n"): + break + end += len(line) + try: + row = json.loads(line.decode("utf-8", errors="replace")) + except json.JSONDecodeError: + continue + if isinstance(row, dict) and row.get("uuid"): + rows.append(row) + except OSError: + return [], offset, False + return rows, end, offset > 0 + + +def _active_transcript_chain( + rows: list[dict[str, Any]], session_id: str +) -> list[dict[str, Any]]: + """Follow the current Claude conversation branch from its latest record.""" + by_uuid = {str(row["uuid"]): row for row in rows if row.get("uuid")} + leaf = next( + ( + row + for row in reversed(rows) + if not row.get("isSidechain") + and str(row.get("sessionId") or "") == session_id + ), + None, + ) + if leaf is None: + return [] + + chain = [] + seen = set() + current = leaf + while current is not None: + uuid = str(current.get("uuid") or "") + if not uuid or uuid in seen: + break + seen.add(uuid) + chain.append(current) + current = by_uuid.get(str(current.get("parentUuid") or "")) + chain.reverse() + return chain + + +def _human_prompt_text(row: dict[str, Any]) -> str: + if row.get("type") != "user": + return "" + origin = row.get("origin") or {} + if isinstance(origin, dict) and origin.get("kind") not in {None, "human"}: + return "" + message = row.get("message") or {} + content = message.get("content") if isinstance(message, dict) else None + if not isinstance(content, str): + return "" + text = redact(content).strip() + if text.startswith(""): + text = text.removeprefix("").strip() + ignored_prefixes = ( + "", + "", + "", + "", + "", + "", + ) + return "" if text.startswith(ignored_prefixes) else text + + +def _xml_value(text: str, tag: str) -> str: + match = re.search(fr"<{tag}>(.*?)", text, re.DOTALL) + return html.unescape(match.group(1).strip()) if match else "" + + +def _agent_assignment(tool_input: dict[str, Any]) -> str: + prompt = redact(tool_input.get("prompt", "")).strip() + if not prompt: + return "" + agent_type = redact(tool_input.get("subagent_type", "agent")).strip() or "agent" + description = redact(tool_input.get("description", "")).strip() + heading = f"Subagent assignment ({agent_type}" + if description: + heading += f": {description}" + return f"{heading}):\n{prompt}" + + +def _agent_response(tool_input: dict[str, Any], result: str) -> str: + result = redact(result).strip() + if not result or result.startswith("Async agent launched successfully."): + return "" + agent_type = redact(tool_input.get("subagent_type", "agent")).strip() or "agent" + description = redact(tool_input.get("description", "")).strip() + heading = f"Subagent response ({agent_type}" + if description: + heading += f": {description}" + return f"{heading}):\n{result}" + + +def _tool_result_text(block: dict[str, Any]) -> str: + return _message_content_text(block.get("content")) + + +def transcript_extraction_messages( + transcript_path: str, + session_id: str, + *, + previous_leaf_uuid: str = "", + prompt_hint: str = "", + fallback_assistant_message: str = "", + label_final_response: bool = False, + start_offset: int = 0, +) -> tuple[list[dict[str, str]], str, int]: + """Read the meaningful part of the current Claude exchange.""" + rows, end_offset, resumed = _transcript_rows(transcript_path, start_offset) + chain = _active_transcript_chain(rows, session_id) + if not chain: + if resumed: + return [], previous_leaf_uuid, end_offset + fallback = redact(fallback_assistant_message).strip() + return ( + ([{"role": "assistant", "content": f"Main Claude response:\n{fallback}"}] + if fallback + else []), + "", + end_offset, + ) + + leaf_uuid = str(chain[-1].get("uuid") or "") + if previous_leaf_uuid and leaf_uuid == previous_leaf_uuid: + return [], leaf_uuid, end_offset + start = 0 + if previous_leaf_uuid: + for index, row in enumerate(chain): + if str(row.get("uuid") or "") == previous_leaf_uuid: + start = index + 1 + break + else: + previous_leaf_uuid = "" + if not previous_leaf_uuid and not resumed: + prompt_hint = redact(prompt_hint).strip() + candidates = [ + index + for index, row in enumerate(chain) + if _human_prompt_text(row) + and ( + not prompt_hint + or _human_prompt_text(row) == prompt_hint + ) + ] + task_notifications = [ + index + for index, row in enumerate(chain) + if isinstance((row.get("message") or {}).get("content"), str) + and (row.get("message") or {})["content"].startswith("") + ] + if candidates: + start = candidates[-1] + elif task_notifications: + start = task_notifications[-1] + + tool_uses: dict[str, tuple[str, dict[str, Any]]] = {} + for row in chain: + message = row.get("message") or {} + content = message.get("content") if isinstance(message, dict) else None + if not isinstance(content, list): + continue + for block in content: + if not isinstance(block, dict) or block.get("type") != "tool_use": + continue + tool_id = str(block.get("id") or "") + tool_input = block.get("input") or {} + if tool_id and isinstance(tool_input, dict): + tool_uses[tool_id] = (str(block.get("name") or ""), tool_input) + + output: list[dict[str, str]] = [] + + def append(role: str, content: str) -> None: + content = redact(content).strip() + if content: + output.append({"role": role, "content": content}) + + for row in chain[start:]: + message = row.get("message") or {} + if not isinstance(message, dict): + continue + role = str(message.get("role") or "") + content = message.get("content") + + if role == "user" and isinstance(content, str): + if content.startswith(""): + if _xml_value(content, "status") != "completed": + continue + tool_id = _xml_value(content, "tool-use-id") + tool = tool_uses.get(tool_id) + result = _xml_value(content, "result") + if tool and tool[0] == "Agent" and result: + assignment = _agent_assignment(tool[1]) + response = _agent_response(tool[1], result) + append("assistant", assignment) + append("assistant", response) + continue + human = _human_prompt_text(row) + if human: + append("user", human) + continue + + if not isinstance(content, list): + continue + for block in content: + if not isinstance(block, dict): + continue + block_type = block.get("type") + if role == "assistant" and block_type == "text": + append("assistant", str(block.get("text") or "")) + continue + if role != "user" or block_type != "tool_result": + continue + + tool_id = str(block.get("tool_use_id") or "") + tool = tool_uses.get(tool_id) + if not tool: + continue + name, tool_input = tool + result = _tool_result_text(block) + failed = bool(block.get("is_error")) + if name == "Agent" and not failed: + response = _agent_response(tool_input, result) + if response: + append("assistant", _agent_assignment(tool_input)) + append("assistant", response) + elif name == "AskUserQuestion" and result and not failed: + append("user", f"User answers to Claude's questions:\n{result}") + elif name == "ExitPlanMode" and not failed: + plan = redact(tool_input.get("plan", "")).strip() + if plan: + append("assistant", f"Approved implementation plan:\n{plan}") + + fallback = redact(fallback_assistant_message).strip() + if fallback: + labeled = f"Main Claude response:\n{fallback}" + for message in reversed(output): + if message["role"] == "assistant" and message["content"] == fallback: + message["content"] = labeled + break + else: + append("assistant", labeled) + elif label_final_response: + last_message = chain[-1].get("message") or {} + last_content = ( + last_message.get("content") if isinstance(last_message, dict) else None + ) + final_parts = [ + redact(block.get("text", "")).strip() + for block in (last_content if isinstance(last_content, list) else []) + if isinstance(block, dict) + and block.get("type") == "text" + and redact(block.get("text", "")).strip() + ] + for start in range(len(output) - len(final_parts), -1, -1): + candidate = output[start : start + len(final_parts)] + if final_parts and [item["content"] for item in candidate] == final_parts: + candidate[0]["content"] = ( + f"Main Claude response:\n{candidate[0]['content']}" + ) + break + return output, leaf_uuid, end_offset + + +def record_stop( + store: EvidenceStore, hook_input: dict[str, Any] +) -> tuple[RepoContext, str]: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + message = redact(hook_input.get("last_assistant_message", "")).strip() + previous_stop = store.latest_event_payload( + repo.identity, session_id, "assistant_stop" + ) + latest_prompt = store.latest_event_payload(repo.identity, session_id, "user_prompt") + transcript_path = str(hook_input.get("transcript_path") or "") + previous_offset = previous_stop.get("transcript_offset") + start_offset = ( + previous_offset + if isinstance(previous_offset, int) + and str(previous_stop.get("transcript_path") or "") == transcript_path + else 0 + ) + transcript_messages, leaf_uuid, end_offset = transcript_extraction_messages( + transcript_path, + session_id, + previous_leaf_uuid=str(previous_stop.get("transcript_leaf_uuid") or ""), + prompt_hint=str(latest_prompt.get("text") or ""), + fallback_assistant_message=message, + label_final_response=True, + start_offset=start_offset, + ) + if transcript_messages: + payload: dict[str, Any] = { + "text": message, + "transcript_messages": transcript_messages, + } + if leaf_uuid: + payload["transcript_leaf_uuid"] = leaf_uuid + if transcript_path: + payload["transcript_path"] = transcript_path + payload["transcript_offset"] = end_offset + store.record_event( + repo, session_id, "assistant_stop", payload + ) + return repo, session_id diff --git a/integrations/claude-code-plugin/core/flush_worker.py b/integrations/claude-code-plugin/core/flush_worker.py index c60fa82a5..6f7b9ecb2 100644 --- a/integrations/claude-code-plugin/core/flush_worker.py +++ b/integrations/claude-code-plugin/core/flush_worker.py @@ -17,7 +17,7 @@ import telemetry from memory_core import ( EvidenceStore, checkpoint_session, - record_stop, + configure_harness, touch_handoff_heartbeat, ) @@ -27,15 +27,28 @@ def main() -> int: return 2 handoff_path = Path(sys.argv[1]) os.environ["MEM0_CODE_HANDOFF_PATH"] = str(handoff_path) + harness = os.environ.get("MEM0_PLUGIN_HARNESS") + if harness: + source_tag = os.environ.get("MEM0_PLUGIN_SOURCE_TAG", "") + configure_harness( + harness, + env_prefix=os.environ.get("MEM0_PLUGIN_ENV_PREFIX", ""), + data_dir_name=os.environ.get("MEM0_PLUGIN_DATA_DIR_NAME", ""), + source_tag=source_tag, + ) + telemetry.init(harness=harness, source_tag=source_tag.upper()) completed = False try: payload = json.loads(handoff_path.read_text(encoding="utf-8")) delay = float(payload.get("delay_seconds") or 0) if delay > 0: payload.pop("delay_seconds", None) - handoff_path.write_text( - json.dumps(payload), encoding="utf-8" - ) + temporary = handoff_path.with_suffix(f".{os.getpid()}.tmp") + try: + temporary.write_text(json.dumps(payload), encoding="utf-8") + temporary.replace(handoff_path) + finally: + temporary.unlink(missing_ok=True) time.sleep(delay) if not handoff_path.exists(): return 0 @@ -58,8 +71,7 @@ def main() -> int: ): touch_handoff_heartbeat() time.sleep(0.25) - if reason == "session-end": - record_stop(store, hook_input) + # Hooks capture the conversation before handoff; the worker only flushes it. result = checkpoint_session(store, hook_input, reason) print(json.dumps(result, sort_keys=True), flush=True) completed = result.get("status") in { diff --git a/integrations/claude-code-plugin/core/hook_runner.py b/integrations/claude-code-plugin/core/hook_runner.py new file mode 100644 index 000000000..2a2adb557 --- /dev/null +++ b/integrations/claude-code-plugin/core/hook_runner.py @@ -0,0 +1,372 @@ +"""Shared hook orchestration for all Mem0 agent plugins.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +import uuid +from pathlib import Path + +import telemetry +from memory_core import ( + EvidenceStore, + _session_id, + api_key, + bounded, + cache_plugin_api_key, + checkpoint_session, + clear_stale_api_key_cache, + configure_harness, + data_dir, + detached_process_kwargs, + format_context, + harness_config, + record_session_start, + record_tool, + record_user_prompt, + redact, + search_memories, +) + +STALE_RUNNING_SECONDS = 300 +PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60 +PENDING_LAUNCH_LIMIT = 5 +DEFAULT_IDLE_FLUSH_SECONDS = 300 + +_core_dir: Path = Path(__file__).resolve().parent + + +def read_hook_input() -> dict: + try: + value = json.load(sys.stdin) + return value if isinstance(value, dict) else {} + except (json.JSONDecodeError, OSError): + return {} + + +def default_record_stop(store: EvidenceStore, hook_input: dict): + """Record the assistant's response without transcript parsing.""" + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + message = redact(hook_input.get("last_assistant_message", "")).strip() + if message: + store.record_assistant_response(repo, session_id, message) + return repo, session_id + + +def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict: + """Search once before the agent handles the first prompt in a session.""" + repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input) + if not is_first_prompt: + return {} + try: + minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20")) + except ValueError: + minimum_query_chars = 20 + if len(prompt.strip()) < max(minimum_query_chars, 1): + return {} + result = search_memories( + store, repo, session_id, bounded(prompt, 6000), + top_k=5, operation="first-prompt-search", timeout=2, + ) + if not result.memories: + return {} + context = format_context( + result.memories, + "Mem0 found these relevant memories from earlier work in this repository:", + ) + telemetry.record( + "context_injected", + repo=repo, session_id=session_id, trigger="first-prompt", + memory_count=len(result.memories), context_chars=len(context), + prompt_chars=len(prompt), + ) + return { + "hookSpecificOutput": { + "hookEventName": "UserPromptSubmit", + "additionalContext": context, + }, + } + + +def _launch_handoff(handoff_path: Path) -> bool: + running_path = handoff_path.with_suffix(".running") + try: + handoff_path.replace(running_path) + except OSError: + return False + worker = _core_dir / "flush_worker.py" + log_path = data_dir() / "flush-worker.log" + log_handle = open(log_path, "a", encoding="utf-8") + harness = harness_config() + child_env = os.environ.copy() + child_env.update( + { + "MEM0_CODE_DATA_DIR": str(data_dir()), + "MEM0_PLUGIN_HARNESS": harness["name"], + "MEM0_PLUGIN_ENV_PREFIX": harness["env_prefix"], + "MEM0_PLUGIN_DATA_DIR_NAME": harness["data_dir_name"], + "MEM0_PLUGIN_SOURCE_TAG": harness["source_tag"], + } + ) + try: + subprocess.Popen( + [sys.executable, str(worker), str(running_path)], + stdin=subprocess.DEVNULL, + stdout=log_handle, stderr=log_handle, + close_fds=True, + env=child_env, + **detached_process_kwargs(), + ) + finally: + log_handle.close() + return True + + +def recover_pending_handoffs() -> int: + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + now = time.time() + for running in pending_dir.glob("*.running"): + try: + if now - running.stat().st_mtime > STALE_RUNNING_SECONDS: + running.replace(running.with_suffix(".json")) + except OSError: + continue + recoverable = [] + for handoff in pending_dir.glob("*.json"): + try: + age = now - handoff.stat().st_mtime + except OSError: + continue + if age > PENDING_EXPIRY_SECONDS: + handoff.unlink(missing_ok=True) + continue + recoverable.append((age, handoff)) + recoverable.sort(key=lambda item: item[0], reverse=True) + launched = 0 + for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]: + launched += int(_launch_handoff(handoff)) + return launched + + +def refresh_pending_handoffs() -> None: + pending_dir = data_dir() / "pending" + if not pending_dir.is_dir(): + return + for pattern in ("*.json", "*.running"): + for handoff in pending_dir.glob(pattern): + try: + os.utime(handoff) + except OSError: + continue + + +def hand_off_flush( + hook_input: dict, reason: str, *, wait_for_inflight: bool = False, +) -> None: + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + material = ( + f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}" + ) + digest = hashlib.sha256(material.encode()).hexdigest()[:24] + handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json" + temporary_path = handoff_path.with_suffix(".tmp") + temporary_path.write_text( + json.dumps({ + "hook_input": hook_input, + "reason": reason, + "wait_for_inflight": wait_for_inflight, + }), + encoding="utf-8", + ) + temporary_path.replace(handoff_path) + _launch_handoff(handoff_path) + + +def automatic_flush_enabled() -> bool: + return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in { + "1", "true", "yes", "on", + } + + +def schedule_periodic_checkpoint( + store: EvidenceStore, hook_input: dict, repo, session_id: str, +) -> bool: + if ( + not automatic_flush_enabled() + or not api_key() + or not store.checkpoint_due(repo.identity, session_id) + ): + return False + if store.prepare_flush(repo, session_id, "periodic") is None: + return False + hand_off_flush(hook_input, "periodic") + return True + + +def _idle_flush_seconds() -> int: + try: + return max( + int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))), + 0, + ) + except ValueError: + return DEFAULT_IDLE_FLUSH_SECONDS + + +def schedule_idle_flush( + store: EvidenceStore, hook_input: dict, repo, session_id: str, +) -> bool: + delay = _idle_flush_seconds() + if delay <= 0 or not automatic_flush_enabled() or not api_key(): + return False + if store.has_inflight_flush(repo.identity, session_id): + return False + if not store.has_unflushed_events(repo.identity, session_id): + return False + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}" + digest = hashlib.sha256(material.encode()).hexdigest()[:24] + for old in pending_dir.glob(f"idle-{digest}*"): + old.unlink(missing_ok=True) + handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json" + temporary_path = handoff_path.with_suffix(".tmp") + temporary_path.write_text( + json.dumps({ + "hook_input": hook_input, + "reason": "idle", + "delay_seconds": delay, + }), + encoding="utf-8", + ) + temporary_path.replace(handoff_path) + _launch_handoff(handoff_path) + return True + + +def log_failure(exc: Exception) -> None: + try: + log_path = data_dir() / "plugin-errors.log" + with log_path.open("a", encoding="utf-8") as handle: + handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n") + except OSError: + pass + + +def run( + *, + record_stop_fn=None, + extra_actions: dict | None = None, + data_dir_env: str = "MEM0_PLUGIN_DATA_DIR", + automatic_flush_reasons: set | None = None, +) -> int: + if record_stop_fn is None: + record_stop_fn = default_record_stop + if automatic_flush_reasons is None: + automatic_flush_reasons = {"session-end"} + + base_actions = ["session-start", "user-prompt", "post-tool", "stop", "flush"] + all_actions = base_actions + list((extra_actions or {}).keys()) + + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=all_actions) + parser.add_argument("--reason", default="manual") + parser.add_argument("--plugin-data-dir", default="") + parser.add_argument("--harness", default="") + args = parser.parse_args() + + if args.harness: + configure_harness(args.harness) + telemetry.init(harness=args.harness) + + if args.plugin_data_dir: + os.environ[data_dir_env] = args.plugin_data_dir + + cache_plugin_api_key() + if args.action == "session-start": + clear_stale_api_key_cache() + + hook_input = read_hook_input() + store = EvidenceStore() + try: + if store.is_paused(): + if args.action == "session-start": + refresh_pending_handoffs() + telemetry.record("session_start", paused=True) + telemetry.spawn_flush() + return 0 + + if args.action == "session-start": + if telemetry.is_first_run(): + telemetry.record("install") + recovered = recover_pending_handoffs() + record_session_start(store, hook_input) + if recovered: + telemetry.record("handoff_recovered", count=recovered) + telemetry.spawn_flush() + elif args.action == "user-prompt": + output = first_prompt_memory_output(store, hook_input) + if output: + print(json.dumps(output)) + elif args.action == "post-tool": + record_tool(store, hook_input) + elif args.action == "stop": + repo, session_id = record_stop_fn(store, hook_input) + if not schedule_periodic_checkpoint(store, hook_input, repo, session_id): + schedule_idle_flush(store, hook_input, repo, session_id) + elif args.action == "flush": + automatic = args.reason in automatic_flush_reasons + if automatic and not automatic_flush_enabled(): + return 0 + if args.reason == "session-end": + record_stop_fn(store, hook_input) + if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1": + print(json.dumps(checkpoint_session(store, hook_input, args.reason))) + else: + session_id = str(hook_input.get("session_id") or "unknown-session") + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + already_running = store.has_inflight_flush(repo.identity, session_id) + if already_running and args.reason == "session-end": + hand_off_flush(hook_input, args.reason, wait_for_inflight=True) + elif not already_running and store.prepare_flush( + repo, session_id, args.reason, + ) is not None: + hand_off_flush(hook_input, args.reason) + elif extra_actions and args.action in extra_actions: + result = extra_actions[args.action](store, hook_input) + if result: + print(json.dumps(result)) + finally: + store.close() + return 0 + + +def entry_point( + *, + record_stop_fn=None, + extra_actions: dict | None = None, + data_dir_env: str = "MEM0_PLUGIN_DATA_DIR", + automatic_flush_reasons: set | None = None, +) -> None: + try: + raise SystemExit(run( + record_stop_fn=record_stop_fn, + extra_actions=extra_actions, + data_dir_env=data_dir_env, + automatic_flush_reasons=automatic_flush_reasons, + )) + except Exception as exc: + log_failure(exc) + raise SystemExit(0) + + +if __name__ == "__main__": + entry_point() diff --git a/integrations/claude-code-plugin/core/mcp_server.py b/integrations/claude-code-plugin/core/mcp_server.py index 2a9a37c07..036fbbdc9 100644 --- a/integrations/claude-code-plugin/core/mcp_server.py +++ b/integrations/claude-code-plugin/core/mcp_server.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Expose Mem0's memory search as one local Claude Code tool.""" +"""Expose Mem0's memory search as one local coding-agent tool.""" from __future__ import annotations @@ -11,13 +11,13 @@ from typing import Any import telemetry from memory_core import ( CODING_MEMORY_CATEGORY_NAMES, + PLUGIN_VERSION, + SEARCH_SCOPES, format_search_result, resolve_repo, - SEARCH_SCOPES, search_memories, ) - PROTOCOL_VERSION = "2024-11-05" TOOL_NAME = "search_memories" TOOL_DESCRIPTION = ( @@ -30,8 +30,7 @@ TOOL_DESCRIPTION = ( "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. Pass run_id to look " - "at one earlier Claude Code session only." + "working in, and 'mine' is your preferences alone." ) TOOL_SCHEMA = { "type": "object", @@ -65,8 +64,10 @@ TOOL_SCHEMA = { "run_id": { "type": "string", "minLength": 1, - "maxLength": 200, - "description": "Optional Claude Code session ID. Restricts the search to memories written from that session.", + "description": ( + "Optional coding-agent session ID. With any scope, restricts results to memories " + "saved in that session. Omit to recall memories across sessions." + ), }, }, "required": ["query"], @@ -110,16 +111,17 @@ def _validate_arguments( raise ToolInputError(f"scope must be one of {list(SEARCH_SCOPES)}.") run_id = arguments.get("run_id") - if run_id is not None and ( - not isinstance(run_id, str) or not run_id.strip() or len(run_id) > 200 - ): - raise ToolInputError("run_id must be a non-empty string of at most 200 characters.") + if run_id is not None: + if not isinstance(run_id, str) or not run_id.strip(): + raise ToolInputError("run_id must be a non-empty string.") + run_id = run_id.strip() + return query, top_k, category, scope, run_id -def call_search_memories(arguments: Any) -> str: +def call_search_memories(arguments: Any, cwd: str | None = None) -> str: query, top_k, category, scope, run_id = _validate_arguments(arguments) - repo = resolve_repo(os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()) + repo = resolve_repo(cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()) result = search_memories( None, repo, @@ -134,6 +136,19 @@ def call_search_memories(arguments: Any) -> str: return format_search_result(result) +def _workspace_cwd(params: dict[str, Any]) -> str | None: + meta = params.get("_meta") + if not isinstance(meta, dict): + return None + metadata = meta.get("x-codex-turn-metadata") + if not isinstance(metadata, dict): + return None + workspaces = metadata.get("workspaces") or {} + if isinstance(workspaces, dict): + return next((path for path in workspaces if isinstance(path, str) and path), None) + return None + + def _tool_response(text: str, *, is_error: bool = False) -> dict[str, Any]: return { "content": [{"type": "text", "text": text}], @@ -157,7 +172,7 @@ def handle_request(message: Any) -> dict[str, Any] | None: "result": { "protocolVersion": requested or PROTOCOL_VERSION, "capabilities": {"tools": {"listChanged": False}}, - "serverInfo": {"name": "mem0", "version": "0.3.0"}, + "serverInfo": {"name": "mem0", "version": PLUGIN_VERSION}, }, } if method == "ping": @@ -187,7 +202,9 @@ def handle_request(message: Any) -> dict[str, Any] | None: result = _tool_response("Unknown Mem0 tool.", is_error=True) else: try: - result = _tool_response(call_search_memories(params.get("arguments"))) + result = _tool_response( + call_search_memories(params.get("arguments"), _workspace_cwd(params)) + ) except ToolInputError as exc: result = _tool_response(str(exc), is_error=True) except Exception: diff --git a/integrations/claude-code-plugin/core/memory_cli.py b/integrations/claude-code-plugin/core/memory_cli.py index eb1b595b9..595729feb 100644 --- a/integrations/claude-code-plugin/core/memory_cli.py +++ b/integrations/claude-code-plugin/core/memory_cli.py @@ -14,6 +14,7 @@ from memory_core import ( data_dir, doctor, forget_remote_repo, + configure_harness, resolve_repo, user_id, ) @@ -60,6 +61,7 @@ def _print_status(value: dict) -> None: def main() -> int: parser = argparse.ArgumentParser() parser.add_argument("--plugin-data-dir", default="") + parser.add_argument("--harness", default="") subparsers = parser.add_subparsers(dest="command", required=True) status = subparsers.add_parser("status") @@ -77,6 +79,10 @@ def main() -> int: forget.add_argument("--include-project-memory", action="store_true") args = parser.parse_args() + if args.harness: + source_tag = f"{args.harness.replace('-', '_')}_plugin" + configure_harness(args.harness, source_tag=source_tag) + telemetry.init(harness=args.harness, source_tag=source_tag.upper()) if args.plugin_data_dir: os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir store = EvidenceStore() diff --git a/integrations/claude-code-plugin/core/memory_core.py b/integrations/claude-code-plugin/core/memory_core.py index b9d9267b7..cf71196b8 100644 --- a/integrations/claude-code-plugin/core/memory_core.py +++ b/integrations/claude-code-plugin/core/memory_core.py @@ -1,16 +1,15 @@ #!/usr/bin/env python3 -"""Save useful coding memories and search them in later Claude Code sessions. +"""Shared core for Mem0 agent plugins. -Hooks record small session details locally. When Claude compacts or ends the -session, Mem0 sends the useful parts of the session to Mem0 so it can create -memories. Claude can search those memories during later work in the repository. +Hooks record small session details locally. When the agent compacts or ends the +session, Mem0 sends the useful parts to the platform so it can create memories. +The agent can search those memories during later work in the repository. """ from __future__ import annotations import functools import hashlib -import html import json import math import os @@ -20,20 +19,46 @@ import subprocess import sys import time import urllib.error -import urllib.request import urllib.parse +import urllib.request from dataclasses import dataclass -from datetime import timezone, datetime +from datetime import datetime, timezone from pathlib import Path from typing import Any, Iterable import telemetry - DEFAULT_API_URL = "https://api.mem0.ai" -PLUGIN_VERSION = "0.3.0" -MAX_PROMPT_CHARS = 6000 -MAX_ASSISTANT_CHARS = 6000 +PLUGIN_VERSION = "0.3.1" + +_harness_name: str = "generic" +_harness_env_prefix: str = "MEM0_PLUGIN" +_harness_data_dir_name: str = "mem0-plugin" +_harness_source_tag: str = "mem0_plugin" + + +def configure_harness( + name: str, + env_prefix: str = "", + data_dir_name: str = "", + source_tag: str = "", +) -> None: + global _harness_name, _harness_env_prefix, _harness_data_dir_name, _harness_source_tag + _harness_name = name + _harness_env_prefix = env_prefix or f"MEM0_{name.upper().replace('-', '_')}" + _harness_data_dir_name = data_dir_name or f"{name}-plugin" + _harness_source_tag = source_tag or f"{name.replace('-', '_')}_plugin" + + +def harness_config() -> dict[str, str]: + return { + "name": _harness_name, + "env_prefix": _harness_env_prefix, + "data_dir_name": _harness_data_dir_name, + "source_tag": _harness_source_tag, + } + + MAX_COMMAND_CHARS = 2000 MAX_RESULT_CHARS = 2500 MAX_EPISODE_CHARS = 12000 @@ -52,7 +77,7 @@ A completed change should produce one memory explaining the resulting behavior, 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 Claude's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or Claude 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. @@ -130,6 +155,11 @@ SECRET_PATTERNS = [ r"-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----", re.DOTALL, ), + re.compile( + r'(?i)("(?:api[_-]?key|password|secret(?:[_-]?access[_-]?key)?' + r'|(?:access|refresh|session)[_-]?token|token|authorization|credential' + r')"\s*:\s*")(?:\\.|[^"\\])*' + ), ] @@ -213,13 +243,21 @@ def directory_chain(repo: RepoContext) -> list[str]: return ["/".join(parts[: index + 1]) for index in range(len(parts))] +def _shared_project_ids(repo: RepoContext) -> list[str]: + """Current and pre-upgrade namespaces, shared by recall and explicit deletion.""" + if not repo.identity.startswith("local:") and repo.project_id != repo.app_id: + return [repo.project_id, repo.app_id] + return [repo.project_id] + + def _search_filters(user: str, repo: RepoContext, scope: str) -> dict[str, Any]: """Build the scope filter: app_id scopes to the repo, then union shared and personal lanes.""" app_scope = {"app_id": repo.app_id} mine = {"AND": [{"user_id": user}, app_scope]} if scope == "mine": return mine - shared: dict[str, Any] = {"AND": [{"agent_id": repo.project_id}, app_scope]} + projects = [{"AND": [{"agent_id": project_id}, app_scope]} for project_id in _shared_project_ids(repo)] + shared: dict[str, Any] = projects[0] if len(projects) == 1 else {"OR": projects} if scope == "dir" and repo.directory: shared = {"AND": [shared, {"metadata": {"dirs": {"contains": repo.directory}}}]} return {"OR": [shared, mine]} @@ -297,9 +335,9 @@ class RepoContext: def _project_id(root: str, identity: str, app_id: str) -> str: - """The shared namespace: the repository, or a folder path hashed so same-named folders stay apart.""" + """The shared namespace: includes a host hash so repos with the same owner/name on different hosts stay apart.""" if not identity.startswith("local:"): - return app_id + return f"{app_id}-{hashlib.sha256(identity.encode()).hexdigest()[:10]}" return f"local-{app_id}-{hashlib.sha256(root.encode()).hexdigest()[:10]}" @@ -345,8 +383,8 @@ def resolve_repo(cwd: str | None) -> RepoContext: def api_key() -> str: configured = ( os.environ.get("MEM0_API_KEY") + or os.environ.get("PLUGIN_OPTION_API_KEY") or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") - # Compatibility with the pre-marketplace development harness. or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") or "" ).strip() @@ -359,9 +397,10 @@ def api_key() -> str: def cache_plugin_api_key() -> bool: - """Bridge Claude's hook-only sensitive config into plugin-owned storage.""" + """Bridge host's hook-only sensitive config into plugin-owned storage.""" configured = ( - os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") or "" ).strip() @@ -394,6 +433,7 @@ def clear_stale_api_key_cache() -> bool: """Drop the cached key file once every configured key source is gone.""" configured = ( os.environ.get("MEM0_API_KEY") + or os.environ.get("PLUGIN_OPTION_API_KEY") or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") or "" @@ -411,7 +451,7 @@ def clear_stale_api_key_cache() -> bool: def detached_process_kwargs(platform: str | None = None) -> dict: - """Keep a spawned worker alive after Claude Code exits, on POSIX and Windows.""" + """Keep a spawned worker alive after the coding agent exits, on POSIX and Windows.""" if (platform or sys.platform) == "win32": return { "creationflags": subprocess.DETACHED_PROCESS @@ -422,7 +462,8 @@ def detached_process_kwargs(platform: str | None = None) -> dict: def _plugin_option(name: str, fallback: str = "") -> str: return ( - os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name.upper()}") + os.environ.get(f"PLUGIN_OPTION_{name.upper()}") + or os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name.upper()}") or os.environ.get(fallback) or "" ).strip() @@ -440,11 +481,14 @@ def user_id() -> str: def data_dir() -> Path: - configured = os.environ.get("MEM0_CODE_DATA_DIR") or os.environ.get( - "CLAUDE_PLUGIN_DATA" + configured = ( + os.environ.get("MEM0_CODE_DATA_DIR") + or os.environ.get("MEM0_PLUGIN_DATA_DIR") + or os.environ.get("PLUGIN_DATA") + or os.environ.get("CLAUDE_PLUGIN_DATA") ) return ( - Path(configured).expanduser() if configured else Path.home() / ".mem0" / "claude-code-plugin" + Path(configured).expanduser() if configured else Path.home() / ".mem0" / _harness_data_dir_name ) @@ -464,316 +508,11 @@ def _int_option(name: str, fallback: str, default: int) -> int: -def _message_content_text(content: Any) -> str: - """Return visible text from one Claude transcript message.""" - if isinstance(content, str): - return redact(content).strip() - if not isinstance(content, list): - return "" - parts = [] - for block in content: - if not isinstance(block, dict) or block.get("type") != "text": - continue - text = redact(block.get("text", "")).strip() - if text: - parts.append(text) - return "\n\n".join(parts) - - -def _transcript_rows( - path: str, offset: int = 0 -) -> tuple[list[dict[str, Any]], int, bool]: - """Parse transcript rows from a byte offset, returning rows, end offset, and whether the offset was honored.""" - if not path: - return [], 0, False - rows = [] - try: - resolved = Path(path).expanduser() - if not 0 <= offset <= resolved.stat().st_size: - offset = 0 - end = offset - with resolved.open("rb") as handle: - handle.seek(offset) - for line in handle: - if not line.endswith(b"\n"): - break - end += len(line) - try: - row = json.loads(line.decode("utf-8", errors="replace")) - except json.JSONDecodeError: - continue - if isinstance(row, dict) and row.get("uuid"): - rows.append(row) - except OSError: - return [], offset, False - return rows, end, offset > 0 - - -def _active_transcript_chain( - rows: list[dict[str, Any]], session_id: str -) -> list[dict[str, Any]]: - """Follow the current Claude conversation branch from its latest record.""" - by_uuid = {str(row["uuid"]): row for row in rows if row.get("uuid")} - leaf = next( - ( - row - for row in reversed(rows) - if not row.get("isSidechain") - and str(row.get("sessionId") or "") == session_id - ), - None, - ) - if leaf is None: - return [] - - chain = [] - seen = set() - current = leaf - while current is not None: - uuid = str(current.get("uuid") or "") - if not uuid or uuid in seen: - break - seen.add(uuid) - chain.append(current) - current = by_uuid.get(str(current.get("parentUuid") or "")) - chain.reverse() - return chain - - -def _human_prompt_text(row: dict[str, Any]) -> str: - if row.get("type") != "user": - return "" - origin = row.get("origin") or {} - if isinstance(origin, dict) and origin.get("kind") not in {None, "human"}: - return "" - message = row.get("message") or {} - content = message.get("content") if isinstance(message, dict) else None - if not isinstance(content, str): - return "" - text = redact(content).strip() - if text.startswith(""): - text = text.removeprefix("").strip() - ignored_prefixes = ( - "", - "", - "", - "", - "", - "", - ) - return "" if text.startswith(ignored_prefixes) else text - - -def _xml_value(text: str, tag: str) -> str: - match = re.search(fr"<{tag}>(.*?)", text, re.DOTALL) - return html.unescape(match.group(1).strip()) if match else "" - - -def _agent_assignment(tool_input: dict[str, Any]) -> str: - prompt = redact(tool_input.get("prompt", "")).strip() - if not prompt: - return "" - agent_type = redact(tool_input.get("subagent_type", "agent")).strip() or "agent" - description = redact(tool_input.get("description", "")).strip() - heading = f"Subagent assignment ({agent_type}" - if description: - heading += f": {description}" - return f"{heading}):\n{prompt}" - - -def _agent_response(tool_input: dict[str, Any], result: str) -> str: - result = redact(result).strip() - if not result or result.startswith("Async agent launched successfully."): - return "" - agent_type = redact(tool_input.get("subagent_type", "agent")).strip() or "agent" - description = redact(tool_input.get("description", "")).strip() - heading = f"Subagent response ({agent_type}" - if description: - heading += f": {description}" - return f"{heading}):\n{result}" - - -def _tool_result_text(block: dict[str, Any]) -> str: - return _message_content_text(block.get("content")) - - -def transcript_extraction_messages( - transcript_path: str, - session_id: str, - *, - previous_leaf_uuid: str = "", - prompt_hint: str = "", - fallback_assistant_message: str = "", - label_final_response: bool = False, - start_offset: int = 0, -) -> tuple[list[dict[str, str]], str, int]: - """Read the meaningful part of the current Claude exchange. - - The returned messages contain human prompts, visible Claude text, accepted - plans, answers collected through AskUserQuestion, and completed native - subagent assignments and responses. Raw tool output and hidden reasoning - are deliberately excluded. - """ - rows, end_offset, resumed = _transcript_rows(transcript_path, start_offset) - chain = _active_transcript_chain(rows, session_id) - if not chain: - if resumed: - return [], previous_leaf_uuid, end_offset - fallback = redact(fallback_assistant_message).strip() - return ( - ([{"role": "assistant", "content": f"Main Claude response:\n{fallback}"}] - if fallback - else []), - "", - end_offset, - ) - - leaf_uuid = str(chain[-1].get("uuid") or "") - if previous_leaf_uuid and leaf_uuid == previous_leaf_uuid: - return [], leaf_uuid, end_offset - start = 0 - if previous_leaf_uuid: - for index, row in enumerate(chain): - if str(row.get("uuid") or "") == previous_leaf_uuid: - start = index + 1 - break - else: - previous_leaf_uuid = "" - if not previous_leaf_uuid and not resumed: - prompt_hint = redact(prompt_hint).strip() - candidates = [ - index - for index, row in enumerate(chain) - if _human_prompt_text(row) - and ( - not prompt_hint - or _human_prompt_text(row) == prompt_hint - ) - ] - task_notifications = [ - index - for index, row in enumerate(chain) - if isinstance((row.get("message") or {}).get("content"), str) - and (row.get("message") or {})["content"].startswith("") - ] - if candidates: - start = candidates[-1] - elif task_notifications: - start = task_notifications[-1] - - tool_uses: dict[str, tuple[str, dict[str, Any]]] = {} - for row in chain: - message = row.get("message") or {} - content = message.get("content") if isinstance(message, dict) else None - if not isinstance(content, list): - continue - for block in content: - if not isinstance(block, dict) or block.get("type") != "tool_use": - continue - tool_id = str(block.get("id") or "") - tool_input = block.get("input") or {} - if tool_id and isinstance(tool_input, dict): - tool_uses[tool_id] = (str(block.get("name") or ""), tool_input) - - output: list[dict[str, str]] = [] - - def append(role: str, content: str) -> None: - content = redact(content).strip() - if content: - output.append({"role": role, "content": content}) - - for row in chain[start:]: - message = row.get("message") or {} - if not isinstance(message, dict): - continue - role = str(message.get("role") or "") - content = message.get("content") - - if role == "user" and isinstance(content, str): - if content.startswith(""): - if _xml_value(content, "status") != "completed": - continue - tool_id = _xml_value(content, "tool-use-id") - tool = tool_uses.get(tool_id) - result = _xml_value(content, "result") - if tool and tool[0] == "Agent" and result: - assignment = _agent_assignment(tool[1]) - response = _agent_response(tool[1], result) - append("assistant", assignment) - append("assistant", response) - continue - human = _human_prompt_text(row) - if human: - append("user", human) - continue - - if not isinstance(content, list): - continue - for block in content: - if not isinstance(block, dict): - continue - block_type = block.get("type") - if role == "assistant" and block_type == "text": - append("assistant", str(block.get("text") or "")) - continue - if role != "user" or block_type != "tool_result": - continue - - tool_id = str(block.get("tool_use_id") or "") - tool = tool_uses.get(tool_id) - if not tool: - continue - name, tool_input = tool - result = _tool_result_text(block) - failed = bool(block.get("is_error")) - if name == "Agent" and not failed: - response = _agent_response(tool_input, result) - if response: - append("assistant", _agent_assignment(tool_input)) - append("assistant", response) - elif name == "AskUserQuestion" and result and not failed: - append("user", f"User answers to Claude's questions:\n{result}") - elif name == "ExitPlanMode" and not failed: - plan = redact(tool_input.get("plan", "")).strip() - if plan: - append("assistant", f"Approved implementation plan:\n{plan}") - - fallback = redact(fallback_assistant_message).strip() - if fallback: - labeled = f"Main Claude response:\n{fallback}" - for message in reversed(output): - if message["role"] == "assistant" and message["content"] == fallback: - message["content"] = labeled - break - else: - append("assistant", labeled) - elif label_final_response: - last_message = chain[-1].get("message") or {} - last_content = ( - last_message.get("content") if isinstance(last_message, dict) else None - ) - final_parts = [ - redact(block.get("text", "")).strip() - for block in (last_content if isinstance(last_content, list) else []) - if isinstance(block, dict) - and block.get("type") == "text" - and redact(block.get("text", "")).strip() - ] - for start in range(len(output) - len(final_parts), -1, -1): - candidate = output[start : start + len(final_parts)] - if final_parts and [item["content"] for item in candidate] == final_parts: - candidate[0]["content"] = ( - f"Main Claude response:\n{candidate[0]['content']}" - ) - break - return output, leaf_uuid, end_offset - - def _checkpoint_message(event: dict[str, Any]) -> str: kind = event.get("kind") payload = event.get("payload") or {} if kind == "user_prompt": - return bounded(payload.get("text", ""), MAX_PROMPT_CHARS) + return redact(payload.get("text", "")).strip() if kind == "assistant_stop": transcript_messages = payload.get("transcript_messages") or [] if isinstance(transcript_messages, list): @@ -784,9 +523,9 @@ def _checkpoint_message(event: dict[str, Any]) -> str: ) if text: return text - return bounded(payload.get("text", ""), MAX_ASSISTANT_CHARS) + return redact(payload.get("text", "")).strip() if kind == "sidekick_stop": - return bounded(payload.get("final_message", ""), MAX_ASSISTANT_CHARS) + return redact(payload.get("final_message", "")).strip() return "" @@ -998,8 +737,27 @@ class EvidenceStore: self.conn.commit() return int(cursor.lastrowid) + def record_assistant_response(self, repo: RepoContext, session_id: str, message: str) -> None: + """Ignore repeated response hooks until another prompt or a different answer arrives.""" + with self.conn: + # Serialize the check and insert across concurrent Stop and SessionEnd hooks. + self.conn.execute("BEGIN IMMEDIATE") + previous = self.conn.execute( + """SELECT kind, payload_json FROM events + WHERE repo_id = ? AND session_id = ? AND kind IN ('user_prompt', 'assistant_stop') + ORDER BY id DESC LIMIT 1""", + (repo.identity, session_id), + ).fetchone() + if ( + previous is not None + and previous["kind"] == "assistant_stop" + and json.loads(previous["payload_json"]).get("text") == message + ): + return + self.record_event(repo, session_id, "assistant_stop", {"text": message}) + def repo_for_session(self, session_id: str, cwd: str | None) -> RepoContext: - """Keep one project scope for every hook in a Claude Code session.""" + """Keep one project scope for every hook in a coding-agent session.""" current = resolve_repo(cwd) if session_id == "unknown-session": return current @@ -1041,78 +799,77 @@ class EvidenceStore: def prepare_flush( self, repo: RepoContext, session_id: str, reason: str ) -> tuple[str, list[dict[str, Any]]] | None: - existing = self.conn.execute( - """SELECT * FROM flushes - WHERE repo_id = ? AND session_id = ? - AND status NOT IN ('semantic-succeeded', 'explicitly-stored', 'gave-up') - ORDER BY created_at LIMIT 1""", - (repo.identity, session_id), - ).fetchone() - if existing and int(existing["attempts"] or 0) >= MAX_FLUSH_ATTEMPTS: - with self.conn: + with self.conn: + self.conn.execute("BEGIN IMMEDIATE") + existing = self.conn.execute( + """SELECT * FROM flushes + WHERE repo_id = ? AND session_id = ? + AND status NOT IN ('semantic-succeeded', 'explicitly-stored', 'gave-up') + ORDER BY created_at LIMIT 1""", + (repo.identity, session_id), + ).fetchone() + if existing and int(existing["attempts"] or 0) >= MAX_FLUSH_ATTEMPTS: self.conn.execute( "UPDATE flushes SET status = 'gave-up', updated_at = ? WHERE packet_id = ?", (utc_now(), existing["packet_id"]), ) - telemetry.record( - "flush", - repo=repo, - session_id=session_id, - reason=reason, - status="gave-up", - success=False, - attempts=int(existing["attempts"] or 0), - ) - existing = None - if existing: - if reason != "periodic" and existing["reason"] == "periodic": - with self.conn: + telemetry.record( + "flush", + repo=repo, + session_id=session_id, + reason=reason, + status="gave-up", + success=False, + attempts=int(existing["attempts"] or 0), + ) + existing = None + if existing: + if reason != "periodic" and existing["reason"] == "periodic": self.conn.execute( "UPDATE flushes SET reason = ?, updated_at = ? WHERE packet_id = ?", (reason, utc_now(), existing["packet_id"]), ) - existing_rows = self.conn.execute( - "SELECT * FROM events WHERE flush_id = ? ORDER BY id", - (existing["packet_id"],), + existing_rows = self.conn.execute( + "SELECT * FROM events WHERE flush_id = ? ORDER BY id", + (existing["packet_id"],), + ).fetchall() + if existing_rows: + return str(existing["packet_id"]), [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in existing_rows + ] + + rows = self.conn.execute( + """SELECT * FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id""", + (repo.identity, session_id), ).fetchall() - if existing_rows: - return str(existing["packet_id"]), [ - { - "id": row["id"], - "created_at": row["created_at"], - "kind": row["kind"], - "payload": json.loads(row["payload_json"]), - } - for row in existing_rows - ] + if not rows: + return None - rows = self.conn.execute( - """SELECT * FROM events - WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL - ORDER BY id""", - (repo.identity, session_id), - ).fetchall() - if not rows: - return None + events = [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in rows + ] + events = select_checkpoint_events(events, force=reason != "periodic") + if not events: + return None + event_start, event_end = events[0]["id"], events[-1]["id"] + packet_material = f"{repo.identity}\0{session_id}\0{event_start}\0{event_end}" + packet_id = hashlib.sha256(packet_material.encode()).hexdigest()[:32] + now = utc_now() - events = [ - { - "id": row["id"], - "created_at": row["created_at"], - "kind": row["kind"], - "payload": json.loads(row["payload_json"]), - } - for row in rows - ] - events = select_checkpoint_events(events, force=reason != "periodic") - if not events: - return None - event_start, event_end = events[0]["id"], events[-1]["id"] - packet_material = f"{repo.identity}\0{session_id}\0{event_start}\0{event_end}" - packet_id = hashlib.sha256(packet_material.encode()).hexdigest()[:32] - now = utc_now() - - with self.conn: self.conn.execute( """INSERT OR IGNORE INTO flushes (packet_id, repo_id, app_id, session_id, reason, event_start, @@ -1137,7 +894,7 @@ class EvidenceStore: f"WHERE id IN ({placeholders}) AND flush_id IS NULL", (packet_id, *event_ids), ) - return packet_id, events + return packet_id, events def checkpoint_due(self, repo_id: str, session_id: str) -> bool: if self.has_inflight_flush(repo_id, session_id): @@ -1318,9 +1075,19 @@ class EvidenceStore: agent_type: str, transcript_path: str, final_message: str, - ) -> None: + ) -> str: now = utc_now() - with self.conn: + self.conn.execute("BEGIN IMMEDIATE") + try: + if not agent_id: + rows = self.conn.execute( + """SELECT agent_id FROM sidekick_runs + WHERE repo_id = ? AND session_id = ? AND agent_type = ? AND stopped_at IS NULL + LIMIT 2""", + (repo.identity, session_id, agent_type), + ).fetchall() + # Without a host ID, overlapping runs cannot be correlated reliably. + agent_id = rows[0]["agent_id"] if len(rows) == 1 else f"unknown-agent-{time.time_ns()}" self.conn.execute( """INSERT INTO sidekick_runs (repo_id, session_id, agent_id, agent_type, started_at, @@ -1338,9 +1105,14 @@ class EvidenceStore: now, now, bounded(transcript_path, 2000), - bounded(final_message, MAX_ASSISTANT_CHARS), + redact(final_message).strip(), ), ) + self.conn.commit() + except Exception: + self.conn.rollback() + raise + return agent_id def operation( self, @@ -1518,7 +1290,7 @@ def record_user_prompt( ) -> tuple[RepoContext, str, str, bool]: session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) - prompt = bounded(hook_input.get("prompt", ""), MAX_PROMPT_CHARS) + prompt = redact(hook_input.get("prompt", "")).strip() is_first_prompt = not store.has_event(repo.identity, session_id, "user_prompt") store.record_event(repo, session_id, "user_prompt", {"text": prompt}) return repo, session_id, prompt, is_first_prompt @@ -1543,7 +1315,7 @@ def _tool_result_preview(response: Any) -> str: return bounded(response, MAX_RESULT_CHARS) -def tool_payload(hook_input: dict[str, Any], *, failed: bool = False) -> dict[str, Any]: +def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> dict[str, Any]: name = str(hook_input.get("tool_name") or "unknown") tool_input = hook_input.get("tool_input") or {} if not isinstance(tool_input, dict): @@ -1597,7 +1369,7 @@ def tool_payload(hook_input: dict[str, Any], *, failed: bool = False) -> dict[st def record_tool( - store: EvidenceStore, hook_input: dict[str, Any], *, failed: bool = False + store: EvidenceStore, hook_input: dict[str, Any], *, failed: bool | None = False ) -> None: session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) @@ -1612,51 +1384,8 @@ def record_tool( ) -def record_stop( - store: EvidenceStore, hook_input: dict[str, Any] -) -> tuple[RepoContext, str]: - session_id = _session_id(hook_input) - repo = store.repo_for_session(session_id, hook_input.get("cwd")) - message = bounded(hook_input.get("last_assistant_message", ""), MAX_ASSISTANT_CHARS) - previous_stop = store.latest_event_payload( - repo.identity, session_id, "assistant_stop" - ) - latest_prompt = store.latest_event_payload(repo.identity, session_id, "user_prompt") - transcript_path = str(hook_input.get("transcript_path") or "") - previous_offset = previous_stop.get("transcript_offset") - start_offset = ( - previous_offset - if isinstance(previous_offset, int) - and str(previous_stop.get("transcript_path") or "") == transcript_path - else 0 - ) - transcript_messages, leaf_uuid, end_offset = transcript_extraction_messages( - transcript_path, - session_id, - previous_leaf_uuid=str(previous_stop.get("transcript_leaf_uuid") or ""), - prompt_hint=str(latest_prompt.get("text") or ""), - fallback_assistant_message=message, - label_final_response=True, - start_offset=start_offset, - ) - if transcript_messages: - payload: dict[str, Any] = { - "text": message, - "transcript_messages": transcript_messages, - } - if leaf_uuid: - payload["transcript_leaf_uuid"] = leaf_uuid - if transcript_path: - payload["transcript_path"] = transcript_path - payload["transcript_offset"] = end_offset - store.record_event( - repo, session_id, "assistant_stop", payload - ) - return repo, session_id - - def record_sidekick_start( - store: EvidenceStore, hook_input: dict[str, Any] + store: EvidenceStore, hook_input: dict[str, Any], *, inject_context: bool = True ) -> str: """Record a native sidekick and reuse the main turn's retrieved memories.""" session_id = _session_id(hook_input) @@ -1666,6 +1395,8 @@ def record_sidekick_start( context = combine_context( format_context(store.injected_memories(session_id, repo.identity)) ) + if not inject_context: + context = "" first_start = store.start_sidekick( repo, session_id, agent_id, agent_type, len(context) ) @@ -1694,13 +1425,11 @@ def record_sidekick_start( def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) - agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200) agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) - final_message = bounded( - hook_input.get("last_assistant_message", ""), MAX_ASSISTANT_CHARS - ) + agent_id = bounded(hook_input.get("agent_id", ""), 200) + final_message = redact(hook_input.get("last_assistant_message", "")).strip() transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000) - store.stop_sidekick( + agent_id = store.stop_sidekick( repo, session_id, agent_id, @@ -1775,17 +1504,17 @@ def build_episode( task_outcome: str = "", ) -> tuple[str, dict[str, Any]]: prompts = [ - bounded(e["payload"].get("text", ""), MAX_PROMPT_CHARS) + redact(e["payload"].get("text", "")).strip() for e in events if e["kind"] == "user_prompt" and e["payload"].get("text") ] assistant_conclusions = [ - bounded(e["payload"].get("text", ""), MAX_ASSISTANT_CHARS) + redact(e["payload"].get("text", "")).strip() for e in events if e["kind"] == "assistant_stop" and e["payload"].get("text") ] sidekick_outcomes = [ - bounded(e["payload"].get("final_message", ""), MAX_ASSISTANT_CHARS) + redact(e["payload"].get("final_message", "")).strip() for e in events if e["kind"] == "sidekick_stop" and e["payload"].get("final_message") ] @@ -1812,7 +1541,7 @@ def build_episode( { "command": t.get("command", ""), "kind": t.get("command_kind", "shell"), - "status": "failed" if t.get("failed") else "succeeded", + "status": "unknown" if t.get("failed", False) is None else "failed" if t.get("failed") else "succeeded", "result": t.get("result_preview", ""), } for t in tools @@ -1820,10 +1549,7 @@ def build_episode( ] task = bounded(canonical_task or (prompts[0] if prompts else ""), 4000) - conclusion = bounded( - assistant_conclusions[-1] if assistant_conclusions else "", - MAX_ASSISTANT_CHARS, - ) + conclusion = redact(assistant_conclusions[-1] if assistant_conclusions else "").strip() outcome = bounded(task_outcome, 2000) extraction_messages: list[dict[str, str]] = [] @@ -1835,16 +1561,14 @@ def build_episode( pending_user_messages.append( { "role": "user", - "content": bounded( - event["payload"].get("text", ""), MAX_PROMPT_CHARS - ), + "content": redact(event["payload"].get("text", "")).strip(), } ) elif event["kind"] == "assistant_stop": transcript_messages = event["payload"].get("transcript_messages") or [] if isinstance(transcript_messages, list) and transcript_messages: transcript_users = { - str(message.get("content") or "").strip() + redact(message.get("content") or "").strip() for message in transcript_messages if isinstance(message, dict) and message.get("role") == "user" } @@ -1856,7 +1580,7 @@ def build_episode( extraction_messages.extend( { "role": str(message.get("role") or ""), - "content": str(message.get("content") or ""), + "content": redact(message.get("content") or "").strip(), } for message in transcript_messages if isinstance(message, dict) @@ -1869,10 +1593,7 @@ def build_episode( extraction_messages.append( { "role": "assistant", - "content": bounded( - event["payload"].get("text", ""), - MAX_ASSISTANT_CHARS, - ), + "content": redact(event["payload"].get("text", "")).strip(), } ) pending_user_messages = [] @@ -1972,7 +1693,7 @@ def build_extraction_messages(structured: dict[str, Any]) -> list[dict[str, str] """Build the session messages sent to Mem0 for memory extraction.""" evidence = build_semantic_evidence(structured) messages = [ - {"role": message["role"], "content": message["content"]} + {"role": message["role"], "content": redact(message["content"]).strip()} for message in structured.get("extraction_messages", []) if message.get("role") in {"user", "assistant"} and message.get("content") ] @@ -2014,7 +1735,7 @@ def extraction_message_batches( *, max_tokens: int = MAX_EXTRACTION_INPUT_TOKENS, ) -> list[list[dict[str, str]]]: - """Split large extraction input without cutting messages or agent pairs.""" + """Keep exchanges together when possible; split oversized messages to enforce the request budget.""" if not messages or _message_tokens(messages) <= max_tokens: return [messages] @@ -2047,9 +1768,29 @@ def extraction_message_batches( units.append([message]) index += 1 + bounded_units: list[list[dict[str, str]]] = [] + for unit in units: + if _message_tokens(unit) <= max_tokens: + bounded_units.append(unit) + continue + for message in unit: + remaining = message["content"] + while remaining: + low, high = 0, len(remaining) + while low < high: + middle = (low + high + 1) // 2 + if _message_tokens([{**message, "content": remaining[:middle]}]) <= max_tokens: + low = middle + else: + high = middle - 1 + if low == 0: + raise ValueError("Extraction token budget cannot fit a message") + bounded_units.append([{**message, "content": remaining[:low]}]) + remaining = remaining[low:] + batches: list[list[dict[str, str]]] = [] batch: list[dict[str, str]] = [] - for unit in units: + for unit in bounded_units: candidate = [*batch, *unit] if batch and _message_tokens(candidate) > max_tokens: batches.append(batch) @@ -2152,6 +1893,11 @@ def _wait_for_event(api_url: str, key: str, event_id: str) -> tuple[str, int, in key, min(10, poll_seconds + 5), ) + except urllib.error.HTTPError as exc: + if exc.code not in {408, 429} and exc.code < 500: + raise + time.sleep(poll_seconds) + continue except (urllib.error.URLError, TimeoutError, OSError): # The extraction job is durable server-side. A transient polling # failure must not discard a job that may still complete normally. @@ -2217,7 +1963,7 @@ def flush_session( task_outcome=bounded(hook_input.get("task_outcome", ""), 2000), ) - metadata = {"source": "claude_code_plugin"} + metadata = {"source": _harness_source_tag} if repo.branch and repo.branch not in {"detached", "unknown"}: metadata["branch"] = repo.branch if repo.head_sha: @@ -2684,7 +2430,7 @@ def format_context( def format_search_result(result: MemorySearchResult) -> str: - """Return only the text Claude needs from an explicit memory search.""" + """Return only the text the coding agent needs from an explicit memory search.""" if not result.succeeded: return "Memory search failed." if result.memories: @@ -2731,7 +2477,11 @@ def _scoped_memory_ids( app_id_prefix=prefix, ) if include_project: - _collect_memory_ids(api_url, key, {"agent_id": repo.project_id}, ids, seen) + for project_id in _shared_project_ids(repo): + _collect_memory_ids( + api_url, key, {"agent_id": project_id}, ids, seen, + app_id_prefix=prefix, + ) return ids diff --git a/integrations/claude-code-plugin/core/telemetry.py b/integrations/claude-code-plugin/core/telemetry.py index 2b704a339..249595475 100644 --- a/integrations/claude-code-plugin/core/telemetry.py +++ b/integrations/claude-code-plugin/core/telemetry.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Anonymous usage telemetry for the Mem0 Claude Code plugin. +"""Anonymous usage telemetry for Mem0 agent plugins. Hooks run on a 3-6 second budget and fire on every tool call, so recording never touches the network: `record` appends one JSON line to a local spool and returns. @@ -29,6 +29,38 @@ from typing import Any import memory_core +_harness: str = "generic" +_source_tag: str = "MEM0_PLUGIN" +_PRIVATE_KEYS = { + "apikey", + "authorization", + "password", + "query", + "secret", + "prompt", + "token", + "text", + "memory", + "message", + "error", + "path", + "cwd", + "userid", + "agentid", + "runid", + "repoid", + "repositoryid", + "projectid", + "appid", + "filters", +} + + +def init(harness: str = "generic", source_tag: str = "") -> None: + global _harness, _source_tag + _harness = harness + _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN" + POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/" POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/" @@ -54,6 +86,23 @@ def _digest(value: str, length: int = 16) -> str: return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length] +def _safe_value(value: Any) -> Any: + if isinstance(value, str): + return memory_core.redact(value) + if isinstance(value, dict): + return { + key: _safe_value(item) + for key, item in value.items() + if "".join(character for character in str(key).lower() if character.isalnum()) + not in _PRIVATE_KEYS + } + if isinstance(value, (list, tuple)): + return [_safe_value(item) for item in value] + if value is None or isinstance(value, (bool, int, float)): + return value + return memory_core.redact(value) + + def _spool_path() -> Path: return memory_core.data_dir() / "telemetry.jsonl" @@ -118,8 +167,9 @@ def record( return except OSError: pass + properties = _safe_value(properties) properties.update( - harness="claude-code", + harness=_harness, plugin_version=memory_core.PLUGIN_VERSION, os=sys.platform, python_version=platform.python_version(), @@ -316,7 +366,7 @@ def flush() -> int: "distinct_id": distinct_id, "timestamp": event.get("timestamp"), "properties": { - "source": "CLAUDE_CODE_PLUGIN", + "source": _source_tag, "language": "python", "$process_person_profile": False, "$lib": "posthog-python", diff --git a/integrations/claude-code-plugin/plugin-build.json b/integrations/claude-code-plugin/plugin-build.json new file mode 100644 index 000000000..68d306fd6 --- /dev/null +++ b/integrations/claude-code-plugin/plugin-build.json @@ -0,0 +1,17 @@ +{ + "id": "mem0", + "version": "0.3.1", + "homepage": "https://docs.mem0.ai/integrations/claude-code", + "native": { + "pluginRoot": "${CLAUDE_PLUGIN_ROOT}", + "pluginData": "${CLAUDE_PLUGIN_DATA}", + "files": { + ".claude-plugin/plugin.json": ".claude-plugin/plugin.json", + ".mcp.json": ".mcp.json", + "hooks/hooks.json": "hooks/hooks.json", + "adapters/claude/hook.py": "adapters/claude/hook.py", + "adapters/claude/transcript.py": "adapters/claude/transcript.py", + "agents/sidekick.md": "agents/sidekick.md" + } + } +} diff --git a/integrations/claude-code-plugin/skills/forget/SKILL.md b/integrations/claude-code-plugin/skills/forget/SKILL.md index c61219cc6..7cf25a38e 100644 --- a/integrations/claude-code-plugin/skills/forget/SKILL.md +++ b/integrations/claude-code-plugin/skills/forget/SKILL.md @@ -14,7 +14,7 @@ so it stays unless the user explicitly asks to delete that too. After the user confirms, run: ```bash -python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" forget --remote --yes +python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" --harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" forget --remote --yes ``` If the user also asked to delete the repository's shared project memory, add diff --git a/integrations/claude-code-plugin/skills/pause/SKILL.md b/integrations/claude-code-plugin/skills/pause/SKILL.md index 6492ccc43..5aef04f39 100644 --- a/integrations/claude-code-plugin/skills/pause/SKILL.md +++ b/integrations/claude-code-plugin/skills/pause/SKILL.md @@ -11,7 +11,7 @@ anonymous telemetry ping still fires at session start unless `MEM0_TELEMETRY=false`): ```bash -python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" pause +python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" --harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" pause ``` Confirm the new state back to the user, and remind them that already-created diff --git a/integrations/claude-code-plugin/skills/resume/SKILL.md b/integrations/claude-code-plugin/skills/resume/SKILL.md index f4877fc9f..61082fb42 100644 --- a/integrations/claude-code-plugin/skills/resume/SKILL.md +++ b/integrations/claude-code-plugin/skills/resume/SKILL.md @@ -11,7 +11,7 @@ Resume memory capture for this machine. Run: ```bash -python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" resume +python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" --harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" resume ``` Confirm to the user that capture is active again. New sessions record evidence and diff --git a/integrations/claude-code-plugin/skills/search/SKILL.md b/integrations/claude-code-plugin/skills/search/SKILL.md index ad5c958bb..198a1f023 100644 --- a/integrations/claude-code-plugin/skills/search/SKILL.md +++ b/integrations/claude-code-plugin/skills/search/SKILL.md @@ -20,7 +20,9 @@ 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 -monorepo), `mine` for your own preferences alone. Pass `run_id` with a Claude -Code session ID to look at what one earlier session recorded, for example to -pick up where a compacted or closed session left off. Return the tool's result -directly. +monorepo), `mine` for your own preferences alone. + +Pass `run_id` with any scope to retrieve memories saved in a specific coding-agent +session. Omit `run_id` to search across sessions. It filters the memories returned; +it does not identify the session making the search request. Use a known session ID, +never invent one. Return the tool's result directly. diff --git a/integrations/claude-code-plugin/skills/status/SKILL.md b/integrations/claude-code-plugin/skills/status/SKILL.md index ef572549c..ed5e49b3f 100644 --- a/integrations/claude-code-plugin/skills/status/SKILL.md +++ b/integrations/claude-code-plugin/skills/status/SKILL.md @@ -9,8 +9,8 @@ disable-model-invocation: false Run both commands and report the combined result in plain language: ```bash -python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" status --json -python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" doctor +python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" --harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" status --json +python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" --harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" doctor ``` Summarize, using only fields the JSON actually reports: whether capture is diff --git a/integrations/claude-code-plugin/tests/conftest.py b/integrations/claude-code-plugin/tests/conftest.py index 85245a5ee..a5b795951 100644 --- a/integrations/claude-code-plugin/tests/conftest.py +++ b/integrations/claude-code-plugin/tests/conftest.py @@ -1,7 +1,20 @@ -"""Keep the test suite from sending usage telemetry to the live PostHog project.""" +"""Configure harness identity and disable live telemetry for the test suite.""" from __future__ import annotations import os +import sys +from pathlib import Path os.environ["MEM0_TELEMETRY"] = "false" + +HOST_ROOT = Path(__file__).resolve().parents[1] +_core = HOST_ROOT / "core" +sys.path.insert(0, str(_core)) + +import hook_runner # noqa: E402,F401 +from memory_core import configure_harness # noqa: E402 +import telemetry # noqa: E402 + +configure_harness("claude-code", data_dir_name="claude-code-plugin", source_tag="claude_code_plugin") +telemetry.init(harness="claude-code", source_tag="CLAUDE_CODE_PLUGIN") diff --git a/integrations/claude-code-plugin/tests/integration/test_live_scoping.py b/integrations/claude-code-plugin/tests/integration/test_live_scoping.py index da223f5c8..90542868f 100644 --- a/integrations/claude-code-plugin/tests/integration/test_live_scoping.py +++ b/integrations/claude-code-plugin/tests/integration/test_live_scoping.py @@ -13,10 +13,11 @@ from pathlib import Path import pytest PLUGIN_ROOT = Path(__file__).resolve().parents[2] -sys.path.insert(0, str(PLUGIN_ROOT / "core")) -sys.path.insert(0, str(PLUGIN_ROOT / "adapters" / "claude")) +_core_dir = PLUGIN_ROOT / "core" +sys.path.insert(0, str(_core_dir)) +sys.path.insert(0, str(PLUGIN_ROOT)) -import hook # noqa: E402 +import hook_runner # noqa: E402 import memory_core # noqa: E402 pytestmark = pytest.mark.skipif( @@ -177,15 +178,17 @@ def test_shared_project_memory_reaches_a_teammate_who_never_wrote(ns): def test_repo_scope_spans_every_subdirectory(ns): found = ns.search("erin", ns.root, "how many times are Stripe webhooks retried", scope="repo") assert "stripe" in _text(found) - app_ids = {m.get("app_id") for m in found} - assert any(app.endswith("/services/billing") for app in app_ids) + assert any("services/billing" in (memory.get("metadata") or {}).get("dirs", []) for memory in found) def test_dir_scope_narrows_shared_memory_to_the_directory(ns): billing = ns.root / "services" / "billing" found = ns.search("erin", billing, "how do I run the tests here", scope="dir") assert "billing-test" in _text(found) - assert {m.get("app_id") for m in found if m.get("agent_id")} == {memory_core.directory_app_id(memory_core.resolve_repo(str(billing)))} + shared = [memory for memory in found if memory.get("agent_id")] + assert shared + assert {memory.get("app_id") for memory in shared} == {memory_core.resolve_repo(str(billing)).app_id} + assert all("services/billing" in (memory.get("metadata") or {}).get("dirs", []) for memory in shared) web = ns.root / "apps" / "web" elsewhere = ns.search("erin", web, "Stripe webhook retries exponential backoff", scope="dir", tries=1) @@ -232,7 +235,7 @@ def test_a_pending_packet_is_recovered_and_delivered_by_the_worker(ns): stale.write_text(json.dumps({"hook_input": {"session_id": sid, "cwd": str(ns.root)}, "reason": "session-end"})) os.utime(stale, (time.time() - 3600, time.time() - 3600)) - assert hook.recover_pending_handoffs() == 1 + assert hook_runner.recover_pending_handoffs() == 1 deadline = time.time() + 240 while time.time() < deadline and list(pending.iterdir()): time.sleep(3) diff --git a/integrations/claude-code-plugin/tests/test_claude_build.py b/integrations/claude-code-plugin/tests/test_claude_build.py new file mode 100644 index 000000000..46ccfb206 --- /dev/null +++ b/integrations/claude-code-plugin/tests/test_claude_build.py @@ -0,0 +1,35 @@ +from __future__ import annotations + +import sys +from pathlib import Path + +HOST = Path(__file__).resolve().parents[1] +CORE_ROOT = HOST.parent / "agent-plugin-core" +sys.path.insert(0, str(CORE_ROOT)) + +from build.build import SHARED_SKILLS, build, render_template # noqa: E402 + + +def test_native_claude_bundle_preserves_working_contract(tmp_path: Path) -> None: + root = build("claude-code", "native", tmp_path / "claude-code") + + assert (root / ".claude-plugin" / "plugin.json").read_bytes() == ( + HOST / ".claude-plugin" / "plugin.json" + ).read_bytes() + assert (root / ".mcp.json").read_bytes() == (HOST / ".mcp.json").read_bytes() + assert (root / "hooks" / "hooks.json").read_bytes() == (HOST / "hooks" / "hooks.json").read_bytes() + assert (root / "agents" / "sidekick.md").read_bytes() == (HOST / "agents" / "sidekick.md").read_bytes() + values = { + "PLUGIN_ROOT": "${CLAUDE_PLUGIN_ROOT}", + "PLUGIN_DATA": "${PLUGIN_DATA}", + "PLUGIN_DATA_ARG": '--plugin-data-dir "${CLAUDE_PLUGIN_DATA}"', + "COMMAND_PREFIX": "mem0", + "HARNESS_ID": "claude-code", + "HARNESS_NAME": "Claude Code", + } + for skill in SHARED_SKILLS.glob("*/SKILL.md.tmpl"): + rendered = render_template(skill.read_text(encoding="utf-8"), values) + assert (root / "skills" / skill.parent.name / "SKILL.md").read_text(encoding="utf-8") == rendered + assert (root / "adapters" / "claude" / "hook.py").is_file() + assert (root / "core" / "mcp_server.py").is_file() + assert not any(path.is_symlink() for path in root.rglob("*")) diff --git a/integrations/claude-code-plugin/tests/test_memory_core.py b/integrations/claude-code-plugin/tests/test_memory_core.py index 23bf72f8a..6c91b7299 100644 --- a/integrations/claude-code-plugin/tests/test_memory_core.py +++ b/integrations/claude-code-plugin/tests/test_memory_core.py @@ -11,16 +11,18 @@ from unittest.mock import patch import pytest - -PLUGIN_ROOT = Path(__file__).resolve().parents[1] -CORE = PLUGIN_ROOT / "core" -ADAPTER = PLUGIN_ROOT / "adapters" / "claude" +HOST_ROOT = Path(__file__).resolve().parents[1] +REPOSITORY_ROOT = HOST_ROOT.parents[1] +PLUGIN_ROOT = HOST_ROOT +CORE = HOST_ROOT / "core" +ADAPTER = HOST_ROOT / "adapters" / "claude" / "hook.py" sys.path.insert(0, str(CORE)) -sys.path.insert(0, str(ADAPTER)) +sys.path.insert(0, str(ADAPTER.parent)) -import memory_core # noqa: E402 -import memory_cli # noqa: E402 import mcp_server # noqa: E402 +import memory_cli # noqa: E402 +import memory_core # noqa: E402 +import transcript as transcript_mod # noqa: E402 @pytest.fixture @@ -54,6 +56,14 @@ def repo() -> memory_core.RepoContext: ) +def test_portable_plugin_uses_standard_data_directory(tmp_path, monkeypatch): + monkeypatch.delenv("MEM0_CODE_DATA_DIR", raising=False) + monkeypatch.delenv("CLAUDE_PLUGIN_DATA", raising=False) + monkeypatch.setenv("PLUGIN_DATA", str(tmp_path)) + + assert memory_core.data_dir() == tmp_path + + def _write_transcript(path: Path, session_id: str, entries: list[dict]) -> None: parent = None rows = [] @@ -235,7 +245,7 @@ def test_transcript_extraction_keeps_meaningful_messages_and_excludes_raw_tools( ], ) - messages, leaf, _ = memory_core.transcript_extraction_messages( + messages, leaf, _ = transcript_mod.transcript_extraction_messages( str(transcript), "s1" ) serialized = json.dumps(messages) @@ -335,7 +345,7 @@ def test_transcript_extraction_pairs_background_agent_notification(tmp_path): ], ) - messages, _, _ = memory_core.transcript_extraction_messages( + messages, _, _ = transcript_mod.transcript_extraction_messages( str(transcript), "s1", previous_leaf_uuid="launch-result" ) serialized = json.dumps(messages) @@ -388,7 +398,7 @@ def test_transcript_extraction_omits_claude_ui_messages_but_keeps_attachments( ], ) - messages, _, _ = memory_core.transcript_extraction_messages( + messages, _, _ = transcript_mod.transcript_extraction_messages( str(transcript), "s1", prompt_hint="The attached issue says repository scope is wrong." ) serialized = json.dumps(messages) @@ -487,7 +497,7 @@ def test_transcript_extraction_uses_active_branch_and_omits_rejected_plan(tmp_pa "".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8" ) - messages, leaf, _ = memory_core.transcript_extraction_messages( + messages, leaf, _ = transcript_mod.transcript_extraction_messages( str(transcript), "s1" ) serialized = json.dumps(messages) @@ -525,7 +535,7 @@ def test_record_stop_processes_only_new_transcript_entries( store, {"session_id": "s1", "cwd": "/tmp/repo", "prompt": "Inspect the parser."}, ) - memory_core.record_stop( + transcript_mod.record_stop( store, { "session_id": "s1", @@ -562,7 +572,7 @@ def test_record_stop_processes_only_new_transcript_entries( "prompt": "Where is that implemented?", }, ) - memory_core.record_stop( + transcript_mod.record_stop( store, { "session_id": "s1", @@ -591,7 +601,7 @@ def test_record_stop_processes_only_new_transcript_entries( ] -def test_extraction_messages_keep_long_content(): +def test_extraction_messages_preserve_long_content(): long_response = "repository detail " * 4000 structured = { "extraction_messages": [ @@ -605,10 +615,47 @@ def test_extraction_messages_keep_long_content(): assert messages == [ {"role": "user", "content": "Explain the repository."}, - {"role": "assistant", "content": long_response}, + {"role": "assistant", "content": long_response.strip()}, ] +@pytest.mark.parametrize("capture", ["hook", "transcript"]) +def test_long_conversation_reaches_extraction_without_truncation(isolated_env, monkeypatch, capture): + import hook_runner + + monkeypatch.setenv("MEM0_API_KEY", "test-key") + monkeypatch.setattr(memory_core, "resolve_repo", lambda cwd: repo()) + prompt = "Repository question. " * 2000 + "Final user requirement. api_key=hidden-user-secret" + answer = "Repository answer. " * 4000 + "Final implementation detail. password=hidden-agent-secret" + payload = {"session_id": "s1", "cwd": "/tmp/repo", "prompt": prompt, "last_assistant_message": answer} + store = memory_core.EvidenceStore() + memory_core.record_user_prompt(store, payload) + if capture == "transcript": + transcript = isolated_env / "long-session.jsonl" + _write_transcript(transcript, "s1", [ + {"type": "user", "message": {"role": "user", "content": prompt}}, + {"type": "assistant", "message": {"role": "assistant", "content": answer}}, + ]) + transcript_mod.record_stop(store, {**payload, "transcript_path": str(transcript)}) + else: + hook_runner.default_record_stop(store, payload) + + with ( + patch.object(memory_core, "_request_json", return_value=({"event_id": "extraction"}, 200, 20)) as request, + patch.object(memory_core, "_wait_for_event", return_value=("SUCCEEDED", 20, 1)), + ): + assert memory_core.flush_session(store, payload, "session-end")["status"] == "semantic-succeeded" + + batches = [call.args[2]["messages"] for call in request.call_args_list] + assert len(batches) > 1 + assert all(memory_core._message_tokens(batch) <= memory_core.MAX_EXTRACTION_INPUT_TOKENS for batch in batches) + for role, text in (("user", prompt), ("assistant", answer)): + actual = "".join(message["content"] for batch in batches for message in batch if message["role"] == role) + prefix = "Main Claude response:\n" if capture == "transcript" and role == "assistant" else "" + assert actual == prefix + memory_core.redact(text) + store.close() + + def test_upgrade_removes_legacy_snapshot_tables(isolated_env): database = Path(os.environ["MEM0_CODE_DATA_DIR"]) / "evidence.sqlite3" database.parent.mkdir(parents=True, exist_ok=True) @@ -863,6 +910,20 @@ def test_common_tokens_and_private_keys_are_redacted(): assert "private-material" not in value +def test_json_shaped_secrets_are_redacted(): + value = memory_core.redact('{"apiKey": "sk-secret-12345", "name": "test"}') + assert "sk-secret-12345" not in value + assert "[REDACTED]" in value + assert '"name": "test"' in value + + value = memory_core.redact('{"password": "hunter2", "count": 1}') + assert "hunter2" not in value + + value = memory_core.redact('{"secret_access_key": "ABCDEFGHIJ1234567890", "region": "us-east-1"}') + assert "ABCDEFGHIJ1234567890" not in value + assert '"region": "us-east-1"' in value + + def test_remote_identity_removes_embedded_credentials(): normalized = memory_core._normalize_remote( "https://secret-token@github.com/example/repo.git" @@ -896,6 +957,49 @@ def test_repo_scope_matches_the_previous_plugin_mapping( assert resolved.app_id == "customer-platform" +def test_different_git_hosts_produce_different_project_ids(): + github = memory_core._project_id("/tmp/repo", "https://github.com/acme/api", "acme-api") + gitlab = memory_core._project_id("/tmp/repo", "https://gitlab.internal/acme/api", "acme-api") + + assert github != gitlab + assert github.startswith("acme-api-") + assert gitlab.startswith("acme-api-") + + +@pytest.mark.parametrize("scope", ["repo", "dir", "mine"]) +def test_upgraded_repo_search_retrieves_legacy_and_current_shared_memories(isolated_env, monkeypatch, scope): + from dataclasses import replace + + monkeypatch.setenv("MEM0_API_KEY", "test-key") + project = replace(repo(), project_id=memory_core._project_id(repo().root, repo().identity, repo().app_id)) + records = [ + {"id": "legacy", "agent_id": project.app_id, "app_id": project.app_id}, + {"id": "current", "agent_id": project.project_id, "app_id": project.app_id}, + {"id": "personal", "user_id": "test-user", "app_id": project.app_id}, + {"id": "teammate", "user_id": "someone-else", "app_id": project.app_id}, + {"id": "other-app", "agent_id": project.app_id, "app_id": "another-repo"}, + {"id": "other-host", "agent_id": "code-example-other-host", "app_id": project.app_id}, + ] + + def matches(record, filters): + for key, value in filters.items(): + if key == "AND": + return all(matches(record, child) for child in value) + if key == "OR": + return any(matches(record, child) for child in value) + if record.get(key) != value: + return False + return True + + def search(url, key, payload, timeout): + return {"results": [record for record in records if matches(record, payload["filters"])]}, 0, 0 + + monkeypatch.setattr(memory_core, "_request_json_with_network_retry", search) + result = memory_core.search_memories(None, project, None, "prior work", scope=scope) + expected = {"personal"} if scope == "mine" else {"legacy", "current", "personal"} + assert {memory["id"] for memory in result.memories} == expected + + def test_non_git_session_keeps_starting_project_scope_after_nested_commands( isolated_env, ): @@ -1061,32 +1165,32 @@ def test_forced_checkpoint_sends_an_incomplete_remainder(isolated_env): def test_stop_schedules_one_background_checkpoint_when_block_is_ready( isolated_env, ): - import hook + import hook_runner store = memory_core.EvidenceStore() for number in range(1, 5): _record_exchange(store, number) with ( - patch.object(hook, "api_key", return_value="m0-test-key"), - patch.object(hook, "hand_off_flush") as handoff, + patch.object(hook_runner, "api_key", return_value="m0-test-key"), + patch.object(hook_runner, "hand_off_flush") as handoff, ): assert ( - hook.schedule_periodic_checkpoint( + hook_runner.schedule_periodic_checkpoint( store, {"session_id": "s1", "cwd": "/tmp/repo"}, repo(), "s1" ) is False ) _record_exchange(store, 5) assert ( - hook.schedule_periodic_checkpoint( + hook_runner.schedule_periodic_checkpoint( store, {"session_id": "s1", "cwd": "/tmp/repo"}, repo(), "s1" ) is True ) _record_exchange(store, 6) assert ( - hook.schedule_periodic_checkpoint( + hook_runner.schedule_periodic_checkpoint( store, {"session_id": "s1", "cwd": "/tmp/repo"}, repo(), "s1" ) is False @@ -1100,64 +1204,64 @@ def test_stop_schedules_one_background_checkpoint_when_block_is_ready( def test_stop_schedules_idle_flush_when_periodic_not_due(isolated_env): - import hook + import hook_runner store = memory_core.EvidenceStore() _record_exchange(store, 1) hook_input = {"session_id": "s1", "cwd": "/tmp/repo"} with ( - patch.object(hook, "api_key", return_value="m0-test-key"), - patch.object(hook, "_launch_handoff", return_value=True) as launch, + patch.object(hook_runner, "api_key", return_value="m0-test-key"), + patch.object(hook_runner, "_launch_handoff", return_value=True) as launch, ): - assert not hook.schedule_periodic_checkpoint(store, hook_input, repo(), "s1") - assert hook.schedule_idle_flush(store, hook_input, repo(), "s1") + assert not hook_runner.schedule_periodic_checkpoint(store, hook_input, repo(), "s1") + assert hook_runner.schedule_idle_flush(store, hook_input, repo(), "s1") payload = json.loads(launch.call_args.args[0].read_text(encoding="utf-8")) assert payload["reason"] == "idle" - assert payload["delay_seconds"] == hook.DEFAULT_IDLE_FLUSH_SECONDS + assert payload["delay_seconds"] == hook_runner.DEFAULT_IDLE_FLUSH_SECONDS store.close() def test_idle_flush_skipped_when_inflight_flush_exists(isolated_env): - import hook + import hook_runner store = memory_core.EvidenceStore() for number in range(1, 6): _record_exchange(store, number) hook_input = {"session_id": "s1", "cwd": "/tmp/repo"} - with patch.object(hook, "api_key", return_value="m0-test-key"): + with patch.object(hook_runner, "api_key", return_value="m0-test-key"): store.prepare_flush(repo(), "s1", "periodic") - assert not hook.schedule_idle_flush(store, hook_input, repo(), "s1") + assert not hook_runner.schedule_idle_flush(store, hook_input, repo(), "s1") store.close() def test_idle_flush_skipped_when_no_unflushed_events(isolated_env): - import hook + import hook_runner store = memory_core.EvidenceStore() hook_input = {"session_id": "s1", "cwd": "/tmp/repo"} - with patch.object(hook, "api_key", return_value="m0-test-key"): - assert not hook.schedule_idle_flush(store, hook_input, repo(), "s1") + with patch.object(hook_runner, "api_key", return_value="m0-test-key"): + assert not hook_runner.schedule_idle_flush(store, hook_input, repo(), "s1") store.close() def test_idle_flush_skipped_when_disabled(isolated_env, monkeypatch): - import hook + import hook_runner store = memory_core.EvidenceStore() _record_exchange(store, 1) monkeypatch.setenv("MEM0_CODE_IDLE_FLUSH_SECONDS", "0") hook_input = {"session_id": "s1", "cwd": "/tmp/repo"} - with patch.object(hook, "api_key", return_value="m0-test-key"): - assert not hook.schedule_idle_flush(store, hook_input, repo(), "s1") + with patch.object(hook_runner, "api_key", return_value="m0-test-key"): + assert not hook_runner.schedule_idle_flush(store, hook_input, repo(), "s1") store.close() def test_stop_hook_falls_through_to_idle_flush(isolated_env, monkeypatch): - import hook + import hook_runner store = memory_core.EvidenceStore() _record_exchange(store, 1) @@ -1166,7 +1270,7 @@ def test_stop_hook_falls_through_to_idle_flush(isolated_env, monkeypatch): periodic_called = [] idle_called = [] - original_periodic = hook.schedule_periodic_checkpoint + original_periodic = hook_runner.schedule_periodic_checkpoint def mock_periodic(*a, **kw): result = original_periodic(*a, **kw) @@ -1178,14 +1282,17 @@ def test_stop_hook_falls_through_to_idle_flush(isolated_env, monkeypatch): return True with ( - patch.object(hook, "api_key", return_value="m0-test-key"), - patch.object(hook, "schedule_periodic_checkpoint", side_effect=mock_periodic), - patch.object(hook, "schedule_idle_flush", side_effect=mock_idle), - patch.object(hook, "record_stop", return_value=(repo(), "s1")), + patch.object(hook_runner, "api_key", return_value="m0-test-key"), + patch.object(hook_runner, "schedule_periodic_checkpoint", side_effect=mock_periodic), + patch.object(hook_runner, "schedule_idle_flush", side_effect=mock_idle), ): monkeypatch.setattr("sys.stdin", __import__("io").StringIO(json.dumps(hook_input))) monkeypatch.setattr("sys.argv", ["hook.py", "stop"]) - hook.main() + hook_runner.run( + record_stop_fn=lambda s, h: (repo(), "s1"), + data_dir_env="MEM0_CODE_DATA_DIR", + automatic_flush_reasons={"session-end", "pre-compact"}, + ) assert periodic_called == [False] assert idle_called == [True] @@ -1228,6 +1335,136 @@ def test_flush_worker_sleeps_for_delay_seconds(isolated_env, monkeypatch): assert "delay_seconds" not in rewritten_content +def test_session_end_worker_does_not_repeat_captured_final_response(isolated_env, monkeypatch): + import flush_worker + + monkeypatch.setenv("MEM0_API_KEY", "test-key") + monkeypatch.setattr(memory_core, "resolve_repo", lambda cwd: repo()) + store = memory_core.EvidenceStore() + for index in range(5): + store.record_event(repo(), "s1", "user_prompt", {"text": f"Earlier prompt {index}"}) + store.record_event(repo(), "s1", "assistant_stop", {"text": f"Earlier answer {index}"}) + first_packet, _ = store.prepare_flush(repo(), "s1", "periodic") + store.update_flush(first_packet, status="semantic-queued", semantic_event_id="earlier-extraction") + + prompt = "How does the serializer handle dates?" + answer = "The serializer preserves timezone-naive dates." + transcript = isolated_env / "session.jsonl" + _write_transcript(transcript, "s1", [ + {"type": "user", "message": {"role": "user", "content": prompt}}, + {"type": "assistant", "message": {"role": "assistant", "content": answer}}, + ]) + hook_input = { + "session_id": "s1", "cwd": "/tmp/repo", + "transcript_path": str(transcript), "last_assistant_message": answer, + } + memory_core.record_user_prompt(store, {**hook_input, "prompt": prompt}) + transcript_mod.record_stop(store, hook_input) + # SessionEnd captures again before handing off, using the same transcript cursor. + transcript_mod.record_stop(store, hook_input) + handoff = isolated_env / "session-end.running" + handoff.write_text(json.dumps({ + "hook_input": hook_input, "reason": "session-end", "wait_for_inflight": True, + })) + monkeypatch.setattr(sys, "argv", ["flush_worker.py", str(handoff)]) + monkeypatch.setenv("MEM0_CODE_HANDOFF_PATH", str(handoff)) + monkeypatch.setattr(flush_worker.time, "sleep", lambda seconds: store.update_flush( + first_packet, status="semantic-succeeded", + )) + with ( + patch.object(memory_core, "_request_json", return_value=({"event_id": "final-extraction"}, 200, 20)) as request, + patch.object(memory_core, "_wait_for_event", return_value=("SUCCEEDED", 20, 1)), + ): + assert flush_worker.main() == 0 + + assert request.call_count == 1 + messages = request.call_args.args[2]["messages"] + assert sum(prompt in message["content"] for message in messages) == 1 + assert sum(answer in message["content"] for message in messages) == 1 + assert not handoff.exists() + store.close() + + +def test_default_stop_records_each_exchange_once_across_repeated_hooks(isolated_env, monkeypatch): + import hook_runner + + monkeypatch.setattr(memory_core, "resolve_repo", lambda cwd: repo()) + store = memory_core.EvidenceStore() + hook_input = {"session_id": "s1", "cwd": "/tmp/repo", "last_assistant_message": "The parser uses UTC."} + for _ in range(2): + memory_core.record_user_prompt(store, {**hook_input, "prompt": "What timezone does the parser use?"}) + hook_runner.default_record_stop(store, hook_input) + # A tool notification and a flush must not make a repeated Stop look like a new answer. + store.record_event(repo(), "s1", "tool_result", {"tool": "Read"}) + packet, _ = store.prepare_flush(repo(), "s1", "session-end") + store.update_flush(packet, status="semantic-succeeded") + hook_runner.default_record_stop(store, hook_input) + + responses = store.conn.execute("SELECT payload_json FROM events WHERE kind = 'assistant_stop'").fetchall() + assert [json.loads(row[0])["text"] for row in responses] == ["The parser uses UTC."] * 2 + assert not store.has_unflushed_events(repo().identity, "s1") + store.close() + + +def test_concurrent_response_hooks_record_one_answer(isolated_env): + from concurrent.futures import ThreadPoolExecutor + from threading import Barrier + + store = memory_core.EvidenceStore() + store.record_event(repo(), "s1", "user_prompt", {"text": "Inspect the parser."}) + ready = Barrier(2) + + def capture(): + connection = memory_core.EvidenceStore(store.path) + try: + ready.wait(timeout=5) + connection.record_assistant_response(repo(), "s1", "The parser uses UTC.") + finally: + connection.close() + + with ThreadPoolExecutor(max_workers=2) as workers: + list(workers.map(lambda _: capture(), range(2))) + assert store.conn.execute("SELECT COUNT(*) FROM events WHERE kind = 'assistant_stop'").fetchone()[0] == 1 + store.record_assistant_response(repo(), "s1", "The serializer also uses UTC.") + store.record_assistant_response(repo(), "s2", "The parser uses UTC.") + assert store.conn.execute("SELECT COUNT(*) FROM events WHERE kind = 'assistant_stop'").fetchone()[0] == 3 + store.close() + + +def test_flush_worker_restores_harness_identity_from_child_environment(isolated_env, monkeypatch): + import flush_worker + + handoff_path = Path(os.environ["MEM0_CODE_DATA_DIR"]) / "pending" / "kimi.running" + handoff_path.parent.mkdir(parents=True, exist_ok=True) + handoff_path.write_text( + json.dumps({"hook_input": {"session_id": "s1", "cwd": "/tmp/repo"}}), + encoding="utf-8", + ) + monkeypatch.setenv("MEM0_PLUGIN_HARNESS", "kimi") + monkeypatch.setenv("MEM0_PLUGIN_ENV_PREFIX", "MEM0_KIMI") + monkeypatch.setenv("MEM0_PLUGIN_DATA_DIR_NAME", "kimi-plugin") + monkeypatch.setenv("MEM0_PLUGIN_SOURCE_TAG", "kimi_plugin") + monkeypatch.setattr("sys.argv", ["flush_worker.py", str(handoff_path)]) + + with ( + patch.object(flush_worker, "configure_harness", wraps=memory_core.configure_harness) as configure, + patch.object(flush_worker.telemetry, "init") as telemetry_init, + patch.object(flush_worker, "checkpoint_session", return_value={"status": "nothing-to-flush"}), + ): + flush_worker.main() + + configure.assert_called_once_with( + "kimi", + env_prefix="MEM0_KIMI", + data_dir_name="kimi-plugin", + source_tag="kimi_plugin", + ) + telemetry_init.assert_called_once_with(harness="kimi", source_tag="KIMI_PLUGIN") + memory_core.configure_harness( + "claude-code", data_dir_name="claude-code-plugin", source_tag="claude_code_plugin" + ) + + def test_launch_handoff_resolves_flush_worker_under_core(isolated_env): """hook.py lives in adapters/claude/; flush_worker.py lives in core/. @@ -1235,7 +1472,7 @@ def test_launch_handoff_resolves_flush_worker_under_core(isolated_env): sibling of hook.py, or every background flush launches against a nonexistent path. """ - import hook + import hook_runner data_dir_path = Path(os.environ["MEM0_CODE_DATA_DIR"]) pending_dir = data_dir_path / "pending" @@ -1243,13 +1480,18 @@ def test_launch_handoff_resolves_flush_worker_under_core(isolated_env): handoff_path = pending_dir / "test-handoff.json" handoff_path.write_text("{}", encoding="utf-8") - with patch.object(hook.subprocess, "Popen") as popen: - assert hook._launch_handoff(handoff_path) is True + with patch.object(hook_runner.subprocess, "Popen") as popen: + assert hook_runner._launch_handoff(handoff_path) is True launched_args = popen.call_args.args[0] worker_path = Path(launched_args[1]) assert worker_path == CORE / "flush_worker.py" assert worker_path.is_file() + child_env = popen.call_args.kwargs["env"] + assert child_env["MEM0_PLUGIN_HARNESS"] == "claude-code" + assert child_env["MEM0_PLUGIN_DATA_DIR_NAME"] == "claude-code-plugin" + assert child_env["MEM0_PLUGIN_SOURCE_TAG"] == "claude_code_plugin" + assert child_env["MEM0_CODE_DATA_DIR"] == os.environ["MEM0_CODE_DATA_DIR"] def test_flush_worker_detaches_on_windows_as_well_as_posix(monkeypatch): @@ -1258,30 +1500,30 @@ def test_flush_worker_detaches_on_windows_as_well_as_posix(monkeypatch): Without a creationflags fallback the worker stays attached to Claude's console on Windows and background extraction can die with the session. """ - import hook + import hook_runner - assert hook.detached_process_kwargs("darwin") == {"start_new_session": True} - assert hook.detached_process_kwargs("linux") == {"start_new_session": True} + assert hook_runner.detached_process_kwargs("darwin") == {"start_new_session": True} + assert hook_runner.detached_process_kwargs("linux") == {"start_new_session": True} monkeypatch.setattr(subprocess, "DETACHED_PROCESS", 0x00000008, raising=False) monkeypatch.setattr( subprocess, "CREATE_NEW_PROCESS_GROUP", 0x00000200, raising=False ) - windows_kwargs = hook.detached_process_kwargs("win32") + windows_kwargs = hook_runner.detached_process_kwargs("win32") assert windows_kwargs == {"creationflags": 0x00000208} assert "start_new_session" not in windows_kwargs def test_launch_handoff_always_requests_detachment(isolated_env): - import hook + import hook_runner pending_dir = Path(os.environ["MEM0_CODE_DATA_DIR"]) / "pending" pending_dir.mkdir(parents=True, exist_ok=True) handoff_path = pending_dir / "detach-handoff.json" handoff_path.write_text("{}", encoding="utf-8") - with patch.object(hook.subprocess, "Popen") as popen: - assert hook._launch_handoff(handoff_path) is True + with patch.object(hook_runner.subprocess, "Popen") as popen: + assert hook_runner._launch_handoff(handoff_path) is True assert popen.call_args.kwargs["start_new_session"] is True @@ -1294,23 +1536,23 @@ def test_pending_recovery_is_capped_and_leaves_the_rest_for_next_session( Each worker can block for MEM0_CODE_EXTRACTION_WAIT_SECONDS, so an uncapped launch is a thundering herd at session start. """ - import hook + import hook_runner pending_dir = Path(os.environ["MEM0_CODE_DATA_DIR"]) / "pending" pending_dir.mkdir(parents=True, exist_ok=True) - for number in range(hook.PENDING_LAUNCH_LIMIT + 3): + for number in range(hook_runner.PENDING_LAUNCH_LIMIT + 3): (pending_dir / f"packet-{number}.json").write_text("{}", encoding="utf-8") - with patch.object(hook.subprocess, "Popen"): - launched = hook.recover_pending_handoffs() + with patch.object(hook_runner.subprocess, "Popen"): + launched = hook_runner.recover_pending_handoffs() - assert launched == hook.PENDING_LAUNCH_LIMIT - assert len(list(pending_dir.glob("*.running"))) == hook.PENDING_LAUNCH_LIMIT + assert launched == hook_runner.PENDING_LAUNCH_LIMIT + assert len(list(pending_dir.glob("*.running"))) == hook_runner.PENDING_LAUNCH_LIMIT assert len(list(pending_dir.glob("*.json"))) == 3 def test_pending_recovery_drops_packets_past_the_expiry_window(isolated_env): - import hook + import hook_runner pending_dir = Path(os.environ["MEM0_CODE_DATA_DIR"]) / "pending" pending_dir.mkdir(parents=True, exist_ok=True) @@ -1319,11 +1561,11 @@ def test_pending_recovery_drops_packets_past_the_expiry_window(isolated_env): fresh = pending_dir / "fresh.json" fresh.write_text("{}", encoding="utf-8") - stale_time = time.time() - hook.PENDING_EXPIRY_SECONDS - 60 + stale_time = time.time() - hook_runner.PENDING_EXPIRY_SECONDS - 60 os.utime(expired, (stale_time, stale_time)) - with patch.object(hook.subprocess, "Popen"): - launched = hook.recover_pending_handoffs() + with patch.object(hook_runner.subprocess, "Popen"): + launched = hook_runner.recover_pending_handoffs() assert launched == 1 assert not expired.exists() @@ -2061,7 +2303,7 @@ def test_format_context_labels_memories_from_non_main_branches(): def test_sidekick_instructions_reject_unrequested_related_changes(): - prompt = (Path(__file__).parents[1] / "agents" / "sidekick.md").read_text() + 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 @@ -2121,6 +2363,36 @@ def test_sidekick_reuses_parent_memory_once_and_records_lifecycle( store.close() +def test_sidekick_stop_without_agent_id_closes_latest_matching_run(isolated_env): + store = memory_core.EvidenceStore() + start_input = { + "session_id": "s1", + "cwd": "/tmp/repo", + "agent_id": "agent-123", + "agent_type": "sidekick", + } + + with patch.object(memory_core, "resolve_repo", return_value=repo()): + memory_core.record_sidekick_start(store, start_input) + memory_core.record_sidekick_stop( + store, + { + "session_id": "s1", + "cwd": "/tmp/repo", + "agent_type": "sidekick", + "last_assistant_message": "Done.", + }, + ) + + rows = store.conn.execute("SELECT agent_id, stopped_at, final_message FROM sidekick_runs").fetchall() + store.close() + + assert len(rows) == 1 + assert rows[0]["agent_id"] == "agent-123" + assert rows[0]["stopped_at"] + assert rows[0]["final_message"] == "Done." + + def test_search_once_per_session_avoids_repeated_remote_searches( isolated_env, monkeypatch ): @@ -2325,7 +2597,8 @@ def test_mcp_tool_contract_is_small_and_read_only(): "query", "top_k", "category", - "scope", "run_id", + "scope", + "run_id", } assert tool["inputSchema"]["required"] == ["query"] assert tool["inputSchema"]["properties"]["top_k"]["minimum"] == 1 @@ -2335,6 +2608,8 @@ def test_mcp_tool_contract_is_small_and_read_only(): ) assert tool["annotations"]["readOnlyHint"] is True assert tool["annotations"]["idempotentHint"] is True + assert "Claude" not in tool["description"] + assert "Claude" not in memory_core.PROJECT_MEMORY_INSTRUCTIONS def test_plugin_mcp_config_starts_the_local_server(): @@ -2430,6 +2705,51 @@ def test_mcp_tool_is_session_independent_and_returns_plain_memories( assert "project_knowledge" not in rendered +@pytest.mark.parametrize("scope", ["repo", "dir", "mine"]) +def test_mcp_search_passes_run_id_for_every_scope(isolated_env, monkeypatch, scope): + from dataclasses import replace + + monkeypatch.setenv("MEM0_API_KEY", "test-key") + project = replace(repo(), directory="src", project_id="code-example-hash") + monkeypatch.setattr(mcp_server, "resolve_repo", lambda cwd: project) + with patch.object( + memory_core, "_request_json_with_network_retry", return_value=({"results": []}, 0, 0) + ) as request: + mcp_server.call_search_memories({"query": "parser", "scope": scope}) + across_sessions = request.call_args.args[2]["filters"] + mcp_server.call_search_memories({"query": "parser", "scope": scope, "run_id": "session-42"}) + assert request.call_args.args[2]["filters"] == {"AND": [across_sessions, {"run_id": "session-42"}]} + + +def test_mcp_tool_uses_codex_workspace_metadata(isolated_env): + result = memory_core.MemorySearchResult( + succeeded=True, matched_count=0, already_shown_count=0, memories=[] + ) + request = { + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": { + "name": "search_memories", + "arguments": {"query": "parser"}, + "_meta": { + "x-codex-turn-metadata": { + "workspaces": {"/tmp/active-repository": {"has_changes": False}} + } + }, + }, + } + + with ( + patch.object(mcp_server, "resolve_repo", return_value=repo()) as resolve, + patch.object(mcp_server, "search_memories", return_value=result), + ): + response = mcp_server.handle_request(request) + + resolve.assert_called_once_with("/tmp/active-repository") + assert response["result"]["isError"] is False + + @pytest.mark.parametrize( "arguments, message", [ @@ -2438,7 +2758,8 @@ def test_mcp_tool_is_session_independent_and_returns_plain_memories( ({"query": "parser", "top_k": True}, "1 to 20"), ({"query": "parser", "category": "other"}, "supported categories"), ({"query": "parser", "threshold": 0.5}, "Unknown search argument"), - ({"query": "parser", "run_id": ""}, "run_id must be"), + ({"query": "parser", "run_id": " "}, "run_id must be a non-empty string"), + ({"query": "parser", "run_id": 42}, "run_id must be a non-empty string"), ], ) def test_mcp_tool_rejects_invalid_arguments(arguments, message): @@ -2447,7 +2768,7 @@ def test_mcp_tool_rejects_invalid_arguments(arguments, message): def test_search_skill_describes_memory_as_optional_starting_knowledge(): - prompt = (Path(__file__).parents[1] / "skills" / "search" / "SKILL.md").read_text() + prompt = (PLUGIN_ROOT / "skills" / "search" / "SKILL.md").read_text() normalized = " ".join(prompt.split()) assert "earlier work may already explain" in normalized @@ -2455,6 +2776,9 @@ def test_search_skill_describes_memory_as_optional_starting_knowledge(): assert "Call `search_memories` with the user's question" in normalized assert "Return the tool's result directly" in normalized assert "Run the search before repository exploration" not in normalized + assert "run_id" in normalized + assert "--run-id" in normalized + assert "Omit `run_id` to search across sessions" in normalized def test_control_skills_exposed(): @@ -2493,7 +2817,7 @@ def test_pause_skill_points_to_dedicated_resume_command(): def test_resume_skill_runs_cli_and_is_a_dedicated_command(): text = (PLUGIN_ROOT / "skills" / "resume" / "SKILL.md").read_text() assert "disable-model-invocation: true" in text - assert 'core/memory_cli.py" resume' in text + assert '--harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" resume' in text def test_remember_skill_acknowledges_without_write_api(): @@ -2591,7 +2915,7 @@ def _run_hook( env.pop("CLAUDE_PLUGIN_OPTION_API_KEY", None) env.pop("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY", None) return subprocess.run( - [sys.executable, str(ADAPTER / "hook.py"), action, *extra], + [sys.executable, str(ADAPTER), action, *extra], input=json.dumps(payload), text=True, capture_output=True, @@ -2774,7 +3098,7 @@ def test_first_user_prompt_searches_verbatim_and_returns_five_memories( for index in range(1, 7) ] - import hook + import hook_runner with ( patch.object(memory_core, "resolve_repo", return_value=repo()), @@ -2784,7 +3108,7 @@ def test_first_user_prompt_searches_verbatim_and_returns_five_memories( return_value=({"results": results}, 200, 600), ) as request, ): - output = hook.first_prompt_memory_output( + output = hook_runner.first_prompt_memory_output( store, {"session_id": "s1", "cwd": "/tmp/repo", "prompt": prompt}, ) @@ -2814,7 +3138,7 @@ def test_later_user_prompts_do_not_search_automatically(isolated_env, monkeypatc monkeypatch.setenv("MEM0_API_KEY", "m0-test-key") store = memory_core.EvidenceStore() - import hook + import hook_runner with ( patch.object(memory_core, "resolve_repo", return_value=repo()), @@ -2824,7 +3148,7 @@ def test_later_user_prompts_do_not_search_automatically(isolated_env, monkeypatc return_value=({"results": []}, 100, 20), ) as request, ): - first = hook.first_prompt_memory_output( + first = hook_runner.first_prompt_memory_output( store, { "session_id": "s1", @@ -2832,7 +3156,7 @@ def test_later_user_prompts_do_not_search_automatically(isolated_env, monkeypatc "prompt": "Where is ODS date formatting implemented?", }, ) - second = hook.first_prompt_memory_output( + second = hook_runner.first_prompt_memory_output( store, { "session_id": "s1", @@ -2853,7 +3177,7 @@ def test_manual_search_remains_available_after_automatic_search( monkeypatch.setenv("MEM0_API_KEY", "m0-test-key") store = memory_core.EvidenceStore() - import hook + import hook_runner with ( patch.object(memory_core, "resolve_repo", return_value=repo()), @@ -2878,7 +3202,7 @@ def test_manual_search_remains_available_after_automatic_search( ], ) as request, ): - hook.first_prompt_memory_output( + hook_runner.first_prompt_memory_output( store, { "session_id": "s1", @@ -2912,7 +3236,7 @@ def test_first_prompt_is_silent_when_all_matches_were_already_provided( } store.mark_injected("s1", repo().identity, [existing]) - import hook + import hook_runner with ( patch.object(memory_core, "resolve_repo", return_value=repo()), @@ -2922,7 +3246,7 @@ def test_first_prompt_is_silent_when_all_matches_were_already_provided( return_value=({"results": [existing]}, 100, 100), ), ): - output = hook.first_prompt_memory_output( + output = hook_runner.first_prompt_memory_output( store, { "session_id": "s1", @@ -2943,7 +3267,7 @@ def test_user_prompt_search_failure_still_records_evidence_and_emits_no_context( env["MEM0_API_KEY"] = "m0-test-key" env["MEM0_API_URL"] = "http://127.0.0.1:1" result = subprocess.run( - [sys.executable, str(ADAPTER / "hook.py"), "user-prompt"], + [sys.executable, str(ADAPTER), "user-prompt"], input=json.dumps( { "session_id": "s1", @@ -3027,7 +3351,7 @@ def test_plugin_entrypoints_share_explicit_claude_data_dir(tmp_path, monkeypatch sidekick = subprocess.run( [ sys.executable, - str(ADAPTER / "hook.py"), + str(ADAPTER), "sidekick-start", "--plugin-data-dir", str(canonical_data), @@ -3102,7 +3426,7 @@ def test_automatic_flush_can_be_disabled_for_external_harnesses(isolated_env): env["MEM0_API_KEY"] = "m0-test-key" start = subprocess.run( - [sys.executable, str(ADAPTER / "hook.py"), "user-prompt"], + [sys.executable, str(ADAPTER), "user-prompt"], input=json.dumps( {"session_id": "s1", "cwd": cwd, "prompt": "Inspect parser behavior."} ), @@ -3112,7 +3436,7 @@ def test_automatic_flush_can_be_disabled_for_external_harnesses(isolated_env): check=False, ) flushed = subprocess.run( - [sys.executable, str(ADAPTER / "hook.py"), "flush", "--reason", "session-end"], + [sys.executable, str(ADAPTER), "flush", "--reason", "session-end"], input=json.dumps({"session_id": "s1", "cwd": cwd}), text=True, capture_output=True, @@ -3136,12 +3460,29 @@ 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.0" - root = PLUGIN_ROOT.parents[1] + assert manifest["version"] == memory_core.PLUGIN_VERSION == "0.3.1" + root = REPOSITORY_ROOT for mp in (root / "marketplace.json", root / ".claude-plugin" / "marketplace.json"): entry = next(p for p in json.loads(mp.read_text())["plugins"] if p["name"] == "mem0") assert entry["version"] == memory_core.PLUGIN_VERSION assert entry["source"] == "./integrations/claude-code-plugin" + manifests = { + "cursor": ".cursor-plugin/plugin.json", + "codex": ".codex-plugin/plugin.json", + "kimi": "kimi.plugin.json", + "mem0-agent": "plugin.json", + } + for host, filename in manifests.items(): + manifest = json.loads((root / "integrations" / f"{host}-plugin" / filename).read_text()) + assert manifest["version"] == memory_core.PLUGIN_VERSION + for host in ("claude-code", "cursor", "codex", "kimi", "antigravity"): + descriptor = json.loads((root / "integrations" / f"{host}-plugin" / "plugin-build.json").read_text()) + assert descriptor["version"] == memory_core.PLUGIN_VERSION + for directory in (".cursor-plugin", ".kimi-plugin"): + marketplace = json.loads((root / directory / "marketplace.json").read_text()) + assert marketplace["plugins"][0]["version"] == memory_core.PLUGIN_VERSION + response = mcp_server.handle_request({"jsonrpc": "2.0", "id": 1, "method": "initialize"}) + assert response["result"]["serverInfo"]["version"] == memory_core.PLUGIN_VERSION def test_user_id_falls_back_to_the_windows_account_name(monkeypatch): @@ -3183,7 +3524,7 @@ def test_transcript_rows_resume_from_a_byte_offset(tmp_path): ], ) - rows, end, resumed = memory_core._transcript_rows(str(transcript)) + rows, end, resumed = transcript_mod._transcript_rows(str(transcript)) assert [row["uuid"] for row in rows] == ["entry-1", "entry-2"] assert end == transcript.stat().st_size assert resumed is False @@ -3201,12 +3542,12 @@ def test_transcript_rows_resume_from_a_byte_offset(tmp_path): handle.write(json.dumps(third_row) + "\n") handle.write('{"uuid": "partial-row"') - rows, end, resumed = memory_core._transcript_rows(str(transcript), first_size) + rows, end, resumed = transcript_mod._transcript_rows(str(transcript), first_size) assert [row["uuid"] for row in rows] == ["entry-3"] assert resumed is True assert end < transcript.stat().st_size - rows, _, resumed = memory_core._transcript_rows( + rows, _, resumed = transcript_mod._transcript_rows( str(transcript), transcript.stat().st_size + 100 ) assert [row["uuid"] for row in rows] == ["entry-1", "entry-2", "entry-3"] @@ -3235,7 +3576,7 @@ def test_record_stop_reads_the_transcript_from_the_stored_offset( store = memory_core.EvidenceStore() with patch.object(memory_core, "resolve_repo", return_value=repo()): - memory_core.record_stop( + transcript_mod.record_stop( store, { "session_id": "s1", @@ -3270,7 +3611,7 @@ def test_record_stop_reads_the_transcript_from_the_stored_offset( }, ] _write_transcript(transcript, "s1", second_entries) - original_rows = memory_core._transcript_rows + original_rows = transcript_mod._transcript_rows offsets = [] def spying_rows(path, offset=0): @@ -3279,9 +3620,9 @@ def test_record_stop_reads_the_transcript_from_the_stored_offset( with ( patch.object(memory_core, "resolve_repo", return_value=repo()), - patch.object(memory_core, "_transcript_rows", side_effect=spying_rows), + patch.object(transcript_mod, "_transcript_rows", side_effect=spying_rows), ): - memory_core.record_stop( + transcript_mod.record_stop( store, { "session_id": "s1", @@ -3355,7 +3696,7 @@ def test_event_poll_touches_the_worker_heartbeat(isolated_env, monkeypatch, tmp_ def test_paused_session_start_keeps_pending_packets_fresh(isolated_env): - import hook + import hook_runner pending_dir = Path(os.environ["MEM0_CODE_DATA_DIR"]) / "pending" pending_dir.mkdir(parents=True, exist_ok=True) @@ -3363,11 +3704,11 @@ def test_paused_session_start_keeps_pending_packets_fresh(isolated_env): held.write_text("{}", encoding="utf-8") claimed = pending_dir / "claimed.running" claimed.write_text("{}", encoding="utf-8") - stale_time = time.time() - hook.PENDING_EXPIRY_SECONDS - 60 + stale_time = time.time() - hook_runner.PENDING_EXPIRY_SECONDS - 60 for path in (held, claimed): os.utime(path, (stale_time, stale_time)) - hook.refresh_pending_handoffs() + hook_runner.refresh_pending_handoffs() assert held.stat().st_mtime > time.time() - 60 assert claimed.stat().st_mtime > time.time() - 60 @@ -3635,7 +3976,7 @@ def test_forget_only_touches_shared_project_memory_when_asked(monkeypatch, isola repo = memory_core.RepoContext( cwd="/x", root="/x", identity="x", app_id="repo-a", branch="main", head_sha="abc", project_id="repo-a" ) - listed = [({"results": []}, 0, 0), ({"results": [{"id": "shared-1"}]}, 0, 0)] + listed = [({"results": []}, 0, 0), ({"results": [{"id": "shared-1", "app_id": "repo-a"}]}, 0, 0)] with patch.object(memory_core, "_request_json", side_effect=listed) as request: with patch.object(memory_core, "_delete_memory", return_value=True): result = memory_core.forget_remote_repo(repo, include_project_memory=True) @@ -3647,6 +3988,36 @@ def test_forget_only_touches_shared_project_memory_when_asked(monkeypatch, isola assert result == {"status": "deleted", "deleted": 1} +@pytest.mark.parametrize("include_project", [False, True]) +def test_forget_includes_legacy_shared_memories_only_when_requested(monkeypatch, isolated_env, include_project): + from dataclasses import replace + + monkeypatch.setenv("MEM0_API_KEY", "test-key") + project = replace(repo(), project_id="code-example-hash") + listed = { + "test-user": [{"id": "personal", "app_id": project.app_id}], + project.project_id: [{"id": "current", "app_id": project.app_id}], + project.app_id: [ + {"id": "legacy", "app_id": project.app_id}, + {"id": "other-app", "app_id": "another-repo"}, + ], + } + + def request(url, key, payload, timeout): + identity = next(iter(payload["filters"].values())) + return {"results": listed[identity]}, 0, 0 + + with ( + patch.object(memory_core, "_request_json", side_effect=request), + patch.object(memory_core, "_delete_memory", return_value=True) as delete, + ): + result = memory_core.forget_remote_repo(project, include_project_memory=include_project) + + expected = {"personal", "current", "legacy"} if include_project else {"personal"} + assert {call.args[2] for call in delete.call_args_list} == expected + assert result == {"status": "deleted", "deleted": len(expected)} + + def test_forget_reports_partial_failures(monkeypatch, isolated_env): monkeypatch.setenv("MEM0_API_KEY", "test-key") repo = memory_core.RepoContext( @@ -4025,7 +4396,8 @@ def test_same_named_folders_at_different_paths_get_different_namespaces(): b = memory_core._project_id("/home/raj/marketing", "local:/home/raj/marketing", "marketing") assert a != b assert a.startswith("local-marketing-") and b.startswith("local-marketing-") - assert memory_core._project_id("/x", "https://github.com/acme/api", "acme-api") == "acme-api" + remote_id = memory_core._project_id("/x", "https://github.com/acme/api", "acme-api") + assert remote_id.startswith("acme-api-") and remote_id != "acme-api" def test_relative_directory_is_empty_at_the_root_and_posix_below(): @@ -4171,3 +4543,88 @@ def test_every_write_carries_the_session_run_id(isolated_env, monkeypatch): assert len(bodies) == 1 assert bodies[0]["run_id"] == "s1" store.close() + + +def test_shared_transcripts_redact_without_truncating_before_extraction(): + secret = '"password": "plain-private-value" ' + prompt = secret + 'x' * 20000 + answer = secret + '界' * 40000 + events = [ + {"kind": "user_prompt", "payload": {"text": prompt}}, + {"kind": "assistant_stop", "payload": {"transcript_messages": [ + {"role": "user", "content": prompt}, + {"role": "assistant", "content": answer}, + ]}}, + ] + _, structured = memory_core.build_episode(repo(), "s1", "packet", events) + messages = memory_core.build_extraction_messages(structured) + assert [message["role"] for message in messages] == ["user", "assistant"] + assert "plain-private-value" not in json.dumps(structured) + assert [message["content"] for message in messages] == [memory_core.redact(prompt), memory_core.redact(answer)] + + +@pytest.mark.parametrize("status", [400, 401, 403, 404, 422]) +def test_event_polling_fails_fast_on_permanent_http_errors(status): + error = memory_core.urllib.error.HTTPError("https://example.test", status, "rejected", {}, None) + with patch.object(memory_core, "_get_json", side_effect=error), patch.object(memory_core.time, "sleep") as sleep: + with pytest.raises(memory_core.urllib.error.HTTPError): + memory_core._wait_for_event("https://example.test", "test-key", "event") + sleep.assert_not_called() + + +def test_prepare_flush_locks_before_reading_events(isolated_env): + store = memory_core.EvidenceStore() + store.record_event(repo(), "s1", "user_prompt", {"text": "Explain this."}) + statements = [] + store.conn.set_trace_callback(statements.append) + store.prepare_flush(repo(), "s1", "session-end") + assert statements[0] == "BEGIN IMMEDIATE" + assert not store.conn.in_transaction + store.close() + + +def test_extraction_batches_bound_individual_messages_without_losing_text(): + content = '界\\"\n' * 1000 + messages = [{"role": "assistant", "content": content}] + batches = memory_core.extraction_message_batches(messages, max_tokens=200) + assert all(memory_core._message_tokens(batch) <= 200 for batch in batches) + assert ''.join(message['content'] for batch in batches for message in batch) == content + + +def test_overlapping_subagent_stop_without_id_does_not_guess(isolated_env): + store = memory_core.EvidenceStore() + store.start_sidekick(repo(), "s1", "first", "sidekick", 0) + store.start_sidekick(repo(), "s1", "second", "sidekick", 0) + stopped = store.stop_sidekick(repo(), "s1", "", "sidekick", "", "Uncorrelated response") + assert stopped not in {"first", "second"} + rows = store.conn.execute("SELECT agent_id, stopped_at, final_message FROM sidekick_runs").fetchall() + assert all(row["stopped_at"] is None for row in rows if row["agent_id"] in {"first", "second"}) + assert next(row for row in rows if row["agent_id"] == stopped)["final_message"] == "Uncorrelated response" + store.close() + + +def test_delayed_handoff_survives_failed_atomic_rewrite(isolated_env, monkeypatch): + import flush_worker + + path = isolated_env / "checkpoint.running" + original = {"delay_seconds": 10, "hook_input": {"session_id": "s1"}} + path.write_text(json.dumps(original)) + monkeypatch.setattr(sys, "argv", ["flush_worker.py", str(path)]) + replace = Path.replace + + def fail_temporary(source, target): + if source.suffix == ".tmp": + raise OSError("simulated disk failure") + return replace(source, target) + + with patch.object(Path, "replace", fail_temporary), patch.object(flush_worker, "checkpoint_session") as checkpoint: + with pytest.raises(OSError, match="simulated disk failure"): + flush_worker.main() + assert json.loads(path.with_suffix(".json").read_text()) == original + assert not list(isolated_env.glob("*.tmp")) + checkpoint.assert_not_called() + + +def test_json_secret_redaction_handles_escaped_quotes(): + value = json.dumps({"password": 'prefix"private suffix'}) + assert json.loads(memory_core.redact(value)) == {"password": "[REDACTED]"} diff --git a/integrations/claude-code-plugin/tests/test_telemetry.py b/integrations/claude-code-plugin/tests/test_telemetry.py index a36980426..0ae280b19 100644 --- a/integrations/claude-code-plugin/tests/test_telemetry.py +++ b/integrations/claude-code-plugin/tests/test_telemetry.py @@ -7,9 +7,8 @@ from unittest.mock import patch import pytest - -PLUGIN_ROOT = Path(__file__).resolve().parents[1] -CORE = PLUGIN_ROOT / "core" +HOST_ROOT = Path(__file__).resolve().parents[1] +CORE = HOST_ROOT / "core" sys.path.insert(0, str(CORE)) import memory_core # noqa: E402 @@ -77,6 +76,46 @@ def test_record_hashes_identifiers_and_keeps_no_content(isolated_env): assert "session-abcdef" not in serialized +def test_record_rejects_sensitive_properties_at_the_shared_boundary(isolated_env): + secret = "sk-eval-12345678901234567890" + telemetry.record( + "search", + prompt=f"remember {secret}", + query=secret, + api_key=secret, + user_id="private-user", + note=f"failure contained {secret}", + memory_count=2, + ) + + (event,) = spool_lines() + assert event["properties"]["memory_count"] == 2 + serialized = json.dumps(event) + assert secret not in serialized + assert "private-user" not in serialized + assert not {"prompt", "query", "api_key", "user_id"} & event["properties"].keys() + + +@pytest.mark.parametrize("key", ["password", "token", "secret", "authorization"]) +def test_record_removes_sensitive_keys_from_nested_lists(isolated_env, key): + secret = "sk-eval-12345678901234567890" + telemetry.record( + "search", + details=[ + {key: "plain-value", "count": 2}, + {"nested": {key.upper(): "plain-value", "ok": True}}, + [f"failure contained {secret}"], + ], + ) + + (event,) = spool_lines() + assert event["properties"]["details"] == [ + {"count": 2}, + {"nested": {"ok": True}}, + ["failure contained [REDACTED]"], + ] + + def test_record_stops_appending_past_the_spool_cap(isolated_env): spool = memory_core.data_dir() / "telemetry.jsonl" spool.parent.mkdir(parents=True, exist_ok=True) diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json new file mode 100644 index 000000000..916b72e66 --- /dev/null +++ b/integrations/codex-plugin/.codex-plugin/plugin.json @@ -0,0 +1,13 @@ +{ + "name": "mem0", + "version": "0.3.1", + "description": "Cross-session memory and token savings for coding agents.", + "author": { "name": "Mem0", "email": "support@mem0.ai" }, + "homepage": "https://docs.mem0.ai/integrations/codex", + "repository": "https://github.com/mem0ai/mem0", + "license": "Apache-2.0", + "keywords": ["memory", "coding-agents", "continual-learning", "token-efficiency"], + "skills": "./skills/", + "hooks": "./hooks/hooks.json", + "mcpServers": "./.mcp.json" +} diff --git a/integrations/codex-plugin/.mcp.json b/integrations/codex-plugin/.mcp.json new file mode 100644 index 000000000..00daa05bd --- /dev/null +++ b/integrations/codex-plugin/.mcp.json @@ -0,0 +1,19 @@ +{ + "mcpServers": { + "mem0": { + "type": "stdio", + "command": "python3", + "args": ["./core/mcp_server.py"], + "cwd": ".", + "env_vars": [ + "MEM0_API_KEY", + "MEM0_API_URL", + "MEM0_CODE_USER_ID", + "MEM0_USER_ID", + "MEM0_RESOLVED_USER_ID", + "MEM0_PROJECT_ID", + "MEM0_TELEMETRY" + ] + } + } +} diff --git a/integrations/codex-plugin/core/flush_worker.py b/integrations/codex-plugin/core/flush_worker.py new file mode 100644 index 000000000..6f7b9ecb2 --- /dev/null +++ b/integrations/codex-plugin/core/flush_worker.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Detached remote checkpoint worker. + +Claude Code may cancel SessionEnd hooks as a print-mode process exits. The hook +therefore persists its input first and launches this process in a new session. +""" + +from __future__ import annotations + +import json +import os +import sys +import time +from pathlib import Path + +import telemetry +from memory_core import ( + EvidenceStore, + checkpoint_session, + configure_harness, + touch_handoff_heartbeat, +) + + +def main() -> int: + if len(sys.argv) != 2: + return 2 + handoff_path = Path(sys.argv[1]) + os.environ["MEM0_CODE_HANDOFF_PATH"] = str(handoff_path) + harness = os.environ.get("MEM0_PLUGIN_HARNESS") + if harness: + source_tag = os.environ.get("MEM0_PLUGIN_SOURCE_TAG", "") + configure_harness( + harness, + env_prefix=os.environ.get("MEM0_PLUGIN_ENV_PREFIX", ""), + data_dir_name=os.environ.get("MEM0_PLUGIN_DATA_DIR_NAME", ""), + source_tag=source_tag, + ) + telemetry.init(harness=harness, source_tag=source_tag.upper()) + completed = False + try: + payload = json.loads(handoff_path.read_text(encoding="utf-8")) + delay = float(payload.get("delay_seconds") or 0) + if delay > 0: + payload.pop("delay_seconds", None) + temporary = handoff_path.with_suffix(f".{os.getpid()}.tmp") + try: + temporary.write_text(json.dumps(payload), encoding="utf-8") + temporary.replace(handoff_path) + finally: + temporary.unlink(missing_ok=True) + time.sleep(delay) + if not handoff_path.exists(): + return 0 + hook_input = payload.get("hook_input") or {} + reason = str(payload.get("reason") or "checkpoint") + wait_for_inflight = bool(payload.get("wait_for_inflight")) + store = EvidenceStore() + try: + if wait_for_inflight: + session_id = str( + hook_input.get("session_id") or "unknown-session" + ) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + deadline = time.monotonic() + float( + os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120") + ) + while ( + store.has_inflight_flush(repo.identity, session_id) + and time.monotonic() < deadline + ): + touch_handoff_heartbeat() + time.sleep(0.25) + # Hooks capture the conversation before handoff; the worker only flushes it. + result = checkpoint_session(store, hook_input, reason) + print(json.dumps(result, sort_keys=True), flush=True) + completed = result.get("status") in { + "semantic-succeeded", + "explicitly-stored", + "nothing-to-flush", + } + finally: + store.close() + return 0 + finally: + telemetry.flush() + if completed: + try: + handoff_path.unlink() + except OSError: + pass + elif handoff_path.suffix == ".running": + try: + handoff_path.replace(handoff_path.with_suffix(".json")) + except OSError: + pass + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/codex-plugin/core/hook_runner.py b/integrations/codex-plugin/core/hook_runner.py new file mode 100644 index 000000000..2a2adb557 --- /dev/null +++ b/integrations/codex-plugin/core/hook_runner.py @@ -0,0 +1,372 @@ +"""Shared hook orchestration for all Mem0 agent plugins.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +import uuid +from pathlib import Path + +import telemetry +from memory_core import ( + EvidenceStore, + _session_id, + api_key, + bounded, + cache_plugin_api_key, + checkpoint_session, + clear_stale_api_key_cache, + configure_harness, + data_dir, + detached_process_kwargs, + format_context, + harness_config, + record_session_start, + record_tool, + record_user_prompt, + redact, + search_memories, +) + +STALE_RUNNING_SECONDS = 300 +PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60 +PENDING_LAUNCH_LIMIT = 5 +DEFAULT_IDLE_FLUSH_SECONDS = 300 + +_core_dir: Path = Path(__file__).resolve().parent + + +def read_hook_input() -> dict: + try: + value = json.load(sys.stdin) + return value if isinstance(value, dict) else {} + except (json.JSONDecodeError, OSError): + return {} + + +def default_record_stop(store: EvidenceStore, hook_input: dict): + """Record the assistant's response without transcript parsing.""" + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + message = redact(hook_input.get("last_assistant_message", "")).strip() + if message: + store.record_assistant_response(repo, session_id, message) + return repo, session_id + + +def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict: + """Search once before the agent handles the first prompt in a session.""" + repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input) + if not is_first_prompt: + return {} + try: + minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20")) + except ValueError: + minimum_query_chars = 20 + if len(prompt.strip()) < max(minimum_query_chars, 1): + return {} + result = search_memories( + store, repo, session_id, bounded(prompt, 6000), + top_k=5, operation="first-prompt-search", timeout=2, + ) + if not result.memories: + return {} + context = format_context( + result.memories, + "Mem0 found these relevant memories from earlier work in this repository:", + ) + telemetry.record( + "context_injected", + repo=repo, session_id=session_id, trigger="first-prompt", + memory_count=len(result.memories), context_chars=len(context), + prompt_chars=len(prompt), + ) + return { + "hookSpecificOutput": { + "hookEventName": "UserPromptSubmit", + "additionalContext": context, + }, + } + + +def _launch_handoff(handoff_path: Path) -> bool: + running_path = handoff_path.with_suffix(".running") + try: + handoff_path.replace(running_path) + except OSError: + return False + worker = _core_dir / "flush_worker.py" + log_path = data_dir() / "flush-worker.log" + log_handle = open(log_path, "a", encoding="utf-8") + harness = harness_config() + child_env = os.environ.copy() + child_env.update( + { + "MEM0_CODE_DATA_DIR": str(data_dir()), + "MEM0_PLUGIN_HARNESS": harness["name"], + "MEM0_PLUGIN_ENV_PREFIX": harness["env_prefix"], + "MEM0_PLUGIN_DATA_DIR_NAME": harness["data_dir_name"], + "MEM0_PLUGIN_SOURCE_TAG": harness["source_tag"], + } + ) + try: + subprocess.Popen( + [sys.executable, str(worker), str(running_path)], + stdin=subprocess.DEVNULL, + stdout=log_handle, stderr=log_handle, + close_fds=True, + env=child_env, + **detached_process_kwargs(), + ) + finally: + log_handle.close() + return True + + +def recover_pending_handoffs() -> int: + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + now = time.time() + for running in pending_dir.glob("*.running"): + try: + if now - running.stat().st_mtime > STALE_RUNNING_SECONDS: + running.replace(running.with_suffix(".json")) + except OSError: + continue + recoverable = [] + for handoff in pending_dir.glob("*.json"): + try: + age = now - handoff.stat().st_mtime + except OSError: + continue + if age > PENDING_EXPIRY_SECONDS: + handoff.unlink(missing_ok=True) + continue + recoverable.append((age, handoff)) + recoverable.sort(key=lambda item: item[0], reverse=True) + launched = 0 + for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]: + launched += int(_launch_handoff(handoff)) + return launched + + +def refresh_pending_handoffs() -> None: + pending_dir = data_dir() / "pending" + if not pending_dir.is_dir(): + return + for pattern in ("*.json", "*.running"): + for handoff in pending_dir.glob(pattern): + try: + os.utime(handoff) + except OSError: + continue + + +def hand_off_flush( + hook_input: dict, reason: str, *, wait_for_inflight: bool = False, +) -> None: + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + material = ( + f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}" + ) + digest = hashlib.sha256(material.encode()).hexdigest()[:24] + handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json" + temporary_path = handoff_path.with_suffix(".tmp") + temporary_path.write_text( + json.dumps({ + "hook_input": hook_input, + "reason": reason, + "wait_for_inflight": wait_for_inflight, + }), + encoding="utf-8", + ) + temporary_path.replace(handoff_path) + _launch_handoff(handoff_path) + + +def automatic_flush_enabled() -> bool: + return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in { + "1", "true", "yes", "on", + } + + +def schedule_periodic_checkpoint( + store: EvidenceStore, hook_input: dict, repo, session_id: str, +) -> bool: + if ( + not automatic_flush_enabled() + or not api_key() + or not store.checkpoint_due(repo.identity, session_id) + ): + return False + if store.prepare_flush(repo, session_id, "periodic") is None: + return False + hand_off_flush(hook_input, "periodic") + return True + + +def _idle_flush_seconds() -> int: + try: + return max( + int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))), + 0, + ) + except ValueError: + return DEFAULT_IDLE_FLUSH_SECONDS + + +def schedule_idle_flush( + store: EvidenceStore, hook_input: dict, repo, session_id: str, +) -> bool: + delay = _idle_flush_seconds() + if delay <= 0 or not automatic_flush_enabled() or not api_key(): + return False + if store.has_inflight_flush(repo.identity, session_id): + return False + if not store.has_unflushed_events(repo.identity, session_id): + return False + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}" + digest = hashlib.sha256(material.encode()).hexdigest()[:24] + for old in pending_dir.glob(f"idle-{digest}*"): + old.unlink(missing_ok=True) + handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json" + temporary_path = handoff_path.with_suffix(".tmp") + temporary_path.write_text( + json.dumps({ + "hook_input": hook_input, + "reason": "idle", + "delay_seconds": delay, + }), + encoding="utf-8", + ) + temporary_path.replace(handoff_path) + _launch_handoff(handoff_path) + return True + + +def log_failure(exc: Exception) -> None: + try: + log_path = data_dir() / "plugin-errors.log" + with log_path.open("a", encoding="utf-8") as handle: + handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n") + except OSError: + pass + + +def run( + *, + record_stop_fn=None, + extra_actions: dict | None = None, + data_dir_env: str = "MEM0_PLUGIN_DATA_DIR", + automatic_flush_reasons: set | None = None, +) -> int: + if record_stop_fn is None: + record_stop_fn = default_record_stop + if automatic_flush_reasons is None: + automatic_flush_reasons = {"session-end"} + + base_actions = ["session-start", "user-prompt", "post-tool", "stop", "flush"] + all_actions = base_actions + list((extra_actions or {}).keys()) + + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=all_actions) + parser.add_argument("--reason", default="manual") + parser.add_argument("--plugin-data-dir", default="") + parser.add_argument("--harness", default="") + args = parser.parse_args() + + if args.harness: + configure_harness(args.harness) + telemetry.init(harness=args.harness) + + if args.plugin_data_dir: + os.environ[data_dir_env] = args.plugin_data_dir + + cache_plugin_api_key() + if args.action == "session-start": + clear_stale_api_key_cache() + + hook_input = read_hook_input() + store = EvidenceStore() + try: + if store.is_paused(): + if args.action == "session-start": + refresh_pending_handoffs() + telemetry.record("session_start", paused=True) + telemetry.spawn_flush() + return 0 + + if args.action == "session-start": + if telemetry.is_first_run(): + telemetry.record("install") + recovered = recover_pending_handoffs() + record_session_start(store, hook_input) + if recovered: + telemetry.record("handoff_recovered", count=recovered) + telemetry.spawn_flush() + elif args.action == "user-prompt": + output = first_prompt_memory_output(store, hook_input) + if output: + print(json.dumps(output)) + elif args.action == "post-tool": + record_tool(store, hook_input) + elif args.action == "stop": + repo, session_id = record_stop_fn(store, hook_input) + if not schedule_periodic_checkpoint(store, hook_input, repo, session_id): + schedule_idle_flush(store, hook_input, repo, session_id) + elif args.action == "flush": + automatic = args.reason in automatic_flush_reasons + if automatic and not automatic_flush_enabled(): + return 0 + if args.reason == "session-end": + record_stop_fn(store, hook_input) + if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1": + print(json.dumps(checkpoint_session(store, hook_input, args.reason))) + else: + session_id = str(hook_input.get("session_id") or "unknown-session") + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + already_running = store.has_inflight_flush(repo.identity, session_id) + if already_running and args.reason == "session-end": + hand_off_flush(hook_input, args.reason, wait_for_inflight=True) + elif not already_running and store.prepare_flush( + repo, session_id, args.reason, + ) is not None: + hand_off_flush(hook_input, args.reason) + elif extra_actions and args.action in extra_actions: + result = extra_actions[args.action](store, hook_input) + if result: + print(json.dumps(result)) + finally: + store.close() + return 0 + + +def entry_point( + *, + record_stop_fn=None, + extra_actions: dict | None = None, + data_dir_env: str = "MEM0_PLUGIN_DATA_DIR", + automatic_flush_reasons: set | None = None, +) -> None: + try: + raise SystemExit(run( + record_stop_fn=record_stop_fn, + extra_actions=extra_actions, + data_dir_env=data_dir_env, + automatic_flush_reasons=automatic_flush_reasons, + )) + except Exception as exc: + log_failure(exc) + raise SystemExit(0) + + +if __name__ == "__main__": + entry_point() diff --git a/integrations/codex-plugin/core/mcp_server.py b/integrations/codex-plugin/core/mcp_server.py new file mode 100644 index 000000000..036fbbdc9 --- /dev/null +++ b/integrations/codex-plugin/core/mcp_server.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Expose Mem0's memory search as one local coding-agent tool.""" + +from __future__ import annotations + +import json +import os +import sys +from typing import Any + +import telemetry +from memory_core import ( + CODING_MEMORY_CATEGORY_NAMES, + PLUGIN_VERSION, + SEARCH_SCOPES, + format_search_result, + resolve_repo, + search_memories, +) + +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." +) +TOOL_SCHEMA = { + "type": "object", + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 2000, + "description": "A direct question about earlier work in this repository.", + }, + "top_k": { + "type": "integer", + "minimum": 1, + "maximum": 20, + "description": "Maximum memories to return. Uses Mem0's configured default when omitted.", + }, + "category": { + "type": "string", + "enum": list(CODING_MEMORY_CATEGORY_NAMES), + "description": "Optional memory category. Omit to search every category.", + }, + "scope": { + "type": "string", + "enum": list(SEARCH_SCOPES), + "description": ( + "Which memories to search. 'repo' (default) is the whole repository's " + "shared memory plus your own preferences, 'dir' narrows the shared " + "part to the current directory, 'mine' is your preferences alone." + ), + }, + "run_id": { + "type": "string", + "minLength": 1, + "description": ( + "Optional coding-agent session ID. With any scope, restricts results to memories " + "saved in that session. Omit to recall memories across sessions." + ), + }, + }, + "required": ["query"], + "additionalProperties": False, +} + + +class ToolInputError(ValueError): + pass + + +def _validate_arguments( + arguments: Any, +) -> tuple[str, int | None, str | None, str | None, str | None]: + if not isinstance(arguments, dict): + raise ToolInputError("Search arguments must be an object.") + + unknown = set(arguments) - {"query", "top_k", "category", "scope", "run_id"} + if unknown: + raise ToolInputError(f"Unknown search argument: {sorted(unknown)[0]}") + + query = arguments.get("query") + if not isinstance(query, str) or not query.strip(): + raise ToolInputError("query must be a non-empty string.") + query = query.strip() + if len(query) > 2000: + raise ToolInputError("query must be at most 2,000 characters.") + + top_k = arguments.get("top_k") + if top_k is not None and ( + isinstance(top_k, bool) or not isinstance(top_k, int) or not 1 <= top_k <= 20 + ): + raise ToolInputError("top_k must be an integer from 1 to 20.") + + category = arguments.get("category") + if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES: + raise ToolInputError("category must be one of Mem0's supported categories.") + + scope = arguments.get("scope") + if scope is not None and scope not in SEARCH_SCOPES: + raise ToolInputError(f"scope must be one of {list(SEARCH_SCOPES)}.") + + run_id = arguments.get("run_id") + if run_id is not None: + if not isinstance(run_id, str) or not run_id.strip(): + raise ToolInputError("run_id must be a non-empty string.") + run_id = run_id.strip() + + return query, top_k, category, scope, run_id + + +def call_search_memories(arguments: Any, cwd: str | None = None) -> str: + query, top_k, category, scope, run_id = _validate_arguments(arguments) + repo = resolve_repo(cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()) + result = search_memories( + None, + repo, + None, + query, + top_k=top_k, + category=category, + scope=scope, + run_id=run_id, + operation="mcp-search", + ) + return format_search_result(result) + + +def _workspace_cwd(params: dict[str, Any]) -> str | None: + meta = params.get("_meta") + if not isinstance(meta, dict): + return None + metadata = meta.get("x-codex-turn-metadata") + if not isinstance(metadata, dict): + return None + workspaces = metadata.get("workspaces") or {} + if isinstance(workspaces, dict): + return next((path for path in workspaces if isinstance(path, str) and path), None) + return None + + +def _tool_response(text: str, *, is_error: bool = False) -> dict[str, Any]: + return { + "content": [{"type": "text", "text": text}], + "isError": is_error, + } + + +def handle_request(message: Any) -> dict[str, Any] | None: + if not isinstance(message, dict): + return None + request_id = message.get("id") + method = message.get("method") + + if method == "notifications/initialized": + return None + if method == "initialize": + requested = (message.get("params") or {}).get("protocolVersion") + return { + "jsonrpc": "2.0", + "id": request_id, + "result": { + "protocolVersion": requested or PROTOCOL_VERSION, + "capabilities": {"tools": {"listChanged": False}}, + "serverInfo": {"name": "mem0", "version": PLUGIN_VERSION}, + }, + } + if method == "ping": + return {"jsonrpc": "2.0", "id": request_id, "result": {}} + if method == "tools/list": + return { + "jsonrpc": "2.0", + "id": request_id, + "result": { + "tools": [ + { + "name": TOOL_NAME, + "description": TOOL_DESCRIPTION, + "inputSchema": TOOL_SCHEMA, + "annotations": { + "readOnlyHint": True, + "idempotentHint": True, + "openWorldHint": True, + }, + } + ] + }, + } + if method == "tools/call": + params = message.get("params") or {} + if params.get("name") != TOOL_NAME: + result = _tool_response("Unknown Mem0 tool.", is_error=True) + else: + try: + result = _tool_response( + call_search_memories(params.get("arguments"), _workspace_cwd(params)) + ) + except ToolInputError as exc: + result = _tool_response(str(exc), is_error=True) + except Exception: + result = _tool_response("Memory search failed.", is_error=True) + return {"jsonrpc": "2.0", "id": request_id, "result": result} + if request_id is None: + return None + return { + "jsonrpc": "2.0", + "id": request_id, + "error": {"code": -32601, "message": "Method not found"}, + } + + +def main() -> int: + for raw_line in sys.stdin: + try: + message = json.loads(raw_line) + response = handle_request(message) + except json.JSONDecodeError: + response = { + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32700, "message": "Parse error"}, + } + except Exception: + response = { + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32603, "message": "Internal error"}, + } + if response is not None: + sys.stdout.write(json.dumps(response, separators=(",", ":")) + "\n") + sys.stdout.flush() + telemetry.spawn_flush() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/codex-plugin/core/memory_cli.py b/integrations/codex-plugin/core/memory_cli.py new file mode 100644 index 000000000..595729feb --- /dev/null +++ b/integrations/codex-plugin/core/memory_cli.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Mem0 diagnostics and user controls.""" + +from __future__ import annotations + +import argparse +import json +import os + +import telemetry +from memory_core import ( + EvidenceStore, + api_key, + data_dir, + doctor, + forget_remote_repo, + configure_harness, + resolve_repo, + user_id, +) + + +def _print_status(value: dict) -> None: + last = value.get("last_operation") or {} + print(f"Mem0: {'paused' if value['paused'] else 'active'}") + print(f"Repository: {value['repo_id']}") + print(f"Local data: {value['data_dir']}") + print(f"API key: {'configured' if value['api_key_configured'] else 'missing'}") + print( + "Saved on this computer: " + f"{value['events']} session details, {value['flushes']} memory updates" + ) + print( + f"Used in this repository: {value['retrievals']} memories returned, " + f"{value['sidekick_runs']} sidekick runs" + ) + if last: + item_label = "" + if last["operation"] in {"flush", "flush-retry"}: + item_label = f", {last['item_count']} memories" + operation = ( + "memory update" + if last["operation"] in {"flush", "flush-retry"} + else last["operation"].replace("-", " ") + ) + print( + f"Last {operation}: " + f"{'succeeded' if last['success'] else 'failed'} " + f"({last['duration_ms']:.1f} ms{item_label})" + ) + sidekick = value.get("last_sidekick") or {} + if sidekick: + state = "finished" if sidekick.get("stopped_at") else "started" + print( + "Last sidekick: " + f"{state}, received {sidekick['context_chars']} characters of memory, " + f"agent {sidekick['agent_id']}" + ) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--plugin-data-dir", default="") + parser.add_argument("--harness", default="") + subparsers = parser.add_subparsers(dest="command", required=True) + + status = subparsers.add_parser("status") + status.add_argument("--json", action="store_true") + + doctor_parser = subparsers.add_parser("doctor") + doctor_parser.add_argument("--json", action="store_true") + + subparsers.add_parser("pause") + subparsers.add_parser("resume") + + forget = subparsers.add_parser("forget") + forget.add_argument("--remote", action="store_true") + forget.add_argument("--yes", action="store_true") + forget.add_argument("--include-project-memory", action="store_true") + + args = parser.parse_args() + if args.harness: + source_tag = f"{args.harness.replace('-', '_')}_plugin" + configure_harness(args.harness, source_tag=source_tag) + telemetry.init(harness=args.harness, source_tag=source_tag.upper()) + if args.plugin_data_dir: + os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir + store = EvidenceStore() + try: + repo = resolve_repo(os.getcwd()) + telemetry.record("control", repo=repo, action=args.command) + if args.command == "status": + result = { + **store.status(repo.identity), + "repo_id": repo.identity, + "app_id": repo.app_id, + "project_id": repo.project_id, + "directory": repo.directory, + "user_id": user_id(), + "data_dir": str(data_dir()), + "api_key_configured": bool(api_key()), + } + if args.json: + print(json.dumps(result, indent=2, default=str)) + else: + _print_status(result) + elif args.command == "doctor": + result = doctor(os.getcwd()) + if args.json: + print(json.dumps(result, indent=2, default=str)) + else: + for name, check in result["checks"].items(): + print( + f"{'PASS' if check['ok'] else 'FAIL'} {name}: {check['detail']}" + ) + return 0 if result["ok"] else 1 + elif args.command == "pause": + store.set_setting("paused", "true") + print("Mem0 stopped saving and searching memories.") + elif args.command == "resume": + store.set_setting("paused", "false") + print("Mem0 resumed saving and searching memories.") + elif args.command == "forget": + if not args.yes: + print( + "Refusing to delete data without --yes. Add --remote to also " + "delete this user/repository scope from Mem0." + ) + return 2 + remote_result = ( + forget_remote_repo( + repo, include_project_memory=args.include_project_memory + ) + if args.remote + else None + ) + local_result = store.forget_local_repo(repo.identity) + print( + json.dumps( + {"local": local_result, "remote": remote_result}, + indent=2, + default=str, + ) + ) + if remote_result and remote_result.get("status") == "error": + return 1 + finally: + store.close() + telemetry.spawn_flush() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/codex-plugin/core/memory_core.py b/integrations/codex-plugin/core/memory_core.py new file mode 100644 index 000000000..cf71196b8 --- /dev/null +++ b/integrations/codex-plugin/core/memory_core.py @@ -0,0 +1,2645 @@ +#!/usr/bin/env python3 +"""Shared core for Mem0 agent plugins. + +Hooks record small session details locally. When the agent compacts or ends the +session, Mem0 sends the useful parts to the platform so it can create memories. +The agent can search those memories during later work in the repository. +""" + +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import sqlite3 +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Iterable + +import telemetry + +DEFAULT_API_URL = "https://api.mem0.ai" +PLUGIN_VERSION = "0.3.1" + +_harness_name: str = "generic" +_harness_env_prefix: str = "MEM0_PLUGIN" +_harness_data_dir_name: str = "mem0-plugin" +_harness_source_tag: str = "mem0_plugin" + + +def configure_harness( + name: str, + env_prefix: str = "", + data_dir_name: str = "", + source_tag: str = "", +) -> None: + global _harness_name, _harness_env_prefix, _harness_data_dir_name, _harness_source_tag + _harness_name = name + _harness_env_prefix = env_prefix or f"MEM0_{name.upper().replace('-', '_')}" + _harness_data_dir_name = data_dir_name or f"{name}-plugin" + _harness_source_tag = source_tag or f"{name.replace('-', '_')}_plugin" + + +def harness_config() -> dict[str, str]: + return { + "name": _harness_name, + "env_prefix": _harness_env_prefix, + "data_dir_name": _harness_data_dir_name, + "source_tag": _harness_source_tag, + } + + +MAX_COMMAND_CHARS = 2000 +MAX_RESULT_CHARS = 2500 +MAX_EPISODE_CHARS = 12000 +CHECKPOINT_EXCHANGES = 5 +CHECKPOINT_MESSAGES = 10 +CHECKPOINT_SOURCE_CHARS = 40000 +DEFAULT_MAX_CONTEXT_CHARS = 4000 +MAX_EXTRACTION_INPUT_TOKENS = 24000 +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. + +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 current coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions. + +Write about the repository, not the user, assistant, session, or task. Do not save personal preferences. Do not save a memory that only states which repository, branch, or directory the session worked in. Do not include test results, documentation updates, release notes, or temporary state. + +If nothing useful was established, return no memories.""" + +PERSONAL_MEMORY_INSTRUCTIONS = """Save concise facts about the user that will help in any repository: preferred tools, package managers, languages, coding style, review and communication preferences, and anything the user explicitly asked to be remembered about themselves. + +Write in the third person about the user, not about the repository, the assistant, the session, or the task. Do not save repository facts, project decisions, commands, or what was built. + +Never save that the user has no preferences or that nothing was learned. If nothing was learned about the user, return no memories.""" + +CODING_MEMORY_CATEGORIES = [ + { + "project_knowledge": ( + "What the project is and how its code, APIs, data, files, and " + "components work." + ) + }, + { + "decisions_and_constraints": ( + "Why an approach was chosen, what must remain true, and rules future " + "work must follow." + ) + }, + { + "workflows": ( + "How to run, test, debug, deploy, configure, or otherwise work on the " + "project." + ) + }, + { + "problems_and_fixes": ( + "Bugs, failures, known pitfalls, their causes, and how to fix or avoid " + "them." + ) + }, + { + "results": ( + "Outcomes and measurements from tests, benchmarks, experiments, or " + "investigations." + ) + }, +] +CODING_MEMORY_CATEGORY_NAMES = tuple( + category_name + for category in CODING_MEMORY_CATEGORIES + for category_name in category +) + +TEST_COMMAND_RE = re.compile( + r"(?:^|\s)(?:pytest|py\.test|jest|vitest|go\s+test|cargo\s+test|" + r"npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|" + r"mvn\s+test|gradle\s+test|make\s+test)(?:\s|$)", + re.IGNORECASE, +) +BUILD_COMMAND_RE = re.compile( + r"(?:^|\s)(?:npm|pnpm|yarn)\s+(?:run\s+)?build(?:\s|$)|" + r"(?:^|\s)(?:cargo|go|mvn|gradle|make)\s+build(?:\s|$)", + re.IGNORECASE, +) + +SECRET_PATTERNS = [ + re.compile(r"(?i)(authorization\s*[:=]\s*(?:bearer|token)\s+)[^\s\"']+"), + re.compile( + r"(?i)((?:api[_-]?key|secret[_-]?access[_-]?key|session[_-]?token)\s*[:=]\s*)[^\s\"']+" + ), + re.compile( + r"(?i)((?:access[_-]?token|refresh[_-]?token|password|credential)" + r"\s*[:=]\s*)[^\s&\"']+" + ), + re.compile(r"\b(?:sk|m0|mem0_sk|psk)-[A-Za-z0-9_\-]{12,}\b"), + re.compile(r"\b(?:ASIA|AKIA)[A-Z0-9]{12,}\b"), + re.compile(r"\b(?:ghp_|github_pat_|xox[baprs]-)[A-Za-z0-9_\-]{12,}\b"), + re.compile( + r"-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----", + re.DOTALL, + ), + re.compile( + r'(?i)("(?:api[_-]?key|password|secret(?:[_-]?access[_-]?key)?' + r'|(?:access|refresh|session)[_-]?token|token|authorization|credential' + r')"\s*:\s*")(?:\\.|[^"\\])*' + ), +] + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def redact(value: Any) -> str: + text = ( + value + if isinstance(value, str) + else json.dumps(value, ensure_ascii=False, default=str) + ) + for pattern in SECRET_PATTERNS: + if pattern.groups: + text = pattern.sub(r"\1[REDACTED]", text) + else: + text = pattern.sub("[REDACTED]", text) + return text + + +def bounded(value: Any, limit: int) -> str: + text = redact(value).strip() + if len(text) <= limit: + return text + return text[:limit] + f"\n...[truncated {len(text) - limit} chars]" + + +def _git(cwd: str, *args: str) -> str: + try: + result = subprocess.run( + ["git", "-C", cwd, *args], + check=False, + capture_output=True, + text=True, + timeout=0.5, + ) + except (OSError, subprocess.TimeoutExpired): + return "" + return result.stdout.strip() if result.returncode == 0 else "" + + +def _normalize_remote(remote: str) -> str: + remote = remote.strip() + if remote.startswith("git@") and ":" in remote: + host_path = remote[4:].replace(":", "/", 1) + remote = f"https://{host_path}" + if remote.endswith(".git"): + remote = remote[:-4] + if "://" in remote: + parsed = urllib.parse.urlsplit(remote) + hostname = parsed.hostname or "" + if parsed.port: + hostname = f"{hostname}:{parsed.port}" + remote = urllib.parse.urlunsplit( + (parsed.scheme, hostname, parsed.path, parsed.query, parsed.fragment) + ) + return remote.rstrip("/") + + +_WILDCARD_SCOPE = re.compile(r"^\*+$") + + +def _scope_value(raw: str | None) -> str: + """Reject wildcards as identities: they are filter syntax and would widen the scope.""" + value = (raw or "").strip() + return "" if _WILDCARD_SCOPE.match(value) else value + + +SEARCH_SCOPES = ("repo", "dir", "mine") +DEFAULT_SEARCH_SCOPE = "repo" + +def directory_app_id(repo: RepoContext) -> str: + """The app_id of the directory this session runs in: the repository at the root, repository/path below it.""" + return f"{repo.app_id}/{repo.directory}" if repo.directory else repo.app_id + + +def directory_chain(repo: RepoContext) -> list[str]: + """Every directory a memory belongs to, from the top-level folder down to the one it was written in.""" + parts = repo.directory.split("/") if repo.directory else [] + return ["/".join(parts[: index + 1]) for index in range(len(parts))] + + +def _shared_project_ids(repo: RepoContext) -> list[str]: + """Current and pre-upgrade namespaces, shared by recall and explicit deletion.""" + if not repo.identity.startswith("local:") and repo.project_id != repo.app_id: + return [repo.project_id, repo.app_id] + return [repo.project_id] + + +def _search_filters(user: str, repo: RepoContext, scope: str) -> dict[str, Any]: + """Build the scope filter: app_id scopes to the repo, then union shared and personal lanes.""" + app_scope = {"app_id": repo.app_id} + mine = {"AND": [{"user_id": user}, app_scope]} + if scope == "mine": + return mine + projects = [{"AND": [{"agent_id": project_id}, app_scope]} for project_id in _shared_project_ids(repo)] + shared: dict[str, Any] = projects[0] if len(projects) == 1 else {"OR": projects} + if scope == "dir" and repo.directory: + shared = {"AND": [shared, {"metadata": {"dirs": {"contains": repo.directory}}}]} + return {"OR": [shared, mine]} + + +def search_scope() -> str: + configured = ( + _plugin_option("search_scope", "MEM0_CODE_SEARCH_SCOPE") or "" + ).strip().lower() + return configured if configured in SEARCH_SCOPES else DEFAULT_SEARCH_SCOPE + + +def resolve_search_scope(scope: str | None) -> str: + value = (scope or search_scope()).strip().lower() + if value not in SEARCH_SCOPES: + raise ValueError(f"Unknown search scope: {value}") + return value + + +def _legacy_project_map(cwd: str, root: str, raw_remote: str) -> str: + """Return the project name used by the previous Claude Code plugin.""" + try: + data = json.loads((Path.home() / ".mem0" / "project_map.json").read_text()) + except (OSError, json.JSONDecodeError): + return "" + if not isinstance(data, dict): + return "" + + keys = list(dict.fromkeys([cwd, root, os.path.realpath(cwd), os.path.realpath(root)])) + if raw_remote: + keys.append(f"remote:{hashlib.sha256(raw_remote.encode()).hexdigest()[:16]}") + for key in keys: + value = data.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + return "" + + +def _legacy_project_id(cwd: str, root: str, raw_remote: str, identity: str) -> str: + """Use the repository namespace created by the previous Mem0 plugin.""" + configured = _scope_value(os.environ.get("MEM0_PROJECT_ID")) + if configured: + return configured + + mapped = _scope_value(_legacy_project_map(cwd, root, raw_remote)) + if mapped: + return mapped + + remote = raw_remote or ("" if identity.startswith("local:") else identity) + remote = remote.strip().removesuffix(".git") + for prefix in ("https://", "http://", "ssh://", "git://"): + if remote.startswith(prefix): + remote = remote[len(prefix) :] + break + else: + remote = re.sub(r"^git@", "", remote) + parts = [part for part in remote.replace(":", "/", 1).split("/") if part] + if len(parts) >= 2: + return f"{parts[-2]}-{parts[-1]}".replace("/", "-").replace(":", "-") + if parts: + return parts[-1].replace("/", "-").replace(":", "-") + return os.path.basename(root or cwd) or "unknown" + + +@dataclass(frozen=True) +class RepoContext: + cwd: str + root: str + identity: str + app_id: str + branch: str + head_sha: str + project_id: str = "" + directory: str = "" + + +def _project_id(root: str, identity: str, app_id: str) -> str: + """The shared namespace: includes a host hash so repos with the same owner/name on different hosts stay apart.""" + if not identity.startswith("local:"): + return f"{app_id}-{hashlib.sha256(identity.encode()).hexdigest()[:10]}" + return f"local-{app_id}-{hashlib.sha256(root.encode()).hexdigest()[:10]}" + + +def _relative_directory(cwd: str, root: str) -> str: + relative = os.path.relpath(cwd, root) + return "" if relative == "." or relative.startswith("..") else relative.replace(os.sep, "/") + + +@dataclass(frozen=True) +class MemorySearchResult: + succeeded: bool + matched_count: int + already_shown_count: int + memories: list[dict[str, Any]] + + +@functools.lru_cache(maxsize=64) +def _resolve_repo_cached(cwd: str) -> RepoContext: + given_cwd = cwd + cwd = os.path.realpath(cwd) + given_root = _git(cwd, "rev-parse", "--show-toplevel") or given_cwd + root = os.path.realpath(given_root) + raw_remote = _git(root, "config", "--get", "remote.origin.url") + remote = _normalize_remote(raw_remote) + identity = remote or f"local:{root}" + app_id = _legacy_project_id(given_cwd, given_root, raw_remote, identity) + return RepoContext( + cwd=cwd, + root=root, + identity=identity, + app_id=app_id, + branch=_git(root, "branch", "--show-current") or "detached", + head_sha=_git(root, "rev-parse", "HEAD"), + project_id=_project_id(root, identity, app_id), + directory=_relative_directory(cwd, root), + ) + + +def resolve_repo(cwd: str | None) -> RepoContext: + return _resolve_repo_cached(os.path.abspath(cwd or os.getcwd())) + + +def api_key() -> str: + configured = ( + os.environ.get("MEM0_API_KEY") + or os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if configured: + return configured + try: + return (data_dir() / "api-key").read_text(encoding="utf-8").strip() + except OSError: + return "" + + +def cache_plugin_api_key() -> bool: + """Bridge host's hook-only sensitive config into plugin-owned storage.""" + configured = ( + os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if not configured: + return False + + directory = data_dir() + directory.mkdir(parents=True, exist_ok=True) + path = directory / "api-key" + temporary = directory / f"api-key.{os.getpid()}.tmp" + descriptor = os.open( + temporary, + os.O_WRONLY | os.O_CREAT | os.O_TRUNC, + 0o600, + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + handle.write(configured) + os.replace(temporary, path) + os.chmod(path, 0o600) + finally: + try: + temporary.unlink() + except FileNotFoundError: + pass + return True + + +def clear_stale_api_key_cache() -> bool: + """Drop the cached key file once every configured key source is gone.""" + configured = ( + os.environ.get("MEM0_API_KEY") + or os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if configured: + return False + path = data_dir() / "api-key" + if not path.exists(): + return False + try: + path.unlink() + except OSError: + return False + return True + + +def detached_process_kwargs(platform: str | None = None) -> dict: + """Keep a spawned worker alive after the coding agent exits, on POSIX and Windows.""" + if (platform or sys.platform) == "win32": + return { + "creationflags": subprocess.DETACHED_PROCESS + | subprocess.CREATE_NEW_PROCESS_GROUP + } + return {"start_new_session": True} + + +def _plugin_option(name: str, fallback: str = "") -> str: + return ( + os.environ.get(f"PLUGIN_OPTION_{name.upper()}") + or os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name.upper()}") + or os.environ.get(fallback) + or "" + ).strip() + + +def user_id() -> str: + return ( + _scope_value(_plugin_option("user_id", "MEM0_CODE_USER_ID")) + or _scope_value(os.environ.get("MEM0_USER_ID")) + or _scope_value(os.environ.get("MEM0_RESOLVED_USER_ID")) + or _scope_value(os.environ.get("USER")) + or _scope_value(os.environ.get("USERNAME")) + or "default" + ) + + +def data_dir() -> Path: + configured = ( + os.environ.get("MEM0_CODE_DATA_DIR") + or os.environ.get("MEM0_PLUGIN_DATA_DIR") + or os.environ.get("PLUGIN_DATA") + or os.environ.get("CLAUDE_PLUGIN_DATA") + ) + return ( + Path(configured).expanduser() if configured else Path.home() / ".mem0" / _harness_data_dir_name + ) + + +def _bool_option(name: str, fallback: str, default: bool = False) -> bool: + value = _plugin_option(name, fallback) + if not value: + return default + return value.lower() in {"1", "true", "yes", "on"} + + +def _int_option(name: str, fallback: str, default: int) -> int: + value = _plugin_option(name, fallback) + try: + return int(value) if value else default + except ValueError: + return default + + + +def _checkpoint_message(event: dict[str, Any]) -> str: + kind = event.get("kind") + payload = event.get("payload") or {} + if kind == "user_prompt": + return redact(payload.get("text", "")).strip() + if kind == "assistant_stop": + transcript_messages = payload.get("transcript_messages") or [] + if isinstance(transcript_messages, list): + text = "\n".join( + str(message.get("content") or "") + for message in transcript_messages + if isinstance(message, dict) and message.get("content") + ) + if text: + return text + return redact(payload.get("text", "")).strip() + if kind == "sidekick_stop": + return redact(payload.get("final_message", "")).strip() + return "" + + +def checkpoint_stats(events: list[dict[str, Any]]) -> tuple[int, int, int]: + """Return completed exchanges, messages, and source characters.""" + completed = sum(event.get("kind") == "assistant_stop" for event in events) + contents = [content for event in events if (content := _checkpoint_message(event))] + return completed, len(contents), sum(len(content) for content in contents) + + +def select_checkpoint_events( + events: list[dict[str, Any]], *, force: bool +) -> list[dict[str, Any]]: + """Select one ordered extraction block without splitting an exchange.""" + for index, event in enumerate(events): + if event.get("kind") != "assistant_stop": + continue + candidate = events[: index + 1] + completed, messages, source_chars = checkpoint_stats(candidate) + if ( + completed >= CHECKPOINT_EXCHANGES + or messages >= CHECKPOINT_MESSAGES + or source_chars >= CHECKPOINT_SOURCE_CHARS + ): + return candidate + return events if force else [] + + +class EvidenceStore: + def __init__(self, path: Path | None = None): + directory = data_dir() if path is None else path.parent + directory.mkdir(parents=True, exist_ok=True) + self.path = path or directory / "evidence.sqlite3" + try: + self._open() + except sqlite3.DatabaseError: + self._quarantine() + self._open() + + def _open(self) -> None: + self.conn = sqlite3.connect(self.path, timeout=10) + self.conn.row_factory = sqlite3.Row + try: + self.conn.execute("PRAGMA journal_mode=WAL") + self.conn.execute("PRAGMA busy_timeout=10000") + self._migrate() + except sqlite3.DatabaseError: + self.conn.close() + raise + + def _quarantine(self) -> None: + """Move an unreadable database aside so capture restarts cleanly.""" + stamp = int(time.time()) + for suffix in ("", "-wal", "-shm"): + source = Path(f"{self.path}{suffix}") + try: + source.replace(f"{self.path}.corrupt-{stamp}{suffix}") + except FileNotFoundError: + continue + except OSError: + try: + source.unlink() + except OSError: + pass + telemetry.record("db_quarantined") + + def close(self) -> None: + self.conn.close() + + def _migrate(self) -> None: + self.conn.executescript( + """ + CREATE TABLE IF NOT EXISTS events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + session_id TEXT NOT NULL, + created_at TEXT NOT NULL, + kind TEXT NOT NULL, + payload_json TEXT NOT NULL, + flush_id TEXT + ); + CREATE INDEX IF NOT EXISTS events_session_idx + ON events(repo_id, session_id, flush_id, id); + + CREATE TABLE IF NOT EXISTS session_scopes ( + session_id TEXT PRIMARY KEY, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + root TEXT NOT NULL, + branch TEXT NOT NULL, + head_sha TEXT NOT NULL, + created_at TEXT NOT NULL, + directory TEXT NOT NULL DEFAULT '' + ); + + CREATE TABLE IF NOT EXISTS flushes ( + packet_id TEXT PRIMARY KEY, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + session_id TEXT NOT NULL, + reason TEXT NOT NULL, + event_start INTEGER NOT NULL, + event_end INTEGER NOT NULL, + status TEXT NOT NULL, + episode_event_id TEXT, + semantic_event_id TEXT, + error TEXT, + attempts INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS retrievals ( + session_id TEXT NOT NULL, + repo_id TEXT NOT NULL, + memory_id TEXT NOT NULL, + injected_at TEXT NOT NULL, + rank INTEGER, + score REAL, + memory_text TEXT, + context_chars INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY(session_id, repo_id, memory_id) + ); + + CREATE TABLE IF NOT EXISTS operations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created_at TEXT NOT NULL, + repo_id TEXT NOT NULL, + session_id TEXT NOT NULL, + operation TEXT NOT NULL, + duration_ms REAL NOT NULL, + success INTEGER NOT NULL, + item_count INTEGER NOT NULL DEFAULT 0, + request_chars INTEGER NOT NULL DEFAULT 0, + response_chars INTEGER NOT NULL DEFAULT 0, + error TEXT + ); + + CREATE TABLE IF NOT EXISTS sidekick_runs ( + repo_id TEXT NOT NULL, + session_id TEXT NOT NULL, + agent_id TEXT NOT NULL, + agent_type TEXT NOT NULL, + started_at TEXT NOT NULL, + stopped_at TEXT, + transcript_path TEXT, + context_chars INTEGER NOT NULL DEFAULT 0, + final_message TEXT, + PRIMARY KEY(repo_id, session_id, agent_id) + ); + CREATE INDEX IF NOT EXISTS sidekick_runs_repo_idx + ON sidekick_runs(repo_id, started_at); + + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + """ + ) + # Remove the pre-0.1.1 no-tools snapshot implementation. The real coding + # sidekick is a native Claude Code agent and stores no state in this DB. + self.conn.executescript( + """ + DROP TABLE IF EXISTS sidekick_calls; + DROP TABLE IF EXISTS sidekick_snapshots; + DROP TABLE IF EXISTS sidekick_state; + DROP TABLE IF EXISTS sidekick_packets; + """ + ) + self._ensure_column("retrievals", "rank", "INTEGER") + self._ensure_column("retrievals", "score", "REAL") + self._ensure_column("retrievals", "memory_text", "TEXT") + self._ensure_column("retrievals", "context_chars", "INTEGER NOT NULL DEFAULT 0") + self._ensure_column("flushes", "attempts", "INTEGER NOT NULL DEFAULT 0") + self._ensure_column("session_scopes", "directory", "TEXT NOT NULL DEFAULT ''") + self.conn.commit() + + def _ensure_column(self, table: str, column: str, declaration: str) -> None: + columns = { + str(row["name"]) + for row in self.conn.execute(f"PRAGMA table_info({table})").fetchall() + } + if column not in columns: + self.conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {declaration}") + + def record_event( + self, + repo: RepoContext, + session_id: str, + kind: str, + payload: dict[str, Any], + ) -> int: + cursor = self.conn.execute( + """INSERT INTO events + (repo_id, app_id, session_id, created_at, kind, payload_json) + VALUES (?, ?, ?, ?, ?, ?)""", + ( + repo.identity, + repo.app_id, + session_id, + utc_now(), + kind, + json.dumps(payload, ensure_ascii=False, sort_keys=True), + ), + ) + self.conn.commit() + return int(cursor.lastrowid) + + def record_assistant_response(self, repo: RepoContext, session_id: str, message: str) -> None: + """Ignore repeated response hooks until another prompt or a different answer arrives.""" + with self.conn: + # Serialize the check and insert across concurrent Stop and SessionEnd hooks. + self.conn.execute("BEGIN IMMEDIATE") + previous = self.conn.execute( + """SELECT kind, payload_json FROM events + WHERE repo_id = ? AND session_id = ? AND kind IN ('user_prompt', 'assistant_stop') + ORDER BY id DESC LIMIT 1""", + (repo.identity, session_id), + ).fetchone() + if ( + previous is not None + and previous["kind"] == "assistant_stop" + and json.loads(previous["payload_json"]).get("text") == message + ): + return + self.record_event(repo, session_id, "assistant_stop", {"text": message}) + + def repo_for_session(self, session_id: str, cwd: str | None) -> RepoContext: + """Keep one project scope for every hook in a coding-agent session.""" + current = resolve_repo(cwd) + if session_id == "unknown-session": + return current + + with self.conn: + self.conn.execute( + """INSERT OR IGNORE INTO session_scopes + (session_id, repo_id, app_id, root, branch, head_sha, created_at, directory) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", + ( + session_id, + current.identity, + current.app_id, + current.root, + current.branch, + current.head_sha, + utc_now(), + current.directory, + ), + ) + scope = self.conn.execute( + "SELECT * FROM session_scopes WHERE session_id = ?", (session_id,) + ).fetchone() + same_git_repo = ( + current.identity == scope["repo_id"] and bool(current.head_sha) + ) + pinned = current if same_git_repo else resolve_repo(str(scope["root"])) + return RepoContext( + cwd=current.cwd, + root=pinned.root, + identity=str(scope["repo_id"]), + app_id=str(scope["app_id"]), + branch=pinned.branch, + head_sha=pinned.head_sha, + project_id=pinned.project_id, + directory=str(scope["directory"] or ""), + ) + + def prepare_flush( + self, repo: RepoContext, session_id: str, reason: str + ) -> tuple[str, list[dict[str, Any]]] | None: + with self.conn: + self.conn.execute("BEGIN IMMEDIATE") + existing = self.conn.execute( + """SELECT * FROM flushes + WHERE repo_id = ? AND session_id = ? + AND status NOT IN ('semantic-succeeded', 'explicitly-stored', 'gave-up') + ORDER BY created_at LIMIT 1""", + (repo.identity, session_id), + ).fetchone() + if existing and int(existing["attempts"] or 0) >= MAX_FLUSH_ATTEMPTS: + self.conn.execute( + "UPDATE flushes SET status = 'gave-up', updated_at = ? WHERE packet_id = ?", + (utc_now(), existing["packet_id"]), + ) + telemetry.record( + "flush", + repo=repo, + session_id=session_id, + reason=reason, + status="gave-up", + success=False, + attempts=int(existing["attempts"] or 0), + ) + existing = None + if existing: + if reason != "periodic" and existing["reason"] == "periodic": + self.conn.execute( + "UPDATE flushes SET reason = ?, updated_at = ? WHERE packet_id = ?", + (reason, utc_now(), existing["packet_id"]), + ) + existing_rows = self.conn.execute( + "SELECT * FROM events WHERE flush_id = ? ORDER BY id", + (existing["packet_id"],), + ).fetchall() + if existing_rows: + return str(existing["packet_id"]), [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in existing_rows + ] + + rows = self.conn.execute( + """SELECT * FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id""", + (repo.identity, session_id), + ).fetchall() + if not rows: + return None + + events = [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in rows + ] + events = select_checkpoint_events(events, force=reason != "periodic") + if not events: + return None + event_start, event_end = events[0]["id"], events[-1]["id"] + packet_material = f"{repo.identity}\0{session_id}\0{event_start}\0{event_end}" + packet_id = hashlib.sha256(packet_material.encode()).hexdigest()[:32] + now = utc_now() + + self.conn.execute( + """INSERT OR IGNORE INTO flushes + (packet_id, repo_id, app_id, session_id, reason, event_start, + event_end, status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, 'prepared', ?, ?)""", + ( + packet_id, + repo.identity, + repo.app_id, + session_id, + reason, + event_start, + event_end, + now, + now, + ), + ) + event_ids = [event["id"] for event in events] + placeholders = ", ".join("?" for _ in event_ids) + self.conn.execute( + f"UPDATE events SET flush_id = ? " + f"WHERE id IN ({placeholders}) AND flush_id IS NULL", + (packet_id, *event_ids), + ) + return packet_id, events + + def checkpoint_due(self, repo_id: str, session_id: str) -> bool: + if self.has_inflight_flush(repo_id, session_id): + return False + rows = self.conn.execute( + """SELECT * FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id""", + (repo_id, session_id), + ).fetchall() + events = [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in rows + ] + return bool(select_checkpoint_events(events, force=False)) + + def has_inflight_flush(self, repo_id: str, session_id: str) -> bool: + return ( + self.conn.execute( + """SELECT 1 FROM flushes + WHERE repo_id = ? AND session_id = ? + AND status IN ('prepared', 'semantic-queued') + LIMIT 1""", + (repo_id, session_id), + ).fetchone() + is not None + ) + + def flush_record(self, packet_id: str) -> dict[str, Any] | None: + row = self.conn.execute( + "SELECT * FROM flushes WHERE packet_id = ?", (packet_id,) + ).fetchone() + return dict(row) if row else None + + def has_unflushed_events(self, repo_id: str, session_id: str) -> bool: + return ( + self.conn.execute( + """SELECT 1 FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + LIMIT 1""", + (repo_id, session_id), + ).fetchone() + is not None + ) + + def unflushed_starts_with_session_start( + self, repo_id: str, session_id: str + ) -> bool: + row = self.conn.execute( + """SELECT kind FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id LIMIT 1""", + (repo_id, session_id), + ).fetchone() + return bool(row and row["kind"] == "session_start") + + def update_flush(self, packet_id: str, **fields: Any) -> None: + allowed = {"status", "episode_event_id", "semantic_event_id", "error"} + updates = {key: value for key, value in fields.items() if key in allowed} + updates["updated_at"] = utc_now() + clause = ", ".join(f"{key} = ?" for key in updates) + failed = str(fields.get("status", "")) in { + "error", + "semantic-failed", + "semantic-timeout", + "semantic-missing", + } + if failed: + clause += ", attempts = attempts + 1" + with self.conn: + self.conn.execute( + f"UPDATE flushes SET {clause} WHERE packet_id = ?", + [*updates.values(), packet_id], + ) + + def unseen( + self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]] + ) -> list[dict[str, Any]]: + seen = { + row["memory_id"] + for row in self.conn.execute( + "SELECT memory_id FROM retrievals WHERE session_id = ? AND repo_id = ?", + (session_id, repo_id), + ) + } + return [memory for memory in memories if str(memory.get("id", "")) not in seen] + + def mark_injected( + self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]] + ) -> None: + now = utc_now() + with self.conn: + for rank, memory in enumerate(memories, start=1): + memory_id = str(memory.get("id", "")) + if memory_id: + memory_text = bounded( + memory.get("memory") or memory.get("text") or "", + 4000, + ) + try: + score = float(memory["score"]) + except (KeyError, TypeError, ValueError): + score = None + self.conn.execute( + """INSERT OR IGNORE INTO retrievals + (session_id, repo_id, memory_id, injected_at, rank, + score, memory_text, context_chars) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", + ( + session_id, + repo_id, + memory_id, + now, + rank, + score, + memory_text, + len(memory_text), + ), + ) + + def injected_memories( + self, session_id: str, repo_id: str + ) -> list[dict[str, Any]]: + """Return the exact memories already supplied to the main conversation.""" + rows = self.conn.execute( + """SELECT memory_id, rank, score, memory_text + FROM retrievals + WHERE session_id = ? AND repo_id = ? + ORDER BY COALESCE(rank, 2147483647), injected_at, memory_id""", + (session_id, repo_id), + ).fetchall() + return [ + { + "id": row["memory_id"], + "memory": row["memory_text"], + "score": row["score"], + } + for row in rows + if row["memory_text"] + ] + + def start_sidekick( + self, + repo: RepoContext, + session_id: str, + agent_id: str, + agent_type: str, + context_chars: int, + ) -> bool: + """Record one native sidekick instance and whether context was first sent.""" + with self.conn: + cursor = self.conn.execute( + """INSERT OR IGNORE INTO sidekick_runs + (repo_id, session_id, agent_id, agent_type, started_at, + context_chars) + VALUES (?, ?, ?, ?, ?, ?)""", + ( + repo.identity, + session_id, + agent_id, + agent_type, + utc_now(), + context_chars, + ), + ) + return int(cursor.rowcount) > 0 + + def stop_sidekick( + self, + repo: RepoContext, + session_id: str, + agent_id: str, + agent_type: str, + transcript_path: str, + final_message: str, + ) -> str: + now = utc_now() + self.conn.execute("BEGIN IMMEDIATE") + try: + if not agent_id: + rows = self.conn.execute( + """SELECT agent_id FROM sidekick_runs + WHERE repo_id = ? AND session_id = ? AND agent_type = ? AND stopped_at IS NULL + LIMIT 2""", + (repo.identity, session_id, agent_type), + ).fetchall() + # Without a host ID, overlapping runs cannot be correlated reliably. + agent_id = rows[0]["agent_id"] if len(rows) == 1 else f"unknown-agent-{time.time_ns()}" + self.conn.execute( + """INSERT INTO sidekick_runs + (repo_id, session_id, agent_id, agent_type, started_at, + stopped_at, transcript_path, final_message) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(repo_id, session_id, agent_id) DO UPDATE SET + stopped_at = excluded.stopped_at, + transcript_path = excluded.transcript_path, + final_message = excluded.final_message""", + ( + repo.identity, + session_id, + agent_id, + agent_type, + now, + now, + bounded(transcript_path, 2000), + redact(final_message).strip(), + ), + ) + self.conn.commit() + except Exception: + self.conn.rollback() + raise + return agent_id + + def operation( + self, + repo: RepoContext, + session_id: str, + operation: str, + duration_ms: float, + success: bool, + *, + item_count: int = 0, + request_chars: int = 0, + response_chars: int = 0, + error: str = "", + ) -> None: + with self.conn: + self.conn.execute( + """INSERT INTO operations + (created_at, repo_id, session_id, operation, duration_ms, + success, item_count, request_chars, response_chars, error) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", + ( + utc_now(), + repo.identity, + session_id, + operation, + duration_ms, + int(success), + item_count, + request_chars, + response_chars, + bounded(error, 1000), + ), + ) + + def has_operation(self, repo_id: str, session_id: str, operation: str) -> bool: + row = self.conn.execute( + """SELECT 1 FROM operations + WHERE repo_id = ? AND session_id = ? AND operation = ? + LIMIT 1""", + (repo_id, session_id, operation), + ).fetchone() + return row is not None + + def has_event(self, repo_id: str, session_id: str, kind: str) -> bool: + row = self.conn.execute( + """SELECT 1 FROM events + WHERE repo_id = ? AND session_id = ? AND kind = ? + LIMIT 1""", + (repo_id, session_id, kind), + ).fetchone() + return row is not None + + def latest_event_payload( + self, repo_id: str, session_id: str, kind: str + ) -> dict[str, Any]: + row = self.conn.execute( + """SELECT payload_json FROM events + WHERE repo_id = ? AND session_id = ? AND kind = ? + ORDER BY id DESC LIMIT 1""", + (repo_id, session_id, kind), + ).fetchone() + if not row: + return {} + try: + payload = json.loads(row["payload_json"]) + except json.JSONDecodeError: + return {} + return payload if isinstance(payload, dict) else {} + + def setting(self, key: str, default: str = "") -> str: + row = self.conn.execute( + "SELECT value FROM settings WHERE key = ?", (key,) + ).fetchone() + return str(row["value"]) if row else default + + def set_setting(self, key: str, value: str) -> None: + with self.conn: + self.conn.execute( + """INSERT INTO settings(key, value, updated_at) + VALUES (?, ?, ?) + ON CONFLICT(key) DO UPDATE SET + value = excluded.value, + updated_at = excluded.updated_at""", + (key, value, utc_now()), + ) + + def is_paused(self) -> bool: + return self.setting("paused", "false").lower() in { + "1", + "true", + "yes", + "on", + } + + def forget_local_repo(self, repo_id: str) -> dict[str, int]: + tables = { + "events": "repo_id", + "session_scopes": "repo_id", + "flushes": "repo_id", + "retrievals": "repo_id", + "operations": "repo_id", + "sidekick_runs": "repo_id", + } + removed: dict[str, int] = {} + with self.conn: + for table, column in tables.items(): + cursor = self.conn.execute( + f"DELETE FROM {table} WHERE {column} = ?", (repo_id,) + ) + removed[table] = max(int(cursor.rowcount), 0) + return removed + + def status(self, repo_id: str) -> dict[str, Any]: + def count(table: str) -> int: + return int( + self.conn.execute( + f"SELECT COUNT(*) FROM {table} WHERE repo_id = ?", (repo_id,) + ).fetchone()[0] + ) + + last_operation = self.conn.execute( + """SELECT created_at, operation, duration_ms, success, item_count, error + FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""", + (repo_id,), + ).fetchone() + last_sidekick = self.conn.execute( + """SELECT session_id, agent_id, agent_type, started_at, stopped_at, + context_chars + FROM sidekick_runs WHERE repo_id = ? + ORDER BY started_at DESC LIMIT 1""", + (repo_id,), + ).fetchone() + return { + "paused": self.is_paused(), + "events": count("events"), + "flushes": count("flushes"), + "retrievals": count("retrievals"), + "sidekick_runs": count("sidekick_runs"), + "last_operation": dict(last_operation) if last_operation else None, + "last_sidekick": dict(last_sidekick) if last_sidekick else None, + } + + +def _session_id(hook_input: dict[str, Any]) -> str: + return str(hook_input.get("session_id") or "unknown-session") + + +def record_session_start(store: EvidenceStore, hook_input: dict[str, Any]) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + store.record_event( + repo, + session_id, + "session_start", + { + "source": hook_input.get("source", "startup"), + "model": bounded(hook_input.get("model", ""), 200), + "branch": repo.branch, + "head_sha": repo.head_sha, + }, + ) + telemetry.record( + "session_start", + repo=repo, + session_id=session_id, + trigger=bounded(str(hook_input.get("source", "startup")), 60), + model=bounded(hook_input.get("model", ""), 200), + api_key_configured=bool(api_key()), + is_git_repo=not repo.identity.startswith("local:"), + ) + + +def record_user_prompt( + store: EvidenceStore, hook_input: dict[str, Any] +) -> tuple[RepoContext, str, str, bool]: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + prompt = redact(hook_input.get("prompt", "")).strip() + is_first_prompt = not store.has_event(repo.identity, session_id, "user_prompt") + store.record_event(repo, session_id, "user_prompt", {"text": prompt}) + return repo, session_id, prompt, is_first_prompt + + +def _tool_result_preview(response: Any) -> str: + if isinstance(response, dict): + selected = {} + for key in ( + "stdout", + "stderr", + "output", + "content", + "error", + "filePath", + "success", + "interrupted", + ): + if key in response: + selected[key] = response[key] + response = selected or {"keys": sorted(response.keys())[:20]} + return bounded(response, MAX_RESULT_CHARS) + + +def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> dict[str, Any]: + name = str(hook_input.get("tool_name") or "unknown") + tool_input = hook_input.get("tool_input") or {} + if not isinstance(tool_input, dict): + tool_input = {} + payload: dict[str, Any] = { + "tool": name, + "failed": failed, + "duration_ms": hook_input.get("duration_ms"), + "agent_role": "sidekick" if hook_input.get("agent_id") else "main", + } + if hook_input.get("agent_id"): + payload["agent_id"] = bounded(hook_input["agent_id"], 200) + if hook_input.get("agent_type"): + payload["agent_type"] = bounded(hook_input["agent_type"], 200) + + if name in {"Read", "Write", "Edit", "MultiEdit", "NotebookEdit"}: + path = tool_input.get("file_path") or tool_input.get("notebook_path") + if path: + payload["path"] = bounded(path, 1000) + if name in {"Write", "Edit", "MultiEdit", "NotebookEdit"}: + payload["mutation_chars"] = sum( + len(str(tool_input.get(key, ""))) + for key in ("content", "new_string", "new_source", "edits") + ) + elif name == "Bash" or "command" in tool_input: + command = bounded(tool_input.get("command", ""), MAX_COMMAND_CHARS) + payload["command"] = command + payload["command_kind"] = ( + "test" + if TEST_COMMAND_RE.search(command) + else "build" + if BUILD_COMMAND_RE.search(command) + else "shell" + ) + response = ( + hook_input.get("error") if failed else hook_input.get("tool_response") + ) + payload["result_preview"] = _tool_result_preview(response) + elif name in {"Grep", "Glob", "WebSearch", "WebFetch"}: + for key in ("pattern", "path", "query", "url"): + if tool_input.get(key): + payload[key] = bounded(tool_input[key], 1000) + else: + payload["input_keys"] = sorted(tool_input.keys())[:20] + if failed: + payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS) + + if failed and "error" not in payload: + payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS) + return payload + + +def record_tool( + store: EvidenceStore, hook_input: dict[str, Any], *, failed: bool | None = False +) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + payload = tool_payload(hook_input, failed=failed) + if payload.get("path"): + payload["repo_path"] = _repo_relative_path(repo, str(payload["path"])) + store.record_event( + repo, + session_id, + "tool_failure" if failed else "tool_result", + payload, + ) + + +def record_sidekick_start( + store: EvidenceStore, hook_input: dict[str, Any], *, inject_context: bool = True +) -> str: + """Record a native sidekick and reuse the main turn's retrieved memories.""" + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200) + agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + context = combine_context( + format_context(store.injected_memories(session_id, repo.identity)) + ) + if not inject_context: + context = "" + first_start = store.start_sidekick( + repo, session_id, agent_id, agent_type, len(context) + ) + store.record_event( + repo, + session_id, + "sidekick_start", + { + "agent_id": agent_id, + "agent_type": agent_type, + "context_chars": len(context) if first_start else 0, + "worktree_root": bounded(repo.root, 2000), + }, + ) + telemetry.record( + "sidekick", + repo=repo, + session_id=session_id, + phase="start", + first_start=first_start, + context_chars=len(context) if first_start else 0, + ) + return context if first_start else "" + + +def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_id = bounded(hook_input.get("agent_id", ""), 200) + final_message = redact(hook_input.get("last_assistant_message", "")).strip() + transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000) + agent_id = store.stop_sidekick( + repo, + session_id, + agent_id, + agent_type, + transcript_path, + final_message, + ) + store.record_event( + repo, + session_id, + "sidekick_stop", + { + "agent_id": agent_id, + "agent_type": agent_type, + "transcript_path": transcript_path, + "final_message": final_message, + }, + ) + telemetry.record( + "sidekick", + repo=repo, + session_id=session_id, + phase="stop", + has_transcript=bool(transcript_path), + message_chars=len(final_message), + ) + + +def _ordered_unique(values: Iterable[str]) -> list[str]: + seen: set[str] = set() + result = [] + for value in values: + if value and value not in seen: + seen.add(value) + result.append(value) + return result + + +def _repo_relative_path(repo: RepoContext, value: str) -> str: + value = str(value or "").strip() + if not value: + return "" + try: + path = Path(value) + if path.is_absolute(): + try: + return path.resolve().relative_to(Path(repo.root).resolve()).as_posix() + except ValueError: + return "" + except (OSError, ValueError): + pass + return bounded(value, 1000) + + +def _render_command_lines(commands: list[dict[str, str]]) -> list[str]: + lines = [] + for command in commands: + line = f"- [{command['status']}/{command['kind']}] {command['command']}" + if command["result"]: + line += f" — {bounded(command['result'], 500).replace(chr(10), ' ')}" + lines.append(line) + return lines + + +def build_episode( + repo: RepoContext, + session_id: str, + packet_id: str, + events: list[dict[str, Any]], + *, + canonical_task: str = "", + task_outcome: str = "", +) -> tuple[str, dict[str, Any]]: + prompts = [ + redact(e["payload"].get("text", "")).strip() + for e in events + if e["kind"] == "user_prompt" and e["payload"].get("text") + ] + assistant_conclusions = [ + redact(e["payload"].get("text", "")).strip() + for e in events + if e["kind"] == "assistant_stop" and e["payload"].get("text") + ] + sidekick_outcomes = [ + redact(e["payload"].get("final_message", "")).strip() + for e in events + if e["kind"] == "sidekick_stop" and e["payload"].get("final_message") + ] + tools = [ + e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"} + and e["payload"].get("agent_role", "main") == "main" + ] + read_paths = _ordered_unique( + _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", ""))) + for t in tools + if t.get("tool") == "Read" + ) + modified_paths = _ordered_unique( + _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", ""))) + for t in tools + if t.get("tool") in {"Write", "Edit", "MultiEdit", "NotebookEdit"} + ) + searches = [ + {key: t[key] for key in ("tool", "pattern", "path", "query", "url") if key in t} + for t in tools + if t.get("tool") in {"Grep", "Glob", "WebSearch", "WebFetch"} + ] + commands = [ + { + "command": t.get("command", ""), + "kind": t.get("command_kind", "shell"), + "status": "unknown" if t.get("failed", False) is None else "failed" if t.get("failed") else "succeeded", + "result": t.get("result_preview", ""), + } + for t in tools + if t.get("command") + ] + + task = bounded(canonical_task or (prompts[0] if prompts else ""), 4000) + conclusion = redact(assistant_conclusions[-1] if assistant_conclusions else "").strip() + outcome = bounded(task_outcome, 2000) + + extraction_messages: list[dict[str, str]] = [] + pending_user_messages: list[dict[str, str]] = [] + if task and not prompts: + pending_user_messages.append({"role": "user", "content": task}) + for event in events: + if event["kind"] == "user_prompt" and event["payload"].get("text"): + pending_user_messages.append( + { + "role": "user", + "content": redact(event["payload"].get("text", "")).strip(), + } + ) + elif event["kind"] == "assistant_stop": + transcript_messages = event["payload"].get("transcript_messages") or [] + if isinstance(transcript_messages, list) and transcript_messages: + transcript_users = { + redact(message.get("content") or "").strip() + for message in transcript_messages + if isinstance(message, dict) and message.get("role") == "user" + } + extraction_messages.extend( + message + for message in pending_user_messages + if message["content"].strip() not in transcript_users + ) + extraction_messages.extend( + { + "role": str(message.get("role") or ""), + "content": redact(message.get("content") or "").strip(), + } + for message in transcript_messages + if isinstance(message, dict) + and message.get("role") in {"user", "assistant"} + and message.get("content") + ) + else: + extraction_messages.extend(pending_user_messages) + if event["payload"].get("text"): + extraction_messages.append( + { + "role": "assistant", + "content": redact(event["payload"].get("text", "")).strip(), + } + ) + pending_user_messages = [] + elif event["kind"] == "sidekick_stop": + pass + extraction_messages.extend(pending_user_messages) + + structured = { + "packet_id": packet_id, + "repo": repo.identity, + "app_id": repo.app_id, + "session_id": session_id, + "branch": repo.branch, + "head_sha": repo.head_sha, + "task": task, + "task_outcome": outcome, + "assistant_conclusion": conclusion, + "user_messages": prompts, + "assistant_outcomes": assistant_conclusions, + "sidekick_outcomes": sidekick_outcomes, + "extraction_messages": extraction_messages, + "files_read": read_paths[:50], + "files_modified": modified_paths[:50], + "searches": searches[-30:], + "commands": commands[-30:], + } + lines = ["Coding-session episode"] + if task: + lines.extend(["", "Task:", task]) + if modified_paths: + lines.extend( + ["", "Files modified:", *[f"- {path}" for path in modified_paths[:50]]] + ) + if read_paths: + lines.extend(["", "Files read:", *[f"- {path}" for path in read_paths[:50]]]) + if commands: + lines.append("") + lines.append("Observed commands:") + lines.extend(_render_command_lines(commands[-30:])) + if searches: + lines.extend( + [ + "", + "Observed searches:", + *[ + f"- {json.dumps(item, ensure_ascii=False, sort_keys=True)}" + for item in searches[-20:] + ], + ] + ) + if conclusion: + lines.extend(["", "Agent conclusion:", conclusion]) + if outcome: + lines.extend(["", "Task outcome:", outcome]) + lines.extend( + [ + "", + f"Provenance: repo={repo.identity}; branch={repo.branch}; head={repo.head_sha}; packet={packet_id}", + ] + ) + content = "\n".join(lines) + return bounded(content, MAX_EPISODE_CHARS), structured + + +def build_semantic_evidence(structured: dict[str, Any]) -> str: + """Format changed paths for memory extraction. + + Test and build results remain in the local evidence store for diagnostics, + but are not useful repository knowledge by default and should not steer + memory extraction toward transient verification details. + """ + modified_paths = [ + bounded(path, 500) for path in structured.get("files_modified", [])[:20] + ] + commands = structured.get("commands") or [] + if not any(command.get("status") == "failed" for command in commands): + commands = [] + + if not modified_paths and not commands: + return "" + + lines = ["Additional repository details from this session"] + if modified_paths: + lines.extend( + [ + "", + "Changed paths:", + *[f"- {path}" for path in modified_paths], + ] + ) + if commands: + lines.extend(["", "Commands run in this session:", *_render_command_lines(commands)]) + return bounded("\n".join(lines), 8000) + + +def build_extraction_messages(structured: dict[str, Any]) -> list[dict[str, str]]: + """Build the session messages sent to Mem0 for memory extraction.""" + evidence = build_semantic_evidence(structured) + messages = [ + {"role": message["role"], "content": redact(message["content"]).strip()} + for message in structured.get("extraction_messages", []) + if message.get("role") in {"user", "assistant"} and message.get("content") + ] + if evidence: + for message in reversed(messages): + if message["role"] == "assistant": + message["content"] = f"{message['content']}\n\n{evidence}" + break + else: + messages.append({"role": "assistant", "content": evidence}) + + return messages + + +def _estimated_tokens(value: str) -> int: + """Conservatively estimate tokens without adding a tokenizer dependency.""" + ascii_chars = sum(ord(char) < 128 for char in value) + return math.ceil((ascii_chars * 0.4) + (len(value) - ascii_chars)) + + +def _message_tokens(messages: list[dict[str, str]]) -> int: + return _estimated_tokens(json.dumps(messages, ensure_ascii=False)) + + +def _is_agent_assignment(message: dict[str, str]) -> bool: + return message.get("role") == "assistant" and message.get( + "content", "" + ).startswith("Subagent assignment (") + + +def _is_agent_response(message: dict[str, str]) -> bool: + return message.get("role") == "assistant" and message.get( + "content", "" + ).startswith("Subagent response (") + + +def extraction_message_batches( + messages: list[dict[str, str]], + *, + max_tokens: int = MAX_EXTRACTION_INPUT_TOKENS, +) -> list[list[dict[str, str]]]: + """Keep exchanges together when possible; split oversized messages to enforce the request budget.""" + if not messages or _message_tokens(messages) <= max_tokens: + return [messages] + + exchanges: list[list[dict[str, str]]] = [] + exchange: list[dict[str, str]] = [] + for message in messages: + if message.get("role") == "user" and exchange: + exchanges.append(exchange) + exchange = [] + exchange.append(message) + if exchange: + exchanges.append(exchange) + + units: list[list[dict[str, str]]] = [] + for exchange in exchanges: + if _message_tokens(exchange) <= max_tokens: + units.append(exchange) + continue + index = 0 + while index < len(exchange): + message = exchange[index] + if ( + _is_agent_assignment(message) + and index + 1 < len(exchange) + and _is_agent_response(exchange[index + 1]) + ): + units.append(exchange[index : index + 2]) + index += 2 + else: + units.append([message]) + index += 1 + + bounded_units: list[list[dict[str, str]]] = [] + for unit in units: + if _message_tokens(unit) <= max_tokens: + bounded_units.append(unit) + continue + for message in unit: + remaining = message["content"] + while remaining: + low, high = 0, len(remaining) + while low < high: + middle = (low + high + 1) // 2 + if _message_tokens([{**message, "content": remaining[:middle]}]) <= max_tokens: + low = middle + else: + high = middle - 1 + if low == 0: + raise ValueError("Extraction token budget cannot fit a message") + bounded_units.append([{**message, "content": remaining[:low]}]) + remaining = remaining[low:] + + batches: list[list[dict[str, str]]] = [] + batch: list[dict[str, str]] = [] + for unit in bounded_units: + candidate = [*batch, *unit] + if batch and _message_tokens(candidate) > max_tokens: + batches.append(batch) + batch = list(unit) + else: + batch = candidate + if batch: + batches.append(batch) + return batches + + +def _request_json( + url: str, key: str, payload: dict[str, Any], timeout: float +) -> tuple[dict[str, Any] | list[Any], int, int]: + raw = json.dumps(payload, ensure_ascii=False).encode() + request = urllib.request.Request( + url, + data=raw, + headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + response_raw = response.read() + parsed = json.loads(response_raw or b"{}") + return parsed, len(raw), len(response_raw) + + +def _request_json_with_network_retry( + url: str, key: str, payload: dict[str, Any], timeout: float +) -> tuple[dict[str, Any] | list[Any], int, int]: + """Retry one transient connection failure without retrying API responses.""" + try: + return _request_json(url, key, payload, timeout) + except urllib.error.HTTPError: + raise + except (urllib.error.URLError, TimeoutError, OSError): + time.sleep(0.25) + return _request_json(url, key, payload, timeout) + + +def _get_json( + url: str, key: str, timeout: float +) -> tuple[dict[str, Any] | list[Any], int]: + request = urllib.request.Request( + url, + headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + method="GET", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + response_raw = response.read() + return json.loads(response_raw or b"{}"), len(response_raw) + + +def _event_id(response: dict[str, Any] | list[Any]) -> str: + return str(response.get("event_id", "")) if isinstance(response, dict) else "" + + +def _stored_event_ids(value: Any) -> list[str]: + raw = str(value or "") + if not raw.startswith("["): + return [] + try: + parsed = json.loads(raw) + except json.JSONDecodeError: + return [] + return [str(item or "") for item in parsed] if isinstance(parsed, list) else [] + + +def _result_count(response: dict[str, Any] | list[Any]) -> int: + if isinstance(response, dict): + results = response.get("results") + return len(results) if isinstance(results, list) else 0 + return len(response) if isinstance(response, list) else 0 + + +def touch_handoff_heartbeat() -> None: + """Mark the worker's handoff file alive so recovery does not relaunch it.""" + path = os.environ.get("MEM0_CODE_HANDOFF_PATH", "") + if not path: + return + try: + os.utime(path) + except OSError: + pass + + +def _wait_for_event(api_url: str, key: str, event_id: str) -> tuple[str, int, int]: + """Wait for extraction to finish before a later task can search the store.""" + if not event_id: + return "MISSING", 0, 0 + wait_seconds = float(os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120")) + poll_seconds = max(float(os.environ.get("MEM0_CODE_EVENT_POLL_SECONDS", "1")), 0.1) + deadline = time.monotonic() + wait_seconds + response_chars = 0 + while time.monotonic() < deadline: + touch_handoff_heartbeat() + try: + response, size = _get_json( + f"{api_url}/v1/event/{event_id}/", + key, + min(10, poll_seconds + 5), + ) + except urllib.error.HTTPError as exc: + if exc.code not in {408, 429} and exc.code < 500: + raise + time.sleep(poll_seconds) + continue + except (urllib.error.URLError, TimeoutError, OSError): + # The extraction job is durable server-side. A transient polling + # failure must not discard a job that may still complete normally. + time.sleep(poll_seconds) + continue + response_chars += size + status = ( + str(response.get("status", "UNKNOWN")) + if isinstance(response, dict) + else "UNKNOWN" + ) + if status in {"SUCCEEDED", "FAILED"}: + return status, response_chars, _result_count(response) + time.sleep(poll_seconds) + return "TIMEOUT", response_chars, 0 + + +def _record_flush( + repo: RepoContext, + session_id: str, + reason: str, + status: str, + elapsed: float, + **extra: Any, +) -> None: + telemetry.record( + "flush", + repo=repo, + session_id=session_id, + reason=reason, + status=status, + success=status in {"semantic-succeeded", "nothing-to-flush"}, + duration_ms=round(elapsed, 2), + **extra, + ) + + +def flush_session( + store: EvidenceStore, hook_input: dict[str, Any], reason: str +) -> dict[str, Any]: + key = api_key() + if not key: + telemetry.record("flush", reason=reason, status="local-only", success=False) + return {"status": "local-only", "reason": "no-api-key"} + + session_id = _session_id(hook_input) + if session_id == "unknown-session": + telemetry.record("flush", reason=reason, status="no-session-id", success=False) + return {"status": "error", "reason": "no-session-id"} + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + prepared = store.prepare_flush(repo, session_id, reason) + if prepared is None: + return {"status": "nothing-to-flush"} + packet_id, events = prepared + existing_flush = store.flush_record(packet_id) or {} + + _, structured = build_episode( + repo, + session_id, + packet_id, + events, + canonical_task=bounded(hook_input.get("task", ""), 4000), + task_outcome=bounded(hook_input.get("task_outcome", ""), 2000), + ) + + metadata = {"source": _harness_source_tag} + if repo.branch and repo.branch not in {"detached", "unknown"}: + metadata["branch"] = repo.branch + if repo.head_sha: + metadata["git_sha"] = repo.head_sha + api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + add_url = f"{api_url}/v3/memories/add/" + + write_user = _scope_value(user_id()) + write_project = _scope_value(repo.project_id) + if not write_user or not _scope_value(repo.app_id) or not write_project: + telemetry.record("flush", reason=reason, status="unscoped", success=False) + return {"status": "error", "reason": "wildcard-scope"} + + body = { + "agent_id": write_project, + "user_id": write_user, + "app_id": repo.app_id, + "run_id": session_id, + "metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)}, + "agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS, + "custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS, + "custom_categories": CODING_MEMORY_CATEGORIES, + "infer": True, + } + + started = time.perf_counter() + try: + stored_events = _stored_event_ids(existing_flush.get("semantic_event_id")) + existing_event = ( + "" if stored_events else str(existing_flush.get("semantic_event_id") or "") + ) + if existing_event: + existing_status, existing_resp, existing_items = _wait_for_event( + api_url, key, existing_event + ) + if existing_status == "SUCCEEDED": + elapsed = (time.perf_counter() - started) * 1000 + store.update_flush( + packet_id, + status="semantic-succeeded", + semantic_event_id=existing_event, + error="", + ) + store.operation( + repo, + session_id, + "flush-retry", + elapsed, + True, + item_count=existing_items, + response_chars=existing_resp, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-succeeded", + elapsed, + memory_count=existing_items, + resumed=True, + ) + effective_reason = str( + (store.flush_record(packet_id) or {}).get("reason") or reason + ) + if ( + store.has_unflushed_events(repo.identity, session_id) + and not store.unflushed_starts_with_session_start( + repo.identity, session_id + ) + and ( + effective_reason != "periodic" + or store.checkpoint_due(repo.identity, session_id) + ) + ): + return flush_session(store, hook_input, effective_reason) + return { + "status": "semantic-succeeded", + "packet_id": packet_id, + "semantic_event_id": existing_event, + "semantic_status": existing_status, + "memory_count": existing_items, + "duration_ms": round(elapsed, 2), + "resumed": True, + } + if existing_status == "TIMEOUT": + elapsed = (time.perf_counter() - started) * 1000 + error = "semantic extraction event timed out" + store.update_flush(packet_id, status="semantic-timeout", error=error) + store.operation( + repo, + session_id, + "flush-retry", + elapsed, + False, + response_chars=existing_resp, + error=error, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-timeout", + elapsed, + resumed=True, + error_kind="timeout", + ) + return { + "status": "semantic-timeout", + "packet_id": packet_id, + "semantic_event_id": existing_event, + "duration_ms": round(elapsed, 2), + "resumed": True, + } + + message_batches = [ + batch + for batch in extraction_message_batches( + build_extraction_messages(structured) + ) + if batch + ] + batches = [(body, messages) for messages in message_batches] + if not batches: + store.update_flush(packet_id, status="semantic-succeeded", error="") + return {"status": "nothing-to-flush", "packet_id": packet_id} + operation_name = "flush-retry" if stored_events else "flush" + semantic_events = stored_events[: len(batches)] + semantic_events += [""] * (len(batches) - len(semantic_events)) + semantic_req = 0 + semantic_resp = 0 + for index, (body, messages) in enumerate(batches): + if semantic_events[index]: + continue + semantic_response, request_chars, response_chars = _request_json( + add_url, + key, + {**body, "messages": messages}, + 15, + ) + semantic_events[index] = _event_id(semantic_response) + semantic_req += request_chars + semantic_resp += response_chars + store.update_flush( + packet_id, + status="semantic-queued", + semantic_event_id=json.dumps(semantic_events), + ) + + semantic_event = semantic_events[-1] + semantic_status = "SUCCEEDED" + event_resp = 0 + semantic_items = 0 + failed_event = semantic_event + for index, queued_event in enumerate(semantic_events): + status, response_chars, item_count = _wait_for_event( + api_url, key, queued_event + ) + event_resp += response_chars + semantic_items += item_count + if status != "SUCCEEDED": + semantic_status = status + failed_event = queued_event + if status in {"FAILED", "MISSING"}: + semantic_events[index] = "" + store.update_flush( + packet_id, semantic_event_id=json.dumps(semantic_events) + ) + break + if semantic_status != "SUCCEEDED": + elapsed = (time.perf_counter() - started) * 1000 + error = f"semantic extraction event {semantic_status.lower()}" + store.update_flush( + packet_id, status=f"semantic-{semantic_status.lower()}", error=error + ) + store.operation( + repo, + session_id, + operation_name, + elapsed, + False, + item_count=semantic_items, + request_chars=semantic_req, + response_chars=semantic_resp + event_resp, + error=error, + ) + _record_flush( + repo, + session_id, + reason, + f"semantic-{semantic_status.lower()}", + elapsed, + memory_count=semantic_items, + batch_count=len(batches), + error_kind=telemetry.error_kind(error), + ) + return { + "status": f"semantic-{semantic_status.lower()}", + "packet_id": packet_id, + "semantic_event_id": failed_event, + "memory_count": semantic_items, + "duration_ms": round(elapsed, 2), + } + + elapsed = (time.perf_counter() - started) * 1000 + store.update_flush( + packet_id, + status="semantic-succeeded", + semantic_event_id=json.dumps(semantic_events), + error="", + ) + store.operation( + repo, + session_id, + operation_name, + elapsed, + True, + item_count=semantic_items, + request_chars=semantic_req, + response_chars=semantic_resp + event_resp, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-succeeded", + elapsed, + memory_count=semantic_items, + batch_count=len(batches), + request_chars=semantic_req, + ) + effective_reason = str( + (store.flush_record(packet_id) or {}).get("reason") or reason + ) + if ( + store.has_unflushed_events(repo.identity, session_id) + and not store.unflushed_starts_with_session_start( + repo.identity, session_id + ) + and ( + effective_reason != "periodic" + or store.checkpoint_due(repo.identity, session_id) + ) + ): + return flush_session(store, hook_input, effective_reason) + return { + "status": "semantic-succeeded", + "packet_id": packet_id, + "semantic_event_id": semantic_event, + "semantic_status": semantic_status, + "memory_count": semantic_items, + "duration_ms": round(elapsed, 2), + } + except Exception as exc: # hooks must fail open + elapsed = (time.perf_counter() - started) * 1000 + error = bounded(str(exc), 1000) + store.update_flush(packet_id, status="error", error=error) + store.operation(repo, session_id, "flush", elapsed, False, error=error) + _record_flush( + repo, + session_id, + reason, + "error", + elapsed, + error_kind=telemetry.error_kind(exc), + ) + return {"status": "error", "packet_id": packet_id, "error": error} + + +def checkpoint_session( + store: EvidenceStore, hook_input: dict[str, Any], reason: str +) -> dict[str, Any]: + """Run remote extraction at a durable boundary.""" + return flush_session(store, hook_input, reason) + + + +def search_memories( + store: EvidenceStore | None, + repo: RepoContext, + session_id: str | None, + query: str, + *, + top_k: int | None = None, + category: str | None = None, + scope: str | None = None, + run_id: str | None = None, + operation: str = "search", + timeout: float = 5, +) -> MemorySearchResult: + key = api_key() + if not key or not query.strip(): + return MemorySearchResult(False, 0, 0, []) + search_once = os.environ.get( + "MEM0_CODE_SEARCH_ONCE_PER_SESSION", "false" + ).lower() in { + "1", + "true", + "yes", + "on", + } + track_session = store is not None and bool(session_id) + if ( + search_once + and track_session + and store.has_operation(repo.identity, session_id, "search") + ): + return MemorySearchResult(False, 0, 0, []) + + result_limit = min( + max( + top_k + if top_k is not None + else _int_option("top_k", "MEM0_CODE_TOP_K", 3), + 1, + ), + 20, + ) + if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES: + raise ValueError(f"Unknown memory category: {category}") + user, project = _scope_value(user_id()), _scope_value(repo.project_id) + if not user or not project or not _scope_value(repo.app_id): + return MemorySearchResult(False, 0, 0, []) + filters = _search_filters(user, repo, resolve_search_scope(scope)) + if category: + filters = {"AND": [filters, {"categories": {"contains": category}}]} + if run_id: + filters = {"AND": [filters, {"run_id": run_id}]} + payload = { + "query": query, + "app_id": repo.app_id, + "filters": filters, + "top_k": result_limit, + "rerank": False, + "latest_only": True, + } + url = ( + os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + + "/v3/memories/search/" + ) + started = time.perf_counter() + try: + response, request_chars, response_chars = _request_json_with_network_retry( + url, key, payload, timeout + ) + memories = ( + response if isinstance(response, list) else response.get("results", []) + ) + memories = [ + memory + for memory in memories + if isinstance(memory, dict) + and (memory.get("metadata") or {}).get("record_kind") != "task_episode" + ][:result_limit] + if track_session: + returned_memories = store.unseen(session_id, repo.identity, memories) + store.mark_injected(session_id, repo.identity, returned_memories) + already_shown_count = len(memories) - len(returned_memories) + else: + returned_memories = memories + already_shown_count = 0 + elapsed = (time.perf_counter() - started) * 1000 + if track_session: + store.operation( + repo, + session_id, + operation, + elapsed, + True, + item_count=len(returned_memories), + request_chars=request_chars, + response_chars=response_chars, + ) + telemetry.record( + "search", + repo=repo, + session_id=session_id, + trigger=operation, + success=True, + duration_ms=round(elapsed, 2), + matched_count=len(memories), + returned_count=len(returned_memories), + already_shown_count=already_shown_count, + top_k=result_limit, + has_category=bool(category), + ) + return MemorySearchResult( + succeeded=True, + matched_count=len(memories), + already_shown_count=already_shown_count, + memories=returned_memories, + ) + except Exception as exc: + elapsed = (time.perf_counter() - started) * 1000 + if track_session: + store.operation(repo, session_id, operation, elapsed, False, error=str(exc)) + telemetry.record( + "search", + repo=repo, + session_id=session_id, + trigger=operation, + success=False, + duration_ms=round(elapsed, 2), + top_k=result_limit, + has_category=bool(category), + error_kind=telemetry.error_kind(exc), + ) + return MemorySearchResult(False, 0, 0, []) + + +def format_context( + memories: list[dict[str, Any]], + heading: str = "Relevant repository memories:", +) -> str: + if not memories: + return "" + limit = min( + max( + _int_option( + "max_context_chars", + "MEM0_CODE_MAX_CONTEXT_CHARS", + DEFAULT_MAX_CONTEXT_CHARS, + ), + 1000, + ), + 10000, + ) + lines = [heading] if heading else [] + for memory in memories: + text = re.sub( + r"\s+", + " ", + redact(memory.get("memory") or memory.get("text") or ""), + ) + text = text.strip() + if not text: + continue + branch = str((memory.get("metadata") or {}).get("branch") or "").strip() + branch_label = ( + f" [learnt on branch {branch}]" + if branch.casefold() not in {"", "main", "master", "unknown", "detached"} + else "" + ) + number = len(lines) if heading else len(lines) + 1 + entry = f"{number}. {text}{branch_label}" + candidate = "\n".join([*lines, entry]) + if len(candidate) <= limit: + lines.append(entry) + continue + if not lines or (heading and len(lines) == 1): + prefix = f"{number}. " + suffix = f"…{branch_label}" + available = ( + limit + - len("\n".join(lines)) + - (1 if lines else 0) + - len(prefix) + - len(suffix) + ) + if available > 0: + lines.append(prefix + text[:available].rstrip() + suffix) + break + minimum_lines = 2 if heading else 1 + return "\n".join(lines) if len(lines) >= minimum_lines else "" + + +def format_search_result(result: MemorySearchResult) -> str: + """Return only the text the coding agent needs from an explicit memory search.""" + if not result.succeeded: + return "Memory search failed." + if result.memories: + rendered = format_context(result.memories, heading="") + if rendered: + return rendered + return "No matching memories found." + + +def combine_context(*contexts: str) -> str: + """Combine memory sources under one hard budget without repeated lines.""" + seen: set[str] = set() + lines: list[str] = [] + for context in contexts: + for line in str(context or "").splitlines(): + normalized = re.sub(r"\s+", " ", line).strip().casefold() + if not normalized or normalized in seen: + continue + seen.add(normalized) + lines.append(line.rstrip()) + limit = min( + max( + _int_option( + "max_context_chars", + "MEM0_CODE_MAX_CONTEXT_CHARS", + DEFAULT_MAX_CONTEXT_CHARS, + ), + 1000, + ), + 10000, + ) + return bounded("\n".join(lines), limit) if lines else "" + + +def _scoped_memory_ids( + api_url: str, key: str, user: str, repo: RepoContext, include_project: bool +) -> list[str]: + """List this user's memory ids for this repository, plus the shared project memory when asked.""" + ids: list[str] = [] + seen: set[str] = set() + prefix = repo.app_id + _collect_memory_ids( + api_url, key, {"user_id": user}, ids, seen, + app_id_prefix=prefix, + ) + if include_project: + for project_id in _shared_project_ids(repo): + _collect_memory_ids( + api_url, key, {"agent_id": project_id}, ids, seen, + app_id_prefix=prefix, + ) + return ids + + +def _collect_memory_ids( + api_url: str, + key: str, + filters: dict[str, Any], + ids: list[str], + seen: set[str], + *, + app_id_prefix: str = "", +) -> None: + """Page through one list filter; the list endpoint returns nothing for an OR whose user branch has no memories.""" + payload = {"filters": filters} + for page in range(1, FORGET_MAX_PAGES + 1): + parsed, _, _ = _request_json( + f"{api_url}/v2/memories/?page={page}&page_size={FORGET_PAGE_SIZE}", + key, + payload, + 15, + ) + items = parsed.get("results") if isinstance(parsed, dict) else parsed + if not isinstance(items, list) or not items: + break + for item in items: + if not isinstance(item, dict): + continue + memory_id = str(item.get("id", "")) + if not memory_id or memory_id in seen: + continue + if app_id_prefix: + item_app_id = str(item.get("app_id") or "") + if item_app_id != app_id_prefix and not item_app_id.startswith(app_id_prefix + "/"): + continue + seen.add(memory_id) + ids.append(memory_id) + if len(items) < FORGET_PAGE_SIZE: + break + + +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"}, + method="DELETE", + ) + try: + with urllib.request.urlopen(request, timeout=15): + return True + except Exception: + return False + + +def forget_remote_repo( + repo: RepoContext, *, include_project_memory: bool = False +) -> dict[str, Any]: + """Delete this user's memories for this repository; project memory is shared, so only on request.""" + key = api_key() + if not key: + telemetry.record("forget", repo=repo, success=False, error_kind="no-api-key") + return {"status": "error", "error": "Mem0 API key is not configured"} + user = _scope_value(user_id()) + if not user or not _scope_value(repo.app_id) or not _scope_value(repo.project_id): + telemetry.record("forget", repo=repo, success=False, error_kind="unscoped") + return { + "status": "error", + "error": "Refusing to forget: the user or repository scope is a wildcard", + } + api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + try: + memory_ids = _scoped_memory_ids(api_url, key, user, repo, include_project_memory) + except Exception as exc: + telemetry.record( + "forget", repo=repo, success=False, error_kind=telemetry.error_kind(exc) + ) + return {"status": "error", "error": bounded(str(exc), 1000)} + deleted = sum(_delete_memory(api_url, key, memory_id) for memory_id in memory_ids) + failed = len(memory_ids) - deleted + telemetry.record("forget", repo=repo, success=not failed, item_count=deleted) + if failed: + return { + "status": "partial", + "deleted": deleted, + "failed": failed, + "error": f"{failed} of {len(memory_ids)} memories could not be deleted", + } + return {"status": "deleted", "deleted": deleted} + + +def _doctor_mem0_authentication(repo: RepoContext) -> dict[str, Any]: + """Verify the configured key with one read-only, repository-scoped search.""" + key = api_key() + if not key: + return {"ok": False, "detail": "API key missing"} + payload = { + "query": "Mem0 authentication check", + "filters": { + "AND": [ + {"user_id": user_id()}, + {"app_id": repo.app_id}, + ] + }, + "top_k": 1, + "threshold": 1.0, + "rerank": False, + } + url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + started = time.perf_counter() + try: + _request_json(f"{url}/v3/memories/search/", key, payload, 5) + except Exception as exc: + return {"ok": False, "detail": bounded(str(exc), 300)} + elapsed = (time.perf_counter() - started) * 1000 + return {"ok": True, "detail": f"connected ({elapsed:.0f} ms)"} + + +def _doctor_user_id() -> dict[str, Any]: + """Flag a configured user ID the plugin refuses, since the silent fallback surprises people.""" + configured = _plugin_option("user_id", "MEM0_CODE_USER_ID") or os.environ.get( + "MEM0_USER_ID", "" + ) + if configured and not _scope_value(configured): + return { + "ok": False, + "detail": f"configured user_id {configured!r} is a wildcard; using {user_id()!r}", + } + return {"ok": True, "detail": user_id()} + + +def doctor(cwd: str | None = None) -> dict[str, Any]: + repo = resolve_repo(cwd) + directory = data_dir() + directory.mkdir(parents=True, exist_ok=True) + checks: dict[str, dict[str, Any]] = { + "python": { + "ok": tuple(sys.version_info[:2]) >= (3, 10), + "detail": f"{sys.version_info.major}.{sys.version_info.minor}", + }, + "data_directory": { + "ok": os.access(directory, os.W_OK), + "detail": str(directory), + }, + "mem0_api_key": { + "ok": bool(api_key()), + "detail": "configured" if api_key() else "missing", + }, + "repository": { + "ok": bool(repo.identity), + "detail": repo.identity, + }, + "user_id": _doctor_user_id(), + "mem0_authentication": _doctor_mem0_authentication(repo), + } + return { + "ok": all(bool(value["ok"]) for value in checks.values()), + "plugin_version": PLUGIN_VERSION, + "repo_id": repo.identity, + "app_id": repo.app_id, + "user_id": user_id(), + "checks": checks, + } diff --git a/integrations/codex-plugin/core/telemetry.py b/integrations/codex-plugin/core/telemetry.py new file mode 100644 index 000000000..249595475 --- /dev/null +++ b/integrations/codex-plugin/core/telemetry.py @@ -0,0 +1,397 @@ +#!/usr/bin/env python3 +"""Anonymous usage telemetry for Mem0 agent plugins. + +Hooks run on a 3-6 second budget and fire on every tool call, so recording never +touches the network: `record` appends one JSON line to a local spool and returns. +A detached `python3 telemetry.py` drains the spool in one batched PostHog request, +started once per session and again from the flush worker that is already detached. + +Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false. + +Never sends prompts, memory text, queries, file paths, repository names, or API +keys: only event names, durations, counts, coarse outcomes, and salted hashes. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import platform +import subprocess +import sys +import time +import urllib.error +import urllib.request +import uuid +from pathlib import Path +from typing import Any + +import memory_core + +_harness: str = "generic" +_source_tag: str = "MEM0_PLUGIN" +_PRIVATE_KEYS = { + "apikey", + "authorization", + "password", + "query", + "secret", + "prompt", + "token", + "text", + "memory", + "message", + "error", + "path", + "cwd", + "userid", + "agentid", + "runid", + "repoid", + "repositoryid", + "projectid", + "appid", + "filters", +} + + +def init(harness: str = "generic", source_tag: str = "") -> None: + global _harness, _source_tag + _harness = harness + _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN" + +POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" +POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/" +POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/" +EVENT_PREFIX = "code" +SPOOL_LIMIT_BYTES = 256 * 1024 +BATCH_SIZE = 100 +SEND_TIMEOUT = 5 +CLAIM_STALE_SECONDS = 120 +CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60 + + +def is_enabled() -> bool: + """Whether telemetry is switched on for this process.""" + return os.environ.get("MEM0_TELEMETRY", "true").strip().lower() not in { + "false", + "0", + "no", + "off", + } + + +def _digest(value: str, length: int = 16) -> str: + return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length] + + +def _safe_value(value: Any) -> Any: + if isinstance(value, str): + return memory_core.redact(value) + if isinstance(value, dict): + return { + key: _safe_value(item) + for key, item in value.items() + if "".join(character for character in str(key).lower() if character.isalnum()) + not in _PRIVATE_KEYS + } + if isinstance(value, (list, tuple)): + return [_safe_value(item) for item in value] + if value is None or isinstance(value, (bool, int, float)): + return value + return memory_core.redact(value) + + +def _spool_path() -> Path: + return memory_core.data_dir() / "telemetry.jsonl" + + +def _identity_path() -> Path: + return memory_core.data_dir() / "telemetry-identity.json" + + +def _read_identity() -> dict[str, str]: + try: + value = json.loads(_identity_path().read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {} + return value if isinstance(value, dict) else {} + + +def _write_identity(identity: dict[str, str]) -> None: + path = _identity_path() + temporary = path.with_suffix(f".{os.getpid()}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + temporary.write_text(json.dumps(identity), encoding="utf-8") + temporary.replace(path) + except OSError: + try: + temporary.unlink() + except OSError: + pass + + +def anonymous_id(identity: dict[str, str] | None = None) -> str: + """Per-machine anonymous identifier, created and persisted on first use.""" + identity = _read_identity() if identity is None else identity + existing = identity.get("anonymous_id") + if existing: + return existing + created = f"code-anon-{uuid.uuid4().hex}" + identity["anonymous_id"] = created + _write_identity(identity) + return created + + +def is_first_run() -> bool: + """Whether this machine has never recorded a plugin event before.""" + return not _identity_path().exists() + + +def record( + event: str, + *, + repo: Any = None, + session_id: str | None = None, + **properties: Any, +) -> None: + """Append one event to the local spool. Never blocks and never raises.""" + if not is_enabled(): + return + try: + spool = _spool_path() + try: + if spool.stat().st_size > SPOOL_LIMIT_BYTES: + return + except OSError: + pass + properties = _safe_value(properties) + properties.update( + harness=_harness, + plugin_version=memory_core.PLUGIN_VERSION, + os=sys.platform, + python_version=platform.python_version(), + ) + if repo is not None: + properties["repo_hash"] = _digest(getattr(repo, "identity", "")) + if session_id: + properties["session_hash"] = _digest(session_id) + line = json.dumps( + { + "event": f"{EVENT_PREFIX}.{event}", + "timestamp": memory_core.utc_now(), + "properties": { + key: value for key, value in properties.items() if value is not None + }, + }, + separators=(",", ":"), + default=str, + ) + spool.parent.mkdir(parents=True, exist_ok=True) + with spool.open("a", encoding="utf-8") as handle: + handle.write(line + "\n") + except Exception: + pass + + +def error_kind(exc: BaseException | str) -> str: + """Coarse, content-free label for a failure, safe to send.""" + text = exc if isinstance(exc, str) else f"{type(exc).__name__}: {exc}" + lowered = text.lower() + if "timed out" in lowered or "timeout" in lowered: + return "timeout" + if "401" in lowered or "403" in lowered or "unauthor" in lowered or "forbidden" in lowered: + return "auth" + if "429" in lowered or "rate limit" in lowered: + return "rate-limited" + if any(code in lowered for code in ("500", "502", "503", "504")): + return "server-error" + if "400" in lowered or "422" in lowered: + return "bad-request" + if isinstance(exc, str): + return "other" + if isinstance(exc, urllib.error.URLError): + return "network" + return type(exc).__name__ + + +def spawn_flush() -> bool: + """Start the detached sender that drains the spool.""" + if not is_enabled(): + return False + try: + if not _spool_path().exists() and not any( + memory_core.data_dir().glob("telemetry-*.sending") + ): + return False + subprocess.Popen( + [sys.executable, str(Path(__file__).resolve())], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + close_fds=True, + **memory_core.detached_process_kwargs(), + ) + return True + except Exception: + return False + + +def _claim_spool() -> Path | None: + """Rename the spool aside so exactly one sender owns each batch.""" + directory = memory_core.data_dir() + claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending" + spool = _spool_path() + try: + spool.replace(claim) + return claim + except OSError: + pass + now = time.time() + for orphan in sorted(directory.glob("telemetry-*.sending")): + try: + age = now - orphan.stat().st_mtime + except OSError: + continue + if age > CLAIM_EXPIRY_SECONDS: + try: + orphan.unlink() + except OSError: + pass + continue + if age < CLAIM_STALE_SECONDS: + continue + try: + orphan.replace(claim) + return claim + except OSError: + continue + return None + + +def _resolve_email(key: str) -> str: + """Trade the API key for the account email so events join other Mem0 surfaces.""" + url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/" + request = urllib.request.Request( + url, headers={"Authorization": f"Token {key}", "Content-Type": "application/json"} + ) + try: + with urllib.request.urlopen(request, timeout=SEND_TIMEOUT) as response: + payload = json.loads(response.read().decode("utf-8")) + except Exception: + return "" + email = payload.get("user_email") if isinstance(payload, dict) else "" + return email if isinstance(email, str) else "" + + +def _post(payload: dict[str, Any], url: str) -> bool: + request = urllib.request.Request( + url, + data=json.dumps(payload, default=str).encode("utf-8"), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=SEND_TIMEOUT): + return True + except Exception: + return False + + +def resolve_distinct_id() -> tuple[str, str]: + """Return the PostHog distinct id and the anonymous id it replaced, if any.""" + identity = _read_identity() + email = identity.get("email", "") + if email: + return email, "" + key = memory_core.api_key() + if not key: + return anonymous_id(identity), "" + email = _resolve_email(key) + if not email: + return anonymous_id(identity), "" + previous = identity.get("anonymous_id", "") + identity["email"] = email + _write_identity(identity) + return email, previous + + +def flush() -> int: + """Drain claimed spools to PostHog and return the number of events sent.""" + if not is_enabled(): + return 0 + claim = _claim_spool() + if claim is None: + return 0 + try: + lines = claim.read_text(encoding="utf-8").splitlines() + except OSError: + return 0 + events = [] + for line in lines: + try: + value = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(value, dict) and value.get("event"): + events.append(value) + if not events: + try: + claim.unlink() + except OSError: + pass + return 0 + + distinct_id, aliased_anonymous_id = resolve_distinct_id() + if aliased_anonymous_id: + _post( + { + "api_key": POSTHOG_API_KEY, + "event": "$identify", + "distinct_id": distinct_id, + "properties": { + "$anon_distinct_id": aliased_anonymous_id, + "$lib": "posthog-python", + }, + }, + POSTHOG_CAPTURE_URL, + ) + + sent = 0 + for start in range(0, len(events), BATCH_SIZE): + batch = [ + { + "event": event["event"], + "distinct_id": distinct_id, + "timestamp": event.get("timestamp"), + "properties": { + "source": _source_tag, + "language": "python", + "$process_person_profile": False, + "$lib": "posthog-python", + **(event.get("properties") or {}), + }, + } + for event in events[start : start + BATCH_SIZE] + ] + if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL): + return sent + sent += len(batch) + try: + claim.unlink() + except OSError: + pass + return sent + + +def main() -> int: + flush() + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except Exception: + raise SystemExit(0) diff --git a/integrations/codex-plugin/hooks/adapter.py b/integrations/codex-plugin/hooks/adapter.py new file mode 100644 index 000000000..1fb6b0b3a --- /dev/null +++ b/integrations/codex-plugin/hooks/adapter.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +"""Run Codex hooks through the shared Mem0 runtime.""" + +from __future__ import annotations + +import sys +from pathlib import Path + +HERE = Path(__file__).resolve() +BUNDLED_CORE = HERE.parent.parent / "core" +CORE = BUNDLED_CORE if BUNDLED_CORE.is_dir() else HERE.parents[2] / "core" / "python" +sys.path.insert(0, str(CORE)) + +import hook_runner # noqa: E402 +import telemetry # noqa: E402 +from memory_core import ( # noqa: E402 + configure_harness, + record_sidekick_start, + record_sidekick_stop, + record_tool, +) + +configure_harness("codex", data_dir_name="codex-plugin", source_tag="codex_plugin") +telemetry.init(harness="codex", source_tag="CODEX_PLUGIN") + + +def _sidekick_start(store, hook_input): + context = record_sidekick_start(store, hook_input) + if context: + return { + "hookSpecificOutput": { + "hookEventName": "SubagentStart", + "additionalContext": context, + } + } + + +def _sidekick_stop(store, hook_input): + record_sidekick_stop(store, hook_input) + + +def _post_tool(store, payload): + response = payload.get("tool_response") + failed = None + if isinstance(response, dict): + exit_code = response.get("exit_code") + if isinstance(exit_code, int) and not isinstance(exit_code, bool): + failed = exit_code != 0 + elif isinstance(response.get("isError"), bool): + failed = response["isError"] + elif isinstance(response.get("success"), bool): + failed = not response["success"] + if failed: + payload = {**payload, "error": response} + record_tool(store, payload, failed=failed) + + +if __name__ == "__main__": + if len(sys.argv) > 1 and sys.argv[1] == "post-tool": + sys.argv[1] = "codex-post-tool" + hook_runner.entry_point( + extra_actions={"sidekick-start": _sidekick_start, "sidekick-stop": _sidekick_stop, "codex-post-tool": _post_tool}, + automatic_flush_reasons={"session-end", "pre-compact"}, + ) diff --git a/integrations/codex-plugin/hooks/hooks.json b/integrations/codex-plugin/hooks/hooks.json new file mode 100644 index 000000000..44c3732a1 --- /dev/null +++ b/integrations/codex-plugin/hooks/hooks.json @@ -0,0 +1,63 @@ +{ + "description": "Create memories from coding sessions and recall them in later work.", + "hooks": { + "SessionStart": [ + { + "matcher": "startup|resume|clear|compact", + "hooks": [ + { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" session-start --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 } + ] + } + ], + "UserPromptSubmit": [ + { + "hooks": [ + { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" user-prompt --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 } + ] + } + ], + "PostToolUse": [ + { + "matcher": ".*", + "hooks": [ + { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" post-tool --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 } + ] + } + ], + "SubagentStart": [ + { + "hooks": [ + { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" sidekick-start --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 } + ] + } + ], + "SubagentStop": [ + { + "hooks": [ + { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" sidekick-stop --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 } + ] + } + ], + "Stop": [ + { + "hooks": [ + { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" stop --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 } + ] + } + ], + "PreCompact": [ + { + "hooks": [ + { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" flush --reason pre-compact --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 } + ] + } + ], + "SessionEnd": [ + { + "hooks": [ + { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" flush --reason session-end --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 } + ] + } + ] + } +} diff --git a/integrations/codex-plugin/plugin-build.json b/integrations/codex-plugin/plugin-build.json new file mode 100644 index 000000000..8d4c51c07 --- /dev/null +++ b/integrations/codex-plugin/plugin-build.json @@ -0,0 +1,15 @@ +{ + "id": "mem0", + "version": "0.3.1", + "homepage": "https://docs.mem0.ai/integrations/codex", + "native": { + "pluginRoot": "${PLUGIN_ROOT}", + "pluginData": "${PLUGIN_DATA}", + "files": { + ".codex-plugin/plugin.json": ".codex-plugin/plugin.json", + "hooks/hooks.json": "hooks/hooks.json", + "hooks/adapter.py": "hooks/adapter.py", + ".mcp.json": ".mcp.json" + } + } +} diff --git a/integrations/codex-plugin/skills/forget/SKILL.md b/integrations/codex-plugin/skills/forget/SKILL.md new file mode 100644 index 000000000..09b285cac --- /dev/null +++ b/integrations/codex-plugin/skills/forget/SKILL.md @@ -0,0 +1,26 @@ +--- +name: forget +description: Delete the Mem0 memories stored for this repository and this user. Use when the user asks to forget, clear, wipe, or delete memories. +disable-model-invocation: true +--- + +# Forget this repository's memories + +This permanently deletes remote memories. Before running anything, tell the +user exactly what will be deleted: their own memories for this repository +only. The repository's project memory is shared by everyone who works in it, +so it stays unless the user explicitly asks to delete that too. + +After the user confirms, run: + +```bash +python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "codex" --plugin-data-dir "${PLUGIN_DATA}" forget --remote --yes +``` + +If the user also asked to delete the repository's shared project memory, add +`--include-project-memory` and say that this removes it for every teammate. + +Report what the command output says was deleted. If the user only wants local +data cleared (evidence log, pending queue), run the same command without +`--remote`. Never pass `--yes` before the user has confirmed in this +conversation. diff --git a/integrations/codex-plugin/skills/pause/SKILL.md b/integrations/codex-plugin/skills/pause/SKILL.md new file mode 100644 index 000000000..d8a52f47b --- /dev/null +++ b/integrations/codex-plugin/skills/pause/SKILL.md @@ -0,0 +1,20 @@ +--- +name: pause +description: Pause Mem0 memory capture on this machine. Use when the user wants to stop memories being recorded, for example for private work or experiments. +disable-model-invocation: true +--- + +# Pause memory capture + +To pause (hooks stop capturing and sending session content; a minimal +anonymous telemetry ping still fires at session start unless +`MEM0_TELEMETRY=false`): + +```bash +python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "codex" --plugin-data-dir "${PLUGIN_DATA}" pause +``` + +Confirm the new state back to the user, and remind them that already-created +memories still exist and remain searchable. Pending unsent packets are held +while paused, not expired, and are delivered after resuming. To turn capture +back on, use `/mem0:resume`. diff --git a/integrations/codex-plugin/skills/remember/SKILL.md b/integrations/codex-plugin/skills/remember/SKILL.md new file mode 100644 index 000000000..7be5fc9be --- /dev/null +++ b/integrations/codex-plugin/skills/remember/SKILL.md @@ -0,0 +1,21 @@ +--- +name: remember +description: Acknowledge a "remember this" request and make sure it is captured well. Use when the user explicitly asks to remember, note, or save something for future sessions. +disable-model-invocation: true +--- + +# Remember something for future sessions + +Mem0 creates memories from the session automatically — there is no separate +write command. When the user asks to remember something: + +1. Restate the fact clearly and completely in your reply, in one or two + sentences, including any names, values, or paths it depends on. Your visible + reply is what memory extraction reads, so a precise restatement is what gets + remembered. +2. Tell the user it will be saved with this session's memories when the session + ends or compacts, and that it will surface in future sessions in this + repository (they can check later with /mem0:search). + +Do not invent a storage confirmation or a memory ID — creation happens in the +background after the session. diff --git a/integrations/codex-plugin/skills/resume/SKILL.md b/integrations/codex-plugin/skills/resume/SKILL.md new file mode 100644 index 000000000..59a097585 --- /dev/null +++ b/integrations/codex-plugin/skills/resume/SKILL.md @@ -0,0 +1,19 @@ +--- +name: resume +description: Resume Mem0 memory capture after it was paused with /mem0:pause. +disable-model-invocation: true +--- + +# Resume memory capture + +Resume memory capture for this machine. + +Run: + +```bash +python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "codex" --plugin-data-dir "${PLUGIN_DATA}" resume +``` + +Confirm to the user that capture is active again. New sessions record evidence and +create memories as normal; nothing that happened while paused is retroactively +captured. diff --git a/integrations/codex-plugin/skills/search/SKILL.md b/integrations/codex-plugin/skills/search/SKILL.md new file mode 100644 index 000000000..f6c27b19c --- /dev/null +++ b/integrations/codex-plugin/skills/search/SKILL.md @@ -0,0 +1,28 @@ +--- +name: search +description: Search memories from earlier Codex 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. +argument-hint: "[question] [--top-k number] [--category category-name] [--scope repo|dir|mine] [--run-id session-id]" +disable-model-invocation: true +--- + +# Search memories + +Call `search_memories` with the user's question. Treat `--top-k`, `--category`, +`--scope`, and `--run-id` as tool arguments instead of including them in the +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. + +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 +monorepo), `mine` for your own preferences alone. + +Pass `run_id` with any scope to retrieve memories saved in a specific coding-agent +session. Omit `run_id` to search across sessions. It filters the memories returned; +it does not identify the session making the search request. Use a known session ID, +never invent one. Return the tool's result directly. diff --git a/integrations/codex-plugin/skills/status/SKILL.md b/integrations/codex-plugin/skills/status/SKILL.md new file mode 100644 index 000000000..4f67cc829 --- /dev/null +++ b/integrations/codex-plugin/skills/status/SKILL.md @@ -0,0 +1,23 @@ +--- +name: status +description: Show whether Mem0 memory is working in this repository, covering configuration, capture state, pending flushes, and whether the Mem0 API key is valid. Use when the user asks whether memory is on, why a memory is missing, or anything looks broken. +disable-model-invocation: false +--- + +# Memory status + +Run both commands and report the combined result in plain language: + +```bash +python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "codex" --plugin-data-dir "${PLUGIN_DATA}" status --json +python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "codex" --plugin-data-dir "${PLUGIN_DATA}" doctor +``` + +Summarize, using only fields the JSON actually reports: whether capture is +active or paused, the user ID and repository scope (`repo_id`), whether an +API key is configured, the event/flush/retrieval counts (`flushes` is the +number of completed flushes, not a pending count), and the doctor check +results. If doctor reports an authentication failure (401 / invalid key), say +clearly that the Mem0 API key is invalid or expired and that memories are NOT +being created. Never report an auth failure as "no memories found". Suggest +reinstalling with `--config api_key=...` in that case. diff --git a/integrations/codex-plugin/tests/test_codex.py b/integrations/codex-plugin/tests/test_codex.py new file mode 100644 index 000000000..4254c1f13 --- /dev/null +++ b/integrations/codex-plugin/tests/test_codex.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import json +import sqlite3 +import subprocess +import sys +from pathlib import Path + +HOST = Path(__file__).resolve().parents[1] +CORE_ROOT = HOST.parent / "agent-plugin-core" +sys.path.insert(0, str(CORE_ROOT)) + +from build.build import build # noqa: E402 + + +def test_codex_hooks_use_native_events_and_plugin_paths() -> None: + hooks = json.loads((HOST / "hooks" / "hooks.json").read_text(encoding="utf-8"))["hooks"] + + assert set(hooks) == { + "SessionStart", + "UserPromptSubmit", + "PostToolUse", + "SubagentStart", + "SubagentStop", + "Stop", + "PreCompact", + "SessionEnd", + } + commands = [hook["command"] for groups in hooks.values() for group in groups for hook in group["hooks"]] + assert "matcher" not in hooks["SubagentStart"][0] + assert "matcher" not in hooks["SubagentStop"][0] + assert all("${PLUGIN_ROOT}/hooks/adapter.py" in command for command in commands) + assert any("flush --reason pre-compact" in command for command in commands) + assert any("flush --reason session-end" in command for command in commands) + assert all(hook.get("timeout", 0) <= 3 for groups in hooks.values() for group in groups for hook in group["hooks"]) + + +def test_codex_sidekick_records_lifecycle(tmp_path: Path) -> None: + adapter = HOST / "hooks" / "adapter.py" + payload = { + "session_id": "session-1", + "cwd": str(tmp_path), + "agent_id": "agent-1", + "agent_type": "default", + } + + for action, extra in ( + ("sidekick-start", {}), + ("sidekick-stop", {"last_assistant_message": "SIDEKICK_OK"}), + ): + result = subprocess.run( + [sys.executable, str(adapter), action, "--plugin-data-dir", str(tmp_path / "data")], + input=json.dumps({**payload, **extra}), + text=True, + capture_output=True, + check=False, + ) + assert result.returncode == 0, result.stderr + + with sqlite3.connect(tmp_path / "data" / "evidence.sqlite3") as connection: + row = connection.execute( + "SELECT agent_id, stopped_at, final_message FROM sidekick_runs" + ).fetchone() + + assert row is not None + assert row[0] == "agent-1" + assert row[1] + assert row[2] == "SIDEKICK_OK" + + +def test_codex_mcp_uses_host_relative_paths() -> None: + manifest = json.loads((HOST / ".codex-plugin" / "plugin.json").read_text(encoding="utf-8")) + assert manifest["mcpServers"] == "./.mcp.json" + + server = json.loads((HOST / ".mcp.json").read_text(encoding="utf-8"))["mcpServers"]["mem0"] + assert server["command"] == "python3" + assert server["args"] == ["./core/mcp_server.py"] + assert server["cwd"] == "." + assert set(server["env_vars"]) >= {"MEM0_API_KEY", "MEM0_CODE_USER_ID"} + assert "PLUGIN_ROOT" not in json.dumps(server) + + +def test_native_codex_bundle_is_self_contained(tmp_path: Path) -> None: + root = build("codex", "native", tmp_path / "codex") + + manifest = json.loads((root / ".codex-plugin" / "plugin.json").read_text(encoding="utf-8")) + assert manifest["hooks"] == "./hooks/hooks.json" + assert manifest["skills"] == "./skills/" + assert (root / "hooks" / "adapter.py").is_file() + assert (root / "core" / "mcp_server.py").is_file() + assert (root / ".mcp.json").is_file() + assert not (root / "agents").exists() + assert not any(path.is_symlink() for path in root.rglob("*")) + + +def test_codex_post_tool_keeps_failures_and_unknown_outcomes(tmp_path): + for response, failed in [("raw command output", None), ({"exit_code": 1, "stderr": "failed"}, True), ({"isError": False}, False)]: + result = subprocess.run( + [sys.executable, str(HOST / "hooks" / "adapter.py"), "post-tool", "--plugin-data-dir", str(tmp_path / "data")], + input=json.dumps({"session_id": "s1", "cwd": str(tmp_path), "tool_name": "Bash", + "tool_input": {"command": "test command"}, "tool_response": response}), + text=True, capture_output=True, check=False, + ) + assert result.returncode == 0, result.stderr + with sqlite3.connect(tmp_path / "data" / "evidence.sqlite3") as connection: + row = connection.execute("SELECT payload_json FROM events ORDER BY id DESC LIMIT 1").fetchone() + assert json.loads(row[0])["failed"] is failed diff --git a/integrations/cursor-plugin/.cursor-plugin/plugin.json b/integrations/cursor-plugin/.cursor-plugin/plugin.json new file mode 100644 index 000000000..fe9594a12 --- /dev/null +++ b/integrations/cursor-plugin/.cursor-plugin/plugin.json @@ -0,0 +1,25 @@ +{ + "name": "mem0", + "version": "0.3.1", + "description": "Cross-session memory and token savings for coding agents.", + "author": { "name": "Mem0", "email": "support@mem0.ai" }, + "homepage": "https://docs.mem0.ai/integrations/cursor", + "repository": "https://github.com/mem0ai/mem0", + "license": "Apache-2.0", + "keywords": ["memory", "coding-agents", "continual-learning", "token-efficiency"], + "skills": "./skills/", + "agents": "./agents/", + "hooks": "./hooks/hooks.json", + "mcpServers": "./mcp.json", + "variables": { + "type": "object", + "properties": { + "api_key": { "type": "string", "title": "Mem0 API Key", "description": "Mem0 Platform API key used to create and search memories." }, + "user_id": { "type": "string", "title": "Memory user ID", "description": "Optional stable ID shared across machines.", "default": "" }, + "top_k": { "type": "number", "title": "Manual search results", "default": 3, "minimum": 1, "maximum": 20 }, + "max_context_chars": { "type": "number", "title": "Maximum retrieved context", "default": 4000, "minimum": 1000, "maximum": 10000 }, + "search_scope": { "type": "string", "title": "Default search scope", "default": "repo", "enum": ["repo", "dir", "mine"] } + }, + "required": ["api_key"] + } +} diff --git a/integrations/cursor-plugin/agents/sidekick.md b/integrations/cursor-plugin/agents/sidekick.md new file mode 100644 index 000000000..31fa6e945 --- /dev/null +++ b/integrations/cursor-plugin/agents/sidekick.md @@ -0,0 +1,16 @@ +--- +name: sidekick +description: Coding agent with an isolated context. Delegate focused investigation, implementation, testing, debugging, or review work to it, then review its result. +model: inherit +--- + +You are Mem0's Cursor sidekick. Complete only the work the parent agent assigns. +Return a tested result the parent can review without repeating your investigation. + +Always call `search_memories` before work that can depend on earlier decisions, +repository history, or user preferences. Inspect the relevant code and repository +rules, make requested edits, and run the smallest decisive checks. + +Do not make adjacent improvements. Ask the parent one concise question only when +a material decision or unsafe ambiguity blocks progress. Otherwise proceed and +report the outcome, changed files, validation, and remaining risk. diff --git a/integrations/cursor-plugin/core/flush_worker.py b/integrations/cursor-plugin/core/flush_worker.py new file mode 100644 index 000000000..6f7b9ecb2 --- /dev/null +++ b/integrations/cursor-plugin/core/flush_worker.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Detached remote checkpoint worker. + +Claude Code may cancel SessionEnd hooks as a print-mode process exits. The hook +therefore persists its input first and launches this process in a new session. +""" + +from __future__ import annotations + +import json +import os +import sys +import time +from pathlib import Path + +import telemetry +from memory_core import ( + EvidenceStore, + checkpoint_session, + configure_harness, + touch_handoff_heartbeat, +) + + +def main() -> int: + if len(sys.argv) != 2: + return 2 + handoff_path = Path(sys.argv[1]) + os.environ["MEM0_CODE_HANDOFF_PATH"] = str(handoff_path) + harness = os.environ.get("MEM0_PLUGIN_HARNESS") + if harness: + source_tag = os.environ.get("MEM0_PLUGIN_SOURCE_TAG", "") + configure_harness( + harness, + env_prefix=os.environ.get("MEM0_PLUGIN_ENV_PREFIX", ""), + data_dir_name=os.environ.get("MEM0_PLUGIN_DATA_DIR_NAME", ""), + source_tag=source_tag, + ) + telemetry.init(harness=harness, source_tag=source_tag.upper()) + completed = False + try: + payload = json.loads(handoff_path.read_text(encoding="utf-8")) + delay = float(payload.get("delay_seconds") or 0) + if delay > 0: + payload.pop("delay_seconds", None) + temporary = handoff_path.with_suffix(f".{os.getpid()}.tmp") + try: + temporary.write_text(json.dumps(payload), encoding="utf-8") + temporary.replace(handoff_path) + finally: + temporary.unlink(missing_ok=True) + time.sleep(delay) + if not handoff_path.exists(): + return 0 + hook_input = payload.get("hook_input") or {} + reason = str(payload.get("reason") or "checkpoint") + wait_for_inflight = bool(payload.get("wait_for_inflight")) + store = EvidenceStore() + try: + if wait_for_inflight: + session_id = str( + hook_input.get("session_id") or "unknown-session" + ) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + deadline = time.monotonic() + float( + os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120") + ) + while ( + store.has_inflight_flush(repo.identity, session_id) + and time.monotonic() < deadline + ): + touch_handoff_heartbeat() + time.sleep(0.25) + # Hooks capture the conversation before handoff; the worker only flushes it. + result = checkpoint_session(store, hook_input, reason) + print(json.dumps(result, sort_keys=True), flush=True) + completed = result.get("status") in { + "semantic-succeeded", + "explicitly-stored", + "nothing-to-flush", + } + finally: + store.close() + return 0 + finally: + telemetry.flush() + if completed: + try: + handoff_path.unlink() + except OSError: + pass + elif handoff_path.suffix == ".running": + try: + handoff_path.replace(handoff_path.with_suffix(".json")) + except OSError: + pass + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/cursor-plugin/core/hook_runner.py b/integrations/cursor-plugin/core/hook_runner.py new file mode 100644 index 000000000..2a2adb557 --- /dev/null +++ b/integrations/cursor-plugin/core/hook_runner.py @@ -0,0 +1,372 @@ +"""Shared hook orchestration for all Mem0 agent plugins.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +import uuid +from pathlib import Path + +import telemetry +from memory_core import ( + EvidenceStore, + _session_id, + api_key, + bounded, + cache_plugin_api_key, + checkpoint_session, + clear_stale_api_key_cache, + configure_harness, + data_dir, + detached_process_kwargs, + format_context, + harness_config, + record_session_start, + record_tool, + record_user_prompt, + redact, + search_memories, +) + +STALE_RUNNING_SECONDS = 300 +PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60 +PENDING_LAUNCH_LIMIT = 5 +DEFAULT_IDLE_FLUSH_SECONDS = 300 + +_core_dir: Path = Path(__file__).resolve().parent + + +def read_hook_input() -> dict: + try: + value = json.load(sys.stdin) + return value if isinstance(value, dict) else {} + except (json.JSONDecodeError, OSError): + return {} + + +def default_record_stop(store: EvidenceStore, hook_input: dict): + """Record the assistant's response without transcript parsing.""" + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + message = redact(hook_input.get("last_assistant_message", "")).strip() + if message: + store.record_assistant_response(repo, session_id, message) + return repo, session_id + + +def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict: + """Search once before the agent handles the first prompt in a session.""" + repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input) + if not is_first_prompt: + return {} + try: + minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20")) + except ValueError: + minimum_query_chars = 20 + if len(prompt.strip()) < max(minimum_query_chars, 1): + return {} + result = search_memories( + store, repo, session_id, bounded(prompt, 6000), + top_k=5, operation="first-prompt-search", timeout=2, + ) + if not result.memories: + return {} + context = format_context( + result.memories, + "Mem0 found these relevant memories from earlier work in this repository:", + ) + telemetry.record( + "context_injected", + repo=repo, session_id=session_id, trigger="first-prompt", + memory_count=len(result.memories), context_chars=len(context), + prompt_chars=len(prompt), + ) + return { + "hookSpecificOutput": { + "hookEventName": "UserPromptSubmit", + "additionalContext": context, + }, + } + + +def _launch_handoff(handoff_path: Path) -> bool: + running_path = handoff_path.with_suffix(".running") + try: + handoff_path.replace(running_path) + except OSError: + return False + worker = _core_dir / "flush_worker.py" + log_path = data_dir() / "flush-worker.log" + log_handle = open(log_path, "a", encoding="utf-8") + harness = harness_config() + child_env = os.environ.copy() + child_env.update( + { + "MEM0_CODE_DATA_DIR": str(data_dir()), + "MEM0_PLUGIN_HARNESS": harness["name"], + "MEM0_PLUGIN_ENV_PREFIX": harness["env_prefix"], + "MEM0_PLUGIN_DATA_DIR_NAME": harness["data_dir_name"], + "MEM0_PLUGIN_SOURCE_TAG": harness["source_tag"], + } + ) + try: + subprocess.Popen( + [sys.executable, str(worker), str(running_path)], + stdin=subprocess.DEVNULL, + stdout=log_handle, stderr=log_handle, + close_fds=True, + env=child_env, + **detached_process_kwargs(), + ) + finally: + log_handle.close() + return True + + +def recover_pending_handoffs() -> int: + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + now = time.time() + for running in pending_dir.glob("*.running"): + try: + if now - running.stat().st_mtime > STALE_RUNNING_SECONDS: + running.replace(running.with_suffix(".json")) + except OSError: + continue + recoverable = [] + for handoff in pending_dir.glob("*.json"): + try: + age = now - handoff.stat().st_mtime + except OSError: + continue + if age > PENDING_EXPIRY_SECONDS: + handoff.unlink(missing_ok=True) + continue + recoverable.append((age, handoff)) + recoverable.sort(key=lambda item: item[0], reverse=True) + launched = 0 + for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]: + launched += int(_launch_handoff(handoff)) + return launched + + +def refresh_pending_handoffs() -> None: + pending_dir = data_dir() / "pending" + if not pending_dir.is_dir(): + return + for pattern in ("*.json", "*.running"): + for handoff in pending_dir.glob(pattern): + try: + os.utime(handoff) + except OSError: + continue + + +def hand_off_flush( + hook_input: dict, reason: str, *, wait_for_inflight: bool = False, +) -> None: + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + material = ( + f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}" + ) + digest = hashlib.sha256(material.encode()).hexdigest()[:24] + handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json" + temporary_path = handoff_path.with_suffix(".tmp") + temporary_path.write_text( + json.dumps({ + "hook_input": hook_input, + "reason": reason, + "wait_for_inflight": wait_for_inflight, + }), + encoding="utf-8", + ) + temporary_path.replace(handoff_path) + _launch_handoff(handoff_path) + + +def automatic_flush_enabled() -> bool: + return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in { + "1", "true", "yes", "on", + } + + +def schedule_periodic_checkpoint( + store: EvidenceStore, hook_input: dict, repo, session_id: str, +) -> bool: + if ( + not automatic_flush_enabled() + or not api_key() + or not store.checkpoint_due(repo.identity, session_id) + ): + return False + if store.prepare_flush(repo, session_id, "periodic") is None: + return False + hand_off_flush(hook_input, "periodic") + return True + + +def _idle_flush_seconds() -> int: + try: + return max( + int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))), + 0, + ) + except ValueError: + return DEFAULT_IDLE_FLUSH_SECONDS + + +def schedule_idle_flush( + store: EvidenceStore, hook_input: dict, repo, session_id: str, +) -> bool: + delay = _idle_flush_seconds() + if delay <= 0 or not automatic_flush_enabled() or not api_key(): + return False + if store.has_inflight_flush(repo.identity, session_id): + return False + if not store.has_unflushed_events(repo.identity, session_id): + return False + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}" + digest = hashlib.sha256(material.encode()).hexdigest()[:24] + for old in pending_dir.glob(f"idle-{digest}*"): + old.unlink(missing_ok=True) + handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json" + temporary_path = handoff_path.with_suffix(".tmp") + temporary_path.write_text( + json.dumps({ + "hook_input": hook_input, + "reason": "idle", + "delay_seconds": delay, + }), + encoding="utf-8", + ) + temporary_path.replace(handoff_path) + _launch_handoff(handoff_path) + return True + + +def log_failure(exc: Exception) -> None: + try: + log_path = data_dir() / "plugin-errors.log" + with log_path.open("a", encoding="utf-8") as handle: + handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n") + except OSError: + pass + + +def run( + *, + record_stop_fn=None, + extra_actions: dict | None = None, + data_dir_env: str = "MEM0_PLUGIN_DATA_DIR", + automatic_flush_reasons: set | None = None, +) -> int: + if record_stop_fn is None: + record_stop_fn = default_record_stop + if automatic_flush_reasons is None: + automatic_flush_reasons = {"session-end"} + + base_actions = ["session-start", "user-prompt", "post-tool", "stop", "flush"] + all_actions = base_actions + list((extra_actions or {}).keys()) + + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=all_actions) + parser.add_argument("--reason", default="manual") + parser.add_argument("--plugin-data-dir", default="") + parser.add_argument("--harness", default="") + args = parser.parse_args() + + if args.harness: + configure_harness(args.harness) + telemetry.init(harness=args.harness) + + if args.plugin_data_dir: + os.environ[data_dir_env] = args.plugin_data_dir + + cache_plugin_api_key() + if args.action == "session-start": + clear_stale_api_key_cache() + + hook_input = read_hook_input() + store = EvidenceStore() + try: + if store.is_paused(): + if args.action == "session-start": + refresh_pending_handoffs() + telemetry.record("session_start", paused=True) + telemetry.spawn_flush() + return 0 + + if args.action == "session-start": + if telemetry.is_first_run(): + telemetry.record("install") + recovered = recover_pending_handoffs() + record_session_start(store, hook_input) + if recovered: + telemetry.record("handoff_recovered", count=recovered) + telemetry.spawn_flush() + elif args.action == "user-prompt": + output = first_prompt_memory_output(store, hook_input) + if output: + print(json.dumps(output)) + elif args.action == "post-tool": + record_tool(store, hook_input) + elif args.action == "stop": + repo, session_id = record_stop_fn(store, hook_input) + if not schedule_periodic_checkpoint(store, hook_input, repo, session_id): + schedule_idle_flush(store, hook_input, repo, session_id) + elif args.action == "flush": + automatic = args.reason in automatic_flush_reasons + if automatic and not automatic_flush_enabled(): + return 0 + if args.reason == "session-end": + record_stop_fn(store, hook_input) + if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1": + print(json.dumps(checkpoint_session(store, hook_input, args.reason))) + else: + session_id = str(hook_input.get("session_id") or "unknown-session") + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + already_running = store.has_inflight_flush(repo.identity, session_id) + if already_running and args.reason == "session-end": + hand_off_flush(hook_input, args.reason, wait_for_inflight=True) + elif not already_running and store.prepare_flush( + repo, session_id, args.reason, + ) is not None: + hand_off_flush(hook_input, args.reason) + elif extra_actions and args.action in extra_actions: + result = extra_actions[args.action](store, hook_input) + if result: + print(json.dumps(result)) + finally: + store.close() + return 0 + + +def entry_point( + *, + record_stop_fn=None, + extra_actions: dict | None = None, + data_dir_env: str = "MEM0_PLUGIN_DATA_DIR", + automatic_flush_reasons: set | None = None, +) -> None: + try: + raise SystemExit(run( + record_stop_fn=record_stop_fn, + extra_actions=extra_actions, + data_dir_env=data_dir_env, + automatic_flush_reasons=automatic_flush_reasons, + )) + except Exception as exc: + log_failure(exc) + raise SystemExit(0) + + +if __name__ == "__main__": + entry_point() diff --git a/integrations/cursor-plugin/core/mcp_server.py b/integrations/cursor-plugin/core/mcp_server.py new file mode 100644 index 000000000..036fbbdc9 --- /dev/null +++ b/integrations/cursor-plugin/core/mcp_server.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Expose Mem0's memory search as one local coding-agent tool.""" + +from __future__ import annotations + +import json +import os +import sys +from typing import Any + +import telemetry +from memory_core import ( + CODING_MEMORY_CATEGORY_NAMES, + PLUGIN_VERSION, + SEARCH_SCOPES, + format_search_result, + resolve_repo, + search_memories, +) + +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." +) +TOOL_SCHEMA = { + "type": "object", + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 2000, + "description": "A direct question about earlier work in this repository.", + }, + "top_k": { + "type": "integer", + "minimum": 1, + "maximum": 20, + "description": "Maximum memories to return. Uses Mem0's configured default when omitted.", + }, + "category": { + "type": "string", + "enum": list(CODING_MEMORY_CATEGORY_NAMES), + "description": "Optional memory category. Omit to search every category.", + }, + "scope": { + "type": "string", + "enum": list(SEARCH_SCOPES), + "description": ( + "Which memories to search. 'repo' (default) is the whole repository's " + "shared memory plus your own preferences, 'dir' narrows the shared " + "part to the current directory, 'mine' is your preferences alone." + ), + }, + "run_id": { + "type": "string", + "minLength": 1, + "description": ( + "Optional coding-agent session ID. With any scope, restricts results to memories " + "saved in that session. Omit to recall memories across sessions." + ), + }, + }, + "required": ["query"], + "additionalProperties": False, +} + + +class ToolInputError(ValueError): + pass + + +def _validate_arguments( + arguments: Any, +) -> tuple[str, int | None, str | None, str | None, str | None]: + if not isinstance(arguments, dict): + raise ToolInputError("Search arguments must be an object.") + + unknown = set(arguments) - {"query", "top_k", "category", "scope", "run_id"} + if unknown: + raise ToolInputError(f"Unknown search argument: {sorted(unknown)[0]}") + + query = arguments.get("query") + if not isinstance(query, str) or not query.strip(): + raise ToolInputError("query must be a non-empty string.") + query = query.strip() + if len(query) > 2000: + raise ToolInputError("query must be at most 2,000 characters.") + + top_k = arguments.get("top_k") + if top_k is not None and ( + isinstance(top_k, bool) or not isinstance(top_k, int) or not 1 <= top_k <= 20 + ): + raise ToolInputError("top_k must be an integer from 1 to 20.") + + category = arguments.get("category") + if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES: + raise ToolInputError("category must be one of Mem0's supported categories.") + + scope = arguments.get("scope") + if scope is not None and scope not in SEARCH_SCOPES: + raise ToolInputError(f"scope must be one of {list(SEARCH_SCOPES)}.") + + run_id = arguments.get("run_id") + if run_id is not None: + if not isinstance(run_id, str) or not run_id.strip(): + raise ToolInputError("run_id must be a non-empty string.") + run_id = run_id.strip() + + return query, top_k, category, scope, run_id + + +def call_search_memories(arguments: Any, cwd: str | None = None) -> str: + query, top_k, category, scope, run_id = _validate_arguments(arguments) + repo = resolve_repo(cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()) + result = search_memories( + None, + repo, + None, + query, + top_k=top_k, + category=category, + scope=scope, + run_id=run_id, + operation="mcp-search", + ) + return format_search_result(result) + + +def _workspace_cwd(params: dict[str, Any]) -> str | None: + meta = params.get("_meta") + if not isinstance(meta, dict): + return None + metadata = meta.get("x-codex-turn-metadata") + if not isinstance(metadata, dict): + return None + workspaces = metadata.get("workspaces") or {} + if isinstance(workspaces, dict): + return next((path for path in workspaces if isinstance(path, str) and path), None) + return None + + +def _tool_response(text: str, *, is_error: bool = False) -> dict[str, Any]: + return { + "content": [{"type": "text", "text": text}], + "isError": is_error, + } + + +def handle_request(message: Any) -> dict[str, Any] | None: + if not isinstance(message, dict): + return None + request_id = message.get("id") + method = message.get("method") + + if method == "notifications/initialized": + return None + if method == "initialize": + requested = (message.get("params") or {}).get("protocolVersion") + return { + "jsonrpc": "2.0", + "id": request_id, + "result": { + "protocolVersion": requested or PROTOCOL_VERSION, + "capabilities": {"tools": {"listChanged": False}}, + "serverInfo": {"name": "mem0", "version": PLUGIN_VERSION}, + }, + } + if method == "ping": + return {"jsonrpc": "2.0", "id": request_id, "result": {}} + if method == "tools/list": + return { + "jsonrpc": "2.0", + "id": request_id, + "result": { + "tools": [ + { + "name": TOOL_NAME, + "description": TOOL_DESCRIPTION, + "inputSchema": TOOL_SCHEMA, + "annotations": { + "readOnlyHint": True, + "idempotentHint": True, + "openWorldHint": True, + }, + } + ] + }, + } + if method == "tools/call": + params = message.get("params") or {} + if params.get("name") != TOOL_NAME: + result = _tool_response("Unknown Mem0 tool.", is_error=True) + else: + try: + result = _tool_response( + call_search_memories(params.get("arguments"), _workspace_cwd(params)) + ) + except ToolInputError as exc: + result = _tool_response(str(exc), is_error=True) + except Exception: + result = _tool_response("Memory search failed.", is_error=True) + return {"jsonrpc": "2.0", "id": request_id, "result": result} + if request_id is None: + return None + return { + "jsonrpc": "2.0", + "id": request_id, + "error": {"code": -32601, "message": "Method not found"}, + } + + +def main() -> int: + for raw_line in sys.stdin: + try: + message = json.loads(raw_line) + response = handle_request(message) + except json.JSONDecodeError: + response = { + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32700, "message": "Parse error"}, + } + except Exception: + response = { + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32603, "message": "Internal error"}, + } + if response is not None: + sys.stdout.write(json.dumps(response, separators=(",", ":")) + "\n") + sys.stdout.flush() + telemetry.spawn_flush() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/cursor-plugin/core/memory_cli.py b/integrations/cursor-plugin/core/memory_cli.py new file mode 100644 index 000000000..595729feb --- /dev/null +++ b/integrations/cursor-plugin/core/memory_cli.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Mem0 diagnostics and user controls.""" + +from __future__ import annotations + +import argparse +import json +import os + +import telemetry +from memory_core import ( + EvidenceStore, + api_key, + data_dir, + doctor, + forget_remote_repo, + configure_harness, + resolve_repo, + user_id, +) + + +def _print_status(value: dict) -> None: + last = value.get("last_operation") or {} + print(f"Mem0: {'paused' if value['paused'] else 'active'}") + print(f"Repository: {value['repo_id']}") + print(f"Local data: {value['data_dir']}") + print(f"API key: {'configured' if value['api_key_configured'] else 'missing'}") + print( + "Saved on this computer: " + f"{value['events']} session details, {value['flushes']} memory updates" + ) + print( + f"Used in this repository: {value['retrievals']} memories returned, " + f"{value['sidekick_runs']} sidekick runs" + ) + if last: + item_label = "" + if last["operation"] in {"flush", "flush-retry"}: + item_label = f", {last['item_count']} memories" + operation = ( + "memory update" + if last["operation"] in {"flush", "flush-retry"} + else last["operation"].replace("-", " ") + ) + print( + f"Last {operation}: " + f"{'succeeded' if last['success'] else 'failed'} " + f"({last['duration_ms']:.1f} ms{item_label})" + ) + sidekick = value.get("last_sidekick") or {} + if sidekick: + state = "finished" if sidekick.get("stopped_at") else "started" + print( + "Last sidekick: " + f"{state}, received {sidekick['context_chars']} characters of memory, " + f"agent {sidekick['agent_id']}" + ) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--plugin-data-dir", default="") + parser.add_argument("--harness", default="") + subparsers = parser.add_subparsers(dest="command", required=True) + + status = subparsers.add_parser("status") + status.add_argument("--json", action="store_true") + + doctor_parser = subparsers.add_parser("doctor") + doctor_parser.add_argument("--json", action="store_true") + + subparsers.add_parser("pause") + subparsers.add_parser("resume") + + forget = subparsers.add_parser("forget") + forget.add_argument("--remote", action="store_true") + forget.add_argument("--yes", action="store_true") + forget.add_argument("--include-project-memory", action="store_true") + + args = parser.parse_args() + if args.harness: + source_tag = f"{args.harness.replace('-', '_')}_plugin" + configure_harness(args.harness, source_tag=source_tag) + telemetry.init(harness=args.harness, source_tag=source_tag.upper()) + if args.plugin_data_dir: + os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir + store = EvidenceStore() + try: + repo = resolve_repo(os.getcwd()) + telemetry.record("control", repo=repo, action=args.command) + if args.command == "status": + result = { + **store.status(repo.identity), + "repo_id": repo.identity, + "app_id": repo.app_id, + "project_id": repo.project_id, + "directory": repo.directory, + "user_id": user_id(), + "data_dir": str(data_dir()), + "api_key_configured": bool(api_key()), + } + if args.json: + print(json.dumps(result, indent=2, default=str)) + else: + _print_status(result) + elif args.command == "doctor": + result = doctor(os.getcwd()) + if args.json: + print(json.dumps(result, indent=2, default=str)) + else: + for name, check in result["checks"].items(): + print( + f"{'PASS' if check['ok'] else 'FAIL'} {name}: {check['detail']}" + ) + return 0 if result["ok"] else 1 + elif args.command == "pause": + store.set_setting("paused", "true") + print("Mem0 stopped saving and searching memories.") + elif args.command == "resume": + store.set_setting("paused", "false") + print("Mem0 resumed saving and searching memories.") + elif args.command == "forget": + if not args.yes: + print( + "Refusing to delete data without --yes. Add --remote to also " + "delete this user/repository scope from Mem0." + ) + return 2 + remote_result = ( + forget_remote_repo( + repo, include_project_memory=args.include_project_memory + ) + if args.remote + else None + ) + local_result = store.forget_local_repo(repo.identity) + print( + json.dumps( + {"local": local_result, "remote": remote_result}, + indent=2, + default=str, + ) + ) + if remote_result and remote_result.get("status") == "error": + return 1 + finally: + store.close() + telemetry.spawn_flush() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/cursor-plugin/core/memory_core.py b/integrations/cursor-plugin/core/memory_core.py new file mode 100644 index 000000000..cf71196b8 --- /dev/null +++ b/integrations/cursor-plugin/core/memory_core.py @@ -0,0 +1,2645 @@ +#!/usr/bin/env python3 +"""Shared core for Mem0 agent plugins. + +Hooks record small session details locally. When the agent compacts or ends the +session, Mem0 sends the useful parts to the platform so it can create memories. +The agent can search those memories during later work in the repository. +""" + +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import sqlite3 +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Iterable + +import telemetry + +DEFAULT_API_URL = "https://api.mem0.ai" +PLUGIN_VERSION = "0.3.1" + +_harness_name: str = "generic" +_harness_env_prefix: str = "MEM0_PLUGIN" +_harness_data_dir_name: str = "mem0-plugin" +_harness_source_tag: str = "mem0_plugin" + + +def configure_harness( + name: str, + env_prefix: str = "", + data_dir_name: str = "", + source_tag: str = "", +) -> None: + global _harness_name, _harness_env_prefix, _harness_data_dir_name, _harness_source_tag + _harness_name = name + _harness_env_prefix = env_prefix or f"MEM0_{name.upper().replace('-', '_')}" + _harness_data_dir_name = data_dir_name or f"{name}-plugin" + _harness_source_tag = source_tag or f"{name.replace('-', '_')}_plugin" + + +def harness_config() -> dict[str, str]: + return { + "name": _harness_name, + "env_prefix": _harness_env_prefix, + "data_dir_name": _harness_data_dir_name, + "source_tag": _harness_source_tag, + } + + +MAX_COMMAND_CHARS = 2000 +MAX_RESULT_CHARS = 2500 +MAX_EPISODE_CHARS = 12000 +CHECKPOINT_EXCHANGES = 5 +CHECKPOINT_MESSAGES = 10 +CHECKPOINT_SOURCE_CHARS = 40000 +DEFAULT_MAX_CONTEXT_CHARS = 4000 +MAX_EXTRACTION_INPUT_TOKENS = 24000 +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. + +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 current coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions. + +Write about the repository, not the user, assistant, session, or task. Do not save personal preferences. Do not save a memory that only states which repository, branch, or directory the session worked in. Do not include test results, documentation updates, release notes, or temporary state. + +If nothing useful was established, return no memories.""" + +PERSONAL_MEMORY_INSTRUCTIONS = """Save concise facts about the user that will help in any repository: preferred tools, package managers, languages, coding style, review and communication preferences, and anything the user explicitly asked to be remembered about themselves. + +Write in the third person about the user, not about the repository, the assistant, the session, or the task. Do not save repository facts, project decisions, commands, or what was built. + +Never save that the user has no preferences or that nothing was learned. If nothing was learned about the user, return no memories.""" + +CODING_MEMORY_CATEGORIES = [ + { + "project_knowledge": ( + "What the project is and how its code, APIs, data, files, and " + "components work." + ) + }, + { + "decisions_and_constraints": ( + "Why an approach was chosen, what must remain true, and rules future " + "work must follow." + ) + }, + { + "workflows": ( + "How to run, test, debug, deploy, configure, or otherwise work on the " + "project." + ) + }, + { + "problems_and_fixes": ( + "Bugs, failures, known pitfalls, their causes, and how to fix or avoid " + "them." + ) + }, + { + "results": ( + "Outcomes and measurements from tests, benchmarks, experiments, or " + "investigations." + ) + }, +] +CODING_MEMORY_CATEGORY_NAMES = tuple( + category_name + for category in CODING_MEMORY_CATEGORIES + for category_name in category +) + +TEST_COMMAND_RE = re.compile( + r"(?:^|\s)(?:pytest|py\.test|jest|vitest|go\s+test|cargo\s+test|" + r"npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|" + r"mvn\s+test|gradle\s+test|make\s+test)(?:\s|$)", + re.IGNORECASE, +) +BUILD_COMMAND_RE = re.compile( + r"(?:^|\s)(?:npm|pnpm|yarn)\s+(?:run\s+)?build(?:\s|$)|" + r"(?:^|\s)(?:cargo|go|mvn|gradle|make)\s+build(?:\s|$)", + re.IGNORECASE, +) + +SECRET_PATTERNS = [ + re.compile(r"(?i)(authorization\s*[:=]\s*(?:bearer|token)\s+)[^\s\"']+"), + re.compile( + r"(?i)((?:api[_-]?key|secret[_-]?access[_-]?key|session[_-]?token)\s*[:=]\s*)[^\s\"']+" + ), + re.compile( + r"(?i)((?:access[_-]?token|refresh[_-]?token|password|credential)" + r"\s*[:=]\s*)[^\s&\"']+" + ), + re.compile(r"\b(?:sk|m0|mem0_sk|psk)-[A-Za-z0-9_\-]{12,}\b"), + re.compile(r"\b(?:ASIA|AKIA)[A-Z0-9]{12,}\b"), + re.compile(r"\b(?:ghp_|github_pat_|xox[baprs]-)[A-Za-z0-9_\-]{12,}\b"), + re.compile( + r"-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----", + re.DOTALL, + ), + re.compile( + r'(?i)("(?:api[_-]?key|password|secret(?:[_-]?access[_-]?key)?' + r'|(?:access|refresh|session)[_-]?token|token|authorization|credential' + r')"\s*:\s*")(?:\\.|[^"\\])*' + ), +] + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def redact(value: Any) -> str: + text = ( + value + if isinstance(value, str) + else json.dumps(value, ensure_ascii=False, default=str) + ) + for pattern in SECRET_PATTERNS: + if pattern.groups: + text = pattern.sub(r"\1[REDACTED]", text) + else: + text = pattern.sub("[REDACTED]", text) + return text + + +def bounded(value: Any, limit: int) -> str: + text = redact(value).strip() + if len(text) <= limit: + return text + return text[:limit] + f"\n...[truncated {len(text) - limit} chars]" + + +def _git(cwd: str, *args: str) -> str: + try: + result = subprocess.run( + ["git", "-C", cwd, *args], + check=False, + capture_output=True, + text=True, + timeout=0.5, + ) + except (OSError, subprocess.TimeoutExpired): + return "" + return result.stdout.strip() if result.returncode == 0 else "" + + +def _normalize_remote(remote: str) -> str: + remote = remote.strip() + if remote.startswith("git@") and ":" in remote: + host_path = remote[4:].replace(":", "/", 1) + remote = f"https://{host_path}" + if remote.endswith(".git"): + remote = remote[:-4] + if "://" in remote: + parsed = urllib.parse.urlsplit(remote) + hostname = parsed.hostname or "" + if parsed.port: + hostname = f"{hostname}:{parsed.port}" + remote = urllib.parse.urlunsplit( + (parsed.scheme, hostname, parsed.path, parsed.query, parsed.fragment) + ) + return remote.rstrip("/") + + +_WILDCARD_SCOPE = re.compile(r"^\*+$") + + +def _scope_value(raw: str | None) -> str: + """Reject wildcards as identities: they are filter syntax and would widen the scope.""" + value = (raw or "").strip() + return "" if _WILDCARD_SCOPE.match(value) else value + + +SEARCH_SCOPES = ("repo", "dir", "mine") +DEFAULT_SEARCH_SCOPE = "repo" + +def directory_app_id(repo: RepoContext) -> str: + """The app_id of the directory this session runs in: the repository at the root, repository/path below it.""" + return f"{repo.app_id}/{repo.directory}" if repo.directory else repo.app_id + + +def directory_chain(repo: RepoContext) -> list[str]: + """Every directory a memory belongs to, from the top-level folder down to the one it was written in.""" + parts = repo.directory.split("/") if repo.directory else [] + return ["/".join(parts[: index + 1]) for index in range(len(parts))] + + +def _shared_project_ids(repo: RepoContext) -> list[str]: + """Current and pre-upgrade namespaces, shared by recall and explicit deletion.""" + if not repo.identity.startswith("local:") and repo.project_id != repo.app_id: + return [repo.project_id, repo.app_id] + return [repo.project_id] + + +def _search_filters(user: str, repo: RepoContext, scope: str) -> dict[str, Any]: + """Build the scope filter: app_id scopes to the repo, then union shared and personal lanes.""" + app_scope = {"app_id": repo.app_id} + mine = {"AND": [{"user_id": user}, app_scope]} + if scope == "mine": + return mine + projects = [{"AND": [{"agent_id": project_id}, app_scope]} for project_id in _shared_project_ids(repo)] + shared: dict[str, Any] = projects[0] if len(projects) == 1 else {"OR": projects} + if scope == "dir" and repo.directory: + shared = {"AND": [shared, {"metadata": {"dirs": {"contains": repo.directory}}}]} + return {"OR": [shared, mine]} + + +def search_scope() -> str: + configured = ( + _plugin_option("search_scope", "MEM0_CODE_SEARCH_SCOPE") or "" + ).strip().lower() + return configured if configured in SEARCH_SCOPES else DEFAULT_SEARCH_SCOPE + + +def resolve_search_scope(scope: str | None) -> str: + value = (scope or search_scope()).strip().lower() + if value not in SEARCH_SCOPES: + raise ValueError(f"Unknown search scope: {value}") + return value + + +def _legacy_project_map(cwd: str, root: str, raw_remote: str) -> str: + """Return the project name used by the previous Claude Code plugin.""" + try: + data = json.loads((Path.home() / ".mem0" / "project_map.json").read_text()) + except (OSError, json.JSONDecodeError): + return "" + if not isinstance(data, dict): + return "" + + keys = list(dict.fromkeys([cwd, root, os.path.realpath(cwd), os.path.realpath(root)])) + if raw_remote: + keys.append(f"remote:{hashlib.sha256(raw_remote.encode()).hexdigest()[:16]}") + for key in keys: + value = data.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + return "" + + +def _legacy_project_id(cwd: str, root: str, raw_remote: str, identity: str) -> str: + """Use the repository namespace created by the previous Mem0 plugin.""" + configured = _scope_value(os.environ.get("MEM0_PROJECT_ID")) + if configured: + return configured + + mapped = _scope_value(_legacy_project_map(cwd, root, raw_remote)) + if mapped: + return mapped + + remote = raw_remote or ("" if identity.startswith("local:") else identity) + remote = remote.strip().removesuffix(".git") + for prefix in ("https://", "http://", "ssh://", "git://"): + if remote.startswith(prefix): + remote = remote[len(prefix) :] + break + else: + remote = re.sub(r"^git@", "", remote) + parts = [part for part in remote.replace(":", "/", 1).split("/") if part] + if len(parts) >= 2: + return f"{parts[-2]}-{parts[-1]}".replace("/", "-").replace(":", "-") + if parts: + return parts[-1].replace("/", "-").replace(":", "-") + return os.path.basename(root or cwd) or "unknown" + + +@dataclass(frozen=True) +class RepoContext: + cwd: str + root: str + identity: str + app_id: str + branch: str + head_sha: str + project_id: str = "" + directory: str = "" + + +def _project_id(root: str, identity: str, app_id: str) -> str: + """The shared namespace: includes a host hash so repos with the same owner/name on different hosts stay apart.""" + if not identity.startswith("local:"): + return f"{app_id}-{hashlib.sha256(identity.encode()).hexdigest()[:10]}" + return f"local-{app_id}-{hashlib.sha256(root.encode()).hexdigest()[:10]}" + + +def _relative_directory(cwd: str, root: str) -> str: + relative = os.path.relpath(cwd, root) + return "" if relative == "." or relative.startswith("..") else relative.replace(os.sep, "/") + + +@dataclass(frozen=True) +class MemorySearchResult: + succeeded: bool + matched_count: int + already_shown_count: int + memories: list[dict[str, Any]] + + +@functools.lru_cache(maxsize=64) +def _resolve_repo_cached(cwd: str) -> RepoContext: + given_cwd = cwd + cwd = os.path.realpath(cwd) + given_root = _git(cwd, "rev-parse", "--show-toplevel") or given_cwd + root = os.path.realpath(given_root) + raw_remote = _git(root, "config", "--get", "remote.origin.url") + remote = _normalize_remote(raw_remote) + identity = remote or f"local:{root}" + app_id = _legacy_project_id(given_cwd, given_root, raw_remote, identity) + return RepoContext( + cwd=cwd, + root=root, + identity=identity, + app_id=app_id, + branch=_git(root, "branch", "--show-current") or "detached", + head_sha=_git(root, "rev-parse", "HEAD"), + project_id=_project_id(root, identity, app_id), + directory=_relative_directory(cwd, root), + ) + + +def resolve_repo(cwd: str | None) -> RepoContext: + return _resolve_repo_cached(os.path.abspath(cwd or os.getcwd())) + + +def api_key() -> str: + configured = ( + os.environ.get("MEM0_API_KEY") + or os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if configured: + return configured + try: + return (data_dir() / "api-key").read_text(encoding="utf-8").strip() + except OSError: + return "" + + +def cache_plugin_api_key() -> bool: + """Bridge host's hook-only sensitive config into plugin-owned storage.""" + configured = ( + os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if not configured: + return False + + directory = data_dir() + directory.mkdir(parents=True, exist_ok=True) + path = directory / "api-key" + temporary = directory / f"api-key.{os.getpid()}.tmp" + descriptor = os.open( + temporary, + os.O_WRONLY | os.O_CREAT | os.O_TRUNC, + 0o600, + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + handle.write(configured) + os.replace(temporary, path) + os.chmod(path, 0o600) + finally: + try: + temporary.unlink() + except FileNotFoundError: + pass + return True + + +def clear_stale_api_key_cache() -> bool: + """Drop the cached key file once every configured key source is gone.""" + configured = ( + os.environ.get("MEM0_API_KEY") + or os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if configured: + return False + path = data_dir() / "api-key" + if not path.exists(): + return False + try: + path.unlink() + except OSError: + return False + return True + + +def detached_process_kwargs(platform: str | None = None) -> dict: + """Keep a spawned worker alive after the coding agent exits, on POSIX and Windows.""" + if (platform or sys.platform) == "win32": + return { + "creationflags": subprocess.DETACHED_PROCESS + | subprocess.CREATE_NEW_PROCESS_GROUP + } + return {"start_new_session": True} + + +def _plugin_option(name: str, fallback: str = "") -> str: + return ( + os.environ.get(f"PLUGIN_OPTION_{name.upper()}") + or os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name.upper()}") + or os.environ.get(fallback) + or "" + ).strip() + + +def user_id() -> str: + return ( + _scope_value(_plugin_option("user_id", "MEM0_CODE_USER_ID")) + or _scope_value(os.environ.get("MEM0_USER_ID")) + or _scope_value(os.environ.get("MEM0_RESOLVED_USER_ID")) + or _scope_value(os.environ.get("USER")) + or _scope_value(os.environ.get("USERNAME")) + or "default" + ) + + +def data_dir() -> Path: + configured = ( + os.environ.get("MEM0_CODE_DATA_DIR") + or os.environ.get("MEM0_PLUGIN_DATA_DIR") + or os.environ.get("PLUGIN_DATA") + or os.environ.get("CLAUDE_PLUGIN_DATA") + ) + return ( + Path(configured).expanduser() if configured else Path.home() / ".mem0" / _harness_data_dir_name + ) + + +def _bool_option(name: str, fallback: str, default: bool = False) -> bool: + value = _plugin_option(name, fallback) + if not value: + return default + return value.lower() in {"1", "true", "yes", "on"} + + +def _int_option(name: str, fallback: str, default: int) -> int: + value = _plugin_option(name, fallback) + try: + return int(value) if value else default + except ValueError: + return default + + + +def _checkpoint_message(event: dict[str, Any]) -> str: + kind = event.get("kind") + payload = event.get("payload") or {} + if kind == "user_prompt": + return redact(payload.get("text", "")).strip() + if kind == "assistant_stop": + transcript_messages = payload.get("transcript_messages") or [] + if isinstance(transcript_messages, list): + text = "\n".join( + str(message.get("content") or "") + for message in transcript_messages + if isinstance(message, dict) and message.get("content") + ) + if text: + return text + return redact(payload.get("text", "")).strip() + if kind == "sidekick_stop": + return redact(payload.get("final_message", "")).strip() + return "" + + +def checkpoint_stats(events: list[dict[str, Any]]) -> tuple[int, int, int]: + """Return completed exchanges, messages, and source characters.""" + completed = sum(event.get("kind") == "assistant_stop" for event in events) + contents = [content for event in events if (content := _checkpoint_message(event))] + return completed, len(contents), sum(len(content) for content in contents) + + +def select_checkpoint_events( + events: list[dict[str, Any]], *, force: bool +) -> list[dict[str, Any]]: + """Select one ordered extraction block without splitting an exchange.""" + for index, event in enumerate(events): + if event.get("kind") != "assistant_stop": + continue + candidate = events[: index + 1] + completed, messages, source_chars = checkpoint_stats(candidate) + if ( + completed >= CHECKPOINT_EXCHANGES + or messages >= CHECKPOINT_MESSAGES + or source_chars >= CHECKPOINT_SOURCE_CHARS + ): + return candidate + return events if force else [] + + +class EvidenceStore: + def __init__(self, path: Path | None = None): + directory = data_dir() if path is None else path.parent + directory.mkdir(parents=True, exist_ok=True) + self.path = path or directory / "evidence.sqlite3" + try: + self._open() + except sqlite3.DatabaseError: + self._quarantine() + self._open() + + def _open(self) -> None: + self.conn = sqlite3.connect(self.path, timeout=10) + self.conn.row_factory = sqlite3.Row + try: + self.conn.execute("PRAGMA journal_mode=WAL") + self.conn.execute("PRAGMA busy_timeout=10000") + self._migrate() + except sqlite3.DatabaseError: + self.conn.close() + raise + + def _quarantine(self) -> None: + """Move an unreadable database aside so capture restarts cleanly.""" + stamp = int(time.time()) + for suffix in ("", "-wal", "-shm"): + source = Path(f"{self.path}{suffix}") + try: + source.replace(f"{self.path}.corrupt-{stamp}{suffix}") + except FileNotFoundError: + continue + except OSError: + try: + source.unlink() + except OSError: + pass + telemetry.record("db_quarantined") + + def close(self) -> None: + self.conn.close() + + def _migrate(self) -> None: + self.conn.executescript( + """ + CREATE TABLE IF NOT EXISTS events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + session_id TEXT NOT NULL, + created_at TEXT NOT NULL, + kind TEXT NOT NULL, + payload_json TEXT NOT NULL, + flush_id TEXT + ); + CREATE INDEX IF NOT EXISTS events_session_idx + ON events(repo_id, session_id, flush_id, id); + + CREATE TABLE IF NOT EXISTS session_scopes ( + session_id TEXT PRIMARY KEY, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + root TEXT NOT NULL, + branch TEXT NOT NULL, + head_sha TEXT NOT NULL, + created_at TEXT NOT NULL, + directory TEXT NOT NULL DEFAULT '' + ); + + CREATE TABLE IF NOT EXISTS flushes ( + packet_id TEXT PRIMARY KEY, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + session_id TEXT NOT NULL, + reason TEXT NOT NULL, + event_start INTEGER NOT NULL, + event_end INTEGER NOT NULL, + status TEXT NOT NULL, + episode_event_id TEXT, + semantic_event_id TEXT, + error TEXT, + attempts INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS retrievals ( + session_id TEXT NOT NULL, + repo_id TEXT NOT NULL, + memory_id TEXT NOT NULL, + injected_at TEXT NOT NULL, + rank INTEGER, + score REAL, + memory_text TEXT, + context_chars INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY(session_id, repo_id, memory_id) + ); + + CREATE TABLE IF NOT EXISTS operations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created_at TEXT NOT NULL, + repo_id TEXT NOT NULL, + session_id TEXT NOT NULL, + operation TEXT NOT NULL, + duration_ms REAL NOT NULL, + success INTEGER NOT NULL, + item_count INTEGER NOT NULL DEFAULT 0, + request_chars INTEGER NOT NULL DEFAULT 0, + response_chars INTEGER NOT NULL DEFAULT 0, + error TEXT + ); + + CREATE TABLE IF NOT EXISTS sidekick_runs ( + repo_id TEXT NOT NULL, + session_id TEXT NOT NULL, + agent_id TEXT NOT NULL, + agent_type TEXT NOT NULL, + started_at TEXT NOT NULL, + stopped_at TEXT, + transcript_path TEXT, + context_chars INTEGER NOT NULL DEFAULT 0, + final_message TEXT, + PRIMARY KEY(repo_id, session_id, agent_id) + ); + CREATE INDEX IF NOT EXISTS sidekick_runs_repo_idx + ON sidekick_runs(repo_id, started_at); + + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + """ + ) + # Remove the pre-0.1.1 no-tools snapshot implementation. The real coding + # sidekick is a native Claude Code agent and stores no state in this DB. + self.conn.executescript( + """ + DROP TABLE IF EXISTS sidekick_calls; + DROP TABLE IF EXISTS sidekick_snapshots; + DROP TABLE IF EXISTS sidekick_state; + DROP TABLE IF EXISTS sidekick_packets; + """ + ) + self._ensure_column("retrievals", "rank", "INTEGER") + self._ensure_column("retrievals", "score", "REAL") + self._ensure_column("retrievals", "memory_text", "TEXT") + self._ensure_column("retrievals", "context_chars", "INTEGER NOT NULL DEFAULT 0") + self._ensure_column("flushes", "attempts", "INTEGER NOT NULL DEFAULT 0") + self._ensure_column("session_scopes", "directory", "TEXT NOT NULL DEFAULT ''") + self.conn.commit() + + def _ensure_column(self, table: str, column: str, declaration: str) -> None: + columns = { + str(row["name"]) + for row in self.conn.execute(f"PRAGMA table_info({table})").fetchall() + } + if column not in columns: + self.conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {declaration}") + + def record_event( + self, + repo: RepoContext, + session_id: str, + kind: str, + payload: dict[str, Any], + ) -> int: + cursor = self.conn.execute( + """INSERT INTO events + (repo_id, app_id, session_id, created_at, kind, payload_json) + VALUES (?, ?, ?, ?, ?, ?)""", + ( + repo.identity, + repo.app_id, + session_id, + utc_now(), + kind, + json.dumps(payload, ensure_ascii=False, sort_keys=True), + ), + ) + self.conn.commit() + return int(cursor.lastrowid) + + def record_assistant_response(self, repo: RepoContext, session_id: str, message: str) -> None: + """Ignore repeated response hooks until another prompt or a different answer arrives.""" + with self.conn: + # Serialize the check and insert across concurrent Stop and SessionEnd hooks. + self.conn.execute("BEGIN IMMEDIATE") + previous = self.conn.execute( + """SELECT kind, payload_json FROM events + WHERE repo_id = ? AND session_id = ? AND kind IN ('user_prompt', 'assistant_stop') + ORDER BY id DESC LIMIT 1""", + (repo.identity, session_id), + ).fetchone() + if ( + previous is not None + and previous["kind"] == "assistant_stop" + and json.loads(previous["payload_json"]).get("text") == message + ): + return + self.record_event(repo, session_id, "assistant_stop", {"text": message}) + + def repo_for_session(self, session_id: str, cwd: str | None) -> RepoContext: + """Keep one project scope for every hook in a coding-agent session.""" + current = resolve_repo(cwd) + if session_id == "unknown-session": + return current + + with self.conn: + self.conn.execute( + """INSERT OR IGNORE INTO session_scopes + (session_id, repo_id, app_id, root, branch, head_sha, created_at, directory) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", + ( + session_id, + current.identity, + current.app_id, + current.root, + current.branch, + current.head_sha, + utc_now(), + current.directory, + ), + ) + scope = self.conn.execute( + "SELECT * FROM session_scopes WHERE session_id = ?", (session_id,) + ).fetchone() + same_git_repo = ( + current.identity == scope["repo_id"] and bool(current.head_sha) + ) + pinned = current if same_git_repo else resolve_repo(str(scope["root"])) + return RepoContext( + cwd=current.cwd, + root=pinned.root, + identity=str(scope["repo_id"]), + app_id=str(scope["app_id"]), + branch=pinned.branch, + head_sha=pinned.head_sha, + project_id=pinned.project_id, + directory=str(scope["directory"] or ""), + ) + + def prepare_flush( + self, repo: RepoContext, session_id: str, reason: str + ) -> tuple[str, list[dict[str, Any]]] | None: + with self.conn: + self.conn.execute("BEGIN IMMEDIATE") + existing = self.conn.execute( + """SELECT * FROM flushes + WHERE repo_id = ? AND session_id = ? + AND status NOT IN ('semantic-succeeded', 'explicitly-stored', 'gave-up') + ORDER BY created_at LIMIT 1""", + (repo.identity, session_id), + ).fetchone() + if existing and int(existing["attempts"] or 0) >= MAX_FLUSH_ATTEMPTS: + self.conn.execute( + "UPDATE flushes SET status = 'gave-up', updated_at = ? WHERE packet_id = ?", + (utc_now(), existing["packet_id"]), + ) + telemetry.record( + "flush", + repo=repo, + session_id=session_id, + reason=reason, + status="gave-up", + success=False, + attempts=int(existing["attempts"] or 0), + ) + existing = None + if existing: + if reason != "periodic" and existing["reason"] == "periodic": + self.conn.execute( + "UPDATE flushes SET reason = ?, updated_at = ? WHERE packet_id = ?", + (reason, utc_now(), existing["packet_id"]), + ) + existing_rows = self.conn.execute( + "SELECT * FROM events WHERE flush_id = ? ORDER BY id", + (existing["packet_id"],), + ).fetchall() + if existing_rows: + return str(existing["packet_id"]), [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in existing_rows + ] + + rows = self.conn.execute( + """SELECT * FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id""", + (repo.identity, session_id), + ).fetchall() + if not rows: + return None + + events = [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in rows + ] + events = select_checkpoint_events(events, force=reason != "periodic") + if not events: + return None + event_start, event_end = events[0]["id"], events[-1]["id"] + packet_material = f"{repo.identity}\0{session_id}\0{event_start}\0{event_end}" + packet_id = hashlib.sha256(packet_material.encode()).hexdigest()[:32] + now = utc_now() + + self.conn.execute( + """INSERT OR IGNORE INTO flushes + (packet_id, repo_id, app_id, session_id, reason, event_start, + event_end, status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, 'prepared', ?, ?)""", + ( + packet_id, + repo.identity, + repo.app_id, + session_id, + reason, + event_start, + event_end, + now, + now, + ), + ) + event_ids = [event["id"] for event in events] + placeholders = ", ".join("?" for _ in event_ids) + self.conn.execute( + f"UPDATE events SET flush_id = ? " + f"WHERE id IN ({placeholders}) AND flush_id IS NULL", + (packet_id, *event_ids), + ) + return packet_id, events + + def checkpoint_due(self, repo_id: str, session_id: str) -> bool: + if self.has_inflight_flush(repo_id, session_id): + return False + rows = self.conn.execute( + """SELECT * FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id""", + (repo_id, session_id), + ).fetchall() + events = [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in rows + ] + return bool(select_checkpoint_events(events, force=False)) + + def has_inflight_flush(self, repo_id: str, session_id: str) -> bool: + return ( + self.conn.execute( + """SELECT 1 FROM flushes + WHERE repo_id = ? AND session_id = ? + AND status IN ('prepared', 'semantic-queued') + LIMIT 1""", + (repo_id, session_id), + ).fetchone() + is not None + ) + + def flush_record(self, packet_id: str) -> dict[str, Any] | None: + row = self.conn.execute( + "SELECT * FROM flushes WHERE packet_id = ?", (packet_id,) + ).fetchone() + return dict(row) if row else None + + def has_unflushed_events(self, repo_id: str, session_id: str) -> bool: + return ( + self.conn.execute( + """SELECT 1 FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + LIMIT 1""", + (repo_id, session_id), + ).fetchone() + is not None + ) + + def unflushed_starts_with_session_start( + self, repo_id: str, session_id: str + ) -> bool: + row = self.conn.execute( + """SELECT kind FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id LIMIT 1""", + (repo_id, session_id), + ).fetchone() + return bool(row and row["kind"] == "session_start") + + def update_flush(self, packet_id: str, **fields: Any) -> None: + allowed = {"status", "episode_event_id", "semantic_event_id", "error"} + updates = {key: value for key, value in fields.items() if key in allowed} + updates["updated_at"] = utc_now() + clause = ", ".join(f"{key} = ?" for key in updates) + failed = str(fields.get("status", "")) in { + "error", + "semantic-failed", + "semantic-timeout", + "semantic-missing", + } + if failed: + clause += ", attempts = attempts + 1" + with self.conn: + self.conn.execute( + f"UPDATE flushes SET {clause} WHERE packet_id = ?", + [*updates.values(), packet_id], + ) + + def unseen( + self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]] + ) -> list[dict[str, Any]]: + seen = { + row["memory_id"] + for row in self.conn.execute( + "SELECT memory_id FROM retrievals WHERE session_id = ? AND repo_id = ?", + (session_id, repo_id), + ) + } + return [memory for memory in memories if str(memory.get("id", "")) not in seen] + + def mark_injected( + self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]] + ) -> None: + now = utc_now() + with self.conn: + for rank, memory in enumerate(memories, start=1): + memory_id = str(memory.get("id", "")) + if memory_id: + memory_text = bounded( + memory.get("memory") or memory.get("text") or "", + 4000, + ) + try: + score = float(memory["score"]) + except (KeyError, TypeError, ValueError): + score = None + self.conn.execute( + """INSERT OR IGNORE INTO retrievals + (session_id, repo_id, memory_id, injected_at, rank, + score, memory_text, context_chars) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", + ( + session_id, + repo_id, + memory_id, + now, + rank, + score, + memory_text, + len(memory_text), + ), + ) + + def injected_memories( + self, session_id: str, repo_id: str + ) -> list[dict[str, Any]]: + """Return the exact memories already supplied to the main conversation.""" + rows = self.conn.execute( + """SELECT memory_id, rank, score, memory_text + FROM retrievals + WHERE session_id = ? AND repo_id = ? + ORDER BY COALESCE(rank, 2147483647), injected_at, memory_id""", + (session_id, repo_id), + ).fetchall() + return [ + { + "id": row["memory_id"], + "memory": row["memory_text"], + "score": row["score"], + } + for row in rows + if row["memory_text"] + ] + + def start_sidekick( + self, + repo: RepoContext, + session_id: str, + agent_id: str, + agent_type: str, + context_chars: int, + ) -> bool: + """Record one native sidekick instance and whether context was first sent.""" + with self.conn: + cursor = self.conn.execute( + """INSERT OR IGNORE INTO sidekick_runs + (repo_id, session_id, agent_id, agent_type, started_at, + context_chars) + VALUES (?, ?, ?, ?, ?, ?)""", + ( + repo.identity, + session_id, + agent_id, + agent_type, + utc_now(), + context_chars, + ), + ) + return int(cursor.rowcount) > 0 + + def stop_sidekick( + self, + repo: RepoContext, + session_id: str, + agent_id: str, + agent_type: str, + transcript_path: str, + final_message: str, + ) -> str: + now = utc_now() + self.conn.execute("BEGIN IMMEDIATE") + try: + if not agent_id: + rows = self.conn.execute( + """SELECT agent_id FROM sidekick_runs + WHERE repo_id = ? AND session_id = ? AND agent_type = ? AND stopped_at IS NULL + LIMIT 2""", + (repo.identity, session_id, agent_type), + ).fetchall() + # Without a host ID, overlapping runs cannot be correlated reliably. + agent_id = rows[0]["agent_id"] if len(rows) == 1 else f"unknown-agent-{time.time_ns()}" + self.conn.execute( + """INSERT INTO sidekick_runs + (repo_id, session_id, agent_id, agent_type, started_at, + stopped_at, transcript_path, final_message) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(repo_id, session_id, agent_id) DO UPDATE SET + stopped_at = excluded.stopped_at, + transcript_path = excluded.transcript_path, + final_message = excluded.final_message""", + ( + repo.identity, + session_id, + agent_id, + agent_type, + now, + now, + bounded(transcript_path, 2000), + redact(final_message).strip(), + ), + ) + self.conn.commit() + except Exception: + self.conn.rollback() + raise + return agent_id + + def operation( + self, + repo: RepoContext, + session_id: str, + operation: str, + duration_ms: float, + success: bool, + *, + item_count: int = 0, + request_chars: int = 0, + response_chars: int = 0, + error: str = "", + ) -> None: + with self.conn: + self.conn.execute( + """INSERT INTO operations + (created_at, repo_id, session_id, operation, duration_ms, + success, item_count, request_chars, response_chars, error) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", + ( + utc_now(), + repo.identity, + session_id, + operation, + duration_ms, + int(success), + item_count, + request_chars, + response_chars, + bounded(error, 1000), + ), + ) + + def has_operation(self, repo_id: str, session_id: str, operation: str) -> bool: + row = self.conn.execute( + """SELECT 1 FROM operations + WHERE repo_id = ? AND session_id = ? AND operation = ? + LIMIT 1""", + (repo_id, session_id, operation), + ).fetchone() + return row is not None + + def has_event(self, repo_id: str, session_id: str, kind: str) -> bool: + row = self.conn.execute( + """SELECT 1 FROM events + WHERE repo_id = ? AND session_id = ? AND kind = ? + LIMIT 1""", + (repo_id, session_id, kind), + ).fetchone() + return row is not None + + def latest_event_payload( + self, repo_id: str, session_id: str, kind: str + ) -> dict[str, Any]: + row = self.conn.execute( + """SELECT payload_json FROM events + WHERE repo_id = ? AND session_id = ? AND kind = ? + ORDER BY id DESC LIMIT 1""", + (repo_id, session_id, kind), + ).fetchone() + if not row: + return {} + try: + payload = json.loads(row["payload_json"]) + except json.JSONDecodeError: + return {} + return payload if isinstance(payload, dict) else {} + + def setting(self, key: str, default: str = "") -> str: + row = self.conn.execute( + "SELECT value FROM settings WHERE key = ?", (key,) + ).fetchone() + return str(row["value"]) if row else default + + def set_setting(self, key: str, value: str) -> None: + with self.conn: + self.conn.execute( + """INSERT INTO settings(key, value, updated_at) + VALUES (?, ?, ?) + ON CONFLICT(key) DO UPDATE SET + value = excluded.value, + updated_at = excluded.updated_at""", + (key, value, utc_now()), + ) + + def is_paused(self) -> bool: + return self.setting("paused", "false").lower() in { + "1", + "true", + "yes", + "on", + } + + def forget_local_repo(self, repo_id: str) -> dict[str, int]: + tables = { + "events": "repo_id", + "session_scopes": "repo_id", + "flushes": "repo_id", + "retrievals": "repo_id", + "operations": "repo_id", + "sidekick_runs": "repo_id", + } + removed: dict[str, int] = {} + with self.conn: + for table, column in tables.items(): + cursor = self.conn.execute( + f"DELETE FROM {table} WHERE {column} = ?", (repo_id,) + ) + removed[table] = max(int(cursor.rowcount), 0) + return removed + + def status(self, repo_id: str) -> dict[str, Any]: + def count(table: str) -> int: + return int( + self.conn.execute( + f"SELECT COUNT(*) FROM {table} WHERE repo_id = ?", (repo_id,) + ).fetchone()[0] + ) + + last_operation = self.conn.execute( + """SELECT created_at, operation, duration_ms, success, item_count, error + FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""", + (repo_id,), + ).fetchone() + last_sidekick = self.conn.execute( + """SELECT session_id, agent_id, agent_type, started_at, stopped_at, + context_chars + FROM sidekick_runs WHERE repo_id = ? + ORDER BY started_at DESC LIMIT 1""", + (repo_id,), + ).fetchone() + return { + "paused": self.is_paused(), + "events": count("events"), + "flushes": count("flushes"), + "retrievals": count("retrievals"), + "sidekick_runs": count("sidekick_runs"), + "last_operation": dict(last_operation) if last_operation else None, + "last_sidekick": dict(last_sidekick) if last_sidekick else None, + } + + +def _session_id(hook_input: dict[str, Any]) -> str: + return str(hook_input.get("session_id") or "unknown-session") + + +def record_session_start(store: EvidenceStore, hook_input: dict[str, Any]) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + store.record_event( + repo, + session_id, + "session_start", + { + "source": hook_input.get("source", "startup"), + "model": bounded(hook_input.get("model", ""), 200), + "branch": repo.branch, + "head_sha": repo.head_sha, + }, + ) + telemetry.record( + "session_start", + repo=repo, + session_id=session_id, + trigger=bounded(str(hook_input.get("source", "startup")), 60), + model=bounded(hook_input.get("model", ""), 200), + api_key_configured=bool(api_key()), + is_git_repo=not repo.identity.startswith("local:"), + ) + + +def record_user_prompt( + store: EvidenceStore, hook_input: dict[str, Any] +) -> tuple[RepoContext, str, str, bool]: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + prompt = redact(hook_input.get("prompt", "")).strip() + is_first_prompt = not store.has_event(repo.identity, session_id, "user_prompt") + store.record_event(repo, session_id, "user_prompt", {"text": prompt}) + return repo, session_id, prompt, is_first_prompt + + +def _tool_result_preview(response: Any) -> str: + if isinstance(response, dict): + selected = {} + for key in ( + "stdout", + "stderr", + "output", + "content", + "error", + "filePath", + "success", + "interrupted", + ): + if key in response: + selected[key] = response[key] + response = selected or {"keys": sorted(response.keys())[:20]} + return bounded(response, MAX_RESULT_CHARS) + + +def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> dict[str, Any]: + name = str(hook_input.get("tool_name") or "unknown") + tool_input = hook_input.get("tool_input") or {} + if not isinstance(tool_input, dict): + tool_input = {} + payload: dict[str, Any] = { + "tool": name, + "failed": failed, + "duration_ms": hook_input.get("duration_ms"), + "agent_role": "sidekick" if hook_input.get("agent_id") else "main", + } + if hook_input.get("agent_id"): + payload["agent_id"] = bounded(hook_input["agent_id"], 200) + if hook_input.get("agent_type"): + payload["agent_type"] = bounded(hook_input["agent_type"], 200) + + if name in {"Read", "Write", "Edit", "MultiEdit", "NotebookEdit"}: + path = tool_input.get("file_path") or tool_input.get("notebook_path") + if path: + payload["path"] = bounded(path, 1000) + if name in {"Write", "Edit", "MultiEdit", "NotebookEdit"}: + payload["mutation_chars"] = sum( + len(str(tool_input.get(key, ""))) + for key in ("content", "new_string", "new_source", "edits") + ) + elif name == "Bash" or "command" in tool_input: + command = bounded(tool_input.get("command", ""), MAX_COMMAND_CHARS) + payload["command"] = command + payload["command_kind"] = ( + "test" + if TEST_COMMAND_RE.search(command) + else "build" + if BUILD_COMMAND_RE.search(command) + else "shell" + ) + response = ( + hook_input.get("error") if failed else hook_input.get("tool_response") + ) + payload["result_preview"] = _tool_result_preview(response) + elif name in {"Grep", "Glob", "WebSearch", "WebFetch"}: + for key in ("pattern", "path", "query", "url"): + if tool_input.get(key): + payload[key] = bounded(tool_input[key], 1000) + else: + payload["input_keys"] = sorted(tool_input.keys())[:20] + if failed: + payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS) + + if failed and "error" not in payload: + payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS) + return payload + + +def record_tool( + store: EvidenceStore, hook_input: dict[str, Any], *, failed: bool | None = False +) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + payload = tool_payload(hook_input, failed=failed) + if payload.get("path"): + payload["repo_path"] = _repo_relative_path(repo, str(payload["path"])) + store.record_event( + repo, + session_id, + "tool_failure" if failed else "tool_result", + payload, + ) + + +def record_sidekick_start( + store: EvidenceStore, hook_input: dict[str, Any], *, inject_context: bool = True +) -> str: + """Record a native sidekick and reuse the main turn's retrieved memories.""" + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200) + agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + context = combine_context( + format_context(store.injected_memories(session_id, repo.identity)) + ) + if not inject_context: + context = "" + first_start = store.start_sidekick( + repo, session_id, agent_id, agent_type, len(context) + ) + store.record_event( + repo, + session_id, + "sidekick_start", + { + "agent_id": agent_id, + "agent_type": agent_type, + "context_chars": len(context) if first_start else 0, + "worktree_root": bounded(repo.root, 2000), + }, + ) + telemetry.record( + "sidekick", + repo=repo, + session_id=session_id, + phase="start", + first_start=first_start, + context_chars=len(context) if first_start else 0, + ) + return context if first_start else "" + + +def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_id = bounded(hook_input.get("agent_id", ""), 200) + final_message = redact(hook_input.get("last_assistant_message", "")).strip() + transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000) + agent_id = store.stop_sidekick( + repo, + session_id, + agent_id, + agent_type, + transcript_path, + final_message, + ) + store.record_event( + repo, + session_id, + "sidekick_stop", + { + "agent_id": agent_id, + "agent_type": agent_type, + "transcript_path": transcript_path, + "final_message": final_message, + }, + ) + telemetry.record( + "sidekick", + repo=repo, + session_id=session_id, + phase="stop", + has_transcript=bool(transcript_path), + message_chars=len(final_message), + ) + + +def _ordered_unique(values: Iterable[str]) -> list[str]: + seen: set[str] = set() + result = [] + for value in values: + if value and value not in seen: + seen.add(value) + result.append(value) + return result + + +def _repo_relative_path(repo: RepoContext, value: str) -> str: + value = str(value or "").strip() + if not value: + return "" + try: + path = Path(value) + if path.is_absolute(): + try: + return path.resolve().relative_to(Path(repo.root).resolve()).as_posix() + except ValueError: + return "" + except (OSError, ValueError): + pass + return bounded(value, 1000) + + +def _render_command_lines(commands: list[dict[str, str]]) -> list[str]: + lines = [] + for command in commands: + line = f"- [{command['status']}/{command['kind']}] {command['command']}" + if command["result"]: + line += f" — {bounded(command['result'], 500).replace(chr(10), ' ')}" + lines.append(line) + return lines + + +def build_episode( + repo: RepoContext, + session_id: str, + packet_id: str, + events: list[dict[str, Any]], + *, + canonical_task: str = "", + task_outcome: str = "", +) -> tuple[str, dict[str, Any]]: + prompts = [ + redact(e["payload"].get("text", "")).strip() + for e in events + if e["kind"] == "user_prompt" and e["payload"].get("text") + ] + assistant_conclusions = [ + redact(e["payload"].get("text", "")).strip() + for e in events + if e["kind"] == "assistant_stop" and e["payload"].get("text") + ] + sidekick_outcomes = [ + redact(e["payload"].get("final_message", "")).strip() + for e in events + if e["kind"] == "sidekick_stop" and e["payload"].get("final_message") + ] + tools = [ + e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"} + and e["payload"].get("agent_role", "main") == "main" + ] + read_paths = _ordered_unique( + _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", ""))) + for t in tools + if t.get("tool") == "Read" + ) + modified_paths = _ordered_unique( + _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", ""))) + for t in tools + if t.get("tool") in {"Write", "Edit", "MultiEdit", "NotebookEdit"} + ) + searches = [ + {key: t[key] for key in ("tool", "pattern", "path", "query", "url") if key in t} + for t in tools + if t.get("tool") in {"Grep", "Glob", "WebSearch", "WebFetch"} + ] + commands = [ + { + "command": t.get("command", ""), + "kind": t.get("command_kind", "shell"), + "status": "unknown" if t.get("failed", False) is None else "failed" if t.get("failed") else "succeeded", + "result": t.get("result_preview", ""), + } + for t in tools + if t.get("command") + ] + + task = bounded(canonical_task or (prompts[0] if prompts else ""), 4000) + conclusion = redact(assistant_conclusions[-1] if assistant_conclusions else "").strip() + outcome = bounded(task_outcome, 2000) + + extraction_messages: list[dict[str, str]] = [] + pending_user_messages: list[dict[str, str]] = [] + if task and not prompts: + pending_user_messages.append({"role": "user", "content": task}) + for event in events: + if event["kind"] == "user_prompt" and event["payload"].get("text"): + pending_user_messages.append( + { + "role": "user", + "content": redact(event["payload"].get("text", "")).strip(), + } + ) + elif event["kind"] == "assistant_stop": + transcript_messages = event["payload"].get("transcript_messages") or [] + if isinstance(transcript_messages, list) and transcript_messages: + transcript_users = { + redact(message.get("content") or "").strip() + for message in transcript_messages + if isinstance(message, dict) and message.get("role") == "user" + } + extraction_messages.extend( + message + for message in pending_user_messages + if message["content"].strip() not in transcript_users + ) + extraction_messages.extend( + { + "role": str(message.get("role") or ""), + "content": redact(message.get("content") or "").strip(), + } + for message in transcript_messages + if isinstance(message, dict) + and message.get("role") in {"user", "assistant"} + and message.get("content") + ) + else: + extraction_messages.extend(pending_user_messages) + if event["payload"].get("text"): + extraction_messages.append( + { + "role": "assistant", + "content": redact(event["payload"].get("text", "")).strip(), + } + ) + pending_user_messages = [] + elif event["kind"] == "sidekick_stop": + pass + extraction_messages.extend(pending_user_messages) + + structured = { + "packet_id": packet_id, + "repo": repo.identity, + "app_id": repo.app_id, + "session_id": session_id, + "branch": repo.branch, + "head_sha": repo.head_sha, + "task": task, + "task_outcome": outcome, + "assistant_conclusion": conclusion, + "user_messages": prompts, + "assistant_outcomes": assistant_conclusions, + "sidekick_outcomes": sidekick_outcomes, + "extraction_messages": extraction_messages, + "files_read": read_paths[:50], + "files_modified": modified_paths[:50], + "searches": searches[-30:], + "commands": commands[-30:], + } + lines = ["Coding-session episode"] + if task: + lines.extend(["", "Task:", task]) + if modified_paths: + lines.extend( + ["", "Files modified:", *[f"- {path}" for path in modified_paths[:50]]] + ) + if read_paths: + lines.extend(["", "Files read:", *[f"- {path}" for path in read_paths[:50]]]) + if commands: + lines.append("") + lines.append("Observed commands:") + lines.extend(_render_command_lines(commands[-30:])) + if searches: + lines.extend( + [ + "", + "Observed searches:", + *[ + f"- {json.dumps(item, ensure_ascii=False, sort_keys=True)}" + for item in searches[-20:] + ], + ] + ) + if conclusion: + lines.extend(["", "Agent conclusion:", conclusion]) + if outcome: + lines.extend(["", "Task outcome:", outcome]) + lines.extend( + [ + "", + f"Provenance: repo={repo.identity}; branch={repo.branch}; head={repo.head_sha}; packet={packet_id}", + ] + ) + content = "\n".join(lines) + return bounded(content, MAX_EPISODE_CHARS), structured + + +def build_semantic_evidence(structured: dict[str, Any]) -> str: + """Format changed paths for memory extraction. + + Test and build results remain in the local evidence store for diagnostics, + but are not useful repository knowledge by default and should not steer + memory extraction toward transient verification details. + """ + modified_paths = [ + bounded(path, 500) for path in structured.get("files_modified", [])[:20] + ] + commands = structured.get("commands") or [] + if not any(command.get("status") == "failed" for command in commands): + commands = [] + + if not modified_paths and not commands: + return "" + + lines = ["Additional repository details from this session"] + if modified_paths: + lines.extend( + [ + "", + "Changed paths:", + *[f"- {path}" for path in modified_paths], + ] + ) + if commands: + lines.extend(["", "Commands run in this session:", *_render_command_lines(commands)]) + return bounded("\n".join(lines), 8000) + + +def build_extraction_messages(structured: dict[str, Any]) -> list[dict[str, str]]: + """Build the session messages sent to Mem0 for memory extraction.""" + evidence = build_semantic_evidence(structured) + messages = [ + {"role": message["role"], "content": redact(message["content"]).strip()} + for message in structured.get("extraction_messages", []) + if message.get("role") in {"user", "assistant"} and message.get("content") + ] + if evidence: + for message in reversed(messages): + if message["role"] == "assistant": + message["content"] = f"{message['content']}\n\n{evidence}" + break + else: + messages.append({"role": "assistant", "content": evidence}) + + return messages + + +def _estimated_tokens(value: str) -> int: + """Conservatively estimate tokens without adding a tokenizer dependency.""" + ascii_chars = sum(ord(char) < 128 for char in value) + return math.ceil((ascii_chars * 0.4) + (len(value) - ascii_chars)) + + +def _message_tokens(messages: list[dict[str, str]]) -> int: + return _estimated_tokens(json.dumps(messages, ensure_ascii=False)) + + +def _is_agent_assignment(message: dict[str, str]) -> bool: + return message.get("role") == "assistant" and message.get( + "content", "" + ).startswith("Subagent assignment (") + + +def _is_agent_response(message: dict[str, str]) -> bool: + return message.get("role") == "assistant" and message.get( + "content", "" + ).startswith("Subagent response (") + + +def extraction_message_batches( + messages: list[dict[str, str]], + *, + max_tokens: int = MAX_EXTRACTION_INPUT_TOKENS, +) -> list[list[dict[str, str]]]: + """Keep exchanges together when possible; split oversized messages to enforce the request budget.""" + if not messages or _message_tokens(messages) <= max_tokens: + return [messages] + + exchanges: list[list[dict[str, str]]] = [] + exchange: list[dict[str, str]] = [] + for message in messages: + if message.get("role") == "user" and exchange: + exchanges.append(exchange) + exchange = [] + exchange.append(message) + if exchange: + exchanges.append(exchange) + + units: list[list[dict[str, str]]] = [] + for exchange in exchanges: + if _message_tokens(exchange) <= max_tokens: + units.append(exchange) + continue + index = 0 + while index < len(exchange): + message = exchange[index] + if ( + _is_agent_assignment(message) + and index + 1 < len(exchange) + and _is_agent_response(exchange[index + 1]) + ): + units.append(exchange[index : index + 2]) + index += 2 + else: + units.append([message]) + index += 1 + + bounded_units: list[list[dict[str, str]]] = [] + for unit in units: + if _message_tokens(unit) <= max_tokens: + bounded_units.append(unit) + continue + for message in unit: + remaining = message["content"] + while remaining: + low, high = 0, len(remaining) + while low < high: + middle = (low + high + 1) // 2 + if _message_tokens([{**message, "content": remaining[:middle]}]) <= max_tokens: + low = middle + else: + high = middle - 1 + if low == 0: + raise ValueError("Extraction token budget cannot fit a message") + bounded_units.append([{**message, "content": remaining[:low]}]) + remaining = remaining[low:] + + batches: list[list[dict[str, str]]] = [] + batch: list[dict[str, str]] = [] + for unit in bounded_units: + candidate = [*batch, *unit] + if batch and _message_tokens(candidate) > max_tokens: + batches.append(batch) + batch = list(unit) + else: + batch = candidate + if batch: + batches.append(batch) + return batches + + +def _request_json( + url: str, key: str, payload: dict[str, Any], timeout: float +) -> tuple[dict[str, Any] | list[Any], int, int]: + raw = json.dumps(payload, ensure_ascii=False).encode() + request = urllib.request.Request( + url, + data=raw, + headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + response_raw = response.read() + parsed = json.loads(response_raw or b"{}") + return parsed, len(raw), len(response_raw) + + +def _request_json_with_network_retry( + url: str, key: str, payload: dict[str, Any], timeout: float +) -> tuple[dict[str, Any] | list[Any], int, int]: + """Retry one transient connection failure without retrying API responses.""" + try: + return _request_json(url, key, payload, timeout) + except urllib.error.HTTPError: + raise + except (urllib.error.URLError, TimeoutError, OSError): + time.sleep(0.25) + return _request_json(url, key, payload, timeout) + + +def _get_json( + url: str, key: str, timeout: float +) -> tuple[dict[str, Any] | list[Any], int]: + request = urllib.request.Request( + url, + headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + method="GET", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + response_raw = response.read() + return json.loads(response_raw or b"{}"), len(response_raw) + + +def _event_id(response: dict[str, Any] | list[Any]) -> str: + return str(response.get("event_id", "")) if isinstance(response, dict) else "" + + +def _stored_event_ids(value: Any) -> list[str]: + raw = str(value or "") + if not raw.startswith("["): + return [] + try: + parsed = json.loads(raw) + except json.JSONDecodeError: + return [] + return [str(item or "") for item in parsed] if isinstance(parsed, list) else [] + + +def _result_count(response: dict[str, Any] | list[Any]) -> int: + if isinstance(response, dict): + results = response.get("results") + return len(results) if isinstance(results, list) else 0 + return len(response) if isinstance(response, list) else 0 + + +def touch_handoff_heartbeat() -> None: + """Mark the worker's handoff file alive so recovery does not relaunch it.""" + path = os.environ.get("MEM0_CODE_HANDOFF_PATH", "") + if not path: + return + try: + os.utime(path) + except OSError: + pass + + +def _wait_for_event(api_url: str, key: str, event_id: str) -> tuple[str, int, int]: + """Wait for extraction to finish before a later task can search the store.""" + if not event_id: + return "MISSING", 0, 0 + wait_seconds = float(os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120")) + poll_seconds = max(float(os.environ.get("MEM0_CODE_EVENT_POLL_SECONDS", "1")), 0.1) + deadline = time.monotonic() + wait_seconds + response_chars = 0 + while time.monotonic() < deadline: + touch_handoff_heartbeat() + try: + response, size = _get_json( + f"{api_url}/v1/event/{event_id}/", + key, + min(10, poll_seconds + 5), + ) + except urllib.error.HTTPError as exc: + if exc.code not in {408, 429} and exc.code < 500: + raise + time.sleep(poll_seconds) + continue + except (urllib.error.URLError, TimeoutError, OSError): + # The extraction job is durable server-side. A transient polling + # failure must not discard a job that may still complete normally. + time.sleep(poll_seconds) + continue + response_chars += size + status = ( + str(response.get("status", "UNKNOWN")) + if isinstance(response, dict) + else "UNKNOWN" + ) + if status in {"SUCCEEDED", "FAILED"}: + return status, response_chars, _result_count(response) + time.sleep(poll_seconds) + return "TIMEOUT", response_chars, 0 + + +def _record_flush( + repo: RepoContext, + session_id: str, + reason: str, + status: str, + elapsed: float, + **extra: Any, +) -> None: + telemetry.record( + "flush", + repo=repo, + session_id=session_id, + reason=reason, + status=status, + success=status in {"semantic-succeeded", "nothing-to-flush"}, + duration_ms=round(elapsed, 2), + **extra, + ) + + +def flush_session( + store: EvidenceStore, hook_input: dict[str, Any], reason: str +) -> dict[str, Any]: + key = api_key() + if not key: + telemetry.record("flush", reason=reason, status="local-only", success=False) + return {"status": "local-only", "reason": "no-api-key"} + + session_id = _session_id(hook_input) + if session_id == "unknown-session": + telemetry.record("flush", reason=reason, status="no-session-id", success=False) + return {"status": "error", "reason": "no-session-id"} + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + prepared = store.prepare_flush(repo, session_id, reason) + if prepared is None: + return {"status": "nothing-to-flush"} + packet_id, events = prepared + existing_flush = store.flush_record(packet_id) or {} + + _, structured = build_episode( + repo, + session_id, + packet_id, + events, + canonical_task=bounded(hook_input.get("task", ""), 4000), + task_outcome=bounded(hook_input.get("task_outcome", ""), 2000), + ) + + metadata = {"source": _harness_source_tag} + if repo.branch and repo.branch not in {"detached", "unknown"}: + metadata["branch"] = repo.branch + if repo.head_sha: + metadata["git_sha"] = repo.head_sha + api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + add_url = f"{api_url}/v3/memories/add/" + + write_user = _scope_value(user_id()) + write_project = _scope_value(repo.project_id) + if not write_user or not _scope_value(repo.app_id) or not write_project: + telemetry.record("flush", reason=reason, status="unscoped", success=False) + return {"status": "error", "reason": "wildcard-scope"} + + body = { + "agent_id": write_project, + "user_id": write_user, + "app_id": repo.app_id, + "run_id": session_id, + "metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)}, + "agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS, + "custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS, + "custom_categories": CODING_MEMORY_CATEGORIES, + "infer": True, + } + + started = time.perf_counter() + try: + stored_events = _stored_event_ids(existing_flush.get("semantic_event_id")) + existing_event = ( + "" if stored_events else str(existing_flush.get("semantic_event_id") or "") + ) + if existing_event: + existing_status, existing_resp, existing_items = _wait_for_event( + api_url, key, existing_event + ) + if existing_status == "SUCCEEDED": + elapsed = (time.perf_counter() - started) * 1000 + store.update_flush( + packet_id, + status="semantic-succeeded", + semantic_event_id=existing_event, + error="", + ) + store.operation( + repo, + session_id, + "flush-retry", + elapsed, + True, + item_count=existing_items, + response_chars=existing_resp, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-succeeded", + elapsed, + memory_count=existing_items, + resumed=True, + ) + effective_reason = str( + (store.flush_record(packet_id) or {}).get("reason") or reason + ) + if ( + store.has_unflushed_events(repo.identity, session_id) + and not store.unflushed_starts_with_session_start( + repo.identity, session_id + ) + and ( + effective_reason != "periodic" + or store.checkpoint_due(repo.identity, session_id) + ) + ): + return flush_session(store, hook_input, effective_reason) + return { + "status": "semantic-succeeded", + "packet_id": packet_id, + "semantic_event_id": existing_event, + "semantic_status": existing_status, + "memory_count": existing_items, + "duration_ms": round(elapsed, 2), + "resumed": True, + } + if existing_status == "TIMEOUT": + elapsed = (time.perf_counter() - started) * 1000 + error = "semantic extraction event timed out" + store.update_flush(packet_id, status="semantic-timeout", error=error) + store.operation( + repo, + session_id, + "flush-retry", + elapsed, + False, + response_chars=existing_resp, + error=error, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-timeout", + elapsed, + resumed=True, + error_kind="timeout", + ) + return { + "status": "semantic-timeout", + "packet_id": packet_id, + "semantic_event_id": existing_event, + "duration_ms": round(elapsed, 2), + "resumed": True, + } + + message_batches = [ + batch + for batch in extraction_message_batches( + build_extraction_messages(structured) + ) + if batch + ] + batches = [(body, messages) for messages in message_batches] + if not batches: + store.update_flush(packet_id, status="semantic-succeeded", error="") + return {"status": "nothing-to-flush", "packet_id": packet_id} + operation_name = "flush-retry" if stored_events else "flush" + semantic_events = stored_events[: len(batches)] + semantic_events += [""] * (len(batches) - len(semantic_events)) + semantic_req = 0 + semantic_resp = 0 + for index, (body, messages) in enumerate(batches): + if semantic_events[index]: + continue + semantic_response, request_chars, response_chars = _request_json( + add_url, + key, + {**body, "messages": messages}, + 15, + ) + semantic_events[index] = _event_id(semantic_response) + semantic_req += request_chars + semantic_resp += response_chars + store.update_flush( + packet_id, + status="semantic-queued", + semantic_event_id=json.dumps(semantic_events), + ) + + semantic_event = semantic_events[-1] + semantic_status = "SUCCEEDED" + event_resp = 0 + semantic_items = 0 + failed_event = semantic_event + for index, queued_event in enumerate(semantic_events): + status, response_chars, item_count = _wait_for_event( + api_url, key, queued_event + ) + event_resp += response_chars + semantic_items += item_count + if status != "SUCCEEDED": + semantic_status = status + failed_event = queued_event + if status in {"FAILED", "MISSING"}: + semantic_events[index] = "" + store.update_flush( + packet_id, semantic_event_id=json.dumps(semantic_events) + ) + break + if semantic_status != "SUCCEEDED": + elapsed = (time.perf_counter() - started) * 1000 + error = f"semantic extraction event {semantic_status.lower()}" + store.update_flush( + packet_id, status=f"semantic-{semantic_status.lower()}", error=error + ) + store.operation( + repo, + session_id, + operation_name, + elapsed, + False, + item_count=semantic_items, + request_chars=semantic_req, + response_chars=semantic_resp + event_resp, + error=error, + ) + _record_flush( + repo, + session_id, + reason, + f"semantic-{semantic_status.lower()}", + elapsed, + memory_count=semantic_items, + batch_count=len(batches), + error_kind=telemetry.error_kind(error), + ) + return { + "status": f"semantic-{semantic_status.lower()}", + "packet_id": packet_id, + "semantic_event_id": failed_event, + "memory_count": semantic_items, + "duration_ms": round(elapsed, 2), + } + + elapsed = (time.perf_counter() - started) * 1000 + store.update_flush( + packet_id, + status="semantic-succeeded", + semantic_event_id=json.dumps(semantic_events), + error="", + ) + store.operation( + repo, + session_id, + operation_name, + elapsed, + True, + item_count=semantic_items, + request_chars=semantic_req, + response_chars=semantic_resp + event_resp, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-succeeded", + elapsed, + memory_count=semantic_items, + batch_count=len(batches), + request_chars=semantic_req, + ) + effective_reason = str( + (store.flush_record(packet_id) or {}).get("reason") or reason + ) + if ( + store.has_unflushed_events(repo.identity, session_id) + and not store.unflushed_starts_with_session_start( + repo.identity, session_id + ) + and ( + effective_reason != "periodic" + or store.checkpoint_due(repo.identity, session_id) + ) + ): + return flush_session(store, hook_input, effective_reason) + return { + "status": "semantic-succeeded", + "packet_id": packet_id, + "semantic_event_id": semantic_event, + "semantic_status": semantic_status, + "memory_count": semantic_items, + "duration_ms": round(elapsed, 2), + } + except Exception as exc: # hooks must fail open + elapsed = (time.perf_counter() - started) * 1000 + error = bounded(str(exc), 1000) + store.update_flush(packet_id, status="error", error=error) + store.operation(repo, session_id, "flush", elapsed, False, error=error) + _record_flush( + repo, + session_id, + reason, + "error", + elapsed, + error_kind=telemetry.error_kind(exc), + ) + return {"status": "error", "packet_id": packet_id, "error": error} + + +def checkpoint_session( + store: EvidenceStore, hook_input: dict[str, Any], reason: str +) -> dict[str, Any]: + """Run remote extraction at a durable boundary.""" + return flush_session(store, hook_input, reason) + + + +def search_memories( + store: EvidenceStore | None, + repo: RepoContext, + session_id: str | None, + query: str, + *, + top_k: int | None = None, + category: str | None = None, + scope: str | None = None, + run_id: str | None = None, + operation: str = "search", + timeout: float = 5, +) -> MemorySearchResult: + key = api_key() + if not key or not query.strip(): + return MemorySearchResult(False, 0, 0, []) + search_once = os.environ.get( + "MEM0_CODE_SEARCH_ONCE_PER_SESSION", "false" + ).lower() in { + "1", + "true", + "yes", + "on", + } + track_session = store is not None and bool(session_id) + if ( + search_once + and track_session + and store.has_operation(repo.identity, session_id, "search") + ): + return MemorySearchResult(False, 0, 0, []) + + result_limit = min( + max( + top_k + if top_k is not None + else _int_option("top_k", "MEM0_CODE_TOP_K", 3), + 1, + ), + 20, + ) + if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES: + raise ValueError(f"Unknown memory category: {category}") + user, project = _scope_value(user_id()), _scope_value(repo.project_id) + if not user or not project or not _scope_value(repo.app_id): + return MemorySearchResult(False, 0, 0, []) + filters = _search_filters(user, repo, resolve_search_scope(scope)) + if category: + filters = {"AND": [filters, {"categories": {"contains": category}}]} + if run_id: + filters = {"AND": [filters, {"run_id": run_id}]} + payload = { + "query": query, + "app_id": repo.app_id, + "filters": filters, + "top_k": result_limit, + "rerank": False, + "latest_only": True, + } + url = ( + os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + + "/v3/memories/search/" + ) + started = time.perf_counter() + try: + response, request_chars, response_chars = _request_json_with_network_retry( + url, key, payload, timeout + ) + memories = ( + response if isinstance(response, list) else response.get("results", []) + ) + memories = [ + memory + for memory in memories + if isinstance(memory, dict) + and (memory.get("metadata") or {}).get("record_kind") != "task_episode" + ][:result_limit] + if track_session: + returned_memories = store.unseen(session_id, repo.identity, memories) + store.mark_injected(session_id, repo.identity, returned_memories) + already_shown_count = len(memories) - len(returned_memories) + else: + returned_memories = memories + already_shown_count = 0 + elapsed = (time.perf_counter() - started) * 1000 + if track_session: + store.operation( + repo, + session_id, + operation, + elapsed, + True, + item_count=len(returned_memories), + request_chars=request_chars, + response_chars=response_chars, + ) + telemetry.record( + "search", + repo=repo, + session_id=session_id, + trigger=operation, + success=True, + duration_ms=round(elapsed, 2), + matched_count=len(memories), + returned_count=len(returned_memories), + already_shown_count=already_shown_count, + top_k=result_limit, + has_category=bool(category), + ) + return MemorySearchResult( + succeeded=True, + matched_count=len(memories), + already_shown_count=already_shown_count, + memories=returned_memories, + ) + except Exception as exc: + elapsed = (time.perf_counter() - started) * 1000 + if track_session: + store.operation(repo, session_id, operation, elapsed, False, error=str(exc)) + telemetry.record( + "search", + repo=repo, + session_id=session_id, + trigger=operation, + success=False, + duration_ms=round(elapsed, 2), + top_k=result_limit, + has_category=bool(category), + error_kind=telemetry.error_kind(exc), + ) + return MemorySearchResult(False, 0, 0, []) + + +def format_context( + memories: list[dict[str, Any]], + heading: str = "Relevant repository memories:", +) -> str: + if not memories: + return "" + limit = min( + max( + _int_option( + "max_context_chars", + "MEM0_CODE_MAX_CONTEXT_CHARS", + DEFAULT_MAX_CONTEXT_CHARS, + ), + 1000, + ), + 10000, + ) + lines = [heading] if heading else [] + for memory in memories: + text = re.sub( + r"\s+", + " ", + redact(memory.get("memory") or memory.get("text") or ""), + ) + text = text.strip() + if not text: + continue + branch = str((memory.get("metadata") or {}).get("branch") or "").strip() + branch_label = ( + f" [learnt on branch {branch}]" + if branch.casefold() not in {"", "main", "master", "unknown", "detached"} + else "" + ) + number = len(lines) if heading else len(lines) + 1 + entry = f"{number}. {text}{branch_label}" + candidate = "\n".join([*lines, entry]) + if len(candidate) <= limit: + lines.append(entry) + continue + if not lines or (heading and len(lines) == 1): + prefix = f"{number}. " + suffix = f"…{branch_label}" + available = ( + limit + - len("\n".join(lines)) + - (1 if lines else 0) + - len(prefix) + - len(suffix) + ) + if available > 0: + lines.append(prefix + text[:available].rstrip() + suffix) + break + minimum_lines = 2 if heading else 1 + return "\n".join(lines) if len(lines) >= minimum_lines else "" + + +def format_search_result(result: MemorySearchResult) -> str: + """Return only the text the coding agent needs from an explicit memory search.""" + if not result.succeeded: + return "Memory search failed." + if result.memories: + rendered = format_context(result.memories, heading="") + if rendered: + return rendered + return "No matching memories found." + + +def combine_context(*contexts: str) -> str: + """Combine memory sources under one hard budget without repeated lines.""" + seen: set[str] = set() + lines: list[str] = [] + for context in contexts: + for line in str(context or "").splitlines(): + normalized = re.sub(r"\s+", " ", line).strip().casefold() + if not normalized or normalized in seen: + continue + seen.add(normalized) + lines.append(line.rstrip()) + limit = min( + max( + _int_option( + "max_context_chars", + "MEM0_CODE_MAX_CONTEXT_CHARS", + DEFAULT_MAX_CONTEXT_CHARS, + ), + 1000, + ), + 10000, + ) + return bounded("\n".join(lines), limit) if lines else "" + + +def _scoped_memory_ids( + api_url: str, key: str, user: str, repo: RepoContext, include_project: bool +) -> list[str]: + """List this user's memory ids for this repository, plus the shared project memory when asked.""" + ids: list[str] = [] + seen: set[str] = set() + prefix = repo.app_id + _collect_memory_ids( + api_url, key, {"user_id": user}, ids, seen, + app_id_prefix=prefix, + ) + if include_project: + for project_id in _shared_project_ids(repo): + _collect_memory_ids( + api_url, key, {"agent_id": project_id}, ids, seen, + app_id_prefix=prefix, + ) + return ids + + +def _collect_memory_ids( + api_url: str, + key: str, + filters: dict[str, Any], + ids: list[str], + seen: set[str], + *, + app_id_prefix: str = "", +) -> None: + """Page through one list filter; the list endpoint returns nothing for an OR whose user branch has no memories.""" + payload = {"filters": filters} + for page in range(1, FORGET_MAX_PAGES + 1): + parsed, _, _ = _request_json( + f"{api_url}/v2/memories/?page={page}&page_size={FORGET_PAGE_SIZE}", + key, + payload, + 15, + ) + items = parsed.get("results") if isinstance(parsed, dict) else parsed + if not isinstance(items, list) or not items: + break + for item in items: + if not isinstance(item, dict): + continue + memory_id = str(item.get("id", "")) + if not memory_id or memory_id in seen: + continue + if app_id_prefix: + item_app_id = str(item.get("app_id") or "") + if item_app_id != app_id_prefix and not item_app_id.startswith(app_id_prefix + "/"): + continue + seen.add(memory_id) + ids.append(memory_id) + if len(items) < FORGET_PAGE_SIZE: + break + + +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"}, + method="DELETE", + ) + try: + with urllib.request.urlopen(request, timeout=15): + return True + except Exception: + return False + + +def forget_remote_repo( + repo: RepoContext, *, include_project_memory: bool = False +) -> dict[str, Any]: + """Delete this user's memories for this repository; project memory is shared, so only on request.""" + key = api_key() + if not key: + telemetry.record("forget", repo=repo, success=False, error_kind="no-api-key") + return {"status": "error", "error": "Mem0 API key is not configured"} + user = _scope_value(user_id()) + if not user or not _scope_value(repo.app_id) or not _scope_value(repo.project_id): + telemetry.record("forget", repo=repo, success=False, error_kind="unscoped") + return { + "status": "error", + "error": "Refusing to forget: the user or repository scope is a wildcard", + } + api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + try: + memory_ids = _scoped_memory_ids(api_url, key, user, repo, include_project_memory) + except Exception as exc: + telemetry.record( + "forget", repo=repo, success=False, error_kind=telemetry.error_kind(exc) + ) + return {"status": "error", "error": bounded(str(exc), 1000)} + deleted = sum(_delete_memory(api_url, key, memory_id) for memory_id in memory_ids) + failed = len(memory_ids) - deleted + telemetry.record("forget", repo=repo, success=not failed, item_count=deleted) + if failed: + return { + "status": "partial", + "deleted": deleted, + "failed": failed, + "error": f"{failed} of {len(memory_ids)} memories could not be deleted", + } + return {"status": "deleted", "deleted": deleted} + + +def _doctor_mem0_authentication(repo: RepoContext) -> dict[str, Any]: + """Verify the configured key with one read-only, repository-scoped search.""" + key = api_key() + if not key: + return {"ok": False, "detail": "API key missing"} + payload = { + "query": "Mem0 authentication check", + "filters": { + "AND": [ + {"user_id": user_id()}, + {"app_id": repo.app_id}, + ] + }, + "top_k": 1, + "threshold": 1.0, + "rerank": False, + } + url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + started = time.perf_counter() + try: + _request_json(f"{url}/v3/memories/search/", key, payload, 5) + except Exception as exc: + return {"ok": False, "detail": bounded(str(exc), 300)} + elapsed = (time.perf_counter() - started) * 1000 + return {"ok": True, "detail": f"connected ({elapsed:.0f} ms)"} + + +def _doctor_user_id() -> dict[str, Any]: + """Flag a configured user ID the plugin refuses, since the silent fallback surprises people.""" + configured = _plugin_option("user_id", "MEM0_CODE_USER_ID") or os.environ.get( + "MEM0_USER_ID", "" + ) + if configured and not _scope_value(configured): + return { + "ok": False, + "detail": f"configured user_id {configured!r} is a wildcard; using {user_id()!r}", + } + return {"ok": True, "detail": user_id()} + + +def doctor(cwd: str | None = None) -> dict[str, Any]: + repo = resolve_repo(cwd) + directory = data_dir() + directory.mkdir(parents=True, exist_ok=True) + checks: dict[str, dict[str, Any]] = { + "python": { + "ok": tuple(sys.version_info[:2]) >= (3, 10), + "detail": f"{sys.version_info.major}.{sys.version_info.minor}", + }, + "data_directory": { + "ok": os.access(directory, os.W_OK), + "detail": str(directory), + }, + "mem0_api_key": { + "ok": bool(api_key()), + "detail": "configured" if api_key() else "missing", + }, + "repository": { + "ok": bool(repo.identity), + "detail": repo.identity, + }, + "user_id": _doctor_user_id(), + "mem0_authentication": _doctor_mem0_authentication(repo), + } + return { + "ok": all(bool(value["ok"]) for value in checks.values()), + "plugin_version": PLUGIN_VERSION, + "repo_id": repo.identity, + "app_id": repo.app_id, + "user_id": user_id(), + "checks": checks, + } diff --git a/integrations/cursor-plugin/core/telemetry.py b/integrations/cursor-plugin/core/telemetry.py new file mode 100644 index 000000000..249595475 --- /dev/null +++ b/integrations/cursor-plugin/core/telemetry.py @@ -0,0 +1,397 @@ +#!/usr/bin/env python3 +"""Anonymous usage telemetry for Mem0 agent plugins. + +Hooks run on a 3-6 second budget and fire on every tool call, so recording never +touches the network: `record` appends one JSON line to a local spool and returns. +A detached `python3 telemetry.py` drains the spool in one batched PostHog request, +started once per session and again from the flush worker that is already detached. + +Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false. + +Never sends prompts, memory text, queries, file paths, repository names, or API +keys: only event names, durations, counts, coarse outcomes, and salted hashes. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import platform +import subprocess +import sys +import time +import urllib.error +import urllib.request +import uuid +from pathlib import Path +from typing import Any + +import memory_core + +_harness: str = "generic" +_source_tag: str = "MEM0_PLUGIN" +_PRIVATE_KEYS = { + "apikey", + "authorization", + "password", + "query", + "secret", + "prompt", + "token", + "text", + "memory", + "message", + "error", + "path", + "cwd", + "userid", + "agentid", + "runid", + "repoid", + "repositoryid", + "projectid", + "appid", + "filters", +} + + +def init(harness: str = "generic", source_tag: str = "") -> None: + global _harness, _source_tag + _harness = harness + _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN" + +POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" +POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/" +POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/" +EVENT_PREFIX = "code" +SPOOL_LIMIT_BYTES = 256 * 1024 +BATCH_SIZE = 100 +SEND_TIMEOUT = 5 +CLAIM_STALE_SECONDS = 120 +CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60 + + +def is_enabled() -> bool: + """Whether telemetry is switched on for this process.""" + return os.environ.get("MEM0_TELEMETRY", "true").strip().lower() not in { + "false", + "0", + "no", + "off", + } + + +def _digest(value: str, length: int = 16) -> str: + return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length] + + +def _safe_value(value: Any) -> Any: + if isinstance(value, str): + return memory_core.redact(value) + if isinstance(value, dict): + return { + key: _safe_value(item) + for key, item in value.items() + if "".join(character for character in str(key).lower() if character.isalnum()) + not in _PRIVATE_KEYS + } + if isinstance(value, (list, tuple)): + return [_safe_value(item) for item in value] + if value is None or isinstance(value, (bool, int, float)): + return value + return memory_core.redact(value) + + +def _spool_path() -> Path: + return memory_core.data_dir() / "telemetry.jsonl" + + +def _identity_path() -> Path: + return memory_core.data_dir() / "telemetry-identity.json" + + +def _read_identity() -> dict[str, str]: + try: + value = json.loads(_identity_path().read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {} + return value if isinstance(value, dict) else {} + + +def _write_identity(identity: dict[str, str]) -> None: + path = _identity_path() + temporary = path.with_suffix(f".{os.getpid()}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + temporary.write_text(json.dumps(identity), encoding="utf-8") + temporary.replace(path) + except OSError: + try: + temporary.unlink() + except OSError: + pass + + +def anonymous_id(identity: dict[str, str] | None = None) -> str: + """Per-machine anonymous identifier, created and persisted on first use.""" + identity = _read_identity() if identity is None else identity + existing = identity.get("anonymous_id") + if existing: + return existing + created = f"code-anon-{uuid.uuid4().hex}" + identity["anonymous_id"] = created + _write_identity(identity) + return created + + +def is_first_run() -> bool: + """Whether this machine has never recorded a plugin event before.""" + return not _identity_path().exists() + + +def record( + event: str, + *, + repo: Any = None, + session_id: str | None = None, + **properties: Any, +) -> None: + """Append one event to the local spool. Never blocks and never raises.""" + if not is_enabled(): + return + try: + spool = _spool_path() + try: + if spool.stat().st_size > SPOOL_LIMIT_BYTES: + return + except OSError: + pass + properties = _safe_value(properties) + properties.update( + harness=_harness, + plugin_version=memory_core.PLUGIN_VERSION, + os=sys.platform, + python_version=platform.python_version(), + ) + if repo is not None: + properties["repo_hash"] = _digest(getattr(repo, "identity", "")) + if session_id: + properties["session_hash"] = _digest(session_id) + line = json.dumps( + { + "event": f"{EVENT_PREFIX}.{event}", + "timestamp": memory_core.utc_now(), + "properties": { + key: value for key, value in properties.items() if value is not None + }, + }, + separators=(",", ":"), + default=str, + ) + spool.parent.mkdir(parents=True, exist_ok=True) + with spool.open("a", encoding="utf-8") as handle: + handle.write(line + "\n") + except Exception: + pass + + +def error_kind(exc: BaseException | str) -> str: + """Coarse, content-free label for a failure, safe to send.""" + text = exc if isinstance(exc, str) else f"{type(exc).__name__}: {exc}" + lowered = text.lower() + if "timed out" in lowered or "timeout" in lowered: + return "timeout" + if "401" in lowered or "403" in lowered or "unauthor" in lowered or "forbidden" in lowered: + return "auth" + if "429" in lowered or "rate limit" in lowered: + return "rate-limited" + if any(code in lowered for code in ("500", "502", "503", "504")): + return "server-error" + if "400" in lowered or "422" in lowered: + return "bad-request" + if isinstance(exc, str): + return "other" + if isinstance(exc, urllib.error.URLError): + return "network" + return type(exc).__name__ + + +def spawn_flush() -> bool: + """Start the detached sender that drains the spool.""" + if not is_enabled(): + return False + try: + if not _spool_path().exists() and not any( + memory_core.data_dir().glob("telemetry-*.sending") + ): + return False + subprocess.Popen( + [sys.executable, str(Path(__file__).resolve())], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + close_fds=True, + **memory_core.detached_process_kwargs(), + ) + return True + except Exception: + return False + + +def _claim_spool() -> Path | None: + """Rename the spool aside so exactly one sender owns each batch.""" + directory = memory_core.data_dir() + claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending" + spool = _spool_path() + try: + spool.replace(claim) + return claim + except OSError: + pass + now = time.time() + for orphan in sorted(directory.glob("telemetry-*.sending")): + try: + age = now - orphan.stat().st_mtime + except OSError: + continue + if age > CLAIM_EXPIRY_SECONDS: + try: + orphan.unlink() + except OSError: + pass + continue + if age < CLAIM_STALE_SECONDS: + continue + try: + orphan.replace(claim) + return claim + except OSError: + continue + return None + + +def _resolve_email(key: str) -> str: + """Trade the API key for the account email so events join other Mem0 surfaces.""" + url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/" + request = urllib.request.Request( + url, headers={"Authorization": f"Token {key}", "Content-Type": "application/json"} + ) + try: + with urllib.request.urlopen(request, timeout=SEND_TIMEOUT) as response: + payload = json.loads(response.read().decode("utf-8")) + except Exception: + return "" + email = payload.get("user_email") if isinstance(payload, dict) else "" + return email if isinstance(email, str) else "" + + +def _post(payload: dict[str, Any], url: str) -> bool: + request = urllib.request.Request( + url, + data=json.dumps(payload, default=str).encode("utf-8"), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=SEND_TIMEOUT): + return True + except Exception: + return False + + +def resolve_distinct_id() -> tuple[str, str]: + """Return the PostHog distinct id and the anonymous id it replaced, if any.""" + identity = _read_identity() + email = identity.get("email", "") + if email: + return email, "" + key = memory_core.api_key() + if not key: + return anonymous_id(identity), "" + email = _resolve_email(key) + if not email: + return anonymous_id(identity), "" + previous = identity.get("anonymous_id", "") + identity["email"] = email + _write_identity(identity) + return email, previous + + +def flush() -> int: + """Drain claimed spools to PostHog and return the number of events sent.""" + if not is_enabled(): + return 0 + claim = _claim_spool() + if claim is None: + return 0 + try: + lines = claim.read_text(encoding="utf-8").splitlines() + except OSError: + return 0 + events = [] + for line in lines: + try: + value = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(value, dict) and value.get("event"): + events.append(value) + if not events: + try: + claim.unlink() + except OSError: + pass + return 0 + + distinct_id, aliased_anonymous_id = resolve_distinct_id() + if aliased_anonymous_id: + _post( + { + "api_key": POSTHOG_API_KEY, + "event": "$identify", + "distinct_id": distinct_id, + "properties": { + "$anon_distinct_id": aliased_anonymous_id, + "$lib": "posthog-python", + }, + }, + POSTHOG_CAPTURE_URL, + ) + + sent = 0 + for start in range(0, len(events), BATCH_SIZE): + batch = [ + { + "event": event["event"], + "distinct_id": distinct_id, + "timestamp": event.get("timestamp"), + "properties": { + "source": _source_tag, + "language": "python", + "$process_person_profile": False, + "$lib": "posthog-python", + **(event.get("properties") or {}), + }, + } + for event in events[start : start + BATCH_SIZE] + ] + if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL): + return sent + sent += len(batch) + try: + claim.unlink() + except OSError: + pass + return sent + + +def main() -> int: + flush() + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except Exception: + raise SystemExit(0) diff --git a/integrations/cursor-plugin/hooks/adapter.py b/integrations/cursor-plugin/hooks/adapter.py new file mode 100644 index 000000000..d167f9a28 --- /dev/null +++ b/integrations/cursor-plugin/hooks/adapter.py @@ -0,0 +1,132 @@ +#!/usr/bin/env python3 +"""Translate Cursor's native hooks into the shared Mem0 runtime.""" + +from __future__ import annotations + +import contextlib +import io +import json +import os +import sys +from pathlib import Path + +HERE = Path(__file__).resolve() +BUNDLED_CORE = HERE.parent.parent / "core" +CORE = BUNDLED_CORE if BUNDLED_CORE.is_dir() else HERE.parents[2] / "core" / "python" +sys.path.insert(0, str(CORE)) + +import hook_runner # noqa: E402 +import telemetry # noqa: E402 +from memory_core import ( # noqa: E402 + configure_harness, + record_sidekick_start, + record_sidekick_stop, + record_tool, +) + +EVENTS = { + "sessionStart": "session-start", + "beforeSubmitPrompt": "user-prompt", + "postToolUse": "post-tool", + "postToolUseFailure": "post-tool-failure", + "afterAgentResponse": "assistant-stop", + "subagentStart": "sidekick-start", + "subagentStop": "sidekick-stop", + "stop": "stop", + "sessionEnd": "session-end", + "preCompact": "pre-compact", +} + + +def normalize(payload: dict, event: str) -> dict: + value = dict(payload) + value.setdefault("session_id", value.get("conversation_id") or value.get("parent_conversation_id", "")) + roots = value.get("workspace_roots") or [] + if roots: + value.setdefault("cwd", roots[0]) + if "tool_output" in value: + value.setdefault("tool_response", value["tool_output"]) + if "error_message" in value: + value.setdefault("tool_response", value["error_message"]) + if "text" in value: + value.setdefault("last_assistant_message", value["text"]) + if "summary" in value: + value.setdefault("last_assistant_message", value["summary"]) + if "subagent_id" in value: + value.setdefault("agent_id", value["subagent_id"]) + if "subagent_type" in value: + value.setdefault("agent_type", value["subagent_type"]) + return {"action": EVENTS[event], "payload": value} + + +def _record_failure(store, payload): + return record_tool(store, payload, failed=True) + + +def _record_response(store, payload): + hook_runner.default_record_stop(store, payload) + + +def _record_sidekick_start(store, payload): + record_sidekick_start(store, payload, inject_context=False) + return {"permission": "allow"} + + +def _record_sidekick_stop(store, payload): + record_sidekick_stop(store, payload) + + +def main() -> int: + if len(sys.argv) != 2 or sys.argv[1] not in EVENTS: + return 2 + event = sys.argv[1] + try: + raw = json.load(sys.stdin) + except (json.JSONDecodeError, OSError): + raw = {} + normalized = normalize(raw if isinstance(raw, dict) else {}, event) + action = normalized["action"] + arguments = { + "session-end": ["flush", "--reason", "session-end"], + "pre-compact": ["flush", "--reason", "pre-compact"], + }.get(action, [action]) + sys.argv = [sys.argv[0], *arguments] + sys.stdin = io.StringIO(json.dumps(normalized["payload"])) + + configure_harness("cursor", data_dir_name="cursor-plugin", source_tag="cursor_plugin") + telemetry.init(harness="cursor", source_tag="CURSOR_PLUGIN") + with contextlib.redirect_stdout(io.StringIO()): + result = hook_runner.run( + extra_actions={ + "post-tool-failure": _record_failure, + "assistant-stop": _record_response, + "sidekick-start": _record_sidekick_start, + "sidekick-stop": _record_sidekick_stop, + }, + automatic_flush_reasons={"session-end", "pre-compact"}, + ) + if event == "sessionStart": + environment = { + key: value + for key in ( + "PLUGIN_OPTION_API_KEY", + "PLUGIN_OPTION_USER_ID", + "PLUGIN_OPTION_TOP_K", + "PLUGIN_OPTION_MAX_CONTEXT_CHARS", + "PLUGIN_OPTION_SEARCH_SCOPE", + ) + if (value := os.environ.get(key)) + } + if environment: + print(json.dumps({"env": environment})) + elif event == "subagentStart": + print(json.dumps({"permission": "allow"})) + return result + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except Exception as exc: + hook_runner.log_failure(exc) + raise SystemExit(0) from None diff --git a/integrations/cursor-plugin/hooks/hooks.json b/integrations/cursor-plugin/hooks/hooks.json new file mode 100644 index 000000000..1e4875d50 --- /dev/null +++ b/integrations/cursor-plugin/hooks/hooks.json @@ -0,0 +1,15 @@ +{ + "version": 1, + "hooks": { + "sessionStart": [{ "command": "PLUGIN_OPTION_API_KEY=\"${api_key}\" PLUGIN_OPTION_USER_ID=\"${user_id}\" PLUGIN_OPTION_TOP_K=\"${top_k}\" PLUGIN_OPTION_MAX_CONTEXT_CHARS=\"${max_context_chars}\" PLUGIN_OPTION_SEARCH_SCOPE=\"${search_scope}\" python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" sessionStart", "timeout": 5 }], + "beforeSubmitPrompt": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" beforeSubmitPrompt", "timeout": 6 }], + "postToolUse": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" postToolUse", "timeout": 3 }], + "postToolUseFailure": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" postToolUseFailure", "timeout": 3 }], + "afterAgentResponse": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" afterAgentResponse", "timeout": 3 }], + "subagentStart": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" subagentStart", "matcher": "^sidekick$", "timeout": 5 }], + "subagentStop": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" subagentStop", "matcher": "^sidekick$", "timeout": 5 }], + "stop": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" stop", "timeout": 3 }], + "preCompact": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" preCompact", "timeout": 5 }], + "sessionEnd": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" sessionEnd", "timeout": 5 }] + } +} diff --git a/integrations/cursor-plugin/mcp.json b/integrations/cursor-plugin/mcp.json new file mode 100644 index 000000000..b17c1186c --- /dev/null +++ b/integrations/cursor-plugin/mcp.json @@ -0,0 +1,18 @@ +{ + "mcpServers": { + "mem0": { + "type": "stdio", + "command": "python3", + "args": [ + "${CURSOR_PLUGIN_ROOT}/core/mcp_server.py" + ], + "env": { + "PLUGIN_OPTION_API_KEY": "${api_key}", + "PLUGIN_OPTION_USER_ID": "${user_id}", + "PLUGIN_OPTION_TOP_K": "${top_k}", + "PLUGIN_OPTION_MAX_CONTEXT_CHARS": "${max_context_chars}", + "PLUGIN_OPTION_SEARCH_SCOPE": "${search_scope}" + } + } + } +} diff --git a/integrations/cursor-plugin/plugin-build.json b/integrations/cursor-plugin/plugin-build.json new file mode 100644 index 000000000..bddfbec4a --- /dev/null +++ b/integrations/cursor-plugin/plugin-build.json @@ -0,0 +1,15 @@ +{ + "id": "mem0", + "version": "0.3.1", + "homepage": "https://docs.mem0.ai/integrations/cursor", + "native": { + "pluginRoot": "${CURSOR_PLUGIN_ROOT}", + "files": { + ".cursor-plugin/plugin.json": ".cursor-plugin/plugin.json", + "hooks/hooks.json": "hooks/hooks.json", + "hooks/adapter.py": "hooks/adapter.py", + "agents/sidekick.md": "agents/sidekick.md", + "mcp.json": "mcp.json" + } + } +} diff --git a/integrations/cursor-plugin/skills/forget/SKILL.md b/integrations/cursor-plugin/skills/forget/SKILL.md new file mode 100644 index 000000000..c3af4d3df --- /dev/null +++ b/integrations/cursor-plugin/skills/forget/SKILL.md @@ -0,0 +1,26 @@ +--- +name: forget +description: Delete the Mem0 memories stored for this repository and this user. Use when the user asks to forget, clear, wipe, or delete memories. +disable-model-invocation: true +--- + +# Forget this repository's memories + +This permanently deletes remote memories. Before running anything, tell the +user exactly what will be deleted: their own memories for this repository +only. The repository's project memory is shared by everyone who works in it, +so it stays unless the user explicitly asks to delete that too. + +After the user confirms, run: + +```bash +python3 "${CURSOR_PLUGIN_ROOT}/core/memory_cli.py" --harness "cursor" forget --remote --yes +``` + +If the user also asked to delete the repository's shared project memory, add +`--include-project-memory` and say that this removes it for every teammate. + +Report what the command output says was deleted. If the user only wants local +data cleared (evidence log, pending queue), run the same command without +`--remote`. Never pass `--yes` before the user has confirmed in this +conversation. diff --git a/integrations/cursor-plugin/skills/pause/SKILL.md b/integrations/cursor-plugin/skills/pause/SKILL.md new file mode 100644 index 000000000..634385145 --- /dev/null +++ b/integrations/cursor-plugin/skills/pause/SKILL.md @@ -0,0 +1,20 @@ +--- +name: pause +description: Pause Mem0 memory capture on this machine. Use when the user wants to stop memories being recorded, for example for private work or experiments. +disable-model-invocation: true +--- + +# Pause memory capture + +To pause (hooks stop capturing and sending session content; a minimal +anonymous telemetry ping still fires at session start unless +`MEM0_TELEMETRY=false`): + +```bash +python3 "${CURSOR_PLUGIN_ROOT}/core/memory_cli.py" --harness "cursor" pause +``` + +Confirm the new state back to the user, and remind them that already-created +memories still exist and remain searchable. Pending unsent packets are held +while paused, not expired, and are delivered after resuming. To turn capture +back on, use `/mem0:resume`. diff --git a/integrations/cursor-plugin/skills/remember/SKILL.md b/integrations/cursor-plugin/skills/remember/SKILL.md new file mode 100644 index 000000000..7be5fc9be --- /dev/null +++ b/integrations/cursor-plugin/skills/remember/SKILL.md @@ -0,0 +1,21 @@ +--- +name: remember +description: Acknowledge a "remember this" request and make sure it is captured well. Use when the user explicitly asks to remember, note, or save something for future sessions. +disable-model-invocation: true +--- + +# Remember something for future sessions + +Mem0 creates memories from the session automatically — there is no separate +write command. When the user asks to remember something: + +1. Restate the fact clearly and completely in your reply, in one or two + sentences, including any names, values, or paths it depends on. Your visible + reply is what memory extraction reads, so a precise restatement is what gets + remembered. +2. Tell the user it will be saved with this session's memories when the session + ends or compacts, and that it will surface in future sessions in this + repository (they can check later with /mem0:search). + +Do not invent a storage confirmation or a memory ID — creation happens in the +background after the session. diff --git a/integrations/cursor-plugin/skills/resume/SKILL.md b/integrations/cursor-plugin/skills/resume/SKILL.md new file mode 100644 index 000000000..d45bd545d --- /dev/null +++ b/integrations/cursor-plugin/skills/resume/SKILL.md @@ -0,0 +1,19 @@ +--- +name: resume +description: Resume Mem0 memory capture after it was paused with /mem0:pause. +disable-model-invocation: true +--- + +# Resume memory capture + +Resume memory capture for this machine. + +Run: + +```bash +python3 "${CURSOR_PLUGIN_ROOT}/core/memory_cli.py" --harness "cursor" resume +``` + +Confirm to the user that capture is active again. New sessions record evidence and +create memories as normal; nothing that happened while paused is retroactively +captured. diff --git a/integrations/cursor-plugin/skills/search/SKILL.md b/integrations/cursor-plugin/skills/search/SKILL.md new file mode 100644 index 000000000..7a7ddfa90 --- /dev/null +++ b/integrations/cursor-plugin/skills/search/SKILL.md @@ -0,0 +1,28 @@ +--- +name: search +description: Search memories from earlier Cursor 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. +argument-hint: "[question] [--top-k number] [--category category-name] [--scope repo|dir|mine] [--run-id session-id]" +disable-model-invocation: true +--- + +# Search memories + +Call `search_memories` with the user's question. Treat `--top-k`, `--category`, +`--scope`, and `--run-id` as tool arguments instead of including them in the +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. + +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 +monorepo), `mine` for your own preferences alone. + +Pass `run_id` with any scope to retrieve memories saved in a specific coding-agent +session. Omit `run_id` to search across sessions. It filters the memories returned; +it does not identify the session making the search request. Use a known session ID, +never invent one. Return the tool's result directly. diff --git a/integrations/cursor-plugin/skills/status/SKILL.md b/integrations/cursor-plugin/skills/status/SKILL.md new file mode 100644 index 000000000..23ad94e33 --- /dev/null +++ b/integrations/cursor-plugin/skills/status/SKILL.md @@ -0,0 +1,23 @@ +--- +name: status +description: Show whether Mem0 memory is working in this repository, covering configuration, capture state, pending flushes, and whether the Mem0 API key is valid. Use when the user asks whether memory is on, why a memory is missing, or anything looks broken. +disable-model-invocation: false +--- + +# Memory status + +Run both commands and report the combined result in plain language: + +```bash +python3 "${CURSOR_PLUGIN_ROOT}/core/memory_cli.py" --harness "cursor" status --json +python3 "${CURSOR_PLUGIN_ROOT}/core/memory_cli.py" --harness "cursor" doctor +``` + +Summarize, using only fields the JSON actually reports: whether capture is +active or paused, the user ID and repository scope (`repo_id`), whether an +API key is configured, the event/flush/retrieval counts (`flushes` is the +number of completed flushes, not a pending count), and the doctor check +results. If doctor reports an authentication failure (401 / invalid key), say +clearly that the Mem0 API key is invalid or expired and that memories are NOT +being created. Never report an auth failure as "no memories found". Suggest +reinstalling with `--config api_key=...` in that case. diff --git a/integrations/cursor-plugin/tests/test_adapter.py b/integrations/cursor-plugin/tests/test_adapter.py new file mode 100644 index 000000000..d0956e410 --- /dev/null +++ b/integrations/cursor-plugin/tests/test_adapter.py @@ -0,0 +1,112 @@ +from __future__ import annotations + +import importlib.util +import json +import sys +from pathlib import Path + +import pytest + +HOST = Path(__file__).resolve().parents[1] +CORE_ROOT = HOST.parent / "agent-plugin-core" +sys.path.insert(0, str(CORE_ROOT)) +from build.build import build # noqa: E402 + +SPEC = importlib.util.spec_from_file_location("cursor_adapter", HOST / "hooks" / "adapter.py") +assert SPEC and SPEC.loader +adapter = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(adapter) + + +@pytest.mark.parametrize( + ("event", "action"), + [ + ("sessionStart", "session-start"), + ("beforeSubmitPrompt", "user-prompt"), + ("postToolUse", "post-tool"), + ("postToolUseFailure", "post-tool-failure"), + ("afterAgentResponse", "assistant-stop"), + ("subagentStart", "sidekick-start"), + ("subagentStop", "sidekick-stop"), + ("stop", "stop"), + ("sessionEnd", "session-end"), + ("preCompact", "pre-compact"), + ], +) +def test_normalizes_cursor_events(event: str, action: str) -> None: + normalized = adapter.normalize( + { + "conversation_id": "conversation-1", + "workspace_roots": ["/worktree"], + "tool_output": "done", + "text": "assistant response", + }, + event, + ) + + assert normalized["action"] == action + assert normalized["payload"]["session_id"] == "conversation-1" + assert normalized["payload"]["cwd"] == "/worktree" + assert normalized["payload"]["tool_response"] == "done" + assert normalized["payload"]["last_assistant_message"] == "assistant response" + + +def test_after_agent_response_does_not_return_internal_context(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(adapter.hook_runner, "default_record_stop", lambda store, payload: (object(), "session")) + + assert adapter._record_response(object(), {}) is None + + +def test_normalizes_cursor_sidekick_fields() -> None: + started = adapter.normalize( + { + "subagent_id": "agent-1", + "subagent_type": "sidekick", + "parent_conversation_id": "parent-1", + }, + "subagentStart", + )["payload"] + stopped = adapter.normalize({"summary": "done"}, "subagentStop")["payload"] + + assert started["agent_id"] == "agent-1" + assert started["agent_type"] == "sidekick" + assert started["session_id"] == "parent-1" + assert stopped["last_assistant_message"] == "done" + + +def test_cursor_sidekick_records_lifecycle_without_blocking(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(adapter, "record_sidekick_start", lambda store, payload, *, inject_context: "" if not inject_context else pytest.fail("cannot inject context")) + stopped = [] + monkeypatch.setattr(adapter, "record_sidekick_stop", lambda store, payload: stopped.append(payload)) + + assert adapter._record_sidekick_start(object(), {}) == {"permission": "allow"} + assert adapter._record_sidekick_stop(object(), {"summary": "done"}) is None + assert stopped == [{"summary": "done"}] + + +def test_cursor_hooks_use_native_flat_entries() -> None: + hooks = json.loads((HOST / "hooks" / "hooks.json").read_text(encoding="utf-8")) + + assert hooks["version"] == 1 + assert set(hooks["hooks"]) >= { + "sessionStart", + "beforeSubmitPrompt", + "postToolUse", + "subagentStart", + "subagentStop", + "stop", + "sessionEnd", + } + assert hooks["hooks"]["subagentStart"][0]["matcher"] == "^sidekick$" + assert hooks["hooks"]["subagentStop"][0]["matcher"] == "^sidekick$" + assert all("hooks" not in entry for entries in hooks["hooks"].values() for entry in entries) + + +def test_native_cursor_bundle_is_self_contained(tmp_path: Path) -> None: + root = build("cursor", "native", tmp_path / "cursor") + + manifest = json.loads((root / ".cursor-plugin" / "plugin.json").read_text(encoding="utf-8")) + assert manifest["hooks"] == "./hooks/hooks.json" + assert (root / "hooks" / "adapter.py").is_file() + assert (root / "agents" / "sidekick.md").is_file() + assert not any(path.is_symlink() for path in root.rglob("*")) diff --git a/integrations/deepseek-plugin/README.md b/integrations/deepseek-plugin/README.md index 088835d08..fc6617c3f 100644 --- a/integrations/deepseek-plugin/README.md +++ b/integrations/deepseek-plugin/README.md @@ -2,10 +2,12 @@ [Mem0](https://mem0.ai) long-term memory as a native [DeepSeek Harness](https://github.com/deepseek-ai/deepseek-harness) (Cordis) plugin. -It gives a Harness agent two memory tools backed by the Mem0 SDK, so recall and writes persist across sessions: +It gives a Harness agent automatic long-term memory plus two explicit memory tools backed by the Mem0 SDK: -| Tool | Does | +| Capability | Does | |---|---| +| Auto-recall | Searches Mem0 for the latest human prompt and adds unseen results to the model context | +| Auto-capture | Stores the human/assistant messages from each completed turn | | `search_memory` | Recall facts from Mem0 relevant to a query | | `add_memory` | Store a fact in Mem0 for future sessions | @@ -13,33 +15,47 @@ Unlike the local/file-based memory plugins in the ecosystem, Mem0 is a managed b ## How it works -A Cordis plugin is a module exporting `apply(ctx, config)`. This one declares `inject = ['tools']` so it waits for the harness tool registry, then registers the two tools via `ctx.tools.register(defineTool(...))`. When the plugin unmounts, the tools are removed automatically (Cordis revertible effects). +A Cordis plugin is a module exporting `apply(ctx, config)`. This one waits for the Harness tool and system-prompt services, then uses the native extension points: + +- `system-prompt/assemble` recalls memory before a model request. +- `session/event` captures only completed turns from the durable event stream. +- `ctx.tools.register(...)` exposes explicit search and add tools. + +Cordis owns listener and tool cleanup when the plugin unmounts. Every automatic path is fail-open: a memory API failure does not block the agent. ``` [ mem0ai SDK ] <-- managed memory, owned by Mem0 | -[ deepseek-plugin: apply(ctx) -> ctx.tools.register(...) ] <-- this package +[ deepseek-plugin: prompt + session listeners, memory tools ] <-- this package | [ DeepSeek Harness ] <-- the agent, loaded via cordis.yml ``` ## Try it locally -1. Build the plugin: +1. Build and pack the plugin: ```sh cd integrations/deepseek-plugin - pnpm install + pnpm install --frozen-lockfile pnpm build + mkdir -p /tmp/mem0-deepseek-plugin + pnpm pack --pack-destination /tmp/mem0-deepseek-plugin ``` 2. Set your Mem0 key: ```sh export MEM0_API_KEY=... ``` -3. Point Harness at it. Copy `cordis.example.yml`, set the absolute path to `dist/index.js` and your `userId`, then: +3. Install it into a disposable Harness profile: ```sh - pnpm dsh web --patch ./integrations/deepseek-plugin/cordis.example.yml + DSH_HOME=/tmp/mem0-dsh-dev pnpm dlx @deepseek-ai/dsh@0.1.1-rc.2 \ + plugin --profile headless add /tmp/mem0-deepseek-plugin/mem0-deepseek-plugin-0.3.0.tgz ``` -4. Open http://127.0.0.1:3080 and ask the agent to remember something, then recall it in a later turn. +4. Copy `cordis.example.yml`, set its installed package path and your `userId`, then run Harness with the same profile: + ```sh + DSH_HOME=/tmp/mem0-dsh-dev pnpm dlx @deepseek-ai/dsh@0.1.1-rc.2 \ + web --patch ./integrations/deepseek-plugin/cordis.example.yml + ``` +5. Open http://127.0.0.1:3080 and ask the agent to remember something, then recall it in a later turn. For a Mem0 Platform on-prem or dedicated deployment, point `config.host` at that base URL (defaults to `api.mem0.ai`). `host` is a Platform base-URL override — it is not a switch to self-hosted Mem0 OSS, whose server exposes a different API surface. @@ -49,7 +65,10 @@ For a Mem0 Platform on-prem or dedicated deployment, point `config.host` at that |---|---|---|---| | `apiKey` | no | `$MEM0_API_KEY` | Mem0 platform API key | | `userId` | yes | | Entity that owns the memories | +| `allowUserOverride` | no | `false` | Permit model-selected access to a different user only in a trusted multi-user deployment | | `host` | no | `api.mem0.ai` | Platform base URL (on-prem / dedicated) | +| `autoRecall` | no | `true` | Recall relevant memory before model requests | +| `autoCapture` | no | `true` | Store completed human/assistant turns | ## Telemetry @@ -59,4 +78,6 @@ The plugin also sends anonymous usage events (which tool ran, duration, result c ## Status -Developer preview. Tracks the DeepSeek Harness v0.1 plugin API (`@deepseek-ai/cordis`, `@deepseek-ai/dsh-tools`), which is young and moving; pin versions once it stabilizes. Auto-capture (store turns without an explicit tool call) and auto-recall (inject memory into the prompt at assembly) are planned once the harness session/assembly event API is confirmed. +Developer preview. Tracks the DeepSeek Harness v0.1 plugin API, which is young and moving. Harness capability packages are peer dependencies supplied by the host; this package pins matching release-candidate versions for local typechecking and tests. + +Per-call `userId` overrides are rejected unless the operator enables `allowUserOverride: true`. Automatic recall and capture always use the configured user. diff --git a/integrations/deepseek-plugin/cordis.example.yml b/integrations/deepseek-plugin/cordis.example.yml index 7a0ac3bb9..5ed84b162 100644 --- a/integrations/deepseek-plugin/cordis.example.yml +++ b/integrations/deepseek-plugin/cordis.example.yml @@ -1,19 +1,17 @@ # Example DeepSeek Harness config that loads deepseek-plugin alongside the built-in # tools plugin. Load with: # -# pnpm dsh web --patch ./integrations/deepseek-plugin/cordis.example.yml +# DSH_HOME=/tmp/mem0-dsh-dev pnpm dlx @deepseek-ai/dsh@0.1.1-rc.2 \ +# web --patch ./integrations/deepseek-plugin/cordis.example.yml # -# The tools plugin (and its system-prompt dependency) must be present, because -# the memory tools contribute schemas the system prompt renders. - -- name: "@deepseek-ai/dsh-system-prompt" -- name: "@deepseek-ai/dsh-tools" - insert: - id: mem0 - # Absolute path to the built plugin (run `pnpm build` first), or point - # at src/index.ts when running through tsx during development. - name: "/absolute/path/to/mem0/integrations/deepseek-plugin/dist/index.js" + # Install the packed plugin into this disposable profile first; loading + # raw dist bypasses Harness's peer dependency installation. + name: "/tmp/mem0-dsh-dev/profiles/headless/node_modules/@mem0/deepseek-plugin/dist/index.js" config: # apiKey is read from the MEM0_API_KEY env var when omitted here. userId: "your-user-id" + # autoRecall: true # optional; enabled by default + # autoCapture: true # optional; enabled by default # host: "https://your-onprem.mem0.ai" # optional: Platform on-prem / dedicated base URL diff --git a/integrations/deepseek-plugin/package.json b/integrations/deepseek-plugin/package.json index b64e4a4e7..ea00bb9c5 100644 --- a/integrations/deepseek-plugin/package.json +++ b/integrations/deepseek-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@mem0/deepseek-plugin", - "version": "0.1.1", + "version": "0.3.0", "description": "Mem0 long-term memory as a native DeepSeek Harness (Cordis) plugin.", "type": "module", "license": "Apache-2.0", @@ -31,7 +31,6 @@ }, "files": [ "dist", - "src", "README.md", "LICENSE" ], @@ -46,11 +45,17 @@ }, "peerDependencies": { "@deepseek-ai/cordis": "*", + "@deepseek-ai/dsh-agent": "*", + "@deepseek-ai/dsh-session": "*", + "@deepseek-ai/dsh-system-prompt": "*", "@deepseek-ai/dsh-tools": "*" }, "devDependencies": { "@deepseek-ai/cordis": "4.0.1", - "@deepseek-ai/dsh-tools": "0.0.1-rc.1", + "@deepseek-ai/dsh-agent": "0.1.1-rc.2", + "@deepseek-ai/dsh-session": "0.1.1-rc.2", + "@deepseek-ai/dsh-system-prompt": "0.1.1-rc.2", + "@deepseek-ai/dsh-tools": "0.1.1-rc.2", "@types/node": "^22.15.0", "tsup": "^8.5.0", "typescript": "^5.6.0", diff --git a/integrations/deepseek-plugin/pnpm-lock.yaml b/integrations/deepseek-plugin/pnpm-lock.yaml index 26bc065c8..1444b53d4 100644 --- a/integrations/deepseek-plugin/pnpm-lock.yaml +++ b/integrations/deepseek-plugin/pnpm-lock.yaml @@ -15,9 +15,18 @@ importers: '@deepseek-ai/cordis': specifier: 4.0.1 version: 4.0.1 + '@deepseek-ai/dsh-agent': + specifier: 0.1.1-rc.2 + version: 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)(@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))(@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)) + '@deepseek-ai/dsh-session': + specifier: 0.1.1-rc.2 + version: 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1) + '@deepseek-ai/dsh-system-prompt': + specifier: 0.1.1-rc.2 + version: 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1) '@deepseek-ai/dsh-tools': - specifier: 0.0.1-rc.1 - version: 0.0.1-rc.1(@deepseek-ai/cordis@4.0.1) + specifier: 0.1.1-rc.2 + version: 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)(@deepseek-ai/dsh-agent@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)(@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))(@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)))(@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))(@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)) '@types/node': specifier: ^22.15.0 version: 22.20.1 @@ -48,18 +57,47 @@ packages: '@deepseek-ai/cosmokit@1.8.2': resolution: {integrity: sha512-muBOKtSrUKU5m/xpq8ZXWL6hQ/jgd4PhU2PqH97bcxIiLEJfNwZOGQEx4t/aS/GgxRAR+ra9pMHPMtTHU4sqqA==} - '@deepseek-ai/dsh-tools@0.0.1-rc.1': - resolution: {integrity: sha512-mrtq+UXc6UVidrGo4GM8RAH0Gqc4iFOmtPeQAz59Phhjl3EmzkFI0Mo6dQlHQamrc2J9jppPtGtUzW9qHmwxDQ==} + '@deepseek-ai/dsh-agent@0.1.1-rc.2': + resolution: {integrity: sha512-cC7lnJe7JgPFcreNXxcxLMxQd78LnpVO9ZXROjZsGRQN1zGH6i/DduI892F1am85IfzzO+XTxMwwUHmfwamb0g==} peerDependencies: - '@deepseek-ai/cordis': ^4.0.1-rc.1 - '@deepseek-ai/dsh-agent': ^0.0.1-rc.1 - '@deepseek-ai/dsh-code-runtime': ^0.0.1-rc.1 - '@deepseek-ai/dsh-invariants': ^0.0.1-rc.1 - '@deepseek-ai/dsh-llm': ^0.0.1-rc.1 - '@deepseek-ai/dsh-scope': ^0.0.1-rc.1 - '@deepseek-ai/dsh-session': ^0.0.1-rc.1 - '@deepseek-ai/dsh-system-prompt': ^0.0.1-rc.1 - '@deepseek-ai/dsh-user-approval': ^0.0.1-rc.1 + '@deepseek-ai/cordis': ^4.0.1 + '@deepseek-ai/dsh-invariants': ^0.1.1-rc.2 + '@deepseek-ai/dsh-llm': ^0.1.1-rc.2 + '@deepseek-ai/dsh-scope': ^0.1.1-rc.2 + '@deepseek-ai/dsh-session': ^0.1.1-rc.2 + '@deepseek-ai/dsh-system-prompt': ^0.1.1-rc.2 + '@deepseek-ai/dsh-typert-protocol': ^0.1.1-rc.2 + + '@deepseek-ai/dsh-session@0.1.1-rc.2': + resolution: {integrity: sha512-4/cv6X9HPhm47eyRhCu/WZwzrtJKegk5J+0xaxcZ9i8S0smdxP57tqy8a0jkSshLQn7BzMFxneQrlYExrLrDhQ==} + peerDependencies: + '@deepseek-ai/cordis': ^4.0.1 + '@deepseek-ai/dsh-brand': ^0.1.1-rc.2 + '@deepseek-ai/dsh-invariants': ^0.1.1-rc.2 + '@deepseek-ai/dsh-llm': ^0.1.1-rc.2 + '@deepseek-ai/dsh-scope': ^0.1.1-rc.2 + '@deepseek-ai/dsh-typert-protocol': ^0.1.1-rc.2 + + '@deepseek-ai/dsh-system-prompt@0.1.1-rc.2': + resolution: {integrity: sha512-on4hjAlYI5uX9q7Sf95YkMMBVe6heywtA/H50ksrIMUub8U2B98hO9iQpHhjwIO1F1vu+5pLcPvRr6yUGGmtXQ==} + peerDependencies: + '@deepseek-ai/cordis': ^4.0.1 + '@deepseek-ai/dsh-invariants': ^0.1.1-rc.2 + '@deepseek-ai/dsh-llm': ^0.1.1-rc.2 + '@deepseek-ai/dsh-scope': ^0.1.1-rc.2 + + '@deepseek-ai/dsh-tools@0.1.1-rc.2': + resolution: {integrity: sha512-0GGL4D55MwYDepzZMOI3L0ycu5b2qr96GL0Y7snwhAnpK2Di61rbX3fJE+PB3ZrovGX0csIRdt9n3iJZDVtDrw==} + peerDependencies: + '@deepseek-ai/cordis': ^4.0.1 + '@deepseek-ai/dsh-agent': ^0.1.1-rc.2 + '@deepseek-ai/dsh-code-runtime': ^0.1.1-rc.2 + '@deepseek-ai/dsh-invariants': ^0.1.1-rc.2 + '@deepseek-ai/dsh-llm': ^0.1.1-rc.2 + '@deepseek-ai/dsh-scope': ^0.1.1-rc.2 + '@deepseek-ai/dsh-session': ^0.1.1-rc.2 + '@deepseek-ai/dsh-system-prompt': ^0.1.1-rc.2 + '@deepseek-ai/dsh-user-approval': ^0.1.1-rc.2 '@deepseek-ai/schemastery@3.18.1': resolution: {integrity: sha512-Qn0FCSwCQnpnj6SB31I6i2sIKgKWnkbJM8O0EU91Gv2UsYVvtZTl6IA0sCwk2e2MZf5S8w5hpq9QkeVvK9qwxg==} @@ -1238,9 +1276,27 @@ snapshots: '@deepseek-ai/cosmokit@1.8.2': {} - '@deepseek-ai/dsh-tools@0.0.1-rc.1(@deepseek-ai/cordis@4.0.1)': + '@deepseek-ai/dsh-agent@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)(@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))(@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))': dependencies: '@deepseek-ai/cordis': 4.0.1 + '@deepseek-ai/dsh-session': 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1) + '@deepseek-ai/dsh-system-prompt': 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1) + + '@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)': + dependencies: + '@deepseek-ai/cordis': 4.0.1 + + '@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)': + dependencies: + '@deepseek-ai/cordis': 4.0.1 + '@deepseek-ai/schemastery': 3.18.1 + + '@deepseek-ai/dsh-tools@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)(@deepseek-ai/dsh-agent@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)(@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))(@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)))(@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))(@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))': + dependencies: + '@deepseek-ai/cordis': 4.0.1 + '@deepseek-ai/dsh-agent': 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)(@deepseek-ai/dsh-session@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1))(@deepseek-ai/dsh-system-prompt@0.1.1-rc.2(@deepseek-ai/cordis@4.0.1)) + '@deepseek-ai/dsh-session': 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1) + '@deepseek-ai/dsh-system-prompt': 0.1.1-rc.2(@deepseek-ai/cordis@4.0.1) '@deepseek-ai/schemastery': 3.18.1 '@deepseek-ai/schemastery@3.18.1': diff --git a/integrations/deepseek-plugin/src/formatting.ts b/integrations/deepseek-plugin/src/formatting.ts index 63296a185..79bb6283f 100644 --- a/integrations/deepseek-plugin/src/formatting.ts +++ b/integrations/deepseek-plugin/src/formatting.ts @@ -1,69 +1,7 @@ -/** - * Compact, token-cheap rendering of Mem0 results for the model context. - * - * Mirrors the format used by the sibling Mem0 plugins - * (integrations/pi-agent-plugin/src/memory/formatting.ts) so a memory reads the - * same way across every harness: `[category] text (age) [mem0:id]`. Dumping the - * raw search envelope instead would spend most of the tokens on JSON scaffolding. - */ - -export interface MemoryLike { - id: string; - memory?: string; - categories?: string[]; - createdAt?: Date | string; -} - -export function formatAge(date: Date | string): string { - const d = typeof date === "string" ? new Date(date) : date; - const ms = Date.now() - d.getTime(); - const minutes = Math.floor(ms / 60_000); - if (minutes < 60) return `${minutes}m ago`; - const hours = Math.floor(minutes / 60); - if (hours < 24) return `${hours}h ago`; - const days = Math.floor(hours / 24); - return `${days}d ago`; -} - -export function formatMemoryCompact(mem: MemoryLike): string { - const cat = mem.categories?.[0] ?? "uncategorized"; - const age = mem.createdAt ? ` (${formatAge(mem.createdAt)})` : ""; - return `[${cat}] ${mem.memory ?? "(empty)"}${age} [mem0:${mem.id}]`; -} - -export function formatMemoryList(memories: MemoryLike[]): string { - if (memories.length === 0) return "No memories found."; - return memories - .map((m, i) => `${i + 1}. ${formatMemoryCompact(m)}`) - .join("\n"); -} - -/** - * One-line confirmation for a write. - * - * `client.add` hits the async `/v3/memories/add/` endpoint, which returns - * `{ event_id, status: "PENDING" }` — extraction runs server-side *after* the - * call returns, so the extracted memories are not in this response. Report the - * write as queued in that case; only render a list when the backend actually - * returns memories (older / OSS shapes). - */ -export function formatAddResult(result: unknown): string { - const items: MemoryLike[] = Array.isArray(result) - ? (result as MemoryLike[]) - : ((result as { results?: MemoryLike[] } | null)?.results ?? - (result ? [result as MemoryLike] : [])); - - const pending = items.find( - (r) => (r as { status?: string }).status === "PENDING", - ) as { eventId?: string; event_id?: string } | undefined; - if (pending) { - // The SDK camel-cases response keys (event_id -> eventId); accept either. - const id = pending.eventId ?? pending.event_id; - const evt = id ? ` (event ${id})` : ""; - return `Memory queued for background extraction${evt}; it will be searchable shortly.`; - } - - if (items.length === 0) return "Memory stored."; - const noun = items.length === 1 ? "memory" : "memories"; - return `Stored ${items.length} ${noun}:\n${formatMemoryList(items)}`; -} +export { + formatAddResult, + formatAge, + formatMemoryCompact, + formatMemoryList, +} from "../../agent-plugin-core/typescript/src/formatting.ts"; +export type { MemoryLike } from "../../agent-plugin-core/typescript/src/formatting.ts"; diff --git a/integrations/deepseek-plugin/src/index.ts b/integrations/deepseek-plugin/src/index.ts index 6cb9bef12..bea70c02c 100644 --- a/integrations/deepseek-plugin/src/index.ts +++ b/integrations/deepseek-plugin/src/index.ts @@ -6,20 +6,24 @@ * - `add_memory` stores a fact for future sessions * * A plugin is a Cordis module that exports `apply(ctx, config)`. Declaring - * `inject = ['tools']` holds the plugin until the harness tool registry exists; + * `inject = ['tools', 'systemPrompt']` holds the plugin until the harness services exist; * tools registered via `ctx.tools.register(...)` are auto-unregistered when the * plugin unmounts (Cordis revertible effects). */ import type { Context } from "@deepseek-ai/cordis"; +import type {} from "@deepseek-ai/dsh-agent"; +import type { PromptAssembly } from "@deepseek-ai/dsh-system-prompt"; +import type {} from "@deepseek-ai/dsh-session"; import { defineTool } from "@deepseek-ai/dsh-tools"; import { MemoryClient } from "mem0ai"; import { formatMemoryList, formatAddResult } from "./formatting.ts"; 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"; export const name = "mem0"; -export const inject = ["tools"]; +export const inject = ["tools", "systemPrompt"]; // Tags writes so Mem0's backend attributes them to this integration in // telemetry. The backend keeps recognized values via its KNOWN_EVENT_SOURCES @@ -29,14 +33,32 @@ export const inject = ["tools"]; const SOURCE = "DEEPSEEK_HARNESS"; const DEFAULT_SEARCH_LIMIT = 10; +const AUTO_RECALL_LIMIT = 5; + +interface HarnessMessage { + role: string; + content?: unknown; + source?: { kind?: string }; +} + +interface SessionState { + lifecycle: ReturnType; + messages: HarnessMessage[]; +} export interface Config { /** Mem0 API key. Defaults to the MEM0_API_KEY env var. */ apiKey?: string; /** Default entity that owns the memories (Mem0 user scope). */ userId: string; + /** Explicitly allow model-selected cross-user access. Defaults to false. */ + allowUserOverride?: boolean; /** Optional Mem0 Platform base-URL override (on-prem / dedicated); defaults to api.mem0.ai. Not a switch to self-hosted OSS. */ host?: string; + /** Recall relevant memory before each model request. Defaults to true. */ + autoRecall?: boolean; + /** Store completed turns automatically. Defaults to true. */ + autoCapture?: boolean; } // Both tools return a single text string; the render is identical, so lift it @@ -55,7 +77,7 @@ const scopeParams = { userId: { type: "string", description: - "Entity that owns the memory. Defaults to the plugin's configured userId; set this only to read or write another user's memories.", + "Entity that owns the memory. Defaults to the plugin's configured userId; cross-user overrides require allowUserOverride in plugin configuration.", }, agentId: { type: "string", @@ -72,8 +94,8 @@ export function apply(ctx: Context, config: Config): void { if (!apiKey) { throw new Error("deepseek-plugin: set config.apiKey or the MEM0_API_KEY env var"); } - const userId = config.userId; - if (!userId) { + const userId = config.userId?.trim(); + if (!userId || /^\*+$/.test(userId)) { throw new Error("deepseek-plugin: config.userId is required"); } @@ -81,8 +103,95 @@ export function apply(ctx: Context, config: Config): void { apiKey, ...(config.host ? { host: config.host } : {}), }); + const toolLifecycle = createMemoryLifecycle(); + const sessionStates = new WeakMap(); + const stateFor = (session: object): SessionState => { + let state = sessionStates.get(session); + if (!state) { + const lifecycle = createMemoryLifecycle(); + lifecycle.beginSession(); + state = { lifecycle, messages: [] }; + sessionStates.set(session, state); + } + return state; + }; - captureEvent("deepseek.plugin.mounted", { has_host: Boolean(config.host) }, client); + captureEvent("deepseek.plugin.mounted", { + has_host: Boolean(config.host), + auto_recall: config.autoRecall !== false, + auto_capture: config.autoCapture !== false, + }, client); + + if (config.autoRecall !== false) { + ctx.on("system-prompt/assemble", async (_input, context, next): Promise => { + const assembly = await next(); + const { agent, signal } = context; + if (!agent || signal?.aborted) return assembly; + + const state = stateFor(agent.session); + const prompt = state.lifecycle.prepareConversation( + agent.session + .deriveMessages() + .filter((message) => message.role === "user" && message.source?.kind === "user"), + ).at(-1)?.content; + if (!prompt) return assembly; + + const memoryContext = await state.lifecycle.recall(prompt, true, async (query) => { + const started = Date.now(); + try { + const result = await client.search(query, { + filters: resolveSearchFilters({}, userId), + topK: AUTO_RECALL_LIMIT, + }); + captureEvent("deepseek.recall.auto", { + success: true, + duration_ms: Date.now() - started, + result_count: result.results?.length ?? 0, + }, client); + return result; + } catch (err) { + captureEvent("deepseek.recall.auto", { + success: false, + duration_ms: Date.now() - started, + error_kind: errorKind(err), + }, client); + throw err; + } + }); + if (!memoryContext || signal?.aborted) return assembly; + return { + ...assembly, + contexts: [...assembly.contexts, { name: "mem0:recall", text: memoryContext }], + }; + }); + } + + if (config.autoCapture !== false) { + ctx.on("session/event", (session, event) => { + const state = stateFor(session); + if (event.type === "turn/start") { + state.messages = []; + } else if (event.type === "user/message" && event.data.source.kind === "user") { + state.messages.push(event.data); + } else if (event.type === "assistant/message") { + state.messages.push(event.data.message); + } else if (event.type === "turn/end") { + const conversation = state.lifecycle.prepareConversation(state.messages); + state.messages = []; + if (event.data.reason.kind !== "completed" || conversation.length === 0) return; + void client + .add(conversation, { userId, source: SOURCE }) + .then(() => captureEvent("deepseek.capture.auto", { + success: true, + message_count: conversation.length, + }, client)) + .catch((err: unknown) => captureEvent("deepseek.capture.auto", { + success: false, + error_kind: errorKind(err), + }, client)); + } + }); + } // Recall. The platform rejects top-level entity params on search, so scope // goes inside `filters` (unlike add below, which takes them top-level). @@ -101,11 +210,15 @@ export function apply(ctx: Context, config: Config): void { }, output: textOutput, async execute({ query, limit, userId: u, agentId, runId }) { + if (u?.trim() && u.trim() !== userId && config.allowUserOverride !== true) { + throw new Error("Cross-user access requires allowUserOverride in plugin configuration."); + } + const safeQuery = toolLifecycle.prepareUserText(query); const filters = resolveSearchFilters({ userId: u, agentId, runId }, userId); const topK = limit && limit > 0 ? limit : DEFAULT_SEARCH_LIMIT; const started = Date.now(); try { - const { results } = await client.search(query, { filters, topK }); + const { results } = await client.search(safeQuery, { filters, topK }); captureEvent( "deepseek.tool.search_memory", { @@ -150,13 +263,19 @@ export function apply(ctx: Context, config: Config): void { }, output: textOutput, async execute({ text, userId: u, agentId, runId }) { + if (u?.trim() && u.trim() !== userId && config.allowUserOverride !== true) { + throw new Error("Cross-user access requires allowUserOverride in plugin configuration."); + } const addParams = resolveAddParams({ userId: u, agentId, runId }, userId); const started = Date.now(); try { - const result = await client.add([{ role: "user", content: text }], { - ...addParams, - source: SOURCE, - }); + const result = await client.add( + [{ role: "user", content: toolLifecycle.prepareUserText(text) }], + { + ...addParams, + source: SOURCE, + }, + ); captureEvent( "deepseek.tool.add_memory", { diff --git a/integrations/deepseek-plugin/src/output.ts b/integrations/deepseek-plugin/src/output.ts index 44eee7c30..7ec64eff9 100644 --- a/integrations/deepseek-plugin/src/output.ts +++ b/integrations/deepseek-plugin/src/output.ts @@ -1,33 +1,5 @@ -/** - * Hard cap on tool output before it reaches the model context. - * - * Same guard the sibling plugins apply (200 lines / 50KB, see - * integrations/pi-agent-plugin/src/memory/tools.ts): a large recall or a wide - * result set can otherwise flood the context window in a single tool call. - */ - -export const MAX_OUTPUT_LINES = 200; -export const MAX_OUTPUT_BYTES = 50_000; - -export function truncateOutput(text: string): string { - const lines = text.split("\n"); - if (lines.length <= MAX_OUTPUT_LINES && text.length <= MAX_OUTPUT_BYTES) { - return text; - } - - const kept = lines.slice(0, MAX_OUTPUT_LINES); - let result = kept.join("\n"); - const byteCapped = result.length > MAX_OUTPUT_BYTES; - if (byteCapped) { - result = result.slice(0, MAX_OUTPUT_BYTES); - } - - const dropped = lines.length - kept.length; - const reasons: string[] = []; - if (dropped > 0) reasons.push(`showing ${kept.length} of ${lines.length} lines`); - if (byteCapped) reasons.push(`cut at ${Math.floor(MAX_OUTPUT_BYTES / 1000)}KB`); - if (reasons.length > 0) { - result += `\n\n[Output truncated: ${reasons.join(", ")}]`; - } - return result; -} +export { + MAX_OUTPUT_BYTES, + MAX_OUTPUT_LINES, + truncateOutput, +} from "../../agent-plugin-core/typescript/src/formatting.ts"; diff --git a/integrations/deepseek-plugin/src/scoping.ts b/integrations/deepseek-plugin/src/scoping.ts index ee5bfd81d..ac471b0aa 100644 --- a/integrations/deepseek-plugin/src/scoping.ts +++ b/integrations/deepseek-plugin/src/scoping.ts @@ -1,53 +1,5 @@ -/** - * Per-call memory scoping. - * - * The plugin is mounted with one default `userId`, but a single harness install - * can serve more than one entity, so both tools accept optional `userId` / - * `agentId` / `runId` params that override the mount-time default per call. - * A missing or blank param falls back to the configured user. - * - * The two call sites need different key casing, and it is deliberate rather than - * incidental: search passes scope inside `filters`, sent to the platform raw, so - * it must be snake_case; add takes the entity params top-level, through the - * SDK's camel->snake converter, so it must be camelCase. Keeping the split - * explicit (like integrations/pi-agent-plugin/src/memory/scoping.ts) means the - * asymmetry is visible in the code, not load-bearing on a converter no-op. - */ - -export interface EntityParams { - userId?: string; - agentId?: string; - runId?: string; -} - -const clean = (v: string | undefined) => v?.trim() || undefined; - -/** Search: snake_case, spread into `filters` and passed to the platform raw. */ -export function resolveSearchFilters( - params: EntityParams, - defaultUserId: string, -): Record { - const filters: Record = { - user_id: clean(params.userId) ?? defaultUserId, - }; - const agentId = clean(params.agentId); - if (agentId) filters.agent_id = agentId; - const runId = clean(params.runId); - if (runId) filters.run_id = runId; - return filters; -} - -/** Add: camelCase, top-level params run through the SDK's camel->snake converter. */ -export function resolveAddParams( - params: EntityParams, - defaultUserId: string, -): Record { - const out: Record = { - userId: clean(params.userId) ?? defaultUserId, - }; - const agentId = clean(params.agentId); - if (agentId) out.agentId = agentId; - const runId = clean(params.runId); - if (runId) out.runId = runId; - return out; -} +export { + entityAddParams as resolveAddParams, + entitySearchFilters as resolveSearchFilters, +} from "../../agent-plugin-core/typescript/src/identity.ts"; +export type { EntityParams } from "../../agent-plugin-core/typescript/src/identity.ts"; diff --git a/integrations/deepseek-plugin/src/telemetry.ts b/integrations/deepseek-plugin/src/telemetry.ts index b963e62ce..24cd868a3 100644 --- a/integrations/deepseek-plugin/src/telemetry.ts +++ b/integrations/deepseek-plugin/src/telemetry.ts @@ -1,173 +1,98 @@ -/** - * Anonymous usage telemetry for the DeepSeek Harness plugin. - * - * Fire-and-forget PostHog events over native fetch, batched and flushed every - * 5 seconds, at 10 queued events, or on process exit. Never throws, never logs. - * - * Events carry only tool names, durations, counts, and coarse failure kinds: - * never queries, memory text, filters, or API keys. - * - * Disable with MEM0_TELEMETRY=false. - */ import { randomUUID } from "node:crypto"; import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; -const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"; -const POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/"; -const FLUSH_INTERVAL_MS = 5_000; -const FLUSH_THRESHOLD = 10; -const SEND_TIMEOUT_MS = 3_000; +import { + createTelemetry, + errorKind, + isTelemetryEnabled, +} from "../../agent-plugin-core/typescript/src/telemetry.ts"; -const PLUGIN_VERSION = ((): string => { +export { errorKind, isTelemetryEnabled }; + +const PLUGIN_VERSION = (() => { try { - return JSON.parse( - fs.readFileSync(new URL("../package.json", import.meta.url), "utf-8"), - ).version; + return JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf-8")).version; } catch { return "unknown"; } })(); -/** The Mem0 SDK resolves this to the account email once ping() lands, so events join other Mem0 surfaces. */ export interface TelemetryIdentity { telemetryId?: string; } -let queue: Record[] = []; -let flushTimer: ReturnType | undefined; -let exitHandlerInstalled = false; let cachedAnonymousId: string | undefined; let identified = false; +let currentDistinctId = ""; function identityPath(): string { return path.join(os.homedir(), ".mem0", "deepseek-plugin-telemetry.json"); } -export function isTelemetryEnabled(): boolean { - const value = process.env.MEM0_TELEMETRY?.toLowerCase(); - return value !== "false" && value !== "0" && value !== "no" && value !== "off"; -} - function anonymousId(): string { if (cachedAnonymousId) return cachedAnonymousId; try { const stored = JSON.parse(fs.readFileSync(identityPath(), "utf-8")); if (typeof stored.anonymousId === "string" && stored.anonymousId) { - cachedAnonymousId = stored.anonymousId; - return cachedAnonymousId!; + return (cachedAnonymousId = stored.anonymousId); } } catch { - /* first run, or an unreadable identity file */ + // First run or unreadable identity file. } const created = `deepseek-anon-${randomUUID().replace(/-/g, "")}`; try { - const target = identityPath(); - fs.mkdirSync(path.dirname(target), { recursive: true }); - fs.writeFileSync(target, JSON.stringify({ anonymousId: created }), "utf-8"); + fs.mkdirSync(path.dirname(identityPath()), { recursive: true }); + fs.writeFileSync(identityPath(), JSON.stringify({ anonymousId: created }), "utf-8"); } catch { - /* an unwritable home directory must not break the plugin */ + // An unwritable home directory must not break the plugin. } - cachedAnonymousId = created; - return created; + return (cachedAnonymousId = created); } -/** Merge the pre-ping anonymous history into the account once the email resolves. */ -function identifyEvent(distinctId: string): Record | undefined { +function previousAnonymousId(distinctId: string): string | undefined { if (identified || distinctId.startsWith("deepseek-anon-")) return undefined; identified = true; - let storedAnonymousId: string | undefined; try { - storedAnonymousId = JSON.parse(fs.readFileSync(identityPath(), "utf-8")).anonymousId; + const stored = JSON.parse(fs.readFileSync(identityPath(), "utf-8")).anonymousId; fs.unlinkSync(identityPath()); + cachedAnonymousId = undefined; + return typeof stored === "string" && stored ? stored : undefined; } catch { return undefined; } - cachedAnonymousId = undefined; - if (!storedAnonymousId) return undefined; - return { - event: "$identify", - distinct_id: distinctId, - properties: { $anon_distinct_id: storedAnonymousId, $lib: "posthog-node" }, - }; } -export function flushEvents(): void { - if (queue.length === 0) return; - const batch = queue; - queue = []; - fetch(POSTHOG_BATCH_URL, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ api_key: POSTHOG_API_KEY, batch }), - signal: AbortSignal.timeout(SEND_TIMEOUT_MS), - }).catch(() => { - /* telemetry never surfaces its own failures */ - }); -} - -function scheduleFlush(): void { - if (!flushTimer) { - flushTimer = setInterval(flushEvents, FLUSH_INTERVAL_MS); - flushTimer.unref?.(); - } - if (!exitHandlerInstalled) { - exitHandlerInstalled = true; - process.on("beforeExit", flushEvents); - } -} - -export function errorKind(error: unknown): string { - const text = (error instanceof Error ? error.message : String(error)).toLowerCase(); - if (text.includes("timeout") || text.includes("aborted")) return "timeout"; - if (text.includes("401") || text.includes("403") || text.includes("unauthor")) return "auth"; - if (text.includes("429") || text.includes("rate limit")) return "rate-limited"; - if (/50[0234]/.test(text)) return "server-error"; - if (text.includes("400") || text.includes("422")) return "bad-request"; - if (text.includes("fetch failed") || text.includes("enotfound")) return "network"; - return error instanceof Error ? error.constructor.name : "other"; -} +const telemetry = createTelemetry({ + host: "deepseek", + source: "DEEPSEEK_HARNESS", + version: PLUGIN_VERSION, + distinctId: () => currentDistinctId, +}); export function captureEvent( event: string, properties: Record, client: TelemetryIdentity, ): void { - if (!isTelemetryEnabled()) return; - try { - const distinctId = client.telemetryId || anonymousId(); - const identify = identifyEvent(distinctId); - if (identify) queue.push(identify); - queue.push({ - event, - distinct_id: distinctId, - properties: { - source: "DEEPSEEK_HARNESS", - language: "node", - plugin_version: PLUGIN_VERSION, - node_version: process.version, - os: process.platform, - $process_person_profile: false, - $lib: "posthog-node", - ...properties, - }, - }); - scheduleFlush(); - if (queue.length >= FLUSH_THRESHOLD) flushEvents(); - } catch { - /* telemetry never breaks a tool call */ - } + currentDistinctId = client.telemetryId || anonymousId(); + const anonymous = previousAnonymousId(currentDistinctId); + if (anonymous) telemetry.capture("$identify", { $anon_distinct_id: anonymous }); + telemetry.capture(event, properties); +} + +export function flushEvents(): void { + void telemetry.flush(); } export function _queueForTesting(): Record[] { - return queue; + return telemetry.queueForTesting(); } export function _resetForTesting(): void { - queue = []; - clearInterval(flushTimer); - flushTimer = undefined; + telemetry.resetForTesting(); cachedAnonymousId = undefined; + currentDistinctId = ""; identified = false; } diff --git a/integrations/deepseek-plugin/tests/apply.test.ts b/integrations/deepseek-plugin/tests/apply.test.ts index 5c6c413be..797b69695 100644 --- a/integrations/deepseek-plugin/tests/apply.test.ts +++ b/integrations/deepseek-plugin/tests/apply.test.ts @@ -25,15 +25,28 @@ interface RegisteredTool { execute(args: unknown, exec: unknown): Promise; } +type HarnessListener = (...args: any[]) => unknown; + function applyAndCollect(config: Config): Map { const tools = new Map(); const ctx = { tools: { register: (t: RegisteredTool) => tools.set(t.name, t) }, + on: vi.fn(), }; apply(ctx as never, config); return tools; } +function applyAndCollectListeners(config: Config): Map { + const listeners = new Map(); + const ctx = { + tools: { register: vi.fn() }, + on: (event: string, listener: HarnessListener) => listeners.set(event, listener), + }; + apply(ctx as never, config); + return listeners; +} + let savedKey: string | undefined; let savedTelemetry: string | undefined; @@ -68,6 +81,97 @@ describe("apply() config validation", () => { }); }); +describe("Harness lifecycle", () => { + it("automatically recalls memory into the prompt for the latest human message", async () => { + mockSearch.mockResolvedValue({ + results: [{ id: "m1", memory: "Likes tea" }], + }); + const listeners = applyAndCollectListeners({ apiKey: "k", userId: "u" }); + const assemble = listeners.get("system-prompt/assemble")!; + const base = { sections: [], contexts: [], tools: [], variables: {} }; + + const result = await assemble( + base, + { + agent: { + session: { + deriveMessages: () => [ + { + role: "user", + content: [{ type: "text", text: "What do I drink?" }], + source: { kind: "user" }, + }, + ], + }, + }, + }, + async () => base, + ); + + expect(mockSearch).toHaveBeenCalledWith("What do I drink?", { + filters: { user_id: "u" }, + topK: 5, + }); + expect(result).toMatchObject({ + contexts: [{ name: "mem0:recall", text: expect.stringContaining("Likes tea") }], + }); + }); + + it("automatically captures a completed human and assistant turn", async () => { + mockAdd.mockResolvedValue({ eventId: "evt-1", status: "PENDING" }); + const listeners = applyAndCollectListeners({ apiKey: "k", userId: "u" }); + const onSessionEvent = listeners.get("session/event")!; + const session = {}; + + onSessionEvent(session, { type: "turn/start", data: { turn: 1 } }); + onSessionEvent(session, { + type: "user/message", + data: { + role: "user", + content: [{ type: "text", text: "Remember I like tea" }], + source: { kind: "user" }, + }, + }); + onSessionEvent(session, { + type: "assistant/message", + data: { + turn: 1, + message: { + role: "assistant", + content: [{ type: "text", text: "I will remember that." }], + source: { kind: "model" }, + }, + }, + }); + onSessionEvent(session, { + type: "turn/end", + data: { turn: 1, reason: { kind: "completed" } }, + }); + + await vi.waitFor(() => { + expect(mockAdd).toHaveBeenCalledWith( + [ + { role: "user", content: "Remember I like tea" }, + { role: "assistant", content: "I will remember that." }, + ], + { userId: "u", source: "DEEPSEEK_HARNESS" }, + ); + }); + }); + + it("can disable automatic recall and capture without removing the memory tools", () => { + const listeners = applyAndCollectListeners({ + apiKey: "k", + userId: "u", + autoRecall: false, + autoCapture: false, + }); + + expect(listeners.has("system-prompt/assemble")).toBe(false); + expect(listeners.has("session/event")).toBe(false); + }); +}); + describe("search_memory tool", () => { it("returns a formatted list scoped to the configured user", async () => { mockSearch.mockResolvedValue({ @@ -87,7 +191,7 @@ describe("search_memory tool", () => { it("honors a per-call userId override and limit", async () => { mockSearch.mockResolvedValue({ results: [] }); - const tools = applyAndCollect({ apiKey: "k", userId: "u" }); + const tools = applyAndCollect({ apiKey: "k", userId: "u", allowUserOverride: true }); await tools.get("search_memory")!.execute({ query: "x", userId: "alice", limit: 3 }, {}); @@ -136,6 +240,18 @@ describe("add_memory tool", () => { expect(out).toContain("[mem0:m1]"); }); + it("redacts credentials before storing explicit memory", async () => { + mockAdd.mockResolvedValue([]); + const tools = applyAndCollect({ apiKey: "k", userId: "u" }); + + await tools.get("add_memory")!.execute({ text: "api_key=do-not-store-this" }, {}); + + expect(mockAdd).toHaveBeenCalledWith( + [{ role: "user", content: "api_key=[REDACTED]" }], + { userId: "u", source: "DEEPSEEK_HARNESS" }, + ); + }); + it("returns a graceful failure line on error", async () => { mockAdd.mockRejectedValue(new Error("boom")); const tools = applyAndCollect({ apiKey: "k", userId: "u" }); @@ -146,3 +262,13 @@ describe("add_memory tool", () => { expect(out).toContain("boom"); }); }); + +describe("tool user ownership", () => { + it("rejects cross-user reads and writes before contacting Mem0", async () => { + const tools = applyAndCollect({ apiKey: "k", userId: "u" }); + await expect(tools.get("search_memory")!.execute({ query: "x", userId: "other" }, {})).rejects.toThrow(/allowUserOverride/); + await expect(tools.get("add_memory")!.execute({ text: "x", userId: "other" }, {})).rejects.toThrow(/allowUserOverride/); + expect(mockSearch).not.toHaveBeenCalled(); + expect(mockAdd).not.toHaveBeenCalled(); + }); +}); diff --git a/integrations/deepseek-plugin/tests/telemetry.test.ts b/integrations/deepseek-plugin/tests/telemetry.test.ts index d81b2869e..14d77d6eb 100644 --- a/integrations/deepseek-plugin/tests/telemetry.test.ts +++ b/integrations/deepseek-plugin/tests/telemetry.test.ts @@ -31,7 +31,10 @@ interface RegisteredTool { function applyAndCollect(config: Config): Map { const tools = new Map(); - apply({ tools: { register: (t: RegisteredTool) => tools.set(t.name, t) } } as never, config); + apply({ + tools: { register: (t: RegisteredTool) => tools.set(t.name, t) }, + on: vi.fn(), + } as never, config); return tools; } @@ -190,7 +193,7 @@ describe("tool instrumentation", () => { it("records a write with its size but not its text", async () => { mockAdd.mockResolvedValue([{ id: "m1", memory: "Fact" }]); - const tools = applyAndCollect({ apiKey: "k", userId: "u" }); + const tools = applyAndCollect({ apiKey: "k", userId: "u", allowUserOverride: true }); await tools.get("add_memory")!.execute({ text: "secret fact", userId: "alice" }, {}); diff --git a/integrations/deepseek-plugin/tsconfig.json b/integrations/deepseek-plugin/tsconfig.json index 412c13bac..c36f17b65 100644 --- a/integrations/deepseek-plugin/tsconfig.json +++ b/integrations/deepseek-plugin/tsconfig.json @@ -6,7 +6,6 @@ "lib": ["ES2022"], "declaration": true, "outDir": "dist", - "rootDir": "src", "strict": true, "types": ["node"], "esModuleInterop": true, diff --git a/integrations/kimi-plugin/agents/sidekick.md b/integrations/kimi-plugin/agents/sidekick.md new file mode 100644 index 000000000..8032119b0 --- /dev/null +++ b/integrations/kimi-plugin/agents/sidekick.md @@ -0,0 +1,18 @@ +--- +name: sidekick +description: Coding subagent for focused implementation, investigation, testing, debugging, or review work. +whenToUse: Delegate a bounded engineering task that benefits from its own isolated context. +--- + +You are Mem0's coding sidekick. Complete only the bounded task the main agent +delegates to you and return a concise, self-contained result. + +Search Mem0 before work that may depend on prior repository decisions or user +preferences. Inspect the relevant repository rules and code, make changes when +asked, and run the smallest decisive validation. Do not claim Git worktree +isolation: Kimi provides a separate context, while filesystem isolation depends +on the caller's environment. + +Your final response must state the outcome, changed files, validation, and any +remaining risk. Do not commit, push, or open a pull request unless the caller +explicitly asks. diff --git a/integrations/kimi-plugin/core/flush_worker.py b/integrations/kimi-plugin/core/flush_worker.py new file mode 100644 index 000000000..6f7b9ecb2 --- /dev/null +++ b/integrations/kimi-plugin/core/flush_worker.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Detached remote checkpoint worker. + +Claude Code may cancel SessionEnd hooks as a print-mode process exits. The hook +therefore persists its input first and launches this process in a new session. +""" + +from __future__ import annotations + +import json +import os +import sys +import time +from pathlib import Path + +import telemetry +from memory_core import ( + EvidenceStore, + checkpoint_session, + configure_harness, + touch_handoff_heartbeat, +) + + +def main() -> int: + if len(sys.argv) != 2: + return 2 + handoff_path = Path(sys.argv[1]) + os.environ["MEM0_CODE_HANDOFF_PATH"] = str(handoff_path) + harness = os.environ.get("MEM0_PLUGIN_HARNESS") + if harness: + source_tag = os.environ.get("MEM0_PLUGIN_SOURCE_TAG", "") + configure_harness( + harness, + env_prefix=os.environ.get("MEM0_PLUGIN_ENV_PREFIX", ""), + data_dir_name=os.environ.get("MEM0_PLUGIN_DATA_DIR_NAME", ""), + source_tag=source_tag, + ) + telemetry.init(harness=harness, source_tag=source_tag.upper()) + completed = False + try: + payload = json.loads(handoff_path.read_text(encoding="utf-8")) + delay = float(payload.get("delay_seconds") or 0) + if delay > 0: + payload.pop("delay_seconds", None) + temporary = handoff_path.with_suffix(f".{os.getpid()}.tmp") + try: + temporary.write_text(json.dumps(payload), encoding="utf-8") + temporary.replace(handoff_path) + finally: + temporary.unlink(missing_ok=True) + time.sleep(delay) + if not handoff_path.exists(): + return 0 + hook_input = payload.get("hook_input") or {} + reason = str(payload.get("reason") or "checkpoint") + wait_for_inflight = bool(payload.get("wait_for_inflight")) + store = EvidenceStore() + try: + if wait_for_inflight: + session_id = str( + hook_input.get("session_id") or "unknown-session" + ) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + deadline = time.monotonic() + float( + os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120") + ) + while ( + store.has_inflight_flush(repo.identity, session_id) + and time.monotonic() < deadline + ): + touch_handoff_heartbeat() + time.sleep(0.25) + # Hooks capture the conversation before handoff; the worker only flushes it. + result = checkpoint_session(store, hook_input, reason) + print(json.dumps(result, sort_keys=True), flush=True) + completed = result.get("status") in { + "semantic-succeeded", + "explicitly-stored", + "nothing-to-flush", + } + finally: + store.close() + return 0 + finally: + telemetry.flush() + if completed: + try: + handoff_path.unlink() + except OSError: + pass + elif handoff_path.suffix == ".running": + try: + handoff_path.replace(handoff_path.with_suffix(".json")) + except OSError: + pass + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/kimi-plugin/core/hook_runner.py b/integrations/kimi-plugin/core/hook_runner.py new file mode 100644 index 000000000..2a2adb557 --- /dev/null +++ b/integrations/kimi-plugin/core/hook_runner.py @@ -0,0 +1,372 @@ +"""Shared hook orchestration for all Mem0 agent plugins.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import subprocess +import sys +import time +import uuid +from pathlib import Path + +import telemetry +from memory_core import ( + EvidenceStore, + _session_id, + api_key, + bounded, + cache_plugin_api_key, + checkpoint_session, + clear_stale_api_key_cache, + configure_harness, + data_dir, + detached_process_kwargs, + format_context, + harness_config, + record_session_start, + record_tool, + record_user_prompt, + redact, + search_memories, +) + +STALE_RUNNING_SECONDS = 300 +PENDING_EXPIRY_SECONDS = 7 * 24 * 60 * 60 +PENDING_LAUNCH_LIMIT = 5 +DEFAULT_IDLE_FLUSH_SECONDS = 300 + +_core_dir: Path = Path(__file__).resolve().parent + + +def read_hook_input() -> dict: + try: + value = json.load(sys.stdin) + return value if isinstance(value, dict) else {} + except (json.JSONDecodeError, OSError): + return {} + + +def default_record_stop(store: EvidenceStore, hook_input: dict): + """Record the assistant's response without transcript parsing.""" + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + message = redact(hook_input.get("last_assistant_message", "")).strip() + if message: + store.record_assistant_response(repo, session_id, message) + return repo, session_id + + +def first_prompt_memory_output(store: EvidenceStore, hook_input: dict) -> dict: + """Search once before the agent handles the first prompt in a session.""" + repo, session_id, prompt, is_first_prompt = record_user_prompt(store, hook_input) + if not is_first_prompt: + return {} + try: + minimum_query_chars = int(os.environ.get("MEM0_CODE_MIN_QUERY_CHARS", "20")) + except ValueError: + minimum_query_chars = 20 + if len(prompt.strip()) < max(minimum_query_chars, 1): + return {} + result = search_memories( + store, repo, session_id, bounded(prompt, 6000), + top_k=5, operation="first-prompt-search", timeout=2, + ) + if not result.memories: + return {} + context = format_context( + result.memories, + "Mem0 found these relevant memories from earlier work in this repository:", + ) + telemetry.record( + "context_injected", + repo=repo, session_id=session_id, trigger="first-prompt", + memory_count=len(result.memories), context_chars=len(context), + prompt_chars=len(prompt), + ) + return { + "hookSpecificOutput": { + "hookEventName": "UserPromptSubmit", + "additionalContext": context, + }, + } + + +def _launch_handoff(handoff_path: Path) -> bool: + running_path = handoff_path.with_suffix(".running") + try: + handoff_path.replace(running_path) + except OSError: + return False + worker = _core_dir / "flush_worker.py" + log_path = data_dir() / "flush-worker.log" + log_handle = open(log_path, "a", encoding="utf-8") + harness = harness_config() + child_env = os.environ.copy() + child_env.update( + { + "MEM0_CODE_DATA_DIR": str(data_dir()), + "MEM0_PLUGIN_HARNESS": harness["name"], + "MEM0_PLUGIN_ENV_PREFIX": harness["env_prefix"], + "MEM0_PLUGIN_DATA_DIR_NAME": harness["data_dir_name"], + "MEM0_PLUGIN_SOURCE_TAG": harness["source_tag"], + } + ) + try: + subprocess.Popen( + [sys.executable, str(worker), str(running_path)], + stdin=subprocess.DEVNULL, + stdout=log_handle, stderr=log_handle, + close_fds=True, + env=child_env, + **detached_process_kwargs(), + ) + finally: + log_handle.close() + return True + + +def recover_pending_handoffs() -> int: + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + now = time.time() + for running in pending_dir.glob("*.running"): + try: + if now - running.stat().st_mtime > STALE_RUNNING_SECONDS: + running.replace(running.with_suffix(".json")) + except OSError: + continue + recoverable = [] + for handoff in pending_dir.glob("*.json"): + try: + age = now - handoff.stat().st_mtime + except OSError: + continue + if age > PENDING_EXPIRY_SECONDS: + handoff.unlink(missing_ok=True) + continue + recoverable.append((age, handoff)) + recoverable.sort(key=lambda item: item[0], reverse=True) + launched = 0 + for _, handoff in recoverable[:PENDING_LAUNCH_LIMIT]: + launched += int(_launch_handoff(handoff)) + return launched + + +def refresh_pending_handoffs() -> None: + pending_dir = data_dir() / "pending" + if not pending_dir.is_dir(): + return + for pattern in ("*.json", "*.running"): + for handoff in pending_dir.glob(pattern): + try: + os.utime(handoff) + except OSError: + continue + + +def hand_off_flush( + hook_input: dict, reason: str, *, wait_for_inflight: bool = False, +) -> None: + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + material = ( + f"{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}\0{reason}" + ) + digest = hashlib.sha256(material.encode()).hexdigest()[:24] + handoff_path = pending_dir / f"{digest}-{uuid.uuid4().hex[:8]}.json" + temporary_path = handoff_path.with_suffix(".tmp") + temporary_path.write_text( + json.dumps({ + "hook_input": hook_input, + "reason": reason, + "wait_for_inflight": wait_for_inflight, + }), + encoding="utf-8", + ) + temporary_path.replace(handoff_path) + _launch_handoff(handoff_path) + + +def automatic_flush_enabled() -> bool: + return os.environ.get("MEM0_CODE_AUTO_FLUSH", "true").lower() in { + "1", "true", "yes", "on", + } + + +def schedule_periodic_checkpoint( + store: EvidenceStore, hook_input: dict, repo, session_id: str, +) -> bool: + if ( + not automatic_flush_enabled() + or not api_key() + or not store.checkpoint_due(repo.identity, session_id) + ): + return False + if store.prepare_flush(repo, session_id, "periodic") is None: + return False + hand_off_flush(hook_input, "periodic") + return True + + +def _idle_flush_seconds() -> int: + try: + return max( + int(os.environ.get("MEM0_CODE_IDLE_FLUSH_SECONDS", str(DEFAULT_IDLE_FLUSH_SECONDS))), + 0, + ) + except ValueError: + return DEFAULT_IDLE_FLUSH_SECONDS + + +def schedule_idle_flush( + store: EvidenceStore, hook_input: dict, repo, session_id: str, +) -> bool: + delay = _idle_flush_seconds() + if delay <= 0 or not automatic_flush_enabled() or not api_key(): + return False + if store.has_inflight_flush(repo.identity, session_id): + return False + if not store.has_unflushed_events(repo.identity, session_id): + return False + pending_dir = data_dir() / "pending" + pending_dir.mkdir(parents=True, exist_ok=True) + material = f"idle\0{hook_input.get('cwd', '')}\0{hook_input.get('session_id', '')}" + digest = hashlib.sha256(material.encode()).hexdigest()[:24] + for old in pending_dir.glob(f"idle-{digest}*"): + old.unlink(missing_ok=True) + handoff_path = pending_dir / f"idle-{digest}-{uuid.uuid4().hex[:8]}.json" + temporary_path = handoff_path.with_suffix(".tmp") + temporary_path.write_text( + json.dumps({ + "hook_input": hook_input, + "reason": "idle", + "delay_seconds": delay, + }), + encoding="utf-8", + ) + temporary_path.replace(handoff_path) + _launch_handoff(handoff_path) + return True + + +def log_failure(exc: Exception) -> None: + try: + log_path = data_dir() / "plugin-errors.log" + with log_path.open("a", encoding="utf-8") as handle: + handle.write(f"{time.time():.3f} {type(exc).__name__}: {exc}\n") + except OSError: + pass + + +def run( + *, + record_stop_fn=None, + extra_actions: dict | None = None, + data_dir_env: str = "MEM0_PLUGIN_DATA_DIR", + automatic_flush_reasons: set | None = None, +) -> int: + if record_stop_fn is None: + record_stop_fn = default_record_stop + if automatic_flush_reasons is None: + automatic_flush_reasons = {"session-end"} + + base_actions = ["session-start", "user-prompt", "post-tool", "stop", "flush"] + all_actions = base_actions + list((extra_actions or {}).keys()) + + parser = argparse.ArgumentParser() + parser.add_argument("action", choices=all_actions) + parser.add_argument("--reason", default="manual") + parser.add_argument("--plugin-data-dir", default="") + parser.add_argument("--harness", default="") + args = parser.parse_args() + + if args.harness: + configure_harness(args.harness) + telemetry.init(harness=args.harness) + + if args.plugin_data_dir: + os.environ[data_dir_env] = args.plugin_data_dir + + cache_plugin_api_key() + if args.action == "session-start": + clear_stale_api_key_cache() + + hook_input = read_hook_input() + store = EvidenceStore() + try: + if store.is_paused(): + if args.action == "session-start": + refresh_pending_handoffs() + telemetry.record("session_start", paused=True) + telemetry.spawn_flush() + return 0 + + if args.action == "session-start": + if telemetry.is_first_run(): + telemetry.record("install") + recovered = recover_pending_handoffs() + record_session_start(store, hook_input) + if recovered: + telemetry.record("handoff_recovered", count=recovered) + telemetry.spawn_flush() + elif args.action == "user-prompt": + output = first_prompt_memory_output(store, hook_input) + if output: + print(json.dumps(output)) + elif args.action == "post-tool": + record_tool(store, hook_input) + elif args.action == "stop": + repo, session_id = record_stop_fn(store, hook_input) + if not schedule_periodic_checkpoint(store, hook_input, repo, session_id): + schedule_idle_flush(store, hook_input, repo, session_id) + elif args.action == "flush": + automatic = args.reason in automatic_flush_reasons + if automatic and not automatic_flush_enabled(): + return 0 + if args.reason == "session-end": + record_stop_fn(store, hook_input) + if os.environ.get("MEM0_CODE_SYNC_FLUSH") == "1": + print(json.dumps(checkpoint_session(store, hook_input, args.reason))) + else: + session_id = str(hook_input.get("session_id") or "unknown-session") + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + already_running = store.has_inflight_flush(repo.identity, session_id) + if already_running and args.reason == "session-end": + hand_off_flush(hook_input, args.reason, wait_for_inflight=True) + elif not already_running and store.prepare_flush( + repo, session_id, args.reason, + ) is not None: + hand_off_flush(hook_input, args.reason) + elif extra_actions and args.action in extra_actions: + result = extra_actions[args.action](store, hook_input) + if result: + print(json.dumps(result)) + finally: + store.close() + return 0 + + +def entry_point( + *, + record_stop_fn=None, + extra_actions: dict | None = None, + data_dir_env: str = "MEM0_PLUGIN_DATA_DIR", + automatic_flush_reasons: set | None = None, +) -> None: + try: + raise SystemExit(run( + record_stop_fn=record_stop_fn, + extra_actions=extra_actions, + data_dir_env=data_dir_env, + automatic_flush_reasons=automatic_flush_reasons, + )) + except Exception as exc: + log_failure(exc) + raise SystemExit(0) + + +if __name__ == "__main__": + entry_point() diff --git a/integrations/kimi-plugin/core/mcp_server.py b/integrations/kimi-plugin/core/mcp_server.py new file mode 100644 index 000000000..036fbbdc9 --- /dev/null +++ b/integrations/kimi-plugin/core/mcp_server.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Expose Mem0's memory search as one local coding-agent tool.""" + +from __future__ import annotations + +import json +import os +import sys +from typing import Any + +import telemetry +from memory_core import ( + CODING_MEMORY_CATEGORY_NAMES, + PLUGIN_VERSION, + SEARCH_SCOPES, + format_search_result, + resolve_repo, + search_memories, +) + +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." +) +TOOL_SCHEMA = { + "type": "object", + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 2000, + "description": "A direct question about earlier work in this repository.", + }, + "top_k": { + "type": "integer", + "minimum": 1, + "maximum": 20, + "description": "Maximum memories to return. Uses Mem0's configured default when omitted.", + }, + "category": { + "type": "string", + "enum": list(CODING_MEMORY_CATEGORY_NAMES), + "description": "Optional memory category. Omit to search every category.", + }, + "scope": { + "type": "string", + "enum": list(SEARCH_SCOPES), + "description": ( + "Which memories to search. 'repo' (default) is the whole repository's " + "shared memory plus your own preferences, 'dir' narrows the shared " + "part to the current directory, 'mine' is your preferences alone." + ), + }, + "run_id": { + "type": "string", + "minLength": 1, + "description": ( + "Optional coding-agent session ID. With any scope, restricts results to memories " + "saved in that session. Omit to recall memories across sessions." + ), + }, + }, + "required": ["query"], + "additionalProperties": False, +} + + +class ToolInputError(ValueError): + pass + + +def _validate_arguments( + arguments: Any, +) -> tuple[str, int | None, str | None, str | None, str | None]: + if not isinstance(arguments, dict): + raise ToolInputError("Search arguments must be an object.") + + unknown = set(arguments) - {"query", "top_k", "category", "scope", "run_id"} + if unknown: + raise ToolInputError(f"Unknown search argument: {sorted(unknown)[0]}") + + query = arguments.get("query") + if not isinstance(query, str) or not query.strip(): + raise ToolInputError("query must be a non-empty string.") + query = query.strip() + if len(query) > 2000: + raise ToolInputError("query must be at most 2,000 characters.") + + top_k = arguments.get("top_k") + if top_k is not None and ( + isinstance(top_k, bool) or not isinstance(top_k, int) or not 1 <= top_k <= 20 + ): + raise ToolInputError("top_k must be an integer from 1 to 20.") + + category = arguments.get("category") + if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES: + raise ToolInputError("category must be one of Mem0's supported categories.") + + scope = arguments.get("scope") + if scope is not None and scope not in SEARCH_SCOPES: + raise ToolInputError(f"scope must be one of {list(SEARCH_SCOPES)}.") + + run_id = arguments.get("run_id") + if run_id is not None: + if not isinstance(run_id, str) or not run_id.strip(): + raise ToolInputError("run_id must be a non-empty string.") + run_id = run_id.strip() + + return query, top_k, category, scope, run_id + + +def call_search_memories(arguments: Any, cwd: str | None = None) -> str: + query, top_k, category, scope, run_id = _validate_arguments(arguments) + repo = resolve_repo(cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()) + result = search_memories( + None, + repo, + None, + query, + top_k=top_k, + category=category, + scope=scope, + run_id=run_id, + operation="mcp-search", + ) + return format_search_result(result) + + +def _workspace_cwd(params: dict[str, Any]) -> str | None: + meta = params.get("_meta") + if not isinstance(meta, dict): + return None + metadata = meta.get("x-codex-turn-metadata") + if not isinstance(metadata, dict): + return None + workspaces = metadata.get("workspaces") or {} + if isinstance(workspaces, dict): + return next((path for path in workspaces if isinstance(path, str) and path), None) + return None + + +def _tool_response(text: str, *, is_error: bool = False) -> dict[str, Any]: + return { + "content": [{"type": "text", "text": text}], + "isError": is_error, + } + + +def handle_request(message: Any) -> dict[str, Any] | None: + if not isinstance(message, dict): + return None + request_id = message.get("id") + method = message.get("method") + + if method == "notifications/initialized": + return None + if method == "initialize": + requested = (message.get("params") or {}).get("protocolVersion") + return { + "jsonrpc": "2.0", + "id": request_id, + "result": { + "protocolVersion": requested or PROTOCOL_VERSION, + "capabilities": {"tools": {"listChanged": False}}, + "serverInfo": {"name": "mem0", "version": PLUGIN_VERSION}, + }, + } + if method == "ping": + return {"jsonrpc": "2.0", "id": request_id, "result": {}} + if method == "tools/list": + return { + "jsonrpc": "2.0", + "id": request_id, + "result": { + "tools": [ + { + "name": TOOL_NAME, + "description": TOOL_DESCRIPTION, + "inputSchema": TOOL_SCHEMA, + "annotations": { + "readOnlyHint": True, + "idempotentHint": True, + "openWorldHint": True, + }, + } + ] + }, + } + if method == "tools/call": + params = message.get("params") or {} + if params.get("name") != TOOL_NAME: + result = _tool_response("Unknown Mem0 tool.", is_error=True) + else: + try: + result = _tool_response( + call_search_memories(params.get("arguments"), _workspace_cwd(params)) + ) + except ToolInputError as exc: + result = _tool_response(str(exc), is_error=True) + except Exception: + result = _tool_response("Memory search failed.", is_error=True) + return {"jsonrpc": "2.0", "id": request_id, "result": result} + if request_id is None: + return None + return { + "jsonrpc": "2.0", + "id": request_id, + "error": {"code": -32601, "message": "Method not found"}, + } + + +def main() -> int: + for raw_line in sys.stdin: + try: + message = json.loads(raw_line) + response = handle_request(message) + except json.JSONDecodeError: + response = { + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32700, "message": "Parse error"}, + } + except Exception: + response = { + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32603, "message": "Internal error"}, + } + if response is not None: + sys.stdout.write(json.dumps(response, separators=(",", ":")) + "\n") + sys.stdout.flush() + telemetry.spawn_flush() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/kimi-plugin/core/memory_cli.py b/integrations/kimi-plugin/core/memory_cli.py new file mode 100644 index 000000000..595729feb --- /dev/null +++ b/integrations/kimi-plugin/core/memory_cli.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Mem0 diagnostics and user controls.""" + +from __future__ import annotations + +import argparse +import json +import os + +import telemetry +from memory_core import ( + EvidenceStore, + api_key, + data_dir, + doctor, + forget_remote_repo, + configure_harness, + resolve_repo, + user_id, +) + + +def _print_status(value: dict) -> None: + last = value.get("last_operation") or {} + print(f"Mem0: {'paused' if value['paused'] else 'active'}") + print(f"Repository: {value['repo_id']}") + print(f"Local data: {value['data_dir']}") + print(f"API key: {'configured' if value['api_key_configured'] else 'missing'}") + print( + "Saved on this computer: " + f"{value['events']} session details, {value['flushes']} memory updates" + ) + print( + f"Used in this repository: {value['retrievals']} memories returned, " + f"{value['sidekick_runs']} sidekick runs" + ) + if last: + item_label = "" + if last["operation"] in {"flush", "flush-retry"}: + item_label = f", {last['item_count']} memories" + operation = ( + "memory update" + if last["operation"] in {"flush", "flush-retry"} + else last["operation"].replace("-", " ") + ) + print( + f"Last {operation}: " + f"{'succeeded' if last['success'] else 'failed'} " + f"({last['duration_ms']:.1f} ms{item_label})" + ) + sidekick = value.get("last_sidekick") or {} + if sidekick: + state = "finished" if sidekick.get("stopped_at") else "started" + print( + "Last sidekick: " + f"{state}, received {sidekick['context_chars']} characters of memory, " + f"agent {sidekick['agent_id']}" + ) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--plugin-data-dir", default="") + parser.add_argument("--harness", default="") + subparsers = parser.add_subparsers(dest="command", required=True) + + status = subparsers.add_parser("status") + status.add_argument("--json", action="store_true") + + doctor_parser = subparsers.add_parser("doctor") + doctor_parser.add_argument("--json", action="store_true") + + subparsers.add_parser("pause") + subparsers.add_parser("resume") + + forget = subparsers.add_parser("forget") + forget.add_argument("--remote", action="store_true") + forget.add_argument("--yes", action="store_true") + forget.add_argument("--include-project-memory", action="store_true") + + args = parser.parse_args() + if args.harness: + source_tag = f"{args.harness.replace('-', '_')}_plugin" + configure_harness(args.harness, source_tag=source_tag) + telemetry.init(harness=args.harness, source_tag=source_tag.upper()) + if args.plugin_data_dir: + os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir + store = EvidenceStore() + try: + repo = resolve_repo(os.getcwd()) + telemetry.record("control", repo=repo, action=args.command) + if args.command == "status": + result = { + **store.status(repo.identity), + "repo_id": repo.identity, + "app_id": repo.app_id, + "project_id": repo.project_id, + "directory": repo.directory, + "user_id": user_id(), + "data_dir": str(data_dir()), + "api_key_configured": bool(api_key()), + } + if args.json: + print(json.dumps(result, indent=2, default=str)) + else: + _print_status(result) + elif args.command == "doctor": + result = doctor(os.getcwd()) + if args.json: + print(json.dumps(result, indent=2, default=str)) + else: + for name, check in result["checks"].items(): + print( + f"{'PASS' if check['ok'] else 'FAIL'} {name}: {check['detail']}" + ) + return 0 if result["ok"] else 1 + elif args.command == "pause": + store.set_setting("paused", "true") + print("Mem0 stopped saving and searching memories.") + elif args.command == "resume": + store.set_setting("paused", "false") + print("Mem0 resumed saving and searching memories.") + elif args.command == "forget": + if not args.yes: + print( + "Refusing to delete data without --yes. Add --remote to also " + "delete this user/repository scope from Mem0." + ) + return 2 + remote_result = ( + forget_remote_repo( + repo, include_project_memory=args.include_project_memory + ) + if args.remote + else None + ) + local_result = store.forget_local_repo(repo.identity) + print( + json.dumps( + {"local": local_result, "remote": remote_result}, + indent=2, + default=str, + ) + ) + if remote_result and remote_result.get("status") == "error": + return 1 + finally: + store.close() + telemetry.spawn_flush() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/kimi-plugin/core/memory_core.py b/integrations/kimi-plugin/core/memory_core.py new file mode 100644 index 000000000..cf71196b8 --- /dev/null +++ b/integrations/kimi-plugin/core/memory_core.py @@ -0,0 +1,2645 @@ +#!/usr/bin/env python3 +"""Shared core for Mem0 agent plugins. + +Hooks record small session details locally. When the agent compacts or ends the +session, Mem0 sends the useful parts to the platform so it can create memories. +The agent can search those memories during later work in the repository. +""" + +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import sqlite3 +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Iterable + +import telemetry + +DEFAULT_API_URL = "https://api.mem0.ai" +PLUGIN_VERSION = "0.3.1" + +_harness_name: str = "generic" +_harness_env_prefix: str = "MEM0_PLUGIN" +_harness_data_dir_name: str = "mem0-plugin" +_harness_source_tag: str = "mem0_plugin" + + +def configure_harness( + name: str, + env_prefix: str = "", + data_dir_name: str = "", + source_tag: str = "", +) -> None: + global _harness_name, _harness_env_prefix, _harness_data_dir_name, _harness_source_tag + _harness_name = name + _harness_env_prefix = env_prefix or f"MEM0_{name.upper().replace('-', '_')}" + _harness_data_dir_name = data_dir_name or f"{name}-plugin" + _harness_source_tag = source_tag or f"{name.replace('-', '_')}_plugin" + + +def harness_config() -> dict[str, str]: + return { + "name": _harness_name, + "env_prefix": _harness_env_prefix, + "data_dir_name": _harness_data_dir_name, + "source_tag": _harness_source_tag, + } + + +MAX_COMMAND_CHARS = 2000 +MAX_RESULT_CHARS = 2500 +MAX_EPISODE_CHARS = 12000 +CHECKPOINT_EXCHANGES = 5 +CHECKPOINT_MESSAGES = 10 +CHECKPOINT_SOURCE_CHARS = 40000 +DEFAULT_MAX_CONTEXT_CHARS = 4000 +MAX_EXTRACTION_INPUT_TOKENS = 24000 +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. + +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 current coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions. + +Write about the repository, not the user, assistant, session, or task. Do not save personal preferences. Do not save a memory that only states which repository, branch, or directory the session worked in. Do not include test results, documentation updates, release notes, or temporary state. + +If nothing useful was established, return no memories.""" + +PERSONAL_MEMORY_INSTRUCTIONS = """Save concise facts about the user that will help in any repository: preferred tools, package managers, languages, coding style, review and communication preferences, and anything the user explicitly asked to be remembered about themselves. + +Write in the third person about the user, not about the repository, the assistant, the session, or the task. Do not save repository facts, project decisions, commands, or what was built. + +Never save that the user has no preferences or that nothing was learned. If nothing was learned about the user, return no memories.""" + +CODING_MEMORY_CATEGORIES = [ + { + "project_knowledge": ( + "What the project is and how its code, APIs, data, files, and " + "components work." + ) + }, + { + "decisions_and_constraints": ( + "Why an approach was chosen, what must remain true, and rules future " + "work must follow." + ) + }, + { + "workflows": ( + "How to run, test, debug, deploy, configure, or otherwise work on the " + "project." + ) + }, + { + "problems_and_fixes": ( + "Bugs, failures, known pitfalls, their causes, and how to fix or avoid " + "them." + ) + }, + { + "results": ( + "Outcomes and measurements from tests, benchmarks, experiments, or " + "investigations." + ) + }, +] +CODING_MEMORY_CATEGORY_NAMES = tuple( + category_name + for category in CODING_MEMORY_CATEGORIES + for category_name in category +) + +TEST_COMMAND_RE = re.compile( + r"(?:^|\s)(?:pytest|py\.test|jest|vitest|go\s+test|cargo\s+test|" + r"npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|" + r"mvn\s+test|gradle\s+test|make\s+test)(?:\s|$)", + re.IGNORECASE, +) +BUILD_COMMAND_RE = re.compile( + r"(?:^|\s)(?:npm|pnpm|yarn)\s+(?:run\s+)?build(?:\s|$)|" + r"(?:^|\s)(?:cargo|go|mvn|gradle|make)\s+build(?:\s|$)", + re.IGNORECASE, +) + +SECRET_PATTERNS = [ + re.compile(r"(?i)(authorization\s*[:=]\s*(?:bearer|token)\s+)[^\s\"']+"), + re.compile( + r"(?i)((?:api[_-]?key|secret[_-]?access[_-]?key|session[_-]?token)\s*[:=]\s*)[^\s\"']+" + ), + re.compile( + r"(?i)((?:access[_-]?token|refresh[_-]?token|password|credential)" + r"\s*[:=]\s*)[^\s&\"']+" + ), + re.compile(r"\b(?:sk|m0|mem0_sk|psk)-[A-Za-z0-9_\-]{12,}\b"), + re.compile(r"\b(?:ASIA|AKIA)[A-Z0-9]{12,}\b"), + re.compile(r"\b(?:ghp_|github_pat_|xox[baprs]-)[A-Za-z0-9_\-]{12,}\b"), + re.compile( + r"-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----", + re.DOTALL, + ), + re.compile( + r'(?i)("(?:api[_-]?key|password|secret(?:[_-]?access[_-]?key)?' + r'|(?:access|refresh|session)[_-]?token|token|authorization|credential' + r')"\s*:\s*")(?:\\.|[^"\\])*' + ), +] + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def redact(value: Any) -> str: + text = ( + value + if isinstance(value, str) + else json.dumps(value, ensure_ascii=False, default=str) + ) + for pattern in SECRET_PATTERNS: + if pattern.groups: + text = pattern.sub(r"\1[REDACTED]", text) + else: + text = pattern.sub("[REDACTED]", text) + return text + + +def bounded(value: Any, limit: int) -> str: + text = redact(value).strip() + if len(text) <= limit: + return text + return text[:limit] + f"\n...[truncated {len(text) - limit} chars]" + + +def _git(cwd: str, *args: str) -> str: + try: + result = subprocess.run( + ["git", "-C", cwd, *args], + check=False, + capture_output=True, + text=True, + timeout=0.5, + ) + except (OSError, subprocess.TimeoutExpired): + return "" + return result.stdout.strip() if result.returncode == 0 else "" + + +def _normalize_remote(remote: str) -> str: + remote = remote.strip() + if remote.startswith("git@") and ":" in remote: + host_path = remote[4:].replace(":", "/", 1) + remote = f"https://{host_path}" + if remote.endswith(".git"): + remote = remote[:-4] + if "://" in remote: + parsed = urllib.parse.urlsplit(remote) + hostname = parsed.hostname or "" + if parsed.port: + hostname = f"{hostname}:{parsed.port}" + remote = urllib.parse.urlunsplit( + (parsed.scheme, hostname, parsed.path, parsed.query, parsed.fragment) + ) + return remote.rstrip("/") + + +_WILDCARD_SCOPE = re.compile(r"^\*+$") + + +def _scope_value(raw: str | None) -> str: + """Reject wildcards as identities: they are filter syntax and would widen the scope.""" + value = (raw or "").strip() + return "" if _WILDCARD_SCOPE.match(value) else value + + +SEARCH_SCOPES = ("repo", "dir", "mine") +DEFAULT_SEARCH_SCOPE = "repo" + +def directory_app_id(repo: RepoContext) -> str: + """The app_id of the directory this session runs in: the repository at the root, repository/path below it.""" + return f"{repo.app_id}/{repo.directory}" if repo.directory else repo.app_id + + +def directory_chain(repo: RepoContext) -> list[str]: + """Every directory a memory belongs to, from the top-level folder down to the one it was written in.""" + parts = repo.directory.split("/") if repo.directory else [] + return ["/".join(parts[: index + 1]) for index in range(len(parts))] + + +def _shared_project_ids(repo: RepoContext) -> list[str]: + """Current and pre-upgrade namespaces, shared by recall and explicit deletion.""" + if not repo.identity.startswith("local:") and repo.project_id != repo.app_id: + return [repo.project_id, repo.app_id] + return [repo.project_id] + + +def _search_filters(user: str, repo: RepoContext, scope: str) -> dict[str, Any]: + """Build the scope filter: app_id scopes to the repo, then union shared and personal lanes.""" + app_scope = {"app_id": repo.app_id} + mine = {"AND": [{"user_id": user}, app_scope]} + if scope == "mine": + return mine + projects = [{"AND": [{"agent_id": project_id}, app_scope]} for project_id in _shared_project_ids(repo)] + shared: dict[str, Any] = projects[0] if len(projects) == 1 else {"OR": projects} + if scope == "dir" and repo.directory: + shared = {"AND": [shared, {"metadata": {"dirs": {"contains": repo.directory}}}]} + return {"OR": [shared, mine]} + + +def search_scope() -> str: + configured = ( + _plugin_option("search_scope", "MEM0_CODE_SEARCH_SCOPE") or "" + ).strip().lower() + return configured if configured in SEARCH_SCOPES else DEFAULT_SEARCH_SCOPE + + +def resolve_search_scope(scope: str | None) -> str: + value = (scope or search_scope()).strip().lower() + if value not in SEARCH_SCOPES: + raise ValueError(f"Unknown search scope: {value}") + return value + + +def _legacy_project_map(cwd: str, root: str, raw_remote: str) -> str: + """Return the project name used by the previous Claude Code plugin.""" + try: + data = json.loads((Path.home() / ".mem0" / "project_map.json").read_text()) + except (OSError, json.JSONDecodeError): + return "" + if not isinstance(data, dict): + return "" + + keys = list(dict.fromkeys([cwd, root, os.path.realpath(cwd), os.path.realpath(root)])) + if raw_remote: + keys.append(f"remote:{hashlib.sha256(raw_remote.encode()).hexdigest()[:16]}") + for key in keys: + value = data.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + return "" + + +def _legacy_project_id(cwd: str, root: str, raw_remote: str, identity: str) -> str: + """Use the repository namespace created by the previous Mem0 plugin.""" + configured = _scope_value(os.environ.get("MEM0_PROJECT_ID")) + if configured: + return configured + + mapped = _scope_value(_legacy_project_map(cwd, root, raw_remote)) + if mapped: + return mapped + + remote = raw_remote or ("" if identity.startswith("local:") else identity) + remote = remote.strip().removesuffix(".git") + for prefix in ("https://", "http://", "ssh://", "git://"): + if remote.startswith(prefix): + remote = remote[len(prefix) :] + break + else: + remote = re.sub(r"^git@", "", remote) + parts = [part for part in remote.replace(":", "/", 1).split("/") if part] + if len(parts) >= 2: + return f"{parts[-2]}-{parts[-1]}".replace("/", "-").replace(":", "-") + if parts: + return parts[-1].replace("/", "-").replace(":", "-") + return os.path.basename(root or cwd) or "unknown" + + +@dataclass(frozen=True) +class RepoContext: + cwd: str + root: str + identity: str + app_id: str + branch: str + head_sha: str + project_id: str = "" + directory: str = "" + + +def _project_id(root: str, identity: str, app_id: str) -> str: + """The shared namespace: includes a host hash so repos with the same owner/name on different hosts stay apart.""" + if not identity.startswith("local:"): + return f"{app_id}-{hashlib.sha256(identity.encode()).hexdigest()[:10]}" + return f"local-{app_id}-{hashlib.sha256(root.encode()).hexdigest()[:10]}" + + +def _relative_directory(cwd: str, root: str) -> str: + relative = os.path.relpath(cwd, root) + return "" if relative == "." or relative.startswith("..") else relative.replace(os.sep, "/") + + +@dataclass(frozen=True) +class MemorySearchResult: + succeeded: bool + matched_count: int + already_shown_count: int + memories: list[dict[str, Any]] + + +@functools.lru_cache(maxsize=64) +def _resolve_repo_cached(cwd: str) -> RepoContext: + given_cwd = cwd + cwd = os.path.realpath(cwd) + given_root = _git(cwd, "rev-parse", "--show-toplevel") or given_cwd + root = os.path.realpath(given_root) + raw_remote = _git(root, "config", "--get", "remote.origin.url") + remote = _normalize_remote(raw_remote) + identity = remote or f"local:{root}" + app_id = _legacy_project_id(given_cwd, given_root, raw_remote, identity) + return RepoContext( + cwd=cwd, + root=root, + identity=identity, + app_id=app_id, + branch=_git(root, "branch", "--show-current") or "detached", + head_sha=_git(root, "rev-parse", "HEAD"), + project_id=_project_id(root, identity, app_id), + directory=_relative_directory(cwd, root), + ) + + +def resolve_repo(cwd: str | None) -> RepoContext: + return _resolve_repo_cached(os.path.abspath(cwd or os.getcwd())) + + +def api_key() -> str: + configured = ( + os.environ.get("MEM0_API_KEY") + or os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if configured: + return configured + try: + return (data_dir() / "api-key").read_text(encoding="utf-8").strip() + except OSError: + return "" + + +def cache_plugin_api_key() -> bool: + """Bridge host's hook-only sensitive config into plugin-owned storage.""" + configured = ( + os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if not configured: + return False + + directory = data_dir() + directory.mkdir(parents=True, exist_ok=True) + path = directory / "api-key" + temporary = directory / f"api-key.{os.getpid()}.tmp" + descriptor = os.open( + temporary, + os.O_WRONLY | os.O_CREAT | os.O_TRUNC, + 0o600, + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + handle.write(configured) + os.replace(temporary, path) + os.chmod(path, 0o600) + finally: + try: + temporary.unlink() + except FileNotFoundError: + pass + return True + + +def clear_stale_api_key_cache() -> bool: + """Drop the cached key file once every configured key source is gone.""" + configured = ( + os.environ.get("MEM0_API_KEY") + or os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if configured: + return False + path = data_dir() / "api-key" + if not path.exists(): + return False + try: + path.unlink() + except OSError: + return False + return True + + +def detached_process_kwargs(platform: str | None = None) -> dict: + """Keep a spawned worker alive after the coding agent exits, on POSIX and Windows.""" + if (platform or sys.platform) == "win32": + return { + "creationflags": subprocess.DETACHED_PROCESS + | subprocess.CREATE_NEW_PROCESS_GROUP + } + return {"start_new_session": True} + + +def _plugin_option(name: str, fallback: str = "") -> str: + return ( + os.environ.get(f"PLUGIN_OPTION_{name.upper()}") + or os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name.upper()}") + or os.environ.get(fallback) + or "" + ).strip() + + +def user_id() -> str: + return ( + _scope_value(_plugin_option("user_id", "MEM0_CODE_USER_ID")) + or _scope_value(os.environ.get("MEM0_USER_ID")) + or _scope_value(os.environ.get("MEM0_RESOLVED_USER_ID")) + or _scope_value(os.environ.get("USER")) + or _scope_value(os.environ.get("USERNAME")) + or "default" + ) + + +def data_dir() -> Path: + configured = ( + os.environ.get("MEM0_CODE_DATA_DIR") + or os.environ.get("MEM0_PLUGIN_DATA_DIR") + or os.environ.get("PLUGIN_DATA") + or os.environ.get("CLAUDE_PLUGIN_DATA") + ) + return ( + Path(configured).expanduser() if configured else Path.home() / ".mem0" / _harness_data_dir_name + ) + + +def _bool_option(name: str, fallback: str, default: bool = False) -> bool: + value = _plugin_option(name, fallback) + if not value: + return default + return value.lower() in {"1", "true", "yes", "on"} + + +def _int_option(name: str, fallback: str, default: int) -> int: + value = _plugin_option(name, fallback) + try: + return int(value) if value else default + except ValueError: + return default + + + +def _checkpoint_message(event: dict[str, Any]) -> str: + kind = event.get("kind") + payload = event.get("payload") or {} + if kind == "user_prompt": + return redact(payload.get("text", "")).strip() + if kind == "assistant_stop": + transcript_messages = payload.get("transcript_messages") or [] + if isinstance(transcript_messages, list): + text = "\n".join( + str(message.get("content") or "") + for message in transcript_messages + if isinstance(message, dict) and message.get("content") + ) + if text: + return text + return redact(payload.get("text", "")).strip() + if kind == "sidekick_stop": + return redact(payload.get("final_message", "")).strip() + return "" + + +def checkpoint_stats(events: list[dict[str, Any]]) -> tuple[int, int, int]: + """Return completed exchanges, messages, and source characters.""" + completed = sum(event.get("kind") == "assistant_stop" for event in events) + contents = [content for event in events if (content := _checkpoint_message(event))] + return completed, len(contents), sum(len(content) for content in contents) + + +def select_checkpoint_events( + events: list[dict[str, Any]], *, force: bool +) -> list[dict[str, Any]]: + """Select one ordered extraction block without splitting an exchange.""" + for index, event in enumerate(events): + if event.get("kind") != "assistant_stop": + continue + candidate = events[: index + 1] + completed, messages, source_chars = checkpoint_stats(candidate) + if ( + completed >= CHECKPOINT_EXCHANGES + or messages >= CHECKPOINT_MESSAGES + or source_chars >= CHECKPOINT_SOURCE_CHARS + ): + return candidate + return events if force else [] + + +class EvidenceStore: + def __init__(self, path: Path | None = None): + directory = data_dir() if path is None else path.parent + directory.mkdir(parents=True, exist_ok=True) + self.path = path or directory / "evidence.sqlite3" + try: + self._open() + except sqlite3.DatabaseError: + self._quarantine() + self._open() + + def _open(self) -> None: + self.conn = sqlite3.connect(self.path, timeout=10) + self.conn.row_factory = sqlite3.Row + try: + self.conn.execute("PRAGMA journal_mode=WAL") + self.conn.execute("PRAGMA busy_timeout=10000") + self._migrate() + except sqlite3.DatabaseError: + self.conn.close() + raise + + def _quarantine(self) -> None: + """Move an unreadable database aside so capture restarts cleanly.""" + stamp = int(time.time()) + for suffix in ("", "-wal", "-shm"): + source = Path(f"{self.path}{suffix}") + try: + source.replace(f"{self.path}.corrupt-{stamp}{suffix}") + except FileNotFoundError: + continue + except OSError: + try: + source.unlink() + except OSError: + pass + telemetry.record("db_quarantined") + + def close(self) -> None: + self.conn.close() + + def _migrate(self) -> None: + self.conn.executescript( + """ + CREATE TABLE IF NOT EXISTS events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + session_id TEXT NOT NULL, + created_at TEXT NOT NULL, + kind TEXT NOT NULL, + payload_json TEXT NOT NULL, + flush_id TEXT + ); + CREATE INDEX IF NOT EXISTS events_session_idx + ON events(repo_id, session_id, flush_id, id); + + CREATE TABLE IF NOT EXISTS session_scopes ( + session_id TEXT PRIMARY KEY, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + root TEXT NOT NULL, + branch TEXT NOT NULL, + head_sha TEXT NOT NULL, + created_at TEXT NOT NULL, + directory TEXT NOT NULL DEFAULT '' + ); + + CREATE TABLE IF NOT EXISTS flushes ( + packet_id TEXT PRIMARY KEY, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + session_id TEXT NOT NULL, + reason TEXT NOT NULL, + event_start INTEGER NOT NULL, + event_end INTEGER NOT NULL, + status TEXT NOT NULL, + episode_event_id TEXT, + semantic_event_id TEXT, + error TEXT, + attempts INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS retrievals ( + session_id TEXT NOT NULL, + repo_id TEXT NOT NULL, + memory_id TEXT NOT NULL, + injected_at TEXT NOT NULL, + rank INTEGER, + score REAL, + memory_text TEXT, + context_chars INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY(session_id, repo_id, memory_id) + ); + + CREATE TABLE IF NOT EXISTS operations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created_at TEXT NOT NULL, + repo_id TEXT NOT NULL, + session_id TEXT NOT NULL, + operation TEXT NOT NULL, + duration_ms REAL NOT NULL, + success INTEGER NOT NULL, + item_count INTEGER NOT NULL DEFAULT 0, + request_chars INTEGER NOT NULL DEFAULT 0, + response_chars INTEGER NOT NULL DEFAULT 0, + error TEXT + ); + + CREATE TABLE IF NOT EXISTS sidekick_runs ( + repo_id TEXT NOT NULL, + session_id TEXT NOT NULL, + agent_id TEXT NOT NULL, + agent_type TEXT NOT NULL, + started_at TEXT NOT NULL, + stopped_at TEXT, + transcript_path TEXT, + context_chars INTEGER NOT NULL DEFAULT 0, + final_message TEXT, + PRIMARY KEY(repo_id, session_id, agent_id) + ); + CREATE INDEX IF NOT EXISTS sidekick_runs_repo_idx + ON sidekick_runs(repo_id, started_at); + + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + """ + ) + # Remove the pre-0.1.1 no-tools snapshot implementation. The real coding + # sidekick is a native Claude Code agent and stores no state in this DB. + self.conn.executescript( + """ + DROP TABLE IF EXISTS sidekick_calls; + DROP TABLE IF EXISTS sidekick_snapshots; + DROP TABLE IF EXISTS sidekick_state; + DROP TABLE IF EXISTS sidekick_packets; + """ + ) + self._ensure_column("retrievals", "rank", "INTEGER") + self._ensure_column("retrievals", "score", "REAL") + self._ensure_column("retrievals", "memory_text", "TEXT") + self._ensure_column("retrievals", "context_chars", "INTEGER NOT NULL DEFAULT 0") + self._ensure_column("flushes", "attempts", "INTEGER NOT NULL DEFAULT 0") + self._ensure_column("session_scopes", "directory", "TEXT NOT NULL DEFAULT ''") + self.conn.commit() + + def _ensure_column(self, table: str, column: str, declaration: str) -> None: + columns = { + str(row["name"]) + for row in self.conn.execute(f"PRAGMA table_info({table})").fetchall() + } + if column not in columns: + self.conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {declaration}") + + def record_event( + self, + repo: RepoContext, + session_id: str, + kind: str, + payload: dict[str, Any], + ) -> int: + cursor = self.conn.execute( + """INSERT INTO events + (repo_id, app_id, session_id, created_at, kind, payload_json) + VALUES (?, ?, ?, ?, ?, ?)""", + ( + repo.identity, + repo.app_id, + session_id, + utc_now(), + kind, + json.dumps(payload, ensure_ascii=False, sort_keys=True), + ), + ) + self.conn.commit() + return int(cursor.lastrowid) + + def record_assistant_response(self, repo: RepoContext, session_id: str, message: str) -> None: + """Ignore repeated response hooks until another prompt or a different answer arrives.""" + with self.conn: + # Serialize the check and insert across concurrent Stop and SessionEnd hooks. + self.conn.execute("BEGIN IMMEDIATE") + previous = self.conn.execute( + """SELECT kind, payload_json FROM events + WHERE repo_id = ? AND session_id = ? AND kind IN ('user_prompt', 'assistant_stop') + ORDER BY id DESC LIMIT 1""", + (repo.identity, session_id), + ).fetchone() + if ( + previous is not None + and previous["kind"] == "assistant_stop" + and json.loads(previous["payload_json"]).get("text") == message + ): + return + self.record_event(repo, session_id, "assistant_stop", {"text": message}) + + def repo_for_session(self, session_id: str, cwd: str | None) -> RepoContext: + """Keep one project scope for every hook in a coding-agent session.""" + current = resolve_repo(cwd) + if session_id == "unknown-session": + return current + + with self.conn: + self.conn.execute( + """INSERT OR IGNORE INTO session_scopes + (session_id, repo_id, app_id, root, branch, head_sha, created_at, directory) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", + ( + session_id, + current.identity, + current.app_id, + current.root, + current.branch, + current.head_sha, + utc_now(), + current.directory, + ), + ) + scope = self.conn.execute( + "SELECT * FROM session_scopes WHERE session_id = ?", (session_id,) + ).fetchone() + same_git_repo = ( + current.identity == scope["repo_id"] and bool(current.head_sha) + ) + pinned = current if same_git_repo else resolve_repo(str(scope["root"])) + return RepoContext( + cwd=current.cwd, + root=pinned.root, + identity=str(scope["repo_id"]), + app_id=str(scope["app_id"]), + branch=pinned.branch, + head_sha=pinned.head_sha, + project_id=pinned.project_id, + directory=str(scope["directory"] or ""), + ) + + def prepare_flush( + self, repo: RepoContext, session_id: str, reason: str + ) -> tuple[str, list[dict[str, Any]]] | None: + with self.conn: + self.conn.execute("BEGIN IMMEDIATE") + existing = self.conn.execute( + """SELECT * FROM flushes + WHERE repo_id = ? AND session_id = ? + AND status NOT IN ('semantic-succeeded', 'explicitly-stored', 'gave-up') + ORDER BY created_at LIMIT 1""", + (repo.identity, session_id), + ).fetchone() + if existing and int(existing["attempts"] or 0) >= MAX_FLUSH_ATTEMPTS: + self.conn.execute( + "UPDATE flushes SET status = 'gave-up', updated_at = ? WHERE packet_id = ?", + (utc_now(), existing["packet_id"]), + ) + telemetry.record( + "flush", + repo=repo, + session_id=session_id, + reason=reason, + status="gave-up", + success=False, + attempts=int(existing["attempts"] or 0), + ) + existing = None + if existing: + if reason != "periodic" and existing["reason"] == "periodic": + self.conn.execute( + "UPDATE flushes SET reason = ?, updated_at = ? WHERE packet_id = ?", + (reason, utc_now(), existing["packet_id"]), + ) + existing_rows = self.conn.execute( + "SELECT * FROM events WHERE flush_id = ? ORDER BY id", + (existing["packet_id"],), + ).fetchall() + if existing_rows: + return str(existing["packet_id"]), [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in existing_rows + ] + + rows = self.conn.execute( + """SELECT * FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id""", + (repo.identity, session_id), + ).fetchall() + if not rows: + return None + + events = [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in rows + ] + events = select_checkpoint_events(events, force=reason != "periodic") + if not events: + return None + event_start, event_end = events[0]["id"], events[-1]["id"] + packet_material = f"{repo.identity}\0{session_id}\0{event_start}\0{event_end}" + packet_id = hashlib.sha256(packet_material.encode()).hexdigest()[:32] + now = utc_now() + + self.conn.execute( + """INSERT OR IGNORE INTO flushes + (packet_id, repo_id, app_id, session_id, reason, event_start, + event_end, status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, 'prepared', ?, ?)""", + ( + packet_id, + repo.identity, + repo.app_id, + session_id, + reason, + event_start, + event_end, + now, + now, + ), + ) + event_ids = [event["id"] for event in events] + placeholders = ", ".join("?" for _ in event_ids) + self.conn.execute( + f"UPDATE events SET flush_id = ? " + f"WHERE id IN ({placeholders}) AND flush_id IS NULL", + (packet_id, *event_ids), + ) + return packet_id, events + + def checkpoint_due(self, repo_id: str, session_id: str) -> bool: + if self.has_inflight_flush(repo_id, session_id): + return False + rows = self.conn.execute( + """SELECT * FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id""", + (repo_id, session_id), + ).fetchall() + events = [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in rows + ] + return bool(select_checkpoint_events(events, force=False)) + + def has_inflight_flush(self, repo_id: str, session_id: str) -> bool: + return ( + self.conn.execute( + """SELECT 1 FROM flushes + WHERE repo_id = ? AND session_id = ? + AND status IN ('prepared', 'semantic-queued') + LIMIT 1""", + (repo_id, session_id), + ).fetchone() + is not None + ) + + def flush_record(self, packet_id: str) -> dict[str, Any] | None: + row = self.conn.execute( + "SELECT * FROM flushes WHERE packet_id = ?", (packet_id,) + ).fetchone() + return dict(row) if row else None + + def has_unflushed_events(self, repo_id: str, session_id: str) -> bool: + return ( + self.conn.execute( + """SELECT 1 FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + LIMIT 1""", + (repo_id, session_id), + ).fetchone() + is not None + ) + + def unflushed_starts_with_session_start( + self, repo_id: str, session_id: str + ) -> bool: + row = self.conn.execute( + """SELECT kind FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id LIMIT 1""", + (repo_id, session_id), + ).fetchone() + return bool(row and row["kind"] == "session_start") + + def update_flush(self, packet_id: str, **fields: Any) -> None: + allowed = {"status", "episode_event_id", "semantic_event_id", "error"} + updates = {key: value for key, value in fields.items() if key in allowed} + updates["updated_at"] = utc_now() + clause = ", ".join(f"{key} = ?" for key in updates) + failed = str(fields.get("status", "")) in { + "error", + "semantic-failed", + "semantic-timeout", + "semantic-missing", + } + if failed: + clause += ", attempts = attempts + 1" + with self.conn: + self.conn.execute( + f"UPDATE flushes SET {clause} WHERE packet_id = ?", + [*updates.values(), packet_id], + ) + + def unseen( + self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]] + ) -> list[dict[str, Any]]: + seen = { + row["memory_id"] + for row in self.conn.execute( + "SELECT memory_id FROM retrievals WHERE session_id = ? AND repo_id = ?", + (session_id, repo_id), + ) + } + return [memory for memory in memories if str(memory.get("id", "")) not in seen] + + def mark_injected( + self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]] + ) -> None: + now = utc_now() + with self.conn: + for rank, memory in enumerate(memories, start=1): + memory_id = str(memory.get("id", "")) + if memory_id: + memory_text = bounded( + memory.get("memory") or memory.get("text") or "", + 4000, + ) + try: + score = float(memory["score"]) + except (KeyError, TypeError, ValueError): + score = None + self.conn.execute( + """INSERT OR IGNORE INTO retrievals + (session_id, repo_id, memory_id, injected_at, rank, + score, memory_text, context_chars) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", + ( + session_id, + repo_id, + memory_id, + now, + rank, + score, + memory_text, + len(memory_text), + ), + ) + + def injected_memories( + self, session_id: str, repo_id: str + ) -> list[dict[str, Any]]: + """Return the exact memories already supplied to the main conversation.""" + rows = self.conn.execute( + """SELECT memory_id, rank, score, memory_text + FROM retrievals + WHERE session_id = ? AND repo_id = ? + ORDER BY COALESCE(rank, 2147483647), injected_at, memory_id""", + (session_id, repo_id), + ).fetchall() + return [ + { + "id": row["memory_id"], + "memory": row["memory_text"], + "score": row["score"], + } + for row in rows + if row["memory_text"] + ] + + def start_sidekick( + self, + repo: RepoContext, + session_id: str, + agent_id: str, + agent_type: str, + context_chars: int, + ) -> bool: + """Record one native sidekick instance and whether context was first sent.""" + with self.conn: + cursor = self.conn.execute( + """INSERT OR IGNORE INTO sidekick_runs + (repo_id, session_id, agent_id, agent_type, started_at, + context_chars) + VALUES (?, ?, ?, ?, ?, ?)""", + ( + repo.identity, + session_id, + agent_id, + agent_type, + utc_now(), + context_chars, + ), + ) + return int(cursor.rowcount) > 0 + + def stop_sidekick( + self, + repo: RepoContext, + session_id: str, + agent_id: str, + agent_type: str, + transcript_path: str, + final_message: str, + ) -> str: + now = utc_now() + self.conn.execute("BEGIN IMMEDIATE") + try: + if not agent_id: + rows = self.conn.execute( + """SELECT agent_id FROM sidekick_runs + WHERE repo_id = ? AND session_id = ? AND agent_type = ? AND stopped_at IS NULL + LIMIT 2""", + (repo.identity, session_id, agent_type), + ).fetchall() + # Without a host ID, overlapping runs cannot be correlated reliably. + agent_id = rows[0]["agent_id"] if len(rows) == 1 else f"unknown-agent-{time.time_ns()}" + self.conn.execute( + """INSERT INTO sidekick_runs + (repo_id, session_id, agent_id, agent_type, started_at, + stopped_at, transcript_path, final_message) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(repo_id, session_id, agent_id) DO UPDATE SET + stopped_at = excluded.stopped_at, + transcript_path = excluded.transcript_path, + final_message = excluded.final_message""", + ( + repo.identity, + session_id, + agent_id, + agent_type, + now, + now, + bounded(transcript_path, 2000), + redact(final_message).strip(), + ), + ) + self.conn.commit() + except Exception: + self.conn.rollback() + raise + return agent_id + + def operation( + self, + repo: RepoContext, + session_id: str, + operation: str, + duration_ms: float, + success: bool, + *, + item_count: int = 0, + request_chars: int = 0, + response_chars: int = 0, + error: str = "", + ) -> None: + with self.conn: + self.conn.execute( + """INSERT INTO operations + (created_at, repo_id, session_id, operation, duration_ms, + success, item_count, request_chars, response_chars, error) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", + ( + utc_now(), + repo.identity, + session_id, + operation, + duration_ms, + int(success), + item_count, + request_chars, + response_chars, + bounded(error, 1000), + ), + ) + + def has_operation(self, repo_id: str, session_id: str, operation: str) -> bool: + row = self.conn.execute( + """SELECT 1 FROM operations + WHERE repo_id = ? AND session_id = ? AND operation = ? + LIMIT 1""", + (repo_id, session_id, operation), + ).fetchone() + return row is not None + + def has_event(self, repo_id: str, session_id: str, kind: str) -> bool: + row = self.conn.execute( + """SELECT 1 FROM events + WHERE repo_id = ? AND session_id = ? AND kind = ? + LIMIT 1""", + (repo_id, session_id, kind), + ).fetchone() + return row is not None + + def latest_event_payload( + self, repo_id: str, session_id: str, kind: str + ) -> dict[str, Any]: + row = self.conn.execute( + """SELECT payload_json FROM events + WHERE repo_id = ? AND session_id = ? AND kind = ? + ORDER BY id DESC LIMIT 1""", + (repo_id, session_id, kind), + ).fetchone() + if not row: + return {} + try: + payload = json.loads(row["payload_json"]) + except json.JSONDecodeError: + return {} + return payload if isinstance(payload, dict) else {} + + def setting(self, key: str, default: str = "") -> str: + row = self.conn.execute( + "SELECT value FROM settings WHERE key = ?", (key,) + ).fetchone() + return str(row["value"]) if row else default + + def set_setting(self, key: str, value: str) -> None: + with self.conn: + self.conn.execute( + """INSERT INTO settings(key, value, updated_at) + VALUES (?, ?, ?) + ON CONFLICT(key) DO UPDATE SET + value = excluded.value, + updated_at = excluded.updated_at""", + (key, value, utc_now()), + ) + + def is_paused(self) -> bool: + return self.setting("paused", "false").lower() in { + "1", + "true", + "yes", + "on", + } + + def forget_local_repo(self, repo_id: str) -> dict[str, int]: + tables = { + "events": "repo_id", + "session_scopes": "repo_id", + "flushes": "repo_id", + "retrievals": "repo_id", + "operations": "repo_id", + "sidekick_runs": "repo_id", + } + removed: dict[str, int] = {} + with self.conn: + for table, column in tables.items(): + cursor = self.conn.execute( + f"DELETE FROM {table} WHERE {column} = ?", (repo_id,) + ) + removed[table] = max(int(cursor.rowcount), 0) + return removed + + def status(self, repo_id: str) -> dict[str, Any]: + def count(table: str) -> int: + return int( + self.conn.execute( + f"SELECT COUNT(*) FROM {table} WHERE repo_id = ?", (repo_id,) + ).fetchone()[0] + ) + + last_operation = self.conn.execute( + """SELECT created_at, operation, duration_ms, success, item_count, error + FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""", + (repo_id,), + ).fetchone() + last_sidekick = self.conn.execute( + """SELECT session_id, agent_id, agent_type, started_at, stopped_at, + context_chars + FROM sidekick_runs WHERE repo_id = ? + ORDER BY started_at DESC LIMIT 1""", + (repo_id,), + ).fetchone() + return { + "paused": self.is_paused(), + "events": count("events"), + "flushes": count("flushes"), + "retrievals": count("retrievals"), + "sidekick_runs": count("sidekick_runs"), + "last_operation": dict(last_operation) if last_operation else None, + "last_sidekick": dict(last_sidekick) if last_sidekick else None, + } + + +def _session_id(hook_input: dict[str, Any]) -> str: + return str(hook_input.get("session_id") or "unknown-session") + + +def record_session_start(store: EvidenceStore, hook_input: dict[str, Any]) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + store.record_event( + repo, + session_id, + "session_start", + { + "source": hook_input.get("source", "startup"), + "model": bounded(hook_input.get("model", ""), 200), + "branch": repo.branch, + "head_sha": repo.head_sha, + }, + ) + telemetry.record( + "session_start", + repo=repo, + session_id=session_id, + trigger=bounded(str(hook_input.get("source", "startup")), 60), + model=bounded(hook_input.get("model", ""), 200), + api_key_configured=bool(api_key()), + is_git_repo=not repo.identity.startswith("local:"), + ) + + +def record_user_prompt( + store: EvidenceStore, hook_input: dict[str, Any] +) -> tuple[RepoContext, str, str, bool]: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + prompt = redact(hook_input.get("prompt", "")).strip() + is_first_prompt = not store.has_event(repo.identity, session_id, "user_prompt") + store.record_event(repo, session_id, "user_prompt", {"text": prompt}) + return repo, session_id, prompt, is_first_prompt + + +def _tool_result_preview(response: Any) -> str: + if isinstance(response, dict): + selected = {} + for key in ( + "stdout", + "stderr", + "output", + "content", + "error", + "filePath", + "success", + "interrupted", + ): + if key in response: + selected[key] = response[key] + response = selected or {"keys": sorted(response.keys())[:20]} + return bounded(response, MAX_RESULT_CHARS) + + +def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> dict[str, Any]: + name = str(hook_input.get("tool_name") or "unknown") + tool_input = hook_input.get("tool_input") or {} + if not isinstance(tool_input, dict): + tool_input = {} + payload: dict[str, Any] = { + "tool": name, + "failed": failed, + "duration_ms": hook_input.get("duration_ms"), + "agent_role": "sidekick" if hook_input.get("agent_id") else "main", + } + if hook_input.get("agent_id"): + payload["agent_id"] = bounded(hook_input["agent_id"], 200) + if hook_input.get("agent_type"): + payload["agent_type"] = bounded(hook_input["agent_type"], 200) + + if name in {"Read", "Write", "Edit", "MultiEdit", "NotebookEdit"}: + path = tool_input.get("file_path") or tool_input.get("notebook_path") + if path: + payload["path"] = bounded(path, 1000) + if name in {"Write", "Edit", "MultiEdit", "NotebookEdit"}: + payload["mutation_chars"] = sum( + len(str(tool_input.get(key, ""))) + for key in ("content", "new_string", "new_source", "edits") + ) + elif name == "Bash" or "command" in tool_input: + command = bounded(tool_input.get("command", ""), MAX_COMMAND_CHARS) + payload["command"] = command + payload["command_kind"] = ( + "test" + if TEST_COMMAND_RE.search(command) + else "build" + if BUILD_COMMAND_RE.search(command) + else "shell" + ) + response = ( + hook_input.get("error") if failed else hook_input.get("tool_response") + ) + payload["result_preview"] = _tool_result_preview(response) + elif name in {"Grep", "Glob", "WebSearch", "WebFetch"}: + for key in ("pattern", "path", "query", "url"): + if tool_input.get(key): + payload[key] = bounded(tool_input[key], 1000) + else: + payload["input_keys"] = sorted(tool_input.keys())[:20] + if failed: + payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS) + + if failed and "error" not in payload: + payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS) + return payload + + +def record_tool( + store: EvidenceStore, hook_input: dict[str, Any], *, failed: bool | None = False +) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + payload = tool_payload(hook_input, failed=failed) + if payload.get("path"): + payload["repo_path"] = _repo_relative_path(repo, str(payload["path"])) + store.record_event( + repo, + session_id, + "tool_failure" if failed else "tool_result", + payload, + ) + + +def record_sidekick_start( + store: EvidenceStore, hook_input: dict[str, Any], *, inject_context: bool = True +) -> str: + """Record a native sidekick and reuse the main turn's retrieved memories.""" + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200) + agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + context = combine_context( + format_context(store.injected_memories(session_id, repo.identity)) + ) + if not inject_context: + context = "" + first_start = store.start_sidekick( + repo, session_id, agent_id, agent_type, len(context) + ) + store.record_event( + repo, + session_id, + "sidekick_start", + { + "agent_id": agent_id, + "agent_type": agent_type, + "context_chars": len(context) if first_start else 0, + "worktree_root": bounded(repo.root, 2000), + }, + ) + telemetry.record( + "sidekick", + repo=repo, + session_id=session_id, + phase="start", + first_start=first_start, + context_chars=len(context) if first_start else 0, + ) + return context if first_start else "" + + +def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_id = bounded(hook_input.get("agent_id", ""), 200) + final_message = redact(hook_input.get("last_assistant_message", "")).strip() + transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000) + agent_id = store.stop_sidekick( + repo, + session_id, + agent_id, + agent_type, + transcript_path, + final_message, + ) + store.record_event( + repo, + session_id, + "sidekick_stop", + { + "agent_id": agent_id, + "agent_type": agent_type, + "transcript_path": transcript_path, + "final_message": final_message, + }, + ) + telemetry.record( + "sidekick", + repo=repo, + session_id=session_id, + phase="stop", + has_transcript=bool(transcript_path), + message_chars=len(final_message), + ) + + +def _ordered_unique(values: Iterable[str]) -> list[str]: + seen: set[str] = set() + result = [] + for value in values: + if value and value not in seen: + seen.add(value) + result.append(value) + return result + + +def _repo_relative_path(repo: RepoContext, value: str) -> str: + value = str(value or "").strip() + if not value: + return "" + try: + path = Path(value) + if path.is_absolute(): + try: + return path.resolve().relative_to(Path(repo.root).resolve()).as_posix() + except ValueError: + return "" + except (OSError, ValueError): + pass + return bounded(value, 1000) + + +def _render_command_lines(commands: list[dict[str, str]]) -> list[str]: + lines = [] + for command in commands: + line = f"- [{command['status']}/{command['kind']}] {command['command']}" + if command["result"]: + line += f" — {bounded(command['result'], 500).replace(chr(10), ' ')}" + lines.append(line) + return lines + + +def build_episode( + repo: RepoContext, + session_id: str, + packet_id: str, + events: list[dict[str, Any]], + *, + canonical_task: str = "", + task_outcome: str = "", +) -> tuple[str, dict[str, Any]]: + prompts = [ + redact(e["payload"].get("text", "")).strip() + for e in events + if e["kind"] == "user_prompt" and e["payload"].get("text") + ] + assistant_conclusions = [ + redact(e["payload"].get("text", "")).strip() + for e in events + if e["kind"] == "assistant_stop" and e["payload"].get("text") + ] + sidekick_outcomes = [ + redact(e["payload"].get("final_message", "")).strip() + for e in events + if e["kind"] == "sidekick_stop" and e["payload"].get("final_message") + ] + tools = [ + e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"} + and e["payload"].get("agent_role", "main") == "main" + ] + read_paths = _ordered_unique( + _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", ""))) + for t in tools + if t.get("tool") == "Read" + ) + modified_paths = _ordered_unique( + _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", ""))) + for t in tools + if t.get("tool") in {"Write", "Edit", "MultiEdit", "NotebookEdit"} + ) + searches = [ + {key: t[key] for key in ("tool", "pattern", "path", "query", "url") if key in t} + for t in tools + if t.get("tool") in {"Grep", "Glob", "WebSearch", "WebFetch"} + ] + commands = [ + { + "command": t.get("command", ""), + "kind": t.get("command_kind", "shell"), + "status": "unknown" if t.get("failed", False) is None else "failed" if t.get("failed") else "succeeded", + "result": t.get("result_preview", ""), + } + for t in tools + if t.get("command") + ] + + task = bounded(canonical_task or (prompts[0] if prompts else ""), 4000) + conclusion = redact(assistant_conclusions[-1] if assistant_conclusions else "").strip() + outcome = bounded(task_outcome, 2000) + + extraction_messages: list[dict[str, str]] = [] + pending_user_messages: list[dict[str, str]] = [] + if task and not prompts: + pending_user_messages.append({"role": "user", "content": task}) + for event in events: + if event["kind"] == "user_prompt" and event["payload"].get("text"): + pending_user_messages.append( + { + "role": "user", + "content": redact(event["payload"].get("text", "")).strip(), + } + ) + elif event["kind"] == "assistant_stop": + transcript_messages = event["payload"].get("transcript_messages") or [] + if isinstance(transcript_messages, list) and transcript_messages: + transcript_users = { + redact(message.get("content") or "").strip() + for message in transcript_messages + if isinstance(message, dict) and message.get("role") == "user" + } + extraction_messages.extend( + message + for message in pending_user_messages + if message["content"].strip() not in transcript_users + ) + extraction_messages.extend( + { + "role": str(message.get("role") or ""), + "content": redact(message.get("content") or "").strip(), + } + for message in transcript_messages + if isinstance(message, dict) + and message.get("role") in {"user", "assistant"} + and message.get("content") + ) + else: + extraction_messages.extend(pending_user_messages) + if event["payload"].get("text"): + extraction_messages.append( + { + "role": "assistant", + "content": redact(event["payload"].get("text", "")).strip(), + } + ) + pending_user_messages = [] + elif event["kind"] == "sidekick_stop": + pass + extraction_messages.extend(pending_user_messages) + + structured = { + "packet_id": packet_id, + "repo": repo.identity, + "app_id": repo.app_id, + "session_id": session_id, + "branch": repo.branch, + "head_sha": repo.head_sha, + "task": task, + "task_outcome": outcome, + "assistant_conclusion": conclusion, + "user_messages": prompts, + "assistant_outcomes": assistant_conclusions, + "sidekick_outcomes": sidekick_outcomes, + "extraction_messages": extraction_messages, + "files_read": read_paths[:50], + "files_modified": modified_paths[:50], + "searches": searches[-30:], + "commands": commands[-30:], + } + lines = ["Coding-session episode"] + if task: + lines.extend(["", "Task:", task]) + if modified_paths: + lines.extend( + ["", "Files modified:", *[f"- {path}" for path in modified_paths[:50]]] + ) + if read_paths: + lines.extend(["", "Files read:", *[f"- {path}" for path in read_paths[:50]]]) + if commands: + lines.append("") + lines.append("Observed commands:") + lines.extend(_render_command_lines(commands[-30:])) + if searches: + lines.extend( + [ + "", + "Observed searches:", + *[ + f"- {json.dumps(item, ensure_ascii=False, sort_keys=True)}" + for item in searches[-20:] + ], + ] + ) + if conclusion: + lines.extend(["", "Agent conclusion:", conclusion]) + if outcome: + lines.extend(["", "Task outcome:", outcome]) + lines.extend( + [ + "", + f"Provenance: repo={repo.identity}; branch={repo.branch}; head={repo.head_sha}; packet={packet_id}", + ] + ) + content = "\n".join(lines) + return bounded(content, MAX_EPISODE_CHARS), structured + + +def build_semantic_evidence(structured: dict[str, Any]) -> str: + """Format changed paths for memory extraction. + + Test and build results remain in the local evidence store for diagnostics, + but are not useful repository knowledge by default and should not steer + memory extraction toward transient verification details. + """ + modified_paths = [ + bounded(path, 500) for path in structured.get("files_modified", [])[:20] + ] + commands = structured.get("commands") or [] + if not any(command.get("status") == "failed" for command in commands): + commands = [] + + if not modified_paths and not commands: + return "" + + lines = ["Additional repository details from this session"] + if modified_paths: + lines.extend( + [ + "", + "Changed paths:", + *[f"- {path}" for path in modified_paths], + ] + ) + if commands: + lines.extend(["", "Commands run in this session:", *_render_command_lines(commands)]) + return bounded("\n".join(lines), 8000) + + +def build_extraction_messages(structured: dict[str, Any]) -> list[dict[str, str]]: + """Build the session messages sent to Mem0 for memory extraction.""" + evidence = build_semantic_evidence(structured) + messages = [ + {"role": message["role"], "content": redact(message["content"]).strip()} + for message in structured.get("extraction_messages", []) + if message.get("role") in {"user", "assistant"} and message.get("content") + ] + if evidence: + for message in reversed(messages): + if message["role"] == "assistant": + message["content"] = f"{message['content']}\n\n{evidence}" + break + else: + messages.append({"role": "assistant", "content": evidence}) + + return messages + + +def _estimated_tokens(value: str) -> int: + """Conservatively estimate tokens without adding a tokenizer dependency.""" + ascii_chars = sum(ord(char) < 128 for char in value) + return math.ceil((ascii_chars * 0.4) + (len(value) - ascii_chars)) + + +def _message_tokens(messages: list[dict[str, str]]) -> int: + return _estimated_tokens(json.dumps(messages, ensure_ascii=False)) + + +def _is_agent_assignment(message: dict[str, str]) -> bool: + return message.get("role") == "assistant" and message.get( + "content", "" + ).startswith("Subagent assignment (") + + +def _is_agent_response(message: dict[str, str]) -> bool: + return message.get("role") == "assistant" and message.get( + "content", "" + ).startswith("Subagent response (") + + +def extraction_message_batches( + messages: list[dict[str, str]], + *, + max_tokens: int = MAX_EXTRACTION_INPUT_TOKENS, +) -> list[list[dict[str, str]]]: + """Keep exchanges together when possible; split oversized messages to enforce the request budget.""" + if not messages or _message_tokens(messages) <= max_tokens: + return [messages] + + exchanges: list[list[dict[str, str]]] = [] + exchange: list[dict[str, str]] = [] + for message in messages: + if message.get("role") == "user" and exchange: + exchanges.append(exchange) + exchange = [] + exchange.append(message) + if exchange: + exchanges.append(exchange) + + units: list[list[dict[str, str]]] = [] + for exchange in exchanges: + if _message_tokens(exchange) <= max_tokens: + units.append(exchange) + continue + index = 0 + while index < len(exchange): + message = exchange[index] + if ( + _is_agent_assignment(message) + and index + 1 < len(exchange) + and _is_agent_response(exchange[index + 1]) + ): + units.append(exchange[index : index + 2]) + index += 2 + else: + units.append([message]) + index += 1 + + bounded_units: list[list[dict[str, str]]] = [] + for unit in units: + if _message_tokens(unit) <= max_tokens: + bounded_units.append(unit) + continue + for message in unit: + remaining = message["content"] + while remaining: + low, high = 0, len(remaining) + while low < high: + middle = (low + high + 1) // 2 + if _message_tokens([{**message, "content": remaining[:middle]}]) <= max_tokens: + low = middle + else: + high = middle - 1 + if low == 0: + raise ValueError("Extraction token budget cannot fit a message") + bounded_units.append([{**message, "content": remaining[:low]}]) + remaining = remaining[low:] + + batches: list[list[dict[str, str]]] = [] + batch: list[dict[str, str]] = [] + for unit in bounded_units: + candidate = [*batch, *unit] + if batch and _message_tokens(candidate) > max_tokens: + batches.append(batch) + batch = list(unit) + else: + batch = candidate + if batch: + batches.append(batch) + return batches + + +def _request_json( + url: str, key: str, payload: dict[str, Any], timeout: float +) -> tuple[dict[str, Any] | list[Any], int, int]: + raw = json.dumps(payload, ensure_ascii=False).encode() + request = urllib.request.Request( + url, + data=raw, + headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + response_raw = response.read() + parsed = json.loads(response_raw or b"{}") + return parsed, len(raw), len(response_raw) + + +def _request_json_with_network_retry( + url: str, key: str, payload: dict[str, Any], timeout: float +) -> tuple[dict[str, Any] | list[Any], int, int]: + """Retry one transient connection failure without retrying API responses.""" + try: + return _request_json(url, key, payload, timeout) + except urllib.error.HTTPError: + raise + except (urllib.error.URLError, TimeoutError, OSError): + time.sleep(0.25) + return _request_json(url, key, payload, timeout) + + +def _get_json( + url: str, key: str, timeout: float +) -> tuple[dict[str, Any] | list[Any], int]: + request = urllib.request.Request( + url, + headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + method="GET", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + response_raw = response.read() + return json.loads(response_raw or b"{}"), len(response_raw) + + +def _event_id(response: dict[str, Any] | list[Any]) -> str: + return str(response.get("event_id", "")) if isinstance(response, dict) else "" + + +def _stored_event_ids(value: Any) -> list[str]: + raw = str(value or "") + if not raw.startswith("["): + return [] + try: + parsed = json.loads(raw) + except json.JSONDecodeError: + return [] + return [str(item or "") for item in parsed] if isinstance(parsed, list) else [] + + +def _result_count(response: dict[str, Any] | list[Any]) -> int: + if isinstance(response, dict): + results = response.get("results") + return len(results) if isinstance(results, list) else 0 + return len(response) if isinstance(response, list) else 0 + + +def touch_handoff_heartbeat() -> None: + """Mark the worker's handoff file alive so recovery does not relaunch it.""" + path = os.environ.get("MEM0_CODE_HANDOFF_PATH", "") + if not path: + return + try: + os.utime(path) + except OSError: + pass + + +def _wait_for_event(api_url: str, key: str, event_id: str) -> tuple[str, int, int]: + """Wait for extraction to finish before a later task can search the store.""" + if not event_id: + return "MISSING", 0, 0 + wait_seconds = float(os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120")) + poll_seconds = max(float(os.environ.get("MEM0_CODE_EVENT_POLL_SECONDS", "1")), 0.1) + deadline = time.monotonic() + wait_seconds + response_chars = 0 + while time.monotonic() < deadline: + touch_handoff_heartbeat() + try: + response, size = _get_json( + f"{api_url}/v1/event/{event_id}/", + key, + min(10, poll_seconds + 5), + ) + except urllib.error.HTTPError as exc: + if exc.code not in {408, 429} and exc.code < 500: + raise + time.sleep(poll_seconds) + continue + except (urllib.error.URLError, TimeoutError, OSError): + # The extraction job is durable server-side. A transient polling + # failure must not discard a job that may still complete normally. + time.sleep(poll_seconds) + continue + response_chars += size + status = ( + str(response.get("status", "UNKNOWN")) + if isinstance(response, dict) + else "UNKNOWN" + ) + if status in {"SUCCEEDED", "FAILED"}: + return status, response_chars, _result_count(response) + time.sleep(poll_seconds) + return "TIMEOUT", response_chars, 0 + + +def _record_flush( + repo: RepoContext, + session_id: str, + reason: str, + status: str, + elapsed: float, + **extra: Any, +) -> None: + telemetry.record( + "flush", + repo=repo, + session_id=session_id, + reason=reason, + status=status, + success=status in {"semantic-succeeded", "nothing-to-flush"}, + duration_ms=round(elapsed, 2), + **extra, + ) + + +def flush_session( + store: EvidenceStore, hook_input: dict[str, Any], reason: str +) -> dict[str, Any]: + key = api_key() + if not key: + telemetry.record("flush", reason=reason, status="local-only", success=False) + return {"status": "local-only", "reason": "no-api-key"} + + session_id = _session_id(hook_input) + if session_id == "unknown-session": + telemetry.record("flush", reason=reason, status="no-session-id", success=False) + return {"status": "error", "reason": "no-session-id"} + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + prepared = store.prepare_flush(repo, session_id, reason) + if prepared is None: + return {"status": "nothing-to-flush"} + packet_id, events = prepared + existing_flush = store.flush_record(packet_id) or {} + + _, structured = build_episode( + repo, + session_id, + packet_id, + events, + canonical_task=bounded(hook_input.get("task", ""), 4000), + task_outcome=bounded(hook_input.get("task_outcome", ""), 2000), + ) + + metadata = {"source": _harness_source_tag} + if repo.branch and repo.branch not in {"detached", "unknown"}: + metadata["branch"] = repo.branch + if repo.head_sha: + metadata["git_sha"] = repo.head_sha + api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + add_url = f"{api_url}/v3/memories/add/" + + write_user = _scope_value(user_id()) + write_project = _scope_value(repo.project_id) + if not write_user or not _scope_value(repo.app_id) or not write_project: + telemetry.record("flush", reason=reason, status="unscoped", success=False) + return {"status": "error", "reason": "wildcard-scope"} + + body = { + "agent_id": write_project, + "user_id": write_user, + "app_id": repo.app_id, + "run_id": session_id, + "metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)}, + "agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS, + "custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS, + "custom_categories": CODING_MEMORY_CATEGORIES, + "infer": True, + } + + started = time.perf_counter() + try: + stored_events = _stored_event_ids(existing_flush.get("semantic_event_id")) + existing_event = ( + "" if stored_events else str(existing_flush.get("semantic_event_id") or "") + ) + if existing_event: + existing_status, existing_resp, existing_items = _wait_for_event( + api_url, key, existing_event + ) + if existing_status == "SUCCEEDED": + elapsed = (time.perf_counter() - started) * 1000 + store.update_flush( + packet_id, + status="semantic-succeeded", + semantic_event_id=existing_event, + error="", + ) + store.operation( + repo, + session_id, + "flush-retry", + elapsed, + True, + item_count=existing_items, + response_chars=existing_resp, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-succeeded", + elapsed, + memory_count=existing_items, + resumed=True, + ) + effective_reason = str( + (store.flush_record(packet_id) or {}).get("reason") or reason + ) + if ( + store.has_unflushed_events(repo.identity, session_id) + and not store.unflushed_starts_with_session_start( + repo.identity, session_id + ) + and ( + effective_reason != "periodic" + or store.checkpoint_due(repo.identity, session_id) + ) + ): + return flush_session(store, hook_input, effective_reason) + return { + "status": "semantic-succeeded", + "packet_id": packet_id, + "semantic_event_id": existing_event, + "semantic_status": existing_status, + "memory_count": existing_items, + "duration_ms": round(elapsed, 2), + "resumed": True, + } + if existing_status == "TIMEOUT": + elapsed = (time.perf_counter() - started) * 1000 + error = "semantic extraction event timed out" + store.update_flush(packet_id, status="semantic-timeout", error=error) + store.operation( + repo, + session_id, + "flush-retry", + elapsed, + False, + response_chars=existing_resp, + error=error, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-timeout", + elapsed, + resumed=True, + error_kind="timeout", + ) + return { + "status": "semantic-timeout", + "packet_id": packet_id, + "semantic_event_id": existing_event, + "duration_ms": round(elapsed, 2), + "resumed": True, + } + + message_batches = [ + batch + for batch in extraction_message_batches( + build_extraction_messages(structured) + ) + if batch + ] + batches = [(body, messages) for messages in message_batches] + if not batches: + store.update_flush(packet_id, status="semantic-succeeded", error="") + return {"status": "nothing-to-flush", "packet_id": packet_id} + operation_name = "flush-retry" if stored_events else "flush" + semantic_events = stored_events[: len(batches)] + semantic_events += [""] * (len(batches) - len(semantic_events)) + semantic_req = 0 + semantic_resp = 0 + for index, (body, messages) in enumerate(batches): + if semantic_events[index]: + continue + semantic_response, request_chars, response_chars = _request_json( + add_url, + key, + {**body, "messages": messages}, + 15, + ) + semantic_events[index] = _event_id(semantic_response) + semantic_req += request_chars + semantic_resp += response_chars + store.update_flush( + packet_id, + status="semantic-queued", + semantic_event_id=json.dumps(semantic_events), + ) + + semantic_event = semantic_events[-1] + semantic_status = "SUCCEEDED" + event_resp = 0 + semantic_items = 0 + failed_event = semantic_event + for index, queued_event in enumerate(semantic_events): + status, response_chars, item_count = _wait_for_event( + api_url, key, queued_event + ) + event_resp += response_chars + semantic_items += item_count + if status != "SUCCEEDED": + semantic_status = status + failed_event = queued_event + if status in {"FAILED", "MISSING"}: + semantic_events[index] = "" + store.update_flush( + packet_id, semantic_event_id=json.dumps(semantic_events) + ) + break + if semantic_status != "SUCCEEDED": + elapsed = (time.perf_counter() - started) * 1000 + error = f"semantic extraction event {semantic_status.lower()}" + store.update_flush( + packet_id, status=f"semantic-{semantic_status.lower()}", error=error + ) + store.operation( + repo, + session_id, + operation_name, + elapsed, + False, + item_count=semantic_items, + request_chars=semantic_req, + response_chars=semantic_resp + event_resp, + error=error, + ) + _record_flush( + repo, + session_id, + reason, + f"semantic-{semantic_status.lower()}", + elapsed, + memory_count=semantic_items, + batch_count=len(batches), + error_kind=telemetry.error_kind(error), + ) + return { + "status": f"semantic-{semantic_status.lower()}", + "packet_id": packet_id, + "semantic_event_id": failed_event, + "memory_count": semantic_items, + "duration_ms": round(elapsed, 2), + } + + elapsed = (time.perf_counter() - started) * 1000 + store.update_flush( + packet_id, + status="semantic-succeeded", + semantic_event_id=json.dumps(semantic_events), + error="", + ) + store.operation( + repo, + session_id, + operation_name, + elapsed, + True, + item_count=semantic_items, + request_chars=semantic_req, + response_chars=semantic_resp + event_resp, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-succeeded", + elapsed, + memory_count=semantic_items, + batch_count=len(batches), + request_chars=semantic_req, + ) + effective_reason = str( + (store.flush_record(packet_id) or {}).get("reason") or reason + ) + if ( + store.has_unflushed_events(repo.identity, session_id) + and not store.unflushed_starts_with_session_start( + repo.identity, session_id + ) + and ( + effective_reason != "periodic" + or store.checkpoint_due(repo.identity, session_id) + ) + ): + return flush_session(store, hook_input, effective_reason) + return { + "status": "semantic-succeeded", + "packet_id": packet_id, + "semantic_event_id": semantic_event, + "semantic_status": semantic_status, + "memory_count": semantic_items, + "duration_ms": round(elapsed, 2), + } + except Exception as exc: # hooks must fail open + elapsed = (time.perf_counter() - started) * 1000 + error = bounded(str(exc), 1000) + store.update_flush(packet_id, status="error", error=error) + store.operation(repo, session_id, "flush", elapsed, False, error=error) + _record_flush( + repo, + session_id, + reason, + "error", + elapsed, + error_kind=telemetry.error_kind(exc), + ) + return {"status": "error", "packet_id": packet_id, "error": error} + + +def checkpoint_session( + store: EvidenceStore, hook_input: dict[str, Any], reason: str +) -> dict[str, Any]: + """Run remote extraction at a durable boundary.""" + return flush_session(store, hook_input, reason) + + + +def search_memories( + store: EvidenceStore | None, + repo: RepoContext, + session_id: str | None, + query: str, + *, + top_k: int | None = None, + category: str | None = None, + scope: str | None = None, + run_id: str | None = None, + operation: str = "search", + timeout: float = 5, +) -> MemorySearchResult: + key = api_key() + if not key or not query.strip(): + return MemorySearchResult(False, 0, 0, []) + search_once = os.environ.get( + "MEM0_CODE_SEARCH_ONCE_PER_SESSION", "false" + ).lower() in { + "1", + "true", + "yes", + "on", + } + track_session = store is not None and bool(session_id) + if ( + search_once + and track_session + and store.has_operation(repo.identity, session_id, "search") + ): + return MemorySearchResult(False, 0, 0, []) + + result_limit = min( + max( + top_k + if top_k is not None + else _int_option("top_k", "MEM0_CODE_TOP_K", 3), + 1, + ), + 20, + ) + if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES: + raise ValueError(f"Unknown memory category: {category}") + user, project = _scope_value(user_id()), _scope_value(repo.project_id) + if not user or not project or not _scope_value(repo.app_id): + return MemorySearchResult(False, 0, 0, []) + filters = _search_filters(user, repo, resolve_search_scope(scope)) + if category: + filters = {"AND": [filters, {"categories": {"contains": category}}]} + if run_id: + filters = {"AND": [filters, {"run_id": run_id}]} + payload = { + "query": query, + "app_id": repo.app_id, + "filters": filters, + "top_k": result_limit, + "rerank": False, + "latest_only": True, + } + url = ( + os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + + "/v3/memories/search/" + ) + started = time.perf_counter() + try: + response, request_chars, response_chars = _request_json_with_network_retry( + url, key, payload, timeout + ) + memories = ( + response if isinstance(response, list) else response.get("results", []) + ) + memories = [ + memory + for memory in memories + if isinstance(memory, dict) + and (memory.get("metadata") or {}).get("record_kind") != "task_episode" + ][:result_limit] + if track_session: + returned_memories = store.unseen(session_id, repo.identity, memories) + store.mark_injected(session_id, repo.identity, returned_memories) + already_shown_count = len(memories) - len(returned_memories) + else: + returned_memories = memories + already_shown_count = 0 + elapsed = (time.perf_counter() - started) * 1000 + if track_session: + store.operation( + repo, + session_id, + operation, + elapsed, + True, + item_count=len(returned_memories), + request_chars=request_chars, + response_chars=response_chars, + ) + telemetry.record( + "search", + repo=repo, + session_id=session_id, + trigger=operation, + success=True, + duration_ms=round(elapsed, 2), + matched_count=len(memories), + returned_count=len(returned_memories), + already_shown_count=already_shown_count, + top_k=result_limit, + has_category=bool(category), + ) + return MemorySearchResult( + succeeded=True, + matched_count=len(memories), + already_shown_count=already_shown_count, + memories=returned_memories, + ) + except Exception as exc: + elapsed = (time.perf_counter() - started) * 1000 + if track_session: + store.operation(repo, session_id, operation, elapsed, False, error=str(exc)) + telemetry.record( + "search", + repo=repo, + session_id=session_id, + trigger=operation, + success=False, + duration_ms=round(elapsed, 2), + top_k=result_limit, + has_category=bool(category), + error_kind=telemetry.error_kind(exc), + ) + return MemorySearchResult(False, 0, 0, []) + + +def format_context( + memories: list[dict[str, Any]], + heading: str = "Relevant repository memories:", +) -> str: + if not memories: + return "" + limit = min( + max( + _int_option( + "max_context_chars", + "MEM0_CODE_MAX_CONTEXT_CHARS", + DEFAULT_MAX_CONTEXT_CHARS, + ), + 1000, + ), + 10000, + ) + lines = [heading] if heading else [] + for memory in memories: + text = re.sub( + r"\s+", + " ", + redact(memory.get("memory") or memory.get("text") or ""), + ) + text = text.strip() + if not text: + continue + branch = str((memory.get("metadata") or {}).get("branch") or "").strip() + branch_label = ( + f" [learnt on branch {branch}]" + if branch.casefold() not in {"", "main", "master", "unknown", "detached"} + else "" + ) + number = len(lines) if heading else len(lines) + 1 + entry = f"{number}. {text}{branch_label}" + candidate = "\n".join([*lines, entry]) + if len(candidate) <= limit: + lines.append(entry) + continue + if not lines or (heading and len(lines) == 1): + prefix = f"{number}. " + suffix = f"…{branch_label}" + available = ( + limit + - len("\n".join(lines)) + - (1 if lines else 0) + - len(prefix) + - len(suffix) + ) + if available > 0: + lines.append(prefix + text[:available].rstrip() + suffix) + break + minimum_lines = 2 if heading else 1 + return "\n".join(lines) if len(lines) >= minimum_lines else "" + + +def format_search_result(result: MemorySearchResult) -> str: + """Return only the text the coding agent needs from an explicit memory search.""" + if not result.succeeded: + return "Memory search failed." + if result.memories: + rendered = format_context(result.memories, heading="") + if rendered: + return rendered + return "No matching memories found." + + +def combine_context(*contexts: str) -> str: + """Combine memory sources under one hard budget without repeated lines.""" + seen: set[str] = set() + lines: list[str] = [] + for context in contexts: + for line in str(context or "").splitlines(): + normalized = re.sub(r"\s+", " ", line).strip().casefold() + if not normalized or normalized in seen: + continue + seen.add(normalized) + lines.append(line.rstrip()) + limit = min( + max( + _int_option( + "max_context_chars", + "MEM0_CODE_MAX_CONTEXT_CHARS", + DEFAULT_MAX_CONTEXT_CHARS, + ), + 1000, + ), + 10000, + ) + return bounded("\n".join(lines), limit) if lines else "" + + +def _scoped_memory_ids( + api_url: str, key: str, user: str, repo: RepoContext, include_project: bool +) -> list[str]: + """List this user's memory ids for this repository, plus the shared project memory when asked.""" + ids: list[str] = [] + seen: set[str] = set() + prefix = repo.app_id + _collect_memory_ids( + api_url, key, {"user_id": user}, ids, seen, + app_id_prefix=prefix, + ) + if include_project: + for project_id in _shared_project_ids(repo): + _collect_memory_ids( + api_url, key, {"agent_id": project_id}, ids, seen, + app_id_prefix=prefix, + ) + return ids + + +def _collect_memory_ids( + api_url: str, + key: str, + filters: dict[str, Any], + ids: list[str], + seen: set[str], + *, + app_id_prefix: str = "", +) -> None: + """Page through one list filter; the list endpoint returns nothing for an OR whose user branch has no memories.""" + payload = {"filters": filters} + for page in range(1, FORGET_MAX_PAGES + 1): + parsed, _, _ = _request_json( + f"{api_url}/v2/memories/?page={page}&page_size={FORGET_PAGE_SIZE}", + key, + payload, + 15, + ) + items = parsed.get("results") if isinstance(parsed, dict) else parsed + if not isinstance(items, list) or not items: + break + for item in items: + if not isinstance(item, dict): + continue + memory_id = str(item.get("id", "")) + if not memory_id or memory_id in seen: + continue + if app_id_prefix: + item_app_id = str(item.get("app_id") or "") + if item_app_id != app_id_prefix and not item_app_id.startswith(app_id_prefix + "/"): + continue + seen.add(memory_id) + ids.append(memory_id) + if len(items) < FORGET_PAGE_SIZE: + break + + +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"}, + method="DELETE", + ) + try: + with urllib.request.urlopen(request, timeout=15): + return True + except Exception: + return False + + +def forget_remote_repo( + repo: RepoContext, *, include_project_memory: bool = False +) -> dict[str, Any]: + """Delete this user's memories for this repository; project memory is shared, so only on request.""" + key = api_key() + if not key: + telemetry.record("forget", repo=repo, success=False, error_kind="no-api-key") + return {"status": "error", "error": "Mem0 API key is not configured"} + user = _scope_value(user_id()) + if not user or not _scope_value(repo.app_id) or not _scope_value(repo.project_id): + telemetry.record("forget", repo=repo, success=False, error_kind="unscoped") + return { + "status": "error", + "error": "Refusing to forget: the user or repository scope is a wildcard", + } + api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + try: + memory_ids = _scoped_memory_ids(api_url, key, user, repo, include_project_memory) + except Exception as exc: + telemetry.record( + "forget", repo=repo, success=False, error_kind=telemetry.error_kind(exc) + ) + return {"status": "error", "error": bounded(str(exc), 1000)} + deleted = sum(_delete_memory(api_url, key, memory_id) for memory_id in memory_ids) + failed = len(memory_ids) - deleted + telemetry.record("forget", repo=repo, success=not failed, item_count=deleted) + if failed: + return { + "status": "partial", + "deleted": deleted, + "failed": failed, + "error": f"{failed} of {len(memory_ids)} memories could not be deleted", + } + return {"status": "deleted", "deleted": deleted} + + +def _doctor_mem0_authentication(repo: RepoContext) -> dict[str, Any]: + """Verify the configured key with one read-only, repository-scoped search.""" + key = api_key() + if not key: + return {"ok": False, "detail": "API key missing"} + payload = { + "query": "Mem0 authentication check", + "filters": { + "AND": [ + {"user_id": user_id()}, + {"app_id": repo.app_id}, + ] + }, + "top_k": 1, + "threshold": 1.0, + "rerank": False, + } + url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + started = time.perf_counter() + try: + _request_json(f"{url}/v3/memories/search/", key, payload, 5) + except Exception as exc: + return {"ok": False, "detail": bounded(str(exc), 300)} + elapsed = (time.perf_counter() - started) * 1000 + return {"ok": True, "detail": f"connected ({elapsed:.0f} ms)"} + + +def _doctor_user_id() -> dict[str, Any]: + """Flag a configured user ID the plugin refuses, since the silent fallback surprises people.""" + configured = _plugin_option("user_id", "MEM0_CODE_USER_ID") or os.environ.get( + "MEM0_USER_ID", "" + ) + if configured and not _scope_value(configured): + return { + "ok": False, + "detail": f"configured user_id {configured!r} is a wildcard; using {user_id()!r}", + } + return {"ok": True, "detail": user_id()} + + +def doctor(cwd: str | None = None) -> dict[str, Any]: + repo = resolve_repo(cwd) + directory = data_dir() + directory.mkdir(parents=True, exist_ok=True) + checks: dict[str, dict[str, Any]] = { + "python": { + "ok": tuple(sys.version_info[:2]) >= (3, 10), + "detail": f"{sys.version_info.major}.{sys.version_info.minor}", + }, + "data_directory": { + "ok": os.access(directory, os.W_OK), + "detail": str(directory), + }, + "mem0_api_key": { + "ok": bool(api_key()), + "detail": "configured" if api_key() else "missing", + }, + "repository": { + "ok": bool(repo.identity), + "detail": repo.identity, + }, + "user_id": _doctor_user_id(), + "mem0_authentication": _doctor_mem0_authentication(repo), + } + return { + "ok": all(bool(value["ok"]) for value in checks.values()), + "plugin_version": PLUGIN_VERSION, + "repo_id": repo.identity, + "app_id": repo.app_id, + "user_id": user_id(), + "checks": checks, + } diff --git a/integrations/kimi-plugin/core/telemetry.py b/integrations/kimi-plugin/core/telemetry.py new file mode 100644 index 000000000..249595475 --- /dev/null +++ b/integrations/kimi-plugin/core/telemetry.py @@ -0,0 +1,397 @@ +#!/usr/bin/env python3 +"""Anonymous usage telemetry for Mem0 agent plugins. + +Hooks run on a 3-6 second budget and fire on every tool call, so recording never +touches the network: `record` appends one JSON line to a local spool and returns. +A detached `python3 telemetry.py` drains the spool in one batched PostHog request, +started once per session and again from the flush worker that is already detached. + +Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false. + +Never sends prompts, memory text, queries, file paths, repository names, or API +keys: only event names, durations, counts, coarse outcomes, and salted hashes. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import platform +import subprocess +import sys +import time +import urllib.error +import urllib.request +import uuid +from pathlib import Path +from typing import Any + +import memory_core + +_harness: str = "generic" +_source_tag: str = "MEM0_PLUGIN" +_PRIVATE_KEYS = { + "apikey", + "authorization", + "password", + "query", + "secret", + "prompt", + "token", + "text", + "memory", + "message", + "error", + "path", + "cwd", + "userid", + "agentid", + "runid", + "repoid", + "repositoryid", + "projectid", + "appid", + "filters", +} + + +def init(harness: str = "generic", source_tag: str = "") -> None: + global _harness, _source_tag + _harness = harness + _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN" + +POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" +POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/" +POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/" +EVENT_PREFIX = "code" +SPOOL_LIMIT_BYTES = 256 * 1024 +BATCH_SIZE = 100 +SEND_TIMEOUT = 5 +CLAIM_STALE_SECONDS = 120 +CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60 + + +def is_enabled() -> bool: + """Whether telemetry is switched on for this process.""" + return os.environ.get("MEM0_TELEMETRY", "true").strip().lower() not in { + "false", + "0", + "no", + "off", + } + + +def _digest(value: str, length: int = 16) -> str: + return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length] + + +def _safe_value(value: Any) -> Any: + if isinstance(value, str): + return memory_core.redact(value) + if isinstance(value, dict): + return { + key: _safe_value(item) + for key, item in value.items() + if "".join(character for character in str(key).lower() if character.isalnum()) + not in _PRIVATE_KEYS + } + if isinstance(value, (list, tuple)): + return [_safe_value(item) for item in value] + if value is None or isinstance(value, (bool, int, float)): + return value + return memory_core.redact(value) + + +def _spool_path() -> Path: + return memory_core.data_dir() / "telemetry.jsonl" + + +def _identity_path() -> Path: + return memory_core.data_dir() / "telemetry-identity.json" + + +def _read_identity() -> dict[str, str]: + try: + value = json.loads(_identity_path().read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {} + return value if isinstance(value, dict) else {} + + +def _write_identity(identity: dict[str, str]) -> None: + path = _identity_path() + temporary = path.with_suffix(f".{os.getpid()}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + temporary.write_text(json.dumps(identity), encoding="utf-8") + temporary.replace(path) + except OSError: + try: + temporary.unlink() + except OSError: + pass + + +def anonymous_id(identity: dict[str, str] | None = None) -> str: + """Per-machine anonymous identifier, created and persisted on first use.""" + identity = _read_identity() if identity is None else identity + existing = identity.get("anonymous_id") + if existing: + return existing + created = f"code-anon-{uuid.uuid4().hex}" + identity["anonymous_id"] = created + _write_identity(identity) + return created + + +def is_first_run() -> bool: + """Whether this machine has never recorded a plugin event before.""" + return not _identity_path().exists() + + +def record( + event: str, + *, + repo: Any = None, + session_id: str | None = None, + **properties: Any, +) -> None: + """Append one event to the local spool. Never blocks and never raises.""" + if not is_enabled(): + return + try: + spool = _spool_path() + try: + if spool.stat().st_size > SPOOL_LIMIT_BYTES: + return + except OSError: + pass + properties = _safe_value(properties) + properties.update( + harness=_harness, + plugin_version=memory_core.PLUGIN_VERSION, + os=sys.platform, + python_version=platform.python_version(), + ) + if repo is not None: + properties["repo_hash"] = _digest(getattr(repo, "identity", "")) + if session_id: + properties["session_hash"] = _digest(session_id) + line = json.dumps( + { + "event": f"{EVENT_PREFIX}.{event}", + "timestamp": memory_core.utc_now(), + "properties": { + key: value for key, value in properties.items() if value is not None + }, + }, + separators=(",", ":"), + default=str, + ) + spool.parent.mkdir(parents=True, exist_ok=True) + with spool.open("a", encoding="utf-8") as handle: + handle.write(line + "\n") + except Exception: + pass + + +def error_kind(exc: BaseException | str) -> str: + """Coarse, content-free label for a failure, safe to send.""" + text = exc if isinstance(exc, str) else f"{type(exc).__name__}: {exc}" + lowered = text.lower() + if "timed out" in lowered or "timeout" in lowered: + return "timeout" + if "401" in lowered or "403" in lowered or "unauthor" in lowered or "forbidden" in lowered: + return "auth" + if "429" in lowered or "rate limit" in lowered: + return "rate-limited" + if any(code in lowered for code in ("500", "502", "503", "504")): + return "server-error" + if "400" in lowered or "422" in lowered: + return "bad-request" + if isinstance(exc, str): + return "other" + if isinstance(exc, urllib.error.URLError): + return "network" + return type(exc).__name__ + + +def spawn_flush() -> bool: + """Start the detached sender that drains the spool.""" + if not is_enabled(): + return False + try: + if not _spool_path().exists() and not any( + memory_core.data_dir().glob("telemetry-*.sending") + ): + return False + subprocess.Popen( + [sys.executable, str(Path(__file__).resolve())], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + close_fds=True, + **memory_core.detached_process_kwargs(), + ) + return True + except Exception: + return False + + +def _claim_spool() -> Path | None: + """Rename the spool aside so exactly one sender owns each batch.""" + directory = memory_core.data_dir() + claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending" + spool = _spool_path() + try: + spool.replace(claim) + return claim + except OSError: + pass + now = time.time() + for orphan in sorted(directory.glob("telemetry-*.sending")): + try: + age = now - orphan.stat().st_mtime + except OSError: + continue + if age > CLAIM_EXPIRY_SECONDS: + try: + orphan.unlink() + except OSError: + pass + continue + if age < CLAIM_STALE_SECONDS: + continue + try: + orphan.replace(claim) + return claim + except OSError: + continue + return None + + +def _resolve_email(key: str) -> str: + """Trade the API key for the account email so events join other Mem0 surfaces.""" + url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/" + request = urllib.request.Request( + url, headers={"Authorization": f"Token {key}", "Content-Type": "application/json"} + ) + try: + with urllib.request.urlopen(request, timeout=SEND_TIMEOUT) as response: + payload = json.loads(response.read().decode("utf-8")) + except Exception: + return "" + email = payload.get("user_email") if isinstance(payload, dict) else "" + return email if isinstance(email, str) else "" + + +def _post(payload: dict[str, Any], url: str) -> bool: + request = urllib.request.Request( + url, + data=json.dumps(payload, default=str).encode("utf-8"), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=SEND_TIMEOUT): + return True + except Exception: + return False + + +def resolve_distinct_id() -> tuple[str, str]: + """Return the PostHog distinct id and the anonymous id it replaced, if any.""" + identity = _read_identity() + email = identity.get("email", "") + if email: + return email, "" + key = memory_core.api_key() + if not key: + return anonymous_id(identity), "" + email = _resolve_email(key) + if not email: + return anonymous_id(identity), "" + previous = identity.get("anonymous_id", "") + identity["email"] = email + _write_identity(identity) + return email, previous + + +def flush() -> int: + """Drain claimed spools to PostHog and return the number of events sent.""" + if not is_enabled(): + return 0 + claim = _claim_spool() + if claim is None: + return 0 + try: + lines = claim.read_text(encoding="utf-8").splitlines() + except OSError: + return 0 + events = [] + for line in lines: + try: + value = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(value, dict) and value.get("event"): + events.append(value) + if not events: + try: + claim.unlink() + except OSError: + pass + return 0 + + distinct_id, aliased_anonymous_id = resolve_distinct_id() + if aliased_anonymous_id: + _post( + { + "api_key": POSTHOG_API_KEY, + "event": "$identify", + "distinct_id": distinct_id, + "properties": { + "$anon_distinct_id": aliased_anonymous_id, + "$lib": "posthog-python", + }, + }, + POSTHOG_CAPTURE_URL, + ) + + sent = 0 + for start in range(0, len(events), BATCH_SIZE): + batch = [ + { + "event": event["event"], + "distinct_id": distinct_id, + "timestamp": event.get("timestamp"), + "properties": { + "source": _source_tag, + "language": "python", + "$process_person_profile": False, + "$lib": "posthog-python", + **(event.get("properties") or {}), + }, + } + for event in events[start : start + BATCH_SIZE] + ] + if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL): + return sent + sent += len(batch) + try: + claim.unlink() + except OSError: + pass + return sent + + +def main() -> int: + flush() + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except Exception: + raise SystemExit(0) diff --git a/integrations/kimi-plugin/hooks/adapter.py b/integrations/kimi-plugin/hooks/adapter.py new file mode 100644 index 000000000..3a16b52d3 --- /dev/null +++ b/integrations/kimi-plugin/hooks/adapter.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Translate Kimi Code hooks into the shared Mem0 runtime.""" + +from __future__ import annotations + +import contextlib +import io +import json +import os +import sys +import uuid +from pathlib import Path + +HERE = Path(__file__).resolve() +BUNDLED_CORE = HERE.parent.parent / "core" +CORE = BUNDLED_CORE if BUNDLED_CORE.is_dir() else HERE.parents[2] / "core" / "python" +sys.path.insert(0, str(CORE)) + +import hook_runner # noqa: E402 +import telemetry # noqa: E402 +from memory_core import configure_harness, record_sidekick_start, record_sidekick_stop, record_tool # noqa: E402 + +EVENTS = { + "SessionStart": ["session-start"], + "UserPromptSubmit": ["user-prompt"], + "PostToolUse": ["post-tool"], + "PostToolUseFailure": ["post-tool-failure"], + "Stop": ["stop"], + "PreCompact": ["flush", "--reason", "pre-compact"], + "SessionEnd": ["flush", "--reason", "session-end"], + "SubagentStart": ["sidekick-start"], + "SubagentStop": ["sidekick-stop"], +} + + +def _session_dir(session_id: str) -> Path | None: + home = Path(os.environ.get("KIMI_CODE_HOME", Path.home() / ".kimi-code")).expanduser() + found = None + try: + with (home / "session_index.jsonl").open(encoding="utf-8") as index: + for line in index: + try: + entry = json.loads(line) + except json.JSONDecodeError: + continue + if entry.get("sessionId") == session_id and isinstance(entry.get("sessionDir"), str): + found = Path(entry["sessionDir"]) + except OSError: + pass + if found: + return found + if not session_id or Path(session_id).name != session_id: + return None + return next((path for path in (home / "sessions").glob(f"*/{session_id}") if path.is_dir()), None) + + +def _last_assistant_message(transcript: Path) -> str: + message = "" + step_id = None + parts = [] + try: + lines = transcript.read_text(encoding="utf-8").splitlines() + except OSError: + return "" + for line in lines: + try: + record = json.loads(line) + except json.JSONDecodeError: + continue + if record.get("type") != "context.append_loop_event" or not isinstance(record.get("event"), dict): + continue + event = record["event"] + if event.get("type") == "step.begin": + step_id = event.get("uuid") + parts = [] + elif event.get("type") == "content.part" and event.get("stepUuid") == step_id: + part = event.get("part") + if isinstance(part, dict) and part.get("type") == "text" and isinstance(part.get("text"), str): + parts.append(part["text"]) + elif event.get("type") == "step.end" and event.get("uuid") == step_id: + if event.get("finishReason") not in {"error", "interrupted"} and parts: + message = "".join(parts) + step_id = None + parts = [] + return message + + +def normalize(payload: dict) -> dict: + value = dict(payload) + if "tool_output" in value: + value.setdefault("tool_response", value["tool_output"]) + if "error" in value: + value.setdefault("tool_response", value["error"]) + if "response" in value: + value.setdefault("last_assistant_message", value["response"]) + if "agent_name" in value: + value.setdefault("agent_type", value["agent_name"]) + if value.get("hook_event_name") == "Stop": + session = _session_dir(str(value.get("session_id") or "")) + transcript = session / "agents" / "main" / "wire.jsonl" if session else None + if transcript and transcript.is_file(): + value.setdefault("transcript_path", str(transcript)) + if message := _last_assistant_message(transcript): + value.setdefault("last_assistant_message", message) + return value + + +def _sidekick_start(store, payload): + payload = dict(payload) + payload.setdefault("agent_id", f"kimi-{uuid.uuid4().hex}") + context = record_sidekick_start(store, payload) + return {"hookSpecificOutput": {"additionalContext": context}} if context else None + + +def _sidekick_stop(store, payload): + record_sidekick_stop(store, payload) + + +def main() -> int: + if len(sys.argv) != 2 or sys.argv[1] not in EVENTS: + return 2 + event = sys.argv[1] + try: + raw = json.load(sys.stdin) + except (json.JSONDecodeError, OSError): + raw = {} + sys.argv = [sys.argv[0], *EVENTS[event]] + sys.stdin = io.StringIO(json.dumps(normalize(raw if isinstance(raw, dict) else {}))) + configure_harness("kimi", data_dir_name="kimi-plugin", source_tag="kimi_plugin") + telemetry.init(harness="kimi", source_tag="KIMI_PLUGIN") + output = io.StringIO() + with contextlib.redirect_stdout(output): + result = hook_runner.run( + extra_actions={ + "post-tool-failure": lambda store, payload: record_tool(store, payload, failed=True), + "sidekick-start": _sidekick_start, + "sidekick-stop": _sidekick_stop, + }, + automatic_flush_reasons={"session-end", "pre-compact"}, + ) + if event in {"UserPromptSubmit", "SubagentStart"} and (raw_output := output.getvalue().strip()): + parsed = json.loads(raw_output) + context = parsed.get("hookSpecificOutput", {}).get("additionalContext", "") + if context: + print(context) + return result + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except Exception as exc: + hook_runner.log_failure(exc) + raise SystemExit(0) from None diff --git a/integrations/kimi-plugin/kimi.plugin.json b/integrations/kimi-plugin/kimi.plugin.json new file mode 100644 index 000000000..062a783ee --- /dev/null +++ b/integrations/kimi-plugin/kimi.plugin.json @@ -0,0 +1,32 @@ +{ + "name": "mem0", + "version": "0.3.1", + "description": "Cross-session memory and token savings for coding agents.", + "keywords": ["memory", "coding-agents", "continual-learning", "token-efficiency"], + "author": { "name": "Mem0", "email": "support@mem0.ai" }, + "homepage": "https://docs.mem0.ai/integrations/kimi", + "license": "Apache-2.0", + "interface": { + "displayName": "Mem0", + "shortDescription": "Cross-session memory for Kimi Code" + }, + "skills": "./skills/", + "agents": "./agents/", + "mcpServers": { + "mem0": { + "command": "python3", + "args": ["./core/mcp_server.py"] + } + }, + "hooks": [ + { "event": "SessionStart", "command": "python3 ./hooks/adapter.py SessionStart", "timeout": 5 }, + { "event": "UserPromptSubmit", "command": "python3 ./hooks/adapter.py UserPromptSubmit", "timeout": 6 }, + { "event": "PostToolUse", "matcher": ".*", "command": "python3 ./hooks/adapter.py PostToolUse", "timeout": 3 }, + { "event": "PostToolUseFailure", "matcher": ".*", "command": "python3 ./hooks/adapter.py PostToolUseFailure", "timeout": 3 }, + { "event": "Stop", "command": "python3 ./hooks/adapter.py Stop", "timeout": 3 }, + { "event": "PreCompact", "command": "python3 ./hooks/adapter.py PreCompact", "timeout": 5 }, + { "event": "SessionEnd", "command": "python3 ./hooks/adapter.py SessionEnd", "timeout": 5 }, + { "event": "SubagentStart", "matcher": "^sidekick$", "command": "python3 ./hooks/adapter.py SubagentStart", "timeout": 5 }, + { "event": "SubagentStop", "matcher": "^sidekick$", "command": "python3 ./hooks/adapter.py SubagentStop", "timeout": 5 } + ] +} diff --git a/integrations/kimi-plugin/plugin-build.json b/integrations/kimi-plugin/plugin-build.json new file mode 100644 index 000000000..021a03a80 --- /dev/null +++ b/integrations/kimi-plugin/plugin-build.json @@ -0,0 +1,13 @@ +{ + "id": "mem0", + "version": "0.3.1", + "homepage": "https://docs.mem0.ai/integrations/kimi", + "native": { + "pluginRoot": "${KIMI_PLUGIN_ROOT}", + "files": { + "kimi.plugin.json": "kimi.plugin.json", + "hooks/adapter.py": "hooks/adapter.py", + "agents/sidekick.md": "agents/sidekick.md" + } + } +} diff --git a/integrations/kimi-plugin/skills/forget/SKILL.md b/integrations/kimi-plugin/skills/forget/SKILL.md new file mode 100644 index 000000000..f4709793e --- /dev/null +++ b/integrations/kimi-plugin/skills/forget/SKILL.md @@ -0,0 +1,26 @@ +--- +name: forget +description: Delete the Mem0 memories stored for this repository and this user. Use when the user asks to forget, clear, wipe, or delete memories. +disable-model-invocation: true +--- + +# Forget this repository's memories + +This permanently deletes remote memories. Before running anything, tell the +user exactly what will be deleted: their own memories for this repository +only. The repository's project memory is shared by everyone who works in it, +so it stays unless the user explicitly asks to delete that too. + +After the user confirms, run: + +```bash +python3 "${KIMI_PLUGIN_ROOT}/core/memory_cli.py" --harness "kimi" forget --remote --yes +``` + +If the user also asked to delete the repository's shared project memory, add +`--include-project-memory` and say that this removes it for every teammate. + +Report what the command output says was deleted. If the user only wants local +data cleared (evidence log, pending queue), run the same command without +`--remote`. Never pass `--yes` before the user has confirmed in this +conversation. diff --git a/integrations/kimi-plugin/skills/pause/SKILL.md b/integrations/kimi-plugin/skills/pause/SKILL.md new file mode 100644 index 000000000..9f217a468 --- /dev/null +++ b/integrations/kimi-plugin/skills/pause/SKILL.md @@ -0,0 +1,20 @@ +--- +name: pause +description: Pause Mem0 memory capture on this machine. Use when the user wants to stop memories being recorded, for example for private work or experiments. +disable-model-invocation: true +--- + +# Pause memory capture + +To pause (hooks stop capturing and sending session content; a minimal +anonymous telemetry ping still fires at session start unless +`MEM0_TELEMETRY=false`): + +```bash +python3 "${KIMI_PLUGIN_ROOT}/core/memory_cli.py" --harness "kimi" pause +``` + +Confirm the new state back to the user, and remind them that already-created +memories still exist and remain searchable. Pending unsent packets are held +while paused, not expired, and are delivered after resuming. To turn capture +back on, use `/mem0:resume`. diff --git a/integrations/kimi-plugin/skills/remember/SKILL.md b/integrations/kimi-plugin/skills/remember/SKILL.md new file mode 100644 index 000000000..7be5fc9be --- /dev/null +++ b/integrations/kimi-plugin/skills/remember/SKILL.md @@ -0,0 +1,21 @@ +--- +name: remember +description: Acknowledge a "remember this" request and make sure it is captured well. Use when the user explicitly asks to remember, note, or save something for future sessions. +disable-model-invocation: true +--- + +# Remember something for future sessions + +Mem0 creates memories from the session automatically — there is no separate +write command. When the user asks to remember something: + +1. Restate the fact clearly and completely in your reply, in one or two + sentences, including any names, values, or paths it depends on. Your visible + reply is what memory extraction reads, so a precise restatement is what gets + remembered. +2. Tell the user it will be saved with this session's memories when the session + ends or compacts, and that it will surface in future sessions in this + repository (they can check later with /mem0:search). + +Do not invent a storage confirmation or a memory ID — creation happens in the +background after the session. diff --git a/integrations/kimi-plugin/skills/resume/SKILL.md b/integrations/kimi-plugin/skills/resume/SKILL.md new file mode 100644 index 000000000..7dd91be96 --- /dev/null +++ b/integrations/kimi-plugin/skills/resume/SKILL.md @@ -0,0 +1,19 @@ +--- +name: resume +description: Resume Mem0 memory capture after it was paused with /mem0:pause. +disable-model-invocation: true +--- + +# Resume memory capture + +Resume memory capture for this machine. + +Run: + +```bash +python3 "${KIMI_PLUGIN_ROOT}/core/memory_cli.py" --harness "kimi" resume +``` + +Confirm to the user that capture is active again. New sessions record evidence and +create memories as normal; nothing that happened while paused is retroactively +captured. diff --git a/integrations/kimi-plugin/skills/search/SKILL.md b/integrations/kimi-plugin/skills/search/SKILL.md new file mode 100644 index 000000000..eb92a6ca8 --- /dev/null +++ b/integrations/kimi-plugin/skills/search/SKILL.md @@ -0,0 +1,28 @@ +--- +name: search +description: Search memories from earlier Kimi 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. +argument-hint: "[question] [--top-k number] [--category category-name] [--scope repo|dir|mine] [--run-id session-id]" +disable-model-invocation: true +--- + +# Search memories + +Call `search_memories` with the user's question. Treat `--top-k`, `--category`, +`--scope`, and `--run-id` as tool arguments instead of including them in the +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. + +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 +monorepo), `mine` for your own preferences alone. + +Pass `run_id` with any scope to retrieve memories saved in a specific coding-agent +session. Omit `run_id` to search across sessions. It filters the memories returned; +it does not identify the session making the search request. Use a known session ID, +never invent one. Return the tool's result directly. diff --git a/integrations/kimi-plugin/skills/status/SKILL.md b/integrations/kimi-plugin/skills/status/SKILL.md new file mode 100644 index 000000000..165c0c675 --- /dev/null +++ b/integrations/kimi-plugin/skills/status/SKILL.md @@ -0,0 +1,23 @@ +--- +name: status +description: Show whether Mem0 memory is working in this repository, covering configuration, capture state, pending flushes, and whether the Mem0 API key is valid. Use when the user asks whether memory is on, why a memory is missing, or anything looks broken. +disable-model-invocation: false +--- + +# Memory status + +Run both commands and report the combined result in plain language: + +```bash +python3 "${KIMI_PLUGIN_ROOT}/core/memory_cli.py" --harness "kimi" status --json +python3 "${KIMI_PLUGIN_ROOT}/core/memory_cli.py" --harness "kimi" doctor +``` + +Summarize, using only fields the JSON actually reports: whether capture is +active or paused, the user ID and repository scope (`repo_id`), whether an +API key is configured, the event/flush/retrieval counts (`flushes` is the +number of completed flushes, not a pending count), and the doctor check +results. If doctor reports an authentication failure (401 / invalid key), say +clearly that the Mem0 API key is invalid or expired and that memories are NOT +being created. Never report an auth failure as "no memories found". Suggest +reinstalling with `--config api_key=...` in that case. diff --git a/integrations/kimi-plugin/tests/test_kimi.py b/integrations/kimi-plugin/tests/test_kimi.py new file mode 100644 index 000000000..ec93be86c --- /dev/null +++ b/integrations/kimi-plugin/tests/test_kimi.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import importlib.util +import json +import sys +from pathlib import Path + +HOST = Path(__file__).resolve().parents[1] +CORE_ROOT = HOST.parent / "agent-plugin-core" +sys.path.insert(0, str(CORE_ROOT)) + +from build.build import build # noqa: E402 + +SPEC = importlib.util.spec_from_file_location("kimi_adapter", HOST / "hooks" / "adapter.py") +assert SPEC and SPEC.loader +adapter = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(adapter) + + +def _write_kimi_session(home: Path, session_id: str, records: list[dict]) -> Path: + session = home / "sessions" / "wd_mem0_deadbeef1234" / session_id + transcript = session / "agents" / "main" / "wire.jsonl" + transcript.parent.mkdir(parents=True) + transcript.write_text("\n".join(json.dumps(record) for record in records) + "\n", encoding="utf-8") + (home / "session_index.jsonl").write_text( + json.dumps({"sessionId": session_id, "sessionDir": str(session), "workDir": "/work/mem0"}) + "\n", + encoding="utf-8", + ) + return transcript + + +def test_stop_reads_main_response_from_kimi_session_transcript(tmp_path: Path, monkeypatch) -> None: + transcript = _write_kimi_session( + tmp_path, + "session_abc", + [ + {"type": "metadata", "protocol_version": "1.5", "created_at": 1788431400000}, + { + "type": "context.append_loop_event", + "agentId": "main", + "event": {"type": "step.begin", "uuid": "step-1", "turnId": "0", "step": 1}, + "time": 1788431400100, + }, + { + "type": "context.append_loop_event", + "agentId": "main", + "event": { + "type": "content.part", + "stepUuid": "step-1", + "part": {"type": "text", "text": "Earlier answer."}, + }, + "time": 1788431400200, + }, + { + "type": "context.append_loop_event", + "agentId": "main", + "event": {"type": "step.end", "uuid": "step-1", "finishReason": "end_turn"}, + "time": 1788431400300, + }, + { + "type": "context.append_loop_event", + "agentId": "main", + "event": {"type": "step.begin", "uuid": "step-2", "turnId": "1", "step": 1}, + "time": 1788431400400, + }, + { + "type": "context.append_loop_event", + "agentId": "main", + "event": { + "type": "content.part", + "stepUuid": "step-2", + "part": {"type": "think", "think": "Do not capture this reasoning."}, + }, + "time": 1788431400500, + }, + { + "type": "context.append_loop_event", + "agentId": "main", + "event": { + "type": "content.part", + "stepUuid": "step-2", + "part": {"type": "text", "text": "Fixed and "}, + }, + "time": 1788431400600, + }, + { + "type": "context.append_loop_event", + "agentId": "main", + "event": { + "type": "content.part", + "stepUuid": "step-2", + "part": {"type": "text", "text": "tested."}, + }, + "time": 1788431400700, + }, + { + "type": "context.append_loop_event", + "agentId": "main", + "event": {"type": "step.end", "uuid": "step-2", "finishReason": "end_turn"}, + "time": 1788431400800, + }, + ], + ) + monkeypatch.setenv("KIMI_CODE_HOME", str(tmp_path)) + + value = adapter.normalize( + { + "hook_event_name": "Stop", + "session_id": "session_abc", + "session_title": "Fix Kimi capture", + "client_type": "kimi_code_cli", + "cwd": "/work/mem0", + "stop_hook_active": False, + } + ) + + assert value["last_assistant_message"] == "Fixed and tested." + assert value["transcript_path"] == str(transcript) + + +def test_repeated_sidekick_invocations_get_distinct_run_ids(tmp_path: Path) -> None: + store = adapter.hook_runner.EvidenceStore(tmp_path / "evidence.sqlite3") + payload = { + "hook_event_name": "SubagentStart", + "session_id": "session_abc", + "session_title": "Fix Kimi capture", + "client_type": "kimi_code_cli", + "cwd": str(tmp_path), + "agent_name": "sidekick", + "prompt": "Fix the adapter", + } + + try: + adapter._sidekick_start(store, adapter.normalize({**payload, "agent_id": "first"})) + adapter._sidekick_start(store, adapter.normalize({**payload, "agent_id": "second"})) + adapter._sidekick_stop( + store, + adapter.normalize( + { + **payload, + "hook_event_name": "SubagentStop", + "response": "First run complete.", + "agent_id": "first", + } + ), + ) + adapter._sidekick_stop( + store, + adapter.normalize( + { + **payload, + "hook_event_name": "SubagentStop", + "response": "Second run complete.", + "agent_id": "second", + } + ), + ) + + rows = store.conn.execute( + "SELECT agent_id, stopped_at, final_message FROM sidekick_runs ORDER BY started_at, agent_id" + ).fetchall() + finally: + store.close() + + assert len(rows) == 2 + assert rows[0]["agent_id"] != rows[1]["agent_id"] + assert all(row["stopped_at"] for row in rows) + assert {row["agent_id"]: row["final_message"] for row in rows} == { + "first": "First run complete.", "second": "Second run complete." + } + + +def test_native_kimi_bundle_uses_inline_native_contract(tmp_path: Path) -> None: + root = build("kimi", "native", tmp_path / "kimi") + + manifest = json.loads((root / "kimi.plugin.json").read_text(encoding="utf-8")) + assert manifest["skills"] == "./skills/" + assert manifest["agents"] == "./agents/" + assert manifest["mcpServers"]["mem0"]["args"] == ["./core/mcp_server.py"] + assert {hook["event"] for hook in manifest["hooks"]} >= { + "SessionStart", + "UserPromptSubmit", + "PostToolUse", + "SubagentStart", + "SubagentStop", + "PreCompact", + "SessionEnd", + } + assert (root / "agents" / "sidekick.md").is_file() + assert not any(path.is_symlink() for path in root.rglob("*")) diff --git a/integrations/mem0-agent-plugin/core/mcp_server.py b/integrations/mem0-agent-plugin/core/mcp_server.py new file mode 100644 index 000000000..036fbbdc9 --- /dev/null +++ b/integrations/mem0-agent-plugin/core/mcp_server.py @@ -0,0 +1,247 @@ +#!/usr/bin/env python3 +"""Expose Mem0's memory search as one local coding-agent tool.""" + +from __future__ import annotations + +import json +import os +import sys +from typing import Any + +import telemetry +from memory_core import ( + CODING_MEMORY_CATEGORY_NAMES, + PLUGIN_VERSION, + SEARCH_SCOPES, + format_search_result, + resolve_repo, + search_memories, +) + +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." +) +TOOL_SCHEMA = { + "type": "object", + "properties": { + "query": { + "type": "string", + "minLength": 1, + "maxLength": 2000, + "description": "A direct question about earlier work in this repository.", + }, + "top_k": { + "type": "integer", + "minimum": 1, + "maximum": 20, + "description": "Maximum memories to return. Uses Mem0's configured default when omitted.", + }, + "category": { + "type": "string", + "enum": list(CODING_MEMORY_CATEGORY_NAMES), + "description": "Optional memory category. Omit to search every category.", + }, + "scope": { + "type": "string", + "enum": list(SEARCH_SCOPES), + "description": ( + "Which memories to search. 'repo' (default) is the whole repository's " + "shared memory plus your own preferences, 'dir' narrows the shared " + "part to the current directory, 'mine' is your preferences alone." + ), + }, + "run_id": { + "type": "string", + "minLength": 1, + "description": ( + "Optional coding-agent session ID. With any scope, restricts results to memories " + "saved in that session. Omit to recall memories across sessions." + ), + }, + }, + "required": ["query"], + "additionalProperties": False, +} + + +class ToolInputError(ValueError): + pass + + +def _validate_arguments( + arguments: Any, +) -> tuple[str, int | None, str | None, str | None, str | None]: + if not isinstance(arguments, dict): + raise ToolInputError("Search arguments must be an object.") + + unknown = set(arguments) - {"query", "top_k", "category", "scope", "run_id"} + if unknown: + raise ToolInputError(f"Unknown search argument: {sorted(unknown)[0]}") + + query = arguments.get("query") + if not isinstance(query, str) or not query.strip(): + raise ToolInputError("query must be a non-empty string.") + query = query.strip() + if len(query) > 2000: + raise ToolInputError("query must be at most 2,000 characters.") + + top_k = arguments.get("top_k") + if top_k is not None and ( + isinstance(top_k, bool) or not isinstance(top_k, int) or not 1 <= top_k <= 20 + ): + raise ToolInputError("top_k must be an integer from 1 to 20.") + + category = arguments.get("category") + if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES: + raise ToolInputError("category must be one of Mem0's supported categories.") + + scope = arguments.get("scope") + if scope is not None and scope not in SEARCH_SCOPES: + raise ToolInputError(f"scope must be one of {list(SEARCH_SCOPES)}.") + + run_id = arguments.get("run_id") + if run_id is not None: + if not isinstance(run_id, str) or not run_id.strip(): + raise ToolInputError("run_id must be a non-empty string.") + run_id = run_id.strip() + + return query, top_k, category, scope, run_id + + +def call_search_memories(arguments: Any, cwd: str | None = None) -> str: + query, top_k, category, scope, run_id = _validate_arguments(arguments) + repo = resolve_repo(cwd or os.environ.get("CLAUDE_PROJECT_DIR") or os.getcwd()) + result = search_memories( + None, + repo, + None, + query, + top_k=top_k, + category=category, + scope=scope, + run_id=run_id, + operation="mcp-search", + ) + return format_search_result(result) + + +def _workspace_cwd(params: dict[str, Any]) -> str | None: + meta = params.get("_meta") + if not isinstance(meta, dict): + return None + metadata = meta.get("x-codex-turn-metadata") + if not isinstance(metadata, dict): + return None + workspaces = metadata.get("workspaces") or {} + if isinstance(workspaces, dict): + return next((path for path in workspaces if isinstance(path, str) and path), None) + return None + + +def _tool_response(text: str, *, is_error: bool = False) -> dict[str, Any]: + return { + "content": [{"type": "text", "text": text}], + "isError": is_error, + } + + +def handle_request(message: Any) -> dict[str, Any] | None: + if not isinstance(message, dict): + return None + request_id = message.get("id") + method = message.get("method") + + if method == "notifications/initialized": + return None + if method == "initialize": + requested = (message.get("params") or {}).get("protocolVersion") + return { + "jsonrpc": "2.0", + "id": request_id, + "result": { + "protocolVersion": requested or PROTOCOL_VERSION, + "capabilities": {"tools": {"listChanged": False}}, + "serverInfo": {"name": "mem0", "version": PLUGIN_VERSION}, + }, + } + if method == "ping": + return {"jsonrpc": "2.0", "id": request_id, "result": {}} + if method == "tools/list": + return { + "jsonrpc": "2.0", + "id": request_id, + "result": { + "tools": [ + { + "name": TOOL_NAME, + "description": TOOL_DESCRIPTION, + "inputSchema": TOOL_SCHEMA, + "annotations": { + "readOnlyHint": True, + "idempotentHint": True, + "openWorldHint": True, + }, + } + ] + }, + } + if method == "tools/call": + params = message.get("params") or {} + if params.get("name") != TOOL_NAME: + result = _tool_response("Unknown Mem0 tool.", is_error=True) + else: + try: + result = _tool_response( + call_search_memories(params.get("arguments"), _workspace_cwd(params)) + ) + except ToolInputError as exc: + result = _tool_response(str(exc), is_error=True) + except Exception: + result = _tool_response("Memory search failed.", is_error=True) + return {"jsonrpc": "2.0", "id": request_id, "result": result} + if request_id is None: + return None + return { + "jsonrpc": "2.0", + "id": request_id, + "error": {"code": -32601, "message": "Method not found"}, + } + + +def main() -> int: + for raw_line in sys.stdin: + try: + message = json.loads(raw_line) + response = handle_request(message) + except json.JSONDecodeError: + response = { + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32700, "message": "Parse error"}, + } + except Exception: + response = { + "jsonrpc": "2.0", + "id": None, + "error": {"code": -32603, "message": "Internal error"}, + } + if response is not None: + sys.stdout.write(json.dumps(response, separators=(",", ":")) + "\n") + sys.stdout.flush() + telemetry.spawn_flush() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/mem0-agent-plugin/core/memory_cli.py b/integrations/mem0-agent-plugin/core/memory_cli.py new file mode 100644 index 000000000..595729feb --- /dev/null +++ b/integrations/mem0-agent-plugin/core/memory_cli.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Mem0 diagnostics and user controls.""" + +from __future__ import annotations + +import argparse +import json +import os + +import telemetry +from memory_core import ( + EvidenceStore, + api_key, + data_dir, + doctor, + forget_remote_repo, + configure_harness, + resolve_repo, + user_id, +) + + +def _print_status(value: dict) -> None: + last = value.get("last_operation") or {} + print(f"Mem0: {'paused' if value['paused'] else 'active'}") + print(f"Repository: {value['repo_id']}") + print(f"Local data: {value['data_dir']}") + print(f"API key: {'configured' if value['api_key_configured'] else 'missing'}") + print( + "Saved on this computer: " + f"{value['events']} session details, {value['flushes']} memory updates" + ) + print( + f"Used in this repository: {value['retrievals']} memories returned, " + f"{value['sidekick_runs']} sidekick runs" + ) + if last: + item_label = "" + if last["operation"] in {"flush", "flush-retry"}: + item_label = f", {last['item_count']} memories" + operation = ( + "memory update" + if last["operation"] in {"flush", "flush-retry"} + else last["operation"].replace("-", " ") + ) + print( + f"Last {operation}: " + f"{'succeeded' if last['success'] else 'failed'} " + f"({last['duration_ms']:.1f} ms{item_label})" + ) + sidekick = value.get("last_sidekick") or {} + if sidekick: + state = "finished" if sidekick.get("stopped_at") else "started" + print( + "Last sidekick: " + f"{state}, received {sidekick['context_chars']} characters of memory, " + f"agent {sidekick['agent_id']}" + ) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--plugin-data-dir", default="") + parser.add_argument("--harness", default="") + subparsers = parser.add_subparsers(dest="command", required=True) + + status = subparsers.add_parser("status") + status.add_argument("--json", action="store_true") + + doctor_parser = subparsers.add_parser("doctor") + doctor_parser.add_argument("--json", action="store_true") + + subparsers.add_parser("pause") + subparsers.add_parser("resume") + + forget = subparsers.add_parser("forget") + forget.add_argument("--remote", action="store_true") + forget.add_argument("--yes", action="store_true") + forget.add_argument("--include-project-memory", action="store_true") + + args = parser.parse_args() + if args.harness: + source_tag = f"{args.harness.replace('-', '_')}_plugin" + configure_harness(args.harness, source_tag=source_tag) + telemetry.init(harness=args.harness, source_tag=source_tag.upper()) + if args.plugin_data_dir: + os.environ["MEM0_CODE_DATA_DIR"] = args.plugin_data_dir + store = EvidenceStore() + try: + repo = resolve_repo(os.getcwd()) + telemetry.record("control", repo=repo, action=args.command) + if args.command == "status": + result = { + **store.status(repo.identity), + "repo_id": repo.identity, + "app_id": repo.app_id, + "project_id": repo.project_id, + "directory": repo.directory, + "user_id": user_id(), + "data_dir": str(data_dir()), + "api_key_configured": bool(api_key()), + } + if args.json: + print(json.dumps(result, indent=2, default=str)) + else: + _print_status(result) + elif args.command == "doctor": + result = doctor(os.getcwd()) + if args.json: + print(json.dumps(result, indent=2, default=str)) + else: + for name, check in result["checks"].items(): + print( + f"{'PASS' if check['ok'] else 'FAIL'} {name}: {check['detail']}" + ) + return 0 if result["ok"] else 1 + elif args.command == "pause": + store.set_setting("paused", "true") + print("Mem0 stopped saving and searching memories.") + elif args.command == "resume": + store.set_setting("paused", "false") + print("Mem0 resumed saving and searching memories.") + elif args.command == "forget": + if not args.yes: + print( + "Refusing to delete data without --yes. Add --remote to also " + "delete this user/repository scope from Mem0." + ) + return 2 + remote_result = ( + forget_remote_repo( + repo, include_project_memory=args.include_project_memory + ) + if args.remote + else None + ) + local_result = store.forget_local_repo(repo.identity) + print( + json.dumps( + {"local": local_result, "remote": remote_result}, + indent=2, + default=str, + ) + ) + if remote_result and remote_result.get("status") == "error": + return 1 + finally: + store.close() + telemetry.spawn_flush() + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/integrations/mem0-agent-plugin/core/memory_core.py b/integrations/mem0-agent-plugin/core/memory_core.py new file mode 100644 index 000000000..cf71196b8 --- /dev/null +++ b/integrations/mem0-agent-plugin/core/memory_core.py @@ -0,0 +1,2645 @@ +#!/usr/bin/env python3 +"""Shared core for Mem0 agent plugins. + +Hooks record small session details locally. When the agent compacts or ends the +session, Mem0 sends the useful parts to the platform so it can create memories. +The agent can search those memories during later work in the repository. +""" + +from __future__ import annotations + +import functools +import hashlib +import json +import math +import os +import re +import sqlite3 +import subprocess +import sys +import time +import urllib.error +import urllib.parse +import urllib.request +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Iterable + +import telemetry + +DEFAULT_API_URL = "https://api.mem0.ai" +PLUGIN_VERSION = "0.3.1" + +_harness_name: str = "generic" +_harness_env_prefix: str = "MEM0_PLUGIN" +_harness_data_dir_name: str = "mem0-plugin" +_harness_source_tag: str = "mem0_plugin" + + +def configure_harness( + name: str, + env_prefix: str = "", + data_dir_name: str = "", + source_tag: str = "", +) -> None: + global _harness_name, _harness_env_prefix, _harness_data_dir_name, _harness_source_tag + _harness_name = name + _harness_env_prefix = env_prefix or f"MEM0_{name.upper().replace('-', '_')}" + _harness_data_dir_name = data_dir_name or f"{name}-plugin" + _harness_source_tag = source_tag or f"{name.replace('-', '_')}_plugin" + + +def harness_config() -> dict[str, str]: + return { + "name": _harness_name, + "env_prefix": _harness_env_prefix, + "data_dir_name": _harness_data_dir_name, + "source_tag": _harness_source_tag, + } + + +MAX_COMMAND_CHARS = 2000 +MAX_RESULT_CHARS = 2500 +MAX_EPISODE_CHARS = 12000 +CHECKPOINT_EXCHANGES = 5 +CHECKPOINT_MESSAGES = 10 +CHECKPOINT_SOURCE_CHARS = 40000 +DEFAULT_MAX_CONTEXT_CHARS = 4000 +MAX_EXTRACTION_INPUT_TOKENS = 24000 +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. + +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 current coding agent's final response for conclusions about current repository behavior. Do not save proposed or recommended changes unless the user accepted them or the coding agent completed them. Treat subagent responses as supporting repository evidence, not as decisions. + +Write about the repository, not the user, assistant, session, or task. Do not save personal preferences. Do not save a memory that only states which repository, branch, or directory the session worked in. Do not include test results, documentation updates, release notes, or temporary state. + +If nothing useful was established, return no memories.""" + +PERSONAL_MEMORY_INSTRUCTIONS = """Save concise facts about the user that will help in any repository: preferred tools, package managers, languages, coding style, review and communication preferences, and anything the user explicitly asked to be remembered about themselves. + +Write in the third person about the user, not about the repository, the assistant, the session, or the task. Do not save repository facts, project decisions, commands, or what was built. + +Never save that the user has no preferences or that nothing was learned. If nothing was learned about the user, return no memories.""" + +CODING_MEMORY_CATEGORIES = [ + { + "project_knowledge": ( + "What the project is and how its code, APIs, data, files, and " + "components work." + ) + }, + { + "decisions_and_constraints": ( + "Why an approach was chosen, what must remain true, and rules future " + "work must follow." + ) + }, + { + "workflows": ( + "How to run, test, debug, deploy, configure, or otherwise work on the " + "project." + ) + }, + { + "problems_and_fixes": ( + "Bugs, failures, known pitfalls, their causes, and how to fix or avoid " + "them." + ) + }, + { + "results": ( + "Outcomes and measurements from tests, benchmarks, experiments, or " + "investigations." + ) + }, +] +CODING_MEMORY_CATEGORY_NAMES = tuple( + category_name + for category in CODING_MEMORY_CATEGORIES + for category_name in category +) + +TEST_COMMAND_RE = re.compile( + r"(?:^|\s)(?:pytest|py\.test|jest|vitest|go\s+test|cargo\s+test|" + r"npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|" + r"mvn\s+test|gradle\s+test|make\s+test)(?:\s|$)", + re.IGNORECASE, +) +BUILD_COMMAND_RE = re.compile( + r"(?:^|\s)(?:npm|pnpm|yarn)\s+(?:run\s+)?build(?:\s|$)|" + r"(?:^|\s)(?:cargo|go|mvn|gradle|make)\s+build(?:\s|$)", + re.IGNORECASE, +) + +SECRET_PATTERNS = [ + re.compile(r"(?i)(authorization\s*[:=]\s*(?:bearer|token)\s+)[^\s\"']+"), + re.compile( + r"(?i)((?:api[_-]?key|secret[_-]?access[_-]?key|session[_-]?token)\s*[:=]\s*)[^\s\"']+" + ), + re.compile( + r"(?i)((?:access[_-]?token|refresh[_-]?token|password|credential)" + r"\s*[:=]\s*)[^\s&\"']+" + ), + re.compile(r"\b(?:sk|m0|mem0_sk|psk)-[A-Za-z0-9_\-]{12,}\b"), + re.compile(r"\b(?:ASIA|AKIA)[A-Z0-9]{12,}\b"), + re.compile(r"\b(?:ghp_|github_pat_|xox[baprs]-)[A-Za-z0-9_\-]{12,}\b"), + re.compile( + r"-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----", + re.DOTALL, + ), + re.compile( + r'(?i)("(?:api[_-]?key|password|secret(?:[_-]?access[_-]?key)?' + r'|(?:access|refresh|session)[_-]?token|token|authorization|credential' + r')"\s*:\s*")(?:\\.|[^"\\])*' + ), +] + + +def utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def redact(value: Any) -> str: + text = ( + value + if isinstance(value, str) + else json.dumps(value, ensure_ascii=False, default=str) + ) + for pattern in SECRET_PATTERNS: + if pattern.groups: + text = pattern.sub(r"\1[REDACTED]", text) + else: + text = pattern.sub("[REDACTED]", text) + return text + + +def bounded(value: Any, limit: int) -> str: + text = redact(value).strip() + if len(text) <= limit: + return text + return text[:limit] + f"\n...[truncated {len(text) - limit} chars]" + + +def _git(cwd: str, *args: str) -> str: + try: + result = subprocess.run( + ["git", "-C", cwd, *args], + check=False, + capture_output=True, + text=True, + timeout=0.5, + ) + except (OSError, subprocess.TimeoutExpired): + return "" + return result.stdout.strip() if result.returncode == 0 else "" + + +def _normalize_remote(remote: str) -> str: + remote = remote.strip() + if remote.startswith("git@") and ":" in remote: + host_path = remote[4:].replace(":", "/", 1) + remote = f"https://{host_path}" + if remote.endswith(".git"): + remote = remote[:-4] + if "://" in remote: + parsed = urllib.parse.urlsplit(remote) + hostname = parsed.hostname or "" + if parsed.port: + hostname = f"{hostname}:{parsed.port}" + remote = urllib.parse.urlunsplit( + (parsed.scheme, hostname, parsed.path, parsed.query, parsed.fragment) + ) + return remote.rstrip("/") + + +_WILDCARD_SCOPE = re.compile(r"^\*+$") + + +def _scope_value(raw: str | None) -> str: + """Reject wildcards as identities: they are filter syntax and would widen the scope.""" + value = (raw or "").strip() + return "" if _WILDCARD_SCOPE.match(value) else value + + +SEARCH_SCOPES = ("repo", "dir", "mine") +DEFAULT_SEARCH_SCOPE = "repo" + +def directory_app_id(repo: RepoContext) -> str: + """The app_id of the directory this session runs in: the repository at the root, repository/path below it.""" + return f"{repo.app_id}/{repo.directory}" if repo.directory else repo.app_id + + +def directory_chain(repo: RepoContext) -> list[str]: + """Every directory a memory belongs to, from the top-level folder down to the one it was written in.""" + parts = repo.directory.split("/") if repo.directory else [] + return ["/".join(parts[: index + 1]) for index in range(len(parts))] + + +def _shared_project_ids(repo: RepoContext) -> list[str]: + """Current and pre-upgrade namespaces, shared by recall and explicit deletion.""" + if not repo.identity.startswith("local:") and repo.project_id != repo.app_id: + return [repo.project_id, repo.app_id] + return [repo.project_id] + + +def _search_filters(user: str, repo: RepoContext, scope: str) -> dict[str, Any]: + """Build the scope filter: app_id scopes to the repo, then union shared and personal lanes.""" + app_scope = {"app_id": repo.app_id} + mine = {"AND": [{"user_id": user}, app_scope]} + if scope == "mine": + return mine + projects = [{"AND": [{"agent_id": project_id}, app_scope]} for project_id in _shared_project_ids(repo)] + shared: dict[str, Any] = projects[0] if len(projects) == 1 else {"OR": projects} + if scope == "dir" and repo.directory: + shared = {"AND": [shared, {"metadata": {"dirs": {"contains": repo.directory}}}]} + return {"OR": [shared, mine]} + + +def search_scope() -> str: + configured = ( + _plugin_option("search_scope", "MEM0_CODE_SEARCH_SCOPE") or "" + ).strip().lower() + return configured if configured in SEARCH_SCOPES else DEFAULT_SEARCH_SCOPE + + +def resolve_search_scope(scope: str | None) -> str: + value = (scope or search_scope()).strip().lower() + if value not in SEARCH_SCOPES: + raise ValueError(f"Unknown search scope: {value}") + return value + + +def _legacy_project_map(cwd: str, root: str, raw_remote: str) -> str: + """Return the project name used by the previous Claude Code plugin.""" + try: + data = json.loads((Path.home() / ".mem0" / "project_map.json").read_text()) + except (OSError, json.JSONDecodeError): + return "" + if not isinstance(data, dict): + return "" + + keys = list(dict.fromkeys([cwd, root, os.path.realpath(cwd), os.path.realpath(root)])) + if raw_remote: + keys.append(f"remote:{hashlib.sha256(raw_remote.encode()).hexdigest()[:16]}") + for key in keys: + value = data.get(key) + if isinstance(value, str) and value.strip(): + return value.strip() + return "" + + +def _legacy_project_id(cwd: str, root: str, raw_remote: str, identity: str) -> str: + """Use the repository namespace created by the previous Mem0 plugin.""" + configured = _scope_value(os.environ.get("MEM0_PROJECT_ID")) + if configured: + return configured + + mapped = _scope_value(_legacy_project_map(cwd, root, raw_remote)) + if mapped: + return mapped + + remote = raw_remote or ("" if identity.startswith("local:") else identity) + remote = remote.strip().removesuffix(".git") + for prefix in ("https://", "http://", "ssh://", "git://"): + if remote.startswith(prefix): + remote = remote[len(prefix) :] + break + else: + remote = re.sub(r"^git@", "", remote) + parts = [part for part in remote.replace(":", "/", 1).split("/") if part] + if len(parts) >= 2: + return f"{parts[-2]}-{parts[-1]}".replace("/", "-").replace(":", "-") + if parts: + return parts[-1].replace("/", "-").replace(":", "-") + return os.path.basename(root or cwd) or "unknown" + + +@dataclass(frozen=True) +class RepoContext: + cwd: str + root: str + identity: str + app_id: str + branch: str + head_sha: str + project_id: str = "" + directory: str = "" + + +def _project_id(root: str, identity: str, app_id: str) -> str: + """The shared namespace: includes a host hash so repos with the same owner/name on different hosts stay apart.""" + if not identity.startswith("local:"): + return f"{app_id}-{hashlib.sha256(identity.encode()).hexdigest()[:10]}" + return f"local-{app_id}-{hashlib.sha256(root.encode()).hexdigest()[:10]}" + + +def _relative_directory(cwd: str, root: str) -> str: + relative = os.path.relpath(cwd, root) + return "" if relative == "." or relative.startswith("..") else relative.replace(os.sep, "/") + + +@dataclass(frozen=True) +class MemorySearchResult: + succeeded: bool + matched_count: int + already_shown_count: int + memories: list[dict[str, Any]] + + +@functools.lru_cache(maxsize=64) +def _resolve_repo_cached(cwd: str) -> RepoContext: + given_cwd = cwd + cwd = os.path.realpath(cwd) + given_root = _git(cwd, "rev-parse", "--show-toplevel") or given_cwd + root = os.path.realpath(given_root) + raw_remote = _git(root, "config", "--get", "remote.origin.url") + remote = _normalize_remote(raw_remote) + identity = remote or f"local:{root}" + app_id = _legacy_project_id(given_cwd, given_root, raw_remote, identity) + return RepoContext( + cwd=cwd, + root=root, + identity=identity, + app_id=app_id, + branch=_git(root, "branch", "--show-current") or "detached", + head_sha=_git(root, "rev-parse", "HEAD"), + project_id=_project_id(root, identity, app_id), + directory=_relative_directory(cwd, root), + ) + + +def resolve_repo(cwd: str | None) -> RepoContext: + return _resolve_repo_cached(os.path.abspath(cwd or os.getcwd())) + + +def api_key() -> str: + configured = ( + os.environ.get("MEM0_API_KEY") + or os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if configured: + return configured + try: + return (data_dir() / "api-key").read_text(encoding="utf-8").strip() + except OSError: + return "" + + +def cache_plugin_api_key() -> bool: + """Bridge host's hook-only sensitive config into plugin-owned storage.""" + configured = ( + os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if not configured: + return False + + directory = data_dir() + directory.mkdir(parents=True, exist_ok=True) + path = directory / "api-key" + temporary = directory / f"api-key.{os.getpid()}.tmp" + descriptor = os.open( + temporary, + os.O_WRONLY | os.O_CREAT | os.O_TRUNC, + 0o600, + ) + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + handle.write(configured) + os.replace(temporary, path) + os.chmod(path, 0o600) + finally: + try: + temporary.unlink() + except FileNotFoundError: + pass + return True + + +def clear_stale_api_key_cache() -> bool: + """Drop the cached key file once every configured key source is gone.""" + configured = ( + os.environ.get("MEM0_API_KEY") + or os.environ.get("PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY") + or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") + or "" + ).strip() + if configured: + return False + path = data_dir() / "api-key" + if not path.exists(): + return False + try: + path.unlink() + except OSError: + return False + return True + + +def detached_process_kwargs(platform: str | None = None) -> dict: + """Keep a spawned worker alive after the coding agent exits, on POSIX and Windows.""" + if (platform or sys.platform) == "win32": + return { + "creationflags": subprocess.DETACHED_PROCESS + | subprocess.CREATE_NEW_PROCESS_GROUP + } + return {"start_new_session": True} + + +def _plugin_option(name: str, fallback: str = "") -> str: + return ( + os.environ.get(f"PLUGIN_OPTION_{name.upper()}") + or os.environ.get(f"CLAUDE_PLUGIN_OPTION_{name.upper()}") + or os.environ.get(fallback) + or "" + ).strip() + + +def user_id() -> str: + return ( + _scope_value(_plugin_option("user_id", "MEM0_CODE_USER_ID")) + or _scope_value(os.environ.get("MEM0_USER_ID")) + or _scope_value(os.environ.get("MEM0_RESOLVED_USER_ID")) + or _scope_value(os.environ.get("USER")) + or _scope_value(os.environ.get("USERNAME")) + or "default" + ) + + +def data_dir() -> Path: + configured = ( + os.environ.get("MEM0_CODE_DATA_DIR") + or os.environ.get("MEM0_PLUGIN_DATA_DIR") + or os.environ.get("PLUGIN_DATA") + or os.environ.get("CLAUDE_PLUGIN_DATA") + ) + return ( + Path(configured).expanduser() if configured else Path.home() / ".mem0" / _harness_data_dir_name + ) + + +def _bool_option(name: str, fallback: str, default: bool = False) -> bool: + value = _plugin_option(name, fallback) + if not value: + return default + return value.lower() in {"1", "true", "yes", "on"} + + +def _int_option(name: str, fallback: str, default: int) -> int: + value = _plugin_option(name, fallback) + try: + return int(value) if value else default + except ValueError: + return default + + + +def _checkpoint_message(event: dict[str, Any]) -> str: + kind = event.get("kind") + payload = event.get("payload") or {} + if kind == "user_prompt": + return redact(payload.get("text", "")).strip() + if kind == "assistant_stop": + transcript_messages = payload.get("transcript_messages") or [] + if isinstance(transcript_messages, list): + text = "\n".join( + str(message.get("content") or "") + for message in transcript_messages + if isinstance(message, dict) and message.get("content") + ) + if text: + return text + return redact(payload.get("text", "")).strip() + if kind == "sidekick_stop": + return redact(payload.get("final_message", "")).strip() + return "" + + +def checkpoint_stats(events: list[dict[str, Any]]) -> tuple[int, int, int]: + """Return completed exchanges, messages, and source characters.""" + completed = sum(event.get("kind") == "assistant_stop" for event in events) + contents = [content for event in events if (content := _checkpoint_message(event))] + return completed, len(contents), sum(len(content) for content in contents) + + +def select_checkpoint_events( + events: list[dict[str, Any]], *, force: bool +) -> list[dict[str, Any]]: + """Select one ordered extraction block without splitting an exchange.""" + for index, event in enumerate(events): + if event.get("kind") != "assistant_stop": + continue + candidate = events[: index + 1] + completed, messages, source_chars = checkpoint_stats(candidate) + if ( + completed >= CHECKPOINT_EXCHANGES + or messages >= CHECKPOINT_MESSAGES + or source_chars >= CHECKPOINT_SOURCE_CHARS + ): + return candidate + return events if force else [] + + +class EvidenceStore: + def __init__(self, path: Path | None = None): + directory = data_dir() if path is None else path.parent + directory.mkdir(parents=True, exist_ok=True) + self.path = path or directory / "evidence.sqlite3" + try: + self._open() + except sqlite3.DatabaseError: + self._quarantine() + self._open() + + def _open(self) -> None: + self.conn = sqlite3.connect(self.path, timeout=10) + self.conn.row_factory = sqlite3.Row + try: + self.conn.execute("PRAGMA journal_mode=WAL") + self.conn.execute("PRAGMA busy_timeout=10000") + self._migrate() + except sqlite3.DatabaseError: + self.conn.close() + raise + + def _quarantine(self) -> None: + """Move an unreadable database aside so capture restarts cleanly.""" + stamp = int(time.time()) + for suffix in ("", "-wal", "-shm"): + source = Path(f"{self.path}{suffix}") + try: + source.replace(f"{self.path}.corrupt-{stamp}{suffix}") + except FileNotFoundError: + continue + except OSError: + try: + source.unlink() + except OSError: + pass + telemetry.record("db_quarantined") + + def close(self) -> None: + self.conn.close() + + def _migrate(self) -> None: + self.conn.executescript( + """ + CREATE TABLE IF NOT EXISTS events ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + session_id TEXT NOT NULL, + created_at TEXT NOT NULL, + kind TEXT NOT NULL, + payload_json TEXT NOT NULL, + flush_id TEXT + ); + CREATE INDEX IF NOT EXISTS events_session_idx + ON events(repo_id, session_id, flush_id, id); + + CREATE TABLE IF NOT EXISTS session_scopes ( + session_id TEXT PRIMARY KEY, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + root TEXT NOT NULL, + branch TEXT NOT NULL, + head_sha TEXT NOT NULL, + created_at TEXT NOT NULL, + directory TEXT NOT NULL DEFAULT '' + ); + + CREATE TABLE IF NOT EXISTS flushes ( + packet_id TEXT PRIMARY KEY, + repo_id TEXT NOT NULL, + app_id TEXT NOT NULL, + session_id TEXT NOT NULL, + reason TEXT NOT NULL, + event_start INTEGER NOT NULL, + event_end INTEGER NOT NULL, + status TEXT NOT NULL, + episode_event_id TEXT, + semantic_event_id TEXT, + error TEXT, + attempts INTEGER NOT NULL DEFAULT 0, + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + CREATE TABLE IF NOT EXISTS retrievals ( + session_id TEXT NOT NULL, + repo_id TEXT NOT NULL, + memory_id TEXT NOT NULL, + injected_at TEXT NOT NULL, + rank INTEGER, + score REAL, + memory_text TEXT, + context_chars INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY(session_id, repo_id, memory_id) + ); + + CREATE TABLE IF NOT EXISTS operations ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + created_at TEXT NOT NULL, + repo_id TEXT NOT NULL, + session_id TEXT NOT NULL, + operation TEXT NOT NULL, + duration_ms REAL NOT NULL, + success INTEGER NOT NULL, + item_count INTEGER NOT NULL DEFAULT 0, + request_chars INTEGER NOT NULL DEFAULT 0, + response_chars INTEGER NOT NULL DEFAULT 0, + error TEXT + ); + + CREATE TABLE IF NOT EXISTS sidekick_runs ( + repo_id TEXT NOT NULL, + session_id TEXT NOT NULL, + agent_id TEXT NOT NULL, + agent_type TEXT NOT NULL, + started_at TEXT NOT NULL, + stopped_at TEXT, + transcript_path TEXT, + context_chars INTEGER NOT NULL DEFAULT 0, + final_message TEXT, + PRIMARY KEY(repo_id, session_id, agent_id) + ); + CREATE INDEX IF NOT EXISTS sidekick_runs_repo_idx + ON sidekick_runs(repo_id, started_at); + + CREATE TABLE IF NOT EXISTS settings ( + key TEXT PRIMARY KEY, + value TEXT NOT NULL, + updated_at TEXT NOT NULL + ); + + """ + ) + # Remove the pre-0.1.1 no-tools snapshot implementation. The real coding + # sidekick is a native Claude Code agent and stores no state in this DB. + self.conn.executescript( + """ + DROP TABLE IF EXISTS sidekick_calls; + DROP TABLE IF EXISTS sidekick_snapshots; + DROP TABLE IF EXISTS sidekick_state; + DROP TABLE IF EXISTS sidekick_packets; + """ + ) + self._ensure_column("retrievals", "rank", "INTEGER") + self._ensure_column("retrievals", "score", "REAL") + self._ensure_column("retrievals", "memory_text", "TEXT") + self._ensure_column("retrievals", "context_chars", "INTEGER NOT NULL DEFAULT 0") + self._ensure_column("flushes", "attempts", "INTEGER NOT NULL DEFAULT 0") + self._ensure_column("session_scopes", "directory", "TEXT NOT NULL DEFAULT ''") + self.conn.commit() + + def _ensure_column(self, table: str, column: str, declaration: str) -> None: + columns = { + str(row["name"]) + for row in self.conn.execute(f"PRAGMA table_info({table})").fetchall() + } + if column not in columns: + self.conn.execute(f"ALTER TABLE {table} ADD COLUMN {column} {declaration}") + + def record_event( + self, + repo: RepoContext, + session_id: str, + kind: str, + payload: dict[str, Any], + ) -> int: + cursor = self.conn.execute( + """INSERT INTO events + (repo_id, app_id, session_id, created_at, kind, payload_json) + VALUES (?, ?, ?, ?, ?, ?)""", + ( + repo.identity, + repo.app_id, + session_id, + utc_now(), + kind, + json.dumps(payload, ensure_ascii=False, sort_keys=True), + ), + ) + self.conn.commit() + return int(cursor.lastrowid) + + def record_assistant_response(self, repo: RepoContext, session_id: str, message: str) -> None: + """Ignore repeated response hooks until another prompt or a different answer arrives.""" + with self.conn: + # Serialize the check and insert across concurrent Stop and SessionEnd hooks. + self.conn.execute("BEGIN IMMEDIATE") + previous = self.conn.execute( + """SELECT kind, payload_json FROM events + WHERE repo_id = ? AND session_id = ? AND kind IN ('user_prompt', 'assistant_stop') + ORDER BY id DESC LIMIT 1""", + (repo.identity, session_id), + ).fetchone() + if ( + previous is not None + and previous["kind"] == "assistant_stop" + and json.loads(previous["payload_json"]).get("text") == message + ): + return + self.record_event(repo, session_id, "assistant_stop", {"text": message}) + + def repo_for_session(self, session_id: str, cwd: str | None) -> RepoContext: + """Keep one project scope for every hook in a coding-agent session.""" + current = resolve_repo(cwd) + if session_id == "unknown-session": + return current + + with self.conn: + self.conn.execute( + """INSERT OR IGNORE INTO session_scopes + (session_id, repo_id, app_id, root, branch, head_sha, created_at, directory) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", + ( + session_id, + current.identity, + current.app_id, + current.root, + current.branch, + current.head_sha, + utc_now(), + current.directory, + ), + ) + scope = self.conn.execute( + "SELECT * FROM session_scopes WHERE session_id = ?", (session_id,) + ).fetchone() + same_git_repo = ( + current.identity == scope["repo_id"] and bool(current.head_sha) + ) + pinned = current if same_git_repo else resolve_repo(str(scope["root"])) + return RepoContext( + cwd=current.cwd, + root=pinned.root, + identity=str(scope["repo_id"]), + app_id=str(scope["app_id"]), + branch=pinned.branch, + head_sha=pinned.head_sha, + project_id=pinned.project_id, + directory=str(scope["directory"] or ""), + ) + + def prepare_flush( + self, repo: RepoContext, session_id: str, reason: str + ) -> tuple[str, list[dict[str, Any]]] | None: + with self.conn: + self.conn.execute("BEGIN IMMEDIATE") + existing = self.conn.execute( + """SELECT * FROM flushes + WHERE repo_id = ? AND session_id = ? + AND status NOT IN ('semantic-succeeded', 'explicitly-stored', 'gave-up') + ORDER BY created_at LIMIT 1""", + (repo.identity, session_id), + ).fetchone() + if existing and int(existing["attempts"] or 0) >= MAX_FLUSH_ATTEMPTS: + self.conn.execute( + "UPDATE flushes SET status = 'gave-up', updated_at = ? WHERE packet_id = ?", + (utc_now(), existing["packet_id"]), + ) + telemetry.record( + "flush", + repo=repo, + session_id=session_id, + reason=reason, + status="gave-up", + success=False, + attempts=int(existing["attempts"] or 0), + ) + existing = None + if existing: + if reason != "periodic" and existing["reason"] == "periodic": + self.conn.execute( + "UPDATE flushes SET reason = ?, updated_at = ? WHERE packet_id = ?", + (reason, utc_now(), existing["packet_id"]), + ) + existing_rows = self.conn.execute( + "SELECT * FROM events WHERE flush_id = ? ORDER BY id", + (existing["packet_id"],), + ).fetchall() + if existing_rows: + return str(existing["packet_id"]), [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in existing_rows + ] + + rows = self.conn.execute( + """SELECT * FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id""", + (repo.identity, session_id), + ).fetchall() + if not rows: + return None + + events = [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in rows + ] + events = select_checkpoint_events(events, force=reason != "periodic") + if not events: + return None + event_start, event_end = events[0]["id"], events[-1]["id"] + packet_material = f"{repo.identity}\0{session_id}\0{event_start}\0{event_end}" + packet_id = hashlib.sha256(packet_material.encode()).hexdigest()[:32] + now = utc_now() + + self.conn.execute( + """INSERT OR IGNORE INTO flushes + (packet_id, repo_id, app_id, session_id, reason, event_start, + event_end, status, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, 'prepared', ?, ?)""", + ( + packet_id, + repo.identity, + repo.app_id, + session_id, + reason, + event_start, + event_end, + now, + now, + ), + ) + event_ids = [event["id"] for event in events] + placeholders = ", ".join("?" for _ in event_ids) + self.conn.execute( + f"UPDATE events SET flush_id = ? " + f"WHERE id IN ({placeholders}) AND flush_id IS NULL", + (packet_id, *event_ids), + ) + return packet_id, events + + def checkpoint_due(self, repo_id: str, session_id: str) -> bool: + if self.has_inflight_flush(repo_id, session_id): + return False + rows = self.conn.execute( + """SELECT * FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id""", + (repo_id, session_id), + ).fetchall() + events = [ + { + "id": row["id"], + "created_at": row["created_at"], + "kind": row["kind"], + "payload": json.loads(row["payload_json"]), + } + for row in rows + ] + return bool(select_checkpoint_events(events, force=False)) + + def has_inflight_flush(self, repo_id: str, session_id: str) -> bool: + return ( + self.conn.execute( + """SELECT 1 FROM flushes + WHERE repo_id = ? AND session_id = ? + AND status IN ('prepared', 'semantic-queued') + LIMIT 1""", + (repo_id, session_id), + ).fetchone() + is not None + ) + + def flush_record(self, packet_id: str) -> dict[str, Any] | None: + row = self.conn.execute( + "SELECT * FROM flushes WHERE packet_id = ?", (packet_id,) + ).fetchone() + return dict(row) if row else None + + def has_unflushed_events(self, repo_id: str, session_id: str) -> bool: + return ( + self.conn.execute( + """SELECT 1 FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + LIMIT 1""", + (repo_id, session_id), + ).fetchone() + is not None + ) + + def unflushed_starts_with_session_start( + self, repo_id: str, session_id: str + ) -> bool: + row = self.conn.execute( + """SELECT kind FROM events + WHERE repo_id = ? AND session_id = ? AND flush_id IS NULL + ORDER BY id LIMIT 1""", + (repo_id, session_id), + ).fetchone() + return bool(row and row["kind"] == "session_start") + + def update_flush(self, packet_id: str, **fields: Any) -> None: + allowed = {"status", "episode_event_id", "semantic_event_id", "error"} + updates = {key: value for key, value in fields.items() if key in allowed} + updates["updated_at"] = utc_now() + clause = ", ".join(f"{key} = ?" for key in updates) + failed = str(fields.get("status", "")) in { + "error", + "semantic-failed", + "semantic-timeout", + "semantic-missing", + } + if failed: + clause += ", attempts = attempts + 1" + with self.conn: + self.conn.execute( + f"UPDATE flushes SET {clause} WHERE packet_id = ?", + [*updates.values(), packet_id], + ) + + def unseen( + self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]] + ) -> list[dict[str, Any]]: + seen = { + row["memory_id"] + for row in self.conn.execute( + "SELECT memory_id FROM retrievals WHERE session_id = ? AND repo_id = ?", + (session_id, repo_id), + ) + } + return [memory for memory in memories if str(memory.get("id", "")) not in seen] + + def mark_injected( + self, session_id: str, repo_id: str, memories: Iterable[dict[str, Any]] + ) -> None: + now = utc_now() + with self.conn: + for rank, memory in enumerate(memories, start=1): + memory_id = str(memory.get("id", "")) + if memory_id: + memory_text = bounded( + memory.get("memory") or memory.get("text") or "", + 4000, + ) + try: + score = float(memory["score"]) + except (KeyError, TypeError, ValueError): + score = None + self.conn.execute( + """INSERT OR IGNORE INTO retrievals + (session_id, repo_id, memory_id, injected_at, rank, + score, memory_text, context_chars) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", + ( + session_id, + repo_id, + memory_id, + now, + rank, + score, + memory_text, + len(memory_text), + ), + ) + + def injected_memories( + self, session_id: str, repo_id: str + ) -> list[dict[str, Any]]: + """Return the exact memories already supplied to the main conversation.""" + rows = self.conn.execute( + """SELECT memory_id, rank, score, memory_text + FROM retrievals + WHERE session_id = ? AND repo_id = ? + ORDER BY COALESCE(rank, 2147483647), injected_at, memory_id""", + (session_id, repo_id), + ).fetchall() + return [ + { + "id": row["memory_id"], + "memory": row["memory_text"], + "score": row["score"], + } + for row in rows + if row["memory_text"] + ] + + def start_sidekick( + self, + repo: RepoContext, + session_id: str, + agent_id: str, + agent_type: str, + context_chars: int, + ) -> bool: + """Record one native sidekick instance and whether context was first sent.""" + with self.conn: + cursor = self.conn.execute( + """INSERT OR IGNORE INTO sidekick_runs + (repo_id, session_id, agent_id, agent_type, started_at, + context_chars) + VALUES (?, ?, ?, ?, ?, ?)""", + ( + repo.identity, + session_id, + agent_id, + agent_type, + utc_now(), + context_chars, + ), + ) + return int(cursor.rowcount) > 0 + + def stop_sidekick( + self, + repo: RepoContext, + session_id: str, + agent_id: str, + agent_type: str, + transcript_path: str, + final_message: str, + ) -> str: + now = utc_now() + self.conn.execute("BEGIN IMMEDIATE") + try: + if not agent_id: + rows = self.conn.execute( + """SELECT agent_id FROM sidekick_runs + WHERE repo_id = ? AND session_id = ? AND agent_type = ? AND stopped_at IS NULL + LIMIT 2""", + (repo.identity, session_id, agent_type), + ).fetchall() + # Without a host ID, overlapping runs cannot be correlated reliably. + agent_id = rows[0]["agent_id"] if len(rows) == 1 else f"unknown-agent-{time.time_ns()}" + self.conn.execute( + """INSERT INTO sidekick_runs + (repo_id, session_id, agent_id, agent_type, started_at, + stopped_at, transcript_path, final_message) + VALUES (?, ?, ?, ?, ?, ?, ?, ?) + ON CONFLICT(repo_id, session_id, agent_id) DO UPDATE SET + stopped_at = excluded.stopped_at, + transcript_path = excluded.transcript_path, + final_message = excluded.final_message""", + ( + repo.identity, + session_id, + agent_id, + agent_type, + now, + now, + bounded(transcript_path, 2000), + redact(final_message).strip(), + ), + ) + self.conn.commit() + except Exception: + self.conn.rollback() + raise + return agent_id + + def operation( + self, + repo: RepoContext, + session_id: str, + operation: str, + duration_ms: float, + success: bool, + *, + item_count: int = 0, + request_chars: int = 0, + response_chars: int = 0, + error: str = "", + ) -> None: + with self.conn: + self.conn.execute( + """INSERT INTO operations + (created_at, repo_id, session_id, operation, duration_ms, + success, item_count, request_chars, response_chars, error) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""", + ( + utc_now(), + repo.identity, + session_id, + operation, + duration_ms, + int(success), + item_count, + request_chars, + response_chars, + bounded(error, 1000), + ), + ) + + def has_operation(self, repo_id: str, session_id: str, operation: str) -> bool: + row = self.conn.execute( + """SELECT 1 FROM operations + WHERE repo_id = ? AND session_id = ? AND operation = ? + LIMIT 1""", + (repo_id, session_id, operation), + ).fetchone() + return row is not None + + def has_event(self, repo_id: str, session_id: str, kind: str) -> bool: + row = self.conn.execute( + """SELECT 1 FROM events + WHERE repo_id = ? AND session_id = ? AND kind = ? + LIMIT 1""", + (repo_id, session_id, kind), + ).fetchone() + return row is not None + + def latest_event_payload( + self, repo_id: str, session_id: str, kind: str + ) -> dict[str, Any]: + row = self.conn.execute( + """SELECT payload_json FROM events + WHERE repo_id = ? AND session_id = ? AND kind = ? + ORDER BY id DESC LIMIT 1""", + (repo_id, session_id, kind), + ).fetchone() + if not row: + return {} + try: + payload = json.loads(row["payload_json"]) + except json.JSONDecodeError: + return {} + return payload if isinstance(payload, dict) else {} + + def setting(self, key: str, default: str = "") -> str: + row = self.conn.execute( + "SELECT value FROM settings WHERE key = ?", (key,) + ).fetchone() + return str(row["value"]) if row else default + + def set_setting(self, key: str, value: str) -> None: + with self.conn: + self.conn.execute( + """INSERT INTO settings(key, value, updated_at) + VALUES (?, ?, ?) + ON CONFLICT(key) DO UPDATE SET + value = excluded.value, + updated_at = excluded.updated_at""", + (key, value, utc_now()), + ) + + def is_paused(self) -> bool: + return self.setting("paused", "false").lower() in { + "1", + "true", + "yes", + "on", + } + + def forget_local_repo(self, repo_id: str) -> dict[str, int]: + tables = { + "events": "repo_id", + "session_scopes": "repo_id", + "flushes": "repo_id", + "retrievals": "repo_id", + "operations": "repo_id", + "sidekick_runs": "repo_id", + } + removed: dict[str, int] = {} + with self.conn: + for table, column in tables.items(): + cursor = self.conn.execute( + f"DELETE FROM {table} WHERE {column} = ?", (repo_id,) + ) + removed[table] = max(int(cursor.rowcount), 0) + return removed + + def status(self, repo_id: str) -> dict[str, Any]: + def count(table: str) -> int: + return int( + self.conn.execute( + f"SELECT COUNT(*) FROM {table} WHERE repo_id = ?", (repo_id,) + ).fetchone()[0] + ) + + last_operation = self.conn.execute( + """SELECT created_at, operation, duration_ms, success, item_count, error + FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""", + (repo_id,), + ).fetchone() + last_sidekick = self.conn.execute( + """SELECT session_id, agent_id, agent_type, started_at, stopped_at, + context_chars + FROM sidekick_runs WHERE repo_id = ? + ORDER BY started_at DESC LIMIT 1""", + (repo_id,), + ).fetchone() + return { + "paused": self.is_paused(), + "events": count("events"), + "flushes": count("flushes"), + "retrievals": count("retrievals"), + "sidekick_runs": count("sidekick_runs"), + "last_operation": dict(last_operation) if last_operation else None, + "last_sidekick": dict(last_sidekick) if last_sidekick else None, + } + + +def _session_id(hook_input: dict[str, Any]) -> str: + return str(hook_input.get("session_id") or "unknown-session") + + +def record_session_start(store: EvidenceStore, hook_input: dict[str, Any]) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + store.record_event( + repo, + session_id, + "session_start", + { + "source": hook_input.get("source", "startup"), + "model": bounded(hook_input.get("model", ""), 200), + "branch": repo.branch, + "head_sha": repo.head_sha, + }, + ) + telemetry.record( + "session_start", + repo=repo, + session_id=session_id, + trigger=bounded(str(hook_input.get("source", "startup")), 60), + model=bounded(hook_input.get("model", ""), 200), + api_key_configured=bool(api_key()), + is_git_repo=not repo.identity.startswith("local:"), + ) + + +def record_user_prompt( + store: EvidenceStore, hook_input: dict[str, Any] +) -> tuple[RepoContext, str, str, bool]: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + prompt = redact(hook_input.get("prompt", "")).strip() + is_first_prompt = not store.has_event(repo.identity, session_id, "user_prompt") + store.record_event(repo, session_id, "user_prompt", {"text": prompt}) + return repo, session_id, prompt, is_first_prompt + + +def _tool_result_preview(response: Any) -> str: + if isinstance(response, dict): + selected = {} + for key in ( + "stdout", + "stderr", + "output", + "content", + "error", + "filePath", + "success", + "interrupted", + ): + if key in response: + selected[key] = response[key] + response = selected or {"keys": sorted(response.keys())[:20]} + return bounded(response, MAX_RESULT_CHARS) + + +def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> dict[str, Any]: + name = str(hook_input.get("tool_name") or "unknown") + tool_input = hook_input.get("tool_input") or {} + if not isinstance(tool_input, dict): + tool_input = {} + payload: dict[str, Any] = { + "tool": name, + "failed": failed, + "duration_ms": hook_input.get("duration_ms"), + "agent_role": "sidekick" if hook_input.get("agent_id") else "main", + } + if hook_input.get("agent_id"): + payload["agent_id"] = bounded(hook_input["agent_id"], 200) + if hook_input.get("agent_type"): + payload["agent_type"] = bounded(hook_input["agent_type"], 200) + + if name in {"Read", "Write", "Edit", "MultiEdit", "NotebookEdit"}: + path = tool_input.get("file_path") or tool_input.get("notebook_path") + if path: + payload["path"] = bounded(path, 1000) + if name in {"Write", "Edit", "MultiEdit", "NotebookEdit"}: + payload["mutation_chars"] = sum( + len(str(tool_input.get(key, ""))) + for key in ("content", "new_string", "new_source", "edits") + ) + elif name == "Bash" or "command" in tool_input: + command = bounded(tool_input.get("command", ""), MAX_COMMAND_CHARS) + payload["command"] = command + payload["command_kind"] = ( + "test" + if TEST_COMMAND_RE.search(command) + else "build" + if BUILD_COMMAND_RE.search(command) + else "shell" + ) + response = ( + hook_input.get("error") if failed else hook_input.get("tool_response") + ) + payload["result_preview"] = _tool_result_preview(response) + elif name in {"Grep", "Glob", "WebSearch", "WebFetch"}: + for key in ("pattern", "path", "query", "url"): + if tool_input.get(key): + payload[key] = bounded(tool_input[key], 1000) + else: + payload["input_keys"] = sorted(tool_input.keys())[:20] + if failed: + payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS) + + if failed and "error" not in payload: + payload["error"] = bounded(hook_input.get("error", ""), MAX_RESULT_CHARS) + return payload + + +def record_tool( + store: EvidenceStore, hook_input: dict[str, Any], *, failed: bool | None = False +) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + payload = tool_payload(hook_input, failed=failed) + if payload.get("path"): + payload["repo_path"] = _repo_relative_path(repo, str(payload["path"])) + store.record_event( + repo, + session_id, + "tool_failure" if failed else "tool_result", + payload, + ) + + +def record_sidekick_start( + store: EvidenceStore, hook_input: dict[str, Any], *, inject_context: bool = True +) -> str: + """Record a native sidekick and reuse the main turn's retrieved memories.""" + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200) + agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + context = combine_context( + format_context(store.injected_memories(session_id, repo.identity)) + ) + if not inject_context: + context = "" + first_start = store.start_sidekick( + repo, session_id, agent_id, agent_type, len(context) + ) + store.record_event( + repo, + session_id, + "sidekick_start", + { + "agent_id": agent_id, + "agent_type": agent_type, + "context_chars": len(context) if first_start else 0, + "worktree_root": bounded(repo.root, 2000), + }, + ) + telemetry.record( + "sidekick", + repo=repo, + session_id=session_id, + phase="start", + first_start=first_start, + context_chars=len(context) if first_start else 0, + ) + return context if first_start else "" + + +def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: + session_id = _session_id(hook_input) + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_id = bounded(hook_input.get("agent_id", ""), 200) + final_message = redact(hook_input.get("last_assistant_message", "")).strip() + transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000) + agent_id = store.stop_sidekick( + repo, + session_id, + agent_id, + agent_type, + transcript_path, + final_message, + ) + store.record_event( + repo, + session_id, + "sidekick_stop", + { + "agent_id": agent_id, + "agent_type": agent_type, + "transcript_path": transcript_path, + "final_message": final_message, + }, + ) + telemetry.record( + "sidekick", + repo=repo, + session_id=session_id, + phase="stop", + has_transcript=bool(transcript_path), + message_chars=len(final_message), + ) + + +def _ordered_unique(values: Iterable[str]) -> list[str]: + seen: set[str] = set() + result = [] + for value in values: + if value and value not in seen: + seen.add(value) + result.append(value) + return result + + +def _repo_relative_path(repo: RepoContext, value: str) -> str: + value = str(value or "").strip() + if not value: + return "" + try: + path = Path(value) + if path.is_absolute(): + try: + return path.resolve().relative_to(Path(repo.root).resolve()).as_posix() + except ValueError: + return "" + except (OSError, ValueError): + pass + return bounded(value, 1000) + + +def _render_command_lines(commands: list[dict[str, str]]) -> list[str]: + lines = [] + for command in commands: + line = f"- [{command['status']}/{command['kind']}] {command['command']}" + if command["result"]: + line += f" — {bounded(command['result'], 500).replace(chr(10), ' ')}" + lines.append(line) + return lines + + +def build_episode( + repo: RepoContext, + session_id: str, + packet_id: str, + events: list[dict[str, Any]], + *, + canonical_task: str = "", + task_outcome: str = "", +) -> tuple[str, dict[str, Any]]: + prompts = [ + redact(e["payload"].get("text", "")).strip() + for e in events + if e["kind"] == "user_prompt" and e["payload"].get("text") + ] + assistant_conclusions = [ + redact(e["payload"].get("text", "")).strip() + for e in events + if e["kind"] == "assistant_stop" and e["payload"].get("text") + ] + sidekick_outcomes = [ + redact(e["payload"].get("final_message", "")).strip() + for e in events + if e["kind"] == "sidekick_stop" and e["payload"].get("final_message") + ] + tools = [ + e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"} + and e["payload"].get("agent_role", "main") == "main" + ] + read_paths = _ordered_unique( + _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", ""))) + for t in tools + if t.get("tool") == "Read" + ) + modified_paths = _ordered_unique( + _repo_relative_path(repo, str(t.get("repo_path") or t.get("path", ""))) + for t in tools + if t.get("tool") in {"Write", "Edit", "MultiEdit", "NotebookEdit"} + ) + searches = [ + {key: t[key] for key in ("tool", "pattern", "path", "query", "url") if key in t} + for t in tools + if t.get("tool") in {"Grep", "Glob", "WebSearch", "WebFetch"} + ] + commands = [ + { + "command": t.get("command", ""), + "kind": t.get("command_kind", "shell"), + "status": "unknown" if t.get("failed", False) is None else "failed" if t.get("failed") else "succeeded", + "result": t.get("result_preview", ""), + } + for t in tools + if t.get("command") + ] + + task = bounded(canonical_task or (prompts[0] if prompts else ""), 4000) + conclusion = redact(assistant_conclusions[-1] if assistant_conclusions else "").strip() + outcome = bounded(task_outcome, 2000) + + extraction_messages: list[dict[str, str]] = [] + pending_user_messages: list[dict[str, str]] = [] + if task and not prompts: + pending_user_messages.append({"role": "user", "content": task}) + for event in events: + if event["kind"] == "user_prompt" and event["payload"].get("text"): + pending_user_messages.append( + { + "role": "user", + "content": redact(event["payload"].get("text", "")).strip(), + } + ) + elif event["kind"] == "assistant_stop": + transcript_messages = event["payload"].get("transcript_messages") or [] + if isinstance(transcript_messages, list) and transcript_messages: + transcript_users = { + redact(message.get("content") or "").strip() + for message in transcript_messages + if isinstance(message, dict) and message.get("role") == "user" + } + extraction_messages.extend( + message + for message in pending_user_messages + if message["content"].strip() not in transcript_users + ) + extraction_messages.extend( + { + "role": str(message.get("role") or ""), + "content": redact(message.get("content") or "").strip(), + } + for message in transcript_messages + if isinstance(message, dict) + and message.get("role") in {"user", "assistant"} + and message.get("content") + ) + else: + extraction_messages.extend(pending_user_messages) + if event["payload"].get("text"): + extraction_messages.append( + { + "role": "assistant", + "content": redact(event["payload"].get("text", "")).strip(), + } + ) + pending_user_messages = [] + elif event["kind"] == "sidekick_stop": + pass + extraction_messages.extend(pending_user_messages) + + structured = { + "packet_id": packet_id, + "repo": repo.identity, + "app_id": repo.app_id, + "session_id": session_id, + "branch": repo.branch, + "head_sha": repo.head_sha, + "task": task, + "task_outcome": outcome, + "assistant_conclusion": conclusion, + "user_messages": prompts, + "assistant_outcomes": assistant_conclusions, + "sidekick_outcomes": sidekick_outcomes, + "extraction_messages": extraction_messages, + "files_read": read_paths[:50], + "files_modified": modified_paths[:50], + "searches": searches[-30:], + "commands": commands[-30:], + } + lines = ["Coding-session episode"] + if task: + lines.extend(["", "Task:", task]) + if modified_paths: + lines.extend( + ["", "Files modified:", *[f"- {path}" for path in modified_paths[:50]]] + ) + if read_paths: + lines.extend(["", "Files read:", *[f"- {path}" for path in read_paths[:50]]]) + if commands: + lines.append("") + lines.append("Observed commands:") + lines.extend(_render_command_lines(commands[-30:])) + if searches: + lines.extend( + [ + "", + "Observed searches:", + *[ + f"- {json.dumps(item, ensure_ascii=False, sort_keys=True)}" + for item in searches[-20:] + ], + ] + ) + if conclusion: + lines.extend(["", "Agent conclusion:", conclusion]) + if outcome: + lines.extend(["", "Task outcome:", outcome]) + lines.extend( + [ + "", + f"Provenance: repo={repo.identity}; branch={repo.branch}; head={repo.head_sha}; packet={packet_id}", + ] + ) + content = "\n".join(lines) + return bounded(content, MAX_EPISODE_CHARS), structured + + +def build_semantic_evidence(structured: dict[str, Any]) -> str: + """Format changed paths for memory extraction. + + Test and build results remain in the local evidence store for diagnostics, + but are not useful repository knowledge by default and should not steer + memory extraction toward transient verification details. + """ + modified_paths = [ + bounded(path, 500) for path in structured.get("files_modified", [])[:20] + ] + commands = structured.get("commands") or [] + if not any(command.get("status") == "failed" for command in commands): + commands = [] + + if not modified_paths and not commands: + return "" + + lines = ["Additional repository details from this session"] + if modified_paths: + lines.extend( + [ + "", + "Changed paths:", + *[f"- {path}" for path in modified_paths], + ] + ) + if commands: + lines.extend(["", "Commands run in this session:", *_render_command_lines(commands)]) + return bounded("\n".join(lines), 8000) + + +def build_extraction_messages(structured: dict[str, Any]) -> list[dict[str, str]]: + """Build the session messages sent to Mem0 for memory extraction.""" + evidence = build_semantic_evidence(structured) + messages = [ + {"role": message["role"], "content": redact(message["content"]).strip()} + for message in structured.get("extraction_messages", []) + if message.get("role") in {"user", "assistant"} and message.get("content") + ] + if evidence: + for message in reversed(messages): + if message["role"] == "assistant": + message["content"] = f"{message['content']}\n\n{evidence}" + break + else: + messages.append({"role": "assistant", "content": evidence}) + + return messages + + +def _estimated_tokens(value: str) -> int: + """Conservatively estimate tokens without adding a tokenizer dependency.""" + ascii_chars = sum(ord(char) < 128 for char in value) + return math.ceil((ascii_chars * 0.4) + (len(value) - ascii_chars)) + + +def _message_tokens(messages: list[dict[str, str]]) -> int: + return _estimated_tokens(json.dumps(messages, ensure_ascii=False)) + + +def _is_agent_assignment(message: dict[str, str]) -> bool: + return message.get("role") == "assistant" and message.get( + "content", "" + ).startswith("Subagent assignment (") + + +def _is_agent_response(message: dict[str, str]) -> bool: + return message.get("role") == "assistant" and message.get( + "content", "" + ).startswith("Subagent response (") + + +def extraction_message_batches( + messages: list[dict[str, str]], + *, + max_tokens: int = MAX_EXTRACTION_INPUT_TOKENS, +) -> list[list[dict[str, str]]]: + """Keep exchanges together when possible; split oversized messages to enforce the request budget.""" + if not messages or _message_tokens(messages) <= max_tokens: + return [messages] + + exchanges: list[list[dict[str, str]]] = [] + exchange: list[dict[str, str]] = [] + for message in messages: + if message.get("role") == "user" and exchange: + exchanges.append(exchange) + exchange = [] + exchange.append(message) + if exchange: + exchanges.append(exchange) + + units: list[list[dict[str, str]]] = [] + for exchange in exchanges: + if _message_tokens(exchange) <= max_tokens: + units.append(exchange) + continue + index = 0 + while index < len(exchange): + message = exchange[index] + if ( + _is_agent_assignment(message) + and index + 1 < len(exchange) + and _is_agent_response(exchange[index + 1]) + ): + units.append(exchange[index : index + 2]) + index += 2 + else: + units.append([message]) + index += 1 + + bounded_units: list[list[dict[str, str]]] = [] + for unit in units: + if _message_tokens(unit) <= max_tokens: + bounded_units.append(unit) + continue + for message in unit: + remaining = message["content"] + while remaining: + low, high = 0, len(remaining) + while low < high: + middle = (low + high + 1) // 2 + if _message_tokens([{**message, "content": remaining[:middle]}]) <= max_tokens: + low = middle + else: + high = middle - 1 + if low == 0: + raise ValueError("Extraction token budget cannot fit a message") + bounded_units.append([{**message, "content": remaining[:low]}]) + remaining = remaining[low:] + + batches: list[list[dict[str, str]]] = [] + batch: list[dict[str, str]] = [] + for unit in bounded_units: + candidate = [*batch, *unit] + if batch and _message_tokens(candidate) > max_tokens: + batches.append(batch) + batch = list(unit) + else: + batch = candidate + if batch: + batches.append(batch) + return batches + + +def _request_json( + url: str, key: str, payload: dict[str, Any], timeout: float +) -> tuple[dict[str, Any] | list[Any], int, int]: + raw = json.dumps(payload, ensure_ascii=False).encode() + request = urllib.request.Request( + url, + data=raw, + headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + method="POST", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + response_raw = response.read() + parsed = json.loads(response_raw or b"{}") + return parsed, len(raw), len(response_raw) + + +def _request_json_with_network_retry( + url: str, key: str, payload: dict[str, Any], timeout: float +) -> tuple[dict[str, Any] | list[Any], int, int]: + """Retry one transient connection failure without retrying API responses.""" + try: + return _request_json(url, key, payload, timeout) + except urllib.error.HTTPError: + raise + except (urllib.error.URLError, TimeoutError, OSError): + time.sleep(0.25) + return _request_json(url, key, payload, timeout) + + +def _get_json( + url: str, key: str, timeout: float +) -> tuple[dict[str, Any] | list[Any], int]: + request = urllib.request.Request( + url, + headers={"Authorization": f"Token {key}", "Content-Type": "application/json"}, + method="GET", + ) + with urllib.request.urlopen(request, timeout=timeout) as response: + response_raw = response.read() + return json.loads(response_raw or b"{}"), len(response_raw) + + +def _event_id(response: dict[str, Any] | list[Any]) -> str: + return str(response.get("event_id", "")) if isinstance(response, dict) else "" + + +def _stored_event_ids(value: Any) -> list[str]: + raw = str(value or "") + if not raw.startswith("["): + return [] + try: + parsed = json.loads(raw) + except json.JSONDecodeError: + return [] + return [str(item or "") for item in parsed] if isinstance(parsed, list) else [] + + +def _result_count(response: dict[str, Any] | list[Any]) -> int: + if isinstance(response, dict): + results = response.get("results") + return len(results) if isinstance(results, list) else 0 + return len(response) if isinstance(response, list) else 0 + + +def touch_handoff_heartbeat() -> None: + """Mark the worker's handoff file alive so recovery does not relaunch it.""" + path = os.environ.get("MEM0_CODE_HANDOFF_PATH", "") + if not path: + return + try: + os.utime(path) + except OSError: + pass + + +def _wait_for_event(api_url: str, key: str, event_id: str) -> tuple[str, int, int]: + """Wait for extraction to finish before a later task can search the store.""" + if not event_id: + return "MISSING", 0, 0 + wait_seconds = float(os.environ.get("MEM0_CODE_EXTRACTION_WAIT_SECONDS", "120")) + poll_seconds = max(float(os.environ.get("MEM0_CODE_EVENT_POLL_SECONDS", "1")), 0.1) + deadline = time.monotonic() + wait_seconds + response_chars = 0 + while time.monotonic() < deadline: + touch_handoff_heartbeat() + try: + response, size = _get_json( + f"{api_url}/v1/event/{event_id}/", + key, + min(10, poll_seconds + 5), + ) + except urllib.error.HTTPError as exc: + if exc.code not in {408, 429} and exc.code < 500: + raise + time.sleep(poll_seconds) + continue + except (urllib.error.URLError, TimeoutError, OSError): + # The extraction job is durable server-side. A transient polling + # failure must not discard a job that may still complete normally. + time.sleep(poll_seconds) + continue + response_chars += size + status = ( + str(response.get("status", "UNKNOWN")) + if isinstance(response, dict) + else "UNKNOWN" + ) + if status in {"SUCCEEDED", "FAILED"}: + return status, response_chars, _result_count(response) + time.sleep(poll_seconds) + return "TIMEOUT", response_chars, 0 + + +def _record_flush( + repo: RepoContext, + session_id: str, + reason: str, + status: str, + elapsed: float, + **extra: Any, +) -> None: + telemetry.record( + "flush", + repo=repo, + session_id=session_id, + reason=reason, + status=status, + success=status in {"semantic-succeeded", "nothing-to-flush"}, + duration_ms=round(elapsed, 2), + **extra, + ) + + +def flush_session( + store: EvidenceStore, hook_input: dict[str, Any], reason: str +) -> dict[str, Any]: + key = api_key() + if not key: + telemetry.record("flush", reason=reason, status="local-only", success=False) + return {"status": "local-only", "reason": "no-api-key"} + + session_id = _session_id(hook_input) + if session_id == "unknown-session": + telemetry.record("flush", reason=reason, status="no-session-id", success=False) + return {"status": "error", "reason": "no-session-id"} + repo = store.repo_for_session(session_id, hook_input.get("cwd")) + prepared = store.prepare_flush(repo, session_id, reason) + if prepared is None: + return {"status": "nothing-to-flush"} + packet_id, events = prepared + existing_flush = store.flush_record(packet_id) or {} + + _, structured = build_episode( + repo, + session_id, + packet_id, + events, + canonical_task=bounded(hook_input.get("task", ""), 4000), + task_outcome=bounded(hook_input.get("task_outcome", ""), 2000), + ) + + metadata = {"source": _harness_source_tag} + if repo.branch and repo.branch not in {"detached", "unknown"}: + metadata["branch"] = repo.branch + if repo.head_sha: + metadata["git_sha"] = repo.head_sha + api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + add_url = f"{api_url}/v3/memories/add/" + + write_user = _scope_value(user_id()) + write_project = _scope_value(repo.project_id) + if not write_user or not _scope_value(repo.app_id) or not write_project: + telemetry.record("flush", reason=reason, status="unscoped", success=False) + return {"status": "error", "reason": "wildcard-scope"} + + body = { + "agent_id": write_project, + "user_id": write_user, + "app_id": repo.app_id, + "run_id": session_id, + "metadata": {**metadata, "author": write_user, "dirs": directory_chain(repo)}, + "agent_custom_instructions": PROJECT_MEMORY_INSTRUCTIONS, + "custom_instructions": PERSONAL_MEMORY_INSTRUCTIONS, + "custom_categories": CODING_MEMORY_CATEGORIES, + "infer": True, + } + + started = time.perf_counter() + try: + stored_events = _stored_event_ids(existing_flush.get("semantic_event_id")) + existing_event = ( + "" if stored_events else str(existing_flush.get("semantic_event_id") or "") + ) + if existing_event: + existing_status, existing_resp, existing_items = _wait_for_event( + api_url, key, existing_event + ) + if existing_status == "SUCCEEDED": + elapsed = (time.perf_counter() - started) * 1000 + store.update_flush( + packet_id, + status="semantic-succeeded", + semantic_event_id=existing_event, + error="", + ) + store.operation( + repo, + session_id, + "flush-retry", + elapsed, + True, + item_count=existing_items, + response_chars=existing_resp, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-succeeded", + elapsed, + memory_count=existing_items, + resumed=True, + ) + effective_reason = str( + (store.flush_record(packet_id) or {}).get("reason") or reason + ) + if ( + store.has_unflushed_events(repo.identity, session_id) + and not store.unflushed_starts_with_session_start( + repo.identity, session_id + ) + and ( + effective_reason != "periodic" + or store.checkpoint_due(repo.identity, session_id) + ) + ): + return flush_session(store, hook_input, effective_reason) + return { + "status": "semantic-succeeded", + "packet_id": packet_id, + "semantic_event_id": existing_event, + "semantic_status": existing_status, + "memory_count": existing_items, + "duration_ms": round(elapsed, 2), + "resumed": True, + } + if existing_status == "TIMEOUT": + elapsed = (time.perf_counter() - started) * 1000 + error = "semantic extraction event timed out" + store.update_flush(packet_id, status="semantic-timeout", error=error) + store.operation( + repo, + session_id, + "flush-retry", + elapsed, + False, + response_chars=existing_resp, + error=error, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-timeout", + elapsed, + resumed=True, + error_kind="timeout", + ) + return { + "status": "semantic-timeout", + "packet_id": packet_id, + "semantic_event_id": existing_event, + "duration_ms": round(elapsed, 2), + "resumed": True, + } + + message_batches = [ + batch + for batch in extraction_message_batches( + build_extraction_messages(structured) + ) + if batch + ] + batches = [(body, messages) for messages in message_batches] + if not batches: + store.update_flush(packet_id, status="semantic-succeeded", error="") + return {"status": "nothing-to-flush", "packet_id": packet_id} + operation_name = "flush-retry" if stored_events else "flush" + semantic_events = stored_events[: len(batches)] + semantic_events += [""] * (len(batches) - len(semantic_events)) + semantic_req = 0 + semantic_resp = 0 + for index, (body, messages) in enumerate(batches): + if semantic_events[index]: + continue + semantic_response, request_chars, response_chars = _request_json( + add_url, + key, + {**body, "messages": messages}, + 15, + ) + semantic_events[index] = _event_id(semantic_response) + semantic_req += request_chars + semantic_resp += response_chars + store.update_flush( + packet_id, + status="semantic-queued", + semantic_event_id=json.dumps(semantic_events), + ) + + semantic_event = semantic_events[-1] + semantic_status = "SUCCEEDED" + event_resp = 0 + semantic_items = 0 + failed_event = semantic_event + for index, queued_event in enumerate(semantic_events): + status, response_chars, item_count = _wait_for_event( + api_url, key, queued_event + ) + event_resp += response_chars + semantic_items += item_count + if status != "SUCCEEDED": + semantic_status = status + failed_event = queued_event + if status in {"FAILED", "MISSING"}: + semantic_events[index] = "" + store.update_flush( + packet_id, semantic_event_id=json.dumps(semantic_events) + ) + break + if semantic_status != "SUCCEEDED": + elapsed = (time.perf_counter() - started) * 1000 + error = f"semantic extraction event {semantic_status.lower()}" + store.update_flush( + packet_id, status=f"semantic-{semantic_status.lower()}", error=error + ) + store.operation( + repo, + session_id, + operation_name, + elapsed, + False, + item_count=semantic_items, + request_chars=semantic_req, + response_chars=semantic_resp + event_resp, + error=error, + ) + _record_flush( + repo, + session_id, + reason, + f"semantic-{semantic_status.lower()}", + elapsed, + memory_count=semantic_items, + batch_count=len(batches), + error_kind=telemetry.error_kind(error), + ) + return { + "status": f"semantic-{semantic_status.lower()}", + "packet_id": packet_id, + "semantic_event_id": failed_event, + "memory_count": semantic_items, + "duration_ms": round(elapsed, 2), + } + + elapsed = (time.perf_counter() - started) * 1000 + store.update_flush( + packet_id, + status="semantic-succeeded", + semantic_event_id=json.dumps(semantic_events), + error="", + ) + store.operation( + repo, + session_id, + operation_name, + elapsed, + True, + item_count=semantic_items, + request_chars=semantic_req, + response_chars=semantic_resp + event_resp, + ) + _record_flush( + repo, + session_id, + reason, + "semantic-succeeded", + elapsed, + memory_count=semantic_items, + batch_count=len(batches), + request_chars=semantic_req, + ) + effective_reason = str( + (store.flush_record(packet_id) or {}).get("reason") or reason + ) + if ( + store.has_unflushed_events(repo.identity, session_id) + and not store.unflushed_starts_with_session_start( + repo.identity, session_id + ) + and ( + effective_reason != "periodic" + or store.checkpoint_due(repo.identity, session_id) + ) + ): + return flush_session(store, hook_input, effective_reason) + return { + "status": "semantic-succeeded", + "packet_id": packet_id, + "semantic_event_id": semantic_event, + "semantic_status": semantic_status, + "memory_count": semantic_items, + "duration_ms": round(elapsed, 2), + } + except Exception as exc: # hooks must fail open + elapsed = (time.perf_counter() - started) * 1000 + error = bounded(str(exc), 1000) + store.update_flush(packet_id, status="error", error=error) + store.operation(repo, session_id, "flush", elapsed, False, error=error) + _record_flush( + repo, + session_id, + reason, + "error", + elapsed, + error_kind=telemetry.error_kind(exc), + ) + return {"status": "error", "packet_id": packet_id, "error": error} + + +def checkpoint_session( + store: EvidenceStore, hook_input: dict[str, Any], reason: str +) -> dict[str, Any]: + """Run remote extraction at a durable boundary.""" + return flush_session(store, hook_input, reason) + + + +def search_memories( + store: EvidenceStore | None, + repo: RepoContext, + session_id: str | None, + query: str, + *, + top_k: int | None = None, + category: str | None = None, + scope: str | None = None, + run_id: str | None = None, + operation: str = "search", + timeout: float = 5, +) -> MemorySearchResult: + key = api_key() + if not key or not query.strip(): + return MemorySearchResult(False, 0, 0, []) + search_once = os.environ.get( + "MEM0_CODE_SEARCH_ONCE_PER_SESSION", "false" + ).lower() in { + "1", + "true", + "yes", + "on", + } + track_session = store is not None and bool(session_id) + if ( + search_once + and track_session + and store.has_operation(repo.identity, session_id, "search") + ): + return MemorySearchResult(False, 0, 0, []) + + result_limit = min( + max( + top_k + if top_k is not None + else _int_option("top_k", "MEM0_CODE_TOP_K", 3), + 1, + ), + 20, + ) + if category is not None and category not in CODING_MEMORY_CATEGORY_NAMES: + raise ValueError(f"Unknown memory category: {category}") + user, project = _scope_value(user_id()), _scope_value(repo.project_id) + if not user or not project or not _scope_value(repo.app_id): + return MemorySearchResult(False, 0, 0, []) + filters = _search_filters(user, repo, resolve_search_scope(scope)) + if category: + filters = {"AND": [filters, {"categories": {"contains": category}}]} + if run_id: + filters = {"AND": [filters, {"run_id": run_id}]} + payload = { + "query": query, + "app_id": repo.app_id, + "filters": filters, + "top_k": result_limit, + "rerank": False, + "latest_only": True, + } + url = ( + os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + + "/v3/memories/search/" + ) + started = time.perf_counter() + try: + response, request_chars, response_chars = _request_json_with_network_retry( + url, key, payload, timeout + ) + memories = ( + response if isinstance(response, list) else response.get("results", []) + ) + memories = [ + memory + for memory in memories + if isinstance(memory, dict) + and (memory.get("metadata") or {}).get("record_kind") != "task_episode" + ][:result_limit] + if track_session: + returned_memories = store.unseen(session_id, repo.identity, memories) + store.mark_injected(session_id, repo.identity, returned_memories) + already_shown_count = len(memories) - len(returned_memories) + else: + returned_memories = memories + already_shown_count = 0 + elapsed = (time.perf_counter() - started) * 1000 + if track_session: + store.operation( + repo, + session_id, + operation, + elapsed, + True, + item_count=len(returned_memories), + request_chars=request_chars, + response_chars=response_chars, + ) + telemetry.record( + "search", + repo=repo, + session_id=session_id, + trigger=operation, + success=True, + duration_ms=round(elapsed, 2), + matched_count=len(memories), + returned_count=len(returned_memories), + already_shown_count=already_shown_count, + top_k=result_limit, + has_category=bool(category), + ) + return MemorySearchResult( + succeeded=True, + matched_count=len(memories), + already_shown_count=already_shown_count, + memories=returned_memories, + ) + except Exception as exc: + elapsed = (time.perf_counter() - started) * 1000 + if track_session: + store.operation(repo, session_id, operation, elapsed, False, error=str(exc)) + telemetry.record( + "search", + repo=repo, + session_id=session_id, + trigger=operation, + success=False, + duration_ms=round(elapsed, 2), + top_k=result_limit, + has_category=bool(category), + error_kind=telemetry.error_kind(exc), + ) + return MemorySearchResult(False, 0, 0, []) + + +def format_context( + memories: list[dict[str, Any]], + heading: str = "Relevant repository memories:", +) -> str: + if not memories: + return "" + limit = min( + max( + _int_option( + "max_context_chars", + "MEM0_CODE_MAX_CONTEXT_CHARS", + DEFAULT_MAX_CONTEXT_CHARS, + ), + 1000, + ), + 10000, + ) + lines = [heading] if heading else [] + for memory in memories: + text = re.sub( + r"\s+", + " ", + redact(memory.get("memory") or memory.get("text") or ""), + ) + text = text.strip() + if not text: + continue + branch = str((memory.get("metadata") or {}).get("branch") or "").strip() + branch_label = ( + f" [learnt on branch {branch}]" + if branch.casefold() not in {"", "main", "master", "unknown", "detached"} + else "" + ) + number = len(lines) if heading else len(lines) + 1 + entry = f"{number}. {text}{branch_label}" + candidate = "\n".join([*lines, entry]) + if len(candidate) <= limit: + lines.append(entry) + continue + if not lines or (heading and len(lines) == 1): + prefix = f"{number}. " + suffix = f"…{branch_label}" + available = ( + limit + - len("\n".join(lines)) + - (1 if lines else 0) + - len(prefix) + - len(suffix) + ) + if available > 0: + lines.append(prefix + text[:available].rstrip() + suffix) + break + minimum_lines = 2 if heading else 1 + return "\n".join(lines) if len(lines) >= minimum_lines else "" + + +def format_search_result(result: MemorySearchResult) -> str: + """Return only the text the coding agent needs from an explicit memory search.""" + if not result.succeeded: + return "Memory search failed." + if result.memories: + rendered = format_context(result.memories, heading="") + if rendered: + return rendered + return "No matching memories found." + + +def combine_context(*contexts: str) -> str: + """Combine memory sources under one hard budget without repeated lines.""" + seen: set[str] = set() + lines: list[str] = [] + for context in contexts: + for line in str(context or "").splitlines(): + normalized = re.sub(r"\s+", " ", line).strip().casefold() + if not normalized or normalized in seen: + continue + seen.add(normalized) + lines.append(line.rstrip()) + limit = min( + max( + _int_option( + "max_context_chars", + "MEM0_CODE_MAX_CONTEXT_CHARS", + DEFAULT_MAX_CONTEXT_CHARS, + ), + 1000, + ), + 10000, + ) + return bounded("\n".join(lines), limit) if lines else "" + + +def _scoped_memory_ids( + api_url: str, key: str, user: str, repo: RepoContext, include_project: bool +) -> list[str]: + """List this user's memory ids for this repository, plus the shared project memory when asked.""" + ids: list[str] = [] + seen: set[str] = set() + prefix = repo.app_id + _collect_memory_ids( + api_url, key, {"user_id": user}, ids, seen, + app_id_prefix=prefix, + ) + if include_project: + for project_id in _shared_project_ids(repo): + _collect_memory_ids( + api_url, key, {"agent_id": project_id}, ids, seen, + app_id_prefix=prefix, + ) + return ids + + +def _collect_memory_ids( + api_url: str, + key: str, + filters: dict[str, Any], + ids: list[str], + seen: set[str], + *, + app_id_prefix: str = "", +) -> None: + """Page through one list filter; the list endpoint returns nothing for an OR whose user branch has no memories.""" + payload = {"filters": filters} + for page in range(1, FORGET_MAX_PAGES + 1): + parsed, _, _ = _request_json( + f"{api_url}/v2/memories/?page={page}&page_size={FORGET_PAGE_SIZE}", + key, + payload, + 15, + ) + items = parsed.get("results") if isinstance(parsed, dict) else parsed + if not isinstance(items, list) or not items: + break + for item in items: + if not isinstance(item, dict): + continue + memory_id = str(item.get("id", "")) + if not memory_id or memory_id in seen: + continue + if app_id_prefix: + item_app_id = str(item.get("app_id") or "") + if item_app_id != app_id_prefix and not item_app_id.startswith(app_id_prefix + "/"): + continue + seen.add(memory_id) + ids.append(memory_id) + if len(items) < FORGET_PAGE_SIZE: + break + + +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"}, + method="DELETE", + ) + try: + with urllib.request.urlopen(request, timeout=15): + return True + except Exception: + return False + + +def forget_remote_repo( + repo: RepoContext, *, include_project_memory: bool = False +) -> dict[str, Any]: + """Delete this user's memories for this repository; project memory is shared, so only on request.""" + key = api_key() + if not key: + telemetry.record("forget", repo=repo, success=False, error_kind="no-api-key") + return {"status": "error", "error": "Mem0 API key is not configured"} + user = _scope_value(user_id()) + if not user or not _scope_value(repo.app_id) or not _scope_value(repo.project_id): + telemetry.record("forget", repo=repo, success=False, error_kind="unscoped") + return { + "status": "error", + "error": "Refusing to forget: the user or repository scope is a wildcard", + } + api_url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + try: + memory_ids = _scoped_memory_ids(api_url, key, user, repo, include_project_memory) + except Exception as exc: + telemetry.record( + "forget", repo=repo, success=False, error_kind=telemetry.error_kind(exc) + ) + return {"status": "error", "error": bounded(str(exc), 1000)} + deleted = sum(_delete_memory(api_url, key, memory_id) for memory_id in memory_ids) + failed = len(memory_ids) - deleted + telemetry.record("forget", repo=repo, success=not failed, item_count=deleted) + if failed: + return { + "status": "partial", + "deleted": deleted, + "failed": failed, + "error": f"{failed} of {len(memory_ids)} memories could not be deleted", + } + return {"status": "deleted", "deleted": deleted} + + +def _doctor_mem0_authentication(repo: RepoContext) -> dict[str, Any]: + """Verify the configured key with one read-only, repository-scoped search.""" + key = api_key() + if not key: + return {"ok": False, "detail": "API key missing"} + payload = { + "query": "Mem0 authentication check", + "filters": { + "AND": [ + {"user_id": user_id()}, + {"app_id": repo.app_id}, + ] + }, + "top_k": 1, + "threshold": 1.0, + "rerank": False, + } + url = os.environ.get("MEM0_API_URL", DEFAULT_API_URL).rstrip("/") + started = time.perf_counter() + try: + _request_json(f"{url}/v3/memories/search/", key, payload, 5) + except Exception as exc: + return {"ok": False, "detail": bounded(str(exc), 300)} + elapsed = (time.perf_counter() - started) * 1000 + return {"ok": True, "detail": f"connected ({elapsed:.0f} ms)"} + + +def _doctor_user_id() -> dict[str, Any]: + """Flag a configured user ID the plugin refuses, since the silent fallback surprises people.""" + configured = _plugin_option("user_id", "MEM0_CODE_USER_ID") or os.environ.get( + "MEM0_USER_ID", "" + ) + if configured and not _scope_value(configured): + return { + "ok": False, + "detail": f"configured user_id {configured!r} is a wildcard; using {user_id()!r}", + } + return {"ok": True, "detail": user_id()} + + +def doctor(cwd: str | None = None) -> dict[str, Any]: + repo = resolve_repo(cwd) + directory = data_dir() + directory.mkdir(parents=True, exist_ok=True) + checks: dict[str, dict[str, Any]] = { + "python": { + "ok": tuple(sys.version_info[:2]) >= (3, 10), + "detail": f"{sys.version_info.major}.{sys.version_info.minor}", + }, + "data_directory": { + "ok": os.access(directory, os.W_OK), + "detail": str(directory), + }, + "mem0_api_key": { + "ok": bool(api_key()), + "detail": "configured" if api_key() else "missing", + }, + "repository": { + "ok": bool(repo.identity), + "detail": repo.identity, + }, + "user_id": _doctor_user_id(), + "mem0_authentication": _doctor_mem0_authentication(repo), + } + return { + "ok": all(bool(value["ok"]) for value in checks.values()), + "plugin_version": PLUGIN_VERSION, + "repo_id": repo.identity, + "app_id": repo.app_id, + "user_id": user_id(), + "checks": checks, + } diff --git a/integrations/mem0-agent-plugin/core/telemetry.py b/integrations/mem0-agent-plugin/core/telemetry.py new file mode 100644 index 000000000..249595475 --- /dev/null +++ b/integrations/mem0-agent-plugin/core/telemetry.py @@ -0,0 +1,397 @@ +#!/usr/bin/env python3 +"""Anonymous usage telemetry for Mem0 agent plugins. + +Hooks run on a 3-6 second budget and fire on every tool call, so recording never +touches the network: `record` appends one JSON line to a local spool and returns. +A detached `python3 telemetry.py` drains the spool in one batched PostHog request, +started once per session and again from the flush worker that is already detached. + +Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false. + +Never sends prompts, memory text, queries, file paths, repository names, or API +keys: only event names, durations, counts, coarse outcomes, and salted hashes. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import platform +import subprocess +import sys +import time +import urllib.error +import urllib.request +import uuid +from pathlib import Path +from typing import Any + +import memory_core + +_harness: str = "generic" +_source_tag: str = "MEM0_PLUGIN" +_PRIVATE_KEYS = { + "apikey", + "authorization", + "password", + "query", + "secret", + "prompt", + "token", + "text", + "memory", + "message", + "error", + "path", + "cwd", + "userid", + "agentid", + "runid", + "repoid", + "repositoryid", + "projectid", + "appid", + "filters", +} + + +def init(harness: str = "generic", source_tag: str = "") -> None: + global _harness, _source_tag + _harness = harness + _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN" + +POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" +POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/" +POSTHOG_BATCH_URL = "https://us.i.posthog.com/batch/" +EVENT_PREFIX = "code" +SPOOL_LIMIT_BYTES = 256 * 1024 +BATCH_SIZE = 100 +SEND_TIMEOUT = 5 +CLAIM_STALE_SECONDS = 120 +CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60 + + +def is_enabled() -> bool: + """Whether telemetry is switched on for this process.""" + return os.environ.get("MEM0_TELEMETRY", "true").strip().lower() not in { + "false", + "0", + "no", + "off", + } + + +def _digest(value: str, length: int = 16) -> str: + return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length] + + +def _safe_value(value: Any) -> Any: + if isinstance(value, str): + return memory_core.redact(value) + if isinstance(value, dict): + return { + key: _safe_value(item) + for key, item in value.items() + if "".join(character for character in str(key).lower() if character.isalnum()) + not in _PRIVATE_KEYS + } + if isinstance(value, (list, tuple)): + return [_safe_value(item) for item in value] + if value is None or isinstance(value, (bool, int, float)): + return value + return memory_core.redact(value) + + +def _spool_path() -> Path: + return memory_core.data_dir() / "telemetry.jsonl" + + +def _identity_path() -> Path: + return memory_core.data_dir() / "telemetry-identity.json" + + +def _read_identity() -> dict[str, str]: + try: + value = json.loads(_identity_path().read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + return {} + return value if isinstance(value, dict) else {} + + +def _write_identity(identity: dict[str, str]) -> None: + path = _identity_path() + temporary = path.with_suffix(f".{os.getpid()}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + temporary.write_text(json.dumps(identity), encoding="utf-8") + temporary.replace(path) + except OSError: + try: + temporary.unlink() + except OSError: + pass + + +def anonymous_id(identity: dict[str, str] | None = None) -> str: + """Per-machine anonymous identifier, created and persisted on first use.""" + identity = _read_identity() if identity is None else identity + existing = identity.get("anonymous_id") + if existing: + return existing + created = f"code-anon-{uuid.uuid4().hex}" + identity["anonymous_id"] = created + _write_identity(identity) + return created + + +def is_first_run() -> bool: + """Whether this machine has never recorded a plugin event before.""" + return not _identity_path().exists() + + +def record( + event: str, + *, + repo: Any = None, + session_id: str | None = None, + **properties: Any, +) -> None: + """Append one event to the local spool. Never blocks and never raises.""" + if not is_enabled(): + return + try: + spool = _spool_path() + try: + if spool.stat().st_size > SPOOL_LIMIT_BYTES: + return + except OSError: + pass + properties = _safe_value(properties) + properties.update( + harness=_harness, + plugin_version=memory_core.PLUGIN_VERSION, + os=sys.platform, + python_version=platform.python_version(), + ) + if repo is not None: + properties["repo_hash"] = _digest(getattr(repo, "identity", "")) + if session_id: + properties["session_hash"] = _digest(session_id) + line = json.dumps( + { + "event": f"{EVENT_PREFIX}.{event}", + "timestamp": memory_core.utc_now(), + "properties": { + key: value for key, value in properties.items() if value is not None + }, + }, + separators=(",", ":"), + default=str, + ) + spool.parent.mkdir(parents=True, exist_ok=True) + with spool.open("a", encoding="utf-8") as handle: + handle.write(line + "\n") + except Exception: + pass + + +def error_kind(exc: BaseException | str) -> str: + """Coarse, content-free label for a failure, safe to send.""" + text = exc if isinstance(exc, str) else f"{type(exc).__name__}: {exc}" + lowered = text.lower() + if "timed out" in lowered or "timeout" in lowered: + return "timeout" + if "401" in lowered or "403" in lowered or "unauthor" in lowered or "forbidden" in lowered: + return "auth" + if "429" in lowered or "rate limit" in lowered: + return "rate-limited" + if any(code in lowered for code in ("500", "502", "503", "504")): + return "server-error" + if "400" in lowered or "422" in lowered: + return "bad-request" + if isinstance(exc, str): + return "other" + if isinstance(exc, urllib.error.URLError): + return "network" + return type(exc).__name__ + + +def spawn_flush() -> bool: + """Start the detached sender that drains the spool.""" + if not is_enabled(): + return False + try: + if not _spool_path().exists() and not any( + memory_core.data_dir().glob("telemetry-*.sending") + ): + return False + subprocess.Popen( + [sys.executable, str(Path(__file__).resolve())], + stdin=subprocess.DEVNULL, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + close_fds=True, + **memory_core.detached_process_kwargs(), + ) + return True + except Exception: + return False + + +def _claim_spool() -> Path | None: + """Rename the spool aside so exactly one sender owns each batch.""" + directory = memory_core.data_dir() + claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending" + spool = _spool_path() + try: + spool.replace(claim) + return claim + except OSError: + pass + now = time.time() + for orphan in sorted(directory.glob("telemetry-*.sending")): + try: + age = now - orphan.stat().st_mtime + except OSError: + continue + if age > CLAIM_EXPIRY_SECONDS: + try: + orphan.unlink() + except OSError: + pass + continue + if age < CLAIM_STALE_SECONDS: + continue + try: + orphan.replace(claim) + return claim + except OSError: + continue + return None + + +def _resolve_email(key: str) -> str: + """Trade the API key for the account email so events join other Mem0 surfaces.""" + url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/" + request = urllib.request.Request( + url, headers={"Authorization": f"Token {key}", "Content-Type": "application/json"} + ) + try: + with urllib.request.urlopen(request, timeout=SEND_TIMEOUT) as response: + payload = json.loads(response.read().decode("utf-8")) + except Exception: + return "" + email = payload.get("user_email") if isinstance(payload, dict) else "" + return email if isinstance(email, str) else "" + + +def _post(payload: dict[str, Any], url: str) -> bool: + request = urllib.request.Request( + url, + data=json.dumps(payload, default=str).encode("utf-8"), + headers={"Content-Type": "application/json"}, + ) + try: + with urllib.request.urlopen(request, timeout=SEND_TIMEOUT): + return True + except Exception: + return False + + +def resolve_distinct_id() -> tuple[str, str]: + """Return the PostHog distinct id and the anonymous id it replaced, if any.""" + identity = _read_identity() + email = identity.get("email", "") + if email: + return email, "" + key = memory_core.api_key() + if not key: + return anonymous_id(identity), "" + email = _resolve_email(key) + if not email: + return anonymous_id(identity), "" + previous = identity.get("anonymous_id", "") + identity["email"] = email + _write_identity(identity) + return email, previous + + +def flush() -> int: + """Drain claimed spools to PostHog and return the number of events sent.""" + if not is_enabled(): + return 0 + claim = _claim_spool() + if claim is None: + return 0 + try: + lines = claim.read_text(encoding="utf-8").splitlines() + except OSError: + return 0 + events = [] + for line in lines: + try: + value = json.loads(line) + except json.JSONDecodeError: + continue + if isinstance(value, dict) and value.get("event"): + events.append(value) + if not events: + try: + claim.unlink() + except OSError: + pass + return 0 + + distinct_id, aliased_anonymous_id = resolve_distinct_id() + if aliased_anonymous_id: + _post( + { + "api_key": POSTHOG_API_KEY, + "event": "$identify", + "distinct_id": distinct_id, + "properties": { + "$anon_distinct_id": aliased_anonymous_id, + "$lib": "posthog-python", + }, + }, + POSTHOG_CAPTURE_URL, + ) + + sent = 0 + for start in range(0, len(events), BATCH_SIZE): + batch = [ + { + "event": event["event"], + "distinct_id": distinct_id, + "timestamp": event.get("timestamp"), + "properties": { + "source": _source_tag, + "language": "python", + "$process_person_profile": False, + "$lib": "posthog-python", + **(event.get("properties") or {}), + }, + } + for event in events[start : start + BATCH_SIZE] + ] + if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL): + return sent + sent += len(batch) + try: + claim.unlink() + except OSError: + pass + return sent + + +def main() -> int: + flush() + return 0 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except Exception: + raise SystemExit(0) diff --git a/integrations/mem0-agent-plugin/mcp.json b/integrations/mem0-agent-plugin/mcp.json new file mode 100644 index 000000000..dffd6771f --- /dev/null +++ b/integrations/mem0-agent-plugin/mcp.json @@ -0,0 +1,12 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/mcp.schema.json", + "mcpServers": { + "mem0": { + "type": "stdio", + "command": "python3", + "args": [ + "${PLUGIN_ROOT}/core/mcp_server.py" + ] + } + } +} diff --git a/integrations/mem0-agent-plugin/plugin.json b/integrations/mem0-agent-plugin/plugin.json new file mode 100644 index 000000000..2cbaa99de --- /dev/null +++ b/integrations/mem0-agent-plugin/plugin.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", + "name": "mem0", + "version": "0.3.1", + "description": "Cross-session memory and token savings for coding agents.", + "author": { + "name": "Mem0", + "email": "support@mem0.ai" + }, + "homepage": "https://docs.mem0.ai/integrations", + "repository": "https://github.com/mem0ai/mem0", + "license": "Apache-2.0", + "keywords": [ + "memory", + "coding-agents", + "continual-learning", + "token-efficiency" + ] +} diff --git a/integrations/mem0-agent-plugin/skills/forget/SKILL.md b/integrations/mem0-agent-plugin/skills/forget/SKILL.md new file mode 100644 index 000000000..0c272e9ff --- /dev/null +++ b/integrations/mem0-agent-plugin/skills/forget/SKILL.md @@ -0,0 +1,25 @@ +--- +name: forget +description: Delete the Mem0 memories stored for this repository and this user. Use when the user asks to forget, clear, wipe, or delete memories. +--- + +# Forget this repository's memories + +This permanently deletes remote memories. Before running anything, tell the +user exactly what will be deleted: their own memories for this repository +only. The repository's project memory is shared by everyone who works in it, +so it stays unless the user explicitly asks to delete that too. + +After the user confirms, run: + +```bash +python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "coding-agent" forget --remote --yes +``` + +If the user also asked to delete the repository's shared project memory, add +`--include-project-memory` and say that this removes it for every teammate. + +Report what the command output says was deleted. If the user only wants local +data cleared (evidence log, pending queue), run the same command without +`--remote`. Never pass `--yes` before the user has confirmed in this +conversation. diff --git a/integrations/mem0-agent-plugin/skills/pause/SKILL.md b/integrations/mem0-agent-plugin/skills/pause/SKILL.md new file mode 100644 index 000000000..c6316dd0b --- /dev/null +++ b/integrations/mem0-agent-plugin/skills/pause/SKILL.md @@ -0,0 +1,19 @@ +--- +name: pause +description: Pause Mem0 memory capture on this machine. Use when the user wants to stop memories being recorded, for example for private work or experiments. +--- + +# Pause memory capture + +To pause (hooks stop capturing and sending session content; a minimal +anonymous telemetry ping still fires at session start unless +`MEM0_TELEMETRY=false`): + +```bash +python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "coding-agent" pause +``` + +Confirm the new state back to the user, and remind them that already-created +memories still exist and remain searchable. Pending unsent packets are held +while paused, not expired, and are delivered after resuming. To turn capture +back on, use `/mem0:resume`. diff --git a/integrations/mem0-agent-plugin/skills/remember/SKILL.md b/integrations/mem0-agent-plugin/skills/remember/SKILL.md new file mode 100644 index 000000000..531a8b70b --- /dev/null +++ b/integrations/mem0-agent-plugin/skills/remember/SKILL.md @@ -0,0 +1,20 @@ +--- +name: remember +description: Acknowledge a "remember this" request and make sure it is captured well. Use when the user explicitly asks to remember, note, or save something for future sessions. +--- + +# Remember something for future sessions + +Mem0 creates memories from the session automatically — there is no separate +write command. When the user asks to remember something: + +1. Restate the fact clearly and completely in your reply, in one or two + sentences, including any names, values, or paths it depends on. Your visible + reply is what memory extraction reads, so a precise restatement is what gets + remembered. +2. Tell the user it will be saved with this session's memories when the session + ends or compacts, and that it will surface in future sessions in this + repository (they can check later with /mem0:search). + +Do not invent a storage confirmation or a memory ID — creation happens in the +background after the session. diff --git a/integrations/mem0-agent-plugin/skills/resume/SKILL.md b/integrations/mem0-agent-plugin/skills/resume/SKILL.md new file mode 100644 index 000000000..3668d68dd --- /dev/null +++ b/integrations/mem0-agent-plugin/skills/resume/SKILL.md @@ -0,0 +1,18 @@ +--- +name: resume +description: Resume Mem0 memory capture after it was paused with /mem0:pause. +--- + +# Resume memory capture + +Resume memory capture for this machine. + +Run: + +```bash +python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "coding-agent" resume +``` + +Confirm to the user that capture is active again. New sessions record evidence and +create memories as normal; nothing that happened while paused is retroactively +captured. diff --git a/integrations/mem0-agent-plugin/skills/search/SKILL.md b/integrations/mem0-agent-plugin/skills/search/SKILL.md new file mode 100644 index 000000000..d52c4ff34 --- /dev/null +++ b/integrations/mem0-agent-plugin/skills/search/SKILL.md @@ -0,0 +1,26 @@ +--- +name: search +description: Search memories from earlier Coding Agent 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. +--- + +# Search memories + +Call `search_memories` with the user's question. Treat `--top-k`, `--category`, +`--scope`, and `--run-id` as tool arguments instead of including them in the +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. + +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 +monorepo), `mine` for your own preferences alone. + +Pass `run_id` with any scope to retrieve memories saved in a specific coding-agent +session. Omit `run_id` to search across sessions. It filters the memories returned; +it does not identify the session making the search request. Use a known session ID, +never invent one. Return the tool's result directly. diff --git a/integrations/mem0-agent-plugin/skills/status/SKILL.md b/integrations/mem0-agent-plugin/skills/status/SKILL.md new file mode 100644 index 000000000..7717e656b --- /dev/null +++ b/integrations/mem0-agent-plugin/skills/status/SKILL.md @@ -0,0 +1,22 @@ +--- +name: status +description: Show whether Mem0 memory is working in this repository, covering configuration, capture state, pending flushes, and whether the Mem0 API key is valid. Use when the user asks whether memory is on, why a memory is missing, or anything looks broken. +--- + +# Memory status + +Run both commands and report the combined result in plain language: + +```bash +python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "coding-agent" status --json +python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "coding-agent" doctor +``` + +Summarize, using only fields the JSON actually reports: whether capture is +active or paused, the user ID and repository scope (`repo_id`), whether an +API key is configured, the event/flush/retrieval counts (`flushes` is the +number of completed flushes, not a pending count), and the doctor check +results. If doctor reports an authentication failure (401 / invalid key), say +clearly that the Mem0 API key is invalid or expired and that memories are NOT +being created. Never report an auth failure as "no memories found". Suggest +reinstalling with `--config api_key=...` in that case. diff --git a/integrations/mem0-plugin/.codex-mcp.json b/integrations/mem0-plugin/.codex-mcp.json deleted file mode 100644 index eba6c6609..000000000 --- a/integrations/mem0-plugin/.codex-mcp.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "mcpServers": { - "mem0": { - "url": "https://mcp.mem0.ai/mcp", - "bearer_token_env_var": "MEM0_API_KEY" - } - } -} diff --git a/integrations/mem0-plugin/.codex-plugin/plugin.json b/integrations/mem0-plugin/.codex-plugin/plugin.json deleted file mode 100644 index cfdd9a6c0..000000000 --- a/integrations/mem0-plugin/.codex-plugin/plugin.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "name": "mem0", - "version": "0.2.15", - "description": "Persistent memory for Codex. Remembers decisions, patterns, and preferences across sessions.", - "author": { - "name": "Mem0", - "email": "support@mem0.ai", - "url": "https://mem0.ai" - }, - "homepage": "https://mem0.ai", - "repository": "https://github.com/mem0ai/mem0", - "license": "Apache-2.0", - "keywords": ["memory", "personalization", "mcp", "semantic-search"], - "skills": "./skills/", - "mcpServers": "./.codex-mcp.json", - "hooks": "./hooks/codex-hooks.json", - "interface": { - "displayName": "Mem0", - "shortDescription": "Persistent memory layer for AI coding workflows", - "longDescription": "Mem0 adds long-term memory to Codex. Store decisions, user preferences, project context, and session state across conversations. Memories are automatically retrieved via semantic search so Codex always has the right context.", - "developerName": "Mem0", - "category": "Productivity", - "capabilities": ["Read", "Write"], - "websiteURL": "https://mem0.ai", - "privacyPolicyURL": "https://mem0.ai/privacy", - "termsOfServiceURL": "https://mem0.ai/terms", - "defaultPrompt": [ - "Search my memories for recent project decisions", - "Remember that I prefer TypeScript over JavaScript", - "What do you know about my coding preferences?" - ], - "brandColor": "#FBBF24", - "logo": "./logo.svg" - } -} diff --git a/integrations/mem0-plugin/.cursor-mcp.json b/integrations/mem0-plugin/.cursor-mcp.json deleted file mode 100644 index 80c40be60..000000000 --- a/integrations/mem0-plugin/.cursor-mcp.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "mcpServers": { - "mem0": { - "url": "https://mcp.mem0.ai/mcp/", - "headers": { - "Authorization": "Token ${env:MEM0_API_KEY}" - } - } - } -} diff --git a/integrations/mem0-plugin/.cursor-plugin/plugin.json b/integrations/mem0-plugin/.cursor-plugin/plugin.json deleted file mode 100644 index fe500f4cd..000000000 --- a/integrations/mem0-plugin/.cursor-plugin/plugin.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "name": "mem0", - "version": "0.2.15", - "description": "Mem0 memory layer for AI applications. Add persistent memory, personalization, and semantic search using the Mem0 Platform MCP server.", - "author": { - "name": "Mem0", - "email": "support@mem0.ai" - }, - "homepage": "https://mem0.ai", - "repository": "https://github.com/mem0ai/mem0", - "logo": "logo.svg", - "license": "Apache-2.0", - "keywords": ["mem0", "memory", "mcp", "personalization", "semantic-search"], - "skills": "./skills/", - "hooks": "./hooks/cursor-hooks.json", - "mcpServers": "./.cursor-mcp.json" -} diff --git a/integrations/mem0-plugin/.kimi-plugin/plugin.json b/integrations/mem0-plugin/.kimi-plugin/plugin.json deleted file mode 100644 index 27d8a8ae4..000000000 --- a/integrations/mem0-plugin/.kimi-plugin/plugin.json +++ /dev/null @@ -1,86 +0,0 @@ -{ - "name": "mem0", - "version": "0.1.0", - "description": "Persistent memory for Kimi Code. Remembers decisions, patterns, and preferences across sessions.", - "author": { - "name": "Mem0", - "email": "support@mem0.ai", - "url": "https://mem0.ai" - }, - "homepage": "https://mem0.ai", - "repository": "https://github.com/mem0ai/mem0", - "license": "Apache-2.0", - "keywords": ["memory", "personalization", "mcp", "semantic-search"], - "skills": "./skills/", - "sessionStart": { - "skill": "context-loader" - }, - "hooks": [ - { - "event": "SessionStart", - "matcher": "^(startup|resume)$", - "command": "\"$KIMI_PLUGIN_ROOT/scripts/kimi_hook_shim.sh\" on_session_start.sh", - "timeout": 30 - }, - { - "event": "UserPromptSubmit", - "command": "\"$KIMI_PLUGIN_ROOT/scripts/kimi_hook_shim.sh\" on_user_prompt.sh", - "timeout": 12 - }, - { - "event": "PreToolUse", - "matcher": "^(Write|Edit|MultiEdit)$", - "command": "\"$KIMI_PLUGIN_ROOT/scripts/kimi_hook_shim.sh\" block_memory_write.sh", - "timeout": 5 - }, - { - "event": "PreToolUse", - "matcher": "^mcp__.*mem0.*__(add_memory|search_memories|get_memories|delete_all_memories)$", - "command": "\"$KIMI_PLUGIN_ROOT/scripts/kimi_hook_shim.sh\" enforce_metadata_defaults.sh", - "timeout": 5 - }, - { - "event": "PreToolUse", - "matcher": "^Read$", - "command": "\"$KIMI_PLUGIN_ROOT/scripts/kimi_hook_shim.sh\" on_file_read.sh", - "timeout": 5 - }, - { - "event": "PostToolUse", - "matcher": "^mcp__.*mem0.*__", - "command": "\"$KIMI_PLUGIN_ROOT/scripts/kimi_hook_shim.sh\" on_post_tool_use.sh", - "timeout": 5 - }, - { - "event": "PostToolUse", - "matcher": "^Bash$", - "command": "\"$KIMI_PLUGIN_ROOT/scripts/kimi_hook_shim.sh\" on_bash_output.sh", - "timeout": 12 - }, - { - "event": "Stop", - "command": "\"$KIMI_PLUGIN_ROOT/scripts/kimi_hook_shim.sh\" on_stop.sh", - "timeout": 30 - }, - { - "event": "PreCompact", - "command": "\"$KIMI_PLUGIN_ROOT/scripts/kimi_hook_shim.sh\" on_pre_compact.sh", - "timeout": 30 - } - ], - "mcpServers": { - "mem0": { - "transport": "http", - "url": "https://mcp.mem0.ai/mcp/", - "bearerTokenEnvVar": "MEM0_API_KEY" - } - }, - "interface": { - "displayName": "Mem0", - "shortDescription": "Persistent memory layer for AI coding workflows", - "longDescription": "Mem0 adds long-term memory to Kimi Code. Store decisions, user preferences, project context, and session state across conversations. Memories are automatically retrieved via semantic search so Kimi always has the right context available.", - "developerName": "Mem0", - "websiteURL": "https://mem0.ai", - "logo": "./logo.svg" - } -} diff --git a/integrations/mem0-plugin/.opencode-plugin/dream.test.ts b/integrations/mem0-plugin/.opencode-plugin/dream.test.ts deleted file mode 100644 index f8fe588dc..000000000 --- a/integrations/mem0-plugin/.opencode-plugin/dream.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { - loadDreamConfig, - incrementSessionCount, - checkCheapGates, - checkMemoryGate, - acquireDreamLock, - releaseDreamLock, - recordDreamCompletion, - DREAM_DEFAULTS, - DREAM_PROTOCOL, -} from "./dream"; - -let dir: string; - -beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), "mem0-dream-")); -}); - -afterEach(() => { - try { - rmSync(dir, { recursive: true, force: true }); - } catch { - /* ignore */ - } - delete process.env.MEM0_DREAM; -}); - -describe("auto-dream gates", () => { - test("memory gate passes at >= minMemories, fails below", () => { - expect(checkMemoryGate(DREAM_DEFAULTS.minMemories, {}).pass).toBe(true); - expect(checkMemoryGate(DREAM_DEFAULTS.minMemories - 1, {}).pass).toBe(false); - }); - - test("cheap gates: fresh state blocks on session count, passes after enough sessions", () => { - // Fresh state: time gate passes (lastConsolidatedAt=0), but 0 sessions blocks. - expect(checkCheapGates(dir, {}).proceed).toBe(false); - for (let i = 0; i < DREAM_DEFAULTS.minSessions; i++) { - incrementSessionCount(dir, `ses_${i}`); - } - expect(checkCheapGates(dir, {}).proceed).toBe(true); - }); - - test("incrementSessionCount only counts distinct session ids", () => { - incrementSessionCount(dir, "ses_a"); - incrementSessionCount(dir, "ses_a"); - incrementSessionCount(dir, "ses_a"); - expect(checkCheapGates(dir, { minHours: 0 }).reason).toContain("sessions: 1"); - }); - - test("recordDreamCompletion resets gates (recent time blocks again)", () => { - for (let i = 0; i < 6; i++) incrementSessionCount(dir, `ses_${i}`); - expect(checkCheapGates(dir, {}).proceed).toBe(true); - recordDreamCompletion(dir); - const r = checkCheapGates(dir, {}); - expect(r.proceed).toBe(false); - expect(r.reason).toContain("time"); - }); - - test("dream lock is exclusive and reclaimable after release", () => { - expect(acquireDreamLock(dir)).toBe(true); - expect(acquireDreamLock(dir)).toBe(false); - releaseDreamLock(dir); - expect(acquireDreamLock(dir)).toBe(true); - }); -}); - -describe("dream config", () => { - test("defaults when no settings file", () => { - const cfg = loadDreamConfig(dir); - expect(cfg.enabled).toBe(true); - expect(cfg.auto).toBe(true); - expect(cfg.minMemories).toBe(DREAM_DEFAULTS.minMemories); - }); - - test("MEM0_DREAM=false force-disables", () => { - process.env.MEM0_DREAM = "false"; - expect(loadDreamConfig(dir).enabled).toBe(false); - }); - - test("settings.json dream block overrides defaults", () => { - writeFileSync( - join(dir, "settings.json"), - JSON.stringify({ dream: { minMemories: 99, auto: false } }), - ); - const cfg = loadDreamConfig(dir); - expect(cfg.minMemories).toBe(99); - expect(cfg.auto).toBe(false); - expect(cfg.enabled).toBe(true); - }); - - test("protocol uses native tools, not the MCP tool", () => { - expect(DREAM_PROTOCOL).toContain("get_memories"); - expect(DREAM_PROTOCOL).toContain("add_memory"); - expect(DREAM_PROTOCOL).not.toContain("mem0_memory"); - }); -}); diff --git a/integrations/mem0-plugin/.opencode-plugin/dream.ts b/integrations/mem0-plugin/.opencode-plugin/dream.ts deleted file mode 100644 index 68395c54b..000000000 --- a/integrations/mem0-plugin/.opencode-plugin/dream.ts +++ /dev/null @@ -1,225 +0,0 @@ -/** - * Auto-dream: gated automatic memory consolidation for the Mem0 OpenCode plugin. - * - * Ported from the (stable) pi-agent plugin's dream module and adapted to - * OpenCode's hook model. When the cheap gates (time since last consolidation + - * sessions since) and the memory-count gate all pass, the plugin injects the - * DREAM_PROTOCOL into the agent's context so it consolidates memories (merge - * duplicates, drop stale/sensitive entries, rewrite vague ones) before - * answering. A filesystem lock prevents concurrent sessions from dreaming at - * once, and completion is recorded so it won't re-trigger until the next cycle. - * - * State + lock live in ~/.mem0/ alongside settings.json. Opt out with - * MEM0_DREAM=false, or tune via the `dream` block in ~/.mem0/settings.json. - */ - -import { existsSync, mkdirSync, readFileSync, writeFileSync, unlinkSync } from "node:fs"; -import { join } from "node:path"; - -export interface DreamConfig { - enabled: boolean; - auto: boolean; - minHours: number; - minSessions: number; - minMemories: number; -} - -interface DreamState { - lastConsolidatedAt: number; - sessionsSince: number; - lastSessionId: string | null; -} - -interface DreamLock { - pid: number; - startedAt: number; -} - -const LOCK_STALE_MS = 60 * 60 * 1000; - -export const DREAM_DEFAULTS: DreamConfig = { - enabled: true, - auto: true, - minHours: 24, - minSessions: 5, - minMemories: 20, -}; - -function statePath(stateDir: string): string { - return join(stateDir, "mem0-dream-state.json"); -} - -function lockPath(stateDir: string): string { - return join(stateDir, "mem0-dream.lock"); -} - -function ensureDir(dir: string): void { - try { - mkdirSync(dir, { recursive: true }); - } catch { - /* exists */ - } -} - -function readState(stateDir: string): DreamState { - try { - return JSON.parse(readFileSync(statePath(stateDir), "utf-8")) as DreamState; - } catch { - return { lastConsolidatedAt: 0, sessionsSince: 0, lastSessionId: null }; - } -} - -function writeState(stateDir: string, state: DreamState): void { - ensureDir(stateDir); - writeFileSync(statePath(stateDir), JSON.stringify(state, null, 2)); -} - -/** - * Load dream config from ~/.mem0/settings.json (`dream` block), applying - * defaults. MEM0_DREAM=false (or 0/no/off) force-disables regardless. - */ -export function loadDreamConfig(settingsDir: string): DreamConfig { - let envEnabled: boolean | undefined; - const env = process.env.MEM0_DREAM; - if (env !== undefined) { - const s = env.toLowerCase(); - envEnabled = s !== "false" && s !== "0" && s !== "no" && s !== "off"; - } - - let cfg: DreamConfig = { ...DREAM_DEFAULTS }; - try { - const sp = join(settingsDir, "settings.json"); - if (existsSync(sp)) { - const settings = JSON.parse(readFileSync(sp, "utf-8")); - const d = settings?.dream; - if (d && typeof d === "object") { - cfg = { - enabled: typeof d.enabled === "boolean" ? d.enabled : cfg.enabled, - auto: typeof d.auto === "boolean" ? d.auto : cfg.auto, - minHours: typeof d.minHours === "number" ? d.minHours : cfg.minHours, - minSessions: typeof d.minSessions === "number" ? d.minSessions : cfg.minSessions, - minMemories: typeof d.minMemories === "number" ? d.minMemories : cfg.minMemories, - }; - } - } - } catch { - /* defaults */ - } - - if (envEnabled !== undefined) cfg.enabled = envEnabled; - return cfg; -} - -/** Count a new session toward the dream gate (once per distinct sessionId). */ -export function incrementSessionCount(stateDir: string, sessionId: string): void { - const state = readState(stateDir); - if (state.lastSessionId !== sessionId) { - state.sessionsSince++; - state.lastSessionId = sessionId; - writeState(stateDir, state); - } -} - -/** Cheap gates that don't need an API call: time since last + sessions since. */ -export function checkCheapGates( - stateDir: string, - config: Partial, -): { proceed: boolean; reason?: string } { - const minHours = config.minHours ?? DREAM_DEFAULTS.minHours; - const minSessions = config.minSessions ?? DREAM_DEFAULTS.minSessions; - const state = readState(stateDir); - - const hoursSince = (Date.now() - state.lastConsolidatedAt) / 3_600_000; - if (hoursSince < minHours) { - return { proceed: false, reason: `time: ${hoursSince.toFixed(1)}h < ${minHours}h` }; - } - if (state.sessionsSince < minSessions) { - return { proceed: false, reason: `sessions: ${state.sessionsSince} < ${minSessions}` }; - } - return { proceed: true }; -} - -/** Memory-count gate (uses the count already fetched at session init). */ -export function checkMemoryGate( - memoryCount: number, - config: Partial, -): { pass: boolean; reason?: string } { - const minMemories = config.minMemories ?? DREAM_DEFAULTS.minMemories; - if (memoryCount < minMemories) { - return { pass: false, reason: `memories: ${memoryCount} < ${minMemories}` }; - } - return { pass: true }; -} - -/** Acquire an exclusive dream lock (stale locks > 1h are reclaimed). */ -export function acquireDreamLock(stateDir: string): boolean { - ensureDir(stateDir); - const lp = lockPath(stateDir); - - try { - const lock = JSON.parse(readFileSync(lp, "utf-8")) as DreamLock; - if (Date.now() - lock.startedAt < LOCK_STALE_MS) { - return false; - } - try { - unlinkSync(lp); - } catch { - /* race ok */ - } - } catch { - /* no lock file */ - } - - const lock: DreamLock = { pid: process.pid, startedAt: Date.now() }; - try { - writeFileSync(lp, JSON.stringify(lock), { flag: "wx" }); - return true; - } catch { - return false; - } -} - -export function releaseDreamLock(stateDir: string): void { - try { - unlinkSync(lockPath(stateDir)); - } catch { - /* already gone */ - } -} - -/** Reset the gates after a successful consolidation. */ -export function recordDreamCompletion(stateDir: string): void { - const state = readState(stateDir); - state.lastConsolidatedAt = Date.now(); - state.sessionsSince = 0; - state.lastSessionId = null; - writeState(stateDir, state); -} - -/** - * Consolidation protocol injected into the agent context when a dream is - * triggered. Uses the plugin's native OpenCode memory tools (get_memories / - * add_memory / delete_memory) rather than an MCP tool. - */ -export const DREAM_PROTOCOL = ` -You are running memory consolidation. Complete these steps using the mem0 memory tools (get_memories, add_memory, delete_memory): - -1. ORIENT — Call get_memories to list all memories. Count by category. Note oldest/newest. - -2. GATHER TARGETS — Review each memory. Classify as: - - DELETE: sensitive information (API keys, passwords, tokens), expired/stale entries, noise, redundant operational details - - MERGE: near-duplicates (same fact stated differently). Keep the better-worded one, delete the other. - - REWRITE: vague, first-person, or poorly-categorized entries. add_memory with improved text, then delete_memory the old one. - - KEEP: everything else. - Skip any memory starting with "[PINNED]". - -3. CONSOLIDATE — Execute the changes: - - Delete stale/duplicate entries with delete_memory - - For merges: add_memory the merged text, delete_memory both originals - - For rewrites: add_memory the improved version, delete_memory the original - -4. REPORT — Summarize: how many reviewed, deleted, merged, rewritten, final count. - -Quality targets: zero sensitive data stored, zero duplicates, all entries are atomic (one fact each), 15-50 words each. -After consolidation, respond to the user's message normally. -`; diff --git a/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-dream/SKILL.md b/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-dream/SKILL.md deleted file mode 100644 index 47441e0f4..000000000 --- a/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-dream/SKILL.md +++ /dev/null @@ -1,237 +0,0 @@ ---- -name: mem0-dream -description: Consolidates stored memories by merging duplicates, resolving contradictions, and pruning stale entries. Use when memory count is high, search results feel noisy or repetitive, or periodic cleanup is needed to maintain memory quality. ---- - -# Mem0 Dream — Memory Consolidation - -This skill performs a memory consolidation pass: it fetches all project memories, -identifies near-duplicates, flags contradictions, and prunes stale entries based on -configured retention policies. All proposed changes are shown as a diff for user -approval before anything is modified. - -**IMPORTANT: Execute steps strictly in order (1 → 2 → 3 → 4 → 5 → 6). Each step depends on the previous one. Do NOT run steps in parallel or skip ahead.** - -## Step 1: Load Retention Policies - -Check for a project config file in the project root (current working directory): - -1. Look for `.mem0.json` first. If it exists, parse it as JSON and read the - `retention` field (a dict of `category → days | null`). -2. If `.mem0.json` is not present, look for `.mem0.md`. If it exists, scan it - for a `retention:` section or YAML front matter with retention settings and - parse what you find. -3. If neither file exists, skip config loading entirely. - -If no config is found or the config contains no retention settings, fall back to -these built-in defaults: - -| `metadata.type` | Default retention | -|---|---| -| `session_state` | 90 days | -| `compact_summary` | 90 days | -| all others | no pruning | - -Store the resolved policies for use in Step 3. - ---- - -## Step 2: Fetch ALL Project Memories - -Call `get_memories` to retrieve every memory for the active project: - -```python -get_memories( - filters={"AND": [{"user_id": ""}, {"app_id": ""}]}, - page_size=200, -) -``` - -If the response indicates more pages exist, paginate until all memories are fetched. -Collect the full list before proceeding. If zero memories are found, print: - -``` -No memories found for project . Nothing to consolidate. -``` - -…and stop. - ---- - -## Step 3: Analyze — Find Issues - -Work entirely in-memory; do not modify anything yet. - -Group memories by `metadata.type` (use `"unknown"` when the field is absent). -For each group, identify the following: - -### 3a. Near-duplicate pairs (merge candidates) - -Two memories are near-duplicates when they express the same fact or decision but -phrased differently (e.g., "Use PostgreSQL for auth" and "Auth DB is PostgreSQL"). - -Heuristics — two memories are near-duplicates if **all** of these hold: -- Similarity threshold: estimated cosine similarity > 0.9 (use noun/keyword overlap as proxy — if >60% of significant nouns overlap, treat as >0.9 similarity). -- Same `metadata.type`. -- Neither memory is pinned (`metadata.pinned != true`). - -For each qualifying pair, draft a merged version that is more complete and specific -than either original. - -### 3b. Contradictions - -Two memories contradict when they assert opposing facts about the same topic -(e.g., "Deploy to ECS" vs. "Deploy to Vercel"). - -Identify the likely winner: the more recent memory with higher confidence wins. -Store both IDs and their content for user review. - -### 3c. Prune candidates - -A memory is a prune candidate when **any** of the following is true: - -1. Its `metadata.type` has a retention policy and the memory is older than the - configured number of days (compare `created_at` to today). -2. Its confidence score is below 0.3 AND it contains no information unique to - this project (no file paths, identifiers, or domain-specific nouns). - -**Always skip memories where `metadata.pinned == true`**, regardless of age or -confidence. - ---- - -## Step 4: Print Diff Report - -Print a structured diff to the terminal before making any changes. Use exactly -this format: - -``` -## dream — consolidation report - -Merges (): - [mem0:] + [mem0:] → "" - -Conflicts (): - [mem0:] vs [mem0:] — "" [A/B/skip] - -Prune (): - [mem0:] — , d old - -Proposed: merges, prunes, conflicts. Apply? [Y/n] -``` - -If there are zero items in any category, omit that section entirely. - -If there are zero total proposals (no merges, no prunes, no conflicts), print: - -``` -Dream complete. No duplicate, contradictory, or stale memories found. -``` - -…and stop. - ---- - -## Step 5: Wait for User Input and Apply - -### 5a. Contradictions - -For each `CONFLICT` pair in the report, wait for the user to type `A`, `B`, or -`skip` (case-insensitive). If they enter nothing (empty), treat as `skip`. - -Record the winner for each pair before proceeding to the final apply confirmation. - -### 5b. Final confirmation - -After all conflict resolutions are collected, prompt: - -``` -Apply? [Y/n] -``` - -If the user types `n` or `no` (case-insensitive), print `Cancelled. No changes made.` -and stop. - -If the user confirms (`Y`, `yes`, or empty / Enter), apply all changes in this order: - -#### Merges - -For each approved merge pair: -1. `delete_memory()` -2. `delete_memory()` -3. `add_memory` with: - - `text=""` - - `user_id=` - - `app_id=` (top-level, not in metadata) - - `metadata={"type": "", "branch": "", "confidence": , "source": "mem0-dream"}` - - `infer=False` - -#### Contradictions (resolved) - -For each resolved conflict where the user chose A or B: -- Delete the loser (the non-chosen memory): `delete_memory(memory_id=)` - -Contradictions where the user chose `skip` are left untouched. - -#### Prunes - -For each prune candidate: -- `delete_memory()` - ---- - -## Step 6: Print Summary - -After all changes are applied, print: - -``` -Dream complete — merged: , pruned: , conflicts resolved: , skipped: -``` - ---- - -## Auto mode - -When invoked with `--auto` (e.g., `/mem0-dream --auto`), run non-interactively: - -- **Merges**: applied automatically (no contradiction, both are compatible). -- **Prunes**: applied automatically (age/confidence-based, no ambiguity). -- **Contradictions**: skipped — they require human judgment. - -### Concurrency guard - -Before doing any work, check for a lock file at `/tmp/mem0_dream_auto.lock`: -- If the lock file exists and is less than 10 minutes old, print `[mem0-dream --auto] Another run in progress — skipping.` and stop. -- Otherwise, create the lock file (write the current timestamp). Delete it when done (in all exit paths). - -### Execution - -In auto mode: -1. Load policies and fetch memories (Steps 1–3) as normal. -2. Apply merges and prunes silently without printing the diff or prompting. -3. Print a compact summary: - ``` - [mem0-dream --auto] project= merged= pruned= conflicts_skipped= - ``` -4. If contradictions were detected but skipped, check if a `mem0-dream-auto` reminder already exists before storing one: - - Search for existing reminders: `search_memories(query="mem0-dream contradictions manual review", filters={"AND": [{"user_id": ""}, {"app_id": ""}, {"metadata": {"source": "mem0-dream-auto"}}]}, top_k=1)` - - If a result exists with similarity > 0.9, skip storing the reminder (one already exists). - - If no match, store the reminder: - ```python - add_memory( - text="mem0-dream detected contradiction(s) requiring manual review. Run /mem0-dream to resolve them interactively.", - user_id="", - app_id="", - metadata={"type": "task_learning", "source": "mem0-dream-auto", "branch": ""}, - infer=False, - ) - ``` - -## See also - -- `/mem0-forget` — targeted deletion of specific memories (search + confirm + delete) -- `/mem0-status --deep` — quick quality scan without applying changes - -## Output formatting - -IMPORTANT: Do NOT use markdown in your output. OpenCode TUI renders text verbatim — markdown like **bold**, ## headers, and | table | syntax appears as raw characters. Use plain text with indentation for structure. Use dashes for lists. Use spaces to align columns instead of markdown tables. diff --git a/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-pin/SKILL.md b/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-pin/SKILL.md deleted file mode 100644 index e2b86ebc5..000000000 --- a/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-pin/SKILL.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -name: mem0-pin -description: Pins or unpins a memory to protect it from pruning during dream consolidation. Use when a memory is critical and must never be removed, such as architecture decisions, security constraints, or immutable team conventions. ---- - -# Mem0 Pin - -Pin a memory to mark it as high-priority and protect from pruning. - -## Execution - -### Step 1: Find the memory - -The user provides either a search query or memory ID. - -**If memory ID:** -- Call `get_memory` with the ID. - -**If search query:** -- Call `search_memories` with the query, `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=5`. -- Show numbered list with content previews. -- Ask: "Which memory to pin? Enter a number." - -### Step 2: Read current content - -Call `get_memory` with the selected memory ID. Store: -- `original_text` — the memory's text content -- `original_metadata` — the existing `metadata` dict - -### Step 3: Pin it - -The `update_memory` tool updates a memory by `id`. To pin durably, append a pin -marker to the text so it travels with the memory: - -```python -pinned_text = "[PINNED] " + original_text if not original_text.startswith("[PINNED]") else original_text -update_memory(id=, text=pinned_text) -``` - -**For new memories** (user wants to pin text that isn't stored yet): -1. Call `add_memory` with: - - `text="[PINNED] "` - - `user_id=` - - `app_id=` - - `metadata={"pinned": true, "type": "decision", "confidence": 1.0}` - - `infer=False` -2. The response contains `event_id`. Call `get_event_status(event_id=)` once to retrieve the memory ID, then confirm. - -### Step 4: Confirm - -``` -Pinned: "" -Memory ID: -``` - -Append `...` only if content exceeds 80 characters. - -### Unpin - -If the user says "unpin": -1. Call `get_memory` to read current content. -2. Remove the pin marker from the text: - ```python - unpinned_text = original_text.removeprefix("[PINNED] ") - update_memory(memory_id=, text=unpinned_text) - ``` -3. Print: `Unpinned: "..."` - -## Output formatting - -IMPORTANT: Do NOT use markdown in your output. OpenCode TUI renders text verbatim — markdown like **bold**, ## headers, and | table | syntax appears as raw characters. Use plain text with indentation for structure. Use dashes for lists. Use spaces to align columns instead of markdown tables. diff --git a/integrations/mem0-plugin/.opencode-plugin/project.ts b/integrations/mem0-plugin/.opencode-plugin/project.ts deleted file mode 100644 index cc89ffb6d..000000000 --- a/integrations/mem0-plugin/.opencode-plugin/project.ts +++ /dev/null @@ -1,20 +0,0 @@ -/** - * Project identity resolution for the Mem0 OpenCode plugin. - * - * The project id (`app_id`) scopes memories to a repo. We derive it from the - * git remote so it is stable across clones, worktrees, and sub-directories — - * falling back (in opencode-mem0.ts) to the git repo root dir name, then the - * cwd. Keeping the parser pure makes the tricky remote formats testable. - */ - -/** - * Parse `owner/repo` out of a git remote URL and return it as `owner-repo`. - * Handles https, scp-style ssh, custom ssh host aliases (e.g. - * `git@github.com-work:owner/repo.git`), an optional `.git` suffix, and a - * trailing slash. Returns null when no owner/repo can be found. - */ -export function parseProjectFromRemote(remote: string): string | null { - const m = remote.trim().match(/[:/]([^/:]+)\/([^/:]+?)(?:\.git)?\/?$/); - if (!m) return null; - return `${m[1]}-${m[2]}`; -} diff --git a/integrations/mem0-plugin/.opencode-plugin/scope.ts b/integrations/mem0-plugin/.opencode-plugin/scope.ts deleted file mode 100644 index 940f77767..000000000 --- a/integrations/mem0-plugin/.opencode-plugin/scope.ts +++ /dev/null @@ -1,71 +0,0 @@ -/** - * Memory scope resolution — ported from the pi-agent plugin's scoping model. - * - * Lets the agent choose, per memory operation, how wide to read/write: - * - "project" (default): this repo only -> { user_id, app_id } - * - "session": this run only -> { user_id, app_id, run_id } - * - "global": across ALL of the user's projects -> { user_id, app_id: "*" } - * - * Mirrors pi-agent/src/memory/scoping.ts (resolveSearchFilters / resolveAddParams) - * so the OpenCode plugin exposes scope the same way: as a per-call tool parameter, - * not a stateful "switch project" command. - */ - -export type Scope = "project" | "session" | "global"; - -/** Filters for `search` / `get_memories` at the given scope. */ -export function scopeSearchFilters( - scope: Scope, - userId: string, - appId: string, - runId: string, -): Record { - switch (scope) { - case "session": - return { user_id: userId, app_id: appId, run_id: runId }; - case "global": - return { user_id: userId, app_id: "*" }; - case "project": - default: - return { user_id: userId, app_id: appId }; - } -} - -/** Identity params for `add` / `delete_all` at the given scope. */ -export function scopeWriteParams( - scope: Scope, - userId: string, - appId: string, - runId: string, -): { user_id: string; app_id?: string; run_id?: string } { - switch (scope) { - case "session": - return { user_id: userId, app_id: appId, run_id: runId }; - case "global": - return { user_id: userId }; - case "project": - default: - return { user_id: userId, app_id: appId }; - } -} - -/** Normalize an arbitrary value to a valid Scope (defaults to "project"). */ -export function asScope(value: unknown): Scope { - return value === "session" || value === "global" ? value : "project"; -} - -/** - * Resolve the persisted default scope from a parsed `~/.mem0/settings.json` - * object. This is the user-changeable default applied to memory operations when - * no explicit `scope` is passed (set via the `mem0-scope` skill). Falls back to - * "project" when unset or invalid. - */ -export function resolveDefaultScope( - settings: Record | null | undefined, -): Scope { - return asScope(settings?.default_scope); -} - -/** Guidance injected so the agent uses `global` only when explicitly asked. */ -export const SCOPE_GUIDANCE = - 'Memory tools accept an optional `scope`: omit it (or "project") for normal queries; use "session" to limit to the current run; use "global" ONLY when the user explicitly asks to search across all their projects in this workspace.'; diff --git a/integrations/mem0-plugin/.opencode-plugin/telemetry.ts b/integrations/mem0-plugin/.opencode-plugin/telemetry.ts deleted file mode 100644 index f8557b21a..000000000 --- a/integrations/mem0-plugin/.opencode-plugin/telemetry.ts +++ /dev/null @@ -1,113 +0,0 @@ -/** - * Plugin telemetry for the Mem0 OpenCode plugin — anonymous usage tracking - * via PostHog. - * - * Emits the SAME event schema as the Mem0 editor plugin's telemetry.py - * (event names prefixed `plugin.`, `source: "plugin"`, `platform: "opencode"`, - * `distinct_id = sha256(apiKey)[:32]`) so OpenCode shows up as just another - * `platform` value in the shared plugin dashboard instead of a separate - * event namespace. - * - * Fire-and-forget: never throws, never blocks, failures are swallowed. Only - * fires when an API key is present (same as the editor plugin — anonymous - * installs without a key emit nothing). Disable with MEM0_TELEMETRY=false. - * - * Never sends: memory content, API keys, raw user/project IDs. Only sends: - * event type, platform, plugin version, and anonymized hashes of the API key - * and project ID. - */ - -import { createHash } from "node:crypto"; -import { readFileSync } from "node:fs"; -import { release } from "node:os"; - -const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"; -const POSTHOG_HOST = "https://us.i.posthog.com/i/v0/e/"; -const REQUEST_TIMEOUT_MS = 2_000; - -function _loadPluginVersion(): string { - // Source context: telemetry.ts sits next to package.json (./). - // Bundled context: dist/index.js sits one level below it (../). - for (const rel of ["./package.json", "../package.json"]) { - try { - const pkg = JSON.parse(readFileSync(new URL(rel, import.meta.url), "utf-8")); - if (pkg?.name === "@mem0/opencode-plugin" && pkg.version) return pkg.version; - } catch { - /* try next candidate */ - } - } - return "unknown"; -} - -const PLUGIN_VERSION = _loadPluginVersion(); - -export function isTelemetryEnabled(): boolean { - const val = process.env.MEM0_TELEMETRY; - if (val === undefined) return true; - const s = val.toLowerCase(); - return s !== "false" && s !== "0" && s !== "no" && s !== "off"; -} - -function distinctId(apiKey: string): string { - // Matches telemetry.py `_distinct_id()` so the same user is one person in - // PostHog whether they use OpenCode or any other Mem0 editor plugin. - return createHash("sha256").update(apiKey).digest("hex").slice(0, 32); -} - -/** - * Build the PostHog event payload, or null when telemetry is disabled or no - * API key is available. Pure (aside from env/version reads) and exported for - * testing. System-controlled properties are applied last so a caller cannot - * override `source`/`platform`/etc. - */ -export function buildEvent( - eventType: string, - properties: Record, - apiKey: string | undefined, - projectId?: string, -): Record | null { - if (!isTelemetryEnabled() || !apiKey) return null; - return { - api_key: POSTHOG_API_KEY, - distinct_id: distinctId(apiKey), - event: `plugin.${eventType}`, - properties: { - ...properties, - source: "plugin", - platform: "opencode", - plugin_version: PLUGIN_VERSION, - os: process.platform, - os_version: release(), - sample_rate: 1.0, - $process_person_profile: false, - $lib: "posthog-node", - // Anonymized project segmentation, matching telemetry.py's project_hash. - ...(projectId - ? { project_hash: createHash("sha256").update(projectId).digest("hex") } - : {}), - }, - }; -} - -/** Send a usage event, fire-and-forget. Never throws, never blocks. */ -export function captureEvent( - eventType: string, - properties: Record, - apiKey: string | undefined, - projectId?: string, -): void { - const payload = buildEvent(eventType, properties, apiKey, projectId); - if (!payload) return; - try { - void fetch(POSTHOG_HOST, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify(payload), - signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), - }).catch(() => { - /* fire-and-forget */ - }); - } catch { - /* never throw */ - } -} diff --git a/integrations/mem0-plugin/README.md b/integrations/mem0-plugin/README.md deleted file mode 100644 index 1e381fbf4..000000000 --- a/integrations/mem0-plugin/README.md +++ /dev/null @@ -1,278 +0,0 @@ -> **Claude Code users:** version 0.3.0 of the Claude Code plugin now lives at -> [`integrations/claude-code-plugin`](../claude-code-plugin/) and is what `mem0@mem0-plugins` installs. -> Update with `claude plugin marketplace update mem0-plugins` then -> `claude plugin update mem0@mem0-plugins --scope user` — your memories carry over -> automatically. This directory continues to serve the Cursor, Codex, Kimi, -> Antigravity, and OpenCode integrations until they are ported. The Claude Code -> manifest, hooks, and MCP config have been removed from this directory, so -> there is nothing here left to install into Claude Code. - -# Mem0 Plugin for Cursor, Codex, Kimi, OpenCode & Antigravity - -Add persistent memory to your AI workflows. Store, retrieve, and manage memories across sessions using the Mem0 Platform. Works with **Cursor**, **Codex**, **Kimi**, **OpenCode**, and **Antigravity**. For Claude Code, use [`integrations/claude-code-plugin`](../claude-code-plugin/). - -## Quick path for agents - -If you're an AI agent setting up Mem0 autonomously (no human dashboard signup available), run: - -```bash -mem0 init --agent --json -``` - -This mints an evaluation API key in <5 seconds — no email, no OTP, no browser. The key is written to your config and exported as `MEM0_API_KEY` for the current shell. Use it immediately against the Mem0 Platform or the MCP server. The human owner can later run `mem0 init --email ` to claim ownership: memories transfer, the same API key keeps working, and the agent isn't disrupted. - -Humans setting up Mem0 by hand should continue with Step 1 below. - -## Step 1: Set your API key - -> **You must complete this step before installing the plugin.** - -1. Sign up at [app.mem0.ai](https://app.mem0.ai?utm_source=oss&utm_medium=mem0-plugin-readme) if you haven't already -2. Go to [app.mem0.ai/dashboard/api-keys](https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=mem0-plugin-readme) -3. Click **Create API Key** and copy the key (starts with `m0-`) -4. Set the key using **one** of these methods: - - **CLI** — add to your shell profile: - - ```bash - # For zsh (default on macOS) - echo 'export MEM0_API_KEY="m0-your-api-key"' >> ~/.zshrc - source ~/.zshrc - - # For bash - echo 'export MEM0_API_KEY="m0-your-api-key"' >> ~/.bashrc - source ~/.bashrc - ``` - - **Desktop app** — use the local environment editor: - - Click the environment dropdown next to the prompt box → hover over **Local** → click the **gear icon** → add `MEM0_API_KEY` with your key. Values are stored encrypted on your machine. - - > **Note:** The Desktop app does not inherit custom environment variables from shell profiles — it only reads `PATH`. You must use the local environment editor for Desktop. - -5. Confirm it's set: - - ```bash - echo $MEM0_API_KEY - # Should print: m0-your-api-key - ``` - -## Step 2: Install the plugin - -Choose one of the options below. All require `MEM0_API_KEY` to be set first (see above). - -### Codex - -**Option A — Direct MCP** (fastest, MCP only): - -Codex reads MCP servers from `~/.codex/config.toml` as TOML. Add: - -```toml -[mcp_servers.mem0] -url = "https://mcp.mem0.ai/mcp" -bearer_token_env_var = "MEM0_API_KEY" -``` - -Export `MEM0_API_KEY` in your shell and restart Codex. `codex mcp add` only supports stdio servers, so HTTP servers like Mem0's must be added via `config.toml` directly (or via the **Plugins → Connect to a custom MCP → Streamable HTTP** UI in the Codex app). - -**Option B — Sideload the plugin** (full experience: MCP + skills + opt-in hooks): - -Clone the repo and register the bundled marketplace with one CLI call: - -```bash -git clone https://github.com/mem0ai/mem0.git ~/codex-plugins/mem0-source -codex plugin marketplace add ~/codex-plugins/mem0-source -``` - -This points Codex at the repo's `.agents/plugins/marketplace.json`, which references `integrations/mem0-plugin/` as the local source. Restart Codex, run `/plugins`, and install **Mem0** from the **Mem0 Plugins** marketplace. - -> **Don't combine with Option A.** The plugin manifest auto-registers `mem0` as an MCP server via `integrations/mem0-plugin/.codex-mcp.json` — adding a manual `[mcp_servers.mem0]` block would duplicate the registration. - -**Optional — enable lifecycle hooks.** Codex doesn't auto-wire hooks from plugin manifests; it only reads `~/.codex/hooks.json` (or `/.codex/hooks.json`) ([docs](https://developers.openai.com/codex/hooks)). Run the bundled installer once to merge Mem0's entries: - -```bash -python3 ~/codex-plugins/mem0-source/integrations/mem0-plugin/scripts/install_codex_hooks.py -``` - -This merges six event handlers into `~/.codex/hooks.json` with absolute paths pointing into your clone: - -| Event | What it does | -|-------|--------------| -| `SessionStart` | Loads prior memories as bootstrap context | -| `UserPromptSubmit` | Injects relevant memories into the prompt | -| `PreToolUse` (3 handlers) | Blocks MEMORY.md writes; enforces `user_id`/`app_id` on mem0 tool calls; scans files being read for relevant memory context | -| `PostToolUse` (2 handlers) | Tracks stats, scans bash errors for related memories | -| `Stop` | Reminds the agent to persist learnings at turn end | -| `PreCompact` | Stores a summary before the context is compacted | - -Re-running the installer is idempotent (replaces the Mem0 entries rather than duplicating) and preserves any other hooks you have. To remove: `python3 .../install_codex_hooks.py --uninstall`. If you move or delete the clone directory, re-run the installer from the new location — the hooks file stores absolute paths. - -Codex hooks also require the `codex_hooks` feature flag in `~/.codex/config.toml`: - -```toml -[features] -codex_hooks = true -``` - -The installer prints a reminder if the flag isn't set. Restart Codex after editing the config. - -**Managing the plugin:** - -```bash -codex plugin marketplace upgrade # pull latest plugin versions -codex plugin marketplace remove mem0-plugins # unregister the marketplace -``` - -### Cursor - -> **Already have `mem0` configured as an MCP server?** Remove the existing entry from your Cursor MCP settings before installing to avoid duplicate tools. - -**Option A — One-click deeplink** (installs MCP server only): - -[Install Mem0 MCP in Cursor](cursor://anysphere.cursor-deeplink/mcp/install?name=mem0&config=eyJtY3BTZXJ2ZXJzIjp7Im1lbTAiOnsidXJsIjoiaHR0cHM6Ly9tY3AubWVtMC5haS9tY3AvIiwiaGVhZGVycyI6eyJBdXRob3JpemF0aW9uIjoiVG9rZW4gJHtlbnY6TUVNMF9BUElfS0VZfSJ9fX19) - -**Option B — Manual configuration** (MCP server only): - -Add the following to your `.cursor/mcp.json`: - -```json -{ - "mcpServers": { - "mem0": { - "url": "https://mcp.mem0.ai/mcp/", - "headers": { - "Authorization": "Token ${env:MEM0_API_KEY}" - } - } - } -} -``` - -### OpenCode - -```bash -opencode plugin @mem0/opencode-plugin -``` - -Add `--global` to install for all projects. The plugin auto-registers its native memory tools, hooks, and skills via its `config` hook — no MCP server to configure. Restart OpenCode after installing. - -See [OpenCode integration docs](https://docs.mem0.ai/integrations/opencode) for full details. - -### Antigravity (Google) - -**Option A — degit** (recommended): - -```bash -# Install the plugin (MCP server, hooks, scripts) -npx degit mem0ai/mem0/integrations/mem0-plugin ~/.gemini/config/plugins/mem0 -``` - -This installs the MCP server, lifecycle hooks, and shared scripts. - -See [Antigravity integration docs](https://docs.mem0.ai/integrations/antigravity) for full details. - -## Post-Installation: Run `/mem0:onboard` - -After installing, start a new session and run: - -``` -/mem0:onboard -``` - -This runs the setup wizard which: -1. Verifies your API key and MCP connection -2. Detects and imports project files (`CLAUDE.md`, `AGENTS.md`, `.cursorrules`) -3. Installs coding-optimized memory categories -4. Shows your identity (user ID, project scope, branch) - -The onboarding is idempotent — safe to re-run anytime. On first session in a new project (0 memories), the agent is prompted to run it automatically. - -## Verify it works - -After onboarding, confirm everything is connected: - -1. Run `/mem0:health` to check connectivity -2. Run `/mem0:stats` to see memory counts -3. Try `/mem0:remember "we use TypeScript"` then `/mem0:tour` to see it stored - -## Available Skills - -The plugin includes 17 skills accessible via `/mem0:` commands: - -| Command | Description | -|---------|-------------| -| `/mem0:remember` | Store a memory verbatim — decisions, preferences, conventions | -| `/mem0:tour` | Browse all memories grouped by category | -| `/mem0:peek` | Quick search with compact one-liner results | -| `/mem0:stats` | Session and project memory statistics | -| `/mem0:dream` | Consolidate memories — merge duplicates, resolve contradictions | -| `/mem0:pin` | Protect critical memories from pruning | -| `/mem0:forget` | Delete memories by search or ID | -| `/mem0:health` | Diagnose connectivity, API key, and read/write | -| `/mem0:export` | Export memories to portable Markdown | -| `/mem0:import` | Import memories from export file or MEMORY.md | -| `/mem0:list-projects` | List all projects with stored memories | -| `/mem0:switch-project` | Override auto-detected project scope | -| `/mem0:memory-reviewer` | Audit memory quality — duplicates, contradictions, stale | -| `/mem0:context-loader` | Pre-load relevant memories for current task | - -## What's included - -| Component | Cursor (MCP) | Codex (Sideload) | Codex (Direct MCP) | OpenCode (Full) | OpenCode (MCP) | Antigravity | -|-----------|:------------:|:----------------:|:------------------:|:---------------:|:--------------:|:-----------:| -| MCP Server | Yes | Yes | Yes | Yes | Yes | Yes | -| Lifecycle Hooks | No | Opt-in | No | Yes | No | Yes | -| Mem0 SDK Skill | No | Yes | No | Yes | No | Yes | - -- **MCP Server** — Connects to the Mem0 remote MCP server (`mcp.mem0.ai`), providing tools to add, search, update, and delete memories. No local dependencies required. -- **Lifecycle Hooks** — Automatic memory capture at key points. OpenCode and Antigravity wire hooks natively when the full plugin is installed. Codex hooks are opt-in via a one-time installer (`scripts/install_codex_hooks.py`). -- **Mem0 SDK Skill** — Guides the AI on how to integrate the Mem0 SDK (Python & TypeScript) into your applications. - -## Updating the plugin - -When the plugin updates (new version pulled from the marketplace, or a fresh local install), the MCP server connection in your existing session is left holding a stale handle and stops responding. **Restart your client to reconnect:** - -- **Cursor:** quit and relaunch. -- **Codex:** restart the editor session. -- **OpenCode:** restart the session. -- **Antigravity:** restart the session. - -Your `MEM0_API_KEY` doesn't need to be re-entered — the auth header is re-read from your environment on the new session. The plugin's MCP config uses `${MEM0_API_KEY}` interpolation at session start, not at install time, so as long as the env var is set persistently (in your shell profile), reconnection is automatic on restart. - -If reconnection still fails after a restart, check that `MEM0_API_KEY` is reachable in the new shell (`echo $MEM0_API_KEY`) and confirm you're using a key that starts with `m0-` (from https://app.mem0.ai/dashboard/api-keys, not a legacy token). - -## Coding-tuned categories (automatic) - -mem0 auto-tags every memory with one or more `categories` from a project-level list. The default list is consumer-oriented (`food`, `hobbies`, `music` …) — useful for chat assistants, less so for code. **The plugin installs a coding-focused taxonomy automatically in the background on session start** — no prompt, no manual step. New memories then auto-tag against 17 development-oriented categories: `architecture_decisions`, `anti_patterns`, `task_learnings`, `tooling_setup`, `bug_fixes`, `coding_conventions`, `user_preferences`, `dependency_decisions`, `performance_findings`, `security_constraints`, `testing_patterns`, `data_model`, `api_contracts`, `deployment_runbook`, `team_norms`, `domain_glossary`, `experiment_results`. - -The background setup is idempotent and runs once per account (cached in `~/.mem0/categories_setup.json`); it re-applies only if the taxonomy itself changes. To preview the taxonomy or force a refresh manually: - -```bash -# Dry-run -- prints current vs proposed, no changes: -python integrations/mem0-plugin/scripts/setup_coding_categories.py - -# Write explicitly: -python integrations/mem0-plugin/scripts/setup_coding_categories.py --apply -``` - -Requires the `mem0ai` Python SDK (`pip install mem0ai`) and `MEM0_API_KEY` set. `project.update(custom_categories=[...])` always replaces the full list. - -## MCP Tools - -Once installed, the following tools are available: - -| Tool | Description | -|------|-------------| -| `add_memory` | Save text or conversation history for a user/agent | -| `search_memories` | Semantic search across memories with filters | -| `get_memories` | List memories with filters and pagination | -| `get_memory` | Retrieve a specific memory by ID | -| `update_memory` | Overwrite a memory's text by ID | -| `delete_memory` | Delete a single memory by ID | -| `delete_all_memories` | Bulk delete all memories in scope | -| `delete_entities` | Delete a user/agent/app/run entity and its memories | -| `list_entities` | List users/agents/apps/runs stored in Mem0 | - -## License - -Apache-2.0 diff --git a/integrations/mem0-plugin/hooks.json b/integrations/mem0-plugin/hooks.json deleted file mode 100644 index c7b9144b1..000000000 --- a/integrations/mem0-plugin/hooks.json +++ /dev/null @@ -1,104 +0,0 @@ -{ - "hooks": { - "SessionStart": [ - { - "matcher": "*", - "hooks": [ - { - "name": "mem0-ensure-deps", - "type": "command", - "command": "ANTIGRAVITY_PLUGIN_ROOT=${extensionPath} CLAUDE_PLUGIN_ROOT=${extensionPath} bash ${extensionPath}/scripts/ensure_deps.sh || true", - "timeout": 60 - }, - { - "name": "mem0-session-start", - "type": "command", - "command": "ANTIGRAVITY_PLUGIN_ROOT=${extensionPath} CLAUDE_PLUGIN_ROOT=${extensionPath} bash ${extensionPath}/scripts/on_session_start.sh || true" - } - ] - } - ], - "UserPromptSubmit": [ - { - "hooks": [ - { - "name": "mem0-user-prompt", - "type": "command", - "command": "ANTIGRAVITY_PLUGIN_ROOT=${extensionPath} CLAUDE_PLUGIN_ROOT=${extensionPath} bash ${extensionPath}/scripts/on_user_prompt.sh || true", - "timeout": 8 - } - ] - } - ], - "PreToolUse": [ - { - "matcher": "Write|Edit|MultiEdit", - "hooks": [ - { - "name": "mem0-block-memory-write", - "type": "command", - "command": "ANTIGRAVITY_PLUGIN_ROOT=${extensionPath} CLAUDE_PLUGIN_ROOT=${extensionPath} bash ${extensionPath}/scripts/block_memory_write.sh" - } - ] - }, - { - "matcher": "mcp__mem0__.*|mcp__plugin_mem0_mem0__.*", - "hooks": [ - { - "name": "mem0-enforce-metadata", - "type": "command", - "command": "ANTIGRAVITY_PLUGIN_ROOT=${extensionPath} CLAUDE_PLUGIN_ROOT=${extensionPath} bash ${extensionPath}/scripts/enforce_metadata_defaults.sh", - "timeout": 3 - } - ] - }, - { - "matcher": "Read", - "hooks": [ - { - "name": "mem0-file-context", - "type": "command", - "command": "ANTIGRAVITY_PLUGIN_ROOT=${extensionPath} CLAUDE_PLUGIN_ROOT=${extensionPath} bash ${extensionPath}/scripts/on_file_read.sh", - "timeout": 5 - } - ] - } - ], - "Stop": [ - { - "hooks": [ - { - "name": "mem0-session-summary", - "type": "command", - "command": "ANTIGRAVITY_PLUGIN_ROOT=${extensionPath} CLAUDE_PLUGIN_ROOT=${extensionPath} bash ${extensionPath}/scripts/on_stop.sh", - "timeout": 30 - } - ] - } - ], - "PostToolUse": [ - { - "matcher": "mcp__mem0__.*|mcp__plugin_mem0_mem0__.*", - "hooks": [ - { - "name": "mem0-post-tool", - "type": "command", - "command": "ANTIGRAVITY_PLUGIN_ROOT=${extensionPath} CLAUDE_PLUGIN_ROOT=${extensionPath} bash ${extensionPath}/scripts/on_post_tool_use.sh", - "timeout": 3 - } - ] - }, - { - "matcher": "Bash", - "hooks": [ - { - "name": "mem0-bash-output", - "type": "command", - "command": "ANTIGRAVITY_PLUGIN_ROOT=${extensionPath} CLAUDE_PLUGIN_ROOT=${extensionPath} bash ${extensionPath}/scripts/on_bash_output.sh", - "timeout": 5 - } - ] - } - ] - } -} diff --git a/integrations/mem0-plugin/hooks/codex-hooks.json b/integrations/mem0-plugin/hooks/codex-hooks.json deleted file mode 100644 index 7e0cb002f..000000000 --- a/integrations/mem0-plugin/hooks/codex-hooks.json +++ /dev/null @@ -1,104 +0,0 @@ -{ - "hooks": { - "PreToolUse": [ - { - "matcher": "Write|Edit|MultiEdit", - "hooks": [ - { - "type": "command", - "command": "MEM0_PLATFORM=codex ${PLUGIN_ROOT}/scripts/block_memory_write.sh", - "timeout": 3 - } - ] - }, - { - "matcher": "mcp__mem0__add_memory|mcp__plugin_mem0_mem0__add_memory|mcp__mem0__search_memories|mcp__plugin_mem0_mem0__search_memories|mcp__mem0__get_memories|mcp__plugin_mem0_mem0__get_memories|mcp__mem0__delete_all_memories|mcp__plugin_mem0_mem0__delete_all_memories", - "hooks": [ - { - "type": "command", - "command": "MEM0_PLATFORM=codex ${PLUGIN_ROOT}/scripts/enforce_metadata_defaults.sh", - "timeout": 3 - } - ] - }, - { - "matcher": "Read", - "hooks": [ - { - "type": "command", - "command": "MEM0_PLATFORM=codex ${PLUGIN_ROOT}/scripts/on_file_read.sh", - "timeout": 5 - } - ] - } - ], - "SessionStart": [ - { - "matcher": "startup|resume|compact", - "hooks": [ - { - "type": "command", - "command": "MEM0_PLATFORM=codex ${PLUGIN_ROOT}/scripts/on_session_start.sh", - "statusMessage": "Loading mem0 context..." - } - ] - } - ], - "UserPromptSubmit": [ - { - "hooks": [ - { - "type": "command", - "command": "MEM0_PLATFORM=codex ${PLUGIN_ROOT}/scripts/on_user_prompt.sh", - "statusMessage": "Checking memory relevance...", - "timeout": 12 - } - ] - } - ], - "PostToolUse": [ - { - "matcher": "mcp__mem0__.*|mcp__plugin_mem0_mem0__.*", - "hooks": [ - { - "type": "command", - "command": "MEM0_PLATFORM=codex ${PLUGIN_ROOT}/scripts/on_post_tool_use.sh", - "timeout": 3 - } - ] - }, - { - "matcher": "Bash", - "hooks": [ - { - "type": "command", - "command": "MEM0_PLATFORM=codex ${PLUGIN_ROOT}/scripts/on_bash_output.sh", - "timeout": 12 - } - ] - } - ], - "Stop": [ - { - "hooks": [ - { - "type": "command", - "command": "MEM0_PLATFORM=codex ${PLUGIN_ROOT}/scripts/on_stop.sh", - "timeout": 30 - } - ] - } - ], - "PreCompact": [ - { - "hooks": [ - { - "type": "command", - "command": "MEM0_PLATFORM=codex ${PLUGIN_ROOT}/scripts/on_pre_compact.sh", - "statusMessage": "Preparing pre-compaction summary..." - } - ] - } - ] - } -} diff --git a/integrations/mem0-plugin/hooks/cursor-hooks.json b/integrations/mem0-plugin/hooks/cursor-hooks.json deleted file mode 100644 index 1a07cb23b..000000000 --- a/integrations/mem0-plugin/hooks/cursor-hooks.json +++ /dev/null @@ -1,56 +0,0 @@ -{ - "version": 1, - "hooks": { - "sessionStart": [ - { - "command": "${CURSOR_PLUGIN_ROOT}/scripts/on_session_start_cursor.sh", - "matcher": "startup|resume|compact" - } - ], - "preToolUse": [ - { - "command": "${CURSOR_PLUGIN_ROOT}/scripts/block_memory_write_cursor.sh", - "matcher": "Write|Edit|MultiEdit" - }, - { - "command": "${CURSOR_PLUGIN_ROOT}/scripts/enforce_metadata_defaults.sh", - "matcher": "mcp__mem0__add_memory|mcp__plugin_mem0_mem0__add_memory|mcp__mem0__search_memories|mcp__plugin_mem0_mem0__search_memories|mcp__mem0__get_memories|mcp__plugin_mem0_mem0__get_memories|mcp__mem0__delete_all_memories|mcp__plugin_mem0_mem0__delete_all_memories", - "timeout": 3 - }, - { - "command": "${CURSOR_PLUGIN_ROOT}/scripts/on_file_read_cursor.sh", - "matcher": "Read", - "timeout": 5 - } - ], - "postToolUse": [ - { - "command": "${CURSOR_PLUGIN_ROOT}/scripts/on_post_tool_use_cursor.sh", - "matcher": "mcp__mem0__.*|mcp__plugin_mem0_mem0__.*", - "timeout": 3 - }, - { - "command": "${CURSOR_PLUGIN_ROOT}/scripts/on_bash_output.sh", - "matcher": "Bash", - "timeout": 12 - } - ], - "stop": [ - { - "command": "${CURSOR_PLUGIN_ROOT}/scripts/on_stop_cursor.sh", - "timeout": 30 - } - ], - "preCompact": [ - { - "command": "${CURSOR_PLUGIN_ROOT}/scripts/on_pre_compact_cursor.sh" - } - ], - "beforeSubmitPrompt": [ - { - "command": "${CURSOR_PLUGIN_ROOT}/scripts/on_user_prompt_cursor.sh", - "timeout": 12 - } - ] - } -} diff --git a/integrations/mem0-plugin/logo.svg b/integrations/mem0-plugin/logo.svg deleted file mode 100644 index cf13d0d38..000000000 --- a/integrations/mem0-plugin/logo.svg +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - - - - - - - - - - - - diff --git a/integrations/mem0-plugin/mcp_config.json b/integrations/mem0-plugin/mcp_config.json deleted file mode 100644 index 86e2428d5..000000000 --- a/integrations/mem0-plugin/mcp_config.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "mcpServers": { - "mem0": { - "serverUrl": "https://mcp.mem0.ai/mcp/", - "headers": { - "Authorization": "Token ${MEM0_API_KEY}" - } - } - } -} diff --git a/integrations/mem0-plugin/plugin.json b/integrations/mem0-plugin/plugin.json deleted file mode 100644 index 35d1fdf63..000000000 --- a/integrations/mem0-plugin/plugin.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "id": "mem0", - "name": "mem0", - "version": "0.1.7", - "description": "Persistent semantic memory for Antigravity agents. Cross-session, user-level recall via the Mem0 Platform MCP server. 16 slash commands, lifecycle hooks for auto-capture and metadata enforcement.", - "author": { "name": "Mem0", "email": "support@mem0.ai" }, - "publisher": "mem0ai", - "homepage": "https://mem0.ai", - "repository": "https://github.com/mem0ai/mem0", - "license": "Apache-2.0", - "keywords": ["memory", "persistence", "personalization", "mcp", "semantic-search"], - "contextFileName": "AGENTS.md" -} diff --git a/integrations/mem0-plugin/requirements.txt b/integrations/mem0-plugin/requirements.txt deleted file mode 100644 index 633d7eaad..000000000 --- a/integrations/mem0-plugin/requirements.txt +++ /dev/null @@ -1 +0,0 @@ -mem0ai diff --git a/integrations/mem0-plugin/scripts/_chunking.py b/integrations/mem0-plugin/scripts/_chunking.py deleted file mode 100644 index 359199d9d..000000000 --- a/integrations/mem0-plugin/scripts/_chunking.py +++ /dev/null @@ -1,75 +0,0 @@ -"""Shared content-chunking utilities for mem0-plugin import scripts.""" - -from __future__ import annotations - -MIN_CHUNK_CHARS = 50 -MAX_CHUNK_CHARS = 10_000 - - -def split_by_headers(content: str, header_prefix: str = "## ") -> list[str]: - """Split content by Markdown header lines (e.g. '## '). - - The header line is included at the start of each chunk. - Returns a list of non-empty chunk strings. - """ - chunks: list[str] = [] - current_lines: list[str] = [] - - for line in content.splitlines(keepends=True): - if line.startswith(header_prefix) and current_lines: - chunk = "".join(current_lines).strip() - if chunk: - chunks.append(chunk) - current_lines = [line] - else: - current_lines.append(line) - - if current_lines: - chunk = "".join(current_lines).strip() - if chunk: - chunks.append(chunk) - - return chunks - - -def split_by_hr_or_headers(content: str) -> list[str]: - """Split content by '---' horizontal rules or '## ' headers. - - Used for .continue/rules.md which may use either convention. - """ - import re - - # Split on lines that are exactly "---" or start with "## " - chunks: list[str] = [] - current_lines: list[str] = [] - - for line in content.splitlines(keepends=True): - is_hr = re.match(r"^---\s*$", line) - is_h2 = line.startswith("## ") - - if (is_hr or is_h2) and current_lines: - chunk = "".join(current_lines).strip() - if chunk: - chunks.append(chunk) - current_lines = [] if is_hr else [line] - else: - current_lines.append(line) - - if current_lines: - chunk = "".join(current_lines).strip() - if chunk: - chunks.append(chunk) - - return chunks - - -def filter_and_truncate(chunks: list[str]) -> list[str]: - """Filter out chunks shorter than MIN_CHUNK_CHARS, truncate long chunks.""" - result: list[str] = [] - for chunk in chunks: - if len(chunk) < MIN_CHUNK_CHARS: - continue - if len(chunk) > MAX_CHUNK_CHARS: - chunk = chunk[:MAX_CHUNK_CHARS] - result.append(chunk) - return result diff --git a/integrations/mem0-plugin/scripts/_formatting.py b/integrations/mem0-plugin/scripts/_formatting.py deleted file mode 100644 index eb5e23368..000000000 --- a/integrations/mem0-plugin/scripts/_formatting.py +++ /dev/null @@ -1,51 +0,0 @@ -"""Shared formatting helpers for mem0 plugin hooks. - -Constants and utilities used by file_context.py, session_timeline.py, -and any future hook that displays memories. -""" - -from __future__ import annotations - -TYPE_ICONS = { - "decision": "⚖️", - "anti_pattern": "\U0001f534", - "bug_fix": "\U0001f534", - "convention": "\U0001f504", - "task_learning": "\U0001f535", - "user_preference": "\U0001f7e3", - "session_summary": "\U0001f4cb", - "session_state": "\U0001f4cb", - "project_profile": "\U0001f4d6", - "compact_summary": "\U0001f4cb", - "auto_capture": "✅", - "environmental": "🌐", - "health_check": "🩺", -} - - -def format_age(memory: dict) -> str: - """Format how long ago a memory was created, e.g. '2h ago', '3d ago'.""" - created = memory.get("created_at", "") - if not created: - return "" - try: - from datetime import datetime, timezone - - if created.endswith("Z"): - created = created[:-1] + "+00:00" - dt = datetime.fromisoformat(created) - now = datetime.now(timezone.utc) - delta = now - dt - seconds = int(delta.total_seconds()) - if seconds < 3600: - return f"{seconds // 60}m ago" - if seconds < 86400: - return f"{seconds // 3600}h ago" - days = seconds // 86400 - if days == 1: - return "1d ago" - if days < 30: - return f"{days}d ago" - return f"{days // 30}mo ago" - except Exception: - return "" diff --git a/integrations/mem0-plugin/scripts/_identity.py b/integrations/mem0-plugin/scripts/_identity.py deleted file mode 100644 index d60ccb4a3..000000000 --- a/integrations/mem0-plugin/scripts/_identity.py +++ /dev/null @@ -1,104 +0,0 @@ -"""Resolve mem0 identity: API key, user_id, and settings. - -API key resolution (first non-empty wins): - 1. MEM0_API_KEY env var (explicit / shell profile) - 2. CLAUDE_PLUGIN_OPTION_API_KEY (injected by Claude Code userConfig) - 3. CLAUDE_PLUGIN_OPTION_MEM0_API_KEY (legacy userConfig) - 4. Extract from shell profile files (~/.zshrc, ~/.bashrc, etc.) - Desktop app doesn't inherit shell env — this covers users who - set MEM0_API_KEY in their profile but use the Desktop app. - -User ID resolution: - 1. MEM0_USER_ID env var (explicit override) - 2. $USER, else "default" - -Settings resolution: - ~/.mem0/settings.json (user-editable, falls back to defaults) -""" - -from __future__ import annotations - -import os -import re -from pathlib import Path - - -def _extract_key_from_shell_profiles() -> str: - """Extract MEM0_API_KEY from shell profile files. - - The Desktop app only reads PATH from shell profiles — env vars like - MEM0_API_KEY are not inherited. This handles the common - ``export MEM0_API_KEY=...`` pattern without sourcing the full profile. - """ - profiles = [".zshrc", ".bashrc", ".zprofile", ".bash_profile", ".profile"] - pattern = re.compile(r'^\s*(?:export\s+)?MEM0_API_KEY=(.+)$') - - for name in profiles: - path = Path.home() / name - if not path.is_file(): - continue - try: - for line in path.read_text(encoding="utf-8", errors="replace").splitlines(): - m = pattern.match(line) - if not m: - continue - value = m.group(1).strip() - value = re.sub(r'#.*$', '', value).strip() - value = value.strip("\"'") - if value and not value.startswith("$"): - return value - except OSError: - continue - return "" - - -def resolve_api_key() -> str: - key = os.environ.get("MEM0_API_KEY", "").strip() - if key: - return key - key = os.environ.get("CLAUDE_PLUGIN_OPTION_API_KEY", "").strip() - if key: - return key - key = os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY", "").strip() - if key: - return key - key = _extract_key_from_shell_profiles() - if key: - return key - return "" - - -def resolve_user_id() -> str: - explicit = os.environ.get("MEM0_USER_ID", "").strip() - if explicit: - return explicit - return os.environ.get("USER") or "default" - - -def resolve_config() -> dict: - """Resolve settings from ~/.mem0/settings.json (primary) with env var overrides.""" - try: - from load_settings import load_settings - return load_settings() - except ImportError: - return { - "auto_save": True, - "auto_search": True, - "search_limit": 10, - "retention_session_days": 90, - "confidence_threshold": 0.3, - "debug": False, - } - - -try: - from _project import resolve_branch, resolve_project_id, save_project_mapping -except ImportError: - def resolve_project_id(cwd: str | None = None) -> str: - return os.path.basename(cwd or os.getcwd()) - - def resolve_branch(cwd: str | None = None) -> str: - return "unknown" - - def save_project_mapping(cwd: str, project_id: str) -> None: - pass diff --git a/integrations/mem0-plugin/scripts/_identity.sh b/integrations/mem0-plugin/scripts/_identity.sh deleted file mode 100644 index 4a25b8afc..000000000 --- a/integrations/mem0-plugin/scripts/_identity.sh +++ /dev/null @@ -1,87 +0,0 @@ -# Source this file. Sets MEM0_API_KEY, MEM0_RESOLVED_USER_ID, and settings. -# -# API key resolution (first non-empty wins): -# 1. MEM0_API_KEY env var (explicit / shell profile) -# 2. CLAUDE_PLUGIN_OPTION_API_KEY (injected by Claude Code userConfig) -# 3. CLAUDE_PLUGIN_OPTION_MEM0_API_KEY (legacy userConfig) -# 4. Extract from shell profile files (~/.zshrc, ~/.bashrc, etc.) -# Desktop app doesn't inherit shell env — this fallback covers users -# who set MEM0_API_KEY in their profile but use the Desktop app. -# -# Settings: ~/.mem0/settings.json (user-editable, falls back to defaults) - -_SCRIPT_DIR="$( cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd )" - -# Resolve API key: env var > userConfig > shell profile extraction -if [ -z "${MEM0_API_KEY:-}" ] && [ -n "${CLAUDE_PLUGIN_OPTION_API_KEY:-}" ]; then - MEM0_API_KEY="$CLAUDE_PLUGIN_OPTION_API_KEY" - export MEM0_API_KEY -fi -if [ -z "${MEM0_API_KEY:-}" ] && [ -n "${CLAUDE_PLUGIN_OPTION_MEM0_API_KEY:-}" ]; then - MEM0_API_KEY="$CLAUDE_PLUGIN_OPTION_MEM0_API_KEY" - export MEM0_API_KEY -fi -# Fallback: extract MEM0_API_KEY from shell profile files. -# The Desktop app only reads PATH from shell profiles — env vars like -# MEM0_API_KEY are not inherited. This grep-based extraction handles -# the common `export MEM0_API_KEY=...` pattern without sourcing the -# full profile (which could have side effects). -if [ -z "${MEM0_API_KEY:-}" ]; then - for _profile in "$HOME/.zshrc" "$HOME/.bashrc" "$HOME/.zprofile" "$HOME/.bash_profile" "$HOME/.profile"; do - if [ -f "$_profile" ]; then - _extracted=$(grep -E '^\s*(export\s+)?MEM0_API_KEY=' "$_profile" 2>/dev/null \ - | tail -1 \ - | sed 's/^[^=]*=//' \ - | sed "s/^[\"']//;s/[\"']$//" \ - | sed 's/#.*//' \ - | tr -d '[:space:]') - # Only use literal values — skip variable references like ${OTHER_VAR} - if [ -n "$_extracted" ] && [ "${_extracted#\$}" = "$_extracted" ]; then - MEM0_API_KEY="$_extracted" - export MEM0_API_KEY - break - fi - fi - done -fi - -_mem0_resolve_identity() { - if [ -n "${MEM0_USER_ID:-}" ]; then - printf '%s' "$MEM0_USER_ID" - return - fi - printf '%s' "${USER:-default}" -} - -MEM0_RESOLVED_USER_ID="$(_mem0_resolve_identity)" -export MEM0_RESOLVED_USER_ID - -_MEM0_IDENTITY_ANNOTATION="" -if [ -n "${MEM0_USER_ID:-}" ] && [ "$MEM0_USER_ID" != "${USER:-default}" ]; then - _MEM0_IDENTITY_ANNOTATION=" (override; default: ${USER:-default})" -fi -export _MEM0_IDENTITY_ANNOTATION - -# Load settings from ~/.mem0/settings.json -if command -v python3 >/dev/null 2>&1; then - _SETTINGS_JSON=$(PYTHONPATH="$_SCRIPT_DIR" python3 -c "from load_settings import load_settings; import json; print(json.dumps(load_settings()))" 2>/dev/null || echo "{}") - MEM0_AUTO_SAVE=$(echo "$_SETTINGS_JSON" | python3 -c "import sys,json; print(str(json.load(sys.stdin).get('auto_save',True)).lower())" 2>/dev/null || echo "true") - MEM0_AUTO_SEARCH=$(echo "$_SETTINGS_JSON" | python3 -c "import sys,json; print(str(json.load(sys.stdin).get('auto_search',True)).lower())" 2>/dev/null || echo "true") - MEM0_SEARCH_LIMIT=$(echo "$_SETTINGS_JSON" | python3 -c "import sys,json; print(json.load(sys.stdin).get('search_limit',10))" 2>/dev/null || echo "10") - MEM0_RETENTION_SESSION_DAYS=$(echo "$_SETTINGS_JSON" | python3 -c "import sys,json; print(json.load(sys.stdin).get('retention_session_days',90))" 2>/dev/null || echo "90") - MEM0_CONFIDENCE_THRESHOLD=$(echo "$_SETTINGS_JSON" | python3 -c "import sys,json; print(json.load(sys.stdin).get('confidence_threshold',0.3))" 2>/dev/null || echo "0.3") - MEM0_GLOBAL_SEARCH=$(echo "$_SETTINGS_JSON" | python3 -c "import sys,json; print(str(json.load(sys.stdin).get('global_search',False)).lower())" 2>/dev/null || echo "false") - MEM0_DEBUG=$(echo "$_SETTINGS_JSON" | python3 -c "import sys,json; print(str(json.load(sys.stdin).get('debug',False)).lower())" 2>/dev/null || echo "false") -else - MEM0_AUTO_SAVE="true" - MEM0_AUTO_SEARCH="true" - MEM0_SEARCH_LIMIT="10" - MEM0_RETENTION_SESSION_DAYS="90" - MEM0_CONFIDENCE_THRESHOLD="0.3" - MEM0_GLOBAL_SEARCH="false" - MEM0_DEBUG="false" -fi -export MEM0_AUTO_SAVE MEM0_AUTO_SEARCH MEM0_SEARCH_LIMIT MEM0_RETENTION_SESSION_DAYS MEM0_CONFIDENCE_THRESHOLD MEM0_GLOBAL_SEARCH MEM0_DEBUG - -# Also resolve project context -. "$_SCRIPT_DIR/_project.sh" diff --git a/integrations/mem0-plugin/scripts/_instructions.py b/integrations/mem0-plugin/scripts/_instructions.py deleted file mode 100644 index 8b4a5e8ae..000000000 --- a/integrations/mem0-plugin/scripts/_instructions.py +++ /dev/null @@ -1,51 +0,0 @@ -"""Resolve the project's mem0 extraction policy from ``mem0.md``. - -A repo's ``mem0.md`` can carry two prose sections that steer what Mem0 extracts: - - ## Instructions - Remember architecture decisions and conventions. Ignore debug noise and secrets. - - ## Agent Instructions - For agent-scoped memories, focus on the tools and task outcomes. - -``## Instructions`` maps to Mem0's ``custom_instructions`` (user/project-scoped -extraction) and ``## Agent Instructions`` to ``agent_custom_instructions`` -(agent-scoped extraction). Both are passed verbatim on memory writes, so the -policy lives in the repo, travels with it, and is shared by the whole team. - -The hook writers call :func:`load_instructions` and merge the result into their -``/v3/memories/add`` body. Returns only the keys that are actually set, so a -project with no policy adds nothing. -""" - -from __future__ import annotations - -import os - -from parse_mem0_config import load_full_config - - -def load_instructions(cwd: str | None = None) -> dict[str, str]: - """Return the extraction policy for the project at *cwd* (defaults to the - ``MEM0_CWD`` env var, then the process cwd). - - Keys (present only when non-empty): - - ``custom_instructions`` from ``## Instructions`` - - ``agent_custom_instructions`` from ``## Agent Instructions`` - """ - if cwd is None: - cwd = os.environ.get("MEM0_CWD") or os.getcwd() - - try: - config = load_full_config(cwd) - except Exception: - return {} - - out: dict[str, str] = {} - custom = config.get("instructions") - if isinstance(custom, str) and custom.strip(): - out["custom_instructions"] = custom.strip() - agent = config.get("agent_instructions") - if isinstance(agent, str) and agent.strip(): - out["agent_custom_instructions"] = agent.strip() - return out diff --git a/integrations/mem0-plugin/scripts/_project.py b/integrations/mem0-plugin/scripts/_project.py deleted file mode 100644 index eb64272b5..000000000 --- a/integrations/mem0-plugin/scripts/_project.py +++ /dev/null @@ -1,175 +0,0 @@ -"""Resolve mem0 project_id and branch. - -Resolution priority (project_id): - 1. MEM0_PROJECT_ID env var (explicit override) - 2. ~/.mem0/project_map.json lookup by cwd - 2b. ~/.mem0/project_map.json lookup by remote hash (self-healing fallback) - 3. Git remote slug: strip protocol/prefix, strip .git, replace / and : with - - e.g. git@github.com:mem0ai/mem0.git -> mem0ai-mem0 - 4. Fallback: basename of cwd -""" - -from __future__ import annotations - -import hashlib -import json -import os -import re -import subprocess - - -def resolve_project_id(cwd: str | None = None) -> str: - if cwd is None: - cwd = os.getcwd() - - # 1. Explicit override - explicit = os.environ.get("MEM0_PROJECT_ID", "").strip() - if explicit: - return explicit - - # 2. project_map.json lookup - map_path = os.path.expanduser("~/.mem0/project_map.json") - if os.path.isfile(map_path): - try: - with open(map_path) as f: - project_map = json.load(f) - mapped = project_map.get(cwd, "").strip() - if mapped: - return mapped - # 2b. Remote hash fallback (self-healing when folder is moved/renamed) - remote_key = _remote_hash_key(cwd) - if remote_key: - mapped = project_map.get(remote_key, "").strip() - if mapped: - # Self-heal: write the new CWD key so future lookups are fast - project_map[cwd] = mapped - try: - with open(map_path, "w") as f: - json.dump(project_map, f, indent=2) - except OSError: - pass - return mapped - except (OSError, json.JSONDecodeError, AttributeError): - pass - - # 3. Git remote slug - try: - result = subprocess.run( - ["git", "remote", "get-url", "origin"], - capture_output=True, - text=True, - check=True, - cwd=cwd, - ) - remote_url = result.stdout.strip() - if remote_url: - slug = _remote_url_to_slug(remote_url) - if slug: - return slug - except (subprocess.CalledProcessError, OSError): - pass - - # 4. Fallback: basename of cwd - return os.path.basename(cwd) or "unknown" - - -def resolve_branch(cwd: str | None = None) -> str: - if cwd is None: - cwd = os.getcwd() - try: - result = subprocess.run( - ["git", "branch", "--show-current"], - capture_output=True, - text=True, - check=True, - cwd=cwd, - ) - branch = result.stdout.strip() - return branch if branch else "unknown" - except (subprocess.CalledProcessError, OSError): - return "unknown" - - -def save_project_mapping(cwd: str, project_id: str) -> None: - """Write cwd -> project_id (and remote hash key -> project_id) into ~/.mem0/project_map.json.""" - mem0_dir = os.path.expanduser("~/.mem0") - os.makedirs(mem0_dir, exist_ok=True) - map_path = os.path.join(mem0_dir, "project_map.json") - project_map: dict[str, str] = {} - if os.path.isfile(map_path): - try: - with open(map_path) as f: - project_map = json.load(f) - except (OSError, json.JSONDecodeError): - project_map = {} - project_map[cwd] = project_id - # Also write the remote hash key so the mapping survives folder moves/renames - remote_key = _remote_hash_key(cwd) - if remote_key: - project_map[remote_key] = project_id - with open(map_path, "w") as f: - json.dump(project_map, f, indent=2) - - -def _remote_hash_key(cwd: str | None = None) -> str: - """Return a stable key derived from the git remote URL. - - Runs ``git config --get remote.origin.url`` in *cwd* and returns a string - of the form ``remote:``. Returns an empty string when - the directory is not a git repo or has no remote configured. - """ - if cwd is None: - cwd = os.getcwd() - try: - result = subprocess.run( - ["git", "config", "--get", "remote.origin.url"], - capture_output=True, - text=True, - check=True, - cwd=cwd, - ) - url = result.stdout.strip() - if not url: - return "" - digest = hashlib.sha256(url.encode()).hexdigest()[:16] - return f"remote:{digest}" - except (subprocess.CalledProcessError, OSError): - return "" - - -def _remote_url_to_slug(url: str) -> str: - """Convert a git remote URL to a deterministic slug. - - Handles: - - HTTPS: https://github.com/owner/repo.git - - SSH: git@github.com:owner/repo.git - - SSH: git@github.com-alias:owner/repo.git (custom host aliases) - - ssh://: ssh://git@github.com/owner/repo.git - - git://: git://github.com/owner/repo.git - """ - slug = url.strip() - # Strip .git suffix - if slug.endswith(".git"): - slug = slug[:-4] - # Strip protocol prefixes - for prefix in ("https://", "http://", "ssh://", "git://"): - if slug.startswith(prefix): - slug = slug[len(prefix):] - break - else: - # Handle git@ style (no protocol prefix matched) - slug = re.sub(r"^git@", "", slug) - # Replace the first colon (SSH host:path separator) with / - slug = slug.replace(":", "/", 1) - # Split on / and take last two components (owner, repo) - parts = [p for p in slug.split("/") if p] - if len(parts) >= 2: - owner, repo = parts[-2], parts[-1] - slug = f"{owner}-{repo}" - elif parts: - slug = parts[-1] - else: - return "" - # Replace any remaining / and : with - - slug = slug.replace("/", "-").replace(":", "-") - return slug diff --git a/integrations/mem0-plugin/scripts/_project.sh b/integrations/mem0-plugin/scripts/_project.sh deleted file mode 100755 index c4419ac3b..000000000 --- a/integrations/mem0-plugin/scripts/_project.sh +++ /dev/null @@ -1,77 +0,0 @@ -# Source this file. Sets MEM0_PROJECT_ID and MEM0_BRANCH. -# -# Resolution priority (project_id): -# 1. MEM0_PROJECT_ID env var (explicit override) -# 2. ~/.mem0/project_map.json lookup by $PWD (requires jq) -# 3. Git remote slug: strip protocol/prefix, strip .git, replace / and : with - -# e.g. git@github.com:mem0ai/mem0.git -> mem0ai-mem0 -# 4. Fallback: basename of $PWD -# -# Branch resolution: -# git branch --show-current, fallback "unknown" - -_mem0_resolve_project_id() { - # 1. Explicit override - if [ -n "${MEM0_PROJECT_ID:-}" ]; then - printf '%s' "$MEM0_PROJECT_ID" - return - fi - - # 2. project_map.json lookup by $PWD - _mem0_map="$HOME/.mem0/project_map.json" - if [ -f "$_mem0_map" ] && command -v jq >/dev/null 2>&1; then - _mem0_mapped=$(jq -r --arg cwd "$PWD" '.[$cwd] // empty' "$_mem0_map" 2>/dev/null) - if [ -n "$_mem0_mapped" ]; then - printf '%s' "$_mem0_mapped" - return - fi - fi - - # 3. Git remote slug - _mem0_remote_url=$(git remote get-url origin 2>/dev/null) - if [ -n "$_mem0_remote_url" ]; then - _mem0_slug="$_mem0_remote_url" - # Strip .git suffix - _mem0_slug="${_mem0_slug%.git}" - # Strip protocol prefixes - _mem0_slug="${_mem0_slug#https://}" - _mem0_slug="${_mem0_slug#http://}" - _mem0_slug="${_mem0_slug#ssh://}" - _mem0_slug="${_mem0_slug#git://}" - _mem0_slug="${_mem0_slug#git@}" - # Replace first colon (SSH host:path separator) with / - # shellcheck disable=SC2039 - _mem0_slug="${_mem0_slug/://}" - # Keep only the last two path components (owner/repo) - _mem0_owner=$(printf '%s' "$_mem0_slug" | awk -F'/' '{print $(NF-1)}') - _mem0_repo=$(printf '%s' "$_mem0_slug" | awk -F'/' '{print $NF}') - _mem0_slug="${_mem0_owner}-${_mem0_repo}" - # Replace any remaining / and : with - - # shellcheck disable=SC2039 - _mem0_slug="${_mem0_slug//\//-}" - # shellcheck disable=SC2039 - _mem0_slug="${_mem0_slug//:/-}" - if [ -n "$_mem0_slug" ]; then - printf '%s' "$_mem0_slug" - _MEM0_PERSIST_CWD="$PWD" _MEM0_PERSIST_SLUG="$_mem0_slug" python3 -c " -import os, sys -sys.path.insert(0, '$(dirname "${BASH_SOURCE[0]:-$0}")') -from _project import save_project_mapping -save_project_mapping(os.environ['_MEM0_PERSIST_CWD'], os.environ['_MEM0_PERSIST_SLUG']) -" 2>/dev/null || true - return - fi - fi - - # 4. Fallback: basename of $PWD - printf '%s' "$(basename "$PWD")" -} - -_mem0_resolve_branch() { - git branch --show-current 2>/dev/null || printf 'unknown' -} - -MEM0_PROJECT_ID="$(_mem0_resolve_project_id)" -MEM0_BRANCH="$(_mem0_resolve_branch)" -export MEM0_PROJECT_ID -export MEM0_BRANCH diff --git a/integrations/mem0-plugin/scripts/_search.py b/integrations/mem0-plugin/scripts/_search.py deleted file mode 100644 index 95db89ce9..000000000 --- a/integrations/mem0-plugin/scripts/_search.py +++ /dev/null @@ -1,105 +0,0 @@ -"""Shared mem0 search API helper. - -Wraps POST /v3/memories/search/ into a single function call. -All pre-fetch hooks use this instead of duplicating urllib boilerplate. -""" - -from __future__ import annotations - -import json -import os -import sys -import urllib.request - -SEARCH_URL = "https://api.mem0.ai/v3/memories/search/" -SEARCH_TIMEOUT = 5 - - -def should_rerank() -> bool: - """Whether auto-injection searches should request Platform reranking. - - The REST search endpoint does not rerank when ``rerank`` is omitted, so - auto-injected context is ordered by raw vector similarity and the single - most relevant memory can fall outside the injected top_k window. We default - reranking ON for the hook-driven injection path (the extra ~150-200ms is - well within the hook's curl budget) and let users opt out via MEM0_RERANK. - - MEM0_RERANK is read case-insensitively; ``0``, ``false``, ``no``, and - ``off`` disable reranking. Anything else (including unset) enables it. - """ - raw = os.environ.get("MEM0_RERANK") - if raw is None: - return True - return raw.strip().lower() not in ("0", "false", "no", "off", "") - - -def _do_search(api_key: str, payload: dict) -> list[dict]: - body = json.dumps(payload).encode() - req = urllib.request.Request( - SEARCH_URL, - data=body, - headers={"Authorization": f"Token {api_key}", "Content-Type": "application/json"}, - method="POST", - ) - with urllib.request.urlopen(req, timeout=SEARCH_TIMEOUT) as r: - data = json.loads(r.read()) - return data if isinstance(data, list) else data.get("results", []) - - -def search_memories( - api_key: str, - user_id: str, - project_id: str, - query: str, - metadata_type: str | None = None, - metadata_filters: dict | None = None, - top_k: int = 3, - min_score: float = 0.0, - rerank: bool = False, - threshold: float = 0.3, - global_search: bool = False, -) -> list[dict]: - if not api_key: - return [] - - if global_search: - filters: dict = {"OR": [{"user_id": "*"}]} - else: - base_clauses: list[dict] = [{"user_id": user_id}, {"app_id": project_id}] - if metadata_type: - base_clauses.append({"metadata": {"type": metadata_type}}) - if metadata_filters: - for key, value in metadata_filters.items(): - base_clauses.append({"metadata": {key: value}}) - filters = {"AND": base_clauses} - - base_payload: dict = {"query": query, "top_k": top_k, "threshold": threshold} - if rerank: - base_payload["rerank"] = True - - try: - payload = {**base_payload, "filters": filters} - results = _do_search(api_key, payload)[:top_k] - - if min_score > 0: - results = [m for m in results if m.get("score", 0) >= min_score] - return results - except Exception as e: - print(f"[mem0] search request failed: {e}", file=sys.stderr) - return [] - - -def format_results_for_context( - memories: list[dict], - heading: str = "Relevant memories", -) -> str: - if not memories: - return "" - lines = [f"### {heading}", ""] - for m in memories: - mid = m.get("id", "?")[:8] - text = m.get("memory", "")[:200] - cat = (m.get("metadata") or {}).get("type", "unknown") - lines.append(f"- [{cat}] {text} [mem0:{mid}]") - lines.append("") - return "\n".join(lines) diff --git a/integrations/mem0-plugin/scripts/auto_capture.py b/integrations/mem0-plugin/scripts/auto_capture.py deleted file mode 100755 index b48a928b4..000000000 --- a/integrations/mem0-plugin/scripts/auto_capture.py +++ /dev/null @@ -1,213 +0,0 @@ -#!/usr/bin/env python3 -"""Auto-capture recent conversation exchanges into mem0. - -Runs in the background from UserPromptSubmit hook (every 3rd message). -Reads the last few exchanges from the transcript, sends them to the -mem0 API with infer=True so the platform extracts facts automatically. - -Input: env vars (MEM0_API_KEY, MEM0_RESOLVED_USER_ID, MEM0_PROJECT_ID, etc.) - argv[1] = transcript_path -Output: stderr logs only (exit 0 always — must not block) -""" - -from __future__ import annotations - -import json -import logging -import os -import sys -import urllib.error -import urllib.request - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from _identity import resolve_api_key, resolve_user_id -from _instructions import load_instructions -from _project import resolve_branch, resolve_project_id - -log = logging.getLogger("mem0-auto-capture") -log.setLevel(logging.DEBUG) -_handler = logging.StreamHandler(sys.stderr) -_handler.setFormatter(logging.Formatter("[mem0-auto-capture] %(message)s")) -log.addHandler(_handler) - -if os.environ.get("MEM0_DEBUG"): - _log_dir = os.path.expanduser("~/.mem0") - try: - os.makedirs(_log_dir, exist_ok=True) - _fh = logging.FileHandler(os.path.join(_log_dir, "hooks.log")) - _fh.setFormatter(logging.Formatter("[mem0-auto-capture] %(asctime)s %(message)s")) - log.addHandler(_fh) - except OSError: - pass - -API_URL = "https://api.mem0.ai" -TAIL_LINES = 200 -MAX_CONTENT_CHARS = 8000 -MIN_CONTENT_CHARS = 100 - - -def tail_lines(filepath: str, n: int) -> list[str]: - try: - with open(filepath, "rb") as f: - f.seek(0, 2) - file_size = f.tell() - if file_size == 0: - return [] - chunk_size = min(file_size, n * 4096) - f.seek(max(0, file_size - chunk_size)) - data = f.read().decode("utf-8", errors="replace") - return data.splitlines()[-n:] - except OSError: - return [] - - -def extract_recent_exchanges(lines: list[str], max_exchanges: int = 3) -> list[dict]: - """Extract the last N user+assistant message pairs from the transcript JSONL.""" - messages = [] - for line in lines: - line = line.strip() - if not line: - continue - try: - entry = json.loads(line) - except json.JSONDecodeError: - continue - - if entry.get("isCompactSummary"): - continue - - msg = entry.get("message", {}) - role = msg.get("role", "") - if role not in ("user", "assistant"): - continue - - content = msg.get("content", "") - if isinstance(content, list): - parts = [] - for block in content: - if isinstance(block, str): - parts.append(block) - elif isinstance(block, dict) and block.get("type") == "text": - parts.append(block.get("text", "")) - content = "\n".join(parts).strip() - - if not content or len(content) < 20: - continue - - # Skip tool-call-only assistant messages - if role == "assistant" and content.startswith("{"): - continue - - messages.append({"role": role, "content": content[:2000]}) - - # Take last N exchanges (pairs of user+assistant) - if not messages: - return [] - - result = messages[-(max_exchanges * 2):] - return result - - -def store_exchange(api_key: str, messages: list[dict], user_id: str, - project_id: str, branch: str, session_id: str) -> bool: - metadata = { - "type": "auto_capture", - "source": "auto_capture", - "confidence": 0.7, - } - if branch: - metadata["branch"] = branch - if session_id: - metadata["session_id"] = session_id - - body = { - "messages": messages, - "user_id": user_id, - "app_id": project_id, - "metadata": metadata, - "infer": True, - } - # Apply the project's mem0.md extraction policy (custom/agent instructions). - body.update(load_instructions()) - - data = json.dumps(body).encode("utf-8") - req = urllib.request.Request( - f"{API_URL}/v3/memories/add/", - data=data, - headers={ - "Content-Type": "application/json", - "Authorization": f"Token {api_key}", - }, - method="POST", - ) - try: - with urllib.request.urlopen(req, timeout=15) as resp: - if resp.status in (200, 201): - result = json.loads(resp.read()) - log.info("Auto-captured: event_id=%s status=%s", - result.get("event_id", "?"), result.get("status", "?")) - return True - log.warning("API returned status %d", resp.status) - return False - except urllib.error.URLError as e: - log.warning("API call failed: %s", e) - return False - - -def main(): - api_key = resolve_api_key() - if not api_key: - log.debug("MEM0_API_KEY not set, skipping") - return - - if len(sys.argv) < 2: - log.debug("No transcript_path argument") - return - - transcript_path = sys.argv[1] - if not transcript_path or not os.path.isfile(transcript_path): - log.debug("Transcript not found: %s", transcript_path) - return - - user_id = resolve_user_id() - project_id = resolve_project_id() - branch = resolve_branch() - session_id = "" - sid_file = f"/tmp/mem0_session_id_{os.environ.get('USER', 'default')}" - if os.path.isfile(sid_file): - try: - with open(sid_file) as f: - session_id = f.read().strip() - except OSError: - pass - - lines = tail_lines(transcript_path, TAIL_LINES) - if not lines: - log.debug("Transcript empty") - return - - messages = extract_recent_exchanges(lines, max_exchanges=4) - if not messages: - log.debug("No substantial exchanges found") - return - - total_chars = sum(len(m["content"]) for m in messages) - if total_chars < MIN_CONTENT_CHARS: - log.debug("Exchanges too short (%d chars), skipping", total_chars) - return - - log.info("Auto-capturing %d messages (%d chars)", len(messages), total_chars) - if store_exchange(api_key, messages, user_id, project_id, branch, session_id): - try: - import session_stats - session_stats.record_add("auto_capture") - except Exception: - pass - - -if __name__ == "__main__": - try: - main() - except Exception as e: - log.error("Unexpected error: %s", e) - sys.exit(0) diff --git a/integrations/mem0-plugin/scripts/auto_import.py b/integrations/mem0-plugin/scripts/auto_import.py deleted file mode 100644 index 004772bbd..000000000 --- a/integrations/mem0-plugin/scripts/auto_import.py +++ /dev/null @@ -1,374 +0,0 @@ -#!/usr/bin/env python3 -"""Auto-import declarative project files into mem0. - -Runs in the background from the SessionStart hook (startup only). -Imports CLAUDE.md, AGENTS.md, .cursorrules, .windsurfrules, mem0.md -into mem0 as project profile memories, skipping unchanged files via -SHA-256 hashing. - -Input: MEM0_CWD env var (optional, defaults to os.getcwd()) -Output: stderr logs only (exit 0 always — must not block) -""" - -from __future__ import annotations - -import hashlib -import json -import logging -import os -import sys -import urllib.error -import urllib.request - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from _chunking import filter_and_truncate, split_by_headers -from _identity import resolve_api_key, resolve_user_id -from _project import resolve_branch, resolve_project_id, save_project_mapping - -log = logging.getLogger("mem0-auto-import") -log.setLevel(logging.DEBUG) -_handler = logging.StreamHandler(sys.stderr) -_handler.setFormatter(logging.Formatter("[mem0-auto-import] %(message)s")) -log.addHandler(_handler) - -if os.environ.get("MEM0_DEBUG"): - _log_dir = os.path.expanduser("~/.mem0") - try: - os.makedirs(_log_dir, exist_ok=True) - _file_handler = logging.FileHandler(os.path.join(_log_dir, "hooks.log")) - _file_handler.setFormatter(logging.Formatter("[mem0-auto-import] %(asctime)s %(message)s")) - log.addHandler(_file_handler) - except OSError: - pass - -API_URL = "https://api.mem0.ai" -MAX_FILE_SIZE = 100_000 # skip files over 100 KB -TARGET_FILES = ["CLAUDE.md", "AGENTS.md", ".cursorrules", ".windsurfrules", "mem0.md"] -HASH_STORE = os.path.expanduser("~/.mem0/file_hashes.json") -LOCK_FILE = os.path.expanduser("~/.mem0/auto_import.lock") - - -def _acquire_lock() -> bool: - """Try to acquire a file lock. Returns False if another instance is running.""" - try: - os.makedirs(os.path.dirname(LOCK_FILE), exist_ok=True) - fd = os.open(LOCK_FILE, os.O_CREAT | os.O_EXCL | os.O_WRONLY) - os.write(fd, str(os.getpid()).encode()) - os.close(fd) - return True - except FileExistsError: - try: - mtime = os.path.getmtime(LOCK_FILE) - import time - if time.time() - mtime > 120: - os.unlink(LOCK_FILE) - return _acquire_lock() - except OSError: - pass - return False - - -def _release_lock() -> None: - try: - os.unlink(LOCK_FILE) - except OSError: - pass - - -def _git_root(cwd: str) -> str: - """Return the git repo root, or empty string if not in a repo.""" - import subprocess - try: - result = subprocess.run( - ["git", "rev-parse", "--show-toplevel"], - cwd=cwd, capture_output=True, text=True, timeout=5, - ) - if result.returncode == 0: - return result.stdout.strip() - except (OSError, subprocess.TimeoutExpired): - pass - return "" - - -def sha256_file(path: str) -> str: - """Return the hex SHA-256 digest of a file.""" - h = hashlib.sha256() - with open(path, "rb") as f: - for chunk in iter(lambda: f.read(65536), b""): - h.update(chunk) - return h.hexdigest() - - -def load_hashes() -> dict[str, str]: - """Load the hash store from disk; return empty dict on any error.""" - if not os.path.isfile(HASH_STORE): - return {} - try: - with open(HASH_STORE) as f: - return json.load(f) - except (OSError, json.JSONDecodeError): - return {} - - -def save_hashes(hashes: dict[str, str]) -> None: - """Persist the hash store to disk.""" - mem0_dir = os.path.expanduser("~/.mem0") - os.makedirs(mem0_dir, exist_ok=True) - try: - with open(HASH_STORE, "w") as f: - json.dump(hashes, f, indent=2) - except OSError as e: - log.warning("Could not save hash store: %s", e) - - -def already_imported(api_key: str, user_id: str, project_id: str, filename: str) -> bool: - body = json.dumps({ - "query": filename, - "filters": { - "AND": [ - {"user_id": user_id}, - {"app_id": project_id}, - {"metadata": {"source": "auto-import"}}, - ] - }, - "top_k": 10, - "threshold": 0.0, - }).encode() - req = urllib.request.Request( - f"{API_URL}/v3/memories/search/", - data=body, - headers={"Content-Type": "application/json", "Authorization": f"Token {api_key}"}, - method="POST", - ) - try: - with urllib.request.urlopen(req, timeout=5) as r: - data = json.loads(r.read()) - results = data if isinstance(data, list) else data.get("results", []) - for result in results: - meta = result.get("metadata", {}) if isinstance(result, dict) else {} - file_field = meta.get("file", "") - if file_field == filename or file_field.startswith(f"{filename}["): - return True - return False - except Exception: - return False - - -def _delete_stale_chunks(api_key: str, user_id: str, project_id: str, filename: str) -> int: - """Find and delete existing chunks for a file before re-import. Returns count deleted.""" - body = json.dumps({ - "query": filename, - "filters": { - "AND": [ - {"user_id": user_id}, - {"app_id": project_id}, - {"metadata": {"source": "auto-import"}}, - ] - }, - "top_k": 20, - "threshold": 0.0, - }).encode() - req = urllib.request.Request( - f"{API_URL}/v3/memories/search/", - data=body, - headers={"Content-Type": "application/json", "Authorization": f"Token {api_key}"}, - method="POST", - ) - ids_to_delete = [] - try: - with urllib.request.urlopen(req, timeout=10) as r: - data = json.loads(r.read()) - results = data if isinstance(data, list) else data.get("results", []) - for result in results: - if not isinstance(result, dict): - continue - meta = result.get("metadata", {}) - file_field = meta.get("file", "") - if file_field == filename or file_field.startswith(f"{filename}["): - mid = result.get("id") - if mid: - ids_to_delete.append(mid) - except Exception as e: - log.warning("Failed to search for stale chunks of %s: %s", filename, e) - return 0 - - deleted = 0 - for mid in ids_to_delete: - try: - del_req = urllib.request.Request( - f"{API_URL}/v1/memories/{mid}/", - headers={"Authorization": f"Token {api_key}"}, - method="DELETE", - ) - with urllib.request.urlopen(del_req, timeout=10): - deleted += 1 - except Exception as e: - log.warning("Failed to delete stale chunk %s: %s", mid, e) - - if deleted: - log.info("Deleted %d stale chunk(s) for %s before re-import", deleted, filename) - return deleted - - -def post_memory(api_key: str, content: str, user_id: str, filename: str, project_id: str, branch: str = "") -> bool: - """POST a project profile memory to the Mem0 REST API.""" - metadata = { - "type": "project_profile", - "file": filename, - "source": "auto-import", - } - if branch: - metadata["branch"] = branch - body = { - "messages": [ - { - "role": "user", - "content": f"## Project Profile: {filename}\n\nProject: {project_id}\n\n{content}", - } - ], - "user_id": user_id, - "app_id": project_id, - "metadata": metadata, - "infer": False, - } - - data = json.dumps(body).encode("utf-8") - req = urllib.request.Request( - f"{API_URL}/v3/memories/add/", - data=data, - headers={ - "Content-Type": "application/json", - "Authorization": f"Token {api_key}", - }, - method="POST", - ) - - try: - with urllib.request.urlopen(req, timeout=15) as resp: - if resp.status in (200, 201): - log.info("Imported %s (project=%s)", filename, project_id) - return True - log.warning("API returned status %d for %s", resp.status, filename) - return False - except urllib.error.URLError as e: - log.warning("API call failed for %s: %s", filename, e) - return False - - -def main() -> None: - api_key = resolve_api_key() - if not api_key: - log.debug("MEM0_API_KEY not set, skipping auto-import") - return - - cwd = os.environ.get("MEM0_CWD", "").strip() or os.getcwd() - user_id = resolve_user_id() - project_id = resolve_project_id(cwd) - branch = resolve_branch(cwd) - - save_project_mapping(cwd, project_id) - - git_root = _git_root(cwd) - search_dirs = [cwd] - if git_root and os.path.realpath(git_root) != os.path.realpath(cwd): - search_dirs.append(git_root) - - log.debug("Auto-import started: cwd=%s git_root=%s project=%s user=%s branch=%s", cwd, git_root or "(none)", project_id, user_id, branch) - - hashes = load_hashes() - updated = False - seen_content_hashes: set[str] = set() - - for filename in TARGET_FILES: - filepath = "" - for search_dir in search_dirs: - candidate = os.path.join(search_dir, filename) - if os.path.isfile(candidate): - filepath = candidate - break - - if not filepath: - log.debug("Not found, skipping: %s", filename) - continue - - filepath = os.path.realpath(filepath) - - try: - file_size = os.path.getsize(filepath) - except OSError: - log.debug("Cannot stat %s, skipping", filename) - continue - - if file_size > MAX_FILE_SIZE: - log.debug("Skipping %s: size %d exceeds %d bytes", filename, file_size, MAX_FILE_SIZE) - continue - - try: - current_hash = sha256_file(filepath) - except OSError as e: - log.debug("Cannot hash %s: %s", filename, e) - continue - - if current_hash in seen_content_hashes: - log.debug("Duplicate content, skipping: %s (same as earlier file)", filename) - continue - seen_content_hashes.add(current_hash) - - hash_key = f"{project_id}:{branch}:{filename}" if branch else f"{project_id}:{filename}" - if hashes.get(hash_key) == current_hash: - if already_imported(api_key, user_id, project_id, filename): - log.debug("Unchanged and still in mem0, skipping: %s", filename) - continue - log.info("Hash matches but memories missing server-side, re-importing: %s", filename) - - elif already_imported(api_key, user_id, project_id, filename): - log.debug("Already in mem0, updating hash store: %s", filename) - hashes[hash_key] = current_hash - updated = True - continue - - try: - with open(filepath, encoding="utf-8", errors="replace") as f: - content = f.read() - except OSError as e: - log.debug("Cannot read %s: %s", filename, e) - continue - - _delete_stale_chunks(api_key, user_id, project_id, filename) - - is_markdown = filename.endswith(".md") - if is_markdown: - chunks = filter_and_truncate(split_by_headers(content)) - else: - chunks = filter_and_truncate([content]) - - if not chunks: - chunks = [content[:10000]] - - success = True - for i, chunk in enumerate(chunks): - chunk_name = f"{filename}[{i+1}/{len(chunks)}]" if len(chunks) > 1 else filename - if not post_memory(api_key, chunk, user_id, chunk_name, project_id, branch): - success = False - - if success: - hashes[hash_key] = current_hash - updated = True - - if updated: - save_hashes(hashes) - else: - log.debug("No files imported this run") - - -if __name__ == "__main__": - if not _acquire_lock(): - log.debug("Another auto_import instance is running — skipping") - sys.exit(0) - try: - main() - except Exception as e: - log.error("Unexpected error: %s", e) - finally: - _release_lock() - sys.exit(0) diff --git a/integrations/mem0-plugin/scripts/auto_setup_categories.py b/integrations/mem0-plugin/scripts/auto_setup_categories.py deleted file mode 100644 index a94ed00a5..000000000 --- a/integrations/mem0-plugin/scripts/auto_setup_categories.py +++ /dev/null @@ -1,236 +0,0 @@ -#!/usr/bin/env python3 -"""Auto-configure mem0's coding-category taxonomy in the background. - -Runs from the SessionStart hook (startup only), exactly like auto_import.py. -mem0 auto-tags every memory with `categories`; by default that list is -consumer-oriented (food, hobbies, ...), which is useless for code. This script -replaces it with the coding-focused taxonomy defined in -``setup_coding_categories.CODING_CATEGORIES`` so search and retrieval are tuned -for development work — without the user ever being asked during onboarding. - -Design (mirrors auto_import.py): - - Resolve the API key; do nothing if it is absent. - - Gate on a state file (``~/.mem0/categories_setup.json``) keyed by a hash of - the API key -> a hash of the taxonomy. Categories are scoped to the mem0 - *project* tied to the API key (NOT to the local repo), so this only needs to - run once per account, and re-runs only if the taxonomy itself changes. - - Hold a lock file so concurrent sessions don't race. - - Reuse the proven SDK path (``client.project.update``) via the plugin venv. - - Always exit 0; log to stderr only. Must never block a session. - -Run with no arguments (background) or in the foreground for onboarding to print -a parseable status line. - -Requires MEM0_API_KEY (or CLAUDE_PLUGIN_OPTION_API_KEY) and the mem0ai SDK, -which ensure_deps.sh installs into ${CLAUDE_PLUGIN_DATA}/venv on session start. -""" - -from __future__ import annotations - -import hashlib -import json -import logging -import os -import sys -import time - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -# Importing setup_coding_categories also injects the plugin venv's site-packages -# onto sys.path (its module-level bootstrap), so ``from mem0 import MemoryClient`` -# works even when this script is run with the system python3. -from _identity import resolve_api_key # noqa: E402 -from setup_coding_categories import CODING_CATEGORIES, _categories_match # noqa: E402 - -log = logging.getLogger("mem0-auto-categories") -log.setLevel(logging.DEBUG) -_handler = logging.StreamHandler(sys.stderr) -_handler.setFormatter(logging.Formatter("[mem0-auto-categories] %(message)s")) -log.addHandler(_handler) - -if os.environ.get("MEM0_DEBUG"): - _log_dir = os.path.expanduser("~/.mem0") - try: - os.makedirs(_log_dir, exist_ok=True) - _file_handler = logging.FileHandler(os.path.join(_log_dir, "hooks.log")) - _file_handler.setFormatter(logging.Formatter("[mem0-auto-categories] %(asctime)s %(message)s")) - log.addHandler(_file_handler) - except OSError: - pass - -STATE_FILE = os.path.expanduser("~/.mem0/categories_setup.json") -LOCK_FILE = os.path.expanduser("~/.mem0/categories_setup.lock") - - -# --------------------------------------------------------------------------- # -# Fingerprints # -# --------------------------------------------------------------------------- # -def categories_fingerprint(categories: list = CODING_CATEGORIES) -> str: - """Stable, order-independent 16-hex digest of the category taxonomy. - - Reordering the categories yields the same fingerprint; adding, removing, or - editing a category changes it (so the taxonomy re-applies on upgrade). - """ - pairs = sorted( - (str(key), str(value)) - for entry in categories - if isinstance(entry, dict) - for key, value in entry.items() - ) - payload = json.dumps(pairs, sort_keys=True, ensure_ascii=False) - return hashlib.sha256(payload.encode("utf-8")).hexdigest()[:16] - - -def apikey_fingerprint(api_key: str) -> str: - """Opaque 16-hex digest of the API key. Never stores the key itself.""" - return hashlib.sha256(api_key.encode("utf-8")).hexdigest()[:16] - - -# --------------------------------------------------------------------------- # -# State file # -# --------------------------------------------------------------------------- # -def load_state(path: str = STATE_FILE) -> dict: - """Load the apikey-fingerprint -> categories-fingerprint map; {} on any error.""" - if not os.path.isfile(path): - return {} - try: - with open(path) as f: - data = json.load(f) - return data if isinstance(data, dict) else {} - except (OSError, json.JSONDecodeError): - return {} - - -def save_state(state: dict, path: str = STATE_FILE) -> None: - """Persist the state map, creating the parent directory if needed.""" - parent = os.path.dirname(path) - if parent: - try: - os.makedirs(parent, exist_ok=True) - except OSError as e: - log.warning("Could not create state dir: %s", e) - return - try: - with open(path, "w") as f: - json.dump(state, f, indent=2) - except OSError as e: - log.warning("Could not save categories state: %s", e) - - -def is_applied(state: dict, key_fp: str, cat_fp: str) -> bool: - """True only when this API key has already had this exact taxonomy applied.""" - return state.get(key_fp) == cat_fp - - -# --------------------------------------------------------------------------- # -# SDK interaction (client injected for testability) # -# --------------------------------------------------------------------------- # -def make_client(): - """Construct a MemoryClient. Imported lazily so this module loads without the SDK.""" - from mem0 import MemoryClient - - return MemoryClient() - - -def fetch_current_categories(client) -> list | None: - """Return the project's current custom_categories, or None if unavailable.""" - current = client.project.get(fields=["custom_categories"]) - if isinstance(current, dict): - return current.get("custom_categories") - return None - - -def apply_categories(client, proposed: list = CODING_CATEGORIES) -> str: - """Install the coding taxonomy if it isn't already in place. - - Returns "already-configured" when the project already matches (no write), or - "applied" after a successful ``project.update``. Raises on API failure. - """ - current = fetch_current_categories(client) - if _categories_match(current, proposed): - return "already-configured" - client.project.update(custom_categories=proposed) - return "applied" - - -# --------------------------------------------------------------------------- # -# Lock (mirrors auto_import.py) # -# --------------------------------------------------------------------------- # -def _acquire_lock() -> bool: - """Try to acquire a file lock. Returns False if another instance is running.""" - try: - os.makedirs(os.path.dirname(LOCK_FILE), exist_ok=True) - fd = os.open(LOCK_FILE, os.O_CREAT | os.O_EXCL | os.O_WRONLY) - os.write(fd, str(os.getpid()).encode()) - os.close(fd) - return True - except FileExistsError: - try: - if time.time() - os.path.getmtime(LOCK_FILE) > 120: - os.unlink(LOCK_FILE) - return _acquire_lock() - except OSError: - pass - return False - - -def _release_lock() -> None: - try: - os.unlink(LOCK_FILE) - except OSError: - pass - - -# --------------------------------------------------------------------------- # -# Entry point # -# --------------------------------------------------------------------------- # -def main() -> None: - api_key = resolve_api_key() - if not api_key: - log.debug("MEM0_API_KEY not set, skipping coding-categories setup") - return - - key_fp = apikey_fingerprint(api_key) - cat_fp = categories_fingerprint() - - state = load_state() - if is_applied(state, key_fp, cat_fp): - log.debug("Coding categories already configured for this account (cached); skipping") - return - - os.environ["MEM0_API_KEY"] = api_key - - try: - client = make_client() - except ImportError: - log.debug("mem0ai SDK not ready yet (venv installing?); will retry next session") - return - except Exception as e: - log.warning("Could not initialise MemoryClient: %s", e) - return - - try: - result = apply_categories(client) - except Exception as e: - log.warning("Could not configure coding categories: %s", e) - return - - state[key_fp] = cat_fp - save_state(state) - - if result == "applied": - log.info("Applied %d coding categories", len(CODING_CATEGORIES)) - else: - log.info("Coding categories already configured") - - -if __name__ == "__main__": - if not _acquire_lock(): - log.debug("Another auto_setup_categories instance is running — skipping") - sys.exit(0) - try: - main() - except Exception as e: # never block a session - log.error("Unexpected error: %s", e) - finally: - _release_lock() - sys.exit(0) diff --git a/integrations/mem0-plugin/scripts/block_memory_write.sh b/integrations/mem0-plugin/scripts/block_memory_write.sh deleted file mode 100755 index 1b3802663..000000000 --- a/integrations/mem0-plugin/scripts/block_memory_write.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# Hook: PreToolUse (matcher: Write|Edit) -# -# Blocks writes to MEMORY.md and auto-memory files, redirecting Claude -# to use the mem0 MCP add_memory tool instead. -# -# Input: JSON on stdin with tool_name, tool_input -# Output: stderr message (exit 2 = block) -# -# Exit codes: -# 0 = allow the tool call -# 2 = block the tool call (stderr is shown to Claude as feedback) - -set -euo pipefail - -if [ -n "${MEM0_DEBUG:-}" ]; then - mkdir -p "$HOME/.mem0" && exec 2>>"$HOME/.mem0/hooks.log" -fi - -INPUT=$(cat) - -FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""' 2>/dev/null || echo "") - -if [ -z "$FILE_PATH" ]; then - exit 0 -fi - -case "$FILE_PATH" in - */.claude/*/MEMORY.md|*/.claude/memory/*) - echo "BLOCKED: Do not write to $FILE_PATH. Use the mem0 MCP \`add_memory\` tool instead to persist memories. This project uses mem0 for all memory storage." >&2 - exit 2 - ;; - *) - exit 0 - ;; -esac diff --git a/integrations/mem0-plugin/scripts/block_memory_write_cursor.sh b/integrations/mem0-plugin/scripts/block_memory_write_cursor.sh deleted file mode 100755 index 21b2cf0f8..000000000 --- a/integrations/mem0-plugin/scripts/block_memory_write_cursor.sh +++ /dev/null @@ -1,33 +0,0 @@ -#!/usr/bin/env bash -# Hook: preToolUse (Cursor) — blocks writes to MEMORY.md -# -# Cursor variant of block_memory_write.sh. Returns JSON: -# {"permission":"deny","agent_message":"..."} on block, -# {"permission":"allow"} on pass. - -set -uo pipefail - -if [ -n "${MEM0_DEBUG:-}" ]; then - mkdir -p "$HOME/.mem0" && exec 2>>"$HOME/.mem0/hooks.log" -fi - -INPUT=$(cat) - -FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // .tool_input.path // ""' 2>/dev/null || echo "") - -if [ -z "$FILE_PATH" ]; then - jq -cn '{permission:"allow"}' - exit 0 -fi - -case "$FILE_PATH" in - */MEMORY.md|*/.claude/memory/*|*/.cursor/memory/*) - jq -cn --arg msg "Do not write to $FILE_PATH. Use the mem0 MCP add_memory tool instead to persist memories." \ - '{permission:"deny", agent_message:$msg}' - exit 0 - ;; - *) - jq -cn '{permission:"allow"}' - exit 0 - ;; -esac diff --git a/integrations/mem0-plugin/scripts/capture_compact_summary.py b/integrations/mem0-plugin/scripts/capture_compact_summary.py deleted file mode 100644 index d2f7de0ba..000000000 --- a/integrations/mem0-plugin/scripts/capture_compact_summary.py +++ /dev/null @@ -1,203 +0,0 @@ -#!/usr/bin/env python3 -"""Capture the post-compaction summary into mem0. - -PreCompact hooks fire BEFORE the summary is generated, so they can't -store the actual compact-summary text. This script runs at -SessionStart with source=compact, reads the transcript, finds the -most recent entry flagged isCompactSummary=true, and stores it as a -memory tagged metadata.type=compact_summary. - -Input: JSON on stdin with transcript_path, session_id, source -Output: stderr logs only (exit 0 always -- must not block) - -Spawned in the background by on_session_start.sh; the user-facing -bootstrap text continues without waiting on the network. -""" - -from __future__ import annotations - -import json -import logging -import os -import sys -import urllib.error -import urllib.request -from datetime import date, timedelta - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from _identity import resolve_api_key, resolve_user_id -from _instructions import load_instructions -from _project import resolve_branch, resolve_project_id - -log = logging.getLogger("mem0-compact-summary") -log.setLevel(logging.DEBUG) -_handler = logging.StreamHandler(sys.stderr) -_handler.setFormatter(logging.Formatter("[mem0-compact-summary] %(message)s")) -log.addHandler(_handler) - -if os.environ.get("MEM0_DEBUG"): - _log_dir = os.path.expanduser("~/.mem0") - try: - os.makedirs(_log_dir, exist_ok=True) - _file_handler = logging.FileHandler(os.path.join(_log_dir, "hooks.log")) - _file_handler.setFormatter(logging.Formatter("[mem0-compact-summary] %(asctime)s %(message)s")) - log.addHandler(_file_handler) - except OSError: - pass - -API_URL = "https://api.mem0.ai" -MAX_TAIL_LINES = 2000 -MAX_SUMMARY_CHARS = 50000 -# Compact summaries describe a single session's state -- stale after a quarter. -COMPACT_SUMMARY_EXPIRY_DAYS = 90 - - -def tail_lines(filepath: str, n: int) -> list[str]: - try: - with open(filepath, "rb") as f: - f.seek(0, 2) - file_size = f.tell() - if file_size == 0: - return [] - chunk_size = min(file_size, n * 4096) - f.seek(max(0, file_size - chunk_size)) - data = f.read().decode("utf-8", errors="replace") - return data.splitlines()[-n:] - except OSError: - return [] - - -def find_compact_summary(lines: list[str]) -> str: - """Walk transcript backwards, return text content of the most recent - entry flagged isCompactSummary=true. Empty string if none found.""" - for line in reversed(lines): - line = line.strip() - if not line: - continue - try: - entry = json.loads(line) - except json.JSONDecodeError: - continue - if not entry.get("isCompactSummary"): - continue - - message = entry.get("message", {}) - content = message.get("content", []) - if isinstance(content, str): - return content[:MAX_SUMMARY_CHARS] - if isinstance(content, list): - parts = [] - for block in content: - if isinstance(block, str): - parts.append(block) - elif isinstance(block, dict) and block.get("type") == "text": - parts.append(block.get("text", "")) - return "\n".join(parts).strip()[:MAX_SUMMARY_CHARS] - return "" - - -def store_summary(api_key: str, summary: str, user_id: str, session_id: str, project_id: str = "", branch: str = "", cwd: str | None = None) -> bool: - expires = (date.today() + timedelta(days=COMPACT_SUMMARY_EXPIRY_DAYS)).isoformat() - metadata = { - "type": "compact_summary", - "source": "session-start-compact", - "session_id": session_id, - } - if branch: - metadata["branch"] = branch - # The compact summary is model-authored prose, in the first person and with no - # framing to mark it as such. Under role="user" mem0 reads "I recommend X" as - # the human saying it and stores "User recommends X". - body = { - "messages": [{"role": "assistant", "content": summary}], - "user_id": user_id, - "app_id": project_id, - "metadata": metadata, - "infer": True, - "expiration_date": expires, - } - # Apply the project's mem0.md extraction policy (custom/agent instructions). - body.update(load_instructions(cwd)) - - data = json.dumps(body).encode("utf-8") - req = urllib.request.Request( - f"{API_URL}/v3/memories/add/", - data=data, - headers={ - "Content-Type": "application/json", - "Authorization": f"Token {api_key}", - }, - method="POST", - ) - try: - with urllib.request.urlopen(req, timeout=15) as resp: - if resp.status in (200, 201): - log.info("Compact summary stored") - return True - log.warning("API returned status %d", resp.status) - return False - except urllib.error.URLError as e: - log.warning("API call failed: %s", e) - return False - - -def main(): - api_key = resolve_api_key() - if not api_key: - log.debug("MEM0_API_KEY not set, skipping capture") - return - - try: - hook_input = json.loads(sys.stdin.read()) - except (json.JSONDecodeError, OSError): - log.debug("No valid JSON on stdin") - return - - transcript_path = hook_input.get("transcript_path", "") - if not transcript_path: - log.debug("No transcript_path provided") - return - - session_id = hook_input.get("session_id", "") - cwd = hook_input.get("cwd") or None - user_id = resolve_user_id() - project_id = resolve_project_id(cwd) - branch = resolve_branch(cwd) - - lines = tail_lines(transcript_path, MAX_TAIL_LINES) - if not lines: - log.debug("Transcript empty or unreadable: %s", transcript_path) - return - - summary = find_compact_summary(lines) - if not summary: - log.debug("No isCompactSummary entry found") - return - - if len(summary.strip()) < 100: - log.debug("Compact summary too short (%d chars) — skipping", len(summary.strip())) - return - - marker_dir = os.path.expanduser("~/.mem0") - marker_file = os.path.join(marker_dir, f"compact_captured_{session_id}") - if session_id and os.path.isfile(marker_file): - log.info("Compact summary already captured for session %s — skipping", session_id) - return - - log.info("Capturing compact summary (%d chars)", len(summary)) - if store_summary(api_key, summary, user_id, session_id, project_id, branch, cwd): - if session_id: - try: - os.makedirs(marker_dir, exist_ok=True) - with open(marker_file, "w") as f: - f.write("") - except OSError: - pass - - -if __name__ == "__main__": - try: - main() - except Exception as e: - log.error("Unexpected error: %s", e) - sys.exit(0) diff --git a/integrations/mem0-plugin/scripts/capture_session_summary.py b/integrations/mem0-plugin/scripts/capture_session_summary.py deleted file mode 100644 index 6c3fa92fa..000000000 --- a/integrations/mem0-plugin/scripts/capture_session_summary.py +++ /dev/null @@ -1,272 +0,0 @@ -#!/usr/bin/env python3 -"""Capture a structured session summary on Stop hook. - -Runs on every Stop (end of each assistant turn). Each invocation reads -the transcript JSONL, extracts the latest assistant message and all -files touched so far, then stores via mem0 API with infer=True. Uses -run_id=session_id to scope infer dedup to the session, so the final -stored summary reflects the most recent turn — not just the first. - -Input: JSON on stdin with transcript_path, session_id, cwd, agent_id -Output: stderr logs only (exit 0 always — must not block) -""" - -from __future__ import annotations - -import json -import logging -import os -import re -import sys -import urllib.error -import urllib.request -from datetime import date, timedelta - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from _identity import resolve_api_key, resolve_user_id -from _instructions import load_instructions -from _project import resolve_branch, resolve_project_id - -log = logging.getLogger("mem0-session-summary") -log.setLevel(logging.DEBUG) -_handler = logging.StreamHandler(sys.stderr) -_handler.setFormatter(logging.Formatter("[mem0-session-summary] %(message)s")) -log.addHandler(_handler) - -if os.environ.get("MEM0_DEBUG"): - _log_dir = os.path.expanduser("~/.mem0") - try: - os.makedirs(_log_dir, exist_ok=True) - _fh = logging.FileHandler(os.path.join(_log_dir, "hooks.log")) - _fh.setFormatter(logging.Formatter("[mem0-session-summary] %(asctime)s %(message)s")) - log.addHandler(_fh) - except OSError: - pass - -API_URL = "https://api.mem0.ai" -MAX_TAIL_LINES = 3000 -MAX_SUMMARY_CHARS = 50000 -SUMMARY_EXPIRY_DAYS = 90 - -SYSTEM_TAG_RE = re.compile( - r"<(?:system-reminder|private|claude-mem-context|persisted-output|system_instruction)>" - r".*?" - r"", - re.DOTALL, -) - - -def tail_lines(filepath: str, n: int) -> list[str]: - try: - with open(filepath, "rb") as f: - f.seek(0, 2) - file_size = f.tell() - if file_size == 0: - return [] - chunk_size = min(file_size, n * 4096) - f.seek(max(0, file_size - chunk_size)) - data = f.read().decode("utf-8", errors="replace") - return data.splitlines()[-n:] - except OSError: - return [] - - -def extract_last_assistant_message(lines: list[str]) -> str: - """Walk transcript backwards, return text content of the last assistant message.""" - for line in reversed(lines): - line = line.strip() - if not line: - continue - if '"type":"assistant"' not in line and '"type": "assistant"' not in line: - continue - try: - entry = json.loads(line) - except json.JSONDecodeError: - continue - if entry.get("type") != "assistant": - continue - message = entry.get("message", {}) - content = message.get("content", []) - if isinstance(content, str): - return content - if isinstance(content, list): - parts = [] - for block in content: - if isinstance(block, str): - parts.append(block) - elif isinstance(block, dict) and block.get("type") == "text": - parts.append(block.get("text", "")) - return "\n".join(parts).strip() - return "" - - -def extract_files_touched(lines: list[str]) -> list[str]: - """Extract unique file paths from tool_use content blocks in transcript.""" - files = set() - file_ext_re = re.compile( - r"[a-zA-Z0-9_./-]+\.(?:py|ts|tsx|js|jsx|rs|go|rb|java|sh|yaml|yml|json|toml|md|sql|css|html)" - ) - for line in lines: - line = line.strip() - if not line: - continue - if '"tool_use"' not in line and '"file_path"' not in line: - continue - try: - entry = json.loads(line) - except json.JSONDecodeError: - continue - content = entry.get("message", {}).get("content", []) - if not isinstance(content, list): - continue - for block in content: - if not isinstance(block, dict) or block.get("type") != "tool_use": - continue - inp = block.get("input", {}) - if not isinstance(inp, dict): - continue - fp = inp.get("file_path", "") - if fp: - files.add(fp) - command = inp.get("command", "") - if command: - for match in file_ext_re.findall(command): - files.add(match) - return sorted(files)[:20] - - -def strip_tags(text: str) -> str: - return SYSTEM_TAG_RE.sub("", text).strip() - - -def build_summary_prompt(assistant_msg: str, files: list[str]) -> str: - """Build a structured prompt that helps mem0's AI extract a good summary.""" - files_section = "" - if files: - file_list = ", ".join(files[:10]) - files_section = f"\n\nFiles touched during this session: {file_list}" - - return ( - f"Session summary — store the following as a structured session summary.\n\n" - f"What the assistant accomplished in this session:\n" - f"{assistant_msg[:MAX_SUMMARY_CHARS]}" - f"{files_section}\n\n" - f"Extract and remember: what was requested, what was investigated, " - f"key decisions made, what was completed, and what needs to happen next." - ) - - -def store_summary( - api_key: str, - summary_prompt: str, - user_id: str, - session_id: str, - project_id: str, - branch: str, - files: list[str], - cwd: str | None = None, -) -> bool: - expires = (date.today() + timedelta(days=SUMMARY_EXPIRY_DAYS)).isoformat() - metadata = { - "type": "session_summary", - "source": "stop-hook", - "session_id": session_id, - } - if branch: - metadata["branch"] = branch - if files: - metadata["files_touched"] = files[:20] - - # summary_prompt wraps the assistant's own last message. Mem0 extracts "facts - # about the user" from each message and role is the only signal telling it who - # spoke, so role="user" here turns Claude's opinions into the human's stated - # preferences ("User prefers dropping Redis..."). - body = { - "messages": [{"role": "assistant", "content": summary_prompt}], - "user_id": user_id, - "app_id": project_id, - "run_id": session_id, - "metadata": metadata, - "infer": True, - "expiration_date": expires, - } - # Apply the project's mem0.md extraction policy (custom/agent instructions). - body.update(load_instructions(cwd)) - - data = json.dumps(body).encode("utf-8") - req = urllib.request.Request( - f"{API_URL}/v3/memories/add/", - data=data, - headers={ - "Content-Type": "application/json", - "Authorization": f"Token {api_key}", - }, - method="POST", - ) - try: - with urllib.request.urlopen(req, timeout=15) as resp: - if resp.status in (200, 201): - log.info("Session summary stored") - return True - log.warning("API returned status %d", resp.status) - return False - except urllib.error.URLError as e: - log.warning("API call failed: %s", e) - return False - - -def main(): - api_key = resolve_api_key() - if not api_key: - log.debug("MEM0_API_KEY not set, skipping") - return - - try: - hook_input = json.loads(sys.stdin.read()) - except (json.JSONDecodeError, OSError): - log.debug("No valid JSON on stdin") - return - - # Guard: skip subagent sessions (only root sessions get summaries) - agent_id = hook_input.get("agent_id", "") - if agent_id: - log.debug("Subagent session (agent_id=%s), skipping", agent_id) - return - - transcript_path = hook_input.get("transcript_path", "") - if not transcript_path: - log.debug("No transcript_path provided") - return - - session_id = hook_input.get("session_id", "") - cwd = hook_input.get("cwd") or None - - user_id = resolve_user_id() - project_id = resolve_project_id(cwd) - branch = resolve_branch(cwd) - - lines = tail_lines(transcript_path, MAX_TAIL_LINES) - if not lines: - log.debug("Transcript empty or unreadable: %s", transcript_path) - return - - assistant_msg = extract_last_assistant_message(lines) - if not assistant_msg or len(assistant_msg.strip()) < 100: - log.debug("Assistant message too short (%d chars) — skipping", len(assistant_msg.strip())) - return - - assistant_msg = strip_tags(assistant_msg) - files = extract_files_touched(lines) - - summary_prompt = build_summary_prompt(assistant_msg, files) - - log.info("Capturing session summary (%d chars, %d files)", len(assistant_msg), len(files)) - store_summary(api_key, summary_prompt, user_id, session_id, project_id, branch, files, cwd) - - -if __name__ == "__main__": - try: - main() - except Exception as e: - log.error("Unexpected error: %s", e) - sys.exit(0) diff --git a/integrations/mem0-plugin/scripts/enforce_metadata_defaults.sh b/integrations/mem0-plugin/scripts/enforce_metadata_defaults.sh deleted file mode 100755 index e24b63648..000000000 --- a/integrations/mem0-plugin/scripts/enforce_metadata_defaults.sh +++ /dev/null @@ -1,218 +0,0 @@ -#!/usr/bin/env bash -# PreToolUse hook for mem0 MCP tools. -# Injects identity (user_id, app_id) and metadata defaults when the agent -# omits them. Uses the hookSpecificOutput.updatedInput contract to modify -# tool call parameters before execution. -# -# Handles: -# add_memory — top-level user_id, app_id, metadata defaults -# search_memories — user_id/app_id into filters.AND[] -# get_memories — user_id/app_id into filters.AND[] -# delete_all_memories — top-level user_id, app_id -# -# Hook contract: -# exit 0 = allow. If stdout contains {"hookSpecificOutput": {"updatedInput": ...}}, -# the updatedInput replaces the tool's input parameters. -# exit 2 = block (stderr shown as rejection reason). - -set -uo pipefail - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -source "$SCRIPT_DIR/_identity.sh" 2>/dev/null || true - -INPUT=$(cat) - -TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name // ""' 2>/dev/null) - -# Determine which handler to use based on tool name -HANDLER="" -case "$TOOL_NAME" in - mcp__mem0__add_memory|mcp__plugin_mem0_mem0__add_memory) - HANDLER="add_memory" ;; - mcp__mem0__search_memories|mcp__plugin_mem0_mem0__search_memories) - HANDLER="search_memories" ;; - mcp__mem0__get_memories|mcp__plugin_mem0_mem0__get_memories) - HANDLER="get_memories" ;; - mcp__mem0__delete_all_memories|mcp__plugin_mem0_mem0__delete_all_memories) - HANDLER="delete_all" ;; - *) exit 0 ;; -esac - -TOOL_INPUT=$(echo "$INPUT" | jq -r '.tool_input // "{}"' 2>/dev/null) - -_PATCH_OUT="/tmp/mem0_enforce_$$" -trap 'rm -f "$_PATCH_OUT"' EXIT -_MEM0_TOOL_INPUT="$TOOL_INPUT" \ -_MEM0_USER_ID="${MEM0_RESOLVED_USER_ID:-}" \ -_MEM0_APP_ID="${MEM0_PROJECT_ID:-}" \ -_MEM0_GLOBAL_SEARCH="${MEM0_GLOBAL_SEARCH:-false}" \ -_MEM0_HANDLER="$HANDLER" \ -python3 <<'PYEOF' > "$_PATCH_OUT" 2>/dev/null || true -import json, os, sys - -raw = os.environ.get("_MEM0_TOOL_INPUT", "{}") -try: - inp = json.loads(raw) -except Exception: - sys.exit(0) - -handler = os.environ.get("_MEM0_HANDLER", "") -resolved_uid = os.environ.get("_MEM0_USER_ID", "") -resolved_aid = os.environ.get("_MEM0_APP_ID", "") -global_search = os.environ.get("_MEM0_GLOBAL_SEARCH", "false") == "true" -changed = False - - -def inject_top_level_identity(inp, uid, aid): - """Inject user_id/app_id as top-level params (for add_memory, delete_all).""" - changed = False - if uid and not inp.get("user_id"): - inp["user_id"] = uid - changed = True - if aid and not inp.get("app_id"): - inp["app_id"] = aid - changed = True - return changed - - -def inject_filter_identity(inp, uid, aid): - """Inject user_id/app_id into filters.AND[] (for search/get_memories).""" - changed = False - if not uid and not aid: - return False - - filters = inp.get("filters") - - if filters is None: - # No filters at all — create from scratch - and_clauses = [] - if uid: - and_clauses.append({"user_id": uid}) - if aid: - and_clauses.append({"app_id": aid}) - inp["filters"] = {"AND": and_clauses} - return True - - if not isinstance(filters, dict): - return False - - # Check if filters already contain user_id/app_id - and_clauses = filters.get("AND") - if and_clauses is None: - # Filters exist but no AND — could be flat like {"user_id": "x"} - has_uid = "user_id" in filters - has_aid = "app_id" in filters - if has_uid and has_aid: - return False - # Convert flat filters to AND format and add missing identity - existing = [] - for k, v in list(filters.items()): - existing.append({k: v}) - if uid and not has_uid: - existing.append({"user_id": uid}) - changed = True - if aid and not has_aid: - existing.append({"app_id": aid}) - changed = True - if changed: - inp["filters"] = {"AND": existing} - return changed - - if not isinstance(and_clauses, list): - return False - - # AND array exists — check for existing user_id/app_id - has_uid = any("user_id" in c for c in and_clauses if isinstance(c, dict)) - has_aid = any("app_id" in c for c in and_clauses if isinstance(c, dict)) - - if uid and not has_uid: - and_clauses.append({"user_id": uid}) - changed = True - if aid and not has_aid: - and_clauses.append({"app_id": aid}) - changed = True - - return changed - - -if handler == "add_memory": - changed = inject_top_level_identity(inp, resolved_uid, resolved_aid) - - meta = inp.get("metadata") or {} - - if "confidence" not in meta: - meta["confidence"] = 0.7 - changed = True - if "files" not in meta: - meta["files"] = ["*"] - changed = True - if "source" not in meta: - meta["source"] = "auto_capture" - changed = True - if "type" not in meta: - meta["type"] = "task_learning" - changed = True - - if meta.get("confidence", 0) >= 1.0 and "infer" not in inp: - inp["infer"] = False - changed = True - - # Track session in metadata instead of run_id. - # run_id creates a separate entity partition in the v3 API, - # making memories invisible to search/get_memories calls - # that don't include a run_id filter. - if "session_id" not in meta: - sid = os.environ.get("MEM0_SESSION_ID", "") - if not sid: - session_file = "/tmp/mem0_session_id_" + os.environ.get("USER", "default") - if os.path.isfile(session_file): - try: - with open(session_file) as f: - sid = f.read().strip() - except OSError: - pass - if sid: - meta["session_id"] = sid - changed = True - - if changed: - inp["metadata"] = meta - -elif handler in ("search_memories", "get_memories"): - if global_search: - inp["filters"] = {"OR": [{"user_id": "*"}]} - changed = True - else: - changed = inject_filter_identity(inp, resolved_uid, resolved_aid) - -elif handler == "delete_all": - changed = inject_top_level_identity(inp, resolved_uid, resolved_aid) - -if changed: - print(json.dumps(inp)) -PYEOF -PATCHED=$(cat "$_PATCH_OUT" 2>/dev/null) -rm -f "$_PATCH_OUT" - -if [ -n "$PATCHED" ] && echo "$PATCHED" | jq empty 2>/dev/null; then - jq -n --argjson updated "$PATCHED" '{ - "hookSpecificOutput": { - "hookEventName": "PreToolUse", - "permissionDecision": "allow", - "updatedInput": $updated - } - }' 2>/dev/null || true -fi - -# Track session stats here because PostToolUse hooks don't fire for plugin MCP tools. -case "$HANDLER" in - add_memory) - _CAT=$(echo "$TOOL_INPUT" | jq -r '.metadata.type // .metadata.category // ""' 2>/dev/null || echo "") - python3 "$SCRIPT_DIR/session_stats.py" add "$_CAT" 2>/dev/null & - ;; - search_memories|get_memories) - python3 "$SCRIPT_DIR/session_stats.py" search 2>/dev/null & - ;; -esac - -exit 0 diff --git a/integrations/mem0-plugin/scripts/ensure_deps.sh b/integrations/mem0-plugin/scripts/ensure_deps.sh deleted file mode 100755 index 8bb54a483..000000000 --- a/integrations/mem0-plugin/scripts/ensure_deps.sh +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env bash -# Install mem0ai SDK into a persistent venv inside CLAUDE_PLUGIN_DATA. -# Runs on SessionStart; skips if requirements.txt hasn't changed. -set -euo pipefail - -PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "$(dirname "$0")/.." && pwd)}" -DATA_DIR="${CLAUDE_PLUGIN_DATA:-${HOME}/.mem0/plugin-data}" -VENV_DIR="${DATA_DIR}/venv" -REQ_SRC="${PLUGIN_ROOT}/requirements.txt" -REQ_STAMP="${DATA_DIR}/requirements.txt" - -mkdir -p "${DATA_DIR}" - -LOCKDIR="${DATA_DIR}/.install-lock" - -needs_install=false - -if [ ! -f "${VENV_DIR}/bin/python3" ]; then - needs_install=true -elif ! diff -q "${REQ_SRC}" "${REQ_STAMP}" >/dev/null 2>&1; then - needs_install=true -fi - -if [ "${needs_install}" = "true" ]; then - if mkdir "${LOCKDIR}" 2>/dev/null; then - # We acquired the lock — proceed with installation - trap 'rmdir "${LOCKDIR}" 2>/dev/null || true' EXIT - python3 -m venv "${VENV_DIR}" 2>/dev/null || python -m venv "${VENV_DIR}" - "${VENV_DIR}/bin/pip" install --quiet --upgrade pip >/dev/null 2>&1 || true - if "${VENV_DIR}/bin/pip" install --quiet -r "${REQ_SRC}" 2>/dev/null; then - cp "${REQ_SRC}" "${REQ_STAMP}" - rm -f "${DATA_DIR}/.install-failed" - else - rm -f "${REQ_STAMP}" - touch "${DATA_DIR}/.install-failed" - echo "mem0 plugin: failed to install Python dependencies" >&2 - exit 0 - fi - else - # Another process holds the lock — wait up to 60s for it to finish - for i in $(seq 1 60); do - [ ! -d "${LOCKDIR}" ] && break - sleep 1 - done - # Check if the other process's install failed - if [ -f "${DATA_DIR}/.install-failed" ]; then - echo "mem0 plugin: dependency installation failed (by another session)" >&2 - fi - fi -fi diff --git a/integrations/mem0-plugin/scripts/file_context.py b/integrations/mem0-plugin/scripts/file_context.py deleted file mode 100644 index a1ebf2735..000000000 --- a/integrations/mem0-plugin/scripts/file_context.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/env python3 -"""File-context injection for PreToolUse/Read hook. - -When Claude is about to read a file, this script searches mem0 for -memories that reference that file path and returns a compact timeline -of prior work. This gives Claude context like "last time you fixed a -null pointer here" before it reads the file. - -Modeled after claude-mem's file-context handler but adapted for mem0's -cloud API architecture. - -Input: file_path (positional arg), env vars for identity -Output: JSON to stdout with hookSpecificOutput.additionalContext -""" - -from __future__ import annotations - -import os -import sys -from pathlib import Path - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from _formatting import TYPE_ICONS, format_age -from _identity import resolve_api_key, resolve_user_id -from _project import resolve_project_id -from _search import search_memories, should_rerank - -FILE_READ_GATE_MIN_BYTES = 1500 -MAX_RESULTS = 5 -SEARCH_TIMEOUT = 5 - - -def gate_file(file_path: str, cwd: str) -> str | None: - """Return the resolved absolute path if the file passes gating, else None.""" - if not file_path: - return None - p = Path(file_path) - if not p.is_absolute(): - p = Path(cwd) / p - try: - p = p.resolve() - if not p.is_file(): - return None - if p.stat().st_size < FILE_READ_GATE_MIN_BYTES: - return None - return str(p) - except OSError: - return None - - -def relative_path(abs_path: str, cwd: str) -> str: - try: - return os.path.relpath(abs_path, cwd) - except ValueError: - return abs_path - - -def format_timeline(memories: list[dict], file_path: str) -> str: - """Format memories into a compact timeline for context injection.""" - if not memories: - return "" - - rel = file_path - lines = [ - f"Prior work on `{rel}` — {len(memories)} memories found.", - "Need details? Use `search_memories` with the memory ID.", - "", - ] - - for m in memories: - mid = m.get("id", "?")[:8] - text = (m.get("memory", "") or "")[:150].replace("\n", " ").strip() - meta = m.get("metadata") or {} - cat = meta.get("type", "unknown") - icon = TYPE_ICONS.get(cat, "❓") - age = format_age(m) - age_str = f" ({age})" if age else "" - lines.append(f"- {icon} [{cat}]{age_str} {text} [mem0:{mid}]") - - return "\n".join(lines) - - -def search_file_context( - api_key: str, user_id: str, project_id: str, file_path: str, cwd: str -) -> str: - """Search mem0 for memories related to a file path.""" - global_search = os.environ.get("MEM0_GLOBAL_SEARCH", "false") == "true" - rel = relative_path(file_path, cwd) - basename = os.path.basename(file_path) - - query = f"{rel} {basename}" if rel != basename else rel - results = search_memories( - api_key, user_id, project_id, query, - top_k=MAX_RESULTS, threshold=0.3, - global_search=global_search, - rerank=should_rerank(), - ) - - results = results[:MAX_RESULTS] - - return format_timeline(results, rel) - - -def main(): - if len(sys.argv) < 2: - sys.exit(0) - - file_path = sys.argv[1] - cwd = sys.argv[2] if len(sys.argv) > 2 else os.getcwd() - - api_key = resolve_api_key() - if not api_key: - sys.exit(0) - - resolved = gate_file(file_path, cwd) - if not resolved: - sys.exit(0) - - user_id = resolve_user_id() - project_id = resolve_project_id(cwd) - - timeline = search_file_context(api_key, user_id, project_id, resolved, cwd) - if not timeline: - sys.exit(0) - - print(timeline, end="") - - -if __name__ == "__main__": - try: - main() - except Exception: - pass - sys.exit(0) diff --git a/integrations/mem0-plugin/scripts/import_competing_tools.py b/integrations/mem0-plugin/scripts/import_competing_tools.py deleted file mode 100644 index 968bbbcd2..000000000 --- a/integrations/mem0-plugin/scripts/import_competing_tools.py +++ /dev/null @@ -1,299 +0,0 @@ -#!/usr/bin/env python3 -"""Import memories from competing AI tool configuration files into mem0. - -Sub-commands (via sys.argv[1]): - cursorrules [--path .cursorrules] - copilot [--path .github/copilot-instructions.md] - cline [--path memory-bank/] - continue [--path .continue/rules.md] - -Each sub-command reads configuration files from competing tools, -splits them into chunks, and POSTs each chunk to the mem0 API as a -project_profile memory. - -Output: progress messages to stdout, errors to stderr -Exit: 0 always -""" - -from __future__ import annotations - -import hashlib -import json -import os -import sys -import urllib.error -import urllib.request - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from _chunking import ( - filter_and_truncate, - split_by_headers, - split_by_hr_or_headers, -) -from _identity import resolve_api_key, resolve_user_id -from _project import resolve_branch, resolve_project_id - -API_URL = "https://api.mem0.ai" -HASH_STORE = os.path.expanduser("~/.mem0/import_hashes.json") - - -def _load_hashes() -> dict[str, str]: - if not os.path.isfile(HASH_STORE): - return {} - try: - with open(HASH_STORE) as f: - return json.load(f) - except (OSError, json.JSONDecodeError): - return {} - - -def _save_hashes(hashes: dict[str, str]) -> None: - os.makedirs(os.path.dirname(HASH_STORE), exist_ok=True) - try: - with open(HASH_STORE, "w") as f: - json.dump(hashes, f, indent=2) - except OSError: - pass - - -def _content_hash(content: str) -> str: - return hashlib.sha256(content.encode("utf-8")).hexdigest() - - -# --------------------------------------------------------------------------- -# API helpers -# --------------------------------------------------------------------------- - - -def post_memory(api_key: str, content: str, user_id: str, project_id: str, branch: str, source: str) -> bool: - """POST a single memory chunk to the mem0 API.""" - metadata: dict = { - "type": "project_profile", - "source": source, - } - if branch: - metadata["branch"] = branch - - body = { - "messages": [{"role": "user", "content": content}], - "user_id": user_id, - "app_id": project_id, - "metadata": metadata, - "infer": False, - } - data = json.dumps(body).encode("utf-8") - req = urllib.request.Request( - f"{API_URL}/v3/memories/add/", - data=data, - headers={ - "Content-Type": "application/json", - "Authorization": f"Token {api_key}", - }, - method="POST", - ) - try: - with urllib.request.urlopen(req, timeout=20) as resp: - return resp.status in (200, 201) - except urllib.error.URLError as e: - print(f" [warn] API call failed: {e}", file=sys.stderr) - return False - - -def import_chunks(chunks: list[str], api_key: str, user_id: str, project_id: str, branch: str, source: str, hash_key: str = "") -> int: - """Import a list of content chunks; return number of successful imports. - - Skips import if content hash matches a previous run for the same hash_key.""" - if hash_key: - combined = "\n".join(chunks) - current_hash = _content_hash(combined) - hashes = _load_hashes() - if hashes.get(hash_key) == current_hash: - print(f"Already imported (unchanged) -- skipping: {hash_key}") - return 0 - else: - current_hash = "" - hashes = {} - - success = 0 - for chunk in chunks: - if post_memory(api_key, chunk, user_id, project_id, branch, source): - success += 1 - - if success > 0 and hash_key and current_hash: - hashes[hash_key] = current_hash - _save_hashes(hashes) - - return success - - -# --------------------------------------------------------------------------- -# Sub-command implementations -# --------------------------------------------------------------------------- - - -def _parse_path_arg(args: list[str], flag: str, default: str) -> str: - """Extract --path from args list, falling back to default.""" - for i, arg in enumerate(args): - if arg == flag and i + 1 < len(args): - return args[i + 1] - if arg.startswith(f"{flag}="): - return arg[len(flag) + 1:] - return default - - -def cmd_cursorrules(args: list[str]) -> None: - path = _parse_path_arg(args, "--path", ".cursorrules") - source = "cursor-import" - - api_key = resolve_api_key() - user_id = resolve_user_id() - project_id = resolve_project_id() - branch = resolve_branch() - - if not api_key: - print("Error: MEM0_API_KEY not set", file=sys.stderr) - return - - if not os.path.isfile(path): - print(f"File not found: {path}", file=sys.stderr) - return - - with open(path, encoding="utf-8", errors="replace") as f: - content = f.read() - - raw_chunks = split_by_headers(content, "## ") - # Fall back to treating the whole file as one chunk if no headers found - if not raw_chunks: - raw_chunks = [content.strip()] if content.strip() else [] - - chunks = filter_and_truncate(raw_chunks) - n = import_chunks(chunks, api_key, user_id, project_id, branch, source, hash_key=f"{project_id}:{source}:{path}") - print(f"Imported {n} memories from {source} ({path})") - - -def cmd_copilot(args: list[str]) -> None: - path = _parse_path_arg(args, "--path", ".github/copilot-instructions.md") - source = "copilot-import" - - api_key = resolve_api_key() - user_id = resolve_user_id() - project_id = resolve_project_id() - branch = resolve_branch() - - if not api_key: - print("Error: MEM0_API_KEY not set", file=sys.stderr) - return - - if not os.path.isfile(path): - print(f"File not found: {path}", file=sys.stderr) - return - - with open(path, encoding="utf-8", errors="replace") as f: - content = f.read() - - raw_chunks = split_by_headers(content, "## ") - if not raw_chunks: - raw_chunks = [content.strip()] if content.strip() else [] - - chunks = filter_and_truncate(raw_chunks) - n = import_chunks(chunks, api_key, user_id, project_id, branch, source, hash_key=f"{project_id}:{source}:{path}") - print(f"Imported {n} memories from {source} ({path})") - - -def cmd_cline(args: list[str]) -> None: - dir_path = _parse_path_arg(args, "--path", "memory-bank/") - source = "cline-import" - - api_key = resolve_api_key() - user_id = resolve_user_id() - project_id = resolve_project_id() - branch = resolve_branch() - - if not api_key: - print("Error: MEM0_API_KEY not set", file=sys.stderr) - return - - if not os.path.isdir(dir_path): - print(f"Directory not found: {dir_path}", file=sys.stderr) - return - - md_files = sorted( - f for f in os.listdir(dir_path) if f.endswith(".md") - ) - if not md_files: - print(f"No .md files found in {dir_path}", file=sys.stderr) - return - - total = 0 - for filename in md_files: - filepath = os.path.join(dir_path, filename) - with open(filepath, encoding="utf-8", errors="replace") as f: - content = f.read().strip() - if not content: - continue - chunks = filter_and_truncate([content]) - n = import_chunks(chunks, api_key, user_id, project_id, branch, source, hash_key=f"{project_id}:{source}:{filepath}") - total += n - - print(f"Imported {total} memories from {source} ({dir_path})") - - -def cmd_continue(args: list[str]) -> None: - path = _parse_path_arg(args, "--path", ".continue/rules.md") - source = "continue-import" - - api_key = resolve_api_key() - user_id = resolve_user_id() - project_id = resolve_project_id() - branch = resolve_branch() - - if not api_key: - print("Error: MEM0_API_KEY not set", file=sys.stderr) - return - - if not os.path.isfile(path): - print(f"File not found: {path}", file=sys.stderr) - return - - with open(path, encoding="utf-8", errors="replace") as f: - content = f.read() - - raw_chunks = split_by_hr_or_headers(content) - if not raw_chunks: - raw_chunks = [content.strip()] if content.strip() else [] - - chunks = filter_and_truncate(raw_chunks) - n = import_chunks(chunks, api_key, user_id, project_id, branch, source, hash_key=f"{project_id}:{source}:{path}") - print(f"Imported {n} memories from {source} ({path})") - - -# --------------------------------------------------------------------------- -# Entry point -# --------------------------------------------------------------------------- - -COMMANDS = { - "cursorrules": cmd_cursorrules, - "copilot": cmd_copilot, - "cline": cmd_cline, - "continue": cmd_continue, -} - - -def main() -> None: - if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS: - available = ", ".join(COMMANDS.keys()) - print("Usage: import_competing_tools.py [--path ]", file=sys.stderr) - print(f"Subcommands: {available}", file=sys.stderr) - sys.exit(0) - - subcommand = sys.argv[1] - remaining_args = sys.argv[2:] - COMMANDS[subcommand](remaining_args) - - -if __name__ == "__main__": - try: - main() - except Exception as e: - print(f"Unexpected error: {e}", file=sys.stderr) - sys.exit(0) diff --git a/integrations/mem0-plugin/scripts/install_codex_hooks.py b/integrations/mem0-plugin/scripts/install_codex_hooks.py deleted file mode 100755 index c94ef1561..000000000 --- a/integrations/mem0-plugin/scripts/install_codex_hooks.py +++ /dev/null @@ -1,162 +0,0 @@ -#!/usr/bin/env python3 -"""Install Mem0 lifecycle hooks into ~/.codex/hooks.json. - -Codex discovers hooks only at ~/.codex/hooks.json or /.codex/hooks.json, -and has no plugin-host mechanism for auto-wiring hooks from an installed -plugin. This installer reads the template at hooks/codex-hooks.json, rewrites -the ${PLUGIN_ROOT} placeholder to the absolute install path of this -plugin, then merges the entries into ~/.codex/hooks.json. - -Re-running is idempotent: existing Mem0 entries (identified by the plugin -directory name in the command string) are removed before fresh entries are -added, so upgrades don't leave duplicates. - -Usage: - python3 install_codex_hooks.py # install or update - python3 install_codex_hooks.py --uninstall # remove Mem0 entries - -After installing, Codex requires the hooks feature flag in ~/.codex/config.toml: - - [features] - codex_hooks = true -""" - -from __future__ import annotations - -import argparse -import json -import platform -import sys -from pathlib import Path - -SCRIPT_DIR = Path(__file__).resolve().parent -PLUGIN_ROOT = SCRIPT_DIR.parent - -CODEX_DIR = Path.home() / ".codex" -HOOKS_FILE = CODEX_DIR / "hooks.json" -CONFIG_FILE = CODEX_DIR / "config.toml" - -TEMPLATE_FILE = PLUGIN_ROOT / "hooks" / "codex-hooks.json" - -# Substring we look for when identifying entries this installer owns. -# Matches the plugin directory name, which stays stable across install paths. -OWNER_MARKER = "mem0-plugin" - - -def load_template() -> dict: - raw = TEMPLATE_FILE.read_text() - raw = raw.replace("${PLUGIN_ROOT}", str(PLUGIN_ROOT)) - return json.loads(raw) - - -def load_existing() -> dict: - if not HOOKS_FILE.exists(): - return {"hooks": {}} - try: - return json.loads(HOOKS_FILE.read_text()) - except (json.JSONDecodeError, OSError) as e: - print(f"error: failed to read {HOOKS_FILE}: {e}", file=sys.stderr) - sys.exit(1) - - -def is_owned_entry(entry: dict) -> bool: - for hook in entry.get("hooks", []): - if OWNER_MARKER in hook.get("command", ""): - return True - return False - - -def strip_owned_entries(config: dict) -> dict: - hooks = config.get("hooks", {}) or {} - for event in list(hooks.keys()): - hooks[event] = [e for e in hooks[event] if not is_owned_entry(e)] - if not hooks[event]: - del hooks[event] - config["hooks"] = hooks - return config - - -def merge_template(config: dict, template: dict) -> dict: - hooks = config.setdefault("hooks", {}) - for event, entries in template.get("hooks", {}).items(): - hooks.setdefault(event, []).extend(entries) - return config - - -def write_config(config: dict) -> None: - CODEX_DIR.mkdir(parents=True, exist_ok=True) - HOOKS_FILE.write_text(json.dumps(config, indent=2) + "\n") - - -def feature_flag_enabled() -> bool: - if not CONFIG_FILE.exists(): - return False - content = CONFIG_FILE.read_text() - for line in content.splitlines(): - stripped = line.split("#", 1)[0].strip().replace(" ", "") - if stripped == "codex_hooks=true": - return True - return False - - -def print_feature_flag_hint() -> None: - print() - print("Codex hooks feature flag is not enabled.") - print(f"Add this to {CONFIG_FILE}:") - print() - print(" [features]") - print(" codex_hooks = true") - print() - print("Then restart Codex.") - - -def main() -> int: - parser = argparse.ArgumentParser(description="Install or remove Mem0 Codex hooks.") - parser.add_argument( - "--uninstall", - action="store_true", - help="Remove Mem0 entries from ~/.codex/hooks.json and exit.", - ) - args = parser.parse_args() - - config = load_existing() - - if args.uninstall: - config = strip_owned_entries(config) - write_config(config) - print(f"Removed Mem0 hooks from {HOOKS_FILE}") - return 0 - - # Codex lifecycle hooks register .sh paths directly in ~/.codex/hooks.json. - # On native Windows .sh has no default handler, so Codex spawning a hook - # triggers "Open With" dialogs (one OpenWith.exe per event). See #5243. - if platform.system() == "Windows": - print( - "Codex lifecycle hooks register .sh scripts directly, which Windows\n" - "cannot execute without a bash interpreter on PATH. Re-run this\n" - "installer from WSL or Git Bash, or use Mem0 via MCP / Direct tools\n", - file=sys.stderr, - ) - return 2 - - if not TEMPLATE_FILE.exists(): - print(f"error: template not found at {TEMPLATE_FILE}", file=sys.stderr) - return 1 - - template = load_template() - config = strip_owned_entries(config) - config = merge_template(config, template) - write_config(config) - - print(f"Installed Mem0 hooks into {HOOKS_FILE}") - print(f"Plugin path: {PLUGIN_ROOT}") - print("Events: PreToolUse, SessionStart, UserPromptSubmit, PostToolUse, Stop, PreCompact") - - if not feature_flag_enabled(): - print_feature_flag_hint() - - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/integrations/mem0-plugin/scripts/kimi_hook_shim.sh b/integrations/mem0-plugin/scripts/kimi_hook_shim.sh deleted file mode 100755 index 24e622706..000000000 --- a/integrations/mem0-plugin/scripts/kimi_hook_shim.sh +++ /dev/null @@ -1,120 +0,0 @@ -#!/usr/bin/env bash -# Kimi Code hook adapter. -# -# Kimi Code's hook contract is close to Claude Code's but differs in four ways -# that the mem0 hook scripts care about. Rather than fork nine scripts, every -# Kimi hook entry in .kimi-plugin/plugin.json routes through this shim. -# -# 1. cwd Kimi runs hook commands with cwd forced to the PLUGIN root -# (agent-core-v2 src/app/plugin/manager.ts -> enabledHooks() sets -# `cwd: record.root`). The real project directory only arrives as -# the payload's `cwd` field. _project.sh resolves MEM0_PROJECT_ID -# from $PWD/`git remote`, so we chdir into the payload cwd first. -# -# 2. stdin Kimi sends snake_case JSON like Claude, but: -# - `prompt` is a ContentPart[] array, not a string -# - PostToolUse sends `tool_output`, not `tool_response` -# - file tools use `tool_input.path`, not `tool_input.file_path` -# - plugin MCP tools are `mcp__plugin-mem0_mem0__*` (hyphen), -# not Claude's `mcp__plugin_mem0_mem0__*` -# - there is NO `transcript_path` (no equivalent exists) -# We normalise the first four into the Claude shape. -# -# 3. stdout Kimi's hook stdout parser (agent-core-v2 -# src/agent/externalHooks/runner.ts -> HookJsonOutputSchema) only -# understands top-level `message`, `hookSpecificOutput.message`, -# `hookSpecificOutput.permissionDecision` and -# `hookSpecificOutput.permissionDecisionReason`. -# `additionalContext` and `updatedInput` are NOT recognised. -# Raw (non-JSON) stdout IS appended to context for UserPromptSubmit -# (user-prompt.ts -> userPromptHookMessage falls back to stdout), so -# we unwrap additionalContext into plain text. -# -# 4. exit Same as Claude: 0 = allow, 2 = block (stderr is the reason), -# any other code / timeout = fail-open. -# -# Usage: kimi_hook_shim.sh [args...] - -set -uo pipefail - -SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)" - -[ $# -ge 1 ] || exit 0 -TARGET_NAME="$1" -shift -TARGET="$SCRIPT_DIR/$TARGET_NAME" -[ -f "$TARGET" ] || exit 0 - -# Telemetry attribution (telemetry.py::detect_platform honours MEM0_PLATFORM). -export MEM0_PLATFORM="${MEM0_PLATFORM:-kimi}" - -RAW=$(cat) - -_TMP_BASE="${TMPDIR:-/tmp}" -IN_FILE="$_TMP_BASE/mem0_kimi_in_$$" -OUT_FILE="$_TMP_BASE/mem0_kimi_out_$$" -trap 'rm -f "$IN_FILE" "$OUT_FILE"' EXIT - -HAVE_JQ="" -command -v jq >/dev/null 2>&1 && HAVE_JQ="true" - -# ---------------------------------------------------------------- stdin shape -NORM="" -if [ -n "$HAVE_JQ" ]; then - NORM=$(printf '%s' "$RAW" | jq -c ' - def flat_prompt: - if type == "array" then - [ .[]? | if type == "object" then (.text // "") elif type == "string" then . else "" end ] - | map(select(. != "")) | join("\n") - elif type == "string" then . - else "" end; - . as $in - | (if has("prompt") then .prompt = ($in.prompt | flat_prompt) else . end) - | (if (has("tool_response") | not) and (.tool_output != null) - then .tool_response = .tool_output else . end) - | (if ((.tool_input | type) == "object") and (.tool_input.file_path == null) and (.tool_input.path != null) - then .tool_input.file_path = .tool_input.path else . end) - | (if ((.tool_name | type) == "string") and (.tool_name | startswith("mcp__")) and (.tool_name | test("mem0")) - then .tool_name = (.tool_name | gsub("-"; "_")) else . end) - ' 2>/dev/null) -fi -[ -n "$NORM" ] || NORM="$RAW" - -printf '%s' "$NORM" >"$IN_FILE" 2>/dev/null || exit 0 - -# ------------------------------------------------------------------- real cwd -if [ -n "$HAVE_JQ" ]; then - PROJECT_CWD=$(printf '%s' "$NORM" | jq -r '.cwd // ""' 2>/dev/null || printf '') - if [ -n "$PROJECT_CWD" ] && [ -d "$PROJECT_CWD" ]; then - cd "$PROJECT_CWD" 2>/dev/null || true - fi -fi - -# ------------------------------------------------------------------- dispatch -# Redirect (not pipe) stdout so backgrounded children inside the hook scripts -# cannot hold the shim open until Kimi's timeout fires. -bash "$TARGET" "$@" <"$IN_FILE" >"$OUT_FILE" -CODE=$? - -OUT=$(cat "$OUT_FILE" 2>/dev/null || printf '') - -# --------------------------------------------------------------- stdout shape -if [ -n "$OUT" ] && [ -n "$HAVE_JQ" ] && printf '%s' "$OUT" | jq -e 'type == "object"' >/dev/null 2>&1; then - if printf '%s' "$OUT" | jq -e '.hookSpecificOutput.permissionDecision == "deny"' >/dev/null 2>&1; then - # Kimi understands deny natively — pass the envelope straight through. - printf '%s' "$OUT" - else - CTX=$(printf '%s' "$OUT" | jq -r ' - (.hookSpecificOutput.additionalContext - // .additionalContext - // .message - // .hookSpecificOutput.message - // "") - | gsub("\\\\n"; "\n")' 2>/dev/null || printf '') - [ -n "$CTX" ] && printf '%s\n' "$CTX" - fi -elif [ -n "$OUT" ]; then - printf '%s' "$OUT" -fi - -exit $CODE diff --git a/integrations/mem0-plugin/scripts/load_settings.py b/integrations/mem0-plugin/scripts/load_settings.py deleted file mode 100644 index 139d180c6..000000000 --- a/integrations/mem0-plugin/scripts/load_settings.py +++ /dev/null @@ -1,71 +0,0 @@ -"""Load plugin settings from ~/.mem0/settings.json. - -Settings file is user-editable. Missing file or keys fall back to defaults. -""" - -from __future__ import annotations - -import json -from pathlib import Path - -SETTINGS_PATH = Path.home() / ".mem0" / "settings.json" - -DEFAULTS = { - "auto_save": True, - "auto_search": True, - "search_limit": 10, - "retention_session_days": 90, - "confidence_threshold": 0.3, - "global_search": False, - "debug": False, -} - - -def load_settings() -> dict: - settings = dict(DEFAULTS) - if SETTINGS_PATH.exists(): - try: - with open(SETTINGS_PATH) as f: - user = json.load(f) - except (json.JSONDecodeError, OSError): - return settings - if isinstance(user, dict): - settings.update({k: v for k, v in user.items() if k in DEFAULTS}) - return settings - - -def create_default_settings() -> bool: - """Write the default settings file if absent. Returns True if it was created.""" - SETTINGS_PATH.parent.mkdir(parents=True, exist_ok=True) - if SETTINGS_PATH.exists(): - return False - with open(SETTINGS_PATH, "w") as f: - json.dump(DEFAULTS, f, indent=2) - f.write("\n") - return True - - -def unknown_keys() -> list[str]: - """Keys present in the user's settings file that no code reads.""" - if not SETTINGS_PATH.exists(): - return [] - try: - with open(SETTINGS_PATH) as f: - user = json.load(f) - except (json.JSONDecodeError, OSError): - return [] - if not isinstance(user, dict): - return [] - return sorted(k for k in user if k not in DEFAULTS) - - -if __name__ == "__main__": - import sys - if len(sys.argv) > 1 and sys.argv[1] == "init": - if create_default_settings(): - print(f"Created {SETTINGS_PATH}") - ignored = unknown_keys() - if ignored: - print(f"Ignoring unrecognized settings in {SETTINGS_PATH}: {', '.join(ignored)}") - else: - print(json.dumps(load_settings())) diff --git a/integrations/mem0-plugin/scripts/on_bash_output.sh b/integrations/mem0-plugin/scripts/on_bash_output.sh deleted file mode 100755 index dc8621fc9..000000000 --- a/integrations/mem0-plugin/scripts/on_bash_output.sh +++ /dev/null @@ -1,123 +0,0 @@ -#!/usr/bin/env bash -# Hook: PostToolUse (matcher: Bash) -# -# Scans bash command output for stack traces and error patterns. -# When found, injects a search rubric telling the agent to check mem0 -# for prior occurrences of the same error. -# -# This complements on_user_prompt.sh (which catches errors in the user's -# typed message). This hook catches errors in COMMAND OUTPUT — e.g., -# when `npm test` or `python script.py` fails with a traceback. -# -# Input: JSON on stdin with tool_name, tool_input, tool_response -# Output: Context injected into Claude's next response (exit 0) - -set -uo pipefail - -INPUT=$(cat) - -TOOL_RESULT=$(echo "$INPUT" | jq -r '.tool_response // ""' 2>/dev/null || echo "") - -# Skip short output (< 50 chars unlikely to contain a real stack trace) -if [ ${#TOOL_RESULT} -lt 50 ]; then - exit 0 -fi - -# Skip git operations — not useful for error detection -COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // ""' 2>/dev/null || echo "") -case "$COMMAND" in - *"git commit"*|*"git merge"*|*"git rebase"*) - exit 0 - ;; -esac - -# Detect stack traces and error patterns in command output -HAS_ERROR="" -if echo "$TOOL_RESULT" | grep -qE '(Traceback \(most recent call last\)|panic: |FATAL:|error\[E[0-9]+\])'; then - HAS_ERROR="true" -elif [ "$(echo "$TOOL_RESULT" | grep -cE '(Error:|Exception:)')" -ge 2 ]; then - HAS_ERROR="true" -fi - -if [ -z "$HAS_ERROR" ]; then - exit 0 -fi - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -. "$SCRIPT_DIR/_identity.sh" 2>/dev/null || true - -# Extract error class/message (first matching line) -ERROR_LINE=$(echo "$TOOL_RESULT" | grep -iE '(Error:|Exception:|panic:|FAIL:|fatal:)' | head -1 | sed 's/^[[:space:]]*//' | cut -c1-120) - -# Extract file paths from stack trace frames -TRACE_FILES=$(echo "$TOOL_RESULT" | grep -oE '([a-zA-Z0-9_./-]+\.(py|ts|tsx|js|jsx|rs|go|rb|java|sh))(:[0-9]+)?' | head -5 | sort -u) - -# Build file list for display -FILE_DISPLAY="" -if [ -n "$TRACE_FILES" ]; then - FILE_DISPLAY=$(echo "$TRACE_FILES" | sed 's/^/ - /') -fi - -USER_ID="${MEM0_RESOLVED_USER_ID:-${USER:-default}}" - -# Extract query (first 80 chars of error line) -ERROR_QUERY=$(echo "$ERROR_LINE" | cut -c1-80) - -# Telemetry (fire regardless of API key) -python3 "$SCRIPT_DIR/telemetry.py" bash_error --error_detected 2>/dev/null & - -# No API key — skip output entirely -if [ -z "${MEM0_API_KEY:-}" ]; then - exit 0 -fi - -# Pre-fetch memories: anti_pattern and bug_fix searches -RESULTS=$(PYTHONPATH="$SCRIPT_DIR" MEM0_SEARCH_QUERY="$ERROR_QUERY" MEM0_SEARCH_USER="$USER_ID" \ - MEM0_API_KEY="${MEM0_API_KEY}" MEM0_PROJECT_ID="${MEM0_PROJECT_ID:-unknown}" \ - python3 -c " -import os, sys -sys.path.insert(0, os.environ.get('PYTHONPATH', '.')) -from _search import search_memories, format_results_for_context, should_rerank - -api_key = os.environ.get('MEM0_API_KEY', '') -user_id = os.environ.get('MEM0_SEARCH_USER', 'default') -project_id = os.environ.get('MEM0_PROJECT_ID', 'unknown') -query = os.environ.get('MEM0_SEARCH_QUERY', '') -rerank = should_rerank() - -r1 = search_memories(api_key, user_id, project_id, query, metadata_type='anti_pattern', top_k=3, rerank=rerank) -r2 = search_memories(api_key, user_id, project_id, query, metadata_type='bug_fix', top_k=3, rerank=rerank) - -seen = set() -combined = [] -for m in r1 + r2: - mid = m.get('id', '') - if mid not in seen: - seen.add(mid) - combined.append(m) - -print(format_results_for_context(combined, heading='Prior error memories'), end='') -" 2>/dev/null || echo "") - -# Build context string for JSON output -CTX="Error detected in command output\n\n" -CTX="${CTX}\`${COMMAND}\` produced an error:\n> ${ERROR_LINE}\n" - -if [ -n "$FILE_DISPLAY" ]; then - CTX="${CTX}\nFiles in stack trace:\n${FILE_DISPLAY}\n" -fi - -if [ -n "$RESULTS" ]; then - CTX="${CTX}\n${RESULTS}\n" -fi - -CTX="${CTX}\nResolved errors are stored as anti_pattern or bug_fix memories for future reference." - -jq -cn --arg ctx "$CTX" '{ - hookSpecificOutput: { - hookEventName: "PostToolUse", - additionalContext: $ctx - } -}' 2>/dev/null || true - -exit 0 diff --git a/integrations/mem0-plugin/scripts/on_file_read.sh b/integrations/mem0-plugin/scripts/on_file_read.sh deleted file mode 100755 index d190d81d9..000000000 --- a/integrations/mem0-plugin/scripts/on_file_read.sh +++ /dev/null @@ -1,51 +0,0 @@ -#!/usr/bin/env bash -# Hook: PreToolUse (matcher: Read) -# -# Injects prior work context before Claude reads a file. Searches mem0 -# for memories referencing the file path and returns a compact timeline. -# -# Modeled after claude-mem's file-context handler, adapted for mem0 cloud API. -# -# Input: JSON on stdin with tool_name, tool_input (file_path), cwd -# Output: JSON with hookSpecificOutput.additionalContext + permissionDecision -# -# Must never block the Read — silent exit on any failure. - -set -uo pipefail - -INPUT=$(cat) - -# Extract file path from tool_input -FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // ""' 2>/dev/null || echo "") -if [ -z "$FILE_PATH" ]; then - exit 0 -fi - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" - -# Resolve API key (covers Desktop app users who set it in shell profile) -if [ -z "${MEM0_API_KEY:-}" ]; then - . "$SCRIPT_DIR/_identity.sh" 2>/dev/null || true -fi -if [ -z "${MEM0_API_KEY:-}" ]; then - exit 0 -fi -CWD=$(echo "$INPUT" | jq -r '.cwd // "."' 2>/dev/null || echo ".") - -# Call the Python worker — it handles gating (file size, existence) -TIMELINE=$(python3 "$SCRIPT_DIR/file_context.py" "$FILE_PATH" "$CWD" 2>/dev/null || echo "") - -if [ -z "$TIMELINE" ]; then - exit 0 -fi - -# Return context injection with permissionDecision: allow -jq -cn --arg ctx "$TIMELINE" '{ - hookSpecificOutput: { - hookEventName: "PreToolUse", - additionalContext: $ctx, - permissionDecision: "allow" - } -}' 2>/dev/null || true - -exit 0 diff --git a/integrations/mem0-plugin/scripts/on_file_read_cursor.sh b/integrations/mem0-plugin/scripts/on_file_read_cursor.sh deleted file mode 100755 index c0531d4e1..000000000 --- a/integrations/mem0-plugin/scripts/on_file_read_cursor.sh +++ /dev/null @@ -1,41 +0,0 @@ -#!/usr/bin/env bash -# Hook: preToolUse (matcher: Read) — Cursor variant -# -# Same as on_file_read.sh but uses CURSOR_PLUGIN_ROOT for path resolution -# and sources Cursor-specific identity. - -set -uo pipefail - -INPUT=$(cat) - -FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // ""' 2>/dev/null || echo "") -if [ -z "$FILE_PATH" ]; then - exit 0 -fi - -if [ -z "${MEM0_API_KEY:-}" ]; then - SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" - . "$SCRIPT_DIR/_identity.sh" 2>/dev/null || true -fi -if [ -z "${MEM0_API_KEY:-}" ]; then - exit 0 -fi - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -CWD=$(echo "$INPUT" | jq -r '.cwd // "."' 2>/dev/null || echo ".") - -TIMELINE=$(python3 "$SCRIPT_DIR/file_context.py" "$FILE_PATH" "$CWD" 2>/dev/null || echo "") - -if [ -z "$TIMELINE" ]; then - exit 0 -fi - -jq -cn --arg ctx "$TIMELINE" '{ - hookSpecificOutput: { - hookEventName: "PreToolUse", - additionalContext: $ctx, - permissionDecision: "allow" - } -}' 2>/dev/null || true - -exit 0 diff --git a/integrations/mem0-plugin/scripts/on_post_tool_use.sh b/integrations/mem0-plugin/scripts/on_post_tool_use.sh deleted file mode 100755 index 55636cfa5..000000000 --- a/integrations/mem0-plugin/scripts/on_post_tool_use.sh +++ /dev/null @@ -1,36 +0,0 @@ -#!/usr/bin/env bash -# Hook: PostToolUse — track mem0 MCP tool usage for session stats -# -# Fires after any tool call. We only care about mem0 MCP tools: -# mcp__mem0__add_memory → record an add -# mcp__mem0__search_memories → record a search -# -# Input: JSON on stdin with tool_name, tool_input, tool_response -# Output: none (exit 0, non-blocking) - -set -uo pipefail - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" - -INPUT=$(cat) -TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name // ""' 2>/dev/null || echo "") - -case "$TOOL_NAME" in - *__add_memory) - CATEGORY=$(echo "$INPUT" | jq -r '.tool_input.metadata.type // .tool_input.metadata.category // ""' 2>/dev/null || echo "") - python3 "$SCRIPT_DIR/session_stats.py" add "$CATEGORY" 2>/dev/null || true - python3 "$SCRIPT_DIR/telemetry.py" tool_use --tool=add_memory 2>/dev/null & - ;; - *__search_memories|*__get_memories) - python3 "$SCRIPT_DIR/session_stats.py" search 2>/dev/null || true - python3 "$SCRIPT_DIR/telemetry.py" tool_use --tool=search_memories 2>/dev/null & - ;; - *__delete_memory) - python3 "$SCRIPT_DIR/telemetry.py" tool_use --tool=delete_memory 2>/dev/null & - ;; - *__update_memory) - python3 "$SCRIPT_DIR/telemetry.py" tool_use --tool=update_memory 2>/dev/null & - ;; -esac - -exit 0 diff --git a/integrations/mem0-plugin/scripts/on_post_tool_use_cursor.sh b/integrations/mem0-plugin/scripts/on_post_tool_use_cursor.sh deleted file mode 100755 index bcfb39ace..000000000 --- a/integrations/mem0-plugin/scripts/on_post_tool_use_cursor.sh +++ /dev/null @@ -1,18 +0,0 @@ -#!/usr/bin/env bash -# Hook: postToolUse (Cursor) — track mem0 MCP tool usage for session stats -# -# Wraps on_post_tool_use.sh. Cursor expects JSON output but PostToolUse -# has no meaningful return value, so we output {} after tracking. - -set -uo pipefail - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" - -# Pin platform so the shared script's telemetry is attributed to cursor. -export MEM0_PLATFORM=cursor - -# Run the shared tracker (output is ignored) -"$SCRIPT_DIR/on_post_tool_use.sh" 2>/dev/null || true - -echo '{}' -exit 0 diff --git a/integrations/mem0-plugin/scripts/on_pre_compact.py b/integrations/mem0-plugin/scripts/on_pre_compact.py deleted file mode 100755 index 882e26481..000000000 --- a/integrations/mem0-plugin/scripts/on_pre_compact.py +++ /dev/null @@ -1,314 +0,0 @@ -#!/usr/bin/env python3 -"""Capture session state via the Mem0 REST API. - -Safety net for PreCompact and Stop hooks — reads the transcript JSONL, -extracts structured session state, and stores it in Mem0 directly. - -Used by: - - PreCompact hook: Tags with "pre-compaction" (context about to be lost) - - Stop hook: Tags with "session-end" (session ending, Claude can't respond) - -Input: JSON on stdin with transcript_path, session_id, cwd -Output: stderr logs only (exit 0 always — must not block) -""" - -from __future__ import annotations - -import json -import logging -import os -import sys -import urllib.error -import urllib.request -from datetime import date, timedelta - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from _identity import resolve_api_key, resolve_user_id -from _project import resolve_branch, resolve_project_id - -log = logging.getLogger("mem0-capture") -log.setLevel(logging.DEBUG) -_handler = logging.StreamHandler(sys.stderr) -_handler.setFormatter(logging.Formatter("[mem0-capture] %(message)s")) -log.addHandler(_handler) - -if os.environ.get("MEM0_DEBUG"): - _log_dir = os.path.expanduser("~/.mem0") - try: - os.makedirs(_log_dir, exist_ok=True) - _file_handler = logging.FileHandler(os.path.join(_log_dir, "hooks.log")) - _file_handler.setFormatter(logging.Formatter("[mem0-capture] %(asctime)s %(message)s")) - log.addHandler(_file_handler) - except OSError: - pass - -API_URL = "https://api.mem0.ai" -MAX_TAIL_LINES = 500 -MAX_USER_MESSAGES = 30 -MAX_BASH_COMMANDS = 20 -MAX_ASSISTANT_TEXT = 10000 -# session_state captures churn fast (active codebase, files in flight). Past -# ~3 months they're stale noise. Durable facts (decisions, conventions) are -# stored separately by the agent without an expiration_date. -SESSION_STATE_EXPIRY_DAYS = 90 - - -def tail_lines(filepath: str, n: int) -> list[str]: - """Read last n lines of a file efficiently.""" - try: - with open(filepath, "rb") as f: - f.seek(0, 2) - file_size = f.tell() - if file_size == 0: - return [] - chunk_size = min(file_size, n * 4096) - f.seek(max(0, file_size - chunk_size)) - data = f.read().decode("utf-8", errors="replace") - return data.splitlines()[-n:] - except OSError: - return [] - - -def parse_transcript(lines: list[str]) -> dict: - """Parse transcript JSONL lines and extract session state.""" - user_messages: list[str] = [] - files_modified: set[str] = set() - bash_commands: list[str] = [] - last_assistant_text = "" - - for line in lines: - line = line.strip() - if not line: - continue - try: - entry = json.loads(line) - except json.JSONDecodeError: - continue - - entry_type = entry.get("type") - if entry_type not in ("user", "assistant"): - continue - if entry.get("isSidechain"): - continue - - message = entry.get("message", {}) - content_blocks = message.get("content", []) - - if entry_type == "user": - parts = [] - if isinstance(content_blocks, str): - parts.append(content_blocks) - elif isinstance(content_blocks, list): - for block in content_blocks: - if isinstance(block, str): - parts.append(block) - elif isinstance(block, dict) and block.get("type") == "text": - parts.append(block.get("text", "")) - text = "\n".join(parts).strip() - if text and len(text) > 10 and not text.startswith("<"): - user_messages.append(text) - - elif entry_type == "assistant": - for block in content_blocks: - if not isinstance(block, dict): - continue - if block.get("type") == "text": - text = block.get("text", "").strip() - if text: - last_assistant_text = text - if block.get("type") == "tool_use": - tool_name = block.get("name", "") - tool_input = block.get("input", {}) - if tool_name in ("Write", "Edit"): - fp = tool_input.get("file_path", "") - if fp: - files_modified.add(fp) - elif tool_name == "Bash": - cmd = tool_input.get("command", "") - if cmd: - bash_commands.append(cmd) - - return { - "user_messages": user_messages[-MAX_USER_MESSAGES:], - "files_modified": sorted(files_modified), - "bash_commands": bash_commands[-MAX_BASH_COMMANDS:], - "last_assistant_text": last_assistant_text[:MAX_ASSISTANT_TEXT], - } - - -def build_content(state: dict, source: str) -> str: - """Build minimal context — only what's needed to resume work. - - This is a FALLBACK safety net, not the primary capture path. - The agent handles rich memory storage via on_pre_compact.sh prompts. - This script only fires when the agent didn't store enough on its own. - - Keep it short — mem0 infer=True will extract structured facts. - """ - parts = [] - - if state["files_modified"]: - parts.append(f"Files touched: {', '.join(state['files_modified'][:15])}") - - if state["bash_commands"]: - git_cmds = [c for c in state["bash_commands"] if "git " in c] - if git_cmds: - parts.append(f"Git operations: {len(git_cmds)}") - - return "\n".join(parts) - - -def store_memory(api_key: str, content: str, user_id: str, source: str, session_id: str = "", project_id: str = "", branch: str = "") -> bool: - """Store session state as a memory via the Mem0 REST API.""" - expires = (date.today() + timedelta(days=SESSION_STATE_EXPIRY_DAYS)).isoformat() - metadata = { - "type": "session_state", - "source": source, - "session_id": session_id, - } - if branch: - metadata["branch"] = branch - body = { - "messages": [ - {"role": "user", "content": content} - ], - "user_id": user_id, - "app_id": project_id, - "metadata": metadata, - "expiration_date": expires, - "infer": True, - } - - data = json.dumps(body).encode("utf-8") - req = urllib.request.Request( - f"{API_URL}/v3/memories/add/", - data=data, - headers={ - "Content-Type": "application/json", - "Authorization": f"Token {api_key}", - }, - method="POST", - ) - - try: - with urllib.request.urlopen(req, timeout=15) as resp: - if resp.status in (200, 201): - log.info("Session state stored successfully") - return True - log.warning("API returned status %d", resp.status) - return False - except urllib.error.URLError as e: - log.warning("API call failed: %s", e) - return False - - -def format_status(state: dict, source: str, stored: bool, skipped_reason: str = "") -> str: - """Build a clean, readable status line for terminal display.""" - files_count = len(state.get("files_modified", [])) - git_cmds = [c for c in state.get("bash_commands", []) if "git " in c] - user_msgs = len(state.get("user_messages", [])) - - parts = [] - if files_count: - parts.append(f"{files_count} file{'s' if files_count != 1 else ''} touched") - if git_cmds: - parts.append(f"{len(git_cmds)} git op{'s' if len(git_cmds) != 1 else ''}") - if user_msgs: - parts.append(f"{user_msgs} exchange{'s' if user_msgs != 1 else ''}") - - activity = ", ".join(parts) if parts else "minimal activity" - - if source == "pre-compaction": - icon = "✨" # ✨ - label = "Pre-compaction snapshot" - else: - icon = "\U0001f4be" # 💾 - label = "Session-end snapshot" - - if skipped_reason: - return f"{icon} Mem0 {label} — {activity} — {skipped_reason}" - elif stored: - return f"{icon} Mem0 {label} — {activity} — saved to mem0" - else: - return f"{icon} Mem0 {label} — {activity} — nothing to capture" - - -def main(): - source = "pre-compaction" - show_status = False - for arg in sys.argv[1:]: - if arg.startswith("--source="): - source = arg.split("=", 1)[1] - elif arg == "--status": - show_status = True - - api_key = resolve_api_key() - if not api_key: - log.debug("MEM0_API_KEY not set, skipping capture") - if show_status: - print("✨ Mem0 — no API key, skipping capture") - return - - try: - hook_input = json.loads(sys.stdin.read()) - except (json.JSONDecodeError, OSError): - log.debug("No valid JSON on stdin") - return - - transcript_path = hook_input.get("transcript_path", "") - if not transcript_path: - log.debug("No transcript_path provided") - return - - session_id = hook_input.get("session_id", "") - cwd = hook_input.get("cwd") or None - user_id = resolve_user_id() - project_id = resolve_project_id(cwd) - branch = resolve_branch(cwd) - - lines = tail_lines(transcript_path, MAX_TAIL_LINES) - if not lines: - log.debug("Transcript empty or unreadable: %s", transcript_path) - return - - state = parse_transcript(lines) - - # Skip if agent already stored memories this session — avoid duplicate writes. - stats_file = f"/tmp/mem0_session_stats_{os.environ.get('USER', 'default')}.json" - try: - with open(stats_file) as f: - stats = json.load(f) - if stats.get("adds", 0) >= 1: - log.info("Agent stored %d memories this session — skipping fallback", stats["adds"]) - if show_status: - print(format_status(state, source, False, f"agent already stored {stats['adds']} memor{'ies' if stats['adds'] != 1 else 'y'}")) - return - except (OSError, json.JSONDecodeError): - pass - - if not state["files_modified"]: - log.debug("No files modified — skipping fallback capture") - if show_status: - print(format_status(state, source, False)) - return - - content = build_content(state, source) - if not content.strip(): - log.debug("No content to store") - if show_status: - print(format_status(state, source, False)) - return - - log.info("Fallback capture: %d files modified", len(state["files_modified"])) - stored = store_memory(api_key, content, user_id, source, session_id, project_id, branch) - - if show_status: - print(format_status(state, source, stored)) - - -if __name__ == "__main__": - try: - main() - except Exception as e: - log.error("Unexpected error: %s", e) - sys.exit(0) diff --git a/integrations/mem0-plugin/scripts/on_pre_compact.sh b/integrations/mem0-plugin/scripts/on_pre_compact.sh deleted file mode 100755 index fb27acb75..000000000 --- a/integrations/mem0-plugin/scripts/on_pre_compact.sh +++ /dev/null @@ -1,23 +0,0 @@ -#!/usr/bin/env bash -# Hook: PreCompact -# -# Fires BEFORE context compaction. Captures session state via REST API -# in the background. Runs silently — no output to user. - -set -uo pipefail - -if [ -n "${MEM0_DEBUG:-}" ]; then - mkdir -p "$HOME/.mem0" && exec 2>>"$HOME/.mem0/hooks.log" -fi - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -INPUT=$(cat) - -python3 "$SCRIPT_DIR/telemetry.py" pre_compact 2>/dev/null & - -# Capture in background, no stdout -_TMP="/tmp/mem0_precompact_input_$$.json" -printf '%s' "$INPUT" > "$_TMP" 2>/dev/null -(python3 "$SCRIPT_DIR/on_pre_compact.py" --source=pre-compaction < "$_TMP" 2>/dev/null; rm -f "$_TMP") & - -exit 0 diff --git a/integrations/mem0-plugin/scripts/on_pre_compact_cursor.sh b/integrations/mem0-plugin/scripts/on_pre_compact_cursor.sh deleted file mode 100755 index ca5a5a8e2..000000000 --- a/integrations/mem0-plugin/scripts/on_pre_compact_cursor.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash -# Hook: preCompact (Cursor) -# -# Wraps on_pre_compact.sh and converts plain-text output to Cursor's -# expected JSON format: {"user_message":""} - -set -uo pipefail - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" - -# Pin platform so the shared script's telemetry is attributed to cursor. -export MEM0_PLATFORM=cursor - -TEXT=$("$SCRIPT_DIR/on_pre_compact.sh" 2>/dev/null || echo "") - -if [ -z "$TEXT" ]; then - echo '{}' - exit 0 -fi - -jq -cn --arg msg "$TEXT" '{user_message:$msg}' -exit 0 diff --git a/integrations/mem0-plugin/scripts/on_session_start.sh b/integrations/mem0-plugin/scripts/on_session_start.sh deleted file mode 100755 index b2e83926b..000000000 --- a/integrations/mem0-plugin/scripts/on_session_start.sh +++ /dev/null @@ -1,207 +0,0 @@ -#!/usr/bin/env bash -set -uo pipefail - -if [ -n "${MEM0_DEBUG:-}" ]; then - mkdir -p "$HOME/.mem0" && exec 2>>"$HOME/.mem0/hooks.log" -fi - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -. "$SCRIPT_DIR/_identity.sh" 2>/dev/null || true - -INPUT=$(cat) -SOURCE=$(echo "$INPUT" | jq -r '.source // "startup"' 2>/dev/null || echo "startup") - -if [ "$SOURCE" = "startup" ]; then - python3 "$SCRIPT_DIR/session_stats.py" init 2>/dev/null || true - rm -f /tmp/mem0_recent_reads_${USER:-default}_* 2>/dev/null || true -fi -PYTHONPATH="$SCRIPT_DIR" python3 "$SCRIPT_DIR/load_settings.py" init 2>/dev/null || true -rm -f "/tmp/mem0_rubric_injected_${USER:-default}" 2>/dev/null || true -rm -f /tmp/mem0_rubric_* 2>/dev/null || true -rm -f "/tmp/mem0_msg_count_${USER:-default}" 2>/dev/null || true -MEM0_SESSION_ID=$(echo "$INPUT" | jq -r '.session_id // ""' 2>/dev/null || echo "") -if [ -z "$MEM0_SESSION_ID" ]; then - MEM0_SESSION_ID="ses_$(date +%s)_$$" -fi -printf '%s' "$MEM0_SESSION_ID" > "/tmp/mem0_session_id_${USER:-default}" -export MEM0_SESSION_ID - -# Persist identity to Claude's env so Bash tool calls, MCP config, and other hooks see them -if [ -n "${CLAUDE_ENV_FILE:-}" ]; then - echo "export MEM0_SESSION_ID=\"$MEM0_SESSION_ID\"" >> "$CLAUDE_ENV_FILE" - echo "export MEM0_RESOLVED_USER_ID=\"${MEM0_RESOLVED_USER_ID:-${USER:-default}}\"" >> "$CLAUDE_ENV_FILE" - echo "export MEM0_PROJECT_ID=\"${MEM0_PROJECT_ID:-unknown}\"" >> "$CLAUDE_ENV_FILE" - echo "export MEM0_BRANCH=\"${MEM0_BRANCH:-unknown}\"" >> "$CLAUDE_ENV_FILE" - if [ -n "${MEM0_API_KEY:-}" ]; then - echo "export MEM0_API_KEY=\"$MEM0_API_KEY\"" >> "$CLAUDE_ENV_FILE" - fi -fi - -if [ -z "${MEM0_API_KEY:-}" ]; then - _UID="${MEM0_RESOLVED_USER_ID:-${USER:-default}}" - _PID="${MEM0_PROJECT_ID:-unknown}" - _BR="${MEM0_BRANCH:-unknown}" - cat </dev/null 2>&1; then - MEM0_COUNT=$(python3 -c " -import json, os, urllib.request, urllib.error -api_key = os.environ.get('MEM0_API_KEY', '') -user_id = os.environ.get('MEM0_RESOLVED_USER_ID', 'default') -app_id = os.environ.get('MEM0_PROJECT_ID', '') -global_search = os.environ.get('MEM0_GLOBAL_SEARCH', 'false') == 'true' - -def get_count(filters): - body = json.dumps({'filters': filters}).encode() - req = urllib.request.Request( - 'https://api.mem0.ai/v3/memories/?page=1&page_size=1', - headers={'Authorization': f'Token {api_key}', 'Content-Type': 'application/json'}, - data=body, method='POST', - ) - with urllib.request.urlopen(req, timeout=5) as r: - data = json.loads(r.read()) - if isinstance(data, dict) and 'count' in data: - return data['count'] - if isinstance(data, list): - return len(data) - return 0 - -try: - if global_search: - filters = {'OR': [{'user_id': '*'}]} - else: - filters = {'AND': [{'user_id': user_id}, {'app_id': app_id}]} - total = get_count(filters) - print(total) -except Exception: - print('?') -" 2>/dev/null || echo "?") -fi - -_UID="${MEM0_RESOLVED_USER_ID:-${USER:-default}}" -_ANN="${_MEM0_IDENTITY_ANNOTATION:-}" -_PID="${MEM0_PROJECT_ID:-unknown}" -_BR="${MEM0_BRANCH:-unknown}" -_GS="${MEM0_GLOBAL_SEARCH:-false}" - -if [ "$_GS" = "true" ]; then - _SCOPE_LABEL="scope=global" - _SCOPE_INSTR="Global search is ON — searches return all memories across all users and projects. Writes still use user_id: \`${_UID}\`, app_id: \`${_PID}\`." -else - _SCOPE_LABEL="project=${_PID}" - _SCOPE_INSTR="Always include \`user_id\` + \`app_id\` in every \`search_memories\` filter and \`add_memory\` call: -- user_id: \`${_UID}\` -- app_id: \`${_PID}\` (project scope — passed as top-level \`app_id\`, NOT in metadata)" -fi - -cat </dev/null || echo ".") -if command -v python3 >/dev/null 2>&1; then - MEM0_PROJECT_CONFIG=$(python3 "$SCRIPT_DIR/parse_mem0_config.py" --full "$MEM0_CWD_RESOLVED" 2>/dev/null || echo "{}") - if [ -n "$MEM0_PROJECT_CONFIG" ] && [ "$MEM0_PROJECT_CONFIG" != "{}" ]; then - _CONFIG_KEYS=$(echo "$MEM0_PROJECT_CONFIG" | python3 -c "import sys,json; d=json.load(sys.stdin); print(len(d))" 2>/dev/null || echo "?") - echo "mem0.md loaded (${_CONFIG_KEYS} sections configured)." - # Surface the project's memory policy so the model applies it when choosing - # what to store via add_memory (the hook writes also send it as an - # extraction param — see _instructions.py). - _INSTR=$(echo "$MEM0_PROJECT_CONFIG" | python3 -c "import sys,json; print(json.load(sys.stdin).get('instructions',''))" 2>/dev/null || echo "") - if [ -n "$_INSTR" ]; then - echo "" - echo "Project memory policy (from mem0.md): ${_INSTR}" - fi - fi -fi - -if [ "$SOURCE" = "startup" ]; then - if [ "$MEM0_COUNT" = "0" ]; then - echo "New project with 0 memories. Invoke the mem0:onboard skill to import project files. Coding categories install automatically in the background." - else - echo "Search mem0 for recent decisions and task learnings before responding. Run 2 parallel searches: one for decision type, one for task_learning type." - - # Inject compact recent activity timeline (non-blocking, 5s timeout) - # Use perl alarm as portable timeout (macOS lacks GNU timeout) - _TIMELINE=$(MEM0_CWD="$MEM0_CWD_RESOLVED" perl -e 'alarm 5; exec @ARGV' python3 "$SCRIPT_DIR/session_timeline.py" 2>/dev/null || echo "") - if [ -n "$_TIMELINE" ]; then - echo "" - echo "$_TIMELINE" - fi - fi - - _PROJ_KEY=$(printf '%s' "$MEM0_CWD_RESOLVED" | tr '/' '-') - _MEMORY_MD="$HOME/.claude/projects/${_PROJ_KEY}/memory/MEMORY.md" - if [ -f "$_MEMORY_MD" ] && [ -s "$_MEMORY_MD" ]; then - echo "Native MEMORY.md detected at ${_MEMORY_MD}. Add autoMemoryEnabled:false to settings.json or run /mem0:import." - fi - - MEM0_CWD="$MEM0_CWD_RESOLVED" \ - python3 "$SCRIPT_DIR/auto_import.py" 2>/dev/null & - - # Configure the coding-category taxonomy in the background (idempotent, never blocks). - # Prefer the venv python since this path needs the mem0ai SDK. - _VENV_PY="${CLAUDE_PLUGIN_DATA:-$HOME/.mem0/plugin-data}/venv/bin/python3" - if [ -x "$_VENV_PY" ]; then - MEM0_CWD="$MEM0_CWD_RESOLVED" "$_VENV_PY" "$SCRIPT_DIR/auto_setup_categories.py" 2>/dev/null & - else - MEM0_CWD="$MEM0_CWD_RESOLVED" python3 "$SCRIPT_DIR/auto_setup_categories.py" 2>/dev/null & - fi - -elif [ "$SOURCE" = "resume" ]; then - echo "Session resumed. Search mem0 for session_state and decision memories to pick up where you left off. Run 2 parallel searches." - -elif [ "$SOURCE" = "compact" ]; then - echo "Context compacted. Search mem0 for session_state and decision memories to recover context. Run 2 parallel searches." - if [ "${MEM0_AUTO_SAVE:-true}" != "false" ]; then - printf '%s' "$INPUT" | python3 "$SCRIPT_DIR/capture_compact_summary.py" 2>/dev/null & - fi -fi - -python3 "$SCRIPT_DIR/telemetry.py" session_start --source="$SOURCE" --memory_count="${MEM0_COUNT:-0}" 2>/dev/null & - -exit 0 diff --git a/integrations/mem0-plugin/scripts/on_session_start_cursor.sh b/integrations/mem0-plugin/scripts/on_session_start_cursor.sh deleted file mode 100755 index 905a5fb5b..000000000 --- a/integrations/mem0-plugin/scripts/on_session_start_cursor.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash -# Hook: sessionStart (Cursor) -# -# Wraps on_session_start.sh and converts plain-text output to Cursor's -# expected JSON format: {"additional_context":""} - -set -uo pipefail - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" - -# Pin platform so the shared script's telemetry is attributed to cursor. -export MEM0_PLATFORM=cursor - -TEXT=$("$SCRIPT_DIR/on_session_start.sh" 2>/dev/null || echo "") - -if [ -z "$TEXT" ]; then - echo '{}' - exit 0 -fi - -jq -cn --arg ctx "$TEXT" '{additional_context:$ctx}' -exit 0 diff --git a/integrations/mem0-plugin/scripts/on_stop.sh b/integrations/mem0-plugin/scripts/on_stop.sh deleted file mode 100755 index 636270816..000000000 --- a/integrations/mem0-plugin/scripts/on_stop.sh +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env bash -# Hook: Stop -# -# Captures a structured session summary when a Claude Code session ends. -# Parses the transcript, extracts the last assistant message and files -# touched, then stores via mem0 API with infer=True for AI extraction. -# -# Guards: -# - Skips subagent sessions (agent_id present) -# - Skips if no API key -# - Skips if no transcript_path -# - Dedup via marker file -# -# Input: JSON on stdin with transcript_path, session_id, agent_id, cwd -# Output: Nothing to stdout (background capture). Always exits 0. - -set -uo pipefail - -if [ -n "${MEM0_DEBUG:-}" ]; then - mkdir -p "$HOME/.mem0" && exec 2>>"$HOME/.mem0/hooks.log" -fi - -INPUT=$(cat) - -# Guard: skip subagent sessions -AGENT_ID=$(echo "$INPUT" | jq -r '.agent_id // ""' 2>/dev/null || echo "") -if [ -n "$AGENT_ID" ]; then - exit 0 -fi - -# Resolve identity if needed -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -. "$SCRIPT_DIR/_identity.sh" 2>/dev/null || true - -# Honor auto_save=false in ~/.mem0/settings.json -if [ "${MEM0_AUTO_SAVE:-true}" = "false" ]; then - exit 0 -fi - -if [ -z "${MEM0_API_KEY:-}" ]; then - exit 0 -fi - -TRANSCRIPT_PATH=$(echo "$INPUT" | jq -r '.transcript_path // ""' 2>/dev/null || echo "") -if [ -z "$TRANSCRIPT_PATH" ]; then - exit 0 -fi - -# Run capture in the background — fires every turn now, so avoid blocking -echo "$INPUT" | python3 "$SCRIPT_DIR/capture_session_summary.py" 2>/dev/null & - -# Telemetry -python3 "$SCRIPT_DIR/telemetry.py" session_stop 2>/dev/null & - -exit 0 diff --git a/integrations/mem0-plugin/scripts/on_stop_cursor.sh b/integrations/mem0-plugin/scripts/on_stop_cursor.sh deleted file mode 100755 index 77a8cd0a4..000000000 --- a/integrations/mem0-plugin/scripts/on_stop_cursor.sh +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env bash -# Hook: stop — Cursor variant -# -# Same as on_stop.sh but uses CURSOR_PLUGIN_ROOT and Cursor-specific -# identity resolution. - -set -uo pipefail - -if [ -n "${MEM0_DEBUG:-}" ]; then - mkdir -p "$HOME/.mem0" && exec 2>>"$HOME/.mem0/hooks.log" -fi - -INPUT=$(cat) - -AGENT_ID=$(echo "$INPUT" | jq -r '.agent_id // ""' 2>/dev/null || echo "") -if [ -n "$AGENT_ID" ]; then - exit 0 -fi - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -# Pin platform so this hook's telemetry is attributed to cursor. -export MEM0_PLATFORM=cursor -. "$SCRIPT_DIR/_identity.sh" 2>/dev/null || true - -if [ -z "${MEM0_API_KEY:-}" ]; then - exit 0 -fi - -TRANSCRIPT_PATH=$(echo "$INPUT" | jq -r '.transcript_path // ""' 2>/dev/null || echo "") -if [ -z "$TRANSCRIPT_PATH" ]; then - exit 0 -fi - -echo "$INPUT" | python3 "$SCRIPT_DIR/capture_session_summary.py" 2>/dev/null || true - -python3 "$SCRIPT_DIR/telemetry.py" session_stop 2>/dev/null & - -exit 0 diff --git a/integrations/mem0-plugin/scripts/on_user_prompt.sh b/integrations/mem0-plugin/scripts/on_user_prompt.sh deleted file mode 100755 index f30380003..000000000 --- a/integrations/mem0-plugin/scripts/on_user_prompt.sh +++ /dev/null @@ -1,228 +0,0 @@ -#!/usr/bin/env bash -# Hook: UserPromptSubmit -# -# Fires on every user message. Prefetches memories relevant to the current -# prompt (so relevant context is guaranteed) and also injects a decision -# rubric telling the agent when to search further itself -- including -# follow-up searches for multi-part questions. Prefetch can be disabled -# with MEM0_PREFETCH=false. -# -# Input: JSON on stdin (prompt, session_id, cwd, transcript_path) -# Output: Decision rubric injected into Claude's context (exit 0) - -# Intentionally omit -e so the script always exits 0 even if jq fails -- -# must never block the user's prompt. -set -uo pipefail - -if [ -n "${MEM0_DEBUG:-}" ]; then - mkdir -p "$HOME/.mem0" && exec 2>>"$HOME/.mem0/hooks.log" -fi - -INPUT=$(cat) -PROMPT=$(echo "$INPUT" | jq -r '.prompt // ""' 2>/dev/null || echo "") - -# Acknowledgements and short replies don't warrant memory context -if [ ${#PROMPT} -lt 20 ]; then - exit 0 -fi - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" -# shellcheck source=_identity.sh -. "$SCRIPT_DIR/_identity.sh" 2>/dev/null || true - -# Rubric dedup: only inject full rubric once per session. -# Key on session ID to avoid cross-session interference. -SESSION_ID=$(echo "$INPUT" | jq -r '.session_id // ""' 2>/dev/null || echo "") -if [ -z "$SESSION_ID" ]; then - _SID_FILE="/tmp/mem0_session_id_${USER:-default}" - [ -f "$_SID_FILE" ] && SESSION_ID=$(cat "$_SID_FILE" 2>/dev/null) || true -fi -if [ -z "$SESSION_ID" ]; then - SESSION_ID="default_${USER:-unknown}" -fi -RUBRIC_DIR="${MEM0_RUBRIC_DIR:-/tmp}" -RUBRIC_FLAG="$RUBRIC_DIR/mem0_rubric_${SESSION_ID}" -RUBRIC_ALREADY_SHOWN="" -if [ -f "$RUBRIC_FLAG" ]; then - RUBRIC_ALREADY_SHOWN="true" -fi - -# Track message count for periodic memory-save nudges. -# Every 5th substantial message, remind the agent to store learnings. -MSG_COUNT_FILE="/tmp/mem0_msg_count_${USER:-default}" -MSG_COUNT=0 -if [ -f "$MSG_COUNT_FILE" ]; then - MSG_COUNT=$(cat "$MSG_COUNT_FILE" 2>/dev/null || echo "0") -fi -MSG_COUNT=$((MSG_COUNT + 1)) -printf '%s' "$MSG_COUNT" > "$MSG_COUNT_FILE" 2>/dev/null || true -NEEDS_SAVE_NUDGE="" -if [ $((MSG_COUNT % 5)) -eq 0 ] && [ "$MSG_COUNT" -gt 0 ]; then - NEEDS_SAVE_NUDGE="true" -fi - -# Detect stack traces and error patterns in the prompt (no API needed) -HAS_ERROR="" -if echo "$PROMPT" | grep -qE '(Traceback|panic:)'; then - HAS_ERROR="true" -elif echo "$PROMPT" | grep -qE '^\s*fatal: '; then - HAS_ERROR="true" -elif [ "$(echo "$PROMPT" | grep -cE '(Error:|Exception:|FAIL:)')" -ge 2 ]; then - HAS_ERROR="true" -fi - -# Detect file paths in the prompt (no API needed) -FILE_PATHS=$(echo "$PROMPT" | grep -oE '([a-zA-Z0-9_./-]+\.(py|ts|tsx|js|jsx|rs|go|rb|java|sh|yaml|yml|json|toml|md|sql|css|html))\b' 2>/dev/null | head -5 || echo "") - -# Detect session-resume patterns -HAS_RESUME="" -if echo "$PROMPT" | grep -qiE '(where (did )?(we|I) (leave|left) off|continue (from )?(where|last)|what were we (working|doing)|pick up where|resume (from |where)|what.s the (current|latest) (state|status)|catch me up|where are we)'; then - HAS_RESUME="true" -fi - -# Detect explicit memory-save intent -HAS_REMEMBER="" -if echo "$PROMPT" | grep -qiE '(remember (this|that)|save (this|that) (fact|info|memory|note)|store (this|that)|don.t forget (this|that)|keep (this|that) in (mind|memory))'; then - HAS_REMEMBER="true" -fi - -# Telemetry (background, fire-and-forget) -_TELEM_ARGS="" -[ -n "$HAS_ERROR" ] && _TELEM_ARGS="$_TELEM_ARGS --error_detected" -[ -n "$FILE_PATHS" ] && _TELEM_ARGS="$_TELEM_ARGS --file_paths_detected" -[ -n "$HAS_RESUME" ] && _TELEM_ARGS="$_TELEM_ARGS --resume_detected" -[ -n "$HAS_REMEMBER" ] && _TELEM_ARGS="$_TELEM_ARGS --remember_detected" -python3 "$SCRIPT_DIR/telemetry.py" user_prompt $_TELEM_ARGS 2>/dev/null & - -# No API key — emit detections only, skip search rubric -if [ -z "${MEM0_API_KEY:-}" ]; then - _PROMPT_CTX="" - if [ -n "$HAS_ERROR" ]; then - _PROMPT_CTX="Error detected in prompt. Set MEM0_API_KEY to search past debugging context." - fi - if [ -n "$FILE_PATHS" ]; then - _PROMPT_CTX="${_PROMPT_CTX:+${_PROMPT_CTX}\n}File paths detected: ${FILE_PATHS}" - fi - if [ -n "$_PROMPT_CTX" ]; then - jq -cn --arg ctx "$_PROMPT_CTX" '{ - hookSpecificOutput: { - hookEventName: "UserPromptSubmit", - additionalContext: $ctx - } - }' - fi - exit 0 -fi -USER_ID="$MEM0_RESOLVED_USER_ID" - -_PROMPT_CTX="" - -if [ -n "$HAS_RESUME" ]; then - RESUME_RESULTS=$(PYTHONPATH="$SCRIPT_DIR" MEM0_SEARCH_USER="$USER_ID" python3 -c " -import os, sys -sys.path.insert(0, os.environ.get('PYTHONPATH', '.')) -from _search import search_memories, format_results_for_context, should_rerank - -api_key = os.environ.get('MEM0_API_KEY', '') -user_id = os.environ.get('MEM0_SEARCH_USER', 'default') -project_id = os.environ.get('MEM0_PROJECT_ID', 'unknown') -rerank = should_rerank() - -state = search_memories(api_key, user_id, project_id, 'session state current task', metadata_type='session_state', top_k=3, rerank=rerank) -decisions = search_memories(api_key, user_id, project_id, 'recent decisions and learnings', metadata_type='decision', top_k=3, rerank=rerank) - -all_r = state + decisions -seen = set() -unique = [] -for m in all_r: - mid = m.get('id', '') - if mid not in seen: - seen.add(mid) - unique.append(m) - -if unique: - print(format_results_for_context(unique, heading='Session context recovered from mem0')) - print() - print('These memories provide context for resuming work.') -else: - print('No session state found in mem0.') -" 2>/dev/null || echo "") - - if [ -n "$RESUME_RESULTS" ]; then - _PROMPT_CTX="${RESUME_RESULTS}" - fi -fi - -# Query-driven prefetch: search mem0 with the current prompt and inject the top -# matches so relevant memories are guaranteed in context, not left for the agent -# to fetch. Skipped on resume (handled above with targeted queries) and when -# MEM0_PREFETCH=false. -if [ -z "$HAS_RESUME" ] && [ "${MEM0_PREFETCH:-true}" != "false" ]; then - PREFETCH_RESULTS=$(PYTHONPATH="$SCRIPT_DIR" MEM0_SEARCH_USER="$USER_ID" MEM0_SEARCH_QUERY="$PROMPT" python3 -c " -import os, sys -sys.path.insert(0, os.environ.get('PYTHONPATH', '.')) -from _search import search_memories, format_results_for_context, should_rerank - -api_key = os.environ.get('MEM0_API_KEY', '') -user_id = os.environ.get('MEM0_SEARCH_USER', 'default') -project_id = os.environ.get('MEM0_PROJECT_ID', 'unknown') -query = os.environ.get('MEM0_SEARCH_QUERY', '') - -results = search_memories(api_key, user_id, project_id, query, top_k=5, rerank=should_rerank()) -if results: - print(format_results_for_context(results, heading='Relevant memories (auto-retrieved for this request)')) -" 2>/dev/null || echo "") - - if [ -n "$PREFETCH_RESULTS" ]; then - _PROMPT_CTX="${_PROMPT_CTX:+${_PROMPT_CTX}\n}${PREFETCH_RESULTS}" - fi -fi - -if [ -n "$HAS_REMEMBER" ]; then - _PROMPT_CTX="${_PROMPT_CTX:+${_PROMPT_CTX}\n}Remember intent detected. The /mem0:remember skill auto-classifies, sets confidence=1.0, and stores verbatim." -fi - -if [ -z "$RUBRIC_ALREADY_SHOWN" ]; then - _PROMPT_CTX="${_PROMPT_CTX:+${_PROMPT_CTX}\n}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. For multi-part or comparative questions, run follow-up searches and combine results before answering -- one search is rarely enough." - touch "$RUBRIC_FLAG" 2>/dev/null || true -fi - -if [ -n "$HAS_ERROR" ]; then - _PROMPT_CTX="${_PROMPT_CTX:+${_PROMPT_CTX}\n}Error detected in prompt. Prior occurrences are available in mem0 via anti_pattern and task_learning type filters." -fi - -if [ -n "$FILE_PATHS" ]; then - _PROMPT_CTX="${_PROMPT_CTX:+${_PROMPT_CTX}\n}File paths detected: ${FILE_PATHS}" -fi - -# Auto-capture: directly call mem0 API in background every 3rd message. -# At MSG_COUNT=3 the 3rd response isn't in the transcript yet (hook fires -# before Claude responds), so we capture 4 exchanges instead of 3. The -# overlapping window ensures the next batch (MSG_COUNT=6) picks up the -# exchange that was incomplete in the previous batch. -TRANSCRIPT_PATH=$(echo "$INPUT" | jq -r '.transcript_path // ""' 2>/dev/null || echo "") -if [ "${MEM0_AUTO_SAVE:-true}" != "false" ] && [ $((MSG_COUNT % 3)) -eq 0 ] && [ "$MSG_COUNT" -gt 0 ] && [ -n "$TRANSCRIPT_PATH" ]; then - python3 "$SCRIPT_DIR/auto_capture.py" "$TRANSCRIPT_PATH" 2>/dev/null & -fi - -# Prompt-based nudge as fallback when auto-capture hasn't run yet. -_ADDS=0 -_STATS_FILE="/tmp/mem0_session_stats_${USER:-default}.json" -if [ -f "$_STATS_FILE" ]; then - _ADDS=$(python3 -c "import json; print(json.load(open('$_STATS_FILE')).get('adds',0))" 2>/dev/null || echo "0") -fi - -if [ "$MSG_COUNT" -ge 3 ] && [ "$_ADDS" -lt "$((MSG_COUNT / 3))" ]; then - _PROMPT_CTX="${_PROMPT_CTX:+${_PROMPT_CTX}\n}After responding, store any new decisions, learnings, or preferences from this exchange via add_memory. Keep it to 1 sentence per memory." -fi - -if [ -n "$_PROMPT_CTX" ]; then - jq -cn --arg ctx "$_PROMPT_CTX" '{ - hookSpecificOutput: { - hookEventName: "UserPromptSubmit", - additionalContext: $ctx - } - }' -fi - -exit 0 diff --git a/integrations/mem0-plugin/scripts/on_user_prompt_cursor.sh b/integrations/mem0-plugin/scripts/on_user_prompt_cursor.sh deleted file mode 100755 index 17a82a7f2..000000000 --- a/integrations/mem0-plugin/scripts/on_user_prompt_cursor.sh +++ /dev/null @@ -1,22 +0,0 @@ -#!/usr/bin/env bash -# Hook: beforeSubmitPrompt (Cursor) -# -# Wraps on_user_prompt.sh and converts plain-text output to Cursor's -# expected JSON format: {"continue":true,"user_message":""} - -set -uo pipefail - -SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" - -# Pin platform so the shared script's telemetry is attributed to cursor. -export MEM0_PLATFORM=cursor - -TEXT=$("$SCRIPT_DIR/on_user_prompt.sh" 2>/dev/null || echo "") - -if [ -z "$TEXT" ]; then - jq -cn '{continue:true}' - exit 0 -fi - -jq -cn --arg msg "$TEXT" '{continue:true, user_message:$msg}' -exit 0 diff --git a/integrations/mem0-plugin/scripts/parse_export_file.py b/integrations/mem0-plugin/scripts/parse_export_file.py deleted file mode 100644 index eb28ab919..000000000 --- a/integrations/mem0-plugin/scripts/parse_export_file.py +++ /dev/null @@ -1,150 +0,0 @@ -#!/usr/bin/env python3 -"""Parse a mem0 export file and output JSON. - -Input: path to a mem0-export-*.md file (sys.argv[1]) -Output: JSON array of memory records to stdout -Exit: 0 always - -Each block in the file is delimited by lines containing exactly "---". -Blocks have a YAML-like frontmatter section (key: value lines) followed -by a blank line and the memory content text. - -Example block format: ---- -id: abc123 -created_at: 2024-01-01T00:00:00Z -type: task_learnings -confidence: 0.9 -branch: main -files: src/foo.py, src/bar.py -categories: coding_conventions, task_learnings ---- -The actual memory content text goes here. - -""" - -from __future__ import annotations - -import json -import re -import sys - - -def parse_blocks(content: str) -> list[dict]: - """Split content on '---' boundaries and parse each block. - - Returns a list of dicts with keys: - id, type, confidence, branch, files (list), categories (list), content (str) - - Blocks with empty content are skipped. - Missing optional fields default to "" (scalar) or [] (list fields). - """ - # Normalise line endings - content = content.replace("\r\n", "\n").replace("\r", "\n") - - # Split on lines that are exactly "---" - raw_blocks = re.split(r"(?m)^---\s*$", content) - - # After splitting on "---", the structure for each memory is: - # raw_blocks[0] = preamble (before first ---, typically empty) - # raw_blocks[1] = frontmatter for block 1 - # raw_blocks[2] = content for block 1 - # raw_blocks[3] = frontmatter for block 2 - # raw_blocks[4] = content for block 2 - # ... - # So frontmatter blocks are at odd indices (1, 3, 5, ...) and - # content blocks at even indices (2, 4, 6, ...). - - results: list[dict] = [] - - # Pair up frontmatter + content starting at index 1 - i = 1 - while i < len(raw_blocks): - frontmatter_raw = raw_blocks[i] - content_raw = raw_blocks[i + 1] if i + 1 < len(raw_blocks) else "" - - # Parse the frontmatter key-value pairs - fm = _parse_frontmatter(frontmatter_raw) - - # Strip leading/trailing whitespace from content - memory_content = content_raw.strip() - - # Skip blocks with empty content - if not memory_content: - i += 2 - continue - - record = { - "id": fm.get("id", ""), - "type": fm.get("type", ""), - "confidence": fm.get("confidence", ""), - "branch": fm.get("branch", ""), - "files": _parse_list_field(fm.get("files", "")), - "categories": _parse_list_field(fm.get("categories", "")), - "content": memory_content, - } - - # Include created_at if present - if "created_at" in fm: - record["created_at"] = fm["created_at"] - - results.append(record) - i += 2 - - return results - - -def _parse_frontmatter(text: str) -> dict[str, str]: - """Parse simple 'key: value' lines from frontmatter text. - - Only the first colon is used as the delimiter — values may contain colons. - Lines not matching 'key: value' are ignored. - """ - result: dict[str, str] = {} - for line in text.splitlines(): - line = line.strip() - if not line: - continue - match = re.match(r"^([A-Za-z_][A-Za-z0-9_]*)\s*:\s*(.*)$", line) - if match: - key = match.group(1).strip() - value = match.group(2).strip() - result[key] = value - return result - - -def _parse_list_field(value: str) -> list[str]: - """Split a comma-separated value into a list, stripping whitespace. - - Returns [] for empty/whitespace-only input. - """ - if not value or not value.strip(): - return [] - return [item.strip() for item in value.split(",") if item.strip()] - - -def main() -> None: - if len(sys.argv) < 2: - print("Usage: parse_export_file.py ", file=sys.stderr) - print("[]") - sys.exit(0) - - filepath = sys.argv[1] - try: - if filepath == "-": - content = sys.stdin.read() - else: - with open(filepath, encoding="utf-8", errors="replace") as f: - content = f.read() - except OSError as e: - print(f"Error reading file: {e}", file=sys.stderr) - print("[]") - sys.exit(0) - - records = parse_blocks(content) - print(json.dumps(records, ensure_ascii=False, indent=2)) - sys.exit(0) - - -if __name__ == "__main__": - main() diff --git a/integrations/mem0-plugin/scripts/parse_mem0_config.py b/integrations/mem0-plugin/scripts/parse_mem0_config.py deleted file mode 100644 index dd6361f3a..000000000 --- a/integrations/mem0-plugin/scripts/parse_mem0_config.py +++ /dev/null @@ -1,316 +0,0 @@ -#!/usr/bin/env python3 -"""Parse mem0.md project configuration file. - -Reads the optional ``mem0.md`` file in a project directory and extracts -retention policies from a ``## Retention`` section. - -Retention format (inside the section): - : d — keep for N days - : forever — never prune (returned as None) - -Usage (CLI): - python3 parse_mem0_config.py [] - -Prints a JSON object mapping category names to day counts (int) or null -(forever) on stdout. Prints ``{}`` when no mem0.md or no ## Retention -section is found. -""" - -from __future__ import annotations - -import json -import os -import re -import sys - - -def find_mem0_config(cwd: str) -> str | None: - """Look for ``mem0.md`` in *cwd*. - - Returns the absolute path to ``mem0.md`` if found, else ``None``. - """ - candidate = os.path.join(cwd, "mem0.md") - return candidate if os.path.isfile(candidate) else None - - -def parse_retention(content: str) -> dict[str, int | None]: - """Parse the ``## Retention`` section of *content*. - - Scans for a heading that matches ``## Retention`` (case-insensitive), - then reads lines until the next ``##``-level heading or end of string. - - Each non-blank, non-comment line inside the section is expected to be:: - - : d → days=N (int) - : forever → days=None - - Malformed lines are silently skipped. - - Args: - content: Full text of a mem0.md file. - - Returns: - Dict mapping category name (str) to day count (int) or ``None`` - (forever). Empty dict when no ``## Retention`` section is found. - """ - # Find the ## Retention section (allow any amount of trailing whitespace / - # extra words, but the heading must start with "## Retention"). - section_match = re.search( - r"^##\s+Retention[^\n]*\n(.*?)(?=^##\s|\Z)", - content, - flags=re.MULTILINE | re.DOTALL | re.IGNORECASE, - ) - if not section_match: - return {} - - section_text = section_match.group(1) - policies: dict[str, int | None] = {} - - for line in section_text.splitlines(): - # Strip comments and whitespace - line = re.sub(r"#.*$", "", line).strip() - if not line: - continue - - # Match ": " - line_match = re.match(r"^([^:]+):\s*(.+)$", line) - if not line_match: - continue - - category = line_match.group(1).strip() - value = line_match.group(2).strip().lower() - - if value == "forever": - policies[category] = None - else: - days_match = re.match(r"^(\d+)d$", value) - if days_match: - policies[category] = int(days_match.group(1)) - # else: malformed value — skip silently - - return policies - - -def parse_section_kv(content: str, heading: str) -> dict[str, str]: - """Parse a key-value section from mem0.md. - - Looks for ``## `` (case-insensitive) and reads ``key: value`` - lines until the next ``##``-level heading or end of string. - """ - pattern = rf"^##\s+{re.escape(heading)}[^\n]*\n(.*?)(?=^##\s|\Z)" - match = re.search(pattern, content, flags=re.MULTILINE | re.DOTALL | re.IGNORECASE) - if not match: - return {} - - result: dict[str, str] = {} - for line in match.group(1).splitlines(): - line = re.sub(r"#.*$", "", line).strip() - if not line: - continue - m = re.match(r"^([^:]+):\s*(.+)$", line) - if m: - result[m.group(1).strip()] = m.group(2).strip() - return result - - -def parse_section_list(content: str, heading: str) -> list[str]: - """Parse a list section from mem0.md. - - Looks for ``## `` and reads ``- item`` or bare lines. - """ - pattern = rf"^##\s+{re.escape(heading)}[^\n]*\n(.*?)(?=^##\s|\Z)" - match = re.search(pattern, content, flags=re.MULTILINE | re.DOTALL | re.IGNORECASE) - if not match: - return [] - - items: list[str] = [] - for line in match.group(1).splitlines(): - line = re.sub(r"#.*$", "", line).strip() - line = re.sub(r"^[-*]\s+", "", line).strip() - if line: - items.append(line) - return items - - -def parse_section_text(content: str, heading: str) -> str: - """Parse a free-text prose section from mem0.md. - - Looks for ``## `` (case-insensitive) and returns the prose beneath - it (up to the next ``##`` heading) collapsed to a single line. Blank lines and - full-line ``#`` comments are dropped; inline ``#`` is preserved (prose may - reference e.g. issue ``#123``). - """ - pattern = rf"^##\s+{re.escape(heading)}[^\n]*\n(.*?)(?=^##\s|\Z)" - match = re.search(pattern, content, flags=re.MULTILINE | re.DOTALL | re.IGNORECASE) - if not match: - return "" - - lines: list[str] = [] - for line in match.group(1).splitlines(): - stripped = line.strip() - if not stripped or stripped.startswith("#"): - continue - lines.append(stripped) - return " ".join(lines).strip() - - -def parse_ignore_patterns(content: str) -> list[str]: - """Parse the ``## Ignore`` section of *content*. - - Each non-blank line is a glob pattern (e.g., ``node_modules``, ``*.lock``). - Lines starting with ``#`` are comments and skipped. - """ - pattern = r"^##\s+Ignore[^\n]*\n(.*?)(?=^##\s|\Z)" - match = re.search(pattern, content, flags=re.MULTILINE | re.DOTALL | re.IGNORECASE) - if not match: - return [] - - patterns: list[str] = [] - for line in match.group(1).splitlines(): - line = line.strip() - if not line or line.startswith("#"): - continue - line = re.sub(r"^[-*]\s+", "", line).strip() - if line: - patterns.append(line) - return patterns - - -def load_full_config(cwd: str | None = None) -> dict: - """Load all config sections from mem0.md. - - Returns a dict with keys: retention, search, categories, identity, - ignore, project_id. - Each is populated only if the corresponding ``##`` section exists. - """ - if cwd is None: - cwd = os.getcwd() - - config_path = find_mem0_config(cwd) - if config_path is None: - return {} - - try: - with open(config_path, encoding="utf-8") as fh: - content = fh.read() - except OSError: - return {} - - config: dict = {} - - retention = parse_retention(content) - if retention: - config["retention"] = retention - - search = parse_section_kv(content, "Search") - if search: - config["search"] = search - - categories = parse_section_list(content, "Categories") - if categories: - config["categories"] = categories - config["default_categories"] = categories - - identity = parse_section_kv(content, "Identity") - if identity: - config["identity"] = identity - if "project_id" in identity: - config["project_id"] = identity["project_id"] - - ignore = parse_ignore_patterns(content) - if ignore: - config["ignore"] = ignore - - settings = parse_section_kv(content, "Settings") - if settings: - config["settings"] = settings - - # Extraction policy: `## Instructions` -> custom_instructions (user/project - # scope), `## Agent Instructions` -> agent_custom_instructions (agent scope). - instructions = parse_section_text(content, "Instructions") - if instructions: - config["instructions"] = instructions - - agent_instructions = parse_section_text(content, "Agent Instructions") - if agent_instructions: - config["agent_instructions"] = agent_instructions - - return config - - -def load_retention_policies(cwd: str | None = None) -> dict[str, int | None]: - """Load retention policies from the mem0.md in *cwd*. - - Combines :func:`find_mem0_config` and :func:`parse_retention` into a - single convenience function. - """ - if cwd is None: - cwd = os.getcwd() - - config_path = find_mem0_config(cwd) - if config_path is None: - return {} - - try: - with open(config_path, encoding="utf-8") as fh: - content = fh.read() - except OSError: - return {} - - return parse_retention(content) - - -def main() -> int: - """CLI entry point. - - With ``--full``, prints the complete config. Without it, prints only - retention policies (backward-compatible). - - With ``--key ``, prints the scalar value at that path in the - full config (e.g. ``--key settings.commit_prompts``). Prints an empty - string when the key is absent. Exits 1 only on unexpected errors. - """ - full_mode = "--full" in sys.argv - - # Extract --key - key_path: str | None = None - raw_args = sys.argv[1:] - filtered_args: list[str] = [] - i = 0 - while i < len(raw_args): - if raw_args[i] == "--key" and i + 1 < len(raw_args): - key_path = raw_args[i + 1] - i += 2 - elif raw_args[i].startswith("--key="): - key_path = raw_args[i][len("--key="):] - i += 1 - elif raw_args[i].startswith("--"): - i += 1 # skip other flags like --full - else: - filtered_args.append(raw_args[i]) - i += 1 - - cwd = filtered_args[0] if filtered_args else os.getcwd() - - if key_path is not None: - config = load_full_config(cwd) - # Traverse dotted path - value: object = config - for part in key_path.split("."): - if not isinstance(value, dict): - value = None - break - value = value.get(part) - print(value if value is not None else "") - return 0 - - if full_mode: - config = load_full_config(cwd) - else: - config = load_retention_policies(cwd) - print(json.dumps(config)) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/integrations/mem0-plugin/scripts/session_stats.py b/integrations/mem0-plugin/scripts/session_stats.py deleted file mode 100644 index 357fe4dd6..000000000 --- a/integrations/mem0-plugin/scripts/session_stats.py +++ /dev/null @@ -1,138 +0,0 @@ -#!/usr/bin/env python3 -"""Session stats tracker for mem0 plugin. - -Tracks memory adds/searches per session. -Uses /tmp/mem0_session_stats_$USER.json (single file per user, reset on init). - -Usage: - python session_stats.py init # reset for new session - python session_stats.py add # record a memory write - python session_stats.py search # record a search - python session_stats.py report # print summary, clean up temp file -""" - -from __future__ import annotations - -import json -import os -import sys -from datetime import datetime - -STATS_FILE = f"/tmp/mem0_session_stats_{os.environ.get('USER', 'default')}.json" - - -def _load() -> dict: - if os.path.isfile(STATS_FILE): - try: - with open(STATS_FILE) as f: - return json.load(f) - except (json.JSONDecodeError, OSError): - pass - return { - "adds": 0, - "searches": 0, - "categories": [], - "category_counts": {}, - "started": datetime.now().isoformat(), - } - - -def _save(stats: dict) -> None: - with open(STATS_FILE, "w") as f: - json.dump(stats, f) - - -MAX_RECENT_IDS = 50 - - -def init() -> None: - _save({ - "adds": 0, - "searches": 0, - "categories": [], - "category_counts": {}, - "recent_ids": [], - "started": datetime.now().isoformat(), - }) - - -def record_add(category: str = "", memory_id: str = "") -> None: - stats = _load() - stats["adds"] = stats.get("adds", 0) + 1 - if category: - if category not in stats.get("categories", []): - stats.setdefault("categories", []).append(category) - counts = stats.setdefault("category_counts", {}) - counts[category] = counts.get(category, 0) + 1 - if memory_id: - recent = stats.setdefault("recent_ids", []) - recent.append({"id": memory_id, "category": category, "ts": datetime.now().isoformat()}) - if len(recent) > MAX_RECENT_IDS: - stats["recent_ids"] = recent[-MAX_RECENT_IDS:] - _save(stats) - - -def record_search() -> None: - stats = _load() - stats["searches"] = stats.get("searches", 0) + 1 - _save(stats) - - -def peek() -> str: - """Return current stats as JSON without clearing the file.""" - stats = _load() - return json.dumps(stats) - - -def report() -> str: - stats = _load() - adds = stats.get("adds", 0) - searches = stats.get("searches", 0) - categories = stats.get("categories", []) - - if adds == 0 and searches == 0: - return "" - - parts = [] - category_counts = stats.get("category_counts", {}) - if category_counts: - breakdown = ", ".join(f"{c} {n}" for c, n in sorted(category_counts.items(), key=lambda x: -x[1])) - parts.append(f"Session: wrote {adds} memories ({breakdown}), retrieved {searches}") - else: - parts.append(f"Session: wrote {adds} memories, retrieved {searches}") - if categories: - parts.append(f"Categories touched: {', '.join(categories)}") - - return ". ".join(parts) + "." - - -def main() -> int: - if len(sys.argv) < 2: - print("Usage: session_stats.py [init|add|search|report]", file=sys.stderr) - return 1 - - cmd = sys.argv[1] - if cmd == "init": - init() - elif cmd == "add": - category = sys.argv[2] if len(sys.argv) > 2 else "" - memory_id = sys.argv[3] if len(sys.argv) > 3 else "" - record_add(category, memory_id) - elif cmd == "search": - record_search() - elif cmd == "peek": - print(peek()) - elif cmd == "report": - result = report() - if result: - print(result) - else: - print("Session: no memory operations.") - else: - print(f"Unknown command: {cmd}", file=sys.stderr) - return 1 - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/integrations/mem0-plugin/scripts/session_timeline.py b/integrations/mem0-plugin/scripts/session_timeline.py deleted file mode 100644 index 86e22f7fb..000000000 --- a/integrations/mem0-plugin/scripts/session_timeline.py +++ /dev/null @@ -1,106 +0,0 @@ -#!/usr/bin/env python3 -"""Fetch recent memories and format a compact timeline for SessionStart. - -Searches mem0 cloud API for the most recent memories in the project -and formats them as a compact activity timeline injected below the -existing SessionStart banner. - -Input: env vars for identity (MEM0_API_KEY, MEM0_RESOLVED_USER_ID, etc.) -Output: Compact timeline text to stdout (empty if nothing found) -""" - -from __future__ import annotations - -import json -import os -import sys -import urllib.request - -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) -from _formatting import TYPE_ICONS, format_age -from _identity import resolve_api_key, resolve_user_id -from _project import resolve_project_id - -API_URL = "https://api.mem0.ai" -MAX_RECENT = 10 -MAX_SUMMARIES = 3 -FETCH_TIMEOUT = 5 - - -def fetch_recent_memories(api_key: str, user_id: str, project_id: str) -> list[dict]: - """Fetch the most recent memories for this project via GET list endpoint.""" - global_search = os.environ.get("MEM0_GLOBAL_SEARCH", "false") == "true" - - if global_search: - filters = {"OR": [{"user_id": "*"}]} - else: - filters = {"AND": [{"user_id": user_id}, {"app_id": project_id}]} - - body = json.dumps({"filters": filters}).encode() - req = urllib.request.Request( - f"{API_URL}/v3/memories/?page=1&page_size={MAX_RECENT}", - data=body, - headers={ - "Authorization": f"Token {api_key}", - "Content-Type": "application/json", - }, - method="POST", - ) - try: - with urllib.request.urlopen(req, timeout=FETCH_TIMEOUT) as r: - result = json.loads(r.read()) - if isinstance(result, dict) and "results" in result: - return result["results"][:MAX_RECENT] - if isinstance(result, list): - return result[:MAX_RECENT] - return [] - except Exception: - return [] - - -def format_timeline(memories: list[dict]) -> str: - """Format memories into a compact recent activity timeline.""" - if not memories: - return "" - - lines = ["### Recent Activity", ""] - - for m in memories: - mid = m.get("id", "?")[:8] - text = (m.get("memory", "") or "")[:120].replace("\n", " ").strip() - meta = m.get("metadata") or {} - cat = meta.get("type", "unknown") - icon = TYPE_ICONS.get(cat, "❓") - age = format_age(m) - age_str = f" ({age})" if age else "" - lines.append(f"- {icon} [{cat}]{age_str} {text} [mem0:{mid}]") - - lines.append("") - lines.append("Search mem0 for details on any of these, or for past decisions and task learnings relevant to the current task.") - - return "\n".join(lines) - - -def main(): - api_key = resolve_api_key() - if not api_key: - return - - user_id = resolve_user_id() - project_id = resolve_project_id(os.environ.get("MEM0_CWD")) - - memories = fetch_recent_memories(api_key, user_id, project_id) - if not memories: - return - - timeline = format_timeline(memories) - if timeline: - print(timeline, end="") - - -if __name__ == "__main__": - try: - main() - except Exception: - pass - sys.exit(0) diff --git a/integrations/mem0-plugin/scripts/setup_coding_categories.py b/integrations/mem0-plugin/scripts/setup_coding_categories.py deleted file mode 100644 index c3850adba..000000000 --- a/integrations/mem0-plugin/scripts/setup_coding_categories.py +++ /dev/null @@ -1,236 +0,0 @@ -#!/usr/bin/env python3 -"""Replace mem0's default category taxonomy with one tuned for coding workflows. - -mem0 auto-tags every memory with one or more `categories`. By default the list -is consumer-oriented (food, hobbies, music, ...), which is meaningless for code. -This script replaces the project's category list with a coding-focused one. - -Uses the mem0ai SDK (client.project.update). The SDK is installed into a -persistent venv at ${CLAUDE_PLUGIN_DATA}/venv by the ensure_deps.sh hook. - -Usage: - python setup_coding_categories.py # dry-run: show current vs proposed - python setup_coding_categories.py --apply # actually call project.update() - -Requires MEM0_API_KEY (or CLAUDE_PLUGIN_OPTION_MEM0_API_KEY). -""" - -from __future__ import annotations - -import argparse -import json -import os -import sys - -_script_dir = os.path.dirname(os.path.abspath(__file__)) -sys.path.insert(0, _script_dir) -from _identity import resolve_api_key # noqa: E402 - -_plugin_root = os.environ.get("CLAUDE_PLUGIN_ROOT", os.path.join(_script_dir, "..")) -_data_dir = os.environ.get("CLAUDE_PLUGIN_DATA", os.path.join(os.path.expanduser("~"), ".mem0", "plugin-data")) -_venv_site = os.path.join(_data_dir, "venv", "lib") -if os.path.isdir(_venv_site): - for d in sorted(os.listdir(_venv_site)): - sp = os.path.join(_venv_site, d, "site-packages") - if os.path.isdir(sp) and sp not in sys.path: - sys.path.insert(1, sp) - -CODING_CATEGORIES = [ - { - "architecture_decisions": ( - "Design choices, system structure, technology selection, trade-offs evaluated, " - "and architectural patterns adopted in the project." - ) - }, - { - "anti_patterns": ( - "Approaches that failed, debugging dead-ends, common mistakes to avoid, " - "and lessons learned from things that didn't work." - ) - }, - { - "task_learnings": ( - "Strategies and approaches that succeeded for specific tasks, including tooling " - "tricks, workflow shortcuts, and effective problem-solving patterns." - ) - }, - { - "tooling_setup": ( - "Development environment, build tools, dependencies, package managers, deploy " - "pipelines, and configuration steps for the project." - ) - }, - { - "bug_fixes": ( - "Specific bug fixes with root cause analysis, the fix applied, and how the bug " - "was diagnosed -- useful for recognising similar issues later." - ) - }, - { - "coding_conventions": ( - "Code style, naming patterns, file organisation, error-handling conventions, " - "and team agreements about how code is written in this project." - ) - }, - { - "user_preferences": ( - "User's stated preferences for tools, libraries, languages, formatting, " - "and ways of working." - ) - }, - { - "dependency_decisions": ( - "Why specific libraries, frameworks, or package versions were chosen or replaced, " - "including the alternatives considered and the reasoning behind the selection." - ) - }, - { - "performance_findings": ( - "Profiling results, bottlenecks identified, optimisations applied, and measurable " - "improvements achieved -- useful for avoiding regressions and guiding future work." - ) - }, - { - "security_constraints": ( - "Security requirements, authentication and authorisation rules, data-handling " - "constraints, compliance obligations, and known threat mitigations in effect." - ) - }, - { - "testing_patterns": ( - "Test strategies, frameworks chosen, coverage targets, fixture patterns, mocking " - "approaches, and how the test suite is structured for this project." - ) - }, - { - "data_model": ( - "Schema definitions, database column semantics, domain object relationships, " - "field constraints, and how data flows between storage and application layers." - ) - }, - { - "api_contracts": ( - "API endpoint shapes, request and response schemas, authentication requirements, " - "versioning policy, and any breaking-change commitments or deprecation timelines." - ) - }, - { - "deployment_runbook": ( - "How to build, release, deploy, and roll back the project. CI/CD pipeline steps, " - "environment-specific configuration, and on-call runbook entries." - ) - }, - { - "team_norms": ( - "Team working agreements, PR review etiquette, branching strategy, on-call " - "rotation, and other social or process conventions the team has agreed on." - ) - }, - { - "domain_glossary": ( - "Domain-specific terms, abbreviations, and acronyms with their precise meanings " - "in this project -- prevents misunderstandings across code, docs, and discussion." - ) - }, - { - "experiment_results": ( - "Results from A/B tests, feature-flag experiments, spikes, or proof-of-concept " - "work -- what was tried, what was measured, and what conclusion was reached." - ) - }, -] - - -def _print_categories(label: str, cats): - print(f"=== {label} ===") - if cats: - print(json.dumps(cats, indent=2)) - else: - print("(none / using mem0 defaults)") - print() - - -def _categories_match(current: list | None, proposed: list) -> bool: - """Compare categories by key sets, tolerating order differences and extra API fields.""" - if not current: - return False - current_keys = {k for d in current if isinstance(d, dict) for k in d} - proposed_keys = {k for d in proposed if isinstance(d, dict) for k in d} - if current_keys != proposed_keys: - return False - current_map = {k: v for d in current if isinstance(d, dict) for k, v in d.items()} - proposed_map = {k: v for d in proposed if isinstance(d, dict) for k, v in d.items()} - return all( - current_map.get(k, "").strip() == v.strip() - for k, v in proposed_map.items() - ) - - -def main() -> int: - ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) - ap.add_argument( - "--apply", - action="store_true", - help="Actually call project.update(). Without this flag, runs in dry-run mode.", - ) - args = ap.parse_args() - - api_key = resolve_api_key() - if not api_key: - print("ERROR: MEM0_API_KEY is not set. Export it or configure it via plugin userConfig.", file=sys.stderr) - return 1 - os.environ["MEM0_API_KEY"] = api_key - - try: - from mem0 import MemoryClient - except ImportError: - print( - "ERROR: mem0ai SDK not found. The plugin's ensure_deps.sh hook should\n" - "install it automatically on session start. Try restarting Claude Code,\n" - "or run manually: pip install mem0ai", - file=sys.stderr, - ) - return 1 - - try: - client = MemoryClient() - except Exception as e: - print( - f"ERROR initialising MemoryClient: {e}\n" - "Most commonly this is an invalid MEM0_API_KEY -- check the key at " - "https://app.mem0.ai/dashboard/api-keys", - file=sys.stderr, - ) - return 1 - - try: - current = client.project.get(fields=["custom_categories"]) - current_cats = current.get("custom_categories") if isinstance(current, dict) else None - except Exception as e: - print(f"ERROR fetching current categories: {e}", file=sys.stderr) - return 1 - - _print_categories("Current project categories", current_cats) - _print_categories("Proposed coding categories", CODING_CATEGORIES) - - if not args.apply: - print("Dry-run only -- no changes made. Re-run with --apply to write.") - return 0 - - if _categories_match(current_cats, CODING_CATEGORIES): - print("Categories already match -- skipping update.") - return 0 - - print("Applying coding categories...") - try: - response = client.project.update(custom_categories=CODING_CATEGORIES) - except Exception as e: - print(f"ERROR applying update: {e}", file=sys.stderr) - return 1 - - print("Done.", response if response else "") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/integrations/mem0-plugin/scripts/telemetry.py b/integrations/mem0-plugin/scripts/telemetry.py deleted file mode 100644 index 7f351e02c..000000000 --- a/integrations/mem0-plugin/scripts/telemetry.py +++ /dev/null @@ -1,174 +0,0 @@ -#!/usr/bin/env python3 -"""Lightweight fire-and-forget telemetry for the mem0 plugin. - -Sends anonymous usage events to PostHog using the same project key and -endpoint as the mem0 Python SDK and CLI. No posthog library dependency — -uses stdlib urllib directly (same pattern as cli/python telemetry_sender.py). - -CLI usage (called from hooks as a background subprocess): - python3 telemetry.py [--memory_count=N] [--categories_count=N] - [--error_detected] [--file_paths_detected] - [--source=] [--tool=] - -Opt-out: set MEM0_TELEMETRY=false (or 0/no/off) to disable all telemetry. - -Never sends: user content, memory content, API keys, raw user/project IDs. -Only sends: event type, platform, plugin version, anonymized hashes, counts. -""" - -from __future__ import annotations - -import hashlib -import json -import os -import platform -import sys -import urllib.error -import urllib.request - -# Each editor surface ships its own manifest with its own version line -# (Antigravity is on 0.1.x while Cursor/Codex are on 0.2.x), so we read the -# manifest matching the detected platform rather than a single shared one. -_PLATFORM_MANIFESTS = { - "antigravity": ("..", "plugin.json"), - "cursor": ("..", ".cursor-plugin", "plugin.json"), - "codex": ("..", ".codex-plugin", "plugin.json"), - "kimi": ("..", ".kimi-plugin", "plugin.json"), -} - - -def _load_plugin_version(platform_name: str = "") -> str: - parts = _PLATFORM_MANIFESTS.get(platform_name) - if parts is None: - return "unknown" - try: - plugin_json = os.path.join(os.path.dirname(__file__), *parts) - with open(plugin_json) as f: - return json.load(f).get("version", "unknown") - except (OSError, json.JSONDecodeError, KeyError): - return "unknown" - - -POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" -POSTHOG_HOST = "https://us.i.posthog.com/i/v0/e/" -REQUEST_TIMEOUT = 2 - -SAMPLE_RATE = 1.0 - - -def _sha256(value: str) -> str: - return hashlib.sha256(value.encode("utf-8")).hexdigest() - - -def _distinct_id() -> str: - """Stable anonymous ID: SHA-256 of API key if available, else SHA-256 of username.""" - api_key = os.environ.get("MEM0_API_KEY") or os.environ.get("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY") or "" - if api_key: - return hashlib.sha256(api_key.encode()).hexdigest()[:32] - user_id = os.environ.get("MEM0_RESOLVED_USER_ID") or os.environ.get("USER") or "unknown" - return _sha256(user_id) - - -def detect_platform() -> str: - explicit = os.environ.get("MEM0_PLATFORM") - if explicit: - return explicit - if os.environ.get("ANTIGRAVITY_PLUGIN_ROOT"): - return "antigravity" - if os.environ.get("KIMI_PLUGIN_ROOT"): - return "kimi" - if os.environ.get("PLUGIN_ROOT"): - return "codex" - if os.environ.get("CURSOR_PLUGIN_ROOT"): - return "cursor" - if os.environ.get("WINDSURF_PLUGIN_ROOT"): - return "windsurf" - return "plugin" - - -def is_enabled() -> bool: - return os.environ.get("MEM0_TELEMETRY", "true").lower() not in ("false", "0", "no", "off") - - -def build_posthog_payload(event_name: str, properties: dict | None = None) -> dict: - project_id = os.environ.get("MEM0_PROJECT_ID") or "unknown" - plat = detect_platform() - return { - "api_key": POSTHOG_API_KEY, - "distinct_id": _distinct_id(), - "event": event_name, - "properties": { - **(properties or {}), - "source": "plugin", - "platform": plat, - "plugin_version": _load_plugin_version(plat), - "project_hash": _sha256(project_id), - "os": sys.platform, - "os_version": platform.version(), - "sample_rate": SAMPLE_RATE, - "$process_person_profile": False, - "$lib": "posthog-python", - }, - } - - -def send(payload: dict) -> None: - data = json.dumps(payload).encode("utf-8") - req = urllib.request.Request( - POSTHOG_HOST, - data=data, - headers={"Content-Type": "application/json"}, - ) - try: - with urllib.request.urlopen(req, timeout=REQUEST_TIMEOUT): - pass - except Exception: - pass - - -def emit(event_type: str, properties: dict | None = None) -> None: - if not is_enabled(): - return - send(build_posthog_payload(f"plugin.{event_type}", properties)) - - -def main() -> int: - if not is_enabled(): - return 0 - if len(sys.argv) < 2: - return 1 - - event_type = sys.argv[1] - properties: dict = {} - - for arg in sys.argv[2:]: - if arg.startswith("--memory_count="): - try: - properties["memory_count"] = int(arg.split("=", 1)[1]) - except ValueError: - pass - elif arg.startswith("--categories_count="): - try: - properties["categories_count"] = int(arg.split("=", 1)[1]) - except ValueError: - pass - elif arg == "--error_detected": - properties["error_detected"] = True - elif arg == "--file_paths_detected": - properties["file_paths_detected"] = True - elif arg.startswith("--source="): - properties["source_detail"] = arg.split("=", 1)[1] - elif arg.startswith("--tool="): - properties["tool"] = arg.split("=", 1)[1] - elif arg.startswith("--files_count="): - try: - properties["files_count"] = int(arg.split("=", 1)[1]) - except ValueError: - pass - - emit(event_type, properties) - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/integrations/mem0-plugin/skills/context-loader/SKILL.md b/integrations/mem0-plugin/skills/context-loader/SKILL.md deleted file mode 100644 index 25d3a339d..000000000 --- a/integrations/mem0-plugin/skills/context-loader/SKILL.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -name: context-loader -description: Searches and injects relevant memories into context before starting work on a task. Use when beginning a new task, switching context, or when project history, past decisions, or coding conventions need to be loaded. ---- - -# 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: - - | Query angle | Filter | Purpose | - |---|---|---| - | Feature/module name | `{"AND": [{"user_id": ""}, {"app_id": ""}, {"metadata": {"type": "decision"}}]}` | Architecture decisions | - | File paths mentioned | `{"AND": [{"user_id": ""}, {"app_id": ""}, {"metadata": {"type": "convention"}}]}` | Coding patterns | - | Error keywords (if any) | `{"AND": [{"user_id": ""}, {"app_id": ""}, {"metadata": {"type": "anti_pattern"}}]}` | Known pitfalls | - | Broad project context | `{"AND": [{"user_id": ""}, {"app_id": ""}]}` | Catch-all | - -3. **Deduplicate** results by memory ID across all search responses. - -4. **Output compact context block** (max 10 memories): - -``` -context-loader: loaded memories for "" - - [decision] [mem0:] - - [convention] [mem0:] - - [anti_pattern] [mem0:] -``` - -5. If **zero results**: output nothing. Don't announce empty context. - -## Constraints - -- **Read-only** — never modify or delete memories -- **Max 10 memories** returned (most relevant only) -- **Silent on empty** — only surfaces findings if relevant context exists -- Skip memories already visible in current session context diff --git a/integrations/mem0-plugin/skills/dream/SKILL.md b/integrations/mem0-plugin/skills/dream/SKILL.md deleted file mode 100644 index c5319c565..000000000 --- a/integrations/mem0-plugin/skills/dream/SKILL.md +++ /dev/null @@ -1,232 +0,0 @@ ---- -name: dream -description: Consolidates stored memories by merging duplicates, resolving contradictions, and pruning stale entries. Use when memory count is high, search results feel noisy or repetitive, or periodic cleanup is needed to maintain memory quality. ---- - -# Mem0 Dream — Memory Consolidation - -This skill performs a memory consolidation pass: it fetches all project memories, -identifies near-duplicates, flags contradictions, and prunes stale entries based on -configured retention policies. All proposed changes are shown as a diff for user -approval before anything is modified. - -**IMPORTANT: Execute steps strictly in order (1 → 2 → 3 → 4 → 5 → 6). Each step depends on the previous one. Do NOT run steps in parallel or skip ahead.** - -## Step 1: Load Retention Policies - -Determine the active retention policy by running the parser script. Use the -appropriate `PLUGIN_ROOT` variable for the current platform (`${CLAUDE_PLUGIN_ROOT}`, -`${CODEX_PLUGIN_ROOT}`, or `${CURSOR_PLUGIN_ROOT}`): - -```bash -python3 "/scripts/parse_mem0_config.py" "" -``` - -Parse the JSON output (a dict of `category → days | null`). If the script fails -or returns `{}`, fall back to these built-in defaults: - -| `metadata.type` | Default retention | -|---|---| -| `session_state` | 90 days | -| `compact_summary` | 90 days | -| all others | no pruning | - -Store the resolved policies for use in Step 3. - ---- - -## Step 2: Fetch ALL Project Memories - -Call `get_memories` to retrieve every memory for the active project: - -```python -get_memories( - filters={"AND": [{"user_id": ""}, {"app_id": ""}]}, - page_size=200, -) -``` - -If the response indicates more pages exist, paginate until all memories are fetched. -Collect the full list before proceeding. If zero memories are found, print: - -``` -No memories found for project . Nothing to consolidate. -``` - -…and stop. - ---- - -## Step 3: Analyze — Find Issues - -Work entirely in-memory; do not modify anything yet. - -Group memories by `metadata.type` (use `"unknown"` when the field is absent). -For each group, identify the following: - -### 3a. Near-duplicate pairs (merge candidates) - -Two memories are near-duplicates when they express the same fact or decision but -phrased differently (e.g., "Use PostgreSQL for auth" and "Auth DB is PostgreSQL"). - -Heuristics — two memories are near-duplicates if **all** of these hold: -- Similarity threshold: estimated cosine similarity > 0.9 (use noun/keyword overlap as proxy — if >60% of significant nouns overlap, treat as >0.9 similarity). -- Same `metadata.type`. -- Neither memory is pinned (`metadata.pinned != true`). - -For each qualifying pair, draft a merged version that is more complete and specific -than either original. - -### 3b. Contradictions - -Two memories contradict when they assert opposing facts about the same topic -(e.g., "Deploy to ECS" vs. "Deploy to Vercel"). - -Identify the likely winner: the more recent memory with higher confidence wins. -Store both IDs and their content for user review. - -### 3c. Prune candidates - -A memory is a prune candidate when **any** of the following is true: - -1. Its `metadata.type` has a retention policy and the memory is older than the - configured number of days (compare `created_at` to today). -2. Its confidence score is below 0.3 AND it contains no information unique to - this project (no file paths, identifiers, or domain-specific nouns). - -**Always skip memories where `metadata.pinned == true`**, regardless of age or -confidence. - ---- - -## Step 4: Print Diff Report - -Print a structured diff to the terminal before making any changes. Use exactly -this format: - -``` -## dream — consolidation report - -Merges (): - [mem0:] + [mem0:] → "" - -Conflicts (): - [mem0:] vs [mem0:] — "" [A/B/skip] - -Prune (): - [mem0:] — , d old - -Proposed: merges, prunes, conflicts. Apply? [Y/n] -``` - -If there are zero items in any category, omit that section entirely. - -If there are zero total proposals (no merges, no prunes, no conflicts), print: - -``` -Dream complete. No duplicate, contradictory, or stale memories found. -``` - -…and stop. - ---- - -## Step 5: Wait for User Input and Apply - -### 5a. Contradictions - -For each `CONFLICT` pair in the report, wait for the user to type `A`, `B`, or -`skip` (case-insensitive). If they enter nothing (empty), treat as `skip`. - -Record the winner for each pair before proceeding to the final apply confirmation. - -### 5b. Final confirmation - -After all conflict resolutions are collected, prompt: - -``` -Apply? [Y/n] -``` - -If the user types `n` or `no` (case-insensitive), print `Cancelled. No changes made.` -and stop. - -If the user confirms (`Y`, `yes`, or empty / Enter), apply all changes in this order: - -#### Merges - -For each approved merge pair: -1. `delete_memory()` -2. `delete_memory()` -3. `add_memory` with: - - `text=""` - - `user_id=` - - `app_id=` (top-level, not in metadata) - - `metadata={"type": "", "branch": "", "confidence": , "source": "mem0-dream"}` - - `infer=False` - -#### Contradictions (resolved) - -For each resolved conflict where the user chose A or B: -- Delete the loser (the non-chosen memory): `delete_memory(memory_id=)` - -Contradictions where the user chose `skip` are left untouched. - -#### Prunes - -For each prune candidate: -- `delete_memory()` - ---- - -## Step 6: Print Summary - -After all changes are applied, print: - -``` -Dream complete — merged: , pruned: , conflicts resolved: , skipped: -``` - ---- - -## Auto mode - -When invoked with `--auto` (e.g., `/mem0:dream --auto`), run non-interactively: - -- **Merges**: applied automatically (no contradiction, both are compatible). -- **Prunes**: applied automatically (age/confidence-based, no ambiguity). -- **Contradictions**: skipped — they require human judgment. - -### Concurrency guard - -Before doing any work, check for a lock file at `/tmp/mem0_dream_auto.lock`: -- If the lock file exists and is less than 10 minutes old, print `[mem0-dream --auto] Another run in progress — skipping.` and stop. -- Otherwise, create the lock file (write the current timestamp). Delete it when done (in all exit paths). - -### Execution - -In auto mode: -1. Load policies and fetch memories (Steps 1–3) as normal. -2. Apply merges and prunes silently without printing the diff or prompting. -3. Print a compact summary: - ``` - [mem0-dream --auto] project= merged= pruned= conflicts_skipped= - ``` -4. If contradictions were detected but skipped, check if a `mem0-dream-auto` reminder already exists before storing one: - - Search for existing reminders: `search_memories(query="mem0-dream contradictions manual review", filters={"AND": [{"user_id": ""}, {"app_id": ""}, {"metadata": {"source": "mem0-dream-auto"}}]}, top_k=1)` - - If a result exists with similarity > 0.9, skip storing the reminder (one already exists). - - If no match, store the reminder: - ```python - add_memory( - text="mem0-dream detected contradiction(s) requiring manual review. Run /mem0:dream to resolve them interactively.", - user_id="", - app_id="", - metadata={"type": "task_learning", "source": "mem0-dream-auto", "branch": ""}, - infer=False, - ) - ``` - -## See also - -- `/mem0:forget` — targeted deletion of specific memories (search + confirm + delete) -- `/mem0:health --deep` — quick quality scan without applying changes diff --git a/integrations/mem0-plugin/skills/export/SKILL.md b/integrations/mem0-plugin/skills/export/SKILL.md deleted file mode 100644 index 67fb0ae57..000000000 --- a/integrations/mem0-plugin/skills/export/SKILL.md +++ /dev/null @@ -1,76 +0,0 @@ ---- -name: export -description: Exports all project memories to a portable Markdown file for backup or migration. Use when backing up memories, migrating to another project, sharing memory state with teammates, or archiving before cleanup. ---- - -# Mem0 Export - -Export all memories for the current project to a portable Markdown file. - -## Execution - -### Step 1: Resolve identity - -Determine the active identity: -- `user_id` from `MEM0_USER_ID` env var, else `$USER`, else `"default"` -- `project_id` (used as `app_id`) from `MEM0_PROJECT_ID` env var, or via the project resolver - -### Step 2: Fetch all memories - -Call `get_memories` with: -- `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}` -- `page_size=200` - -If the response is paginated (i.e. the result contains a `next` cursor or the count equals `page_size`), continue fetching pages until all memories are retrieved. - -### Step 3: Format each memory as a YAML-frontmatter block - -For each memory record, produce a block in this exact format: - -``` ---- -id: -created_at: -type: -confidence: -branch: -files: -categories: ---- - - -``` - -Notes: -- The `---` delimiters must be on their own lines with no extra whitespace. -- `files` and `categories` are written as comma-separated values on a single line. -- Leave a blank line after the content before the next `---` (for readability). -- If a field is missing or null, write an empty string (not "null"). - -### Step 4: Write the export file - -Determine the output filename: - -``` -mem0-export--.md -``` - -Where `` is today's date in UTC. - -Write all formatted blocks to this file using the Write tool (or equivalent). The file is written to the current working directory. - -### Step 5: Print summary - -``` -Exported memories to -``` - -Where `` is the total number of memory blocks written. - -## Error Handling - -- If `get_memories` returns an error or zero memories, print: - ``` - No memories found for project . Nothing exported. - ``` -- If the write fails, report the error to the user. diff --git a/integrations/mem0-plugin/skills/forget/SKILL.md b/integrations/mem0-plugin/skills/forget/SKILL.md deleted file mode 100644 index 2b32d865f..000000000 --- a/integrations/mem0-plugin/skills/forget/SKILL.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -name: forget -description: Deletes memories by search query or memory ID with confirmation before removal. Use when removing outdated decisions, incorrect memories, sensitive data, or cleaning up after experiments. Also handles undo of recent additions. ---- - -# Mem0 Forget - -Delete specific memories from mem0. - -## Execution - -### Step 1: Parse input - -The user provides either: -- A search query: `/mem0:forget auth module decisions` -- A memory ID: `/mem0:forget ` - -If no argument, ask: "What should I forget? Provide a search query or memory ID." - -### Step 2: Find memories - -**If memory ID provided** (looks like a UUID or hex string): -- Call `get_memory` with the ID to verify it exists. -- Show: `Found: "" (created )` - -**If search query provided:** -- Call `search_memories` with: - - `query=` - - `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}` - - `top_k=10` -- Show numbered list: - ``` - Found memories matching "": - 1. (type: , created: ) [ID: ] - 2. ... - ``` - -### Step 3: Confirm - -Ask: "Delete which memories? Enter numbers (e.g., 1,3,5), 'all', or 'cancel'." - -For a single memory ID, ask: "Delete this memory? [y/N]" - -**Never delete without confirmation.** This is destructive. - -### Step 4: Delete - -For each confirmed memory, call `delete_memory` with the memory ID. - -### Step 5: Report - -``` -Deleted memories. -``` - -If any deletions failed, report which ones and why. - -## Undo recent writes - -If the user says "undo last N memories" or "undo last write": - -1. Read session stats to get recently written memory IDs: - ```bash - SCRIPT_DIR="${CLAUDE_PLUGIN_ROOT:-${CODEX_PLUGIN_ROOT:-${CURSOR_PLUGIN_ROOT:-}}}/scripts" - python3 "$SCRIPT_DIR/session_stats.py" peek - ``` -2. Parse the `recent_ids` array from the JSON output. Each entry has `id`, `category`, `ts`. -3. Show the last N entries (default 1) and ask for confirmation. -4. Delete confirmed entries via `delete_memory`. - -If `recent_ids` is empty, tell the user: "No recent memory IDs tracked this session. Try `/mem0:tour` to browse recent memories, or `/mem0:forget ` to find specific ones." diff --git a/integrations/mem0-plugin/skills/health/SKILL.md b/integrations/mem0-plugin/skills/health/SKILL.md deleted file mode 100644 index 9b5b51a8c..000000000 --- a/integrations/mem0-plugin/skills/health/SKILL.md +++ /dev/null @@ -1,160 +0,0 @@ ---- -name: health -description: Diagnoses mem0 connectivity, API key validity, and memory read/write functionality. Use when memory operations fail, searches return empty, add_memory errors occur, MCP connection drops, or to verify the plugin is working correctly. ---- - -# Mem0 Health Check - -Run a diagnostic check on the mem0 plugin. Useful for troubleshooting. - -## Execution - -Run ALL checks, then display a single summary. Do not stop on the first failure. - -### Check 1: API key - -```bash -_KEY="${MEM0_API_KEY:-${CLAUDE_PLUGIN_OPTION_MEM0_API_KEY:-}}" -[ -n "$_KEY" ] && echo "${_KEY:0:6}..." || echo "NOT_SET" -``` - -- If `NOT_SET`: FAIL — "No API key configured" -- If set: PASS — the command already prints only the first 6 chars - -### Check 2: Identity resolution - -Resolve identity using the plugin's own resolver scripts to match what hooks use: - -```bash -SCRIPT_DIR="${CLAUDE_PLUGIN_ROOT:-${CODEX_PLUGIN_ROOT:-${CURSOR_PLUGIN_ROOT:-}}}/scripts" -source "$SCRIPT_DIR/_identity.sh" 2>/dev/null -echo "user_id=${MEM0_RESOLVED_USER_ID:-}" -echo "project_id=${MEM0_PROJECT_ID:-}" -echo "branch=${MEM0_BRANCH:-}" -``` - -If `CLAUDE_PLUGIN_ROOT` is not available, fall back to: -- `user_id`: from `MEM0_USER_ID` or `$USER` -- `project_id`: from `MEM0_PROJECT_ID` or check `~/.mem0/project_map.json` for `$PWD` -- `branch`: from `git branch --show-current` - -PASS if all three are non-empty. WARN if any falls back to defaults. - -### Check 3: MCP server connectivity - -Call `search_memories` with: -- `query="health check"` -- `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}` -- `top_k=1` - -- If returns successfully (even empty): PASS -- If errors: FAIL — show the error message - -### Check 4: Memory write capability - -Call `add_memory` with: -- `text="Health check probe — safe to delete."` -- `user_id=` -- `app_id=` -- `metadata={"type": "health_check", "probe": true}` -- `infer=False` - -The response returns `event_id` (v3 writes are async). Call `get_event_status(event_id=)` to check processing. - -- If status is `SUCCEEDED`: PASS — extract the memory ID from the event result, then call `delete_memory` with that ID to clean up. -- If status is `PENDING` after 5 seconds: PASS (write accepted, processing delayed) -- If errors: FAIL — show the error. - -### Check 5: Session stats tracker - -Check if the session stats file exists and is readable: - -```bash -STATS_FILE="/tmp/mem0_session_stats_${USER}.json" -if [ -f "$STATS_FILE" ] && python3 -c "import json; json.load(open('$STATS_FILE'))" 2>/dev/null; then - echo "OK" -else - echo "FAIL" -fi -``` - -This file is created by the SessionStart hook and updated by PostToolUse hooks throughout the session. If it doesn't exist, the session hooks may not have fired yet — try sending a message first, then recheck. - -### Display - -``` -## mem0 health - -PASS API Key m0-dVe... -PASS Identity user=kartik, project=mem0, branch=main -PASS MCP Connection 142ms -PASS Write/Read write + delete OK -PASS Session Tracker stats file active - -All checks passed. -``` - -If any check fails, add a `## Troubleshooting` section with specific fix steps for each failure. - -## Extended mode: Memory Quality Analysis - -When invoked with `--deep` (e.g., `/mem0:health --deep`), run the standard 5 checks above **plus** a memory quality scan. - -### Quality Check 1: Duplicates - -Call `get_memories` with `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `page_size=200`. Compare all pairs within the same `metadata.type` group for high textual overlap (shared nouns/keywords > 60%). Report: - -``` -Potential duplicates: pairs - [mem0:] ≈ [mem0:] — both about "" -``` - -### Quality Check 2: Stale memories - -Flag memories where: -- `metadata.type` is `session_state` or `compact_summary` AND older than 90 days -- `metadata.confidence` < 0.3 AND older than 30 days - -``` -Stale candidates: - [mem0:] — session_state, 142d old -``` - -### Quality Check 2b: Low-confidence memories - -Flag memories where `metadata.confidence` < 0.5 (regardless of age). Report separately from stale: - -``` -Low-confidence memories: - [mem0:] — confidence=0.3, "" -``` - -### Quality Check 3: Contradictions - -Within each `metadata.type` group, flag pairs that assert opposing facts about the same topic. Use semantic judgment — look for negation patterns, conflicting tool/framework choices, or reversed decisions. - -``` -Possible contradictions: - [mem0:] vs [mem0:] — conflicting on "" -``` - -### Quality Check 4: Orphan memories - -Memories with no `metadata.type` set, or with `metadata.type` not in the 17 known coding categories. These were likely written without proper tagging. - -``` -Untagged/orphan memories: -``` - -### Quality summary - -``` -## Memory Quality - -Duplicates: · Stale: · Contradictions: · Orphans: -``` - -If all counts are 0: `Memory quality: clean.` -If any non-zero: append `Run /mem0:dream to fix.` - -To fix issues found by `--deep`, run `/mem0:dream` for automated consolidation (merges, prunes, conflict resolution). diff --git a/integrations/mem0-plugin/skills/import/SKILL.md b/integrations/mem0-plugin/skills/import/SKILL.md deleted file mode 100644 index 7e6c657fd..000000000 --- a/integrations/mem0-plugin/skills/import/SKILL.md +++ /dev/null @@ -1,177 +0,0 @@ ---- -name: import -description: Imports memories from an exported Markdown file or MEMORY.md into the current project. Use when migrating from another project, restoring from backup, importing Claude Code native MEMORY.md content, or setting up a new project with existing knowledge. ---- - -# Mem0 Import - -Import memories from a mem0 export file into the current project. - -## Execution - -### Step 1: Determine the export file to import - -If the user provided a filename as an argument to `/mem0:import `, use that file. - -Otherwise, list `.md` files in the current directory whose names contain `mem0-export`: - -```bash -ls -1 *.md 2>/dev/null | grep mem0-export || echo "No export files found" -``` - -If multiple files are found, ask the user which one to import. If none are found, print: -``` -No mem0-export files found in the current directory. -Run /mem0:export first, or provide the filename: /mem0:import -``` - -### Step 2: Parse the export file - -Determine the plugin root. Use the appropriate variable for the current platform: -- Claude Code: `${CLAUDE_PLUGIN_ROOT}` -- Codex: `${CODEX_PLUGIN_ROOT}` -- Cursor: `${CURSOR_PLUGIN_ROOT}` - -Run the parser script to extract memory records as JSON: - -```bash -python3 "/scripts/parse_export_file.py" "" -``` - -This outputs a JSON array where each element has: -- `id` — original memory ID (for reference only; a new ID will be assigned on import) -- `type` — metadata type -- `confidence` — metadata confidence value -- `branch` — metadata branch -- `files` — list of associated files -- `categories` — list of categories -- `content` — the memory text - -If the script fails or outputs `[]`, print: -``` -Failed to parse or file contains no valid memory blocks. -``` -and stop. - -### Step 3: Resolve identity - -Determine the active identity: -- `user_id` from `MEM0_USER_ID` env var, else `$USER`, else `"default"` -- `project_id` (used as `app_id`) from `MEM0_PROJECT_ID` env var, or via the project resolver - -### Step 4: Import each memory - -For each record in the parsed JSON array, call `add_memory` with: - -- `text=""` -- `user_id=` -- `app_id=` -- `metadata={` - - `"type": ""` (if non-empty) - - `"confidence": ""` (if non-empty) - - `"branch": ""` (if non-empty) - - `"files": ` (the list, if non-empty) - - `"source": "import"` - - `}` -- `infer=False` - -Notes: -- Do NOT pass the original `id` — the platform assigns a new ID. -- Skip records where `content` is empty (the parser already filters these, but be defensive). -- Continue importing even if individual records fail; track the count of successes. - -### Step 5: Print results - -``` -Imported memories into project -``` - -Where `` is the number of successfully imported memories. - -If any failed: -``` -Imported / memories into project ( failed) -``` - -## Importing from competing AI tools (`--tools`) - -When invoked with `--tools` (e.g., `/mem0:import --tools`), detect and import -from competing AI tool configuration files: - -### Supported tools - -| Tool | File/directory | -|------|---------------| -| Cursor | `.cursorrules` | -| GitHub Copilot | `.github/copilot-instructions.md` | -| Cline | `memory-bank/` (directory of `.md` files) | -| Continue | `.continue/rules.md` | - -### T1: Detect - -```bash -test -f .cursorrules && echo "cursor: .cursorrules" -test -f .github/copilot-instructions.md && echo "copilot: .github/copilot-instructions.md" -test -d memory-bank/ && echo "cline: memory-bank/" -test -f .continue/rules.md && echo "continue: .continue/rules.md" -``` - -### T2: Ask user - -List found files, ask which to import (numbers, comma-separated, or "all"). -If none found: -``` -No competing tool configuration files found. -Checked: .cursorrules, .github/copilot-instructions.md, memory-bank/, .continue/rules.md -``` - -### T3: Run import - -For each selected tool: -```bash -python3 "/scripts/import_competing_tools.py" --path -``` - -Tools: `cursorrules`, `copilot`, `cline`, `continue`. - -### T4: Report - -``` -Imported memories into (cursor: , copilot: ) -``` - -Notes: `infer=False`, tagged `metadata.source=-import`, sections <50 chars -skipped, chunks >10k chars truncated, safe to re-run (deduplication handles it). - ---- - -## Importing Claude Code's native MEMORY.md - -When invoked with a path to Claude Code's native `MEMORY.md` file (typically -`~/.claude/projects//memory/MEMORY.md`), or when `on_session_start.sh` -detects native auto-memory and the user chooses to import: - -1. Read the file. It contains newline-separated memory entries (one fact per line, - sometimes with `- ` bullet prefix). -2. Split by non-empty lines. Each line becomes one memory. -3. Skip lines shorter than 20 characters or lines that are just headers (`#`). -4. For each line, call `add_memory` with: - - `text=""` - - `user_id=` - - `app_id=` - - `metadata={"type": "task_learning", "source": "memory-md-import", "confidence": 0.8}` - - `infer=False` -5. Report: `Imported memories from MEMORY.md into project ` -6. Suggest disabling native auto-memory: - ``` - To avoid duplicate memory systems, add to ~/.claude/settings.json: - "autoMemoryEnabled": false - ``` - -This handles the cold-start gap when a user has been using Claude Code's native -memory and switches to mem0. - -## Error Handling - -- If the parser script is not found at `/scripts/parse_export_file.py`, print an error and stop. -- If `add_memory` calls fail consistently (e.g. auth error), report the issue and stop early. diff --git a/integrations/mem0-plugin/skills/list-projects/SKILL.md b/integrations/mem0-plugin/skills/list-projects/SKILL.md deleted file mode 100644 index 8cdbfee71..000000000 --- a/integrations/mem0-plugin/skills/list-projects/SKILL.md +++ /dev/null @@ -1,60 +0,0 @@ ---- -name: list-projects -description: Lists all projects with stored memories for the current user, showing memory counts and last activity dates. Use when checking which projects have memories, comparing memory distribution across repos, or finding a specific project scope. ---- - -# Mem0 List Projects - -Show all known project scopes for the current user. - -## Execution - -### Step 1: Fetch memories to discover app_ids - -There is no dedicated "list projects" API endpoint. Discover projects by fetching -the user's memories across all scopes. - -**Important:** A filter with only `user_id` triggers implicit null scoping — it -excludes memories that have a non-null `app_id`. Run two queries and merge: - -1. **Null-scoped:** `get_memories` with `filters={"AND": [{"user_id": ""}]}`, `page_size=200` - — catches memories without `app_id` -2. **App-scoped:** `get_memories` with `filters={"AND": [{"user_id": ""}, {"app_id": {"exists": true}}]}`, `page_size=200` - — catches memories with any `app_id` - -Run both calls in parallel. Merge results, deduplicate by memory `id`. - -If either response indicates more pages, paginate (up to 1000 total). - -### Step 2: Extract distinct projects - -For each memory, determine project by: -1. Top-level `app_id` field (preferred) -2. `metadata.project_id` (legacy memories) -3. `metadata.project` (oldest format) -4. `"(unscoped)"` if none found - -Group by resolved project name. For each project, count: -- Total memories -- Most recent `created_at` date -- Top 3 `metadata.type` values by frequency - -### Step 3: Display - -``` -## mem0 projects - - memories (last: ) ← current - memories (last: ) - - projects, total memories -``` - -Mark current project with `← current`. Sort by memory count descending. - -### Step 4: Empty state - -If zero memories found: -``` -No projects found. Run /mem0:onboard to get started. -``` diff --git a/integrations/mem0-plugin/skills/mem0/LICENSE b/integrations/mem0-plugin/skills/mem0/LICENSE deleted file mode 100644 index 78c99ae28..000000000 --- a/integrations/mem0-plugin/skills/mem0/LICENSE +++ /dev/null @@ -1,189 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but not - limited to compiled object code, generated documentation, and - conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work. - - "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 the 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 the 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 any 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 - - Copyright 2024 Mem0.ai - - 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. diff --git a/integrations/mem0-plugin/skills/mem0/README.md b/integrations/mem0-plugin/skills/mem0/README.md deleted file mode 100644 index 4ed29d162..000000000 --- a/integrations/mem0-plugin/skills/mem0/README.md +++ /dev/null @@ -1,73 +0,0 @@ -# Mem0 Skill for Claude - -Add persistent memory to any AI application in minutes using [Mem0 Platform](https://app.mem0.ai?utm_source=oss&utm_medium=mem0-plugin-skill-readme). - -## What This Skill Does - -When installed, Claude can: - -- **Set up Mem0** in your Python or TypeScript project -- **Integrate memory** into your existing AI app (LangChain, CrewAI, Vercel AI, OpenAI Agents, LangGraph, LlamaIndex, etc.) -- **Generate working code** using real API references and tested patterns -- **Search live docs** on demand for the latest Mem0 documentation - -## Installation - -This skill is included automatically when you install the Mem0 plugin: - -``` -/plugin marketplace add mem0ai/mem0 -/plugin install mem0@mem0-plugins -``` - -See the [plugin README](../../README.md) for full setup instructions. - -### Prerequisites - -- A Mem0 Platform API key ([Get one here](https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=mem0-plugin-skill-readme)) -- Python 3.10+ or Node.js 18+ -- Set the environment variable: - - ```bash - export MEM0_API_KEY="m0-your-api-key" - ``` - -## Quick Start - -After installing, just ask Claude: - -- "Set up mem0 in my project" -- "Add memory to my chatbot" -- "Help me search user memories with filters" -- "Integrate mem0 with my LangChain app" -- "Add graph memory to track entity relationships" - -## What's Inside - -```text -skills/mem0/ -├── SKILL.md # Skill definition and instructions -├── README.md # This file -├── LICENSE # Apache-2.0 -├── scripts/ -│ └── mem0_doc_search.py # Search live Mem0 docs on demand -└── references/ # Documentation (loaded on demand) - ├── quickstart.md # Full quickstart (Python, TS, cURL) - ├── sdk-guide.md # All SDK methods (Python + TypeScript) - ├── api-reference.md # REST endpoints, filters, memory object - ├── architecture.md # Processing pipeline, lifecycle, scoping, performance - ├── features.md # Retrieval, graph, categories, MCP, webhooks, multimodal - ├── integration-patterns.md # LangChain, CrewAI, Vercel AI, LangGraph, LlamaIndex, etc. - └── use-cases.md # 7 real-world patterns with Python + TypeScript code -``` - -## Links - -- [Mem0 Platform Dashboard](https://app.mem0.ai?utm_source=oss&utm_medium=mem0-plugin-skill-readme) -- [Mem0 Documentation](https://docs.mem0.ai) -- [Mem0 GitHub](https://github.com/mem0ai/mem0) -- [API Reference](https://docs.mem0.ai/api-reference) - -## License - -Apache-2.0 diff --git a/integrations/mem0-plugin/skills/mem0/SKILL.md b/integrations/mem0-plugin/skills/mem0/SKILL.md deleted file mode 100644 index 24cd827f2..000000000 --- a/integrations/mem0-plugin/skills/mem0/SKILL.md +++ /dev/null @@ -1,187 +0,0 @@ ---- -name: mem0 -description: Mem0 SDK reference covering Python and TypeScript APIs, memory client methods, configuration, and framework integrations. Use when writing code that calls mem0 APIs, configuring memory providers, or integrating mem0 into an application. -license: Apache-2.0 -metadata: - author: mem0ai - version: "0.1.1" - category: ai-memory - tags: "memory, personalization, ai, python, typescript, vector-search" -compatibility: Requires Python 3.10+ or Node.js 18+, pip install mem0ai or npm install mem0ai, MEM0_API_KEY env var (Platform), and internet access to api.mem0.ai. Uses Mem0 v3 API. ---- - -# Mem0 Platform Integration - -> **Skill Graph:** This skill is part of the Mem0 skill graph: -> - **mem0** (this skill) -- Platform Client SDK + OSS (Python + TypeScript) -> - **[mem0-vercel-ai-sdk](https://github.com/mem0ai/mem0/tree/main/skills/mem0-vercel-ai-sdk)** -- Vercel AI SDK provider - -Mem0 is a managed memory layer for AI applications. It stores, retrieves, and manages user memories via API — no infrastructure to deploy. For self-hosted usage, see the OSS section in the client references below. - -## Step 1: Install and authenticate - -**Python:** -```bash -pip install mem0ai -export MEM0_API_KEY="m0-your-api-key" -``` - -**TypeScript/JavaScript:** -```bash -npm install mem0ai -export MEM0_API_KEY="m0-your-api-key" -``` - -Get an API key at: https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=mem0-plugin-skill - -> **Don't have a `MEM0_API_KEY`?** Sign up at https://app.mem0.ai and create one from the dashboard. Keys start with `m0-`. - -## Step 2: Initialize the client - -**Python:** -```python -from mem0 import MemoryClient -client = MemoryClient(api_key="m0-xxx") -``` - -**TypeScript:** -```typescript -import MemoryClient from 'mem0ai'; -const client = new MemoryClient({ apiKey: 'm0-xxx' }); -``` - -For async Python, use `AsyncMemoryClient`. - -## Step 3: Core operations - -Every Mem0 integration follows the same pattern: **retrieve → generate → store**. - -### Add memories -```python -messages = [ - {"role": "user", "content": "I'm a vegetarian and allergic to nuts."}, - {"role": "assistant", "content": "Got it! I'll remember that."} -] -client.add(messages, user_id="alice") -``` - -### Search memories -```python -results = client.search("dietary preferences", filters={"user_id": "alice"}) -for mem in results.get("results", []): - print(mem["memory"]) -``` - -### Get all memories -```python -all_memories = client.get_all(filters={"user_id": "alice"}) -``` - -### Update a memory -```python -client.update("memory-uuid", text="Updated: vegetarian, nut allergy, prefers organic") -``` - -### Delete a memory -```python -client.delete("memory-uuid") -client.delete_all(user_id="alice") # delete all for a user -``` - -## Common integration pattern - -```python -from mem0 import MemoryClient -from openai import OpenAI - -mem0 = MemoryClient() -openai = OpenAI() - -def chat(user_input: str, user_id: str) -> str: - # 1. Retrieve relevant memories - memories = mem0.search(user_input, filters={"user_id": user_id}) - context = "\n".join([m["memory"] for m in memories.get("results", [])]) - - # 2. Generate response with memory context - response = openai.chat.completions.create( - model="gpt-5-mini", - messages=[ - {"role": "system", "content": f"User context:\n{context}"}, - {"role": "user", "content": user_input}, - ] - ) - reply = response.choices[0].message.content - - # 3. Store interaction for future context - mem0.add( - [{"role": "user", "content": user_input}, {"role": "assistant", "content": reply}], - user_id=user_id - ) - return reply -``` - -## Common edge cases - -- **Search returns empty:** v3 processes `add()` asynchronously — returns an event ID immediately. Wait 2-3s before searching. Also verify `user_id` matches exactly (case-sensitive) and use `filters={"user_id": "..."}` syntax. -- **AND filter with user_id + agent_id returns empty:** Entities are stored separately. `{"AND": [{"user_id": "alice"}, {"agent_id": "bot"}]}` returns nothing. Use `OR` instead, or query each separately. -- **Duplicate memories:** Don't mix `infer=True` (default) and `infer=False` for the same data. `infer=True` extracts facts via LLM with dedup. `infer=False` stores raw — same text can be stored twice. -- **Implicit null scoping:** `filters={"user_id": "alice"}` only returns memories where `agent_id`, `app_id`, `run_id` are ALL null. Wrap in `{"OR": [...]}` to include memories with non-null scoping fields. -- **Platform vs OSS imports:** Platform: `from mem0 import MemoryClient`. OSS: `from mem0 import Memory`. Don't mix them — `MemoryClient` talks to `api.mem0.ai`, `Memory` runs locally. -- **v3 defaults:** `top_k=20`, `threshold=0.1`, `rerank=False`. Adjust as needed. - -## v3 API (Current) - -Mem0 v3 uses single-pass extraction, entity linking, and multi-signal retrieval. - -**Key v3 changes from v2:** -- **Endpoints:** `POST /v3/memories/add/`, `POST /v3/memories/search/`, `POST /v3/memories/` (paginated list) -- **Extraction:** Single ADD-only pass — no more UPDATE/DELETE operations during extraction. Memories accumulate rather than consolidate. -- **Entity linking:** Replaces graph memory. Auto-extracted during `add()`, no config needed. Remove `enable_graph` and `graph_store` from any old config. -- **Defaults:** `top_k=20`, `threshold=0.1`, `rerank=False` -- **Removed params:** `org_id`, `project_id`, `enable_graph` — all removed from SDK -- **TypeScript:** Exclusively camelCase (`userId`, `agentId`, `appId`, `topK`) -- **Add response:** Async — returns event ID immediately, poll via `GET /v1/event/{event_id}/` - -See the [migration guide](https://docs.mem0.ai/migration/platform-v2-to-v3) for details. - -## Live documentation search - -For the latest docs beyond what's in the references, use the doc search tool: - -```bash -python ${CLAUDE_SKILL_DIR}/scripts/mem0_doc_search.py --query "topic" -python ${CLAUDE_SKILL_DIR}/scripts/mem0_doc_search.py --page "/platform/features/graph-memory" -python ${CLAUDE_SKILL_DIR}/scripts/mem0_doc_search.py --index -``` - -No API key needed — searches docs.mem0.ai directly. - -## Client SDK References - -Language-specific deep references (Platform + OSS): - -| Language | File | -|----------|------| -| Python (MemoryClient + AsyncMemoryClient + Memory OSS) | [client/python.md](client/python.md) | -| TypeScript/Node.js (MemoryClient + Memory OSS) | [client/node.md](client/node.md) | -| Python vs TypeScript differences | [client/differences.md](client/differences.md) | - -## Platform References - -Load these on demand for deeper detail: - -| Topic | File | -|-------|------| -| Quickstart (Python, TS, cURL) | [references/quickstart.md](references/quickstart.md) | -| SDK guide (all methods, both languages) | [references/sdk-guide.md](references/sdk-guide.md) | -| API reference (endpoints, filters, object schema) | [references/api-reference.md](references/api-reference.md) | -| Architecture (pipeline, lifecycle, scoping, performance) | [references/architecture.md](references/architecture.md) | -| Platform features (retrieval, graph, categories, MCP, etc.) | [references/features.md](references/features.md) | -| Framework integrations (LangChain, CrewAI, OpenAI Agents, etc.) | [references/integration-patterns.md](references/integration-patterns.md) | -| Use cases & examples (real-world patterns with code) | [references/use-cases.md](references/use-cases.md) | - -## Related Mem0 Skills - -| Skill | When to use | Link | -|-------|-------------|------| -| mem0-vercel-ai-sdk | Vercel AI SDK provider with automatic memory | [GitHub](https://github.com/mem0ai/mem0/tree/main/skills/mem0-vercel-ai-sdk) | diff --git a/integrations/mem0-plugin/skills/mem0/client/differences.md b/integrations/mem0-plugin/skills/mem0/client/differences.md deleted file mode 100644 index e5e80e250..000000000 --- a/integrations/mem0-plugin/skills/mem0/client/differences.md +++ /dev/null @@ -1,129 +0,0 @@ -# Python vs TypeScript SDK Differences - -Quick-reference cheatsheet for developers working across both Mem0 SDKs. - -## Constructor - -| Aspect | Python | TypeScript | -|--------|--------|------------| -| Import (Platform) | `from mem0 import MemoryClient` | `import MemoryClient from 'mem0ai'` | -| Import (OSS) | `from mem0 import Memory` | `import { Memory } from 'mem0ai/oss'` | -| Constructor | `MemoryClient(api_key="m0-xxx")` | `new MemoryClient({ apiKey: 'm0-xxx' })` | -| Required param | `api_key` (positional or kwarg) | `apiKey` (in options object) | - -Both read from `MEM0_API_KEY` env var if no key provided. - -## Method Naming - -| Operation | Python | TypeScript | -|-----------|--------|------------| -| Add | `add()` | `add()` | -| Search | `search()` | `search()` | -| Get | `get()` | `get()` | -| Get all | `get_all()` | `getAll()` | -| Update | `update()` | `update()` | -| Delete | `delete()` | `delete()` | -| Delete all | `delete_all()` | `deleteAll()` | -| History | `history()` | `history()` | -| Batch update | `batch_update()` | `batchUpdate()` | -| Batch delete | `batch_delete()` | `batchDelete()` | -| List users | `users()` | `users()` | -| Delete users | `delete_users()` | `deleteUsers()` | -| Get project | `project.get()` | `getProject()` | -| Update project | `project.update()` | `updateProject()` | -| Create webhook | `create_webhook()` | `createWebhook()` | -| Get webhooks | `get_webhooks()` | `getWebhooks()` | -| Update webhook | `update_webhook()` | `updateWebhook()` | -| Delete webhook | `delete_webhook()` | `deleteWebhook()` | -| Create export | `create_memory_export()` | `createMemoryExport()` | -| Get export | `get_memory_export()` | `getMemoryExport()` | -| Feedback | `feedback()` | `feedback()` | - -**Rule:** Python uses `snake_case`, TypeScript uses `camelCase` for method names. - -## Parameter Passing - -```python -# Python: kwargs -client.add(messages, user_id="alice", metadata={"source": "chat"}) -client.search("query", filters={"user_id": "alice"}, top_k=5, rerank=True) -``` - -```typescript -// TypeScript: options object with camelCase for top-level params, snake_case for filter keys -await client.add(messages, { userId: 'alice', metadata: { source: 'chat' } }); -await client.search('query', { filters: { user_id: 'alice' }, topK: 5, rerank: true }); -``` - -**v3:** Python uses `snake_case` everywhere. TypeScript uses `camelCase` for top-level params (`userId`, `topK`) but `snake_case` for filter keys (`user_id`, `agent_id`). - -## Architectural Differences - -| Aspect | Python | TypeScript | -|--------|--------|------------| -| HTTP library | httpx | axios | -| Default timeout | 300s | 60s | -| Sync support | Yes (`MemoryClient`) | No (all async) | -| Async support | Yes (`AsyncMemoryClient`) | All methods are async | -| Project management | `client.project.*` (separate class) | `client.getProject()` / `client.updateProject()` | -| Context manager | `async with AsyncMemoryClient()` | Not supported | - -## Platform Features: Python-only - -These methods exist in Python but not TypeScript: - -| Method | Description | -|--------|-------------| -| `get_summary(filters)` | Get summary of memories | -| `reset()` | Delete ALL data (users + memories) | -| `project.create(name)` | Create a new project | -| `project.delete()` | Delete current project | -| `project.get_members()` | List project members | -| `project.add_member(email, role)` | Add member to project | -| `project.update_member(email, role)` | Change member role | -| `project.remove_member(email)` | Remove member | - -## Platform Features: TypeScript-only - -| Method | Description | -|--------|-------------| -| `deleteUser(data)` | Convenience method for single entity deletion | -| `ping()` | Health check endpoint | - -## OSS Config Naming - -| Python config key | TypeScript config key | -|-------------------|----------------------| -| `vector_store` | `vectorStore` | -| `history_db_path` | `historyDbPath` | -| `custom_instructions` | `customInstructions` | - -## OSS Scope Parameter Naming - -| Python | TypeScript | -|--------|------------| -| `user_id="alice"` | `userId: 'alice'` | -| `agent_id="bot"` | `agentId: 'bot'` | -| `run_id="session"` | `runId: 'session'` | - -## Entity ID Passing (v3) - -| Method | Python | TypeScript | -|--------|--------|------------| -| add() | Top-level: `user_id="alice"` | Top-level: `{ userId: 'alice' }` | -| search() | In filters: `filters={"user_id": "alice"}` | In filters: `{ filters: { user_id: 'alice' } }` | -| get_all() | In filters: `filters={"user_id": "alice"}` | In filters: `{ filters: { user_id: 'alice' } }` | - -## Common Gotcha - -When searching/filtering, both Python and TypeScript use `snake_case` for filter keys. TypeScript only uses `camelCase` for top-level method parameters: - -```python -# Python - snake_case in filters -results = client.search("query", filters={"user_id": "alice"}) -``` - -```typescript -// TypeScript - snake_case in filters, camelCase for top-level params -const results = await client.search('query', { filters: { user_id: 'alice' }, topK: 20 }); -``` diff --git a/integrations/mem0-plugin/skills/mem0/client/node.md b/integrations/mem0-plugin/skills/mem0/client/node.md deleted file mode 100644 index ca85ba7ba..000000000 --- a/integrations/mem0-plugin/skills/mem0/client/node.md +++ /dev/null @@ -1,418 +0,0 @@ -# Mem0 Node.js / TypeScript SDK Reference - -Complete reference for the `mem0ai` npm package. Covers both the Platform client (managed API) and the Open Source self-hosted variant. - ---- - -## Platform Client - -### Installation - -```bash -npm install mem0ai -export MEM0_API_KEY="m0-your-api-key" -``` - -### MemoryClient - -```typescript -import MemoryClient from 'mem0ai'; - -const client = new MemoryClient({ apiKey: 'm0-xxx' }); -``` - -**Constructor:** `new MemoryClient({ apiKey })`. If `apiKey` is not provided, reads from `MEM0_API_KEY` environment variable. - -- HTTP library: `axios` -- Timeout: 60 seconds -- Base URL: `https://api.mem0.ai` -- All methods are async (return `Promise`) - ---- - -### Memory Methods - -#### add(messages, options?) - -Store new memories from messages. - -```typescript -const messages = [ - { role: 'user', content: "I'm a vegetarian and allergic to nuts." }, - { role: 'assistant', content: "Got it! I'll remember that." }, -]; -await client.add(messages, { userId: 'alice' }); -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `messages` | `Message[]` | Array of `{role, content}` objects | -| `options.userId` | string | User identifier | -| `options.agentId` | string | Agent identifier | -| `options.appId` | string | Application identifier | -| `options.runId` | string | Session identifier | -| `options.metadata` | object | Custom key-value pairs | -| `options.infer` | boolean | If false, store raw text (default: true) | - -**Returns:** `Promise` -- list of events - -#### search(query, options?) - -Search memories by semantic similarity. - -```typescript -const results = await client.search('dietary preferences', { filters: { user_id: 'alice' }, topK: 20 }); -for (const mem of results.results) { - console.log(mem.memory, mem.score); -} -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `query` | string | Natural language search query | -| `options.filters` | object | Filter object with entity IDs (`user_id`, `agent_id`, etc.) and/or `AND`/`OR`/`NOT` conditions | -| `options.topK` | number | Number of results (default: 20) | -| `options.rerank` | boolean | Enable semantic reranking (default: false) | -| `options.threshold` | number | Minimum similarity (default: 0.1) | - -**Returns:** `Promise` -- `{results: [{id, memory, score, ...}]}` - -#### get(memoryId) - -```typescript -const memory = await client.get('ea925981-...'); -``` - -#### getAll(options?) - -Retrieve all memories. Requires at least one entity identifier in filters. - -```typescript -const memories = await client.getAll({ filters: { user_id: 'alice' } }); -// With filters -const filtered = await client.getAll({ - filters: { AND: [{ user_id: 'alice' }, { categories: { contains: 'health' } }] }, -}); -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `options.filters` | object | Filter object with entity IDs (`user_id`, `agent_id`, etc.) and/or `AND`/`OR`/`NOT` conditions | -| `options.page` | number | Page number | -| `options.pageSize` | number | Results per page | - -#### update(memoryId, data) - -```typescript -await client.update('ea925981-...', { text: 'Updated: vegan since 2024' }); -await client.update('ea925981-...', { text: 'Updated', metadata: { verified: true } }); -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `memoryId` | string | Memory ID | -| `data.text` | string | New content | -| `data.metadata` | object | New metadata | -| `data.timestamp` | string | New timestamp | - -#### delete(memoryId) - -```typescript -await client.delete('ea925981-...'); -``` - -#### deleteAll(options?) - -```typescript -await client.deleteAll({ userId: 'alice' }); -``` - -#### history(memoryId) - -```typescript -const history = await client.history('ea925981-...'); -// Returns: [{previousValue, newValue, action, timestamps}] -``` - ---- - -### Batch Methods - -#### batchUpdate(memories) - -```typescript -await client.batchUpdate([ - { memoryId: 'uuid-1', text: 'Updated text' }, - { memoryId: 'uuid-2', text: 'Another update' }, -]); -``` - -#### batchDelete(memories) - -```typescript -await client.batchDelete(['uuid-1', 'uuid-2', 'uuid-3']); -``` - ---- - -### User/Entity Management - -#### users() - -```typescript -const users = await client.users(); -// Returns: {results: [{type: "user", name: "alice"}, ...]} -``` - -#### deleteUser(data) / deleteUsers(data) - -```typescript -await client.deleteUser({ userId: 'alice' }); // Single entity -await client.deleteUsers({ agentId: 'bot-1' }); // Flexible -``` - ---- - -### Project Management - -```typescript -// Get project config -const config = await client.getProject({ fields: ['customCategories'] }); - -// Update project settings -await client.updateProject({ - customInstructions: 'Extract dietary preferences and health info', - customCategories: [{ health: 'Medical and dietary info' }], -}); -``` - ---- - -### Webhooks - -```typescript -// List -const webhooks = await client.getWebhooks({ projectId: 'proj_123' }); - -// Create -const webhook = await client.createWebhook({ - url: 'https://your-app.com/webhook', - name: 'Memory Logger', - projectId: 'proj_123', - eventTypes: ['memory_add', 'memory_update'], -}); - -// Update -await client.updateWebhook({ - webhookId: 'wh_123', - name: 'Updated Logger', - url: 'https://new-url.com', -}); - -// Delete -await client.deleteWebhook({ webhookId: 'wh_123' }); -``` - ---- - -### Feedback - -```typescript -await client.feedback({ - memoryId: 'mem-123', - feedback: 'POSITIVE', - feedbackReason: 'Accurately captured preference', -}); -``` - ---- - -### Export - -```typescript -const exportReq = await client.createMemoryExport({ - schema: JSON.stringify({ type: 'object', properties: { name: { type: 'string' } } }), - filters: { user_id: 'alice' }, -}); - -const result = await client.getMemoryExport({ memoryExportId: exportReq.id }); -``` - ---- - -### TypeScript Types - -Key interfaces from `mem0.types.ts`: - -```typescript -interface Message { role: string; content: string; } -interface Memory { id: string; memory: string; userId: string; categories: string[]; score?: number; /* ... */ } -interface MemoryOptions { userId?: string; agentId?: string; appId?: string; runId?: string; metadata?: object; /* ... */ } -interface SearchOptions { filters?: object; topK?: number; rerank?: boolean; threshold?: number; /* ... */ } -interface MemoryHistory { id: string; memoryId: string; previousValue: string; newValue: string; action: string; /* ... */ } -interface FeedbackPayload { memoryId: string; feedback: string; feedbackReason?: string; } -interface WebhookCreatePayload { url: string; name: string; projectId: string; eventTypes: string[]; } -``` - ---- - -## Open Source / Self-Hosted - -### Installation - -```bash -npm install mem0ai -``` - -### Memory Class - -```typescript -import { Memory } from 'mem0ai/oss'; - -const m = new Memory(); // Uses default config -``` - -**Import:** `from 'mem0ai/oss'` (NOT the default export -- that is `MemoryClient` for Platform) - -### Configuration - -```typescript -const config = { - llm: { - provider: 'openai', // openai, groq, anthropic, google, ollama, lmstudio, mistral, azure - config: { - model: 'gpt-5-mini', - apiKey: 'sk-xxx', - }, - }, - embedder: { - provider: 'openai', // openai, ollama, lmstudio, google, azure, langchain, anthropic - config: { - model: 'text-embedding-3-small', - apiKey: 'sk-xxx', - }, - }, - vectorStore: { - provider: 'qdrant', // memory, qdrant, redis, supabase, langchain, azure_ai_search, pgvector - config: { - collectionName: 'my_memories', - host: 'localhost', - port: 6333, - }, - }, - historyDbPath: 'history.db', - customInstructions: '...', - disableHistory: false, -}; - -const m = new Memory(config); -// Or from dict with validation: -const m2 = Memory.fromConfig(config); -``` - -### Methods - -All methods are async (return `Promise`): - -#### add(messages, config) - -```typescript -await m.add('I prefer dark mode', { userId: 'alice' }); -await m.add([ - { role: 'user', content: 'I like hiking' }, - { role: 'assistant', content: 'Great outdoor activity!' }, -], { userId: 'alice' }); -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `messages` | `string \| Message[]` | Content to store | -| `config.userId` | string | User identifier (at least one scope required) | -| `config.agentId` | string | Agent identifier | -| `config.runId` | string | Session identifier | -| `config.metadata` | object | Custom key-value pairs | -| `config.filters` | object | Additional filters | -| `config.infer` | boolean | LLM inference (default: true) | - -**Returns:** `Promise<{results: [...], relations?: [...]}>` - -#### search(query, config) - -```typescript -const results = await m.search('dietary preferences', { filters: { user_id: 'alice' }, topK: 5 }); -``` - -| Parameter | Type | Description | -|-----------|------|-------------| -| `query` | string | Search query | -| `config.filters` | object | Filter object with entity IDs (`user_id`, `agent_id`, `run_id`, etc.) | -| `config.topK` | number | Max results (default: 20) | - -#### get(memoryId) / getAll(config) / update(memoryId, data) / delete(memoryId) / deleteAll(config) / history(memoryId) - -Same interface patterns. Note: OSS `update` takes a string for data, not an object. - -```typescript -await m.update('mem-id', 'new content'); -``` - -#### reset() - -Clear the entire vector store and history. - -```typescript -await m.reset(); -``` - ---- - -## Key Differences: Platform vs OSS - -| Aspect | Platform (`MemoryClient`) | OSS (`Memory`) | -|--------|--------------------------|----------------| -| **Import** | `import MemoryClient from 'mem0ai'` | `import { Memory } from 'mem0ai/oss'` | -| **Auth** | API key required (`MEM0_API_KEY`) | No API key -- config-based | -| **Execution** | API calls to `api.mem0.ai` | Local execution | -| **Infrastructure** | Fully managed | Self-managed vector DB, embedder, LLM | -| **Param style** | Top-level: `camelCase` (`userId`, `topK`), filter keys: `snake_case` (`user_id`) | Top-level: `camelCase` (`userId`, `topK`), filter keys: `snake_case` (`user_id`) | -| **Batch ops** | `batchUpdate`, `batchDelete` | Not available | -| **Webhooks** | Full CRUD | Not available | -| **Export** | `createMemoryExport` | Not available | -| **Feedback** | `feedback()` | Not available | -| **Project mgmt** | `getProject`, `updateProject` | Not available | -| **User listing** | `users()`, `deleteUser()` | Not available | -| **History** | Platform-managed | SQLite (configurable) | - ---- - -## v2 Compatibility - -If you're using SDK v2.x: - -**Naming Changes:** -- Top-level params now use camelCase: `topK`, `rerank` (not `top_k`) -- Filter keys use snake_case: `user_id`, `agent_id` -- OSS: `limit` renamed to `topK` - -**API Changes:** -```typescript -// v2 - top-level entity IDs, snake_case -await client.search("query", { user_id: "alice", top_k: 20 }); - -// v3 - filters object with snake_case keys, camelCase top-level params -await client.search("query", { filters: { user_id: "alice" }, topK: 20 }); -``` - -**Default Changes:** -| Param | v2 | v3 | -|-------|----|----| -| `topK` | 100 | 20 | -| `threshold` | none | 0.1 | -| `rerank` | true | false | - -**Removed:** -- `OutputFormat` and `API_VERSION` enums -- `organizationId`, `projectId` from constructor -- `enableGraph`, `asyncMode`, `outputFormat`, `immutable`, `expirationDate`, `filterMemories`, `batchSize`, `forceAddOnly`, `includes`, `excludes`, `keywordSearch` - -See the [v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for details. diff --git a/integrations/mem0-plugin/skills/mem0/client/python.md b/integrations/mem0-plugin/skills/mem0/client/python.md deleted file mode 100644 index 0cf35a550..000000000 --- a/integrations/mem0-plugin/skills/mem0/client/python.md +++ /dev/null @@ -1,487 +0,0 @@ -# Mem0 Python SDK Reference - -Complete reference for the `mem0ai` Python package. Covers both the Platform client (managed API) and the Open Source self-hosted variant. - ---- - -## Platform Client - -### Installation - -```bash -pip install mem0ai -export MEM0_API_KEY="m0-your-api-key" -``` - -### MemoryClient (Synchronous) - -```python -from mem0 import MemoryClient - -client = MemoryClient(api_key="m0-xxx") -``` - -**Constructor:** `MemoryClient(api_key=None)`. If `api_key` is not provided, reads from `MEM0_API_KEY` environment variable. Raises `ValueError` if no key found. - -- HTTP library: `httpx` -- Timeout: 300 seconds -- Base URL: `https://api.mem0.ai` - -### AsyncMemoryClient (Asynchronous) - -```python -from mem0 import AsyncMemoryClient - -client = AsyncMemoryClient(api_key="m0-xxx") - -# Or use as context manager -async with AsyncMemoryClient(api_key="m0-xxx") as client: - results = await client.search("query", filters={"user_id": "alice"}) -``` - -Same methods as `MemoryClient`, all `async`/`await`. Supports async context manager. - ---- - -### Memory Methods - -#### add(messages, **kwargs) - -Store new memories from messages. - -```python -messages = [ - {"role": "user", "content": "I'm a vegetarian and allergic to nuts."}, - {"role": "assistant", "content": "Got it! I'll remember that."} -] -client.add(messages, user_id="alice") -``` - -| Parameter | Type | Default | Description | -|-----------|------|---------|-------------| -| `messages` | str \| dict \| list[dict] | required | Message content. Strings auto-convert to user messages | -| `user_id` | str | None | User identifier | -| `agent_id` | str | None | Agent identifier | -| `app_id` | str | None | Application identifier | -| `run_id` | str | None | Session/run identifier | -| `metadata` | dict | None | Custom key-value pairs | -| `infer` | bool | True | If False, store raw text without LLM inference | -| `custom_categories` | list | None | Override project categories | -| `custom_instructions` | str | None | Override extraction instructions | -| `timestamp` | int \| float \| str | None | Custom timestamp (Unix epoch or ISO 8601) | - -**Returns:** `dict` -- list of events: `[{"id": "...", "event": "ADD", "data": {"memory": "..."}}]` - -#### search(query, **kwargs) - -Search memories by semantic similarity. - -```python -results = client.search("dietary preferences", filters={"user_id": "alice"}) -for mem in results.get("results", []): - print(mem["memory"], mem["score"]) -``` - -| Parameter | Type | Default | Description | -|-----------|------|---------|-------------| -| `query` | str | required | Natural language search query | -| `filters` | dict | None | Filter object with entity IDs and/or `AND`/`OR`/`NOT` conditions (e.g., `{"user_id": "alice"}`) | -| `top_k` | int | 10 | Number of results | -| `rerank` | bool | False | Enable deep semantic reranking (+150-200ms) | -| `threshold` | float | 0.1 | Minimum similarity score | -| `fields` | list | None | Specific fields to return | -| `categories` | list | None | Filter by category | - -**Returns:** `dict` -- `{"results": [{id, memory, user_id, categories, score, created_at, ...}]}` - -#### get(memory_id) - -Retrieve a single memory by ID. - -```python -memory = client.get(memory_id="ea925981-...") -``` - -**Returns:** `dict` -- full memory object - -#### get_all(**kwargs) - -Retrieve all memories with optional filtering. Requires at least one entity identifier. - -```python -memories = client.get_all(filters={"user_id": "alice"}) -# With compound filters -memories = client.get_all(filters={"AND": [{"user_id": "alice"}, {"categories": {"contains": "health"}}]}) -``` - -| Parameter | Type | Default | Description | -|-----------|------|---------|-------------| -| `filters` | dict | None | Filter object with entity IDs and/or `AND`/`OR`/`NOT` conditions | -| `top_k` | int | None | Limit results | -| `page` | int | None | Page number | -| `page_size` | int | None | Results per page | - -**Returns:** `dict` -- `{"results": [...]}` - -#### update(memory_id, text=None, metadata=None, timestamp=None) - -Update a memory's content, metadata, or timestamp. At least one parameter required. - -```python -client.update("ea925981-...", text="Updated: vegan since 2024") -client.update("ea925981-...", metadata={"verified": True}) -``` - -**Returns:** `dict` -- updated memory - -#### delete(memory_id) - -Permanently delete a single memory. - -```python -client.delete("ea925981-...") -``` - -#### delete_all(**kwargs) - -Delete all memories matching filters. Irreversible. - -```python -client.delete_all(user_id="alice") -``` - -#### history(memory_id) - -Get the change history of a memory. - -```python -history = client.history("ea925981-...") -# Returns: [{previous_value, new_value, action, timestamps}] -``` - ---- - -### Batch Methods - -#### batch_update(memories) - -Update up to 1000 memories in a single request. - -```python -client.batch_update([ - {"memory_id": "uuid-1", "text": "Updated text"}, - {"memory_id": "uuid-2", "text": "Another update", "metadata": {"verified": True}}, -]) -``` - -#### batch_delete(memories) - -Delete up to 1000 memories in a single request. - -```python -client.batch_delete([ - {"memory_id": "uuid-1"}, - {"memory_id": "uuid-2"}, -]) -``` - ---- - -### User/Entity Management - -#### users() - -List all users, agents, and sessions that have memories. - -```python -users = client.users() -# Returns: {"results": [{"type": "user", "name": "alice"}, ...]} -``` - -#### delete_users(user_id=None, agent_id=None, app_id=None, run_id=None) - -Delete a specific entity and all its memories. - -```python -client.delete_users(user_id="alice") -``` - -#### reset() - -Delete ALL users, agents, sessions, and memories. Complete data reset. - -```python -client.reset() -``` - ---- - -### Export & Summary - -#### create_memory_export(schema, **kwargs) - -Create a structured export of memories. - -```python -import json - -schema = json.dumps({ - "type": "object", - "properties": { - "name": {"type": "string"}, - "preferences": {"type": "array", "items": {"type": "string"}}, - } -}) -export = client.create_memory_export(schema=schema, user_id="alice") -``` - -#### get_memory_export(**kwargs) - -Retrieve a previously created export. - -```python -result = client.get_memory_export(memory_export_id=export["id"]) -``` - -#### get_summary(filters=None) - -Get a summary of memories. - -```python -summary = client.get_summary(filters={"user_id": "alice"}) -``` - ---- - -### Feedback - -#### feedback(memory_id, feedback=None, feedback_reason=None) - -Provide quality feedback on a memory. - -```python -client.feedback( - memory_id="mem-123", - feedback="POSITIVE", # POSITIVE | NEGATIVE | VERY_NEGATIVE | None (clear) - feedback_reason="Accurately captured preference" -) -``` - ---- - -### Webhooks - -```python -# List -webhooks = client.get_webhooks(project_id="proj_123") - -# Create -webhook = client.create_webhook( - url="https://your-app.com/webhook", - name="Memory Logger", - project_id="proj_123", - event_types=["memory_add", "memory_update"] -) - -# Update -client.update_webhook(webhook_id=123, name="Updated", url="https://new-url.com") - -# Delete -client.delete_webhook(webhook_id=123) -``` - ---- - -### Project Management - -Access via `client.project.*`: - -```python -# Get project config -config = client.project.get(fields=["custom_categories", "custom_instructions"]) - -# Update project settings -client.project.update( - custom_instructions="Extract dietary preferences and health info", - custom_categories=[{"health": "Medical and dietary info"}], - multilingual=True, -) - -# Create/delete project -client.project.create(name="My Project", description="...") -client.project.delete() - -# Member management -members = client.project.get_members() -client.project.add_member(email="user@example.com", role="READER") # READER or OWNER -client.project.update_member(email="user@example.com", role="OWNER") -client.project.remove_member(email="user@example.com") -``` - ---- - -## Open Source / Self-Hosted - -### Installation - -```bash -pip install mem0ai -``` - -### Memory Class - -```python -from mem0 import Memory - -m = Memory() # Uses default config (OpenAI embedder + in-memory vector store) -``` - -**Import:** `from mem0 import Memory` (NOT `MemoryClient` -- that is the Platform client) - -### Configuration - -```python -config = { - "llm": { - "provider": "openai", # openai, groq, azure, ollama, lmstudio, google, anthropic, mistral - "config": { - "model": "gpt-5-mini", - "api_key": "sk-xxx", - } - }, - "embedder": { - "provider": "openai", # openai, ollama, azure, lmstudio, google, huggingface - "config": { - "model": "text-embedding-3-small", - "api_key": "sk-xxx", - } - }, - "vector_store": { - "provider": "qdrant", # faiss, qdrant, pgvector, redis, supabase, azure_ai_search, memory - "config": { - "collection_name": "my_memories", - "host": "localhost", - "port": 6333, - } - }, - "history_db_path": "history.db", # SQLite path for change history - "custom_instructions": "...", # Custom LLM prompt for extraction -} - -m = Memory.from_config(config) -``` - -### Context Manager - -```python -with Memory(config) as m: - m.add("I prefer dark mode", user_id="alice") - results = m.search("preferences", filters={"user_id": "alice"}) -# SQLite connections released automatically -``` - -### Methods - -All methods mirror the Platform client but run locally: - -#### add(messages, *, user_id, agent_id, run_id, metadata, infer=True) - -```python -m.add("I'm a vegetarian", user_id="alice") -m.add([ - {"role": "user", "content": "I like hiking"}, - {"role": "assistant", "content": "Great outdoor activity!"} -], user_id="alice") -``` - -At least one of `user_id`, `agent_id`, `run_id` required. - -**Returns:** `{"results": [...], "relations": [...]}` - -#### search(query, *, filters=None, top_k=20, threshold=0.1, rerank=False) - -```python -results = m.search("dietary preferences", filters={"user_id": "alice"}, top_k=5) -``` - -Entity IDs (`user_id`, `agent_id`, `run_id`) must be passed inside the `filters` dict. - -Supports filter operators: `eq`, `ne`, `in`, `nin`, `gt`, `gte`, `lt`, `lte`, `contains`, `not_contains`. - -#### get(memory_id) / get_all(**kwargs) / update(memory_id, data, metadata=None) / delete(memory_id) / delete_all(**kwargs) / history(memory_id) - -Same interface as Platform client. - -#### reset() - -Clear the entire vector store collection and history database. Recreates the vector store. - -```python -m.reset() -``` - -#### close() - -Release SQLite connections. Called automatically when using context manager. - -### AsyncMemory - -```python -from mem0 import AsyncMemory - -m = AsyncMemory(config) -await m.add("text", user_id="alice") -results = await m.search("query", filters={"user_id": "alice"}) -``` - ---- - -## Key Differences: Platform vs OSS - -| Aspect | Platform (`MemoryClient`) | OSS (`Memory`) | -|--------|--------------------------|----------------| -| **Import** | `from mem0 import MemoryClient` | `from mem0 import Memory` | -| **Auth** | API key required (`MEM0_API_KEY`) | No API key -- config-based | -| **Execution** | API calls to `api.mem0.ai` | Local execution | -| **Infrastructure** | Fully managed | Self-managed vector DB, embedder, LLM | -| **Entity filtering** | `filters={"user_id": "..."}` | `filters={"user_id": "..."}` | -| **Batch ops** | `batch_update`, `batch_delete` | Not available | -| **Webhooks** | Full CRUD | Not available | -| **Export** | `create_memory_export`, `get_memory_export` | Not available | -| **Feedback** | `feedback()` | Not available | -| **Project mgmt** | `client.project.*` | Not available | -| **User listing** | `users()`, `delete_users()` | Not available | -| **Custom prompts** | Via project settings | Direct config (`custom_instructions`) | -| **History** | Platform-managed | SQLite (configurable) | -| **Async** | `AsyncMemoryClient` | `AsyncMemory` | - ---- - -## v2 Compatibility - -If you're using SDK v2.x or the v2 API: - -**API Changes:** -- **Entity IDs in search/get_all:** Pass `user_id`, `agent_id` as top-level kwargs instead of inside `filters` - ```python - # v2 - results = client.search("query", user_id="alice") - # v3 - results = client.search("query", filters={"user_id": "alice"}) - ``` -- **add() returns:** v2 returns ADD, UPDATE, DELETE events; v3 returns ADD only - -**Default Changes:** -| Param | v2 | v3 | -|-------|----|----| -| `top_k` | 100 | 20 | -| `threshold` | None | 0.1 | -| `rerank` | True | False | - -**Removed Parameters:** -- Constructor: `org_id`, `project_id` -- add(): `async_mode`, `output_format`, `enable_graph`, `immutable`, `expiration_date`, `filter_memories`, `batch_size`, `force_add_only`, `includes`, `excludes`, `keyword_search` -- search()/get_all(): `enable_graph` -- Config: `enable_graph`, `graph_store`, `custom_fact_extraction_prompt` (renamed to `custom_instructions`) - -See the [v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for full details. diff --git a/integrations/mem0-plugin/skills/mem0/references/api-reference.md b/integrations/mem0-plugin/skills/mem0/references/api-reference.md deleted file mode 100644 index 4ab8548ca..000000000 --- a/integrations/mem0-plugin/skills/mem0/references/api-reference.md +++ /dev/null @@ -1,150 +0,0 @@ -# Mem0 Platform API Reference - -REST API endpoints for the Mem0 Platform. Base URL: `https://api.mem0.ai` - -All endpoints require: `Authorization: Token ` - -## Endpoints - -| Operation | Method | URL | -|-----------|--------|-----| -| Add Memories | `POST` | `/v3/memories/add/` | -| Search Memories | `POST` | `/v3/memories/search/` | -| Get All Memories | `POST` | `/v3/memories/` | -| Get Single Memory | `GET` | `/v1/memories/{memory_id}/` | -| Update Memory | `PUT` | `/v1/memories/{memory_id}/` | -| Delete Memory | `DELETE` | `/v1/memories/{memory_id}/` | -| Delete All Memories | `DELETE` | `/v1/memories/?user_id=X&app_id=Y` | -| Get Event Status | `GET` | `/v1/event/{event_id}/` | - -## Memory Object Structure - -| Field | Type | Description | -|-------|------|-------------| -| `id` | string (UUID) | Unique memory identifier | -| `memory` | string | Text content of the memory | -| `user_id` | string | Associated user | -| `agent_id` | string (nullable) | Agent identifier | -| `app_id` | string (nullable) | Application identifier | -| `run_id` | string (nullable) | Run/session identifier | -| `metadata` | object | Custom key-value pairs | -| `categories` | array of strings | Auto-assigned category tags | -| `hash` | string | Content hash | -| `created_at` | datetime | Creation timestamp | -| `updated_at` | datetime | Last modification timestamp | - -Search results additionally include `score` (relevance metric). - -## Scoping Identifiers - -Memories can be scoped to different levels: - -| Scope | Parameter | Use Case | -|-------|-----------|----------| -| User | `user_id` | Per-user memory isolation | -| Agent | `agent_id` | Per-agent memory partitioning | -| Application | `app_id` | Cross-agent app-level memory | -| Run/Session | `run_id` | Session-scoped temporary memory | - -**Critical:** Combining `user_id` and `agent_id` in a single AND filter yields empty results. Entities are stored separately. Use `OR` logic or separate queries. - -## Processing Model - -- Memories are processed **asynchronously** (v3 default) -- Add responses return queued `ADD` events only (v3 is ADD-only, no UPDATE/DELETE) -- Poll status via `GET /v1/event/{event_id}/` - -## Filter System - -Filters use nested JSON with a logical operator at the root: - -```json -{ - "AND": [ - {"user_id": "alice"}, - {"categories": {"contains": "finance"}}, - {"created_at": {"gte": "2024-01-01"}} - ] -} -``` - -Root must be `AND`, `OR`, or `NOT`. Simple shorthand `{"user_id": "alice"}` also works. - -### Supported Operators - -| Operator | Description | -|----------|-------------| -| `eq` | Equal to (default) | -| `ne` | Not equal to | -| `in` | Matches any value in array | -| `gt`, `gte` | Greater than / greater than or equal | -| `lt`, `lte` | Less than / less than or equal | -| `contains` | Case-sensitive containment | -| `icontains` | Case-insensitive containment | -| `*` | Wildcard -- matches any non-null value | - -### Filterable Fields - -| Field | Valid Operators | -|-------|-----------------| -| `user_id`, `agent_id`, `app_id`, `run_id` | `eq`, `ne`, `in`, `*` | -| `created_at`, `updated_at`, `timestamp` | `gt`, `gte`, `lt`, `lte`, `eq`, `ne` | -| `categories` | `eq`, `ne`, `in`, `contains` | -| `metadata` | `eq`, `ne`, `contains` (top-level keys only) | -| `keywords` | `contains`, `icontains` | -| `memory_ids` | `in` | - -### Filter Constraints - -1. **Entity scope partitioning:** `user_id` AND `agent_id` in one `AND` block yields empty results. -2. **Metadata limitations:** Only top-level keys. Only `eq`, `contains`, `ne`. No `in` or `gt`. -3. **Operator syntax:** Use `gte`, `lt`, `ne`. SQL-style (`>=`, `!=`) rejected. -4. **Entity filter required for get-all:** At least one of `user_id`, `agent_id`, `app_id`, or `run_id`. -5. **Wildcard excludes null:** `*` matches only non-null values. -6. **Date format:** ISO 8601 (`YYYY-MM-DDTHH:MM:SSZ`). Timezone-naive defaults to UTC. - -## Response Formats - -### Add Response (v3) - -```json -{ - "message": "Memory processing has been queued for background execution", - "status": "PENDING", - "event_id": "evt-uuid" -} -``` - -v3 is ADD-only. No UPDATE or DELETE events. - -### Search Response - -```json -{ - "results": [ - { - "id": "ea925981-...", - "memory": "Is a vegetarian and allergic to nuts.", - "user_id": "user123", - "categories": ["food", "health"], - "score": 0.89, - "created_at": "2024-07-26T10:29:36.630547-07:00" - } - ] -} -``` - -In v3, `score` is a combined multi-signal relevance score. - -### Get All Response (v3) - -```json -{ - "count": 123, - "next": "https://api.mem0.ai/v3/memories/?page=2&page_size=50", - "previous": null, - "results": [...] -} -``` - -v3 returns paginated envelope. Use `page` and `page_size` query params. diff --git a/integrations/mem0-plugin/skills/mem0/references/architecture.md b/integrations/mem0-plugin/skills/mem0/references/architecture.md deleted file mode 100644 index 4a04c820b..000000000 --- a/integrations/mem0-plugin/skills/mem0/references/architecture.md +++ /dev/null @@ -1,330 +0,0 @@ -# Mem0 Platform Architecture - -How Mem0 processes, stores, and retrieves memories under the hood. - -## Table of Contents - -- [Core Concept](#core-concept) -- [Memory Processing Pipeline](#memory-processing-pipeline) -- [Retrieval Pipeline](#retrieval-pipeline) -- [Memory Lifecycle](#memory-lifecycle) -- [Memory Object Structure](#memory-object-structure) -- [Scoping & Multi-Tenancy](#scoping--multi-tenancy) -- [Memory Layers](#memory-layers) -- [Performance Characteristics](#performance-characteristics) - ---- - -## Core Concept - -Mem0 is a managed memory layer that sits between your AI application and users. Every integration follows the same 3-step loop: - -``` -User Input → Retrieve relevant memories → Enrich LLM prompt → Generate response → Store new memories -``` - -Mem0 handles the complexity of extraction, deduplication, conflict resolution, and semantic retrieval so your application only needs to call `search()` and `add()`. - -**Storage architecture:** -- **Vector store**: Embeddings for semantic similarity search -- **Entity store**: Automatic entity linking for relationship-aware retrieval - ---- - -## Memory Processing Pipeline - -### What happens when you call `client.add()` - -``` -Messages In - │ - ▼ -┌─────────────────────┐ -│ 1. EXTRACTION │ Single LLM call extracts all distinct new facts -│ (infer=True) │ If infer=False, stores raw text as-is -└─────────┬───────────┘ - │ - ▼ -┌─────────────────────┐ -│ 2. DEDUPLICATION │ Hash-based dedup (MD5 prevents exact duplicates) -│ │ No UPDATE/DELETE - v3 is ADD-only -└─────────┬───────────┘ - │ - ▼ -┌─────────────────────┐ -│ 3. STORAGE │ Batch embed → vector store -│ │ Entity extraction → entity store -└─────────┬───────────┘ - │ - ▼ - Memory Object -``` - -### Processing (v3) - -v3 processes memories asynchronously by default: -- API returns immediately: `{"status": "PENDING", "event_id": "evt-..."}` -- Poll status via `GET /v1/event/{event_id}/` -- Use webhooks for completion notifications - -### Extraction modes - -**Inferred (`infer=True`, default):** -- LLM extracts structured facts from conversation -- Conflict resolution deduplicates and resolves contradictions -- Best for: natural conversation → memory - -**Raw (`infer=False`):** -- Stores text exactly as provided, no LLM processing -- Skips conflict resolution — same fact can be stored twice -- Only `user` role messages are stored; `assistant` messages ignored -- Best for: bulk imports, pre-structured data, migrations - -**Warning:** Don't mix `infer=True` and `infer=False` for the same data — the same fact will be stored twice. - ---- - -## Retrieval Pipeline (v3) - -### What happens when you call `client.search()` - -``` -Query In - │ - ▼ -┌─────────────────────┐ -│ 1. PREPROCESSING │ Lemmatize keywords, extract entities -└─────────┬───────────┘ - │ - ▼ -┌─────────────────────┐ -│ 2. PARALLEL SCORING │ Semantic search (vector similarity) -│ │ BM25 keyword search (term matching) -│ │ Entity matching (entity graph boost) -└─────────┬───────────┘ - │ - ▼ -┌─────────────────────┐ -│ 3. SCORE FUSION │ Combine signals into single score -│ │ Optional: rerank=True for deep reordering -└─────────┬───────────┘ - │ - ▼ - Results (combined score per memory) -``` - -### v3 Search Defaults - -| Parameter | Default | Notes | -|-----------|---------|-------| -| `top_k` | 20 | Was 100 in v2 | -| `threshold` | 0.1 | Was None in v2 | -| `rerank` | False | Was True in v2 | - -### Implicit null scoping - -When you search with `filters={"user_id": "alice"}` only, Mem0 returns memories where `agent_id`, `app_id`, and `run_id` are all null. This prevents cross-scope leakage by default. - -To include memories with non-null fields, use explicit filters: -```python -# Gets memories for alice regardless of agent/app/run -filters={"OR": [{"user_id": "alice"}]} -``` - ---- - -## Memory Lifecycle (v3) - -v3 uses ADD-only extraction. Memories accumulate over time rather than being consolidated. - -### Creation -- `client.add(messages, user_id="...")` -- Single-pass extraction → deduplication → storage -- Returns `{"event_id": "...", "status": "PENDING"}` - -### Updates -- `client.update(memory_id, text="...")` replaces text -- Batch: `client.batch_update([...])` - -### Deletion -- Single: `client.delete(memory_id)` -- Batch: `client.batch_delete([...])` -- Bulk: `client.delete_all(filters={"user_id": "alice"})` - ---- - -## Memory Object Structure - -```json -{ - "id": "uuid-string", - "memory": "Extracted memory text", - "user_id": "user-identifier", - "agent_id": null, - "app_id": null, - "run_id": null, - "metadata": { "source": "chat", "priority": "high" }, - "categories": ["health", "preferences"], - "created_at": "2025-03-12T12:34:56Z", - "updated_at": "2025-03-12T12:34:56Z", - "structured_attributes": { - "day": 12, "month": 3, "year": 2025, - "hour": 12, "minute": 34, - "day_of_week": "wednesday", - "is_weekend": false, - "quarter": 1, "week_of_year": 11 - }, - "score": 0.85 -} -``` - -| Field | Type | Description | -|-------|------|-------------| -| `id` | UUID | Unique identifier, used for update/delete | -| `memory` | string | Extracted or stored text content | -| `user_id` | string | Primary entity scope | -| `agent_id` | string | Agent scope | -| `app_id` | string | Application scope | -| `run_id` | string | Session/run scope | -| `metadata` | object | Custom key-value pairs for filtering | -| `categories` | array | Auto-assigned or custom category tags | -| `created_at` | datetime | Creation timestamp | -| `updated_at` | datetime | Last modification timestamp | -| `structured_attributes` | object | Temporal breakdown for time-based queries | -| `score` | float | Semantic similarity (search results only, 0-1) | - ---- - -## Scoping & Multi-Tenancy - -Mem0 separates memories across four dimensions to prevent data mixing: - -| Dimension | Field | Purpose | Example | -|-----------|-------|---------|---------| -| User | `user_id` | Persistent persona or account | `"customer_6412"` | -| Agent | `agent_id` | Distinct agent or tool | `"meal_planner"` | -| App | `app_id` | Product surface or deployment | `"ios_retail_app"` | -| Session | `run_id` | Short-lived flow or thread | `"ticket-9241"` | - -### Storage model - -Each entity combination creates separate records. A memory with `user_id="alice"` is stored separately from one with `user_id="alice"` + `agent_id="bot"`. - -### Critical: cross-entity queries - -```python -# This returns NOTHING — user and agent memories are stored separately -filters={"AND": [{"user_id": "alice"}, {"agent_id": "bot"}]} - -# Use OR to query multiple scopes -filters={"OR": [{"user_id": "alice"}, {"agent_id": "bot"}]} - -# Use wildcard to include any non-null value -filters={"AND": [{"user_id": "*"}]} # All users (excludes null) -``` - -### Recommended scoping patterns - -```python -# User-level: persistent preferences -client.add(messages, user_id="alice") - -# Session-level: temporary context -client.add(messages, user_id="alice", run_id="session_123") -# Clean up when done: client.delete_all(run_id="session_123") - -# Agent-level: agent-specific knowledge -client.add(messages, agent_id="support_bot", app_id="helpdesk") - -# Multi-tenant: full isolation -client.add(messages, user_id="alice", agent_id="bot", app_id="acme_corp", run_id="ticket_42") -``` - ---- - -## Memory Layers - -Mem0 supports three layers of memory, from shortest to longest lived: - -### Conversation memory -- In-flight messages within a single turn -- Tool calls, chain-of-thought reasoning -- **Lifetime:** Single response — lost after turn finishes -- **Managed by:** Your application, not Mem0 - -### Session memory -- Short-lived facts for current task or channel -- Multi-step flows (onboarding, debugging, support tickets) -- **Lifetime:** Minutes to hours -- **Managed by:** Mem0 via `run_id` parameter -- Clean up with `client.delete_all(run_id="session_id")` - -### User memory -- Long-lived knowledge tied to a person or account -- Personal preferences, account state, compliance details -- **Lifetime:** Weeks to forever -- **Managed by:** Mem0 via `user_id` parameter -- Persists across all sessions and interactions - -### How layering works in practice - -```python -def chat(user_input: str, user_id: str, session_id: str) -> str: - # 1. Retrieve user memories (long-term preferences) - user_mems = mem0.search(user_input, filters={"user_id": user_id}) - - # 2. Retrieve session memories (current task context) - session_mems = mem0.search(user_input, filters={ - "AND": [{"user_id": user_id}, {"run_id": session_id}] - }) - - # 3. Combine both layers for LLM context - context = format_memories(user_mems) + format_memories(session_mems) - - # 4. Generate response - response = llm.generate(context=context, input=user_input) - - # 5. Store in session scope (temporary) + user scope (persistent) - messages = [{"role": "user", "content": user_input}, {"role": "assistant", "content": response}] - mem0.add(messages, user_id=user_id, run_id=session_id) - - return response -``` - ---- - -## Performance Characteristics - -### Latency - -| Operation | Typical Latency | -|-----------|----------------| -| Hybrid search (v3 default) | ~100-150ms | -| + reranking | +150-200ms | -| Add (async) | < 50ms response | - -### Processing - -- **Async (default):** Returns immediately, processes in background -- **Batch operations:** Up to 1000 memories per batch_update/batch_delete -- **Webhooks:** Real-time notifications when async processing completes - -### Scoping strategy for performance - -- Use `user_id` for all user-facing queries (most common, fastest) -- Add `run_id` for session isolation (narrows search space) -- Avoid wildcard `"*"` filters on large datasets (scans all non-null records) -- Use `top_k` to limit result count when you only need a few memories - ---- - -## Comparison with Alternatives - -| Approach | Pros | Cons | -|----------|------|------| -| **Raw vector DB** | Fast, full control | No extraction, no dedup, no conflict resolution | -| **In-memory chat history** | Zero latency | Lost on restart, no cross-session, grows unbounded | -| **RAG over documents** | Good for static knowledge | No personalization, no memory updates | -| **Mem0 Platform** | Managed extraction + dedup + graph + scoping | External dependency, async processing delay | - -Mem0 combines the best of vector search (semantic retrieval) with automatic extraction (LLM-powered), conflict resolution (deduplication), and structured scoping (multi-tenancy) — in a single managed API. diff --git a/integrations/mem0-plugin/skills/mem0/references/features.md b/integrations/mem0-plugin/skills/mem0/references/features.md deleted file mode 100644 index 1cfaba61f..000000000 --- a/integrations/mem0-plugin/skills/mem0/references/features.md +++ /dev/null @@ -1,406 +0,0 @@ -# Platform Features -- Mem0 Platform - -Additional platform capabilities beyond core CRUD operations. - -## Table of Contents - -- [Advanced Retrieval](#advanced-retrieval) -- [Entity Linking](#entity-linking) -- [Custom Categories](#custom-categories) -- [Custom Instructions](#custom-instructions) -- [Feedback Mechanism](#feedback-mechanism) -- [Memory Export](#memory-export) -- [Group Chat](#group-chat) -- [MCP Integration](#mcp-integration) -- [Webhooks](#webhooks) -- [Multimodal Support](#multimodal-support) - -## Advanced Retrieval - -### Hybrid Search (v3 Default) - -v3 uses multi-signal hybrid search combining: -- **Semantic search** (vector similarity) -- **BM25 keyword search** (normalized term matching) -- **Entity matching** (entity graph boost) - -This is automatic — no configuration needed. - -### Reranking (`rerank=True`) - -Deep semantic reordering of results — most relevant first. - -- Latency: +150-200ms -- Default: `False` (was `True` in v2) -- Best for: user-facing results, top-N precision - -**Python:** -```python -results = client.search(query, filters={"user_id": "user123"}, rerank=True) -``` - -**TypeScript:** -```typescript -const results = await client.search(query, { - filters: { user_id: 'user123' }, - rerank: true, -}); -``` - ---- - -## Entity Linking - -v3 replaces graph memory with built-in entity linking. Entities (proper nouns, quoted text, compound noun phrases) are automatically extracted and linked across memories. - -### How It Works - -1. **Extraction**: During `add()`, entities are automatically extracted from memory text -2. **Storage**: Entities are stored in a parallel collection (`{collection}_entities`) -3. **Retrieval**: During `search()`, query entities are matched and used to boost relevant memories - -Entity linking is automatic — no configuration required. The boost is folded into the combined `score` on each result. - -### v2 Migration Note - -If you were using `enable_graph=True` in v2: -- Remove `enable_graph` from all API calls -- Remove `graph_store` from OSS configuration -- Entity relationships are now consumed through retrieval ranking, not exposed as a separate `relations` array - -See the [v2 to v3 migration guide](https://docs.mem0.ai/migration/platform-v2-to-v3) for details. - ---- - -## Custom Categories - -Replace Mem0's default 15 labels with domain-specific categories. The system automatically tags memories to the closest matching category. - -### Default Categories (15) - -`personal_details`, `family`, `professional_details`, `sports`, `travel`, `food`, `music`, `health`, `technology`, `hobbies`, `fashion`, `entertainment`, `milestones`, `user_preferences`, `misc` - -### Configuration - -**Set project-level categories:** -```python -new_categories = [ - {"lifestyle_management": "Tracks daily routines, habits, wellness activities"}, - {"seeking_structure": "Documents goals around creating routines and systems"}, - {"personal_information": "Basic information about the user"} -] -client.project.update(custom_categories=new_categories) -``` - -```javascript -await client.updateProject({ customCategories: newCategories }); -``` - -**Retrieve active categories:** -```python -categories = client.project.get(fields=["custom_categories"]) -``` - -**Override categories for a single add call:** -```python -client.add(messages, user_id="alice", custom_categories=per_call_categories) -``` - -```javascript -await client.add(messages, { userId: "alice", customCategories: perCallCategories }); -``` - -### Resolution Order - -1. `custom_categories` passed on the `add` call -2. `custom_categories` set on the project -3. Built-in default catalog - -### Key Constraints - -- A per-call list **fully replaces** the project list for that call. The lists are not merged. -- Categories are applied at ingestion time. Changing the list later does not re-tag existing memories. - -### Main Use Case - -Per-call lists give different users or entities their own vocabulary inside a single project, without splitting them across projects. - ---- - -## Custom Instructions - -Natural language filters that control what information Mem0 extracts when creating memories. - -### Set Instructions - -```python -client.project.update(custom_instructions="Your guidelines here...") -``` - -```javascript -await client.updateProject({ customInstructions: "Your guidelines here..." }); -``` - -### Template Structure - -1. **Task Description** -- brief extraction overview -2. **Information Categories** -- numbered sections with specific details to capture -3. **Processing Guidelines** -- quality and handling rules -4. **Exclusion List** -- sensitive/irrelevant data to filter out - -### Domain Examples - -**E-commerce:** Capture product issues, preferences, service experience; exclude payment data. - -**Education:** Extract learning progress, student preferences, performance patterns; exclude specific grades. - -**Finance:** Track financial goals, life events, investment interests; exclude account numbers and SSNs. - -### Best Practices - -- Start simply, test with sample messages, iterate based on results -- Avoid overly lengthy instructions -- Be specific about what to include AND exclude - ---- - -## Feedback Mechanism - -Provide feedback on extracted memories to improve system quality over time. - -### Feedback Types - -| Type | Meaning | -|------|---------| -| `POSITIVE` | Memory is useful and accurate | -| `NEGATIVE` | Memory is not useful | -| `VERY_NEGATIVE` | Memory is harmful or completely wrong | -| `None` | Clear existing feedback | - -### Usage - -**Python:** -```python -client.feedback( - memory_id="mem-123", - feedback="POSITIVE", - feedback_reason="Accurately captured dietary preference" -) - -# Bulk feedback -for item in feedback_data: - client.feedback(**item) -``` - -**TypeScript:** -```typescript -await client.feedback('mem-123', { - feedback: 'POSITIVE', - feedbackReason: 'Accurately captured dietary preference', -}); -``` - ---- - -## Memory Export - -Create structured exports of memories using customizable schemas with filters. - -### Usage - -```python -import json - -# Define export schema -schema = { - "type": "object", - "properties": { - "name": {"type": "string"}, - "preferences": {"type": "array", "items": {"type": "string"}}, - "health_info": {"type": "string"}, - } -} - -# Create export -response = client.create_memory_export( - schema=json.dumps(schema), - filters={"user_id": "alice"}, - export_instructions="Create comprehensive profile based on all memories" -) - -# Retrieve export (may take a moment to process) -result = client.get_memory_export(memory_export_id=response["id"]) -``` - -**Best for:** Data analytics, user profile generation, compliance audits, CRM sync. - ---- - -## Group Chat - -Process multi-participant conversations and automatically attribute memories to individual speakers. - -### Usage - -```python -messages = [ - {"role": "user", "name": "Alice", "content": "I think we should use React for the frontend"}, - {"role": "user", "name": "Bob", "content": "I prefer Vue.js, it's simpler for our use case"}, - {"role": "assistant", "content": "Both are great choices. Let me note your preferences."}, -] - -# Mem0 automatically attributes memories to each speaker -response = client.add(messages, run_id="team_meeting_1") - -# Retrieve Alice's memories from that session -alice_mems = client.get_all( - filters={"AND": [{"user_id": "alice"}, {"run_id": "team_meeting_1"}]} -) -``` - -Use the `name` field in messages to identify speakers. Mem0 maps names to entity scopes automatically. - ---- - -## MCP Integration - -Model Context Protocol integration enables AI clients (Claude, Claude Code, Cursor, Windsurf, VS Code, OpenCode) to manage Mem0 memory autonomously. - -### Setup - -Add Mem0 MCP to your clients with a single command: - -```bash -npx mcp-add \ - --name mem0-mcp \ - --type http \ - --url "https://mcp.mem0.ai/mcp" \ - --clients "claude,claude code,cursor,windsurf,vscode,opencode" -``` - -### Available MCP Tools - -The MCP server exposes 9 memory tools that AI agents can use autonomously: -- Add, search, get, update, delete memories -- Get history, list users, delete users -- Search Mem0 documentation - -### How It Works - -1. Add Mem0 MCP to your AI client using the setup command above -2. The agent autonomously decides when to store/retrieve memories -3. No manual API calls needed — the agent manages memory as part of its reasoning - -**Best for:** Universal AI client integration — one protocol works everywhere. - ---- - -## Webhooks - -Real-time event notifications for memory operations. - -### Supported Events - -| Event | Trigger | -|-------|---------| -| `memory_add` | Memory created | -| `memory_update` | Memory modified | -| `memory_delete` | Memory removed | -| `memory_categorize` | Memory tagged | - -### Create Webhook - -Note: `project_id` here refers to the Mem0 dashboard project scope for webhooks — not the deprecated client init parameter. - -```python -webhook = client.create_webhook( - url="https://your-app.com/webhook", - name="Memory Logger", - project_id="proj_123", - event_types=["memory_add", "memory_categorize"] -) -``` - -### Manage Webhooks - -```python -# Retrieve -webhooks = client.get_webhooks(project_id="proj_123") - -# Update -client.update_webhook( - name="Updated Logger", - url="https://your-app.com/new-webhook", - event_types=["memory_update", "memory_add"], - webhook_id="wh_123" -) - -# Delete -client.delete_webhook(webhook_id="wh_123") -``` - -### Payload Structure - -Memory events contain: ID, data object with memory content, event type (`ADD`/`UPDATE`/`DELETE`). -Categorization events contain: memory ID, event type (`CATEGORIZE`), assigned category labels. - ---- - -## Multimodal Support - -Mem0 can process images and documents alongside text. - -### Supported Media Types - -- Images: JPG, PNG -- Documents: MDX, TXT, PDF - -### Image via URL - -```python -image_message = { - "role": "user", - "content": { - "type": "image_url", - "image_url": {"url": "https://example.com/image.jpg"} - } -} -client.add([image_message], user_id="alice") -``` - -### Image via Base64 - -```python -import base64 -with open("photo.jpg", "rb") as f: - base64_image = base64.b64encode(f.read()).decode("utf-8") - -image_message = { - "role": "user", - "content": { - "type": "image_url", - "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"} - } -} -client.add([image_message], user_id="alice") -``` - -### Document (MDX/TXT) - -```python -doc_message = { - "role": "user", - "content": {"type": "mdx_url", "mdx_url": {"url": document_url}} -} -client.add([doc_message], user_id="alice") -``` - -### PDF Document - -```python -pdf_message = { - "role": "user", - "content": {"type": "pdf_url", "pdf_url": {"url": pdf_url}} -} -client.add([pdf_message], user_id="alice") -``` diff --git a/integrations/mem0-plugin/skills/mem0/references/integration-patterns.md b/integrations/mem0-plugin/skills/mem0/references/integration-patterns.md deleted file mode 100644 index 71cfa981c..000000000 --- a/integrations/mem0-plugin/skills/mem0/references/integration-patterns.md +++ /dev/null @@ -1,395 +0,0 @@ -# Mem0 Integration Patterns - -Working code examples for integrating Mem0 Platform with popular AI frameworks. -All examples use `MemoryClient` (Platform API key). - -Code examples are sourced from official Mem0 integration docs at docs.mem0.ai, simplified for quick reference. - ---- - -## Common Pattern - -Every integration follows the same 3-step loop: - -1. **Retrieve** -- search relevant memories before generating a response -2. **Generate** -- include memories as context in the LLM prompt -3. **Store** -- save the interaction back to Mem0 for future use - ---- - -## LangChain - -Source: [docs.mem0.ai/integrations/langchain](https://docs.mem0.ai/integrations/langchain) - -```python -from langchain_openai import ChatOpenAI -from langchain_core.messages import SystemMessage, HumanMessage -from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder -from mem0 import MemoryClient - -llm = ChatOpenAI(model="gpt-5-mini") -mem0 = MemoryClient() - -prompt = ChatPromptTemplate.from_messages([ - SystemMessage(content="You are a helpful travel agent AI. Use the provided context to personalize your responses."), - MessagesPlaceholder(variable_name="context"), - HumanMessage(content="{input}") -]) - -def retrieve_context(query: str, user_id: str): - """Retrieve relevant memories from Mem0""" - memories = mem0.search(query, filters={"user_id": user_id}) - memory_list = memories['results'] - serialized = ' '.join([m["memory"] for m in memory_list]) - return [ - {"role": "system", "content": f"Relevant information: {serialized}"}, - {"role": "user", "content": query} - ] - -def chat_turn(user_input: str, user_id: str) -> str: - # 1. Retrieve - context = retrieve_context(user_input, user_id) - # 2. Generate - chain = prompt | llm - response = chain.invoke({"context": context, "input": user_input}) - # 3. Store - mem0.add( - [{"role": "user", "content": user_input}, {"role": "assistant", "content": response.content}], - user_id=user_id - ) - return response.content -``` - ---- - -## CrewAI - -Source: [docs.mem0.ai/integrations/crewai](https://docs.mem0.ai/integrations/crewai) - -CrewAI has native Mem0 integration via `memory_config`: - -```python -from crewai import Agent, Task, Crew, Process -from mem0 import MemoryClient - -client = MemoryClient() - -# Store user preferences first -messages = [ - {"role": "user", "content": "I am more of a beach person than a mountain person."}, - {"role": "assistant", "content": "Noted! I'll recommend beach destinations."}, - {"role": "user", "content": "I like Airbnb more than hotels."}, -] -client.add(messages, user_id="crew_user_1") - -# Create agent -travel_agent = Agent( - role="Personalized Travel Planner", - goal="Plan personalized travel itineraries", - backstory="You are a seasoned travel planner.", - memory=True, -) - -# Create task -task = Task( - description="Find places to live, eat, and visit in San Francisco.", - expected_output="A detailed list of places to live, eat, and visit.", - agent=travel_agent, -) - -# Setup crew with Mem0 memory -crew = Crew( - agents=[travel_agent], - tasks=[task], - process=Process.sequential, - memory=True, - memory_config={ - "provider": "mem0", - "config": {"user_id": "crew_user_1"}, - } -) - -result = crew.kickoff() -``` - ---- - -## Vercel AI SDK - -> **Dedicated skill available.** For comprehensive Vercel AI SDK documentation, see the [mem0-vercel-ai-sdk skill](https://github.com/mem0ai/mem0/tree/main/skills/mem0-vercel-ai-sdk). - -Install: `npm install @mem0/vercel-ai-provider` - -Quick example (wrapped model with automatic memory): - -```typescript -import { generateText } from "ai"; -import { createMem0 } from "@mem0/vercel-ai-provider"; - -const mem0 = createMem0(); -const { text } = await generateText({ - model: mem0("gpt-5-mini", { user_id: "borat" }), - prompt: "Suggest me a good car to buy!", -}); -``` - -Supported providers: `openai`, `anthropic`, `google`, `groq`, `cohere` - ---- - -## OpenAI Agents SDK - -Source: [docs.mem0.ai/integrations/openai-agents-sdk](https://docs.mem0.ai/integrations/openai-agents-sdk) - -```python -from agents import Agent, Runner, function_tool -from mem0 import MemoryClient - -mem0 = MemoryClient() - -@function_tool -def search_memory(query: str, user_id: str) -> str: - """Search through past conversations and memories""" - memories = mem0.search(query, filters={"user_id": user_id}, top_k=3) - if memories and memories.get('results'): - return "\n".join([f"- {mem['memory']}" for mem in memories['results']]) - return "No relevant memories found." - -@function_tool -def save_memory(content: str, user_id: str) -> str: - """Save important information to memory""" - mem0.add([{"role": "user", "content": content}], user_id=user_id) - return "Information saved to memory." - -agent = Agent( - name="Personal Assistant", - instructions="""You are a helpful personal assistant with memory capabilities. - Use search_memory to recall past conversations. - Use save_memory to store important information.""", - tools=[search_memory, save_memory], - model="gpt-5-mini" -) - -result = Runner.run_sync(agent, "I love Italian food and I'm planning a trip to Rome next month") -print(result.final_output) -``` - -### Multi-Agent with Handoffs - -```python -from agents import Agent, Runner, function_tool - -travel_agent = Agent( - name="Travel Planner", - instructions="You are a travel planning specialist. Use search_memory and save_memory tools.", - tools=[search_memory, save_memory], - model="gpt-5-mini" -) - -health_agent = Agent( - name="Health Advisor", - instructions="You are a health and wellness advisor. Use search_memory and save_memory tools.", - tools=[search_memory, save_memory], - model="gpt-5-mini" -) - -triage_agent = Agent( - name="Personal Assistant", - instructions="""Route travel questions to Travel Planner, health questions to Health Advisor.""", - handoffs=[travel_agent, health_agent], - model="gpt-5-mini" -) - -result = Runner.run_sync(triage_agent, "Plan a healthy meal for my Italy trip") -``` - ---- - -## Pipecat (Voice / Real-Time) - -Source: [docs.mem0.ai/integrations/pipecat](https://docs.mem0.ai/integrations/pipecat) - -```python -from pipecat.services.mem0 import Mem0MemoryService - -memory = Mem0MemoryService( - api_key=os.getenv("MEM0_API_KEY"), - user_id="alice", - agent_id="voice_bot", - params={ - "search_limit": 10, - "search_threshold": 0.1, - "system_prompt": "Here are your past memories:", - "add_as_system_message": True, - } -) - -# Use in pipeline -pipeline = Pipeline([ - transport.input(), - stt, - user_context, - memory, # Memory enhances context automatically - llm, - transport.output(), - assistant_context -]) -``` - - - ---- - -## LangGraph - -Source: [docs.mem0.ai/integrations/langgraph](https://docs.mem0.ai/integrations/langgraph) - -State-based agent workflows with memory persistence. Best for complex conversation flows with branching logic. - -```python -from typing import Annotated, TypedDict, List -from langgraph.graph import StateGraph, START -from langgraph.graph.message import add_messages -from langchain_openai import ChatOpenAI -from mem0 import MemoryClient -from langchain_core.messages import SystemMessage, HumanMessage, AIMessage - -llm = ChatOpenAI(model="gpt-5-mini") -mem0 = MemoryClient() - -class State(TypedDict): - messages: Annotated[List[HumanMessage | AIMessage], add_messages] - mem0_user_id: str - -def chatbot(state: State): - messages = state["messages"] - user_id = state["mem0_user_id"] - - # Retrieve relevant memories - memories = mem0.search(messages[-1].content, filters={"user_id": user_id}) - context = "Relevant context:\n" - for memory in memories["results"]: - context += f"- {memory['memory']}\n" - - system_message = SystemMessage(content=f"""You are a helpful support assistant. -{context}""") - - response = llm.invoke([system_message] + messages) - - # Store the interaction - mem0.add( - [{"role": "user", "content": messages[-1].content}, - {"role": "assistant", "content": response.content}], - user_id=user_id - ) - return {"messages": [response]} - -graph = StateGraph(State) -graph.add_node("chatbot", chatbot) -graph.add_edge(START, "chatbot") -app = graph.compile() - -# Usage -result = app.invoke({ - "messages": [HumanMessage(content="I need help with my order")], - "mem0_user_id": "customer_123" -}) -``` - ---- - -## LlamaIndex - -Source: [docs.mem0.ai/integrations/llama-index](https://docs.mem0.ai/integrations/llama-index) - -Install: `pip install llama-index-core llama-index-memory-mem0` - -LlamaIndex has native Mem0 support via `Mem0Memory`. Works with ReAct and FunctionCalling agents. - -```python -from llama_index.memory.mem0 import Mem0Memory - -context = {"user_id": "alice", "agent_id": "llama_agent_1"} -memory = Mem0Memory.from_client( - context=context, - search_msg_limit=4, # messages from chat history used for retrieval (default: 5) -) - -# Use with LlamaIndex agent -from llama_index.core.agent import FunctionCallingAgent -from llama_index.llms.openai import OpenAI - -llm = OpenAI(model="gpt-5-mini") -agent = FunctionCallingAgent.from_tools( - tools=[], - llm=llm, - memory=memory, - verbose=True, -) - -response = agent.chat("I prefer vegetarian restaurants") -# Memory automatically stores and retrieves context -response = agent.chat("What kind of food do I like?") -# Agent retrieves the vegetarian preference from Mem0 -``` - ---- - -## AutoGen - -Source: [docs.mem0.ai/integrations/autogen](https://docs.mem0.ai/integrations/autogen) - -Install: `pip install autogen mem0ai` - -Multi-agent conversational systems with memory persistence. - -```python -from autogen import ConversableAgent -from mem0 import MemoryClient - -memory_client = MemoryClient() -USER_ID = "alice" - -agent = ConversableAgent( - "chatbot", - llm_config={"config_list": [{"model": "gpt-5-mini", "api_key": os.environ["OPENAI_API_KEY"]}]}, - code_execution_config=False, - human_input_mode="NEVER", -) - -def get_context_aware_response(question: str) -> str: - # Retrieve memories for context - relevant_memories = memory_client.search(question, filters={"user_id": USER_ID}) - context = "\n".join([m["memory"] for m in relevant_memories.get("results", [])]) - - prompt = f"""Answer considering previous interactions: - Previous context: {context} - Question: {question}""" - - reply = agent.generate_reply(messages=[{"content": prompt, "role": "user"}]) - - # Store the new interaction - memory_client.add( - [{"role": "user", "content": question}, {"role": "assistant", "content": reply}], - user_id=USER_ID - ) - return reply -``` - ---- - -## All Supported Frameworks - -Beyond the examples above, Mem0 integrates with: - -| Framework | Type | Install | -|-----------|------|---------| -| [Mastra](https://docs.mem0.ai/integrations/mastra) | TS agent framework | `npm install @mastra/mem0` | -| [ElevenLabs](https://docs.mem0.ai/integrations/elevenlabs) | Voice AI | `pip install elevenlabs mem0ai` | -| [LiveKit](https://docs.mem0.ai/integrations/livekit) | Real-time voice/video | `pip install livekit-agents mem0ai` | -| [Camel AI](https://docs.mem0.ai/integrations/camel-ai) | Multi-agent framework | `pip install camel-ai[all] mem0ai` | -| [AWS Bedrock](https://docs.mem0.ai/integrations/aws-bedrock) | Cloud LLM provider | `pip install boto3 mem0ai` | -| [Dify](https://docs.mem0.ai/integrations/dify) | Low-code AI platform | Plugin-based | -| [Google AI ADK](https://docs.mem0.ai/integrations/google-ai-adk) | Google agent framework | `pip install google-adk mem0ai` | - -For the general Python pattern (no framework), see the "Common integration pattern" in [SKILL.md](../SKILL.md). diff --git a/integrations/mem0-plugin/skills/mem0/references/quickstart.md b/integrations/mem0-plugin/skills/mem0/references/quickstart.md deleted file mode 100644 index 132982a49..000000000 --- a/integrations/mem0-plugin/skills/mem0/references/quickstart.md +++ /dev/null @@ -1,119 +0,0 @@ -# Mem0 Platform Quickstart - -Get running with Mem0 in 2 minutes. No infrastructure to deploy -- just an API key. - -## Prerequisites - -- Python 3.10+ or Node.js 18+ -- A Mem0 Platform API key ([Get one here](https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=mem0-plugin-skill-quickstart)) - -## Python Setup - -```bash -pip install mem0ai -export MEM0_API_KEY="m0-your-api-key" -``` - -```python -from mem0 import MemoryClient - -client = MemoryClient(api_key="your-api-key") - -# Add a memory -messages = [ - {"role": "user", "content": "I'm a vegetarian and allergic to nuts."}, - {"role": "assistant", "content": "Got it! I'll remember your dietary preferences."} -] -client.add(messages, user_id="user123") - -# Search memories -results = client.search("What are my dietary restrictions?", filters={"user_id": "user123"}) -print(results) -``` - -### Async Client - -```python -from mem0 import AsyncMemoryClient - -client = AsyncMemoryClient(api_key="your-api-key") - -await client.add(messages, user_id="user123") -results = await client.search("query", filters={"user_id": "user123"}) -``` - -## TypeScript / JavaScript Setup - -```bash -npm install mem0ai -export MEM0_API_KEY="m0-your-api-key" -``` - -```javascript -import MemoryClient from 'mem0ai'; - -const client = new MemoryClient({ apiKey: 'your-api-key' }); - -// Add a memory -const messages = [ - {"role": "user", "content": "I'm a vegetarian and allergic to nuts."}, - {"role": "assistant", "content": "Got it! I'll remember your dietary preferences."} -]; -await client.add(messages, { userId: "user123" }); - -// Search memories -const results = await client.search("What are my dietary restrictions?", { - filters: { user_id: "user123" } -}); -console.log(results); -``` - -## cURL - -```bash -export MEM0_API_KEY="m0-your-api-key" - -# Add memory -curl -X POST https://api.mem0.ai/v3/memories/add/ \ - -H "Authorization: Token $MEM0_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "messages": [ - {"role": "user", "content": "I am a vegetarian and allergic to nuts."}, - {"role": "assistant", "content": "Got it! I will remember your dietary preferences."} - ], - "user_id": "user123" - }' - -# Search memories -curl -X POST https://api.mem0.ai/v3/memories/search/ \ - -H "Authorization: Token $MEM0_API_KEY" \ - -H "Content-Type: application/json" \ - -d '{ - "query": "What are my dietary restrictions?", - "filters": {"user_id": "user123"} - }' -``` - -## Sample Response - -```json -{ - "results": [ - { - "id": "14e1b28a-2014-40ad-ac42-69c9ef42193d", - "memory": "Allergic to nuts", - "user_id": "user123", - "categories": ["health"], - "created_at": "2025-10-22T04:40:22.864647-07:00", - "score": 0.30 - } - ] -} -``` - -## Next Steps - -- [SDK Guide](sdk-guide.md) -- all methods for Python and TypeScript -- [API Reference](api-reference.md) -- REST endpoints and memory object structure -- [Integration Patterns](integration-patterns.md) -- LangChain, CrewAI, Vercel AI, etc. diff --git a/integrations/mem0-plugin/skills/mem0/references/sdk-guide.md b/integrations/mem0-plugin/skills/mem0/references/sdk-guide.md deleted file mode 100644 index 512c0d19c..000000000 --- a/integrations/mem0-plugin/skills/mem0/references/sdk-guide.md +++ /dev/null @@ -1,353 +0,0 @@ -# Mem0 SDK Guide - -Complete SDK reference for Python and TypeScript. All methods use `MemoryClient` (Platform API). - -> **For language-specific deep references (including OSS):** See [client/python.md](../client/python.md) and [client/node.md](../client/node.md). For Python vs TypeScript differences: [client/differences.md](../client/differences.md). - -## Initialization - -**Python:** -```python -from mem0 import MemoryClient -client = MemoryClient(api_key="m0-your-api-key") -``` - -**Python (Async):** -```python -from mem0 import AsyncMemoryClient -client = AsyncMemoryClient(api_key="m0-your-api-key") -``` - -**TypeScript:** -```typescript -import MemoryClient from 'mem0ai'; -const client = new MemoryClient({ apiKey: 'm0-your-api-key' }); -``` - -Constructor accepts `apiKey` (required) and `host` (optional, default: `https://api.mem0.ai`). - ---- - -## add() -- Store Memories - -**Python:** -```python -messages = [ - {"role": "user", "content": "I'm a vegetarian and allergic to nuts."}, - {"role": "assistant", "content": "Got it! I'll remember that."} -] -client.add(messages, user_id="alice") - -# With metadata -client.add(messages, user_id="alice", metadata={"source": "onboarding"}) -``` - -**TypeScript:** -```typescript -await client.add(messages, { userId: "alice" }); -await client.add(messages, { userId: "alice", metadata: { source: "onboarding" } }); -``` - -### Parameters - -| Name | Type | Description | -|------|------|-------------| -| `messages` | array | `[{"role": "user", "content": "..."}]` | -| `user_id` | string | User identifier (recommended) | -| `agent_id` | string | Agent identifier | -| `run_id` | string | Session identifier | -| `metadata` | object | Custom key-value pairs | -| `infer` | boolean | If `false`, store raw text without inference (default: `true`) | - -### Advanced Add Options - -```python -# Agent + session scoping -client.add(messages, user_id="alice", agent_id="nutrition-agent", run_id="session-456") - -# Raw text -- skip LLM inference -client.add( - [{"role": "user", "content": "User prefers dark mode."}], - user_id="alice", - infer=False, -) -``` - ---- - -## search() -- Find Memories - -**Python:** -```python -results = client.search("dietary preferences?", filters={"user_id": "alice"}) - -# With filters and reranking -results = client.search( - query="work experience", - filters={"AND": [{"user_id": "alice"}, {"categories": {"contains": "professional_details"}}]}, - top_k=5, - rerank=True, - threshold=0.5 -) -``` - -**TypeScript:** -```typescript -const results = await client.search("dietary preferences", { filters: { user_id: "alice" } }); -const results = await client.search("work experience", { - filters: { AND: [{ user_id: "alice" }, { categories: { contains: "professional_details" } }] }, - topK: 5, - rerank: true, -}); -``` - -### Parameters - -| Name | Type | Description | -|------|------|-------------| -| `query` | string | Natural language search query | -| `filters` | object | Filter object (AND/OR operators). Use `{"user_id": "..."}` to filter by user | -| `top_k` | number | Number of results (default: 10 for Platform) | -| `rerank` | boolean | Enable reranking for better relevance (default: `false`) | -| `threshold` | number | Minimum similarity score (default: 0.1) | - -### Common Filter Patterns - -**Python:** -```python -# Single user filter -filters={"user_id": "alice"} - -# OR across agents -filters={"OR": [{"user_id": "alice"}, {"agent_id": {"in": ["travel-agent", "sports-agent"]}}]} - -# Category filtering (partial match) -filters={"AND": [{"user_id": "alice"}, {"categories": {"contains": "finance"}}]} - -# Category filtering (exact match) -filters={"AND": [{"user_id": "alice"}, {"categories": {"in": ["personal_information"]}}]} - -# Wildcard (match any non-null run) -filters={"AND": [{"user_id": "alice"}, {"run_id": "*"}]} - -# Date range -filters={"AND": [ - {"user_id": "alice"}, - {"created_at": {"gte": "2024-01-01T00:00:00Z"}}, - {"created_at": {"lt": "2024-02-01T00:00:00Z"}} -]} - -# Exclude categories with NOT -filters={"AND": [{"user_id": "user_123"}, {"NOT": {"categories": {"in": ["spam", "test"]}}}]} - -# Multi-dimensional query -filters={"AND": [ - {"user_id": "user_123"}, - {"keywords": {"icontains": "invoice"}}, - {"categories": {"in": ["finance"]}}, - {"created_at": {"gte": "2024-01-01T00:00:00Z"}} -]} -``` - -**TypeScript:** -```typescript -// Single user filter -filters: { user_id: "alice" } - -// OR across agents -filters: { OR: [{ user_id: "alice" }, { agent_id: { in: ["travel-agent", "sports-agent"] } }] } - -// Category filtering (partial match) -filters: { AND: [{ user_id: "alice" }, { categories: { contains: "finance" } }] } - -// Category filtering (exact match) -filters: { AND: [{ user_id: "alice" }, { categories: { in: ["personal_information"] } }] } -``` - ---- - -## get() / getAll() -- Retrieve Memories - -**Python:** -```python -# Single memory by ID -memory = client.get(memory_id="ea925981-...") - -# All memories for a user -memories = client.get_all(filters={"user_id": "alice"}) - -# With date range -memories = client.get_all( - filters={"AND": [ - {"user_id": "alex"}, - {"created_at": {"gte": "2024-07-01", "lte": "2024-07-31"}} - ]} -) -``` - -**TypeScript:** -```typescript -const memory = await client.get("ea925981-..."); -const memories = await client.getAll({ filters: { user_id: "alice" } }); -``` - -**Note:** `get_all` requires at least one of `user_id`, `agent_id`, `app_id`, or `run_id` in filters. - ---- - -## update() -- Modify Memories - -**Python:** -```python -client.update(memory_id="ea925981-...", text="Updated: vegan since 2024") -client.update(memory_id="ea925981-...", text="Updated", metadata={"verified": True}) -``` - -**TypeScript:** -```typescript -await client.update("ea925981-...", { text: "Updated: vegan since 2024" }); -``` - ---- - -## delete() / deleteAll() -- Remove Memories - -**Python:** -```python -client.delete(memory_id="ea925981-...") -client.delete_all(user_id="alice") # Irreversible bulk delete -``` - -**TypeScript:** -```typescript -await client.delete("ea925981-..."); -await client.deleteAll({ userId: "alice" }); -``` - ---- - -## history() -- Track Changes - -**Python:** -```python -history = client.history(memory_id="ea925981-...") -# Returns: [{previous_value, new_value, action, timestamps}] -``` - -**TypeScript:** -```typescript -const history = await client.history("ea925981-..."); -``` - ---- - -## Batch Operations (TypeScript) - -```typescript -// Batch update -await client.batchUpdate([ - { memoryId: "uuid-1", text: "Updated text" }, - { memoryId: "uuid-2", text: "Another updated text" }, -]); - -// Batch delete -await client.batchDelete(["uuid-1", "uuid-2", "uuid-3"]); -``` - ---- - -## Additional Methods - -```python -# List all users/agents/sessions with memories -users = client.users() - -# Delete a user/agent entity -client.delete_users(user_id="alice") - -# Submit feedback on a memory -client.feedback(memory_id="...", feedback="POSITIVE", feedback_reason="Accurate extraction") - -# Export memories -export = client.create_memory_export(filters={"AND": [{"user_id": "alice"}]}) -data = client.get_memory_export(memory_export_id=export["id"]) -``` - ---- - -## Common Pitfalls - -1. **Entity cross-filtering fails silently** -- `AND` with `user_id` + `agent_id` returns empty. Use `OR`. -2. **SQL operators rejected** -- use `gte`, `lt`, etc. Not `>=`, `<`. -3. **Metadata filtering is limited** -- only top-level keys with `eq`, `contains`, `ne`. -4. **Wildcard `*` excludes null** -- only matches non-null values. -5. **Default threshold is 0.1** -- increase for stricter matching. -6. **Async processing** -- memories process asynchronously. Wait 2-3s after `add()` before searching. - -## Naming Conventions - -Python uses `snake_case` everywhere (`user_id`, `memory_id`, `get_all`). TypeScript uses `camelCase` for methods (`getAll`, `deleteAll`, `batchUpdate`) and top-level parameters (`userId`, `topK`, `pageSize`), but filter keys use `snake_case` (`user_id`, `agent_id`). - ---- - -## v2 to v3 Migration - -### Breaking Changes in v3 - -**1. Entity IDs in search() and getAll()** - -v3 requires entity IDs (`user_id`, `agent_id`, `run_id`) inside `filters` instead of as top-level parameters: - -```python -# v2 (deprecated) -client.search("query", user_id="alice") -client.get_all(user_id="alice") - -# v3 -client.search("query", filters={"user_id": "alice"}) -client.get_all(filters={"user_id": "alice"}) -``` - -```typescript -// v2 (deprecated) -await client.search("query", { user_id: "alice" }); -await client.getAll({ user_id: "alice" }); - -// v3 -await client.search("query", { filters: { user_id: "alice" } }); -await client.getAll({ filters: { user_id: "alice" } }); -``` - -**2. TypeScript Parameter Naming** - -v3 TypeScript uses camelCase for all parameters: - -| v2 | v3 | -|----|-----| -| `user_id` | `userId` | -| `agent_id` | `agentId` | -| `run_id` | `runId` | -| `top_k` | `topK` | -| `page_size` | `pageSize` | - -**3. Default Values Changed** - -| Parameter | v2 Default | v3 Default | -|-----------|------------|------------| -| `threshold` | 0.3 | 0.1 | -| `rerank` | (not specified) | `false` | - -**4. Removed Parameters** - -The following parameters are no longer supported: - -| Parameter | Status | -|-----------|--------| -| `enable_graph` | Removed from add/search/getAll | -| `keyword_search` | Removed from search | -| `filter_memories` | Removed | -| `immutable` | Removed from add | -| `expiration_date` | Removed from add | -| `includes` | Removed from add | -| `excludes` | Removed from add | -| `async_mode` | Removed from add | diff --git a/integrations/mem0-plugin/skills/mem0/references/use-cases.md b/integrations/mem0-plugin/skills/mem0/references/use-cases.md deleted file mode 100644 index 5f3ba655d..000000000 --- a/integrations/mem0-plugin/skills/mem0/references/use-cases.md +++ /dev/null @@ -1,720 +0,0 @@ -# Mem0 Use Cases & Examples - -Real-world implementation patterns for Mem0 Platform. Each use case includes complete, runnable code in both Python and TypeScript. - -## Table of Contents - -- [Personalized AI Companion](#1-personalized-ai-companion) -- [Customer Support with Categories](#2-customer-support-with-categories) -- [Healthcare Coach](#3-healthcare-coach) -- [Content Creation Workflow](#4-content-creation-workflow) -- [Multi-Agent / Multi-Tenant](#5-multi-agent--multi-tenant) -- [Personalized Search](#6-personalized-search) -- [Email Intelligence](#7-email-intelligence) -- [Common Patterns Across Use Cases](#common-patterns-across-use-cases) - ---- - -## 1. Personalized AI Companion - -A fitness coach that remembers goals, preferences, and progress across sessions. Mem0 persists context across app restarts — no session state needed. - -### Implementation (Python) - -```python -from mem0 import MemoryClient -from openai import OpenAI - -mem0 = MemoryClient() -openai_client = OpenAI() - -def chat(user_input: str, user_id: str) -> str: - # 1. Retrieve relevant memories - memories = mem0.search(user_input, user_id=user_id) - context = "\n".join([f"- {m['memory']}" for m in memories.get("results", [])]) - - # 2. Generate response with memory context - system_prompt = f"""You are Ray, a personal fitness coach. -Use these known facts about the user to personalize your response: -{context if context else 'No prior context yet.'}""" - - response = openai_client.chat.completions.create( - model="gpt-5-mini", - messages=[ - {"role": "system", "content": system_prompt}, - {"role": "user", "content": user_input}, - ] - ) - reply = response.choices[0].message.content - - # 3. Store interaction for future context - mem0.add( - [{"role": "user", "content": user_input}, {"role": "assistant", "content": reply}], - user_id=user_id - ) - return reply - -# Usage -chat("I want to run a marathon in under 4 hours", user_id="max") -# Next day, app restarted: -chat("What should I focus on today?", user_id="max") -# Ray remembers the sub-4 marathon goal -``` - -### Implementation (TypeScript) - -```typescript -import MemoryClient from 'mem0ai'; -import OpenAI from 'openai'; - -const mem0 = new MemoryClient({ apiKey: process.env.MEM0_API_KEY! }); -const openai = new OpenAI(); - -async function chat(userInput: string, userId: string): Promise { - // 1. Retrieve relevant memories - const memories = await mem0.search(userInput, { filters: { user_id: userId } }); - const context = memories.results - ?.map((m: any) => `- ${m.memory}`) - .join('\n') || 'No prior context yet.'; - - // 2. Generate response with memory context - const response = await openai.chat.completions.create({ - model: 'gpt-5-mini', - messages: [ - { role: 'system', content: `You are Ray, a personal fitness coach.\nUser context:\n${context}` }, - { role: 'user', content: userInput }, - ], - }); - const reply = response.choices[0].message.content!; - - // 3. Store interaction - await mem0.add( - [{ role: 'user', content: userInput }, { role: 'assistant', content: reply }], - { userId: userId } - ); - return reply; -} -``` - -### Key Benefits - -- Context persists across app restarts — no session management needed -- Memories are automatically deduplicated and updated -- Works with any LLM provider (OpenAI, Anthropic, etc.) - -**Best for:** Fitness coaches, tutors, therapists — any assistant that needs to remember goals across sessions. - ---- - -## 2. Customer Support with Categories - -Auto-categorize support data so teams retrieve the right facts fast. Uses custom categories for structured retrieval. - -### Implementation (Python) - -```python -from mem0 import MemoryClient - -client = MemoryClient() - -# 1. Define categories at the project level (one-time setup) -custom_categories = [ - {"support_tickets": "Customer issues and resolutions"}, - {"account_info": "Account details and preferences"}, - {"billing": "Payment history and billing questions"}, - {"product_feedback": "Feature requests and feedback"}, -] -client.project.update(custom_categories=custom_categories) - -# 2. Store interactions — auto-classified into categories -def log_support_interaction(user_id: str, message: str, priority: str = "normal"): - client.add( - [{"role": "user", "content": message}], - user_id=user_id, - metadata={"priority": priority, "source": "support_chat"} - ) - -# 3. Retrieve by category -def get_billing_issues(user_id: str): - return client.get_all( - filters={ - "AND": [ - {"user_id": user_id}, - {"categories": {"in": ["billing"]}} - ] - } - ) - -def search_support_history(user_id: str, query: str): - return client.search( - query, - filters={ - "AND": [ - {"user_id": user_id}, - {"categories": {"contains": "support_tickets"}} - ] - }, - top_k=5 - ) - -# Usage -log_support_interaction("maria", "I was charged twice for last month's subscription", priority="high") -log_support_interaction("maria", "The dashboard is loading slowly on mobile") -billing = get_billing_issues("maria") # Returns only billing-related memories -``` - -### Implementation (TypeScript) - -```typescript -import MemoryClient from 'mem0ai'; - -const client = new MemoryClient({ apiKey: process.env.MEM0_API_KEY! }); - -// Setup categories (one-time) -await client.updateProject({ - custom_categories: [ - { support_tickets: 'Customer issues and resolutions' }, - { billing: 'Payment history and billing questions' }, - { product_feedback: 'Feature requests and feedback' }, - ], -}); - -async function logInteraction(userId: string, message: string, priority = 'normal') { - await client.add( - [{ role: 'user', content: message }], - { userId: userId, metadata: { priority, source: 'support_chat' } } - ); -} - -async function getBillingIssues(userId: string) { - return client.getAll({ - filters: { AND: [{ user_id: userId }, { categories: { in: ['billing'] } }] }, - }); -} -``` - -### Key Benefits - -- Automatic categorization — no manual tagging -- Filter by category for structured retrieval -- Metadata (`priority`, `source`) enables multi-dimensional queries - -**Best for:** Help desks, SaaS support, e-commerce — structured retrieval by category eliminates manual scanning. - ---- - -## 3. Healthcare Coach - -Guide patients with an assistant that remembers medical history. Uses high `threshold` for confident retrieval in safety-critical contexts. - -### Implementation (Python) - -```python -from mem0 import MemoryClient -from openai import OpenAI - -mem0 = MemoryClient() -openai_client = OpenAI() - -def save_patient_info(user_id: str, information: str): - mem0.add( - [{"role": "user", "content": information}], - user_id=user_id, - run_id="healthcare_session", - metadata={"type": "patient_information"} - ) - -def consult(user_id: str, question: str) -> str: - # High threshold for medical accuracy - memories = mem0.search(question, user_id=user_id, top_k=5, threshold=0.7) - context = "\n".join([f"- {m['memory']}" for m in memories.get("results", [])]) - - response = openai_client.chat.completions.create( - model="gpt-5-mini", - messages=[ - {"role": "system", "content": f"You are a health coach. Patient context:\n{context}"}, - {"role": "user", "content": question}, - ] - ) - reply = response.choices[0].message.content - - # Store the interaction - mem0.add( - [{"role": "user", "content": question}, {"role": "assistant", "content": reply}], - user_id=user_id, - run_id="healthcare_session", - ) - return reply - -# Usage -save_patient_info("alex", "I'm allergic to penicillin and take metformin for type 2 diabetes") -consult("alex", "Can I take amoxicillin for my sore throat?") -# Remembers penicillin allergy — amoxicillin is a penicillin-type antibiotic -``` - -### Implementation (TypeScript) - -```typescript -import MemoryClient from 'mem0ai'; -import OpenAI from 'openai'; - -const mem0 = new MemoryClient({ apiKey: process.env.MEM0_API_KEY! }); -const openai = new OpenAI(); - -async function savePatientInfo(userId: string, info: string) { - await mem0.add( - [{ role: 'user', content: info }], - { userId: userId, runId: 'healthcare_session', metadata: { type: 'patient_information' } } - ); -} - -async function consult(userId: string, question: string): Promise { - const memories = await mem0.search(question, { - filters: { user_id: userId }, - topK: 5, - threshold: 0.7, - }); - const context = memories.results?.map((m: any) => `- ${m.memory}`).join('\n') || ''; - - const response = await openai.chat.completions.create({ - model: 'gpt-5-mini', - messages: [ - { role: 'system', content: `You are a health coach. Patient context:\n${context}` }, - { role: 'user', content: question }, - ], - }); - const reply = response.choices[0].message.content!; - - await mem0.add( - [{ role: 'user', content: question }, { role: 'assistant', content: reply }], - { userId: userId, runId: 'healthcare_session' } - ); - return reply; -} -``` - -### Key Benefits - -- High threshold (0.7) ensures only confident matches for safety-critical retrieval -- Session scoping via `run_id` groups related health interactions -- Metadata tagging separates patient info from conversation history - -**Best for:** Telehealth, wellness apps, patient management — persistent health context across visits. - ---- - -## 4. Content Creation Workflow - -Store voice guidelines once and apply them across every draft. Uses `run_id` and `metadata` to scope writing preferences per session. - -### Implementation (Python) - -```python -from mem0 import MemoryClient -from openai import OpenAI - -mem0 = MemoryClient() -openai_client = OpenAI() - -def store_writing_preferences(user_id: str, preferences: str): - mem0.add( - [{"role": "user", "content": preferences}], - user_id=user_id, - run_id="editing_session", - metadata={"type": "preferences", "category": "writing_style"} - ) - -def draft_content(user_id: str, topic: str) -> str: - # Retrieve writing preferences - prefs = mem0.search( - "writing style preferences", - filters={"AND": [{"user_id": user_id}, {"run_id": "editing_session"}]} - ) - style_context = "\n".join([f"- {m['memory']}" for m in prefs.get("results", [])]) - - response = openai_client.chat.completions.create( - model="gpt-5-mini", - messages=[ - {"role": "system", "content": f"Write content matching these style preferences:\n{style_context}"}, - {"role": "user", "content": f"Write a blog post about: {topic}"}, - ] - ) - return response.choices[0].message.content - -# Usage -store_writing_preferences("writer_01", "I prefer short sentences. Active voice. No jargon. Use analogies.") -draft_content("writer_01", "Why AI memory matters for chatbots") -# Drafts content matching the stored voice guidelines -``` - -### Implementation (TypeScript) - -```typescript -import MemoryClient from 'mem0ai'; -import OpenAI from 'openai'; - -const mem0 = new MemoryClient({ apiKey: process.env.MEM0_API_KEY! }); -const openai = new OpenAI(); - -async function storePreferences(userId: string, preferences: string) { - await mem0.add( - [{ role: 'user', content: preferences }], - { userId: userId, runId: 'editing_session', metadata: { type: 'preferences' } } - ); -} - -async function draftContent(userId: string, topic: string): Promise { - const prefs = await mem0.search('writing style preferences', { - filters: { AND: [{ user_id: userId }, { run_id: 'editing_session' }] }, - }); - const styleContext = prefs.results?.map((m: any) => `- ${m.memory}`).join('\n') || ''; - - const response = await openai.chat.completions.create({ - model: 'gpt-5-mini', - messages: [ - { role: 'system', content: `Write content matching these preferences:\n${styleContext}` }, - { role: 'user', content: `Write a blog post about: ${topic}` }, - ], - }); - return response.choices[0].message.content!; -} -``` - -### Key Benefits - -- Voice consistency across all content without repeating guidelines -- Scoped sessions let you maintain different style profiles -- Preferences update automatically as you refine them - -**Best for:** Marketing teams, technical writers, agencies — consistent voice across all content. - ---- - -## 5. Multi-Agent / Multi-Tenant - -Keep memories separate using `user_id`, `agent_id`, `app_id`, and `run_id` scoping. Critical for multi-agent workflows and multi-tenant apps. - -### Implementation (Python) - -```python -from mem0 import MemoryClient - -client = MemoryClient() - -# Store memories scoped to user + agent + session -def store_scoped_memory(messages: list, user_id: str, agent_id: str, run_id: str, app_id: str): - client.add( - messages, - user_id=user_id, - agent_id=agent_id, - run_id=run_id, - app_id=app_id - ) - -# Query within a specific scope -def search_user_session(query: str, user_id: str, app_id: str, run_id: str): - """Search memories for a specific user within a specific session.""" - return client.search( - query, - filters={ - "AND": [ - {"user_id": user_id}, - {"app_id": app_id}, - {"run_id": run_id} - ] - } - ) - -def search_agent_knowledge(query: str, agent_id: str, app_id: str): - """Search all memories an agent has across all users.""" - return client.search( - query, - filters={ - "AND": [ - {"agent_id": agent_id}, - {"app_id": app_id} - ] - } - ) - -# Usage: Travel concierge app with multiple agents -store_scoped_memory( - [{"role": "user", "content": "I'm vegetarian and prefer window seats"}], - user_id="traveler_cam", - agent_id="travel_planner", - run_id="tokyo-2025", - app_id="concierge_app" -) - -# User-scoped query: "What does Cam prefer?" -user_mems = search_user_session("dietary restrictions?", "traveler_cam", "concierge_app", "tokyo-2025") - -# Agent-scoped query: "What do all travelers prefer?" (across users) -agent_mems = search_agent_knowledge("common dietary restrictions?", "travel_planner", "concierge_app") -``` - -### Implementation (TypeScript) - -```typescript -import MemoryClient from 'mem0ai'; - -const client = new MemoryClient({ apiKey: process.env.MEM0_API_KEY! }); - -async function storeScopedMemory( - messages: Array<{ role: string; content: string }>, - userId: string, agentId: string, runId: string, appId: string -) { - await client.add(messages, { - userId: userId, - agentId: agentId, - runId: runId, - appId: appId, - }); -} - -async function searchUserSession(query: string, userId: string, appId: string, runId: string) { - return client.search(query, { - filters: { AND: [{ user_id: userId }, { app_id: appId }, { run_id: runId }] }, - }); -} - -async function searchAgentKnowledge(query: string, agentId: string, appId: string) { - return client.search(query, { - filters: { AND: [{ agent_id: agentId }, { app_id: appId }] }, - }); -} -``` - -### Key Benefits - -- Full isolation between users, agents, sessions, and apps -- Query at any scope level — user, agent, session, or app-wide -- No memory leakage between tenants - -**Best for:** Multi-agent workflows, multi-tenant SaaS — proper isolation at every level. - ---- - -## 6. Personalized Search - -Blend real-time search results with personal context. Uses `custom_instructions` to infer preferences from queries. - -### Implementation (Python) - -```python -from mem0 import MemoryClient -from openai import OpenAI - -mem0 = MemoryClient() -openai_client = OpenAI() - -# One-time setup: configure Mem0 to infer from queries -mem0.project.update( - custom_instructions="""Infer user preferences and facts from their search queries. -Extract dietary preferences, location, interests, and purchase history.""" -) - -def personalized_search(user_id: str, query: str, search_results: list) -> str: - # Get user context from memory - memories = mem0.search(query, user_id=user_id, top_k=5) - user_context = "\n".join([f"- {m['memory']}" for m in memories.get("results", [])]) - - response = openai_client.chat.completions.create( - model="gpt-5-mini", - messages=[ - {"role": "system", "content": f"Personalize search results using user context:\n{user_context}"}, - {"role": "user", "content": f"Query: {query}\n\nSearch results:\n{search_results}"}, - ] - ) - reply = response.choices[0].message.content - - # Store the query to learn preferences over time - mem0.add( - [{"role": "user", "content": query}], - user_id=user_id - ) - return reply - -# Usage -personalized_search("user_42", "best restaurants nearby", ["Restaurant A", "Restaurant B"]) -# Over time, Mem0 learns: "user prefers vegetarian, lives in Austin" -# Future searches are automatically personalized -``` - -### Implementation (TypeScript) - -```typescript -import MemoryClient from 'mem0ai'; -import OpenAI from 'openai'; - -const mem0 = new MemoryClient({ apiKey: process.env.MEM0_API_KEY! }); -const openai = new OpenAI(); - -async function personalizedSearch(userId: string, query: string, searchResults: string[]): Promise { - const memories = await mem0.search(query, { filters: { user_id: userId }, topK: 5 }); - const context = memories.results?.map((m: any) => `- ${m.memory}`).join('\n') || ''; - - const response = await openai.chat.completions.create({ - model: 'gpt-5-mini', - messages: [ - { role: 'system', content: `Personalize results using user context:\n${context}` }, - { role: 'user', content: `Query: ${query}\nResults: ${searchResults.join(', ')}` }, - ], - }); - const reply = response.choices[0].message.content!; - - await mem0.add([{ role: 'user', content: query }], { userId: userId }); - return reply; -} -``` - -### Key Benefits - -- Learns preferences from queries automatically via `custom_instructions` -- Personalizes any search provider (Tavily, Google, Bing) -- Zero manual preference setup — improves over time - -**Best for:** Personalized search engines, recommendation systems — search results tailored to individual users. - ---- - -## 7. Email Intelligence - -Capture, categorize, and recall inbox threads using persistent memories with rich metadata. - -### Implementation (Python) - -```python -from mem0 import MemoryClient - -client = MemoryClient() - -def store_email(user_id: str, sender: str, subject: str, body: str, date: str): - client.add( - [{"role": "user", "content": f"Email from {sender}: {subject}\n\n{body}"}], - user_id=user_id, - metadata={"email_type": "incoming", "sender": sender, "subject": subject, "date": date} - ) - -def search_emails(user_id: str, query: str): - return client.search( - query, - filters={"AND": [{"user_id": user_id}, {"categories": {"contains": "email"}}]}, - top_k=10 - ) - -def get_emails_from_sender(user_id: str, sender: str): - return client.get_all( - filters={ - "AND": [ - {"user_id": user_id}, - {"metadata": {"contains": sender}} - ] - } - ) - -# Usage -store_email("alice", "bob@acme.com", "Q3 Budget Review", "Attached is the Q3 budget...", "2025-01-15") -store_email("alice", "carol@acme.com", "Sprint Planning", "Here are the priorities...", "2025-01-16") - -results = search_emails("alice", "budget discussions") -sender_emails = get_emails_from_sender("alice", "bob@acme.com") -``` - -### Implementation (TypeScript) - -```typescript -import MemoryClient from 'mem0ai'; - -const client = new MemoryClient({ apiKey: process.env.MEM0_API_KEY! }); - -async function storeEmail(userId: string, sender: string, subject: string, body: string, date: string) { - await client.add( - [{ role: 'user', content: `Email from ${sender}: ${subject}\n\n${body}` }], - { userId: userId, metadata: { email_type: 'incoming', sender, subject, date } } - ); -} - -async function searchEmails(userId: string, query: string) { - return client.search(query, { - filters: { AND: [{ user_id: userId }, { categories: { contains: 'email' } }] }, - topK: 10, - }); -} -``` - -### Key Benefits - -- Rich metadata enables multi-dimensional queries (sender, date, subject) -- Category filtering separates emails from other memory types -- Semantic search across all email content - -**Best for:** Inbox management, email automation — searchable email memories with metadata filtering. - ---- - -## Common Patterns Across Use Cases - -### Pattern 1: Retrieve → Generate → Store - -Every use case follows the same 3-step loop: - -```python -# 1. Retrieve relevant context -memories = mem0.search(user_input, user_id=user_id) -context = "\n".join([m["memory"] for m in memories.get("results", [])]) - -# 2. Generate with context -response = llm.generate(system_prompt=f"Context:\n{context}", user_input=user_input) - -# 3. Store the interaction -mem0.add( - [{"role": "user", "content": user_input}, {"role": "assistant", "content": response}], - user_id=user_id -) -``` - -### Pattern 2: Scope with Entity Identifiers - -Use `user_id`, `agent_id`, `app_id`, and `run_id` to isolate memories: - -```python -# User-level: personal preferences -client.add(messages, user_id="alice") - -# Session-level: conversation within one session -client.add(messages, user_id="alice", run_id="session_123") - -# Agent-level: agent-specific knowledge -client.add(messages, agent_id="support_bot", app_id="helpdesk") -``` - -### Pattern 3: Rich Metadata for Filtering - -Attach structured metadata for multi-dimensional queries: - -```python -# Store with metadata -client.add(messages, user_id="alice", metadata={"priority": "high", "source": "phone_call"}) - -# Filter by category + metadata -client.search("billing issues", filters={ - "AND": [{"user_id": "alice"}, {"categories": {"contains": "billing"}}] -}) -``` - -### Pattern 4: Custom Instructions for Domain-Specific Extraction - -Control what Mem0 extracts from conversations: - -```python -client.project.update( - custom_instructions="Extract medical conditions, medications, and allergies. Exclude billing info." -) -``` - ---- - -## More Examples - -For 30+ cookbooks with complete working code: [docs.mem0.ai/cookbooks](https://docs.mem0.ai/cookbooks) diff --git a/integrations/mem0-plugin/skills/mem0/scripts/mem0_doc_search.py b/integrations/mem0-plugin/skills/mem0/scripts/mem0_doc_search.py deleted file mode 100755 index a04c89afb..000000000 --- a/integrations/mem0-plugin/skills/mem0/scripts/mem0_doc_search.py +++ /dev/null @@ -1,220 +0,0 @@ -#!/usr/bin/env python3 -""" -Mem0 Documentation Search Agent (Mintlify-based) -On-demand search tool for querying Mem0 documentation without storing content locally. - -This tool leverages Mintlify's documentation structure to perform just-in-time -retrieval of technical information from docs.mem0.ai. - -Usage: - python mem0_doc_search.py --query "how to add graph memory" - python mem0_doc_search.py --query "filter syntax for categories" - python mem0_doc_search.py --page "/platform/features/graph-memory" - python mem0_doc_search.py --index - python mem0_doc_search.py --query "webhook events" --section platform - -Purpose: - - Avoid bloating local context with full documentation - - Enable just-in-time retrieval of technical details - - Query specific documentation pages on demand - - Search across the full Mem0 documentation site -""" - -import argparse -import json -import sys -import urllib.error -import urllib.parse -import urllib.request - -DOCS_BASE = "https://docs.mem0.ai" -SEARCH_ENDPOINT = f"{DOCS_BASE}/api/search" -LLMS_INDEX = f"{DOCS_BASE}/llms.txt" - -# Known documentation sections for targeted retrieval -SECTION_MAP = { - "platform": [ - "/platform/overview", - "/platform/quickstart", - "/platform/features", - "/platform/features/graph-memory", - "/platform/features/selective-memory", - "/platform/features/custom-categories", - "/platform/features/v2-memory-filters", - "/platform/features/async-client", - "/platform/features/webhooks", - "/platform/features/multimodal-support", - ], - "api": [ - "/api-reference/memory/add-memories", - "/api-reference/memory/v2-search-memories", - "/api-reference/memory/v2-get-memories", - "/api-reference/memory/get-memory", - "/api-reference/memory/update-memory", - "/api-reference/memory/delete-memory", - ], - "open-source": [ - "/open-source/overview", - "/open-source/python-quickstart", - "/open-source/node-quickstart", - "/open-source/features", - "/open-source/features/graph-memory", - "/open-source/features/rest-api", - "/open-source/configure-components", - ], - "sdks": [ - "/sdks/python", - "/sdks/js", - ], - "integrations": [ - "/integrations", - ], -} - - -def fetch_url(url: str) -> str: - """Fetch content from a URL.""" - req = urllib.request.Request(url, headers={"User-Agent": "Mem0DocSearchAgent/1.0"}) - try: - with urllib.request.urlopen(req, timeout=15) as resp: - return resp.read().decode("utf-8") - except urllib.error.HTTPError as e: - return f"HTTP Error {e.code}: {e.reason}" - except urllib.error.URLError as e: - return f"URL Error: {e.reason}" - - -def search_docs(query: str, section: str | None = None) -> dict: - """ - Search Mem0 documentation using Mintlify's search API. - Falls back to the llms.txt index for keyword matching if the API is unavailable. - """ - # Try Mintlify search API first - params = urllib.parse.urlencode({"query": query}) - search_url = f"{SEARCH_ENDPOINT}?{params}" - - try: - result = fetch_url(search_url) - data = json.loads(result) - if isinstance(data, dict) and data.get("results"): - results = data["results"] - if section and section in SECTION_MAP: - section_paths = SECTION_MAP[section] - results = [r for r in results if any(r.get("url", "").startswith(p) for p in section_paths)] - return {"source": "mintlify_search", "results": results} - except (json.JSONDecodeError, Exception): - pass - - # Fallback: search llms.txt index for matching URLs - index_content = fetch_url(LLMS_INDEX) - query_lower = query.lower() - matching_urls = [] - - for line in index_content.splitlines(): - line = line.strip() - if not line or line.startswith("#"): - continue - if query_lower in line.lower(): - matching_urls.append(line) - - if section and section in SECTION_MAP: - section_paths = SECTION_MAP[section] - matching_urls = [u for u in matching_urls if any(p in u for p in section_paths)] - - return { - "source": "llms_txt_index", - "query": query, - "matching_urls": matching_urls[:20], - "suggestion": "Fetch specific URLs for detailed content", - } - - -def fetch_page(page_path: str) -> dict: - """Fetch a specific documentation page.""" - url = f"{DOCS_BASE}{page_path}" if page_path.startswith("/") else page_path - content = fetch_url(url) - return {"url": url, "content": content[:10000], "truncated": len(content) > 10000} - - -def get_index() -> dict: - """Fetch the full documentation index from llms.txt.""" - content = fetch_url(LLMS_INDEX) - urls = [line.strip() for line in content.splitlines() if line.strip() and not line.startswith("#")] - return {"total_pages": len(urls), "urls": urls, "sections": list(SECTION_MAP.keys())} - - -def list_section(section: str) -> dict: - """List all known pages in a documentation section.""" - if section not in SECTION_MAP: - return {"error": f"Unknown section: {section}", "available": list(SECTION_MAP.keys())} - return { - "section": section, - "pages": [f"{DOCS_BASE}{p}" for p in SECTION_MAP[section]], - } - - -def main(): - parser = argparse.ArgumentParser(description="Search Mem0 documentation on demand") - parser.add_argument("--query", help="Search query for documentation") - parser.add_argument("--page", help="Fetch a specific page path (e.g., /platform/features/graph-memory)") - parser.add_argument("--index", action="store_true", help="Show full documentation index") - parser.add_argument("--section", help="Filter by section or list section pages") - parser.add_argument("--json", action="store_true", help="Output as JSON") - - args = parser.parse_args() - - if args.index: - result = get_index() - elif args.section and not args.query: - result = list_section(args.section) - elif args.page: - result = fetch_page(args.page) - elif args.query: - result = search_docs(args.query, section=args.section) - else: - parser.print_help() - sys.exit(1) - - if args.json: - print(json.dumps(result, indent=2)) - else: - if isinstance(result, dict): - if "results" in result: - print(f"Source: {result.get('source', 'unknown')}") - for r in result["results"]: - print(f" - {r.get('title', 'N/A')}: {r.get('url', 'N/A')}") - if r.get("description"): - print(f" {r['description'][:200]}") - elif "matching_urls" in result: - print(f"Source: {result['source']}") - print(f"Query: {result['query']}") - for url in result["matching_urls"]: - print(f" - {url}") - if result.get("suggestion"): - print(f"\n{result['suggestion']}") - elif "urls" in result: - print(f"Total documentation pages: {result['total_pages']}") - print(f"Sections: {', '.join(result['sections'])}") - for url in result["urls"][:30]: - print(f" - {url}") - if result["total_pages"] > 30: - print(f" ... and {result['total_pages'] - 30} more") - elif "pages" in result: - print(f"Section: {result['section']}") - for page in result["pages"]: - print(f" - {page}") - elif "content" in result: - print(f"URL: {result['url']}") - if result.get("truncated"): - print("[Content truncated to 10000 chars]") - print(result["content"]) - elif "error" in result: - print(f"Error: {result['error']}") - if result.get("available"): - print(f"Available sections: {', '.join(result['available'])}") - else: - print(json.dumps(result, indent=2)) - - -if __name__ == "__main__": - main() diff --git a/integrations/mem0-plugin/skills/memory-reviewer/SKILL.md b/integrations/mem0-plugin/skills/memory-reviewer/SKILL.md deleted file mode 100644 index 4cc7a5970..000000000 --- a/integrations/mem0-plugin/skills/memory-reviewer/SKILL.md +++ /dev/null @@ -1,59 +0,0 @@ ---- -name: memory-reviewer -description: Reviews stored memory quality by detecting duplicates, contradictions, and stale entries with actionable recommendations. Use when search results seem conflicting, before running dream consolidation, or for periodic memory hygiene audits. ---- - -# Memory Reviewer - -Audits memory quality for the active project. Finds duplicates, contradictions, and low-confidence entries. - -## When to use - -- User asks "check my memories", "memory quality", "any duplicates?" -- User runs `/mem0:memory-reviewer` directly -- After a session with 5+ memory writes (suggest proactively) -- After `/mem0:health --deep` identifies issues - -## Steps - -1. **Fetch all memories** for active project via `get_memories` with `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `page_size=200`. Paginate if needed — cap at 200 memories. - -2. **Group by `metadata.type`**. Common types: `decision`, `convention`, `anti_pattern`, `task_learning`, `project_profile`, `user_preference`, `session_state`. - -3. **Scan each group for issues:** - - | Issue | Detection method | - |---|---| - | **Near-duplicates** | >60% noun overlap within same type. Compare memory text after stripping stop words. | - | **Contradictions** | Opposing facts about same topic (e.g., "use PostgreSQL" vs "use MySQL" for same component) | - | **Low-confidence** | `metadata.confidence < 0.3` | - | **Missing type** | No `metadata.type` set | - | **Stale** | `created_at` older than 180 days with no updates | - -4. **Output compact summary:** - -``` -memory-reviewer: project= total= - duplicates: found - contradictions: found - low_confidence: found - untagged: found - stale: found -``` - -5. **If issues found**, list them with memory IDs: - -``` -Issues: - [duplicate] "" ≈ "" [mem0:, mem0:] - [contradiction] "" vs "" [mem0:, mem0:] - [low_conf] "" (confidence: 0.1) [mem0:] -``` - -6. **Suggest action**: "Run `/mem0:dream` to consolidate duplicates and resolve contradictions." - -## Constraints - -- **Read-only** — never modify or delete memories (that's `/mem0:dream`'s job) -- **Max 200 memories** per scan -- Report findings, let user decide on action diff --git a/integrations/mem0-plugin/skills/onboard/SKILL.md b/integrations/mem0-plugin/skills/onboard/SKILL.md deleted file mode 100644 index 896e917ec..000000000 --- a/integrations/mem0-plugin/skills/onboard/SKILL.md +++ /dev/null @@ -1,184 +0,0 @@ ---- -name: onboard -description: Sets up mem0 for a new project including API key configuration, MCP authentication, project file import, and coding categories. Use on first run in a new project, when API key needs updating, or to re-run initial setup after configuration changes. ---- - -# Mem0 Onboarding Wizard - -Run this wizard to set up the mem0 plugin for the current project. Complete in ~60 seconds. - -**IMPORTANT: Execute steps strictly in order (0 → 1 → 2 → 3 → 4 → 5 → 6). Each step depends on the previous one. Do NOT run steps in parallel or skip ahead. Complete one step fully before starting the next.** - -## Step 0: Ensure mem0ai SDK is installed - -The plugin installs the `mem0ai` Python SDK automatically on session start via a venv in `${CLAUDE_PLUGIN_DATA}/venv`. If Step 5 (categories) fails with an import error, run: - -```bash -"${CLAUDE_PLUGIN_ROOT}/scripts/ensure_deps.sh" -``` - -This is silent and idempotent — safe to run anytime. - -## Step 1: Set up API key - -Check if the API key is available from any source: - -```bash -[ -n "${MEM0_API_KEY:-${CLAUDE_PLUGIN_OPTION_API_KEY:-}}" ] && echo "SET" || echo "NOT_SET" -``` - -IMPORTANT: Never run `echo $MEM0_API_KEY` — that prints the secret in plaintext to the conversation log. - -### If API key IS set (output is "SET") - -Print: `- API key found.` and proceed to Step 2. - -### If API key is NOT set (output is "NOT_SET") - -Guide the user through API key setup. Show this message: - -``` -Step 1: Setting up API key. - -- API key not found. Let's set it up. - - 1. Get your API key from https://app.mem0.ai/dashboard/api-keys - - 2. Choose ONE method: - - Option A — CLI (shell profile): - echo 'export MEM0_API_KEY="m0-your-key-here"' >> ~/.zshrc - source ~/.zshrc - - Option B — Desktop app (local environment editor): - Click the environment dropdown next to the prompt box, - hover over "Local", click the gear icon, and add: - MEM0_API_KEY = m0-your-key-here - (Stored encrypted on your machine, applies to all local sessions) - - Note: The Desktop app does NOT inherit custom env vars from - shell profiles — it only reads PATH. Use Option B for Desktop. - - 3. Verify: - [ -n "${MEM0_API_KEY:-${CLAUDE_PLUGIN_OPTION_API_KEY:-}}" ] && echo "SET" || echo "NOT_SET" -``` - -After the user confirms, re-run the verify command. If NOT_SET, repeat. If SET, proceed to Step 2. - -## Step 2: MCP server connection - -First, check if MCP tools are already available using ToolSearch with query `"mem0 search_memories"`. The exact tool name varies by install method (may be `mcp__mem0__search_memories` or `mcp__plugin_mem0_mem0__search_memories`). - -**If MCP tools ARE found:** Print `- MCP already connected.` and proceed to Step 3. - -**If MCP tools are NOT found:** - -The MCP server authenticates using the `MEM0_API_KEY` set in Step 1. No OAuth or browser login is needed. - -1. Verify the API key is set (re-run the Step 1 check) -2. Check the plugin is installed: run `/plugins` and confirm `mem0` appears -3. Check the MCP server is listed: run `/mcp` and look for `mcp.mem0.ai` -4. If the server shows an error, ask the user to restart Claude Code and run `/mem0:onboard` again -5. If all checks pass but tools are still missing: "Restart Claude Code and run `/mem0:onboard` again." - -**STOP here** — do not proceed without MCP tools. - -## Step 3: Verify connectivity and show identity - -Call `search_memories` with `query="project setup"`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=1` to verify connectivity. - -Print: -``` -- Connected - user: - project: - branch: -``` - -If the search fails, troubleshoot the API key and MCP connection. - -## Step 4: Import project files - -Project files (CLAUDE.md, AGENTS.md, etc.) are automatically imported into mem0 when a session starts. This step verifies import status and triggers a re-import if needed. - -### 4a: Detect project files - -```bash -for f in CLAUDE.md AGENTS.md .cursorrules .windsurfrules mem0.md; do - [ -f "$f" ] && echo "FOUND: $f ($(wc -c < "$f") bytes)" -done || true -``` - -If no files found, print `- No project files found. Skipping import.` and proceed to Step 5. - -### 4b: Check and import - -Run auto_import in foreground to check status and import if needed: - -```bash -MEM0_DEBUG=1 MEM0_CWD="$PWD" python3 "${CLAUDE_PLUGIN_ROOT}/scripts/auto_import.py" -``` - -### 4c: Report to user - -Parse the auto_import output and print a user-friendly summary: - -- If output contains `Imported` lines: - ``` - - Importing project files into mem0... done. - file(s) imported ( chunks). These are stored verbatim for future context. - ``` -- If output contains only `skipping` lines: - ``` - - Project files already in mem0 (imported during session start). Verified server-side. - ``` -- If output contains `re-importing`: - ``` - - Project files were missing from mem0. Re-imported successfully. - ``` -- If output contains errors or no files were processed: - ``` - - Project file import failed. Check API key and retry with: /mem0:onboard - ``` - -## Step 5: Coding categories (automatic) - -Coding categories optimized for development workflows are installed **automatically in the background on session start** — the same way project files are imported (Step 4). The user is no longer asked. This step only verifies they are in place and applies them if the background run hasn't finished yet. - -The installer is idempotent and self-caching: it compares existing categories against the proposed set, skips the API call when they already match, and skips all network calls entirely once applied for this account (re-applying only if the taxonomy changes). Safe to run anytime. - -Run it in the foreground to verify, using the plugin's venv python: - -```bash -VENV_PY="${CLAUDE_PLUGIN_DATA}/venv/bin/python3" -if [ -x "${VENV_PY}" ]; then - MEM0_DEBUG=1 "${VENV_PY}" "${CLAUDE_PLUGIN_ROOT}/scripts/auto_setup_categories.py" -else - MEM0_DEBUG=1 python3 "${CLAUDE_PLUGIN_ROOT}/scripts/auto_setup_categories.py" -fi -``` - -Parse the output: -- contains `Applied coding categories` → Print: `- Coding categories installed ( categories).` -- contains `already configured` → Print: `- Coding categories already configured.` -- error or `SDK not ready` → run the dependency installer first, then retry: -```bash -"${CLAUDE_PLUGIN_ROOT}/scripts/ensure_deps.sh" -``` -Then retry the categories script. - -## Step 6: Summary - -Print a summary: -``` -- Onboarding complete. - user_id: - project_id: (app_id) - files: found, imported - categories: - -Memory is now active for this project. Start working — mem0 will -automatically search relevant context and capture learnings. - -Run /mem0:tour to see what mem0 already knows about this project. -``` diff --git a/integrations/mem0-plugin/skills/peek/SKILL.md b/integrations/mem0-plugin/skills/peek/SKILL.md deleted file mode 100644 index ccc6b2a0c..000000000 --- a/integrations/mem0-plugin/skills/peek/SKILL.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -name: peek -description: Searches memories and displays compact one-liner results, or looks up a specific memory by ID. Use for quick memory lookups, checking if a decision was recorded, resolving [mem0:id] citations, or browsing memories without full category detail. ---- - -# Mem0 Peek - -Quick search with compact output. Lighter than `/mem0:tour`. - -## Execution - -### Step 1: Parse query - -The user provides a search query: `/mem0:peek auth middleware` - -If no query provided, ask: "What should I search for?" - -**Memory ID detection:** If the query matches any of these patterns, treat it as a -direct memory ID lookup instead of a search: -- Bare hex: `^[a-f0-9]{8}$` (short ID) or `^[a-f0-9]{8}-[a-f0-9-]+$` (full UUID) -- Citation ref: `[mem0:]` — extract the hex portion - -When an ID is detected: -1. Call `get_memory()` directly (if short ID, try as prefix of full UUID) -2. If found, skip to Step 3 and display the single result -3. If not found, fall through to search using the ID as query text - -### 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` - -### Step 3: Display - -Deduplicate by ID, then show compact results: - -``` -## mem0 peek: "" ( results) - -1. [decision] Auth module uses JWT with RS256 keys (2025-05-15) [mem0:a3f8b2c1] -2. [anti_pattern] Don't use symmetric HS256 — leaked in env (2025-05-10) [mem0:7e2d9f4a] -3. [convention] All middleware in src/middleware/ (2025-05-08) [mem0:c4d5e6f7] -``` - -Format: `. [] () [mem0:]` - -If no results: -``` -No memories matching "" for project . -``` diff --git a/integrations/mem0-plugin/skills/pin/SKILL.md b/integrations/mem0-plugin/skills/pin/SKILL.md deleted file mode 100644 index 5ee20be7d..000000000 --- a/integrations/mem0-plugin/skills/pin/SKILL.md +++ /dev/null @@ -1,67 +0,0 @@ ---- -name: pin -description: Pins or unpins a memory to protect it from pruning during dream consolidation. Use when a memory is critical and must never be removed, such as architecture decisions, security constraints, or immutable team conventions. ---- - -# Mem0 Pin - -Pin a memory to mark it as high-priority and protect from pruning. - -## Execution - -### Step 1: Find the memory - -The user provides either a search query or memory ID. - -**If memory ID:** -- Call `get_memory` with the ID. - -**If search query:** -- Call `search_memories` with the query, `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=5`. -- Show numbered list with content previews. -- Ask: "Which memory to pin? Enter a number." - -### Step 2: Read current content - -Call `get_memory` with the selected memory ID. Store: -- `original_text` — the memory's text content -- `original_metadata` — the existing `metadata` dict - -### Step 3: Pin it - -The MCP `update_memory` tool only accepts `memory_id`, `text`, and `source` — it -does not accept a `metadata` parameter. To pin, append a pin marker to the text: - -```python -pinned_text = "[PINNED] " + original_text if not original_text.startswith("[PINNED]") else original_text -update_memory(memory_id=, text=pinned_text) -``` - -**For new memories** (user wants to pin text that isn't stored yet): -1. Call `add_memory` with: - - `text="[PINNED] "` - - `user_id=` - - `app_id=` - - `metadata={"pinned": true, "type": "decision", "confidence": 1.0}` - - `infer=False` -2. The response contains `event_id`. Call `get_event_status(event_id=)` once to retrieve the memory ID, then confirm. - -### Step 4: Confirm - -``` -Pinned: "" -Memory ID: -``` - -Append `...` only if content exceeds 80 characters. - -### Unpin - -If the user says "unpin": -1. Call `get_memory` to read current content. -2. Remove the pin marker from the text: - ```python - unpinned_text = original_text.removeprefix("[PINNED] ") - update_memory(memory_id=, text=unpinned_text) - ``` -3. Print: `Unpinned: "..."` diff --git a/integrations/mem0-plugin/skills/policy/SKILL.md b/integrations/mem0-plugin/skills/policy/SKILL.md deleted file mode 100644 index 43bd64ed2..000000000 --- a/integrations/mem0-plugin/skills/policy/SKILL.md +++ /dev/null @@ -1,71 +0,0 @@ ---- -name: policy -description: Views or sets the project's memory-extraction policy (what Mem0 remembers vs ignores) stored in mem0.md. Use when the user says set a memory policy, custom instructions, what should mem0 remember, tell mem0 to ignore X, or asks to see/change the current instructions. ---- - -# Mem0 Policy - -The project's memory policy lives in a `## Instructions` section of `mem0.md` at -the repo root. It is version-controlled and shared by the whole team, and it maps -to Mem0's `custom_instructions` (what to extract / ignore). An optional -`## Agent Instructions` section maps to `agent_custom_instructions` (guidance for -agent-scoped memories only). - -The policy takes effect on the **next session** (mem0.md is re-parsed on -SessionStart) and is applied automatically on the plugin's memory writes. - -## Execution - -### Step 1: Determine intent from the argument - -`/mem0:policy` is invoked as `/mem0:policy [] `: - -| Argument | Action | -|---|---| -| _(none)_ or `show` | Show the current policy | -| `set ` or free text | Set/replace the `## Instructions` (custom) policy | -| `agent ` | Set/replace the `## Agent Instructions` policy | -| `clear` | Remove both policy sections | - -### Step 2: Locate mem0.md - -`mem0.md` sits at the repo root (the current working directory). If it does not -exist yet and the user is setting a policy, you will create it. - -### Step 3a: Show - -Run `python3 "$CLAUDE_PLUGIN_ROOT/scripts/parse_mem0_config.py" --key instructions .` -and `--key agent_instructions .` (or read `mem0.md` directly). Print: - -``` -Memory policy for this project (mem0.md): - Instructions: - Agent Instructions: -``` - -If `mem0.md` is absent, say there is no policy yet and offer to set one. - -### Step 3b: Set / clear - -Edit `mem0.md`, adding or replacing the target section. Keep the instruction a -short prose paragraph (what to remember, what to ignore). Example: - -```markdown -## Instructions -Remember architecture decisions, API contracts, and team conventions. -Ignore transient debugging output, stack traces, and anything resembling a secret. -``` - -- Preserve any other existing sections (`## Retention`, `## Categories`, etc.). -- If the section already exists, replace its body; otherwise append the section. -- For `clear`, delete the `## Instructions` and `## Agent Instructions` sections. - -### Step 4: Confirm - -``` -Updated memory policy in mem0.md. -Takes effect next session. Commit mem0.md to share it with your team. -``` - -Remind the user that `## Agent Instructions` only affects agent-scoped memories, -so it is a no-op unless memories are written with an `agent_id`. diff --git a/integrations/mem0-plugin/skills/remember/SKILL.md b/integrations/mem0-plugin/skills/remember/SKILL.md deleted file mode 100644 index 599c2f7a7..000000000 --- a/integrations/mem0-plugin/skills/remember/SKILL.md +++ /dev/null @@ -1,57 +0,0 @@ ---- -name: remember -description: Stores a memory verbatim from user input with appropriate type classification and metadata. Use when the user says remember this, save this, store this, note that, or explicitly asks to record a decision, preference, convention, or learning. ---- - -# Mem0 Remember - -Store a fact or learning directly into mem0. - -## Execution - -### Step 1: Extract the content - -The user provides the content as an argument: `/mem0:remember ` - -If no text was provided, ask: "What should I remember?" - -### Step 2: Classify the memory - -Based on the content, pick the best `metadata.type`: - -| Content signal | Type | -|---|---| -| "we decided...", "always use...", "never..." | `decision` | -| "X doesn't work because...", "don't try..." | `anti_pattern` | -| "I prefer...", "use X instead of Y" | `user_preference` | -| "the convention is...", "we always..." | `convention` | -| "learned that...", "figured out..." | `task_learning` | -| setup, env, tooling, config | `environmental` | -| anything else | `task_learning` | - -### Step 3: Store - -Call `add_memory` with: -- `text=""` -- `user_id=` -- `app_id=` -- `metadata={"type": "", "branch": "", "confidence": 1.0, "source": "remember_command"}` -- `infer=False` - -`infer=False` because the user stated the fact explicitly — no extraction needed. -`confidence=1.0` because the user explicitly asked to store this. - -### Step 4: Confirm - -The `add_memory` response returns `event_id` (not `memory_id`) because writes are async. -Call `get_event_status(event_id=)` once. - -- If status is `SUCCEEDED`: print the memory ID from the result. -- If status is `PENDING` or `processing`: print with the event ID as fallback. - -``` -Remembered as : "" -Memory ID: -``` - -Append `...` only if content was truncated (longer than 80 chars). diff --git a/integrations/mem0-plugin/skills/stats/SKILL.md b/integrations/mem0-plugin/skills/stats/SKILL.md deleted file mode 100644 index 5652cb58e..000000000 --- a/integrations/mem0-plugin/skills/stats/SKILL.md +++ /dev/null @@ -1,130 +0,0 @@ ---- -name: stats -description: Displays memory usage statistics for the current session and project including counts by category, age distribution, and API latency. Use when checking how many memories exist, reviewing session activity, or auditing memory distribution across categories. ---- - -# Mem0 Stats - -Show session and lifetime memory statistics. - -## Execution - -### Step 1: Gather session stats - -Run the session stats reporter: - -```bash -SCRIPT_DIR="${CLAUDE_PLUGIN_ROOT:-${CODEX_PLUGIN_ROOT:-${CURSOR_PLUGIN_ROOT:-}}}/scripts" -python3 "$SCRIPT_DIR/session_stats.py" peek 2>/dev/null || echo "{}" -``` - -The `peek` command returns JSON without clearing the stats file (unlike `report`). - -If the script returns empty or errors, note "No session data available" and continue. - -### Step 2: Fetch lifetime and session stats from API - -**Lifetime stats:** -Call `get_memories` to fetch all memories for this project: - -`filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `page_size=100` - -Group by: -1. `categories[0]` (platform-assigned) — primary grouping -2. `metadata.type` (agent-assigned) — secondary if no categories -3. `created_at` date — for age analysis - -**Category normalization:** Merge `auto_capture` and `uncategorized` into a single `uncategorized` row. These are memories where the platform didn't assign a meaningful content category. Do NOT show `auto_capture` as its own row in the table. - -**Session stats (local only):** -Session stats come from the local stats file read in Step 1. Do NOT query the API with -`run_id` or `metadata.session_id` filters — these return unreliable results because -memories are stored without `run_id` and metadata filters on `session_id` are inconsistent. - -The local stats file tracks adds and searches for the current session accurately. - -Also run a `search_memories` MCP tool call with `query="project"`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=1` to measure round-trip latency. Note the time before and after the MCP call — do NOT attempt raw HTTP calls to the API. - -### Step 3: Display - -Print a minimal dashboard. No ASCII bar charts — use a clean table layout: - -``` -## mem0 stats - -**Session** () — 3 written, 5 searches, categories: decision, convention - -**Project: my-project** — 55 memories, API: 84ms - -| Category | Count | -|----------------------|-------| -| decision | 24 | -| convention | 15 | -| anti_pattern | 6 | -| task_learning | 5 | -| user_preference | 3 | -| session_state | 2 | - -**Age** — oldest: 2026-02-15, newest: 2026-05-23 - < 7 days: 5 · 7–30d: 12 · 30–90d: 10 · > 90d: 8 - -**Identity** — user: kartik · project: my-project · branch: main -``` - -**Display rules:** -- Category table: sort by count descending, omit categories with 0 memories -- Age: single line with dot-separated buckets, computed from `created_at` -- Session line: skip if no session data available -- If only 1-2 total memories, skip the category table — just show the count -- Keep everything compact — no decorative borders or filler - -## Weekly digest mode - -When invoked with `--weekly` (e.g., `/mem0:stats --weekly`), append a weekly -activity digest after the standard stats dashboard: - -### W1: Fetch recent memories - -Call `search_memories` in parallel with time-scoped queries: -1. `query="decisions made this week"`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}, {"created_at": {"gte": "<7 days ago YYYY-MM-DD>"}}]}`, `top_k=20` -2. `query="bugs errors fixes"`, same time filter, `top_k=20` -3. `query="patterns conventions learnings"`, same time filter, `top_k=20` - -### W2: Analyze - -Merge by ID. Group into "New this week" by `categories[0]` or `metadata.type`. -Calculate: memories added last 7 days, most active categories, most active day. - -### W3: Display - -Append after the standard stats: - -``` -### This week (May 16 – May 23) - -+12 memories — most active: Wednesday (5) - -| Category | New | -|---------------|-----| -| decision | 5 | -| task_learning | 4 | -| bug_fix | 3 | - -**Highlights** -- <2-3 sentence summary of most important decisions/learnings this week> -``` - -### W4: Write digest file - -Write to `~/.mem0/weekly-digest.md` (overwrite). Append one-line to -`~/.mem0/digest-history.log`: -``` - | | + memories | top: -``` - -### W5: Empty state - -If no new memories in 7 days: -``` -No new memories in the past week. Total: memories in . -``` diff --git a/integrations/mem0-plugin/skills/switch-project/SKILL.md b/integrations/mem0-plugin/skills/switch-project/SKILL.md deleted file mode 100644 index 739e19beb..000000000 --- a/integrations/mem0-plugin/skills/switch-project/SKILL.md +++ /dev/null @@ -1,103 +0,0 @@ ---- -name: switch-project -description: Overrides the auto-detected project scope to read and write memories under a different project ID, or enables global search to access all memories across all users and projects. Use when working across multiple projects, accessing memories from another repo, enabling team-wide memory access, or when auto-detection resolves to the wrong project. ---- - -# Mem0 Switch Project - -Override the automatic project_id detection for the current directory, or enable global search mode. - -## Usage - -- `/mem0:switch-project ` — switch to a specific project scope -- `/mem0:switch-project --global` — enable global search (all memories, all users, all projects) -- `/mem0:switch-project --no-global` — disable global search and return to per-project scoping - -## Execution - -### If `--global` flag is provided: - -1. Set `global_search: true` in `~/.mem0/settings.json` using the Bash tool: - - ```bash - python3 -c " - import json, os - settings_file = os.path.expanduser('~/.mem0/settings.json') - settings = {} - if os.path.isfile(settings_file): - with open(settings_file) as f: - settings = json.load(f) - settings['global_search'] = True - with open(settings_file, 'w') as f: - json.dump(settings, f, indent=2) - print('Global search enabled') - " - ``` - -2. Print: - ``` - Global search enabled. - Searches now return all memories across all users and projects. - Writes still use the current user_id and app_id. - Restart the session for the change to take effect. - ``` - -### If `--no-global` flag is provided: - -1. Set `global_search: false` in `~/.mem0/settings.json` using the Bash tool: - - ```bash - python3 -c " - import json, os - settings_file = os.path.expanduser('~/.mem0/settings.json') - settings = {} - if os.path.isfile(settings_file): - with open(settings_file) as f: - settings = json.load(f) - settings['global_search'] = False - with open(settings_file, 'w') as f: - json.dump(settings, f, indent=2) - print('Global search disabled') - " - ``` - -2. Print: - ``` - Global search disabled. - Searches now return only memories scoped to the current project. - Restart the session for the change to take effect. - ``` - -### If a project name is provided (no flags): - -1. If no project name was given, ask: "What project_id should this directory use?" - -2. Write the mapping to `~/.mem0/project_map.json` using the Bash tool: - - ```bash - python3 -c " - import json, os - map_file = os.path.expanduser('~/.mem0/project_map.json') - mapping = {} - if os.path.isfile(map_file): - with open(map_file) as f: - mapping = json.load(f) - mapping[os.getcwd()] = '' - os.makedirs(os.path.dirname(map_file), exist_ok=True) - with open(map_file, 'w') as f: - json.dump(mapping, f, indent=2) - print(f'Mapped {os.getcwd()} -> ') - " - ``` - - (Replace `` with the user's chosen project name.) - -3. Verify by searching for existing memories: - - Call `search_memories` with `query="project"`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=1` - -4. Print: - ``` - Switched to project . - memories found for this project. - Note: This override persists across sessions for this directory. - ``` diff --git a/integrations/mem0-plugin/skills/tour/SKILL.md b/integrations/mem0-plugin/skills/tour/SKILL.md deleted file mode 100644 index 7e3bcb4aa..000000000 --- a/integrations/mem0-plugin/skills/tour/SKILL.md +++ /dev/null @@ -1,123 +0,0 @@ ---- -name: tour -description: Browses all stored memories grouped by category with full content display. Use when reviewing all project memories, exploring stored knowledge, onboarding to a project, or getting an overview of captured decisions, conventions, and learnings. ---- - -# Mem0 Project Tour - -Show the user what mem0 has stored for the current project. - -## Cross-project mode - -When invoked with `--all-projects` (e.g., `/mem0:tour --all-projects` or -`/mem0:tour --all-projects auth middleware`), search across ALL projects: - -1. Call `get_memories` with `filters={"AND": [{"user_id": ""}]}`, `page_size=200` — **no `app_id` filter**. -2. If a search query was also provided, run `search_memories` with `query=`, - `filters={"AND": [{"user_id": ""}]}`, `top_k=20` — again no `app_id`. -3. Group results by `app_id` first, then by category within each project. -4. Display: - ``` - ## ( memories) ← current - **Architecture Decisions** — - ... - - ## ( memories) - ... - - memories across projects - ``` -5. Mark the current project with `← (current)` in the heading. - -If `--all-projects` is NOT present, use the standard single-project flow below. - -## Peek mode (compact search) - -When `/mem0:tour` receives a search query argument (e.g., `/mem0:tour auth middleware`) -WITHOUT `--all-projects`, run in **peek mode** — compact one-liner results: - -1. Run 2 parallel `search_memories` calls: - - Broad: `query=`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=10`, `rerank=true` - - Targeted: `query=`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}, {"metadata": {"type": "decision"}}]}`, `top_k=5`, `rerank=true` -2. Deduplicate by ID, display compact results: - ``` - ## mem0 search: "" ( results) - - 1. [decision] Auth module uses JWT with RS256 keys (2025-05-15) [mem0:a3f8b2c1] - 2. [anti_pattern] Don't use symmetric HS256 — leaked in env (2025-05-10) [mem0:7e2d9f4a] - 3. [convention] All middleware in src/middleware/ (2025-05-08) [mem0:c4d5e6f7] - ``` - Format: `. [] () [mem0:]` -3. If no results: `No memories matching "" for project .` - -If no query argument and no `--all-projects` flag, use the full tour flow below. - -## Execution - -### Step 1: Fetch ALL memories for this project - -Call `get_memories` to fetch all memories for this project: - -`filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `page_size=100` - -### Step 2: Run supplementary semantic searches - -In parallel, run these `search_memories` calls to get relevance-ranked results for key topics: - -- `query="architecture decisions design choices"`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=10`, `rerank=true` -- `query="bugs errors failures anti-patterns"`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=10`, `rerank=true` -- `query="project setup tooling conventions preferences"`, `filters={"AND": [{"user_id": ""}, {"app_id": ""}]}`, `top_k=10`, `rerank=true` - -**Do NOT filter by `metadata.type` in these calls.** The platform auto-assigns `categories` — filtering on `metadata.type` misses memories that were auto-categorized but don't have an explicit `metadata.type`. - -### Step 3: Merge and group - -Merge all results by memory ID (deduplicate). For each memory, determine its group using this priority: - -1. **Platform `categories` field** (array on each memory, auto-assigned by Mem0). Use the first category value. -2. **`metadata.type` field** (if present, set explicitly by hooks/agent). Use as fallback if no `categories`. -3. **"other"** bucket for memories with neither. - -Map category names to display names: - -| Platform category / metadata.type | Display name | -|---|---| -| `architecture decisions`, `architecture_decisions`, `decision` | Architecture Decisions | -| `anti patterns`, `anti_patterns`, `anti_pattern` | Anti-Patterns | -| `task learnings`, `task_learnings`, `task_learning` | Task Learnings | -| `coding conventions`, `coding_conventions`, `convention` | Coding Conventions | -| `user preferences`, `user_preferences`, `user_preference` | User Preferences | -| `project profile`, `project_profile` | Project Profile | -| `tooling setup`, `tooling_setup`, `environmental` | Tooling & Setup | -| `technology`, `professional_details` | Tooling & Setup | -| `session_state` | Session State | -| `compact_summary` | Compact Summaries | -| anything else | Other | - -### Step 4: Display results - -Sort groups by descending memory count. For each group that has results, print: - -``` -## ( memories) -- (score: ) -- ... -``` - -Show the **full memory text** for each entry — do NOT truncate. If a group has more than 10 entries, show top 10 by recency (or similarity score if from a search call) and note `... and more`. - -For groups with zero results, skip them entirely — don't print empty groups. - -### Step 5: Print totals - -``` - memories across categories — project: , branch: -``` - -### Step 6: Empty state - -If zero memories found for this project, print: -``` -No memories stored yet for project . -Run /mem0:onboard to import project files, or start working — mem0 captures learnings automatically. -``` diff --git a/integrations/mem0-plugin/tests/conftest.py b/integrations/mem0-plugin/tests/conftest.py deleted file mode 100644 index a170017f5..000000000 --- a/integrations/mem0-plugin/tests/conftest.py +++ /dev/null @@ -1,65 +0,0 @@ -"""Shared fixtures for mem0-plugin tests.""" - -from __future__ import annotations - -import os -import subprocess -import sys - -import pytest - -SCRIPTS_DIR = os.path.join(os.path.dirname(__file__), "..", "scripts") - - -@pytest.fixture(autouse=True) -def _scripts_on_path(): - """Ensure scripts/ is on sys.path so we can import _project, session_stats, etc.""" - abs_scripts = os.path.abspath(SCRIPTS_DIR) - if abs_scripts not in sys.path: - sys.path.insert(0, abs_scripts) - yield - if abs_scripts in sys.path: - sys.path.remove(abs_scripts) - - -@pytest.fixture(autouse=True) -def _isolated_home(tmp_path, monkeypatch): - """Point HOME at a tmp dir so ~/.mem0 writes never touch the real home.""" - home = tmp_path / "home" - home.mkdir() - monkeypatch.setenv("HOME", str(home)) - monkeypatch.setenv("USERPROFILE", str(home)) - monkeypatch.delenv("MEM0_PROJECT_ID", raising=False) - yield home - - -@pytest.fixture() -def tmp_git_repo(tmp_path): - """Create a temp dir with a git repo and HTTPS remote.""" - subprocess.run(["git", "init"], cwd=tmp_path, capture_output=True, check=True) - subprocess.run( - ["git", "remote", "add", "origin", "https://github.com/mem0ai/mem0.git"], - cwd=tmp_path, - capture_output=True, - check=True, - ) - return tmp_path - - -@pytest.fixture() -def tmp_git_repo_ssh(tmp_path): - """Create a temp dir with a git repo and SSH remote.""" - subprocess.run(["git", "init"], cwd=tmp_path, capture_output=True, check=True) - subprocess.run( - ["git", "remote", "add", "origin", "git@github.com:acme/cool-project.git"], - cwd=tmp_path, - capture_output=True, - check=True, - ) - return tmp_path - - -@pytest.fixture() -def tmp_no_git(tmp_path): - """Temp dir with no git repo.""" - return tmp_path diff --git a/integrations/mem0-plugin/tests/test_auto_capture.py b/integrations/mem0-plugin/tests/test_auto_capture.py deleted file mode 100644 index 3866b9503..000000000 --- a/integrations/mem0-plugin/tests/test_auto_capture.py +++ /dev/null @@ -1,142 +0,0 @@ -"""Tests for auto_capture.py transcript parsing and exchange extraction.""" - -from __future__ import annotations - -import json -import os -import sys - -import pytest - -SCRIPTS_DIR = os.path.join(os.path.dirname(__file__), "..", "scripts") - - -@pytest.fixture(autouse=True) -def _scripts_path(): - abs_scripts = os.path.abspath(SCRIPTS_DIR) - if abs_scripts not in sys.path: - sys.path.insert(0, abs_scripts) - yield - if abs_scripts in sys.path: - sys.path.remove(abs_scripts) - - -def _make_transcript(tmp_path, entries): - path = tmp_path / "transcript.jsonl" - lines = [] - for entry in entries: - lines.append(json.dumps(entry)) - path.write_text("\n".join(lines) + "\n") - return str(path) - - -def _msg(role, content): - return {"message": {"role": role, "content": content}} - - -class TestTailLines: - def test_reads_last_n_lines(self, tmp_path): - from auto_capture import tail_lines - - p = tmp_path / "test.txt" - p.write_text("\n".join(f"line{i}" for i in range(100)) + "\n") - result = tail_lines(str(p), 5) - assert len(result) >= 5 - assert result[-1] == "line99" - - def test_empty_file(self, tmp_path): - from auto_capture import tail_lines - - p = tmp_path / "empty.txt" - p.write_text("") - assert tail_lines(str(p), 10) == [] - - def test_nonexistent_file(self): - from auto_capture import tail_lines - - assert tail_lines("/nonexistent/path", 10) == [] - - -class TestExtractRecentExchanges: - def test_extracts_user_assistant_pairs(self): - from auto_capture import extract_recent_exchanges - - lines = [ - json.dumps(_msg("user", "What is Python used for?" * 3)), - json.dumps(_msg("assistant", "Python is used for many things." * 3)), - json.dumps(_msg("user", "Tell me about web frameworks." * 3)), - json.dumps(_msg("assistant", "Django and Flask are popular." * 3)), - ] - result = extract_recent_exchanges(lines, max_exchanges=2) - assert len(result) == 4 - assert result[0]["role"] == "user" - assert result[1]["role"] == "assistant" - - def test_skips_short_messages(self): - from auto_capture import extract_recent_exchanges - - lines = [ - json.dumps(_msg("user", "ok")), - json.dumps(_msg("assistant", "Sure, here is a detailed explanation." * 3)), - ] - result = extract_recent_exchanges(lines, max_exchanges=2) - assert len(result) == 1 - assert result[0]["role"] == "assistant" - - def test_skips_compact_summaries(self): - from auto_capture import extract_recent_exchanges - - lines = [ - json.dumps({"isCompactSummary": True, "message": {"role": "assistant", "content": "summary " * 20}}), - json.dumps(_msg("user", "This is a real user message here." * 2)), - ] - result = extract_recent_exchanges(lines, max_exchanges=2) - assert len(result) == 1 - assert result[0]["role"] == "user" - - def test_limits_to_max_exchanges(self): - from auto_capture import extract_recent_exchanges - - lines = [] - for i in range(10): - lines.append(json.dumps(_msg("user", f"Question number {i} with enough text to pass." * 2))) - lines.append(json.dumps(_msg("assistant", f"Answer number {i} with enough text to pass." * 2))) - result = extract_recent_exchanges(lines, max_exchanges=2) - assert len(result) == 4 - - def test_handles_list_content(self): - from auto_capture import extract_recent_exchanges - - lines = [ - json.dumps({"message": {"role": "user", "content": [ - {"type": "text", "text": "This is block content that is long enough." * 2}, - ]}}), - ] - result = extract_recent_exchanges(lines, max_exchanges=2) - assert len(result) == 1 - assert "block content" in result[0]["content"] - - def test_empty_lines(self): - from auto_capture import extract_recent_exchanges - - assert extract_recent_exchanges([], max_exchanges=2) == [] - - def test_truncates_long_content(self): - from auto_capture import extract_recent_exchanges - - long_text = "x" * 5000 - lines = [json.dumps(_msg("user", long_text))] - result = extract_recent_exchanges(lines, max_exchanges=1) - assert len(result) == 1 - assert len(result[0]["content"]) == 2000 - - def test_skips_tool_call_assistant_messages(self): - from auto_capture import extract_recent_exchanges - - lines = [ - json.dumps(_msg("assistant", '{"tool_calls": [{"name": "read"}]}')), - json.dumps(_msg("user", "Thanks for reading that file for me!" * 2)), - ] - result = extract_recent_exchanges(lines, max_exchanges=2) - assert len(result) == 1 - assert result[0]["role"] == "user" diff --git a/integrations/mem0-plugin/tests/test_auto_setup_categories.py b/integrations/mem0-plugin/tests/test_auto_setup_categories.py deleted file mode 100644 index 23562f232..000000000 --- a/integrations/mem0-plugin/tests/test_auto_setup_categories.py +++ /dev/null @@ -1,153 +0,0 @@ -"""Tests for auto_setup_categories.py -- the background coding-categories installer. - -Covers the pure, network-free logic: - - fingerprints (api key + category taxonomy) - - state-file gating (load / save / is_applied) - - idempotent apply via an injected fake client (no SDK, no network) - - single source of truth for the category list (shared with setup_coding_categories) -""" - -from __future__ import annotations - -import os -import sys - -SCRIPTS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "scripts")) -if SCRIPTS_DIR not in sys.path: - sys.path.insert(0, SCRIPTS_DIR) - -import auto_setup_categories as asc # noqa: E402 -from setup_coding_categories import CODING_CATEGORIES # noqa: E402 - - -# --------------------------------------------------------------------------- # -# Fake client (dependency injection — apply_categories takes a client) # -# --------------------------------------------------------------------------- # -class _FakeProject: - def __init__(self, current): - self._current = current - self.update_calls: list = [] - - def get(self, fields=None): - return {"custom_categories": self._current} - - def update(self, custom_categories=None, **kwargs): - self.update_calls.append(custom_categories) - return {"ok": True} - - -class _FakeClient: - def __init__(self, current): - self.project = _FakeProject(current) - - -# --------------------------------------------------------------------------- # -# Source-of-truth: the taxonomy is shared, not duplicated # -# --------------------------------------------------------------------------- # -def test_uses_shared_category_list(): - """auto_setup_categories must reuse setup_coding_categories' list, not fork it.""" - assert asc.CODING_CATEGORIES is CODING_CATEGORIES - assert len(asc.CODING_CATEGORIES) == 17 - - -# --------------------------------------------------------------------------- # -# Fingerprints # -# --------------------------------------------------------------------------- # -def test_categories_fingerprint_is_stable_hex(): - fp = asc.categories_fingerprint(CODING_CATEGORIES) - assert isinstance(fp, str) - assert len(fp) == 16 - assert all(c in "0123456789abcdef" for c in fp) - # deterministic across calls - assert fp == asc.categories_fingerprint(CODING_CATEGORIES) - - -def test_categories_fingerprint_changes_when_taxonomy_changes(): - base = asc.categories_fingerprint(CODING_CATEGORIES) - changed = asc.categories_fingerprint(CODING_CATEGORIES + [{"new_one": "desc"}]) - assert base != changed - - -def test_categories_fingerprint_order_independent(): - """Reordering the same categories must yield the same fingerprint.""" - reordered = list(reversed(CODING_CATEGORIES)) - assert asc.categories_fingerprint(CODING_CATEGORIES) == asc.categories_fingerprint(reordered) - - -def test_apikey_fingerprint_is_stable_and_opaque(): - key = "m0-supersecret-abc123" - fp = asc.apikey_fingerprint(key) - assert isinstance(fp, str) - assert len(fp) == 16 - assert fp == asc.apikey_fingerprint(key) - # never leak the raw key - assert "supersecret" not in fp - assert key not in fp - - -def test_apikey_fingerprint_differs_per_key(): - assert asc.apikey_fingerprint("m0-aaa") != asc.apikey_fingerprint("m0-bbb") - - -# --------------------------------------------------------------------------- # -# State file: load / save / gating # -# --------------------------------------------------------------------------- # -def test_load_state_missing_file_returns_empty(tmp_path): - assert asc.load_state(str(tmp_path / "does_not_exist.json")) == {} - - -def test_load_state_corrupt_file_returns_empty(tmp_path): - p = tmp_path / "categories_setup.json" - p.write_text("{not valid json") - assert asc.load_state(str(p)) == {} - - -def test_save_then_load_roundtrip_creates_parent_dir(tmp_path): - p = tmp_path / "nested" / "categories_setup.json" - asc.save_state({"abc123": "deadbeef00000000"}, str(p)) - assert p.is_file() - assert asc.load_state(str(p)) == {"abc123": "deadbeef00000000"} - - -def test_is_applied_true_only_on_exact_match(): - state = {"keyfp": "catfp"} - assert asc.is_applied(state, "keyfp", "catfp") is True - # stale taxonomy fingerprint - assert asc.is_applied(state, "keyfp", "OTHER") is False - # unknown api key - assert asc.is_applied(state, "other-key", "catfp") is False - # empty state - assert asc.is_applied({}, "keyfp", "catfp") is False - - -# --------------------------------------------------------------------------- # -# apply_categories: idempotent, network-free via fake client # -# --------------------------------------------------------------------------- # -def test_apply_skips_update_when_already_matching(): - client = _FakeClient(CODING_CATEGORIES) - result = asc.apply_categories(client, CODING_CATEGORIES) - assert result == "already-configured" - assert client.project.update_calls == [] # must NOT hit the write endpoint - - -def test_apply_updates_when_no_categories_set(): - client = _FakeClient(None) - result = asc.apply_categories(client, CODING_CATEGORIES) - assert result == "applied" - assert client.project.update_calls == [CODING_CATEGORIES] - - -def test_apply_updates_when_categories_differ(): - client = _FakeClient([{"food": "consumer default"}]) - result = asc.apply_categories(client, CODING_CATEGORIES) - assert result == "applied" - assert client.project.update_calls == [CODING_CATEGORIES] - - -def test_fetch_current_categories_handles_non_dict(): - """A non-dict project response must degrade to None, not raise.""" - - class Weird: - project = type("P", (), {"get": staticmethod(lambda fields=None: "unexpected")})() - - assert asc.fetch_current_categories(Weird()) is None diff --git a/integrations/mem0-plugin/tests/test_capture_session_summary.py b/integrations/mem0-plugin/tests/test_capture_session_summary.py deleted file mode 100644 index 7ce1f1458..000000000 --- a/integrations/mem0-plugin/tests/test_capture_session_summary.py +++ /dev/null @@ -1,79 +0,0 @@ -"""Regression tests for capture_session_summary.py request body construction. - -Guards against the double-JSON-encoding bug where ``files_touched`` was stored -as a pre-serialized JSON string and then encoded a second time with the rest of -the request body — surfacing as escaped, slash-heavy blobs in the memories shown -inside Claude Code / Cursor / Codex / Antigravity (all four editors share this -script). -""" - -from __future__ import annotations - -import json - - -class _FakeResp: - status = 200 - - def __enter__(self): - return self - - def __exit__(self, *_): - return False - - -def _capture_request_body(monkeypatch): - """Patch urlopen so store_summary posts nowhere; capture the request body.""" - import capture_session_summary as css - - captured: dict = {} - - def fake_urlopen(req, timeout=0): - captured["raw"] = req.data.decode("utf-8") - captured["body"] = json.loads(captured["raw"]) - return _FakeResp() - - monkeypatch.setattr(css.urllib.request, "urlopen", fake_urlopen) - return captured, css - - -def test_files_touched_is_json_array_not_double_encoded(monkeypatch): - """files_touched must be a real JSON array, encoded exactly once.""" - captured, css = _capture_request_body(monkeypatch) - files = ["mem0/memory/main.py", "src/client/index.ts"] - - css.store_summary( - api_key="test-key", - summary_prompt="did some work", - user_id="u1", - session_id="s1", - project_id="p1", - branch="main", - files=files, - ) - - files_touched = captured["body"]["metadata"]["files_touched"] - assert isinstance(files_touched, list), ( - "files_touched must be a JSON array, not a double-encoded string; " - f"got {type(files_touched).__name__}: {files_touched!r}" - ) - assert files_touched == files - # The file paths must not appear as an escaped JSON string inside the body. - assert '\\"' not in captured["raw"] - - -def test_files_touched_omitted_when_no_files(monkeypatch): - """No files touched -> no files_touched key (unchanged behaviour).""" - captured, css = _capture_request_body(monkeypatch) - - css.store_summary( - api_key="test-key", - summary_prompt="did some work", - user_id="u1", - session_id="s1", - project_id="p1", - branch="main", - files=[], - ) - - assert "files_touched" not in captured["body"]["metadata"] diff --git a/integrations/mem0-plugin/tests/test_coding_categories.py b/integrations/mem0-plugin/tests/test_coding_categories.py deleted file mode 100644 index c4d57b62f..000000000 --- a/integrations/mem0-plugin/tests/test_coding_categories.py +++ /dev/null @@ -1,88 +0,0 @@ -"""Tests for setup_coding_categories.py -- CODING_CATEGORIES list completeness.""" - -from __future__ import annotations - -import importlib -import os -import sys - -import pytest - -SCRIPTS_DIR = os.path.join(os.path.dirname(__file__), "..", "scripts") - -EXPECTED_KEYS = [ - "architecture_decisions", - "anti_patterns", - "task_learnings", - "tooling_setup", - "bug_fixes", - "coding_conventions", - "user_preferences", - "dependency_decisions", - "performance_findings", - "security_constraints", - "testing_patterns", - "data_model", - "api_contracts", - "deployment_runbook", - "team_norms", - "domain_glossary", - "experiment_results", -] - - -@pytest.fixture() -def coding_categories(): - """Import CODING_CATEGORIES from setup_coding_categories, ensuring scripts/ is on path.""" - abs_scripts = os.path.abspath(SCRIPTS_DIR) - inserted = False - if abs_scripts not in sys.path: - sys.path.insert(0, abs_scripts) - inserted = True - # Force re-import in case another test already loaded a stale version - mod_name = "setup_coding_categories" - if mod_name in sys.modules: - del sys.modules[mod_name] - mod = importlib.import_module(mod_name) - yield mod.CODING_CATEGORIES - if inserted and abs_scripts in sys.path: - sys.path.remove(abs_scripts) - - -def test_total_count(coding_categories): - """CODING_CATEGORIES must contain exactly 17 entries.""" - assert len(coding_categories) == 17, ( - f"Expected 17 categories, found {len(coding_categories)}: " - f"{[list(c.keys())[0] for c in coding_categories]}" - ) - - -def test_all_expected_keys_present(coding_categories): - """Every expected category key must appear exactly once.""" - actual_keys = [list(cat.keys())[0] for cat in coding_categories] - for key in EXPECTED_KEYS: - assert key in actual_keys, f"Missing expected category key: '{key}'" - - -def test_no_duplicate_keys(coding_categories): - """No category key may appear more than once.""" - actual_keys = [list(cat.keys())[0] for cat in coding_categories] - seen = set() - duplicates = [] - for key in actual_keys: - if key in seen: - duplicates.append(key) - seen.add(key) - assert not duplicates, f"Duplicate category keys found: {duplicates}" - - -def test_each_description_is_non_empty_string(coding_categories): - """Every category must have a non-empty string description.""" - for cat in coding_categories: - assert len(cat) == 1, f"Category dict should have exactly one key, got: {cat}" - key = list(cat.keys())[0] - description = cat[key] - assert isinstance(description, str), ( - f"Category '{key}' description is not a string: {type(description)}" - ) - assert description.strip(), f"Category '{key}' has an empty description" diff --git a/integrations/mem0-plugin/tests/test_import_competing_tools.py b/integrations/mem0-plugin/tests/test_import_competing_tools.py deleted file mode 100644 index 48a76d700..000000000 --- a/integrations/mem0-plugin/tests/test_import_competing_tools.py +++ /dev/null @@ -1,355 +0,0 @@ -"""Tests for import_competing_tools.py — competing tool file importers.""" - -from __future__ import annotations - -import json -import os -import sys -from unittest import mock - -SCRIPTS_DIR = os.path.join(os.path.dirname(__file__), "..", "scripts") - - -# --------------------------------------------------------------------------- -# split_sections tests (unit tests on the splitter functions) -# --------------------------------------------------------------------------- - - -def test_split_by_headers_cursorrules(): - """split_by_headers correctly splits .cursorrules content on ## headers.""" - from _chunking import split_by_headers - - content = """\ -# My Cursor Rules - -Some preamble text that belongs to the first section. - -## TypeScript Conventions - -Always use strict mode. Prefer const over let. -Never use var. - -## React Patterns - -Use functional components with hooks. -Avoid class components. - -## Testing - -Write tests for all utility functions. -""" - chunks = split_by_headers(content, "## ") - assert len(chunks) == 4 # preamble + 3 sections - - # First chunk is the preamble (before any ## header) - assert "preamble text" in chunks[0] - - # Remaining chunks start with their header - assert chunks[1].startswith("## TypeScript Conventions") - assert "strict mode" in chunks[1] - - assert chunks[2].startswith("## React Patterns") - assert "functional components" in chunks[2] - - assert chunks[3].startswith("## Testing") - assert "utility functions" in chunks[3] - - -def test_split_by_headers_copilot(): - """split_by_headers correctly splits copilot-instructions.md on ## headers.""" - from _chunking import split_by_headers - - content = """\ -## Code Style - -Use 2-space indentation. Always add trailing commas. - -## Architecture - -Follow clean architecture principles. Keep business logic in domain layer. -""" - chunks = split_by_headers(content, "## ") - assert len(chunks) == 2 - assert chunks[0].startswith("## Code Style") - assert "2-space indentation" in chunks[0] - assert chunks[1].startswith("## Architecture") - assert "clean architecture" in chunks[1] - - -def test_split_by_headers_no_headers(): - """split_by_headers returns entire content as one chunk if no headers found.""" - from _chunking import split_by_headers - - content = "This file has no headers at all. Just plain text." - chunks = split_by_headers(content, "## ") - assert len(chunks) == 1 - assert "Just plain text" in chunks[0] - - -def test_split_cline_multiple_md_files(tmp_path): - """cmd_cline processes multiple .md files from memory-bank/ directory.""" - from _chunking import filter_and_truncate - - # Create a temporary memory-bank directory with .md files - mb_dir = tmp_path / "memory-bank" - mb_dir.mkdir() - - (mb_dir / "architecture.md").write_text( - "# Architecture Decisions\n\nUse microservices architecture with event sourcing." - ) - (mb_dir / "conventions.md").write_text( - "# Code Conventions\n\nAll functions must have type hints. Use black formatter." - ) - (mb_dir / "empty.md").write_text("") # empty file should be skipped - - # Read and verify we can split the files - md_files = sorted(f for f in os.listdir(str(mb_dir)) if f.endswith(".md")) - assert "architecture.md" in md_files - assert "conventions.md" in md_files - assert "empty.md" in md_files - - non_empty = [] - for filename in md_files: - filepath = os.path.join(str(mb_dir), filename) - with open(filepath) as f: - content = f.read().strip() - if content: - chunks = filter_and_truncate([content]) - non_empty.extend(chunks) - - assert len(non_empty) == 2 - assert any("microservices" in c for c in non_empty) - assert any("type hints" in c for c in non_empty) - - -def test_split_by_hr_or_headers_continue(): - """split_by_hr_or_headers correctly splits .continue/rules.md.""" - from _chunking import split_by_hr_or_headers - - content = """\ -## First Section - -Content of first section. - ---- - -## Second Section - -Content of second section. - ---- - -Third section without a header (just after HR). -""" - chunks = split_by_hr_or_headers(content) - # Should split into meaningful chunks - assert len(chunks) >= 2 - assert any("First Section" in c for c in chunks) - assert any("Second Section" in c for c in chunks) - - -def test_filter_and_truncate_skips_short(): - """filter_and_truncate skips chunks shorter than MIN_CHUNK_CHARS (50).""" - from _chunking import filter_and_truncate - - chunks = [ - "Short", # < 50 chars, should be filtered - "A" * 49, # exactly 49 chars, should be filtered - "A" * 50, # exactly 50 chars, should be kept - "A long enough chunk that definitely passes the minimum length filter.", - ] - result = filter_and_truncate(chunks) - assert len(result) == 2 - assert all(len(c) >= 50 for c in result) - - -def test_filter_and_truncate_truncates_long(): - """filter_and_truncate truncates chunks over MAX_CHUNK_CHARS (10000).""" - from _chunking import MAX_CHUNK_CHARS, filter_and_truncate - - long_chunk = "X" * (MAX_CHUNK_CHARS + 500) - result = filter_and_truncate([long_chunk]) - assert len(result) == 1 - assert len(result[0]) == MAX_CHUNK_CHARS - - -# --------------------------------------------------------------------------- -# Mock API tests -# --------------------------------------------------------------------------- - - -def _make_mock_response(status: int = 201, body: dict | None = None) -> mock.MagicMock: - """Create a mock HTTP response object.""" - if body is None: - body = {"id": "new-mem-id", "memory": "test"} - resp = mock.MagicMock() - resp.status = status - resp.read.return_value = json.dumps(body).encode() - resp.__enter__ = lambda s: s - resp.__exit__ = mock.MagicMock(return_value=False) - return resp - - -def test_cursorrules_import_api_call(tmp_path): - """cmd_cursorrules calls the API with correct app_id (top-level), infer=False, and correct source.""" - from import_competing_tools import cmd_cursorrules - - # Create a .cursorrules file with enough content - cursorrules = tmp_path / ".cursorrules" - cursorrules.write_text( - "## TypeScript Rules\n\nAlways use strict TypeScript. Never use 'any' type. " - "Prefer interfaces over type aliases for object shapes." - ) - - captured_requests: list[dict] = [] - - def mock_urlopen(req, timeout=None): - body = json.loads(req.data.decode()) - captured_requests.append(body) - return _make_mock_response(201) - - with mock.patch("import_competing_tools.resolve_api_key", return_value="m0-testkey"), \ - mock.patch("import_competing_tools.resolve_user_id", return_value="testuser"), \ - mock.patch("import_competing_tools.resolve_project_id", return_value="my-project"), \ - mock.patch("import_competing_tools.resolve_branch", return_value="main"), \ - mock.patch("urllib.request.urlopen", side_effect=mock_urlopen): - - original_cwd = os.getcwd() - os.chdir(str(tmp_path)) - try: - cmd_cursorrules(["--path", str(cursorrules)]) - finally: - os.chdir(original_cwd) - - assert len(captured_requests) >= 1 - - req_body = captured_requests[0] - - # app_id must be top-level (not inside metadata) - assert req_body["app_id"] == "my-project", f"Expected app_id at top level, got: {req_body}" - - # infer must be False (not "false", but the boolean False) - assert req_body["infer"] is False, f"Expected infer=False, got: {req_body['infer']}" - - # source must be cursor-import - assert req_body["metadata"]["source"] == "cursor-import", ( - f"Expected source=cursor-import, got: {req_body['metadata'].get('source')}" - ) - - # user_id must be set - assert req_body["user_id"] == "testuser" - - # messages must be a list with role/content - assert isinstance(req_body["messages"], list) - assert req_body["messages"][0]["role"] == "user" - assert len(req_body["messages"][0]["content"]) > 0 - - -def test_copilot_import_api_call(tmp_path): - """cmd_copilot calls the API with source=copilot-import.""" - from import_competing_tools import cmd_copilot - - copilot_dir = tmp_path / ".github" - copilot_dir.mkdir() - copilot_file = copilot_dir / "copilot-instructions.md" - copilot_file.write_text( - "## Code Style\n\nUse 2-space indentation. Always add trailing commas in multi-line structures. " - "Prefer const over let. Never use var in JavaScript code." - ) - - captured: list[dict] = [] - - def mock_urlopen(req, timeout=None): - captured.append(json.loads(req.data.decode())) - return _make_mock_response(201) - - with mock.patch("import_competing_tools.resolve_api_key", return_value="m0-key"), \ - mock.patch("import_competing_tools.resolve_user_id", return_value="user1"), \ - mock.patch("import_competing_tools.resolve_project_id", return_value="proj1"), \ - mock.patch("import_competing_tools.resolve_branch", return_value="main"), \ - mock.patch("urllib.request.urlopen", side_effect=mock_urlopen): - - cmd_copilot(["--path", str(copilot_file)]) - - assert len(captured) >= 1 - assert captured[0]["metadata"]["source"] == "copilot-import" - assert captured[0]["app_id"] == "proj1" - assert captured[0]["infer"] is False - - -def test_cline_import_multiple_files(tmp_path): - """cmd_cline imports one memory per non-empty .md file.""" - from import_competing_tools import cmd_cline - - mb = tmp_path / "memory-bank" - mb.mkdir() - (mb / "arch.md").write_text( - "Architecture: microservices with event-sourcing. Each service owns its database. " - "Communication via message bus only. No direct service-to-service HTTP calls." - ) - (mb / "style.md").write_text( - "Code style: PEP 8 for Python. Black formatter. isort for imports. " - "Line length 120. Type hints required on all public functions and methods." - ) - (mb / "empty.md").write_text("") - - captured: list[dict] = [] - - def mock_urlopen(req, timeout=None): - captured.append(json.loads(req.data.decode())) - return _make_mock_response(201) - - with mock.patch("import_competing_tools.resolve_api_key", return_value="m0-key"), \ - mock.patch("import_competing_tools.resolve_user_id", return_value="user1"), \ - mock.patch("import_competing_tools.resolve_project_id", return_value="proj1"), \ - mock.patch("import_competing_tools.resolve_branch", return_value="main"), \ - mock.patch("urllib.request.urlopen", side_effect=mock_urlopen): - - cmd_cline(["--path", str(mb)]) - - # Should have exactly 2 imports (empty.md skipped) - assert len(captured) == 2 - sources = {r["metadata"]["source"] for r in captured} - assert sources == {"cline-import"} - for r in captured: - assert r["infer"] is False - assert r["app_id"] == "proj1" - - -def test_no_api_key_does_not_call_api(tmp_path): - """When no API key is set, no HTTP call is made.""" - from import_competing_tools import cmd_cursorrules - - cursorrules = tmp_path / ".cursorrules" - cursorrules.write_text("## Rules\n\n" + "x" * 100) - - with mock.patch("import_competing_tools.resolve_api_key", return_value=""), \ - mock.patch("urllib.request.urlopen") as mock_url: - - cmd_cursorrules(["--path", str(cursorrules)]) - - mock_url.assert_not_called() - - -def test_missing_file_does_not_call_api(tmp_path): - """When the source file doesn't exist, no HTTP call is made.""" - from import_competing_tools import cmd_cursorrules - - with mock.patch("import_competing_tools.resolve_api_key", return_value="m0-key"), \ - mock.patch("urllib.request.urlopen") as mock_url: - - cmd_cursorrules(["--path", str(tmp_path / "nonexistent.cursorrules")]) - - mock_url.assert_not_called() - - -def test_main_unknown_subcommand_exits_zero(): - """Calling main() with an unknown subcommand exits 0.""" - import subprocess - result = subprocess.run( - [sys.executable, os.path.join(SCRIPTS_DIR, "import_competing_tools.py"), "unknown"], - capture_output=True, - text=True, - env={**os.environ, "MEM0_API_KEY": ""}, - ) - assert result.returncode == 0 diff --git a/integrations/mem0-plugin/tests/test_instructions.py b/integrations/mem0-plugin/tests/test_instructions.py deleted file mode 100644 index cbbe41005..000000000 --- a/integrations/mem0-plugin/tests/test_instructions.py +++ /dev/null @@ -1,126 +0,0 @@ -"""Tests for the mem0.md extraction-policy feature. - -Covers the parser (`parse_section_text` + the Instructions sections in -`load_full_config`) and the `_instructions.load_instructions` helper that the -hook writers use to attach `custom_instructions` / `agent_custom_instructions` -to a memory write. -""" - -from __future__ import annotations - -MEM0_MD = """\ -# mem0.md - -## Categories -- architecture_decisions - -## Instructions -Remember architecture decisions and conventions. -Ignore transient debug output and secrets (issue #123 refs are fine). - -## Agent Instructions -For agent memories, focus on tools and task outcomes. -""" - - -# --------------------------------------------------------------------------- -# parse_section_text -# --------------------------------------------------------------------------- - - -def test_parse_section_text_collapses_prose(): - from parse_mem0_config import parse_section_text - - text = parse_section_text(MEM0_MD, "Instructions") - assert text == ( - "Remember architecture decisions and conventions. " - "Ignore transient debug output and secrets (issue #123 refs are fine)." - ) - - -def test_parse_section_text_preserves_inline_hash(): - """Inline '#' (e.g. issue refs) is kept; only full-line comments are dropped.""" - from parse_mem0_config import parse_section_text - - assert "#123" in parse_section_text(MEM0_MD, "Instructions") - - -def test_instructions_and_agent_instructions_are_distinct(): - """'## Instructions' must not swallow '## Agent Instructions'.""" - from parse_mem0_config import parse_section_text - - assert parse_section_text(MEM0_MD, "Instructions").startswith("Remember architecture") - assert parse_section_text(MEM0_MD, "Agent Instructions") == ( - "For agent memories, focus on tools and task outcomes." - ) - - -def test_parse_section_text_missing_returns_empty(): - from parse_mem0_config import parse_section_text - - assert parse_section_text("## Retention\nx: 1d\n", "Instructions") == "" - - -def test_load_full_config_includes_instructions(tmp_path): - from parse_mem0_config import load_full_config - - (tmp_path / "mem0.md").write_text(MEM0_MD) - config = load_full_config(str(tmp_path)) - assert config["instructions"].startswith("Remember architecture") - assert config["agent_instructions"].startswith("For agent memories") - - -# --------------------------------------------------------------------------- -# load_instructions (the helper the hook writers call) -# --------------------------------------------------------------------------- - - -def test_load_instructions_maps_to_api_field_names(tmp_path): - from _instructions import load_instructions - - (tmp_path / "mem0.md").write_text(MEM0_MD) - out = load_instructions(str(tmp_path)) - assert out == { - "custom_instructions": ( - "Remember architecture decisions and conventions. " - "Ignore transient debug output and secrets (issue #123 refs are fine)." - ), - "agent_custom_instructions": "For agent memories, focus on tools and task outcomes.", - } - - -def test_load_instructions_no_config_is_empty(tmp_path): - """No mem0.md -> empty dict, so a write body gains nothing.""" - from _instructions import load_instructions - - assert load_instructions(str(tmp_path)) == {} - - -def test_load_instructions_only_custom(tmp_path): - """A project with only '## Instructions' omits the agent key entirely.""" - from _instructions import load_instructions - - (tmp_path / "mem0.md").write_text("## Instructions\nRemember decisions.\n") - out = load_instructions(str(tmp_path)) - assert out == {"custom_instructions": "Remember decisions."} - - -def test_load_instructions_defaults_cwd_to_env(tmp_path, monkeypatch): - """With no arg, cwd falls back to MEM0_CWD.""" - from _instructions import load_instructions - - (tmp_path / "mem0.md").write_text("## Instructions\nRemember decisions.\n") - monkeypatch.setenv("MEM0_CWD", str(tmp_path)) - assert load_instructions() == {"custom_instructions": "Remember decisions."} - - -def test_load_instructions_body_merge_shape(tmp_path): - """The result merges cleanly into an add body without clobbering other keys.""" - from _instructions import load_instructions - - (tmp_path / "mem0.md").write_text("## Instructions\nRemember decisions.\n") - body = {"messages": [], "user_id": "u", "infer": True} - body.update(load_instructions(str(tmp_path))) - assert body["user_id"] == "u" and body["infer"] is True - assert body["custom_instructions"] == "Remember decisions." - assert "agent_custom_instructions" not in body diff --git a/integrations/mem0-plugin/tests/test_kimi_manifests.py b/integrations/mem0-plugin/tests/test_kimi_manifests.py deleted file mode 100644 index 942f2ced6..000000000 --- a/integrations/mem0-plugin/tests/test_kimi_manifests.py +++ /dev/null @@ -1,80 +0,0 @@ -"""Validate the Kimi Code plugin manifests and hook wiring. - -Kimi Code loads a plugin from `.kimi-plugin/plugin.json`. This test locks down -the structural contract so a stray edit cannot silently break the plugin: - - - both manifests parse and carry the required Kimi fields - - the MCP server uses Kimi's supported auth (transport/url/bearerTokenEnvVar) - - every hook command routes through kimi_hook_shim.sh and targets a script - that actually exists in scripts/ - - the sessionStart skill and skills/ path resolve on disk -""" - -import json -import os - -PLUGIN_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -REPO_ROOT = os.path.dirname(os.path.dirname(PLUGIN_DIR)) - -SUBDIR_MANIFEST = os.path.join(PLUGIN_DIR, ".kimi-plugin", "plugin.json") -ROOT_MARKETPLACE = os.path.join(REPO_ROOT, ".kimi-plugin", "marketplace.json") -SHIM = os.path.join(PLUGIN_DIR, "scripts", "kimi_hook_shim.sh") - - -def _load(path): - with open(path) as fh: - return json.load(fh) - - -def test_manifest_parses_and_has_required_fields(): - m = _load(SUBDIR_MANIFEST) - assert m["name"] == "mem0" - for field in ("version", "description", "skills", "mcpServers", "interface", "hooks"): - assert field in m, f"manifest missing {field}" - - -def test_mcp_uses_kimi_supported_auth(): - srv = _load(SUBDIR_MANIFEST)["mcpServers"]["mem0"] - assert srv["transport"] == "http" - assert srv["url"] == "https://mcp.mem0.ai/mcp/" # trailing slash avoids the 307 redirect - # Kimi reads the named env var and sends Authorization: Bearer . - assert srv["bearerTokenEnvVar"] == "MEM0_API_KEY" - assert "headers" not in srv # Kimi does not interpolate ${env:...} inside headers - - -def test_sessionstart_skill_and_skills_dir_resolve(): - m = _load(SUBDIR_MANIFEST) - assert m["skills"] == "./skills/" - assert os.path.isdir(os.path.join(PLUGIN_DIR, "skills")) - start_skill = m["sessionStart"]["skill"] - assert os.path.isdir(os.path.join(PLUGIN_DIR, "skills", start_skill)) - - -def test_shim_exists_and_is_executable(): - assert os.path.isfile(SHIM) - assert os.access(SHIM, os.X_OK), "kimi_hook_shim.sh must be executable" - - -def test_every_hook_routes_through_shim_to_a_real_script(): - hooks = _load(SUBDIR_MANIFEST)["hooks"] - assert hooks, "no hooks declared" - valid_events = { - "SessionStart", "UserPromptSubmit", "PreToolUse", - "PostToolUse", "Stop", "PreCompact", - } - for hook in hooks: - assert hook["event"] in valid_events, f"unknown event {hook['event']}" - cmd = hook["command"] - assert "kimi_hook_shim.sh" in cmd, f"hook must route through the shim: {cmd}" - assert "$KIMI_PLUGIN_ROOT/scripts/kimi_hook_shim.sh" in cmd - target = cmd.rsplit('"', 1)[-1].strip() # the script name after the shim - assert target.endswith(".sh") - assert os.path.isfile(os.path.join(PLUGIN_DIR, "scripts", target)), \ - f"hook target script missing: {target}" - - -def test_root_marketplace_catalog(): - cat = _load(ROOT_MARKETPLACE) - entry = cat["plugins"][0] - assert entry["id"] == "mem0" # Kimi marketplace entries key on id - assert entry["source"].startswith("https://github.com/mem0ai/mem0") diff --git a/integrations/mem0-plugin/tests/test_load_settings.py b/integrations/mem0-plugin/tests/test_load_settings.py deleted file mode 100644 index 0f3216256..000000000 --- a/integrations/mem0-plugin/tests/test_load_settings.py +++ /dev/null @@ -1,86 +0,0 @@ -"""Tests for scripts/load_settings.py.""" - -from __future__ import annotations - -import json -import os -import subprocess -import sys - -import pytest - - -@pytest.fixture() -def settings(tmp_path, monkeypatch): - import load_settings - - path = tmp_path / ".mem0" / "settings.json" - monkeypatch.setattr(load_settings, "SETTINGS_PATH", path) - return load_settings - - -def test_creates_file_when_absent(settings): - assert settings.create_default_settings() is True - assert settings.SETTINGS_PATH.exists() - assert json.loads(settings.SETTINGS_PATH.read_text()) == settings.DEFAULTS - - -def test_does_not_recreate_or_overwrite_existing(settings): - settings.SETTINGS_PATH.parent.mkdir(parents=True) - settings.SETTINGS_PATH.write_text('{"search_limit": 42}') - - assert settings.create_default_settings() is False - assert json.loads(settings.SETTINGS_PATH.read_text()) == {"search_limit": 42} - - -def test_user_values_override_defaults(settings): - settings.SETTINGS_PATH.parent.mkdir(parents=True) - settings.SETTINGS_PATH.write_text('{"search_limit": 3, "auto_save": false}') - - loaded = settings.load_settings() - assert loaded["search_limit"] == 3 - assert loaded["auto_save"] is False - assert loaded["global_search"] == settings.DEFAULTS["global_search"] - - -def test_unknown_keys_are_dropped_but_reported(settings): - settings.SETTINGS_PATH.parent.mkdir(parents=True) - settings.SETTINGS_PATH.write_text('{"skip_tools": ["Read"], "output_style": "compact"}') - - assert "skip_tools" not in settings.load_settings() - assert settings.unknown_keys() == ["output_style", "skip_tools"] - - -def test_unknown_keys_empty_for_clean_file(settings): - settings.create_default_settings() - assert settings.unknown_keys() == [] - - -@pytest.mark.parametrize("body", ["{not json", '["a", "list"]']) -def test_malformed_file_falls_back_to_defaults(settings, body): - settings.SETTINGS_PATH.parent.mkdir(parents=True) - settings.SETTINGS_PATH.write_text(body) - - assert settings.load_settings() == settings.DEFAULTS - assert settings.unknown_keys() == [] - - -def test_init_announces_creation_only_once(_isolated_home): - import load_settings - - home = _isolated_home - - def run_init(): - return subprocess.run( - [sys.executable, load_settings.__file__, "init"], - capture_output=True, - text=True, - check=True, - env={**os.environ, "HOME": str(home)}, - ).stdout - - first = run_init() - second = run_init() - - assert "Created" in first - assert "Created" not in second diff --git a/integrations/mem0-plugin/tests/test_message_roles.py b/integrations/mem0-plugin/tests/test_message_roles.py deleted file mode 100644 index 0a36ca66e..000000000 --- a/integrations/mem0-plugin/tests/test_message_roles.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Regression tests: assistant-authored text must never be posted as role="user". - -The Stop hook (capture_session_summary) and the post-compact hook -(capture_compact_summary) both ship *model-authored* prose to -POST /v3/memories/add/. Mem0's fact extractor renders each message as -"{role}: {content}" and is instructed to extract "facts and preferences about -the user" — so role is the only signal separating what the human said from what -Claude said. - -Posting Claude's own words under role="user" made the extractor read Claude's -first-person prose ("I recommend pgvector", "I found the bug in auth.py") as the -*human's* statements and store them under their user_id. The Stop hook fires on -every assistant turn, so this corrupted memory on nearly every message. -""" - -from __future__ import annotations - -import json - - -class _FakeResp: - status = 200 - - def __enter__(self): - return self - - def __exit__(self, *_): - return False - - -def _capture(monkeypatch, module): - """Patch urlopen so store_summary posts nowhere; capture the request body.""" - captured: dict = {} - - def fake_urlopen(req, timeout=0): - captured["body"] = json.loads(req.data.decode("utf-8")) - return _FakeResp() - - monkeypatch.setattr(module.urllib.request, "urlopen", fake_urlopen) - return captured - - -# Claude's own voice — first-person prose that must never be attributed to the human. -ASSISTANT_PROSE = ( - "I traced the root cause to auth.py and I recommend we switch to pgvector " - "for the vector store. I'll refactor the session handler next." -) - - -def test_session_summary_posts_assistant_prose_as_assistant(monkeypatch): - """Stop hook: the last assistant message must be tagged role="assistant".""" - import capture_session_summary as css - - captured = _capture(monkeypatch, css) - - css.store_summary( - api_key="test-key", - summary_prompt=css.build_summary_prompt(ASSISTANT_PROSE, []), - user_id="u1", - session_id="s1", - project_id="p1", - branch="main", - files=[], - ) - - messages = captured["body"]["messages"] - for msg in messages: - if ASSISTANT_PROSE in msg["content"]: - assert msg["role"] == "assistant", ( - "Claude's own words were posted as role='user' — mem0 will extract " - "them as facts about the human. Got role=%r" % msg["role"] - ) - break - else: - raise AssertionError("assistant prose never made it into the payload") - - -def test_compact_summary_posts_assistant_prose_as_assistant(monkeypatch): - """Post-compact hook: the compact summary is model-authored, not user-authored.""" - import capture_compact_summary as ccs - - captured = _capture(monkeypatch, ccs) - - ccs.store_summary( - api_key="test-key", - summary=ASSISTANT_PROSE, - user_id="u1", - session_id="s1", - project_id="p1", - branch="main", - ) - - messages = captured["body"]["messages"] - for msg in messages: - if ASSISTANT_PROSE in msg["content"]: - assert msg["role"] == "assistant", ( - "Compact summary (written by Claude) was posted as role='user'. Got role=%r" % msg["role"] - ) - break - else: - raise AssertionError("assistant prose never made it into the payload") - - -def test_no_user_role_message_carries_assistant_prose(monkeypatch): - """Belt and braces: no user-role message may contain the assistant's words.""" - import capture_session_summary as css - - captured = _capture(monkeypatch, css) - - css.store_summary( - api_key="test-key", - summary_prompt=css.build_summary_prompt(ASSISTANT_PROSE, ["auth.py"]), - user_id="u1", - session_id="s1", - project_id="p1", - branch="main", - files=["auth.py"], - ) - - for msg in captured["body"]["messages"]: - if msg["role"] == "user": - assert ASSISTANT_PROSE not in msg["content"], ( - "A user-role message carries Claude's prose — this is the misattribution bug." - ) - - -def test_auto_capture_preserves_real_roles(): - """auto_capture is the reference: it must pass roles through untouched.""" - import auto_capture - - lines = [ - json.dumps({"type": "user", "message": {"role": "user", "content": "why is the build failing on main?"}}), - json.dumps( - { - "type": "assistant", - "message": {"role": "assistant", "content": [{"type": "text", "text": ASSISTANT_PROSE}]}, - } - ), - ] - - messages = auto_capture.extract_recent_exchanges(lines) - - assert [m["role"] for m in messages] == ["user", "assistant"] - assert ASSISTANT_PROSE in messages[1]["content"] diff --git a/integrations/mem0-plugin/tests/test_parse_export_file.py b/integrations/mem0-plugin/tests/test_parse_export_file.py deleted file mode 100644 index 66dccbd1d..000000000 --- a/integrations/mem0-plugin/tests/test_parse_export_file.py +++ /dev/null @@ -1,298 +0,0 @@ -"""Tests for parse_export_file.py — mem0 export file parser.""" - -from __future__ import annotations - -import json -import os -import subprocess -import sys - -SCRIPTS_DIR = os.path.join(os.path.dirname(__file__), "..", "scripts") - - -# --------------------------------------------------------------------------- -# Direct function tests -# --------------------------------------------------------------------------- - - -def test_parse_blocks_single_valid_block(): - """parse_blocks returns one record for a single valid block.""" - from parse_export_file import parse_blocks - - content = """\ ---- -id: abc123 -created_at: 2024-01-15T10:00:00Z -type: task_learnings -confidence: 0.85 -branch: main -files: src/foo.py, src/bar.py -categories: coding_conventions, task_learnings ---- -Always use context managers when opening files. -""" - records = parse_blocks(content) - assert len(records) == 1 - r = records[0] - assert r["id"] == "abc123" - assert r["type"] == "task_learnings" - assert r["confidence"] == "0.85" - assert r["branch"] == "main" - assert r["files"] == ["src/foo.py", "src/bar.py"] - assert r["categories"] == ["coding_conventions", "task_learnings"] - assert "Always use context managers" in r["content"] - - -def test_parse_blocks_multiple_blocks(): - """parse_blocks returns the correct number of records for multiple blocks.""" - from parse_export_file import parse_blocks - - content = """\ ---- -id: mem001 -type: architecture_decisions -confidence: 0.9 -branch: main -files: -categories: architecture_decisions ---- -Use hexagonal architecture for the core domain. - ---- -id: mem002 -type: anti_patterns -confidence: 0.75 -branch: feat/refactor -files: src/legacy.py -categories: anti_patterns ---- -Avoid direct database calls from view layer. - ---- -id: mem003 -type: coding_conventions -confidence: 0.8 -branch: main -files: src/utils.py, src/helpers.py -categories: ---- -Use snake_case for all Python identifiers. -""" - records = parse_blocks(content) - assert len(records) == 3 - - assert records[0]["id"] == "mem001" - assert records[0]["categories"] == ["architecture_decisions"] - assert "hexagonal architecture" in records[0]["content"] - - assert records[1]["id"] == "mem002" - assert records[1]["files"] == ["src/legacy.py"] - assert "direct database calls" in records[1]["content"] - - assert records[2]["id"] == "mem003" - assert records[2]["files"] == ["src/utils.py", "src/helpers.py"] - assert records[2]["categories"] == [] - assert "snake_case" in records[2]["content"] - - -def test_parse_blocks_missing_optional_fields(): - """parse_blocks uses defaults when optional fields are absent.""" - from parse_export_file import parse_blocks - - # confidence, branch, files, categories all absent - content = """\ ---- -id: xyz789 -type: task_learnings ---- -Run tests before committing. -""" - records = parse_blocks(content) - assert len(records) == 1 - r = records[0] - assert r["id"] == "xyz789" - assert r["confidence"] == "" # default empty string - assert r["branch"] == "" # default empty string - assert r["files"] == [] # default empty list - assert r["categories"] == [] # default empty list - assert "Run tests" in r["content"] - - -def test_parse_blocks_filters_empty_content(): - """parse_blocks skips blocks whose content is empty or whitespace-only.""" - from parse_export_file import parse_blocks - - content = """\ ---- -id: empty1 -type: task_learnings ---- - ---- -id: real1 -type: task_learnings ---- -This block has real content. - ---- -id: empty2 -type: coding_conventions ---- - -""" - records = parse_blocks(content) - # Only the block with actual content should be returned - assert len(records) == 1 - assert records[0]["id"] == "real1" - assert "real content" in records[0]["content"] - - -def test_parse_blocks_round_trip(): - """Content formatted by export matches what parse_blocks expects.""" - from parse_export_file import parse_blocks - - # Simulate the exact format produced by the export skill - memory_id = "test-id-001" - created_at = "2024-06-01T12:00:00Z" - mem_type = "architecture_decisions" - confidence = "0.92" - branch = "feat/new-feature" - files = ["src/main.py", "tests/test_main.py"] - categories = ["architecture_decisions", "coding_conventions"] - memory_content = "Use dependency injection for all service classes." - - # Format exactly as the export skill would - block = ( - "---\n" - f"id: {memory_id}\n" - f"created_at: {created_at}\n" - f"type: {mem_type}\n" - f"confidence: {confidence}\n" - f"branch: {branch}\n" - f"files: {', '.join(files)}\n" - f"categories: {', '.join(categories)}\n" - "---\n" - f"{memory_content}\n" - "\n" - ) - - records = parse_blocks(block) - assert len(records) == 1 - r = records[0] - assert r["id"] == memory_id - assert r["type"] == mem_type - assert r["confidence"] == confidence - assert r["branch"] == branch - assert r["files"] == files - assert r["categories"] == categories - assert r["content"] == memory_content - - -def test_parse_blocks_multiline_content(): - """parse_blocks correctly captures multi-line memory content.""" - from parse_export_file import parse_blocks - - content = """\ ---- -id: multi001 -type: task_learnings ---- -Line one of the memory. -Line two of the memory. - -Line four after blank line. -""" - records = parse_blocks(content) - assert len(records) == 1 - assert "Line one" in records[0]["content"] - assert "Line two" in records[0]["content"] - assert "Line four" in records[0]["content"] - - -def test_parse_blocks_empty_input(): - """parse_blocks returns empty list for empty input.""" - from parse_export_file import parse_blocks - - assert parse_blocks("") == [] - assert parse_blocks(" \n ") == [] - - -def test_parse_blocks_no_blocks(): - """parse_blocks returns empty list for content without any --- delimiters.""" - from parse_export_file import parse_blocks - - assert parse_blocks("Just some text without any delimiters.") == [] - - -def test_parse_blocks_value_with_colon(): - """parse_blocks handles values that themselves contain colons.""" - from parse_export_file import parse_blocks - - content = """\ ---- -id: colon-test -type: task_learnings -created_at: 2024-01-01T10:00:00Z ---- -Timestamp values contain colons and should parse correctly. -""" - records = parse_blocks(content) - assert len(records) == 1 - assert records[0]["id"] == "colon-test" - # created_at field should be captured (it's in the record if present) - assert "2024-01-01T10:00:00Z" in records[0].get("created_at", "") - - -# --------------------------------------------------------------------------- -# CLI / subprocess tests -# --------------------------------------------------------------------------- - - -def test_main_cli_outputs_json(tmp_path): - """Running parse_export_file.py as a script outputs valid JSON.""" - export_file = tmp_path / "mem0-export-test.md" - export_file.write_text("""\ ---- -id: cli-test-001 -type: task_learnings -confidence: 0.8 -branch: main -files: -categories: task_learnings ---- -Prefer composition over inheritance. -""") - - result = subprocess.run( - [sys.executable, os.path.join(SCRIPTS_DIR, "parse_export_file.py"), str(export_file)], - capture_output=True, - text=True, - ) - assert result.returncode == 0 - records = json.loads(result.stdout) - assert isinstance(records, list) - assert len(records) == 1 - assert records[0]["id"] == "cli-test-001" - - -def test_main_cli_no_args_exits_zero(): - """Running parse_export_file.py with no arguments exits 0 and prints [].""" - result = subprocess.run( - [sys.executable, os.path.join(SCRIPTS_DIR, "parse_export_file.py")], - capture_output=True, - text=True, - ) - assert result.returncode == 0 - assert result.stdout.strip() == "[]" - - -def test_main_cli_missing_file_exits_zero(tmp_path): - """Running parse_export_file.py with a missing file exits 0 and prints [].""" - result = subprocess.run( - [sys.executable, os.path.join(SCRIPTS_DIR, "parse_export_file.py"), - str(tmp_path / "nonexistent.md")], - capture_output=True, - text=True, - ) - assert result.returncode == 0 - assert result.stdout.strip() == "[]" diff --git a/integrations/mem0-plugin/tests/test_parse_mem0_config.py b/integrations/mem0-plugin/tests/test_parse_mem0_config.py deleted file mode 100644 index 4ba261f6d..000000000 --- a/integrations/mem0-plugin/tests/test_parse_mem0_config.py +++ /dev/null @@ -1,439 +0,0 @@ -"""Tests for parse_mem0_config.py — mem0.md retention policy parser.""" - -from __future__ import annotations - -import json -import os -import subprocess -import sys - -SCRIPTS_DIR = os.path.join(os.path.dirname(__file__), "..", "scripts") - - -# --------------------------------------------------------------------------- -# parse_retention — unit tests -# --------------------------------------------------------------------------- - - -def test_parse_retention_valid_section(): - """parse_retention extracts day-count policies correctly.""" - from parse_mem0_config import parse_retention - - content = """\ -# Project Config - -## Retention - -session_state: 90d -compact_summary: 60d -decision: 180d -""" - result = parse_retention(content) - assert result == { - "session_state": 90, - "compact_summary": 60, - "decision": 180, - } - - -def test_parse_retention_forever_returns_none(): - """parse_retention maps 'forever' to None.""" - from parse_mem0_config import parse_retention - - content = """\ -## Retention - -user_preference: forever -anti_pattern: forever -session_state: 30d -""" - result = parse_retention(content) - assert result["user_preference"] is None - assert result["anti_pattern"] is None - assert result["session_state"] == 30 - - -def test_parse_retention_no_section_returns_empty(): - """parse_retention returns {} when there is no ## Retention heading.""" - from parse_mem0_config import parse_retention - - content = """\ -# Project Config - -## Some Other Section - -key: value -""" - result = parse_retention(content) - assert result == {} - - -def test_parse_retention_stops_at_next_heading(): - """parse_retention stops reading at the next ## heading.""" - from parse_mem0_config import parse_retention - - content = """\ -## Retention - -session_state: 7d - -## Other Section - -other_key: 999d -""" - result = parse_retention(content) - assert "session_state" in result - assert "other_key" not in result - - -def test_parse_retention_malformed_lines_skipped(): - """Malformed lines (no colon, bad day format) are silently ignored.""" - from parse_mem0_config import parse_retention - - content = """\ -## Retention - -session_state: 90d -bad_line_no_colon -another: badvalue -decision: 30d -""" - result = parse_retention(content) - assert result == {"session_state": 90, "decision": 30} - - -def test_parse_retention_comments_ignored(): - """Inline # comments are stripped before parsing.""" - from parse_mem0_config import parse_retention - - content = """\ -## Retention - -session_state: 90d # rolling 90-day window -user_preference: forever # never prune preferences -""" - result = parse_retention(content) - assert result["session_state"] == 90 - assert result["user_preference"] is None - - -def test_parse_retention_case_insensitive_heading(): - """## retention (lowercase) is matched the same as ## Retention.""" - from parse_mem0_config import parse_retention - - content = """\ -## retention - -session_state: 14d -""" - result = parse_retention(content) - assert result == {"session_state": 14} - - -def test_parse_retention_empty_section_returns_empty(): - """A ## Retention section with no valid lines returns {}.""" - from parse_mem0_config import parse_retention - - content = """\ -## Retention - -# only comments here - -## Next Section -""" - result = parse_retention(content) - assert result == {} - - -# --------------------------------------------------------------------------- -# load_retention_policies — integration tests with tmp files -# --------------------------------------------------------------------------- - - -def test_load_retention_policies_with_tmp_file(tmp_path): - """load_retention_policies reads a real mem0.md from disk.""" - from parse_mem0_config import load_retention_policies - - mem0_md = tmp_path / "mem0.md" - mem0_md.write_text( - """\ -# My Project - -## Retention - -session_state: 90d -compact_summary: 60d -decision: forever -""", - encoding="utf-8", - ) - - result = load_retention_policies(str(tmp_path)) - assert result == { - "session_state": 90, - "compact_summary": 60, - "decision": None, - } - - -def test_load_retention_policies_no_mem0_md_returns_empty(tmp_path): - """load_retention_policies returns {} when no mem0.md exists.""" - from parse_mem0_config import load_retention_policies - - result = load_retention_policies(str(tmp_path)) - assert result == {} - - -def test_load_retention_policies_no_retention_section_returns_empty(tmp_path): - """load_retention_policies returns {} when mem0.md has no ## Retention.""" - from parse_mem0_config import load_retention_policies - - mem0_md = tmp_path / "mem0.md" - mem0_md.write_text( - """\ -# My Project - -Some general project notes here. -No retention section. -""", - encoding="utf-8", - ) - - result = load_retention_policies(str(tmp_path)) - assert result == {} - - -def test_load_retention_policies_defaults_to_cwd(tmp_path, monkeypatch): - """load_retention_policies uses os.getcwd() when cwd is None.""" - from parse_mem0_config import load_retention_policies - - monkeypatch.chdir(tmp_path) - mem0_md = tmp_path / "mem0.md" - mem0_md.write_text("## Retention\nsession_state: 45d\n", encoding="utf-8") - - result = load_retention_policies() # no cwd arg - assert result == {"session_state": 45} - - -# --------------------------------------------------------------------------- -# CLI / main() — subprocess test -# --------------------------------------------------------------------------- - - -def test_cli_main_prints_json(tmp_path): - """CLI: python parse_mem0_config.py prints valid JSON.""" - mem0_md = tmp_path / "mem0.md" - mem0_md.write_text( - "## Retention\nsession_state: 90d\nuser_preference: forever\n", - encoding="utf-8", - ) - - result = subprocess.run( - [sys.executable, os.path.join(SCRIPTS_DIR, "parse_mem0_config.py"), str(tmp_path)], - capture_output=True, - text=True, - ) - assert result.returncode == 0 - data = json.loads(result.stdout) - assert data["session_state"] == 90 - assert data["user_preference"] is None - - -def test_cli_main_no_file_prints_empty_json(tmp_path): - """CLI: prints '{}' when no mem0.md exists.""" - result = subprocess.run( - [sys.executable, os.path.join(SCRIPTS_DIR, "parse_mem0_config.py"), str(tmp_path)], - capture_output=True, - text=True, - ) - assert result.returncode == 0 - assert json.loads(result.stdout) == {} - - -# --------------------------------------------------------------------------- -# parse_section_kv — unit tests -# --------------------------------------------------------------------------- - - -def test_parse_section_kv_basic(): - """parse_section_kv extracts key-value pairs from a named section.""" - from parse_mem0_config import parse_section_kv - - content = """\ -## Search - -default_limit: 10 -boost_recency: true -""" - result = parse_section_kv(content, "Search") - assert result == {"default_limit": "10", "boost_recency": "true"} - - -def test_parse_section_kv_missing_section(): - """parse_section_kv returns {} when section doesn't exist.""" - from parse_mem0_config import parse_section_kv - - result = parse_section_kv("## Other\nfoo: bar\n", "Search") - assert result == {} - - -def test_parse_section_kv_stops_at_next_heading(): - """parse_section_kv stops at the next ## heading.""" - from parse_mem0_config import parse_section_kv - - content = """\ -## Identity - -user_id: kartik -project_id: mem0 - -## Other - -ignored: yes -""" - result = parse_section_kv(content, "Identity") - assert result == {"user_id": "kartik", "project_id": "mem0"} - assert "ignored" not in result - - -# --------------------------------------------------------------------------- -# parse_section_list — unit tests -# --------------------------------------------------------------------------- - - -def test_parse_section_list_basic(): - """parse_section_list extracts list items from a named section.""" - from parse_mem0_config import parse_section_list - - content = """\ -## Categories - -- architecture_decisions -- bug_fixes -- coding_conventions -""" - result = parse_section_list(content, "Categories") - assert result == ["architecture_decisions", "bug_fixes", "coding_conventions"] - - -def test_parse_section_list_bare_lines(): - """parse_section_list works with bare lines (no bullet prefix).""" - from parse_mem0_config import parse_section_list - - content = """\ -## Categories - -architecture_decisions -bug_fixes -""" - result = parse_section_list(content, "Categories") - assert result == ["architecture_decisions", "bug_fixes"] - - -def test_parse_section_list_missing_section(): - """parse_section_list returns [] when section doesn't exist.""" - from parse_mem0_config import parse_section_list - - result = parse_section_list("## Other\n- foo\n", "Categories") - assert result == [] - - -# --------------------------------------------------------------------------- -# load_full_config — integration tests -# --------------------------------------------------------------------------- - - -def test_load_full_config_all_sections(tmp_path): - """load_full_config extracts all sections from mem0.md.""" - from parse_mem0_config import load_full_config - - mem0_md = tmp_path / "mem0.md" - mem0_md.write_text( - """\ -# My Project - -## Retention - -session_state: 90d -decision: forever - -## Search - -default_limit: 20 -boost_recency: true - -## Categories - -- architecture_decisions -- bug_fixes -- security_constraints - -## Identity - -user_id: kartik -project_id: my-project -""", - encoding="utf-8", - ) - - config = load_full_config(str(tmp_path)) - assert config["retention"] == {"session_state": 90, "decision": None} - assert config["search"] == {"default_limit": "20", "boost_recency": "true"} - assert config["categories"] == ["architecture_decisions", "bug_fixes", "security_constraints"] - assert config["identity"] == {"user_id": "kartik", "project_id": "my-project"} - - -def test_load_full_config_partial_sections(tmp_path): - """load_full_config only includes sections that exist.""" - from parse_mem0_config import load_full_config - - mem0_md = tmp_path / "mem0.md" - mem0_md.write_text("## Retention\nsession_state: 30d\n", encoding="utf-8") - - config = load_full_config(str(tmp_path)) - assert "retention" in config - assert "search" not in config - assert "categories" not in config - assert "identity" not in config - - -def test_load_full_config_no_file(tmp_path): - """load_full_config returns {} when no mem0.md exists.""" - from parse_mem0_config import load_full_config - - config = load_full_config(str(tmp_path)) - assert config == {} - - -def test_cli_full_flag(tmp_path): - """CLI: --full prints all sections as JSON.""" - mem0_md = tmp_path / "mem0.md" - mem0_md.write_text( - "## Retention\nsession_state: 90d\n\n## Search\nlimit: 10\n", - encoding="utf-8", - ) - - result = subprocess.run( - [sys.executable, os.path.join(SCRIPTS_DIR, "parse_mem0_config.py"), "--full", str(tmp_path)], - capture_output=True, - text=True, - ) - assert result.returncode == 0 - data = json.loads(result.stdout) - assert "retention" in data - assert "search" in data - - -def test_load_full_config_settings_section(tmp_path): - """Settings section is parsed by load_full_config.""" - mem0_md = tmp_path / "mem0.md" - mem0_md.write_text("""\ -## Settings -commit_prompts: true -subagent_skip: Explore, Plan, code-reviewer -""") - sys.path.insert(0, SCRIPTS_DIR) - from parse_mem0_config import load_full_config - config = load_full_config(str(tmp_path)) - assert config.get("settings", {}).get("commit_prompts") == "true" - assert config.get("settings", {}).get("subagent_skip") == "Explore, Plan, code-reviewer" diff --git a/integrations/mem0-plugin/tests/test_project.py b/integrations/mem0-plugin/tests/test_project.py deleted file mode 100644 index 39867b41d..000000000 --- a/integrations/mem0-plugin/tests/test_project.py +++ /dev/null @@ -1,171 +0,0 @@ -"""Tests for _project.py — project_id + branch resolver.""" - -from __future__ import annotations - -import json -import os -import subprocess - - -def test_resolve_project_id_from_https_remote(tmp_git_repo): - from _project import resolve_project_id - - pid = resolve_project_id(str(tmp_git_repo)) - assert pid == "mem0ai-mem0" - - -def test_resolve_project_id_from_ssh_remote(tmp_git_repo_ssh): - from _project import resolve_project_id - - pid = resolve_project_id(str(tmp_git_repo_ssh)) - assert pid == "acme-cool-project" - - -def test_resolve_project_id_fallback_basename(tmp_no_git): - from _project import resolve_project_id - - pid = resolve_project_id(str(tmp_no_git)) - assert pid == os.path.basename(str(tmp_no_git)) - - -def test_resolve_project_id_from_env(tmp_no_git, monkeypatch): - from _project import resolve_project_id - - monkeypatch.setenv("MEM0_PROJECT_ID", "my-override") - pid = resolve_project_id(str(tmp_no_git)) - assert pid == "my-override" - - -def test_resolve_project_id_from_project_map(tmp_no_git): - from _project import resolve_project_id, save_project_mapping - - save_project_mapping(str(tmp_no_git), "custom-project") - pid = resolve_project_id(str(tmp_no_git)) - assert pid == "custom-project" - - -def test_save_project_mapping_creates_file(tmp_no_git): - from _project import save_project_mapping - - save_project_mapping(str(tmp_no_git), "test-proj") - map_path = os.path.expanduser("~/.mem0/project_map.json") - assert os.path.isfile(map_path) - with open(map_path) as f: - data = json.load(f) - assert data[str(tmp_no_git)] == "test-proj" - - -def test_resolve_branch_in_git_repo(tmp_git_repo): - from _project import resolve_branch - - subprocess.run( - ["git", "checkout", "-b", "feat/test-branch"], - cwd=tmp_git_repo, - capture_output=True, - check=True, - ) - branch = resolve_branch(str(tmp_git_repo)) - assert branch == "feat/test-branch" - - -def test_resolve_branch_no_git(tmp_no_git): - from _project import resolve_branch - - branch = resolve_branch(str(tmp_no_git)) - assert branch == "unknown" - - -def test_remote_url_to_slug_various_formats(): - from _project import _remote_url_to_slug - - assert _remote_url_to_slug("https://github.com/mem0ai/mem0.git") == "mem0ai-mem0" - assert _remote_url_to_slug("git@github.com:mem0ai/mem0.git") == "mem0ai-mem0" - assert _remote_url_to_slug("ssh://git@github.com/acme/app.git") == "acme-app" - assert _remote_url_to_slug("https://gitlab.com/org/sub/repo.git") == "sub-repo" - assert _remote_url_to_slug("git@bitbucket.org:team/project.git") == "team-project" - - -def test_remote_url_to_slug_no_git_suffix(): - from _project import _remote_url_to_slug - - assert _remote_url_to_slug("https://github.com/foo/bar") == "foo-bar" - - -def test_resolve_project_id_priority_order(tmp_git_repo, monkeypatch): - """Env var > project_map > git remote > basename.""" - from _project import resolve_project_id, save_project_mapping - - # Git remote gives "mem0ai-mem0" - assert resolve_project_id(str(tmp_git_repo)) == "mem0ai-mem0" - - # project_map overrides git remote - save_project_mapping(str(tmp_git_repo), "from-map") - assert resolve_project_id(str(tmp_git_repo)) == "from-map" - - # Env var overrides everything - monkeypatch.setenv("MEM0_PROJECT_ID", "from-env") - assert resolve_project_id(str(tmp_git_repo)) == "from-env" - - -def test_remote_hash_key_format(tmp_git_repo): - """_remote_hash_key() returns 'remote:<16-char-hex>' for a repo with a remote.""" - import re - - from _project import _remote_hash_key - - key = _remote_hash_key(str(tmp_git_repo)) - assert re.fullmatch(r"remote:[0-9a-f]{16}", key), ( - f"Expected 'remote:<16-char-hex>', got {key!r}" - ) - - -def test_remote_hash_key_no_git(tmp_no_git): - """_remote_hash_key() returns empty string when not in a git repo.""" - from _project import _remote_hash_key - - key = _remote_hash_key(str(tmp_no_git)) - assert key == "" - - -def test_save_project_mapping_writes_remote_key(tmp_git_repo): - """save_project_mapping() writes both the CWD key and the remote hash key.""" - import re - - from _project import save_project_mapping - - save_project_mapping(str(tmp_git_repo), "my-project") - map_path = os.path.expanduser("~/.mem0/project_map.json") - with open(map_path) as f: - data = json.load(f) - - assert data[str(tmp_git_repo)] == "my-project" - remote_keys = [k for k in data if re.fullmatch(r"remote:[0-9a-f]{16}", k)] - assert remote_keys, "Expected at least one remote: key in project_map.json" - assert data[remote_keys[0]] == "my-project" - - -def test_resolve_project_id_remote_hash_fallback(tmp_git_repo, tmp_path): - """Moving the project folder: remote hash key is used as fallback.""" - from _project import resolve_project_id, save_project_mapping - - # Save mapping for original location - save_project_mapping(str(tmp_git_repo), "stable-project") - - # Simulate folder move: resolve using a different CWD path that shares the same remote. - # We use a second tmp_git_repo with the same remote URL to mimic a renamed directory. - import subprocess as _sp - new_repo = tmp_path / "moved_repo" - new_repo.mkdir() - _sp.run(["git", "init"], cwd=new_repo, capture_output=True, check=True) - _sp.run( - ["git", "remote", "add", "origin", "https://github.com/mem0ai/mem0.git"], - cwd=new_repo, - capture_output=True, - check=True, - ) - - # The new CWD is NOT in project_map, but remote hash should match - pid = resolve_project_id(str(new_repo)) - assert pid == "stable-project", ( - f"Expected 'stable-project' via remote hash fallback, got {pid!r}" - ) diff --git a/integrations/mem0-plugin/tests/test_rubric_dedup.py b/integrations/mem0-plugin/tests/test_rubric_dedup.py deleted file mode 100644 index 2a211ddbe..000000000 --- a/integrations/mem0-plugin/tests/test_rubric_dedup.py +++ /dev/null @@ -1,61 +0,0 @@ -"""Tests for rubric deduplication in on_user_prompt.sh.""" - -from __future__ import annotations - -import json -import os -import subprocess - -import pytest - -SCRIPTS_DIR = os.path.join(os.path.dirname(__file__), "..", "scripts") - - -@pytest.fixture(autouse=True) -def _clean_rubric_flag(tmp_path, monkeypatch): - """Use a temp dir for the rubric flag file and clean msg counter.""" - monkeypatch.setenv("MEM0_RUBRIC_DIR", str(tmp_path)) - msg_count_file = "/tmp/mem0_msg_count_testuser" - yield - if os.path.exists(msg_count_file): - os.unlink(msg_count_file) - - -def _run_hook(prompt: str, env_overrides: dict | None = None, session_id: str = "test-sess-001") -> str: - """Run on_user_prompt.sh with a simulated prompt and return stdout.""" - env = { - **os.environ, - "USER": "testuser", - "MEM0_API_KEY": "test-key-123", - "MEM0_RESOLVED_USER_ID": "testuser", - "MEM0_PROJECT_ID": "test-project", - "MEM0_BRANCH": "main", - "MEM0_PREFETCH": "false", - } - if env_overrides: - env.update(env_overrides) - - input_json = json.dumps({"prompt": prompt, "session_id": session_id}) - result = subprocess.run( - ["bash", os.path.join(SCRIPTS_DIR, "on_user_prompt.sh")], - input=input_json, - capture_output=True, - text=True, - env=env, - timeout=10, - ) - return result.stdout - - -def test_first_prompt_gets_full_rubric(): - """First substantial prompt of session gets full memory check rubric.""" - output = _run_hook("How should we refactor the auth module?") - assert "Mem0 searches apply" in output - assert "metadata.type" in output - - -def test_second_prompt_gets_no_rubric(): - """Second prompt of session emits nothing — rubric and tips only on first prompt.""" - _run_hook("How should we refactor the auth module?") - output = _run_hook("What about the database layer?") - assert output.strip() == "" diff --git a/integrations/mem0-plugin/tests/test_search.py b/integrations/mem0-plugin/tests/test_search.py deleted file mode 100644 index 58c1c8042..000000000 --- a/integrations/mem0-plugin/tests/test_search.py +++ /dev/null @@ -1,211 +0,0 @@ -"""Tests for _search.py — shared mem0 search API helper.""" - -from __future__ import annotations - -import json -import urllib.error -from unittest.mock import MagicMock, patch - - -def test_search_memories_returns_results(): - from _search import search_memories - - fake_results = [ - {"id": "abc123", "memory": "Use Postgres for auth", "metadata": {"type": "decision"}}, - {"id": "def456", "memory": "Never use floats for money", "metadata": {"type": "anti_pattern"}}, - ] - - def mock_urlopen(req, timeout=None): - resp = MagicMock() - resp.read.return_value = json.dumps({"results": fake_results}).encode() - resp.__enter__ = lambda s: s - resp.__exit__ = MagicMock(return_value=False) - return resp - - with patch("urllib.request.urlopen", side_effect=mock_urlopen): - results = search_memories("test-key", "user1", "proj1", "auth decisions") - - assert len(results) == 2 - assert results[0]["id"] == "abc123" - - -def test_search_memories_with_metadata_type(): - from _search import search_memories - - captured_body = {} - - def mock_urlopen(req, timeout=None): - captured_body.update(json.loads(req.data.decode())) - resp = MagicMock() - resp.read.return_value = json.dumps({"results": []}).encode() - resp.__enter__ = lambda s: s - resp.__exit__ = MagicMock(return_value=False) - return resp - - with patch("urllib.request.urlopen", side_effect=mock_urlopen): - search_memories("key", "user", "proj", "query", metadata_type="decision") - - filters = captured_body["filters"] - assert {"metadata": {"type": "decision"}} in filters["AND"] - - -def test_search_memories_handles_api_error(): - from _search import search_memories - - with patch("urllib.request.urlopen", side_effect=Exception("timeout")): - results = search_memories("key", "user", "proj", "query") - - assert results == [] - - -def test_search_memories_handles_list_response(): - from _search import search_memories - - fake_results = [{"id": "abc", "memory": "test"}] - - def mock_urlopen(req, timeout=None): - resp = MagicMock() - resp.read.return_value = json.dumps(fake_results).encode() - resp.__enter__ = lambda s: s - resp.__exit__ = MagicMock(return_value=False) - return resp - - with patch("urllib.request.urlopen", side_effect=mock_urlopen): - results = search_memories("key", "user", "proj", "query") - - assert len(results) == 1 - - -def test_search_memories_respects_top_k(): - from _search import search_memories - - captured_body = {} - - def mock_urlopen(req, timeout=None): - captured_body.update(json.loads(req.data.decode())) - resp = MagicMock() - resp.read.return_value = json.dumps({"results": []}).encode() - resp.__enter__ = lambda s: s - resp.__exit__ = MagicMock(return_value=False) - return resp - - with patch("urllib.request.urlopen", side_effect=mock_urlopen): - search_memories("key", "user", "proj", "query", top_k=5) - - assert captured_body["top_k"] == 5 - - -def test_search_memories_no_api_key_returns_empty(): - from _search import search_memories - - results = search_memories("", "user", "proj", "query") - assert results == [] - - -def test_search_memories_logs_rate_limit_error(capsys): - """Bug bash #22: a 429 must not look identical to a genuine empty result.""" - from _search import search_memories - - def mock_urlopen(req, timeout=None): - raise urllib.error.HTTPError("http://x", 429, "Too Many Requests", {}, None) - - with patch("urllib.request.urlopen", side_effect=mock_urlopen): - results = search_memories("key", "user", "proj", "query") - - assert results == [] - err = capsys.readouterr().err - assert "429" in err - assert "Too Many Requests" in err - - -def test_search_memories_happy_path_is_silent(capsys): - from _search import search_memories - - def mock_urlopen(req, timeout=None): - resp = MagicMock() - resp.read.return_value = json.dumps({"results": []}).encode() - resp.__enter__ = lambda s: s - resp.__exit__ = MagicMock(return_value=False) - return resp - - with patch("urllib.request.urlopen", side_effect=mock_urlopen): - results = search_memories("key", "user", "proj", "query") - - assert results == [] - assert capsys.readouterr().err == "" - - -def test_search_memories_omits_rerank_by_default(): - """Regression for #5684: rerank must not be sent unless requested.""" - from _search import search_memories - - captured_body = {} - - def mock_urlopen(req, timeout=None): - captured_body.update(json.loads(req.data.decode())) - resp = MagicMock() - resp.read.return_value = json.dumps({"results": []}).encode() - resp.__enter__ = lambda s: s - resp.__exit__ = MagicMock(return_value=False) - return resp - - with patch("urllib.request.urlopen", side_effect=mock_urlopen): - search_memories("key", "user", "proj", "query") - - assert "rerank" not in captured_body - - -def test_search_memories_forwards_rerank_true(): - """Regression for #5684: rerank=True must reach the request body so the - REST endpoint actually reranks (it does not rerank when omitted).""" - from _search import search_memories - - captured_body = {} - - def mock_urlopen(req, timeout=None): - captured_body.update(json.loads(req.data.decode())) - resp = MagicMock() - resp.read.return_value = json.dumps({"results": []}).encode() - resp.__enter__ = lambda s: s - resp.__exit__ = MagicMock(return_value=False) - return resp - - with patch("urllib.request.urlopen", side_effect=mock_urlopen): - search_memories("key", "user", "proj", "query", rerank=True) - - assert captured_body.get("rerank") is True - - -def test_should_rerank_defaults_true(monkeypatch): - """Regression for #5684: auto-injection reranks by default.""" - from _search import should_rerank - - monkeypatch.delenv("MEM0_RERANK", raising=False) - assert should_rerank() is True - - -def test_should_rerank_opt_out_values(monkeypatch): - from _search import should_rerank - - for falsey in ("0", "false", "False", "NO", "off", ""): - monkeypatch.setenv("MEM0_RERANK", falsey) - assert should_rerank() is False, falsey - - for truthy in ("1", "true", "yes", "on"): - monkeypatch.setenv("MEM0_RERANK", truthy) - assert should_rerank() is True, truthy - - -def test_format_results_for_context(): - from _search import format_results_for_context - - memories = [ - {"id": "abc12345-long-id", "memory": "Use Postgres for auth", "metadata": {"type": "decision"}}, - {"id": "def67890-long-id", "memory": "JWT tokens expire in 1h", "metadata": {"type": "convention"}}, - ] - - output = format_results_for_context(memories, heading="Relevant memories") - assert "Relevant memories" in output - assert "[decision]" in output - assert "Use Postgres for auth" in output - assert "abc12345" in output diff --git a/integrations/mem0-plugin/tests/test_session_stats.py b/integrations/mem0-plugin/tests/test_session_stats.py deleted file mode 100644 index 19d15e20d..000000000 --- a/integrations/mem0-plugin/tests/test_session_stats.py +++ /dev/null @@ -1,248 +0,0 @@ -"""Tests for session_stats.py — session-level memory operation tracker.""" - -from __future__ import annotations - -import json -import os -import subprocess -import sys - -import pytest - -SCRIPTS_DIR = os.path.join(os.path.dirname(__file__), "..", "scripts") - - -@pytest.fixture(autouse=True) -def _isolate_stats_file(tmp_path, monkeypatch): - """Point STATS_FILE to a temp location so tests don't interfere.""" - stats_file = str(tmp_path / "test_stats.json") - monkeypatch.setattr("session_stats.STATS_FILE", stats_file) - yield stats_file - - -def test_init_creates_file(_isolate_stats_file): - import session_stats - - session_stats.init() - assert os.path.isfile(_isolate_stats_file) - with open(_isolate_stats_file) as f: - data = json.load(f) - assert data["adds"] == 0 - assert data["searches"] == 0 - assert data["categories"] == [] - - -def test_record_add_increments(_isolate_stats_file): - import session_stats - - session_stats.init() - session_stats.record_add("bug_fixes") - session_stats.record_add("bug_fixes") - session_stats.record_add("decisions") - - with open(_isolate_stats_file) as f: - data = json.load(f) - assert data["adds"] == 3 - assert set(data["categories"]) == {"bug_fixes", "decisions"} - - -def test_record_search_increments(_isolate_stats_file): - import session_stats - - session_stats.init() - session_stats.record_search() - session_stats.record_search() - - with open(_isolate_stats_file) as f: - data = json.load(f) - assert data["searches"] == 2 - - -def test_report_returns_summary(_isolate_stats_file): - import session_stats - - session_stats.init() - session_stats.record_add("architecture_decisions") - session_stats.record_add("task_learnings") - session_stats.record_search() - session_stats.record_search() - session_stats.record_search() - - result = session_stats.report() - assert "wrote 2 memories" in result - assert "retrieved 3" in result - assert "architecture_decisions" in result - assert "task_learnings" in result - - -def test_report_empty_session(_isolate_stats_file): - import session_stats - - session_stats.init() - result = session_stats.report() - assert result == "" - - -def test_report_preserves_file(_isolate_stats_file): - import session_stats - - session_stats.init() - session_stats.record_add() - session_stats.report() - assert os.path.isfile(_isolate_stats_file) - - -def test_record_add_no_category(_isolate_stats_file): - import session_stats - - session_stats.init() - session_stats.record_add("") - session_stats.record_add() - - with open(_isolate_stats_file) as f: - data = json.load(f) - assert data["adds"] == 2 - assert data["categories"] == [] - - -def test_duplicate_categories_not_added(_isolate_stats_file): - import session_stats - - session_stats.init() - session_stats.record_add("bug_fixes") - session_stats.record_add("bug_fixes") - session_stats.record_add("bug_fixes") - - with open(_isolate_stats_file) as f: - data = json.load(f) - assert data["adds"] == 3 - assert data["categories"] == ["bug_fixes"] - - -def test_cli_init(tmp_path): - """Test CLI invocation: session_stats.py init.""" - env = {**os.environ, "USER": "test"} - result = subprocess.run( - [sys.executable, os.path.join(SCRIPTS_DIR, "session_stats.py"), "init"], - capture_output=True, - text=True, - env=env, - ) - assert result.returncode == 0 - - -def test_cli_report_no_data(tmp_path): - """Test CLI invocation: report with no prior init prints fallback.""" - env = {**os.environ, "USER": f"test_{os.getpid()}"} - result = subprocess.run( - [sys.executable, os.path.join(SCRIPTS_DIR, "session_stats.py"), "report"], - capture_output=True, - text=True, - env=env, - ) - assert result.returncode == 0 - - -def test_peek_returns_json_without_clearing(_isolate_stats_file): - """peek returns JSON stats without deleting the stats file.""" - import session_stats - - session_stats.init() - session_stats.record_add("decisions") - session_stats.record_add("decisions") - session_stats.record_search() - - result = session_stats.peek() - data = json.loads(result) - assert data["adds"] == 2 - assert data["searches"] == 1 - - assert os.path.isfile(_isolate_stats_file) - - -def test_category_counts_tracked(_isolate_stats_file): - """category_counts tracks per-category add counts.""" - import session_stats - - session_stats.init() - session_stats.record_add("bug_fixes") - session_stats.record_add("bug_fixes") - session_stats.record_add("bug_fixes") - session_stats.record_add("decisions") - - with open(_isolate_stats_file) as f: - data = json.load(f) - assert data["category_counts"]["bug_fixes"] == 3 - assert data["category_counts"]["decisions"] == 1 - - -def test_category_counts_empty_category_not_tracked(_isolate_stats_file): - """Empty category string doesn't appear in category_counts.""" - import session_stats - - session_stats.init() - session_stats.record_add("") - session_stats.record_add() - - with open(_isolate_stats_file) as f: - data = json.load(f) - assert data["category_counts"] == {} - - -def test_recent_ids_tracked(_isolate_stats_file): - """record_add with memory_id stores ID in recent_ids.""" - import session_stats - - session_stats.init() - session_stats.record_add("decision", "abc-123") - session_stats.record_add("convention", "def-456") - - with open(_isolate_stats_file) as f: - data = json.load(f) - assert len(data["recent_ids"]) == 2 - assert data["recent_ids"][0]["id"] == "abc-123" - assert data["recent_ids"][1]["id"] == "def-456" - assert data["recent_ids"][0]["category"] == "decision" - - -def test_recent_ids_capped(_isolate_stats_file): - """recent_ids list is capped at MAX_RECENT_IDS.""" - import session_stats - - session_stats.init() - for i in range(60): - session_stats.record_add("test", f"id-{i}") - - with open(_isolate_stats_file) as f: - data = json.load(f) - assert len(data["recent_ids"]) == session_stats.MAX_RECENT_IDS - assert data["recent_ids"][0]["id"] == f"id-{60 - session_stats.MAX_RECENT_IDS}" - - -def test_recent_ids_empty_without_memory_id(_isolate_stats_file): - """record_add without memory_id doesn't add to recent_ids.""" - import session_stats - - session_stats.init() - session_stats.record_add("decision") - session_stats.record_add("convention", "") - - with open(_isolate_stats_file) as f: - data = json.load(f) - assert data["recent_ids"] == [] - - -def test_cli_peek(tmp_path): - """Test CLI invocation: session_stats.py peek outputs JSON.""" - env = {**os.environ, "USER": "test"} - subprocess.run( - [sys.executable, os.path.join(SCRIPTS_DIR, "session_stats.py"), "init"], - capture_output=True, text=True, env=env, - ) - result = subprocess.run( - [sys.executable, os.path.join(SCRIPTS_DIR, "session_stats.py"), "peek"], - capture_output=True, text=True, env=env, - ) - assert result.returncode == 0 - data = json.loads(result.stdout) - assert "adds" in data diff --git a/integrations/mem0-plugin/tests/test_telemetry.py b/integrations/mem0-plugin/tests/test_telemetry.py deleted file mode 100644 index c44cc1b9b..000000000 --- a/integrations/mem0-plugin/tests/test_telemetry.py +++ /dev/null @@ -1,268 +0,0 @@ -"""Tests for telemetry.py — fire-and-forget PostHog plugin telemetry.""" - -from __future__ import annotations - -import json -import os -import sys -import urllib.error - -SCRIPTS_DIR = os.path.join(os.path.dirname(__file__), "..", "scripts") -sys.path.insert(0, os.path.abspath(SCRIPTS_DIR)) - - -def test_import_succeeds(): - import telemetry - - assert hasattr(telemetry, "emit") - assert hasattr(telemetry, "main") - - -def test_opt_out_skips_send(monkeypatch): - import telemetry - - monkeypatch.setenv("MEM0_TELEMETRY", "false") - sent = [] - monkeypatch.setattr(telemetry, "send", lambda p: sent.append(p)) - telemetry.emit("session_start") - assert sent == [] - - -def test_opt_out_variants(monkeypatch): - import telemetry - - for val in ("0", "no", "off", "FALSE", "No"): - monkeypatch.setenv("MEM0_TELEMETRY", val) - assert not telemetry.is_enabled() - - -def test_enabled_by_default(monkeypatch): - import telemetry - - monkeypatch.delenv("MEM0_TELEMETRY", raising=False) - assert telemetry.is_enabled() - - -def test_posthog_payload_structure(monkeypatch): - import telemetry - - monkeypatch.setenv("MEM0_RESOLVED_USER_ID", "testuser") - monkeypatch.setenv("MEM0_PROJECT_ID", "test-project") - monkeypatch.delenv("MEM0_API_KEY", raising=False) - monkeypatch.delenv("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY", raising=False) - - payload = telemetry.build_posthog_payload("plugin.session_start", {"memory_count": 5}) - - assert payload["api_key"] == telemetry.POSTHOG_API_KEY - assert payload["event"] == "plugin.session_start" - assert "distinct_id" in payload - assert payload["properties"]["source"] == "plugin" - assert isinstance(payload["properties"]["plugin_version"], str) - assert payload["properties"]["plugin_version"] != "" - assert payload["properties"]["memory_count"] == 5 - assert payload["properties"]["$process_person_profile"] is False - - raw = json.dumps(payload) - assert "testuser" not in raw - assert "test-project" not in raw - - -def test_system_props_override_caller_props(monkeypatch): - """H8: system properties must win over caller-supplied properties.""" - import telemetry - - monkeypatch.setenv("MEM0_RESOLVED_USER_ID", "testuser") - monkeypatch.setenv("MEM0_PROJECT_ID", "test-project") - monkeypatch.delenv("MEM0_API_KEY", raising=False) - monkeypatch.delenv("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY", raising=False) - - # Caller tries to override system-controlled properties - caller_props = { - "source": "CALLER_OVERRIDE", - "platform": "CALLER_OVERRIDE", - "plugin_version": "CALLER_OVERRIDE", - "memory_count": 42, - } - payload = telemetry.build_posthog_payload("plugin.test", caller_props) - props = payload["properties"] - - # System props must win - assert props["source"] == "plugin" - assert props["platform"] == telemetry.detect_platform() - assert props["plugin_version"] == telemetry._load_plugin_version(telemetry.detect_platform()) - # Caller-only props still present - assert props["memory_count"] == 42 - - -def test_distinct_id_from_api_key(monkeypatch): - import hashlib - - import telemetry - - monkeypatch.setenv("MEM0_API_KEY", "m0-testkey123") - expected = hashlib.sha256(b"m0-testkey123").hexdigest()[:32] - assert telemetry._distinct_id() == expected - - -def test_distinct_id_fallback_no_key(monkeypatch): - import telemetry - - monkeypatch.delenv("MEM0_API_KEY", raising=False) - monkeypatch.delenv("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY", raising=False) - monkeypatch.setenv("MEM0_RESOLVED_USER_ID", "kartik") - assert telemetry._distinct_id() == telemetry._sha256("kartik") - - -def test_hash_deterministic(): - import telemetry - - h1 = telemetry._sha256("same-value") - h2 = telemetry._sha256("same-value") - assert h1 == h2 - assert h1 != telemetry._sha256("different-value") - - -def test_platform_cursor(monkeypatch): - import telemetry - - monkeypatch.delenv("MEM0_PLATFORM", raising=False) - monkeypatch.delenv("ANTIGRAVITY_PLUGIN_ROOT", raising=False) - monkeypatch.delenv("PLUGIN_ROOT", raising=False) - monkeypatch.delenv("CLAUDE_PLUGIN_ROOT", raising=False) - monkeypatch.setenv("CURSOR_PLUGIN_ROOT", "/path") - assert telemetry.detect_platform() == "cursor" - - -def test_platform_codex(monkeypatch): - import telemetry - - monkeypatch.delenv("MEM0_PLATFORM", raising=False) - monkeypatch.delenv("ANTIGRAVITY_PLUGIN_ROOT", raising=False) - monkeypatch.delenv("CLAUDE_PLUGIN_ROOT", raising=False) - monkeypatch.delenv("CURSOR_PLUGIN_ROOT", raising=False) - monkeypatch.setenv("PLUGIN_ROOT", "/path") - assert telemetry.detect_platform() == "codex" - - -def test_platform_kimi(monkeypatch): - """Kimi Code usage must be attributed to its own platform so it can be - counted distinctly. The shim also pins MEM0_PLATFORM=kimi; this covers the - KIMI_PLUGIN_ROOT auto-detection fallback.""" - import telemetry - - monkeypatch.delenv("MEM0_PLATFORM", raising=False) - monkeypatch.delenv("ANTIGRAVITY_PLUGIN_ROOT", raising=False) - monkeypatch.delenv("CLAUDE_PLUGIN_ROOT", raising=False) - monkeypatch.delenv("CURSOR_PLUGIN_ROOT", raising=False) - monkeypatch.delenv("PLUGIN_ROOT", raising=False) - monkeypatch.setenv("KIMI_PLUGIN_ROOT", "/path") - assert telemetry.detect_platform() == "kimi" - - -def test_platform_explicit_override(monkeypatch): - """MEM0_PLATFORM wins over auto-detection so each editor can label - itself reliably even when host env vars are ambiguous or absent.""" - import telemetry - - monkeypatch.setenv("CLAUDE_PLUGIN_ROOT", "/path") # conflicting auto-signal - monkeypatch.setenv("MEM0_PLATFORM", "cursor") - assert telemetry.detect_platform() == "cursor" - - -def test_platform_antigravity(monkeypatch): - """Antigravity sets CLAUDE_PLUGIN_ROOT so the shared scripts resolve their - paths. That must not change how it is attributed.""" - import telemetry - - monkeypatch.delenv("MEM0_PLATFORM", raising=False) - monkeypatch.setenv("ANTIGRAVITY_PLUGIN_ROOT", "/ext") - monkeypatch.setenv("CLAUDE_PLUGIN_ROOT", "/ext") # antigravity sets both - assert telemetry.detect_platform() == "antigravity" - - -def test_plugin_version_is_per_editor(monkeypatch): - """Each editor reports the version from its OWN manifest. Antigravity is on - a 0.1.x line while Cursor/Codex are on 0.2.x, so they must not all report - the same shared version. An unsupported surface reports "unknown" rather - than borrowing a version it does not ship.""" - import telemetry - - plugin_dir = os.path.join(os.path.dirname(__file__), "..") - manifests = { - "antigravity": "plugin.json", - "cursor": os.path.join(".cursor-plugin", "plugin.json"), - "codex": os.path.join(".codex-plugin", "plugin.json"), - "kimi": os.path.join(".kimi-plugin", "plugin.json"), - } - for plat, rel in manifests.items(): - monkeypatch.setenv("MEM0_PLATFORM", plat) - with open(os.path.join(plugin_dir, rel)) as f: - expected = json.load(f)["version"] - payload = telemetry.build_posthog_payload("plugin.test") - assert payload["properties"]["plugin_version"] == expected, f"{plat} should report {expected} from {rel}" - - monkeypatch.setenv("MEM0_PLATFORM", "claude-code") - payload = telemetry.build_posthog_payload("plugin.test") - assert payload["properties"]["plugin_version"] == "unknown" - - -def test_send_fails_silently(monkeypatch): - import telemetry - - def raise_error(req, timeout): - raise urllib.error.URLError("connection refused") - - monkeypatch.setattr(telemetry.urllib.request, "urlopen", raise_error) - telemetry.send({"event": "test"}) - - -def test_cli_exits_zero_when_disabled(monkeypatch): - import telemetry - - monkeypatch.setenv("MEM0_TELEMETRY", "false") - monkeypatch.setattr(sys, "argv", ["telemetry.py", "session_start"]) - assert telemetry.main() == 0 - - -def test_cli_no_args_exits_nonzero(monkeypatch): - import telemetry - - monkeypatch.delenv("MEM0_TELEMETRY", raising=False) - monkeypatch.setattr(sys, "argv", ["telemetry.py"]) - assert telemetry.main() == 1 - - -def test_cursor_wrappers_pin_platform(): - """Cursor wrappers delegate to the shared scripts, which auto-detect the - platform from host env vars. Since Cursor may not export CURSOR_PLUGIN_ROOT - to the subprocess, each wrapper must pin MEM0_PLATFORM=cursor so the - delegated telemetry is attributed to cursor, not the 'plugin' fallback.""" - scripts_dir = os.path.join(os.path.dirname(__file__), "..", "scripts") - cursor_wrappers = [ - "on_session_start_cursor.sh", - "on_user_prompt_cursor.sh", - "on_post_tool_use_cursor.sh", - "on_pre_compact_cursor.sh", - "on_stop_cursor.sh", - ] - for name in cursor_wrappers: - with open(os.path.join(scripts_dir, name)) as f: - content = f.read() - assert "export MEM0_PLATFORM=cursor" in content, f"{name} must `export MEM0_PLATFORM=cursor` before delegating" - - -def test_codex_hooks_pin_platform(): - """Codex installs standalone hooks (absolute paths) via install_codex_hooks.py, - so PLUGIN_ROOT is not set at runtime and the platform falls back to 'plugin'. - Codex runs hook commands through a shell, so every command pins - MEM0_PLATFORM=codex inline for correct attribution.""" - hooks_path = os.path.join(os.path.dirname(__file__), "..", "hooks", "codex-hooks.json") - with open(hooks_path) as f: - config = json.load(f) - - commands = [ - h["command"] for entries in config["hooks"].values() for entry in entries for h in entry.get("hooks", []) - ] - assert commands, "expected at least one codex hook command" - for cmd in commands: - assert "MEM0_PLATFORM=codex" in cmd, f"codex hook command missing platform pin: {cmd}" diff --git a/integrations/mem0-plugin/tests/test_write_path.py b/integrations/mem0-plugin/tests/test_write_path.py deleted file mode 100644 index 1be57df83..000000000 --- a/integrations/mem0-plugin/tests/test_write_path.py +++ /dev/null @@ -1,207 +0,0 @@ -"""Tests for write-path app_id migration and API key resolution. - -Verifies that all scripts writing to the Mem0 API: -1. Pass app_id as a top-level parameter (not in metadata) -2. Do NOT include project_id in metadata -3. Include branch in metadata when available -4. Use resolve_api_key() for key resolution with userConfig fallback -""" - -from __future__ import annotations - -import json -from unittest.mock import MagicMock, patch - - -def test_auto_import_post_memory_uses_app_id(): - """auto_import.post_memory sends app_id top-level, not metadata.project_id.""" - from auto_import import post_memory - - captured = {} - - def mock_urlopen(req, timeout=None): - body = json.loads(req.data.decode("utf-8")) - captured.update(body) - resp = MagicMock() - resp.status = 200 - resp.__enter__ = lambda s: s - resp.__exit__ = MagicMock(return_value=False) - return resp - - with patch("urllib.request.urlopen", side_effect=mock_urlopen): - result = post_memory( - api_key="test-key", - content="test content", - user_id="testuser", - filename="CLAUDE.md", - project_id="my-project", - branch="main", - ) - - assert result is True - assert captured["app_id"] == "my-project" - assert captured["user_id"] == "testuser" - assert "project_id" not in captured.get("metadata", {}) - assert captured["metadata"]["type"] == "project_profile" - assert captured["metadata"]["branch"] == "main" - assert captured["infer"] is False - - -def test_auto_import_post_memory_omits_empty_branch(): - """auto_import.post_memory skips branch in metadata when empty.""" - from auto_import import post_memory - - captured = {} - - def mock_urlopen(req, timeout=None): - body = json.loads(req.data.decode("utf-8")) - captured.update(body) - resp = MagicMock() - resp.status = 200 - resp.__enter__ = lambda s: s - resp.__exit__ = MagicMock(return_value=False) - return resp - - with patch("urllib.request.urlopen", side_effect=mock_urlopen): - post_memory("key", "content", "user", "FILE.md", "proj", branch="") - - assert "branch" not in captured.get("metadata", {}) - - -def test_on_pre_compact_store_memory_uses_app_id(): - """on_pre_compact.store_memory sends app_id top-level.""" - from on_pre_compact import store_memory - - captured = {} - - def mock_urlopen(req, timeout=None): - body = json.loads(req.data.decode("utf-8")) - captured.update(body) - resp = MagicMock() - resp.status = 200 - resp.__enter__ = lambda s: s - resp.__exit__ = MagicMock(return_value=False) - return resp - - with patch("urllib.request.urlopen", side_effect=mock_urlopen): - result = store_memory( - api_key="test-key", - content="session state content", - user_id="testuser", - source="pre-compaction", - session_id="sess-123", - project_id="my-project", - branch="feat/auth", - ) - - assert result is True - assert captured["app_id"] == "my-project" - assert captured["user_id"] == "testuser" - assert "project_id" not in captured.get("metadata", {}) - assert captured["metadata"]["type"] == "session_state" - assert captured["metadata"]["source"] == "pre-compaction" - assert captured["metadata"]["branch"] == "feat/auth" - assert "expiration_date" in captured - - -def test_capture_compact_summary_store_uses_app_id(): - """capture_compact_summary.store_summary sends app_id top-level.""" - from capture_compact_summary import store_summary - - captured = {} - - def mock_urlopen(req, timeout=None): - body = json.loads(req.data.decode("utf-8")) - captured.update(body) - resp = MagicMock() - resp.status = 200 - resp.__enter__ = lambda s: s - resp.__exit__ = MagicMock(return_value=False) - return resp - - with patch("urllib.request.urlopen", side_effect=mock_urlopen): - result = store_summary( - api_key="test-key", - summary="compact summary text", - user_id="testuser", - session_id="sess-456", - project_id="my-project", - branch="main", - ) - - assert result is True - assert captured["app_id"] == "my-project" - assert captured["user_id"] == "testuser" - assert "project_id" not in captured.get("metadata", {}) - assert captured["metadata"]["type"] == "compact_summary" - assert captured["metadata"]["branch"] == "main" - assert captured["infer"] is True - assert "expiration_date" in captured - - -def test_no_metadata_project_id_anywhere(): - """Ensure none of the write functions put project_id in metadata.""" - from auto_import import post_memory - from capture_compact_summary import store_summary - from on_pre_compact import store_memory - - bodies = [] - - def mock_urlopen(req, timeout=None): - body = json.loads(req.data.decode("utf-8")) - bodies.append(body) - resp = MagicMock() - resp.status = 200 - resp.__enter__ = lambda s: s - resp.__exit__ = MagicMock(return_value=False) - return resp - - with patch("urllib.request.urlopen", side_effect=mock_urlopen): - post_memory("k", "c", "u", "f", "proj", "br") - store_memory("k", "c", "u", "src", "sid", "proj", "br") - store_summary("k", "s", "u", "sid", "proj", "br") - - for i, body in enumerate(bodies): - metadata = body.get("metadata", {}) - assert "project_id" not in metadata, f"Write function #{i} still has metadata.project_id" - assert body.get("app_id") == "proj", f"Write function #{i} missing app_id top-level" - - -def test_resolve_api_key_prefers_env_var(monkeypatch): - """resolve_api_key returns MEM0_API_KEY when both are set.""" - from _identity import resolve_api_key - - monkeypatch.setenv("MEM0_API_KEY", "direct-key") - monkeypatch.setenv("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY", "fallback-key") - assert resolve_api_key() == "direct-key" - - -def test_resolve_api_key_falls_back_to_plugin_option(monkeypatch): - """resolve_api_key falls back to CLAUDE_PLUGIN_OPTION_MEM0_API_KEY.""" - from _identity import resolve_api_key - - monkeypatch.delenv("MEM0_API_KEY", raising=False) - monkeypatch.setenv("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY", "fallback-key") - assert resolve_api_key() == "fallback-key" - - -def test_resolve_api_key_returns_empty_when_neither_set(monkeypatch): - """resolve_api_key returns empty string when no key is available.""" - from _identity import resolve_api_key - - monkeypatch.delenv("MEM0_API_KEY", raising=False) - monkeypatch.delenv("CLAUDE_PLUGIN_OPTION_API_KEY", raising=False) - monkeypatch.delenv("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY", raising=False) - monkeypatch.setattr("_identity._extract_key_from_shell_profiles", lambda: "") - assert resolve_api_key() == "" - - -def test_resolve_api_key_falls_back_to_shell_profile(monkeypatch): - """resolve_api_key extracts key from shell profile when env vars are empty.""" - from _identity import resolve_api_key - - monkeypatch.delenv("MEM0_API_KEY", raising=False) - monkeypatch.delenv("CLAUDE_PLUGIN_OPTION_API_KEY", raising=False) - monkeypatch.delenv("CLAUDE_PLUGIN_OPTION_MEM0_API_KEY", raising=False) - monkeypatch.setattr("_identity._extract_key_from_shell_profiles", lambda: "m0-from-profile") - assert resolve_api_key() == "m0-from-profile" diff --git a/integrations/mem0-strands/python/pyproject.toml b/integrations/mem0-strands/python/pyproject.toml index 5b558993f..5776ad695 100644 --- a/integrations/mem0-strands/python/pyproject.toml +++ b/integrations/mem0-strands/python/pyproject.toml @@ -77,7 +77,7 @@ select = [ ] [tool.mypy] -python_version = "3.10" +python_version = "3.12" warn_return_any = true warn_unused_configs = true ignore_missing_imports = true diff --git a/integrations/openclaw/README.md b/integrations/openclaw/README.md index 4db861feb..1d70dffa3 100644 --- a/integrations/openclaw/README.md +++ b/integrations/openclaw/README.md @@ -4,7 +4,7 @@ Long-term memory for [OpenClaw](https://github.com/openclaw/openclaw) agents, po Your agent forgets everything between sessions. This plugin fixes that — it stores conversations, extracts what matters, and brings it back when relevant. -By default, the plugin runs in **skills mode**: the agent controls what to remember (triage), how to recall (recall), and periodic cleanup (dream). Skills mode, `autoRecall`, and `autoCapture` are all enabled by default during `openclaw mem0 init`. +By default, the plugin runs in **skills mode**: the agent controls what to remember (triage) and how to recall (recall). Skills mode, `autoRecall`, and `autoCapture` are all enabled by default during `openclaw mem0 init`. ## Requirements @@ -74,7 +74,6 @@ Humans should follow the Quick Start below. "keywordSearch": true, "identityAlwaysInclude": true }, - "dream": { "enabled": true }, "domain": "companion" } } @@ -210,11 +209,10 @@ All `oss` fields are optional. See the [Mem0 OSS docs](https://docs.mem0.ai/open ### Skills Mode (Default) -Enabled automatically during `openclaw mem0 init`. The agent controls memory through three skills: +Enabled automatically during `openclaw mem0 init`. The agent controls memory through two skills: - **Triage** — Extracts durable facts from conversations using a structured protocol. Categories, importance gates, and domain overlays control what gets stored. - **Recall** — Before each turn, rewrites the user message into search queries, retrieves relevant memories with reranking, and injects them into context. -- **Dream** — Periodic memory consolidation: merges duplicates, resolves conflicts, and prunes stale entries. When skills mode is active, the skills handle memory operations. `autoRecall` and `autoCapture` remain `true` by default alongside skills mode. The built-in `session-memory` hook is disabled to avoid conflicts. @@ -280,10 +278,6 @@ openclaw mem0 config set user_id alice openclaw mem0 event list openclaw mem0 event status -# Memory consolidation -openclaw mem0 dream -openclaw mem0 dream --dry-run - # JSON output (any command) openclaw mem0 search "preferences" --json openclaw mem0 list --json @@ -316,7 +310,6 @@ Enabled by default during `openclaw mem0 init`. `autoRecall` and `autoCapture` a | `skills.recall.rerank` | `boolean` | `true` | Rerank search results for relevance | | `skills.recall.keywordSearch` | `boolean` | `true` | Augment with keyword-based search | | `skills.recall.identityAlwaysInclude` | `boolean` | `true` | Always include identity memories | -| `skills.dream.enabled` | `boolean` | `true` | Enable periodic memory consolidation | | `skills.domain` | `string` | `"companion"` | Domain overlay for triage rules | ### Platform Mode @@ -362,7 +355,7 @@ To avoid plaintext credentials: ### Memory Processing -In **skills mode** (default after `openclaw mem0 init`), the agent uses structured protocols (triage, recall, dream) to decide what to store and recall. The built-in `session-memory` hook is disabled to avoid conflicts. +In **skills mode** (default after `openclaw mem0 init`), the agent uses structured triage and recall protocols to decide what to store and recall. The built-in `session-memory` hook is disabled to avoid conflicts. Without skills, `autoCapture` and `autoRecall` are both enabled by default: - `autoCapture`: sends conversation content to your configured backend after each agent turn @@ -377,7 +370,6 @@ In platform mode, conversation content is sent to `api.mem0.ai` for processing. | `~/.openclaw/openclaw.json` | Plugin configuration (API keys, user ID, settings) | | `~/.mem0/vector_store.db` | Local vector store (open-source mode only) | | `~/.mem0/history.db` | Memory edit history (open-source mode only) | -| `/dream-state.json` | Memory consolidation state | ## License diff --git a/integrations/openclaw/cli/commands.ts b/integrations/openclaw/cli/commands.ts index 2d5897446..e2eb71bf5 100644 --- a/integrations/openclaw/cli/commands.ts +++ b/integrations/openclaw/cli/commands.ts @@ -20,7 +20,6 @@ * - config set : Update a plugin config field * - event list : List recent background events * - event status: Get status of a specific event - * - dream : Run memory consolidation * * Naming conventions match the Python CLI (`mem0 init`, `mem0 search`, etc.) */ @@ -36,7 +35,6 @@ import type { MemoryItem, SearchOptions, } from "../types.ts"; -import { loadDreamPrompt } from "../skill-loader.ts"; import { readText } from "../fs-safe.ts"; import type { PluginAuthConfig } from "./config-file.ts"; import { @@ -1227,7 +1225,18 @@ export function registerCliCommands( .option("--json", "Output as JSON") .action(async (opts: { json?: boolean } = {}) => { try { - const auth = readPluginAuth(); + if (cfg.needsSetup || !backend) { + const error = "Mem0 is not configured. Run `openclaw mem0 init`."; + if (jsonOut(opts, { + ok: true, + mode: cfg.mode, + connected: false, + userId: cfg.userId, + error, + })) return; + console.log(error); + return; + } const result = await backend.status(); if (jsonOut(opts, { ok: true, @@ -1714,7 +1723,6 @@ export function registerCliCommands( status: "Check connectivity and authentication", config: "Manage mem0 configuration (show, get, set)", event: "Manage background processing events (list, status)", - dream: "Run memory consolidation (review, merge, prune)", help: "Show help. Use --json for machine-readable output (for LLM agents)", }, }; @@ -1736,7 +1744,6 @@ export function registerCliCommands( status: { description: "Check connectivity", flags: { "--json": "JSON output" } }, config: { description: "Manage configuration (show, get, set)", flags: { "--json": "JSON output" } }, event: { description: "Manage background events (list, status)", flags: { "--json": "JSON output" } }, - dream: { description: "Run memory consolidation", flags: { "--dry-run": "Show inventory only", "--json": "JSON output" } }, help: { description: "Show help", flags: { "--json": "JSON output" } }, }, }, @@ -1760,108 +1767,6 @@ export function registerCliCommands( console.log(""); }); - // ==================================================================== - // dream - // ==================================================================== - - mem0 - .command("dream") - .description( - "Run memory consolidation (review, merge, prune stored memories)", - ) - .option( - "--dry-run", - "Show memory inventory without running consolidation", - ) - .option("--json", "Output as JSON") - .action(async (opts: { dryRun?: boolean; json?: boolean }) => { - try { - const uid = cfg.userId; - const memories = await provider.getAll({ - user_id: uid, - source: "OPENCLAW", - }); - const count = Array.isArray(memories) ? memories.length : 0; - - if (count === 0) { - if (jsonOut(opts, { ok: true, count: 0, message: "No memories to consolidate." })) return; - console.log("No memories to consolidate."); - return; - } - - const catCounts = new Map(); - for (const mem of memories) { - const cat = - (mem.metadata as any)?.category ?? - mem.categories?.[0] ?? - "uncategorized"; - catCounts.set(cat, (catCounts.get(cat) ?? 0) + 1); - } - - if (opts.dryRun && opts.json) { - jsonOut(opts, { ok: true, count, categories: Object.fromEntries(catCounts) }); - return; - } - - if (opts.json && !opts.dryRun) { - jsonOut(opts, { ok: true, count, message: `${count} memories available for consolidation` }); - return; - } - - process.stderr.write(`\nMemory inventory for "${uid}":\n`); - for (const [cat, num] of [...catCounts.entries()].sort( - (a, b) => b[1] - a[1], - )) { - process.stderr.write(` ${cat}: ${num}\n`); - } - process.stderr.write(` TOTAL: ${count}\n\n`); - - if (opts.dryRun) { - process.stderr.write("Dry run — no changes made.\n"); - return; - } - - const dreamPrompt = loadDreamPrompt(cfg.skills ?? {}); - if (!dreamPrompt) { - process.stderr.write( - "Dream skill file not found at skills/memory-dream/SKILL.md\n", - ); - return; - } - - const memoryDump = (memories as MemoryItem[]) - .map((m, i) => { - const cat = - (m.metadata as any)?.category ?? - m.categories?.[0] ?? - "uncategorized"; - const imp = (m.metadata as any)?.importance ?? "?"; - const created = m.created_at ?? "unknown"; - return `${i + 1}. [${m.id}] (${cat}, importance: ${imp}, created: ${created}) ${m.memory}`; - }) - .join("\n"); - - const fullPrompt = [ - "", - dreamPrompt, - "", - "", - ``, - memoryDump, - "", - "", - "Begin consolidation. Review all memories above and execute merge, delete, and rewrite operations using the available tools.", - ].join("\n"); - - process.stdout.write(fullPrompt + "\n"); - process.stderr.write( - `Dream prompt written to stdout (${fullPrompt.length} chars). Paste it into an OpenClaw session to run consolidation.\n`, - ); - } catch (err) { - if (jsonErr(opts, `Dream failed: ${String(err)}`)) return; - console.error(`Dream failed: ${String(err)}`); - } - }); }, { descriptors: [ diff --git a/integrations/openclaw/cli/config-file.ts b/integrations/openclaw/cli/config-file.ts index 2af2f36bd..99453cb1b 100644 --- a/integrations/openclaw/cli/config-file.ts +++ b/integrations/openclaw/cli/config-file.ts @@ -189,7 +189,7 @@ export function writePluginConfigField( /** * Default skills configuration — matches configure.py output. - * Enables triage, recall (with reranking), and dream consolidation. + * Enables triage and recall with reranking. */ const DEFAULT_SKILLS_CONFIG = { triage: { enabled: true }, @@ -200,7 +200,6 @@ const DEFAULT_SKILLS_CONFIG = { keywordSearch: true, identityAlwaysInclude: true, }, - dream: { enabled: true }, domain: "companion", }; diff --git a/integrations/openclaw/dream-gate.ts b/integrations/openclaw/dream-gate.ts deleted file mode 100644 index 4d7764725..000000000 --- a/integrations/openclaw/dream-gate.ts +++ /dev/null @@ -1,214 +0,0 @@ -/** - * Dream Gate — activity tracking, gate logic, and lock mechanism - * for automatic memory consolidation. - * - * State persists in the plugin's stateDir so it survives gateway restarts. - * Lock prevents concurrent consolidation runs. - */ - -import * as path from "node:path"; -import { readText, writeText, mkdirp, unlink } from "./fs-safe.ts"; - -// ============================================================================ -// Types -// ============================================================================ - -interface DreamState { - lastConsolidatedAt: number; // ms since epoch, 0 = never - sessionsSince: number; // interactive sessions since last consolidation - lastSessionId: string | null; -} - -interface DreamLock { - pid: number; - startedAt: number; -} - -interface DreamGateConfig { - minHours: number; - minSessions: number; - minMemories: number; -} - -const DEFAULTS: DreamGateConfig = { - minHours: 24, - minSessions: 5, - minMemories: 20, -}; - -const LOCK_STALE_MS = 60 * 60 * 1000; // 1 hour - -// ============================================================================ -// State Persistence -// ============================================================================ - -function statePath(stateDir: string): string { - return path.join(stateDir, "dream-state.json"); -} - -function lockPath(stateDir: string): string { - return path.join(stateDir, "dream.lock"); -} - -function ensureDir(dir: string): void { - try { - mkdirp(dir); - } catch { - /* exists */ - } -} - -function readState(stateDir: string): DreamState { - try { - const raw = readText(statePath(stateDir)); - return JSON.parse(raw) as DreamState; - } catch { - return { lastConsolidatedAt: 0, sessionsSince: 0, lastSessionId: null }; - } -} - -function writeState(stateDir: string, state: DreamState): void { - ensureDir(stateDir); - writeText(statePath(stateDir), JSON.stringify(state, null, 2)); -} - -// ============================================================================ -// Session Tracking -// ============================================================================ - -/** - * Called from agent_end on every interactive turn. - * Increments session counter (deduped by sessionId). - */ -export function incrementSessionCount( - stateDir: string, - sessionId: string, -): void { - const state = readState(stateDir); - if (state.lastSessionId !== sessionId) { - state.sessionsSince++; - state.lastSessionId = sessionId; - writeState(stateDir, state); - } -} - -// ============================================================================ -// Gate Logic -// ============================================================================ - -/** - * Check cheap gates (time + sessions). These are local file reads only. - * Call this BEFORE any API calls. If this fails, skip the expensive - * memory count check entirely. - */ -export function checkCheapGates( - stateDir: string, - config: { minHours?: number; minSessions?: number }, -): { proceed: boolean; reason?: string } { - const minHours = config.minHours ?? DEFAULTS.minHours; - const minSessions = config.minSessions ?? DEFAULTS.minSessions; - const state = readState(stateDir); - - // Gate 1: Time (one local file read) - const hoursSince = (Date.now() - state.lastConsolidatedAt) / 3_600_000; - if (hoursSince < minHours) { - return { - proceed: false, - reason: `time: ${hoursSince.toFixed(1)}h < ${minHours}h`, - }; - } - - // Gate 2: Sessions (same file, already read) - if (state.sessionsSince < minSessions) { - return { - proceed: false, - reason: `sessions: ${state.sessionsSince} < ${minSessions}`, - }; - } - - return { proceed: true }; -} - -/** - * Check expensive memory count gate. Only call AFTER checkCheapGates passes. - */ -export function checkMemoryGate( - memoryCount: number, - config: { minMemories?: number }, -): { pass: boolean; reason?: string } { - const minMemories = config.minMemories ?? DEFAULTS.minMemories; - if (memoryCount < minMemories) { - return { pass: false, reason: `memories: ${memoryCount} < ${minMemories}` }; - } - return { pass: true }; -} - -// ============================================================================ -// Lock -// ============================================================================ - -/** - * Try to acquire the dream lock. Returns true if acquired. - * Stale locks (older than 1 hour) are reclaimed. - */ -export function acquireDreamLock(stateDir: string): boolean { - ensureDir(stateDir); - const lp = lockPath(stateDir); - - // Check existing lock - try { - const raw = readText(lp); - const lock = JSON.parse(raw) as DreamLock; - const age = Date.now() - lock.startedAt; - if (age < LOCK_STALE_MS) { - return false; // Held and not stale - } - // Stale lock — remove it before attempting exclusive create - try { - unlink(lp); - } catch { - /* race ok */ - } - } catch { - // No lock file, proceed - } - - // Atomic create with exclusive flag (wx). If two processes race, - // only one succeeds. The other gets EEXIST. - const lock: DreamLock = { pid: process.pid, startedAt: Date.now() }; - try { - writeText(lp, JSON.stringify(lock), { flag: "wx" }); - return true; - } catch { - return false; // Lost race - } -} - -/** - * Release the dream lock and record successful completion. - */ -export function releaseDreamLock(stateDir: string): void { - try { - unlink(lockPath(stateDir)); - } catch { - /* already gone */ - } -} - -/** - * Record that consolidation completed. Resets session counter. - */ -export function recordDreamCompletion(stateDir: string): void { - const state = readState(stateDir); - state.lastConsolidatedAt = Date.now(); - state.sessionsSince = 0; - state.lastSessionId = null; - writeState(stateDir, state); -} - -/** - * Get current dream state for logging/diagnostics. - */ -export function getDreamState(stateDir: string): DreamState { - return readState(stateDir); -} diff --git a/integrations/openclaw/filtering.ts b/integrations/openclaw/filtering.ts index 6c51a2798..84500fa98 100644 --- a/integrations/openclaw/filtering.ts +++ b/integrations/openclaw/filtering.ts @@ -1,6 +1,6 @@ /** * Pre-extraction message filtering: noise detection, content stripping, - * generic assistant detection, truncation, and deduplication. + * and generic assistant detection. */ import type { MemoryItem } from "./types.ts"; @@ -109,8 +109,6 @@ const NOISE_CONTENT_PATTERNS: Array<{ pattern: RegExp; replacement: string }> = }, ]; -const MAX_MESSAGE_LENGTH = 2000; - /** * Patterns indicating an assistant message is a generic acknowledgment with * no extractable facts. These are produced when the agent receives a @@ -179,19 +177,9 @@ export function stripNoiseFromContent(content: string): string { return cleaned; } -/** - * Truncate a message to `MAX_MESSAGE_LENGTH` characters, preserving the - * opening (which typically contains the summary/conclusion) and appending - * a truncation marker so the extraction model knows content was cut. - */ -function truncateMessage(content: string): string { - if (content.length <= MAX_MESSAGE_LENGTH) return content; - return content.slice(0, MAX_MESSAGE_LENGTH) + "\n[...truncated]"; -} - /** * Full pre-extraction pipeline: drop noise messages, strip noise fragments, - * filter session-specific content, and truncate remaining messages. + * and filter session-specific content without truncating remaining messages. */ export function filterMessagesForExtraction( messages: Array<{ role: string; content: string }>, @@ -206,7 +194,7 @@ export function filterMessagesForExtraction( if (isSessionSpecificContent(msg.content)) continue; const cleaned = stripNoiseFromContent(msg.content); if (!cleaned) continue; - filtered.push({ role: msg.role, content: truncateMessage(cleaned) }); + filtered.push({ role: msg.role, content: cleaned }); } return filtered; } diff --git a/integrations/openclaw/index.test.ts b/integrations/openclaw/index.test.ts index da86c5a7c..d3f4ea775 100644 --- a/integrations/openclaw/index.test.ts +++ b/integrations/openclaw/index.test.ts @@ -3,6 +3,7 @@ * message filtering logic. */ import { describe, it, expect, vi } from "vitest"; +import { createMemoryLifecycle } from "../agent-plugin-core/typescript/src/lifecycle.ts"; import memoryPlugin, { extractAgentId, effectiveUserId, @@ -521,13 +522,14 @@ What is the deployment plan?`, expect(result[0].content).toBe("What is the deployment plan?"); }); - it("truncates long messages", () => { - const longContent = "A".repeat(3000); - const messages = [{ role: "assistant", content: longContent }]; - const result = filterMessagesForExtraction(messages); - expect(result).toHaveLength(1); - expect(result[0].content.length).toBeLessThan(2100); - expect(result[0].content).toContain("[...truncated]"); + it.each(["user", "assistant"])("preserves long %s messages through extraction preparation", (role) => { + const content = "Repository detail. ".repeat(600) + "Final requirement. password=hidden-extraction-secret"; + const result = createMemoryLifecycle().prepareConversation( + filterMessagesForExtraction([{ role, content }]), + ); + expect(result).toEqual([ + { role, content: content.replace("hidden-extraction-secret", "[REDACTED]") }, + ]); }); it("returns empty array when all messages are noise", () => { diff --git a/integrations/openclaw/index.ts b/integrations/openclaw/index.ts index 58f59b6f9..835a869bd 100644 --- a/integrations/openclaw/index.ts +++ b/integrations/openclaw/index.ts @@ -43,18 +43,9 @@ import { } from "./isolation.ts"; import { loadCompactTriagePrompt, - loadDreamPrompt, isSkillsMode, } from "./skill-loader.ts"; import { recall as skillRecall, sanitizeQuery } from "./recall.ts"; -import { - incrementSessionCount, - checkCheapGates, - checkMemoryGate, - acquireDreamLock, - releaseDreamLock, - recordDreamCompletion, -} from "./dream-gate.ts"; import { PlatformBackend } from "./backend/platform.ts"; import type { Backend } from "./backend/base.ts"; import { registerCliCommands } from "./cli/commands.ts"; @@ -62,6 +53,7 @@ import { readPluginAuth } from "./cli/config-file.ts"; import { registerAllTools } from "./tools/index.ts"; import type { ToolDeps } from "./tools/index.ts"; import { captureEvent } from "./telemetry.ts"; +import { createMemoryLifecycle } from "../agent-plugin-core/typescript/src/lifecycle.ts"; import { bootstrapTelemetryFlag } from "./fs-safe.ts"; // ============================================================================ @@ -176,6 +168,8 @@ const memoryPlugin = definePluginEntry({ } const provider = createProvider(cfg, api); + const lifecycle = createMemoryLifecycle(); + lifecycle.beginSession(); // Create Backend instance — PlatformBackend for platform mode, providerToBackend adapter for OSS let backend: Backend; @@ -220,10 +214,6 @@ const memoryPlugin = definePluginEntry({ api.registerMemoryCapability({ publicArtifacts: createPublicArtifactsProvider({ provider, - cfg, - get stateDir() { - return pluginStateDir; - }, effectiveUserId: _effectiveUserId, }), runtime: { @@ -373,10 +363,10 @@ const memoryPlugin = definePluginEntry({ setCurrentSessionId: (id: string) => { currentSessionId = id; }, - getStateDir: () => pluginStateDir, }, skillsActive, _captureEvent, + lifecycle, ); // ======================================================================== @@ -420,13 +410,13 @@ function registerHooks( ) => SearchOptions, session: { setCurrentSessionId: (id: string) => void; - getStateDir: () => string | undefined; }, skillsActive: boolean = false, _captureEvent: ( event: string, props?: Record, ) => void = () => {}, + lifecycle: ReturnType = createMemoryLifecycle(), ) { // ======================================================================== // SKILLS MODE: Agentic memory via before_prompt_build @@ -493,7 +483,7 @@ function registerHooks( if (recallEnabled && recallStrategy !== "manual") { const recallStart = Date.now(); try { - const query = sanitizeQuery(event.prompt); + const query = lifecycle.prepareUserText(sanitizeQuery(event.prompt)); // Smart mode: skip session search (saves 1 API call per turn) const sessionIdForRecall = @@ -533,142 +523,18 @@ function registerHooks( ); } - // Auto-dream: check CHEAP gates first (local file reads only). - // Only hit the API for memory count if time + session gates pass. - const stateDir = session.getStateDir(); - const dreamEnabled = - cfg.skills?.dream?.enabled !== false && - cfg.skills?.dream?.auto !== false; - let dreamContext = ""; - if (dreamEnabled && stateDir && !isSubagent) { - try { - const cheapResult = checkCheapGates( - stateDir, - cfg.skills?.dream ?? {}, - ); - if (cheapResult.proceed) { - // Cheap gates passed. Now do the expensive memory count check. - const memories = await provider.getAll({ - user_id: userId, - source: "OPENCLAW", - }); - const memCount = Array.isArray(memories) ? memories.length : 0; - const memResult = checkMemoryGate( - memCount, - cfg.skills?.dream ?? {}, - ); - if (memResult.pass && acquireDreamLock(stateDir)) { - const dreamPrompt = loadDreamPrompt(cfg.skills ?? {}); - if (dreamPrompt) { - dreamContext = - "\n\n\nIMPORTANT: Before responding to the user, run a memory consolidation pass. Follow the protocol below, then respond normally.\n\n" + - dreamPrompt + - "\n"; - // Track which session triggered dream (session-keyed, not global) - dreamSessionId = sessionId; - _captureEvent("openclaw.hook.dream", { - phase: "triggered", - memory_count: memCount, - }); - api.logger.info( - `openclaw-mem0: auto-dream triggered (${memCount} memories, gate passed)`, - ); - } else { - releaseDreamLock(stateDir); - } - } - } - } catch (err) { - api.logger.warn( - `openclaw-mem0: auto-dream gate check failed: ${String(err)}`, - ); - } - } - return { prependSystemContext: systemContext, // cached by provider - prependContext: recallContext + dreamContext, // per-turn dynamic + prependContext: recallContext, // per-turn dynamic }; }); - // Session-keyed dream tracking. Only the session that triggered dream - // can complete it. Prevents cross-session false completion. - let dreamSessionId: string | undefined; - api.on("agent_end", async (event: any, ctx: any) => { const sessionId = ctx?.sessionKey ?? undefined; - const trigger = ctx?.trigger ?? undefined; if (sessionId) session.setCurrentSessionId(sessionId); - // If dream was triggered for THIS session, handle cleanup regardless - // of success/failure. A failed turn must still release the lock. - const stateDir = session.getStateDir(); - if (dreamSessionId && dreamSessionId === sessionId && stateDir) { - dreamSessionId = undefined; - - if (!event.success) { - // Turn failed/aborted after lock acquired. Release lock, do not - // record completion. Gates will re-trigger next eligible turn. - releaseDreamLock(stateDir); - api.logger.warn( - "openclaw-mem0: auto-dream turn failed, lock released, will retry", - ); - return; - } - - // Verify the model actually performed WRITE operations (not just reads). - // Only count memory_add, memory_update, memory_delete. - // Exclude memory_list and memory_search (read-only, orient-only pass). - // Scan only the LAST assistant message (this turn), not the full session - // snapshot, to avoid matching earlier tool calls from prior turns. - const WRITE_TOOLS = new Set([ - "memory_add", - "memory_update", - "memory_delete", - ]); - const messages = event.messages ?? []; - // Find the last assistant message (this turn's output) - const lastAssistant = [...messages] - .reverse() - .find((m: any) => m.role === "assistant"); - const writeToolUsed = - lastAssistant && Array.isArray(lastAssistant.content) - ? lastAssistant.content.some( - (block: any) => - block.type === "tool_use" && WRITE_TOOLS.has(block.name), - ) - : false; - - if (writeToolUsed) { - releaseDreamLock(stateDir); - recordDreamCompletion(stateDir); - _captureEvent("openclaw.hook.dream", { - phase: "completed", - write_tools_used: true, - }); - api.logger.info( - "openclaw-mem0: auto-dream completed (verified write tool usage), lock released", - ); - } else { - releaseDreamLock(stateDir); - api.logger.warn( - "openclaw-mem0: auto-dream injected but no write tools executed. Lock released, will retry.", - ); - } - return; - } - if (!event.success) return; - // Track session for dream gating (interactive turns only) - if ( - stateDir && - sessionId && - !isNonInteractiveTrigger(trigger, sessionId) - ) { - incrementSessionCount(stateDir, sessionId); - } - api.logger.info("openclaw-mem0: skills-mode agent_end (no auto-capture)"); }); @@ -733,6 +599,7 @@ function registerHooks( "", ) .trim(); + const safePrompt = lifecycle.prepareUserText(cleanPrompt); const recallStart = Date.now(); const recallWork = async () => { @@ -741,7 +608,7 @@ function registerHooks( // Search long-term memories (user-scoped; subagents read from parent namespace) let longTermResults = await provider.search( - cleanPrompt, + safePrompt, buildSearchOptions( undefined, recallTopK, @@ -767,7 +634,7 @@ function registerHooks( // Only broaden for genuinely new sessions with short prompts // (cold-start blindness). Skip on subsequent turns to save API calls. - if (isNewSession && cleanPrompt.length < 100) { + if (isNewSession && safePrompt.length < 100) { const broadOpts = buildSearchOptions( undefined, 5, @@ -1007,8 +874,9 @@ function registerHooks( content: m.content, })); - // Apply noise filtering pipeline: drop noise, strip fragments, truncate - const formattedMessages = filterMessagesForExtraction(selected); + // Filter noise and redact secrets without truncating message text. + const formattedMessages: Array<{ role: string; content: string }> = + lifecycle.prepareConversation(filterMessagesForExtraction(selected)); if (formattedMessages.length === 0) return; diff --git a/integrations/openclaw/openclaw-plugin-sdk.d.ts b/integrations/openclaw/openclaw-plugin-sdk.d.ts index 9854a5462..7eda91994 100644 --- a/integrations/openclaw/openclaw-plugin-sdk.d.ts +++ b/integrations/openclaw/openclaw-plugin-sdk.d.ts @@ -1,7 +1,7 @@ declare module "openclaw/plugin-sdk" { export interface MemoryArtifact { id: string; - type: "memory" | "dream" | "digest" | "entity"; + type: "memory" | "digest" | "entity"; title: string; content: string; metadata?: Record; diff --git a/integrations/openclaw/openclaw.plugin.json b/integrations/openclaw/openclaw.plugin.json index 34564bfe4..2d9f46518 100644 --- a/integrations/openclaw/openclaw.plugin.json +++ b/integrations/openclaw/openclaw.plugin.json @@ -2,7 +2,7 @@ "id": "openclaw-mem0", "name": "Memory (Mem0)", "description": "Mem0 memory backend for OpenClaw — platform (mem0.ai cloud) or self-hosted open-source. Auto-recall and auto-capture are opt-in (disabled by default). Supports OpenAI, Anthropic, Ollama (fully local), Qdrant, and PGVector providers.", - "version": "1.0.15", + "version": "1.1.0", "kind": "memory", "skills": ["skills"], "commandAliases": [ @@ -145,7 +145,7 @@ "skills": { "label": "Agentic Memory Skills", "advanced": true, - "help": "Enable skills-based memory extraction. The agent controls what to remember (triage), how to recall (recall), and periodic cleanup (dream). Disables auto-capture when active." + "help": "Enable skills-based memory extraction. The agent controls what to remember (triage) and how to recall (recall). Disables auto-capture when active." } }, "configSchema": { @@ -279,16 +279,6 @@ "categoryOrder": { "type": "array", "items": { "type": "string" } } } }, - "dream": { - "type": "object", - "properties": { - "enabled": { "type": "boolean" }, - "auto": { "type": "boolean" }, - "minHours": { "type": "number" }, - "minSessions": { "type": "number" }, - "minMemories": { "type": "number" } - } - }, "domain": { "type": "string" }, "customRules": { "type": "object", @@ -317,4 +307,4 @@ "hosts": ["us.i.posthog.com"] } ] -} \ No newline at end of file +} diff --git a/integrations/openclaw/package.json b/integrations/openclaw/package.json index ead4e38d0..6ea5a0aab 100644 --- a/integrations/openclaw/package.json +++ b/integrations/openclaw/package.json @@ -1,6 +1,6 @@ { "name": "@mem0/openclaw-mem0", - "version": "1.0.16", + "version": "1.1.0", "type": "module", "description": "Mem0 memory backend for OpenClaw — platform or self-hosted open-source", "license": "Apache-2.0", diff --git a/integrations/openclaw/public-artifacts.ts b/integrations/openclaw/public-artifacts.ts index a8ba105f5..cce6705ca 100644 --- a/integrations/openclaw/public-artifacts.ts +++ b/integrations/openclaw/public-artifacts.ts @@ -1,18 +1,15 @@ /** * Public Artifacts Provider for OpenClaw memory-wiki bridge mode. * - * Exposes Mem0 memories and dream state as artifacts that can be + * Exposes Mem0 memories as artifacts that can be * consumed by other plugins (e.g., memory-wiki in bridge mode). */ -import type { Mem0Provider, MemoryItem, Mem0Config } from "./types.ts"; +import type { Mem0Provider, MemoryItem } from "./types.ts"; import type { MemoryArtifact } from "openclaw/plugin-sdk"; -import { getDreamState } from "./dream-gate.ts"; export interface PublicArtifactsContext { provider: Mem0Provider; - cfg: Mem0Config; - stateDir?: string; effectiveUserId: (sessionKey?: string) => string; } @@ -28,7 +25,7 @@ export function createPublicArtifactsProvider(ctx: PublicArtifactsContext) { }): Promise { const artifacts: MemoryArtifact[] = []; const userId = options?.userId ?? ctx.effectiveUserId(); - const types = options?.types ?? ["memory", "dream", "entity"]; + const types = options?.types ?? ["memory", "entity"]; const limit = options?.limit ?? 100; try { @@ -44,14 +41,6 @@ export function createPublicArtifactsProvider(ctx: PublicArtifactsContext) { } } - // Dream state artifact (if dream enabled and stateDir available) - if (types.includes("dream") && ctx.stateDir && ctx.cfg.skills?.dream?.enabled) { - const dreamArtifact = getDreamArtifact(ctx.stateDir, userId); - if (dreamArtifact) { - artifacts.push(dreamArtifact); - } - } - // Entity artifacts (grouped memories by category) if (types.includes("entity")) { const entityArtifacts = extractEntityArtifacts(artifacts.filter(a => a.type === "memory")); @@ -90,39 +79,6 @@ function memoryToArtifact(mem: MemoryItem): MemoryArtifact { }; } -/** - * Get dream consolidation state as an artifact. - */ -function getDreamArtifact(stateDir: string, userId: string): MemoryArtifact | null { - try { - const state = getDreamState(stateDir); - if (state.lastConsolidatedAt === 0) { - return null; // No consolidation has occurred yet - } - - const lastDate = new Date(state.lastConsolidatedAt).toISOString(); - return { - id: `mem0:dream:${userId}:state`, - type: "dream", - title: `Dream State (last: ${lastDate.split("T")[0]})`, - content: [ - `Last consolidation: ${lastDate}`, - `Sessions since: ${state.sessionsSince}`, - `Last session: ${state.lastSessionId ?? "none"}`, - ].join("\n"), - metadata: { - lastConsolidatedAt: state.lastConsolidatedAt, - sessionsSince: state.sessionsSince, - lastSessionId: state.lastSessionId, - user_id: userId, - }, - updatedAt: lastDate, - }; - } catch { - return null; - } -} - /** * Extract entity artifacts from memories (grouped by category). */ diff --git a/integrations/openclaw/scripts/configure.py b/integrations/openclaw/scripts/configure.py index 26eaa673c..742a2c7b6 100755 --- a/integrations/openclaw/scripts/configure.py +++ b/integrations/openclaw/scripts/configure.py @@ -54,7 +54,6 @@ def main(): "keywordSearch": True, "identityAlwaysInclude": True, }, - "dream": {"enabled": True}, "domain": "companion", }, }, diff --git a/integrations/openclaw/skill-loader.ts b/integrations/openclaw/skill-loader.ts index 628c98e23..7e7fbce94 100644 --- a/integrations/openclaw/skill-loader.ts +++ b/integrations/openclaw/skill-loader.ts @@ -346,12 +346,12 @@ export function loadSkill( } // Inject triage knobs (importanceThreshold, credentialPatterns) - if (skillName === "memory-triage" || skillName === "memory-dream") { + if (skillName === "memory-triage") { const knobs = renderTriageKnobs(config); if (knobs) parts.push(knobs); } - // Append user custom rules (triage-only — extraction rules don't apply to recall/dream) + // Append user custom rules to the triage prompt. if (skillName === "memory-triage" && config.customRules) { const rulesBlock: string[] = ["\n## User Custom Rules\n"]; if (config.customRules.include?.length) { @@ -659,15 +659,6 @@ export function loadCompactTriagePrompt(config: SkillsConfig = {}): string { return parts.join("\n"); } -/** - * Load the dream skill prompt for consolidation sessions. - */ -export function loadDreamPrompt(config: SkillsConfig = {}): string { - const dream = loadSkill("memory-dream", config); - if (!dream) return ""; - return dream.prompt; -} - /** * Resolve the effective categories — user overrides merged with defaults. */ diff --git a/integrations/openclaw/skills/memory-dream/SKILL.md b/integrations/openclaw/skills/memory-dream/SKILL.md deleted file mode 100644 index e6ccf0032..000000000 --- a/integrations/openclaw/skills/memory-dream/SKILL.md +++ /dev/null @@ -1,150 +0,0 @@ ---- -name: memory-dream -description: > - Memory consolidation protocol. Reviews all stored memories, merges duplicates, - removes noise and credentials, rewrites unclear entries, and enforces TTL expiration. - Use when the user asks to clean up, consolidate, or review their memories. - Also triggers automatically after sufficient activity (configurable). -user-invocable: true -metadata: - {"openclaw": {"injected": true, "emoji": "💤", "requires": {"env": ["MEM0_API_KEY", "OPENAI_API_KEY", "ANTHROPIC_API_KEY"], "bins": []}}} ---- - -# Memory Consolidation - -You are performing a memory consolidation pass. Your goal is to review all stored memories for this user and improve their overall quality. Think of this as compressing raw observations into clean, durable knowledge. - -## Available Tools - -### memory_search -Semantic search across stored memories. -- `query` (required): search query -- `limit`: max results -- `userId`, `agentId`: scope overrides -- `scope`: `"all"` (default), `"session"`, or `"long-term"` -- `categories`: filter by category array - -### memory_add -Store new facts in long-term memory. -- `facts` (required): array of facts — ALL must share the same category -- `category`: `"identity"`, `"preference"`, `"decision"`, `"rule"`, `"project"`, `"configuration"`, `"technical"`, `"relationship"` -- `importance`: 0.0–1.0 - -### memory_get -Retrieve a single memory by ID. -- `memoryId` (required): the memory ID - -### memory_list -List all stored memories for a user or agent. -- `userId`, `agentId`: scope overrides -- `scope`: `"all"` (default), `"session"`, or `"long-term"` - -### memory_update -Update an existing memory's text in place. Atomic and preserves edit history. -- `memoryId` (required): the memory ID to update -- `text` (required): the new text (replaces old) - -### memory_delete -Delete memories by ID, query, or bulk. -- `memoryId`: specific memory ID to delete -- `all`: delete ALL memories (requires `confirm: true`) -- `userId`, `agentId`: scope overrides - -### memory_event_list -List recent background processing events (platform mode only). - -### memory_event_status -Get status of a specific background event. -- `event_id` (required): the event ID to check - -Follow these four phases in order. Do not skip phases. - -## Phase 1: Orient - -Survey the current memory landscape before making any changes. - -1. Call `memory_list` to load all stored memories. -2. Count memories by category. Note the total. -3. Identify the oldest and newest memories by their timestamps. -4. Note any obvious problems visible in the list: duplicates, very short entries, entries without temporal anchors. - -Do not modify anything in this phase. The goal is to understand what you are working with. - -## Phase 2: Gather Targets - -Identify which memories need action. Use the tools to investigate. - -**Search for recent additions:** -Call `memory_search` with a `created_at` filter to find memories added since the last consolidation. These are the most likely to need merging or cleanup. - -**Classify each target into one of these actions:** -- DELETE: contains credentials, expired by TTL, pure noise, raw tool output, standalone timestamps -- MERGE: two or more memories express the same fact in different words, or a series tracks incremental changes to the same entity -- REWRITE: vague, missing temporal anchor, uses first person instead of third, wrong category, overly verbose - -## Phase 3: Consolidate - -Execute the actions identified in Phase 2. Work in this priority order: - -### 3a. Delete dangerous and expired entries - -Delete immediately using `memory_delete`: -- Credentials, API keys, tokens, passwords, secrets (matching known credential prefixes and auth patterns injected by the plugin at runtime) -- Pure timestamps with no context -- Raw tool output stored as memory -- Heartbeat or cron execution records -- Generic acknowledgments stored as memory ("ok", "got it") -- Operational memories older than 7 days -- Project memories older than 90 days - -### 3b. Merge duplicates - -When two or more memories express the same fact: -1. Pick the most complete version as the base -2. Call `memory_update` on the best version to incorporate missing details from the others -3. Call `memory_delete` on the redundant entries - -`memory_update` is preferred over forget-then-store because it is atomic and preserves edit history. - -When merging, follow these rules: -- Keep the user's original words for opinions and preferences -- Preserve temporal anchors from both versions -- Do not exceed 50 words in the merged result -- The merged memory must be self-contained (understandable without the deleted ones) - -### 3c. Rewrite unclear entries - -When a memory needs improvement but is not a duplicate: -1. Call `memory_update` with the improved text - -Rewrite when: -- Memory uses first person ("I prefer") instead of third ("User prefers") -- Memory lacks a temporal anchor for time-sensitive information -- Memory is vague ("likes python") and can be made specific ("User prefers Python for backend development") -- Memory has the wrong category assignment -- Memory is over 50 words and can be compressed without losing information - -## Phase 4: Report - -After completing all operations, summarize what you did: - -``` -Consolidation complete. -- Reviewed: [total count] -- Deleted (credentials/secrets): [count] -- Deleted (expired/stale): [count] -- Merged: [count] groups into [count] memories -- Rewritten: [count] -- Final count: [total remaining] -- Issues found: [any notable problems or observations] -``` - -## Quality Targets - -After consolidation, the memory store should have: -- Zero memories containing credentials or secrets -- Zero duplicate memories (same fact in different words) -- All project and operational memories have temporal anchors ("As of YYYY-MM-DD") -- All memories use third person voice -- All memories are correctly categorized -- Each memory is 15-50 words, self-contained, and atomic (one fact per memory) diff --git a/integrations/openclaw/telemetry.ts b/integrations/openclaw/telemetry.ts index 3e2b4c7a4..fc1c6b99d 100644 --- a/integrations/openclaw/telemetry.ts +++ b/integrations/openclaw/telemetry.ts @@ -1,301 +1,115 @@ -/** - * Plugin telemetry — anonymous usage tracking via PostHog. - * - * Sends fire-and-forget events to PostHog using native fetch(). - * Events are batched and flushed every 5 seconds or when the queue - * reaches 10 events, whichever comes first. - * - * Disable with: MEM0_TELEMETRY=false - */ - import { createHash, randomUUID } from "node:crypto"; -import { readPluginAuth, writePluginAuth, getBaseUrl, clearAnonymousTelemetryId } from "./cli/config-file.ts"; + +import { createTelemetry } from "../agent-plugin-core/typescript/src/telemetry.ts"; +import { clearAnonymousTelemetryId, getBaseUrl, readPluginAuth, writePluginAuth } from "./cli/config-file.ts"; declare const __OPENCLAW_PLUGIN_VERSION__: string; export const PLUGIN_VERSION: string = __OPENCLAW_PLUGIN_VERSION__; -const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"; -const POSTHOG_HOST = "https://us.i.posthog.com/i/v0/e/"; +let cachedAnonymousId: string | undefined; +let aliasCheckDone = false; +let emailResolutionAttempted = false; +let currentDistinctId = ""; -const FLUSH_INTERVAL_MS = 5_000; -const FLUSH_THRESHOLD = 10; - -let eventQueue: Record[] = []; -let flushTimer: ReturnType | undefined; - -let _cachedAnonymousId: string | undefined; -let _aliasCheckDone = false; - -/** - * Return a persistent per-machine anonymous ID, generating one if needed. - * - * Stored in ~/.openclaw/openclaw.json under the plugin's `anonymousTelemetryId` - * field so repeat sessions on the same machine share one PostHog identity - * instead of collapsing into a single shared fallback string. The result is - * cached in module memory after the first read so we don't re-touch disk on - * every queued event. - */ -function getOrCreateAnonymousId(): string { - if (_cachedAnonymousId) return _cachedAnonymousId; - try { - const auth = readPluginAuth(); - if (auth.anonymousTelemetryId) { - _cachedAnonymousId = auth.anonymousTelemetryId; - return _cachedAnonymousId; - } - } catch { - /* ignore */ - } - const newId = `openclaw-anon-${randomUUID().replace(/-/g, "")}`; - try { - writePluginAuth({ anonymousTelemetryId: newId }); - } catch { - /* ignore — return generated id anyway */ - } - _cachedAnonymousId = newId; - return newId; +function enabled(): boolean { + const value = (globalThis as any).__mem0_telemetry_override ?? process.env.MEM0_TELEMETRY; + return value === undefined || !["false", "0", "no", "off"].includes(String(value).toLowerCase()); } -/** - * If we just resolved to a real identity but a stored anonymous id exists, - * build a one-shot PostHog $identify event so the pre-signup history gets - * stitched onto the authenticated profile. Returns null when no aliasing is - * needed (already done, or no anon id on disk, or still anonymous). - * - * Caller is responsible for pushing the returned event onto eventQueue ahead - * of the regular event. - */ -function maybeBuildIdentifyEvent( - distinctId: string, -): Record | null { - if (_aliasCheckDone) return null; - if (!distinctId || distinctId.startsWith("openclaw-anon-")) return null; +function anonymousId(): string { + if (cachedAnonymousId) return cachedAnonymousId; try { - const auth = readPluginAuth(); - const storedAnon = auth.anonymousTelemetryId; - if (!storedAnon) { - _aliasCheckDone = true; - return null; - } - const identifyEvent = { - event: "$identify", - distinct_id: distinctId, - properties: { - $anon_distinct_id: storedAnon, - $lib: "posthog-node", - }, - }; - // Clear the anonymous ID from config after aliasing (don't write empty string) - try { - clearAnonymousTelemetryId(); - } catch { - /* ignore — alias may double-fire next session, harmless */ - } - _aliasCheckDone = true; - _cachedAnonymousId = undefined; - return identifyEvent; + const stored = readPluginAuth().anonymousTelemetryId; + if (stored) return (cachedAnonymousId = stored); } catch { - return null; + // First run or unreadable config. + } + const created = `openclaw-anon-${randomUUID().replace(/-/g, "")}`; + try { + writePluginAuth({ anonymousTelemetryId: created }); + } catch { + // An unwritable config must not break the plugin. + } + return (cachedAnonymousId = created); +} + +function distinctId(apiKey?: string): string { + try { + const email = readPluginAuth().userEmail; + if (email) return createHash("sha256").update(email).digest("hex"); + } catch { + // Fall through to the API key or anonymous identity. + } + return apiKey ? createHash("sha256").update(apiKey).digest("hex") : anonymousId(); +} + +const telemetry = createTelemetry({ + host: "openclaw", + source: "OPENCLAW", + version: PLUGIN_VERSION, + distinctId: () => currentDistinctId, + enabled, +}); + +function identifyAnonymous(id: string): void { + if (aliasCheckDone || id.startsWith("openclaw-anon-")) return; + try { + const anonymous = readPluginAuth().anonymousTelemetryId; + aliasCheckDone = true; + if (!anonymous) return; + telemetry.capture("$identify", { $anon_distinct_id: anonymous }); + clearAnonymousTelemetryId(); + cachedAnonymousId = undefined; + } catch { + // Aliasing is best effort. } } -let _emailResolutionAttempted = false; - -/** - * If we have an apiKey but no cached userEmail, do a one-shot /v1/ping/ - * call to resolve the email and cache it. This runs async as a side-effect; - * the current event ships with md5(apiKey) but subsequent events (including - * those flushed by the beforeExit handler in the same process) will use - * the resolved email. - */ -function maybeResolveEmail(apiKey: string): void { - if (_emailResolutionAttempted) return; - _emailResolutionAttempted = true; - - const baseUrl = getBaseUrl().replace(/\/+$/, ""); - fetch(`${baseUrl}/v1/ping/`, { +function resolveEmail(apiKey: string): void { + if (emailResolutionAttempted) return; + emailResolutionAttempted = true; + fetch(`${getBaseUrl().replace(/\/+$/, "")}/v1/ping/`, { method: "GET", - headers: { - Authorization: `Token ${apiKey}`, - "Content-Type": "application/json", - }, + headers: { Authorization: `Token ${apiKey}`, "Content-Type": "application/json" }, signal: AbortSignal.timeout(5_000), }) - .then((res) => res.json()) + .then((response) => response.json()) .then((data: any) => { - const email = data?.user_email; - if (email) { - try { - writePluginAuth({ userEmail: email }); - } catch { - /* ignore */ - } - const oldId = createHash("sha256").update(apiKey).digest("hex"); - const newId = createHash("sha256").update(email).digest("hex"); - for (const ev of eventQueue) { - if (ev.distinct_id === oldId) { - ev.distinct_id = newId; - } - } + if (!data?.user_email) return; + writePluginAuth({ userEmail: data.user_email }); + const oldId = createHash("sha256").update(apiKey).digest("hex"); + const newId = createHash("sha256").update(data.user_email).digest("hex"); + for (const event of telemetry.queueForTesting()) { + if (event.distinct_id === oldId) event.distinct_id = newId; } }) .catch(() => { - /* silently swallow — md5(apiKey) is used as fallback */ + // The API-key hash remains a stable fallback. }); } -let _telemetryEnabled: boolean | undefined; -function isTelemetryEnabled(): boolean { - if (_telemetryEnabled !== undefined) return _telemetryEnabled; - try { - const val = (globalThis as any).__mem0_telemetry_override; - if (val !== undefined) { - const s = String(val).toLowerCase(); - _telemetryEnabled = s !== "false" && s !== "0" && s !== "no"; - } else { - _telemetryEnabled = true; - } - } catch { - _telemetryEnabled = true; - } - return _telemetryEnabled; -} - -/** - * Return a stable anonymous identifier for the current user. - * - * Priority: cached userEmail (from /v1/ping/) > MD5(apiKey) > - * persistent per-machine anonymous ID. - */ -function getDistinctId(apiKey?: string): string { - try { - const auth = readPluginAuth(); - if (auth.userEmail) { - return createHash("sha256").update(auth.userEmail).digest("hex"); - } - } catch { - /* ignore */ - } - if (apiKey) { - return createHash("sha256").update(apiKey).digest("hex"); - } - return getOrCreateAnonymousId(); -} - -function ensureFlushTimer(): void { - if (flushTimer) return; - flushTimer = setInterval(flushEvents, FLUSH_INTERVAL_MS); - if (typeof flushTimer === "object" && "unref" in flushTimer) { - flushTimer.unref(); - } -} - -let _exitHandlerInstalled = false; - -/** - * Install a one-time `beforeExit` handler that drains queued events on - * process exit. Without this, short-lived CLI invocations (e.g. one - * `openclaw mem0 status` call) exit before the unref'd flushTimer fires - * and before FLUSH_THRESHOLD is hit, dropping every queued event silently. - * - * Returning a Promise from a `beforeExit` handler keeps the event loop - * alive until that Promise resolves, so the awaited fetch actually has - * time to land at PostHog. - */ -function ensureExitHandler(): void { - if (_exitHandlerInstalled) return; - _exitHandlerInstalled = true; - process.on("beforeExit", async () => { - if (eventQueue.length === 0) return; - const batch = eventQueue; - eventQueue = []; - const body = JSON.stringify({ api_key: POSTHOG_API_KEY, batch }); - try { - await fetch(POSTHOG_HOST, { - method: "POST", - headers: { - "Content-Type": "application/json", - "Content-Length": String(Buffer.byteLength(body)), - }, - body, - signal: AbortSignal.timeout(3_000), - }); - } catch { - /* silently swallow */ - } - }); -} - -function flushEvents(): void { - if (eventQueue.length === 0) return; - const batch = eventQueue; - eventQueue = []; - - const body = JSON.stringify({ api_key: POSTHOG_API_KEY, batch }); - fetch(POSTHOG_HOST, { - method: "POST", - headers: { - "Content-Type": "application/json", - "Content-Length": String(Buffer.byteLength(body)), - }, - body, - signal: AbortSignal.timeout(3_000), - }).catch(() => { - /* silently swallow */ - }); -} - -/** - * Capture a PostHog event (non-blocking, never throws). - */ export function captureEvent( eventName: string, properties: Record = {}, - ctx?: { apiKey?: string; mode?: string; skillsActive?: boolean }, + context?: { apiKey?: string; mode?: string; skillsActive?: boolean }, ): void { - if (!isTelemetryEnabled()) return; - + if (!enabled()) return; try { - const distinctId = getDistinctId(ctx?.apiKey); - + currentDistinctId = distinctId(context?.apiKey); let hasEmail = false; - try { hasEmail = !!readPluginAuth().userEmail; } catch { /* ignore */ } - if (ctx?.apiKey && !hasEmail && !distinctId.startsWith("openclaw-anon-")) { - maybeResolveEmail(ctx.apiKey); + try { + hasEmail = Boolean(readPluginAuth().userEmail); + } catch { + // Resolve it below when possible. } - - // First authenticated event after a previous anonymous session: queue a - // $identify ahead of the regular event so PostHog merges the anonymous - // history onto the authenticated profile in the same batch flush. - const identifyEvent = maybeBuildIdentifyEvent(distinctId); - if (identifyEvent) { - eventQueue.push(identifyEvent); - } - - eventQueue.push({ - event: eventName, - distinct_id: distinctId, - properties: { - source: "OPENCLAW", - language: "node", - plugin_version: PLUGIN_VERSION, - node_version: process.version, - os: process.platform, - mode: ctx?.mode, - skills_active: ctx?.skillsActive, - $process_person_profile: false, - $lib: "posthog-node", - ...properties, - }, + if (context?.apiKey && !hasEmail) resolveEmail(context.apiKey); + identifyAnonymous(currentDistinctId); + telemetry.capture(eventName, { + mode: context?.mode, + skills_active: context?.skillsActive, + ...properties, }); - - ensureFlushTimer(); - ensureExitHandler(); - - if (eventQueue.length >= FLUSH_THRESHOLD) { - flushEvents(); - } } catch { - /* silently swallow */ + // Telemetry must never affect plugin behavior. } } diff --git a/integrations/openclaw/tests/cli-commands.test.ts b/integrations/openclaw/tests/cli-commands.test.ts index 77cd52f49..ed036e9c7 100644 --- a/integrations/openclaw/tests/cli-commands.test.ts +++ b/integrations/openclaw/tests/cli-commands.test.ts @@ -29,11 +29,6 @@ vi.mock("../fs-safe.ts", () => ({ unlink: vi.fn(), })); -vi.mock("../skill-loader.ts", () => ({ - loadDreamPrompt: vi.fn().mockReturnValue("dream prompt"), -})); - - // --------------------------------------------------------------------------- // Imports (after mocks) // --------------------------------------------------------------------------- @@ -46,7 +41,6 @@ import { enableSkillsConfig, getBaseUrl, } from "../cli/config-file.ts"; -import { loadDreamPrompt } from "../skill-loader.ts"; // --------------------------------------------------------------------------- // Mock Commander program builder @@ -263,8 +257,6 @@ describe("registerCliCommands", () => { (readPluginAuth as ReturnType).mockReturnValue({}); (writePluginAuth as ReturnType).mockImplementation(() => {}); (getBaseUrl as ReturnType).mockReturnValue("https://api.mem0.ai"); - (loadDreamPrompt as ReturnType).mockReturnValue("dream prompt"); - consoleSpy = { log: vi.spyOn(console, "log").mockImplementation(() => {}), error: vi.spyOn(console, "error").mockImplementation(() => {}), @@ -311,7 +303,6 @@ describe("registerCliCommands", () => { expect(names).toContain("delete"); expect(names).toContain("status"); expect(names).toContain("config"); - expect(names).toContain("dream"); }); it("registers config subcommands: show, get, set", () => { @@ -1037,6 +1028,19 @@ describe("registerCliCommands", () => { // ======================================================================== describe("status subcommand", () => { + it("reports setup instructions when Mem0 is not configured", async () => { + const { mem0, backend, cfg } = setup(); + (cfg as any).needsSetup = true; + const statusCmd = findCommand(mem0, "status")!; + + await statusCmd._action!(); + + expect(backend.status).not.toHaveBeenCalled(); + expect(consoleSpy.log).toHaveBeenCalledWith( + expect.stringContaining("openclaw mem0 init"), + ); + }); + it("calls backend.status and prints connection info", async () => { const { mem0, backend } = setup(); const statusCmd = findCommand(mem0, "status")!; @@ -1280,104 +1284,6 @@ describe("registerCliCommands", () => { }); }); - // ======================================================================== - // dream subcommand - // ======================================================================== - - describe("dream subcommand", () => { - it("fetches memories and outputs dream prompt to stdout", async () => { - const { mem0, provider } = setup(); - provider.getAll.mockResolvedValueOnce([ - { - id: "m1", - memory: "User is an engineer", - categories: ["identity"], - metadata: { category: "identity", importance: 0.9 }, - created_at: "2026-01-01", - }, - ]); - const stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true); - const dreamCmd = findCommand(mem0, "dream")!; - - await dreamCmd._action!({}); - - expect(provider.getAll).toHaveBeenCalledWith( - expect.objectContaining({ - user_id: "testuser", - source: "OPENCLAW", - }), - ); - expect(loadDreamPrompt).toHaveBeenCalled(); - - // stdout should contain the dream prompt - const stdoutOutput = stdoutSpy.mock.calls.map((c) => c[0]).join(""); - expect(stdoutOutput).toContain(""); - expect(stdoutOutput).toContain("dream prompt"); - expect(stdoutOutput).toContain(" { - const { mem0, provider } = setup(); - provider.getAll.mockResolvedValueOnce([ - { id: "m1", memory: "test", categories: [], metadata: {}, created_at: "2026-01-01" }, - ]); - const stdoutSpy = vi.spyOn(process.stdout, "write").mockImplementation(() => true); - const dreamCmd = findCommand(mem0, "dream")!; - - await dreamCmd._action!({ dryRun: true }); - - // Dry run should write inventory to stderr, NOT dream prompt to stdout - expect(stderrSpy).toHaveBeenCalledWith( - expect.stringContaining("Dry run"), - ); - expect(stdoutSpy).not.toHaveBeenCalled(); - - stdoutSpy.mockRestore(); - }); - - it("prints message when no memories to consolidate", async () => { - const { mem0, provider } = setup(); - provider.getAll.mockResolvedValueOnce([]); - const dreamCmd = findCommand(mem0, "dream")!; - - await dreamCmd._action!({}); - - expect(consoleSpy.log).toHaveBeenCalledWith( - "No memories to consolidate.", - ); - }); - - it("prints error when dream skill file is not found", async () => { - const { mem0, provider } = setup(); - provider.getAll.mockResolvedValueOnce([ - { id: "m1", memory: "test", categories: [], metadata: {}, created_at: "2026-01-01" }, - ]); - (loadDreamPrompt as ReturnType).mockReturnValueOnce(""); - const dreamCmd = findCommand(mem0, "dream")!; - - await dreamCmd._action!({}); - - expect(stderrSpy).toHaveBeenCalledWith( - expect.stringContaining("Dream skill file not found"), - ); - }); - - it("handles dream errors gracefully", async () => { - const { mem0, provider } = setup(); - provider.getAll.mockRejectedValueOnce(new Error("dream boom")); - const dreamCmd = findCommand(mem0, "dream")!; - - await dreamCmd._action!({}); - - expect(consoleSpy.error).toHaveBeenCalledWith( - expect.stringContaining("Dream failed"), - ); - }); - }); - // ======================================================================== // import subcommand // ======================================================================== @@ -1647,7 +1553,7 @@ describe("registerCliCommands", () => { // ======================================================================== describe("--json flag registration", () => { - for (const name of ["search", "add", "get", "list", "update", "delete", "status", "import", "dream"]) { + for (const name of ["search", "add", "get", "list", "update", "delete", "status", "import"]) { it(`registers --json on ${name}`, () => { const { mem0 } = setup(); const cmd = findCommand(mem0, name)!; diff --git a/integrations/openclaw/tests/config.test.ts b/integrations/openclaw/tests/config.test.ts index 6eb7441ac..2c6dbac2e 100644 --- a/integrations/openclaw/tests/config.test.ts +++ b/integrations/openclaw/tests/config.test.ts @@ -1,6 +1,8 @@ /** * Tests for config.ts — mem0ConfigSchema.parse() and exported constants. */ +import { readFileSync } from "node:fs"; + import { describe, it, expect } from "vitest"; import { mem0ConfigSchema, @@ -8,6 +10,14 @@ import { DEFAULT_CUSTOM_CATEGORIES, } from "../config.ts"; +describe("plugin manifest", () => { + it("matches the package version", () => { + const packageJson = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")); + const manifest = JSON.parse(readFileSync(new URL("../openclaw.plugin.json", import.meta.url), "utf8")); + expect(manifest.version).toBe(packageJson.version); + }); +}); + // --------------------------------------------------------------------------- // Exported constants // --------------------------------------------------------------------------- @@ -379,13 +389,6 @@ describe("mem0ConfigSchema.parse() — skills config", () => { tokenBudget: 2000, maxMemories: 10, }, - dream: { - enabled: true, - auto: true, - minHours: 12, - minSessions: 3, - minMemories: 15, - }, domain: "engineering", customRules: { include: ["tool configs"], diff --git a/integrations/openclaw/tests/dream-gate.test.ts b/integrations/openclaw/tests/dream-gate.test.ts deleted file mode 100644 index cf8dc26db..000000000 --- a/integrations/openclaw/tests/dream-gate.test.ts +++ /dev/null @@ -1,376 +0,0 @@ -/** - * Tests for dream-gate.ts — activity tracking, gate logic, and lock mechanism - * for automatic memory consolidation. - * - * All filesystem operations are mocked via fs-safe.ts. - * Time-dependent tests use vi.useFakeTimers(). - */ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; - -vi.mock("../fs-safe.ts", () => ({ - readText: vi.fn(), - writeText: vi.fn(), - mkdirp: vi.fn(), - unlink: vi.fn(), -})); - -import { readText, writeText, mkdirp, unlink } from "../fs-safe.ts"; -import { - incrementSessionCount, - checkCheapGates, - checkMemoryGate, - acquireDreamLock, - releaseDreamLock, - recordDreamCompletion, - getDreamState, -} from "../dream-gate.ts"; - -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - -const mockReadText = readText as ReturnType; -const mockWriteText = writeText as ReturnType; -const mockMkdirp = mkdirp as ReturnType; -const mockUnlink = unlink as ReturnType; - -const STATE_DIR = "/tmp/test-state"; - -interface DreamState { - lastConsolidatedAt: number; - sessionsSince: number; - lastSessionId: string | null; -} - -function setDreamState(state: DreamState): void { - mockReadText.mockImplementation((filePath: string) => { - if (filePath.endsWith("dream-state.json")) { - return JSON.stringify(state); - } - throw new Error("ENOENT"); - }); -} - -function setNoState(): void { - mockReadText.mockImplementation(() => { - throw new Error("ENOENT"); - }); -} - -function getWrittenState(): DreamState { - const call = mockWriteText.mock.calls.find((c: unknown[]) => - (c[0] as string).endsWith("dream-state.json"), - ); - if (!call) throw new Error("No state file written"); - return JSON.parse(call[1] as string); -} - -beforeEach(() => { - vi.resetAllMocks(); - mockMkdirp.mockReturnValue(undefined); - mockUnlink.mockReturnValue(undefined); -}); - -// --------------------------------------------------------------------------- -// incrementSessionCount -// --------------------------------------------------------------------------- - -describe("incrementSessionCount", () => { - it("increments counter for a new session", () => { - setDreamState({ - lastConsolidatedAt: 0, - sessionsSince: 3, - lastSessionId: "session-old", - }); - - incrementSessionCount(STATE_DIR, "session-new"); - - const written = getWrittenState(); - expect(written.sessionsSince).toBe(4); - expect(written.lastSessionId).toBe("session-new"); - }); - - it("deduplicates same session (no increment)", () => { - setDreamState({ - lastConsolidatedAt: 0, - sessionsSince: 3, - lastSessionId: "session-same", - }); - - incrementSessionCount(STATE_DIR, "session-same"); - - // writeText should NOT have been called for the state file - const stateWrites = mockWriteText.mock.calls.filter((c: unknown[]) => - (c[0] as string).endsWith("dream-state.json"), - ); - expect(stateWrites).toHaveLength(0); - }); -}); - -// --------------------------------------------------------------------------- -// checkCheapGates -// --------------------------------------------------------------------------- - -describe("checkCheapGates", () => { - beforeEach(() => { - vi.useFakeTimers(); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - it("fails time gate when consolidation was too recent", () => { - const now = Date.now(); - vi.setSystemTime(now); - - // Last consolidated 1 hour ago, but minHours is 24 - setDreamState({ - lastConsolidatedAt: now - 1 * 3_600_000, - sessionsSince: 100, - lastSessionId: null, - }); - - const result = checkCheapGates(STATE_DIR, { minHours: 24, minSessions: 5 }); - expect(result.proceed).toBe(false); - expect(result.reason).toContain("time"); - }); - - it("fails session gate when too few sessions", () => { - const now = Date.now(); - vi.setSystemTime(now); - - // Last consolidated 48 hours ago (passes time gate), but only 2 sessions - setDreamState({ - lastConsolidatedAt: now - 48 * 3_600_000, - sessionsSince: 2, - lastSessionId: null, - }); - - const result = checkCheapGates(STATE_DIR, { - minHours: 24, - minSessions: 5, - }); - expect(result.proceed).toBe(false); - expect(result.reason).toContain("sessions"); - }); - - it("passes both gates when conditions are met", () => { - const now = Date.now(); - vi.setSystemTime(now); - - // 48 hours ago, 10 sessions — both gates pass - setDreamState({ - lastConsolidatedAt: now - 48 * 3_600_000, - sessionsSince: 10, - lastSessionId: null, - }); - - const result = checkCheapGates(STATE_DIR, { - minHours: 24, - minSessions: 5, - }); - expect(result.proceed).toBe(true); - expect(result.reason).toBeUndefined(); - }); - - it("uses defaults when config is empty", () => { - const now = Date.now(); - vi.setSystemTime(now); - - // Never consolidated (0), 100 sessions — should pass with defaults (24h, 5 sessions) - setDreamState({ - lastConsolidatedAt: 0, - sessionsSince: 100, - lastSessionId: null, - }); - - const result = checkCheapGates(STATE_DIR, {}); - expect(result.proceed).toBe(true); - }); -}); - -// --------------------------------------------------------------------------- -// checkMemoryGate -// --------------------------------------------------------------------------- - -describe("checkMemoryGate", () => { - it("fails when too few memories", () => { - const result = checkMemoryGate(5, { minMemories: 20 }); - expect(result.pass).toBe(false); - expect(result.reason).toContain("memories"); - expect(result.reason).toContain("5"); - }); - - it("passes when enough memories", () => { - const result = checkMemoryGate(25, { minMemories: 20 }); - expect(result.pass).toBe(true); - expect(result.reason).toBeUndefined(); - }); -}); - -// --------------------------------------------------------------------------- -// acquireDreamLock -// --------------------------------------------------------------------------- - -describe("acquireDreamLock", () => { - beforeEach(() => { - vi.useFakeTimers(); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - it("succeeds when no lock exists", () => { - const now = Date.now(); - vi.setSystemTime(now); - - // readText throws for lock file (not found), writeText succeeds for wx create - mockReadText.mockImplementation(() => { - throw new Error("ENOENT"); - }); - mockWriteText.mockReturnValue(undefined); - - const result = acquireDreamLock(STATE_DIR); - expect(result).toBe(true); - - // Verify it wrote a lock file with wx flag - const lockWrite = mockWriteText.mock.calls.find((c: unknown[]) => - (c[0] as string).endsWith("dream.lock"), - ); - expect(lockWrite).toBeDefined(); - const lockData = JSON.parse(lockWrite![1] as string); - expect(lockData.pid).toBe(process.pid); - expect(lockData.startedAt).toBe(now); - expect(lockWrite![2]).toEqual({ flag: "wx" }); - }); - - it("fails when lock exists and is fresh", () => { - const now = Date.now(); - vi.setSystemTime(now); - - // Lock was created 10 minutes ago — still fresh (< 1 hour) - mockReadText.mockImplementation((filePath: string) => { - if (filePath.endsWith("dream.lock")) { - return JSON.stringify({ - pid: 12345, - startedAt: now - 10 * 60 * 1000, - }); - } - throw new Error("ENOENT"); - }); - - const result = acquireDreamLock(STATE_DIR); - expect(result).toBe(false); - - // Should NOT have written a new lock - const lockWrites = mockWriteText.mock.calls.filter((c: unknown[]) => - (c[0] as string).endsWith("dream.lock"), - ); - expect(lockWrites).toHaveLength(0); - }); - - it("succeeds when lock is stale (>1hr old)", () => { - const now = Date.now(); - vi.setSystemTime(now); - - // Lock was created 2 hours ago — stale - mockReadText.mockImplementation((filePath: string) => { - if (filePath.endsWith("dream.lock")) { - return JSON.stringify({ - pid: 99999, - startedAt: now - 2 * 60 * 60 * 1000, - }); - } - throw new Error("ENOENT"); - }); - mockWriteText.mockReturnValue(undefined); - - const result = acquireDreamLock(STATE_DIR); - expect(result).toBe(true); - - // Should have unlinked the stale lock - expect(mockUnlink).toHaveBeenCalled(); - - // Should have written a new lock - const lockWrite = mockWriteText.mock.calls.find((c: unknown[]) => - (c[0] as string).endsWith("dream.lock"), - ); - expect(lockWrite).toBeDefined(); - }); -}); - -// --------------------------------------------------------------------------- -// releaseDreamLock -// --------------------------------------------------------------------------- - -describe("releaseDreamLock", () => { - it("removes lock file", () => { - releaseDreamLock(STATE_DIR); - expect(mockUnlink).toHaveBeenCalledWith( - expect.stringContaining("dream.lock"), - ); - }); -}); - -// --------------------------------------------------------------------------- -// recordDreamCompletion -// --------------------------------------------------------------------------- - -describe("recordDreamCompletion", () => { - beforeEach(() => { - vi.useFakeTimers(); - }); - - afterEach(() => { - vi.useRealTimers(); - }); - - it("resets session counter and records timestamp", () => { - const now = 1700000000000; - vi.setSystemTime(now); - - setDreamState({ - lastConsolidatedAt: 0, - sessionsSince: 15, - lastSessionId: "session-xyz", - }); - - recordDreamCompletion(STATE_DIR); - - const written = getWrittenState(); - expect(written.lastConsolidatedAt).toBe(now); - expect(written.sessionsSince).toBe(0); - expect(written.lastSessionId).toBeNull(); - }); -}); - -// --------------------------------------------------------------------------- -// getDreamState -// --------------------------------------------------------------------------- - -describe("getDreamState", () => { - it("returns default state when no file exists", () => { - setNoState(); - - const state = getDreamState(STATE_DIR); - expect(state).toEqual({ - lastConsolidatedAt: 0, - sessionsSince: 0, - lastSessionId: null, - }); - }); - - it("returns persisted state when file exists", () => { - const persisted = { - lastConsolidatedAt: 1700000000000, - sessionsSince: 7, - lastSessionId: "session-abc", - }; - setDreamState(persisted); - - const state = getDreamState(STATE_DIR); - expect(state).toEqual(persisted); - }); -}); diff --git a/integrations/openclaw/tsconfig.json b/integrations/openclaw/tsconfig.json index 2292f3295..1968e88d2 100644 --- a/integrations/openclaw/tsconfig.json +++ b/integrations/openclaw/tsconfig.json @@ -7,7 +7,7 @@ "declarationMap": true, "sourceMap": true, "outDir": "dist", - "rootDir": ".", + "rootDir": "..", "strict": false, "noImplicitAny": false, "types": ["node"], @@ -19,6 +19,6 @@ "allowImportingTsExtensions": true, "noEmit": true }, - "include": ["index.ts", "types.ts", "providers.ts", "config.ts", "filtering.ts", "isolation.ts", "openclaw-plugin-sdk.d.ts", "backend/**/*.ts", "tools/**/*.ts", "cli/**/*.ts", "skill-loader.ts", "recall.ts", "dream-gate.ts", "telemetry.ts", "fs-safe.ts"], + "include": ["index.ts", "types.ts", "providers.ts", "config.ts", "filtering.ts", "isolation.ts", "openclaw-plugin-sdk.d.ts", "backend/**/*.ts", "tools/**/*.ts", "cli/**/*.ts", "skill-loader.ts", "recall.ts", "telemetry.ts", "fs-safe.ts"], "exclude": ["node_modules", "dist", "**/*.test.ts"] } diff --git a/integrations/openclaw/types.ts b/integrations/openclaw/types.ts index 29d552396..caebf3fef 100644 --- a/integrations/openclaw/types.ts +++ b/integrations/openclaw/types.ts @@ -87,17 +87,6 @@ export interface SkillsConfig { identityAlwaysInclude?: boolean; categoryOrder?: string[]; }; - dream?: { - enabled?: boolean; - /** Enable automatic triggering based on activity gates. Default: true when dream enabled. */ - auto?: boolean; - /** Minimum hours between consolidations. Default: 24. */ - minHours?: number; - /** Minimum interactive sessions before triggering. Default: 5. */ - minSessions?: number; - /** Minimum total memories to justify consolidation. Default: 20. */ - minMemories?: number; - }; domain?: string; customRules?: { include?: string[]; diff --git a/integrations/mem0-plugin/.opencode-plugin/LICENSE b/integrations/opencode-plugin/LICENSE similarity index 100% rename from integrations/mem0-plugin/.opencode-plugin/LICENSE rename to integrations/opencode-plugin/LICENSE diff --git a/integrations/mem0-plugin/.opencode-plugin/README.md b/integrations/opencode-plugin/README.md similarity index 88% rename from integrations/mem0-plugin/.opencode-plugin/README.md rename to integrations/opencode-plugin/README.md index b4ba842a7..7199af3f3 100644 --- a/integrations/mem0-plugin/.opencode-plugin/README.md +++ b/integrations/opencode-plugin/README.md @@ -13,7 +13,7 @@ This adds the plugin to your `~/.config/opencode/opencode.json`. The plugin regi **Or let your agent do it** — paste this into OpenCode: ``` -Install @mem0/opencode-plugin by following https://raw.githubusercontent.com/mem0ai/mem0/main/integrations/mem0-plugin/.opencode-plugin/README.md +Install @mem0/opencode-plugin by following https://raw.githubusercontent.com/mem0ai/mem0/main/integrations/opencode-plugin/README.md ``` Get your API key (free): [app.mem0.ai/dashboard/api-keys](https://app.mem0.ai/dashboard/api-keys) @@ -30,7 +30,7 @@ Restart OpenCode. |-----------|-------------| | **9 Native Memory Tools** | `add_memory`, `search_memories`, `get_memories`, `update_memory`, `delete_memory`, and more — registered as OpenCode tools, backed by the `mem0ai` SDK (no MCP server required) | | **Lifecycle Hooks** | Auto-search on session start and every prompt, error memory lookup, compaction context, secret redaction | -| **9 Skills** | `/mem0-remember`, `/mem0-tour`, `/mem0-search`, `/mem0-status`, `/mem0-scope`, `/mem0-dream`, `/mem0-forget`, `/mem0-pin`, `/mem0-context-loader` — discovered in place from the plugin via OpenCode's `skills.paths` | +| **7 Skills** | `/mem0-remember`, `/mem0-tour`, `/mem0-search`, `/mem0-status`, `/mem0-scope`, `/mem0-forget`, `/mem0-context-loader` — discovered in place from the plugin via OpenCode's `skills.paths` | ## Hooks @@ -59,6 +59,7 @@ Pure TypeScript — no Python, no shell scripts. Memory operations are native Op | `delete_all_memories` | Bulk delete all memories in scope | | `delete_entities` | Delete an entity and its memories | | `list_entities` | List users/agents/apps stored in Mem0 | +| `get_event_status` | Check the processing status of an asynchronous memory event | ## Memory scope @@ -69,7 +70,7 @@ scope (used when none is passed) with the `/mem0-scope` skill: |-------|-------|--------| | `project` (default) | this repo (`user_id` + `app_id`) | this repo | | `session` | this run (adds `run_id`) | this run | -| `global` | all your projects (`app_id="*"`) | user-wide (drops `app_id`) | +| `global` | all your projects (filtered by your user ID) | user-wide (drops `app_id`) | ``` /mem0-scope # show the current default scope @@ -99,3 +100,5 @@ If the `mem0` tools respond, you're all set. ## License Apache-2.0 + +A memory tool cannot select global scope unless `/mem0-scope global` or the plugin settings already enable it. diff --git a/integrations/mem0-plugin/.opencode-plugin/api-key.test.ts b/integrations/opencode-plugin/api-key.test.ts similarity index 100% rename from integrations/mem0-plugin/.opencode-plugin/api-key.test.ts rename to integrations/opencode-plugin/api-key.test.ts diff --git a/integrations/mem0-plugin/.opencode-plugin/api-key.ts b/integrations/opencode-plugin/api-key.ts similarity index 100% rename from integrations/mem0-plugin/.opencode-plugin/api-key.ts rename to integrations/opencode-plugin/api-key.ts diff --git a/integrations/mem0-plugin/.opencode-plugin/bun.lock b/integrations/opencode-plugin/bun.lock similarity index 94% rename from integrations/mem0-plugin/.opencode-plugin/bun.lock rename to integrations/opencode-plugin/bun.lock index 9da6adb40..744a408ca 100644 --- a/integrations/mem0-plugin/.opencode-plugin/bun.lock +++ b/integrations/opencode-plugin/bun.lock @@ -12,9 +12,6 @@ "bun-types": ">=1.3.14", "typescript": "^5.7.3", }, - "peerDependencies": { - "bun": ">=1.0.0", - }, }, }, "packages": { @@ -88,38 +85,6 @@ "@opencode-ai/sdk": ["@opencode-ai/sdk@1.15.11", "", { "dependencies": { "cross-spawn": "7.0.6" } }, "sha512-IyYyDVsO8SKbKbkSadHpDuYnYC+2vmEeLU+rW+rH2M54Sigq6l3gDHno16+U6SRut+lowbph7v/ry3WbV67V3w=="], - "@oven/bun-darwin-aarch64": ["@oven/bun-darwin-aarch64@1.3.14", "", { "os": "darwin", "cpu": "arm64" }, "sha512-Omj20SuiHBOUjUBIyqtkNjSUIjOtEOJwmbix/ZyFH4BaQ6OZTaaRWIR4TjHVz0yadHgli6lLTiAh1uarnvD49A=="], - - "@oven/bun-darwin-x64": ["@oven/bun-darwin-x64@1.3.14", "", { "os": "darwin", "cpu": "x64" }, "sha512-FFj3QdU/OhlDyZOJ8CWfN5eWLpRlT4qjZg7lMQi7jA6GuoY5ajlO1zWLP/MuHYRSbXQUvV52RejNi8DVnAp13w=="], - - "@oven/bun-darwin-x64-baseline": ["@oven/bun-darwin-x64-baseline@1.3.14", "", { "os": "darwin", "cpu": "x64" }, "sha512-OSfsTZstc898HHElhU4NccaBGOSSDn5VfahiVTnidZ9B/+wb7WTyfZJaBeJcfjwJ9H2W9uTh2TGtl3UfcXgV9g=="], - - "@oven/bun-freebsd-aarch64": ["@oven/bun-freebsd-aarch64@1.3.14", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-LIKrXaFxAHybVO5Pf+9XP2FHUj/5APvXTUKk9dqHm5iFz4oH+W24cmhjkJirNujh9hKeTyrpWSe3no9JZKowIw=="], - - "@oven/bun-freebsd-x64": ["@oven/bun-freebsd-x64@1.3.14", "", { "os": "freebsd", "cpu": "x64" }, "sha512-uwD+fGUH1ADpIF3B1U2jWzzb20QwRLZfj5QZ28GUCGrAJ/nTmWrD6YYGsblCY1wuhldRez3lU40AyuvSCyLYmw=="], - - "@oven/bun-linux-aarch64": ["@oven/bun-linux-aarch64@1.3.14", "", { "os": "linux", "cpu": "arm64" }, "sha512-X5SsPZHs+iYO8R/efIcRtc7gT2Q2DgPfliCxEkx4cXBumwkw0c/EsHMNwH3EgGpCDaZ7IYVPhpCG/xBOQHEwZw=="], - - "@oven/bun-linux-aarch64-android": ["@oven/bun-linux-aarch64-android@1.3.14", "", { "os": "android", "cpu": "arm64" }, "sha512-y4kq5b85lsrmFb9Xvi4w9mA5IEFJkLMrSmYn06q24KjL9rUWDWO3VFZEtteZxUN5+ec3Zm5S8OnJw1umaCbVjA=="], - - "@oven/bun-linux-aarch64-musl": ["@oven/bun-linux-aarch64-musl@1.3.14", "", { "os": "linux", "cpu": "arm64" }, "sha512-jmqOA92Cd1NL/1XBd4bFkJLxQ86K0RW7ohxS2qzzAvuitO4JiIxjjTeCspoU44zCozH72HpfZfUE2On31OjnWA=="], - - "@oven/bun-linux-x64": ["@oven/bun-linux-x64@1.3.14", "", { "os": "linux", "cpu": "x64" }, "sha512-7OVTAKvwfPmSbIV1HpdOoVVx5VRc427GuPPne93N6vk4eQBPId9nXmZDh9/zGaKPdbVjVtQSZafWQoUjx38Utw=="], - - "@oven/bun-linux-x64-android": ["@oven/bun-linux-x64-android@1.3.14", "", { "os": "android", "cpu": "x64" }, "sha512-qe9e1d+3VAEU7nAA2ol9Jvmy/o99PVMSgZhHn7Q/9O3YcDrfEqyQ8zm4zoe5qTEo8HZH0dN03Le0Ys2eQPs7eg=="], - - "@oven/bun-linux-x64-baseline": ["@oven/bun-linux-x64-baseline@1.3.14", "", { "os": "linux", "cpu": "x64" }, "sha512-q/8EdOC0yUE8FPeoOVq8/Pw5I9/tJaYmUfO/uDUAREx8IUnOJH1RJ5A3BjFqre8pvJoiZA9AovPJq5FnNNjSxA=="], - - "@oven/bun-linux-x64-musl": ["@oven/bun-linux-x64-musl@1.3.14", "", { "os": "linux", "cpu": "x64" }, "sha512-GBCB/k/sIqcr06eTNgg7g46qiUv35Jasx4XiccJ/n7RGqrE4RWUD/XJBbWFprVPjvqd59+QtSnS99XGqvftHfg=="], - - "@oven/bun-linux-x64-musl-baseline": ["@oven/bun-linux-x64-musl-baseline@1.3.14", "", { "os": "linux", "cpu": "x64" }, "sha512-n6iE71G4lQE4XkrZhQQcL5YUlxDbnq6nqV7zeQi33PMsLT/0kYE+RvHOtBWZ3w0wMdXZfINmp63hIb9ijUBGtw=="], - - "@oven/bun-windows-aarch64": ["@oven/bun-windows-aarch64@1.3.14", "", { "os": "win32", "cpu": "arm64" }, "sha512-T7s3x/BsVKQObGU6QDkZeI6wKynzqGbBH1yI77jrrj5siElclxr3DQrDIk8CV4G5/SJq2HHq4kpLyYY2DKCSmA=="], - - "@oven/bun-windows-x64": ["@oven/bun-windows-x64@1.3.14", "", { "os": "win32", "cpu": "x64" }, "sha512-mUFWL3BoYkNpjd8e9PqROiFF/1Xeotq20mABJsiQH62jM1g5zqWh4khw1RZ6bX8Q8fWvlPaxG1PjofkmjUi3vg=="], - - "@oven/bun-windows-x64-baseline": ["@oven/bun-windows-x64-baseline@1.3.14", "", { "os": "win32", "cpu": "x64" }, "sha512-uIjLUC1S9DWgICzuoMba7vurBJnBruE4S5CxnvmZkdqWVXRzx1Rgu636HoH+k0qeaQCFh3jeG3JQ1y6fRHv0sw=="], - "@protobufjs/aspromise": ["@protobufjs/aspromise@1.1.2", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="], "@protobufjs/base64": ["@protobufjs/base64@1.1.2", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="], @@ -244,8 +209,6 @@ "buffer-writer": ["buffer-writer@2.0.0", "", {}, "sha512-a7ZpuTZU1TRtnwyCNW3I5dc0wWNC3VR9S++Ewyk2HHZdrO3CQJqSpd+95Us590V6AL7JqUAH2IwZ/398PmNFgw=="], - "bun": ["bun@1.3.14", "", { "optionalDependencies": { "@oven/bun-darwin-aarch64": "1.3.14", "@oven/bun-darwin-x64": "1.3.14", "@oven/bun-darwin-x64-baseline": "1.3.14", "@oven/bun-freebsd-aarch64": "1.3.14", "@oven/bun-freebsd-x64": "1.3.14", "@oven/bun-linux-aarch64": "1.3.14", "@oven/bun-linux-aarch64-android": "1.3.14", "@oven/bun-linux-aarch64-musl": "1.3.14", "@oven/bun-linux-x64": "1.3.14", "@oven/bun-linux-x64-android": "1.3.14", "@oven/bun-linux-x64-baseline": "1.3.14", "@oven/bun-linux-x64-musl": "1.3.14", "@oven/bun-linux-x64-musl-baseline": "1.3.14", "@oven/bun-windows-aarch64": "1.3.14", "@oven/bun-windows-x64": "1.3.14", "@oven/bun-windows-x64-baseline": "1.3.14" }, "os": [ "!aix", "!sunos", "!openbsd", ], "cpu": [ "x64", "arm64", ], "bin": { "bun": "bin/bun.exe", "bunx": "bin/bunx.exe" } }, "sha512-aB6GVd42x1Y5ie1K16SF+oLGtgSkwX9hgoDdIW88pjvfTccU8F1vfpoOt34QLv0dZ1v3XimtaxPlZUG81Gx9Zg=="], - "bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="], "bundle-name": ["bundle-name@4.1.0", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="], diff --git a/integrations/opencode-plugin/index.d.ts b/integrations/opencode-plugin/index.d.ts new file mode 100644 index 000000000..607d13c2d --- /dev/null +++ b/integrations/opencode-plugin/index.d.ts @@ -0,0 +1,4 @@ +import type { Plugin } from "@opencode-ai/plugin"; + +declare const Mem0Plugin: Plugin; +export default Mem0Plugin; diff --git a/integrations/mem0-plugin/.opencode-plugin/opencode-mem0.ts b/integrations/opencode-plugin/opencode-mem0.ts similarity index 92% rename from integrations/mem0-plugin/.opencode-plugin/opencode-mem0.ts rename to integrations/opencode-plugin/opencode-mem0.ts index d5f2acb30..8dcf6d535 100644 --- a/integrations/mem0-plugin/.opencode-plugin/opencode-mem0.ts +++ b/integrations/opencode-plugin/opencode-mem0.ts @@ -1,3 +1,4 @@ +import { resolveToolScope } from "../agent-plugin-core/typescript/src/scoping.ts"; // Mem0 memory plugin for OpenCode: captures and recalls memories across sessions // (add / search / manage) via the Mem0 platform, wired through OpenCode plugin hooks. // Memory operations are exposed as native OpenCode tools backed by the mem0ai SDK @@ -13,19 +14,10 @@ import {homedir} from "os"; import {join} from "path"; import {createHash} from "crypto"; import {captureEvent} from "./telemetry"; -import { - loadDreamConfig, - incrementSessionCount, - checkCheapGates, - checkMemoryGate, - acquireDreamLock, - releaseDreamLock, - recordDreamCompletion, - DREAM_PROTOCOL, -} from "./dream"; import {asScope, scopeSearchFilters, scopeWriteParams, resolveDefaultScope, SCOPE_GUIDANCE, type Scope} from "./scope"; import {parseProjectFromRemote} from "./project"; import {resolveApiKey} from "./api-key"; +import {createMemoryLifecycle} from "../agent-plugin-core/typescript/src/lifecycle.ts"; async function getUserId(): Promise { if (process.env.MEM0_USER_ID) return process.env.MEM0_USER_ID; @@ -78,23 +70,6 @@ function generateSessionId(): string { return `ses_${ts}_${rnd}`; } -const SECRET_PATTERNS = [ - /sk-[A-Za-z0-9]{20,}/g, - /m0-[A-Za-z0-9]{20,}/g, - /AKIA[0-9A-Z]{16}/g, - /xox[baprs]-[A-Za-z0-9-]{20,}/g, - /ghp_[A-Za-z0-9]{36,}/g, - /gho_[A-Za-z0-9]{36,}/g, -]; - -function redact(text: string): string { - let out = text; - for (const re of SECRET_PATTERNS) { - out = out.replace(re, "[REDACTED]"); - } - return out; -} - /** Read & parse `~/.mem0/settings.json`, returning {} when missing/invalid. */ function loadSettings(): Record { try { @@ -259,7 +234,7 @@ function extractUserText(input: any, output: any): string { const Mem0Plugin: Plugin = async (ctx) => { const {$, client} = ctx; - const apiKey = resolveApiKey(); + const apiKey = resolveApiKey(process.env, process.env.HOME || process.env.USERPROFILE || homedir()); if (!apiKey) { try { @@ -283,6 +258,8 @@ const Mem0Plugin: Plugin = async (ctx) => { const stats = {adds: 0, searches: 0, messages: 0}; const sessionId = generateSessionId(); const globalSearch = loadGlobalSearch(); + const lifecycle = createMemoryLifecycle(); + lifecycle.beginSession(); let initialized = false; let memoryCount = 0; @@ -290,12 +267,6 @@ const Mem0Plugin: Plugin = async (ctx) => { const systemContext: string[] = []; - // Auto-dream: gated memory-consolidation state (ported from the pi-agent plugin). - const mem0StateDir = join(homedir(), ".mem0"); - const dreamConfig = loadDreamConfig(mem0StateDir); - let dreamTriggered = false; - let dreamWriteSeen = false; - // Emit a session_stop telemetry event once when the process winds down. let sessionStopSent = false; const emitSessionStop = () => { @@ -307,16 +278,6 @@ const Mem0Plugin: Plugin = async (ctx) => { apiKey, appId, ); - // Finish an in-flight auto-dream: record completion if the agent consolidated, - // and always release the lock so the next eligible session can dream. - if (dreamTriggered) { - if (dreamWriteSeen) { - recordDreamCompletion(mem0StateDir); - captureEvent("dream_completed", {}, apiKey, appId); - } - releaseDreamLock(mem0StateDir); - dreamTriggered = false; - } }; try { process.on("beforeExit", emitSessionStop); @@ -366,7 +327,7 @@ Identity context (resolved at plugin startup): // user's persisted default scope (read fresh so /mem0-scope applies at once). // A "project" default preserves the existing behavior, including global_search. function readScopeFilters(args: any): any { - if (args.scope) return scopeSearchFilters(asScope(args.scope), userId, appId, sessionId); + if (args.scope) return scopeSearchFilters(resolveToolScope(asScope(args.scope), loadDefaultScope()), userId, appId, sessionId); if (args.filters || args.agent_id) return resolveFilters(args, globalSearch, userId, appId); const ds = loadDefaultScope(); return ds === "project" @@ -428,9 +389,8 @@ Identity context (resolved at plugin startup): }, async execute(args) { stats.adds++; - if (dreamTriggered) dreamWriteSeen = true; captureEvent("tool_use", {tool: "add_memory"}, apiKey, appId); - const effScope: Scope = args.scope ? asScope(args.scope) : loadDefaultScope(); + const effScope: Scope = resolveToolScope(args.scope ? asScope(args.scope) : undefined, loadDefaultScope()); const sp = scopeWriteParams(effScope, userId, appId, sessionId); const finalUserId = args.agent_id ? args.user_id : (args.user_id ?? sp.user_id); const finalAppId = args.app_id ?? sp.app_id; @@ -449,7 +409,7 @@ Identity context (resolved at plugin startup): } const res = await mem0.add( - [{ role: "user", content: args.text }], + [{ role: "user", content: lifecycle.prepareUserText(args.text) }], { user_id: finalUserId, app_id: finalAppId, @@ -481,7 +441,7 @@ Identity context (resolved at plugin startup): const topK = args.limit ?? args.top_k ?? 10; const filters = readScopeFilters(args); - const res = await mem0.search(args.query, { + const res = await mem0.search(lifecycle.prepareUserText(args.query), { filters, topK, }); @@ -535,7 +495,10 @@ Identity context (resolved at plugin startup): async execute(args) { captureEvent("tool_use", {tool: "update_memory"}, apiKey, appId); const res = await mem0.update(args.id, { - text: args.text, + text: + args.text === undefined + ? undefined + : lifecycle.prepareUserText(args.text), metadata: args.metadata, }); return JSON.stringify(res); @@ -548,7 +511,6 @@ Identity context (resolved at plugin startup): id: tool.schema.string().describe("The ID of the memory to delete"), }, async execute(args) { - if (dreamTriggered) dreamWriteSeen = true; captureEvent("tool_use", {tool: "delete_memory"}, apiKey, appId); const res = await mem0.delete(args.id); return JSON.stringify(res); @@ -564,9 +526,8 @@ Identity context (resolved at plugin startup): scope: tool.schema.string().optional().describe('Scope to delete: "project" (default), "session", or "global" (user-wide). Use "global" only when explicitly asked.'), }, async execute(args) { - if (dreamTriggered) dreamWriteSeen = true; captureEvent("tool_use", {tool: "delete_all_memories"}, apiKey, appId); - const sp = args.scope ? scopeWriteParams(asScope(args.scope), userId, appId, sessionId) : null; + const sp = args.scope ? scopeWriteParams(resolveToolScope(asScope(args.scope), loadDefaultScope()), userId, appId, sessionId) : null; const res = await mem0.deleteAll({ user_id: sp ? sp.user_id : (args.agent_id ? args.user_id : (args.user_id ?? userId)), app_id: sp ? sp.app_id : (args.app_id ?? appId), @@ -631,17 +592,13 @@ Identity context (resolved at plugin startup): const userText = extractUserText(input, output); if (!userText || userText.length < 10) return; - const safeText = redact(userText); + const safeText = lifecycle.prepareUserText(userText); msgCount++; stats.messages++; if (!initialized) { initialized = true; - if (dreamConfig.enabled) { - incrementSessionCount(mem0StateDir, sessionId); - } - const searchFilters = globalSearch ? {OR: [{user_id: "*"}]} : {AND: [{user_id: userId}, {app_id: appId}]}; @@ -727,28 +684,6 @@ Identity context (resolved at plugin startup): captureEvent("session_start", {memory_count: memoryCount}, apiKey, appId); - // Auto-dream: when the time/session/memory gates pass, inject the - // consolidation protocol so the agent tidies memories before answering. - if (dreamConfig.enabled && dreamConfig.auto && !dreamTriggered) { - const gates = checkCheapGates(mem0StateDir, dreamConfig); - const memGate = checkMemoryGate(memoryCount, dreamConfig); - if (gates.proceed && memGate.pass && acquireDreamLock(mem0StateDir)) { - dreamTriggered = true; - systemContext.push(DREAM_PROTOCOL); - captureEvent("dream_triggered", {memory_count: memoryCount}, apiKey, appId); - } else { - // Make "why didn't auto-dream run?" answerable from the logs. - const waiting = [gates.reason, memGate.reason].filter(Boolean).join("; "); - if (waiting) { - try { - await client.app.log({ - body: {service: "mem0", level: "info", message: `auto-dream waiting — ${waiting}`}, - }); - } catch { - } - } - } - } } const hasRemember = NUDGE_RE.test(safeText); diff --git a/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-context-loader/SKILL.md b/integrations/opencode-plugin/opencode-skills/mem0-context-loader/SKILL.md similarity index 100% rename from integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-context-loader/SKILL.md rename to integrations/opencode-plugin/opencode-skills/mem0-context-loader/SKILL.md diff --git a/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-forget/SKILL.md b/integrations/opencode-plugin/opencode-skills/mem0-forget/SKILL.md similarity index 100% rename from integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-forget/SKILL.md rename to integrations/opencode-plugin/opencode-skills/mem0-forget/SKILL.md diff --git a/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-remember/SKILL.md b/integrations/opencode-plugin/opencode-skills/mem0-remember/SKILL.md similarity index 100% rename from integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-remember/SKILL.md rename to integrations/opencode-plugin/opencode-skills/mem0-remember/SKILL.md diff --git a/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-scope/SKILL.md b/integrations/opencode-plugin/opencode-skills/mem0-scope/SKILL.md similarity index 98% rename from integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-scope/SKILL.md rename to integrations/opencode-plugin/opencode-skills/mem0-scope/SKILL.md index 776f4b364..1e2128141 100644 --- a/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-scope/SKILL.md +++ b/integrations/opencode-plugin/opencode-skills/mem0-scope/SKILL.md @@ -75,7 +75,7 @@ Look at the user's message for a target scope word: `project`, `session`, or 3. Write the file back with the Write tool, keeping ALL existing keys and only setting `"default_scope"` to the target. Pretty-print with 2-space indent and - a trailing newline. Do not drop `global_search`, `dream`, `auto_save`, or any + a trailing newline. Do not drop `global_search`, `auto_save`, or any other field that was present. Example resulting file (when other keys already existed): diff --git a/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-search/SKILL.md b/integrations/opencode-plugin/opencode-skills/mem0-search/SKILL.md similarity index 100% rename from integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-search/SKILL.md rename to integrations/opencode-plugin/opencode-skills/mem0-search/SKILL.md diff --git a/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-status/SKILL.md b/integrations/opencode-plugin/opencode-skills/mem0-status/SKILL.md similarity index 69% rename from integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-status/SKILL.md rename to integrations/opencode-plugin/opencode-skills/mem0-status/SKILL.md index 89a0e4542..9c1d6f151 100644 --- a/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-status/SKILL.md +++ b/integrations/opencode-plugin/opencode-skills/mem0-status/SKILL.md @@ -79,36 +79,6 @@ echo "branch=${MEM0_BRANCH:-}" - If all three are non-empty: PASS — "Session active" - If any are missing: WARN — "Plugin env vars not set; shell.env hook may not have fired" -### Check 6: Auto-dream readiness - -Explain whether auto-dream (memory consolidation) is eligible to run, and if not, exactly which gate is blocking. Auto-dream runs at most once per session and only when **all** gates pass: time since last consolidation ≥ `minHours`, sessions since ≥ `minSessions`, and project memory count ≥ `minMemories`. - -Read the gate state and thresholds: - -```bash -_ST="$HOME/.mem0/mem0-dream-state.json" -_SET="$HOME/.mem0/settings.json" -echo "sessions_since=$(grep -o '"sessionsSince"[[:space:]]*:[[:space:]]*[0-9]*' "$_ST" 2>/dev/null | grep -o '[0-9]*$' || echo 0)" -echo "last_consolidated_ms=$(grep -o '"lastConsolidatedAt"[[:space:]]*:[[:space:]]*[0-9]*' "$_ST" 2>/dev/null | grep -o '[0-9]*$' || echo 0)" -echo "min_hours=$(grep -o '"minHours"[[:space:]]*:[[:space:]]*[0-9]*' "$_SET" 2>/dev/null | grep -o '[0-9]*$' || echo 24)" -echo "min_sessions=$(grep -o '"minSessions"[[:space:]]*:[[:space:]]*[0-9]*' "$_SET" 2>/dev/null | grep -o '[0-9]*$' || echo 5)" -echo "min_memories=$(grep -o '"minMemories"[[:space:]]*:[[:space:]]*[0-9]*' "$_SET" 2>/dev/null | grep -o '[0-9]*$' || echo 20)" -echo "now_s=$(date +%s)" -echo "dream_env=${MEM0_DREAM:-unset}" -``` - -For the memory count, reuse the project memory count from Check 3/4 (or call `get_memories` with the project filter, `page_size=1`, and read `count`). - -Compute each gate: -- **time**: `hours_since = (now_s - last_consolidated_ms/1000) / 3600`. Passes when `≥ min_hours`. If `last_consolidated_ms` is 0 it has never run → time gate passes. -- **sessions**: passes when `sessions_since ≥ min_sessions`. -- **memories**: passes when project memory count `≥ min_memories`. - -Report: -- If `dream_env` is `false`/`0`/`no`/`off`, or `dream.enabled` is false in settings: WARN — "Auto-dream disabled". -- If all three gates pass: PASS — "eligible (runs at next session start)". -- Otherwise: WARN — list the blocking gate(s), e.g. `sessions 2/5, memories 3/20`. This is expected, not an error — auto-dream is just waiting. Note the user can run `/mem0-dream` to consolidate now, or lower the thresholds via the `dream` block in `~/.mem0/settings.json`. - ### Display ``` @@ -120,18 +90,15 @@ PASS Default scope project PASS Memory Tools 142ms PASS Write/Read write + delete OK PASS Session session_id=abc123, app_id=mem0, branch=main -WARN Auto-dream waiting — sessions 2/5, memories 3/20 (/mem0-dream to run now) All checks passed. ``` -The Auto-dream line is informational: WARN here means "waiting on gates", not a failure. Show PASS when eligible, or "disabled" when turned off. - If any check fails, add a `## Troubleshooting` section with specific fix steps for each failure. ## Extended mode: Memory Quality Analysis -When invoked with `--deep` (e.g., `/mem0-status --deep`), run the standard 6 checks above **plus** a memory quality scan. +When invoked with `--deep` (e.g., `/mem0-status --deep`), run the standard 5 checks above **plus** a memory quality scan. ### Quality Check 1: Duplicates @@ -188,9 +155,7 @@ Duplicates: · Stale: · Contradictions: · Orphans: ``` If all counts are 0: `Memory quality: clean.` -If any non-zero: append `Run /mem0-dream to fix.` - -To fix issues found by `--deep`, run `/mem0-dream` for automated consolidation (merges, prunes, conflict resolution). +If any non-zero, list the affected memory IDs so the user can review them with the normal search, update, and delete tools. ## Output formatting diff --git a/integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-tour/SKILL.md b/integrations/opencode-plugin/opencode-skills/mem0-tour/SKILL.md similarity index 100% rename from integrations/mem0-plugin/.opencode-plugin/opencode-skills/mem0-tour/SKILL.md rename to integrations/opencode-plugin/opencode-skills/mem0-tour/SKILL.md diff --git a/integrations/mem0-plugin/.opencode-plugin/package.json b/integrations/opencode-plugin/package.json similarity index 81% rename from integrations/mem0-plugin/.opencode-plugin/package.json rename to integrations/opencode-plugin/package.json index 2bd5fefd2..79f68c4a8 100644 --- a/integrations/mem0-plugin/.opencode-plugin/package.json +++ b/integrations/opencode-plugin/package.json @@ -1,13 +1,13 @@ { "name": "@mem0/opencode-plugin", - "version": "0.2.2", + "version": "0.3.0", "type": "module", "description": "Mem0 persistent memory plugin for OpenCode — add, search, and manage memories across sessions", "main": "dist/index.js", - "types": "dist/index.d.ts", + "types": "index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", + "types": "./index.d.ts", "import": "./dist/index.js" } }, @@ -26,15 +26,16 @@ "repository": { "type": "git", "url": "https://github.com/mem0ai/mem0", - "directory": "integrations/mem0-plugin/.opencode-plugin" + "directory": "integrations/opencode-plugin" }, "files": [ "dist", + "index.d.ts", "LICENSE", "opencode-skills" ], "scripts": { - "build": "bun build opencode-mem0.ts --outdir dist --target bun --format esm --entry-naming index.[ext] && tsc --emitDeclarationOnly --outDir dist --declaration", + "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", "prepack": "bun run build", @@ -59,8 +60,5 @@ "devDependencies": { "bun-types": ">=1.3.14", "typescript": "^5.7.3" - }, - "peerDependencies": { - "bun": ">=1.0.0" } } diff --git a/integrations/mem0-plugin/.opencode-plugin/project.test.ts b/integrations/opencode-plugin/project.test.ts similarity index 100% rename from integrations/mem0-plugin/.opencode-plugin/project.test.ts rename to integrations/opencode-plugin/project.test.ts diff --git a/integrations/opencode-plugin/project.ts b/integrations/opencode-plugin/project.ts new file mode 100644 index 000000000..4e5be585d --- /dev/null +++ b/integrations/opencode-plugin/project.ts @@ -0,0 +1 @@ +export { parseProjectFromRemote } from "../agent-plugin-core/typescript/src/identity.ts"; diff --git a/integrations/mem0-plugin/.opencode-plugin/scope.test.ts b/integrations/opencode-plugin/scope.test.ts similarity index 99% rename from integrations/mem0-plugin/.opencode-plugin/scope.test.ts rename to integrations/opencode-plugin/scope.test.ts index 49718b469..32b45a9cd 100644 --- a/integrations/mem0-plugin/.opencode-plugin/scope.test.ts +++ b/integrations/opencode-plugin/scope.test.ts @@ -29,7 +29,6 @@ describe("memory scope (pi-agent parity)", () => { test("global scope spans all the user's projects (matches pi-agent)", () => { expect(scopeSearchFilters("global", "u", "app", "run")).toEqual({ user_id: "u", - app_id: "*", }); // global writes drop app_id so the memory is user-wide, not project-bound expect(scopeWriteParams("global", "u", "app", "run")).toEqual({ user_id: "u" }); diff --git a/integrations/opencode-plugin/scope.ts b/integrations/opencode-plugin/scope.ts new file mode 100644 index 000000000..eaa4521c7 --- /dev/null +++ b/integrations/opencode-plugin/scope.ts @@ -0,0 +1,42 @@ +import { + normalizeScope, + scopeAddParams, + scopeSearchFilters as sharedSearchFilters, + type Scope, +} from "../agent-plugin-core/typescript/src/scoping.ts"; + +export type { Scope }; + +const context = (userId: string, appId: string, runId: string) => ({ userId, appId, runId }); + +export function scopeSearchFilters( + scope: Scope, + userId: string, + appId: string, + runId: string, +): Record { + return sharedSearchFilters(scope, context(userId, appId, runId)); +} + +export function scopeWriteParams( + scope: Scope, + userId: string, + appId: string, + runId: string, +): { user_id: string; app_id?: string; run_id?: string } { + const values = scopeAddParams(scope, context(userId, appId, runId)); + return { + user_id: values.userId, + ...(values.appId ? { app_id: values.appId } : {}), + ...(values.runId ? { run_id: values.runId } : {}), + }; +} + +export const asScope = normalizeScope; + +export function resolveDefaultScope(settings: Record | null | undefined): Scope { + return normalizeScope(settings?.default_scope); +} + +export const SCOPE_GUIDANCE = + 'Memory tools accept an optional `scope`: omit it (or "project") for normal queries; use "session" to limit to the current run; use "global" only after the user enables /mem0-scope global.'; diff --git a/integrations/mem0-plugin/.opencode-plugin/telemetry.test.ts b/integrations/opencode-plugin/telemetry.test.ts similarity index 100% rename from integrations/mem0-plugin/.opencode-plugin/telemetry.test.ts rename to integrations/opencode-plugin/telemetry.test.ts diff --git a/integrations/opencode-plugin/telemetry.ts b/integrations/opencode-plugin/telemetry.ts new file mode 100644 index 000000000..8d0861d97 --- /dev/null +++ b/integrations/opencode-plugin/telemetry.ts @@ -0,0 +1,66 @@ +import { createHash } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { release } from "node:os"; + +import { + createTelemetry, + isTelemetryEnabled, +} from "../agent-plugin-core/typescript/src/telemetry.ts"; + +export { isTelemetryEnabled }; + +const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"; +const PLUGIN_VERSION = (() => { + for (const relative of ["./package.json", "../package.json"]) { + try { + const pkg = JSON.parse(readFileSync(new URL(relative, import.meta.url), "utf-8")); + if (pkg?.name === "@mem0/opencode-plugin" && pkg.version) return pkg.version; + } catch { + // Try the source or bundled location. + } + } + return "unknown"; +})(); + +let currentDistinctId = ""; +const telemetry = createTelemetry({ + host: "opencode", + source: "plugin", + version: PLUGIN_VERSION, + distinctId: () => currentDistinctId, + eventName: (event) => `plugin.${event}`, + commonProperties: { + platform: "opencode", + os_version: release(), + sample_rate: 1.0, + }, +}); + +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") } : {}; +} + +export function buildEvent( + eventType: string, + properties: Record, + apiKey: string | undefined, + projectId?: string, +): Record | null { + currentDistinctId = apiKey ? distinctId(apiKey) : ""; + const event = telemetry.build(eventType, { ...properties, ...projectHash(projectId) }); + return event ? { api_key: POSTHOG_API_KEY, ...event } : null; +} + +export function captureEvent( + eventType: string, + properties: Record, + apiKey: string | undefined, + projectId?: string, +): void { + currentDistinctId = apiKey ? distinctId(apiKey) : ""; + telemetry.capture(eventType, { ...properties, ...projectHash(projectId) }); +} diff --git a/integrations/mem0-plugin/.opencode-plugin/tsconfig.json b/integrations/opencode-plugin/tsconfig.json similarity index 88% rename from integrations/mem0-plugin/.opencode-plugin/tsconfig.json rename to integrations/opencode-plugin/tsconfig.json index a635ca045..9ff59dc82 100644 --- a/integrations/mem0-plugin/.opencode-plugin/tsconfig.json +++ b/integrations/opencode-plugin/tsconfig.json @@ -6,12 +6,13 @@ "declaration": true, "declarationDir": "dist", "outDir": "dist", - "rootDir": ".", + "rootDir": "..", "strict": true, "esModuleInterop": true, "skipLibCheck": true, "lib": ["ESNext"], "types": ["bun-types"], + "allowImportingTsExtensions": true, "noEmit": false, "emitDeclarationOnly": true }, diff --git a/integrations/pi-agent-plugin/README.md b/integrations/pi-agent-plugin/README.md index 0c88c1b6b..c4d9a8286 100644 --- a/integrations/pi-agent-plugin/README.md +++ b/integrations/pi-agent-plugin/README.md @@ -2,7 +2,7 @@ Persistent semantic memory for [Pi Agent](https://pi.dev), powered by [Mem0](https://mem0.ai). -This extension gives Pi Agent long-term memory that persists across sessions, projects, and devices. Memories are automatically captured from conversations and can be searched, managed, and consolidated through slash commands and an agent-accessible tool. +This extension gives Pi Agent long-term memory that persists across sessions, projects, and devices. Memories are automatically captured from conversations and can be searched and managed through slash commands and an agent-accessible tool. ## Features @@ -10,9 +10,8 @@ This extension gives Pi Agent long-term memory that persists across sessions, pr - **Semantic search** — find memories by meaning, not just keywords - **Scoped memory** — project, session, or global scope - **Monorepo-aware** — uses git root for project detection, consistent app_id across subdirectories -- **Dream consolidation** — merges duplicates, resolves contradictions, prunes stale entries - **Confirmation dialogs** — destructive commands ask before acting -- **8 slash commands** — essential memory management from the command line +- **6 slash commands** — essential memory management from the command line - **Agent tool** — `mem0_memory` tool lets the agent search and store memories autonomously ## Setup @@ -43,20 +42,13 @@ Or create a config file at `~/.pi/agent/mem0-config.json`: "userId": "your-username", "autoCapture": true, "defaultScope": "project", - "searchThreshold": 0.2, - "dream": { - "enabled": true, - "auto": true, - "minHours": 24, - "minSessions": 5, - "minMemories": 20 - } + "searchThreshold": 0.3 } ``` Environment variables (`MEM0_API_KEY`, `MEM0_USER_ID`) override the config file. -`searchThreshold` (default `0.3`) is the minimum similarity score (0–1) a memory must reach to count as a match for `/mem0-search`, `/mem0-forget`, and `/mem0-pin`. It is passed to the mem0 search API (along with reranking for higher-precision ordering), so a query with no sufficiently similar memory reports no match instead of returning the closest unrelated memories. Raise it to be stricter; lower it if relevant results are missed. +`searchThreshold` (default `0.3`) is the minimum similarity score (0–1) a memory must reach to count as a match for `/mem0-search` and `/mem0-forget`. It is passed to the mem0 search API (along with reranking for higher-precision ordering), so a query with no sufficiently similar memory reports no match instead of returning the closest unrelated memories. Raise it to be stricter; lower it if relevant results are missed. ## Commands @@ -66,14 +58,12 @@ Environment variables (`MEM0_API_KEY`, `MEM0_USER_ID`) override the config file. | `/mem0-forget ` | Search and delete memories (with confirmation) | | `/mem0-search ` | Semantic search across memories | | `/mem0-tour [scope]` | Browse all memories grouped by category | -| `/mem0-dream` | Consolidate — merge duplicates, prune stale, resolve contradictions | -| `/mem0-pin ` | Pin a memory to protect from dream pruning (preserves ID) | | `/mem0-scope ` | Change default scope for this session | | `/mem0-status` | Connection health, identity, and memory count | ## Skills -The plugin includes 8 skills that guide the agent on how to use each capability: +The plugin includes 6 skills that guide the agent on how to use each capability: | Skill | Purpose | |-------|---------| @@ -81,9 +71,7 @@ The plugin includes 8 skills that guide the agent on how to use each capability: | `remember` | Store facts with category classification | | `search` | Quick semantic search with compact results | | `forget` | Delete memories with confirmation | -| `dream` | Memory consolidation workflow | | `tour` | Full memory walkthrough by category | -| `pin` | Protect critical memories from pruning | | `status` | Health check and diagnostics | ## Memory Scopes @@ -120,15 +108,14 @@ pi-agent-plugin/ ├── src/ │ ├── entry.ts # Extension entry point │ ├── index.ts # Barrel exports -│ ├── commands.ts # 8 slash commands +│ ├── commands.ts # 6 slash commands │ ├── prompt.ts # System prompt injection (MEMORY_POLICY) │ ├── types.ts # Shared interfaces and categories │ ├── telemetry.ts # PostHog telemetry (batched, PII-safe) │ ├── config/ # Config loading (~/.pi/agent/mem0-config.json) │ ├── memory/ # Tool registration, scoping (git root), formatting -│ ├── capture/ # Auto-capture from conversations (user + assistant) -│ └── dream/ # Consolidation state, gating, locking, prompts -├── skills/ # 8 SKILL.md files for Pi Agent +│ └── capture/ # Auto-capture from conversations (user + assistant) +├── skills/ # 6 SKILL.md files for Pi Agent ├── tests/ # Vitest unit tests └── dist/ # Built output (ESM + DTS) ``` @@ -145,3 +132,5 @@ pnpm run build # Build (ESM + declarations) ## License [Apache-2.0](LICENSE) + +Global tool operations require `/mem0-scope global` or `defaultScope: "global"` in plugin configuration. A model-supplied `scope` argument cannot enable cross-project access on its own. Empty or wildcard user, project, and session identities are rejected. diff --git a/integrations/pi-agent-plugin/package.json b/integrations/pi-agent-plugin/package.json index 69d3d69ca..d9b3f7d2e 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.1.5", + "version": "0.3.0", "type": "module", "description": "Mem0 memory extension for Pi Agent persistent, scoped, semantic memory across sessions and projects", "license": "Apache-2.0", @@ -32,14 +32,13 @@ }, "files": [ "dist", - "src", "skills", "README.md", "LICENSE" ], "pi": { "extensions": [ - "./src/entry.ts" + "./dist/entry.js" ], "skills": [ "./skills" diff --git a/integrations/pi-agent-plugin/skills/dream/SKILL.md b/integrations/pi-agent-plugin/skills/dream/SKILL.md deleted file mode 100644 index 21e9c5f43..000000000 --- a/integrations/pi-agent-plugin/skills/dream/SKILL.md +++ /dev/null @@ -1,125 +0,0 @@ ---- -name: dream -description: Consolidates stored memories by merging duplicates, resolving contradictions, and pruning stale entries. Use when memory count is high, search results feel noisy or repetitive, or periodic cleanup is needed to maintain memory quality. ---- - -# Dream — Memory Consolidation - -This skill performs a memory consolidation pass: it fetches all memories, identifies near-duplicates, flags contradictions, and prunes stale entries. All proposed changes are shown as a diff for user approval before anything is modified. - -**IMPORTANT: Execute steps strictly in order (1 -> 2 -> 3 -> 4 -> 5). Each step depends on the previous one. Do NOT run steps in parallel or skip ahead.** - -## Step 1: Fetch ALL Memories - -Use `mem0_memory` tool with `action="get_all"` to retrieve every memory. - -If zero memories are found, print: - -``` -No memories found. Nothing to consolidate. -``` - -...and stop. - -## Step 2: Analyze — Find Issues - -Work entirely in-memory; do not modify anything yet. - -Group memories by category. For each group, identify the following: - -### 2a. Near-duplicate pairs (merge candidates) - -Two memories are near-duplicates when they express the same fact but phrased differently (e.g., "Prefers morning meetings" and "Likes scheduling meetings early"). - -Heuristics — two memories are near-duplicates if **all** of these hold: -- If >60% of significant nouns/keywords overlap, treat as near-duplicate. -- Same category. -- Neither memory is pinned (content does not start with `[PINNED]`). - -For each qualifying pair, draft a merged version that is more complete than either original. - -### 2b. Contradictions - -Two memories contradict when they assert opposing facts about the same topic (e.g., "Prefers cats" vs. "Allergic to cats, prefers dogs"). - -Identify the likely winner: the more recent memory wins. Store both IDs and their content for user review. - -### 2c. Prune candidates - -A memory is a prune candidate when **any** of the following is true: - -1. It is older than 180 days AND has not been accessed recently. -2. Its content is extremely vague (fewer than 5 meaningful words). - -**Always skip memories where content starts with `[PINNED]`**, regardless of age. - -## Step 3: Print Diff Report - -Print a structured diff before making any changes: - -``` -## dream — consolidation report - -Merges (): - [mem0:] + [mem0:] -> "" - -Conflicts (): - [mem0:] vs [mem0:] — "" [A/B/skip] - -Prune (): - [mem0:] — , d old - -Proposed: merges, prunes, conflicts. Apply? [Y/n] -``` - -If there are zero total proposals, print: - -``` -Dream complete. No duplicate, contradictory, or stale memories found. -``` - -...and stop. - -## Step 4: Wait for User Input and Apply - -### 4a. Contradictions - -For each conflict pair, wait for the user to choose A, B, or skip. - -### 4b. Final confirmation - -After all conflict resolutions are collected, prompt: `Apply? [Y/n]` - -If the user declines, print `Cancelled. No changes made.` and stop. - -If confirmed, apply all changes: - -**Merges:** Delete both originals, add the merged version using `mem0_memory` with `action="add"`. - -**Contradictions (resolved):** Delete the loser using `mem0_memory` with `action="delete"`. - -**Prunes:** Delete each using `mem0_memory` with `action="delete"`. - -## Step 5: Print Summary - -``` -Dream complete — merged: , pruned: , conflicts resolved: , skipped: -``` - -## Auto mode - -When invoked with `--auto` (e.g., `/mem0-dream --auto`), run non-interactively: - -- **Merges**: applied automatically. -- **Prunes**: applied automatically. -- **Contradictions**: skipped — they require human judgment. - -Print a compact summary: -``` -[mem0-dream --auto] merged= pruned= conflicts_skipped= -``` - -## See also - -- `/mem0-forget` — targeted deletion of specific memories -- `/mem0-status` — quick health check diff --git a/integrations/pi-agent-plugin/skills/pin/SKILL.md b/integrations/pi-agent-plugin/skills/pin/SKILL.md deleted file mode 100644 index 11b075d37..000000000 --- a/integrations/pi-agent-plugin/skills/pin/SKILL.md +++ /dev/null @@ -1,48 +0,0 @@ ---- -name: pin -description: Pins or unpins a memory to protect it from pruning during dream consolidation. Use when a memory is critical and must never be removed, such as core preferences, important decisions, or immutable personal facts. ---- - -# Pin - -Pin a memory to mark it as high-priority and protect from dream pruning. - -## Execution - -### Step 1: Find the memory - -The user provides either a search query or memory ID. - -**If memory ID:** Look it up directly. - -**If search query:** -- Use `mem0_memory` tool with `action="search"`, `query=`. -- Show numbered list with content previews. -- Ask: "Which memory to pin? Enter a number." - -### Step 2: Pin it - -Pinning works by prepending `[PINNED]` to the memory text. This marker tells the dream consolidation to skip it during pruning. - -Use `mem0_memory` tool with `action="add"`, `content="[PINNED] "`. - -Then delete the original using `mem0_memory` with `action="delete"` and the original memory ID. - -**For new memories** (user wants to pin text that isn't stored yet): -- Use `mem0_memory` tool with `action="add"`, `content="[PINNED] "`. - -### Step 3: Confirm - -``` -Pinned: "" -``` - -Append `...` only if content exceeds 80 characters. - -### Unpin - -If the user says "unpin": -1. Find the memory (search or by ID). -2. Create a new memory without the `[PINNED]` prefix. -3. Delete the pinned version. -4. Print: `Unpinned: "..."` diff --git a/integrations/pi-agent-plugin/skills/status/SKILL.md b/integrations/pi-agent-plugin/skills/status/SKILL.md index 75d073fd7..5778cfe7f 100644 --- a/integrations/pi-agent-plugin/skills/status/SKILL.md +++ b/integrations/pi-agent-plugin/skills/status/SKILL.md @@ -86,4 +86,4 @@ Duplicates: · Stale: · Contradictions: ``` If all counts are 0: `Memory quality: clean.` -If any non-zero: append `Run /mem0-dream to fix.` +If any non-zero, list the affected memory IDs so the user can review them with the normal search and forget commands. diff --git a/integrations/pi-agent-plugin/src/capture/index.ts b/integrations/pi-agent-plugin/src/capture/index.ts index 3b7a5d5d4..0c35fb630 100644 --- a/integrations/pi-agent-plugin/src/capture/index.ts +++ b/integrations/pi-agent-plugin/src/capture/index.ts @@ -4,37 +4,9 @@ import type { Mem0Config, ScopeContext } from "../types.ts"; import { DEFAULT_CUSTOM_CATEGORIES } from "../types.ts"; import { resolveAddParams } from "../memory/scoping.ts"; import { captureEvent } from "../telemetry.ts"; +import { createMemoryLifecycle } from "../../../agent-plugin-core/typescript/src/lifecycle.ts"; -interface MessageLike { - role: string; - content?: unknown; -} - -function extractText(content: unknown): string | null { - if (typeof content === "string") return content; - if (Array.isArray(content)) { - const texts = content - .filter((b: any) => b.type === "text" && typeof b.text === "string") - .map((b: any) => b.text); - return texts.length > 0 ? texts.join("\n") : null; - } - return null; -} - -export function extractConversation( - messages: MessageLike[], -): Array<{ role: "user" | "assistant"; content: string }> { - const result: Array<{ role: "user" | "assistant"; content: string }> = []; - - for (const msg of messages) { - if (msg.role !== "user" && msg.role !== "assistant") continue; - const text = extractText(msg.content); - if (!text) continue; - result.push({ role: msg.role as "user" | "assistant", content: text }); - } - - return result; -} +export { extractConversation } from "../../../agent-plugin-core/typescript/src/lifecycle.ts"; export function setupAutoCapture( pi: ExtensionAPI, @@ -42,12 +14,13 @@ export function setupAutoCapture( config: Mem0Config, getScopeCtx: () => ScopeContext, telemetryCtx?: { apiKey?: string }, + lifecycle: ReturnType = createMemoryLifecycle(), ): void { if (!config.autoCapture) return; pi.on("agent_end", async (event) => { const messages = event.messages ?? []; - const conversation = extractConversation(messages); + const conversation = lifecycle.prepareConversation(messages); if (conversation.length === 0) return; const scopeCtx = getScopeCtx(); diff --git a/integrations/pi-agent-plugin/src/commands.test.ts b/integrations/pi-agent-plugin/src/commands.test.ts index 1ba46c6be..73ac9c6cb 100644 --- a/integrations/pi-agent-plugin/src/commands.test.ts +++ b/integrations/pi-agent-plugin/src/commands.test.ts @@ -6,14 +6,6 @@ vi.mock("./telemetry.ts", () => ({ captureCommandEvent: vi.fn(), })); -vi.mock("./dream/index.ts", () => ({ - acquireDreamLock: vi.fn(() => true), -})); - -vi.mock("./dream/prompt.ts", () => ({ - DREAM_PROTOCOL: "dream protocol text", -})); - function makeMem0() { return { search: vi.fn(), @@ -56,7 +48,6 @@ const defaultConfig: Mem0Config = { defaultScope: "project", contextInjection: false, searchThreshold: 0.3, - dream: { enabled: false, auto: false, minHours: 24, minSessions: 5, minMemories: 20 }, }; const scopeCtx: ScopeContext = { userId: "test-user", appId: "test-app", runId: "test-run" }; @@ -74,14 +65,14 @@ describe("registerCommands", () => { it("registers all expected commands", () => { const names = [...pi._commands.keys()]; - expect(names).toContain("mem0-remember"); - expect(names).toContain("mem0-forget"); - expect(names).toContain("mem0-search"); - expect(names).toContain("mem0-tour"); - expect(names).toContain("mem0-dream"); - expect(names).toContain("mem0-pin"); - expect(names).toContain("mem0-scope"); - expect(names).toContain("mem0-status"); + expect(names).toEqual([ + "mem0-remember", + "mem0-forget", + "mem0-search", + "mem0-tour", + "mem0-scope", + "mem0-status", + ]); }); describe("/mem0-forget", () => { @@ -197,103 +188,6 @@ describe("registerCommands", () => { }); }); - describe("/mem0-pin", () => { - it("uses update to pin in-place, preserving memory ID", async () => { - const ctx = makeCtx(true); - mem0.search.mockResolvedValue({ results: [{ id: "abc-123", memory: "important fact" }] }); - mem0.update.mockResolvedValue([]); - - await pi._invoke("mem0-pin", "important", ctx); - - expect(ctx.ui.confirm).toHaveBeenCalledWith( - "Pin this memory?", - expect.stringContaining("important fact"), - ); - expect(mem0.update).toHaveBeenCalledWith("abc-123", { text: "[PINNED] important fact" }); - expect(mem0.add).not.toHaveBeenCalled(); - expect(mem0.delete).not.toHaveBeenCalled(); - }); - - it("sends a visible confirmation after pinning", async () => { - const ctx = makeCtx(true); - mem0.search.mockResolvedValue({ results: [{ id: "abc-123", memory: "important fact" }] }); - mem0.update.mockResolvedValue([]); - - await pi._invoke("mem0-pin", "important", ctx); - - expect(pi.sendMessage).toHaveBeenCalledWith( - expect.objectContaining({ - customType: "mem0-pin", - content: expect.stringContaining("Pinned"), - display: true, - }), - ); - }); - - it("does not pin when user cancels", async () => { - const ctx = makeCtx(false); - mem0.search.mockResolvedValue({ results: [{ id: "abc-123", memory: "fact" }] }); - - await pi._invoke("mem0-pin", "fact", ctx); - - expect(mem0.update).not.toHaveBeenCalled(); - }); - - it("skips already-pinned memories with a visible message", async () => { - const ctx = makeCtx(); - mem0.search.mockResolvedValue({ results: [{ id: "abc-123", memory: "[PINNED] fact" }] }); - - await pi._invoke("mem0-pin", "fact", ctx); - - expect(ctx.ui.confirm).not.toHaveBeenCalled(); - expect(mem0.add).not.toHaveBeenCalled(); - expect(pi.sendMessage).toHaveBeenCalledWith( - expect.objectContaining({ content: expect.stringContaining("Already pinned"), display: true }), - ); - }); - - it("uses select UI for multiple matches and pins chosen memory", async () => { - const ctx = makeCtx(); - mem0.search.mockResolvedValue({ - results: [ - { id: "id-1", memory: "fact one" }, - { id: "id-2", memory: "fact two" }, - ], - }); - mem0.update.mockResolvedValue([]); - ctx.ui.select = vi.fn(async (_title: string, options: string[]) => options[1]); - - await pi._invoke("mem0-pin", "fact", ctx); - - expect(ctx.ui.select).toHaveBeenCalledWith( - expect.stringContaining("which should I pin"), - expect.arrayContaining([ - expect.stringContaining("fact one"), - expect.stringContaining("fact two"), - ]), - ); - expect(mem0.update).toHaveBeenCalledWith("id-2", { text: "[PINNED] fact two" }); - }); - - it("does not pin when user cancels select", async () => { - const ctx = makeCtx(); - ctx.ui.select = vi.fn(async () => undefined); - mem0.search.mockResolvedValue({ - results: [ - { id: "id-1", memory: "fact one" }, - { id: "id-2", memory: "fact two" }, - ], - }); - - await pi._invoke("mem0-pin", "fact", ctx); - - expect(mem0.update).not.toHaveBeenCalled(); - expect(pi.sendMessage).toHaveBeenCalledWith( - expect.objectContaining({ content: expect.stringContaining("Cancelled"), display: true }), - ); - }); - }); - describe("/mem0-search", () => { it("performs server-side semantic search with a relevance threshold", async () => { const ctx = makeCtx(); @@ -488,23 +382,4 @@ describe("registerCommands", () => { }); }); - describe("/mem0-dream", () => { - it("feeds the protocol to the agent and shows a clean status line", async () => { - const ctx = makeCtx(); - - await pi._invoke("mem0-dream", "", ctx); - - expect(pi.sendMessage).toHaveBeenCalledWith( - expect.objectContaining({ customType: "mem0-dream", display: false }), - expect.objectContaining({ triggerTurn: true }), - ); - expect(pi.sendMessage).toHaveBeenCalledWith( - expect.objectContaining({ - customType: "mem0-dream", - content: expect.stringContaining("Dreaming"), - display: true, - }), - ); - }); - }); }); diff --git a/integrations/pi-agent-plugin/src/commands.ts b/integrations/pi-agent-plugin/src/commands.ts index e5b760043..9379bed9a 100644 --- a/integrations/pi-agent-plugin/src/commands.ts +++ b/integrations/pi-agent-plugin/src/commands.ts @@ -4,9 +4,6 @@ import type { Mem0Config, ScopeContext, Scope } from "./types.ts"; import { DEFAULT_CUSTOM_CATEGORIES } from "./types.ts"; import { resolveSearchFilters, resolveAddParams } from "./memory/scoping.ts"; import { formatMemoryList, formatMemoryCompact, groupByCategory } from "./memory/formatting.ts"; -import { DREAM_PROTOCOL } from "./dream/prompt.ts"; -import { acquireDreamLock } from "./dream/index.ts"; -import { CONFIG_DIR } from "./config/index.ts"; import { captureCommandEvent } from "./telemetry.ts"; const SEARCH_TOP_K = 10; @@ -184,90 +181,6 @@ export function registerCommands( }, }); - pi.registerCommand("mem0-dream", { - description: "Consolidate memories — merge duplicates, prune stale entries, resolve contradictions", - handler: async (_args, ctx) => { - if (!acquireDreamLock(CONFIG_DIR)) { - ctx.ui.notify("A dream consolidation is already in progress.", "warning"); - return; - } - - captureCommandEvent("mem0-dream", {}, telemetryCtx); - pi.sendMessage({ customType: "mem0-dream", content: DREAM_PROTOCOL, display: false }, { triggerTurn: true }); - sendFeedback( - "mem0-dream", - "**Dreaming** — reviewing your memories to merge duplicates, resolve contradictions, and prune stale entries. I'll report what changed.", - ); - }, - }); - - pi.registerCommand("mem0-pin", { - description: "Pin a memory to protect it from dream pruning", - handler: async (args, ctx) => { - const query = args?.trim(); - if (!query) { - ctx.ui.notify("Usage: /mem0-pin ", "warning"); - return; - } - - const memories = await searchMemories(query, config.defaultScope); - - if (memories.length === 0) { - captureCommandEvent("mem0-pin", { result_count: 0 }, telemetryCtx); - sendFeedback("mem0-pin", `**No matches for "${query}"** — nothing to pin.`); - return; - } - - const pinned = (mem: Parameters[0]) => { - captureCommandEvent("mem0-pin", { pinned: true }, telemetryCtx); - sendFeedback( - "mem0-pin", - ["**Pinned** — protected from dream pruning", `- ${formatMemoryCompact(mem)}`].join("\n"), - ); - }; - const alreadyPinned = (mem: Parameters[0]) => { - sendFeedback("mem0-pin", ["**Already pinned**", `- ${formatMemoryCompact(mem)}`].join("\n")); - }; - - if (memories.length === 1) { - const target = memories[0]; - const text = target.memory ?? ""; - if (text.startsWith("[PINNED]")) { - alreadyPinned(target); - return; - } - const confirmed = await ctx.ui.confirm("Pin this memory?", formatMemoryCompact(target)); - if (!confirmed) { - sendFeedback("mem0-pin", "**Cancelled** — nothing was pinned."); - return; - } - await mem0.update(target.id, { text: `[PINNED] ${text}` }); - pinned(target); - return; - } - - const labels = memories.map((m) => formatMemoryCompact(m)); - const selected = await ctx.ui.select( - `Found ${pluralize(memories.length, "match", "matches")} for "${query}" — which should I pin?`, - labels, - ); - if (!selected) { - sendFeedback("mem0-pin", "**Cancelled** — nothing was pinned."); - return; - } - const idx = labels.indexOf(selected); - if (idx < 0) return; - const target = memories[idx]; - const selectedText = target.memory ?? ""; - if (selectedText.startsWith("[PINNED]")) { - alreadyPinned(target); - return; - } - await mem0.update(target.id, { text: `[PINNED] ${selectedText}` }); - pinned(target); - }, - }); - pi.registerCommand("mem0-scope", { description: "Change default memory scope for this session (project, session, global)", handler: async (args, ctx) => { @@ -329,7 +242,6 @@ export function registerCommands( `- Search relevance threshold: ${config.searchThreshold}`, `- Project memories: ${count}`, `- Auto-capture: ${config.autoCapture ? "on" : "off"}`, - `- Dream: ${config.dream.enabled ? "enabled" : "disabled"}`, ]; captureCommandEvent("mem0-status", { connected, memory_count: count }, telemetryCtx); diff --git a/integrations/pi-agent-plugin/src/config/index.ts b/integrations/pi-agent-plugin/src/config/index.ts index 8788896cf..36746b50e 100644 --- a/integrations/pi-agent-plugin/src/config/index.ts +++ b/integrations/pi-agent-plugin/src/config/index.ts @@ -1,20 +1,12 @@ import * as fs from "node:fs"; import * as os from "node:os"; import * as path from "node:path"; -import type { Mem0Config, DreamConfig } from "../types.ts"; +import type { Mem0Config } from "../types.ts"; const AGENT_ROOT = path.join(os.homedir(), ".pi", "agent"); export const CONFIG_DIR = AGENT_ROOT; const CONFIG_PATH = path.join(AGENT_ROOT, "mem0-config.json"); -const DEFAULT_DREAM: DreamConfig = { - enabled: true, - auto: true, - minHours: 24, - minSessions: 5, - minMemories: 20, -}; - const DEFAULT_CONFIG: Mem0Config = { apiKey: "", userId: "", @@ -22,7 +14,6 @@ const DEFAULT_CONFIG: Mem0Config = { defaultScope: "project", contextInjection: true, searchThreshold: 0.3, - dream: DEFAULT_DREAM, }; export function loadConfig(): Mem0Config { @@ -37,15 +28,9 @@ export function loadConfig(): Mem0Config { } } - const dream: DreamConfig = { - ...DEFAULT_DREAM, - ...(fileConfig.dream ?? {}), - }; - const config: Mem0Config = { ...DEFAULT_CONFIG, ...fileConfig, - dream, }; if (process.env.MEM0_API_KEY) { diff --git a/integrations/pi-agent-plugin/src/dream/index.ts b/integrations/pi-agent-plugin/src/dream/index.ts deleted file mode 100644 index 2129d947b..000000000 --- a/integrations/pi-agent-plugin/src/dream/index.ts +++ /dev/null @@ -1,115 +0,0 @@ -import * as fs from "node:fs"; -import * as path from "node:path"; -import type { DreamState, DreamLock, DreamConfig } from "../types.ts"; - -const LOCK_STALE_MS = 60 * 60 * 1000; - -const DEFAULTS: DreamConfig = { - enabled: true, - auto: true, - minHours: 24, - minSessions: 5, - minMemories: 20, -}; - -function statePath(stateDir: string): string { - return path.join(stateDir, "mem0-dream-state.json"); -} - -function lockPath(stateDir: string): string { - return path.join(stateDir, "mem0-dream.lock"); -} - -function ensureDir(dir: string): void { - try { - fs.mkdirSync(dir, { recursive: true }); - } catch { /* exists */ } -} - -function readState(stateDir: string): DreamState { - try { - const raw = fs.readFileSync(statePath(stateDir), "utf-8"); - return JSON.parse(raw) as DreamState; - } catch { - return { lastConsolidatedAt: 0, sessionsSince: 0, lastSessionId: null }; - } -} - -function writeState(stateDir: string, state: DreamState): void { - ensureDir(stateDir); - fs.writeFileSync(statePath(stateDir), JSON.stringify(state, null, 2)); -} - -export function incrementSessionCount(stateDir: string, sessionId: string): void { - const state = readState(stateDir); - if (state.lastSessionId !== sessionId) { - state.sessionsSince++; - state.lastSessionId = sessionId; - writeState(stateDir, state); - } -} - -export function checkCheapGates( - stateDir: string, - config: Partial, -): { proceed: boolean; reason?: string } { - const minHours = config.minHours ?? DEFAULTS.minHours; - const minSessions = config.minSessions ?? DEFAULTS.minSessions; - const state = readState(stateDir); - - const hoursSince = (Date.now() - state.lastConsolidatedAt) / 3_600_000; - if (hoursSince < minHours) { - return { proceed: false, reason: `time: ${hoursSince.toFixed(1)}h < ${minHours}h` }; - } - - if (state.sessionsSince < minSessions) { - return { proceed: false, reason: `sessions: ${state.sessionsSince} < ${minSessions}` }; - } - - return { proceed: true }; -} - -export function checkMemoryGate( - memoryCount: number, - config: Partial, -): { pass: boolean; reason?: string } { - const minMemories = config.minMemories ?? DEFAULTS.minMemories; - if (memoryCount < minMemories) { - return { pass: false, reason: `memories: ${memoryCount} < ${minMemories}` }; - } - return { pass: true }; -} - -export function acquireDreamLock(stateDir: string): boolean { - ensureDir(stateDir); - const lp = lockPath(stateDir); - - try { - const raw = fs.readFileSync(lp, "utf-8"); - const lock = JSON.parse(raw) as DreamLock; - if (Date.now() - lock.startedAt < LOCK_STALE_MS) { - return false; - } - try { fs.unlinkSync(lp); } catch { /* race ok */ } - } catch { /* no lock file */ } - - const lock: DreamLock = { pid: process.pid, startedAt: Date.now() }; - try { - fs.writeFileSync(lp, JSON.stringify(lock), { flag: "wx" }); - return true; - } catch { - return false; - } -} - -export function releaseDreamLock(stateDir: string): void { - try { fs.unlinkSync(lockPath(stateDir)); } catch { /* already gone */ } -} - -export function recordDreamCompletion(stateDir: string): void { - const state = readState(stateDir); - state.lastConsolidatedAt = Date.now(); - state.sessionsSince = 0; - state.lastSessionId = null; - writeState(stateDir, state); -} diff --git a/integrations/pi-agent-plugin/src/dream/prompt.ts b/integrations/pi-agent-plugin/src/dream/prompt.ts deleted file mode 100644 index 4da1e7171..000000000 --- a/integrations/pi-agent-plugin/src/dream/prompt.ts +++ /dev/null @@ -1,22 +0,0 @@ -export const DREAM_PROTOCOL = ` -You are running memory consolidation. Complete these steps using the mem0_memory tool: - -1. ORIENT — Call mem0_memory with action "get_all" to list all memories. Count by category. Note oldest/newest. - -2. GATHER TARGETS — Review each memory. Classify as: - - DELETE: sensitive information (API keys, passwords, tokens), expired/stale entries, noise, redundant operational details - - MERGE: near-duplicates (same fact stated differently). Keep the better-worded one, delete the other. - - REWRITE: vague, first-person, or poorly-categorized entries. Use mem0_memory "add" with improved text, then "delete" the old one. - - KEEP: everything else. - Skip any memory starting with "[PINNED]". - -3. CONSOLIDATE — Execute the changes: - - Delete stale/duplicate entries - - For merges: add the merged text, delete both originals - - For rewrites: add improved version, delete original - -4. REPORT — Summarize: how many reviewed, deleted, merged, rewritten, final count. - -Quality targets: zero sensitive data stored, zero duplicates, all entries are atomic (one fact each), 15-50 words each. -After consolidation, respond to the user's message normally. -`; diff --git a/integrations/pi-agent-plugin/src/entry.ts b/integrations/pi-agent-plugin/src/entry.ts index 51ad5bcd0..d49d78ad0 100644 --- a/integrations/pi-agent-plugin/src/entry.ts +++ b/integrations/pi-agent-plugin/src/entry.ts @@ -1,24 +1,17 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import MemoryClient from "mem0ai"; -import { loadConfig, CONFIG_DIR } from "./config/index.ts"; +import { loadConfig } from "./config/index.ts"; import { detectAppId, detectRunId, resolveSearchFilters } from "./memory/scoping.ts"; -import { formatMemoryList } from "./memory/formatting.ts"; import { registerMemoryTool } from "./memory/tools.ts"; import { registerCommands } from "./commands.ts"; import { setupAutoCapture } from "./capture/index.ts"; import { MEMORY_POLICY } from "./prompt.ts"; -import { DREAM_PROTOCOL } from "./dream/prompt.ts"; -import { - incrementSessionCount, - checkCheapGates, - checkMemoryGate, - acquireDreamLock, - releaseDreamLock, - recordDreamCompletion, -} from "./dream/index.ts"; import { captureEvent } from "./telemetry.ts"; import * as os from "node:os"; import type { ScopeContext } from "./types.ts"; +import { createMemoryLifecycle } from "../../agent-plugin-core/typescript/src/lifecycle.ts"; + +export { buildRecallContext } from "../../agent-plugin-core/typescript/src/lifecycle.ts"; export function resolveUserId(configUserId: string): string { if (configUserId) return configUserId; @@ -27,31 +20,6 @@ export function resolveUserId(configUserId: string): string { try { return os.userInfo().username; } catch { return "default"; } } -/** - * Build the auto-recall context block for a turn: search memory with the user's - * prompt and format the top matches so they are guaranteed in context instead of - * relying on the agent to call the tool. Best-effort — returns "" when disabled, - * the prompt is blank, nothing matches, or the search fails; it must never block - * the turn. - */ -export async function buildRecallContext( - prompt: string, - enabled: boolean, - search: (query: string) => Promise<{ results?: unknown[] }>, -): Promise { - if (!enabled) return ""; - const q = prompt.trim(); - if (!q) return ""; - try { - const res = await search(q); - const memories = (res.results ?? []) as Parameters[0]; - if (memories.length === 0) return ""; - return `\nRetrieved automatically for the current request. This is a shallow first pass — search mem0_memory for more if you need it.\n${formatMemoryList(memories)}\n`; - } catch { - return ""; - } -} - export default function mem0Extension(pi: ExtensionAPI): void { const config = loadConfig(); @@ -73,20 +41,21 @@ export default function mem0Extension(pi: ExtensionAPI): void { } const telemetryCtx = { apiKey: config.apiKey }; + const lifecycle = createMemoryLifecycle(); // ── Register tool + commands + auto-capture ───────────────────────── registerMemoryTool(pi, mem0, config, getScopeCtx, telemetryCtx); registerCommands(pi, mem0, config, getScopeCtx, telemetryCtx); - setupAutoCapture(pi, mem0, config, getScopeCtx, telemetryCtx); + setupAutoCapture(pi, mem0, config, getScopeCtx, telemetryCtx, lifecycle); captureEvent("pi.plugin.registered", { auto_capture: config.autoCapture, - dream_enabled: config.dream.enabled, default_scope: config.defaultScope, }, telemetryCtx); // ── session_start: detect project + session, reconstruct scope ────── pi.on("session_start", async (_event, ctx) => { + lifecycle.beginSession(); scopeCtx.appId = detectAppId(ctx.cwd); const sessionFile = ctx.sessionManager?.getSessionFile?.(); @@ -96,86 +65,29 @@ export default function mem0Extension(pi: ExtensionAPI): void { scopeCtx.userId = config.userId; } - if (config.dream.enabled) { - incrementSessionCount(CONFIG_DIR, scopeCtx.runId); - } - captureEvent("pi.session.start", {}, telemetryCtx); }); - // ── before_agent_start: append memory policy + auto-dream trigger ─── - let dreamTriggered = false; - let dreamChecked = false; - + // ── before_agent_start: append memory policy and recall ───────────── pi.on("before_agent_start", async (event, _ctx) => { let extra = MEMORY_POLICY; // Guaranteed retrieval: prefetch memories relevant to this prompt so the // agent always has them, rather than depending on it to call the tool. - const recall = await buildRecallContext( + const recall = await lifecycle.recall( event.prompt ?? "", config.contextInjection, (q) => mem0.search(q, { filters: resolveSearchFilters("project", scopeCtx) }), ); if (recall) extra += "\n\n" + recall; - if (config.dream.enabled && config.dream.auto && !dreamTriggered && !dreamChecked) { - const gates = checkCheapGates(CONFIG_DIR, config.dream); - if (gates.proceed) { - try { - const filters = resolveSearchFilters("project", scopeCtx); - const result = await mem0.getAll({ filters }); - const count = result.count ?? (result.results ?? []).length; - dreamChecked = true; - const memGate = checkMemoryGate(count, config.dream); - - if (memGate.pass && acquireDreamLock(CONFIG_DIR)) { - dreamTriggered = true; - extra += "\n\n" + DREAM_PROTOCOL; - captureEvent("pi.dream.triggered", { memory_count: count }, telemetryCtx); - } - } catch { - // Transient error — retry next turn - } - } - } - return { systemPrompt: (event.systemPrompt ?? "") + "\n\n" + extra, }; }); - // ── agent_end: dream completion check ─────────────────────────────── - pi.on("agent_end", async (event) => { - if (!dreamTriggered) return; - - const messages = event.messages ?? []; - const hadWriteAction = messages.some((m) => { - if (m.role !== "assistant") return false; - const content = Array.isArray(m.content) ? m.content : []; - return content.some( - (block: any) => - block.type === "tool_use" && - block.name === "mem0_memory" && - ["add", "delete", "delete_all"].includes(block.input?.action), - ); - }); - - if (hadWriteAction) { - recordDreamCompletion(CONFIG_DIR); - captureEvent("pi.dream.completed", {}, telemetryCtx); - } - - releaseDreamLock(CONFIG_DIR); - dreamTriggered = false; - }); - - // ── session_shutdown: release dream lock if still held ────────────── + // ── session_shutdown ──────────────────────────────────────────────── pi.on("session_shutdown", async () => { captureEvent("pi.session.stop", {}, telemetryCtx); - if (dreamTriggered) { - releaseDreamLock(CONFIG_DIR); - dreamTriggered = false; - } }); } diff --git a/integrations/pi-agent-plugin/src/index.ts b/integrations/pi-agent-plugin/src/index.ts index 0da362d47..228ef3833 100644 --- a/integrations/pi-agent-plugin/src/index.ts +++ b/integrations/pi-agent-plugin/src/index.ts @@ -1,7 +1,6 @@ export type { Scope, Mem0Config, - DreamConfig, ScopeContext, CustomCategory, } from "./types.ts"; @@ -15,16 +14,6 @@ export { formatAge, formatMemoryCompact, formatMemoryList, groupByCategory } fro export { setupAutoCapture, extractConversation } from "./capture/index.ts"; -export { - incrementSessionCount, - checkCheapGates, - checkMemoryGate, - acquireDreamLock, - releaseDreamLock, - recordDreamCompletion, -} from "./dream/index.ts"; -export { DREAM_PROTOCOL } from "./dream/prompt.ts"; - export { MEMORY_POLICY } from "./prompt.ts"; export { registerCommands } from "./commands.ts"; diff --git a/integrations/pi-agent-plugin/src/memory/formatting.ts b/integrations/pi-agent-plugin/src/memory/formatting.ts index 5d6bd3366..e8f4c6461 100644 --- a/integrations/pi-agent-plugin/src/memory/formatting.ts +++ b/integrations/pi-agent-plugin/src/memory/formatting.ts @@ -1,43 +1,7 @@ -interface MemoryLike { - id: string; - memory?: string; - categories?: string[]; - createdAt?: Date | string; -} - -export function formatAge(date: Date | string): string { - const d = typeof date === "string" ? new Date(date) : date; - const ms = Date.now() - d.getTime(); - const minutes = Math.floor(ms / 60_000); - if (minutes < 60) return `${minutes}m ago`; - const hours = Math.floor(minutes / 60); - if (hours < 24) return `${hours}h ago`; - const days = Math.floor(hours / 24); - return `${days}d ago`; -} - -export function formatMemoryCompact(mem: MemoryLike): string { - const cat = mem.categories?.[0] ?? "uncategorized"; - const age = mem.createdAt ? ` (${formatAge(mem.createdAt)})` : ""; - return `[${cat}] ${mem.memory ?? "(empty)"}${age} [mem0:${mem.id}]`; -} - -export function formatMemoryList(memories: MemoryLike[]): string { - if (memories.length === 0) return "No memories found."; - return memories - .map((m, i) => `${i + 1}. ${formatMemoryCompact(m)}`) - .join("\n"); -} - -export function groupByCategory( - memories: MemoryLike[], -): Map { - const groups = new Map(); - for (const m of memories) { - const cat = m.categories?.[0] ?? "uncategorized"; - const list = groups.get(cat) ?? []; - list.push(m); - groups.set(cat, list); - } - return groups; -} +export { + formatAge, + formatMemoryCompact, + formatMemoryList, + groupByCategory, +} from "../../../agent-plugin-core/typescript/src/formatting.ts"; +export type { MemoryLike } from "../../../agent-plugin-core/typescript/src/formatting.ts"; diff --git a/integrations/pi-agent-plugin/src/memory/scoping.test.ts b/integrations/pi-agent-plugin/src/memory/scoping.test.ts index ee843a176..35229ee3c 100644 --- a/integrations/pi-agent-plugin/src/memory/scoping.test.ts +++ b/integrations/pi-agent-plugin/src/memory/scoping.test.ts @@ -63,8 +63,8 @@ describe("resolveSearchFilters", () => { expect(resolveSearchFilters("session", ctx)).toEqual({ user_id: "u1", app_id: "a1", run_id: "r1" }); }); - it("uses wildcard app_id for global scope", () => { - expect(resolveSearchFilters("global", ctx)).toEqual({ user_id: "u1", app_id: "*" }); + it("limits global scope to the configured user", () => { + expect(resolveSearchFilters("global", ctx)).toEqual({ user_id: "u1" }); }); }); diff --git a/integrations/pi-agent-plugin/src/memory/scoping.ts b/integrations/pi-agent-plugin/src/memory/scoping.ts index 8f5d2af44..3131ab57c 100644 --- a/integrations/pi-agent-plugin/src/memory/scoping.ts +++ b/integrations/pi-agent-plugin/src/memory/scoping.ts @@ -2,6 +2,10 @@ import * as path from "node:path"; import * as crypto from "node:crypto"; import { execFileSync } from "node:child_process"; import type { Scope, ScopeContext } from "../types.ts"; +import { + scopeAddParams, + scopeSearchFilters, +} from "../../../agent-plugin-core/typescript/src/scoping.ts"; export function detectAppId(cwd: string): string { try { @@ -26,26 +30,12 @@ export function resolveSearchFilters( scope: Scope, ctx: ScopeContext, ): Record { - switch (scope) { - case "project": - return { user_id: ctx.userId, app_id: ctx.appId }; - case "session": - return { user_id: ctx.userId, app_id: ctx.appId, run_id: ctx.runId }; - case "global": - return { user_id: ctx.userId, app_id: "*" }; - } + return scopeSearchFilters(scope, ctx); } export function resolveAddParams( scope: Scope, ctx: ScopeContext, ): Record { - switch (scope) { - case "project": - return { userId: ctx.userId, appId: ctx.appId }; - case "session": - return { userId: ctx.userId, appId: ctx.appId, runId: ctx.runId }; - case "global": - return { userId: ctx.userId }; - } + return scopeAddParams(scope, ctx); } diff --git a/integrations/pi-agent-plugin/src/memory/tools.ts b/integrations/pi-agent-plugin/src/memory/tools.ts index 0ab06c142..96d8e9b3e 100644 --- a/integrations/pi-agent-plugin/src/memory/tools.ts +++ b/integrations/pi-agent-plugin/src/memory/tools.ts @@ -1,3 +1,4 @@ +import { resolveToolScope } from "../../../agent-plugin-core/typescript/src/scoping.ts"; import type { ExtensionAPI } from "@earendil-works/pi-coding-agent"; import { Type } from "typebox"; import { StringEnum } from "@earendil-works/pi-ai"; @@ -17,6 +18,10 @@ interface MemoryResult { const MAX_OUTPUT_LINES = 200; const MAX_OUTPUT_BYTES = 50_000; +function normalizeMemoryId(id: string): string { + return id.replace(/^\[?mem0:([0-9a-f-]{36})\]?$/i, "$1"); +} + function truncateOutput(text: string): string { const lines = text.split("\n"); if (lines.length <= MAX_OUTPUT_LINES && text.length <= MAX_OUTPUT_BYTES) { @@ -50,7 +55,7 @@ export function buildToolExecute( defaultScope: Scope, ) { return async (params: ToolParams, signal?: AbortSignal) => { - const scope = params.scope ?? defaultScope; + const scope = resolveToolScope(params.scope, defaultScope); switch (params.action) { case "search": { @@ -96,18 +101,19 @@ export function buildToolExecute( if (signal?.aborted) throw new Error("Cancelled"); if (!params.memory_id) throw new Error("memory_id is required for update"); if (!params.content) throw new Error("content is required for update"); - const updateResult = await mem0.update(params.memory_id, { text: params.content }); + const memoryId = normalizeMemoryId(params.memory_id); + const updateResult = await mem0.update(memoryId, { text: params.content }); const res = updateResult as MemoryResult; return { content: [{ type: "text" as const, text: res.status ?? "Memory updated." }], - details: { memoryId: params.memory_id }, + details: { memoryId }, }; } case "delete": { if (signal?.aborted) throw new Error("Cancelled"); if (!params.memory_id) throw new Error("memory_id is required for delete"); - const result = await mem0.delete(params.memory_id); + const result = await mem0.delete(normalizeMemoryId(params.memory_id)); return { content: [{ type: "text" as const, text: result.message ?? "Memory deleted." }], details: {}, @@ -145,7 +151,7 @@ export function registerMemoryTool( 'For multi-part or comparative questions, run several searches with different phrasings and combine the results before answering -- one search is rarely enough', 'Use mem0_memory with action "add" to save important facts, preferences, goals, decisions, or lessons the user shares', 'Use mem0_memory with action "update" to modify an existing memory — requires memory_id and content. Preserves the memory ID', - "Always use the default project scope unless the user EXPLICITLY asks to search across all projects — only then use scope \"global\"", + "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\"", "Do NOT pass scope at all for normal queries — omitting it uses the project default automatically", ], parameters: Type.Object({ diff --git a/integrations/pi-agent-plugin/src/telemetry.ts b/integrations/pi-agent-plugin/src/telemetry.ts index f9c5eb568..fa98ddf18 100644 --- a/integrations/pi-agent-plugin/src/telemetry.ts +++ b/integrations/pi-agent-plugin/src/telemetry.ts @@ -1,240 +1,99 @@ -/** - * Plugin telemetry — anonymous usage tracking via PostHog. - * - * Sends fire-and-forget events to PostHog using native fetch(). - * Events are batched and flushed every 5 seconds or when the queue - * reaches 10 events, whichever comes first. - * - * Disable with: MEM0_TELEMETRY=false - */ - import { createHash, randomUUID } from "node:crypto"; import * as fs from "node:fs"; import * as path from "node:path"; + +import { createTelemetry } from "../../agent-plugin-core/typescript/src/telemetry.ts"; import { CONFIG_DIR } from "./config/index.ts"; -const POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX"; -const POSTHOG_HOST = "https://us.i.posthog.com/i/v0/e/"; - -const FLUSH_INTERVAL_MS = 5_000; -const FLUSH_THRESHOLD = 10; - -let eventQueue: Record[] = []; -let flushTimer: ReturnType | undefined; - -function _loadPluginVersion(): string { +const PLUGIN_VERSION = (() => { try { - const pkgUrl = new URL("../package.json", import.meta.url); - const pkg = JSON.parse(fs.readFileSync(pkgUrl, "utf-8")); - return pkg.version ?? "unknown"; + return JSON.parse(fs.readFileSync(new URL("../package.json", import.meta.url), "utf-8")).version; } catch { return "unknown"; } -} - -const PLUGIN_VERSION = _loadPluginVersion(); - -// ── Opt-out ────────────────────────────────────────────────────────────── - -function isTelemetryEnabled(): boolean { - try { - const val = process.env.MEM0_TELEMETRY; - if (val !== undefined) { - const s = val.toLowerCase(); - return s !== "false" && s !== "0" && s !== "no" && s !== "off"; - } - return true; - } catch { - return true; - } -} - -// ── Identity ───────────────────────────────────────────────────────────── - +})(); const TELEMETRY_ID_PATH = path.join(CONFIG_DIR, "mem0-telemetry-id.json"); -let _cachedAnonymousId: string | undefined; +let cachedAnonymousId: string | undefined; +let currentDistinctId = ""; +let identified = false; -function getOrCreateAnonymousId(): string { - if (_cachedAnonymousId) return _cachedAnonymousId; +function anonymousId(): string { + if (cachedAnonymousId) return cachedAnonymousId; try { - if (fs.existsSync(TELEMETRY_ID_PATH)) { - const data = JSON.parse(fs.readFileSync(TELEMETRY_ID_PATH, "utf-8")); - if (data.anonymousId) { - _cachedAnonymousId = data.anonymousId; - return _cachedAnonymousId!; - } - } - } catch { /* ignore */ } - - const newId = `pi-mem0-anon-${randomUUID().replace(/-/g, "")}`; + const stored = JSON.parse(fs.readFileSync(TELEMETRY_ID_PATH, "utf-8")).anonymousId; + if (typeof stored === "string" && stored) return (cachedAnonymousId = stored); + } catch { + // First run or unreadable identity file. + } + const created = `pi-mem0-anon-${randomUUID().replace(/-/g, "")}`; try { fs.mkdirSync(CONFIG_DIR, { recursive: true }); - fs.writeFileSync(TELEMETRY_ID_PATH, JSON.stringify({ anonymousId: newId }), "utf-8"); - } catch { /* ignore */ } - _cachedAnonymousId = newId; - return newId; -} - -function getDistinctId(apiKey?: string): string { - if (apiKey) { - return createHash("sha256").update(apiKey).digest("hex"); - } - return getOrCreateAnonymousId(); -} - -let _identifyDone = false; - -function maybeBuildIdentifyEvent(distinctId: string): Record | null { - if (_identifyDone) return null; - if (!distinctId || distinctId.startsWith("pi-mem0-anon-")) return null; - try { - if (!fs.existsSync(TELEMETRY_ID_PATH)) { - _identifyDone = true; - return null; - } - const data = JSON.parse(fs.readFileSync(TELEMETRY_ID_PATH, "utf-8")); - const storedAnon = data.anonymousId; - if (!storedAnon) { - _identifyDone = true; - return null; - } - const identifyEvent = { - event: "$identify", - distinct_id: distinctId, - properties: { $anon_distinct_id: storedAnon, $lib: "posthog-node" }, - }; - try { - fs.unlinkSync(TELEMETRY_ID_PATH); - } catch { /* ignore */ } - _identifyDone = true; - _cachedAnonymousId = undefined; - return identifyEvent; + fs.writeFileSync(TELEMETRY_ID_PATH, JSON.stringify({ anonymousId: created }), "utf-8"); } catch { - return null; + // An unwritable config directory must not break the plugin. + } + return (cachedAnonymousId = created); +} + +function distinctId(apiKey?: string): string { + return apiKey ? createHash("sha256").update(apiKey).digest("hex") : anonymousId(); +} + +function previousAnonymousId(id: string): string | undefined { + if (identified || id.startsWith("pi-mem0-anon-")) return undefined; + identified = true; + try { + const stored = JSON.parse(fs.readFileSync(TELEMETRY_ID_PATH, "utf-8")).anonymousId; + fs.unlinkSync(TELEMETRY_ID_PATH); + cachedAnonymousId = undefined; + return typeof stored === "string" && stored ? stored : undefined; + } catch { + return undefined; } } -// ── Flush machinery ────────────────────────────────────────────────────── - -function ensureFlushTimer(): void { - if (flushTimer) return; - flushTimer = setInterval(flushEvents, FLUSH_INTERVAL_MS); - if (typeof flushTimer === "object" && "unref" in flushTimer) { - flushTimer.unref(); - } -} - -let _exitHandlerInstalled = false; - -function ensureExitHandler(): void { - if (_exitHandlerInstalled) return; - _exitHandlerInstalled = true; - process.on("beforeExit", async () => { - if (eventQueue.length === 0) return; - const batch = eventQueue; - eventQueue = []; - const body = JSON.stringify({ api_key: POSTHOG_API_KEY, batch }); - try { - await fetch(POSTHOG_HOST, { - method: "POST", - headers: { - "Content-Type": "application/json", - "Content-Length": String(Buffer.byteLength(body)), - }, - body, - signal: AbortSignal.timeout(3_000), - }); - } catch { /* silently swallow */ } - }); -} - -function flushEvents(): void { - if (eventQueue.length === 0) return; - const batch = eventQueue; - eventQueue = []; - - const body = JSON.stringify({ api_key: POSTHOG_API_KEY, batch }); - fetch(POSTHOG_HOST, { - method: "POST", - headers: { - "Content-Type": "application/json", - "Content-Length": String(Buffer.byteLength(body)), - }, - body, - signal: AbortSignal.timeout(3_000), - }).catch(() => { /* silently swallow */ }); -} - -// ── Public API ─────────────────────────────────────────────────────────── +const telemetry = createTelemetry({ + host: "pi", + source: "PI_AGENT_PLUGIN", + version: PLUGIN_VERSION, + distinctId: () => currentDistinctId, +}); export function captureEvent( eventName: string, properties: Record = {}, - ctx?: { apiKey?: string }, + context?: { apiKey?: string }, ): void { - if (!isTelemetryEnabled()) return; - - try { - const distinctId = getDistinctId(ctx?.apiKey); - - const identifyEvent = maybeBuildIdentifyEvent(distinctId); - if (identifyEvent) { - eventQueue.push(identifyEvent); - } - - eventQueue.push({ - event: eventName, - distinct_id: distinctId, - properties: { - source: "PI_AGENT_PLUGIN", - language: "node", - plugin_version: PLUGIN_VERSION, - node_version: process.version, - os: process.platform, - $process_person_profile: false, - $lib: "posthog-node", - ...properties, - }, - }); - - ensureFlushTimer(); - ensureExitHandler(); - - if (eventQueue.length >= FLUSH_THRESHOLD) { - flushEvents(); - } - } catch { /* silently swallow */ } + currentDistinctId = distinctId(context?.apiKey); + const anonymous = previousAnonymousId(currentDistinctId); + if (anonymous) telemetry.capture("$identify", { $anon_distinct_id: anonymous }); + telemetry.capture(eventName, properties); } export function captureToolEvent( action: string, properties: Record = {}, - ctx?: { apiKey?: string }, + context?: { apiKey?: string }, ): void { - captureEvent("pi.tool.mem0_memory", { action, ...properties }, ctx); + captureEvent("pi.tool.mem0_memory", { action, ...properties }, context); } export function captureCommandEvent( command: string, properties: Record = {}, - ctx?: { apiKey?: string }, + context?: { apiKey?: string }, ): void { - captureEvent(`pi.command.${command}`, properties, ctx); + captureEvent(`pi.command.${command}`, properties, context); } -// ── Test helpers ───────────────────────────────────────────────────────── - export function _getEventQueue(): Record[] { - return eventQueue; + return telemetry.queueForTesting(); } export function _resetForTesting(): void { - eventQueue = []; - if (flushTimer) { - clearInterval(flushTimer); - flushTimer = undefined; - } - _cachedAnonymousId = undefined; - _identifyDone = false; + telemetry.resetForTesting(); + cachedAnonymousId = undefined; + currentDistinctId = ""; + identified = false; } diff --git a/integrations/pi-agent-plugin/src/types.ts b/integrations/pi-agent-plugin/src/types.ts index e23e80e4c..c2243cb37 100644 --- a/integrations/pi-agent-plugin/src/types.ts +++ b/integrations/pi-agent-plugin/src/types.ts @@ -1,13 +1,5 @@ export type Scope = "project" | "session" | "global"; -export interface DreamConfig { - enabled: boolean; - auto: boolean; - minHours: number; - minSessions: number; - minMemories: number; -} - export interface Mem0Config { apiKey: string; userId: string; @@ -15,18 +7,6 @@ export interface Mem0Config { defaultScope: Scope; contextInjection: boolean; searchThreshold: number; - dream: DreamConfig; -} - -export interface DreamState { - lastConsolidatedAt: number; - sessionsSince: number; - lastSessionId: string | null; -} - -export interface DreamLock { - pid: number; - startedAt: number; } export interface ScopeContext { diff --git a/integrations/pi-agent-plugin/tests/capture.test.ts b/integrations/pi-agent-plugin/tests/capture.test.ts index 6f07b3035..5651909be 100644 --- a/integrations/pi-agent-plugin/tests/capture.test.ts +++ b/integrations/pi-agent-plugin/tests/capture.test.ts @@ -59,4 +59,10 @@ describe("extractConversation", () => { it("returns empty array for empty input", () => { expect(extractConversation([])).toEqual([]); }); + + it("redacts credentials before automatic capture", () => { + expect(extractConversation([ + { role: "user", content: "api_key=do-not-store-this" }, + ])).toEqual([{ role: "user", content: "api_key=[REDACTED]" }]); + }); }); diff --git a/integrations/pi-agent-plugin/tests/config.test.ts b/integrations/pi-agent-plugin/tests/config.test.ts index 434210938..524cbd2ef 100644 --- a/integrations/pi-agent-plugin/tests/config.test.ts +++ b/integrations/pi-agent-plugin/tests/config.test.ts @@ -43,8 +43,6 @@ describe("loadConfig", () => { const config = loadConfig(); expect(config.apiKey).toBe("m0-file-key"); expect(config.userId).toBe("file-user"); - expect(config.dream.enabled).toBe(true); - expect(config.dream.minHours).toBe(24); }); it("env vars override config file", () => { diff --git a/integrations/pi-agent-plugin/tests/dream.test.ts b/integrations/pi-agent-plugin/tests/dream.test.ts deleted file mode 100644 index 42c40223c..000000000 --- a/integrations/pi-agent-plugin/tests/dream.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; -import * as fs from "node:fs"; -import { checkCheapGates, checkMemoryGate } from "../src/dream/index.ts"; - -vi.mock("node:fs"); - -const STATE_DIR = "/tmp/test-mem0-dream"; - -describe("checkCheapGates", () => { - beforeEach(() => { - vi.mocked(fs.mkdirSync).mockReturnValue(undefined); - }); - - afterEach(() => { - vi.restoreAllMocks(); - }); - - it("blocks when no state file exists (zero sessions)", () => { - vi.mocked(fs.readFileSync).mockImplementation(() => { throw new Error("ENOENT"); }); - const result = checkCheapGates(STATE_DIR, {}); - expect(result.proceed).toBe(false); - expect(result.reason).toContain("sessions"); - }); - - it("blocks when consolidated recently", () => { - vi.mocked(fs.readFileSync).mockReturnValue( - JSON.stringify({ lastConsolidatedAt: Date.now() - 3_600_000, sessionsSince: 10, lastSessionId: null }) - ); - const result = checkCheapGates(STATE_DIR, {}); - expect(result.proceed).toBe(false); - expect(result.reason).toContain("time"); - }); - - it("blocks when not enough sessions", () => { - vi.mocked(fs.readFileSync).mockReturnValue( - JSON.stringify({ lastConsolidatedAt: Date.now() - 48 * 3_600_000, sessionsSince: 2, lastSessionId: null }) - ); - const result = checkCheapGates(STATE_DIR, {}); - expect(result.proceed).toBe(false); - expect(result.reason).toContain("sessions"); - }); - - it("proceeds when both gates pass", () => { - vi.mocked(fs.readFileSync).mockReturnValue( - JSON.stringify({ lastConsolidatedAt: Date.now() - 48 * 3_600_000, sessionsSince: 10, lastSessionId: null }) - ); - expect(checkCheapGates(STATE_DIR, {}).proceed).toBe(true); - }); -}); - -describe("checkMemoryGate", () => { - it("blocks when too few memories", () => { - expect(checkMemoryGate(5, {}).pass).toBe(false); - }); - - it("passes when enough memories", () => { - expect(checkMemoryGate(25, {}).pass).toBe(true); - }); -}); diff --git a/integrations/pi-agent-plugin/tests/scoping.test.ts b/integrations/pi-agent-plugin/tests/scoping.test.ts index 9cf468216..d5b34a531 100644 --- a/integrations/pi-agent-plugin/tests/scoping.test.ts +++ b/integrations/pi-agent-plugin/tests/scoping.test.ts @@ -21,9 +21,9 @@ describe("resolveSearchFilters", () => { }); }); - it("global scope returns user_id with app_id wildcard", () => { + it("global scope returns user_id only", () => { expect(resolveSearchFilters("global", ctx)).toEqual({ - user_id: "kartik", app_id: "*", + user_id: "kartik", }); }); }); diff --git a/integrations/pi-agent-plugin/tests/tools.test.ts b/integrations/pi-agent-plugin/tests/tools.test.ts index f9b753ef5..5ea892d81 100644 --- a/integrations/pi-agent-plugin/tests/tools.test.ts +++ b/integrations/pi-agent-plugin/tests/tools.test.ts @@ -6,6 +6,7 @@ const mockMem0 = { search: vi.fn(), add: vi.fn(), getAll: vi.fn(), + update: vi.fn(), delete: vi.fn(), deleteAll: vi.fn(), }; @@ -38,11 +39,13 @@ describe("buildToolExecute", () => { expect(call[1].customCategories.length).toBe(10); }); - it("search with scope=global filters by user_id with app_id wildcard", async () => { + it("search uses global scope only after the user selects it", async () => { mockMem0.search.mockResolvedValue({ results: [] }); - await execute({ action: "search", query: "preferences", scope: "global" }); + await expect(execute({ action: "search", query: "preferences", scope: "global" })).rejects.toThrow(/Select global/); + const globalExecute = buildToolExecute(mockMem0 as any, scopeCtx, "global"); + await globalExecute({ action: "search", query: "preferences", scope: "global" }); expect(mockMem0.search).toHaveBeenCalledWith("preferences", { - filters: { user_id: "testuser", app_id: "*" }, + filters: { user_id: "testuser" }, }); }); @@ -58,4 +61,19 @@ describe("buildToolExecute", () => { await execute({ action: "delete", memory_id: fullId }); expect(mockMem0.delete).toHaveBeenCalledWith(fullId); }); + + it("write actions accept the citation ID returned by search", async () => { + mockMem0.update.mockResolvedValue({ status: "updated" }); + mockMem0.delete.mockResolvedValue({ message: "deleted" }); + await execute({ + action: "update", + memory_id: "[mem0:956e3d68-b420-4e07-a4e3-3019e7cebe6f]", + content: "updated memory", + }); + await execute({ action: "delete", memory_id: "mem0:956e3d68-b420-4e07-a4e3-3019e7cebe6f" }); + expect(mockMem0.update).toHaveBeenLastCalledWith("956e3d68-b420-4e07-a4e3-3019e7cebe6f", { + text: "updated memory", + }); + expect(mockMem0.delete).toHaveBeenLastCalledWith("956e3d68-b420-4e07-a4e3-3019e7cebe6f"); + }); }); diff --git a/integrations/pi-agent-plugin/tsconfig.json b/integrations/pi-agent-plugin/tsconfig.json index 8808fe6ed..8aa40a76d 100644 --- a/integrations/pi-agent-plugin/tsconfig.json +++ b/integrations/pi-agent-plugin/tsconfig.json @@ -8,7 +8,7 @@ "declarationMap": true, "sourceMap": true, "outDir": "dist", - "rootDir": "src", + "rootDir": "..", "strict": true, "types": ["node"], "esModuleInterop": true, diff --git a/marketplace.json b/marketplace.json index b1f765015..eea48e2af 100644 --- a/marketplace.json +++ b/marketplace.json @@ -13,7 +13,7 @@ }, "category": "Productivity", "description": "Cross-session memory and token savings for coding agents.", - "version": "0.3.0" + "version": "0.3.1" } ] } diff --git a/skills/mem0-integrate/SKILL.md b/skills/mem0-integrate/SKILL.md index 4b651d69a..34dfd284f 100644 --- a/skills/mem0-integrate/SKILL.md +++ b/skills/mem0-integrate/SKILL.md @@ -46,7 +46,7 @@ standalone `SKILL.md` with triggers, examples, and version-pinned code. - SDK (Python + TS, Platform + OSS): https://raw.githubusercontent.com/mem0ai/mem0/main/skills/mem0/SKILL.md - CLI: https://raw.githubusercontent.com/mem0ai/mem0/main/skills/mem0-cli/SKILL.md - Vercel AI SDK: https://raw.githubusercontent.com/mem0ai/mem0/main/skills/mem0-vercel-ai-sdk/SKILL.md -- Editor/MCP plugin glue (9 MCP tools): https://github.com/mem0ai/mem0/tree/main/integrations/mem0-plugin +- Portable editor/MCP plugin: https://github.com/mem0ai/mem0/tree/main/integrations/mem0-agent-plugin ### SDK source (read when docs are ambiguous) Public repo. Cross-check against the `mem0_tested_versions` range in this @@ -109,7 +109,7 @@ the target stack. If yes, delegate — copy its call-site pattern into |---|---|---| | `@ai-sdk/*` + `ai` in `package.json` | `skills/mem0-vercel-ai-sdk` | Integration is via `createMem0` provider wrapper, not raw `MemoryClient`. | | CLI-only repo (Typer, Commander, Click, Cobra) with no LLM call sites | `skills/mem0-cli` | Call sites are command handlers, not model wrappers. Consider whether mem0 actually fits first. | -| Target is an MCP client / editor config (Claude Code, Cursor, Codex settings) | `integrations/mem0-plugin` | Wire via MCP server URL + hooks; no SDK code usually needed. | +| Target is an MCP client / editor config (Claude Code, Cursor, Codex settings) | `integrations/mem0-agent-plugin` | Wire via MCP server URL + hooks; no SDK code usually needed. | | Any other Python or TS repo with an LLM call site | `skills/mem0` | Default SDK integration path. | Record the delegated skill's raw URL in `plan.md` under a From 02f7a9b2c4fe38dedb96631e48c85c74ad58b605 Mon Sep 17 00:00:00 2001 From: Kartik Date: Wed, 9 Sep 2026 01:03:26 +0530 Subject: [PATCH 02/61] docs: align agent plugin guides with shared runtime behavior (#7269) --- docs/changelog/sdk.mdx | 7 ++++--- docs/integrations/antigravity.mdx | 8 +++++++- docs/integrations/claude-code.mdx | 12 ++++++------ docs/integrations/codex.mdx | 22 ++++++++++++++-------- docs/integrations/cursor.mdx | 8 +++++++- docs/integrations/deepseek-plugin.mdx | 4 ++-- docs/integrations/kimi.mdx | 12 +++++++++--- docs/integrations/openclaw.mdx | 6 +++--- docs/integrations/opencode.mdx | 6 ++++-- docs/integrations/pi-agent.mdx | 12 ++++++------ docs/llms.txt | 8 ++++---- integrations/agent-plugin-core/README.md | 22 ++++++++++++++++++++++ integrations/claude-code-plugin/README.md | 18 +++++++++++------- integrations/deepseek-plugin/README.md | 16 +++++++++++++--- integrations/openclaw/README.md | 14 +++++++++----- integrations/opencode-plugin/README.md | 20 ++++++++++++++------ integrations/pi-agent-plugin/README.md | 14 +++++++++++--- 17 files changed, 146 insertions(+), 63 deletions(-) diff --git a/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdx index 454f86964..fff64b9e0 100644 --- a/docs/changelog/sdk.mdx +++ b/docs/changelog/sdk.mdx @@ -2066,7 +2066,7 @@ A full-featured command-line interface for Mem0, available in both Python and No - Consolidated the coding-agent integrations into `integrations/agent-plugin-core/`: one Python runtime, one TypeScript utility library, and six canonical Python-plugin skill templates. Native adapters retain each host's event contracts and capabilities. - Python plugins ship generated, self-contained `core/` and `skills/` directories. Builds validate portable schemas and skills, parse native JSON, and reject generated-file drift, missing files, stale generated files, and symlinks. TypeScript packages bundle the shared source into their distributable JavaScript and verify their entry points. - Replaced the old `integrations/mem0-plugin/` layout with native host directories and one portable `integrations/mem0-agent-plugin/` package. Updated marketplace paths, installation guides, and integration-skill links. OpenCode now lives in `integrations/opencode-plugin/`. -- Native Python plugins expose one local, read-only `search_memories` MCP tool and six skills: search, remember, forget, status, pause, and resume. The shared search tool no longer accepts `run_id`; session IDs remain internal metadata. This local tool is separate from the hosted Mem0 MCP server's tool set. +- Native Python plugins expose one local, read-only `search_memories` MCP tool and six skills: search, remember, forget, status, pause, and resume. The shared search tool accepts optional `run_id` with every scope (`repo`, `dir`, and `mine`) to recall memories from a specific coding-agent session. Omitting it searches across sessions. This local tool is separate from the hosted Mem0 MCP server's tool set. **Fixes:** - Hooks, controls, MCP servers, and detached workers use the same host-specific data directory. Detached workers retain the host identity and telemetry source; `--plugin-data-dir` reaches the shared resolver. @@ -2380,7 +2380,7 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex **Fixes:** - Session-end extraction no longer appends a final answer already captured from the transcript while an earlier extraction was running. - Existing repository memories remain searchable after the shared-ID change; explicit shared-memory deletion also covers the legacy ID. Background workers and control skills consistently use Claude's data directory. -- Receives the shared JSON-secret redaction and nested telemetry filtering fixes. The local search tool exposes query, result count, category, and scope without asking the agent for a session ID. +- Receives the shared JSON-secret redaction and nested telemetry filtering fixes. The local search tool exposes query, result count, category, scope, and optional `run_id` for session-specific recall across all scopes. [#7203](https://github.com/mem0ai/mem0/pull/7203) @@ -2435,7 +2435,7 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex **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 claim automatic lifecycle capture or host-specific subagent isolation. +- 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) @@ -2680,6 +2680,7 @@ Existing memories written by the previous versions are not rewritten. If your me **Fixes:** - `openclaw mem0 status` handles an unconfigured installation without crashing and directs users to setup. +- Removed OpenClaw's separate 2,000-character extraction cutoff. Selected user and assistant messages retain their full redacted text; recent-message selection, earlier summary selection, and noise filtering still apply. - Telemetry removes sensitive properties recursively and uses the shared failure-safe delivery implementation. [#7203](https://github.com/mem0ai/mem0/pull/7203) diff --git a/docs/integrations/antigravity.mdx b/docs/integrations/antigravity.mdx index d9229bf2f..ef4aca8c6 100644 --- a/docs/integrations/antigravity.mdx +++ b/docs/integrations/antigravity.mdx @@ -78,7 +78,7 @@ The plugin translates Antigravity events into the shared Mem0 capture lifecycle. |------|-------|-------------| | **Invocation** | `PreInvocation` | Initializes the first invocation and recovers pending capture | | **Post-tool** | `PostToolUse` | Records useful tool results and failures | -| **Stop** | `Stop` | Captures the completed exchange for a later session | +| **Stop** | `Stop` | Reads completed transcript messages and starts a background flush | Recall is explicit through `search_memories` and the search skill. The current Antigravity adapter does not inject query-specific memory during `PreInvocation` because that event does not include the user's prompt. @@ -106,6 +106,12 @@ MEM0_CWD="$PWD" agy The adapter uses `MEM0_CWD` only when Antigravity omits the workspace. If neither value is available, it skips recall and capture instead of writing memories under an incorrect repository scope. +## Search and capture + +The local `search_memories` tool accepts `query`, `top_k`, `category`, `scope` (`repo`, `dir`, or `mine`), and optional `run_id` with every scope. Use a known session ID to recall memories saved in that session; omit it to search across sessions. See [search scopes](/integrations/claude-code#search-scope) for the shared Python search contract, including legacy repository memory compatibility. + +Captured prompts and responses retain their full redacted text without a per-message character cutoff. Large extraction inputs are split across requests without dropping message text; recall output and tool-result previews have separate limits. + ## Troubleshooting - **No tools appearing**: Restart your Antigravity session after installation diff --git a/docs/integrations/claude-code.mdx b/docs/integrations/claude-code.mdx index e185758dc..829489386 100644 --- a/docs/integrations/claude-code.mdx +++ b/docs/integrations/claude-code.mdx @@ -42,14 +42,14 @@ claude plugin uninstall mem0@mem0-plugins # uninstall the plugin (keeps the Once installed, memory works without any action from you: -- **Capture** happens in the background as you work. Hooks save user messages, Claude's answers, changed files, and test/build results locally. Nothing calls a model or slows your session. -- **Recall** happens automatically before Claude's first response in a new session. The plugin searches your memories with your prompt and injects up to five relevant ones. +- **Capture** happens in the background as you work. Hooks save user messages, Claude's answers, changed files, and test/build results locally. Capture records evidence locally; memory extraction runs through Mem0 in a background worker. +- **Recall** happens automatically before Claude's first response in a new session. If the first prompt has at least 20 characters, the plugin searches with that prompt and injects up to five relevant memories. For shorter prompts or later questions, use explicit search. ### Commands | Command | What it does | | --- | --- | -| `/mem0:search` | Search memories from earlier sessions. Supports `--top-k `, `--category `, and `--scope `. | +| `/mem0:search` | Search memories from earlier sessions. Supports `--top-k `, `--category `, `--scope `, and `--run-id `. | | `/mem0:status` | Check if memory is working: config, capture state, pending flushes, API key validity. | | `/mem0:forget` | Delete your memories for this repo (shared project memory stays unless you pass `--include-project-memory`). | | `/mem0:pause` | Pause memory capture. | @@ -60,7 +60,7 @@ Categories for `--category`: `project_knowledge`, `decisions_and_constraints`, ` ### Search tool -After the automatic first-prompt search, Claude can also call `search_memories` with a specific question, and you can run `/mem0:search` yourself. Explicit searches return up to 3 results by default (configurable to 20). All results are capped at 4,000 characters. +After the automatic first-prompt search, Claude can also call `search_memories` with a specific question, and you can run `/mem0:search` yourself. Explicit searches return up to 3 results by default (configurable to 20). The combined search output is capped at 4,000 characters by default, configurable with `max_context_chars`. This recall limit does not truncate captured messages sent for extraction. ### Sidekick agent @@ -80,7 +80,7 @@ At startup, Sidekick receives the memories already recalled for its parent sessi The plugin follows a simple cycle: capture during a session, extract memories in the background, recall in the next session. - Sequence diagram: session start triggers first-prompt search, hooks capture activity during the session, a background worker extracts memories after every five exchanges or on idle/exit, and the next session recalls them. + Sequence diagram: the first user prompt triggers search, hooks capture activity during the session, a background worker extracts memories after every five exchanges or on idle/exit, and the next session recalls them. **Step by step:** @@ -153,7 +153,7 @@ Breaking update. Your memories carry over, most local config does not. - **Commands replaced.** Old commands replaced by `/mem0:search`, `/mem0:status`, `/mem0:forget`, `/mem0:pause`, `/mem0:resume`, `/mem0:remember`. - **MCP server replaced.** Nine read/write tools replaced by the single read-only `search_memories` tool. - **Local config ignored.** `~/.mem0/settings.json` and per-project `mem0.md` files are no longer read. -- **Old memories searchable, not by category.** Normal search finds pre-upgrade memories, but category filters do not. +- **Old memories remain searchable.** Pre-upgrade memories may use different categories. Omit category filters if an older memory is missing from the results. ```bash claude plugin marketplace update mem0-plugins diff --git a/docs/integrations/codex.mdx b/docs/integrations/codex.mdx index 33f09b16c..8bd68627c 100644 --- a/docs/integrations/codex.mdx +++ b/docs/integrations/codex.mdx @@ -3,7 +3,7 @@ title: Codex description: "Add persistent memory to OpenAI Codex with automatic capture, automatic recall, a search tool, and six memory skills." --- -Add persistent memory to [**OpenAI Codex**](https://openai.com/index/codex/) with the Mem0 plugin. Codex forgets everything between tasks. This plugin fixes that by connecting to Mem0's cloud memory layer via MCP, automatically capturing learnings at key lifecycle points, and retrieving relevant context before every response. +Add persistent memory to [**OpenAI Codex**](https://openai.com/index/codex/) with the Mem0 plugin. Codex forgets everything between tasks. This plugin fixes that by connecting to Mem0's cloud memory layer via MCP, automatically capturing learnings at key lifecycle points, and retrieving relevant context on the first prompt of a session. Codex can use the search tool for recall later in the session. Current plugin version: `0.3.1`. @@ -79,7 +79,7 @@ bearer_token_env_var = "MEM0_API_KEY" Make sure `MEM0_API_KEY` is exported in the shell you launch Codex from, then restart Codex. -This gives you the MCP tools but not the lifecycle hooks or SDK skill. +This gives you the hosted MCP tools but not the plugin's lifecycle hooks or six memory skills. ### Managing the Plugin @@ -115,7 +115,7 @@ Lifecycle hooks that shell out to local scripts (Option A) are not applicable in | Native subagent memory lifecycle | Yes | No | | Memory skills | 6 | No | -Codex plugins cannot currently bundle a named custom agent. If you define project or user agents under `.codex/agents/` or `~/.codex/agents/`, the full Mem0 plugin gives every native subagent the parent turn's retrieved memory context and records its completed result. +Mem0's Codex package does not bundle a named custom agent. If you define project or user agents under `.codex/agents/` or `~/.codex/agents/`, the full Mem0 plugin gives every native subagent the parent turn's retrieved memory context and records its completed result. ## Direct MCP tools @@ -139,8 +139,8 @@ Option A registers the hooks with the plugin. No separate hook installer or glob | Hook | Event | What it does | |------|-------|-------------| -| **Session start** | `SessionStart` | Loads prior memories and displays status banner | -| **User prompt** | `UserPromptSubmit` | Searches relevant memories before each message | +| **Session start** | `SessionStart` | Initializes the project session and recovers pending capture | +| **User prompt** | `UserPromptSubmit` | Records each prompt; searches on the first prompt when it has at least 20 characters | | **Post-tool** | `PostToolUse` | Records useful tool outcomes for the completed exchange | | **Subagent start** | `SubagentStart` | Reuses the parent turn's retrieved memory context in the child | | **Subagent stop** | `SubagentStop` | Records the child transcript path and completed result | @@ -148,18 +148,18 @@ Option A registers the hooks with the plugin. No separate hook installer or glob | **Pre-compact** | `PreCompact` | Flushes pending capture before context compaction | | **Session end** | `SessionEnd` | Flushes any remaining capture in the background | -What you type is stored as yours. What Codex produces (session summaries and compaction summaries) is stored as the assistant's, so its suggestions never become your stated preferences. +What you type is stored as yours. Codex's captured responses are stored as the assistant's, so its suggestions never become your stated preferences. ## Example Workflow ```text # Task 1: Setting up a new service -You: Create a REST API for the notifications service using Express and TypeScript. +You: Create a REST API for the notifications service using Express and TypeScript. Prefer explicit error types over generic catch-all handlers. # Codex searches memories, finds your preferences from prior tasks. # Mem0 stores what you said as yours: # - Your preference: "Prefers explicit error types over generic catch-all" -# ...and what Codex did as the assistant's, in the session summary: +# ...and completed work reported by Codex as the assistant's: # - Decision: "Notifications service uses Express + TypeScript + Zod validation" # - Convention: "All API routes follow /api/v1/{resource} pattern" @@ -170,6 +170,12 @@ You: Add WebSocket support for real-time notification delivery. # Follows the same patterns established in the first task. ``` +## Search and capture + +The local `search_memories` tool accepts `query`, `top_k`, `category`, `scope` (`repo`, `dir`, or `mine`), and optional `run_id` with every scope. Use a known session ID to recall memories saved in that session; omit it to search across sessions. See [search scopes](/integrations/claude-code#search-scope) for the shared Python search contract, including legacy repository memory compatibility. + +Captured prompts and responses retain their full redacted text without a per-message character cutoff. Large extraction inputs are split across requests without dropping message text; recall output and tool-result previews have separate limits. + ## Troubleshooting - **"Connection failed"**: Verify `MEM0_API_KEY` is set: `echo $MEM0_API_KEY` diff --git a/docs/integrations/cursor.mdx b/docs/integrations/cursor.mdx index df54d27dc..3105dc14d 100644 --- a/docs/integrations/cursor.mdx +++ b/docs/integrations/cursor.mdx @@ -139,7 +139,7 @@ Cursor's `subagentStart` hook also cannot inject parent context. The bundled Sid ```text # Session 1: Debugging a performance issue -You: The API endpoint /users is taking 3 seconds. Help me optimize it. +You: The API endpoint /users is taking 3 seconds. Help me optimize it. Prefer query-level fixes over caching. # Cursor agent searches memories, proceeds with investigation. # Mem0 stores what you said as yours: @@ -155,6 +155,12 @@ You: The /orders endpoint is also slow, same pattern as before. # Immediately checks for N+1 queries and missing indexes. ``` +## Search and capture + +The local `search_memories` tool accepts `query`, `top_k`, `category`, `scope` (`repo`, `dir`, or `mine`), and optional `run_id` with every scope. Use a known session ID to recall memories saved in that session; omit it to search across sessions. See [search scopes](/integrations/claude-code#search-scope) for the shared Python search contract, including legacy repository memory compatibility. + +Captured prompts and responses retain their full redacted text without a per-message character cutoff. Large extraction inputs are split across requests without dropping message text; recall output and tool-result previews have separate limits. + ## Troubleshooting - **"Connection failed"**: Verify `MEM0_API_KEY` is set: `echo $MEM0_API_KEY` diff --git a/docs/integrations/deepseek-plugin.mdx b/docs/integrations/deepseek-plugin.mdx index 1a9f98a6d..2e7cc5177 100644 --- a/docs/integrations/deepseek-plugin.mdx +++ b/docs/integrations/deepseek-plugin.mdx @@ -18,7 +18,7 @@ The plugin provides automatic memory plus two agent-callable tools: | `search_memory` | Recall facts from Mem0 relevant to a query | | `add_memory` | Store a fact in Mem0 for future sessions | -Unlike file-based memory plugins, Mem0 is a managed backend: server-side extraction, semantic dedup, and conflict resolution, with the same memory reusable across every agent you connect. +Unlike file-based memory plugins, Mem0 is a managed backend: server-side extraction, semantic dedup, and conflict resolution, with memories reusable by integrations that use compatible user identities and search filters. ## How it works @@ -108,7 +108,7 @@ For a Mem0 Platform on-prem or dedicated deployment, point `config.host` at that | `autoRecall` | no | `true` | Recall relevant memory before model requests | | `autoCapture` | no | `true` | Store completed human and assistant turns | -Both tools also accept optional per-call `userId`, `agentId`, and `runId` params so a single install can partition memory by entity, agent, or session; when omitted they fall back to the configured `userId`. +Both tools also accept optional per-call `userId`, `agentId`, and `runId` params so a single install can partition memory by entity, agent, or session; `userId` defaults to the configured user, while `agentId` and `runId` are omitted unless supplied. Automatic recall and capture use the configured user without an agent, repository, or session filter. Automatic capture preserves full redacted user and assistant message text without a per-message character cutoff. ## Telemetry diff --git a/docs/integrations/kimi.mdx b/docs/integrations/kimi.mdx index 9b66d7603..ef7058ed5 100644 --- a/docs/integrations/kimi.mdx +++ b/docs/integrations/kimi.mdx @@ -38,7 +38,7 @@ Run `/plugins info mem0` to confirm that the plugin, MCP server, skills, hooks, ## What you get - **Automatic capture:** Kimi records completed exchanges locally and flushes durable project knowledge to Mem0 in the background. -- **Automatic recall:** Relevant memories are added before Kimi answers the first prompt in a session. +- **Automatic recall:** Relevant memories are added before Kimi answers the first prompt in a session, if that prompt has at least 20 characters. - **Explicit search:** Kimi can call `search_memories` when it needs a more specific answer. - **Six memory skills:** Search, status, remember, forget, pause, and resume use the same memory behavior as the other Mem0 coding-agent plugins. - **Project scoping:** Memories stay attached to the repository, with separate personal and shared project lanes. @@ -52,8 +52,8 @@ Kimi's native lifecycle events are translated into the shared Mem0 memory lifecy | Kimi event | What Mem0 does | | --- | --- | -| `SessionStart` | Loads recent project context | -| `UserPromptSubmit` | Searches for relevant memories before the response | +| `SessionStart` | Initializes the project session and recovers pending capture | +| `UserPromptSubmit` | Records each prompt; searches on the first prompt when it has at least 20 characters | | `PostToolUse` / `PostToolUseFailure` | Records useful tool results and failures | | `Stop` | Captures the completed exchange | | `PreCompact` / `SessionEnd` | Flushes pending capture in the background | @@ -87,6 +87,12 @@ Kimi should return `ORCHID-9274` from memory. Run `/reload` or start a new session after enabling, disabling, or reinstalling the plugin. +## Search and capture + +The local `search_memories` tool accepts `query`, `top_k`, `category`, `scope` (`repo`, `dir`, or `mine`), and optional `run_id` with every scope. Use a known session ID to recall memories saved in that session; omit it to search across sessions. See [search scopes](/integrations/claude-code#search-scope) for the shared Python search contract, including legacy repository memory compatibility. + +Captured prompts and responses retain their full redacted text without a per-message character cutoff. Large extraction inputs are split across requests without dropping message text; recall output and tool-result previews have separate limits. + ## Troubleshooting | Problem | Fix | diff --git a/docs/integrations/openclaw.mdx b/docs/integrations/openclaw.mdx index 501900de6..7ee02e2b1 100644 --- a/docs/integrations/openclaw.mdx +++ b/docs/integrations/openclaw.mdx @@ -343,8 +343,8 @@ openclaw mem0 status --json |-----|------|---------|-------------| | `mode` | `"platform"` \| `"open-source"` | `"platform"` | Which backend to use | | `userId` | `string` | OS username | Scope memories per user | -| `autoRecall` | `boolean` | `true` | Inject memories before each turn. Ignored when `skills` is configured. | -| `autoCapture` | `boolean` | `true` | Store facts after each turn. Ignored when `skills` is configured. | +| `autoRecall` | `boolean` | `true` | Inject memories before each turn, including when skills mode is configured. | +| `autoCapture` | `boolean` | `true` | Store facts after each turn, including when skills mode is configured. | | `topK` | `number` | `5` | Max memories per recall | | `searchThreshold` | `number` | `0.3` | Min similarity (0–1) | @@ -443,7 +443,7 @@ If `openclaw plugins update` fails: ### Auto-Capture and Auto-Recall -Auto-capture and auto-recall are **enabled by default**. When skills mode is configured (the default after `openclaw mem0 init`), these are ignored in favor of the skills-based triage and recall protocol. +Auto-capture and auto-recall are **enabled by default**. They also run when skills mode is configured (the default after `openclaw mem0 init`). Set `autoRecall` or `autoCapture` to `false` to disable the corresponding automatic hook while using skills. To disable either: diff --git a/docs/integrations/opencode.mdx b/docs/integrations/opencode.mdx index 6c6ff5470..57412841e 100644 --- a/docs/integrations/opencode.mdx +++ b/docs/integrations/opencode.mdx @@ -113,13 +113,15 @@ The plugin uses the [mem0ai](https://www.npmjs.com/package/mem0ai) TypeScript SD | OpenCode Event | Hook | What happens | |----------------|------|-------------| | `config` | **Config** | Registers the `/mem0-*` slash commands (`config.command`) and adds the plugin's own `opencode-skills/` dir to OpenCode's `skills.paths` for in-place skill discovery (no copying) | -| `chat.message` | **Chat message** | Searches prior memories on session start, searches relevant memories before each prompt, auto-captures learnings periodically | +| `chat.message` | **Chat message** | Searches prior memories on session start, searches relevant memories before each prompt, sends every third qualifying user prompt for extraction | | `tool.execute.before` | **Pre-tool** | Blocks MEMORY.md writes, steering them to the `add_memory` tool | | `tool.execute.after` | **Post-tool** | Scans Bash errors and pre-fetches related error memories | | `experimental.chat.messages.transform` | **Messages transform** | Injects memory context (session memories, search results, error lookups) into the prompt | -| `experimental.session.compacting` | **Compaction** | Stores session state memory, then injects prior memories into compaction context so nothing is lost | +| `experimental.session.compacting` | **Compaction** | Stores session state memory, then injects prior memories into compaction context | | `shell.env` | **Shell env** | Exports `MEM0_USER_ID`, `MEM0_APP_ID`, `MEM0_SESSION_ID`, and `MEM0_BRANCH` to all shell executions | +Automatic capture sends the selected user prompt with its full redacted text, without a per-message character cutoff. It does not capture every prompt or the full assistant transcript. These automatic writes use user and project scope, with the session ID in `metadata.session_id`; session-scoped tools use top-level `run_id`. A session-scoped search therefore does not include automatic writes that lack `run_id`. + ## Troubleshooting - **No tools appearing**: Restart OpenCode after installing diff --git a/docs/integrations/pi-agent.mdx b/docs/integrations/pi-agent.mdx index e743bc7a9..570fd3b20 100644 --- a/docs/integrations/pi-agent.mdx +++ b/docs/integrations/pi-agent.mdx @@ -11,7 +11,7 @@ Add persistent memory to [**Pi Agent**](https://pi.dev) with `@mem0/pi-agent-plu The plugin provides: 1. **Auto-capture**: Extracts durable facts from both user and assistant messages automatically -2. **Semantic recall**: Retrieves relevant memories via the `mem0_memory` tool before each response +2. **Semantic recall**: Automatically searches project memories before each agent turn; `mem0_memory` supports additional explicit searches 3. **Monorepo-aware scoping**: Uses git root for project detection, consistent across subdirectories 4. **Confirmation dialogs**: Destructive commands ask before acting via Pi's built-in UI 5. **6 skills + 6 commands**: Essential memory management from slash commands and agent-guided workflows @@ -117,10 +117,12 @@ Memories are scoped using Mem0's `user_id`, `app_id`, and `run_id` parameters: | Scope | Filters | Use Case | |-------|---------|----------| | `project` | user_id + app_id (git root) | **Default.** Project-specific knowledge: decisions, architecture, config | -| `session` | user_id + app_id + run_id | Ephemeral context for the current session only | +| `session` | user_id + app_id + run_id | Memories saved with the current session ID (no automatic expiration) | | `global` | user_id only | All memories across all your projects | -The `app_id` is auto-detected from the git repository root (`git rev-parse --show-toplevel`), so all subdirectories within a monorepo share the same memory pool. Falls back to the working directory name for non-git directories. The `run_id` is derived from Pi's session file path. +The `app_id` is auto-detected from the git repository root (`git rev-parse --show-toplevel`), so all subdirectories within a monorepo share the same memory pool. Falls back to the working directory name for non-git directories. The `run_id` is derived from Pi's session file path. Automatic recall and capture use project scope, regardless of `defaultScope`; automatic writes do not include `run_id`. Use session-scoped tools or commands to save and recall session-specific memories. Captured user and assistant message text is redacted without a per-message character cutoff. + +Global tool operations require `/mem0-scope global` or `defaultScope: "global"` in plugin configuration. A model-supplied `scope` argument cannot enable cross-project access on its own. Empty or wildcard user, project, and session identities are rejected. ## Confirmation Dialogs @@ -144,7 +146,7 @@ You: What do you know about my preferences? ## Troubleshooting - **"No API key found"**: Verify `MEM0_API_KEY` is set: `echo $MEM0_API_KEY`. If empty, add it to your shell profile (see Prerequisites) -- **Extension not loading**: Check Pi startup output for errors. Run `pi -e ./src/entry.ts` from the plugin directory for verbose output +- **Extension not loading**: Check Pi startup output for errors. For a source checkout, run `pnpm build`, then `pi -e ./dist/entry.js` from the plugin directory - **Memories not capturing**: Verify `autoCapture` is `true` (default). Check `/mem0-status` for connection health - **Wrong project detected**: The plugin uses the git repository root as `app_id`. If not in a git repo, it falls back to the working directory name. Run `/mem0-status` to see the detected project @@ -158,5 +160,3 @@ You: What do you know about my preferences?
- -Global tool operations require `/mem0-scope global` or `defaultScope: "global"` in plugin configuration. A model-supplied `scope` argument cannot enable cross-project access on its own. Empty or wildcard user, project, and session identities are rejected. diff --git a/docs/llms.txt b/docs/llms.txt index 0523c6ab9..0510d2bf2 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -267,7 +267,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st - [Strands Agents](https://docs.mem0.ai/integrations/strands) [Both]: Use when the user is on AWS Strands and wants a native MemoryStore. ### AI Coding Tools -- [Claude Code](https://docs.mem0.ai/integrations/claude-code) [Both]: Use when wiring memory into Claude Code. +- [Claude Code](https://docs.mem0.ai/integrations/claude-code) [Platform]: Use when wiring memory into Claude Code. - [Claude.ai](https://docs.mem0.ai/integrations/claude-ai) [Platform]: Use when connecting Mem0 to Claude.ai (the hosted web app) via a custom remote MCP connector, or when Claude's native memory seems to be crowding out mem0 tool calls. - [Cursor](https://docs.mem0.ai/integrations/cursor) [Platform]: Use when adding lifecycle capture, explicit memory recall, six skills, and a sidekick to Cursor. - [Codex](https://docs.mem0.ai/integrations/codex) [Platform]: Use when adding automatic capture and recall, six memory skills, and a search tool to OpenAI Codex. @@ -418,17 +418,17 @@ Each subdirectory is a Claude Code Skill (`SKILL.md` + supporting assets). Load Source: https://github.com/mem0ai/mem0/tree/main/integrations/claude-code-plugin -The self-contained Claude Code plugin lives in `integrations/claude-code-plugin/` (v0.3.0, installs as `mem0@mem0-plugins`). It captures evidence locally through lifecycle hooks, extracts memories in a detached background worker, and exposes a single local MCP tool, `search_memories`, plus six `/mem0:*` skills and the unchanged `mem0:sidekick` agent. Pure-stdlib Python, nothing to install. +The self-contained Claude Code plugin lives in `integrations/claude-code-plugin/` (v0.3.1, installs as `mem0@mem0-plugins`). It captures evidence locally through lifecycle hooks, extracts memories in a detached background worker, and exposes a single local MCP tool, `search_memories`, plus six `/mem0:*` skills and the unchanged `mem0:sidekick` agent. Pure-stdlib Python, nothing to install. ### Coding-Agent Plugin Sources Source: https://github.com/mem0ai/mem0/tree/main/integrations/agent-plugin-core -The `integrations/agent-plugin-core/` directory is the single source for shared Python and TypeScript memory behavior. Native plugins live in their own sibling directories, while `integrations/mem0-agent-plugin/` is the single portable Agent Plugins v1 package. TypeScript integrations reuse the core's lifecycle, formatting, identity, scoping, and telemetry utilities while keeping their public packages and native host APIs unchanged. +The `integrations/agent-plugin-core/` directory is the single source for shared Python and TypeScript memory behavior. Native plugins live in their own sibling directories, while `integrations/mem0-agent-plugin/` is the single portable Agent Plugins v1 package. The portable package provides search and skills but no automatic capture; its remember skill cannot save a new memory on its own. Shared Python search accepts optional `run_id` for session-specific recall in every scope. TypeScript integrations reuse the core's lifecycle, formatting, identity, scoping, and telemetry utilities while keeping their public packages and native host APIs unchanged. Editor-specific setup docs (already listed above under `## Integrations > AI Coding Tools`): -- `integrations/claude-code` [Both] +- `integrations/claude-code` [Platform] - `integrations/cursor` [Platform] - `integrations/codex` [Platform] - `integrations/kimi` [Platform] diff --git a/integrations/agent-plugin-core/README.md b/integrations/agent-plugin-core/README.md index b2bc6e5cc..8831bd71c 100644 --- a/integrations/agent-plugin-core/README.md +++ b/integrations/agent-plugin-core/README.md @@ -27,6 +27,28 @@ Claude Code remains the behavioral source of truth. Its sidekick stays at `claud TypeScript integrations (`openclaw`, `opencode-plugin`, `pi-agent-plugin`, and `deepseek-plugin`) import `typescript/src/` at build time. Their package builders include the shared implementation in their normal output; they do not carry checked-in copies. +## Shared memory behavior + +The six Python packages use the same `search_memories` MCP tool and six skill templates. Native hooks collect conversations and flush them to Mem0 in the background. The portable package uses the Agent Plugins v1 layout so compatible hosts can load its MCP server and skills. It has no lifecycle hooks or flush worker; its bundled `remember` skill assumes automatic capture and cannot save a memory on its own. + +Python search accepts `query`, `top_k`, `category`, `scope`, and optional `run_id`: + +| Scope | Memories searched | +| --- | --- | +| `repo` (default) | Shared repository memories and your personal memories in that repository | +| `dir` | Shared memories from the current directory and its children, plus your personal repository memories | +| `mine` | Your personal memories in that repository | + +`run_id` filters any scope to memories saved in a known coding-agent session. Omit it for recall across sessions; it does not attribute the search request to the current session. Native Python extraction writes include the session's `run_id`. + +New Git repository writes use a hashed remote identity for shared `agent_id`. Search and explicit shared-memory deletion include both that ID and the legacy unhashed ID under the same `app_id`. Legacy memories remain accessible, but their original ambiguity between matching owner/repository names on different Git hosts remains. + +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. + +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). + ## Build and verify From the repository root: diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index ae80910fc..b7d659250 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -4,6 +4,8 @@ Persistent cross-session memory for Claude Code, plus a Sonnet sidekick agent fo Claude Code forgets everything between sessions. This plugin fixes that: hooks capture session details locally, a background worker turns them into Mem0 memories, and Claude automatically gets the relevant ones back at the start of later sessions. +Current bundle version: `0.3.1`. + ## Prerequisites - Python 3.10+ and Git. @@ -45,15 +47,17 @@ claude --plugin-dir integrations/claude-code-plugin ### Memory -1. **Capture.** Hooks save the main agent's activity locally: user messages, Claude's answers, changed file paths, and short test/build results. No model calls, no blocking. Sidekick output is excluded. +1. **Capture.** Hooks save the main agent's activity locally: user messages, Claude's answers, changed file paths, and short test/build results. Capture does not call a model. Sidekick assignments and completed responses are recorded separately as supporting evidence. -2. **Flush.** After every five completed exchanges, a detached background worker sends that batch to Mem0. Large exchanges flush sooner. Ending or compacting the session flushes anything remaining. If idle, an auto-flush runs after five minutes (configurable with `MEM0_CODE_IDLE_FLUSH_SECONDS`). The worker survives Claude Code exiting. +2. **Flush.** After every five completed exchanges, a detached background worker sends that batch to Mem0. Large exchanges flush sooner. Ending or compacting the session flushes anything remaining. The session-end worker sends the conversation already collected by hooks without recording the final answer again. If idle, an auto-flush runs after five minutes (configurable with `MEM0_CODE_IDLE_FLUSH_SECONDS`). The worker survives Claude Code exiting. -3. **Extract.** Each flush sends a single `add` call with `agent_id` (the project identity), `user_id` (you), `app_id` (the repository), and `run_id` (the session). Mem0 classifies each extracted memory as either: +3. **Extract.** Each flush sends one or more `add` calls with `agent_id` (the project identity), `user_id` (you), `app_id` (the repository), and `run_id` (the session). Mem0 classifies each extracted memory as either: - **Shared project memory** (`agent_id`): one namespace per repo, scoped by `app_id`. Stores conventions, decisions, constraints, working commands, and failed commands with their fixes. Everyone on the repo reads and writes the same pool. Never carries a `user_id`. Directory information is stored in metadata for directory-scoped searches. - **Personal memory** (`user_id`): your preferred tools, style, habits, and anything you asked to be remembered. Scoped to the repo by `app_id`. Private to you. -4. **Recall.** On the next session's first prompt, the plugin searches automatically and supplies up to five relevant memories. No model is called to write the query. +4. **Recall.** On the next session's first prompt, if it has at least 20 characters, the plugin searches automatically and supplies up to five relevant memories. No model is called to write the query. + +Captured prompts and responses retain their full text after secret redaction. Oversized extraction input is split across requests without discarding message text. Search results and tool evidence still have separate size limits. After that first search, Claude can call `search_memories` with a specific question, and you can run `/mem0:search` yourself. Explicit searches return up to 3 results by default (configurable to 20), capped at 4,000 characters. @@ -88,7 +92,7 @@ By default the worktree branches from the repo's default branch. Set `worktree.b | Command | What it does | | --- | --- | -| `/mem0:search` | Search memories from earlier sessions. Accepts `--top-k `, `--category `, and `--scope `. | +| `/mem0:search` | Search memories from earlier sessions. Accepts `--top-k `, `--category `, `--scope `, and `--run-id `. | | `/mem0:status` | Check config, capture state, pending flushes, and API key validity. | | `/mem0:forget` | Delete your memories for this repo (shared project memory stays unless you pass `--include-project-memory`). | | `/mem0:pause` | Pause memory capture. | @@ -105,7 +109,7 @@ Categories for `--category`: `project_knowledge`, `decisions_and_constraints`, ` | `dir` | Project memory from the current directory (and children), plus your preferences | | `mine` | Your personal preferences only | -Set the default with the `search_scope` setting or `MEM0_CODE_SEARCH_SCOPE`. Search spans earlier sessions without a session ID; `run_id` remains internal metadata. +Set the default with the `search_scope` setting or `MEM0_CODE_SEARCH_SCOPE`. Pass optional `run_id` to `search_memories` (or `--run-id` to `/mem0:search`) with any scope to search memories saved in that session. Omit it to search across sessions. This filters the returned memories; it does not identify the session making the request. Use a known session ID. New Git repository memories use a hash of the remote identity in `agent_id`. Searches also include the previous unhashed ID under the same repository `app_id`, so shared memories remain available after upgrading. Older IDs retain their original limitation: matching owner/repository names on different Git hosts share that legacy namespace. Local folders keep their path-based namespaces. @@ -132,7 +136,7 @@ Local data lives in `${CLAUDE_PLUGIN_DATA}`: - `plugin-errors.log`: hook errors (no credentials) - `telemetry.jsonl` / `telemetry-identity.json`: anonymous usage events -Mem0 receives each block of user messages, Claude's answers, the sidekick's answer, and changed file paths. Complete files and general tool output stay on your machine. Values that look like credentials are redacted before anything is sent. +Mem0 receives captured user messages, Claude's answers, sidekick assignments and completed responses, and changed file paths. When a failed command is recorded, extraction can also include bounded command details and results. Complete files and general tool output stay on your machine. Values that look like credentials are redacted before anything is sent. ## Telemetry diff --git a/integrations/deepseek-plugin/README.md b/integrations/deepseek-plugin/README.md index fc6617c3f..2b55aaf50 100644 --- a/integrations/deepseek-plugin/README.md +++ b/integrations/deepseek-plugin/README.md @@ -11,7 +11,9 @@ It gives a Harness agent automatic long-term memory plus two explicit memory too | `search_memory` | Recall facts from Mem0 relevant to a query | | `add_memory` | Store a fact in Mem0 for future sessions | -Unlike the local/file-based memory plugins in the ecosystem, Mem0 is a managed backend: server-side extraction, semantic dedup and conflict resolution, and the same memory bank reusable across Harness, Claude Code, Codex, and other agents. +Unlike the local/file-based memory plugins in the ecosystem, Mem0 is a managed backend: server-side extraction, semantic dedup and conflict resolution, and memories that other agents can retrieve when their user and entity filters match. + +Current package version: `0.3.0`. ## How it works @@ -21,6 +23,8 @@ A Cordis plugin is a module exporting `apply(ctx, config)`. This one waits for t - `session/event` captures only completed turns from the durable event stream. - `ctx.tools.register(...)` exposes explicit search and add tools. +Completed human and assistant text is preserved after secret redaction, without the former 6,000-character per-message cutoff. Recall queries and displayed tool results retain separate size limits. These behaviors use [agent-plugin-core](../agent-plugin-core/README.md); this integration keeps its native tools and user-based scoping. + Cordis owns listener and tool cleanup when the plugin unmounts. Every automatic path is fail-open: a memory API failure does not block the agent. ``` @@ -70,6 +74,14 @@ For a Mem0 Platform on-prem or dedicated deployment, point `config.host` at that | `autoRecall` | no | `true` | Recall relevant memory before model requests | | `autoCapture` | no | `true` | Store completed human/assistant turns | +## Memory scope + +Automatic capture and recall use the configured `userId` across sessions. Automatic writes do not attach a repository ID or `runId`. + +Both `search_memory` and `add_memory` accept optional `agentId` and `runId`. On search, these narrow the returned memories; on add, they attach those identities to the stored memory. Pass a known `runId` to search memories explicitly saved with that session ID. This does not include automatically captured user-only memories or identify the session making the request. + +Per-call `userId` overrides are rejected unless the operator enables `allowUserOverride: true`. Automatic recall and capture always use the configured user. + ## Telemetry Writes are tagged `source="DEEPSEEK_HARNESS"` so Mem0's backend can attribute usage to this integration. For it to surface by name (rather than bucketing into `OTHERS`), `DEEPSEEK_HARNESS` must be present in the backend's `KNOWN_EVENT_SOURCES` allowlist, a one-line platform change matching the existing `ZAPIER` / `STRANDS` sources. @@ -79,5 +91,3 @@ The plugin also sends anonymous usage events (which tool ran, duration, result c ## Status Developer preview. Tracks the DeepSeek Harness v0.1 plugin API, which is young and moving. Harness capability packages are peer dependencies supplied by the host; this package pins matching release-candidate versions for local typechecking and tests. - -Per-call `userId` overrides are rejected unless the operator enables `allowUserOverride: true`. Automatic recall and capture always use the configured user. diff --git a/integrations/openclaw/README.md b/integrations/openclaw/README.md index 1d70dffa3..0d0224d9b 100644 --- a/integrations/openclaw/README.md +++ b/integrations/openclaw/README.md @@ -6,6 +6,8 @@ Your agent forgets everything between sessions. This plugin fixes that — it st By default, the plugin runs in **skills mode**: the agent controls what to remember (triage) and how to recall (recall). Skills mode, `autoRecall`, and `autoCapture` are all enabled by default during `openclaw mem0 init`. +Current package version: `1.1.0`. Shared redaction and lifecycle utilities come from [agent-plugin-core](../agent-plugin-core/README.md); OpenClaw keeps its own tools, skills, and memory scopes. + ## Requirements Check your OpenClaw version: @@ -218,12 +220,14 @@ When skills mode is active, the skills handle memory operations. `autoRecall` an ### Auto-Recall & Auto-Capture -When skills mode is not configured, the plugin uses `autoRecall` and `autoCapture` (both enabled by default): +The plugin also registers `autoRecall` and `autoCapture` when their flags are enabled (both default to `true`), including alongside skills mode: - **Auto-Recall** — Before the agent responds, the plugin searches Mem0 for relevant memories and injects them into context. - **Auto-Capture** — After the agent responds, the conversation is filtered through a noise-removal pipeline and sent to Mem0. New facts get stored, stale ones updated, duplicates merged. -Set `autoRecall: false` or `autoCapture: false` to disable individually. The agent can also use memory tools (`memory_add`, `memory_search`, etc.) explicitly regardless of these settings. +Automatic capture selects a recent-message window and earlier assistant summaries, removes injected context and noise, and redacts secrets. Selected message text is no longer cut off at 2,000 characters. This preserves full redacted text for selected messages, not every message in the session. Capture skips non-interactive triggers, subagent sessions, and turns that already used memory mutation tools. + +Set `autoRecall: false` or `autoCapture: false` to disable these automatic hooks individually. The agent can also use memory tools (`memory_add`, `memory_search`, etc.) explicitly regardless of these settings. ### Memory Scopes @@ -293,8 +297,8 @@ openclaw mem0 help --json # discover all comma | --- | ---- | ------- | ----------- | | `mode` | `"platform"` \| `"open-source"` | `"platform"` | Backend mode | | `userId` | `string` | OS username | User identifier. All memories scoped to this value. | -| `autoRecall` | `boolean` | `true` | Inject relevant memories before each turn. Ignored when `skills` is set. | -| `autoCapture` | `boolean` | `true` | Extract and store facts after each turn. Ignored when `skills` is set. | +| `autoRecall` | `boolean` | `true` | Inject relevant memories before each turn. Also runs when skills mode is enabled. | +| `autoCapture` | `boolean` | `true` | Extract and store facts after each turn. Also runs when skills mode is enabled. | | `topK` | `number` | `5` | Max memories returned per recall | | `searchThreshold` | `number` | `0.1` | Minimum similarity score (0-1) | @@ -357,7 +361,7 @@ To avoid plaintext credentials: In **skills mode** (default after `openclaw mem0 init`), the agent uses structured triage and recall protocols to decide what to store and recall. The built-in `session-memory` hook is disabled to avoid conflicts. -Without skills, `autoCapture` and `autoRecall` are both enabled by default: +`autoCapture` and `autoRecall` are both enabled by default, including alongside skills: - `autoCapture`: sends conversation content to your configured backend after each agent turn - `autoRecall`: queries your memory store before each agent turn and injects results into context diff --git a/integrations/opencode-plugin/README.md b/integrations/opencode-plugin/README.md index 7199af3f3..296877c23 100644 --- a/integrations/opencode-plugin/README.md +++ b/integrations/opencode-plugin/README.md @@ -2,6 +2,8 @@ Persistent memory for [OpenCode](https://opencode.ai). Your agent remembers decisions, preferences, and learnings across sessions automatically. +Current package version: `0.3.0`. This native TypeScript integration keeps its own tools and scopes while sharing redaction and lifecycle utilities with [agent-plugin-core](../agent-plugin-core/README.md). + ## Install ```bash @@ -28,7 +30,7 @@ Restart OpenCode. | Component | Description | |-----------|-------------| -| **9 Native Memory Tools** | `add_memory`, `search_memories`, `get_memories`, `update_memory`, `delete_memory`, and more — registered as OpenCode tools, backed by the `mem0ai` SDK (no MCP server required) | +| **10 Native Memory Tools** | `add_memory`, `search_memories`, `get_memories`, `update_memory`, `delete_memory`, and more — registered as OpenCode tools, backed by the `mem0ai` SDK (no MCP server required) | | **Lifecycle Hooks** | Auto-search on session start and every prompt, error memory lookup, compaction context, secret redaction | | **7 Skills** | `/mem0-remember`, `/mem0-tour`, `/mem0-search`, `/mem0-status`, `/mem0-scope`, `/mem0-forget`, `/mem0-context-loader` — discovered in place from the plugin via OpenCode's `skills.paths` | @@ -43,7 +45,7 @@ Pure TypeScript — no Python, no shell scripts. Memory operations are native Op | **Pre-tool** | `tool.execute.before` | Blocks MEMORY.md writes, steering them to the `add_memory` tool | | **Post-tool** | `tool.execute.after` | Scans bash errors and pre-fetches related memories | | **Messages transform** | `experimental.chat.messages.transform` | Injects memory context (session memories, search results, error lookups) into the prompt | -| **Compaction** | `experimental.session.compacting` | Stores session state memory, then injects prior memories into compaction context so nothing is lost | +| **Compaction** | `experimental.session.compacting` | Stores session state memory, then injects prior memories into compaction context | | **Shell env** | `shell.env` | Exports `MEM0_USER_ID`, `MEM0_APP_ID`, `MEM0_SESSION_ID`, and `MEM0_BRANCH` to shell | ## Memory Tools @@ -63,7 +65,7 @@ Pure TypeScript — no Python, no shell scripts. Memory operations are native Op ## Memory scope -Every memory tool accepts an optional `scope`, and you can set the **default** +`add_memory`, `search_memories`, `get_memories`, and `delete_all_memories` accept an optional `scope`. You can set the **default** scope (used when none is passed) with the `/mem0-scope` skill: | Scope | Reads | Writes | @@ -83,6 +85,14 @@ fresh on each memory operation, so a change applies immediately — no restart. `delete_all_memories` always requires an explicit `scope="global"` to delete user-wide, so changing the default can't trigger a cross-project wipe. +## Capture and session context + +Automatic capture saves every third qualifying user prompt. Other exchanges and assistant conclusions can be saved through `add_memory` or the remember skill; this is not a complete transcript recorder. Captured and explicitly saved text is redacted without the former 6,000-character cutoff. + +Automatic capture uses the user and repository IDs, with the session ID in metadata. Explicit `session`-scope writes and searches use the top-level `run_id` filter. A session-scoped search therefore does not automatically include project memories that only carry `metadata.session_id`. + +These `project`/`session`/`global` scopes are specific to this integration, not the Python plugins' `repo`/`dir`/`mine` scopes. Global tool access requires the user to enable it through `/mem0-scope global` or plugin settings first. + ## Verify Start OpenCode and ask: *"Search my memories for recent decisions"* @@ -94,11 +104,9 @@ If the `mem0` tools respond, you're all set. | Problem | Fix | |---------|-----| | No tools appearing | Restart OpenCode after installing | -| 401 Unauthorized | `echo $MEM0_API_KEY` must print your `m0-` key | +| 401 Unauthorized | Check that `MEM0_API_KEY` is set to a valid key without printing it | | Plugin not loading | Run `opencode plugin @mem0/opencode-plugin` again | ## License Apache-2.0 - -A memory tool cannot select global scope unless `/mem0-scope global` or the plugin settings already enable it. diff --git a/integrations/pi-agent-plugin/README.md b/integrations/pi-agent-plugin/README.md index c4d9a8286..3b343fcdb 100644 --- a/integrations/pi-agent-plugin/README.md +++ b/integrations/pi-agent-plugin/README.md @@ -4,6 +4,8 @@ Persistent semantic memory for [Pi Agent](https://pi.dev), powered by [Mem0](htt This extension gives Pi Agent long-term memory that persists across sessions, projects, and devices. Memories are automatically captured from conversations and can be searched and managed through slash commands and an agent-accessible tool. +Current package version: `0.3.0`. Shared redaction and lifecycle utilities come from [agent-plugin-core](../agent-plugin-core/README.md); Pi keeps its own tools and scopes. + ## Features - **Automatic memory capture** — learns from every conversation (both user and assistant messages) @@ -79,11 +81,19 @@ The plugin includes 6 skills that guide the agent on how to use each capability: | Scope | Filters | Use case | |-------|---------|----------| | `project` | user + app_id (git root) | Default. Project-specific knowledge | -| `session` | user + app_id + run_id | Ephemeral, session-only context | +| `session` | user + app_id + run_id | Recall restricted to memories saved with the current session ID | | `global` | user only | All memories across all your projects | Project scoping uses `git rev-parse --show-toplevel` to detect the repository root, so all subdirectories within a monorepo share the same memory pool. +Global tool operations require `/mem0-scope global` or `defaultScope: "global"` in plugin configuration. A model-supplied `scope` argument cannot enable cross-project access on its own. Empty or wildcard user, project, and session identities are rejected. + +## Automatic recall and capture + +Before an agent response, the extension searches project memories and injects relevant results. After `agent_end`, automatic capture sends the user and assistant text supplied by Pi to Mem0 in **project** scope, regardless of the default scope selected for explicit commands. Captured text is redacted without the former 6,000-character per-message cutoff. + +Automatic project writes do not attach `run_id`. Session-scoped recall applies to memories explicitly saved in session scope; it does not make project memories session-specific or automatically expire them. Recall queries and displayed tool results keep separate size limits. + ## Memory Categories Memories are automatically classified into 10 general-purpose categories: @@ -132,5 +142,3 @@ pnpm run build # Build (ESM + declarations) ## License [Apache-2.0](LICENSE) - -Global tool operations require `/mem0-scope global` or `defaultScope: "global"` in plugin configuration. A model-supplied `scope` argument cannot enable cross-project access on its own. Empty or wildcard user, project, and session identities are rejected. From 1d83bb08357fa189552caa764aa4a23f813e878c Mon Sep 17 00:00:00 2001 From: Himanshu-Sangshetti Date: Wed, 9 Sep 2026 10:01:26 +0800 Subject: [PATCH 03/61] feat(integrations): add @mem0/eve memory provider Give Eve agents a first-class Mem0 recall/capture provider so they can use Mem0 in the agent loop instead of MCP. Co-authored-by: Cursor --- .github/AGENTS.md | 2 + .github/workflows/ci-gate.yml | 13 + .github/workflows/eve-cd.yml | 57 + .github/workflows/eve-checks.yml | 85 + .github/workflows/release.yml | 1 + docs/docs.json | 1 + docs/integrations/eve.mdx | 68 + docs/llms.txt | 1 + integrations/AGENTS.md | 8 + integrations/eve/.gitignore | 4 + integrations/eve/LICENSE | 201 ++ integrations/eve/README.md | 90 + integrations/eve/package.json | 59 + integrations/eve/pnpm-lock.yaml | 3429 ++++++++++++++++++++ integrations/eve/registry/README.md | 36 + integrations/eve/registry/item.json | 17 + integrations/eve/registry/mem0.ts | 11 + integrations/eve/src/capture.ts | 26 + integrations/eve/src/errors.ts | 3 + integrations/eve/src/idempotency.ts | 26 + integrations/eve/src/index.ts | 3 + integrations/eve/src/messages.ts | 79 + integrations/eve/src/options.ts | 74 + integrations/eve/src/provider.ts | 120 + integrations/eve/src/recall.ts | 36 + integrations/eve/src/store.ts | 83 + integrations/eve/src/tools.ts | 53 + integrations/eve/tests/capture.test.ts | 45 + integrations/eve/tests/helpers.ts | 73 + integrations/eve/tests/idempotency.test.ts | 32 + integrations/eve/tests/messages.test.ts | 86 + integrations/eve/tests/options.test.ts | 30 + integrations/eve/tests/provider.test.ts | 121 + integrations/eve/tests/recall.test.ts | 50 + integrations/eve/tsconfig.json | 22 + integrations/eve/tsup.config.ts | 10 + integrations/eve/vitest.config.ts | 8 + 37 files changed, 5063 insertions(+) create mode 100644 .github/workflows/eve-cd.yml create mode 100644 .github/workflows/eve-checks.yml create mode 100644 docs/integrations/eve.mdx create mode 100644 integrations/eve/.gitignore create mode 100644 integrations/eve/LICENSE create mode 100644 integrations/eve/README.md create mode 100644 integrations/eve/package.json create mode 100644 integrations/eve/pnpm-lock.yaml create mode 100644 integrations/eve/registry/README.md create mode 100644 integrations/eve/registry/item.json create mode 100644 integrations/eve/registry/mem0.ts create mode 100644 integrations/eve/src/capture.ts create mode 100644 integrations/eve/src/errors.ts create mode 100644 integrations/eve/src/idempotency.ts create mode 100644 integrations/eve/src/index.ts create mode 100644 integrations/eve/src/messages.ts create mode 100644 integrations/eve/src/options.ts create mode 100644 integrations/eve/src/provider.ts create mode 100644 integrations/eve/src/recall.ts create mode 100644 integrations/eve/src/store.ts create mode 100644 integrations/eve/src/tools.ts create mode 100644 integrations/eve/tests/capture.test.ts create mode 100644 integrations/eve/tests/helpers.ts create mode 100644 integrations/eve/tests/idempotency.test.ts create mode 100644 integrations/eve/tests/messages.test.ts create mode 100644 integrations/eve/tests/options.test.ts create mode 100644 integrations/eve/tests/provider.test.ts create mode 100644 integrations/eve/tests/recall.test.ts create mode 100644 integrations/eve/tsconfig.json create mode 100644 integrations/eve/tsup.config.ts create mode 100644 integrations/eve/vitest.config.ts diff --git a/.github/AGENTS.md b/.github/AGENTS.md index e207cb9fd..797c0cb00 100644 --- a/.github/AGENTS.md +++ b/.github/AGENTS.md @@ -26,6 +26,7 @@ Package workflows keep their own push-to-main and manual triggers. Their `pull_r | n8n Node | `n8n-nodes-mem0-checks.yml` | Push to main (`integrations/n8n-nodes-mem0/`), manual | ESLint + tsc build on Node 20 | | Zapier App | `zapier-mem0-checks.yml` | Push to main (`integrations/zapier-mem0/`), manual | tsc + `zapier validate` + offline unit tests on Node 22 | | mem0-strands | `mem0-strands-checks.yml` | Push to main (`integrations/mem0-strands/`), manual | Ruff + mypy + pytest + hatch build on Python 3.10, 3.11, 3.12 | +| Eve | `eve-checks.yml` | Push to main (`integrations/eve/`), manual | tsc + vitest + tsup on Node 24 | | docs llms.txt | `docs-llms-txt-check.yml` | Manual | `docs/llms.txt` coverage | | GitHub Scripts | inline in `ci-gate.yml` | none | `node` over every `.github/scripts/*.test.js` | @@ -64,6 +65,7 @@ Requiring `CI Gate` also means fork PRs from first-time contributors cannot merg | DeepSeek Harness Plugin | `deepseek-plugin-cd.yml` | `deepseek-plugin-v*` | npm (`@mem0/deepseek-plugin`) | | n8n Node | `n8n-nodes-mem0-cd.yml` | `n8n-nodes-mem0-v*` | npm (`@mem0/n8n-nodes-mem0`) | | mem0-strands | `mem0-strands-cd.yml` | `mem0-strands-v*` | PyPI (`mem0-strands`) | +| Eve | `eve-cd.yml` | `eve-v*` | npm (`@mem0/eve`) | - Package CD workflows are `workflow_dispatch`-only, with `tag` and `prerelease` inputs. They check out and build the given tag. - All publishing uses **OIDC trusted publishing**. No tokens, no secrets. diff --git a/.github/workflows/ci-gate.yml b/.github/workflows/ci-gate.yml index 2359de80b..ed0ca7848 100644 --- a/.github/workflows/ci-gate.yml +++ b/.github/workflows/ci-gate.yml @@ -46,6 +46,7 @@ jobs: n8n_nodes_mem0: ${{ steps.filter.outputs.n8n_nodes_mem0 }} zapier_mem0: ${{ steps.filter.outputs.zapier_mem0 }} mem0_strands: ${{ steps.filter.outputs.mem0_strands }} + eve: ${{ steps.filter.outputs.eve }} docs_llms_txt: ${{ steps.filter.outputs.docs_llms_txt }} github_scripts: ${{ steps.filter.outputs.github_scripts }} steps: @@ -110,6 +111,10 @@ jobs: - 'integrations/mem0-strands/**' - '.github/workflows/mem0-strands-checks.yml' - '.github/workflows/ci-gate.yml' + eve: + - 'integrations/eve/**' + - '.github/workflows/eve-checks.yml' + - '.github/workflows/ci-gate.yml' docs_llms_txt: - 'docs/**/*.mdx' - 'docs/llms.txt' @@ -214,6 +219,13 @@ jobs: uses: ./.github/workflows/mem0-strands-checks.yml secrets: inherit + eve: + name: Eve + needs: changes + if: needs.changes.outputs.eve == 'true' + uses: ./.github/workflows/eve-checks.yml + secrets: inherit + docs-llms-txt: name: docs llms.txt needs: changes @@ -256,6 +268,7 @@ jobs: - n8n-nodes-mem0 - zapier-mem0 - mem0-strands + - eve - docs-llms-txt - github-scripts if: always() diff --git a/.github/workflows/eve-cd.yml b/.github/workflows/eve-cd.yml new file mode 100644 index 000000000..b4c58a256 --- /dev/null +++ b/.github/workflows/eve-cd.yml @@ -0,0 +1,57 @@ +name: Publish @mem0/eve 📦 to npm + +on: + workflow_dispatch: + inputs: + tag: + description: 'Release tag to build and publish (e.g. eve-v0.1.0)' + required: true + type: string + prerelease: + description: 'Publish under the version preid dist-tag instead of latest' + required: false + type: boolean + default: false + +jobs: + build-n-publish: + name: Build and publish @mem0/eve 📦 to npm + if: startsWith(inputs.tag, 'eve-v') + runs-on: ubuntu-latest + permissions: + id-token: write + defaults: + run: + working-directory: integrations/eve + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.tag }} + + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 9 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version: '24' + registry-url: 'https://registry.npmjs.org' + cache: 'pnpm' + cache-dependency-path: integrations/eve/pnpm-lock.yaml + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Build + run: pnpm build + + - name: Publish to npm + run: | + if [ "${{ inputs.prerelease }}" = "true" ]; then + PREID=$(node -p "require('./package.json').version.split('-')[1].split('.')[0]") + npx npm@latest publish --provenance --access public --tag "$PREID" + else + npx npm@latest publish --provenance --access public + fi diff --git a/.github/workflows/eve-checks.yml b/.github/workflows/eve-checks.yml new file mode 100644 index 000000000..68627f90c --- /dev/null +++ b/.github/workflows/eve-checks.yml @@ -0,0 +1,85 @@ +name: eve checks + +on: + workflow_dispatch: + push: + branches: [main] + paths: + - 'integrations/eve/**' + - '.github/workflows/eve-checks.yml' + workflow_call: + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 9 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 24 + cache: 'pnpm' + cache-dependency-path: integrations/eve/pnpm-lock.yaml + + - name: Install dependencies + run: cd integrations/eve && pnpm install --frozen-lockfile + + - name: Type check + run: cd integrations/eve && pnpm typecheck + + test: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 9 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 24 + cache: 'pnpm' + cache-dependency-path: integrations/eve/pnpm-lock.yaml + + - name: Install dependencies + run: cd integrations/eve && pnpm install --frozen-lockfile + + - name: Run tests + run: cd integrations/eve && pnpm test + + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 9 + + - name: Setup Node.js + uses: actions/setup-node@v4 + with: + node-version: 24 + cache: 'pnpm' + cache-dependency-path: integrations/eve/pnpm-lock.yaml + + - name: Install dependencies + run: cd integrations/eve && pnpm install --frozen-lockfile + + - name: Build + run: cd integrations/eve && pnpm build + + - name: Verify dist output exists + run: | + test -f integrations/eve/dist/index.js || (echo "Build output missing: dist/index.js" && exit 1) + test -f integrations/eve/dist/index.d.ts || (echo "Build output missing: dist/index.d.ts" && exit 1) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0cbb086e4..401551d99 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -48,6 +48,7 @@ jobs: deepseek-plugin-v*) workflow="deepseek-plugin-cd.yml" ;; n8n-nodes-mem0-v*) workflow="n8n-nodes-mem0-cd.yml" ;; mem0-strands-v*) workflow="mem0-strands-cd.yml" ;; + eve-v*) workflow="eve-cd.yml" ;; v*) workflow="cd.yml" ;; *) echo "::error::Release tag '$TAG' does not match any known package prefix — nothing will be published. See the tag prefix table in AGENTS.md." diff --git a/docs/docs.json b/docs/docs.json index 269cf9426..a0c0d1151 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -325,6 +325,7 @@ "integrations/google-ai-adk", "integrations/mastra", "integrations/vercel-ai-sdk", + "integrations/eve", "integrations/vercel", "integrations/chatdev", "integrations/strands" diff --git a/docs/integrations/eve.mdx b/docs/integrations/eve.mdx new file mode 100644 index 000000000..e3a8c1e86 --- /dev/null +++ b/docs/integrations/eve.mdx @@ -0,0 +1,68 @@ +--- +title: Eve +description: "Use Mem0 as a first-class memory provider for Vercel Eve agents." +--- + +[Eve](https://eve.dev/docs/memory) is Vercel's agent framework. A memory provider sits in the agent loop: Eve recalls context before each turn, captures completed turns, and exposes provider tools. `@mem0/eve` is Mem0's implementation of that contract. + +This is not the Mem0 MCP connection. MCP gives the model tools it may or may not call. The memory provider runs automatically. + +## Install + +```bash +npm install @mem0/eve +``` + +`eve` is a peer dependency. Get an API key from the [Mem0 dashboard](https://app.mem0.ai/dashboard/api-keys). + +Create `agent/memory/mem0.ts`: + +```ts +import { defineMemory } from "eve/memory"; +import { byPrincipal } from "eve/memory/scope"; +import { mem0Provider } from "@mem0/eve"; + +export default defineMemory({ + description: "Recall and manage durable context for the current user.", + provider: mem0Provider({ + apiKey: process.env.MEM0_API_KEY!, + }), + scope: byPrincipal, +}); +``` + +After Eve lists Mem0 in the official registry, the same slot is created by: + +```bash +eve add memory/mem0 +``` + +## How it works + +1. **Recall.** Before each turn, Mem0 searches memories for the locked Eve scope and returns them as attributed user-role messages. +2. **Capture.** After a successful turn, Mem0 adds the user and assistant messages and extracts durable facts. +3. **Tools.** The model can call `search`, `remember`, and `forget`. Eve qualifies them as `mem0__search`, `mem0__remember`, and `mem0__forget` when the slot file is `mem0.ts`. + +Eve owns namespace, scope, and when recall/capture run. Mem0 owns storage, ranking, and extraction. Every read and write is partitioned by `memory.scope.key`. + +## Options + +```ts +mem0Provider({ + apiKey: process.env.MEM0_API_KEY!, + topK: 5, + threshold: 0.1, + rerank: false, + infer: true, + autoSearch: { enabled: true }, + capture: { enabled: true }, +}); +``` + +See the [`@mem0/eve` README](https://github.com/mem0ai/mem0/tree/main/integrations/eve) for the full option list. + +## Related + +- [Eve memory docs](https://eve.dev/docs/memory) +- [Build a memory provider](https://eve.dev/docs/memory/custom-provider) +- [Vercel AI SDK](/integrations/vercel-ai-sdk) for `generateText` / `streamText` apps that are not Eve agents diff --git a/docs/llms.txt b/docs/llms.txt index ae45ad462..79166ce8c 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -263,6 +263,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st - [Mastra](https://docs.mem0.ai/integrations/mastra) [Platform]: Use when the user is on Mastra (TypeScript). - [OpenClaw](https://docs.mem0.ai/integrations/openclaw) [Both]: Use when wiring Mem0 into Claude Code or editors via OpenClaw. - [Vercel AI SDK](https://docs.mem0.ai/integrations/vercel-ai-sdk) [Both]: Use when the user is on the Vercel AI SDK. +- [Eve](https://docs.mem0.ai/integrations/eve) [Platform]: Use when adding Mem0 as a first-class Eve memory provider (`@mem0/eve`, `mem0Provider`, `eve add memory/mem0`). Not the Mem0 MCP connection. - [Vercel](https://docs.mem0.ai/integrations/vercel) [Platform]: Use when deploying on Vercel and installing Mem0 from the Vercel Marketplace. - [Strands Agents](https://docs.mem0.ai/integrations/strands) [Both]: Use when the user is on AWS Strands and wants a native MemoryStore. diff --git a/integrations/AGENTS.md b/integrations/AGENTS.md index 6083dcf6a..8e683ae65 100644 --- a/integrations/AGENTS.md +++ b/integrations/AGENTS.md @@ -4,6 +4,7 @@ Agent and editor integrations. Each subdirectory is self-contained: its own `pac | Directory | Package | Build | Lint | Test | |-----------|---------|-------|------|------| +| `eve/` | `@mem0/eve` | tsup (ESM) | none | vitest | | `vercel-ai-sdk/` | `@mem0/vercel-ai-provider` | tsup (CJS+ESM) | ESLint + Prettier | jest + vitest (edge/node) | | `openclaw/` | `@mem0/openclaw-mem0` | tsup (ESM) | none | vitest | | `claude-code-plugin/` | Claude Code plugin, installs as `mem0@mem0-plugins` (v0.3.0) | none | ruff | pytest | @@ -20,6 +21,12 @@ pnpm everywhere except `.opencode-plugin/` (Bun) and `mem0-strands/` (Python: pi ## Commands ```bash +cd integrations/eve +pnpm install +pnpm run typecheck +pnpm run test +pnpm run build + cd integrations/vercel-ai-sdk pnpm install pnpm run build # tsup @@ -40,6 +47,7 @@ Run the type check after every TypeScript change: `pnpm run typecheck` or `tsc - ## What each one is +- **`eve/`** is the Eve memory provider (`mem0Provider`). Eve calls recall before each turn and capture after each turn. This is not the Mem0 MCP connection. - **`vercel-ai-sdk/`** wraps the Vercel AI SDK through a `createMem0` provider. Integrations for AI-SDK repos go through this wrapper, not raw `MemoryClient`. - **`claude-code-plugin/`** is the Claude Code plugin (v0.3.0, installs as `mem0@mem0-plugins`): local evidence capture via lifecycle hooks, background memory extraction to the Mem0 Platform, a local `search_memories` MCP tool, six `/mem0:*` skills, and the `mem0:sidekick` agent. Pure-stdlib Python — no dependencies to install. Its `core/` + `adapters/claude/` split marks engine vs. harness glue; future per-harness plugins start by copying `core/` and keeping the contract tests verbatim (see its `docs/CONTRACT.md`). - **`mem0-plugin/`** connects Cursor, Codex, Kimi, Antigravity, and OpenCode to the MCP server at `mcp.mem0.ai` and installs lifecycle hooks for automatic memory capture. Exposes 9 MCP tools: `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`. The Claude Code plugin moved to [`claude-code-plugin/`](claude-code-plugin/) in v0.3.0 (installs as `mem0@mem0-plugins`); do not run both at the same time. diff --git a/integrations/eve/.gitignore b/integrations/eve/.gitignore new file mode 100644 index 000000000..8d0aa9acf --- /dev/null +++ b/integrations/eve/.gitignore @@ -0,0 +1,4 @@ +node_modules +dist +coverage +*.tgz diff --git a/integrations/eve/LICENSE b/integrations/eve/LICENSE new file mode 100644 index 000000000..d20d5102c --- /dev/null +++ b/integrations/eve/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [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. diff --git a/integrations/eve/README.md b/integrations/eve/README.md new file mode 100644 index 000000000..90b4f8212 --- /dev/null +++ b/integrations/eve/README.md @@ -0,0 +1,90 @@ +# @mem0/eve + +Mem0 as a first-class [Eve](https://eve.dev/docs/memory) memory provider. + +Eve recalls relevant memories before each turn, captures completed turns automatically, and exposes search / remember / forget tools bound to the locked memory scope. Mem0 owns storage, extraction, and retrieval. + +```ts +import { defineMemory } from "eve/memory"; +import { byPrincipal } from "eve/memory/scope"; +import { mem0Provider } from "@mem0/eve"; + +export default defineMemory({ + description: "Recall and manage durable context for the current user.", + provider: mem0Provider({ + apiKey: process.env.MEM0_API_KEY!, + }), + scope: byPrincipal, +}); +``` + +## Install + +```bash +npm install @mem0/eve +``` + +`eve` is a peer dependency. Get an API key from the [Mem0 dashboard](https://app.mem0.ai/dashboard/api-keys). + +Until Eve lists Mem0 in the official registry, add the slot file yourself as `agent/memory/mem0.ts`. After the registry PR lands, this becomes: + +```bash +eve add memory/mem0 +``` + +## What it does + +| Eve hook | Mem0 behavior | +|---|---| +| `recall["turn.started"]` | Semantic search over memories for the locked scope | +| `recall["compaction.completed"]` | Same search after Eve compacting history | +| `capture["turn.completed"]` | Add the completed user/assistant turn | +| `tools()` | `search`, `remember`, `forget` | + +Every read and write is partitioned by `memory.scope.key`. The model cannot choose another caller. Replay uses `operationId` as an idempotency key. + +If the slot file is named `mem0.ts`, Eve qualifies tools as `mem0__search`, `mem0__remember`, and `mem0__forget`. + +## Options + +```ts +mem0Provider({ + apiKey: process.env.MEM0_API_KEY!, + host: "https://api.mem0.ai", + topK: 5, + threshold: 0.1, + rerank: false, + infer: true, + autoSearch: { enabled: true }, + capture: { enabled: true }, + metadata: { app: "support-agent" }, +}); +``` + +| Option | Default | Purpose | +|---|---|---| +| `apiKey` | required | String or async getter | +| `host` | `https://api.mem0.ai` | Mem0 Platform host | +| `topK` | `5` | Memories recalled per turn | +| `threshold` | `0.1` | Minimum similarity | +| `rerank` | `false` | Mem0 reranking | +| `infer` | `true` | Extract facts on capture | +| `autoSearch.enabled` | `true` | Recall before each turn | +| `capture.enabled` | `true` | Write after each successful turn | +| `metadata` | `{}` | Extra metadata on captured turns | + +## Official registry + +Eve already listed Mem0 as an MCP connection. This package is the memory-provider path. After `@mem0/eve` is on npm, open a PR against [vercel/eve](https://github.com/vercel/eve) that adds `memory/mem0` using the files in [`registry/`](./registry). See [`registry/README.md`](./registry/README.md). + +## Development + +Requires Node.js 24+. + +```bash +cd integrations/eve +pnpm install +pnpm test +pnpm typecheck +pnpm build +``` diff --git a/integrations/eve/package.json b/integrations/eve/package.json new file mode 100644 index 000000000..5085ff34a --- /dev/null +++ b/integrations/eve/package.json @@ -0,0 +1,59 @@ +{ + "name": "@mem0/eve", + "version": "0.1.0", + "description": "Mem0 memory provider for Eve agents. Recall, capture, and scope-bound tools.", + "type": "module", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "https://github.com/mem0ai/mem0", + "directory": "integrations/eve" + }, + "keywords": [ + "eve", + "mem0", + "memory", + "agents", + "vercel" + ], + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js", + "default": "./dist/index.js" + } + }, + "publishConfig": { + "access": "public" + }, + "files": [ + "dist", + "README.md", + "LICENSE" + ], + "scripts": { + "build": "tsup", + "test": "vitest run", + "test:watch": "vitest", + "typecheck": "tsc --noEmit" + }, + "dependencies": { + "mem0ai": "^3.1.0", + "zod": "^4.0.0" + }, + "peerDependencies": { + "eve": ">=0.47.3" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "eve": "^0.52.2", + "tsup": "^8.5.0", + "typescript": "^5.8.3", + "vitest": "^4.1.7" + }, + "engines": { + "node": ">=24" + } +} diff --git a/integrations/eve/pnpm-lock.yaml b/integrations/eve/pnpm-lock.yaml new file mode 100644 index 000000000..173469513 --- /dev/null +++ b/integrations/eve/pnpm-lock.yaml @@ -0,0 +1,3429 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + mem0ai: + specifier: ^3.1.0 + version: 3.1.8(@cloudflare/workers-types@4.20260702.1)(@types/jest@29.5.14)(@types/pg@8.11.0)(better-sqlite3@12.11.1)(compromise@14.16.0)(mongodb@7.5.0)(natural@8.1.1)(pg@8.11.3) + zod: + specifier: ^4.0.0 + version: 4.5.4 + devDependencies: + '@types/node': + specifier: ^24.0.0 + version: 24.13.3 + eve: + specifier: ^0.52.2 + version: 0.52.2(ai@7.0.93(zod@4.5.4)) + tsup: + specifier: ^8.5.0 + version: 8.5.1(postcss@8.5.28)(typescript@5.9.3) + typescript: + specifier: ^5.8.3 + version: 5.9.3 + vitest: + specifier: ^4.1.7 + version: 4.1.11(@types/node@24.13.3)(vite@8.2.2(@types/node@24.13.3)(esbuild@0.27.7)) + +packages: + + '@ai-sdk/gateway@4.0.75': + resolution: {integrity: sha512-HOnhw3oXtBnboBF7kAKipjToCN6+5w6EuukiUKiULcxBitS+vbHRRv9IUBcq+Z1wkXcJjfywKrt5r++I6OYyXg==} + engines: {node: '>=22'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + + '@ai-sdk/provider-utils@5.0.36': + resolution: {integrity: sha512-MFXBn6XDyf37PNQAge/HTatPJE8Vmg/g/w4WPtjSV53jq8FKAzoaN5+43hsdQa9bqgN+/13jxug9ChvsG+godQ==} + engines: {node: '>=22'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + + '@ai-sdk/provider@4.0.10': + resolution: {integrity: sha512-fX2ENAc7iDpZ+Wp4+Rk06Usn/Ys7dI9uAkGv0jlF6XVrW13NkRWx5Ou+U6lIM2E1fTLkCs16GGrUAaVvroag7A==} + engines: {node: '>=22'} + + '@babel/code-frame@7.29.7': + resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} + engines: {node: '>=6.9.0'} + + '@babel/helper-validator-identifier@7.29.7': + resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} + engines: {node: '>=6.9.0'} + + '@cloudflare/workers-types@4.20260702.1': + resolution: {integrity: sha512-mOhf5TUEB1m2vPrxtqoIGfz0fUC9xyxRDx5gWHy5s+OCo6dcV+g7wI1R7gYCMFohhqF/2y2xeKVwMwCJjfn/WA==} + + '@esbuild/aix-ppc64@0.27.7': + resolution: {integrity: sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [aix] + + '@esbuild/android-arm64@0.27.7': + resolution: {integrity: sha512-62dPZHpIXzvChfvfLJow3q5dDtiNMkwiRzPylSCfriLvZeq0a1bWChrGx/BbUbPwOrsWKMn8idSllklzBy+dgQ==} + engines: {node: '>=18'} + cpu: [arm64] + os: [android] + + '@esbuild/android-arm@0.27.7': + resolution: {integrity: sha512-jbPXvB4Yj2yBV7HUfE2KHe4GJX51QplCN1pGbYjvsyCZbQmies29EoJbkEc+vYuU5o45AfQn37vZlyXy4YJ8RQ==} + engines: {node: '>=18'} + cpu: [arm] + os: [android] + + '@esbuild/android-x64@0.27.7': + resolution: {integrity: sha512-x5VpMODneVDb70PYV2VQOmIUUiBtY3D3mPBG8NxVk5CogneYhkR7MmM3yR/uMdITLrC1ml/NV1rj4bMJuy9MCg==} + engines: {node: '>=18'} + cpu: [x64] + os: [android] + + '@esbuild/darwin-arm64@0.27.7': + resolution: {integrity: sha512-5lckdqeuBPlKUwvoCXIgI2D9/ABmPq3Rdp7IfL70393YgaASt7tbju3Ac+ePVi3KDH6N2RqePfHnXkaDtY9fkw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [darwin] + + '@esbuild/darwin-x64@0.27.7': + resolution: {integrity: sha512-rYnXrKcXuT7Z+WL5K980jVFdvVKhCHhUwid+dDYQpH+qu+TefcomiMAJpIiC2EM3Rjtq0sO3StMV/+3w3MyyqQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [darwin] + + '@esbuild/freebsd-arm64@0.27.7': + resolution: {integrity: sha512-B48PqeCsEgOtzME2GbNM2roU29AMTuOIN91dsMO30t+Ydis3z/3Ngoj5hhnsOSSwNzS+6JppqWsuhTp6E82l2w==} + engines: {node: '>=18'} + cpu: [arm64] + os: [freebsd] + + '@esbuild/freebsd-x64@0.27.7': + resolution: {integrity: sha512-jOBDK5XEjA4m5IJK3bpAQF9/Lelu/Z9ZcdhTRLf4cajlB+8VEhFFRjWgfy3M1O4rO2GQ/b2dLwCUGpiF/eATNQ==} + engines: {node: '>=18'} + cpu: [x64] + os: [freebsd] + + '@esbuild/linux-arm64@0.27.7': + resolution: {integrity: sha512-RZPHBoxXuNnPQO9rvjh5jdkRmVizktkT7TCDkDmQ0W2SwHInKCAV95GRuvdSvA7w4VMwfCjUiPwDi0ZO6Nfe9A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [linux] + + '@esbuild/linux-arm@0.27.7': + resolution: {integrity: sha512-RkT/YXYBTSULo3+af8Ib0ykH8u2MBh57o7q/DAs3lTJlyVQkgQvlrPTnjIzzRPQyavxtPtfg0EopvDyIt0j1rA==} + engines: {node: '>=18'} + cpu: [arm] + os: [linux] + + '@esbuild/linux-ia32@0.27.7': + resolution: {integrity: sha512-GA48aKNkyQDbd3KtkplYWT102C5sn/EZTY4XROkxONgruHPU72l+gW+FfF8tf2cFjeHaRbWpOYa/uRBz/Xq1Pg==} + engines: {node: '>=18'} + cpu: [ia32] + os: [linux] + + '@esbuild/linux-loong64@0.27.7': + resolution: {integrity: sha512-a4POruNM2oWsD4WKvBSEKGIiWQF8fZOAsycHOt6JBpZ+JN2n2JH9WAv56SOyu9X5IqAjqSIPTaJkqN8F7XOQ5Q==} + engines: {node: '>=18'} + cpu: [loong64] + os: [linux] + + '@esbuild/linux-mips64el@0.27.7': + resolution: {integrity: sha512-KabT5I6StirGfIz0FMgl1I+R1H73Gp0ofL9A3nG3i/cYFJzKHhouBV5VWK1CSgKvVaG4q1RNpCTR2LuTVB3fIw==} + engines: {node: '>=18'} + cpu: [mips64el] + os: [linux] + + '@esbuild/linux-ppc64@0.27.7': + resolution: {integrity: sha512-gRsL4x6wsGHGRqhtI+ifpN/vpOFTQtnbsupUF5R5YTAg+y/lKelYR1hXbnBdzDjGbMYjVJLJTd2OFmMewAgwlQ==} + engines: {node: '>=18'} + cpu: [ppc64] + os: [linux] + + '@esbuild/linux-riscv64@0.27.7': + resolution: {integrity: sha512-hL25LbxO1QOngGzu2U5xeXtxXcW+/GvMN3ejANqXkxZ/opySAZMrc+9LY/WyjAan41unrR3YrmtTsUpwT66InQ==} + engines: {node: '>=18'} + cpu: [riscv64] + os: [linux] + + '@esbuild/linux-s390x@0.27.7': + resolution: {integrity: sha512-2k8go8Ycu1Kb46vEelhu1vqEP+UeRVj2zY1pSuPdgvbd5ykAw82Lrro28vXUrRmzEsUV0NzCf54yARIK8r0fdw==} + engines: {node: '>=18'} + cpu: [s390x] + os: [linux] + + '@esbuild/linux-x64@0.27.7': + resolution: {integrity: sha512-hzznmADPt+OmsYzw1EE33ccA+HPdIqiCRq7cQeL1Jlq2gb1+OyWBkMCrYGBJ+sxVzve2ZJEVeePbLM2iEIZSxA==} + engines: {node: '>=18'} + cpu: [x64] + os: [linux] + + '@esbuild/netbsd-arm64@0.27.7': + resolution: {integrity: sha512-b6pqtrQdigZBwZxAn1UpazEisvwaIDvdbMbmrly7cDTMFnw/+3lVxxCTGOrkPVnsYIosJJXAsILG9XcQS+Yu6w==} + engines: {node: '>=18'} + cpu: [arm64] + os: [netbsd] + + '@esbuild/netbsd-x64@0.27.7': + resolution: {integrity: sha512-OfatkLojr6U+WN5EDYuoQhtM+1xco+/6FSzJJnuWiUw5eVcicbyK3dq5EeV/QHT1uy6GoDhGbFpprUiHUYggrw==} + engines: {node: '>=18'} + cpu: [x64] + os: [netbsd] + + '@esbuild/openbsd-arm64@0.27.7': + resolution: {integrity: sha512-AFuojMQTxAz75Fo8idVcqoQWEHIXFRbOc1TrVcFSgCZtQfSdc1RXgB3tjOn/krRHENUB4j00bfGjyl2mJrU37A==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openbsd] + + '@esbuild/openbsd-x64@0.27.7': + resolution: {integrity: sha512-+A1NJmfM8WNDv5CLVQYJ5PshuRm/4cI6WMZRg1by1GwPIQPCTs1GLEUHwiiQGT5zDdyLiRM/l1G0Pv54gvtKIg==} + engines: {node: '>=18'} + cpu: [x64] + os: [openbsd] + + '@esbuild/openharmony-arm64@0.27.7': + resolution: {integrity: sha512-+KrvYb/C8zA9CU/g0sR6w2RBw7IGc5J2BPnc3dYc5VJxHCSF1yNMxTV5LQ7GuKteQXZtspjFbiuW5/dOj7H4Yw==} + engines: {node: '>=18'} + cpu: [arm64] + os: [openharmony] + + '@esbuild/sunos-x64@0.27.7': + resolution: {integrity: sha512-ikktIhFBzQNt/QDyOL580ti9+5mL/YZeUPKU2ivGtGjdTYoqz6jObj6nOMfhASpS4GU4Q/Clh1QtxWAvcYKamA==} + engines: {node: '>=18'} + cpu: [x64] + os: [sunos] + + '@esbuild/win32-arm64@0.27.7': + resolution: {integrity: sha512-7yRhbHvPqSpRUV7Q20VuDwbjW5kIMwTHpptuUzV+AA46kiPze5Z7qgt6CLCK3pWFrHeNfDd1VKgyP4O+ng17CA==} + engines: {node: '>=18'} + cpu: [arm64] + os: [win32] + + '@esbuild/win32-ia32@0.27.7': + resolution: {integrity: sha512-SmwKXe6VHIyZYbBLJrhOoCJRB/Z1tckzmgTLfFYOfpMAx63BJEaL9ExI8x7v0oAO3Zh6D/Oi1gVxEYr5oUCFhw==} + engines: {node: '>=18'} + cpu: [ia32] + os: [win32] + + '@esbuild/win32-x64@0.27.7': + resolution: {integrity: sha512-56hiAJPhwQ1R4i+21FVF7V8kSD5zZTdHcVuRFMW0hn753vVfQN8xlx4uOPT4xoGH0Z/oVATuR82AiqSTDIpaHg==} + engines: {node: '>=18'} + cpu: [x64] + os: [win32] + + '@jest/expect-utils@29.7.0': + resolution: {integrity: sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jest/schemas@29.6.3': + resolution: {integrity: sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jest/types@29.6.3': + resolution: {integrity: sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + '@jridgewell/gen-mapping@0.3.13': + resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} + + '@jridgewell/resolve-uri@3.1.2': + resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} + engines: {node: '>=6.0.0'} + + '@jridgewell/sourcemap-codec@1.6.0': + resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} + + '@jridgewell/trace-mapping@0.3.31': + resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + + '@mongodb-js/saslprep@1.5.2': + resolution: {integrity: sha512-UBvCBdPHAmiiDNEpD2ORBGzna4qYr06fLELfGDPW3/KZ9uLK+cGT9npAc/x/6/8SLzdbILMuc3HWFQ0FvJMhCw==} + + '@napi-rs/lzma-linux-x64-gnu@1.5.1': + resolution: {integrity: sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==} + engines: {node: ^22.20 || ^24.12 || >=25} + cpu: [x64] + os: [linux] + + '@oxc-project/types@0.148.0': + resolution: {integrity: sha512-Nm4s/jB+4FpFsPhWGEC4h7rzksesmtnMXomo6rCMcg/b8zLQuOziRgkCS1fxDCXOlJB/6Q8oABOZ/OP6RIPj9A==} + + '@redis/bloom@5.12.1': + resolution: {integrity: sha512-PUUfv+ms7jgPSBVoo/DN4AkPHj4D5TZSd6SbJX7egzBplkYUcKmHRE8RKia7UtZ8bSQbLguLvxVO+asKtQfZWA==} + engines: {node: '>= 18.19.0'} + peerDependencies: + '@redis/client': ^5.12.1 + + '@redis/client@5.12.1': + resolution: {integrity: sha512-7aPGWeqA3uFm43o19umzdl16CEjK/JQGtSXVPevplTaOU3VJA/rseBC1QvYUz9lLDIMBimc4SW/zrW4S89BaCA==} + engines: {node: '>= 18.19.0'} + peerDependencies: + '@node-rs/xxhash': ^1.1.0 + '@opentelemetry/api': '>=1 <2' + peerDependenciesMeta: + '@node-rs/xxhash': + optional: true + '@opentelemetry/api': + optional: true + + '@redis/json@5.12.1': + resolution: {integrity: sha512-eOze75esLve4vfqDel7aMX08CNaiLLQS2fV8mpRN9NxPe1rVR4vQyYiW/OgtGUysF6QOr9ANhfxABKNOJfXdKg==} + engines: {node: '>= 18.19.0'} + peerDependencies: + '@redis/client': ^5.12.1 + + '@redis/search@5.12.1': + resolution: {integrity: sha512-ItlxbxC9cKI6IU1TLWoczwJCRb6TdmkEpWv05UrPawqaAnWGRu3rcIqsc5vN483T2fSociuyV1UkWIL5I4//2w==} + engines: {node: '>= 18.19.0'} + peerDependencies: + '@redis/client': ^5.12.1 + + '@redis/time-series@5.12.1': + resolution: {integrity: sha512-c6JL6E3EcZJuNqKFz+KM+l9l5mpcQiKvTwgA3blt5glWJ8hjDk0yeHN3beE/MpqYIQ8UEX44ItQzgkE/gCBELQ==} + engines: {node: '>= 18.19.0'} + peerDependencies: + '@redis/client': ^5.12.1 + + '@rolldown/binding-android-arm-eabi@1.2.7': + resolution: {integrity: sha512-EypzgnYCwyVY4NDHKzGmNJT5b+XaQEBniHxsMdeIQLB/tcCzZnhqrzHpZFbX9iaxx+5RiB8caATBtfvZP7zVxQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.7': + resolution: {integrity: sha512-l17HE9EweWaqJZhuUuNBN/FzM62xw+DECVnJyvMsxn8vJFAGLy5QfLDoYAcronkAN8VxKZHezDpulHDPx95vFw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.7': + resolution: {integrity: sha512-8ED8ELFvHXc6OCETIn4gXObPiaR6bckM/ipXtbzlPVDRMBfEGjCKgO90F9YtfdpDatVx/ZQw7aZ1vUMf/+T3Mw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.7': + resolution: {integrity: sha512-/WPripjtiAIZ2tWY7ddijORT0Ujg87wxWW/qcoFVCKAWVDPhtY0xr7Dj0M3GyNGz60jGwTElhro/mkF9dT7dDQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.7': + resolution: {integrity: sha512-14DI4NcqpvbICxSnGLx3PmtDaWqRP/KGSGb6C+JLLVPeZRl6dKdHba3pGsqT3vpdTqhEYIPG0MMQ8c0xYqoJxA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.7': + resolution: {integrity: sha512-bxrWIRvHWQvbJwi+VIie/kDJmQxcNE6xxWwZdqF/ExVAigtHkv54WTLQPb+QsZdnFy18fg7JPfWGL0RH6vwIlQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.7': + resolution: {integrity: sha512-toOY2BChBZyuxU7OYX6Tn389di4IzAqPTycVcci0O7FSfBqzRB3RZn+K5Is6ANf4tmgRd/K1yZTsNTXbkXsnLg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + + '@rolldown/binding-linux-arm64-musl@1.2.7': + resolution: {integrity: sha512-lAIXTH/aiLRLxsTgQvfhjo4K1ydWIp00+V0voOr9beb/9ZmkUFrSIb03dXNFRgMNvkE6oGsF10ioQ6UsI+vS5Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + + '@rolldown/binding-linux-ppc64-gnu@1.2.7': + resolution: {integrity: sha512-kdnwS28Pkenp/mZMRwjXXXwxQ7pIsm+bF919LUK93BOyhcLsrVKdP2p9fxpiPNPAbNuch8ypQt0pm2P2LYCAGg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + + '@rolldown/binding-linux-s390x-gnu@1.2.7': + resolution: {integrity: sha512-516OdsyLdr5E65paF3yBF55t8mfm9+gmtCsK3xI7XKXIT7EfRlHhxL8K/NR6Hu8BWSgF5+1w74lTL0+nxcc8Qw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + + '@rolldown/binding-linux-x64-gnu@1.2.7': + resolution: {integrity: sha512-r8/z8n7GFaYRln3xmP1Cxy0HH/HLM0uBUPkEuSVEfKGDA89M0FsZRZJRSwe/tJjRx+fpH/gjorfhB8tmEbSFLA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + + '@rolldown/binding-linux-x64-musl@1.2.7': + resolution: {integrity: sha512-pAsE8iiDxUg1xBqdhrTfg45AVDVpirjz00sblEYClGNNcMnDb+e8beQgqIAw6LvauX/APvgxUnwrgun/YYGBhw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + + '@rolldown/binding-openharmony-arm64@1.2.7': + resolution: {integrity: sha512-lTcIYmmnQQA8Or/2DatS6oSqcdLHvendjS+zLu+FwgToynWMRSmQdpM65fTANJgIS4mjbMOo5KT2lnT9SAb96w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.7': + resolution: {integrity: sha512-e3Gu3WxbNk/UqQhxqU7YIYO+9ZBvWNz3U+h/qRFosscMFzdRPbXYSaSWgSnklv2fz1TgzBTcti2z35c/7irsHw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.7': + resolution: {integrity: sha512-W/jg5qoRSqjsEv0+dZi4e687mcHqmVuU0P4fK6qS/xjetW2Gmc1W8j//z5nAeNcC8Ttm0hV46IjcYeuVwYhuiw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@rollup/rollup-android-arm-eabi@4.63.1': + resolution: {integrity: sha512-UZ8sUxPTiHWYX9QNdJedb1kDZSpS1t/VPWBWGSgqHNi9w3Cu6IXvu2mzbhiTiPvtrqgTQJ+zqiAq2iPIPilpaQ==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.63.1': + resolution: {integrity: sha512-cQ4nFQABN5cDvDpbvJ7bMStCpnaVxynZrRMfUJYgxcIk9Sh54FIO1vtfkg0B69REjER77ioZ/ov+eAApx/KmLQ==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.63.1': + resolution: {integrity: sha512-FQNqd1lRy/0QhDk3xeRIkSBiCpXCiDnZO3YLVdcDKN1UBiKToNftCzcXYNLshmPDUMlu2TdeS8tGcsU6f3YF1Q==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.63.1': + resolution: {integrity: sha512-pvD16V939D3CloK0+qikpGaxiPrDUXTe7Y5cWOMkMSy7m1cawa8EGy/kXYi/G/cKAC4HDAbSnzCIk1WmsoOKXg==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.63.1': + resolution: {integrity: sha512-pcFGeL2345VwdTnJhA6zLbew+YgWB0qBG2+dMtXjCicf6+rm6kO6cOoh5VnTe0ZMrMRgRyuHmCJxZWrIdzYuOw==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.63.1': + resolution: {integrity: sha512-mRJlqSRulVzcKq/LKA6ICSIc3K/l4fzlVn/gePn2nXIHy8seRi5z/eeRE0d/XMBxcMldiXtQTSpRj0tkkC3g8Q==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.63.1': + resolution: {integrity: sha512-YDUNvVM85TI3g/1OpnqKP1h4NeW/j64DfWMf+G3M809xNk1bJSnpFp4sh83NpmVE5DXnkh8ULor4LTVZKoYLHw==} + cpu: [arm] + os: [linux] + + '@rollup/rollup-linux-arm-musleabihf@4.63.1': + resolution: {integrity: sha512-7Mcn71p9ZuQFAj+h+dhQXy/yeLePRS2yKRnmW1DijA9thKO5qap0GNOIQK4yQ6iP3SU0Mrb/yWo8h8vgRba8lw==} + cpu: [arm] + os: [linux] + + '@rollup/rollup-linux-arm64-gnu@4.63.1': + resolution: {integrity: sha512-4YiLQTX6U4CSl0L9cluep9A9W6UmTfqBDc2/CH6wlu54pl4E7Jn3cOD8oxzvBDEGk/JMKgJ47C8g+radF7mwvg==} + cpu: [arm64] + os: [linux] + + '@rollup/rollup-linux-arm64-musl@4.63.1': + resolution: {integrity: sha512-2ra8F7w8OquwZN9z2/fKFnli69wa8PLwaVzRMIPGb13ByMJwC28Fbp8YcVGoUhlYMTt7j5j9bNgpysrN2UM+vw==} + cpu: [arm64] + os: [linux] + + '@rollup/rollup-linux-loong64-gnu@4.63.1': + resolution: {integrity: sha512-Sy20ncyhjmBP0Ml+UvQbimjlk6VFgjW5uNP+qqwHB00mTE8Bl2C1TuHTlRwK2YoXeZbee5lP2XevBWVkAQAtSQ==} + cpu: [loong64] + os: [linux] + + '@rollup/rollup-linux-loong64-musl@4.63.1': + resolution: {integrity: sha512-noITLp8oNjYliPnGWmLyelIHwULGqbHloQHGw1rtxbWhTuWooRpnZarZQJ1y9EUC4szuCusCc+HEpUtxpIwYvA==} + cpu: [loong64] + os: [linux] + + '@rollup/rollup-linux-ppc64-gnu@4.63.1': + resolution: {integrity: sha512-hlxxXd+F1mWiAcaFR7Sv9ZQT6m6UfI8+Vy/kFJzztq2pDMU/0wZ9sish0iszNZvsQDo8Gc0i5yuFEOz5dDf6fA==} + cpu: [ppc64] + os: [linux] + + '@rollup/rollup-linux-ppc64-musl@4.63.1': + resolution: {integrity: sha512-EF7OpqQTQ/BvGqLzUi4rEHuagCV9MugAUXSHemwPW5vxZ75RR+jxO/2j95Ph2dalMpFHSVECjRoioHZgA9zOYA==} + cpu: [ppc64] + os: [linux] + + '@rollup/rollup-linux-riscv64-gnu@4.63.1': + resolution: {integrity: sha512-wQO3JesW9PRkwlabQ27y7sPfVOOTLRG73I4F2UYHG5PXun3J9U3y+b7ezVKSYbsvSKGQ1k1cq8Qlun4C9kLt3w==} + cpu: [riscv64] + os: [linux] + + '@rollup/rollup-linux-riscv64-musl@4.63.1': + resolution: {integrity: sha512-ouAGwhO6wHRXdnOVCOsB0tRFkA7nhNB2Nwax6oECXN0YiN8EYUTBAOudADOB1PI+yDL61TeNx/u7MVCzksNbkQ==} + cpu: [riscv64] + os: [linux] + + '@rollup/rollup-linux-s390x-gnu@4.63.1': + resolution: {integrity: sha512-q2R38Sn+1J8RxhfJ+T54wSWmyKXWec+9jgDfqO2AtArEqHO5R2aeayp5H5OYLr5UYDVGsVaZPEFUooMhYCdz5A==} + cpu: [s390x] + os: [linux] + + '@rollup/rollup-linux-x64-gnu@4.63.1': + resolution: {integrity: sha512-gfI5T24WLLuFfSKw7Go/zDXjAAV0fny0swTaDv+WjK7vqcw4cRhFfdsyKL1n+ukI+ooBxn3bVQnyrn06WpI50w==} + cpu: [x64] + os: [linux] + + '@rollup/rollup-linux-x64-musl@4.63.1': + resolution: {integrity: sha512-4h6XqthmB4Hspji84wvgk+ElodTsGj+dbZqHJHHtKxj4mYq0ANSEEPX9ys3moJueqsRjwpaJYH7874Itwnj2ow==} + cpu: [x64] + os: [linux] + + '@rollup/rollup-openbsd-x64@4.63.1': + resolution: {integrity: sha512-dlfCOa87o1VAYegLQ9EKilx2JCeRofiyPGhTCmqnuXZ6bMPiycO1rq1+sKoulAp7pGLIsTIw+1x5R+zgh5LhhA==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.63.1': + resolution: {integrity: sha512-cjkLbOlfcm3QGhMM1J5zaZjsw1GggbN6rw9UTSSRrPrR1KkcXnN7Uq9rPw34xImQ9VOY9GN+6u2Zj80B9ptkcw==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.63.1': + resolution: {integrity: sha512-Li1KdUnWGE4N3e1F/B4RTB1ms+nG4WBgjByO46pkeBVX/2UBsY53xf5vK9WygVmnH3RwncIST7lkSdLSY6P9lg==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.63.1': + resolution: {integrity: sha512-t4ZYOSoLTgwhuFMrmTMLx/+i1DQVK7HYqMc6kY46EApwi8X0nIVphzdNoThU3xt6n+N5urG1/gxBdCaKDLavfg==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.63.1': + resolution: {integrity: sha512-RgroPfMmKlD1RzSDxvwgcPiy2HNQKoYV7OmwIXDsk73uKW5t6B/V8KIy27SMv/FNXFo/oSBtWc9J0X7t91ezZg==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.63.1': + resolution: {integrity: sha512-at8QVep6S3h5Y6gSbdGU06bRY5WJkf6WUduM9YtvYMbYhB1MOFfUgc6kehitQXzOtMSaT70q7f9ydPhpqu821w==} + cpu: [x64] + os: [win32] + + '@sinclair/typebox@0.27.12': + resolution: {integrity: sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g==} + + '@standard-schema/spec@1.1.0': + resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} + + '@types/chai@5.2.3': + resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} + + '@types/deep-eql@4.0.2': + resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} + + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} + + '@types/istanbul-lib-coverage@2.0.6': + resolution: {integrity: sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==} + + '@types/istanbul-lib-report@3.0.3': + resolution: {integrity: sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA==} + + '@types/istanbul-reports@3.0.4': + resolution: {integrity: sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ==} + + '@types/jest@29.5.14': + resolution: {integrity: sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ==} + + '@types/node-fetch@2.6.13': + resolution: {integrity: sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==} + + '@types/node@18.19.130': + resolution: {integrity: sha512-GRaXQx6jGfL8sKfaIDD6OupbIHBr9jv7Jnaml9tB7l4v068PAOXqfcujMMo5PhbIs6ggR1XODELqahT2R8v0fg==} + + '@types/node@24.13.3': + resolution: {integrity: sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==} + + '@types/pg@8.11.0': + resolution: {integrity: sha512-sDAlRiBNthGjNFfvt0k6mtotoVYVQ63pA8R4EMWka7crawSR60waVYR0HAgmPRs/e2YaeJTD/43OoZ3PFw80pw==} + + '@types/stack-utils@2.0.3': + resolution: {integrity: sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw==} + + '@types/webidl-conversions@7.0.3': + resolution: {integrity: sha512-CiJJvcRtIgzadHCYXw7dqEnMNRjhGZlYK05Mj9OyktqV8uVT8fD2BFOB7S1uwBE3Kj2Z+4UyPmFw/Ixgw/LAlA==} + + '@types/whatwg-url@13.0.0': + resolution: {integrity: sha512-N8WXpbE6Wgri7KUSvrmQcqrMllKZ9uxkYWMt+mCSGwNc0Hsw9VQTW7ApqI4XNrx6/SaM2QQJCzMPDEXE058s+Q==} + + '@types/yargs-parser@21.0.3': + resolution: {integrity: sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==} + + '@types/yargs@17.0.35': + resolution: {integrity: sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg==} + + '@vercel/oidc@3.2.0': + resolution: {integrity: sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug==} + engines: {node: '>= 20'} + + '@vitest/expect@4.1.11': + resolution: {integrity: sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==} + + '@vitest/mocker@4.1.11': + resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==} + peerDependencies: + msw: ^2.4.9 + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + msw: + optional: true + vite: + optional: true + + '@vitest/pretty-format@4.1.11': + resolution: {integrity: sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==} + + '@vitest/runner@4.1.11': + resolution: {integrity: sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==} + + '@vitest/snapshot@4.1.11': + resolution: {integrity: sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==} + + '@vitest/spy@4.1.11': + resolution: {integrity: sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==} + + '@vitest/utils@4.1.11': + resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==} + + '@workflow/serde@4.1.0': + resolution: {integrity: sha512-pav4F2BoirECWR7Nf1TKt+2eETcBj7jj4cBefQ8VXQCA6NPkaKeLfj/zMgi+3zYV5ZIBT4GuUiphsj0/b9hPQQ==} + + abort-controller@3.0.0: + resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==} + engines: {node: '>=6.5'} + + acorn@8.18.0: + resolution: {integrity: sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==} + engines: {node: '>=0.4.0'} + hasBin: true + + afinn-165-financialmarketnews@3.0.0: + resolution: {integrity: sha512-0g9A1S3ZomFIGDTzZ0t6xmv4AuokBvBmpes8htiyHpH7N4xDmvSQL6UxL/Zcs2ypRb3VwgCscaD8Q3zEawKYhw==} + + afinn-165@2.0.2: + resolution: {integrity: sha512-mJ/RLUfpXfQA6bzugv+bBsc/QYkVrKaLYeS8fWBpKbTCsonv4iuV9ET0fgReEunm9vKLkaNgnekuSNlTC3WQ1Q==} + + agent-base@6.0.2: + resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==} + engines: {node: '>= 6.0.0'} + + agentkeepalive@4.6.0: + resolution: {integrity: sha512-kja8j7PjmncONqaTsB8fQ+wE2mSU2DJ9D4XKoJ5PFWIdRMa6SLSN1ff4mOr4jCbfRSsxR4keIiySJU0N9T5hIQ==} + engines: {node: '>= 8.0.0'} + + ai@7.0.93: + resolution: {integrity: sha512-CJss6zb9mlltk/mCr8qom20NBnqEQxVawkqwtT62tCwsxilZpXfHNRMRwcS3XRpzdP1kEluVuDBUayYWEEd95g==} + engines: {node: '>=22'} + peerDependencies: + zod: ^3.25.76 || ^4.1.8 + + ansi-styles@4.3.0: + resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} + engines: {node: '>=8'} + + ansi-styles@5.2.0: + resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==} + engines: {node: '>=10'} + + any-promise@1.3.0: + resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} + + apparatus@0.0.10: + resolution: {integrity: sha512-KLy/ugo33KZA7nugtQ7O0E1c8kQ52N3IvD/XgIh4w/Nr28ypfkwDfA67F1ev4N1m5D+BOk1+b2dEJDfpj/VvZg==} + engines: {node: '>=0.2.6'} + + assertion-error@2.0.1: + resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} + engines: {node: '>=12'} + + asynckit@0.4.0: + resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} + + axios@1.20.0: + resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==} + + base64-js@1.5.1: + resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} + + better-sqlite3@12.11.1: + resolution: {integrity: sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==} + engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x} + + bindings@1.5.0: + resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==} + + bl@4.1.0: + resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==} + + braces@3.0.3: + resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} + engines: {node: '>=8'} + + bson@7.3.2: + resolution: {integrity: sha512-1w0ra+ho1cuE+w8jzwgzTFIimFtCfZeCoOsvIPQg6uyFCsp8M29U7bNNf5GrFh88TXbYg1g3TyKUGpd6O7q6zA==} + engines: {node: '>=20.19.0'} + + buffer-writer@2.0.0: + resolution: {integrity: sha512-a7ZpuTZU1TRtnwyCNW3I5dc0wWNC3VR9S++Ewyk2HHZdrO3CQJqSpd+95Us590V6AL7JqUAH2IwZ/398PmNFgw==} + engines: {node: '>=4'} + + buffer@5.7.1: + resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} + + bundle-require@5.1.0: + resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + peerDependencies: + esbuild: '>=0.18' + + cac@6.7.14: + resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} + engines: {node: '>=8'} + + call-bind-apply-helpers@1.0.2: + resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==} + engines: {node: '>= 0.4'} + + chai@6.2.2: + resolution: {integrity: sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==} + engines: {node: '>=18'} + + chalk@4.1.2: + resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} + engines: {node: '>=10'} + + chokidar@4.0.3: + resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==} + engines: {node: '>= 14.16.0'} + + chownr@1.1.4: + resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==} + + ci-info@3.9.0: + resolution: {integrity: sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==} + engines: {node: '>=8'} + + cluster-key-slot@1.1.2: + resolution: {integrity: sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==} + engines: {node: '>=0.10.0'} + + color-convert@2.0.1: + resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} + engines: {node: '>=7.0.0'} + + color-name@1.1.4: + resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + + combined-stream@1.0.8: + resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} + engines: {node: '>= 0.8'} + + commander@4.1.1: + resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==} + engines: {node: '>= 6'} + + compromise@14.16.0: + resolution: {integrity: sha512-4DFYl/Hl7sW4XWUDfx9S5vxqyYKpZDwwqrpXsQv5acdbVP+joKceIcIaLb0lhVWUpDBV0OnExk/o/dnYUwXnhQ==} + engines: {node: '>=12.0.0'} + + confbox@0.1.8: + resolution: {integrity: sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==} + + consola@3.4.2: + resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==} + engines: {node: ^14.18.0 || >=16.10.0} + + convert-source-map@2.0.0: + resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} + + crossws@0.4.12: + resolution: {integrity: sha512-aypfsr6t0uNvkqaZc6zvBfXzC6pLI0/sIulpkV6RwCVtZqG5ebBzv4weImKK0VNCj91Wl9F5j7p5WU4MNrybng==} + peerDependencies: + srvx: '>=0.11.5' + peerDependenciesMeta: + srvx: + optional: true + + db0@0.4.1: + resolution: {integrity: sha512-6RBY/bSn42UrqATwsiULj2uYFyEykB3XeA/NLIVQeHNXlYV6D4Idxx3/aa6k5Y45Dwzx7sygeLotnqHWSeURYA==} + + debug@4.4.3: + resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} + engines: {node: '>=6.0'} + peerDependencies: + supports-color: '*' + peerDependenciesMeta: + supports-color: + optional: true + + decompress-response@6.0.0: + resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==} + engines: {node: '>=10'} + + deep-extend@0.6.0: + resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==} + engines: {node: '>=4.0.0'} + + delayed-stream@1.0.0: + resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} + engines: {node: '>=0.4.0'} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + diff-sequences@29.6.3: + resolution: {integrity: sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + dotenv@17.4.2: + resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==} + engines: {node: '>=12'} + + dunder-proto@1.0.1: + resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} + engines: {node: '>= 0.4'} + + efrt@2.7.0: + resolution: {integrity: sha512-/RInbCy1d4P6Zdfa+TMVsf/ufZVotat5hCw3QXmWtjU+3pFEOvOQ7ibo3aIxyCJw2leIeAMjmPj+1SLJiCpdrQ==} + engines: {node: '>=12.0.0'} + + end-of-stream@1.4.5: + resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==} + + env-runner@0.2.1: + resolution: {integrity: sha512-2iDP2DfheAMMAKeXBggEuFmpSq+1Xs6wQoHba1g65pZFXlC3VHD1O6/tgVzS6GQLv+P2koPKZPKgKhXkigNBdg==} + hasBin: true + + es-define-property@1.0.1: + resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==} + engines: {node: '>= 0.4'} + + es-errors@1.3.0: + resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==} + engines: {node: '>= 0.4'} + + es-module-lexer@2.3.2: + resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + + es-object-atoms@1.1.2: + resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==} + engines: {node: '>= 0.4'} + + es-set-tostringtag@2.1.0: + resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} + engines: {node: '>= 0.4'} + + esbuild@0.27.7: + resolution: {integrity: sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w==} + engines: {node: '>=18'} + hasBin: true + + escape-string-regexp@2.0.0: + resolution: {integrity: sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==} + engines: {node: '>=8'} + + estree-walker@3.0.3: + resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} + + eve@0.52.2: + resolution: {integrity: sha512-FM3aC2A3SCKQxtyhSNR5+CaIVlKJmTGb7rCqcuHEhZShDKo1IXCTt/F7r4toqkLDG6lW7VcStTku77KWiosLfg==} + engines: {node: '>=24'} + hasBin: true + peerDependencies: + '@opentelemetry/api': ^1.0.0 + ai: ^7.0.82 + braintrust: ^3.0.0 + just-bash: ^3.1.0 + microsandbox: ^0.5.0 + peerDependenciesMeta: + '@opentelemetry/api': + optional: true + braintrust: + optional: true + just-bash: + optional: true + microsandbox: + optional: true + + event-target-shim@5.0.1: + resolution: {integrity: sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==} + engines: {node: '>=6'} + + eventsource-parser@3.1.1: + resolution: {integrity: sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==} + engines: {node: '>=18.0.0'} + + expand-template@2.0.3: + resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==} + engines: {node: '>=6'} + + expect-type@1.4.0: + resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} + engines: {node: '>=12.0.0'} + + expect@29.7.0: + resolution: {integrity: sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + exsolve@1.1.1: + resolution: {integrity: sha512-9U/jZUgjnSGyntRr6y5Muu1MJcwFl6kPu7k8qLF0IMNfLqvw0NZ4nnVDq0RVoZ0RvCyumib4Ez3KYrVfilrw+g==} + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + file-uri-to-path@1.0.0: + resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==} + + fill-range@7.1.1: + resolution: {integrity: sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==} + engines: {node: '>=8'} + + 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==} + engines: {node: '>=4.0'} + peerDependencies: + debug: '*' + peerDependenciesMeta: + debug: + optional: true + + form-data-encoder@1.7.2: + resolution: {integrity: sha512-qfqtYan3rxrnCk1VYaA4H+Ms9xdpPqvLZa6xmMgFvhO32x7/3J/ExcTd6qpxM0vH2GdMI+poehyBZvqfMTto8A==} + + form-data@4.0.6: + resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==} + engines: {node: '>= 6'} + + formdata-node@4.4.1: + resolution: {integrity: sha512-0iirZp3uVDjVGt9p49aTaqjk84TrglENEDuqfdlZQ1roC9CWlPk6Avf8EEnZNcAqPonwkG35x4n3ww/1THYAeQ==} + engines: {node: '>= 12.20'} + + fs-constants@1.0.0: + resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==} + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + function-bind@1.1.2: + resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==} + + get-intrinsic@1.3.0: + resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} + engines: {node: '>= 0.4'} + + get-proto@1.0.1: + resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==} + engines: {node: '>= 0.4'} + + github-from-package@0.0.0: + resolution: {integrity: sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==} + + gopd@1.2.0: + resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==} + engines: {node: '>= 0.4'} + + graceful-fs@4.2.11: + resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} + + grad-school@0.0.5: + resolution: {integrity: sha512-rXunEHF9M9EkMydTBux7+IryYXEZinRk6g8OBOGDBzo/qWJjhTxy86i5q7lQYpCLHN8Sqv1XX3OIOc7ka2gtvQ==} + engines: {node: '>=8.0.0'} + + h3@2.0.1-rc.31: + resolution: {integrity: sha512-AG7qZzF99a0BSYoXT3evJgIhwSIUKow7R+hwkLRZS06WJ9nbSb7QXUDgs1ByBjp6svTvl++N/GKA7I9YPz9cQQ==} + engines: {node: '>=20.11.1'} + hasBin: true + peerDependencies: + crossws: ^0.4.12 + ocache: '>=0.3.0' + peerDependenciesMeta: + crossws: + optional: true + ocache: + optional: true + + has-flag@4.0.0: + resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} + engines: {node: '>=8'} + + has-symbols@1.1.0: + resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} + engines: {node: '>= 0.4'} + + has-tostringtag@1.0.2: + resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} + engines: {node: '>= 0.4'} + + hasown@2.0.4: + resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} + engines: {node: '>= 0.4'} + + hookable@6.1.1: + resolution: {integrity: sha512-U9LYDy1CwhMCnprUfeAZWZGByVbhd54hwepegYTK7Pi5NvqEj63ifz5z+xukznehT7i6NIZRu89Ay1AZmRsLEQ==} + + https-proxy-agent@5.0.1: + resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==} + engines: {node: '>= 6'} + + httpxy@0.5.5: + resolution: {integrity: sha512-uDjmnPyp1q4Sgzf3w+J/Fc6UqcCEj0x4Wjp7OqK5dGhNeDgpyrAmnS6ey8QWrX3SWDon2DMKf9sBa5X9+CVyMA==} + + humanize-ms@1.2.1: + resolution: {integrity: sha512-Fl70vYtsAFb/C06PTS9dZBo7ihau+Tu/DNCk/OyHhea07S+aeMWpFFkUaXRa8fI+ScZbEI8dfSxwY7gxZ9SAVQ==} + + ieee754@1.2.1: + resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} + + inherits@2.0.4: + resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} + + ini@1.3.8: + resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==} + + is-number@7.0.0: + resolution: {integrity: sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==} + engines: {node: '>=0.12.0'} + + jest-diff@29.7.0: + resolution: {integrity: sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-get-type@29.6.3: + resolution: {integrity: sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-matcher-utils@29.7.0: + resolution: {integrity: sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-message-util@29.7.0: + resolution: {integrity: sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + jest-util@29.7.0: + resolution: {integrity: sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + joycon@3.1.1: + resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==} + engines: {node: '>=10'} + + js-tokens@4.0.0: + resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + + json-schema@0.4.0: + resolution: {integrity: sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==} + + kareem@3.3.0: + resolution: {integrity: sha512-kpSuLD3/7RenBnjnJdOHXCKC8dTd1JzeOiJhN0necWWci6cC+qX+VuwPnMVgb+a4+KNJSfgqahpnfWaeDXCimw==} + engines: {node: '>=18.0.0'} + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + 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.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + 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.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + + 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.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + lilconfig@3.1.3: + resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==} + engines: {node: '>=14'} + + lines-and-columns@1.2.4: + resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} + + load-tsconfig@0.2.5: + resolution: {integrity: sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + + magic-string@0.30.21: + resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==} + + math-intrinsics@1.1.0: + resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==} + engines: {node: '>= 0.4'} + + mem0ai@3.1.8: + resolution: {integrity: sha512-K6GMfW0Yy7aaOBHPOX8bGO3+vuO3wvNH1SOJWDgK4QkSbPE8RM+XMLY8mNSvBPBggzHlrxBdD2I1Lwz9gCqzFw==} + engines: {node: '>=18'} + peerDependencies: + '@anthropic-ai/sdk': ^0.40.1 + '@aws-sdk/client-bedrock-runtime': '>=3.0.0 <3.968.0' + '@aws-sdk/client-neptune-graph': '>=3.0.0 <3.968.0' + '@aws-sdk/client-s3vectors': 3.967.0 + '@azure/identity': ^4.0.0 + '@azure/search-documents': ^12.0.0 + '@cloudflare/workers-types': ^4.20250504.0 + '@databricks/sql': ^1.16.0 + '@elastic/elasticsearch': ^9.0.0 + '@google-cloud/aiplatform': ^6.8.0 + '@google/genai': ^1.40.0 + '@huggingface/transformers': ^3.0.0 || ^4.0.0 + '@langchain/core': ^1.1.47 + '@mistralai/mistralai': ^1.5.2 + '@mochow/mochow-sdk-node': ^2.1.5 + '@opensearch-project/opensearch': ^3.5.1 + '@pinecone-database/pinecone': ^8.0.0 + '@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 + '@upstash/vector': ^1.2.3 + '@zilliz/milvus2-sdk-node': ^2.4.0 || ^3.0.0 + better-sqlite3: ^12.6.2 + cassandra-driver: 4.8.0 + chromadb: ^3.5.0 + cloudflare: ^4.2.0 + cohere-ai: ^7.17.0 || ^8.0.0 + compromise: ^14.0.0 + fastembed: ^2.1.0 + groq-sdk: 0.3.0 + iovalkey: ^0.3.3 + mongodb: ^7.0.0 + mysql2: ^3.0.0 + natural: ^8.0.1 + ollama: ^0.5.14 + oracledb: ^6.5.0 || ^7.0.0 + pg: 8.11.3 + redis: ^4.6.13 + weaviate-client: ^3.0.0 + zeroentropy: ^0.1.0-alpha.10 + peerDependenciesMeta: + '@anthropic-ai/sdk': + optional: true + '@aws-sdk/client-bedrock-runtime': + optional: true + '@aws-sdk/client-neptune-graph': + optional: true + '@aws-sdk/client-s3vectors': + optional: true + '@azure/identity': + optional: true + '@azure/search-documents': + optional: true + '@databricks/sql': + optional: true + '@elastic/elasticsearch': + optional: true + '@google-cloud/aiplatform': + optional: true + '@google/genai': + optional: true + '@huggingface/transformers': + optional: true + '@langchain/core': + optional: true + '@mistralai/mistralai': + optional: true + '@mochow/mochow-sdk-node': + optional: true + '@opensearch-project/opensearch': + optional: true + '@pinecone-database/pinecone': + optional: true + '@qdrant/js-client-rest': + optional: true + '@supabase/supabase-js': + optional: true + '@turbopuffer/turbopuffer': + optional: true + '@upstash/vector': + optional: true + '@zilliz/milvus2-sdk-node': + optional: true + cassandra-driver: + optional: true + chromadb: + optional: true + cloudflare: + optional: true + cohere-ai: + optional: true + fastembed: + optional: true + groq-sdk: + optional: true + iovalkey: + optional: true + mongodb: + optional: true + mysql2: + optional: true + ollama: + optional: true + oracledb: + optional: true + redis: + optional: true + weaviate-client: + optional: true + zeroentropy: + optional: true + + memjs@1.3.2: + resolution: {integrity: sha512-qUEg2g8vxPe+zPn09KidjIStHPtoBO8Cttm8bgJFWWabbsjQ9Av9Ky+6UcvKx6ue0LLb/LEhtcyQpRyKfzeXcg==} + engines: {node: '>=0.10.0'} + + memory-pager@1.5.0: + resolution: {integrity: sha512-ZS4Bp4r/Zoeq6+NLJpP+0Zzm0pR8whtGPf1XExKLJBAczGMnSi3It14OiNCStjQjM6NU1okjQGSxgEZN8eBYKg==} + + micromatch@4.0.8: + resolution: {integrity: sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==} + engines: {node: '>=8.6'} + + mime-db@1.52.0: + resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==} + engines: {node: '>= 0.6'} + + mime-types@2.1.35: + resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==} + engines: {node: '>= 0.6'} + + mimic-response@3.1.0: + resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==} + engines: {node: '>=10'} + + minimist@1.2.8: + resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} + + mkdirp-classic@0.5.3: + resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==} + + mlly@1.8.2: + resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==} + + mongodb-connection-string-url@7.0.2: + resolution: {integrity: sha512-ZoS07RoFqpKYQwAk59qmrx8+jJHNHU30UjlU96QktiGn1ltvDr+vCznLX5DiUBLEpMAHatHNWV1nM/74ul66kA==} + engines: {node: '>=20.19.0'} + + mongodb@7.5.0: + resolution: {integrity: sha512-5FnrEDLnvp6ycUOGLNLLU33BfCx2qmp2mJjGPDwKLruYsVzXVSK5fsGpoDXvsXJwBfBsD7ebMRdawbDxC2814g==} + engines: {node: '>=20.19.0'} + peerDependencies: + '@aws-sdk/credential-providers': ^3.806.0 + '@mongodb-js/zstd': ^7.0.0 + gcp-metadata: ^7.0.1 + kerberos: ^7.0.0 + mongodb-client-encryption: ^7.2.0 + snappy: ^7.3.2 + socks: ^2.8.6 + peerDependenciesMeta: + '@aws-sdk/credential-providers': + optional: true + '@mongodb-js/zstd': + optional: true + gcp-metadata: + optional: true + kerberos: + optional: true + mongodb-client-encryption: + optional: true + snappy: + optional: true + socks: + optional: true + + mongoose@9.9.5: + resolution: {integrity: sha512-t/kUoeDjlHmav7yCaq//YKU3wiIgUPaTj4GrluiTHUw4jQ77/CXtdMDSor4f1u3SKLhIK6NgCF+AzzUqU02Aag==} + engines: {node: '>=20.19.0'} + + mpath@0.9.0: + resolution: {integrity: sha512-ikJRQTk8hw5DEoFVxHG1Gn9T/xcjtdnOKIU1JTmGjZZlg9LST2mBLmcX3/ICIbgJydT2GOc15RnNy5mHmzfSew==} + engines: {node: '>=4.0.0'} + + mquery@6.0.0: + resolution: {integrity: sha512-b2KQNsmgtkscfeDgkYMcWGn9vZI9YoXh802VDEwE6qc50zxBFQ0Oo8ROkawbPAsXCY1/Z1yp0MagqsZStPWJjw==} + engines: {node: '>=20.19.0'} + + ms@2.1.3: + resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + + 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==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + napi-build-utils@2.0.0: + resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==} + + natural@8.1.1: + resolution: {integrity: sha512-Ucb+lsUcGxUqu3rn8cwHjT6gJQosO63nIX/aBQXB3+IDkNbFV7PuviysO+Rzz3aKn7PZhPj3bNF4PS9gDVjYCQ==} + engines: {node: '>=0.4.10'} + + nf3@0.3.24: + resolution: {integrity: sha512-HxLK4bo+5jNsEETZp4w3tJblHOA9MCBY14IN9nZJJV8JDxt9yNIYxuBuLMjTAR5GFa3HL61+8VQDUrXv3/C8fw==} + + nitro@3.0.260903-beta: + resolution: {integrity: sha512-54gANPi62O8rfMvepiJUVuIzEIinYfpeHbebywlLxvVTgIYXDwSvpaU9Id+0sJOBjBx0wC1/CVYXJkH7SY+l0g==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + node-abi@3.96.0: + resolution: {integrity: sha512-rebQ/lz7i0EkoLzUVSrKRzA69zMkwLp95kKMWoMDkkM00Suxz0D7zEQPwRml5fQum24mj7bPvmlgLAmu2JCiYg==} + engines: {node: '>=10'} + + node-domexception@1.0.0: + resolution: {integrity: sha512-/jKZoMpw0F8GRwl4/eLROPA3cfcXtLApP0QzLmUT/HuPCZWyB7IY9ZrMeKw2O/nFIqPQB3PVM9aYm0F312AXDQ==} + engines: {node: '>=10.5.0'} + deprecated: Use your platform's native DOMException instead + + node-fetch@2.7.0: + resolution: {integrity: sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==} + engines: {node: 4.x || >=6.0.0} + peerDependencies: + encoding: ^0.1.0 + peerDependenciesMeta: + encoding: + optional: true + + object-assign@4.1.1: + resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} + engines: {node: '>=0.10.0'} + + obuf@1.1.2: + resolution: {integrity: sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg==} + + obug@2.1.4: + resolution: {integrity: sha512-4a+OsYv9UktOJKE+l1A4OufDgdRF9PifWj+tJnHURo/P+WOxpG4GzUFL9qCalmWauao6ogiG+QvnCovwPoyAWA==} + engines: {node: '>=12.20.0'} + + ocache@0.3.0: + resolution: {integrity: sha512-RS/9P0zeBb0gDJmadGERLH8lZNXK7xbufTDhclkXGvFGTsj0G4M5/cLk+mizcERH29mLXNnocfB5wjcK70wGJg==} + + once@1.4.0: + resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} + + openai@4.104.0: + resolution: {integrity: sha512-p99EFNsA/yX6UhVO93f5kJsDRLAg+CTA2RBqdHK4RtK8u5IJw32Hyb2dTGKbnnFmnuoBv5r7Z2CURI9sGZpSuA==} + hasBin: true + peerDependencies: + ws: ^8.18.0 + zod: ^3.23.8 + peerDependenciesMeta: + ws: + optional: true + zod: + optional: true + + packet-reader@1.0.0: + resolution: {integrity: sha512-HAKu/fG3HpHFO0AA8WE8q2g+gBJaZ9MG7fcKk+IJPLTGAD6Psw4443l+9DGRbOIh3/aXr7Phy0TjilYivJo5XQ==} + + pathe@2.0.3: + resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} + + pg-cloudflare@1.4.0: + resolution: {integrity: sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==} + + pg-connection-string@2.14.0: + resolution: {integrity: sha512-XwWDGcLRGCXAR8F/AM5bG7Q+A3Wm2s6QeEjlOKZLlH3UYcguiqCWKyWXVag5TLTIjR7oOJUY8kcADaZgWPyLeg==} + + pg-int8@1.0.1: + resolution: {integrity: sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==} + engines: {node: '>=4.0.0'} + + pg-numeric@1.0.2: + resolution: {integrity: sha512-BM/Thnrw5jm2kKLE5uJkXqqExRUY/toLHda65XgFTBTFYZyopbKjBe29Ii3RbkvlsMoFwD+tHeGaCjjv0gHlyw==} + engines: {node: '>=4'} + + pg-pool@3.14.0: + resolution: {integrity: sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==} + peerDependencies: + pg: '>=8.0' + + pg-protocol@1.16.0: + resolution: {integrity: sha512-sILXutLVjCLjcDuOmvhX5e2Z4cS5qG/6Bu3VkpFwdf/633ElGLpEh9bgmuI5I4sqKqkifQiGyiCcx1HdtrK7tg==} + + pg-types@2.2.0: + resolution: {integrity: sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==} + engines: {node: '>=4'} + + pg-types@4.1.0: + 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.23.0: + resolution: {integrity: sha512-Ip2EQCngowJLGOfCwkFhPXU7/ljlhn6Rxlmy4XYfL2Y+vyRM59+8uR2xqRWKdYmbXmxCFOAmKxBuSUCdF34qLg==} + engines: {node: '>= 16.0.0'} + peerDependencies: + pg-native: '>=3.0.1' + peerDependenciesMeta: + pg-native: + optional: true + + pgpass@1.0.5: + resolution: {integrity: sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==} + + pgpass@1.0.6: + resolution: {integrity: sha512-lqIfH7bdgsxHAY/ZnUOwm+aCFKrsHBDhSFuk9O0B9uCqJAIkrKTo/+LQqLPLUS4e04+jCmQVikxE3QipH5chPw==} + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@2.3.2: + resolution: {integrity: sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==} + engines: {node: '>=8.6'} + + 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'} + + pkg-types@1.3.1: + resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==} + + postcss-load-config@6.0.1: + resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==} + engines: {node: '>= 18'} + peerDependencies: + jiti: '>=1.21.0' + postcss: '>=8.0.9' + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + jiti: + optional: true + postcss: + optional: true + tsx: + optional: true + yaml: + optional: true + + postcss@8.5.28: + resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==} + engines: {node: ^10 || ^12 || >=14} + + postgres-array@2.0.0: + resolution: {integrity: sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==} + engines: {node: '>=4'} + + postgres-array@3.0.4: + resolution: {integrity: sha512-nAUSGfSDGOaOAEGwqsRY27GPOea7CNipJPOA7lPbdEpx5Kg3qzdP0AaWC5MlhTWV9s4hFX39nomVZ+C4tnGOJQ==} + engines: {node: '>=12'} + + postgres-bytea@1.0.1: + resolution: {integrity: sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==} + engines: {node: '>=0.10.0'} + + postgres-bytea@3.0.0: + resolution: {integrity: sha512-CNd4jim9RFPkObHSjVHlVrxoVQXz7quwNFpz7RY1okNNme49+sVyiTvTRobiLV548Hx/hb1BG+iE7h9493WzFw==} + engines: {node: '>= 6'} + + postgres-date@1.0.7: + resolution: {integrity: sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==} + engines: {node: '>=0.10.0'} + + postgres-date@2.1.0: + resolution: {integrity: sha512-K7Juri8gtgXVcDfZttFKVmhglp7epKb1K4pgrkLxehjqkrgPhfG6OO8LHLkfaqkbpjNRnra018XwAr1yQFWGcA==} + engines: {node: '>=12'} + + postgres-interval@1.2.0: + resolution: {integrity: sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==} + engines: {node: '>=0.10.0'} + + postgres-interval@3.0.0: + resolution: {integrity: sha512-BSNDnbyZCXSxgA+1f5UU2GmwhoI0aU5yMxRGO8CdFEcY2BQF9xm/7MqKnYoM1nJDk8nONNWDk9WeSmePFhQdlw==} + engines: {node: '>=12'} + + postgres-range@1.1.4: + resolution: {integrity: sha512-i/hbxIE9803Alj/6ytL7UHQxRvZkI9O4Sy+J3HGc4F4oo/2eQAjTSNJ0bfxyse3bH0nuVesCk+3IRLaMtG3H6w==} + + prebuild-install@7.1.3: + resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==} + engines: {node: '>=10'} + deprecated: No longer maintained. Please contact the author of the relevant native addon; alternatives are available. + hasBin: true + + pretty-format@29.7.0: + resolution: {integrity: sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ==} + engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0} + + proxy-from-env@2.1.0: + resolution: {integrity: sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==} + engines: {node: '>=10'} + + pump@3.0.4: + resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==} + + punycode@2.3.1: + resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} + engines: {node: '>=6'} + + rc@1.2.8: + resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==} + hasBin: true + + react-is@18.3.1: + resolution: {integrity: sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg==} + + readable-stream@3.6.2: + resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==} + engines: {node: '>= 6'} + + readdirp@4.1.2: + resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} + engines: {node: '>= 14.18.0'} + + redis@5.12.1: + resolution: {integrity: sha512-LDsoVvb/CpoV9EN3FXvgvSHNJWuCIzl9MiO3ppOevuGLpSGJhwfQjpEwfFJcQvNSddHADDdZaWx0HnmMxRXG7g==} + engines: {node: '>= 18.19.0'} + + resolve-from@5.0.0: + resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==} + engines: {node: '>=8'} + + rolldown@1.2.7: + resolution: {integrity: sha512-g0EtLvBjTUB7jhyV0S/TCup3v/XSVl45vUIGbOGU4QPiyjTenCe4mKuFvW9fEgYmS2Fo42AUssRmNuMziXdrig==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + rollup@4.63.1: + resolution: {integrity: sha512-3Df9jsstwhccuEfmAMi9l8XUh/GOkVObmFTU7CCVBysEbcOZLl84jCtaAZMcPiMz2EGKsATzQcU+Xr3n/wU6cg==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + + rou3@0.9.2: + resolution: {integrity: sha512-3SOzvaAg8rkHrXtRjpCvCvbyO5to9oOO27Z/XqHEYXfMRVSw/qMIVdmaOk9W2lcRLtR6dlqTjo9hDeJk70QBYQ==} + + safe-buffer@5.2.1: + resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} + + safe-stable-stringify@2.5.0: + resolution: {integrity: sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==} + engines: {node: '>=10'} + + semver@7.8.5: + resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} + engines: {node: '>=10'} + hasBin: true + + sift@17.1.3: + resolution: {integrity: sha512-Rtlj66/b0ICeFzYTuNvX/EF1igRbbnGSvEyT79McoZa/DeGhMyC5pWKOEsZKnpkqtSeovd5FL/bjHWC3CIIvCQ==} + + siginfo@2.0.0: + resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + + simple-concat@1.0.1: + resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==} + + simple-get@4.0.1: + resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==} + + slash@3.0.0: + resolution: {integrity: sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q==} + engines: {node: '>=8'} + + source-map-js@1.2.1: + resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} + engines: {node: '>=0.10.0'} + + source-map@0.7.6: + resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==} + engines: {node: '>= 12'} + + sparse-bitfield@3.0.3: + resolution: {integrity: sha512-kvzhi7vqKTfkh0PZU+2D2PIllw2ymqJKujUcyPMd9Y75Nv4nPbGJZXNhxsgdQab2BmlDct1YnfQCguEvHr7VsQ==} + + split2@4.2.0: + resolution: {integrity: sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==} + engines: {node: '>= 10.x'} + + srvx@1.0.4: + resolution: {integrity: sha512-eZmYaxUfZSo7/8m8UdsHRJNmTLSCTPPom9d7a60vMmuVeZvwhbvflRR+00/CxTCjMOFa5+H8tgBeNDVZ+w7AAQ==} + engines: {node: '>=20.16.0'} + hasBin: true + + stack-utils@2.0.6: + resolution: {integrity: sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==} + engines: {node: '>=10'} + + stackback@0.0.2: + resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} + + std-env@4.2.0: + resolution: {integrity: sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==} + + stopwords-iso@1.1.0: + resolution: {integrity: sha512-I6GPS/E0zyieHehMRPQcqkiBMJKGgLta+1hREixhoLPqEA0AlVFiC43dl8uPpmkkeRdDMzYRWFWk5/l9x7nmNg==} + engines: {node: '>=0.10.0'} + + string_decoder@1.3.0: + resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} + + strip-json-comments@2.0.1: + resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==} + engines: {node: '>=0.10.0'} + + sucrase@3.35.1: + resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==} + engines: {node: '>=16 || 14 >=14.17'} + hasBin: true + + suffix-thumb@5.0.2: + resolution: {integrity: sha512-I5PWXAFKx3FYnI9a+dQMWNqTxoRt6vdBdb0O+BJ1sxXCWtSoQCusc13E58f+9p4MYx/qCnEMkD5jac6K2j3dgA==} + + supports-color@7.2.0: + resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} + engines: {node: '>=8'} + + sylvester@0.0.21: + resolution: {integrity: sha512-yUT0ukFkFEt4nb+NY+n2ag51aS/u9UHXoZw+A4jgD77/jzZsBoSDHuqysrVCBC4CYR4TYvUJq54ONpXgDBH8tA==} + engines: {node: '>=0.2.6'} + + tar-fs@2.1.5: + resolution: {integrity: sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==} + + tar-stream@2.2.0: + resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==} + engines: {node: '>=6'} + + thenify-all@1.6.0: + resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==} + engines: {node: '>=0.8'} + + thenify@3.3.1: + resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==} + + tinybench@2.9.0: + resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + + tinyexec@0.3.2: + resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} + + tinyexec@1.3.1: + resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} + engines: {node: '>=18'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + tinyrainbow@3.1.1: + resolution: {integrity: sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==} + engines: {node: '>=14.0.0'} + + to-regex-range@5.0.1: + resolution: {integrity: sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==} + engines: {node: '>=8.0'} + + tr46@0.0.3: + resolution: {integrity: sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==} + + tr46@5.1.1: + resolution: {integrity: sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==} + engines: {node: '>=18'} + + tree-kill@1.2.2: + resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==} + hasBin: true + + ts-interface-checker@0.1.13: + resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==} + + tsup@8.5.1: + resolution: {integrity: sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==} + engines: {node: '>=18'} + hasBin: true + peerDependencies: + '@microsoft/api-extractor': ^7.36.0 + '@swc/core': ^1 + postcss: ^8.4.12 + typescript: '>=4.5.0' + peerDependenciesMeta: + '@microsoft/api-extractor': + optional: true + '@swc/core': + optional: true + postcss: + optional: true + typescript: + optional: true + + tunnel-agent@0.6.0: + resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==} + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + ufo@1.6.4: + resolution: {integrity: sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==} + + underscore@1.13.8: + resolution: {integrity: sha512-DXtD3ZtEQzc7M8m4cXotyHR+FAS18C64asBYY5vqZexfYryNNnDc02W4hKg3rdQuqOYas1jkseX0+nZXjTXnvQ==} + + undici-types@5.26.5: + resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==} + + undici-types@7.18.2: + resolution: {integrity: sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==} + + undici@7.29.1: + resolution: {integrity: sha512-RYONW2MeafgYlkVOKYKkA/Ag7BmXqgIWCa8t1m0JcxrQg9pI9lEqRhAOruOBCbAohOa/gkCF+iPi9hrgvTzu6Q==} + engines: {node: '>=20.18.1'} + + undici@8.9.0: + resolution: {integrity: sha512-aWZpUj7XoGonMClx4gdDRfgBjqeA+F473aDmROQQbM9n6PRfK/u1q/a0X4wMTgcHfT8H6fpbt98PFuDUwFg2YA==} + engines: {node: '>=22.19.0'} + + unenv@2.0.0-rc.24: + resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==} + + unstorage@2.0.0-alpha.10: + resolution: {integrity: sha512-6h1veZp8gnp4dGllf0tDijoXxDYymJu251IpKKkrSVH+QHL6tXFbwG85KM+CBHSgpkkgtPuIiZ9oLCLP5+1Evw==} + + util-deprecate@1.0.2: + resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} + + uuid@11.1.1: + resolution: {integrity: sha512-vIYxrBCC/N/K+Js3qSN88go7kIfNPssr/hHCesKCQNAjmgvYS2oqr69kIufEG+O4+PfezOH4EbIeHCfFov8ZgQ==} + hasBin: true + + uuid@13.0.2: + resolution: {integrity: sha512-vzi9uRZ926x4XV73S/4qQaTwPXM2JBj6/6lI/byHH1jOpCzb0zDbfytgA9LcN/hzb2l7WQSQnxITOVx5un/wGw==} + hasBin: true + + vite@8.2.2: + resolution: {integrity: sha512-cFKLV/PRgAUlIRm5WjMjJ86jrftzpqcgH+Us+DS8mI3CDNiH30Whrz8uHL3+MOLPAgqbMBAqWdAHAphOAM+z/Q==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.4.0 || ^0.5.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + vitest@4.1.11: + resolution: {integrity: sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==} + engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} + hasBin: true + peerDependencies: + '@edge-runtime/vm': '*' + '@opentelemetry/api': ^1.9.0 + '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 + '@vitest/browser-playwright': 4.1.11 + '@vitest/browser-preview': 4.1.11 + '@vitest/browser-webdriverio': 4.1.11 + '@vitest/coverage-istanbul': 4.1.11 + '@vitest/coverage-v8': 4.1.11 + '@vitest/ui': 4.1.11 + happy-dom: '*' + jsdom: '*' + vite: ^6.0.0 || ^7.0.0 || ^8.0.0 + peerDependenciesMeta: + '@edge-runtime/vm': + optional: true + '@opentelemetry/api': + optional: true + '@types/node': + optional: true + '@vitest/browser-playwright': + optional: true + '@vitest/browser-preview': + optional: true + '@vitest/browser-webdriverio': + optional: true + '@vitest/coverage-istanbul': + optional: true + '@vitest/coverage-v8': + optional: true + '@vitest/ui': + optional: true + happy-dom: + optional: true + jsdom: + optional: true + + web-streams-polyfill@4.0.0-beta.3: + resolution: {integrity: sha512-QW95TCTaHmsYfHDybGMwO5IJIM93I/6vTRk+daHTWFPhwh+C8Cg7j7XyKrwrj8Ib6vYXe0ocYNrmzY4xAAN6ug==} + engines: {node: '>= 14'} + + webidl-conversions@3.0.1: + resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} + + webidl-conversions@7.0.0: + resolution: {integrity: sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==} + engines: {node: '>=12'} + + whatwg-url@14.2.0: + resolution: {integrity: sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==} + engines: {node: '>=18'} + + whatwg-url@5.0.0: + resolution: {integrity: sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==} + + why-is-node-running@2.3.0: + resolution: {integrity: sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==} + engines: {node: '>=8'} + hasBin: true + + wordnet-db@3.1.14: + resolution: {integrity: sha512-zVyFsvE+mq9MCmwXUWHIcpfbrHHClZWZiVOzKSxNJruIcFn2RbY55zkhiAMMxM8zCVSmtNiViq8FsAZSFpMYag==} + engines: {node: '>=0.6.0'} + + wrappy@1.0.2: + resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} + + xtend@4.0.2: + resolution: {integrity: sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==} + engines: {node: '>=0.4'} + + zod@3.25.76: + resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==} + + zod@4.5.4: + resolution: {integrity: sha512-sC95tT5iHHH9gtpj6A81kh+NEaRAUFN+qlUPDUbRfOMvNf5QCBqsb3WgvnpVtK5Y+4UfA6KqufotuTvMGiTlsA==} + +snapshots: + + '@ai-sdk/gateway@4.0.75(zod@4.5.4)': + dependencies: + '@ai-sdk/provider': 4.0.10 + '@ai-sdk/provider-utils': 5.0.36(zod@4.5.4) + '@vercel/oidc': 3.2.0 + zod: 4.5.4 + + '@ai-sdk/provider-utils@5.0.36(zod@4.5.4)': + dependencies: + '@ai-sdk/provider': 4.0.10 + '@standard-schema/spec': 1.1.0 + '@workflow/serde': 4.1.0 + eventsource-parser: 3.1.1 + undici: 7.29.1 + zod: 4.5.4 + + '@ai-sdk/provider@4.0.10': + dependencies: + json-schema: 0.4.0 + + '@babel/code-frame@7.29.7': + dependencies: + '@babel/helper-validator-identifier': 7.29.7 + js-tokens: 4.0.0 + picocolors: 1.1.1 + + '@babel/helper-validator-identifier@7.29.7': {} + + '@cloudflare/workers-types@4.20260702.1': {} + + '@esbuild/aix-ppc64@0.27.7': + optional: true + + '@esbuild/android-arm64@0.27.7': + optional: true + + '@esbuild/android-arm@0.27.7': + optional: true + + '@esbuild/android-x64@0.27.7': + optional: true + + '@esbuild/darwin-arm64@0.27.7': + optional: true + + '@esbuild/darwin-x64@0.27.7': + optional: true + + '@esbuild/freebsd-arm64@0.27.7': + optional: true + + '@esbuild/freebsd-x64@0.27.7': + optional: true + + '@esbuild/linux-arm64@0.27.7': + optional: true + + '@esbuild/linux-arm@0.27.7': + optional: true + + '@esbuild/linux-ia32@0.27.7': + optional: true + + '@esbuild/linux-loong64@0.27.7': + optional: true + + '@esbuild/linux-mips64el@0.27.7': + optional: true + + '@esbuild/linux-ppc64@0.27.7': + optional: true + + '@esbuild/linux-riscv64@0.27.7': + optional: true + + '@esbuild/linux-s390x@0.27.7': + optional: true + + '@esbuild/linux-x64@0.27.7': + optional: true + + '@esbuild/netbsd-arm64@0.27.7': + optional: true + + '@esbuild/netbsd-x64@0.27.7': + optional: true + + '@esbuild/openbsd-arm64@0.27.7': + optional: true + + '@esbuild/openbsd-x64@0.27.7': + optional: true + + '@esbuild/openharmony-arm64@0.27.7': + optional: true + + '@esbuild/sunos-x64@0.27.7': + optional: true + + '@esbuild/win32-arm64@0.27.7': + optional: true + + '@esbuild/win32-ia32@0.27.7': + optional: true + + '@esbuild/win32-x64@0.27.7': + optional: true + + '@jest/expect-utils@29.7.0': + dependencies: + jest-get-type: 29.6.3 + + '@jest/schemas@29.6.3': + dependencies: + '@sinclair/typebox': 0.27.12 + + '@jest/types@29.6.3': + dependencies: + '@jest/schemas': 29.6.3 + '@types/istanbul-lib-coverage': 2.0.6 + '@types/istanbul-reports': 3.0.4 + '@types/node': 24.13.3 + '@types/yargs': 17.0.35 + chalk: 4.1.2 + + '@jridgewell/gen-mapping@0.3.13': + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + '@jridgewell/trace-mapping': 0.3.31 + + '@jridgewell/resolve-uri@3.1.2': {} + + '@jridgewell/sourcemap-codec@1.6.0': {} + + '@jridgewell/trace-mapping@0.3.31': + dependencies: + '@jridgewell/resolve-uri': 3.1.2 + '@jridgewell/sourcemap-codec': 1.6.0 + + '@mongodb-js/saslprep@1.5.2': + dependencies: + sparse-bitfield: 3.0.3 + + '@napi-rs/lzma-linux-x64-gnu@1.5.1': + optional: true + + '@oxc-project/types@0.148.0': {} + + '@redis/bloom@5.12.1(@redis/client@5.12.1)': + dependencies: + '@redis/client': 5.12.1 + + '@redis/client@5.12.1': + dependencies: + cluster-key-slot: 1.1.2 + + '@redis/json@5.12.1(@redis/client@5.12.1)': + dependencies: + '@redis/client': 5.12.1 + + '@redis/search@5.12.1(@redis/client@5.12.1)': + dependencies: + '@redis/client': 5.12.1 + + '@redis/time-series@5.12.1(@redis/client@5.12.1)': + dependencies: + '@redis/client': 5.12.1 + + '@rolldown/binding-android-arm-eabi@1.2.7': + optional: true + + '@rolldown/binding-android-arm64@1.2.7': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.7': + optional: true + + '@rolldown/binding-darwin-x64@1.2.7': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.7': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.7': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.7': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.7': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.7': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.7': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.7': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.7': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.7': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.7': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.7': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@rollup/rollup-android-arm-eabi@4.63.1': + optional: true + + '@rollup/rollup-android-arm64@4.63.1': + optional: true + + '@rollup/rollup-darwin-arm64@4.63.1': + optional: true + + '@rollup/rollup-darwin-x64@4.63.1': + optional: true + + '@rollup/rollup-freebsd-arm64@4.63.1': + optional: true + + '@rollup/rollup-freebsd-x64@4.63.1': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.63.1': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.63.1': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.63.1': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.63.1': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.63.1': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.63.1': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.63.1': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.63.1': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.63.1': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.63.1': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.63.1': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.63.1': + optional: true + + '@rollup/rollup-linux-x64-musl@4.63.1': + optional: true + + '@rollup/rollup-openbsd-x64@4.63.1': + optional: true + + '@rollup/rollup-openharmony-arm64@4.63.1': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.63.1': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.63.1': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.63.1': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.63.1': + optional: true + + '@sinclair/typebox@0.27.12': {} + + '@standard-schema/spec@1.1.0': {} + + '@types/chai@5.2.3': + dependencies: + '@types/deep-eql': 4.0.2 + assertion-error: 2.0.1 + + '@types/deep-eql@4.0.2': {} + + '@types/estree@1.0.9': {} + + '@types/istanbul-lib-coverage@2.0.6': {} + + '@types/istanbul-lib-report@3.0.3': + dependencies: + '@types/istanbul-lib-coverage': 2.0.6 + + '@types/istanbul-reports@3.0.4': + dependencies: + '@types/istanbul-lib-report': 3.0.3 + + '@types/jest@29.5.14': + dependencies: + expect: 29.7.0 + pretty-format: 29.7.0 + + '@types/node-fetch@2.6.13': + dependencies: + '@types/node': 24.13.3 + form-data: 4.0.6 + + '@types/node@18.19.130': + dependencies: + undici-types: 5.26.5 + + '@types/node@24.13.3': + dependencies: + undici-types: 7.18.2 + + '@types/pg@8.11.0': + dependencies: + '@types/node': 24.13.3 + pg-protocol: 1.16.0 + pg-types: 4.1.0 + + '@types/stack-utils@2.0.3': {} + + '@types/webidl-conversions@7.0.3': {} + + '@types/whatwg-url@13.0.0': + dependencies: + '@types/webidl-conversions': 7.0.3 + + '@types/yargs-parser@21.0.3': {} + + '@types/yargs@17.0.35': + dependencies: + '@types/yargs-parser': 21.0.3 + + '@vercel/oidc@3.2.0': {} + + '@vitest/expect@4.1.11': + dependencies: + '@standard-schema/spec': 1.1.0 + '@types/chai': 5.2.3 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 + chai: 6.2.2 + tinyrainbow: 3.1.1 + + '@vitest/mocker@4.1.11(vite@8.2.2(@types/node@24.13.3)(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@24.13.3)(esbuild@0.27.7) + + '@vitest/pretty-format@4.1.11': + dependencies: + tinyrainbow: 3.1.1 + + '@vitest/runner@4.1.11': + dependencies: + '@vitest/utils': 4.1.11 + pathe: 2.0.3 + + '@vitest/snapshot@4.1.11': + dependencies: + '@vitest/pretty-format': 4.1.11 + '@vitest/utils': 4.1.11 + magic-string: 0.30.21 + pathe: 2.0.3 + + '@vitest/spy@4.1.11': {} + + '@vitest/utils@4.1.11': + dependencies: + '@vitest/pretty-format': 4.1.11 + convert-source-map: 2.0.0 + tinyrainbow: 3.1.1 + + '@workflow/serde@4.1.0': {} + + abort-controller@3.0.0: + dependencies: + event-target-shim: 5.0.1 + + acorn@8.18.0: {} + + afinn-165-financialmarketnews@3.0.0: {} + + afinn-165@2.0.2: {} + + agent-base@6.0.2: + dependencies: + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + agentkeepalive@4.6.0: + dependencies: + humanize-ms: 1.2.1 + + ai@7.0.93(zod@4.5.4): + dependencies: + '@ai-sdk/gateway': 4.0.75(zod@4.5.4) + '@ai-sdk/provider': 4.0.10 + '@ai-sdk/provider-utils': 5.0.36(zod@4.5.4) + zod: 4.5.4 + + ansi-styles@4.3.0: + dependencies: + color-convert: 2.0.1 + + ansi-styles@5.2.0: {} + + any-promise@1.3.0: {} + + apparatus@0.0.10: + dependencies: + sylvester: 0.0.21 + + assertion-error@2.0.1: {} + + asynckit@0.4.0: {} + + axios@1.20.0: + dependencies: + follow-redirects: 1.16.0 + form-data: 4.0.6 + https-proxy-agent: 5.0.1 + proxy-from-env: 2.1.0 + transitivePeerDependencies: + - debug + - supports-color + + base64-js@1.5.1: {} + + better-sqlite3@12.11.1: + dependencies: + bindings: 1.5.0 + prebuild-install: 7.1.3 + + bindings@1.5.0: + dependencies: + file-uri-to-path: 1.0.0 + + bl@4.1.0: + dependencies: + buffer: 5.7.1 + inherits: 2.0.4 + readable-stream: 3.6.2 + + braces@3.0.3: + dependencies: + fill-range: 7.1.1 + + bson@7.3.2: {} + + buffer-writer@2.0.0: {} + + buffer@5.7.1: + dependencies: + base64-js: 1.5.1 + ieee754: 1.2.1 + + bundle-require@5.1.0(esbuild@0.27.7): + dependencies: + esbuild: 0.27.7 + load-tsconfig: 0.2.5 + + cac@6.7.14: {} + + call-bind-apply-helpers@1.0.2: + dependencies: + es-errors: 1.3.0 + function-bind: 1.1.2 + + chai@6.2.2: {} + + chalk@4.1.2: + dependencies: + ansi-styles: 4.3.0 + supports-color: 7.2.0 + + chokidar@4.0.3: + dependencies: + readdirp: 4.1.2 + + chownr@1.1.4: {} + + ci-info@3.9.0: {} + + cluster-key-slot@1.1.2: {} + + color-convert@2.0.1: + dependencies: + color-name: 1.1.4 + + color-name@1.1.4: {} + + combined-stream@1.0.8: + dependencies: + delayed-stream: 1.0.0 + + commander@4.1.1: {} + + compromise@14.16.0: + dependencies: + efrt: 2.7.0 + grad-school: 0.0.5 + suffix-thumb: 5.0.2 + + confbox@0.1.8: {} + + consola@3.4.2: {} + + convert-source-map@2.0.0: {} + + crossws@0.4.12(srvx@1.0.4): + optionalDependencies: + srvx: 1.0.4 + + db0@0.4.1: {} + + debug@4.4.3: + dependencies: + ms: 2.1.3 + + decompress-response@6.0.0: + dependencies: + mimic-response: 3.1.0 + + deep-extend@0.6.0: {} + + delayed-stream@1.0.0: {} + + detect-libc@2.1.2: {} + + diff-sequences@29.6.3: {} + + dotenv@17.4.2: {} + + dunder-proto@1.0.1: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-errors: 1.3.0 + gopd: 1.2.0 + + efrt@2.7.0: {} + + end-of-stream@1.4.5: + dependencies: + once: 1.4.0 + + env-runner@0.2.1: + dependencies: + crossws: 0.4.12(srvx@1.0.4) + exsolve: 1.1.1 + httpxy: 0.5.5 + srvx: 1.0.4 + + es-define-property@1.0.1: {} + + es-errors@1.3.0: {} + + es-module-lexer@2.3.2: {} + + es-object-atoms@1.1.2: + dependencies: + es-errors: 1.3.0 + + es-set-tostringtag@2.1.0: + dependencies: + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + has-tostringtag: 1.0.2 + hasown: 2.0.4 + + esbuild@0.27.7: + optionalDependencies: + '@esbuild/aix-ppc64': 0.27.7 + '@esbuild/android-arm': 0.27.7 + '@esbuild/android-arm64': 0.27.7 + '@esbuild/android-x64': 0.27.7 + '@esbuild/darwin-arm64': 0.27.7 + '@esbuild/darwin-x64': 0.27.7 + '@esbuild/freebsd-arm64': 0.27.7 + '@esbuild/freebsd-x64': 0.27.7 + '@esbuild/linux-arm': 0.27.7 + '@esbuild/linux-arm64': 0.27.7 + '@esbuild/linux-ia32': 0.27.7 + '@esbuild/linux-loong64': 0.27.7 + '@esbuild/linux-mips64el': 0.27.7 + '@esbuild/linux-ppc64': 0.27.7 + '@esbuild/linux-riscv64': 0.27.7 + '@esbuild/linux-s390x': 0.27.7 + '@esbuild/linux-x64': 0.27.7 + '@esbuild/netbsd-arm64': 0.27.7 + '@esbuild/netbsd-x64': 0.27.7 + '@esbuild/openbsd-arm64': 0.27.7 + '@esbuild/openbsd-x64': 0.27.7 + '@esbuild/openharmony-arm64': 0.27.7 + '@esbuild/sunos-x64': 0.27.7 + '@esbuild/win32-arm64': 0.27.7 + '@esbuild/win32-ia32': 0.27.7 + '@esbuild/win32-x64': 0.27.7 + + escape-string-regexp@2.0.0: {} + + estree-walker@3.0.3: + dependencies: + '@types/estree': 1.0.9 + + eve@0.52.2(ai@7.0.93(zod@4.5.4)): + dependencies: + ai: 7.0.93(zod@4.5.4) + nitro: 3.0.260903-beta + undici: 8.9.0 + + event-target-shim@5.0.1: {} + + eventsource-parser@3.1.1: {} + + expand-template@2.0.3: {} + + expect-type@1.4.0: {} + + expect@29.7.0: + dependencies: + '@jest/expect-utils': 29.7.0 + jest-get-type: 29.6.3 + jest-matcher-utils: 29.7.0 + jest-message-util: 29.7.0 + jest-util: 29.7.0 + + exsolve@1.1.1: {} + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + file-uri-to-path@1.0.0: {} + + fill-range@7.1.1: + dependencies: + to-regex-range: 5.0.1 + + fix-dts-default-cjs-exports@1.0.1: + dependencies: + magic-string: 0.30.21 + mlly: 1.8.2 + rollup: 4.63.1 + + follow-redirects@1.16.0: {} + + form-data-encoder@1.7.2: {} + + form-data@4.0.6: + dependencies: + asynckit: 0.4.0 + combined-stream: 1.0.8 + es-set-tostringtag: 2.1.0 + hasown: 2.0.4 + mime-types: 2.1.35 + + formdata-node@4.4.1: + dependencies: + node-domexception: 1.0.0 + web-streams-polyfill: 4.0.0-beta.3 + + fs-constants@1.0.0: {} + + fsevents@2.3.3: + optional: true + + function-bind@1.1.2: {} + + get-intrinsic@1.3.0: + dependencies: + call-bind-apply-helpers: 1.0.2 + es-define-property: 1.0.1 + es-errors: 1.3.0 + es-object-atoms: 1.1.2 + function-bind: 1.1.2 + get-proto: 1.0.1 + gopd: 1.2.0 + has-symbols: 1.1.0 + hasown: 2.0.4 + math-intrinsics: 1.1.0 + + get-proto@1.0.1: + dependencies: + dunder-proto: 1.0.1 + es-object-atoms: 1.1.2 + + github-from-package@0.0.0: {} + + gopd@1.2.0: {} + + graceful-fs@4.2.11: {} + + grad-school@0.0.5: {} + + h3@2.0.1-rc.31(crossws@0.4.12(srvx@1.0.4))(ocache@0.3.0): + dependencies: + rou3: 0.9.2 + srvx: 1.0.4 + optionalDependencies: + crossws: 0.4.12(srvx@1.0.4) + ocache: 0.3.0 + + has-flag@4.0.0: {} + + has-symbols@1.1.0: {} + + has-tostringtag@1.0.2: + dependencies: + has-symbols: 1.1.0 + + hasown@2.0.4: + dependencies: + function-bind: 1.1.2 + + hookable@6.1.1: {} + + https-proxy-agent@5.0.1: + dependencies: + agent-base: 6.0.2 + debug: 4.4.3 + transitivePeerDependencies: + - supports-color + + httpxy@0.5.5: {} + + humanize-ms@1.2.1: + dependencies: + ms: 2.1.3 + + ieee754@1.2.1: {} + + inherits@2.0.4: {} + + ini@1.3.8: {} + + is-number@7.0.0: {} + + jest-diff@29.7.0: + dependencies: + chalk: 4.1.2 + diff-sequences: 29.6.3 + jest-get-type: 29.6.3 + pretty-format: 29.7.0 + + jest-get-type@29.6.3: {} + + jest-matcher-utils@29.7.0: + dependencies: + chalk: 4.1.2 + jest-diff: 29.7.0 + jest-get-type: 29.6.3 + pretty-format: 29.7.0 + + jest-message-util@29.7.0: + dependencies: + '@babel/code-frame': 7.29.7 + '@jest/types': 29.6.3 + '@types/stack-utils': 2.0.3 + chalk: 4.1.2 + graceful-fs: 4.2.11 + micromatch: 4.0.8 + pretty-format: 29.7.0 + slash: 3.0.0 + stack-utils: 2.0.6 + + jest-util@29.7.0: + dependencies: + '@jest/types': 29.6.3 + '@types/node': 24.13.3 + chalk: 4.1.2 + ci-info: 3.9.0 + graceful-fs: 4.2.11 + picomatch: 2.3.2 + + joycon@3.1.1: {} + + js-tokens@4.0.0: {} + + json-schema@0.4.0: {} + + kareem@3.3.0: {} + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + lilconfig@3.1.3: {} + + lines-and-columns@1.2.4: {} + + load-tsconfig@0.2.5: {} + + magic-string@0.30.21: + dependencies: + '@jridgewell/sourcemap-codec': 1.6.0 + + math-intrinsics@1.1.0: {} + + mem0ai@3.1.8(@cloudflare/workers-types@4.20260702.1)(@types/jest@29.5.14)(@types/pg@8.11.0)(better-sqlite3@12.11.1)(compromise@14.16.0)(mongodb@7.5.0)(natural@8.1.1)(pg@8.11.3): + dependencies: + '@cloudflare/workers-types': 4.20260702.1 + '@types/jest': 29.5.14 + '@types/pg': 8.11.0 + axios: 1.20.0 + better-sqlite3: 12.11.1 + compromise: 14.16.0 + natural: 8.1.1 + openai: 4.104.0(zod@3.25.76) + pg: 8.11.3 + uuid: 11.1.1 + zod: 3.25.76 + optionalDependencies: + mongodb: 7.5.0 + transitivePeerDependencies: + - debug + - encoding + - supports-color + - ws + + memjs@1.3.2: {} + + memory-pager@1.5.0: {} + + micromatch@4.0.8: + dependencies: + braces: 3.0.3 + picomatch: 2.3.2 + + mime-db@1.52.0: {} + + mime-types@2.1.35: + dependencies: + mime-db: 1.52.0 + + mimic-response@3.1.0: {} + + minimist@1.2.8: {} + + mkdirp-classic@0.5.3: {} + + mlly@1.8.2: + dependencies: + acorn: 8.18.0 + pathe: 2.0.3 + pkg-types: 1.3.1 + ufo: 1.6.4 + + mongodb-connection-string-url@7.0.2: + dependencies: + '@types/whatwg-url': 13.0.0 + whatwg-url: 14.2.0 + + mongodb@7.5.0: + dependencies: + '@mongodb-js/saslprep': 1.5.2 + bson: 7.3.2 + mongodb-connection-string-url: 7.0.2 + + mongoose@9.9.5: + dependencies: + '@standard-schema/spec': 1.1.0 + kareem: 3.3.0 + mongodb: 7.5.0 + mpath: 0.9.0 + mquery: 6.0.0 + ms: 2.1.3 + sift: 17.1.3 + transitivePeerDependencies: + - '@aws-sdk/credential-providers' + - '@mongodb-js/zstd' + - gcp-metadata + - kerberos + - mongodb-client-encryption + - snappy + - socks + + mpath@0.9.0: {} + + mquery@6.0.0: {} + + ms@2.1.3: {} + + mz@2.7.0: + dependencies: + any-promise: 1.3.0 + object-assign: 4.1.1 + thenify-all: 1.6.0 + + nanoid@3.3.18: {} + + napi-build-utils@2.0.0: {} + + natural@8.1.1: + dependencies: + afinn-165: 2.0.2 + afinn-165-financialmarketnews: 3.0.0 + apparatus: 0.0.10 + dotenv: 17.4.2 + memjs: 1.3.2 + mongoose: 9.9.5 + pg: 8.23.0 + redis: 5.12.1 + safe-stable-stringify: 2.5.0 + stopwords-iso: 1.1.0 + sylvester: 0.0.21 + underscore: 1.13.8 + uuid: 13.0.2 + wordnet-db: 3.1.14 + transitivePeerDependencies: + - '@aws-sdk/credential-providers' + - '@mongodb-js/zstd' + - '@node-rs/xxhash' + - '@opentelemetry/api' + - gcp-metadata + - kerberos + - mongodb-client-encryption + - pg-native + - snappy + - socks + + nf3@0.3.24: {} + + nitro@3.0.260903-beta: + dependencies: + consola: 3.4.2 + crossws: 0.4.12(srvx@1.0.4) + db0: 0.4.1 + env-runner: 0.2.1 + h3: 2.0.1-rc.31(crossws@0.4.12(srvx@1.0.4))(ocache@0.3.0) + hookable: 6.1.1 + nf3: 0.3.24 + ocache: 0.3.0 + rolldown: 1.2.7 + rou3: 0.9.2 + srvx: 1.0.4 + unenv: 2.0.0-rc.24 + unstorage: 2.0.0-alpha.10 + + node-abi@3.96.0: + dependencies: + semver: 7.8.5 + + node-domexception@1.0.0: {} + + node-fetch@2.7.0: + dependencies: + whatwg-url: 5.0.0 + + object-assign@4.1.1: {} + + obuf@1.1.2: {} + + obug@2.1.4: {} + + ocache@0.3.0: {} + + once@1.4.0: + dependencies: + wrappy: 1.0.2 + + openai@4.104.0(zod@3.25.76): + dependencies: + '@types/node': 18.19.130 + '@types/node-fetch': 2.6.13 + abort-controller: 3.0.0 + agentkeepalive: 4.6.0 + form-data-encoder: 1.7.2 + formdata-node: 4.4.1 + node-fetch: 2.7.0 + optionalDependencies: + zod: 3.25.76 + transitivePeerDependencies: + - encoding + + packet-reader@1.0.0: {} + + pathe@2.0.3: {} + + pg-cloudflare@1.4.0: + optional: true + + pg-connection-string@2.14.0: {} + + pg-int8@1.0.1: {} + + 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.23.0): + dependencies: + pg: 8.23.0 + + pg-protocol@1.16.0: {} + + pg-types@2.2.0: + dependencies: + pg-int8: 1.0.1 + postgres-array: 2.0.0 + postgres-bytea: 1.0.1 + postgres-date: 1.0.7 + postgres-interval: 1.2.0 + + pg-types@4.1.0: + dependencies: + pg-int8: 1.0.1 + pg-numeric: 1.0.2 + postgres-array: 3.0.4 + postgres-bytea: 3.0.0 + postgres-date: 2.1.0 + 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.14.0 + pg-pool: 3.14.0(pg@8.11.3) + pg-protocol: 1.16.0 + pg-types: 2.2.0 + pgpass: 1.0.6 + optionalDependencies: + pg-cloudflare: 1.4.0 + + pg@8.23.0: + dependencies: + pg-connection-string: 2.14.0 + pg-pool: 3.14.0(pg@8.23.0) + pg-protocol: 1.16.0 + pg-types: 2.2.0 + pgpass: 1.0.5 + optionalDependencies: + pg-cloudflare: 1.4.0 + + pgpass@1.0.5: + dependencies: + split2: 4.2.0 + + pgpass@1.0.6: {} + + picocolors@1.1.1: {} + + picomatch@2.3.2: {} + + picomatch@4.0.7: {} + + pirates@4.0.7: {} + + pkg-types@1.3.1: + dependencies: + confbox: 0.1.8 + mlly: 1.8.2 + pathe: 2.0.3 + + postcss-load-config@6.0.1(postcss@8.5.28): + dependencies: + lilconfig: 3.1.3 + optionalDependencies: + postcss: 8.5.28 + + postcss@8.5.28: + dependencies: + nanoid: 3.3.18 + picocolors: 1.1.1 + source-map-js: 1.2.1 + + postgres-array@2.0.0: {} + + postgres-array@3.0.4: {} + + postgres-bytea@1.0.1: {} + + postgres-bytea@3.0.0: + dependencies: + obuf: 1.1.2 + + postgres-date@1.0.7: {} + + postgres-date@2.1.0: {} + + postgres-interval@1.2.0: + dependencies: + xtend: 4.0.2 + + postgres-interval@3.0.0: {} + + postgres-range@1.1.4: {} + + prebuild-install@7.1.3: + dependencies: + detect-libc: 2.1.2 + expand-template: 2.0.3 + github-from-package: 0.0.0 + minimist: 1.2.8 + mkdirp-classic: 0.5.3 + napi-build-utils: 2.0.0 + node-abi: 3.96.0 + pump: 3.0.4 + rc: 1.2.8 + simple-get: 4.0.1 + tar-fs: 2.1.5 + tunnel-agent: 0.6.0 + + pretty-format@29.7.0: + dependencies: + '@jest/schemas': 29.6.3 + ansi-styles: 5.2.0 + react-is: 18.3.1 + + proxy-from-env@2.1.0: {} + + pump@3.0.4: + dependencies: + end-of-stream: 1.4.5 + once: 1.4.0 + + punycode@2.3.1: {} + + rc@1.2.8: + dependencies: + deep-extend: 0.6.0 + ini: 1.3.8 + minimist: 1.2.8 + strip-json-comments: 2.0.1 + + react-is@18.3.1: {} + + readable-stream@3.6.2: + dependencies: + inherits: 2.0.4 + string_decoder: 1.3.0 + util-deprecate: 1.0.2 + + readdirp@4.1.2: {} + + redis@5.12.1: + dependencies: + '@redis/bloom': 5.12.1(@redis/client@5.12.1) + '@redis/client': 5.12.1 + '@redis/json': 5.12.1(@redis/client@5.12.1) + '@redis/search': 5.12.1(@redis/client@5.12.1) + '@redis/time-series': 5.12.1(@redis/client@5.12.1) + transitivePeerDependencies: + - '@node-rs/xxhash' + - '@opentelemetry/api' + + resolve-from@5.0.0: {} + + rolldown@1.2.7: + dependencies: + '@oxc-project/types': 0.148.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.7 + '@rolldown/binding-android-arm64': 1.2.7 + '@rolldown/binding-darwin-arm64': 1.2.7 + '@rolldown/binding-darwin-x64': 1.2.7 + '@rolldown/binding-freebsd-x64': 1.2.7 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.7 + '@rolldown/binding-linux-arm64-gnu': 1.2.7 + '@rolldown/binding-linux-arm64-musl': 1.2.7 + '@rolldown/binding-linux-ppc64-gnu': 1.2.7 + '@rolldown/binding-linux-s390x-gnu': 1.2.7 + '@rolldown/binding-linux-x64-gnu': 1.2.7 + '@rolldown/binding-linux-x64-musl': 1.2.7 + '@rolldown/binding-openharmony-arm64': 1.2.7 + '@rolldown/binding-win32-arm64-msvc': 1.2.7 + '@rolldown/binding-win32-x64-msvc': 1.2.7 + + rollup@4.63.1: + dependencies: + '@types/estree': 1.0.9 + optionalDependencies: + '@napi-rs/lzma-linux-x64-gnu': 1.5.1 + '@rollup/rollup-android-arm-eabi': 4.63.1 + '@rollup/rollup-android-arm64': 4.63.1 + '@rollup/rollup-darwin-arm64': 4.63.1 + '@rollup/rollup-darwin-x64': 4.63.1 + '@rollup/rollup-freebsd-arm64': 4.63.1 + '@rollup/rollup-freebsd-x64': 4.63.1 + '@rollup/rollup-linux-arm-gnueabihf': 4.63.1 + '@rollup/rollup-linux-arm-musleabihf': 4.63.1 + '@rollup/rollup-linux-arm64-gnu': 4.63.1 + '@rollup/rollup-linux-arm64-musl': 4.63.1 + '@rollup/rollup-linux-loong64-gnu': 4.63.1 + '@rollup/rollup-linux-loong64-musl': 4.63.1 + '@rollup/rollup-linux-ppc64-gnu': 4.63.1 + '@rollup/rollup-linux-ppc64-musl': 4.63.1 + '@rollup/rollup-linux-riscv64-gnu': 4.63.1 + '@rollup/rollup-linux-riscv64-musl': 4.63.1 + '@rollup/rollup-linux-s390x-gnu': 4.63.1 + '@rollup/rollup-linux-x64-gnu': 4.63.1 + '@rollup/rollup-linux-x64-musl': 4.63.1 + '@rollup/rollup-openbsd-x64': 4.63.1 + '@rollup/rollup-openharmony-arm64': 4.63.1 + '@rollup/rollup-win32-arm64-msvc': 4.63.1 + '@rollup/rollup-win32-ia32-msvc': 4.63.1 + '@rollup/rollup-win32-x64-gnu': 4.63.1 + '@rollup/rollup-win32-x64-msvc': 4.63.1 + fsevents: 2.3.3 + + rou3@0.9.2: {} + + safe-buffer@5.2.1: {} + + safe-stable-stringify@2.5.0: {} + + semver@7.8.5: {} + + sift@17.1.3: {} + + siginfo@2.0.0: {} + + simple-concat@1.0.1: {} + + simple-get@4.0.1: + dependencies: + decompress-response: 6.0.0 + once: 1.4.0 + simple-concat: 1.0.1 + + slash@3.0.0: {} + + source-map-js@1.2.1: {} + + source-map@0.7.6: {} + + sparse-bitfield@3.0.3: + dependencies: + memory-pager: 1.5.0 + + split2@4.2.0: {} + + srvx@1.0.4: {} + + stack-utils@2.0.6: + dependencies: + escape-string-regexp: 2.0.0 + + stackback@0.0.2: {} + + std-env@4.2.0: {} + + stopwords-iso@1.1.0: {} + + string_decoder@1.3.0: + dependencies: + safe-buffer: 5.2.1 + + strip-json-comments@2.0.1: {} + + sucrase@3.35.1: + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + commander: 4.1.1 + lines-and-columns: 1.2.4 + mz: 2.7.0 + pirates: 4.0.7 + tinyglobby: 0.2.17 + ts-interface-checker: 0.1.13 + + suffix-thumb@5.0.2: {} + + supports-color@7.2.0: + dependencies: + has-flag: 4.0.0 + + sylvester@0.0.21: {} + + tar-fs@2.1.5: + dependencies: + chownr: 1.1.4 + mkdirp-classic: 0.5.3 + pump: 3.0.4 + tar-stream: 2.2.0 + + tar-stream@2.2.0: + dependencies: + bl: 4.1.0 + end-of-stream: 1.4.5 + fs-constants: 1.0.0 + inherits: 2.0.4 + readable-stream: 3.6.2 + + thenify-all@1.6.0: + dependencies: + thenify: 3.3.1 + + thenify@3.3.1: + dependencies: + any-promise: 1.3.0 + + tinybench@2.9.0: {} + + tinyexec@0.3.2: {} + + tinyexec@1.3.1: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + tinyrainbow@3.1.1: {} + + to-regex-range@5.0.1: + dependencies: + is-number: 7.0.0 + + tr46@0.0.3: {} + + tr46@5.1.1: + dependencies: + punycode: 2.3.1 + + tree-kill@1.2.2: {} + + ts-interface-checker@0.1.13: {} + + tsup@8.5.1(postcss@8.5.28)(typescript@5.9.3): + dependencies: + bundle-require: 5.1.0(esbuild@0.27.7) + cac: 6.7.14 + chokidar: 4.0.3 + consola: 3.4.2 + debug: 4.4.3 + esbuild: 0.27.7 + 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.28) + resolve-from: 5.0.0 + rollup: 4.63.1 + source-map: 0.7.6 + sucrase: 3.35.1 + tinyexec: 0.3.2 + tinyglobby: 0.2.17 + tree-kill: 1.2.2 + optionalDependencies: + postcss: 8.5.28 + typescript: 5.9.3 + transitivePeerDependencies: + - jiti + - supports-color + - tsx + - yaml + + tunnel-agent@0.6.0: + dependencies: + safe-buffer: 5.2.1 + + typescript@5.9.3: {} + + ufo@1.6.4: {} + + underscore@1.13.8: {} + + undici-types@5.26.5: {} + + undici-types@7.18.2: {} + + undici@7.29.1: {} + + undici@8.9.0: {} + + unenv@2.0.0-rc.24: + dependencies: + pathe: 2.0.3 + + unstorage@2.0.0-alpha.10: {} + + util-deprecate@1.0.2: {} + + uuid@11.1.1: {} + + uuid@13.0.2: {} + + vite@8.2.2(@types/node@24.13.3)(esbuild@0.27.7): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.28 + rolldown: 1.2.7 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 24.13.3 + esbuild: 0.27.7 + fsevents: 2.3.3 + + vitest@4.1.11(@types/node@24.13.3)(vite@8.2.2(@types/node@24.13.3)(esbuild@0.27.7)): + dependencies: + '@vitest/expect': 4.1.11 + '@vitest/mocker': 4.1.11(vite@8.2.2(@types/node@24.13.3)(esbuild@0.27.7)) + '@vitest/pretty-format': 4.1.11 + '@vitest/runner': 4.1.11 + '@vitest/snapshot': 4.1.11 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 + es-module-lexer: 2.3.2 + expect-type: 1.4.0 + magic-string: 0.30.21 + obug: 2.1.4 + pathe: 2.0.3 + picomatch: 4.0.7 + std-env: 4.2.0 + tinybench: 2.9.0 + tinyexec: 1.3.1 + tinyglobby: 0.2.17 + tinyrainbow: 3.1.1 + vite: 8.2.2(@types/node@24.13.3)(esbuild@0.27.7) + why-is-node-running: 2.3.0 + optionalDependencies: + '@types/node': 24.13.3 + transitivePeerDependencies: + - msw + + web-streams-polyfill@4.0.0-beta.3: {} + + webidl-conversions@3.0.1: {} + + webidl-conversions@7.0.0: {} + + whatwg-url@14.2.0: + dependencies: + tr46: 5.1.1 + webidl-conversions: 7.0.0 + + whatwg-url@5.0.0: + dependencies: + tr46: 0.0.3 + webidl-conversions: 3.0.1 + + why-is-node-running@2.3.0: + dependencies: + siginfo: 2.0.0 + stackback: 0.0.2 + + wordnet-db@3.1.14: {} + + wrappy@1.0.2: {} + + xtend@4.0.2: {} + + zod@3.25.76: {} + + zod@4.5.4: {} diff --git a/integrations/eve/registry/README.md b/integrations/eve/registry/README.md new file mode 100644 index 000000000..c369f5a78 --- /dev/null +++ b/integrations/eve/registry/README.md @@ -0,0 +1,36 @@ +# Eve registry contribution + +These files are the Mem0 side of `eve add memory/mem0`. They are not published in the npm tarball. Copy them into a PR against [vercel/eve](https://github.com/vercel/eve) after `@mem0/eve` is on npm. + +Supermemory's version of this change is [vercel/eve#2775](https://github.com/vercel/eve/pull/2775). Eve already asked Mem0 to own the package and open that PR. + +## What the Eve PR should do + +1. Add a `kind: "memory"` catalog item named `mem0`. +2. Install `@mem0/eve` and declare `MEM0_API_KEY`. +3. Write `agent/memory/mem0.ts` from [`mem0.ts`](./mem0.ts). +4. List Mem0 on [eve.dev/docs/memory](https://eve.dev/docs/memory) next to Supermemory and Upstash. + +[`item.json`](./item.json) is the shadcn-registry shape Eve uses for `eve add`. Adapt field names to Eve's current catalog schema if it has moved since this was written. + +## Suggested install command + +```bash +eve add memory/mem0 +``` + +## Suggested docs snippet + +```ts +import { mem0Provider } from "@mem0/eve"; +import { defineMemory } from "eve/memory"; +import { byPrincipal } from "eve/memory/scope"; + +export default defineMemory({ + description: "Recall and manage durable context for the current user.", + provider: mem0Provider({ + apiKey: process.env.MEM0_API_KEY!, + }), + scope: byPrincipal, +}); +``` diff --git a/integrations/eve/registry/item.json b/integrations/eve/registry/item.json new file mode 100644 index 000000000..0cf1566a1 --- /dev/null +++ b/integrations/eve/registry/item.json @@ -0,0 +1,17 @@ +{ + "name": "mem0", + "type": "registry:item", + "title": "Mem0", + "description": "Hosted semantic memory for Eve agents. Recalls relevant context before each turn, captures completed turns, and exposes search, remember, and forget tools.", + "dependencies": ["@mem0/eve"], + "envVars": { + "MEM0_API_KEY": "" + }, + "files": [ + { + "path": "registry/mem0.ts", + "type": "registry:file", + "target": "agent/memory/mem0.ts" + } + ] +} diff --git a/integrations/eve/registry/mem0.ts b/integrations/eve/registry/mem0.ts new file mode 100644 index 000000000..ab3e0d640 --- /dev/null +++ b/integrations/eve/registry/mem0.ts @@ -0,0 +1,11 @@ +import { mem0Provider } from "@mem0/eve"; +import { defineMemory } from "eve/memory"; +import { byPrincipal } from "eve/memory/scope"; + +export default defineMemory({ + description: "Recall and manage durable context for the current user.", + provider: mem0Provider({ + apiKey: process.env.MEM0_API_KEY!, + }), + scope: byPrincipal, +}); diff --git a/integrations/eve/src/capture.ts b/integrations/eve/src/capture.ts new file mode 100644 index 000000000..ab91eb486 --- /dev/null +++ b/integrations/eve/src/capture.ts @@ -0,0 +1,26 @@ +import { completedTurnMessages, type ConversationMessage } from "./messages.js"; +import type { MemoryStore } from "./store.js"; + +export async function captureCompletedTurn(input: { + store: MemoryStore; + scopeKey: string; + infer: boolean; + metadata: Readonly>; + messages: readonly ConversationMessage[]; + turnInput: readonly ConversationMessage[]; +}): Promise { + const messages = completedTurnMessages({ + messages: input.messages, + turnInput: input.turnInput, + }); + if (messages.length === 0) { + return false; + } + + await input.store.add(messages, { + userId: input.scopeKey, + infer: input.infer, + metadata: input.metadata, + }); + return true; +} diff --git a/integrations/eve/src/errors.ts b/integrations/eve/src/errors.ts new file mode 100644 index 000000000..422a60a4a --- /dev/null +++ b/integrations/eve/src/errors.ts @@ -0,0 +1,3 @@ +export function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : "Unknown Mem0 error"; +} diff --git a/integrations/eve/src/idempotency.ts b/integrations/eve/src/idempotency.ts new file mode 100644 index 000000000..6f41726e0 --- /dev/null +++ b/integrations/eve/src/idempotency.ts @@ -0,0 +1,26 @@ +const DEFAULT_LIMIT = 256; + +export function createIdempotencyGate(limit = DEFAULT_LIMIT) { + const seen = new Map>(); + + return function once(operationId: string, work: () => Promise): Promise { + const existing = seen.get(operationId); + if (existing) { + return existing; + } + + const pending = work().catch((error: unknown) => { + seen.delete(operationId); + throw error; + }); + + seen.set(operationId, pending); + if (seen.size > limit) { + const oldest = seen.keys().next().value; + if (oldest && oldest !== operationId) { + seen.delete(oldest); + } + } + return pending; + }; +} diff --git a/integrations/eve/src/index.ts b/integrations/eve/src/index.ts new file mode 100644 index 000000000..024ecfaee --- /dev/null +++ b/integrations/eve/src/index.ts @@ -0,0 +1,3 @@ +export { mem0Provider, mem0Provider as default } from "./provider.js"; +export type { Mem0ApiKey, Mem0ProviderOptions } from "./options.js"; +export type { MemoryStore, MemoryMessage, SearchHit } from "./store.js"; diff --git a/integrations/eve/src/messages.ts b/integrations/eve/src/messages.ts new file mode 100644 index 000000000..ef76ca4e0 --- /dev/null +++ b/integrations/eve/src/messages.ts @@ -0,0 +1,79 @@ +import type { MemoryMessage } from "./store.js"; + +export interface ConversationMessage { + readonly role: string; + readonly content: unknown; +} + +export function extractText(content: unknown): string { + if (typeof content === "string") { + return content.trim(); + } + if (!Array.isArray(content)) { + return ""; + } + + return content + .map((part) => { + if (typeof part === "string") { + return part; + } + if (part && typeof part === "object" && "text" in part) { + const text = (part as { text: unknown }).text; + return typeof text === "string" ? text : ""; + } + return ""; + }) + .join("\n") + .trim(); +} + +export function lastUserText(messages: readonly ConversationMessage[]): string { + for (let index = messages.length - 1; index >= 0; index -= 1) { + const message = messages[index]; + if (message?.role !== "user") { + continue; + } + const text = extractText(message.content); + if (text.length > 0) { + return text; + } + } + return ""; +} + +export function conversationMessages( + messages: readonly ConversationMessage[], +): MemoryMessage[] { + const result: MemoryMessage[] = []; + for (const message of messages) { + if (message.role !== "user" && message.role !== "assistant") { + continue; + } + const text = extractText(message.content); + if (text.length === 0) { + continue; + } + result.push({ role: message.role, content: text }); + } + return result; +} + +export function completedTurnMessages(input: { + readonly messages: readonly ConversationMessage[]; + readonly turnInput: readonly ConversationMessage[]; +}): MemoryMessage[] { + const users = conversationMessages(input.turnInput).filter( + (message) => message.role === "user", + ); + if (users.length === 0) { + return []; + } + + const history = conversationMessages(input.messages); + const lastAssistant = [...history] + .reverse() + .find((message) => message.role === "assistant"); + + return lastAssistant ? [...users, lastAssistant] : users; +} diff --git a/integrations/eve/src/options.ts b/integrations/eve/src/options.ts new file mode 100644 index 000000000..3e37c1417 --- /dev/null +++ b/integrations/eve/src/options.ts @@ -0,0 +1,74 @@ +import type { MemoryStore } from "./store.js"; + +export type Mem0ApiKey = string | (() => string | Promise); + +export interface Mem0ProviderOptions { + readonly apiKey: Mem0ApiKey; + readonly host?: string; + readonly topK?: number; + readonly threshold?: number; + readonly rerank?: boolean; + readonly infer?: boolean; + readonly autoSearch?: { + readonly enabled?: boolean; + }; + readonly capture?: { + readonly enabled?: boolean; + }; + readonly metadata?: Readonly>; + readonly store?: MemoryStore; +} + +export interface ResolvedMem0ProviderOptions { + readonly apiKey: Mem0ApiKey; + readonly host: string; + readonly topK: number; + readonly threshold: number; + readonly rerank: boolean; + readonly infer: boolean; + readonly autoSearch: { + readonly enabled: boolean; + }; + readonly capture: { + readonly enabled: boolean; + }; + readonly metadata: Readonly>; + readonly store?: MemoryStore; +} + +export function resolveOptions(options: Mem0ProviderOptions): ResolvedMem0ProviderOptions { + const apiKey = options.apiKey; + if (typeof apiKey === "string") { + const trimmed = apiKey.trim(); + if (trimmed.length === 0) { + throw new Error("Mem0 API key cannot be empty"); + } + } + + const topK = options.topK ?? 5; + if (!Number.isInteger(topK) || topK < 1 || topK > 100) { + throw new Error("topK must be an integer between 1 and 100"); + } + + const threshold = options.threshold ?? 0.1; + if (!Number.isFinite(threshold) || threshold < 0 || threshold > 1) { + throw new Error("threshold must be a number between 0 and 1"); + } + + return { + apiKey, + host: options.host ?? "https://api.mem0.ai", + topK, + threshold, + rerank: options.rerank ?? false, + infer: options.infer ?? true, + autoSearch: { + enabled: options.autoSearch?.enabled ?? true, + }, + capture: { + enabled: options.capture?.enabled ?? true, + }, + metadata: options.metadata ?? {}, + ...(options.store ? { store: options.store } : {}), + }; +} diff --git a/integrations/eve/src/provider.ts b/integrations/eve/src/provider.ts new file mode 100644 index 000000000..c2e08a129 --- /dev/null +++ b/integrations/eve/src/provider.ts @@ -0,0 +1,120 @@ +import { defineMemoryProvider, type MemoryProvider } from "eve/memory"; +import { captureCompletedTurn } from "./capture.js"; +import { errorMessage } from "./errors.js"; +import { createIdempotencyGate } from "./idempotency.js"; +import { lastUserText, type ConversationMessage } from "./messages.js"; +import { resolveOptions, type Mem0ProviderOptions } from "./options.js"; +import { recallMemories } from "./recall.js"; +import { createMem0Store, type MemoryStore } from "./store.js"; +import { createMem0Tools } from "./tools.js"; + +function asConversation(messages: readonly unknown[]): ConversationMessage[] { + return messages.filter((message): message is ConversationMessage => { + if (message === null || typeof message !== "object") { + return false; + } + return ( + "role" in message && typeof (message as { role: unknown }).role === "string" + ); + }); +} + +export function mem0Provider(options: Mem0ProviderOptions): MemoryProvider { + const config = resolveOptions(options); + const once = createIdempotencyGate(); + let storePromise: Promise | undefined; + + const getStore = async (): Promise => { + if (config.store) { + return config.store; + } + storePromise ??= createMem0Store({ + apiKey: config.apiKey, + host: config.host, + }); + return storePromise; + }; + + const recall = async (context: { + abortSignal: AbortSignal; + messages: readonly unknown[]; + session: { id: string }; + memory: { scope: { key: string } }; + turn?: { input: readonly unknown[] } | null; + }) => { + if (!config.autoSearch.enabled) { + return null; + } + + const querySource = context.turn?.input ?? context.messages; + const query = lastUserText(asConversation(querySource)); + + try { + const store = await getStore(); + return await recallMemories({ + store, + scopeKey: context.memory.scope.key, + query, + topK: config.topK, + threshold: config.threshold, + rerank: config.rerank, + }); + } catch (error) { + if (context.abortSignal.aborted) { + throw error; + } + console.error("[@mem0/eve] recall failed", { + error: errorMessage(error), + sessionId: context.session.id, + }); + return null; + } + }; + + return defineMemoryProvider({ + recall: { + "turn.started": recall, + "compaction.completed": recall, + }, + ...(config.capture.enabled + ? { + capture: { + async "turn.completed"(context) { + try { + const store = await getStore(); + await once(context.operationId, async () => { + await captureCompletedTurn({ + store, + scopeKey: context.memory.scope.key, + infer: config.infer, + metadata: { + ...config.metadata, + source: "eve", + operation_id: context.operationId, + session_id: context.session.id, + slot: context.memory.slot, + }, + messages: asConversation(context.messages), + turnInput: asConversation(context.turn.input), + }); + }); + } catch (error) { + if (context.abortSignal.aborted) { + throw error; + } + console.error("[@mem0/eve] capture failed", { + error: errorMessage(error), + sessionId: context.session.id, + turnId: context.turn.id, + }); + } + }, + }, + } + : {}), + async tools(context) { + const store = await getStore(); + return createMem0Tools(store, context.memory.scope.key); + }, + }); +} diff --git a/integrations/eve/src/recall.ts b/integrations/eve/src/recall.ts new file mode 100644 index 000000000..18a39baf7 --- /dev/null +++ b/integrations/eve/src/recall.ts @@ -0,0 +1,36 @@ +import type { SearchHit, MemoryStore } from "./store.js"; + +export interface RecallMessage { + readonly id: string; + readonly content: string; +} + +export function formatRecallMessages(hits: readonly SearchHit[]): RecallMessage[] { + return hits.flatMap((hit) => { + const content = hit.memory.trim(); + return content.length > 0 ? [{ id: hit.id, content }] : []; + }); +} + +export async function recallMemories(input: { + store: MemoryStore; + scopeKey: string; + query: string; + topK: number; + threshold: number; + rerank: boolean; +}): Promise<{ messages: RecallMessage[] } | null> { + const query = input.query.trim(); + if (query.length === 0) { + return null; + } + + const { results } = await input.store.search(query, { + filters: { user_id: input.scopeKey }, + topK: input.topK, + threshold: input.threshold, + rerank: input.rerank, + }); + const messages = formatRecallMessages(results); + return messages.length > 0 ? { messages } : null; +} diff --git a/integrations/eve/src/store.ts b/integrations/eve/src/store.ts new file mode 100644 index 000000000..bf0148e9d --- /dev/null +++ b/integrations/eve/src/store.ts @@ -0,0 +1,83 @@ +import type { Mem0ApiKey } from "./options.js"; + +export type MemoryRole = "user" | "assistant"; + +export interface MemoryMessage { + readonly role: MemoryRole; + readonly content: string; +} + +export interface SearchHit { + readonly id: string; + readonly memory: string; +} + +export interface AddMemoryInput { + readonly userId: string; + readonly infer: boolean; + readonly metadata: Readonly>; +} + +export interface SearchMemoryInput { + readonly filters: { + readonly user_id: string; + }; + readonly topK: number; + readonly threshold: number; + readonly rerank: boolean; +} + +export interface MemoryStore { + add(messages: readonly MemoryMessage[], input: AddMemoryInput): Promise; + search(query: string, input: SearchMemoryInput): Promise<{ results: readonly SearchHit[] }>; + delete(memoryId: string): Promise; +} + +export async function resolveApiKey(apiKey: Mem0ApiKey): Promise { + const value = typeof apiKey === "function" ? await apiKey() : apiKey; + const trimmed = value.trim(); + if (trimmed.length === 0) { + throw new Error("Mem0 API key cannot be empty"); + } + return trimmed; +} + +export async function createMem0Store(input: { + apiKey: Mem0ApiKey; + host: string; +}): Promise { + const MemoryClient = (await import("mem0ai")).default; + const client = new MemoryClient({ + apiKey: await resolveApiKey(input.apiKey), + host: input.host, + }); + + return { + async add(messages, options) { + return client.add([...messages], { + userId: options.userId, + infer: options.infer, + metadata: { ...options.metadata }, + }); + }, + async search(query, options) { + const response = await client.search(query, { + filters: options.filters, + topK: options.topK, + threshold: options.threshold, + rerank: options.rerank, + }); + const results = Array.isArray(response?.results) ? response.results : []; + return { + results: results.flatMap((item) => { + const id = typeof item.id === "string" ? item.id : ""; + const memory = typeof item.memory === "string" ? item.memory : ""; + return id && memory ? [{ id, memory }] : []; + }), + }; + }, + async delete(memoryId) { + return client.delete(memoryId); + }, + }; +} diff --git a/integrations/eve/src/tools.ts b/integrations/eve/src/tools.ts new file mode 100644 index 000000000..c8bd9eddc --- /dev/null +++ b/integrations/eve/src/tools.ts @@ -0,0 +1,53 @@ +import { defineTool } from "eve/tools"; +import { z } from "zod"; +import type { MemoryStore } from "./store.js"; + +export function createMem0Tools(store: MemoryStore, scopeKey: string) { + return { + search: defineTool({ + description: "Search long-term memories for the current caller.", + inputSchema: z.object({ + query: z.string().min(1).max(2000), + }), + async execute({ query }) { + const { results } = await store.search(query, { + filters: { user_id: scopeKey }, + topK: 8, + threshold: 0.1, + rerank: false, + }); + return { + memories: results.map((hit) => ({ + id: hit.id, + memory: hit.memory, + })), + }; + }, + }), + remember: defineTool({ + description: + "Save one durable fact or preference about the current caller.", + inputSchema: z.object({ + text: z.string().min(1).max(4000), + }), + async execute({ text }) { + await store.add([{ role: "user", content: text }], { + userId: scopeKey, + infer: true, + metadata: { source: "eve-tool" }, + }); + return { saved: true }; + }, + }), + forget: defineTool({ + description: "Delete one memory belonging to the current caller by id.", + inputSchema: z.object({ + id: z.string().min(1), + }), + async execute({ id }) { + await store.delete(id); + return { deleted: true }; + }, + }), + }; +} diff --git a/integrations/eve/tests/capture.test.ts b/integrations/eve/tests/capture.test.ts new file mode 100644 index 000000000..da0351a17 --- /dev/null +++ b/integrations/eve/tests/capture.test.ts @@ -0,0 +1,45 @@ +import { describe, expect, it } from "vitest"; +import { captureCompletedTurn } from "../src/capture.js"; +import { createFakeStore } from "./helpers.js"; + +describe("captureCompletedTurn", () => { + it("adds the current turn under the locked scope", async () => { + const store = createFakeStore(); + const captured = await captureCompletedTurn({ + store, + scopeKey: "scope_abc", + infer: true, + metadata: { source: "eve" }, + turnInput: [{ role: "user", content: "I am vegetarian" }], + messages: [ + { role: "user", content: "I am vegetarian" }, + { role: "assistant", content: "Got it." }, + ], + }); + + expect(captured).toBe(true); + expect(store.added).toEqual([ + { + userId: "scope_abc", + messages: [ + { role: "user", content: "I am vegetarian" }, + { role: "assistant", content: "Got it." }, + ], + }, + ]); + }); + + it("does not write when the turn has no user text", async () => { + const store = createFakeStore(); + const captured = await captureCompletedTurn({ + store, + scopeKey: "scope_abc", + infer: true, + metadata: {}, + turnInput: [], + messages: [], + }); + expect(captured).toBe(false); + expect(store.added).toEqual([]); + }); +}); diff --git a/integrations/eve/tests/helpers.ts b/integrations/eve/tests/helpers.ts new file mode 100644 index 000000000..e50440709 --- /dev/null +++ b/integrations/eve/tests/helpers.ts @@ -0,0 +1,73 @@ +import type { MemoryMessage, MemoryStore, SearchHit } from "../src/store.js"; + +export function createFakeStore(hits: SearchHit[] = []): MemoryStore & { + added: Array<{ messages: readonly MemoryMessage[]; userId: string }>; + searched: Array<{ query: string; userId: string }>; + deleted: string[]; +} { + const added: Array<{ messages: readonly MemoryMessage[]; userId: string }> = []; + const searched: Array<{ query: string; userId: string }> = []; + const deleted: string[] = []; + + return { + added, + searched, + deleted, + async add(messages, input) { + added.push({ messages, userId: input.userId }); + return { eventId: "evt_1" }; + }, + async search(query, input) { + searched.push({ query, userId: input.filters.user_id }); + return { results: hits }; + }, + async delete(memoryId) { + deleted.push(memoryId); + return { message: "ok" }; + }, + }; +} + +export function memoryContext(input?: { + scopeKey?: string; + operationId?: string; + turnInput?: Array<{ role: string; content: unknown }>; + messages?: Array<{ role: string; content: unknown }>; +}): { + abortSignal: AbortSignal; + operationId: string; + session: { id: string }; + memory: { + scope: { key: string; namespace: string; value: string }; + slot: string; + }; + messages: Array<{ role: string; content: unknown }>; + turn: { + id: string; + sequence: number; + input: Array<{ role: string; content: unknown }>; + }; +} { + return { + abortSignal: new AbortController().signal, + operationId: input?.operationId ?? "op_1", + session: { id: "sess_1" }, + memory: { + scope: { + key: input?.scopeKey ?? "scope_abc", + namespace: "default", + value: "user_1", + }, + slot: "mem0", + }, + messages: input?.messages ?? [ + { role: "user", content: "I am vegetarian" }, + { role: "assistant", content: "I will remember that." }, + ], + turn: { + id: "turn_1", + sequence: 1, + input: input?.turnInput ?? [{ role: "user", content: "I am vegetarian" }], + }, + }; +} diff --git a/integrations/eve/tests/idempotency.test.ts b/integrations/eve/tests/idempotency.test.ts new file mode 100644 index 000000000..56bb74a0b --- /dev/null +++ b/integrations/eve/tests/idempotency.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it } from "vitest"; +import { createIdempotencyGate } from "../src/idempotency.js"; + +describe("createIdempotencyGate", () => { + it("runs work once per operation id", async () => { + const once = createIdempotencyGate(); + let calls = 0; + const work = async () => { + calls += 1; + }; + + await Promise.all([once("op_1", work), once("op_1", work)]); + await once("op_1", work); + + expect(calls).toBe(1); + }); + + it("retries after a failure", async () => { + const once = createIdempotencyGate(); + let calls = 0; + const work = async () => { + calls += 1; + if (calls === 1) { + throw new Error("nope"); + } + }; + + await expect(once("op_1", work)).rejects.toThrow("nope"); + await once("op_1", work); + expect(calls).toBe(2); + }); +}); diff --git a/integrations/eve/tests/messages.test.ts b/integrations/eve/tests/messages.test.ts new file mode 100644 index 000000000..5f1de765a --- /dev/null +++ b/integrations/eve/tests/messages.test.ts @@ -0,0 +1,86 @@ +import { describe, expect, it } from "vitest"; +import { + completedTurnMessages, + conversationMessages, + extractText, + lastUserText, +} from "../src/messages.js"; + +describe("extractText", () => { + it("reads a string", () => { + expect(extractText(" hello ")).toBe("hello"); + }); + + it("joins text parts", () => { + expect( + extractText([ + { type: "text", text: "I like" }, + { type: "text", text: "tea" }, + ]), + ).toBe("I like\ntea"); + }); + + it("ignores non-text parts", () => { + expect(extractText([{ type: "image", url: "x" }])).toBe(""); + }); +}); + +describe("lastUserText", () => { + it("returns the last user message", () => { + expect( + lastUserText([ + { role: "user", content: "first" }, + { role: "assistant", content: "ok" }, + { role: "user", content: "second" }, + ]), + ).toBe("second"); + }); + + it("returns empty when there is no user text", () => { + expect(lastUserText([{ role: "assistant", content: "hi" }])).toBe(""); + }); +}); + +describe("conversationMessages", () => { + it("keeps user and assistant text only", () => { + expect( + conversationMessages([ + { role: "system", content: "ignore" }, + { role: "user", content: "hello" }, + { role: "assistant", content: "hi" }, + { role: "user", content: "" }, + ]), + ).toEqual([ + { role: "user", content: "hello" }, + { role: "assistant", content: "hi" }, + ]); + }); +}); + +describe("completedTurnMessages", () => { + it("pairs the current user turn with the latest assistant reply", () => { + expect( + completedTurnMessages({ + turnInput: [{ role: "user", content: "I like tea" }], + messages: [ + { role: "user", content: "older" }, + { role: "assistant", content: "older reply" }, + { role: "user", content: "I like tea" }, + { role: "assistant", content: "Noted." }, + ], + }), + ).toEqual([ + { role: "user", content: "I like tea" }, + { role: "assistant", content: "Noted." }, + ]); + }); + + it("skips capture when the turn has no user text", () => { + expect( + completedTurnMessages({ + turnInput: [{ role: "assistant", content: "hello" }], + messages: [{ role: "assistant", content: "hello" }], + }), + ).toEqual([]); + }); +}); diff --git a/integrations/eve/tests/options.test.ts b/integrations/eve/tests/options.test.ts new file mode 100644 index 000000000..6b67ff9b0 --- /dev/null +++ b/integrations/eve/tests/options.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from "vitest"; +import { resolveOptions } from "../src/options.js"; +import { createFakeStore } from "./helpers.js"; + +describe("resolveOptions", () => { + it("applies defaults", () => { + expect(resolveOptions({ apiKey: "m0-test" })).toMatchObject({ + host: "https://api.mem0.ai", + topK: 5, + threshold: 0.1, + rerank: false, + infer: true, + autoSearch: { enabled: true }, + capture: { enabled: true }, + }); + }); + + it("rejects an empty api key", () => { + expect(() => resolveOptions({ apiKey: " " })).toThrow(/empty/); + }); + + it("rejects an invalid topK", () => { + expect(() => resolveOptions({ apiKey: "m0-test", topK: 0 })).toThrow(/topK/); + }); + + it("keeps an injected store", () => { + const store = createFakeStore(); + expect(resolveOptions({ apiKey: "m0-test", store }).store).toBe(store); + }); +}); diff --git a/integrations/eve/tests/provider.test.ts b/integrations/eve/tests/provider.test.ts new file mode 100644 index 000000000..a34313314 --- /dev/null +++ b/integrations/eve/tests/provider.test.ts @@ -0,0 +1,121 @@ +import type { + MemoryToolsContext, + MemoryTurnCompletedContext, + MemoryTurnStartedContext, +} from "eve/memory"; +import { describe, expect, it, vi } from "vitest"; +import { mem0Provider } from "../src/provider.js"; +import { createFakeStore, memoryContext } from "./helpers.js"; + +function startedContext( + input?: Parameters[0], +): MemoryTurnStartedContext { + return memoryContext(input) as unknown as MemoryTurnStartedContext; +} + +function completedContext( + input?: Parameters[0], +): MemoryTurnCompletedContext { + return memoryContext(input) as unknown as MemoryTurnCompletedContext; +} + +function toolsContext( + input?: Parameters[0], +): MemoryToolsContext { + return memoryContext(input) as unknown as MemoryToolsContext; +} + +async function runTool( + tool: { execute: (input: never, context: never) => unknown }, + input: object, +): Promise { + return tool.execute(input as never, {} as never); +} + +describe("mem0Provider", () => { + it("recalls memories for the locked scope on turn start", async () => { + const store = createFakeStore([{ id: "mem_1", memory: "User likes tea" }]); + const provider = mem0Provider({ apiKey: "m0-test", store }); + const result = await provider.recall["turn.started"]( + startedContext({ + turnInput: [{ role: "user", content: "What do I drink?" }], + }), + ); + + expect(store.searched).toEqual([ + { query: "What do I drink?", userId: "scope_abc" }, + ]); + expect(result).toEqual({ + messages: [{ id: "mem_1", content: "User likes tea" }], + }); + }); + + it("does not fail the turn when search throws", async () => { + const store = createFakeStore(); + store.search = async () => { + throw new Error("mem0 down"); + }; + const provider = mem0Provider({ apiKey: "m0-test", store }); + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + + await expect( + provider.recall["turn.started"](startedContext()), + ).resolves.toBeNull(); + + error.mockRestore(); + }); + + it("captures a completed turn once per operation id", async () => { + const store = createFakeStore(); + const provider = mem0Provider({ apiKey: "m0-test", store }); + const capture = provider.capture?.["turn.completed"]; + expect(capture).toBeTypeOf("function"); + + const context = completedContext({ operationId: "op_replay" }); + await capture!(context); + await capture!(context); + + expect(store.added).toHaveLength(1); + expect(store.added[0]?.userId).toBe("scope_abc"); + }); + + it("omits capture when it is disabled", () => { + const provider = mem0Provider({ + apiKey: "m0-test", + store: createFakeStore(), + capture: { enabled: false }, + }); + expect(provider.capture).toBeUndefined(); + }); + + it("binds tools to the locked scope", async () => { + const store = createFakeStore([{ id: "mem_1", memory: "likes tea" }]); + const provider = mem0Provider({ apiKey: "m0-test", store }); + const tools = await provider.tools!(toolsContext()); + if (!tools) { + throw new Error("expected tools"); + } + + const searchTool = tools.search; + const rememberTool = tools.remember; + const forgetTool = tools.forget; + if (!searchTool || !rememberTool || !forgetTool) { + throw new Error("expected search, remember, and forget tools"); + } + + const search = await runTool(searchTool, { query: "drinks" }); + const remember = await runTool(rememberTool, { + text: "Allergic to peanuts", + }); + const forget = await runTool(forgetTool, { id: "mem_1" }); + + expect(search).toEqual({ + memories: [{ id: "mem_1", memory: "likes tea" }], + }); + expect(remember).toEqual({ saved: true }); + expect(forget).toEqual({ deleted: true }); + expect(store.searched[0]?.userId).toBe("scope_abc"); + expect(store.added[0]?.userId).toBe("scope_abc"); + expect(store.deleted).toEqual(["mem_1"]); + }); +}); diff --git a/integrations/eve/tests/recall.test.ts b/integrations/eve/tests/recall.test.ts new file mode 100644 index 000000000..da95f26a3 --- /dev/null +++ b/integrations/eve/tests/recall.test.ts @@ -0,0 +1,50 @@ +import { describe, expect, it } from "vitest"; +import { formatRecallMessages, recallMemories } from "../src/recall.js"; +import { createFakeStore } from "./helpers.js"; + +describe("formatRecallMessages", () => { + it("drops empty memories", () => { + expect( + formatRecallMessages([ + { id: "1", memory: " likes tea " }, + { id: "2", memory: " " }, + ]), + ).toEqual([{ id: "1", content: "likes tea" }]); + }); +}); + +describe("recallMemories", () => { + it("searches inside the locked scope and returns keyed messages", async () => { + const store = createFakeStore([{ id: "mem_1", memory: "User likes tea" }]); + const result = await recallMemories({ + store, + scopeKey: "scope_abc", + query: "What does the user drink?", + topK: 5, + threshold: 0.1, + rerank: false, + }); + + expect(store.searched).toEqual([ + { query: "What does the user drink?", userId: "scope_abc" }, + ]); + expect(result).toEqual({ + messages: [{ id: "mem_1", content: "User likes tea" }], + }); + }); + + it("returns null for an empty query", async () => { + const store = createFakeStore([{ id: "mem_1", memory: "x" }]); + await expect( + recallMemories({ + store, + scopeKey: "scope_abc", + query: " ", + topK: 5, + threshold: 0.1, + rerank: false, + }), + ).resolves.toBeNull(); + expect(store.searched).toEqual([]); + }); +}); diff --git a/integrations/eve/tsconfig.json b/integrations/eve/tsconfig.json new file mode 100644 index 000000000..eb949355a --- /dev/null +++ b/integrations/eve/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "ES2022", + "moduleResolution": "bundler", + "lib": ["ES2022"], + "strict": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "skipLibCheck": true, + "esModuleInterop": true, + "isolatedModules": true, + "verbatimModuleSyntax": true, + "noEmit": true, + "types": ["node"] + }, + "include": ["src/**/*.ts", "tests/**/*.ts"], + "exclude": ["node_modules", "dist"] +} diff --git a/integrations/eve/tsup.config.ts b/integrations/eve/tsup.config.ts new file mode 100644 index 000000000..9e0f7ca0a --- /dev/null +++ b/integrations/eve/tsup.config.ts @@ -0,0 +1,10 @@ +import { defineConfig } from "tsup"; + +export default defineConfig({ + entry: ["src/index.ts"], + format: ["esm"], + dts: true, + sourcemap: true, + clean: true, + external: ["eve", "eve/memory", "eve/tools", "mem0ai", "zod"], +}); diff --git a/integrations/eve/vitest.config.ts b/integrations/eve/vitest.config.ts new file mode 100644 index 000000000..faa6d98e1 --- /dev/null +++ b/integrations/eve/vitest.config.ts @@ -0,0 +1,8 @@ +import { defineConfig } from "vitest/config"; + +export default defineConfig({ + test: { + environment: "node", + include: ["tests/**/*.test.ts"], + }, +}); From 10d6717068914e1f1ba36eebc1e7840dc717bcf4 Mon Sep 17 00:00:00 2001 From: Himanshu-Sangshetti Date: Wed, 9 Sep 2026 10:48:26 +0800 Subject: [PATCH 04/61] fix(eve): scope forget, persist capture idempotency, and fail closed Review findings: delete was not partitioned by scope.key, capture replay after restart could double-write, and Mem0 errors were swallowed as empty recall. Co-authored-by: Cursor --- docs/integrations/eve.mdx | 14 +- docs/llms.txt | 2 +- integrations/AGENTS.md | 2 +- integrations/eve/README.md | 31 +-- integrations/eve/registry/README.md | 2 +- integrations/eve/src/capture.ts | 13 +- integrations/eve/src/errors.ts | 36 ++++ integrations/eve/src/idempotency.ts | 2 + integrations/eve/src/index.ts | 7 +- integrations/eve/src/messages.ts | 29 +-- integrations/eve/src/options.ts | 61 ++++-- integrations/eve/src/provider.ts | 90 +++++---- integrations/eve/src/recall.ts | 5 +- integrations/eve/src/store.ts | 143 ++++++++++++-- integrations/eve/src/tools.ts | 25 ++- integrations/eve/tests/capture.test.ts | 35 +++- integrations/eve/tests/errors.test.ts | 38 ++++ integrations/eve/tests/helpers.ts | 117 +++++++++-- integrations/eve/tests/idempotency.test.ts | 15 ++ integrations/eve/tests/messages.test.ts | 4 + integrations/eve/tests/options.test.ts | 52 ++++- integrations/eve/tests/provider.test.ts | 207 ++++++++++++++++++-- integrations/eve/tests/recall.test.ts | 31 ++- integrations/eve/tests/store.test.ts | 217 +++++++++++++++++++++ 24 files changed, 1013 insertions(+), 165 deletions(-) create mode 100644 integrations/eve/tests/errors.test.ts create mode 100644 integrations/eve/tests/store.test.ts diff --git a/docs/integrations/eve.mdx b/docs/integrations/eve.mdx index e3a8c1e86..f3b78b5ac 100644 --- a/docs/integrations/eve.mdx +++ b/docs/integrations/eve.mdx @@ -5,7 +5,7 @@ description: "Use Mem0 as a first-class memory provider for Vercel Eve agents." [Eve](https://eve.dev/docs/memory) is Vercel's agent framework. A memory provider sits in the agent loop: Eve recalls context before each turn, captures completed turns, and exposes provider tools. `@mem0/eve` is Mem0's implementation of that contract. -This is not the Mem0 MCP connection. MCP gives the model tools it may or may not call. The memory provider runs automatically. +This is not the Mem0 MCP connection. MCP gives the model tools it may or may not call. The memory provider runs automatically. The live MCP install is `eve add connection/mem0`. ## Install @@ -31,19 +31,15 @@ export default defineMemory({ }); ``` -After Eve lists Mem0 in the official registry, the same slot is created by: - -```bash -eve add memory/mem0 -``` +`eve add memory/mem0` is not in Eve's catalog yet. After Mem0 is listed in the official registry, that command will create the same slot file. ## How it works -1. **Recall.** Before each turn, Mem0 searches memories for the locked Eve scope and returns them as attributed user-role messages. -2. **Capture.** After a successful turn, Mem0 adds the user and assistant messages and extracts durable facts. +1. **Recall.** Before each turn and after compaction, Mem0 searches memories for the locked Eve scope and returns `{ id, content }` messages. Eve injects those as user-role messages attributed to the slot. +2. **Capture.** After a successful turn, Mem0 adds the user messages from that turn and, when present, the latest assistant reply. By default (`infer: true`) Mem0 extracts durable facts. 3. **Tools.** The model can call `search`, `remember`, and `forget`. Eve qualifies them as `mem0__search`, `mem0__remember`, and `mem0__forget` when the slot file is `mem0.ts`. -Eve owns namespace, scope, and when recall/capture run. Mem0 owns storage, ranking, and extraction. Every read and write is partitioned by `memory.scope.key`. +Eve owns namespace, scope, and when recall/capture run. Mem0 owns storage, ranking, and extraction. Search, capture, remember, and forget are partitioned by `memory.scope.key`. Forget deletes by id only after confirming the memory belongs to that key. ## Options diff --git a/docs/llms.txt b/docs/llms.txt index 79166ce8c..66fa71410 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -263,7 +263,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st - [Mastra](https://docs.mem0.ai/integrations/mastra) [Platform]: Use when the user is on Mastra (TypeScript). - [OpenClaw](https://docs.mem0.ai/integrations/openclaw) [Both]: Use when wiring Mem0 into Claude Code or editors via OpenClaw. - [Vercel AI SDK](https://docs.mem0.ai/integrations/vercel-ai-sdk) [Both]: Use when the user is on the Vercel AI SDK. -- [Eve](https://docs.mem0.ai/integrations/eve) [Platform]: Use when adding Mem0 as a first-class Eve memory provider (`@mem0/eve`, `mem0Provider`, `eve add memory/mem0`). Not the Mem0 MCP connection. +- [Eve](https://docs.mem0.ai/integrations/eve) [Platform]: Use when adding Mem0 as a first-class Eve memory provider (`@mem0/eve`, `mem0Provider`, hand-written `agent/memory/mem0.ts`). `eve add memory/mem0` is not available yet. Not the Mem0 MCP connection (`eve add connection/mem0`). - [Vercel](https://docs.mem0.ai/integrations/vercel) [Platform]: Use when deploying on Vercel and installing Mem0 from the Vercel Marketplace. - [Strands Agents](https://docs.mem0.ai/integrations/strands) [Both]: Use when the user is on AWS Strands and wants a native MemoryStore. diff --git a/integrations/AGENTS.md b/integrations/AGENTS.md index 8e683ae65..4cd7fbd66 100644 --- a/integrations/AGENTS.md +++ b/integrations/AGENTS.md @@ -47,7 +47,7 @@ Run the type check after every TypeScript change: `pnpm run typecheck` or `tsc - ## What each one is -- **`eve/`** is the Eve memory provider (`mem0Provider`). Eve calls recall before each turn and capture after each turn. This is not the Mem0 MCP connection. +- **`eve/`** is the Eve memory provider (`mem0Provider`). Eve calls recall on `turn.started` and `compaction.completed`, capture on `turn.completed` when enabled, and exposes `search` / `remember` / `forget` tools. This is not the Mem0 MCP connection. - **`vercel-ai-sdk/`** wraps the Vercel AI SDK through a `createMem0` provider. Integrations for AI-SDK repos go through this wrapper, not raw `MemoryClient`. - **`claude-code-plugin/`** is the Claude Code plugin (v0.3.0, installs as `mem0@mem0-plugins`): local evidence capture via lifecycle hooks, background memory extraction to the Mem0 Platform, a local `search_memories` MCP tool, six `/mem0:*` skills, and the `mem0:sidekick` agent. Pure-stdlib Python — no dependencies to install. Its `core/` + `adapters/claude/` split marks engine vs. harness glue; future per-harness plugins start by copying `core/` and keeping the contract tests verbatim (see its `docs/CONTRACT.md`). - **`mem0-plugin/`** connects Cursor, Codex, Kimi, Antigravity, and OpenCode to the MCP server at `mcp.mem0.ai` and installs lifecycle hooks for automatic memory capture. Exposes 9 MCP tools: `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory`, `delete_memory`, `delete_all_memories`, `delete_entities`, `list_entities`. The Claude Code plugin moved to [`claude-code-plugin/`](claude-code-plugin/) in v0.3.0 (installs as `mem0@mem0-plugins`); do not run both at the same time. diff --git a/integrations/eve/README.md b/integrations/eve/README.md index 90b4f8212..37d129e51 100644 --- a/integrations/eve/README.md +++ b/integrations/eve/README.md @@ -26,25 +26,27 @@ npm install @mem0/eve `eve` is a peer dependency. Get an API key from the [Mem0 dashboard](https://app.mem0.ai/dashboard/api-keys). -Until Eve lists Mem0 in the official registry, add the slot file yourself as `agent/memory/mem0.ts`. After the registry PR lands, this becomes: +Until Eve lists Mem0 in the official registry, add the slot file yourself as `agent/memory/mem0.ts`. `eve add memory/mem0` is not available yet. After the registry PR lands, that command will create the same file. -```bash -eve add memory/mem0 -``` +The live MCP path today is `eve add connection/mem0`. That is a different integration: tools the model may call, not automatic recall/capture. ## What it does | Eve hook | Mem0 behavior | |---|---| | `recall["turn.started"]` | Semantic search over memories for the locked scope | -| `recall["compaction.completed"]` | Same search after Eve compacting history | -| `capture["turn.completed"]` | Add the completed user/assistant turn | +| `recall["compaction.completed"]` | Same search after Eve compacting history (`turn` may be null) | +| `capture["turn.completed"]` | Add the completed user turn and, when present, the latest assistant reply | | `tools()` | `search`, `remember`, `forget` | -Every read and write is partitioned by `memory.scope.key`. The model cannot choose another caller. Replay uses `operationId` as an idempotency key. +Search, capture, remember, and forget are partitioned by `memory.scope.key`. Forget loads the memory first and deletes only when `userId` matches that key. + +Capture uses `operationId` as an idempotency key: an in-process gate plus a durable `metadata.operation_id` lookup so Eve replays after restart do not write twice. If the slot file is named `mem0.ts`, Eve qualifies tools as `mem0__search`, `mem0__remember`, and `mem0__forget`. +A throwing `recall` fails the Eve turn. A throwing `capture` is logged by Eve and does not fail the turn. Tool `execute` errors become failed tool results the model can see. + ## Options ```ts @@ -63,15 +65,16 @@ mem0Provider({ | Option | Default | Purpose | |---|---|---| -| `apiKey` | required | String or async getter | -| `host` | `https://api.mem0.ai` | Mem0 Platform host | -| `topK` | `5` | Memories recalled per turn | -| `threshold` | `0.1` | Minimum similarity | -| `rerank` | `false` | Mem0 reranking | -| `infer` | `true` | Extract facts on capture | -| `autoSearch.enabled` | `true` | Recall before each turn | +| `apiKey` | required without `store` | String or async getter. Function keys are validated on first use. | +| `host` | `https://api.mem0.ai` | Mem0 Platform host (`http:` or `https:` URL) | +| `topK` | `5` | Result count for automatic recall and the `search` tool | +| `threshold` | `0.1` | Minimum similarity for automatic recall and the `search` tool | +| `rerank` | `false` | Mem0 reranking for automatic recall and the `search` tool | +| `infer` | `true` | Extract facts on capture and on `remember` | +| `autoSearch.enabled` | `true` | Recall on `turn.started` and `compaction.completed` | | `capture.enabled` | `true` | Write after each successful turn | | `metadata` | `{}` | Extra metadata on captured turns | +| `store` | unset | Test / advanced injection. Replaces the Mem0 client and must honor `userId`. | ## Official registry diff --git a/integrations/eve/registry/README.md b/integrations/eve/registry/README.md index c369f5a78..80a2d8b75 100644 --- a/integrations/eve/registry/README.md +++ b/integrations/eve/registry/README.md @@ -2,7 +2,7 @@ These files are the Mem0 side of `eve add memory/mem0`. They are not published in the npm tarball. Copy them into a PR against [vercel/eve](https://github.com/vercel/eve) after `@mem0/eve` is on npm. -Supermemory's version of this change is [vercel/eve#2775](https://github.com/vercel/eve/pull/2775). Eve already asked Mem0 to own the package and open that PR. +Supermemory's version of this change is [vercel/eve#2775](https://github.com/vercel/eve/pull/2775). Use that PR as the catalog/shape reference. ## What the Eve PR should do diff --git a/integrations/eve/src/capture.ts b/integrations/eve/src/capture.ts index ab91eb486..d28ecf73c 100644 --- a/integrations/eve/src/capture.ts +++ b/integrations/eve/src/capture.ts @@ -1,14 +1,23 @@ import { completedTurnMessages, type ConversationMessage } from "./messages.js"; -import type { MemoryStore } from "./store.js"; +import type { MemoryStore, StoreMetadata } from "./store.js"; export async function captureCompletedTurn(input: { store: MemoryStore; scopeKey: string; + operationId: string; infer: boolean; - metadata: Readonly>; + metadata: StoreMetadata; messages: readonly ConversationMessage[]; turnInput: readonly ConversationMessage[]; }): Promise { + const existing = await input.store.listByMetadata({ + userId: input.scopeKey, + metadata: { operation_id: input.operationId }, + }); + if (existing.length > 0) { + return false; + } + const messages = completedTurnMessages({ messages: input.messages, turnInput: input.turnInput, diff --git a/integrations/eve/src/errors.ts b/integrations/eve/src/errors.ts index 422a60a4a..d6f95e364 100644 --- a/integrations/eve/src/errors.ts +++ b/integrations/eve/src/errors.ts @@ -1,3 +1,39 @@ export function errorMessage(error: unknown): string { return error instanceof Error ? error.message : "Unknown Mem0 error"; } + +export function isSetupError(error: unknown): boolean { + if (!(error instanceof Error)) { + return false; + } + const text = `${error.name} ${error.message}`.toLowerCase(); + return ( + text.includes("api key") || + text.includes("cannot be empty") || + text.includes("authentication") || + text.includes("unauthorized") || + text.includes("401") || + text.includes("403") + ); +} + +export function isNotFoundError(error: unknown): boolean { + if (!(error instanceof Error)) { + return false; + } + const text = `${error.name} ${error.message}`.toLowerCase(); + return text.includes("not found") || text.includes("404"); +} + +export function logProviderError( + scope: string, + error: unknown, + extra: Readonly>, +): void { + console.error(`[@mem0/eve] ${scope}`, { + error, + name: error instanceof Error ? error.name : undefined, + message: errorMessage(error), + ...extra, + }); +} diff --git a/integrations/eve/src/idempotency.ts b/integrations/eve/src/idempotency.ts index 6f41726e0..c1a8eea47 100644 --- a/integrations/eve/src/idempotency.ts +++ b/integrations/eve/src/idempotency.ts @@ -1,5 +1,7 @@ const DEFAULT_LIMIT = 256; +// In-process fast path only. Durable replay after restart is handled by +// listing memories with metadata.operation_id before add. export function createIdempotencyGate(limit = DEFAULT_LIMIT) { const seen = new Map>(); diff --git a/integrations/eve/src/index.ts b/integrations/eve/src/index.ts index 024ecfaee..bf1c81c1b 100644 --- a/integrations/eve/src/index.ts +++ b/integrations/eve/src/index.ts @@ -1,3 +1,8 @@ export { mem0Provider, mem0Provider as default } from "./provider.js"; -export type { Mem0ApiKey, Mem0ProviderOptions } from "./options.js"; +export type { + Mem0ApiKey, + Mem0InjectedProviderOptions, + Mem0ProviderOptions, + Mem0RemoteProviderOptions, +} from "./options.js"; export type { MemoryStore, MemoryMessage, SearchHit } from "./store.js"; diff --git a/integrations/eve/src/messages.ts b/integrations/eve/src/messages.ts index ef76ca4e0..18d7dd36f 100644 --- a/integrations/eve/src/messages.ts +++ b/integrations/eve/src/messages.ts @@ -5,27 +5,29 @@ export interface ConversationMessage { readonly content: unknown; } +function textFromPart(part: unknown): string { + if (typeof part === "string") { + return part; + } + if (part && typeof part === "object" && "text" in part) { + const text = (part as { text: unknown }).text; + return typeof text === "string" ? text : ""; + } + return ""; +} + export function extractText(content: unknown): string { if (typeof content === "string") { return content.trim(); } + if (content && typeof content === "object" && !Array.isArray(content)) { + return textFromPart(content).trim(); + } if (!Array.isArray(content)) { return ""; } - return content - .map((part) => { - if (typeof part === "string") { - return part; - } - if (part && typeof part === "object" && "text" in part) { - const text = (part as { text: unknown }).text; - return typeof text === "string" ? text : ""; - } - return ""; - }) - .join("\n") - .trim(); + return content.map(textFromPart).join("\n").trim(); } export function lastUserText(messages: readonly ConversationMessage[]): string { @@ -70,6 +72,7 @@ export function completedTurnMessages(input: { return []; } + // Pair this turn's users with the latest assistant in the settled history. const history = conversationMessages(input.messages); const lastAssistant = [...history] .reverse() diff --git a/integrations/eve/src/options.ts b/integrations/eve/src/options.ts index 3e37c1417..c370bd4c2 100644 --- a/integrations/eve/src/options.ts +++ b/integrations/eve/src/options.ts @@ -2,9 +2,7 @@ import type { MemoryStore } from "./store.js"; export type Mem0ApiKey = string | (() => string | Promise); -export interface Mem0ProviderOptions { - readonly apiKey: Mem0ApiKey; - readonly host?: string; +export interface Mem0SharedProviderOptions { readonly topK?: number; readonly threshold?: number; readonly rerank?: boolean; @@ -16,11 +14,23 @@ export interface Mem0ProviderOptions { readonly enabled?: boolean; }; readonly metadata?: Readonly>; - readonly store?: MemoryStore; } -export interface ResolvedMem0ProviderOptions { +export interface Mem0RemoteProviderOptions extends Mem0SharedProviderOptions { readonly apiKey: Mem0ApiKey; + readonly host?: string; +} + +export interface Mem0InjectedProviderOptions extends Mem0SharedProviderOptions { + readonly store: MemoryStore; + readonly apiKey?: Mem0ApiKey; + readonly host?: string; +} + +export type Mem0ProviderOptions = Mem0RemoteProviderOptions | Mem0InjectedProviderOptions; + +export interface ResolvedMem0ProviderOptions { + readonly apiKey?: Mem0ApiKey; readonly host: string; readonly topK: number; readonly threshold: number; @@ -36,13 +46,38 @@ export interface ResolvedMem0ProviderOptions { readonly store?: MemoryStore; } +function validateApiKey(apiKey: Mem0ApiKey): void { + if (typeof apiKey === "string" && apiKey.trim().length === 0) { + throw new Error("Mem0 API key cannot be empty"); + } +} + +function resolveHost(host: string | undefined): string { + const trimmed = host?.trim() ?? ""; + if (trimmed.length === 0) { + return "https://api.mem0.ai"; + } + + let parsed: URL; + try { + parsed = new URL(trimmed); + } catch { + throw new Error("host must be an http or https URL"); + } + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { + throw new Error("host must be an http or https URL"); + } + return trimmed; +} + export function resolveOptions(options: Mem0ProviderOptions): ResolvedMem0ProviderOptions { + const store = "store" in options ? options.store : undefined; const apiKey = options.apiKey; - if (typeof apiKey === "string") { - const trimmed = apiKey.trim(); - if (trimmed.length === 0) { - throw new Error("Mem0 API key cannot be empty"); - } + if (!store && apiKey === undefined) { + throw new Error("apiKey is required unless a store is provided"); + } + if (apiKey !== undefined) { + validateApiKey(apiKey); } const topK = options.topK ?? 5; @@ -56,8 +91,8 @@ export function resolveOptions(options: Mem0ProviderOptions): ResolvedMem0Provid } return { - apiKey, - host: options.host ?? "https://api.mem0.ai", + ...(apiKey !== undefined ? { apiKey } : {}), + host: resolveHost(options.host), topK, threshold, rerank: options.rerank ?? false, @@ -69,6 +104,6 @@ export function resolveOptions(options: Mem0ProviderOptions): ResolvedMem0Provid enabled: options.capture?.enabled ?? true, }, metadata: options.metadata ?? {}, - ...(options.store ? { store: options.store } : {}), + ...(store ? { store } : {}), }; } diff --git a/integrations/eve/src/provider.ts b/integrations/eve/src/provider.ts index c2e08a129..232450fc2 100644 --- a/integrations/eve/src/provider.ts +++ b/integrations/eve/src/provider.ts @@ -1,11 +1,11 @@ import { defineMemoryProvider, type MemoryProvider } from "eve/memory"; import { captureCompletedTurn } from "./capture.js"; -import { errorMessage } from "./errors.js"; +import { isSetupError, logProviderError } from "./errors.js"; import { createIdempotencyGate } from "./idempotency.js"; import { lastUserText, type ConversationMessage } from "./messages.js"; import { resolveOptions, type Mem0ProviderOptions } from "./options.js"; import { recallMemories } from "./recall.js"; -import { createMem0Store, type MemoryStore } from "./store.js"; +import { createLazyStore, createMem0Store, type MemoryStore } from "./store.js"; import { createMem0Tools } from "./tools.js"; function asConversation(messages: readonly unknown[]): ConversationMessage[] { @@ -14,7 +14,9 @@ function asConversation(messages: readonly unknown[]): ConversationMessage[] { return false; } return ( - "role" in message && typeof (message as { role: unknown }).role === "string" + "role" in message && + typeof (message as { role: unknown }).role === "string" && + "content" in message ); }); } @@ -22,17 +24,21 @@ function asConversation(messages: readonly unknown[]): ConversationMessage[] { export function mem0Provider(options: Mem0ProviderOptions): MemoryProvider { const config = resolveOptions(options); const once = createIdempotencyGate(); - let storePromise: Promise | undefined; + const loadRemoteStore = createLazyStore(async () => { + if (!config.apiKey) { + throw new Error("Mem0 API key cannot be empty"); + } + return createMem0Store({ + apiKey: config.apiKey, + host: config.host, + }); + }); const getStore = async (): Promise => { if (config.store) { return config.store; } - storePromise ??= createMem0Store({ - apiKey: config.apiKey, - host: config.host, - }); - return storePromise; + return loadRemoteStore(); }; const recall = async (context: { @@ -47,7 +53,13 @@ export function mem0Provider(options: Mem0ProviderOptions): MemoryProvider { } const querySource = context.turn?.input ?? context.messages; - const query = lastUserText(asConversation(querySource)); + const conversation = asConversation(querySource); + if (querySource.length > 0 && conversation.length === 0) { + console.error("[@mem0/eve] dropped all recall messages; no searchable user text", { + sessionId: context.session.id, + }); + } + const query = lastUserText(conversation); try { const store = await getStore(); @@ -60,14 +72,13 @@ export function mem0Provider(options: Mem0ProviderOptions): MemoryProvider { rerank: config.rerank, }); } catch (error) { - if (context.abortSignal.aborted) { + if (context.abortSignal.aborted || isSetupError(error)) { throw error; } - console.error("[@mem0/eve] recall failed", { - error: errorMessage(error), + logProviderError("recall failed", error, { sessionId: context.session.id, }); - return null; + throw error; } }; @@ -80,41 +91,36 @@ export function mem0Provider(options: Mem0ProviderOptions): MemoryProvider { ? { capture: { async "turn.completed"(context) { - try { - const store = await getStore(); - await once(context.operationId, async () => { - await captureCompletedTurn({ - store, - scopeKey: context.memory.scope.key, - infer: config.infer, - metadata: { - ...config.metadata, - source: "eve", - operation_id: context.operationId, - session_id: context.session.id, - slot: context.memory.slot, - }, - messages: asConversation(context.messages), - turnInput: asConversation(context.turn.input), - }); + const store = await getStore(); + await once(context.operationId, async () => { + await captureCompletedTurn({ + store, + scopeKey: context.memory.scope.key, + operationId: context.operationId, + infer: config.infer, + metadata: { + ...config.metadata, + source: "eve", + operation_id: context.operationId, + session_id: context.session.id, + slot: context.memory.slot, + }, + messages: asConversation(context.messages), + turnInput: asConversation(context.turn.input), }); - } catch (error) { - if (context.abortSignal.aborted) { - throw error; - } - console.error("[@mem0/eve] capture failed", { - error: errorMessage(error), - sessionId: context.session.id, - turnId: context.turn.id, - }); - } + }); }, }, } : {}), async tools(context) { const store = await getStore(); - return createMem0Tools(store, context.memory.scope.key); + return createMem0Tools(store, context.memory.scope.key, { + topK: config.topK, + threshold: config.threshold, + rerank: config.rerank, + infer: config.infer, + }); }, }); } diff --git a/integrations/eve/src/recall.ts b/integrations/eve/src/recall.ts index 18a39baf7..e2eec2ec4 100644 --- a/integrations/eve/src/recall.ts +++ b/integrations/eve/src/recall.ts @@ -7,8 +7,9 @@ export interface RecallMessage { export function formatRecallMessages(hits: readonly SearchHit[]): RecallMessage[] { return hits.flatMap((hit) => { + const id = hit.id.trim(); const content = hit.memory.trim(); - return content.length > 0 ? [{ id: hit.id, content }] : []; + return id.length > 0 && content.length > 0 ? [{ id, content }] : []; }); } @@ -26,7 +27,7 @@ export async function recallMemories(input: { } const { results } = await input.store.search(query, { - filters: { user_id: input.scopeKey }, + userId: input.scopeKey, topK: input.topK, threshold: input.threshold, rerank: input.rerank, diff --git a/integrations/eve/src/store.ts b/integrations/eve/src/store.ts index bf0148e9d..9d7d27b42 100644 --- a/integrations/eve/src/store.ts +++ b/integrations/eve/src/store.ts @@ -1,4 +1,5 @@ import type { Mem0ApiKey } from "./options.js"; +import { isNotFoundError } from "./errors.js"; export type MemoryRole = "user" | "assistant"; @@ -12,25 +13,94 @@ export interface SearchHit { readonly memory: string; } -export interface AddMemoryInput { +export interface MemoryRecord { + readonly id: string; readonly userId: string; - readonly infer: boolean; readonly metadata: Readonly>; } +export type StoreMetadata = Readonly>; + +export interface AddMemoryInput { + readonly userId: string; + readonly infer: boolean; + readonly metadata: StoreMetadata; +} + export interface SearchMemoryInput { - readonly filters: { - readonly user_id: string; - }; + readonly userId: string; readonly topK: number; readonly threshold: number; readonly rerank: boolean; } export interface MemoryStore { - add(messages: readonly MemoryMessage[], input: AddMemoryInput): Promise; + add(messages: readonly MemoryMessage[], input: AddMemoryInput): Promise; search(query: string, input: SearchMemoryInput): Promise<{ results: readonly SearchHit[] }>; - delete(memoryId: string): Promise; + get(memoryId: string): Promise; + listByMetadata(input: { + readonly userId: string; + readonly metadata: Readonly>; + }): Promise; + delete(memoryId: string, userId: string): Promise; +} + +export function parseSearchHit(item: unknown): SearchHit | null { + if (!item || typeof item !== "object") { + return null; + } + const record = item as Record; + const nested = + record.data && typeof record.data === "object" + ? (record.data as Record) + : undefined; + const idValue = record.id ?? record.memory_id ?? nested?.id; + const id = + typeof idValue === "string" + ? idValue.trim() + : typeof idValue === "number" + ? String(idValue) + : ""; + const memoryValue = + record.memory ?? record.text ?? nested?.memory ?? nested?.text; + const memory = typeof memoryValue === "string" ? memoryValue : ""; + if (id.length === 0 || memory.trim().length === 0) { + return null; + } + return { id, memory }; +} + +export function parseMemoryRecord(item: unknown): MemoryRecord | null { + if (!item || typeof item !== "object") { + return null; + } + const record = item as Record; + const idValue = record.id ?? record.memory_id; + const id = typeof idValue === "string" ? idValue.trim() : ""; + const userIdValue = record.userId ?? record.user_id; + const userId = typeof userIdValue === "string" ? userIdValue : ""; + if (id.length === 0 || userId.length === 0) { + return null; + } + const metadata = + record.metadata && typeof record.metadata === "object" + ? (record.metadata as Record) + : {}; + return { id, userId, metadata }; +} + +function asItemList(response: unknown, operation: string): unknown[] { + if (Array.isArray(response)) { + return response; + } + if (response && typeof response === "object") { + const record = response as Record; + const raw = record.results ?? record.memories; + if (Array.isArray(raw)) { + return raw; + } + } + throw new Error(`Mem0 ${operation} returned an unexpected response shape`); } export async function resolveApiKey(apiKey: Mem0ApiKey): Promise { @@ -42,6 +112,20 @@ export async function resolveApiKey(apiKey: Mem0ApiKey): Promise { return trimmed; } +export function createLazyStore(factory: () => Promise) { + let pending: Promise | undefined; + + return async (): Promise => { + if (!pending) { + pending = factory().catch((error: unknown) => { + pending = undefined; + throw error; + }); + } + return pending; + }; +} + export async function createMem0Store(input: { apiKey: Mem0ApiKey; host: string; @@ -52,9 +136,9 @@ export async function createMem0Store(input: { host: input.host, }); - return { + const store: MemoryStore = { async add(messages, options) { - return client.add([...messages], { + await client.add([...messages], { userId: options.userId, infer: options.infer, metadata: { ...options.metadata }, @@ -62,22 +146,47 @@ export async function createMem0Store(input: { }, async search(query, options) { const response = await client.search(query, { - filters: options.filters, + filters: { user_id: options.userId }, topK: options.topK, threshold: options.threshold, rerank: options.rerank, }); - const results = Array.isArray(response?.results) ? response.results : []; return { - results: results.flatMap((item) => { - const id = typeof item.id === "string" ? item.id : ""; - const memory = typeof item.memory === "string" ? item.memory : ""; - return id && memory ? [{ id, memory }] : []; + results: asItemList(response, "search").flatMap((item) => { + const hit = parseSearchHit(item); + return hit ? [hit] : []; }), }; }, - async delete(memoryId) { - return client.delete(memoryId); + async get(memoryId) { + try { + return parseMemoryRecord(await client.get(memoryId)); + } catch (error) { + if (isNotFoundError(error)) { + return null; + } + throw error; + } + }, + async listByMetadata({ userId, metadata }) { + const response = await client.getAll({ + filters: { + AND: [{ user_id: userId }, { metadata }], + }, + pageSize: 5, + }); + return asItemList(response, "getAll").flatMap((item) => { + const record = parseMemoryRecord(item); + return record && record.userId === userId ? [record] : []; + }); + }, + async delete(memoryId, userId) { + const record = await store.get(memoryId); + if (!record || record.userId !== userId) { + throw new Error("Memory not found"); + } + await client.delete(memoryId); }, }; + return store; } diff --git a/integrations/eve/src/tools.ts b/integrations/eve/src/tools.ts index c8bd9eddc..3d65b1ede 100644 --- a/integrations/eve/src/tools.ts +++ b/integrations/eve/src/tools.ts @@ -2,7 +2,18 @@ import { defineTool } from "eve/tools"; import { z } from "zod"; import type { MemoryStore } from "./store.js"; -export function createMem0Tools(store: MemoryStore, scopeKey: string) { +export interface Mem0ToolOptions { + readonly topK: number; + readonly threshold: number; + readonly rerank: boolean; + readonly infer: boolean; +} + +export function createMem0Tools( + store: MemoryStore, + scopeKey: string, + options: Mem0ToolOptions, +) { return { search: defineTool({ description: "Search long-term memories for the current caller.", @@ -11,10 +22,10 @@ export function createMem0Tools(store: MemoryStore, scopeKey: string) { }), async execute({ query }) { const { results } = await store.search(query, { - filters: { user_id: scopeKey }, - topK: 8, - threshold: 0.1, - rerank: false, + userId: scopeKey, + topK: options.topK, + threshold: options.threshold, + rerank: options.rerank, }); return { memories: results.map((hit) => ({ @@ -33,7 +44,7 @@ export function createMem0Tools(store: MemoryStore, scopeKey: string) { async execute({ text }) { await store.add([{ role: "user", content: text }], { userId: scopeKey, - infer: true, + infer: options.infer, metadata: { source: "eve-tool" }, }); return { saved: true }; @@ -45,7 +56,7 @@ export function createMem0Tools(store: MemoryStore, scopeKey: string) { id: z.string().min(1), }), async execute({ id }) { - await store.delete(id); + await store.delete(id, scopeKey); return { deleted: true }; }, }), diff --git a/integrations/eve/tests/capture.test.ts b/integrations/eve/tests/capture.test.ts index da0351a17..d2a653162 100644 --- a/integrations/eve/tests/capture.test.ts +++ b/integrations/eve/tests/capture.test.ts @@ -8,8 +8,9 @@ describe("captureCompletedTurn", () => { const captured = await captureCompletedTurn({ store, scopeKey: "scope_abc", - infer: true, - metadata: { source: "eve" }, + operationId: "op_1", + infer: false, + metadata: { source: "eve", operation_id: "op_1" }, turnInput: [{ role: "user", content: "I am vegetarian" }], messages: [ { role: "user", content: "I am vegetarian" }, @@ -21,6 +22,8 @@ describe("captureCompletedTurn", () => { expect(store.added).toEqual([ { userId: "scope_abc", + infer: false, + metadata: { source: "eve", operation_id: "op_1" }, messages: [ { role: "user", content: "I am vegetarian" }, { role: "assistant", content: "Got it." }, @@ -34,12 +37,38 @@ describe("captureCompletedTurn", () => { const captured = await captureCompletedTurn({ store, scopeKey: "scope_abc", + operationId: "op_1", infer: true, - metadata: {}, + metadata: { operation_id: "op_1" }, turnInput: [], messages: [], }); expect(captured).toBe(false); expect(store.added).toEqual([]); }); + + it("skips add when the operation id was already captured", async () => { + const store = createFakeStore([ + { + id: "mem_existing", + memory: "already stored", + metadata: { operation_id: "op_replay" }, + }, + ]); + const captured = await captureCompletedTurn({ + store, + scopeKey: "scope_abc", + operationId: "op_replay", + infer: true, + metadata: { operation_id: "op_replay" }, + turnInput: [{ role: "user", content: "I am vegetarian" }], + messages: [ + { role: "user", content: "I am vegetarian" }, + { role: "assistant", content: "Got it." }, + ], + }); + + expect(captured).toBe(false); + expect(store.added).toEqual([]); + }); }); diff --git a/integrations/eve/tests/errors.test.ts b/integrations/eve/tests/errors.test.ts new file mode 100644 index 000000000..d9e672eb1 --- /dev/null +++ b/integrations/eve/tests/errors.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it, vi } from "vitest"; +import { + errorMessage, + isNotFoundError, + isSetupError, + logProviderError, +} from "../src/errors.js"; + +describe("errors", () => { + it("classifies setup and not-found errors", () => { + expect(isSetupError(new Error("Mem0 API key cannot be empty"))).toBe(true); + expect(isSetupError(Object.assign(new Error("denied"), { name: "AuthenticationError" }))).toBe( + true, + ); + expect(isSetupError(new Error("mem0 down"))).toBe(false); + expect(isNotFoundError(new Error("Memory not found"))).toBe(true); + expect(isNotFoundError(new Error("HTTP 404"))).toBe(true); + expect(errorMessage("x")).toBe("Unknown Mem0 error"); + }); + + it("logs the original error object", () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + const failure = Object.assign(new Error("HTTP 401"), { + name: "AuthenticationError", + }); + try { + logProviderError("recall failed", failure, { sessionId: "sess_1" }); + expect(error).toHaveBeenCalledWith("[@mem0/eve] recall failed", { + error: failure, + name: "AuthenticationError", + message: "HTTP 401", + sessionId: "sess_1", + }); + } finally { + error.mockRestore(); + } + }); +}); diff --git a/integrations/eve/tests/helpers.ts b/integrations/eve/tests/helpers.ts index e50440709..f84555ee7 100644 --- a/integrations/eve/tests/helpers.ts +++ b/integrations/eve/tests/helpers.ts @@ -1,29 +1,86 @@ -import type { MemoryMessage, MemoryStore, SearchHit } from "../src/store.js"; +import type { + AddMemoryInput, + MemoryMessage, + MemoryRecord, + MemoryStore, + SearchHit, + SearchMemoryInput, +} from "../src/store.js"; -export function createFakeStore(hits: SearchHit[] = []): MemoryStore & { - added: Array<{ messages: readonly MemoryMessage[]; userId: string }>; - searched: Array<{ query: string; userId: string }>; +export type FakeHit = SearchHit & { + readonly userId?: string; + readonly metadata?: Readonly>; +}; + +export type FakeAdd = { + messages: readonly MemoryMessage[]; + userId: string; + infer: boolean; + metadata: Readonly>; +}; + +export type FakeSearch = SearchMemoryInput & { + query: string; +}; + +export function createFakeStore(hits: FakeHit[] = []): MemoryStore & { + added: FakeAdd[]; + searched: FakeSearch[]; deleted: string[]; + records: MemoryRecord[]; } { - const added: Array<{ messages: readonly MemoryMessage[]; userId: string }> = []; - const searched: Array<{ query: string; userId: string }> = []; + const added: FakeAdd[] = []; + const searched: FakeSearch[] = []; const deleted: string[] = []; + const records: MemoryRecord[] = hits.map((hit) => ({ + id: hit.id, + userId: hit.userId ?? "scope_abc", + metadata: hit.metadata ?? {}, + })); return { added, searched, deleted, + records, async add(messages, input) { - added.push({ messages, userId: input.userId }); - return { eventId: "evt_1" }; + added.push({ + messages, + userId: input.userId, + infer: input.infer, + metadata: input.metadata, + }); + records.push({ + id: `mem_added_${added.length}`, + userId: input.userId, + metadata: input.metadata, + }); }, async search(query, input) { - searched.push({ query, userId: input.filters.user_id }); - return { results: hits }; + searched.push({ query, ...input }); + return { + results: hits.filter((hit) => (hit.userId ?? "scope_abc") === input.userId), + }; }, - async delete(memoryId) { + async get(memoryId) { + return records.find((record) => record.id === memoryId) ?? null; + }, + async listByMetadata({ userId, metadata }) { + return records.filter((record) => { + if (record.userId !== userId) { + return false; + } + return Object.entries(metadata).every( + ([key, value]) => record.metadata[key] === value, + ); + }); + }, + async delete(memoryId, userId) { + const record = records.find((item) => item.id === memoryId); + if (!record || record.userId !== userId) { + throw new Error("Memory not found"); + } deleted.push(memoryId); - return { message: "ok" }; }, }; } @@ -31,6 +88,14 @@ export function createFakeStore(hits: SearchHit[] = []): MemoryStore & { export function memoryContext(input?: { scopeKey?: string; operationId?: string; + aborted?: boolean; + turn?: + | { + id?: string; + sequence?: number; + input: Array<{ role: string; content: unknown }>; + } + | null; turnInput?: Array<{ role: string; content: unknown }>; messages?: Array<{ role: string; content: unknown }>; }): { @@ -46,10 +111,21 @@ export function memoryContext(input?: { id: string; sequence: number; input: Array<{ role: string; content: unknown }>; - }; + } | null; } { + const controller = new AbortController(); + if (input?.aborted) { + controller.abort(); + } + + const turnInput = + input?.turn === null + ? undefined + : (input?.turn?.input ?? + input?.turnInput ?? [{ role: "user", content: "I am vegetarian" }]); + return { - abortSignal: new AbortController().signal, + abortSignal: controller.signal, operationId: input?.operationId ?? "op_1", session: { id: "sess_1" }, memory: { @@ -64,10 +140,13 @@ export function memoryContext(input?: { { role: "user", content: "I am vegetarian" }, { role: "assistant", content: "I will remember that." }, ], - turn: { - id: "turn_1", - sequence: 1, - input: input?.turnInput ?? [{ role: "user", content: "I am vegetarian" }], - }, + turn: + input?.turn === null + ? null + : { + id: input?.turn?.id ?? "turn_1", + sequence: input?.turn?.sequence ?? 1, + input: turnInput ?? [{ role: "user", content: "I am vegetarian" }], + }, }; } diff --git a/integrations/eve/tests/idempotency.test.ts b/integrations/eve/tests/idempotency.test.ts index 56bb74a0b..d92af9069 100644 --- a/integrations/eve/tests/idempotency.test.ts +++ b/integrations/eve/tests/idempotency.test.ts @@ -29,4 +29,19 @@ describe("createIdempotencyGate", () => { await once("op_1", work); expect(calls).toBe(2); }); + + it("evicts the oldest id after the cap", async () => { + const once = createIdempotencyGate(2); + let calls = 0; + const work = async () => { + calls += 1; + }; + + await once("op_1", work); + await once("op_2", work); + await once("op_3", work); + await once("op_1", work); + + expect(calls).toBe(4); + }); }); diff --git a/integrations/eve/tests/messages.test.ts b/integrations/eve/tests/messages.test.ts index 5f1de765a..4e8fca5e1 100644 --- a/integrations/eve/tests/messages.test.ts +++ b/integrations/eve/tests/messages.test.ts @@ -20,6 +20,10 @@ describe("extractText", () => { ).toBe("I like\ntea"); }); + it("reads a single text object", () => { + expect(extractText({ type: "text", text: " solo " })).toBe("solo"); + }); + it("ignores non-text parts", () => { expect(extractText([{ type: "image", url: "x" }])).toBe(""); }); diff --git a/integrations/eve/tests/options.test.ts b/integrations/eve/tests/options.test.ts index 6b67ff9b0..6b6ab80a9 100644 --- a/integrations/eve/tests/options.test.ts +++ b/integrations/eve/tests/options.test.ts @@ -4,7 +4,8 @@ import { createFakeStore } from "./helpers.js"; describe("resolveOptions", () => { it("applies defaults", () => { - expect(resolveOptions({ apiKey: "m0-test" })).toMatchObject({ + expect(resolveOptions({ apiKey: "m0-test" })).toEqual({ + apiKey: "m0-test", host: "https://api.mem0.ai", topK: 5, threshold: 0.1, @@ -12,6 +13,7 @@ describe("resolveOptions", () => { infer: true, autoSearch: { enabled: true }, capture: { enabled: true }, + metadata: {}, }); }); @@ -19,8 +21,56 @@ describe("resolveOptions", () => { expect(() => resolveOptions({ apiKey: " " })).toThrow(/empty/); }); + it("requires an api key when no store is provided", () => { + expect(() => resolveOptions({} as never)).toThrow(/apiKey is required/); + }); + + it("allows a store without an api key", () => { + const store = createFakeStore(); + expect(resolveOptions({ store }).store).toBe(store); + }); + + it("does not invoke a function api key at resolve time", () => { + let calls = 0; + const apiKey = () => { + calls += 1; + return ""; + }; + expect(() => resolveOptions({ apiKey })).not.toThrow(); + expect(calls).toBe(0); + }); + it("rejects an invalid topK", () => { expect(() => resolveOptions({ apiKey: "m0-test", topK: 0 })).toThrow(/topK/); + expect(() => resolveOptions({ apiKey: "m0-test", topK: 101 })).toThrow(/topK/); + expect(() => resolveOptions({ apiKey: "m0-test", topK: 1.5 })).toThrow(/topK/); + }); + + it("rejects an invalid threshold", () => { + expect(() => resolveOptions({ apiKey: "m0-test", threshold: -0.1 })).toThrow( + /threshold/, + ); + expect(() => resolveOptions({ apiKey: "m0-test", threshold: 1.1 })).toThrow( + /threshold/, + ); + expect(() => resolveOptions({ apiKey: "m0-test", threshold: Number.NaN })).toThrow( + /threshold/, + ); + }); + + it("rejects a non-http host", () => { + expect(() => resolveOptions({ apiKey: "m0-test", host: "localhost" })).toThrow( + /host/, + ); + expect(() => resolveOptions({ apiKey: "m0-test", host: "ftp://mem0.ai" })).toThrow( + /host/, + ); + }); + + it("treats a blank host as the default", () => { + expect(resolveOptions({ apiKey: "m0-test", host: " " }).host).toBe( + "https://api.mem0.ai", + ); }); it("keeps an injected store", () => { diff --git a/integrations/eve/tests/provider.test.ts b/integrations/eve/tests/provider.test.ts index a34313314..e6a30af9d 100644 --- a/integrations/eve/tests/provider.test.ts +++ b/integrations/eve/tests/provider.test.ts @@ -1,4 +1,5 @@ import type { + MemoryCompactionCompletedContext, MemoryToolsContext, MemoryTurnCompletedContext, MemoryTurnStartedContext, @@ -19,6 +20,15 @@ function completedContext( return memoryContext(input) as unknown as MemoryTurnCompletedContext; } +function compactionContext( + input?: Parameters[0], +): MemoryCompactionCompletedContext { + return memoryContext({ + ...input, + turn: input?.turn === undefined ? null : input.turn, + }) as unknown as MemoryCompactionCompletedContext; +} + function toolsContext( input?: Parameters[0], ): MemoryToolsContext { @@ -32,10 +42,20 @@ async function runTool( return tool.execute(input as never, {} as never); } +function requireCapture( + provider: ReturnType, +): NonNullable["turn.completed"]> { + const capture = provider.capture?.["turn.completed"]; + if (!capture) { + throw new Error("expected turn.completed"); + } + return capture; +} + describe("mem0Provider", () => { it("recalls memories for the locked scope on turn start", async () => { const store = createFakeStore([{ id: "mem_1", memory: "User likes tea" }]); - const provider = mem0Provider({ apiKey: "m0-test", store }); + const provider = mem0Provider({ store }); const result = await provider.recall["turn.started"]( startedContext({ turnInput: [{ role: "user", content: "What do I drink?" }], @@ -43,31 +63,110 @@ describe("mem0Provider", () => { ); expect(store.searched).toEqual([ - { query: "What do I drink?", userId: "scope_abc" }, + { + query: "What do I drink?", + userId: "scope_abc", + topK: 5, + threshold: 0.1, + rerank: false, + }, ]); expect(result).toEqual({ messages: [{ id: "mem_1", content: "User likes tea" }], }); }); - it("does not fail the turn when search throws", async () => { + it("forwards recall search options", async () => { + const store = createFakeStore([{ id: "mem_1", memory: "User likes tea" }]); + const provider = mem0Provider({ + store, + topK: 3, + threshold: 0.5, + rerank: true, + }); + await provider.recall["turn.started"]( + startedContext({ + turnInput: [{ role: "user", content: "tea" }], + }), + ); + expect(store.searched[0]).toMatchObject({ + topK: 3, + threshold: 0.5, + rerank: true, + }); + }); + + it("skips search when autoSearch is disabled", async () => { + const store = createFakeStore([{ id: "mem_1", memory: "User likes tea" }]); + const provider = mem0Provider({ store, autoSearch: { enabled: false } }); + await expect( + provider.recall["turn.started"](startedContext()), + ).resolves.toBeNull(); + expect(store.searched).toEqual([]); + }); + + it("recalls after compaction when turn is null", async () => { + const store = createFakeStore([{ id: "mem_1", memory: "User likes tea" }]); + const provider = mem0Provider({ store }); + const recallAfterCompaction = provider.recall["compaction.completed"]; + if (!recallAfterCompaction) { + throw new Error("expected compaction.completed"); + } + const result = await recallAfterCompaction( + compactionContext({ + messages: [ + { role: "user", content: "What do I drink?" }, + { role: "assistant", content: "tea" }, + ], + }), + ); + + expect(store.searched).toEqual([ + { + query: "What do I drink?", + userId: "scope_abc", + topK: 5, + threshold: 0.1, + rerank: false, + }, + ]); + expect(result).toEqual({ + messages: [{ id: "mem_1", content: "User likes tea" }], + }); + }); + + it("fails the turn when search throws", async () => { const store = createFakeStore(); store.search = async () => { throw new Error("mem0 down"); }; - const provider = mem0Provider({ apiKey: "m0-test", store }); + const provider = mem0Provider({ store }); const error = vi.spyOn(console, "error").mockImplementation(() => {}); - await expect( - provider.recall["turn.started"](startedContext()), - ).resolves.toBeNull(); + try { + await expect( + provider.recall["turn.started"](startedContext()), + ).rejects.toThrow("mem0 down"); + } finally { + error.mockRestore(); + } + }); - error.mockRestore(); + it("rethrows when recall is aborted", async () => { + const store = createFakeStore(); + store.search = async () => { + throw new Error("cancelled"); + }; + const provider = mem0Provider({ store }); + + await expect( + provider.recall["turn.started"](startedContext({ aborted: true })), + ).rejects.toThrow("cancelled"); }); it("captures a completed turn once per operation id", async () => { const store = createFakeStore(); - const provider = mem0Provider({ apiKey: "m0-test", store }); + const provider = mem0Provider({ store }); const capture = provider.capture?.["turn.completed"]; expect(capture).toBeTypeOf("function"); @@ -76,12 +175,42 @@ describe("mem0Provider", () => { await capture!(context); expect(store.added).toHaveLength(1); - expect(store.added[0]?.userId).toBe("scope_abc"); + expect(store.added[0]).toMatchObject({ + userId: "scope_abc", + infer: true, + metadata: { + source: "eve", + operation_id: "op_replay", + session_id: "sess_1", + slot: "mem0", + }, + }); + }); + + it("does not recapture after process restart when operation metadata exists", async () => { + const store = createFakeStore(); + const first = requireCapture(mem0Provider({ store })); + await first(completedContext({ operationId: "op_replay" })); + + const restarted = requireCapture(mem0Provider({ store })); + await restarted(completedContext({ operationId: "op_replay" })); + + expect(store.added).toHaveLength(1); + }); + + it("surfaces capture store failures", async () => { + const store = createFakeStore(); + store.add = async () => { + throw new Error("write failed"); + }; + + await expect( + requireCapture(mem0Provider({ store }))(completedContext()), + ).rejects.toThrow("write failed"); }); it("omits capture when it is disabled", () => { const provider = mem0Provider({ - apiKey: "m0-test", store: createFakeStore(), capture: { enabled: false }, }); @@ -90,7 +219,13 @@ describe("mem0Provider", () => { it("binds tools to the locked scope", async () => { const store = createFakeStore([{ id: "mem_1", memory: "likes tea" }]); - const provider = mem0Provider({ apiKey: "m0-test", store }); + const provider = mem0Provider({ + store, + topK: 3, + threshold: 0.4, + rerank: true, + infer: false, + }); const tools = await provider.tools!(toolsContext()); if (!tools) { throw new Error("expected tools"); @@ -114,8 +249,52 @@ describe("mem0Provider", () => { }); expect(remember).toEqual({ saved: true }); expect(forget).toEqual({ deleted: true }); - expect(store.searched[0]?.userId).toBe("scope_abc"); - expect(store.added[0]?.userId).toBe("scope_abc"); + expect(store.searched[0]).toMatchObject({ + userId: "scope_abc", + topK: 3, + threshold: 0.4, + rerank: true, + }); + expect(store.added[0]).toMatchObject({ + userId: "scope_abc", + infer: false, + metadata: { source: "eve-tool" }, + messages: [{ role: "user", content: "Allergic to peanuts" }], + }); expect(store.deleted).toEqual(["mem_1"]); }); + + it("refuses to forget a memory from another scope", async () => { + const store = createFakeStore([ + { id: "mem_other", memory: "secret", userId: "scope_other" }, + ]); + const provider = mem0Provider({ store }); + const tools = await provider.tools!(toolsContext()); + const forgetTool = tools?.forget; + if (!forgetTool) { + throw new Error("expected forget tool"); + } + + await expect(runTool(forgetTool, { id: "mem_other" })).rejects.toThrow( + /Memory not found/, + ); + expect(store.deleted).toEqual([]); + }); + + it("surfaces tool store failures", async () => { + const store = createFakeStore(); + store.add = async () => { + throw new Error("add failed"); + }; + const provider = mem0Provider({ store }); + const tools = await provider.tools!(toolsContext()); + const rememberTool = tools?.remember; + if (!rememberTool) { + throw new Error("expected remember tool"); + } + + await expect( + runTool(rememberTool, { text: "remember this" }), + ).rejects.toThrow("add failed"); + }); }); diff --git a/integrations/eve/tests/recall.test.ts b/integrations/eve/tests/recall.test.ts index da95f26a3..7d55eb647 100644 --- a/integrations/eve/tests/recall.test.ts +++ b/integrations/eve/tests/recall.test.ts @@ -3,11 +3,12 @@ import { formatRecallMessages, recallMemories } from "../src/recall.js"; import { createFakeStore } from "./helpers.js"; describe("formatRecallMessages", () => { - it("drops empty memories", () => { + it("drops empty memories and empty ids", () => { expect( formatRecallMessages([ { id: "1", memory: " likes tea " }, { id: "2", memory: " " }, + { id: " ", memory: "kept text" }, ]), ).toEqual([{ id: "1", content: "likes tea" }]); }); @@ -20,13 +21,19 @@ describe("recallMemories", () => { store, scopeKey: "scope_abc", query: "What does the user drink?", - topK: 5, - threshold: 0.1, - rerank: false, + topK: 3, + threshold: 0.5, + rerank: true, }); expect(store.searched).toEqual([ - { query: "What does the user drink?", userId: "scope_abc" }, + { + query: "What does the user drink?", + userId: "scope_abc", + topK: 3, + threshold: 0.5, + rerank: true, + }, ]); expect(result).toEqual({ messages: [{ id: "mem_1", content: "User likes tea" }], @@ -47,4 +54,18 @@ describe("recallMemories", () => { ).resolves.toBeNull(); expect(store.searched).toEqual([]); }); + + it("returns null when search has no usable hits", async () => { + const store = createFakeStore([{ id: " ", memory: " " }]); + await expect( + recallMemories({ + store, + scopeKey: "scope_abc", + query: "tea", + topK: 5, + threshold: 0.1, + rerank: false, + }), + ).resolves.toBeNull(); + }); }); diff --git a/integrations/eve/tests/store.test.ts b/integrations/eve/tests/store.test.ts new file mode 100644 index 000000000..1ed3ccd15 --- /dev/null +++ b/integrations/eve/tests/store.test.ts @@ -0,0 +1,217 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +const { MemoryClient, add, search, get, getAll, del } = vi.hoisted(() => { + const add = vi.fn(); + const search = vi.fn(); + const get = vi.fn(); + const getAll = vi.fn(); + const del = vi.fn(); + const MemoryClient = vi.fn( + class { + add = add; + search = search; + get = get; + getAll = getAll; + delete = del; + }, + ); + return { MemoryClient, add, search, get, getAll, del }; +}); + +vi.mock("mem0ai", () => ({ + default: MemoryClient, +})); + +import { + createLazyStore, + createMem0Store, + parseMemoryRecord, + parseSearchHit, + resolveApiKey, +} from "../src/store.js"; + +describe("parseSearchHit", () => { + it("accepts id, memory_id, nested text, and numeric ids", () => { + expect(parseSearchHit({ id: 12, memory: "tea" })).toEqual({ + id: "12", + memory: "tea", + }); + expect( + parseSearchHit({ memory_id: "m1", data: { memory: "nested" } }), + ).toEqual({ id: "m1", memory: "nested" }); + expect(parseSearchHit({ id: "m2", text: "plain" })).toEqual({ + id: "m2", + memory: "plain", + }); + expect(parseSearchHit({ id: "", memory: "x" })).toBeNull(); + }); +}); + +describe("parseMemoryRecord", () => { + it("requires id and userId", () => { + expect( + parseMemoryRecord({ + id: "m1", + user_id: "scope_abc", + metadata: { source: "eve" }, + }), + ).toEqual({ + id: "m1", + userId: "scope_abc", + metadata: { source: "eve" }, + }); + expect(parseMemoryRecord({ id: "m1" })).toBeNull(); + }); +}); + +describe("resolveApiKey", () => { + it("trims string keys and rejects empty values", async () => { + await expect(resolveApiKey(" token ")).resolves.toBe("token"); + await expect(resolveApiKey(" ")).rejects.toThrow(/empty/); + }); + + it("resolves async getters", async () => { + await expect(resolveApiKey(async () => " secret ")).resolves.toBe("secret"); + await expect(resolveApiKey(async () => "")).rejects.toThrow(/empty/); + }); +}); + +describe("createLazyStore", () => { + it("retries after a failed factory call", async () => { + let calls = 0; + const load = createLazyStore(async () => { + calls += 1; + if (calls === 1) { + throw new Error("unavailable"); + } + return { name: "store" } as never; + }); + + await expect(load()).rejects.toThrow("unavailable"); + await expect(load()).resolves.toEqual({ name: "store" }); + expect(calls).toBe(2); + }); +}); + +describe("createMem0Store", () => { + beforeEach(() => { + add.mockReset(); + search.mockReset(); + get.mockReset(); + getAll.mockReset(); + del.mockReset(); + MemoryClient.mockClear(); + }); + + it("constructs the client with a resolved key and host", async () => { + const store = await createMem0Store({ + apiKey: async () => " m0-live ", + host: "https://api.mem0.ai", + }); + expect(store).toBeTruthy(); + expect(MemoryClient).toHaveBeenCalledWith({ + apiKey: "m0-live", + host: "https://api.mem0.ai", + }); + }); + + it("forwards add, search, and metadata filters", async () => { + search.mockResolvedValue({ + results: [{ id: "m1", memory: "likes tea" }, { id: 2, memory: "" }], + }); + getAll.mockResolvedValue({ + results: [{ id: "m9", userId: "scope_abc", metadata: { operation_id: "op_1" } }], + }); + add.mockResolvedValue({ eventId: "evt_1" }); + + const store = await createMem0Store({ + apiKey: "m0-test", + host: "https://api.mem0.ai", + }); + + await store.add([{ role: "user", content: "I like tea" }], { + userId: "scope_abc", + infer: false, + metadata: { source: "eve", operation_id: "op_1" }, + }); + const found = await store.search("tea", { + userId: "scope_abc", + topK: 3, + threshold: 0.5, + rerank: true, + }); + const existing = await store.listByMetadata({ + userId: "scope_abc", + metadata: { operation_id: "op_1" }, + }); + + expect(add).toHaveBeenCalledWith( + [{ role: "user", content: "I like tea" }], + { + userId: "scope_abc", + infer: false, + metadata: { source: "eve", operation_id: "op_1" }, + }, + ); + expect(search).toHaveBeenCalledWith("tea", { + filters: { user_id: "scope_abc" }, + topK: 3, + threshold: 0.5, + rerank: true, + }); + expect(found.results).toEqual([{ id: "m1", memory: "likes tea" }]); + expect(existing).toEqual([ + { + id: "m9", + userId: "scope_abc", + metadata: { operation_id: "op_1" }, + }, + ]); + }); + + it("accepts a bare search array and rejects unknown envelopes", async () => { + const store = await createMem0Store({ + apiKey: "m0-test", + host: "https://api.mem0.ai", + }); + search.mockResolvedValueOnce([{ id: "m1", memory: "tea" }]); + await expect( + store.search("tea", { + userId: "scope_abc", + topK: 5, + threshold: 0.1, + rerank: false, + }), + ).resolves.toEqual({ results: [{ id: "m1", memory: "tea" }] }); + + search.mockResolvedValueOnce({ memories: "nope" }); + await expect( + store.search("tea", { + userId: "scope_abc", + topK: 5, + threshold: 0.1, + rerank: false, + }), + ).rejects.toThrow(/unexpected response shape/); + }); + + it("deletes only when the memory belongs to the scope", async () => { + const store = await createMem0Store({ + apiKey: "m0-test", + host: "https://api.mem0.ai", + }); + + get.mockResolvedValueOnce({ id: "m1", userId: "scope_abc" }); + await store.delete("m1", "scope_abc"); + expect(del).toHaveBeenCalledWith("m1"); + + get.mockResolvedValueOnce({ id: "m2", user_id: "other" }); + await expect(store.delete("m2", "scope_abc")).rejects.toThrow(/Memory not found/); + expect(del).toHaveBeenCalledTimes(1); + + get.mockRejectedValueOnce(new Error("Memory not found")); + await expect(store.delete("missing", "scope_abc")).rejects.toThrow( + /Memory not found/, + ); + }); +}); From d873892dad288744cde5d6d845539616dc0f7993 Mon Sep 17 00:00:00 2001 From: Kartik Date: Thu, 10 Sep 2026 20:51:50 +0530 Subject: [PATCH 05/61] feat(plugins)!: make Sidekick exclusive to Claude Code (#7278) --- docs/changelog/sdk.mdx | 36 ++++++++++ docs/integrations.mdx | 2 + docs/integrations/antigravity.mdx | 5 +- docs/integrations/claude-code.mdx | 2 + docs/integrations/codex.mdx | 2 + docs/integrations/cursor.mdx | 10 +-- docs/integrations/deepseek-plugin.mdx | 2 + docs/integrations/kimi.mdx | 8 ++- docs/integrations/openclaw.mdx | 2 + docs/integrations/opencode.mdx | 2 + docs/integrations/pi-agent.mdx | 2 + docs/llms.txt | 8 +-- integrations/agent-plugin-core/README.md | 12 ++-- .../agent-plugin-core/python/memory_cli.py | 16 ++--- .../agent-plugin-core/python/memory_core.py | 58 ++++++++--------- .../agent-plugin-core/tests/test_build.py | 23 ++++++- .../{test_sidekick.py => test_subagents.py} | 65 ++++++++++++------- .../agents/sidekick/agent.md | 17 ----- .../antigravity-plugin/core/memory_cli.py | 16 ++--- .../antigravity-plugin/core/memory_core.py | 58 ++++++++--------- .../antigravity-plugin/plugin-build.json | 3 +- .../tests/test_antigravity.py | 2 +- integrations/claude-code-plugin/README.md | 2 + .../adapters/claude/hook.py | 10 +-- .../claude-code-plugin/core/memory_cli.py | 16 ++--- .../claude-code-plugin/core/memory_core.py | 58 ++++++++--------- .../tests/test_memory_core.py | 34 +++++----- integrations/codex-plugin/core/memory_cli.py | 16 ++--- integrations/codex-plugin/core/memory_core.py | 58 ++++++++--------- integrations/codex-plugin/hooks/adapter.py | 14 ++-- integrations/codex-plugin/hooks/hooks.json | 4 +- integrations/codex-plugin/tests/test_codex.py | 8 +-- .../cursor-plugin/.cursor-plugin/plugin.json | 1 - integrations/cursor-plugin/agents/sidekick.md | 16 ----- integrations/cursor-plugin/core/memory_cli.py | 16 ++--- .../cursor-plugin/core/memory_core.py | 58 ++++++++--------- integrations/cursor-plugin/hooks/adapter.py | 21 ------ integrations/cursor-plugin/hooks/hooks.json | 2 - integrations/cursor-plugin/plugin-build.json | 1 - .../cursor-plugin/tests/test_adapter.py | 37 +---------- integrations/deepseek-plugin/README.md | 4 +- integrations/kimi-plugin/agents/sidekick.md | 18 ----- integrations/kimi-plugin/core/memory_cli.py | 16 ++--- integrations/kimi-plugin/core/memory_core.py | 58 ++++++++--------- integrations/kimi-plugin/hooks/adapter.py | 22 +------ integrations/kimi-plugin/kimi.plugin.json | 5 +- integrations/kimi-plugin/plugin-build.json | 3 +- integrations/kimi-plugin/tests/test_kimi.py | 59 +---------------- .../mem0-agent-plugin/core/memory_cli.py | 16 ++--- .../mem0-agent-plugin/core/memory_core.py | 58 ++++++++--------- integrations/openclaw/README.md | 46 ++++++------- integrations/opencode-plugin/README.md | 16 +++-- integrations/pi-agent-plugin/README.md | 16 +++-- 53 files changed, 483 insertions(+), 577 deletions(-) rename integrations/agent-plugin-core/tests/{test_sidekick.py => test_subagents.py} (51%) delete mode 100644 integrations/antigravity-plugin/agents/sidekick/agent.md delete mode 100644 integrations/cursor-plugin/agents/sidekick.md delete mode 100644 integrations/kimi-plugin/agents/sidekick.md diff --git a/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdx index fff64b9e0..71fb7e1d8 100644 --- a/docs/changelog/sdk.mdx +++ b/docs/changelog/sdk.mdx @@ -2371,6 +2371,12 @@ 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. + + + **Changed:** @@ -2390,6 +2396,12 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex + + +Removes Sidekick and its start/stop hooks. Memory capture, search, and six skills remain available. + + + **Changed:** @@ -2409,6 +2421,12 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex + + +Renames shared tracking to use subagent terminology. Native subagent memory support remains available. + + + **Changed:** @@ -2427,6 +2445,12 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex + + +Sidekick is available only in Claude Code, not in the portable package. + + + **Added:** @@ -2543,6 +2567,12 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex + + +Removes Sidekick. Memory capture, search, and six skills remain available. + + + **Changed:** @@ -2635,6 +2665,12 @@ 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. + + + **Changed:** diff --git a/docs/integrations.mdx b/docs/integrations.mdx index b87b5d432..138e6cffe 100644 --- a/docs/integrations.mdx +++ b/docs/integrations.mdx @@ -17,6 +17,8 @@ Mem0 seamlessly integrates with popular AI frameworks and tools to enhance your **Universal Integration**: Use Mem0 MCP for a standardized protocol that works with ANY AI client. +Sidekick is available only in the [Claude Code plugin](/integrations/claude-code#sidekick-agent). Other plugins, including the portable package, provide memory without Sidekick. + Here are the available integrations for Mem0: ## Integrations diff --git a/docs/integrations/antigravity.mdx b/docs/integrations/antigravity.mdx index ef4aca8c6..08158ffa0 100644 --- a/docs/integrations/antigravity.mdx +++ b/docs/integrations/antigravity.mdx @@ -7,6 +7,8 @@ Add persistent memory to [**Google Antigravity**](https://antigravity.google) (` Current plugin version: `0.3.1`. +Sidekick is available only in the [Claude Code plugin](/integrations/claude-code#sidekick-agent). + ## Prerequisites 1. A Mem0 API key (starts with `m0-`): @@ -48,11 +50,10 @@ This installs the generated Antigravity bundle with the Mem0 server, lifecycle h | Local MCP Server (`search_memories`) | Yes | | Lifecycle Hooks | Yes | | 6 Memory Skills | Yes | -| Sidekick Agent | Yes | ## Memory tools and skills -The full plugin exposes a focused `search_memories` tool and captures completed work through lifecycle hooks. Six skills provide search, status, remember, forget, pause, and resume workflows. A native sidekick can handle a bounded task in the workspace assigned by Antigravity; it does not claim Claude Code worktree isolation. +The full plugin exposes a focused `search_memories` tool and captures completed work through lifecycle hooks. Six skills provide search, status, remember, forget, pause, and resume workflows. If you need the full set of direct CRUD tools, connect the [hosted Mem0 MCP server](/platform/mem0-mcp) separately instead of installing both configurations under the same server name. diff --git a/docs/integrations/claude-code.mdx b/docs/integrations/claude-code.mdx index 829489386..0b8e5a328 100644 --- a/docs/integrations/claude-code.mdx +++ b/docs/integrations/claude-code.mdx @@ -64,6 +64,8 @@ After the automatic first-prompt search, Claude can also call `search_memories` ### Sidekick agent +Sidekick is available only in Claude Code. + `mem0:sidekick` is a Sonnet coding agent that runs in a separate Git worktree. Use it to offload investigation, implementation, testing, or review without burning main-session context. ```text diff --git a/docs/integrations/codex.mdx b/docs/integrations/codex.mdx index 8bd68627c..d0ad0735f 100644 --- a/docs/integrations/codex.mdx +++ b/docs/integrations/codex.mdx @@ -7,6 +7,8 @@ Add persistent memory to [**OpenAI Codex**](https://openai.com/index/codex/) wit Current plugin version: `0.3.1`. +Sidekick is available only in the [Claude Code plugin](/integrations/claude-code#sidekick-agent). + ## Prerequisites Before setting up Mem0 with Codex, ensure you have: diff --git a/docs/integrations/cursor.mdx b/docs/integrations/cursor.mdx index 3105dc14d..49eb8861b 100644 --- a/docs/integrations/cursor.mdx +++ b/docs/integrations/cursor.mdx @@ -7,6 +7,8 @@ Add persistent memory to [**Cursor**](https://cursor.com) with the Mem0 plugin. Current plugin version: `0.3.1`. +Sidekick is available only in the [Claude Code plugin](/integrations/claude-code#sidekick-agent). + ## Prerequisites Before setting up Mem0 with Cursor, ensure you have: @@ -49,7 +51,7 @@ cursor-agent plugin marketplace add https://github.com/mem0ai/mem0 Open Cursor's **Customize** page or run `/plugins`, select the **Mem0 Plugins** marketplace, and install **Mem0** at user or project scope. Enter your Mem0 API key when Cursor asks for the plugin configuration, then restart Cursor. -The full plugin includes automatic capture, the `search_memories` recall tool, lifecycle hooks, a sidekick agent, and six memory skills. +The full plugin includes automatic capture, the `search_memories` recall tool, lifecycle hooks, and six memory skills. ### Option B: One-Click Deeplink (MCP Only) @@ -98,7 +100,6 @@ Add the following to your `.cursor/mcp.json`: | Recall | `search_memories` | MCP search tools | | Lifecycle hooks | Yes | No | | Memory skills | 6 | No | -| Sidekick agent | Yes | No | ## MCP-only tools @@ -125,15 +126,14 @@ The full plugin translates Cursor's native events into the shared Mem0 memory li | `sessionStart` | Initializes the project session and recovers pending capture | | `beforeSubmitPrompt` | Observes the submitted prompt; recall stays tool-driven because this event cannot inject context | | `postToolUse` / `postToolUseFailure` | Records useful tool results and failures | -| `subagentStart` / `subagentStop` | Records the Mem0 Sidekick lifecycle and completed result | | `afterAgentResponse` / `stop` | Captures the completed exchange | | `preCompact` / `sessionEnd` | Flushes pending capture in the background | - Cursor's `beforeSubmitPrompt` hook can allow or block a prompt, but it cannot add context to that prompt. The plugin therefore gives the agent `search_memories` and a memory-aware sidekick for recall instead of claiming automatic per-prompt injection. + Cursor's `beforeSubmitPrompt` hook cannot add context to a prompt. Use `search_memories` to recall memories. -Cursor's `subagentStart` hook also cannot inject parent context. The bundled Sidekick searches Mem0 itself, while the lifecycle hooks correlate its start and completion for later capture. +The plugin does not register subagent start or stop hooks. ## Example Workflow diff --git a/docs/integrations/deepseek-plugin.mdx b/docs/integrations/deepseek-plugin.mdx index 2e7cc5177..16b8badaf 100644 --- a/docs/integrations/deepseek-plugin.mdx +++ b/docs/integrations/deepseek-plugin.mdx @@ -7,6 +7,8 @@ Add persistent memory to the [**DeepSeek Harness**](https://github.com/deepseek- Current package version: `0.3.0`. +Sidekick is available only in the [Claude Code plugin](/integrations/claude-code#sidekick-agent). + ## Overview The plugin provides automatic memory plus two agent-callable tools: diff --git a/docs/integrations/kimi.mdx b/docs/integrations/kimi.mdx index ef7058ed5..e6bd27706 100644 --- a/docs/integrations/kimi.mdx +++ b/docs/integrations/kimi.mdx @@ -7,6 +7,8 @@ Kimi Code forgets project decisions between sessions. The Mem0 plugin captures c Current plugin version: `0.3.1`. +Sidekick is available only in the [Claude Code plugin](/integrations/claude-code#sidekick-agent). + ## Prerequisites 1. A Mem0 Platform account and API key: @@ -33,7 +35,7 @@ Inside Kimi Code, install the native plugin bundle and reload the session: /reload ``` -Run `/plugins info mem0` to confirm that the plugin, MCP server, skills, hooks, and sidekick agent loaded. +Run `/plugins info mem0` to confirm that the plugin, MCP server, skills, and hooks loaded. ## What you get @@ -42,7 +44,6 @@ Run `/plugins info mem0` to confirm that the plugin, MCP server, skills, hooks, - **Explicit search:** Kimi can call `search_memories` when it needs a more specific answer. - **Six memory skills:** Search, status, remember, forget, pause, and resume use the same memory behavior as the other Mem0 coding-agent plugins. - **Project scoping:** Memories stay attached to the repository, with separate personal and shared project lanes. -- **Kimi sidekick:** A focused subagent can investigate or implement a bounded task in a separate context. Filesystem isolation depends on the environment Kimi provides. Credentials are redacted before memory capture. If Mem0 is unavailable, hooks fail open so Kimi can continue its normal work. @@ -57,7 +58,8 @@ Kimi's native lifecycle events are translated into the shared Mem0 memory lifecy | `PostToolUse` / `PostToolUseFailure` | Records useful tool results and failures | | `Stop` | Captures the completed exchange | | `PreCompact` / `SessionEnd` | Flushes pending capture in the background | -| `SubagentStart` / `SubagentStop` | Passes parent context to the Mem0 sidekick and records its lifecycle | + +The plugin does not register subagent start or stop hooks or supply parent memories to child agents. ## Verify the plugin diff --git a/docs/integrations/openclaw.mdx b/docs/integrations/openclaw.mdx index 7ee02e2b1..a9642d444 100644 --- a/docs/integrations/openclaw.mdx +++ b/docs/integrations/openclaw.mdx @@ -7,6 +7,8 @@ Add long-term memory to [OpenClaw](https://github.com/openclaw/openclaw) agents Current package version: `1.1.0`. +Sidekick is available only in the [Claude Code plugin](/integrations/claude-code#sidekick-agent). OpenClaw subagents can recall parent memories. Mem0 does not capture their sessions. + ## Overview diff --git a/docs/integrations/opencode.mdx b/docs/integrations/opencode.mdx index 57412841e..70c5a6558 100644 --- a/docs/integrations/opencode.mdx +++ b/docs/integrations/opencode.mdx @@ -7,6 +7,8 @@ Add persistent memory to [**OpenCode**](https://opencode.ai) with the Mem0 plugi Current package version: `0.3.0`. +Sidekick is available only in the [Claude Code plugin](/integrations/claude-code#sidekick-agent). + ## Prerequisites 1. A Mem0 API key (starts with `m0-`): diff --git a/docs/integrations/pi-agent.mdx b/docs/integrations/pi-agent.mdx index 570fd3b20..5a00c5d28 100644 --- a/docs/integrations/pi-agent.mdx +++ b/docs/integrations/pi-agent.mdx @@ -7,6 +7,8 @@ Add persistent memory to [**Pi Agent**](https://pi.dev) with `@mem0/pi-agent-plu Current package version: `0.3.0`. +Sidekick is available only in the [Claude Code plugin](/integrations/claude-code#sidekick-agent). + ## Overview The plugin provides: diff --git a/docs/llms.txt b/docs/llms.txt index 0510d2bf2..65e13de8f 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -269,11 +269,11 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st ### AI Coding Tools - [Claude Code](https://docs.mem0.ai/integrations/claude-code) [Platform]: Use when wiring memory into Claude Code. - [Claude.ai](https://docs.mem0.ai/integrations/claude-ai) [Platform]: Use when connecting Mem0 to Claude.ai (the hosted web app) via a custom remote MCP connector, or when Claude's native memory seems to be crowding out mem0 tool calls. -- [Cursor](https://docs.mem0.ai/integrations/cursor) [Platform]: Use when adding lifecycle capture, explicit memory recall, six skills, and a sidekick to Cursor. +- [Cursor](https://docs.mem0.ai/integrations/cursor) [Platform]: Use when adding lifecycle capture, explicit memory recall, and six memory skills to Cursor. - [Codex](https://docs.mem0.ai/integrations/codex) [Platform]: Use when adding automatic capture and recall, six memory skills, and a search tool to OpenAI Codex. - [Kimi Code](https://docs.mem0.ai/integrations/kimi) [Platform]: Use when adding persistent project memory to Kimi Code through its native plugin lifecycle. - [OpenCode](https://docs.mem0.ai/integrations/opencode) [Platform]: Use when adding ten native SDK memory tools, automatic context, seven skills, and project scoping to OpenCode. -- [Antigravity](https://docs.mem0.ai/integrations/antigravity) [Platform]: Use when adding lifecycle capture, explicit recall, six memory skills, and a native sidekick to Google Antigravity. +- [Antigravity](https://docs.mem0.ai/integrations/antigravity) [Platform]: Use when adding lifecycle capture, explicit recall, and six memory skills to Google Antigravity. ### Voice & Real-time - [LiveKit](https://docs.mem0.ai/integrations/livekit) [Platform]: Use when building real-time voice/video with memory. @@ -418,13 +418,13 @@ Each subdirectory is a Claude Code Skill (`SKILL.md` + supporting assets). Load Source: https://github.com/mem0ai/mem0/tree/main/integrations/claude-code-plugin -The self-contained Claude Code plugin lives in `integrations/claude-code-plugin/` (v0.3.1, installs as `mem0@mem0-plugins`). It captures evidence locally through lifecycle hooks, extracts memories in a detached background worker, and exposes a single local MCP tool, `search_memories`, plus six `/mem0:*` skills and the unchanged `mem0:sidekick` agent. Pure-stdlib Python, nothing to install. +The self-contained Claude Code plugin lives in `integrations/claude-code-plugin/` (v0.3.1, installs as `mem0@mem0-plugins`). It captures evidence locally through lifecycle hooks, extracts memories in a detached background worker, and exposes a single local MCP tool, `search_memories`, plus six `/mem0:*` skills and `mem0:sidekick`, available only in Claude Code. Pure-stdlib Python, nothing to install. ### Coding-Agent Plugin Sources Source: https://github.com/mem0ai/mem0/tree/main/integrations/agent-plugin-core -The `integrations/agent-plugin-core/` directory is the single source for shared Python and TypeScript memory behavior. Native plugins live in their own sibling directories, while `integrations/mem0-agent-plugin/` is the single portable Agent Plugins v1 package. The portable package provides search and skills but no automatic capture; its remember skill cannot save a new memory on its own. Shared Python search accepts optional `run_id` for session-specific recall in every scope. TypeScript integrations reuse the core's lifecycle, formatting, identity, scoping, and telemetry utilities while keeping their public packages and native host APIs unchanged. +The `integrations/agent-plugin-core/` directory is the single source for shared Python and TypeScript memory behavior. Native plugins live in their own sibling directories, while `integrations/mem0-agent-plugin/` is the single portable Agent Plugins v1 package. Sidekick is available only in Claude Code. The portable package provides search and skills but no automatic capture; its remember skill cannot save a new memory on its own. Shared Python search accepts optional `run_id` for session-specific recall in every scope. TypeScript integrations reuse the core's lifecycle, formatting, identity, scoping, and telemetry utilities while keeping their public packages and native host APIs unchanged. Editor-specific setup docs (already listed above under `## Integrations > AI Coding Tools`): diff --git a/integrations/agent-plugin-core/README.md b/integrations/agent-plugin-core/README.md index 8831bd71c..f11026319 100644 --- a/integrations/agent-plugin-core/README.md +++ b/integrations/agent-plugin-core/README.md @@ -23,7 +23,7 @@ integrations/ Each native directory owns only its manifest, native hooks or adapter, tests, and `plugin-build.json`. Its `core/` and `skills/` directories are generated from this module. They are committed because clients install a self-contained plugin directory and the Agent Plugins specification forbids package files from resolving outside the plugin root. -Claude Code remains the behavioral source of truth. Its sidekick stays at `claude-code-plugin/agents/sidekick.md` and is not generated or copied to hosts without a compatible native subagent interface. +Sidekick belongs only to Claude Code. Its agent definition is in `claude-code-plugin/agents/sidekick.md`; its hooks are in `claude-code-plugin/adapters/claude/hook.py`. Other plugins must not register Sidekick. The shared core handles memory and native subagent tracking for Claude Code and Codex. TypeScript integrations (`openclaw`, `opencode-plugin`, `pi-agent-plugin`, and `deepseek-plugin`) import `typescript/src/` at build time. Their package builders include the shared implementation in their normal output; they do not carry checked-in copies. @@ -106,19 +106,21 @@ For another native Python host: Keep capture, recall, memory scoping, redaction, skill text, and telemetry in this shared module. Host directories should contain only behavior required by their native SDK. -For a TypeScript host, import the shared lifecycle modules directly and keep only native SDK registration in the integration. Do not advertise capture, compaction, or sidekick behavior unless the host exposes the necessary lifecycle seam. +For a TypeScript host, import the shared lifecycle modules directly and keep only native SDK registration in the integration. Do not advertise capture or compaction behavior unless the host exposes the necessary lifecycle seam. Sidekick is limited to Claude Code. ## Host capture capabilities | Host | Conversation capture | Tool outcomes | Subagent context and correlation | | --- | --- | --- | --- | | Claude Code | Incremental active transcript branch | Native success/failure hooks | Parent context; native agent ID | -| Cursor | Prompt and response hooks; duplicate responses suppressed | Native success/failure hooks | Sidekick searches itself; no parent-injection claim | +| Cursor | Prompt and response hooks; duplicate responses suppressed | Native success/failure hooks | No plugin subagent hooks or agent declaration | | Codex | Native prompt and final-response fields | Structured failure indicators when present; otherwise unknown | Parent context; native agent ID | -| Kimi | Prompt hooks and completed v2 wire output | Native success/failure hooks | Parent context; without an ID, a stop matches only one unambiguous active run | -| Antigravity | Incremental completed transcript messages, including later prompts | Native tool errors | Sidekick searches itself; no worktree-isolation claim | +| Kimi | Prompt hooks and completed v2 wire output | Native success/failure hooks | No plugin subagent hooks or agent declaration | +| Antigravity | Incremental completed transcript messages, including later prompts | Native tool errors | No plugin subagent hooks or agent declaration | | Portable v1 | Explicit memory skills | No native lifecycle hooks | No native subagent declaration | +Python status uses `subagent_runs` and `last_subagent`. Legacy SQLite names and event handling keep existing records and running workers compatible. + An uncorrelated subagent completion is kept as its own record; the plugin never guesses which overlapping run completed. Codex's documented hook fields already match the shared input contract, so no speculative field aliases or unsupported failure event are registered. Offline conformance exercises the adapters and MCP servers with native-shaped payloads and builds each distributable package. It does not establish that every installed editor or Harness version loads the plugin correctly; those checks require smoke tests in the actual hosts. diff --git a/integrations/agent-plugin-core/python/memory_cli.py b/integrations/agent-plugin-core/python/memory_cli.py index 595729feb..76d2ee871 100644 --- a/integrations/agent-plugin-core/python/memory_cli.py +++ b/integrations/agent-plugin-core/python/memory_cli.py @@ -11,10 +11,10 @@ import telemetry from memory_core import ( EvidenceStore, api_key, + configure_harness, data_dir, doctor, forget_remote_repo, - configure_harness, resolve_repo, user_id, ) @@ -32,7 +32,7 @@ def _print_status(value: dict) -> None: ) print( f"Used in this repository: {value['retrievals']} memories returned, " - f"{value['sidekick_runs']} sidekick runs" + f"{value['subagent_runs']} subagent runs" ) if last: item_label = "" @@ -48,13 +48,13 @@ def _print_status(value: dict) -> None: f"{'succeeded' if last['success'] else 'failed'} " f"({last['duration_ms']:.1f} ms{item_label})" ) - sidekick = value.get("last_sidekick") or {} - if sidekick: - state = "finished" if sidekick.get("stopped_at") else "started" + subagent = value.get("last_subagent") or {} + if subagent: + state = "finished" if subagent.get("stopped_at") else "started" print( - "Last sidekick: " - f"{state}, received {sidekick['context_chars']} characters of memory, " - f"agent {sidekick['agent_id']}" + "Last subagent: " + f"{state}, received {subagent['context_chars']} characters of memory, " + f"agent {subagent['agent_id']}" ) diff --git a/integrations/agent-plugin-core/python/memory_core.py b/integrations/agent-plugin-core/python/memory_core.py index cf71196b8..77d7a2b80 100644 --- a/integrations/agent-plugin-core/python/memory_core.py +++ b/integrations/agent-plugin-core/python/memory_core.py @@ -524,7 +524,7 @@ def _checkpoint_message(event: dict[str, Any]) -> str: if text: return text return redact(payload.get("text", "")).strip() - if kind == "sidekick_stop": + if kind in {"subagent_stop", "sidekick_stop"}: return redact(payload.get("final_message", "")).strip() return "" @@ -596,6 +596,7 @@ class EvidenceStore: self.conn.close() def _migrate(self) -> None: + # Keep the legacy table name so existing databases and in-flight workers remain compatible. self.conn.executescript( """ CREATE TABLE IF NOT EXISTS events ( @@ -688,8 +689,7 @@ class EvidenceStore: """ ) - # Remove the pre-0.1.1 no-tools snapshot implementation. The real coding - # sidekick is a native Claude Code agent and stores no state in this DB. + # Remove the pre-0.1.1 snapshot implementation. self.conn.executescript( """ DROP TABLE IF EXISTS sidekick_calls; @@ -1041,7 +1041,7 @@ class EvidenceStore: if row["memory_text"] ] - def start_sidekick( + def start_subagent( self, repo: RepoContext, session_id: str, @@ -1049,7 +1049,7 @@ class EvidenceStore: agent_type: str, context_chars: int, ) -> bool: - """Record one native sidekick instance and whether context was first sent.""" + """Record one native subagent instance and whether context was first sent.""" with self.conn: cursor = self.conn.execute( """INSERT OR IGNORE INTO sidekick_runs @@ -1067,7 +1067,7 @@ class EvidenceStore: ) return int(cursor.rowcount) > 0 - def stop_sidekick( + def stop_subagent( self, repo: RepoContext, session_id: str, @@ -1222,7 +1222,7 @@ class EvidenceStore: cursor = self.conn.execute( f"DELETE FROM {table} WHERE {column} = ?", (repo_id,) ) - removed[table] = max(int(cursor.rowcount), 0) + removed["subagent_runs" if table == "sidekick_runs" else table] = max(int(cursor.rowcount), 0) return removed def status(self, repo_id: str) -> dict[str, Any]: @@ -1238,7 +1238,7 @@ class EvidenceStore: FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""", (repo_id,), ).fetchone() - last_sidekick = self.conn.execute( + last_subagent = self.conn.execute( """SELECT session_id, agent_id, agent_type, started_at, stopped_at, context_chars FROM sidekick_runs WHERE repo_id = ? @@ -1250,9 +1250,9 @@ class EvidenceStore: "events": count("events"), "flushes": count("flushes"), "retrievals": count("retrievals"), - "sidekick_runs": count("sidekick_runs"), + "subagent_runs": count("sidekick_runs"), "last_operation": dict(last_operation) if last_operation else None, - "last_sidekick": dict(last_sidekick) if last_sidekick else None, + "last_subagent": dict(last_subagent) if last_subagent else None, } @@ -1324,7 +1324,7 @@ def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> "tool": name, "failed": failed, "duration_ms": hook_input.get("duration_ms"), - "agent_role": "sidekick" if hook_input.get("agent_id") else "main", + "agent_role": "subagent" if hook_input.get("agent_id") else "main", } if hook_input.get("agent_id"): payload["agent_id"] = bounded(hook_input["agent_id"], 200) @@ -1384,35 +1384,33 @@ def record_tool( ) -def record_sidekick_start( - store: EvidenceStore, hook_input: dict[str, Any], *, inject_context: bool = True +def record_subagent_start( + store: EvidenceStore, hook_input: dict[str, Any] ) -> str: - """Record a native sidekick and reuse the main turn's retrieved memories.""" + """Record a native subagent and reuse the main turn's retrieved memories.""" session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200) - agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200) context = combine_context( format_context(store.injected_memories(session_id, repo.identity)) ) - if not inject_context: - context = "" - first_start = store.start_sidekick( + first_start = store.start_subagent( repo, session_id, agent_id, agent_type, len(context) ) store.record_event( repo, session_id, - "sidekick_start", + "subagent_start", { "agent_id": agent_id, "agent_type": agent_type, "context_chars": len(context) if first_start else 0, - "worktree_root": bounded(repo.root, 2000), + "repo_root": bounded(repo.root, 2000), }, ) telemetry.record( - "sidekick", + "subagent", repo=repo, session_id=session_id, phase="start", @@ -1422,14 +1420,14 @@ def record_sidekick_start( return context if first_start else "" -def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: +def record_subagent_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) - agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200) agent_id = bounded(hook_input.get("agent_id", ""), 200) final_message = redact(hook_input.get("last_assistant_message", "")).strip() transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000) - agent_id = store.stop_sidekick( + agent_id = store.stop_subagent( repo, session_id, agent_id, @@ -1440,7 +1438,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No store.record_event( repo, session_id, - "sidekick_stop", + "subagent_stop", { "agent_id": agent_id, "agent_type": agent_type, @@ -1449,7 +1447,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No }, ) telemetry.record( - "sidekick", + "subagent", repo=repo, session_id=session_id, phase="stop", @@ -1513,10 +1511,10 @@ def build_episode( for e in events if e["kind"] == "assistant_stop" and e["payload"].get("text") ] - sidekick_outcomes = [ + subagent_outcomes = [ redact(e["payload"].get("final_message", "")).strip() for e in events - if e["kind"] == "sidekick_stop" and e["payload"].get("final_message") + if e["kind"] in {"subagent_stop", "sidekick_stop"} and e["payload"].get("final_message") ] tools = [ e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"} @@ -1597,7 +1595,7 @@ def build_episode( } ) pending_user_messages = [] - elif event["kind"] == "sidekick_stop": + elif event["kind"] in {"subagent_stop", "sidekick_stop"}: pass extraction_messages.extend(pending_user_messages) @@ -1613,7 +1611,7 @@ def build_episode( "assistant_conclusion": conclusion, "user_messages": prompts, "assistant_outcomes": assistant_conclusions, - "sidekick_outcomes": sidekick_outcomes, + "subagent_outcomes": subagent_outcomes, "extraction_messages": extraction_messages, "files_read": read_paths[:50], "files_modified": modified_paths[:50], diff --git a/integrations/agent-plugin-core/tests/test_build.py b/integrations/agent-plugin-core/tests/test_build.py index dfa154f3d..54b5e5c6a 100644 --- a/integrations/agent-plugin-core/tests/test_build.py +++ b/integrations/agent-plugin-core/tests/test_build.py @@ -1,7 +1,7 @@ from __future__ import annotations -import sys import json +import sys from pathlib import Path import pytest @@ -10,7 +10,12 @@ ROOT = Path(__file__).resolve().parents[1] REPOSITORY_ROOT = ROOT.parents[1] sys.path.insert(0, str(ROOT)) -from build.build import build, bundle_drift, render_template, replace_output # noqa: E402 +from build.build import ( # noqa: E402 + build, + bundle_drift, + render_template, + replace_output, +) from build.validate import validate_bundle # noqa: E402 @@ -57,6 +62,7 @@ def test_portable_bundle_is_conformant_and_self_contained(tmp_path: Path) -> Non assert "env" not in server assert not (root / "core" / "hook_runner.py").exists() assert not (root / "core" / "flush_worker.py").exists() + assert not (root / "agents").exists() for skill in (root / "skills").glob("*/SKILL.md"): frontmatter = skill.read_text(encoding="utf-8").split("---", 2)[1] keys = {line.split(":", 1)[0] for line in frontmatter.splitlines() if ":" in line} @@ -73,6 +79,19 @@ def test_native_bundle_is_self_contained(host: str, tmp_path: Path) -> None: assert not any(path.is_symlink() for path in root.rglob("*")) +@pytest.mark.parametrize("host", ["claude-code", "cursor", "codex", "kimi", "antigravity"]) +def test_only_claude_bundles_sidekick(host: str, tmp_path: Path) -> None: + root = build(host, "native", tmp_path / host) + if host == "claude-code": + agent = (root / "agents" / "sidekick.md").read_text() + assert "model: sonnet" in agent + assert "isolation: worktree" in agent + else: + assert not (root / "agents").exists() + for path in root.rglob("*.json"): + assert "sidekick" not in path.read_text().lower() + + @pytest.mark.parametrize("host", ["claude-code", "cursor", "codex", "kimi", "antigravity"]) def test_native_control_skills_select_the_host_store(host: str, tmp_path: Path) -> None: root = build(host, "native", tmp_path / host) diff --git a/integrations/agent-plugin-core/tests/test_sidekick.py b/integrations/agent-plugin-core/tests/test_subagents.py similarity index 51% rename from integrations/agent-plugin-core/tests/test_sidekick.py rename to integrations/agent-plugin-core/tests/test_subagents.py index 9503e946e..f91b3e091 100644 --- a/integrations/agent-plugin-core/tests/test_sidekick.py +++ b/integrations/agent-plugin-core/tests/test_subagents.py @@ -2,6 +2,7 @@ import json import os +import sqlite3 import subprocess import sys from pathlib import Path @@ -11,11 +12,43 @@ import pytest ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "python")) -from memory_core import EvidenceStore # noqa: E402 +from memory_core import EvidenceStore, RepoContext, checkpoint_stats # noqa: E402 -@pytest.mark.parametrize("host", ["claude-code", "codex", "kimi", "cursor"]) -def test_sidekick_hooks_preserve_parent_scope_and_correlate_completion(tmp_path, host): +def test_generic_tracking_preserves_legacy_runs_and_can_finish_them(tmp_path): + database = tmp_path / "evidence.sqlite3" + with sqlite3.connect(database) as connection: + connection.executescript(""" + CREATE TABLE sidekick_runs ( + repo_id TEXT NOT NULL, session_id TEXT NOT NULL, + agent_id TEXT NOT NULL, agent_type TEXT NOT NULL, + started_at TEXT NOT NULL, stopped_at TEXT, transcript_path TEXT, + context_chars INTEGER NOT NULL DEFAULT 0, final_message TEXT, + PRIMARY KEY(repo_id, session_id, agent_id) + ); + INSERT INTO sidekick_runs VALUES + ('repo', 'session', 'worker', 'default', '2026-09-10', NULL, NULL, 123, NULL); + """) + for _ in range(2): + store = EvidenceStore(database) + try: + assert store.status("repo")["subagent_runs"] == 1 + row = store.conn.execute("SELECT * FROM sidekick_runs").fetchone() + assert row["agent_id"] == "worker" + assert row["context_chars"] == 123 + repo = RepoContext(str(tmp_path), str(tmp_path), "repo", "app", "main", "") + store.stop_subagent(repo, "session", "worker", "default", "", "Completed after upgrade.") + assert store.status("repo")["last_subagent"]["stopped_at"] + assert store.conn.execute("SELECT final_message FROM sidekick_runs").fetchone()[0] == ( + "Completed after upgrade." + ) + finally: + store.close() + assert checkpoint_stats([{"kind": "sidekick_stop", "payload": {"final_message": "Legacy result."}}]) == (0, 1, 14) + + +@pytest.mark.parametrize("host", ["claude-code", "codex"]) +def test_subagent_hooks_preserve_parent_scope_and_correlate_completion(tmp_path, host): parent = tmp_path / "parent" child = tmp_path / "child-worktree" parent.mkdir() @@ -30,21 +63,10 @@ def test_sidekick_hooks_preserve_parent_scope_and_correlate_completion(tmp_path, plugin = ROOT.parent / f"{host}-plugin" adapter = plugin / ("adapters/claude/hook.py" if host == "claude-code" else "hooks/adapter.py") start, stop = "sidekick-start", "sidekick-stop" - payload = {"session_id": "parent-session", "cwd": str(child), "agent_id": "worker", "agent_type": "sidekick"} + payload = {"session_id": "parent-session", "cwd": str(child), "agent_id": "worker", "agent_type": "default"} response_key = "last_assistant_message" - if host == "kimi": - start, stop = "SubagentStart", "SubagentStop" - payload["agent_name"] = payload.pop("agent_type") - response_key = "response" - elif host == "cursor": - start, stop = "subagentStart", "subagentStop" - payload = { - "conversation_id": "parent-session", - "workspace_roots": [str(child)], - "subagent_id": "worker", - "subagent_type": "sidekick", - } - response_key = "summary" + if host == "codex": + start, stop = "subagent-start", "subagent-stop" env = {key: value for key, value in os.environ.items() if not key.startswith(("MEM0_", "CLAUDE_PLUGIN_"))} env.update(MEM0_CODE_DATA_DIR=str(database.parent), MEM0_TELEMETRY="false", MEM0_API_URL="http://127.0.0.1:1") @@ -62,11 +84,8 @@ def test_sidekick_hooks_preserve_parent_scope_and_correlate_completion(tmp_path, return result.stdout output = invoke(start, payload) - if host == "cursor": - assert json.loads(output) == {"permission": "allow"} - else: - context = output if host == "kimi" else json.loads(output)["hookSpecificOutput"]["additionalContext"] - assert "Parent memory marker." in context + context = json.loads(output)["hookSpecificOutput"]["additionalContext"] + assert "Parent memory marker." in context assert "Foreign memory marker." not in output assert "Parent memory marker." not in invoke(start, payload) invoke(stop, {**payload, response_key: "Finished the delegated task."}) @@ -80,4 +99,4 @@ def test_sidekick_hooks_preserve_parent_scope_and_correlate_completion(tmp_path, ) assert runs[0]["stopped_at"] assert runs[0]["final_message"] == "Finished the delegated task." - assert (runs[0]["context_chars"] > 0) == (host != "cursor") + assert runs[0]["context_chars"] > 0 diff --git a/integrations/antigravity-plugin/agents/sidekick/agent.md b/integrations/antigravity-plugin/agents/sidekick/agent.md deleted file mode 100644 index 6a4d8f29a..000000000 --- a/integrations/antigravity-plugin/agents/sidekick/agent.md +++ /dev/null @@ -1,17 +0,0 @@ ---- -name: sidekick -description: Coding subagent for focused implementation, investigation, testing, debugging, or review work. -subagent: true ---- - -You are Mem0's coding sidekick. Complete only the bounded task the main agent -delegates to you and return a concise, self-contained result. - -Search Mem0 before work that may depend on prior repository decisions or user -preferences. Inspect the relevant repository rules and code, make changes when -asked, and run the smallest decisive validation. Use only the workspace the -caller assigned; do not assume a separate Git worktree. - -Your final response must state the outcome, changed files, validation, and any -remaining risk. Do not commit, push, or open a pull request unless the caller -explicitly asks. diff --git a/integrations/antigravity-plugin/core/memory_cli.py b/integrations/antigravity-plugin/core/memory_cli.py index 595729feb..76d2ee871 100644 --- a/integrations/antigravity-plugin/core/memory_cli.py +++ b/integrations/antigravity-plugin/core/memory_cli.py @@ -11,10 +11,10 @@ import telemetry from memory_core import ( EvidenceStore, api_key, + configure_harness, data_dir, doctor, forget_remote_repo, - configure_harness, resolve_repo, user_id, ) @@ -32,7 +32,7 @@ def _print_status(value: dict) -> None: ) print( f"Used in this repository: {value['retrievals']} memories returned, " - f"{value['sidekick_runs']} sidekick runs" + f"{value['subagent_runs']} subagent runs" ) if last: item_label = "" @@ -48,13 +48,13 @@ def _print_status(value: dict) -> None: f"{'succeeded' if last['success'] else 'failed'} " f"({last['duration_ms']:.1f} ms{item_label})" ) - sidekick = value.get("last_sidekick") or {} - if sidekick: - state = "finished" if sidekick.get("stopped_at") else "started" + subagent = value.get("last_subagent") or {} + if subagent: + state = "finished" if subagent.get("stopped_at") else "started" print( - "Last sidekick: " - f"{state}, received {sidekick['context_chars']} characters of memory, " - f"agent {sidekick['agent_id']}" + "Last subagent: " + f"{state}, received {subagent['context_chars']} characters of memory, " + f"agent {subagent['agent_id']}" ) diff --git a/integrations/antigravity-plugin/core/memory_core.py b/integrations/antigravity-plugin/core/memory_core.py index cf71196b8..77d7a2b80 100644 --- a/integrations/antigravity-plugin/core/memory_core.py +++ b/integrations/antigravity-plugin/core/memory_core.py @@ -524,7 +524,7 @@ def _checkpoint_message(event: dict[str, Any]) -> str: if text: return text return redact(payload.get("text", "")).strip() - if kind == "sidekick_stop": + if kind in {"subagent_stop", "sidekick_stop"}: return redact(payload.get("final_message", "")).strip() return "" @@ -596,6 +596,7 @@ class EvidenceStore: self.conn.close() def _migrate(self) -> None: + # Keep the legacy table name so existing databases and in-flight workers remain compatible. self.conn.executescript( """ CREATE TABLE IF NOT EXISTS events ( @@ -688,8 +689,7 @@ class EvidenceStore: """ ) - # Remove the pre-0.1.1 no-tools snapshot implementation. The real coding - # sidekick is a native Claude Code agent and stores no state in this DB. + # Remove the pre-0.1.1 snapshot implementation. self.conn.executescript( """ DROP TABLE IF EXISTS sidekick_calls; @@ -1041,7 +1041,7 @@ class EvidenceStore: if row["memory_text"] ] - def start_sidekick( + def start_subagent( self, repo: RepoContext, session_id: str, @@ -1049,7 +1049,7 @@ class EvidenceStore: agent_type: str, context_chars: int, ) -> bool: - """Record one native sidekick instance and whether context was first sent.""" + """Record one native subagent instance and whether context was first sent.""" with self.conn: cursor = self.conn.execute( """INSERT OR IGNORE INTO sidekick_runs @@ -1067,7 +1067,7 @@ class EvidenceStore: ) return int(cursor.rowcount) > 0 - def stop_sidekick( + def stop_subagent( self, repo: RepoContext, session_id: str, @@ -1222,7 +1222,7 @@ class EvidenceStore: cursor = self.conn.execute( f"DELETE FROM {table} WHERE {column} = ?", (repo_id,) ) - removed[table] = max(int(cursor.rowcount), 0) + removed["subagent_runs" if table == "sidekick_runs" else table] = max(int(cursor.rowcount), 0) return removed def status(self, repo_id: str) -> dict[str, Any]: @@ -1238,7 +1238,7 @@ class EvidenceStore: FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""", (repo_id,), ).fetchone() - last_sidekick = self.conn.execute( + last_subagent = self.conn.execute( """SELECT session_id, agent_id, agent_type, started_at, stopped_at, context_chars FROM sidekick_runs WHERE repo_id = ? @@ -1250,9 +1250,9 @@ class EvidenceStore: "events": count("events"), "flushes": count("flushes"), "retrievals": count("retrievals"), - "sidekick_runs": count("sidekick_runs"), + "subagent_runs": count("sidekick_runs"), "last_operation": dict(last_operation) if last_operation else None, - "last_sidekick": dict(last_sidekick) if last_sidekick else None, + "last_subagent": dict(last_subagent) if last_subagent else None, } @@ -1324,7 +1324,7 @@ def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> "tool": name, "failed": failed, "duration_ms": hook_input.get("duration_ms"), - "agent_role": "sidekick" if hook_input.get("agent_id") else "main", + "agent_role": "subagent" if hook_input.get("agent_id") else "main", } if hook_input.get("agent_id"): payload["agent_id"] = bounded(hook_input["agent_id"], 200) @@ -1384,35 +1384,33 @@ def record_tool( ) -def record_sidekick_start( - store: EvidenceStore, hook_input: dict[str, Any], *, inject_context: bool = True +def record_subagent_start( + store: EvidenceStore, hook_input: dict[str, Any] ) -> str: - """Record a native sidekick and reuse the main turn's retrieved memories.""" + """Record a native subagent and reuse the main turn's retrieved memories.""" session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200) - agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200) context = combine_context( format_context(store.injected_memories(session_id, repo.identity)) ) - if not inject_context: - context = "" - first_start = store.start_sidekick( + first_start = store.start_subagent( repo, session_id, agent_id, agent_type, len(context) ) store.record_event( repo, session_id, - "sidekick_start", + "subagent_start", { "agent_id": agent_id, "agent_type": agent_type, "context_chars": len(context) if first_start else 0, - "worktree_root": bounded(repo.root, 2000), + "repo_root": bounded(repo.root, 2000), }, ) telemetry.record( - "sidekick", + "subagent", repo=repo, session_id=session_id, phase="start", @@ -1422,14 +1420,14 @@ def record_sidekick_start( return context if first_start else "" -def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: +def record_subagent_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) - agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200) agent_id = bounded(hook_input.get("agent_id", ""), 200) final_message = redact(hook_input.get("last_assistant_message", "")).strip() transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000) - agent_id = store.stop_sidekick( + agent_id = store.stop_subagent( repo, session_id, agent_id, @@ -1440,7 +1438,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No store.record_event( repo, session_id, - "sidekick_stop", + "subagent_stop", { "agent_id": agent_id, "agent_type": agent_type, @@ -1449,7 +1447,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No }, ) telemetry.record( - "sidekick", + "subagent", repo=repo, session_id=session_id, phase="stop", @@ -1513,10 +1511,10 @@ def build_episode( for e in events if e["kind"] == "assistant_stop" and e["payload"].get("text") ] - sidekick_outcomes = [ + subagent_outcomes = [ redact(e["payload"].get("final_message", "")).strip() for e in events - if e["kind"] == "sidekick_stop" and e["payload"].get("final_message") + if e["kind"] in {"subagent_stop", "sidekick_stop"} and e["payload"].get("final_message") ] tools = [ e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"} @@ -1597,7 +1595,7 @@ def build_episode( } ) pending_user_messages = [] - elif event["kind"] == "sidekick_stop": + elif event["kind"] in {"subagent_stop", "sidekick_stop"}: pass extraction_messages.extend(pending_user_messages) @@ -1613,7 +1611,7 @@ def build_episode( "assistant_conclusion": conclusion, "user_messages": prompts, "assistant_outcomes": assistant_conclusions, - "sidekick_outcomes": sidekick_outcomes, + "subagent_outcomes": subagent_outcomes, "extraction_messages": extraction_messages, "files_read": read_paths[:50], "files_modified": modified_paths[:50], diff --git a/integrations/antigravity-plugin/plugin-build.json b/integrations/antigravity-plugin/plugin-build.json index 506bfeb51..ac65c4bea 100644 --- a/integrations/antigravity-plugin/plugin-build.json +++ b/integrations/antigravity-plugin/plugin-build.json @@ -8,8 +8,7 @@ "plugin.json": "plugin.json", "hooks.json": "hooks.json", "mcp_config.json": "mcp_config.json", - "hooks/adapter.py": "hooks/adapter.py", - "agents/sidekick/agent.md": "agents/sidekick/agent.md" + "hooks/adapter.py": "hooks/adapter.py" } } } diff --git a/integrations/antigravity-plugin/tests/test_antigravity.py b/integrations/antigravity-plugin/tests/test_antigravity.py index 531a7b181..6c73fbeb2 100644 --- a/integrations/antigravity-plugin/tests/test_antigravity.py +++ b/integrations/antigravity-plugin/tests/test_antigravity.py @@ -115,7 +115,7 @@ def test_native_antigravity_bundle_uses_supported_events(tmp_path: Path) -> None assert manifest["$schema"] == "https://antigravity.google/schemas/v1/plugin.json" assert set(hooks) == {"PreInvocation", "PostToolUse", "Stop"} assert (root / "mcp_config.json").is_file() - assert (root / "agents" / "sidekick" / "agent.md").is_file() + assert not (root / "agents").exists() assert not any(path.is_symlink() for path in root.rglob("*")) diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index b7d659250..130460b17 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -63,6 +63,8 @@ After that first search, Claude can call `search_memories` with a specific quest ### Sonnet sidekick agent +Sidekick is available only in this plugin. The shared core handles memory and subagent tracking. + `mem0:sidekick` is a Sonnet coding agent that runs in a separate Git worktree. It can investigate, implement, test, debug, or review something instead of the main (Opus/Fable) session doing the same work, reducing cost when the main agent doesn't need to repeat it. The main agent reviews the result. Corrections go back to the same sidekick so it keeps what it learned. Changes stay in the sidekick's worktree until the main agent reviews and copies them over. diff --git a/integrations/claude-code-plugin/adapters/claude/hook.py b/integrations/claude-code-plugin/adapters/claude/hook.py index 278cd190d..f38d959b2 100644 --- a/integrations/claude-code-plugin/adapters/claude/hook.py +++ b/integrations/claude-code-plugin/adapters/claude/hook.py @@ -12,22 +12,22 @@ _core_dir = _bundled_core if (_bundled_core / "memory_core.py").is_file() else _ sys.path.insert(0, str(_core_dir)) sys.path.insert(0, str(_here.parent)) +import hook_runner # noqa: E402 import telemetry # noqa: E402 from memory_core import ( # noqa: E402 configure_harness, - record_sidekick_start, - record_sidekick_stop, + record_subagent_start, + record_subagent_stop, record_tool, ) from transcript import record_stop # noqa: E402 -import hook_runner # noqa: E402 configure_harness("claude-code", data_dir_name="claude-code-plugin", source_tag="claude_code_plugin") telemetry.init(harness="claude-code", source_tag="CLAUDE_CODE_PLUGIN") def _sidekick_start(store, hook_input): - context = record_sidekick_start(store, hook_input) + context = record_subagent_start(store, {"agent_type": "mem0:sidekick", **hook_input}) if context: return { "hookSpecificOutput": { @@ -38,7 +38,7 @@ def _sidekick_start(store, hook_input): def _sidekick_stop(store, hook_input): - record_sidekick_stop(store, hook_input) + record_subagent_stop(store, {"agent_type": "mem0:sidekick", **hook_input}) if __name__ == "__main__": diff --git a/integrations/claude-code-plugin/core/memory_cli.py b/integrations/claude-code-plugin/core/memory_cli.py index 595729feb..76d2ee871 100644 --- a/integrations/claude-code-plugin/core/memory_cli.py +++ b/integrations/claude-code-plugin/core/memory_cli.py @@ -11,10 +11,10 @@ import telemetry from memory_core import ( EvidenceStore, api_key, + configure_harness, data_dir, doctor, forget_remote_repo, - configure_harness, resolve_repo, user_id, ) @@ -32,7 +32,7 @@ def _print_status(value: dict) -> None: ) print( f"Used in this repository: {value['retrievals']} memories returned, " - f"{value['sidekick_runs']} sidekick runs" + f"{value['subagent_runs']} subagent runs" ) if last: item_label = "" @@ -48,13 +48,13 @@ def _print_status(value: dict) -> None: f"{'succeeded' if last['success'] else 'failed'} " f"({last['duration_ms']:.1f} ms{item_label})" ) - sidekick = value.get("last_sidekick") or {} - if sidekick: - state = "finished" if sidekick.get("stopped_at") else "started" + subagent = value.get("last_subagent") or {} + if subagent: + state = "finished" if subagent.get("stopped_at") else "started" print( - "Last sidekick: " - f"{state}, received {sidekick['context_chars']} characters of memory, " - f"agent {sidekick['agent_id']}" + "Last subagent: " + f"{state}, received {subagent['context_chars']} characters of memory, " + f"agent {subagent['agent_id']}" ) diff --git a/integrations/claude-code-plugin/core/memory_core.py b/integrations/claude-code-plugin/core/memory_core.py index cf71196b8..77d7a2b80 100644 --- a/integrations/claude-code-plugin/core/memory_core.py +++ b/integrations/claude-code-plugin/core/memory_core.py @@ -524,7 +524,7 @@ def _checkpoint_message(event: dict[str, Any]) -> str: if text: return text return redact(payload.get("text", "")).strip() - if kind == "sidekick_stop": + if kind in {"subagent_stop", "sidekick_stop"}: return redact(payload.get("final_message", "")).strip() return "" @@ -596,6 +596,7 @@ class EvidenceStore: self.conn.close() def _migrate(self) -> None: + # Keep the legacy table name so existing databases and in-flight workers remain compatible. self.conn.executescript( """ CREATE TABLE IF NOT EXISTS events ( @@ -688,8 +689,7 @@ class EvidenceStore: """ ) - # Remove the pre-0.1.1 no-tools snapshot implementation. The real coding - # sidekick is a native Claude Code agent and stores no state in this DB. + # Remove the pre-0.1.1 snapshot implementation. self.conn.executescript( """ DROP TABLE IF EXISTS sidekick_calls; @@ -1041,7 +1041,7 @@ class EvidenceStore: if row["memory_text"] ] - def start_sidekick( + def start_subagent( self, repo: RepoContext, session_id: str, @@ -1049,7 +1049,7 @@ class EvidenceStore: agent_type: str, context_chars: int, ) -> bool: - """Record one native sidekick instance and whether context was first sent.""" + """Record one native subagent instance and whether context was first sent.""" with self.conn: cursor = self.conn.execute( """INSERT OR IGNORE INTO sidekick_runs @@ -1067,7 +1067,7 @@ class EvidenceStore: ) return int(cursor.rowcount) > 0 - def stop_sidekick( + def stop_subagent( self, repo: RepoContext, session_id: str, @@ -1222,7 +1222,7 @@ class EvidenceStore: cursor = self.conn.execute( f"DELETE FROM {table} WHERE {column} = ?", (repo_id,) ) - removed[table] = max(int(cursor.rowcount), 0) + removed["subagent_runs" if table == "sidekick_runs" else table] = max(int(cursor.rowcount), 0) return removed def status(self, repo_id: str) -> dict[str, Any]: @@ -1238,7 +1238,7 @@ class EvidenceStore: FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""", (repo_id,), ).fetchone() - last_sidekick = self.conn.execute( + last_subagent = self.conn.execute( """SELECT session_id, agent_id, agent_type, started_at, stopped_at, context_chars FROM sidekick_runs WHERE repo_id = ? @@ -1250,9 +1250,9 @@ class EvidenceStore: "events": count("events"), "flushes": count("flushes"), "retrievals": count("retrievals"), - "sidekick_runs": count("sidekick_runs"), + "subagent_runs": count("sidekick_runs"), "last_operation": dict(last_operation) if last_operation else None, - "last_sidekick": dict(last_sidekick) if last_sidekick else None, + "last_subagent": dict(last_subagent) if last_subagent else None, } @@ -1324,7 +1324,7 @@ def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> "tool": name, "failed": failed, "duration_ms": hook_input.get("duration_ms"), - "agent_role": "sidekick" if hook_input.get("agent_id") else "main", + "agent_role": "subagent" if hook_input.get("agent_id") else "main", } if hook_input.get("agent_id"): payload["agent_id"] = bounded(hook_input["agent_id"], 200) @@ -1384,35 +1384,33 @@ def record_tool( ) -def record_sidekick_start( - store: EvidenceStore, hook_input: dict[str, Any], *, inject_context: bool = True +def record_subagent_start( + store: EvidenceStore, hook_input: dict[str, Any] ) -> str: - """Record a native sidekick and reuse the main turn's retrieved memories.""" + """Record a native subagent and reuse the main turn's retrieved memories.""" session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200) - agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200) context = combine_context( format_context(store.injected_memories(session_id, repo.identity)) ) - if not inject_context: - context = "" - first_start = store.start_sidekick( + first_start = store.start_subagent( repo, session_id, agent_id, agent_type, len(context) ) store.record_event( repo, session_id, - "sidekick_start", + "subagent_start", { "agent_id": agent_id, "agent_type": agent_type, "context_chars": len(context) if first_start else 0, - "worktree_root": bounded(repo.root, 2000), + "repo_root": bounded(repo.root, 2000), }, ) telemetry.record( - "sidekick", + "subagent", repo=repo, session_id=session_id, phase="start", @@ -1422,14 +1420,14 @@ def record_sidekick_start( return context if first_start else "" -def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: +def record_subagent_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) - agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200) agent_id = bounded(hook_input.get("agent_id", ""), 200) final_message = redact(hook_input.get("last_assistant_message", "")).strip() transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000) - agent_id = store.stop_sidekick( + agent_id = store.stop_subagent( repo, session_id, agent_id, @@ -1440,7 +1438,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No store.record_event( repo, session_id, - "sidekick_stop", + "subagent_stop", { "agent_id": agent_id, "agent_type": agent_type, @@ -1449,7 +1447,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No }, ) telemetry.record( - "sidekick", + "subagent", repo=repo, session_id=session_id, phase="stop", @@ -1513,10 +1511,10 @@ def build_episode( for e in events if e["kind"] == "assistant_stop" and e["payload"].get("text") ] - sidekick_outcomes = [ + subagent_outcomes = [ redact(e["payload"].get("final_message", "")).strip() for e in events - if e["kind"] == "sidekick_stop" and e["payload"].get("final_message") + if e["kind"] in {"subagent_stop", "sidekick_stop"} and e["payload"].get("final_message") ] tools = [ e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"} @@ -1597,7 +1595,7 @@ def build_episode( } ) pending_user_messages = [] - elif event["kind"] == "sidekick_stop": + elif event["kind"] in {"subagent_stop", "sidekick_stop"}: pass extraction_messages.extend(pending_user_messages) @@ -1613,7 +1611,7 @@ def build_episode( "assistant_conclusion": conclusion, "user_messages": prompts, "assistant_outcomes": assistant_conclusions, - "sidekick_outcomes": sidekick_outcomes, + "subagent_outcomes": subagent_outcomes, "extraction_messages": extraction_messages, "files_read": read_paths[:50], "files_modified": modified_paths[:50], diff --git a/integrations/claude-code-plugin/tests/test_memory_core.py b/integrations/claude-code-plugin/tests/test_memory_core.py index 6c91b7299..8c7017913 100644 --- a/integrations/claude-code-plugin/tests/test_memory_core.py +++ b/integrations/claude-code-plugin/tests/test_memory_core.py @@ -803,7 +803,7 @@ def test_tool_capture_identifies_main_and_sidekick_roles(): ) assert main["agent_role"] == "main" - assert sidekick["agent_role"] == "sidekick" + assert sidekick["agent_role"] == "subagent" assert sidekick["agent_id"] == "agent-123" assert sidekick["agent_type"] == "mem0:sidekick" @@ -1665,7 +1665,7 @@ def test_checkpoint_queues_only_prod_extraction_with_canonical_evidence( store.record_event( repo(), "s1", - "sidekick_stop", + "subagent_stop", { "agent_id": "agent-1", "agent_type": "mem0:sidekick", @@ -2337,9 +2337,9 @@ def test_sidekick_reuses_parent_memory_once_and_records_lifecycle( } with patch.object(memory_core, "resolve_repo", return_value=repo()): - first = memory_core.record_sidekick_start(store, start_input) - repeated = memory_core.record_sidekick_start(store, start_input) - memory_core.record_sidekick_stop( + first = memory_core.record_subagent_start(store, start_input) + repeated = memory_core.record_subagent_start(store, start_input) + memory_core.record_subagent_stop( store, { **start_input, @@ -2359,11 +2359,11 @@ def test_sidekick_reuses_parent_memory_once_and_records_lifecycle( row[0] for row in store.conn.execute("SELECT kind FROM events ORDER BY id").fetchall() ] - assert events == ["sidekick_start", "sidekick_start", "sidekick_stop"] + assert events == ["subagent_start", "subagent_start", "subagent_stop"] store.close() -def test_sidekick_stop_without_agent_id_closes_latest_matching_run(isolated_env): +def test_subagent_stop_without_agent_id_closes_latest_matching_run(isolated_env): store = memory_core.EvidenceStore() start_input = { "session_id": "s1", @@ -2373,8 +2373,8 @@ def test_sidekick_stop_without_agent_id_closes_latest_matching_run(isolated_env) } with patch.object(memory_core, "resolve_repo", return_value=repo()): - memory_core.record_sidekick_start(store, start_input) - memory_core.record_sidekick_stop( + memory_core.record_subagent_start(store, start_input) + memory_core.record_subagent_stop( store, { "session_id": "s1", @@ -2836,14 +2836,14 @@ def test_status_output_explains_memory_activity_in_plain_language(capsys): "events": 8, "flushes": 2, "retrievals": 3, - "sidekick_runs": 1, + "subagent_runs": 1, "last_operation": { "operation": "flush", "success": 1, "duration_ms": 123.4, "item_count": 2, }, - "last_sidekick": { + "last_subagent": { "stopped_at": "now", "context_chars": 240, "agent_id": "agent-1", @@ -2853,9 +2853,9 @@ def test_status_output_explains_memory_activity_in_plain_language(capsys): output = capsys.readouterr().out assert "Saved on this computer: 8 session details, 2 memory updates" in output - assert "3 memories returned, 1 sidekick runs" in output + assert "3 memories returned, 1 subagent runs" in output assert "Last memory update: succeeded" in output - assert "Last sidekick: finished, received 240 characters of memory" in output + assert "Last subagent: finished, received 240 characters of memory" in output assert "checkpoint" not in output.lower() assert "injected" not in output.lower() @@ -3391,7 +3391,7 @@ def test_plugin_entrypoints_share_explicit_claude_data_dir(tmp_path, monkeypatch status_payload = json.loads(status.stdout) assert status_payload["data_dir"] == str(canonical_data) assert status_payload["retrievals"] == 1 - assert status_payload["sidekick_runs"] == 1 + assert status_payload["subagent_runs"] == 1 assert not (conflicting_data / "evidence.sqlite3").exists() @@ -4593,9 +4593,9 @@ def test_extraction_batches_bound_individual_messages_without_losing_text(): def test_overlapping_subagent_stop_without_id_does_not_guess(isolated_env): store = memory_core.EvidenceStore() - store.start_sidekick(repo(), "s1", "first", "sidekick", 0) - store.start_sidekick(repo(), "s1", "second", "sidekick", 0) - stopped = store.stop_sidekick(repo(), "s1", "", "sidekick", "", "Uncorrelated response") + store.start_subagent(repo(), "s1", "first", "sidekick", 0) + store.start_subagent(repo(), "s1", "second", "sidekick", 0) + stopped = store.stop_subagent(repo(), "s1", "", "sidekick", "", "Uncorrelated response") assert stopped not in {"first", "second"} rows = store.conn.execute("SELECT agent_id, stopped_at, final_message FROM sidekick_runs").fetchall() assert all(row["stopped_at"] is None for row in rows if row["agent_id"] in {"first", "second"}) diff --git a/integrations/codex-plugin/core/memory_cli.py b/integrations/codex-plugin/core/memory_cli.py index 595729feb..76d2ee871 100644 --- a/integrations/codex-plugin/core/memory_cli.py +++ b/integrations/codex-plugin/core/memory_cli.py @@ -11,10 +11,10 @@ import telemetry from memory_core import ( EvidenceStore, api_key, + configure_harness, data_dir, doctor, forget_remote_repo, - configure_harness, resolve_repo, user_id, ) @@ -32,7 +32,7 @@ def _print_status(value: dict) -> None: ) print( f"Used in this repository: {value['retrievals']} memories returned, " - f"{value['sidekick_runs']} sidekick runs" + f"{value['subagent_runs']} subagent runs" ) if last: item_label = "" @@ -48,13 +48,13 @@ def _print_status(value: dict) -> None: f"{'succeeded' if last['success'] else 'failed'} " f"({last['duration_ms']:.1f} ms{item_label})" ) - sidekick = value.get("last_sidekick") or {} - if sidekick: - state = "finished" if sidekick.get("stopped_at") else "started" + subagent = value.get("last_subagent") or {} + if subagent: + state = "finished" if subagent.get("stopped_at") else "started" print( - "Last sidekick: " - f"{state}, received {sidekick['context_chars']} characters of memory, " - f"agent {sidekick['agent_id']}" + "Last subagent: " + f"{state}, received {subagent['context_chars']} characters of memory, " + f"agent {subagent['agent_id']}" ) diff --git a/integrations/codex-plugin/core/memory_core.py b/integrations/codex-plugin/core/memory_core.py index cf71196b8..77d7a2b80 100644 --- a/integrations/codex-plugin/core/memory_core.py +++ b/integrations/codex-plugin/core/memory_core.py @@ -524,7 +524,7 @@ def _checkpoint_message(event: dict[str, Any]) -> str: if text: return text return redact(payload.get("text", "")).strip() - if kind == "sidekick_stop": + if kind in {"subagent_stop", "sidekick_stop"}: return redact(payload.get("final_message", "")).strip() return "" @@ -596,6 +596,7 @@ class EvidenceStore: self.conn.close() def _migrate(self) -> None: + # Keep the legacy table name so existing databases and in-flight workers remain compatible. self.conn.executescript( """ CREATE TABLE IF NOT EXISTS events ( @@ -688,8 +689,7 @@ class EvidenceStore: """ ) - # Remove the pre-0.1.1 no-tools snapshot implementation. The real coding - # sidekick is a native Claude Code agent and stores no state in this DB. + # Remove the pre-0.1.1 snapshot implementation. self.conn.executescript( """ DROP TABLE IF EXISTS sidekick_calls; @@ -1041,7 +1041,7 @@ class EvidenceStore: if row["memory_text"] ] - def start_sidekick( + def start_subagent( self, repo: RepoContext, session_id: str, @@ -1049,7 +1049,7 @@ class EvidenceStore: agent_type: str, context_chars: int, ) -> bool: - """Record one native sidekick instance and whether context was first sent.""" + """Record one native subagent instance and whether context was first sent.""" with self.conn: cursor = self.conn.execute( """INSERT OR IGNORE INTO sidekick_runs @@ -1067,7 +1067,7 @@ class EvidenceStore: ) return int(cursor.rowcount) > 0 - def stop_sidekick( + def stop_subagent( self, repo: RepoContext, session_id: str, @@ -1222,7 +1222,7 @@ class EvidenceStore: cursor = self.conn.execute( f"DELETE FROM {table} WHERE {column} = ?", (repo_id,) ) - removed[table] = max(int(cursor.rowcount), 0) + removed["subagent_runs" if table == "sidekick_runs" else table] = max(int(cursor.rowcount), 0) return removed def status(self, repo_id: str) -> dict[str, Any]: @@ -1238,7 +1238,7 @@ class EvidenceStore: FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""", (repo_id,), ).fetchone() - last_sidekick = self.conn.execute( + last_subagent = self.conn.execute( """SELECT session_id, agent_id, agent_type, started_at, stopped_at, context_chars FROM sidekick_runs WHERE repo_id = ? @@ -1250,9 +1250,9 @@ class EvidenceStore: "events": count("events"), "flushes": count("flushes"), "retrievals": count("retrievals"), - "sidekick_runs": count("sidekick_runs"), + "subagent_runs": count("sidekick_runs"), "last_operation": dict(last_operation) if last_operation else None, - "last_sidekick": dict(last_sidekick) if last_sidekick else None, + "last_subagent": dict(last_subagent) if last_subagent else None, } @@ -1324,7 +1324,7 @@ def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> "tool": name, "failed": failed, "duration_ms": hook_input.get("duration_ms"), - "agent_role": "sidekick" if hook_input.get("agent_id") else "main", + "agent_role": "subagent" if hook_input.get("agent_id") else "main", } if hook_input.get("agent_id"): payload["agent_id"] = bounded(hook_input["agent_id"], 200) @@ -1384,35 +1384,33 @@ def record_tool( ) -def record_sidekick_start( - store: EvidenceStore, hook_input: dict[str, Any], *, inject_context: bool = True +def record_subagent_start( + store: EvidenceStore, hook_input: dict[str, Any] ) -> str: - """Record a native sidekick and reuse the main turn's retrieved memories.""" + """Record a native subagent and reuse the main turn's retrieved memories.""" session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200) - agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200) context = combine_context( format_context(store.injected_memories(session_id, repo.identity)) ) - if not inject_context: - context = "" - first_start = store.start_sidekick( + first_start = store.start_subagent( repo, session_id, agent_id, agent_type, len(context) ) store.record_event( repo, session_id, - "sidekick_start", + "subagent_start", { "agent_id": agent_id, "agent_type": agent_type, "context_chars": len(context) if first_start else 0, - "worktree_root": bounded(repo.root, 2000), + "repo_root": bounded(repo.root, 2000), }, ) telemetry.record( - "sidekick", + "subagent", repo=repo, session_id=session_id, phase="start", @@ -1422,14 +1420,14 @@ def record_sidekick_start( return context if first_start else "" -def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: +def record_subagent_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) - agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200) agent_id = bounded(hook_input.get("agent_id", ""), 200) final_message = redact(hook_input.get("last_assistant_message", "")).strip() transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000) - agent_id = store.stop_sidekick( + agent_id = store.stop_subagent( repo, session_id, agent_id, @@ -1440,7 +1438,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No store.record_event( repo, session_id, - "sidekick_stop", + "subagent_stop", { "agent_id": agent_id, "agent_type": agent_type, @@ -1449,7 +1447,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No }, ) telemetry.record( - "sidekick", + "subagent", repo=repo, session_id=session_id, phase="stop", @@ -1513,10 +1511,10 @@ def build_episode( for e in events if e["kind"] == "assistant_stop" and e["payload"].get("text") ] - sidekick_outcomes = [ + subagent_outcomes = [ redact(e["payload"].get("final_message", "")).strip() for e in events - if e["kind"] == "sidekick_stop" and e["payload"].get("final_message") + if e["kind"] in {"subagent_stop", "sidekick_stop"} and e["payload"].get("final_message") ] tools = [ e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"} @@ -1597,7 +1595,7 @@ def build_episode( } ) pending_user_messages = [] - elif event["kind"] == "sidekick_stop": + elif event["kind"] in {"subagent_stop", "sidekick_stop"}: pass extraction_messages.extend(pending_user_messages) @@ -1613,7 +1611,7 @@ def build_episode( "assistant_conclusion": conclusion, "user_messages": prompts, "assistant_outcomes": assistant_conclusions, - "sidekick_outcomes": sidekick_outcomes, + "subagent_outcomes": subagent_outcomes, "extraction_messages": extraction_messages, "files_read": read_paths[:50], "files_modified": modified_paths[:50], diff --git a/integrations/codex-plugin/hooks/adapter.py b/integrations/codex-plugin/hooks/adapter.py index 1fb6b0b3a..2032c6496 100644 --- a/integrations/codex-plugin/hooks/adapter.py +++ b/integrations/codex-plugin/hooks/adapter.py @@ -15,8 +15,8 @@ import hook_runner # noqa: E402 import telemetry # noqa: E402 from memory_core import ( # noqa: E402 configure_harness, - record_sidekick_start, - record_sidekick_stop, + record_subagent_start, + record_subagent_stop, record_tool, ) @@ -24,8 +24,8 @@ configure_harness("codex", data_dir_name="codex-plugin", source_tag="codex_plugi telemetry.init(harness="codex", source_tag="CODEX_PLUGIN") -def _sidekick_start(store, hook_input): - context = record_sidekick_start(store, hook_input) +def _subagent_start(store, hook_input): + context = record_subagent_start(store, hook_input) if context: return { "hookSpecificOutput": { @@ -35,8 +35,8 @@ def _sidekick_start(store, hook_input): } -def _sidekick_stop(store, hook_input): - record_sidekick_stop(store, hook_input) +def _subagent_stop(store, hook_input): + record_subagent_stop(store, hook_input) def _post_tool(store, payload): @@ -59,6 +59,6 @@ if __name__ == "__main__": if len(sys.argv) > 1 and sys.argv[1] == "post-tool": sys.argv[1] = "codex-post-tool" hook_runner.entry_point( - extra_actions={"sidekick-start": _sidekick_start, "sidekick-stop": _sidekick_stop, "codex-post-tool": _post_tool}, + extra_actions={"subagent-start": _subagent_start, "subagent-stop": _subagent_stop, "codex-post-tool": _post_tool}, automatic_flush_reasons={"session-end", "pre-compact"}, ) diff --git a/integrations/codex-plugin/hooks/hooks.json b/integrations/codex-plugin/hooks/hooks.json index 44c3732a1..1941c3e8f 100644 --- a/integrations/codex-plugin/hooks/hooks.json +++ b/integrations/codex-plugin/hooks/hooks.json @@ -27,14 +27,14 @@ "SubagentStart": [ { "hooks": [ - { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" sidekick-start --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 } + { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" subagent-start --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 } ] } ], "SubagentStop": [ { "hooks": [ - { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" sidekick-stop --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 } + { "type": "command", "command": "python3 \"${PLUGIN_ROOT}/hooks/adapter.py\" subagent-stop --plugin-data-dir \"${PLUGIN_DATA}\"", "timeout": 3 } ] } ], diff --git a/integrations/codex-plugin/tests/test_codex.py b/integrations/codex-plugin/tests/test_codex.py index 4254c1f13..dc5cce8fc 100644 --- a/integrations/codex-plugin/tests/test_codex.py +++ b/integrations/codex-plugin/tests/test_codex.py @@ -35,7 +35,7 @@ def test_codex_hooks_use_native_events_and_plugin_paths() -> None: assert all(hook.get("timeout", 0) <= 3 for groups in hooks.values() for group in groups for hook in group["hooks"]) -def test_codex_sidekick_records_lifecycle(tmp_path: Path) -> None: +def test_codex_subagent_records_lifecycle(tmp_path: Path) -> None: adapter = HOST / "hooks" / "adapter.py" payload = { "session_id": "session-1", @@ -45,8 +45,8 @@ def test_codex_sidekick_records_lifecycle(tmp_path: Path) -> None: } for action, extra in ( - ("sidekick-start", {}), - ("sidekick-stop", {"last_assistant_message": "SIDEKICK_OK"}), + ("subagent-start", {}), + ("subagent-stop", {"last_assistant_message": "SUBAGENT_OK"}), ): result = subprocess.run( [sys.executable, str(adapter), action, "--plugin-data-dir", str(tmp_path / "data")], @@ -65,7 +65,7 @@ def test_codex_sidekick_records_lifecycle(tmp_path: Path) -> None: assert row is not None assert row[0] == "agent-1" assert row[1] - assert row[2] == "SIDEKICK_OK" + assert row[2] == "SUBAGENT_OK" def test_codex_mcp_uses_host_relative_paths() -> None: diff --git a/integrations/cursor-plugin/.cursor-plugin/plugin.json b/integrations/cursor-plugin/.cursor-plugin/plugin.json index fe9594a12..e33de76a2 100644 --- a/integrations/cursor-plugin/.cursor-plugin/plugin.json +++ b/integrations/cursor-plugin/.cursor-plugin/plugin.json @@ -8,7 +8,6 @@ "license": "Apache-2.0", "keywords": ["memory", "coding-agents", "continual-learning", "token-efficiency"], "skills": "./skills/", - "agents": "./agents/", "hooks": "./hooks/hooks.json", "mcpServers": "./mcp.json", "variables": { diff --git a/integrations/cursor-plugin/agents/sidekick.md b/integrations/cursor-plugin/agents/sidekick.md deleted file mode 100644 index 31fa6e945..000000000 --- a/integrations/cursor-plugin/agents/sidekick.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -name: sidekick -description: Coding agent with an isolated context. Delegate focused investigation, implementation, testing, debugging, or review work to it, then review its result. -model: inherit ---- - -You are Mem0's Cursor sidekick. Complete only the work the parent agent assigns. -Return a tested result the parent can review without repeating your investigation. - -Always call `search_memories` before work that can depend on earlier decisions, -repository history, or user preferences. Inspect the relevant code and repository -rules, make requested edits, and run the smallest decisive checks. - -Do not make adjacent improvements. Ask the parent one concise question only when -a material decision or unsafe ambiguity blocks progress. Otherwise proceed and -report the outcome, changed files, validation, and remaining risk. diff --git a/integrations/cursor-plugin/core/memory_cli.py b/integrations/cursor-plugin/core/memory_cli.py index 595729feb..76d2ee871 100644 --- a/integrations/cursor-plugin/core/memory_cli.py +++ b/integrations/cursor-plugin/core/memory_cli.py @@ -11,10 +11,10 @@ import telemetry from memory_core import ( EvidenceStore, api_key, + configure_harness, data_dir, doctor, forget_remote_repo, - configure_harness, resolve_repo, user_id, ) @@ -32,7 +32,7 @@ def _print_status(value: dict) -> None: ) print( f"Used in this repository: {value['retrievals']} memories returned, " - f"{value['sidekick_runs']} sidekick runs" + f"{value['subagent_runs']} subagent runs" ) if last: item_label = "" @@ -48,13 +48,13 @@ def _print_status(value: dict) -> None: f"{'succeeded' if last['success'] else 'failed'} " f"({last['duration_ms']:.1f} ms{item_label})" ) - sidekick = value.get("last_sidekick") or {} - if sidekick: - state = "finished" if sidekick.get("stopped_at") else "started" + subagent = value.get("last_subagent") or {} + if subagent: + state = "finished" if subagent.get("stopped_at") else "started" print( - "Last sidekick: " - f"{state}, received {sidekick['context_chars']} characters of memory, " - f"agent {sidekick['agent_id']}" + "Last subagent: " + f"{state}, received {subagent['context_chars']} characters of memory, " + f"agent {subagent['agent_id']}" ) diff --git a/integrations/cursor-plugin/core/memory_core.py b/integrations/cursor-plugin/core/memory_core.py index cf71196b8..77d7a2b80 100644 --- a/integrations/cursor-plugin/core/memory_core.py +++ b/integrations/cursor-plugin/core/memory_core.py @@ -524,7 +524,7 @@ def _checkpoint_message(event: dict[str, Any]) -> str: if text: return text return redact(payload.get("text", "")).strip() - if kind == "sidekick_stop": + if kind in {"subagent_stop", "sidekick_stop"}: return redact(payload.get("final_message", "")).strip() return "" @@ -596,6 +596,7 @@ class EvidenceStore: self.conn.close() def _migrate(self) -> None: + # Keep the legacy table name so existing databases and in-flight workers remain compatible. self.conn.executescript( """ CREATE TABLE IF NOT EXISTS events ( @@ -688,8 +689,7 @@ class EvidenceStore: """ ) - # Remove the pre-0.1.1 no-tools snapshot implementation. The real coding - # sidekick is a native Claude Code agent and stores no state in this DB. + # Remove the pre-0.1.1 snapshot implementation. self.conn.executescript( """ DROP TABLE IF EXISTS sidekick_calls; @@ -1041,7 +1041,7 @@ class EvidenceStore: if row["memory_text"] ] - def start_sidekick( + def start_subagent( self, repo: RepoContext, session_id: str, @@ -1049,7 +1049,7 @@ class EvidenceStore: agent_type: str, context_chars: int, ) -> bool: - """Record one native sidekick instance and whether context was first sent.""" + """Record one native subagent instance and whether context was first sent.""" with self.conn: cursor = self.conn.execute( """INSERT OR IGNORE INTO sidekick_runs @@ -1067,7 +1067,7 @@ class EvidenceStore: ) return int(cursor.rowcount) > 0 - def stop_sidekick( + def stop_subagent( self, repo: RepoContext, session_id: str, @@ -1222,7 +1222,7 @@ class EvidenceStore: cursor = self.conn.execute( f"DELETE FROM {table} WHERE {column} = ?", (repo_id,) ) - removed[table] = max(int(cursor.rowcount), 0) + removed["subagent_runs" if table == "sidekick_runs" else table] = max(int(cursor.rowcount), 0) return removed def status(self, repo_id: str) -> dict[str, Any]: @@ -1238,7 +1238,7 @@ class EvidenceStore: FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""", (repo_id,), ).fetchone() - last_sidekick = self.conn.execute( + last_subagent = self.conn.execute( """SELECT session_id, agent_id, agent_type, started_at, stopped_at, context_chars FROM sidekick_runs WHERE repo_id = ? @@ -1250,9 +1250,9 @@ class EvidenceStore: "events": count("events"), "flushes": count("flushes"), "retrievals": count("retrievals"), - "sidekick_runs": count("sidekick_runs"), + "subagent_runs": count("sidekick_runs"), "last_operation": dict(last_operation) if last_operation else None, - "last_sidekick": dict(last_sidekick) if last_sidekick else None, + "last_subagent": dict(last_subagent) if last_subagent else None, } @@ -1324,7 +1324,7 @@ def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> "tool": name, "failed": failed, "duration_ms": hook_input.get("duration_ms"), - "agent_role": "sidekick" if hook_input.get("agent_id") else "main", + "agent_role": "subagent" if hook_input.get("agent_id") else "main", } if hook_input.get("agent_id"): payload["agent_id"] = bounded(hook_input["agent_id"], 200) @@ -1384,35 +1384,33 @@ def record_tool( ) -def record_sidekick_start( - store: EvidenceStore, hook_input: dict[str, Any], *, inject_context: bool = True +def record_subagent_start( + store: EvidenceStore, hook_input: dict[str, Any] ) -> str: - """Record a native sidekick and reuse the main turn's retrieved memories.""" + """Record a native subagent and reuse the main turn's retrieved memories.""" session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200) - agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200) context = combine_context( format_context(store.injected_memories(session_id, repo.identity)) ) - if not inject_context: - context = "" - first_start = store.start_sidekick( + first_start = store.start_subagent( repo, session_id, agent_id, agent_type, len(context) ) store.record_event( repo, session_id, - "sidekick_start", + "subagent_start", { "agent_id": agent_id, "agent_type": agent_type, "context_chars": len(context) if first_start else 0, - "worktree_root": bounded(repo.root, 2000), + "repo_root": bounded(repo.root, 2000), }, ) telemetry.record( - "sidekick", + "subagent", repo=repo, session_id=session_id, phase="start", @@ -1422,14 +1420,14 @@ def record_sidekick_start( return context if first_start else "" -def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: +def record_subagent_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) - agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200) agent_id = bounded(hook_input.get("agent_id", ""), 200) final_message = redact(hook_input.get("last_assistant_message", "")).strip() transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000) - agent_id = store.stop_sidekick( + agent_id = store.stop_subagent( repo, session_id, agent_id, @@ -1440,7 +1438,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No store.record_event( repo, session_id, - "sidekick_stop", + "subagent_stop", { "agent_id": agent_id, "agent_type": agent_type, @@ -1449,7 +1447,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No }, ) telemetry.record( - "sidekick", + "subagent", repo=repo, session_id=session_id, phase="stop", @@ -1513,10 +1511,10 @@ def build_episode( for e in events if e["kind"] == "assistant_stop" and e["payload"].get("text") ] - sidekick_outcomes = [ + subagent_outcomes = [ redact(e["payload"].get("final_message", "")).strip() for e in events - if e["kind"] == "sidekick_stop" and e["payload"].get("final_message") + if e["kind"] in {"subagent_stop", "sidekick_stop"} and e["payload"].get("final_message") ] tools = [ e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"} @@ -1597,7 +1595,7 @@ def build_episode( } ) pending_user_messages = [] - elif event["kind"] == "sidekick_stop": + elif event["kind"] in {"subagent_stop", "sidekick_stop"}: pass extraction_messages.extend(pending_user_messages) @@ -1613,7 +1611,7 @@ def build_episode( "assistant_conclusion": conclusion, "user_messages": prompts, "assistant_outcomes": assistant_conclusions, - "sidekick_outcomes": sidekick_outcomes, + "subagent_outcomes": subagent_outcomes, "extraction_messages": extraction_messages, "files_read": read_paths[:50], "files_modified": modified_paths[:50], diff --git a/integrations/cursor-plugin/hooks/adapter.py b/integrations/cursor-plugin/hooks/adapter.py index d167f9a28..ba82f4eab 100644 --- a/integrations/cursor-plugin/hooks/adapter.py +++ b/integrations/cursor-plugin/hooks/adapter.py @@ -19,8 +19,6 @@ import hook_runner # noqa: E402 import telemetry # noqa: E402 from memory_core import ( # noqa: E402 configure_harness, - record_sidekick_start, - record_sidekick_stop, record_tool, ) @@ -30,8 +28,6 @@ EVENTS = { "postToolUse": "post-tool", "postToolUseFailure": "post-tool-failure", "afterAgentResponse": "assistant-stop", - "subagentStart": "sidekick-start", - "subagentStop": "sidekick-stop", "stop": "stop", "sessionEnd": "session-end", "preCompact": "pre-compact", @@ -52,10 +48,6 @@ def normalize(payload: dict, event: str) -> dict: value.setdefault("last_assistant_message", value["text"]) if "summary" in value: value.setdefault("last_assistant_message", value["summary"]) - if "subagent_id" in value: - value.setdefault("agent_id", value["subagent_id"]) - if "subagent_type" in value: - value.setdefault("agent_type", value["subagent_type"]) return {"action": EVENTS[event], "payload": value} @@ -67,15 +59,6 @@ def _record_response(store, payload): hook_runner.default_record_stop(store, payload) -def _record_sidekick_start(store, payload): - record_sidekick_start(store, payload, inject_context=False) - return {"permission": "allow"} - - -def _record_sidekick_stop(store, payload): - record_sidekick_stop(store, payload) - - def main() -> int: if len(sys.argv) != 2 or sys.argv[1] not in EVENTS: return 2 @@ -100,8 +83,6 @@ def main() -> int: extra_actions={ "post-tool-failure": _record_failure, "assistant-stop": _record_response, - "sidekick-start": _record_sidekick_start, - "sidekick-stop": _record_sidekick_stop, }, automatic_flush_reasons={"session-end", "pre-compact"}, ) @@ -119,8 +100,6 @@ def main() -> int: } if environment: print(json.dumps({"env": environment})) - elif event == "subagentStart": - print(json.dumps({"permission": "allow"})) return result diff --git a/integrations/cursor-plugin/hooks/hooks.json b/integrations/cursor-plugin/hooks/hooks.json index 1e4875d50..dcd1d7c5d 100644 --- a/integrations/cursor-plugin/hooks/hooks.json +++ b/integrations/cursor-plugin/hooks/hooks.json @@ -6,8 +6,6 @@ "postToolUse": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" postToolUse", "timeout": 3 }], "postToolUseFailure": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" postToolUseFailure", "timeout": 3 }], "afterAgentResponse": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" afterAgentResponse", "timeout": 3 }], - "subagentStart": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" subagentStart", "matcher": "^sidekick$", "timeout": 5 }], - "subagentStop": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" subagentStop", "matcher": "^sidekick$", "timeout": 5 }], "stop": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" stop", "timeout": 3 }], "preCompact": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" preCompact", "timeout": 5 }], "sessionEnd": [{ "command": "python3 \"${CURSOR_PLUGIN_ROOT}/hooks/adapter.py\" sessionEnd", "timeout": 5 }] diff --git a/integrations/cursor-plugin/plugin-build.json b/integrations/cursor-plugin/plugin-build.json index bddfbec4a..279b3178c 100644 --- a/integrations/cursor-plugin/plugin-build.json +++ b/integrations/cursor-plugin/plugin-build.json @@ -8,7 +8,6 @@ ".cursor-plugin/plugin.json": ".cursor-plugin/plugin.json", "hooks/hooks.json": "hooks/hooks.json", "hooks/adapter.py": "hooks/adapter.py", - "agents/sidekick.md": "agents/sidekick.md", "mcp.json": "mcp.json" } } diff --git a/integrations/cursor-plugin/tests/test_adapter.py b/integrations/cursor-plugin/tests/test_adapter.py index d0956e410..7db6f81c3 100644 --- a/integrations/cursor-plugin/tests/test_adapter.py +++ b/integrations/cursor-plugin/tests/test_adapter.py @@ -26,8 +26,6 @@ SPEC.loader.exec_module(adapter) ("postToolUse", "post-tool"), ("postToolUseFailure", "post-tool-failure"), ("afterAgentResponse", "assistant-stop"), - ("subagentStart", "sidekick-start"), - ("subagentStop", "sidekick-stop"), ("stop", "stop"), ("sessionEnd", "session-end"), ("preCompact", "pre-compact"), @@ -57,48 +55,18 @@ def test_after_agent_response_does_not_return_internal_context(monkeypatch: pyte assert adapter._record_response(object(), {}) is None -def test_normalizes_cursor_sidekick_fields() -> None: - started = adapter.normalize( - { - "subagent_id": "agent-1", - "subagent_type": "sidekick", - "parent_conversation_id": "parent-1", - }, - "subagentStart", - )["payload"] - stopped = adapter.normalize({"summary": "done"}, "subagentStop")["payload"] - - assert started["agent_id"] == "agent-1" - assert started["agent_type"] == "sidekick" - assert started["session_id"] == "parent-1" - assert stopped["last_assistant_message"] == "done" - - -def test_cursor_sidekick_records_lifecycle_without_blocking(monkeypatch: pytest.MonkeyPatch) -> None: - monkeypatch.setattr(adapter, "record_sidekick_start", lambda store, payload, *, inject_context: "" if not inject_context else pytest.fail("cannot inject context")) - stopped = [] - monkeypatch.setattr(adapter, "record_sidekick_stop", lambda store, payload: stopped.append(payload)) - - assert adapter._record_sidekick_start(object(), {}) == {"permission": "allow"} - assert adapter._record_sidekick_stop(object(), {"summary": "done"}) is None - assert stopped == [{"summary": "done"}] - - def test_cursor_hooks_use_native_flat_entries() -> None: hooks = json.loads((HOST / "hooks" / "hooks.json").read_text(encoding="utf-8")) assert hooks["version"] == 1 + assert not {"subagentStart", "subagentStop"} & hooks["hooks"].keys() assert set(hooks["hooks"]) >= { "sessionStart", "beforeSubmitPrompt", "postToolUse", - "subagentStart", - "subagentStop", "stop", "sessionEnd", } - assert hooks["hooks"]["subagentStart"][0]["matcher"] == "^sidekick$" - assert hooks["hooks"]["subagentStop"][0]["matcher"] == "^sidekick$" assert all("hooks" not in entry for entries in hooks["hooks"].values() for entry in entries) @@ -107,6 +75,7 @@ def test_native_cursor_bundle_is_self_contained(tmp_path: Path) -> None: manifest = json.loads((root / ".cursor-plugin" / "plugin.json").read_text(encoding="utf-8")) assert manifest["hooks"] == "./hooks/hooks.json" + assert "agents" not in manifest assert (root / "hooks" / "adapter.py").is_file() - assert (root / "agents" / "sidekick.md").is_file() + assert not (root / "agents").exists() assert not any(path.is_symlink() for path in root.rglob("*")) diff --git a/integrations/deepseek-plugin/README.md b/integrations/deepseek-plugin/README.md index 2b55aaf50..93e5f563f 100644 --- a/integrations/deepseek-plugin/README.md +++ b/integrations/deepseek-plugin/README.md @@ -15,6 +15,8 @@ Unlike the local/file-based memory plugins in the ecosystem, Mem0 is a managed b Current package version: `0.3.0`. +Sidekick is available only in the [Claude Code plugin](../claude-code-plugin/README.md#sonnet-sidekick-agent). + ## How it works A Cordis plugin is a module exporting `apply(ctx, config)`. This one waits for the Harness tool and system-prompt services, then uses the native extension points: @@ -61,7 +63,7 @@ Cordis owns listener and tool cleanup when the plugin unmounts. Every automatic ``` 5. Open http://127.0.0.1:3080 and ask the agent to remember something, then recall it in a later turn. -For a Mem0 Platform on-prem or dedicated deployment, point `config.host` at that base URL (defaults to `api.mem0.ai`). `host` is a Platform base-URL override — it is not a switch to self-hosted Mem0 OSS, whose server exposes a different API surface. +For a Mem0 Platform on-prem or dedicated deployment, point `config.host` at that base URL (defaults to `api.mem0.ai`). `host` overrides the Platform base URL. It does not support the self-hosted Mem0 OSS API. ## Configuration diff --git a/integrations/kimi-plugin/agents/sidekick.md b/integrations/kimi-plugin/agents/sidekick.md deleted file mode 100644 index 8032119b0..000000000 --- a/integrations/kimi-plugin/agents/sidekick.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -name: sidekick -description: Coding subagent for focused implementation, investigation, testing, debugging, or review work. -whenToUse: Delegate a bounded engineering task that benefits from its own isolated context. ---- - -You are Mem0's coding sidekick. Complete only the bounded task the main agent -delegates to you and return a concise, self-contained result. - -Search Mem0 before work that may depend on prior repository decisions or user -preferences. Inspect the relevant repository rules and code, make changes when -asked, and run the smallest decisive validation. Do not claim Git worktree -isolation: Kimi provides a separate context, while filesystem isolation depends -on the caller's environment. - -Your final response must state the outcome, changed files, validation, and any -remaining risk. Do not commit, push, or open a pull request unless the caller -explicitly asks. diff --git a/integrations/kimi-plugin/core/memory_cli.py b/integrations/kimi-plugin/core/memory_cli.py index 595729feb..76d2ee871 100644 --- a/integrations/kimi-plugin/core/memory_cli.py +++ b/integrations/kimi-plugin/core/memory_cli.py @@ -11,10 +11,10 @@ import telemetry from memory_core import ( EvidenceStore, api_key, + configure_harness, data_dir, doctor, forget_remote_repo, - configure_harness, resolve_repo, user_id, ) @@ -32,7 +32,7 @@ def _print_status(value: dict) -> None: ) print( f"Used in this repository: {value['retrievals']} memories returned, " - f"{value['sidekick_runs']} sidekick runs" + f"{value['subagent_runs']} subagent runs" ) if last: item_label = "" @@ -48,13 +48,13 @@ def _print_status(value: dict) -> None: f"{'succeeded' if last['success'] else 'failed'} " f"({last['duration_ms']:.1f} ms{item_label})" ) - sidekick = value.get("last_sidekick") or {} - if sidekick: - state = "finished" if sidekick.get("stopped_at") else "started" + subagent = value.get("last_subagent") or {} + if subagent: + state = "finished" if subagent.get("stopped_at") else "started" print( - "Last sidekick: " - f"{state}, received {sidekick['context_chars']} characters of memory, " - f"agent {sidekick['agent_id']}" + "Last subagent: " + f"{state}, received {subagent['context_chars']} characters of memory, " + f"agent {subagent['agent_id']}" ) diff --git a/integrations/kimi-plugin/core/memory_core.py b/integrations/kimi-plugin/core/memory_core.py index cf71196b8..77d7a2b80 100644 --- a/integrations/kimi-plugin/core/memory_core.py +++ b/integrations/kimi-plugin/core/memory_core.py @@ -524,7 +524,7 @@ def _checkpoint_message(event: dict[str, Any]) -> str: if text: return text return redact(payload.get("text", "")).strip() - if kind == "sidekick_stop": + if kind in {"subagent_stop", "sidekick_stop"}: return redact(payload.get("final_message", "")).strip() return "" @@ -596,6 +596,7 @@ class EvidenceStore: self.conn.close() def _migrate(self) -> None: + # Keep the legacy table name so existing databases and in-flight workers remain compatible. self.conn.executescript( """ CREATE TABLE IF NOT EXISTS events ( @@ -688,8 +689,7 @@ class EvidenceStore: """ ) - # Remove the pre-0.1.1 no-tools snapshot implementation. The real coding - # sidekick is a native Claude Code agent and stores no state in this DB. + # Remove the pre-0.1.1 snapshot implementation. self.conn.executescript( """ DROP TABLE IF EXISTS sidekick_calls; @@ -1041,7 +1041,7 @@ class EvidenceStore: if row["memory_text"] ] - def start_sidekick( + def start_subagent( self, repo: RepoContext, session_id: str, @@ -1049,7 +1049,7 @@ class EvidenceStore: agent_type: str, context_chars: int, ) -> bool: - """Record one native sidekick instance and whether context was first sent.""" + """Record one native subagent instance and whether context was first sent.""" with self.conn: cursor = self.conn.execute( """INSERT OR IGNORE INTO sidekick_runs @@ -1067,7 +1067,7 @@ class EvidenceStore: ) return int(cursor.rowcount) > 0 - def stop_sidekick( + def stop_subagent( self, repo: RepoContext, session_id: str, @@ -1222,7 +1222,7 @@ class EvidenceStore: cursor = self.conn.execute( f"DELETE FROM {table} WHERE {column} = ?", (repo_id,) ) - removed[table] = max(int(cursor.rowcount), 0) + removed["subagent_runs" if table == "sidekick_runs" else table] = max(int(cursor.rowcount), 0) return removed def status(self, repo_id: str) -> dict[str, Any]: @@ -1238,7 +1238,7 @@ class EvidenceStore: FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""", (repo_id,), ).fetchone() - last_sidekick = self.conn.execute( + last_subagent = self.conn.execute( """SELECT session_id, agent_id, agent_type, started_at, stopped_at, context_chars FROM sidekick_runs WHERE repo_id = ? @@ -1250,9 +1250,9 @@ class EvidenceStore: "events": count("events"), "flushes": count("flushes"), "retrievals": count("retrievals"), - "sidekick_runs": count("sidekick_runs"), + "subagent_runs": count("sidekick_runs"), "last_operation": dict(last_operation) if last_operation else None, - "last_sidekick": dict(last_sidekick) if last_sidekick else None, + "last_subagent": dict(last_subagent) if last_subagent else None, } @@ -1324,7 +1324,7 @@ def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> "tool": name, "failed": failed, "duration_ms": hook_input.get("duration_ms"), - "agent_role": "sidekick" if hook_input.get("agent_id") else "main", + "agent_role": "subagent" if hook_input.get("agent_id") else "main", } if hook_input.get("agent_id"): payload["agent_id"] = bounded(hook_input["agent_id"], 200) @@ -1384,35 +1384,33 @@ def record_tool( ) -def record_sidekick_start( - store: EvidenceStore, hook_input: dict[str, Any], *, inject_context: bool = True +def record_subagent_start( + store: EvidenceStore, hook_input: dict[str, Any] ) -> str: - """Record a native sidekick and reuse the main turn's retrieved memories.""" + """Record a native subagent and reuse the main turn's retrieved memories.""" session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200) - agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200) context = combine_context( format_context(store.injected_memories(session_id, repo.identity)) ) - if not inject_context: - context = "" - first_start = store.start_sidekick( + first_start = store.start_subagent( repo, session_id, agent_id, agent_type, len(context) ) store.record_event( repo, session_id, - "sidekick_start", + "subagent_start", { "agent_id": agent_id, "agent_type": agent_type, "context_chars": len(context) if first_start else 0, - "worktree_root": bounded(repo.root, 2000), + "repo_root": bounded(repo.root, 2000), }, ) telemetry.record( - "sidekick", + "subagent", repo=repo, session_id=session_id, phase="start", @@ -1422,14 +1420,14 @@ def record_sidekick_start( return context if first_start else "" -def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: +def record_subagent_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) - agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200) agent_id = bounded(hook_input.get("agent_id", ""), 200) final_message = redact(hook_input.get("last_assistant_message", "")).strip() transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000) - agent_id = store.stop_sidekick( + agent_id = store.stop_subagent( repo, session_id, agent_id, @@ -1440,7 +1438,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No store.record_event( repo, session_id, - "sidekick_stop", + "subagent_stop", { "agent_id": agent_id, "agent_type": agent_type, @@ -1449,7 +1447,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No }, ) telemetry.record( - "sidekick", + "subagent", repo=repo, session_id=session_id, phase="stop", @@ -1513,10 +1511,10 @@ def build_episode( for e in events if e["kind"] == "assistant_stop" and e["payload"].get("text") ] - sidekick_outcomes = [ + subagent_outcomes = [ redact(e["payload"].get("final_message", "")).strip() for e in events - if e["kind"] == "sidekick_stop" and e["payload"].get("final_message") + if e["kind"] in {"subagent_stop", "sidekick_stop"} and e["payload"].get("final_message") ] tools = [ e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"} @@ -1597,7 +1595,7 @@ def build_episode( } ) pending_user_messages = [] - elif event["kind"] == "sidekick_stop": + elif event["kind"] in {"subagent_stop", "sidekick_stop"}: pass extraction_messages.extend(pending_user_messages) @@ -1613,7 +1611,7 @@ def build_episode( "assistant_conclusion": conclusion, "user_messages": prompts, "assistant_outcomes": assistant_conclusions, - "sidekick_outcomes": sidekick_outcomes, + "subagent_outcomes": subagent_outcomes, "extraction_messages": extraction_messages, "files_read": read_paths[:50], "files_modified": modified_paths[:50], diff --git a/integrations/kimi-plugin/hooks/adapter.py b/integrations/kimi-plugin/hooks/adapter.py index 3a16b52d3..a3c019c39 100644 --- a/integrations/kimi-plugin/hooks/adapter.py +++ b/integrations/kimi-plugin/hooks/adapter.py @@ -8,7 +8,6 @@ import io import json import os import sys -import uuid from pathlib import Path HERE = Path(__file__).resolve() @@ -18,7 +17,7 @@ sys.path.insert(0, str(CORE)) import hook_runner # noqa: E402 import telemetry # noqa: E402 -from memory_core import configure_harness, record_sidekick_start, record_sidekick_stop, record_tool # noqa: E402 +from memory_core import configure_harness, record_tool # noqa: E402 EVENTS = { "SessionStart": ["session-start"], @@ -28,8 +27,6 @@ EVENTS = { "Stop": ["stop"], "PreCompact": ["flush", "--reason", "pre-compact"], "SessionEnd": ["flush", "--reason", "session-end"], - "SubagentStart": ["sidekick-start"], - "SubagentStop": ["sidekick-stop"], } @@ -93,8 +90,6 @@ def normalize(payload: dict) -> dict: value.setdefault("tool_response", value["error"]) if "response" in value: value.setdefault("last_assistant_message", value["response"]) - if "agent_name" in value: - value.setdefault("agent_type", value["agent_name"]) if value.get("hook_event_name") == "Stop": session = _session_dir(str(value.get("session_id") or "")) transcript = session / "agents" / "main" / "wire.jsonl" if session else None @@ -105,17 +100,6 @@ def normalize(payload: dict) -> dict: return value -def _sidekick_start(store, payload): - payload = dict(payload) - payload.setdefault("agent_id", f"kimi-{uuid.uuid4().hex}") - context = record_sidekick_start(store, payload) - return {"hookSpecificOutput": {"additionalContext": context}} if context else None - - -def _sidekick_stop(store, payload): - record_sidekick_stop(store, payload) - - def main() -> int: if len(sys.argv) != 2 or sys.argv[1] not in EVENTS: return 2 @@ -133,12 +117,10 @@ def main() -> int: result = hook_runner.run( extra_actions={ "post-tool-failure": lambda store, payload: record_tool(store, payload, failed=True), - "sidekick-start": _sidekick_start, - "sidekick-stop": _sidekick_stop, }, automatic_flush_reasons={"session-end", "pre-compact"}, ) - if event in {"UserPromptSubmit", "SubagentStart"} and (raw_output := output.getvalue().strip()): + if event == "UserPromptSubmit" and (raw_output := output.getvalue().strip()): parsed = json.loads(raw_output) context = parsed.get("hookSpecificOutput", {}).get("additionalContext", "") if context: diff --git a/integrations/kimi-plugin/kimi.plugin.json b/integrations/kimi-plugin/kimi.plugin.json index 062a783ee..0d63501fe 100644 --- a/integrations/kimi-plugin/kimi.plugin.json +++ b/integrations/kimi-plugin/kimi.plugin.json @@ -11,7 +11,6 @@ "shortDescription": "Cross-session memory for Kimi Code" }, "skills": "./skills/", - "agents": "./agents/", "mcpServers": { "mem0": { "command": "python3", @@ -25,8 +24,6 @@ { "event": "PostToolUseFailure", "matcher": ".*", "command": "python3 ./hooks/adapter.py PostToolUseFailure", "timeout": 3 }, { "event": "Stop", "command": "python3 ./hooks/adapter.py Stop", "timeout": 3 }, { "event": "PreCompact", "command": "python3 ./hooks/adapter.py PreCompact", "timeout": 5 }, - { "event": "SessionEnd", "command": "python3 ./hooks/adapter.py SessionEnd", "timeout": 5 }, - { "event": "SubagentStart", "matcher": "^sidekick$", "command": "python3 ./hooks/adapter.py SubagentStart", "timeout": 5 }, - { "event": "SubagentStop", "matcher": "^sidekick$", "command": "python3 ./hooks/adapter.py SubagentStop", "timeout": 5 } + { "event": "SessionEnd", "command": "python3 ./hooks/adapter.py SessionEnd", "timeout": 5 } ] } diff --git a/integrations/kimi-plugin/plugin-build.json b/integrations/kimi-plugin/plugin-build.json index 021a03a80..3926a57df 100644 --- a/integrations/kimi-plugin/plugin-build.json +++ b/integrations/kimi-plugin/plugin-build.json @@ -6,8 +6,7 @@ "pluginRoot": "${KIMI_PLUGIN_ROOT}", "files": { "kimi.plugin.json": "kimi.plugin.json", - "hooks/adapter.py": "hooks/adapter.py", - "agents/sidekick.md": "agents/sidekick.md" + "hooks/adapter.py": "hooks/adapter.py" } } } diff --git a/integrations/kimi-plugin/tests/test_kimi.py b/integrations/kimi-plugin/tests/test_kimi.py index ec93be86c..93ae66563 100644 --- a/integrations/kimi-plugin/tests/test_kimi.py +++ b/integrations/kimi-plugin/tests/test_kimi.py @@ -118,73 +118,20 @@ def test_stop_reads_main_response_from_kimi_session_transcript(tmp_path: Path, m assert value["transcript_path"] == str(transcript) -def test_repeated_sidekick_invocations_get_distinct_run_ids(tmp_path: Path) -> None: - store = adapter.hook_runner.EvidenceStore(tmp_path / "evidence.sqlite3") - payload = { - "hook_event_name": "SubagentStart", - "session_id": "session_abc", - "session_title": "Fix Kimi capture", - "client_type": "kimi_code_cli", - "cwd": str(tmp_path), - "agent_name": "sidekick", - "prompt": "Fix the adapter", - } - - try: - adapter._sidekick_start(store, adapter.normalize({**payload, "agent_id": "first"})) - adapter._sidekick_start(store, adapter.normalize({**payload, "agent_id": "second"})) - adapter._sidekick_stop( - store, - adapter.normalize( - { - **payload, - "hook_event_name": "SubagentStop", - "response": "First run complete.", - "agent_id": "first", - } - ), - ) - adapter._sidekick_stop( - store, - adapter.normalize( - { - **payload, - "hook_event_name": "SubagentStop", - "response": "Second run complete.", - "agent_id": "second", - } - ), - ) - - rows = store.conn.execute( - "SELECT agent_id, stopped_at, final_message FROM sidekick_runs ORDER BY started_at, agent_id" - ).fetchall() - finally: - store.close() - - assert len(rows) == 2 - assert rows[0]["agent_id"] != rows[1]["agent_id"] - assert all(row["stopped_at"] for row in rows) - assert {row["agent_id"]: row["final_message"] for row in rows} == { - "first": "First run complete.", "second": "Second run complete." - } - - def test_native_kimi_bundle_uses_inline_native_contract(tmp_path: Path) -> None: root = build("kimi", "native", tmp_path / "kimi") manifest = json.loads((root / "kimi.plugin.json").read_text(encoding="utf-8")) assert manifest["skills"] == "./skills/" - assert manifest["agents"] == "./agents/" + assert "agents" not in manifest assert manifest["mcpServers"]["mem0"]["args"] == ["./core/mcp_server.py"] + assert not {"SubagentStart", "SubagentStop"} & {hook["event"] for hook in manifest["hooks"]} assert {hook["event"] for hook in manifest["hooks"]} >= { "SessionStart", "UserPromptSubmit", "PostToolUse", - "SubagentStart", - "SubagentStop", "PreCompact", "SessionEnd", } - assert (root / "agents" / "sidekick.md").is_file() + assert not (root / "agents").exists() assert not any(path.is_symlink() for path in root.rglob("*")) diff --git a/integrations/mem0-agent-plugin/core/memory_cli.py b/integrations/mem0-agent-plugin/core/memory_cli.py index 595729feb..76d2ee871 100644 --- a/integrations/mem0-agent-plugin/core/memory_cli.py +++ b/integrations/mem0-agent-plugin/core/memory_cli.py @@ -11,10 +11,10 @@ import telemetry from memory_core import ( EvidenceStore, api_key, + configure_harness, data_dir, doctor, forget_remote_repo, - configure_harness, resolve_repo, user_id, ) @@ -32,7 +32,7 @@ def _print_status(value: dict) -> None: ) print( f"Used in this repository: {value['retrievals']} memories returned, " - f"{value['sidekick_runs']} sidekick runs" + f"{value['subagent_runs']} subagent runs" ) if last: item_label = "" @@ -48,13 +48,13 @@ def _print_status(value: dict) -> None: f"{'succeeded' if last['success'] else 'failed'} " f"({last['duration_ms']:.1f} ms{item_label})" ) - sidekick = value.get("last_sidekick") or {} - if sidekick: - state = "finished" if sidekick.get("stopped_at") else "started" + subagent = value.get("last_subagent") or {} + if subagent: + state = "finished" if subagent.get("stopped_at") else "started" print( - "Last sidekick: " - f"{state}, received {sidekick['context_chars']} characters of memory, " - f"agent {sidekick['agent_id']}" + "Last subagent: " + f"{state}, received {subagent['context_chars']} characters of memory, " + f"agent {subagent['agent_id']}" ) diff --git a/integrations/mem0-agent-plugin/core/memory_core.py b/integrations/mem0-agent-plugin/core/memory_core.py index cf71196b8..77d7a2b80 100644 --- a/integrations/mem0-agent-plugin/core/memory_core.py +++ b/integrations/mem0-agent-plugin/core/memory_core.py @@ -524,7 +524,7 @@ def _checkpoint_message(event: dict[str, Any]) -> str: if text: return text return redact(payload.get("text", "")).strip() - if kind == "sidekick_stop": + if kind in {"subagent_stop", "sidekick_stop"}: return redact(payload.get("final_message", "")).strip() return "" @@ -596,6 +596,7 @@ class EvidenceStore: self.conn.close() def _migrate(self) -> None: + # Keep the legacy table name so existing databases and in-flight workers remain compatible. self.conn.executescript( """ CREATE TABLE IF NOT EXISTS events ( @@ -688,8 +689,7 @@ class EvidenceStore: """ ) - # Remove the pre-0.1.1 no-tools snapshot implementation. The real coding - # sidekick is a native Claude Code agent and stores no state in this DB. + # Remove the pre-0.1.1 snapshot implementation. self.conn.executescript( """ DROP TABLE IF EXISTS sidekick_calls; @@ -1041,7 +1041,7 @@ class EvidenceStore: if row["memory_text"] ] - def start_sidekick( + def start_subagent( self, repo: RepoContext, session_id: str, @@ -1049,7 +1049,7 @@ class EvidenceStore: agent_type: str, context_chars: int, ) -> bool: - """Record one native sidekick instance and whether context was first sent.""" + """Record one native subagent instance and whether context was first sent.""" with self.conn: cursor = self.conn.execute( """INSERT OR IGNORE INTO sidekick_runs @@ -1067,7 +1067,7 @@ class EvidenceStore: ) return int(cursor.rowcount) > 0 - def stop_sidekick( + def stop_subagent( self, repo: RepoContext, session_id: str, @@ -1222,7 +1222,7 @@ class EvidenceStore: cursor = self.conn.execute( f"DELETE FROM {table} WHERE {column} = ?", (repo_id,) ) - removed[table] = max(int(cursor.rowcount), 0) + removed["subagent_runs" if table == "sidekick_runs" else table] = max(int(cursor.rowcount), 0) return removed def status(self, repo_id: str) -> dict[str, Any]: @@ -1238,7 +1238,7 @@ class EvidenceStore: FROM operations WHERE repo_id = ? ORDER BY id DESC LIMIT 1""", (repo_id,), ).fetchone() - last_sidekick = self.conn.execute( + last_subagent = self.conn.execute( """SELECT session_id, agent_id, agent_type, started_at, stopped_at, context_chars FROM sidekick_runs WHERE repo_id = ? @@ -1250,9 +1250,9 @@ class EvidenceStore: "events": count("events"), "flushes": count("flushes"), "retrievals": count("retrievals"), - "sidekick_runs": count("sidekick_runs"), + "subagent_runs": count("sidekick_runs"), "last_operation": dict(last_operation) if last_operation else None, - "last_sidekick": dict(last_sidekick) if last_sidekick else None, + "last_subagent": dict(last_subagent) if last_subagent else None, } @@ -1324,7 +1324,7 @@ def tool_payload(hook_input: dict[str, Any], *, failed: bool | None = False) -> "tool": name, "failed": failed, "duration_ms": hook_input.get("duration_ms"), - "agent_role": "sidekick" if hook_input.get("agent_id") else "main", + "agent_role": "subagent" if hook_input.get("agent_id") else "main", } if hook_input.get("agent_id"): payload["agent_id"] = bounded(hook_input["agent_id"], 200) @@ -1384,35 +1384,33 @@ def record_tool( ) -def record_sidekick_start( - store: EvidenceStore, hook_input: dict[str, Any], *, inject_context: bool = True +def record_subagent_start( + store: EvidenceStore, hook_input: dict[str, Any] ) -> str: - """Record a native sidekick and reuse the main turn's retrieved memories.""" + """Record a native subagent and reuse the main turn's retrieved memories.""" session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) agent_id = bounded(hook_input.get("agent_id", "unknown-agent"), 200) - agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200) context = combine_context( format_context(store.injected_memories(session_id, repo.identity)) ) - if not inject_context: - context = "" - first_start = store.start_sidekick( + first_start = store.start_subagent( repo, session_id, agent_id, agent_type, len(context) ) store.record_event( repo, session_id, - "sidekick_start", + "subagent_start", { "agent_id": agent_id, "agent_type": agent_type, "context_chars": len(context) if first_start else 0, - "worktree_root": bounded(repo.root, 2000), + "repo_root": bounded(repo.root, 2000), }, ) telemetry.record( - "sidekick", + "subagent", repo=repo, session_id=session_id, phase="start", @@ -1422,14 +1420,14 @@ def record_sidekick_start( return context if first_start else "" -def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: +def record_subagent_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> None: session_id = _session_id(hook_input) repo = store.repo_for_session(session_id, hook_input.get("cwd")) - agent_type = bounded(hook_input.get("agent_type", "mem0:sidekick"), 200) + agent_type = bounded(hook_input.get("agent_type", "unknown-agent"), 200) agent_id = bounded(hook_input.get("agent_id", ""), 200) final_message = redact(hook_input.get("last_assistant_message", "")).strip() transcript_path = bounded(hook_input.get("agent_transcript_path", ""), 2000) - agent_id = store.stop_sidekick( + agent_id = store.stop_subagent( repo, session_id, agent_id, @@ -1440,7 +1438,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No store.record_event( repo, session_id, - "sidekick_stop", + "subagent_stop", { "agent_id": agent_id, "agent_type": agent_type, @@ -1449,7 +1447,7 @@ def record_sidekick_stop(store: EvidenceStore, hook_input: dict[str, Any]) -> No }, ) telemetry.record( - "sidekick", + "subagent", repo=repo, session_id=session_id, phase="stop", @@ -1513,10 +1511,10 @@ def build_episode( for e in events if e["kind"] == "assistant_stop" and e["payload"].get("text") ] - sidekick_outcomes = [ + subagent_outcomes = [ redact(e["payload"].get("final_message", "")).strip() for e in events - if e["kind"] == "sidekick_stop" and e["payload"].get("final_message") + if e["kind"] in {"subagent_stop", "sidekick_stop"} and e["payload"].get("final_message") ] tools = [ e["payload"] for e in events if e["kind"] in {"tool_result", "tool_failure"} @@ -1597,7 +1595,7 @@ def build_episode( } ) pending_user_messages = [] - elif event["kind"] == "sidekick_stop": + elif event["kind"] in {"subagent_stop", "sidekick_stop"}: pass extraction_messages.extend(pending_user_messages) @@ -1613,7 +1611,7 @@ def build_episode( "assistant_conclusion": conclusion, "user_messages": prompts, "assistant_outcomes": assistant_conclusions, - "sidekick_outcomes": sidekick_outcomes, + "subagent_outcomes": subagent_outcomes, "extraction_messages": extraction_messages, "files_read": read_paths[:50], "files_modified": modified_paths[:50], diff --git a/integrations/openclaw/README.md b/integrations/openclaw/README.md index 0d0224d9b..400e79d4f 100644 --- a/integrations/openclaw/README.md +++ b/integrations/openclaw/README.md @@ -2,12 +2,14 @@ Long-term memory for [OpenClaw](https://github.com/openclaw/openclaw) agents, powered by [Mem0](https://mem0.ai). -Your agent forgets everything between sessions. This plugin fixes that — it stores conversations, extracts what matters, and brings it back when relevant. +Your agent forgets everything between sessions. This plugin stores conversations and recalls relevant memories. By default, the plugin runs in **skills mode**: the agent controls what to remember (triage) and how to recall (recall). Skills mode, `autoRecall`, and `autoCapture` are all enabled by default during `openclaw mem0 init`. Current package version: `1.1.0`. Shared redaction and lifecycle utilities come from [agent-plugin-core](../agent-plugin-core/README.md); OpenClaw keeps its own tools, skills, and memory scopes. +Sidekick is available only in the [Claude Code plugin](../claude-code-plugin/README.md#sonnet-sidekick-agent). + ## Requirements Check your OpenClaw version: @@ -29,7 +31,7 @@ If you're an AI agent setting up Mem0 autonomously (no human dashboard signup), mem0 init --agent --json ``` -No email, no OTP, no browser. The key is written to your Mem0 CLI config and exported as `MEM0_API_KEY` — pass it to `openclaw mem0 init --api-key $MEM0_API_KEY --user-id ` to wire OpenClaw up immediately. The human owner can later run `mem0 init --email ` to claim ownership: memories transfer, same API key keeps working, no agent disruption. +No email, no OTP, no browser. The key is written to your Mem0 CLI config and exported as `MEM0_API_KEY`. Pass it to `openclaw mem0 init --api-key $MEM0_API_KEY --user-id ` to wire OpenClaw up immediately. The human owner can later run `mem0 init --email ` to claim ownership: memories transfer, same API key keeps working, no agent disruption. Humans should follow the Quick Start below. @@ -95,9 +97,9 @@ openclaw plugins update openclaw-mem0 ### Open-Source (Self-hosted) -No Mem0 key needed. Vectors are stored locally in SQLite at `~/.mem0/vector_store.db` — no external database required. +No Mem0 key needed. Vectors are stored locally in SQLite at `~/.mem0/vector_store.db`. No external database is required. -Defaults: `text-embedding-3-small` (OpenAI) for embeddings, `gpt-5-mini` (OpenAI) for fact extraction — requires `OPENAI_API_KEY`. For a fully local setup, use Ollama for both LLM and embeddings. +Defaults: `text-embedding-3-small` (OpenAI) for embeddings, `gpt-5-mini` (OpenAI) for fact extraction. Both require `OPENAI_API_KEY`. For a fully local setup, use Ollama for both LLM and embeddings. #### Interactive Setup (Recommended) @@ -108,16 +110,16 @@ openclaw mem0 init --mode open-source ``` The wizard walks you through: -1. **LLM provider** — OpenAI (`gpt-5-mini`), Ollama (`llama3.1:8b`, local), or Anthropic (`claude-sonnet-4-5-20250514`) -2. **Embedding provider** — OpenAI (`text-embedding-3-small`) or Ollama (`nomic-embed-text`, local) -3. **Vector store** — Qdrant (`http://localhost:6333`) or PGVector (PostgreSQL) -4. **User ID** — your memory namespace identifier +1. **LLM provider**: OpenAI (`gpt-5-mini`), Ollama (`llama3.1:8b`, local), or Anthropic (`claude-sonnet-4-5-20250514`) +2. **Embedding provider**: OpenAI (`text-embedding-3-small`) or Ollama (`nomic-embed-text`, local) +3. **Vector store**: Qdrant (`http://localhost:6333`) or PGVector (PostgreSQL) +4. **User ID**: your memory namespace identifier Each step tests connectivity (Ollama, Qdrant, PGVector) before proceeding. #### Non-Interactive Setup -For CI/CD, scripts, or agent-driven setup — pass all options as flags: +For automated setup, pass all options as flags: ```bash # Fully local with Ollama + Qdrant @@ -166,7 +168,7 @@ openclaw mem0 init --mode open-source --oss-llm ollama --oss-embedder ollama --o #### Manual Config -Minimal config — uses OpenAI defaults: +Minimal config using OpenAI defaults: ```json5 { @@ -213,8 +215,8 @@ All `oss` fields are optional. See the [Mem0 OSS docs](https://docs.mem0.ai/open Enabled automatically during `openclaw mem0 init`. The agent controls memory through two skills: -- **Triage** — Extracts durable facts from conversations using a structured protocol. Categories, importance gates, and domain overlays control what gets stored. -- **Recall** — Before each turn, rewrites the user message into search queries, retrieves relevant memories with reranking, and injects them into context. +- **Triage**: Extracts durable facts from conversations using a structured protocol. Categories, importance gates, and domain overlays control what gets stored. +- **Recall**: Before each turn, rewrites the user message into search queries, retrieves relevant memories with reranking, and injects them into context. When skills mode is active, the skills handle memory operations. `autoRecall` and `autoCapture` remain `true` by default alongside skills mode. The built-in `session-memory` hook is disabled to avoid conflicts. @@ -222,8 +224,8 @@ When skills mode is active, the skills handle memory operations. `autoRecall` an The plugin also registers `autoRecall` and `autoCapture` when their flags are enabled (both default to `true`), including alongside skills mode: -- **Auto-Recall** — Before the agent responds, the plugin searches Mem0 for relevant memories and injects them into context. -- **Auto-Capture** — After the agent responds, the conversation is filtered through a noise-removal pipeline and sent to Mem0. New facts get stored, stale ones updated, duplicates merged. +- **Auto-Recall**: Before the agent responds, the plugin searches Mem0 for relevant memories and injects them into context. +- **Auto-Capture**: After the agent responds, the conversation is filtered through a noise-removal pipeline and sent to Mem0. New facts get stored, stale ones updated, duplicates merged. Automatic capture selects a recent-message window and earlier assistant summaries, removes injected context and noise, and redacts secrets. Selected message text is no longer cut off at 2,000 characters. This preserves full redacted text for selected messages, not every message in the session. Capture skips non-interactive triggers, subagent sessions, and turns that already used memory mutation tools. @@ -231,8 +233,8 @@ Set `autoRecall: false` or `autoCapture: false` to disable these automatic hooks ### Memory Scopes -- **Session (short-term)** — Scoped to the current conversation via `run_id`. Recalled alongside long-term memories. -- **User (long-term)** — Persistent across all sessions. Default for `memory_add`. +- **Session (short-term)**: Scoped to the current conversation via `run_id`. Recalled alongside long-term memories. +- **User (long-term)**: Persistent across all sessions. Default for `memory_add`. ### Multi-Agent Isolation @@ -320,7 +322,7 @@ Enabled by default during `openclaw mem0 init`. `autoRecall` and `autoCapture` a | Key | Type | Default | Description | | --- | ---- | ------- | ----------- | -| `apiKey` | `string` | — | **Required.** Mem0 API key (supports `${MEM0_API_KEY}`) | +| `apiKey` | `string` | Not set | **Required.** Mem0 API key (supports `${MEM0_API_KEY}`) | | `customInstructions` | `string` | *(built-in)* | Custom extraction rules | | `customCategories` | `object` | *(12 defaults)* | Category name to description map | @@ -332,12 +334,12 @@ All fields optional. Defaults: `text-embedding-3-small` embeddings, local SQLite | --- | ---- | ------- | ----------- | | `customPrompt` | `string` | *(built-in)* | Extraction prompt | | `oss.embedder.provider` | `string` | `"openai"` | Embedding provider | -| `oss.embedder.config` | `object` | — | Provider config (`apiKey`, `model`, `baseURL`) | +| `oss.embedder.config` | `object` | Not set | Provider config (`apiKey`, `model`, `baseURL`) | | `oss.vectorStore.provider` | `string` | `"memory"` | Vector store provider (see list above) | -| `oss.vectorStore.config` | `object` | — | Provider config (`host`, `port`, `collectionName`, `dbPath`) | +| `oss.vectorStore.config` | `object` | Not set | Provider config (`host`, `port`, `collectionName`, `dbPath`) | | `oss.llm.provider` | `string` | `"openai"` | LLM provider | -| `oss.llm.config` | `object` | — | Provider config (`apiKey`, `model`, `baseURL`) | -| `oss.historyDbPath` | `string` | — | SQLite path for edit history | +| `oss.llm.config` | `object` | Not set | Provider config (`apiKey`, `model`, `baseURL`) | +| `oss.historyDbPath` | `string` | Not set | SQLite path for edit history | ## Privacy & Security @@ -347,7 +349,7 @@ All fields optional. Defaults: `text-embedding-3-small` embeddings, local SQLite |------|----------------|-------------------| | **Platform** | Conversations sent to `api.mem0.ai` for memory extraction and retrieval | `MEM0_API_KEY` | | **Open-Source (OpenAI)** | LLM/embedding calls to OpenAI API; vectors stored locally at `~/.mem0/vector_store.db` | `OPENAI_API_KEY` | -| **Open-Source (Ollama)** | Fully local — LLM, embeddings, and vectors all on your machine | None | +| **Open-Source (Ollama)** | LLM, embeddings, and vectors run locally | None | ### Credential Storage diff --git a/integrations/opencode-plugin/README.md b/integrations/opencode-plugin/README.md index 296877c23..b66eb4464 100644 --- a/integrations/opencode-plugin/README.md +++ b/integrations/opencode-plugin/README.md @@ -4,15 +4,17 @@ Persistent memory for [OpenCode](https://opencode.ai). Your agent remembers deci Current package version: `0.3.0`. This native TypeScript integration keeps its own tools and scopes while sharing redaction and lifecycle utilities with [agent-plugin-core](../agent-plugin-core/README.md). +Sidekick is available only in the [Claude Code plugin](../claude-code-plugin/README.md#sonnet-sidekick-agent). + ## Install ```bash opencode plugin @mem0/opencode-plugin ``` -This adds the plugin to your `~/.config/opencode/opencode.json`. The plugin registers its memory tools and skills itself — there is no MCP server to configure. +This adds the plugin to your `~/.config/opencode/opencode.json`. The plugin registers its memory tools and skills. No MCP server configuration is needed. -**Or let your agent do it** — paste this into OpenCode: +**Or let your agent do it**: paste this into OpenCode: ``` Install @mem0/opencode-plugin by following https://raw.githubusercontent.com/mem0ai/mem0/main/integrations/opencode-plugin/README.md @@ -30,17 +32,17 @@ Restart OpenCode. | Component | Description | |-----------|-------------| -| **10 Native Memory Tools** | `add_memory`, `search_memories`, `get_memories`, `update_memory`, `delete_memory`, and more — registered as OpenCode tools, backed by the `mem0ai` SDK (no MCP server required) | +| **10 Native Memory Tools** | `add_memory`, `search_memories`, `get_memories`, `update_memory`, `delete_memory`, and more, backed by the `mem0ai` SDK | | **Lifecycle Hooks** | Auto-search on session start and every prompt, error memory lookup, compaction context, secret redaction | -| **7 Skills** | `/mem0-remember`, `/mem0-tour`, `/mem0-search`, `/mem0-status`, `/mem0-scope`, `/mem0-forget`, `/mem0-context-loader` — discovered in place from the plugin via OpenCode's `skills.paths` | +| **7 Skills** | `/mem0-remember`, `/mem0-tour`, `/mem0-search`, `/mem0-status`, `/mem0-scope`, `/mem0-forget`, `/mem0-context-loader`. Discovered through OpenCode's `skills.paths` | ## Hooks -Pure TypeScript — no Python, no shell scripts. Memory operations are native OpenCode tools backed by the [mem0ai](https://www.npmjs.com/package/mem0ai) SDK directly. +Written in TypeScript. Memory operations are native OpenCode tools backed by the [mem0ai](https://www.npmjs.com/package/mem0ai) SDK directly. | Hook | Event | What it does | |------|-------|-------------| -| **Config** | `config` | Registers the `/mem0-*` slash commands (via `config.command`) and adds the plugin's own `opencode-skills/` dir to OpenCode's `skills.paths` for in-place skill discovery — no copying into `~/.config/opencode/skills` | +| **Config** | `config` | Registers the `/mem0-*` slash commands (via `config.command`) and adds the plugin's own `opencode-skills/` dir to OpenCode's `skills.paths` for skill discovery without copying files | | **Chat message** | `chat.message` | Loads prior memories on session start, searches relevant memories before each prompt, auto-captures learnings periodically | | **Pre-tool** | `tool.execute.before` | Blocks MEMORY.md writes, steering them to the `add_memory` tool | | **Post-tool** | `tool.execute.after` | Scans bash errors and pre-fetches related memories | @@ -81,7 +83,7 @@ scope (used when none is passed) with the `/mem0-scope` skill: ``` The default persists in `~/.mem0/settings.json` (`default_scope`) and is read -fresh on each memory operation, so a change applies immediately — no restart. +fresh on each memory operation, so changes apply without a restart. `delete_all_memories` always requires an explicit `scope="global"` to delete user-wide, so changing the default can't trigger a cross-project wipe. diff --git a/integrations/pi-agent-plugin/README.md b/integrations/pi-agent-plugin/README.md index 3b343fcdb..cb28d2314 100644 --- a/integrations/pi-agent-plugin/README.md +++ b/integrations/pi-agent-plugin/README.md @@ -6,15 +6,17 @@ This extension gives Pi Agent long-term memory that persists across sessions, pr Current package version: `0.3.0`. Shared redaction and lifecycle utilities come from [agent-plugin-core](../agent-plugin-core/README.md); Pi keeps its own tools and scopes. +Sidekick is available only in the [Claude Code plugin](../claude-code-plugin/README.md#sonnet-sidekick-agent). + ## Features -- **Automatic memory capture** — learns from every conversation (both user and assistant messages) -- **Semantic search** — find memories by meaning, not just keywords -- **Scoped memory** — project, session, or global scope -- **Monorepo-aware** — uses git root for project detection, consistent app_id across subdirectories -- **Confirmation dialogs** — destructive commands ask before acting -- **6 slash commands** — essential memory management from the command line -- **Agent tool** — `mem0_memory` tool lets the agent search and store memories autonomously +- **Automatic memory capture**: learns from every conversation (both user and assistant messages) +- **Semantic search**: find memories by meaning, not just keywords +- **Scoped memory**: project, session, or global scope +- **Monorepo-aware**: uses git root for project detection, consistent app_id across subdirectories +- **Confirmation dialogs**: destructive commands ask before acting +- **6 slash commands**: essential memory management from the command line +- **Agent tool**: `mem0_memory` tool lets the agent search and store memories autonomously ## Setup From c7ee362aff94a369af70f13f2b4f853f6793ff4c Mon Sep 17 00:00:00 2001 From: Harsh Vardhan Gupta Date: Fri, 11 Sep 2026 16:07:57 +0530 Subject: [PATCH 06/61] fix(security): resolve 12 Vanta/Dependabot vulnerabilities across 6 pnpm workspaces + poetry.lock (#7280) Co-authored-by: kartik-mem0 --- cli/node/package.json | 2 +- cli/node/pnpm-lock.yaml | 92 +++++++------- integrations/openclaw/package.json | 4 +- integrations/openclaw/pnpm-lock.yaml | 112 +++++++++--------- integrations/pi-agent-plugin/package.json | 2 +- integrations/pi-agent-plugin/pnpm-lock.yaml | 92 +++++++------- integrations/vercel-ai-sdk/package.json | 3 +- integrations/vercel-ai-sdk/pnpm-lock.yaml | 53 +++++---- .../vercel-ai-sdk/pnpm-workspace.yaml | 1 + mem0-ts/package.json | 4 +- mem0-ts/pnpm-lock.yaml | 73 ++++++------ mem0-ts/pnpm-workspace.yaml | 2 + poetry.lock | 20 +++- server/dashboard/pnpm-lock.yaml | 52 ++++---- server/dashboard/pnpm-workspace.yaml | 1 + 15 files changed, 271 insertions(+), 242 deletions(-) diff --git a/cli/node/package.json b/cli/node/package.json index 0fefe0039..d078066e2 100644 --- a/cli/node/package.json +++ b/cli/node/package.json @@ -41,7 +41,7 @@ "tsup": "^8.0.0", "tsx": "^4.7.0", "vite": "^6.0.0", - "vitest": "^4.1.0", + "vitest": "^4.1.11", "@biomejs/biome": "^1.7.0", "@types/node": "^20.0.0" }, diff --git a/cli/node/pnpm-lock.yaml b/cli/node/pnpm-lock.yaml index 390560cd1..968075cc7 100644 --- a/cli/node/pnpm-lock.yaml +++ b/cli/node/pnpm-lock.yaml @@ -51,8 +51,8 @@ importers: specifier: ^6.0.0 version: 6.4.3(@types/node@20.19.37)(tsx@4.21.0) vitest: - specifier: ^4.1.0 - version: 4.1.8(@types/node@20.19.37)(vite@6.4.3(@types/node@20.19.37)(tsx@4.21.0)) + 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)) packages: @@ -439,11 +439,11 @@ packages: '@types/node@20.19.37': resolution: {integrity: sha512-8kzdPJ3FsNsVIurqBs7oodNnCEVbni9yUEkaHbgptDACOPW04jimGagZ51E6+lXUwJjgnBw+hyko/lkFWCldqw==} - '@vitest/expect@4.1.8': - resolution: {integrity: sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ==} + '@vitest/expect@4.1.11': + resolution: {integrity: sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==} - '@vitest/mocker@4.1.8': - resolution: {integrity: sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw==} + '@vitest/mocker@4.1.11': + resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==} peerDependencies: msw: ^2.4.9 vite: ^6.0.0 || ^7.0.0 || ^8.0.0 @@ -453,20 +453,20 @@ packages: vite: optional: true - '@vitest/pretty-format@4.1.8': - resolution: {integrity: sha512-9GasEBxpZ1VYIpqHf/0+YGg121uSNwCKOJqIrTwWP/TB7DmFCiaBpNl3aPZzoLWfWkuqhbH8vJIVobZkvdo2cA==} + '@vitest/pretty-format@4.1.11': + resolution: {integrity: sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==} - '@vitest/runner@4.1.8': - resolution: {integrity: sha512-EmVxeBAfMJvycdjd6Hm+RbFBbA9fKvo0Kx37hNpBYoYeavH3RNsBXWDooR1mgD52dCrxIIuP7UotpfiwOikvcg==} + '@vitest/runner@4.1.11': + resolution: {integrity: sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==} - '@vitest/snapshot@4.1.8': - resolution: {integrity: sha512-acfZboRmAIf05DEKcBQy33VXojFJjtUdLyo7oOmV9kebb2xdU01UknNiPuPZoJZQyO7DF0gZdTGTpeAzET9QPQ==} + '@vitest/snapshot@4.1.11': + resolution: {integrity: sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==} - '@vitest/spy@4.1.8': - resolution: {integrity: sha512-6EevtBp6OZOPF7bmz36HrGMeP3txgVSrgebWxHOafDXGkhIzfXK14f8KF6MuFfgXXUeHxmpD3BQxkV00/3s5mA==} + '@vitest/spy@4.1.11': + resolution: {integrity: sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==} - '@vitest/utils@4.1.8': - resolution: {integrity: sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg==} + '@vitest/utils@4.1.11': + resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==} acorn@8.16.0: resolution: {integrity: sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==} @@ -910,20 +910,20 @@ packages: yaml: optional: true - vitest@4.1.8: - resolution: {integrity: sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==} + vitest@4.1.11: + resolution: {integrity: sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==} engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} hasBin: true peerDependencies: '@edge-runtime/vm': '*' '@opentelemetry/api': ^1.9.0 '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 - '@vitest/browser-playwright': 4.1.8 - '@vitest/browser-preview': 4.1.8 - '@vitest/browser-webdriverio': 4.1.8 - '@vitest/coverage-istanbul': 4.1.8 - '@vitest/coverage-v8': 4.1.8 - '@vitest/ui': 4.1.8 + '@vitest/browser-playwright': 4.1.11 + '@vitest/browser-preview': 4.1.11 + '@vitest/browser-webdriverio': 4.1.11 + '@vitest/coverage-istanbul': 4.1.11 + '@vitest/coverage-v8': 4.1.11 + '@vitest/ui': 4.1.11 happy-dom: '*' jsdom: '*' vite: ^6.0.0 || ^7.0.0 || ^8.0.0 @@ -1186,44 +1186,44 @@ snapshots: dependencies: undici-types: 6.21.0 - '@vitest/expect@4.1.8': + '@vitest/expect@4.1.11': dependencies: '@standard-schema/spec': 1.1.0 '@types/chai': 5.2.3 - '@vitest/spy': 4.1.8 - '@vitest/utils': 4.1.8 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.8(vite@6.4.3(@types/node@20.19.37)(tsx@4.21.0))': + '@vitest/mocker@4.1.11(vite@6.4.3(@types/node@20.19.37)(tsx@4.21.0))': dependencies: - '@vitest/spy': 4.1.8 + '@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) - '@vitest/pretty-format@4.1.8': + '@vitest/pretty-format@4.1.11': dependencies: tinyrainbow: 3.1.0 - '@vitest/runner@4.1.8': + '@vitest/runner@4.1.11': dependencies: - '@vitest/utils': 4.1.8 + '@vitest/utils': 4.1.11 pathe: 2.0.3 - '@vitest/snapshot@4.1.8': + '@vitest/snapshot@4.1.11': dependencies: - '@vitest/pretty-format': 4.1.8 - '@vitest/utils': 4.1.8 + '@vitest/pretty-format': 4.1.11 + '@vitest/utils': 4.1.11 magic-string: 0.30.21 pathe: 2.0.3 - '@vitest/spy@4.1.8': {} + '@vitest/spy@4.1.11': {} - '@vitest/utils@4.1.8': + '@vitest/utils@4.1.11': dependencies: - '@vitest/pretty-format': 4.1.8 + '@vitest/pretty-format': 4.1.11 convert-source-map: 2.0.0 tinyrainbow: 3.1.0 @@ -1627,15 +1627,15 @@ snapshots: fsevents: 2.3.3 tsx: 4.21.0 - vitest@4.1.8(@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.3(@types/node@20.19.37)(tsx@4.21.0)): dependencies: - '@vitest/expect': 4.1.8 - '@vitest/mocker': 4.1.8(vite@6.4.3(@types/node@20.19.37)(tsx@4.21.0)) - '@vitest/pretty-format': 4.1.8 - '@vitest/runner': 4.1.8 - '@vitest/snapshot': 4.1.8 - '@vitest/spy': 4.1.8 - '@vitest/utils': 4.1.8 + '@vitest/expect': 4.1.11 + '@vitest/mocker': 4.1.11(vite@6.4.3(@types/node@20.19.37)(tsx@4.21.0)) + '@vitest/pretty-format': 4.1.11 + '@vitest/runner': 4.1.11 + '@vitest/snapshot': 4.1.11 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 es-module-lexer: 2.1.0 expect-type: 1.3.0 magic-string: 0.30.21 diff --git a/integrations/openclaw/package.json b/integrations/openclaw/package.json index 6ea5a0aab..03938e4da 100644 --- a/integrations/openclaw/package.json +++ b/integrations/openclaw/package.json @@ -56,11 +56,11 @@ "devDependencies": { "@qdrant/js-client-rest": "^1.18.0", "@types/node": "^22.15.0", - "@vitest/coverage-v8": "^4.1.7", + "@vitest/coverage-v8": "^4.1.11", "tsup": "^8.5.0", "typescript": "^5.8.3", "vite": "^8.0.5", - "vitest": "^4.1.7" + "vitest": "^4.1.11" }, "pnpm": { "overrides": { diff --git a/integrations/openclaw/pnpm-lock.yaml b/integrations/openclaw/pnpm-lock.yaml index f0d26cfa7..79dd0d10a 100644 --- a/integrations/openclaw/pnpm-lock.yaml +++ b/integrations/openclaw/pnpm-lock.yaml @@ -36,8 +36,8 @@ importers: specifier: ^22.15.0 version: 22.19.20 '@vitest/coverage-v8': - specifier: ^4.1.7 - version: 4.1.8(vitest@4.1.8) + specifier: ^4.1.11 + 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) @@ -48,8 +48,8 @@ importers: specifier: ^8.0.5 version: 8.0.16(@types/node@22.19.20)(esbuild@0.28.1) vitest: - specifier: ^4.1.7 - version: 4.1.8(@types/node@22.19.20)(@vitest/coverage-v8@4.1.8)(vite@8.0.16(@types/node@22.19.20)(esbuild@0.28.1)) + 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)) packages: @@ -767,20 +767,20 @@ packages: resolution: {integrity: sha512-jIXhD0eWQ1JA6ln/5Dltyx22UxWNrw0hZmhy2rlv6m6KgF7kplHx3g0fzi09lNmTJQRR91OlemYp3xFnvDK9og==} engines: {node: '>=20.0.0'} - '@vitest/coverage-v8@4.1.8': - resolution: {integrity: sha512-lt3kovsyHwYe00wq4D1ti0Z974fWj4NLp6siqiyEufUpyFwK9Yhi7rBhac9JL5aA0zoMrJqc4vYPZRUnI7l7nw==} + '@vitest/coverage-v8@4.1.11': + resolution: {integrity: sha512-8MVGEFnJIcdGjcbfKmeq8z0pZHH0JlVtoVZH9Q/qwUp6wyFnEJUBMrw9DCaj+ra3vShGmhavjalMIhPNxZAUcw==} peerDependencies: - '@vitest/browser': 4.1.8 - vitest: 4.1.8 + '@vitest/browser': 4.1.11 + vitest: 4.1.11 peerDependenciesMeta: '@vitest/browser': optional: true - '@vitest/expect@4.1.8': - resolution: {integrity: sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ==} + '@vitest/expect@4.1.11': + resolution: {integrity: sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==} - '@vitest/mocker@4.1.8': - resolution: {integrity: sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw==} + '@vitest/mocker@4.1.11': + resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==} peerDependencies: msw: ^2.4.9 vite: ^8.0.5 @@ -790,20 +790,20 @@ packages: vite: optional: true - '@vitest/pretty-format@4.1.8': - resolution: {integrity: sha512-9GasEBxpZ1VYIpqHf/0+YGg121uSNwCKOJqIrTwWP/TB7DmFCiaBpNl3aPZzoLWfWkuqhbH8vJIVobZkvdo2cA==} + '@vitest/pretty-format@4.1.11': + resolution: {integrity: sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==} - '@vitest/runner@4.1.8': - resolution: {integrity: sha512-EmVxeBAfMJvycdjd6Hm+RbFBbA9fKvo0Kx37hNpBYoYeavH3RNsBXWDooR1mgD52dCrxIIuP7UotpfiwOikvcg==} + '@vitest/runner@4.1.11': + resolution: {integrity: sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==} - '@vitest/snapshot@4.1.8': - resolution: {integrity: sha512-acfZboRmAIf05DEKcBQy33VXojFJjtUdLyo7oOmV9kebb2xdU01UknNiPuPZoJZQyO7DF0gZdTGTpeAzET9QPQ==} + '@vitest/snapshot@4.1.11': + resolution: {integrity: sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==} - '@vitest/spy@4.1.8': - resolution: {integrity: sha512-6EevtBp6OZOPF7bmz36HrGMeP3txgVSrgebWxHOafDXGkhIzfXK14f8KF6MuFfgXXUeHxmpD3BQxkV00/3s5mA==} + '@vitest/spy@4.1.11': + resolution: {integrity: sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==} - '@vitest/utils@4.1.8': - resolution: {integrity: sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg==} + '@vitest/utils@4.1.11': + resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==} abort-controller@3.0.0: resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==} @@ -2094,20 +2094,20 @@ packages: yaml: optional: true - vitest@4.1.8: - resolution: {integrity: sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==} + vitest@4.1.11: + resolution: {integrity: sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==} engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} hasBin: true peerDependencies: '@edge-runtime/vm': '*' '@opentelemetry/api': ^1.9.0 '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 - '@vitest/browser-playwright': 4.1.8 - '@vitest/browser-preview': 4.1.8 - '@vitest/browser-webdriverio': 4.1.8 - '@vitest/coverage-istanbul': 4.1.8 - '@vitest/coverage-v8': 4.1.8 - '@vitest/ui': 4.1.8 + '@vitest/browser-playwright': 4.1.11 + '@vitest/browser-preview': 4.1.11 + '@vitest/browser-webdriverio': 4.1.11 + '@vitest/coverage-istanbul': 4.1.11 + '@vitest/coverage-v8': 4.1.11 + '@vitest/ui': 4.1.11 happy-dom: '*' jsdom: '*' vite: ^8.0.5 @@ -2807,10 +2807,10 @@ snapshots: transitivePeerDependencies: - supports-color - '@vitest/coverage-v8@4.1.8(vitest@4.1.8)': + '@vitest/coverage-v8@4.1.11(vitest@4.1.11)': dependencies: '@bcoe/v8-coverage': 1.0.2 - '@vitest/utils': 4.1.8 + '@vitest/utils': 4.1.11 ast-v8-to-istanbul: 1.0.3 istanbul-lib-coverage: 3.2.2 istanbul-lib-report: 3.0.1 @@ -2819,46 +2819,46 @@ snapshots: obug: 2.1.2 std-env: 4.1.0 tinyrainbow: 3.1.0 - vitest: 4.1.8(@types/node@22.19.20)(@vitest/coverage-v8@4.1.8)(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.0.16(@types/node@22.19.20)(esbuild@0.28.1)) - '@vitest/expect@4.1.8': + '@vitest/expect@4.1.11': dependencies: '@standard-schema/spec': 1.1.0 '@types/chai': 5.2.3 - '@vitest/spy': 4.1.8 - '@vitest/utils': 4.1.8 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.8(vite@8.0.16(@types/node@22.19.20)(esbuild@0.28.1))': + '@vitest/mocker@4.1.11(vite@8.0.16(@types/node@22.19.20)(esbuild@0.28.1))': dependencies: - '@vitest/spy': 4.1.8 + '@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) - '@vitest/pretty-format@4.1.8': + '@vitest/pretty-format@4.1.11': dependencies: tinyrainbow: 3.1.0 - '@vitest/runner@4.1.8': + '@vitest/runner@4.1.11': dependencies: - '@vitest/utils': 4.1.8 + '@vitest/utils': 4.1.11 pathe: 2.0.3 - '@vitest/snapshot@4.1.8': + '@vitest/snapshot@4.1.11': dependencies: - '@vitest/pretty-format': 4.1.8 - '@vitest/utils': 4.1.8 + '@vitest/pretty-format': 4.1.11 + '@vitest/utils': 4.1.11 magic-string: 0.30.21 pathe: 2.0.3 - '@vitest/spy@4.1.8': {} + '@vitest/spy@4.1.11': {} - '@vitest/utils@4.1.8': + '@vitest/utils@4.1.11': dependencies: - '@vitest/pretty-format': 4.1.8 + '@vitest/pretty-format': 4.1.11 convert-source-map: 2.0.0 tinyrainbow: 3.1.0 @@ -4141,15 +4141,15 @@ snapshots: esbuild: 0.28.1 fsevents: 2.3.3 - vitest@4.1.8(@types/node@22.19.20)(@vitest/coverage-v8@4.1.8)(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.0.16(@types/node@22.19.20)(esbuild@0.28.1)): dependencies: - '@vitest/expect': 4.1.8 - '@vitest/mocker': 4.1.8(vite@8.0.16(@types/node@22.19.20)(esbuild@0.28.1)) - '@vitest/pretty-format': 4.1.8 - '@vitest/runner': 4.1.8 - '@vitest/snapshot': 4.1.8 - '@vitest/spy': 4.1.8 - '@vitest/utils': 4.1.8 + '@vitest/expect': 4.1.11 + '@vitest/mocker': 4.1.11(vite@8.0.16(@types/node@22.19.20)(esbuild@0.28.1)) + '@vitest/pretty-format': 4.1.11 + '@vitest/runner': 4.1.11 + '@vitest/snapshot': 4.1.11 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 es-module-lexer: 2.1.0 expect-type: 1.3.0 magic-string: 0.30.21 @@ -4165,7 +4165,7 @@ snapshots: why-is-node-running: 2.3.0 optionalDependencies: '@types/node': 22.19.20 - '@vitest/coverage-v8': 4.1.8(vitest@4.1.8) + '@vitest/coverage-v8': 4.1.11(vitest@4.1.11) transitivePeerDependencies: - msw diff --git a/integrations/pi-agent-plugin/package.json b/integrations/pi-agent-plugin/package.json index d9b3f7d2e..d05673406 100644 --- a/integrations/pi-agent-plugin/package.json +++ b/integrations/pi-agent-plugin/package.json @@ -62,7 +62,7 @@ "tsup": "^8.5.0", "typebox": "^1.2.3", "typescript": "^6.0.3", - "vitest": "^4.1.7" + "vitest": "^4.1.11" }, "dependencies": { "mem0ai": "^3.0.7" diff --git a/integrations/pi-agent-plugin/pnpm-lock.yaml b/integrations/pi-agent-plugin/pnpm-lock.yaml index 87a5d4004..177023505 100644 --- a/integrations/pi-agent-plugin/pnpm-lock.yaml +++ b/integrations/pi-agent-plugin/pnpm-lock.yaml @@ -43,8 +43,8 @@ importers: specifier: ^6.0.3 version: 6.0.3 vitest: - specifier: ^4.1.7 - version: 4.1.8(@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)) + 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)) packages: @@ -985,11 +985,11 @@ packages: resolution: {integrity: sha512-jIXhD0eWQ1JA6ln/5Dltyx22UxWNrw0hZmhy2rlv6m6KgF7kplHx3g0fzi09lNmTJQRR91OlemYp3xFnvDK9og==} engines: {node: '>=20.0.0'} - '@vitest/expect@4.1.8': - resolution: {integrity: sha512-h3nDO677RDLEGlBxyQ5CW8RlMThSKSRLUePLOx09gNIWRL40edgA1GCZSZgf1W55MFAG6/Sw14KeaAnqv0NKdQ==} + '@vitest/expect@4.1.11': + resolution: {integrity: sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==} - '@vitest/mocker@4.1.8': - resolution: {integrity: sha512-LEiN/xe4OSIbKe9HQIp5OC24agGD9J5CnmMgsLohVVoOPWL9a2sBoR6VBx43jQZb7Kr1l4RCuyCJzcAa0+dojw==} + '@vitest/mocker@4.1.11': + resolution: {integrity: sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==} peerDependencies: msw: ^2.4.9 vite: ^6.0.0 || ^7.0.0 || ^8.0.0 @@ -999,20 +999,20 @@ packages: vite: optional: true - '@vitest/pretty-format@4.1.8': - resolution: {integrity: sha512-9GasEBxpZ1VYIpqHf/0+YGg121uSNwCKOJqIrTwWP/TB7DmFCiaBpNl3aPZzoLWfWkuqhbH8vJIVobZkvdo2cA==} + '@vitest/pretty-format@4.1.11': + resolution: {integrity: sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==} - '@vitest/runner@4.1.8': - resolution: {integrity: sha512-EmVxeBAfMJvycdjd6Hm+RbFBbA9fKvo0Kx37hNpBYoYeavH3RNsBXWDooR1mgD52dCrxIIuP7UotpfiwOikvcg==} + '@vitest/runner@4.1.11': + resolution: {integrity: sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==} - '@vitest/snapshot@4.1.8': - resolution: {integrity: sha512-acfZboRmAIf05DEKcBQy33VXojFJjtUdLyo7oOmV9kebb2xdU01UknNiPuPZoJZQyO7DF0gZdTGTpeAzET9QPQ==} + '@vitest/snapshot@4.1.11': + resolution: {integrity: sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==} - '@vitest/spy@4.1.8': - resolution: {integrity: sha512-6EevtBp6OZOPF7bmz36HrGMeP3txgVSrgebWxHOafDXGkhIzfXK14f8KF6MuFfgXXUeHxmpD3BQxkV00/3s5mA==} + '@vitest/spy@4.1.11': + resolution: {integrity: sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==} - '@vitest/utils@4.1.8': - resolution: {integrity: sha512-uOJamYALNhfJ6iolExyQM40yIQwDqYnkKtQ5VCiSe17E33H0aQ/u+1GlRuz4LZBk6Mm3sg90G9hEbmEt37C1Zg==} + '@vitest/utils@4.1.11': + resolution: {integrity: sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==} abort-controller@3.0.0: resolution: {integrity: sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==} @@ -2416,20 +2416,20 @@ packages: yaml: optional: true - vitest@4.1.8: - resolution: {integrity: sha512-flY6ScbCIt9HThs+C5HS7jvGOB560DJtk/Z15IQROTA6zEy49Nh8T/dofWTQL+n3vswqn87sbJNiuqw1SDp5Ig==} + vitest@4.1.11: + resolution: {integrity: sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==} engines: {node: ^20.0.0 || ^22.0.0 || >=24.0.0} hasBin: true peerDependencies: '@edge-runtime/vm': '*' '@opentelemetry/api': ^1.9.0 '@types/node': ^20.0.0 || ^22.0.0 || >=24.0.0 - '@vitest/browser-playwright': 4.1.8 - '@vitest/browser-preview': 4.1.8 - '@vitest/browser-webdriverio': 4.1.8 - '@vitest/coverage-istanbul': 4.1.8 - '@vitest/coverage-v8': 4.1.8 - '@vitest/ui': 4.1.8 + '@vitest/browser-playwright': 4.1.11 + '@vitest/browser-preview': 4.1.11 + '@vitest/browser-webdriverio': 4.1.11 + '@vitest/coverage-istanbul': 4.1.11 + '@vitest/coverage-v8': 4.1.11 + '@vitest/ui': 4.1.11 happy-dom: '*' jsdom: '*' vite: ^6.0.0 || ^7.0.0 || ^8.0.0 @@ -3517,44 +3517,44 @@ snapshots: transitivePeerDependencies: - supports-color - '@vitest/expect@4.1.8': + '@vitest/expect@4.1.11': dependencies: '@standard-schema/spec': 1.1.0 '@types/chai': 5.2.3 - '@vitest/spy': 4.1.8 - '@vitest/utils': 4.1.8 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 chai: 6.2.2 tinyrainbow: 3.1.0 - '@vitest/mocker@4.1.8(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.0.16(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0))': dependencies: - '@vitest/spy': 4.1.8 + '@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) - '@vitest/pretty-format@4.1.8': + '@vitest/pretty-format@4.1.11': dependencies: tinyrainbow: 3.1.0 - '@vitest/runner@4.1.8': + '@vitest/runner@4.1.11': dependencies: - '@vitest/utils': 4.1.8 + '@vitest/utils': 4.1.11 pathe: 2.0.3 - '@vitest/snapshot@4.1.8': + '@vitest/snapshot@4.1.11': dependencies: - '@vitest/pretty-format': 4.1.8 - '@vitest/utils': 4.1.8 + '@vitest/pretty-format': 4.1.11 + '@vitest/utils': 4.1.11 magic-string: 0.30.21 pathe: 2.0.3 - '@vitest/spy@4.1.8': {} + '@vitest/spy@4.1.11': {} - '@vitest/utils@4.1.8': + '@vitest/utils@4.1.11': dependencies: - '@vitest/pretty-format': 4.1.8 + '@vitest/pretty-format': 4.1.11 convert-source-map: 2.0.0 tinyrainbow: 3.1.0 @@ -4919,15 +4919,15 @@ snapshots: jiti: 2.7.0 yaml: 2.9.0 - vitest@4.1.8(@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.0.16(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0)): dependencies: - '@vitest/expect': 4.1.8 - '@vitest/mocker': 4.1.8(vite@8.0.16(@types/node@25.9.2)(esbuild@0.28.1)(jiti@2.7.0)(yaml@2.9.0)) - '@vitest/pretty-format': 4.1.8 - '@vitest/runner': 4.1.8 - '@vitest/snapshot': 4.1.8 - '@vitest/spy': 4.1.8 - '@vitest/utils': 4.1.8 + '@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/pretty-format': 4.1.11 + '@vitest/runner': 4.1.11 + '@vitest/snapshot': 4.1.11 + '@vitest/spy': 4.1.11 + '@vitest/utils': 4.1.11 es-module-lexer: 2.1.0 expect-type: 1.3.0 magic-string: 0.30.21 diff --git a/integrations/vercel-ai-sdk/package.json b/integrations/vercel-ai-sdk/package.json index eeaa54266..7b417e460 100644 --- a/integrations/vercel-ai-sdk/package.json +++ b/integrations/vercel-ai-sdk/package.json @@ -89,7 +89,8 @@ "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@>=4.0.0 <4.3.1": ">=4.3.1 <5.0.0", + "browserslist@<4.28.7": ">=4.28.7 <5.0.0" } } } diff --git a/integrations/vercel-ai-sdk/pnpm-lock.yaml b/integrations/vercel-ai-sdk/pnpm-lock.yaml index f33237ad0..f8208a36a 100644 --- a/integrations/vercel-ai-sdk/pnpm-lock.yaml +++ b/integrations/vercel-ai-sdk/pnpm-lock.yaml @@ -16,6 +16,7 @@ overrides: 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' importers: @@ -832,8 +833,8 @@ packages: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} - baseline-browser-mapping@2.10.35: - resolution: {integrity: sha512-honAfLBde0HAFLdNyBEfuuENkF6zR+ozxqxa/2zJKHBe1qzLqyTSeRKpdPEHAP03rlDGyQOPnCSxnVpVqQo9Mg==} + baseline-browser-mapping@2.11.21: + resolution: {integrity: sha512-uh8vpY/1/YyFkunIDFH/12p7/7VdPKA1hejMVEbdkEaWnUz0Hesvx5EbiU6XxjyHZIOju+ZMbQJkRh+es3/spQ==} engines: {node: '>=6.0.0'} hasBin: true @@ -852,8 +853,8 @@ packages: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} - browserslist@4.28.2: - resolution: {integrity: sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==} + browserslist@4.28.9: + resolution: {integrity: sha512-EWazOblFYUvlGZcfGhPUPmYh3nikUxBVb+y9MJun5f3hBi812X+8MSQTujLBtgK3cf51fJWbWfOjyeO954d+Eg==} engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true @@ -889,8 +890,8 @@ packages: resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==} engines: {node: '>=10'} - caniuse-lite@1.0.30001797: - resolution: {integrity: sha512-l8xKG+gwAIExZGl9FrF7KUwuOmk6wbEPC9Xoy/RtnWv1XG0Q4LFlagaLpUv3Kiza3W/wm27zy0yWJEieYKAP6w==} + caniuse-lite@1.0.30001810: + resolution: {integrity: sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==} chalk@4.1.2: resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} @@ -999,8 +1000,8 @@ packages: resolution: {integrity: sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==} engines: {node: '>=12'} - electron-to-chromium@1.5.371: - resolution: {integrity: sha512-e9htk9mAYL6AzmkEhSvVVw7IWGSBJ/Bqdn2eRyRLrj1g6sncN4WbFt5qnILYoCktktr45pyjIrOiRvBThQ808w==} + electron-to-chromium@1.5.426: + resolution: {integrity: sha512-2Gcq6inCQs/AqfHP3f5ftCzk+pqeW2VlA1LgmPqEj2hfBO8HiZRspNYkD4HzFBe4u6lGqca4BspFr6Ix4Q400g==} emittery@0.13.1: resolution: {integrity: sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==} @@ -1456,8 +1457,8 @@ packages: node-int64@0.4.0: resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==} - node-releases@2.0.47: - resolution: {integrity: sha512-Uzmd6LXpouKo8EUK68IjH4+E01w/hXyV3R3g/geCJo+rXLNfh1xucB+LOzYEOQPSiUK3h/xZf0cQGcSsmyL2Og==} + node-releases@2.0.55: + resolution: {integrity: sha512-mIrE/Cw9y+9Au6dS5vDKDhQza9YvG6w+ZrS6X+ZzA7yFW/soAeaups4Qzn1bL6g5FVy8WtP79+0j82oPIbqRjQ==} engines: {node: '>=18'} nodemon@3.1.14: @@ -1837,11 +1838,11 @@ packages: undici-types@5.26.5: resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==} - update-browserslist-db@1.2.3: - resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==} + update-browserslist-db@1.3.2: + resolution: {integrity: sha512-UQ+MSxlhRm1bzjhU+DcuXfjFO1FzNtqhK5+9Yvlp90ItDLk5vT932A0rFu619nf7RVS+Y/VeaUW1jaRDqZ8VJw==} hasBin: true peerDependencies: - browserslist: '>= 4.21.0' + browserslist: '>=4.28.7 <5.0.0' v8-compile-cache-lib@3.0.1: resolution: {integrity: sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==} @@ -1988,7 +1989,7 @@ snapshots: dependencies: '@babel/compat-data': 7.29.7 '@babel/helper-validator-option': 7.29.7 - browserslist: 4.28.2 + browserslist: 4.28.9 lru-cache: 5.1.1 semver: 6.3.1 @@ -2672,7 +2673,7 @@ snapshots: balanced-match@4.0.4: {} - baseline-browser-mapping@2.10.35: {} + baseline-browser-mapping@2.11.21: {} binary-extensions@2.3.0: {} @@ -2689,13 +2690,13 @@ snapshots: dependencies: fill-range: 7.1.1 - browserslist@4.28.2: + browserslist@4.28.9: dependencies: - baseline-browser-mapping: 2.10.35 - caniuse-lite: 1.0.30001797 - electron-to-chromium: 1.5.371 - node-releases: 2.0.47 - update-browserslist-db: 1.2.3(browserslist@4.28.2) + baseline-browser-mapping: 2.11.21 + caniuse-lite: 1.0.30001810 + electron-to-chromium: 1.5.426 + node-releases: 2.0.55 + update-browserslist-db: 1.3.2(browserslist@4.28.9) bs-logger@0.2.6: dependencies: @@ -2720,7 +2721,7 @@ snapshots: camelcase@6.3.0: {} - caniuse-lite@1.0.30001797: {} + caniuse-lite@1.0.30001810: {} chalk@4.1.2: dependencies: @@ -2816,7 +2817,7 @@ snapshots: dotenv@16.6.1: {} - electron-to-chromium@1.5.371: {} + electron-to-chromium@1.5.426: {} emittery@0.13.1: {} @@ -3446,7 +3447,7 @@ snapshots: node-int64@0.4.0: {} - node-releases@2.0.47: {} + node-releases@2.0.55: {} nodemon@3.1.14: dependencies: @@ -3799,9 +3800,9 @@ snapshots: undici-types@5.26.5: {} - update-browserslist-db@1.2.3(browserslist@4.28.2): + update-browserslist-db@1.3.2(browserslist@4.28.9): dependencies: - browserslist: 4.28.2 + browserslist: 4.28.9 escalade: 3.2.0 picocolors: 1.1.1 diff --git a/integrations/vercel-ai-sdk/pnpm-workspace.yaml b/integrations/vercel-ai-sdk/pnpm-workspace.yaml index 6c52679f2..93ff161d8 100644 --- a/integrations/vercel-ai-sdk/pnpm-workspace.yaml +++ b/integrations/vercel-ai-sdk/pnpm-workspace.yaml @@ -17,3 +17,4 @@ overrides: "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" diff --git a/mem0-ts/package.json b/mem0-ts/package.json index 7e41a4ac0..7697b2384 100644 --- a/mem0-ts/package.json +++ b/mem0-ts/package.json @@ -306,7 +306,9 @@ "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.3.1": ">=10.3.1 <11.0.0", + "browserslist@<4.28.7": ">=4.28.7 <5.0.0", + "mysql2@<3.23.1": ">=3.23.1 <4.0.0" } } } diff --git a/mem0-ts/pnpm-lock.yaml b/mem0-ts/pnpm-lock.yaml index 795795d2f..5deb30e7b 100644 --- a/mem0-ts/pnpm-lock.yaml +++ b/mem0-ts/pnpm-lock.yaml @@ -40,6 +40,8 @@ overrides: 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' + browserslist@<4.28.7: '>=4.28.7 <5.0.0' + mysql2@<3.23.1: '>=3.23.1 <4.0.0' patchedDependencies: tar@7.5.22: @@ -150,8 +152,8 @@ importers: specifier: ^7.0.0 version: 7.2.0(socks@2.8.9) mysql2: - specifier: ^3.0.0 - version: 3.22.5(@types/node@22.19.21) + specifier: '>=3.23.1 <4.0.0' + version: 3.24.4(@types/node@22.19.21) natural: specifier: ^8.0.1 version: 8.1.1(@opentelemetry/api@1.9.1)(socks@2.8.9) @@ -2146,8 +2148,8 @@ packages: base64-js@1.5.1: resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} - baseline-browser-mapping@2.10.35: - resolution: {integrity: sha512-honAfLBde0HAFLdNyBEfuuENkF6zR+ozxqxa/2zJKHBe1qzLqyTSeRKpdPEHAP03rlDGyQOPnCSxnVpVqQo9Mg==} + baseline-browser-mapping@2.11.21: + resolution: {integrity: sha512-uh8vpY/1/YyFkunIDFH/12p7/7VdPKA1hejMVEbdkEaWnUz0Hesvx5EbiU6XxjyHZIOju+ZMbQJkRh+es3/spQ==} engines: {node: '>=6.0.0'} hasBin: true @@ -2200,8 +2202,8 @@ packages: browser-or-node@1.3.0: resolution: {integrity: sha512-0F2z/VSnLbmEeBcUrSuDH5l0HxTXdQQzLjkmBR4cYfvg1zJrKSlmIZFqyFR8oX0NrwPhy3c3HQ6i3OxMbew4Tg==} - browserslist@4.28.2: - resolution: {integrity: sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==} + browserslist@4.28.9: + resolution: {integrity: sha512-EWazOblFYUvlGZcfGhPUPmYh3nikUxBVb+y9MJun5f3hBi812X+8MSQTujLBtgK3cf51fJWbWfOjyeO954d+Eg==} engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true @@ -2266,8 +2268,8 @@ packages: resolution: {integrity: sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==} engines: {node: '>=10'} - caniuse-lite@1.0.30001799: - resolution: {integrity: sha512-hG1bReV+OUU+MOqK4t/ZWI0tZOyz3rqS9XuhOUz1cIcbwBKjOyJEJuw9ER5JuNyqxNk8u/JUVbGibBOL1yrjFw==} + caniuse-lite@1.0.30001810: + resolution: {integrity: sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==} cassandra-driver@4.8.0: resolution: {integrity: sha512-HritfMGq9V7SuESeSodHvArs0mLuMk7uh+7hQK2lqdvXrvm50aWxb4RPxkK3mPDdsgHjJ427xNRFITMH2ei+Sw==} @@ -2593,8 +2595,8 @@ packages: resolution: {integrity: sha512-/RInbCy1d4P6Zdfa+TMVsf/ufZVotat5hCw3QXmWtjU+3pFEOvOQ7ibo3aIxyCJw2leIeAMjmPj+1SLJiCpdrQ==} engines: {node: '>=12.0.0'} - electron-to-chromium@1.5.371: - resolution: {integrity: sha512-e9htk9mAYL6AzmkEhSvVVw7IWGSBJ/Bqdn2eRyRLrj1g6sncN4WbFt5qnILYoCktktr45pyjIrOiRvBThQ808w==} + electron-to-chromium@1.5.426: + resolution: {integrity: sha512-2Gcq6inCQs/AqfHP3f5ftCzk+pqeW2VlA1LgmPqEj2hfBO8HiZRspNYkD4HzFBe4u6lGqca4BspFr6Ix4Q400g==} emittery@0.13.1: resolution: {integrity: sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ==} @@ -3630,8 +3632,8 @@ packages: resolution: {integrity: sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==} hasBin: true - mysql2@3.22.5: - resolution: {integrity: sha512-95uZ2TrPWAZdwpB3vvvDbmEMcNG8yIeNCyu6GUcr/QnWEE/wXm7+mhOCsdQfWQDTV7qYT/PDUZ4U4UPP4AsXqQ==} + mysql2@3.24.4: + resolution: {integrity: sha512-A2olluVlj0mvgyIRRISMEzXc51m+21mRtcMVjJyIpt2GG98+XrC9m9HzsqcMsX2LcnfccJvY5NB22g8fENBnOA==} engines: {node: '>= 8.0'} peerDependencies: '@types/node': '>= 8' @@ -3697,8 +3699,8 @@ packages: node-int64@0.4.0: resolution: {integrity: sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw==} - node-releases@2.0.47: - resolution: {integrity: sha512-Uzmd6LXpouKo8EUK68IjH4+E01w/hXyV3R3g/geCJo+rXLNfh1xucB+LOzYEOQPSiUK3h/xZf0cQGcSsmyL2Og==} + node-releases@2.0.55: + resolution: {integrity: sha512-mIrE/Cw9y+9Au6dS5vDKDhQza9YvG6w+ZrS6X+ZzA7yFW/soAeaups4Qzn1bL6g5FVy8WtP79+0j82oPIbqRjQ==} engines: {node: '>=18'} nodemon@3.1.14: @@ -4318,8 +4320,8 @@ packages: sprintf-js@1.1.3: resolution: {integrity: sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==} - sql-escaper@1.3.3: - resolution: {integrity: sha512-BsTCV265VpTp8tm1wyIm1xqQCS+Q9NHx2Sr+WcnUrgLrQ6yiDIvHYJV5gHxsj1lMBy2zm5twLaZao8Jd+S8JJw==} + sql-escaper@1.5.1: + resolution: {integrity: sha512-4toX5E1fQbBrpfXidaHnF0669nkAdETeIPTs2SUjxxD7RRIs9ICG4gtpmfc68JCEKehsdwLFqBu9VlQqZ1P1gg==} engines: {bun: '>=1.0.0', deno: '>=2.0.0', node: '>=12.0.0'} stack-trace@0.0.10: @@ -4627,11 +4629,11 @@ packages: resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==} engines: {node: '>=20.18.1'} - update-browserslist-db@1.2.3: - resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==} + update-browserslist-db@1.3.2: + resolution: {integrity: sha512-UQ+MSxlhRm1bzjhU+DcuXfjFO1FzNtqhK5+9Yvlp90ItDLk5vT932A0rFu619nf7RVS+Y/VeaUW1jaRDqZ8VJw==} hasBin: true peerDependencies: - browserslist: '>= 4.21.0' + browserslist: '>=4.28.7 <5.0.0' util-deprecate@1.0.2: resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} @@ -5915,7 +5917,7 @@ snapshots: dependencies: '@babel/compat-data': 7.29.7 '@babel/helper-validator-option': 7.29.7 - browserslist: 4.28.2 + browserslist: 4.28.9 lru-cache: 5.1.1 semver: 6.3.1 @@ -7519,7 +7521,7 @@ snapshots: base64-js@1.5.1: {} - baseline-browser-mapping@2.10.35: {} + baseline-browser-mapping@2.11.21: {} basic-ftp@5.3.1: {} @@ -7567,13 +7569,13 @@ snapshots: browser-or-node@1.3.0: {} - browserslist@4.28.2: + browserslist@4.28.9: dependencies: - baseline-browser-mapping: 2.10.35 - caniuse-lite: 1.0.30001799 - electron-to-chromium: 1.5.371 - node-releases: 2.0.47 - update-browserslist-db: 1.2.3(browserslist@4.28.2) + baseline-browser-mapping: 2.11.21 + caniuse-lite: 1.0.30001810 + electron-to-chromium: 1.5.426 + node-releases: 2.0.55 + update-browserslist-db: 1.3.2(browserslist@4.28.9) bs-logger@0.2.6: dependencies: @@ -7625,7 +7627,7 @@ snapshots: camelcase@6.3.0: {} - caniuse-lite@1.0.30001799: {} + caniuse-lite@1.0.30001810: {} cassandra-driver@4.8.0: dependencies: @@ -7929,7 +7931,7 @@ snapshots: efrt@2.7.0: {} - electron-to-chromium@1.5.371: {} + electron-to-chromium@1.5.426: {} emittery@0.13.1: {} @@ -9145,17 +9147,16 @@ snapshots: mustache@4.2.0: {} - mysql2@3.22.5(@types/node@22.19.21): + mysql2@3.24.4(@types/node@22.19.21): dependencies: '@types/node': 22.19.21 aws-ssl-profiles: 1.1.2 - denque: 2.1.0 generate-function: 2.3.1 iconv-lite: 0.7.3 long: 5.3.2 lru.min: 1.1.4 named-placeholders: 1.1.6 - sql-escaper: 1.3.3 + sql-escaper: 1.5.1 mz@2.7.0: dependencies: @@ -9239,7 +9240,7 @@ snapshots: node-int64@0.4.0: {} - node-releases@2.0.47: {} + node-releases@2.0.55: {} nodemon@3.1.14: dependencies: @@ -9916,7 +9917,7 @@ snapshots: sprintf-js@1.1.3: {} - sql-escaper@1.3.3: {} + sql-escaper@1.5.1: {} stack-trace@0.0.10: {} @@ -10219,9 +10220,9 @@ snapshots: undici@7.29.0: {} - update-browserslist-db@1.2.3(browserslist@4.28.2): + update-browserslist-db@1.3.2(browserslist@4.28.9): dependencies: - browserslist: 4.28.2 + browserslist: 4.28.9 escalade: 3.2.0 picocolors: 1.1.1 diff --git a/mem0-ts/pnpm-workspace.yaml b/mem0-ts/pnpm-workspace.yaml index 0bc89a968..4048a653c 100644 --- a/mem0-ts/pnpm-workspace.yaml +++ b/mem0-ts/pnpm-workspace.yaml @@ -38,6 +38,8 @@ overrides: "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" + "browserslist@<4.28.7": ">=4.28.7 <5.0.0" + "mysql2@<3.23.1": ">=3.23.1 <4.0.0" patchedDependencies: "tar@7.5.22": "patches/tar@7.5.22.patch" diff --git a/poetry.lock b/poetry.lock index 3e98dffd6..ee07e1dbe 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1355,6 +1355,19 @@ docs = ["docutils"] pg = ["PyGreSQL (>=5)"] tests = ["pytest (>=7)", "ruff"] +[[package]] +name = "defusedxml" +version = "0.7.1" +description = "XML bomb protection for Python stdlib modules" +optional = true +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" +groups = ["main"] +markers = "extra == \"vector-stores\"" +files = [ + {file = "defusedxml-0.7.1-py2.py3-none-any.whl", hash = "sha256:a352e7e428770286cc899e2542b6cdaedb2b4953ff269a210103ec58f6198a61"}, + {file = "defusedxml-0.7.1.tar.gz", hash = "sha256:1bb3032db185915b62d7c6209c5a8792be6a32ab2fedacc84e01b52c51aa3e69"}, +] + [[package]] name = "deprecated" version = "1.2.18" @@ -4296,19 +4309,20 @@ test-extras = ["pytest-mpl", "pytest-randomly"] [[package]] name = "nltk" -version = "3.9.4" +version = "3.10.3" description = "Natural Language Toolkit" optional = true python-versions = ">=3.10" groups = ["main"] markers = "extra == \"vector-stores\"" files = [ - {file = "nltk-3.9.4-py3-none-any.whl", hash = "sha256:f2fa301c3a12718ce4a0e9305c5675299da5ad9e26068218b69d692fda84828f"}, - {file = "nltk-3.9.4.tar.gz", hash = "sha256:ed03bc098a40481310320808b2db712d95d13ca65b27372f8a403949c8b523d0"}, + {file = "nltk-3.10.3-py3-none-any.whl", hash = "sha256:ff9598a8e20518ee0d557745890cc4435b9578489e2dcbc69c4f81fa060caf7c"}, + {file = "nltk-3.10.3.tar.gz", hash = "sha256:bb9327a461c3811c2fa4900e03840401f2126adfb30c0072827c433bd2444ea4"}, ] [package.dependencies] click = "*" +defusedxml = "*" joblib = "*" regex = ">=2021.8.3" tqdm = "*" diff --git a/server/dashboard/pnpm-lock.yaml b/server/dashboard/pnpm-lock.yaml index 75f8fa66d..acbd0b7eb 100644 --- a/server/dashboard/pnpm-lock.yaml +++ b/server/dashboard/pnpm-lock.yaml @@ -16,6 +16,7 @@ overrides: postcss@<8.5.18: '>=8.5.18 <9.0.0' nanoid@<3.3.18: '>=3.3.18 <4.0.0' sharp@<0.35.0: '>=0.35.0 <0.36.0' + browserslist@<4.28.7: '>=4.28.7 <5.0.0' importers: @@ -1507,8 +1508,8 @@ packages: resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} engines: {node: 18 || 20 || >=22} - baseline-browser-mapping@2.10.35: - resolution: {integrity: sha512-honAfLBde0HAFLdNyBEfuuENkF6zR+ozxqxa/2zJKHBe1qzLqyTSeRKpdPEHAP03rlDGyQOPnCSxnVpVqQo9Mg==} + baseline-browser-mapping@2.11.21: + resolution: {integrity: sha512-uh8vpY/1/YyFkunIDFH/12p7/7VdPKA1hejMVEbdkEaWnUz0Hesvx5EbiU6XxjyHZIOju+ZMbQJkRh+es3/spQ==} engines: {node: '>=6.0.0'} hasBin: true @@ -1527,8 +1528,8 @@ packages: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} - browserslist@4.28.2: - resolution: {integrity: sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==} + browserslist@4.28.9: + resolution: {integrity: sha512-EWazOblFYUvlGZcfGhPUPmYh3nikUxBVb+y9MJun5f3hBi812X+8MSQTujLBtgK3cf51fJWbWfOjyeO954d+Eg==} engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true @@ -1555,6 +1556,9 @@ packages: caniuse-lite@1.0.30001797: resolution: {integrity: sha512-l8xKG+gwAIExZGl9FrF7KUwuOmk6wbEPC9Xoy/RtnWv1XG0Q4LFlagaLpUv3Kiza3W/wm27zy0yWJEieYKAP6w==} + caniuse-lite@1.0.30001810: + resolution: {integrity: sha512-TITQPUkaz+aVk5GL6NhOdwk1aEaNTSDPsGFWrTuhKGtjTF70jL/Oht2W4c6rXUe5fu7Ie19VIahAXHIIiWWNeg==} + chalk@4.1.2: resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} engines: {node: '>=10'} @@ -1749,8 +1753,8 @@ packages: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} - electron-to-chromium@1.5.371: - resolution: {integrity: sha512-e9htk9mAYL6AzmkEhSvVVw7IWGSBJ/Bqdn2eRyRLrj1g6sncN4WbFt5qnILYoCktktr45pyjIrOiRvBThQ808w==} + electron-to-chromium@1.5.426: + resolution: {integrity: sha512-2Gcq6inCQs/AqfHP3f5ftCzk+pqeW2VlA1LgmPqEj2hfBO8HiZRspNYkD4HzFBe4u6lGqca4BspFr6Ix4Q400g==} emoji-regex@9.2.2: resolution: {integrity: sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==} @@ -2438,8 +2442,8 @@ packages: resolution: {integrity: sha512-pyFS63ptit/P5WqUkt+UUfe+4oevH+bFeIiPPdfb0pFeYEu/1ELnJu5l+5EcTKYL5M7zaAa7S8ddywgXypqKCw==} engines: {node: '>= 0.4'} - node-releases@2.0.47: - resolution: {integrity: sha512-Uzmd6LXpouKo8EUK68IjH4+E01w/hXyV3R3g/geCJo+rXLNfh1xucB+LOzYEOQPSiUK3h/xZf0cQGcSsmyL2Og==} + node-releases@2.0.55: + resolution: {integrity: sha512-mIrE/Cw9y+9Au6dS5vDKDhQza9YvG6w+ZrS6X+ZzA7yFW/soAeaups4Qzn1bL6g5FVy8WtP79+0j82oPIbqRjQ==} engines: {node: '>=18'} normalize-path@3.0.0: @@ -3033,11 +3037,11 @@ packages: unrs-resolver@1.12.2: resolution: {integrity: sha512-dmlRxBJJayXjqTwC+JtF1HhJmgf3ftQ3YejFcZrf4+KKtJv0qDsK1pjqaaVjG7wJ5NJ6UVP1OqRMQ71Z4C3rxQ==} - update-browserslist-db@1.2.3: - resolution: {integrity: sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==} + update-browserslist-db@1.3.2: + resolution: {integrity: sha512-UQ+MSxlhRm1bzjhU+DcuXfjFO1FzNtqhK5+9Yvlp90ItDLk5vT932A0rFu619nf7RVS+Y/VeaUW1jaRDqZ8VJw==} hasBin: true peerDependencies: - browserslist: '>= 4.21.0' + browserslist: '>=4.28.7 <5.0.0' uri-js@4.4.1: resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} @@ -4350,7 +4354,7 @@ snapshots: autoprefixer@10.5.0(postcss@8.5.23): dependencies: - browserslist: 4.28.2 + browserslist: 4.28.9 caniuse-lite: 1.0.30001797 fraction.js: 5.3.4 picocolors: 1.1.1 @@ -4379,7 +4383,7 @@ snapshots: balanced-match@4.0.4: {} - baseline-browser-mapping@2.10.35: {} + baseline-browser-mapping@2.11.21: {} binary-extensions@2.3.0: {} @@ -4396,13 +4400,13 @@ snapshots: dependencies: fill-range: 7.1.1 - browserslist@4.28.2: + browserslist@4.28.9: dependencies: - baseline-browser-mapping: 2.10.35 - caniuse-lite: 1.0.30001797 - electron-to-chromium: 1.5.371 - node-releases: 2.0.47 - update-browserslist-db: 1.2.3(browserslist@4.28.2) + baseline-browser-mapping: 2.11.21 + caniuse-lite: 1.0.30001810 + electron-to-chromium: 1.5.426 + node-releases: 2.0.55 + update-browserslist-db: 1.3.2(browserslist@4.28.9) call-bind-apply-helpers@1.0.2: dependencies: @@ -4427,6 +4431,8 @@ snapshots: caniuse-lite@1.0.30001797: {} + caniuse-lite@1.0.30001810: {} + chalk@4.1.2: dependencies: ansi-styles: 4.3.0 @@ -4614,7 +4620,7 @@ snapshots: es-errors: 1.3.0 gopd: 1.2.0 - electron-to-chromium@1.5.371: {} + electron-to-chromium@1.5.426: {} emoji-regex@9.2.2: {} @@ -5446,7 +5452,7 @@ snapshots: object.entries: 1.1.9 semver: 6.3.1 - node-releases@2.0.47: {} + node-releases@2.0.55: {} normalize-path@3.0.0: {} @@ -6159,9 +6165,9 @@ snapshots: '@unrs/resolver-binding-win32-ia32-msvc': 1.12.2 '@unrs/resolver-binding-win32-x64-msvc': 1.12.2 - update-browserslist-db@1.2.3(browserslist@4.28.2): + update-browserslist-db@1.3.2(browserslist@4.28.9): dependencies: - browserslist: 4.28.2 + browserslist: 4.28.9 escalade: 3.2.0 picocolors: 1.1.1 diff --git a/server/dashboard/pnpm-workspace.yaml b/server/dashboard/pnpm-workspace.yaml index cbefbd0eb..dc4045c9e 100644 --- a/server/dashboard/pnpm-workspace.yaml +++ b/server/dashboard/pnpm-workspace.yaml @@ -13,3 +13,4 @@ overrides: "postcss@<8.5.18": ">=8.5.18 <9.0.0" "nanoid@<3.3.18": ">=3.3.18 <4.0.0" "sharp@<0.35.0": ">=0.35.0 <0.36.0" + "browserslist@<4.28.7": ">=4.28.7 <5.0.0" From 75e9efa261a3a545bff346eaefbdcc3162800ab9 Mon Sep 17 00:00:00 2001 From: Himanshu-Sangshetti Date: Sat, 12 Sep 2026 00:36:29 +0900 Subject: [PATCH 07/61] =?UTF-8?q?fix(eve):=20address=20review=20=E2=80=94?= =?UTF-8?q?=20async-write=20status,=20reasoning=20filter,=20turn-bounded?= =?UTF-8?q?=20capture,=20best-effort=20dedup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Review by @kartik-mem0. Root cause across all four: Mem0's hosted add with infer:true is async and returns a PENDING event before the memory is visible. - store.ts/tools.ts: add() returns AddResult{status,eventId} via parseAddResult; the v3 add path returns {status:"PENDING", event_id}, so remember reports {status:"queued", eventId} for async writes and {status:"saved"} only when resolved. FAILED/unknown status maps to completed, not queued. - messages.ts: drop typed non-text parts (reasoning no longer leaks into memory); bound the captured assistant reply to the current turn and collect all of its text segments (text->tool->text) instead of a stale prior answer. - capture.ts + README + eve.mdx: document operationId dedup as best-effort (lookup+add is not atomic; pending/concurrent windows can double-write); removed the "restart replays cannot write twice" claim. Tests: 68 pass (+15). Added reasoning, tool-only/cross-turn, multi-segment, pending/concurrent capture replay, and PENDING/FAILED add-result cases. Typecheck + build clean. --- docs/integrations/eve.mdx | 4 +- integrations/eve/README.md | 6 ++- integrations/eve/src/capture.ts | 6 +++ integrations/eve/src/messages.ts | 56 +++++++++++++++++---- integrations/eve/src/store.ts | 46 ++++++++++++++++- integrations/eve/src/tools.ts | 18 +++++-- integrations/eve/tests/capture.test.ts | 67 +++++++++++++++++++++++++ integrations/eve/tests/helpers.ts | 12 ++++- integrations/eve/tests/messages.test.ts | 63 +++++++++++++++++++++++ integrations/eve/tests/provider.test.ts | 14 +++++- integrations/eve/tests/store.test.ts | 57 ++++++++++++++++++++- 11 files changed, 327 insertions(+), 22 deletions(-) diff --git a/docs/integrations/eve.mdx b/docs/integrations/eve.mdx index f3b78b5ac..4e8329617 100644 --- a/docs/integrations/eve.mdx +++ b/docs/integrations/eve.mdx @@ -36,8 +36,8 @@ export default defineMemory({ ## How it works 1. **Recall.** Before each turn and after compaction, Mem0 searches memories for the locked Eve scope and returns `{ id, content }` messages. Eve injects those as user-role messages attributed to the slot. -2. **Capture.** After a successful turn, Mem0 adds the user messages from that turn and, when present, the latest assistant reply. By default (`infer: true`) Mem0 extracts durable facts. -3. **Tools.** The model can call `search`, `remember`, and `forget`. Eve qualifies them as `mem0__search`, `mem0__remember`, and `mem0__forget` when the slot file is `mem0.ts`. +2. **Capture.** After a successful turn, Mem0 adds the user messages from that turn and, when present, that turn's assistant reply. By default (`infer: true`) Mem0 extracts durable facts. Capture is deduplicated per `operationId` on a best-effort basis (an in-process gate plus a durable `metadata.operation_id` lookup); because that check and the write are not atomic and platform writes are asynchronous, a restart or concurrent worker can occasionally capture a turn twice. +3. **Tools.** The model can call `search`, `remember`, and `forget`. Eve qualifies them as `mem0__search`, `mem0__remember`, and `mem0__forget` when the slot file is `mem0.ts`. `remember` returns `{ status: "saved" }` on a resolved write or `{ status: "queued" }` when the platform accepts it for asynchronous extraction. Eve owns namespace, scope, and when recall/capture run. Mem0 owns storage, ranking, and extraction. Search, capture, remember, and forget are partitioned by `memory.scope.key`. Forget deletes by id only after confirming the memory belongs to that key. diff --git a/integrations/eve/README.md b/integrations/eve/README.md index 37d129e51..87ead5552 100644 --- a/integrations/eve/README.md +++ b/integrations/eve/README.md @@ -36,12 +36,14 @@ The live MCP path today is `eve add connection/mem0`. That is a different integr |---|---| | `recall["turn.started"]` | Semantic search over memories for the locked scope | | `recall["compaction.completed"]` | Same search after Eve compacting history (`turn` may be null) | -| `capture["turn.completed"]` | Add the completed user turn and, when present, the latest assistant reply | +| `capture["turn.completed"]` | Add the completed user turn and, when present, this turn's assistant reply | | `tools()` | `search`, `remember`, `forget` | Search, capture, remember, and forget are partitioned by `memory.scope.key`. Forget loads the memory first and deletes only when `userId` matches that key. -Capture uses `operationId` as an idempotency key: an in-process gate plus a durable `metadata.operation_id` lookup so Eve replays after restart do not write twice. +Capture uses `operationId` for **best-effort** deduplication: an in-process gate plus a durable `metadata.operation_id` lookup. This is not atomic — with `infer: true` a prior write can be a PENDING event whose memory is not yet visible, so a restart during that window (or two concurrent workers) can capture the same turn twice. Eliminating that would require a backend-supported atomic idempotency key. + +`remember` returns `{ status: "saved" }` when the write resolves, or `{ status: "queued" }` when the platform accepts it for asynchronous extraction (it becomes searchable a moment later). If the slot file is named `mem0.ts`, Eve qualifies tools as `mem0__search`, `mem0__remember`, and `mem0__forget`. diff --git a/integrations/eve/src/capture.ts b/integrations/eve/src/capture.ts index d28ecf73c..2fdfea959 100644 --- a/integrations/eve/src/capture.ts +++ b/integrations/eve/src/capture.ts @@ -10,6 +10,12 @@ export async function captureCompletedTurn(input: { messages: readonly ConversationMessage[]; turnInput: readonly ConversationMessage[]; }): Promise { + // Best-effort deduplication, not a guarantee. This lookup + add is not atomic, + // and with infer:true the prior write can still be a PENDING event whose + // memory is not yet visible here. So a restart during that window, or two + // workers that both clear this check before either write, can capture the + // same operation twice. The in-process gate in provider.ts narrows the common + // case; eliminating it would need a backend-supported atomic idempotency key. const existing = await input.store.listByMetadata({ userId: input.scopeKey, metadata: { operation_id: input.operationId }, diff --git a/integrations/eve/src/messages.ts b/integrations/eve/src/messages.ts index 18d7dd36f..1d8b50ee0 100644 --- a/integrations/eve/src/messages.ts +++ b/integrations/eve/src/messages.ts @@ -9,9 +9,16 @@ function textFromPart(part: unknown): string { if (typeof part === "string") { return part; } - if (part && typeof part === "object" && "text" in part) { - const text = (part as { text: unknown }).text; - return typeof text === "string" ? text : ""; + if (part && typeof part === "object") { + const record = part as { type?: unknown; text?: unknown }; + // Typed parts must be explicit text. A `reasoning` part also carries a + // `text` field, so accepting any object with `text` would leak the model's + // private reasoning into long-term memory. Untyped `{ text }` (no `type` + // key) stays supported for callers that pass a bare text object. + if ("type" in record && record.type !== "text") { + return ""; + } + return typeof record.text === "string" ? record.text : ""; } return ""; } @@ -72,11 +79,42 @@ export function completedTurnMessages(input: { return []; } - // Pair this turn's users with the latest assistant in the settled history. - const history = conversationMessages(input.messages); - const lastAssistant = [...history] - .reverse() - .find((message) => message.role === "assistant"); + // Pair this turn's users with the assistant reply produced *in this turn* + // only. The current turn begins at the last user message in the settled + // history; any assistant text after it belongs to this turn. Walking the + // whole history instead would attach an older answer to the new user input + // when this turn is tool-only (no assistant text of its own). + let lastUserIndex = -1; + for (let index = input.messages.length - 1; index >= 0; index -= 1) { + if (input.messages[index]?.role === "user") { + lastUserIndex = index; + break; + } + } - return lastAssistant ? [...users, lastAssistant] : users; + // Collect every assistant text segment produced in this turn, in order, so a + // text -> tool-call -> text answer is captured whole rather than losing the + // pre-tool content. + const assistantSegments: string[] = []; + if (lastUserIndex >= 0) { + for ( + let index = lastUserIndex + 1; + index < input.messages.length; + index += 1 + ) { + const message = input.messages[index]; + if (message?.role !== "assistant") { + continue; + } + const text = extractText(message.content); + if (text.length > 0) { + assistantSegments.push(text); + } + } + } + + const assistantText = assistantSegments.join("\n"); + return assistantText + ? [...users, { role: "assistant", content: assistantText }] + : users; } diff --git a/integrations/eve/src/store.ts b/integrations/eve/src/store.ts index 9d7d27b42..7973229bd 100644 --- a/integrations/eve/src/store.ts +++ b/integrations/eve/src/store.ts @@ -27,6 +27,15 @@ export interface AddMemoryInput { readonly metadata: StoreMetadata; } +// A hosted-platform write with `infer: true` is asynchronous: Mem0 accepts the +// request and returns an `event_id` with a PENDING status before extraction has +// produced (or rejected) any memory. `queued` reflects that accepted-not-yet- +// stored state; `completed` means the write resolved synchronously. +export interface AddResult { + readonly status: "queued" | "completed"; + readonly eventId?: string; +} + export interface SearchMemoryInput { readonly userId: string; readonly topK: number; @@ -35,7 +44,10 @@ export interface SearchMemoryInput { } export interface MemoryStore { - add(messages: readonly MemoryMessage[], input: AddMemoryInput): Promise; + add( + messages: readonly MemoryMessage[], + input: AddMemoryInput, + ): Promise; search(query: string, input: SearchMemoryInput): Promise<{ results: readonly SearchHit[] }>; get(memoryId: string): Promise; listByMetadata(input: { @@ -70,6 +82,35 @@ export function parseSearchHit(item: unknown): SearchHit | null { return { id, memory }; } +// Event statuses that mean "accepted, extraction not finished". Only these map +// to `queued`; a terminal status (SUCCEEDED/FAILED) or an unknown/absent status +// falls through to `completed`, so a FAILED write is never reported as still +// pending. (The hosted add path returns PENDING synchronously; FAILED only +// appears later via event polling.) +const PENDING_STATUSES = new Set(["PENDING", "RUNNING", "PROCESSING", "QUEUED"]); + +export function parseAddResult(response: unknown): AddResult { + if (response && typeof response === "object" && !Array.isArray(response)) { + const record = response as Record; + const eventIdValue = record.event_id ?? record.eventId; + const eventId = + typeof eventIdValue === "string" && eventIdValue.length > 0 + ? eventIdValue + : undefined; + const status = + typeof record.status === "string" ? record.status.toUpperCase() : ""; + if (eventId && PENDING_STATUSES.has(status)) { + return { status: "queued", eventId }; + } + if (eventId) { + return { status: "completed", eventId }; + } + } + // A memory-results array (or any non-event payload) means the write already + // resolved; there is nothing left pending to report. + return { status: "completed" }; +} + export function parseMemoryRecord(item: unknown): MemoryRecord | null { if (!item || typeof item !== "object") { return null; @@ -138,11 +179,12 @@ export async function createMem0Store(input: { const store: MemoryStore = { async add(messages, options) { - await client.add([...messages], { + const response = await client.add([...messages], { userId: options.userId, infer: options.infer, metadata: { ...options.metadata }, }); + return parseAddResult(response); }, async search(query, options) { const response = await client.search(query, { diff --git a/integrations/eve/src/tools.ts b/integrations/eve/src/tools.ts index 3d65b1ede..731e08648 100644 --- a/integrations/eve/src/tools.ts +++ b/integrations/eve/src/tools.ts @@ -37,17 +37,29 @@ export function createMem0Tools( }), remember: defineTool({ description: - "Save one durable fact or preference about the current caller.", + "Save one durable fact or preference about the current caller. On the " + + "hosted platform the write is queued for extraction and may take a " + + "moment to become searchable; a `queued` status means accepted, not yet " + + "stored. Do not claim the fact is saved when the status is queued.", inputSchema: z.object({ text: z.string().min(1).max(4000), }), async execute({ text }) { - await store.add([{ role: "user", content: text }], { + const result = await store.add([{ role: "user", content: text }], { userId: scopeKey, infer: options.infer, metadata: { source: "eve-tool" }, }); - return { saved: true }; + // Report the true write state. With infer:true the platform returns a + // PENDING event, so promising "saved" would let the model tell the user + // a fact is stored when only the request was queued. Surface the eventId + // so the write can be correlated/confirmed rather than left a dead end. + return result.status === "queued" + ? { + status: "queued" as const, + ...(result.eventId ? { eventId: result.eventId } : {}), + } + : { status: "saved" as const }; }, }), forget: defineTool({ diff --git a/integrations/eve/tests/capture.test.ts b/integrations/eve/tests/capture.test.ts index d2a653162..a6fb0931b 100644 --- a/integrations/eve/tests/capture.test.ts +++ b/integrations/eve/tests/capture.test.ts @@ -47,6 +47,73 @@ describe("captureCompletedTurn", () => { expect(store.added).toEqual([]); }); + it("dedupes a replay once the prior write is visible", async () => { + const store = createFakeStore(); + const args = { + store, + scopeKey: "scope_abc", + operationId: "op_dedup", + infer: true, + metadata: { source: "eve", operation_id: "op_dedup" }, + turnInput: [{ role: "user", content: "I am vegetarian" }], + messages: [ + { role: "user", content: "I am vegetarian" }, + { role: "assistant", content: "Got it." }, + ], + }; + // First write is immediately visible (completed), so the replay is deduped. + expect(await captureCompletedTurn(args)).toBe(true); + expect(await captureCompletedTurn(args)).toBe(false); + expect(store.added).toHaveLength(1); + }); + + it("cannot dedupe while the prior write is still pending (best-effort)", async () => { + // Documents the known limitation: with infer:true the first write is a + // PENDING event whose memory is not yet visible, so the metadata lookup + // finds nothing and a restart replay writes the same operation again. + const store = createFakeStore([], { pendingWrites: true }); + const args = { + store, + scopeKey: "scope_abc", + operationId: "op_pending", + infer: true, + metadata: { source: "eve", operation_id: "op_pending" }, + turnInput: [{ role: "user", content: "I am vegetarian" }], + messages: [ + { role: "user", content: "I am vegetarian" }, + { role: "assistant", content: "Got it." }, + ], + }; + expect(await captureCompletedTurn(args)).toBe(true); + expect(await captureCompletedTurn(args)).toBe(true); + expect(store.added).toHaveLength(2); + }); + + it("does not dedupe concurrent replays that both pass the lookup (best-effort)", async () => { + // Two workers on separate provider instances both clear the metadata check + // before either write lands, so both capture the same operation. + const store = createFakeStore([], { pendingWrites: true }); + const args = { + store, + scopeKey: "scope_abc", + operationId: "op_concurrent", + infer: true, + metadata: { source: "eve", operation_id: "op_concurrent" }, + turnInput: [{ role: "user", content: "I am vegetarian" }], + messages: [ + { role: "user", content: "I am vegetarian" }, + { role: "assistant", content: "Got it." }, + ], + }; + const [first, second] = await Promise.all([ + captureCompletedTurn(args), + captureCompletedTurn(args), + ]); + expect(first).toBe(true); + expect(second).toBe(true); + expect(store.added).toHaveLength(2); + }); + it("skips add when the operation id was already captured", async () => { const store = createFakeStore([ { diff --git a/integrations/eve/tests/helpers.ts b/integrations/eve/tests/helpers.ts index f84555ee7..c277bf2c8 100644 --- a/integrations/eve/tests/helpers.ts +++ b/integrations/eve/tests/helpers.ts @@ -23,7 +23,10 @@ export type FakeSearch = SearchMemoryInput & { query: string; }; -export function createFakeStore(hits: FakeHit[] = []): MemoryStore & { +export function createFakeStore( + hits: FakeHit[] = [], + options: { pendingWrites?: boolean } = {}, +): MemoryStore & { added: FakeAdd[]; searched: FakeSearch[]; deleted: string[]; @@ -50,11 +53,18 @@ export function createFakeStore(hits: FakeHit[] = []): MemoryStore & { infer: input.infer, metadata: input.metadata, }); + // Model Mem0's async extraction: a pending write is accepted but its + // memory is not yet visible to listByMetadata/get, so it cannot dedupe a + // replay. A resolved write becomes immediately visible. + if (options.pendingWrites) { + return { status: "queued" as const, eventId: `evt_${added.length}` }; + } records.push({ id: `mem_added_${added.length}`, userId: input.userId, metadata: input.metadata, }); + return { status: "completed" as const }; }, async search(query, input) { searched.push({ query, ...input }); diff --git a/integrations/eve/tests/messages.test.ts b/integrations/eve/tests/messages.test.ts index 4e8fca5e1..66ab56a0c 100644 --- a/integrations/eve/tests/messages.test.ts +++ b/integrations/eve/tests/messages.test.ts @@ -27,6 +27,19 @@ describe("extractText", () => { it("ignores non-text parts", () => { expect(extractText([{ type: "image", url: "x" }])).toBe(""); }); + + it("ignores reasoning parts and keeps only the final text", () => { + expect( + extractText([ + { type: "reasoning", text: "speculation" }, + { type: "text", text: "Noted." }, + ]), + ).toBe("Noted."); + }); + + it("still reads an untyped text object", () => { + expect(extractText({ text: " bare " })).toBe("bare"); + }); }); describe("lastUserText", () => { @@ -87,4 +100,54 @@ describe("completedTurnMessages", () => { }), ).toEqual([]); }); + + it("does not attach a previous turn's answer to a tool-only turn", () => { + // Older Q&A, then a new user message whose only assistant output is a + // tool call (no text). The stale "older reply" must not be captured. + expect( + completedTurnMessages({ + turnInput: [{ role: "user", content: "new question" }], + messages: [ + { role: "user", content: "older question" }, + { role: "assistant", content: "older reply" }, + { role: "user", content: "new question" }, + { role: "assistant", content: [{ type: "tool-call", id: "t1" }] }, + ], + }), + ).toEqual([{ role: "user", content: "new question" }]); + }); + + it("captures all assistant text in a text/tool-call/text turn", () => { + expect( + completedTurnMessages({ + turnInput: [{ role: "user", content: "Q" }], + messages: [ + { role: "user", content: "Q" }, + { role: "assistant", content: "part A" }, + { role: "assistant", content: [{ type: "tool-call", id: "t1" }] }, + { role: "assistant", content: "part B" }, + ], + }), + ).toEqual([ + { role: "user", content: "Q" }, + { role: "assistant", content: "part A\npart B" }, + ]); + }); + + it("captures this turn's assistant reply, not an earlier one", () => { + expect( + completedTurnMessages({ + turnInput: [{ role: "user", content: "new question" }], + messages: [ + { role: "user", content: "older question" }, + { role: "assistant", content: "older reply" }, + { role: "user", content: "new question" }, + { role: "assistant", content: "new reply" }, + ], + }), + ).toEqual([ + { role: "user", content: "new question" }, + { role: "assistant", content: "new reply" }, + ]); + }); }); diff --git a/integrations/eve/tests/provider.test.ts b/integrations/eve/tests/provider.test.ts index e6a30af9d..33abee57d 100644 --- a/integrations/eve/tests/provider.test.ts +++ b/integrations/eve/tests/provider.test.ts @@ -247,7 +247,7 @@ describe("mem0Provider", () => { expect(search).toEqual({ memories: [{ id: "mem_1", memory: "likes tea" }], }); - expect(remember).toEqual({ saved: true }); + expect(remember).toEqual({ status: "saved" }); expect(forget).toEqual({ deleted: true }); expect(store.searched[0]).toMatchObject({ userId: "scope_abc", @@ -264,6 +264,18 @@ describe("mem0Provider", () => { expect(store.deleted).toEqual(["mem_1"]); }); + it("reports remember as queued when the write is still pending", async () => { + const store = createFakeStore([], { pendingWrites: true }); + const provider = mem0Provider({ store, infer: true }); + const tools = await provider.tools!(toolsContext()); + const rememberTool = tools?.remember; + if (!rememberTool) { + throw new Error("expected remember tool"); + } + const remember = await runTool(rememberTool, { text: "Allergic to peanuts" }); + expect(remember).toEqual({ status: "queued", eventId: "evt_1" }); + }); + it("refuses to forget a memory from another scope", async () => { const store = createFakeStore([ { id: "mem_other", memory: "secret", userId: "scope_other" }, diff --git a/integrations/eve/tests/store.test.ts b/integrations/eve/tests/store.test.ts index 1ed3ccd15..3e58c47ed 100644 --- a/integrations/eve/tests/store.test.ts +++ b/integrations/eve/tests/store.test.ts @@ -25,11 +25,48 @@ vi.mock("mem0ai", () => ({ import { createLazyStore, createMem0Store, + parseAddResult, parseMemoryRecord, parseSearchHit, resolveApiKey, } from "../src/store.js"; +describe("parseAddResult", () => { + it("reports a pending event as queued", () => { + expect(parseAddResult({ event_id: "evt_1", status: "PENDING" })).toEqual({ + status: "queued", + eventId: "evt_1", + }); + }); + + it("reports a succeeded event as completed", () => { + expect(parseAddResult({ event_id: "evt_1", status: "SUCCEEDED" })).toEqual({ + status: "completed", + eventId: "evt_1", + }); + }); + + it("treats a memory-results array as completed", () => { + expect(parseAddResult([{ id: "m1", memory: "tea" }])).toEqual({ + status: "completed", + }); + }); + + it("does not report a failed event as queued", () => { + expect(parseAddResult({ event_id: "evt_1", status: "FAILED" })).toEqual({ + status: "completed", + eventId: "evt_1", + }); + }); + + it("does not report an event with no status as queued", () => { + expect(parseAddResult({ event_id: "evt_1" })).toEqual({ + status: "completed", + eventId: "evt_1", + }); + }); +}); + describe("parseSearchHit", () => { it("accepts id, memory_id, nested text, and numeric ids", () => { expect(parseSearchHit({ id: 12, memory: "tea" })).toEqual({ @@ -122,18 +159,19 @@ describe("createMem0Store", () => { getAll.mockResolvedValue({ results: [{ id: "m9", userId: "scope_abc", metadata: { operation_id: "op_1" } }], }); - add.mockResolvedValue({ eventId: "evt_1" }); + add.mockResolvedValue({ event_id: "evt_1", status: "SUCCEEDED" }); const store = await createMem0Store({ apiKey: "m0-test", host: "https://api.mem0.ai", }); - await store.add([{ role: "user", content: "I like tea" }], { + const addResult = await store.add([{ role: "user", content: "I like tea" }], { userId: "scope_abc", infer: false, metadata: { source: "eve", operation_id: "op_1" }, }); + expect(addResult).toEqual({ status: "completed", eventId: "evt_1" }); const found = await store.search("tea", { userId: "scope_abc", topK: 3, @@ -169,6 +207,21 @@ describe("createMem0Store", () => { ]); }); + it("surfaces a pending platform write as queued", async () => { + const store = await createMem0Store({ + apiKey: "m0-test", + host: "https://api.mem0.ai", + }); + add.mockResolvedValueOnce({ event_id: "evt_9", status: "PENDING" }); + await expect( + store.add([{ role: "user", content: "I like tea" }], { + userId: "scope_abc", + infer: true, + metadata: { source: "eve" }, + }), + ).resolves.toEqual({ status: "queued", eventId: "evt_9" }); + }); + it("accepts a bare search array and rejects unknown envelopes", async () => { const store = await createMem0Store({ apiKey: "m0-test", From dc7f88363fd0abd5c448f466bfed57a78fcf411a Mon Sep 17 00:00:00 2001 From: jianyx1 <166109249+jianyx1@users.noreply.github.com> Date: Tue, 15 Sep 2026 21:53:17 +0800 Subject: [PATCH 08/61] docs: fix Hermes integration page to match the current plugin (#7244) --- docs/integrations/hermes.mdx | 87 +++++++++++++++++++++++++----------- 1 file changed, 61 insertions(+), 26 deletions(-) diff --git a/docs/integrations/hermes.mdx b/docs/integrations/hermes.mdx index abe167622..dce08e63f 100644 --- a/docs/integrations/hermes.mdx +++ b/docs/integrations/hermes.mdx @@ -1,39 +1,35 @@ --- title: Hermes Agent -description: "Add long-term memory to Hermes agents with Mem0, on managed Mem0 Cloud or fully self-hosted (OSS), with automatic background sync and zero-latency prefetch." +description: "Add long-term memory to Hermes agents with Mem0: managed Platform, a self-hosted server, or fully local OSS — with current-turn recall and background fact extraction." --- -Add long-term memory to [Hermes Agent](https://github.com/NousResearch/hermes-agent), a self-improving AI agent CLI by Nous Research. Hermes has a pluggable memory system, and Mem0 is one of the supported providers. Once enabled, Mem0 learns facts from your conversations and surfaces relevant ones before each turn, without slowing down the chat. +Add long-term memory to [Hermes Agent](https://github.com/NousResearch/hermes-agent), a self-improving AI agent CLI by Nous Research. Hermes has a pluggable memory system, and Mem0 is one of the supported providers. Once enabled, Mem0 learns facts from your conversations and surfaces relevant ones for the current question, without slowing down the chat. -You can run Mem0 in two ways: +You can run Mem0 in three ways: - **Platform mode** (default): managed Mem0 Cloud. Add your API key and you are ready. -- **OSS mode**: fully self-hosted with your own LLM, embedder, and vector store. No data leaves your machine. +- **Self-hosted server mode**: point the plugin at a Mem0 server you run yourself (the Docker-shipped server). The plugin only talks HTTP to your server. +- **OSS mode**: run Mem0 in-process with your own LLM, embedder, and vector store. No Mem0 server required. ## How It Works -Hermes runs a built-in memory system (file-based `MEMORY.md` and `USER.md`) alongside one external provider. When Mem0 is active, it works additively with the built-in system at three points in every conversation turn. +Hermes runs a built-in memory system (file-based `MEMORY.md` and `USER.md`) alongside one external provider. When Mem0 is active, it works additively with the built-in system at two points in every conversation turn. -### 1. Before the agent responds (prefetch) +### 1. Current-turn recall (bounded wait) -When you send a message, Hermes checks for cached Mem0 search results from the previous turn. If they exist, those memories are injected into the system prompt so the model can see them. This is zero-latency, with no waiting on an API call. +When you send a message, Hermes searches your stored memories for the current question and waits up to 3 seconds for results. If they arrive in time, they are injected into the system prompt so the model can see them. If the backend is slower, Hermes skips the injection and the model can still call `mem0_search` itself — so a slow backend never blocks a turn. -### 2. After the agent responds (sync) +### 2. Background fact extraction (sync) Once the model finishes, Hermes sends the `(user message, assistant response)` pair to Mem0 in a background thread. Mem0 extracts facts automatically (for example, "user prefers Python" or "user works at Acme Corp"), so you never have to tell it what to remember. Each write is tagged with the gateway channel it came from. -### 3. Background prefetch for the next turn - -At the same time, Hermes runs a background search to pre-load relevant memories for your next message. By the time you type, the results are already cached. - ## Agent Tools -When Mem0 is active, the model gets five tools it can call during a conversation: +When Mem0 is active, the model gets four tools it can call during a conversation: | Tool | Description | Parameters | |------|-------------|------------| -| `mem0_list` | List all stored memories, for a full overview | `page`, `page_size` (default 100, max 200) | -| `mem0_search` | Semantic search by meaning, ranked by relevance | `query` (required), `top_k` (default 10, max 50), `rerank` (default `true`, Platform mode only) | +| `mem0_search` | Semantic search by meaning, ranked by relevance | `query` (required), `top_k` (default 10, max 50), `rerank` (default `false`, Platform mode only) | | `mem0_add` | Store a fact verbatim, with no LLM extraction | `content` (required) | | `mem0_update` | Update a memory's text by ID | `memory_id`, `text` (both required) | | `mem0_delete` | Delete a memory by ID | `memory_id` (required) | @@ -79,6 +75,36 @@ memory: That's it. Mem0 runs automatically from here. +## Self-Hosted Server Setup + +Run the [Mem0 server](https://github.com/mem0ai/mem0/tree/main/server) (FastAPI + pgvector) from its Docker image and point the plugin at it. Unlike OSS mode, the plugin just talks HTTP to your server. + +### Interactive + +```bash +hermes memory setup +# Select "mem0", then "Self-hosted server", and enter the server URL +``` + +### With flags + +```bash +hermes memory setup mem0 --mode selfhosted \ + --host http://localhost:8888 \ + --api-key your-admin-api-key +``` + +### With environment variables + +```bash +echo "MEM0_HOST=http://localhost:8888" >> ~/.hermes/.env +echo "MEM0_API_KEY=your-admin-api-key" >> ~/.hermes/.env +``` + +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. @@ -111,15 +137,20 @@ hermes memory setup mem0 --mode oss \ | Flag | Description | |------|-------------| -| `--mode` | `platform` or `oss` | +| `--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 | @@ -127,7 +158,7 @@ hermes memory setup mem0 --mode oss \ ## Switching Modes -You can move between Platform and OSS at any time. Run the setup command again, or edit `~/.hermes/mem0.json` directly. +You can move between the three modes at any time. Run the setup command again, or edit `~/.hermes/mem0.json` directly. ```bash # Platform to OSS @@ -136,6 +167,9 @@ 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 ``` @@ -146,7 +180,7 @@ A self-hosted `~/.hermes/mem0.json` looks like this: { "mode": "oss", "oss": { - "llm": {"provider": "openai", "config": {"model": "gpt-5-mini"}}, + "llm": {"provider": "openai", "config": {"model": "gpt-5-mini", "is_reasoning_model": true}}, "embedder": {"provider": "openai", "config": {"model": "text-embedding-3-small"}}, "vector_store": {"provider": "qdrant", "config": {"path": "~/.hermes/mem0_qdrant"}} } @@ -159,11 +193,12 @@ Behavioral settings live in `~/.hermes/mem0.json` and are written for you by `he | Key | Default | Description | |-----|---------|-------------| -| `mode` | `platform` | `platform` (Mem0 Cloud) or `oss` (self-hosted) | -| `api_key` | none | Mem0 Platform API key, required in Platform mode. Stored in `.env` as `MEM0_API_KEY` | +| `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 | | `agent_id` | `hermes` | Agent identifier attached to writes | -| `rerank` | `true` | Rerank search results for relevance (Platform mode only) | +| `rerank` | `false` | Rerank search results for relevance (Platform mode only) | ### Cross-channel memories @@ -174,12 +209,11 @@ Hermes can run from the CLI and from gateways like Telegram, Slack, and Discord. Either way, every write is tagged with `metadata.channel` (for example `telegram` or `cli`), so per-channel views are still possible at query time. - ## Reliability - **Circuit breaker**: if Mem0 fails five times in a row, Hermes pauses calls for two minutes, then retries. The agent keeps working without memory during that window. Expected client errors, like a 404 on a missing memory id, do not count toward tripping the breaker. -- **Non-blocking**: every Mem0 call runs in a background daemon thread, so a slow or failed call never blocks your conversation. -- **Thread-safe**: the client uses lazy initialization with locking, and the background sync and prefetch threads are guarded so concurrent gateway messages cannot produce duplicate memories. +- **Non-blocking**: fact extraction runs in a background daemon thread, and current-turn recall waits at most 3 seconds, so a slow or failed call never blocks your conversation. +- **Thread-safe**: the client uses lazy initialization with locking, and the background sync and recall threads are guarded so concurrent gateway messages cannot produce duplicate memories. ## Troubleshooting @@ -188,6 +222,7 @@ Either way, every write is tagged with `metadata.channel` (for example `telegram The circuit breaker tripped after five consecutive failures and resets after two minutes. - **Platform mode**: check your API key and internet connection. +- **Self-hosted server mode**: check that the server is running and reachable at the configured `host` URL. - **OSS mode**: make sure your vector store (Qdrant or PGVector) is running and reachable. ### OSS: vector store connection refused @@ -217,8 +252,8 @@ curl http://localhost:11434/api/tags ## Key Features -1. **Two ways to run**: managed Platform or fully self-hosted OSS, switchable at any time. -2. **Zero-latency recall**: memories are prefetched in the background and cached before you type. +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`). From b51f7692f002d4f8719dd5c0f23d4d129003757d Mon Sep 17 00:00:00 2001 From: PowderXu <126909591+PowderXu@users.noreply.github.com> Date: Tue, 15 Sep 2026 10:11:46 -0400 Subject: [PATCH 09/61] docs(upstash): correct the default collection namespace (#7287) --- docs/components/vectordbs/dbs/upstash-vector.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/components/vectordbs/dbs/upstash-vector.mdx b/docs/components/vectordbs/dbs/upstash-vector.mdx index 1858516f8..90fa49397 100644 --- a/docs/components/vectordbs/dbs/upstash-vector.mdx +++ b/docs/components/vectordbs/dbs/upstash-vector.mdx @@ -102,7 +102,7 @@ Here are the parameters available for configuring Upstash Vector: | `url` | URL for the Upstash Vector index | `None` | | `token` | Token for the Upstash Vector index | `None` | | `client` | An `upstash_vector.Index` instance | `None` | -| `collection_name` | The default namespace used | `""` | +| `collection_name` | The default namespace used | `"mem0"` | | `enable_embeddings` | Whether to use Upstash embeddings | `False` | From 0df3e4b87df20785f0741370c75e44428796193e Mon Sep 17 00:00:00 2001 From: Paurush Mittal <137642194+paurushmittal@users.noreply.github.com> Date: Wed, 16 Sep 2026 17:14:33 +0530 Subject: [PATCH 10/61] fix(docs): correct rendered titles and remaining SEO links (#7344) --- docs/api-reference.mdx | 5 ++--- docs/api-reference/memory/delete-memory.mdx | 5 ++--- docs/api-reference/memory/update-memory.mdx | 5 ++--- docs/api-reference/organization/add-org-member.mdx | 5 ++--- docs/api-reference/organization/get-org-members.mdx | 5 ++--- docs/api-reference/project/add-project-member.mdx | 5 ++--- docs/api-reference/project/get-project-members.mdx | 5 ++--- docs/components/embedders/config.mdx | 5 ++--- docs/components/embedders/models/aws-bedrock.mdx | 5 ++--- docs/components/embedders/models/azure-openai.mdx | 5 ++--- docs/components/embedders/models/google-ai.mdx | 5 ++--- docs/components/embedders/models/langchain.mdx | 5 ++--- docs/components/embedders/models/lmstudio.mdx | 5 ++--- docs/components/embedders/models/ollama.mdx | 5 ++--- docs/components/embedders/models/openai.mdx | 5 ++--- docs/components/embedders/models/together.mdx | 5 ++--- docs/components/embedders/overview.mdx | 5 ++--- docs/components/llms/config.mdx | 5 ++--- docs/components/llms/models/aws-bedrock.mdx | 5 ++--- docs/components/llms/models/azure-openai.mdx | 5 ++--- docs/components/llms/models/deepseek.mdx | 2 +- docs/components/llms/models/google-ai.mdx | 5 ++--- docs/components/llms/models/langchain.mdx | 5 ++--- docs/components/llms/models/lmstudio.mdx | 7 +++---- docs/components/llms/models/minimax.mdx | 2 +- docs/components/llms/models/ollama.mdx | 5 ++--- docs/components/llms/models/openai.mdx | 5 ++--- docs/components/llms/models/together.mdx | 5 ++--- docs/components/llms/models/xAI.mdx | 5 ++--- docs/components/llms/overview.mdx | 5 ++--- docs/components/rerankers/overview.mdx | 5 ++--- docs/components/vectordbs/config.mdx | 5 ++--- docs/components/vectordbs/dbs/langchain.mdx | 5 ++--- docs/components/vectordbs/overview.mdx | 5 ++--- docs/cookbooks/overview.mdx | 5 ++--- docs/core-concepts/memory-operations/delete.mdx | 5 ++--- docs/core-concepts/memory-operations/update.mdx | 5 ++--- docs/integrations.mdx | 5 ++--- docs/integrations/aws-bedrock.mdx | 5 ++--- docs/integrations/codex.mdx | 2 +- docs/integrations/flowise.mdx | 2 +- docs/integrations/langchain.mdx | 5 ++--- docs/integrations/n8n.mdx | 5 ++--- docs/open-source/features/custom-instructions.mdx | 5 ++--- docs/open-source/features/multimodal-support.mdx | 5 ++--- docs/open-source/features/overview.mdx | 5 ++--- docs/open-source/features/rest-api.mdx | 2 +- docs/open-source/overview.mdx | 5 ++--- docs/platform/cli.mdx | 5 ++--- docs/platform/features/custom-instructions.mdx | 5 ++--- docs/platform/features/multimodal-support.mdx | 5 ++--- docs/platform/overview.mdx | 5 ++--- 52 files changed, 100 insertions(+), 147 deletions(-) diff --git a/docs/api-reference.mdx b/docs/api-reference.mdx index 1aac9708e..2477bf313 100644 --- a/docs/api-reference.mdx +++ b/docs/api-reference.mdx @@ -1,7 +1,6 @@ --- -title: "Overview" -seo: - title: "API Reference Overview - Mem0" +title: "API Reference Overview" +sidebarTitle: "Overview" icon: "terminal" iconType: "solid" description: "REST APIs for memory management, search, and entity operations" diff --git a/docs/api-reference/memory/delete-memory.mdx b/docs/api-reference/memory/delete-memory.mdx index 1ff61da9e..87084b005 100644 --- a/docs/api-reference/memory/delete-memory.mdx +++ b/docs/api-reference/memory/delete-memory.mdx @@ -1,7 +1,6 @@ --- -title: 'Delete Memory' -seo: - title: "Delete Memory API Endpoint - Mem0" +title: "Delete Memory API Endpoint" +sidebarTitle: "Delete Memory" description: "Delete a single memory by its unique memory ID from the Mem0 platform using the DELETE endpoint." openapi: delete /v1/memories/{memory_id}/ --- \ No newline at end of file diff --git a/docs/api-reference/memory/update-memory.mdx b/docs/api-reference/memory/update-memory.mdx index 4818be587..a8a53a2e0 100644 --- a/docs/api-reference/memory/update-memory.mdx +++ b/docs/api-reference/memory/update-memory.mdx @@ -1,7 +1,6 @@ --- -title: 'Update Memory' -seo: - title: "Update Memory API Endpoint - Mem0" +title: "Update Memory API Endpoint" +sidebarTitle: "Update Memory" description: "Update the content, metadata, timestamp, or expiration date of a single memory by its unique ID using the PUT endpoint." openapi: put /v1/memories/{memory_id}/ --- diff --git a/docs/api-reference/organization/add-org-member.mdx b/docs/api-reference/organization/add-org-member.mdx index 2b0f00f4f..35237ffb6 100644 --- a/docs/api-reference/organization/add-org-member.mdx +++ b/docs/api-reference/organization/add-org-member.mdx @@ -1,7 +1,6 @@ --- -title: 'Add Member' -seo: - title: "Add Organization Member API Endpoint - Mem0" +title: "Add Organization Member API Endpoint" +sidebarTitle: "Add Member" description: "Add a new member to an organization with a specified role such as READER or OWNER access level." openapi: post /api/v1/orgs/organizations/{org_id}/members/ --- diff --git a/docs/api-reference/organization/get-org-members.mdx b/docs/api-reference/organization/get-org-members.mdx index b1a401195..333859d4c 100644 --- a/docs/api-reference/organization/get-org-members.mdx +++ b/docs/api-reference/organization/get-org-members.mdx @@ -1,7 +1,6 @@ --- -title: 'Get Members' -seo: - title: "Get Organization Members API Endpoint - Mem0" +title: "Get Organization Members API Endpoint" +sidebarTitle: "Get Members" description: "Retrieve a list of all members belonging to a specific organization on the Mem0 platform." openapi: get /api/v1/orgs/organizations/{org_id}/members/ --- \ No newline at end of file diff --git a/docs/api-reference/project/add-project-member.mdx b/docs/api-reference/project/add-project-member.mdx index f3e78c7f1..d1338f1b6 100644 --- a/docs/api-reference/project/add-project-member.mdx +++ b/docs/api-reference/project/add-project-member.mdx @@ -1,7 +1,6 @@ --- -title: 'Add Member' -seo: - title: "Add Project Member API Endpoint - Mem0" +title: "Add Project Member API Endpoint" +sidebarTitle: "Add Member" description: "Add a new member to a project with a specified role such as READER or OWNER access level." openapi: post /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/ --- diff --git a/docs/api-reference/project/get-project-members.mdx b/docs/api-reference/project/get-project-members.mdx index 722aafeba..35a4d5eb8 100644 --- a/docs/api-reference/project/get-project-members.mdx +++ b/docs/api-reference/project/get-project-members.mdx @@ -1,7 +1,6 @@ --- -title: 'Get Members' -seo: - title: "Get Project Members API Endpoint - Mem0" +title: "Get Project Members API Endpoint" +sidebarTitle: "Get Members" description: "Retrieve a list of all members belonging to a specific project on the Mem0 platform." openapi: get /api/v1/orgs/organizations/{org_id}/projects/{project_id}/members/ --- \ No newline at end of file diff --git a/docs/components/embedders/config.mdx b/docs/components/embedders/config.mdx index dd107fc04..577db6353 100644 --- a/docs/components/embedders/config.mdx +++ b/docs/components/embedders/config.mdx @@ -1,7 +1,6 @@ --- -title: Configurations -seo: - title: "Embedder Configuration Reference - Mem0" +title: "Embedder Configuration Reference" +sidebarTitle: "Configurations" description: "Reference for embedder configuration options in Mem0, including provider selection and model settings." --- diff --git a/docs/components/embedders/models/aws-bedrock.mdx b/docs/components/embedders/models/aws-bedrock.mdx index d831a5aad..2528a79fe 100644 --- a/docs/components/embedders/models/aws-bedrock.mdx +++ b/docs/components/embedders/models/aws-bedrock.mdx @@ -1,7 +1,6 @@ --- -title: AWS Bedrock -seo: - title: "AWS Bedrock as Embedding Provider - Mem0" +title: "AWS Bedrock as Embedding Provider" +sidebarTitle: "AWS Bedrock" description: "Configure AWS Bedrock as an embedding provider in Mem0 with IAM credentials and boto3 authentication." --- diff --git a/docs/components/embedders/models/azure-openai.mdx b/docs/components/embedders/models/azure-openai.mdx index 1b0e7cb9c..eb1086444 100644 --- a/docs/components/embedders/models/azure-openai.mdx +++ b/docs/components/embedders/models/azure-openai.mdx @@ -1,7 +1,6 @@ --- -title: Azure OpenAI -seo: - title: "Azure OpenAI as Embedding Provider - Mem0" +title: "Azure OpenAI as Embedding Provider" +sidebarTitle: "Azure OpenAI" description: "Configure Azure OpenAI as an embedding provider in Mem0 with API key, deployment, and endpoint settings." --- diff --git a/docs/components/embedders/models/google-ai.mdx b/docs/components/embedders/models/google-ai.mdx index c9a67bf1c..726dd83e0 100644 --- a/docs/components/embedders/models/google-ai.mdx +++ b/docs/components/embedders/models/google-ai.mdx @@ -1,7 +1,6 @@ --- -title: Google AI -seo: - title: "Google AI as Embedding Provider - Mem0" +title: "Google AI as Embedding Provider" +sidebarTitle: "Google AI" description: "Configure Google AI as an embedding provider in Mem0 using Gemini models and the GOOGLE_API_KEY variable." --- diff --git a/docs/components/embedders/models/langchain.mdx b/docs/components/embedders/models/langchain.mdx index 05908c295..e72ab32e7 100644 --- a/docs/components/embedders/models/langchain.mdx +++ b/docs/components/embedders/models/langchain.mdx @@ -1,7 +1,6 @@ --- -title: LangChain -seo: - title: "LangChain as Embedding Provider - Mem0" +title: "LangChain as Embedding Provider" +sidebarTitle: "LangChain" description: "Use LangChain as an embedding provider in Mem0 to access a wide range of models through a unified interface." --- diff --git a/docs/components/embedders/models/lmstudio.mdx b/docs/components/embedders/models/lmstudio.mdx index 8fe656be0..5ab13b08e 100644 --- a/docs/components/embedders/models/lmstudio.mdx +++ b/docs/components/embedders/models/lmstudio.mdx @@ -1,7 +1,6 @@ --- -title: "LM Studio" -seo: - title: "LM Studio as Embedding Provider - Mem0" +title: "LM Studio as Embedding Provider" +sidebarTitle: "LM Studio" description: "Configure LM Studio as an embedding provider in Mem0 for local embedding generation with models like nomic-embed-text." --- You can use embedding models from LM Studio to run Mem0 locally. diff --git a/docs/components/embedders/models/ollama.mdx b/docs/components/embedders/models/ollama.mdx index cc3f65e78..e4345b727 100644 --- a/docs/components/embedders/models/ollama.mdx +++ b/docs/components/embedders/models/ollama.mdx @@ -1,7 +1,6 @@ --- -title: "Ollama" -seo: - title: "Ollama as Embedding Provider - Mem0" +title: "Ollama as Embedding Provider" +sidebarTitle: "Ollama" description: "Configure Ollama as an embedding provider in Mem0 to generate embeddings locally using open-source models." --- You can use embedding models from Ollama to run Mem0 locally. diff --git a/docs/components/embedders/models/openai.mdx b/docs/components/embedders/models/openai.mdx index 376ffb87d..4acf136aa 100644 --- a/docs/components/embedders/models/openai.mdx +++ b/docs/components/embedders/models/openai.mdx @@ -1,7 +1,6 @@ --- -title: OpenAI -seo: - title: "OpenAI as Embedding Provider - Mem0" +title: "OpenAI as Embedding Provider" +sidebarTitle: "OpenAI" description: "Configure OpenAI as an embedding provider in Mem0 using models like text-embedding-3-large for vector generation." --- diff --git a/docs/components/embedders/models/together.mdx b/docs/components/embedders/models/together.mdx index 1cc4329c1..75f44227e 100644 --- a/docs/components/embedders/models/together.mdx +++ b/docs/components/embedders/models/together.mdx @@ -1,7 +1,6 @@ --- -title: Together -seo: - title: "Together AI as Embedding Provider - Mem0" +title: "Together AI as Embedding Provider" +sidebarTitle: "Together" description: "Configure Together AI as an embedding provider in Mem0 with support for 1024-dimensional embedding models." --- diff --git a/docs/components/embedders/overview.mdx b/docs/components/embedders/overview.mdx index e8cffd476..28f649091 100644 --- a/docs/components/embedders/overview.mdx +++ b/docs/components/embedders/overview.mdx @@ -1,7 +1,6 @@ --- -title: Overview -seo: - title: "Embedding Providers Overview - Mem0" +title: "Embedding Providers Overview" +sidebarTitle: Overview description: "Overview of all supported embedding model providers in Mem0, including OpenAI, Azure, Ollama, and more." --- diff --git a/docs/components/llms/config.mdx b/docs/components/llms/config.mdx index 5482376dc..5c67c876a 100644 --- a/docs/components/llms/config.mdx +++ b/docs/components/llms/config.mdx @@ -1,7 +1,6 @@ --- -title: Configurations -seo: - title: "LLM Configuration Reference - Mem0" +title: "LLM Configuration Reference" +sidebarTitle: "Configurations" description: "Reference for LLM configuration options in Mem0 for Python and TypeScript, including value precedence rules." --- diff --git a/docs/components/llms/models/aws-bedrock.mdx b/docs/components/llms/models/aws-bedrock.mdx index e75971391..f6f940024 100644 --- a/docs/components/llms/models/aws-bedrock.mdx +++ b/docs/components/llms/models/aws-bedrock.mdx @@ -1,7 +1,6 @@ --- -title: AWS Bedrock -seo: - title: "AWS Bedrock as LLM Provider - Mem0" +title: "AWS Bedrock as LLM Provider" +sidebarTitle: "AWS Bedrock" description: "Configure AWS Bedrock as an LLM provider in Mem0 with IAM authentication and Claude model support." --- diff --git a/docs/components/llms/models/azure-openai.mdx b/docs/components/llms/models/azure-openai.mdx index 550ff0fce..a81d3ec5f 100644 --- a/docs/components/llms/models/azure-openai.mdx +++ b/docs/components/llms/models/azure-openai.mdx @@ -1,7 +1,6 @@ --- -title: Azure OpenAI -seo: - title: "Azure OpenAI as LLM Provider - Mem0" +title: "Azure OpenAI as LLM Provider" +sidebarTitle: "Azure OpenAI" description: "Configure Azure OpenAI as an LLM provider in Mem0 with Azure Identity authentication and deployment settings." --- diff --git a/docs/components/llms/models/deepseek.mdx b/docs/components/llms/models/deepseek.mdx index ef178382a..6d9ccdb0f 100644 --- a/docs/components/llms/models/deepseek.mdx +++ b/docs/components/llms/models/deepseek.mdx @@ -3,7 +3,7 @@ title: DeepSeek description: "Configure DeepSeek as an LLM provider in Mem0 with API key setup and optional custom endpoint configuration." --- -To use DeepSeek LLM models, you have to set the `DEEPSEEK_API_KEY` environment variable. You can also optionally set `DEEPSEEK_API_BASE` if you need to use a different API endpoint (defaults to "https://api.deepseek.com"). +To use DeepSeek LLM models, you have to set the `DEEPSEEK_API_KEY` environment variable. You can also optionally set `DEEPSEEK_API_BASE` if you need to use a different API endpoint (defaults to `https://api.deepseek.com`). ## Usage diff --git a/docs/components/llms/models/google-ai.mdx b/docs/components/llms/models/google-ai.mdx index ba5e50d07..5cb7a576e 100644 --- a/docs/components/llms/models/google-ai.mdx +++ b/docs/components/llms/models/google-ai.mdx @@ -1,7 +1,6 @@ --- -title: Google AI -seo: - title: "Google AI as LLM Provider - Mem0" +title: "Google AI as LLM Provider" +sidebarTitle: "Google AI" description: "Configure Google Gemini as an LLM provider in Mem0 using the google.genai SDK and GOOGLE_API_KEY variable." --- diff --git a/docs/components/llms/models/langchain.mdx b/docs/components/llms/models/langchain.mdx index b7676ece2..2bace4cb9 100644 --- a/docs/components/llms/models/langchain.mdx +++ b/docs/components/llms/models/langchain.mdx @@ -1,7 +1,6 @@ --- -title: LangChain -seo: - title: "LangChain as LLM Provider - Mem0" +title: "LangChain as LLM Provider" +sidebarTitle: "LangChain" description: "Use LangChain as an LLM provider in Mem0 to integrate with various chat models through a unified interface." --- diff --git a/docs/components/llms/models/lmstudio.mdx b/docs/components/llms/models/lmstudio.mdx index 727ede319..192fe64e2 100644 --- a/docs/components/llms/models/lmstudio.mdx +++ b/docs/components/llms/models/lmstudio.mdx @@ -1,7 +1,6 @@ --- -title: LM Studio -seo: - title: "LM Studio as LLM Provider - Mem0" +title: "LM Studio as LLM Provider" +sidebarTitle: "LM Studio" description: "Configure LM Studio as an LLM provider in Mem0 for running local language models via an OpenAI-compatible API." --- @@ -78,7 +77,7 @@ m.add(messages, user_id="alice123", metadata={"category": "movies"}) To use LM Studio, you need to: 1. Download and install [LM Studio](https://lmstudio.ai/) 2. Start a local server from the "Server" tab - 3. Set the appropriate `lmstudio_base_url` in your configuration (default is usually http://localhost:1234/v1) + 3. Set the appropriate `lmstudio_base_url` in your configuration (default is usually `http://localhost:1234/v1`) ## Config diff --git a/docs/components/llms/models/minimax.mdx b/docs/components/llms/models/minimax.mdx index d885324e3..3d5cf36ac 100644 --- a/docs/components/llms/models/minimax.mdx +++ b/docs/components/llms/models/minimax.mdx @@ -3,7 +3,7 @@ title: MiniMax description: "Configure MiniMax as an LLM provider in Mem0 with API key setup and optional custom endpoint configuration." --- -To use MiniMax LLM models, you have to set the `MINIMAX_API_KEY` environment variable. You can also optionally set `MINIMAX_API_BASE` if you need to use a different API endpoint (defaults to "https://api.minimax.io/v1"). +To use MiniMax LLM models, you have to set the `MINIMAX_API_KEY` environment variable. You can also optionally set `MINIMAX_API_BASE` if you need to use a different API endpoint (defaults to `https://api.minimax.io/v1`). ## Usage diff --git a/docs/components/llms/models/ollama.mdx b/docs/components/llms/models/ollama.mdx index 2d6133575..7aef3d948 100644 --- a/docs/components/llms/models/ollama.mdx +++ b/docs/components/llms/models/ollama.mdx @@ -1,7 +1,6 @@ --- -title: Ollama -seo: - title: "Ollama as LLM Provider - Mem0" +title: "Ollama as LLM Provider" +sidebarTitle: "Ollama" description: "Configure Ollama as an LLM provider in Mem0 for running local language models with tool-calling support." --- diff --git a/docs/components/llms/models/openai.mdx b/docs/components/llms/models/openai.mdx index 5fe67ffb0..12e709b1f 100644 --- a/docs/components/llms/models/openai.mdx +++ b/docs/components/llms/models/openai.mdx @@ -1,7 +1,6 @@ --- -title: OpenAI -seo: - title: "OpenAI as LLM Provider - Mem0" +title: "OpenAI as LLM Provider" +sidebarTitle: "OpenAI" description: "Configure OpenAI as an LLM provider in Mem0 with support for GPT models and Openrouter compatibility." --- diff --git a/docs/components/llms/models/together.mdx b/docs/components/llms/models/together.mdx index 314564e61..d80b0592f 100644 --- a/docs/components/llms/models/together.mdx +++ b/docs/components/llms/models/together.mdx @@ -1,7 +1,6 @@ --- -title: Together -seo: - title: "Together AI as LLM Provider - Mem0" +title: "Together AI as LLM Provider" +sidebarTitle: "Together" description: "Configure Together AI as an LLM provider in Mem0 with API key setup and optional custom endpoint configuration." --- diff --git a/docs/components/llms/models/xAI.mdx b/docs/components/llms/models/xAI.mdx index 3c4ff4edc..59d41444a 100644 --- a/docs/components/llms/models/xAI.mdx +++ b/docs/components/llms/models/xAI.mdx @@ -1,7 +1,6 @@ --- -title: xAI -seo: - title: "xAI Grok as LLM Provider - Mem0" +title: "xAI Grok as LLM Provider" +sidebarTitle: "xAI" description: "Configure xAI Grok models as an LLM provider in Mem0 with API key setup and usage examples." --- diff --git a/docs/components/llms/overview.mdx b/docs/components/llms/overview.mdx index e500f58cc..99755a9d1 100644 --- a/docs/components/llms/overview.mdx +++ b/docs/components/llms/overview.mdx @@ -1,7 +1,6 @@ --- -title: Overview -seo: - title: "LLM Providers Overview - Mem0" +title: "LLM Providers Overview" +sidebarTitle: Overview description: "Overview of all supported LLM providers in Mem0, including OpenAI, Anthropic, Groq, Ollama, and more." --- diff --git a/docs/components/rerankers/overview.mdx b/docs/components/rerankers/overview.mdx index 8ec18c4e7..b5cfde3a9 100644 --- a/docs/components/rerankers/overview.mdx +++ b/docs/components/rerankers/overview.mdx @@ -1,7 +1,6 @@ --- -title: Overview -seo: - title: "Reranker Providers Overview - Mem0" +title: "Reranker Providers Overview" +sidebarTitle: "Overview" description: 'Pick the right reranker path to boost Mem0 search relevance.' --- diff --git a/docs/components/vectordbs/config.mdx b/docs/components/vectordbs/config.mdx index 2fcd6fa7a..d48dc1672 100644 --- a/docs/components/vectordbs/config.mdx +++ b/docs/components/vectordbs/config.mdx @@ -1,7 +1,6 @@ --- -title: Configurations -seo: - title: "Vector Store Configuration Reference - Mem0" +title: "Vector Store Configuration Reference" +sidebarTitle: "Configurations" description: "Reference for vector database configuration options in Mem0, including provider selection and connection settings." --- diff --git a/docs/components/vectordbs/dbs/langchain.mdx b/docs/components/vectordbs/dbs/langchain.mdx index 0ff348466..10cbee109 100644 --- a/docs/components/vectordbs/dbs/langchain.mdx +++ b/docs/components/vectordbs/dbs/langchain.mdx @@ -1,7 +1,6 @@ --- -title: LangChain -seo: - title: "LangChain as Vector Store Provider - Mem0" +title: "LangChain as Vector Store Provider" +sidebarTitle: "LangChain" description: "Use LangChain as a unified vector store provider in Mem0 to access multiple vector databases through one interface." --- diff --git a/docs/components/vectordbs/overview.mdx b/docs/components/vectordbs/overview.mdx index 2d7085d61..21f979c95 100644 --- a/docs/components/vectordbs/overview.mdx +++ b/docs/components/vectordbs/overview.mdx @@ -1,7 +1,6 @@ --- -title: Overview -seo: - title: "Vector Store Providers Overview - Mem0" +title: "Vector Store Providers Overview" +sidebarTitle: "Overview" description: "Overview of all supported vector databases in Mem0, including Qdrant, Chroma, PGVector, Pinecone, Oracle, and more." --- diff --git a/docs/cookbooks/overview.mdx b/docs/cookbooks/overview.mdx index df98e590c..c8434e771 100644 --- a/docs/cookbooks/overview.mdx +++ b/docs/cookbooks/overview.mdx @@ -1,7 +1,6 @@ --- -title: Overview -seo: - title: "Cookbooks and Tutorials - Mem0" +title: "Cookbooks and Tutorials" +sidebarTitle: "Overview" description: "Browse cookbook examples and tutorials for building AI applications with Mem0, from companion chatbots to AI agents." --- diff --git a/docs/core-concepts/memory-operations/delete.mdx b/docs/core-concepts/memory-operations/delete.mdx index 694546f8e..eb8f4c8c9 100644 --- a/docs/core-concepts/memory-operations/delete.mdx +++ b/docs/core-concepts/memory-operations/delete.mdx @@ -1,7 +1,6 @@ --- -title: Delete Memory -seo: - title: "Delete Memory Operation - Mem0" +title: "Delete Memory Operation" +sidebarTitle: "Delete Memory" description: Remove memories from Mem0 either individually, in bulk, or via filters. icon: "trash" iconType: "solid" diff --git a/docs/core-concepts/memory-operations/update.mdx b/docs/core-concepts/memory-operations/update.mdx index b53af5559..b1e190b47 100644 --- a/docs/core-concepts/memory-operations/update.mdx +++ b/docs/core-concepts/memory-operations/update.mdx @@ -1,7 +1,6 @@ --- -title: Update Memory -seo: - title: "Update Memory Operation - Mem0" +title: "Update Memory Operation" +sidebarTitle: "Update Memory" description: Modify an existing memory by updating its content or metadata. icon: "pen-to-square" iconType: "solid" diff --git a/docs/integrations.mdx b/docs/integrations.mdx index 138e6cffe..a912afcad 100644 --- a/docs/integrations.mdx +++ b/docs/integrations.mdx @@ -1,7 +1,6 @@ --- -title: Overview -seo: - title: "Integrations Overview - Mem0" +title: "Integrations Overview" +sidebarTitle: "Overview" description: "Overview of Mem0 integrations with popular AI frameworks and tools for persistent memory and context management." --- diff --git a/docs/integrations/aws-bedrock.mdx b/docs/integrations/aws-bedrock.mdx index 55c757f16..069893fc6 100644 --- a/docs/integrations/aws-bedrock.mdx +++ b/docs/integrations/aws-bedrock.mdx @@ -1,7 +1,6 @@ --- -title: AWS Bedrock -seo: - title: "AWS Bedrock Integration with Mem0" +title: "AWS Bedrock Integration" +sidebarTitle: "AWS Bedrock" description: "Use Mem0 with AWS Bedrock and OpenSearch Service for cloud-native persistent semantic memory storage." --- diff --git a/docs/integrations/codex.mdx b/docs/integrations/codex.mdx index d0ad0735f..a91f4f8f0 100644 --- a/docs/integrations/codex.mdx +++ b/docs/integrations/codex.mdx @@ -3,7 +3,7 @@ title: Codex description: "Add persistent memory to OpenAI Codex with automatic capture, automatic recall, a search tool, and six memory skills." --- -Add persistent memory to [**OpenAI Codex**](https://openai.com/index/codex/) with the Mem0 plugin. Codex forgets everything between tasks. This plugin fixes that by connecting to Mem0's cloud memory layer via MCP, automatically capturing learnings at key lifecycle points, and retrieving relevant context on the first prompt of a session. Codex can use the search tool for recall later in the session. +Add persistent memory to [**OpenAI Codex**](https://openai.com/codex/) with the Mem0 plugin. Codex forgets everything between tasks. This plugin fixes that by connecting to Mem0's cloud memory layer via MCP, automatically capturing learnings at key lifecycle points, and retrieving relevant context on the first prompt of a session. Codex can use the search tool for recall later in the session. Current plugin version: `0.3.1`. diff --git a/docs/integrations/flowise.mdx b/docs/integrations/flowise.mdx index 790a470fb..56649eb7b 100644 --- a/docs/integrations/flowise.mdx +++ b/docs/integrations/flowise.mdx @@ -23,7 +23,7 @@ npm install -g flowise npx flowise start ``` -2. Access to the Flowise UI at http://localhost:3000 +2. Access to the Flowise UI at `http://localhost:3000` 3. Basic familiarity with [Flowise's LLM orchestration](https://flowiseai.com/#features) concepts ## Setup and Configuration diff --git a/docs/integrations/langchain.mdx b/docs/integrations/langchain.mdx index 2f8d1a7a9..ae8e41ef3 100644 --- a/docs/integrations/langchain.mdx +++ b/docs/integrations/langchain.mdx @@ -1,7 +1,6 @@ --- -title: Langchain -seo: - title: "LangChain Integration with Mem0" +title: "LangChain Integration" +sidebarTitle: "Langchain" description: "Build personalized AI agents using LangChain for conversation flow and Mem0 for long-term memory retention." --- diff --git a/docs/integrations/n8n.mdx b/docs/integrations/n8n.mdx index b9d345d6b..f53358b77 100644 --- a/docs/integrations/n8n.mdx +++ b/docs/integrations/n8n.mdx @@ -1,7 +1,6 @@ --- -title: n8n -seo: - title: "n8n Integration with Mem0" +title: "n8n Integration" +sidebarTitle: "n8n" description: "Add long-term memory to n8n workflows and AI Agents with the Mem0 community node, no code required." --- diff --git a/docs/open-source/features/custom-instructions.mdx b/docs/open-source/features/custom-instructions.mdx index 06a3acd10..b6d40f39f 100644 --- a/docs/open-source/features/custom-instructions.mdx +++ b/docs/open-source/features/custom-instructions.mdx @@ -1,7 +1,6 @@ --- -title: Custom Instructions -seo: - title: "Open Source Custom Instructions - Mem0" +title: "Open Source Custom Instructions" +sidebarTitle: "Custom Instructions" description: Tailor fact extraction so Mem0 stores only the details you care about. icon: "wand-magic-sparkles" --- diff --git a/docs/open-source/features/multimodal-support.mdx b/docs/open-source/features/multimodal-support.mdx index 7fb9f335b..b1697cced 100644 --- a/docs/open-source/features/multimodal-support.mdx +++ b/docs/open-source/features/multimodal-support.mdx @@ -1,7 +1,6 @@ --- -title: Multimodal Support -seo: - title: "Open Source Multimodal Support - Mem0" +title: "Open Source Multimodal Support" +sidebarTitle: "Multimodal Support" description: Capture and recall memories from both text and images. icon: "image" --- diff --git a/docs/open-source/features/overview.mdx b/docs/open-source/features/overview.mdx index 8e8379bd8..59c01f5f6 100644 --- a/docs/open-source/features/overview.mdx +++ b/docs/open-source/features/overview.mdx @@ -1,7 +1,6 @@ --- -title: "Overview" -seo: - title: "Open Source Features Overview - Mem0" +title: "Open Source Features Overview" +sidebarTitle: "Overview" description: "Self-hosting features that extend Mem0 beyond basic memory storage" icon: "list" --- diff --git a/docs/open-source/features/rest-api.mdx b/docs/open-source/features/rest-api.mdx index b798d242d..4a877907c 100644 --- a/docs/open-source/features/rest-api.mdx +++ b/docs/open-source/features/rest-api.mdx @@ -56,7 +56,7 @@ The Mem0 REST API server exposes every OSS memory operation over HTTP. Run it al make bootstrap # starts Compose, creates an admin, issues the first API key ``` - Or to start the stack only and finish setup via the browser wizard at http://localhost:3000: + Or to start the stack only and finish setup via the browser wizard at `http://localhost:3000`: ```bash cd server diff --git a/docs/open-source/overview.mdx b/docs/open-source/overview.mdx index 667172c08..0adb15003 100644 --- a/docs/open-source/overview.mdx +++ b/docs/open-source/overview.mdx @@ -1,7 +1,6 @@ --- -title: "Overview" -seo: - title: "Mem0 Open Source Overview" +title: "Open Source Overview" +sidebarTitle: "Overview" description: "Self-host Mem0 with full control over your infrastructure and data" icon: "house" --- diff --git a/docs/platform/cli.mdx b/docs/platform/cli.mdx index 21d48d29e..e34f0aa59 100644 --- a/docs/platform/cli.mdx +++ b/docs/platform/cli.mdx @@ -1,7 +1,6 @@ --- -title: CLI -seo: - title: "Mem0 CLI for Terminal Memory Management" +title: "CLI for Terminal Memory Management" +sidebarTitle: "CLI" description: "Manage memories from your terminal, for both humans and AI agents." icon: "terminal" iconType: "solid" diff --git a/docs/platform/features/custom-instructions.mdx b/docs/platform/features/custom-instructions.mdx index 923c8f5dc..8b5b1f35e 100644 --- a/docs/platform/features/custom-instructions.mdx +++ b/docs/platform/features/custom-instructions.mdx @@ -1,7 +1,6 @@ --- -title: Custom Instructions -seo: - title: "Platform Custom Instructions - Mem0" +title: "Platform Custom Instructions" +sidebarTitle: "Custom Instructions" description: 'Control how Mem0 extracts and stores memories using natural language guidelines' --- diff --git a/docs/platform/features/multimodal-support.mdx b/docs/platform/features/multimodal-support.mdx index 4c450ea37..3de9e0177 100644 --- a/docs/platform/features/multimodal-support.mdx +++ b/docs/platform/features/multimodal-support.mdx @@ -1,7 +1,6 @@ --- -title: Multimodal Support -seo: - title: "Platform Multimodal Support - Mem0" +title: "Platform Multimodal Support" +sidebarTitle: "Multimodal Support" description: Integrate images and documents into your interactions with Mem0 --- diff --git a/docs/platform/overview.mdx b/docs/platform/overview.mdx index 35933c511..ddb5ff405 100644 --- a/docs/platform/overview.mdx +++ b/docs/platform/overview.mdx @@ -1,7 +1,6 @@ --- -title: "Overview" -seo: - title: "Mem0 Platform Overview" +title: "Platform Overview" +sidebarTitle: "Overview" description: "Managed memory layer for AI agents, production-ready in minutes" icon: "cloud" --- From f5220ff8d4236f2369a19b554f76a47059deb2b6 Mon Sep 17 00:00:00 2001 From: ANIRUDDHA ADAK Date: Thu, 17 Sep 2026 19:23:45 +0530 Subject: [PATCH 11/61] fix(security): bump next to 15.5.24, patches GHSA-p293-qw3h-jr36 (#7320) --- examples/mem0-demo/package.json | 2 +- server/dashboard/package.json | 2 +- server/dashboard/pnpm-lock.yaml | 84 ++++++++++++++++----------------- 3 files changed, 44 insertions(+), 44 deletions(-) diff --git a/examples/mem0-demo/package.json b/examples/mem0-demo/package.json index ec5b7c61c..ef1f8d20a 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.21", + "next": "15.5.24", "react": "^19.0.0", "react-dom": "^19.0.0", "react-markdown": "^10.0.1", diff --git a/server/dashboard/package.json b/server/dashboard/package.json index 7d1b86432..d2ce90831 100644 --- a/server/dashboard/package.json +++ b/server/dashboard/package.json @@ -45,7 +45,7 @@ "framer-motion": "^12.23.12", "lodash": "^4.18.1", "lucide-react": "^0.542.0", - "next": "15.5.21", + "next": "15.5.24", "next-themes": "^0.4.4", "react": "^19.0.0", "react-copy-to-clipboard": "^5.1.0", diff --git a/server/dashboard/pnpm-lock.yaml b/server/dashboard/pnpm-lock.yaml index acbd0b7eb..1fe88f38f 100644 --- a/server/dashboard/pnpm-lock.yaml +++ b/server/dashboard/pnpm-lock.yaml @@ -122,8 +122,8 @@ importers: specifier: ^0.542.0 version: 0.542.0(react@19.2.7) next: - specifier: 15.5.21 - version: 15.5.21(@types/node@22.5.4)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) + specifier: 15.5.24 + version: 15.5.24(@types/node@22.5.4)(react-dom@19.2.7(react@19.2.7))(react@19.2.7) next-themes: specifier: ^0.4.4 version: 0.4.6(react-dom@19.2.7(react@19.2.7))(react@19.2.7) @@ -476,60 +476,60 @@ packages: '@emnapi/core': ^1.7.1 '@emnapi/runtime': ^1.7.1 - '@next/env@15.5.21': - resolution: {integrity: sha512-hjJI/GfrjWHgNguRIBzItjRRu0m3Nrz17GhxsjuHfjIvg9hyg3239REd2dpI+bpMTFuVrVprHzEQ19m++cDtbw==} + '@next/env@15.5.24': + resolution: {integrity: sha512-mBDF7T0XKZjs9SpUAl0buizVO+O02ULjOvWX8o/AZo/5AGw/UAS1Zzcylmd4pqbftzmKQi+L/nB4jgBYKEAl5Q==} '@next/eslint-plugin-next@15.5.18': resolution: {integrity: sha512-w4MYq8M26a8PNrfto0JosLf5/3ssln1rsyP96g2DkC8uFVymStM5DLSz5ElxxrPRg2XnTMnFo3kREFlhYvxhWw==} - '@next/swc-darwin-arm64@15.5.21': - resolution: {integrity: sha512-ZfjqPEdi6TRC/fWx7UDbwb1fbVgyh2uD5tVTRKIDZDlYM+UNuE/LafDG2fwuAoZilADpABh46OY/F5qf9JjqLQ==} + '@next/swc-darwin-arm64@15.5.24': + resolution: {integrity: sha512-AGdNLvxZNY6eR2iSnV+6wUa8CiHTMr4F7g3uHH7fT4ICIJBE00R9u4tzN/Vuwsw0cOi8MTD2HJcTCb6siMH88Q==} engines: {node: '>= 10'} cpu: [arm64] os: [darwin] - '@next/swc-darwin-x64@15.5.21': - resolution: {integrity: sha512-TlCf1NpxgQLzTrexuev75xwmNCJMd1/qkJpTVP1GRRcih93hlIBn1P72hkh8T0gnRFr6BmWksQtbyG3jT6jnww==} + '@next/swc-darwin-x64@15.5.24': + resolution: {integrity: sha512-9HrQajBMmGcrrrvDfRimiCrbAPh3E6uHJmwBovYr6Yrmi9p9PZqI876BrXX280wICh3o2XwUlp4blkB0NNBqFg==} engines: {node: '>= 10'} cpu: [x64] os: [darwin] - '@next/swc-linux-arm64-gnu@15.5.21': - resolution: {integrity: sha512-LXRsq1p+HvHSi7ygwNcSEEcK0zuo5jS75ZlqFHtOH+LF7qntXAJVJxah+1Pi/GyBm7EpkwU7m4EgbvIKrMqm9A==} + '@next/swc-linux-arm64-gnu@15.5.24': + resolution: {integrity: sha512-rl9LSfE75si0WT3cDgdUC1XYCKS+TgxC+/IjitmeycrAG18X/plIP1/vy8dd/HPycYcIvE688PD7FuvEAiEAew==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] libc: [glibc] - '@next/swc-linux-arm64-musl@15.5.21': - resolution: {integrity: sha512-hyGixhFxpDKjqoev6l4KlcRBlt9AXWrGhDZwmwg49sMJM5tnKQPSi+SEj9+e5n+l/bthRGZUdh59GKIs6lQPRw==} + '@next/swc-linux-arm64-musl@15.5.24': + resolution: {integrity: sha512-TlNAnpsjxSF3aAUtqnfmtXXf8m9sIDBlmF3c7bTAlnshUYu2U0OxN2uf5d0gcFwqHVEdivJNBcCaqNOwPGNimw==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] libc: [musl] - '@next/swc-linux-x64-gnu@15.5.21': - resolution: {integrity: sha512-qfE+YfOba6S2+13e8qn1/UozDVNZ2clBlrs8UtDoax4s8ediu6sq93z66OEHUYlb69Tffh5JTNkgtsAKiSuugg==} + '@next/swc-linux-x64-gnu@15.5.24': + resolution: {integrity: sha512-7dwtlhr0SLndqTG1z9ncRkbJswDZiKWlxzFyXDvJ2RDZRDRHp8zyMJ4D9UH/FgnQeXxxB6gZy2pMcIUoNKQ4pA==} engines: {node: '>= 10'} cpu: [x64] os: [linux] libc: [glibc] - '@next/swc-linux-x64-musl@15.5.21': - resolution: {integrity: sha512-BXLGG+EvIwp/Rrgl6HY8sqvD6BOUOIRz8/naDbeLNX7mlA5H2XRcL6MW/0IGnJISfj5BA9gNhFyJj5yOoiIDJQ==} + '@next/swc-linux-x64-musl@15.5.24': + resolution: {integrity: sha512-kGZxM+WhkYs0276lFrMkj7PRtXT3Btp6cwvfSO/cCVLxJJttB5Ccnl2niaCgUja8HgSbEVnMHpg3FJWoOJ9e/g==} engines: {node: '>= 10'} cpu: [x64] os: [linux] libc: [musl] - '@next/swc-win32-arm64-msvc@15.5.21': - resolution: {integrity: sha512-tNGNOlT0Wn7E4IMsSnufjXN/l2L2/AGdLLpa2vzS89SYCBuihgLn3ngLsIrvndAnWo9nAkus+4gZHTI/Ijx9HA==} + '@next/swc-win32-arm64-msvc@15.5.24': + resolution: {integrity: sha512-jBDDkZ/qKAqkWivWDMkJSXUzbzV0QKRBKJjEHUAvSB97Hzw7NLzJ6yV56Lts/wjir7s4P31GYgpbS6ZL+hasAA==} engines: {node: '>= 10'} cpu: [arm64] os: [win32] - '@next/swc-win32-x64-msvc@15.5.21': - resolution: {integrity: sha512-DmIdWmC9p4rdNIiQqo8ap0+Cnj6kKtTZnuSCxoYydSc8sgpDgAg9wFhxplunak9imLV0pTvc5WVCOHwm5eHLtQ==} + '@next/swc-win32-x64-msvc@15.5.24': + resolution: {integrity: sha512-JqtwjvvorjacQ0spgjmUJoxySoYgPwdT1sFdQ0/zmW4iMlP2hjYlCoJIyS7o6Epb4Fug8eco3HXFoBDUCDeH7Q==} engines: {node: '>= 10'} cpu: [x64] os: [win32] @@ -2417,8 +2417,8 @@ packages: react: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc react-dom: ^16.8 || ^17 || ^18 || ^19 || ^19.0.0-rc - next@15.5.21: - resolution: {integrity: sha512-/TsdBtkWLhkl+NVL3Uqws2UphNd6IPzOtzSk1fHaf+0P7GQKLZDUytyhns/Ykbzdy9+YRjwG7ONvrHaaTDdFqQ==} + next@15.5.24: + resolution: {integrity: sha512-Y+xn8EQCoC3ZbsFPyzE+tE8XOdrWeUdUF7NeXbmg9DsgAxl5UYxlsrvgVESHTyTGigoTa1bCUrxn70F5bqt0Gw==} engines: {node: ^18.18.0 || ^19.8.0 || >= 20.0.0} hasBin: true peerDependencies: @@ -3343,34 +3343,34 @@ snapshots: '@tybys/wasm-util': 0.10.2 optional: true - '@next/env@15.5.21': {} + '@next/env@15.5.24': {} '@next/eslint-plugin-next@15.5.18': dependencies: fast-glob: 3.3.1 - '@next/swc-darwin-arm64@15.5.21': + '@next/swc-darwin-arm64@15.5.24': optional: true - '@next/swc-darwin-x64@15.5.21': + '@next/swc-darwin-x64@15.5.24': optional: true - '@next/swc-linux-arm64-gnu@15.5.21': + '@next/swc-linux-arm64-gnu@15.5.24': optional: true - '@next/swc-linux-arm64-musl@15.5.21': + '@next/swc-linux-arm64-musl@15.5.24': optional: true - '@next/swc-linux-x64-gnu@15.5.21': + '@next/swc-linux-x64-gnu@15.5.24': optional: true - '@next/swc-linux-x64-musl@15.5.21': + '@next/swc-linux-x64-musl@15.5.24': optional: true - '@next/swc-win32-arm64-msvc@15.5.21': + '@next/swc-win32-arm64-msvc@15.5.24': optional: true - '@next/swc-win32-x64-msvc@15.5.21': + '@next/swc-win32-x64-msvc@15.5.24': optional: true '@nodelib/fs.scandir@2.1.5': @@ -5421,24 +5421,24 @@ snapshots: react: 19.2.7 react-dom: 19.2.7(react@19.2.7) - next@15.5.21(@types/node@22.5.4)(react-dom@19.2.7(react@19.2.7))(react@19.2.7): + next@15.5.24(@types/node@22.5.4)(react-dom@19.2.7(react@19.2.7))(react@19.2.7): dependencies: - '@next/env': 15.5.21 + '@next/env': 15.5.24 '@swc/helpers': 0.5.15 - caniuse-lite: 1.0.30001797 + caniuse-lite: 1.0.30001810 postcss: 8.5.23 react: 19.2.7 react-dom: 19.2.7(react@19.2.7) styled-jsx: 5.1.6(react@19.2.7) optionalDependencies: - '@next/swc-darwin-arm64': 15.5.21 - '@next/swc-darwin-x64': 15.5.21 - '@next/swc-linux-arm64-gnu': 15.5.21 - '@next/swc-linux-arm64-musl': 15.5.21 - '@next/swc-linux-x64-gnu': 15.5.21 - '@next/swc-linux-x64-musl': 15.5.21 - '@next/swc-win32-arm64-msvc': 15.5.21 - '@next/swc-win32-x64-msvc': 15.5.21 + '@next/swc-darwin-arm64': 15.5.24 + '@next/swc-darwin-x64': 15.5.24 + '@next/swc-linux-arm64-gnu': 15.5.24 + '@next/swc-linux-arm64-musl': 15.5.24 + '@next/swc-linux-x64-gnu': 15.5.24 + '@next/swc-linux-x64-musl': 15.5.24 + '@next/swc-win32-arm64-msvc': 15.5.24 + '@next/swc-win32-x64-msvc': 15.5.24 sharp: 0.35.3(@types/node@22.5.4) transitivePeerDependencies: - '@babel/core' From f135cb994979170401d4e62d37fd043ed01ac5f8 Mon Sep 17 00:00:00 2001 From: "mintlify[bot]" <109931778+mintlify[bot]@users.noreply.github.com> Date: Thu, 17 Sep 2026 19:32:03 +0530 Subject: [PATCH 12/61] SEO & metadata audit: shorten hermes description (#7359) Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com> --- docs/integrations/hermes.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/integrations/hermes.mdx b/docs/integrations/hermes.mdx index dce08e63f..26de7221c 100644 --- a/docs/integrations/hermes.mdx +++ b/docs/integrations/hermes.mdx @@ -1,6 +1,6 @@ --- title: Hermes Agent -description: "Add long-term memory to Hermes agents with Mem0: managed Platform, a self-hosted server, or fully local OSS — with current-turn recall and background fact extraction." +description: "Add long-term memory to Hermes agents using Mem0 Platform, a self-hosted server, or local OSS mode with background fact extraction." --- Add long-term memory to [Hermes Agent](https://github.com/NousResearch/hermes-agent), a self-improving AI agent CLI by Nous Research. Hermes has a pluggable memory system, and Mem0 is one of the supported providers. Once enabled, Mem0 learns facts from your conversations and surfaces relevant ones for the current question, without slowing down the chat. From 84bf468176f0c5e82493bb95aec5484eb2d92bc1 Mon Sep 17 00:00:00 2001 From: Kartik Date: Fri, 18 Sep 2026 06:54:04 +0530 Subject: [PATCH 13/61] docs: add practical Mem0 Copilot guide (MEM-6344) (#7337) --- docs/docs.json | 1 + docs/llms.txt | 1 + docs/platform/copilot.mdx | 194 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 196 insertions(+) create mode 100644 docs/platform/copilot.mdx diff --git a/docs/docs.json b/docs/docs.json index c1c4887d2..4ca51fa24 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -41,6 +41,7 @@ "pages": [ "platform/quickstart", "platform/overview", + "platform/copilot", "platform/agent-signup", "vibecoding", "platform/cli", diff --git a/docs/llms.txt b/docs/llms.txt index 65e13de8f..686835a0e 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -171,6 +171,7 @@ If the user is on a pre-current major (Python < 2, TS < 3, or a Platform call st - [Introduction](https://docs.mem0.ai/introduction) [Both]: Use when the user wants a one-page overview of how memory fits between the LLM and the app. - [Vibe Code with Mem0](https://docs.mem0.ai/vibecoding) [Both]: Use when the user is in Claude Code, Cursor, or Windsurf and wants memory wired into their editor. - [Platform Overview](https://docs.mem0.ai/platform/overview) [Platform]: Use when the user picks the managed product - 4-line integration, hosted API, dashboard. +- [Mem0 Copilot](https://docs.mem0.ai/platform/copilot) [Platform]: Use when inspecting project memories, reviewing configuration changes, or testing extraction in the dashboard. - [Sign up as an agent](https://docs.mem0.ai/platform/agent-signup) [Platform]: Use when an AI agent needs to mint a Mem0 API key autonomously - four commands, no email or dashboard, human claims ownership later. - [Platform vs Open Source](https://docs.mem0.ai/platform/platform-vs-oss) [Both]: Use when the user is deciding between managed and self-hosted. - [Platform Quickstart](https://docs.mem0.ai/platform/quickstart) [Platform]: Use for the first Platform integration - API key plus `MemoryClient.add/search`. diff --git a/docs/platform/copilot.mdx b/docs/platform/copilot.mdx new file mode 100644 index 000000000..3d218ff84 --- /dev/null +++ b/docs/platform/copilot.mdx @@ -0,0 +1,194 @@ +--- +title: "Mem0 Copilot" +description: "Inspect project memories, review configuration changes, and test extraction from the Mem0 dashboard." +icon: "message" +--- + +Copilot is an AI assistant in the [Mem0 dashboard](https://app.mem0.ai/dashboard/copilot). Ask it to inspect stored memories, suggest extraction rules and categories, change project settings, or explain the platform SDKs and APIs. + +You describe the task in chat. Copilot uses tools to read project data or propose changes. In **Review changes** mode, you approve each change before it runs. + +## Start with your project + +1. Sign in to the dashboard and select the organization and project you want to work on. +2. Open **Copilot** in the sidebar. +3. Select **Review changes** below the message box. +4. Ask: “Show my current project settings and explain what each one does.” +5. Expand an activity card, such as **Read project config**, to see its **Input** and **Result**. Check these results when reviewing an answer or confirming a change. + +You can ask about settings or SDK usage with an empty project. Suggestions based on stored data need enough project history to analyze. + +## Inspect stored memories + +Start with a project overview, then narrow the question: + +| Prompt | What to inspect | +| --- | --- | +| “Summarize what this project has stored and how it is categorized.” | The memories and category patterns Copilot reads. Check which records support its summary. | +| “Analyze the memories for user alice.” | Facts stored for `alice`, their categories, and unwanted information. To investigate a missing fact, also provide the original input. | +| “Search alice's memories for dietary preferences.” | Memories relevant to the query within that user's scope. | + +Copilot can list memories across the project. Searching by meaning needs a specific User, Agent, App, or Run ID. Select one in **Scope** or name it in your prompt. + +Memory lists are paginated, and suggestions use samples. Check the activity results to see which records were read. Ask for more pages when you need to inspect the rest. + +### Choose the memory scope + +Open **Scope** below the message box. Select an existing ID or type one and choose it. + +| Control | Identifies | +| --- | --- | +| **User** | The end user whose memories you want to inspect, such as `alice`. | +| **Agent** | An AI agent associated with the memories. | +| **App** | An application associated with the memories. | +| **Run** | A particular execution or session associated with the memories. | + +A field set to **any** adds no filter for that entity type. **Clear scope** removes the selections. Scope gives Copilot default IDs to use; you can request a different entity in a message. Check the activity's **Input** to confirm which IDs it used. Adding a test memory requires a **User** ID, even when another entity is selected. + + + Scope selects memories, not separate settings. Categories, extraction instructions, memory depth, and multilingual settings apply to the selected project. Category and extraction suggestions also analyze project data, regardless of the selected entity. + + +See [Entity-scoped memory](/platform/features/entity-scoped-memory) for how these IDs organize memories in your application. + +## Review and apply changes + +The mode control below the message box determines when changes run: + +- **Review changes**: Copilot pauses before changing project configuration or adding a test memory. Read the proposal and choose whether to apply it. +- **Auto-apply**: Copilot can change settings and add test memories without asking for approval. Check the selected project and scope before using it. + +Ask Copilot to show the current settings before requesting an update. In the approval card, review every listed field. Approving the card applies the whole proposal, including fields you did not edit. + +| Action | Effect | +| --- | --- | +| **Apply change** | Approve the proposed write. Inspect the subsequent result to confirm it succeeded. | +| **Edit** | When offered, edit extraction instructions or category names and descriptions. Choose **Apply with edits** to submit your revision. | +| **Discard edits** | Return to the original proposal without applying it. | +| **Decline** | Reject this proposal without applying it. | +| **Ask for something else** | Enter feedback and choose **Send**. This declines the current proposal and sends your feedback as a new message. Review the next proposal before applying it. | + +Not every field has an inline editor. If a proposal includes both extraction instructions and categories, only the instructions get an editor. The editor cannot apply blank instructions or an empty category list. Use **Ask for something else** to change other fields or request separate proposals. + + + A generated prompt profile contains separate prompts for extraction and summaries. If your project uses one, saving extraction instructions through Copilot deactivates it. Review the replacement rules and test the affected behavior before using them in production. + + +## What Copilot cannot do + +Copilot cannot perform these actions, even in **Auto-apply** mode: + +- Create or delete API keys. +- Directly edit or delete existing memories. +- Export project data. +- Invite or remove organization or project members, or change their roles and permissions. +- Create or delete organizations or projects. +- Change billing details or subscription plans. + +Use the dashboard or the relevant platform API for these tasks. Copilot can explain the steps or point you to documentation, but it cannot carry out the actions. + +Copilot supports the managed Mem0 platform. It does not help configure or use the [self-hosted open-source library](/open-source/overview). + +## Example 1: Stop storing small talk, then test extraction + +This walkthrough uses a project where you have noticed greetings or small talk in stored memories. Use a development project when trying configuration changes, since a test user does not isolate project settings. + + + + Select the project, set **User** to `alice`, and ask: + + > Analyze the memories for user alice. + + Inspect the returned memories. Identify examples of small talk you want to exclude and useful facts you still want to keep. + + + With **Review changes** selected, ask: + + > Update my extraction instructions to ignore greetings and small talk. Keep the existing rules for durable user preferences. + + Check for a **Read project config** activity before reviewing the update. If it is missing, ask Copilot to read the current instructions first. If analysis reports insufficient data, ask it to use the rule you provided. You can also set the rule directly through [Custom instructions](/platform/features/custom-instructions). + + + Review the full replacement text. Keep existing rules your application needs. For this test, the relevant rules could look like: + + ```text + Remember the following: + + * The user's dietary preferences and food restrictions. + + Don't remember the following: + + * Greetings and small talk. + ``` + + Use **Edit** to adjust the wording, or **Ask for something else** to request a revision. + + Choose **Apply change** or **Apply with edits**, then inspect the result to confirm the instructions were saved. + + + Choose a new **User** ID for this test, such as `copilot-extraction-test-01`, and clear any other entity selections. Ask: + + > Add this as a user message for copilot-extraction-test-01: “Hi! How's your day? I prefer vegetarian meals and avoid peanuts.” + + Review the test-memory proposal and choose **Apply change**. + + + Adding a test memory writes to the selected project. It is not a dry run. Use a dedicated test user so you can find and remove the test data afterward. + + + + Expand **Add test memory** and inspect **Result**. A `PENDING` status means extraction is still running. Use the returned `event_id` with the [Get Event API](/api-reference/events/get-event) to check progress. Wait for `SUCCEEDED` before evaluating the output. If the event is `FAILED`, inspect its details before retrying. + + Then ask: + + > List all memories for user copilot-extraction-test-01. Then search that user's memories for dietary preferences. + + Check that the memories retain the vegetarian preference and peanut restriction, and exclude the greeting. Inspect the full list as well as search results: a relevant search can hide unwanted small-talk records. + + If the output is wrong, describe the mismatch and review another instruction change. Use a new test user for the next attempt so earlier memories do not affect the result. Remove test data afterward through the dashboard or [memory deletion API](/api-reference/memory/delete-memories). + + + +Test with new inputs after changing settings. Updating configuration is not a cleanup operation for existing memories. See [Custom instructions](/platform/features/custom-instructions) for guidance on writing extraction rules. + +## Example 2: Suggest categories and extraction instructions + +These workflows sample the selected project's data. Generating a suggestion does not update settings by itself. Copilot can then propose applying it, which follows the selected review mode. Use **Review changes** to inspect suggestions before they are saved. + +| Workflow | Data used | Example prompt | +| --- | --- | --- | +| Custom categories | Stored memories, excluding deleted memories. | “Suggest custom categories from this project's memories.” | +| Extraction instructions | Successful requests to add conversation data, including requests that produced no memories. | “Compare recent add requests with the extracted memories and suggest better extraction instructions.” | + +Category suggestions identify recurring themes. Review the names, descriptions, and examples. Applying a category list replaces the project's previous list; it does not add to it or re-tag existing memories. See [Custom categories](/platform/features/custom-categories) for project and per-call behavior. + +Extraction suggestions compare conversation inputs with what was extracted. One add request can produce several memories or none, so the number of add requests is different from the number of stored memories. Keep your application's existing requirements when reviewing the proposal. + +Both workflows require enough project data. If a suggestion fails because there is too little data, check the activity's **Result** for the current and required counts. You can still inspect memories, ask SDK/API questions, or provide your own rules instead of requesting a data-based suggestion. + +## Example 3: Adjust detail and language + +Ask Copilot to read the current settings, then request the change you need: + +- **Memory depth** controls the level of detail: **Less**, **Medium**, or **More detailed**. Try “Show my current memory depth, then propose More detailed memories.” For deciding *which facts* to retain, use extraction instructions. +- **Multilingual** behavior preserves the user's original language. Try “Enable multilingual behavior so memories preserve the language of the input.” Test it with a new conversation in the language your application uses. + +Both are project settings. Review the proposed values and test a fresh input after applying them. See [Organization and project settings](/api-reference/organizations-projects) for configuration through the API. + +## Example 4: Ask SDK and API questions + +Include your language and the task, for example: + +> Show me how to search memories for user alice with the managed Mem0 Python SDK. Link the documentation you used. + +Copilot can look up the official platform documentation. Check the **Browse mem0 docs** and **Read docs page** activities and open the cited pages. If an answer has no sources, ask for them before using the example. The [Platform quickstart](/platform/quickstart) covers adding and searching memories in code. + +## Resume a conversation and check message limits + +Use **History** to reopen your 50 most recently active chats for the selected project. Chats belong to the person who created them; other project members cannot open them. Use **New chat** to start a separate conversation, or **Delete chat** in history to remove one. Deleting a chat does not undo settings changes or remove test memories. + +Message allowances depend on the organization's plan and are shared across its projects and members. They reset at the start of each calendar month in UTC. + +For plans with a limit, a usage notice appears once 80% of the allowance is used. Below that point, no counter is shown. At the limit, new messages are disabled until the allowance resets or the plan is upgraded. Follow the notice's upgrade link to review plan options. + +Sending feedback through **Ask for something else** counts as a new message. Approving or declining a saved proposal without feedback does not use another message. Test additions and searches also use the platform APIs and remain subject to their normal quotas. From e4e0307ae6c13dfa0b11d77c8b66936e524aede1 Mon Sep 17 00:00:00 2001 From: Saket Aryan Date: Fri, 18 Sep 2026 13:23:05 +0530 Subject: [PATCH 14/61] fix(plugins): say what telemetry actually sends, and salt the hashes (#7322) --- docs/integrations/claude-code.mdx | 30 ++++ docs/integrations/deepseek-plugin.mdx | 2 +- docs/integrations/openclaw.mdx | 4 +- .../agent-plugin-core/python/telemetry.py | 138 +++++++++++++++++- .../skills/pause/SKILL.md.tmpl | 4 +- .../antigravity-plugin/core/telemetry.py | 138 +++++++++++++++++- .../antigravity-plugin/skills/pause/SKILL.md | 4 +- integrations/claude-code-plugin/README.md | 14 +- .../claude-code-plugin/core/telemetry.py | 138 +++++++++++++++++- .../claude-code-plugin/skills/pause/SKILL.md | 4 +- .../tests/test_telemetry.py | 112 ++++++++++++++ integrations/codex-plugin/core/telemetry.py | 138 +++++++++++++++++- .../codex-plugin/skills/pause/SKILL.md | 4 +- integrations/cursor-plugin/core/telemetry.py | 138 +++++++++++++++++- .../cursor-plugin/skills/pause/SKILL.md | 4 +- integrations/deepseek-plugin/README.md | 4 +- integrations/deepseek-plugin/src/index.ts | 6 +- integrations/kimi-plugin/core/telemetry.py | 138 +++++++++++++++++- .../kimi-plugin/skills/pause/SKILL.md | 4 +- .../mem0-agent-plugin/core/telemetry.py | 138 +++++++++++++++++- .../mem0-agent-plugin/skills/pause/SKILL.md | 4 +- integrations/mem0-strands/README.md | 8 +- integrations/zapier-mem0/README.md | 2 +- 23 files changed, 1120 insertions(+), 56 deletions(-) diff --git a/docs/integrations/claude-code.mdx b/docs/integrations/claude-code.mdx index 0b8e5a328..4277bb90e 100644 --- a/docs/integrations/claude-code.mdx +++ b/docs/integrations/claude-code.mdx @@ -172,6 +172,36 @@ claude plugin update mem0@mem0-plugins --scope user | Sidekick won't start | Must be in a Git repo. Check that your Claude Code version supports plugin agents and worktrees. | | Remove the plugin | `claude plugin uninstall mem0@mem0-plugins` | +## Telemetry + +The plugin sends usage events (which hook ran, timing, result counts, failure +types) so Mem0 can see what's used and what's breaking. + +These events are **not anonymous**. When an API key is configured, which +installing the plugin requires, they are sent under your Mem0 account email, +the same way the Python SDK and the CLI attribute theirs. Without a key they +are sent under a random per-machine id. + +Each event carries the event name, the plugin version, the harness it ran in, +your OS and Python version, and per-event properties describing what happened: +timings, counts, coarse outcome and failure labels, and which model was +configured. Repository and session identifiers are hashed with a random salt +generated on your machine, so they cannot be linked back to a repository name +or path. + +The exact set is enforced in code rather than by this list: every property is +filtered through a denylist of sensitive keys and credential-shaped values are +redacted before anything is sent. + +Prompts, memory text, queries, file paths, repository names, and API keys are +never sent. + +Turn it off: + +```bash +export MEM0_TELEMETRY=false +``` + Detailed MCP configuration for all clients diff --git a/docs/integrations/deepseek-plugin.mdx b/docs/integrations/deepseek-plugin.mdx index 16b8badaf..0242496e1 100644 --- a/docs/integrations/deepseek-plugin.mdx +++ b/docs/integrations/deepseek-plugin.mdx @@ -114,7 +114,7 @@ Both tools also accept optional per-call `userId`, `agentId`, and `runId` params ## Telemetry -Writes are tagged `source="DEEPSEEK_HARNESS"` so Mem0 can attribute usage to this integration. Anonymous usage events include operation names, durations, result counts, and coarse failure kinds. Queries, memory text, entity IDs, and API keys are never included. Set `MEM0_TELEMETRY=false` to opt out. +Writes are tagged `source="DEEPSEEK_HARNESS"` so Mem0 can attribute usage to this integration. Usage events include operation names, durations, result counts, and coarse failure kinds. They are **not anonymous**: when an API key is configured they are sent under your Mem0 account email, the same way the SDK attributes its own. Queries, memory text, entity IDs, and API keys are never included. Set `MEM0_TELEMETRY=false` to opt out. This plugin is a developer preview and tracks the evolving DeepSeek Harness plugin API. diff --git a/docs/integrations/openclaw.mdx b/docs/integrations/openclaw.mdx index a9642d444..fd7d449d9 100644 --- a/docs/integrations/openclaw.mdx +++ b/docs/integrations/openclaw.mdx @@ -481,7 +481,9 @@ Plugin config is stored in `~/.openclaw/openclaw.json` with file permissions `0o ### Telemetry -Anonymous usage telemetry (PostHog) is enabled by default to help improve the plugin. No conversation content or memory values are included, only event counts (recall, capture, tool usage, CLI commands). +Usage telemetry (PostHog) is enabled by default to help improve the plugin. No conversation content or memory values are included, only event counts (recall, capture, tool usage, CLI commands). + +These events are **not anonymous**. OpenClaw does not send your account email the way the SDK does, but it does send an unsalted SHA-256 hash of it, falling back to a hash of the API key and then to a random per-machine id. Mem0 holds the email the hash is derived from, so the hash identifies your account rather than concealing it. The first run that resolves an account also emits a PostHog `$identify`, which permanently merges any earlier random id into that identity. To opt out, set the environment variable: diff --git a/integrations/agent-plugin-core/python/telemetry.py b/integrations/agent-plugin-core/python/telemetry.py index 249595475..132de5b0c 100644 --- a/integrations/agent-plugin-core/python/telemetry.py +++ b/integrations/agent-plugin-core/python/telemetry.py @@ -1,5 +1,9 @@ #!/usr/bin/env python3 -"""Anonymous usage telemetry for Mem0 agent plugins. +"""Usage telemetry for Mem0 agent plugins. + +Events are linked to your Mem0 account email when an API key is configured, and +to a random per-machine id otherwise. Not anonymous — the Python SDK and CLI +attribute the same way. Hooks run on a 3-6 second budget and fire on every tool call, so recording never touches the network: `record` appends one JSON line to a local spool and returns. @@ -9,7 +13,8 @@ started once per session and again from the flush worker that is already detache Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false. Never sends prompts, memory text, queries, file paths, repository names, or API -keys: only event names, durations, counts, coarse outcomes, and salted hashes. +keys: only event names, durations, counts, coarse outcomes, and repo/session +identifiers hashed with a random per-install salt. """ from __future__ import annotations @@ -29,6 +34,7 @@ from typing import Any import memory_core +_salt_cache: str = "" _harness: str = "generic" _source_tag: str = "MEM0_PLUGIN" _PRIVATE_KEYS = { @@ -83,9 +89,126 @@ def is_enabled() -> bool: def _digest(value: str, length: int = 16) -> str: + """Unsalted digest. Only for values that are already secrets (API keys).""" return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length] +def _salt_path() -> Path: + return memory_core.data_dir() / "telemetry-salt" + + +def _install_salt() -> str: + """Random per-install salt, created once and memoized for the process. + + Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in + the identity file. Three reasons, all of which produced wrong data when this + lived in the identity dict: + + - Hooks are short-lived separate processes firing on every tool call, and + people run more than one agent window. A read-modify-write would let each + process mint its own salt, so one repository would hash several ways in the + window before a writer won. + - resolve_distinct_id holds a copy of the identity dict across a network call + to /v1/ping/, so whichever write landed second erased the other's key — + losing either the salt (repo_hash changes mid-stream) or the email (a + second $identify, splitting the person). + - Touching the identity file from record() would create it, and is_first_run + keys off that file, so recording an event would silently suppress the + install event. + + Published atomically, and there is deliberately no derived fallback. Creating + the file with O_CREAT|O_EXCL and then writing into it leaves a window where + the file exists and is empty, and a concurrent hook that reads it in that + window gets nothing. Falling back to a digest of the path would hand that + process a salt an attacker can compute, memoized for its whole run, which is + the privacy control this function exists to provide silently turning itself + off under load. The salt is written to a private temp file first and linked + into place, so the name either does not exist or already has the full value. + + Returns "" when it genuinely cannot persist. Callers omit the hash entirely + rather than emit an unsalted one. + """ + global _salt_cache + if _salt_cache: + return _salt_cache + + path = _salt_path() + # Read before writing. Hooks are separate processes firing on every tool + # call, so all but the first find the salt already published; going straight + # to create-fsync-link-unlink meant every one of them paid an fsync to + # discover that, on a path whose whole promise is appending a line and + # returning. + try: + _salt_cache = path.read_text(encoding="utf-8").strip() + if _salt_cache: + return _salt_cache + except OSError: + pass + + temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(handle, "w", encoding="utf-8") as stream: + stream.write(uuid.uuid4().hex) + stream.flush() + os.fsync(stream.fileno()) + try: + # Atomic claim: fails if another process already published one. + # os.link rather than replace, which would clobber theirs. + os.link(temporary, path) + except FileExistsError: + pass + except OSError: + # No hardlinks here (some network mounts, some container volumes). + # Claim the name directly instead. That reopens the empty-file + # window, but the window is now benign: a reader that lands in it + # gets "" and omits the hash for that process rather than caching a + # guessable one. Losing the hashes on every run of an entire + # filesystem is the worse failure. + try: + fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(fallback, "w", encoding="utf-8") as stream: + stream.write(temporary.read_text(encoding="utf-8")) + except OSError: + pass + except OSError: + pass + finally: + try: + temporary.unlink() + except OSError: + pass + + try: + _salt_cache = path.read_text(encoding="utf-8").strip() + except OSError: + _salt_cache = "" + return _salt_cache + + +def _scoped_digest(value: str, length: int = 16) -> str: + """Salted digest for values drawn from a guessable space. + + repo.identity is a git remote URL, or ``local:`` when there is + no remote — which normally contains the account username. Sixteen unsalted + hex characters over that input space is enumerable, so this is not a + privacy control without the salt. Salting per install keeps every + within-account join the analytics actually use and gives up only + cross-machine joins on the same repository, which nothing computes. + + Returns "" when there is no salt, so record() omits the property. An + unsalted digest over this input space is close to plaintext, and emitting one + under a name that implies it is hashed is worse than sending nothing. + """ + if not value: + return "" + salt = _install_salt() + if not salt: + return "" + return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length] + + def _safe_value(value: Any) -> Any: if isinstance(value, str): return memory_core.redact(value) @@ -174,10 +297,17 @@ def record( os=sys.platform, python_version=platform.python_version(), ) + # Assigned only when the digest is real. _scoped_digest returns "" when + # the salt could not be persisted, and an empty property is worse than an + # absent one: it survives the None filter below and reads as a value. if repo is not None: - properties["repo_hash"] = _digest(getattr(repo, "identity", "")) + repo_hash = _scoped_digest(getattr(repo, "identity", "")) + if repo_hash: + properties["repo_hash"] = repo_hash if session_id: - properties["session_hash"] = _digest(session_id) + session_hash = _scoped_digest(session_id) + if session_hash: + properties["session_hash"] = session_hash line = json.dumps( { "event": f"{EVENT_PREFIX}.{event}", diff --git a/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl b/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl index 9cc720c7a..569305ec7 100644 --- a/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl +++ b/integrations/agent-plugin-core/skills/pause/SKILL.md.tmpl @@ -7,8 +7,8 @@ disable-model-invocation: true # Pause memory capture To pause (hooks stop capturing and sending session content; a minimal -anonymous telemetry ping still fires at session start unless -`MEM0_TELEMETRY=false`): +telemetry ping still fires at session start, under your Mem0 account email, +unless `MEM0_TELEMETRY=false`): ```bash python3 "{{PLUGIN_ROOT}}/core/memory_cli.py" --harness "{{HARNESS_ID}}" {{PLUGIN_DATA_ARG}} pause diff --git a/integrations/antigravity-plugin/core/telemetry.py b/integrations/antigravity-plugin/core/telemetry.py index 249595475..132de5b0c 100644 --- a/integrations/antigravity-plugin/core/telemetry.py +++ b/integrations/antigravity-plugin/core/telemetry.py @@ -1,5 +1,9 @@ #!/usr/bin/env python3 -"""Anonymous usage telemetry for Mem0 agent plugins. +"""Usage telemetry for Mem0 agent plugins. + +Events are linked to your Mem0 account email when an API key is configured, and +to a random per-machine id otherwise. Not anonymous — the Python SDK and CLI +attribute the same way. Hooks run on a 3-6 second budget and fire on every tool call, so recording never touches the network: `record` appends one JSON line to a local spool and returns. @@ -9,7 +13,8 @@ started once per session and again from the flush worker that is already detache Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false. Never sends prompts, memory text, queries, file paths, repository names, or API -keys: only event names, durations, counts, coarse outcomes, and salted hashes. +keys: only event names, durations, counts, coarse outcomes, and repo/session +identifiers hashed with a random per-install salt. """ from __future__ import annotations @@ -29,6 +34,7 @@ from typing import Any import memory_core +_salt_cache: str = "" _harness: str = "generic" _source_tag: str = "MEM0_PLUGIN" _PRIVATE_KEYS = { @@ -83,9 +89,126 @@ def is_enabled() -> bool: def _digest(value: str, length: int = 16) -> str: + """Unsalted digest. Only for values that are already secrets (API keys).""" return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length] +def _salt_path() -> Path: + return memory_core.data_dir() / "telemetry-salt" + + +def _install_salt() -> str: + """Random per-install salt, created once and memoized for the process. + + Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in + the identity file. Three reasons, all of which produced wrong data when this + lived in the identity dict: + + - Hooks are short-lived separate processes firing on every tool call, and + people run more than one agent window. A read-modify-write would let each + process mint its own salt, so one repository would hash several ways in the + window before a writer won. + - resolve_distinct_id holds a copy of the identity dict across a network call + to /v1/ping/, so whichever write landed second erased the other's key — + losing either the salt (repo_hash changes mid-stream) or the email (a + second $identify, splitting the person). + - Touching the identity file from record() would create it, and is_first_run + keys off that file, so recording an event would silently suppress the + install event. + + Published atomically, and there is deliberately no derived fallback. Creating + the file with O_CREAT|O_EXCL and then writing into it leaves a window where + the file exists and is empty, and a concurrent hook that reads it in that + window gets nothing. Falling back to a digest of the path would hand that + process a salt an attacker can compute, memoized for its whole run, which is + the privacy control this function exists to provide silently turning itself + off under load. The salt is written to a private temp file first and linked + into place, so the name either does not exist or already has the full value. + + Returns "" when it genuinely cannot persist. Callers omit the hash entirely + rather than emit an unsalted one. + """ + global _salt_cache + if _salt_cache: + return _salt_cache + + path = _salt_path() + # Read before writing. Hooks are separate processes firing on every tool + # call, so all but the first find the salt already published; going straight + # to create-fsync-link-unlink meant every one of them paid an fsync to + # discover that, on a path whose whole promise is appending a line and + # returning. + try: + _salt_cache = path.read_text(encoding="utf-8").strip() + if _salt_cache: + return _salt_cache + except OSError: + pass + + temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(handle, "w", encoding="utf-8") as stream: + stream.write(uuid.uuid4().hex) + stream.flush() + os.fsync(stream.fileno()) + try: + # Atomic claim: fails if another process already published one. + # os.link rather than replace, which would clobber theirs. + os.link(temporary, path) + except FileExistsError: + pass + except OSError: + # No hardlinks here (some network mounts, some container volumes). + # Claim the name directly instead. That reopens the empty-file + # window, but the window is now benign: a reader that lands in it + # gets "" and omits the hash for that process rather than caching a + # guessable one. Losing the hashes on every run of an entire + # filesystem is the worse failure. + try: + fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(fallback, "w", encoding="utf-8") as stream: + stream.write(temporary.read_text(encoding="utf-8")) + except OSError: + pass + except OSError: + pass + finally: + try: + temporary.unlink() + except OSError: + pass + + try: + _salt_cache = path.read_text(encoding="utf-8").strip() + except OSError: + _salt_cache = "" + return _salt_cache + + +def _scoped_digest(value: str, length: int = 16) -> str: + """Salted digest for values drawn from a guessable space. + + repo.identity is a git remote URL, or ``local:`` when there is + no remote — which normally contains the account username. Sixteen unsalted + hex characters over that input space is enumerable, so this is not a + privacy control without the salt. Salting per install keeps every + within-account join the analytics actually use and gives up only + cross-machine joins on the same repository, which nothing computes. + + Returns "" when there is no salt, so record() omits the property. An + unsalted digest over this input space is close to plaintext, and emitting one + under a name that implies it is hashed is worse than sending nothing. + """ + if not value: + return "" + salt = _install_salt() + if not salt: + return "" + return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length] + + def _safe_value(value: Any) -> Any: if isinstance(value, str): return memory_core.redact(value) @@ -174,10 +297,17 @@ def record( os=sys.platform, python_version=platform.python_version(), ) + # Assigned only when the digest is real. _scoped_digest returns "" when + # the salt could not be persisted, and an empty property is worse than an + # absent one: it survives the None filter below and reads as a value. if repo is not None: - properties["repo_hash"] = _digest(getattr(repo, "identity", "")) + repo_hash = _scoped_digest(getattr(repo, "identity", "")) + if repo_hash: + properties["repo_hash"] = repo_hash if session_id: - properties["session_hash"] = _digest(session_id) + session_hash = _scoped_digest(session_id) + if session_hash: + properties["session_hash"] = session_hash line = json.dumps( { "event": f"{EVENT_PREFIX}.{event}", diff --git a/integrations/antigravity-plugin/skills/pause/SKILL.md b/integrations/antigravity-plugin/skills/pause/SKILL.md index e88f7d315..77b4146b6 100644 --- a/integrations/antigravity-plugin/skills/pause/SKILL.md +++ b/integrations/antigravity-plugin/skills/pause/SKILL.md @@ -7,8 +7,8 @@ disable-model-invocation: true # Pause memory capture To pause (hooks stop capturing and sending session content; a minimal -anonymous telemetry ping still fires at session start unless -`MEM0_TELEMETRY=false`): +telemetry ping still fires at session start, under your Mem0 account email, +unless `MEM0_TELEMETRY=false`): ```bash python3 "${ANTIGRAVITY_PLUGIN_ROOT}/core/memory_cli.py" --harness "antigravity" pause diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index 130460b17..b58f54c79 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -136,13 +136,23 @@ Local data lives in `${CLAUDE_PLUGIN_DATA}`: - `pending/`: sessions waiting to be sent to Mem0 (retried after interruption) - `flush-worker.log`: whether memory creation succeeded - `plugin-errors.log`: hook errors (no credentials) -- `telemetry.jsonl` / `telemetry-identity.json`: anonymous usage events +- `telemetry.jsonl` / `telemetry-identity.json`: usage events and the id they are sent under +- `telemetry-salt`: random per-install salt for the repo and session hashes +- `install-state.json`: records that install has been counted once on this machine Mem0 receives captured user messages, Claude's answers, sidekick assignments and completed responses, and changed file paths. When a failed command is recorded, extraction can also include bounded command details and results. Complete files and general tool output stay on your machine. Values that look like credentials are redacted before anything is sent. ## Telemetry -Anonymous usage events (which hook ran, timing, result counts, failure types) so Mem0 can identify what's used and what's breaking. Repo and session IDs are hashed before leaving your machine. Prompts, memory text, file paths, tool output, and API keys are never sent. +Usage events (which hook ran, timing, result counts, failure types) so Mem0 can identify what's used and what's breaking. + +**These events are not anonymous.** When an API key is configured — which installing the plugin requires — events are sent under your Mem0 account email, the same way the Python SDK and the CLI attribute theirs. Without a key they are sent under a random per-machine id. + +What each event carries: the event name, the plugin version, the harness it ran in, your OS and Python version, and per-event properties describing what happened — timings, counts, coarse outcome and failure labels, and which model was configured. Repository and session identifiers are hashed with a random salt generated on your machine, so they cannot be linked back to a repository name or path. + +Rather than restate a list that drifts, the exact set is enforced in code: `telemetry.record` filters every property through a denylist of sensitive keys and redacts credential-shaped values. See `_PRIVATE_KEYS` in `core/telemetry.py`. + +Prompts, memory text, queries, file paths, repository names, and API keys are never sent. Turn it off: diff --git a/integrations/claude-code-plugin/core/telemetry.py b/integrations/claude-code-plugin/core/telemetry.py index 249595475..132de5b0c 100644 --- a/integrations/claude-code-plugin/core/telemetry.py +++ b/integrations/claude-code-plugin/core/telemetry.py @@ -1,5 +1,9 @@ #!/usr/bin/env python3 -"""Anonymous usage telemetry for Mem0 agent plugins. +"""Usage telemetry for Mem0 agent plugins. + +Events are linked to your Mem0 account email when an API key is configured, and +to a random per-machine id otherwise. Not anonymous — the Python SDK and CLI +attribute the same way. Hooks run on a 3-6 second budget and fire on every tool call, so recording never touches the network: `record` appends one JSON line to a local spool and returns. @@ -9,7 +13,8 @@ started once per session and again from the flush worker that is already detache Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false. Never sends prompts, memory text, queries, file paths, repository names, or API -keys: only event names, durations, counts, coarse outcomes, and salted hashes. +keys: only event names, durations, counts, coarse outcomes, and repo/session +identifiers hashed with a random per-install salt. """ from __future__ import annotations @@ -29,6 +34,7 @@ from typing import Any import memory_core +_salt_cache: str = "" _harness: str = "generic" _source_tag: str = "MEM0_PLUGIN" _PRIVATE_KEYS = { @@ -83,9 +89,126 @@ def is_enabled() -> bool: def _digest(value: str, length: int = 16) -> str: + """Unsalted digest. Only for values that are already secrets (API keys).""" return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length] +def _salt_path() -> Path: + return memory_core.data_dir() / "telemetry-salt" + + +def _install_salt() -> str: + """Random per-install salt, created once and memoized for the process. + + Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in + the identity file. Three reasons, all of which produced wrong data when this + lived in the identity dict: + + - Hooks are short-lived separate processes firing on every tool call, and + people run more than one agent window. A read-modify-write would let each + process mint its own salt, so one repository would hash several ways in the + window before a writer won. + - resolve_distinct_id holds a copy of the identity dict across a network call + to /v1/ping/, so whichever write landed second erased the other's key — + losing either the salt (repo_hash changes mid-stream) or the email (a + second $identify, splitting the person). + - Touching the identity file from record() would create it, and is_first_run + keys off that file, so recording an event would silently suppress the + install event. + + Published atomically, and there is deliberately no derived fallback. Creating + the file with O_CREAT|O_EXCL and then writing into it leaves a window where + the file exists and is empty, and a concurrent hook that reads it in that + window gets nothing. Falling back to a digest of the path would hand that + process a salt an attacker can compute, memoized for its whole run, which is + the privacy control this function exists to provide silently turning itself + off under load. The salt is written to a private temp file first and linked + into place, so the name either does not exist or already has the full value. + + Returns "" when it genuinely cannot persist. Callers omit the hash entirely + rather than emit an unsalted one. + """ + global _salt_cache + if _salt_cache: + return _salt_cache + + path = _salt_path() + # Read before writing. Hooks are separate processes firing on every tool + # call, so all but the first find the salt already published; going straight + # to create-fsync-link-unlink meant every one of them paid an fsync to + # discover that, on a path whose whole promise is appending a line and + # returning. + try: + _salt_cache = path.read_text(encoding="utf-8").strip() + if _salt_cache: + return _salt_cache + except OSError: + pass + + temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(handle, "w", encoding="utf-8") as stream: + stream.write(uuid.uuid4().hex) + stream.flush() + os.fsync(stream.fileno()) + try: + # Atomic claim: fails if another process already published one. + # os.link rather than replace, which would clobber theirs. + os.link(temporary, path) + except FileExistsError: + pass + except OSError: + # No hardlinks here (some network mounts, some container volumes). + # Claim the name directly instead. That reopens the empty-file + # window, but the window is now benign: a reader that lands in it + # gets "" and omits the hash for that process rather than caching a + # guessable one. Losing the hashes on every run of an entire + # filesystem is the worse failure. + try: + fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(fallback, "w", encoding="utf-8") as stream: + stream.write(temporary.read_text(encoding="utf-8")) + except OSError: + pass + except OSError: + pass + finally: + try: + temporary.unlink() + except OSError: + pass + + try: + _salt_cache = path.read_text(encoding="utf-8").strip() + except OSError: + _salt_cache = "" + return _salt_cache + + +def _scoped_digest(value: str, length: int = 16) -> str: + """Salted digest for values drawn from a guessable space. + + repo.identity is a git remote URL, or ``local:`` when there is + no remote — which normally contains the account username. Sixteen unsalted + hex characters over that input space is enumerable, so this is not a + privacy control without the salt. Salting per install keeps every + within-account join the analytics actually use and gives up only + cross-machine joins on the same repository, which nothing computes. + + Returns "" when there is no salt, so record() omits the property. An + unsalted digest over this input space is close to plaintext, and emitting one + under a name that implies it is hashed is worse than sending nothing. + """ + if not value: + return "" + salt = _install_salt() + if not salt: + return "" + return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length] + + def _safe_value(value: Any) -> Any: if isinstance(value, str): return memory_core.redact(value) @@ -174,10 +297,17 @@ def record( os=sys.platform, python_version=platform.python_version(), ) + # Assigned only when the digest is real. _scoped_digest returns "" when + # the salt could not be persisted, and an empty property is worse than an + # absent one: it survives the None filter below and reads as a value. if repo is not None: - properties["repo_hash"] = _digest(getattr(repo, "identity", "")) + repo_hash = _scoped_digest(getattr(repo, "identity", "")) + if repo_hash: + properties["repo_hash"] = repo_hash if session_id: - properties["session_hash"] = _digest(session_id) + session_hash = _scoped_digest(session_id) + if session_hash: + properties["session_hash"] = session_hash line = json.dumps( { "event": f"{EVENT_PREFIX}.{event}", diff --git a/integrations/claude-code-plugin/skills/pause/SKILL.md b/integrations/claude-code-plugin/skills/pause/SKILL.md index 5aef04f39..ce69d13d2 100644 --- a/integrations/claude-code-plugin/skills/pause/SKILL.md +++ b/integrations/claude-code-plugin/skills/pause/SKILL.md @@ -7,8 +7,8 @@ disable-model-invocation: true # Pause memory capture To pause (hooks stop capturing and sending session content; a minimal -anonymous telemetry ping still fires at session start unless -`MEM0_TELEMETRY=false`): +telemetry ping still fires at session start, under your Mem0 account email, +unless `MEM0_TELEMETRY=false`): ```bash python3 "${CLAUDE_PLUGIN_ROOT}/core/memory_cli.py" --harness "claude-code" --plugin-data-dir "${CLAUDE_PLUGIN_DATA}" pause diff --git a/integrations/claude-code-plugin/tests/test_telemetry.py b/integrations/claude-code-plugin/tests/test_telemetry.py index 0ae280b19..6029fa98a 100644 --- a/integrations/claude-code-plugin/tests/test_telemetry.py +++ b/integrations/claude-code-plugin/tests/test_telemetry.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import os import sys from pathlib import Path from unittest.mock import patch @@ -273,3 +274,114 @@ def test_spawn_flush_does_nothing_without_a_spool(isolated_env): with patch.object(telemetry.subprocess, "Popen") as popen: assert telemetry.spawn_flush() is True popen.assert_called_once() + + +def test_salt_is_stable_across_processes(isolated_env): + """Hooks are separate short-lived processes; one repo must hash one way. + + An unlocked read-modify-write let each process mint its own salt, so a + repository hashed several ways in the window before one writer won. + """ + import subprocess as sp + + core = str(Path(__file__).resolve().parents[1] / "core") + script = ( + f"import sys; sys.path.insert(0, {core!r})\n" + "import telemetry\n" + "print(telemetry._install_salt())" + ) + env = {**os.environ, "MEM0_CODE_DATA_DIR": str(memory_core.data_dir())} + salts = { + sp.run([sys.executable, "-c", script], capture_output=True, text=True, env=env).stdout.strip() + for _ in range(4) + } + assert len(salts) == 1, f"one repo hashed {len(salts)} ways: {salts}" + + +def test_salt_does_not_touch_the_identity_file(isolated_env): + """The identity file is is_first_run's marker and the sender's email store. + + Writing the salt into it would create it from record(), suppressing the + install event, and would race resolve_distinct_id, which holds a stale copy + of that dict across a network call. + """ + telemetry._install_salt() + assert not telemetry._identity_path().exists() + + +def test_no_salt_means_no_hash_rather_than_an_unsalted_one(isolated_env, monkeypatch): + """A read-only data dir drops the property; it must not emit a weak digest. + + The previous fallback was a digest of the salt file's own path, which an + attacker can compute, memoized for the whole process. A property named + repo_hash carrying an effectively unsalted digest is worse than no property: + it reads as protected and is not. + """ + telemetry._salt_cache = "" + monkeypatch.setattr(telemetry.os, "open", lambda *a, **k: (_ for _ in ()).throw(OSError("read-only"))) + + assert telemetry._install_salt() == "" + assert telemetry._scoped_digest("git@github.com:acme/secret.git") == "" + + +def test_a_half_written_salt_is_never_visible_to_another_process(isolated_env, monkeypatch): + """The window this closes: file created, value not yet written. + + O_CREAT|O_EXCL then write leaves the name present and empty in between. A + hook reading it there used to get "", fall back to the path digest and cache + that for its whole run, so the same repo hashed two ways depending on timing. + Publishing by link means the name either does not exist or is complete. + """ + telemetry._salt_cache = "" + salt_path = telemetry._salt_path() + observed = [] + + real_link = telemetry.os.link + + def observing_link(source, target): + # Stand where the racing reader stands: after the temp file is written, + # before the real name exists. + observed.append(salt_path.exists()) + return real_link(source, target) + + monkeypatch.setattr(telemetry.os, "link", observing_link) + salt = telemetry._install_salt() + + assert observed == [False], "the salt name existed before it held a value" + assert len(salt) == 32 + assert salt_path.read_text(encoding="utf-8").strip() == salt + + +def test_a_filesystem_without_hardlinks_still_gets_a_salt(isolated_env, monkeypatch): + """Publishing by link must not become a silent loss of the hashes. + + Some network mounts and container volumes reject os.link. Returning "" + there would drop repo_hash and session_hash on every run for that whole + cohort, which is a bigger loss than the narrow race the link closes. + """ + telemetry._salt_cache = "" + monkeypatch.setattr( + telemetry.os, "link", lambda src, dst: (_ for _ in ()).throw(OSError(38, "not implemented")) + ) + + salt = telemetry._install_salt() + + assert len(salt) == 32, "no salt on a filesystem without hardlinks" + assert telemetry._salt_path().read_text(encoding="utf-8").strip() == salt + assert telemetry._scoped_digest("git@github.com:acme/x.git") != "" + assert not list(telemetry._salt_path().parent.glob("telemetry-salt.*.tmp")) + + +def test_a_concurrent_writer_does_not_clobber_the_published_salt(isolated_env): + """Second process to finish must adopt the first one's salt, not replace it. + + os.link rather than os.replace is what makes losing the race harmless. + """ + telemetry._salt_cache = "" + first = telemetry._install_salt() + + telemetry._salt_cache = "" + second = telemetry._install_salt() + + assert second == first + assert not list(telemetry._salt_path().parent.glob("telemetry-salt.*.tmp")), "temp file left behind" diff --git a/integrations/codex-plugin/core/telemetry.py b/integrations/codex-plugin/core/telemetry.py index 249595475..132de5b0c 100644 --- a/integrations/codex-plugin/core/telemetry.py +++ b/integrations/codex-plugin/core/telemetry.py @@ -1,5 +1,9 @@ #!/usr/bin/env python3 -"""Anonymous usage telemetry for Mem0 agent plugins. +"""Usage telemetry for Mem0 agent plugins. + +Events are linked to your Mem0 account email when an API key is configured, and +to a random per-machine id otherwise. Not anonymous — the Python SDK and CLI +attribute the same way. Hooks run on a 3-6 second budget and fire on every tool call, so recording never touches the network: `record` appends one JSON line to a local spool and returns. @@ -9,7 +13,8 @@ started once per session and again from the flush worker that is already detache Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false. Never sends prompts, memory text, queries, file paths, repository names, or API -keys: only event names, durations, counts, coarse outcomes, and salted hashes. +keys: only event names, durations, counts, coarse outcomes, and repo/session +identifiers hashed with a random per-install salt. """ from __future__ import annotations @@ -29,6 +34,7 @@ from typing import Any import memory_core +_salt_cache: str = "" _harness: str = "generic" _source_tag: str = "MEM0_PLUGIN" _PRIVATE_KEYS = { @@ -83,9 +89,126 @@ def is_enabled() -> bool: def _digest(value: str, length: int = 16) -> str: + """Unsalted digest. Only for values that are already secrets (API keys).""" return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length] +def _salt_path() -> Path: + return memory_core.data_dir() / "telemetry-salt" + + +def _install_salt() -> str: + """Random per-install salt, created once and memoized for the process. + + Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in + the identity file. Three reasons, all of which produced wrong data when this + lived in the identity dict: + + - Hooks are short-lived separate processes firing on every tool call, and + people run more than one agent window. A read-modify-write would let each + process mint its own salt, so one repository would hash several ways in the + window before a writer won. + - resolve_distinct_id holds a copy of the identity dict across a network call + to /v1/ping/, so whichever write landed second erased the other's key — + losing either the salt (repo_hash changes mid-stream) or the email (a + second $identify, splitting the person). + - Touching the identity file from record() would create it, and is_first_run + keys off that file, so recording an event would silently suppress the + install event. + + Published atomically, and there is deliberately no derived fallback. Creating + the file with O_CREAT|O_EXCL and then writing into it leaves a window where + the file exists and is empty, and a concurrent hook that reads it in that + window gets nothing. Falling back to a digest of the path would hand that + process a salt an attacker can compute, memoized for its whole run, which is + the privacy control this function exists to provide silently turning itself + off under load. The salt is written to a private temp file first and linked + into place, so the name either does not exist or already has the full value. + + Returns "" when it genuinely cannot persist. Callers omit the hash entirely + rather than emit an unsalted one. + """ + global _salt_cache + if _salt_cache: + return _salt_cache + + path = _salt_path() + # Read before writing. Hooks are separate processes firing on every tool + # call, so all but the first find the salt already published; going straight + # to create-fsync-link-unlink meant every one of them paid an fsync to + # discover that, on a path whose whole promise is appending a line and + # returning. + try: + _salt_cache = path.read_text(encoding="utf-8").strip() + if _salt_cache: + return _salt_cache + except OSError: + pass + + temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(handle, "w", encoding="utf-8") as stream: + stream.write(uuid.uuid4().hex) + stream.flush() + os.fsync(stream.fileno()) + try: + # Atomic claim: fails if another process already published one. + # os.link rather than replace, which would clobber theirs. + os.link(temporary, path) + except FileExistsError: + pass + except OSError: + # No hardlinks here (some network mounts, some container volumes). + # Claim the name directly instead. That reopens the empty-file + # window, but the window is now benign: a reader that lands in it + # gets "" and omits the hash for that process rather than caching a + # guessable one. Losing the hashes on every run of an entire + # filesystem is the worse failure. + try: + fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(fallback, "w", encoding="utf-8") as stream: + stream.write(temporary.read_text(encoding="utf-8")) + except OSError: + pass + except OSError: + pass + finally: + try: + temporary.unlink() + except OSError: + pass + + try: + _salt_cache = path.read_text(encoding="utf-8").strip() + except OSError: + _salt_cache = "" + return _salt_cache + + +def _scoped_digest(value: str, length: int = 16) -> str: + """Salted digest for values drawn from a guessable space. + + repo.identity is a git remote URL, or ``local:`` when there is + no remote — which normally contains the account username. Sixteen unsalted + hex characters over that input space is enumerable, so this is not a + privacy control without the salt. Salting per install keeps every + within-account join the analytics actually use and gives up only + cross-machine joins on the same repository, which nothing computes. + + Returns "" when there is no salt, so record() omits the property. An + unsalted digest over this input space is close to plaintext, and emitting one + under a name that implies it is hashed is worse than sending nothing. + """ + if not value: + return "" + salt = _install_salt() + if not salt: + return "" + return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length] + + def _safe_value(value: Any) -> Any: if isinstance(value, str): return memory_core.redact(value) @@ -174,10 +297,17 @@ def record( os=sys.platform, python_version=platform.python_version(), ) + # Assigned only when the digest is real. _scoped_digest returns "" when + # the salt could not be persisted, and an empty property is worse than an + # absent one: it survives the None filter below and reads as a value. if repo is not None: - properties["repo_hash"] = _digest(getattr(repo, "identity", "")) + repo_hash = _scoped_digest(getattr(repo, "identity", "")) + if repo_hash: + properties["repo_hash"] = repo_hash if session_id: - properties["session_hash"] = _digest(session_id) + session_hash = _scoped_digest(session_id) + if session_hash: + properties["session_hash"] = session_hash line = json.dumps( { "event": f"{EVENT_PREFIX}.{event}", diff --git a/integrations/codex-plugin/skills/pause/SKILL.md b/integrations/codex-plugin/skills/pause/SKILL.md index d8a52f47b..c8f8ddd5f 100644 --- a/integrations/codex-plugin/skills/pause/SKILL.md +++ b/integrations/codex-plugin/skills/pause/SKILL.md @@ -7,8 +7,8 @@ disable-model-invocation: true # Pause memory capture To pause (hooks stop capturing and sending session content; a minimal -anonymous telemetry ping still fires at session start unless -`MEM0_TELEMETRY=false`): +telemetry ping still fires at session start, under your Mem0 account email, +unless `MEM0_TELEMETRY=false`): ```bash python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "codex" --plugin-data-dir "${PLUGIN_DATA}" pause diff --git a/integrations/cursor-plugin/core/telemetry.py b/integrations/cursor-plugin/core/telemetry.py index 249595475..132de5b0c 100644 --- a/integrations/cursor-plugin/core/telemetry.py +++ b/integrations/cursor-plugin/core/telemetry.py @@ -1,5 +1,9 @@ #!/usr/bin/env python3 -"""Anonymous usage telemetry for Mem0 agent plugins. +"""Usage telemetry for Mem0 agent plugins. + +Events are linked to your Mem0 account email when an API key is configured, and +to a random per-machine id otherwise. Not anonymous — the Python SDK and CLI +attribute the same way. Hooks run on a 3-6 second budget and fire on every tool call, so recording never touches the network: `record` appends one JSON line to a local spool and returns. @@ -9,7 +13,8 @@ started once per session and again from the flush worker that is already detache Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false. Never sends prompts, memory text, queries, file paths, repository names, or API -keys: only event names, durations, counts, coarse outcomes, and salted hashes. +keys: only event names, durations, counts, coarse outcomes, and repo/session +identifiers hashed with a random per-install salt. """ from __future__ import annotations @@ -29,6 +34,7 @@ from typing import Any import memory_core +_salt_cache: str = "" _harness: str = "generic" _source_tag: str = "MEM0_PLUGIN" _PRIVATE_KEYS = { @@ -83,9 +89,126 @@ def is_enabled() -> bool: def _digest(value: str, length: int = 16) -> str: + """Unsalted digest. Only for values that are already secrets (API keys).""" return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length] +def _salt_path() -> Path: + return memory_core.data_dir() / "telemetry-salt" + + +def _install_salt() -> str: + """Random per-install salt, created once and memoized for the process. + + Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in + the identity file. Three reasons, all of which produced wrong data when this + lived in the identity dict: + + - Hooks are short-lived separate processes firing on every tool call, and + people run more than one agent window. A read-modify-write would let each + process mint its own salt, so one repository would hash several ways in the + window before a writer won. + - resolve_distinct_id holds a copy of the identity dict across a network call + to /v1/ping/, so whichever write landed second erased the other's key — + losing either the salt (repo_hash changes mid-stream) or the email (a + second $identify, splitting the person). + - Touching the identity file from record() would create it, and is_first_run + keys off that file, so recording an event would silently suppress the + install event. + + Published atomically, and there is deliberately no derived fallback. Creating + the file with O_CREAT|O_EXCL and then writing into it leaves a window where + the file exists and is empty, and a concurrent hook that reads it in that + window gets nothing. Falling back to a digest of the path would hand that + process a salt an attacker can compute, memoized for its whole run, which is + the privacy control this function exists to provide silently turning itself + off under load. The salt is written to a private temp file first and linked + into place, so the name either does not exist or already has the full value. + + Returns "" when it genuinely cannot persist. Callers omit the hash entirely + rather than emit an unsalted one. + """ + global _salt_cache + if _salt_cache: + return _salt_cache + + path = _salt_path() + # Read before writing. Hooks are separate processes firing on every tool + # call, so all but the first find the salt already published; going straight + # to create-fsync-link-unlink meant every one of them paid an fsync to + # discover that, on a path whose whole promise is appending a line and + # returning. + try: + _salt_cache = path.read_text(encoding="utf-8").strip() + if _salt_cache: + return _salt_cache + except OSError: + pass + + temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(handle, "w", encoding="utf-8") as stream: + stream.write(uuid.uuid4().hex) + stream.flush() + os.fsync(stream.fileno()) + try: + # Atomic claim: fails if another process already published one. + # os.link rather than replace, which would clobber theirs. + os.link(temporary, path) + except FileExistsError: + pass + except OSError: + # No hardlinks here (some network mounts, some container volumes). + # Claim the name directly instead. That reopens the empty-file + # window, but the window is now benign: a reader that lands in it + # gets "" and omits the hash for that process rather than caching a + # guessable one. Losing the hashes on every run of an entire + # filesystem is the worse failure. + try: + fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(fallback, "w", encoding="utf-8") as stream: + stream.write(temporary.read_text(encoding="utf-8")) + except OSError: + pass + except OSError: + pass + finally: + try: + temporary.unlink() + except OSError: + pass + + try: + _salt_cache = path.read_text(encoding="utf-8").strip() + except OSError: + _salt_cache = "" + return _salt_cache + + +def _scoped_digest(value: str, length: int = 16) -> str: + """Salted digest for values drawn from a guessable space. + + repo.identity is a git remote URL, or ``local:`` when there is + no remote — which normally contains the account username. Sixteen unsalted + hex characters over that input space is enumerable, so this is not a + privacy control without the salt. Salting per install keeps every + within-account join the analytics actually use and gives up only + cross-machine joins on the same repository, which nothing computes. + + Returns "" when there is no salt, so record() omits the property. An + unsalted digest over this input space is close to plaintext, and emitting one + under a name that implies it is hashed is worse than sending nothing. + """ + if not value: + return "" + salt = _install_salt() + if not salt: + return "" + return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length] + + def _safe_value(value: Any) -> Any: if isinstance(value, str): return memory_core.redact(value) @@ -174,10 +297,17 @@ def record( os=sys.platform, python_version=platform.python_version(), ) + # Assigned only when the digest is real. _scoped_digest returns "" when + # the salt could not be persisted, and an empty property is worse than an + # absent one: it survives the None filter below and reads as a value. if repo is not None: - properties["repo_hash"] = _digest(getattr(repo, "identity", "")) + repo_hash = _scoped_digest(getattr(repo, "identity", "")) + if repo_hash: + properties["repo_hash"] = repo_hash if session_id: - properties["session_hash"] = _digest(session_id) + session_hash = _scoped_digest(session_id) + if session_hash: + properties["session_hash"] = session_hash line = json.dumps( { "event": f"{EVENT_PREFIX}.{event}", diff --git a/integrations/cursor-plugin/skills/pause/SKILL.md b/integrations/cursor-plugin/skills/pause/SKILL.md index 634385145..17384c368 100644 --- a/integrations/cursor-plugin/skills/pause/SKILL.md +++ b/integrations/cursor-plugin/skills/pause/SKILL.md @@ -7,8 +7,8 @@ disable-model-invocation: true # Pause memory capture To pause (hooks stop capturing and sending session content; a minimal -anonymous telemetry ping still fires at session start unless -`MEM0_TELEMETRY=false`): +telemetry ping still fires at session start, under your Mem0 account email, +unless `MEM0_TELEMETRY=false`): ```bash python3 "${CURSOR_PLUGIN_ROOT}/core/memory_cli.py" --harness "cursor" pause diff --git a/integrations/deepseek-plugin/README.md b/integrations/deepseek-plugin/README.md index 93e5f563f..d5cb3345a 100644 --- a/integrations/deepseek-plugin/README.md +++ b/integrations/deepseek-plugin/README.md @@ -86,9 +86,9 @@ Per-call `userId` overrides are rejected unless the operator enables `allowUserO ## Telemetry -Writes are tagged `source="DEEPSEEK_HARNESS"` so Mem0's backend can attribute usage to this integration. For it to surface by name (rather than bucketing into `OTHERS`), `DEEPSEEK_HARNESS` must be present in the backend's `KNOWN_EVENT_SOURCES` allowlist, a one-line platform change matching the existing `ZAPIER` / `STRANDS` sources. +Writes are tagged `source="DEEPSEEK_HARNESS"`. That value has to exist in the backend's `EventSource` enum for usage to surface by name; until it does, these writes read as `OTHERS`. It is added by [mem0ai/platform#3602](https://github.com/mem0ai/platform/pull/3602), which has to ship before this claim is true. -The plugin also sends anonymous usage events (which tool ran, duration, result counts, coarse failure kind) so Mem0 can tell how the plugin is used and where it breaks. Queries, memory text, and entity ids are never sent. Turn it off with `MEM0_TELEMETRY=false`. +The plugin also sends usage events (which tool ran, duration, result counts, coarse failure kind) so Mem0 can tell how the plugin is used and where it breaks. These are **not anonymous**: when an API key is configured they are sent under your Mem0 account email, the same way the SDK attributes its own. Queries, memory text, and entity ids are never sent. Turn it off with `MEM0_TELEMETRY=false`. ## Status diff --git a/integrations/deepseek-plugin/src/index.ts b/integrations/deepseek-plugin/src/index.ts index bea70c02c..2d24b498a 100644 --- a/integrations/deepseek-plugin/src/index.ts +++ b/integrations/deepseek-plugin/src/index.ts @@ -26,10 +26,8 @@ export const name = "mem0"; export const inject = ["tools", "systemPrompt"]; // Tags writes so Mem0's backend attributes them to this integration in -// telemetry. The backend keeps recognized values via its KNOWN_EVENT_SOURCES -// allowlist; unknown values bucket into "OTHERS", so "DEEPSEEK_HARNESS" must be -// added to that allowlist for usage to surface by name (a one-line backend PR, -// same pattern as the ZAPIER / STRANDS sources). +// telemetry. The backend's KNOWN_EVENT_SOURCES allowlist recognizes this value; +// anything outside it buckets into "OTHERS". const SOURCE = "DEEPSEEK_HARNESS"; const DEFAULT_SEARCH_LIMIT = 10; diff --git a/integrations/kimi-plugin/core/telemetry.py b/integrations/kimi-plugin/core/telemetry.py index 249595475..132de5b0c 100644 --- a/integrations/kimi-plugin/core/telemetry.py +++ b/integrations/kimi-plugin/core/telemetry.py @@ -1,5 +1,9 @@ #!/usr/bin/env python3 -"""Anonymous usage telemetry for Mem0 agent plugins. +"""Usage telemetry for Mem0 agent plugins. + +Events are linked to your Mem0 account email when an API key is configured, and +to a random per-machine id otherwise. Not anonymous — the Python SDK and CLI +attribute the same way. Hooks run on a 3-6 second budget and fire on every tool call, so recording never touches the network: `record` appends one JSON line to a local spool and returns. @@ -9,7 +13,8 @@ started once per session and again from the flush worker that is already detache Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false. Never sends prompts, memory text, queries, file paths, repository names, or API -keys: only event names, durations, counts, coarse outcomes, and salted hashes. +keys: only event names, durations, counts, coarse outcomes, and repo/session +identifiers hashed with a random per-install salt. """ from __future__ import annotations @@ -29,6 +34,7 @@ from typing import Any import memory_core +_salt_cache: str = "" _harness: str = "generic" _source_tag: str = "MEM0_PLUGIN" _PRIVATE_KEYS = { @@ -83,9 +89,126 @@ def is_enabled() -> bool: def _digest(value: str, length: int = 16) -> str: + """Unsalted digest. Only for values that are already secrets (API keys).""" return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length] +def _salt_path() -> Path: + return memory_core.data_dir() / "telemetry-salt" + + +def _install_salt() -> str: + """Random per-install salt, created once and memoized for the process. + + Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in + the identity file. Three reasons, all of which produced wrong data when this + lived in the identity dict: + + - Hooks are short-lived separate processes firing on every tool call, and + people run more than one agent window. A read-modify-write would let each + process mint its own salt, so one repository would hash several ways in the + window before a writer won. + - resolve_distinct_id holds a copy of the identity dict across a network call + to /v1/ping/, so whichever write landed second erased the other's key — + losing either the salt (repo_hash changes mid-stream) or the email (a + second $identify, splitting the person). + - Touching the identity file from record() would create it, and is_first_run + keys off that file, so recording an event would silently suppress the + install event. + + Published atomically, and there is deliberately no derived fallback. Creating + the file with O_CREAT|O_EXCL and then writing into it leaves a window where + the file exists and is empty, and a concurrent hook that reads it in that + window gets nothing. Falling back to a digest of the path would hand that + process a salt an attacker can compute, memoized for its whole run, which is + the privacy control this function exists to provide silently turning itself + off under load. The salt is written to a private temp file first and linked + into place, so the name either does not exist or already has the full value. + + Returns "" when it genuinely cannot persist. Callers omit the hash entirely + rather than emit an unsalted one. + """ + global _salt_cache + if _salt_cache: + return _salt_cache + + path = _salt_path() + # Read before writing. Hooks are separate processes firing on every tool + # call, so all but the first find the salt already published; going straight + # to create-fsync-link-unlink meant every one of them paid an fsync to + # discover that, on a path whose whole promise is appending a line and + # returning. + try: + _salt_cache = path.read_text(encoding="utf-8").strip() + if _salt_cache: + return _salt_cache + except OSError: + pass + + temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(handle, "w", encoding="utf-8") as stream: + stream.write(uuid.uuid4().hex) + stream.flush() + os.fsync(stream.fileno()) + try: + # Atomic claim: fails if another process already published one. + # os.link rather than replace, which would clobber theirs. + os.link(temporary, path) + except FileExistsError: + pass + except OSError: + # No hardlinks here (some network mounts, some container volumes). + # Claim the name directly instead. That reopens the empty-file + # window, but the window is now benign: a reader that lands in it + # gets "" and omits the hash for that process rather than caching a + # guessable one. Losing the hashes on every run of an entire + # filesystem is the worse failure. + try: + fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(fallback, "w", encoding="utf-8") as stream: + stream.write(temporary.read_text(encoding="utf-8")) + except OSError: + pass + except OSError: + pass + finally: + try: + temporary.unlink() + except OSError: + pass + + try: + _salt_cache = path.read_text(encoding="utf-8").strip() + except OSError: + _salt_cache = "" + return _salt_cache + + +def _scoped_digest(value: str, length: int = 16) -> str: + """Salted digest for values drawn from a guessable space. + + repo.identity is a git remote URL, or ``local:`` when there is + no remote — which normally contains the account username. Sixteen unsalted + hex characters over that input space is enumerable, so this is not a + privacy control without the salt. Salting per install keeps every + within-account join the analytics actually use and gives up only + cross-machine joins on the same repository, which nothing computes. + + Returns "" when there is no salt, so record() omits the property. An + unsalted digest over this input space is close to plaintext, and emitting one + under a name that implies it is hashed is worse than sending nothing. + """ + if not value: + return "" + salt = _install_salt() + if not salt: + return "" + return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length] + + def _safe_value(value: Any) -> Any: if isinstance(value, str): return memory_core.redact(value) @@ -174,10 +297,17 @@ def record( os=sys.platform, python_version=platform.python_version(), ) + # Assigned only when the digest is real. _scoped_digest returns "" when + # the salt could not be persisted, and an empty property is worse than an + # absent one: it survives the None filter below and reads as a value. if repo is not None: - properties["repo_hash"] = _digest(getattr(repo, "identity", "")) + repo_hash = _scoped_digest(getattr(repo, "identity", "")) + if repo_hash: + properties["repo_hash"] = repo_hash if session_id: - properties["session_hash"] = _digest(session_id) + session_hash = _scoped_digest(session_id) + if session_hash: + properties["session_hash"] = session_hash line = json.dumps( { "event": f"{EVENT_PREFIX}.{event}", diff --git a/integrations/kimi-plugin/skills/pause/SKILL.md b/integrations/kimi-plugin/skills/pause/SKILL.md index 9f217a468..8f93e3bf7 100644 --- a/integrations/kimi-plugin/skills/pause/SKILL.md +++ b/integrations/kimi-plugin/skills/pause/SKILL.md @@ -7,8 +7,8 @@ disable-model-invocation: true # Pause memory capture To pause (hooks stop capturing and sending session content; a minimal -anonymous telemetry ping still fires at session start unless -`MEM0_TELEMETRY=false`): +telemetry ping still fires at session start, under your Mem0 account email, +unless `MEM0_TELEMETRY=false`): ```bash python3 "${KIMI_PLUGIN_ROOT}/core/memory_cli.py" --harness "kimi" pause diff --git a/integrations/mem0-agent-plugin/core/telemetry.py b/integrations/mem0-agent-plugin/core/telemetry.py index 249595475..132de5b0c 100644 --- a/integrations/mem0-agent-plugin/core/telemetry.py +++ b/integrations/mem0-agent-plugin/core/telemetry.py @@ -1,5 +1,9 @@ #!/usr/bin/env python3 -"""Anonymous usage telemetry for Mem0 agent plugins. +"""Usage telemetry for Mem0 agent plugins. + +Events are linked to your Mem0 account email when an API key is configured, and +to a random per-machine id otherwise. Not anonymous — the Python SDK and CLI +attribute the same way. Hooks run on a 3-6 second budget and fire on every tool call, so recording never touches the network: `record` appends one JSON line to a local spool and returns. @@ -9,7 +13,8 @@ started once per session and again from the flush worker that is already detache Pure stdlib, matching the rest of the plugin. Opt out with MEM0_TELEMETRY=false. Never sends prompts, memory text, queries, file paths, repository names, or API -keys: only event names, durations, counts, coarse outcomes, and salted hashes. +keys: only event names, durations, counts, coarse outcomes, and repo/session +identifiers hashed with a random per-install salt. """ from __future__ import annotations @@ -29,6 +34,7 @@ from typing import Any import memory_core +_salt_cache: str = "" _harness: str = "generic" _source_tag: str = "MEM0_PLUGIN" _PRIVATE_KEYS = { @@ -83,9 +89,126 @@ def is_enabled() -> bool: def _digest(value: str, length: int = 16) -> str: + """Unsalted digest. Only for values that are already secrets (API keys).""" return hashlib.sha256(value.encode("utf-8")).hexdigest()[:length] +def _salt_path() -> Path: + return memory_core.data_dir() / "telemetry-salt" + + +def _install_salt() -> str: + """Random per-install salt, created once and memoized for the process. + + Deliberately its own file, claimed with O_CREAT|O_EXCL, rather than a key in + the identity file. Three reasons, all of which produced wrong data when this + lived in the identity dict: + + - Hooks are short-lived separate processes firing on every tool call, and + people run more than one agent window. A read-modify-write would let each + process mint its own salt, so one repository would hash several ways in the + window before a writer won. + - resolve_distinct_id holds a copy of the identity dict across a network call + to /v1/ping/, so whichever write landed second erased the other's key — + losing either the salt (repo_hash changes mid-stream) or the email (a + second $identify, splitting the person). + - Touching the identity file from record() would create it, and is_first_run + keys off that file, so recording an event would silently suppress the + install event. + + Published atomically, and there is deliberately no derived fallback. Creating + the file with O_CREAT|O_EXCL and then writing into it leaves a window where + the file exists and is empty, and a concurrent hook that reads it in that + window gets nothing. Falling back to a digest of the path would hand that + process a salt an attacker can compute, memoized for its whole run, which is + the privacy control this function exists to provide silently turning itself + off under load. The salt is written to a private temp file first and linked + into place, so the name either does not exist or already has the full value. + + Returns "" when it genuinely cannot persist. Callers omit the hash entirely + rather than emit an unsalted one. + """ + global _salt_cache + if _salt_cache: + return _salt_cache + + path = _salt_path() + # Read before writing. Hooks are separate processes firing on every tool + # call, so all but the first find the salt already published; going straight + # to create-fsync-link-unlink meant every one of them paid an fsync to + # discover that, on a path whose whole promise is appending a line and + # returning. + try: + _salt_cache = path.read_text(encoding="utf-8").strip() + if _salt_cache: + return _salt_cache + except OSError: + pass + + temporary = path.with_name(f"{path.name}.{os.getpid()}.tmp") + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(handle, "w", encoding="utf-8") as stream: + stream.write(uuid.uuid4().hex) + stream.flush() + os.fsync(stream.fileno()) + try: + # Atomic claim: fails if another process already published one. + # os.link rather than replace, which would clobber theirs. + os.link(temporary, path) + except FileExistsError: + pass + except OSError: + # No hardlinks here (some network mounts, some container volumes). + # Claim the name directly instead. That reopens the empty-file + # window, but the window is now benign: a reader that lands in it + # gets "" and omits the hash for that process rather than caching a + # guessable one. Losing the hashes on every run of an entire + # filesystem is the worse failure. + try: + fallback = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + with os.fdopen(fallback, "w", encoding="utf-8") as stream: + stream.write(temporary.read_text(encoding="utf-8")) + except OSError: + pass + except OSError: + pass + finally: + try: + temporary.unlink() + except OSError: + pass + + try: + _salt_cache = path.read_text(encoding="utf-8").strip() + except OSError: + _salt_cache = "" + return _salt_cache + + +def _scoped_digest(value: str, length: int = 16) -> str: + """Salted digest for values drawn from a guessable space. + + repo.identity is a git remote URL, or ``local:`` when there is + no remote — which normally contains the account username. Sixteen unsalted + hex characters over that input space is enumerable, so this is not a + privacy control without the salt. Salting per install keeps every + within-account join the analytics actually use and gives up only + cross-machine joins on the same repository, which nothing computes. + + Returns "" when there is no salt, so record() omits the property. An + unsalted digest over this input space is close to plaintext, and emitting one + under a name that implies it is hashed is worse than sending nothing. + """ + if not value: + return "" + salt = _install_salt() + if not salt: + return "" + return hashlib.sha256(f"{salt}:{value}".encode("utf-8")).hexdigest()[:length] + + def _safe_value(value: Any) -> Any: if isinstance(value, str): return memory_core.redact(value) @@ -174,10 +297,17 @@ def record( os=sys.platform, python_version=platform.python_version(), ) + # Assigned only when the digest is real. _scoped_digest returns "" when + # the salt could not be persisted, and an empty property is worse than an + # absent one: it survives the None filter below and reads as a value. if repo is not None: - properties["repo_hash"] = _digest(getattr(repo, "identity", "")) + repo_hash = _scoped_digest(getattr(repo, "identity", "")) + if repo_hash: + properties["repo_hash"] = repo_hash if session_id: - properties["session_hash"] = _digest(session_id) + session_hash = _scoped_digest(session_id) + if session_hash: + properties["session_hash"] = session_hash line = json.dumps( { "event": f"{EVENT_PREFIX}.{event}", diff --git a/integrations/mem0-agent-plugin/skills/pause/SKILL.md b/integrations/mem0-agent-plugin/skills/pause/SKILL.md index c6316dd0b..a87d6c3ee 100644 --- a/integrations/mem0-agent-plugin/skills/pause/SKILL.md +++ b/integrations/mem0-agent-plugin/skills/pause/SKILL.md @@ -6,8 +6,8 @@ description: Pause Mem0 memory capture on this machine. Use when the user wants # Pause memory capture To pause (hooks stop capturing and sending session content; a minimal -anonymous telemetry ping still fires at session start unless -`MEM0_TELEMETRY=false`): +telemetry ping still fires at session start, under your Mem0 account email, +unless `MEM0_TELEMETRY=false`): ```bash python3 "${PLUGIN_ROOT}/core/memory_cli.py" --harness "coding-agent" pause diff --git a/integrations/mem0-strands/README.md b/integrations/mem0-strands/README.md index f45d98e44..8ea4ecacc 100644 --- a/integrations/mem0-strands/README.md +++ b/integrations/mem0-strands/README.md @@ -79,9 +79,11 @@ the tool share one Mem0 backend and namespace. ## Telemetry -The store sends anonymous usage events (store configuration, operation, duration, -result counts, coarse failure kind) over the Mem0 SDK's existing telemetry client, -tagged `source="STRANDS"`. Queries, memory text, message content, entity ids, and +The store sends usage events (store configuration, operation, duration, result +counts, coarse failure kind) over the Mem0 SDK's existing telemetry client, +tagged `source="STRANDS"`. These are **not anonymous**: when an API key is +configured they are sent under your Mem0 account email, the same way the SDK +attributes its own. Queries, memory text, message content, entity ids, and metadata are never sent. Turn it off with `MEM0_TELEMETRY=false`. ## Development diff --git a/integrations/zapier-mem0/README.md b/integrations/zapier-mem0/README.md index 7b3f5ed0f..dab21d3f3 100644 --- a/integrations/zapier-mem0/README.md +++ b/integrations/zapier-mem0/README.md @@ -32,7 +32,7 @@ pnpm test:unit # offline unit tests (mocked, no network) MEM0_API_KEY=m0-... pnpm test # unit + live E2E against api.mem0.ai ``` -Anonymous usage telemetry is sent to Mem0; opt out with `MEM0_TELEMETRY=false`. +This app sends no telemetry of its own. Its API requests carry `source: "ZAPIER"` so Mem0 can see aggregate usage of the integration. To deploy (maintainers): `pnpm build && zapier push`. From 012cd32c3a5a8d1cbd3eccc3f71a62fa29e9ff26 Mon Sep 17 00:00:00 2001 From: Saket Aryan Date: Fri, 18 Sep 2026 13:42:34 +0530 Subject: [PATCH 15/61] fix(plugins): report the plugin that produced the event, not the one that sent it (#7323) --- integrations/agent-plugin-core/build/build.py | 28 +++ .../agent-plugin-core/python/telemetry.py | 42 +++- .../tests/test_uninitialised_identity.py | 179 ++++++++++++++++++ .../antigravity-plugin/core/_harness_id.py | 9 + .../antigravity-plugin/core/telemetry.py | 42 +++- .../claude-code-plugin/core/_harness_id.py | 9 + .../claude-code-plugin/core/telemetry.py | 42 +++- integrations/codex-plugin/core/_harness_id.py | 9 + integrations/codex-plugin/core/telemetry.py | 42 +++- .../cursor-plugin/core/_harness_id.py | 9 + integrations/cursor-plugin/core/telemetry.py | 42 +++- integrations/kimi-plugin/core/_harness_id.py | 9 + integrations/kimi-plugin/core/telemetry.py | 42 +++- .../mem0-agent-plugin/core/_harness_id.py | 9 + .../mem0-agent-plugin/core/telemetry.py | 42 +++- 15 files changed, 520 insertions(+), 35 deletions(-) create mode 100644 integrations/agent-plugin-core/tests/test_uninitialised_identity.py create mode 100644 integrations/antigravity-plugin/core/_harness_id.py create mode 100644 integrations/claude-code-plugin/core/_harness_id.py create mode 100644 integrations/codex-plugin/core/_harness_id.py create mode 100644 integrations/cursor-plugin/core/_harness_id.py create mode 100644 integrations/kimi-plugin/core/_harness_id.py create mode 100644 integrations/mem0-agent-plugin/core/_harness_id.py diff --git a/integrations/agent-plugin-core/build/build.py b/integrations/agent-plugin-core/build/build.py index 7a72e5c51..e675efb02 100644 --- a/integrations/agent-plugin-core/build/build.py +++ b/integrations/agent-plugin-core/build/build.py @@ -81,6 +81,28 @@ def replace_output(staged: Path, output: Path) -> Path: return output +def _render_harness_id(host: str) -> 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. + """ + tag = host.upper().replace("-", "_") + "_PLUGIN" + return ( + '"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit."""\n' + "\n" + f'HARNESS_ID = "{host}"\n' + f'SOURCE_TAG = "{tag}"\n' + "\n" + "# Platform-side vocabulary (mem0_event.source + X-Application). The whole\n" + "# plugin family is one source; which editor it runs in is the application.\n" + 'PLATFORM_SOURCE = "MEM0_PLUGIN"\n' + f'PLATFORM_APPLICATION = "{host}"\n' + ) + + def _bundle_python( staged: Path, host: str, @@ -96,6 +118,12 @@ def _bundle_python( continue shutil.copy2(source, core / source.name) + # Generated per host so identity does not depend on an entrypoint remembering + # to call telemetry.init(). mcp_server.py and the detached telemetry.py sender + # never did, which is how MCP searches reported harness=generic and every + # batch they drained was labelled MEM0_PLUGIN regardless of the real host. + (core / "_harness_id.py").write_text(_render_harness_id(host), encoding="utf-8") + values = { "PLUGIN_ROOT": plugin_root, "PLUGIN_DATA": "${PLUGIN_DATA}", diff --git a/integrations/agent-plugin-core/python/telemetry.py b/integrations/agent-plugin-core/python/telemetry.py index 132de5b0c..6d7aeecae 100644 --- a/integrations/agent-plugin-core/python/telemetry.py +++ b/integrations/agent-plugin-core/python/telemetry.py @@ -34,9 +34,24 @@ from typing import Any import memory_core +# Seeded from the per-host module the build generates into core/. Two processes +# in this pipeline never call init() — mcp_server.py, and the detached +# `python3 telemetry.py` sender that spawn_flush() starts — so a module default +# was what every one of their events got labelled with. +try: # pragma: no cover - absent only in the un-built shared source tree + from _harness_id import HARNESS_ID as _DEFAULT_HARNESS + from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION + from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE + from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG +except ImportError: + _DEFAULT_HARNESS = "generic" + _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN" + _PLATFORM_SOURCE = "MEM0_PLUGIN" + _PLATFORM_APPLICATION = "" + _salt_cache: str = "" -_harness: str = "generic" -_source_tag: str = "MEM0_PLUGIN" +_harness: str = _DEFAULT_HARNESS +_source_tag: str = _DEFAULT_SOURCE_TAG _PRIVATE_KEYS = { "apikey", "authorization", @@ -62,10 +77,19 @@ _PRIVATE_KEYS = { } -def init(harness: str = "generic", source_tag: str = "") -> None: +def init(harness: str = "", source_tag: str = "") -> None: + """Override the generated identity. Optional — core/_harness_id.py is the default. + + The fallback shape matches memory_core.configure_harness's (``_PLUGIN``). + It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which + meant one plugin could emit three different source values depending on which + process happened to send the batch. + """ global _harness, _source_tag - _harness = harness - _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN" + _harness = harness or _DEFAULT_HARNESS + _source_tag = source_tag or ( + f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG + ) POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/" @@ -291,8 +315,13 @@ def record( except OSError: pass properties = _safe_value(properties) + # Stamped in the RECORDING process, beside harness. `source` used to be + # read in the sending process from a module global, so whichever process + # drained the spool named every event in it. flush() spreads per-event + # properties last, so this now wins over any sender's default. properties.update( harness=_harness, + source=_source_tag, plugin_version=memory_core.PLUGIN_VERSION, os=sys.platform, python_version=platform.python_version(), @@ -311,6 +340,7 @@ def record( line = json.dumps( { "event": f"{EVENT_PREFIX}.{event}", + "uuid": str(uuid.uuid4()), "timestamp": memory_core.utc_now(), "properties": { key: value for key, value in properties.items() if value is not None @@ -496,6 +526,8 @@ def flush() -> int: "distinct_id": distinct_id, "timestamp": event.get("timestamp"), "properties": { + # Fallback only: events recorded by a build before source + # moved into record() have none of their own. "source": _source_tag, "language": "python", "$process_person_profile": False, diff --git a/integrations/agent-plugin-core/tests/test_uninitialised_identity.py b/integrations/agent-plugin-core/tests/test_uninitialised_identity.py new file mode 100644 index 000000000..14f911bee --- /dev/null +++ b/integrations/agent-plugin-core/tests/test_uninitialised_identity.py @@ -0,0 +1,179 @@ +"""Core telemetry behaviour with NO telemetry.init(), in a real subprocess. + +Why this file exists +-------------------- +``telemetry.py`` lives in ``agent-plugin-core/python/`` but its only tests lived +under ``claude-code-plugin/tests/``, behind a ``conftest.py`` that calls +``configure_harness()`` and ``telemetry.init()`` at import. Core behaviour was +therefore only ever exercised inside an already-configured module. + +Two processes in the real pipeline never call ``init()``: + +- ``mcp_server.py``, which records every manual search; +- the detached ``python3 telemetry.py`` sender that ``spawn_flush()`` starts at + session start, after every skill command, and when the MCP server exits. + +Both fell back to module defaults, so MCP searches reported ``harness=generic`` +and everything that sender delivered was labelled ``MEM0_PLUGIN`` regardless of +which of the six plugins produced it. The suite stayed green throughout. + +These tests run in a fresh interpreter with no conftest, against a built host +bundle, which is the only arrangement that can catch that class of bug. +""" + +from __future__ import annotations + +import json +import subprocess +import sys +import tempfile +from pathlib import Path + +import pytest + +CORE_ROOT = Path(__file__).resolve().parents[1] +REPOSITORY_ROOT = CORE_ROOT.parents[1] +HOSTS = { + "claude-code": ("claude-code-plugin", "CLAUDE_CODE_PLUGIN"), + "cursor": ("cursor-plugin", "CURSOR_PLUGIN"), + "codex": ("codex-plugin", "CODEX_PLUGIN"), + "kimi": ("kimi-plugin", "KIMI_PLUGIN"), + "antigravity": ("antigravity-plugin", "ANTIGRAVITY_PLUGIN"), + # Portable: no flush_worker and no hook_runner, so its ONLY sender is the + # uninitialised telemetry.py. A native-only test passes here vacuously. + "coding-agent": ("mem0-agent-plugin", "CODING_AGENT_PLUGIN"), +} + + +def _core_dir(directory: str) -> Path: + return REPOSITORY_ROOT / "integrations" / directory / "core" + + +def _run(core: Path, data_dir: Path, body: str) -> str: + """Execute `body` in a fresh interpreter with only the host's core on sys.path.""" + script = f"import sys; sys.path.insert(0, {str(core)!r})\n{body}" + result = subprocess.run( + [sys.executable, "-c", script], + capture_output=True, + text=True, + env={ + "MEM0_CODE_DATA_DIR": str(data_dir), + "PATH": "/usr/bin:/bin", + "HOME": str(data_dir), + }, + ) + assert result.returncode == 0, result.stderr + return result.stdout.strip() + + +@pytest.mark.parametrize("harness,spec", sorted(HOSTS.items())) +def test_identity_resolves_without_init(harness, spec): + """Every built host knows what it is with no configuration call at all.""" + directory, source_tag = spec + core = _core_dir(directory) + if not core.exists(): + pytest.skip(f"{directory} is not built in this tree") + + with tempfile.TemporaryDirectory() as tmp: + out = _run( + core, + Path(tmp), + "import telemetry; print(telemetry._harness, telemetry._source_tag)", + ) + assert out == f"{harness} {source_tag}" + + +def test_mcp_server_records_the_real_harness(): + """mcp_server imports telemetry and never initialises it (server.py has no init). + + Its recorded events used to carry harness=generic for every plugin. + """ + core = _core_dir("claude-code-plugin") + if not core.exists(): + pytest.skip("claude-code-plugin is not built in this tree") + + with tempfile.TemporaryDirectory() as tmp: + data_dir = Path(tmp) + _run( + core, + data_dir, + "import mcp_server, telemetry; telemetry.record('search', trigger='mcp-search')", + ) + spooled = (data_dir / "telemetry.jsonl").read_text(encoding="utf-8").strip() + + event = json.loads(spooled) + assert event["properties"]["harness"] == "claude-code" + assert event["properties"]["source"] == "CLAUDE_CODE_PLUGIN" + + +def test_the_detached_sender_does_not_relabel_events(): + """`python3 telemetry.py` is the sender spawn_flush() starts, and never inits. + + source is stamped at record time now, so which process sends is irrelevant. + """ + core = _core_dir("claude-code-plugin") + if not core.exists(): + pytest.skip("claude-code-plugin is not built in this tree") + + with tempfile.TemporaryDirectory() as tmp: + data_dir = Path(tmp) + _run(core, data_dir, "import telemetry; telemetry.record('search')") + + captured = data_dir / "captured.json" + # Drain with a fresh, unconfigured interpreter, capturing the payload + # instead of posting it. + _run( + core, + data_dir, + "import json, telemetry\n" + "sent = []\n" + "telemetry._post = lambda payload, url: sent.append(payload) or True\n" + "telemetry.flush()\n" + f"open({str(captured)!r}, 'w').write(json.dumps(sent))", + ) + payloads = json.loads(captured.read_text(encoding="utf-8")) + + batches = [p for p in payloads if "batch" in p] + assert batches, "nothing was sent" + properties = batches[0]["batch"][0]["properties"] + assert properties["source"] == "CLAUDE_CODE_PLUGIN" + assert properties["harness"] == "claude-code" + + +def test_every_event_carries_a_uuid_for_dedupe(): + core = _core_dir("claude-code-plugin") + if not core.exists(): + pytest.skip("claude-code-plugin is not built in this tree") + + with tempfile.TemporaryDirectory() as tmp: + data_dir = Path(tmp) + _run(core, data_dir, "import telemetry; telemetry.record('search'); telemetry.record('flush')") + lines = (data_dir / "telemetry.jsonl").read_text(encoding="utf-8").strip().splitlines() + + ids = [json.loads(line)["uuid"] for line in lines] + assert len(ids) == 2 + assert len(set(ids)) == 2 + + +def test_source_tag_defaults_agree_between_the_two_modules(): + """configure_harness and telemetry.init must derive the same tag. + + They disagreed: `_plugin` in one and `MEM0__PLUGIN` in the other, + so one plugin could emit three different source values depending on which + process sent the batch. + """ + core = _core_dir("claude-code-plugin") + if not core.exists(): + pytest.skip("claude-code-plugin is not built in this tree") + + with tempfile.TemporaryDirectory() as tmp: + out = _run( + core, + Path(tmp), + "import memory_core, telemetry\n" + "memory_core.configure_harness('kimi')\n" + "telemetry.init(harness='kimi')\n" + "print(memory_core.harness_config()['source_tag'].upper(), telemetry._source_tag)", + ) + left, right = out.split() + assert left == right == "KIMI_PLUGIN" diff --git a/integrations/antigravity-plugin/core/_harness_id.py b/integrations/antigravity-plugin/core/_harness_id.py new file mode 100644 index 000000000..2c8a515f4 --- /dev/null +++ b/integrations/antigravity-plugin/core/_harness_id.py @@ -0,0 +1,9 @@ +"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit.""" + +HARNESS_ID = "antigravity" +SOURCE_TAG = "ANTIGRAVITY_PLUGIN" + +# Platform-side vocabulary (mem0_event.source + X-Application). The whole +# plugin family is one source; which editor it runs in is the application. +PLATFORM_SOURCE = "MEM0_PLUGIN" +PLATFORM_APPLICATION = "antigravity" diff --git a/integrations/antigravity-plugin/core/telemetry.py b/integrations/antigravity-plugin/core/telemetry.py index 132de5b0c..6d7aeecae 100644 --- a/integrations/antigravity-plugin/core/telemetry.py +++ b/integrations/antigravity-plugin/core/telemetry.py @@ -34,9 +34,24 @@ from typing import Any import memory_core +# Seeded from the per-host module the build generates into core/. Two processes +# in this pipeline never call init() — mcp_server.py, and the detached +# `python3 telemetry.py` sender that spawn_flush() starts — so a module default +# was what every one of their events got labelled with. +try: # pragma: no cover - absent only in the un-built shared source tree + from _harness_id import HARNESS_ID as _DEFAULT_HARNESS + from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION + from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE + from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG +except ImportError: + _DEFAULT_HARNESS = "generic" + _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN" + _PLATFORM_SOURCE = "MEM0_PLUGIN" + _PLATFORM_APPLICATION = "" + _salt_cache: str = "" -_harness: str = "generic" -_source_tag: str = "MEM0_PLUGIN" +_harness: str = _DEFAULT_HARNESS +_source_tag: str = _DEFAULT_SOURCE_TAG _PRIVATE_KEYS = { "apikey", "authorization", @@ -62,10 +77,19 @@ _PRIVATE_KEYS = { } -def init(harness: str = "generic", source_tag: str = "") -> None: +def init(harness: str = "", source_tag: str = "") -> None: + """Override the generated identity. Optional — core/_harness_id.py is the default. + + The fallback shape matches memory_core.configure_harness's (``_PLUGIN``). + It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which + meant one plugin could emit three different source values depending on which + process happened to send the batch. + """ global _harness, _source_tag - _harness = harness - _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN" + _harness = harness or _DEFAULT_HARNESS + _source_tag = source_tag or ( + f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG + ) POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/" @@ -291,8 +315,13 @@ def record( except OSError: pass properties = _safe_value(properties) + # Stamped in the RECORDING process, beside harness. `source` used to be + # read in the sending process from a module global, so whichever process + # drained the spool named every event in it. flush() spreads per-event + # properties last, so this now wins over any sender's default. properties.update( harness=_harness, + source=_source_tag, plugin_version=memory_core.PLUGIN_VERSION, os=sys.platform, python_version=platform.python_version(), @@ -311,6 +340,7 @@ def record( line = json.dumps( { "event": f"{EVENT_PREFIX}.{event}", + "uuid": str(uuid.uuid4()), "timestamp": memory_core.utc_now(), "properties": { key: value for key, value in properties.items() if value is not None @@ -496,6 +526,8 @@ def flush() -> int: "distinct_id": distinct_id, "timestamp": event.get("timestamp"), "properties": { + # Fallback only: events recorded by a build before source + # moved into record() have none of their own. "source": _source_tag, "language": "python", "$process_person_profile": False, diff --git a/integrations/claude-code-plugin/core/_harness_id.py b/integrations/claude-code-plugin/core/_harness_id.py new file mode 100644 index 000000000..6c3e1ce15 --- /dev/null +++ b/integrations/claude-code-plugin/core/_harness_id.py @@ -0,0 +1,9 @@ +"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit.""" + +HARNESS_ID = "claude-code" +SOURCE_TAG = "CLAUDE_CODE_PLUGIN" + +# Platform-side vocabulary (mem0_event.source + X-Application). The whole +# plugin family is one source; which editor it runs in is the application. +PLATFORM_SOURCE = "MEM0_PLUGIN" +PLATFORM_APPLICATION = "claude-code" diff --git a/integrations/claude-code-plugin/core/telemetry.py b/integrations/claude-code-plugin/core/telemetry.py index 132de5b0c..6d7aeecae 100644 --- a/integrations/claude-code-plugin/core/telemetry.py +++ b/integrations/claude-code-plugin/core/telemetry.py @@ -34,9 +34,24 @@ from typing import Any import memory_core +# Seeded from the per-host module the build generates into core/. Two processes +# in this pipeline never call init() — mcp_server.py, and the detached +# `python3 telemetry.py` sender that spawn_flush() starts — so a module default +# was what every one of their events got labelled with. +try: # pragma: no cover - absent only in the un-built shared source tree + from _harness_id import HARNESS_ID as _DEFAULT_HARNESS + from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION + from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE + from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG +except ImportError: + _DEFAULT_HARNESS = "generic" + _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN" + _PLATFORM_SOURCE = "MEM0_PLUGIN" + _PLATFORM_APPLICATION = "" + _salt_cache: str = "" -_harness: str = "generic" -_source_tag: str = "MEM0_PLUGIN" +_harness: str = _DEFAULT_HARNESS +_source_tag: str = _DEFAULT_SOURCE_TAG _PRIVATE_KEYS = { "apikey", "authorization", @@ -62,10 +77,19 @@ _PRIVATE_KEYS = { } -def init(harness: str = "generic", source_tag: str = "") -> None: +def init(harness: str = "", source_tag: str = "") -> None: + """Override the generated identity. Optional — core/_harness_id.py is the default. + + The fallback shape matches memory_core.configure_harness's (``_PLUGIN``). + It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which + meant one plugin could emit three different source values depending on which + process happened to send the batch. + """ global _harness, _source_tag - _harness = harness - _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN" + _harness = harness or _DEFAULT_HARNESS + _source_tag = source_tag or ( + f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG + ) POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/" @@ -291,8 +315,13 @@ def record( except OSError: pass properties = _safe_value(properties) + # Stamped in the RECORDING process, beside harness. `source` used to be + # read in the sending process from a module global, so whichever process + # drained the spool named every event in it. flush() spreads per-event + # properties last, so this now wins over any sender's default. properties.update( harness=_harness, + source=_source_tag, plugin_version=memory_core.PLUGIN_VERSION, os=sys.platform, python_version=platform.python_version(), @@ -311,6 +340,7 @@ def record( line = json.dumps( { "event": f"{EVENT_PREFIX}.{event}", + "uuid": str(uuid.uuid4()), "timestamp": memory_core.utc_now(), "properties": { key: value for key, value in properties.items() if value is not None @@ -496,6 +526,8 @@ def flush() -> int: "distinct_id": distinct_id, "timestamp": event.get("timestamp"), "properties": { + # Fallback only: events recorded by a build before source + # moved into record() have none of their own. "source": _source_tag, "language": "python", "$process_person_profile": False, diff --git a/integrations/codex-plugin/core/_harness_id.py b/integrations/codex-plugin/core/_harness_id.py new file mode 100644 index 000000000..152313a21 --- /dev/null +++ b/integrations/codex-plugin/core/_harness_id.py @@ -0,0 +1,9 @@ +"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit.""" + +HARNESS_ID = "codex" +SOURCE_TAG = "CODEX_PLUGIN" + +# Platform-side vocabulary (mem0_event.source + X-Application). The whole +# plugin family is one source; which editor it runs in is the application. +PLATFORM_SOURCE = "MEM0_PLUGIN" +PLATFORM_APPLICATION = "codex" diff --git a/integrations/codex-plugin/core/telemetry.py b/integrations/codex-plugin/core/telemetry.py index 132de5b0c..6d7aeecae 100644 --- a/integrations/codex-plugin/core/telemetry.py +++ b/integrations/codex-plugin/core/telemetry.py @@ -34,9 +34,24 @@ from typing import Any import memory_core +# Seeded from the per-host module the build generates into core/. Two processes +# in this pipeline never call init() — mcp_server.py, and the detached +# `python3 telemetry.py` sender that spawn_flush() starts — so a module default +# was what every one of their events got labelled with. +try: # pragma: no cover - absent only in the un-built shared source tree + from _harness_id import HARNESS_ID as _DEFAULT_HARNESS + from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION + from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE + from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG +except ImportError: + _DEFAULT_HARNESS = "generic" + _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN" + _PLATFORM_SOURCE = "MEM0_PLUGIN" + _PLATFORM_APPLICATION = "" + _salt_cache: str = "" -_harness: str = "generic" -_source_tag: str = "MEM0_PLUGIN" +_harness: str = _DEFAULT_HARNESS +_source_tag: str = _DEFAULT_SOURCE_TAG _PRIVATE_KEYS = { "apikey", "authorization", @@ -62,10 +77,19 @@ _PRIVATE_KEYS = { } -def init(harness: str = "generic", source_tag: str = "") -> None: +def init(harness: str = "", source_tag: str = "") -> None: + """Override the generated identity. Optional — core/_harness_id.py is the default. + + The fallback shape matches memory_core.configure_harness's (``_PLUGIN``). + It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which + meant one plugin could emit three different source values depending on which + process happened to send the batch. + """ global _harness, _source_tag - _harness = harness - _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN" + _harness = harness or _DEFAULT_HARNESS + _source_tag = source_tag or ( + f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG + ) POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/" @@ -291,8 +315,13 @@ def record( except OSError: pass properties = _safe_value(properties) + # Stamped in the RECORDING process, beside harness. `source` used to be + # read in the sending process from a module global, so whichever process + # drained the spool named every event in it. flush() spreads per-event + # properties last, so this now wins over any sender's default. properties.update( harness=_harness, + source=_source_tag, plugin_version=memory_core.PLUGIN_VERSION, os=sys.platform, python_version=platform.python_version(), @@ -311,6 +340,7 @@ def record( line = json.dumps( { "event": f"{EVENT_PREFIX}.{event}", + "uuid": str(uuid.uuid4()), "timestamp": memory_core.utc_now(), "properties": { key: value for key, value in properties.items() if value is not None @@ -496,6 +526,8 @@ def flush() -> int: "distinct_id": distinct_id, "timestamp": event.get("timestamp"), "properties": { + # Fallback only: events recorded by a build before source + # moved into record() have none of their own. "source": _source_tag, "language": "python", "$process_person_profile": False, diff --git a/integrations/cursor-plugin/core/_harness_id.py b/integrations/cursor-plugin/core/_harness_id.py new file mode 100644 index 000000000..40241a7f4 --- /dev/null +++ b/integrations/cursor-plugin/core/_harness_id.py @@ -0,0 +1,9 @@ +"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit.""" + +HARNESS_ID = "cursor" +SOURCE_TAG = "CURSOR_PLUGIN" + +# Platform-side vocabulary (mem0_event.source + X-Application). The whole +# plugin family is one source; which editor it runs in is the application. +PLATFORM_SOURCE = "MEM0_PLUGIN" +PLATFORM_APPLICATION = "cursor" diff --git a/integrations/cursor-plugin/core/telemetry.py b/integrations/cursor-plugin/core/telemetry.py index 132de5b0c..6d7aeecae 100644 --- a/integrations/cursor-plugin/core/telemetry.py +++ b/integrations/cursor-plugin/core/telemetry.py @@ -34,9 +34,24 @@ from typing import Any import memory_core +# Seeded from the per-host module the build generates into core/. Two processes +# in this pipeline never call init() — mcp_server.py, and the detached +# `python3 telemetry.py` sender that spawn_flush() starts — so a module default +# was what every one of their events got labelled with. +try: # pragma: no cover - absent only in the un-built shared source tree + from _harness_id import HARNESS_ID as _DEFAULT_HARNESS + from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION + from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE + from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG +except ImportError: + _DEFAULT_HARNESS = "generic" + _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN" + _PLATFORM_SOURCE = "MEM0_PLUGIN" + _PLATFORM_APPLICATION = "" + _salt_cache: str = "" -_harness: str = "generic" -_source_tag: str = "MEM0_PLUGIN" +_harness: str = _DEFAULT_HARNESS +_source_tag: str = _DEFAULT_SOURCE_TAG _PRIVATE_KEYS = { "apikey", "authorization", @@ -62,10 +77,19 @@ _PRIVATE_KEYS = { } -def init(harness: str = "generic", source_tag: str = "") -> None: +def init(harness: str = "", source_tag: str = "") -> None: + """Override the generated identity. Optional — core/_harness_id.py is the default. + + The fallback shape matches memory_core.configure_harness's (``_PLUGIN``). + It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which + meant one plugin could emit three different source values depending on which + process happened to send the batch. + """ global _harness, _source_tag - _harness = harness - _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN" + _harness = harness or _DEFAULT_HARNESS + _source_tag = source_tag or ( + f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG + ) POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/" @@ -291,8 +315,13 @@ def record( except OSError: pass properties = _safe_value(properties) + # Stamped in the RECORDING process, beside harness. `source` used to be + # read in the sending process from a module global, so whichever process + # drained the spool named every event in it. flush() spreads per-event + # properties last, so this now wins over any sender's default. properties.update( harness=_harness, + source=_source_tag, plugin_version=memory_core.PLUGIN_VERSION, os=sys.platform, python_version=platform.python_version(), @@ -311,6 +340,7 @@ def record( line = json.dumps( { "event": f"{EVENT_PREFIX}.{event}", + "uuid": str(uuid.uuid4()), "timestamp": memory_core.utc_now(), "properties": { key: value for key, value in properties.items() if value is not None @@ -496,6 +526,8 @@ def flush() -> int: "distinct_id": distinct_id, "timestamp": event.get("timestamp"), "properties": { + # Fallback only: events recorded by a build before source + # moved into record() have none of their own. "source": _source_tag, "language": "python", "$process_person_profile": False, diff --git a/integrations/kimi-plugin/core/_harness_id.py b/integrations/kimi-plugin/core/_harness_id.py new file mode 100644 index 000000000..aa17750b1 --- /dev/null +++ b/integrations/kimi-plugin/core/_harness_id.py @@ -0,0 +1,9 @@ +"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit.""" + +HARNESS_ID = "kimi" +SOURCE_TAG = "KIMI_PLUGIN" + +# Platform-side vocabulary (mem0_event.source + X-Application). The whole +# plugin family is one source; which editor it runs in is the application. +PLATFORM_SOURCE = "MEM0_PLUGIN" +PLATFORM_APPLICATION = "kimi" diff --git a/integrations/kimi-plugin/core/telemetry.py b/integrations/kimi-plugin/core/telemetry.py index 132de5b0c..6d7aeecae 100644 --- a/integrations/kimi-plugin/core/telemetry.py +++ b/integrations/kimi-plugin/core/telemetry.py @@ -34,9 +34,24 @@ from typing import Any import memory_core +# Seeded from the per-host module the build generates into core/. Two processes +# in this pipeline never call init() — mcp_server.py, and the detached +# `python3 telemetry.py` sender that spawn_flush() starts — so a module default +# was what every one of their events got labelled with. +try: # pragma: no cover - absent only in the un-built shared source tree + from _harness_id import HARNESS_ID as _DEFAULT_HARNESS + from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION + from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE + from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG +except ImportError: + _DEFAULT_HARNESS = "generic" + _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN" + _PLATFORM_SOURCE = "MEM0_PLUGIN" + _PLATFORM_APPLICATION = "" + _salt_cache: str = "" -_harness: str = "generic" -_source_tag: str = "MEM0_PLUGIN" +_harness: str = _DEFAULT_HARNESS +_source_tag: str = _DEFAULT_SOURCE_TAG _PRIVATE_KEYS = { "apikey", "authorization", @@ -62,10 +77,19 @@ _PRIVATE_KEYS = { } -def init(harness: str = "generic", source_tag: str = "") -> None: +def init(harness: str = "", source_tag: str = "") -> None: + """Override the generated identity. Optional — core/_harness_id.py is the default. + + The fallback shape matches memory_core.configure_harness's (``_PLUGIN``). + It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which + meant one plugin could emit three different source values depending on which + process happened to send the batch. + """ global _harness, _source_tag - _harness = harness - _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN" + _harness = harness or _DEFAULT_HARNESS + _source_tag = source_tag or ( + f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG + ) POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/" @@ -291,8 +315,13 @@ def record( except OSError: pass properties = _safe_value(properties) + # Stamped in the RECORDING process, beside harness. `source` used to be + # read in the sending process from a module global, so whichever process + # drained the spool named every event in it. flush() spreads per-event + # properties last, so this now wins over any sender's default. properties.update( harness=_harness, + source=_source_tag, plugin_version=memory_core.PLUGIN_VERSION, os=sys.platform, python_version=platform.python_version(), @@ -311,6 +340,7 @@ def record( line = json.dumps( { "event": f"{EVENT_PREFIX}.{event}", + "uuid": str(uuid.uuid4()), "timestamp": memory_core.utc_now(), "properties": { key: value for key, value in properties.items() if value is not None @@ -496,6 +526,8 @@ def flush() -> int: "distinct_id": distinct_id, "timestamp": event.get("timestamp"), "properties": { + # Fallback only: events recorded by a build before source + # moved into record() have none of their own. "source": _source_tag, "language": "python", "$process_person_profile": False, diff --git a/integrations/mem0-agent-plugin/core/_harness_id.py b/integrations/mem0-agent-plugin/core/_harness_id.py new file mode 100644 index 000000000..b0836d6de --- /dev/null +++ b/integrations/mem0-agent-plugin/core/_harness_id.py @@ -0,0 +1,9 @@ +"""Generated by integrations/agent-plugin-core/build/build.py. Do not edit.""" + +HARNESS_ID = "coding-agent" +SOURCE_TAG = "CODING_AGENT_PLUGIN" + +# Platform-side vocabulary (mem0_event.source + X-Application). The whole +# plugin family is one source; which editor it runs in is the application. +PLATFORM_SOURCE = "MEM0_PLUGIN" +PLATFORM_APPLICATION = "coding-agent" diff --git a/integrations/mem0-agent-plugin/core/telemetry.py b/integrations/mem0-agent-plugin/core/telemetry.py index 132de5b0c..6d7aeecae 100644 --- a/integrations/mem0-agent-plugin/core/telemetry.py +++ b/integrations/mem0-agent-plugin/core/telemetry.py @@ -34,9 +34,24 @@ from typing import Any import memory_core +# Seeded from the per-host module the build generates into core/. Two processes +# in this pipeline never call init() — mcp_server.py, and the detached +# `python3 telemetry.py` sender that spawn_flush() starts — so a module default +# was what every one of their events got labelled with. +try: # pragma: no cover - absent only in the un-built shared source tree + from _harness_id import HARNESS_ID as _DEFAULT_HARNESS + from _harness_id import PLATFORM_APPLICATION as _PLATFORM_APPLICATION + from _harness_id import PLATFORM_SOURCE as _PLATFORM_SOURCE + from _harness_id import SOURCE_TAG as _DEFAULT_SOURCE_TAG +except ImportError: + _DEFAULT_HARNESS = "generic" + _DEFAULT_SOURCE_TAG = "MEM0_PLUGIN" + _PLATFORM_SOURCE = "MEM0_PLUGIN" + _PLATFORM_APPLICATION = "" + _salt_cache: str = "" -_harness: str = "generic" -_source_tag: str = "MEM0_PLUGIN" +_harness: str = _DEFAULT_HARNESS +_source_tag: str = _DEFAULT_SOURCE_TAG _PRIVATE_KEYS = { "apikey", "authorization", @@ -62,10 +77,19 @@ _PRIVATE_KEYS = { } -def init(harness: str = "generic", source_tag: str = "") -> None: +def init(harness: str = "", source_tag: str = "") -> None: + """Override the generated identity. Optional — core/_harness_id.py is the default. + + The fallback shape matches memory_core.configure_harness's (``_PLUGIN``). + It used to be ``MEM0__PLUGIN`` here and ``_plugin`` there, which + meant one plugin could emit three different source values depending on which + process happened to send the batch. + """ global _harness, _source_tag - _harness = harness - _source_tag = source_tag or f"MEM0_{harness.upper().replace('-', '_')}_PLUGIN" + _harness = harness or _DEFAULT_HARNESS + _source_tag = source_tag or ( + f"{_harness.upper().replace('-', '_')}_PLUGIN" if harness else _DEFAULT_SOURCE_TAG + ) POSTHOG_API_KEY = "phc_hgJkUVJFYtmaJqrvf6CYN67TIQ8yhXAkWzUn9AMU4yX" POSTHOG_CAPTURE_URL = "https://us.i.posthog.com/i/v0/e/" @@ -291,8 +315,13 @@ def record( except OSError: pass properties = _safe_value(properties) + # Stamped in the RECORDING process, beside harness. `source` used to be + # read in the sending process from a module global, so whichever process + # drained the spool named every event in it. flush() spreads per-event + # properties last, so this now wins over any sender's default. properties.update( harness=_harness, + source=_source_tag, plugin_version=memory_core.PLUGIN_VERSION, os=sys.platform, python_version=platform.python_version(), @@ -311,6 +340,7 @@ def record( line = json.dumps( { "event": f"{EVENT_PREFIX}.{event}", + "uuid": str(uuid.uuid4()), "timestamp": memory_core.utc_now(), "properties": { key: value for key, value in properties.items() if value is not None @@ -496,6 +526,8 @@ def flush() -> int: "distinct_id": distinct_id, "timestamp": event.get("timestamp"), "properties": { + # Fallback only: events recorded by a build before source + # moved into record() have none of their own. "source": _source_tag, "language": "python", "$process_person_profile": False, From 33629990956ca6336501deea2e9cd625e5fe09af Mon Sep 17 00:00:00 2001 From: Saket Aryan Date: Fri, 18 Sep 2026 13:43:33 +0530 Subject: [PATCH 16/61] fix(plugins): stop delivering telemetry events twice, and stop losing parked ones (#7324) --- .../agent-plugin-core/python/telemetry.py | 274 ++++++++++- .../tests/test_spool_delivery.py | 446 ++++++++++++++++++ .../antigravity-plugin/core/telemetry.py | 274 ++++++++++- .../claude-code-plugin/core/telemetry.py | 274 ++++++++++- .../tests/test_telemetry.py | 18 +- integrations/codex-plugin/core/telemetry.py | 274 ++++++++++- integrations/cursor-plugin/core/telemetry.py | 274 ++++++++++- integrations/kimi-plugin/core/telemetry.py | 274 ++++++++++- .../mem0-agent-plugin/core/telemetry.py | 274 ++++++++++- 9 files changed, 2243 insertions(+), 139 deletions(-) create mode 100644 integrations/agent-plugin-core/tests/test_spool_delivery.py diff --git a/integrations/agent-plugin-core/python/telemetry.py b/integrations/agent-plugin-core/python/telemetry.py index 6d7aeecae..a4375f002 100644 --- a/integrations/agent-plugin-core/python/telemetry.py +++ b/integrations/agent-plugin-core/python/telemetry.py @@ -100,6 +100,16 @@ BATCH_SIZE = 100 SEND_TIMEOUT = 5 CLAIM_STALE_SECONDS = 120 CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60 +# A batch is only discarded once it has genuinely been retried this many times. +MAX_CLAIM_ATTEMPTS = 3 +# Parked claims drained per run, after the live spool. Bounded so a long backlog +# cannot turn one flush into an unbounded send loop. +MAX_PARKED_PER_RUN = 3 +# Added to the wait before a released claim becomes reclaimable, per attempt +# already spent. Releasing straight to "reclaimable now" let two senders burn the +# whole budget within seconds of one another on a single momentary failure, and +# discard a batch a retry a minute later would have delivered. +RETRY_COOLDOWN_SECONDS = 60 def is_enabled() -> bool: @@ -399,38 +409,201 @@ def spawn_flush() -> bool: return False +def _claim_name(attempt: int = 0) -> str: + """Claim filename. The attempt count rides in the name so the 7-day expiry + only ever discards a batch that was actually retried and failed.""" + return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending" + + +def _claim_attempt(claim: Path) -> int: + """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape. + + Anchored on field position, not on a leading "a": the legacy shape is + ``telemetry--.sending`` and a hex id such as ``a1234567`` would + otherwise parse as attempt 1234567 and be discarded unsent on the first + flush after an upgrade. + """ + stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name + parts = stem.split("-") + if len(parts) != 4: + return 0 + tail = parts[3] + if tail.startswith("a") and tail[1:].isdigit(): + return int(tail[1:]) + return 0 + + +def _touch(path: Path) -> None: + """Refresh mtime so a claim's age measures time since it was claimed. + + ``Path.replace`` is ``os.rename``, which preserves mtime — so a claim created + after a quiet minute inherited the spool's last-write time and looked + abandoned the instant it was made. A second sender would then take it over + while the first was still posting, and both would deliver the batch. + """ + try: + os.utime(path, None) + except OSError: + pass + + def _claim_spool() -> Path | None: """Rename the spool aside so exactly one sender owns each batch.""" directory = memory_core.data_dir() - claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending" + claim = directory / _claim_name() spool = _spool_path() try: spool.replace(claim) + _touch(claim) return claim except OSError: pass + return _claim_parked(directory) + + +def _sweep_debris(directory: Path) -> None: + """Remove files nothing else will ever pick up again. + + *.partial is a temp file orphaned by a crash between write and rename. + *.corrupt is a batch quarantined for undecodable content. No glob in this + module matches either, so without this they accumulate on disk for the life + of the install. + + Quarantined batches are kept far longer than debris: they are the only + evidence left of events that could not be delivered, and someone diagnosing + a report of missing telemetry has to be able to find one. + """ now = time.time() - for orphan in sorted(directory.glob("telemetry-*.sending")): + for debris in directory.glob("telemetry-*.partial"): + try: + if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS: + debris.unlink() + except OSError: + continue + for quarantined in directory.glob("telemetry-*.corrupt"): + try: + if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS: + quarantined.unlink() + except OSError: + continue + # The same reasoning covers *.tmp. _write_identity and _install_salt both + # create one and unlink it in a finally, which a SIGKILL skips, and no glob + # in this module matches the leftovers either. + for temporary in directory.glob("telemetry-*.tmp"): + try: + if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS: + temporary.unlink() + except OSError: + continue + + +def _claim_parked(directory: Path) -> Path | None: + """Take the oldest abandoned claim, if any lease has actually expired. + + Kept separate from the live spool so flush() can drain both in one run. + Previously parked batches were only reachable when no spool existed at all, + and because sessions keep recording there usually was one — so a batch + parked by a failed send waited until the 7-day expiry deleted it unsent, + even though its own presence is what started the sender. + """ + now = time.time() + for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime): try: age = now - orphan.stat().st_mtime except OSError: continue - if age > CLAIM_EXPIRY_SECONDS: + if age < CLAIM_STALE_SECONDS: + # Someone else holds a live lease on it. This check has to come + # first. Claiming a file bumps its attempt count and refreshes its + # mtime, so a sender that has just taken the final attempt looks + # exhausted to everyone else while it is actively draining. Judging + # exhaustion before liveness let a second sender unlink a batch out + # from under its owner, losing every event in it. + continue + # Attempts, not age. Every re-claim touches the mtime and every release + # backdates it by a fixed amount, so age is pinned near the stale + # threshold and never reaches the expiry. Age stays only as a backstop + # for files that never carried an attempt marker. + if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS: try: orphan.unlink() except OSError: pass continue - if age < CLAIM_STALE_SECONDS: - continue + claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1) try: orphan.replace(claim) + _touch(claim) return claim except OSError: continue return None +def _safe_mtime(path: Path) -> float: + try: + return path.stat().st_mtime + except OSError: + return 0.0 + + +def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool: + """Persist the unsent remainder, atomically, and refresh the lease. + + Called after every successful batch. Two jobs: a retry resumes where the + send stopped instead of re-posting from the top, and the rewrite doubles as + the lease heartbeat, so a slow sender does not have its claim stolen + mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS. + """ + if not remaining: + try: + claim.unlink() + except OSError: + pass + return True + temporary = claim.with_suffix(f".{os.getpid()}.partial") + try: + payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining) + # fsync before the rename: without it the rename can land while the + # bytes have not, and the claim comes back empty or truncated after a + # crash. _drain then reads zero events and unlinks it. + with open(temporary, "w", encoding="utf-8") as handle: + handle.write(payload) + handle.flush() + os.fsync(handle.fileno()) + temporary.replace(claim) + _touch(claim) + return True + except OSError: + try: + temporary.unlink() + except OSError: + pass + return False + + +def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None: + """Persist the remainder and drop the lease, because this sender has given up. + + Distinct from the per-batch heartbeat: heartbeating on the way out would + make an abandoned batch look actively owned for a further + CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the + threshold lets the next flush pick it up immediately, while the attempt + count in the filename still bounds how many times that can happen. + """ + if not _rewrite_claim(claim, remaining): + return + try: + # Backdate past the stale threshold so the next flush can pick it up, + # minus a cooldown that grows with the attempts already spent. Clamped so + # the mtime never lands in the future, which would read as a live lease. + cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS) + released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown + os.utime(claim, (released, released)) + except OSError: + pass + + def _resolve_email(key: str) -> str: """Trade the API key for the account email so events join other Mem0 surfaces.""" url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/" @@ -478,16 +651,61 @@ def resolve_distinct_id() -> tuple[str, str]: def flush() -> int: - """Drain claimed spools to PostHog and return the number of events sent.""" + """Drain the live spool, then any parked claims, and return events sent.""" if not is_enabled(): return 0 - claim = _claim_spool() + sent, delivered = _drain(_claim_spool()) + if not delivered: + # The network is failing. Retrying other batches now would only burn + # their attempt budget against the same broken connection. + return sent + + # Parked batches used to starve behind the live spool indefinitely. Bounded + # per run so a long backlog cannot turn one flush into an unbounded loop. + directory = memory_core.data_dir() + _sweep_debris(directory) + for _ in range(MAX_PARKED_PER_RUN): + parked = _claim_parked(directory) + if parked is None: + break + count, delivered = _drain(parked) + sent += count + if not delivered: + break + return sent + + +def _drain(claim: Path | None) -> tuple[int, bool]: + """Post one claimed batch file, recording progress after every batch. + + Returns (events sent, whether everything was delivered). + """ if claim is None: - return 0 + return 0, True try: lines = claim.read_text(encoding="utf-8").splitlines() + except ValueError: + # UnicodeDecodeError from a torn write: the content is unrecoverable, so + # quarantine rather than retry. flush() runs from a bare `finally:` in + # flush_worker, so raising here also skips the handoff cleanup, and an + # undecodable file would otherwise be re-read on every flush forever. + # Reported as delivered because there is nothing left to deliver and the + # rest of the run should continue. + try: + claim.replace(claim.with_suffix(".corrupt")) + except OSError: + try: + claim.unlink() + except OSError: + pass + return 0, True except OSError: - return 0 + # Could not read it, which is not the same as having nothing to send. + # The file is left exactly where it is: a vanished or briefly unreadable + # claim is retryable, and quarantining it here would discard events over + # a transient filesystem error. Reported as undelivered so the run stops + # instead of counting a batch nothing was posted from as delivered. + return 0, False events = [] for line in lines: try: @@ -497,11 +715,18 @@ def flush() -> int: if isinstance(value, dict) and value.get("event"): events.append(value) if not events: + # Only delete when the file really is empty. A non-empty file that + # parses to nothing is a torn write, and its contents are the unsent + # remainder — deleting it is the data loss this PR exists to prevent. try: - claim.unlink() + empty = claim.stat().st_size == 0 + except OSError: + empty = True + try: + claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink() except OSError: pass - return 0 + return 0, True distinct_id, aliased_anonymous_id = resolve_distinct_id() if aliased_anonymous_id: @@ -520,10 +745,13 @@ def flush() -> int: sent = 0 for start in range(0, len(events), BATCH_SIZE): + chunk = events[start : start + BATCH_SIZE] batch = [ { "event": event["event"], "distinct_id": distinct_id, + # Carried through from record() so a resend can be collapsed. + "uuid": event.get("uuid"), "timestamp": event.get("timestamp"), "properties": { # Fallback only: events recorded by a build before source @@ -535,16 +763,24 @@ def flush() -> int: **(event.get("properties") or {}), }, } - for event in events[start : start + BATCH_SIZE] + for event in chunk ] if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL): - return sent - sent += len(batch) - try: - claim.unlink() - except OSError: - pass - return sent + # Keep only what has not been delivered, and release the lease. + # Previously the whole file was kept and the retry re-posted every + # batch, including the ones that had already arrived. + _release_claim(claim, events[start:]) + return sent, False + sent += len(chunk) + # Record progress and refresh the lease after each successful batch, so + # a crash repeats at most one batch instead of the entire file. If the + # rewrite fails the claim still holds delivered events, so stop rather + # than carry on as though progress were recorded — continuing is how the + # duplicate delivery this PR fixes would come back. + if not _rewrite_claim(claim, events[start + len(chunk) :]): + _release_claim(claim, events[start + len(chunk) :]) + return sent, False + return sent, True def main() -> int: diff --git a/integrations/agent-plugin-core/tests/test_spool_delivery.py b/integrations/agent-plugin-core/tests/test_spool_delivery.py new file mode 100644 index 000000000..accd631a6 --- /dev/null +++ b/integrations/agent-plugin-core/tests/test_spool_delivery.py @@ -0,0 +1,446 @@ +"""Delivery semantics of the telemetry spool: no duplicates, no starvation. + +These run against a built host's core in-process (not a subprocess) because they +need to inject failures into ``_post``. The identity tests next door cover the +uninitialised-process case that needs a real interpreter. +""" + +from __future__ import annotations + +import importlib +import json +import os +import sys +import time +from pathlib import Path + +import pytest + +CORE_ROOT = Path(__file__).resolve().parents[1] +REPOSITORY_ROOT = CORE_ROOT.parents[1] +HOST_CORE = REPOSITORY_ROOT / "integrations" / "claude-code-plugin" / "core" + +pytestmark = pytest.mark.skipif(not HOST_CORE.exists(), reason="claude-code-plugin is not built") + + +@pytest.fixture() +def telemetry(tmp_path, monkeypatch): + # CI runs this directory and claude-code-plugin/tests in ONE pytest process, + # and that suite's conftest sets MEM0_TELEMETRY=false at import, process-wide. + # Without this the whole file silently no-ops: record() returns early and + # every assertion sees an empty spool. Do not rely on ambient env. + monkeypatch.setenv("MEM0_TELEMETRY", "true") + monkeypatch.setenv("MEM0_CODE_DATA_DIR", str(tmp_path / "data")) + monkeypatch.syspath_prepend(str(HOST_CORE)) + + # Save and RESTORE rather than delete. claude-code-plugin/tests/conftest.py + # imports memory_core once at collection and calls configure_harness() on it; + # dropping the module left a later re-import with default harness config, so + # tests in that suite failed depending on collection order. + names = ("telemetry", "memory_core", "_harness_id") + saved = {name: sys.modules.get(name) for name in names} + for name in names: + sys.modules.pop(name, None) + + module = importlib.import_module("telemetry") + monkeypatch.setattr(module, "resolve_distinct_id", lambda: ("tester@example.com", "")) + try: + yield module + finally: + for name in names: + sys.modules.pop(name, None) + if saved[name] is not None: + sys.modules[name] = saved[name] + + +def _delivered(payloads): + return [event for payload in payloads if "batch" in payload for event in payload["batch"]] + + +def test_a_partial_failure_does_not_redeliver_what_already_arrived(telemetry): + """Defect 2a: flush kept the whole claim on failure and retried from the top. + + 150 events across two batches, the second failing, previously delivered 250. + """ + for index in range(150): + telemetry.record("search", index=index) + + sent: list[dict] = [] + calls = {"n": 0} + + def flaky(payload, url): + calls["n"] += 1 + if calls["n"] == 2: # second batch fails + return False + sent.append(payload) + return True + + telemetry._post = flaky + telemetry.flush() + + telemetry._post = lambda payload, url: sent.append(payload) or True + telemetry.flush() + + events = _delivered(sent) + assert len(events) == 150 + assert len({event["uuid"] for event in events}) == 150 + + +def test_a_fresh_claim_is_not_immediately_stealable(telemetry): + """Defect 2b: rename preserves mtime, so a claim inherited the spool's age. + + With the last write older than the stale threshold, a claim made now looked + abandoned the instant it existed and a second sender took it over. + """ + telemetry.record("search") + spool = telemetry._spool_path() + old = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60) + os.utime(spool, (old, old)) + + first = telemetry._claim_spool() + assert first is not None + + # A second sender starting right now must find nothing to take. + assert telemetry._claim_parked(first.parent) is None + + +def test_a_live_final_attempt_is_not_deleted_by_another_sender(telemetry): + """Review finding: exhaustion was judged before liveness, so owners lost batches. + + Claiming a parked file bumps its attempt count and refreshes its mtime. Once + the count reaches the budget, the owner draining it looked exhausted to every + other sender, which unlinked the file out from under it. Everything in that + batch was gone, which is precisely the loss this PR exists to stop. + """ + telemetry.record("search", reason="owned-by-the-first-sender") + spool = telemetry._spool_path() + stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60) + os.utime(spool, (stale, stale)) + + claim = telemetry._claim_spool() + assert claim is not None + + # Walk it to the final attempt, ageing it each round so it can be re-claimed. + # _claim_spool hands back a0 and _release_claim keeps the name, so it takes + # one full round per attempt to reach the budget. + for _ in range(telemetry.MAX_CLAIM_ATTEMPTS): + # Carry the marker through each rewrite so the final assertion proves the + # events survived, not merely that some file with the right name did. + telemetry._release_claim(claim, [{"event": "code.search", "uuid": "owned-by-the-first-sender"}]) + parked = sorted(claim.parent.glob("telemetry-*.sending")) + assert parked, "the batch was dropped while still inside its budget" + os.utime(parked[0], (stale, stale)) + claim = telemetry._claim_parked(claim.parent) + assert claim is not None + + assert telemetry._claim_attempt(claim) >= telemetry.MAX_CLAIM_ATTEMPTS + assert claim.exists() + + # The owner is draining it right now: fresh mtime, live lease. + second_sender = telemetry._claim_parked(claim.parent) + + assert second_sender is None, "a second sender took a batch under a live lease" + assert claim.exists(), "a second sender deleted a batch its owner was draining" + assert "owned-by-the-first-sender" in claim.read_text(encoding="utf-8") + + +def test_an_exhausted_batch_is_still_discarded_once_its_lease_lapses(telemetry): + """The liveness check must defer the cleanup, not cancel it. + + Guards the obvious over-correction: skipping live claims is only safe if an + abandoned one at the same attempt count is still reaped on a later run. + """ + telemetry.record("search") + spool = telemetry._spool_path() + stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60) + os.utime(spool, (stale, stale)) + + claim = telemetry._claim_spool() + assert claim is not None + exhausted = claim.parent / telemetry._claim_name(telemetry.MAX_CLAIM_ATTEMPTS) + claim.replace(exhausted) + os.utime(exhausted, (stale, stale)) + + assert telemetry._claim_parked(exhausted.parent) is None + assert not exhausted.exists(), "an abandoned exhausted batch was left behind forever" + + +def test_a_parked_batch_is_drained_behind_the_live_spool(telemetry): + """Defect 6: parked claims were only reachable when no spool existed. + + Because sessions keep recording there usually was one, so a batch parked by + a failed send waited until the 7-day expiry deleted it unsent — even though + its own presence is what starts the sender. + """ + telemetry.record("parked") + telemetry._post = lambda payload, url: False + telemetry.flush() + + parked = list(telemetry.memory_core.data_dir().glob("telemetry-*.sending")) + assert len(parked) == 1 + old = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60) + os.utime(parked[0], (old, old)) + + telemetry.record("fresh") + sent: list[dict] = [] + telemetry._post = lambda payload, url: sent.append(payload) or True + telemetry.flush() + + names = {event["event"] for event in _delivered(sent)} + assert names == {"code.parked", "code.fresh"} + + +def test_a_batch_is_retried_until_the_budget_is_spent_not_discarded(telemetry): + """Expiry discards what failed repeatedly, not what merely sat for a while. + + The budget is the attempt count, because age cannot be one: every re-claim + touches the mtime and every release backdates it, so age never accumulates. + """ + telemetry.record("parked") + telemetry._post = lambda payload, url: False + telemetry.flush() + + parked = list(telemetry.memory_core.data_dir().glob("telemetry-*.sending")) + assert len(parked) == 1 + assert telemetry._claim_attempt(parked[0]) < telemetry.MAX_CLAIM_ATTEMPTS + + sent: list[dict] = [] + telemetry._post = lambda payload, url: sent.append(payload) or True + telemetry.flush() + + assert [event["event"] for event in _delivered(sent)] == ["code.parked"] + + +def test_progress_is_recorded_after_every_batch(telemetry): + """A crash repeats at most one batch, not the whole file.""" + for index in range(250): + telemetry.record("search", index=index) + + calls = {"n": 0} + + def die_after_two(payload, url): + calls["n"] += 1 + if calls["n"] > 2: + return False + return True + + telemetry._post = die_after_two + telemetry.flush() + + parked = list(telemetry.memory_core.data_dir().glob("telemetry-*.sending")) + assert len(parked) == 1 + remaining = parked[0].read_text(encoding="utf-8").strip().splitlines() + # Two batches of 100 landed; only the last 50 should still be pending. + assert len(remaining) == 50 + assert json.loads(remaining[0])["properties"]["index"] == 200 + + +def test_the_heartbeat_actually_refreshes_the_lease(telemetry): + """The claim rewrite doubles as the lease heartbeat. + + Previously asserted `SEND_TIMEOUT * 4 < CLAIM_STALE_SECONDS`, which compares + two constants and executes none of the code under test. Drive the real + rewrite and watch the mtime move instead. + """ + for index in range(150): + telemetry.record("search", index=index) + claim = telemetry._claim_spool() + assert claim is not None + + stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60) + os.utime(claim, (stale, stale)) + assert time.time() - claim.stat().st_mtime > telemetry.CLAIM_STALE_SECONDS + + telemetry._rewrite_claim(claim, [{"event": "code.x", "properties": {}}]) + assert time.time() - claim.stat().st_mtime < telemetry.CLAIM_STALE_SECONDS + + +def test_an_undeliverable_batch_is_eventually_given_up_on(telemetry): + """Expiry has to be reachable from a state the state machine can produce. + + It was not: every re-claim touched the mtime and every release backdated it + by a fixed amount, so age hovered near the stale threshold and the 7-day + expiry never fired. An undeliverable batch lived on disk forever, and + spawn_flush saw it and started a sender on every hook. + """ + telemetry.record("doomed") + telemetry._post = lambda payload, url: False + + directory = telemetry.memory_core.data_dir() + for _ in range(telemetry.MAX_CLAIM_ATTEMPTS + 3): + telemetry.flush() + # Attempts now carry a cooldown, so a released claim is not instantly + # reclaimable. Age it to stand in for the wall time a real retry waits; + # without this the loop spins inside one cooldown and proves nothing. + for parked in directory.glob("telemetry-*.sending"): + stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60) + os.utime(parked, (stale, stale)) + + leftover = list(directory.glob("telemetry-*.sending")) + assert leftover == [], f"batch never given up on: {[p.name for p in leftover]}" + + +def test_a_batch_that_cannot_be_read_is_not_counted_as_delivered(telemetry): + """Review finding: a read failure reported 'everything delivered'. + + Nothing was posted, so calling it delivered lets flush() carry on to other + claims as though this batch had arrived, and hides the failure from the one + signal that says the run went badly. It also must not quarantine: a briefly + unreadable file is retryable, and moving it to .corrupt discards the events + over a transient filesystem error, because nothing ever re-globs .corrupt. + """ + telemetry.record("search") + spool = telemetry._spool_path() + stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60) + os.utime(spool, (stale, stale)) + claim = telemetry._claim_spool() + assert claim is not None + + original = Path.read_text + + def unreadable(self, *args, **kwargs): + if self == claim: + raise OSError(5, "I/O error") + return original(self, *args, **kwargs) + + Path.read_text = unreadable + try: + sent, delivered = telemetry._drain(claim) + finally: + Path.read_text = original + + assert sent == 0 + assert delivered is False, "an unread batch was reported as delivered" + assert claim.exists(), "a transient read error discarded the batch" + assert not list(claim.parent.glob("*.corrupt")), "quarantined over a transient error" + + +def test_undecodable_content_is_still_quarantined_and_the_run_continues(telemetry): + """The other half: genuinely unrecoverable content must not block the run. + + Guards the over-correction. If every read problem returned undelivered, one + torn file would stop every later claim on every flush, forever. + """ + telemetry.record("search") + spool = telemetry._spool_path() + stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60) + os.utime(spool, (stale, stale)) + claim = telemetry._claim_spool() + assert claim is not None + claim.write_bytes(b"\xff\xfe torn \x00 write") + + sent, delivered = telemetry._drain(claim) + + assert (sent, delivered) == (0, True) + assert not claim.exists() + assert list(claim.parent.glob("*.corrupt")), "unrecoverable content was not quarantined" + + +def test_retries_are_spread_over_real_time_not_burned_at_once(telemetry): + """Review finding: releasing straight to reclaimable spent the budget instantly. + + Two senders hitting one momentary failure could walk a batch from attempt 0 + to the limit within seconds and discard it, when a retry a minute later would + have delivered. Each release now has to age past a cooldown that grows with + the attempts already spent. + """ + telemetry.record("doomed") + telemetry._post = lambda payload, url: False + + directory = telemetry.memory_core.data_dir() + telemetry.flush() + + parked = list(directory.glob("telemetry-*.sending")) + assert parked, "the batch was discarded on its first failure" + assert telemetry._claim_attempt(parked[0]) == 0 + + # Second sender, immediately: the cooldown has not elapsed, so it must not + # be able to spend another attempt. + telemetry.flush() + still = list(directory.glob("telemetry-*.sending")) + assert len(still) == 1 + assert telemetry._claim_attempt(still[0]) <= 1, "burned attempts without waiting" + + +def test_a_legacy_claim_filename_is_not_mistaken_for_a_huge_attempt_count(telemetry): + """The old shape is telemetry--.sending, and hex can start with 'a'.""" + assert telemetry._claim_attempt(Path("telemetry-999-deadbeef.sending")) == 0 + assert telemetry._claim_attempt(Path("telemetry-999-a1234567.sending")) == 0 + assert telemetry._claim_attempt(Path("telemetry-999-deadbeef-a2.sending")) == 2 + + +def test_a_torn_claim_is_quarantined_not_deleted(telemetry): + """A non-empty file that parses to nothing is the remainder, not garbage.""" + telemetry.record("search") + claim = telemetry._claim_spool() + claim.write_bytes(b"\xff\xfe not utf-8 at all") + stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60) + os.utime(claim, (stale, stale)) + + sent = telemetry.flush() + + assert sent == 0 + assert not claim.exists() + quarantined = list(telemetry.memory_core.data_dir().glob("*.corrupt")) + assert len(quarantined) == 1, "torn claim was destroyed instead of kept" + + +def test_a_failed_rewrite_stops_instead_of_redelivering(telemetry): + """Ignoring the rewrite result reintroduced the duplicates this PR fixes.""" + for index in range(250): + telemetry.record("search", index=index) + + telemetry._rewrite_claim = lambda claim, remaining: False + delivered = [] + telemetry._post = lambda payload, url: delivered.extend(payload.get("batch", [])) or True + + telemetry.flush() + assert len(delivered) == 100, f"kept going after a failed rewrite: {len(delivered)}" + + +def test_partial_files_are_swept(telemetry): + """Nothing else globs *.partial, so a crash mid-rename orphans one forever.""" + data_dir = telemetry.memory_core.data_dir() + data_dir.mkdir(parents=True, exist_ok=True) + debris = data_dir / "telemetry-1-abc-a0.1.partial" + debris.write_text("x", encoding="utf-8") + old = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60) + os.utime(debris, (old, old)) + + telemetry.flush() + assert not debris.exists() + + +def test_quarantined_batches_are_eventually_collected(telemetry): + """Nothing re-globs .corrupt, so without a sweep they live on disk forever. + + Kept much longer than .partial debris on purpose: a quarantined batch is the + only remaining evidence of events that could not be delivered. + """ + directory = telemetry.memory_core.data_dir() + directory.mkdir(parents=True, exist_ok=True) + fresh = directory / "telemetry-1-aaaaaaaa-a0.corrupt" + old = directory / "telemetry-2-bbbbbbbb-a0.corrupt" + for path in (fresh, old): + path.write_text("torn", encoding="utf-8") + expired = time.time() - (telemetry.CLAIM_EXPIRY_SECONDS + 60) + os.utime(old, (expired, expired)) + + telemetry._sweep_debris(directory) + + assert fresh.exists(), "a recent quarantine was discarded before anyone could look at it" + assert not old.exists(), "an expired quarantine was left on disk forever" + + +def test_temp_files_orphaned_by_a_kill_are_collected(telemetry): + """_write_identity and _install_salt unlink in a finally, which SIGKILL skips.""" + directory = telemetry.memory_core.data_dir() + directory.mkdir(parents=True, exist_ok=True) + orphan = directory / "telemetry-salt.999.tmp" + orphan.write_text("abandoned", encoding="utf-8") + stale = time.time() - (telemetry.CLAIM_STALE_SECONDS + 60) + os.utime(orphan, (stale, stale)) + + telemetry._sweep_debris(directory) + + assert not orphan.exists(), "a killed process left a temp file on disk forever" diff --git a/integrations/antigravity-plugin/core/telemetry.py b/integrations/antigravity-plugin/core/telemetry.py index 6d7aeecae..a4375f002 100644 --- a/integrations/antigravity-plugin/core/telemetry.py +++ b/integrations/antigravity-plugin/core/telemetry.py @@ -100,6 +100,16 @@ BATCH_SIZE = 100 SEND_TIMEOUT = 5 CLAIM_STALE_SECONDS = 120 CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60 +# A batch is only discarded once it has genuinely been retried this many times. +MAX_CLAIM_ATTEMPTS = 3 +# Parked claims drained per run, after the live spool. Bounded so a long backlog +# cannot turn one flush into an unbounded send loop. +MAX_PARKED_PER_RUN = 3 +# Added to the wait before a released claim becomes reclaimable, per attempt +# already spent. Releasing straight to "reclaimable now" let two senders burn the +# whole budget within seconds of one another on a single momentary failure, and +# discard a batch a retry a minute later would have delivered. +RETRY_COOLDOWN_SECONDS = 60 def is_enabled() -> bool: @@ -399,38 +409,201 @@ def spawn_flush() -> bool: return False +def _claim_name(attempt: int = 0) -> str: + """Claim filename. The attempt count rides in the name so the 7-day expiry + only ever discards a batch that was actually retried and failed.""" + return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending" + + +def _claim_attempt(claim: Path) -> int: + """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape. + + Anchored on field position, not on a leading "a": the legacy shape is + ``telemetry--.sending`` and a hex id such as ``a1234567`` would + otherwise parse as attempt 1234567 and be discarded unsent on the first + flush after an upgrade. + """ + stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name + parts = stem.split("-") + if len(parts) != 4: + return 0 + tail = parts[3] + if tail.startswith("a") and tail[1:].isdigit(): + return int(tail[1:]) + return 0 + + +def _touch(path: Path) -> None: + """Refresh mtime so a claim's age measures time since it was claimed. + + ``Path.replace`` is ``os.rename``, which preserves mtime — so a claim created + after a quiet minute inherited the spool's last-write time and looked + abandoned the instant it was made. A second sender would then take it over + while the first was still posting, and both would deliver the batch. + """ + try: + os.utime(path, None) + except OSError: + pass + + def _claim_spool() -> Path | None: """Rename the spool aside so exactly one sender owns each batch.""" directory = memory_core.data_dir() - claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending" + claim = directory / _claim_name() spool = _spool_path() try: spool.replace(claim) + _touch(claim) return claim except OSError: pass + return _claim_parked(directory) + + +def _sweep_debris(directory: Path) -> None: + """Remove files nothing else will ever pick up again. + + *.partial is a temp file orphaned by a crash between write and rename. + *.corrupt is a batch quarantined for undecodable content. No glob in this + module matches either, so without this they accumulate on disk for the life + of the install. + + Quarantined batches are kept far longer than debris: they are the only + evidence left of events that could not be delivered, and someone diagnosing + a report of missing telemetry has to be able to find one. + """ now = time.time() - for orphan in sorted(directory.glob("telemetry-*.sending")): + for debris in directory.glob("telemetry-*.partial"): + try: + if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS: + debris.unlink() + except OSError: + continue + for quarantined in directory.glob("telemetry-*.corrupt"): + try: + if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS: + quarantined.unlink() + except OSError: + continue + # The same reasoning covers *.tmp. _write_identity and _install_salt both + # create one and unlink it in a finally, which a SIGKILL skips, and no glob + # in this module matches the leftovers either. + for temporary in directory.glob("telemetry-*.tmp"): + try: + if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS: + temporary.unlink() + except OSError: + continue + + +def _claim_parked(directory: Path) -> Path | None: + """Take the oldest abandoned claim, if any lease has actually expired. + + Kept separate from the live spool so flush() can drain both in one run. + Previously parked batches were only reachable when no spool existed at all, + and because sessions keep recording there usually was one — so a batch + parked by a failed send waited until the 7-day expiry deleted it unsent, + even though its own presence is what started the sender. + """ + now = time.time() + for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime): try: age = now - orphan.stat().st_mtime except OSError: continue - if age > CLAIM_EXPIRY_SECONDS: + if age < CLAIM_STALE_SECONDS: + # Someone else holds a live lease on it. This check has to come + # first. Claiming a file bumps its attempt count and refreshes its + # mtime, so a sender that has just taken the final attempt looks + # exhausted to everyone else while it is actively draining. Judging + # exhaustion before liveness let a second sender unlink a batch out + # from under its owner, losing every event in it. + continue + # Attempts, not age. Every re-claim touches the mtime and every release + # backdates it by a fixed amount, so age is pinned near the stale + # threshold and never reaches the expiry. Age stays only as a backstop + # for files that never carried an attempt marker. + if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS: try: orphan.unlink() except OSError: pass continue - if age < CLAIM_STALE_SECONDS: - continue + claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1) try: orphan.replace(claim) + _touch(claim) return claim except OSError: continue return None +def _safe_mtime(path: Path) -> float: + try: + return path.stat().st_mtime + except OSError: + return 0.0 + + +def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool: + """Persist the unsent remainder, atomically, and refresh the lease. + + Called after every successful batch. Two jobs: a retry resumes where the + send stopped instead of re-posting from the top, and the rewrite doubles as + the lease heartbeat, so a slow sender does not have its claim stolen + mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS. + """ + if not remaining: + try: + claim.unlink() + except OSError: + pass + return True + temporary = claim.with_suffix(f".{os.getpid()}.partial") + try: + payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining) + # fsync before the rename: without it the rename can land while the + # bytes have not, and the claim comes back empty or truncated after a + # crash. _drain then reads zero events and unlinks it. + with open(temporary, "w", encoding="utf-8") as handle: + handle.write(payload) + handle.flush() + os.fsync(handle.fileno()) + temporary.replace(claim) + _touch(claim) + return True + except OSError: + try: + temporary.unlink() + except OSError: + pass + return False + + +def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None: + """Persist the remainder and drop the lease, because this sender has given up. + + Distinct from the per-batch heartbeat: heartbeating on the way out would + make an abandoned batch look actively owned for a further + CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the + threshold lets the next flush pick it up immediately, while the attempt + count in the filename still bounds how many times that can happen. + """ + if not _rewrite_claim(claim, remaining): + return + try: + # Backdate past the stale threshold so the next flush can pick it up, + # minus a cooldown that grows with the attempts already spent. Clamped so + # the mtime never lands in the future, which would read as a live lease. + cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS) + released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown + os.utime(claim, (released, released)) + except OSError: + pass + + def _resolve_email(key: str) -> str: """Trade the API key for the account email so events join other Mem0 surfaces.""" url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/" @@ -478,16 +651,61 @@ def resolve_distinct_id() -> tuple[str, str]: def flush() -> int: - """Drain claimed spools to PostHog and return the number of events sent.""" + """Drain the live spool, then any parked claims, and return events sent.""" if not is_enabled(): return 0 - claim = _claim_spool() + sent, delivered = _drain(_claim_spool()) + if not delivered: + # The network is failing. Retrying other batches now would only burn + # their attempt budget against the same broken connection. + return sent + + # Parked batches used to starve behind the live spool indefinitely. Bounded + # per run so a long backlog cannot turn one flush into an unbounded loop. + directory = memory_core.data_dir() + _sweep_debris(directory) + for _ in range(MAX_PARKED_PER_RUN): + parked = _claim_parked(directory) + if parked is None: + break + count, delivered = _drain(parked) + sent += count + if not delivered: + break + return sent + + +def _drain(claim: Path | None) -> tuple[int, bool]: + """Post one claimed batch file, recording progress after every batch. + + Returns (events sent, whether everything was delivered). + """ if claim is None: - return 0 + return 0, True try: lines = claim.read_text(encoding="utf-8").splitlines() + except ValueError: + # UnicodeDecodeError from a torn write: the content is unrecoverable, so + # quarantine rather than retry. flush() runs from a bare `finally:` in + # flush_worker, so raising here also skips the handoff cleanup, and an + # undecodable file would otherwise be re-read on every flush forever. + # Reported as delivered because there is nothing left to deliver and the + # rest of the run should continue. + try: + claim.replace(claim.with_suffix(".corrupt")) + except OSError: + try: + claim.unlink() + except OSError: + pass + return 0, True except OSError: - return 0 + # Could not read it, which is not the same as having nothing to send. + # The file is left exactly where it is: a vanished or briefly unreadable + # claim is retryable, and quarantining it here would discard events over + # a transient filesystem error. Reported as undelivered so the run stops + # instead of counting a batch nothing was posted from as delivered. + return 0, False events = [] for line in lines: try: @@ -497,11 +715,18 @@ def flush() -> int: if isinstance(value, dict) and value.get("event"): events.append(value) if not events: + # Only delete when the file really is empty. A non-empty file that + # parses to nothing is a torn write, and its contents are the unsent + # remainder — deleting it is the data loss this PR exists to prevent. try: - claim.unlink() + empty = claim.stat().st_size == 0 + except OSError: + empty = True + try: + claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink() except OSError: pass - return 0 + return 0, True distinct_id, aliased_anonymous_id = resolve_distinct_id() if aliased_anonymous_id: @@ -520,10 +745,13 @@ def flush() -> int: sent = 0 for start in range(0, len(events), BATCH_SIZE): + chunk = events[start : start + BATCH_SIZE] batch = [ { "event": event["event"], "distinct_id": distinct_id, + # Carried through from record() so a resend can be collapsed. + "uuid": event.get("uuid"), "timestamp": event.get("timestamp"), "properties": { # Fallback only: events recorded by a build before source @@ -535,16 +763,24 @@ def flush() -> int: **(event.get("properties") or {}), }, } - for event in events[start : start + BATCH_SIZE] + for event in chunk ] if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL): - return sent - sent += len(batch) - try: - claim.unlink() - except OSError: - pass - return sent + # Keep only what has not been delivered, and release the lease. + # Previously the whole file was kept and the retry re-posted every + # batch, including the ones that had already arrived. + _release_claim(claim, events[start:]) + return sent, False + sent += len(chunk) + # Record progress and refresh the lease after each successful batch, so + # a crash repeats at most one batch instead of the entire file. If the + # rewrite fails the claim still holds delivered events, so stop rather + # than carry on as though progress were recorded — continuing is how the + # duplicate delivery this PR fixes would come back. + if not _rewrite_claim(claim, events[start + len(chunk) :]): + _release_claim(claim, events[start + len(chunk) :]) + return sent, False + return sent, True def main() -> int: diff --git a/integrations/claude-code-plugin/core/telemetry.py b/integrations/claude-code-plugin/core/telemetry.py index 6d7aeecae..a4375f002 100644 --- a/integrations/claude-code-plugin/core/telemetry.py +++ b/integrations/claude-code-plugin/core/telemetry.py @@ -100,6 +100,16 @@ BATCH_SIZE = 100 SEND_TIMEOUT = 5 CLAIM_STALE_SECONDS = 120 CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60 +# A batch is only discarded once it has genuinely been retried this many times. +MAX_CLAIM_ATTEMPTS = 3 +# Parked claims drained per run, after the live spool. Bounded so a long backlog +# cannot turn one flush into an unbounded send loop. +MAX_PARKED_PER_RUN = 3 +# Added to the wait before a released claim becomes reclaimable, per attempt +# already spent. Releasing straight to "reclaimable now" let two senders burn the +# whole budget within seconds of one another on a single momentary failure, and +# discard a batch a retry a minute later would have delivered. +RETRY_COOLDOWN_SECONDS = 60 def is_enabled() -> bool: @@ -399,38 +409,201 @@ def spawn_flush() -> bool: return False +def _claim_name(attempt: int = 0) -> str: + """Claim filename. The attempt count rides in the name so the 7-day expiry + only ever discards a batch that was actually retried and failed.""" + return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending" + + +def _claim_attempt(claim: Path) -> int: + """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape. + + Anchored on field position, not on a leading "a": the legacy shape is + ``telemetry--.sending`` and a hex id such as ``a1234567`` would + otherwise parse as attempt 1234567 and be discarded unsent on the first + flush after an upgrade. + """ + stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name + parts = stem.split("-") + if len(parts) != 4: + return 0 + tail = parts[3] + if tail.startswith("a") and tail[1:].isdigit(): + return int(tail[1:]) + return 0 + + +def _touch(path: Path) -> None: + """Refresh mtime so a claim's age measures time since it was claimed. + + ``Path.replace`` is ``os.rename``, which preserves mtime — so a claim created + after a quiet minute inherited the spool's last-write time and looked + abandoned the instant it was made. A second sender would then take it over + while the first was still posting, and both would deliver the batch. + """ + try: + os.utime(path, None) + except OSError: + pass + + def _claim_spool() -> Path | None: """Rename the spool aside so exactly one sender owns each batch.""" directory = memory_core.data_dir() - claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending" + claim = directory / _claim_name() spool = _spool_path() try: spool.replace(claim) + _touch(claim) return claim except OSError: pass + return _claim_parked(directory) + + +def _sweep_debris(directory: Path) -> None: + """Remove files nothing else will ever pick up again. + + *.partial is a temp file orphaned by a crash between write and rename. + *.corrupt is a batch quarantined for undecodable content. No glob in this + module matches either, so without this they accumulate on disk for the life + of the install. + + Quarantined batches are kept far longer than debris: they are the only + evidence left of events that could not be delivered, and someone diagnosing + a report of missing telemetry has to be able to find one. + """ now = time.time() - for orphan in sorted(directory.glob("telemetry-*.sending")): + for debris in directory.glob("telemetry-*.partial"): + try: + if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS: + debris.unlink() + except OSError: + continue + for quarantined in directory.glob("telemetry-*.corrupt"): + try: + if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS: + quarantined.unlink() + except OSError: + continue + # The same reasoning covers *.tmp. _write_identity and _install_salt both + # create one and unlink it in a finally, which a SIGKILL skips, and no glob + # in this module matches the leftovers either. + for temporary in directory.glob("telemetry-*.tmp"): + try: + if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS: + temporary.unlink() + except OSError: + continue + + +def _claim_parked(directory: Path) -> Path | None: + """Take the oldest abandoned claim, if any lease has actually expired. + + Kept separate from the live spool so flush() can drain both in one run. + Previously parked batches were only reachable when no spool existed at all, + and because sessions keep recording there usually was one — so a batch + parked by a failed send waited until the 7-day expiry deleted it unsent, + even though its own presence is what started the sender. + """ + now = time.time() + for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime): try: age = now - orphan.stat().st_mtime except OSError: continue - if age > CLAIM_EXPIRY_SECONDS: + if age < CLAIM_STALE_SECONDS: + # Someone else holds a live lease on it. This check has to come + # first. Claiming a file bumps its attempt count and refreshes its + # mtime, so a sender that has just taken the final attempt looks + # exhausted to everyone else while it is actively draining. Judging + # exhaustion before liveness let a second sender unlink a batch out + # from under its owner, losing every event in it. + continue + # Attempts, not age. Every re-claim touches the mtime and every release + # backdates it by a fixed amount, so age is pinned near the stale + # threshold and never reaches the expiry. Age stays only as a backstop + # for files that never carried an attempt marker. + if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS: try: orphan.unlink() except OSError: pass continue - if age < CLAIM_STALE_SECONDS: - continue + claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1) try: orphan.replace(claim) + _touch(claim) return claim except OSError: continue return None +def _safe_mtime(path: Path) -> float: + try: + return path.stat().st_mtime + except OSError: + return 0.0 + + +def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool: + """Persist the unsent remainder, atomically, and refresh the lease. + + Called after every successful batch. Two jobs: a retry resumes where the + send stopped instead of re-posting from the top, and the rewrite doubles as + the lease heartbeat, so a slow sender does not have its claim stolen + mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS. + """ + if not remaining: + try: + claim.unlink() + except OSError: + pass + return True + temporary = claim.with_suffix(f".{os.getpid()}.partial") + try: + payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining) + # fsync before the rename: without it the rename can land while the + # bytes have not, and the claim comes back empty or truncated after a + # crash. _drain then reads zero events and unlinks it. + with open(temporary, "w", encoding="utf-8") as handle: + handle.write(payload) + handle.flush() + os.fsync(handle.fileno()) + temporary.replace(claim) + _touch(claim) + return True + except OSError: + try: + temporary.unlink() + except OSError: + pass + return False + + +def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None: + """Persist the remainder and drop the lease, because this sender has given up. + + Distinct from the per-batch heartbeat: heartbeating on the way out would + make an abandoned batch look actively owned for a further + CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the + threshold lets the next flush pick it up immediately, while the attempt + count in the filename still bounds how many times that can happen. + """ + if not _rewrite_claim(claim, remaining): + return + try: + # Backdate past the stale threshold so the next flush can pick it up, + # minus a cooldown that grows with the attempts already spent. Clamped so + # the mtime never lands in the future, which would read as a live lease. + cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS) + released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown + os.utime(claim, (released, released)) + except OSError: + pass + + def _resolve_email(key: str) -> str: """Trade the API key for the account email so events join other Mem0 surfaces.""" url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/" @@ -478,16 +651,61 @@ def resolve_distinct_id() -> tuple[str, str]: def flush() -> int: - """Drain claimed spools to PostHog and return the number of events sent.""" + """Drain the live spool, then any parked claims, and return events sent.""" if not is_enabled(): return 0 - claim = _claim_spool() + sent, delivered = _drain(_claim_spool()) + if not delivered: + # The network is failing. Retrying other batches now would only burn + # their attempt budget against the same broken connection. + return sent + + # Parked batches used to starve behind the live spool indefinitely. Bounded + # per run so a long backlog cannot turn one flush into an unbounded loop. + directory = memory_core.data_dir() + _sweep_debris(directory) + for _ in range(MAX_PARKED_PER_RUN): + parked = _claim_parked(directory) + if parked is None: + break + count, delivered = _drain(parked) + sent += count + if not delivered: + break + return sent + + +def _drain(claim: Path | None) -> tuple[int, bool]: + """Post one claimed batch file, recording progress after every batch. + + Returns (events sent, whether everything was delivered). + """ if claim is None: - return 0 + return 0, True try: lines = claim.read_text(encoding="utf-8").splitlines() + except ValueError: + # UnicodeDecodeError from a torn write: the content is unrecoverable, so + # quarantine rather than retry. flush() runs from a bare `finally:` in + # flush_worker, so raising here also skips the handoff cleanup, and an + # undecodable file would otherwise be re-read on every flush forever. + # Reported as delivered because there is nothing left to deliver and the + # rest of the run should continue. + try: + claim.replace(claim.with_suffix(".corrupt")) + except OSError: + try: + claim.unlink() + except OSError: + pass + return 0, True except OSError: - return 0 + # Could not read it, which is not the same as having nothing to send. + # The file is left exactly where it is: a vanished or briefly unreadable + # claim is retryable, and quarantining it here would discard events over + # a transient filesystem error. Reported as undelivered so the run stops + # instead of counting a batch nothing was posted from as delivered. + return 0, False events = [] for line in lines: try: @@ -497,11 +715,18 @@ def flush() -> int: if isinstance(value, dict) and value.get("event"): events.append(value) if not events: + # Only delete when the file really is empty. A non-empty file that + # parses to nothing is a torn write, and its contents are the unsent + # remainder — deleting it is the data loss this PR exists to prevent. try: - claim.unlink() + empty = claim.stat().st_size == 0 + except OSError: + empty = True + try: + claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink() except OSError: pass - return 0 + return 0, True distinct_id, aliased_anonymous_id = resolve_distinct_id() if aliased_anonymous_id: @@ -520,10 +745,13 @@ def flush() -> int: sent = 0 for start in range(0, len(events), BATCH_SIZE): + chunk = events[start : start + BATCH_SIZE] batch = [ { "event": event["event"], "distinct_id": distinct_id, + # Carried through from record() so a resend can be collapsed. + "uuid": event.get("uuid"), "timestamp": event.get("timestamp"), "properties": { # Fallback only: events recorded by a build before source @@ -535,16 +763,24 @@ def flush() -> int: **(event.get("properties") or {}), }, } - for event in events[start : start + BATCH_SIZE] + for event in chunk ] if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL): - return sent - sent += len(batch) - try: - claim.unlink() - except OSError: - pass - return sent + # Keep only what has not been delivered, and release the lease. + # Previously the whole file was kept and the retry re-posted every + # batch, including the ones that had already arrived. + _release_claim(claim, events[start:]) + return sent, False + sent += len(chunk) + # Record progress and refresh the lease after each successful batch, so + # a crash repeats at most one batch instead of the entire file. If the + # rewrite fails the claim still holds delivered events, so stop rather + # than carry on as though progress were recorded — continuing is how the + # duplicate delivery this PR fixes would come back. + if not _rewrite_claim(claim, events[start + len(chunk) :]): + _release_claim(claim, events[start + len(chunk) :]) + return sent, False + return sent, True def main() -> int: diff --git a/integrations/claude-code-plugin/tests/test_telemetry.py b/integrations/claude-code-plugin/tests/test_telemetry.py index 6029fa98a..de0db10c6 100644 --- a/integrations/claude-code-plugin/tests/test_telemetry.py +++ b/integrations/claude-code-plugin/tests/test_telemetry.py @@ -199,9 +199,11 @@ def test_a_stale_claim_is_reclaimed(isolated_env, monkeypatch): telemetry.record("search") orphan = telemetry._claim_spool() assert orphan is not None - monkeypatch.setattr( - telemetry.time, "time", lambda: orphan.stat().st_mtime + telemetry.CLAIM_STALE_SECONDS + 1 - ) + # Frozen rather than re-stat'd per call: flush() drains the live spool and + # then looks for parked claims in the same run, so by the second look this + # file no longer exists. + stale_now = orphan.stat().st_mtime + telemetry.CLAIM_STALE_SECONDS + 1 + monkeypatch.setattr(telemetry.time, "time", lambda: stale_now) with patch.object(telemetry, "_post", lambda payload, url: True): assert telemetry.flush() == 1 @@ -211,9 +213,13 @@ def test_an_expired_claim_is_dropped(isolated_env, monkeypatch): telemetry.record("search") orphan = telemetry._claim_spool() assert orphan is not None - monkeypatch.setattr( - telemetry.time, "time", lambda: orphan.stat().st_mtime + telemetry.CLAIM_EXPIRY_SECONDS + 1 - ) + expired_now = orphan.stat().st_mtime + telemetry.CLAIM_EXPIRY_SECONDS + 1 + monkeypatch.setattr(telemetry.time, "time", lambda: expired_now) + # Expiry now only discards a batch that was genuinely retried and failed, + # so age alone is not enough — age it past the attempt budget too. + retried = orphan.parent / orphan.name.replace("-a0.", f"-a{telemetry.MAX_CLAIM_ATTEMPTS}.") + orphan.replace(retried) + os.utime(retried, (expired_now, expired_now - telemetry.CLAIM_EXPIRY_SECONDS - 1)) assert telemetry._claim_spool() is None assert not list(memory_core.data_dir().glob("telemetry-*.sending")) diff --git a/integrations/codex-plugin/core/telemetry.py b/integrations/codex-plugin/core/telemetry.py index 6d7aeecae..a4375f002 100644 --- a/integrations/codex-plugin/core/telemetry.py +++ b/integrations/codex-plugin/core/telemetry.py @@ -100,6 +100,16 @@ BATCH_SIZE = 100 SEND_TIMEOUT = 5 CLAIM_STALE_SECONDS = 120 CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60 +# A batch is only discarded once it has genuinely been retried this many times. +MAX_CLAIM_ATTEMPTS = 3 +# Parked claims drained per run, after the live spool. Bounded so a long backlog +# cannot turn one flush into an unbounded send loop. +MAX_PARKED_PER_RUN = 3 +# Added to the wait before a released claim becomes reclaimable, per attempt +# already spent. Releasing straight to "reclaimable now" let two senders burn the +# whole budget within seconds of one another on a single momentary failure, and +# discard a batch a retry a minute later would have delivered. +RETRY_COOLDOWN_SECONDS = 60 def is_enabled() -> bool: @@ -399,38 +409,201 @@ def spawn_flush() -> bool: return False +def _claim_name(attempt: int = 0) -> str: + """Claim filename. The attempt count rides in the name so the 7-day expiry + only ever discards a batch that was actually retried and failed.""" + return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending" + + +def _claim_attempt(claim: Path) -> int: + """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape. + + Anchored on field position, not on a leading "a": the legacy shape is + ``telemetry--.sending`` and a hex id such as ``a1234567`` would + otherwise parse as attempt 1234567 and be discarded unsent on the first + flush after an upgrade. + """ + stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name + parts = stem.split("-") + if len(parts) != 4: + return 0 + tail = parts[3] + if tail.startswith("a") and tail[1:].isdigit(): + return int(tail[1:]) + return 0 + + +def _touch(path: Path) -> None: + """Refresh mtime so a claim's age measures time since it was claimed. + + ``Path.replace`` is ``os.rename``, which preserves mtime — so a claim created + after a quiet minute inherited the spool's last-write time and looked + abandoned the instant it was made. A second sender would then take it over + while the first was still posting, and both would deliver the batch. + """ + try: + os.utime(path, None) + except OSError: + pass + + def _claim_spool() -> Path | None: """Rename the spool aside so exactly one sender owns each batch.""" directory = memory_core.data_dir() - claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending" + claim = directory / _claim_name() spool = _spool_path() try: spool.replace(claim) + _touch(claim) return claim except OSError: pass + return _claim_parked(directory) + + +def _sweep_debris(directory: Path) -> None: + """Remove files nothing else will ever pick up again. + + *.partial is a temp file orphaned by a crash between write and rename. + *.corrupt is a batch quarantined for undecodable content. No glob in this + module matches either, so without this they accumulate on disk for the life + of the install. + + Quarantined batches are kept far longer than debris: they are the only + evidence left of events that could not be delivered, and someone diagnosing + a report of missing telemetry has to be able to find one. + """ now = time.time() - for orphan in sorted(directory.glob("telemetry-*.sending")): + for debris in directory.glob("telemetry-*.partial"): + try: + if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS: + debris.unlink() + except OSError: + continue + for quarantined in directory.glob("telemetry-*.corrupt"): + try: + if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS: + quarantined.unlink() + except OSError: + continue + # The same reasoning covers *.tmp. _write_identity and _install_salt both + # create one and unlink it in a finally, which a SIGKILL skips, and no glob + # in this module matches the leftovers either. + for temporary in directory.glob("telemetry-*.tmp"): + try: + if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS: + temporary.unlink() + except OSError: + continue + + +def _claim_parked(directory: Path) -> Path | None: + """Take the oldest abandoned claim, if any lease has actually expired. + + Kept separate from the live spool so flush() can drain both in one run. + Previously parked batches were only reachable when no spool existed at all, + and because sessions keep recording there usually was one — so a batch + parked by a failed send waited until the 7-day expiry deleted it unsent, + even though its own presence is what started the sender. + """ + now = time.time() + for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime): try: age = now - orphan.stat().st_mtime except OSError: continue - if age > CLAIM_EXPIRY_SECONDS: + if age < CLAIM_STALE_SECONDS: + # Someone else holds a live lease on it. This check has to come + # first. Claiming a file bumps its attempt count and refreshes its + # mtime, so a sender that has just taken the final attempt looks + # exhausted to everyone else while it is actively draining. Judging + # exhaustion before liveness let a second sender unlink a batch out + # from under its owner, losing every event in it. + continue + # Attempts, not age. Every re-claim touches the mtime and every release + # backdates it by a fixed amount, so age is pinned near the stale + # threshold and never reaches the expiry. Age stays only as a backstop + # for files that never carried an attempt marker. + if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS: try: orphan.unlink() except OSError: pass continue - if age < CLAIM_STALE_SECONDS: - continue + claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1) try: orphan.replace(claim) + _touch(claim) return claim except OSError: continue return None +def _safe_mtime(path: Path) -> float: + try: + return path.stat().st_mtime + except OSError: + return 0.0 + + +def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool: + """Persist the unsent remainder, atomically, and refresh the lease. + + Called after every successful batch. Two jobs: a retry resumes where the + send stopped instead of re-posting from the top, and the rewrite doubles as + the lease heartbeat, so a slow sender does not have its claim stolen + mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS. + """ + if not remaining: + try: + claim.unlink() + except OSError: + pass + return True + temporary = claim.with_suffix(f".{os.getpid()}.partial") + try: + payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining) + # fsync before the rename: without it the rename can land while the + # bytes have not, and the claim comes back empty or truncated after a + # crash. _drain then reads zero events and unlinks it. + with open(temporary, "w", encoding="utf-8") as handle: + handle.write(payload) + handle.flush() + os.fsync(handle.fileno()) + temporary.replace(claim) + _touch(claim) + return True + except OSError: + try: + temporary.unlink() + except OSError: + pass + return False + + +def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None: + """Persist the remainder and drop the lease, because this sender has given up. + + Distinct from the per-batch heartbeat: heartbeating on the way out would + make an abandoned batch look actively owned for a further + CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the + threshold lets the next flush pick it up immediately, while the attempt + count in the filename still bounds how many times that can happen. + """ + if not _rewrite_claim(claim, remaining): + return + try: + # Backdate past the stale threshold so the next flush can pick it up, + # minus a cooldown that grows with the attempts already spent. Clamped so + # the mtime never lands in the future, which would read as a live lease. + cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS) + released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown + os.utime(claim, (released, released)) + except OSError: + pass + + def _resolve_email(key: str) -> str: """Trade the API key for the account email so events join other Mem0 surfaces.""" url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/" @@ -478,16 +651,61 @@ def resolve_distinct_id() -> tuple[str, str]: def flush() -> int: - """Drain claimed spools to PostHog and return the number of events sent.""" + """Drain the live spool, then any parked claims, and return events sent.""" if not is_enabled(): return 0 - claim = _claim_spool() + sent, delivered = _drain(_claim_spool()) + if not delivered: + # The network is failing. Retrying other batches now would only burn + # their attempt budget against the same broken connection. + return sent + + # Parked batches used to starve behind the live spool indefinitely. Bounded + # per run so a long backlog cannot turn one flush into an unbounded loop. + directory = memory_core.data_dir() + _sweep_debris(directory) + for _ in range(MAX_PARKED_PER_RUN): + parked = _claim_parked(directory) + if parked is None: + break + count, delivered = _drain(parked) + sent += count + if not delivered: + break + return sent + + +def _drain(claim: Path | None) -> tuple[int, bool]: + """Post one claimed batch file, recording progress after every batch. + + Returns (events sent, whether everything was delivered). + """ if claim is None: - return 0 + return 0, True try: lines = claim.read_text(encoding="utf-8").splitlines() + except ValueError: + # UnicodeDecodeError from a torn write: the content is unrecoverable, so + # quarantine rather than retry. flush() runs from a bare `finally:` in + # flush_worker, so raising here also skips the handoff cleanup, and an + # undecodable file would otherwise be re-read on every flush forever. + # Reported as delivered because there is nothing left to deliver and the + # rest of the run should continue. + try: + claim.replace(claim.with_suffix(".corrupt")) + except OSError: + try: + claim.unlink() + except OSError: + pass + return 0, True except OSError: - return 0 + # Could not read it, which is not the same as having nothing to send. + # The file is left exactly where it is: a vanished or briefly unreadable + # claim is retryable, and quarantining it here would discard events over + # a transient filesystem error. Reported as undelivered so the run stops + # instead of counting a batch nothing was posted from as delivered. + return 0, False events = [] for line in lines: try: @@ -497,11 +715,18 @@ def flush() -> int: if isinstance(value, dict) and value.get("event"): events.append(value) if not events: + # Only delete when the file really is empty. A non-empty file that + # parses to nothing is a torn write, and its contents are the unsent + # remainder — deleting it is the data loss this PR exists to prevent. try: - claim.unlink() + empty = claim.stat().st_size == 0 + except OSError: + empty = True + try: + claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink() except OSError: pass - return 0 + return 0, True distinct_id, aliased_anonymous_id = resolve_distinct_id() if aliased_anonymous_id: @@ -520,10 +745,13 @@ def flush() -> int: sent = 0 for start in range(0, len(events), BATCH_SIZE): + chunk = events[start : start + BATCH_SIZE] batch = [ { "event": event["event"], "distinct_id": distinct_id, + # Carried through from record() so a resend can be collapsed. + "uuid": event.get("uuid"), "timestamp": event.get("timestamp"), "properties": { # Fallback only: events recorded by a build before source @@ -535,16 +763,24 @@ def flush() -> int: **(event.get("properties") or {}), }, } - for event in events[start : start + BATCH_SIZE] + for event in chunk ] if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL): - return sent - sent += len(batch) - try: - claim.unlink() - except OSError: - pass - return sent + # Keep only what has not been delivered, and release the lease. + # Previously the whole file was kept and the retry re-posted every + # batch, including the ones that had already arrived. + _release_claim(claim, events[start:]) + return sent, False + sent += len(chunk) + # Record progress and refresh the lease after each successful batch, so + # a crash repeats at most one batch instead of the entire file. If the + # rewrite fails the claim still holds delivered events, so stop rather + # than carry on as though progress were recorded — continuing is how the + # duplicate delivery this PR fixes would come back. + if not _rewrite_claim(claim, events[start + len(chunk) :]): + _release_claim(claim, events[start + len(chunk) :]) + return sent, False + return sent, True def main() -> int: diff --git a/integrations/cursor-plugin/core/telemetry.py b/integrations/cursor-plugin/core/telemetry.py index 6d7aeecae..a4375f002 100644 --- a/integrations/cursor-plugin/core/telemetry.py +++ b/integrations/cursor-plugin/core/telemetry.py @@ -100,6 +100,16 @@ BATCH_SIZE = 100 SEND_TIMEOUT = 5 CLAIM_STALE_SECONDS = 120 CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60 +# A batch is only discarded once it has genuinely been retried this many times. +MAX_CLAIM_ATTEMPTS = 3 +# Parked claims drained per run, after the live spool. Bounded so a long backlog +# cannot turn one flush into an unbounded send loop. +MAX_PARKED_PER_RUN = 3 +# Added to the wait before a released claim becomes reclaimable, per attempt +# already spent. Releasing straight to "reclaimable now" let two senders burn the +# whole budget within seconds of one another on a single momentary failure, and +# discard a batch a retry a minute later would have delivered. +RETRY_COOLDOWN_SECONDS = 60 def is_enabled() -> bool: @@ -399,38 +409,201 @@ def spawn_flush() -> bool: return False +def _claim_name(attempt: int = 0) -> str: + """Claim filename. The attempt count rides in the name so the 7-day expiry + only ever discards a batch that was actually retried and failed.""" + return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending" + + +def _claim_attempt(claim: Path) -> int: + """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape. + + Anchored on field position, not on a leading "a": the legacy shape is + ``telemetry--.sending`` and a hex id such as ``a1234567`` would + otherwise parse as attempt 1234567 and be discarded unsent on the first + flush after an upgrade. + """ + stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name + parts = stem.split("-") + if len(parts) != 4: + return 0 + tail = parts[3] + if tail.startswith("a") and tail[1:].isdigit(): + return int(tail[1:]) + return 0 + + +def _touch(path: Path) -> None: + """Refresh mtime so a claim's age measures time since it was claimed. + + ``Path.replace`` is ``os.rename``, which preserves mtime — so a claim created + after a quiet minute inherited the spool's last-write time and looked + abandoned the instant it was made. A second sender would then take it over + while the first was still posting, and both would deliver the batch. + """ + try: + os.utime(path, None) + except OSError: + pass + + def _claim_spool() -> Path | None: """Rename the spool aside so exactly one sender owns each batch.""" directory = memory_core.data_dir() - claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending" + claim = directory / _claim_name() spool = _spool_path() try: spool.replace(claim) + _touch(claim) return claim except OSError: pass + return _claim_parked(directory) + + +def _sweep_debris(directory: Path) -> None: + """Remove files nothing else will ever pick up again. + + *.partial is a temp file orphaned by a crash between write and rename. + *.corrupt is a batch quarantined for undecodable content. No glob in this + module matches either, so without this they accumulate on disk for the life + of the install. + + Quarantined batches are kept far longer than debris: they are the only + evidence left of events that could not be delivered, and someone diagnosing + a report of missing telemetry has to be able to find one. + """ now = time.time() - for orphan in sorted(directory.glob("telemetry-*.sending")): + for debris in directory.glob("telemetry-*.partial"): + try: + if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS: + debris.unlink() + except OSError: + continue + for quarantined in directory.glob("telemetry-*.corrupt"): + try: + if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS: + quarantined.unlink() + except OSError: + continue + # The same reasoning covers *.tmp. _write_identity and _install_salt both + # create one and unlink it in a finally, which a SIGKILL skips, and no glob + # in this module matches the leftovers either. + for temporary in directory.glob("telemetry-*.tmp"): + try: + if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS: + temporary.unlink() + except OSError: + continue + + +def _claim_parked(directory: Path) -> Path | None: + """Take the oldest abandoned claim, if any lease has actually expired. + + Kept separate from the live spool so flush() can drain both in one run. + Previously parked batches were only reachable when no spool existed at all, + and because sessions keep recording there usually was one — so a batch + parked by a failed send waited until the 7-day expiry deleted it unsent, + even though its own presence is what started the sender. + """ + now = time.time() + for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime): try: age = now - orphan.stat().st_mtime except OSError: continue - if age > CLAIM_EXPIRY_SECONDS: + if age < CLAIM_STALE_SECONDS: + # Someone else holds a live lease on it. This check has to come + # first. Claiming a file bumps its attempt count and refreshes its + # mtime, so a sender that has just taken the final attempt looks + # exhausted to everyone else while it is actively draining. Judging + # exhaustion before liveness let a second sender unlink a batch out + # from under its owner, losing every event in it. + continue + # Attempts, not age. Every re-claim touches the mtime and every release + # backdates it by a fixed amount, so age is pinned near the stale + # threshold and never reaches the expiry. Age stays only as a backstop + # for files that never carried an attempt marker. + if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS: try: orphan.unlink() except OSError: pass continue - if age < CLAIM_STALE_SECONDS: - continue + claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1) try: orphan.replace(claim) + _touch(claim) return claim except OSError: continue return None +def _safe_mtime(path: Path) -> float: + try: + return path.stat().st_mtime + except OSError: + return 0.0 + + +def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool: + """Persist the unsent remainder, atomically, and refresh the lease. + + Called after every successful batch. Two jobs: a retry resumes where the + send stopped instead of re-posting from the top, and the rewrite doubles as + the lease heartbeat, so a slow sender does not have its claim stolen + mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS. + """ + if not remaining: + try: + claim.unlink() + except OSError: + pass + return True + temporary = claim.with_suffix(f".{os.getpid()}.partial") + try: + payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining) + # fsync before the rename: without it the rename can land while the + # bytes have not, and the claim comes back empty or truncated after a + # crash. _drain then reads zero events and unlinks it. + with open(temporary, "w", encoding="utf-8") as handle: + handle.write(payload) + handle.flush() + os.fsync(handle.fileno()) + temporary.replace(claim) + _touch(claim) + return True + except OSError: + try: + temporary.unlink() + except OSError: + pass + return False + + +def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None: + """Persist the remainder and drop the lease, because this sender has given up. + + Distinct from the per-batch heartbeat: heartbeating on the way out would + make an abandoned batch look actively owned for a further + CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the + threshold lets the next flush pick it up immediately, while the attempt + count in the filename still bounds how many times that can happen. + """ + if not _rewrite_claim(claim, remaining): + return + try: + # Backdate past the stale threshold so the next flush can pick it up, + # minus a cooldown that grows with the attempts already spent. Clamped so + # the mtime never lands in the future, which would read as a live lease. + cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS) + released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown + os.utime(claim, (released, released)) + except OSError: + pass + + def _resolve_email(key: str) -> str: """Trade the API key for the account email so events join other Mem0 surfaces.""" url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/" @@ -478,16 +651,61 @@ def resolve_distinct_id() -> tuple[str, str]: def flush() -> int: - """Drain claimed spools to PostHog and return the number of events sent.""" + """Drain the live spool, then any parked claims, and return events sent.""" if not is_enabled(): return 0 - claim = _claim_spool() + sent, delivered = _drain(_claim_spool()) + if not delivered: + # The network is failing. Retrying other batches now would only burn + # their attempt budget against the same broken connection. + return sent + + # Parked batches used to starve behind the live spool indefinitely. Bounded + # per run so a long backlog cannot turn one flush into an unbounded loop. + directory = memory_core.data_dir() + _sweep_debris(directory) + for _ in range(MAX_PARKED_PER_RUN): + parked = _claim_parked(directory) + if parked is None: + break + count, delivered = _drain(parked) + sent += count + if not delivered: + break + return sent + + +def _drain(claim: Path | None) -> tuple[int, bool]: + """Post one claimed batch file, recording progress after every batch. + + Returns (events sent, whether everything was delivered). + """ if claim is None: - return 0 + return 0, True try: lines = claim.read_text(encoding="utf-8").splitlines() + except ValueError: + # UnicodeDecodeError from a torn write: the content is unrecoverable, so + # quarantine rather than retry. flush() runs from a bare `finally:` in + # flush_worker, so raising here also skips the handoff cleanup, and an + # undecodable file would otherwise be re-read on every flush forever. + # Reported as delivered because there is nothing left to deliver and the + # rest of the run should continue. + try: + claim.replace(claim.with_suffix(".corrupt")) + except OSError: + try: + claim.unlink() + except OSError: + pass + return 0, True except OSError: - return 0 + # Could not read it, which is not the same as having nothing to send. + # The file is left exactly where it is: a vanished or briefly unreadable + # claim is retryable, and quarantining it here would discard events over + # a transient filesystem error. Reported as undelivered so the run stops + # instead of counting a batch nothing was posted from as delivered. + return 0, False events = [] for line in lines: try: @@ -497,11 +715,18 @@ def flush() -> int: if isinstance(value, dict) and value.get("event"): events.append(value) if not events: + # Only delete when the file really is empty. A non-empty file that + # parses to nothing is a torn write, and its contents are the unsent + # remainder — deleting it is the data loss this PR exists to prevent. try: - claim.unlink() + empty = claim.stat().st_size == 0 + except OSError: + empty = True + try: + claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink() except OSError: pass - return 0 + return 0, True distinct_id, aliased_anonymous_id = resolve_distinct_id() if aliased_anonymous_id: @@ -520,10 +745,13 @@ def flush() -> int: sent = 0 for start in range(0, len(events), BATCH_SIZE): + chunk = events[start : start + BATCH_SIZE] batch = [ { "event": event["event"], "distinct_id": distinct_id, + # Carried through from record() so a resend can be collapsed. + "uuid": event.get("uuid"), "timestamp": event.get("timestamp"), "properties": { # Fallback only: events recorded by a build before source @@ -535,16 +763,24 @@ def flush() -> int: **(event.get("properties") or {}), }, } - for event in events[start : start + BATCH_SIZE] + for event in chunk ] if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL): - return sent - sent += len(batch) - try: - claim.unlink() - except OSError: - pass - return sent + # Keep only what has not been delivered, and release the lease. + # Previously the whole file was kept and the retry re-posted every + # batch, including the ones that had already arrived. + _release_claim(claim, events[start:]) + return sent, False + sent += len(chunk) + # Record progress and refresh the lease after each successful batch, so + # a crash repeats at most one batch instead of the entire file. If the + # rewrite fails the claim still holds delivered events, so stop rather + # than carry on as though progress were recorded — continuing is how the + # duplicate delivery this PR fixes would come back. + if not _rewrite_claim(claim, events[start + len(chunk) :]): + _release_claim(claim, events[start + len(chunk) :]) + return sent, False + return sent, True def main() -> int: diff --git a/integrations/kimi-plugin/core/telemetry.py b/integrations/kimi-plugin/core/telemetry.py index 6d7aeecae..a4375f002 100644 --- a/integrations/kimi-plugin/core/telemetry.py +++ b/integrations/kimi-plugin/core/telemetry.py @@ -100,6 +100,16 @@ BATCH_SIZE = 100 SEND_TIMEOUT = 5 CLAIM_STALE_SECONDS = 120 CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60 +# A batch is only discarded once it has genuinely been retried this many times. +MAX_CLAIM_ATTEMPTS = 3 +# Parked claims drained per run, after the live spool. Bounded so a long backlog +# cannot turn one flush into an unbounded send loop. +MAX_PARKED_PER_RUN = 3 +# Added to the wait before a released claim becomes reclaimable, per attempt +# already spent. Releasing straight to "reclaimable now" let two senders burn the +# whole budget within seconds of one another on a single momentary failure, and +# discard a batch a retry a minute later would have delivered. +RETRY_COOLDOWN_SECONDS = 60 def is_enabled() -> bool: @@ -399,38 +409,201 @@ def spawn_flush() -> bool: return False +def _claim_name(attempt: int = 0) -> str: + """Claim filename. The attempt count rides in the name so the 7-day expiry + only ever discards a batch that was actually retried and failed.""" + return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending" + + +def _claim_attempt(claim: Path) -> int: + """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape. + + Anchored on field position, not on a leading "a": the legacy shape is + ``telemetry--.sending`` and a hex id such as ``a1234567`` would + otherwise parse as attempt 1234567 and be discarded unsent on the first + flush after an upgrade. + """ + stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name + parts = stem.split("-") + if len(parts) != 4: + return 0 + tail = parts[3] + if tail.startswith("a") and tail[1:].isdigit(): + return int(tail[1:]) + return 0 + + +def _touch(path: Path) -> None: + """Refresh mtime so a claim's age measures time since it was claimed. + + ``Path.replace`` is ``os.rename``, which preserves mtime — so a claim created + after a quiet minute inherited the spool's last-write time and looked + abandoned the instant it was made. A second sender would then take it over + while the first was still posting, and both would deliver the batch. + """ + try: + os.utime(path, None) + except OSError: + pass + + def _claim_spool() -> Path | None: """Rename the spool aside so exactly one sender owns each batch.""" directory = memory_core.data_dir() - claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending" + claim = directory / _claim_name() spool = _spool_path() try: spool.replace(claim) + _touch(claim) return claim except OSError: pass + return _claim_parked(directory) + + +def _sweep_debris(directory: Path) -> None: + """Remove files nothing else will ever pick up again. + + *.partial is a temp file orphaned by a crash between write and rename. + *.corrupt is a batch quarantined for undecodable content. No glob in this + module matches either, so without this they accumulate on disk for the life + of the install. + + Quarantined batches are kept far longer than debris: they are the only + evidence left of events that could not be delivered, and someone diagnosing + a report of missing telemetry has to be able to find one. + """ now = time.time() - for orphan in sorted(directory.glob("telemetry-*.sending")): + for debris in directory.glob("telemetry-*.partial"): + try: + if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS: + debris.unlink() + except OSError: + continue + for quarantined in directory.glob("telemetry-*.corrupt"): + try: + if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS: + quarantined.unlink() + except OSError: + continue + # The same reasoning covers *.tmp. _write_identity and _install_salt both + # create one and unlink it in a finally, which a SIGKILL skips, and no glob + # in this module matches the leftovers either. + for temporary in directory.glob("telemetry-*.tmp"): + try: + if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS: + temporary.unlink() + except OSError: + continue + + +def _claim_parked(directory: Path) -> Path | None: + """Take the oldest abandoned claim, if any lease has actually expired. + + Kept separate from the live spool so flush() can drain both in one run. + Previously parked batches were only reachable when no spool existed at all, + and because sessions keep recording there usually was one — so a batch + parked by a failed send waited until the 7-day expiry deleted it unsent, + even though its own presence is what started the sender. + """ + now = time.time() + for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime): try: age = now - orphan.stat().st_mtime except OSError: continue - if age > CLAIM_EXPIRY_SECONDS: + if age < CLAIM_STALE_SECONDS: + # Someone else holds a live lease on it. This check has to come + # first. Claiming a file bumps its attempt count and refreshes its + # mtime, so a sender that has just taken the final attempt looks + # exhausted to everyone else while it is actively draining. Judging + # exhaustion before liveness let a second sender unlink a batch out + # from under its owner, losing every event in it. + continue + # Attempts, not age. Every re-claim touches the mtime and every release + # backdates it by a fixed amount, so age is pinned near the stale + # threshold and never reaches the expiry. Age stays only as a backstop + # for files that never carried an attempt marker. + if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS: try: orphan.unlink() except OSError: pass continue - if age < CLAIM_STALE_SECONDS: - continue + claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1) try: orphan.replace(claim) + _touch(claim) return claim except OSError: continue return None +def _safe_mtime(path: Path) -> float: + try: + return path.stat().st_mtime + except OSError: + return 0.0 + + +def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool: + """Persist the unsent remainder, atomically, and refresh the lease. + + Called after every successful batch. Two jobs: a retry resumes where the + send stopped instead of re-posting from the top, and the rewrite doubles as + the lease heartbeat, so a slow sender does not have its claim stolen + mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS. + """ + if not remaining: + try: + claim.unlink() + except OSError: + pass + return True + temporary = claim.with_suffix(f".{os.getpid()}.partial") + try: + payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining) + # fsync before the rename: without it the rename can land while the + # bytes have not, and the claim comes back empty or truncated after a + # crash. _drain then reads zero events and unlinks it. + with open(temporary, "w", encoding="utf-8") as handle: + handle.write(payload) + handle.flush() + os.fsync(handle.fileno()) + temporary.replace(claim) + _touch(claim) + return True + except OSError: + try: + temporary.unlink() + except OSError: + pass + return False + + +def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None: + """Persist the remainder and drop the lease, because this sender has given up. + + Distinct from the per-batch heartbeat: heartbeating on the way out would + make an abandoned batch look actively owned for a further + CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the + threshold lets the next flush pick it up immediately, while the attempt + count in the filename still bounds how many times that can happen. + """ + if not _rewrite_claim(claim, remaining): + return + try: + # Backdate past the stale threshold so the next flush can pick it up, + # minus a cooldown that grows with the attempts already spent. Clamped so + # the mtime never lands in the future, which would read as a live lease. + cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS) + released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown + os.utime(claim, (released, released)) + except OSError: + pass + + def _resolve_email(key: str) -> str: """Trade the API key for the account email so events join other Mem0 surfaces.""" url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/" @@ -478,16 +651,61 @@ def resolve_distinct_id() -> tuple[str, str]: def flush() -> int: - """Drain claimed spools to PostHog and return the number of events sent.""" + """Drain the live spool, then any parked claims, and return events sent.""" if not is_enabled(): return 0 - claim = _claim_spool() + sent, delivered = _drain(_claim_spool()) + if not delivered: + # The network is failing. Retrying other batches now would only burn + # their attempt budget against the same broken connection. + return sent + + # Parked batches used to starve behind the live spool indefinitely. Bounded + # per run so a long backlog cannot turn one flush into an unbounded loop. + directory = memory_core.data_dir() + _sweep_debris(directory) + for _ in range(MAX_PARKED_PER_RUN): + parked = _claim_parked(directory) + if parked is None: + break + count, delivered = _drain(parked) + sent += count + if not delivered: + break + return sent + + +def _drain(claim: Path | None) -> tuple[int, bool]: + """Post one claimed batch file, recording progress after every batch. + + Returns (events sent, whether everything was delivered). + """ if claim is None: - return 0 + return 0, True try: lines = claim.read_text(encoding="utf-8").splitlines() + except ValueError: + # UnicodeDecodeError from a torn write: the content is unrecoverable, so + # quarantine rather than retry. flush() runs from a bare `finally:` in + # flush_worker, so raising here also skips the handoff cleanup, and an + # undecodable file would otherwise be re-read on every flush forever. + # Reported as delivered because there is nothing left to deliver and the + # rest of the run should continue. + try: + claim.replace(claim.with_suffix(".corrupt")) + except OSError: + try: + claim.unlink() + except OSError: + pass + return 0, True except OSError: - return 0 + # Could not read it, which is not the same as having nothing to send. + # The file is left exactly where it is: a vanished or briefly unreadable + # claim is retryable, and quarantining it here would discard events over + # a transient filesystem error. Reported as undelivered so the run stops + # instead of counting a batch nothing was posted from as delivered. + return 0, False events = [] for line in lines: try: @@ -497,11 +715,18 @@ def flush() -> int: if isinstance(value, dict) and value.get("event"): events.append(value) if not events: + # Only delete when the file really is empty. A non-empty file that + # parses to nothing is a torn write, and its contents are the unsent + # remainder — deleting it is the data loss this PR exists to prevent. try: - claim.unlink() + empty = claim.stat().st_size == 0 + except OSError: + empty = True + try: + claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink() except OSError: pass - return 0 + return 0, True distinct_id, aliased_anonymous_id = resolve_distinct_id() if aliased_anonymous_id: @@ -520,10 +745,13 @@ def flush() -> int: sent = 0 for start in range(0, len(events), BATCH_SIZE): + chunk = events[start : start + BATCH_SIZE] batch = [ { "event": event["event"], "distinct_id": distinct_id, + # Carried through from record() so a resend can be collapsed. + "uuid": event.get("uuid"), "timestamp": event.get("timestamp"), "properties": { # Fallback only: events recorded by a build before source @@ -535,16 +763,24 @@ def flush() -> int: **(event.get("properties") or {}), }, } - for event in events[start : start + BATCH_SIZE] + for event in chunk ] if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL): - return sent - sent += len(batch) - try: - claim.unlink() - except OSError: - pass - return sent + # Keep only what has not been delivered, and release the lease. + # Previously the whole file was kept and the retry re-posted every + # batch, including the ones that had already arrived. + _release_claim(claim, events[start:]) + return sent, False + sent += len(chunk) + # Record progress and refresh the lease after each successful batch, so + # a crash repeats at most one batch instead of the entire file. If the + # rewrite fails the claim still holds delivered events, so stop rather + # than carry on as though progress were recorded — continuing is how the + # duplicate delivery this PR fixes would come back. + if not _rewrite_claim(claim, events[start + len(chunk) :]): + _release_claim(claim, events[start + len(chunk) :]) + return sent, False + return sent, True def main() -> int: diff --git a/integrations/mem0-agent-plugin/core/telemetry.py b/integrations/mem0-agent-plugin/core/telemetry.py index 6d7aeecae..a4375f002 100644 --- a/integrations/mem0-agent-plugin/core/telemetry.py +++ b/integrations/mem0-agent-plugin/core/telemetry.py @@ -100,6 +100,16 @@ BATCH_SIZE = 100 SEND_TIMEOUT = 5 CLAIM_STALE_SECONDS = 120 CLAIM_EXPIRY_SECONDS = 7 * 24 * 60 * 60 +# A batch is only discarded once it has genuinely been retried this many times. +MAX_CLAIM_ATTEMPTS = 3 +# Parked claims drained per run, after the live spool. Bounded so a long backlog +# cannot turn one flush into an unbounded send loop. +MAX_PARKED_PER_RUN = 3 +# Added to the wait before a released claim becomes reclaimable, per attempt +# already spent. Releasing straight to "reclaimable now" let two senders burn the +# whole budget within seconds of one another on a single momentary failure, and +# discard a batch a retry a minute later would have delivered. +RETRY_COOLDOWN_SECONDS = 60 def is_enabled() -> bool: @@ -399,38 +409,201 @@ def spawn_flush() -> bool: return False +def _claim_name(attempt: int = 0) -> str: + """Claim filename. The attempt count rides in the name so the 7-day expiry + only ever discards a batch that was actually retried and failed.""" + return f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}-a{attempt}.sending" + + +def _claim_attempt(claim: Path) -> int: + """Attempts recorded in a claim filename; 0 for the pre-attempt-count shape. + + Anchored on field position, not on a leading "a": the legacy shape is + ``telemetry--.sending`` and a hex id such as ``a1234567`` would + otherwise parse as attempt 1234567 and be discarded unsent on the first + flush after an upgrade. + """ + stem = claim.name[: -len(".sending")] if claim.name.endswith(".sending") else claim.name + parts = stem.split("-") + if len(parts) != 4: + return 0 + tail = parts[3] + if tail.startswith("a") and tail[1:].isdigit(): + return int(tail[1:]) + return 0 + + +def _touch(path: Path) -> None: + """Refresh mtime so a claim's age measures time since it was claimed. + + ``Path.replace`` is ``os.rename``, which preserves mtime — so a claim created + after a quiet minute inherited the spool's last-write time and looked + abandoned the instant it was made. A second sender would then take it over + while the first was still posting, and both would deliver the batch. + """ + try: + os.utime(path, None) + except OSError: + pass + + def _claim_spool() -> Path | None: """Rename the spool aside so exactly one sender owns each batch.""" directory = memory_core.data_dir() - claim = directory / f"telemetry-{os.getpid()}-{uuid.uuid4().hex[:8]}.sending" + claim = directory / _claim_name() spool = _spool_path() try: spool.replace(claim) + _touch(claim) return claim except OSError: pass + return _claim_parked(directory) + + +def _sweep_debris(directory: Path) -> None: + """Remove files nothing else will ever pick up again. + + *.partial is a temp file orphaned by a crash between write and rename. + *.corrupt is a batch quarantined for undecodable content. No glob in this + module matches either, so without this they accumulate on disk for the life + of the install. + + Quarantined batches are kept far longer than debris: they are the only + evidence left of events that could not be delivered, and someone diagnosing + a report of missing telemetry has to be able to find one. + """ now = time.time() - for orphan in sorted(directory.glob("telemetry-*.sending")): + for debris in directory.glob("telemetry-*.partial"): + try: + if now - debris.stat().st_mtime > CLAIM_STALE_SECONDS: + debris.unlink() + except OSError: + continue + for quarantined in directory.glob("telemetry-*.corrupt"): + try: + if now - quarantined.stat().st_mtime > CLAIM_EXPIRY_SECONDS: + quarantined.unlink() + except OSError: + continue + # The same reasoning covers *.tmp. _write_identity and _install_salt both + # create one and unlink it in a finally, which a SIGKILL skips, and no glob + # in this module matches the leftovers either. + for temporary in directory.glob("telemetry-*.tmp"): + try: + if now - temporary.stat().st_mtime > CLAIM_STALE_SECONDS: + temporary.unlink() + except OSError: + continue + + +def _claim_parked(directory: Path) -> Path | None: + """Take the oldest abandoned claim, if any lease has actually expired. + + Kept separate from the live spool so flush() can drain both in one run. + Previously parked batches were only reachable when no spool existed at all, + and because sessions keep recording there usually was one — so a batch + parked by a failed send waited until the 7-day expiry deleted it unsent, + even though its own presence is what started the sender. + """ + now = time.time() + for orphan in sorted(directory.glob("telemetry-*.sending"), key=_safe_mtime): try: age = now - orphan.stat().st_mtime except OSError: continue - if age > CLAIM_EXPIRY_SECONDS: + if age < CLAIM_STALE_SECONDS: + # Someone else holds a live lease on it. This check has to come + # first. Claiming a file bumps its attempt count and refreshes its + # mtime, so a sender that has just taken the final attempt looks + # exhausted to everyone else while it is actively draining. Judging + # exhaustion before liveness let a second sender unlink a batch out + # from under its owner, losing every event in it. + continue + # Attempts, not age. Every re-claim touches the mtime and every release + # backdates it by a fixed amount, so age is pinned near the stale + # threshold and never reaches the expiry. Age stays only as a backstop + # for files that never carried an attempt marker. + if _claim_attempt(orphan) >= MAX_CLAIM_ATTEMPTS or age > CLAIM_EXPIRY_SECONDS: try: orphan.unlink() except OSError: pass continue - if age < CLAIM_STALE_SECONDS: - continue + claim = orphan.parent / _claim_name(_claim_attempt(orphan) + 1) try: orphan.replace(claim) + _touch(claim) return claim except OSError: continue return None +def _safe_mtime(path: Path) -> float: + try: + return path.stat().st_mtime + except OSError: + return 0.0 + + +def _rewrite_claim(claim: Path, remaining: list[dict[str, Any]]) -> bool: + """Persist the unsent remainder, atomically, and refresh the lease. + + Called after every successful batch. Two jobs: a retry resumes where the + send stopped instead of re-posting from the top, and the rewrite doubles as + the lease heartbeat, so a slow sender does not have its claim stolen + mid-flight. Interval is one batch, well inside CLAIM_STALE_SECONDS. + """ + if not remaining: + try: + claim.unlink() + except OSError: + pass + return True + temporary = claim.with_suffix(f".{os.getpid()}.partial") + try: + payload = "".join(json.dumps(event, separators=(",", ":"), default=str) + "\n" for event in remaining) + # fsync before the rename: without it the rename can land while the + # bytes have not, and the claim comes back empty or truncated after a + # crash. _drain then reads zero events and unlinks it. + with open(temporary, "w", encoding="utf-8") as handle: + handle.write(payload) + handle.flush() + os.fsync(handle.fileno()) + temporary.replace(claim) + _touch(claim) + return True + except OSError: + try: + temporary.unlink() + except OSError: + pass + return False + + +def _release_claim(claim: Path, remaining: list[dict[str, Any]]) -> None: + """Persist the remainder and drop the lease, because this sender has given up. + + Distinct from the per-batch heartbeat: heartbeating on the way out would + make an abandoned batch look actively owned for a further + CLAIM_STALE_SECONDS, delaying the retry for no reason. Ageing it past the + threshold lets the next flush pick it up immediately, while the attempt + count in the filename still bounds how many times that can happen. + """ + if not _rewrite_claim(claim, remaining): + return + try: + # Backdate past the stale threshold so the next flush can pick it up, + # minus a cooldown that grows with the attempts already spent. Clamped so + # the mtime never lands in the future, which would read as a live lease. + cooldown = min(_claim_attempt(claim) * RETRY_COOLDOWN_SECONDS, CLAIM_STALE_SECONDS) + released = time.time() - CLAIM_STALE_SECONDS - 1 + cooldown + os.utime(claim, (released, released)) + except OSError: + pass + + def _resolve_email(key: str) -> str: """Trade the API key for the account email so events join other Mem0 surfaces.""" url = os.environ.get("MEM0_API_URL", memory_core.DEFAULT_API_URL).rstrip("/") + "/v1/ping/" @@ -478,16 +651,61 @@ def resolve_distinct_id() -> tuple[str, str]: def flush() -> int: - """Drain claimed spools to PostHog and return the number of events sent.""" + """Drain the live spool, then any parked claims, and return events sent.""" if not is_enabled(): return 0 - claim = _claim_spool() + sent, delivered = _drain(_claim_spool()) + if not delivered: + # The network is failing. Retrying other batches now would only burn + # their attempt budget against the same broken connection. + return sent + + # Parked batches used to starve behind the live spool indefinitely. Bounded + # per run so a long backlog cannot turn one flush into an unbounded loop. + directory = memory_core.data_dir() + _sweep_debris(directory) + for _ in range(MAX_PARKED_PER_RUN): + parked = _claim_parked(directory) + if parked is None: + break + count, delivered = _drain(parked) + sent += count + if not delivered: + break + return sent + + +def _drain(claim: Path | None) -> tuple[int, bool]: + """Post one claimed batch file, recording progress after every batch. + + Returns (events sent, whether everything was delivered). + """ if claim is None: - return 0 + return 0, True try: lines = claim.read_text(encoding="utf-8").splitlines() + except ValueError: + # UnicodeDecodeError from a torn write: the content is unrecoverable, so + # quarantine rather than retry. flush() runs from a bare `finally:` in + # flush_worker, so raising here also skips the handoff cleanup, and an + # undecodable file would otherwise be re-read on every flush forever. + # Reported as delivered because there is nothing left to deliver and the + # rest of the run should continue. + try: + claim.replace(claim.with_suffix(".corrupt")) + except OSError: + try: + claim.unlink() + except OSError: + pass + return 0, True except OSError: - return 0 + # Could not read it, which is not the same as having nothing to send. + # The file is left exactly where it is: a vanished or briefly unreadable + # claim is retryable, and quarantining it here would discard events over + # a transient filesystem error. Reported as undelivered so the run stops + # instead of counting a batch nothing was posted from as delivered. + return 0, False events = [] for line in lines: try: @@ -497,11 +715,18 @@ def flush() -> int: if isinstance(value, dict) and value.get("event"): events.append(value) if not events: + # Only delete when the file really is empty. A non-empty file that + # parses to nothing is a torn write, and its contents are the unsent + # remainder — deleting it is the data loss this PR exists to prevent. try: - claim.unlink() + empty = claim.stat().st_size == 0 + except OSError: + empty = True + try: + claim.replace(claim.with_suffix(".corrupt")) if not empty else claim.unlink() except OSError: pass - return 0 + return 0, True distinct_id, aliased_anonymous_id = resolve_distinct_id() if aliased_anonymous_id: @@ -520,10 +745,13 @@ def flush() -> int: sent = 0 for start in range(0, len(events), BATCH_SIZE): + chunk = events[start : start + BATCH_SIZE] batch = [ { "event": event["event"], "distinct_id": distinct_id, + # Carried through from record() so a resend can be collapsed. + "uuid": event.get("uuid"), "timestamp": event.get("timestamp"), "properties": { # Fallback only: events recorded by a build before source @@ -535,16 +763,24 @@ def flush() -> int: **(event.get("properties") or {}), }, } - for event in events[start : start + BATCH_SIZE] + for event in chunk ] if not _post({"api_key": POSTHOG_API_KEY, "batch": batch}, POSTHOG_BATCH_URL): - return sent - sent += len(batch) - try: - claim.unlink() - except OSError: - pass - return sent + # Keep only what has not been delivered, and release the lease. + # Previously the whole file was kept and the retry re-posted every + # batch, including the ones that had already arrived. + _release_claim(claim, events[start:]) + return sent, False + sent += len(chunk) + # Record progress and refresh the lease after each successful batch, so + # a crash repeats at most one batch instead of the entire file. If the + # rewrite fails the claim still holds delivered events, so stop rather + # than carry on as though progress were recorded — continuing is how the + # duplicate delivery this PR fixes would come back. + if not _rewrite_claim(claim, events[start + len(chunk) :]): + _release_claim(claim, events[start + len(chunk) :]) + return sent, False + return sent, True def main() -> int: From 4e38b057fd110c201bd372ab5e1620e81c67a4ed Mon Sep 17 00:00:00 2001 From: Saket Aryan Date: Fri, 18 Sep 2026 13:46:25 +0530 Subject: [PATCH 17/61] fix(plugins): count installs once, and re-resolve the email when the key changes (#7325) --- .../agent-plugin-core/python/hook_runner.py | 18 +- .../agent-plugin-core/python/telemetry.py | 240 +++++++++++++++++- .../tests/test_uninitialised_identity.py | 68 +++++ .../antigravity-plugin/core/hook_runner.py | 18 +- .../antigravity-plugin/core/telemetry.py | 240 +++++++++++++++++- .../claude-code-plugin/core/hook_runner.py | 18 +- .../claude-code-plugin/core/telemetry.py | 240 +++++++++++++++++- .../tests/test_telemetry.py | 140 +++++++++- integrations/codex-plugin/core/hook_runner.py | 18 +- integrations/codex-plugin/core/telemetry.py | 240 +++++++++++++++++- .../cursor-plugin/core/hook_runner.py | 18 +- integrations/cursor-plugin/core/telemetry.py | 240 +++++++++++++++++- integrations/kimi-plugin/core/hook_runner.py | 18 +- integrations/kimi-plugin/core/telemetry.py | 240 +++++++++++++++++- .../mem0-agent-plugin/core/telemetry.py | 240 +++++++++++++++++- 15 files changed, 1912 insertions(+), 84 deletions(-) diff --git a/integrations/agent-plugin-core/python/hook_runner.py b/integrations/agent-plugin-core/python/hook_runner.py index 2a2adb557..b3d8a3210 100644 --- a/integrations/agent-plugin-core/python/hook_runner.py +++ b/integrations/agent-plugin-core/python/hook_runner.py @@ -290,6 +290,11 @@ def run( if args.plugin_data_dir: os.environ[data_dir_env] = args.plugin_data_dir + # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key + # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking + # after them always saw content and every fresh install reported an upgrade. + data_dir_was_empty = telemetry.data_dir_was_empty() + cache_plugin_api_key() if args.action == "session-start": clear_stale_api_key_cache() @@ -305,8 +310,19 @@ def run( return 0 if args.action == "session-start": - if telemetry.is_first_run(): + # Claims the marker atomically and says which event to record, so a + # second session starting alongside this one cannot record it too. + first_event = telemetry.claim_install(was_empty=data_dir_was_empty) + if first_event == "install": telemetry.record("install") + elif first_event == "upgrade": + # First run after a build that never wrote the marker; the + # predecessor version was never recorded anywhere. + telemetry.record("upgrade", from_version="pre-0.3") + else: + previous = telemetry.claim_version_change() + if previous: + telemetry.record("upgrade", from_version=previous) recovered = recover_pending_handoffs() record_session_start(store, hook_input) if recovered: diff --git a/integrations/agent-plugin-core/python/telemetry.py b/integrations/agent-plugin-core/python/telemetry.py index a4375f002..c1fc0084c 100644 --- a/integrations/agent-plugin-core/python/telemetry.py +++ b/integrations/agent-plugin-core/python/telemetry.py @@ -302,9 +302,176 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str: return created +def _rotate_anonymous_id(identity: dict[str, str]) -> str: + """Mint a fresh anonymous id because the account context is gone. + + The previous id may already have been merged into a person profile by an + $identify, and that merge is permanent. Reusing it after a logout or a key + change attributes everything that follows to the account that just went + away, which is the same misattribution the key fingerprint exists to stop, + only arriving through the anonymous path instead. + + `aliased` is cleared with it: the new id has never been merged, so it is + eligible to be aliased into whatever account comes next. + """ + created = f"code-anon-{uuid.uuid4().hex}" + identity["anonymous_id"] = created + identity.pop("aliased", None) + _write_identity(identity) + return created + + +def _install_state_path() -> Path: + return memory_core.data_dir() / "install-state.json" + + def is_first_run() -> bool: - """Whether this machine has never recorded a plugin event before.""" - return not _identity_path().exists() + """Whether install has never been recorded on this machine. + + Deliberately NOT the identity file. That file is only written by a + successful flush, so an offline or firewalled user recorded code.install on + every single session, forever — and every 0.2.x user recorded one on their + first 0.3.x session because 0.2.x never wrote it at all. + """ + return not _install_state_path().exists() + + +def data_dir_was_empty() -> bool: + """Whether the data directory is untouched. Call BEFORE anything writes to it. + + hook_runner reaches claim_install() only after cache_plugin_api_key() has + written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so + asking at claim time always saw content and every fresh install reported an + upgrade. The caller snapshots this at the top of the run instead. + """ + return not _data_dir_has_content() + + +def claim_install(was_empty: bool | None = None) -> str | None: + """Claim the one install/upgrade record for this machine, atomically. + + Returns the event to record ("install" or "upgrade"), or None if another + session already claimed it. O_CREAT|O_EXCL so two sessions starting together + cannot both win. + + `was_empty` must come from data_dir_was_empty() called before this process + wrote anything. Omitting it falls back to checking now, which is only + correct for a caller that has touched nothing. + """ + if not is_enabled(): + # Never consume the one-shot claim while the user is opted out, or they + # would silently lose their install event if they later opt in. + return None + + path = _install_state_path() + upgrading = not (data_dir_was_empty() if was_empty is None else was_empty) + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + return None + except OSError: + return None + try: + with os.fdopen(handle, "w", encoding="utf-8") as stream: + json.dump( + { + "plugin_version": memory_core.PLUGIN_VERSION, + "installed_at": memory_core.utc_now(), + "upgraded": upgrading, + }, + stream, + ) + # Durable before this returns. The O_EXCL open is what makes the + # claim exclusive, so it cannot be replaced by a temp-and-rename + # without losing that, which leaves the content as the thing to make + # safe. A kill between the open and this fsync used to leave a marker + # that exists but parses to nothing: is_first_run reads it as claimed + # and claim_version_change cannot read a version out of it. + stream.flush() + os.fsync(stream.fileno()) + except OSError: + pass + return "upgrade" if upgrading else "install" + + +def _data_dir_has_content() -> bool: + """Whether anything predates this session in the plugin data directory.""" + try: + for entry in memory_core.data_dir().iterdir(): + if entry.name != "install-state.json": + return True + except OSError: + pass + return False + + +def _repair_install_state(path: Path) -> None: + """Rewrite an unparseable marker so version tracking can resume.""" + try: + temporary = path.with_suffix(f".{os.getpid()}.tmp") + temporary.write_text( + json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}), + encoding="utf-8", + ) + temporary.replace(path) + except OSError: + pass + + +def claim_version_change() -> str | None: + """Return the previously recorded version if it differs, updating the marker. + + Only meaningful once the marker exists — the first transition into 0.3.x has + no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting + the marker means the next session sees no change and records nothing. + """ + path = _install_state_path() + try: + state = json.loads(path.read_text(encoding="utf-8")) + except OSError: + return None + except json.JSONDecodeError: + # A crash between O_EXCL and the write leaves an empty marker. Left + # alone it disables every future upgrade event on this machine, because + # claim_install sees the file and this function cannot parse it. + state = None + if not isinstance(state, dict): + _repair_install_state(path) + return None + previous = str(state.get("plugin_version") or "") + if not previous or previous == memory_core.PLUGIN_VERSION: + return None + # Claim the transition with an exclusive sentinel before rewriting the + # marker. A plain read-modify-write let every concurrently starting session + # observe the old version and each record its own upgrade — and the first + # session after a version bump is exactly when several agent windows restart + # together. + sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}") + try: + os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)) + except FileExistsError: + return None + except OSError: + return None + + state["plugin_version"] = memory_core.PLUGIN_VERSION + state["upgraded_at"] = memory_core.utc_now() + temporary = path.with_suffix(f".{os.getpid()}.tmp") + try: + temporary.write_text(json.dumps(state), encoding="utf-8") + temporary.replace(path) + except OSError: + # Release the claim. The marker still records the old version, so + # without this the sentinel makes claim_version_change return early on + # every later run and this version's upgrade is never recorded again. + for leftover in (sentinel, temporary): + try: + leftover.unlink() + except OSError: + pass + return None + return previous def record( @@ -633,21 +800,72 @@ def _post(payload: dict[str, Any], url: str) -> bool: def resolve_distinct_id() -> tuple[str, str]: - """Return the PostHog distinct id and the anonymous id it replaced, if any.""" + """Return the PostHog distinct id and the anonymous id it replaced, if any. + + The second value becomes a PostHog $identify alias. It is ONLY ever an + anonymous id: aliasing one account email to another merges two real person + profiles and cannot be undone, so a key that now belongs to a different + account re-resolves with no alias. + """ identity = _read_identity() - email = identity.get("email", "") - if email: - return email, "" key = memory_core.api_key() + fingerprint = _digest(key) if key else "" + email = identity.get("email", "") + + if email and fingerprint: + recorded = identity.get("key_fingerprint", "") + if recorded == fingerprint: + return email, "" + if not recorded: + # Rows written before fingerprints existed. Verify rather than + # adopt: a key changed before the upgrade would otherwise bind the + # new key to the previous account's email, permanently, and the + # fingerprint would then agree with itself forever after. + verified = _resolve_email(key) + if not verified: + # Offline, firewalled, or the API is down. Keep the previous + # behaviour and retry on the next flush rather than dropping a + # real account attribution. Safe because the same network that + # failed /v1/ping/ is about to fail the PostHog POST, so nothing + # is delivered under the unverified identity in the meantime. + return email, "" + identity["email"] = verified + identity["key_fingerprint"] = fingerprint + _write_identity(identity) + return verified, "" + if not key: + # No key to verify the account with; do not keep attributing to it. + if email: + identity.pop("email", None) + identity.pop("key_fingerprint", None) + return _rotate_anonymous_id(identity), "" return anonymous_id(identity), "" - email = _resolve_email(key) - if not email: + + resolved = _resolve_email(key) + if not resolved: + # The key changed and will not resolve (revoked, offline, API down). + # Reaching here with an email means the recorded fingerprint disagreed, + # so the key really did change. Drop the account and rotate: the stored + # anonymous id may already be merged into that account's person, and + # reusing it would keep the events on the profile we are trying to + # leave. + if email: + identity.pop("email", None) + identity.pop("key_fingerprint", None) + return _rotate_anonymous_id(identity), "" return anonymous_id(identity), "" - previous = identity.get("anonymous_id", "") - identity["email"] = email + + # Alias only when going anonymous -> email for the first time. Once an anon + # id has been merged into an account it must never be offered again: an + # alias naming an already-identified id is what could link two real people. + previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "") + if previous: + identity["aliased"] = True + identity["email"] = resolved + identity["key_fingerprint"] = fingerprint _write_identity(identity) - return email, previous + return resolved, previous def flush() -> int: diff --git a/integrations/agent-plugin-core/tests/test_uninitialised_identity.py b/integrations/agent-plugin-core/tests/test_uninitialised_identity.py index 14f911bee..7d48dbcc3 100644 --- a/integrations/agent-plugin-core/tests/test_uninitialised_identity.py +++ b/integrations/agent-plugin-core/tests/test_uninitialised_identity.py @@ -177,3 +177,71 @@ def test_source_tag_defaults_agree_between_the_two_modules(): ) left, right = out.split() assert left == right == "KIMI_PLUGIN" + + +def _session_start(core: Path, data_dir: Path) -> list[str]: + """Drive the real hook_runner session-start path and return lifecycle events.""" + recorded = "\n".join( + [ + "import io, json, sys", + f"sys.path.insert(0, {str(core)!r})", + "import telemetry, hook_runner", + "seen = []", + "telemetry.record = lambda event, **kw: seen.append(event) or None", + "telemetry.spawn_flush = lambda: False", + # run() reads sys.argv through argparse; it takes no positional args. + "sys.argv = ['hook_runner', 'session-start']", + "sys.stdin = io.StringIO('{}')", + "hook_runner.run()", + "print(json.dumps([e for e in seen if e in ('install', 'upgrade')]))", + ] + ) + import json as _json + + return _json.loads(_run(core, data_dir, recorded) or "[]") + + +def test_a_fresh_install_reports_install_not_upgrade(): + """The decision must survive the writes hook_runner does before asking. + + claim_install() is reached only after cache_plugin_api_key() has written + `api-key` and EvidenceStore() has created `evidence.sqlite3`. Asking "is the + data dir empty" at that point always saw content, so code.install could + never fire and every new user was counted as an upgrade. + """ + core = _core_dir("claude-code-plugin") + if not core.exists(): + pytest.skip("claude-code-plugin is not built in this tree") + + with tempfile.TemporaryDirectory() as tmp: + data_dir = Path(tmp) / "data" + assert _session_start(core, data_dir) == ["install"] + + +def test_the_lifecycle_event_fires_exactly_once(): + core = _core_dir("claude-code-plugin") + if not core.exists(): + pytest.skip("claude-code-plugin is not built in this tree") + + with tempfile.TemporaryDirectory() as tmp: + data_dir = Path(tmp) / "data" + first = _session_start(core, data_dir) + second = _session_start(core, data_dir) + third = _session_start(core, data_dir) + + assert first == ["install"] + assert second == [] + assert third == [] + + +def test_an_existing_data_dir_reports_upgrade(): + core = _core_dir("claude-code-plugin") + if not core.exists(): + pytest.skip("claude-code-plugin is not built in this tree") + + with tempfile.TemporaryDirectory() as tmp: + data_dir = Path(tmp) / "data" + data_dir.mkdir(parents=True) + # A 0.2.x leftover: the data dir survives the upgrade. + (data_dir / "requirements.txt").write_text("mem0ai\n", encoding="utf-8") + assert _session_start(core, data_dir) == ["upgrade"] diff --git a/integrations/antigravity-plugin/core/hook_runner.py b/integrations/antigravity-plugin/core/hook_runner.py index 2a2adb557..b3d8a3210 100644 --- a/integrations/antigravity-plugin/core/hook_runner.py +++ b/integrations/antigravity-plugin/core/hook_runner.py @@ -290,6 +290,11 @@ def run( if args.plugin_data_dir: os.environ[data_dir_env] = args.plugin_data_dir + # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key + # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking + # after them always saw content and every fresh install reported an upgrade. + data_dir_was_empty = telemetry.data_dir_was_empty() + cache_plugin_api_key() if args.action == "session-start": clear_stale_api_key_cache() @@ -305,8 +310,19 @@ def run( return 0 if args.action == "session-start": - if telemetry.is_first_run(): + # Claims the marker atomically and says which event to record, so a + # second session starting alongside this one cannot record it too. + first_event = telemetry.claim_install(was_empty=data_dir_was_empty) + if first_event == "install": telemetry.record("install") + elif first_event == "upgrade": + # First run after a build that never wrote the marker; the + # predecessor version was never recorded anywhere. + telemetry.record("upgrade", from_version="pre-0.3") + else: + previous = telemetry.claim_version_change() + if previous: + telemetry.record("upgrade", from_version=previous) recovered = recover_pending_handoffs() record_session_start(store, hook_input) if recovered: diff --git a/integrations/antigravity-plugin/core/telemetry.py b/integrations/antigravity-plugin/core/telemetry.py index a4375f002..c1fc0084c 100644 --- a/integrations/antigravity-plugin/core/telemetry.py +++ b/integrations/antigravity-plugin/core/telemetry.py @@ -302,9 +302,176 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str: return created +def _rotate_anonymous_id(identity: dict[str, str]) -> str: + """Mint a fresh anonymous id because the account context is gone. + + The previous id may already have been merged into a person profile by an + $identify, and that merge is permanent. Reusing it after a logout or a key + change attributes everything that follows to the account that just went + away, which is the same misattribution the key fingerprint exists to stop, + only arriving through the anonymous path instead. + + `aliased` is cleared with it: the new id has never been merged, so it is + eligible to be aliased into whatever account comes next. + """ + created = f"code-anon-{uuid.uuid4().hex}" + identity["anonymous_id"] = created + identity.pop("aliased", None) + _write_identity(identity) + return created + + +def _install_state_path() -> Path: + return memory_core.data_dir() / "install-state.json" + + def is_first_run() -> bool: - """Whether this machine has never recorded a plugin event before.""" - return not _identity_path().exists() + """Whether install has never been recorded on this machine. + + Deliberately NOT the identity file. That file is only written by a + successful flush, so an offline or firewalled user recorded code.install on + every single session, forever — and every 0.2.x user recorded one on their + first 0.3.x session because 0.2.x never wrote it at all. + """ + return not _install_state_path().exists() + + +def data_dir_was_empty() -> bool: + """Whether the data directory is untouched. Call BEFORE anything writes to it. + + hook_runner reaches claim_install() only after cache_plugin_api_key() has + written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so + asking at claim time always saw content and every fresh install reported an + upgrade. The caller snapshots this at the top of the run instead. + """ + return not _data_dir_has_content() + + +def claim_install(was_empty: bool | None = None) -> str | None: + """Claim the one install/upgrade record for this machine, atomically. + + Returns the event to record ("install" or "upgrade"), or None if another + session already claimed it. O_CREAT|O_EXCL so two sessions starting together + cannot both win. + + `was_empty` must come from data_dir_was_empty() called before this process + wrote anything. Omitting it falls back to checking now, which is only + correct for a caller that has touched nothing. + """ + if not is_enabled(): + # Never consume the one-shot claim while the user is opted out, or they + # would silently lose their install event if they later opt in. + return None + + path = _install_state_path() + upgrading = not (data_dir_was_empty() if was_empty is None else was_empty) + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + return None + except OSError: + return None + try: + with os.fdopen(handle, "w", encoding="utf-8") as stream: + json.dump( + { + "plugin_version": memory_core.PLUGIN_VERSION, + "installed_at": memory_core.utc_now(), + "upgraded": upgrading, + }, + stream, + ) + # Durable before this returns. The O_EXCL open is what makes the + # claim exclusive, so it cannot be replaced by a temp-and-rename + # without losing that, which leaves the content as the thing to make + # safe. A kill between the open and this fsync used to leave a marker + # that exists but parses to nothing: is_first_run reads it as claimed + # and claim_version_change cannot read a version out of it. + stream.flush() + os.fsync(stream.fileno()) + except OSError: + pass + return "upgrade" if upgrading else "install" + + +def _data_dir_has_content() -> bool: + """Whether anything predates this session in the plugin data directory.""" + try: + for entry in memory_core.data_dir().iterdir(): + if entry.name != "install-state.json": + return True + except OSError: + pass + return False + + +def _repair_install_state(path: Path) -> None: + """Rewrite an unparseable marker so version tracking can resume.""" + try: + temporary = path.with_suffix(f".{os.getpid()}.tmp") + temporary.write_text( + json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}), + encoding="utf-8", + ) + temporary.replace(path) + except OSError: + pass + + +def claim_version_change() -> str | None: + """Return the previously recorded version if it differs, updating the marker. + + Only meaningful once the marker exists — the first transition into 0.3.x has + no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting + the marker means the next session sees no change and records nothing. + """ + path = _install_state_path() + try: + state = json.loads(path.read_text(encoding="utf-8")) + except OSError: + return None + except json.JSONDecodeError: + # A crash between O_EXCL and the write leaves an empty marker. Left + # alone it disables every future upgrade event on this machine, because + # claim_install sees the file and this function cannot parse it. + state = None + if not isinstance(state, dict): + _repair_install_state(path) + return None + previous = str(state.get("plugin_version") or "") + if not previous or previous == memory_core.PLUGIN_VERSION: + return None + # Claim the transition with an exclusive sentinel before rewriting the + # marker. A plain read-modify-write let every concurrently starting session + # observe the old version and each record its own upgrade — and the first + # session after a version bump is exactly when several agent windows restart + # together. + sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}") + try: + os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)) + except FileExistsError: + return None + except OSError: + return None + + state["plugin_version"] = memory_core.PLUGIN_VERSION + state["upgraded_at"] = memory_core.utc_now() + temporary = path.with_suffix(f".{os.getpid()}.tmp") + try: + temporary.write_text(json.dumps(state), encoding="utf-8") + temporary.replace(path) + except OSError: + # Release the claim. The marker still records the old version, so + # without this the sentinel makes claim_version_change return early on + # every later run and this version's upgrade is never recorded again. + for leftover in (sentinel, temporary): + try: + leftover.unlink() + except OSError: + pass + return None + return previous def record( @@ -633,21 +800,72 @@ def _post(payload: dict[str, Any], url: str) -> bool: def resolve_distinct_id() -> tuple[str, str]: - """Return the PostHog distinct id and the anonymous id it replaced, if any.""" + """Return the PostHog distinct id and the anonymous id it replaced, if any. + + The second value becomes a PostHog $identify alias. It is ONLY ever an + anonymous id: aliasing one account email to another merges two real person + profiles and cannot be undone, so a key that now belongs to a different + account re-resolves with no alias. + """ identity = _read_identity() - email = identity.get("email", "") - if email: - return email, "" key = memory_core.api_key() + fingerprint = _digest(key) if key else "" + email = identity.get("email", "") + + if email and fingerprint: + recorded = identity.get("key_fingerprint", "") + if recorded == fingerprint: + return email, "" + if not recorded: + # Rows written before fingerprints existed. Verify rather than + # adopt: a key changed before the upgrade would otherwise bind the + # new key to the previous account's email, permanently, and the + # fingerprint would then agree with itself forever after. + verified = _resolve_email(key) + if not verified: + # Offline, firewalled, or the API is down. Keep the previous + # behaviour and retry on the next flush rather than dropping a + # real account attribution. Safe because the same network that + # failed /v1/ping/ is about to fail the PostHog POST, so nothing + # is delivered under the unverified identity in the meantime. + return email, "" + identity["email"] = verified + identity["key_fingerprint"] = fingerprint + _write_identity(identity) + return verified, "" + if not key: + # No key to verify the account with; do not keep attributing to it. + if email: + identity.pop("email", None) + identity.pop("key_fingerprint", None) + return _rotate_anonymous_id(identity), "" return anonymous_id(identity), "" - email = _resolve_email(key) - if not email: + + resolved = _resolve_email(key) + if not resolved: + # The key changed and will not resolve (revoked, offline, API down). + # Reaching here with an email means the recorded fingerprint disagreed, + # so the key really did change. Drop the account and rotate: the stored + # anonymous id may already be merged into that account's person, and + # reusing it would keep the events on the profile we are trying to + # leave. + if email: + identity.pop("email", None) + identity.pop("key_fingerprint", None) + return _rotate_anonymous_id(identity), "" return anonymous_id(identity), "" - previous = identity.get("anonymous_id", "") - identity["email"] = email + + # Alias only when going anonymous -> email for the first time. Once an anon + # id has been merged into an account it must never be offered again: an + # alias naming an already-identified id is what could link two real people. + previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "") + if previous: + identity["aliased"] = True + identity["email"] = resolved + identity["key_fingerprint"] = fingerprint _write_identity(identity) - return email, previous + return resolved, previous def flush() -> int: diff --git a/integrations/claude-code-plugin/core/hook_runner.py b/integrations/claude-code-plugin/core/hook_runner.py index 2a2adb557..b3d8a3210 100644 --- a/integrations/claude-code-plugin/core/hook_runner.py +++ b/integrations/claude-code-plugin/core/hook_runner.py @@ -290,6 +290,11 @@ def run( if args.plugin_data_dir: os.environ[data_dir_env] = args.plugin_data_dir + # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key + # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking + # after them always saw content and every fresh install reported an upgrade. + data_dir_was_empty = telemetry.data_dir_was_empty() + cache_plugin_api_key() if args.action == "session-start": clear_stale_api_key_cache() @@ -305,8 +310,19 @@ def run( return 0 if args.action == "session-start": - if telemetry.is_first_run(): + # Claims the marker atomically and says which event to record, so a + # second session starting alongside this one cannot record it too. + first_event = telemetry.claim_install(was_empty=data_dir_was_empty) + if first_event == "install": telemetry.record("install") + elif first_event == "upgrade": + # First run after a build that never wrote the marker; the + # predecessor version was never recorded anywhere. + telemetry.record("upgrade", from_version="pre-0.3") + else: + previous = telemetry.claim_version_change() + if previous: + telemetry.record("upgrade", from_version=previous) recovered = recover_pending_handoffs() record_session_start(store, hook_input) if recovered: diff --git a/integrations/claude-code-plugin/core/telemetry.py b/integrations/claude-code-plugin/core/telemetry.py index a4375f002..c1fc0084c 100644 --- a/integrations/claude-code-plugin/core/telemetry.py +++ b/integrations/claude-code-plugin/core/telemetry.py @@ -302,9 +302,176 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str: return created +def _rotate_anonymous_id(identity: dict[str, str]) -> str: + """Mint a fresh anonymous id because the account context is gone. + + The previous id may already have been merged into a person profile by an + $identify, and that merge is permanent. Reusing it after a logout or a key + change attributes everything that follows to the account that just went + away, which is the same misattribution the key fingerprint exists to stop, + only arriving through the anonymous path instead. + + `aliased` is cleared with it: the new id has never been merged, so it is + eligible to be aliased into whatever account comes next. + """ + created = f"code-anon-{uuid.uuid4().hex}" + identity["anonymous_id"] = created + identity.pop("aliased", None) + _write_identity(identity) + return created + + +def _install_state_path() -> Path: + return memory_core.data_dir() / "install-state.json" + + def is_first_run() -> bool: - """Whether this machine has never recorded a plugin event before.""" - return not _identity_path().exists() + """Whether install has never been recorded on this machine. + + Deliberately NOT the identity file. That file is only written by a + successful flush, so an offline or firewalled user recorded code.install on + every single session, forever — and every 0.2.x user recorded one on their + first 0.3.x session because 0.2.x never wrote it at all. + """ + return not _install_state_path().exists() + + +def data_dir_was_empty() -> bool: + """Whether the data directory is untouched. Call BEFORE anything writes to it. + + hook_runner reaches claim_install() only after cache_plugin_api_key() has + written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so + asking at claim time always saw content and every fresh install reported an + upgrade. The caller snapshots this at the top of the run instead. + """ + return not _data_dir_has_content() + + +def claim_install(was_empty: bool | None = None) -> str | None: + """Claim the one install/upgrade record for this machine, atomically. + + Returns the event to record ("install" or "upgrade"), or None if another + session already claimed it. O_CREAT|O_EXCL so two sessions starting together + cannot both win. + + `was_empty` must come from data_dir_was_empty() called before this process + wrote anything. Omitting it falls back to checking now, which is only + correct for a caller that has touched nothing. + """ + if not is_enabled(): + # Never consume the one-shot claim while the user is opted out, or they + # would silently lose their install event if they later opt in. + return None + + path = _install_state_path() + upgrading = not (data_dir_was_empty() if was_empty is None else was_empty) + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + return None + except OSError: + return None + try: + with os.fdopen(handle, "w", encoding="utf-8") as stream: + json.dump( + { + "plugin_version": memory_core.PLUGIN_VERSION, + "installed_at": memory_core.utc_now(), + "upgraded": upgrading, + }, + stream, + ) + # Durable before this returns. The O_EXCL open is what makes the + # claim exclusive, so it cannot be replaced by a temp-and-rename + # without losing that, which leaves the content as the thing to make + # safe. A kill between the open and this fsync used to leave a marker + # that exists but parses to nothing: is_first_run reads it as claimed + # and claim_version_change cannot read a version out of it. + stream.flush() + os.fsync(stream.fileno()) + except OSError: + pass + return "upgrade" if upgrading else "install" + + +def _data_dir_has_content() -> bool: + """Whether anything predates this session in the plugin data directory.""" + try: + for entry in memory_core.data_dir().iterdir(): + if entry.name != "install-state.json": + return True + except OSError: + pass + return False + + +def _repair_install_state(path: Path) -> None: + """Rewrite an unparseable marker so version tracking can resume.""" + try: + temporary = path.with_suffix(f".{os.getpid()}.tmp") + temporary.write_text( + json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}), + encoding="utf-8", + ) + temporary.replace(path) + except OSError: + pass + + +def claim_version_change() -> str | None: + """Return the previously recorded version if it differs, updating the marker. + + Only meaningful once the marker exists — the first transition into 0.3.x has + no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting + the marker means the next session sees no change and records nothing. + """ + path = _install_state_path() + try: + state = json.loads(path.read_text(encoding="utf-8")) + except OSError: + return None + except json.JSONDecodeError: + # A crash between O_EXCL and the write leaves an empty marker. Left + # alone it disables every future upgrade event on this machine, because + # claim_install sees the file and this function cannot parse it. + state = None + if not isinstance(state, dict): + _repair_install_state(path) + return None + previous = str(state.get("plugin_version") or "") + if not previous or previous == memory_core.PLUGIN_VERSION: + return None + # Claim the transition with an exclusive sentinel before rewriting the + # marker. A plain read-modify-write let every concurrently starting session + # observe the old version and each record its own upgrade — and the first + # session after a version bump is exactly when several agent windows restart + # together. + sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}") + try: + os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)) + except FileExistsError: + return None + except OSError: + return None + + state["plugin_version"] = memory_core.PLUGIN_VERSION + state["upgraded_at"] = memory_core.utc_now() + temporary = path.with_suffix(f".{os.getpid()}.tmp") + try: + temporary.write_text(json.dumps(state), encoding="utf-8") + temporary.replace(path) + except OSError: + # Release the claim. The marker still records the old version, so + # without this the sentinel makes claim_version_change return early on + # every later run and this version's upgrade is never recorded again. + for leftover in (sentinel, temporary): + try: + leftover.unlink() + except OSError: + pass + return None + return previous def record( @@ -633,21 +800,72 @@ def _post(payload: dict[str, Any], url: str) -> bool: def resolve_distinct_id() -> tuple[str, str]: - """Return the PostHog distinct id and the anonymous id it replaced, if any.""" + """Return the PostHog distinct id and the anonymous id it replaced, if any. + + The second value becomes a PostHog $identify alias. It is ONLY ever an + anonymous id: aliasing one account email to another merges two real person + profiles and cannot be undone, so a key that now belongs to a different + account re-resolves with no alias. + """ identity = _read_identity() - email = identity.get("email", "") - if email: - return email, "" key = memory_core.api_key() + fingerprint = _digest(key) if key else "" + email = identity.get("email", "") + + if email and fingerprint: + recorded = identity.get("key_fingerprint", "") + if recorded == fingerprint: + return email, "" + if not recorded: + # Rows written before fingerprints existed. Verify rather than + # adopt: a key changed before the upgrade would otherwise bind the + # new key to the previous account's email, permanently, and the + # fingerprint would then agree with itself forever after. + verified = _resolve_email(key) + if not verified: + # Offline, firewalled, or the API is down. Keep the previous + # behaviour and retry on the next flush rather than dropping a + # real account attribution. Safe because the same network that + # failed /v1/ping/ is about to fail the PostHog POST, so nothing + # is delivered under the unverified identity in the meantime. + return email, "" + identity["email"] = verified + identity["key_fingerprint"] = fingerprint + _write_identity(identity) + return verified, "" + if not key: + # No key to verify the account with; do not keep attributing to it. + if email: + identity.pop("email", None) + identity.pop("key_fingerprint", None) + return _rotate_anonymous_id(identity), "" return anonymous_id(identity), "" - email = _resolve_email(key) - if not email: + + resolved = _resolve_email(key) + if not resolved: + # The key changed and will not resolve (revoked, offline, API down). + # Reaching here with an email means the recorded fingerprint disagreed, + # so the key really did change. Drop the account and rotate: the stored + # anonymous id may already be merged into that account's person, and + # reusing it would keep the events on the profile we are trying to + # leave. + if email: + identity.pop("email", None) + identity.pop("key_fingerprint", None) + return _rotate_anonymous_id(identity), "" return anonymous_id(identity), "" - previous = identity.get("anonymous_id", "") - identity["email"] = email + + # Alias only when going anonymous -> email for the first time. Once an anon + # id has been merged into an account it must never be offered again: an + # alias naming an already-identified id is what could link two real people. + previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "") + if previous: + identity["aliased"] = True + identity["email"] = resolved + identity["key_fingerprint"] = fingerprint _write_identity(identity) - return email, previous + return resolved, previous def flush() -> int: diff --git a/integrations/claude-code-plugin/tests/test_telemetry.py b/integrations/claude-code-plugin/tests/test_telemetry.py index de0db10c6..73bf8f121 100644 --- a/integrations/claude-code-plugin/tests/test_telemetry.py +++ b/integrations/claude-code-plugin/tests/test_telemetry.py @@ -265,12 +265,150 @@ def test_an_unresolvable_key_falls_back_to_the_anonymous_id(isolated_env, monkey assert telemetry.resolve_distinct_id()[0].startswith("code-anon-") -def test_is_first_run_flips_after_the_first_identity_write(isolated_env): +def test_logging_out_does_not_leave_events_on_the_previous_account(isolated_env, monkeypatch): + """Review finding: clearing the email kept an id already merged into a person. + + The anonymous id is offered to PostHog as $anon_distinct_id on first sign-in, + and that merge is permanent. Keeping it after the key goes away means every + later anonymous event lands on the account that just left. + """ + # Run anonymously first, which is the only way an id exists to be merged. + merged = telemetry.anonymous_id() + + monkeypatch.setenv("MEM0_API_KEY", "key-for-account-a") + with patch.object(telemetry, "_resolve_email", lambda key: "a@example.com"): + identified, alias = telemetry.resolve_distinct_id() + assert identified == "a@example.com" + assert alias == merged, "the anonymous id was merged into this account" + + monkeypatch.delenv("MEM0_API_KEY", raising=False) + after_logout, logout_alias = telemetry.resolve_distinct_id() + + assert after_logout.startswith("code-anon-") + assert after_logout != merged, "reused an id already merged into the previous account" + assert logout_alias == "" + assert "aliased" not in telemetry._read_identity(), "rotated id must be aliasable again" + + +def test_a_changed_key_that_will_not_resolve_rotates_the_anonymous_id(isolated_env, monkeypatch): + """Same leak by the other route: fingerprint disagrees and the lookup fails.""" + merged = telemetry.anonymous_id() + monkeypatch.setenv("MEM0_API_KEY", "key-for-account-a") + with patch.object(telemetry, "_resolve_email", lambda key: "a@example.com"): + telemetry.resolve_distinct_id() + + monkeypatch.setenv("MEM0_API_KEY", "key-for-account-b") + with patch.object(telemetry, "_resolve_email", lambda key: ""): + after, alias = telemetry.resolve_distinct_id() + + assert after.startswith("code-anon-") + assert after != merged + assert alias == "" + assert "email" not in telemetry._read_identity() + + +def test_a_legacy_cached_email_is_verified_before_the_key_is_bound(isolated_env, monkeypatch): + """Review finding: a key changed before upgrading bound the wrong account. + + Rows written before fingerprints existed carry an email and no fingerprint. + Adopting the current key without checking pinned that key to the previous + account's email, and every run after that agreed with itself. + """ + telemetry._write_identity({"email": "old@example.com", "anonymous_id": "code-anon-seed"}) + monkeypatch.setenv("MEM0_API_KEY", "key-for-account-b") + + with patch.object(telemetry, "_resolve_email", lambda key: "new@example.com"): + resolved, alias = telemetry.resolve_distinct_id() + + assert resolved == "new@example.com" + assert alias == "", "email to email must never alias; it merges two real people" + stored = telemetry._read_identity() + assert stored["email"] == "new@example.com" + assert stored["key_fingerprint"] == telemetry._digest("key-for-account-b") + + +def test_a_legacy_row_keeps_working_when_the_account_cannot_be_checked(isolated_env, monkeypatch): + """Firewalled users must not lose attribution, and must not bind unverified. + + The same network that fails /v1/ping/ fails the PostHog POST, so nothing is + delivered under the unverified identity while this holds. + """ + telemetry._write_identity({"email": "old@example.com"}) + monkeypatch.setenv("MEM0_API_KEY", "key-for-account-b") + + with patch.object(telemetry, "_resolve_email", lambda key: ""): + resolved, _ = telemetry.resolve_distinct_id() + + assert resolved == "old@example.com" + assert "key_fingerprint" not in telemetry._read_identity(), "bound an unverified key" + + +def test_a_failed_upgrade_claim_can_be_retried(isolated_env, monkeypatch): + """Review finding: a failed rewrite left the sentinel and suppressed forever. + + claim_version_change returns early on FileExistsError, and the marker still + holds the old version, so the upgrade for that version was never recorded + again on that machine. + """ + telemetry.claim_install() + state_path = memory_core.data_dir() / "install-state.json" + state = json.loads(state_path.read_text()) + state["plugin_version"] = "0.0.1-old" + state_path.write_text(json.dumps(state), encoding="utf-8") + + real_replace = Path.replace + + def failing_replace(self, target): + raise OSError("disk full") + + monkeypatch.setattr(Path, "replace", failing_replace) + assert telemetry.claim_version_change() is None + + monkeypatch.setattr(Path, "replace", real_replace) + assert telemetry.claim_version_change() == "0.0.1-old", "sentinel suppressed the retry" + + +def test_first_run_is_not_flipped_by_writing_the_identity_file(isolated_env): + """The identity file is written by a successful flush, not by recording. + + Keying first-run off it meant an offline user recorded code.install on every + session forever, and every 0.2.x user recorded one on their first 0.3.x run. + """ assert telemetry.is_first_run() telemetry.anonymous_id() + assert telemetry.is_first_run() + + +def test_claiming_install_ends_first_run(isolated_env): + assert telemetry.claim_install() == "install" assert not telemetry.is_first_run() +def test_install_can_only_be_claimed_once(isolated_env): + """Two sessions starting together must not both record an install.""" + assert telemetry.claim_install() == "install" + assert telemetry.claim_install() is None + + +def test_a_populated_data_dir_reads_as_an_upgrade(isolated_env): + """A fresh install has an empty data directory; anything else predates it.""" + data_dir = memory_core.data_dir() + data_dir.mkdir(parents=True, exist_ok=True) + (data_dir / "requirements.txt").write_text("mem0ai\n", encoding="utf-8") + assert telemetry.claim_install() == "upgrade" + + +def test_a_version_change_is_claimed_once(isolated_env): + telemetry.claim_install() + state_path = memory_core.data_dir() / "install-state.json" + state = json.loads(state_path.read_text()) + state["plugin_version"] = "0.0.1-old" + state_path.write_text(json.dumps(state), encoding="utf-8") + + assert telemetry.claim_version_change() == "0.0.1-old" + assert telemetry.claim_version_change() is None + + def test_spawn_flush_does_nothing_without_a_spool(isolated_env): with patch.object(telemetry.subprocess, "Popen") as popen: assert telemetry.spawn_flush() is False diff --git a/integrations/codex-plugin/core/hook_runner.py b/integrations/codex-plugin/core/hook_runner.py index 2a2adb557..b3d8a3210 100644 --- a/integrations/codex-plugin/core/hook_runner.py +++ b/integrations/codex-plugin/core/hook_runner.py @@ -290,6 +290,11 @@ def run( if args.plugin_data_dir: os.environ[data_dir_env] = args.plugin_data_dir + # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key + # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking + # after them always saw content and every fresh install reported an upgrade. + data_dir_was_empty = telemetry.data_dir_was_empty() + cache_plugin_api_key() if args.action == "session-start": clear_stale_api_key_cache() @@ -305,8 +310,19 @@ def run( return 0 if args.action == "session-start": - if telemetry.is_first_run(): + # Claims the marker atomically and says which event to record, so a + # second session starting alongside this one cannot record it too. + first_event = telemetry.claim_install(was_empty=data_dir_was_empty) + if first_event == "install": telemetry.record("install") + elif first_event == "upgrade": + # First run after a build that never wrote the marker; the + # predecessor version was never recorded anywhere. + telemetry.record("upgrade", from_version="pre-0.3") + else: + previous = telemetry.claim_version_change() + if previous: + telemetry.record("upgrade", from_version=previous) recovered = recover_pending_handoffs() record_session_start(store, hook_input) if recovered: diff --git a/integrations/codex-plugin/core/telemetry.py b/integrations/codex-plugin/core/telemetry.py index a4375f002..c1fc0084c 100644 --- a/integrations/codex-plugin/core/telemetry.py +++ b/integrations/codex-plugin/core/telemetry.py @@ -302,9 +302,176 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str: return created +def _rotate_anonymous_id(identity: dict[str, str]) -> str: + """Mint a fresh anonymous id because the account context is gone. + + The previous id may already have been merged into a person profile by an + $identify, and that merge is permanent. Reusing it after a logout or a key + change attributes everything that follows to the account that just went + away, which is the same misattribution the key fingerprint exists to stop, + only arriving through the anonymous path instead. + + `aliased` is cleared with it: the new id has never been merged, so it is + eligible to be aliased into whatever account comes next. + """ + created = f"code-anon-{uuid.uuid4().hex}" + identity["anonymous_id"] = created + identity.pop("aliased", None) + _write_identity(identity) + return created + + +def _install_state_path() -> Path: + return memory_core.data_dir() / "install-state.json" + + def is_first_run() -> bool: - """Whether this machine has never recorded a plugin event before.""" - return not _identity_path().exists() + """Whether install has never been recorded on this machine. + + Deliberately NOT the identity file. That file is only written by a + successful flush, so an offline or firewalled user recorded code.install on + every single session, forever — and every 0.2.x user recorded one on their + first 0.3.x session because 0.2.x never wrote it at all. + """ + return not _install_state_path().exists() + + +def data_dir_was_empty() -> bool: + """Whether the data directory is untouched. Call BEFORE anything writes to it. + + hook_runner reaches claim_install() only after cache_plugin_api_key() has + written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so + asking at claim time always saw content and every fresh install reported an + upgrade. The caller snapshots this at the top of the run instead. + """ + return not _data_dir_has_content() + + +def claim_install(was_empty: bool | None = None) -> str | None: + """Claim the one install/upgrade record for this machine, atomically. + + Returns the event to record ("install" or "upgrade"), or None if another + session already claimed it. O_CREAT|O_EXCL so two sessions starting together + cannot both win. + + `was_empty` must come from data_dir_was_empty() called before this process + wrote anything. Omitting it falls back to checking now, which is only + correct for a caller that has touched nothing. + """ + if not is_enabled(): + # Never consume the one-shot claim while the user is opted out, or they + # would silently lose their install event if they later opt in. + return None + + path = _install_state_path() + upgrading = not (data_dir_was_empty() if was_empty is None else was_empty) + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + return None + except OSError: + return None + try: + with os.fdopen(handle, "w", encoding="utf-8") as stream: + json.dump( + { + "plugin_version": memory_core.PLUGIN_VERSION, + "installed_at": memory_core.utc_now(), + "upgraded": upgrading, + }, + stream, + ) + # Durable before this returns. The O_EXCL open is what makes the + # claim exclusive, so it cannot be replaced by a temp-and-rename + # without losing that, which leaves the content as the thing to make + # safe. A kill between the open and this fsync used to leave a marker + # that exists but parses to nothing: is_first_run reads it as claimed + # and claim_version_change cannot read a version out of it. + stream.flush() + os.fsync(stream.fileno()) + except OSError: + pass + return "upgrade" if upgrading else "install" + + +def _data_dir_has_content() -> bool: + """Whether anything predates this session in the plugin data directory.""" + try: + for entry in memory_core.data_dir().iterdir(): + if entry.name != "install-state.json": + return True + except OSError: + pass + return False + + +def _repair_install_state(path: Path) -> None: + """Rewrite an unparseable marker so version tracking can resume.""" + try: + temporary = path.with_suffix(f".{os.getpid()}.tmp") + temporary.write_text( + json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}), + encoding="utf-8", + ) + temporary.replace(path) + except OSError: + pass + + +def claim_version_change() -> str | None: + """Return the previously recorded version if it differs, updating the marker. + + Only meaningful once the marker exists — the first transition into 0.3.x has + no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting + the marker means the next session sees no change and records nothing. + """ + path = _install_state_path() + try: + state = json.loads(path.read_text(encoding="utf-8")) + except OSError: + return None + except json.JSONDecodeError: + # A crash between O_EXCL and the write leaves an empty marker. Left + # alone it disables every future upgrade event on this machine, because + # claim_install sees the file and this function cannot parse it. + state = None + if not isinstance(state, dict): + _repair_install_state(path) + return None + previous = str(state.get("plugin_version") or "") + if not previous or previous == memory_core.PLUGIN_VERSION: + return None + # Claim the transition with an exclusive sentinel before rewriting the + # marker. A plain read-modify-write let every concurrently starting session + # observe the old version and each record its own upgrade — and the first + # session after a version bump is exactly when several agent windows restart + # together. + sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}") + try: + os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)) + except FileExistsError: + return None + except OSError: + return None + + state["plugin_version"] = memory_core.PLUGIN_VERSION + state["upgraded_at"] = memory_core.utc_now() + temporary = path.with_suffix(f".{os.getpid()}.tmp") + try: + temporary.write_text(json.dumps(state), encoding="utf-8") + temporary.replace(path) + except OSError: + # Release the claim. The marker still records the old version, so + # without this the sentinel makes claim_version_change return early on + # every later run and this version's upgrade is never recorded again. + for leftover in (sentinel, temporary): + try: + leftover.unlink() + except OSError: + pass + return None + return previous def record( @@ -633,21 +800,72 @@ def _post(payload: dict[str, Any], url: str) -> bool: def resolve_distinct_id() -> tuple[str, str]: - """Return the PostHog distinct id and the anonymous id it replaced, if any.""" + """Return the PostHog distinct id and the anonymous id it replaced, if any. + + The second value becomes a PostHog $identify alias. It is ONLY ever an + anonymous id: aliasing one account email to another merges two real person + profiles and cannot be undone, so a key that now belongs to a different + account re-resolves with no alias. + """ identity = _read_identity() - email = identity.get("email", "") - if email: - return email, "" key = memory_core.api_key() + fingerprint = _digest(key) if key else "" + email = identity.get("email", "") + + if email and fingerprint: + recorded = identity.get("key_fingerprint", "") + if recorded == fingerprint: + return email, "" + if not recorded: + # Rows written before fingerprints existed. Verify rather than + # adopt: a key changed before the upgrade would otherwise bind the + # new key to the previous account's email, permanently, and the + # fingerprint would then agree with itself forever after. + verified = _resolve_email(key) + if not verified: + # Offline, firewalled, or the API is down. Keep the previous + # behaviour and retry on the next flush rather than dropping a + # real account attribution. Safe because the same network that + # failed /v1/ping/ is about to fail the PostHog POST, so nothing + # is delivered under the unverified identity in the meantime. + return email, "" + identity["email"] = verified + identity["key_fingerprint"] = fingerprint + _write_identity(identity) + return verified, "" + if not key: + # No key to verify the account with; do not keep attributing to it. + if email: + identity.pop("email", None) + identity.pop("key_fingerprint", None) + return _rotate_anonymous_id(identity), "" return anonymous_id(identity), "" - email = _resolve_email(key) - if not email: + + resolved = _resolve_email(key) + if not resolved: + # The key changed and will not resolve (revoked, offline, API down). + # Reaching here with an email means the recorded fingerprint disagreed, + # so the key really did change. Drop the account and rotate: the stored + # anonymous id may already be merged into that account's person, and + # reusing it would keep the events on the profile we are trying to + # leave. + if email: + identity.pop("email", None) + identity.pop("key_fingerprint", None) + return _rotate_anonymous_id(identity), "" return anonymous_id(identity), "" - previous = identity.get("anonymous_id", "") - identity["email"] = email + + # Alias only when going anonymous -> email for the first time. Once an anon + # id has been merged into an account it must never be offered again: an + # alias naming an already-identified id is what could link two real people. + previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "") + if previous: + identity["aliased"] = True + identity["email"] = resolved + identity["key_fingerprint"] = fingerprint _write_identity(identity) - return email, previous + return resolved, previous def flush() -> int: diff --git a/integrations/cursor-plugin/core/hook_runner.py b/integrations/cursor-plugin/core/hook_runner.py index 2a2adb557..b3d8a3210 100644 --- a/integrations/cursor-plugin/core/hook_runner.py +++ b/integrations/cursor-plugin/core/hook_runner.py @@ -290,6 +290,11 @@ def run( if args.plugin_data_dir: os.environ[data_dir_env] = args.plugin_data_dir + # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key + # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking + # after them always saw content and every fresh install reported an upgrade. + data_dir_was_empty = telemetry.data_dir_was_empty() + cache_plugin_api_key() if args.action == "session-start": clear_stale_api_key_cache() @@ -305,8 +310,19 @@ def run( return 0 if args.action == "session-start": - if telemetry.is_first_run(): + # Claims the marker atomically and says which event to record, so a + # second session starting alongside this one cannot record it too. + first_event = telemetry.claim_install(was_empty=data_dir_was_empty) + if first_event == "install": telemetry.record("install") + elif first_event == "upgrade": + # First run after a build that never wrote the marker; the + # predecessor version was never recorded anywhere. + telemetry.record("upgrade", from_version="pre-0.3") + else: + previous = telemetry.claim_version_change() + if previous: + telemetry.record("upgrade", from_version=previous) recovered = recover_pending_handoffs() record_session_start(store, hook_input) if recovered: diff --git a/integrations/cursor-plugin/core/telemetry.py b/integrations/cursor-plugin/core/telemetry.py index a4375f002..c1fc0084c 100644 --- a/integrations/cursor-plugin/core/telemetry.py +++ b/integrations/cursor-plugin/core/telemetry.py @@ -302,9 +302,176 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str: return created +def _rotate_anonymous_id(identity: dict[str, str]) -> str: + """Mint a fresh anonymous id because the account context is gone. + + The previous id may already have been merged into a person profile by an + $identify, and that merge is permanent. Reusing it after a logout or a key + change attributes everything that follows to the account that just went + away, which is the same misattribution the key fingerprint exists to stop, + only arriving through the anonymous path instead. + + `aliased` is cleared with it: the new id has never been merged, so it is + eligible to be aliased into whatever account comes next. + """ + created = f"code-anon-{uuid.uuid4().hex}" + identity["anonymous_id"] = created + identity.pop("aliased", None) + _write_identity(identity) + return created + + +def _install_state_path() -> Path: + return memory_core.data_dir() / "install-state.json" + + def is_first_run() -> bool: - """Whether this machine has never recorded a plugin event before.""" - return not _identity_path().exists() + """Whether install has never been recorded on this machine. + + Deliberately NOT the identity file. That file is only written by a + successful flush, so an offline or firewalled user recorded code.install on + every single session, forever — and every 0.2.x user recorded one on their + first 0.3.x session because 0.2.x never wrote it at all. + """ + return not _install_state_path().exists() + + +def data_dir_was_empty() -> bool: + """Whether the data directory is untouched. Call BEFORE anything writes to it. + + hook_runner reaches claim_install() only after cache_plugin_api_key() has + written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so + asking at claim time always saw content and every fresh install reported an + upgrade. The caller snapshots this at the top of the run instead. + """ + return not _data_dir_has_content() + + +def claim_install(was_empty: bool | None = None) -> str | None: + """Claim the one install/upgrade record for this machine, atomically. + + Returns the event to record ("install" or "upgrade"), or None if another + session already claimed it. O_CREAT|O_EXCL so two sessions starting together + cannot both win. + + `was_empty` must come from data_dir_was_empty() called before this process + wrote anything. Omitting it falls back to checking now, which is only + correct for a caller that has touched nothing. + """ + if not is_enabled(): + # Never consume the one-shot claim while the user is opted out, or they + # would silently lose their install event if they later opt in. + return None + + path = _install_state_path() + upgrading = not (data_dir_was_empty() if was_empty is None else was_empty) + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + return None + except OSError: + return None + try: + with os.fdopen(handle, "w", encoding="utf-8") as stream: + json.dump( + { + "plugin_version": memory_core.PLUGIN_VERSION, + "installed_at": memory_core.utc_now(), + "upgraded": upgrading, + }, + stream, + ) + # Durable before this returns. The O_EXCL open is what makes the + # claim exclusive, so it cannot be replaced by a temp-and-rename + # without losing that, which leaves the content as the thing to make + # safe. A kill between the open and this fsync used to leave a marker + # that exists but parses to nothing: is_first_run reads it as claimed + # and claim_version_change cannot read a version out of it. + stream.flush() + os.fsync(stream.fileno()) + except OSError: + pass + return "upgrade" if upgrading else "install" + + +def _data_dir_has_content() -> bool: + """Whether anything predates this session in the plugin data directory.""" + try: + for entry in memory_core.data_dir().iterdir(): + if entry.name != "install-state.json": + return True + except OSError: + pass + return False + + +def _repair_install_state(path: Path) -> None: + """Rewrite an unparseable marker so version tracking can resume.""" + try: + temporary = path.with_suffix(f".{os.getpid()}.tmp") + temporary.write_text( + json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}), + encoding="utf-8", + ) + temporary.replace(path) + except OSError: + pass + + +def claim_version_change() -> str | None: + """Return the previously recorded version if it differs, updating the marker. + + Only meaningful once the marker exists — the first transition into 0.3.x has + no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting + the marker means the next session sees no change and records nothing. + """ + path = _install_state_path() + try: + state = json.loads(path.read_text(encoding="utf-8")) + except OSError: + return None + except json.JSONDecodeError: + # A crash between O_EXCL and the write leaves an empty marker. Left + # alone it disables every future upgrade event on this machine, because + # claim_install sees the file and this function cannot parse it. + state = None + if not isinstance(state, dict): + _repair_install_state(path) + return None + previous = str(state.get("plugin_version") or "") + if not previous or previous == memory_core.PLUGIN_VERSION: + return None + # Claim the transition with an exclusive sentinel before rewriting the + # marker. A plain read-modify-write let every concurrently starting session + # observe the old version and each record its own upgrade — and the first + # session after a version bump is exactly when several agent windows restart + # together. + sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}") + try: + os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)) + except FileExistsError: + return None + except OSError: + return None + + state["plugin_version"] = memory_core.PLUGIN_VERSION + state["upgraded_at"] = memory_core.utc_now() + temporary = path.with_suffix(f".{os.getpid()}.tmp") + try: + temporary.write_text(json.dumps(state), encoding="utf-8") + temporary.replace(path) + except OSError: + # Release the claim. The marker still records the old version, so + # without this the sentinel makes claim_version_change return early on + # every later run and this version's upgrade is never recorded again. + for leftover in (sentinel, temporary): + try: + leftover.unlink() + except OSError: + pass + return None + return previous def record( @@ -633,21 +800,72 @@ def _post(payload: dict[str, Any], url: str) -> bool: def resolve_distinct_id() -> tuple[str, str]: - """Return the PostHog distinct id and the anonymous id it replaced, if any.""" + """Return the PostHog distinct id and the anonymous id it replaced, if any. + + The second value becomes a PostHog $identify alias. It is ONLY ever an + anonymous id: aliasing one account email to another merges two real person + profiles and cannot be undone, so a key that now belongs to a different + account re-resolves with no alias. + """ identity = _read_identity() - email = identity.get("email", "") - if email: - return email, "" key = memory_core.api_key() + fingerprint = _digest(key) if key else "" + email = identity.get("email", "") + + if email and fingerprint: + recorded = identity.get("key_fingerprint", "") + if recorded == fingerprint: + return email, "" + if not recorded: + # Rows written before fingerprints existed. Verify rather than + # adopt: a key changed before the upgrade would otherwise bind the + # new key to the previous account's email, permanently, and the + # fingerprint would then agree with itself forever after. + verified = _resolve_email(key) + if not verified: + # Offline, firewalled, or the API is down. Keep the previous + # behaviour and retry on the next flush rather than dropping a + # real account attribution. Safe because the same network that + # failed /v1/ping/ is about to fail the PostHog POST, so nothing + # is delivered under the unverified identity in the meantime. + return email, "" + identity["email"] = verified + identity["key_fingerprint"] = fingerprint + _write_identity(identity) + return verified, "" + if not key: + # No key to verify the account with; do not keep attributing to it. + if email: + identity.pop("email", None) + identity.pop("key_fingerprint", None) + return _rotate_anonymous_id(identity), "" return anonymous_id(identity), "" - email = _resolve_email(key) - if not email: + + resolved = _resolve_email(key) + if not resolved: + # The key changed and will not resolve (revoked, offline, API down). + # Reaching here with an email means the recorded fingerprint disagreed, + # so the key really did change. Drop the account and rotate: the stored + # anonymous id may already be merged into that account's person, and + # reusing it would keep the events on the profile we are trying to + # leave. + if email: + identity.pop("email", None) + identity.pop("key_fingerprint", None) + return _rotate_anonymous_id(identity), "" return anonymous_id(identity), "" - previous = identity.get("anonymous_id", "") - identity["email"] = email + + # Alias only when going anonymous -> email for the first time. Once an anon + # id has been merged into an account it must never be offered again: an + # alias naming an already-identified id is what could link two real people. + previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "") + if previous: + identity["aliased"] = True + identity["email"] = resolved + identity["key_fingerprint"] = fingerprint _write_identity(identity) - return email, previous + return resolved, previous def flush() -> int: diff --git a/integrations/kimi-plugin/core/hook_runner.py b/integrations/kimi-plugin/core/hook_runner.py index 2a2adb557..b3d8a3210 100644 --- a/integrations/kimi-plugin/core/hook_runner.py +++ b/integrations/kimi-plugin/core/hook_runner.py @@ -290,6 +290,11 @@ def run( if args.plugin_data_dir: os.environ[data_dir_env] = args.plugin_data_dir + # Snapshot BEFORE anything writes to the data dir: cache_plugin_api_key + # writes `api-key` and EvidenceStore creates `evidence.sqlite3`, so asking + # after them always saw content and every fresh install reported an upgrade. + data_dir_was_empty = telemetry.data_dir_was_empty() + cache_plugin_api_key() if args.action == "session-start": clear_stale_api_key_cache() @@ -305,8 +310,19 @@ def run( return 0 if args.action == "session-start": - if telemetry.is_first_run(): + # Claims the marker atomically and says which event to record, so a + # second session starting alongside this one cannot record it too. + first_event = telemetry.claim_install(was_empty=data_dir_was_empty) + if first_event == "install": telemetry.record("install") + elif first_event == "upgrade": + # First run after a build that never wrote the marker; the + # predecessor version was never recorded anywhere. + telemetry.record("upgrade", from_version="pre-0.3") + else: + previous = telemetry.claim_version_change() + if previous: + telemetry.record("upgrade", from_version=previous) recovered = recover_pending_handoffs() record_session_start(store, hook_input) if recovered: diff --git a/integrations/kimi-plugin/core/telemetry.py b/integrations/kimi-plugin/core/telemetry.py index a4375f002..c1fc0084c 100644 --- a/integrations/kimi-plugin/core/telemetry.py +++ b/integrations/kimi-plugin/core/telemetry.py @@ -302,9 +302,176 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str: return created +def _rotate_anonymous_id(identity: dict[str, str]) -> str: + """Mint a fresh anonymous id because the account context is gone. + + The previous id may already have been merged into a person profile by an + $identify, and that merge is permanent. Reusing it after a logout or a key + change attributes everything that follows to the account that just went + away, which is the same misattribution the key fingerprint exists to stop, + only arriving through the anonymous path instead. + + `aliased` is cleared with it: the new id has never been merged, so it is + eligible to be aliased into whatever account comes next. + """ + created = f"code-anon-{uuid.uuid4().hex}" + identity["anonymous_id"] = created + identity.pop("aliased", None) + _write_identity(identity) + return created + + +def _install_state_path() -> Path: + return memory_core.data_dir() / "install-state.json" + + def is_first_run() -> bool: - """Whether this machine has never recorded a plugin event before.""" - return not _identity_path().exists() + """Whether install has never been recorded on this machine. + + Deliberately NOT the identity file. That file is only written by a + successful flush, so an offline or firewalled user recorded code.install on + every single session, forever — and every 0.2.x user recorded one on their + first 0.3.x session because 0.2.x never wrote it at all. + """ + return not _install_state_path().exists() + + +def data_dir_was_empty() -> bool: + """Whether the data directory is untouched. Call BEFORE anything writes to it. + + hook_runner reaches claim_install() only after cache_plugin_api_key() has + written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so + asking at claim time always saw content and every fresh install reported an + upgrade. The caller snapshots this at the top of the run instead. + """ + return not _data_dir_has_content() + + +def claim_install(was_empty: bool | None = None) -> str | None: + """Claim the one install/upgrade record for this machine, atomically. + + Returns the event to record ("install" or "upgrade"), or None if another + session already claimed it. O_CREAT|O_EXCL so two sessions starting together + cannot both win. + + `was_empty` must come from data_dir_was_empty() called before this process + wrote anything. Omitting it falls back to checking now, which is only + correct for a caller that has touched nothing. + """ + if not is_enabled(): + # Never consume the one-shot claim while the user is opted out, or they + # would silently lose their install event if they later opt in. + return None + + path = _install_state_path() + upgrading = not (data_dir_was_empty() if was_empty is None else was_empty) + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + return None + except OSError: + return None + try: + with os.fdopen(handle, "w", encoding="utf-8") as stream: + json.dump( + { + "plugin_version": memory_core.PLUGIN_VERSION, + "installed_at": memory_core.utc_now(), + "upgraded": upgrading, + }, + stream, + ) + # Durable before this returns. The O_EXCL open is what makes the + # claim exclusive, so it cannot be replaced by a temp-and-rename + # without losing that, which leaves the content as the thing to make + # safe. A kill between the open and this fsync used to leave a marker + # that exists but parses to nothing: is_first_run reads it as claimed + # and claim_version_change cannot read a version out of it. + stream.flush() + os.fsync(stream.fileno()) + except OSError: + pass + return "upgrade" if upgrading else "install" + + +def _data_dir_has_content() -> bool: + """Whether anything predates this session in the plugin data directory.""" + try: + for entry in memory_core.data_dir().iterdir(): + if entry.name != "install-state.json": + return True + except OSError: + pass + return False + + +def _repair_install_state(path: Path) -> None: + """Rewrite an unparseable marker so version tracking can resume.""" + try: + temporary = path.with_suffix(f".{os.getpid()}.tmp") + temporary.write_text( + json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}), + encoding="utf-8", + ) + temporary.replace(path) + except OSError: + pass + + +def claim_version_change() -> str | None: + """Return the previously recorded version if it differs, updating the marker. + + Only meaningful once the marker exists — the first transition into 0.3.x has + no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting + the marker means the next session sees no change and records nothing. + """ + path = _install_state_path() + try: + state = json.loads(path.read_text(encoding="utf-8")) + except OSError: + return None + except json.JSONDecodeError: + # A crash between O_EXCL and the write leaves an empty marker. Left + # alone it disables every future upgrade event on this machine, because + # claim_install sees the file and this function cannot parse it. + state = None + if not isinstance(state, dict): + _repair_install_state(path) + return None + previous = str(state.get("plugin_version") or "") + if not previous or previous == memory_core.PLUGIN_VERSION: + return None + # Claim the transition with an exclusive sentinel before rewriting the + # marker. A plain read-modify-write let every concurrently starting session + # observe the old version and each record its own upgrade — and the first + # session after a version bump is exactly when several agent windows restart + # together. + sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}") + try: + os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)) + except FileExistsError: + return None + except OSError: + return None + + state["plugin_version"] = memory_core.PLUGIN_VERSION + state["upgraded_at"] = memory_core.utc_now() + temporary = path.with_suffix(f".{os.getpid()}.tmp") + try: + temporary.write_text(json.dumps(state), encoding="utf-8") + temporary.replace(path) + except OSError: + # Release the claim. The marker still records the old version, so + # without this the sentinel makes claim_version_change return early on + # every later run and this version's upgrade is never recorded again. + for leftover in (sentinel, temporary): + try: + leftover.unlink() + except OSError: + pass + return None + return previous def record( @@ -633,21 +800,72 @@ def _post(payload: dict[str, Any], url: str) -> bool: def resolve_distinct_id() -> tuple[str, str]: - """Return the PostHog distinct id and the anonymous id it replaced, if any.""" + """Return the PostHog distinct id and the anonymous id it replaced, if any. + + The second value becomes a PostHog $identify alias. It is ONLY ever an + anonymous id: aliasing one account email to another merges two real person + profiles and cannot be undone, so a key that now belongs to a different + account re-resolves with no alias. + """ identity = _read_identity() - email = identity.get("email", "") - if email: - return email, "" key = memory_core.api_key() + fingerprint = _digest(key) if key else "" + email = identity.get("email", "") + + if email and fingerprint: + recorded = identity.get("key_fingerprint", "") + if recorded == fingerprint: + return email, "" + if not recorded: + # Rows written before fingerprints existed. Verify rather than + # adopt: a key changed before the upgrade would otherwise bind the + # new key to the previous account's email, permanently, and the + # fingerprint would then agree with itself forever after. + verified = _resolve_email(key) + if not verified: + # Offline, firewalled, or the API is down. Keep the previous + # behaviour and retry on the next flush rather than dropping a + # real account attribution. Safe because the same network that + # failed /v1/ping/ is about to fail the PostHog POST, so nothing + # is delivered under the unverified identity in the meantime. + return email, "" + identity["email"] = verified + identity["key_fingerprint"] = fingerprint + _write_identity(identity) + return verified, "" + if not key: + # No key to verify the account with; do not keep attributing to it. + if email: + identity.pop("email", None) + identity.pop("key_fingerprint", None) + return _rotate_anonymous_id(identity), "" return anonymous_id(identity), "" - email = _resolve_email(key) - if not email: + + resolved = _resolve_email(key) + if not resolved: + # The key changed and will not resolve (revoked, offline, API down). + # Reaching here with an email means the recorded fingerprint disagreed, + # so the key really did change. Drop the account and rotate: the stored + # anonymous id may already be merged into that account's person, and + # reusing it would keep the events on the profile we are trying to + # leave. + if email: + identity.pop("email", None) + identity.pop("key_fingerprint", None) + return _rotate_anonymous_id(identity), "" return anonymous_id(identity), "" - previous = identity.get("anonymous_id", "") - identity["email"] = email + + # Alias only when going anonymous -> email for the first time. Once an anon + # id has been merged into an account it must never be offered again: an + # alias naming an already-identified id is what could link two real people. + previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "") + if previous: + identity["aliased"] = True + identity["email"] = resolved + identity["key_fingerprint"] = fingerprint _write_identity(identity) - return email, previous + return resolved, previous def flush() -> int: diff --git a/integrations/mem0-agent-plugin/core/telemetry.py b/integrations/mem0-agent-plugin/core/telemetry.py index a4375f002..c1fc0084c 100644 --- a/integrations/mem0-agent-plugin/core/telemetry.py +++ b/integrations/mem0-agent-plugin/core/telemetry.py @@ -302,9 +302,176 @@ def anonymous_id(identity: dict[str, str] | None = None) -> str: return created +def _rotate_anonymous_id(identity: dict[str, str]) -> str: + """Mint a fresh anonymous id because the account context is gone. + + The previous id may already have been merged into a person profile by an + $identify, and that merge is permanent. Reusing it after a logout or a key + change attributes everything that follows to the account that just went + away, which is the same misattribution the key fingerprint exists to stop, + only arriving through the anonymous path instead. + + `aliased` is cleared with it: the new id has never been merged, so it is + eligible to be aliased into whatever account comes next. + """ + created = f"code-anon-{uuid.uuid4().hex}" + identity["anonymous_id"] = created + identity.pop("aliased", None) + _write_identity(identity) + return created + + +def _install_state_path() -> Path: + return memory_core.data_dir() / "install-state.json" + + def is_first_run() -> bool: - """Whether this machine has never recorded a plugin event before.""" - return not _identity_path().exists() + """Whether install has never been recorded on this machine. + + Deliberately NOT the identity file. That file is only written by a + successful flush, so an offline or firewalled user recorded code.install on + every single session, forever — and every 0.2.x user recorded one on their + first 0.3.x session because 0.2.x never wrote it at all. + """ + return not _install_state_path().exists() + + +def data_dir_was_empty() -> bool: + """Whether the data directory is untouched. Call BEFORE anything writes to it. + + hook_runner reaches claim_install() only after cache_plugin_api_key() has + written `api-key` and EvidenceStore() has created `evidence.sqlite3`, so + asking at claim time always saw content and every fresh install reported an + upgrade. The caller snapshots this at the top of the run instead. + """ + return not _data_dir_has_content() + + +def claim_install(was_empty: bool | None = None) -> str | None: + """Claim the one install/upgrade record for this machine, atomically. + + Returns the event to record ("install" or "upgrade"), or None if another + session already claimed it. O_CREAT|O_EXCL so two sessions starting together + cannot both win. + + `was_empty` must come from data_dir_was_empty() called before this process + wrote anything. Omitting it falls back to checking now, which is only + correct for a caller that has touched nothing. + """ + if not is_enabled(): + # Never consume the one-shot claim while the user is opted out, or they + # would silently lose their install event if they later opt in. + return None + + path = _install_state_path() + upgrading = not (data_dir_was_empty() if was_empty is None else was_empty) + try: + path.parent.mkdir(parents=True, exist_ok=True) + handle = os.open(path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + return None + except OSError: + return None + try: + with os.fdopen(handle, "w", encoding="utf-8") as stream: + json.dump( + { + "plugin_version": memory_core.PLUGIN_VERSION, + "installed_at": memory_core.utc_now(), + "upgraded": upgrading, + }, + stream, + ) + # Durable before this returns. The O_EXCL open is what makes the + # claim exclusive, so it cannot be replaced by a temp-and-rename + # without losing that, which leaves the content as the thing to make + # safe. A kill between the open and this fsync used to leave a marker + # that exists but parses to nothing: is_first_run reads it as claimed + # and claim_version_change cannot read a version out of it. + stream.flush() + os.fsync(stream.fileno()) + except OSError: + pass + return "upgrade" if upgrading else "install" + + +def _data_dir_has_content() -> bool: + """Whether anything predates this session in the plugin data directory.""" + try: + for entry in memory_core.data_dir().iterdir(): + if entry.name != "install-state.json": + return True + except OSError: + pass + return False + + +def _repair_install_state(path: Path) -> None: + """Rewrite an unparseable marker so version tracking can resume.""" + try: + temporary = path.with_suffix(f".{os.getpid()}.tmp") + temporary.write_text( + json.dumps({"plugin_version": memory_core.PLUGIN_VERSION, "repaired_at": memory_core.utc_now()}), + encoding="utf-8", + ) + temporary.replace(path) + except OSError: + pass + + +def claim_version_change() -> str | None: + """Return the previously recorded version if it differs, updating the marker. + + Only meaningful once the marker exists — the first transition into 0.3.x has + no recorded predecessor and reports "pre-0.3" instead. Claiming by rewriting + the marker means the next session sees no change and records nothing. + """ + path = _install_state_path() + try: + state = json.loads(path.read_text(encoding="utf-8")) + except OSError: + return None + except json.JSONDecodeError: + # A crash between O_EXCL and the write leaves an empty marker. Left + # alone it disables every future upgrade event on this machine, because + # claim_install sees the file and this function cannot parse it. + state = None + if not isinstance(state, dict): + _repair_install_state(path) + return None + previous = str(state.get("plugin_version") or "") + if not previous or previous == memory_core.PLUGIN_VERSION: + return None + # Claim the transition with an exclusive sentinel before rewriting the + # marker. A plain read-modify-write let every concurrently starting session + # observe the old version and each record its own upgrade — and the first + # session after a version bump is exactly when several agent windows restart + # together. + sentinel = path.with_name(f"upgraded-{memory_core.PLUGIN_VERSION}") + try: + os.close(os.open(sentinel, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)) + except FileExistsError: + return None + except OSError: + return None + + state["plugin_version"] = memory_core.PLUGIN_VERSION + state["upgraded_at"] = memory_core.utc_now() + temporary = path.with_suffix(f".{os.getpid()}.tmp") + try: + temporary.write_text(json.dumps(state), encoding="utf-8") + temporary.replace(path) + except OSError: + # Release the claim. The marker still records the old version, so + # without this the sentinel makes claim_version_change return early on + # every later run and this version's upgrade is never recorded again. + for leftover in (sentinel, temporary): + try: + leftover.unlink() + except OSError: + pass + return None + return previous def record( @@ -633,21 +800,72 @@ def _post(payload: dict[str, Any], url: str) -> bool: def resolve_distinct_id() -> tuple[str, str]: - """Return the PostHog distinct id and the anonymous id it replaced, if any.""" + """Return the PostHog distinct id and the anonymous id it replaced, if any. + + The second value becomes a PostHog $identify alias. It is ONLY ever an + anonymous id: aliasing one account email to another merges two real person + profiles and cannot be undone, so a key that now belongs to a different + account re-resolves with no alias. + """ identity = _read_identity() - email = identity.get("email", "") - if email: - return email, "" key = memory_core.api_key() + fingerprint = _digest(key) if key else "" + email = identity.get("email", "") + + if email and fingerprint: + recorded = identity.get("key_fingerprint", "") + if recorded == fingerprint: + return email, "" + if not recorded: + # Rows written before fingerprints existed. Verify rather than + # adopt: a key changed before the upgrade would otherwise bind the + # new key to the previous account's email, permanently, and the + # fingerprint would then agree with itself forever after. + verified = _resolve_email(key) + if not verified: + # Offline, firewalled, or the API is down. Keep the previous + # behaviour and retry on the next flush rather than dropping a + # real account attribution. Safe because the same network that + # failed /v1/ping/ is about to fail the PostHog POST, so nothing + # is delivered under the unverified identity in the meantime. + return email, "" + identity["email"] = verified + identity["key_fingerprint"] = fingerprint + _write_identity(identity) + return verified, "" + if not key: + # No key to verify the account with; do not keep attributing to it. + if email: + identity.pop("email", None) + identity.pop("key_fingerprint", None) + return _rotate_anonymous_id(identity), "" return anonymous_id(identity), "" - email = _resolve_email(key) - if not email: + + resolved = _resolve_email(key) + if not resolved: + # The key changed and will not resolve (revoked, offline, API down). + # Reaching here with an email means the recorded fingerprint disagreed, + # so the key really did change. Drop the account and rotate: the stored + # anonymous id may already be merged into that account's person, and + # reusing it would keep the events on the profile we are trying to + # leave. + if email: + identity.pop("email", None) + identity.pop("key_fingerprint", None) + return _rotate_anonymous_id(identity), "" return anonymous_id(identity), "" - previous = identity.get("anonymous_id", "") - identity["email"] = email + + # Alias only when going anonymous -> email for the first time. Once an anon + # id has been merged into an account it must never be offered again: an + # alias naming an already-identified id is what could link two real people. + previous = "" if (email or identity.get("aliased")) else identity.get("anonymous_id", "") + if previous: + identity["aliased"] = True + identity["email"] = resolved + identity["key_fingerprint"] = fingerprint _write_identity(identity) - return email, previous + return resolved, previous def flush() -> int: From 1a5c7ad28c67ae04381998eb69d829fd1de55de9 Mon Sep 17 00:00:00 2001 From: Saket Aryan Date: Fri, 18 Sep 2026 14:13:11 +0530 Subject: [PATCH 18/61] feat(integrations): declare which surface each client is, and its version (#7326) --- cli/node/src/backend/platform.ts | 3 +- cli/python/src/mem0_cli/backend/platform.py | 3 +- integrations/AGENTS.md | 43 +++++++ integrations/agent-plugin-core/build/build.py | 16 ++- .../agent-plugin-core/python/memory_core.py | 41 +++++- .../agent-plugin-core/tests/test_build.py | 32 +++++ .../tests/test_uninitialised_identity.py | 27 ++++ .../antigravity-plugin/core/_harness_id.py | 2 + .../antigravity-plugin/core/memory_core.py | 41 +++++- .../claude-code-plugin/core/_harness_id.py | 2 + .../claude-code-plugin/core/memory_core.py | 41 +++++- integrations/codex-plugin/core/_harness_id.py | 2 + integrations/codex-plugin/core/memory_core.py | 41 +++++- .../cursor-plugin/core/_harness_id.py | 2 + .../cursor-plugin/core/memory_core.py | 41 +++++- integrations/deepseek-plugin/src/index.ts | 5 +- integrations/kimi-plugin/core/_harness_id.py | 2 + integrations/kimi-plugin/core/memory_core.py | 41 +++++- .../mem0-agent-plugin/core/_harness_id.py | 4 +- .../mem0-agent-plugin/core/memory_core.py | 41 +++++- .../pi-agent-plugin/src/attribution.test.ts | 80 ++++++++++++ .../pi-agent-plugin/src/attribution.ts | 65 ++++++++++ integrations/pi-agent-plugin/src/commands.ts | 16 ++- integrations/pi-agent-plugin/src/entry.ts | 6 + integrations/vercel-ai-sdk/src/mem0-utils.ts | 19 ++- integrations/vercel-ai-sdk/tsconfig.json | 1 + integrations/vercel-ai-sdk/tsup.config.ts | 7 ++ mem0-ts/src/client/mem0.ts | 61 +++++++++ mem0-ts/src/client/mem0.types.ts | 3 + mem0/client/main.py | 118 ++++++++++++++---- tests/test_client_surface_headers.py | 63 ++++++++++ 31 files changed, 812 insertions(+), 57 deletions(-) create mode 100644 integrations/pi-agent-plugin/src/attribution.test.ts create mode 100644 integrations/pi-agent-plugin/src/attribution.ts create mode 100644 tests/test_client_surface_headers.py 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/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/integrations/AGENTS.md b/integrations/AGENTS.md index c129dd48b..221c8206f 100644 --- a/integrations/AGENTS.md +++ b/integrations/AGENTS.md @@ -49,6 +49,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 +101,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/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/memory_core.py b/integrations/agent-plugin-core/python/memory_core.py index 77d7a2b80..d350e76d2 100644 --- a/integrations/agent-plugin-core/python/memory_core.py +++ b/integrations/agent-plugin-core/python/memory_core.py @@ -1800,6 +1800,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 +1835,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 +1862,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 +2008,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 +2558,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/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/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/memory_core.py b/integrations/antigravity-plugin/core/memory_core.py index 77d7a2b80..d350e76d2 100644 --- a/integrations/antigravity-plugin/core/memory_core.py +++ b/integrations/antigravity-plugin/core/memory_core.py @@ -1800,6 +1800,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 +1835,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 +1862,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 +2008,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 +2558,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/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/memory_core.py b/integrations/claude-code-plugin/core/memory_core.py index 77d7a2b80..d350e76d2 100644 --- a/integrations/claude-code-plugin/core/memory_core.py +++ b/integrations/claude-code-plugin/core/memory_core.py @@ -1800,6 +1800,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 +1835,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 +1862,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 +2008,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 +2558,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/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/memory_core.py b/integrations/codex-plugin/core/memory_core.py index 77d7a2b80..d350e76d2 100644 --- a/integrations/codex-plugin/core/memory_core.py +++ b/integrations/codex-plugin/core/memory_core.py @@ -1800,6 +1800,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 +1835,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 +1862,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 +2008,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 +2558,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/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/memory_core.py b/integrations/cursor-plugin/core/memory_core.py index 77d7a2b80..d350e76d2 100644 --- a/integrations/cursor-plugin/core/memory_core.py +++ b/integrations/cursor-plugin/core/memory_core.py @@ -1800,6 +1800,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 +1835,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 +1862,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 +2008,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 +2558,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/deepseek-plugin/src/index.ts b/integrations/deepseek-plugin/src/index.ts index 2d24b498a..3ac86f4b0 100644 --- a/integrations/deepseek-plugin/src/index.ts +++ b/integrations/deepseek-plugin/src/index.ts @@ -26,8 +26,9 @@ 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; 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/memory_core.py b/integrations/kimi-plugin/core/memory_core.py index 77d7a2b80..d350e76d2 100644 --- a/integrations/kimi-plugin/core/memory_core.py +++ b/integrations/kimi-plugin/core/memory_core.py @@ -1800,6 +1800,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 +1835,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 +1862,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 +2008,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 +2558,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/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/memory_core.py b/integrations/mem0-agent-plugin/core/memory_core.py index 77d7a2b80..d350e76d2 100644 --- a/integrations/mem0-agent-plugin/core/memory_core.py +++ b/integrations/mem0-agent-plugin/core/memory_core.py @@ -1800,6 +1800,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 +1835,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 +1862,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 +2008,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 +2558,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/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/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/mem0-ts/src/client/mem0.ts b/mem0-ts/src/client/mem0.ts index ff259f2fe..33e03f0c2 100644 --- a/mem0-ts/src/client/mem0.ts +++ b/mem0-ts/src/client/mem0.ts @@ -95,6 +95,66 @@ interface ClientIdentity { 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 +189,7 @@ export default class MemoryClient { this.headers = { Authorization: `Token ${this.apiKey}`, "Content-Type": "application/json", + ...surfaceHeaders(), }; this.client = axios.create({ diff --git a/mem0-ts/src/client/mem0.types.ts b/mem0-ts/src/client/mem0.types.ts index c230441e0..cbe541321 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 { diff --git a/mem0/client/main.py b/mem0/client/main.py index a52986dcd..3a82d9e5a 100644 --- a/mem0/client/main.py +++ b/mem0/client/main.py @@ -79,6 +79,95 @@ def _maybe_alias_anon_to_email(user_email): logger.debug("Failed to alias anon telemetry to %r: %s", user_email, e) +def _sdk_version() -> str: + """Resolved here rather than imported from the package root, which would cycle.""" + try: + import importlib.metadata + + return importlib.metadata.version("mem0ai") + except Exception: + return "unknown" + + +def _apply_client_headers(client: Any, api_key: str, user_id: str) -> None: + """Merge our headers into a caller-supplied client without erasing theirs. + + A wrapper may hand us a client already carrying its own X-Mem0-Source or a + partial X-Mem0-Client stack. Blanket update() replaced both, which is the + opposite of the set-once / append-only contract: the outermost layer is the + one whose identity should survive. + """ + existing = client.headers + mine = _client_headers(api_key, user_id) + + outer_stack = existing.get("X-Mem0-Client") + if outer_stack: + entries = [part.strip() for part in str(outer_stack).split(",") if part.strip()] + mine["X-Mem0-Client"] = _bounded_stack(entries, f"mem0-python/{_sdk_version()}") + + for name, value in mine.items(): + if name in ("X-Mem0-Source", "X-Application") and existing.get(name): + continue + existing[name] = value + + +MAX_STACK_ENTRIES = 4 +MAX_STACK_CHARS = 200 + + +def _bounded_stack(caller_entries, own: str) -> str: + """Append our own entry and bound the result, dropping WHOLE entries. + + Two rules, and the second is the one that was wrong. Neither cap cuts + characters: a blunt slice severs an identifier and leaves a fragment that + parses as a real client name. And the reserved slot is OURS. Appending first + and then trimming to four dropped exactly the entry this function exists to + add, every time a caller already sent four, so the SDK vanished from its own + stack while the caller's claims all survived. + """ + kept = [] + budget = MAX_STACK_CHARS - len(own) + for entry in list(caller_entries)[: MAX_STACK_ENTRIES - 1]: + cost = len(entry) + len(", ") + if cost > budget: + break + budget -= cost + kept.append(entry) + return ", ".join(kept + [own]) + + +def _client_headers(api_key: str, user_id: str) -> Dict[str, str]: + """Auth plus surface-identity headers. + + X-Mem0-Source and X-Application are SET-ONCE by contract: whichever layer is + outermost sets them, and nothing below overwrites. A plugin or harness that + wraps this SDK therefore keeps its own identity — it declares via MEM0_SOURCE + / MEM0_APPLICATION and the SDK defers. + + X-Mem0-Client is APPEND-ONLY: every layer adds itself, so the platform sees + the whole stack rather than only whoever spoke last. + """ + headers = { + "Authorization": f"Token {api_key}", + "Mem0-User-ID": user_id, + "X-Mem0-Client": _client_stack(), + } + source = os.getenv("MEM0_SOURCE", "").strip() + if source: + headers["X-Mem0-Source"] = source + application = os.getenv("MEM0_APPLICATION", "").strip() + if application: + headers["X-Application"] = application + return headers + + +def _client_stack() -> str: + """This SDK appended to any stack an outer layer already declared.""" + existing = os.getenv("MEM0_CLIENT_STACK", "").strip() + entries = [part.strip() for part in existing.split(",") if part.strip()] if existing else [] + return _bounded_stack(entries, f"mem0-python/{_sdk_version()}") + + class MemoryClient: """Client for interacting with the Mem0 API. @@ -129,19 +218,11 @@ class MemoryClient: self.client = client # Ensure the client has the correct base_url and headers self.client.base_url = httpx.URL(self.host) - self.client.headers.update( - { - "Authorization": f"Token {self.api_key}", - "Mem0-User-ID": self.user_id, - } - ) + _apply_client_headers(self.client, self.api_key, self.user_id) else: self.client = httpx.Client( base_url=self.host, - headers={ - "Authorization": f"Token {self.api_key}", - "Mem0-User-ID": self.user_id, - }, + headers=_client_headers(self.api_key, self.user_id), timeout=300, ) self.user_email = self._validate_api_key() @@ -1018,19 +1099,11 @@ class AsyncMemoryClient: self.async_client = client # Ensure the client has the correct base_url and headers self.async_client.base_url = httpx.URL(self.host) - self.async_client.headers.update( - { - "Authorization": f"Token {self.api_key}", - "Mem0-User-ID": self.user_id, - } - ) + _apply_client_headers(self.async_client, self.api_key, self.user_id) else: self.async_client = httpx.AsyncClient( base_url=self.host, - headers={ - "Authorization": f"Token {self.api_key}", - "Mem0-User-ID": self.user_id, - }, + headers=_client_headers(self.api_key, self.user_id), timeout=300, ) @@ -1053,10 +1126,7 @@ class AsyncMemoryClient: params = self._prepare_params() response = requests.get( f"{self.host}/v1/ping/", - headers={ - "Authorization": f"Token {self.api_key}", - "Mem0-User-ID": self.user_id, - }, + headers=_client_headers(self.api_key, self.user_id), params=params, ) response.raise_for_status() diff --git a/tests/test_client_surface_headers.py b/tests/test_client_surface_headers.py new file mode 100644 index 000000000..51d09d306 --- /dev/null +++ b/tests/test_client_surface_headers.py @@ -0,0 +1,63 @@ +"""Surface-identity headers, and that a client can be constructed at all. + +The construction test exists because it was not there: a signature change to +_bounded_stack missed the _client_stack call site, every MemoryClient(...) raised +TypeError, and the whole suite stayed green because nothing built one. +""" + +import os +from unittest.mock import patch + +from mem0.client.main import _bounded_stack, _client_headers, _client_stack + + +def test_a_client_can_be_constructed(): + from mem0 import MemoryClient + + # _validate_api_key normally populates org/project from the API response; + # stubbing it leaves them None, which a later accessor rejects. Set them the + # way a real validation would. This test is about construction reaching the + # header stage at all. + def _stub(self): + self.org_id, self.project_id = "org", "proj" + + with patch.object(MemoryClient, "_validate_api_key", _stub): + client = MemoryClient(api_key="m0-test") + + assert client.client.headers["X-Mem0-Client"].startswith("mem0-python/") + + +# AsyncMemoryClient is deliberately not constructed here: its validation path +# makes a real request to /v1/ping/, and a unit test that needs the network is +# worse than none. It shares _client_headers with the sync client, which is the +# code the construction test above actually guards. +def test_headers_carry_this_sdk(): + headers = _client_headers("m0-test", "u1") + assert headers["X-Mem0-Client"].startswith("mem0-python/") + + +def test_our_entry_survives_a_caller_that_already_filled_the_stack(): + # Appending first and trimming to four dropped exactly the entry the + # function exists to add. + stack = _bounded_stack(["a/1", "b/2", "c/3", "d/4"], "mem0-python/9.9.9") + + assert "mem0-python/9.9.9" in stack + assert len(stack.split(",")) <= 4 + + +def test_the_character_cap_drops_whole_entries_not_characters(): + long_entries = [f"{'n' * 90}/1.0", f"{'m' * 90}/1.0", "c/3"] + stack = _bounded_stack(long_entries, "mem0-python/9.9.9") + + assert len(stack) <= 200 + assert stack.endswith("mem0-python/9.9.9") + for entry in stack.split(","): + assert entry.strip().count("/") == 1, f"severed entry: {entry!r}" + + +def test_an_outer_stack_is_appended_to_not_replaced(): + with patch.dict(os.environ, {"MEM0_CLIENT_STACK": "openclaw/2.1.0"}): + stack = _client_stack() + + assert stack.startswith("openclaw/2.1.0") + assert "mem0-python/" in stack From a8d36343128c0410a3e71626b8edfd31f875bd17 Mon Sep 17 00:00:00 2001 From: Saket Aryan Date: Fri, 18 Sep 2026 14:13:22 +0530 Subject: [PATCH 19/61] fix(plugins): stop the TypeScript telemetry losing events and misattributing accounts (#7358) --- .github/workflows/opencode-plugin-checks.yml | 3 + .../typescript/src/telemetry.ts | 99 ++++++- .../typescript/tests/telemetry.test.ts | 247 ++++++++++++++++++ integrations/openclaw/cli/config-file.ts | 20 ++ integrations/openclaw/config.ts | 1 + integrations/openclaw/openclaw.plugin.json | 4 + integrations/openclaw/telemetry.ts | 64 ++++- .../openclaw/tests/config-file.test.ts | 40 +++ integrations/openclaw/tests/config.test.ts | 15 ++ integrations/openclaw/tests/telemetry.test.ts | 80 +++++- integrations/opencode-plugin/package.json | 1 + .../opencode-plugin/telemetry.test.ts | 51 +++- integrations/opencode-plugin/telemetry.ts | 27 +- 13 files changed, 623 insertions(+), 29 deletions(-) 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/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/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/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..02d05be4b 100644 --- a/integrations/openclaw/openclaw.plugin.json +++ b/integrations/openclaw/openclaw.plugin.json @@ -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/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/opencode-plugin/package.json b/integrations/opencode-plugin/package.json index 79f68c4a8..acdbaf469 100644 --- a/integrations/opencode-plugin/package.json +++ b/integrations/opencode-plugin/package.json @@ -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) }); } From 19f713408273fb1d657daa38d7b82ccf496d36d5 Mon Sep 17 00:00:00 2001 From: Saket Aryan Date: Fri, 18 Sep 2026 16:28:55 +0530 Subject: [PATCH 20/61] chore(release): bump every package the telemetry attribution work changed (#7373) Co-authored-by: kartik-mem0 --- .claude-plugin/marketplace.json | 2 +- .cursor-plugin/marketplace.json | 2 +- .kimi-plugin/marketplace.json | 2 +- cli/node/package.json | 2 +- cli/python/pyproject.toml | 2 +- cli/python/src/mem0_cli/__init__.py | 2 +- docs/changelog/sdk.mdx | 131 +++++++++++++----- .../agent-plugin-core/python/memory_core.py | 2 +- .../antigravity-plugin/core/memory_core.py | 2 +- .../antigravity-plugin/plugin-build.json | 2 +- .../.claude-plugin/plugin.json | 2 +- .../claude-code-plugin/core/memory_core.py | 2 +- .../claude-code-plugin/plugin-build.json | 2 +- .../tests/test_memory_core.py | 8 +- .../codex-plugin/.codex-plugin/plugin.json | 2 +- integrations/codex-plugin/core/memory_core.py | 2 +- integrations/codex-plugin/plugin-build.json | 2 +- .../cursor-plugin/.cursor-plugin/plugin.json | 2 +- .../cursor-plugin/core/memory_core.py | 2 +- integrations/cursor-plugin/plugin-build.json | 2 +- integrations/deepseek-plugin/package.json | 2 +- integrations/kimi-plugin/core/memory_core.py | 2 +- integrations/kimi-plugin/kimi.plugin.json | 2 +- integrations/kimi-plugin/plugin-build.json | 2 +- .../mem0-agent-plugin/core/memory_core.py | 2 +- integrations/mem0-agent-plugin/plugin.json | 2 +- integrations/openclaw/openclaw.plugin.json | 2 +- integrations/openclaw/package.json | 2 +- integrations/opencode-plugin/package.json | 2 +- integrations/pi-agent-plugin/package.json | 2 +- integrations/vercel-ai-sdk/package.json | 2 +- marketplace.json | 2 +- mem0-ts/package.json | 2 +- pyproject.toml | 2 +- 34 files changed, 135 insertions(+), 68 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index d46a19e49..ccaa4dcea 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.2" } ] } diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.json index 409b7d8fc..84f31855b 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.2" } ] } diff --git a/.kimi-plugin/marketplace.json b/.kimi-plugin/marketplace.json index 8ff2134b4..0b8cbcac0 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.2", "description": "Cross-session memory and token savings for coding agents.", "homepage": "https://mem0.ai", "keywords": ["memory", "personalization", "mcp", "semantic-search"], diff --git a/cli/node/package.json b/cli/node/package.json index d078066e2..b2f57b09f 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": { 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/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdx index 71fb7e1d8..50922493e 100644 --- a/docs/changelog/sdk.mdx +++ b/docs/changelog/sdk.mdx @@ -7,6 +7,14 @@ mode: "wide" + + +**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:** @@ -1227,6 +1235,14 @@ See the [OSS v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to- + + +**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 +1880,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 +2099,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 +2394,14 @@ 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:** +- **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 +2424,14 @@ 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:** +- **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 +2454,14 @@ 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:** +- **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 +2481,16 @@ 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) - - - - - + + +**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 +2589,14 @@ Sidekick is available only in Claude Code, not in the portable package. - + -Removes Sidekick. Memory capture, search, and six skills remain available. +**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 +2692,14 @@ 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:** +- **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 +2737,14 @@ Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skill + + +**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 +3033,13 @@ Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skill + + +**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 +3153,13 @@ Removes Sidekick and its start/stop hooks. Memory capture, recall, and six skill + + +**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 +3204,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/integrations/agent-plugin-core/python/memory_core.py b/integrations/agent-plugin-core/python/memory_core.py index d350e76d2..ea2670dac 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.2" _harness_name: str = "generic" _harness_env_prefix: str = "MEM0_PLUGIN" diff --git a/integrations/antigravity-plugin/core/memory_core.py b/integrations/antigravity-plugin/core/memory_core.py index d350e76d2..ea2670dac 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.2" _harness_name: str = "generic" _harness_env_prefix: str = "MEM0_PLUGIN" diff --git a/integrations/antigravity-plugin/plugin-build.json b/integrations/antigravity-plugin/plugin-build.json index ac65c4bea..43b90d8cb 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.2", "homepage": "https://docs.mem0.ai/integrations/antigravity", "native": { "pluginRoot": "${ANTIGRAVITY_PLUGIN_ROOT}", diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index 6f214cc14..0dd8298e9 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.2", "description": "Cross-session memory and token savings for coding agents.", "author": { "name": "Mem0" diff --git a/integrations/claude-code-plugin/core/memory_core.py b/integrations/claude-code-plugin/core/memory_core.py index d350e76d2..ea2670dac 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.2" _harness_name: str = "generic" _harness_env_prefix: str = "MEM0_PLUGIN" diff --git a/integrations/claude-code-plugin/plugin-build.json b/integrations/claude-code-plugin/plugin-build.json index 68d306fd6..4b98c2919 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.2", "homepage": "https://docs.mem0.ai/integrations/claude-code", "native": { "pluginRoot": "${CLAUDE_PLUGIN_ROOT}", diff --git a/integrations/claude-code-plugin/tests/test_memory_core.py b/integrations/claude-code-plugin/tests/test_memory_core.py index 8c7017913..9aea939cf 100644 --- a/integrations/claude-code-plugin/tests/test_memory_core.py +++ b/integrations/claude-code-plugin/tests/test_memory_core.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import re import os import sqlite3 import subprocess @@ -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") diff --git a/integrations/codex-plugin/.codex-plugin/plugin.json b/integrations/codex-plugin/.codex-plugin/plugin.json index 916b72e66..0a80bf9e3 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.2", "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/memory_core.py b/integrations/codex-plugin/core/memory_core.py index d350e76d2..ea2670dac 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.2" _harness_name: str = "generic" _harness_env_prefix: str = "MEM0_PLUGIN" diff --git a/integrations/codex-plugin/plugin-build.json b/integrations/codex-plugin/plugin-build.json index 8d4c51c07..7f5fc94f6 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.2", "homepage": "https://docs.mem0.ai/integrations/codex", "native": { "pluginRoot": "${PLUGIN_ROOT}", diff --git a/integrations/cursor-plugin/.cursor-plugin/plugin.json b/integrations/cursor-plugin/.cursor-plugin/plugin.json index e33de76a2..a30f9ad9a 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.2", "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/memory_core.py b/integrations/cursor-plugin/core/memory_core.py index d350e76d2..ea2670dac 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.2" _harness_name: str = "generic" _harness_env_prefix: str = "MEM0_PLUGIN" diff --git a/integrations/cursor-plugin/plugin-build.json b/integrations/cursor-plugin/plugin-build.json index 279b3178c..30024586e 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.2", "homepage": "https://docs.mem0.ai/integrations/cursor", "native": { "pluginRoot": "${CURSOR_PLUGIN_ROOT}", diff --git a/integrations/deepseek-plugin/package.json b/integrations/deepseek-plugin/package.json index ea00bb9c5..2df84283c 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.1", "description": "Mem0 long-term memory as a native DeepSeek Harness (Cordis) plugin.", "type": "module", "license": "Apache-2.0", diff --git a/integrations/kimi-plugin/core/memory_core.py b/integrations/kimi-plugin/core/memory_core.py index d350e76d2..ea2670dac 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.2" _harness_name: str = "generic" _harness_env_prefix: str = "MEM0_PLUGIN" diff --git a/integrations/kimi-plugin/kimi.plugin.json b/integrations/kimi-plugin/kimi.plugin.json index 0d63501fe..e58bec328 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.2", "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..e73643eab 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.2", "homepage": "https://docs.mem0.ai/integrations/kimi", "native": { "pluginRoot": "${KIMI_PLUGIN_ROOT}", diff --git a/integrations/mem0-agent-plugin/core/memory_core.py b/integrations/mem0-agent-plugin/core/memory_core.py index d350e76d2..ea2670dac 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.2" _harness_name: str = "generic" _harness_env_prefix: str = "MEM0_PLUGIN" diff --git a/integrations/mem0-agent-plugin/plugin.json b/integrations/mem0-agent-plugin/plugin.json index 2cbaa99de..7a2baba80 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.2", "description": "Cross-session memory and token savings for coding agents.", "author": { "name": "Mem0", diff --git a/integrations/openclaw/openclaw.plugin.json b/integrations/openclaw/openclaw.plugin.json index 02d05be4b..9d4cacaf8 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.0", "kind": "memory", "skills": ["skills"], "commandAliases": [ diff --git a/integrations/openclaw/package.json b/integrations/openclaw/package.json index 03938e4da..49f49dbf4 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.0", "type": "module", "description": "Mem0 memory backend for OpenClaw — platform or self-hosted open-source", "license": "Apache-2.0", diff --git a/integrations/opencode-plugin/package.json b/integrations/opencode-plugin/package.json index acdbaf469..efcb60a28 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.0", "type": "module", "description": "Mem0 persistent memory plugin for OpenCode — add, search, and manage memories across sessions", "main": "dist/index.js", diff --git a/integrations/pi-agent-plugin/package.json b/integrations/pi-agent-plugin/package.json index d05673406..7ef9f822e 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.1", "type": "module", "description": "Mem0 memory extension for Pi Agent persistent, scoped, semantic memory across sessions and projects", "license": "Apache-2.0", diff --git a/integrations/vercel-ai-sdk/package.json b/integrations/vercel-ai-sdk/package.json index 7b417e460..1165c3f92 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", diff --git a/marketplace.json b/marketplace.json index eea48e2af..b1608c958 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.2" } ] } diff --git a/mem0-ts/package.json b/mem0-ts/package.json index 7697b2384..b0490dd2e 100644 --- a/mem0-ts/package.json +++ b/mem0-ts/package.json @@ -1,6 +1,6 @@ { "name": "mem0ai", - "version": "3.1.8", + "version": "3.2.0", "description": "The Memory Layer For Your AI Apps", "main": "./dist/index.js", "module": "./dist/index.mjs", diff --git a/pyproject.toml b/pyproject.toml index 587dac221..73c5cdf71 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "mem0ai" -version = "2.0.20" +version = "2.1.0" description = "Long-term memory for AI Agents" authors = [ { name = "Mem0", email = "support@mem0.ai" } From a39a802bbc93e85b820078cd3c4dbaf53af25dbe Mon Sep 17 00:00:00 2001 From: Himanshu <104683257+Himanshu-Sangshetti@users.noreply.github.com> Date: Fri, 18 Sep 2026 23:19:15 +0530 Subject: [PATCH 21/61] docs(cookbooks): Company Brain with Mem0 Platform + Supabase (#7309) --- docs/cookbooks/integrations/supabase.mdx | 388 +++++++++++++++++++++++ docs/docs.json | 3 +- docs/llms.txt | 1 + 3 files changed, 391 insertions(+), 1 deletion(-) create mode 100644 docs/cookbooks/integrations/supabase.mdx diff --git a/docs/cookbooks/integrations/supabase.mdx b/docs/cookbooks/integrations/supabase.mdx new file mode 100644 index 000000000..cf9b8c038 --- /dev/null +++ b/docs/cookbooks/integrations/supabase.mdx @@ -0,0 +1,388 @@ +--- +title: Build a Company Brain with Mem0 Platform and Supabase +description: "A step-by-step guide to a shared organizational memory: Mem0 Platform is the managed brain, Supabase is your system of record, and every agent taps it through 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/docs.json b/docs/docs.json index 4ca51fa24..7aecc007c 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -444,7 +444,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" ] }, { diff --git a/docs/llms.txt b/docs/llms.txt index 686835a0e..ce60e29f5 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -326,6 +326,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. From 17852dc648ed332aa62360de2eba4ff84ebf6ad9 Mon Sep 17 00:00:00 2001 From: "mintlify[bot]" <109931778+mintlify[bot]@users.noreply.github.com> Date: Tue, 22 Sep 2026 18:50:39 +0530 Subject: [PATCH 22/61] SEO & metadata audit: shorten supabase cookbook description (#7380) Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com> --- docs/cookbooks/integrations/supabase.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/cookbooks/integrations/supabase.mdx b/docs/cookbooks/integrations/supabase.mdx index cf9b8c038..60b102324 100644 --- a/docs/cookbooks/integrations/supabase.mdx +++ b/docs/cookbooks/integrations/supabase.mdx @@ -1,6 +1,6 @@ --- title: Build a Company Brain with Mem0 Platform and Supabase -description: "A step-by-step guide to a shared organizational memory: Mem0 Platform is the managed brain, Supabase is your system of record, and every agent taps it through the Mem0 MCP server." +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." --- From 8b38da9ab8f1e0347870abad662c8c26c07007f2 Mon Sep 17 00:00:00 2001 From: "mintlify[bot]" <109931778+mintlify[bot]@users.noreply.github.com> Date: Tue, 22 Sep 2026 18:51:03 +0530 Subject: [PATCH 23/61] Fix grammar & typos: SDK changelog v2.0.8 entry (#6716) Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com> --- docs/changelog/sdk.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdx index 50922493e..5562fbe1d 100644 --- a/docs/changelog/sdk.mdx +++ b/docs/changelog/sdk.mdx @@ -182,7 +182,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)) From a214ec37bcc6309b0332ac3e8a58b7fc717dfa19 Mon Sep 17 00:00:00 2001 From: Shahil kadia Date: Tue, 22 Sep 2026 19:01:33 +0530 Subject: [PATCH 24/61] fix(examples): migrate OSS Memory search/get_all calls to v3 filters API (#7300) Co-authored-by: Shahil Kadia --- examples/misc/movie_recommendation_grok3.py | 6 +++--- examples/misc/strands_agent_aws_elasticache_neptune.py | 6 +++--- examples/misc/vllm_example.py | 10 +++++----- 3 files changed, 11 insertions(+), 11 deletions(-) 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!") From fd8fd087ea551648897717ce7bca86acfee5b268 Mon Sep 17 00:00:00 2001 From: 88lin <431761794@qq.com> Date: Tue, 22 Sep 2026 21:55:51 +0800 Subject: [PATCH 25/61] docs(vectordbs/pinecone): document extra_params on the Python config table (#7222) --- docs/components/vectordbs/dbs/pinecone.mdx | 1 + 1 file changed, 1 insertion(+) 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` | From 5d38e3703ab58df2922fe900b772412e9ae1bcab Mon Sep 17 00:00:00 2001 From: Deshraj Yadav Date: Tue, 22 Sep 2026 07:22:54 -0700 Subject: [PATCH 26/61] chore: remove CLI_SPECIFICATION.md (#4578) Co-authored-by: Claude Opus 4.6 (1M context) Co-authored-by: kartik-mem0 --- cli/CLI_SPECIFICATION.md | 1613 -------------------------------------- 1 file changed, 1613 deletions(-) delete mode 100644 cli/CLI_SPECIFICATION.md 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 From f8082a7345dadd9e042ebbc40b57b1498c8f6d63 Mon Sep 17 00:00:00 2001 From: "mintlify[bot]" <109931778+mintlify[bot]@users.noreply.github.com> Date: Tue, 22 Sep 2026 20:06:21 +0530 Subject: [PATCH 27/61] Fix grammar & typos: API casing in template heading (#7410) Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com> --- docs/templates/api_reference_template.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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. From 8c02c425a53ea31bd0d493bbcf0ab22c1be3609d Mon Sep 17 00:00:00 2001 From: Kartik Date: Wed, 23 Sep 2026 19:35:25 +0530 Subject: [PATCH 28/61] fix(agent-plugins): match memo prompts and tool descriptions, release 0.3.3 (#7420) Co-authored-by: Claude --- .claude-plugin/marketplace.json | 2 +- .cursor-plugin/marketplace.json | 2 +- .kimi-plugin/marketplace.json | 2 +- docs/changelog/sdk.mdx | 84 +++++++++++++++++++ integrations/agent-plugin-core/README.md | 4 +- .../agent-plugin-core/python/mcp_server.py | 13 +-- .../agent-plugin-core/python/memory_core.py | 10 +-- .../skills/search/SKILL.md.tmpl | 8 +- .../typescript/src/lifecycle.ts | 7 +- .../typescript/src/prompts.ts | 10 +++ .../typescript/tests/prompts.test.ts | 31 +++++++ .../antigravity-plugin/core/mcp_server.py | 13 +-- .../antigravity-plugin/core/memory_core.py | 10 +-- .../antigravity-plugin/plugin-build.json | 2 +- .../antigravity-plugin/skills/search/SKILL.md | 8 +- .../.claude-plugin/plugin.json | 2 +- .../claude-code-plugin/agents/sidekick.md | 7 +- .../claude-code-plugin/core/mcp_server.py | 13 +-- .../claude-code-plugin/core/memory_core.py | 10 +-- .../claude-code-plugin/plugin-build.json | 2 +- .../claude-code-plugin/skills/search/SKILL.md | 8 +- .../tests/test_memory_core.py | 8 +- .../codex-plugin/.codex-plugin/plugin.json | 2 +- integrations/codex-plugin/core/mcp_server.py | 13 +-- integrations/codex-plugin/core/memory_core.py | 10 +-- integrations/codex-plugin/plugin-build.json | 2 +- .../codex-plugin/skills/search/SKILL.md | 8 +- .../cursor-plugin/.cursor-plugin/plugin.json | 2 +- integrations/cursor-plugin/core/mcp_server.py | 13 +-- .../cursor-plugin/core/memory_core.py | 10 +-- integrations/cursor-plugin/plugin-build.json | 2 +- .../cursor-plugin/skills/search/SKILL.md | 8 +- integrations/deepseek-plugin/package.json | 2 +- integrations/deepseek-plugin/src/index.ts | 12 ++- integrations/kimi-plugin/core/mcp_server.py | 13 +-- integrations/kimi-plugin/core/memory_core.py | 10 +-- integrations/kimi-plugin/kimi.plugin.json | 2 +- integrations/kimi-plugin/plugin-build.json | 2 +- .../kimi-plugin/skills/search/SKILL.md | 8 +- .../mem0-agent-plugin/core/mcp_server.py | 13 +-- .../mem0-agent-plugin/core/memory_core.py | 10 +-- integrations/mem0-agent-plugin/plugin.json | 2 +- .../mem0-agent-plugin/skills/search/SKILL.md | 8 +- integrations/openclaw/openclaw.plugin.json | 2 +- integrations/openclaw/package.json | 2 +- integrations/openclaw/tools/memory-search.ts | 5 +- integrations/opencode-plugin/opencode-mem0.ts | 11 +-- .../mem0-context-loader/SKILL.md | 24 +----- .../opencode-skills/mem0-search/SKILL.md | 7 +- integrations/opencode-plugin/package.json | 2 +- integrations/pi-agent-plugin/README.md | 2 +- integrations/pi-agent-plugin/package.json | 2 +- .../skills/context-loader/SKILL.md | 23 +---- .../pi-agent-plugin/src/memory/tools.ts | 10 +-- integrations/pi-agent-plugin/src/prompt.ts | 11 ++- marketplace.json | 2 +- 56 files changed, 262 insertions(+), 249 deletions(-) create mode 100644 integrations/agent-plugin-core/typescript/src/prompts.ts create mode 100644 integrations/agent-plugin-core/typescript/tests/prompts.test.ts diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index ccaa4dcea..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.2" + "version": "0.3.3" } ] } diff --git a/.cursor-plugin/marketplace.json b/.cursor-plugin/marketplace.json index 84f31855b..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.2" + "version": "0.3.3" } ] } diff --git a/.kimi-plugin/marketplace.json b/.kimi-plugin/marketplace.json index 0b8cbcac0..47c986c6c 100644 --- a/.kimi-plugin/marketplace.json +++ b/.kimi-plugin/marketplace.json @@ -5,7 +5,7 @@ { "id": "mem0", "displayName": "Mem0", - "version": "0.3.2", + "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/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdx index 5562fbe1d..008e58b9f 100644 --- a/docs/changelog/sdk.mdx +++ b/docs/changelog/sdk.mdx @@ -2394,6 +2394,17 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex + + +**Improvements:** +- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Sidekick:** Sidekick searches memories when earlier sessions could help, instead of before every answer ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420)) + + + **Improvements:** @@ -2424,6 +2435,16 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex + + +**Improvements:** +- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420)) + + + **Improvements:** @@ -2454,6 +2475,16 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex + + +**Improvements:** +- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420)) + + + **Improvements:** @@ -2483,6 +2514,15 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex + + +**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:** @@ -2589,6 +2629,16 @@ Initial release of the Mem0 plugin for Claude Code and Cursor, followed by Codex + + +**Improvements:** +- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420)) + + + **Improvements:** @@ -2692,6 +2742,16 @@ Existing memories written by the previous versions are not rewritten. If your me + + +**Improvements:** +- **Search:** The `search_memories` tool description no longer tells the agent to call it before answering anything that could depend on prior context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help, which reduces unnecessary searches ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Extraction:** Repository memory instructions are shorter. They no longer ask for a dedicated memory for each command that failed and was then fixed, and no longer carry separate rules against saving personal preferences or memories that only name the repository, branch, or directory ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Search skill:** `/search` no longer describes categories as best-effort labels or asks for a retry without the category ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Packaging:** `PLUGIN_VERSION` bumped to `0.3.3`, so the `mem0-plugin/` wire header and `plugin_version` telemetry field identify builds with these prompts ([#7420](https://github.com/mem0ai/mem0/pull/7420)) + + + **Improvements:** @@ -2737,6 +2797,13 @@ Existing memories written by the previous versions are not rewritten. If your me + + +**Improvements:** +- **Search:** The `memory_search` tool description no longer asks the agent to search proactively or to run several searches for multi-part questions. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help. Recall strategies (`smart`, `always`, `manual`) are unchanged ([#7420](https://github.com/mem0ai/mem0/pull/7420)) + + + **Changes:** @@ -3033,6 +3100,15 @@ Existing memories written by the previous versions are not rewritten. If your me + + +**Improvements:** +- **Search:** The memory policy, `mem0_memory` tool description, and prompt guidelines no longer ask the agent to search before answering anything that may depend on earlier context or to run several searches per question. They now ask for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Skills:** `context-loader` makes one search instead of 2-4 parallel searches, and uses the search skill description from the other coding-agent plugins ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Automatic recall:** Injected memories are introduced as "Mem0 found these relevant memories from earlier work in this repository:", the same heading as the Python plugins. The old heading called them a shallow first pass and told the agent to search again ([#7420](https://github.com/mem0ai/mem0/pull/7420)) + + + **Improvements:** @@ -3153,6 +3229,14 @@ Existing memories written by the previous versions are not rewritten. If your me + + +**Improvements:** +- **Search:** The `search_memory` tool description no longer asks the agent to search proactively before answering anything that may depend on earlier context. It now asks for a search before repeating investigation or when earlier decisions, fixes, commands, or results may help ([#7420](https://github.com/mem0ai/mem0/pull/7420)) +- **Automatic recall:** Injected memories are introduced as "Mem0 found these relevant memories from earlier work:". The old heading called them a shallow first pass and told the agent to search again with `mem0_memory`, a tool DeepSeek does not have ([#7420](https://github.com/mem0ai/mem0/pull/7420)) + + + **Improvements:** 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/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 ea2670dac..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.2" +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.""" 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/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/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/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 ea2670dac..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.2" +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.""" diff --git a/integrations/antigravity-plugin/plugin-build.json b/integrations/antigravity-plugin/plugin-build.json index 43b90d8cb..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.2", + "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 0dd8298e9..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.2", + "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/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 ea2670dac..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.2" +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.""" diff --git a/integrations/claude-code-plugin/plugin-build.json b/integrations/claude-code-plugin/plugin-build.json index 4b98c2919..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.2", + "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 9aea939cf..b6b1c28f9 100644 --- a/integrations/claude-code-plugin/tests/test_memory_core.py +++ b/integrations/claude-code-plugin/tests/test_memory_core.py @@ -1,8 +1,8 @@ from __future__ import annotations import json -import re import os +import re import sqlite3 import subprocess import sys @@ -2307,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 @@ -4333,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 0a80bf9e3..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.2", + "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/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 ea2670dac..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.2" +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.""" diff --git a/integrations/codex-plugin/plugin-build.json b/integrations/codex-plugin/plugin-build.json index 7f5fc94f6..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.2", + "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 a30f9ad9a..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.2", + "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/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 ea2670dac..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.2" +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.""" diff --git a/integrations/cursor-plugin/plugin-build.json b/integrations/cursor-plugin/plugin-build.json index 30024586e..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.2", + "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 2df84283c..41a8fe7a5 100644 --- a/integrations/deepseek-plugin/package.json +++ b/integrations/deepseek-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@mem0/deepseek-plugin", - "version": "0.3.1", + "version": "0.3.2", "description": "Mem0 long-term memory as a native DeepSeek Harness (Cordis) plugin.", "type": "module", "license": "Apache-2.0", diff --git a/integrations/deepseek-plugin/src/index.ts b/integrations/deepseek-plugin/src/index.ts index 3ac86f4b0..c5eb64390 100644 --- a/integrations/deepseek-plugin/src/index.ts +++ b/integrations/deepseek-plugin/src/index.ts @@ -21,6 +21,11 @@ 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"]; @@ -107,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); @@ -197,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/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 ea2670dac..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.2" +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.""" diff --git a/integrations/kimi-plugin/kimi.plugin.json b/integrations/kimi-plugin/kimi.plugin.json index e58bec328..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.2", + "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 e73643eab..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.2", + "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/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 ea2670dac..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.2" +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.""" diff --git a/integrations/mem0-agent-plugin/plugin.json b/integrations/mem0-agent-plugin/plugin.json index 7a2baba80..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.2", + "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/openclaw/openclaw.plugin.json b/integrations/openclaw/openclaw.plugin.json index 9d4cacaf8..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.2.0", + "version": "1.2.1", "kind": "memory", "skills": ["skills"], "commandAliases": [ diff --git a/integrations/openclaw/package.json b/integrations/openclaw/package.json index 49f49dbf4..39aaeb70e 100644 --- a/integrations/openclaw/package.json +++ b/integrations/openclaw/package.json @@ -1,6 +1,6 @@ { "name": "@mem0/openclaw-mem0", - "version": "1.2.0", + "version": "1.2.1", "type": "module", "description": "Mem0 memory backend for OpenClaw — platform or self-hosted open-source", "license": "Apache-2.0", 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 efcb60a28..36c3dce6b 100644 --- a/integrations/opencode-plugin/package.json +++ b/integrations/opencode-plugin/package.json @@ -1,6 +1,6 @@ { "name": "@mem0/opencode-plugin", - "version": "0.4.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", 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 7ef9f822e..fbec4db1b 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.1", + "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", 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/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/marketplace.json b/marketplace.json index b1608c958..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.2" + "version": "0.3.3" } ] } From 83b07b1537d688b9687bb116f8e0c6a9cabf2d95 Mon Sep 17 00:00:00 2001 From: "mintlify[bot]" <109931778+mintlify[bot]@users.noreply.github.com> Date: Wed, 23 Sep 2026 19:53:11 +0530 Subject: [PATCH 29/61] Fix grammar & typos: minor fixes across docs (#7423) Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com> --- docs/components/embedders/models/together.mdx | 2 +- docs/components/vectordbs/dbs/azure.mdx | 2 +- docs/cookbooks/integrations/healthcare-google-adk.mdx | 2 +- docs/integrations/llama-index.mdx | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) 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/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/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 = { From 0cddc36d524ac6f54228e6355048adb936b436c3 Mon Sep 17 00:00:00 2001 From: Brennan <31714723+BCathcart@users.noreply.github.com> Date: Wed, 23 Sep 2026 10:02:04 -0700 Subject: [PATCH 30/61] Protect against None timestamps in Valkey layer (#6993) Signed-off-by: Brennan Cathcart --- mem0/vector_stores/valkey.py | 20 +++++--------------- tests/vector_stores/test_valkey.py | 26 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/mem0/vector_stores/valkey.py b/mem0/vector_stores/valkey.py index 0688a1288..189285539 100644 --- a/mem0/vector_stores/valkey.py +++ b/mem0/vector_stores/valkey.py @@ -299,13 +299,8 @@ class ValkeyDB(VectorStoreBase): # Create the key for the hash key = f"{self.prefix}:{id}" - # Check for required fields and provide defaults if missing - if "data" not in payload: - # Silently use default value for missing 'data' field - pass - - # Ensure created_at is present - if "created_at" not in payload: + # Default created_at when missing or None to current time + if not payload.get("created_at"): payload["created_at"] = datetime.now(pytz.timezone(self.timezone)).isoformat() # Prepare the hash data @@ -499,13 +494,8 @@ class ValkeyDB(VectorStoreBase): try: key = f"{self.prefix}:{vector_id}" - # Check for required fields and provide defaults if missing - if "data" not in payload: - # Silently use default value for missing 'data' field - pass - - # Ensure created_at is present - if "created_at" not in payload: + # Default created_at when missing or None to current time + if not payload.get("created_at"): payload["created_at"] = datetime.now(pytz.timezone(self.timezone)).isoformat() # Prepare the hash data @@ -521,7 +511,7 @@ class ValkeyDB(VectorStoreBase): hash_data["embedding"] = np.array(vector, dtype=np.float32).tobytes() # Add updated_at if available - if "updated_at" in payload: + if payload.get("updated_at"): hash_data["updated_at"] = int(datetime.fromisoformat(payload["updated_at"]).timestamp()) # Add optional fields diff --git a/tests/vector_stores/test_valkey.py b/tests/vector_stores/test_valkey.py index 769f511d4..b42a54848 100644 --- a/tests/vector_stores/test_valkey.py +++ b/tests/vector_stores/test_valkey.py @@ -158,6 +158,32 @@ def test_insert_handles_missing_created_at(valkey_db, mock_valkey_client): assert "created_at" in kwargs["mapping"] # Should be added automatically +def test_insert_and_update_with_none_timestamps(valkey_db, mock_valkey_client): + """Regression: a None timestamp must not crash insert() or update(). + + A None created_at falls back to now and a None updated_at is skipped, so + neither reaches fromisoformat() which only accepts a str. + """ + vector = np.random.rand(1536).tolist() + + valkey_db.insert( + vectors=[vector], + payloads=[{"hash": "h", "data": "d", "created_at": None, "updated_at": None}], + ids=["id1"], + ) + _, insert_kwargs = mock_valkey_client.hset.call_args + assert isinstance(insert_kwargs["mapping"]["created_at"], int) + + valkey_db.update( + vector_id="id1", + vector=vector, + payload={"hash": "h", "data": "d", "created_at": None, "updated_at": None}, + ) + _, update_kwargs = mock_valkey_client.hset.call_args + assert isinstance(update_kwargs["mapping"]["created_at"], int) + assert "updated_at" not in update_kwargs["mapping"] + + def test_delete(valkey_db, mock_valkey_client): """Test deleting a vector.""" # Call delete From ea9bbcabed98418a1800c104aade8975e6460a04 Mon Sep 17 00:00:00 2001 From: Karthik Date: Thu, 24 Sep 2026 00:11:22 +0530 Subject: [PATCH 31/61] =?UTF-8?q?feat(profiles):=20User=20Profiles=20v1=20?= =?UTF-8?q?=E2=80=94=20SDK=20methods=20+=20docs=20(#7340)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Pratik <10096516+pratikgajjar@users.noreply.github.com> Co-authored-by: Claude Opus 4.8 (1M context) --- .../profiles/generate-profiles.mdx | 5 + .../profiles/get-profile-job.mdx | 5 + .../profiles/get-profile-settings.mdx | 5 + docs/api-reference/profiles/get-profile.mdx | 5 + .../profiles/update-profile-settings.mdx | 5 + docs/changelog/sdk.mdx | 14 + docs/docs.json | 12 + docs/llms.txt | 6 + docs/openapi.json | 476 ++++++++++- docs/platform/features/user-profiles.mdx | 359 ++++++++ examples/notebooks/user-profiles.ipynb | 764 ++++++++++++++++++ mem0-ts/package.json | 2 +- mem0-ts/src/client/index.ts | 8 + mem0-ts/src/client/mem0.ts | 206 ++++- mem0-ts/src/client/mem0.types.ts | 95 +++ .../tests/memoryClient.profiles.test.ts | 341 ++++++++ mem0-ts/src/client/utils.ts | 3 + mem0/client/main.py | 384 ++++++++- pyproject.toml | 2 +- tests/test_client_profiles.py | 272 +++++++ 20 files changed, 2961 insertions(+), 8 deletions(-) create mode 100644 docs/api-reference/profiles/generate-profiles.mdx create mode 100644 docs/api-reference/profiles/get-profile-job.mdx create mode 100644 docs/api-reference/profiles/get-profile-settings.mdx create mode 100644 docs/api-reference/profiles/get-profile.mdx create mode 100644 docs/api-reference/profiles/update-profile-settings.mdx create mode 100644 docs/platform/features/user-profiles.mdx create mode 100644 examples/notebooks/user-profiles.ipynb create mode 100644 mem0-ts/src/client/tests/memoryClient.profiles.test.ts create mode 100644 tests/test_client_profiles.py 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 008e58b9f..bf53c5d31 100644 --- a/docs/changelog/sdk.mdx +++ b/docs/changelog/sdk.mdx @@ -7,6 +7,13 @@ mode: "wide" + + +**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)) + + + **Improvements:** @@ -1235,6 +1242,13 @@ See the [OSS v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to- + + +**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:** diff --git a/docs/docs.json b/docs/docs.json index 7aecc007c..969ebad35 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -72,6 +72,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", @@ -513,6 +514,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", diff --git a/docs/llms.txt b/docs/llms.txt index ce60e29f5..2a939cbe3 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -198,6 +198,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. @@ -364,6 +365,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/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/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/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/mem0-ts/package.json b/mem0-ts/package.json index b0490dd2e..3bb996079 100644 --- a/mem0-ts/package.json +++ b/mem0-ts/package.json @@ -1,6 +1,6 @@ { "name": "mem0ai", - "version": "3.2.0", + "version": "3.3.0", "description": "The Memory Layer For Your AI Apps", "main": "./dist/index.js", "module": "./dist/index.mjs", 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 33e03f0c2..0f8725164 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, @@ -92,6 +99,9 @@ interface ClientIdentity { } // Shares one ping per (host, api key) across clients; FIFO-capped. +// One collection for every generation; the operation is a body field. +const PROFILE_JOBS_PATH = "/v2/profiles/jobs/"; + const IDENTITY_CACHE_MAX_DEFAULT = 50; const identityByCredentials = new Map>(); @@ -305,7 +315,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: { @@ -318,8 +329,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( @@ -816,6 +830,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 cbe541321..606cf0daf 100644 --- a/mem0-ts/src/client/mem0.types.ts +++ b/mem0-ts/src/client/mem0.types.ts @@ -239,3 +239,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.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/client/main.py b/mem0/client/main.py index 3a82d9e5a..d65d4f0b1 100644 --- a/mem0/client/main.py +++ b/mem0/client/main.py @@ -1,6 +1,7 @@ import hashlib import logging import os +import uuid import warnings from typing import Any, Dict, List, Optional from urllib.parse import quote @@ -39,6 +40,43 @@ setup_config() # Entity parameters that must be passed via filters, not top-level ENTITY_PARAMS = frozenset({"user_id", "agent_id", "app_id", "run_id"}) +# One collection for every generation; the operation is a body field. +PROFILE_JOBS_PATH = "/v2/profiles/jobs/" +PROFILE_SETTINGS_PATH = "/v2/profiles/settings/" + +# Distinguishes an omitted argument from an explicit ``None`` that clears a field. +_UNSET: Any = object() + + +def _profile_settings_payload( + enabled: Optional[bool], + schema: Any = _UNSET, + custom_instructions: Any = _UNSET, +) -> Dict[str, Any]: + """Build the settings body the API accepts. + + ``schema`` and ``custom_instructions`` are per user and nest under + ``entities``; only ``enabled`` is project-wide. This mirrors what + ``get_profile_settings`` returns, so the two round-trip. + + Sending them flat is rejected with ``Unsupported settings``, so this shape is + not cosmetic. ``_UNSET`` leaves a field unchanged; an explicit ``None`` clears it. + """ + + payload: Dict[str, Any] = {} + if enabled is not None: + payload["enabled"] = enabled + + entity_settings: Dict[str, Any] = {} + if schema is not _UNSET: + entity_settings["schema"] = schema + if custom_instructions is not _UNSET: + entity_settings["custom_instructions"] = custom_instructions + + if entity_settings: + payload["entities"] = {"user": entity_settings} + return payload + def _validate_and_trim_search_query(query: str) -> str: if not isinstance(query, str): @@ -452,7 +490,9 @@ class MemoryClient: payload = {k: v for k, v in payload.items() if v is not None or k == "expiration_date"} if not payload: - raise ValueError("At least one of text, metadata, timestamp, or expiration_date must be provided for update.") + raise ValueError( + "At least one of text, metadata, timestamp, or expiration_date must be provided for update." + ) capture_client_event("client.update", self, {"memory_id": memory_id, "sync_type": "sync"}) params = self._prepare_params() @@ -763,6 +803,174 @@ class MemoryClient: capture_client_event("client.get_summary", self, {"sync_type": "sync"}) return response.json() + @api_error_handler + def get_profile(self, entity_id: str) -> Dict[str, Any]: + """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. + + Args: + entity_id: The user's id, as you supplied it on ``add`` (e.g. "alice"). + + Returns: + Dict with ``profile``, ``status``, ``entity_type``, ``entity_id``, + ``updated_at`` and ``generation_count``. ``status`` is one of + "succeeded", "pending", "failed", "not_enabled" or "insufficient_data". + + Raises: + AuthenticationError: If authentication fails. + NotFoundError: If no such user exists in the project. + """ + + response = self.client.get(f"/v2/entities/user/{_encode_path_segment(entity_id)}/profile/") + response.raise_for_status() + capture_client_event("client.get_profile", self, {"sync_type": "sync"}) + return response.json() + + @api_error_handler + def generate_profile(self, entity_id: str, idempotency_key: Optional[str] = None) -> Dict[str, Any]: + """Generate or refresh the profile for a single 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 :meth:`get_profile` and branch on ``status``. + + Args: + entity_id: The user's id, as you supplied it on ``add``. + idempotency_key: Optional key that makes the create idempotent. Reuse + the same value to safely retry a lost request without starting + (and being billed for) a second job. A fresh key is generated when + omitted. + + Returns: + Dict containing ``job_id``, ``status``, ``status_url``, ``operation``, + ``entity_type``, ``entity_count_reserved``, ``event_id`` and + ``replayed``. Poll :meth:`get_profile` and branch on ``status``. + + Raises: + ValidationError: If profiles are not enabled and configured for the + project. + NotFoundError: If no such user exists in the project. + """ + + response = self.client.post( + PROFILE_JOBS_PATH, + json={"operation": "trigger", "entity_type": "user", "entity_id": entity_id}, + headers={"Idempotency-Key": idempotency_key or uuid.uuid4().hex}, + ) + response.raise_for_status() + capture_client_event("client.generate_profile", self, {"sync_type": "sync"}) + return response.json() + + @api_error_handler + def get_profile_settings(self) -> Dict[str, Any]: + """Get the profile settings for the current project. + + Returns: + Dict with ``enabled`` and ``capabilities`` at the top level, and + ``entities`` holding each entity type's ``schema`` and + ``custom_instructions``. + """ + + response = self.client.get(PROFILE_SETTINGS_PATH) + response.raise_for_status() + capture_client_event("client.get_profile_settings", self, {"sync_type": "sync"}) + return response.json() + + @api_error_handler + def update_profile_settings( + self, + enabled: Optional[bool] = None, + schema: Any = _UNSET, + custom_instructions: Any = _UNSET, + ) -> Dict[str, Any]: + """Update the profile settings for the current project. + + Only the arguments you pass are written. + + Args: + enabled: Turn profile generation on or off. Project-wide. + schema: JSON Schema for the profile. Every property needs a + ``description``. Pass ``None`` to clear it; omit to leave it + unchanged. Applies to user profiles. + custom_instructions: Extra guidance for the extraction step. Pass + ``None`` to clear it; omit to leave it unchanged. Applies to user + profiles. + + Returns: + Dict with the settings as stored after the update, in the same + shape :meth:`get_profile_settings` returns. + + Raises: + ValidationError: If the schema is not a valid profile schema. + """ + + payload = _profile_settings_payload(enabled, schema, custom_instructions) + response = self.client.post(PROFILE_SETTINGS_PATH, json=payload) + response.raise_for_status() + capture_client_event( + "client.update_profile_settings", + self, + {"keys": list(payload.keys()), "sync_type": "sync"}, + ) + return response.json() + + @api_error_handler + def sample_profiles(self, limit: Optional[int] = None, idempotency_key: Optional[str] = None) -> Dict[str, Any]: + """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. + + Args: + limit: How many users to sample, 1-10. Defaults to the server value. + idempotency_key: Optional key that makes the create idempotent. Reuse + the same value to safely retry without starting a second sample + run. A fresh key is generated when omitted. + + Returns: + Dict containing ``job_id``, ``status``, ``status_url``, ``sampled`` + and the ``entity_ids`` that were picked. Poll + :meth:`get_profile_job` with ``status_url`` until the status is terminal. + + Raises: + ValidationError: If profiles are not enabled and configured. + RateLimitError: If a sample run was already started very recently. + """ + + payload = self._prepare_params({"limit": limit}) + payload["operation"] = "sample" + payload["entity_type"] = "user" + response = self.client.post( + PROFILE_JOBS_PATH, + json=payload, + headers={"Idempotency-Key": idempotency_key or uuid.uuid4().hex}, + ) + response.raise_for_status() + capture_client_event("client.sample_profiles", self, {"sync_type": "sync"}) + return response.json() + + @api_error_handler + def get_profile_job(self, job_id_or_status_url: str) -> Dict[str, Any]: + """Read one generation job. + + Accepts the ``status_url`` from a create call, or a bare job id. Prefer + passing ``status_url`` so a route change needs no client update. + + Returns: + Dict whose ``job`` key holds the job: ``status``, ``total``, + ``completed``, ``succeeded``, ``failed`` and ``skipped``. ``total`` is + null until ``enumeration_complete``. + """ + + path = job_id_or_status_url + if not path.startswith("/"): + path = f"{PROFILE_JOBS_PATH}{path}/" + response = self.client.get(path) + response.raise_for_status() + return response.json() + @api_error_handler def get_project(self, fields: Optional[List[str]] = None) -> Dict[str, Any]: """Get instructions or categories for the current project. @@ -1361,7 +1569,9 @@ class AsyncMemoryClient: payload = {k: v for k, v in payload.items() if v is not None or k == "expiration_date"} if not payload: - raise ValueError("At least one of text, metadata, timestamp, or expiration_date must be provided for update.") + raise ValueError( + "At least one of text, metadata, timestamp, or expiration_date must be provided for update." + ) capture_client_event("client.update", self, {"memory_id": memory_id, "sync_type": "async"}) params = self._prepare_params() @@ -1658,6 +1868,176 @@ class AsyncMemoryClient: capture_client_event("client.get_summary", self, {"sync_type": "async"}) return response.json() + @api_error_handler + async def get_profile(self, entity_id: str) -> Dict[str, Any]: + """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. + + Args: + entity_id: The user's id, as you supplied it on ``add`` (e.g. "alice"). + + Returns: + Dict with ``profile``, ``status``, ``entity_type``, ``entity_id``, + ``updated_at`` and ``generation_count``. ``status`` is one of + "succeeded", "pending", "failed", "not_enabled" or "insufficient_data". + + Raises: + AuthenticationError: If authentication fails. + NotFoundError: If no such user exists in the project. + """ + + response = await self.async_client.get(f"/v2/entities/user/{_encode_path_segment(entity_id)}/profile/") + response.raise_for_status() + capture_client_event("client.get_profile", self, {"sync_type": "async"}) + return response.json() + + @api_error_handler + async def generate_profile(self, entity_id: str, idempotency_key: Optional[str] = None) -> Dict[str, Any]: + """Generate or refresh the profile for a single 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 :meth:`get_profile` and branch on ``status``. + + Args: + entity_id: The user's id, as you supplied it on ``add``. + idempotency_key: Optional key that makes the create idempotent. Reuse + the same value to safely retry a lost request without starting + (and being billed for) a second job. A fresh key is generated when + omitted. + + Returns: + Dict containing ``job_id``, ``status``, ``status_url``, ``operation``, + ``entity_type``, ``entity_count_reserved``, ``event_id`` and + ``replayed``. Poll :meth:`get_profile` and branch on ``status``. + + Raises: + ValidationError: If profiles are not enabled and configured for the + project. + NotFoundError: If no such user exists in the project. + """ + + response = await self.async_client.post( + PROFILE_JOBS_PATH, + json={"operation": "trigger", "entity_type": "user", "entity_id": entity_id}, + headers={"Idempotency-Key": idempotency_key or uuid.uuid4().hex}, + ) + response.raise_for_status() + capture_client_event("client.generate_profile", self, {"sync_type": "async"}) + return response.json() + + @api_error_handler + async def get_profile_settings(self) -> Dict[str, Any]: + """Get the profile settings for the current project. + + Returns: + Dict with ``enabled`` and ``capabilities`` at the top level, and + ``entities`` holding each entity type's ``schema`` and + ``custom_instructions``. + """ + + response = await self.async_client.get(PROFILE_SETTINGS_PATH) + response.raise_for_status() + capture_client_event("client.get_profile_settings", self, {"sync_type": "async"}) + return response.json() + + @api_error_handler + async def update_profile_settings( + self, + enabled: Optional[bool] = None, + schema: Any = _UNSET, + custom_instructions: Any = _UNSET, + ) -> Dict[str, Any]: + """Update the profile settings for the current project. + + Only the arguments you pass are written. + + Args: + enabled: Turn profile generation on or off. Project-wide. + schema: JSON Schema for the profile. Every property needs a + ``description``. Pass ``None`` to clear it; omit to leave it + unchanged. Applies to user profiles. + custom_instructions: Extra guidance for the extraction step. Pass + ``None`` to clear it; omit to leave it unchanged. Applies to user + profiles. + + Returns: + Dict with the settings as stored after the update, in the same + shape :meth:`get_profile_settings` returns. + + Raises: + ValidationError: If the schema is not a valid profile schema. + """ + + payload = _profile_settings_payload(enabled, schema, custom_instructions) + response = await self.async_client.post(PROFILE_SETTINGS_PATH, json=payload) + response.raise_for_status() + capture_client_event( + "client.update_profile_settings", + self, + {"keys": list(payload.keys()), "sync_type": "async"}, + ) + return response.json() + + @api_error_handler + async def sample_profiles( + self, limit: Optional[int] = None, idempotency_key: Optional[str] = None + ) -> Dict[str, Any]: + """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. + + Args: + limit: How many users to sample, 1-10. Defaults to the server value. + idempotency_key: Optional key that makes the create idempotent. Reuse + the same value to safely retry without starting a second sample + run. A fresh key is generated when omitted. + + Returns: + Dict containing ``job_id``, ``status``, ``status_url``, ``sampled`` + and the ``entity_ids`` that were picked. Poll + :meth:`get_profile_job` with ``status_url`` until the status is terminal. + + Raises: + ValidationError: If profiles are not enabled and configured. + RateLimitError: If a sample run was already started very recently. + """ + + payload = self._prepare_params({"limit": limit}) + payload["operation"] = "sample" + payload["entity_type"] = "user" + response = await self.async_client.post( + PROFILE_JOBS_PATH, + json=payload, + headers={"Idempotency-Key": idempotency_key or uuid.uuid4().hex}, + ) + response.raise_for_status() + capture_client_event("client.sample_profiles", self, {"sync_type": "async"}) + return response.json() + + @api_error_handler + async def get_profile_job(self, job_id_or_status_url: str) -> Dict[str, Any]: + """Read one generation job. + + Accepts the ``status_url`` from a create call, or a bare job id. Prefer + passing ``status_url`` so a route change needs no client update. + + Returns: + Dict whose ``job`` key holds the job: ``status``, ``total``, + ``completed``, ``succeeded``, ``failed`` and ``skipped``. ``total`` is + null until ``enumeration_complete``. + """ + + path = job_id_or_status_url + if not path.startswith("/"): + path = f"{PROFILE_JOBS_PATH}{path}/" + response = await self.async_client.get(path) + response.raise_for_status() + return response.json() + @api_error_handler async def get_project(self, fields: Optional[List[str]] = None) -> Dict[str, Any]: """Get instructions or categories for the current project. diff --git a/pyproject.toml b/pyproject.toml index 73c5cdf71..ddb3d7153 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "mem0ai" -version = "2.1.0" +version = "2.2.0" description = "Long-term memory for AI Agents" authors = [ { name = "Mem0", email = "support@mem0.ai" } diff --git a/tests/test_client_profiles.py b/tests/test_client_profiles.py new file mode 100644 index 000000000..c2ea0eff3 --- /dev/null +++ b/tests/test_client_profiles.py @@ -0,0 +1,272 @@ +"""Tests for the MemoryClient profile methods. + +These assert request construction — path, verb, body — rather than echoing a +mocked response back. The profile payload itself is the customer's own JSON +Schema shape, so the tests also pin that the SDK passes it through untouched. +""" + +import asyncio +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + + +@pytest.fixture +def mock_memory_client(): + """A MemoryClient whose transport is mocked.""" + with patch("mem0.client.main.httpx.Client") as mock_httpx: + mock_http_client = MagicMock() + mock_http_client.get.return_value = MagicMock( + json=lambda: {"org_id": "org1", "project_id": "proj1", "user_email": "test@test.com"}, + raise_for_status=lambda: None, + ) + mock_httpx.return_value = mock_http_client + + with patch("mem0.client.main.capture_client_event"): + from mem0.client.main import MemoryClient + + client = MemoryClient(api_key="test-api-key") + # The constructor pings through this same mock; drop that call. + mock_http_client.get.reset_mock() + yield client + + +def _assert_job_call(post_mock, expected_json): + """One jobs collection, operation in the body, idempotency key per attempt.""" + post_mock.assert_called_once() + args, kwargs = post_mock.call_args + assert args[0] == "/v2/profiles/jobs/" + assert kwargs["json"] == expected_json + assert kwargs["headers"]["Idempotency-Key"] + + +def _mock_response(payload): + response = MagicMock() + response.json.return_value = payload + response.raise_for_status.return_value = None + return response + + +class TestGetProfile: + def test_reads_the_v2_entity_route(self, mock_memory_client): + mock_memory_client.client.get.return_value = _mock_response( + {"profile": {}, "status": "pending", "entity_type": "user", "entity_id": "alice"} + ) + + mock_memory_client.get_profile("alice") + + mock_memory_client.client.get.assert_called_once_with("/v2/entities/user/alice/profile/") + + def test_encodes_path_segments(self, mock_memory_client): + """An id with a slash must not open a new path segment.""" + mock_memory_client.client.get.return_value = _mock_response({"profile": {}, "status": "pending"}) + + mock_memory_client.get_profile("tenant/alice") + + mock_memory_client.client.get.assert_called_once_with("/v2/entities/user/tenant%2Falice/profile/") + + def test_returns_the_envelope_verbatim(self, mock_memory_client): + """The customer's schema keys reach the caller exactly as stored.""" + payload = { + "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, + } + mock_memory_client.client.get.return_value = _mock_response(payload) + + assert mock_memory_client.get_profile("alice") == payload + + +class TestGenerateProfile: + def test_posts_entity_type_and_id(self, mock_memory_client): + mock_memory_client.client.post.return_value = _mock_response( + {"job_id": "j1", "status": "QUEUED", "status_url": "/v2/profiles/jobs/j1/"} + ) + + mock_memory_client.generate_profile("alice") + + _assert_job_call( + mock_memory_client.client.post, + {"operation": "trigger", "entity_type": "user", "entity_id": "alice"}, + ) + + def test_reuses_caller_idempotency_key(self, mock_memory_client): + """A caller-supplied key lets a retry hit the same job instead of billing twice.""" + mock_memory_client.client.post.return_value = _mock_response({"job_id": "j1", "status": "QUEUED"}) + + mock_memory_client.generate_profile("alice", idempotency_key="retry-key-123") + + _, kwargs = mock_memory_client.client.post.call_args + assert kwargs["headers"]["Idempotency-Key"] == "retry-key-123" + + +class TestProfileSettings: + def test_get_reads_v2(self, mock_memory_client): + mock_memory_client.client.get.return_value = _mock_response( + {"enabled": True, "entities": {"user": {"schema": None, "custom_instructions": None}}} + ) + + mock_memory_client.get_profile_settings() + + mock_memory_client.client.get.assert_called_once_with("/v2/profiles/settings/") + + def test_update_sends_only_supplied_fields(self, mock_memory_client): + """A partial update must not blank the fields it never mentions.""" + mock_memory_client.client.post.return_value = _mock_response({"enabled": False}) + + mock_memory_client.update_profile_settings(enabled=False) + + mock_memory_client.client.post.assert_called_once_with( + "/v2/profiles/settings/", + json={"enabled": False}, + ) + + def test_update_nests_schema_under_entities(self, mock_memory_client): + """The API takes only ``enabled`` and ``entities`` at the top level. + + A flat body is rejected with ``Unsupported settings``, so this nesting is + what makes the call work at all. + """ + schema = {"type": "object", "properties": {"x": {"type": "string", "description": "d"}}} + mock_memory_client.client.post.return_value = _mock_response({"enabled": True}) + + mock_memory_client.update_profile_settings(enabled=True, schema=schema) + + _, kwargs = mock_memory_client.client.post.call_args + assert set(kwargs["json"]) == {"enabled", "entities"} + assert "schema" not in kwargs["json"] + + def test_update_targets_the_user_entity_type(self, mock_memory_client): + schema = {"type": "object", "properties": {"x": {"type": "string", "description": "d"}}} + mock_memory_client.client.post.return_value = _mock_response({"enabled": True}) + + mock_memory_client.update_profile_settings(schema=schema) + + _, kwargs = mock_memory_client.client.post.call_args + assert kwargs["json"] == {"entities": {"user": {"schema": schema}}} + + def test_update_passes_schema_verbatim(self, mock_memory_client): + schema = { + "type": "object", + "properties": { + "favorite_topics": { + "type": "array", + "description": "Topics the user returns to", + "items": {"type": "string"}, + } + }, + } + mock_memory_client.client.post.return_value = _mock_response({"enabled": True}) + + mock_memory_client.update_profile_settings(enabled=True, schema=schema, custom_instructions="Keep it durable") + + mock_memory_client.client.post.assert_called_once_with( + "/v2/profiles/settings/", + json={ + "enabled": True, + "entities": {"user": {"schema": schema, "custom_instructions": "Keep it durable"}}, + }, + ) + + def test_update_clears_fields_with_explicit_none(self, mock_memory_client): + """Explicit ``None`` clears a field; the sentinel default leaves it untouched.""" + mock_memory_client.client.post.return_value = _mock_response({"enabled": True}) + + mock_memory_client.update_profile_settings(schema=None, custom_instructions=None) + + _, kwargs = mock_memory_client.client.post.call_args + assert kwargs["json"] == {"entities": {"user": {"schema": None, "custom_instructions": None}}} + + +class TestSampleProfiles: + def test_sample_without_limit(self, mock_memory_client): + mock_memory_client.client.post.return_value = _mock_response({"sampled": 5, "entity_ids": []}) + + mock_memory_client.sample_profiles() + + _assert_job_call(mock_memory_client.client.post, {"operation": "sample", "entity_type": "user"}) + + def test_sample_with_limit(self, mock_memory_client): + mock_memory_client.client.post.return_value = _mock_response({"sampled": 3, "entity_ids": []}) + + mock_memory_client.sample_profiles(limit=3) + + _assert_job_call( + mock_memory_client.client.post, + {"operation": "sample", "limit": 3, "entity_type": "user"}, + ) + + +class TestAsyncClientParity: + """The async client must speak the same wire protocol as the sync one.""" + + @pytest.fixture + def async_client(self): + # AsyncMemoryClient validates the key synchronously, through requests. + validation = MagicMock() + validation.json.return_value = { + "org_id": "org1", + "project_id": "proj1", + "user_email": "test@test.com", + } + validation.raise_for_status.return_value = None + + with patch("mem0.client.main.httpx.AsyncClient") as mock_httpx: + mock_httpx.return_value = MagicMock() + with patch("mem0.client.main.requests.get", return_value=validation): + with patch("mem0.client.main.capture_client_event"): + from mem0.client.main import AsyncMemoryClient + + yield AsyncMemoryClient(api_key="test-api-key") + + def test_get_profile(self, async_client): + async_client.async_client.get = AsyncMock(return_value=_mock_response({"profile": {}, "status": "pending"})) + + asyncio.run(async_client.get_profile("alice")) + + async_client.async_client.get.assert_called_once_with("/v2/entities/user/alice/profile/") + + def test_generate_profile(self, async_client): + async_client.async_client.post = AsyncMock(return_value=_mock_response({"job_id": "j1", "status": "QUEUED"})) + + asyncio.run(async_client.generate_profile("alice")) + + _assert_job_call( + async_client.async_client.post, + {"operation": "trigger", "entity_type": "user", "entity_id": "alice"}, + ) + + def test_update_settings_partial(self, async_client): + async_client.async_client.post = AsyncMock(return_value=_mock_response({"enabled": True})) + + asyncio.run(async_client.update_profile_settings(enabled=True)) + + async_client.async_client.post.assert_called_once_with( + "/v2/profiles/settings/", + json={"enabled": True}, + ) + + def test_update_settings_nests_schema(self, async_client): + """The async client builds the same body as the sync one.""" + schema = {"type": "object", "properties": {"x": {"type": "string", "description": "d"}}} + async_client.async_client.post = AsyncMock(return_value=_mock_response({"enabled": True})) + + asyncio.run(async_client.update_profile_settings(enabled=True, schema=schema)) + + async_client.async_client.post.assert_called_once_with( + "/v2/profiles/settings/", + json={"enabled": True, "entities": {"user": {"schema": schema}}}, + ) + + def test_update_settings_clears_with_none(self, async_client): + async_client.async_client.post = AsyncMock(return_value=_mock_response({"enabled": True})) + + asyncio.run(async_client.update_profile_settings(custom_instructions=None)) + + async_client.async_client.post.assert_called_once_with( + "/v2/profiles/settings/", + json={"entities": {"user": {"custom_instructions": None}}}, + ) From 47a69e1e72dc562b6fdd49a9ef892229afc7508a Mon Sep 17 00:00:00 2001 From: Kartik Date: Thu, 24 Sep 2026 00:30:19 +0530 Subject: [PATCH 32/61] docs(changelog): add v2.2.1 entry for Valkey None-timestamps fix (#7425) --- docs/changelog/sdk.mdx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdx index bf53c5d31..3f4a64202 100644 --- a/docs/changelog/sdk.mdx +++ b/docs/changelog/sdk.mdx @@ -12,6 +12,9 @@ mode: "wide" **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)) + From 43849c6e9d4d773b83a8144b6373aedc67241a5d Mon Sep 17 00:00:00 2001 From: Kartik Date: Thu, 24 Sep 2026 17:53:29 +0530 Subject: [PATCH 33/61] feat(integrations): migrate and validate standalone Hermes Mem0 plugin (#7372) --- docs/integrations/hermes.mdx | 208 ++++--- docs/llms.txt | 2 +- integrations/AGENTS.md | 1 + integrations/hermes-plugin-mem0/.gitignore | 3 + integrations/hermes-plugin-mem0/LICENSE | 236 ++++++++ integrations/hermes-plugin-mem0/README.md | 131 ++++ integrations/hermes-plugin-mem0/__init__.py | 504 ++++++++++++++++ integrations/hermes-plugin-mem0/_backend.py | 336 +++++++++++ .../hermes-plugin-mem0/_openai_llm.py | 66 ++ .../hermes-plugin-mem0/_oss_providers.py | 53 ++ integrations/hermes-plugin-mem0/_setup.py | 567 ++++++++++++++++++ integrations/hermes-plugin-mem0/plugin.yaml | 5 + .../hermes-plugin-mem0/pyproject.toml | 17 + .../hermes-plugin-mem0/tests/smoke_hermes.py | 178 ++++++ .../hermes-plugin-mem0/tests/test_plugin.py | 286 +++++++++ server/requirements.txt | 2 +- 16 files changed, 2501 insertions(+), 94 deletions(-) create mode 100644 integrations/hermes-plugin-mem0/.gitignore create mode 100644 integrations/hermes-plugin-mem0/LICENSE create mode 100644 integrations/hermes-plugin-mem0/README.md create mode 100644 integrations/hermes-plugin-mem0/__init__.py create mode 100644 integrations/hermes-plugin-mem0/_backend.py create mode 100644 integrations/hermes-plugin-mem0/_openai_llm.py create mode 100644 integrations/hermes-plugin-mem0/_oss_providers.py create mode 100644 integrations/hermes-plugin-mem0/_setup.py create mode 100644 integrations/hermes-plugin-mem0/plugin.yaml create mode 100644 integrations/hermes-plugin-mem0/pyproject.toml create mode 100644 integrations/hermes-plugin-mem0/tests/smoke_hermes.py create mode 100644 integrations/hermes-plugin-mem0/tests/test_plugin.py diff --git a/docs/integrations/hermes.mdx b/docs/integrations/hermes.mdx index 26de7221c..f1d385144 100644 --- a/docs/integrations/hermes.mdx +++ b/docs/integrations/hermes.mdx @@ -1,9 +1,9 @@ --- title: Hermes Agent -description: "Add long-term memory to Hermes agents using Mem0 Platform, a self-hosted server, or local OSS mode with background fact extraction." +description: "Add persistent memory to Hermes Agent with Mem0 Cloud, a self-hosted server, or the in-process OSS SDK." --- -Add long-term memory to [Hermes Agent](https://github.com/NousResearch/hermes-agent), a self-improving AI agent CLI by Nous Research. Hermes has a pluggable memory system, and Mem0 is one of the supported providers. Once enabled, Mem0 learns facts from your conversations and surfaces relevant ones for the current question, without slowing down the chat. +Add long-term memory to [Hermes Agent](https://github.com/NousResearch/hermes-agent), a self-improving AI agent CLI by Nous Research. The [standalone Mem0 plugin](https://github.com/mem0ai/mem0/tree/main/integrations/hermes-plugin-mem0) learns facts from conversations and recalls relevant memories for the current question. You can run Mem0 in three ways: @@ -17,11 +17,15 @@ Hermes runs a built-in memory system (file-based `MEMORY.md` and `USER.md`) alon ### 1. Current-turn recall (bounded wait) -When you send a message, Hermes searches your stored memories for the current question and waits up to 3 seconds for results. If they arrive in time, they are injected into the system prompt so the model can see them. If the backend is slower, Hermes skips the injection and the model can still call `mem0_search` itself — so a slow backend never blocks a turn. +When you send a message, Hermes searches your stored memories for the current question and waits up to 3 seconds for results. If they arrive in time, they are injected into the system prompt so the model can see them. If the backend is slower, Hermes skips the injection and the model can still call `mem0_search` itself after the bounded recall wait. ### 2. Background fact extraction (sync) -Once the model finishes, Hermes sends the `(user message, assistant response)` pair to Mem0 in a background thread. Mem0 extracts facts automatically (for example, "user prefers Python" or "user works at Acme Corp"), so you never have to tell it what to remember. Each write is tagged with the gateway channel it came from. +Once the model finishes, the plugin sends the user message and assistant response to Mem0 in a background thread for fact extraction. Each write includes the agent identifier and gateway channel. + + + Automatic capture truncates each message to **450 characters by default in every mode**, preferring a sentence boundary. Adjust `sync_max_chars` for your model's context limit. Capture is best effort: if the previous sync is still running after a five-second wait, the next turn is skipped. Use `mem0_add` to store specific text verbatim. + ## 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/llms.txt b/docs/llms.txt index 2a939cbe3..12dbdd339 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -257,7 +257,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. diff --git a/integrations/AGENTS.md b/integrations/AGENTS.md index 221c8206f..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 | 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/server/requirements.txt b/server/requirements.txt index 33a11c55c..e42309ebd 100644 --- a/server/requirements.txt +++ b/server/requirements.txt @@ -3,7 +3,7 @@ uvicorn==0.34.0 pydantic[email]==2.10.4 mem0ai>=0.1.48 python-dotenv==1.2.2 -psycopg>=3.2.8 +psycopg[binary]>=3.2.8,<4.0.0 psycopg-pool>=3.2.6,<4.0.0 # Bundled LLM/embedder providers. Extend by adding the provider's package From f4acc89a298ac7573fcd50faf46a4bfa7aeedb15 Mon Sep 17 00:00:00 2001 From: Kartik Date: Thu, 24 Sep 2026 18:00:54 +0530 Subject: [PATCH 34/61] docs: remove memory types page and preserve redirects (#7437) --- docs/core-concepts/how-it-works.mdx | 4 +- docs/core-concepts/memory-types.mdx | 118 ------------------ docs/docs.json | 7 +- docs/integrations/camel-ai.mdx | 6 +- docs/llms.txt | 1 - docs/platform/overview.mdx | 4 +- docs/platform/platform-vs-oss.mdx | 2 +- docs/templates/feature_guide_template.mdx | 2 +- .../parameters_reference_template.mdx | 6 +- docs/vibecoding.mdx | 4 +- mem0-ts/src/client/mem0.types.ts | 2 + mem0/memory/main.py | 4 + 12 files changed, 24 insertions(+), 136 deletions(-) delete mode 100644 docs/core-concepts/memory-types.mdx 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-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 969ebad35..4371c1ffe 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", @@ -1033,7 +1032,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/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) 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/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/mem0-ts/src/client/mem0.types.ts b/mem0-ts/src/client/mem0.types.ts index 606cf0daf..a178f4529 100644 --- a/mem0-ts/src/client/mem0.types.ts +++ b/mem0-ts/src/client/mem0.types.ts @@ -125,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; diff --git a/mem0/memory/main.py b/mem0/memory/main.py index a8b159f14..ac75baa04 100644 --- a/mem0/memory/main.py +++ b/mem0/memory/main.py @@ -850,6 +850,8 @@ class Memory(MemoryBase): suggestion="Convert your input to a string, dictionary, or list of dictionaries." ) + # TODO: Remove procedural-memory support in a future breaking release. + # Remove memory_type and its helpers from Memory and AsyncMemory together. if agent_id is not None and memory_type == MemoryType.PROCEDURAL.value: results = self._create_procedural_memory(messages, metadata=processed_metadata, prompt=prompt) scale_threshold_notice = detect_scale_threshold_from_add_result(self, results) @@ -2502,6 +2504,8 @@ class AsyncMemory(MemoryBase): suggestion="Convert your input to a string, dictionary, or list of dictionaries." ) + # TODO: Remove procedural-memory support in a future breaking release. + # Remove memory_type and its helpers from Memory and AsyncMemory together. if agent_id is not None and memory_type == MemoryType.PROCEDURAL.value: results = await self._create_procedural_memory( messages, metadata=processed_metadata, prompt=prompt, llm=llm From 2c6ff619d12d8b8afad9b0be8731a973acd0d70a Mon Sep 17 00:00:00 2001 From: Diwakar Ray Yadav Date: Thu, 24 Sep 2026 22:16:31 +0545 Subject: [PATCH 35/61] fix(memory): exclude vector-store-rejected records from ADD results (#7066) --- mem0/memory/main.py | 56 ++++++++++---- tests/memory/test_main.py | 157 +++++++++++++++++++++++++++++++++++++- 2 files changed, 197 insertions(+), 16 deletions(-) diff --git a/mem0/memory/main.py b/mem0/memory/main.py index ac75baa04..05a55c876 100644 --- a/mem0/memory/main.py +++ b/mem0/memory/main.py @@ -22,7 +22,7 @@ from mem0.configs.prompts import ( PROCEDURAL_MEMORY_SYSTEM_PROMPT, generate_additive_extraction_prompt, ) -from mem0.exceptions import LLMError +from mem0.exceptions import LLMError, VectorStoreError from mem0.exceptions import ValidationError as Mem0ValidationError from mem0.memory.base import MemoryBase from mem0.memory.notices import ( @@ -1049,19 +1049,31 @@ class Memory(MemoryBase): all_ids = [r[0] for r in records] all_payloads = [r[3] for r in records] + # Only records confirmed to be stored make it into history, entity + # links, and the returned results — a record the store rejected must + # never be reported back as a successful ADD. + persisted_records = [] try: self.vector_store.insert( vectors=all_vectors, ids=all_ids, payloads=all_payloads, ) + persisted_records = records except Exception: # Fallback: insert one by one - for mid, vec, pay in zip(all_ids, all_vectors, all_payloads): + for rec in records: try: - self.vector_store.insert(vectors=[vec], ids=[mid], payloads=[pay]) + self.vector_store.insert(vectors=[rec[2]], ids=[rec[0]], payloads=[rec[3]]) + persisted_records.append(rec) except Exception as e: - logger.error(f"Failed to insert memory {mid}: {e}") + logger.error(f"Failed to insert memory {rec[0]}: {e}") + + if not persisted_records: + self.db.save_messages(messages, session_scope) + raise VectorStoreError( + f"Failed to insert any of the {len(records)} extracted memories into the vector store" + ) # Batch history history_records = [ @@ -1073,7 +1085,7 @@ class Memory(MemoryBase): "created_at": r[3].get("created_at"), "is_deleted": 0, } - for r in records + for r in persisted_records ] try: self.db.batch_add_history(history_records) @@ -1087,12 +1099,12 @@ class Memory(MemoryBase): # Phase 7: Batch entity linking try: - all_texts = [r[1] for r in records] + all_texts = [r[1] for r in persisted_records] all_entities = extract_entities_batch(all_texts) # 7a: Global dedup — collect unique entities across all memories global_entities = {} # normalized_key -> (entity_type, entity_text, set of memory_ids) - for idx, (memory_id, text, embedding, payload) in enumerate(records): + for idx, (memory_id, text, embedding, payload) in enumerate(persisted_records): entities = all_entities[idx] if idx < len(all_entities) else [] for entity_type, entity_text in entities: key = self._normalize_entity_text(entity_text) @@ -1196,7 +1208,7 @@ class Memory(MemoryBase): returned_memories = [ {"id": r[0], "memory": r[1], "event": "ADD"} - for r in records + for r in persisted_records ] keys, encoded_ids = process_telemetry_filters(filters) @@ -2709,6 +2721,10 @@ class AsyncMemory(MemoryBase): all_ids = [r[0] for r in records] all_payloads = [r[3] for r in records] + # Only records confirmed to be stored make it into history, entity + # links, and the returned results — a record the store rejected must + # never be reported back as a successful ADD. + persisted_records = [] try: await asyncio.to_thread( self.vector_store.insert, @@ -2716,12 +2732,22 @@ class AsyncMemory(MemoryBase): ids=all_ids, payloads=all_payloads, ) + persisted_records = records except Exception: - for mid, vec, pay in zip(all_ids, all_vectors, all_payloads): + for rec in records: try: - await asyncio.to_thread(self.vector_store.insert, vectors=[vec], ids=[mid], payloads=[pay]) + await asyncio.to_thread( + self.vector_store.insert, vectors=[rec[2]], ids=[rec[0]], payloads=[rec[3]] + ) + persisted_records.append(rec) except Exception as e: - logger.error(f"Failed to insert memory {mid} (async): {e}") + logger.error(f"Failed to insert memory {rec[0]} (async): {e}") + + if not persisted_records: + await asyncio.to_thread(self.db.save_messages, messages, session_scope) + raise VectorStoreError( + f"Failed to insert any of the {len(records)} extracted memories into the vector store" + ) # Batch history history_records = [ @@ -2733,7 +2759,7 @@ class AsyncMemory(MemoryBase): "created_at": r[3].get("created_at"), "is_deleted": 0, } - for r in records + for r in persisted_records ] try: await asyncio.to_thread(self.db.batch_add_history, history_records) @@ -2749,12 +2775,12 @@ class AsyncMemory(MemoryBase): # Phase 7: Batch entity linking try: - all_texts = [r[1] for r in records] + all_texts = [r[1] for r in persisted_records] all_entities = await asyncio.to_thread(extract_entities_batch, all_texts) # 7a: Global dedup global_entities = {} - for idx, (memory_id, text, embedding, payload) in enumerate(records): + for idx, (memory_id, text, embedding, payload) in enumerate(persisted_records): entities = all_entities[idx] if idx < len(all_entities) else [] for entity_type, entity_text in entities: key = self._normalize_entity_text(entity_text) @@ -2856,7 +2882,7 @@ class AsyncMemory(MemoryBase): returned_memories = [ {"id": r[0], "memory": r[1], "event": "ADD"} - for r in records + for r in persisted_records ] keys, encoded_ids = process_telemetry_filters(effective_filters) diff --git a/tests/memory/test_main.py b/tests/memory/test_main.py index cea7e3842..00d962c34 100644 --- a/tests/memory/test_main.py +++ b/tests/memory/test_main.py @@ -1,3 +1,4 @@ +import json import logging import time from datetime import datetime, timezone @@ -6,7 +7,7 @@ from unittest.mock import MagicMock, Mock import pytest -from mem0.exceptions import LLMError +from mem0.exceptions import LLMError, VectorStoreError from mem0.memory.main import AsyncMemory, Memory @@ -1178,3 +1179,157 @@ class TestAddPipelineEntityEmbeddingCountGuard: assert any("padding/truncating" in r.message for r in caplog.records), ( "expected count-mismatch warning was not emitted" ) + +class TestPartialInsertFailure: + """Records the vector store rejects must never be reported as successful ADDs (#6911).""" + + LLM_RESPONSE = json.dumps( + { + "memory": [ + {"text": "User's name is Aryan"}, + {"text": "User is allergic to penicillin"}, + {"text": "User works as an engineer"}, + ] + } + ) + + @pytest.fixture + def mock_memory(self, mocker): + mock_llm, _ = _setup_mocks(mocker) + + memory = Memory() + memory.config = mocker.MagicMock() + memory.config.custom_instructions = None + memory.config.custom_update_memory_prompt = None + memory.custom_instructions = None + memory.api_version = "v1.1" + memory.db.get_last_messages = MagicMock(return_value=[]) + memory.db.save_messages = MagicMock() + memory.db.batch_add_history = MagicMock() + memory.embedding_model.embed_batch = Mock(side_effect=lambda texts, action: [[0.1, 0.2, 0.3] for _ in texts]) + mocker.patch("mem0.memory.main.extract_entities_batch", return_value=[]) + mocker.patch("mem0.memory.main.capture_event") + + return memory + + def test_rejected_records_are_not_reported_as_add(self, mock_memory): + """A record rejected by the vector store must be absent from results and history.""" + poison = "User is allergic to penicillin" + real_insert = mock_memory.vector_store.insert + + def flaky_insert(vectors, ids, payloads): + if len(ids) > 1: + raise RuntimeError("batch insert rejected") + if payloads[0]["data"] == poison: + raise RuntimeError("record rejected by vector store") + return real_insert(vectors=vectors, ids=ids, payloads=payloads) + + mock_memory.vector_store.insert = Mock(side_effect=flaky_insert) + mock_memory.llm.generate_response.return_value = self.LLM_RESPONSE + + result = mock_memory._add_to_vector_store( + messages=[{"role": "user", "content": "My name is Aryan. I work as an engineer."}], + metadata={}, + filters={}, + infer=True, + ) + + assert [r["memory"] for r in result] == [ + "User's name is Aryan", + "User works as an engineer", + ] + assert all(r["event"] == "ADD" for r in result) + + history = mock_memory.db.batch_add_history.call_args.args[0] + assert {h["new_memory"] for h in history} == { + "User's name is Aryan", + "User works as an engineer", + } + + def test_all_inserts_failed_raises_vector_store_error(self, mock_memory): + """If nothing persisted, add() must raise VectorStoreError instead of reporting success.""" + mock_memory.vector_store.insert = Mock(side_effect=RuntimeError("vector store down")) + mock_memory.llm.generate_response.return_value = self.LLM_RESPONSE + + with pytest.raises(VectorStoreError, match="Failed to insert any"): + mock_memory._add_to_vector_store( + messages=[{"role": "user", "content": "test"}], + metadata={}, + filters={}, + infer=True, + ) + + # Raw messages are still saved so a later retry can re-extract them. + mock_memory.db.save_messages.assert_called_once() + + +@pytest.mark.asyncio +class TestAsyncPartialInsertFailure: + """Async mirror of TestPartialInsertFailure (#6911).""" + + LLM_RESPONSE = TestPartialInsertFailure.LLM_RESPONSE + + @pytest.fixture + def mock_async_memory(self, mocker): + mock_llm, _ = _setup_mocks(mocker) + + memory = AsyncMemory() + memory.config = mocker.MagicMock() + memory.config.custom_instructions = None + memory.config.custom_update_memory_prompt = None + memory.custom_instructions = None + memory.api_version = "v1.1" + memory.db.get_last_messages = MagicMock(return_value=[]) + memory.db.save_messages = MagicMock() + memory.db.batch_add_history = MagicMock() + memory.embedding_model.embed_batch = Mock(side_effect=lambda texts, action: [[0.1, 0.2, 0.3] for _ in texts]) + mocker.patch("mem0.memory.main.extract_entities_batch", return_value=[]) + mocker.patch("mem0.memory.main.capture_event") + + return memory + + async def test_rejected_records_are_not_reported_as_add(self, mock_async_memory): + poison = "User is allergic to penicillin" + real_insert = mock_async_memory.vector_store.insert + + def flaky_insert(vectors, ids, payloads): + if len(ids) > 1: + raise RuntimeError("batch insert rejected") + if payloads[0]["data"] == poison: + raise RuntimeError("record rejected by vector store") + return real_insert(vectors=vectors, ids=ids, payloads=payloads) + + mock_async_memory.vector_store.insert = Mock(side_effect=flaky_insert) + mock_async_memory.llm.generate_response.return_value = self.LLM_RESPONSE + + result = await mock_async_memory._add_to_vector_store( + messages=[{"role": "user", "content": "My name is Aryan. I work as an engineer."}], + metadata={}, + effective_filters={}, + infer=True, + ) + + assert [r["memory"] for r in result] == [ + "User's name is Aryan", + "User works as an engineer", + ] + + history = mock_async_memory.db.batch_add_history.call_args.args[0] + assert {h["new_memory"] for h in history} == { + "User's name is Aryan", + "User works as an engineer", + } + + async def test_all_inserts_failed_raises_vector_store_error(self, mock_async_memory): + mock_async_memory.vector_store.insert = Mock(side_effect=RuntimeError("vector store down")) + mock_async_memory.llm.generate_response.return_value = self.LLM_RESPONSE + + with pytest.raises(VectorStoreError, match="Failed to insert any"): + await mock_async_memory._add_to_vector_store( + messages=[{"role": "user", "content": "test"}], + metadata={}, + effective_filters={}, + infer=True, + ) + + mock_async_memory.db.save_messages.assert_called_once() From d675cf68adea399b475b71b38832361c34a432c8 Mon Sep 17 00:00:00 2001 From: Mohd Quamar Tyagi <104281681+Tyagiquamar@users.noreply.github.com> Date: Thu, 24 Sep 2026 22:04:57 +0530 Subject: [PATCH 36/61] fix(memory): restore Memory and AsyncMemory context-manager protocol (#7354) --- mem0/memory/main.py | 14 ++++++++++++++ tests/test_telemetry.py | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+) diff --git a/mem0/memory/main.py b/mem0/memory/main.py index 05a55c876..e750edbf1 100644 --- a/mem0/memory/main.py +++ b/mem0/memory/main.py @@ -2179,6 +2179,13 @@ class Memory(MemoryBase): self.db.close() self.db = None + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.close() + return False + def chat(self, query): raise NotImplementedError("Chat function not implemented yet.") @@ -3894,5 +3901,12 @@ class AsyncMemory(MemoryBase): self.db.close() self.db = None + async def __aenter__(self): + return self + + async def __aexit__(self, exc_type, exc_val, exc_tb): + self.close() + return False + async def chat(self, query): raise NotImplementedError("Chat function not implemented yet.") diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py index fb7001a62..7c1df5c01 100644 --- a/tests/test_telemetry.py +++ b/tests/test_telemetry.py @@ -333,6 +333,25 @@ class TestMemoryLifecycle: # db attribute not set at all m.close() # should not raise due to hasattr guard + def test_context_manager_returns_self_and_closes(self): + """with-block should yield the instance and close() it on exit.""" + m = self._make_mock_memory() + db = m.db + with m as ctx: + assert ctx is m + db.close.assert_called_once_with() + assert m.db is None + + def test_context_manager_closes_on_exception(self): + """Exceptions from the with-body should propagate after close().""" + m = self._make_mock_memory() + db = m.db + with pytest.raises(RuntimeError, match="boom"): + with m: + raise RuntimeError("boom") + db.close.assert_called_once_with() + assert m.db is None + class TestAsyncMemoryLifecycle: """Verify AsyncMemory.close() and async context manager support.""" @@ -357,6 +376,27 @@ class TestAsyncMemoryLifecycle: m = AsyncMemory.__new__(AsyncMemory) m.close() # should not raise + @pytest.mark.asyncio + async def test_async_context_manager_returns_self_and_closes(self): + """async with-block should yield the instance and close() it on exit.""" + m = self._make_mock_async_memory() + db = m.db + async with m as ctx: + assert ctx is m + db.close.assert_called_once_with() + assert m.db is None + + @pytest.mark.asyncio + async def test_async_context_manager_closes_on_exception(self): + """Exceptions from the async with-body should propagate after close().""" + m = self._make_mock_async_memory() + db = m.db + with pytest.raises(RuntimeError, match="boom"): + async with m: + raise RuntimeError("boom") + db.close.assert_called_once_with() + assert m.db is None + class TestTelemetryEnvVar: """Verify the MEM0_TELEMETRY env var parsing logic.""" From 989c7da0fc8e4df6342dbb8c448af9816d60d24c Mon Sep 17 00:00:00 2001 From: Varun S G <143688508+warun7@users.noreply.github.com> Date: Thu, 24 Sep 2026 22:14:28 +0530 Subject: [PATCH 37/61] fix(oss): stop ConfigManager from injecting OpenAI's baseURL and model into other providers (#7350) --- mem0-ts/src/oss/src/config/manager.ts | 17 ++++-- mem0-ts/src/oss/tests/config-manager.test.ts | 60 ++++++++++++++++++-- 2 files changed, 69 insertions(+), 8 deletions(-) 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/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); + } }); }); From 8d6c001966573786d36908bfe4dfd52935749200 Mon Sep 17 00:00:00 2001 From: "mintlify[bot]" <109931778+mintlify[bot]@users.noreply.github.com> Date: Fri, 25 Sep 2026 09:58:06 +0530 Subject: [PATCH 38/61] Fix grammar & typos: correct OpenSearch spelling in changelog (#7442) Co-authored-by: mintlify[bot] <109931778+mintlify[bot]@users.noreply.github.com> --- docs/changelog/sdk.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdx index 3f4a64202..5598d0d96 100644 --- a/docs/changelog/sdk.mdx +++ b/docs/changelog/sdk.mdx @@ -982,7 +982,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:** From 545306db5a52bc45fa07585dd7f71ed6ea8dbed2 Mon Sep 17 00:00:00 2001 From: Abhay Singh Date: Fri, 25 Sep 2026 15:30:31 +0530 Subject: [PATCH 39/61] fix(ts-oss/turbopuffer): apply all filter operators, not just gte/lte (#6578) --- .../src/oss/src/vector_stores/turbopuffer.ts | 53 +++++++-- .../src/oss/tests/turbopuffer.unit.test.ts | 102 ++++++++++++++++++ 2 files changed, 144 insertions(+), 11 deletions(-) create mode 100644 mem0-ts/src/oss/tests/turbopuffer.unit.test.ts diff --git a/mem0-ts/src/oss/src/vector_stores/turbopuffer.ts b/mem0-ts/src/oss/src/vector_stores/turbopuffer.ts index 5134aa80a..8979818d2 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; diff --git a/mem0-ts/src/oss/tests/turbopuffer.unit.test.ts b/mem0-ts/src/oss/tests/turbopuffer.unit.test.ts new file mode 100644 index 000000000..5dcec9f05 --- /dev/null +++ b/mem0-ts/src/oss/tests/turbopuffer.unit.test.ts @@ -0,0 +1,102 @@ +/// +/** + * Turbopuffer vector store — filter translation unit tests. + * + * Drives the private convertFilters() through the public search() API with a + * virtually-mocked @turbopuffer/turbopuffer peer, and asserts the filter tuple + * handed to ns.query(). + */ + +const mockQuery = jest.fn().mockResolvedValue({ rows: [] }); + +// The peer is an optional dependency and may not be installed; mock it +// virtually. createClient() does `new sdk.default({...})`, whose namespace() +// returns the object search() calls query() on. +jest.mock( + "@turbopuffer/turbopuffer", + () => ({ + __esModule: true, + default: class { + namespace() { + return { query: mockQuery }; + } + }, + }), + { virtual: true }, +); + +import { TurbopufferDB } from "../src/vector_stores/turbopuffer"; + +function makeStore() { + return new TurbopufferDB({ + apiKey: "test-key", + collectionName: "mem0", + } as any); +} + +async function filterFor(filters: any): Promise { + mockQuery.mockClear(); + await makeStore().search([0.1, 0.2, 0.3], 5, filters); + return mockQuery.mock.calls[0][0].filters; +} + +describe("TurbopufferDB convertFilters", () => { + it("maps every operator, not just gte/lte", async () => { + expect(await filterFor({ age: { gt: 18 } })).toEqual(["age", "Gt", 18]); + expect(await filterFor({ age: { lt: 65 } })).toEqual(["age", "Lt", 65]); + expect(await filterFor({ age: { ne: 40 } })).toEqual(["age", "NotEq", 40]); + expect(await filterFor({ role: { eq: "admin" } })).toEqual([ + "role", + "Eq", + "admin", + ]); + expect(await filterFor({ tier: { in: ["a", "b"] } })).toEqual([ + "tier", + "In", + ["a", "b"], + ]); + expect(await filterFor({ tier: { nin: ["x"] } })).toEqual([ + "tier", + "NotIn", + ["x"], + ]); + }); + + it("applies every operator in a compound range (AND), not just the first", async () => { + const filter = await filterFor({ age: { gt: 18, lt: 65 } }); + expect(filter[0]).toBe("And"); + expect(filter[1]).toEqual( + expect.arrayContaining([ + ["age", "Gt", 18], + ["age", "Lt", 65], + ]), + ); + }); + + it("treats a bare array value as an 'in' filter", async () => { + expect(await filterFor({ tier: ["gold", "silver"] })).toEqual([ + "tier", + "In", + ["gold", "silver"], + ]); + }); + + it("keeps scalar equality working", async () => { + expect(await filterFor({ user_id: "u1" })).toEqual(["user_id", "Eq", "u1"]); + }); + + it("skips a '*' wildcard value instead of matching it literally", async () => { + // Only the real agent_id clause survives; user_id: "*" contributes nothing. + expect(await filterFor({ user_id: "*", agent_id: "a1" })).toEqual([ + "agent_id", + "Eq", + "a1", + ]); + }); + + it("throws on an unsupported operator rather than silently dropping it", async () => { + await expect( + makeStore().search([0.1, 0.2, 0.3], 5, { name: { startsWith: "a" } }), + ).rejects.toThrow(/Unsupported Turbopuffer filter operator 'startsWith'/); + }); +}); From ccd216cff058e6a45ef12464ef9653dec9b0e512 Mon Sep 17 00:00:00 2001 From: Yash Singh <123385188+yashs33244@users.noreply.github.com> Date: Fri, 25 Sep 2026 15:53:35 +0530 Subject: [PATCH 40/61] fix(vector_stores/turbopuffer): apply all filter operators instead of dropping them (#6564) --- mem0/vector_stores/turbopuffer.py | 24 ++++++++++++++--- tests/vector_stores/test_turbopuffer.py | 34 +++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/mem0/vector_stores/turbopuffer.py b/mem0/vector_stores/turbopuffer.py index bef4b40b2..76281fc96 100644 --- a/mem0/vector_stores/turbopuffer.py +++ b/mem0/vector_stores/turbopuffer.py @@ -131,6 +131,18 @@ class TurbopufferDB(VectorStoreBase): )) return results + # Maps mem0 filter operators to their Turbopuffer equivalents. + OPERATOR_MAP = { + "eq": "Eq", + "ne": "NotEq", + "gt": "Gt", + "gte": "Gte", + "lt": "Lt", + "lte": "Lte", + "in": "In", + "nin": "NotIn", + } + def _convert_filters(self, filters: Optional[Dict]): """ Convert mem0 filters to Turbopuffer filter format. @@ -143,10 +155,14 @@ class TurbopufferDB(VectorStoreBase): conditions = [] for key, value in filters.items(): if isinstance(value, dict): - if "gte" in value: - conditions.append((key, "Gte", value["gte"])) - if "lte" in value: - conditions.append((key, "Lte", value["lte"])) + for op, operand in value.items(): + tpuf_op = self.OPERATOR_MAP.get(op) + if tpuf_op is None: + raise ValueError( + f"Unsupported filter operator '{op}' for field '{key}'. " + f"Supported operators: {sorted(self.OPERATOR_MAP)}" + ) + conditions.append((key, tpuf_op, operand)) else: conditions.append((key, "Eq", value)) diff --git a/tests/vector_stores/test_turbopuffer.py b/tests/vector_stores/test_turbopuffer.py index d1915b94e..e1b9233bb 100644 --- a/tests/vector_stores/test_turbopuffer.py +++ b/tests/vector_stores/test_turbopuffer.py @@ -276,6 +276,40 @@ class TestConvertFilters: assert ("user_id", "Eq", "u1") in conditions assert ("score", "Gte", 0.5) in conditions + def test_gt_operator_not_dropped(self, db): + """Regression: {"gt": ...} was silently dropped, returning unfiltered results.""" + result = db._convert_filters({"age": {"gt": 18}}) + assert result == ("age", "Gt", 18) + + @pytest.mark.parametrize( + "op,expected_token", + [ + ("eq", "Eq"), + ("ne", "NotEq"), + ("gt", "Gt"), + ("gte", "Gte"), + ("lt", "Lt"), + ("lte", "Lte"), + ("in", "In"), + ("nin", "NotIn"), + ], + ) + def test_all_operators_mapped(self, db, op, expected_token): + operand = [1, 2] if op in ("in", "nin") else 5 + result = db._convert_filters({"age": {op: operand}}) + assert result == ("age", expected_token, operand) + + def test_multiple_operators_on_one_field(self, db): + result = db._convert_filters({"age": {"gt": 18, "lt": 65}}) + assert result[0] == "And" + conditions = result[1] + assert ("age", "Gt", 18) in conditions + assert ("age", "Lt", 65) in conditions + + def test_unknown_operator_raises(self, db): + with pytest.raises(ValueError, match="Unsupported filter operator"): + db._convert_filters({"age": {"between": [1, 2]}}) + # ── search ─────────────────────────────────────────────────────────── From fb6d5e1917dd28def068821d86356e602aff446a Mon Sep 17 00:00:00 2001 From: Ayaan Gazali Date: Fri, 25 Sep 2026 03:50:09 -0700 Subject: [PATCH 41/61] fix(llms/aws_bedrock): iterate Converse content blocks for Anthropic text (#6369) --- mem0/llms/aws_bedrock.py | 15 ++++++++--- tests/llms/test_aws_bedrock.py | 48 ++++++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 3 deletions(-) diff --git a/mem0/llms/aws_bedrock.py b/mem0/llms/aws_bedrock.py index 20b7f3883..7fabbd22d 100644 --- a/mem0/llms/aws_bedrock.py +++ b/mem0/llms/aws_bedrock.py @@ -579,11 +579,20 @@ class AWSBedrockLLM(LLMBase): # Use converse API for Anthropic models response = self.client.converse(**converse_params) - # Parse Converse API response + # Parse Converse API response. Claude reasoning models can emit a + # `reasoningContent` block before the `text` block, so iterate to + # find the first block that carries text instead of indexing + # content[0] (same approach as the MiniMax branch below). if hasattr(response, 'output') and hasattr(response.output, 'message'): - return response.output.message.content[0].text + for block in response.output.message.content: + if hasattr(block, 'text'): + return block.text + return "" elif 'output' in response and 'message' in response['output']: - return response['output']['message']['content'][0]['text'] + for block in response['output']['message']['content']: + if 'text' in block: + return block['text'] + return "" else: return str(response) diff --git a/tests/llms/test_aws_bedrock.py b/tests/llms/test_aws_bedrock.py index f683f8c3f..ecb960d09 100644 --- a/tests/llms/test_aws_bedrock.py +++ b/tests/llms/test_aws_bedrock.py @@ -506,3 +506,51 @@ class TestParseResponseLegacy: response = {"body": body} result = llm._parse_response(response, tools=None) assert result == "hello from ai21" + + +class TestAnthropicConverseContentParsing: + """The Anthropic Converse branch must not assume content[0] is the text + block: Claude reasoning models emit a reasoningContent block before the + text block, and some stop conditions produce an empty content array. The + parser iterates for the first block carrying text, like the MiniMax branch. + """ + + def test_text_after_reasoning_content_block(self, mock_boto3): + mock_boto3.converse.return_value = { + "output": { + "message": { + "content": [ + {"reasoningContent": {"reasoningText": {"text": "step by step..."}}}, + {"text": "final answer"}, + ] + } + } + } + llm = _make_llm("anthropic.claude-3-5-sonnet-20240620-v1:0", mock_boto3) + + assert llm.generate_response(MESSAGES) == "final answer" + + def test_empty_content_returns_empty_string(self, mock_boto3): + mock_boto3.converse.return_value = {"output": {"message": {"content": []}}} + llm = _make_llm("anthropic.claude-3-5-sonnet-20240620-v1:0", mock_boto3) + + assert llm.generate_response(MESSAGES) == "" + + def test_plain_text_content_still_returned(self, mock_boto3): + mock_boto3.converse.return_value = _converse_response("plain answer") + llm = _make_llm("anthropic.claude-3-5-sonnet-20240620-v1:0", mock_boto3) + + assert llm.generate_response(MESSAGES) == "plain answer" + + def test_object_style_response_iterates_blocks(self, mock_boto3): + # Defensive attr-style branch: object wrapper with a reasoning block first. + from types import SimpleNamespace + + reasoning_block = SimpleNamespace(reasoningContent={"reasoningText": {"text": "hmm"}}) + text_block = SimpleNamespace(text="object answer") + mock_boto3.converse.return_value = SimpleNamespace( + output=SimpleNamespace(message=SimpleNamespace(content=[reasoning_block, text_block])) + ) + llm = _make_llm("anthropic.claude-3-5-sonnet-20240620-v1:0", mock_boto3) + + assert llm.generate_response(MESSAGES) == "object answer" From a2d8a8a849810e887757d2be7d716cf894c5627c Mon Sep 17 00:00:00 2001 From: Yash Singh <123385188+yashs33244@users.noreply.github.com> Date: Fri, 25 Sep 2026 16:21:16 +0530 Subject: [PATCH 42/61] fix(vector_stores/s3_vectors): make search score metric-aware (#6547) --- mem0/vector_stores/s3_vectors.py | 12 +++++++- tests/vector_stores/test_s3_vectors.py | 39 ++++++++++++++++++++++++++ 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/mem0/vector_stores/s3_vectors.py b/mem0/vector_stores/s3_vectors.py index da059a409..55dadb878 100644 --- a/mem0/vector_stores/s3_vectors.py +++ b/mem0/vector_stores/s3_vectors.py @@ -69,6 +69,16 @@ class S3Vectors(VectorStoreBase): else: raise + def _distance_to_score(self, raw_distance: Optional[float]) -> Optional[float]: + if raw_distance is None: + return None + # Euclidean distance is unbounded, so 1 - distance would collapse most + # scores to 0. Use a bounded monotonic map instead. Cosine distance is + # in [0, 2], where 1 - distance is already a valid similarity. + if self.distance_metric == "euclidean": + return 1.0 / (1.0 + raw_distance) + return max(0.0, 1.0 - raw_distance) + def _parse_output(self, vectors: List[Dict]) -> List[OutputData]: results = [] for v in vectors: @@ -81,7 +91,7 @@ class S3Vectors(VectorStoreBase): logger.warning(f"Failed to parse metadata for key {v.get('key')}") payload = {} raw_distance = v.get("distance") - score = max(0.0, 1.0 - raw_distance) if raw_distance is not None else None + score = self._distance_to_score(raw_distance) results.append(OutputData(id=v.get("key"), score=score, payload=payload)) return results diff --git a/tests/vector_stores/test_s3_vectors.py b/tests/vector_stores/test_s3_vectors.py index 68b7fa0f6..b72db32f4 100644 --- a/tests/vector_stores/test_s3_vectors.py +++ b/tests/vector_stores/test_s3_vectors.py @@ -186,6 +186,45 @@ def test_search(mock_boto_client): assert results[0].score == pytest.approx(0.1) +def test_search_score_cosine_uses_one_minus_distance(mock_boto_client): + """Cosine metric keeps the 1 - distance similarity mapping.""" + mock_boto_client.query_vectors.return_value = {"vectors": [{"key": "id1", "distance": 0.25, "metadata": {}}]} + store = S3Vectors( + vector_bucket_name=BUCKET_NAME, + collection_name=INDEX_NAME, + embedding_model_dims=EMBEDDING_DIMS, + distance_metric="cosine", + ) + + results = store.search(query="test", vectors=[0.1, 0.2], top_k=1) + + assert results[0].score == pytest.approx(0.75) + + +def test_search_score_euclidean_uses_bounded_map(mock_boto_client): + """Euclidean distance is unbounded; scores must not collapse to 0.""" + mock_boto_client.query_vectors.return_value = { + "vectors": [ + {"key": "near", "distance": 0.5, "metadata": {}}, + {"key": "far", "distance": 4.0, "metadata": {}}, + ] + } + store = S3Vectors( + vector_bucket_name=BUCKET_NAME, + collection_name=INDEX_NAME, + embedding_model_dims=EMBEDDING_DIMS, + distance_metric="euclidean", + ) + + results = store.search(query="test", vectors=[0.1, 0.2], top_k=2) + + # 1 / (1 + d): a distance > 1 would give a negative (clamped 0) score under + # the old cosine-only formula; the bounded map keeps ranking intact. + assert results[0].score == pytest.approx(1.0 / 1.5) + assert results[1].score == pytest.approx(1.0 / 5.0) + assert results[0].score > results[1].score > 0.0 + + def test_get(mock_boto_client): """Test retrieving a vector by ID.""" mock_boto_client.get_vectors.return_value = { From 70c676c8c44d96b3032c5a8650809a2a14924734 Mon Sep 17 00:00:00 2001 From: Ratish jain <43003421+ratishjain12@users.noreply.github.com> Date: Fri, 25 Sep 2026 17:04:47 +0530 Subject: [PATCH 43/61] fix: wire dev tooling (ruff/isort/pre-commit) into hatch dev environments (#6684) --- pyproject.toml | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index ddb3d7153..b16a6c0db 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -83,7 +83,7 @@ test = [ dev = [ "ruff==0.16.0", "isort>=5.13.2", - "pytest>=8.2.2", + "pre-commit>=3.5.0", ] [tool.pytest.ini_options] @@ -111,6 +111,7 @@ features = [ "vector-stores", "llms", "extras", + "dev", ] [tool.hatch.envs.dev_py_3_11] @@ -120,6 +121,7 @@ features = [ "vector-stores", "llms", "extras", + "dev", ] [tool.hatch.envs.dev_py_3_12] @@ -129,6 +131,12 @@ features = [ "vector-stores", "llms", "extras", + "dev", +] + +[tool.hatch.envs.default] +features = [ + "dev", ] [tool.hatch.envs.default.scripts] From 5fd01d284a35a044602350d1faabaa02ee27c00d Mon Sep 17 00:00:00 2001 From: Abhay Singh Date: Fri, 25 Sep 2026 17:07:11 +0530 Subject: [PATCH 44/61] fix(ts-oss/turbopuffer): bound euclidean_squared distance to a similarity score (#6580) --- .../src/oss/src/vector_stores/turbopuffer.ts | 13 ++- .../src/oss/tests/turbopuffer.score.test.ts | 80 +++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) create mode 100644 mem0-ts/src/oss/tests/turbopuffer.score.test.ts diff --git a/mem0-ts/src/oss/src/vector_stores/turbopuffer.ts b/mem0-ts/src/oss/src/vector_stores/turbopuffer.ts index 8979818d2..30e032630 100644 --- a/mem0-ts/src/oss/src/vector_stores/turbopuffer.ts +++ b/mem0-ts/src/oss/src/vector_stores/turbopuffer.ts @@ -305,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/tests/turbopuffer.score.test.ts b/mem0-ts/src/oss/tests/turbopuffer.score.test.ts new file mode 100644 index 000000000..b6e8ba844 --- /dev/null +++ b/mem0-ts/src/oss/tests/turbopuffer.score.test.ts @@ -0,0 +1,80 @@ +/// +/** + * Turbopuffer vector store — score conversion unit tests. + * + * Drives parseRows() through the public search() API with a virtually-mocked + * @turbopuffer/turbopuffer peer, asserting the score returned per metric. + */ + +const mockQuery = jest.fn(); + +jest.mock( + "@turbopuffer/turbopuffer", + () => ({ + __esModule: true, + default: class { + namespace() { + return { query: mockQuery }; + } + }, + }), + { virtual: true }, +); + +import { TurbopufferDB } from "../src/vector_stores/turbopuffer"; + +function makeStore(distanceMetric?: string) { + return new TurbopufferDB({ + apiKey: "test-key", + collectionName: "mem0", + ...(distanceMetric ? { distanceMetric } : {}), + } as any); +} + +async function scoreFor( + distanceMetric: string | undefined, + row: Record, +): Promise { + mockQuery.mockResolvedValueOnce({ rows: [row] }); + const results = await makeStore(distanceMetric).search([0.1, 0.2, 0.3], 5); + return results[0].score; +} + +describe("TurbopufferDB score conversion", () => { + it("keeps cosine distance as 1 - dist (default metric)", async () => { + // cosine_distance is the default; a distance of 0.25 -> similarity 0.75. + expect(await scoreFor(undefined, { id: "a", $dist: 0.25 })).toBeCloseTo( + 0.75, + 10, + ); + }); + + it("bounds an unbounded euclidean_squared distance to a 0..1 similarity", async () => { + // $dist = 4.0 is a squared distance. 1 - 4.0 = -3.0 would invert ranking; + // 1 / (1 + 4.0) = 0.2 keeps it higher-is-better and in range. + const score = await scoreFor("euclidean_squared", { id: "a", $dist: 4.0 }); + expect(score).toBeCloseTo(0.2, 10); + expect(score!).toBeGreaterThanOrEqual(0); + expect(score!).toBeLessThanOrEqual(1); + }); + + it("ranks a nearer euclidean_squared hit above a farther one", async () => { + mockQuery.mockResolvedValueOnce({ + rows: [ + { id: "near", $dist: 1.0 }, + { id: "far", $dist: 9.0 }, + ], + }); + const results = await makeStore("euclidean_squared").search( + [0.1, 0.2, 0.3], + 5, + ); + const near = results.find((r) => r.id === "near")!; + const far = results.find((r) => r.id === "far")!; + expect(near.score!).toBeGreaterThan(far.score!); + }); + + it("preserves an undefined score when the row has no distance", async () => { + expect(await scoreFor("euclidean_squared", { id: "a" })).toBeUndefined(); + }); +}); From 8127e8bd47a8f5b6eabd178c0637e72621b9b976 Mon Sep 17 00:00:00 2001 From: Yash Singh <123385188+yashs33244@users.noreply.github.com> Date: Fri, 25 Sep 2026 17:08:20 +0530 Subject: [PATCH 45/61] fix(vector_stores/turbopuffer): make search score respect distance_metric (#6559) --- mem0/vector_stores/turbopuffer.py | 9 +++++++- tests/vector_stores/test_turbopuffer.py | 29 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/mem0/vector_stores/turbopuffer.py b/mem0/vector_stores/turbopuffer.py index 76281fc96..97109704f 100644 --- a/mem0/vector_stores/turbopuffer.py +++ b/mem0/vector_stores/turbopuffer.py @@ -122,7 +122,14 @@ class TurbopufferDB(VectorStoreBase): dist = row_dict.pop("$dist", None) row_dict.pop("vector", None) - score = 1 - dist if dist is not None else None + if dist is None: + score = None + elif self.distance_metric == "euclidean_squared": + # $dist is unbounded squared-L2 (lower = closer); map to a bounded + # higher-is-better score, mirroring milvus/baidu. Cosine returns 1 - dist. + score = 1.0 / (1.0 + dist) + else: + score = 1 - dist results.append(OutputData( id=row_id, diff --git a/tests/vector_stores/test_turbopuffer.py b/tests/vector_stores/test_turbopuffer.py index e1b9233bb..df0670570 100644 --- a/tests/vector_stores/test_turbopuffer.py +++ b/tests/vector_stores/test_turbopuffer.py @@ -232,6 +232,35 @@ class TestParseOutput: def test_parse_empty_rows(self, db): assert db._parse_output([]) == [] + def test_parse_cosine_score_is_one_minus_dist(self, db): + # Default cosine metric: score = 1 - dist, unchanged by the metric fix. + results = db._parse_output([_make_row("id1", dist=0.25)]) + assert results[0].score == pytest.approx(0.75) + + def test_parse_euclidean_squared_score_is_bounded(self, mock_client): + # euclidean_squared $dist is unbounded (e.g. 4.0). 1 - dist would give -3.0, + # violating the higher-is-better contract; map it to 1/(1+dist) instead. + db = TurbopufferDB( + collection_name="test_ns", + embedding_model_dims=4, + api_key="tpuf_test_key", + region="gcp-us-central1", + distance_metric="euclidean_squared", + ) + results = db._parse_output([_make_row("id1", dist=4.0)]) + assert results[0].score == pytest.approx(0.2) + assert 0.0 <= results[0].score <= 1.0 + + def test_parse_euclidean_squared_preserves_none(self, mock_client): + db = TurbopufferDB( + collection_name="test_ns", + embedding_model_dims=4, + api_key="tpuf_test_key", + region="gcp-us-central1", + distance_metric="euclidean_squared", + ) + assert db._parse_output([_make_row("id1")])[0].score is None + # ── _convert_filters ───────────────────────────────────────────────── From 947ac798183dfbac7c3c0f37478e13fa5f17e91d Mon Sep 17 00:00:00 2001 From: Kartik Date: Fri, 25 Sep 2026 20:46:24 +0530 Subject: [PATCH 46/61] fix(ts-sdk): stop forcing pg on installs (optional ranged pg peer, optional natural) (#7450) --- docs/components/vectordbs/dbs/pgvector.mdx | 6 +++ mem0-ts/package.json | 17 +++++-- mem0-ts/pnpm-lock.yaml | 48 +++---------------- mem0-ts/src/oss/src/vector_stores/pgvector.ts | 40 +++++++++++----- .../oss/tests/missing-optional-peers.test.ts | 39 +++++++++++++++ 5 files changed, 93 insertions(+), 57 deletions(-) create mode 100644 mem0-ts/src/oss/tests/missing-optional-peers.test.ts 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/mem0-ts/package.json b/mem0-ts/package.json index 3bb996079..e6f29d4cb 100644 --- a/mem0-ts/package.json +++ b/mem0-ts/package.json @@ -100,7 +100,8 @@ "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", @@ -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": { diff --git a/mem0-ts/pnpm-lock.yaml b/mem0-ts/pnpm-lock.yaml index 5deb30e7b..5e04cbfdd 100644 --- a/mem0-ts/pnpm-lock.yaml +++ b/mem0-ts/pnpm-lock.yaml @@ -109,11 +109,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 @@ -167,8 +164,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 +188,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 @@ -2228,10 +2228,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==} @@ -3846,9 +3842,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 +3913,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'} @@ -7593,8 +7577,6 @@ snapshots: buffer-from@1.1.2: {} - buffer-writer@2.0.0: {} - buffer@5.7.1: dependencies: base64-js: 1.5.1 @@ -9409,8 +9391,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 +9438,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 +9462,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 diff --git a/mem0-ts/src/oss/src/vector_stores/pgvector.ts b/mem0-ts/src/oss/src/vector_stores/pgvector.ts index 450ffc9a5..b7f2c2f69 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], @@ -453,6 +465,7 @@ export class PGVector implements VectorStore { vector: number[], payload: Record, ): Promise { + await this.initialize(); const vectorStr = `[${vector.join(",")}]`; await this.client.query( ` @@ -465,12 +478,14 @@ export class PGVector implements VectorStore { } 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 +502,7 @@ export class PGVector implements VectorStore { filters?: SearchFilters, topK: number = 100, ): Promise<[VectorStoreResult[], number]> { + await this.initialize(); const { conditions, values: filterValues, @@ -525,10 +541,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 +566,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/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"); + }); +}); From 94c3fe9f238f3dbf29c9ce98643bd71eb13077cd Mon Sep 17 00:00:00 2001 From: Kartik Date: Fri, 25 Sep 2026 23:04:12 +0530 Subject: [PATCH 47/61] chore(release): bump Python SDK to 2.2.1 and TypeScript SDK to 3.3.1 (#7456) --- docs/changelog/sdk.mdx | 22 ++++++++++++++ mem0-ts/package.json | 2 +- .../src/oss/tests/turbopuffer.score.test.ts | 22 ++++++-------- .../src/oss/tests/turbopuffer.unit.test.ts | 29 ++++++++----------- pyproject.toml | 2 +- 5 files changed, 45 insertions(+), 32 deletions(-) diff --git a/docs/changelog/sdk.mdx b/docs/changelog/sdk.mdx index 5598d0d96..14c9c014d 100644 --- a/docs/changelog/sdk.mdx +++ b/docs/changelog/sdk.mdx @@ -7,6 +7,18 @@ 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:** @@ -1245,6 +1257,16 @@ 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:** diff --git a/mem0-ts/package.json b/mem0-ts/package.json index e6f29d4cb..b03a73485 100644 --- a/mem0-ts/package.json +++ b/mem0-ts/package.json @@ -1,6 +1,6 @@ { "name": "mem0ai", - "version": "3.3.0", + "version": "3.3.1", "description": "The Memory Layer For Your AI Apps", "main": "./dist/index.js", "module": "./dist/index.mjs", diff --git a/mem0-ts/src/oss/tests/turbopuffer.score.test.ts b/mem0-ts/src/oss/tests/turbopuffer.score.test.ts index b6e8ba844..31db83ce3 100644 --- a/mem0-ts/src/oss/tests/turbopuffer.score.test.ts +++ b/mem0-ts/src/oss/tests/turbopuffer.score.test.ts @@ -2,24 +2,20 @@ /** * Turbopuffer vector store — score conversion unit tests. * - * Drives parseRows() through the public search() API with a virtually-mocked + * Drives parseRows() through the public search() API with a mocked * @turbopuffer/turbopuffer peer, asserting the score returned per metric. */ const mockQuery = jest.fn(); -jest.mock( - "@turbopuffer/turbopuffer", - () => ({ - __esModule: true, - default: class { - namespace() { - return { query: mockQuery }; - } - }, - }), - { virtual: true }, -); +jest.mock("@turbopuffer/turbopuffer", () => ({ + __esModule: true, + default: class { + namespace() { + return { query: mockQuery }; + } + }, +})); import { TurbopufferDB } from "../src/vector_stores/turbopuffer"; diff --git a/mem0-ts/src/oss/tests/turbopuffer.unit.test.ts b/mem0-ts/src/oss/tests/turbopuffer.unit.test.ts index 5dcec9f05..c781f3ebb 100644 --- a/mem0-ts/src/oss/tests/turbopuffer.unit.test.ts +++ b/mem0-ts/src/oss/tests/turbopuffer.unit.test.ts @@ -3,27 +3,22 @@ * Turbopuffer vector store — filter translation unit tests. * * Drives the private convertFilters() through the public search() API with a - * virtually-mocked @turbopuffer/turbopuffer peer, and asserts the filter tuple - * handed to ns.query(). + * mocked @turbopuffer/turbopuffer peer, and asserts the filter tuple handed to + * ns.query(). */ const mockQuery = jest.fn().mockResolvedValue({ rows: [] }); -// The peer is an optional dependency and may not be installed; mock it -// virtually. createClient() does `new sdk.default({...})`, whose namespace() -// returns the object search() calls query() on. -jest.mock( - "@turbopuffer/turbopuffer", - () => ({ - __esModule: true, - default: class { - namespace() { - return { query: mockQuery }; - } - }, - }), - { virtual: true }, -); +// createClient() does `new sdk.default({...})`, whose namespace() returns the +// object search() calls query() on. +jest.mock("@turbopuffer/turbopuffer", () => ({ + __esModule: true, + default: class { + namespace() { + return { query: mockQuery }; + } + }, +})); import { TurbopufferDB } from "../src/vector_stores/turbopuffer"; diff --git a/pyproject.toml b/pyproject.toml index b16a6c0db..c6c1f38d3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "mem0ai" -version = "2.2.0" +version = "2.2.1" description = "Long-term memory for AI Agents" authors = [ { name = "Mem0", email = "support@mem0.ai" } From abb81c88e1f738a8117d8293530fbc31a5ef8fd9 Mon Sep 17 00:00:00 2001 From: Harsh Vardhan Gupta Date: Thu, 1 Oct 2026 21:46:18 +0530 Subject: [PATCH 48/61] fix(security): resolve 7 Vanta MEDIUM Dependabot vulnerabilities (undici, ip-address, adm-zip) (#7510) Co-authored-by: Claude Opus 5.5 --- integrations/openclaw/package.json | 2 +- integrations/openclaw/pnpm-lock.yaml | 10 +++--- integrations/openclaw/pnpm-workspace.yaml | 2 +- integrations/pi-agent-plugin/package.json | 4 +-- integrations/pi-agent-plugin/pnpm-lock.yaml | 20 +++++------ .../pi-agent-plugin/pnpm-workspace.yaml | 4 +-- mem0-ts/package.json | 6 ++-- mem0-ts/pnpm-lock.yaml | 36 +++++++++---------- mem0-ts/pnpm-workspace.yaml | 6 ++-- 9 files changed, 45 insertions(+), 45 deletions(-) diff --git a/integrations/openclaw/package.json b/integrations/openclaw/package.json index 39aaeb70e..df01be01a 100644 --- a/integrations/openclaw/package.json +++ b/integrations/openclaw/package.json @@ -72,7 +72,7 @@ "@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", + "undici@<7.29.1": ">=7.29.1 <8.0.0", "axios@<1.18.0": ">=1.18.0 <2.0.0", "postcss@<8.5.18": ">=8.5.18 <9.0.0", "mongoose@>=9.0.0 <9.7.2": ">=9.7.2 <10.0.0" diff --git a/integrations/openclaw/pnpm-lock.yaml b/integrations/openclaw/pnpm-lock.yaml index 79dd0d10a..6e8729d46 100644 --- a/integrations/openclaw/pnpm-lock.yaml +++ b/integrations/openclaw/pnpm-lock.yaml @@ -13,7 +13,7 @@ overrides: '@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' + undici@<7.29.1: '>=7.29.1 <8.0.0' axios@<1.18.0: '>=1.18.0 <2.0.0' postcss@<8.5.18: '>=8.5.18 <9.0.0' mongoose@>=9.0.0 <9.7.2: '>=9.7.2 <10.0.0' @@ -2036,8 +2036,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.0: + resolution: {integrity: sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==} engines: {node: '>=20.18.1'} util-deprecate@1.0.2: @@ -2547,7 +2547,7 @@ snapshots: dependencies: '@qdrant/openapi-typescript-fetch': 1.2.6 typescript: 5.9.3 - undici: 7.29.0 + undici: 7.30.0 '@qdrant/openapi-typescript-fetch@1.2.6': {} @@ -4121,7 +4121,7 @@ snapshots: undici-types@6.21.0: {} - undici@7.29.0: {} + undici@7.30.0: {} util-deprecate@1.0.2: {} diff --git a/integrations/openclaw/pnpm-workspace.yaml b/integrations/openclaw/pnpm-workspace.yaml index 0f9f833bc..34e812fa8 100644 --- a/integrations/openclaw/pnpm-workspace.yaml +++ b/integrations/openclaw/pnpm-workspace.yaml @@ -21,7 +21,7 @@ overrides: "@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" + "undici@<7.29.1": ">=7.29.1 <8.0.0" "axios@<1.18.0": ">=1.18.0 <2.0.0" "postcss@<8.5.18": ">=8.5.18 <9.0.0" "mongoose@>=9.0.0 <9.7.2": ">=9.7.2 <10.0.0" diff --git a/integrations/pi-agent-plugin/package.json b/integrations/pi-agent-plugin/package.json index fbec4db1b..56952c42f 100644 --- a/integrations/pi-agent-plugin/package.json +++ b/integrations/pi-agent-plugin/package.json @@ -72,8 +72,8 @@ "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", + "undici@<7.29.1": ">=7.29.1 <8.0.0", + "undici@>=8.0.0 <8.10.2": ">=8.10.2 <9.0.0", "axios@<1.18.0": ">=1.18.0 <2.0.0", "brace-expansion@>=3.0.0 <5.0.8": ">=5.0.8 <6.0.0", "postcss@<8.5.18": ">=8.5.18 <9.0.0", diff --git a/integrations/pi-agent-plugin/pnpm-lock.yaml b/integrations/pi-agent-plugin/pnpm-lock.yaml index 177023505..0a4100fc8 100644 --- a/integrations/pi-agent-plugin/pnpm-lock.yaml +++ b/integrations/pi-agent-plugin/pnpm-lock.yaml @@ -8,8 +8,8 @@ overrides: 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' + undici@<7.29.1: '>=7.29.1 <8.0.0' + undici@>=8.0.0 <8.10.2: '>=8.10.2 <9.0.0' axios@<1.18.0: '>=1.18.0 <2.0.0' brace-expansion@>=3.0.0 <5.0.8: '>=5.0.8 <6.0.0' postcss@<8.5.18: '>=8.5.18 <9.0.0' @@ -2354,12 +2354,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.0: + resolution: {integrity: sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==} engines: {node: '>=20.18.1'} - undici@8.10.0: - resolution: {integrity: sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ==} + undici@8.11.2: + resolution: {integrity: sha512-u4UB2/IrKdU6lFxumHmmo1a3fCQO5tzQllRorfoRS63txhrB7xTpSn1PftwC4qEHkOaqP95fCWW4lJzwErwzhQ==} engines: {node: '>=22.19.0'} util-deprecate@1.0.2: @@ -2942,7 +2942,7 @@ snapshots: minimatch: 10.2.5 proper-lockfile: 4.1.2 typebox: 1.1.38 - undici: 8.10.0 + undici: 8.11.2 yaml: 2.9.0 optionalDependencies: '@mariozechner/clipboard': 0.3.9 @@ -3203,7 +3203,7 @@ snapshots: dependencies: '@qdrant/openapi-typescript-fetch': 1.2.6 typescript: 6.0.3 - undici: 7.29.0 + undici: 7.30.0 '@qdrant/openapi-typescript-fetch@1.2.6': {} @@ -4895,9 +4895,9 @@ snapshots: undici-types@7.24.6: {} - undici@7.29.0: {} + undici@7.30.0: {} - undici@8.10.0: {} + undici@8.11.2: {} util-deprecate@1.0.2: {} diff --git a/integrations/pi-agent-plugin/pnpm-workspace.yaml b/integrations/pi-agent-plugin/pnpm-workspace.yaml index 283b117cc..071ea6a55 100644 --- a/integrations/pi-agent-plugin/pnpm-workspace.yaml +++ b/integrations/pi-agent-plugin/pnpm-workspace.yaml @@ -5,8 +5,8 @@ overrides: "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" + "undici@<7.29.1": ">=7.29.1 <8.0.0" + "undici@>=8.0.0 <8.10.2": ">=8.10.2 <9.0.0" "axios@<1.18.0": ">=1.18.0 <2.0.0" "brace-expansion@>=3.0.0 <5.0.8": ">=5.0.8 <6.0.0" "postcss@<8.5.18": ">=8.5.18 <9.0.0" diff --git a/mem0-ts/package.json b/mem0-ts/package.json index b03a73485..c34192188 100644 --- a/mem0-ts/package.json +++ b/mem0-ts/package.json @@ -288,7 +288,7 @@ "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", + "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", @@ -303,7 +303,7 @@ "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.29.1": ">=7.29.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", @@ -315,7 +315,7 @@ "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" } diff --git a/mem0-ts/pnpm-lock.yaml b/mem0-ts/pnpm-lock.yaml index 5e04cbfdd..27e0811f7 100644 --- a/mem0-ts/pnpm-lock.yaml +++ b/mem0-ts/pnpm-lock.yaml @@ -12,7 +12,7 @@ overrides: 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' + 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,7 +27,7 @@ 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.29.1: '>=7.29.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' @@ -39,7 +39,7 @@ overrides: 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' @@ -2009,8 +2009,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: @@ -3034,8 +3034,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: @@ -4609,8 +4609,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.0: + resolution: {integrity: sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==} engines: {node: '>=20.18.1'} update-browserslist-db@1.3.2: @@ -6138,7 +6138,7 @@ snapshots: ms: 2.1.3 secure-json-parse: 4.1.0 tslib: 2.8.1 - undici: 7.29.0 + undici: 7.30.0 transitivePeerDependencies: - supports-color @@ -6706,7 +6706,7 @@ snapshots: dependencies: '@qdrant/openapi-typescript-fetch': 1.2.6 typescript: 5.5.4 - undici: 7.29.0 + undici: 7.30.0 '@qdrant/openapi-typescript-fetch@1.2.6': {} @@ -7178,7 +7178,7 @@ snapshots: '@turbopuffer/turbopuffer@2.5.0': dependencies: pako: 2.2.0 - undici: 7.29.0 + undici: 7.30.0 '@types/babel__core@7.20.5': dependencies: @@ -7346,7 +7346,7 @@ snapshots: acorn@8.16.0: {} - adm-zip@0.6.0: {} + adm-zip@0.6.1: {} afinn-165-financialmarketnews@3.0.0: {} @@ -7614,7 +7614,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: @@ -8435,7 +8435,7 @@ snapshots: transitivePeerDependencies: - supports-color - ip-address@10.4.0: {} + ip-address@10.7.2: {} is-arrayish@0.2.1: {} @@ -9291,7 +9291,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 @@ -9845,7 +9845,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: @@ -10182,7 +10182,7 @@ snapshots: undici-types@7.24.6: {} - undici@7.29.0: {} + undici@7.30.0: {} update-browserslist-db@1.3.2(browserslist@4.28.9): dependencies: diff --git a/mem0-ts/pnpm-workspace.yaml b/mem0-ts/pnpm-workspace.yaml index 4048a653c..61017d969 100644 --- a/mem0-ts/pnpm-workspace.yaml +++ b/mem0-ts/pnpm-workspace.yaml @@ -13,7 +13,7 @@ overrides: "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" + "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,7 +27,7 @@ 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.29.1": ">=7.29.1 <8.0.0" "axios@<1.18.0": ">=1.18.0 <2.0.0" "brace-expansion@<1.1.16": ">=1.1.16 <2.0.0" "brace-expansion@>=2.0.0 <2.1.4": ">=2.1.4 <3.0.0" @@ -37,7 +37,7 @@ overrides: "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" From c93420c49a6b14c3d446bdb156d96811908fd90a Mon Sep 17 00:00:00 2001 From: Harsh Vardhan Gupta Date: Mon, 5 Oct 2026 20:52:59 +0530 Subject: [PATCH 49/61] fix(security): resolve 13 Vanta HIGH Dependabot vulnerabilities (#7528) Co-authored-by: Claude Opus 5.5 --- integrations/deepseek-plugin/package.json | 5 + integrations/deepseek-plugin/pnpm-lock.yaml | 11 +- integrations/n8n-nodes-mem0/package.json | 4 +- integrations/n8n-nodes-mem0/pnpm-lock.yaml | 22 +- integrations/openclaw/package.json | 2 +- integrations/openclaw/pnpm-lock.yaml | 10 +- integrations/openclaw/pnpm-workspace.yaml | 2 +- integrations/pi-agent-plugin/package.json | 2 +- integrations/pi-agent-plugin/pnpm-lock.yaml | 10 +- .../pi-agent-plugin/pnpm-workspace.yaml | 2 +- integrations/vercel-ai-sdk/package.json | 4 +- integrations/vercel-ai-sdk/pnpm-lock.yaml | 12 +- .../vercel-ai-sdk/pnpm-workspace.yaml | 4 +- integrations/zapier-mem0/package.json | 2 +- integrations/zapier-mem0/pnpm-lock.yaml | 10 +- integrations/zapier-mem0/pnpm-workspace.yaml | 2 +- mem0-ts/package.json | 16 +- mem0-ts/pnpm-lock.yaml | 308 +++++++++--------- mem0-ts/pnpm-workspace.yaml | 12 +- server/dashboard/package.json | 2 +- server/dashboard/pnpm-lock.yaml | 266 +++++++-------- server/dashboard/pnpm-workspace.yaml | 8 +- 22 files changed, 365 insertions(+), 351 deletions(-) diff --git a/integrations/deepseek-plugin/package.json b/integrations/deepseek-plugin/package.json index 41a8fe7a5..8df2dc27f 100644 --- a/integrations/deepseek-plugin/package.json +++ b/integrations/deepseek-plugin/package.json @@ -60,5 +60,10 @@ "tsup": "^8.5.0", "typescript": "^5.6.0", "vitest": "^4.1.7" + }, + "pnpm": { + "overrides": { + "axios@<1.20.0": ">=1.20.0 <2.0.0" + } } } diff --git a/integrations/deepseek-plugin/pnpm-lock.yaml b/integrations/deepseek-plugin/pnpm-lock.yaml index 1444b53d4..d9fc88b8b 100644 --- a/integrations/deepseek-plugin/pnpm-lock.yaml +++ b/integrations/deepseek-plugin/pnpm-lock.yaml @@ -4,6 +4,9 @@ settings: autoInstallPeers: false excludeLinksFromLockfile: false +overrides: + axios@<1.20.0: '>=1.20.0 <2.0.0' + importers: .: @@ -575,8 +578,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==} @@ -1610,7 +1613,7 @@ snapshots: asynckit@0.4.0: {} - axios@1.19.0: + axios@1.20.0: dependencies: follow-redirects: 1.16.0 form-data: 4.0.6 @@ -1856,7 +1859,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 diff --git a/integrations/n8n-nodes-mem0/package.json b/integrations/n8n-nodes-mem0/package.json index 207dbbc7c..94e28dd8f 100644 --- a/integrations/n8n-nodes-mem0/package.json +++ b/integrations/n8n-nodes-mem0/package.json @@ -74,8 +74,8 @@ "brace-expansion@<1.1.16": ">=1.1.16 <2.0.0", "brace-expansion@>=2.0.0 <2.1.2": ">=2.1.2 <3.0.0", "brace-expansion@>=5.0.0 <5.0.8": ">=5.0.8", - "js-yaml@<3.15.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" } } } diff --git a/integrations/n8n-nodes-mem0/pnpm-lock.yaml b/integrations/n8n-nodes-mem0/pnpm-lock.yaml index 41440b3ca..34372df52 100644 --- a/integrations/n8n-nodes-mem0/pnpm-lock.yaml +++ b/integrations/n8n-nodes-mem0/pnpm-lock.yaml @@ -11,8 +11,8 @@ overrides: brace-expansion@<1.1.16: '>=1.1.16 <2.0.0' brace-expansion@>=2.0.0 <2.1.2: '>=2.1.2 <3.0.0' brace-expansion@>=5.0.0 <5.0.8: '>=5.0.8' - js-yaml@<3.15.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' importers: @@ -1494,12 +1494,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 +2506,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 +2546,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 +3353,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 @@ -4173,12 +4173,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 diff --git a/integrations/openclaw/package.json b/integrations/openclaw/package.json index df01be01a..f24bca81a 100644 --- a/integrations/openclaw/package.json +++ b/integrations/openclaw/package.json @@ -73,7 +73,7 @@ "uuid@<11.1.1": ">=11.1.1", "esbuild": ">=0.28.1", "undici@<7.29.1": ">=7.29.1 <8.0.0", - "axios@<1.18.0": ">=1.18.0 <2.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" } diff --git a/integrations/openclaw/pnpm-lock.yaml b/integrations/openclaw/pnpm-lock.yaml index 6e8729d46..90d1b23b6 100644 --- a/integrations/openclaw/pnpm-lock.yaml +++ b/integrations/openclaw/pnpm-lock.yaml @@ -14,7 +14,7 @@ overrides: uuid@<11.1.1: '>=11.1.1' esbuild: '>=0.28.1' undici@<7.29.1: '>=7.29.1 <8.0.0' - axios@<1.18.0: '>=1.18.0 <2.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' @@ -857,8 +857,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==} @@ -2906,7 +2906,7 @@ snapshots: asynckit@0.4.0: {} - axios@1.18.1: + axios@1.20.0: dependencies: follow-redirects: 1.16.0 form-data: 4.0.6 @@ -3529,7 +3529,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 diff --git a/integrations/openclaw/pnpm-workspace.yaml b/integrations/openclaw/pnpm-workspace.yaml index 34e812fa8..9f2b3e97c 100644 --- a/integrations/openclaw/pnpm-workspace.yaml +++ b/integrations/openclaw/pnpm-workspace.yaml @@ -22,6 +22,6 @@ overrides: "uuid@<11.1.1": ">=11.1.1" "esbuild": ">=0.28.1" "undici@<7.29.1": ">=7.29.1 <8.0.0" - "axios@<1.18.0": ">=1.18.0 <2.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" diff --git a/integrations/pi-agent-plugin/package.json b/integrations/pi-agent-plugin/package.json index 56952c42f..f6978753b 100644 --- a/integrations/pi-agent-plugin/package.json +++ b/integrations/pi-agent-plugin/package.json @@ -74,7 +74,7 @@ "esbuild": ">=0.28.1", "undici@<7.29.1": ">=7.29.1 <8.0.0", "undici@>=8.0.0 <8.10.2": ">=8.10.2 <9.0.0", - "axios@<1.18.0": ">=1.18.0 <2.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", diff --git a/integrations/pi-agent-plugin/pnpm-lock.yaml b/integrations/pi-agent-plugin/pnpm-lock.yaml index 0a4100fc8..8ae11c8ed 100644 --- a/integrations/pi-agent-plugin/pnpm-lock.yaml +++ b/integrations/pi-agent-plugin/pnpm-lock.yaml @@ -10,7 +10,7 @@ overrides: esbuild: '>=0.28.1' undici@<7.29.1: '>=7.29.1 <8.0.0' undici@>=8.0.0 <8.10.2: '>=8.10.2 <9.0.0' - axios@<1.18.0: '>=1.18.0 <2.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' @@ -1066,8 +1066,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==} @@ -3598,7 +3598,7 @@ snapshots: asynckit@0.4.0: {} - axios@1.18.1: + axios@1.20.0: dependencies: follow-redirects: 1.16.0 form-data: 4.0.6 @@ -4253,7 +4253,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 diff --git a/integrations/pi-agent-plugin/pnpm-workspace.yaml b/integrations/pi-agent-plugin/pnpm-workspace.yaml index 071ea6a55..10de842c5 100644 --- a/integrations/pi-agent-plugin/pnpm-workspace.yaml +++ b/integrations/pi-agent-plugin/pnpm-workspace.yaml @@ -7,7 +7,7 @@ overrides: "esbuild": ">=0.28.1" "undici@<7.29.1": ">=7.29.1 <8.0.0" "undici@>=8.0.0 <8.10.2": ">=8.10.2 <9.0.0" - "axios@<1.18.0": ">=1.18.0 <2.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" diff --git a/integrations/vercel-ai-sdk/package.json b/integrations/vercel-ai-sdk/package.json index 1165c3f92..aef0b639a 100644 --- a/integrations/vercel-ai-sdk/package.json +++ b/integrations/vercel-ai-sdk/package.json @@ -88,8 +88,8 @@ "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" } } diff --git a/integrations/vercel-ai-sdk/pnpm-lock.yaml b/integrations/vercel-ai-sdk/pnpm-lock.yaml index f8208a36a..482bba7d1 100644 --- a/integrations/vercel-ai-sdk/pnpm-lock.yaml +++ b/integrations/vercel-ai-sdk/pnpm-lock.yaml @@ -14,8 +14,8 @@ 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' importers: @@ -1356,8 +1356,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 +2231,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': {} @@ -3360,7 +3360,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 diff --git a/integrations/vercel-ai-sdk/pnpm-workspace.yaml b/integrations/vercel-ai-sdk/pnpm-workspace.yaml index 93ff161d8..cd73ee714 100644 --- a/integrations/vercel-ai-sdk/pnpm-workspace.yaml +++ b/integrations/vercel-ai-sdk/pnpm-workspace.yaml @@ -15,6 +15,6 @@ overrides: "esbuild": ">=0.28.1" "brace-expansion@<1.1.16": ">=1.1.16 <2.0.0" "brace-expansion@>=3.0.0 <5.0.8": ">=5.0.8 <6.0.0" - "js-yaml@<3.15.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" diff --git a/integrations/zapier-mem0/package.json b/integrations/zapier-mem0/package.json index b33e01b53..248ca9572 100644 --- a/integrations/zapier-mem0/package.json +++ b/integrations/zapier-mem0/package.json @@ -72,7 +72,7 @@ "undici@<7.29.0": ">=7.29.0 <8.0.0", "undici@>=8.0.0 <8.9.0": ">=8.9.0 <9.0.0", "brace-expansion@<1.1.16": ">=1.1.16 <2.0.0", - "js-yaml@<3.15.1": ">=3.15.1 <4.0.0" + "js-yaml@<3.15.2": ">=3.15.2 <4.0.0" } } } diff --git a/integrations/zapier-mem0/pnpm-lock.yaml b/integrations/zapier-mem0/pnpm-lock.yaml index 703de111d..2518f4e34 100644 --- a/integrations/zapier-mem0/pnpm-lock.yaml +++ b/integrations/zapier-mem0/pnpm-lock.yaml @@ -11,7 +11,7 @@ overrides: undici@<7.29.0: '>=7.29.0 <8.0.0' undici@>=8.0.0 <8.9.0: '>=8.9.0 <9.0.0' brace-expansion@<1.1.16: '>=1.1.16 <2.0.0' - js-yaml@<3.15.1: '>=3.15.1 <4.0.0' + js-yaml@<3.15.2: '>=3.15.2 <4.0.0' importers: @@ -951,8 +951,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 +1654,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': {} @@ -2714,7 +2714,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 diff --git a/integrations/zapier-mem0/pnpm-workspace.yaml b/integrations/zapier-mem0/pnpm-workspace.yaml index e19a69b83..2b48f0327 100644 --- a/integrations/zapier-mem0/pnpm-workspace.yaml +++ b/integrations/zapier-mem0/pnpm-workspace.yaml @@ -8,4 +8,4 @@ overrides: "undici@<7.29.0": ">=7.29.0 <8.0.0" "undici@>=8.0.0 <8.9.0": ">=8.9.0 <9.0.0" "brace-expansion@<1.1.16": ">=1.1.16 <2.0.0" - "js-yaml@<3.15.1": ">=3.15.1 <4.0.0" + "js-yaml@<3.15.2": ">=3.15.2 <4.0.0" diff --git a/mem0-ts/package.json b/mem0-ts/package.json index c34192188..586bf9030 100644 --- a/mem0-ts/package.json +++ b/mem0-ts/package.json @@ -104,7 +104,7 @@ "@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" @@ -285,9 +285,9 @@ "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", + "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", @@ -306,9 +306,9 @@ "undici@<7.29.1": ">=7.29.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", @@ -317,7 +317,9 @@ "protobufjs@<7.6.5": ">=7.6.5 <8.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" } } } diff --git a/mem0-ts/pnpm-lock.yaml b/mem0-ts/pnpm-lock.yaml index 27e0811f7..623443f1e 100644 --- a/mem0-ts/pnpm-lock.yaml +++ b/mem0-ts/pnpm-lock.yaml @@ -9,9 +9,9 @@ overrides: 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' + 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 @@ -30,9 +30,9 @@ overrides: undici@<7.29.1: '>=7.29.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' @@ -42,6 +42,8 @@ overrides: 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' patchedDependencies: tar@7.5.22: @@ -119,8 +121,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 @@ -861,8 +863,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 +1040,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 +1077,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] @@ -2107,8 +2109,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 +2155,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 +2186,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==} @@ -3282,8 +3284,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: @@ -4209,8 +4211,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': '*' @@ -6142,7 +6144,7 @@ snapshots: transitivePeerDependencies: - supports-color - '@emnapi/runtime@1.11.2': + '@emnapi/runtime@1.11.3': dependencies: tslib: 2.8.1 optional: true @@ -6246,7 +6248,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 @@ -6279,7 +6281,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' @@ -6290,108 +6292,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': {} @@ -6414,7 +6416,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': {} @@ -7320,7 +7322,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 @@ -7432,7 +7434,7 @@ snapshots: aws4@1.13.2: {} - axios@1.18.1: + axios@1.20.0: dependencies: follow-redirects: 1.16.0 form-data: 4.0.6 @@ -7507,7 +7509,7 @@ snapshots: baseline-browser-mapping@2.11.21: {} - basic-ftp@5.3.1: {} + basic-ftp@6.2.1: {} better-sqlite3@12.10.0: dependencies: @@ -7537,7 +7539,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 @@ -8207,7 +8209,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: @@ -8276,7 +8278,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 @@ -8507,7 +8509,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 @@ -8855,7 +8857,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 @@ -9005,7 +9007,7 @@ snapshots: make-dir@4.0.0: dependencies: - semver: 7.8.4 + semver: 7.8.5 make-error@1.3.6: {} @@ -9063,7 +9065,7 @@ snapshots: minimatch@9.0.9: dependencies: - brace-expansion: 2.1.4 + brace-expansion: 2.1.7 minimist@1.2.8: {} @@ -9200,7 +9202,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 @@ -9770,37 +9772,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: diff --git a/mem0-ts/pnpm-workspace.yaml b/mem0-ts/pnpm-workspace.yaml index 61017d969..09ff00416 100644 --- a/mem0-ts/pnpm-workspace.yaml +++ b/mem0-ts/pnpm-workspace.yaml @@ -10,9 +10,9 @@ overrides: "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" + "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" @@ -28,9 +28,9 @@ overrides: "@modelcontextprotocol/sdk": "^1.25.4" "esbuild": ">=0.28.1" "undici@<7.29.1": ">=7.29.1 <8.0.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" @@ -40,6 +40,8 @@ overrides: "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" patchedDependencies: "tar@7.5.22": "patches/tar@7.5.22.patch" diff --git a/server/dashboard/package.json b/server/dashboard/package.json index d2ce90831..051a07edb 100644 --- a/server/dashboard/package.json +++ b/server/dashboard/package.json @@ -37,7 +37,7 @@ "@radix-ui/react-tooltip": "^1.0.7", "@reduxjs/toolkit": "^2.3.0", "@tanstack/react-table": "^8.17.3", - "axios": "^1.18.0", + "axios": "^1.20.0", "class-variance-authority": "^0.7.1", "clsx": "^2.1.0", "cmdk": "^1.0.0", diff --git a/server/dashboard/pnpm-lock.yaml b/server/dashboard/pnpm-lock.yaml index 1fe88f38f..a67dc5898 100644 --- a/server/dashboard/pnpm-lock.yaml +++ b/server/dashboard/pnpm-lock.yaml @@ -8,14 +8,14 @@ overrides: form-data@<4.0.6: '>=4.0.6' prismjs@<1.30.0: '>=1.30.0' uuid@<11.1.1: '>=11.1.1' - 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@>=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' postcss@<8.5.18: '>=8.5.18 <9.0.0' nanoid@<3.3.18: '>=3.3.18 <4.0.0' - sharp@<0.35.0: '>=0.35.0 <0.36.0' + sharp@<0.35.4: '>=0.35.4 <0.36.0' browserslist@<4.28.7: '>=4.28.7 <5.0.0' importers: @@ -98,8 +98,8 @@ importers: specifier: ^8.17.3 version: 8.21.3(react-dom@19.2.7(react@19.2.7))(react@19.2.7) axios: - specifier: ^1.18.0 - version: 1.18.1 + specifier: ^1.20.0 + version: 1.20.0 class-variance-authority: specifier: ^0.7.1 version: 0.7.1 @@ -299,160 +299,160 @@ 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] libc: [glibc] - '@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] libc: [glibc] - '@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] libc: [glibc] - '@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] libc: [glibc] - '@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] libc: [glibc] - '@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] libc: [glibc] - '@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] libc: [musl] - '@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] libc: [musl] - '@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] libc: [glibc] - '@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] libc: [glibc] - '@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] libc: [glibc] - '@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] libc: [glibc] - '@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] libc: [glibc] - '@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] libc: [glibc] - '@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] libc: [musl] - '@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] libc: [musl] - '@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] @@ -1494,8 +1494,8 @@ packages: resolution: {integrity: sha512-s7iGf5GaVMxEG0ENN9x+xTr7GFZCb1ZP/1uATUpCEK2X78nDB3RwbtFCo9pGAf9ru+VwoQ464DkaLEeRM08wJA==} engines: {node: '>=4'} - axios@1.18.1: - resolution: {integrity: sha512-3nTvFlvpn9Zu/RkHUqtc7/+al4UpRW5az71ap5zccp6e8RAYEzhMTecX8Dz1wWDYrPpUoB1HAQEGEAEvUr7S9g==} + axios@1.20.0: + resolution: {integrity: sha512-r8aOh8j9cGKpgQAqpzrUHnSIc6a59Y3Xf/cv8sy1DrHCkZHzQGEuoq1tARk6qSyDdtQGSDgpb9kFlruzPvrgwg==} axobject-query@4.1.0: resolution: {integrity: sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==} @@ -2292,8 +2292,8 @@ packages: js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} - 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 json-buffer@3.0.1: @@ -2832,8 +2832,8 @@ packages: resolution: {integrity: sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==} engines: {node: '>= 0.4'} - 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': '*' @@ -3174,7 +3174,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: @@ -3218,108 +3218,108 @@ snapshots: '@img/colour@1.1.0': optional: true - '@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.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 '@jridgewell/gen-mapping@0.3.13': @@ -4367,7 +4367,7 @@ snapshots: axe-core@4.12.1: {} - axios@1.18.1: + axios@1.20.0: dependencies: follow-redirects: 1.16.0 form-data: 4.0.6 @@ -4897,7 +4897,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 @@ -5310,7 +5310,7 @@ snapshots: js-tokens@4.0.0: {} - js-yaml@4.3.1: + js-yaml@4.3.2: dependencies: argparse: 2.0.1 @@ -5439,7 +5439,7 @@ snapshots: '@next/swc-linux-x64-musl': 15.5.24 '@next/swc-win32-arm64-msvc': 15.5.24 '@next/swc-win32-x64-msvc': 15.5.24 - sharp: 0.35.3(@types/node@22.5.4) + sharp: 0.35.5(@types/node@22.5.4) transitivePeerDependencies: - '@babel/core' - '@types/node' @@ -5852,37 +5852,37 @@ snapshots: es-errors: 1.3.0 es-object-atoms: 1.1.2 - sharp@0.35.3(@types/node@22.5.4): + sharp@0.35.5(@types/node@22.5.4): 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.5.4 optional: true diff --git a/server/dashboard/pnpm-workspace.yaml b/server/dashboard/pnpm-workspace.yaml index dc4045c9e..2cea6a581 100644 --- a/server/dashboard/pnpm-workspace.yaml +++ b/server/dashboard/pnpm-workspace.yaml @@ -5,12 +5,12 @@ overrides: "form-data@<4.0.6": ">=4.0.6" "prismjs@<1.30.0": ">=1.30.0" "uuid@<11.1.1": ">=11.1.1" - "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@>=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" "postcss@<8.5.18": ">=8.5.18 <9.0.0" "nanoid@<3.3.18": ">=3.3.18 <4.0.0" - "sharp@<0.35.0": ">=0.35.0 <0.36.0" + "sharp@<0.35.4": ">=0.35.4 <0.36.0" "browserslist@<4.28.7": ">=4.28.7 <5.0.0" From 0516f19f721d1b0bbf9171410031cd28fd1c19ac Mon Sep 17 00:00:00 2001 From: Shashidhar Kundur <106020668+shashiKundur1@users.noreply.github.com> Date: Wed, 7 Oct 2026 15:53:25 +0530 Subject: [PATCH 50/61] fix(ts-oss): stop add() from mutating the caller's filters object (#6797) --- mem0-ts/src/oss/src/memory/index.ts | 4 +- .../memory.add-filters-isolation.test.ts | 115 ++++++++++++++++++ 2 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 mem0-ts/src/oss/tests/memory.add-filters-isolation.test.ts diff --git a/mem0-ts/src/oss/src/memory/index.ts b/mem0-ts/src/oss/src/memory/index.ts index 1efbc3e45..42f3ca22e 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 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"]); + }); +}); From d62ce07faceafedd4b10d60704db2b9d89d0afff Mon Sep 17 00:00:00 2001 From: rupak Date: Wed, 7 Oct 2026 16:20:38 +0530 Subject: [PATCH 51/61] fix(vector-store): stop writing service account private key to DEBUG logs in GoogleMatchingEngine (#7506) Co-authored-by: rupak-eng --- mem0/vector_stores/vertex_ai_vector_search.py | 4 +-- .../test_vertex_ai_vector_search.py | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 2 deletions(-) diff --git a/mem0/vector_stores/vertex_ai_vector_search.py b/mem0/vector_stores/vertex_ai_vector_search.py index 0954bf90c..417e1cc00 100644 --- a/mem0/vector_stores/vertex_ai_vector_search.py +++ b/mem0/vector_stores/vertex_ai_vector_search.py @@ -34,7 +34,7 @@ class OutputData(BaseModel): class GoogleMatchingEngine(VectorStoreBase): def __init__(self, **kwargs): """Initialize Google Matching Engine client.""" - logger.debug("Initializing Google Matching Engine with kwargs: %s", kwargs) + logger.debug("Initializing Google Matching Engine with config keys: %s", sorted(kwargs)) # If collection_name is passed, use it as deployment_index_id if deployment_index_id is not provided if "collection_name" in kwargs and "deployment_index_id" not in kwargs: @@ -46,7 +46,7 @@ class GoogleMatchingEngine(VectorStoreBase): try: config = GoogleMatchingEngineConfig(**kwargs) - logger.debug("Config created: %s", config.model_dump()) + logger.debug("Config created with fields: %s", sorted(config.model_dump())) logger.debug("Config collection_name: %s", getattr(config, "collection_name", None)) except Exception as e: logger.error("Failed to validate config: %s", str(e)) diff --git a/tests/vector_stores/test_vertex_ai_vector_search.py b/tests/vector_stores/test_vertex_ai_vector_search.py index 7ef994332..12dc1e0be 100644 --- a/tests/vector_stores/test_vertex_ai_vector_search.py +++ b/tests/vector_stores/test_vertex_ai_vector_search.py @@ -1,3 +1,4 @@ +import logging from unittest.mock import Mock, patch import pytest @@ -165,3 +166,35 @@ def test_error_handling(vector_store, mock_vertex_ai): assert isinstance(exc_info.value, exceptions.InvalidArgument) assert "Invalid request" in str(exc_info.value) + + +def test_debug_logs_never_carry_service_account_key(caplog): + """Regression for #7503: constructor DEBUG lines must not log the inline credential. + + The constructor emits the whole kwargs dict and the validated config dump at + DEBUG; when ``service_account_json`` is passed inline that writes the PEM + private key to the log sink. Constructor diagnostics should name the fields, + never their values. + """ + private_key = "-----BEGIN PRIVATE KEY-----\nFAKE-KEY-MATERIAL-FOR-TEST\n-----END PRIVATE KEY-----\n" + kwargs = { + "project_id": "test-project", + "project_number": "123456789", + "region": "us-central1", + "endpoint_id": "test-endpoint", + "index_id": "test-index", + "deployment_index_id": "test-deployment", + "service_account_json": {"type": "service_account", "private_key": private_key}, + } + + with caplog.at_level(logging.DEBUG, logger="mem0.vector_stores.vertex_ai_vector_search"): + # Fails later at credential load (no network, no valid key); the two + # DEBUG statements under test run before that. + with pytest.raises(Exception): + GoogleMatchingEngine(**kwargs) + + logged = caplog.text + assert private_key not in logged + assert "FAKE-KEY-MATERIAL-FOR-TEST" not in logged + # The diagnostics must stay useful: field names are still logged. + assert "service_account_json" in logged From b7ad69afda6b6ed030347c66d48a13e4de9dec08 Mon Sep 17 00:00:00 2001 From: Kartik Date: Wed, 7 Oct 2026 18:36:15 +0530 Subject: [PATCH 52/61] docs(skills): refresh mem0 skills against SDK 2.2.1 / TS 3.3.1 (#7548) --- docs/migration/platform-v2-to-v3.mdx | 8 +- skills/AGENTS.md | 22 +- skills/mem0-cli/README.md | 2 +- skills/mem0-cli/SKILL.md | 31 +-- .../mem0-cli/references/command-reference.md | 207 ++++++++++++------ skills/mem0-cli/references/configuration.md | 80 ++++--- skills/mem0-cli/references/workflows.md | 81 +++---- skills/mem0-integrate/SKILL.md | 8 +- skills/mem0-integrate/references/pipeline.md | 19 +- .../references/subagent-prompts.md | 3 +- skills/mem0-oss-to-platform/README.md | 2 +- skills/mem0-oss-to-platform/SKILL.md | 60 +++-- .../references/api-mapping.md | 124 +++++++---- .../references/gotchas.md | 80 +++++-- .../references/plan-template.md | 13 +- skills/mem0-test-integration/SKILL.md | 44 ++-- skills/mem0-vercel-ai-sdk/README.md | 6 +- skills/mem0-vercel-ai-sdk/SKILL.md | 58 +++-- .../references/memory-utilities.md | 85 +++---- .../references/provider-api.md | 87 ++++---- .../references/usage-patterns.md | 54 ++--- skills/mem0/SKILL.md | 21 +- skills/mem0/client/differences.md | 15 +- skills/mem0/client/node.md | 185 ++++++++++++---- skills/mem0/client/python.md | 139 +++++++----- skills/mem0/references/api-reference.md | 55 +++-- skills/mem0/references/architecture.md | 45 ++-- skills/mem0/references/features.md | 160 +++++++------- .../mem0/references/integration-patterns.md | 82 +++---- skills/mem0/references/quickstart.md | 12 +- skills/mem0/references/sdk-guide.md | 49 +++-- skills/mem0/references/use-cases.md | 31 +-- skills/mem0/scripts/mem0_doc_search.py | 185 ++++++++-------- 33 files changed, 1239 insertions(+), 814 deletions(-) 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/skills/AGENTS.md b/skills/AGENTS.md index 6e0bbc3f5..6b4d87f04 100644 --- a/skills/AGENTS.md +++ b/skills/AGENTS.md @@ -50,16 +50,20 @@ Everything else, meaning full step mechanics, document templates, and verbatim s Current sizes, longest first: ``` -mem0/references/use-cases.md 720 reference, on demand -mem0-cli/references/command-reference.md 694 reference, on demand -mem0/client/python.md 487 reference, on demand -mem0-integrate/references/pipeline.md 375 reference, on demand -mem0-test-integration/SKILL.md 368 entry point, under budget +mem0-cli/references/command-reference.md 757 reference, on demand +mem0/references/use-cases.md 721 reference, on demand +mem0/client/python.md 522 reference, on demand +mem0/client/node.md 507 reference, on demand +mem0-cli/references/workflows.md 446 reference, on demand +mem0/references/features.md 406 reference, on demand +mem0/references/integration-patterns.md 403 reference, on demand +mem0-test-integration/SKILL.md 386 entry point, under budget +mem0-integrate/references/pipeline.md 380 reference, on demand mem0-integrate/SKILL.md 220 entry point -mem0/SKILL.md 193 entry point -mem0-vercel-ai-sdk/SKILL.md 192 entry point -mem0-cli/SKILL.md 169 entry point -mem0-oss-to-platform/SKILL.md 120 entry point +mem0-vercel-ai-sdk/SKILL.md 210 entry point +mem0/SKILL.md 194 entry point +mem0-cli/SKILL.md 170 entry point +mem0-oss-to-platform/SKILL.md 132 entry point ``` `mem0-integrate` is the one skill that needed splitting: it was 620 lines, now diff --git a/skills/mem0-cli/README.md b/skills/mem0-cli/README.md index 4333116e8..35e00c97d 100644 --- a/skills/mem0-cli/README.md +++ b/skills/mem0-cli/README.md @@ -6,7 +6,7 @@ Manage memories from the terminal using the [Mem0 CLI](https://docs.mem0.ai/plat When installed, Claude can: -- **Run mem0 commands** correctly in your terminal (add, search, list, get, update, delete, import, config, init, status, entity, event) +- **Run mem0 commands** correctly in your terminal (add, search, list, get, update, delete, import, config, init, identify, whoami, status, entity, event, agent-rush, version, help) - **Construct complex invocations** with the right flags, scoping, filters, and output formats - **Pipe and script** mem0 commands in shell workflows, CI/CD pipelines, and agent loops - **Debug issues** like missing API keys, entity scoping conflicts, and async processing delays diff --git a/skills/mem0-cli/SKILL.md b/skills/mem0-cli/SKILL.md index 10afd3429..8b420a9f5 100644 --- a/skills/mem0-cli/SKILL.md +++ b/skills/mem0-cli/SKILL.md @@ -12,9 +12,10 @@ description: > license: Apache-2.0 metadata: author: mem0ai - version: "1.1.0" + version: "1.2.0" category: ai-memory tags: "cli, terminal, memory, ai, command-line" + mem0_tested_versions: "mem0-cli (PyPI) >=0.2.13,<0.3.0; @mem0/cli (npm) >=0.2.14,<0.3.0; mem0ai (PyPI) >=2.0.0,<3.0.0; mem0ai (npm) >=3.0.0,<4.0.0" compatibility: Node.js 18+ (npm install -g @mem0/cli) or Python 3.10+ (pip install mem0-cli), MEM0_API_KEY env var --- @@ -34,7 +35,7 @@ npm install -g @mem0/cli pip install mem0-cli ``` -Both packages install a `mem0` binary with identical commands, options, and output formats. +Both packages install a `mem0` binary with the same commands, options, and output formats (see [Node and Python Differences](#node-and-python-differences) for the exceptions). ## Setup @@ -105,7 +106,7 @@ mem0 delete --all --user-id alice --force ## Agent / JSON Mode -Use `--json` or `--agent` to get structured output suitable for LLM consumption. Every command wraps its response in a standard envelope: +Use `--json` or `--agent` to get structured output suitable for LLM consumption. Place the flag before the subcommand (`mem0 --json search "q"`), which works in both CLIs. Data commands (add, search, list, get, update, delete, import, config, entity, event, status) wrap their response in a standard envelope: ```json { @@ -114,7 +115,6 @@ Use `--json` or `--agent` to get structured output suitable for LLM consumption. "duration_ms": 245, "scope": { "user_id": "alice" }, "count": 3, - "error": null, "data": [ { "id": "mem-abc", "memory": "User prefers dark mode", "score": 0.92 } ] @@ -126,30 +126,31 @@ On error: { "status": "error", "command": "search", - "error": "Authentication failed. Your API key may be invalid or expired.", + "error": "Invalid or expired API key.", "data": null } ``` -The `--agent` flag is an alias for `--json`. Both write spinners and progress to stderr so stdout is always clean, parseable JSON. +The `--agent` flag is an alias for `--json` (except on `mem0 init`, where `--agent` is the Agent Mode bootstrap flag). Both write spinners and progress to stderr so stdout is clean, parseable JSON (the one exception is Node `import`, see below). Optional keys: `duration_ms`, `scope`, `count` appear only where relevant, and `mem0_notice` appears when the platform flags an unclaimed Agent Mode account. -## Node and Python Parity +## Node and Python Differences -Both the Node.js (`@mem0/cli`) and Python (`mem0-cli`) CLIs are implemented from the same specification (`cli-spec.json`). They share: +Both the Node.js (`@mem0/cli`) and Python (`mem0-cli`) CLIs share the command set, flags, entity ID resolution, filter building, and the JSON envelope. Choose whichever runtime you already have installed. Known differences: -- Identical command names, arguments, and flags -- Identical output formats (text, json, table, quiet) -- Identical entity ID resolution, graph tri-state, filter building -- Identical error messages and exit codes - -Choose whichever runtime you already have installed. The behavior is the same. +- **`--json` / `--agent` placement:** Python accepts the flag anywhere on the command line. Node reads it only as a global option, so put it before the subcommand (`mem0 --json list`). `mem0 init --json` and `mem0 help --json` work after the subcommand in both. For the Agent Mode bootstrap, Node starts it only from `init --agent` or `init --json` (a root-level `mem0 --json init` or `mem0 --agent init` does not start it, and without an agent runtime env var it fails with the non-TTY error), while Python also accepts those root-level forms. `mem0 init --agent --json` works in both. +- **`--limit`:** `mem0 search --limit` is a Python-only alias for `--top-k`. +- **Agent-mode `delete --all` data:** Python returns `{"deleted": true}` (plus scope for `--project`); Node returns the raw API result. +- **`import` JSON output:** Python prints the envelope with `scope`. Node omits `scope` and writes the `Importing memories... n/n` progress line to stdout before the JSON, so only Python's output pipes cleanly to `jq`. +- **Message text:** The empty-search error (`Search query cannot be empty.` in Python, `No query provided...` in Node) and the delete dry-run footers differ slightly. ## Common Edge Cases - **Async processing delay:** After `mem0 add`, memories process asynchronously. Wait 2-3 seconds before searching for newly added content. Use `mem0 event list` to check processing status. - **`--all` vs `--entity` delete modes:** `mem0 delete --all -u alice` deletes all memories for user alice. `mem0 delete --entity -u alice` deletes the entity itself AND all its memories (cascade). These are mutually exclusive modes. +- **`--dry-run` in `--json`/`--agent` mode:** `mem0 --json delete --all --dry-run` still requires `--force`, then prints nothing and deletes nothing (exit 0). Node also prints nothing for single and `--entity` dry runs. Use text mode to see the preview. +- **`--dry-run` does not protect `--all --project`:** `mem0 delete --all --project --dry-run` ignores the flag and deletes every memory in the project. Never use `--dry-run` to preview a project-wide delete. - **Entity ID resolution:** If you pass any explicit scope flag (e.g. `--user-id`), the CLI uses ONLY the explicit IDs and ignores config defaults. If no scope flags are given, all configured defaults apply. -- **Stdin detection:** When no text argument is provided and input is piped (not a TTY), the CLI reads from stdin. Works with `add`, `search`, and `update`. +- **Stdin detection:** When no text argument is provided and stdin is a pipe or a redirected file (a plain non-TTY is not enough), the CLI reads from stdin. Works with `add`, `search`, and `update`. In `--json`/`--agent` mode `add` never reads stdin (Python also skips it for `search` and `update`), so pass the text as an argument there. ## References diff --git a/skills/mem0-cli/references/command-reference.md b/skills/mem0-cli/references/command-reference.md index 16f85ed50..36346f049 100644 --- a/skills/mem0-cli/references/command-reference.md +++ b/skills/mem0-cli/references/command-reference.md @@ -1,20 +1,25 @@ # Mem0 CLI Command Reference -Complete reference for every command, argument, flag, and output mode in the mem0 CLI. Both the Node.js (`@mem0/cli`) and Python (`mem0-cli`) implementations are identical in behavior. +Complete reference for every command, argument, flag, and output mode in the mem0 CLI. Both the Node.js (`@mem0/cli`) and Python (`mem0-cli`) implementations share the same commands and flags. Where they differ, the difference is called out inline. --- ## Global Options -These options are available on every command: +Only these two options are global: + +| Flag | Type | Description | +|------|------|-------------| +| `--json` / `--agent` | boolean | Agent mode: wrap output in a structured JSON envelope on stdout. Spinners and progress go to stderr (except Node `import`, see its section). Put it before the subcommand (`mem0 --json list`); Python also accepts it anywhere. On `mem0 init`, `--agent` is the Agent Mode bootstrap flag instead (use `--json` there, after the subcommand). | +| `--version` | boolean | Print version and exit. | + +These options are declared per command (not global) on `add`, `search`, `get`, `list`, `update`, `delete`, `import`, `status`, `entity list`, `entity delete`, `event list` and `event status`. `config show` takes only `-o`, and `init` takes only `--api-key`. | Flag | Type | Description | |------|------|-------------| -| `--json` / `--agent` | boolean | Agent mode: wrap all output in a structured JSON envelope on stdout. Spinners and progress go to stderr. | | `-o, --output ` | string | Output format. Supported values vary per command (see matrix below). | | `--api-key ` | string | Override the API key for this invocation. Takes precedence over env var and config file. | | `--base-url ` | string | Override the API base URL (default: `https://api.mem0.ai`). | -| `--version` | boolean | Print version and exit. | --- @@ -41,11 +46,12 @@ Interactive setup wizard. Configures API key and default user ID. **Behavior:** -- If `~/.mem0/config.json` already exists with an API key, warns and asks for confirmation (or errors in non-TTY unless `--force` is set). -- **Email login flow** (`--email`): sends a 6-digit code to the email via `POST /api/v1/auth/email_code/`. If `--code` is also given, verifies immediately. On success, saves API key, org_id, and project_id. Cannot be combined with `--api-key`. -- **API key flow**: if both `--api-key` and `--user-id` are given, runs fully non-interactively. Otherwise prompts for missing values. -- **Agent Mode flow** (`--agent`): POSTs to `/api/v1/auth/agent_mode/`, mints a shadow API key in <5s with no email required. Pass `--agent-caller ` to attribute the signup to your AI agent identity. If omitted, run `mem0 identify ` afterward. -- In non-TTY without sufficient flags, prints a usage hint and exits with error. +- If `~/.mem0/config.json` already exists with an API key, warns and asks for confirmation. In non-TTY it errors with "Existing config would be overwritten." unless `--force` is set. The Agent Mode path (below) runs before this check. +- **Email login flow** (`--email`): sends a 6-digit code to the email via `POST /api/v1/auth/email_code/`. If `--code` is also given, skips sending and verifies immediately via `/api/v1/auth/email_code/verify/`. In non-TTY without `--code`, the code is sent and the command then errors; re-run with `--code`. On success, saves the API key, `user_email`, and `created_via: "email"`, and sets the default user ID to `--user-id`, else `$USER`/`$USERNAME`, else `mem0-cli`. Cannot be combined with `--api-key`. `--code` without `--email` is an error. +- **Claim flow** (`--email` while the existing config is an unclaimed Agent Mode key): runs the same code flow but claims the existing key to that email. The API key value does not change and memories are kept. +- **API key flow**: if both `--api-key` and `--user-id` are given, runs fully non-interactively (and validates the key against the API). In non-TTY, `--api-key` alone is enough (the user ID defaults to `$USER`/`$USERNAME`/`mem0-cli`). In a TTY with no flags, prompts for the auth method (email or API key), then for the missing values. +- **Agent Mode flow** (`init --agent`, `init --json`, or an agent runtime env var such as `CLAUDECODE` or `CURSOR_AGENT`, with no `--api-key`/`--email`; Python also enters it on a global `mem0 --json init` or `mem0 --agent init`, Node does not): first reuses a valid `MEM0_API_KEY` or a valid key already in config (no new key is minted). Otherwise POSTs to `/api/v1/auth/agent_mode/` and mints a shadow API key in <5s with no email required; the generated `user_` becomes `defaults.user_id`. Limited to 5 signups per day per network. Pass `--agent-caller ` to attribute the signup to your AI agent identity. If omitted, run `mem0 identify ` afterward. +- In non-TTY without `--api-key`, `--email`, or an agent signal, prints "Non-interactive terminal detected and --api-key is required." and exits with error. **Examples:** ```bash @@ -61,16 +67,16 @@ mem0 init --agent --agent-caller claude-code # AI agent self-identifies during ### `mem0 identify` -Tag your active Agent Mode key with the AI agent that's using it. Run this once after `mem0 init --agent` if you didn't pass `--agent-caller`. Idempotent — re-running just overwrites the value. +Tag your active Agent Mode key with the AI agent that's using it. Run this once after `mem0 init --agent` if you didn't pass `--agent-caller`. Idempotent: re-running just overwrites the value. **Usage:** `mem0 identify ` -**Argument:** `` — the AI agent identity (e.g. `claude-code`, `cursor`, `codex`, `cline`, `aider`, or a custom string). +**Argument:** ``: the AI agent identity (e.g. `claude-code`, `cursor`, `codex`, `cline`, `aider`, or a custom string). **Behavior:** - PATCHes `/api/v1/auth/agent_mode/caller/` with `Authorization: Token ` and body `{agent_caller}`. -- Only works on unclaimed agent-mode keys (`platform.agent_mode=true` in config). +- Only works on unclaimed agent-mode keys (`platform.agent_mode=true` in config). Errors with "No API key configured." if no key is set, or "This command only works on unclaimed agent-mode keys." otherwise. - Backend sanitizes the value: lowercases, drops anything outside `[a-z0-9._/-]`, truncates to 32 chars. **Examples:** @@ -82,6 +88,45 @@ mem0 identify my-custom-bot --- +### `mem0 whoami` + +Print your AGENTRUSH identifier (`platform.default_user_id` from config). Errors with "No default_user_id found. Run `mem0 init --agent` first." if none is stored. + +**Usage:** `mem0 whoami` + +--- + +### `mem0 agent-rush add|search` + +Commands for the AGENTRUSH event game. Memories are public to other players, so never include real names, emails, secrets, or PII. + +**Usage:** `mem0 agent-rush add ` and `mem0 agent-rush search ` + +- `add`: content must be 50-1000 characters with no URLs. The server requires 3 searches before adding and caps each key at 3 lifetime searches and 3 lifetime adds. +- Requires an API key from config or `MEM0_API_KEY` (otherwise errors with "Not initialized. Run `mem0 init --agent` first."). Node joins unquoted words into one string; Python takes a single quoted argument. + +**Examples:** +```bash +mem0 agent-rush search "constraint satisfaction" +mem0 agent-rush add "I enjoy solving constraint-satisfaction problems and writing small solvers." +``` + +--- + +### `mem0 version` + +Print the CLI version. `mem0 --version` does the same. + +--- + +### `mem0 help` + +**Usage:** `mem0 help [--json]` + +Prints the command overview. `--json` (or global `--json`/`--agent`) prints a machine-readable command spec. In both CLIs this spec is hand-maintained and can lag behind the real option list, so trust `mem0 --help` and this reference over it. + +--- + ### `mem0 add` Add a memory from text, messages, file, or stdin. @@ -106,10 +151,17 @@ Add a memory from text, messages, file, or stdin. | `-f, --file ` | path | - | Read messages from a JSON file. | | `-m, --metadata ` | string | - | Custom metadata as JSON object (e.g. `'{"source":"cli"}'`). | | `--no-infer` | boolean | false | Skip inference; store the text verbatim. | -| `--categories ` | string | - | Categories as JSON array or comma-separated string. | +| `--expires ` | string | - | Expiration date (YYYY-MM-DD). Must be in the future. | +| `--immutable` | boolean | false | Accepted but has no effect on v3: the memory can still be updated and no marker is stored. | +| `--custom-instructions ` | string | - | Custom instructions for fact extraction. | +| `--agent-custom-instructions ` | string | - | Extraction instructions for agent-scoped memories, overriding the project setting. | +| `--custom-categories ` | string | - | Custom categories as a JSON array of `{name: description}` objects. | +| `--structured-data-schema ` | string | - | Schema for structured data extraction, as JSON. | +| `--timestamp ` | integer | - | Unix timestamp for the memory. | +| `--categories ` | string | - | Rejected with an error. Use `--custom-categories` instead. | | `-o, --output ` | string | `text` | Output format: `text`, `json`, `quiet`. | -**Input priority:** `--file` > `--messages` > text argument > stdin (if piped and no text). +**Input priority:** `--file` > `--messages` > text argument > stdin (if piped or redirected, no text, and not in `--json`/`--agent` mode). Text content is wrapped as `[{"role": "user", "content": ""}]` before sending to the API. Messages from `--messages` or `--file` are sent as-is. @@ -130,9 +182,8 @@ mem0 add "allergic to nuts" -u alice -m '{"source":"onboarding"}' mem0 add --messages '[{"role":"user","content":"I like Python"}]' -u alice mem0 add --file conversation.json -u alice -o json echo "I prefer dark mode" | mem0 add -u alice -mem0 add "temporary note" -u alice --expires 2025-12-31 -mem0 add "important fact" -u alice --immutable -mem0 add "uses vim" -u alice --categories "tools,preferences" +mem0 add "temporary note" -u alice --expires 2027-12-31 +mem0 add "uses vim" -u alice --custom-categories '[{"tools":"Editors and developer tooling"}]' ``` --- @@ -147,7 +198,7 @@ Search memories by semantic query. | Name | Type | Required | Description | |------|------|----------|-------------| -| `query` | string | Yes | The search query. Falls back to stdin if piped. | +| `query` | string | Yes | The search query. Falls back to stdin if piped or redirected (Python skips this in `--json`/`--agent` mode; Node does not). | **Options:** @@ -157,11 +208,15 @@ Search memories by semantic query. | `--agent-id ` | string | - | Filter by agent. | | `--app-id ` | string | - | Filter by app. | | `--run-id ` | string | - | Filter by run. | -| `-k, --top-k, --limit ` | integer | 10 | Maximum number of results to return. | -| `--threshold ` | float | 0.1 | Minimum similarity score (0.0 to 1.0). | +| `-k, --top-k ` | integer | 10 | Maximum number of results to return (must be >= 1). Python also accepts `--limit` as an alias. | +| `--threshold ` | float | 0.3 | Minimum similarity score (0.0 to 1.0), applied before hybrid score blending, so a returned item's displayed `score` can be lower than this value. | | `--rerank` | boolean | false | Enable reranking for improved relevance (Platform only). | -| `--filter ` | string | - | Advanced filter expression as JSON (AND/OR operators). | -| `--fields ` | string | - | Comma-separated list of fields to return. | +| `--keyword` | boolean | false | Sent to the API as `keyword_search` but not applied by v3 search, which always blends keyword matching into hybrid scoring. | +| `--filter ` | string | - | Advanced filter expression as JSON. If it contains `AND` or `OR` it is sent as-is and entity IDs (including config defaults) are not merged in. | +| `--fields ` | string | - | Comma-separated list of fields to return. Sent to the API but not applied by v3 search. | +| `--show-expired` | boolean | false | Include expired memories. | +| `--reference-date ` | string | - | Reference date for relative queries (YYYY-MM-DD or unix timestamp). | +| `--latest-only` | boolean | false | Only return the latest version of each memory. | | `-o, --output ` | string | `text` | Output format: `text`, `json`, `table`. | **Examples:** @@ -171,6 +226,8 @@ mem0 search "tools" -u alice -o json -k 5 mem0 search "dietary restrictions" -u alice --threshold 0.5 mem0 search "project setup" -u alice --rerank mem0 search "preferences" -u alice --filter '{"categories":{"contains":"food"}}' +mem0 search "invoices" -u alice --filter '{"AND":[{"user_id":"alice"},{"categories":{"in":["work"]}}]}' +mem0 search "plans" -u alice --latest-only echo "preferences" | mem0 search -u alice ``` @@ -221,6 +278,8 @@ List memories with optional filters and pagination. | `--category ` | string | - | Filter by category. | | `--after ` | string | - | Created after (YYYY-MM-DD). | | `--before ` | string | - | Created before (YYYY-MM-DD). | +| `--show-expired` | boolean | false | Include expired memories. | +| `--latest-only` | boolean | false | Only return the latest version of each memory. | | `-o, --output ` | string | `table` | Output format: `text`, `json`, `table`. | **Examples:** @@ -244,13 +303,15 @@ Update a memory's text or metadata. | Name | Type | Required | Description | |------|------|----------|-------------| | `memory_id` | string | Yes | The UUID of the memory to update. | -| `text` | string | No | New memory text. Falls back to stdin if piped and no `--metadata`. | +| `text` | string | No | New memory text. Falls back to stdin if piped or redirected (Python skips this in `--json`/`--agent` mode; Node does not). | **Options:** | Flag | Type | Default | Description | |------|------|---------|-------------| | `-m, --metadata ` | string | - | Update metadata as JSON object. | +| `--expires ` | string | - | Expiration date (YYYY-MM-DD). Must be in the future. | +| `--timestamp ` | integer | - | Unix timestamp for the memory. | | `-o, --output ` | string | `text` | Output format: `text`, `json`, `quiet`. | **Examples:** @@ -282,8 +343,9 @@ Delete a memory, all memories matching a scope, or an entity. This command has t | `--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 (sends wildcard IDs). | -| `--dry-run` | boolean | false | Show what would be deleted without actually deleting. | -| `--force` | boolean | false | Skip confirmation prompt. | +| `--dry-run` | boolean | false | Show what would be deleted without actually deleting. Ignored by `--all --project`, which deletes (see Dry-run behavior). | +| `--force` | boolean | false | Skip confirmation prompt (`--all` and `--entity` only). Required for those modes in `--json`/`--agent` mode. | +| `--delete-linked` | boolean | false | Single-memory mode: also delete memories linked to this memory. | | `-u, --user-id ` | string | - | Scope to user. | | `--agent-id ` | string | - | Scope to agent. | | `--app-id ` | string | - | Scope to app. | @@ -296,14 +358,17 @@ Delete a memory, all memories matching a scope, or an entity. This command has t 2. **Bulk delete:** `mem0 delete --all [scope flags]` -- deletes all memories matching the scope. Add `--project` to wipe all memories project-wide (sends wildcard `*` entity IDs). 3. **Entity cascade:** `mem0 delete --entity [scope flags]` -- deletes the entity itself AND all its memories. -You cannot combine `` with `--all` or `--entity`, and you cannot combine `--all` with `--entity`. If none of these are provided, the command prints a usage hint and exits with an error. +You cannot combine `` with `--all` or `--entity`, and you cannot combine `--all` with `--entity`. If none of these are provided, the command prints an error and exits 1. + +**Entity IDs:** `--all` resolves IDs like `search` (explicit flags only, else config defaults). Single delete and `--entity` use only explicit flags, and `--entity` requires at least one. **Dry-run behavior:** -- Single: fetches the memory, displays it, prints "No changes made." -- `--all`: lists matching memories with count, prints "No changes made." -- `--entity`: shows the affected scope without deleting. +- Single: fetches the memory, displays it, and prints "No changes made." (Python: "No changes made (dry run)."). Node also prints "Would delete memory : ". +- `--all`: lists matching memories, prints "Would delete N memories." and the "No changes made" line. In `--json`/`--agent` mode `--all` still requires `--force` even with `--dry-run`, and the command then exits 0 with no output and deletes nothing. Use text mode to see the preview. +- `--entity`: prints "Would delete entity and all its memories." and the "No changes made" line. +- **Warning:** `--all --project` does not honor `--dry-run`. It skips the preview and deletes every memory in the project (after the confirmation, or immediately with `--force`). Never pass `--dry-run` to `--all --project` expecting a preview. This is a known CLI bug in both CLIs, not intended behavior, so do not rely on it. To preview, run `mem0 delete --all --dry-run` per scope (for example `-u alice`) instead. -**Confirmation:** Without `--force`, all destructive modes prompt `[y/N]`. With `--all --project`, the prompt explicitly warns about project-wide deletion. +**Confirmation:** Without `--force`, `--all` and `--entity` prompt `[y/N]`. Single-memory delete never prompts and ignores `--force`. With `--all --project`, the prompt explicitly warns about project-wide deletion and the scope flags are ignored. **`--all --project` behavior:** Sends `DELETE /v1/memories/` with `user_id=*&agent_id=*&app_id=*&run_id=*`. The API returns an async response. The CLI prints "Deletion started. Memories will be removed in the background." @@ -339,7 +404,7 @@ Import memories from a JSON file. | `--agent-id ` | string | - | Override agent ID for all imported items. | | `-o, --output ` | string | `text` | Output format: `text`, `json`. | -**File format:** A JSON array (or single object) where each item has a `memory`, `text`, or `content` field for the text, plus optional `user_id`, `agent_id`, and `metadata` fields. CLI-provided `--user-id` and `--agent-id` override per-item values. +**File format:** A JSON array (or single object) where each item has a `memory`, `text`, or `content` field for the text, plus optional `user_id`, `agent_id`, and `metadata` fields. `--user-id` and `--agent-id` override per-item values, and so do the config defaults when neither flag is given. Items with no text count as failed. **Import format example:** ```json @@ -350,7 +415,7 @@ Import memories from a JSON file. ] ``` -**Behavior:** Iterates through items, calling the add API for each. Displays progress and reports `added` and `failed` counts on completion. +**Behavior:** Iterates through items, calling the add API for each. Displays progress and reports `added` and `failed` counts on completion (text mode writes the summary to stderr in Python and to stdout in Node). In JSON mode the Python CLI sends progress to stderr and includes `scope` in the envelope; the Node CLI writes the progress line to stdout before the JSON (so `| jq` fails) and omits `scope`. Only `-u`, `--agent-id`, `-o`, `--api-key` and `--base-url` are accepted. **Examples:** ```bash @@ -372,6 +437,8 @@ Display current configuration with secrets redacted. |------|------|---------|-------------| | `-o, --output ` | string | `text` | Output format: `text`, `json`. | +**Behavior:** `-o json` (or agent mode) returns the standard envelope with `data` shaped as `{"defaults": {"user_id", "agent_id", "app_id", "run_id"}, "platform": {"api_key", "base_url"}}`. The API key is redacted and unset defaults are `null`. + **Examples:** ```bash mem0 config show @@ -392,9 +459,9 @@ Get a single configuration value. |------|------|----------|-------------| | `key` | string | Yes | Dotted config key (e.g. `platform.api_key`, `defaults.user_id`). | -**Valid keys:** `platform.api_key`, `platform.base_url`, `defaults.user_id`, `defaults.agent_id`, `defaults.app_id`, `defaults.run_id`. +**Valid keys:** `platform.api_key`, `platform.base_url`, `platform.user_email`, `defaults.user_id`, `defaults.agent_id`, `defaults.app_id`, `defaults.run_id`, plus the short forms `api_key`, `base_url`, `user_email`, `user_id`, `agent_id`, `app_id`, `run_id`. Python also resolves any other field path in the config file (e.g. `platform.agent_mode`); Node does not. -API key values are always redacted in output. +An unknown key prints "Unknown config key: " and still exits 0. API key values are always redacted in output. `config get` and `config set` emit a `{key, value}` envelope only in `--json`/`--agent` mode. **Examples:** ```bash @@ -427,19 +494,6 @@ mem0 config set platform.base_url https://api.mem0.ai --- -### `mem0 config clear` - -Clear the configuration file. Removes `~/.mem0/config.json`. - -**Usage:** `mem0 config clear` - -**Examples:** -```bash -mem0 config clear -``` - ---- - ### `mem0 entity list` List all entities of a given type. @@ -507,9 +561,9 @@ List recent background processing events. | Flag | Type | Default | Description | |------|------|---------|-------------| -| `-o, --output ` | string | `table` | Output format: `text` (table), `json`. | +| `-o, --output ` | string | `table` | Output format: `table`, `json`. | -**Behavior:** Fetches all events for the project. Displays a table with columns: Event ID (first 8 chars), Type, Status (color-coded), Latency, Created. Status values: `PENDING`, `SUCCEEDED`, `FAILED`, `PROCESSING`. +**Behavior:** Fetches all events for the project. Displays a table with columns: Event ID (first 8 chars), Type, Status (color-coded), Latency, Created. Status values: `PENDING`, `RUNNING`, `SUCCEEDED`, `FAILED`. **Examples:** ```bash @@ -585,16 +639,15 @@ mem0 status -o json ## Agent Mode Envelope Format -When `--json` or `--agent` is passed, every command wraps its output in a consistent JSON envelope on stdout: +When `--json` or `--agent` is passed, data commands (add, search, list, get, update, delete, import, config, entity, event, status) wrap their output in a consistent JSON envelope on stdout: ```json { "status": "success", "command": "", "duration_ms": 245, - "scope": { "user_id": "alice", "agent_id": null }, + "scope": { "user_id": "alice" }, "count": 10, - "error": null, "data": { ... } } ``` @@ -603,38 +656,47 @@ When `--json` or `--agent` is passed, every command wraps its output in a consis - `status`: `"success"` or `"error"`. - `command`: The command name (e.g. `"search"`, `"add"`, `"list"`). - `duration_ms`: Elapsed time in milliseconds (optional). -- `scope`: Active entity scope, omitted if empty (optional). +- `scope`: Active entity scope with empty values dropped, omitted if empty (optional). - `count`: Number of results, where applicable (optional). -- `error`: Error message string, or `null` on success. -- `data`: Command-specific response data, or `null` on error. +- `data`: Command-specific response data (`null` on error). +- `error`: Present only on error envelopes (see below); success envelopes have no `error` key. +- `mem0_notice`: Present when the platform flags an unclaimed Agent Mode account (optional). **Sanitized data fields per command in agent mode:** | Command | `data` shape | |---------|-------------| -| `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}]` | +| `add` | `[{id, event}]` for synchronous results (`--no-infer`) or `[{status, event_id}]` for PENDING (default) | +| `search` | `[{id, memory, score, created_at, categories, expiration_date}]` | +| `list` | `[{id, memory, created_at, categories, expiration_date}]` | +| `get` | `{id, memory, created_at, updated_at, categories, metadata, expiration_date}` | +| `update` | `{id, memory, expiration_date}` | +| `delete` (single) | `{id, deleted}` | +| `delete --all` | `{deleted}`, with `scope` in the envelope (Node: raw API result) | +| `delete --all --project` | `{deleted, scope: "project"}` (Node: raw API result) | +| `delete --entity` / `entity delete` | `{deleted}` | +| `entity list` | `[{name, type}]` | | `event list` | `[{id, event_type, status, latency, created_at}]` | | `event status` | `{id, event_type, status, latency, created_at, updated_at, results}` | | `status` | `{connected, backend, base_url}` | -| `config show` | Config object (keys redacted) | -| `import` | `{added, failed, duration_s}` | +| `config show` | `{defaults: {user_id, agent_id, app_id, run_id}, platform: {api_key, base_url}}` (key redacted) | +| `config get` / `config set` | `{key, value}` (agent mode only) | +| `import` | `{added, failed}` | + +**`-o json` without agent mode:** `list`, `status`, `import` and `config show` print the same envelope. `add`, `search`, `get`, `update`, `delete` and `entity delete` print the raw API JSON instead. `entity list`, `event list` and `event status` print the envelope in Node and raw JSON in Python. **Error envelope:** ```json { "status": "error", "command": "search", - "error": "Authentication failed. Your API key may be invalid or expired.", + "error": "Invalid or expired API key.", "data": null } ``` +The `error` text varies by CLI and failure point (for example a 401 after the upfront key check passes returns "Authentication failed. Your API key may be invalid or expired."). Branch on `status`, not on the message. + --- ## Entity ID Resolution @@ -652,19 +714,20 @@ else: use all configured defaults ``` -This applies to commands with `resolveIds: true`: `add`, `search`, `list`, `delete`, `import`. +This applies to `add`, `search`, `list`, `delete --all`, and `import` (user and agent IDs only). Single `delete` and `entity delete` use only explicitly passed flags. --- ## Filter Building -For `search` and `list`, entity IDs and additional filters are composed into the API filter structure: +For `search` and `list`, entity IDs and additional filters are composed into the API filter structure. `--filter` exists only on `search`; `list` builds its extra filters from `--category`, `--after` and `--before`. -1. If the user provides a pre-built filter via `--filter` containing `AND` or `OR` keys, it is passed through to the API as-is. +1. If the user provides a pre-built filter via `--filter` containing `AND` or `OR` keys, it is passed through to the API as-is (entity IDs, including config defaults, are not merged in). 2. Otherwise, the CLI builds an array of AND conditions: - Each entity ID becomes a condition: `{"user_id": "alice"}`, etc. - - Category filters: `{"categories": {"contains": ""}}`. - - Date filters: `{"created_at": {"gte": "YYYY-MM-DD"}}` and/or `{"created_at": {"lte": "YYYY-MM-DD"}}`. + - A `--filter` without `AND`/`OR` contributes each of its top-level keys as a condition. + - Category filters (`list`): `{"categories": {"contains": ""}}`. + - Date filters (`list`): one condition `{"created_at": {"gte": "YYYY-MM-DD", "lte": "YYYY-MM-DD"}}`, with only the bounds you passed. 3. If exactly 1 condition: sent as a single object (no wrapping). 4. If 2+ conditions: wrapped as `{"AND": [condition1, condition2, ...]}`. 5. If 0 conditions: no filter sent. @@ -687,8 +750,8 @@ For `search` and `list`, entity IDs and additional filters are composed into the | `config set` | msg | - | - | - | msg | | `entity list` | - | Y | Y | - | `table` | | `entity delete` | Y | Y | - | Y | `text` | -| `event list` | Y (table) | Y | - | - | `table` | +| `event list` | - | Y | Y | - | `table` | | `event status` | Y | Y | - | - | `text` | | `status` | Y | Y | - | - | `text` | -All commands additionally support agent mode (`--json`/`--agent`) which overrides the output format with the JSON envelope. +Agent mode (`--json`/`--agent`) overrides the output format with the JSON envelope for all data commands above (it applies to `config get` and `config set` too). See the envelope section for how `-o json` differs from agent mode. diff --git a/skills/mem0-cli/references/configuration.md b/skills/mem0-cli/references/configuration.md index 0c5484cfc..51a09ca38 100644 --- a/skills/mem0-cli/references/configuration.md +++ b/skills/mem0-cli/references/configuration.md @@ -13,6 +13,8 @@ Everything about configuring the mem0 CLI: config file format, environment varia The restricted permissions ensure API keys are not world-readable. +Saving an API key also updates an existing `env.MEM0_API_KEY` entry in `~/.claude/settings.json` and existing `export MEM0_API_KEY=...` lines in `~/.zshrc`, `~/.bashrc`, and `~/.bash_profile`. It never creates new entries. + --- ## Config File Schema @@ -28,7 +30,19 @@ The restricted permissions ensure API keys are not world-readable. }, "platform": { "api_key": "", - "base_url": "https://api.mem0.ai" + "base_url": "https://api.mem0.ai", + "user_email": "", + "agent_mode": false, + "created_via": "", + "agent_caller": "", + "claimed_at": "", + "default_user_id": "" + }, + "telemetry": { + "anonymous_id": "" + }, + "agent_rush": { + "acknowledged_at": "" } } ``` @@ -44,12 +58,20 @@ The restricted permissions ensure API keys are not world-readable. | `defaults.run_id` | string | `""` | Default run ID for scoping commands. | | `platform.api_key` | string | `""` | API key for the Mem0 Platform. | | `platform.base_url` | string | `"https://api.mem0.ai"` | Base URL for API requests. | +| `platform.user_email` | string | `""` | Email used for login or claim. Also cached from the ping response during `init`. | +| `platform.agent_mode` | boolean | `false` | `true` while the key is an unclaimed Agent Mode key. | +| `platform.created_via` | string | `""` | How the key was obtained: `agent_mode`, `email`, `api_key`, or `existing_key`. | +| `platform.agent_caller` | string | `""` | Agent name set by `--agent-caller` or `mem0 identify`. | +| `platform.claimed_at` | string | `""` | ISO timestamp once an Agent Mode account is claimed. | +| `platform.default_user_id` | string | `""` | `user_` returned by the Agent Mode bootstrap. Printed by `mem0 whoami`. | +| `telemetry.anonymous_id` | string | `""` | Persistent anonymous ID used for telemetry. | +| `agent_rush.acknowledged_at` | string | `""` | ISO timestamp when the `agent-rush` public-memory warning was acknowledged. | --- ## `mem0 init` Wizard -The `init` command provides two authentication flows: +The `init` command provides three authentication flows: API key, email login, and Agent Mode (see [Agent Mode Init](#agent-mode-init)). ### API Key Flow (default) @@ -65,17 +87,17 @@ mem0 init --api-key m0-xxx --user-id alice 1. Displays the mem0 banner. 2. Checks for existing config. If found with an API key, asks for confirmation to overwrite. -3. Prompts for API key (input masked with `*` characters; supports backspace and Ctrl+U to clear). -4. Prompts for default user ID (default value: `mem0-cli`). -5. Validates the connection by calling the status endpoint. -6. Saves config to `~/.mem0/config.json` with `0600` permissions. -7. Prints success message. +3. Asks how to authenticate (`1` email login, recommended; `2` enter an API key) unless `--api-key` was passed. +4. For option 2, prompts for the API key (input masked with `*` characters; supports backspace and Ctrl+U to clear). +5. Prompts for default user ID (default value: `$USER`, then `$USERNAME`, then `mem0-cli`) unless `--user-id` was passed. +6. Validates the connection by calling the status endpoint. A failed check prints an error but the config is still saved. +7. Saves config to `~/.mem0/config.json` with `0600` permissions. +8. Prints success message. -**Non-interactive mode:** When both `--api-key` and `--user-id` are provided, skips all prompts and saves directly. When running in a non-TTY without both flags, prints an error: +**Non-interactive mode:** When both `--api-key` and `--user-id` are provided, skips all prompts and saves directly. In a non-TTY, `--api-key` alone is enough: the user ID falls back to `$USER`, then `$USERNAME`, then `mem0-cli`. A non-TTY without `--api-key` (and without `--email` or an Agent Mode signal) prints an error: ``` -Non-interactive terminal detected and missing required flags. -Usage: mem0 init --api-key --user-id +Non-interactive terminal detected and --api-key is required. ``` ### Email Login Flow @@ -92,14 +114,23 @@ mem0 init --email alice@company.com --code 482901 1. Sends a 6-digit verification code to the email via `POST /api/v1/auth/email_code/`. 2. If `--code` is provided, verifies immediately. Otherwise prompts for the code. -3. On success: receives API key, org_id, and project_id from the server. -4. Saves to config. Creates a new account if the email is not registered. +3. On success: receives the API key from the server and saves it with `platform.user_email` and `platform.created_via: "email"`. The default user ID is `--user-id`, else `$USER`, else `mem0-cli`. -Cannot be combined with `--api-key`. +Without `--code` in a non-TTY, `init` sends the code and exits with an error telling you to rerun with `--code`. `--code` requires `--email`, and `--email` cannot be combined with `--api-key`. + +**Claiming an Agent Mode account:** If the existing config is an unclaimed Agent Mode key (`platform.agent_mode: true`), `mem0 init --email [--code ]` claims that key for the email instead of minting a new one. The API key stays the same. + +### Agent Mode Init + +```bash +mem0 init --agent --agent-caller --json +``` + +With `init --agent`, `init --json`, or an agent environment variable (such as `CLAUDECODE`, `CURSOR_AGENT`, `CODEX_CLI`, `CLINE`, `AIDER_SESSION`, `GOOSE_AGENT`, `WINDSURF_AGENT`) and no `--api-key` or `--email`, `init` first reuses a valid `MEM0_API_KEY` or a valid key already in the config. Only when there is no valid key does it mint a new Agent Mode key via `POST /api/v1/auth/agent_mode/`, which is limited to 5 signups per day per network. See [command-reference.md](command-reference.md) for the `init` flags and `identify`. ### Force Overwrite -If `~/.mem0/config.json` already exists with an API key, `mem0 init` warns and asks for confirmation. Use `--force` to skip: +If `~/.mem0/config.json` already exists with an API key, `mem0 init` warns and asks for confirmation (in a non-TTY it exits 1 with "Existing config would be overwritten." instead). Use `--force` to skip: ```bash mem0 init --api-key m0-new-key --user-id alice --force @@ -111,7 +142,7 @@ mem0 init --api-key m0-new-key --user-id alice --force ### `mem0 config show` -Displays the current configuration as a formatted table (text mode) or JSON envelope (json mode). API keys are always redacted. +Displays `defaults.*`, `platform.api_key` (redacted), and `platform.base_url` as a formatted table (text mode) or JSON envelope (json mode). Other `platform.*` fields are not shown. ```bash mem0 config show @@ -120,7 +151,7 @@ mem0 config show -o json ### `mem0 config get ` -Reads a single configuration value. The key uses dotted notation. +Reads a single configuration value. The key uses dotted notation or a short alias (`api_key`, `base_url`, `user_email`, `user_id`, `agent_id`, `app_id`, `run_id`). ```bash mem0 config get platform.api_key # prints: m0-x...xxxx (redacted) @@ -130,12 +161,13 @@ mem0 config get defaults.user_id # prints: alice **Valid keys:** - `platform.api_key` - `platform.base_url` +- `platform.user_email` - `defaults.user_id` - `defaults.agent_id` - `defaults.app_id` - `defaults.run_id` -Unknown keys print an error message. +Python also resolves any other field path in the config (for example `platform.created_via`); Node accepts only the keys above and their short aliases. Unknown keys print "Unknown config key: " and still exit 0, so check the output rather than the exit code. In `--json`/`--agent` mode `config get` and `config set` return `{"key": ..., "value": ...}` in the envelope. ### `mem0 config set ` @@ -148,17 +180,9 @@ mem0 config set platform.base_url https://api.mem0.ai **Type coercion:** - Boolean fields accept `true`, `1`, `yes` (case-insensitive) as true. Anything else is false. -- Integer fields are parsed with `parseInt`. +- Integer fields are parsed as integers (Node `parseInt`, Python `int`; Python rejects a non-numeric value as an unknown key). - String fields are stored as-is. -### `mem0 config clear` - -Removes the config file (`~/.mem0/config.json`). - -```bash -mem0 config clear -``` - --- ## Environment Variables @@ -173,6 +197,7 @@ Environment variables override config file values but are overridden by CLI flag | `MEM0_AGENT_ID` | `defaults.agent_id` | string | `""` | | `MEM0_APP_ID` | `defaults.app_id` | string | `""` | | `MEM0_RUN_ID` | `defaults.run_id` | string | `""` | +| `MEM0_TELEMETRY` | n/a | string | enabled. Set to `false` to disable anonymous telemetry. | --- @@ -218,7 +243,10 @@ The `config get` and `config set` commands use dotted key paths. Here is the ful |------------|---------|-------| | `platform.api_key` | platform | api_key | | `platform.base_url` | platform | base_url | +| `platform.user_email` | platform | user_email | | `defaults.user_id` | defaults | user_id | | `defaults.agent_id` | defaults | agent_id | | `defaults.app_id` | defaults | app_id | | `defaults.run_id` | defaults | run_id | + +Short aliases (`api_key`, `base_url`, `user_email`, `user_id`, `agent_id`, `app_id`, `run_id`) map to the same fields. Python additionally resolves any other dotted field path. diff --git a/skills/mem0-cli/references/workflows.md b/skills/mem0-cli/references/workflows.md index 58a441abb..ff8b41aff 100644 --- a/skills/mem0-cli/references/workflows.md +++ b/skills/mem0-cli/references/workflows.md @@ -6,11 +6,11 @@ Practical recipes for using the mem0 CLI in scripts, pipelines, and agent loops. ## Piping Content via Stdin -The CLI reads from stdin when no text argument is provided and input is piped (not a TTY). This works with `add`, `search`, and `update`. +The CLI reads from stdin when no text argument is provided and stdin is a pipe or a redirected file. This works with `add`, `search`, and `update`. It never reads stdin in `--json`/`--agent` mode for `add`, and Python also skips it there for `search` and `update`, so pass the text as an argument in agent mode. **Stdin detection method:** -- Python: `not sys.stdin.isatty()` -- Node: `!process.stdin.isTTY` +- Python: `os.fstat(sys.stdin.fileno())` is a FIFO or a regular file +- Node: `fs.fstatSync(0)` is a FIFO or a regular file ### Add from pipe @@ -69,7 +69,7 @@ The file should be a JSON array where each item has a `memory`, `text`, or `cont ] ``` -CLI-provided `--user-id` overrides per-item `user_id` values. +Items may also carry `agent_id`. CLI-provided `--user-id` and `--agent-id` (or configured defaults) override per-item values. A single JSON object is treated as a one-item array, and items without `memory`, `text`, or `content` are counted as failed. ### Import with JSON output @@ -82,21 +82,24 @@ Output: { "status": "success", "command": "import", - "data": { "added": 42, "failed": 0, "duration_s": 3.14 }, - "duration_ms": 3140 + "duration_ms": 3140, + "scope": { "user_id": "alice" }, + "data": { "added": 42, "failed": 0 } } ``` +This is the Python CLI output. The Node CLI omits `scope` and writes the `Importing memories... n/n` progress line to stdout before the JSON, so its output cannot be piped to `jq`. + --- ## Agent Mode for LLM Consumption -Use `--json` or `--agent` to get structured JSON output suitable for LLM tool calling or agent frameworks. Spinners and progress always go to stderr, keeping stdout clean. +Use `--json` or `--agent` to get structured JSON output suitable for LLM tool calling or agent frameworks. Spinners and progress always go to stderr, keeping stdout clean. Put the flag before the subcommand so it works in both the Python and Node CLIs. ### Search with agent mode ```bash -mem0 search "preferences" --user-id alice --agent +mem0 --agent search "preferences" --user-id alice ``` Output (stdout): @@ -107,7 +110,6 @@ Output (stdout): "duration_ms": 187, "scope": { "user_id": "alice" }, "count": 2, - "error": null, "data": [ { "id": "mem-abc", "memory": "User prefers dark mode", "score": 0.95, "created_at": "2025-01-15T10:00:00Z", "categories": ["preferences"] }, { "id": "mem-def", "memory": "User likes monospace fonts", "score": 0.82, "created_at": "2025-01-15T10:01:00Z", "categories": ["preferences"] } @@ -118,7 +120,7 @@ Output (stdout): ### Add with agent mode ```bash -mem0 add "Uses Python 3.12" --user-id alice --json +mem0 --json add "Uses Python 3.12" --user-id alice ``` ### Error handling in agent mode @@ -126,7 +128,7 @@ mem0 add "Uses Python 3.12" --user-id alice --json Errors also return valid JSON with `"status": "error"`: ```bash -mem0 search "test" --user-id alice --api-key invalid --agent +mem0 --agent search "test" --user-id alice --api-key invalid ``` Output: @@ -134,7 +136,7 @@ Output: { "status": "error", "command": "search", - "error": "Authentication failed. Your API key may be invalid or expired.", + "error": "Invalid or expired API key.", "data": null } ``` @@ -143,30 +145,30 @@ Output: ## JSON Output + jq -Use `--output json` (or `-o json`) for raw JSON output, then pipe to `jq` for processing. +Use `--output json` (or `-o json`) for JSON output, then pipe to `jq` for processing. `search`, `get`, `add`, `update`, and `delete` print the raw API response. `list`, `status`, and `import` print the standard envelope instead, so read the results from `.data`. Piping `import` to `jq` works only with the Python CLI (Node writes its progress line to stdout ahead of the JSON). ### Extract just memory text ```bash -mem0 list --user-id alice --output json | jq '.[] | .memory' +mem0 list --user-id alice --output json | jq '.data[] | .memory' ``` ### Get memory IDs ```bash -mem0 list --user-id alice -o json | jq '.[].id' +mem0 list --user-id alice -o json | jq '.data[].id' ``` ### Count memories ```bash -mem0 list --user-id alice -o json | jq 'length' +mem0 list --user-id alice -o json | jq '.count' ``` ### Filter by category in jq ```bash -mem0 list --user-id alice -o json | jq '[.[] | select(.categories[]? == "preferences")]' +mem0 list --user-id alice -o json | jq '[.data[] | select(.categories[]? == "preferences")]' ``` ### Extract search scores @@ -183,7 +185,7 @@ mem0 search "tools" --user-id alice -o json | jq '.[] | {memory, score}' ```bash # Get IDs, then delete each one -mem0 list --user-id alice -o json | jq -r '.[].id' | while read id; do +mem0 list --user-id alice -o json | jq -r '.data[].id' | while read id; do mem0 delete "$id" --force done ``` @@ -199,7 +201,7 @@ done < memories.txt ### Copy memories between users ```bash -mem0 list --user-id alice -o json | jq -r '.[].memory' | while IFS= read -r mem; do +mem0 list --user-id alice -o json | jq -r '.data[].memory' | while IFS= read -r mem; do mem0 add "$mem" --user-id bob done ``` @@ -216,7 +218,7 @@ mem0 list --user-id alice -o json > alice_memories.json page=1 while true; do result=$(mem0 list --user-id alice -o json --page "$page" --page-size 100) - count=$(echo "$result" | jq 'length') + count=$(echo "$result" | jq '.count') if [ "$count" -eq 0 ]; then break fi @@ -271,7 +273,7 @@ mem0 add "CI run started" --user-id ci-bot ```bash test_summary=$(cat test-results.txt | head -20) -mem0 add "$test_summary" --agent-id ci-bot --metadata '{"type":"test-results"}' --categories "ci,testing" +mem0 add "$test_summary" --agent-id ci-bot --metadata '{"type":"test-results"}' ``` --- @@ -282,11 +284,11 @@ The CLI reads from stdin only when ALL of these conditions are met: 1. No text argument was provided on the command line. 2. For `add`: no `--messages` and no `--file` flag. -3. For `update`: no `--metadata` flag. -4. stdin is piped (not a TTY). +3. stdin is a pipe or a redirected file (a plain non-TTY such as `/dev/null` does not count). +4. The CLI is not in `--json`/`--agent` mode (`add` in both CLIs, `search` and `update` in Python). **This means:** -- `mem0 add --user-id alice` in an interactive terminal will NOT hang waiting for input. It will print a usage error. +- `mem0 add --user-id alice` in an interactive terminal will NOT hang waiting for input. It exits 1 with "No content provided". - `echo "text" | mem0 add --user-id alice` will read "text" from stdin. - `mem0 add "explicit text" --user-id alice` will use the explicit text, even if stdin is piped. @@ -303,8 +305,7 @@ The CLI reads from stdin only when ALL of these conditions are met: ```bash set -e # Exit on error -# This will exit the script if the API key is invalid -mem0 status > /dev/null 2>&1 +mem0 status -o json | jq -e '.data.connected' > /dev/null # Add with error check if mem0 add "test memory" --user-id alice 2>/dev/null; then @@ -317,10 +318,16 @@ fi ### Capture memory ID from add +Default adds are asynchronous and return an `event_id`. Use `--no-infer` for a synchronous add whose `.data[0].id` is the memory id. + ```bash -# Use agent mode to get structured output -result=$(mem0 add "new fact" --user-id alice --agent 2>/dev/null) -memory_id=$(echo "$result" | jq -r '.data[0].id // empty') +event_id=$(mem0 --agent add "new fact" --user-id alice 2>/dev/null | jq -r '.data[0].event_id // empty') +for _ in $(seq 30); do + status=$(mem0 --agent event status "$event_id" | jq -r '.data.status') + [ "$status" = "SUCCEEDED" ] || [ "$status" = "FAILED" ] && break + sleep 2 +done +memory_id=$(mem0 --agent event status "$event_id" | jq -r '.data.results[0].id // empty') if [ -n "$memory_id" ]; then echo "Created memory: $memory_id" fi @@ -330,7 +337,7 @@ fi ```bash # Only add if search returns no results -count=$(mem0 search "dark mode" --user-id alice --agent 2>/dev/null | jq '.count // 0') +count=$(mem0 --agent search "dark mode" --user-id alice 2>/dev/null | jq '.count // 0') if [ "$count" -eq 0 ]; then mem0 add "User prefers dark mode" --user-id alice fi @@ -358,7 +365,7 @@ mem0 list ### Timeout handling -The CLI uses a 30-second timeout for all API requests. For long-running scripts, handle timeouts: +The CLI uses a 30-second timeout for normal API requests (the key-validation ping uses 5 seconds and `init` uses 5, 10 and 30 seconds). For long-running scripts, handle timeouts: ```bash if ! mem0 search "query" --user-id alice -o json 2>/dev/null; then @@ -382,13 +389,13 @@ Or use the event system to poll for completion: ```bash # Add and capture event ID from agent output -result=$(mem0 add "new preference" --user-id alice --agent 2>/dev/null) +result=$(mem0 --agent add "new preference" --user-id alice 2>/dev/null) event_id=$(echo "$result" | jq -r '.data[0].event_id // empty') if [ -n "$event_id" ]; then # Poll until processing completes while true; do - status=$(mem0 event status "$event_id" --agent 2>/dev/null | jq -r '.data.status') + status=$(mem0 --agent event status "$event_id" 2>/dev/null | jq -r '.data.status') if [ "$status" = "SUCCEEDED" ] || [ "$status" = "FAILED" ]; then break fi @@ -413,16 +420,16 @@ shift 2 case "$ACTION" in recall) - mem0 search "$*" --user-id "$USER_ID" --agent 2>/dev/null + mem0 --agent search "$*" --user-id "$USER_ID" 2>/dev/null ;; remember) - mem0 add "$*" --user-id "$USER_ID" --agent 2>/dev/null + mem0 --agent add "$*" --user-id "$USER_ID" 2>/dev/null ;; forget) - mem0 delete --all --user-id "$USER_ID" --force --agent 2>/dev/null + mem0 --agent delete --all --user-id "$USER_ID" --force 2>/dev/null ;; history) - mem0 list --user-id "$USER_ID" --agent 2>/dev/null + mem0 --agent list --user-id "$USER_ID" 2>/dev/null ;; *) echo '{"status":"error","error":"Unknown action: '"$ACTION"'"}' >&2 diff --git a/skills/mem0-integrate/SKILL.md b/skills/mem0-integrate/SKILL.md index 34dfd284f..a18bbf270 100644 --- a/skills/mem0-integrate/SKILL.md +++ b/skills/mem0-integrate/SKILL.md @@ -15,7 +15,7 @@ description: > license: Apache-2.0 metadata: author: mem0ai - version: "0.1.0" + version: "0.1.1" category: ai-memory tags: "memory, integration, tdd, platform, oss" mem0_tested_versions: "mem0ai (PyPI) >=2.0.0,<3.0.0; mem0ai (npm) >=3.0.0,<4.0.0" @@ -36,7 +36,7 @@ of the Mem0 API. - Scope-tagged docs index: https://docs.mem0.ai/llms.txt - Full docs (single file, deep dives): https://docs.mem0.ai/llms-full.txt - OpenAPI spec (Platform REST, machine-readable): https://docs.mem0.ai/openapi.json -- Hosted MCP server: https://mcp.mem0.ai (requires Platform API key) +- Hosted MCP server: https://mcp.mem0.ai/mcp (requires Platform API key) - Integrations index: https://docs.mem0.ai/integrations ### Published Mem0 skills — delegate; do not reimplement @@ -109,7 +109,7 @@ the target stack. If yes, delegate — copy its call-site pattern into |---|---|---| | `@ai-sdk/*` + `ai` in `package.json` | `skills/mem0-vercel-ai-sdk` | Integration is via `createMem0` provider wrapper, not raw `MemoryClient`. | | CLI-only repo (Typer, Commander, Click, Cobra) with no LLM call sites | `skills/mem0-cli` | Call sites are command handlers, not model wrappers. Consider whether mem0 actually fits first. | -| Target is an MCP client / editor config (Claude Code, Cursor, Codex settings) | `integrations/mem0-agent-plugin` | Wire via MCP server URL + hooks; no SDK code usually needed. | +| Target is an MCP client / editor config (Claude Code, Cursor, Codex settings) | `integrations/mem0-agent-plugin` | Local stdio MCP server (one search tool) plus skills, no hooks or automatic capture; for a hosted endpoint use `https://mcp.mem0.ai/mcp`. No SDK code usually needed. | | Any other Python or TS repo with an LLM call site | `skills/mem0` | Default SDK integration path. | Record the delegated skill's raw URL in `plan.md` under a @@ -168,7 +168,7 @@ start executing a step; the summary below is only for routing. | `trace.jsonl` | Every tool call, decision, and subagent exchange this run. | Overwritten per run. | | `diff.patch` | The committed integration as a reviewable patch. | Overwritten per run. | | `heal-trace.md` | Per-attempt record of the self-healing loop (step 10). | Overwritten per run. | -| `product.json` | `{"product": "platform"\|"oss", "language": "...", "mem0_version": "...", "write_site": "file:line", "read_site": "file:line", "feature_flag": "MEM0_ENABLED"}` — consumed by the verification skill. | Overwritten per run. | +| `product.json` | `{"product": "platform"\|"oss", "language": "...", "mem0_version": "...", "write_site": "file:line", "read_site": "file:line", "feature_flag": "MEM0_ENABLED", "preferred_site": ""}`, consumed by the verification skill. | Overwritten per run. | `.mem0-integration/` is added to `.gitignore` on first run. Nothing is written outside this directory and the repo's source tree. diff --git a/skills/mem0-integrate/references/pipeline.md b/skills/mem0-integrate/references/pipeline.md index da8d42495..f1692b766 100644 --- a/skills/mem0-integrate/references/pipeline.md +++ b/skills/mem0-integrate/references/pipeline.md @@ -116,8 +116,11 @@ Present in env, continue. Mode**: run `mem0 init --agent --agent-caller --json` (after `pip install mem0-cli` or `npm install -g @mem0/cli`), substituting your agent identity such as `claude-code`, `cursor`, `codex`. If you forgot -`--agent-caller`, run `mem0 identify ` after init. Cache the key to -`.env` with user consent and continue. Tell the user to claim it later with +`--agent-caller`, run `mem0 identify ` after init. Init does not +print the key: it saves it to `~/.mem0/config.json` (`platform.api_key`, file +mode 0600) and reuses a valid key already there instead of minting a new one, +so read the key from that file. Cache the key to `.env` with user consent and +continue. Tell the user to claim it later with `mem0 init --email `: same key, no agent disruption. Missing and **CI mode** (`MEM0_INTEGRATE_CI=1`), exit code 2 with the name of @@ -184,8 +187,8 @@ Then write `.mem0-integration/plan.md`: call client.add([user_msg, assistant_msg], user_id=)."> **Read pattern:** , limit=5) - and inject results as a system message."> + call client.search(latest_user_msg, filters={"user_id": }, + top_k=5) and inject results["results"] as a system message."> **User identifier source:** @@ -276,7 +279,8 @@ test framework: Test assertion shapes must match the **canonical signatures**: - Platform method signatures: `https://docs.mem0.ai/openapi.json`, the request - body schemas for `/v1/memories/` and `/v1/memories/search/`. + body schemas for `/v3/memories/add/` and `/v3/memories/search/` (the + `/v1/memories/` POST and `/v1/memories/search/` paths are deprecated). - OSS method signatures: the delegated skill named in `plan.md` (fetched from its raw URL), or `skills/mem0/SKILL.md` as the default. - Do not hand-roll request shapes. If the delegated skill has an example @@ -341,7 +345,8 @@ Otherwise loop: 1. **Categorize the failing check** from `scorecard.json` and route: - `install` / `static_checks`, dependency or import fix. - - `unit_tests`, wiring or assertion fix. + - `unit_tests_flag_on`, wiring or assertion fix. (`unit_tests_flag_off` + failing is the non-invasiveness case below.) - `smoke_test`, API key or SDK call-shape fix. - `e2e_test`, recipe, flag-wiring, or integration-point fix. - **Pre-existing test failure** (test skill exit code 7, @@ -351,7 +356,7 @@ Otherwise loop: 2. **Spawn a remediation subagent** with fresh context. Inputs: `plan.md`, `goal.md`, `scorecard.md`, `scorecard.json`, the last committed diff, and - the relevant log for the failing category (`test-stdout.log` / + the relevant log for the failing category (`test-stdout-flag-on.log` / `smoke-stdout.log` / `e2e-app.log` / `e2e-calls.log`). Use the remediation prompt in [`subagent-prompts.md`](subagent-prompts.md) verbatim. diff --git a/skills/mem0-integrate/references/subagent-prompts.md b/skills/mem0-integrate/references/subagent-prompts.md index 811f0483b..835d6a952 100644 --- a/skills/mem0-integrate/references/subagent-prompts.md +++ b/skills/mem0-integrate/references/subagent-prompts.md @@ -31,7 +31,8 @@ so paraphrasing them drops constraints the review step then has to catch. 6. Preserve everything listed under plan.md's "Preserved behavior" and "Coexistence." 7. Lazy client construction. `MemoryClient()` validates the API - key in `__init__` (it makes a network call). Never instantiate + key in `__init__` (Python pings the API; TS throws on a missing + or blank key and pings in the background). Never instantiate it at module-import time, construct on first use inside the request / handler path. The same rule applies to OSS `Memory()`, which can eagerly initialize embedding and LLM providers. Use diff --git a/skills/mem0-oss-to-platform/README.md b/skills/mem0-oss-to-platform/README.md index 2f28e0ac6..b26202c21 100644 --- a/skills/mem0-oss-to-platform/README.md +++ b/skills/mem0-oss-to-platform/README.md @@ -71,7 +71,7 @@ curl -X POST https://api.anthropic.com/v1/skills \ - [Mem0 Platform Dashboard](https://app.mem0.ai) - [Mem0 Documentation](https://docs.mem0.ai) -- [OSS → Platform migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) +- [OSS → Platform migration guide](https://docs.mem0.ai/migration/oss-to-platform) - [Platform vs OSS comparison](https://docs.mem0.ai/platform/platform-vs-oss) ## License diff --git a/skills/mem0-oss-to-platform/SKILL.md b/skills/mem0-oss-to-platform/SKILL.md index 1cdde7dff..57048d462 100644 --- a/skills/mem0-oss-to-platform/SKILL.md +++ b/skills/mem0-oss-to-platform/SKILL.md @@ -1,18 +1,22 @@ --- name: mem0-oss-to-platform description: >- - Plan and then execute a migration of a project from the mem0 open-source / self-hosted SDK - (the local `Memory` class) to the mem0 Platform / hosted / managed SDK (the `MemoryClient` - class). Use this whenever a developer wants to move, switch, or migrate their mem0 usage off - OSS/self-hosted to the hosted API — e.g. "migrate my mem0 setup to the platform", "switch from - self-hosted mem0 to MemoryClient", "use my mem0 API key instead of a local Qdrant", "move mem0 - to the cloud/hosted/managed service", or "replace my local mem0 vector store + embedder config - with the platform". Applies to Python (`from mem0 import Memory` → `from mem0 import MemoryClient`) - and TypeScript/JavaScript (`import { Memory } from "mem0ai/oss"` → `import MemoryClient from "mem0ai"`). - Trigger even when the user doesn't say the word "migrate" but clearly wants their existing mem0 - integration to run against the hosted platform. It first produces a reviewable migration plan, - then executes it after the developer approves. Strictly scoped to the mem0 integration — it does - not refactor, restructure, or "improve" any unrelated code. + Plan, then execute, a migration of a project from the mem0 open-source / self-hosted SDK + (local `Memory` class) to the mem0 Platform / hosted SDK (`MemoryClient`). TRIGGER when: the + developer wants to move, switch, or migrate mem0 off OSS/self-hosted to the hosted API, e.g. + "migrate my mem0 setup to the platform", "switch from self-hosted mem0 to MemoryClient", "use my + mem0 API key instead of a local Qdrant", "replace my local vector store + embedder config with + the platform", even without the word "migrate". Covers Python (`Memory` to `MemoryClient`) and + TypeScript (`mem0ai/oss` to `mem0ai`). Produces a reviewable plan, then executes it after + approval. Touches only the mem0 integration. DO NOT TRIGGER when: adding mem0 to a project that + has none (use `mem0-integrate`) or answering SDK usage questions (use `mem0`). +license: Apache-2.0 +metadata: + author: mem0ai + version: "0.2.0" + category: ai-memory + tags: "migration, oss, self-hosted, platform, hosted" + mem0_tested_versions: "mem0ai (PyPI) >=2.0.0,<3.0.0; mem0ai (npm) >=3.0.0,<4.0.0" --- # Migrate mem0 OSS → mem0 Platform (hosted) @@ -35,7 +39,8 @@ few parameter conventions tighten up and the return values are server responses. So the core of every migration is: 1. `Memory` / `Memory.from_config({...})` → `MemoryClient()` (reads the API key from the env). -2. Delete the local `vector_store` / `llm` / `embedder` / `graph_store` / `history_db_path` config. +2. Delete the local `vector_store` / `llm` / `embedder` / `reranker` / `history_db_path` config (and any + leftover `graph_store`). 3. Fix up each call site to the hosted call convention (entity IDs into `filters`, pagination, etc.). 4. Flag everything that *isn't* a clean 1:1 so the developer can decide (see `references/gotchas.md`). @@ -55,10 +60,11 @@ must be set (in `.env` / secrets manager, never hardcoded) before execution and ### Phase 1 — Discover the mem0 footprint Do not assume the layout. Find every place mem0 appears. Detect the language and the **installed** version first, then sweep for usage. Concretely, search for: -- **Imports / instantiation:** `from mem0 import Memory`, `Memory.from_config`, `Memory(`, - `import ... from "mem0ai"`, `from "mem0ai/oss"`, `new Memory(`. -- **Config blocks:** keys like `vector_store`/`vectorStore`, `embedder`, `llm`, `graph_store`/ - `graphStore`, `history_db_path`, `historyStore`, `custom_fact_extraction_prompt`, +- **Imports / instantiation:** `from mem0 import Memory`, `AsyncMemory`, `Memory.from_config`, + `Memory(`, `import ... from "mem0ai"`, `from "mem0ai/oss"`, `new Memory(`. +- **Config blocks:** keys like `vector_store`/`vectorStore`, `embedder`, `llm`, `reranker`, + `graph_store`/`graphStore`, `history_db_path`/`historyDbPath`, `historyStore`, + `custom_instructions`/`customInstructions`, `custom_fact_extraction_prompt`/`customPrompt`, `custom_update_memory_prompt`, `enable_graph`. - **Every call site:** `.add(`, `.search(`, `.get_all(`/`.getAll(`, `.delete_all(`/`.deleteAll(`, `.get(`, `.update(`, `.delete(`, `.reset(`, `.history(`. @@ -78,11 +84,14 @@ confirm the **real** signatures of the installed package rather than trusting me `site-packages/mem0/client/main.py` if anything is ambiguous (e.g. whether a method *rejects* top-level entity params). Also check the OSS side the project currently uses. - **TypeScript:** read the installed types/dist under `node_modules/mem0ai/` to confirm option names - (`limit` vs `topK`, `userId` vs a nested `filters`) and the default vs `mem0ai/oss` export. + (`limit` vs `topK`, `userId` vs a nested `filters: { user_id }`) and the default vs `mem0ai/oss` + export. This verification step is the single most important habit — it's what keeps the plan correct across mem0 versions. Then consult `references/api-mapping.md` for the OSS→hosted translation of each -method (Python and TypeScript), and the official guide at https://docs.mem0.ai/migration/oss-v2-to-v3. +method (Python and TypeScript). The docs guide is https://docs.mem0.ai/migration/oss-to-platform +(verify its code samples against the installed SDK); OSS upgrade changes are at +https://docs.mem0.ai/migration/oss-v2-to-v3. ### Phase 3 — Map each site and flag the gaps For every call site and config block from Phase 1, determine the hosted equivalent using the @@ -90,7 +99,8 @@ mapping. Most calls map cleanly. Some don't — and those matter more than the m Read `references/gotchas.md` and flag anything that needs a human decision: self-hosted/data- residency setups, local model choices moving server-side, graph-memory usage, custom prompts, hot- path calls that now make network round-trips, and **existing locally-stored memories not carrying -over** (data migration is out of scope unless the developer asks — note it, don't silently attempt it). +over** (data migration is out of scope unless the developer asks: note it, don't silently attempt it; +if they do ask, see `references/gotchas.md` #1, which covers the hosted-Qdrant migration script). ### Phase 4 — Write the plan and stop Write the full plan to `MEM0_MIGRATION_PLAN.md` at the repo root, following the structure in @@ -106,11 +116,13 @@ Once the developer approves (they may ask for changes first — incorporate them - **Verify**, mirroring how you'd confirm any backend swap: - It imports / type-checks / byte-compiles. - A smoke test exercises `add` → `search`/`get_all` → `delete_all` against the hosted API with a - real `MEM0_API_KEY`, and the app's own entry point still runs. - - No local mem0 storage directory gets created anymore (e.g. a `.mem0/`, local Qdrant path) — - proof the memory really lives on the platform now. + real `MEM0_API_KEY`, and the app's own entry point still runs. Hosted `add` is asynchronous, so + allow a short wait before expecting the fact to show up in `search`/`get_all`. + - No local OSS storage gets created anymore (e.g. `~/.mem0/history.db`, a local Qdrant path). The + client itself still creates `~/.mem0/config.json`, so don't use the bare `.mem0/` directory as + the check. - Report what changed, what was verified, and any flagged concerns the developer still needs to act - on (e.g. configuring custom instructions in the dashboard, migrating old data). + on (e.g. re-applying custom instructions with `project.update`, migrating old data). ## Reference files - `references/api-mapping.md` — exact OSS→hosted method/param/return mapping for Python and diff --git a/skills/mem0-oss-to-platform/references/api-mapping.md b/skills/mem0-oss-to-platform/references/api-mapping.md index 3e16f7e8b..c9d738516 100644 --- a/skills/mem0-oss-to-platform/references/api-mapping.md +++ b/skills/mem0-oss-to-platform/references/api-mapping.md @@ -1,16 +1,17 @@ # OSS → Platform API mapping Exact translation of the mem0 OSS (self-hosted `Memory`) API to the hosted `MemoryClient` API. -**Always confirm against the installed package** (see SKILL.md Phase 2) — versions drift. The facts -below match `mem0ai` 2.0.x (the v3 platform API) and the official guide: -https://docs.mem0.ai/migration/oss-v2-to-v3 +**Always confirm against the installed package** (see SKILL.md Phase 2), since versions drift. The +facts below match Python `mem0ai` 2.2.x and TypeScript `mem0ai` 3.3.x (the `/v3/memories/*` platform +API). Moving stored data: https://docs.mem0.ai/migration/oss-to-platform. OSS upgrade changes +(Python 1.x to 2.x, TS 2.x to 3.x): https://docs.mem0.ai/migration/oss-v2-to-v3 ## Contents - [Python](#python) - [TypeScript / JavaScript](#typescript--javascript) - [Return shapes](#return-shapes) - [Dependencies & environment](#dependencies--environment) -- [v2→v3 default/behavior changes](#v2v3-defaultbehavior-changes) +- [OSS vs Platform defaults and behavior](#oss-vs-platform-defaults-and-behavior) --- @@ -35,28 +36,38 @@ memory = MemoryClient() # reads MEM0_API_KEY from the env ``` Notes: - The client reads `MEM0_API_KEY` from the environment when `api_key` is omitted. -- **Drop** `vector_store`, `llm`, `embedder`, `graph_store`, `history_db_path` — these are managed - server-side now. -- **Drop** `org_id` / `project_id` constructor args if present — they're resolved from the API key - in v3. +- **Drop** `vector_store`, `llm`, `embedder`, `reranker`, `history_db_path`, `version` (and + `graph_store` if a pre-2.0 config still has it): these are managed server-side now. +- `custom_instructions` does have a hosted equivalent: `client.project.update(custom_instructions=...)` + (project-wide) or `custom_instructions=` on `add()`. +- **Drop** `org_id` / `project_id` constructor args if present, they're resolved from the API key. - For async codebases, use `AsyncMemoryClient` (same methods, `await`-ed). ### Method calls | Operation | OSS `Memory` | Hosted `MemoryClient` | |---|---|---| -| add | `memory.add(messages, user_id="u")` | `memory.add(messages, user_id="u")` — unchanged (top-level entity IDs accepted) | -| search | `memory.search(q, user_id="u", limit=N)` *(older)* or `…, filters={"user_id":"u"}, top_k=N` *(newer)* | `memory.search(q, filters={"user_id": "u"}, top_k=N)` — entity IDs **must** be inside `filters`; top-level `user_id`/`agent_id`/`app_id`/`run_id` raise `ValueError` | -| get_all | `memory.get_all(user_id="u")` or `…, filters={"user_id":"u"}` | `memory.get_all(filters={"user_id": "u"}, page=1, page_size=N)` — entity IDs in `filters`; paginated with `page`/`page_size` (**not** `top_k`) | -| delete_all | `memory.delete_all(user_id="u")` | `memory.delete_all(user_id="u")` — unchanged | +| add | `memory.add(messages, user_id="u")` | `memory.add(messages, user_id="u")`: same call (top-level entity IDs accepted, plus `app_id`), but the return value differs (see Return shapes) | +| search | `memory.search(q, filters={"user_id": "u"}, top_k=N)` (pre-2.0 code used top-level `user_id=` and `limit=`) | `memory.search(q, filters={"user_id": "u"}, top_k=N)`: entity IDs **must** be inside `filters`; top-level `user_id`/`agent_id`/`app_id`/`run_id` raise `ValueError` (on OSS 2.x too) | +| get_all | `memory.get_all(filters={"user_id": "u"}, top_k=N)` (not paginated) | `memory.get_all(filters={"user_id": "u"}, page=1, page_size=N)`: entity IDs in `filters`; paginated with `page`/`page_size` (**not** `top_k`) | +| delete_all | `memory.delete_all(user_id="u")` | `memory.delete_all(user_id="u")`: same call (entity IDs are query params, at least one is required, `"*"` is a wildcard). `delete_all(filters=...)` is **not** a Platform form | | get | `memory.get(memory_id)` | `memory.get(memory_id)` | -| update | `memory.update(memory_id, text=...)` *(`data=` is a deprecated alias)* | `memory.update(memory_id, text=...)` — unchanged | +| update | `memory.update(memory_id, text=...)` *(`data=` is a deprecated alias)* | `memory.update(memory_id, text=..., metadata=...)`: use keyword `text=`. A positional string (`update(id, "new text")`) breaks because the second positional is `options`, and there is no `data=` alias | | delete | `memory.delete(memory_id)` | `memory.delete(memory_id)` | -| reset | `memory.reset()` (wipes the local store) | **No global reset.** Use `memory.delete_all(filters=...)` scoped to the relevant entity. Flag this. | +| history | `memory.history(memory_id)` | `memory.history(memory_id)`: same call, extra fields on each entry (`input`, `user_id`, `categories`, `metadata`); OSS-only `is_deleted`/`actor_id`/`role` are absent (see Return shapes) | +| reset | `memory.reset()` (wipes the local store) | `memory.reset()` exists but calls `delete_users()`, which deletes **all** users, agents, sessions and memories (first page of entities only, see gotchas). Prefer `delete_all` scoped to an entity. Flag this | Key rule: for **search** and **get_all**, the hosted client requires entity IDs (`user_id`, `agent_id`, `app_id`, `run_id`) inside a `filters` dict and will raise if you pass them top-level. For **add** and **delete_all**, top-level entity IDs are accepted. +Filter differences: Platform validates each top-level filter key against a fixed allowlist +(`AND`/`OR`/`NOT`, `user_id`, `agent_id`, `app_id`, `run_id`, `created_at`, `updated_at`, `timestamp`, +`expiration_date`, `categories`, `metadata`, `memory_ids`, `keywords`) and +returns 400 for anything else, so custom metadata keys must be nested under `"metadata"` +(`{"metadata": {"plan": "pro"}}`). Platform `metadata` supports only `eq`/`ne`/`contains` (`contains` is case-sensitive and matches the whole value or one list member, not a substring), and there is +no `nin` (use `{"NOT": [{"categories": {"in": [...]}}]}`; `NOT` must be a list). OSS accepts arbitrary +metadata keys and a wider operator set. Flag any OSS filter that depends on either. Do not filter on `text`: search fails with a 503 and `get_all` rejects it. Pass the text as the search `query`. + --- ## TypeScript / JavaScript @@ -66,36 +77,64 @@ Confirm option names against `node_modules/mem0ai/` types. ### Import & client construction ```typescript -// OSS (self-hosted) — note the "/oss" subpath +// OSS (self-hosted): note the "/oss" subpath import { Memory } from "mem0ai/oss"; -const memory = new Memory({ /* vectorStore, embedder, llm, historyStore … */ }); +const memory = new Memory({ /* vectorStore, embedder, llm, historyStore, reranker, customInstructions … */ }); -// Platform (hosted) — default export from the package root +// Platform (hosted): default export from the package root import MemoryClient from "mem0ai"; -const memory = new MemoryClient({ apiKey: process.env.MEM0_API_KEY }); -// Drop organizationId / projectId — resolved from the API key in v3. +const memory = new MemoryClient({ apiKey: process.env.MEM0_API_KEY! }); ``` +Notes: +- Unlike Python, the TS client does **not** read `MEM0_API_KEY` itself: `apiKey` is required and the + constructor throws if it is empty. Pass it explicitly. +- Drop `organizationId` / `projectId` if present, they're resolved from the API key. +- Drop `vectorStore`, `embedder`, `llm`, `historyStore`, `historyDbPath`, `reranker`, `disableHistory`, + `version`. `customInstructions` maps to `client.updateProject({ customInstructions })` or + `customInstructions` on `add()`. ### Method calls (option-object differences) -| Operation | OSS / old client | Hosted client (v3) | +| Operation | OSS `Memory` | Hosted client | |---|---|---| -| add | `memory.add(messages, { userId: "u" })` | `memory.add(messages, { userId: "u" })` — unchanged | -| search | `memory.search(q, { userId: "u", limit: 20 })` | `memory.search(q, { filters: { userId: "u" }, topK: 20 })` — entity IDs into `filters`; `limit` → `topK` | -| getAll | `memory.getAll({ userId: "u" })` | `memory.getAll({ filters: { userId: "u" } })` — entity IDs into `filters` | -| deleteAll | `memory.deleteAll({ userId: "u" })` | `memory.deleteAll({ userId: "u" })` | -| get / update / delete | `memory.get(id)` etc. | same, by memory id | +| add | `memory.add(messages, { userId: "u" })` (`messages` may be a string or `Message[]`) | `memory.add(messages, { userId: "u" })`: `messages` must be `Message[]` (wrap a bare string as `[{ role: "user", content: str }]`); the response is an async event (see Return shapes) | +| search | `memory.search(q, { filters: { user_id: "u" }, topK: 20 })` (pre-3.0 code used top-level `userId` and `limit`) | `memory.search(q, { filters: { user_id: "u" }, topK: 20 })`: entity IDs go inside `filters` with **snake_case** keys (`user_id`, not `userId`); top-level `userId` throws; `limit` → `topK` | +| getAll | `memory.getAll({ filters: { user_id: "u" }, topK: 20 })` (not paginated) | `memory.getAll({ filters: { user_id: "u" }, page: 1, pageSize: 50 })`: paginated with `page`/`pageSize` (not `topK`) | +| deleteAll | `memory.deleteAll({ userId: "u" })` | `memory.deleteAll({ userId: "u" })`: same call (at least one entity ID is required) | +| update | `memory.update(id, "new text")` or `memory.update(id, { text, metadata })` | `memory.update(id, { text: "new text" })`: the options object is required, a bare string throws | +| get / delete / history | `memory.get(id)` etc. | same, by memory id (`history` field names differ, see Return shapes) | +| reset | `memory.reset()` (wipes the local store) | No `reset()` on the TS client. `deleteUsers()` with no arguments deletes all users, agents, sessions and memories (first page of entities only, see gotchas). Prefer `deleteAll` scoped to an entity. Flag this | -Also drop legacy options that no longer apply on v3: `async_mode`, `output_format`, `enable_graph`. +Also drop legacy options that no longer apply: `async_mode`, `output_format`, `enable_graph`. --- ## Return shapes -- `search(...)` and `get_all(...)` return `{"results": [...]}`; each item has at least a `memory` - (text) field, plus `id` and (for search) `score`. Code that reads `result["results"]` and pulls - `item["memory"]` keeps working. -- `get_all(...)` on the hosted client is paginated: `{"count", "next", "previous", "results": [...]}`. -- `add(...)` returns the created memories. On v3 it returns **only ADD events** — if the old code - branched on `event == "UPDATE"` / `"DELETE"` from `add()` results, that branch is now dead. +- `search(...)` returns `{"results": [...]}` on both sides; each item has at least a `memory` (text) + field, plus `id` and `score`. Code that reads `result["results"]` and pulls `item["memory"]` keeps + working. +- `get_all(...)`: OSS returns `{"results": [...]}` (no pagination). The hosted client is paginated: + `{"count", "next", "previous", "results": [...]}`. +- `add(...)`: OSS extracts synchronously on both runtimes, but the event sits in a different place: + Python OSS returns `{"results": [{"id", "memory", "event": "ADD"}]}`, TS OSS returns + `{ results: [{ id, memory, metadata: { event: "ADD" } }] }` (no top-level `event`). + The hosted `add` is **asynchronous by default** and returns `{"status": "PENDING", "event_id": "..."}` + from Python. The TS hosted client camelCases response keys, so it returns + `{ status: "PENDING", eventId: "..." }` (its typed return `Array` does not reflect this). + New memories may not be searchable yet. Only `infer=False` is synchronous and returns `results`. + Neither SDK has an event-poll method: poll `GET /v1/event/{event_id}/` over REST if you must wait. + Code that reads `id`/`memory` from `add()` results must change, and any 1.x-era branch on + `event == "UPDATE"` / `"DELETE"` is dead on both sides (add is ADD-only since 2.0). +- `history(...)` field names differ on all four runtimes: + + | Runtime | Entry fields | + |---|---| + | Python OSS | `id`, `memory_id`, `old_memory`, `new_memory`, `event`, `created_at`, `updated_at`, `is_deleted`, `actor_id`, `role` (oldest first) | + | TS OSS | `id`, `memory_id`, `previous_value`, `new_value`, `action`, `created_at`, `updated_at`, `is_deleted` (raw rows, snake_case, newest first) | + | Hosted Python | `id`, `memory_id`, `input`, `old_memory`, `new_memory`, `event`, `user_id`, `categories`, `metadata`, `created_at`, `updated_at` | + | Hosted TS | `id`, `memoryId`, `input`, `oldMemory`, `newMemory`, `event`, `userId`, `categories`, `metadata`, `createdAt`, `updatedAt` | + + Code that reads `previous_value` / `new_value` / `action` from TS OSS history must switch to + `oldMemory` / `newMemory` / `event` on the hosted TS client. --- @@ -109,9 +148,18 @@ Also drop legacy options that no longer apply on v3: `async_mode`, `output_forma - Local-infra services (e.g. a Qdrant docker-compose service) that existed only for mem0 can be retired — flag this rather than deleting infrastructure unilaterally. -## v2→v3 default/behavior changes -From the official migration guide — surface any that affect the project: -- Python `top_k` default changed 100 → 20; TS `limit` renamed to `topK`. -- New `threshold` default `0.1` (was none); new `rerank` default `false` (was true). -- `custom_fact_extraction_prompt` → `custom_instructions`; `custom_update_memory_prompt` deprecated. -- Graph memory (`enable_graph`, `graph_store`) removed from the OSS v3 surface — see gotchas. +## OSS vs Platform defaults and behavior +Surface any that affect the project. Defaults differ between the two sides even when a call looks +identical: +- `search`: OSS `top_k=20`, `threshold=0.1`, `rerank=False`. Platform `top_k=10` (allowed 1 to 1000), + `rerank=false`, and `threshold` is a server-side cutoff, not a floor on the returned `score`. Pass `top_k` explicitly to keep the old result count. +- `get_all`: OSS `top_k=20`, not paginated. Platform `page=1`, `page_size=100`. +- `custom_fact_extraction_prompt` (TS `customPrompt`) was renamed `custom_instructions` + (`customInstructions`) in OSS 2.0/3.0; `custom_update_memory_prompt` is deprecated. See the + constructor notes for the hosted equivalent. +- Graph memory (`enable_graph`, `graph_store`) was removed from OSS (Python 2.0.0, TS 3.0.0). On the + Platform graph is built in and always on, with no flag. See gotchas. +- Platform-only: `app_id`, webhooks, custom categories, batch update/delete, feedback, memory export, + user profiles. `timestamp`, `reference_date` and `decay` raise on OSS. +- OSS-only (no Platform option): `reranker` and `history_db_path` config, `memory_type` and `prompt` + on `add`, `explain` on `search`. diff --git a/skills/mem0-oss-to-platform/references/gotchas.md b/skills/mem0-oss-to-platform/references/gotchas.md index d5e610f72..9f8f8890f 100644 --- a/skills/mem0-oss-to-platform/references/gotchas.md +++ b/skills/mem0-oss-to-platform/references/gotchas.md @@ -9,8 +9,19 @@ section, phrased as a decision for the developer — never silently resolved. Migrating the *code* does not move the *memories*. Anything stored in the local vector store / history DB stays there; the hosted account starts empty. This is the most surprising gap, so call it out prominently. Data migration is **out of scope** unless the developer explicitly asks. If they -do, the rough path is: read everything from the OSS store (`get_all` per user/entity) and re-`add` -it to the hosted client — but treat that as a separate, opt-in task. +do, treat it as a separate, opt-in task: +- **Hosted Qdrant + Python OSS SDK:** the repo ships `scripts/oss-to-platform-migrate.sh` + (`curl -fsSL https://raw.githubusercontent.com/mem0ai/mem0/main/scripts/oss-to-platform-migrate.sh | bash`, + documented at https://docs.mem0.ai/migration/oss-to-platform). It needs `python3`, signs in to the + Platform (`--email`/`--code` or `--api-key`), exports a scope (`--user-id`, `--agent-id`, `--run-id` + or `--all`) from the Qdrant collection (`--qdrant-url`, `--qdrant-api-key`, `--qdrant-collection`, + default `mem0`) to a JSON file under `~/.mem0/migrations/`, and imports it with `infer: False` (stored + verbatim, no re-extraction). `--export-only` / `--import-only` split the two steps so the export can + be reviewed first. Don't run it unprompted: it logs in and writes under `~/.mem0/`. +- **Anything else:** other vector stores are not supported by the script (the docs say hosted Qdrant + only), and its export is written for the Python OSS SDK, so TS-written data is not documented as + supported. The fallback is to read everything from the OSS store (`get_all` per entity) and re-`add` + it with `infer=False`. ## 2. Self-hosting / data residency A local or self-hosted vector store sometimes exists *on purpose* — compliance, data residency, air- @@ -24,15 +35,19 @@ the platform with the platform's configuration. Memory *content and quality may Flag where the project depended on a specific model. ## 4. Graph memory -If the project uses graph memory (`enable_graph`, `graph_store`), this changed in v3 and is handled -differently on the platform. Don't assume a drop-in mapping — verify current platform graph support -in the docs and flag the usage for the developer. +The external graph store (`graph_store`, `enable_graph`; Neo4j/Memgraph/Kuzu/AGE) was removed from OSS +(Python 2.0.0, TS 3.0.0). On the platform graph memory is built in and always on: nothing to enable or +configure, and it only influences ranking (no separate `relations` payload, no typed relationships, +no direct graph queries). Flag any project code that queried its own graph store or read `relations`. +See https://docs.mem0.ai/platform/features/graph-memory. ## 5. Custom prompts / extraction config -`custom_fact_extraction_prompt` → `custom_instructions`, and `custom_update_memory_prompt` is -deprecated. On the platform these tend to be **project-level settings configured in the dashboard** -rather than passed in code. Flag any custom prompt the project relied on so the developer can re- -apply it in the dashboard. +`custom_fact_extraction_prompt` (TS `customPrompt`) was renamed `custom_instructions` +(`customInstructions`), and `custom_update_memory_prompt` is deprecated (fold it into +`custom_instructions`). On the platform `custom_instructions` is a project-level setting: +`client.project.update(custom_instructions=...)` (TS `client.updateProject({ customInstructions })`), +or per call via `custom_instructions=` on `add()`. +Flag any custom prompt the project relied on so the developer can decide where to re-apply it. ## 6. Every call is now a network request Local calls become remote API calls. That introduces latency, network failures, timeouts, rate @@ -41,23 +56,44 @@ error handling / retries / timeouts where the old local calls were effectively i apps, use `AsyncMemoryClient` (Python) so calls don't block the event loop. ## 7. API key & secrets -The hosted client needs `MEM0_API_KEY`. It must come from the environment / a secrets manager — never +The hosted client needs `MEM0_API_KEY`. It must come from the environment / a secrets manager, never hardcoded. Ensure it's added to `.env.example`, local `.env`, CI, and deployment config. Without it -the client fails to initialize. +the client fails to initialize. The Python client reads `MEM0_API_KEY` itself when `api_key` is +omitted; the TS client does not, so pass `apiKey: process.env.MEM0_API_KEY!` explicitly. ## 8. Dropped constructor args & legacy options `org_id` / `project_id` (Python) and `organizationId` / `projectId` (TS) are no longer passed to the -constructor in v3 — they're resolved from the API key. Per-call legacy options like `async_mode`, +constructor, they're resolved from the API key. Per-call legacy options like `async_mode`, `output_format`, and `enable_graph` are gone. Remove them rather than leaving dead args. -## 9. Return-shape drift -- `add()` returns **only ADD events** on v3. Code that inspected `add()` results for `UPDATE` / - `DELETE` events has dead branches now. -- `search` / `get_all` return `{"results": [...]}`; `get_all` is paginated (`count`/`next`/ - `previous`/`results`). Code that limited via `top_k` on `get_all` should move to `page`/`page_size`. -- Default `top_k` dropped 100 → 20, `threshold` now `0.1`, `rerank` now `false` — result counts and - ordering can change even when the call looks equivalent. +## 9. Return-shape and default drift +- `add()` is **asynchronous** on the platform: it returns `{"status": "PENDING", "event_id": "..."}` + (`eventId` on the TS client, which camelCases response keys) instead of the created memories, so new memories may not be searchable yet when it returns + (`infer=False` is synchronous and returns `results`). Code that read `id`/`memory` from `add()` + results, or searched immediately after adding (tests, read-your-writes flows), needs a decision. + Neither SDK exposes an event-poll method; `GET /v1/event/{event_id}/` is REST only. +- `search` returns `{"results": [...]}` on both sides; `get_all` is paginated on the platform + (`count`/`next`/`previous`/`results`). Code that limited via `top_k` on `get_all` should move to + `page`/`page_size` (default `page_size` 100). +- Defaults differ: OSS `search` uses `top_k=20`, the platform uses `top_k=10`. Both default to + `rerank=false`. OSS `threshold` defaults to 0.1; on the platform it is a server-side cutoff, not a floor on the returned `score`. Result counts can change even when the call looks equivalent; + pass `top_k` explicitly. -## 10. No global `reset()` -The OSS `reset()` wipes the whole local store. There's no hosted equivalent that nukes everything; -use `delete_all` scoped by `filters`. Flag any `reset()` call. +## 10. `reset()` is much more destructive +The OSS `reset()` wipes the local store. Python `MemoryClient.reset()` exists but calls `delete_users()`, +which deletes all users, agents, sessions and memories on the platform. The TS client has no `reset()` +(`deleteUsers()` with no arguments does the same). Flag any `reset()` call (often test teardown) and +suggest `delete_all` scoped to the test entity instead. `delete_all(filters=...)` is not a valid +platform form: pass `user_id`/`agent_id`/`app_id`/`run_id` directly. + +The hosted wipe is also incomplete: Python `reset()` and TS `deleteUsers()` with no arguments call +`users()` once and delete only the entities on that first page, so a project with more entities than +one page keeps the rest. Re-run until it raises `No entities to delete`, or delete per entity +(`delete_users(user_id=...)` / `deleteUsers({ userId })`, paging TS with `users({ page, pageSize })`). + +## 11. Filters and update/add signatures +- Platform `filters` only accept an allowlist of top-level keys; custom metadata must be nested under + `"metadata"` and supports only `eq`/`ne`/`contains` (whole value or list member, not a substring; no `nin`; use a `NOT` list, e.g. `{"NOT": [{"categories": {"in": [...]}}]}`). OSS filters on arbitrary metadata + keys or richer operators need rewriting or a decision. +- Python `update` takes `text=` as a keyword (a positional string breaks); TS `update` requires an + options object and TS `add` requires `Message[]`, not a bare string. diff --git a/skills/mem0-oss-to-platform/references/plan-template.md b/skills/mem0-oss-to-platform/references/plan-template.md index bd9cbcd0c..b354e91d6 100644 --- a/skills/mem0-oss-to-platform/references/plan-template.md +++ b/skills/mem0-oss-to-platform/references/plan-template.md @@ -51,13 +51,15 @@ unambiguous. Example: ## Concerns & decisions needed The non-1:1 items from the gotchas that apply here, each phrased as a decision for the developer. Cover, where relevant: data not migrating, self-hosting/data-residency, local models moving server- -side, graph memory, custom prompts (now dashboard settings), network/latency/cost on hot paths, -return-shape changes (`add` ADD-only, `get_all` pagination, default `top_k`/threshold/rerank), and -any `reset()` usage. Be specific about which file/line each concern affects. +side, graph memory, custom prompts (now project-level `custom_instructions`), network/latency/cost on +hot paths, return-shape changes (`add` is async and returns an `event_id` (`eventId` on TS), `get_all` pagination, +default `top_k` 20 vs 10), metadata filters that need rewriting, and any `reset()` usage. Be specific +about which file/line each concern affects. ## Out of scope - Existing memory **data** is not migrated (code only). If wanted, it's a separate opt-in task - (export from the OSS store, re-add to the hosted client). + (for hosted Qdrant + Python OSS, `scripts/oss-to-platform-migrate.sh`; otherwise export from the + OSS store and re-add to the hosted client). - No unrelated refactors, renames, or behavior changes. ## Verification plan @@ -65,7 +67,8 @@ How execution will be confirmed end-to-end: - Imports / type-checks / byte-compiles cleanly. - Smoke test against the hosted API with a real `MEM0_API_KEY`: `add` a fact → `search`/`get_all` returns it → `delete_all` clears it. Plus: the app's own entry point still runs. -- Confirm no local mem0 storage dir is created anymore (e.g. `.mem0/`) — proof memory is hosted. +- Confirm no local OSS storage is created anymore (e.g. `~/.mem0/history.db`, a local Qdrant path). + The client still creates `~/.mem0/config.json`, so the bare `.mem0/` directory is not the check. ## Rollback - All changes are in version control; revert with git if needed. Note the branch/commit strategy. diff --git a/skills/mem0-test-integration/SKILL.md b/skills/mem0-test-integration/SKILL.md index 773d0dd26..d209efd44 100644 --- a/skills/mem0-test-integration/SKILL.md +++ b/skills/mem0-test-integration/SKILL.md @@ -18,7 +18,7 @@ description: > license: Apache-2.0 metadata: author: mem0ai - version: "0.1.0" + version: "0.1.1" category: ai-memory tags: "memory, integration, testing, tdd, platform, oss" coupling: loose @@ -130,7 +130,8 @@ if dependencies don't resolve. - **Eager-init check**: grep the `write_site` and `read_site` files (paths from `product.json`) for `MemoryClient(` or `Memory(` at module scope — i.e., not inside a function, method, or class body. `MemoryClient()` - validates the API key in `__init__` (network call) and OSS `Memory()` + validates the API key in `__init__` (Python pings the API, TS throws on a + blank key and pings in the background) and OSS `Memory()` can eagerly initialize embedding/LLM providers — module-level instantiation hits the wire on import and breaks Pass A's test collection whenever the key is unset. Hit → fail with `file:line` and @@ -140,7 +141,7 @@ if dependencies don't resolve. | Language | Test command (in priority order) | |---|---| -| Python | `pytest` with the test files from step 5 of the companion skill, else `python -m unittest discover`. | +| Python | `pytest` with the test files from step 7 of the companion skill, else `python -m unittest discover`. | | TypeScript / JavaScript | `npm test` if defined in package.json; else auto-detect `vitest` or `jest`. | **Pass A — `feature_flag` unset.** Run the *entire* pre-existing suite @@ -171,26 +172,43 @@ shape for the detected stack. **Platform (Python):** + import os + import time from mem0 import MemoryClient c = MemoryClient() # uses MEM0_API_KEY uid = f"mem0-test-integration-{os.urandom(4).hex()}" c.add([{"role": "user", "content": "I prefer aisle seats"}], user_id=uid) - hits = c.search("seat preference", user_id=uid) + for _ in range(10): + hits = c.search("seat preference", filters={"user_id": uid})["results"] + if hits: + break + time.sleep(2) assert any("aisle" in h.get("memory", "") for h in hits), hits c.delete_all(user_id=uid) # clean up -**Platform (TS):** same shape with `MemoryClient` from `"mem0ai"`. +`add` is asynchronous on Platform (it returns `status: "PENDING"` with an +`event_id`), so the search is retried for a bounded time. Entity IDs go in +`filters` and results come back under `["results"]`. + +**Platform (TS):** same shape with `new MemoryClient({ apiKey: +process.env.MEM0_API_KEY })` from `"mem0ai"` (the TS client does not read the +env var itself), `client.search("seat preference", { filters: { user_id: uid +} })` with hits under `.results`, and `client.deleteAll({ userId: uid })`. **OSS (Python / TS):** uses `Memory()` / `new Memory()` with default config -(OpenAI LLM via `OPENAI_API_KEY`, local Qdrant). If the repo ships a -`docker-compose.yml` with a Qdrant service, the skill starts it first and -tears it down after. If no backing store is reachable → fail with a +(OpenAI LLM via `OPENAI_API_KEY`; Python defaults to an embedded on-disk +Qdrant, TS to an in-memory vector store, so no service is needed unless the +repo's own config points at one). If the repo ships a `docker-compose.yml` +with the configured vector store service, the skill starts it first and tears +it down after. If the configured backing store is not reachable → fail with a clear message naming the fix. The smoke test always uses a **disposable random user_id** prefixed with `mem0-test-integration-` so a failed cleanup doesn't pollute the user's -real data. A background tidy step deletes any prefix-matching entries -older than 24 hours on the next run. +real data. A background tidy step lists Platform entities with `client.users()`, +picks the `type: "user"` entries whose `name` starts with that prefix and whose +`created_at` is older than 24 hours, and calls `delete_all(user_id=...)` for +each on the next run (there is no server-side prefix delete). Capture output to `.mem0-integration/smoke-stdout.log`. @@ -201,7 +219,7 @@ real signal: **does memory actually appear in the app's user-visible output when the integration runs end-to-end?** Requires `plan.md` to contain an `E2E recipe:` section (authored by -`/mem0-integrate` step 5). If absent → status `skipped` (not `fail`), +`/mem0-integrate` step 6). If absent → status `skipped` (not `fail`), note in scorecard that the repo has no runnable entry point. Recipe fields the skill reads: @@ -238,8 +256,8 @@ Execution order: 8. Run `read_call`. 9. Evaluate `read_assert` against `read_call`'s stdout. Miss → fail. 10. Cleanup (always, even on failure): SIGTERM the app, SIGKILL after - 5s, `docker compose down` if services were started, `delete_all` - memories matching `mem0-test-integration-*` on Platform scenarios. + 5s, `docker compose down` if services were started, `delete_all` for + the disposable `MEM0_USER_ID` on Platform scenarios. On any failure, the scorecard includes: diff --git a/skills/mem0-vercel-ai-sdk/README.md b/skills/mem0-vercel-ai-sdk/README.md index 886e352f7..8cd78e52f 100644 --- a/skills/mem0-vercel-ai-sdk/README.md +++ b/skills/mem0-vercel-ai-sdk/README.md @@ -37,7 +37,7 @@ curl -X POST https://api.anthropic.com/v1/skills \ ### Prerequisites - **Node.js 18+** -- **Vercel AI SDK v5** (`ai` package version 5.x) +- **Vercel AI SDK v6** (`ai` package version 6.x) - A Mem0 Platform API key ([Get one here](https://app.mem0.ai/dashboard/api-keys?utm_source=oss&utm_medium=skill-mem0-vercel-ai-sdk-readme)) - An LLM provider API key (OpenAI, Anthropic, Google, Groq, or Cohere) - Set environment variables: @@ -54,7 +54,7 @@ After installing, just ask Claude: - "Add memory to my Vercel AI SDK app" - "Set up mem0 with streamText in my Next.js API route" - "Use retrieveMemories with Anthropic instead of the wrapped model" -- "Show me how to use graph memories with the Vercel AI provider" +- "Show me how to read the Mem0 source from generateText with the Vercel AI provider" - "Help me store conversation history with addMemories" ## What's Inside @@ -67,7 +67,7 @@ skills/mem0-vercel-ai-sdk/ └── references/ # Documentation (loaded on demand) ├── provider-api.md # createMem0, Mem0Provider, types, config ├── memory-utilities.md # addMemories, retrieveMemories, getMemories, searchMemories - └── usage-patterns.md # Working examples: streaming, Next.js, multi-provider, graph + └── usage-patterns.md # Working examples: streaming, Next.js, multi-provider ``` ## Links diff --git a/skills/mem0-vercel-ai-sdk/SKILL.md b/skills/mem0-vercel-ai-sdk/SKILL.md index 8b5e9929e..1d489ebd8 100644 --- a/skills/mem0-vercel-ai-sdk/SKILL.md +++ b/skills/mem0-vercel-ai-sdk/SKILL.md @@ -12,10 +12,11 @@ description: > license: Apache-2.0 metadata: author: mem0ai - version: "1.1.0" + version: "2.0.0" category: ai-memory tags: "vercel, ai-sdk, memory, nextjs, typescript, provider" -compatibility: Node.js 18+, npm install @mem0/vercel-ai-provider, Vercel AI SDK v5 (ai package), MEM0_API_KEY + LLM provider API key + mem0_tested_versions: "@mem0/vercel-ai-provider (npm) >=3.0.0,<4.0.0; ai (npm) >=6.0.0,<7.0.0; mem0ai (npm) >=3.0.0,<4.0.0" +compatibility: Node.js 18+, npm install @mem0/vercel-ai-provider, Vercel AI SDK v6 (ai package ^6), MEM0_API_KEY + LLM provider API key --- # Mem0 Vercel AI SDK Provider @@ -25,9 +26,11 @@ Memory-enhanced AI provider for Vercel AI SDK. Automatically retrieves and store ## Step 1: Install ```bash -npm install @mem0/vercel-ai-provider ai +npm install @mem0/vercel-ai-provider ai@^6 ``` +`ai` and the `@ai-sdk/*` provider packages ship as regular dependencies of `@mem0/vercel-ai-provider`, so nothing else needs installing. The only peer dependency is `zod` (optional, `^3.0.0`). + ## Step 2: Set up environment variables ```bash @@ -53,10 +56,23 @@ const { text } = await generateText({ ``` What happens under the hood: -1. The prompt is sent to Mem0 search (`POST /v3/memories/search/`) to retrieve relevant memories -2. Retrieved memories are injected as a system message at the start of the prompt -3. The underlying LLM (e.g., OpenAI gpt-5-mini) generates a response using the enriched prompt -4. The conversation is stored back to Mem0 (`POST /v3/memories/add/`) as a fire-and-forget async call (no await) +1. The prompt is stored to Mem0 (`POST /v3/memories/add/`), awaited before the LLM call (a failed write is logged and ignored) +2. The prompt is sent to Mem0 search (`POST /v3/memories/search/`) to retrieve relevant memories +3. If any memories are found, they are injected as a system message at the start of the prompt +4. The underlying LLM (e.g., OpenAI gpt-5-mini) generates a response using the enriched prompt + +For `generateText`, the retrieved memories are also attached to the result as a source: + +```typescript +const { text, sources } = await generateText({ + model: mem0("gpt-5-mini", { user_id: "alice" }), + prompt: "Recommend a restaurant", +}); + +console.log(sources.find((s) => s.title === "Mem0 Memories")?.providerMetadata?.mem0); +``` + +The source has `title: "Mem0 Memories"` and `providerMetadata.mem0` holds `memories` (array of memory objects) and `memoriesText`. It is only present when at least one memory was retrieved. ## Pattern 2: Standalone Utilities @@ -111,7 +127,7 @@ for await (const chunk of result.textStream) { } ``` -The wrapped model handles memory retrieval before streaming begins and stores the conversation after. +The wrapped model stores the conversation and retrieves memories before streaming begins. ## Supported Providers @@ -119,7 +135,7 @@ The wrapped model handles memory retrieval before streaming begins and stores th |----------|-------------|------------------| | OpenAI (default) | `"openai"` | `OPENAI_API_KEY` | | Anthropic | `"anthropic"` | `ANTHROPIC_API_KEY` | -| Google | `"google"` | `GOOGLE_GENERATIVE_AI_API_KEY` | +| Google | `"google"` (alias `"gemini"`) | `GOOGLE_GENERATIVE_AI_API_KEY` | | Groq | `"groq"` | `GROQ_API_KEY` | | Cohere | `"cohere"` | `COHERE_API_KEY` | @@ -128,7 +144,7 @@ Select a provider when creating the Mem0 instance: ```typescript const mem0 = createMem0({ provider: "anthropic" }); const { text } = await generateText({ - model: mem0("gpt-5-mini", { user_id: "alice" }), + model: mem0("claude-sonnet-4-20250514", { user_id: "alice" }), prompt: "Hello!", }); ``` @@ -139,11 +155,11 @@ const { text } = await generateText({ ``` User prompt - --> searchInternalMemories (POST /v3/memories/search/) - --> memories injected as system message at start of prompt + --> processMemories: addMemories (POST /v3/memories/add/, awaited) + --> processMemories: getMemories (POST /v3/memories/search/) + --> memories (if any) injected as system message at start of prompt --> underlying LLM generates response (doGenerate or doStream) - --> processMemories fires addMemories as fire-and-forget (no await) - --> response returned to caller + --> response returned to caller (doGenerate also attaches a "Mem0 Memories" source) ``` ### Standalone flow @@ -162,18 +178,20 @@ User controls each step: |----------|---------|----------| | `retrieveMemories` | Formatted system prompt **string** | Injecting directly into `system` parameter | | `getMemories` | Raw memory **array** | Processing memories programmatically | -| `searchMemories` | Full search **response** (results + relations) | Need relations, scores, metadata | +| `searchMemories` | Raw search **response** (as returned by the API) | Need scores and full metadata | | `addMemories` | API response | Storing new messages to Mem0 | -All four accept `LanguageModelV2Prompt | string` as the first argument and optional `Mem0ConfigSettings` as the second. +`retrieveMemories`, `getMemories`, and `searchMemories` accept `LanguageModelV3Prompt | string` as the first argument; `addMemories` is typed as `LanguageModelV3Prompt` (a string also works at runtime). All four take optional `Mem0ConfigSettings` as the second argument. ## Common Edge Cases and Tips -- **Always provide `user_id`** (or `agent_id`/`app_id`/`run_id`) for consistent memory retrieval. Without an entity identifier, memories cannot be scoped. +- **Always provide `user_id`** (or `agent_id`/`app_id`/`run_id`) for consistent memory retrieval. The search endpoint requires at least one entity ID in `filters`; the provider places these IDs there for you. - **Standalone utilities require explicit API key**: pass `mem0ApiKey` in the config object, or set the `MEM0_API_KEY` environment variable. -- **This uses Vercel AI SDK v5** (LanguageModelV2 / ProviderV2 interfaces). It is not compatible with AI SDK v3 or v4. -- **`processMemories` fires `addMemories` as fire-and-forget** (`.then()` without `await`). Memory storage happens asynchronously and does not block the LLM response. -- **The `"gemini"` alias** exists in the provider switch but is NOT in the `supportedProviders` list. Use `"google"` instead. +- **This uses Vercel AI SDK v6** (LanguageModelV3 / ProviderV3 interfaces, `@mem0/vercel-ai-provider` 3.x). Provider 2.x targeted AI SDK v5. It is not compatible with AI SDK v4 or earlier. +- **`processMemories` awaits `addMemories`** before searching and calling the LLM, so each wrapped call includes one memory write and one memory search. If either request fails, the error is logged and the LLM call proceeds without memories. +- **`"google"` and `"gemini"`** are both accepted and map to `@ai-sdk/google`. +- **Removed in 3.0.0**: `org_id`, `project_id`, `org_name`, `project_name`, `output_format`, `filter_memories`, `async_mode`, `enable_graph`, `version`, `api_version`. Graph memory is now a Mem0 Platform project setting, not a provider option. +- **Default `top_k` is 10.** `threshold` and `rerank` are only sent when set (the API default for `rerank` is `false`; `threshold` is a server-side cutoff, not a floor on the returned score). - **Custom host**: set `host` in the config to point to a different Mem0 API endpoint (default: `https://api.mem0.ai`). ## References diff --git a/skills/mem0-vercel-ai-sdk/references/memory-utilities.md b/skills/mem0-vercel-ai-sdk/references/memory-utilities.md index 0ad297fc1..0beeef884 100644 --- a/skills/mem0-vercel-ai-sdk/references/memory-utilities.md +++ b/skills/mem0-vercel-ai-sdk/references/memory-utilities.md @@ -24,7 +24,7 @@ await addMemories( ```typescript async function addMemories( - messages: LanguageModelV2Prompt | string, + messages: LanguageModelV3Prompt, config?: Mem0ConfigSettings ): Promise; ``` @@ -33,15 +33,16 @@ async function addMemories( | Parameter | Type | Description | |-----------|------|-------------| -| `messages` | `LanguageModelV2Prompt \| string` | Messages to store. If a string, wrapped as `[{ role: "user", content: string }]` | +| `messages` | `LanguageModelV3Prompt` | Messages to store. A plain string is also handled at runtime (wrapped as `[{ role: "user", content: string }]`) but is not part of the declared type | | `config` | `Mem0ConfigSettings` | Optional. Must include entity scope (`user_id`, etc.) and API key | **Behavior:** 1. If `messages` is a string, wraps it as a single user message -2. Otherwise, converts `LanguageModelV2Prompt` to Mem0 format via `convertToMem0Format` (handles multimodal content) -3. Calls `POST /v1/memories/` with the converted messages and config +2. Otherwise, converts `LanguageModelV3Prompt` to Mem0 format via `convertToMem0Format` (maps multimodal parts, but the add endpoint rejects them with a 400) +3. Calls `POST {host}/v3/memories/add/` with body `{ messages, user_id?, app_id?, agent_id?, run_id?, metadata?, infer? }` (entity IDs are top-level on add) +4. Throws `HTTP error! status: ` on a non-2xx response -**Returns:** The API response from Mem0 (memory operation result). +**Returns:** The parsed JSON response from Mem0. The v3 add endpoint queues extraction and responds with `{ status: "PENDING", event_id }` (the provider returns the raw REST JSON, so keys stay snake_case, unlike the `mem0ai` client). With `infer: false` messages are stored verbatim synchronously and the response also includes `results`. --- @@ -63,7 +64,7 @@ const systemPrompt = await retrieveMemories("What restaurants do I like?", { ```typescript async function retrieveMemories( - prompt: LanguageModelV2Prompt | string, + prompt: LanguageModelV3Prompt | string, config?: Mem0ConfigSettings ): Promise; ``` @@ -72,13 +73,13 @@ async function retrieveMemories( | Parameter | Type | Description | |-----------|------|-------------| -| `prompt` | `LanguageModelV2Prompt \| string` | The query to search memories for | +| `prompt` | `LanguageModelV3Prompt \| string` | The query to search memories for | | `config` | `Mem0ConfigSettings` | Optional. Entity scope and API key | **Behavior:** -1. Flattens the prompt to a plain string (extracts text from `LanguageModelV2Prompt` parts) -2. Calls `searchInternalMemories` (`POST /v2/memories/search/`) -3. Formats each memory as `"Memory: {memory.memory}\n\n"` +1. Flattens the prompt to a plain string (extracts text from `LanguageModelV3Prompt` parts) +2. Calls `searchInternalMemories` (`POST /v3/memories/search/`) +3. Accepts either a flat array or a `{ results: [...] }` response and formats each memory as `"Memory: {memory.memory}\n\n"` 4. Wraps everything in a system prompt preamble **Returns:** A **string** containing the formatted system prompt with embedded memories. Returns `""` (empty string) if no memories found. @@ -112,7 +113,7 @@ const memories = await getMemories("What are my preferences?", { ```typescript async function getMemories( - prompt: LanguageModelV2Prompt | string, + prompt: LanguageModelV3Prompt | string, config?: Mem0ConfigSettings ): Promise; ``` @@ -121,21 +122,21 @@ async function getMemories( | Parameter | Type | Description | |-----------|------|-------------| -| `prompt` | `LanguageModelV2Prompt \| string` | The query to search memories for | +| `prompt` | `LanguageModelV3Prompt \| string` | The query to search memories for | | `config` | `Mem0ConfigSettings` | Optional. Entity scope and API key | **Behavior:** 1. Flattens the prompt to a plain string -2. Calls `searchInternalMemories` (`POST /v2/memories/search/`) -3. Returns `memories.results` (the array of memory objects) +2. Calls `searchInternalMemories` (`POST /v3/memories/search/`) +3. Normalizes the response: returns the response itself if it is an array, otherwise `response.results` (or `[]`) -**Returns:** Memory object array. +**Returns:** Flat memory object array. --- ## `searchMemories(prompt, config?)` -Retrieves the **full search API response** including results, relations, scores, and metadata. +Retrieves the **raw search API response** including results, scores, and metadata. ```typescript import { searchMemories } from "@mem0/vercel-ai-provider"; @@ -144,14 +145,14 @@ const response = await searchMemories("cooking preferences", { user_id: "alice", mem0ApiKey: "m0-xxx", }); -// Returns: { results: [{ memory: "...", score: 0.95, ... }], relations: [...] } +// Returns: { results: [{ memory: "...", score: 0.95, ... }] } ``` **Signature:** ```typescript async function searchMemories( - prompt: LanguageModelV2Prompt | string, + prompt: LanguageModelV3Prompt | string, config?: Mem0ConfigSettings ): Promise; ``` @@ -160,17 +161,17 @@ async function searchMemories( | Parameter | Type | Description | |-----------|------|-------------| -| `prompt` | `LanguageModelV2Prompt \| string` | The query to search memories for | +| `prompt` | `LanguageModelV3Prompt \| string` | The query to search memories for | | `config` | `Mem0ConfigSettings` | Optional. Entity scope and API key | **Behavior:** 1. Flattens the prompt to a plain string -2. Calls `searchInternalMemories` (`POST /v2/memories/search/`) -3. Returns the full response without any filtering +2. Calls `searchInternalMemories` (`POST /v3/memories/search/`) +3. Returns the response without any normalization -**Returns:** The complete API response object. On error, returns `[]`. +**Returns:** The API response as-is (an object with `results`, or a flat array if the API returns one). On error, logs and returns `[]` instead of throwing (unlike the other utilities, which rethrow). -**Note:** Unlike `getMemories`, this always returns the full response. +**Note:** Unlike `getMemories`, this does not unwrap `results`. --- @@ -180,7 +181,7 @@ async function searchMemories( |----------|---------|----------| | `retrieveMemories` | Formatted system prompt **string** | Injecting directly into a `system` parameter for `generateText`/`streamText` | | `getMemories` | Memory **array** | Processing memories programmatically (filtering, transforming, counting) | -| `searchMemories` | Full API **response** (results + relations) | Need relations, similarity scores, or complete metadata | +| `searchMemories` | Raw API **response** | Need similarity scores or complete metadata | | `addMemories` | API response | Storing new conversation messages as memories | ## Internal: `searchInternalMemories(query, config?, top_k?)` @@ -191,25 +192,27 @@ Not exported. Used by all retrieval functions. async function searchInternalMemories( query: string, config?: Mem0ConfigSettings, - top_k: number = 5 + top_k: number = 10 ): Promise; ``` **Behavior:** -1. Builds a `filters` object from entity identifiers (`user_id`, `app_id`, `agent_id`, `run_id`) -2. Resolves entity identifiers -3. Loads the API key from `config.mem0ApiKey` or `MEM0_API_KEY` env var -4. Calls `POST {host}/v2/memories/search/` with: +1. Builds a `filters` object from `config.filters`, then sets `user_id`, `app_id`, `agent_id`, `run_id` on it when present (entity IDs go inside `filters`, never top-level) +2. Loads the API key from `config.mem0ApiKey` or `MEM0_API_KEY` env var +3. Calls `POST {host}/v3/memories/search/` with: - `query`: the search string - `filters`: the filter object with entity identifiers - - `top_k`: from config or default 5 - - All other config fields spread into the request body + - `top_k`: `config.top_k` or default 10 (an explicit `0` is respected) + - `threshold`, `rerank`, `metadata`: only when set in config + - No other config fields (`infer`, `page`, `page_size`, `host`, `mem0ApiKey`) are sent +4. Sends `Authorization: Token ` plus `X-Mem0-Source: VERCEL_AI_SDK` and `X-Mem0-Client: mem0-vercel-ai-provider/` headers +5. Throws `HTTP error! status: ` on a non-2xx response **Default host:** `https://api.mem0.ai` ## Internal: `convertToMem0Format(messages)` -Not exported. Used by `addMemories` to convert `LanguageModelV2Prompt` messages to Mem0's format. +Not exported. Used by `addMemories` to convert `LanguageModelV3Prompt` messages to Mem0's format. **Multimodal content mapping:** @@ -223,6 +226,8 @@ Not exported. Used by `addMemories` to convert `LanguageModelV2Prompt` messages | MDX content | `{ type: "mdx_url", mdx_url: { url } }` or `{ type: "mdx", ... }` | MDX URL | `{ role, content: { type: "mdx_url", mdx_url: { url } } }` | | PDF content | `{ type: "pdf_url", pdf_url: { url } }` or `{ type: "pdf", ... }` | PDF URL | `{ role, content: { type: "pdf_url", pdf_url: { url } } }` | +`/v3/memories/add/` rejects structured (non-string) `content` with a 400 `Not a valid string.` (live-tested on the Python SDK with `infer` true and false), so a prompt containing these parts is expected to fail with `HTTP error! status: 400` (checked against the endpoint, not through the provider). Only text parts are storable. + The function handles three message content shapes: 1. **String content**: passed through directly 2. **Array content**: each element mapped individually, nulls filtered out @@ -230,7 +235,7 @@ The function handles three message content shapes: ## Internal: `flattenPrompt(prompt)` -Not exported. Extracts plain text from `LanguageModelV2Prompt` for use as a search query. +Not exported. Extracts plain text from `LanguageModelV3Prompt` for use as a search query. - Iterates over prompt parts, extracting text from `user` role messages - For `text` type content: extracts `.text` @@ -249,12 +254,12 @@ All fields are optional. Used across all utility functions. | `agent_id` | `string` | -- | Scope memories to an agent | | `run_id` | `string` | -- | Scope memories to a session/run | | `metadata` | `Record` | -- | Custom metadata | -| `filters` | `Record` | -- | Custom search filters | -| `infer` | `boolean` | -- | Enable inference | -| `page` | `number` | -- | Pagination page number | -| `page_size` | `number` | -- | Results per page | +| `filters` | `Record` | -- | Custom search filters (entity IDs above are merged in and win on conflicts) | +| `infer` | `boolean` | -- | Sent on add only. `false` stores messages verbatim without extraction | +| `page` | `number` | -- | Declared in the type, not sent by the provider | +| `page_size` | `number` | -- | Declared in the type, not sent by the provider | | `mem0ApiKey` | `string` | `MEM0_API_KEY` env | Mem0 API key | -| `top_k` | `number` | `5` | Number of memories to retrieve | -| `threshold` | `number` | -- | Minimum similarity score | -| `rerank` | `boolean` | -- | Enable re-ranking | +| `top_k` | `number` | `10` | Number of memories to retrieve | +| `threshold` | `number` | -- | Server-side relevance cutoff, not a floor on the returned score; sent only when set | +| `rerank` | `boolean` | -- (API default `false`) | Enable re-ranking, sent only when set | | `host` | `string` | `https://api.mem0.ai` | Custom API host | diff --git a/skills/mem0-vercel-ai-sdk/references/provider-api.md b/skills/mem0-vercel-ai-sdk/references/provider-api.md index 63222b815..229a8a1b9 100644 --- a/skills/mem0-vercel-ai-sdk/references/provider-api.md +++ b/skills/mem0-vercel-ai-sdk/references/provider-api.md @@ -25,26 +25,26 @@ When called with no arguments, defaults to `{ provider: "openai" }`. ## `Mem0Provider` Interface -Implements `ProviderV2` from `@ai-sdk/provider`. +Implements `ProviderV3` from `@ai-sdk/provider` (`specificationVersion: "v3"`, AI SDK v6). ```typescript -interface Mem0Provider extends ProviderV2 { +interface Mem0Provider extends ProviderV3 { // Call directly as a function - (modelId: Mem0ChatModelId, settings?: Mem0ChatSettings): LanguageModelV2; + (modelId: Mem0ChatModelId, settings?: Mem0ChatSettings): LanguageModelV3; // Or use named methods - chat(modelId: Mem0ChatModelId, settings?: Mem0ChatSettings): LanguageModelV2; - completion(modelId: Mem0ChatModelId, settings?: Mem0ChatSettings): LanguageModelV2; - languageModel(modelId: Mem0ChatModelId, settings?: Mem0ChatSettings): LanguageModelV2; + chat(modelId: Mem0ChatModelId, settings?: Mem0ChatSettings): LanguageModelV3; + completion(modelId: Mem0ChatModelId, settings?: Mem0ChatSettings): LanguageModelV3; + languageModel(modelId: Mem0ChatModelId, settings?: Mem0ChatSettings): LanguageModelV3; } ``` - **Direct call** (`mem0("gpt-5-mini", {...})`): creates a generic language model (neither chat nor completion mode forced). -- **`chat()`**: creates a model with `modelType: "chat"` (note: in the current source, the chat constructor sets `modelType: "completion"` -- this appears to be a bug; functionally equivalent to `completion()` at present). +- **`chat()`**: creates a model with `modelType: "chat"`. - **`completion()`**: creates a model with `modelType: "completion"`. - **`languageModel()`**: alias for the generic model (same as direct call). -All three return a `Mem0GenericLanguageModel` instance implementing `LanguageModelV2`. +All three return a `Mem0GenericLanguageModel` instance implementing `LanguageModelV3`. ## `Mem0ProviderSettings` Interface @@ -52,14 +52,14 @@ Configuration passed to `createMem0()`. ```typescript interface Mem0ProviderSettings { - baseURL?: string; // Base URL for the LLM provider (default: "http://api.openai.com") - headers?: Record; // Custom headers for LLM requests + baseURL?: string; // Stored on the model config (default: "https://api.openai.com"), not applied to upstream LLM requests + headers?: Record; // Stored on the model config, not applied to upstream LLM requests provider?: string; // LLM provider name (default: "openai") mem0ApiKey?: string; // Mem0 Platform API key (or use MEM0_API_KEY env var) apiKey?: string; // LLM provider API key (e.g., OpenAI key) mem0Config?: Mem0Config; // Default Mem0 config (user_id, etc.) applied to all calls config?: LLMProviderSettings; // Provider-specific settings (OpenAI, Anthropic, etc.) - fetch?: typeof fetch; // Custom fetch implementation (for testing/middleware) + fetch?: typeof fetch; // Stored on the model config, not used by the upstream LLM client or Mem0 API calls generateId?: () => string; // Custom ID generator (internal use) name?: string; // Provider instance name modelType?: "completion" | "chat"; // Force model type @@ -75,7 +75,7 @@ interface Mem0ProviderSettings { | `apiKey` | LLM provider API key | `"sk-xxx"` (OpenAI), `"sk-ant-xxx"` (Anthropic) | | `mem0Config` | Default Mem0 settings for all calls | `{ user_id: "alice" }` | | `config` | Provider-specific SDK settings | `{ organization: "org-xxx" }` for OpenAI | -| `baseURL` | Override LLM provider base URL | `"https://my-proxy.example.com"` | +| `config.baseURL` | Override LLM provider base URL (put it inside `config`; the top-level `baseURL` does not reach the upstream client) | `{ baseURL: "https://my-proxy.example.com/v1" }` | ## `mem0` Singleton @@ -94,7 +94,7 @@ Equivalent to `createMem0()` with no arguments. ## `Mem0ConfigSettings` Interface -Configuration for memory operations. Used as `Mem0ChatSettings` (per-call) or `Mem0Config` (provider-level default). All fields are optional. +Configuration for memory operations. Used as `Mem0ChatSettings` (per-call) or `Mem0Config` (provider-level default; same shape, not exported from the package entry point). All fields are optional. ```typescript interface Mem0ConfigSettings { @@ -104,13 +104,13 @@ interface Mem0ConfigSettings { run_id?: string; // Scope memories to a specific run/session metadata?: Record; // Custom metadata attached to memories filters?: Record; // Custom filters for memory search - infer?: boolean; // Enable inference during memory operations - page?: number; // Pagination: page number - page_size?: number; // Pagination: results per page + infer?: boolean; // Sent on add only: false stores messages verbatim without extraction + page?: number; // Declared in the type, not sent by the provider + page_size?: number; // Declared in the type, not sent by the provider mem0ApiKey?: string; // Mem0 API key (overrides provider-level key) - top_k?: number; // Number of memories to retrieve (default: 5) - threshold?: number; // Minimum similarity score for retrieval (default: 0.1) - rerank?: boolean; // Enable re-ranking of search results (default: false) + top_k?: number; // Number of memories to retrieve (default: 10) + threshold?: number; // Server-side relevance cutoff; sent only when set + rerank?: boolean; // Enable re-ranking of search results; sent only when set (API default: false) host?: string; // Custom Mem0 API host (default: "https://api.mem0.ai") } ``` @@ -137,17 +137,18 @@ mem0("gpt-5-mini", { user_id: "alice" }) ## `LLMProviderSettings` Type -Union of provider-specific settings. Extends all supported provider setting interfaces: +Union of provider-specific settings for all supported provider SDKs: ```typescript -interface LLMProviderSettings extends - OpenAIProviderSettings, - AnthropicProviderSettings, - CohereProviderSettings, - GroqProviderSettings {} +type LLMProviderSettings = + | OpenAIProviderSettings + | AnthropicProviderSettings + | CohereProviderSettings + | GroqProviderSettings + | GoogleGenerativeAIProviderSettings; ``` -Pass via the `config` field of `Mem0ProviderSettings` to forward settings to the underlying LLM provider SDK. +Pass via the `config` field of `Mem0ProviderSettings` to forward settings (e.g., `baseURL`, `headers`, `apiKey`) to the underlying LLM provider SDK. `config` is spread after `apiKey`, so a `config.apiKey` takes precedence. ## Provider Selection: `Mem0ClassSelector` @@ -155,12 +156,12 @@ Internal class that maps the `provider` string to the correct AI SDK provider. ```typescript class Mem0ClassSelector { - static supportedProviders = ["openai", "anthropic", "cohere", "groq", "google"]; + static supportedProviders = ["openai", "anthropic", "cohere", "groq", "google", "gemini"]; // ... } ``` -**Important:** The `"gemini"` alias exists in the provider switch statement (maps to `createGoogleGenerativeAI`) but is **NOT** in the `supportedProviders` list. The constructor validates against `supportedProviders`, so using `"gemini"` will throw `"Model not supported: gemini"`. Use `"google"` instead. +`"gemini"` is an alias of `"google"` (both map to `createGoogleGenerativeAI`). Any other value throws `"Model not supported: "`. ### Provider mapping @@ -170,7 +171,7 @@ class Mem0ClassSelector { | `"anthropic"` | `@ai-sdk/anthropic` | `createAnthropic` | | `"cohere"` | `@ai-sdk/cohere` | `createCohere` | | `"groq"` | `@ai-sdk/groq` | `createGroq` | -| `"google"` | `@ai-sdk/google` | `createGoogleGenerativeAI` | +| `"google"` or `"gemini"` | `@ai-sdk/google` | `createGoogleGenerativeAI` | ## `Mem0` Facade Class @@ -184,7 +185,7 @@ const chatModel = mem0.chat("gpt-5-mini", { user_id: "alice" }); const completionModel = mem0.completion("gpt-5-mini"); ``` -The facade defaults its base URL to `"http://127.0.0.1:11434/api"` (Ollama-style) rather than `"http://api.openai.com"`. It always uses `"openai"` as the provider for created models. +The facade defaults its base URL to `"https://api.openai.com"`. It always uses `"openai"` as the provider for created models, and only stores `baseURL` and `headers` from its options: the `provider`, `mem0ApiKey`, and `apiKey` options are ignored, so `MEM0_API_KEY` and `OPENAI_API_KEY` must come from the environment. Prefer `createMem0` for anything beyond a quick start. **Methods:** - `chat(modelId, settings?)` -- creates a model with `modelType: "chat"` @@ -192,13 +193,11 @@ The facade defaults its base URL to `"http://127.0.0.1:11434/api"` (Ollama-style ## `Mem0GenericLanguageModel` Class -The core class implementing `LanguageModelV2`. Created by `createMem0` or the `Mem0` facade. +The core class implementing `LanguageModelV3`. Created by `createMem0` or the `Mem0` facade. ```typescript -class Mem0GenericLanguageModel implements LanguageModelV2 { - readonly specificationVersion = "v2"; - readonly defaultObjectGenerationMode = "json"; - readonly supportsImageUrls = false; +class Mem0GenericLanguageModel implements LanguageModelV3 { + readonly specificationVersion = "v3"; readonly supportedUrls: Record = { '*': [/.*/] }; provider: string; // e.g., "openai" @@ -206,22 +205,26 @@ class Mem0GenericLanguageModel implements LanguageModelV2 { settings: Mem0ChatSettings; config: Mem0ChatConfig; - async doGenerate(options: LanguageModelV2CallOptions): Promise<...>; - async doStream(options: LanguageModelV2CallOptions): Promise<...>; + async doGenerate(options: LanguageModelV3CallOptions): Promise<...>; + async doStream(options: LanguageModelV3CallOptions): Promise<...>; } ``` +`defaultObjectGenerationMode` and `supportsImageUrls` (V2 properties) no longer exist. + Both `doGenerate` and `doStream` follow the same internal flow: -1. Build `Mem0ConfigSettings` from `config.mem0Config` merged with `settings` +1. Build `Mem0ConfigSettings` from `config.mem0ApiKey`, then `config.mem0Config`, then `settings` (later entries win) 2. Call `processMemories`: - - Fire `addMemories` as fire-and-forget (no await, `.then().catch()`) - - Await `getMemories` to retrieve relevant memories - - Format memories as a system message and prepend to the prompt + - Await `addMemories` (errors are logged and ignored) + - Await `getMemories` to retrieve relevant memories (on failure, continue with no memories) + - If any memories were found, format them as a system message and prepend it to a copy of the prompt 3. Create the underlying LLM model via `Mem0ClassSelector` 4. Delegate to the underlying model's `doGenerate` or `doStream` 5. Return the result +`doGenerate` additionally appends a `source` content part (`title: "Mem0 Memories"`) with `providerMetadata.mem0.memories` and `providerMetadata.mem0.memoriesText` when memories were retrieved. `doStream` returns the underlying stream result unchanged (no Mem0 source) and throws `"Streaming failed or method not implemented."` if streaming setup fails. + **Note:** Entity identifier fields use snake_case (`user_id`, `app_id`, `agent_id`, `run_id`) to match the Mem0 API. ## Type: `Mem0ChatModelId` @@ -230,4 +233,4 @@ Both `doGenerate` and `doStream` follow the same internal flow: type Mem0ChatModelId = string & NonNullable; ``` -Any non-null string. The model ID is passed through to the underlying provider (e.g., `"gpt-5-mini"`, `"gemini-pro"`). +Any non-null string. The model ID is passed through to the underlying provider (e.g., `"gpt-5-mini"`, `"gemini-2.5-flash"`). diff --git a/skills/mem0-vercel-ai-sdk/references/usage-patterns.md b/skills/mem0-vercel-ai-sdk/references/usage-patterns.md index bd1e66518..16cd32b3a 100644 --- a/skills/mem0-vercel-ai-sdk/references/usage-patterns.md +++ b/skills/mem0-vercel-ai-sdk/references/usage-patterns.md @@ -20,7 +20,7 @@ const { text } = await generateText({ console.log(text); ``` -Memories are automatically retrieved before the call and stored after. +The prompt is stored to Mem0 and relevant memories are retrieved before the LLM call (see section 8). ## 2. Wrapped Model with streamText (Streaming) @@ -42,7 +42,7 @@ for await (const chunk of result.textStream) { } ``` -Memory retrieval happens before streaming begins. The conversation is stored to Mem0 as a fire-and-forget call (non-blocking). +The add request and the memory search both finish before streaming begins (extraction itself is async). The Mem0 source (`sources`) is only attached by `generateText`, not by streaming. ## 3. Standalone Utilities with OpenAI @@ -136,7 +136,7 @@ console.log(object); // { breakfast: "Avocado toast (you mentioned loving it)", lunch: "...", ... } ``` -The `defaultObjectGenerationMode` is `"json"`, so structured output works out of the box. +The wrapped model forwards all call options (including the response format) to the underlying provider, so structured output works out of the box. `generateObject` is deprecated in AI SDK v6 in favor of `generateText` with `output: Output.object({ schema })`; both go through the same wrapped model. ## 6. Multi-Provider Setup @@ -195,22 +195,20 @@ A POST handler that uses the wrapped model in a Next.js App Router API route. ```typescript // app/api/chat/route.ts -import { streamText } from "ai"; +import { convertToModelMessages, streamText, UIMessage } from "ai"; import { createMem0 } from "@mem0/vercel-ai-provider"; const mem0 = createMem0(); export async function POST(req: Request) { - const { messages, user_id } = await req.json(); - - const lastMessage = messages[messages.length - 1]; + const { messages, user_id }: { messages: UIMessage[]; user_id: string } = await req.json(); const result = streamText({ model: mem0("gpt-5-mini", { user_id }), - prompt: lastMessage.content, + messages: await convertToModelMessages(messages), }); - return result.toDataStreamResponse(); + return result.toUIMessageStreamResponse(); } ``` @@ -219,22 +217,25 @@ export async function POST(req: Request) { ```typescript // app/api/chat/route.ts import { openai } from "@ai-sdk/openai"; -import { streamText } from "ai"; +import { convertToModelMessages, streamText, UIMessage } from "ai"; import { retrieveMemories, addMemories } from "@mem0/vercel-ai-provider"; export async function POST(req: Request) { - const { messages, user_id } = await req.json(); + const { messages, user_id }: { messages: UIMessage[]; user_id: string } = await req.json(); const lastMessage = messages[messages.length - 1]; + const lastText = lastMessage.parts + .flatMap((part) => (part.type === "text" ? [part.text] : [])) + .join(" "); // Retrieve relevant memories - const memories = await retrieveMemories(lastMessage.content, { + const memories = await retrieveMemories(lastText, { user_id, }); // Stream the response const result = streamText({ model: openai("gpt-5-mini"), - prompt: lastMessage.content, + messages: await convertToModelMessages(messages), system: memories, }); @@ -242,14 +243,14 @@ export async function POST(req: Request) { result.text.then(async (text) => { await addMemories( [ - { role: "user", content: [{ type: "text", text: lastMessage.content }] }, + { role: "user", content: [{ type: "text", text: lastText }] }, { role: "assistant", content: [{ type: "text", text }] }, ], { user_id } ); }); - return result.toDataStreamResponse(); + return result.toUIMessageStreamResponse(); } ``` @@ -260,25 +261,26 @@ export async function POST(req: Request) { ``` 1. doGenerate(options) or doStream(options) is called 2. processMemories(messagesPrompts, mem0Config): - a. addMemories(messagesPrompts, mem0Config) - --> fire-and-forget: .then().catch(), NO await + a. await addMemories(messagesPrompts, mem0Config) --> POST /v3/memories/add/ with converted messages + --> errors are caught and logged b. await getMemories(messagesPrompts, mem0Config) --> POST /v3/memories/search/ with flattened prompt --> returns memory array c. Format memories into system message string - d. Prepend system message to messagesPrompts array + d. If memories were found, prepend the system message to a copy of messagesPrompts e. Return { memories, messagesPrompts } 3. Create underlying LLM via Mem0ClassSelector.createProvider() 4. Call model.doGenerate(updatedOptions) or model.doStream(updatedOptions) -5. Return result +5. doGenerate appends the "Mem0 Memories" source when memories were found +6. Return result ``` -**Critical detail:** The `addMemories` call in step 2a is **NON-BLOCKING**. It uses `.then().catch()` without `await`, meaning: -- Memory storage happens asynchronously in the background -- The LLM response is not delayed by the memory write -- If the memory write fails, it logs an error but does not affect the response -- There is a brief window where the latest conversation is not yet stored +**Critical detail:** The `addMemories` call in step 2a is **awaited**, meaning: +- The add request is sent (and awaited) before the search and the LLM call, but extraction is async (`/v3/memories/add/` only queues the work and returns `PENDING`), so facts from the current prompt are usually not searchable until a later call +- Each wrapped call adds one Mem0 write and one Mem0 search of latency before the LLM starts +- If the memory write fails, it logs an error and the call continues +- `messagesPrompts` is the full prompt (all roles, including earlier turns), so every call sends the entire conversation to the add endpoint ### Memory injection format @@ -318,8 +320,8 @@ const memories = await retrieveMemories(prompt, { const mem0 = createMem0(); const model = mem0("gpt-5-mini", { user_id: "alice", - top_k: 10, // retrieve up to 10 memories (default: 5) - threshold: 0.8, // only memories with score >= 0.8 + top_k: 20, // retrieve up to 20 memories (default: 10) + threshold: 0.8, // server-side cutoff applied before score blending rerank: true, // enable re-ranking of results }); ``` diff --git a/skills/mem0/SKILL.md b/skills/mem0/SKILL.md index 508870f01..4827fcc4b 100644 --- a/skills/mem0/SKILL.md +++ b/skills/mem0/SKILL.md @@ -15,10 +15,11 @@ description: > license: Apache-2.0 metadata: author: mem0ai - version: "3.0.0" + version: "3.1.0" category: ai-memory tags: "memory, personalization, ai, python, typescript, vector-search" -compatibility: Requires Python 3.10+ or Node.js 18+, pip install mem0ai or npm install mem0ai, MEM0_API_KEY env var (Platform), and internet access to api.mem0.ai. SDK v3 with v2 compatibility mode available. + mem0_tested_versions: "mem0ai (PyPI) >=2.0.0,<3.0.0; mem0ai (npm) >=3.0.0,<4.0.0" +compatibility: Requires Python 3.10+ or Node.js 18+, pip install mem0ai or npm install mem0ai, MEM0_API_KEY env var (Platform), and internet access to api.mem0.ai. Targets the v3 API (Python mem0ai 2.x, TypeScript mem0ai 3.x). --- # Mem0 Platform Integration @@ -134,20 +135,20 @@ def chat(user_input: str, user_id: str) -> str: ## Common edge cases -- **Search returns empty:** Memories process asynchronously. Wait 2-3s after `add()` before searching. Also verify `user_id` matches exactly (case-sensitive) and use `filters={"user_id": "..."}` syntax. +- **Search returns empty:** `add()` is asynchronous and returns `{"event_id": "...", "status": "PENDING"}` (`eventId` on the TS client). Memories are searchable once the event is `SUCCEEDED` (poll `GET /v1/event/{event_id}/`, or wait a few seconds). `infer=False` is synchronous. Also verify `user_id` matches exactly (case-sensitive) and use `filters={"user_id": "..."}` syntax. - **AND filter with user_id + agent_id returns empty:** Entities are stored separately. Use `OR` instead, or query separately. - **Duplicate memories:** Don't mix `infer=True` (default) and `infer=False` for the same data. Stick to one mode. -- **Wrong import:** Always use `from mem0 import MemoryClient` (or `AsyncMemoryClient` for async). Do not use `from mem0 import Memory`. -- **v3 defaults:** `top_k=20`, `threshold=0.1`, `rerank=False`. Adjust as needed for your use case. +- **Wrong import:** For the hosted Platform use `from mem0 import MemoryClient` (or `AsyncMemoryClient` for async). `from mem0 import Memory` is the self-hosted OSS class and does not use `MEM0_API_KEY`. +- **v3 defaults (Platform):** `top_k=10`, `rerank=False`. `threshold` is a server-side cutoff applied before score blending, not a floor on the returned `score` (the default and `0.0` return the same or nearly the same results). The client sends none of these unless you pass them. The OSS `Memory.search()` default is `top_k=20`. Adjust as needed for your use case. ## v2 Compatibility -If you're using SDK v2.x, note these differences: -- **Entity IDs:** Pass `user_id` as top-level kwarg to `search()` instead of inside `filters` -- **Defaults:** `top_k=100`, no threshold, `rerank=True` -- **Graph memory:** Available via `enable_graph=True` +The "v2" line is Python SDK 1.x and TypeScript SDK 2.x. If you are still on it, note these differences from the current SDKs (Python 2.x, TypeScript 3.x): +- **Entity IDs:** `user_id` / `agent_id` / `run_id` could be top-level kwargs on `search()` and `get_all()`. They now go inside `filters` (top-level raises an error) +- **Defaults (Platform):** `threshold=0.3`, `rerank=False`. OSS: `top_k=100`, no threshold, `rerank=True` +- **Graph memory:** `enable_graph=True` and `relations` are gone. Entity linking is built in (see [client/python.md](client/python.md) for OSS) -See the [migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for details. +See the [Platform migration guide](https://docs.mem0.ai/migration/platform-v2-to-v3) and the [OSS migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for details. ## Live documentation search diff --git a/skills/mem0/client/differences.md b/skills/mem0/client/differences.md index e5e80e250..3257e643e 100644 --- a/skills/mem0/client/differences.md +++ b/skills/mem0/client/differences.md @@ -9,9 +9,9 @@ Quick-reference cheatsheet for developers working across both Mem0 SDKs. | Import (Platform) | `from mem0 import MemoryClient` | `import MemoryClient from 'mem0ai'` | | Import (OSS) | `from mem0 import Memory` | `import { Memory } from 'mem0ai/oss'` | | Constructor | `MemoryClient(api_key="m0-xxx")` | `new MemoryClient({ apiKey: 'm0-xxx' })` | -| Required param | `api_key` (positional or kwarg) | `apiKey` (in options object) | +| Required param | `api_key` (optional, falls back to `MEM0_API_KEY`) | `apiKey` (required, in options object) | -Both read from `MEM0_API_KEY` env var if no key provided. +Python reads `MEM0_API_KEY` if no key is passed. TypeScript does not read the environment: pass `apiKey: process.env.MEM0_API_KEY` yourself. ## Method Naming @@ -38,6 +38,11 @@ Both read from `MEM0_API_KEY` env var if no key provided. | Create export | `create_memory_export()` | `createMemoryExport()` | | Get export | `get_memory_export()` | `getMemoryExport()` | | Feedback | `feedback()` | `feedback()` | +| Get profile | `get_profile(entity_id)` | `getProfile({ entityId })` | +| Generate profile | `generate_profile(entity_id)` | `generateProfile({ entityId })` | +| Profile settings | `get_profile_settings()` / `update_profile_settings()` | `getProfileSettings()` / `updateProfileSettings()` | +| Sample profiles | `sample_profiles()` | `sampleProfiles()` | +| Profile job | `get_profile_job()` | `getProfileJob()` | **Rule:** Python uses `snake_case`, TypeScript uses `camelCase` for method names. @@ -61,8 +66,8 @@ await client.search('query', { filters: { user_id: 'alice' }, topK: 5, rerank: t | Aspect | Python | TypeScript | |--------|--------|------------| -| HTTP library | httpx | axios | -| Default timeout | 300s | 60s | +| HTTP library | httpx | native `fetch` | +| Default timeout | 300s | None set by the SDK | | Sync support | Yes (`MemoryClient`) | No (all async) | | Async support | Yes (`AsyncMemoryClient`) | All methods are async | | Project management | `client.project.*` (separate class) | `client.getProject()` / `client.updateProject()` | @@ -87,7 +92,7 @@ These methods exist in Python but not TypeScript: | Method | Description | |--------|-------------| -| `deleteUser(data)` | Convenience method for single entity deletion | +| `deleteUser(data)` | Deprecated single entity deletion (use `deleteUsers`) | | `ping()` | Health check endpoint | ## OSS Config Naming diff --git a/skills/mem0/client/node.md b/skills/mem0/client/node.md index ca85ba7ba..4b72d04f6 100644 --- a/skills/mem0/client/node.md +++ b/skills/mem0/client/node.md @@ -21,12 +21,15 @@ import MemoryClient from 'mem0ai'; const client = new MemoryClient({ apiKey: 'm0-xxx' }); ``` -**Constructor:** `new MemoryClient({ apiKey })`. If `apiKey` is not provided, reads from `MEM0_API_KEY` environment variable. +**Constructor:** `new MemoryClient({ apiKey, host?, identityCacheMax? })`. `apiKey` is required: the constructor throws `Mem0 API key is required` when it is missing or empty. There is no `MEM0_API_KEY` environment fallback, so pass `apiKey: process.env.MEM0_API_KEY` yourself. -- HTTP library: `axios` -- Timeout: 60 seconds -- Base URL: `https://api.mem0.ai` +- Also a named export: `import { MemoryClient, Feedback, WebhookEvent } from 'mem0ai'` +- HTTP library: native `fetch` (the axios instance in `mem0.ts` is unused) +- Timeout: none set by the SDK +- Base URL: `https://api.mem0.ai` (override with `host`) - All methods are async (return `Promise`) +- Top-level option names are camelCase and responses come back camelCased (`event_id` becomes `eventId`). Keys inside `filters` are sent as written, so keep them snake_case (`user_id`). +- `MEM0_SOURCE`, `MEM0_APPLICATION` and `MEM0_CLIENT_STACK` set the surface-identity headers for wrappers that cannot pass options. --- @@ -52,16 +55,22 @@ await client.add(messages, { userId: 'alice' }); | `options.appId` | string | Application identifier | | `options.runId` | string | Session identifier | | `options.metadata` | object | Custom key-value pairs | -| `options.infer` | boolean | If false, store raw text (default: true) | +| `options.infer` | boolean | If false, store messages as-is without extraction (default: true) | +| `options.customCategories` | `{[name]: description}[]` | Per-call category list | +| `options.customInstructions` | string | Per-call extraction instructions | +| `options.agentCustomInstructions` | string | Per-call extraction instructions for agent-scoped memories | +| `options.timestamp` | number | Unix timestamp (seconds) to record as the memory time | +| `options.expirationDate` | string | Date after which the memory is no longer returned | +| `options.structuredDataSchema` | object | Schema for structured extraction | -**Returns:** `Promise` -- list of events +**Returns:** typed `Promise>`, but the v3 API queues extraction and responds with `{ status: 'PENDING', eventId }`. With `infer: false` the call is synchronous and the response carries `message`, `status` and `results`. The client has no event-polling method (REST `GET /v1/event/{event_id}/`, see `../references/api-reference.md`). #### search(query, options?) Search memories by semantic similarity. ```typescript -const results = await client.search('dietary preferences', { filters: { user_id: 'alice' }, topK: 20 }); +const results = await client.search('dietary preferences', { filters: { user_id: 'alice' }, topK: 10 }); for (const mem of results.results) { console.log(mem.memory, mem.score); } @@ -71,11 +80,20 @@ for (const mem of results.results) { |-----------|------|-------------| | `query` | string | Natural language search query | | `options.filters` | object | Filter object with entity IDs (`user_id`, `agent_id`, etc.) and/or `AND`/`OR`/`NOT` conditions | -| `options.topK` | number | Number of results (default: 20) | +| `options.topK` | number | Number of results (default: 10) | | `options.rerank` | boolean | Enable semantic reranking (default: false) | -| `options.threshold` | number | Minimum similarity (default: 0.1) | +| `options.threshold` | number | Server-side relevance cutoff (0 to 1), applied before score blending, so it is not a floor on the returned `score`. Omitting it and passing `0` returned the same results in live tests. Filter on `score` client-side for a precise cutoff | +| `options.latestOnly` | boolean | Return only current (non-superseded) memories | +| `options.fields` | string[] | Not applied in v3 | +| `options.categories` | string[] | Not applied in v3. Use `filters: { AND: [{ categories: { in: [...] } }] }` | +| `options.metadata` | object | Not applied in v3. Use `filters: { AND: [{ metadata: {...} }] }` | +| `options.showExpired` | boolean | Include memories past their expiration date | +| `options.referenceDate` | string \| number | Treat this as "now" for relative time queries | +| `options.keywordSearch` | boolean | Not applied in v3 (removed from the v3 search schema; keyword matching is part of v3 hybrid scoring) | -**Returns:** `Promise` -- `{results: [{id, memory, score, ...}]}` +Entity IDs go inside `filters`. A top-level `userId`, `agentId`, `appId` or `runId` throws. + +**Returns:** `Promise<{ results: Array }>` -- `{results: [{id, memory, score, ...}]}` #### get(memoryId) @@ -85,7 +103,7 @@ const memory = await client.get('ea925981-...'); #### getAll(options?) -Retrieve all memories. Requires at least one entity identifier in filters. +Retrieve all memories. Requires non-empty `filters`; scope them with at least one entity identifier. ```typescript const memories = await client.getAll({ filters: { user_id: 'alice' } }); @@ -99,7 +117,12 @@ const filtered = await client.getAll({ |-----------|------|-------------| | `options.filters` | object | Filter object with entity IDs (`user_id`, `agent_id`, etc.) and/or `AND`/`OR`/`NOT` conditions | | `options.page` | number | Page number | -| `options.pageSize` | number | Results per page | +| `options.pageSize` | number | Results per page (default: 100, max: 200) | +| `options.startDate` / `options.endDate` / `options.categories` | - | Not applied in v3. Use `filters` with `created_at` or `categories` | +| `options.latestOnly` | boolean | Return only current (non-superseded) memories | +| `options.showExpired` | boolean | Include memories past their expiration date | + +**Returns:** `Promise<{ count, next, previous, results: Array }>` #### update(memoryId, data) @@ -113,25 +136,33 @@ await client.update('ea925981-...', { text: 'Updated', metadata: { verified: tru | `memoryId` | string | Memory ID | | `data.text` | string | New content | | `data.metadata` | object | New metadata | -| `data.timestamp` | string | New timestamp | +| `data.timestamp` | number \| string | New timestamp | +| `data.expirationDate` | string \| null | New expiration date, `null` to clear | -#### delete(memoryId) +At least one of `text`, `metadata`, `timestamp` or `expirationDate` is required, otherwise the call throws. + +#### delete(memoryId, options?) ```typescript await client.delete('ea925981-...'); +await client.delete('ea925981-...', { deleteLinked: true }); ``` +`deleteLinked: true` also deletes the older memories this one superseded (default: false). + #### deleteAll(options?) ```typescript await client.deleteAll({ userId: 'alice' }); ``` +Takes top-level `userId`, `agentId`, `appId`, `runId` (not `filters`). + #### history(memoryId) ```typescript const history = await client.history('ea925981-...'); -// Returns: [{previousValue, newValue, action, timestamps}] +// Returns: [{id, memoryId, input, oldMemory, newMemory, event, userId, categories, metadata, createdAt, updatedAt}] ``` --- @@ -147,6 +178,8 @@ await client.batchUpdate([ ]); ``` +Each item must include `text`. `metadata` on a batch item is ignored and a metadata-only item returns a 400. Use `update(memoryId, { metadata })` to change metadata. + #### batchDelete(memories) ```typescript @@ -160,17 +193,19 @@ await client.batchDelete(['uuid-1', 'uuid-2', 'uuid-3']); #### users() ```typescript -const users = await client.users(); -// Returns: {results: [{type: "user", name: "alice"}, ...]} +const users = await client.users({ page: 1, pageSize: 50 }); +// Returns: {count, next, previous, totalUsers, totalAgents, totalApps, totalRuns, results: [{id, name, type, createdAt, updatedAt, owner, metadata, isPlayground}, ...]} ``` -#### deleteUser(data) / deleteUsers(data) +#### deleteUsers(params) ```typescript -await client.deleteUser({ userId: 'alice' }); // Single entity -await client.deleteUsers({ agentId: 'bot-1' }); // Flexible +await client.deleteUsers({ userId: 'alice' }); +await client.deleteUsers({ agentId: 'bot-1' }); ``` +Takes one of `userId`, `agentId`, `appId`, `runId`. Calling it with no arguments deletes ALL users, agents, apps and runs, but only those on the first page returned by `users()`: with many entities, re-run it until it throws `No entities to delete`, or page with `users({ page, pageSize })` and delete per entity. `deleteUser({ entity_id, entity_type })` still exists but is deprecated. + --- ### Project Management @@ -182,24 +217,29 @@ const config = await client.getProject({ fields: ['customCategories'] }); // Update project settings await client.updateProject({ customInstructions: 'Extract dietary preferences and health info', + agentCustomInstructions: 'Extract operational lessons for the agent', customCategories: [{ health: 'Medical and dietary info' }], + decay: true, }); ``` +`getProject` requires its options argument (pass `{}` for no field filter). Other `updateProject` keys: `memoryDepth`, `usecaseSetting`, `multilingual`, `version`. Both methods wait for the org and project identity the client resolves at startup and throw if it cannot be resolved. + --- ### Webhooks ```typescript -// List +import { WebhookEvent } from 'mem0ai'; + +// List (projectId is optional, defaults to the project of your API key) const webhooks = await client.getWebhooks({ projectId: 'proj_123' }); -// Create +// Create (always uses the project resolved from your API key) const webhook = await client.createWebhook({ url: 'https://your-app.com/webhook', name: 'Memory Logger', - projectId: 'proj_123', - eventTypes: ['memory_add', 'memory_update'], + eventTypes: [WebhookEvent.MEMORY_ADDED, WebhookEvent.MEMORY_UPDATED], }); // Update @@ -218,26 +258,50 @@ await client.deleteWebhook({ webhookId: 'wh_123' }); ### Feedback ```typescript +import { Feedback } from 'mem0ai'; + await client.feedback({ memoryId: 'mem-123', - feedback: 'POSITIVE', + feedback: Feedback.POSITIVE, feedbackReason: 'Accurately captured preference', }); ``` +`Feedback` values: `POSITIVE`, `NEGATIVE`, `VERY_NEGATIVE`. `feedback` and `feedbackReason` are optional, and `null` clears existing feedback. + --- ### Export ```typescript const exportReq = await client.createMemoryExport({ - schema: JSON.stringify({ type: 'object', properties: { name: { type: 'string' } } }), - filters: { user_id: 'alice' }, + schema: { type: 'object', properties: { name: { type: 'string' } } }, + filters: { AND: [{ user_id: 'alice' }] }, + exportInstructions: 'Build a profile from all memories', }); const result = await client.getMemoryExport({ memoryExportId: exportReq.id }); ``` +`schema` is an object (not a JSON string) and `schema` and `filters` are both required. `getMemoryExport` needs `memoryExportId` or `filters`. + +--- + +### User Profiles (beta) + +```typescript +await client.updateProfileSettings({ + enabled: true, + schema: { type: 'object', properties: { communication_style: { type: 'string', description: 'How the user prefers to be addressed' } } }, +}); + +const job = await client.generateProfile({ entityId: 'alice' }); +const result = await client.getProfile({ entityId: 'alice' }); +if (result.status === 'succeeded') console.log(result.profile); +``` + +Other methods: `getProfileSettings()`, `sampleProfiles({ limit?, idempotencyKey? })`, `getProfileJob(jobIdOrStatusUrl)`. Generation is asynchronous, so branch on `status` (`succeeded`, `pending`, `failed`, `not_enabled`, `insufficient_data`) rather than on an empty `profile`. Every schema property needs a `description`. + --- ### TypeScript Types @@ -245,15 +309,20 @@ const result = await client.getMemoryExport({ memoryExportId: exportReq.id }); Key interfaces from `mem0.types.ts`: ```typescript -interface Message { role: string; content: string; } -interface Memory { id: string; memory: string; userId: string; categories: string[]; score?: number; /* ... */ } -interface MemoryOptions { userId?: string; agentId?: string; appId?: string; runId?: string; metadata?: object; /* ... */ } -interface SearchOptions { filters?: object; topK?: number; rerank?: boolean; threshold?: number; /* ... */ } -interface MemoryHistory { id: string; memoryId: string; previousValue: string; newValue: string; action: string; /* ... */ } -interface FeedbackPayload { memoryId: string; feedback: string; feedbackReason?: string; } -interface WebhookCreatePayload { url: string; name: string; projectId: string; eventTypes: string[]; } +interface Message { role: 'user' | 'assistant'; content: string | { type: 'image_url'; image_url: { url: string } }; } +interface Memory { id: string; memory?: string; userId?: string; categories?: string[]; score?: number; expirationDate?: string | null; /* ... */ } +interface AddMemoryOptions { userId?: string; agentId?: string; appId?: string; runId?: string; metadata?: object; infer?: boolean; /* ... */ } +interface SearchMemoryOptions { filters?: object; topK?: number; rerank?: boolean; threshold?: number; /* ... */ } +interface GetAllMemoryOptions { filters?: object; page?: number; pageSize?: number; /* ... */ } +interface MemoryHistory { id: string; memoryId: string; oldMemory: string | null; newMemory: string | null; event: string; /* ... */ } +interface FeedbackPayload { memoryId: string; feedback?: Feedback | null; feedbackReason?: string | null; } +interface WebhookCreatePayload { name: string; url: string; eventTypes: WebhookEvent[]; } ``` +`Message.content` is typed to allow an `image_url` object, but `/v3/memories/add/` rejects structured content with a 400 (`Not a valid string.`), so pass a plain string (see Multimodal Support in [features.md](../references/features.md)). + +Also exported: `DeleteAllMemoryOptions`, `MemoryUpdateBody`, `PromptUpdatePayload`, `Webhook`, `WebhookUpdatePayload`, `User`, `AllUsers`, the profile types, and the error classes `MemoryError`, `AuthenticationError`, `RateLimitError`, `ValidationError`, `MemoryNotFoundError`, `NetworkError`, `ConfigurationError`, `MemoryQuotaExceededError`. + --- ## Open Source / Self-Hosted @@ -279,21 +348,21 @@ const m = new Memory(); // Uses default config ```typescript const config = { llm: { - provider: 'openai', // openai, groq, anthropic, google, ollama, lmstudio, mistral, azure + provider: 'openai', // openai, openai_structured, anthropic, groq, ollama, lmstudio, google (gemini), azure_openai, mistral, langchain, deepseek, xai, sarvam, aws_bedrock, litellm, minimax, together, vllm config: { model: 'gpt-5-mini', apiKey: 'sk-xxx', }, }, embedder: { - provider: 'openai', // openai, ollama, lmstudio, google, azure, langchain, anthropic + provider: 'openai', // openai, aws_bedrock, ollama, lmstudio, together, google (gemini), azure_openai, fastembed, langchain, vertexai, huggingface config: { model: 'text-embedding-3-small', apiKey: 'sk-xxx', }, }, vectorStore: { - provider: 'qdrant', // memory, qdrant, redis, supabase, langchain, azure_ai_search, pgvector + provider: 'qdrant', // memory (default), qdrant, chroma, redis, valkey, supabase, langchain, vectorize, azure-ai-search, vertex_ai_vector_search, pgvector, databricks, neptune-analytics, elasticsearch, opensearch, upstash_vector, azure_mysql, cassandra, pinecone, s3-vectors, turbopuffer, milvus, mongodb, weaviate, oracledb, baidu config: { collectionName: 'my_memories', host: 'localhost', @@ -310,6 +379,8 @@ const m = new Memory(config); const m2 = Memory.fromConfig(config); ``` +Defaults when omitted: LLM `openai` `gpt-5-mini`, embedder `openai` `text-embedding-3-small`, vector store `memory` (in-process), history `sqlite` at `memory.db`. `reranker` is also accepted (providers `cohere`, `zero_entropy`, `sentence_transformer`, `huggingface`, `llm_reranker`) and applies when `search` is called with `rerank: true`. There is no graph store in the TS OSS SDK. + ### Methods All methods are async (return `Promise`): @@ -327,14 +398,17 @@ await m.add([ | Parameter | Type | Description | |-----------|------|-------------| | `messages` | `string \| Message[]` | Content to store | -| `config.userId` | string | User identifier (at least one scope required) | +| `config.userId` | string | User identifier (at least one of `userId`, `agentId`, `runId` is required) | | `config.agentId` | string | Agent identifier | | `config.runId` | string | Session identifier | | `config.metadata` | object | Custom key-value pairs | | `config.filters` | object | Additional filters | | `config.infer` | boolean | LLM inference (default: true) | +| `config.expirationDate` | string | `YYYY-MM-DD`, expired memories are hidden from `search` and `getAll` | -**Returns:** `Promise<{results: [...], relations?: [...]}>` +`config` is a required argument. `config.timestamp` is not supported in OSS (it throws). + +**Returns:** `Promise<{results: [...]}>`, each item `{ id, memory, metadata: { event: 'ADD' } }` (the event is under `metadata`, not top-level). #### search(query, config) @@ -347,13 +421,23 @@ const results = await m.search('dietary preferences', { filters: { user_id: 'ali | `query` | string | Search query | | `config.filters` | object | Filter object with entity IDs (`user_id`, `agent_id`, `run_id`, etc.) | | `config.topK` | number | Max results (default: 20) | +| `config.threshold` | number | Minimum similarity (default: 0.1) | +| `config.rerank` | boolean | Rerank with the configured `reranker` (no-op without one) | +| `config.showExpired` | boolean | Include expired memories (default: false) | + +Top-level entity IDs throw. `config.referenceDate` is not supported in OSS (it throws). #### get(memoryId) / getAll(config) / update(memoryId, data) / delete(memoryId) / deleteAll(config) / history(memoryId) -Same interface patterns. Note: OSS `update` takes a string for data, not an object. +Same interface patterns, with these differences: +- `getAll({ filters, topK?, showExpired? })` needs an entity ID in `filters` and has no `page`/`pageSize` (`topK` defaults to 20). +- `deleteAll({ userId?, agentId?, runId? })` takes top-level IDs and requires at least one. Use `reset()` to wipe everything. +- `update` takes a string or `{ text?, metadata?, expirationDate? }` and returns `{ message }`. +- `history` returns raw rows `{ id, memory_id, previous_value, new_value, action, created_at, updated_at, is_deleted }` (snake_case, newest first), not the hosted client's `oldMemory` / `newMemory` / `event`. ```typescript await m.update('mem-id', 'new content'); +await m.update('mem-id', { text: 'new content', metadata: { verified: true } }); ``` #### reset() @@ -371,7 +455,7 @@ await m.reset(); | Aspect | Platform (`MemoryClient`) | OSS (`Memory`) | |--------|--------------------------|----------------| | **Import** | `import MemoryClient from 'mem0ai'` | `import { Memory } from 'mem0ai/oss'` | -| **Auth** | API key required (`MEM0_API_KEY`) | No API key -- config-based | +| **Auth** | API key required (`apiKey` option) | No Mem0 API key -- config-based | | **Execution** | API calls to `api.mem0.ai` | Local execution | | **Infrastructure** | Fully managed | Self-managed vector DB, embedder, LLM | | **Param style** | Top-level: `camelCase` (`userId`, `topK`), filter keys: `snake_case` (`user_id`) | Top-level: `camelCase` (`userId`, `topK`), filter keys: `snake_case` (`user_id`) | @@ -380,14 +464,15 @@ await m.reset(); | **Export** | `createMemoryExport` | Not available | | **Feedback** | `feedback()` | Not available | | **Project mgmt** | `getProject`, `updateProject` | Not available | -| **User listing** | `users()`, `deleteUser()` | Not available | +| **User listing** | `users()`, `deleteUsers()` | Not available | +| **Profiles** | `getProfile`, `generateProfile`, profile settings | Not available | | **History** | Platform-managed | SQLite (configurable) | --- ## v2 Compatibility -If you're using SDK v2.x: +If you're migrating from TS SDK 2.x (the pre-V3 line): **Naming Changes:** - Top-level params now use camelCase: `topK`, `rerank` (not `top_k`) @@ -406,13 +491,17 @@ await client.search("query", { filters: { user_id: "alice" }, topK: 20 }); **Default Changes:** | Param | v2 | v3 | |-------|----|----| -| `topK` | 100 | 20 | -| `threshold` | none | 0.1 | -| `rerank` | true | false | +| `topK` (OSS) | 100 | 20 | +| `threshold` | 0.3 (Platform), none (OSS) | server-side cutoff (Platform), 0.1 (OSS) | +| `rerank` | false (Platform), true (OSS) | false | + +Platform `topK` defaults to 10 (max 1000). **Removed:** - `OutputFormat` and `API_VERSION` enums -- `organizationId`, `projectId` from constructor -- `enableGraph`, `asyncMode`, `outputFormat`, `immutable`, `expirationDate`, `filterMemories`, `batchSize`, `forceAddOnly`, `includes`, `excludes`, `keywordSearch` +- `organizationId`, `projectId`, `organizationName`, `projectName` from the constructor +- `add()`: `enableGraph`, `asyncMode`, `outputFormat`, `immutable`, `filterMemories`, `batchSize`, `forceAddOnly`, `includes`, `excludes`, `keywordSearch` +- `search()` and `getAll()`: `enableGraph` +- OSS config: `customPrompt` (now `customInstructions`), `enableGraph` and `graphStore` See the [v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for details. diff --git a/skills/mem0/client/python.md b/skills/mem0/client/python.md index 0cf35a550..53db5ce27 100644 --- a/skills/mem0/client/python.md +++ b/skills/mem0/client/python.md @@ -21,7 +21,7 @@ from mem0 import MemoryClient client = MemoryClient(api_key="m0-xxx") ``` -**Constructor:** `MemoryClient(api_key=None)`. If `api_key` is not provided, reads from `MEM0_API_KEY` environment variable. Raises `ValueError` if no key found. +**Constructor:** `MemoryClient(api_key=None, host=None, client=None)`. If `api_key` is not provided, reads from `MEM0_API_KEY` environment variable. Raises `ValueError` if no key found. `host` overrides the base URL and `client` accepts a custom `httpx.Client`. `MEM0_SOURCE`, `MEM0_APPLICATION` and `MEM0_CLIENT_STACK` set the request identity headers for wrappers. - HTTP library: `httpx` - Timeout: 300 seconds @@ -45,7 +45,7 @@ Same methods as `MemoryClient`, all `async`/`await`. Supports async context mana ### Memory Methods -#### add(messages, **kwargs) +#### add(messages, options=None, **kwargs) Store new memories from messages. @@ -68,11 +68,13 @@ client.add(messages, user_id="alice") | `infer` | bool | True | If False, store raw text without LLM inference | | `custom_categories` | list | None | Override project categories | | `custom_instructions` | str | None | Override extraction instructions | -| `timestamp` | int \| float \| str | None | Custom timestamp (Unix epoch or ISO 8601) | +| `agent_custom_instructions` | str | None | Extraction instructions for agent-scoped memories | +| `expiration_date` | str | None | `YYYY-MM-DD`, memory is hidden after this date | +| `timestamp` | int | None | Custom timestamp (Unix epoch seconds) | -**Returns:** `dict` -- list of events: `[{"id": "...", "event": "ADD", "data": {"memory": "..."}}]` +**Returns:** `dict` -- asynchronous by default: `{"event_id": "...", "status": "PENDING"}`. Poll `GET /v1/event/{event_id}/` until `SUCCEEDED`. With `infer=False` it is synchronous and returns the stored `results`. -#### search(query, **kwargs) +#### search(query, options=None, **kwargs) Search memories by semantic similarity. @@ -88,9 +90,13 @@ for mem in results.get("results", []): | `filters` | dict | None | Filter object with entity IDs and/or `AND`/`OR`/`NOT` conditions (e.g., `{"user_id": "alice"}`) | | `top_k` | int | 10 | Number of results | | `rerank` | bool | False | Enable deep semantic reranking (+150-200ms) | -| `threshold` | float | 0.1 | Minimum similarity score | -| `fields` | list | None | Specific fields to return | -| `categories` | list | None | Filter by category | +| `threshold` | float | server-side | Relevance cutoff (0.0 to 1.0), applied before score blending, so it is not a floor on the returned `score`. The default and `0.0` returned the same or nearly the same results in live tests | +| `fields` | - | - | Not applied in v3 | +| `categories` | - | - | Not applied in v3. Use `filters={"AND": [{"categories": {"in": [...]}}]}` | +| `metadata` | - | - | Not applied in v3. Use `filters={"AND": [{"metadata": {...}}]}` | +| `reference_date` | str \| int | None | Anchor for relative time queries (`YYYY-MM-DD`, ISO datetime, or Unix epoch) | +| `show_expired` | bool | False | Include memories past their `expiration_date` | +| `latest_only` | bool | None | Only return the latest version of a memory | **Returns:** `dict` -- `{"results": [{id, memory, user_id, categories, score, created_at, ...}]}` @@ -104,9 +110,9 @@ memory = client.get(memory_id="ea925981-...") **Returns:** `dict` -- full memory object -#### get_all(**kwargs) +#### get_all(options=None, **kwargs) -Retrieve all memories with optional filtering. Requires at least one entity identifier. +Retrieve all memories with optional filtering. Requires non-empty `filters`; scope them with at least one entity identifier. ```python memories = client.get_all(filters={"user_id": "alice"}) @@ -117,15 +123,17 @@ memories = client.get_all(filters={"AND": [{"user_id": "alice"}, {"categories": | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `filters` | dict | None | Filter object with entity IDs and/or `AND`/`OR`/`NOT` conditions | -| `top_k` | int | None | Limit results | -| `page` | int | None | Page number | -| `page_size` | int | None | Results per page | +| `page` | int | 1 | Page number | +| `page_size` | int | 100 | Results per page (max 200) | +| `start_date` / `end_date` / `categories` | - | - | Not applied in v3. Use `filters` with `created_at` or `categories` | +| `show_expired` | bool | False | Include expired memories | +| `latest_only` | bool | None | Only return the latest version of a memory | -**Returns:** `dict` -- `{"results": [...]}` +**Returns:** `dict` -- `{"count": int, "next": str | None, "previous": str | None, "results": [...]}` -#### update(memory_id, text=None, metadata=None, timestamp=None) +#### update(memory_id, options=None, **kwargs) -Update a memory's content, metadata, or timestamp. At least one parameter required. +Update a memory's `text`, `metadata`, `timestamp`, or `expiration_date` (pass `expiration_date=None` to clear it). At least one required. ```python client.update("ea925981-...", text="Updated: vegan since 2024") @@ -134,17 +142,18 @@ client.update("ea925981-...", metadata={"verified": True}) **Returns:** `dict` -- updated memory -#### delete(memory_id) +#### delete(memory_id, delete_linked=False) -Permanently delete a single memory. +Permanently delete a single memory. With `delete_linked=True`, also deletes the older memories it superseded. ```python client.delete("ea925981-...") +client.delete("ea925981-...", delete_linked=True) ``` -#### delete_all(**kwargs) +#### delete_all(options=None, **kwargs) -Delete all memories matching filters. Irreversible. +Delete all memories matching the entity IDs (`user_id`, `agent_id`, `app_id`, `run_id`, passed as top-level kwargs). Irreversible. ```python client.delete_all(user_id="alice") @@ -156,7 +165,7 @@ Get the change history of a memory. ```python history = client.history("ea925981-...") -# Returns: [{previous_value, new_value, action, timestamps}] +# Returns: [{id, memory_id, input, old_memory, new_memory, event, user_id, categories, metadata, created_at, updated_at}] ``` --- @@ -170,10 +179,12 @@ Update up to 1000 memories in a single request. ```python client.batch_update([ {"memory_id": "uuid-1", "text": "Updated text"}, - {"memory_id": "uuid-2", "text": "Another update", "metadata": {"verified": True}}, + {"memory_id": "uuid-2", "text": "Another update"}, ]) ``` +Each item must include `text`. `metadata` on a batch item is ignored and a metadata-only item returns a 400. Use `update(memory_id, metadata=...)` to change metadata. + #### batch_delete(memories) Delete up to 1000 memories in a single request. @@ -208,7 +219,7 @@ client.delete_users(user_id="alice") #### reset() -Delete ALL users, agents, sessions, and memories. Complete data reset. +Delete ALL users, agents, sessions, and memories. Complete data reset. It only deletes the entities on the first page returned by `users()`, so with many entities re-run it until it raises `No entities to delete`, or delete per entity with `delete_users(user_id=...)`. ```python client.reset() @@ -223,16 +234,14 @@ client.reset() Create a structured export of memories. ```python -import json - -schema = json.dumps({ +schema = { "type": "object", "properties": { "name": {"type": "string"}, "preferences": {"type": "array", "items": {"type": "string"}}, } -}) -export = client.create_memory_export(schema=schema, user_id="alice") +} +export = client.create_memory_export(schema=schema, filters={"AND": [{"user_id": "alice"}]}) ``` #### get_memory_export(**kwargs) @@ -269,6 +278,19 @@ client.feedback( --- +### User Profiles + +```python +profile = client.get_profile("alice") +client.generate_profile("alice") +client.get_profile_settings() +client.update_profile_settings(enabled=True) +``` + +`get_profile` returns `status` (`succeeded`, `pending`, `failed`, `not_enabled`, `insufficient_data`) plus `profile`; generation is asynchronous, so branch on `status`. Other methods: `sample_profiles(limit=None)` and `get_profile_job(job_id_or_status_url)`. + +--- + ### Webhooks ```python @@ -284,10 +306,10 @@ webhook = client.create_webhook( ) # Update -client.update_webhook(webhook_id=123, name="Updated", url="https://new-url.com") +client.update_webhook(webhook_id="wh_123", name="Updated", url="https://new-url.com") # Delete -client.delete_webhook(webhook_id=123) +client.delete_webhook(webhook_id="wh_123") ``` --- @@ -304,7 +326,9 @@ config = client.project.get(fields=["custom_categories", "custom_instructions"]) client.project.update( custom_instructions="Extract dietary preferences and health info", custom_categories=[{"health": "Medical and dietary info"}], + agent_custom_instructions="Extract only what the agent learned about the user", multilingual=True, + decay=True, ) # Create/delete project @@ -326,6 +350,8 @@ client.project.remove_member(email="user@example.com") ```bash pip install mem0ai +pip install "mem0ai[nlp]" # optional: spaCy entity linking (Python 3.10-3.12) +pip install "mem0ai[extras]" # optional: fastembed for Qdrant BM25 keyword search ``` ### Memory Class @@ -333,9 +359,11 @@ pip install mem0ai ```python from mem0 import Memory -m = Memory() # Uses default config (OpenAI embedder + in-memory vector store) +m = Memory() # Defaults: OpenAI gpt-5-mini + text-embedding-3-small, local Qdrant at /tmp/qdrant ``` +`Memory(config)` takes a `MemoryConfig` object. For a plain dict use `Memory.from_config(config)`. Requires `OPENAI_API_KEY` for the default LLM and embedder. + **Import:** `from mem0 import Memory` (NOT `MemoryClient` -- that is the Platform client) ### Configuration @@ -343,28 +371,28 @@ m = Memory() # Uses default config (OpenAI embedder + in-memory vector store) ```python config = { "llm": { - "provider": "openai", # openai, groq, azure, ollama, lmstudio, google, anthropic, mistral + "provider": "openai", # openai, anthropic, gemini, groq, ollama, lmstudio, azure_openai, aws_bedrock, together, deepseek, xai, vllm, litellm, ... "config": { "model": "gpt-5-mini", "api_key": "sk-xxx", } }, "embedder": { - "provider": "openai", # openai, ollama, azure, lmstudio, google, huggingface + "provider": "openai", # openai, ollama, azure_openai, lmstudio, gemini, vertexai, huggingface, fastembed, aws_bedrock, together "config": { "model": "text-embedding-3-small", "api_key": "sk-xxx", } }, "vector_store": { - "provider": "qdrant", # faiss, qdrant, pgvector, redis, supabase, azure_ai_search, memory + "provider": "qdrant", # qdrant (default), chroma, pgvector, pinecone, milvus, redis, supabase, faiss, azure_ai_search, ... "config": { "collection_name": "my_memories", "host": "localhost", "port": 6333, } }, - "history_db_path": "history.db", # SQLite path for change history + "history_db_path": "history.db", # SQLite path for change history (default ~/.mem0/history.db) "custom_instructions": "...", # Custom LLM prompt for extraction } @@ -374,7 +402,7 @@ m = Memory.from_config(config) ### Context Manager ```python -with Memory(config) as m: +with Memory.from_config(config) as m: m.add("I prefer dark mode", user_id="alice") results = m.search("preferences", filters={"user_id": "alice"}) # SQLite connections released automatically @@ -384,7 +412,7 @@ with Memory(config) as m: All methods mirror the Platform client but run locally: -#### add(messages, *, user_id, agent_id, run_id, metadata, infer=True) +#### add(messages, *, user_id, agent_id, run_id, metadata, expiration_date, infer=True, memory_type, prompt) ```python m.add("I'm a vegetarian", user_id="alice") @@ -396,9 +424,11 @@ m.add([ At least one of `user_id`, `agent_id`, `run_id` required. -**Returns:** `{"results": [...], "relations": [...]}` +`timestamp` raises `ValueError` in OSS (Platform only). -#### search(query, *, filters=None, top_k=20, threshold=0.1, rerank=False) +**Returns:** `{"results": [{"id": "...", "memory": "...", "event": "ADD"}]}` + +#### search(query, *, top_k=20, filters=None, threshold=0.1, rerank=False, explain=False, show_expired=False) ```python results = m.search("dietary preferences", filters={"user_id": "alice"}, top_k=5) @@ -406,11 +436,11 @@ results = m.search("dietary preferences", filters={"user_id": "alice"}, top_k=5) Entity IDs (`user_id`, `agent_id`, `run_id`) must be passed inside the `filters` dict. -Supports filter operators: `eq`, `ne`, `in`, `nin`, `gt`, `gte`, `lt`, `lte`, `contains`, `not_contains`. +Supports filter operators: `eq`, `ne`, `in`, `nin`, `gt`, `gte`, `lt`, `lte`, `contains`, `icontains`, plus `AND` / `OR` / `NOT`. `reference_date` raises `ValueError` in OSS (Platform only). -#### get(memory_id) / get_all(**kwargs) / update(memory_id, data, metadata=None) / delete(memory_id) / delete_all(**kwargs) / history(memory_id) +#### get(memory_id) / get_all(*, filters, top_k=20, show_expired=False) / update(memory_id, text=None, metadata=None, expiration_date) / delete(memory_id) / delete_all(user_id=None, agent_id=None, run_id=None) / history(memory_id) -Same interface as Platform client. +`get_all()` requires entity IDs inside `filters` and returns `{"results": [...]}`. `update()` takes `text` (`data` is a deprecated alias) and needs at least one of `text`, `metadata`, `expiration_date`. `delete_all()` needs at least one entity ID and takes them top-level. `m.project.update()` raises `ValueError` in OSS. #### reset() @@ -429,7 +459,7 @@ Release SQLite connections. Called automatically when using context manager. ```python from mem0 import AsyncMemory -m = AsyncMemory(config) +m = AsyncMemory.from_config(config) await m.add("text", user_id="alice") results = await m.search("query", filters={"user_id": "alice"}) ``` @@ -459,10 +489,10 @@ results = await m.search("query", filters={"user_id": "alice"}) ## v2 Compatibility -If you're using SDK v2.x or the v2 API: +The "v2" line is Python SDK 1.x (TypeScript SDK 2.x). If you are still on it, these are the differences from Python 2.x: **API Changes:** -- **Entity IDs in search/get_all:** Pass `user_id`, `agent_id` as top-level kwargs instead of inside `filters` +- **Entity IDs in search/get_all:** `user_id`, `agent_id` were top-level kwargs, now they go inside `filters` (top-level raises `ValueError`) ```python # v2 results = client.search("query", user_id="alice") @@ -470,18 +500,23 @@ If you're using SDK v2.x or the v2 API: results = client.search("query", filters={"user_id": "alice"}) ``` - **add() returns:** v2 returns ADD, UPDATE, DELETE events; v3 returns ADD only +- **Platform add() is async:** returns `{"event_id": "...", "status": "PENDING"}` **Default Changes:** -| Param | v2 | v3 | -|-------|----|----| -| `top_k` | 100 | 20 | -| `threshold` | None | 0.1 | -| `rerank` | True | False | +| Param | v2 Platform | v3 Platform | v2 OSS | v3 OSS | +|-------|-------------|-------------|--------|--------| +| `top_k` | 10 | 10 | 100 | 20 | +| `threshold` | 0.3 | server-side cutoff | None | 0.1 | +| `rerank` | False | False | True | False | **Removed Parameters:** - Constructor: `org_id`, `project_id` -- add(): `async_mode`, `output_format`, `enable_graph`, `immutable`, `expiration_date`, `filter_memories`, `batch_size`, `force_add_only`, `includes`, `excludes`, `keyword_search` +- add(): `async_mode`, `output_format`, `enable_graph`, `immutable`, `filter_memories`, `batch_size`, `force_add_only`, `includes`, `excludes`, `keyword_search` - search()/get_all(): `enable_graph` -- Config: `enable_graph`, `graph_store`, `custom_fact_extraction_prompt` (renamed to `custom_instructions`) +- Config: `enable_graph`, `graph_store`, `custom_fact_extraction_prompt` (renamed to `custom_instructions`), `custom_update_memory_prompt` (deprecated) + +`expiration_date` is still supported on `add()` and `update()`. + +**Graph memory:** the external graph store (Neo4j, Memgraph, Kuzu, AGE) was removed from OSS. Entity linking is built in (spaCy via `mem0ai[nlp]`, stored in a `{collection}_entities` vector collection) and falls back to semantic-only search without it. See the [v2 to v3 migration guide](https://docs.mem0.ai/migration/oss-v2-to-v3) for full details. diff --git a/skills/mem0/references/api-reference.md b/skills/mem0/references/api-reference.md index 62ec4bea7..01d39ee02 100644 --- a/skills/mem0/references/api-reference.md +++ b/skills/mem0/references/api-reference.md @@ -14,8 +14,16 @@ All endpoints require: `Authorization: Token ` | Get Single Memory | `GET` | `/v1/memories/{memory_id}/` | | Update Memory | `PUT` | `/v1/memories/{memory_id}/` | | Delete Memory | `DELETE` | `/v1/memories/{memory_id}/` | +| Memory History | `GET` | `/v1/memories/{memory_id}/history/` | +| Delete by Filter | `DELETE` | `/v1/memories/` (query params `user_id`, `agent_id`, `app_id`, `run_id`, `metadata`; `*` matches all) | +| Batch Update / Delete | `PUT` / `DELETE` | `/v1/batch/` (max 1000 memories per request) | +| Feedback | `POST` | `/v1/feedback/` | +| Create / Get Export | `POST` | `/v1/exports/`, `/v1/exports/get/` | +| List Entities | `GET` | `/v1/entities/` | +| Delete Entity | `DELETE` | `/v2/entities/{entity_type}/{entity_id}/` | +| Event Status | `GET` | `/v1/event/{event_id}/` | -Note: v1/v2 endpoints still work (backward compatible). +The `GET`/`POST` `/v1/memories/`, `POST` `/v2/memories/`, and `POST` `/v1/memories/search/` and `/v2/memories/search/` endpoints are marked deprecated in the OpenAPI spec. Use the `/v3/` endpoints above. ## Memory Object Structure @@ -26,14 +34,16 @@ Note: v1/v2 endpoints still work (backward compatible). | `user_id` | string | Associated user | | `agent_id` | string (nullable) | Agent identifier | | `app_id` | string (nullable) | Application identifier | -| `run_id` | string (nullable) | Run/session identifier | +| `run_id` | string (nullable) | Run/session identifier (see note below) | | `metadata` | object | Custom key-value pairs | | `categories` | array of strings | Auto-assigned category tags | -| `hash` | string | Content hash | +| `expiration_date` | string (nullable) | Date after which the memory is hidden unless `show_expired` is true | | `created_at` | datetime | Creation timestamp | | `updated_at` | datetime | Last modification timestamp | -Search results additionally include `score` (relevance metric). +Search results additionally include `score` (relevance metric) and `score_breakdown` (per-signal scores). Get and get-all results additionally include `structured_attributes` (temporal breakdown of the creation time), `replaced_by`, and `synthesized`, and get also returns `lifecycle_state`. Get and get-all omit `app_id` and `run_id` when they are not set. + +The run/session identifier is `run_id` in search results but `session_id` in get, get-all, and history results. ## Scoping Identifiers @@ -46,13 +56,16 @@ Memories can be scoped to different levels: | Application | `app_id` | Cross-agent app-level memory | | Run/Session | `run_id` | Session-scoped temporary memory | -**Critical:** Combining `user_id` and `agent_id` in a single AND filter yields empty results. Entities are stored separately. Use `OR` logic or separate queries. +**Critical:** Combining `user_id` and `agent_id` in a single AND filter yields empty results for memories created with `infer=true`. Each extracted fact is attributed to its speaker, so a record carries `user_id` (user messages) or `agent_id` (assistant messages), not both. Use `OR` logic or separate queries. Only Direct Import (`infer=false`) writes both fields on one record. `app_id` and `run_id` are stored on every record. + +Filters only constrain the entities you mention. `{"user_id": "alice"}` does not require `agent_id`, `app_id`, or `run_id` to be null. ## Processing Model - Memories are processed **asynchronously** (v3 default) -- Add responses return queued `ADD` events only (v3 is ADD-only, no UPDATE/DELETE) -- Poll status via `GET /v1/event/{event_id}/` +- Add responses return a `PENDING` event (v3 is ADD-only, no UPDATE/DELETE) +- Poll status via `GET /v1/event/{event_id}/` (`PENDING`, `RUNNING`, `FAILED`, `SUCCEEDED`) +- `infer=false` is synchronous: memories are stored verbatim and the response carries `message` and `results` ## Filter System @@ -68,7 +81,7 @@ Filters use nested JSON with a logical operator at the root: } ``` -Root must be `AND`, `OR`, or `NOT`. Simple shorthand `{"user_id": "alice"}` also works. +The root can also be a bare condition such as `{"user_id": "alice"}`. Sibling top-level keys in a flat object are implicitly ANDed. Use `AND`, `OR`, or `NOT` for OR/NOT semantics or nesting. An unrecognized top-level key returns a 400. ### Supported Operators @@ -88,20 +101,21 @@ Root must be `AND`, `OR`, or `NOT`. Simple shorthand `{"user_id": "alice"}` also | Field | Valid Operators | |-------|-----------------| | `user_id`, `agent_id`, `app_id`, `run_id` | `eq`, `ne`, `in`, `*` | -| `created_at`, `updated_at`, `timestamp` | `gt`, `gte`, `lt`, `lte`, `eq`, `ne` | -| `categories` | `eq`, `ne`, `in`, `contains` | -| `metadata` | `eq`, `ne`, `contains` (top-level keys only) | +| `created_at`, `updated_at`, `timestamp`, `expiration_date` | `gt`, `gte`, `lt`, `lte`, `ne` (explicit `eq` is rejected, pass a bare value; `in` fails with a 503 in search and a 500 in get-all) | +| `categories` | `in`, `contains` (`eq` and `ne` are rejected) | +| `metadata` | `eq`, `ne`, `contains` (top-level keys only). `contains` is case-sensitive and matches the whole stored value or one member of a list value, not a substring. `icontains` is rejected with a 400 | | `keywords` | `contains`, `icontains` | -| `memory_ids` | `in` | +| `memory_ids` | plain list of UUIDs (no `in`) | ### Filter Constraints -1. **Entity scope partitioning:** `user_id` AND `agent_id` in one `AND` block yields empty results. +1. **Entity scope partitioning:** `user_id` AND `agent_id` in one `AND` block yields empty results (except for Direct Import records). 2. **Metadata limitations:** Only top-level keys. Only `eq`, `contains`, `ne`. No `in` or `gt`. -3. **Operator syntax:** Use `gte`, `lt`, `ne`. SQL-style (`>=`, `!=`) rejected. -4. **Entity filter required for get-all:** At least one of `user_id`, `agent_id`, `app_id`, or `run_id`. +3. **Operator syntax:** Use `gte`, `lt`, `ne`. SQL-style (`>=`, `!=`) rejected. There is no `nin` on Platform: use `{"NOT": [{"categories": {"in": [...]}}]}`. +4. **Filters required for get-all:** Empty or missing `filters` return a 400. Scope the listing with at least one of `user_id`, `agent_id`, `app_id`, or `run_id` (search enforces this, get-all does not). 5. **Wildcard excludes null:** `*` matches only non-null values. 6. **Date format:** ISO 8601 (`YYYY-MM-DDTHH:MM:SSZ`). Timezone-naive defaults to UTC. +7. **Keyword filter:** `keywords` works in `get_all` filters but returns a 503 inside `search()` filters (MEM-5746). Pass the text as `query` for search. ## Response Formats @@ -109,13 +123,12 @@ Root must be `AND`, `OR`, or `NOT`. Simple shorthand `{"user_id": "alice"}` also ```json { - "message": "Memory processing has been queued for background execution", - "status": "PENDING", - "event_id": "evt-uuid" + "event_id": "evt-uuid", + "status": "PENDING" } ``` -v3 is ADD-only. No UPDATE or DELETE events. +v3 is ADD-only. No UPDATE or DELETE events. With `infer=false` the call is synchronous and the response also carries `message` and `results` (`[{"id": ..., "data": {"memory": ...}, "event": "ADD"}]`). ### Search Response @@ -134,7 +147,7 @@ v3 is ADD-only. No UPDATE or DELETE events. } ``` -In v3, `score` is a combined multi-signal relevance score. +In v3, `score` is a combined multi-signal relevance score in [0, 1]. Request defaults: `top_k` 10 (1 to 1000), `rerank` false. `threshold` is a server-side cutoff applied before score blending, not a floor on the returned `score`: the default and `0.0` returned the same or nearly the same results in live tests, including scores below 0.1. ### Get All Response (v3) @@ -147,4 +160,4 @@ In v3, `score` is a combined multi-signal relevance score. } ``` -v3 returns paginated envelope. Use `page` and `page_size` query params. +v3 returns paginated envelope. Use `page` (default 1) and `page_size` (default 100, max 200) query params. diff --git a/skills/mem0/references/architecture.md b/skills/mem0/references/architecture.md index 4a04c820b..f0ca4083d 100644 --- a/skills/mem0/references/architecture.md +++ b/skills/mem0/references/architecture.md @@ -23,9 +23,10 @@ Mem0 is a managed memory layer that sits between your AI application and users. User Input → Retrieve relevant memories → Enrich LLM prompt → Generate response → Store new memories ``` -Mem0 handles the complexity of extraction, deduplication, conflict resolution, and semantic retrieval so your application only needs to call `search()` and `add()`. +Mem0 handles the complexity of extraction, deduplication, and hybrid retrieval so your application only needs to call `search()` and `add()`. **Storage architecture:** +- **SQL database**: Facts and metadata (the source of truth for each memory) - **Vector store**: Embeddings for semantic similarity search - **Entity store**: Automatic entity linking for relationship-aware retrieval @@ -64,20 +65,22 @@ Messages In v3 processes memories asynchronously by default: - API returns immediately: `{"status": "PENDING", "event_id": "evt-..."}` -- Poll status via `GET /v1/event/{event_id}/` +- Poll status via `GET /v1/event/{event_id}/` (the TS client camelCases response keys, so it sees `eventId`) - Use webhooks for completion notifications +- `infer=False` is the exception: it runs synchronously and returns `message` and `results` ### Extraction modes **Inferred (`infer=True`, default):** -- LLM extracts structured facts from conversation -- Conflict resolution deduplicates and resolves contradictions +- LLM extracts structured facts from conversation, including facts stated by the assistant +- Redundant facts are removed, but nothing is overwritten: when a fact changes, both versions are kept with temporal context - Best for: natural conversation → memory **Raw (`infer=False`):** - Stores text exactly as provided, no LLM processing -- Skips conflict resolution — same fact can be stored twice -- Only `user` role messages are stored; `assistant` messages ignored +- Skips semantic duplicate detection (same fact in different words can be stored twice); exact repeats are deduplicated by hash +- `user` and `assistant` messages are stored, one memory per message; `system` messages are dropped +- Structured multimodal content (`image_url`, `pdf_url`, `txt_url`, `mdx_url`) is rejected with a 400, not skipped - Best for: bulk imports, pre-structured data, migrations **Warning:** Don't mix `infer=True` and `infer=False` for the same data — the same fact will be stored twice. @@ -101,6 +104,7 @@ Query In │ 2. PARALLEL SCORING │ Semantic search (vector similarity) │ │ BM25 keyword search (term matching) │ │ Entity matching (entity graph boost) +│ │ Temporal scoring (time metadata vs query intent) └─────────┬───────────┘ │ ▼ @@ -117,18 +121,17 @@ Query In | Parameter | Default | Notes | |-----------|---------|-------| -| `top_k` | 20 | Was 100 in v2 | -| `threshold` | 0.1 | Was None in v2 | -| `rerank` | False | Was True in v2 | +| `top_k` | 10 | Range 1-1000 (OSS default is 20) | +| `threshold` | server-side cutoff | Not a floor on the returned `score`. On Platform v3 the default and `0.0` return the same or nearly the same results. Was 0.3 on Platform v2 (None on OSS v2) | +| `rerank` | False | Was False on Platform v2 (True on OSS v2) | -### Implicit null scoping +### Unmentioned entities are not constrained -When you search with `filters={"user_id": "alice"}` only, Mem0 returns memories where `agent_id`, `app_id`, and `run_id` are all null. This prevents cross-scope leakage by default. +When you search with `filters={"user_id": "alice"}` only, Mem0 matches on `user_id` alone. It does not require `agent_id`, `app_id`, or `run_id` to be null, so records that also carry those fields are returned. -To include memories with non-null fields, use explicit filters: +To narrow to a scope, name the entity explicitly: ```python -# Gets memories for alice regardless of agent/app/run -filters={"OR": [{"user_id": "alice"}]} +filters={"AND": [{"user_id": "alice"}, {"run_id": "session_123"}]} ``` --- @@ -149,7 +152,7 @@ v3 uses ADD-only extraction. Memories accumulate over time rather than being con ### Deletion - Single: `client.delete(memory_id)` - Batch: `client.batch_delete([...])` -- Bulk: `client.delete_all(filters={"user_id": "alice"})` +- Bulk: `client.delete_all(user_id="alice")` --- @@ -185,13 +188,15 @@ v3 uses ADD-only extraction. Memories accumulate over time rather than being con | `user_id` | string | Primary entity scope | | `agent_id` | string | Agent scope | | `app_id` | string | Application scope | -| `run_id` | string | Session/run scope | +| `run_id` | string | Session/run scope (named `session_id` in get, get-all, and history responses) | | `metadata` | object | Custom key-value pairs for filtering | | `categories` | array | Auto-assigned or custom category tags | +| `expiration_date` | string | Date after which the memory is hidden unless `show_expired` is true | | `created_at` | datetime | Creation timestamp | | `updated_at` | datetime | Last modification timestamp | | `structured_attributes` | object | Temporal breakdown for time-based queries | -| `score` | float | Semantic similarity (search results only, 0-1) | +| `lifecycle_state` | string | Lifecycle state of the memory (returned by get) | +| `score` | float | Combined multi-signal relevance (search results only, 0-1) | --- @@ -208,12 +213,12 @@ Mem0 separates memories across four dimensions to prevent data mixing: ### Storage model -Each entity combination creates separate records. A memory with `user_id="alice"` is stored separately from one with `user_id="alice"` + `agent_id="bot"`. +`app_id` and `run_id` are stored on every record the call produces. `user_id` and `agent_id` behave differently on the default extraction path: each extracted fact is attributed to whoever stated it, so a record carries `user_id` (from `user` messages) or `agent_id` (from `assistant` messages), not both. Only Direct Import (`infer=False`) writes both on one record. ### Critical: cross-entity queries ```python -# This returns NOTHING — user and agent memories are stored separately +# This returns NOTHING for inferred memories: a record has user_id OR agent_id, not both filters={"AND": [{"user_id": "alice"}, {"agent_id": "bot"}]} # Use OR to query multiple scopes @@ -327,4 +332,4 @@ def chat(user_input: str, user_id: str, session_id: str) -> str: | **RAG over documents** | Good for static knowledge | No personalization, no memory updates | | **Mem0 Platform** | Managed extraction + dedup + graph + scoping | External dependency, async processing delay | -Mem0 combines the best of vector search (semantic retrieval) with automatic extraction (LLM-powered), conflict resolution (deduplication), and structured scoping (multi-tenancy) — in a single managed API. +Mem0 combines the best of vector search (semantic retrieval) with automatic extraction (LLM-powered), deduplication, and structured scoping (multi-tenancy), in a single managed API. diff --git a/skills/mem0/references/features.md b/skills/mem0/references/features.md index f930d9a74..a8ff547fb 100644 --- a/skills/mem0/references/features.md +++ b/skills/mem0/references/features.md @@ -23,6 +23,7 @@ v3 uses multi-signal hybrid search combining: - **Semantic search** (vector similarity) - **BM25 keyword search** (normalized term matching) - **Entity matching** (entity graph boost) +- **Temporal reasoning** (Platform only): memories whose event dates match time expressions in the query ("last week", "as of March 2025") get a boost This is automatic — no configuration needed. @@ -56,10 +57,10 @@ v3 replaces graph memory with built-in entity linking. Entities (proper nouns, q ### How It Works 1. **Extraction**: During `add()`, entities are automatically extracted from memory text -2. **Storage**: Entities are stored in a parallel collection (`{collection}_entities`) +2. **Storage**: Entities are stored in a parallel collection (OSS: `{collection}_entities`; on Platform the entity store is managed for you) 3. **Retrieval**: During `search()`, query entities are matched and used to boost relevant memories -Entity linking is automatic — no configuration required. The boost is folded into the combined `score` on each result. +Entity linking is automatic, no configuration required. The boost is folded into the combined `score` on each result. On Platform this is Graph Memory: built in on all plans, no external graph store to provision, and the dashboard Graph view is Pro and Enterprise only. ### v2 Migration Note @@ -141,6 +142,32 @@ client.project.update(custom_instructions="Your guidelines here...") await client.updateProject({ customInstructions: "Your guidelines here..." }); ``` +### Agent Custom Instructions + +`agent_custom_instructions` (Python SDK 2.0.17+, TypeScript SDK 3.1.5+) is a second set of extraction rules that applies only to agent-scoped memories. It is unset by default, and while unset `custom_instructions` applies to every memory. + +```python +client.project.update( + custom_instructions="Extract the user's preferences, goals, and constraints.", + agent_custom_instructions="Extract tools that failed, and retry strategies that worked.", +) +``` + +```javascript +await client.updateProject({ + customInstructions: "Extract the user's preferences, goals, and constraints.", + agentCustomInstructions: "Extract tools that failed, and retry strategies that worked.", +}); +``` + +| The `add` call passes | Instructions applied | +|-----------------------|----------------------| +| `user_id` only | `custom_instructions` | +| `agent_id` only | `agent_custom_instructions` | +| `user_id` and `agent_id` | `agent_custom_instructions` for memories attributed to the assistant, `custom_instructions` for the rest | + +Both fields can also be passed per `add` call to override the project setting for that call. Clear the project value with an empty string. + ### Template Structure 1. **Task Description** -- brief extraction overview @@ -194,8 +221,11 @@ for item in feedback_data: **TypeScript:** ```typescript -await client.feedback('mem-123', { - feedback: 'POSITIVE', +import { Feedback } from 'mem0ai'; + +await client.feedback({ + memoryId: 'mem-123', + feedback: Feedback.POSITIVE, feedbackReason: 'Accurately captured dietary preference', }); ``` @@ -209,8 +239,6 @@ Create structured exports of memories using customizable schemas with filters. ### Usage ```python -import json - # Define export schema schema = { "type": "object", @@ -223,8 +251,8 @@ schema = { # Create export response = client.create_memory_export( - schema=json.dumps(schema), - filters={"user_id": "alice"}, + schema=schema, + filters={"AND": [{"user_id": "alice"}]}, export_instructions="Create comprehensive profile based on all memories" ) @@ -238,33 +266,39 @@ result = client.get_memory_export(memory_export_id=response["id"]) ## Group Chat -Process multi-participant conversations and automatically attribute memories to individual speakers. +Process multi-participant conversations and keep a separate memory profile per speaker. Scope comes only from the `user_id`, `agent_id`, and `run_id` you pass to `add()`: Mem0 does not infer it from the conversation. ### Usage -```python -messages = [ - {"role": "user", "name": "Alice", "content": "I think we should use React for the frontend"}, - {"role": "user", "name": "Bob", "content": "I prefer Vue.js, it's simpler for our use case"}, - {"role": "assistant", "content": "Both are great choices. Let me note your preferences."}, -] +Call `add()` once per participant with their own `user_id`, and share a `run_id` for the session: -# Mem0 automatically attributes memories to each speaker -response = client.add(messages, run_id="team_meeting_1") +```python +client.add( + [{"role": "user", "content": "I think we should use React for the frontend"}], + user_id="alice", run_id="team_meeting_1", +) +client.add( + [{"role": "user", "content": "I prefer Vue.js, it's simpler for our use case"}], + user_id="bob", run_id="team_meeting_1", +) # Retrieve Alice's memories from that session alice_mems = client.get_all( filters={"AND": [{"user_id": "alice"}, {"run_id": "team_meeting_1"}]} ) + +session_mems = client.get_all( + filters={"AND": [{"user_id": "*"}, {"run_id": "team_meeting_1"}]} +) ``` -Use the `name` field in messages to identify speakers. Mem0 maps names to entity scopes automatically. +A `name` field on a message is stored as extraction context only. Passing messages from two different `name`s in one `add()` call does not split the memories: they all land under the `user_id` you passed. --- ## MCP Integration -Model Context Protocol integration enables AI clients (Claude, Claude Code, Cursor, Windsurf, VS Code, OpenCode) to manage Mem0 memory autonomously. +Model Context Protocol integration enables AI clients (Claude, Claude Code, Codex, Cursor, Windsurf, VS Code, OpenCode) to manage Mem0 memory autonomously. ### Setup @@ -275,15 +309,17 @@ npx mcp-add \ --name mem0-mcp \ --type http \ --url "https://mcp.mem0.ai/mcp" \ - --clients "claude,claude code,cursor,windsurf,vscode,opencode" + --clients "claude code,cursor,windsurf,vscode,opencode" ``` +Claude Desktop rejects `mcp-add`: add it under Settings > Connectors instead. Codex reads `~/.codex/config.toml` (TOML, server name `mem0`). The first tool call opens a browser sign-in, or send your API key as a bearer token for headless environments. + ### Available MCP Tools -The MCP server exposes 9 memory tools that AI agents can use autonomously: -- Add, search, get, update, delete memories -- Get history, list users, delete users -- Search Mem0 documentation +The MCP server exposes 11 memory tools that AI agents can use autonomously: +- `add_memory`, `search_memories`, `get_memories`, `get_memory`, `update_memory` +- `delete_memory`, `delete_all_memories`, `delete_entities` +- `list_entities`, `list_events`, `get_event_status` ### How It Works @@ -307,6 +343,12 @@ Real-time event notifications for memory operations. | `memory_update` | Memory modified | | `memory_delete` | Memory removed | | `memory_categorize` | Memory tagged | +| `ingest_job_completed` | Ingest job finished successfully | +| `ingest_job_partially_completed` | Ingest job finished with some items failed | +| `ingest_job_failed` | Ingest job failed entirely | +| `ingest_job_cancelled` | Ingest job cancelled | + +The TypeScript `WebhookEvent` enum covers only the four `memory_*` events (`MEMORY_ADDED`, `MEMORY_UPDATED`, `MEMORY_DELETED`, `MEMORY_CATEGORIZED`). ### Create Webhook @@ -321,6 +363,18 @@ webhook = client.create_webhook( ) ``` +```typescript +import { WebhookEvent } from 'mem0ai'; + +const webhook = await client.createWebhook({ + url: 'https://your-app.com/webhook', + name: 'Memory Logger', + eventTypes: [WebhookEvent.MEMORY_ADDED, WebhookEvent.MEMORY_CATEGORIZED], +}); +``` + +TypeScript `createWebhook` takes no `projectId`: it uses the project resolved by the client. `getWebhooks({ projectId })` accepts one optionally. + ### Manage Webhooks ```python @@ -341,6 +395,7 @@ client.delete_webhook(webhook_id="wh_123") ### Payload Structure +The POST body wraps everything in `event_details`. Memory events contain: ID, data object with memory content, event type (`ADD`/`UPDATE`/`DELETE`). Categorization events contain: memory ID, event type (`CATEGORIZE`), assigned category labels. @@ -348,59 +403,4 @@ Categorization events contain: memory ID, event type (`CATEGORIZE`), assigned ca ## Multimodal Support -Mem0 can process images and documents alongside text. - -### Supported Media Types - -- Images: JPG, PNG -- Documents: MDX, TXT, PDF - -### Image via URL - -```python -image_message = { - "role": "user", - "content": { - "type": "image_url", - "image_url": {"url": "https://example.com/image.jpg"} - } -} -client.add([image_message], user_id="alice") -``` - -### Image via Base64 - -```python -import base64 -with open("photo.jpg", "rb") as f: - base64_image = base64.b64encode(f.read()).decode("utf-8") - -image_message = { - "role": "user", - "content": { - "type": "image_url", - "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"} - } -} -client.add([image_message], user_id="alice") -``` - -### Document (MDX/TXT) - -```python -doc_message = { - "role": "user", - "content": {"type": "mdx_url", "mdx_url": {"url": document_url}} -} -client.add([doc_message], user_id="alice") -``` - -### PDF Document - -```python -pdf_message = { - "role": "user", - "content": {"type": "pdf_url", "pdf_url": {"url": pdf_url}} -} -client.add([pdf_message], user_id="alice") -``` +`POST /v3/memories/add/` (what `client.add()` calls) accepts only string `content`. Structured multimodal content (`image_url`, `pdf_url`, `txt_url`, `mdx_url`) is rejected with a 400 `Not a valid string.`, with `infer=True` and with `infer=False`. To remember what an image or document says, extract the text yourself and pass it as a plain string. diff --git a/skills/mem0/references/integration-patterns.md b/skills/mem0/references/integration-patterns.md index 68232719e..a6d7e64cd 100644 --- a/skills/mem0/references/integration-patterns.md +++ b/skills/mem0/references/integration-patterns.md @@ -38,7 +38,7 @@ prompt = ChatPromptTemplate.from_messages([ def retrieve_context(query: str, user_id: str): """Retrieve relevant memories from Mem0""" - memories = mem0.search(query, user_id=user_id) + memories = mem0.search(query, filters={"user_id": user_id}) memory_list = memories['results'] serialized = ' '.join([m["memory"] for m in memory_list]) return [ @@ -66,7 +66,9 @@ def chat_turn(user_input: str, user_id: str) -> str: Source: [docs.mem0.ai/integrations/crewai](https://docs.mem0.ai/integrations/crewai) -CrewAI has native Mem0 integration via `memory_config`: +Install: `pip install crewai crewai-tools mem0ai` + +Newer CrewAI versions removed the `memory_config={"provider": "mem0"}` shortcut on `Crew(...)`. Wire Mem0 in explicitly through `MemoryClient` (retrieve, inject into the task, store). CrewAI's own `ExternalMemory` API is the native alternative; see the [CrewAI memory docs](https://docs.crewai.com/en/concepts/memory) for the shape your version expects. ```python from crewai import Agent, Task, Crew, Process @@ -74,7 +76,6 @@ from mem0 import MemoryClient client = MemoryClient() -# Store user preferences first messages = [ {"role": "user", "content": "I am more of a beach person than a mountain person."}, {"role": "assistant", "content": "Noted! I'll recommend beach destinations."}, @@ -82,41 +83,41 @@ messages = [ ] client.add(messages, user_id="crew_user_1") -# Create agent -travel_agent = Agent( - role="Personalized Travel Planner", - goal="Plan personalized travel itineraries", - backstory="You are a seasoned travel planner.", - memory=True, -) +def get_user_context(user_id: str, query: str) -> str: + results = client.search(query, filters={"user_id": user_id}).get("results", []) + return "\n".join(f"- {m['memory']}" for m in results) -# Create task -task = Task( - description="Find places to live, eat, and visit in San Francisco.", - expected_output="A detailed list of places to live, eat, and visit.", - agent=travel_agent, -) +def plan_trip(destination: str, user_id: str): + travel_agent = Agent( + role="Personalized Travel Planner", + goal="Plan personalized travel itineraries", + backstory="You are a seasoned travel planner.", + ) + user_context = get_user_context(user_id, f"travel preferences for {destination}") + task = Task( + description=f"""Find places to live, eat, and visit in {destination}. -# Setup crew with Mem0 memory -crew = Crew( - agents=[travel_agent], - tasks=[task], - process=Process.sequential, - memory=True, - memory_config={ - "provider": "mem0", - "config": {"user_id": "crew_user_1"}, - } -) + Known preferences for this user: + {user_context or "No stored preferences yet."} + """, + expected_output=f"A detailed list of places to live, eat, and visit in {destination}.", + agent=travel_agent, + ) + crew = Crew(agents=[travel_agent], tasks=[task], process=Process.sequential) + result = crew.kickoff() + client.add([{"role": "user", "content": f"Planned a trip to {destination}."}], user_id=user_id) + return result -result = crew.kickoff() +result = plan_trip("San Francisco", "crew_user_1") ``` +`add()` is asynchronous on the Platform, so the seed memories above are not searchable the instant it returns and a `plan_trip` call straight after it can see no preferences. Run the seeding in an earlier session, or wait until the `add` event is `SUCCEEDED` (poll `GET /v1/event/{event_id}/`) before the first `plan_trip`. The `add` at the end of `plan_trip` only writes, so it needs no wait. + --- ## Vercel AI SDK -> **Dedicated skill available.** For comprehensive Vercel AI SDK documentation, see the [mem0-vercel-ai-sdk skill](../mem0-vercel-ai-sdk/SKILL.md) ([GitHub](https://github.com/mem0ai/mem0/tree/main/skills/mem0-vercel-ai-sdk)). +> **Dedicated skill available.** For comprehensive Vercel AI SDK documentation, see the [mem0-vercel-ai-sdk skill](../../mem0-vercel-ai-sdk/SKILL.md) ([GitHub](https://github.com/mem0ai/mem0/tree/main/skills/mem0-vercel-ai-sdk)). Install: `npm install @mem0/vercel-ai-provider` @@ -150,7 +151,7 @@ mem0 = MemoryClient() @function_tool def search_memory(query: str, user_id: str) -> str: """Search through past conversations and memories""" - memories = mem0.search(query, user_id=user_id, top_k=3) + memories = mem0.search(query, filters={"user_id": user_id}, top_k=3) if memories and memories.get('results'): return "\n".join([f"- {mem['memory']}" for mem in memories['results']]) return "No relevant memories found." @@ -209,7 +210,11 @@ result = Runner.run_sync(triage_agent, "Plan a healthy meal for my Italy trip") Source: [docs.mem0.ai/integrations/pipecat](https://docs.mem0.ai/integrations/pipecat) +Install: `pip install "pipecat-ai[mem0]"` + ```python +import os + from pipecat.services.mem0 import Mem0MemoryService memory = Mem0MemoryService( @@ -236,8 +241,6 @@ pipeline = Pipeline([ ]) ``` - - --- ## LangGraph @@ -266,7 +269,7 @@ def chatbot(state: State): user_id = state["mem0_user_id"] # Retrieve relevant memories - memories = mem0.search(messages[-1].content, user_id=user_id) + memories = mem0.search(messages[-1].content, filters={"user_id": user_id}) context = "Relevant context:\n" for memory in memories["results"]: context += f"- {memory['memory']}\n" @@ -344,6 +347,8 @@ Install: `pip install autogen mem0ai` Multi-agent conversational systems with memory persistence. ```python +import os + from autogen import ConversableAgent from mem0 import MemoryClient @@ -359,7 +364,7 @@ agent = ConversableAgent( def get_context_aware_response(question: str) -> str: # Retrieve memories for context - relevant_memories = memory_client.search(question, user_id=USER_ID) + relevant_memories = memory_client.search(question, filters={"user_id": USER_ID}) context = "\n".join([m["memory"] for m in relevant_memories.get("results", [])]) prompt = f"""Answer considering previous interactions: @@ -384,12 +389,15 @@ Beyond the examples above, Mem0 integrates with: | Framework | Type | Install | |-----------|------|---------| -| [Mastra](https://docs.mem0.ai/integrations/mastra) | TS agent framework | `npm install @mastra/mem0` | +| [Mastra](https://docs.mem0.ai/integrations/mastra) | TS agent framework | `npm install @mastra/core @mastra/mem0 @ai-sdk/openai zod` | | [ElevenLabs](https://docs.mem0.ai/integrations/elevenlabs) | Voice AI | `pip install elevenlabs mem0ai` | | [LiveKit](https://docs.mem0.ai/integrations/livekit) | Real-time voice/video | `pip install livekit-agents mem0ai` | -| [Camel AI](https://docs.mem0.ai/integrations/camel-ai) | Multi-agent framework | `pip install camel-ai[all] mem0ai` | -| [AWS Bedrock](https://docs.mem0.ai/integrations/aws-bedrock) | Cloud LLM provider | `pip install boto3 mem0ai` | +| [Camel AI](https://docs.mem0.ai/integrations/camel-ai) | Multi-agent framework | `pip install "camel-ai>=0.2.0" mem0ai` | +| [AWS Bedrock](https://docs.mem0.ai/integrations/aws-bedrock) | Cloud LLM provider | `pip install mem0ai boto3 opensearch-py` | | [Dify](https://docs.mem0.ai/integrations/dify) | Low-code AI platform | Plugin-based | | [Google AI ADK](https://docs.mem0.ai/integrations/google-ai-adk) | Google agent framework | `pip install google-adk mem0ai` | +| [Agno](https://docs.mem0.ai/integrations/agno) | Multimodal agent framework | `pip install agno mem0ai` | +| [Strands Agents](https://docs.mem0.ai/integrations/strands) | AWS agent SDK (native `MemoryStore`) | `pip install mem0-strands` | +| [LangChain Tools](https://docs.mem0.ai/integrations/langchain-tools) | Mem0 tools for any LangChain agent | `pip install langchain_core mem0ai` | For the general Python pattern (no framework), see the "Common integration pattern" in [SKILL.md](../SKILL.md). diff --git a/skills/mem0/references/quickstart.md b/skills/mem0/references/quickstart.md index c4afd7841..1e779a599 100644 --- a/skills/mem0/references/quickstart.md +++ b/skills/mem0/references/quickstart.md @@ -27,7 +27,7 @@ messages = [ client.add(messages, user_id="user123") # Search memories -results = client.search("What are my dietary restrictions?", user_id="user123") +results = client.search("What are my dietary restrictions?", filters={"user_id": "user123"}) print(results) ``` @@ -39,7 +39,7 @@ from mem0 import AsyncMemoryClient client = AsyncMemoryClient(api_key="your-api-key") await client.add(messages, user_id="user123") -results = await client.search("query", user_id="user123") +results = await client.search("query", filters={"user_id": "user123"}) ``` ## TypeScript / JavaScript Setup @@ -74,7 +74,7 @@ console.log(results); export MEM0_API_KEY="m0-your-api-key" # Add memory -curl -X POST https://api.mem0.ai/v1/memories/ \ +curl -X POST https://api.mem0.ai/v3/memories/add/ \ -H "Authorization: Token $MEM0_API_KEY" \ -H "Content-Type: application/json" \ -d '{ @@ -86,7 +86,7 @@ curl -X POST https://api.mem0.ai/v1/memories/ \ }' # Search memories -curl -X POST https://api.mem0.ai/v2/memories/search/ \ +curl -X POST https://api.mem0.ai/v3/memories/search/ \ -H "Authorization: Token $MEM0_API_KEY" \ -H "Content-Type: application/json" \ -d '{ @@ -97,6 +97,8 @@ curl -X POST https://api.mem0.ai/v2/memories/search/ \ ## Sample Response +`add()` is asynchronous and returns `{"event_id": "...", "status": "PENDING"}` (`eventId` on the TS client); poll `GET /v1/event/{event_id}/` until it is `SUCCEEDED`. A search returns: + ```json { "results": [ @@ -112,6 +114,8 @@ curl -X POST https://api.mem0.ai/v2/memories/search/ \ } ``` +The TS client returns the same fields camelCased (`userId`, `createdAt`). + ## Next Steps - [SDK Guide](sdk-guide.md) -- all methods for Python and TypeScript diff --git a/skills/mem0/references/sdk-guide.md b/skills/mem0/references/sdk-guide.md index 512c0d19c..33503d32a 100644 --- a/skills/mem0/references/sdk-guide.md +++ b/skills/mem0/references/sdk-guide.md @@ -24,7 +24,7 @@ import MemoryClient from 'mem0ai'; const client = new MemoryClient({ apiKey: 'm0-your-api-key' }); ``` -Constructor accepts `apiKey` (required) and `host` (optional, default: `https://api.mem0.ai`). +Constructor accepts `apiKey` (required in TypeScript; Python falls back to the `MEM0_API_KEY` env var) and `host` (optional, default: `https://api.mem0.ai`). --- @@ -58,6 +58,7 @@ await client.add(messages, { userId: "alice", metadata: { source: "onboarding" } | `run_id` | string | Session identifier | | `metadata` | object | Custom key-value pairs | | `infer` | boolean | If `false`, store raw text without inference (default: `true`) | +| `expiration_date` | string | `YYYY-MM-DD`, memory is hidden from search and get_all after this date | ### Advanced Add Options @@ -109,7 +110,10 @@ const results = await client.search("work experience", { | `filters` | object | Filter object (AND/OR operators). Use `{"user_id": "..."}` to filter by user | | `top_k` | number | Number of results (default: 10 for Platform) | | `rerank` | boolean | Enable reranking for better relevance (default: `false`) | -| `threshold` | number | Minimum similarity score (default: 0.1) | +| `threshold` | number | Server-side relevance cutoff (0 to 1), applied before score blending, so it is not a floor on the returned `score`. The default and `0.0` returned the same or nearly the same results in live tests | +| `reference_date` | string / number | Anchor for relative time queries such as "last week" (epoch, `YYYY-MM-DD`, or ISO datetime) | +| `show_expired` | boolean | Include memories past their `expiration_date` (default: `false`) | +| `latest_only` | boolean | Only return the latest version of a memory | ### Common Filter Patterns @@ -138,12 +142,11 @@ filters={"AND": [ ]} # Exclude categories with NOT -filters={"AND": [{"user_id": "user_123"}, {"NOT": {"categories": {"in": ["spam", "test"]}}}]} +filters={"AND": [{"user_id": "user_123"}, {"NOT": [{"categories": {"in": ["spam", "test"]}}]}]} # Multi-dimensional query filters={"AND": [ {"user_id": "user_123"}, - {"keywords": {"icontains": "invoice"}}, {"categories": {"in": ["finance"]}}, {"created_at": {"gte": "2024-01-01T00:00:00Z"}} ]} @@ -191,7 +194,7 @@ const memory = await client.get("ea925981-..."); const memories = await client.getAll({ filters: { user_id: "alice" } }); ``` -**Note:** `get_all` requires at least one of `user_id`, `agent_id`, `app_id`, or `run_id` in filters. +**Note:** `get_all` requires non-empty `filters`. Scope them with at least one of `user_id`, `agent_id`, `app_id`, or `run_id`. --- @@ -215,12 +218,14 @@ await client.update("ea925981-...", { text: "Updated: vegan since 2024" }); **Python:** ```python client.delete(memory_id="ea925981-...") +client.delete(memory_id="ea925981-...", delete_linked=True) client.delete_all(user_id="alice") # Irreversible bulk delete ``` **TypeScript:** ```typescript await client.delete("ea925981-..."); +await client.delete("ea925981-...", { deleteLinked: true }); await client.deleteAll({ userId: "alice" }); ``` @@ -231,7 +236,7 @@ await client.deleteAll({ userId: "alice" }); **Python:** ```python history = client.history(memory_id="ea925981-...") -# Returns: [{previous_value, new_value, action, timestamps}] +# Returns: [{id, memory_id, input, old_memory, new_memory, event, user_id, categories, metadata, created_at, updated_at}] ``` **TypeScript:** @@ -241,8 +246,19 @@ const history = await client.history("ea925981-..."); --- -## Batch Operations (TypeScript) +## Batch Operations +**Python:** +```python +client.batch_update([ + {"memory_id": "uuid-1", "text": "Updated text"}, + {"memory_id": "uuid-2", "text": "Another updated text"}, +]) + +client.batch_delete([{"memory_id": "uuid-1"}, {"memory_id": "uuid-2"}]) +``` + +**TypeScript:** ```typescript // Batch update await client.batchUpdate([ @@ -254,6 +270,8 @@ await client.batchUpdate([ await client.batchDelete(["uuid-1", "uuid-2", "uuid-3"]); ``` +Each batch update item must include `text`. `metadata` on an item is ignored and a metadata-only item returns a 400. + --- ## Additional Methods @@ -269,8 +287,14 @@ client.delete_users(user_id="alice") client.feedback(memory_id="...", feedback="POSITIVE", feedback_reason="Accurate extraction") # Export memories -export = client.create_memory_export(filters={"AND": [{"user_id": "alice"}]}) +export = client.create_memory_export( + schema={"type": "object", "properties": {"diet": {"type": "string"}}}, + filters={"AND": [{"user_id": "alice"}]}, +) data = client.get_memory_export(memory_export_id=export["id"]) + +profile = client.get_profile("alice") +client.generate_profile("alice") ``` --- @@ -281,8 +305,8 @@ data = client.get_memory_export(memory_export_id=export["id"]) 2. **SQL operators rejected** -- use `gte`, `lt`, etc. Not `>=`, `<`. 3. **Metadata filtering is limited** -- only top-level keys with `eq`, `contains`, `ne`. 4. **Wildcard `*` excludes null** -- only matches non-null values. -5. **Default threshold is 0.1** -- increase for stricter matching. -6. **Async processing** -- memories process asynchronously. Wait 2-3s after `add()` before searching. +5. **Threshold is a server-side cutoff** -- raise it to drop weak matches, but it is applied before score blending, so it is not a floor on the returned `score`. Filter on `score` client-side for a precise cutoff. +6. **Async processing** -- `add()` returns `{"event_id": ..., "status": "PENDING"}` (`eventId` on the TS client). Memories are searchable after the event is `SUCCEEDED` (poll `GET /v1/event/{event_id}/`, or wait a few seconds). `infer=False` is synchronous. ## Naming Conventions @@ -334,8 +358,8 @@ v3 TypeScript uses camelCase for all parameters: | Parameter | v2 Default | v3 Default | |-----------|------------|------------| -| `threshold` | 0.3 | 0.1 | -| `rerank` | (not specified) | `false` | +| `threshold` | 0.3 | server-side cutoff | +| `rerank` | `false` | `false` | **4. Removed Parameters** @@ -347,7 +371,6 @@ The following parameters are no longer supported: | `keyword_search` | Removed from search | | `filter_memories` | Removed | | `immutable` | Removed from add | -| `expiration_date` | Removed from add | | `includes` | Removed from add | | `excludes` | Removed from add | | `async_mode` | Removed from add | diff --git a/skills/mem0/references/use-cases.md b/skills/mem0/references/use-cases.md index 5f3ba655d..dbb514afa 100644 --- a/skills/mem0/references/use-cases.md +++ b/skills/mem0/references/use-cases.md @@ -30,7 +30,7 @@ openai_client = OpenAI() def chat(user_input: str, user_id: str) -> str: # 1. Retrieve relevant memories - memories = mem0.search(user_input, user_id=user_id) + memories = mem0.search(user_input, filters={"user_id": user_id}) context = "\n".join([f"- {m['memory']}" for m in memories.get("results", [])]) # 2. Generate response with memory context @@ -99,7 +99,7 @@ async function chat(userInput: string, userId: string): Promise { ### Key Benefits - Context persists across app restarts — no session management needed -- Memories are automatically deduplicated and updated +- Facts are extracted automatically and accumulate (ADD-only: nothing is overwritten or deleted) - Works with any LLM provider (OpenAI, Anthropic, etc.) **Best for:** Fitness coaches, tutors, therapists — any assistant that needs to remember goals across sessions. @@ -172,7 +172,7 @@ const client = new MemoryClient({ apiKey: process.env.MEM0_API_KEY! }); // Setup categories (one-time) await client.updateProject({ - custom_categories: [ + customCategories: [ { support_tickets: 'Customer issues and resolutions' }, { billing: 'Payment history and billing questions' }, { product_feedback: 'Feature requests and feedback' }, @@ -226,7 +226,7 @@ def save_patient_info(user_id: str, information: str): def consult(user_id: str, question: str) -> str: # High threshold for medical accuracy - memories = mem0.search(question, user_id=user_id, top_k=5, threshold=0.7) + memories = mem0.search(question, filters={"user_id": user_id}, top_k=5, threshold=0.7) context = "\n".join([f"- {m['memory']}" for m in memories.get("results", [])]) response = openai_client.chat.completions.create( @@ -295,7 +295,7 @@ async function consult(userId: string, question: string): Promise { ### Key Benefits -- High threshold (0.7) ensures only confident matches for safety-critical retrieval +- High threshold (0.7) drops weak matches for safety-critical retrieval (it is a server-side cutoff applied before score blending, so check `score` too) - Session scoping via `run_id` groups related health interactions - Metadata tagging separates patient info from conversation history @@ -384,7 +384,7 @@ async function draftContent(userId: string, topic: string): Promise { - Voice consistency across all content without repeating guidelines - Scoped sessions let you maintain different style profiles -- Preferences update automatically as you refine them +- Refined preferences are added alongside earlier ones (ADD-only), and retrieval ranks relevance **Best for:** Marketing teams, technical writers, agencies — consistent voice across all content. @@ -426,7 +426,7 @@ def search_user_session(query: str, user_id: str, app_id: str, run_id: str): ) def search_agent_knowledge(query: str, agent_id: str, app_id: str): - """Search all memories an agent has across all users.""" + """Search facts attributed to an agent (from its assistant messages) in an app.""" return client.search( query, filters={ @@ -449,7 +449,7 @@ store_scoped_memory( # User-scoped query: "What does Cam prefer?" user_mems = search_user_session("dietary restrictions?", "traveler_cam", "concierge_app", "tokyo-2025") -# Agent-scoped query: "What do all travelers prefer?" (across users) +# Agent-scoped query: facts attributed to the travel_planner agent, not user preferences agent_mems = search_agent_knowledge("common dietary restrictions?", "travel_planner", "concierge_app") ``` @@ -490,6 +490,7 @@ async function searchAgentKnowledge(query: string, agentId: string, appId: strin - Full isolation between users, agents, sessions, and apps - Query at any scope level — user, agent, session, or app-wide - No memory leakage between tenants +- When `add` gets both `user_id` and `agent_id`, each fact is attributed to its speaker (user messages carry `user_id`, assistant messages carry `agent_id`), so an `AND` of both ids returns nothing; use `OR` (see [entity-scoped memory](https://docs.mem0.ai/platform/features/entity-scoped-memory)) **Best for:** Multi-agent workflows, multi-tenant SaaS — proper isolation at every level. @@ -516,7 +517,7 @@ Extract dietary preferences, location, interests, and purchase history.""" def personalized_search(user_id: str, query: str, search_results: list) -> str: # Get user context from memory - memories = mem0.search(query, user_id=user_id, top_k=5) + memories = mem0.search(query, filters={"user_id": user_id}, top_k=5) user_context = "\n".join([f"- {m['memory']}" for m in memories.get("results", [])]) response = openai_client.chat.completions.create( @@ -599,7 +600,7 @@ def store_email(user_id: str, sender: str, subject: str, body: str, date: str): def search_emails(user_id: str, query: str): return client.search( query, - filters={"AND": [{"user_id": user_id}, {"categories": {"contains": "email"}}]}, + filters={"AND": [{"user_id": user_id}, {"metadata": {"email_type": "incoming"}}]}, top_k=10 ) @@ -608,7 +609,7 @@ def get_emails_from_sender(user_id: str, sender: str): filters={ "AND": [ {"user_id": user_id}, - {"metadata": {"contains": sender}} + {"metadata": {"sender": sender}} ] } ) @@ -637,7 +638,7 @@ async function storeEmail(userId: string, sender: string, subject: string, body: async function searchEmails(userId: string, query: string) { return client.search(query, { - filters: { AND: [{ user_id: userId }, { categories: { contains: 'email' } }] }, + filters: { AND: [{ user_id: userId }, { metadata: { email_type: 'incoming' } }] }, topK: 10, }); } @@ -646,7 +647,7 @@ async function searchEmails(userId: string, query: string) { ### Key Benefits - Rich metadata enables multi-dimensional queries (sender, date, subject) -- Category filtering separates emails from other memory types +- Metadata filtering (`email_type`) separates emails from other memory types - Semantic search across all email content **Best for:** Inbox management, email automation — searchable email memories with metadata filtering. @@ -661,7 +662,7 @@ Every use case follows the same 3-step loop: ```python # 1. Retrieve relevant context -memories = mem0.search(user_input, user_id=user_id) +memories = mem0.search(user_input, filters={"user_id": user_id}) context = "\n".join([m["memory"] for m in memories.get("results", [])]) # 2. Generate with context @@ -717,4 +718,4 @@ client.project.update( ## More Examples -For 30+ cookbooks with complete working code: [docs.mem0.ai/cookbooks](https://docs.mem0.ai/cookbooks) +For 30+ cookbooks with complete working code: [docs.mem0.ai/cookbooks/overview](https://docs.mem0.ai/cookbooks/overview) diff --git a/skills/mem0/scripts/mem0_doc_search.py b/skills/mem0/scripts/mem0_doc_search.py index a04c89afb..0457038b2 100755 --- a/skills/mem0/scripts/mem0_doc_search.py +++ b/skills/mem0/scripts/mem0_doc_search.py @@ -1,10 +1,10 @@ #!/usr/bin/env python3 """ -Mem0 Documentation Search Agent (Mintlify-based) +Mem0 Documentation Search Agent On-demand search tool for querying Mem0 documentation without storing content locally. -This tool leverages Mintlify's documentation structure to perform just-in-time -retrieval of technical information from docs.mem0.ai. +This tool searches the docs.mem0.ai llms.txt index and fetches pages as markdown +to perform just-in-time retrieval of technical information. Usage: python mem0_doc_search.py --query "how to add graph memory" @@ -20,137 +20,124 @@ Purpose: - Search across the full Mem0 documentation site """ +from __future__ import annotations + import argparse import json +import re import sys import urllib.error import urllib.parse import urllib.request DOCS_BASE = "https://docs.mem0.ai" -SEARCH_ENDPOINT = f"{DOCS_BASE}/api/search" +DOCS_HOST = urllib.parse.urlsplit(DOCS_BASE).netloc LLMS_INDEX = f"{DOCS_BASE}/llms.txt" +ENTRY_URL = re.compile(r"\((https?://[^)\s]+)\)") +MAX_RESULTS = 20 +MAX_PAGE_CHARS = 10000 +MAX_INDEX_BYTES = 2_000_000 -# Known documentation sections for targeted retrieval -SECTION_MAP = { - "platform": [ - "/platform/overview", - "/platform/quickstart", - "/platform/features", - "/platform/features/graph-memory", - "/platform/features/selective-memory", - "/platform/features/custom-categories", - "/platform/features/v2-memory-filters", - "/platform/features/async-client", - "/platform/features/webhooks", - "/platform/features/multimodal-support", - ], - "api": [ - "/api-reference/memory/add-memories", - "/api-reference/memory/v2-search-memories", - "/api-reference/memory/v2-get-memories", - "/api-reference/memory/get-memory", - "/api-reference/memory/update-memory", - "/api-reference/memory/delete-memory", - ], - "open-source": [ - "/open-source/overview", - "/open-source/python-quickstart", - "/open-source/node-quickstart", - "/open-source/features", - "/open-source/features/graph-memory", - "/open-source/features/rest-api", - "/open-source/configure-components", - ], - "sdks": [ - "/sdks/python", - "/sdks/js", - ], - "integrations": [ - "/integrations", - ], +SECTION_PREFIXES = { + "platform": ("/platform/",), + "api": ("/api-reference/",), + "open-source": ("/open-source/", "/components/"), + "integrations": ("/integrations",), } -def fetch_url(url: str) -> str: - """Fetch content from a URL.""" +def require_docs_url(url: str) -> None: + """Exit unless the URL is an https URL on the Mem0 docs host.""" + parts = urllib.parse.urlsplit(url) + if parts.scheme != "https" or parts.netloc != DOCS_HOST: + sys.exit(f"Refusing to fetch {url}: only {DOCS_BASE} is allowed") + + +class DocsRedirectHandler(urllib.request.HTTPRedirectHandler): + """Follow redirects only when they stay on the Mem0 docs host.""" + + def redirect_request(self, req, fp, code, msg, headers, newurl): + require_docs_url(newurl) + return super().redirect_request(req, fp, code, msg, headers, newurl) + + +def fetch_url(url: str, max_bytes: int) -> tuple[str, bool]: + """Fetch at most max_bytes from a docs URL, returning the text and whether it was cut short.""" + require_docs_url(url) + opener = urllib.request.build_opener(DocsRedirectHandler) req = urllib.request.Request(url, headers={"User-Agent": "Mem0DocSearchAgent/1.0"}) try: - with urllib.request.urlopen(req, timeout=15) as resp: - return resp.read().decode("utf-8") + with opener.open(req, timeout=15) as resp: + data = resp.read(max_bytes + 1) except urllib.error.HTTPError as e: - return f"HTTP Error {e.code}: {e.reason}" - except urllib.error.URLError as e: - return f"URL Error: {e.reason}" + sys.exit(f"Error fetching {url}: HTTP {e.code} {e.reason}") + except OSError as e: + sys.exit(f"Error fetching {url}: {e}") + return data[:max_bytes].decode("utf-8", errors="replace"), len(data) > max_bytes + + +def index_entries() -> list: + """Return the page entries listed in the llms.txt index.""" + content, truncated = fetch_url(LLMS_INDEX, MAX_INDEX_BYTES) + if truncated: + sys.exit(f"Error: {LLMS_INDEX} exceeds {MAX_INDEX_BYTES} bytes") + return [line.strip()[2:] for line in content.splitlines() if line.strip().startswith("- [")] + + +def entry_path(entry: str) -> str: + """Extract the URL path from an llms.txt index entry.""" + match = ENTRY_URL.search(entry) + return urllib.parse.urlparse(match.group(1)).path if match else "" def search_docs(query: str, section: str | None = None) -> dict: - """ - Search Mem0 documentation using Mintlify's search API. - Falls back to the llms.txt index for keyword matching if the API is unavailable. - """ - # Try Mintlify search API first - params = urllib.parse.urlencode({"query": query}) - search_url = f"{SEARCH_ENDPOINT}?{params}" + """Search the llms.txt index for entries matching the query terms, best matches first.""" + terms = re.findall(r"[a-z0-9_]+", query.lower()) + entries = index_entries() - try: - result = fetch_url(search_url) - data = json.loads(result) - if isinstance(data, dict) and data.get("results"): - results = data["results"] - if section and section in SECTION_MAP: - section_paths = SECTION_MAP[section] - results = [r for r in results if any(r.get("url", "").startswith(p) for p in section_paths)] - return {"source": "mintlify_search", "results": results} - except (json.JSONDecodeError, Exception): - pass + if section in SECTION_PREFIXES: + entries = [e for e in entries if entry_path(e).startswith(SECTION_PREFIXES[section])] - # Fallback: search llms.txt index for matching URLs - index_content = fetch_url(LLMS_INDEX) - query_lower = query.lower() - matching_urls = [] - - for line in index_content.splitlines(): - line = line.strip() - if not line or line.startswith("#"): - continue - if query_lower in line.lower(): - matching_urls.append(line) - - if section and section in SECTION_MAP: - section_paths = SECTION_MAP[section] - matching_urls = [u for u in matching_urls if any(p in u for p in section_paths)] + scored = [] + for entry in entries: + haystack = entry.lower() + title = haystack.split("]")[0] + score = sum((term in haystack) + (term in title) for term in terms) + if score: + scored.append((score, entry)) + scored.sort(key=lambda item: -item[0]) return { "source": "llms_txt_index", "query": query, - "matching_urls": matching_urls[:20], - "suggestion": "Fetch specific URLs for detailed content", + "matching_urls": [entry for _, entry in scored[:MAX_RESULTS]], + "suggestion": "Fetch specific pages with --page for detailed content", } def fetch_page(page_path: str) -> dict: - """Fetch a specific documentation page.""" - url = f"{DOCS_BASE}{page_path}" if page_path.startswith("/") else page_path - content = fetch_url(url) - return {"url": url, "content": content[:10000], "truncated": len(content) > 10000} + """Fetch a specific documentation page as markdown.""" + parts = urllib.parse.urlsplit(urllib.parse.urljoin(DOCS_BASE, page_path)) + path = parts.path.rstrip("/") + if not path.endswith(".md"): + path = f"{path}.md" + url = urllib.parse.urlunsplit((parts.scheme, parts.netloc, path, "", "")) + content, cut_short = fetch_url(url, MAX_PAGE_CHARS * 4) + return {"url": url, "content": content[:MAX_PAGE_CHARS], "truncated": cut_short or len(content) > MAX_PAGE_CHARS} def get_index() -> dict: """Fetch the full documentation index from llms.txt.""" - content = fetch_url(LLMS_INDEX) - urls = [line.strip() for line in content.splitlines() if line.strip() and not line.startswith("#")] - return {"total_pages": len(urls), "urls": urls, "sections": list(SECTION_MAP.keys())} + urls = index_entries() + return {"total_pages": len(urls), "urls": urls, "sections": list(SECTION_PREFIXES)} def list_section(section: str) -> dict: - """List all known pages in a documentation section.""" - if section not in SECTION_MAP: - return {"error": f"Unknown section: {section}", "available": list(SECTION_MAP.keys())} - return { - "section": section, - "pages": [f"{DOCS_BASE}{p}" for p in SECTION_MAP[section]], - } + """List the llms.txt index entries in a documentation section.""" + if section not in SECTION_PREFIXES: + return {"error": f"Unknown section: {section}", "available": list(SECTION_PREFIXES)} + pages = [e for e in index_entries() if entry_path(e).startswith(SECTION_PREFIXES[section])] + return {"section": section, "pages": pages} def main(): @@ -206,7 +193,7 @@ def main(): elif "content" in result: print(f"URL: {result['url']}") if result.get("truncated"): - print("[Content truncated to 10000 chars]") + print(f"[Content truncated to {MAX_PAGE_CHARS} chars]") print(result["content"]) elif "error" in result: print(f"Error: {result['error']}") From d26ba5e4518cef7fff3c66d4f715b21adf9feabe Mon Sep 17 00:00:00 2001 From: Kartik Date: Mon, 12 Oct 2026 21:58:27 +0530 Subject: [PATCH 53/61] fix(client): reject empty entity IDs and filters in add and delete_all (#7581) --- .../memory-operations/delete.mdx | 4 + docs/platform/features/async-client.mdx | 2 +- .../platform/features/custom-instructions.mdx | 2 +- mem0-ts/src/client/mem0.ts | 32 +++ .../tests/memoryClient.entityGuards.test.ts | 234 ++++++++++++++++++ mem0/client/main.py | 49 +++- mem0/client/types.py | 39 ++- mem0/proxy/main.py | 5 +- tests/test_client.py | 6 +- tests/test_client_entity_guards.py | 198 +++++++++++++++ tests/test_proxy.py | 19 ++ 11 files changed, 548 insertions(+), 42 deletions(-) create mode 100644 mem0-ts/src/client/tests/memoryClient.entityGuards.test.ts create mode 100644 tests/test_client_entity_guards.py 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/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/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/mem0-ts/src/client/mem0.ts b/mem0-ts/src/client/mem0.ts index 0f8725164..c386be323 100644 --- a/mem0-ts/src/client/mem0.ts +++ b/mem0-ts/src/client/mem0.ts @@ -74,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)); } @@ -396,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); @@ -540,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)); @@ -611,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; 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/client/main.py b/mem0/client/main.py index d65d4f0b1..18896466a 100644 --- a/mem0/client/main.py +++ b/mem0/client/main.py @@ -91,6 +91,24 @@ def _encode_path_segment(value: Any) -> str: return quote(str(value), safe="") +def _reject_filters(method: str, params: Dict[str, Any]) -> None: + """Raise when filters is passed to an endpoint that reads entity IDs at the top level.""" + if params.get("filters") is not None: + raise ValueError( + f"filters is not supported in {method}(). Pass entity IDs at the top level, e.g. user_id='...'." + ) + + +def _reject_blank_entity_ids(params: Dict[str, Any]) -> None: + """Raise on an empty or whitespace-only entity ID, which the API treats as matching every memory.""" + for name, value in params.items(): + if name in ENTITY_PARAMS and isinstance(value, str) and not value.strip(): + raise ValueError( + f"{name} cannot be empty or whitespace-only: an empty ID would match every memory in the project. " + f"To delete everything on purpose, call delete_all() with '*' explicitly." + ) + + def _maybe_alias_anon_to_email(user_email): """Fire $identify per prior anon ID so PostHog merges them into email. @@ -309,7 +327,7 @@ class MemoryClient: a user message. options: Typed options for the add operation (AddMemoryOptions). **kwargs: Additional parameters such as user_id, agent_id, app_id, - metadata, filters. + run_id, metadata. Entity IDs go at the top level, not in filters. Returns: A dictionary containing the API response in v1.1 format. @@ -321,8 +339,10 @@ class MemoryClient: MemoryQuotaExceededError: If memory quota is exceeded. NetworkError: If network connectivity issues occur. MemoryNotFoundError: If the memory doesn't exist (for updates/deletes). + ValueError: If filters is passed. """ kwargs = {**(options.model_dump(exclude_unset=True) if options else {}), **kwargs} + _reject_filters("add", kwargs) # Handle different message input formats (align with OSS behavior) if isinstance(messages, str): messages = [{"role": "user", "content": messages}] @@ -533,12 +553,12 @@ class MemoryClient: @api_error_handler def delete_all(self, options: Optional[DeleteAllMemoryOptions] = None, **kwargs) -> Dict[str, str]: - """Delete all memories, with optional filtering. + """Delete all memories for the given entity IDs. Args: options: Typed options for the delete_all operation (DeleteAllMemoryOptions). - **kwargs: Optional parameters for filtering (user_id, agent_id, - app_id). + **kwargs: Entity IDs to delete memories for (user_id, agent_id, app_id, run_id). + Pass '*' to target every entity of that type. Returns: A dictionary containing the API response. @@ -550,8 +570,11 @@ class MemoryClient: MemoryQuotaExceededError: If memory quota is exceeded. NetworkError: If network connectivity issues occur. MemoryNotFoundError: If the memory doesn't exist (for updates/deletes). + ValueError: If filters is passed or an entity ID is empty or whitespace-only. """ kwargs = {**(options.model_dump(exclude_unset=True) if options else {}), **kwargs} + _reject_filters("delete_all", kwargs) + _reject_blank_entity_ids(kwargs) params = self._prepare_params(kwargs) response = self.client.delete("/v1/memories/", params=params) response.raise_for_status() @@ -615,12 +638,13 @@ class MemoryClient: Dict with success message Raises: - ValueError: If specified entity not found + ValueError: If specified entity not found or an entity ID is empty or whitespace-only ValidationError: If the input data is invalid. AuthenticationError: If authentication fails. MemoryNotFoundError: If the entity doesn't exist. NetworkError: If network connectivity issues occur. """ + _reject_blank_entity_ids({"user_id": user_id, "agent_id": agent_id, "app_id": app_id, "run_id": run_id}) if user_id: to_delete = [{"type": "user", "name": user_id}] @@ -1404,7 +1428,7 @@ class AsyncMemoryClient: a user message. options: Typed options for the add operation (AddMemoryOptions). **kwargs: Additional parameters such as user_id, agent_id, app_id, - metadata, filters. + run_id, metadata. Entity IDs go at the top level, not in filters. Returns: A dictionary containing the API response in v1.1 format. @@ -1416,8 +1440,10 @@ class AsyncMemoryClient: MemoryQuotaExceededError: If memory quota is exceeded. NetworkError: If network connectivity issues occur. MemoryNotFoundError: If the memory doesn't exist (for updates/deletes). + ValueError: If filters is passed. """ kwargs = {**(options.model_dump(exclude_unset=True) if options else {}), **kwargs} + _reject_filters("add", kwargs) # Handle different message input formats (align with OSS behavior) if isinstance(messages, str): messages = [{"role": "user", "content": messages}] @@ -1614,11 +1640,12 @@ class AsyncMemoryClient: @api_error_handler async def delete_all(self, options: Optional[DeleteAllMemoryOptions] = None, **kwargs) -> Dict[str, str]: - """Delete all memories, with optional filtering. + """Delete all memories for the given entity IDs. Args: options: Typed options for the delete_all operation (DeleteAllMemoryOptions). - **kwargs: Optional parameters for filtering (user_id, agent_id, app_id). + **kwargs: Entity IDs to delete memories for (user_id, agent_id, app_id, run_id). + Pass '*' to target every entity of that type. Returns: A dictionary containing the API response. @@ -1630,8 +1657,11 @@ class AsyncMemoryClient: MemoryQuotaExceededError: If memory quota is exceeded. NetworkError: If network connectivity issues occur. MemoryNotFoundError: If the memory doesn't exist (for updates/deletes). + ValueError: If filters is passed or an entity ID is empty or whitespace-only. """ kwargs = {**(options.model_dump(exclude_unset=True) if options else {}), **kwargs} + _reject_filters("delete_all", kwargs) + _reject_blank_entity_ids(kwargs) params = self._prepare_params(kwargs) response = await self.async_client.delete("/v1/memories/", params=params) response.raise_for_status() @@ -1694,12 +1724,13 @@ class AsyncMemoryClient: Dict with success message Raises: - ValueError: If specified entity not found + ValueError: If specified entity not found or an entity ID is empty or whitespace-only ValidationError: If the input data is invalid. AuthenticationError: If authentication fails. MemoryNotFoundError: If the entity doesn't exist. NetworkError: If network connectivity issues occur. """ + _reject_blank_entity_ids({"user_id": user_id, "agent_id": agent_id, "app_id": app_id, "run_id": run_id}) if user_id: to_delete = [{"type": "user", "name": user_id}] diff --git a/mem0/client/types.py b/mem0/client/types.py index 5663dcf5d..5d88b821f 100644 --- a/mem0/client/types.py +++ b/mem0/client/types.py @@ -1,11 +1,4 @@ -"""Pydantic option models for MemoryClient methods. - -These models provide IDE autocompletion, runtime validation, and type safety. -Methods accept both typed options and **kwargs for backward compatibility. - -Identity fields (user_id, agent_id, app_id, run_id) must be passed inside -the ``filters`` dict — the v3 API does not accept them at the top level. -""" +"""Pydantic option models for MemoryClient methods.""" from typing import Any, Dict, List, Optional, Union @@ -13,15 +6,12 @@ from pydantic import BaseModel, Field class AddMemoryOptions(BaseModel): - """Options for the add() method. + """Options for the add() method, with entity IDs passed at the top level.""" - Identity fields (user_id, agent_id, app_id, run_id) must be passed inside - the ``filters`` dict — the v3 API does not accept them at the top level. - """ - - filters: Optional[Dict[str, Any]] = Field( - default=None, description="Filters containing entity IDs (e.g. {'user_id': '...'})" - ) + user_id: Optional[str] = Field(default=None, description="User the memory belongs to") + agent_id: Optional[str] = Field(default=None, description="Agent the memory belongs to") + app_id: Optional[str] = Field(default=None, description="App the memory belongs to") + run_id: Optional[str] = Field(default=None, description="Run the memory belongs to") metadata: Optional[Dict[str, Any]] = Field(default=None, description="Additional metadata for the memory") infer: Optional[bool] = Field(default=None, description="Whether to infer memories from the input") custom_categories: Optional[List[Dict[str, Any]]] = Field( @@ -86,15 +76,12 @@ class GetAllMemoryOptions(BaseModel): class DeleteAllMemoryOptions(BaseModel): - """Options for the delete_all() method. + """Options for the delete_all() method, with entity IDs passed at the top level.""" - Identity fields (user_id, agent_id, app_id, run_id) must be passed inside - the ``filters`` dict — the API does not accept them at the top level. - """ - - filters: Optional[Dict[str, Any]] = Field( - default=None, description="Filters containing entity IDs (e.g. {'user_id': '...'})" - ) + user_id: Optional[str] = Field(default=None, description="Delete memories belonging to this user") + agent_id: Optional[str] = Field(default=None, description="Delete memories belonging to this agent") + app_id: Optional[str] = Field(default=None, description="Delete memories belonging to this app") + run_id: Optional[str] = Field(default=None, description="Delete memories belonging to this run") class UpdateMemoryOptions(BaseModel): @@ -103,7 +90,9 @@ class UpdateMemoryOptions(BaseModel): text: Optional[str] = Field(default=None, description="New text content for the memory") metadata: Optional[Dict[str, Any]] = Field(default=None, description="Updated metadata") timestamp: Optional[Union[int, float, str]] = Field(default=None, description="Updated timestamp") - expiration_date: Optional[str] = Field(default=None, description="Expiration date in YYYY-MM-DD format, or None to clear") + expiration_date: Optional[str] = Field( + default=None, description="Expiration date in YYYY-MM-DD format, or None to clear" + ) class ProjectUpdateOptions(BaseModel): diff --git a/mem0/proxy/main.py b/mem0/proxy/main.py index 167bc3f58..5806fca74 100644 --- a/mem0/proxy/main.py +++ b/mem0/proxy/main.py @@ -99,7 +99,7 @@ class Completions: prepared_messages = self._prepare_messages(messages) if prepared_messages[-1]["role"] == "user": - self._async_add_to_memory(messages, user_id, agent_id, run_id, metadata, filters) + self._async_add_to_memory(messages, user_id, agent_id, run_id, metadata) relevant_memories = self._fetch_relevant_memories(messages, user_id, agent_id, run_id, filters, top_k) logger.debug(f"Retrieved {len(relevant_memories)} relevant memories") prepared_messages[-1]["content"] = self._format_query_with_memories(messages, relevant_memories) @@ -146,7 +146,7 @@ class Completions: return [{"role": "system", "content": MEMORY_ANSWER_PROMPT}] + messages return messages - def _async_add_to_memory(self, messages, user_id, agent_id, run_id, metadata, filters): + def _async_add_to_memory(self, messages, user_id, agent_id, run_id, metadata): def add_task(): logger.debug("Adding to memory asynchronously") self.mem0_client.add( @@ -155,7 +155,6 @@ class Completions: agent_id=agent_id, run_id=run_id, metadata=metadata, - filters=filters, ) threading.Thread(target=add_task, daemon=True).start() diff --git a/tests/test_client.py b/tests/test_client.py index 07fc2052b..138b8a97d 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -602,7 +602,7 @@ class TestAddAgentCustomInstructions: mock_memory_client.add( "hello", - filters={"agent_id": "a1"}, + agent_id="a1", agent_custom_instructions="remember tool failures", ) @@ -617,7 +617,7 @@ class TestAddAgentCustomInstructions: mock_memory_client.add( "hello", AddMemoryOptions( - filters={"agent_id": "a1"}, + agent_id="a1", agent_custom_instructions="remember tool failures", ), ) @@ -629,7 +629,7 @@ class TestAddAgentCustomInstructions: """Callers that don't use the feature send an unchanged payload.""" self._mock_add(mock_memory_client) - mock_memory_client.add("hello", filters={"user_id": "u1"}) + mock_memory_client.add("hello", user_id="u1") _, kwargs = mock_memory_client.client.post.call_args assert "agent_custom_instructions" not in kwargs["json"] diff --git a/tests/test_client_entity_guards.py b/tests/test_client_entity_guards.py new file mode 100644 index 000000000..28bef2a75 --- /dev/null +++ b/tests/test_client_entity_guards.py @@ -0,0 +1,198 @@ +"""Tests for entity ID handling in MemoryClient add, delete_all, and delete_users.""" + +import asyncio +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from mem0.client.main import AsyncMemoryClient, MemoryClient +from mem0.client.types import AddMemoryOptions, DeleteAllMemoryOptions + +ENTITY_FIELDS = ["user_id", "agent_id", "app_id", "run_id"] +BLANK_IDS = ["", " ", "\t\n"] + + +def _ok_response(body=None): + response = MagicMock() + response.json.return_value = body if body is not None else {"message": "ok"} + response.raise_for_status.return_value = None + return response + + +@pytest.fixture +def sync_client(): + client = MemoryClient.__new__(MemoryClient) + client.client = MagicMock() + client.client.post.return_value = _ok_response() + client.client.delete.return_value = _ok_response() + with patch("mem0.client.main.capture_client_event"): + yield client + + +@pytest.fixture +def async_client(): + client = AsyncMemoryClient.__new__(AsyncMemoryClient) + client.async_client = MagicMock() + client.async_client.post = AsyncMock(return_value=_ok_response()) + client.async_client.delete = AsyncMock(return_value=_ok_response()) + with patch("mem0.client.main.capture_client_event"): + yield client + + +class TestDeleteAllBlankEntityIds: + @pytest.mark.parametrize("field", ENTITY_FIELDS) + @pytest.mark.parametrize("blank", BLANK_IDS) + def test_sync_raises_without_http_call(self, sync_client, field, blank): + with pytest.raises(ValueError, match=field): + sync_client.delete_all(**{field: blank}) + + sync_client.client.delete.assert_not_called() + + @pytest.mark.parametrize("field", ENTITY_FIELDS) + @pytest.mark.parametrize("blank", BLANK_IDS) + def test_async_raises_without_http_call(self, async_client, field, blank): + with pytest.raises(ValueError, match=field): + asyncio.run(async_client.delete_all(**{field: blank})) + + async_client.async_client.delete.assert_not_called() + + def test_blank_id_next_to_valid_id_still_raises(self, sync_client): + with pytest.raises(ValueError, match="agent_id"): + sync_client.delete_all(user_id="u1", agent_id="") + + sync_client.client.delete.assert_not_called() + + def test_blank_id_in_typed_options_raises(self, sync_client): + with pytest.raises(ValueError, match="user_id"): + sync_client.delete_all(DeleteAllMemoryOptions(user_id=" ")) + + sync_client.client.delete.assert_not_called() + + def test_error_explains_the_risk_and_the_wildcard(self, sync_client): + with pytest.raises(ValueError) as exc_info: + sync_client.delete_all(user_id="") + + message = str(exc_info.value) + assert "every memory in the project" in message + assert "'*'" in message + + +class TestDeleteAllValidInputs: + def test_sync_sends_entity_id_as_query_param(self, sync_client): + sync_client.delete_all(user_id="u1") + + sync_client.client.delete.assert_called_once_with("/v1/memories/", params={"user_id": "u1"}) + + def test_async_sends_entity_id_as_query_param(self, async_client): + asyncio.run(async_client.delete_all(user_id="u1")) + + async_client.async_client.delete.assert_called_once_with("/v1/memories/", params={"user_id": "u1"}) + + def test_typed_options_send_entity_id_as_query_param(self, sync_client): + sync_client.delete_all(DeleteAllMemoryOptions(user_id="u1")) + + sync_client.client.delete.assert_called_once_with("/v1/memories/", params={"user_id": "u1"}) + + def test_wildcard_is_still_allowed(self, sync_client): + sync_client.delete_all(user_id="*") + + sync_client.client.delete.assert_called_once_with("/v1/memories/", params={"user_id": "*"}) + + +class TestDeleteAllRejectsFilters: + def test_sync_raises_without_http_call(self, sync_client): + with pytest.raises(ValueError, match="filters"): + sync_client.delete_all(filters={"user_id": "u1"}) + + sync_client.client.delete.assert_not_called() + + def test_async_raises_without_http_call(self, async_client): + with pytest.raises(ValueError, match="filters"): + asyncio.run(async_client.delete_all(filters={"user_id": "u1"})) + + async_client.async_client.delete.assert_not_called() + + +class TestDeleteUsersBlankEntityIds: + @pytest.mark.parametrize("field", ENTITY_FIELDS) + @pytest.mark.parametrize("blank", BLANK_IDS) + def test_sync_raises_before_any_request(self, sync_client, field, blank): + with patch.object(sync_client, "users") as users: + with pytest.raises(ValueError, match=field): + sync_client.delete_users(**{field: blank}) + + users.assert_not_called() + sync_client.client.delete.assert_not_called() + + @pytest.mark.parametrize("field", ENTITY_FIELDS) + @pytest.mark.parametrize("blank", BLANK_IDS) + def test_async_raises_before_any_request(self, async_client, field, blank): + with patch.object(async_client, "users", new=AsyncMock()) as users: + with pytest.raises(ValueError, match=field): + asyncio.run(async_client.delete_users(**{field: blank})) + + users.assert_not_called() + async_client.async_client.delete.assert_not_called() + + +class TestDeleteUsersValidInputs: + def test_sync_deletes_the_named_entity(self, sync_client): + sync_client.delete_users(user_id="u1") + + sync_client.client.delete.assert_called_once_with("/v2/entities/user/u1/", params={}) + + def test_async_deletes_the_named_entity(self, async_client): + asyncio.run(async_client.delete_users(user_id="u1")) + + async_client.async_client.delete.assert_called_once_with("/v2/entities/user/u1/", params={}) + + def test_no_ids_still_deletes_every_listed_entity(self, sync_client): + listing = {"results": [{"type": "user", "name": "u1"}, {"type": "agent", "name": "a1"}]} + + with patch.object(sync_client, "users", return_value=listing): + sync_client.delete_users() + + deleted_paths = [call.args[0] for call in sync_client.client.delete.call_args_list] + assert deleted_paths == ["/v2/entities/user/u1/", "/v2/entities/agent/a1/"] + + +class TestAddEntityIds: + def test_sync_rejects_filters_without_http_call(self, sync_client): + with pytest.raises(ValueError, match="user_id"): + sync_client.add("hello", filters={"user_id": "u1"}) + + sync_client.client.post.assert_not_called() + + def test_async_rejects_filters_without_http_call(self, async_client): + with pytest.raises(ValueError, match="user_id"): + asyncio.run(async_client.add("hello", filters={"user_id": "u1"})) + + async_client.async_client.post.assert_not_called() + + def test_filters_none_is_treated_as_not_provided(self, sync_client): + sync_client.add("hello", user_id="u1", filters=None) + + payload = sync_client.client.post.call_args.kwargs["json"] + assert payload["user_id"] == "u1" + assert "filters" not in payload + + def test_sync_typed_options_put_entity_ids_in_payload(self, sync_client): + sync_client.add("hello", AddMemoryOptions(user_id="u1", agent_id="a1", app_id="p1", run_id="r1")) + + payload = sync_client.client.post.call_args.kwargs["json"] + assert payload["user_id"] == "u1" + assert payload["agent_id"] == "a1" + assert payload["app_id"] == "p1" + assert payload["run_id"] == "r1" + + def test_async_typed_options_put_entity_ids_in_payload(self, async_client): + asyncio.run(async_client.add("hello", AddMemoryOptions(user_id="u1"))) + + payload = async_client.async_client.post.call_args.kwargs["json"] + assert payload["user_id"] == "u1" + + def test_kwargs_put_entity_ids_in_payload(self, sync_client): + sync_client.add("hello", user_id="u1") + + payload = sync_client.client.post.call_args.kwargs["json"] + assert payload["user_id"] == "u1" diff --git a/tests/test_proxy.py b/tests/test_proxy.py index 8e48a4c6d..26209695e 100644 --- a/tests/test_proxy.py +++ b/tests/test_proxy.py @@ -86,6 +86,25 @@ def test_completions_create(mock_memory_client, mock_litellm): assert response == {"choices": [{"message": {"content": "I'm doing well, thank you!"}}]} +def test_completions_create_keeps_filters_out_of_add(mock_memory_client, mock_litellm): + completions = Completions(mock_memory_client) + mock_memory_client.search.return_value = [] + mock_litellm.supports_function_calling.return_value = True + + with patch("mem0.proxy.main.threading.Thread") as mock_thread: + mock_thread.side_effect = lambda target, daemon: Mock(start=target) + completions.create( + model="gpt-4.1-nano-2025-04-14", + messages=[{"role": "user", "content": "Hello"}], + user_id="test_user", + filters={"categories": {"in": ["travel"]}}, + ) + + assert "filters" not in mock_memory_client.add.call_args.kwargs + assert mock_memory_client.add.call_args.kwargs["user_id"] == "test_user" + assert mock_memory_client.search.call_args.kwargs["filters"] == {"categories": {"in": ["travel"]}} + + def test_completions_create_with_system_message(mock_memory_client, mock_litellm): completions = Completions(mock_memory_client) From 0724291bd864cf807e88ee8981c8226644e8fb42 Mon Sep 17 00:00:00 2001 From: Karthik Date: Wed, 14 Oct 2026 21:09:50 +0530 Subject: [PATCH 54/61] Add OSS Halloween Happy Hour banner to README (#7637) --- README.md | 11 +++++++++++ docs/images/halloween-happy-hour.png | Bin 0 -> 742301 bytes 2 files changed, 11 insertions(+) create mode 100644 docs/images/halloween-happy-hour.png 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/docs/images/halloween-happy-hour.png b/docs/images/halloween-happy-hour.png new file mode 100644 index 0000000000000000000000000000000000000000..8b5ab3874af3dc497c5fcc347001261e482d6992 GIT binary patch literal 742301 zcmV)6K*+y|P)0004iP)t-s`ugkn z`sexi?E3lX`T6Pj`RDie==t{T_xA7i_U!id>-hKR_xI`d_viQb<@NUJ`StJj_3!re z?Dq8Q`1R=a^y&BY=JoXN_4MrZ^y>5U>h<*L_4VfS^y&KZ^Y-)Y_VeoX^X&EW>h|;L z^z-TU^XBvO>htpH@$%{O^5*&O`uFee`RV%f?(XyO=knn%JJ68+uXqI-@5qIx#Zun`q{Dc+Nt@`uI$jJ z@6(_6&z|zjp6$<<_Q{s<%8&NCqRqdT-^G&cxRTk#jPk;b>b8v9!iMv|hv~n9@w$ZQ zu7lLRee=3~?znvHx_9!mdhE1&6A=*-5(o(h4eo6d00961Nkl_wWGPQmD<3IoLkDcA4!_?ZFHy?ie^{2P#)Xvi% zcaQ7SrKN}C$-~2PJQ&BmKb+*7)IJVCfe9THRM_Rnflxa(jEP(?>nCRxCGK^c-DN5bV{=^G2O&zG|xU zB07tCI9o(Qx!N_W^w0S?=*O`xh*7Uru6BBcHD4`t$zEy2Jm2PuO|O=3d_LKFy7ubL zo6|zQBiAHD5Y%p~m@T(^a-&}7Z>}$LC#R?Tn}2`xx4-@Hx99BfViS+l{^@xplR2YD zHk-}o^QEiGO})|j{P~YRy7VyHs;c{;PQP1TEEacdzRHQR$nk3TZgJPjpPgjOW>;va zX7{dJ%V+bAuFP?K`|hqSt8KH}sTGS=b=WLdYbyQx(9xQrsED;HFZUKhQx>I8lisy# zN`h#NB16-?o+=1NWQd{_>OxhtTwQl@O>gmsK_3tLilpOTx0cnv{X$>)LVvjZ&9%H>GSd)h@U;36yH%O-+weTzc$C0=uUqfw!E zc5<>ukC$7gnF9WCR=B>Yx9Cx?-&_|mr>UJcub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Xu0mjfnYs6O literal 0 HcmV?d00001 From 2c81af3bbe27d9bccb09c772d583df9e9be72ee5 Mon Sep 17 00:00:00 2001 From: harsh-mem0 Date: Tue, 20 Oct 2026 21:16:17 -0400 Subject: [PATCH 55/61] docs(platform): rewrite the BYOK page as a feature guide (#7661) Co-authored-by: AGAMPANDEYY --- docs/docs.json | 3 +- .../images/platform/byok-accuracy-vs-cost.png | Bin 0 -> 451843 bytes docs/images/platform/byok-picks.png | Bin 0 -> 76519 bytes docs/llms.txt | 1 + docs/platform/features/byok.mdx | 126 ++++++++++++++++++ 5 files changed, 129 insertions(+), 1 deletion(-) create mode 100644 docs/images/platform/byok-accuracy-vs-cost.png create mode 100644 docs/images/platform/byok-picks.png create mode 100644 docs/platform/features/byok.mdx diff --git a/docs/docs.json b/docs/docs.json index 4371c1ffe..c3ffd6d87 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -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" ] }, { 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 0000000000000000000000000000000000000000..020c40fc04ec74b5a948b3baef954dff988c4113 GIT binary patch literal 451843 zcmeFZhd-8m{|Br+NYgAdjBHtDga)#+vkRFadsEs*1KCB{r$m{VsZC9;@Dk|C?R8-WP zH?PH41TRKQQ>~$*QaXJ?$1CAim*=@XgNq*)UmX2qet=%*lG)z#r})mj2rS^Z{}l*g9j+L2sVC$X6&*c#G{>ZL=JnNeiL!wWzMH6G zPZp-6q=a^F{7=~Y{VVqMSXU{2BWCj9LHXbWY44XOZ){~MLf13+Kh5dv`1D9S{tJNN$m`wtvAU{>KrvXb`t{jI>h{qb?%DA~XjW-+^#Ozm{tEWL$A2`Z|W zXD|G#zs`+4Gsv_0`to9;jKA`<&$W%)q6AC~3+!6+^Spd~)Z@j~hRAEzuKiSB-&_$e z(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g0H{sx?ug@px7=7B@0U1@k^xT>nkV|6IQrGg6jZ;*K_ z7@y}MQyAK<`jncSErFx_$E!Yf?&pIgSB(+beAtY{3;%eIC;p%IHvjs*kMGoYcmDjZ zpE-B#YxO^t^uNBw<@68B+rK^)|M(v|+P^-fK=Hqg@BaRU&uPQ|>y3afJRy|+|6awv z8*u&ogFhSoaaaHKS@L8+|DQgI>6vS%=cx;=-Fp6N RWjMP|8A(Nn0x_eP{|{B0jI00v literal 0 HcmV?d00001 diff --git a/docs/images/platform/byok-picks.png b/docs/images/platform/byok-picks.png new file mode 100644 index 0000000000000000000000000000000000000000..f09b9b2af95e04754f9541485836a66bc1986132 GIT binary patch literal 76519 zcmeEuRX~(o_b(WPNJvVjG=p?^cZ0wH(j_3>DUE`3ceiwd5+dDQ(nB`_5@++i-}k>c zx98$q{O8KSndjNh-fOSDez7J@Sy2l01;GnAI5<=pX>nCJIE1foa8E3do`Am`j&Pj7 z!NbAHh>NJZrR^^vs$**{ARf>C9FJa3HG+p{&@2m^_2goiPC6|}u?@GwG?riP7B^;> z_%hpKH1kg7nfR-(6yu(Da(eZHt_dfp@@6P<2CENzBH>U|NS?d6B4G&|GeRShRpXrZ-@f|iU0e?4^5;K z?Z0n?L&yvf|NACO?CZDxxz8y1|K8?*C+&YD?SJ>p|HEW+3=$b{hCFp?X(?7j&-jB> zjER&THk@!_=jz9+2PInU-MzgtH-1qqatIt;El2lrI5;<#bi z;3~AzJB`8!hG;r#U zp7?(s9aW~qJ|+0r1Vsy(7+XMs8!i4yMVB~Win_bI3rl@Ngw{JdJ3Bd9Yuxn~Tt%2q z3*JoRs7=q(lrSEJd)<-!IGiGBr85&bPz$ahSyZjUbKkzQ*HK z#*>|mrqb5Y(b3S5zz75bY-(x}CWFDgJb{CaQ(?+jT3YJq5sP5_{P`0X7x!SU7vCNp zPI!h4JhIN4G$St7Gehw44<8oCbf3Y&DQReGCL|n8A^e%F4=ZhbB%=PSNadxeZ8gaQFEY6&2u;kVKRq zQC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^&e4GcZ&c3 literal 0 HcmV?d00001 diff --git a/docs/llms.txt b/docs/llms.txt index c511033ce..7ceef9578 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -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 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. + From 26cdefb46600c0fa5953c4b5ee5003c125539fc4 Mon Sep 17 00:00:00 2001 From: harsh-mem0 Date: Mon, 26 Oct 2026 10:51:39 -0400 Subject: [PATCH 56/61] docs(platform): add the pricing FAQ page (#7711) --- docs/docs.json | 3 +- docs/llms.txt | 1 + docs/platform/pricing.mdx | 96 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 99 insertions(+), 1 deletion(-) create mode 100644 docs/platform/pricing.mdx diff --git a/docs/docs.json b/docs/docs.json index c3ffd6d87..b694e288a 100644 --- a/docs/docs.json +++ b/docs/docs.json @@ -116,7 +116,8 @@ "group": "Support", "icon": "life-buoy", "pages": [ - "platform/faqs" + "platform/faqs", + "platform/pricing" ] }, { diff --git a/docs/llms.txt b/docs/llms.txt index 7ceef9578..f13e2fc07 100644 --- a/docs/llms.txt +++ b/docs/llms.txt @@ -225,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. 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. + + From d2b8432b772a5923ab5ba145cf1ae2a9f8b1c3f2 Mon Sep 17 00:00:00 2001 From: harsh-mem0 Date: Fri, 30 Oct 2026 17:35:20 -0400 Subject: [PATCH 57/61] fix(ts): never re-create a deleted memory when update races delete (#7788) --- mem0-ts/src/oss/src/memory/index.ts | 10 +- mem0-ts/src/oss/src/tests/chroma.test.ts | 35 +++- mem0-ts/src/oss/src/tests/mongodb.test.ts | 30 +++- mem0-ts/src/oss/src/tests/pinecone.test.ts | 32 +++- .../oss/src/vector_stores/azure_ai_search.ts | 8 +- .../src/oss/src/vector_stores/azure_mysql.ts | 8 +- mem0-ts/src/oss/src/vector_stores/base.ts | 3 +- mem0-ts/src/oss/src/vector_stores/chroma.ts | 13 +- .../src/oss/src/vector_stores/databricks.ts | 9 +- .../oss/src/vector_stores/elasticsearch.ts | 11 +- mem0-ts/src/oss/src/vector_stores/memory.ts | 5 +- mem0-ts/src/oss/src/vector_stores/mongodb.ts | 5 +- .../src/vector_stores/neptune_analytics.ts | 7 +- .../src/oss/src/vector_stores/opensearch.ts | 13 +- mem0-ts/src/oss/src/vector_stores/oracledb.ts | 6 +- mem0-ts/src/oss/src/vector_stores/pgvector.ts | 5 +- mem0-ts/src/oss/src/vector_stores/pinecone.ts | 7 +- mem0-ts/src/oss/src/vector_stores/qdrant.ts | 19 +- mem0-ts/src/oss/src/vector_stores/redis.ts | 43 ++++- .../oss/src/vector_stores/upstash_vector.ts | 12 +- mem0-ts/src/oss/src/vector_stores/valkey.ts | 47 ++++- mem0-ts/src/oss/src/vector_stores/weaviate.ts | 11 +- .../src/oss/tests/elasticsearch.unit.test.ts | 33 +++- mem0-ts/src/oss/tests/memory.crud.test.ts | 24 +++ mem0-ts/src/oss/tests/opensearch.unit.test.ts | 40 +++++ mem0-ts/src/oss/tests/oracledb.unit.test.ts | 38 ++++ mem0-ts/src/oss/tests/pgvector.unit.test.ts | 25 +++ .../oss/tests/qdrant-keyword-search.test.ts | 22 +++ mem0-ts/src/oss/tests/redis.unit.test.ts | 125 +++++++++++-- .../src/oss/tests/upstash_vector.unit.test.ts | 44 ++++- mem0-ts/src/oss/tests/valkey.test.ts | 136 ++++++++++++++ .../src/oss/tests/vector-store.unit.test.ts | 11 +- .../oss/tests/vector-stores-compat.test.ts | 169 +++++++++++++++++- 33 files changed, 934 insertions(+), 72 deletions(-) diff --git a/mem0-ts/src/oss/src/memory/index.ts b/mem0-ts/src/oss/src/memory/index.ts index 42f3ca22e..00fdc7d97 100644 --- a/mem0-ts/src/oss/src/memory/index.ts +++ b/mem0-ts/src/oss/src/memory/index.ts @@ -1990,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 b7f2c2f69..1bd4d9a2c 100644 --- a/mem0-ts/src/oss/src/vector_stores/pgvector.ts +++ b/mem0-ts/src/oss/src/vector_stores/pgvector.ts @@ -464,10 +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 @@ -475,6 +475,7 @@ export class PGVector implements VectorStore { `, [vectorStr, payload, vectorId], ); + return (result.rowCount ?? 0) > 0; } async delete(vectorId: string): Promise { 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/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/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.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/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

g^LXpZ(>mMl&Zt4aILyYW@oXBXSPiN#XL@JN<(@et=SOkpeN$QdvzmhN)9G$h2b3`tc)1bFbd+IKF}~+{#A% zJ}T(6s9WOP4wYN}NaL))3d%(TLCSDC>It`iVe{OF%*~eq_(q z4!YjguU--qM{d4lqrQ{9ZD1z>Rx5ky{!5{>S!Yte?IN5*lnfTEye2u>+VUjZbdkAz zm{g*OENdk%BiS~=MZ7dxQB7XCv_9rg$v?pa6OBsrhrqY*GAZKwa#RJvHJb$`oYv<^ zRu{(Qf*81kTJAM-2Y>dKdiH$l|8dVD6m5-=7-AiWa>p-NnxWrTbDKkiF9Yb9d?T0^6t+R8_6Of5F^GFIRJ$WAp)` zJoEYd{(iAouSR;c$KG&Ld0VC27O`z%(j3O42isuq(7R`I*w_Jqe!qA#xt!~NU(U2l zeGSXc^?F{67sm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