diff --git a/README.md b/README.md index 20884ba57e..2f6e0c2fe2 100644 --- a/README.md +++ b/README.md @@ -801,6 +801,7 @@ The agentmemory entry is the **same MCP server block** across every host that us | **Zed** | `~/.config/zed/settings.json` | `agentmemory connect zed` writes under `context_servers` (Zed's key, NOT `mcpServers`). Remote MCP servers can be wired via `{"url": "..."}` instead. | | **Droid (Factory.ai)** | `~/.factory/mcp.json` | `agentmemory connect droid` writes the standard `mcpServers` block. Project-scoped overrides go in `/.factory/mcp.json`. Pass `--with-hooks` for native auto-capture. | | **DeepSeek Harness** | `$DSH_HOME/cordis.patch.yml` | `agentmemory connect dsh` appends an `@deepseek-ai/dsh-mcp-client` row to the home-level patch layer every Harness profile loads; tools register as `mcp__agentmemory__*`. Pass `--with-hooks` to also wire auto-capture: the bundled Claude Code hook scripts run through Harness's first-party `@deepseek-ai/dsh-hooks-claude-code` bridge (SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, Stop) via a manifest written to `$DSH_HOME/agentmemory.hooks.json`. Defaults to `~/.dsh` when `DSH_HOME` is unset. | +| **DeepSeek Harness (native capture)** | `plugin/dsh/` | Install the local native package for session capture, recall, approval events, and compaction persistence. Use it instead of the optional Claude Code hooks bridge. See [setup](plugin/dsh/README.md). | | **Goose** | Goose MCP settings UI | Same `mcpServers` block; use `goose configure` → Add Extension → MCP. Direct YAML edit at `~/.config/goose/config.yaml` is supported but the schema uses `extensions:` + `cmd` (not `mcpServers:` + `command`). | | **Aider** | n/a | Talk to the REST API directly: `curl -X POST http://localhost:3111/agentmemory/smart-search -d '{"query": "auth"}'`. | | **Any agent (32+)** | n/a | `npx skillkit install agentmemory` auto-detects the host and merges. | @@ -1435,7 +1436,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Custom plugin systems | `iii worker add ` | -**242 source files · ~55,000 LOC · 3,400+ tests · 324 functions · 67 KV scopes**, all on three primitives. No `agentmemory plugin install`. The plugin system is iii itself. +**243 source files · ~55,000 LOC · 3,400+ tests · 324 functions · 67 KV scopes**, all on three primitives. No `agentmemory plugin install`. The plugin system is iii itself. --- diff --git a/READMEs/README.ar-SA.md b/READMEs/README.ar-SA.md index 72016f76f9..d00df2e954 100644 --- a/READMEs/README.ar-SA.md +++ b/READMEs/README.ar-SA.md @@ -1439,7 +1439,7 @@ fi | Prometheus / Grafana | OTEL في iii + مراقب الحالة الصحية | | أنظمة إضافات مخصصة | `iii worker add ` | -**242 ملف مصدري · ~55,000 سطر برمجي · 3,800+ اختبار · 324 دالة · 67 نطاق KV**، كل ذلك على ثلاث بنى أساسية. لا يوجد أمر `agentmemory plugin install`. نظام الإضافات هو iii نفسه. +**243 ملف مصدري · ~55,000 سطر برمجي · 3,800+ اختبار · 324 دالة · 67 نطاق KV**، كل ذلك على ثلاث بنى أساسية. لا يوجد أمر `agentmemory plugin install`. نظام الإضافات هو iii نفسه. --- diff --git a/READMEs/README.bn-BD.md b/READMEs/README.bn-BD.md index d012d01684..4813096b60 100644 --- a/READMEs/README.bn-BD.md +++ b/READMEs/README.bn-BD.md @@ -1437,7 +1437,7 @@ fi | Prometheus / Grafana | iii OTEL + হেলথ মনিটর | | কাস্টম প্লাগইন সিস্টেম | `iii worker add ` | -**242 সোর্স ফাইল · ~55,000 LOC · 3,400+ টেস্ট · 324 ফাংশন · 67 KV স্কোপ**, সবকিছু তিনটি প্রিমিটিভের উপর। কোনো `agentmemory plugin install` নেই। প্লাগইন সিস্টেমটাই iii নিজে। +**243 সোর্স ফাইল · ~55,000 LOC · 3,400+ টেস্ট · 324 ফাংশন · 67 KV স্কোপ**, সবকিছু তিনটি প্রিমিটিভের উপর। কোনো `agentmemory plugin install` নেই। প্লাগইন সিস্টেমটাই iii নিজে। --- diff --git a/READMEs/README.cs-CZ.md b/READMEs/README.cs-CZ.md index 95ba136864..154b822780 100644 --- a/READMEs/README.cs-CZ.md +++ b/READMEs/README.cs-CZ.md @@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Vlastní systémy pluginů | `iii worker add ` | -**242 zdrojových souborů · ~55,000 řádků kódu · 3,400+ testů · 324 funkcí · 67 KV scopes**, vše na třech primitivech. Žádné `agentmemory plugin install`. Systém pluginů je samo iii. +**243 zdrojových souborů · ~55,000 řádků kódu · 3,400+ testů · 324 funkcí · 67 KV scopes**, vše na třech primitivech. Žádné `agentmemory plugin install`. Systém pluginů je samo iii. --- diff --git a/READMEs/README.da-DK.md b/READMEs/README.da-DK.md index c031a1fb53..33b933b557 100644 --- a/READMEs/README.da-DK.md +++ b/READMEs/README.da-DK.md @@ -1436,7 +1436,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Custom plugin-systemer | `iii worker add ` | -**242 kildefiler · ~55,000 LOC · 3,400+ tests · 324 funktioner · 67 KV-scopes**, alt på tre primitiver. Intet `agentmemory plugin install`. Plugin-systemet er iii selv. +**243 kildefiler · ~55,000 LOC · 3,400+ tests · 324 funktioner · 67 KV-scopes**, alt på tre primitiver. Intet `agentmemory plugin install`. Plugin-systemet er iii selv. --- diff --git a/READMEs/README.de-DE.md b/READMEs/README.de-DE.md index 731b701bc9..2d7e0ab123 100644 --- a/READMEs/README.de-DE.md +++ b/READMEs/README.de-DE.md @@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + Health-Monitor | | Eigene Plugin-Systeme | `iii worker add ` | -**242 Quelldateien · ~55,000 LOC · 3,400+ Tests · 324 Funktionen · 67 KV-Scopes**, alles auf drei Primitiven. Kein `agentmemory plugin install`. Das Plugin-System ist iii selbst. +**243 Quelldateien · ~55,000 LOC · 3,400+ Tests · 324 Funktionen · 67 KV-Scopes**, alles auf drei Primitiven. Kein `agentmemory plugin install`. Das Plugin-System ist iii selbst. --- diff --git a/READMEs/README.el-GR.md b/READMEs/README.el-GR.md index 507f8d6cf7..8e76b7f970 100644 --- a/READMEs/README.el-GR.md +++ b/READMEs/README.el-GR.md @@ -1438,7 +1438,7 @@ fi | Prometheus / Grafana | iii OTEL + monitor υγείας | | Προσαρμοσμένα συστήματα plugin | `iii worker add ` | -**242 αρχεία πηγαίου κώδικα · ~55,000 LOC · 3,400+ δοκιμές · 324 functions · 67 KV scopes**, όλα πάνω σε τρία primitives. Δεν υπάρχει `agentmemory plugin install`. Το σύστημα plugin είναι το ίδιο το iii. +**243 αρχεία πηγαίου κώδικα · ~55,000 LOC · 3,400+ δοκιμές · 324 functions · 67 KV scopes**, όλα πάνω σε τρία primitives. Δεν υπάρχει `agentmemory plugin install`. Το σύστημα plugin είναι το ίδιο το iii. --- diff --git a/READMEs/README.es-ES.md b/READMEs/README.es-ES.md index 62192cea9f..a3c82f00b1 100644 --- a/READMEs/README.es-ES.md +++ b/READMEs/README.es-ES.md @@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + monitor de salud | | Sistemas de plugins propios | `iii worker add ` | -**242 ficheros de código · ~55,000 LOC · 3,400+ tests · 324 funciones · 67 scopes KV**, todo sobre tres primitivos. No hay `agentmemory plugin install`. El sistema de plugins es iii mismo. +**243 ficheros de código · ~55,000 LOC · 3,400+ tests · 324 funciones · 67 scopes KV**, todo sobre tres primitivos. No hay `agentmemory plugin install`. El sistema de plugins es iii mismo. --- diff --git a/READMEs/README.fi-FI.md b/READMEs/README.fi-FI.md index 0d76a764ae..53ebe12411 100644 --- a/READMEs/README.fi-FI.md +++ b/READMEs/README.fi-FI.md @@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + terveysmonitori | | Mukautetut plugin-järjestelmät | `iii worker add ` | -**242 lähdetiedostoa · ~55,000 LOC · 3,400+ testiä · 324 funktiota · 67 KV-scopea**, kaikki kolmen primitiivin päällä. Ei `agentmemory plugin install` -komentoa. Plugin-järjestelmä on iii itse. +**243 lähdetiedostoa · ~55,000 LOC · 3,400+ testiä · 324 funktiota · 67 KV-scopea**, kaikki kolmen primitiivin päällä. Ei `agentmemory plugin install` -komentoa. Plugin-järjestelmä on iii itse. --- diff --git a/READMEs/README.fr-FR.md b/READMEs/README.fr-FR.md index acd4fc2e55..15ed66c9ea 100644 --- a/READMEs/README.fr-FR.md +++ b/READMEs/README.fr-FR.md @@ -1448,7 +1448,7 @@ fi | Prometheus / Grafana | iii OTEL + moniteur de santé | | Systèmes de plugins custom | `iii worker add ` | -**242 fichiers sources · ~55,000 LOC · 3,800+ tests · 324 fonctions · 67 scopes KV**, tout sur trois primitives. Pas de `agentmemory plugin install`. Le système de plugins, c'est iii lui-même. +**243 fichiers sources · ~55,000 LOC · 3,800+ tests · 324 fonctions · 67 scopes KV**, tout sur trois primitives. Pas de `agentmemory plugin install`. Le système de plugins, c'est iii lui-même. --- diff --git a/READMEs/README.he-IL.md b/READMEs/README.he-IL.md index 71e0f857b4..2bc720f071 100644 --- a/READMEs/README.he-IL.md +++ b/READMEs/README.he-IL.md @@ -1439,7 +1439,7 @@ fi | Prometheus / Grafana | iii OTEL + מוניטור health | | מערכות plugin מותאמות אישית | `iii worker add ` | -**242 קבצי מקור · ~55,000 LOC · 3,400+ בדיקות · 324 פונקציות · 67 תחומי KV**, הכול על שלושה primitives. אין `agentmemory plugin install`. מערכת ה-plugin היא iii עצמו. +**243 קבצי מקור · ~55,000 LOC · 3,400+ בדיקות · 324 פונקציות · 67 תחומי KV**, הכול על שלושה primitives. אין `agentmemory plugin install`. מערכת ה-plugin היא iii עצמו. --- diff --git a/READMEs/README.hi-IN.md b/READMEs/README.hi-IN.md index 167d6b6c9f..d00e10c842 100644 --- a/READMEs/README.hi-IN.md +++ b/READMEs/README.hi-IN.md @@ -1449,7 +1449,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Custom plugin systems | `iii worker add ` | -**242 source files · ~55,000 LOC · 3,400+ tests · 324 functions · 67 KV scopes**, सब कुछ तीन primitives पर। कोई `agentmemory plugin install` नहीं। Plugin system iii स्वयं है। +**243 source files · ~55,000 LOC · 3,400+ tests · 324 functions · 67 KV scopes**, सब कुछ तीन primitives पर। कोई `agentmemory plugin install` नहीं। Plugin system iii स्वयं है। --- diff --git a/READMEs/README.hu-HU.md b/READMEs/README.hu-HU.md index 0d4944a3ca..fc28842808 100644 --- a/READMEs/README.hu-HU.md +++ b/READMEs/README.hu-HU.md @@ -1446,7 +1446,7 @@ A `/agentmemory/export` emellett elfogadja a `?maxSessions=`-t és a `?offset=`- | Prometheus / Grafana | iii OTEL + egészségfigyelő | | Egyéni plugin-rendszerek | `iii worker add ` | -**242 forrásfájl · ~55,000 LOC · 3,400+ teszt · 324 funkció · 67 KV-hatókör**, mindez három primitíven. Nincs `agentmemory plugin install`. A plugin-rendszer maga az iii. +**243 forrásfájl · ~55,000 LOC · 3,400+ teszt · 324 funkció · 67 KV-hatókör**, mindez három primitíven. Nincs `agentmemory plugin install`. A plugin-rendszer maga az iii. --- diff --git a/READMEs/README.id-ID.md b/READMEs/README.id-ID.md index 06a26bf123..fe7893930a 100644 --- a/READMEs/README.id-ID.md +++ b/READMEs/README.id-ID.md @@ -1447,7 +1447,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Sistem plugin custom | `iii worker add ` | -**242 file sumber · ~55,000 LOC · 3,800+ pengujian · 324 fungsi · 67 scope KV**, semua di atas tiga primitif. Tidak ada `agentmemory plugin install`. Sistem plugin-nya adalah iii itu sendiri. +**243 file sumber · ~55,000 LOC · 3,800+ pengujian · 324 fungsi · 67 scope KV**, semua di atas tiga primitif. Tidak ada `agentmemory plugin install`. Sistem plugin-nya adalah iii itu sendiri. --- diff --git a/READMEs/README.it-IT.md b/READMEs/README.it-IT.md index c779fe76e4..7d49aaf090 100644 --- a/READMEs/README.it-IT.md +++ b/READMEs/README.it-IT.md @@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + monitor di salute | | Sistemi di plugin personalizzati | `iii worker add ` | -**242 file sorgente · ~55,000 righe di codice · 3,400+ test · 324 funzioni · 67 scope KV**, tutto su tre primitive. Nessun `agentmemory plugin install`. Il sistema di plugin è iii stesso. +**243 file sorgente · ~55,000 righe di codice · 3,400+ test · 324 funzioni · 67 scope KV**, tutto su tre primitive. Nessun `agentmemory plugin install`. Il sistema di plugin è iii stesso. --- diff --git a/READMEs/README.ja-JP.md b/READMEs/README.ja-JP.md index 7b080f72eb..222fa07464 100644 --- a/READMEs/README.ja-JP.md +++ b/READMEs/README.ja-JP.md @@ -1445,7 +1445,7 @@ fi | Prometheus / Grafana | iii OTEL + ヘルスモニタ | | カスタムプラグインシステム | `iii worker add ` | -**242 ソースファイル · ~55,000 LOC · 3,400+ テスト · 324 functions · 67 KV スコープ** — すべて 3 つのプリミティブの上に。`agentmemory plugin install` はありません。プラグインシステムは iii そのものです。 +**243 ソースファイル · ~55,000 LOC · 3,400+ テスト · 324 functions · 67 KV スコープ** — すべて 3 つのプリミティブの上に。`agentmemory plugin install` はありません。プラグインシステムは iii そのものです。 --- diff --git a/READMEs/README.ko-KR.md b/READMEs/README.ko-KR.md index 6ca420d444..8b55554892 100644 --- a/READMEs/README.ko-KR.md +++ b/READMEs/README.ko-KR.md @@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + health 모니터 | | 커스텀 플러그인 시스템 | `iii worker add ` | -**소스 파일 242개 · LOC ~55,000줄 · 테스트 3,400+개 · 함수 324개 · KV 스코프 67개**, 모두 세 가지 프리미티브 위에서 동작합니다. `agentmemory plugin install` 같은 것은 없습니다. 플러그인 시스템은 곧 iii 자체입니다. +**소스 파일 243개 · LOC ~55,000줄 · 테스트 3,400+개 · 함수 324개 · KV 스코프 67개**, 모두 세 가지 프리미티브 위에서 동작합니다. `agentmemory plugin install` 같은 것은 없습니다. 플러그인 시스템은 곧 iii 자체입니다. --- diff --git a/READMEs/README.nb-NO.md b/READMEs/README.nb-NO.md index 67ca2ce102..a82c659427 100644 --- a/READMEs/README.nb-NO.md +++ b/READMEs/README.nb-NO.md @@ -1447,7 +1447,7 @@ fi | Prometheus / Grafana | iii OTEL + helseovervåker | | Egendefinerte plugin-systemer | `iii worker add ` | -**242 kildefiler · ~55,000 LOC · 3,400+ tester · 324 funksjoner · 67 KV-scopes**, alt på tre primitiver. Ingen `agentmemory plugin install`. Plugin-systemet er iii selv. +**243 kildefiler · ~55,000 LOC · 3,400+ tester · 324 funksjoner · 67 KV-scopes**, alt på tre primitiver. Ingen `agentmemory plugin install`. Plugin-systemet er iii selv. --- diff --git a/READMEs/README.nl-NL.md b/READMEs/README.nl-NL.md index 18fa654806..d8039b5969 100644 --- a/READMEs/README.nl-NL.md +++ b/READMEs/README.nl-NL.md @@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Custom plugin-systemen | `iii worker add ` | -**242 bronbestanden · ~55,000 LOC · 3,400+ tests · 324 functies · 67 KV-scopes**, allemaal op drie primitieven. Geen `agentmemory plugin install`. Het pluginsysteem is iii zelf. +**243 bronbestanden · ~55,000 LOC · 3,400+ tests · 324 functies · 67 KV-scopes**, allemaal op drie primitieven. Geen `agentmemory plugin install`. Het pluginsysteem is iii zelf. --- diff --git a/READMEs/README.pl-PL.md b/READMEs/README.pl-PL.md index 9ee733cdfc..071796aa51 100644 --- a/READMEs/README.pl-PL.md +++ b/READMEs/README.pl-PL.md @@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + monitor stanu | | Niestandardowe systemy pluginów | `iii worker add ` | -**242 pliki źródłowe · ~55,000 LOC · 3,800+ testów · 324 funkcje · 67 zakresów KV**, wszystko na trzech prymitywach. Nie ma `agentmemory plugin install`. Systemem pluginów jest sam iii. +**243 pliki źródłowe · ~55,000 LOC · 3,800+ testów · 324 funkcje · 67 zakresów KV**, wszystko na trzech prymitywach. Nie ma `agentmemory plugin install`. Systemem pluginów jest sam iii. --- diff --git a/READMEs/README.pt-BR.md b/READMEs/README.pt-BR.md index 081630adf3..6a4524693d 100644 --- a/READMEs/README.pt-BR.md +++ b/READMEs/README.pt-BR.md @@ -1447,7 +1447,7 @@ fi | Prometheus / Grafana | iii OTEL + monitor de saúde | | Sistemas de plugin customizados | `iii worker add ` | -**242 arquivos de código · ~55,000 LOC · 3,400+ testes · 324 funções · 67 escopos KV**, tudo em cima de três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii. +**243 arquivos de código · ~55,000 LOC · 3,400+ testes · 324 funções · 67 escopos KV**, tudo em cima de três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii. --- diff --git a/READMEs/README.pt-PT.md b/READMEs/README.pt-PT.md index fa45a413fa..eb781087fb 100644 --- a/READMEs/README.pt-PT.md +++ b/READMEs/README.pt-PT.md @@ -1446,7 +1446,7 @@ O `/agentmemory/export` também aceita `?maxSessions=` e `?offset=` para dividir | Prometheus / Grafana | iii OTEL + monitor de saúde | | Sistemas de plugins personalizados | `iii worker add ` | -**242 ficheiros de código-fonte · ~55,000 LOC · 3,400+ testes · 324 funções · 67 âmbitos de KV**, tudo sobre três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii. +**243 ficheiros de código-fonte · ~55,000 LOC · 3,400+ testes · 324 funções · 67 âmbitos de KV**, tudo sobre três primitivos. Sem `agentmemory plugin install`. O sistema de plugins é o próprio iii. --- diff --git a/READMEs/README.ro-RO.md b/READMEs/README.ro-RO.md index ae1772b7e3..1c8bf7ccf4 100644 --- a/READMEs/README.ro-RO.md +++ b/READMEs/README.ro-RO.md @@ -1430,7 +1430,7 @@ fi | Prometheus / Grafana | iii OTEL + monitor de sănătate | | Sisteme de plugin-uri personalizate | `iii worker add ` | -**242 de fișiere sursă · ~55,000 LOC · 3,800+ de teste · 324 de funcții · 67 de domenii KV**, toate pe trei primitive. Niciun `agentmemory plugin install`. Sistemul de plugin-uri este chiar iii. +**243 de fișiere sursă · ~55,000 LOC · 3,800+ de teste · 324 de funcții · 67 de domenii KV**, toate pe trei primitive. Niciun `agentmemory plugin install`. Sistemul de plugin-uri este chiar iii. --- diff --git a/READMEs/README.ru-RU.md b/READMEs/README.ru-RU.md index 3a134a08c0..3442a173e2 100644 --- a/READMEs/README.ru-RU.md +++ b/READMEs/README.ru-RU.md @@ -1446,7 +1446,7 @@ fi | Prometheus / Grafana | iii OTEL + монитор состояния | | Самописные плагинные системы | `iii worker add ` | -**242 исходных файлов · ~55,000 LOC · 3,400+ тестов · 324 функций · 67 KV-scope**, всё на трёх примитивах. Никакого `agentmemory plugin install`. Плагинная система — это сам iii. +**243 исходных файлов · ~55,000 LOC · 3,400+ тестов · 324 функций · 67 KV-scope**, всё на трёх примитивах. Никакого `agentmemory plugin install`. Плагинная система — это сам iii. --- diff --git a/READMEs/README.sv-SE.md b/READMEs/README.sv-SE.md index aff2849ccb..ed1bfbc21b 100644 --- a/READMEs/README.sv-SE.md +++ b/READMEs/README.sv-SE.md @@ -1437,7 +1437,7 @@ fi | Prometheus / Grafana | iii OTEL + hälsoövervakare | | Anpassade pluginsystem | `iii worker add ` | -**242 källkodsfiler · ~55,000 LOC · 3,400+ tester · 324 funktioner · 67 KV-scopes**, allt på tre primitiv. Inget `agentmemory plugin install`. Pluginsystemet är iii självt. +**243 källkodsfiler · ~55,000 LOC · 3,400+ tester · 324 funktioner · 67 KV-scopes**, allt på tre primitiv. Inget `agentmemory plugin install`. Pluginsystemet är iii självt. --- diff --git a/READMEs/README.th-TH.md b/READMEs/README.th-TH.md index 5332c2cb8f..3760219f38 100644 --- a/READMEs/README.th-TH.md +++ b/READMEs/README.th-TH.md @@ -1444,7 +1444,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Custom plugin systems | `iii worker add ` | -**242 source file · ~55,000 LOC · 3,400+ การทดสอบ · 324 function · 67 KV scope** ทั้งหมดอยู่บน primitive สามตัว ไม่มี `agentmemory plugin install` ระบบ plugin ก็คือ iii เองนั่นแหละ +**243 source file · ~55,000 LOC · 3,400+ การทดสอบ · 324 function · 67 KV scope** ทั้งหมดอยู่บน primitive สามตัว ไม่มี `agentmemory plugin install` ระบบ plugin ก็คือ iii เองนั่นแหละ --- diff --git a/READMEs/README.tl-PH.md b/READMEs/README.tl-PH.md index 6b12927217..19b9e7e442 100644 --- a/READMEs/README.tl-PH.md +++ b/READMEs/README.tl-PH.md @@ -1446,7 +1446,7 @@ Tinatanggap din ng `/agentmemory/export` ang `?maxSessions=` at `?offset=` para | Prometheus / Grafana | iii OTEL + health monitor | | Custom na plugin system | `iii worker add ` | -**242 na source file · ~55,000 LOC · 3,400+ na test · 324 na function · 67 na KV scope**, lahat sa tatlong primitive. Walang `agentmemory plugin install`. Ang plugin system mismo ay ang iii. +**243 na source file · ~55,000 LOC · 3,400+ na test · 324 na function · 67 na KV scope**, lahat sa tatlong primitive. Walang `agentmemory plugin install`. Ang plugin system mismo ay ang iii. --- diff --git a/READMEs/README.tr-TR.md b/READMEs/README.tr-TR.md index f99b8ac3c0..c68bd851ba 100644 --- a/READMEs/README.tr-TR.md +++ b/READMEs/README.tr-TR.md @@ -1437,7 +1437,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Custom eklenti sistemleri | `iii worker add ` | -**242 kaynak dosya · ~55,000 LOC · 3,400+ test · 324 fonksiyon · 67 KV scope**, hepsi üç primitif üzerinde. `agentmemory plugin install` yok. Eklenti sistemi, iii'nin kendisidir. +**243 kaynak dosya · ~55,000 LOC · 3,400+ test · 324 fonksiyon · 67 KV scope**, hepsi üç primitif üzerinde. `agentmemory plugin install` yok. Eklenti sistemi, iii'nin kendisidir. --- diff --git a/READMEs/README.uk-UA.md b/READMEs/README.uk-UA.md index 6a00ea24d6..be44505eb3 100644 --- a/READMEs/README.uk-UA.md +++ b/READMEs/README.uk-UA.md @@ -1447,7 +1447,7 @@ fi | Prometheus / Grafana | iii OTEL + монітор стану здоров'я | | Власні системи плагінів | `iii worker add ` | -**242 вихідних файлів · ~55,000 LOC · 3,400+ тестів · 324 функцій · 67 KV-скоупів**, усе на трьох примітивах. Жодного `agentmemory plugin install`. Система плагінів — це сам iii. +**243 вихідних файлів · ~55,000 LOC · 3,400+ тестів · 324 функцій · 67 KV-скоупів**, усе на трьох примітивах. Жодного `agentmemory plugin install`. Система плагінів — це сам iii. --- diff --git a/READMEs/README.ur-PK.md b/READMEs/README.ur-PK.md index b84cbb8192..1f2a46ebb2 100644 --- a/READMEs/README.ur-PK.md +++ b/READMEs/README.ur-PK.md @@ -1432,7 +1432,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | کسٹم plugin سسٹمز | `iii worker add ` | -**242 سورس فائلز · ~55,000 لائنز کوڈ · 3,800+ ٹیسٹس · 324 فنکشنز · 67 KV اسکوپس**، سب تین primitives پر۔ کوئی `agentmemory plugin install` نہیں۔ plugin سسٹم خود iii ہی ہے۔ +**243 سورس فائلز · ~55,000 لائنز کوڈ · 3,800+ ٹیسٹس · 324 فنکشنز · 67 KV اسکوپس**، سب تین primitives پر۔ کوئی `agentmemory plugin install` نہیں۔ plugin سسٹم خود iii ہی ہے۔ --- diff --git a/READMEs/README.vi-VN.md b/READMEs/README.vi-VN.md index f0fb2bcbda..f129ff18f4 100644 --- a/READMEs/README.vi-VN.md +++ b/READMEs/README.vi-VN.md @@ -1437,7 +1437,7 @@ fi | Prometheus / Grafana | iii OTEL + health monitor | | Hệ thống plugin tùy chỉnh | `iii worker add ` | -**242 file source · ~55,000 LOC · 3,400+ test · 324 function · 67 KV scope**, tất cả trên ba primitive. Không có `agentmemory plugin install`. Hệ thống plugin chính là iii. +**243 file source · ~55,000 LOC · 3,400+ test · 324 function · 67 KV scope**, tất cả trên ba primitive. Không có `agentmemory plugin install`. Hệ thống plugin chính là iii. --- diff --git a/READMEs/README.zh-CN.md b/READMEs/README.zh-CN.md index 029a966bb3..cae704af1c 100644 --- a/READMEs/README.zh-CN.md +++ b/READMEs/README.zh-CN.md @@ -1444,7 +1444,7 @@ fi | Prometheus / Grafana | iii OTEL + 健康监控 | | Custom plugin systems | `iii worker add ` | -**242 个源文件 · ~55,000 行代码 · 3,400+ 个测试 · 324 个函数 · 67 个 KV 作用域**,全部基于三种原语。没有 `agentmemory plugin install`。插件系统就是 iii 本身。 +**243 个源文件 · ~55,000 行代码 · 3,400+ 个测试 · 324 个函数 · 67 个 KV 作用域**,全部基于三种原语。没有 `agentmemory plugin install`。插件系统就是 iii 本身。 --- diff --git a/READMEs/README.zh-TW.md b/READMEs/README.zh-TW.md index 568eabdee8..68c1e45568 100644 --- a/READMEs/README.zh-TW.md +++ b/READMEs/README.zh-TW.md @@ -1430,7 +1430,7 @@ fi | Prometheus / Grafana | iii OTEL + 健康監控 | | 自訂外掛系統 | `iii worker add ` | -**242 個原始檔 · ~55,000 行程式碼 · 3,400+ 測試 · 324 個函式 · 67 個 KV 範圍**,全部基於三種原語。沒有 `agentmemory plugin install`。外掛系統就是 iii 本身。 +**243 個原始檔 · ~55,000 行程式碼 · 3,400+ 測試 · 324 個函式 · 67 個 KV 範圍**,全部基於三種原語。沒有 `agentmemory plugin install`。外掛系統就是 iii 本身。 --- diff --git a/docs/dsh-integration.md b/docs/dsh-integration.md new file mode 100644 index 0000000000..bfe590b7c1 --- /dev/null +++ b/docs/dsh-integration.md @@ -0,0 +1,51 @@ +# AgentMemory for DeepSeek Harness + +## Background + +dsh (DeepSeek Harness) is a cordis-based agent harness with no long-term memory: session transcripts and compaction summaries stay per-session and are not semantically retrievable. The integration uses AgentMemory's REST lifecycle endpoints (`/session/start`, `/observe`, `/context`, `/session/end`, `/remember`) and MCP server (`@agentmemory/mcp`). + +## Architecture (four layers) + +| Layer | What | Where | +|---|---|---| +| L1 MCP bridge | `mcp__agentmemory__*` tools via `@deepseek-ai/dsh-mcp-client` (stdio → `@agentmemory/mcp` shim, proxies to the daemon; reduced local fallback when unreachable) | `$DSH_HOME/cordis.patch.yml` entry, written by `agentmemory connect dsh` | +| L2 Behavior guidance | memory-usage guideline injected into every session (`~/.dsh/AGENTS.md`, read by dsh-agent-instructions) + `agentmemory-sync` skill (`~/.dsh/skills/`) | `agentmemory connect dsh --guidelines`; optional skill copied from `plugin/dsh/install/skills/` | +| L3 Auto-capture plugin | `@agentmemory/dsh` cordis plugin: session lifecycle → REST | `plugin/dsh/` | +| L4 Deep collaboration | per-agent isolation (`agentId`), compaction bridge, team memory | plugin config / future | + +## Event mapping: agentmemory hooks ↔ dsh events + +The native plugin maps Harness lifecycle events to the AgentMemory API: + +| agentmemory hook (Claude Code) | dsh event | Form | +|---|---|---| +| SessionStart | `session/created` → `POST /agentmemory/session/start` | injecting (await + timeout + fail silent) | +| SessionStart stdout injection | `agent/pre-step` (step 1) middleware → first-step batch fold (idempotent per session) | injecting | +| UserPromptSubmit | `session/event` (`user/message`) → `/observe prompt_submit` | telemetry (fire-and-forget) | +| PreToolUse (matcher) | `session/event` (`tool/call`) → `/observe post_tool_use` (`mcp__agentmemory__*` self-calls filtered) | telemetry | +| Notification | `session/event` (`approval/asked`) → `/observe notification` (allowlisted fields) | telemetry | +| Stop / SessionEnd | `session/disposed` → `POST /agentmemory/session/end` | telemetry (30s, promise-tracked) | +| PreCompact | `session/event` (`compaction/summary`) → `POST /agentmemory/remember` (compaction bridge) | telemetry | + +Verified with `@deepseek-ai/dsh@0.2.1-rc.2`: session lifecycle handlers receive a session object; `agent/pre-step(payload, next)` is middleware; `session/event(session, event)` carries `user/message`, `tool/call`, `approval/asked`, and `compaction/summary`. Tool arguments are JSON strings and compaction summaries are content-block arrays. Synthetic user messages are excluded from prompt capture. + +## Design contract (same as the official hooks) + +- Injecting handlers **await + time out + fail silently**; they never throw into cordis (`signal.aborted` returns the unmodified decision). +- Telemetry handlers are **fire-and-forget** and never block the agent loop; plugin teardown waits for pending requests and completes tracked sessions. Forced termination can still interrupt requests. +- Project resolution (`git rev-parse`) is cached per cwd — no child process per event; per-session `{cwd, project}` captured at `session/created`. +- Zero runtime dependencies: the plugin is a thin REST bridge (Node built-ins only), so dsh `file:` consumers need no build step; `lib/` is committed (repo convention, cf. `plugin/scripts/*.mjs`). + +## Install and verify + +Follow [the plugin installation guide](../plugin/dsh/README.md) to build and install the local package into the profile you run. The scoped `@agentmemory/dsh` package is not published yet. The MCP bridge supplies tools; the native plugin supplies automatic capture. Avoid enabling the Claude Code hooks bridge alongside the native plugin, which would duplicate capture. Native entries use `id: agentmemory-capture`; rename an older native `id: agentmemory` entry before adding the current MCP adapter. Reinstalling preserves an existing native entry and does not rename it automatically. + +Set `AGENTMEMORY_URL` and `AGENTMEMORY_SECRET` before launching Harness. MCP subprocesses scrub secret-like environment variables, so the configuration explicitly forwards the secret using `!!js process.env.AGENTMEMORY_SECRET`. Configuration files contain the variable reference, never the credential. + +Start a new session, save a distinctive fact using `mcp__agentmemory__memory_save`, then recall it using `mcp__agentmemory__memory_recall`. Verify session completion and observations through the authenticated API examples in the plugin guide. A successful CLI exit alone does not confirm plugin activation: inspect Harness startup warnings for missing packages. + +## Verification + +The native plugin was exercised in the real Harness CLI with a local scripted model endpoint and real AgentMemory daemons on iii 0.22 and 0.24.6. Checks covered MCP save/recall, first-step injection, prompt capture, approval events, compaction persistence, and normal process shutdown. Model inference was scripted; the host, Cordis lifecycle, MCP transport, and daemon were real. + +Run `npm test`, `npm run typecheck`, and `npm run build` from `plugin/dsh`. The generated package must contain `lib/index.js` and `lib/index.d.ts`; install the packed archive for a final host smoke test. diff --git a/plugin/dsh/README.md b/plugin/dsh/README.md new file mode 100644 index 0000000000..8bab2575aa --- /dev/null +++ b/plugin/dsh/README.md @@ -0,0 +1,101 @@ +# @agentmemory/dsh — agentmemory for DeepSeek Harness + +A cordis plugin that connects agentmemory's long-term memory to DeepSeek Harness (dsh). It registers sessions on start, injects recalled context into the first step, captures user messages and tool calls, bridges compaction summaries into the memory store, and summarizes sessions on dispose — mirroring the official agentmemory hooks for Claude Code on dsh's event stream. + +| agentmemory hook (Claude Code) | This plugin (dsh event) | Form | +|---|---|---| +| SessionStart | `session/created` → `POST /agentmemory/session/start` | injecting (await + timeout + fail silent) | +| SessionStart stdout injection | `agent/pre-step` (step 1) middleware → first-step batch fold | injecting | +| UserPromptSubmit | `session/event` (`user/message`) → `/observe prompt_submit` | telemetry (fire-and-forget) | +| PreToolUse (matcher) | `session/event` (`tool/call`) → `/observe post_tool_use` (filters `mcp__agentmemory__*` self-calls) | telemetry | +| Notification | `session/event` (`approval/asked`) → `/observe notification` (allowlisted fields) | telemetry | +| Stop / SessionEnd | `session/disposed` → `POST /agentmemory/session/end` | telemetry (30s, tracked) | +| PreCompact | `compaction/summary` → `POST /agentmemory/remember` (compaction bridge) | telemetry | + +## Install + +Prerequisite: the agentmemory daemon is running (`npx @agentmemory/agentmemory`, REST `http://localhost:3111`). + +### 1. MCP bridge (tools, optional but recommended) + +Run `agentmemory connect dsh` to configure the MCP bridge in `$DSH_HOME/cordis.patch.yml` (default `~/.dsh`), shared by every profile. Add `--guidelines` for the memory guidance. Do not add a second MCP entry in a profile; keep any existing customized entry in one location. + +### 2. Plugin (auto-capture) + +The scoped package is not published yet. Install it from a local checkout: + +```bash +cd /path/to/agentmemory/plugin/dsh +npm install +npm run build +npm pack +dsh plugin --profile web add /path/to/agentmemory/plugin/dsh/agentmemory-dsh-0.1.0.tgz +``` + +Replace `web` with the profile you run (for example, `headless`). This integration is verified with `@deepseek-ai/dsh@0.2.1-rc.2`. + +Then append to that profile's `cordis.patch.yml` (defaults shown; override as needed): + +```yaml +- insert: + - id: agentmemory-capture + name: '@agentmemory/dsh' + config: + url: !!js process.env.AGENTMEMORY_URL || 'http://localhost:3111' + secret: !!js process.env.AGENTMEMORY_SECRET || '' + agentId: dsh # per-agent memory isolation + injectInstructions: true # inject memory-tool guidance on first turn + injectContext: true # inject recalled project context on first turn + injectMaxChars: 6000 # injection budget (≈2k tokens) + observeToolCalls: true # capture tool calls as observations + compactionBridge: true # persist compaction summaries as memories + summarizeOnDispose: true # LLM summary on session dispose +``` + +Use the distinct `agentmemory-capture` ID shown above; an existing MCP entry may already use `agentmemory`. Rename an older native entry if it uses that ID. Do not enable the native plugin and the optional Claude Code hooks bridge together, which would capture events twice. + +Set `AGENTMEMORY_SECRET` to the daemon's bearer secret before launching dsh. Restart dsh after installing the dependency; adding the package alone does not activate the plugin without the patch entry. + +### 3. Behavior guidance (optional) + +- Global guidance: `install/AGENTS.md` → `~/.dsh/AGENTS.md` (auto-injected into every session) +- Memory skill: `install/skills/agentmemory-sync/` → `~/.dsh/skills/agentmemory-sync/` + +## Verify + +1. The first turn of a new session should show injected recalled context/guidance. +2. `curl "${AGENTMEMORY_URL:-http://localhost:3111}/agentmemory/sessions" -H "Authorization: Bearer $AGENTMEMORY_SECRET"` lists the dsh sessions. +3. After ending a session, `curl "${AGENTMEMORY_URL:-http://localhost:3111}/agentmemory/smart-search" -H "Authorization: Bearer $AGENTMEMORY_SECRET" -H 'Content-Type: application/json' -d '{"query":""}'` recalls the new memory. + +## Development + +```bash +npm run build # tsdown → lib/index.js (zero runtime dependencies) +npm test # vitest: REST client, real event shapes, injection, capture and teardown +``` + +Injecting handlers await bounded requests; telemetry handlers do not block the agent loop. Plugin teardown waits for pending requests and completes tracked sessions; forced termination can interrupt requests. REST failures never throw into Cordis; `AGENTMEMORY_DSH_DEBUG=1` logs network errors. + +## Config + +| Field | Default | Description | +|---|---|---| +| `url` | `http://localhost:3111` | agentmemory REST base URL | +| `secret` | empty | Daemon bearer secret, supplied through the configuration environment reference | +| `agentId` | `dsh` | memory owner agent; isolation key under `AGENTMEMORY_AGENT_SCOPE=isolated` | +| `injectInstructions` | `true` | inject memory-tool guidance on the first turn | +| `injectContext` | `true` | inject `/context` recalled project context on the first turn | +| `injectMaxChars` | `6000` | total injection budget in characters | +| `observeToolCalls` | `true` | `tool/call` → `post_tool_use` observations | +| `compactionBridge` | `true` | `compaction/summary` → `/remember` | +| `summarizeOnDispose` | `true` | `session/disposed` → `/session/end` (LLM summary) | + +## Build artifacts + +`lib/index.js` and the generated `lib/index.d.ts` are committed alongside the source. After changing `src/index.ts`, run `npm run build` and commit the new `lib/`. + +## Limitations + +- Event payload fields follow the running dsh version (`session/created`/`disposed` carry the session object; `agent/pre-step` is middleware; `session/event` stream events are `{type, data}`). +- Current Harness approval events use the session stream. The direct `approval/asked` listener remains for older hosts that supply `sessionId`. +- The plugin only bridges REST; the MCP tools still need step 1's bridge. diff --git a/plugin/dsh/install/AGENTS.md b/plugin/dsh/install/AGENTS.md new file mode 100644 index 0000000000..cc3631af2c --- /dev/null +++ b/plugin/dsh/install/AGENTS.md @@ -0,0 +1,7 @@ +## Agent memory (agentmemory) + +You have persistent long-term memory via the agentmemory MCP server. Tools: `mcp__agentmemory__memory_recall`, `mcp__agentmemory__memory_smart_search`, `mcp__agentmemory__memory_save`, `mcp__agentmemory__memory_sessions`. + +- At the START of a task, call `mcp__agentmemory__memory_recall` (or `mcp__agentmemory__memory_smart_search`) to load relevant past decisions, fixes, and user preferences; do not re-ask. +- When you learn something durable (a decision, a fix, a gotcha, a preference, a project convention), call `mcp__agentmemory__memory_save` to persist it. +- Prefer recall over re-deriving; save concise reusable facts, not transcripts. diff --git a/plugin/dsh/install/skills/agentmemory-sync/SKILL.md b/plugin/dsh/install/skills/agentmemory-sync/SKILL.md new file mode 100644 index 0000000000..1371596287 --- /dev/null +++ b/plugin/dsh/install/skills/agentmemory-sync/SKILL.md @@ -0,0 +1,10 @@ +--- +name: agentmemory-sync +description: Sync with the agentmemory long-term memory at task start/end. Use when starting a new task, recalling past work, finishing a task, needing cross-session context, or reviewing what was done. +--- +# agentmemory memory sync + +1. At task start: call mcp__agentmemory__memory_recall with the task keywords and the stable project identifier used by the session, format=compact, to bring relevant history into context. +2. During the task: when you learn something durable (decision/fix/preference/convention), call mcp__agentmemory__memory_save immediately (type=fact, concepts: 2-5 keywords). +3. At task end: call mcp__agentmemory__memory_save with a short outcome summary (type=fact), and confirm the session is registered via mcp__agentmemory__memory_sessions. +4. For large handoffs: call mcp__agentmemory__memory_smart_search with expandIds to recover full results, or use mcp__agentmemory__memory_lesson_save/mcp__agentmemory__memory_lesson_recall for lessons. diff --git a/plugin/dsh/lib/index.d.ts b/plugin/dsh/lib/index.d.ts new file mode 100644 index 0000000000..fa67629812 --- /dev/null +++ b/plugin/dsh/lib/index.d.ts @@ -0,0 +1,49 @@ +//#region src/index.d.ts +type AnyListener = (...args: any[]) => unknown; +interface PluginLogger { + info(...args: unknown[]): void; + warn(...args: unknown[]): void; + error(...args: unknown[]): void; +} +interface PluginContext { + on(event: string, listener: AnyListener): void; + effect(callback: () => void | (() => void | Promise), label?: string): void; + logger: PluginLogger; +} +interface SessionLike { + id: string; + header?: { + cwd?: string; + }; +} +interface SessionEvent { + type: string; + seq?: number; + data: any; +} +interface AgentmemoryConfig { + url: string; + secret: string; + agentId: string; + injectInstructions: boolean; + injectContext: boolean; + injectMaxChars: number; + observeToolCalls: boolean; + compactionBridge: boolean; + summarizeOnDispose: boolean; +} +interface RestClient { + post(path: string, body: Record, timeoutMs?: number): Promise; + fire(path: string, body: Record, timeoutMs?: number): void; +} +declare function makeRestClient(url: string, secret: string, debug?: boolean): RestClient; +declare function resolveProjectName(cwd: string, env?: Record): string; +declare function isAgentmemoryTool(name: string): boolean; +declare function eventTextContent(content: unknown): string; +declare function userMessagePrompt(event: SessionEvent, maxChars: number): string | null; +declare function toolCallObservation(event: SessionEvent, maxChars: number): Record | null; +declare function compactionSummary(event: SessionEvent, maxChars: number): string | null; +declare const name = "agentmemory"; +declare function apply(ctx: PluginContext, rawConfig?: Partial): void; +//#endregion +export { AgentmemoryConfig, PluginContext, RestClient, SessionEvent, SessionLike, apply, compactionSummary, eventTextContent, isAgentmemoryTool, makeRestClient, name, resolveProjectName, toolCallObservation, userMessagePrompt }; \ No newline at end of file diff --git a/plugin/dsh/lib/index.js b/plugin/dsh/lib/index.js new file mode 100644 index 0000000000..a3cc33ff72 --- /dev/null +++ b/plugin/dsh/lib/index.js @@ -0,0 +1,329 @@ +import { execFileSync } from "node:child_process"; +import { basename } from "node:path"; +import { randomUUID } from "node:crypto"; +//#region src/index.ts +const DEFAULTS = { + url: "http://localhost:3111", + secret: "", + agentId: "dsh", + injectInstructions: true, + injectContext: true, + injectMaxChars: 6e3, + observeToolCalls: true, + compactionBridge: true, + summarizeOnDispose: true +}; +const PROMPT_MAX_CHARS = 8e3; +const TOOL_INPUT_MAX_CHARS = 4e3; +const COMPACTION_MAX_CHARS = 6e3; +const OBSERVE_TIMEOUT_MS = 1500; +const SESSION_START_TIMEOUT_MS = 2e3; +const CONTEXT_TIMEOUT_MS = 3e3; +const REMEMBER_TIMEOUT_MS = 5e3; +const SESSION_END_TIMEOUT_MS = 3e4; +const INSTRUCTIONS = [ + "", + "You have persistent cross-session long-term memory via agentmemory. Tools are namespaced `mcp__agentmemory__*` (memory_recall / memory_save / memory_smart_search / memory_sessions / ...).", + "- At the START of a task, call `mcp__agentmemory__memory_recall` (or `mcp__agentmemory__memory_smart_search`) to load relevant past decisions, fixes, and user preferences; do not re-ask.", + "- When you learn something durable (a decision, a fix, a gotcha, a preference, a project convention), call `mcp__agentmemory__memory_save` (concepts: 2-5 comma-separated keywords).", + "- Prefer recall over re-deriving; save concise reusable facts, not transcripts.", + "- If the user asks to forget/delete something, use `mcp__agentmemory__memory_governance_delete` (comma-separated memoryIds).", + "- Tool results are JSON — inspect them before presenting to the user.", + "" +].join("\n"); +function makeRestClient(url, secret, debug = false) { + function headers() { + const h = { "Content-Type": "application/json" }; + if (secret) h["Authorization"] = `Bearer ${secret}`; + return h; + } + async function post(path, body, timeoutMs = 3e3) { + try { + const res = await fetch(`${url}/agentmemory${path}`, { + method: "POST", + headers: headers(), + body: JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs) + }); + if (!res.ok) return null; + return await res.json(); + } catch (err) { + if (debug) console.error(`[agentmemory] POST ${path} failed:`, err.message); + return null; + } + } + function fire(path, body, timeoutMs = 1500) { + post(path, body, timeoutMs); + } + return { + post, + fire + }; +} +function resolveProjectName(cwd, env = process.env) { + const explicit = env["AGENTMEMORY_PROJECT_NAME"]?.trim(); + if (explicit) return explicit; + try { + const top = execFileSync("git", ["rev-parse", "--show-toplevel"], { + cwd, + stdio: [ + "ignore", + "pipe", + "ignore" + ], + encoding: "utf8" + }).trim(); + if (top) return basename(top); + } catch {} + return basename(cwd) || cwd; +} +function isAgentmemoryTool(name) { + return name.startsWith("mcp__agentmemory__") || name.startsWith("agentmemory_"); +} +function eventTextContent(content) { + if (typeof content === "string") return content; + if (Array.isArray(content)) return content.map((block) => { + if (typeof block === "string") return block; + if (block && typeof block === "object") { + const b = block; + if (b.type === "text" && typeof b.text === "string") return b.text; + } + return ""; + }).join("\n"); + return ""; +} +function userMessagePrompt(event, maxChars) { + if (event.type !== "user/message") return null; + if (event.data?.source?.kind && event.data.source.kind !== "user") return null; + const text = eventTextContent(event.data?.content); + if (!text.trim()) return null; + return text.slice(0, maxChars); +} +function toolCallObservation(event, maxChars) { + if (event.type !== "tool/call") return null; + const data = event.data ?? {}; + const name = typeof data.name === "string" ? data.name : ""; + if (!name || isAgentmemoryTool(name)) return null; + let input; + try { + input = (typeof data.arguments === "string" ? data.arguments : JSON.stringify(data.arguments ?? {})).slice(0, maxChars); + } catch { + input = String(data.arguments ?? "").slice(0, maxChars); + } + return { + tool_name: name, + call_id: typeof data.callId === "string" ? data.callId : null, + tool_input: input + }; +} +function compactionSummary(event, maxChars) { + if (event.type !== "compaction/summary") return null; + const data = event.data ?? {}; + const summary = eventTextContent(data.summary) || eventTextContent(data.text) || eventTextContent(data.content); + if (!summary) return null; + return summary.slice(0, maxChars); +} +const name = "agentmemory"; +function apply(ctx, rawConfig = {}) { + const cfg = { + ...DEFAULTS, + ...rawConfig + }; + const debug = process.env["AGENTMEMORY_DSH_DEBUG"] === "1"; + const rest = makeRestClient(cfg.url, cfg.secret, debug); + const logger = ctx.logger; + const startContextCache = /* @__PURE__ */ new Map(); + const injectedSessions = /* @__PURE__ */ new Set(); + const sessionInfos = /* @__PURE__ */ new Map(); + const projectNameCache = /* @__PURE__ */ new Map(); + const pendingCalls = /* @__PURE__ */ new Set(); + function sessionCwd(session) { + return session.header?.cwd || process.cwd(); + } + function cachedProjectName(cwd) { + let project = projectNameCache.get(cwd); + if (project === void 0) { + project = resolveProjectName(cwd); + projectNameCache.set(cwd, project); + } + return project; + } + function trackSession(session) { + if (!session || typeof session.id !== "string") return void 0; + const cwd = sessionCwd(session); + const info = { + cwd, + project: cachedProjectName(cwd) + }; + sessionInfos.set(session.id, info); + return info; + } + function fireObserve(sid, info, hookType, data) { + const call = rest.post("/observe", { + hookType, + sessionId: sid, + project: info.project, + cwd: info.cwd, + timestamp: (/* @__PURE__ */ new Date()).toISOString(), + data + }, OBSERVE_TIMEOUT_MS).catch(() => {}); + pendingCalls.add(call); + call.then(() => pendingCalls.delete(call)); + } + ctx.on("session/created", (session) => { + if (!session || typeof session.id !== "string") return; + const sid = session.id; + const info = trackSession(session); + if (!info) return; + const call = rest.post("/session/start", { + sessionId: sid, + project: info.project, + cwd: info.cwd, + agentId: cfg.agentId + }, SESSION_START_TIMEOUT_MS).then((result) => { + const context = result?.context; + if (typeof context === "string" && context.length > 0) startContextCache.set(sid, context); + }).catch(() => {}); + pendingCalls.add(call); + call.then(() => pendingCalls.delete(call)); + }); + ctx.on("session/event", (session, event) => { + if (!session || !event || typeof event.type !== "string") return; + const sid = session.id; + if (!sid) return; + let info = sessionInfos.get(sid); + if (!info) { + info = trackSession(session); + if (!info) return; + } + const prompt = userMessagePrompt(event, PROMPT_MAX_CHARS); + if (prompt !== null) { + fireObserve(sid, info, "prompt_submit", { userPrompt: prompt }); + return; + } + const tool = toolCallObservation(event, TOOL_INPUT_MAX_CHARS); + if (tool !== null && cfg.observeToolCalls) { + fireObserve(sid, info, "post_tool_use", tool); + return; + } + if (event.type === "approval/asked") { + const data = event.data ?? {}; + fireObserve(sid, info, "notification", { + notification_type: "permission_prompt", + tool_name: typeof data.toolName === "string" ? data.toolName.slice(0, 2e3) : "", + call_id: typeof data.callId === "string" ? data.callId.slice(0, 2e3) : null, + reason: typeof data.reason === "string" ? data.reason.slice(0, 2e3) : "" + }); + return; + } + if (cfg.compactionBridge) { + const summary = compactionSummary(event, COMPACTION_MAX_CHARS); + if (summary !== null) { + const call = rest.post("/remember", { + content: `[dsh compaction] ${summary}`, + type: "fact", + concepts: ["compaction"], + project: info.project + }, REMEMBER_TIMEOUT_MS).catch(() => {}); + pendingCalls.add(call); + call.then(() => pendingCalls.delete(call)); + } + } + }); + ctx.on("agent/pre-step", async ({ agent, messages, step, signal }, next) => { + const decision = await next(); + const session = agent?.session; + if (!session || typeof session.id !== "string") return decision; + const sid = session.id; + if (step !== 1 || injectedSessions.has(sid)) return decision; + if (decision.kind !== "enter" || !Array.isArray(decision.messages) || decision.messages.length === 0) return decision; + if (signal.aborted) return decision; + const project = (sessionInfos.get(sid) ?? trackSession(session))?.project ?? cachedProjectName(sessionCwd(session)); + const parts = []; + if (cfg.injectInstructions) parts.push(INSTRUCTIONS); + if (cfg.injectContext) { + let context = startContextCache.get(sid); + if (!context) { + const result = await rest.post("/context", { + sessionId: sid, + project + }, CONTEXT_TIMEOUT_MS); + context = typeof result?.context === "string" ? result.context : ""; + } else startContextCache.delete(sid); + if (context) parts.push(context); + } + if (parts.length === 0) return decision; + const text = parts.join("\n\n").slice(0, cfg.injectMaxChars); + const message = { + id: randomUUID(), + role: "user", + content: [{ + type: "text", + text + }], + source: { + kind: "agentmemory", + form: "memory-context" + } + }; + injectedSessions.add(sid); + const lastClaimedIndex = decision.messages.length - 1 - [...decision.messages].reverse().findIndex((m) => messages.includes(m)); + const nextMessages = decision.messages.slice(); + nextMessages.splice(lastClaimedIndex + 1, 0, message); + return { + ...decision, + messages: nextMessages + }; + }); + const APPROVAL_FIELDS = [ + "permission", + "pattern", + "title", + "tool_call_id", + "metadata" + ]; + ctx.on("approval/asked", (req) => { + const data = req ?? {}; + const sid = typeof data.sessionId === "string" ? data.sessionId : void 0; + if (!sid) return; + const info = sessionInfos.get(sid); + if (!info) return; + const payload = { notification_type: "permission_prompt" }; + for (const key of APPROVAL_FIELDS) { + const value = data[key]; + if (value === void 0) continue; + let text; + if (typeof value === "string") text = value; + else try { + text = JSON.stringify(value) ?? String(value); + } catch { + text = String(value); + } + payload[key] = text.slice(0, 2e3); + } + fireObserve(sid, info, "notification", payload); + }); + ctx.on("session/disposed", (session) => { + if (!session || typeof session.id !== "string") return; + const sid = session.id; + if (cfg.summarizeOnDispose) { + const call = rest.post("/session/end", { sessionId: sid }, SESSION_END_TIMEOUT_MS).catch(() => {}); + pendingCalls.add(call); + call.then(() => pendingCalls.delete(call)); + } + startContextCache.delete(sid); + injectedSessions.delete(sid); + sessionInfos.delete(sid); + }); + ctx.effect(() => async () => { + await Promise.allSettled([...pendingCalls]); + if (cfg.summarizeOnDispose) await Promise.allSettled([...sessionInfos.keys()].map((sessionId) => rest.post("/session/end", { sessionId }, SESSION_END_TIMEOUT_MS))); + startContextCache.clear(); + injectedSessions.clear(); + sessionInfos.clear(); + projectNameCache.clear(); + }, "agentmemory.dsh.memory"); + if (debug) logger.info(`[agentmemory] dsh plugin active: url=${cfg.url} agentId=${cfg.agentId} inject=${cfg.injectContext} observe=${cfg.observeToolCalls} compactionBridge=${cfg.compactionBridge}`); +} +//#endregion +export { apply, compactionSummary, eventTextContent, isAgentmemoryTool, makeRestClient, name, resolveProjectName, toolCallObservation, userMessagePrompt }; diff --git a/plugin/dsh/package.json b/plugin/dsh/package.json new file mode 100644 index 0000000000..aa56697ab8 --- /dev/null +++ b/plugin/dsh/package.json @@ -0,0 +1,47 @@ +{ + "name": "@agentmemory/dsh", + "version": "0.1.0", + "description": "agentmemory cordis plugin for DeepSeek Harness — auto-captures DSH session lifecycle into long-term memory (session start registration, first-step context injection, tool/prompt observations, compaction bridge, session-end summarization).", + "type": "module", + "main": "lib/index.js", + "types": "lib/index.d.ts", + "exports": { + ".": { + "types": "./lib/index.d.ts", + "default": "./lib/index.js" + }, + "./package.json": "./package.json" + }, + "files": [ + "lib", + "install", + "README.md" + ], + "keywords": [ + "dsh", + "deepseek-harness", + "agentmemory", + "memory", + "cordis", + "plugin" + ], + "license": "Apache-2.0", + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@deepseek-ai/cordis": "^4.0.1" + }, + "devDependencies": { + "@deepseek-ai/cordis": "^4.0.1", + "@types/node": "^25.9.1", + "tsdown": "^0.21.10", + "typescript": "^6.0.3", + "vitest": "^4.1.6" + }, + "scripts": { + "build": "tsdown", + "test": "vitest run", + "typecheck": "tsc --noEmit" + } +} diff --git a/plugin/dsh/src/index.ts b/plugin/dsh/src/index.ts new file mode 100644 index 0000000000..94df66c9ab --- /dev/null +++ b/plugin/dsh/src/index.ts @@ -0,0 +1,493 @@ +// @agentmemory/dsh — cordis plugin for DeepSeek Harness. +// +// Bridges DSH session lifecycle events to the agentmemory REST API, mirroring +// the official agentmemory hooks for Claude Code: +// +// session/created -> POST /agentmemory/session/start (register) +// agent/pre-step (step1) -> inject instructions + recalled context +// session/event -> user/message -> /observe prompt_submit +// tool/call -> /observe post_tool_use +// compaction/summary -> /remember (compaction bridge) +// approval/asked -> /observe notification +// session/disposed -> /agentmemory/session/end (summarize) +// +// Design contract (same as the official hooks): +// - Injecting handlers await + time out + fail silently. +// - Telemetry handlers are fire-and-forget; they never block the agent loop. +// - Anything REST-related failing logs once and never throws into cordis. + +import { execFileSync } from "node:child_process"; +import { basename } from "node:path"; +import { randomUUID } from "node:crypto"; + +// ─────────────────────────── minimal cordis surface ─────────────────────────── +// The plugin intentionally does not import @deepseek-ai/cordis so it builds and +// tests standalone; the running dsh profile supplies the real Context. +// `any` at these boundaries is deliberate: cordis dispatches heterogeneous +// payloads per event and the plugin narrows at runtime; importing the real +// types would couple the package to @deepseek-ai/cordis at build time. + +type AnyListener = (...args: any[]) => unknown; + +interface PluginLogger { + info(...args: unknown[]): void; + warn(...args: unknown[]): void; + error(...args: unknown[]): void; +} + +export interface PluginContext { + on(event: string, listener: AnyListener): void; + effect(callback: () => void | (() => void | Promise), label?: string): void; + logger: PluginLogger; +} + +export interface SessionLike { + id: string; + header?: { cwd?: string }; +} + +// Event payloads vary by event type (user/message, tool/call, compaction/...); +// consumers narrow data at runtime, so it stays `any` at this boundary. +export interface SessionEvent { + type: string; + seq?: number; + data: any; +} + +interface PreStepPayload { + agent: { session: SessionLike; inbox?: { nextStep?: unknown[] } }; + messages: unknown[]; + step: number; + signal: AbortSignal; +} + +// decision.messages mirrors the agent's claimed message batch — heterogeneous +// cordis message shapes, narrowed by the caller. +type PreStepDecision = { + kind: string; + messages: any[]; +}; + +type PreStepNext = () => Promise; + +// ─────────────────────────────── config ─────────────────────────────── + +export interface AgentmemoryConfig { + url: string; + secret: string; + agentId: string; + injectInstructions: boolean; + injectContext: boolean; + injectMaxChars: number; + observeToolCalls: boolean; + compactionBridge: boolean; + summarizeOnDispose: boolean; +} + +const DEFAULTS: AgentmemoryConfig = { + url: "http://localhost:3111", + secret: "", + agentId: "dsh", + injectInstructions: true, + injectContext: true, + injectMaxChars: 6000, + observeToolCalls: true, + compactionBridge: true, + summarizeOnDispose: true, +}; + +// Telemetry/truncation budgets and timeouts (kept in one place so operators +// can tune behavior without hunting magic numbers). +const PROMPT_MAX_CHARS = 8000; +const TOOL_INPUT_MAX_CHARS = 4000; +const COMPACTION_MAX_CHARS = 6000; +const OBSERVE_TIMEOUT_MS = 1500; +const SESSION_START_TIMEOUT_MS = 2000; +const CONTEXT_TIMEOUT_MS = 3000; +const REMEMBER_TIMEOUT_MS = 5000; +const SESSION_END_TIMEOUT_MS = 30000; + +// ─────────────────────────── static instructions ─────────────────────────── + +const INSTRUCTIONS = [ + "", + "You have persistent cross-session long-term memory via agentmemory. Tools are namespaced `mcp__agentmemory__*` (memory_recall / memory_save / memory_smart_search / memory_sessions / ...).", + "- At the START of a task, call `mcp__agentmemory__memory_recall` (or `mcp__agentmemory__memory_smart_search`) to load relevant past decisions, fixes, and user preferences; do not re-ask.", + "- When you learn something durable (a decision, a fix, a gotcha, a preference, a project convention), call `mcp__agentmemory__memory_save` (concepts: 2-5 comma-separated keywords).", + "- Prefer recall over re-deriving; save concise reusable facts, not transcripts.", + "- If the user asks to forget/delete something, use `mcp__agentmemory__memory_governance_delete` (comma-separated memoryIds).", + "- Tool results are JSON — inspect them before presenting to the user.", + "", +].join("\n"); + +// ─────────────────────────── REST client ─────────────────────────── + +export interface RestClient { + post(path: string, body: Record, timeoutMs?: number): Promise; + fire(path: string, body: Record, timeoutMs?: number): void; +} + +export function makeRestClient(url: string, secret: string, debug = false): RestClient { + function headers(): Record { + const h: Record = { "Content-Type": "application/json" }; + if (secret) h["Authorization"] = `Bearer ${secret}`; + return h; + } + + async function post(path: string, body: Record, timeoutMs = 3000): Promise { + try { + const res = await fetch(`${url}/agentmemory${path}`, { + method: "POST", + headers: headers(), + body: JSON.stringify(body), + signal: AbortSignal.timeout(timeoutMs), + }); + if (!res.ok) return null; + return (await res.json()) as T; + } catch (err) { + if (debug) console.error(`[agentmemory] POST ${path} failed:`, (err as Error).message); + return null; + } + } + + function fire(path: string, body: Record, timeoutMs = 1500): void { + void post(path, body, timeoutMs); + } + + return { post, fire }; +} + +// ─────────────────────────── project resolution ─────────────────────────── + +export function resolveProjectName( + cwd: string, + env: Record = process.env, +): string { + const explicit = env["AGENTMEMORY_PROJECT_NAME"]?.trim(); + if (explicit) return explicit; + try { + const top = execFileSync("git", ["rev-parse", "--show-toplevel"], { + cwd, + stdio: ["ignore", "pipe", "ignore"], + encoding: "utf8", + }).trim(); + if (top) return basename(top); + } catch { + // not a git repo, fall through + } + return basename(cwd) || cwd; +} + +// ─────────────────────────── pure event mapping ─────────────────────────── + +export function isAgentmemoryTool(name: string): boolean { + return name.startsWith("mcp__agentmemory__") || name.startsWith("agentmemory_"); +} + +export function eventTextContent(content: unknown): string { + if (typeof content === "string") return content; + if (Array.isArray(content)) { + return content + .map((block) => { + if (typeof block === "string") return block; + if (block && typeof block === "object") { + const b = block as { type?: string; text?: unknown }; + if (b.type === "text" && typeof b.text === "string") return b.text; + } + return ""; + }) + .join("\n"); + } + return ""; +} + +export function userMessagePrompt(event: SessionEvent, maxChars: number): string | null { + if (event.type !== "user/message") return null; + if (event.data?.source?.kind && event.data.source.kind !== "user") return null; + const text = eventTextContent(event.data?.content); + if (!text.trim()) return null; + return text.slice(0, maxChars); +} + +export function toolCallObservation(event: SessionEvent, maxChars: number): Record | null { + if (event.type !== "tool/call") return null; + const data = event.data ?? {}; + const name = typeof data.name === "string" ? data.name : ""; + if (!name || isAgentmemoryTool(name)) return null; + let input: string; + try { + input = (typeof data.arguments === "string" ? data.arguments : JSON.stringify(data.arguments ?? {})).slice(0, maxChars); + } catch { + input = String(data.arguments ?? "").slice(0, maxChars); + } + return { tool_name: name, call_id: typeof data.callId === "string" ? data.callId : null, tool_input: input }; +} + +export function compactionSummary(event: SessionEvent, maxChars: number): string | null { + if (event.type !== "compaction/summary") return null; + const data = event.data ?? {}; + const summary = + eventTextContent(data.summary) || + eventTextContent(data.text) || + eventTextContent(data.content); + if (!summary) return null; + return summary.slice(0, maxChars); +} + +// ─────────────────────────────── plugin ─────────────────────────────── + +export const name = "agentmemory"; + +export function apply(ctx: PluginContext, rawConfig: Partial = {}): void { + const cfg: AgentmemoryConfig = { ...DEFAULTS, ...rawConfig }; + const debug = process.env["AGENTMEMORY_DSH_DEBUG"] === "1"; + const rest = makeRestClient(cfg.url, cfg.secret, debug); + const logger = ctx.logger; + + // sessionId -> context returned by /session/start, for first-step injection. + const startContextCache = new Map(); + // sessionId -> set of sessions that already had their first-step injection. + const injectedSessions = new Set(); + // sessionId -> { cwd, project } captured at session/created; avoids re-spawning + // git per event and keeps approval observations on the right session. + const sessionInfos = new Map(); + // cwd -> projectName memo: git rev-parse is a blocking child process and must + // not run on every session/event (project identity is stable per cwd). + const projectNameCache = new Map(); + // In-flight REST calls still settling at teardown (e.g. /session/end on + // shutdown); kept referenced so nothing is dropped or unhandled. + const pendingCalls = new Set>(); + + function sessionCwd(session: SessionLike): string { + return session.header?.cwd || process.cwd(); + } + + function cachedProjectName(cwd: string): string { + let project = projectNameCache.get(cwd); + if (project === undefined) { + project = resolveProjectName(cwd); + projectNameCache.set(cwd, project); + } + return project; + } + + function trackSession(session: SessionLike): { cwd: string; project: string } | undefined { + if (!session || typeof session.id !== "string") return undefined; + const cwd = sessionCwd(session); + const info = { cwd, project: cachedProjectName(cwd) }; + sessionInfos.set(session.id, info); + return info; + } + + function fireObserve( + sid: string, + info: { cwd: string; project: string }, + hookType: string, + data: Record, + ): void { + const call = rest + .post("/observe", { + hookType, + sessionId: sid, + project: info.project, + cwd: info.cwd, + timestamp: new Date().toISOString(), + data, + }, OBSERVE_TIMEOUT_MS) + .catch(() => {}); + pendingCalls.add(call); + void call.then(() => pendingCalls.delete(call)); + } + + // ── session/created → register with the daemon (await: response feeds injection) ── + ctx.on("session/created", (session: SessionLike) => { + if (!session || typeof session.id !== "string") return; + const sid = session.id; + const info = trackSession(session); + if (!info) return; + const call = rest + .post<{ context?: unknown }>("/session/start", { + sessionId: sid, + project: info.project, + cwd: info.cwd, + agentId: cfg.agentId, + }, SESSION_START_TIMEOUT_MS) + .then((result) => { + const context = result?.context; + if (typeof context === "string" && context.length > 0) { + startContextCache.set(sid, context); + } + }) + .catch(() => {}); + pendingCalls.add(call); + void call.then(() => pendingCalls.delete(call)); + }); + + // ── session/event stream → telemetry observations (fire-and-forget) ── + ctx.on("session/event", (session: SessionLike, event: SessionEvent) => { + if (!session || !event || typeof event.type !== "string") return; + const sid = session.id; + if (!sid) return; + + let info = sessionInfos.get(sid); + if (!info) { + info = trackSession(session); + if (!info) return; + } + + const prompt = userMessagePrompt(event, PROMPT_MAX_CHARS); + if (prompt !== null) { + fireObserve(sid, info, "prompt_submit", { userPrompt: prompt }); + return; + } + + const tool = toolCallObservation(event, TOOL_INPUT_MAX_CHARS); + if (tool !== null && cfg.observeToolCalls) { + fireObserve(sid, info, "post_tool_use", tool); + return; + } + + if (event.type === "approval/asked") { + const data = event.data ?? {}; + fireObserve(sid, info, "notification", { + notification_type: "permission_prompt", + tool_name: typeof data.toolName === "string" ? data.toolName.slice(0, 2000) : "", + call_id: typeof data.callId === "string" ? data.callId.slice(0, 2000) : null, + reason: typeof data.reason === "string" ? data.reason.slice(0, 2000) : "", + }); + return; + } + + if (cfg.compactionBridge) { + const summary = compactionSummary(event, COMPACTION_MAX_CHARS); + if (summary !== null) { + const call = rest + .post("/remember", { + content: `[dsh compaction] ${summary}`, + type: "fact", + concepts: ["compaction"], + project: info.project, + }, REMEMBER_TIMEOUT_MS) + .catch(() => {}); + pendingCalls.add(call); + void call.then(() => pendingCalls.delete(call)); + } + } + }); + + // ── agent/pre-step (step 1) → inject instructions + recalled context ── + ctx.on("agent/pre-step", async ({ agent, messages, step, signal }: PreStepPayload, next: PreStepNext) => { + const decision = await next(); + const session = agent?.session; + if (!session || typeof session.id !== "string") return decision; + const sid = session.id; + if (step !== 1 || injectedSessions.has(sid)) return decision; + if (decision.kind !== "enter" || !Array.isArray(decision.messages) || decision.messages.length === 0) { + return decision; + } + if (signal.aborted) return decision; + + const info = sessionInfos.get(sid) ?? trackSession(session); + const project = info?.project ?? cachedProjectName(sessionCwd(session)); + const parts: string[] = []; + if (cfg.injectInstructions) parts.push(INSTRUCTIONS); + if (cfg.injectContext) { + let context = startContextCache.get(sid); + if (!context) { + const result = await rest.post<{ context?: unknown }>("/context", { sessionId: sid, project }, CONTEXT_TIMEOUT_MS); + context = typeof result?.context === "string" ? result.context : ""; + } else { + startContextCache.delete(sid); + } + if (context) parts.push(context); + } + if (parts.length === 0) return decision; + + const text = parts.join("\n\n").slice(0, cfg.injectMaxChars); + const message = { + id: randomUUID(), + role: "user", + content: [{ type: "text", text }], + source: { kind: "agentmemory", form: "memory-context" }, + }; + injectedSessions.add(sid); + // ES2022-compatible equivalents of findLastIndex/toSpliced (Node 18 safe). + const lastClaimedIndex = + decision.messages.length - 1 - [...decision.messages].reverse().findIndex((m) => messages.includes(m)); + const nextMessages = decision.messages.slice(); + nextMessages.splice(lastClaimedIndex + 1, 0, message); + return { + ...decision, + messages: nextMessages, + }; + }); + + // ── approval/asked → permission observation (fire-and-forget) ── + // Allowlisted fields only: the raw request object may carry sensitive + // tool arguments or file paths; never forward it wholesale. + const APPROVAL_FIELDS = ["permission", "pattern", "title", "tool_call_id", "metadata"] as const; + ctx.on("approval/asked", (req: unknown) => { + const data = (req ?? {}) as Record; + const sid = typeof data.sessionId === "string" ? data.sessionId : undefined; + if (!sid) return; + const info = sessionInfos.get(sid); + if (!info) return; // unknown session: no cwd/project to attribute — skip + const payload: Record = { notification_type: "permission_prompt" }; + for (const key of APPROVAL_FIELDS) { + const value = data[key]; + if (value === undefined) continue; + // Truncate everything, not just strings: approval metadata can carry + // tool arguments or file paths and must not leave the process whole. + let text: string; + if (typeof value === "string") { + text = value; + } else { + try { + // JSON.stringify can return undefined (functions, symbols, toJSON + // returning undefined); fall back to String() before slicing. + text = JSON.stringify(value) ?? String(value); + } catch { + text = String(value); + } + } + payload[key] = text.slice(0, 2000); + } + fireObserve(sid, info, "notification", payload); + }); + + // ── session/disposed → summarize (tracked, longer timeout) ── + ctx.on("session/disposed", (session: SessionLike) => { + if (!session || typeof session.id !== "string") return; + const sid = session.id; + if (cfg.summarizeOnDispose) { + const call = rest + .post("/session/end", { sessionId: sid }, SESSION_END_TIMEOUT_MS) + .catch(() => {}); + pendingCalls.add(call); + void call.then(() => pendingCalls.delete(call)); + } + startContextCache.delete(sid); + injectedSessions.delete(sid); + sessionInfos.delete(sid); + }); + + // Cordis can remove this plugin's listeners before disposing live sessions. + ctx.effect(() => async () => { + await Promise.allSettled([...pendingCalls]); + if (cfg.summarizeOnDispose) { + await Promise.allSettled([...sessionInfos.keys()].map(sessionId => + rest.post("/session/end", { sessionId }, SESSION_END_TIMEOUT_MS), + )); + } + startContextCache.clear(); + injectedSessions.clear(); + sessionInfos.clear(); + projectNameCache.clear(); + }, "agentmemory.dsh.memory"); + + if (debug) { + logger.info( + `[agentmemory] dsh plugin active: url=${cfg.url} agentId=${cfg.agentId} inject=${cfg.injectContext} observe=${cfg.observeToolCalls} compactionBridge=${cfg.compactionBridge}`, + ); + } +} diff --git a/plugin/dsh/test/plugin.test.ts b/plugin/dsh/test/plugin.test.ts new file mode 100644 index 0000000000..0e9a54d474 --- /dev/null +++ b/plugin/dsh/test/plugin.test.ts @@ -0,0 +1,365 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; +import { + apply, + makeRestClient, + resolveProjectName, + isAgentmemoryTool, + userMessagePrompt, + toolCallObservation, + compactionSummary, + type PluginContext, + type SessionEvent, +} from "../src/index"; + +// ─────────────────────────── helpers ─────────────────────────── + +function fakeFetch(impl: (url: string, init?: RequestInit) => Promise) { + vi.stubGlobal("fetch", impl); +} + +function jsonResponse(body: unknown, ok = true): Response { + return new Response(JSON.stringify(body), { status: ok ? 200 : 500, headers: { "Content-Type": "application/json" } }); +} + +function makeCtx() { + const listeners = new Map(); + const logs: string[] = []; + const disposers: Array<() => unknown> = []; + const ctx: PluginContext = { + on(event, listener) { + const arr = listeners.get(event) ?? []; + arr.push(listener); + listeners.set(event, arr); + }, + effect(callback) { + const dispose = callback(); + if (dispose) disposers.push(dispose); + }, + logger: { + info: (...a) => logs.push("info " + a.join(" ")), + warn: (...a) => logs.push("warn " + a.join(" ")), + error: (...a) => logs.push("error " + a.join(" ")), + }, + }; + return { ctx, listeners, logs, dispose: async () => { + for (const dispose of disposers) await dispose(); + } }; +} + +async function fire(listeners: Map, event: string, ...args: unknown[]) { + for (const fn of listeners.get(event) ?? []) { + await (fn as (...a: unknown[]) => unknown)(...args); + } +} + +function session(id: string, cwd = "/tmp/proj"): any { + return { id, header: { cwd } }; +} + +function event(type: string, data: unknown): SessionEvent { + return { type, data } as SessionEvent; +} + +// ─────────────────────────── tests ─────────────────────────── + +describe("makeRestClient", () => { + beforeEach(() => vi.restoreAllMocks()); + afterEach(() => vi.unstubAllGlobals()); + + it("posts JSON with auth header when secret set", async () => { + const calls: Array<{ url: string; init: RequestInit }> = []; + fakeFetch(async (url, init) => { + calls.push({ url, init: init ?? {} }); + return jsonResponse({ ok: true }); + }); + const rest = makeRestClient("http://localhost:3111", "sekrit"); + const out = await rest.post<{ ok: boolean }>("/session/start", { sessionId: "s1" }); + expect(out).toEqual({ ok: true }); + expect(calls).toHaveLength(1); + expect(calls[0].url).toBe("http://localhost:3111/agentmemory/session/start"); + const headers = calls[0].init.headers as Record; + expect(headers["Authorization"]).toBe("Bearer sekrit"); + expect(JSON.parse(String(calls[0].init.body))).toEqual({ sessionId: "s1" }); + }); + + it("returns null on non-ok response", async () => { + fakeFetch(async () => jsonResponse({ error: "x" }, false)); + const rest = makeRestClient("http://x", ""); + expect(await rest.post("/x", {})).toBeNull(); + }); + + it("returns null on network failure without throwing", async () => { + fakeFetch(async () => { throw new Error("boom"); }); + const rest = makeRestClient("http://x", ""); + expect(await rest.post("/x", {})).toBeNull(); + expect(() => rest.fire("/x", {})).not.toThrow(); + }); + + it("fire swallows async rejection", async () => { + fakeFetch(async () => { throw new Error("boom"); }); + const rest = makeRestClient("http://x", ""); + rest.fire("/observe", {}); + await new Promise((r) => setTimeout(r, 20)); + expect(true).toBe(true); + }); +}); + +describe("resolveProjectName", () => { + it("uses explicit env override", () => { + expect(resolveProjectName("/tmp/a", { AGENTMEMORY_PROJECT_NAME: "override" })).toBe("override"); + }); + + it("falls back to cwd basename without git", () => { + expect(resolveProjectName("/tmp/some-dir", {})).toBe("some-dir"); + }); +}); + +describe("isAgentmemoryTool", () => { + it("recognizes dsh-namespaced and opencode-named tools", () => { + expect(isAgentmemoryTool("mcp__agentmemory__memory_recall")).toBe(true); + expect(isAgentmemoryTool("agentmemory_memory_save")).toBe(true); + expect(isAgentmemoryTool("read")).toBe(false); + }); +}); + +describe("event mapping", () => { + it("userMessagePrompt extracts string content", () => { + expect(userMessagePrompt(event("user/message", { content: "hello world" }), 100)).toBe("hello world"); + }); + + it("userMessagePrompt extracts text blocks", () => { + const e = event("user/message", { content: [{ type: "text", text: "a" }, { type: "text", text: "b" }] }); + expect(userMessagePrompt(e, 100)).toBe("a\nb"); + }); + + it("userMessagePrompt returns null for empty", () => { + expect(userMessagePrompt(event("user/message", { content: " " }), 100)).toBeNull(); + expect(userMessagePrompt(event("tool/call", {}), 100)).toBeNull(); + }); + + it("does not recapture injected context as a human prompt", () => { + for (const kind of ["agentmemory", "runtime-context", "compaction"]) { + expect(userMessagePrompt(event("user/message", { + content: [{ type: "text", text: "Private recalled context" }], source: { kind }, + }), 100)).toBeNull(); + } + expect(userMessagePrompt(event("user/message", { + content: "Human request", source: { kind: "user" }, + }), 100)).toBe("Human request"); + }); + + it("toolCallObservation extracts name and arguments and truncates", () => { + const e = event("tool/call", { callId: "c1", name: "read", arguments: { path: "/a/b.txt" } }); + const obs = toolCallObservation(e, 200); + expect(obs).not.toBeNull(); + expect(obs!.tool_name).toBe("read"); + expect(obs!.call_id).toBe("c1"); + expect(JSON.parse(obs!.tool_input as string)).toEqual({ path: "/a/b.txt" }); + }); + + it("toolCallObservation filters agentmemory tools", () => { + const e = event("tool/call", { callId: "c2", name: "mcp__agentmemory__memory_recall", arguments: {} }); + expect(toolCallObservation(e, 200)).toBeNull(); + }); + + it("keeps real Harness JSON tool arguments without double encoding", () => { + const args = '{"path":"/fixture/cobalt.txt"}'; + expect(toolCallObservation(event("tool/call", { + name: "read", callId: "read-1", arguments: args, + }), 200)?.tool_input).toBe(args); + }); + + it("compactionSummary extracts summary text", () => { + expect(compactionSummary(event("compaction/summary", { summary: "did stuff" }), 100)).toBe("did stuff"); + expect(compactionSummary(event("user/message", {}), 100)).toBeNull(); + }); + + it("extracts the real Harness compaction content blocks", () => { + expect(compactionSummary(event("compaction/summary", { + summary: [{ type: "text", text: "Keep cobalt settings." }], + }), 100)).toBe("Keep cobalt settings."); + }); +}); + +describe("plugin apply()", () => { + beforeEach(() => vi.restoreAllMocks()); + afterEach(() => vi.unstubAllGlobals()); + + it("registers session on session/created with project+cwd+agentId", async () => { + const calls: Array<{ url: string; init: RequestInit }> = []; + fakeFetch(async (url, init) => { + calls.push({ url, init: init ?? {} }); + return jsonResponse({ context: "ctx" }); + }); + const { ctx, listeners } = makeCtx(); + apply(ctx, { url: "http://localhost:3111", secret: "", agentId: "dsh-test" }); + + await fire(listeners, "session/created", session("ses_1", "/tmp/proj")); + await new Promise((r) => setTimeout(r, 10)); + + expect(calls).toHaveLength(1); + const body = JSON.parse(String(calls[0].init.body)) as Record; + expect(body.sessionId).toBe("ses_1"); + expect(body.project).toBe("proj"); + expect(body.cwd).toBe("/tmp/proj"); + expect(body.agentId).toBe("dsh-test"); + }); + + it("injects instructions+context into first step batch", async () => { + const { ctx, listeners } = makeCtx(); + apply(ctx, { url: "http://localhost:3111" }); + const preStep = listeners.get("agent/pre-step"); + expect(preStep).toBeDefined(); + + const claimed = [{ id: "m1", role: "user", content: [{ type: "text", text: "hi" }] }]; + let nextCalled = 0; + const next = async () => { + nextCalled++; + return { kind: "enter", messages: [...claimed] }; + }; + const payload = { agent: { session: session("ses_2", "/tmp/proj") }, messages: claimed, step: 1, signal: new AbortController().signal }; + + const decision = await (preStep![0] as any)(payload, next); + expect(nextCalled).toBe(1); + expect(decision.messages).toHaveLength(2); + expect(decision.messages[1].role).toBe("user"); + expect(decision.messages[1].content[0].type).toBe("text"); + expect(String(decision.messages[1].content[0].text)).toContain("agentmemory"); + expect(String(decision.messages[1].content[0].text)).toContain("memory_recall"); + }); + + it("does not inject on step > 1 or already-injected session", async () => { + const { ctx, listeners } = makeCtx(); + apply(ctx, { url: "http://localhost:3111" }); + const preStep = listeners.get("agent/pre-step")![0] as any; + const claimed = [{ id: "m1" }]; + const next = async () => ({ kind: "enter", messages: [...claimed] }); + + const d1 = await preStep({ agent: { session: session("s", "/tmp/p") }, messages: claimed, step: 2, signal: new AbortController().signal }, next); + expect(d1.messages).toHaveLength(1); + + const d2 = await preStep({ agent: { session: session("s", "/tmp/p") }, messages: claimed, step: 1, signal: new AbortController().signal }, next); + expect(d2.messages).toHaveLength(2); + const d3 = await preStep({ agent: { session: session("s", "/tmp/p") }, messages: claimed, step: 1, signal: new AbortController().signal }, next); + expect(d3.messages).toHaveLength(1); + }); + + it("observes prompt_submit and post_tool_use via session/event", async () => { + const calls: Array<{ url: string; init: RequestInit }> = []; + fakeFetch(async (url, init) => { + calls.push({ url, init: init ?? {} }); + return jsonResponse({}); + }); + const { ctx, listeners } = makeCtx(); + apply(ctx, { url: "http://localhost:3111" }); + const ses = session("ses_3", "/tmp/proj"); + + await fire(listeners, "session/event", ses, event("user/message", { content: "do the thing" })); + await fire(listeners, "session/event", ses, event("tool/call", { callId: "c9", name: "edit", arguments: { filePath: "/tmp/proj/a.ts" } })); + await new Promise((r) => setTimeout(r, 10)); + + const observes = calls.filter((c) => c.url.endsWith("/observe")).map((c) => JSON.parse(String(c.init.body))); + expect(observes).toHaveLength(2); + expect(observes[0].hookType).toBe("prompt_submit"); + expect(observes[0].data.userPrompt).toBe("do the thing"); + expect(observes[1].hookType).toBe("post_tool_use"); + expect(observes[1].data.tool_name).toBe("edit"); + }); + + it("compaction bridge remembers summaries", async () => { + const calls: Array<{ url: string; init: RequestInit }> = []; + fakeFetch(async (url, init) => { + calls.push({ url, init: init ?? {} }); + return jsonResponse({}); + }); + const { ctx, listeners } = makeCtx(); + apply(ctx, { url: "http://localhost:3111" }); + + await fire(listeners, "session/event", session("ses_4", "/tmp/proj"), event("compaction/summary", { summary: "refactored auth module" })); + await new Promise((r) => setTimeout(r, 10)); + + const remembers = calls.filter((c) => c.url.endsWith("/remember")); + expect(remembers).toHaveLength(1); + const body = JSON.parse(String(remembers[0].init.body)) as Record; + expect(String(body.content)).toContain("refactored auth module"); + }); + + it("observes real Harness approval events from the session stream", async () => { + const bodies: any[] = []; + fakeFetch(async (_url, init) => { + bodies.push(JSON.parse(String(init?.body))); + return jsonResponse({}); + }); + const { ctx, listeners } = makeCtx(); + apply(ctx); + await fire(listeners, "session/event", session("approval-session"), event("approval/asked", { + id: "approval-1", toolName: "bash", callId: "call-1", reason: "Confirm operation", + })); + expect(bodies).toEqual([expect.objectContaining({ + sessionId: "approval-session", hookType: "notification", + data: expect.objectContaining({ tool_name: "bash", call_id: "call-1" }), + })]); + }); + + it("calls session/end on dispose", async () => { + const calls: Array<{ url: string; init: RequestInit }> = []; + fakeFetch(async (url, init) => { + calls.push({ url, init: init ?? {} }); + return jsonResponse({}); + }); + const { ctx, listeners } = makeCtx(); + apply(ctx, { url: "http://localhost:3111" }); + + await fire(listeners, "session/disposed", session("ses_5")); + await new Promise((r) => setTimeout(r, 10)); + + const ends = calls.filter((c) => c.url.endsWith("/session/end")); + expect(ends).toHaveLength(1); + expect(JSON.parse(String(ends[0].init.body))).toEqual({ sessionId: "ses_5" }); + }); + + it("ends live sessions and waits for requests before host teardown returns", async () => { + let releaseEnd!: () => void; + const ended = new Promise(resolve => { releaseEnd = resolve; }); + const paths: string[] = []; + fakeFetch(async (url) => { + paths.push(url); + if (url.endsWith("/session/end")) await ended; + return jsonResponse({}); + }); + const { ctx, listeners, dispose } = makeCtx(); + apply(ctx); + await fire(listeners, "session/created", session("shutdown-session")); + let disposed = false; + const pending = dispose().then(() => { disposed = true; }); + await new Promise(resolve => setTimeout(resolve, 10)); + expect(paths.some(path => path.endsWith("/session/end"))).toBe(true); + expect(disposed).toBe(false); + releaseEnd(); + await pending; + expect(disposed).toBe(true); + }); + + it("never throws when daemon is unreachable", async () => { + fakeFetch(async () => { throw new Error("ECONNREFUSED"); }); + const { ctx, listeners } = makeCtx(); + apply(ctx, { url: "http://localhost:1" }); + + await expect( + fire(listeners, "session/created", session("s6", "/tmp/p")), + ).resolves.toBeUndefined(); + await expect( + fire(listeners, "session/event", session("s6", "/tmp/p"), event("user/message", { content: "x" })), + ).resolves.toBeUndefined(); + await expect( + fire(listeners, "session/disposed", session("s6")), + ).resolves.toBeUndefined(); + + const preStep = listeners.get("agent/pre-step")![0] as any; + const claimed = [{ id: "m" }]; + const next = async () => ({ kind: "enter", messages: [...claimed] }); + await expect( + preStep({ agent: { session: session("s6", "/tmp/p") }, messages: claimed, step: 1, signal: new AbortController().signal }, next), + ).resolves.toBeTruthy(); + }); +}); diff --git a/plugin/dsh/tsconfig.json b/plugin/dsh/tsconfig.json new file mode 100644 index 0000000000..8bbdc994c4 --- /dev/null +++ b/plugin/dsh/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ES2022", + "types": ["node"], + "module": "ESNext", + "moduleResolution": "bundler", + "strict": true, + "skipLibCheck": true, + "esModuleInterop": true, + "isolatedModules": true, + "resolveJsonModule": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noEmit": true + }, + "include": [ + "src/**/*", + "test/**/*", + "tsdown.config.ts" + ] +} diff --git a/plugin/dsh/tsdown.config.ts b/plugin/dsh/tsdown.config.ts new file mode 100644 index 0000000000..a29518d452 --- /dev/null +++ b/plugin/dsh/tsdown.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from "tsdown"; + +export default defineConfig({ + entry: ["src/index.ts"], + outDir: "lib", + format: ["esm"], + fixedExtension: false, + target: "node20", + clean: true, + sourcemap: false, + dts: true, +}); diff --git a/scripts/docs-sync.state.json b/scripts/docs-sync.state.json index 2726e4afc4..33118b9d39 100644 --- a/scripts/docs-sync.state.json +++ b/scripts/docs-sync.state.json @@ -26,7 +26,7 @@ "324" ], "sourceFiles": [ - "242" + "243" ], "loc": [ "57000" diff --git a/src/cli/connect/guidelines.ts b/src/cli/connect/guidelines.ts index 26770b6a7d..3860719400 100644 --- a/src/cli/connect/guidelines.ts +++ b/src/cli/connect/guidelines.ts @@ -112,6 +112,19 @@ export function guidelineTargets( scope: "global", source: "https://docs.factory.ai/cli/configuration/agents-md", }, + // DeepSeek Harness loads $DSH_HOME/AGENTS.md into every session's first + // step via @deepseek-ai/dsh-agent-instructions (same mechanism as the + // project-level AGENTS.md chain). DSH_HOME override keeps this aligned + // with the dsh adapter, which resolves its profile paths through DSH_HOME. + dsh: { + globalPath: process.env.DSH_HOME + ? join(process.env.DSH_HOME, "AGENTS.md") + : join(home, ".dsh", "AGENTS.md"), + projectPath: "AGENTS.md", + format: "block", + scope: "global", + source: "https://github.com/deepseek-ai/deepseek-harness", + }, // Antigravity does NOT read AGENTS.md; global rules live in ~/.gemini/GEMINI.md. antigravity: { globalPath: join(home, ".gemini", "GEMINI.md"), diff --git a/test/cli-connect-dsh.test.ts b/test/cli-connect-dsh.test.ts new file mode 100644 index 0000000000..69ebf649e3 --- /dev/null +++ b/test/cli-connect-dsh.test.ts @@ -0,0 +1,42 @@ +import { describe, it, expect } from "vitest"; +import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { writeGuideline, guidelineTargets } from "../src/cli/connect/guidelines.js"; + +describe("writeGuideline for dsh", () => { + it("writes the memory-usage block into ~/.dsh/AGENTS.md", () => { + const home = mkdtempSync(join(tmpdir(), "am-dsh-guide-")); + const prev = process.env.DSH_HOME; + delete process.env.DSH_HOME; // the host may set it (e.g. running under dsh) + try { + expect(Object.keys(guidelineTargets(home))).toContain("dsh"); + const result = writeGuideline("dsh", { cwd: "/tmp", home }); + expect(result.kind).toBe("written"); + expect(result.path).toBe(join(home, ".dsh", "AGENTS.md")); + expect(existsSync(result.path)).toBe(true); + expect(readFileSync(result.path, "utf8")).toContain("agentmemory:start"); + } finally { + if (prev === undefined) delete process.env.DSH_HOME; + else process.env.DSH_HOME = prev; + rmSync(home, { recursive: true, force: true }); + } + }); + + it("honors DSH_HOME when resolving the global guideline path", () => { + const home = mkdtempSync(join(tmpdir(), "am-dsh-guide2-")); + const prev = process.env.DSH_HOME; + process.env.DSH_HOME = join(home, "custom-dsh"); + try { + const result = writeGuideline("dsh", { cwd: "/tmp", home }); + expect(result.kind).toBe("written"); + expect(result.path).toBe(join(home, "custom-dsh", "AGENTS.md")); + expect(existsSync(result.path)).toBe(true); + } finally { + if (prev === undefined) delete process.env.DSH_HOME; + else process.env.DSH_HOME = prev; + rmSync(home, { recursive: true, force: true }); + } + }); +}); diff --git a/test/connect-guidelines.test.ts b/test/connect-guidelines.test.ts index 633aedc5e8..694f9d31eb 100644 --- a/test/connect-guidelines.test.ts +++ b/test/connect-guidelines.test.ts @@ -139,6 +139,7 @@ describe("guidelineTargets coverage", () => { "copilot-cli", "cursor", "droid", + "dsh", "gemini-cli", "kiro", "opencode",