The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
chore(memory): remove the bundled mem0 provider (moved to the plugin catalog)
teknium1781334eea4b9
diff --git a/CONTRIBUTING.es.md b/CONTRIBUTING.es.mdindex 3f42e663d3d..71d18122e68 100644--- a/CONTRIBUTING.es.md+++ b/CONTRIBUTING.es.md@@ -51,7 +51,7 @@ Si tu habilidad es especializada, contribuida por la comunidad o de nicho, es me## Proveedores de Memoria: Publicar como Plugin Independiente-**Ya no aceptamos nuevos proveedores de memoria en este repositorio.** El conjunto de proveedores integrados en `plugins/memory/` (mem0, byterover, holographic, openviking, retaindb) está cerrado, y los antiguos proveedores integrados hindsight, honcho y supermemory ahora se distribuyen desde el catálogo de plugins. Si quieres añadir un nuevo backend de memoria, publícalo como un **repositorio de plugin independiente** que los usuarios instalen en `~/.hermes/plugins/` (o a través de un entry point de pip).+**Ya no aceptamos nuevos proveedores de memoria en este repositorio.** El conjunto de proveedores integrados en `plugins/memory/` (byterover, holographic, openviking, retaindb) está cerrado, y los antiguos proveedores integrados hindsight, honcho, supermemory y mem0 ahora se distribuyen desde el catálogo de plugins. Si quieres añadir un nuevo backend de memoria, publícalo como un **repositorio de plugin independiente** que los usuarios instalen en `~/.hermes/plugins/` (o a través de un entry point de pip).Los plugins de memoria independientes:diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex f28f856e419..ec954949cef 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -69,7 +69,7 @@ If your skill is specialized, community-contributed, or niche, it's better suite## Memory Providers: Ship as a Standalone Plugin-**We are no longer accepting new memory providers into this repo.** The set of built-in providers under `plugins/memory/` (mem0, byterover, holographic, openviking, retaindb) is closed, and the former in-tree providers hindsight, honcho and supermemory now ship from the plugin catalog. If you want to add a new memory backend, publish it as a **standalone plugin repo** that users install into `~/.hermes/plugins/` (or via a pip entry point).+**We are no longer accepting new memory providers into this repo.** The set of built-in providers under `plugins/memory/` (byterover, holographic, openviking, retaindb) is closed, and the former in-tree providers hindsight, honcho, supermemory and mem0 now ship from the plugin catalog. If you want to add a new memory backend, publish it as a **standalone plugin repo** that users install into `~/.hermes/plugins/` (or via a pip entry point).Standalone memory plugins:diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex a25bcc9ee12..94baa87e36e 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -1321,8 +1321,8 @@ DEFAULT_CONFIG = {# Periodic built-in memory review; 0 when an external provider auto-extracts."nudge_interval": 10,# External memory provider plugin (empty = built-in only); only ONE at a time: "openviking",- # "mem0", "holographic", "retaindb", "byterover", or a catalog-installed one ("honcho",- # "hindsight", "supermemory").+ # "holographic", "retaindb", "byterover", or a catalog-installed one ("honcho", "hindsight",+ # "supermemory", "mem0")."provider": "",},# Subagent delegation — override the provider:model used by delegate_task so children run on adiff --git a/hermes_cli/doctor_state.py b/hermes_cli/doctor_state.pyindex cb4db53ee1c..cd049b18608 100644--- a/hermes_cli/doctor_state.py+++ b/hermes_cli/doctor_state.py@@ -579,26 +579,13 @@ def _check_skills_hub(should_fix: bool, f: Finding) -> None:("No GITHUB_TOKEN", f"(60 req/hr rate limit — set in {_DHH}/.env for better rates)"))-def _memory_provider_mem0(issues: list) -> None:- from plugins.memory import import_provider_module- mem0_cfg = import_provider_module("mem0")._load_config()- if mem0_cfg.get("api_key", ""):- check_ok("Mem0 API key configured")- check_info(f"user_id={mem0_cfg.get('user_id', '?')} agent_id={mem0_cfg.get('agent_id', '?')}")- else:- _fail_and_issue("Mem0 API key not set", "(set MEM0_API_KEY in .env or run hermes memory setup)",- "Mem0 is set as memory provider but API key is missing", issues)---# provider -> (checker, ImportError row, ImportError issue, label for "check failed")-_MEMORY_PROVIDER_CHECKS = {- "mem0": (_memory_provider_mem0, ("Mem0 plugin not loadable", "run hermes memory setup"),- "Mem0 dependencies missing — run hermes memory setup, then restart Hermes", "Mem0"),-}+# provider -> (checker, ImportError row, ImportError issue, label for "check failed"); every provider+# still bundled or catalog-installed uses the generic check.+_MEMORY_PROVIDER_CHECKS: dict = {}def _memory_provider_generic(name: str) -> None:- """Generic check for every other memory provider (openviking, honcho, hindsight, ...)."""+ """Generic check for every memory provider (openviking, mem0, honcho, hindsight, ...)."""from plugins.memory import load_memory_provider_provider = load_memory_provider(name)if _provider and _provider.is_available():diff --git a/hermes_cli/subcommands/memory.py b/hermes_cli/subcommands/memory.pyindex ca3ded777f2..2ecba0e2600 100644--- a/hermes_cli/subcommands/memory.py+++ b/hermes_cli/subcommands/memory.py@@ -12,9 +12,9 @@ def build_memory_parser(subparsers, *, cmd_memory: Callable) -> None:memory_parser = subparsers.add_parser("memory", help="Configure external memory provider",description="Set up and manage external memory provider plugins.\n\n"- "Bundled providers: openviking, mem0, holographic, retaindb,\n"+ "Bundled providers: openviking, holographic, retaindb,\n""byterover. Catalog providers (e.g. honcho, hindsight,\n"- "supermemory): hermes plugins install <name>.\n\n"+ "supermemory, mem0): hermes plugins install <name>.\n\n""Only one external provider can be active at a time.\n""Built-in memory (MEMORY.md/USER.md) is always active.")memory_sub = memory_parser.add_subparsers(dest="memory_command")diff --git a/locales/af.yaml b/locales/af.yamlindex d64df57334a..a3e0e38350d 100644--- a/locales/af.yaml+++ b/locales/af.yaml@@ -3674,7 +3674,7 @@ tips:t197: "Trajekstoor (--save-trajectories) vang volledige gereedskapsgebruik-spore vas vir modelopleiding."t198: "Drie plugin-tipes: algemeen (gereedskap/hooks), geheueverskaffers en konteksenjins."t199: "hermes plugins install owner/repo installeer plugins direk vanaf GitHub."- t200: "Eksterne geheueverskaffers: OpenViking, Mem0 saamgebundel; Honcho, Hindsight en meer via hermes plugins install."+ t200: "Eksterne geheueverskaffers: OpenViking saamgebundel; Honcho, Hindsight, Mem0 en meer via hermes plugins install."t201: "Plugin-hooks sluit pre/post_tool_call, pre/post_llm_call en transform_terminal_output vir uitvoer-kanonisering in."t202: "Prompt-kasing (Anthropic) verminder koste deur gekasde stelselprompt-voorvoegsels te hergebruik."t203: "Die agent genereer sessietitels outomaties in 'n agtergronddraad — nul impak op vertraging."diff --git a/locales/ar.yaml b/locales/ar.yamlindex 905ba7ec77c..d04319da91e 100644--- a/locales/ar.yaml+++ b/locales/ar.yaml@@ -3674,7 +3674,7 @@ tips:t197: "يسجّل حفظ المسارات (--save-trajectories) آثار استخدام الأدوات كاملةً لتدريب النماذج."t198: "ثلاثة أنواع من الإضافات: عامة (أدوات/خطافات)، ومزوّدو الذاكرة، ومحرّكات السياق."t199: "يثبّت hermes plugins install owner/repo الإضافات مباشرة من GitHub."- t200: "مزوّدو الذاكرة الخارجيون: OpenViking وMem0 مضمّنون؛ وHoncho وHindsight وغيرهما عبر hermes plugins install."+ t200: "مزوّدو الذاكرة الخارجيون: OpenViking مضمّن؛ وHoncho وHindsight وMem0 وغيرهم عبر hermes plugins install."t201: "تشمل خطافات الإضافات pre/post_tool_call وpre/post_llm_call وtransform_terminal_output لتوحيد شكل المخرجات."t202: "يقلّل تخزين المطالبات مؤقتًا (Anthropic) التكاليف بإعادة استخدام بادئات موجّه النظام المخزّنة."t203: "يولّد الوكيل عناوين الجلسات تلقائيًا في خيط خلفي — دون أي تأثير على زمن الاستجابة."diff --git a/locales/de.yaml b/locales/de.yamlindex 36fb51fdfd9..24065a26cf3 100644--- a/locales/de.yaml+++ b/locales/de.yaml@@ -3674,7 +3674,7 @@ tips:t197: "Das Speichern von Trajektorien (--save-trajectories) erfasst vollständige Tool-Nutzungsprotokolle für das Modelltraining."t198: "Drei Plugin-Typen: allgemein (Tools/Hooks), Memory-Anbieter und Kontext-Engines."t199: "hermes plugins install owner/repo installiert Plugins direkt von GitHub."- t200: "Externe Memory-Anbieter: OpenViking, Mem0 sind mitgeliefert; Honcho, Hindsight und weitere über hermes plugins install."+ t200: "Externe Memory-Anbieter: OpenViking ist mitgeliefert; Honcho, Hindsight, Mem0 und weitere über hermes plugins install."t201: "Plugin-Hooks umfassen pre/post_tool_call, pre/post_llm_call und transform_terminal_output zur Kanonisierung von Ausgaben."t202: "Prompt-Caching (Anthropic) senkt die Kosten, indem zwischengespeicherte Präfixe des System-Prompts wiederverwendet werden."t203: "Der Agent erzeugt Sitzungstitel automatisch in einem Hintergrund-Thread — ohne Auswirkung auf die Latenz."diff --git a/locales/en.yaml b/locales/en.yamlindex dbb8972a633..b72265e47e9 100644--- a/locales/en.yaml+++ b/locales/en.yaml@@ -3788,7 +3788,7 @@ tips:t197: "Trajectory saving (--save-trajectories) captures full tool-use traces for model training."t198: "Three plugin types: general (tools/hooks), memory providers, and context engines."t199: "hermes plugins install owner/repo installs plugins directly from GitHub."- t200: "External memory providers: OpenViking, Mem0 bundled; Honcho, Hindsight and more via hermes plugins install."+ t200: "External memory providers: OpenViking bundled; Honcho, Hindsight, Mem0 and more via hermes plugins install."t201: "Plugin hooks include pre/post_tool_call, pre/post_llm_call, and transform_terminal_output for output canonicalization."t202: "Prompt caching (Anthropic) reduces costs by reusing cached system prompt prefixes."t203: "The agent auto-generates session titles in a background thread — zero latency impact."diff --git a/locales/es.yaml b/locales/es.yamlindex 3120e4a4e0a..10c07384d0d 100644--- a/locales/es.yaml+++ b/locales/es.yaml@@ -3674,7 +3674,7 @@ tips:t197: "El guardado de trayectorias (--save-trajectories) captura trazas completas de uso de herramientas para entrenar modelos."t198: "Tres tipos de plugin: generales (herramientas/hooks), proveedores de memoria y motores de contexto."t199: "hermes plugins install owner/repo instala plugins directamente desde GitHub."- t200: "Proveedores de memoria externos: OpenViking y Mem0 vienen incluidos; Honcho, Hindsight y otros vía hermes plugins install."+ t200: "Proveedores de memoria externos: OpenViking viene incluido; Honcho, Hindsight, Mem0 y otros vía hermes plugins install."t201: "Los hooks de plugin incluyen pre/post_tool_call, pre/post_llm_call y transform_terminal_output para canonicalizar la salida."t202: "El caché de prompts (Anthropic) reduce costos reutilizando prefijos del prompt del sistema ya cacheados."t203: "El agente genera los títulos de sesión automáticamente en un hilo en segundo plano: sin impacto en la latencia."diff --git a/locales/fr.yaml b/locales/fr.yamlindex f8cfc98230a..f8db3779d0b 100644--- a/locales/fr.yaml+++ b/locales/fr.yaml@@ -3999,7 +3999,7 @@ tips:t197: "L'enregistrement des trajectoires (--save-trajectories) capture les traces complètes d'utilisation des outils pour l'entraînement de modèles."t198: "Trois types de plugins : généraux (outils/hooks), fournisseurs de mémoire et moteurs de contexte."t199: "hermes plugins install owner/repo installe des plugins directement depuis GitHub."- t200: "Fournisseurs de mémoire externes : OpenViking et Mem0 intégrés ; Honcho, Hindsight et d'autres via hermes plugins install."+ t200: "Fournisseurs de mémoire externes : OpenViking intégré ; Honcho, Hindsight, Mem0 et d'autres via hermes plugins install."t201: "Les hooks de plugin incluent pre/post_tool_call, pre/post_llm_call et transform_terminal_output pour normaliser la sortie."t202: "Le cache de prompt (Anthropic) réduit les coûts en réutilisant les préfixes de prompt système déjà mis en cache."t203: "L'agent génère les titres de session dans un thread d'arrière-plan — aucun impact sur la latence."diff --git a/locales/ga.yaml b/locales/ga.yamlindex 683e4c0375d..4e8df6e69e1 100644--- a/locales/ga.yaml+++ b/locales/ga.yaml@@ -3674,7 +3674,7 @@ tips:t197: "Gabhann sábháil trajectóirí (--save-trajectories) rianta iomlána úsáide uirlisí le haghaidh oiliúna samhlacha."t198: "Trí chineál breiseáin: ginearálta (uirlisí/crúcaí), soláthraithe cuimhne, agus innill chomhthéacs."t199: "Suiteálann hermes plugins install owner/repo breiseáin go díreach ó GitHub."- t200: "Soláthraithe cuimhne seachtracha: OpenViking, Mem0 cuachta; Honcho, Hindsight agus tuilleadh trí hermes plugins install."+ t200: "Soláthraithe cuimhne seachtracha: OpenViking cuachta; Honcho, Hindsight, Mem0 agus tuilleadh trí hermes plugins install."t201: "I measc crúcaí breiseán tá pre/post_tool_call, pre/post_llm_call, agus transform_terminal_output le haghaidh canónú aschuir."t202: "Laghdaíonn taisceadh leideanna (Anthropic) costais trí réimíreanna taiscthe leid an chórais a athúsáid."t203: "Gineann an gníomhaire teidil seisiún go huathoibríoch i snáithe cúlra — gan aon tionchar ar aga freagartha."diff --git a/locales/hu.yaml b/locales/hu.yamlindex fa33a15d3a7..f405844bada 100644--- a/locales/hu.yaml+++ b/locales/hu.yaml@@ -3691,7 +3691,7 @@ tips:t197: "A trajektóriamentés (--save-trajectories) rögzíti a teljes eszközhasználati nyomokat a modelltanításhoz."t198: "Három plugintípus van: általános (eszközök/hookok), memóriaszolgáltatók és kontextusmotorok."t199: "A hermes plugins install owner/repo közvetlenül a GitHubról telepít plugint."- t200: "Külső memóriaszolgáltatók: az OpenViking és a Mem0 beépített; a Honcho, a Hindsight és mások a hermes plugins install parancson keresztül."+ t200: "Külső memóriaszolgáltatók: az OpenViking beépített; a Honcho, a Hindsight, a Mem0 és mások a hermes plugins install parancson keresztül."t201: "A plugin hookok közé tartozik a pre/post_tool_call, a pre/post_llm_call és a transform_terminal_output a kimenet egységesítésére."t202: "A prompt-gyorsítótárazás (Anthropic) a rendszerprompt gyorsítótárazott előtagjainak újrahasznosításával csökkenti a költségeket."t203: "Az ügynök háttérszálon generálja a munkamenetek címét – nincs hatása a késleltetésre."diff --git a/locales/it.yaml b/locales/it.yamlindex 5f432336958..5d79381abf2 100644--- a/locales/it.yaml+++ b/locales/it.yaml@@ -3674,7 +3674,7 @@ tips:t197: "Il salvataggio delle traiettorie (--save-trajectories) cattura tracce complete dell'uso degli strumenti per l'addestramento dei modelli."t198: "Tre tipi di plugin: generali (strumenti/hook), provider di memoria e motori di contesto."t199: "hermes plugins install owner/repo installa i plugin direttamente da GitHub."- t200: "Provider di memoria esterni: OpenViking e Mem0 sono inclusi; Honcho, Hindsight e altri tramite hermes plugins install."+ t200: "Provider di memoria esterni: OpenViking è incluso; Honcho, Hindsight, Mem0 e altri tramite hermes plugins install."t201: "Gli hook dei plugin includono pre/post_tool_call, pre/post_llm_call e transform_terminal_output per la canonicalizzazione dell'output."t202: "Il prompt caching (Anthropic) riduce i costi riutilizzando i prefissi del prompt di sistema in cache."t203: "L'agente genera automaticamente i titoli delle sessioni in un thread in background — nessun impatto sulla latenza."diff --git a/locales/ja.yaml b/locales/ja.yamlindex e6a557b7b48..9bd259d76ab 100644--- a/locales/ja.yaml+++ b/locales/ja.yaml@@ -3674,7 +3674,7 @@ tips:t197: "トラジェクトリ保存(--save-trajectories)は、モデル学習用にツール使用の完全なトレースを記録します。"t198: "プラグインには 3 種類あります。汎用(ツール/フック)、メモリプロバイダー、コンテキストエンジンです。"t199: "hermes plugins install owner/repo で GitHub から直接プラグインをインストールできます。"- t200: "外部メモリプロバイダーとして OpenViking、Mem0 が同梱されており、Honcho、Hindsight などは hermes plugins install で追加できます。"+ t200: "外部メモリプロバイダーとして OpenViking が同梱されており、Honcho、Hindsight、Mem0 などは hermes plugins install で追加できます。"t201: "プラグインフックには pre/post_tool_call、pre/post_llm_call、出力の正規化用の transform_terminal_output などがあります。"t202: "プロンプトキャッシュ(Anthropic)は、キャッシュ済みのシステムプロンプトのプレフィックスを再利用してコストを削減します。"t203: "エージェントはセッションタイトルをバックグラウンドスレッドで自動生成するため、レイテンシへの影響はゼロです。"diff --git a/locales/ko.yaml b/locales/ko.yamlindex f312670010a..a878ff3afa0 100644--- a/locales/ko.yaml+++ b/locales/ko.yaml@@ -3674,7 +3674,7 @@ tips:t197: "궤적 저장(--save-trajectories)은 모델 학습용으로 도구 사용 전체 기록을 남겨요."t198: "플러그인은 세 종류예요: 일반(도구/훅), 메모리 제공자, 컨텍스트 엔진."t199: "hermes plugins install owner/repo로 GitHub에서 직접 플러그인을 설치할 수 있어요."- t200: "외부 메모리 제공자: OpenViking, Mem0은 기본 포함이고, Honcho, Hindsight 등은 hermes plugins install로 설치해요."+ t200: "외부 메모리 제공자: OpenViking은 기본 포함이고, Honcho, Hindsight, Mem0 등은 hermes plugins install로 설치해요."t201: "플러그인 훅에는 pre/post_tool_call, pre/post_llm_call, 그리고 출력 정규화용 transform_terminal_output이 있어요."t202: "프롬프트 캐싱(Anthropic)은 캐시된 시스템 프롬프트 접두부를 재사용해 비용을 줄여요."t203: "에이전트는 백그라운드 스레드에서 세션 제목을 자동 생성해요 — 지연 시간에 영향이 없어요."diff --git a/locales/pt.yaml b/locales/pt.yamlindex fdecc37b062..c65687beb9e 100644--- a/locales/pt.yaml+++ b/locales/pt.yaml@@ -3674,7 +3674,7 @@ tips:t197: "O salvamento de trajetórias (--save-trajectories) captura rastros completos de uso de ferramentas para treinar modelos."t198: "Três tipos de plugin: geral (ferramentas/hooks), fornecedores de memória e motores de contexto."t199: "hermes plugins install owner/repo instala plugins diretamente do GitHub."- t200: "Fornecedores de memória externos: OpenViking e Mem0 incluídos; Honcho, Hindsight e outros via hermes plugins install."+ t200: "Fornecedores de memória externos: OpenViking incluído; Honcho, Hindsight, Mem0 e outros via hermes plugins install."t201: "Os hooks de plugin incluem pre/post_tool_call, pre/post_llm_call e transform_terminal_output para canonicalizar a saída."t202: "O cache de prompt (Anthropic) reduz custos ao reutilizar prefixos de prompt do sistema em cache."t203: "O agente gera títulos de sessão automaticamente em um tópico em segundo plano — sem impacto na latência."diff --git a/locales/ru.yaml b/locales/ru.yamlindex faf6f4a4505..4c4d7a675d3 100644--- a/locales/ru.yaml+++ b/locales/ru.yaml@@ -3674,7 +3674,7 @@ tips:t197: "Сохранение траекторий (--save-trajectories) записывает полные трассы использования инструментов для обучения моделей."t198: "Три типа плагинов: общие (инструменты/хуки), провайдеры памяти и движки контекста."t199: "hermes plugins install owner/repo устанавливает плагины напрямую с GitHub."- t200: "Внешние провайдеры памяти: OpenViking, Mem0 встроены; Honcho, Hindsight и другие — через hermes plugins install."+ t200: "Внешние провайдеры памяти: OpenViking встроен; Honcho, Hindsight, Mem0 и другие — через hermes plugins install."t201: "Хуки плагинов включают pre/post_tool_call, pre/post_llm_call и transform_terminal_output для нормализации вывода."t202: "Кэширование промптов (Anthropic) снижает стоимость за счёт повторного использования кэшированных префиксов системного промпта."t203: "Агент генерирует названия сеансов в фоновом потоке — без влияния на задержку."diff --git a/locales/tr.yaml b/locales/tr.yamlindex 22e2a8381c3..5c8a4c6e1c6 100644--- a/locales/tr.yaml+++ b/locales/tr.yaml@@ -3674,7 +3674,7 @@ tips:t197: "Yörünge kaydı (--save-trajectories), model eğitimi için tam araç kullanım izlerini yakalar."t198: "Üç eklenti türü: genel (araçlar/kancalar), bellek sağlayıcıları ve bağlam motorları."t199: "hermes plugins install owner/repo, eklentileri doğrudan GitHub'dan kurar."- t200: "Harici bellek sağlayıcıları: OpenViking, Mem0 dahili gelir; Honcho, Hindsight ve diğerleri hermes plugins install ile kurulur."+ t200: "Harici bellek sağlayıcıları: OpenViking dahili gelir; Honcho, Hindsight, Mem0 ve diğerleri hermes plugins install ile kurulur."t201: "Eklenti kancaları arasında pre/post_tool_call, pre/post_llm_call ve çıktı normalleştirme için transform_terminal_output bulunur."t202: "İstem önbelleği (Anthropic), önbelleğe alınmış sistem istemi öneklerini yeniden kullanarak maliyetleri düşürür."t203: "Ajan oturum başlıklarını arka plan iş parçacığında otomatik oluşturur — gecikmeye sıfır etki."diff --git a/locales/uk.yaml b/locales/uk.yamlindex 0bcb66940bf..278a90dd0a8 100644--- a/locales/uk.yaml+++ b/locales/uk.yaml@@ -3674,7 +3674,7 @@ tips:t197: "Збереження траєкторій (--save-trajectories) фіксує повні сліди використання інструментів для навчання моделей."t198: "Три типи плагінів: загальні (інструменти та хуки), провайдери пам'яті та контекстні рушії."t199: "hermes plugins install owner/repo встановлює плагіни безпосередньо з GitHub."- t200: "Зовнішні провайдери пам'яті: OpenViking, Mem0 вбудовані; Honcho, Hindsight та інші — через hermes plugins install."+ t200: "Зовнішні провайдери пам'яті: OpenViking вбудований; Honcho, Hindsight, Mem0 та інші — через hermes plugins install."t201: "Хуки плагінів включають pre/post_tool_call, pre/post_llm_call і transform_terminal_output для канонізації виводу."t202: "Кешування промптів (Anthropic) знижує витрати, повторно використовуючи кешовані префікси системного промпту."t203: "Агент генерує назви сеансів у фоновому потоці — без жодного впливу на затримку."diff --git a/locales/zh-hant.yaml b/locales/zh-hant.yamlindex 3c0b32f0cf3..4a576d40ad6 100644--- a/locales/zh-hant.yaml+++ b/locales/zh-hant.yaml@@ -3674,7 +3674,7 @@ tips:t197: "軌跡儲存(--save-trajectories)會記錄完整的工具使用軌跡,供模型訓練使用。"t198: "外掛有三種類型:一般(工具/hook)、記憶提供方,以及上下文引擎。"t199: "hermes plugins install owner/repo 可直接從 GitHub 安裝外掛。"- t200: "外部記憶提供方:內建 OpenViking、Mem0;Honcho、Hindsight 等更多可透過 hermes plugins install 安裝。"+ t200: "外部記憶提供方:內建 OpenViking;Honcho、Hindsight、Mem0 等更多可透過 hermes plugins install 安裝。"t201: "外掛 hook 包含 pre/post_tool_call、pre/post_llm_call,以及用來標準化輸出的 transform_terminal_output。"t202: "提示快取(Anthropic)透過重用已快取的系統提示詞前綴來降低費用。"t203: "代理會在背景執行緒中自動產生工作階段標題 — 完全不影響延遲。"diff --git a/locales/zh.yaml b/locales/zh.yamlindex 9c6fd4d6616..1b37a2d48ec 100644--- a/locales/zh.yaml+++ b/locales/zh.yaml@@ -3674,7 +3674,7 @@ tips:t197: "轨迹保存(--save-trajectories)会记录完整的工具调用轨迹,可用于模型训练。"t198: "插件有三种类型:通用插件(工具/钩子)、记忆提供方和上下文引擎。"t199: "hermes plugins install owner/repo 可直接从 GitHub 安装插件。"- t200: "外部记忆提供方:OpenViking、Mem0 已内置;Honcho、Hindsight 等可通过 hermes plugins install 安装。"+ t200: "外部记忆提供方:OpenViking 已内置;Honcho、Hindsight、Mem0 等可通过 hermes plugins install 安装。"t201: "插件钩子包括 pre/post_tool_call、pre/post_llm_call,以及用于规范化输出的 transform_terminal_output。"t202: "提示词缓存(Anthropic)通过复用已缓存的系统提示词前缀来降低成本。"t203: "代理会在后台线程中自动生成会话标题——对延迟零影响。"diff --git a/plugins/AGENTS.md b/plugins/AGENTS.mdindex 97e7437812a..1bd7953d7a5 100644--- a/plugins/AGENTS.md+++ b/plugins/AGENTS.md@@ -16,9 +16,9 @@ command. A hook with no concrete consumer is speculative infrastructure and is r## What may live in this tree (policy)-- **No new in-tree memory providers (May 2026).** `plugins/memory/` is closed (mem0, byterover,- holographic, openviking, retaindb stay; bug fixes welcome). hindsight (Sep 2026), honcho and- supermemory (Oct 2026) moved to the plugin catalog — `plugin-catalog/<name>.yaml`, auto-installed by+- **No new in-tree memory providers (May 2026).** `plugins/memory/` is closed (byterover,+ holographic, openviking, retaindb stay; bug fixes welcome). hindsight (Sep 2026), honcho,+ supermemory and mem0 (Oct 2026) moved to the plugin catalog — `plugin-catalog/<name>.yaml`, auto-installed by`hermes_cli/memory_provider_migration.py` for homes still configured for them. Host-side code acatalog provider still relies on (the `honcho_host_block` config storage kind, profile clone /rename / update-sync hooks) resolves the provider's modules throughdiff --git a/plugins/memory/mem0/README.md b/plugins/memory/mem0/README.mddeleted file mode 100644index 19fa9809742..00000000000--- a/plugins/memory/mem0/README.md+++ /dev/null@@ -1,188 +0,0 @@-# Mem0 Memory Provider--Server-side LLM fact extraction with semantic search and hybrid multi-signal retrieval via the Mem0 Platform v3 API.--## Requirements--- The `mem0ai` SDK, prepared through PM by `hermes memory setup` when you select Mem0. Restart Hermes after preparation; do not install into its selected environment with pip.-- Mem0 API key from [app.mem0.ai](https://app.mem0.ai)--## Setup--```bash-hermes memory setup # select "mem0"-```--Or manually:-```bash-hermes config set memory.provider mem0-echo "MEM0_API_KEY=your-key" >> ~/.hermes/.env-```--## Config--Behavioral settings live in `$HERMES_HOME/mem0.json` (set them via `hermes memory setup`). Only the secret `MEM0_API_KEY` belongs in `~/.hermes/.env`.--| Key | Default | Description |-|-----|---------|-------------|-| `mode` | `platform` | `platform` (Mem0 Cloud) or `oss` (self-managed, in-process) |-| `host` | — | Self-hosted Mem0 server URL (the Docker dashboard). When set, connects over HTTP with `X-API-Key`. Don't combine with `mode: oss` |-| `user_id` | `hermes-user` | User identifier on Mem0 |-| `agent_id` | `hermes` | Agent identifier |-| `rerank` | `false` | Rerank search results for relevance (platform mode only) |-| `sync_max_chars` | `450` | Per-message character cap applied before each turn is sent for fact extraction (cut at the last sentence boundary). Default fits 512-token embedders; raise it (e.g. `6000`) for 8k-token embedders such as `text-embedding-3-small`, `jina-embeddings-v3`, `bge-m3` |--The plugin has three connection modes:--- **Platform** — Mem0's hosted cloud (`api.mem0.ai`). Set `MEM0_API_KEY`. (default)-- **Self-hosted dashboard** — a Mem0 server you run yourself via Docker. Set `host`. See below.-- **OSS** — run Mem0 in-process with your own LLM + vector store. Set `mode: oss`. See below.--## Self-Hosted Dashboard (Server) Mode--Connect the plugin to a standalone Mem0 server you run yourself — the Docker-shipped Mem0 dashboard/server with its own REST API. Unlike OSS mode (which runs `mem0ai` in-process with your own vector store), here the plugin just talks HTTP to your server.--1. Run the Mem0 server (FastAPI + pgvector) from its Docker image and note its URL and `ADMIN_API_KEY`.-2. Point the plugin at it — via the setup wizard:- ```bash- hermes memory setup # select "mem0" → "Self-hosted server"- # Or non-interactive:- hermes memory setup mem0 --mode selfhosted --host http://localhost:8888 --api-key your-admin-api-key- ```- or via env vars:- ```bash- echo "MEM0_HOST=http://localhost:8888" >> ~/.hermes/.env- echo "MEM0_API_KEY=your-admin-api-key" >> ~/.hermes/.env- ```- or in `$HERMES_HOME/mem0.json`:- ```json- {- "host": "http://localhost:8888",- "api_key": "your-admin-api-key"- }- ```-3. 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. `api_key` is optional — omit it only for servers running with `AUTH_DISABLED`.--> Setting `host` routes to the self-hosted server automatically. Don't set `mode: oss` — OSS takes precedence and ignores `host`.--## OSS (Self-Hosted) Mode--Run Mem0 locally with your own LLM, embedder, and vector store. This is the in-process SDK mode. To instead connect to a Mem0 server you run via Docker, see [Self-Hosted Dashboard (Server) Mode](#self-hosted-dashboard-server-mode) above.--### Interactive Setup--```bash-hermes memory setup-# Select "mem0" → "Open Source (self-hosted)"-# Follow prompts for LLM, embedder, and vector store-```--### Agent-Driven Setup (Flags)--```bash-hermes memory setup mem0 --mode oss \- --oss-llm openai --oss-llm-key sk-... \- --oss-vector qdrant-```--### Supported Providers--| Component | Providers |-|-----------|-----------|-| LLM | openai, ollama |-| Embedder | openai, ollama |-| Vector Store | qdrant (local/server), pgvector |--### Flags Reference--| Flag | Description |-|------|-------------|-| `--mode` | `platform` or `oss` |-| `--oss-llm` | LLM provider (default: openai) |-| `--oss-llm-key` | LLM API key |-| `--oss-embedder` | Embedder provider (default: openai) |-| `--oss-vector` | Vector store (default: qdrant) |-| `--oss-vector-path` | Qdrant local path |-| `--user-id` | User identifier |--## Switching Modes--### Platform to OSS--```bash-hermes memory setup mem0 --mode oss --oss-llm-key sk-...-```--Or edit `$HERMES_HOME/mem0.json` directly:-```json-{- "mode": "oss",- "oss": {- "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"}}- }-}-```--### OSS to Platform--```bash-hermes memory setup mem0 --mode platform --api-key sk-...-```--### Dry Run (preview without writing)--```bash-hermes memory setup mem0 --mode oss --oss-llm-key sk-... --dry-run-```--## Tools--| Tool | Description |-|------|-------------|-| `mem0_search` | Semantic search by meaning |-| `mem0_add` | Store a fact verbatim (no LLM extraction) |-| `mem0_update` | Update a memory's text by ID |-| `mem0_delete` | Delete a memory by ID |--## Troubleshooting--### "Mem0 temporarily unavailable"--Circuit breaker tripped after 5 consecutive failures. Resets after 2 minutes.--- **Platform mode**: Check API key and internet connectivity.-- **OSS mode**: Check that your vector store (qdrant/pgvector) is running.--### OSS: Qdrant connection refused--```bash-# If using local Qdrant, check the storage path is writable:-ls -la ~/.hermes/mem0_qdrant--# If using Qdrant server, check it's reachable:-curl http://localhost:6333/healthz-```--### OSS: PGVector connection refused--```bash-# Verify PostgreSQL is running and accepting connections:-pg_isready -h localhost -p 5432-```--### OSS: Ollama not reachable--```bash-# Check Ollama is running:-curl http://localhost:11434/api/tags-```--### Memories not appearing--- `mem0_add` stores verbatim (no extraction). Use `sync_turn` for LLM extraction.-- Search uses semantic matching — try broader queries.-- Check `user_id` matches between sessions (`$HERMES_HOME/mem0.json`).diff --git a/plugins/memory/mem0/__init__.py b/plugins/memory/mem0/__init__.pydeleted file mode 100644index c329136246f..00000000000--- a/plugins/memory/mem0/__init__.py+++ /dev/null@@ -1,393 +0,0 @@-"""Mem0 memory plugin — MemoryProvider interface.--Server-side fact extraction and semantic search via the Mem0 Platform API (cloud), a-self-hosted Mem0 server (MEM0_HOST, HTTP), or OSS Memory. Secrets live in $HERMES_HOME/.env-(MEM0_API_KEY, MEM0_HOST); settings in $HERMES_HOME/mem0.json via `hermes memory setup`:-mode ("platform"|"oss"), host, user_id (canonical id across gateways; unset → gateway-native-id), agent_id. MEM0_* env vars remain a fallback.-"""--from __future__ import annotations--import atexit-import json-import logging-import threading-import time-from contextlib import suppress-from pathlib import Path-from typing import Any, Dict, List--from agent.memory_provider import MemoryProvider, spawn_context_thread-from agent.secret_scope import get_secret-from tools.registry import tool_error-from utils import atomic_json_write, read_json_or_empty--logger = logging.getLogger(__name__)--# Circuit breaker: after _BREAKER_THRESHOLD consecutive failures, pause API-# calls for _BREAKER_COOLDOWN_SECS to avoid hammering a down server.-_BREAKER_THRESHOLD, _BREAKER_COOLDOWN_SECS, _PREFETCH_WAIT_SECS = 5, 120, 3-_CLIENT_ERROR_TYPES = ("MemoryNotFoundError", "ValidationError")-# Placeholder user_id. initialize() treats it as "no operator-configured user_id"-# so legacy mem0.json files written by the wizard don't override gateway-native ids.-_DEFAULT_USER_ID = "hermes-user"--# sync_turn sends the whole turn to the backend for fact extraction. OSS embedding-# models often have small context windows (bge-small-zh-v1.5: 512 tokens ≈ 500 chars;-# jina-embeddings-v3: 8192), and oversized turns make backend.add() raise — Ollama-# answers HTTP 500, hosted APIs return INPUT_TOKEN_LIMIT_EXCEEDED — which _try only-# logs, silently dropping the turn's memory extraction. Cap each message up front.-# The default fits a 512-token embedder (measured: 450 OK, 600 -> HTTP 500 on-# bge-small-zh-v1.5:f16); ``sync_max_chars`` in mem0.json raises it for larger windows.-_SYNC_MSG_MAX_CHARS = 450---# Sentence ends recognized when trimming a synced message. Deliberately unordered:-# the LAST boundary of ANY kind wins, so one CJK stop early in a mixed-script turn-# cannot outrank a Latin stop near the end of the window. ``".\n"`` is not listed —-# its index can never exceed the bare ``"."`` it starts with.-_SYNC_SENTENCE_ENDS = ("。", "!", "?", ".", "!", "?")---def _truncate_for_sync(text: str, max_len: int = _SYNC_MSG_MAX_CHARS) -> str:- """Cap a synced message at its last sentence boundary within ``max_len``.-- Short messages pass through unchanged; long ones keep the last complete- sentence inside the window so fact extraction still sees coherent statements,- with a hard cut as fallback when no boundary exists (or one only appears in- the first third of the window, which usually means unsegmented input).- """- if len(text) <= max_len:- return text- window = text[:max_len]- cut = max(window.rfind(sep) for sep in _SYNC_SENTENCE_ENDS)- if cut > max_len // 3:- return text[:cut + 1]- return text[:max_len]---def _is_client_error(exc: Exception) -> bool:- """True for user-caused errors (bad ID, not found) that should NOT trip circuit breaker."""- err_str = str(exc).lower()- return type(exc).__name__ in _CLIENT_ERROR_TYPES or any(s in err_str for s in ("404", "not found", "valid uuid"))---def _load_config() -> dict:- """Env vars provide defaults; $HERMES_HOME/mem0.json overrides individual keys.- Layering avoids a silent failure when the JSON file exists but lacks fields- like ``api_key`` that the user set in ``.env``."""- from hermes_constants import get_hermes_home- # Identity (user/agent id), host and mode are .env values like the key: read them through the- # profile scope too, or a secondary profile's memories land in the default profile's account.- # A scope-less multiplex caller raises here on purpose — that is a spawn-site bug, and- # swallowing it would silently route the turn's memories to the default profile.- config = {"mode": get_secret("MEM0_MODE", "") or "platform", "host": get_secret("MEM0_HOST", "") or "",- "agent_id": get_secret("MEM0_AGENT_ID", "") or "hermes", "oss": {}}- if user_id := get_secret("MEM0_USER_ID", ""): # only when explicitly configured, so initialize() can fall back to the gateway-native id- config["user_id"] = user_id- file_cfg = read_json_or_empty(get_hermes_home() / "mem0.json")- config.update({k: v for k, v in file_cfg.items() if v is not None and v != ""})- # MEM0_API_KEY authenticates the Platform and self-hosted HTTP backends; pure OSS mode builds its- # backend from the local ``oss`` config and has no platform credential to resolve, so a profile- # scope WITHOUT the key must still load an OSS config (#99121 as it stands today: the caller is- # scoped, the scope is just empty). Decided after mem0.json overrode the env defaults because- # the file may be what selects ``oss``. Scope-less callers already raised above.- if config.get("mode", "platform") == "oss":- config.setdefault("api_key", "")- elif not config.get("api_key"):- config["api_key"] = get_secret("MEM0_API_KEY", "")- return config---def _schema(name: str, description: str, properties: dict[str, tuple[str, str]], required: list[str]) -> dict:- props = {k: {"type": t, "description": d} for k, (t, d) in properties.items()}- return {"name": name, "description": description, "parameters": {"type": "object", "properties": props, "required": required}}---TOOL_SCHEMAS = [- _schema("mem0_search", "Search the user's memories by meaning; returns facts ranked by relevance. Use this before answering any question that may depend on what you know about the user (preferences, facts, history, people, projects, past decisions). For multi-part or multi-hop questions, call it several times — vary the wording and run follow-up searches on what earlier results reveal; one search is rarely enough.",- {"query": ("string", "What to search for."), "top_k": ("integer", "Max results (default: 10, max: 50)."), "rerank": ("boolean", "Rerank results for relevance (default: false, platform mode only).")}, ["query"]),- _schema("mem0_add", "Store a durable fact about the user, verbatim (no LLM extraction). Call this the moment the user states a lasting preference, correction, decision, or personal detail worth recalling on future turns — don't wait to be asked to remember. Skip transient chit-chat and facts you've already stored.",- {"content": ("string", "The fact to store.")}, ["content"]),- _schema("mem0_update", "Replace the text of an existing memory by its ID (take the ID from a mem0_search result). Use when a stored fact has changed or was wrong — correct it in place instead of adding a duplicate.",- {"memory_id": ("string", "Memory UUID to update."), "text": ("string", "New text content.")}, ["memory_id", "text"]),- _schema("mem0_delete", "Delete a memory by its ID (take the ID from a mem0_search result). Use when a stored fact is obsolete or the user asks you to forget it; prefer mem0_update if the fact merely changed.",- {"memory_id": ("string", "Memory UUID to delete.")}, ["memory_id"]),-]--_PROMPT_BODY = (- "You have persistent memory of this user from past conversations. You should call mem0_search before answering anything that could depend on prior context (the user's preferences, facts, history, people, projects, or earlier decisions) — do not rely on the chat window alone, and do not assume you have no memory.\n"- "For multi-part or multi-hop questions, run several searches with different wording/angles and follow-up searches on what the first results surface; one search is rarely enough. Keep searching until you have every fact the question needs before you answer.\n"- "Tools: mem0_search to find memories, mem0_add to store facts, mem0_update and mem0_delete to manage by ID."-)---class Mem0MemoryProvider(MemoryProvider):- """Mem0 memory with server-side extraction and semantic search (platform, self-hosted or OSS)."""-- def __init__(self):- self._config = self._backend = self._sync_thread = self._prefetch_thread = None- self._mode, self._api_key, self._host, self._user_id, self._agent_id = "platform", "", "", _DEFAULT_USER_ID, "hermes"- self._rerank_default, self._channel = False, "cli" # channel = gateway name (cli/telegram/discord/...)- self._sync_max_chars = _SYNC_MSG_MAX_CHARS- self._prefetch_query = self._prefetch_result = ""- self._prefetch_done = self._atexit_registered = False- self._consecutive_failures, self._breaker_open_until = 0, 0.0 # circuit breaker state- self._breaker_lock, self._sync_lock, self._prefetch_lock = threading.Lock(), threading.Lock(), threading.Lock()-- @property- def name(self) -> str:- return "mem0"-- def is_available(self) -> bool:- cfg = _load_config()- if cfg.get("mode", "platform") == "oss":- return bool(cfg.get("oss", {}).get("vector_store"))- return bool(cfg.get("api_key") or cfg.get("host")) # platform needs a key; self-hosted a host (key optional with AUTH_DISABLED)-- def save_config(self, values, hermes_home):- """Merge-write config to $HERMES_HOME/mem0.json."""- config_path = Path(hermes_home) / "mem0.json"- atomic_json_write(config_path, {**read_json_or_empty(config_path), **values}, mode=0o600)-- def get_config_schema(self):- api_key_required = _load_config().get("mode", "platform") != "oss"- 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):- # Make the pinned mem0 extra importable first; on failure the backend import- # raises the canonical error, captured below.- with suppress(Exception):- from pm import ensure_import- ensure_import("mem0")- 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"- self._sync_max_chars = int(cfg.get("sync_max_chars") or _SYNC_MSG_MAX_CHARS)- self._backend = self._create_backend()- if self._backend and not self._atexit_registered:- atexit.register(self._shutdown_backend)- 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, 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"- {l}" for l 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:- # Same query already answered or still in flight: don't restart it.- 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 = t = spawn_context_thread(_run, name="mem0-prefetch")- t.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(): # still busy after the wait: skip to avoid duplicate ingestion- return- 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})-- _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", lambda self, a: json.dumps(self._backend.update(a["memory_id"], a["text"])), "not_found"),- "mem0_delete": (("memory_id",), "Delete failed", lambda self, a: json.dumps(self._backend.delete(a["memory_id"])), "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 missing := next((k for k in required if not args.get(k, "")), None):- return tool_error(f"Missing required parameter: {missing}")- try:- result = body(self, args)- 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():- t.join(timeout=5.0)- self._shutdown_backend()---def register(ctx) -> None:- """Register Mem0 as a memory provider plugin."""- ctx.register_memory_provider(Mem0MemoryProvider())diff --git a/plugins/memory/mem0/_backend.py b/plugins/memory/mem0/_backend.pydeleted file mode 100644index c1abd8925ae..00000000000--- a/plugins/memory/mem0/_backend.py+++ /dev/null@@ -1,215 +0,0 @@-"""Backend abstraction for Mem0 Platform and OSS modes."""--from __future__ import annotations--from abc import ABC, abstractmethod-from contextlib import closing, suppress-from typing import Any---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 _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 _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))-- 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:- return self._json("POST", "/memories", json={"messages": messages, **_add_kwargs(user_id, agent_id, infer, metadata)})-- 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 = "plugins.memory.mem0._openai_llm.DirectOpenAILLM"---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):- import os- from mem0 import Memory- from ._oss_providers import EMBEDDER_PROVIDERS, KNOWN_DIMS, LLM_PROVIDERS-- 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)- block["config"] = provider_config- return block-- vector_store = dict(oss_config["vector_store"])- vs_config = dict(vector_store.get("config", {}))- if "path" in vs_config:- 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- self._recreate_collection_if_dims_changed(vector_store.get("provider", "qdrant"), vs_config, dims)- 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 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- self._memory = Memory(memory_config)- else:- self._memory = Memory.from_config(config)-- @staticmethod- def _recreate_collection_if_dims_changed(provider: str, vs_config: dict, expected_dims: int) -> None:- """Delete stale vector collection when embedding dimensions change."""- collection_name = vs_config.get("collection_name", "mem0")- with suppress(Exception):- if provider == "qdrant":- from qdrant_client import QdrantClient- path, url = vs_config.get("path"), vs_config.get("url")- if path:- client = QdrantClient(path=path)- elif url:- client = QdrantClient(url=url, api_key=vs_config.get("api_key"))- else:- return- with closing(client):- if not client.collection_exists(collection_name):- return- 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)- current_dims = getattr(vectors, "size", None)- if current_dims is not None and current_dims != expected_dims:- client.delete_collection(collection_name)- elif provider == "pgvector":- import psycopg2- from psycopg2 import sql as pgsql- 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()- if row and row[0] > 0 and row[0] != expected_dims:- cur.execute(pgsql.SQL("DROP TABLE IF EXISTS {}").format(pgsql.Identifier(collection_name)))-- def search(self, query: str, *, filters: dict, top_k: int = 10, rerank: bool = False) -> list[dict]:- return _unwrap_results(self._memory.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._memory.add(messages, **_add_kwargs(user_id, agent_id, infer, metadata))-- def _update(self, memory_id: str, text: str) -> None:- self._memory.update(memory_id, data=text)-- def _delete(self, memory_id: str) -> None:- self._memory.delete(memory_id)-- def close(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)- # Memory, then its vector store, then the store's raw client; the first failure aborts the chain.- for obj in filter(None, (self._memory, vs, getattr(vs, "client", None))):- if hasattr(obj, "close"):- obj.close()diff --git a/plugins/memory/mem0/_openai_llm.py b/plugins/memory/mem0/_openai_llm.pydeleted file mode 100644index bf58c1a4c5f..00000000000--- a/plugins/memory/mem0/_openai_llm.py+++ /dev/null@@ -1,66 +0,0 @@-"""OpenAI-only LLM adapter for Mem0 OSS mode."""--from __future__ import annotations--import logging-from typing import Dict, List, Optional, Union--from mem0.configs.llms.base import BaseLlmConfig-from mem0.configs.llms.openai import OpenAIConfig-from mem0.llms.base import LLMBase-from mem0.llms.openai import OpenAILLM--# BaseLlmConfig fields copied into OpenAIConfig; the last two may be absent on older mem0.-_COPIED_FIELDS = ("model", "temperature", "api_key", "max_tokens", "top_p", "top_k", "enable_vision", "vision_details", "http_client_proxies")-_OPTIONAL_FIELDS = ("reasoning_effort", "is_reasoning_model")---class DirectOpenAILLM(OpenAILLM):- """Use OpenAI credentials and requests regardless of router environment."""-- def __init__(self, config: Optional[Union[BaseLlmConfig, OpenAIConfig, Dict]] = None):- if config is None:- config = OpenAIConfig()- elif isinstance(config, dict):- config = OpenAIConfig(**config)- elif isinstance(config, BaseLlmConfig) and not isinstance(config, OpenAIConfig):- fields = {k: getattr(config, k) for k in _COPIED_FIELDS}- fields.update({k: getattr(config, k, None) for k in _OPTIONAL_FIELDS})- config = OpenAIConfig(**fields)- if not config.model:- config.model = "gpt-5-mini"- # Configs predating the setup marker: keep the default model reasoning-safe- # without overriding an explicit user choice.- if config.model == "gpt-5-mini" and config.is_reasoning_model is None:- config.is_reasoning_model = True- # Bypass OpenAILLM.__init__ (it picks OpenRouter when OPENROUTER_API_KEY is- # set); LLMBase still owns validation and supported-parameter filtering.- LLMBase.__init__(self, config)- # OPENAI_API_KEY / OPENAI_BASE_URL are profile credentials: read them through the secret- # scope, never raw os.environ, or a multiplexed secondary's memory extraction runs on the- # default profile's OpenAI account (and its proxy).- from agent.secret_scope import get_secret- api_key = self.config.api_key or get_secret("OPENAI_API_KEY", "")- if not api_key:- raise ValueError("OpenAI API key is required for the Hermes Mem0 OSS provider")- from openai import OpenAI- self.client = OpenAI(api_key=api_key, base_url=self.config.openai_base_url or get_secret("OPENAI_BASE_URL", "") or "https://api.openai.com/v1")-- 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_responsediff --git a/plugins/memory/mem0/_oss_providers.py b/plugins/memory/mem0/_oss_providers.pydeleted file mode 100644index c6ced627fc1..00000000000--- a/plugins/memory/mem0/_oss_providers.py+++ /dev/null@@ -1,53 +0,0 @@-"""OSS provider definitions for LLM, embedder, and vector store."""--from __future__ import annotations--import os-from typing import Any--from hermes_constants import get_hermes_home--LLM_PROVIDERS: dict[str, dict[str, Any]] = {- "openai": {"label": "OpenAI", "needs_key": True, "env_var": "OPENAI_API_KEY", "default_model": "gpt-5-mini", "base_url_key": "openai_base_url"},- "ollama": {"label": "Ollama (local)", "needs_key": False, "default_model": "llama3.1:8b", "default_url": "http://localhost:11434", "base_url_key": "ollama_base_url", "pip_dep": "ollama"},-}--EMBEDDER_PROVIDERS: dict[str, dict[str, Any]] = {- "openai": {"label": "OpenAI", "needs_key": True, "env_var": "OPENAI_API_KEY", "default_model": "text-embedding-3-small", "base_url_key": "openai_base_url", "dims": 1536},- "ollama": {"label": "Ollama (local)", "needs_key": False, "default_model": "nomic-embed-text", "default_url": "http://localhost:11434", "base_url_key": "ollama_base_url", "dims": 768, "pip_dep": "ollama"},-}--VECTOR_PROVIDERS: dict[str, dict[str, Any]] = {- # Resolved lazily (see ``vector_default_config``): the profile home is a ContextVar at call time,- # not an import-time constant, and ``~/.hermes`` is wrong on Windows and under profiles.- "qdrant": {"label": "Qdrant", "default_config": {"path": lambda: str(get_hermes_home() / "mem0_qdrant")}, "pip_dep": "qdrant-client"},- "pgvector": {- "label": "PGVector",- "default_config": {"host": "localhost", "port": 5432, "user": os.getenv("USER", "postgres"), "dbname": "postgres"},- "pip_dep": "psycopg2-binary",- },-}--KNOWN_DIMS: dict[str, int] = {"text-embedding-3-small": 1536, "text-embedding-3-large": 3072, "text-embedding-ada-002": 1536, "nomic-embed-text": 768}--def vector_default_config(provider_id: str) -> dict[str, Any]:- """A vector store's ``default_config`` with callable defaults resolved for the active profile."""- return {k: (v() if callable(v) else v) for k, v in VECTOR_PROVIDERS[provider_id]["default_config"].items()}---SECTION_REGISTRIES = (("llm", LLM_PROVIDERS), ("embedder", EMBEDDER_PROVIDERS), ("vector_store", VECTOR_PROVIDERS))---def validate_oss_config(oss_config: dict) -> list[str]:- """Validate an OSS config dict. Returns list of error strings (empty = valid)."""- errors: list[str] = []- for section, registry in SECTION_REGISTRIES:- block = oss_config.get(section)- if not block or not isinstance(block, dict):- errors.append(f"Missing required section: {section}")- elif block.get("provider", "") not in registry:- errors.append(f"Unknown {section} provider '{block.get('provider', '')}'. Valid: {', '.join(registry.keys())}")- vs = oss_config.get("vector_store", {})- if vs.get("provider") == "pgvector" and not vs.get("config", {}).get("user"):- errors.append("PGVector requires 'user' in vector_store.config")- return errorsdiff --git a/plugins/memory/mem0/_setup.py b/plugins/memory/mem0/_setup.pydeleted file mode 100644index 1511251e65e..00000000000--- a/plugins/memory/mem0/_setup.py+++ /dev/null@@ -1,519 +0,0 @@-"""Setup wizard for Mem0 plugin — interactive and flag-based modes."""--from __future__ import annotations--import getpass-import json-from contextlib import suppress-import os-import shutil-import socket-import subprocess-import sys-import time-import urllib.error-import urllib.request-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, VECTOR_PROVIDERS, validate_oss_config, vector_default_config--_OLLAMA_URL = "http://localhost:11434"-_PGVECTOR_CONTAINER, _PGVECTOR_IMAGE, _PGVECTOR_PASSWORD = "hermes-pgvector", "pgvector/pgvector:pg17", "hermes"---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-<key> 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}"):- 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}- 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]- env_path.write_text("\n".join(new_lines) + "\n", encoding="utf-8")---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 plugins.memory.mem0 import Mem0MemoryProvider- 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 := _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(provider_config), 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 utils import read_json_or_empty- if env_writes:- _write_env(Path(hermes_home) / ".env", env_writes)- config_path = Path(hermes_home) / "mem0.json" # merge-write, plain text (platform path uses save_config's 0600 atomic write)- config_path.write_text(json.dumps({**read_json_or_empty(config_path), "mode": "oss", "user_id": user_id, "agent_id": agent_id, "oss": oss_config}, indent=2) + "\n", encoding="utf-8")- _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- oss_config, env_writes = build_oss_config(flags)- 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- try:- print(f" Pulling {_PGVECTOR_IMAGE}...")- _docker("pull", _PGVECTOR_IMAGE, timeout=120)- _docker("rm", "-f", _PGVECTOR_CONTAINER, timeout=10) # remove existing container if present- print(f" Starting container '{_PGVECTOR_CONTAINER}' on port {port}...")- _docker("run", "-d", "--name", _PGVECTOR_CONTAINER, "-e", f"POSTGRES_PASSWORD={_PGVECTOR_PASSWORD}", "-p", f"{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": _PGVECTOR_PASSWORD, "dbname": "postgres"}- except subprocess.CalledProcessError as e:- print(f" Failed to start Docker container: {e}")- except Exception as e:- print(f" Docker error: {e}")- 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:- """Point at the pip deps the selected OSS backends need.-- These are third-party backend SDKs (ollama, qdrant-client, ...), not- hermes dependencies — pm does not install arbitrary specs into the- hermes venv. Print the exact command instead."""- deps: set[str] = set()- for registry, pid in [(LLM_PROVIDERS, llm_id), (EMBEDDER_PROVIDERS, embedder_id),- (VECTOR_PROVIDERS, vector_id)]:- dep = registry.get(pid, {}).get("pip_dep")- if dep:- deps.add(dep)- missing = []- for dep in sorted(deps):- import importlib.util-- if importlib.util.find_spec(dep.replace("-", "_").split("[")[0]) is None:- missing.append(dep)- if missing:- print("\n The selected backends need extra packages:")- print(f" Missing: {', '.join(missing)}")- print(" Declare these requirements in the plugin's pyproject.toml, then run `hermes pm install` and restart Hermes.")---def _probe(fn, ok: str, fail: str, exc=Exception) -> tuple[bool, str]:- """Run ``fn``; (True, ok) on success, (False, "fail: <error>") 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 tuple(int(x) for x in installed_ver.split(".")[:3]) < (2, 0, 7):- print(f"\n ⚠ mem0ai {installed_ver} installed but >=2.0.7 required.\n Run `hermes pm repair`, then restart Hermes.")- 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)diff --git a/plugins/memory/mem0/plugin.yaml b/plugins/memory/mem0/plugin.yamldeleted file mode 100644index dc376fa4d3a..00000000000--- a/plugins/memory/mem0/plugin.yaml+++ /dev/null@@ -1,4 +0,0 @@-name: mem0-version: 1.3.0-description: "Mem0 — server-side LLM fact extraction with semantic search, automatic deduplication, and opt-in reranking (platform mode)."-extra: mem0diff --git a/pm/extras.py b/pm/extras.pyindex c53450e71f6..73c482f025d 100644--- a/pm/extras.py+++ b/pm/extras.py@@ -40,7 +40,6 @@ ANCHORS: dict[str, str | tuple[str, ...]] = {"wake-sherpa": "sherpa_onnx","wake-porcupine": "pvporcupine","fal": "fal_client",- "mem0": "mem0","messaging": "telegram","telegram": "telegram","discord": "discord",diff --git a/pyproject.toml b/pyproject.tomlindex a16898701ee..648a597cad2 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -366,12 +366,6 @@ doc-extract = ["firecrawl-anydoc==0.2.4"]trace-upload = ["huggingface-hub==1.24.0"]# Cloud memory providers are opt-in PM extras. They stay outside [all]# so a quarantined release cannot break fresh installs.-# mem0ai pulls qdrant-client → grpcio, which has no win_arm64 wheel — same-# win32-arm64 gate as google-chat. mem0 is lazy-installed, so on arm64 the-# provider is simply unavailable.-mem0 = [- "mem0ai==2.0.10; platform_machine != 'ARM64' or sys_platform != 'win32'",-]# Image resize recovery for the vision tools. Pillow is now a CORE dependency# (see the main `dependencies` list above) since the byte/pixel shrink paths are on# the default vision-embed path and the mid-session lazy install deadlocked the@@ -585,8 +579,6 @@ opt-in-extras = ["kittentts"]matrix = "sys_platform == 'linux'"# grpcio (via google-cloud-pubsub) has no win_arm64 wheel.google-chat = "platform_machine != 'ARM64' or sys_platform != 'win32'"-# qdrant-client → grpcio (via mem0ai) has no win_arm64 wheel.-mem0 = "platform_machine != 'ARM64' or sys_platform != 'win32'"# Match the engine dependency markers so PM refuses an unsupported install.wake-openwakeword = "(platform_machine != 'ARM64' or sys_platform != 'win32') and (platform_machine != 'x86_64' or sys_platform != 'darwin')"# faster-whisper's closure is prebuilt-only: ctranslate2 has no win_arm64 wheel and onnxruntime@@ -733,7 +725,6 @@ markdown = falsematurin = falsemautrix = falsemcp = false-mem0ai = falsemicrosoft-teams-apps = falsemistralai = falsemodal = falsediff --git a/scripts/iso-certify.py b/scripts/iso-certify.pyindex acc8fea9620..01fa8de5a37 100755--- a/scripts/iso-certify.py+++ b/scripts/iso-certify.py@@ -117,7 +117,7 @@ def seed_scratch_home(home: Path, *, isolation: str, heartbeat_secs: int, respaw"compute_host_heartbeat_secs": heartbeat_secs,"compute_host_respawn_max": respawn_max,},- # Keep memory/mem0/skills side-machinery from reaching out.+ # Keep memory/skills side-machinery from reaching out."memory": {"enabled": False},}# config.yaml is the canonical config; write it directly.diff --git a/tests/agent/test_memory_user_id.py b/tests/agent/test_memory_user_id.pyindex 2f5b3fa7c98..18fd07ea681 100644--- a/tests/agent/test_memory_user_id.py+++ b/tests/agent/test_memory_user_id.py@@ -135,44 +135,3 @@ class TestMemoryManagerUserIdThreading:assert provider._init_kwargs["cwd"] == str(tmp_path)agent.close()-# ----------------------------------------------------------------------------# Mem0 provider user_id tests-# -----------------------------------------------------------------------------class TestMem0UserIdScoping:- """Verify Mem0 plugin uses gateway user_id when provided."""-- def test_no_user_id_falls_back_to_config(self):- """Without user_id in kwargs, should use config default."""- from plugins.memory.mem0 import Mem0MemoryProvider-- provider = Mem0MemoryProvider()- with patch("plugins.memory.mem0._load_config", return_value={- "api_key": "test-key",- "user_id": "custom-default",- "agent_id": "hermes",- "rerank": True,- }):- provider.initialize(session_id="test-sess")-- assert provider._user_id == "custom-default"-- def test_different_users_get_different_ids(self):- """Two providers initialized with different user_ids should be scoped differently."""- from plugins.memory.mem0 import Mem0MemoryProvider-- p1 = Mem0MemoryProvider()- p2 = Mem0MemoryProvider()-- with patch("plugins.memory.mem0._load_config", return_value={- "api_key": "test-key",- "user_id": "hermes-user",- "agent_id": "hermes",- "rerank": True,- }):- p1.initialize(session_id="sess-1", user_id="alice_123")- p2.initialize(session_id="sess-2", user_id="bob_456")-- assert p1._user_id == "alice_123"- assert p2._user_id == "bob_456"- assert p1._user_id != p2._user_iddiff --git a/tests/e2e/core/upgrade/test_fresh_process_entrypoints.py b/tests/e2e/core/upgrade/test_fresh_process_entrypoints.pyindex c5ce6f891ac..f178296f71e 100644--- a/tests/e2e/core/upgrade/test_fresh_process_entrypoints.py+++ b/tests/e2e/core/upgrade/test_fresh_process_entrypoints.py@@ -80,7 +80,7 @@ _OPTIONAL_IMPORTS = {"faster_whisper": "faster-whisper", "firecrawl": "firecrawl-py", "google": "google-auth","google_auth_oauthlib": "google-auth-oauthlib", "googleapiclient": "google-api-python-client","httplib2": "httplib2", "lark_oapi": "lark-oapi", "mautrix": "mautrix",- "mcp": "mcp", "mem0": "mem0ai", "microsoft_teams": "microsoft-teams-apps", "mistralai": "mistralai",+ "mcp": "mcp", "microsoft_teams": "microsoft-teams-apps", "mistralai": "mistralai","modal": "modal", "numpy": "numpy", "pyopen_wakeword": "pyopen-wakeword","opentelemetry": "opentelemetry-sdk", "parallel": "parallel-web", "pvporcupine": "pvporcupine","pyasn1": "pyasn1", "qrcode": "qrcode", "sentencepiece": "sentencepiece", "sherpa_onnx": "sherpa-onnx",diff --git a/tests/hermes_cli/test_doctor.py b/tests/hermes_cli/test_doctor.pyindex 529187eca96..5129d1a30f4 100644--- a/tests/hermes_cli/test_doctor.py+++ b/tests/hermes_cli/test_doctor.py@@ -418,12 +418,12 @@ class TestDoctorMemoryProviderSection:assert "Mem0" not in out- def test_mem0_provider_not_installed_shows_fail(self, monkeypatch, tmp_path):- # Make mem0 import fail- monkeypatch.setitem(sys.modules, "plugins.memory.mem0", None)+ def test_catalog_provider_not_installed_names_install_command(self, monkeypatch, tmp_path):+ # mem0 left core for the plugin catalog: a home still configured for it gets the exact command.out = self._run_doctor_and_capture(monkeypatch, tmp_path, provider="mem0")- assert "Memory Provider" in out+ section = out.split("Memory Provider", 1)[1][:600]assert "Built-in memory active" not in out+ assert "mem0 plugin not found" in section and "plugins install mem0" in section@pytest.mark.parametrize("memory_enabled", [False, True])def test_stale_builtin_files_reported_only_when_store_enabled(diff --git a/tests/plugins/memory/test_mem0_backend.py b/tests/plugins/memory/test_mem0_backend.pydeleted file mode 100644index 77cc45603d0..00000000000--- a/tests/plugins/memory/test_mem0_backend.py+++ /dev/null@@ -1,664 +0,0 @@-"""Tests for Mem0Backend abstraction — PlatformBackend, OSSBackend, SelfHostedBackend."""--import copy-import importlib-import json-import os-import sys-import types-from dataclasses import dataclass, field-from types import SimpleNamespace--import pytest--from plugins.memory.mem0._backend import (- PlatformBackend,- OSSBackend,- SelfHostedBackend,-)---class FakePlatformClient:- """Fake MemoryClient for PlatformBackend tests."""-- def __init__(self):- self.calls = []-- def search(self, query, **kwargs):- self.calls.append(("search", query, kwargs))- return {"results": [{"id": "m1", "memory": "fact1", "score": 0.9}]}-- def get_all(self, **kwargs):- self.calls.append(("get_all", kwargs))- return {"count": 1, "next": None, "results": [{"id": "m1", "memory": "fact1"}]}-- def add(self, messages, **kwargs):- self.calls.append(("add", messages, kwargs))- return {"status": "PENDING", "event_id": "evt-1"}-- def update(self, **kwargs):- self.calls.append(("update", kwargs))- return {"id": kwargs["memory_id"], "text": kwargs["text"]}-- def delete(self, **kwargs):- self.calls.append(("delete", kwargs))---class TestPlatformBackend:-- def _make(self):- client = FakePlatformClient()- backend = PlatformBackend.__new__(PlatformBackend)- backend._client = client- return backend, client---- def test_add_forwards_kwargs(self):- backend, client = self._make()- msgs = [{"role": "user", "content": "hi"}]- result = backend.add(msgs, user_id="u1", agent_id="hermes", infer=False)- call = client.calls[0]- assert call[2]["user_id"] == "u1"- assert call[2]["infer"] is False- # metadata kwarg should be omitted entirely when not provided so we- # don't surprise older mem0 client versions with an unknown kwarg.- assert "metadata" not in call[2]------class FakeOSSMemory:- """Fake mem0.Memory for OSSBackend tests."""-- def __init__(self):- self.calls = []-- def search(self, query, **kwargs):- self.calls.append(("search", query, kwargs))- return {"results": [{"id": "m1", "memory": "fact1", "score": 0.8}]}-- def get_all(self, **kwargs):- self.calls.append(("get_all", kwargs))- return {"results": [{"id": "m1", "memory": "fact1"}]}-- def add(self, messages, **kwargs):- self.calls.append(("add", messages, kwargs))- return {"results": [{"id": "m1", "memory": "fact1", "event": "ADD"}]}-- def update(self, memory_id, **kwargs):- self.calls.append(("update", memory_id, kwargs))- return {"message": "Memory updated successfully!"}-- def delete(self, memory_id):- self.calls.append(("delete", memory_id))- return {"message": "Memory deleted successfully!"}---@dataclass-class _FakeMem0State:- factory_registrations: list = field(default_factory=list)- from_config_calls: int = 0- clients: list = field(default_factory=list)- requests: list = field(default_factory=list)---def _install_fake_mem0(monkeypatch):- """Install a small mem0 2.0.10-shaped surface for OSS backend tests."""-- state = _FakeMem0State()-- class BaseLlmConfig:- def __init__(- self,- model=None,- temperature=0.1,- api_key=None,- max_tokens=2000,- top_p=0.1,- top_k=1,- enable_vision=False,- vision_details="auto",- reasoning_effort=None,- http_client_proxies=None,- is_reasoning_model=None,- **kwargs,- ):- self.model = model- self.temperature = temperature- self.api_key = api_key- self.max_tokens = max_tokens- self.top_p = top_p- self.top_k = top_k- self.enable_vision = enable_vision- self.vision_details = vision_details- self.reasoning_effort = reasoning_effort- self.http_client_proxies = http_client_proxies- self.is_reasoning_model = is_reasoning_model- for name, value in kwargs.items():- setattr(self, name, value)-- class OpenAIConfig(BaseLlmConfig):- def __init__(- self,- model=None,- temperature=0.1,- api_key=None,- max_tokens=2000,- top_p=0.1,- top_k=1,- enable_vision=False,- vision_details="auto",- reasoning_effort=None,- http_client_proxies=None,- is_reasoning_model=None,- openai_base_url=None,- models=None,- route="fallback",- openrouter_base_url=None,- site_url=None,- app_name=None,- store=None,- response_callback=None,- ):- super().__init__(- model=model,- temperature=temperature,- api_key=api_key,- max_tokens=max_tokens,- top_p=top_p,- top_k=top_k,- enable_vision=enable_vision,- vision_details=vision_details,- reasoning_effort=reasoning_effort,- http_client_proxies=http_client_proxies,- is_reasoning_model=is_reasoning_model,- )- self.openai_base_url = openai_base_url- self.models = models- self.route = route- self.openrouter_base_url = openrouter_base_url- self.site_url = site_url- self.app_name = app_name- self.store = store- self.response_callback = response_callback-- class LLMBase:- def __init__(self, config=None):- self.config = config or BaseLlmConfig()- if not hasattr(self.config, "model"):- raise ValueError("Configuration must have a 'model' attribute")-- def _get_supported_params(self, **kwargs):- if self.config.is_reasoning_model:- return {- name: kwargs[name]- for name in ("messages", "response_format", "tools", "tool_choice")- if name in kwargs- }- params = {- "temperature": self.config.temperature,- "top_p": self.config.top_p,- "max_tokens": self.config.max_tokens,- }- params.update(kwargs)- return params-- class OpenAILLM(LLMBase):- @staticmethod- def _parse_response(response, tools):- if not tools:- return response.choices[0].message.content- parsed = {- "content": response.choices[0].message.content,- "tool_calls": [],- }- for tool_call in response.choices[0].message.tool_calls or []:- parsed["tool_calls"].append(- {- "name": tool_call.function.name,- "arguments": json.loads(tool_call.function.arguments),- }- )- return parsed-- class Factory:- provider_to_class = {- "openai": ("mem0.llms.openai.OpenAILLM", OpenAIConfig),- "ollama": ("mem0.llms.openai.OpenAILLM", BaseLlmConfig),- }-- @classmethod- def register_provider(cls, name, class_path, config_class=None):- cls.provider_to_class[name] = (- class_path,- config_class or BaseLlmConfig,- )- state.factory_registrations.append((name, class_path, config_class))-- @classmethod- def create(cls, provider_name, config=None, **kwargs):- class_path, config_class = cls.provider_to_class[provider_name]- if config is None:- config = config_class(**kwargs)- elif isinstance(config, dict):- config = config_class(**config)- module_name, class_name = class_path.rsplit(".", 1)- llm_class = getattr(importlib.import_module(module_name), class_name)- return llm_class(config)-- class MemoryConfig:- def __init__(self, **config):- llm = config["llm"]- if llm["provider"] not in {"openai", "ollama"}:- raise ValueError(- f"Unsupported LLM provider: {llm['provider']}"- )- self.llm = SimpleNamespace(- provider=llm["provider"],- config=copy.deepcopy(llm.get("config", {})),- )- embedder = config["embedder"]- self.embedder = SimpleNamespace(- provider=embedder["provider"],- config=copy.deepcopy(embedder.get("config", {})),- )- vector_store = config["vector_store"]- self.vector_store = SimpleNamespace(- provider=vector_store["provider"],- config=copy.deepcopy(vector_store.get("config", {})),- )- self.version = config.get("version", "v1.1")-- class Memory:- instances = []-- def __init__(self, config):- self.config = config- self.llm = Factory.create(config.llm.provider, config.llm.config)- self.embedding_model = SimpleNamespace(- provider=config.embedder.provider,- config=config.embedder.config,- )- self.vector_store = SimpleNamespace(- provider=config.vector_store.provider,- config=config.vector_store.config,- )- type(self).instances.append(self)-- @classmethod- def from_config(cls, config):- # This mirrors mem0 2.0.10: validation rejects the private provider- # before the factory gets a chance to resolve its registration.- state.from_config_calls += 1- return cls(MemoryConfig(**config))-- class FakeOpenAI:- def __init__(self, *, api_key, base_url):- self.api_key = api_key- self.base_url = base_url- state.clients.append(self)- self.chat = SimpleNamespace(- completions=SimpleNamespace(create=self._create)- )-- def _create(self, **params):- state.requests.append(params)- return SimpleNamespace(- choices=[- SimpleNamespace(- message=SimpleNamespace(- content="direct answer",- tool_calls=[- SimpleNamespace(- function=SimpleNamespace(- name="remember",- arguments='{"fact": "tea"}',- )- )- ],- )- )- ]- )-- package_names = {- "mem0": types.ModuleType("mem0"),- "mem0.configs": types.ModuleType("mem0.configs"),- "mem0.configs.llms": types.ModuleType("mem0.configs.llms"),- "mem0.llms": types.ModuleType("mem0.llms"),- "mem0.utils": types.ModuleType("mem0.utils"),- "mem0.configs.base": types.ModuleType("mem0.configs.base"),- "mem0.configs.llms.base": types.ModuleType("mem0.configs.llms.base"),- "mem0.configs.llms.openai": types.ModuleType("mem0.configs.llms.openai"),- "mem0.llms.base": types.ModuleType("mem0.llms.base"),- "mem0.llms.openai": types.ModuleType("mem0.llms.openai"),- "mem0.utils.factory": types.ModuleType("mem0.utils.factory"),- "openai": types.ModuleType("openai"),- }- setattr(package_names["mem0"], "Memory", Memory)- setattr(package_names["mem0.configs.base"], "MemoryConfig", MemoryConfig)- setattr(package_names["mem0.configs.llms.base"], "BaseLlmConfig", BaseLlmConfig)- setattr(package_names["mem0.configs.llms.openai"], "OpenAIConfig", OpenAIConfig)- setattr(package_names["mem0.llms.base"], "LLMBase", LLMBase)- setattr(package_names["mem0.llms.openai"], "OpenAILLM", OpenAILLM)- setattr(package_names["mem0.utils.factory"], "LlmFactory", Factory)- setattr(package_names["openai"], "OpenAI", FakeOpenAI)- for name, module in package_names.items():- if name in {"mem0", "mem0.configs", "mem0.configs.llms", "mem0.llms", "mem0.utils"}:- module.__path__ = []- monkeypatch.setitem(sys.modules, name, module)-- # The class-path registration imports this module after the fake mem0- # surface is installed, so it binds to the test doubles above.- monkeypatch.delitem(- sys.modules, "plugins.memory.mem0._openai_llm", raising=False- )- return state, Memory, Factory---class TestOSSBackend:-- def _make(self):- memory = FakeOSSMemory()- backend = OSSBackend.__new__(OSSBackend)- backend._memory = memory- return backend, memory--- def test_legacy_api_base_aliases_are_normalized_before_mem0_init(self, monkeypatch):- state, Memory, factory = _install_fake_mem0(monkeypatch)- raw = {- "llm": {- "provider": "openai",- "config": {- "model": "gpt-5-mini",- "api_key": "openai-sentinel",- "api_base": "https://llm.example/v1",- },- },- "embedder": {- "provider": "ollama",- "config": {"model": "nomic-embed-text", "api_base": "http://ollama:11434"},- },- "vector_store": {"provider": "qdrant", "config": {}},- }- before = copy.deepcopy(raw)- environment = dict(os.environ)-- OSSBackend(raw)-- assert len(Memory.instances) == 1- captured = Memory.instances[0].config- assert captured.llm.provider == "hermes_openai"- assert captured.llm.config["openai_base_url"] == "https://llm.example/v1"- assert captured.embedder.provider == "ollama"- assert captured.embedder.config["ollama_base_url"] == "http://ollama:11434"- assert "api_base" not in captured.llm.config- assert "api_base" not in captured.embedder.config- assert factory.provider_to_class["hermes_openai"][1].__name__ == "OpenAIConfig"- assert len(state.factory_registrations) == 1- assert state.from_config_calls == 0- assert raw == before- assert dict(os.environ) == environment-- def test_direct_openai_uses_openai_credentials_and_request_shape(self, monkeypatch):- state, _, factory = _install_fake_mem0(monkeypatch)- monkeypatch.setenv("OPENROUTER_API_KEY", "router-sentinel")- monkeypatch.setenv("OPENAI_API_KEY", "env-openai-sentinel")-- module = importlib.import_module("plugins.memory.mem0._openai_llm")- callback_calls = []- config = factory.provider_to_class["openai"][1](- model="gpt-5-mini",- api_key="configured-openai-sentinel",- openai_base_url="https://openai.example/v1",- models=["router-model"],- route="lowest-latency",- site_url="https://hermes.example",- app_name="Hermes",- store=True,- response_callback=lambda *args: callback_calls.append(args),- )- adapter = module.DirectOpenAILLM(config)- assert adapter.config.is_reasoning_model is True- tools = [- {- "type": "function",- "function": {"name": "remember", "parameters": {}},- }- ]-- result = adapter.generate_response(- [{"role": "user", "content": "remember tea"}],- response_format={"type": "json_object"},- tools=tools,- tool_choice="required",- )-- assert len(state.clients) == 1- client = state.clients[0]- assert client.api_key == "configured-openai-sentinel"- assert client.base_url == "https://openai.example/v1"- request = state.requests[0]- assert request["model"] == "gpt-5-mini"- assert request["tools"] == tools- assert request["tool_choice"] == "required"- assert request["response_format"] == {"type": "json_object"}- assert request["store"] is True- assert "models" not in request- assert "route" not in request- assert "extra_headers" not in request- assert "temperature" not in request- assert "top_p" not in request- assert "max_tokens" not in request- assert result == {- "content": "direct answer",- "tool_calls": [{"name": "remember", "arguments": {"fact": "tea"}}],- }- assert len(callback_calls) == 1- assert callback_calls[0][0] is adapter- assert callback_calls[0][2] == request-- def test_direct_openai_preserves_explicit_non_reasoning_override(self, monkeypatch):- state, _, factory = _install_fake_mem0(monkeypatch)- config = factory.provider_to_class["openai"][1](- model="gpt-5-mini",- api_key="configured-openai-sentinel",- is_reasoning_model=False,- )-- module = importlib.import_module("plugins.memory.mem0._openai_llm")- adapter = module.DirectOpenAILLM(config)- adapter.generate_response([{"role": "user", "content": "remember tea"}])-- assert adapter.config.is_reasoning_model is False- request = state.requests[0]- assert request["temperature"] == 0.1- assert request["top_p"] == 0.1- assert request["max_tokens"] == 2000-- def test_direct_openai_defaults_missing_model_to_reasoning_safe_mini(self, monkeypatch):- monkeypatch.setenv("OPENAI_API_KEY", "environment-openai-sentinel")- _install_fake_mem0(monkeypatch)-- module = importlib.import_module("plugins.memory.mem0._openai_llm")- adapter = module.DirectOpenAILLM()-- assert adapter.config.model == "gpt-5-mini"- assert adapter.config.is_reasoning_model is True-- def test_direct_openai_uses_openai_environment_when_config_omits_values(self, monkeypatch):- state, _, factory = _install_fake_mem0(monkeypatch)- monkeypatch.setenv("OPENROUTER_API_KEY", "router-sentinel")- monkeypatch.setenv("OPENAI_API_KEY", "env-openai-sentinel")- monkeypatch.setenv("OPENAI_BASE_URL", "https://env-openai.example/v1")-- module = importlib.import_module("plugins.memory.mem0._openai_llm")- config = factory.provider_to_class["openai"][1](model="gpt-5-mini")- adapter = module.DirectOpenAILLM(config)-- assert len(state.clients) == 1- assert state.clients[0].api_key == "env-openai-sentinel"- assert state.clients[0].base_url == "https://env-openai.example/v1"-- def test_missing_openai_key_fails_before_client_and_hides_router_secret(self, monkeypatch):- state, _, factory = _install_fake_mem0(monkeypatch)- router_secret = "router-secret-sentinel"- monkeypatch.setenv("OPENROUTER_API_KEY", router_secret)- monkeypatch.delenv("OPENAI_API_KEY", raising=False)-- module = importlib.import_module("plugins.memory.mem0._openai_llm")- config = factory.provider_to_class["openai"][1](- model="gpt-5-mini",- api_key=None,- )-- with pytest.raises(ValueError) as exc_info:- module.DirectOpenAILLM(config)-- assert "OpenAI API key" in str(exc_info.value)- assert router_secret not in str(exc_info.value)- assert state.clients == []- assert state.requests == []-- def test_registration_is_idempotent_and_clients_keep_instance_config(self, monkeypatch):- state, Memory, factory = _install_fake_mem0(monkeypatch)- first = {- "llm": {- "provider": "openai",- "config": {- "model": "gpt-5-mini",- "api_key": "first-openai-sentinel",- "openai_base_url": "https://first.example/v1",- },- },- "embedder": {"provider": "ollama", "config": {}},- "vector_store": {"provider": "qdrant", "config": {}},- }- second = {- "llm": {- "provider": "openai",- "config": {- "model": "gpt-5-mini",- "api_key": "second-openai-sentinel",- "openai_base_url": "https://second.example/v1",- },- },- "embedder": {"provider": "ollama", "config": {}},- "vector_store": {"provider": "qdrant", "config": {}},- }- first_before = copy.deepcopy(first)- second_before = copy.deepcopy(second)-- OSSBackend(first)- OSSBackend(second)-- assert len(state.factory_registrations) == 1- assert factory.provider_to_class["hermes_openai"][0].endswith(- "_openai_llm.DirectOpenAILLM"- )- assert [- (client.api_key, client.base_url) for client in state.clients- ] == [- ("first-openai-sentinel", "https://first.example/v1"),- ("second-openai-sentinel", "https://second.example/v1"),- ]- assert len(Memory.instances) == 2- assert state.from_config_calls == 0- assert first == first_before- assert second == second_before-- def test_ollama_bypasses_direct_openai_adapter(self, monkeypatch):- state, Memory, factory = _install_fake_mem0(monkeypatch)- raw = {- "llm": {- "provider": "ollama",- "config": {- "model": "llama3.1:8b",- "api_base": "http://ollama:11434",- },- },- "embedder": {- "provider": "ollama",- "config": {- "model": "nomic-embed-text",- "api_base": "http://ollama:11434",- },- },- "vector_store": {"provider": "qdrant", "config": {}},- }- before = copy.deepcopy(raw)-- OSSBackend(raw)-- assert len(Memory.instances) == 1- assert state.from_config_calls == 1- assert Memory.instances[0].config.llm.provider == "ollama"- assert Memory.instances[0].config.embedder.provider == "ollama"- assert "hermes_openai" not in factory.provider_to_class- assert state.clients == []- assert raw == before---httpx = pytest.importorskip("httpx")---class _StubServer:- """Records requests and serves the real self-hosted server's response shapes."""-- def __init__(self, rows=10):- self.requests = []- self._rows = [{"id": f"m{i}", "memory": f"f{i}"} for i in range(rows)]-- def handler(self, request):- self.requests.append(request)- path, method = request.url.path, request.method- if path == "/search" and method == "POST":- return httpx.Response(200, json={"results": [{"id": "m1", "memory": "tea", "score": 0.9}]})- if path == "/memories" and method == "GET":- top_k = int(request.url.params.get("top_k", len(self._rows)))- return httpx.Response(200, json={"results": self._rows[:top_k]})- if path == "/memories" and method == "POST":- return httpx.Response(200, json={"results": [{"id": "new", "memory": "stored", "event": "ADD"}]})- if path.startswith("/memories/") and method in ("PUT", "DELETE"):- if path.endswith("/missing"): # server 404s unknown ids- return httpx.Response(404, json={"detail": "Memory not found"})- verb = "updated" if method == "PUT" else "Memory deleted successfully"- return httpx.Response(200, json={"message": verb})- return httpx.Response(404, json={"detail": "not found"})---def _backend(server, api_key="adminkey", host="http://sh:8888"):- """Build a SelfHostedBackend routed through the stub transport.-- Uses the real __init__ (via the injectable ``transport`` kwarg) so the- constructor's header/base_url setup is exercised by every test here.- """- return SelfHostedBackend(- api_key, host, transport=httpx.MockTransport(server.handler)- )---class TestSelfHostedBackend:- # --- constructor / auth setup (the crux of the bug) --------------------- def test_init_uses_x_api_key_not_token_auth(self):- b = SelfHostedBackend("adminkey", "http://sh:8888")- assert b._client.headers["x-api-key"] == "adminkey"- assert "authorization" not in b._client.headers # NOT the cloud 'Token' scheme--- # --- search ------------------------------------------------------------- # --- add / update / delete --------------------------------------------- # --- error propagation (feeds the plugin's circuit breaker) ------------ def test_http_error_raises(self):- s = _StubServer()- with pytest.raises(httpx.HTTPStatusError):- _backend(s).delete("missing") # 404 -> raise_for_status; 'not found' won't trip breakerdiff --git a/tests/plugins/memory/test_mem0_backend_integration.py b/tests/plugins/memory/test_mem0_backend_integration.pydeleted file mode 100644index e8942c06976..00000000000--- a/tests/plugins/memory/test_mem0_backend_integration.py+++ /dev/null@@ -1,131 +0,0 @@-"""Integration coverage for Hermes' pinned Mem0 OSS boundary."""--import copy-import os-from types import SimpleNamespace--import pytest---pytest.importorskip("mem0", reason="requires the existing mem0 extra")---def test_openai_backend_uses_real_mem0_config_and_factory(monkeypatch, tmp_path):- mem0_dir = tmp_path / "mem0"- monkeypatch.setenv("MEM0_DIR", str(mem0_dir))- monkeypatch.setenv("OPENAI_API_KEY", "environment-openai-sentinel")- monkeypatch.setenv("OPENROUTER_API_KEY", "router-sentinel")-- import openai- from mem0.memory import main as memory_main- from mem0.utils.factory import LlmFactory-- from plugins.memory.mem0._backend import OSSBackend- from plugins.memory.mem0._openai_llm import DirectOpenAILLM-- clients = []- requests = []-- class FakeOpenAI:- def __init__(self, *, api_key, base_url):- self.api_key = api_key- self.base_url = base_url- self.chat = SimpleNamespace(- completions=SimpleNamespace(create=self._create)- )- clients.append(self)-- @staticmethod- def _create(**params):- requests.append(params)- return SimpleNamespace(- choices=[- SimpleNamespace(- message=SimpleNamespace(- content="direct answer",- tool_calls=None,- )- )- ]- )-- class DummyVectorStore:- pass-- class DummyDB:- def __init__(self, _path):- pass-- monkeypatch.setattr(- LlmFactory,- "provider_to_class",- dict(LlmFactory.provider_to_class),- )- monkeypatch.setattr(openai, "OpenAI", FakeOpenAI)- monkeypatch.setattr(- memory_main.EmbedderFactory,- "create",- lambda *_args, **_kwargs: object(),- )- monkeypatch.setattr(- memory_main.VectorStoreFactory,- "create",- lambda *_args, **_kwargs: DummyVectorStore(),- )- monkeypatch.setattr(memory_main, "SQLiteManager", DummyDB)- monkeypatch.setattr(memory_main, "MEM0_TELEMETRY", False)- monkeypatch.setattr(memory_main, "capture_event", lambda *_args, **_kwargs: None)- monkeypatch.setattr(- OSSBackend,- "_recreate_collection_if_dims_changed",- staticmethod(lambda *_args, **_kwargs: None),- )-- config = {- "llm": {- "provider": "openai",- "config": {- "model": "gpt-5-mini",- "api_key": "configured-openai-sentinel",- "openai_base_url": "https://openai.example/v1",- "models": ["router-model"],- "route": "lowest-latency",- },- },- "embedder": {- "provider": "ollama",- "config": {- "model": "nomic-embed-text",- "ollama_base_url": "http://ollama.example:11434",- "embedding_dims": 768,- },- },- "vector_store": {- "provider": "qdrant",- "config": {- "collection_name": "mem0",- "path": str(tmp_path / "qdrant"),- },- },- }- original_config = copy.deepcopy(config)- environment = dict(os.environ)-- backend = OSSBackend(config)- result = backend._memory.llm.generate_response(- [{"role": "user", "content": "remember tea"}]- )-- assert isinstance(backend._memory.llm, DirectOpenAILLM)- assert len(clients) == 1- assert clients[0].api_key == "configured-openai-sentinel"- assert clients[0].base_url == "https://openai.example/v1"- assert requests == [- {- "model": "gpt-5-mini",- "messages": [{"role": "user", "content": "remember tea"}],- }- ]- assert result == "direct answer"- assert config == original_config- assert dict(os.environ) == environmentdiff --git a/tests/plugins/memory/test_mem0_providers.py b/tests/plugins/memory/test_mem0_providers.pydeleted file mode 100644index 183d4ade1ac..00000000000--- a/tests/plugins/memory/test_mem0_providers.py+++ /dev/null@@ -1,78 +0,0 @@-"""Tests for OSS provider definitions and validation."""--import pytest--from plugins.memory.mem0._oss_providers import (- LLM_PROVIDERS,- EMBEDDER_PROVIDERS,- VECTOR_PROVIDERS,- KNOWN_DIMS,- validate_oss_config,-)---class TestProviderDefinitions:-- def test_llm_providers_have_required_keys(self):- for pid, p in LLM_PROVIDERS.items():- assert "label" in p- assert "needs_key" in p- assert "default_model" in p-- def test_embedder_providers_have_required_keys(self):- for pid, p in EMBEDDER_PROVIDERS.items():- assert "label" in p- assert "needs_key" in p- assert "default_model" in p- assert "dims" in p--- def test_vector_providers_have_required_keys(self):- for pid, p in VECTOR_PROVIDERS.items():- assert "label" in p- assert "default_config" in p--- def test_known_dims_covers_defaults(self):- for pid, p in EMBEDDER_PROVIDERS.items():- assert p["default_model"] in KNOWN_DIMS---class TestValidation:-- def test_valid_openai_config(self):- cfg = {- "llm": {"provider": "openai", "config": {"model": "gpt-4o-mini"}},- "embedder": {"provider": "openai", "config": {"model": "text-embedding-3-small"}},- "vector_store": {"provider": "qdrant", "config": {"path": "/tmp/test"}},- }- errors = validate_oss_config(cfg)- assert errors == []-- def test_unknown_llm_provider(self):- cfg = {- "llm": {"provider": "gemini", "config": {}},- "embedder": {"provider": "openai", "config": {}},- "vector_store": {"provider": "qdrant", "config": {}},- }- errors = validate_oss_config(cfg)- assert any("llm" in e.lower() for e in errors)--- def test_missing_llm_section(self):- cfg = {- "embedder": {"provider": "openai", "config": {}},- "vector_store": {"provider": "qdrant", "config": {}},- }- errors = validate_oss_config(cfg)- assert any("llm" in e.lower() for e in errors)-- def test_pgvector_needs_user(self):- cfg = {- "llm": {"provider": "openai", "config": {}},- "embedder": {"provider": "openai", "config": {}},- "vector_store": {"provider": "pgvector", "config": {"host": "localhost"}},- }- errors = validate_oss_config(cfg)- assert any("user" in e.lower() for e in errors)-diff --git a/tests/plugins/memory/test_mem0_setup.py b/tests/plugins/memory/test_mem0_setup.pydeleted file mode 100644index 4174d539791..00000000000--- a/tests/plugins/memory/test_mem0_setup.py+++ /dev/null@@ -1,238 +0,0 @@-"""Tests for Mem0 setup wizard — flag parsing, config building, validation."""--import json-import sys-import types--from plugins.memory.mem0._setup import (- parse_flags,- build_oss_config,- _write_env,- _prompt_api_key,- post_setup,- _check_qdrant_path,-)---def _inject_fake_hermes_cli(monkeypatch):- """Inject fake hermes_cli modules so yaml/curses aren't required."""- fake_config_mod = types.ModuleType("hermes_cli.config")- fake_config_mod.save_config = lambda c: None-- fake_setup_mod = types.ModuleType("hermes_cli.memory_setup")- fake_setup_mod._curses_select = lambda *a, **kw: 0- fake_setup_mod._prompt = lambda label, default=None, secret=False: default or ""-- fake_hermes_cli = types.ModuleType("hermes_cli")- fake_hermes_cli.config = fake_config_mod- fake_hermes_cli.memory_setup = fake_setup_mod-- monkeypatch.setitem(sys.modules, "hermes_cli", fake_hermes_cli)- monkeypatch.setitem(sys.modules, "hermes_cli.config", fake_config_mod)- monkeypatch.setitem(sys.modules, "hermes_cli.memory_setup", fake_setup_mod)-- monkeypatch.setattr("plugins.memory.mem0._setup._curses_select", lambda *a, **kw: 0)- monkeypatch.setattr("plugins.memory.mem0._setup._prompt", lambda label, default=None, secret=False: default or "")- return fake_config_mod-----class TestBuildOSSConfig:---- def test_explicit_gpt_5_mini_is_reasoning_model(self):- flags = parse_flags([- "--mode", "oss", "--oss-llm-key", "sk-oai",- "--oss-llm-model", "gpt-5-mini",- ])- oss, _ = build_oss_config(flags)- assert oss["llm"]["config"]["model"] == "gpt-5-mini"- assert oss["llm"]["config"]["is_reasoning_model"] is True--- def test_custom_openai_model_is_not_forced_to_reasoning(self):- flags = parse_flags([- "--mode", "oss", "--oss-llm-key", "sk-oai",- "--oss-llm-model", "gpt-5.2",- ])- oss, _ = build_oss_config(flags)- assert oss["llm"]["config"]["model"] == "gpt-5.2"- assert "is_reasoning_model" not in oss["llm"]["config"]--- def test_ollama_no_key_needed(self):- flags = parse_flags(["--mode", "oss", "--oss-llm", "ollama", "--oss-embedder", "ollama"])- oss, env_writes = build_oss_config(flags)- assert oss["llm"]["provider"] == "ollama"- assert "model" in oss["llm"]["config"]- assert oss["llm"]["config"]["ollama_base_url"] == "http://localhost:11434"- assert "is_reasoning_model" not in oss["llm"]["config"]- assert oss["embedder"]["config"]["ollama_base_url"] == "http://localhost:11434"- assert env_writes == {}-- def test_embedder_reuses_llm_key(self):- """When LLM and embedder share same provider, key written once."""- flags = parse_flags(["--mode", "oss", "--oss-llm-key", "sk-oai"])- _, env_writes = build_oss_config(flags)- assert env_writes == {"OPENAI_API_KEY": "sk-oai"}-- def test_different_embedder_needs_separate_key(self):- flags = parse_flags([- "--mode", "oss",- "--oss-llm", "ollama",- "--oss-embedder", "openai", "--oss-embedder-key", "sk-oai",- ])- _, env_writes = build_oss_config(flags)- assert env_writes == {"OPENAI_API_KEY": "sk-oai"}-- def test_pgvector_config(self):- flags = parse_flags([- "--mode", "oss", "--oss-llm-key", "sk-oai",- "--oss-vector", "pgvector",- "--oss-vector-host", "db.local", "--oss-vector-port", "5433",- "--oss-vector-user", "pg", "--oss-vector-dbname", "memdb",- ])- oss, _ = build_oss_config(flags)- vs = oss["vector_store"]- assert vs["provider"] == "pgvector"- assert vs["config"]["host"] == "db.local"- assert vs["config"]["port"] == 5433- assert vs["config"]["user"] == "pg"-- def test_known_dims_auto_set(self):- flags = parse_flags(["--mode", "oss", "--oss-llm-key", "sk-oai"])- oss, _ = build_oss_config(flags)- dims = oss["embedder"]["config"].get("embedding_dims")- assert dims == 1536-- def test_custom_qdrant_path(self):- flags = parse_flags([- "--mode", "oss", "--oss-llm-key", "sk-oai",- "--oss-vector-path", "/data/qdrant",- ])- oss, _ = build_oss_config(flags)- assert oss["vector_store"]["config"]["path"] == "/data/qdrant"---class TestWriteEnv:-- def test_write_new_vars(self, tmp_path):- env_path = tmp_path / ".env"- _write_env(env_path, {"OPENAI_API_KEY": "sk-test"})- content = env_path.read_text()- assert "OPENAI_API_KEY=sk-test" in content-- def test_update_existing_var(self, tmp_path):- env_path = tmp_path / ".env"- env_path.write_text("OPENAI_API_KEY=old\nOTHER=keep\n")- _write_env(env_path, {"OPENAI_API_KEY": "new"})- content = env_path.read_text()- assert "OPENAI_API_KEY=new" in content- assert "OTHER=keep" in content- assert "old" not in content-- def test_preserves_non_ascii_existing_lines(self, tmp_path):- """Existing non-ASCII .env content must survive the read-modify-write- as UTF-8 (the locale codec would crash/mangle it on Windows)."""- env_path = tmp_path / ".env"- env_path.write_bytes("PROXY_NOTE=café-zürich-完了\n".encode("utf-8"))- _write_env(env_path, {"OPENAI_API_KEY": "sk-test"})- content = env_path.read_text(encoding="utf-8")- assert "PROXY_NOTE=café-zürich-完了" in content- assert "OPENAI_API_KEY=sk-test" in content-- def test_updates_first_key_with_bom(self, tmp_path):- """A Notepad-edited .env carries a BOM; the first key must still be- matched/updated in place, not duplicated."""- env_path = tmp_path / ".env"- env_path.write_bytes("OPENAI_API_KEY=old\n".encode("utf-8"))- _write_env(env_path, {"OPENAI_API_KEY": "new"})- content = env_path.read_text(encoding="utf-8")- assert content.count("OPENAI_API_KEY=") == 1- assert "OPENAI_API_KEY=new" in content---class TestPromptApiKey:-- def test_existing_key_found_behind_bom(self, tmp_path, monkeypatch):- """The masked-current-value lookup must see a key on the BOM'd first- line of a Notepad-edited .env instead of prompting from scratch."""- env_path = tmp_path / ".env"- env_path.write_bytes("OPENAI_API_KEY=sk-existing\n".encode("utf-8"))- monkeypatch.delenv("OPENAI_API_KEY", raising=False)-- prompts: list[str] = []-- def _fake_getpass(prompt):- prompts.append(prompt)- return ""-- monkeypatch.setattr("plugins.memory.mem0._setup.getpass.getpass", _fake_getpass)- _prompt_api_key("OpenAI", "OPENAI_API_KEY", str(tmp_path))-- assert len(prompts) == 1- assert "current: ...ting" in prompts[0]---class TestPostSetup:-- def test_platform_flag_mode(self, tmp_path, monkeypatch):- monkeypatch.setattr("sys.argv", ["hermes", "--mode", "platform", "--api-key", "sk-test"])- monkeypatch.setattr("plugins.memory.mem0._setup.get_hermes_home", lambda: tmp_path)- _inject_fake_hermes_cli(monkeypatch)- config = {"memory": {}}- post_setup(str(tmp_path), config)- assert config["memory"]["provider"] == "mem0"- env_content = (tmp_path / ".env").read_text()- assert "MEM0_API_KEY=sk-test" in env_content- mem0_json = json.loads((tmp_path / "mem0.json").read_text())- assert mem0_json["mode"] == "platform"--- def test_selfhosted_flag_mode(self, tmp_path, monkeypatch):- monkeypatch.setattr("sys.argv", [- "hermes", "--mode", "selfhosted",- "--host", "http://localhost:8888/", "--api-key", "admin-key",- ])- monkeypatch.setattr("plugins.memory.mem0._setup.get_hermes_home", lambda: tmp_path)- _inject_fake_hermes_cli(monkeypatch)- monkeypatch.setattr("plugins.memory.mem0._setup._check_selfhosted_server", lambda h: None)- config = {"memory": {}}- post_setup(str(tmp_path), config)- assert config["memory"]["provider"] == "mem0"- env_content = (tmp_path / ".env").read_text()- assert "MEM0_API_KEY=admin-key" in env_content- mem0_json = json.loads((tmp_path / "mem0.json").read_text())- assert mem0_json["host"] == "http://localhost:8888" # trailing slash stripped- assert mem0_json["user_id"] == "hermes-user"-----class TestConnectivityChecks:-- def test_qdrant_path_writable(self, tmp_path):- ok, msg = _check_qdrant_path(str(tmp_path / "qdrant"))- assert ok is True-----def test_discovery_loaded_setup_module_exposes_post_setup(monkeypatch):- """`hermes memory setup mem0` reaches the wizard when the package is first imported by plugin- discovery, which execs sibling modules before ``__init__`` (#103078). The invariant is on the- module the loader actually cached, not on a normal top-level import."""- from plugins.memory import load_memory_provider-- saved = {k: sys.modules.pop(k) for k in list(sys.modules) if k.startswith("plugins.memory.mem0")}- try:- provider = load_memory_provider("mem0", register_skills=False)- assert provider is not None- assert hasattr(sys.modules["plugins.memory.mem0._setup"], "post_setup")- finally:- for k in list(sys.modules):- if k.startswith("plugins.memory.mem0"):- del sys.modules[k]- sys.modules.update(saved)diff --git a/tests/plugins/memory/test_mem0_v3.py b/tests/plugins/memory/test_mem0_v3.pydeleted file mode 100644index e5aa259baae..00000000000--- a/tests/plugins/memory/test_mem0_v3.py+++ /dev/null@@ -1,492 +0,0 @@-"""Tests for Mem0 v3 API — new tool names, paginated responses, update/delete tools."""--import json-import threading-import pytest--from agent import secret_scope-import plugins.memory.mem0 as mem0_plugin-from plugins.memory.mem0 import Mem0MemoryProvider---class FakeBackend:- """Fake Mem0Backend for provider-level tests."""-- def __init__(self, search_results=None, all_results=None):- self._search_results = search_results or []- self._all_results = all_results or {"results": [], "count": 0}- self.captured = []-- def search(self, query, *, filters, top_k=10, rerank=True):- self.captured.append(("search", query, {"filters": filters, "top_k": top_k, "rerank": rerank}))- return self._search_results-- def get_all(self, *, filters, page=1, page_size=100):- self.captured.append(("get_all", {"filters": filters, "page": page, "page_size": page_size}))- return self._all_results-- def add(self, messages, *, user_id, agent_id, infer=False, metadata=None):- self.captured.append((- "add",- messages,- {"user_id": user_id, "agent_id": agent_id, "infer": infer, "metadata": metadata},- ))- return {"status": "PENDING", "event_id": "evt-test-123"}-- def update(self, memory_id, text):- self.captured.append(("update", memory_id, text))- return {"result": "Memory updated.", "memory_id": memory_id}-- def delete(self, memory_id):- self.captured.append(("delete", memory_id))- return {"result": "Memory deleted.", "memory_id": memory_id}---class TestMem0V3Tools:- """Test v3 tool names and response handling."""-- def _make_provider(self, monkeypatch, backend):- provider = Mem0MemoryProvider()- provider.initialize("test-session")- provider._user_id = "u123"- provider._agent_id = "hermes"- provider._backend = backend- return provider---- def test_add_uses_content_param(self, monkeypatch):- backend = FakeBackend()- provider = self._make_provider(monkeypatch, backend)- result = json.loads(provider.handle_tool_call("mem0_add", {"content": "user likes dark mode"}))- assert len(backend.captured) == 1- call = backend.captured[0]- assert call[2]["infer"] is False- assert call[2]["user_id"] == "u123"- assert call[2]["agent_id"] == "hermes"- assert "event_id" in result-----class TestMem0UpdateDelete:-- def _make_provider(self, monkeypatch, backend):- provider = Mem0MemoryProvider()- provider.initialize("test-session")- provider._user_id = "u123"- provider._agent_id = "hermes"- provider._backend = backend- return provider-- def test_update_calls_sdk(self, monkeypatch):- backend = FakeBackend()- provider = self._make_provider(monkeypatch, backend)- result = json.loads(provider.handle_tool_call(- "mem0_update", {"memory_id": "mem-1", "text": "updated fact"}- ))- assert backend.captured[0][1] == "mem-1"- assert backend.captured[0][2] == "updated fact"- assert result["result"] == "Memory updated."- assert result["memory_id"] == "mem-1"--- def test_delete_calls_sdk(self, monkeypatch):- backend = FakeBackend()- provider = self._make_provider(monkeypatch, backend)- result = json.loads(provider.handle_tool_call(- "mem0_delete", {"memory_id": "mem-1"}- ))- assert backend.captured[0][1] == "mem-1"- assert result["result"] == "Memory deleted."---class TestMem0V3Internal:-- def _make_provider(self, monkeypatch, backend):- provider = Mem0MemoryProvider()- provider.initialize("test-session")- provider._user_id = "u123"- provider._agent_id = "hermes"- provider._backend = backend- return provider-- def test_sync_turn_explicit_kwargs(self, monkeypatch):- backend = FakeBackend()- provider = self._make_provider(monkeypatch, backend)- provider.sync_turn("user said", "assistant replied", session_id="s1")- provider._sync_thread.join(timeout=2)- assert len(backend.captured) == 1- call = backend.captured[0]- assert call[2]["user_id"] == "u123"- assert call[2]["agent_id"] == "hermes"- assert call[2]["infer"] is True---class TestSyncTurnTruncation:- """sync_turn must cap messages before ingestion so small-context embedding- backends (OSS Ollama bge-small-zh-v1.5: 512 tokens; jina-embeddings-v3 token- limits) don't fail the whole extraction — a failure _try only logs."""-- def _make_provider(self, monkeypatch, backend):- provider = Mem0MemoryProvider()- provider.initialize("test-session")- provider._user_id = "u123"- provider._agent_id = "hermes"- provider._backend = backend- return provider-- def test_small_context_backend_never_sees_oversized_input(self, monkeypatch):- """Regression for #106235/#37421: an OSS embedding backend with a small- context window raises on oversized input; truncation up front keeps the- extraction from being silently dropped (no breaker failures)."""-- class SmallContextBackend(FakeBackend):- def add(self, messages, **kwargs):- if any(len(m["content"]) > mem0_plugin._SYNC_MSG_MAX_CHARS for m in messages):- raise RuntimeError("HTTP 500: embedding input exceeds model context")- return super().add(messages, **kwargs)-- backend = SmallContextBackend()- provider = self._make_provider(monkeypatch, backend)- provider.sync_turn("Short question?", "".join(f"Fact {i}. " for i in range(200)), session_id="s1")- provider._sync_thread.join(timeout=2)- assert len(backend.captured) == 1- sent = backend.captured[0][1]- assert sent[0]["content"] == "Short question?" # under the cap: untouched- assert len(sent[1]["content"]) <= mem0_plugin._SYNC_MSG_MAX_CHARS and sent[1]["content"].endswith(".")- assert provider._consecutive_failures == 0-- def test_the_boundary_kept_is_the_last_one_in_the_window_whatever_its_script(self):- """A mixed-script turn must not be cut back to an early CJK stop.-- The trim exists to keep as much of the turn as the embedder can take; picking the- first separator KIND that qualifies instead of the last boundary threw away most of- the allowed window whenever two kinds appeared — an early ``。`` (or ``.``, which- outranks ``!``/``?``) beat a boundary 240 characters later, so the facts stated in- the rest of the message never reached extraction.- """- cap = mem0_plugin._SYNC_MSG_MAX_CHARS- early, late = cap // 2, cap - 9-- for early_sep, late_sep in (("。", "."), (".", "!"), ("?", "?"), ("!", ".")):- text = "a" * early + early_sep + "b" * (late - early - 1) + late_sep + "c" * cap- assert text[late] == late_sep and len(text) > cap # both boundaries inside the window- kept = mem0_plugin._truncate_for_sync(text)- assert kept == text[:late + 1], f"{early_sep!r} before {late_sep!r} cut back to {len(kept)} chars"- assert kept.endswith(late_sep)-- def test_a_boundary_only_in_the_first_third_still_falls_back_to_a_hard_cut(self):- """Unsegmented input keeps the whole window rather than a sliver of a sentence."""- cap = mem0_plugin._SYNC_MSG_MAX_CHARS- text = "a" * 10 + "." + "b" * (cap * 2)- assert mem0_plugin._truncate_for_sync(text) == text[:cap]-- def test_sync_max_chars_config_raises_cap(self, monkeypatch, tmp_path):- """8k-token embedders should not be stuck at the 512-token default (#106235)."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- monkeypatch.setenv("MEM0_API_KEY", "test-key")- (tmp_path / "mem0.json").write_text('{"sync_max_chars": 3000}')- backend = FakeBackend()- provider = self._make_provider(monkeypatch, backend)- provider.sync_turn("hi", "Long answer. " * 200, session_id="s1") # 2600 chars- provider._sync_thread.join(timeout=2)- assert backend.captured[0][1][1]["content"] == "Long answer. " * 200---class TestMem0Prefetch:- """prefetch() must recall on the CURRENT question, synchronously.-- The old implementation ignored its ``query`` and returned whatever a- background ``queue_prefetch`` had warmed from the PREVIOUS turn — so the- first turn injected nothing and later turns injected stale, off-topic- memories. These lock the corrected behaviour.- """-- def _make_provider(self, backend):- provider = Mem0MemoryProvider()- provider.initialize("test-session")- provider._user_id = "u123"- provider._agent_id = "hermes"- provider._backend = backend- return provider-- def test_prefetch_searches_current_query(self):- backend = FakeBackend(search_results=[{"id": "m1", "memory": "user prefers dark mode"}])- provider = self._make_provider(backend)- result = provider.prefetch("what theme do I like?")- kind, query, opts = backend.captured[0]- assert kind == "search"- assert query == "what theme do I like?"- assert opts["filters"] == {"user_id": "u123"}- assert opts["top_k"] == 10- assert opts["rerank"] is False- assert "## Mem0 Memory" in result- assert "user prefers dark mode" in result--- def test_on_turn_start_queues_current_query(self):- backend = FakeBackend(search_results=[{"id": "m1", "memory": "lives in Berlin"}])- provider = self._make_provider(backend)- provider.on_turn_start(1, "where do I live?")- provider._prefetch_thread.join(timeout=1)- result = provider.prefetch("where do I live?")- assert "lives in Berlin" in result- assert len([c for c in backend.captured if c[0] == "search"]) == 1-- def test_slow_prefetch_returns_quickly(self, monkeypatch):- entered = threading.Event()- release = threading.Event()- search_returned = threading.Event()-- class SlowBackend(FakeBackend):- def search(self, query, *, filters, top_k=10, rerank=True):- entered.set()- try:- release.wait(30)- return super().search(- query, filters=filters, top_k=top_k, rerank=rerank- )- finally:- search_returned.set()-- monkeypatch.setattr(mem0_plugin, "_PREFETCH_WAIT_SECS", 0.01)- provider = self._make_provider(- SlowBackend(search_results=[{"id": "m1", "memory": "lives in Berlin"}])- )- # DETERMINISTIC non-blocking witness — replaces `assert elapsed < 0.1`.- #- # The old form slept 0.2s in the backend and asserted prefetch returned- # in under 0.1s. That makes the OS scheduler part of the assertion: on- # a loaded box thread startup alone can eat the 100ms budget, so the- # inequality flips with nothing wrong in the code under test. Observed- # failing in a full-directory run of tests/plugins/memory.- #- # The real contract is that prefetch gives up on the slow backend- # instead of waiting for it. Assert it directly: the backend search is- # STILL PARKED (release unset, so `search_returned` cannot be set). If- # prefetch ever waited for the backend, the search would have returned- # first and this fails. No wall-clock constant.- assert provider.prefetch("where do I live?") == ""- assert entered.wait(30), "prefetch never reached the backend"- assert not search_returned.is_set(), (- "prefetch blocked on the slow backend: the backend search had "- "already returned by the time prefetch did"- )-- release.set()- provider._prefetch_thread.join(timeout=30)- assert "lives in Berlin" in provider.prefetch("where do I live?")--- def test_queue_prefetch_fires_no_search(self):- # prefetch is synchronous now, so the post-turn warm is redundant and- # must not fire a wasted backend search.- backend = FakeBackend(search_results=[{"id": "m1", "memory": "x"}])- provider = self._make_provider(backend)- provider.queue_prefetch("previous turn text")- assert backend.captured == []-----class TestMem0ModeSwitch:-- def test_oss_mode_initializes_without_platform_key_in_scope(- self, monkeypatch, tmp_path- ):- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- monkeypatch.delenv("MEM0_API_KEY", raising=False)- (tmp_path / "mem0.json").write_text(- json.dumps(- {- "mode": "oss",- "oss": {"vector_store": {"provider": "qdrant"}},- }- )- )-- # Contract (#99121, restated for fail-loud reads): every production caller is scoped- # (turn/cron/kanban scope installers); an OSS profile whose scope simply lacks MEM0_API_KEY- # must initialize. A scope-LESS multiplex caller is a spawn-site bug and raises instead —- # see test_load_config_fails_closed_without_scope_even_for_identity_settings.- token = secret_scope.set_secret_scope({})- secret_scope.set_multiplex_active(True)- try:- provider = Mem0MemoryProvider()- provider._create_backend = lambda: None # type: ignore[method-assign]- provider.initialize("test")- available = provider.is_available()- finally:- secret_scope.set_multiplex_active(False)- secret_scope.reset_secret_scope(token)-- assert provider._mode == "oss"- assert provider._api_key == ""- assert available is True-- def test_platform_config_still_fails_closed_without_profile_scope(- self, monkeypatch, tmp_path- ):- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- monkeypatch.delenv("MEM0_API_KEY", raising=False)-- token = secret_scope.set_secret_scope(None)- secret_scope.set_multiplex_active(True)- try:- with pytest.raises(secret_scope.UnscopedSecretError):- Mem0MemoryProvider().is_available()- finally:- secret_scope.set_multiplex_active(False)- secret_scope.reset_secret_scope(token)-- def test_load_config_fails_closed_without_scope_even_for_identity_settings(- self, monkeypatch, tmp_path- ):- """A scope-less multiplex caller is a spawn-site bug: identity/mode reads must surface it,- not degrade to '' and route the turn's memories into the default profile's account."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- (tmp_path / "mem0.json").write_text(json.dumps({"mode": "oss", "oss": {"vector_store": {"provider": "qdrant"}}}))-- token = secret_scope.set_secret_scope(None)- secret_scope.set_multiplex_active(True)- try:- with pytest.raises(secret_scope.UnscopedSecretError):- mem0_plugin._load_config()- finally:- secret_scope.set_multiplex_active(False)- secret_scope.reset_secret_scope(token)-- def test_file_api_key_still_overrides_environment(self, monkeypatch, tmp_path):- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- monkeypatch.setenv("MEM0_API_KEY", "env-key")- (tmp_path / "mem0.json").write_text(- json.dumps({"api_key": "file-key"})- )-- assert mem0_plugin._load_config()["api_key"] == "file-key"--- def test_missing_mode_key_defaults_platform(self, monkeypatch, tmp_path):- """Backward compat: old mem0.json without mode key works."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- config_path = tmp_path / "mem0.json"- config_path.write_text('{"user_id": "old-user"}')- monkeypatch.setenv("MEM0_API_KEY", "test-key")- provider = Mem0MemoryProvider()- provider.initialize("test")- assert provider._mode == "platform"- assert provider._user_id == "old-user"-- def test_is_available_platform_needs_key(self, monkeypatch, tmp_path):- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- monkeypatch.delenv("MEM0_API_KEY", raising=False)- provider = Mem0MemoryProvider()- assert provider.is_available() is False---class TestMem0UserIdResolution:- """user_id resolution: configured override > gateway-native id > placeholder.-- Same human across CLI / Telegram / Discord / Slack / etc. should map to- the same memory store when MEM0_USER_ID is set, and only fall back to the- gateway-native id when it isn't.- """-- def _provider(self, monkeypatch, tmp_path):- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- monkeypatch.setenv("MEM0_API_KEY", "test-key")- provider = Mem0MemoryProvider()- # Skip backend instantiation — we only care about identity resolution.- provider._create_backend = lambda: None # type: ignore[method-assign]- return provider-- def test_env_override_beats_gateway_native_id(self, monkeypatch, tmp_path):- monkeypatch.setenv("MEM0_USER_ID", "[email protected]")- provider = self._provider(monkeypatch, tmp_path)- provider.initialize("test", user_id="123456789", platform="telegram")- assert provider._user_id == "[email protected]"-- def test_file_override_beats_gateway_native_id(self, monkeypatch, tmp_path):- monkeypatch.delenv("MEM0_USER_ID", raising=False)- (tmp_path / "mem0.json").write_text('{"user_id": "[email protected]"}')- provider = self._provider(monkeypatch, tmp_path)- provider.initialize("test", user_id="123456789", platform="telegram")- assert provider._user_id == "[email protected]"-- def test_unset_falls_back_to_gateway_native_id(self, monkeypatch, tmp_path):- monkeypatch.delenv("MEM0_USER_ID", raising=False)- provider = self._provider(monkeypatch, tmp_path)- provider.initialize("test", user_id="123456789", platform="telegram")- assert provider._user_id == "123456789"--- def test_legacy_placeholder_in_config_does_not_override_kwargs(self, monkeypatch, tmp_path):- # Setup wizard historically wrote {"user_id": "hermes-user"} as the- # suggested default. Treat that placeholder as unset so users on- # gateways still get gateway-native ids — not silent collisions.- monkeypatch.delenv("MEM0_USER_ID", raising=False)- (tmp_path / "mem0.json").write_text('{"user_id": "hermes-user"}')- provider = self._provider(monkeypatch, tmp_path)- provider.initialize("test", user_id="123456789", platform="telegram")- assert provider._user_id == "123456789"---class _SentinelBackend:- def __init__(self, *args):- self.args = args---class TestCreateBackendRouting:- """_create_backend() must pick the backend matching the configured mode/host."""-- def _provider(self, monkeypatch, *, mode="platform", api_key="k", host=""):- # Neutralize lazy-install so the routing decision is all we exercise.- monkeypatch.setattr("pm.ensure_import", lambda *a, **k: None, raising=False)- provider = Mem0MemoryProvider()- provider._mode = mode- provider._api_key = api_key- provider._host = host- provider._config = {"oss": {"vector_store": {"provider": "qdrant"}}}- return provider-- def test_routes_to_selfhosted_when_host_set(self, monkeypatch):- captured = {}-- class SH(_SentinelBackend):- def __init__(self, api_key, host):- captured["args"] = (api_key, host)-- monkeypatch.setattr("plugins.memory.mem0._backend.SelfHostedBackend", SH)- provider = self._provider(monkeypatch, host="http://sh:8888", api_key="adminkey")- backend = provider._create_backend()- assert isinstance(backend, SH)- assert captured["args"] == ("adminkey", "http://sh:8888")--- def test_oss_mode_takes_precedence_over_host(self, monkeypatch):- class OB(_SentinelBackend):- def __init__(self, cfg):- pass-- monkeypatch.setattr("plugins.memory.mem0._backend.OSSBackend", OB)- provider = self._provider(monkeypatch, mode="oss", host="http://sh:8888")- assert isinstance(provider._create_backend(), OB)-- def test_prompt_label_matches_routing_when_oss_and_host_both_set(self, monkeypatch):- # system_prompt_block must mirror _create_backend precedence: with both- # mode=oss and host set, OSS wins the routing, so the prompt must label- # OSS — not "self-hosted (HTTP API)". Guards the prompt-vs-routing lie.- provider = self._provider(monkeypatch, mode="oss", host="http://sh:8888")- provider._user_id = "test"- block = provider.system_prompt_block()- assert "OSS" in block- assert "HTTP API" not in block---class TestSelfHostedConfig:- """Config plumbing for self-hosted (MEM0_HOST env + is_available)."""-- def test_load_config_reads_mem0_host_env(self, monkeypatch):- monkeypatch.setenv("MEM0_HOST", "http://localhost:8888")- assert mem0_plugin._load_config()["host"] == "http://localhost:8888"diff --git a/tests/plugins/memory/test_memory_lazy_install.py b/tests/plugins/memory/test_memory_lazy_install.pydeleted file mode 100644index 6398a9b4b4b..00000000000--- a/tests/plugins/memory/test_memory_lazy_install.py+++ /dev/null@@ -1,45 +0,0 @@-"""Memory callers cross real PM admission before importing their optional SDK."""-import importlib.machinery-import importlib.abc-import sys-from types import ModuleType--import pytest--[email protected]("state", ["present", "absent", "failed"])-def test_provider_sdk_admission(monkeypatch, tmp_path, state):- extra = "mem0"- import pm.client- from pm import paths- from plugins.memory.mem0 import Mem0MemoryProvider-- sdk = ModuleType(extra)- sdk.__spec__ = importlib.machinery.ModuleSpec(extra, loader=None)- sdk.MemoryClient = lambda **kwargs: object()- sdk.Memory = object- monkeypatch.delitem(sys.modules, extra, raising=False)- if state == "present":- monkeypatch.setitem(sys.modules, extra, sdk)- class MissingSDK(importlib.abc.MetaPathFinder):- def find_spec(self, fullname, path=None, target=None):- if fullname == extra:- raise ModuleNotFoundError("SDK unavailable")- monkeypatch.setattr(sys, "meta_path", [MissingSDK(), *sys.meta_path])- monkeypatch.setattr(paths, "runtime_facts_path", lambda: tmp_path / "unselected-facts")- calls = []- def sync(extras):- calls.append(extras)- if state == "failed":- raise RuntimeError("SDK install refused")- monkeypatch.setitem(sys.modules, extra, sdk)- monkeypatch.setattr(pm.client, "sync_venv", sync)- def construct():- provider = Mem0MemoryProvider()- provider._mode, provider._api_key = "platform", "k"- return provider._create_backend()- if state == "failed":- assert construct() is None- else:- assert construct() is not None- assert calls == ([] if state == "present" else [[extra]])diff --git a/tests/plugins/memory/test_multiplex_memory_identity_scope.py b/tests/plugins/memory/test_multiplex_memory_identity_scope.pyindex 8c95afcdc85..181224d5179 100644--- a/tests/plugins/memory/test_multiplex_memory_identity_scope.py+++ b/tests/plugins/memory/test_multiplex_memory_identity_scope.py@@ -1,7 +1,7 @@"""Multiplex invariant: memory-provider identity/tenant/endpoint never comes from the default profile.Under ``gateway.multiplex_profiles`` ``os.environ`` is the DEFAULT profile's ``.env``. When a secondary-profile's scope does not define MEM0_USER_ID / RETAINDB_PROJECT /+profile's scope does not define RETAINDB_PROJECT /OPENVIKING_* / HERMES_HONCHO_HOST, the provider must fall back to its own default(per-profile partition), NOT write the secondary's memories into the default profile's account."""@@ -12,13 +12,10 @@ import pytestfrom agent import secret_scope_DEFAULT_ENV = {- "MEM0_USER_ID": "user-default", "MEM0_AGENT_ID": "agent-default", "MEM0_HOST": "http://mem0.default",- "MEM0_MODE": "self_hosted","RETAINDB_PROJECT": "proj-default", "RETAINDB_BASE_URL": "https://rdb.default","OPENVIKING_API_KEY": "ov-default", "OPENVIKING_ACCOUNT": "acct-default", "OPENVIKING_USER": "user-default","OPENVIKING_AGENT": "agent-default", "OPENVIKING_ENDPOINT": "http://ov.default","HERMES_HONCHO_HOST": "host-default", "HONCHO_BASE_URL": "https://honcho.default",- "OPENAI_API_KEY": "sk-default", "OPENAI_BASE_URL": "https://openai.default/v1",}@@ -34,8 +31,7 @@ def secondary_profile(monkeypatch, tmp_path):(prof_b / "config.yaml").write_text("{}\n")monkeypatch.setenv("HERMES_HOME", str(prof_b))secret_scope.set_multiplex_active(True)- token = secret_scope.set_secret_scope({"RETAINDB_API_KEY": "rdb-b", "HONCHO_API_KEY": "honcho-b",- "MEM0_API_KEY": "mem0-b"})+ token = secret_scope.set_secret_scope({"RETAINDB_API_KEY": "rdb-b", "HONCHO_API_KEY": "honcho-b"})try:yield prof_bfinally:@@ -44,14 +40,9 @@ def secondary_profile(monkeypatch, tmp_path):def test_secondary_profile_memory_identity_never_inherits_default_environ(secondary_profile):- import plugins.memory.mem0 as mem0import plugins.memory.openviking as openvikingimport plugins.memory.retaindb as retaindb- cfg = mem0._load_config()- assert "user_id" not in cfg # falls back to the gateway-native id, not the default's user- assert (cfg["agent_id"], cfg["host"], cfg["mode"]) == ("hermes", "", "platform")-provider = retaindb.RetainDBMemoryProvider()provider.initialize("s1", hermes_home=str(secondary_profile))assert provider._client.project == "hermes-b"@@ -62,21 +53,3 @@ def test_secondary_profile_memory_identity_never_inherits_default_environ(secondassert "default" not in settings["endpoint"]client = openviking._VikingClient("http://x", "k")assert (client._account, client._user) == ("default", "default") # the built-in tenant, not acct-default---def test_mem0_oss_llm_never_borrows_default_profile_openai_key(secondary_profile):- pytest.importorskip("mem0")- from mem0.configs.llms.openai import OpenAIConfig-- from plugins.memory.mem0._openai_llm import DirectOpenAILLM-- with pytest.raises(ValueError, match="OpenAI API key is required"):- DirectOpenAILLM(OpenAIConfig(model="gpt-5-mini"))- # The secondary's own scoped key + base URL are used when present.- token = secret_scope.set_secret_scope({"OPENAI_API_KEY": "sk-b", "OPENAI_BASE_URL": "https://openai.b/v1"})- try:- llm = DirectOpenAILLM(OpenAIConfig(model="gpt-5-mini"))- finally:- secret_scope.reset_secret_scope(token)- assert llm.client.api_key == "sk-b"- assert str(llm.client.base_url).startswith("https://openai.b/v1")diff --git a/tests/plugins/memory/test_provider_threads_inherit_profile.py b/tests/plugins/memory/test_provider_threads_inherit_profile.pyindex f21ff7bfa64..cdd2c8c1c70 100644--- a/tests/plugins/memory/test_provider_threads_inherit_profile.py+++ b/tests/plugins/memory/test_provider_threads_inherit_profile.py@@ -21,17 +21,6 @@ def _probe_home(seen: dict, key: str = "home"):return _record-def _mem0(seen, tmp_path):- from plugins.memory.mem0 import Mem0MemoryProvider-- p = Mem0MemoryProvider()- p._backend = MagicMock()- p._config = {"mode": "platform"}- p._add = _probe_home(seen)- p.sync_turn("a long enough user message", "assistant reply")- return [p._sync_thread]--def _retaindb(seen, tmp_path):import plugins.memory.retaindb as retaindb@@ -62,7 +51,7 @@ def _openviking(seen, tmp_path):_PROVIDERS = {- "mem0": _mem0, "retaindb": _retaindb, "byterover": _byterover,+ "retaindb": _retaindb, "byterover": _byterover,"openviking": _openviking,}diff --git a/tests/plugins/test_plugin_paths_follow_profile.py b/tests/plugins/test_plugin_paths_follow_profile.pyindex b51c6c5dca9..41de3dae3b2 100644--- a/tests/plugins/test_plugin_paths_follow_profile.py+++ b/tests/plugins/test_plugin_paths_follow_profile.py@@ -21,17 +21,12 @@ def _photon_auth(home):return auth._auth_json_path()-def _mem0_qdrant(home):- from plugins.memory.mem0._oss_providers import vector_default_config- return vector_default_config("qdrant")["path"]--def _openviking_log(home):import plugins.memory.openviking as ovreturn ov.get_hermes_home() / ov._OPENVIKING_SERVER_LOG_RELATIVE_PATH-_RESOLVERS = {"a2a": _a2a_conversation, "photon": _photon_auth, "mem0-qdrant": _mem0_qdrant,+_RESOLVERS = {"a2a": _a2a_conversation, "photon": _photon_auth,"openviking": _openviking_log}diff --git a/tests/test_project_metadata.py b/tests/test_project_metadata.pyindex 7c34678fd01..a5ddabcc4f3 100644--- a/tests/test_project_metadata.py+++ b/tests/test_project_metadata.py@@ -119,7 +119,6 @@ def test_lazy_installable_extras_excluded_from_all():"telegram", "discord","wake", "wake-openwakeword", "wake-sherpa", "wake-porcupine","google-chat",- "mem0","mistral", # mistralai — Voxtral STT/TTS, lazy-installed (stt.mistral / tts.mistral)}all_extra_specs = optional_dependencies["all"]diff --git a/uv.lock b/uv.lockindex 5389dde571a..2b913598993 100644--- a/uv.lock+++ b/uv.lock@@ -61,7 +61,6 @@ markdown = falsematurin = falsemautrix = falsemcp = false-mem0ai = falsemicrosoft-teams-apps = falsemistralai = falsemodal = false@@ -2499,9 +2498,6 @@ mcp = [{ name = "mcp" },{ name = "starlette" },]-mem0 = [- { name = "mem0ai", marker = "platform_machine != 'ARM64' or sys_platform != 'win32'" },-]messaging = [{ name = "aiohttp" },{ name = "brotlicffi" },@@ -2720,7 +2716,6 @@ requires-dist = [{ name = "mautrix", extras = ["encryption"], marker = "sys_platform == 'linux' and extra == 'matrix'", specifier = "==0.21.1" },{ name = "mcp", marker = "extra == 'computer-use'", specifier = "==2.0.0" },{ name = "mcp", marker = "extra == 'mcp'", specifier = "==2.0.0" },- { name = "mem0ai", marker = "(platform_machine != 'ARM64' and extra == 'mem0') or (sys_platform != 'win32' and extra == 'mem0')", specifier = "==2.0.10" },{ name = "microsoft-teams-apps", marker = "extra == 'teams'", specifier = "==2.0.13.4" },{ name = "misaki", extras = ["en"], marker = "(platform_machine != 'x86_64' and sys_platform == 'darwin' and extra == 'kittentts') or (platform_machine != 'ARM64' and sys_platform == 'win32' and extra == 'kittentts') or (sys_platform != 'darwin' and sys_platform != 'win32' and extra == 'kittentts')", git = "https://github.com/NousResearch/misaki.git?rev=f03fd2be7346952a83d3d4845c217fc7667f322d" },{ name = "mistralai", marker = "extra == 'mistral'", specifier = "==2.4.8" },@@ -2805,7 +2800,7 @@ requires-dist = [{ name = "winrt-windows-services-store", marker = "python_full_version >= '3.14' and sys_platform == 'win32'", specifier = ">=3.2.1,<4" },{ name = "youtube-transcript-api", marker = "extra == 'youtube'", specifier = "==1.2.4" },]-provides-extras = ["uvloop", "anthropic", "exa", "firecrawl", "parallel-web", "ddgs", "fal", "edge-tts", "neutts", "kittentts", "piper", "modal", "daytona", "vercel", "google-meet", "messaging", "cron", "slack", "matrix", "wecom", "tts-premium", "voice", "wake", "telegram", "discord", "stt-whisper", "audio-io", "silk", "wake-openwakeword", "wake-sherpa", "wake-porcupine", "google-chat", "doc-extract", "trace-upload", "mem0", "vision", "pty", "mcp", "nemo-relay", "sms", "teams", "computer-use", "acp", "mistral", "otlp", "langfuse", "bedrock", "vertex", "azure-identity", "termux", "termux-all", "dingtalk", "feishu", "google", "youtube", "web", "all"]+provides-extras = ["uvloop", "anthropic", "exa", "firecrawl", "parallel-web", "ddgs", "fal", "edge-tts", "neutts", "kittentts", "piper", "modal", "daytona", "vercel", "google-meet", "messaging", "cron", "slack", "matrix", "wecom", "tts-premium", "voice", "wake", "telegram", "discord", "stt-whisper", "audio-io", "silk", "wake-openwakeword", "wake-sherpa", "wake-porcupine", "google-chat", "doc-extract", "trace-upload", "vision", "pty", "mcp", "nemo-relay", "sms", "teams", "computer-use", "acp", "mistral", "otlp", "langfuse", "bedrock", "vertex", "azure-identity", "termux", "termux-all", "dingtalk", "feishu", "google", "youtube", "web", "all"][package.metadata.requires-dev]dev = [@@ -2954,9 +2949,6 @@ wheels = [][package.optional-dependencies]-http2 = [- { name = "h2" },-]socks = [{ name = "socksio" },]@@ -3557,25 +3549,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" },]-[[package]]-name = "mem0ai"-version = "2.0.10"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "httpx" },- { name = "openai" },- { name = "posthog" },- { name = "protobuf" },- { name = "pydantic" },- { name = "pytz" },- { name = "qdrant-client" },- { name = "sqlalchemy" },-]-sdist = { url = "https://files.pythonhosted.org/packages/90/43/b71a46ea164dbee57d2b436d60bc446179e5829e51759ee199240552701f/mem0ai-2.0.10.tar.gz", hash = "sha256:0d2afcd51f093c915b7d1e6208e86fbf563340de181e5604ff8af9513f3dffc8", size = 236842, upload-time = "2026-06-27T17:10:02.81Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/a4/58/9c25e77f06ec3483267f898c42fba783f2dcc411c7234dd34830bef8a372/mem0ai-2.0.10-py3-none-any.whl", hash = "sha256:9a99401c2c57bfbaf6ab780b193e458eb46802b4d75cac42f61eff13c9e34062", size = 329294, upload-time = "2026-06-27T17:10:01.157Z" },-]-[[package]]name = "microsoft-teams-api"version = "2.0.16"@@ -4741,28 +4714,13 @@ name = "portalocker"version = "3.2.0"source = { registry = "https://pypi.org/simple" }dependencies = [- { name = "pywin32", marker = "sys_platform == 'win32'" },+ { name = "pywin32" },]sdist = { url = "https://files.pythonhosted.org/packages/5e/77/65b857a69ed876e1951e88aaba60f5ce6120c33703f7cb61a3c894b8c1b6/portalocker-3.2.0.tar.gz", hash = "sha256:1f3002956a54a8c3730586c5c77bf18fae4149e07eaf1c29fc3faf4d5a3f89ac", size = 95644, upload-time = "2025-06-14T13:20:40.03Z" }wheels = [{ url = "https://files.pythonhosted.org/packages/4b/a6/38c8e2f318bf67d338f4d629e93b0b4b9af331f455f0390ea8ce4a099b26/portalocker-3.2.0-py3-none-any.whl", hash = "sha256:3cdc5f565312224bc570c49337bd21428bba0ef363bbcf58b9ef4a9f11779968", size = 22424, upload-time = "2025-06-14T13:20:38.083Z" },]-[[package]]-name = "posthog"-version = "7.43.0"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "backoff" },- { name = "distro" },- { name = "requests" },- { name = "typing-extensions" },-]-sdist = { url = "https://files.pythonhosted.org/packages/04/7d/6769ca2903c780b32177975592cd06614b2928b29e4d759c877f1652979c/posthog-7.43.0.tar.gz", hash = "sha256:872294f986e399976f84b57c19fd4e61269e2468a3fdd3ea494552394343c508", size = 475902, upload-time = "2026-08-24T10:01:41.092Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/4a/d9/15f9488311cf41f3e5e117230a10f31839a1ea31e5af7dcf29754311f70d/posthog-7.43.0-py3-none-any.whl", hash = "sha256:29d35fdae68ddc9b257e0d44715b6105a465974361a29844cbe21abcb58e37df", size = 565580, upload-time = "2026-08-24T10:01:39.275Z" },-]-[[package]]name = "preshed"version = "3.0.13"@@ -5571,24 +5529,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" },]-[[package]]-name = "qdrant-client"-version = "1.19.0"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "grpcio" },- { name = "httpx", extra = ["http2"] },- { name = "numpy" },- { name = "portalocker" },- { name = "protobuf" },- { name = "pydantic" },- { name = "urllib3" },-]-sdist = { url = "https://files.pythonhosted.org/packages/3a/33/c6e4ec45b4fca5a0b808e8804e60be54a6d7505b68b53c0b1d0d62ba86c1/qdrant_client-1.19.0.tar.gz", hash = "sha256:365395a04b0a26c309b25b7d8b1c99ef2071ec9a2b74bc8a5fd3b7a3642fe963", size = 350953, upload-time = "2026-08-04T14:32:56.923Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/fc/3c/480c61cc8d5a3e76bb44e86231f408c93643e5498beadbbeb381ab55d02b/qdrant_client-1.19.0-py3-none-any.whl", hash = "sha256:13602a2b3478a95ecdf42f97b93d7f703b63a3361cd912a04495a33a5ac14121", size = 396157, upload-time = "2026-08-04T14:32:55.734Z" },-]-[[package]]name = "qrcode"version = "7.4.2"@@ -6356,48 +6296,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/33/78/d1a1a026ef3af911159398c939b1509d5c36fe524c7b644f34a5146c4e16/spacy_loggers-1.0.5-py3-none-any.whl", hash = "sha256:196284c9c446cc0cdb944005384270d775fdeaf4f494d8e269466cfa497ef645", size = 22343, upload-time = "2023-09-11T12:26:50.586Z" },]-[[package]]-name = "sqlalchemy"-version = "2.0.52"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "greenlet", marker = "platform_machine == 'AMD64' or platform_machine == 'WIN32' or platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'ppc64le' or platform_machine == 'win32' or platform_machine == 'x86_64'" },- { name = "typing-extensions" },-]-sdist = { url = "https://files.pythonhosted.org/packages/3b/21/77b4c147963073040dc3c3a5cb7a8c3001a1893c0209432cb77f9df836aa/sqlalchemy-2.0.52.tar.gz", hash = "sha256:5e2d46356ac2ccb7d268ab6c2319ac6a2b42f1b8d5fd8bd3d46855cd82abee97", size = 9945637, upload-time = "2026-08-11T19:07:09.829Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/6b/08/cc5f7627b92f1456bc0b5fb7e98af4600248abe422a44da0d17a3fe6a448/sqlalchemy-2.0.52-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e0c3ce43907374889f3352bdcc6195c970148a2cb71574cd0237a5071a37fb6c", size = 2172460, upload-time = "2026-08-11T20:58:22.429Z" },- { url = "https://files.pythonhosted.org/packages/ed/dc/9a2abad8bfc8fdcd38c64adc056aeefab7aaa96ecd32f5e8c140e6375f17/sqlalchemy-2.0.52-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a0d48c4b80717c61385b4e966e087c839a66cfd7b780641dcb428f4dba65608", size = 3355720, upload-time = "2026-08-11T21:00:06.746Z" },- { url = "https://files.pythonhosted.org/packages/a8/73/e75597b5841043e3c74055d00d4feb53d9a49a5c89ba2450d2d9aab53597/sqlalchemy-2.0.52-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:938325a5373267afc53bfbe72983b20fbd64ca47842aac62433c3da1137ecff1", size = 3354394, upload-time = "2026-08-11T21:05:51.454Z" },- { url = "https://files.pythonhosted.org/packages/12/25/410fbc6c2f1fa8310f4ef1b6847d47d0ac1c042c7b4e81eaaca063d030a9/sqlalchemy-2.0.52-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:5f8438a98d49424acf69d0d53c0a522951dfe49a6f2d86417fbb37ad3066ab43", size = 3306991, upload-time = "2026-08-11T21:00:08.603Z" },- { url = "https://files.pythonhosted.org/packages/b2/ba/25ffd5c24681ea4b46e62c80ceca8200ce204de1773366321306cf3f608a/sqlalchemy-2.0.52-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4699dbb8d396d199e7e78fd4d525e3ad3d6008a9c8c0160b87e74c606c2c3736", size = 3327454, upload-time = "2026-08-11T21:05:53.368Z" },- { url = "https://files.pythonhosted.org/packages/c2/f1/0f1b1d4800e51218e736a06ed55a3b2a59c257600bbaca7673bf13d2dbec/sqlalchemy-2.0.52-cp311-cp311-win32.whl", hash = "sha256:cef328349452ae152637df4d11ce5a0919ecdf0a363e16c830c3518ee33bde72", size = 2131248, upload-time = "2026-08-11T21:09:50.765Z" },- { url = "https://files.pythonhosted.org/packages/7a/f0/04d2ac5ad66f3d31278f37064ed5f5ef3fe653f7bdaa67036663f223d186/sqlalchemy-2.0.52-cp311-cp311-win_amd64.whl", hash = "sha256:f1c850792a3b25a3ad74dade3f05e4f402cdebfea27438bcadafaa1617f77bcc", size = 2156943, upload-time = "2026-08-11T21:09:51.979Z" },- { url = "https://files.pythonhosted.org/packages/e0/d5/1b77a026d161f98a08f11af1a5f6c47b98ee7c7e2648af525a1004826c78/sqlalchemy-2.0.52-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:be8c49131665dfe2cc74c498aa1240ffb548d0fd901325dd11c2c7a18956f727", size = 2170940, upload-time = "2026-08-11T20:58:11.25Z" },- { url = "https://files.pythonhosted.org/packages/54/bd/f444444adb37b5d53753fb1730ee7a421628e2e3b756c4da461af7e6394a/sqlalchemy-2.0.52-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b2d9e507a458832adcfbd8af6e2036ddf069b7710b799448542ebccae2dceee", size = 3383415, upload-time = "2026-08-11T21:02:38.534Z" },- { url = "https://files.pythonhosted.org/packages/be/57/2eadf93a552568c57e8680b7e58bb5e9770d80942a1bdbaf4f2f63f0d7c8/sqlalchemy-2.0.52-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8738008376d22f30f411ea3efecf39b51110b6996d80bb73786f30bcfdd5fd3b", size = 3398577, upload-time = "2026-08-11T21:16:59.092Z" },- { url = "https://files.pythonhosted.org/packages/15/c3/2887cf9dd111d1fbf05d22165b404c221ef43e029f7a2695e7302f27a7cc/sqlalchemy-2.0.52-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:37a4d548327b6cab9c7d8cdb4e0e82feabee0110c4d150059068e2d1cfbd99ee", size = 3328225, upload-time = "2026-08-11T21:02:40.183Z" },- { url = "https://files.pythonhosted.org/packages/02/0f/466bdf9e1feeeef5587f868c187d8687e21ff8c85b1775e9041130181132/sqlalchemy-2.0.52-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:e49f51a5d59857a7a0dcaf9469febf7197d9394bd88f00d69c2c4e848112cdbf", size = 3357374, upload-time = "2026-08-11T21:17:01.076Z" },- { url = "https://files.pythonhosted.org/packages/22/20/5c2b4583904af4173076dda1c9e53c9e2ffc7a702d2efde0216bbacbf7cb/sqlalchemy-2.0.52-cp312-cp312-win32.whl", hash = "sha256:afda3ec521d0517d0de783fc70030775841900896d832de5bbd066549290470e", size = 2129366, upload-time = "2026-08-11T21:14:50.991Z" },- { url = "https://files.pythonhosted.org/packages/ed/06/543dab8ef62d4e9fb96fb31a30c2b8b14a8763bccf48d428294d6b3041c0/sqlalchemy-2.0.52-cp312-cp312-win_amd64.whl", hash = "sha256:2d5e53e36e37129fe0be8b9d08b6e4052c10a963ee6cda56c8c10dcc194b99ca", size = 2157344, upload-time = "2026-08-11T21:14:52.453Z" },- { url = "https://files.pythonhosted.org/packages/7f/18/e30c6fe1eca1bf34a39fbdd6066121cc9974c850faf6f349eac563697a26/sqlalchemy-2.0.52-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2eb3c6a64b1bfe6704777cfd504e7b8ad093a5f3e03ce67663a5e6742f294e43", size = 2167724, upload-time = "2026-08-11T20:58:12.679Z" },- { url = "https://files.pythonhosted.org/packages/d0/56/2e17d161a4f7ecc1c2ffb93e607b4e1898bb551b451b283235acb8f6ce47/sqlalchemy-2.0.52-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:923bb183c1dc64fdf7b717965e3d59938ec4f8b8710b419a21ce403e5da9a9e1", size = 3321189, upload-time = "2026-08-11T21:02:41.932Z" },- { url = "https://files.pythonhosted.org/packages/cf/b8/8490916e893f3f8d74dc9cc54c078619364999dee37047a188e73abbc852/sqlalchemy-2.0.52-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:651d6d8782e80679e6151707c7b490834d46ada526328895abf567f25e63d29c", size = 3338185, upload-time = "2026-08-11T21:17:02.597Z" },- { url = "https://files.pythonhosted.org/packages/8b/f7/752cc8ee453da222829b3f5c4613614bf750d97429363b70414fa10478e4/sqlalchemy-2.0.52-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:b08cddb8989775e3c88799d86704bdfc3ee6e9846118201aa5997f16f27e3a15", size = 3271698, upload-time = "2026-08-11T21:02:43.963Z" },- { url = "https://files.pythonhosted.org/packages/51/e6/074ade0c07b9e4c8e8bca46820320ed94df9702afdb6f2af06623068d2e6/sqlalchemy-2.0.52-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:ab66fa9618269390d4dfa222f2f2f88f7bc4bf5da13905131b818217db7e8057", size = 3308936, upload-time = "2026-08-11T21:17:04.172Z" },- { url = "https://files.pythonhosted.org/packages/66/07/557c0d04716705599227945ac14e0a17ad0338e899f37d8c2ddff4dcc663/sqlalchemy-2.0.52-cp313-cp313-win32.whl", hash = "sha256:c63bda077685c85ca513286547a531ba57e7a68cf0a7ed3bafcc2bbd18896f4d", size = 2127308, upload-time = "2026-08-11T21:14:53.879Z" },- { url = "https://files.pythonhosted.org/packages/96/4e/226eda27654318ce525d043025221f689abef883da2c7126f9065121618c/sqlalchemy-2.0.52-cp313-cp313-win_amd64.whl", hash = "sha256:9876b09b9f1ce7398b0ffece585c0a911244c53191187341f6bcae640e133751", size = 2153876, upload-time = "2026-08-11T21:14:55.527Z" },- { url = "https://files.pythonhosted.org/packages/d5/f5/71cb30af58c9b80a4e1fac0b73bb48f86d497a774a6a2eb6d2f1e657bb73/sqlalchemy-2.0.52-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:410d52be41d17f1a236d19520fbe776257dc16516ed06bd16d433311842aefd9", size = 2169537, upload-time = "2026-08-11T20:58:13.855Z" },- { url = "https://files.pythonhosted.org/packages/4c/93/d07ebd645d1b07b6b5ed63450a70f063a346a7e0f2c8810daf2e532400cb/sqlalchemy-2.0.52-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:dfe9ce533dbe4d0a2ae1486546619bd30b76bcd670539a44d910361376175f5e", size = 3319606, upload-time = "2026-08-11T21:02:45.829Z" },- { url = "https://files.pythonhosted.org/packages/ae/5c/290c84c7c2566ecd3b65baaae0fddec9bc33b033b398a06123bb86fbfc6e/sqlalchemy-2.0.52-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:812bae5138bfc0aa46fb0686da0fc7f581f68e2bbb05bc24c3713bebaedd1437", size = 3323642, upload-time = "2026-08-11T21:17:05.675Z" },- { url = "https://files.pythonhosted.org/packages/13/f5/2cc160590ca49173359557880b92a0572293ccb899e8f6cedf150c5a3ddf/sqlalchemy-2.0.52-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:50bff43b632a56fbf5ed9afdd76307e1512b62051bcd5afb341ae67205bbb6c8", size = 3268125, upload-time = "2026-08-11T21:02:47.649Z" },- { url = "https://files.pythonhosted.org/packages/35/f3/ea8933fc9f7d1353e9c2ff9965eae687c4cef181120574591ed2fa0633e1/sqlalchemy-2.0.52-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:49565daf5af554f538e23aef1fc81a95a4e49658f152285e45c02f5fc44f04cd", size = 3289516, upload-time = "2026-08-11T21:17:07.267Z" },- { url = "https://files.pythonhosted.org/packages/45/67/05cf86541c1e1716fca1e4a996954a439cd74501707cda607fb7cb02ef50/sqlalchemy-2.0.52-cp314-cp314-win32.whl", hash = "sha256:ab9da41e61b9979b910499d633b241df20c51ee5037e5405b11c2faac3cbe1a2", size = 2130249, upload-time = "2026-08-11T21:14:57.273Z" },- { url = "https://files.pythonhosted.org/packages/96/d7/8ac6ffa1e36169e762ef65bd835046abb2251b1bc17f8f6708e14ed8d31f/sqlalchemy-2.0.52-cp314-cp314-win_amd64.whl", hash = "sha256:a593db51b3bae75db17a5738ad5f992244b3a03863f83c28117ee482c6a3f76d", size = 2156718, upload-time = "2026-08-11T21:14:58.667Z" },- { url = "https://files.pythonhosted.org/packages/dc/4b/e01a737eef378e734cc6394a82248a6ce13b167dfa36c731075ce9fc9c64/sqlalchemy-2.0.52-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c1e61d08bdf4ee2f41024569e3400de7d6734ba498144766b11260936ccfa582", size = 2190344, upload-time = "2026-08-11T19:53:21.393Z" },- { url = "https://files.pythonhosted.org/packages/b3/3f/3582293d1e185e71d19d7c731c3e2ee20ba21981c4a1115c0806c1f62120/sqlalchemy-2.0.52-py3-none-any.whl", hash = "sha256:3b81b8363a919ce53453591cdb93702e6bd54ade6c4fa2f468fc053baee5ed89", size = 1950700, upload-time = "2026-08-11T20:47:21.603Z" },-]-[[package]]name = "srsly"version = "2.5.3"diff --git a/website/docs/getting-started/nix-setup.md b/website/docs/getting-started/nix-setup.mdindex 1715f113397..d4dd84e6f97 100644--- a/website/docs/getting-started/nix-setup.md+++ b/website/docs/getting-started/nix-setup.md@@ -826,14 +826,6 @@ For optional extras declared in hermes-agent's `pyproject.toml`, use `extraDepenservices.hermes-agent.extraDependencyGroups = [ "messaging" ];```-```nix-# Enable a memory provider-services.hermes-agent = {- extraDependencyGroups = [ "mem0" ];- settings.memory.provider = "mem0";-};-```-These groups join the core dependency resolution at build time. Conflictingrequirements can still fail that resolution. The table lists common groups;`pyproject.toml` is authoritative for the complete list and platform markers.@@ -850,7 +842,6 @@ requirements can still fail that resolution. The table lists common groups;| `anthropic` | Native Anthropic SDK (not needed via OpenRouter) || `bedrock` | AWS Bedrock (boto3) || `azure-identity` | Azure Entra ID auth |-| `mem0` | Mem0 memory provider || `modal` | Modal terminal backend || `daytona` | Daytona terminal backend || `exa` | Exa web search |diff --git a/website/docs/integrations/index.md b/website/docs/integrations/index.mdindex eef29e5be73..feed8d745cb 100644--- a/website/docs/integrations/index.md+++ b/website/docs/integrations/index.md@@ -84,7 +84,7 @@ Speech-to-text supports eight providers: local faster-whisper (free, runs on-dev## Memory & Personalization- **[Built-in Memory](../user-guide/features/memory.md)** — Persistent, curated memory via `MEMORY.md` and `USER.md` files. The agent maintains bounded stores of personal notes and user profile data that survive across sessions.-- **[Memory Providers](../user-guide/features/memory-providers.md)** — Plug in external memory backends for deeper personalization. Five providers ship with Hermes: OpenViking (tiered retrieval), Mem0 (cloud extraction), Holographic (local SQLite), RetainDB (hybrid search) and ByteRover (CLI-based); Honcho (dialectic reasoning), Hindsight (knowledge graphs) and Supermemory (semantic recall) are available from the plugin catalog via `hermes plugins install <name>`.+- **[Memory Providers](../user-guide/features/memory-providers.md)** — Plug in external memory backends for deeper personalization. Four providers ship with Hermes: OpenViking (tiered retrieval), Holographic (local SQLite), RetainDB (hybrid search) and ByteRover (CLI-based); Honcho (dialectic reasoning), Hindsight (knowledge graphs), Supermemory (semantic recall) and Mem0 (cloud extraction) are available from the plugin catalog via `hermes plugins install <name>`.## Messaging Platformsdiff --git a/website/docs/reference/cli-commands.md b/website/docs/reference/cli-commands.mdindex 4cb19a23740..c9a07b4b697 100644--- a/website/docs/reference/cli-commands.md+++ b/website/docs/reference/cli-commands.md@@ -1570,7 +1570,7 @@ See [Hooks](../user-guide/features/hooks.md) for event signatures and payload shhermes memory <subcommand>```-Set up and manage external memory provider plugins. Bundled providers: openviking, mem0, holographic, retaindb, byterover; honcho, hindsight and supermemory (plugin catalog) after `hermes plugins install <name>` (`hermes update` does this automatically for a provider already named in `memory.provider`). Only one external provider can be active at a time. Built-in memory (MEMORY.md/USER.md) is always active.+Set up and manage external memory provider plugins. Bundled providers: openviking, holographic, retaindb, byterover; honcho, hindsight, supermemory and mem0 (plugin catalog) after `hermes plugins install <name>` (`hermes update` does this automatically for a provider already named in `memory.provider`). Only one external provider can be active at a time. Built-in memory (MEMORY.md/USER.md) is always active.Subcommands:diff --git a/website/docs/user-guide/features/memory-providers.md b/website/docs/user-guide/features/memory-providers.mdindex 62c198c834a..dd4d6fcbaf9 100644--- a/website/docs/user-guide/features/memory-providers.md+++ b/website/docs/user-guide/features/memory-providers.md@@ -22,8 +22,8 @@ Or set manually in `~/.hermes/config.yaml`:```yamlmemory:- provider: openviking # or mem0, holographic, retaindb, byterover,- # or honcho / hindsight / supermemory (plugin catalog — run+ provider: openviking # or holographic, retaindb, byterover,+ # or honcho / hindsight / supermemory / mem0 (plugin catalog — run# `hermes plugins install <name>` first)```@@ -368,23 +368,27 @@ does not add a separate request.### Mem0+:::info Plugin catalog+Mem0 is maintained by Mem0 and installed from the [plugin catalog](./plugins.md) rather than bundled with Hermes. Source: [mem0ai/mem0 — integrations/hermes-plugin-mem0](https://github.com/mem0ai/mem0/tree/main/integrations/hermes-plugin-mem0). Existing setups are migrated automatically — see [Migrating from bundled Mem0](#migrating-from-bundled-mem0).+:::+Server-side LLM fact extraction with semantic search, reranking, and automatic deduplication. Three connection modes: **Platform** (Mem0 Cloud), **self-hosted dashboard** (a Mem0 server you run via Docker), and **OSS** (Mem0 in-process with your own LLM + vector store).| | ||---|---|| **Best for** | Hands-off memory management — Mem0 handles extraction automatically |-| **Requires** | `hermes memory setup` prepares the Mem0 SDK through PM; API key (platform), a running Mem0 server (self-hosted dashboard), or an LLM + vector store (OSS) |+| **Requires** | `hermes plugins install mem0` (installs the Mem0 SDK with the plugin); API key (platform), a running Mem0 server (self-hosted dashboard), or an LLM + vector store (OSS) || **Data storage** | Mem0 Cloud (platform), your own Mem0 server (self-hosted dashboard), or in-process (OSS) || **Cost** | Mem0 pricing (platform) / free (self-hosted or OSS) |-The `mem0` SDK extra is excluded on native Windows ARM64. An external Mem0-server over HTTP is a separate mode; a remote service does not imply that the-in-process SDK runs on that target.+The mem0ai SDK sends anonymous PostHog usage telemetry unless `MEM0_TELEMETRY=false` is set in+your shell or `~/.hermes/.env`.**Tools (4):** `mem0_search` (semantic search; optional reranking in platform mode, off by default), `mem0_add` (store verbatim facts), `mem0_update` (update by ID), `mem0_delete` (delete by ID)**Setup (Platform):**```bash+hermes plugins install mem0 # from the plugin cataloghermes memory setup # select "mem0" → "Platform"# Or manually:hermes config set memory.provider mem0@@ -447,6 +451,16 @@ The plugin authenticates with `X-API-Key` and uses the server's `/search` / `/me**Switching modes:** Re-run `hermes memory setup mem0 --mode <platform|selfhosted|oss>` or edit `mem0.json` directly.+### Migrating from bundled Mem0++Mem0 used to ship inside the Hermes tree (and as the `hermes-agent[mem0]` pip extra). If your `config.yaml` already has `memory.provider: mem0`, there is nothing to do for most users:++- `hermes update` installs the catalog plugin into every profile home that names the provider.+- If the plugin is still missing on the first agent start (`hermes chat`, the gateway, Desktop), Hermes installs it and tells you it did.+- With `security.allow_lazy_installs: false` the agent-start path does not install anything; it prints the exact `hermes plugins install mem0` command instead.++`memory.provider`, `$HERMES_HOME/mem0.json`, the `MEM0_*` keys in `.env` and the memories stored in Mem0 Cloud, your Mem0 server or the local OSS store are untouched. Verify with `hermes memory status` and `hermes plugins list`.+---### Hindsight@@ -746,7 +760,7 @@ package command. Restart Hermes after successful dependency preparation.|----------|---------|------|-------|-------------|----------------|| **Honcho** (plugin catalog) | Cloud/Self-hosted | Paid/Free | 5 | `hermes plugins install honcho` | Dialectic user modeling + session-scoped context || **OpenViking** | Self-hosted | Free | 6 | `openviking` + server | Filesystem hierarchy + tiered loading |-| **Mem0** | Cloud/Self-hosted | Free/Paid | 4 | `mem0ai` | Server-side LLM extraction + self-hosted/OSS modes |+| **Mem0** (plugin catalog) | Cloud/Self-hosted | Free/Paid | 4 | `hermes plugins install mem0` | Server-side LLM extraction + self-hosted/OSS modes || **Hindsight** (plugin catalog) | Cloud/Local | Free/Paid | 3 | `hermes plugins install hindsight` | Knowledge graph + reflect synthesis || **Holographic** | Local | Free | 2 | None | HRR algebra + trust scoring || **RetainDB** | Cloud | $20/mo | 10 | `requests` | Delta compression |@@ -768,8 +782,9 @@ Each provider's data is isolated per [profile](../profiles.md):Memory providers are moving out of the Hermes tree into their maintainers' own repositories,published through the [plugin catalog](./plugins.md). Hindsight moved first (see[Migrating from bundled Hindsight](#migrating-from-bundled-hindsight)), then Honcho (see-[Upgrading from the bundled Honcho](#upgrading-from-the-bundled-honcho)) and Supermemory (see-[Migrating from bundled Supermemory](#migrating-from-bundled-supermemory)). Nothing changes for you: the+[Upgrading from the bundled Honcho](#upgrading-from-the-bundled-honcho)), Supermemory (see+[Migrating from bundled Supermemory](#migrating-from-bundled-supermemory)) and Mem0 (see+[Migrating from bundled Mem0](#migrating-from-bundled-mem0)). Nothing changes for you: theprovider name, the settings it reads, its data directory and its tools stay the same.When a provider you have configured stops shipping with Hermes, `hermes update` installs itscatalog plugin for every profile that names it; if you update through the Desktop app, thediff --git a/website/docs/user-guide/features/memory.md b/website/docs/user-guide/features/memory.mdindex 67d529647a4..9b249886cd6 100644--- a/website/docs/user-guide/features/memory.md+++ b/website/docs/user-guide/features/memory.md@@ -506,7 +506,7 @@ Full details in [Gating agent skill writes](./skills.md#gating-agent-skill-write## External Memory Providers-For deeper, persistent memory that goes beyond MEMORY.md and USER.md, Hermes ships with 5 external memory provider plugins — OpenViking, Mem0, Holographic, RetainDB and ByteRover — and more, such as Honcho, Hindsight and Supermemory, are available from the [plugin catalog](plugins.md) via `hermes plugins install <name>`.+For deeper, persistent memory that goes beyond MEMORY.md and USER.md, Hermes ships with 4 external memory provider plugins — OpenViking, Holographic, RetainDB and ByteRover — and more, such as Honcho, Hindsight, Supermemory and Mem0, are available from the [plugin catalog](plugins.md) via `hermes plugins install <name>`.External providers run **alongside** built-in memory (never replacing it) and add capabilities like knowledge graphs, semantic search, automatic fact extraction, and cross-session user modeling.diff --git a/website/docs/user-guide/features/overview.md b/website/docs/user-guide/features/overview.mdindex 85f39232fd2..d13c71960df 100644--- a/website/docs/user-guide/features/overview.md+++ b/website/docs/user-guide/features/overview.md@@ -45,7 +45,7 @@ Hermes Agent includes a rich set of capabilities that extend far beyond basic ch- **[Fallback Providers](fallback-providers.md)** — Automatic failover to backup LLM providers when your primary model encounters errors, including independent fallback for auxiliary tasks like vision and compression.- **[Credential Pools](credential-pools.md)** — Distribute API calls across multiple keys for the same provider. Automatic rotation on rate limits or failures.- **[Prompt caching](../configuration#prompt-caching)** — Built-in cross-session 1-hour prefix cache for Claude on native Anthropic, OpenRouter, and Nous Portal. Always-on; no configuration required.-- **[Memory Providers](memory-providers.md)** — Plug in external memory backends (OpenViking, Mem0, Holographic, RetainDB, ByteRover, plus Honcho, Hindsight and Supermemory from the plugin catalog) for cross-session user modeling and personalization beyond the built-in memory system.+- **[Memory Providers](memory-providers.md)** — Plug in external memory backends (OpenViking, Holographic, RetainDB, ByteRover, plus Honcho, Hindsight, Supermemory and Mem0 from the plugin catalog) for cross-session user modeling and personalization beyond the built-in memory system.- **[API Server](api-server.md)** — Expose Hermes as an OpenAI-compatible HTTP endpoint. Connect any frontend that speaks the OpenAI format — Open WebUI, LobeChat, LibreChat, and more.- **[IDE Integration (ACP)](acp.md)** — Use Hermes inside ACP-compatible editors such as VS Code, Zed, and JetBrains. Chat, tool activity, file diffs, and terminal commands render inside your editor.- **[Batch Processing](batch-processing.md)** — Run the agent over many prompts or tasks in parallel from the CLI, with structured outputs and trajectory capture suitable for evals or downstream training pipelines.diff --git a/website/docs/user-guide/windows-native.md b/website/docs/user-guide/windows-native.mdindex c9784b16d74..be6fac37613 100644--- a/website/docs/user-guide/windows-native.md+++ b/website/docs/user-guide/windows-native.md@@ -136,7 +136,7 @@ unavailable; WSL is an alternative, not a requirement of the current design.- Matrix's native encrypted adapter is Linux-only; use a supported proxy routeor a Linux backend on Windows.-- Native Windows ARM64 excludes the `mem0` and `google-chat` SDK extras, and+- Native Windows ARM64 excludes the `google-chat` SDK extra andthe openWakeWord engine. Sherpa supports native Windows ARM64 and is theautomatic wake-word default on that target.- Local Faster-Whisper STT is excluded on native Windows ARM64. Use a cloud